Skip to content

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

[Metabot] Slackbot (#68473)

Sloan Sparger682614038085
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index c67771b5a22..df5c6b0fea3 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -287,6 +287,7 @@
channel
{:team "Gadget"
:api #{metabase.channel.api
+ metabase.channel.api.slack
metabase.channel.core
metabase.channel.email
metabase.channel.email.messages
@@ -2043,7 +2044,8 @@
enterprise/api
{:team "UX West"
- :api #{metabase-enterprise.api.core}
+ :api #{metabase-enterprise.api.core
+ metabase-enterprise.api.routes.common}
:uses #{api
premium-features
util}}
@@ -2307,18 +2309,15 @@
:api #{metabase-enterprise.metabot-v3.api
metabase-enterprise.metabot-v3.core
metabase-enterprise.metabot-v3.init
- metabase-enterprise.metabot-v3.tools.api
- metabase-enterprise.metabot-v3.tools.deftool
- metabase-enterprise.metabot-v3.tools.entity-details
- metabase-enterprise.metabot-v3.tools.field-stats
- metabase-enterprise.metabot-v3.tools.filters
- metabase-enterprise.metabot-v3.tools.search
- metabase-enterprise.metabot-v3.util}
+ metabase-enterprise.metabot-v3.tools.api}
+ :friends #{enterprise/agent-api
+ enterprise/slackbot}
:uses #{activity-feed
analytics
api
app-db
audit-app
+ channel
collections
config
documents
@@ -2328,6 +2327,7 @@
lib-be
models
native-query-snippets
+ notification
parameters
permissions
premium-features
@@ -2346,8 +2346,10 @@
transforms-base
util
warehouses
+ enterprise/api
enterprise/dependencies
enterprise/llm
+ enterprise/slackbot
enterprise/transforms-python}}
enterprise/permission-debug
@@ -2488,6 +2490,27 @@
setup
util}}
+ enterprise/slackbot
+ {:team "Metabot"
+ :api #{metabase-enterprise.slackbot.init}
+ :friends #{enterprise/metabot-v3}
+ :uses #{analytics
+ api
+ channel
+ config
+ formatter
+ lib
+ permissions
+ premium-features
+ query-processor
+ request
+ settings
+ system
+ upload
+ util
+ enterprise/metabot-v3
+ enterprise/sso}}
+
enterprise/snippet-collections
{:team "Querying"
:api #{}
diff --git a/e2e/support/helpers/e2e-sharing-helpers.ts b/e2e/support/helpers/e2e-sharing-helpers.ts
index 314ad904ff2..f45a11f82e6 100644
--- a/e2e/support/helpers/e2e-sharing-helpers.ts
+++ b/e2e/support/helpers/e2e-sharing-helpers.ts
@@ -12,6 +12,7 @@ export const openSharingMenu = (menuItemText?: string) => {
export const removeNotificationHandlerChannel = (channel: string) => {
modal()
+ .findByTestId("alert-configured-channel")
.findByText(channel)
.closest('[data-testid="channel-block"]')
.findByTestId("remove-channel-button")
diff --git a/e2e/test/scenarios/admin-2/settings.cy.spec.js b/e2e/test/scenarios/admin-2/settings.cy.spec.js
index 68b99f1365e..d18e07c63b3 100644
--- a/e2e/test/scenarios/admin-2/settings.cy.spec.js
+++ b/e2e/test/scenarios/admin-2/settings.cy.spec.js
@@ -269,17 +269,13 @@ describe("scenarios > admin > settings", () => {
describe(" > slack settings", () => {
it("should present the form and display errors", () => {
- cy.visit("/admin/settings/notifications");
- cy.findByTestId("admin-layout-content")
- .findByText("Connect to Slack")
- .click();
+ cy.visit("/admin/settings/slack");
- H.modal().findByText("Metabase on Slack");
+ cy.findByRole("main").findByText("Create a Slack app and connect to it.");
cy.findByLabelText(/Slack Bot User OAuth Token/i).type("xoxb");
- cy.button("Save changes").click();
-
- H.modal().findByText(/invalid token/i);
+ cy.button("Connect").click();
+ cy.findByRole("main").findByText(/invalid token/i);
});
});
});
@@ -1092,7 +1088,7 @@ describe("notifications", { tags: "@external" }, () => {
AUTH_METHODS.forEach((auth) => {
it(`${auth.display} Auth`, () => {
- cy.visit("/admin/settings/notifications");
+ cy.visit("/admin/settings/webhooks");
cy.findByRole("heading", { name: "Add a webhook" }).click();
H.modal().within(() => {
@@ -1121,7 +1117,7 @@ describe("notifications", { tags: "@external" }, () => {
});
it("Should allow you to create and edit Notifications", () => {
- cy.visit("/admin/settings/notifications");
+ cy.visit("/admin/settings/webhooks");
cy.findByRole("heading", { name: "Add a webhook" }).click();
diff --git a/e2e/test/scenarios/sharing/alert/alert-permissions.cy.spec.js b/e2e/test/scenarios/sharing/alert/alert-permissions.cy.spec.js
index c15a126978c..6d54db6e4f3 100644
--- a/e2e/test/scenarios/sharing/alert/alert-permissions.cy.spec.js
+++ b/e2e/test/scenarios/sharing/alert/alert-permissions.cy.spec.js
@@ -155,7 +155,8 @@ function createBasicAlert({ includeNormal } = {}) {
H.popover().findByText("Create an alert").click();
if (includeNormal) {
- cy.findByText("Email")
+ cy.findByTestId("alert-configured-channel")
+ .findByText("Email")
.closest('[data-testid="channel-block"]')
.findByTestId("token-field")
.click();
diff --git a/e2e/test/scenarios/sharing/alert/alert.cy.spec.js b/e2e/test/scenarios/sharing/alert/alert.cy.spec.js
index 8241983239d..f34edf43096 100644
--- a/e2e/test/scenarios/sharing/alert/alert.cy.spec.js
+++ b/e2e/test/scenarios/sharing/alert/alert.cy.spec.js
@@ -31,11 +31,11 @@ describe("scenarios > alert", () => {
cy.findByText("Set up Slack")
.should("be.visible")
.closest("a")
- .should("have.attr", "href", "/admin/settings/notifications");
+ .should("have.attr", "href", "/admin/settings/slack");
cy.findByText("Add a webhook")
.should("be.visible")
.closest("a")
- .should("have.attr", "href", "/admin/settings/notifications");
+ .should("have.attr", "href", "/admin/settings/webhooks");
});
});
diff --git a/e2e/test/scenarios/sharing/alert/email-alert.cy.spec.js b/e2e/test/scenarios/sharing/alert/email-alert.cy.spec.js
index 0fdbcf80bed..389a1b7a649 100644
--- a/e2e/test/scenarios/sharing/alert/email-alert.cy.spec.js
+++ b/e2e/test/scenarios/sharing/alert/email-alert.cy.spec.js
@@ -33,7 +33,7 @@ describe("scenarios > alert > email_alert", { tags: "@external" }, () => {
cy.log(
"Should not display slack channel if it is not configured metabase#48407",
);
- cy.findByTestId("alert-create").within(() => {
+ cy.findByTestId("alert-configured-channel").within(() => {
cy.findByTestId("loading-indicator").should("not.exist");
cy.findByText("Slack").should("not.exist");
});
diff --git a/e2e/test/scenarios/sharing/subscriptions.cy.spec.js b/e2e/test/scenarios/sharing/subscriptions.cy.spec.js
index 834d0ccb8f1..3553de01fb4 100644
--- a/e2e/test/scenarios/sharing/subscriptions.cy.spec.js
+++ b/e2e/test/scenarios/sharing/subscriptions.cy.spec.js
@@ -68,7 +68,7 @@ describe("scenarios > dashboard > subscriptions", () => {
cy.findByRole("link", { name: /configure Slack/i }).should(
"have.attr",
"href",
- "/admin/settings/notifications",
+ "/admin/settings/slack",
);
});
});
diff --git a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
index ef03a3d773f..68a03210f0c 100644
--- a/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
+++ b/enterprise/backend/src/metabase_enterprise/api_routes/routes.clj
@@ -130,7 +130,7 @@
"/library" (premium-handler metabase-enterprise.library.api/routes :library)
"/logs" (premium-handler 'metabase-enterprise.advanced-config.api.logs :audit-app)
"/metabot-tools" metabase-enterprise.metabot-v3.tools.api/routes
- "/metabot-v3" (premium-handler metabase-enterprise.metabot-v3.api/routes :metabot-v3)
+ "/metabot-v3" metabase-enterprise.metabot-v3.api/routes
"/permission_debug" (premium-handler metabase-enterprise.permission-debug.api/routes :advanced-permissions)
"/transforms-python" (premium-handler metabase-enterprise.transforms-python.api/routes :transforms-python)
"/scim" (premium-handler metabase-enterprise.scim.routes/routes :scim)
diff --git a/enterprise/backend/src/metabase_enterprise/core/init.clj b/enterprise/backend/src/metabase_enterprise/core/init.clj
index b1c6cae391b..ba0022ba268 100644
--- a/enterprise/backend/src/metabase_enterprise/core/init.clj
+++ b/enterprise/backend/src/metabase_enterprise/core/init.clj
@@ -18,6 +18,7 @@
[metabase-enterprise.remote-sync.init]
[metabase-enterprise.scim.init]
[metabase-enterprise.semantic-search.init]
+ [metabase-enterprise.slackbot.init]
[metabase-enterprise.sso.init]
[metabase-enterprise.stale.init]
[metabase-enterprise.support-access-grants.init]
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/core.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/core.clj
index 7bc4d803a9d..64445bf7b16 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/core.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/core.clj
@@ -155,7 +155,7 @@
(mr/def ::profile-id
"Profile identifier keyword."
- [:enum :embedding_next :internal :transforms_codegen :sql :nlq :document-generate-content])
+ [:enum :embedding_next :internal :transforms_codegen :sql :nlq :document-generate-content :slackbot])
(mr/def ::tracking-opts
"Options for snowplow and prometheus analytics tracking."
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/markdown_link_buffer.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/markdown_link_buffer.clj
index 7424075787e..650fdf7fae8 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/markdown_link_buffer.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/markdown_link_buffer.clj
@@ -8,6 +8,7 @@
(:require
[clojure.string :as str]
[metabase-enterprise.metabot-v3.agent.links :as links]
+ [metabase.system.core :as system]
[metabase.util.log :as log]))
(set! *warn-on-reflection* true)
@@ -25,10 +26,33 @@
[state queries charts]
(assoc state :queries queries :charts charts))
+;;; Slack Link Resolution
+
+(def ^:private slack-link-pattern
+ "Regex matching a complete Slack-format link <metabase://type/id|text>."
+ #"<(metabase://[^>|]+)(?:\|([^>]*))?>")
+
+(defn- resolve-slack-link
+ "Resolve a single Slack-format metabase:// link match. Returns the replacement string."
+ [queries charts [_ url link-text]]
+ (if-let [resolved (links/resolve-metabase-uri url queries charts)]
+ (let [absolute-url (str (system/site-url) resolved)]
+ (if link-text
+ (str "<" absolute-url "|" link-text ">")
+ (str "<" absolute-url ">")))
+ (do
+ (log/warn "Failed to resolve Slack link URL" {:url url})
+ (or link-text url))))
+
+(defn- resolve-slack-links
+ "Resolve all Slack-format metabase:// links in text."
+ [text queries charts]
+ (str/replace text slack-link-pattern (partial resolve-slack-link queries charts)))
+
;;; Buffering Logic
-(defn- find-potential-link-start
- "Find the index of a potential incomplete link start (unmatched '[').
+(defn- find-potential-markdown-link-start
+ "Find the index of a potential incomplete markdown link start (unmatched '[').
Returns nil if no potential incomplete link exists."
[text]
(let [last-open (str/last-index-of text "[")]
@@ -42,13 +66,38 @@
(re-find #"\[[^\]]*\]\([^)]*$" suffix)) ; unclosed (
last-open))))))
+(defn- find-potential-slack-link-start
+ "Find the index of a potential incomplete Slack-format metabase:// link.
+ Only buffers on `<metabase://` prefix — regular `<` characters must NOT trigger buffering.
+ Returns nil if no potential incomplete link exists."
+ [text]
+ (let [idx (str/last-index-of text "<metabase://")]
+ (when idx
+ (let [suffix (subs text idx)]
+ ;; Only buffer if there's no closing > (i.e., the link is incomplete)
+ (when-not (re-find slack-link-pattern suffix)
+ idx)))))
+
+(defn- find-potential-link-start
+ "Find the index of the earliest potential incomplete link start.
+ Checks both markdown [text](url) and Slack <metabase://...|text> formats.
+ Returns nil if no potential incomplete link exists."
+ [text]
+ (let [md-idx (find-potential-markdown-link-start text)
+ slack-idx (find-potential-slack-link-start text)]
+ (cond
+ (and md-idx slack-idx) (min md-idx slack-idx)
+ md-idx md-idx
+ slack-idx slack-idx)))
+
(defn step
"Process a chunk of text through the state machine.
Returns [new-state output-string]."
[{:keys [buffer] :as state} chunk]
(let [text (str buffer chunk)
- ;; First resolve any complete links
- resolved (links/resolve-links text (:queries state) (:charts state))
+ ;; Resolve complete markdown links, then Slack-format links
+ resolved (-> (links/resolve-links text (:queries state) (:charts state))
+ (resolve-slack-links (:queries state) (:charts state)))
;; Then check for incomplete link at the end
split-point (find-potential-link-start resolved)]
(if split-point
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/profiles.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/profiles.clj
index 66cd96f9209..8d555701a76 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/profiles.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/profiles.clj
@@ -139,6 +139,19 @@
#'agent-tools/document-construct-model-chart-tool
#'agent-tools/document-construct-sql-chart-tool]})
+(register-profile!
+ {:name :slackbot
+ :prompt-template "slackbot.selmer"
+ :max-iterations 10
+ :temperature 0.3
+ :tools [#'agent-tools/search-tool
+ #'agent-tools/slackbot-construct-notebook-query-tool
+ #'agent-tools/list-available-fields-tool
+ #'agent-tools/get-field-values-tool
+ #'agent-tools/static-viz-tool
+ #'agent-tools/create-alert-tool
+ #'agent-tools/slackbot-create-dashboard-subscription-tool]})
+
(def ^:private api-string->capability-keyword
"Map from API capability strings (as sent by the frontend) to the keywords
used in tool :capabilities metadata. Keywords pass through unchanged."
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/streaming.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/streaming.clj
index dc264d2ad91..fb2f35ca1f1 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/streaming.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/streaming.clj
@@ -18,6 +18,8 @@
(def todo-list-type "AI-SDK data type for todo lists." "todo_list")
(def code-edit-type "AI-SDK data type for code edits." "code_edit")
(def transform-suggestion-type "AI-SDK data type for transform suggestions." "transform_suggestion")
+(def adhoc-viz-type "AI-SDK data type for ad-hoc visualizations." "adhoc_viz")
+(def static-viz-type "AI-SDK data type for static visualizations." "static_viz")
;;; Query URL Encoding
@@ -91,6 +93,31 @@
:version 1
:data suggestion})
+(defn adhoc-viz-part
+ "Create an ADHOC_VIZ data part for streaming.
+ Value should be a map with :query (dataset query), :link (question URL),
+ and optionally :title and :display.
+
+ This matches Python AI Service's:
+ ai_sdk.create_data_part(data_type=AISDKDataTypes.ADHOC_VIZ, version=1, value=adhoc_viz_value)"
+ [value]
+ {:type :data
+ :data-type adhoc-viz-type
+ :version 1
+ :data value})
+
+(defn static-viz-part
+ "Create a STATIC_VIZ data part for streaming.
+ Value should be a map with :entity_id (int) for the saved question or metric to render.
+
+ This matches Python AI Service's:
+ ai_sdk.create_data_part(data_type=AISDKDataTypes.STATIC_VIZ, version=1, value={\"entity_id\": entity_id})"
+ [value]
+ {:type :data
+ :data-type static-viz-type
+ :version 1
+ :data value})
+
;;; Reaction Conversion
(defn reactions->data-parts
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools.clj
index c18311664be..6f1984dc1f0 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools.clj
@@ -7,14 +7,18 @@
[metabase-enterprise.metabot-v3.agent.tools.charts :as tools.charts]
[metabase-enterprise.metabot-v3.agent.tools.clarification :as tools.clarification]
[metabase-enterprise.metabot-v3.agent.tools.construct :as tools.construct]
+ [metabase-enterprise.metabot-v3.agent.tools.create-alert :as tools.create-alert]
+ [metabase-enterprise.metabot-v3.agent.tools.create-dashboard-subscription :as tools.create-dashboard-subscription]
[metabase-enterprise.metabot-v3.agent.tools.document :as tools.document]
[metabase-enterprise.metabot-v3.agent.tools.metadata :as tools.metadata]
[metabase-enterprise.metabot-v3.agent.tools.navigation :as tools.navigation]
[metabase-enterprise.metabot-v3.agent.tools.resources :as tools.resources]
[metabase-enterprise.metabot-v3.agent.tools.search :as tools.search]
[metabase-enterprise.metabot-v3.agent.tools.shared :as shared]
+ [metabase-enterprise.metabot-v3.agent.tools.slackbot-query :as tools.slackbot-query]
[metabase-enterprise.metabot-v3.agent.tools.snippets :as tools.snippets]
[metabase-enterprise.metabot-v3.agent.tools.sql :as tools.sql]
+ [metabase-enterprise.metabot-v3.agent.tools.static-viz :as tools.static-viz]
[metabase-enterprise.metabot-v3.agent.tools.subscriptions :as tools.subscriptions]
[metabase-enterprise.metabot-v3.agent.tools.todo :as tools.todo]
[metabase-enterprise.metabot-v3.agent.tools.transforms :as tools.transforms]
@@ -69,7 +73,15 @@
[tools.autogen-dashboard
create-autogenerated-dashboard-tool]
[tools.subscriptions
- create-dashboard-subscription-tool])
+ create-dashboard-subscription-tool]
+ [tools.slackbot-query
+ slackbot-construct-notebook-query-tool]
+ [tools.static-viz
+ static-viz-tool]
+ [tools.create-alert
+ create-alert-tool]
+ [tools.create-dashboard-subscription
+ slackbot-create-dashboard-subscription-tool])
(def ^:dynamic ^:private *memory-atom* nil)
@@ -79,7 +91,8 @@
"create_chart" "edit_chart" "todo_write" "todo_read" "navigate_user"
"write_transform_sql" "write_transform_python" "create_autogenerated_dashboard"
"create_sql_query" "edit_sql_query" "replace_sql_query"
- "document_schema_collect" "document_construct_sql_chart" "document_construct_model_chart"})
+ "document_schema_collect" "document_construct_sql_chart" "document_construct_model_chart"
+ "create_alert" "create_dashboard_subscription" "static_viz"})
(defn wrap-tools-with-state
"Wrap state-dependent tools with access to the memory atom.
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/construct.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/construct.clj
index dbf6d1c4fd6..60dee2b1778 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/construct.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/construct.clj
@@ -177,7 +177,9 @@
[:limit [:maybe :int]]
[:visualization {:optional true} construct-visualization-schema]])
-(def ^:private construct-query-schema
+(def construct-query-schema
+ "Schema for the query parameter of construct_notebook_query.
+ Shared with the slackbot query tool variant."
[:or construct-query-metric-schema construct-query-aggregate-schema construct-query-raw-schema])
(def ^:private construct-operation-aliases
@@ -281,6 +283,38 @@
[args]
(mc/decode construct-notebook-query-args-schema args tool-arg-transformer))
+(defn execute-query
+ "Execute a notebook query based on normalized query parameters.
+ Returns the raw query result from filter-tools.
+ Shared between construct-notebook-query-tool and slackbot-construct-notebook-query-tool."
+ [query]
+ (let [normalized-query (normalize-ai-args query)
+ query-type (query-type->keyword (:query-type normalized-query))]
+ (log/debug "execute-query" {:query-type query-type})
+ (case query-type
+ :metric
+ (filter-tools/query-metric
+ {:metric-id (get-in normalized-query [:source :metric-id])
+ :filters (normalize-construct-filters (:filters normalized-query))
+ :group-by (normalize-ai-args (:group-by normalized-query))})
+ :aggregate
+ (filter-tools/query-datasource
+ {:model-id (get-in normalized-query [:source :model-id])
+ :table-id (get-in normalized-query [:source :table-id])
+ :aggregations (normalize-ai-args (:aggregations normalized-query))
+ :filters (normalize-construct-filters (:filters normalized-query))
+ :group-by (normalize-ai-args (:group-by normalized-query))
+ :limit (:limit normalized-query)})
+ :raw
+ (filter-tools/query-datasource
+ {:model-id (get-in normalized-query [:source :model-id])
+ :table-id (get-in normalized-query [:source :table-id])
+ :fields (normalize-ai-args (:fields normalized-query))
+ :filters (normalize-construct-filters (:filters normalized-query))
+ :order-by (normalize-ai-args (:order-by normalized-query))
+ :limit (:limit normalized-query)})
+ {:output (str "Unsupported query_type: " query-type)})))
+
(mu/defn ^{:tool-name "construct_notebook_query"
:decode decode-tool-args}
construct-notebook-query-tool
@@ -289,37 +323,10 @@
(try
(let [;; LLM sometimes nests visualization inside query — pull it out
effective-viz (or visualization (:visualization query))
- normalized-query (normalize-ai-args (dissoc query :visualization))
normalized-visualization (normalize-ai-args effective-viz)
- query-type (query-type->keyword (:query-type normalized-query))
chart-type (or (chart-type->keyword (:chart-type normalized-visualization))
:table)
- _ (log/debug "construct_notebook_query request"
- {:query-type query-type
- :chart-type chart-type})
- query-result (case query-type
- :metric
- (filter-tools/query-metric
- {:metric-id (get-in normalized-query [:source :metric-id])
- :filters (normalize-construct-filters (:filters normalized-query))
- :group-by (normalize-ai-args (:group-by normalized-query))})
- :aggregate
- (filter-tools/query-datasource
- {:model-id (get-in normalized-query [:source :model-id])
- :table-id (get-in normalized-query [:source :table-id])
- :aggregations (normalize-ai-args (:aggregations normalized-query))
- :filters (normalize-construct-filters (:filters normalized-query))
- :group-by (normalize-ai-args (:group-by normalized-query))
- :limit (:limit normalized-query)})
- :raw
- (filter-tools/query-datasource
- {:model-id (get-in normalized-query [:source :model-id])
- :table-id (get-in normalized-query [:source :table-id])
- :fields (normalize-ai-args (:fields normalized-query))
- :filters (normalize-construct-filters (:filters normalized-query))
- :order-by (normalize-ai-args (:order-by normalized-query))
- :limit (:limit normalized-query)})
- {:output (str "Unsupported query_type: " query-type)})
+ query-result (execute-query (dissoc query :visualization))
structured (or (:structured-output query-result) (:structured_output query-result))]
(if (and structured (:query-id structured) (:query structured))
(let [chart-result (create-chart-tools/create-chart
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/create_alert.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/create_alert.clj
new file mode 100644
index 00000000000..e7f67e5710d
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/create_alert.clj
@@ -0,0 +1,87 @@
+(ns metabase-enterprise.metabot-v3.agent.tools.create-alert
+ "Agent tool wrapper for creating alerts on saved questions.
+ Gets slack_channel_id from agent context and calls the create-alert tool endpoint directly."
+ (:require
+ [metabase-enterprise.metabot-v3.agent.tools.shared :as shared]
+ [metabase-enterprise.metabot-v3.tools.create-alert :as tools.create-alert]
+ [metabase.util.log :as log]
+ [metabase.util.malli :as mu]))
+
+(set! *warn-on-reflection* true)
+
+(def schedule-schema
+ "Schedule schema shared with create-dashboard-subscription tool."
+ [:or
+ [:map {:closed true}
+ [:frequency [:= "hourly"]]]
+ [:map {:closed true}
+ [:frequency [:= "daily"]]
+ [:hour [:int {:min 0 :max 23}]]]
+ [:map {:closed true}
+ [:frequency [:= "weekly"]]
+ [:day_of_week [:enum "sunday" "monday" "tuesday" "wednesday" "thursday" "friday" "saturday"]]
+ [:hour [:int {:min 0 :max 23}]]]
+ [:map {:closed true}
+ [:frequency [:= "monthly"]]
+ [:day_of_month [:enum "first-calendar-day"
+ "first-sunday" "first-monday" "first-tuesday" "first-wednesday"
+ "first-thursday" "first-friday" "first-saturday"
+ "middle-of-month"
+ "last-calendar-day"
+ "last-sunday" "last-monday" "last-tuesday" "last-wednesday"
+ "last-thursday" "last-friday" "last-saturday"]]
+ [:hour [:int {:min 0 :max 23}]]]])
+
+(def ^:private create-alert-system-instructions
+ "## Alerts
+
+You can create alerts that notify the user's current Slack channel based on a saved question's results on a
+recurring schedule.
+
+### Required information
+
+Before calling the tool, ensure you have ALL of the following:
+1. **Card ID** — the ID of a saved question, obtained from a prior search result or conversation context
+2. **Send condition** — determines when the alert fires:
+ - `has_result` — sends when the question returns any rows
+ - `goal_above` — sends when the result exceeds the goal line set on the question
+ - `goal_below` — sends when the result drops below the goal line
+3. **Schedule** — frequency (hourly, daily, weekly, monthly) with the appropriate time fields
+4. **Send once** (optional, defaults to false) — if true, the alert is automatically deleted after it fires once
+
+### Important notes
+
+* Alerts are for **saved questions** (cards), not dashboards. For dashboard delivery, use the dashboard subscription tool.
+* `goal_above` and `goal_below` only work on questions that have a goal line configured.
+* If the user doesn't specify a send condition, default to `has_result`.
+
+CRITICAL: When a user asks to be alerted or notified about a saved question's results, you MUST call the create_alert tool.
+NEVER tell the user you have created an alert without actually calling the create_alert tool. If you cannot call the tool
+(e.g. missing required information), explain what is needed instead of pretending the alert was created.")
+
+(mu/defn ^{:tool-name "create_alert"
+ :system-instructions create-alert-system-instructions}
+ create-alert-tool
+ "Create an alert based on a saved question's results on a recurring schedule."
+ [{:keys [card_id send_condition schedule send_once]} :- [:map {:closed true}
+ [:card_id :int]
+ [:send_condition [:enum "has_result" "goal_above" "goal_below"]]
+ [:schedule schedule-schema]
+ [:send_once {:optional true :default false} :boolean]]]
+ (let [slack-channel-id (:slack_channel_id (shared/current-context))]
+ (when-not slack-channel-id
+ (throw (ex-info "This tool can only be used from a Slack channel"
+ {:agent-error? true})))
+ (try
+ (let [result (tools.create-alert/create-alert
+ {:card-id card_id
+ :send-condition (keyword send_condition)
+ :schedule schedule
+ :send-once (boolean send_once)
+ :slack-channel slack-channel-id})]
+ (if (:error result)
+ {:output (:error result)}
+ {:output (or (:output result) "Alert created successfully.")}))
+ (catch Exception e
+ (log/error e "Failed to create alert")
+ {:output (str "Failed to create alert: " (or (ex-message e) "Unknown error"))}))))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/create_dashboard_subscription.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/create_dashboard_subscription.clj
new file mode 100644
index 00000000000..e2e0019e273
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/create_dashboard_subscription.clj
@@ -0,0 +1,55 @@
+(ns metabase-enterprise.metabot-v3.agent.tools.create-dashboard-subscription
+ "Agent tool wrapper for creating dashboard subscriptions.
+ Gets slack_channel_id from agent context and calls the create-dashboard-subscription tool endpoint directly."
+ (:require
+ [metabase-enterprise.metabot-v3.agent.tools.create-alert :as tools.create-alert]
+ [metabase-enterprise.metabot-v3.agent.tools.shared :as shared]
+ [metabase-enterprise.metabot-v3.tools.create-dashboard-subscription :as tools.create-dashboard-subscription]
+ [metabase.util.log :as log]
+ [metabase.util.malli :as mu]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private create-dashboard-subscription-system-instructions
+ "## Dashboard Subscriptions
+
+You can create dashboard subscriptions that deliver dashboard contents to the user's current slack channel on a
+recurring schedule.
+
+### CRITICAL: You MUST call the create_dashboard_subscription tool
+
+When a user asks to subscribe to a dashboard, set up scheduled delivery, or receive regular updates for a dashboard,
+you MUST call the create_dashboard_subscription tool. Never tell the user you have created a subscription without
+actually calling the tool. If you cannot call the tool (e.g. missing required information), explain what is needed
+instead of pretending the subscription was created.
+
+### Required information
+
+Before calling the tool, ensure you have ALL of the following:
+1. **Dashboard ID** — obtained from a prior search result or conversation context
+2. **Schedule** — frequency (hourly, daily, weekly, monthly) with the appropriate time fields
+
+If any required information is missing, ask the user for it rather than assuming or fabricating values.")
+
+(mu/defn ^{:tool-name "create_dashboard_subscription"
+ :system-instructions create-dashboard-subscription-system-instructions}
+ slackbot-create-dashboard-subscription-tool
+ "Create a recurring subscription that delivers a dashboard's contents to a Slack channel."
+ [{:keys [dashboard_id schedule]} :- [:map {:closed true}
+ [:dashboard_id :int]
+ [:schedule tools.create-alert/schedule-schema]]]
+ (let [slack-channel-id (:slack_channel_id (shared/current-context))]
+ (when-not slack-channel-id
+ (throw (ex-info "This tool can only be used from a Slack channel"
+ {:agent-error? true})))
+ (try
+ (let [result (tools.create-dashboard-subscription/create-dashboard-subscription
+ {:dashboard-id dashboard_id
+ :schedule schedule
+ :slack-channel slack-channel-id})]
+ (if (:error result)
+ {:output (:error result)}
+ {:output (or (:output result) "Dashboard subscription created successfully.")}))
+ (catch Exception e
+ (log/error e "Failed to create dashboard subscription")
+ {:output (str "Failed to create dashboard subscription: " (or (ex-message e) "Unknown error"))}))))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/slackbot_query.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/slackbot_query.clj
new file mode 100644
index 00000000000..30069e06625
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/slackbot_query.clj
@@ -0,0 +1,45 @@
+(ns metabase-enterprise.metabot-v3.agent.tools.slackbot-query
+ "Slackbot-specific notebook query tool.
+ Like construct-notebook-query-tool but emits adhoc_viz data parts
+ instead of creating charts. Does not save or navigate."
+ (:require
+ [metabase-enterprise.metabot-v3.agent.streaming :as streaming]
+ [metabase-enterprise.metabot-v3.agent.tools.construct :as construct]
+ [metabase.util.log :as log]
+ [metabase.util.malli :as mu]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private slackbot-query-schema
+ [:map {:closed true}
+ [:reasoning :string]
+ [:query construct/construct-query-schema]
+ [:title {:optional true} [:maybe :string]]
+ [:display {:optional true
+ :description "Visualization type for displaying the query results in Slack. Required in practice whenever the user asks for a chart or graph, and it must match any requested chart type. Valid values: 'table', 'bar', 'line', 'pie', 'area', 'row', 'scatter', 'funnel'. Use requested chart types like 'line', 'bar', 'area', 'pie', 'scatter', 'funnel', 'row', or 'table' when they fit the query. Omitting this field falls back to Metabase's default table display, so do not omit it for chart or graph requests. Only omit it when you intentionally want a plain table and the user did not request a chart type."}
+ [:maybe [:enum "table" "bar" "line" "pie" "area" "row" "scatter" "funnel"]]]])
+
+(mu/defn ^{:tool-name "construct_notebook_query"} slackbot-construct-notebook-query-tool
+ "Construct a notebook query from a metric, model, or table. The query results will be rendered as a visualization in Slack."
+ [{:keys [_reasoning query title display]} :- slackbot-query-schema]
+ (try
+ (let [query-result (construct/execute-query query)
+ structured (or (:structured-output query-result) (:structured_output query-result))]
+ (if (and structured (:query-id structured) (:query structured))
+ (let [metabase-link (streaming/query->question-url (:query structured))
+ adhoc-viz-value (cond-> {:query (:query structured)
+ :link metabase-link}
+ title (assoc :title title)
+ display (assoc :display display))]
+ {:structured-output structured
+ :instructions (str "Query created. The visualization will be posted as a separate "
+ "follow-up message in the thread with the query results. "
+ "Use future tense when referring to results — they haven't "
+ "appeared yet when the user sees your text.")
+ :data-parts [(streaming/adhoc-viz-part adhoc-viz-value)]})
+ query-result))
+ (catch Exception e
+ (log/error e "Failed to construct slackbot notebook query")
+ (if (:agent-error? (ex-data e))
+ {:output (ex-message e)}
+ {:output (str "Failed to construct notebook query: " (or (ex-message e) "Unknown error"))}))))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/static_viz.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/static_viz.clj
new file mode 100644
index 00000000000..b7bcf792e7d
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/static_viz.clj
@@ -0,0 +1,19 @@
+(ns metabase-enterprise.metabot-v3.agent.tools.static-viz
+ "Static visualization tool for the slackbot profile.
+ Renders existing saved questions/metrics as PNG images in Slack."
+ (:require
+ [metabase-enterprise.metabot-v3.agent.streaming :as streaming]
+ [metabase.util.malli :as mu]))
+
+(set! *warn-on-reflection* true)
+
+(mu/defn ^{:tool-name "static_viz"} static-viz-tool
+ "Generate a static visualization (PNG image) of a saved question or metric. The visualization will be posted as a separate follow-up message in the thread."
+ [{:keys [entity_id]} :- [:map {:closed true}
+ [:entity_id :int]]]
+ {:instructions (str "Visualization queued for entity " entity_id ". "
+ "The visualization will be posted as a separate follow-up message "
+ "with the question or metric's name as its title and a link to open "
+ "it in Metabase. Use future tense when referring to the visualization "
+ "in your response — it hasn't appeared yet when the user sees your text.")
+ :data-parts [(streaming/static-viz-part {:entity_id entity_id})]})
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/subscriptions.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/subscriptions.clj
index 72337273326..cd616976b75 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/subscriptions.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/agent/tools/subscriptions.clj
@@ -9,18 +9,19 @@
(mu/defn ^{:tool-name "create_dashboard_subscription"}
create-dashboard-subscription-tool
- "Create a dashboard subscription to send regular email updates.
+ "Create a dashboard subscription to send regular updates via email or Slack.
Use when a user wants to receive or send regular updates on a dashboard's contents.
- Requires a valid dashboard ID, email address, and schedule.
+ Requires a valid dashboard ID, either an email address or a Slack channel name, and a schedule.
Do NOT infer email addresses from usernames or other information.
If the email address is incomplete or missing a part like the TLD,
ask the user for clarification before proceeding."
- [{:keys [dashboard_id email schedule]}
+ [{:keys [dashboard_id email slack_channel schedule]}
:- [:map {:closed true}
[:dashboard_id :int]
- [:email :string]
+ [:email {:optional true} [:maybe :string]]
+ [:slack_channel {:optional true} [:maybe :string]]
[:schedule [:map
[:frequency [:enum "hourly" "daily" "weekly" "monthly"]]
[:hour {:optional true} [:maybe :int]]
@@ -28,15 +29,16 @@
[:day_of_month {:optional true} [:maybe :string]]]]]]
(try
(subscription-tools/create-dashboard-subscription
- {:dashboard-id dashboard_id
- :email email
- :schedule (-> schedule
- (update :frequency keyword)
- (cond->
- (:day_of_week schedule) (-> (assoc :day-of-week (keyword (:day_of_week schedule)))
- (dissoc :day_of_week))
- (:day_of_month schedule) (-> (assoc :day-of-month (keyword (:day_of_month schedule)))
- (dissoc :day_of_month))))})
+ {:dashboard-id dashboard_id
+ :email email
+ :slack-channel slack_channel
+ :schedule (-> schedule
+ (update :frequency keyword)
+ (cond->
+ (:day_of_week schedule) (-> (assoc :day-of-week (keyword (:day_of_week schedule)))
+ (dissoc :day_of_week))
+ (:day_of_month schedule) (-> (assoc :day-of-month (keyword (:day_of_month schedule)))
+ (dissoc :day_of_month))))})
(catch Exception e
(log/error e "Error creating dashboard subscription")
(if (:agent-error? (ex-data e))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/api.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/api.clj
index 3c7b1578fb3..1a44474b1a3 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/api.clj
@@ -1,9 +1,8 @@
(ns metabase-enterprise.metabot-v3.api
"`/api/ee/metabot-v3/` routes"
(:require
- [clj-http.client :as http]
[clojure.core.async :as a]
- [clojure.string :as str]
+ [metabase-enterprise.api.routes.common :as ee.api.routes]
[metabase-enterprise.metabot-v3.agent.core :as agent]
[metabase-enterprise.metabot-v3.api.document]
[metabase-enterprise.metabot-v3.api.metabot]
@@ -12,20 +11,20 @@
[metabase-enterprise.metabot-v3.config :as metabot-v3.config]
[metabase-enterprise.metabot-v3.context :as metabot-v3.context]
[metabase-enterprise.metabot-v3.envelope :as metabot-v3.envelope]
+ [metabase-enterprise.metabot-v3.feedback :as metabot-v3.feedback]
[metabase-enterprise.metabot-v3.self.core :as self.core]
[metabase-enterprise.metabot-v3.settings :as metabot-v3.settings]
[metabase-enterprise.metabot-v3.util :as metabot-v3.u]
+ [metabase-enterprise.slackbot.api]
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.api.routes.common :refer [+auth]]
[metabase.api.util.handlers :as handlers]
[metabase.app-db.core :as app-db]
[metabase.config.core :as config]
- [metabase.premium-features.core :as premium-features]
[metabase.server.streaming-response :as sr]
- [metabase.store-api.core :as store-api]
[metabase.util :as u]
- [metabase.util.json :as json]
+ [metabase.util.i18n :refer [deferred-tru]]
[metabase.util.log :as log]
[metabase.util.malli.schema :as ms]
[toucan2.core :as t2])
@@ -61,6 +60,7 @@
(filter map?)
(map #(+ (:prompt %) (:completion %)))
(apply +))})))
+
(defn- check-metabot-enabled!
"Checks that the Metabot instance identified by `metabot-id` is enabled. Throws a 403 if it's not."
[metabot-id]
@@ -264,23 +264,26 @@
[_route-params
_query-params
feedback :- :map]
- (let [token (premium-features/premium-embedding-token)
- base-url (store-api/store-api-url)]
- (api/check-400 (not (or (str/blank? token) (str/blank? base-url)))
- "Cannot build a request. The license token and/or Store api url are missing!")
- (try
- (http/post (str base-url "/api/v2/metabot/feedback/" token)
- {:content-type :json
- :body (json/encode feedback)})
- api/generic-204-no-content
- (catch Exception e
- (log/error e "Failed to submit feedback to Harbormaster")
- (throw e)))))
+ (try
+ (api/check-400 (metabot-v3.feedback/submit-to-harbormaster! feedback)
+ "Cannot submit feedback. The license token and/or Store API URL are missing!")
+ api/generic-204-no-content
+ (catch Exception e
+ (log/error e "Failed to submit feedback to Harbormaster")
+ (throw e))))
(def ^{:arglists '([request respond raise])} routes
"`/api/ee/metabot-v3` routes."
(handlers/routes
- (api.macros/ns-handler *ns* +auth)
(handlers/route-map-handler
- {"/metabot" metabase-enterprise.metabot-v3.api.metabot/routes
- "/document" metabase-enterprise.metabot-v3.api.document/routes})))
+ {"/metabot" (ee.api.routes/+require-premium-feature
+ :metabot-v3 (deferred-tru "MetaBot")
+ metabase-enterprise.metabot-v3.api.metabot/routes)
+ "/document" (ee.api.routes/+require-premium-feature
+ :metabot-v3 (deferred-tru "MetaBot")
+ metabase-enterprise.metabot-v3.api.document/routes)
+ ;; premium check happens in the route so we still ack events to prevent slack retrying
+ "/slack" metabase-enterprise.slackbot.api/routes})
+ (ee.api.routes/+require-premium-feature
+ :metabot-v3 (deferred-tru "MetaBot")
+ (api.macros/ns-handler *ns* +auth))))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/client.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/client.clj
index af1c77a4dce..836feafea29 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/client.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/client.clj
@@ -125,6 +125,38 @@
(close []
(.close ^Closeable (:http-client response)))))
+(defn- open-ai-stream!
+ "Make a streaming request to the AI service. Returns the HTTP response.
+ Caller is responsible for reading from the response body and closing it."
+ [{:keys [context message history profile-id conversation-id session-id state debug?]}]
+ (premium-features/assert-has-feature :metabot-v3 "MetaBot")
+ (let [url (ai-url "/v2/agent/stream")
+ body (cond-> {:messages (conj (vec history) message)
+ :context context
+ :conversation_id conversation-id
+ :profile_id profile-id
+ :user_id api/*current-user-id*
+ :state state}
+ debug? (assoc :debug true))
+ _ (metabot-v3.context/log body :llm.log/be->llm)
+ _ (log/debugf "V2 request to AI Proxy:\n%s" (u/pprint-to-str body))
+ options (cond-> {:headers {"Accept" "text/event-stream"
+ "Content-Type" "application/json;charset=UTF-8"
+ "x-metabase-instance-token" (premium-features/premium-embedding-token)
+ "x-metabase-session-token" session-id
+ "x-metabase-url" (system/site-url)
+ "Connection" "close"}
+ :body (->json-bytes body)
+ :throw-exceptions false
+ :as :stream
+ :decompress-body false}
+ *debug* (assoc :debug true))
+ response (post! url options)]
+ (log/debugf "Response from AI Proxy:\n%s" (u/pprint-to-str (select-keys response #{:body :status :headers})))
+ (when-not (#{200 202} (:status response))
+ (check-response! response body))
+ response))
+
(mu/defn streaming-request :- :any
"Make a streaming V2 request to the AI Service
@@ -141,7 +173,7 @@
Response chunks are encoded in the format understood by the frontend and AI Service, Clojure backend doesn't
know anything about it and just shuttles them over.
"
- [{:keys [context message history profile-id conversation-id session-id state debug? on-complete]}
+ [{:keys [on-complete] :as opts}
:- [:map
[:context :map]
[:message ::metabot-v3.client.schema/message]
@@ -152,47 +184,12 @@
[:state :map]
[:debug? {:optional true} [:maybe :boolean]]
[:on-complete {:optional true} [:function [:=> [:cat :any] :any]]]]]
- (premium-features/assert-has-feature :metabot-v3 "MetaBot")
(try
- (let [url (ai-url "/v2/agent/stream")
- body (cond-> {:messages (conj (vec history) message)
- :context context
- :conversation_id conversation-id
- :profile_id profile-id
- :user_id api/*current-user-id*
- :state state}
- debug? (assoc :debug true))
- _ (metabot-v3.context/log body :llm.log/be->llm)
- _ (log/debugf "V2 request to AI Proxy:\n%s" (u/pprint-to-str body))
- options (cond-> {:headers {"Accept" "text/event-stream"
- "Content-Type" "application/json;charset=UTF-8"
- "x-metabase-instance-token" (premium-features/premium-embedding-token)
- "x-metabase-session-token" session-id
- "x-metabase-url" (system/site-url)
- ;; close conn so it's not reused so that when we use
- ;; `quick-closing-body` there are no weird problems
- "Connection" "close"}
- :body (->json-bytes body)
- :throw-exceptions false
- :as :stream
- ;; Don't compress streaming responses - adds latency and breaks
- ;; cancellation when streams are incomplete
- :decompress-body false}
- *debug* (assoc :debug true))
- response (post! url options)
- lines (when on-complete
- (atom []))
- ;; NOTE: this atom is unused right now, but we potentially might put its value in database (see
- ;; `on-complete`) to indicate which requests were canceled in flight
+ (let [response (open-ai-stream! opts)
+ lines (when on-complete (atom []))
canceled (atom nil)]
- (metabot-v3.context/log (:body response) :llm.log/llm->be)
- (log/debugf "Response from AI Proxy:\n%s" (u/pprint-to-str (select-keys response #{:body :status :headers})))
- (when-not (#{200 202} (:status response))
- (check-response! response body))
(sr/streaming-response {:content-type "text/event-stream; charset=utf-8"} [os canceled-chan]
- ;; see `quick-closing-body` docs and see `Connection` header supporting this behavior
(with-open [^BufferedReader response-reader (io/reader (quick-closing-body response))]
- ;; Response from the AI Service will send response parts separated by newline
(loop [^String line (.readLine response-reader)]
(cond
(nil? line) nil
@@ -204,22 +201,50 @@
(swap! lines conj line))
(try
(doto os
- ;; `line-seq` strips newlines, so we need to append it back.
(.write (.getBytes line "UTF-8"))
(.write (.getBytes "\n"))
- ;; Immediately flush so it feels fluid on the frontend
(.flush))
(catch EofException _
(reset! canceled true)
(log/debug "Request cancelled, through exception")))
(when-not @canceled
- ;; `recur` cannot be inside of `try`, so we have to signal stop somehow
(recur (.readLine response-reader)))))))
(when on-complete
(on-complete @lines))))
(catch Throwable e
(throw (ex-info (format "Error in request to AI Proxy: %s" (ex-message e)) {} e)))))
+(mu/defn streaming-request-with-callback :- [:sequential :string]
+ "Make a streaming V2 request to the AI Service, invoking a callback for each line.
+ Unlike `streaming-request`, this doesn't return a StreamingResponse - it processes
+ the stream internally and calls `on-line` for each line as it arrives.
+ Returns the collected lines when complete."
+ [{:keys [on-line on-complete] :as opts}
+ :- [:map
+ [:context :map]
+ [:message ::metabot-v3.client.schema/message]
+ [:history ::metabot-v3.client.schema/messages]
+ [:profile-id :string]
+ [:conversation-id :string]
+ [:session-id :string]
+ [:state :map]
+ [:on-line {:optional true} [:function [:=> [:cat :string] :any]]]
+ [:on-complete {:optional true} [:function [:=> [:cat :any] :any]]]]]
+ (let [response (open-ai-stream! opts)
+ lines (atom [])]
+ (try
+ (with-open [^BufferedReader response-reader (io/reader (quick-closing-body response))]
+ (loop [^String line (.readLine response-reader)]
+ (when line
+ (swap! lines conj line)
+ (when on-line (on-line line))
+ (recur (.readLine response-reader)))))
+ (when on-complete
+ (on-complete @lines))
+ (catch java.io.IOException e
+ (log/debugf e "Stream closed while reading AI response (%d lines collected)" (count @lines))))
+ @lines))
+
(mu/defn select-metric-request
"Make a request to AI Service to select a metric."
[metrics :- [:sequential ::metabot-v3.client.schema/metric]
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/config.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/config.clj
index 75b358b8f99..6979e1512fc 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/config.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/config.clj
@@ -12,12 +12,18 @@
"The ID of the embedded Metabot instance."
"c61bf5f5-1025-47b6-9298-bf1827105bb6")
+(def slackbot-metabot-id
+ "The ID of the Slack Metabot instance."
+ "9a89fe64-54b9-4ab2-8022-eccd772e5073")
+
(def metabot-config
"The name of the collection exposed by the answer-sources tool."
{internal-metabot-id {:profile-id "internal"
:entity-id "metabotmetabotmetabot"}
embedded-metabot-id {:profile-id "embedding_next"
- :entity-id "embeddedmetabotmetabo"}})
+ :entity-id "embeddedmetabotmetabo"}
+ slackbot-metabot-id {:profile-id "slackbot"
+ :entity-id "slackbotmetabotmetabo"}})
(defn metabot-id->profile-id
"Return the profile-id for the Metabot instance with ID `metabot-id` or \"default\" if no profile-id is configured."
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/feedback.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/feedback.clj
new file mode 100644
index 00000000000..e3aa33a3035
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/feedback.clj
@@ -0,0 +1,19 @@
+(ns metabase-enterprise.metabot-v3.feedback
+ "Shared feedback submission to Harbormaster via the Store API."
+ (:require
+ [clj-http.client :as http]
+ [clojure.string :as str]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.store-api.core :as store-api]
+ [metabase.util.json :as json]))
+
+(defn submit-to-harbormaster!
+ "Submit metabot feedback to Harbormaster via the Store API.
+ Returns the HTTP response on success, or nil if the token or Store API URL is missing."
+ [feedback]
+ (let [token (premium-features/premium-embedding-token)
+ base-url (store-api/store-api-url)]
+ (when-not (or (str/blank? token) (str/blank? base-url))
+ (http/post (str base-url "/api/v2/metabot/feedback/" token)
+ {:content-type :json
+ :body (json/encode feedback)}))))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/persistence.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/persistence.clj
new file mode 100644
index 00000000000..3dc483f3233
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/persistence.clj
@@ -0,0 +1,44 @@
+(ns metabase-enterprise.metabot-v3.persistence
+ "Persistence for Metabot conversations and messages."
+ (:require
+ [metabase.api.common :as api]
+ [metabase.app-db.core :as app-db]
+ [metabase.util :as u]
+ [toucan2.core :as t2]))
+
+(defn store-message!
+ "Persist messages to MetabotConversation and MetabotMessage tables."
+ [conversation-id profile-id messages & {:keys [slack-msg-id channel-id user-id]}]
+ (let [finish (let [m (u/last messages)]
+ (when (= (:_type m) :FINISH_MESSAGE)
+ m))
+ state (u/seek #(and (= (:_type %) :DATA)
+ (= (:type %) "state"))
+ messages)
+ messages (-> (remove #(or (= % state) (= % finish)) messages)
+ vec)]
+ (app-db/update-or-insert! :model/MetabotConversation {:id conversation-id}
+ (constantly (cond-> {:user_id api/*current-user-id*}
+ state (assoc :state state))))
+ ;; NOTE: this will need to be constrained at some point, see BOT-386
+ (t2/insert-returning-pk! :model/MetabotMessage
+ (cond-> {:conversation_id conversation-id
+ :data messages
+ :usage (:usage finish)
+ :role (:role (first messages))
+ :profile_id profile-id
+ :total_tokens (->> (vals (:usage finish))
+ ;; NOTE: this filter is supporting backward-compatible usage format, can be
+ ;; removed when ai-service does not give us `completionTokens` in `usage`
+ (filter map?)
+ (map #(+ (:prompt %) (:completion %)))
+ (apply +))}
+ channel-id (assoc :channel_id channel-id)
+ slack-msg-id (assoc :slack_msg_id slack-msg-id)
+ user-id (assoc :user_id user-id)))))
+
+(defn set-response-slack-msg-id!
+ "Backfill slack_msg_id on a MetabotMessage by primary key."
+ [msg-id slack-msg-id]
+ (when (and msg-id slack-msg-id)
+ (t2/update! :model/MetabotMessage msg-id {:slack_msg_id slack-msg-id})))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/api.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/api.clj
index 785bc49c36d..6350820614a 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/api.clj
@@ -7,6 +7,8 @@
[metabase-enterprise.metabot-v3.reactions]
[metabase-enterprise.metabot-v3.settings :as metabot-v3.settings]
[metabase-enterprise.metabot-v3.table-utils :as table-utils]
+ [metabase-enterprise.metabot-v3.tools.create-alert
+ :as metabot-v3.tools.create-alert]
[metabase-enterprise.metabot-v3.tools.create-dashboard-subscription
:as metabot-v3.tools.create-dashboard-subscription]
[metabase-enterprise.metabot-v3.tools.deftool :refer [deftool]]
@@ -502,16 +504,34 @@
[:and
[:map
[:dashboard_id :int]
- [:email :string]
+ [:slack_channel :string]
[:schedule ::subscription-schedule]]
[:map {:encode/tool-api-request #(update-keys % metabot-v3.u/safe->kebab-case-en)}]])
(deftool "/create-dashboard-subscription"
- "Create a dashboard subscription."
+ "Create a dashboard subscription and send it to a slack channel."
{:args-schema ::create-dashboard-subscription-arguments
- :result-schema [:map [:output :string]]
+ :result-schema [:map [:error {:optional true} :string
+ :output {:optional true} :string]]
:handler metabot-v3.tools.create-dashboard-subscription/create-dashboard-subscription})
+(mr/def ::create-alert-arguments
+ [:and
+ [:map
+ [:card_id :int]
+ [:send_condition [:enum {:encode/tool-api-request keyword} "has_result" "goal_above" "goal_below"]]
+ [:send_once {:optional true, :default false} :boolean]
+ [:schedule ::subscription-schedule]
+ [:slack_channel :string]]
+ [:map {:encode/tool-api-request #(update-keys % metabot-v3.u/safe->kebab-case-en)}]])
+
+(deftool "/create-alert"
+ "Create an alert for a saved question."
+ {:args-schema ::create-alert-arguments
+ :result-schema [:map [:error {:optional true} :string
+ :output {:optional true} :string]]
+ :handler metabot-v3.tools.create-alert/create-alert})
+
;;; ---------------------------------------------------- Analytics ----------------------------------------------------
(mr/def ::field-values-arguments
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/create_alert.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/create_alert.clj
new file mode 100644
index 00000000000..125e3a4e936
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/create_alert.clj
@@ -0,0 +1,74 @@
+(ns metabase-enterprise.metabot-v3.tools.create-alert
+ (:require
+ [clojure.set :as set]
+ [metabase-enterprise.metabot-v3.tools.util :as metabot-v3.tools.u]
+ [metabase.api.common :as api]
+ [metabase.channel.settings :as channel.settings]
+ [metabase.notification.api :as notification.api]
+ [metabase.util.cron :as u.cron]
+ [toucan2.core :as t2]))
+
+(defn- schedule->cron
+ "Convert the tool schedule format to a Quartz cron string.
+ The schedule comes in as e.g. {:frequency :daily :hour 9} and needs to be
+ converted to a Quartz cron string like \"0 0 9 * * ? *\"."
+ [schedule]
+ (u.cron/schedule-map->cron-string (metabot-v3.tools.u/schedule->schedule-map schedule)))
+
+(defn- create-alert*
+ "Private helper for create-alert (call that instead)."
+ [{:keys [card-id slack-channel schedule send-condition send-once]
+ :or {send-once false}}]
+ (let [card (some-> (t2/select-one :model/Card card-id) api/read-check)
+ channel-name (some->> slack-channel
+ channel.settings/find-cached-slack-channel-or-username
+ :display-name)]
+ (cond
+ (nil? card)
+ {:error "no saved question with this card_id found"}
+
+ (nil? channel-name)
+ {:error "no slack channel found with this name"}
+
+ :else
+ (do
+ (notification.api/create-notification!
+ {:payload_type :notification/card
+ :active true
+ :creator_id api/*current-user-id*
+ :payload {:card_id card-id
+ :send_condition send-condition
+ :send_once send-once}
+ :subscriptions [{:type :notification-subscription/cron
+ :cron_schedule (schedule->cron schedule)}]
+ :handlers [{:channel_type :channel/slack
+ :recipients [{:type :notification-recipient/raw-value
+ :details {:value channel-name}}]}]})
+ {:output "success"}))))
+
+(defn create-alert
+ "Create an alert (notification when a saved question returns results)."
+ [{:keys [card-id send-condition send-once slack-channel]
+ :as args}]
+ (cond
+ (not (int? card-id))
+ {:error "invalid card_id"}
+
+ (and (some? send-once) (not (boolean? send-once)))
+ {:error "send_once must be a boolean"}
+
+ (not (#{:has_result :goal_above :goal_below} send-condition))
+ {:error (str "unsupported send_condition: " (some-> send-condition name))}
+
+ (not (channel.settings/slack-configured?))
+ {:error "slack is not configured. Ask an admin to set up slack notifications in Metabase settings."}
+
+ (empty? slack-channel)
+ {:error "slack_channel is required"}
+
+ :else
+ (try
+ (create-alert* args)
+ (catch Exception e
+ (-> (metabot-v3.tools.u/handle-agent-error e)
+ (set/rename-keys {:output :error}))))))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/create_dashboard_subscription.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/create_dashboard_subscription.clj
index 2f95d6f6a80..92bb91627c9 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/create_dashboard_subscription.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/create_dashboard_subscription.clj
@@ -1,55 +1,71 @@
(ns metabase-enterprise.metabot-v3.tools.create-dashboard-subscription
(:require
+ [clojure.set :as set]
+ [metabase-enterprise.metabot-v3.tools.util :as metabot-v3.tools.u]
[metabase.api.common :as api]
- [metabase.permissions.core :as perms]
- ^{:clj-kondo/ignore [:deprecated-namespace]}
- [metabase.pulse.core :as pulse]
- [metabase.util :as u]
+ [metabase.channel.settings :as channel.settings]
+ [metabase.pulse.api :as pulse.api]
[toucan2.core :as t2]))
+(defn- make-slack-channel
+ "Build a pulse channel for Slack delivery."
+ [schedule slack-channel]
+ (merge {:channel_type :slack
+ :enabled true
+ :details {:channel slack-channel}}
+ (metabot-v3.tools.u/schedule->schedule-map schedule)))
+
+(defn- create-dashboard-subscription*
+ "Private helper for create-dashboard-subscription (call that instead)."
+ [{:keys [dashboard-id slack-channel schedule]}]
+ (let [dashboard (some-> (t2/select-one :model/Dashboard dashboard-id)
+ api/read-check
+ (t2/hydrate [:dashcards :card]))
+ cards (for [{:keys [id card]} (:dashcards dashboard)
+ :when (-> card :id int?)]
+ (-> card
+ api/read-check
+ (select-keys [:id :name :collection_id :description :display :parameter_mappings])
+ (assoc :dashboard_card_id id :dashboard_id dashboard-id)))
+ channel-name (some->> slack-channel
+ channel.settings/find-cached-slack-channel-or-username
+ ;; match existing code which stores display names like "#some-channel"
+ :display-name)
+ pulse-data (-> dashboard
+ (select-keys [:collection_id :collection_position :name :parameters])
+ (assoc :dashboard_id dashboard-id
+ :creator_id api/*current-user-id*
+ :skip_if_empty false))]
+ (cond
+ (nil? dashboard)
+ {:error "no dashboard with this dashboard_id found"}
+
+ (nil? channel-name)
+ {:error "no slack channel found with this name"}
+
+ :else
+ (do (pulse.api/create-pulse-with-perm-checks!
+ cards
+ [(make-slack-channel schedule channel-name)]
+ pulse-data)
+ {:output "success"}))))
+
(defn create-dashboard-subscription
- "Create a dashboard subscription."
- [{:keys [dashboard-id email schedule]}]
- (perms/check-has-application-permission :subscription false)
- (if (int? dashboard-id)
- (let [dashboard (some-> (t2/select-one :model/Dashboard dashboard-id)
- api/read-check
- (t2/hydrate [:dashcards :card]))
- cards (for [{:keys [id card]} (:dashcards dashboard)
- :when (-> card :id int?)]
- (-> card
- api/read-check
- (select-keys [:id :name :collection_id :description :display :parameter_mappings])
- (assoc :dashboard_card_id id :dashboard_id dashboard-id)))
- recipient-id (t2/select-one-fn :id :model/User :email email)
- recipient {:id recipient-id}
- {:keys [frequency hour day-of-week day-of-month]} schedule
- channel {:channel_type :email
- :enabled true
- :recipients [recipient]
- :schedule_day (or (some-> day-of-week name (subs 0 3) u/lower-case-en)
- (some->> day-of-month
- name
- u/lower-case-en
- (re-find #"^(?:first|last)-(mon|tue|wed|thu|fri|sat|sun)")
- second))
- :schedule_frame (some->> day-of-month name (re-find #"^(?:first|mid|last)"))
- :schedule_hour hour
- :schedule_type frequency}
- pulse-data (-> dashboard
- (select-keys [:collection_id :collection_position :name :parameters])
- (assoc :dashboard_id dashboard-id
- :creator_id api/*current-user-id*
- :skip_if_empty false))]
- {:output
- (cond
- (nil? recipient-id)
- "no user with this email found"
-
- (nil? dashboard)
- "no dashboard with this dashboard_id found"
-
- :else
- (do (pulse/create-pulse! (map pulse/card->ref cards) [channel] pulse-data)
- "success"))})
- {:output "invalid dashboard_id"}))
+ "Create a dashboard subscription and send it to a slack channel."
+ [{:keys [dashboard-id slack-channel] :as args}]
+ (cond
+ (not (int? dashboard-id))
+ {:error "invalid dashboard_id"}
+
+ (not (channel.settings/slack-configured?))
+ {:error "slack is not configured. Ask an admin to connect slack in Metabase settings."}
+
+ (empty? slack-channel)
+ {:error "slack_channel is required"}
+
+ :else
+ (try
+ (create-dashboard-subscription* args)
+ (catch Exception e
+ (-> (metabot-v3.tools.u/handle-agent-error e)
+ (set/rename-keys {:output :error}))))))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/entity_details.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/entity_details.clj
index 18ad6e3d7bb..b84f6259208 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/entity_details.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/entity_details.clj
@@ -407,10 +407,14 @@
(let [options (cond-> arguments
(= (:with-field-values? arguments) false) (assoc :field-values-fn identity))
details (if (int? report-id)
- (let [details (card-details report-id options)]
+ (let [card (t2/hydrate (metabot-v3.tools.u/get-card report-id)
+ :average_query_time)
+ mp (lib-be/application-database-metadata-provider (:database_id card))
+ details (card-details card mp options)]
(-> details
(select-keys [:id :type :description :name :verified])
- (assoc :result-columns (:fields details))))
+ (assoc :result-columns (:fields details))
+ (m/assoc-some :average_query_time (:average_query_time card))))
(throw (ex-info "Invalid report_id format"
{:agent-error? true :status-code 400})))]
{:structured-output (assoc details :result-type :entity)}))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/filters.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/filters.clj
index 2a1549429cf..1b6c6d9fa6c 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/filters.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/filters.clj
@@ -376,9 +376,9 @@
query-id (u/generate-nano-id)
query-field-id-prefix (metabot-v3.tools.u/query-field-id-prefix query-id)
returned-cols (lib/returned-columns query)]
- {:type :query
- :query-id query-id
- :query query
+ {:type :query
+ :query-id query-id
+ :query query
:result-columns (into []
(map-indexed #(metabot-v3.tools.u/->result-column query %2 %1 query-field-id-prefix))
returned-cols)}))
@@ -584,9 +584,9 @@
query-id (u/generate-nano-id)
query-field-id-prefix (metabot-v3.tools.u/query-field-id-prefix query-id)
returned-cols (lib/returned-columns query)]
- {:type :query
- :query-id query-id
- :query query
+ {:type :query
+ :query-id query-id
+ :query query
:result-columns (into []
(map-indexed #(metabot-v3.tools.u/->result-column query %2 %1 query-field-id-prefix))
returned-cols)}))
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/util.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/util.clj
index 4dc79c40fca..8da8bfcb8b8 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/util.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/tools/util.clj
@@ -154,6 +154,20 @@
:status-code 400
:field-id field-id}))))
+(defn schedule->schedule-map
+ "Convert a tool schedule map to the schedule-map format used by cron and pulse channels.
+ E.g. {:frequency :daily :hour 9} => {:schedule_type \"daily\" :schedule_hour 9 ...}"
+ [{:keys [frequency hour day-of-week day-of-month]}]
+ {:schedule_type (name frequency)
+ :schedule_hour hour
+ :schedule_day (or (some-> day-of-week name (subs 0 3) u/lower-case-en)
+ (some->> day-of-month
+ name
+ u/lower-case-en
+ (re-find #"^(?:first|last)-(mon|tue|wed|thu|fri|sat|sun)")
+ second))
+ :schedule_frame (some->> day-of-month name (re-find #"^(?:first|mid|last)"))})
+
(defn get-database
"Get the `fields` of the database with ID `id`."
[id & fields]
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_v3/util.clj b/enterprise/backend/src/metabase_enterprise/metabot_v3/util.clj
index 4492ab1ff0d..ca031594fb3 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_v3/util.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_v3/util.clj
@@ -44,11 +44,17 @@
(def prefix-type "AI SDK prefix to type" (set/map-invert type-prefix))
+(defn parse-aisdk-line
+ "Parse a single AI SDK stream line into [type content].
+ Each line has a 2-char type prefix followed by a JSON payload."
+ [line]
+ [(get prefix-type (subs line 0 2)) (json/decode+kw (subs line 2))])
+
(defn aisdk->messages
"Convert AI SDK line format into an array of parsed messages."
[role lines]
(into [] (comp
- (map (fn [line] [(get prefix-type (subs line 0 2)) (json/decode+kw (subs line 2))]))
+ (map parse-aisdk-line)
(partition-by first)
(mapcat (fn [block]
(let [type (ffirst block)]
diff --git a/enterprise/backend/src/metabase_enterprise/slackbot/api.clj b/enterprise/backend/src/metabase_enterprise/slackbot/api.clj
new file mode 100644
index 00000000000..808f5bc2fa5
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/slackbot/api.clj
@@ -0,0 +1,674 @@
+(ns metabase-enterprise.slackbot.api
+ "`/api/ee/metabot-v3/slack` routes"
+ (:require
+ [clojure.string :as str]
+ [malli.core :as mc]
+ [metabase-enterprise.metabot-v3.config :as metabot-v3.config]
+ [metabase-enterprise.metabot-v3.feedback :as metabot-v3.feedback]
+ [metabase-enterprise.slackbot.client :as slackbot.client]
+ [metabase-enterprise.slackbot.config :as slackbot.config]
+ [metabase-enterprise.slackbot.events :as slackbot.events]
+ [metabase-enterprise.slackbot.persistence :as slackbot.persistence]
+ [metabase-enterprise.slackbot.settings :as slackbot.settings]
+ [metabase-enterprise.slackbot.streaming :as slackbot.streaming]
+ [metabase-enterprise.slackbot.uploads :as slackbot.uploads]
+ [metabase-enterprise.sso.settings :as sso-settings]
+ [metabase.analytics.core :as analytics]
+ [metabase.api.macros :as api.macros]
+ [metabase.channel.api.slack :as channel.api.slack]
+ [metabase.channel.settings :as channel.settings]
+ [metabase.config.core :as config]
+ [metabase.permissions.core :as perms]
+ [metabase.premium-features.core :as premium-features :refer [defenterprise
+ defenterprise-schema]]
+ [metabase.request.core :as request]
+ [metabase.settings.core :as setting]
+ [metabase.system.core :as system]
+ [metabase.util :as u]
+ [metabase.util.encryption :as encryption]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.json :as json]
+ [metabase.util.log :as log]
+ [metabase.util.malli :as mu]
+ [metabase.util.malli.schema :as ms]
+ [ring.util.codec :as codec]
+ [toucan2.core :as t2])
+ (:import
+ (java.util.concurrent ExecutorService Executors ThreadFactory)))
+
+(set! *warn-on-reflection* true)
+
+(defonce ^:private event-handler-executor
+ (delay
+ (let [counter (atom 0)
+ factory (reify ThreadFactory
+ (newThread [_ r]
+ (doto (Thread. r (str "slack-event-handler-" (swap! counter inc)))
+ (.setDaemon true))))]
+ (Executors/newFixedThreadPool (long (slackbot.settings/slackbot-event-handler-pool-size)) factory))))
+
+(defn- submit-async
+ "Submit a function for async execution on the bounded event handler thread pool."
+ [f]
+ (.submit ^ExecutorService @event-handler-executor
+ ^Runnable (bound-fn* f)))
+
+(defenterprise clear-slack-bot-settings!
+ "Clears all slackbot-related settings when Slack token is cleared.
+ This ensures enable-sso-slack? becomes false."
+ :feature :metabot-v3
+ []
+ (setting/set-many! {:slack-connect-enabled false
+ :slack-connect-client-id nil
+ :slack-connect-client-secret nil
+ :metabot-slack-signing-secret nil})
+ nil)
+
+(defenterprise-schema get-slack-manifest :- channel.api.slack/SlackManifest
+ "Enterprise implementation - returns full MetaBot manifest with event subscriptions, slash commands, etc."
+ :feature :metabot-v3
+ []
+ (let [base-url (system/site-url)]
+ (when-not base-url
+ (throw (ex-info (tru "You must configure a site-url for Slack integration to work.") {:status-code 503})))
+ (slackbot.config/build-slack-manifest base-url)))
+
+;; ------------------------- VALIDATION ----------------------------------
+
+(defn- assert-valid-slack-req
+ "Asserts that incoming Slack request has a valid signature."
+ [request]
+ (when-not (slackbot.settings/unobfuscated-metabot-slack-signing-secret)
+ (throw (ex-info (str (tru "Slack integration is not fully configured.")) {:status-code 503})))
+ (when-not (:slack/validated? request)
+ (throw (ex-info (str (tru "Slack request signature is not valid.")) {:status-code 401}))))
+
+;; ------------------------- AUTHENTICATION ------------------------------
+
+(defn- slack-id->user-id
+ "Look up a Metabase user ID from Slack user ID."
+ [slack-user-id]
+ (t2/select-one-fn :user_id
+ :model/AuthIdentity
+ :provider "slack-connect"
+ :provider_id slack-user-id
+ {:join [[:core_user :user] [:= :user.id :auth_identity.user_id]]
+ :where [:= :user.is_active true]
+ :order-by [[:created_at :desc]]}))
+
+(defn- slack-user-authorize-link
+ "Link to page where user can initiate SSO auth flow to authorize slackbot"
+ []
+ (let [sso-url "/auth/sso/slack-connect?redirect=/slack-connect-success"]
+ (str (system/site-url) "/auth/login?redirect=" (codec/url-encode sso-url))))
+
+(defn- send-auth-link
+ "Respond to an incoming slack message with a request to authorize.
+ For DMs, always threads the reply. For channel @mentions, only threads
+ if the original message was in a thread."
+ [client event]
+ (let [user-mention (slackbot.events/user-mention (:user event))
+ msg-prefix (if (slackbot.events/dm? event) "" (str user-mention " "))
+ msg (str msg-prefix "Connect your Slack account to Metabase. Once linked, I can use your permissions to query data on your behalf.")]
+ (slackbot.client/post-message
+ client
+ (merge (slackbot.events/event->reply-context event)
+ {;; DMs: always thread. Channels: only thread if already in a thread.
+ :thread_ts (or (:thread_ts event) (:ts event))
+ :text msg
+ :blocks [{:type "section"
+ :text {:type "mrkdwn"
+ :text msg}}
+ {:type "actions"
+ :elements [{:type "button"
+ :text {:type "plain_text"
+ :text ":link: Connect to Metabase"
+ :emoji true}
+ :url (slack-user-authorize-link)}]}]}))))
+
+(defn- require-authenticated-slack-user!
+ "Returns Metabase user-id if authenticated, nil otherwise.
+ Sends auth link as side-effect when not authenticated."
+ [client event]
+ (if-let [user-id (slack-id->user-id (:user event))]
+ user-id
+ (do (send-auth-link client event) nil)))
+
+;; ------------------------- EVENT HANDLING ------------------------------
+
+(mu/defn- handle-url-verification :- slackbot.events/SlackEventsResponse
+ "Respond to a url_verification request (docs: https://docs.slack.dev/reference/events/url_verification)"
+ [event :- slackbot.events/SlackUrlVerificationEvent]
+ {:status 200
+ :headers {"Content-Type" "text/plain"}
+ :body (:challenge event)})
+
+(def ^:private ack-msg
+ "Acknowledgement payload"
+ {:status 200
+ :headers {"Content-Type" "text/plain"}
+ :body "ok"})
+
+(defn- all-files-skipped?
+ "Returns true if all files were skipped (none were CSV/TSV)."
+ [{:keys [upload-result]}]
+ (let [{:keys [results skipped]} upload-result]
+ (and (seq skipped)
+ (empty? results))))
+
+(mu/defn- handle-message-file-share
+ "Process a file_share message - handles CSV uploads"
+ [client :- slackbot.client/SlackClient
+ event :- slackbot.events/SlackMessageFileShareEvent]
+ (let [files (:files event)
+ text (:text event)
+ has-text? (not (str/blank? text))
+ file-handling (when (seq files)
+ (slackbot.uploads/handle-file-uploads files))
+ extra-history (cond
+ ;; Pre-flight error (uploads disabled, no permission)
+ (:error file-handling)
+ [{:role :assistant
+ :content (:error file-handling)}]
+
+ ;; Upload results to communicate to AI
+ (:system-messages file-handling)
+ (:system-messages file-handling))
+ all-skipped? (all-files-skipped? file-handling)
+ should-skip-ai? (and (not has-text?)
+ (not (:error file-handling))
+ all-skipped?)]
+ ;; If all files were skipped (non-CSV) and there's no text, respond directly
+ ;; without calling the AI to avoid sending an empty prompt
+ (if should-skip-ai?
+ (let [skipped-files (get-in file-handling [:upload-result :skipped])]
+ (slackbot.client/post-message client
+ (merge (slackbot.events/event->reply-context event)
+ {:text (format "I can only process CSV and TSV files. The following files were skipped: %s"
+ (str/join ", " skipped-files))})))
+ (slackbot.streaming/send-response client event extra-history))))
+
+(defmethod analytics/known-labels :metabase-slackbot/responses-generated [_]
+ [{:source "dm" :result "success"}
+ {:source "dm" :result "error"}
+ {:source "channel" :result "success"}
+ {:source "channel" :result "error"}])
+
+(defmethod analytics/known-labels :metabase-slackbot/file-uploads [_]
+ [{:result "success"} {:result "error"}])
+
+(defn- event-source
+ "Return the source label for a Slack event: \"dm\" or \"channel\"."
+ [event]
+ (if (slackbot.events/dm? event) "dm" "channel"))
+
+(defn- process-async
+ "Process an event asynchronously with logging and error handling.
+ Authenticates the user and calls handler with [client event]."
+ [handler client event]
+ (let [event-type (or (:subtype event) (:channel_type event) (:type event))]
+ (log/debugf "[slackbot] Processing %s event" event-type)
+ (submit-async
+ (fn []
+ (try
+ (when-let [user-id (require-authenticated-slack-user! client event)]
+ (request/with-current-user user-id
+ (let [source (event-source event)
+ timer (u/start-timer)]
+ (try
+ (handler client event)
+ (analytics/inc! :metabase-slackbot/responses-generated {:source source :result "success"})
+ (catch Exception e
+ (analytics/inc! :metabase-slackbot/responses-generated {:source source :result "error"})
+ (throw e))
+ (finally
+ (analytics/observe! :metabase-slackbot/response-duration-ms {:source source} (u/since-ms timer)))))))
+ (catch Exception e
+ (log/errorf e "[slackbot] Error processing %s: %s" event-type (ex-message e))))))))
+
+(defn- ignore-event
+ "Handle any event we don't care to process"
+ [event]
+ (log/debugf "[slackbot] Ignoring event type=%s channel_type=%s subtype=%s ts=%s"
+ (:type event) (:channel_type event) (:subtype event) (:ts event)))
+
+(def ^:private delete-reaction-names
+ "Slack emoji names that trigger metabot-response deletion."
+ #{"wastebasket" "x"})
+
+(def ^:private removed-notice-blocks
+ [{:type "section"
+ :text {:type "mrkdwn"
+ :text "_Message has been removed._"}}])
+
+(defn- removed-notice-payload
+ [channel-id message-ts]
+ {:channel channel-id
+ :ts message-ts
+ :text "Message has been removed."
+ :blocks removed-notice-blocks})
+
+(defn- replace-response-with-removed-notice!
+ "Replace the Slack message first, then mark the stored response as deleted once Slack confirms the update."
+ [client channel-id message-ts deleter-user-id]
+ (let [res (slackbot.client/update-message client (removed-notice-payload channel-id message-ts))]
+ (if (:ok res)
+ (do
+ (when-not (slackbot.persistence/soft-delete-response! channel-id message-ts deleter-user-id)
+ (log/warnf "[slackbot] Slack message updated but soft delete was not recorded (channel=%s ts=%s user_id=%s)"
+ channel-id message-ts deleter-user-id))
+ (analytics/inc! :metabase-slackbot/responses-deleted)
+ true)
+ (do
+ (log/warnf "[slackbot] Failed to replace metabot response with removed notice: %s (channel=%s ts=%s user_id=%s)"
+ (:error res) channel-id message-ts deleter-user-id)
+ false))))
+
+(defn- authorize-delete-request
+ "Resolve whether a Slack delete request is authorized for the target metabot response."
+ [slack-user-id channel-id message-ts]
+ (cond
+ (nil? channel-id)
+ {:status :ignored
+ :reason :missing-channel
+ :message-ts message-ts}
+
+ (nil? message-ts)
+ {:status :ignored
+ :reason :missing-message-ts
+ :channel-id channel-id}
+
+ :else
+ (let [request-user-id (slack-id->user-id slack-user-id)]
+ (if (nil? request-user-id)
+ {:status :ignored
+ :reason :unlinked-user
+ :slack-user-id slack-user-id
+ :channel-id channel-id
+ :message-ts message-ts}
+ (if-let [owner-user-id (slackbot.persistence/response-owner-user-id channel-id message-ts)]
+ (if (= request-user-id owner-user-id)
+ {:status :authorized
+ :channel-id channel-id
+ :message-ts message-ts
+ :request-user-id request-user-id}
+ {:status :ignored
+ :reason :not-owner
+ :channel-id channel-id
+ :message-ts message-ts
+ :request-user-id request-user-id
+ :owner-user-id owner-user-id})
+ {:status :ignored
+ :reason :untracked-message
+ :channel-id channel-id
+ :message-ts message-ts})))))
+
+(defn- log-ignored-delete-request
+ "Log expected delete-request ignore paths at debug level."
+ [{:keys [source reason channel-id message-ts slack-user-id request-user-id owner-user-id reaction]}]
+ (case reason
+ :missing-channel
+ (log/debugf "[slackbot] Ignoring %s delete request with missing channel for ts=%s reaction=%s"
+ source message-ts reaction)
+
+ :missing-message-ts
+ (log/debugf "[slackbot] Ignoring %s delete request with missing message ts in channel=%s reaction=%s"
+ source channel-id reaction)
+
+ :unlinked-user
+ (log/debugf "[slackbot] Ignoring %s delete request from unlinked slack user=%s reaction=%s channel=%s ts=%s"
+ source slack-user-id reaction channel-id message-ts)
+
+ :not-owner
+ (log/debugf "[slackbot] Ignoring %s delete request from non-owner user_id=%s owner_user_id=%s channel=%s ts=%s reaction=%s"
+ source request-user-id owner-user-id channel-id message-ts reaction)
+
+ :untracked-message
+ (log/debugf "[slackbot] Ignoring %s delete request for untracked message channel=%s ts=%s reaction=%s"
+ source channel-id message-ts reaction)))
+
+(defn- delete-reaction-event?
+ "True when this event is a delete reaction added to a message."
+ [event]
+ (and (slackbot.events/reaction-added? event)
+ (= "message" (get-in event [:item :type]))
+ (contains? delete-reaction-names (:reaction event))))
+
+(defn- handle-delete-reaction
+ "Replace a metabot response with a removed notice when the original request user reacts with an approved emoji."
+ [client event]
+ (try
+ (let [slack-user-id (:user event)
+ reaction (:reaction event)
+ channel-id (get-in event [:item :channel])
+ message-ts (get-in event [:item :ts])
+ authorization (authorize-delete-request slack-user-id channel-id message-ts)]
+ (case (:status authorization)
+ :authorized
+ (when (replace-response-with-removed-notice! client channel-id message-ts (:request-user-id authorization))
+ (log/debugf "[slackbot] Replaced metabot response via reaction=%s channel=%s ts=%s"
+ reaction channel-id message-ts))
+
+ (log-ignored-delete-request (assoc authorization
+ :source "reaction"
+ :reaction reaction))))
+ (catch Exception e
+ (log/error e "[slackbot] Error handling delete reaction"))))
+
+(defn- assert-setup-complete
+ "Asserts that all required Slack settings have been configured."
+ []
+ (when-not (slackbot.config/setup-complete?)
+ (log/errorf "[slackbot] Slack setup incomplete (site_url=%s sso_enabled=%s client_id=%s client_secret=%s signing_secret=%s app_token=%s encryption=%s)"
+ (boolean (system/site-url))
+ (boolean (premium-features/enable-sso-slack?))
+ (boolean (sso-settings/slack-connect-client-id))
+ (boolean (sso-settings/slack-connect-client-secret))
+ (boolean (slackbot.settings/metabot-slack-signing-secret))
+ (boolean (channel.settings/unobfuscated-slack-app-token))
+ (boolean (encryption/default-encryption-enabled?)))
+ (throw (ex-info (str (tru "Slack integration is not fully configured.")) {:status-code 503}))))
+
+(mu/defn- handle-event-callback :- slackbot.events/SlackEventsResponse
+ "Respond to an event_callback request"
+ [payload :- slackbot.events/SlackEventCallbackEvent]
+ (assert-setup-complete)
+ (when (sso-settings/slack-connect-enabled)
+ (let [client {:token (channel.settings/unobfuscated-slack-app-token)}
+ event (:event payload)]
+ (log/debugf "[slackbot] Event callback: event_type=%s user=%s channel=%s"
+ (:type event) (:user event) (:channel event))
+ (cond
+ ((some-fn
+ slackbot.events/bot-message? ;; ignore the bot's own messages
+ slackbot.events/edited-message? ;; ignore message edits
+ slackbot.events/message-deleted? ;; ignore message deletion notifications
+ slackbot.events/app-mention-with-files?) ;; processed via the separate file_share event
+ event)
+ (ignore-event event)
+
+ (and
+ (slackbot.events/file-share? event)
+ (slackbot.events/dm-or-channel-mention? event (slackbot.client/get-bot-user-id client)))
+ (process-async handle-message-file-share client event)
+
+ (delete-reaction-event? event)
+ (submit-async (fn [] (handle-delete-reaction client event)))
+
+ (slackbot.events/reaction-added? event)
+ (log/debugf "[slackbot] Ignoring reaction_added for non-delete emoji reaction=%s item_type=%s channel=%s ts=%s"
+ (:reaction event) (get-in event [:item :type]) (get-in event [:item :channel]) (get-in event [:item :ts]))
+
+ (or (slackbot.events/app-mention? event)
+ (slackbot.events/dm? event))
+ (process-async slackbot.streaming/send-response client event)
+
+ :else
+ (ignore-event event))))
+ ack-msg)
+
+;; ----------------------- ROUTES --------------------------
+;; NOTE: make sure to do premium-features/enable-metabot-v3? checks if you add new endpoints
+
+(api.macros/defendpoint :post "/events" :- slackbot.events/SlackEventsResponse
+ "Respond to activities in Slack"
+ [_route-params
+ _query-params
+ body :- [:multi {:dispatch :type}
+ ["url_verification" slackbot.events/SlackUrlVerificationEvent]
+ ["event_callback" slackbot.events/SlackEventCallbackEvent]
+ [::mc/default [:map [:type :string]]]]
+ request]
+ (log/debugf "[slackbot] Incoming Slack request type=%s slack_event_type=%s request_ts=%s"
+ (:type body)
+ (get-in body [:event :type])
+ (get-in request [:headers "x-slack-request-timestamp"]))
+ (assert-valid-slack-req request)
+ (log/debugf "[slackbot] Received Slack event type=%s slack_event_type=%s" (:type body) (get-in body [:event :type]))
+ ;; all handlers must respond within 3 seconds or slack will retry
+ (if (premium-features/enable-metabot-v3?)
+ (case (:type body)
+ "url_verification" (handle-url-verification body)
+ "event_callback" (handle-event-callback body)
+ ack-msg)
+ ack-msg))
+
+(def SlackBotSettingsRequest
+ "Malli schema for the request body of PUT /api/ee/metabot-v3/slack/settings.
+ All credential fields must be provided together (either all set or all nil)."
+ [:map
+ [:slack-connect-client-id [:maybe ms/NonBlankString]]
+ [:slack-connect-client-secret [:maybe ms/NonBlankString]]
+ [:metabot-slack-signing-secret [:maybe ms/NonBlankString]]])
+
+(def SlackBotSettingsResponse
+ "Malli schema for the response of PUT /api/ee/metabot-v3/slack/settings."
+ [:map
+ [:ok :boolean]])
+
+(api.macros/defendpoint :put "/settings" :- SlackBotSettingsResponse
+ "Update Metabot Slack settings atomically.
+ All credential fields must be provided together.
+ Setting values requires the metabot-v3 feature, but clearing values is always allowed.
+ slack-connect-enabled is automatically set to true when credentials are provided, nil when cleared."
+ [_route-params
+ _query-params
+ {:keys [slack-connect-client-id
+ slack-connect-client-secret
+ metabot-slack-signing-secret]} :- SlackBotSettingsRequest]
+ (perms/check-has-application-permission :setting)
+ (let [all-set? (and slack-connect-client-id
+ slack-connect-client-secret
+ metabot-slack-signing-secret)
+ all-unset? (and (nil? slack-connect-client-id)
+ (nil? slack-connect-client-secret)
+ (nil? metabot-slack-signing-secret))]
+ ;; require metabot-v3 feature only when setting values (clearing is always allowed)
+ (when (not (or all-unset? (premium-features/enable-metabot-v3?)))
+ (throw (ex-info (tru "Metabot feature is not enabled.")
+ {:status-code 402})))
+ ;; all values must be set together or unset together
+ (when-not (or all-set? all-unset?)
+ (throw (ex-info (tru "Must provide client id, client secret and signing secret together.")
+ {:status-code 400})))
+ (setting/set-many! {:slack-connect-client-id slack-connect-client-id
+ :slack-connect-client-secret slack-connect-client-secret
+ :metabot-slack-signing-secret metabot-slack-signing-secret
+ :slack-connect-enabled (boolean all-set?)})
+ {:ok true}))
+
+;; ------------------------- FEEDBACK BUTTONS ------------------------------
+
+(def ^:private issue-type-options
+ [{:text {:type "plain_text" :text "Wrong or unhelpful chart"} :value "unhelpful-chart"}
+ {:text {:type "plain_text" :text "Wrong chart type"} :value "wrong-chart-type"}
+ {:text {:type "plain_text" :text "Incorrect data or results"} :value "not-factual"}
+ {:text {:type "plain_text" :text "Did not follow request"} :value "did-not-follow-request"}
+ {:text {:type "plain_text" :text "Incomplete response"} :value "incomplete-response"}
+ {:text {:type "plain_text" :text "Other"} :value "other"}])
+
+(defn- feedback-modal-view
+ "Build a Slack modal view for collecting detailed feedback."
+ [positive private-metadata]
+ {:type "modal"
+ :callback_id "metabot_feedback_modal"
+ :notify_on_close false
+ :title {:type "plain_text" :text "Metabot feedback"}
+ :submit {:type "plain_text" :text "Submit"}
+ :close {:type "plain_text" :text "Cancel"}
+ :private_metadata (json/encode private-metadata)
+ :blocks
+ (let [freeform-block {:type "input"
+ :block_id "freeform_feedback"
+ :optional true
+ :element {:type "plain_text_input"
+ :action_id "freeform_input"
+ :multiline true
+ :placeholder {:type "plain_text"
+ :text (if positive
+ "Tell us what you liked!"
+ "What could be improved about this response?")}}
+ :label {:type "plain_text" :text "Any details you'd like to share?"}}]
+ (if positive
+ [freeform-block]
+ [{:type "input"
+ :block_id "issue_type"
+ :optional true
+ :element {:type "static_select"
+ :action_id "issue_type_select"
+ :placeholder {:type "plain_text" :text "Select issue type"}
+ :options issue-type-options}
+ :label {:type "plain_text" :text "What kind of issue are you reporting?"}}
+ freeform-block]))})
+
+(defn- build-base-feedback
+ "Build the common feedback payload fields."
+ [user-id conversation-id positive]
+ {:metabot_id (metabot-v3.config/normalize-metabot-id "slackbotmetabotmetabo")
+ :feedback {:positive positive
+ :message_id conversation-id
+ :freeform_feedback ""}
+ :conversation_data {}
+ :version config/mb-version-info
+ :submission_time (str (java.time.OffsetDateTime/now))
+ :is_admin (boolean (t2/select-one-fn :is_superuser :model/User :id user-id))
+ :source "slack"})
+
+(defn- handle-feedback-action
+ "Handle a metabot feedback button click from Slack.
+ Opens the detail modal immediately (trigger_id expires in 3s). Feedback is
+ submitted to Harbormaster only when the user submits the modal."
+ [{:keys [action trigger-id slack-user-id channel-id message-ts]}]
+ (let [{:keys [conversation_id positive]} (json/decode (:value action) true)
+ client {:token (channel.settings/unobfuscated-slack-app-token)}
+ user-id (slack-id->user-id slack-user-id)]
+ (when user-id
+ (try
+ (slackbot.client/open-view
+ client
+ {:trigger_id trigger-id
+ :view (feedback-modal-view positive {:conversation_id conversation_id
+ :positive positive
+ :user_id user-id
+ :channel_id channel-id
+ :message_ts message-ts})})
+ (catch Exception e
+ (log/errorf e "[slackbot] Error opening feedback modal: %s" (ex-data e)))))))
+
+(defn- handle-delete-action
+ "Handle replacing a metabot response message with a removed notice.
+ Only the user who triggered the response can do this."
+ [{:keys [slack-user-id channel-id message-ts]}]
+ (let [authorization (authorize-delete-request slack-user-id channel-id message-ts)]
+ (case (:status authorization)
+ :authorized
+ (let [client {:token (channel.settings/unobfuscated-slack-app-token)}]
+ (submit-async
+ (fn []
+ (try
+ (replace-response-with-removed-notice! client channel-id message-ts (:request-user-id authorization))
+ (catch Exception e
+ (log/errorf e "[slackbot] Error replacing metabot response with removed notice: %s" (ex-data e)))))))
+
+ (log-ignored-delete-request (assoc authorization :source "action")))))
+
+(defn- handle-feedback-modal-submission
+ "Handle submission of the feedback details modal. Submits detailed feedback to Harbormaster."
+ [payload]
+ (let [private-metadata (json/decode (get-in payload [:view :private_metadata]) true)
+ {:keys [conversation_id positive user_id]} private-metadata
+ values (get-in payload [:view :state :values])
+ issue-type (get-in values [:issue_type :issue_type_select :selected_option :value])
+ freeform (get-in values [:freeform_feedback :freeform_input :value])]
+ (submit-async
+ (fn []
+ (try
+ (metabot-v3.feedback/submit-to-harbormaster!
+ (cond-> (build-base-feedback user_id conversation_id positive)
+ true (assoc-in [:feedback :freeform_feedback] (or freeform ""))
+ issue-type (assoc-in [:feedback :issue_type] issue-type)))
+ (catch Exception e
+ (log/error e "[slackbot] Error submitting feedback to Harbormaster")))))))
+
+#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
+(api.macros/defendpoint :post "/interactive"
+ "Handle interactive payloads from Slack (button clicks, modal submissions)."
+ [_route-params _query-params _body request]
+ (assert-valid-slack-req request)
+ (when (premium-features/enable-metabot-v3?)
+ (let [payload (-> (get-in request [:params :payload])
+ (json/decode true))]
+ (case (:type payload)
+ "block_actions"
+ (let [actions (:actions payload)
+ slack-user (get-in payload [:user :id])
+ trigger-id (:trigger_id payload)
+ channel-id (get-in payload [:channel :id])
+ message-ts (get-in payload [:message :ts])]
+ (doseq [action actions]
+ (case (:action_id action)
+ "metabot_feedback"
+ (handle-feedback-action {:action action
+ :trigger-id trigger-id
+ :slack-user-id slack-user
+ :channel-id channel-id
+ :message-ts message-ts})
+
+ "metabot_delete_response"
+ (handle-delete-action {:slack-user-id slack-user
+ :channel-id channel-id
+ :message-ts message-ts})
+ nil)))
+
+ "view_submission"
+ (when (= (get-in payload [:view :callback_id]) "metabot_feedback_modal")
+ (handle-feedback-modal-submission payload))
+
+ nil)))
+ {:status 200 :body ""})
+
+(def ^{:arglists '([request respond raise])} routes
+ "`/api/ee/metabot-v3/slack` routes."
+ (api.macros/ns-handler *ns*))
+
+;; -------------- LOCAL DEV SETUP -------------------
+
+(comment
+ ;; New slack app
+ ;; 1. create a tunnel via `ngrok http 3000`
+ ;; 2. update your site url to the provided tunnel url
+ (system/site-url! "https://<random-id>.ngrok-free.app")
+ ;; 4. visit this url in your browser, following the setup flow outlined there
+ (str (system/site-url) "/admin/metabot/slackbot")
+ ;; 6. verify you've setup your instance correctly
+ (slackbot.config/setup-complete?)
+
+ ;; Updating an existing slack app
+ ;; 1. create a tunnel via `ngrok http 3000`
+ ;; 2. update your site url to the provided tunnel url
+ (system/site-url! "https://3ee6-104-174-230-42.ngrok-free.app")
+ ;; 3. visit the app manifest slack settings page for your slack app (https://app.slack.com/app-settings/.../..../app-manifest)
+ ;; 4. execute this form to copy the manifest to clipboard, paste the result in the manifest page
+ (do
+ (require '[clojure.java.shell :refer [sh]])
+ (sh "pbcopy" :in (json/encode (get-slack-manifest) {:pretty true}))))
+ ;; 5. there will be a notification at the top of the manifest page to verify your new site url, click verify
+
+;; ----------------- DEV -----------------------
+
+(comment
+ (def user-id "XXXXXXXXXXX") ; your slack user id (not the bot's)
+ (def channel "XXXXXXXXXXX") ; slack channel id (e.g. bot's dms)
+ (def thread-ts "XXXXXXXX.XXXXXXX") ; thread id
+
+ (def client {:token (channel.settings/unobfuscated-slack-app-token)})
+ (def message (slackbot.client/post-message client {:channel channel :text "_Thinking..._" :thread_ts thread-ts}))
+ (slackbot.client/delete-message client message)
+ (select-keys message [:channel :ts])
+
+ (slackbot.client/post-ephemeral-message client {:channel channel
+ :user user-id
+ :text "sssh"
+ :thread_ts thread-ts})
+
+ (def thread (slackbot.client/fetch-thread client message)))
diff --git a/enterprise/backend/src/metabase_enterprise/slackbot/channel.clj b/enterprise/backend/src/metabase_enterprise/slackbot/channel.clj
new file mode 100644
index 00000000000..cc7e7a25bed
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/slackbot/channel.clj
@@ -0,0 +1,113 @@
+(ns metabase-enterprise.slackbot.channel
+ "Visible Slack channel reply/update flow for metabot."
+ (:require
+ [clojure.string :as str]
+ [metabase-enterprise.metabot-v3.persistence :as metabot-v3.persistence]
+ [metabase-enterprise.slackbot.client :as slackbot.client]
+ [metabase.util.log :as log]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private channel-response-style-suffix
+ (str "\n\n"
+ "For this Slack channel response: the user already saw tool progress updates. "
+ "Do not narrate the steps you took, do not recap tool calls, and do not include preambles like "
+ "\"I'll...\", \"Let me...\", or \"I found...\". Give a brief final response in "
+ "1-2 sentences before any table or chart."))
+
+(defn- channel-request-prompt
+ "Append channel-specific response style guidance without changing the stored user prompt."
+ [prompt]
+ (str prompt channel-response-style-suffix))
+
+(defn- final-text-blocks
+ "Build the leading text block(s) for a finalized non-streaming Slack message."
+ [text]
+ (if (str/blank? text)
+ []
+ [{:type "section"
+ :text {:type "mrkdwn"
+ :text text}}]))
+
+(defn- make-channel-callbacks
+ "Create callback functions for channel replies.
+ Uses the Slack assistant setStatus API for progress indication.
+ Text is accumulated and sent once in the final message post."
+ [client {:keys [channel thread-ts tool-name->friendly]}]
+ (let [current-text (atom "")]
+ (letfn [(set-status! [status]
+ (try
+ (slackbot.client/set-status client {:status "is doing science..."
+ :channel-id channel
+ :thread-ts thread-ts
+ :loading-messages [(or status "")]})
+ (catch Exception e
+ (log/warnf e "[slackbot] set-status failed (channel=%s thread-ts=%s)" channel thread-ts))))]
+ {:on-text (bound-fn* (fn [text]
+ (when (seq text)
+ (swap! current-text str text))))
+ :on-tool-start (fn [{:keys [tool-name]}]
+ (set-status! (str (tool-name->friendly tool-name "Thinking") "...")))
+ :set-status! set-status!
+ :current-text current-text})))
+
+(defn send-channel-response
+ "Send a visible threaded reply for non-DM Slack conversations.
+ Accumulates AI text during streaming and posts the final response as a single message."
+ [client event extra-history {:keys [channel-id message-ctx channel thread-ts thread bot-user-id prompt conversation-id]}
+ {:keys [tool-name->friendly
+ make-streaming-ai-request collect-viz-blocks feedback-blocks post-viz-error!
+ make-viz-prefetch-callback cancel-prefetched-viz!]}]
+ (let [{:keys [on-text on-tool-start set-status! current-text]}
+ (make-channel-callbacks client {:channel channel
+ :thread-ts thread-ts
+ :tool-name->friendly tool-name->friendly})
+ prefetched-viz (atom {})
+ on-data (make-viz-prefetch-callback prefetched-viz)
+ stored-msg-id (atom nil)]
+ (set-status! "Thinking...")
+ (try
+ (make-streaming-ai-request
+ conversation-id
+ prompt
+ thread
+ bot-user-id
+ channel-id
+ extra-history
+ {:on-text on-text
+ :on-tool-start on-tool-start
+ :on-tool-end nil
+ :on-data on-data
+ :req-slack-msg-id (:ts event)
+ :get-res-slack-msg-id nil
+ :request-prompt (channel-request-prompt prompt)
+ :stored-msg-id stored-msg-id})
+ (when (seq @prefetched-viz)
+ (set-status! "Rendering results..."))
+ (let [{:keys [blocks errors]} (collect-viz-blocks @prefetched-viz)
+ answer-text (str/trim @current-text)
+ final-text (if (or (seq answer-text) (seq blocks))
+ answer-text
+ "I wasn't able to generate a response. Please try again.")
+ final-blocks (into (into (final-text-blocks final-text) blocks)
+ (feedback-blocks conversation-id))
+ res (slackbot.client/post-thread-reply client {:channel channel :thread_ts thread-ts}
+ final-text :blocks final-blocks)]
+ (when-let [res-ts (:ts res)]
+ (metabot-v3.persistence/set-response-slack-msg-id! @stored-msg-id res-ts))
+ (when-not (:ok res)
+ (log/errorf "[slackbot] channel post-message failed: %s (block_count=%d block_types=%s response_messages=%s)"
+ (:error res)
+ (count (or final-blocks []))
+ (pr-str (when final-blocks (mapv :type final-blocks)))
+ (pr-str (get-in res [:response_metadata :messages]))))
+ (doseq [e errors]
+ (post-viz-error! client channel thread-ts e)))
+ (catch Exception e
+ (cancel-prefetched-viz! prefetched-viz)
+ (log/error e "[slackbot] Error in channel response")
+ (set-status! nil)
+ (let [res (slackbot.client/post-thread-reply client message-ctx
+ "Something went wrong. Please try again.")]
+ (when-not (:ok res)
+ (log/errorf "[slackbot] channel error post-message failed: %s" (:error res))))))))
diff --git a/enterprise/backend/src/metabase_enterprise/slackbot/client.clj b/enterprise/backend/src/metabase_enterprise/slackbot/client.clj
new file mode 100644
index 00000000000..f8de0f7460b
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/slackbot/client.clj
@@ -0,0 +1,260 @@
+(ns metabase-enterprise.slackbot.client
+ "Slack API client functions for Metabot slackbot."
+ (:import
+ (java.io InputStream))
+ (:require
+ [clj-http.client :as http]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.json :as json]
+ [metabase.util.log :as log]
+ [metabase.util.malli.schema :as ms]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private streaming-connection-timeout-ms
+ "TCP connection timeout for streaming API calls."
+ 5000)
+
+(def ^:private streaming-socket-timeout-ms
+ "Socket (read) timeout for streaming API calls (start/append/stop)."
+ 5000)
+
+(def SlackClient
+ "Malli schema for a Slack client."
+ [:map {:closed true}
+ [:token ms/NonBlankString]])
+
+(defn- slack-get
+ "GET from slack."
+ [client endpoint params]
+ (let [response (http/get (str "https://slack.com/api" endpoint)
+ {:headers {"Authorization" (str "Bearer " (:token client))}
+ :query-params params})]
+ {:body (json/decode (:body response) true)
+ :headers (:headers response)}))
+
+(defn- slack-post-json
+ "POST to slack."
+ [client endpoint payload & {:keys [socket-timeout connection-timeout]}]
+ (let [response (http/post (str "https://slack.com/api" endpoint)
+ (cond-> {:headers {"Authorization" (str "Bearer " (:token client))}
+ :content-type "application/json; charset=utf-8"
+ :body (json/encode payload)}
+ connection-timeout (assoc :connection-timeout connection-timeout)
+ socket-timeout (assoc :socket-timeout socket-timeout)))]
+ {:body (json/decode (:body response) true)
+ :headers (:headers response)}))
+
+(defn- slack-post-form
+ "POST form to slack."
+ [client endpoint payload]
+ (-> (http/post (str "https://slack.com/api" endpoint)
+ {:headers {"Authorization" (str "Bearer " (:token client))}
+ :content-type "application/x-www-form-urlencoded; charset=utf-8"
+ :form-params payload})
+ :body
+ (json/decode true)))
+
+(def ^:private slack-token-error-codes
+ "Error codes from Slack that indicate an invalid or revoked token."
+ #{"invalid_auth" "account_inactive" "token_revoked" "token_expired" "not_authed"})
+
+(defn auth-test
+ "Call auth.test and return the response including headers.
+ Throws an exception with appropriate status code if the call fails:
+ - 400 for invalid/revoked tokens
+ - 502 for Slack API errors (e.g., Slack is down)"
+ [client]
+ (try
+ (let [{:keys [body headers]} (slack-post-json client "/auth.test" {})]
+ (if (:ok body)
+ {:body body :headers headers}
+ (let [error-code (:error body)
+ invalid-token? (slack-token-error-codes error-code)]
+ (throw (ex-info (if invalid-token?
+ (tru "Invalid Slack bot token: {0}" error-code)
+ (tru "Slack API error: {0}" error-code))
+ {:status-code (if invalid-token? 400 502)
+ :error-code error-code})))))
+ (catch clojure.lang.ExceptionInfo e
+ (throw e))
+ (catch Exception e
+ (throw (ex-info (tru "Unable to connect to Slack API: {0}" (.getMessage e))
+ {:status-code 502}
+ e)))))
+
+(defn get-bot-user-id
+ "Get the bot's Slack user ID"
+ [client]
+ (:user_id (:body (auth-test client))))
+
+(defn fetch-thread
+ "Fetch a Slack thread"
+ ([client message]
+ (fetch-thread client message 50))
+ ([client message limit]
+ (:body (slack-get client "/conversations.replies"
+ {:channel (:channel message)
+ :ts (or (:thread_ts message) (:ts message))
+ :limit limit}))))
+
+(defn- get-upload-url
+ "Get a URL we can upload to"
+ [client args]
+ (slack-post-form client "/files.getUploadURLExternal" args))
+
+(defn set-status
+ "Set the status for a Slack assistant thread."
+ [client {:keys [status channel-id thread-ts loading-messages]}]
+ (:body (slack-post-json client "/assistant.threads.setStatus" (cond-> {:status status
+ :channel_id channel-id
+ :thread_ts thread-ts}
+ loading-messages (assoc :loading_messages loading-messages)))))
+
+(defn post-message
+ "Send a Slack message"
+ [client message]
+ (:body (slack-post-json client "/chat.postMessage" message)))
+
+(defn post-thread-reply
+ "Send a threaded Slack reply using an existing reply context plus text and optional blocks."
+ [client message-ctx text & {:keys [blocks]}]
+ (post-message client
+ (cond-> (assoc message-ctx :text text)
+ blocks (assoc :blocks blocks))))
+
+(defn post-ephemeral-message
+ "Send a Slack ephemeral message (visible only to the specified user)"
+ [client message]
+ (:body (slack-post-json client "/chat.postEphemeral" message)))
+
+(defn post-image
+ "Upload a PNG image and send in a message.
+ Optional initial-comment adds context text alongside the image."
+ [client image-bytes filename channel thread-ts & {:keys [initial-comment]}]
+ (let [{:keys [ok upload_url file_id] :as res} (get-upload-url client {:filename filename
+ :length (alength ^bytes image-bytes)})]
+ (when ok
+ (http/post upload_url
+ {:headers {"Content-Type" "image/png"}
+ :body image-bytes})
+ (:body (slack-post-json client "/files.completeUploadExternal"
+ (cond-> {:files [{:id file_id
+ :title filename}]
+ :channel_id channel
+ :thread_ts thread-ts}
+ initial-comment (assoc :initial_comment initial-comment))))
+ res)))
+
+(defn fetch-message
+ "Fetch a single Slack message by channel and timestamp."
+ [client channel ts]
+ (let [{:keys [messages]} (:body (slack-get client "/conversations.history"
+ {:channel channel
+ :latest ts
+ :limit 1
+ :inclusive true}))]
+ (first messages)))
+
+(defn delete-message
+ "Remove a Slack message"
+ [client message]
+ (:body (slack-post-json client "/chat.delete" (select-keys message [:channel :ts]))))
+
+(defn add-reaction
+ "Add a reaction to a Slack message."
+ [client {:keys [channel ts name]}]
+ (:body (slack-post-json client "/reactions.add" {:channel channel
+ :timestamp ts
+ :name name})))
+
+(defn remove-reaction
+ "Remove a reaction from a Slack message."
+ [client {:keys [channel ts name]}]
+ (:body (slack-post-json client "/reactions.remove" {:channel channel
+ :timestamp ts
+ :name name})))
+
+(defn update-message
+ "Update a Slack message"
+ [client message]
+ (:body (slack-post-json client "/chat.update" message)))
+
+(defn open-view
+ "Open a Slack modal view, triggered from an interaction."
+ [client {:keys [trigger_id view]}]
+ (:body (slack-post-json client "/views.open" {:trigger_id trigger_id
+ :view view})))
+
+(defn download-file-stream
+ "Download a file from Slack, returning an InputStream instead of buffering in memory.
+ Caller is responsible for closing the stream (e.g. via `with-open`)."
+ ^InputStream
+ [client url]
+ (-> (http/get url {:headers {"Authorization" (str "Bearer " (:token client))}
+ :as :stream})
+ :body))
+
+;; -------------------- SLACK STREAMING API --------------------
+;; These functions implement Slack's chat streaming API for progressive AI responses.
+;; See: https://docs.slack.dev/changelog/2025/10/7/chat-streaming/
+
+(defn start-stream
+ "Start a Slack message stream. Returns the stream timestamp on success (acts as an identifier)."
+ [client {:keys [channel thread_ts team_id user_id]}]
+ (let [payload {:channel channel
+ :thread_ts thread_ts
+ :recipient_team_id team_id
+ :recipient_user_id user_id}
+ body (:body (slack-post-json client "/chat.startStream"
+ payload
+ :connection-timeout streaming-connection-timeout-ms
+ :socket-timeout streaming-socket-timeout-ms))]
+ (if (:ok body)
+ {:stream_ts (:ts body)
+ :channel (:channel body)
+ :thread_ts thread_ts}
+ (do
+ (log/warnf "[slackbot] start-stream failed: %s (channel=%s thread_ts=%s recipient_team_id=%s recipient_user_id=%s)"
+ (:error body) channel thread_ts team_id user_id)
+ (log/debugf "[slackbot] start-stream failure body=%s payload=%s"
+ (pr-str body) (pr-str payload))))))
+
+(defn append-stream
+ "Append chunks to an active stream. Each chunk is a map with :type and type-specific keys,
+ e.g. {:type \"markdown_text\" :text \"...\"} or {:type \"task_update\" :id \"...\" :title \"...\" :status \"...\"}."
+ [client channel stream-ts chunks]
+ (let [payload {:channel channel
+ :ts stream-ts
+ :chunks chunks}
+ body (:body (slack-post-json client "/chat.appendStream" payload
+ :connection-timeout streaming-connection-timeout-ms
+ :socket-timeout streaming-socket-timeout-ms))]
+ (when-not (:ok body)
+ (log/warnf "[slackbot] append-stream failed: %s" (:error body)))
+ body))
+
+(defn append-markdown-text
+ "Helper to append markdown text to a stream."
+ [client channel stream-ts text]
+ (append-stream client channel stream-ts [{:type "markdown_text" :text text}]))
+
+(defn stop-stream
+ "Stop a stream and finalize it into a regular message."
+ ([client channel stream-ts]
+ (stop-stream client channel stream-ts nil))
+ ([client channel stream-ts blocks]
+ (let [payload (cond-> {:channel channel
+ :ts stream-ts}
+ blocks (assoc :blocks blocks))
+ block-types (when blocks (mapv :type blocks))
+ body (:body (slack-post-json client "/chat.stopStream"
+ payload
+ :connection-timeout streaming-connection-timeout-ms
+ :socket-timeout streaming-socket-timeout-ms))]
+ (when-not (:ok body)
+ (log/warnf "[slackbot] stop-stream failed: %s (channel=%s stream_ts=%s block_count=%d block_types=%s)"
+ (:error body) channel stream-ts (count (or blocks [])) (pr-str block-types))
+ (log/debugf "[slackbot] stop-stream failure body=%s payload=%s"
+ (pr-str body) (pr-str (update payload :blocks #(when % "[redacted-blocks]")))))
+ body)))
diff --git a/enterprise/backend/src/metabase_enterprise/slackbot/config.clj b/enterprise/backend/src/metabase_enterprise/slackbot/config.clj
new file mode 100644
index 00000000000..fc3878a9bdc
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/slackbot/config.clj
@@ -0,0 +1,84 @@
+(ns metabase-enterprise.slackbot.config
+ "Configuration, manifest, and validation helpers for slackbot."
+ (:require
+ [metabase-enterprise.slackbot.client :as slackbot.client]
+ [metabase-enterprise.slackbot.settings :as slackbot.settings]
+ [metabase-enterprise.sso.settings :as sso-settings]
+ [metabase.channel.settings :as channel.settings]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.system.core :as system]
+ [metabase.util.encryption :as encryption]))
+
+(set! *warn-on-reflection* true)
+
+(defn build-slack-manifest
+ "Build the full Metabot Slack app manifest for the given base URL."
+ [base-url]
+ {:display_information {:name "Metabot"
+ :description "Your AI-powered data assistant"
+ :background_color "#509EE3"}
+ :features {:app_home {:home_tab_enabled false
+ :messages_tab_enabled true
+ :messages_tab_read_only_enabled false}
+ :bot_user {:display_name "Metabot"
+ :always_online false}
+ :assistant_view {:assistant_description "Your AI-powered data assistant"}
+ :slash_commands [{:command "/metabot"
+ :url (str base-url "/api/ee/metabot-v3/slack/commands")
+ :description "Issue a Metabot command"
+ :should_escape false}]}
+ :oauth_config {:redirect_urls [(str base-url "/auth/sso/slack-connect/callback")]
+ :scopes {:bot ["app_mentions:read"
+ "assistant:write"
+ "channels:history"
+ "chat:write"
+ "chat:write.customize"
+ "chat:write.public"
+ "channels:join"
+ "channels:read"
+ "commands"
+ "groups:read"
+ "groups:history"
+ "im:history"
+ "im:read"
+ "files:read"
+ "files:write"
+ "mpim:read"
+ "reactions:read"
+ "reactions:write"
+ "users:read"]}}
+ :settings {:event_subscriptions {:request_url (str base-url "/api/ee/metabot-v3/slack/events")
+ :bot_events ["app_home_opened"
+ "app_mention"
+ "message.channels"
+ "message.im"
+ "reaction_added"
+ "assistant_thread_started"
+ "assistant_thread_context_changed"]}
+ :interactivity {:is_enabled true
+ :request_url (str base-url "/api/ee/metabot-v3/slack/interactive")}
+ :org_deploy_enabled true
+ :socket_mode_enabled false
+ :token_rotation_enabled false}})
+
+(defn setup-complete?
+ "Returns true if all required Slack settings are configured to process events."
+ []
+ (boolean
+ (and (some? (system/site-url))
+ (premium-features/enable-sso-slack?)
+ (sso-settings/slack-connect-client-id)
+ (sso-settings/slack-connect-client-secret)
+ (slackbot.settings/metabot-slack-signing-secret)
+ (channel.settings/unobfuscated-slack-app-token)
+ (encryption/default-encryption-enabled?))))
+
+#_{:clj-kondo/ignore [:clojure-lsp/unused-public-var]}
+(defn validate-bot-token!
+ "Validate a Slack bot token using the auth.test endpoint.
+ Throws an exception with appropriate status code if validation fails:
+ - 400 for invalid/revoked tokens
+ - 502 for Slack API errors (e.g., Slack is down)
+ Returns the response map on success."
+ [token]
+ (slackbot.client/auth-test {:token token}))
diff --git a/enterprise/backend/src/metabase_enterprise/slackbot/events.clj b/enterprise/backend/src/metabase_enterprise/slackbot/events.clj
new file mode 100644
index 00000000000..80775c08673
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/slackbot/events.clj
@@ -0,0 +1,154 @@
+(ns metabase-enterprise.slackbot.events
+ "Event definitions for slackbot."
+ (:require
+ [clojure.string :as str]))
+
+(def SlackEventsResponse
+ "Malli schema for Slack events API response"
+ [:map
+ ;; Response status is expected to be 2xx to indicate the event was received
+ ;; https://docs.slack.dev/apis/events-api/#error-handling
+ [:status [:= 200]]
+ [:headers [:map ["Content-Type" [:= "text/plain"]]]]
+ [:body :string]])
+
+(def SlackUrlVerificationEvent
+ "Malli schema for Slack url_verification event"
+ [:map
+ [:type [:= "url_verification"]]
+ [:challenge :string]])
+
+(def SlackFile
+ "Malli schema for a file attached to a Slack message"
+ [:map
+ [:id :string]
+ [:name :string]
+ [:mimetype {:optional true} [:maybe :string]]
+ [:filetype {:optional true} [:maybe :string]]
+ [:url_private :string]
+ [:size :int]])
+
+(def SlackMessageEvent
+ "Base schema for Slack message events"
+ [:map
+ [:type [:= "message"]]
+ [:channel :string]
+ [:user :string]
+ [:ts :string]
+ [:event_ts :string]
+ [:bot_id {:optional true} [:maybe :string]]])
+
+(def SlackMessageFileShareEvent
+ "Schema for file_share message events"
+ [:merge SlackMessageEvent
+ [:map
+ [:subtype [:= "file_share"]]
+ [:channel_type :string]
+ [:files [:sequential SlackFile]]
+ [:text {:optional true} [:maybe :string]]
+ [:thread_ts {:optional true} [:maybe :string]]]])
+
+(def SlackEventCallbackEvent
+ "Malli schema for Slack event_callback event"
+ [:map
+ [:type [:= "event_callback"]]
+ [:event [:map
+ [:type :string]
+ [:event_ts :string]]]])
+
+(defn user-message?
+ "Check if event is from a user (not a bot)."
+ [event]
+ (nil? (:bot_id event)))
+
+(defn bot-message?
+ "Check if event is from a bot."
+ [event]
+ (not (user-message? event)))
+
+(defn dm?
+ "Check if event is a direct message."
+ [event]
+ (= (:channel_type event) "im"))
+
+(defn channel-message?
+ "Check if event is a public channel message."
+ [event]
+ (= (:channel_type event) "channel"))
+
+(defn file-share?
+ "Check if event is a file share."
+ [event]
+ (= (:subtype event) "file_share"))
+
+(defn has-files?
+ "Check if event has files."
+ [event]
+ (boolean (seq (:files event))))
+
+(defn app-mention?
+ "Check if event is an app_mention event."
+ [event]
+ (= (:type event) "app_mention"))
+
+(defn edited-message?
+ "Check if event is an edited message (message_changed subtype or has :edited key)."
+ [event]
+ (or (= (:subtype event) "message_changed")
+ (some? (:edited event))))
+
+(defn message-deleted?
+ "True when event is a message deletion notification."
+ [event]
+ (= (:subtype event) "message_deleted"))
+
+(defn app-mention-with-files?
+ "Check if event is an app_mention with file attachments.
+ These are skipped because file_share events handle file uploads."
+ [event]
+ (and (app-mention? event)
+ (has-files? event)))
+
+(defn user-mention
+ "Convert a Slack user id to the mention syntax used in message text."
+ [user-id]
+ (str "<@" user-id ">"))
+
+(defn mentions-bot?
+ "Check if event @mentions the bot.
+ Some events, like file uploads in channels, don't come through as app_mention."
+ [event bot-user-id]
+ (some-> (:text event)
+ (str/includes? (user-mention bot-user-id))))
+
+(defn dm-or-channel-mention?
+ "Check if event is an dm or channel w/ mention of the bot."
+ [event bot-id]
+ (or
+ (dm? event)
+ (and (channel-message? event)
+ (mentions-bot? event bot-id))))
+
+(defn event->prompt
+ "Prepare the message event as a prompt that can be sent to an agent"
+ [event bot-user-id]
+ (str/replace (:text event) (user-mention bot-user-id) "@Metabot"))
+
+(defn event->reply-context
+ "Extract the necessary context for a reply from the given `event`"
+ [event]
+ {:channel (:channel event)
+ :thread_ts (or (:thread_ts event)
+ (:ts event))})
+
+(defn reaction-added?
+ "Check if event is a reaction_added event."
+ [event]
+ (= "reaction_added" (:type event)))
+
+(defn strip-bot-mention
+ "Remove bot mention prefix from text (e.g., '<@U123> hello' -> 'hello')"
+ [text bot-user-id]
+ (if bot-user-id
+ (str/replace text (re-pattern (str (user-mention bot-user-id) "\\s?")) "")
+ text))
diff --git a/enterprise/backend/src/metabase_enterprise/slackbot/init.clj b/enterprise/backend/src/metabase_enterprise/slackbot/init.clj
new file mode 100644
index 00000000000..f87fe26ee60
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/slackbot/init.clj
@@ -0,0 +1,3 @@
+(ns metabase-enterprise.slackbot.init
+ (:require
+ [metabase-enterprise.slackbot.settings]))
diff --git a/enterprise/backend/src/metabase_enterprise/slackbot/persistence.clj b/enterprise/backend/src/metabase_enterprise/slackbot/persistence.clj
new file mode 100644
index 00000000000..a7fb3b478ee
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/slackbot/persistence.clj
@@ -0,0 +1,69 @@
+(ns metabase-enterprise.slackbot.persistence
+ "Slack-specific persistence: reconstruct conversation history from stored messages."
+ (:require
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private history-message-types
+ "Message types to include in history sent to ai-service."
+ #{"TOOL_CALL" "TOOL_RESULT"})
+
+(defn- normalize-history-message
+ "Keep only ai-service schema fields, keywordize role."
+ [msg]
+ (-> (select-keys msg [:role :content :tool_calls :tool_call_id])
+ (update :role keyword)))
+
+(defn- extract-history-messages
+ "Filter and normalize stored message data for history."
+ [message]
+ (->> (:data message)
+ (filter #(history-message-types (:_type %)))
+ (mapv normalize-history-message)))
+
+(defn message-history
+ "Tool call history for Slack messages. Returns {slack-msg-id -> [messages...]}."
+ [conversation-id slack-msg-ids]
+ (when (seq slack-msg-ids)
+ (->> (t2/select :model/MetabotMessage
+ :conversation_id conversation-id
+ :role "assistant"
+ :deleted_at nil
+ :slack_msg_id [:in slack-msg-ids])
+ (keep (fn [{:keys [slack_msg_id] :as msg}]
+ (when-let [parts (seq (extract-history-messages msg))]
+ [slack_msg_id parts])))
+ (into {}))))
+
+(defn deleted-message-ids
+ "Slack message ids for assistant responses that were soft-deleted."
+ [conversation-id slack-msg-ids]
+ (when (seq slack-msg-ids)
+ (t2/select-fn-set :slack_msg_id
+ :model/MetabotMessage
+ :conversation_id conversation-id
+ :role "assistant"
+ :deleted_at [:not= nil]
+ :slack_msg_id [:in slack-msg-ids])))
+
+(defn response-owner-user-id
+ "Find the Metabase user ID who triggered the assistant response for this Slack channel/message.
+ Returns nil when the message is not tracked."
+ [channel-id slack-msg-id]
+ (t2/select-one-fn :user_id
+ :model/MetabotMessage
+ :channel_id channel-id
+ :slack_msg_id slack-msg-id
+ :role "assistant"))
+
+(defn soft-delete-response!
+ "Mark the stored assistant response for this Slack channel/message as soft-deleted."
+ [channel-id slack-msg-id deleter-user-id]
+ (when (and channel-id slack-msg-id deleter-user-id)
+ (pos? (t2/update! :model/MetabotMessage
+ {:channel_id channel-id
+ :slack_msg_id slack-msg-id
+ :role "assistant"}
+ {:deleted_at (java.time.OffsetDateTime/now)
+ :deleted_by_user_id deleter-user-id}))))
diff --git a/enterprise/backend/src/metabase_enterprise/slackbot/query.clj b/enterprise/backend/src/metabase_enterprise/slackbot/query.clj
new file mode 100644
index 00000000000..69d815e1686
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/slackbot/query.clj
@@ -0,0 +1,279 @@
+(ns metabase-enterprise.slackbot.query
+ "Ad-hoc query execution and visualization for slackbot."
+ (:require
+ [metabase.api.common :as api]
+ [metabase.channel.render.core :as channel.render]
+ [metabase.formatter.core :as formatter]
+ [metabase.lib.core :as lib]
+ [metabase.query-processor :as qp]
+ [metabase.query-processor.middleware.permissions :as qp.perms]
+ [metabase.query-processor.schema :as qp.schema]
+ [metabase.util :as u]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private render-base-height-px
+ "Base height in pixels for rendered PNGs. Width is calculated from aspect ratio."
+ 640)
+
+(def ^:private render-padding-x-px
+ "Horizontal padding in pixels applied to rendered PNGs."
+ 32)
+
+(def ^:private display-aspect-ratios
+ "Non-default aspect ratios (width:height) for display types, derived from dashboard card size defaults.
+ Most display types use the default 2:1 ratio."
+ {:pie 3/2 ; 12:8
+ :waterfall 7/3 ; 14:6
+ :sankey 8/5}) ; 16:10
+
+(def ^:private default-aspect-ratio
+ "Default aspect ratio when display type not found."
+ 2/1)
+
+(defn- render-dimensions
+ "Calculate render dimensions for a display type based on aspect ratios.
+ Keeps height consistent at render-base-height-px and scales width by aspect ratio."
+ [display]
+ (let [aspect-ratio (get display-aspect-ratios (keyword display) default-aspect-ratio)
+ render-width (long (* render-base-height-px aspect-ratio))]
+ {:width render-width
+ :height render-base-height-px}))
+
+(defn- throw-on-failed-query!
+ [results]
+ (when (= :failed (:status results))
+ (throw (ex-info (or (:error results) "Query execution failed")
+ (select-keys results [:error :status])))))
+
+(defn execute-adhoc-query
+ "Execute an ad-hoc MBQL query in the context of Slackbot and return results."
+ [query]
+ (qp/process-query
+ (-> query
+ qp/userland-query-with-default-constraints
+ (update :info merge {:executed-by api/*current-user-id*
+ :context :slackbot}))))
+
+(defn- generate-adhoc-png
+ "Render query results to PNG."
+ [results display]
+ (let [adhoc-card {:display display
+ :visualization_settings {}}
+ {:keys [width]} (render-dimensions display)]
+ (channel.render/render-adhoc-card-to-png
+ adhoc-card
+ results
+ width
+ {:channel.render/padding-x render-padding-x-px})))
+
+;;; ------------------------------------------ Slack Table Blocks ----------------------------------------------------
+;;; See https://docs.slack.dev/reference/block-kit/blocks/table-block/
+
+(def slack-table-row-limit
+ "Maximum data rows for Slack table blocks.
+ Slack allows 100 total rows including header, so we use 99 for data."
+ 99)
+
+(def ^:private slack-table-max-cols
+ "Maximum number of columns Slack table blocks support."
+ 20)
+
+(def ^:dynamic *slack-table-max-cell-length*
+ "Maximum text length per cell. Longer values are truncated with ellipsis."
+ 128)
+
+(def ^:dynamic *slack-table-max-chars*
+ "Undocumented Slack limit: table blocks exceeding 10,000 characters are rejected with
+ `table_character_count_must_not_exceed_10000`. We use 9,500 as a budget for cell text content
+ to leave headroom for any structural overhead Slack may count."
+ 9500)
+
+(def ^:private no-data-table-blocks
+ [{:type "table"
+ :rows [[{:type "raw_text"
+ :text "No data"}]]
+ :column_settings [{:align "left"}]}])
+
+(defn- normalize-column
+ "Normalize column metadata from the wire format for use with formatters and type checks."
+ [col]
+ (lib/normalize ::qp.schema/result-metadata.column col))
+
+(defn- numeric-column?
+ [col]
+ (let [{:keys [base_type effective_type]} (normalize-column col)]
+ (isa? (or effective_type base_type) :type/Number)))
+
+(defn- create-cell-formatters
+ "Create formatter functions for each column using the standard formatter utility."
+ [cols timezone-id viz-settings]
+ (mapv #(formatter/create-formatter timezone-id (normalize-column %) viz-settings) cols))
+
+(defn- format-cell
+ "Format a cell value for Slack table display.
+ Empty values are replaced with \"-\" since Slack requires non-empty text.
+ Long values are truncated with ellipsis."
+ [value formatter]
+ (let [formatted (if (nil? value)
+ ""
+ (str (formatter value)))]
+ (cond
+ (= formatted "") "-"
+ (> (count formatted) *slack-table-max-cell-length*)
+ (str (u/truncate formatted (dec *slack-table-max-cell-length*)) "\u2026")
+ :else formatted)))
+
+(defn- make-column-settings
+ "Generate column settings for Slack table. Numbers are right-aligned."
+ [cols]
+ (mapv (fn [col]
+ (if (numeric-column? col)
+ {:align "right"}
+ {:align "left"}))
+ cols))
+
+(defn- make-table-row
+ "Create a Slack table row from values and formatters."
+ [row formatters]
+ (mapv (fn [value fmt]
+ {:type "raw_text"
+ :text (format-cell value fmt)})
+ row
+ formatters))
+
+(defn- row-char-count
+ "Total character count of all cell text values in a formatted row."
+ [row]
+ (transduce (map (comp count :text)) + row))
+
+(defn- take-rows-within-char-budget
+ "Take as many rows as fit within the character budget."
+ [rows budget]
+ (let [n (->> (map row-char-count rows)
+ (reductions +)
+ (take-while #(<= % budget))
+ count)]
+ (vec (take (max 1 n) rows))))
+
+(defn format-results-as-table-blocks
+ "Format query results as Slack table blocks.
+ Truncates results if they exceed Slack's limits (100 rows, 20 columns, ~10k chars).
+ Cell text is truncated to [[*slack-table-max-cell-length*]] characters.
+ Works for any result shape including single-cell scalars.
+ Filters hidden columns and handles FK remapping.
+ Adds a context block with truncation message if results were truncated."
+ [results]
+ (let [{:keys [cols rows]} (:data results)
+ timezone-id (get results :results_timezone)
+ viz-settings {}
+ {:keys [cols rows]} (channel.render/prepare-table-data cols rows)
+ total-rows (count rows)
+ display-cols (vec (take slack-table-max-cols cols))
+ display-rows (take slack-table-row-limit rows)
+ truncated-rows (mapv #(vec (take slack-table-max-cols %)) display-rows)
+ formatters (create-cell-formatters display-cols timezone-id viz-settings)
+ headers (mapv #(str (or (:display_name %) (:name %) "")) display-cols)
+ header-row (mapv (fn [h] {:type "raw_text" :text (str h)}) headers)
+ data-rows (mapv #(make-table-row % formatters) truncated-rows)
+ data-rows (take-rows-within-char-budget
+ data-rows
+ (- *slack-table-max-chars* (row-char-count header-row)))
+ displayed-rows (count data-rows)
+ all-rows (into [header-row] data-rows)
+ column-settings (make-column-settings display-cols)
+ table-block {:type "table"
+ :rows all-rows
+ :column_settings column-settings}
+ rows-truncated? (> total-rows displayed-rows)]
+ (cond
+ (zero? total-rows)
+ no-data-table-blocks
+
+ rows-truncated?
+ [table-block
+ {:type "context"
+ :elements [{:type "mrkdwn"
+ :text (format "Showing %d of %d rows" displayed-rows total-rows)}]}]
+
+ :else
+ [table-block])))
+
+(def ^:private supported-png-display-types
+ "Display types that should render as PNG images rather than Slack tables."
+ #{:smartscalar :gauge :progress
+ :bar :line :area :combo :row :pie
+ :scatter :boxplot :waterfall :funnel :sankey})
+
+(defn generate-adhoc-output
+ "Generate output for an ad-hoc query based on display type.
+ Returns a map with :type (:table or :image) and :content.
+ Always executes the query directly.
+
+ - Chart display types (bar, line, pie, etc.) render as PNG
+ - Table display (or nil) renders as native Slack table blocks"
+ [query & {:keys [display]
+ :or {display :table}}]
+ (let [display (keyword display)
+ results (execute-adhoc-query query)]
+ (throw-on-failed-query! results)
+ (if (and (contains? supported-png-display-types display)
+ (seq (get-in results [:data :rows])))
+ {:type :image
+ :content (generate-adhoc-png results display)}
+ {:type :table
+ :content (format-results-as-table-blocks results)})))
+
+;;; ------------------------------------------ Saved Card Visualization ----------------------------------------------------
+
+(defn pulse-card-query-results
+ "Execute a query for a saved card, returning results suitable for rendering."
+ {:arglists '([card])}
+ [{query :dataset_query, card-id :id}]
+ ;; Use the same approach as pulse API - this works for accessible cards
+ (binding [qp.perms/*card-id* card-id]
+ (qp/process-query
+ (qp/userland-query
+ (assoc query
+ :middleware {:process-viz-settings? true
+ :js-int-to-string? false})
+ {:executed-by api/*current-user-id*
+ :context :pulse
+ :card-id card-id}))))
+
+(defn- render-saved-card-png
+ "Render a saved card (already fetched from DB) and pre-fetched results to PNG bytes."
+ [card results]
+ (let [{:keys [width]} (render-dimensions (:display card))
+ options {:channel.render/include-title? false
+ :channel.render/padding-x render-padding-x-px
+ :channel.render/padding-y 0}]
+ ;; TODO: should we use the user's timezone for this?
+ (channel.render/render-pulse-card-to-png (channel.render/defaulted-timezone card)
+ card
+ results
+ width
+ options)))
+
+(defn generate-card-output
+ "Generate output for a saved card based on its display type.
+ Returns a map with :type (:table or :image), :content, and :card-name.
+
+ - `table` and display types not supported by static viz render as native Slack table blocks
+ - static viz chart types render as PNG"
+ [card-id]
+ (let [card (t2/select-one :model/Card :id card-id)
+ _ (when-not card
+ (throw (ex-info "Card not found" {:card-id card-id :type :card-not-found})))
+ card-name (:name card)
+ results (pulse-card-query-results card)]
+ (throw-on-failed-query! results)
+ (if (and (-> card :display keyword supported-png-display-types)
+ (seq (get-in results [:data :rows])))
+ {:type :image
+ :content (render-saved-card-png card results)
+ :card-name card-name}
+ {:type :table
+ :content (format-results-as-table-blocks results)
+ :card-name card-name})))
diff --git a/enterprise/backend/src/metabase_enterprise/slackbot/settings.clj b/enterprise/backend/src/metabase_enterprise/slackbot/settings.clj
new file mode 100644
index 00000000000..f35a4bf6236
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/slackbot/settings.clj
@@ -0,0 +1,37 @@
+(ns metabase-enterprise.slackbot.settings
+ (:require
+ [metabase.premium-features.core :refer [defenterprise]]
+ [metabase.settings.core :as setting :refer [defsetting]]
+ [metabase.util.i18n :refer [deferred-tru]]
+ [metabase.util.string :as u.str]))
+
+(defsetting metabot-slack-signing-secret
+ (deferred-tru "Signing secret for verifying requests from the Metabot Slack app")
+ :type :string
+ :visibility :admin
+ :encryption :when-encryption-key-set
+ :feature :metabot-v3
+ :export? false
+ :audit :no-value
+ :getter (fn []
+ (-> (setting/get-value-of-type :string :metabot-slack-signing-secret)
+ (u.str/mask 4))))
+
+(defn unobfuscated-metabot-slack-signing-secret
+ "Get the unobfuscated value of [[metabot-slack-signing-secret]]."
+ []
+ (setting/get-value-of-type :string :metabot-slack-signing-secret))
+
+(defsetting slackbot-event-handler-pool-size
+ (deferred-tru "Maximum number of concurrent Slack event handler threads.")
+ :visibility :internal
+ :type :integer
+ :default 64
+ :setter :none
+ :export? false)
+
+(defenterprise metabot-slack-signing-secret-setting
+ "Returns the Slack signing secret for Metabot."
+ :feature :metabot-v3
+ []
+ (unobfuscated-metabot-slack-signing-secret))
diff --git a/enterprise/backend/src/metabase_enterprise/slackbot/streaming.clj b/enterprise/backend/src/metabase_enterprise/slackbot/streaming.clj
new file mode 100644
index 00000000000..9b23f0076e6
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/slackbot/streaming.clj
@@ -0,0 +1,583 @@
+(ns metabase-enterprise.slackbot.streaming
+ "Streaming AI responses to Slack using Slack's chat streaming API
+ (startStream/appendStream/stopStream)."
+ (:require
+ [clojure.string :as str]
+ [java-time.api :as t]
+ [metabase-enterprise.metabot-v3.agent.core :as agent]
+ [metabase-enterprise.metabot-v3.context :as metabot-v3.context]
+ [metabase-enterprise.metabot-v3.envelope :as metabot-v3.envelope]
+ [metabase-enterprise.metabot-v3.persistence :as metabot-v3.persistence]
+ [metabase-enterprise.metabot-v3.self.core :as self.core]
+ [metabase-enterprise.metabot-v3.util :as metabot-v3.u]
+ [metabase-enterprise.slackbot.channel :as slackbot.channel]
+ [metabase-enterprise.slackbot.client :as slackbot.client]
+ [metabase-enterprise.slackbot.events :as slackbot.events]
+ [metabase-enterprise.slackbot.persistence :as slackbot.persistence]
+ [metabase-enterprise.slackbot.query :as slackbot.query]
+ [metabase.api.common :as api]
+ [metabase.channel.slack :as channel.slack]
+ [metabase.permissions.core :as perms]
+ [metabase.system.core :as system]
+ [metabase.util :as u]
+ [metabase.util.json :as json]
+ [metabase.util.log :as log])
+ (:import
+ (java.util.concurrent
+ Callable
+ ExecutionException
+ ExecutorService
+ Executors
+ Future
+ ThreadFactory)))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private viz-prefetch-pool-size
+ "Maximum number of visualization rendering threads. Limits concurrent query execution
+ during streaming so we don't overwhelm the QP or database connections."
+ 8)
+
+(defonce ^:private ^ExecutorService viz-prefetch-executor
+ (let [counter (atom 0)
+ factory (reify ThreadFactory
+ (newThread [_ r]
+ (doto (Thread. r (str "viz-prefetch-" (swap! counter inc)))
+ (.setDaemon true))))]
+ (Executors/newFixedThreadPool viz-prefetch-pool-size factory)))
+
+(def ^:private slack-writer-await-timeout-ms
+ "Maximum time to wait for the Slack writer agent to flush pending writes."
+ (* 30 1000))
+
+(def ^:private thinking-placeholder
+ "Displayed while waiting for AI response. Excluded from history."
+ "_Thinking..._")
+
+(defn- ignore-msg?
+ "True for messages that should be excluded from chat history."
+ [msg]
+ (and (slackbot.events/bot-message? msg)
+ (or (= (:text msg) thinking-placeholder)
+ (str/blank? (:text msg)))))
+
+(defn- thread->bot-msg-ids
+ "Slack message ids produced by our bot."
+ [thread]
+ (->> (:messages thread)
+ (filter slackbot.events/bot-message?)
+ (keep :ts)
+ set))
+
+(defn- thread->history
+ "Convert a Slack thread to an ai-service history object.
+ For user messages: uses Slack text (respects edits), strips bot mentions.
+ For bot messages: merges tool calls/data from DB with text from Slack.
+ This preserves tool history that Slack doesn't store while respecting edits."
+ [thread bot-user-id conversation-id]
+ (let [bot-msg-ids (thread->bot-msg-ids thread)
+ msg-history (slackbot.persistence/message-history conversation-id bot-msg-ids)
+ deleted-ids (slackbot.persistence/deleted-message-ids conversation-id bot-msg-ids)]
+ (->> (:messages thread)
+ (filter :text)
+ (remove ignore-msg?)
+ (remove (fn [{:keys [ts] :as msg}]
+ (and (slackbot.events/bot-message? msg)
+ (contains? deleted-ids ts))))
+ (mapcat (fn [{:keys [ts text] :as msg}]
+ (if (slackbot.events/bot-message? msg)
+ ;; bot messages: merge on tool call info from db
+ (conj (get msg-history ts []) {:role :assistant :content text})
+ ;; user messages: user slack history instead to respect user edits
+ [{:role :user :content (slackbot.events/strip-bot-mention text bot-user-id)}])))
+ vec)))
+
+(defn- compute-capabilities
+ "Compute capability strings for the current user based on their permissions."
+ []
+ (let [{:keys [can-create-queries can-create-native-queries]}
+ (perms/query-creation-capabilities api/*current-user-id*)]
+ (cond-> []
+ can-create-queries (conj "permission:save_questions")
+ can-create-native-queries (conj "permission:write_sql_queries"))))
+
+(defn- escape-slack-link-text
+ "Escape characters that have structural meaning inside Slack mrkdwn links (`<URL|label>`)."
+ [s]
+ (-> s
+ (str/replace "&" "&amp;")
+ (str/replace "<" "&lt;")
+ (str/replace ">" "&gt;")
+ (str/replace "|" "\u2502")))
+
+(defn- format-viz-title
+ "Build the title text for a visualization message.
+ Combines the title with a link to the query in Metabase."
+ [title link]
+ (let [full-link (when link (str (system/site-url) link))]
+ (cond
+ (and title full-link) (str "\ud83d\udcca <" full-link "|" (escape-slack-link-text title) ">")
+ title title
+ full-link (str "\ud83d\udcca <" full-link "|Open in Metabase>")
+ :else nil)))
+
+(defn- viz-output->blocks
+ "Build blocks for a visualization to be included in the finalized stop-stream message."
+ [{:keys [type content]} filename title link]
+ (let [text (or (format-viz-title title link) "Query results")]
+ (case type
+ :table (let [title-block {:type "section"
+ :text {:type "mrkdwn" :text text}}
+ blocks (into [title-block] content)]
+ blocks)
+ :image (let [{:keys [id]} (channel.slack/upload-file! content (str filename ".png"))
+ blocks [{:type "section"
+ :text {:type "mrkdwn" :text text}}
+ {:type "image"
+ :slack_file {:id id}
+ :alt_text (or title filename "Visualization")}]]
+ blocks))))
+
+(def ^:private tool-friendly-names
+ "Map of tool names to user-friendly gerund descriptions for slackbot profile tools."
+ {"search" "Searching"
+ "construct_notebook_query" "Building query"
+ "list_available_fields" "Finding available fields"
+ "get_field_values" "Getting field values"
+ "static_viz" "Running query"})
+
+(def ^:private min-text-batch-size
+ "Minimum characters to accumulate before considering a flush."
+ 250)
+
+(def ^:private min-flush-interval-ms
+ "Minimum milliseconds between consecutive text flushes to Slack.
+ At Slack's rate limit of ~100 calls/minute, 600ms spacing leaves
+ headroom for tool-update and other non-text API calls."
+ 600)
+
+(defn- make-streaming-ai-request
+ "Run the agent loop for a slackbot conversation, dispatching parts to callbacks.
+
+ Callbacks:
+ - on-text: Called with text content string
+ - on-tool-start: Called with {:id :tool-name} when a tool starts
+ - on-tool-end: Called with {:id :result} when a tool completes
+ - on-data: Called with (index, {:type data-type :value data}) for each data part
+ - req-slack-msg-id: The Slack message ts for the user's incoming message
+ - get-res-slack-msg-id: Function that returns the Slack message ts for the bot's response"
+ [conversation-id prompt thread bot-user-id channel-id extra-history
+ {:keys [on-text on-tool-start on-tool-end on-data req-slack-msg-id get-res-slack-msg-id request-prompt stored-msg-id]}]
+ (let [data-idx (volatile! -1)
+ message (metabot-v3.envelope/user-message prompt)
+ request-message (metabot-v3.envelope/user-message (or request-prompt prompt))
+ capabilities (compute-capabilities)
+ thread-history (thread->history thread bot-user-id conversation-id)
+ history (into (vec thread-history) extra-history)
+ context (metabot-v3.context/create-context
+ {:current_time_with_timezone (str (java.time.OffsetDateTime/now))
+ :capabilities capabilities
+ :slack_channel_id channel-id})
+ messages (conj (vec history) request-message)
+ _ (metabot-v3.persistence/store-message! conversation-id "slackbot" [message]
+ :channel-id channel-id
+ :slack-msg-id req-slack-msg-id)
+ parts-atom (atom [])
+ dispatch-xf (comp
+ (u/tee-xf parts-atom)
+ (keep (fn [part]
+ (case (:type part)
+ :text
+ (when (and on-text (seq (:text part)))
+ (on-text (:text part)))
+
+ :tool-input
+ (when on-tool-start
+ (on-tool-start {:id (:id part)
+ :tool-name (:function part)}))
+
+ :tool-output
+ (when on-tool-end
+ (on-tool-end {:id (:id part)
+ :result (:result part)}))
+
+ :data
+ (when on-data
+ (on-data (vswap! data-idx inc)
+ {:type (:data-type part)
+ :value (:data part)}))
+
+ nil)
+ nil)))]
+ (transduce dispatch-xf (constantly nil) nil
+ (agent/run-agent-loop
+ {:messages messages
+ :state {}
+ :profile-id :slackbot
+ :context context}))
+ (let [lines (into [] (self.core/aisdk-line-xf) @parts-atom)
+ pk (metabot-v3.persistence/store-message!
+ conversation-id "slackbot"
+ (metabot-v3.u/aisdk->messages :assistant lines)
+ :channel-id channel-id
+ :slack-msg-id (when get-res-slack-msg-id (get-res-slack-msg-id))
+ :user-id api/*current-user-id*)]
+ (when stored-msg-id
+ (reset! stored-msg-id pk)))))
+
+(def ^:private viz-data-types
+ "DATA part types that represent visualizations."
+ #{"static_viz" "adhoc_viz"})
+
+(defn- generate-viz-output
+ "Generate visualization output for a data-part. Called by the prefetch executor during streaming."
+ [{:keys [type value]}]
+ (case type
+ "static_viz"
+ (let [card-id (or (:entity_id value)
+ (throw (ex-info "static_viz missing entity_id" {:value value})))]
+ (slackbot.query/generate-card-output card-id))
+ "adhoc_viz"
+ (let [query (or (:query value)
+ (throw (ex-info "adhoc_viz missing query" {:value value})))
+ display (or (some-> (:display value) keyword) :table)]
+ (slackbot.query/generate-adhoc-output query :display display))))
+
+(defn- viz-error-message
+ "Classify a visualization exception into a user-friendly message."
+ [^Exception e]
+ (let [data (ex-data e)]
+ (cond
+ (:permissions-error? data)
+ "I don't have permission to access this data on your behalf."
+
+ (= :card-not-found (:type data))
+ "This saved question no longer exists or has been deleted."
+
+ :else
+ "Query execution failed, please try again.")))
+
+(defn- post-viz-error!
+ "Post a user-friendly error message for a failed visualization."
+ [client channel thread-ts e]
+ (try
+ (slackbot.client/post-message client {:channel channel
+ :thread_ts thread-ts
+ :text (viz-error-message e)})
+ (catch Exception post-e
+ (log/error post-e "Failed to post visualization error"))))
+
+(defn- collect-viz-blocks
+ "Wait for all in-flight visualization futures and return blocks to include in stop-stream.
+ Returns {:blocks [...], :errors [Exception ...]}.
+ For saved cards (static_viz), uses the actual card name as the title."
+ [prefetched-viz]
+ (reduce
+ (fn [{:keys [blocks errors] :as acc} [idx {:keys [^Future future filename title link]}]]
+ (try
+ (let [output (.get future)
+ resolved-title (or (:card-name output) title)
+ filename (or (some-> resolved-title (u/slugify {:max-length 80})) filename)]
+ (assoc acc :blocks (into blocks (viz-output->blocks output filename resolved-title link))))
+ (catch ExecutionException e
+ (let [cause (or (.getCause e) e)]
+ (log/errorf cause "Visualization future %d failed" idx)
+ {:blocks blocks :errors (conj errors cause)}))
+ (catch Exception e
+ (log/errorf e "Visualization future %d failed" idx)
+ {:blocks blocks :errors (conj errors e)})))
+ {:blocks [] :errors []}
+ (sort-by first prefetched-viz)))
+
+(defn- ensure-stream-started!
+ "Ensure the Slack stream has been started, attempting once if not already tried."
+ [client stream-opts stream-attempted? stream-state]
+ (when (compare-and-set! stream-attempted? false true)
+ (when-let [stream (slackbot.client/start-stream client stream-opts)]
+ (reset! stream-state stream))))
+
+(defn- dismiss-thinking-msg!
+ "Delete the 'Thinking...' placeholder message. Idempotent via reset-vals!.
+ Called from agent actions only."
+ [client channel thinking-ts]
+ (let [[ts] (reset-vals! thinking-ts nil)]
+ (when ts
+ (slackbot.client/delete-message client {:channel channel :ts ts}))))
+
+(defn- drain-pending-text!
+ "Drain all accumulated text from pending-text and send to Slack in one call.
+ Called from agent actions only."
+ [client stream-state pending-text thinking-ts]
+ (when-let [{:keys [stream_ts channel]} @stream-state]
+ (let [[text] (reset-vals! pending-text "")]
+ (when (seq text)
+ (dismiss-thinking-msg! client channel thinking-ts)
+ (slackbot.client/append-markdown-text client channel stream_ts text)))))
+
+(defn- viz-metadata
+ "Extract title, filename, and link metadata from a visualization data-part."
+ [{:keys [type value]}]
+ (let [title (:title value)
+ filename (or (some-> title (u/slugify {:max-length 80}))
+ (case type
+ "static_viz" (str "chart-" (:entity_id value))
+ "adhoc_viz" (str "adhoc-" (t/format "yyyy-MM-dd_HH-mm-ss" (t/zoned-date-time)))))
+ link (case type
+ "adhoc_viz" (:link value)
+ "static_viz" (str "/question/" (:entity_id value)))]
+ {:title title :filename filename :link link}))
+
+(defn- make-viz-prefetch-callback
+ "Create an `:on-data` callback that submits visualization rendering work eagerly."
+ [prefetched-viz]
+ (fn [idx content]
+ (when (viz-data-types (:type content))
+ (let [{:keys [title filename link]} (viz-metadata content)
+ task (bound-fn* #(generate-viz-output content))]
+ (swap! prefetched-viz assoc idx
+ {:future (.submit viz-prefetch-executor ^Callable task)
+ :filename filename
+ :title title
+ :link link})))))
+
+(defn- cancel-prefetched-viz!
+ "Cancel any in-flight visualization futures."
+ [prefetched-viz]
+ (run! #(.cancel ^Future (:future %) true) (vals @prefetched-viz)))
+
+(defn- make-streaming-callbacks
+ "Create streaming callback functions and associated control functions.
+ Slack API writes are dispatched to a background agent so the AI stream reader is never
+ blocked by Slack I/O. The agent serializes writes to preserve ordering.
+
+ Text is coalesced via a shared `pending-text` atom: the callback thread appends text there,
+ and each agent action drains everything accumulated since the last write. This means multiple
+ flushes that pile up while a Slack API call is in flight get combined into a single append,
+ preventing the agent queue from falling further behind over time.
+
+ A 'Thinking...' placeholder message can be posted before the stream starts via
+ `:start-with-thinking!`. It is automatically deleted when the first text or tool update
+ is sent to the stream.
+
+ Visualization DATA parts are prefetched: when a `static_viz` or `adhoc_viz` DATA part
+ arrives mid-stream, the full visualization pipeline (query execution + rendering) is
+ submitted to the executor immediately, overlapping with remaining text generation.
+
+ Returns a map with:
+ - `:on-text`, `:on-tool-start`, `:on-tool-end`, `:on-data` — callbacks for [[make-streaming-ai-request]]
+ - `:start-with-thinking!` — posts a 'Thinking...' placeholder in the thread
+ - `:request-flush!` — schedules a drain of pending text to Slack
+ - `:stream-state` — atom holding `{:stream_ts :channel}` once started, nil before
+ - `:slack-writer` — agent; callers should `(await slack-writer)` before stopping the stream
+ - `:prefetched-viz` — atom holding `{index -> {:future Future :filename str :title str :link str}}` for in-flight visualizations"
+ [client {:keys [channel thread-ts team-id user-id]}]
+ (let [stream-state (atom nil)
+ stream-attempted? (atom false)
+ tool-id->name (atom {})
+ ;; Text awaiting write to Slack. Callback thread appends here; agent thread drains.
+ ;; An atom because it's shared across threads (callback thread writes, agent thread reads).
+ pending-text (atom "")
+ ;; Holds the ts of the "Thinking..." placeholder message, or nil if not posted / already dismissed.
+ thinking-ts (atom nil)
+ slack-writer (agent nil
+ :error-mode :continue
+ :error-handler (fn [_ e] (log/warn e "[slackbot] Async Slack write failed")))
+ stream-opts {:channel channel
+ :thread_ts thread-ts
+ :team_id team-id
+ :user_id user-id}
+
+ ;; Nil means "no flush has happened yet", so the first flush should always pass.
+ last-flush-timer (atom nil)
+
+ request-flush! (fn do-request-flush
+ ([] (do-request-flush false))
+ ([force?]
+ (ensure-stream-started! client stream-opts stream-attempted? stream-state)
+ (when @stream-state
+ (when (or force?
+ (nil? @last-flush-timer)
+ (>= (u/since-ms @last-flush-timer) min-flush-interval-ms))
+ (reset! last-flush-timer (u/start-timer))
+ (send-off slack-writer
+ (bound-fn* (fn [_] (drain-pending-text! client stream-state pending-text thinking-ts) nil)))))))
+
+ start-with-thinking! (fn []
+ (let [response (slackbot.client/post-message client {:channel channel
+ :thread_ts thread-ts
+ :text thinking-placeholder})]
+ (when (:ok response)
+ (reset! thinking-ts (:ts response)))))
+
+ on-text (fn [text]
+ (when (seq text)
+ (swap! pending-text str text)
+ (when (>= (count @pending-text) min-text-batch-size)
+ (request-flush!))))
+
+ send-task-update! (fn [id tool-name status]
+ (when-let [{:keys [stream_ts channel]} @stream-state]
+ (send-off slack-writer
+ (fn [_]
+ (drain-pending-text! client stream-state pending-text thinking-ts)
+ (when (= status "in_progress")
+ (dismiss-thinking-msg! client channel thinking-ts))
+ (slackbot.client/append-stream client channel stream_ts
+ [{:type "task_update"
+ :id id
+ :title (tool-friendly-names tool-name "Thinking")
+ :status status}])
+ (when (= status "complete")
+ (slackbot.client/append-markdown-text client channel stream_ts "\n"))
+ nil))))
+
+ on-tool-start (fn [{:keys [id tool-name]}]
+ (request-flush!)
+ (swap! tool-id->name assoc id tool-name)
+ (send-task-update! id tool-name "in_progress"))
+
+ on-tool-end (fn [{:keys [id]}]
+ (send-task-update! id (get @tool-id->name id) "complete")
+ (swap! tool-id->name dissoc id))
+
+ prefetched-viz (atom {})
+ on-data (make-viz-prefetch-callback prefetched-viz)]
+ {:on-text (bound-fn* on-text)
+ :on-tool-start on-tool-start
+ :on-tool-end on-tool-end
+ :on-data on-data
+ :request-flush! (bound-fn* request-flush!)
+ :start-with-thinking! start-with-thinking!
+ :stream-state stream-state
+ :slack-writer slack-writer
+ :prefetched-viz prefetched-viz}))
+
+(defn- slack-thread->conversation-id
+ "Generate deterministic conversation ID from Slack thread identifiers.
+ Same thread always produces the same UUID (v3)."
+ [team-id channel thread-ts]
+ (str (java.util.UUID/nameUUIDFromBytes
+ (.getBytes (str "slack:" team-id ":" channel ":" thread-ts)))))
+
+(defn- feedback-blocks [conversation-id]
+ [{:type "context_actions"
+ :block_id "metabot_feedback"
+ :elements [{:type "feedback_buttons"
+ :action_id "metabot_feedback"
+ :positive_button {:text {:type "plain_text" :text "Good"}
+ :value (json/encode {:conversation_id conversation-id :positive true})}
+ :negative_button {:text {:type "plain_text" :text "Bad"}
+ :value (json/encode {:conversation_id conversation-id :positive false})}}]}])
+
+(defn- prepare-response-context
+ "Fetch thread/auth context shared by DM and channel delivery paths."
+ [client event]
+ (let [channel-id (:channel event)
+ message-ctx (slackbot.events/event->reply-context event)
+ channel (:channel message-ctx)
+ thread-ts (:thread_ts message-ctx)
+ thread-future (future (-> (slackbot.client/fetch-thread client event)
+ (update :messages #(remove (fn [m] (= (:ts m) (:ts event))) %))))
+ auth-future (future (:body (slackbot.client/auth-test client)))
+ auth-info @auth-future
+ thread @thread-future
+ bot-user-id (:user_id auth-info)
+ prompt (slackbot.events/event->prompt event bot-user-id)
+ conversation-id (slack-thread->conversation-id (:team_id auth-info) channel thread-ts)]
+ {:channel-id channel-id
+ :message-ctx message-ctx
+ :channel channel
+ :thread-ts thread-ts
+ :auth-info auth-info
+ :thread thread
+ :bot-user-id bot-user-id
+ :prompt prompt
+ :conversation-id conversation-id}))
+
+(defn- send-dm-response
+ [client event extra-history {:keys [channel-id message-ctx channel thread-ts auth-info thread bot-user-id prompt conversation-id]}]
+ (let [{:keys [on-text on-tool-start on-tool-end on-data
+ request-flush! start-with-thinking! stream-state slack-writer prefetched-viz]}
+ (make-streaming-callbacks client {:channel channel
+ :thread-ts thread-ts
+ :team-id (:team_id auth-info)
+ :user-id (:user event)})]
+ (start-with-thinking!)
+ (try
+ ;; Start stream early so assistant persistence has :slack_msg_id.
+ (request-flush! true)
+ (let [_data-parts (make-streaming-ai-request
+ conversation-id
+ prompt
+ thread
+ bot-user-id
+ channel-id
+ extra-history
+ {:on-text on-text
+ :on-tool-start on-tool-start
+ :on-tool-end on-tool-end
+ :on-data on-data
+ :req-slack-msg-id (:ts event)
+ :get-res-slack-msg-id (fn [] (:stream_ts @stream-state))})]
+ (request-flush! true)
+ (when-not (await-for slack-writer-await-timeout-ms slack-writer)
+ (log/warn "[slackbot] Timed out waiting for slack-writer agent to flush"))
+ (if-let [{:keys [stream_ts channel]} @stream-state]
+ ;; Hold stop-stream until all viz futures finish so text + viz + controls
+ ;; finalize as a single message.
+ (let [{:keys [blocks errors]} (collect-viz-blocks @prefetched-viz)
+ final-blocks (into blocks (feedback-blocks conversation-id))
+ stop-result (slackbot.client/stop-stream client channel stream_ts final-blocks)]
+ (log/debugf "[slackbot] stop-stream finalize attempt channel=%s thread_ts=%s stream_ts=%s block_count=%d block_types=%s"
+ channel thread-ts stream_ts (count final-blocks) (pr-str (mapv :type final-blocks)))
+ (when-not (:ok stop-result)
+ (log/warnf "[slackbot] stop-stream fallback to post-message: %s" (:error stop-result))
+ (let [fallback-result (slackbot.client/post-thread-reply client
+ message-ctx
+ "I generated a response, but Slack could not render it. Please try again.")]
+ (when-not (:ok fallback-result)
+ (log/errorf "[slackbot] fallback post-message failed after stop-stream error: %s" (:error fallback-result)))))
+ (doseq [e errors]
+ (post-viz-error! client channel thread-ts e)))
+ (slackbot.client/post-thread-reply client message-ctx "I wasn't able to generate a response. Please try again.")))
+ (catch Exception e
+ (cancel-prefetched-viz! prefetched-viz)
+ (log/error e "[slackbot] Error in streaming response")
+ (when-not (await-for slack-writer-await-timeout-ms slack-writer)
+ (log/warn "[slackbot] Timed out waiting for slack-writer agent to flush"))
+ (if-let [{:keys [stream_ts channel]} @stream-state]
+ (try
+ (slackbot.client/append-markdown-text client channel stream_ts
+ "\nSomething went wrong. Please try again.")
+ (let [stop-result (slackbot.client/stop-stream client channel stream_ts)]
+ (when-not (:ok stop-result)
+ (log/warnf "[slackbot] stop-stream during error cleanup failed: %s" (:error stop-result))
+ (let [fallback-result (slackbot.client/post-thread-reply client
+ message-ctx
+ "Something went wrong. Please try again.")]
+ (when-not (:ok fallback-result)
+ (log/errorf "[slackbot] cleanup fallback post-message failed: %s" (:error fallback-result))))))
+ (catch Exception stop-e
+ (log/debug stop-e "[slackbot] Failed to stop stream during error cleanup")))
+ (slackbot.client/post-thread-reply client message-ctx "Something went wrong. Please try again."))))))
+
+(defn send-response
+ "Send a metabot response using Slack delivery suited to the conversation type.
+ DMs stream progressively; non-DMs use a visible post/update flow."
+ ([client event]
+ (send-response client event nil))
+ ([client event extra-history]
+ (let [ctx (prepare-response-context client event)]
+ (if (slackbot.events/dm? event)
+ (send-dm-response client event extra-history ctx)
+ (slackbot.channel/send-channel-response client
+ event
+ extra-history
+ ctx
+ {:tool-name->friendly tool-friendly-names
+ :make-streaming-ai-request make-streaming-ai-request
+ :collect-viz-blocks collect-viz-blocks
+ :feedback-blocks feedback-blocks
+ :post-viz-error! post-viz-error!
+ :make-viz-prefetch-callback make-viz-prefetch-callback
+ :cancel-prefetched-viz! cancel-prefetched-viz!})))))
diff --git a/enterprise/backend/src/metabase_enterprise/slackbot/uploads.clj b/enterprise/backend/src/metabase_enterprise/slackbot/uploads.clj
new file mode 100644
index 00000000000..9ff6aa720dd
--- /dev/null
+++ b/enterprise/backend/src/metabase_enterprise/slackbot/uploads.clj
@@ -0,0 +1,124 @@
+(ns metabase-enterprise.slackbot.uploads
+ "CSV upload handling for slackbot."
+ (:require
+ [clojure.java.io :as io]
+ [clojure.string :as str]
+ [metabase-enterprise.slackbot.client :as slackbot.client]
+ [metabase.analytics.core :as analytics]
+ [metabase.channel.settings :as channel.settings]
+ [metabase.upload.core :as upload]
+ [metabase.util.log :as log]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private max-file-size-bytes
+ "Maximum file size for CSV uploads (200MB)"
+ (* 200 1024 1024))
+
+(def ^:private allowed-csv-filetypes
+ "File types that are allowed for CSV uploads"
+ #{"csv" "tsv"})
+
+(defn- csv-file?
+ "Check if a Slack file is a CSV/TSV based on filetype."
+ [{:keys [filetype]}]
+ (contains? allowed-csv-filetypes filetype))
+
+(defn- validate-file-size
+ "Returns nil if valid, error string if too large."
+ [{:keys [name size]}]
+ (when (> size max-file-size-bytes)
+ (format "File '%s' exceeds %dMB size limit" name (quot max-file-size-bytes (* 1024 1024)))))
+
+(defn- upload-settings
+ "Get upload settings map. Returns nil if uploads are not enabled."
+ []
+ (when-let [db (upload/current-database)]
+ {:db_id (:id db)
+ :schema_name (:uploads_schema_name db)
+ :table_prefix (:uploads_table_prefix db)}))
+
+(defn- process-csv-file
+ "Process a single CSV file upload. Returns a result map with either
+ :model-id/:model-name (success) or :error (failure)."
+ [{:keys [db_id schema_name table_prefix]} {:keys [name url_private] :as file}]
+ (if-let [size-error (validate-file-size file)]
+ (do
+ (log/warnf "[slackbot] File exceeds size limit: file=%s error=%s" name size-error)
+ {:error size-error :filename name})
+ (let [temp-file (java.io.File/createTempFile "slack-upload-" (str "-" name))]
+ (try
+ (with-open [^java.io.InputStream stream (slackbot.client/download-file-stream {:token (channel.settings/unobfuscated-slack-app-token)} url_private)]
+ (io/copy stream temp-file)
+ (let [result (upload/create-csv-upload!
+ {:filename name
+ :file temp-file
+ :db-id db_id
+ :schema-name schema_name
+ :table-prefix table_prefix
+ :collection-id nil})]
+ (log/infof "[slackbot] File uploaded: file=%s model_id=%d" name (:id result))
+ (analytics/inc! :metabase-slackbot/file-uploads {:result "success"})
+ {:filename name
+ :model-id (:id result)
+ :model-name (:name result)}))
+ (catch Exception e
+ (log/warnf "[slackbot] File upload failed: file=%s error=%s" name (ex-message e))
+ (analytics/inc! :metabase-slackbot/file-uploads {:result "error"})
+ {:error (ex-message e) :filename name})
+ (finally
+ (io/delete-file temp-file true))))))
+
+(defn- process-file-uploads
+ "Process all files from a Slack event. Returns a map with:
+ :results - seq of individual file results
+ :skipped - seq of non-CSV filenames that were skipped"
+ [settings files]
+ (let [{csv-files true other-files false} (group-by csv-file? files)
+ skipped (mapv :name other-files)]
+ (when (seq skipped)
+ (log/debugf "[slackbot] Skipping non-CSV files: %s" (pr-str skipped)))
+ {:results (mapv (partial process-csv-file settings) csv-files)
+ :skipped skipped}))
+
+(defn- build-upload-system-messages
+ "Build system messages to inject into AI request about uploads."
+ [{:keys [results skipped]}]
+ (let [successes (filter :model-id results)
+ failures (filter :error results)]
+ (cond-> []
+ (seq successes)
+ (conj {:role :assistant
+ :content (format "The following message included 1 or more attached CSV files which are now available as models in Metabase: %s. You can help them query this data."
+ (str/join ", " (map #(format "%s (model ID: %d)"
+ (:filename %)
+ (:model-id %))
+ successes)))})
+
+ (seq failures)
+ (conj {:role :assistant
+ :content (format "The following message included 1 or more attached CSV files. Some file uploads failed: %s. Explain these errors to the user."
+ (str/join ", " (map #(format "%s: %s"
+ (:filename %)
+ (:error %))
+ failures)))})
+
+ (seq skipped)
+ (conj {:role :assistant
+ :content (format "The following message included 1 or more non-CSV files which are not supported: %s. Let them know only CSV files can be uploaded."
+ (str/join ", " skipped))}))))
+
+(defn handle-file-uploads
+ "Handle file uploads if present. Returns nil if no files, otherwise
+ returns upload result map and messages to inject into AI request."
+ [files]
+ (when (seq files)
+ (if-let [{:keys [db_id schema_name] :as settings} (upload-settings)]
+ (let [db (t2/select-one :model/Database :id db_id)]
+ (if-not (upload/can-create-upload? db schema_name)
+ {:error "You don't have permission to upload files. Contact your Metabase administrator."}
+ (let [result (process-file-uploads settings files)]
+ {:upload-result result
+ :system-messages (build-upload-system-messages result)})))
+ {:error "CSV uploads are not enabled. An administrator needs to configure a database for uploads in Admin > Settings > Uploads."})))
diff --git a/enterprise/backend/src/metabase_enterprise/sso/api/interface.clj b/enterprise/backend/src/metabase_enterprise/sso/api/interface.clj
index 7a1f5337d2d..13cde746ee3 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/api/interface.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/api/interface.clj
@@ -10,10 +10,9 @@
preferred-method (case preferred-method
"jwt" :jwt
"saml" :saml
- "slack-connect" :slack-connect
(throw (ex-info "Invalid auth method"
{:preferred-method preferred-method
- :available [:jwt :saml :slack-connect]})))
+ :available [:jwt :saml]})))
(contains? (:params req) :jwt) :jwt
:else :saml)))
@@ -24,8 +23,7 @@
[req]
(let [enabled-count (count (filter identity
[(sso-settings/saml-enabled)
- (sso-settings/jwt-enabled)
- (sso-settings/slack-connect-enabled)]))]
+ (sso-settings/jwt-enabled)]))]
(cond
;; Multiple SSO methods enabled - use preferred_method or selection logic
(> enabled-count 1) (select-sso-backend req)
@@ -33,7 +31,6 @@
;; Single SSO method enabled
(sso-settings/saml-enabled) :saml
(sso-settings/jwt-enabled) :jwt
- (sso-settings/slack-connect-enabled) :slack-connect
;; No SSO method enabled
:else nil)))
diff --git a/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj b/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj
index 3e46c382ce5..d7e41fac01d 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/api/sso.clj
@@ -8,7 +8,7 @@
[metabase-enterprise.sso.integrations.jwt :as jwt]
[metabase-enterprise.sso.integrations.oidc :as oidc-integration]
[metabase-enterprise.sso.integrations.saml]
- [metabase-enterprise.sso.integrations.slack-connect]
+ [metabase-enterprise.sso.integrations.slack-connect :as slack-connect-integration]
[metabase-enterprise.sso.settings :as sso-settings]
[metabase.api.macros :as api.macros]
[metabase.request.core :as request]
@@ -151,6 +151,30 @@
(log/error e "Error handling SLO")
(sso-error-page e :out))))
+;; GET /auth/sso/slack-connect
+;;
+#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
+(api.macros/defendpoint :get "/slack-connect"
+ "Initiate Slack Connect SSO flow."
+ [_route-params _query-params _body request]
+ (try
+ (slack-connect-integration/sso-initiate request)
+ (catch Throwable e
+ (log/error e "Error initiating Slack Connect SSO")
+ (throw e))))
+
+;; GET /auth/sso/slack-connect/callback
+;;
+#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
+(api.macros/defendpoint :get "/slack-connect/callback"
+ "Slack Connect OIDC callback."
+ [_route-params _query-params _body request]
+ (try
+ (slack-connect-integration/sso-callback request)
+ (catch Throwable e
+ (log/error e "Error handling Slack Connect callback")
+ (throw e))))
+
;; Key schema that excludes `/` so /:key does not greedily match /:key/callback
(def ^:private ProviderKey
[:string {:api/regex #"[a-z0-9][a-z0-9-]*"}])
diff --git a/enterprise/backend/src/metabase_enterprise/sso/integrations/slack_connect.clj b/enterprise/backend/src/metabase_enterprise/sso/integrations/slack_connect.clj
index 7e808acbb85..bae040fb78d 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/integrations/slack_connect.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/integrations/slack_connect.clj
@@ -5,14 +5,13 @@
Both the initial authorization request and the callback are handled via GET.
Flow:
- 1. User accesses GET /auth/sso?preferred_method=slack-connect
+ 1. User accesses GET /auth/sso/slack-connect
2. Metabase redirects to Slack authorization endpoint
3. User authenticates with Slack
- 4. Slack redirects back to GET /auth/sso?code=...&state=...
+ 4. Slack redirects back to GET /auth/sso/slack-connect/callback?code=...&state=...
5. Metabase exchanges code for tokens and creates session"
(:require
[java-time.api :as t]
- [metabase-enterprise.sso.api.interface :as sso.i]
[metabase-enterprise.sso.integrations.sso-utils :as sso-utils]
[metabase-enterprise.sso.settings :as sso-settings]
[metabase.api.common :as api]
@@ -30,49 +29,53 @@
(defn- slack-redirect-uri
"Generate the redirect URI for Slack OIDC callback."
[]
- (str (system/site-url) "/auth/sso"))
+ (str (system/site-url) "/auth/sso/slack-connect/callback"))
-(defmethod sso.i/sso-get :slack-connect
- [{{:keys [code state redirect]} :params
- :as request}]
- ;; Check premium feature is available
+(defn- check-slack-connect-prereqs!
+ "Check that Slack Connect is available and enabled. Throws on failure."
+ []
(premium-features/assert-has-feature :sso-slack (tru "Slack Connect authentication"))
-
(when-not (sso-settings/slack-connect-enabled)
(throw (ex-info (tru "Slack Connect is not enabled")
- {:status-code 400})))
+ {:status-code 400}))))
- (cond
- ;; Case 1: Initial request (no code) - start auth flow
- (not code)
- (let [_ (when (and (= "link-only" (sso-settings/slack-connect-authentication-mode))
- (not api/*current-user-id*))
- (throw (ex-info (tru "Account linking requires an authenticated session")
- {:status-code 401})))
- redirect-url (if redirect
- (sso-utils/check-sso-redirect redirect)
- "/")
- auth-result (auth-identity/authenticate :provider/slack-connect
- (assoc request
- :authenticated-user api/*current-user*
- :redirect-uri (slack-redirect-uri)
- :final-redirect redirect-url))]
+(defn sso-initiate
+ "Initiate Slack Connect SSO flow. Redirects to Slack authorization endpoint."
+ [request]
+ (check-slack-connect-prereqs!)
+ (let [{:keys [redirect]} (:params request)
+ _ (when (and (= "link-only" (sso-settings/slack-connect-authentication-mode))
+ (not api/*current-user-id*))
+ (throw (ex-info (tru "Account linking requires an authenticated session")
+ {:status-code 401})))
+ redirect-url (if redirect
+ (sso-utils/check-sso-redirect redirect)
+ "/")
+ auth-result (auth-identity/authenticate :provider/slack-connect
+ (assoc request
+ :authenticated-user api/*current-user*
+ :redirect-uri (slack-redirect-uri)
+ :final-redirect redirect-url))]
+ (cond
+ (= :redirect (:success? auth-result))
+ (sso/wrap-oidc-redirect auth-result
+ request
+ :slack-connect
+ redirect-url
+ {:browser-id (:browser-id request)})
+ :else
+ (throw (ex-info (or (:message auth-result) (tru "Failed to initiate Slack authentication"))
+ {:status-code 500})))))
- (cond
- (= :redirect (:success? auth-result))
- ;; Use encrypted cookie for state storage
- (sso/wrap-oidc-redirect auth-result
- request
- :slack-connect
- redirect-url
- {:browser-id (:browser-id request)})
- :else
- (throw (ex-info (or (:message auth-result) (tru "Failed to initiate Slack authentication"))
- {:status-code 500}))))
-
- ;; Case 2: Callback with code - complete authentication
- ;; State validation happens inside login! via the OIDC provider
- code
+(defn sso-callback
+ "Handle Slack Connect OIDC callback with authorization code."
+ [request]
+ (check-slack-connect-prereqs!)
+ (let [{:keys [code state]} (:params request)
+ oidc-state-cookie (get-in request [:cookies "metabase.OIDC_STATE" :value])]
+ (when-not oidc-state-cookie
+ (log/warnf "Slack Connect callback missing OIDC state cookie. Request cookies: %s"
+ (keys (:cookies request))))
(let [login-result (auth-identity/login! :provider/slack-connect
(assoc request
:authenticated-user api/*current-user*
@@ -81,14 +84,12 @@
:oidc-provider :slack-connect
:redirect-uri (slack-redirect-uri)
:device-info (request/device-info request)))]
-
(cond
(:success? login-result)
(let [final-redirect (or (:redirect-url login-result) "/")
base-response (-> (response/redirect final-redirect)
(sso/clear-oidc-state-cookie))]
(log/infof "Slack authentication successful for user %s" (get-in login-result [:user :email]))
- ;; In link-only mode, there's no session to set - just return the redirect
(if-let [session (:session login-result)]
(request/set-session-cookies request
base-response
@@ -96,16 +97,7 @@
(t/zoned-date-time (t/zone-id "GMT")))
base-response))
- ;; Login failed (includes state validation failures)
:else
(let [error-msg (or (:message login-result) (tru "Slack authentication failed"))]
(log/errorf "Slack authentication failed: %s" error-msg)
(throw (ex-info error-msg {:status-code 401})))))))
-
-;; OIDC only uses GET requests, so POST should not be used.
-;; Return 405 Method Not Allowed.
-(defmethod sso.i/sso-post :slack-connect
- [_request]
- {:status 405
- :headers {"Allow" "GET"}
- :body (tru "POST not supported for OIDC authentication. Use GET instead.")})
diff --git a/enterprise/backend/src/metabase_enterprise/sso/providers/slack_connect.clj b/enterprise/backend/src/metabase_enterprise/sso/providers/slack_connect.clj
index 47c87463b6d..0ffac188ec6 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/providers/slack_connect.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/providers/slack_connect.clj
@@ -64,7 +64,7 @@
(when (and (sso-settings/slack-connect-client-id)
(sso-settings/slack-connect-client-secret))
{:client-id (sso-settings/slack-connect-client-id)
- :client-secret (sso-settings/slack-connect-client-secret)
+ :client-secret (sso-settings/unobfuscated-slack-connect-client-secret)
:issuer-uri slack-issuer-uri
:scopes ["openid" "profile" "email"]
:redirect-uri (get request :redirect-uri)}))
diff --git a/enterprise/backend/src/metabase_enterprise/sso/settings.clj b/enterprise/backend/src/metabase_enterprise/sso/settings.clj
index 9a608980211..4dd2efd224d 100644
--- a/enterprise/backend/src/metabase_enterprise/sso/settings.clj
+++ b/enterprise/backend/src/metabase_enterprise/sso/settings.clj
@@ -13,6 +13,7 @@
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]
+ [metabase.util.string :as u.str]
[saml20-clj.core :as saml]))
(set! *warn-on-reflection* true)
@@ -361,9 +362,16 @@ using, this usually looks like `https://your-org-name.example.com` or `https://e
(deferred-tru "Client Secret for your Slack app")
:encryption :when-encryption-key-set
:export? false
- :sensitive? true
:feature :sso-slack
- :audit :no-value)
+ :audit :no-value
+ :getter (fn []
+ (-> (setting/get-value-of-type :string :slack-connect-client-secret)
+ (u.str/mask 4))))
+
+(defn unobfuscated-slack-connect-client-secret
+ "Get the unobfuscated value of [[slack-connect-client-secret]]."
+ []
+ (setting/get-value-of-type :string :slack-connect-client-secret))
(def slack-connect-auth-mode-sso
"Authentication mode for full SSO login."
@@ -374,10 +382,10 @@ using, this usually looks like `https://your-org-name.example.com` or `https://e
"link-only")
(defsetting slack-connect-authentication-mode
- (deferred-tru "Controls whether Slack can be used for SSO login or just account linking. Valid values: \"sso\" (default) or \"link-only\"")
+ (deferred-tru "Controls whether Slack can be used for SSO login or just account linking. Valid values: \"sso\" or \"link-only\" (default)")
:type :string
:export? false
- :default slack-connect-auth-mode-sso
+ :default slack-connect-auth-mode-link-only
:feature :sso-slack
:audit :getter
:encryption :no
@@ -504,8 +512,8 @@ using, this usually looks like `https://your-org-name.example.com` or `https://e
:doc "When set to `true`, users who log in via OIDC will automatically get a Metabase account if they don't have one, or get their existing account reactivated. When set to `false`, only users with active Metabase accounts can log in via OIDC.")
(defsetting other-sso-enabled?
- "Are we using an SSO integration other than LDAP or Google Auth or ODIC? These integrations use the `/auth/sso` endpoint for
- authorization rather than the normal login form or Google Auth button."
+ "Are we using an SSO integration other than LDAP or Google Auth or OIDC? These integrations use the `/auth/sso` endpoint
+ (SAML/JWT) or `/auth/sso/slack-connect` (Slack Connect) for authorization rather than the normal login form or Google Auth button."
:visibility :public
:setter :none
- :getter (fn [] (or (saml-enabled) (jwt-enabled) (slack-connect-enabled))))
+ :getter (fn [] (or (saml-enabled) (jwt-enabled))))
diff --git a/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/setting_test.clj b/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/setting_test.clj
index 4e4717ac75b..694d5d69e03 100644
--- a/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/setting_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/advanced_permissions/api/setting_test.clj
@@ -75,8 +75,7 @@
slack/channel-exists? (constantly true)
slack/refresh-channels-and-usernames! (constantly true)
slack/refresh-channels-and-usernames-when-needed! (constantly true)]
- (mt/with-temporary-setting-values [slack-app-token nil
- slack-token "fake-token"]
+ (mt/with-temporary-setting-values [slack-app-token nil]
(mt/user-http-request user :put status "slack/settings" {:slack-app-token "fake-token"})))))
(get-manifest [user status]
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/markdown_link_buffer_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/markdown_link_buffer_test.clj
index 09e76122a4e..3b42c7ef954 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/markdown_link_buffer_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/markdown_link_buffer_test.clj
@@ -1,7 +1,8 @@
(ns metabase-enterprise.metabot-v3.agent.markdown-link-buffer-test
(:require
[clojure.test :refer :all]
- [metabase-enterprise.metabot-v3.agent.markdown-link-buffer :as mlb]))
+ [metabase-enterprise.metabot-v3.agent.markdown-link-buffer :as mlb]
+ [metabase.system.core :as system]))
(defn- process
"Process text through a fresh state with given queries/charts context.
@@ -140,6 +141,46 @@
(is (= "[Model](/model/1) and [Google](https://google.com)" output))
(is (= "" flushed)))))
+;;; Slack link resolution tests
+
+(deftest resolve-slack-link-test
+ (testing "resolves Slack-format metabase:// links"
+ (with-redefs [system/site-url (constantly "https://metabase.example.com")]
+ (let [[output flushed] (process "<metabase://model/123|My Model>")]
+ (is (= "<https://metabase.example.com/model/123|My Model>" output))
+ (is (= "" flushed)))))
+
+ (testing "resolves Slack link without link text"
+ (with-redefs [system/site-url (constantly "https://metabase.example.com")]
+ (let [[output flushed] (process "<metabase://dashboard/456>")]
+ (is (= "<https://metabase.example.com/dashboard/456>" output))
+ (is (= "" flushed)))))
+
+ (testing "falls back to link text for unresolvable Slack link"
+ (let [[output flushed] (process "<metabase://query/unknown|My Query>")]
+ (is (= "My Query" output))
+ (is (= "" flushed)))))
+
+(deftest slack-link-buffering-test
+ (testing "buffers incomplete Slack-format links"
+ (with-redefs [system/site-url (constantly "https://metabase.example.com")]
+ (let [[outputs flushed] (process-chunks ["Check <metabase://mod" "el/123|My Model>"])]
+ (is (= "Check " (first outputs)))
+ (is (re-find #"metabase\.example\.com/model/123" (second outputs)))
+ (is (= "" flushed)))))
+
+ (testing "does NOT buffer regular < characters"
+ (let [[output flushed] (process "x < y and z > w")]
+ (is (= "x < y and z > w" output))
+ (is (= "" flushed)))))
+
+(deftest mixed-link-formats-test
+ (testing "resolves both markdown and Slack-format links in same text"
+ (with-redefs [system/site-url (constantly "https://metabase.example.com")]
+ (let [[output flushed] (process "[Model](/model/1) and <metabase://dashboard/2|Dashboard>")]
+ (is (= "[Model](/model/1) and <https://metabase.example.com/dashboard/2|Dashboard>" output))
+ (is (= "" flushed))))))
+
;;; with-context tests
(deftest with-context-test
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/profiles_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/profiles_test.clj
index 3020c9ca07c..4345bbda0ce 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/profiles_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/profiles_test.clj
@@ -66,11 +66,25 @@
(is (contains? (tool-names profile) "search"))
(is (contains? (tool-names profile) "construct_notebook_query"))))
+ (testing "retrieves slackbot profile"
+ (let [profile (profiles/get-profile :slackbot)]
+ (is (some? profile))
+ (is (= :slackbot (:name profile)))
+ (is (= "openrouter/anthropic/claude-haiku-4-5" (:model profile)))
+ (is (= 10 (:max-iterations profile)))
+ (is (= 0.3 (:temperature profile)))
+ (is (vector? (:tools profile)))
+ (is (contains? (tool-names profile) "search"))
+ (is (contains? (tool-names profile) "construct_notebook_query"))
+ (is (contains? (tool-names profile) "static_viz"))
+ (is (contains? (tool-names profile) "create_alert"))
+ (is (contains? (tool-names profile) "create_dashboard_subscription"))))
+
(testing "returns nil for unknown profile"
(is (nil? (profiles/get-profile :unknown-profile))))
(testing "all profiles have required keys"
- (doseq [profile-id [:embedding_next :internal :transforms_codegen :sql :nlq]]
+ (doseq [profile-id [:embedding_next :internal :transforms_codegen :sql :nlq :slackbot]]
(let [profile (profiles/get-profile profile-id)]
(is (= profile-id (:name profile)))
(is (contains? profile :model))
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/streaming_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/streaming_test.clj
index be5f5a41212..402372883ee 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/streaming_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/streaming_test.clj
@@ -130,13 +130,43 @@
part (streaming/transform-suggestion-part suggestion)]
(is (= suggestion (:data part))))))
+(deftest adhoc-viz-part-test
+ (testing "creates adhoc_viz data part with correct structure"
+ (let [value {:query {:database 1 :type :query :query {:source-table 1}}
+ :link "/question#abc123"
+ :title "My Query"
+ :display "bar"}
+ part (streaming/adhoc-viz-part value)]
+ (is (= :data (:type part)))
+ (is (= "adhoc_viz" (:data-type part)))
+ (is (= 1 (:version part)))
+ (is (= value (:data part)))))
+
+ (testing "handles minimal value without title/display"
+ (let [value {:query {:database 1} :link "/question#xyz"}
+ part (streaming/adhoc-viz-part value)]
+ (is (= :data (:type part)))
+ (is (= "adhoc_viz" (:data-type part)))
+ (is (= value (:data part))))))
+
+(deftest static-viz-part-test
+ (testing "creates static_viz data part with correct structure"
+ (let [value {:entity_id 42}
+ part (streaming/static-viz-part value)]
+ (is (= :data (:type part)))
+ (is (= "static_viz" (:data-type part)))
+ (is (= 1 (:version part)))
+ (is (= value (:data part))))))
+
(deftest data-type-constants-test
(testing "data type constants are defined correctly"
(is (= "navigate_to" streaming/navigate-to-type))
(is (= "state" streaming/state-type))
(is (= "todo_list" streaming/todo-list-type))
(is (= "code_edit" streaming/code-edit-type))
- (is (= "transform_suggestion" streaming/transform-suggestion-type))))
+ (is (= "transform_suggestion" streaming/transform-suggestion-type))
+ (is (= "adhoc_viz" streaming/adhoc-viz-type))
+ (is (= "static_viz" streaming/static-viz-type))))
;;; Transducer Tests
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/tools/slackbot_query_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/tools/slackbot_query_test.clj
new file mode 100644
index 00000000000..69ebdaaf77a
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/tools/slackbot_query_test.clj
@@ -0,0 +1,42 @@
+(ns metabase-enterprise.metabot-v3.agent.tools.slackbot-query-test
+ "Tests for slackbot query tool schema and prompt content."
+ (:require
+ [clojure.java.io :as io]
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [malli.json-schema :as mjs]
+ [metabase-enterprise.metabot-v3.agent.tools.slackbot-query]))
+
+;;; ---------------------------------------- prompt content tests ---------------------------------------------------
+
+(deftest slackbot-prompt-display-guidance-test
+ (testing "slackbot prompt contains display-related guidance"
+ (let [prompt (slurp (io/resource "metabot/prompts/system/slackbot.selmer"))]
+ (is (str/includes? prompt "Set `display` explicitly for Slackbot charts."))
+ (is (str/includes? prompt "Do not omit `display` for chart or graph requests.")))))
+
+(deftest slackbot-prompt-narration-guidance-test
+ (testing "slackbot prompt contains updated narration guidance"
+ (let [prompt (slurp (io/resource "metabot/prompts/system/slackbot.selmer"))]
+ (is (str/includes? prompt "Default to no pre-tool text at all."))
+ (is (str/includes? prompt "Minimal Commentary for Query/Chart Requests")))))
+
+;;; ---------------------------------------- schema tests -----------------------------------------------------------
+
+(deftest display-field-has-description-test
+ (testing "display field in slackbot-query-schema has a description in JSON Schema"
+ (let [schema @#'metabase-enterprise.metabot-v3.agent.tools.slackbot-query/slackbot-query-schema
+ json-schema (mjs/transform schema)
+ display-prop (get-in json-schema [:properties :display])]
+ (is (some? (:description display-prop))
+ "display field should have a :description in the JSON schema")
+ (is (str/includes? (:description display-prop) "Visualization type")
+ "description should mention 'Visualization type'"))))
+
+(deftest display-field-is-optional-test
+ (testing "display field is not in the required list"
+ (let [schema @#'metabase-enterprise.metabot-v3.agent.tools.slackbot-query/slackbot-query-schema
+ json-schema (mjs/transform schema)
+ required (set (:required json-schema))]
+ (is (not (contains? required "display"))
+ "display should not be required"))))
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/tools/subscriptions_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/tools/subscriptions_test.clj
index 36b87b47a13..378405a30ec 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/tools/subscriptions_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/tools/subscriptions_test.clj
@@ -4,6 +4,7 @@
[clojure.test :refer :all]
[metabase-enterprise.metabot-v3.agent.tools.subscriptions :as agent-subscriptions]
[metabase-enterprise.metabot-v3.tools.create-dashboard-subscription :as subscription-tools]
+ [metabase.channel.settings :as channel.settings]
[metabase.test :as mt]))
;;; ------------------------------------------ schema / metadata tests -----------------------------------------------
@@ -22,14 +23,19 @@
(deftest create-dashboard-subscription-happy-path-test
(testing "valid dashboard, valid user email, valid schedule → success"
- (mt/with-current-user (mt/user->id :crowberto)
- (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}]
- (let [email (:email (mt/fetch-user :crowberto))
- result (agent-subscriptions/create-dashboard-subscription-tool
- {:dashboard_id dash-id
- :email email
- :schedule {:frequency "daily" :hour 9}})]
- (is (= "success" (:output result))))))))
+ (let [captured-args (atom nil)]
+ (with-redefs [subscription-tools/create-dashboard-subscription
+ (fn [args] (reset! captured-args args) {:output "success"})]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}]
+ (let [email (:email (mt/fetch-user :crowberto))
+ result (agent-subscriptions/create-dashboard-subscription-tool
+ {:dashboard_id dash-id
+ :email email
+ :schedule {:frequency "daily" :hour 9}})]
+ (is (= "success" (:output result)))
+ (is (= email (:email @captured-args)))
+ (is (= dash-id (:dashboard-id @captured-args))))))))))
(deftest create-dashboard-subscription-invalid-dashboard-id-test
(testing "non-integer dashboard_id → 'invalid dashboard_id'"
@@ -51,24 +57,32 @@
(deftest create-dashboard-subscription-unknown-email-test
(testing "unknown email → 'no user with this email found'"
- (mt/with-current-user (mt/user->id :crowberto)
- (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}]
- (let [result (agent-subscriptions/create-dashboard-subscription-tool
- {:dashboard_id dash-id
- :schedule {:frequency "daily" :hour 9}})]
- (is (= "no user with this email found" (:output result))))))))
+ (with-redefs [subscription-tools/create-dashboard-subscription
+ (fn [{:keys [email]}]
+ (if (= email "[email protected]")
+ {:output "no user with this email found"}
+ {:output "success"}))]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}]
+ (let [result (agent-subscriptions/create-dashboard-subscription-tool
+ {:dashboard_id dash-id
+ :schedule {:frequency "daily" :hour 9}})]
+ (is (= "no user with this email found" (:output result)))))))))
(deftest create-dashboard-subscription-nonexistent-dashboard-test
(testing "nonexistent dashboard → 404 or error message"
- (mt/with-current-user (mt/user->id :crowberto)
- (let [result (agent-subscriptions/create-dashboard-subscription-tool
- {:dashboard_id 999999
- :email (:email (mt/fetch-user :crowberto))
- :schedule {:frequency "daily" :hour 9}})]
- ;; The underlying tool will either return "no dashboard..." or the
- ;; wrapper catches the 404 exception
- (is (string? (:output result)))))))
+ (with-redefs [subscription-tools/create-dashboard-subscription
+ (fn [{:keys [dashboard-id]}]
+ (if (= dashboard-id 999999)
+ {:output "no dashboard with this dashboard_id found"}
+ {:output "success"}))]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [result (agent-subscriptions/create-dashboard-subscription-tool
+ {:dashboard_id 999999
+ :email (:email (mt/fetch-user :crowberto))
+ :schedule {:frequency "daily" :hour 9}})]
+ (is (= "no dashboard with this dashboard_id found" (:output result))))))))
(deftest create-dashboard-subscription-schedule-keywords-test
(testing "schedule keywords are converted from snake_case to kebab-case"
@@ -91,3 +105,85 @@
;; snake_case keys should be absent
(is (nil? (:day_of_week schedule)))
(is (nil? (:day_of_month schedule))))))))
+
+;;; ---------------------------------------- Slack integration tests --------------------------------------------------
+
+(deftest create-dashboard-subscription-slack-happy-path-test
+ (testing "valid dashboard, Slack channel, daily schedule → success"
+ (mt/with-model-cleanup [:model/Pulse]
+ (with-redefs [channel.settings/slack-configured? (constantly true)
+ channel.settings/slack-cached-channels-and-usernames
+ (constantly {:channels [{:display-name "#data-team" :name "data-team" :id "C123"}]})]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}
+ :model/Card {card-id :id} {}
+ :model/DashboardCard _ {:dashboard_id dash-id
+ :card_id card-id
+ :row 0
+ :col 0}]
+ (let [result (agent-subscriptions/create-dashboard-subscription-tool
+ {:dashboard_id dash-id
+ :slack_channel "data-team"
+ :schedule {:frequency "daily" :hour 9}})]
+ (is (= {:output "success"} result)))))))))
+
+(deftest create-dashboard-subscription-slack-monthly-schedule-test
+ (testing "Slack subscription with monthly schedule → success"
+ (mt/with-model-cleanup [:model/Pulse]
+ (with-redefs [channel.settings/slack-configured? (constantly true)
+ channel.settings/slack-cached-channels-and-usernames
+ (constantly {:channels [{:display-name "#data-team" :name "data-team" :id "C123"}]})]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}
+ :model/Card {card-id :id} {}
+ :model/DashboardCard _ {:dashboard_id dash-id
+ :card_id card-id
+ :row 0
+ :col 0}]
+ (let [result (agent-subscriptions/create-dashboard-subscription-tool
+ {:dashboard_id dash-id
+ :slack_channel "data-team"
+ :schedule {:frequency "monthly"
+ :day_of_month "last-sunday"
+ :hour 7}})]
+ (is (= {:output "success"} result)))))))))
+
+(deftest create-dashboard-subscription-slack-required-test
+ (testing "empty slack_channel → error"
+ (with-redefs [channel.settings/slack-configured? (constantly true)]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}]
+ (let [result (agent-subscriptions/create-dashboard-subscription-tool
+ {:dashboard_id dash-id
+ :slack_channel ""
+ :schedule {:frequency "daily" :hour 9}})]
+ (is (= {:error "slack_channel is required"} result))))))))
+
+(deftest create-dashboard-subscription-slack-not-configured-test
+ (testing "Slack not configured → error"
+ (with-redefs [channel.settings/slack-configured? (constantly false)]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}]
+ (let [result (agent-subscriptions/create-dashboard-subscription-tool
+ {:dashboard_id dash-id
+ :slack_channel "data-team"
+ :schedule {:frequency "daily" :hour 9}})]
+ (is (= {:error "slack is not configured. Ask an admin to connect slack in Metabase settings."}
+ result))))))))
+
+(deftest create-dashboard-subscription-slack-channel-not-found-test
+ (testing "nonexistent Slack channel → error"
+ (with-redefs [channel.settings/slack-configured? (constantly true)
+ channel.settings/slack-cached-channels-and-usernames (constantly {:channels []})]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}
+ :model/Card {card-id :id} {}
+ :model/DashboardCard _ {:dashboard_id dash-id
+ :card_id card-id
+ :row 0
+ :col 0}]
+ (let [result (agent-subscriptions/create-dashboard-subscription-tool
+ {:dashboard_id dash-id
+ :slack_channel "no-such-channel"
+ :schedule {:frequency "daily" :hour 9}})]
+ (is (= {:error "no slack channel found with this name"} result))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/tools_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/tools_test.clj
index 7f1dd37c3d0..c014dc9e900 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/tools_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/agent/tools_test.clj
@@ -113,6 +113,17 @@
(is (contains? tools "document_construct_model_chart"))
(is (contains? tools "document_construct_sql_chart"))))
+ (testing "returns tools for slackbot profile"
+ (let [tools (profiles/get-tools-for-profile :slackbot #{})]
+ (is (map? tools))
+ (is (contains? tools "search"))
+ (is (contains? tools "construct_notebook_query"))
+ (is (contains? tools "list_available_fields"))
+ (is (contains? tools "get_field_values"))
+ (is (contains? tools "static_viz"))
+ (is (contains? tools "create_alert"))
+ (is (contains? tools "create_dashboard_subscription"))))
+
(testing "returns empty map for unknown profile"
(let [tools (profiles/get-tools-for-profile :unknown-profile #{})]
(is (empty? tools))))
@@ -187,7 +198,10 @@
(is (contains? @#'agent-tools/state-dependent-tools "create_autogenerated_dashboard"))
(is (contains? @#'agent-tools/state-dependent-tools "document_schema_collect"))
(is (contains? @#'agent-tools/state-dependent-tools "document_construct_sql_chart"))
- (is (contains? @#'agent-tools/state-dependent-tools "document_construct_model_chart"))))
+ (is (contains? @#'agent-tools/state-dependent-tools "document_construct_model_chart"))
+ (is (contains? @#'agent-tools/state-dependent-tools "create_alert"))
+ (is (contains? @#'agent-tools/state-dependent-tools "create_dashboard_subscription"))
+ (is (contains? @#'agent-tools/state-dependent-tools "static_viz"))))
(defn ^{:doc "Test tool"
:schema [:=> [:cat [:map]] :any]
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/api_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/api_test.clj
index af88edfb216..5383166f7b1 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot_v3/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/api_test.clj
@@ -344,6 +344,22 @@
(mt/with-temporary-setting-values [premium-embedding-token nil]
(mt/user-http-request :rasta :post 400 "ee/metabot-v3/feedback" {:foo "bar"})))))))
+(deftest endpoints-require-authentication-test
+ (mt/with-premium-features #{:metabot-v3}
+ (testing "Metabot v3 endpoints require authentication"
+ (testing "/agent-streaming"
+ (is (= "Unauthenticated"
+ (mt/client :post 401 "ee/metabot-v3/agent-streaming"
+ {:message "Test"
+ :context {}
+ :conversation_id (str (random-uuid))
+ :history []
+ :state {}}))))
+ (testing "/feedback"
+ (is (= "Unauthenticated"
+ (mt/client :post 401 "ee/metabot-v3/feedback"
+ {:feedback {}})))))))
+
(deftest metabot-enabled-setting-test
(mt/with-premium-features #{:metabot-v3}
(let [mock-response (client-test/make-mock-text-stream-response
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/client_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/client_test.clj
index 78bc120516e..904b6173b2d 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot_v3/client_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/client_test.clj
@@ -109,6 +109,60 @@
{:_type :FINISH_MESSAGE :finish_reason "error"}]
(metabot-v3.util/aisdk->messages :assistant (str/split-lines body))))))))))
+(deftest streaming-request-with-callback-test
+ (mt/with-premium-features #{:metabot-v3}
+ (let [input ["a1" "a2" "a3"]
+ mock-response (make-mock-text-stream-response input {"some-model" {:prompt 8 :completion 2}})
+ req {:context {:some "context"}
+ :message {:role :user :content "stuff"}
+ :history []
+ :profile-id "test-profile"
+ :conversation-id (str (random-uuid))
+ :session-id "test-session"
+ :state {:some "state"}}]
+ (testing "collects and returns all lines"
+ (mt/with-dynamic-fn-redefs [http/post (mock-post! mock-response)]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [lines (metabot-v3.client/streaming-request-with-callback req)]
+ (is (sequential? lines))
+ (is (pos? (count lines)))
+ (is (=? [{:_type :TEXT :content "a1a2a3"}
+ {:_type :FINISH_MESSAGE :finish_reason "stop"}]
+ (metabot-v3.util/aisdk->messages :assistant lines)))))))
+ (testing "invokes on-line callback for each line"
+ (mt/with-dynamic-fn-redefs [http/post (mock-post! mock-response)]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [callback-lines (atom [])
+ lines (metabot-v3.client/streaming-request-with-callback
+ (assoc req :on-line #(swap! callback-lines conj %)))]
+ (is (= lines @callback-lines))))))
+ (testing "handles stream errors gracefully"
+ (mt/with-dynamic-fn-redefs [http/post (mock-post! mock-response {:delay-ms 10})]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [error-lines (atom [])
+ lines (metabot-v3.client/streaming-request-with-callback
+ (assoc req :on-line #(swap! error-lines conj %)))]
+ (is (sequential? lines))
+ (is (= lines @error-lines)))))))))
+
+(deftest streaming-request-with-callback-on-complete-test
+ (mt/with-premium-features #{:metabot-v3}
+ (let [mock-response (make-mock-text-stream-response ["a" "b"] {"m" {:prompt 1 :completion 1}})
+ req {:context {} :message {:role :user :content "x"} :history []
+ :profile-id "p" :conversation-id (str (random-uuid))
+ :session-id "s" :state {}}]
+ (testing "on-complete receives collected lines"
+ (mt/with-dynamic-fn-redefs [http/post (mock-post! mock-response)]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [result (atom nil)
+ lines (metabot-v3.client/streaming-request-with-callback
+ (assoc req :on-complete #(reset! result %)))]
+ (is (= lines @result))))))
+ (testing "works without on-complete"
+ (mt/with-dynamic-fn-redefs [http/post (mock-post! mock-response)]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (is (sequential? (metabot-v3.client/streaming-request-with-callback req)))))))))
+
(deftest streaming-request-error-excludes-headers-test
(testing "When streaming-request gets an error response, the exception should not include headers"
(mt/with-premium-features #{:metabot-v3}
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/middleware/auth_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/middleware/auth_test.clj
new file mode 100644
index 00000000000..e91f6748c4b
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/middleware/auth_test.clj
@@ -0,0 +1,102 @@
+(ns metabase-enterprise.metabot-v3.middleware.auth-test
+ "EE-specific tests for auth middleware, particularly Slack signature verification."
+ (:require
+ [buddy.core.codecs :as codecs]
+ [buddy.core.mac :as mac]
+ [clojure.test :refer :all]
+ [metabase.server.middleware.auth :as mw.auth]
+ [metabase.test :as mt]
+ [ring.mock.request :as ring.mock]))
+
+(set! *warn-on-reflection* true)
+
+;;; ------------------------------------------ TEST verify-slack-request middleware ------------------------------------------
+
+(def ^:private test-signing-secret "test-slack-signing-secret-12345")
+(def ^:private test-timestamp 1700000000)
+
+(defn- compute-slack-signature
+ "Compute a valid Slack signature for testing"
+ [body timestamp signing-secret]
+ (let [message (str "v0:" timestamp ":" body)
+ signature (-> (mac/hash message {:key signing-secret :alg :hmac+sha256})
+ codecs/bytes->hex)]
+ (str "v0=" signature)))
+
+(defn- wrapped-slack-handler
+ "Invoke verify-slack-request middleware and return the modified request"
+ [request]
+ ((mw.auth/verify-slack-request
+ (fn [request respond _] (respond request)))
+ request
+ identity
+ (fn [e] (throw e))))
+
+(defn- slack-request
+ "Create a mock request with Slack signature headers and a body"
+ ^java.util.Map [^String body ^String timestamp ^String signature]
+ (-> (ring.mock/request :post "/anyurl")
+ (ring.mock/header "x-slack-signature" signature)
+ (ring.mock/header "x-slack-request-timestamp" timestamp)
+ (assoc :body (java.io.ByteArrayInputStream. (.getBytes body "UTF-8")))))
+
+(deftest verify-slack-request-test
+ (mt/with-premium-features #{:metabot-v3}
+ (with-redefs [mw.auth/current-unix-timestamp (constantly test-timestamp)]
+ (testing "Valid signature w/ signing secret configured"
+ (mt/with-temporary-raw-setting-values [metabot-slack-signing-secret test-signing-secret]
+ (let [body "test-body"
+ timestamp (str test-timestamp)
+ signature (compute-slack-signature body timestamp test-signing-secret)
+ result (wrapped-slack-handler (slack-request body timestamp signature))]
+ (is (true? (:slack/validated? result))))))
+
+ (testing "Invalid signature"
+ (mt/with-temporary-raw-setting-values [metabot-slack-signing-secret test-signing-secret]
+ (let [body "test-body"
+ timestamp (str test-timestamp)
+ signature "v0=invalid-signature"
+ result (wrapped-slack-handler (slack-request body timestamp signature))]
+ (is (false? (:slack/validated? result))))))
+
+ (testing "No signature header present - request passes through unchanged"
+ (let [body "test-body"
+ request (-> (ring.mock/request :post "/anyurl")
+ (assoc :body (java.io.ByteArrayInputStream. (.getBytes ^String body "UTF-8"))))
+ result (wrapped-slack-handler request)]
+ (is (not (contains? result :slack/validated?)))))
+
+ (testing "No signing secret configured"
+ (mt/with-temporary-raw-setting-values [metabot-slack-signing-secret nil]
+ (let [body "test-body"
+ timestamp (str test-timestamp)
+ signature "v0=some-signature"
+ result (wrapped-slack-handler (slack-request body timestamp signature))]
+ (is (nil? (:slack/validated? result)))))))))
+
+(defn- validate-request-with-timestamp
+ "Helper to test timestamp validation. Returns :slack/validated? result."
+ [timestamp]
+ (let [body "test-body"
+ signature (compute-slack-signature body timestamp test-signing-secret)
+ result (wrapped-slack-handler (slack-request body timestamp signature))]
+ (:slack/validated? result)))
+
+(deftest verify-slack-request-timestamp-validation-test
+ (mt/with-premium-features #{:metabot-v3}
+ (mt/with-temporary-raw-setting-values [metabot-slack-signing-secret test-signing-secret]
+ (with-redefs [mw.auth/current-unix-timestamp (constantly test-timestamp)]
+ (testing "Replay attack prevention - rejects timestamps outside 5 minute window"
+ (doseq [[expected offset-or-val description]
+ [[true 0 "current time"]
+ [true -300 "exactly 5 min ago"]
+ [true 300 "exactly 5 min ahead"]
+ [false -301 "5+ min ago"]
+ [false 301 "5+ min ahead"]
+ [false "abc" "malformed"]
+ [false nil "missing"]]]
+ (testing description
+ (is (= expected (validate-request-with-timestamp
+ (if (number? offset-or-val)
+ (str (+ test-timestamp offset-or-val))
+ offset-or-val)))))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/tools/api_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/tools/api_test.clj
index 1a597f66cd6..a50ab52d0dd 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot_v3/tools/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/tools/api_test.clj
@@ -6,6 +6,8 @@
[medley.core :as m]
[metabase-enterprise.metabot-v3.client :as metabot-v3.client]
[metabase-enterprise.metabot-v3.tools.api :as metabot-v3.tools.api]
+ [metabase-enterprise.metabot-v3.tools.create-alert :as metabot-v3.tools.create-alert]
+ [metabase-enterprise.metabot-v3.tools.create-dashboard-subscription :as metabot-v3.tools.create-dashboard-subscription]
[metabase-enterprise.metabot-v3.tools.entity-details :as metabot-v3.tools.entity-details]
[metabase-enterprise.metabot-v3.tools.filters :as metabot-v3.tools.filters]
[metabase-enterprise.metabot-v3.tools.test-util :as tools.tu]
@@ -40,6 +42,62 @@
([user metabot-id]
(-> user mt/user->id (#'metabot-v3.client/get-ai-service-token metabot-id))))
+(deftest create-alert-test
+ (mt/with-premium-features #{:metabot-v3}
+ (let [tool-requests (atom [])
+ conversation-id (str (random-uuid))
+ output (str (random-uuid))
+ ai-token (ai-session-token)]
+ (with-redefs [metabot-v3.tools.create-alert/create-alert
+ (fn [arguments]
+ (swap! tool-requests conj arguments)
+ {:output output})]
+ (let [response (mt/user-http-request :rasta :post 200 "ee/metabot-tools/create-alert"
+ {:request-options {:headers {"x-metabase-session" ai-token}}}
+ {:arguments {:card_id 42
+ :send_condition "has_result"
+ :slack_channel "data-team"
+ :schedule {:frequency "daily"
+ :hour 9}}
+ :conversation_id conversation-id})]
+ (is (=? [{:card-id 42
+ :send-condition :has_result
+ :slack-channel "data-team"
+ :schedule {:frequency :daily
+ :hour 9}}]
+ @tool-requests))
+ (is (=? {:output output
+ :conversation_id conversation-id}
+ response)))))))
+
+(deftest create-dashboard-subscription-test
+ (mt/with-premium-features #{:metabot-v3}
+ (let [tool-requests (atom [])
+ conversation-id (str (random-uuid))
+ output (str (random-uuid))
+ ai-token (ai-session-token)]
+ (with-redefs [metabot-v3.tools.create-dashboard-subscription/create-dashboard-subscription
+ (fn [arguments]
+ (swap! tool-requests conj arguments)
+ {:output output})]
+ (let [response (mt/user-http-request :rasta :post 200 "ee/metabot-tools/create-dashboard-subscription"
+ {:request-options {:headers {"x-metabase-session" ai-token}}}
+ {:arguments {:dashboard_id 1
+ :slack_channel "data-team"
+ :schedule {:frequency "monthly"
+ :hour 15
+ :day_of_month "middle-of-month"}}
+ :conversation_id conversation-id})]
+ (is (=? [{:dashboard-id 1
+ :slack-channel "data-team"
+ :schedule {:frequency :monthly
+ :hour 15
+ :day-of-month :middle-of-month}}]
+ @tool-requests))
+ (is (=? {:output output
+ :conversation_id conversation-id}
+ response)))))))
+
(deftest field-values-test
(mt/with-premium-features #{:metabot-v3}
(let [conversation-id (str (random-uuid))
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/tools/create_alert_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/tools/create_alert_test.clj
new file mode 100644
index 00000000000..82476e3e6a1
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/tools/create_alert_test.clj
@@ -0,0 +1,76 @@
+(ns metabase-enterprise.metabot-v3.tools.create-alert-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.metabot-v3.tools.create-alert
+ :as metabot-v3.tools.create-alert]
+ [metabase.channel.settings :as channel.settings]
+ [metabase.test :as mt]))
+
+(defn- alert-data [card-id]
+ {:card-id card-id
+ :send-condition :has_result
+ :slack-channel "data-team"
+ :schedule {:frequency :daily
+ :hour 9}})
+
+(def ^:private fake-channels
+ {:channels [{:display-name "#data-team" :name "data-team" :id "C123"}]})
+
+(deftest create-alert-test
+ (mt/with-model-cleanup [:model/Notification]
+ (mt/with-temp [:model/Card {card-id :id} {}]
+ (let [invoke-tool #(mt/with-current-user (mt/user->id :rasta)
+ (metabot-v3.tools.create-alert/create-alert %))
+ base-data (alert-data card-id)]
+ (with-redefs [channel.settings/slack-configured? (constantly true)
+ channel.settings/slack-cached-channels-and-usernames (constantly fake-channels)]
+ (testing "Slack alert can be created"
+ (is (= {:output "success"}
+ (invoke-tool base-data))))
+ (testing "Alert with goal_above send-condition can be created"
+ (is (= {:output "success"}
+ (invoke-tool (assoc base-data :send-condition :goal_above)))))
+ (testing "Alert with goal_below send-condition can be created"
+ (is (= {:output "success"}
+ (invoke-tool (assoc base-data :send-condition :goal_below)))))
+ (testing "Alert with send-once can be created"
+ (is (= {:output "success"}
+ (invoke-tool (assoc base-data :send-once true))))))))))
+
+(deftest create-alert-validation-test
+ (mt/with-temp [:model/Card {card-id :id} {}]
+ (let [invoke-tool #(mt/with-current-user (mt/user->id :rasta)
+ (metabot-v3.tools.create-alert/create-alert %))
+ base-data (alert-data card-id)]
+ (with-redefs [channel.settings/slack-configured? (constantly true)
+ channel.settings/slack-cached-channels-and-usernames (constantly fake-channels)]
+ (testing "Return an error message if the card-id is invalid"
+ (is (= {:error "invalid card_id"}
+ (invoke-tool (update base-data :card-id str)))))
+ (testing "Return an error message if the card cannot be found"
+ (is (= {:error "no saved question with this card_id found"}
+ (invoke-tool (update base-data :card-id + 100)))))
+ (testing "Slack alert requires slack-channel"
+ (is (= {:error "slack_channel is required"}
+ (invoke-tool (dissoc base-data :slack-channel)))))
+ (testing "Invalid send-condition returns an error"
+ (is (= {:error "unsupported send_condition: always"}
+ (invoke-tool (assoc base-data :send-condition :always)))))
+ (testing "Invalid send-once returns an error"
+ (is (= {:error "send_once must be a boolean"}
+ (invoke-tool (assoc base-data :send-once "true")))))))))
+
+(deftest create-alert-channel-not-configured-test
+ (mt/with-temp [:model/Card {card-id :id} {}]
+ (let [invoke-tool #(mt/with-current-user (mt/user->id :rasta)
+ (metabot-v3.tools.create-alert/create-alert %))
+ base-data (alert-data card-id)]
+ (testing "Slack alert fails when Slack is not configured"
+ (with-redefs [channel.settings/slack-configured? (constantly false)]
+ (is (= {:error "slack is not configured. Ask an admin to set up slack notifications in Metabase settings."}
+ (invoke-tool base-data)))))
+ (testing "Slack alert fails when channel does not exist"
+ (with-redefs [channel.settings/slack-configured? (constantly true)
+ channel.settings/slack-cached-channels-and-usernames (constantly {:channels []})]
+ (is (= {:error "no slack channel found with this name"}
+ (invoke-tool (assoc base-data :slack-channel "no-such-channel")))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_v3/tools/util_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_v3/tools/util_test.clj
index 7b5ffef3922..9d21404b4ac 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot_v3/tools/util_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot_v3/tools/util_test.clj
@@ -10,6 +10,66 @@
[metabase.permissions.models.permissions :as perms]
[metabase.test :as mt]))
+(deftest ^:parallel schedule->schedule-map-test
+ (testing "hourly schedule"
+ (is (= {:schedule_type "hourly"
+ :schedule_hour nil
+ :schedule_day nil
+ :schedule_frame nil}
+ (metabot-v3.tools.util/schedule->schedule-map
+ {:frequency :hourly}))))
+ (testing "daily schedule"
+ (is (= {:schedule_type "daily"
+ :schedule_hour 9
+ :schedule_day nil
+ :schedule_frame nil}
+ (metabot-v3.tools.util/schedule->schedule-map
+ {:frequency :daily
+ :hour 9}))))
+ (testing "weekly schedule"
+ (is (= {:schedule_type "weekly"
+ :schedule_hour 8
+ :schedule_day "mon"
+ :schedule_frame nil}
+ (metabot-v3.tools.util/schedule->schedule-map
+ {:frequency :weekly
+ :hour 8
+ :day-of-week :monday}))))
+ (testing "weekly schedule truncates day name to 3 chars"
+ (is (= "wed"
+ (:schedule_day
+ (metabot-v3.tools.util/schedule->schedule-map
+ {:frequency :weekly
+ :hour 10
+ :day-of-week :wednesday})))))
+ (testing "monthly schedule with first-mon"
+ (is (= {:schedule_type "monthly"
+ :schedule_hour 6
+ :schedule_day "mon"
+ :schedule_frame "first"}
+ (metabot-v3.tools.util/schedule->schedule-map
+ {:frequency :monthly
+ :hour 6
+ :day-of-month :first-mon}))))
+ (testing "monthly schedule with last-fri"
+ (is (= {:schedule_type "monthly"
+ :schedule_hour 17
+ :schedule_day "fri"
+ :schedule_frame "last"}
+ (metabot-v3.tools.util/schedule->schedule-map
+ {:frequency :monthly
+ :hour 17
+ :day-of-month :last-fri}))))
+ (testing "monthly schedule with mid"
+ (is (= {:schedule_type "monthly"
+ :schedule_hour 12
+ :schedule_day nil
+ :schedule_frame "mid"}
+ (metabot-v3.tools.util/schedule->schedule-map
+ {:frequency :monthly
+ :hour 12
+ :day-of-month :mid})))))
+
(deftest metabot-scope-query-test
(testing "metabot-scope-query with collection hierarchy"
(mt/dataset test-data
diff --git a/enterprise/backend/test/metabase_enterprise/sandbox/api/pulse_test.clj b/enterprise/backend/test/metabase_enterprise/sandbox/api/pulse_test.clj
index c2a8f662033..dbea55a1711 100644
--- a/enterprise/backend/test/metabase_enterprise/sandbox/api/pulse_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sandbox/api/pulse_test.clj
@@ -12,7 +12,7 @@
"see. A segmented user should not be able to send messages to those channels. This tests that a "
"segmented user doesn't see any slack channels.")
(met/with-gtaps! {:gtaps {:venues {}}}
- (mt/with-temporary-setting-values [slack-token nil]
+ (mt/with-temporary-setting-values [slack-app-token nil]
(is (= nil
(-> (mt/user-http-request :rasta :get 200 "pulse/form_input")
(get-in [:channels :slack])))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/slackbot/api_test.clj b/enterprise/backend/test/metabase_enterprise/slackbot/api_test.clj
new file mode 100644
index 00000000000..94500f339fb
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/slackbot/api_test.clj
@@ -0,0 +1,1099 @@
+(ns metabase-enterprise.slackbot.api-test
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [metabase-enterprise.metabot-v3.agent.core :as agent]
+ [metabase-enterprise.metabot-v3.feedback :as metabot-v3.feedback]
+ [metabase-enterprise.slackbot.api :as slackbot]
+ [metabase-enterprise.slackbot.client :as slackbot.client]
+ [metabase-enterprise.slackbot.persistence :as slackbot.persistence]
+ [metabase-enterprise.slackbot.query :as slackbot.query]
+ [metabase-enterprise.slackbot.streaming :as slackbot.streaming]
+ [metabase-enterprise.slackbot.test-util :as tu]
+ [metabase-enterprise.sso.settings :as sso-settings]
+ [metabase.analytics.prometheus-test :as prometheus-test]
+ [metabase.server.middleware.auth :as mw.auth]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [metabase.util :as u]
+ [metabase.util.json :as json]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once (fixtures/initialize :test-users))
+
+(deftest manifest-endpoint-test
+ (testing "GET /api/slack/manifest with metabot-v3 feature"
+ (mt/with-premium-features #{:metabot-v3}
+ (mt/with-temporary-setting-values [site-url "https://localhost:3000"]
+ (testing "with site-url configured"
+ (testing "admins can access manifest"
+ (let [response (mt/user-http-request :crowberto :get 200 "slack/manifest")]
+ (is (map? response))
+ (is (contains? response :display_information))
+ (is (contains? response :features))
+ (is (contains? response :oauth_config))
+ (is (contains? response :settings))
+ (let [scopes (set (get-in response [:oauth_config :scopes :bot]))]
+ (is (contains? scopes "reactions:read"))
+ (is (contains? scopes "reactions:write")))))
+ (testing "non-admins cannot access manifest"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :get 403 "slack/manifest"))))))
+ (mt/with-temporary-setting-values [site-url nil]
+ (testing "without site-url configured"
+ (testing "raises a 503 error"
+ (is (= "You must configure a site-url for Slack integration to work."
+ (mt/user-http-request :crowberto :get 503 "slack/manifest")))))))))
+
+(deftest events-endpoint-test
+ (testing "POST /api/ee/metabot-v3/slack/events"
+ (tu/with-slackbot-setup
+ (testing "handles URL verification challenge"
+ (let [body {:type "url_verification"
+ :token "Jhj5dZrVaK7ZwHHjRyZWbDl"
+ :challenge "3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P"}
+ response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options body)
+ body)]
+ (is (= "3eZbrw1aBm2rZgRNFdxV2595E9CY3gmdALWMmHkvFXO7tYXAYM8P" response))))
+
+ (testing "handles 'unknown' events with ack message"
+ (let [body {:type "event_callback"
+ :event {:type "team_rename"
+ :event_ts "1234567890.000001"}}
+ response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options body)
+ body)]
+ (is (= "ok" response))))
+
+ (testing "handles message.im events"
+ (let [body (-> tu/base-dm-event
+ (assoc-in [:event :channel] "D123")
+ (assoc-in [:event :text] "Hello from DM"))
+ response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options body)
+ body)]
+ (is (= "ok" response))))
+
+ (testing "rejects requests without valid signature"
+ (is (= "Slack request signature is not valid."
+ (mt/client :post 401 "ee/metabot-v3/slack/events"
+ {:request-options {:headers {"x-slack-signature" "v0=invalid"
+ "x-slack-request-timestamp" "1234567890"}}}
+ {:type "url_verification"
+ :challenge "test"})))))))
+
+(deftest feature-flag-test
+ (testing "POST /api/ee/metabot-v3/slack/events"
+ (testing "ack events even when metabot-v3 feature is disabled to prevent Slack retries"
+ (tu/with-slackbot-setup
+ (with-redefs [mw.auth/metabot-slack-signing-secret-setting (constantly tu/test-signing-secret)]
+ (mt/with-premium-features #{:sso-slack}
+ (let [body (assoc-in tu/base-dm-event [:event :channel] "D123")
+ response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options body)
+ body)]
+ (is (= "ok" response) "Should ACK the event with 200 OK"))))))))
+
+(deftest edited-message-ignored-test
+ (testing "POST /events ignores edited messages"
+ (tu/with-slackbot-setup
+ (doseq [[desc event-mod] [["with :edited key" {:edited {:user "U123" :ts "123"}}]
+ ["with message_changed subtype" {:subtype "message_changed"}]]]
+ (testing desc
+ (let [event-body (update tu/base-dm-event :event merge {:text "Edited message"} event-mod)]
+ (tu/with-slackbot-mocks
+ {:ai-text "Should not be called"}
+ (fn [{:keys [post-calls ephemeral-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (Thread/sleep 200)
+ (is (= 0 (count @post-calls)))
+ (is (= 0 (count @ephemeral-calls))))))))))))
+
+(deftest message-deleted-ignored-test
+ (testing "POST /events ignores message_deleted events"
+ (tu/with-slackbot-setup
+ (let [event-body (update tu/base-dm-event :event merge {:subtype "message_deleted"})
+ ignored (atom false)]
+ (with-redefs [slackbot/ignore-event (fn [_] (reset! ignored true))
+ slackbot/process-async (fn [& _] (throw (ex-info "process-async should not be called" {})))]
+ (tu/with-slackbot-mocks
+ {:ai-text "Should not be called"}
+ (fn [{:keys [post-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (is @ignored "Event should have been routed to ignore-event")
+ (is (= 0 (count @post-calls)))))))))))
+
+(deftest slackbot-disabled-setting-test
+ (testing "POST /events acks but does not process when slack-connect-enabled is false"
+ (tu/with-slackbot-setup
+ (mt/with-temporary-setting-values [sso-settings/slack-connect-enabled false]
+ (doseq [[desc event-body]
+ [["message.im event" (assoc-in tu/base-dm-event [:event :channel] "D123")]
+ ["app_mention event" tu/base-mention-event]]]
+ (testing desc
+ (tu/with-slackbot-mocks
+ {:ai-text "Should not be called"}
+ (fn [{:keys [post-calls delete-calls ephemeral-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (Thread/sleep 200)
+ (is (= 0 (count @post-calls)) "No messages should be posted")
+ (is (= 0 (count @delete-calls)) "No messages should be deleted")
+ (is (= 0 (count @ephemeral-calls)) "No ephemeral messages should be sent"))))))))))
+
+(deftest user-message-triggers-response-test
+ (testing "POST /events with user message triggers AI response via Slack streaming"
+ (tu/with-slackbot-setup
+ (let [mock-ai-text "Here is your answer"
+ event-body tu/base-dm-event]
+ (tu/with-slackbot-mocks
+ {:ai-text mock-ai-text}
+ (fn [{:keys [stream-calls append-text-calls stop-stream-calls
+ add-reaction-calls remove-reaction-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(>= (count @stop-stream-calls) 1)
+ :done? true?
+ :timeout-ms 5000})
+ (testing "stream was started"
+ (is (= 1 (count @stream-calls)))
+ (is (= "C123" (:channel (first @stream-calls)))))
+ (testing "AI response was streamed"
+ (is (some #(= mock-ai-text %) @append-text-calls)))
+ (testing "stream was stopped"
+ (is (= 1 (count @stop-stream-calls))))
+ (testing "no reactions are added for DMs"
+ (is (empty? @add-reaction-calls))
+ (is (empty? @remove-reaction-calls))))))))))
+
+(deftest app-mention-triggers-response-test
+ (testing "POST /events with app_mention uses visible channel reply (not streaming)"
+ (tu/with-slackbot-setup
+ (let [mock-ai-text "Here is your answer"
+ event-body tu/base-mention-event]
+ (tu/with-slackbot-mocks
+ {:ai-text mock-ai-text}
+ (fn [{:keys [post-calls stream-calls stop-stream-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(>= (count @post-calls) 1)
+ :done? true?
+ :timeout-ms 5000})
+ (testing "a single threaded reply is posted with the answer"
+ (is (= 1 (count @post-calls)))
+ (is (str/includes? (:text (first @post-calls)) mock-ai-text))
+ (is (= "1234567890.000001" (:thread_ts (first @post-calls)))))
+ (testing "streaming APIs are not used for app mentions"
+ (is (empty? @stream-calls))
+ (is (empty? @stop-stream-calls)))
+ (testing "assistant message in DB has slack_msg_id backfilled"
+ (let [msg (t2/select-one :model/MetabotMessage :channel_id "C123" :role "assistant")]
+ (is (some? (:slack_msg_id msg))))))))))))
+
+(deftest stream-start-failure-test
+ (testing "When start-stream fails, falls back to a regular message"
+ (tu/with-slackbot-setup
+ (let [event-body tu/base-dm-event]
+ (tu/with-slackbot-mocks
+ {:ai-text "Here is your answer"}
+ (fn [{:keys [post-calls stop-stream-calls]}]
+ (mt/with-dynamic-fn-redefs
+ [slackbot.client/start-stream (constantly nil)]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(some (fn [m] (= "I wasn't able to generate a response. Please try again." (:text m)))
+ @post-calls)
+ :done? true?
+ :timeout-ms 5000})
+ (testing "fallback message is sent"
+ (is (some #(= "I wasn't able to generate a response. Please try again." (:text %))
+ @post-calls)))
+ (testing "stop-stream is never called"
+ (is (= 0 (count @stop-stream-calls))))))))))))
+
+(deftest ai-request-error-stops-stream-test
+ (testing "When the agent loop throws after the stream has started, the stream is stopped"
+ (tu/with-slackbot-setup
+ (let [event-body tu/base-dm-event]
+ (tu/with-slackbot-mocks
+ {:ai-text "unused"}
+ (fn [{:keys [stop-stream-calls stream-calls append-text-calls]}]
+ (mt/with-dynamic-fn-redefs
+ [agent/run-agent-loop
+ (fn [_opts]
+ (reify clojure.lang.IReduceInit
+ (reduce [_ rf init]
+ ;; Emit some text first (to force stream start), then throw
+ (let [big-text (apply str (repeat (inc @#'slackbot.streaming/min-text-batch-size) "x"))]
+ (rf init {:type :text :text big-text}))
+ (throw (ex-info "Agent loop error" {})))))]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(>= (count @stop-stream-calls) 1)
+ :done? true?
+ :timeout-ms 5000})
+ (testing "stream was started before the error"
+ (is (= 1 (count @stream-calls))))
+ (testing "error message was appended to the stream"
+ (is (some #(str/includes? % "Something went wrong")
+ @append-text-calls)))
+ (testing "stream was stopped during cleanup"
+ (is (= 1 (count @stop-stream-calls))))))))))))
+
+(deftest streaming-request-args-test
+ (testing "POST /events passes correct arguments to agent/run-agent-loop"
+ (tu/with-slackbot-setup
+ (doseq [[desc event-body]
+ [["DM message" (assoc-in tu/base-dm-event [:event :channel] "D-MY-DM-CHANNEL")]
+ ["app_mention in channel" (assoc-in tu/base-mention-event [:event :channel] "C-PUBLIC-CHANNEL")]]]
+ (testing desc
+ (tu/with-slackbot-mocks
+ {:ai-text "response"}
+ (fn [{:keys [ai-request-calls stop-stream-calls update-calls]}]
+ (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)
+ (u/poll {:thunk #(or (>= (count @stop-stream-calls) 1)
+ (>= (count @update-calls) 1))
+ :done? true?
+ :timeout-ms 5000})
+ (is (= 1 (count @ai-request-calls)))
+ (let [opts (first @ai-request-calls)]
+ (is (= :slackbot (:profile-id opts)))
+ (is (map? (:context opts)))
+ (is (= (get-in event-body [:event :channel])
+ (get-in opts [:context :slack_channel_id])))
+ (is (sequential? (:messages opts)))
+ ;; Last message should be the user's request
+ (let [last-msg (last (:messages opts))]
+ (if (= "im" (get-in event-body [:event :channel_type]))
+ (is (= (get-in event-body [:event :text])
+ (:content last-msg)))
+ (let [content (:content last-msg)]
+ (is (str/includes? content "Hello!") "user message is included in prompt")
+ (is (str/includes? content "Do not narrate the steps you took")
+ "channel response-style suffix is appended"))))))))))))
+
+(deftest slack-msg-id-stored-test
+ (testing "User and bot messages are stored with their Slack ts as slack_msg_id"
+ (tu/with-slackbot-setup
+ (let [event-ts "1709567890.000001"
+ long-text (apply str (repeat 60 "x"))]
+ (tu/with-slackbot-mocks
+ {:ai-text long-text}
+ (fn [{:keys [stop-stream-calls]}]
+ (mt/with-model-cleanup [:model/MetabotMessage
+ [:model/MetabotConversation :created_at]]
+ (let [event (assoc-in tu/base-dm-event [:event :ts] event-ts)]
+ (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event) event)
+ (u/poll {:thunk #(>= (count @stop-stream-calls) 1)
+ :done? true?
+ :timeout-ms 5000})
+ (let [user-msg (t2/select-one :model/MetabotMessage :slack_msg_id event-ts :channel_id "C123")
+ bot-msg (t2/select-one :model/MetabotMessage :slack_msg_id "stream123" :channel_id "C123")]
+ (testing "user message has event ts and channel_id"
+ (is (some? user-msg))
+ (is (= event-ts (:slack_msg_id user-msg)))
+ (is (= "C123" (:channel_id user-msg))))
+ (testing "bot message has stream ts, channel_id, and requester user_id"
+ (is (some? bot-msg))
+ (is (= "stream123" (:slack_msg_id bot-msg)))
+ (is (= "C123" (:channel_id bot-msg)))
+ (is (= (mt/user->id :rasta) (:user_id bot-msg)))))))))))))
+
+(deftest user-message-with-visualizations-test
+ (testing "POST /events with visualizations uploads images and finalizes them in stop-stream blocks"
+ (tu/with-slackbot-setup
+ (let [mock-ai-text "Here are your charts"
+ mock-data-parts [{:type "static_viz" :value {:entity_id 101}}
+ {:type "static_viz" :value {:entity_id 202}}
+ {:type "other_type" :value {:foo "bar"}}]
+ event-body (update tu/base-dm-event :event merge
+ {:text "Show me charts"
+ :channel "C456"
+ :ts "1234567890.000002"
+ :event_ts "1234567890.000002"
+ :thread_ts "1234567890.000000"})]
+ (tu/with-slackbot-mocks
+ {:ai-text mock-ai-text
+ :data-parts mock-data-parts}
+ (fn [{:keys [stream-calls append-text-calls stop-stream-calls image-calls
+ generate-card-output-calls fake-png-bytes]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+
+ (u/poll {:thunk #(and (>= (count @stop-stream-calls) 1)
+ (>= (count @image-calls) 2))
+ :done? true?
+ :timeout-ms 5000})
+
+ (testing "streaming message flow works"
+ (is (= 1 (count @stream-calls)))
+ (is (= "C456" (:channel (first @stream-calls))))
+ (is (some #(= mock-ai-text %) @append-text-calls))
+ (is (= 1 (count @stop-stream-calls))))
+
+ (testing "output generation called for each static_viz"
+ (is (= 2 (count @generate-card-output-calls)))
+ (is (= #{101 202} (set (map :card-id @generate-card-output-calls)))))
+
+ (testing "rendered PNGs are uploaded to Slack"
+ (is (= 2 (count @image-calls)))
+ (is (= #{"card_101.png" "card_202.png"}
+ (set (map :filename @image-calls))))
+ (is (every? #(= (vec fake-png-bytes) (vec (:image-bytes %)))
+ @image-calls)))
+
+ (testing "stop-stream includes both image blocks and feedback controls"
+ (let [blocks (:blocks (first @stop-stream-calls))]
+ (is (= ["section" "image" "section" "image" "context_actions"]
+ (mapv :type blocks)))
+ (is (= "feedback_buttons" (get-in blocks [4 :elements 0 :type]))))))))))))
+
+(deftest user-not-linked-sends-auth-message-test
+ (testing "POST /events with unlinked user sends auth message (DM, no user mention prefix)"
+ (tu/with-slackbot-setup
+ (let [event-body (assoc-in tu/base-dm-event [:event :user] "U-UNKNOWN-USER")]
+ (tu/with-slackbot-mocks
+ {:ai-text "Should not be called"
+ :user-id :metabase-enterprise.slackbot.test-util/no-user}
+ (fn [{:keys [post-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(= 1 (count @post-calls))
+ :done? true?
+ :timeout-ms 5000})
+ (testing "auth message posted as regular message, threaded using message ts"
+ (is (=? [{:channel "C123"
+ :thread_ts "1234567890.000001"
+ :text #"(?i).*connect.*slack.*metabase.*"}]
+ @post-calls)))
+ (testing "DM auth message does not include user mention prefix"
+ (is (not (str/starts-with? (:text (first @post-calls)) "<@")))))))))))
+
+(deftest app-mention-unlinked-user-test
+ (testing "POST /events with app_mention from unlinked user sends auth message"
+ (tu/with-slackbot-setup
+ (doseq [[desc thread-ts expected-thread-ts]
+ [["top-level @mention" nil "1234567890.000002"]
+ ["@mention in thread" "1234567890.000001" "1234567890.000001"]]]
+ (testing desc
+ (let [event-body (cond-> (update tu/base-mention-event :event merge
+ {:user "U-UNKNOWN"
+ :ts "1234567890.000002"
+ :event_ts "1234567890.000002"})
+ thread-ts (assoc-in [:event :thread_ts] thread-ts))]
+ (tu/with-slackbot-mocks
+ {:ai-text "Should not be called"
+ :user-id :metabase-enterprise.slackbot.test-util/no-user}
+ (fn [{:keys [post-calls]}]
+ (is (= "ok" (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body) event-body)))
+ (u/poll {:thunk #(= 1 (count @post-calls))
+ :done? true?
+ :timeout-ms 5000})
+ (is (=? {:channel "C123"
+ :thread_ts expected-thread-ts
+ :text #"(?i).*connect.*slack.*metabase.*"}
+ (first @post-calls)))
+ (testing "channel auth message includes user mention prefix"
+ (is (str/starts-with? (:text (first @post-calls)) "<@U-UNKNOWN>")))))))))))
+
+(deftest slack-id->user-id-test
+ (testing "slack-id->user-id only returns active users with sso_source 'slack'"
+ (let [slack-id "U12345SLACK"]
+ (mt/with-temp [:model/User {active-slack-user-id :id} {:email "[email protected]"
+ :is_active true
+ :sso_source "slack"}
+ :model/User {inactive-slack-user-id :id} {:email "[email protected]"
+ :is_active false
+ :sso_source "slack"}
+ :model/User {active-google-user-id :id} {:email "[email protected]"
+ :is_active true
+ :sso_source "google"}]
+ (testing "returns user ID for active user with sso_source 'slack'"
+ (mt/with-temp [:model/AuthIdentity _ {:user_id active-slack-user-id
+ :provider "slack-connect"
+ :provider_id slack-id}]
+ (is (= active-slack-user-id
+ (#'slackbot/slack-id->user-id slack-id)))))
+
+ (testing "returns user ID for active user with sso_source 'google'"
+ (mt/with-temp [:model/AuthIdentity _ {:user_id active-google-user-id
+ :provider "slack-connect"
+ :provider_id slack-id}]
+ (is (= active-google-user-id
+ (#'slackbot/slack-id->user-id slack-id)))))
+
+ (testing "returns nil for inactive user with sso_source 'slack'"
+ (mt/with-temp [:model/AuthIdentity _ {:user_id inactive-slack-user-id
+ :provider "slack-connect"
+ :provider_id slack-id}]
+ (is (nil? (#'slackbot/slack-id->user-id slack-id)))))
+
+ (testing "returns nil for active user with different provider"
+ (mt/with-temp [:model/AuthIdentity _ {:user_id active-google-user-id
+ :provider "google"
+ :provider_id slack-id}]
+ (is (nil? (#'slackbot/slack-id->user-id slack-id)))))
+
+ (testing "returns nil when no AuthIdentity exists"
+ (is (nil? (#'slackbot/slack-id->user-id slack-id))))))))
+
+(deftest channel-message-without-mention-no-auth-test
+ (testing "POST /events with channel message (no @mention) from unlinked user should NOT send auth message"
+ (tu/with-slackbot-setup
+ (let [event-body (update tu/base-dm-event :event merge
+ {:text "Hello everyone!"
+ :user "U-UNKNOWN-USER"
+ :channel_type "channel"})]
+ (tu/with-slackbot-mocks
+ {:ai-text "Should not be called"
+ :user-id :metabase-enterprise.slackbot.test-util/no-user}
+ (fn [{:keys [post-calls ephemeral-calls stream-calls ai-request-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (Thread/sleep 500)
+ (testing "no streaming session should start"
+ (is (= 0 (count @stream-calls))))
+ (testing "no AI requests should be made"
+ (is (= 0 (count @ai-request-calls))))
+ (testing "no regular messages posted"
+ (is (= 0 (count @post-calls))))
+ (testing "no ephemeral auth messages sent"
+ (is (= 0 (count @ephemeral-calls)))))))))))
+
+(deftest channel-message-without-mention-linked-user-test
+ (testing "POST /events with channel message from linked user should be silently ignored"
+ (tu/with-slackbot-setup
+ (let [event-body (update tu/base-dm-event :event merge
+ {:text "Hello team!"
+ :channel_type "channel"})]
+ (tu/with-slackbot-mocks
+ {:ai-text "Should not be called"}
+ (fn [{:keys [post-calls ephemeral-calls stream-calls ai-request-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (Thread/sleep 500)
+ (testing "no streaming session should start"
+ (is (= 0 (count @stream-calls))))
+ (testing "no AI requests should be made"
+ (is (= 0 (count @ai-request-calls))))
+ (testing "no messages posted"
+ (is (= 0 (count @post-calls))))
+ (testing "no ephemeral messages"
+ (is (= 0 (count @ephemeral-calls)))))))))))
+
+(deftest channel-file-share-without-mention-ignored-test
+ (testing "POST /events with file_share in channel without @mention is ignored"
+ (tu/with-slackbot-setup
+ (let [event-body (update tu/base-dm-event :event merge
+ {:subtype "file_share"
+ :text "Here's my data"
+ :channel_type "channel"
+ :files [tu/slack-csv-file]})]
+ (tu/with-slackbot-mocks
+ {:ai-text "Should not be called"}
+ (fn [{:keys [post-calls ephemeral-calls stream-calls ai-request-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (Thread/sleep 200)
+ (testing "no streaming session should start"
+ (is (= 0 (count @stream-calls))))
+ (testing "no AI requests should be made"
+ (is (= 0 (count @ai-request-calls))))
+ (testing "no messages posted"
+ (is (= 0 (count @post-calls))))
+ (testing "no ephemeral messages"
+ (is (= 0 (count @ephemeral-calls)))))))))))
+
+(deftest authorize-delete-request-test
+ (testing "authorize-delete-request"
+ (testing "returns :ignored when channel-id is nil"
+ (is (= :ignored (:status (#'slackbot/authorize-delete-request "U123" nil "ts123")))))
+
+ (testing "returns :ignored when message-ts is nil"
+ (is (= :ignored (:status (#'slackbot/authorize-delete-request "U123" "C123" nil)))))
+
+ (testing "returns :ignored for unknown Slack user"
+ (with-redefs [slackbot/slack-id->user-id (constantly nil)]
+ (is (= {:status :ignored
+ :reason :unlinked-user
+ :slack-user-id "U-UNKNOWN"
+ :channel-id "C123"
+ :message-ts "ts123"}
+ (#'slackbot/authorize-delete-request "U-UNKNOWN" "C123" "ts123")))))
+
+ (testing "returns :ignored when response is not tracked in the DB"
+ (with-redefs [slackbot/slack-id->user-id (constantly (mt/user->id :rasta))
+ slackbot.persistence/response-owner-user-id (constantly nil)]
+ (is (= :ignored (:status (#'slackbot/authorize-delete-request "U123" "C123" "ts123"))))))
+
+ (testing "returns :ignored when the requester is not the response owner"
+ (with-redefs [slackbot/slack-id->user-id (constantly (mt/user->id :rasta))
+ slackbot.persistence/response-owner-user-id (constantly (mt/user->id :crowberto))]
+ (is (= :ignored (:status (#'slackbot/authorize-delete-request "U123" "C123" "ts123"))))))
+
+ (testing "returns :authorized when the requester owns the response"
+ (let [user-id (mt/user->id :rasta)]
+ (with-redefs [slackbot/slack-id->user-id (constantly user-id)
+ slackbot.persistence/response-owner-user-id (constantly user-id)]
+ (is (= {:status :authorized
+ :channel-id "C123"
+ :message-ts "ts123"
+ :request-user-id user-id}
+ (#'slackbot/authorize-delete-request "U123" "C123" "ts123"))))))))
+
+(deftest handle-delete-reaction-test
+ (testing "reaction_added with a delete emoji replaces the bot response with a removed notice"
+ (tu/with-slackbot-setup
+ (let [owner-id (mt/user->id :rasta)
+ channel-id "C123"
+ message-ts "1709567890.333333"
+ event-body {:type "event_callback"
+ :event {:type "reaction_added"
+ :event_ts "1709567890.333334"
+ :user "U123"
+ :reaction "wastebasket"
+ :item {:type "message"
+ :channel channel-id
+ :ts message-ts}}}]
+ (tu/with-slackbot-mocks
+ {:ai-text "not-called"
+ :user-id owner-id}
+ (fn [{:keys [update-calls]}]
+ (mt/with-dynamic-fn-redefs
+ [slackbot.persistence/response-owner-user-id (constantly owner-id)
+ slackbot.persistence/soft-delete-response! (constantly true)]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(>= (count @update-calls) 1)
+ :done? true?
+ :timeout-ms 5000})
+ (testing "Slack message is updated with a removed notice"
+ (is (= 1 (count @update-calls)))
+ (is (= channel-id (:channel (first @update-calls))))
+ (is (= message-ts (:ts (first @update-calls))))
+ (is (str/includes? (:text (first @update-calls)) "removed"))))))))))
+
+ (testing "reaction_added with a non-delete emoji is ignored"
+ (tu/with-slackbot-setup
+ (let [event-body {:type "event_callback"
+ :event {:type "reaction_added"
+ :event_ts "1709567890.000002"
+ :user "U123"
+ :reaction "thumbsup"
+ :item {:type "message"
+ :channel "C123"
+ :ts "1709567890.000001"}}}]
+ (tu/with-slackbot-mocks
+ {:ai-text "not-called"}
+ (fn [{:keys [update-calls]}]
+ (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)
+ (Thread/sleep 200)
+ (is (= 0 (count @update-calls)) "non-delete emoji should produce no update"))))))
+
+ (testing "reaction_added with delete emoji from non-owner is ignored"
+ (tu/with-slackbot-setup
+ (let [event-body {:type "event_callback"
+ :event {:type "reaction_added"
+ :event_ts "1709567890.444445"
+ :user "U-NOT-OWNER"
+ :reaction "x"
+ :item {:type "message"
+ :channel "C123"
+ :ts "1709567890.444444"}}}]
+ (tu/with-slackbot-mocks
+ {:ai-text "not-called"}
+ (fn [{:keys [update-calls]}]
+ (mt/with-dynamic-fn-redefs
+ [slackbot.persistence/response-owner-user-id (constantly (mt/user->id :crowberto))]
+ (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)
+ (Thread/sleep 200)
+ (is (= 0 (count @update-calls)) "delete from non-owner should produce no update"))))))))
+
+(deftest put-slack-settings-test
+ (mt/with-premium-features #{:metabot-v3 :sso-slack}
+ (let [creds {:slack-connect-client-id "id"
+ :slack-connect-client-secret "secret"
+ :metabot-slack-signing-secret "signing"}
+ clear {:slack-connect-client-id nil
+ :slack-connect-client-secret nil
+ :metabot-slack-signing-secret nil}]
+ (testing "set all credentials"
+ (mt/with-temporary-setting-values [sso-settings/slack-connect-enabled false]
+ (mt/with-temporary-raw-setting-values [slack-connect-client-id nil
+ slack-connect-client-secret nil
+ metabot-slack-signing-secret nil]
+ (is (= {:ok true} (mt/user-http-request :crowberto :put 200 "ee/metabot-v3/slack/settings" creds))))))
+
+ (testing "clear all credentials"
+ (mt/with-temporary-setting-values [sso-settings/slack-connect-enabled true]
+ (mt/with-temporary-raw-setting-values [slack-connect-client-id "x"
+ slack-connect-client-secret "x"
+ metabot-slack-signing-secret "x"]
+ (is (= {:ok true} (mt/user-http-request :crowberto :put 200 "ee/metabot-v3/slack/settings" clear))))))
+
+ (testing "partial credentials returns 400"
+ (doseq [partial [(assoc creds :slack-connect-client-id nil)
+ (assoc creds :slack-connect-client-secret nil)
+ (assoc creds :metabot-slack-signing-secret nil)]]
+ (is (= "Must provide client id, client secret and signing secret together."
+ (mt/user-http-request :crowberto :put 400 "ee/metabot-v3/slack/settings" partial)))))
+
+ (testing "non-admin returns 403"
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :put 403 "ee/metabot-v3/slack/settings" creds))))))
+
+ (testing "setting values without metabot-v3 feature returns 402"
+ (mt/with-premium-features #{:sso-slack}
+ (is (= "Metabot feature is not enabled."
+ (mt/user-http-request :crowberto :put 402 "ee/metabot-v3/slack/settings"
+ {:slack-connect-client-id "id"
+ :slack-connect-client-secret "secret"
+ :metabot-slack-signing-secret "signing"}))))))
+
+(deftest feedback-modal-view-test
+ (testing "positive feedback modal has no issue type dropdown"
+ (let [view (#'slackbot/feedback-modal-view true {:conversation_id "c1"})]
+ (is (= "metabot_feedback_modal" (:callback_id view)))
+ (is (= 1 (count (:blocks view))))
+ (is (= "freeform_feedback" (:block_id (first (:blocks view)))))))
+
+ (testing "negative feedback modal has issue type dropdown and freeform input"
+ (let [view (#'slackbot/feedback-modal-view false {:conversation_id "c1"})]
+ (is (= 2 (count (:blocks view))))
+ (is (= "issue_type" (:block_id (first (:blocks view)))))
+ (is (= "freeform_feedback" (:block_id (second (:blocks view))))))))
+
+(deftest handle-feedback-action-authenticated-test
+ (testing "feedback action opens modal with correct private_metadata but does not submit to harbormaster"
+ (let [conversation-id "conv-123"
+ harbormaster-calls (atom [])
+ open-view-calls (atom [])]
+ (with-redefs [slackbot/slack-id->user-id (constantly (mt/user->id :rasta))
+ metabot-v3.feedback/submit-to-harbormaster! (fn [feedback]
+ (swap! harbormaster-calls conj feedback)
+ true)
+ slackbot.client/open-view (fn [_ params]
+ (swap! open-view-calls conj params)
+ {:ok true})]
+ (let [action {:action_id "metabot_feedback"
+ :value (json/encode {:conversation_id conversation-id :positive true})}]
+ (#'slackbot/handle-feedback-action
+ {:action action
+ :trigger-id "trigger-abc"
+ :slack-user-id "U123"
+ :channel-id "C123"
+ :message-ts "123.456"})
+ (testing "modal was opened"
+ (is (= 1 (count @open-view-calls)))
+ (is (= "trigger-abc" (:trigger_id (first @open-view-calls))))
+ (is (= "metabot_feedback_modal" (get-in (first @open-view-calls) [:view :callback_id]))))
+ (testing "private_metadata includes channel_id and message_ts"
+ (let [pm (json/decode (get-in (first @open-view-calls) [:view :private_metadata]) true)]
+ (is (= conversation-id (:conversation_id pm)))
+ (is (true? (:positive pm)))
+ (is (= "C123" (:channel_id pm)))
+ (is (= "123.456" (:message_ts pm)))))
+ (testing "harbormaster was NOT called on button click"
+ (is (= 0 (count @harbormaster-calls)))))))))
+
+(deftest handle-feedback-action-negative-test
+ (testing "negative feedback action opens modal with issue type dropdown"
+ (let [open-view-calls (atom [])]
+ (with-redefs [slackbot/slack-id->user-id (constantly (mt/user->id :rasta))
+ slackbot.client/open-view (fn [_ params]
+ (swap! open-view-calls conj params)
+ {:ok true})]
+ (let [action {:action_id "metabot_feedback"
+ :value (json/encode {:conversation_id "conv-123" :positive false})}]
+ (#'slackbot/handle-feedback-action
+ {:action action
+ :trigger-id "trigger-abc"
+ :slack-user-id "U123"
+ :channel-id "C123"
+ :message-ts "123.456"})
+ (let [view (:view (first @open-view-calls))]
+ (is (= 2 (count (:blocks view))) "negative modal should have issue_type and freeform blocks")
+ (is (= "issue_type" (:block_id (first (:blocks view)))))))))))
+
+(deftest handle-feedback-action-unauthenticated-test
+ (testing "feedback action is silently skipped for unauthenticated user"
+ (let [harbormaster-calls (atom [])
+ open-view-calls (atom [])]
+ (with-redefs [slackbot/slack-id->user-id (constantly nil)
+ metabot-v3.feedback/submit-to-harbormaster! (fn [feedback]
+ (swap! harbormaster-calls conj feedback)
+ true)
+ slackbot.client/open-view (fn [_ params]
+ (swap! open-view-calls conj params)
+ {:ok true})]
+ (let [action {:action_id "metabot_feedback"
+ :value (json/encode {:conversation_id "conv-456" :positive false})}
+ result (#'slackbot/handle-feedback-action
+ {:action action
+ :trigger-id "trigger-abc"
+ :slack-user-id "U-UNKNOWN"
+ :channel-id "C123"
+ :message-ts "123.456"})]
+ (is (nil? result) "should return nil when user is not found")
+ (testing "nothing was called"
+ (is (= 0 (count @harbormaster-calls)))
+ (is (= 0 (count @open-view-calls)))))))))
+
+(deftest handle-feedback-modal-submission-test
+ (testing "modal submission sends feedback to harbormaster"
+ (let [harbormaster-calls (atom [])]
+ (with-redefs [metabot-v3.feedback/submit-to-harbormaster! (fn [feedback]
+ (swap! harbormaster-calls conj feedback)
+ true)]
+ (let [payload {:type "view_submission"
+ :view {:callback_id "metabot_feedback_modal"
+ :private_metadata (json/encode {:conversation_id "conv-123"
+ :positive false
+ :user_id (mt/user->id :rasta)
+ :channel_id "C123"
+ :message_ts "123.456"})
+ :state {:values {:issue_type {:issue_type_select {:selected_option {:value "not-factual"}}}
+ :freeform_feedback {:freeform_input {:value "The answer was wrong"}}}}}}
+ result (#'slackbot/handle-feedback-modal-submission payload)]
+ @result
+ (is (= 1 (count @harbormaster-calls)))
+ (let [feedback (first @harbormaster-calls)]
+ (is (false? (get-in feedback [:feedback :positive])))
+ (is (= "conv-123" (get-in feedback [:feedback :message_id])))
+ (is (= "not-factual" (get-in feedback [:feedback :issue_type])))
+ (is (= "The answer was wrong" (get-in feedback [:feedback :freeform_feedback]))))))))
+
+ (testing "modal submission with only freeform text submits"
+ (let [harbormaster-calls (atom [])]
+ (with-redefs [metabot-v3.feedback/submit-to-harbormaster! (fn [feedback]
+ (swap! harbormaster-calls conj feedback)
+ true)]
+ (let [payload {:type "view_submission"
+ :view {:callback_id "metabot_feedback_modal"
+ :private_metadata (json/encode {:conversation_id "conv-123"
+ :positive true
+ :user_id (mt/user->id :rasta)
+ :channel_id "C123"
+ :message_ts "123.456"})
+ :state {:values {:freeform_feedback {:freeform_input {:value "Great response!"}}}}}}
+ result (#'slackbot/handle-feedback-modal-submission payload)]
+ @result
+ (is (= 1 (count @harbormaster-calls)))
+ (is (= "Great response!" (get-in (first @harbormaster-calls) [:feedback :freeform_feedback])))))))
+
+ (testing "modal submission with no details still submits basic feedback"
+ (let [harbormaster-calls (atom [])]
+ (with-redefs [metabot-v3.feedback/submit-to-harbormaster! (fn [feedback]
+ (swap! harbormaster-calls conj feedback)
+ true)]
+ (let [payload {:type "view_submission"
+ :view {:callback_id "metabot_feedback_modal"
+ :private_metadata (json/encode {:conversation_id "conv-123"
+ :positive true
+ :user_id (mt/user->id :rasta)
+ :channel_id "C123"
+ :message_ts "123.456"})
+ :state {:values {:freeform_feedback {:freeform_input {:value nil}}}}}}
+ result (#'slackbot/handle-feedback-modal-submission payload)]
+ @result
+ (is (= 1 (count @harbormaster-calls)))
+ (is (true? (get-in (first @harbormaster-calls) [:feedback :positive])))))))
+
+ (testing "modal submission with only issue type submits"
+ (let [harbormaster-calls (atom [])]
+ (with-redefs [metabot-v3.feedback/submit-to-harbormaster! (fn [feedback]
+ (swap! harbormaster-calls conj feedback)
+ true)]
+ (let [payload {:type "view_submission"
+ :view {:callback_id "metabot_feedback_modal"
+ :private_metadata (json/encode {:conversation_id "conv-123"
+ :positive false
+ :user_id (mt/user->id :rasta)
+ :channel_id "C123"
+ :message_ts "123.456"})
+ :state {:values {:issue_type {:issue_type_select {:selected_option {:value "ui-bug"}}}
+ :freeform_feedback {:freeform_input {:value nil}}}}}}
+ result (#'slackbot/handle-feedback-modal-submission payload)]
+ @result
+ (is (= 1 (count @harbormaster-calls)))
+ (is (= "ui-bug" (get-in (first @harbormaster-calls) [:feedback :issue_type]))))))))
+
+;; -------------------------------- Visualization Integration Tests --------------------------------
+
+(deftest adhoc-viz-execution-test
+ (testing "POST /events with adhoc_viz executes query and uploads image"
+ (tu/with-slackbot-setup
+ (let [mock-ai-text "Here's your data"
+ mock-query {:database 1 :type "query" :query {:source-table 2}}
+ mock-data-parts [{:type "adhoc_viz" :value {:query mock-query :display "bar"}}]
+ event-body (update tu/base-dm-event :event merge
+ {:text "Show me sales data" :channel "C789"
+ :ts "1234567890.000003" :event_ts "1234567890.000003"
+ :thread_ts "1234567890.000000"})]
+ (tu/with-slackbot-mocks
+ {:ai-text mock-ai-text :data-parts mock-data-parts}
+ (fn [{:keys [stop-stream-calls image-calls generate-adhoc-output-calls fake-png-bytes]}]
+ (mt/client :post 200 "ee/metabot-v3/slack/events" (tu/slack-request-options event-body) event-body)
+ (u/poll {:thunk #(and (>= (count @stop-stream-calls) 1) (>= (count @image-calls) 1))
+ :done? true? :timeout-ms 5000})
+ (testing "generate-adhoc-output called with correct query and display"
+ (is (= 1 (count @generate-adhoc-output-calls)))
+ (is (= mock-query (:query (first @generate-adhoc-output-calls))))
+ (is (= :bar (:display (first @generate-adhoc-output-calls)))))
+ (testing "image uploaded with adhoc filename"
+ (is (= 1 (count @image-calls)))
+ (is (re-matches #"adhoc-\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}\.png" (:filename (first @image-calls))))
+ (is (= (vec fake-png-bytes) (vec (:image-bytes (first @image-calls))))))
+ (testing "stop-stream includes the uploaded image and feedback controls"
+ (let [blocks (:blocks (first @stop-stream-calls))]
+ (is (= ["section" "image" "context_actions"] (mapv :type blocks)))
+ (is (re-matches #"FIMG-\d+" (get-in blocks [1 :slack_file :id])))))))))))
+
+(deftest adhoc-viz-default-display-test
+ (testing "POST /events with adhoc_viz uses :table when display not specified"
+ (tu/with-slackbot-setup
+ (let [mock-query {:database 1 :type "query" :query {:source-table 2}}
+ mock-data-parts [{:type "adhoc_viz" :value {:query mock-query}}]
+ event-body (update tu/base-dm-event :event merge
+ {:text "Show data" :ts "1234567890.000004" :event_ts "1234567890.000004"})]
+ (tu/with-slackbot-mocks
+ {:ai-text "Here's your table" :data-parts mock-data-parts}
+ (fn [{:keys [generate-adhoc-output-calls stop-stream-calls]}]
+ (mt/client :post 200 "ee/metabot-v3/slack/events" (tu/slack-request-options event-body) event-body)
+ (u/poll {:thunk #(and (>= (count @stop-stream-calls) 1) (>= (count @generate-adhoc-output-calls) 1))
+ :done? true? :timeout-ms 5000})
+ (testing "display defaults to :table"
+ (is (= :table (:display (first @generate-adhoc-output-calls)))))))))))
+
+(deftest mixed-viz-types-test
+ (testing "POST /events handles both static_viz and adhoc_viz in same response"
+ (tu/with-slackbot-setup
+ (let [mock-query {:database 1 :type "query" :query {:source-table 2}}
+ mock-data-parts [{:type "static_viz" :value {:entity_id 101}}
+ {:type "adhoc_viz" :value {:query mock-query :display "line"}}
+ {:type "static_viz" :value {:entity_id 202}}]
+ event-body (update tu/base-dm-event :event merge
+ {:text "Show me everything" :channel "C456"
+ :ts "1234567890.000005" :event_ts "1234567890.000005"
+ :thread_ts "1234567890.000000"})]
+ (tu/with-slackbot-mocks
+ {:ai-text "Here's everything" :data-parts mock-data-parts}
+ (fn [{:keys [image-calls stop-stream-calls generate-card-output-calls generate-adhoc-output-calls]}]
+ (mt/client :post 200 "ee/metabot-v3/slack/events" (tu/slack-request-options event-body) event-body)
+ (u/poll {:thunk #(>= (count @image-calls) 3) :done? true? :timeout-ms 5000})
+ (testing "static_viz cards rendered"
+ (is (= #{101 202} (set (map :card-id @generate-card-output-calls)))))
+ (testing "adhoc_viz query rendered"
+ (is (= 1 (count @generate-adhoc-output-calls)))
+ (is (= :line (:display (first @generate-adhoc-output-calls)))))
+ (testing "all images uploaded"
+ (is (= 3 (count @image-calls))))
+ (testing "stop-stream includes all uploaded image blocks"
+ (let [blocks (:blocks (first @stop-stream-calls))]
+ (is (= ["section" "image" "section" "image" "section" "image" "context_actions"]
+ (mapv :type blocks)))))))))))
+
+(deftest viz-error-posts-error-message-test
+ (testing "posts error message when visualization generation fails"
+ (tu/with-slackbot-setup
+ (let [event-body (update tu/base-dm-event :event merge
+ {:text "Show me a chart" :channel "C456"
+ :ts "1234567890.000010" :event_ts "1234567890.000010"
+ :thread_ts "1234567890.000000"})]
+ (tu/with-slackbot-mocks
+ {:ai-text "Here's your chart" :data-parts [{:type "static_viz" :value {:entity_id 999999}}]}
+ (fn [{:keys [post-calls stop-stream-calls]}]
+ (mt/with-dynamic-fn-redefs
+ [slackbot.query/generate-card-output (fn [_card-id]
+ (throw (ex-info "Unexpected render error" {})))]
+ (mt/client :post 200 "ee/metabot-v3/slack/events" (tu/slack-request-options event-body) event-body)
+ (let [error-msg "Query execution failed, please try again."]
+ (u/poll {:thunk #(and (>= (count @stop-stream-calls) 1)
+ (some (fn [m] (= error-msg (:text m))) @post-calls))
+ :done? true? :timeout-ms 5000})
+ (is (some #(= error-msg (:text %)) @post-calls))))))))))
+
+(deftest viz-error-does-not-block-other-vizs-test
+ (testing "a failing viz does not prevent subsequent vizs from rendering"
+ (tu/with-slackbot-setup
+ (let [fake-png (byte-array [0x89 0x50 0x4E 0x47])
+ event-body (update tu/base-dm-event :event merge
+ {:text "Show me charts" :channel "C456"
+ :ts "1234567890.000011" :event_ts "1234567890.000011"
+ :thread_ts "1234567890.000000"})]
+ (tu/with-slackbot-mocks
+ {:ai-text "Here are your charts"
+ :data-parts [{:type "static_viz" :value {:entity_id 999999}}
+ {:type "static_viz" :value {:entity_id 123}}]}
+ (fn [{:keys [post-calls image-calls stop-stream-calls]}]
+ (mt/with-dynamic-fn-redefs
+ [slackbot.query/generate-card-output (fn [card-id]
+ (if (= card-id 999999)
+ (throw (ex-info "Unexpected render error" {}))
+ {:type :image :content fake-png :card-name (str "Card " card-id)}))]
+ (mt/client :post 200 "ee/metabot-v3/slack/events" (tu/slack-request-options event-body) event-body)
+ (u/poll {:thunk #(and (>= (count @stop-stream-calls) 1) (>= (count @image-calls) 1))
+ :done? true? :timeout-ms 5000})
+ (testing "error message posted for failing viz"
+ (is (some #(= "Query execution failed, please try again." (:text %)) @post-calls)))
+ (testing "second card still uploads"
+ (is (= 1 (count @image-calls)))))))))))
+
+(deftest viz-caption-and-link-on-image-test
+ (testing "image viz for static_viz uses the card name as caption, not the AI-provided caption"
+ (tu/with-slackbot-setup
+ (let [mock-data-parts [{:type "static_viz" :value {:entity_id 101 :title "AI-generated caption"}}]
+ event-body (update tu/base-dm-event :event merge
+ {:text "Show revenue" :channel "C456"
+ :ts "1234567890.000020" :event_ts "1234567890.000020"
+ :thread_ts "1234567890.000000"})]
+ (tu/with-slackbot-mocks
+ {:ai-text "Here's your chart" :data-parts mock-data-parts}
+ (fn [{:keys [image-calls stop-stream-calls]}]
+ (mt/client :post 200 "ee/metabot-v3/slack/events" (tu/slack-request-options event-body) event-body)
+ (u/poll {:thunk #(and (>= (count @stop-stream-calls) 1) (>= (count @image-calls) 1))
+ :done? true? :timeout-ms 5000})
+ (let [img (first @image-calls)
+ blocks (:blocks (first @stop-stream-calls))]
+ (testing "filename uses slugified card name"
+ (is (= "card_101.png" (:filename img))))
+ (testing "caption block uses card name with link, not AI caption"
+ (let [caption-text (get-in blocks [0 :text :text])]
+ (is (str/includes? caption-text "Card 101"))
+ (is (not (str/includes? caption-text "AI-generated caption")))
+ (is (str/includes? caption-text "/question/101"))))
+ (testing "image block references the uploaded Slack file"
+ (is (= (:file-id img) (get-in blocks [1 :slack_file :id])))))))))))
+
+(deftest table-viz-with-caption-test
+ (testing "table viz posts include caption block with link"
+ (tu/with-slackbot-setup
+ (let [mock-query {:database 1 :type "query" :query {:source-table 2}}
+ mock-data-parts [{:type "adhoc_viz" :value {:query mock-query :title "Sales Data" :link "/question#abc123"}}]
+ event-body (update tu/base-dm-event :event merge
+ {:text "Show sales" :ts "1234567890.000021" :event_ts "1234567890.000021"
+ :thread_ts "1234567890.000000"})]
+ (tu/with-slackbot-mocks
+ {:ai-text "Here's your table" :data-parts mock-data-parts}
+ (fn [{:keys [stop-stream-calls generate-adhoc-output-calls]}]
+ (mt/client :post 200 "ee/metabot-v3/slack/events" (tu/slack-request-options event-body) event-body)
+ (u/poll {:thunk #(and (>= (count @stop-stream-calls) 1) (>= (count @generate-adhoc-output-calls) 1))
+ :done? true? :timeout-ms 5000})
+ (let [viz-blocks (:blocks (first @stop-stream-calls))]
+ (testing "table viz is finalized in stop-stream blocks"
+ (is (seq viz-blocks)))
+ (testing "first block is caption with mrkdwn text"
+ (let [caption-block (first viz-blocks)]
+ (is (= "section" (:type caption-block)))
+ (is (= "mrkdwn" (get-in caption-block [:text :type])))
+ (is (str/includes? (get-in caption-block [:text :text]) "Sales Data"))))
+ (testing "feedback controls are appended after table blocks"
+ (is (= "context_actions" (get-in viz-blocks [2 :type])))
+ (is (= "feedback_buttons" (get-in viz-blocks [2 :elements 0 :type])))))))))))
+
+;; -------------------------------- Metrics Tests --------------------------------
+
+(deftest dm-response-metrics-test
+ (testing "Successful DM response increments prometheus counters and records duration"
+ (mt/with-prometheus-system! [_ system]
+ (tu/with-slackbot-setup
+ (tu/with-slackbot-mocks
+ {:ai-text "Hello!"}
+ (fn [{:keys [stop-stream-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options tu/base-dm-event) tu/base-dm-event)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(>= (count @stop-stream-calls) 1) :done? true? :timeout-ms 5000})
+ (testing "responses-generated counter is incremented for dm/success"
+ (is (prometheus-test/approx= 1 (mt/metric-value system :metabase-slackbot/responses-generated
+ {:source "dm" :result "success"}))))
+ (testing "response-duration-ms histogram is recorded"
+ (is (pos? (:sum (mt/metric-value system :metabase-slackbot/response-duration-ms {:source "dm"}))))))))))))
+
+(deftest channel-response-metrics-test
+ (testing "Successful channel response increments prometheus counters"
+ (mt/with-prometheus-system! [_ system]
+ (tu/with-slackbot-setup
+ (tu/with-slackbot-mocks
+ {:ai-text "Hello!"}
+ (fn [{:keys [update-calls remove-reaction-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options tu/base-mention-event) tu/base-mention-event)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(and (>= (count @update-calls) 1) (>= (count @remove-reaction-calls) 1))
+ :done? true? :timeout-ms 5000})
+ (testing "responses-generated counter is incremented for channel/success"
+ (is (prometheus-test/approx= 1 (mt/metric-value system :metabase-slackbot/responses-generated
+ {:source "channel" :result "success"})))))))))))
+
+(deftest error-response-metrics-test
+ (testing "Failed response increments error counter and records duration"
+ (mt/with-prometheus-system! [_ system]
+ (tu/with-slackbot-setup
+ (tu/with-slackbot-mocks
+ {:ai-text "Hello!"}
+ (fn [_]
+ (with-redefs [slackbot.streaming/send-response (fn [& _] (throw (Exception. "boom")))]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options tu/base-dm-event) tu/base-dm-event)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(prometheus-test/approx= 1 (mt/metric-value system :metabase-slackbot/responses-generated
+ {:source "dm" :result "error"}))
+ :done? true? :timeout-ms 5000})
+ (testing "responses-generated error counter is incremented"
+ (is (prometheus-test/approx= 1 (mt/metric-value system :metabase-slackbot/responses-generated
+ {:source "dm" :result "error"}))))
+ (testing "response-duration-ms histogram is recorded even on error"
+ (is (pos? (:sum (mt/metric-value system :metabase-slackbot/response-duration-ms {:source "dm"})))))))))))))
+
+(deftest delete-response-metrics-test
+ (testing "Deleting a response increments responses-deleted counter"
+ (mt/with-prometheus-system! [_ system]
+ (tu/with-slackbot-setup
+ (let [channel-id "C123"
+ message-ts "1234567890.000001"
+ user-id (mt/user->id :rasta)]
+ (with-redefs [slackbot.client/update-message (constantly {:ok true})
+ slackbot.persistence/soft-delete-response! (constantly true)]
+ (#'slackbot/replace-response-with-removed-notice!
+ {:token "xoxb-test"} channel-id message-ts user-id)
+ (is (prometheus-test/approx= 1 (mt/metric-value system :metabase-slackbot/responses-deleted)))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/slackbot/config_test.clj b/enterprise/backend/test/metabase_enterprise/slackbot/config_test.clj
new file mode 100644
index 00000000000..dbed07fa134
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/slackbot/config_test.clj
@@ -0,0 +1,51 @@
+(ns metabase-enterprise.slackbot.config-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.slackbot.test-util :as tu]
+ [metabase-enterprise.sso.settings :as sso-settings]
+ [metabase.channel.settings :as channel.settings]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [metabase.util.encryption :as encryption]))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once (fixtures/initialize :test-users))
+
+(deftest setup-complete-test
+ (tu/with-slackbot-setup
+ (let [request-body (assoc-in tu/base-dm-event [:event :text] "test")
+ post-events #(mt/client :post %1 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options request-body) request-body)]
+ (testing "succeeds when all settings are configured"
+ (is (= "ok" (post-events 200))))
+
+ (testing "returns 503 when sso-slack feature disabled"
+ (with-redefs [premium-features/enable-sso-slack? (constantly false)]
+ (is (= "Slack integration is not fully configured." (post-events 503)))))
+
+ (testing "returns 503 when client-id missing"
+ (mt/with-temporary-setting-values [sso-settings/slack-connect-client-id nil]
+ (is (= "Slack integration is not fully configured." (post-events 503)))))
+
+ (testing "returns 503 when client-secret missing"
+ (mt/with-temporary-setting-values [sso-settings/slack-connect-client-secret nil]
+ (is (= "Slack integration is not fully configured." (post-events 503)))))
+
+ (testing "returns 503 when bot-token missing"
+ (mt/with-temporary-setting-values [channel.settings/slack-app-token nil]
+ (is (= "Slack integration is not fully configured." (post-events 503)))))
+
+ (testing "returns 503 when encryption disabled"
+ (with-redefs [encryption/default-secret-key nil]
+ (is (= "Slack integration is not fully configured." (post-events 503)))))
+
+ (testing "returns 503 when site-url missing"
+ (mt/with-temporary-setting-values [site-url nil]
+ (is (= "Slack integration is not fully configured." (post-events 503)))))
+
+ (testing "returns 503 when signing-secret missing (can't sign request)"
+ (mt/with-temporary-raw-setting-values [metabot-slack-signing-secret nil]
+ (is (= "Slack integration is not fully configured."
+ (mt/client :post 503 "ee/metabot-v3/slack/events" request-body))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/slackbot/persistence_test.clj b/enterprise/backend/test/metabase_enterprise/slackbot/persistence_test.clj
new file mode 100644
index 00000000000..4774870ff32
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/slackbot/persistence_test.clj
@@ -0,0 +1,134 @@
+(ns metabase-enterprise.slackbot.persistence-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.slackbot.persistence :as slackbot.persistence]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once (fixtures/initialize :test-users))
+
+(deftest message-history-test
+ (let [conv-id (str (random-uuid))]
+ (mt/with-model-cleanup [:model/MetabotMessage [:model/MetabotConversation :created_at]]
+ (t2/insert! :model/MetabotConversation {:id conv-id :user_id (mt/user->id :rasta)})
+ ;; User message - should be excluded (query filters by role=assistant)
+ (t2/insert! :model/MetabotMessage
+ {:conversation_id conv-id
+ :slack_msg_id "1709567890.000001"
+ :role "user"
+ :profile_id "test"
+ :total_tokens 0
+ :data [{:_type "TEXT" :role "user" :content "what is 2+2?"}]})
+ ;; Assistant message with tool calls
+ (t2/insert! :model/MetabotMessage
+ {:conversation_id conv-id
+ :slack_msg_id "1709567890.000002"
+ :role "assistant"
+ :profile_id "test"
+ :total_tokens 10
+ :data [{:_type "TEXT" :role "assistant" :content "hi"}
+ {:_type "TOOL_CALL" :role "assistant" :tool_calls [{:id "x"}]}
+ {:_type "TOOL_RESULT" :role "tool" :tool_call_id "x" :content "y"}]})
+
+ (testing "only TOOL_CALL and TOOL_RESULT are included, TEXT is filtered out"
+ (let [result (slackbot.persistence/message-history conv-id #{"1709567890.000002"})]
+ (is (= 2 (count (get result "1709567890.000002"))))
+ (is (every? #(#{:assistant :tool} (:role %)) (get result "1709567890.000002")))))
+
+ (testing "user messages are excluded, only assistant role is queried"
+ (let [result (slackbot.persistence/message-history conv-id #{"1709567890.000001"})]
+ (is (empty? result))))
+
+ (testing "non-matching slack_msg_ids return empty map"
+ (let [result (slackbot.persistence/message-history conv-id #{"nonexistent-id"})]
+ (is (empty? result))))
+
+ (testing "soft-deleted messages are excluded from message-history but included in deleted-message-ids"
+ (let [deleted-ts "1709567890.000003"]
+ (t2/insert! :model/MetabotMessage
+ {:conversation_id conv-id
+ :slack_msg_id deleted-ts
+ :role "assistant"
+ :profile_id "test"
+ :total_tokens 10
+ :data [{:_type "TOOL_CALL" :role "assistant" :tool_calls [{:id "y"}]}]
+ :deleted_at (java.time.OffsetDateTime/now)
+ :deleted_by_user_id (mt/user->id :rasta)})
+ (is (empty? (slackbot.persistence/message-history conv-id #{deleted-ts})))
+ (is (= #{deleted-ts}
+ (slackbot.persistence/deleted-message-ids conv-id #{deleted-ts}))))))))
+
+(deftest soft-delete-response-test
+ (testing "soft-delete-response! marks the assistant response as deleted"
+ (mt/with-model-cleanup [:model/MetabotMessage [:model/MetabotConversation :created_at]]
+ (let [channel-id "C123"
+ slack-ts "1709567890.111111"
+ user-id (mt/user->id :rasta)
+ conv-id (str (random-uuid))]
+ (t2/insert! :model/MetabotConversation {:id conv-id :user_id user-id})
+ (t2/insert! :model/MetabotMessage
+ {:conversation_id conv-id
+ :slack_msg_id slack-ts
+ :channel_id channel-id
+ :role "assistant"
+ :profile_id "test"
+ :total_tokens 5
+ :data []})
+ (testing "returns true when a message is soft-deleted"
+ (is (true? (slackbot.persistence/soft-delete-response! channel-id slack-ts user-id))))
+ (let [msg (t2/select-one :model/MetabotMessage
+ :channel_id channel-id
+ :slack_msg_id slack-ts
+ :role "assistant")]
+ (testing "deleted_at is set"
+ (is (some? (:deleted_at msg))))
+ (testing "deleted_by_user_id is set"
+ (is (= user-id (:deleted_by_user_id msg))))))))
+
+ (testing "returns nil when required inputs are missing"
+ (is (nil? (slackbot.persistence/soft-delete-response! nil "ts" 1)))
+ (is (nil? (slackbot.persistence/soft-delete-response! "C123" nil 1)))
+ (is (nil? (slackbot.persistence/soft-delete-response! "C123" "ts" nil)))))
+
+(deftest response-owner-user-id-test
+ (testing "response-owner-user-id returns the user who triggered the bot response"
+ (mt/with-model-cleanup [:model/MetabotMessage [:model/MetabotConversation :created_at]]
+ (let [channel-id "C-OWNER-TEST"
+ slack-ts "1709567890.222222"
+ requester-id (mt/user->id :rasta)
+ later-user-id (mt/user->id :crowberto)
+ conv-id (str (random-uuid))]
+ ;; Simulate a later user having overwritten MetabotConversation.user_id
+ (t2/insert! :model/MetabotConversation {:id conv-id :user_id later-user-id})
+ (t2/insert! :model/MetabotMessage
+ {:conversation_id conv-id
+ :slack_msg_id slack-ts
+ :channel_id channel-id
+ :role "assistant"
+ :user_id requester-id
+ :profile_id "test"
+ :total_tokens 5
+ :data []})
+ (testing "returns the requester, not the (potentially overwritten) conversation owner"
+ (is (= requester-id (slackbot.persistence/response-owner-user-id channel-id slack-ts))))
+ (testing "returns nil for an untracked message ts"
+ (is (nil? (slackbot.persistence/response-owner-user-id channel-id "nonexistent-ts"))))
+ (testing "returns nil when channel does not match"
+ (is (nil? (slackbot.persistence/response-owner-user-id "C-WRONG" slack-ts))))
+
+ (testing "two users in the same thread each own only their own bot response"
+ (let [second-slack-ts "1709567890.333333"]
+ (t2/insert! :model/MetabotMessage
+ {:conversation_id conv-id
+ :slack_msg_id second-slack-ts
+ :channel_id channel-id
+ :role "assistant"
+ :user_id later-user-id
+ :profile_id "test"
+ :total_tokens 5
+ :data []})
+ (is (= requester-id (slackbot.persistence/response-owner-user-id channel-id slack-ts)))
+ (is (= later-user-id (slackbot.persistence/response-owner-user-id channel-id second-slack-ts)))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/slackbot/query_test.clj b/enterprise/backend/test/metabase_enterprise/slackbot/query_test.clj
new file mode 100644
index 00000000000..84facdf55b7
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/slackbot/query_test.clj
@@ -0,0 +1,360 @@
+(ns metabase-enterprise.slackbot.query-test
+ "Integration tests for ad-hoc query execution and visualization."
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [metabase-enterprise.slackbot.query :as slackbot.query]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.test :as mt])
+ (:import
+ (java.awt.image BufferedImage)
+ (java.io ByteArrayInputStream)
+ (javax.imageio ImageIO)))
+
+(set! *warn-on-reflection* true)
+
+(defn- bytes->image
+ "Parse PNG bytes into a BufferedImage. Returns nil if bytes are not a valid image."
+ ^BufferedImage [^bytes b]
+ (with-open [input-stream (ByteArrayInputStream. b)]
+ (ImageIO/read input-stream)))
+
+;;; ------------------------------------------------ Query Execution -------------------------------------------------
+
+(deftest execute-adhoc-query-test
+ (testing "execute-adhoc-query runs a query and returns results"
+ (mt/with-current-user (mt/user->id :rasta)
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/limit 5))
+ results (slackbot.query/execute-adhoc-query query)]
+ (testing "returns query results with expected structure"
+ (is (map? results))
+ (is (contains? results :data))
+ (is (contains? (:data results) :rows))
+ (is (contains? (:data results) :cols)))
+ (testing "returns correct number of rows"
+ (is (= 5 (count (get-in results [:data :rows])))))))))
+
+(deftest execute-adhoc-query-aggregation-test
+ (testing "execute-adhoc-query handles aggregation queries"
+ (mt/with-current-user (mt/user->id :rasta)
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib.metadata/field mp (mt/id :venues :category_id))))
+ results (slackbot.query/execute-adhoc-query query)]
+ (testing "returns aggregated results"
+ (is (seq (get-in results [:data :rows]))))
+ (testing "has correct columns for aggregation"
+ (let [col-names (map :name (get-in results [:data :cols]))]
+ (is (some #(re-find #"(?i)category" %) col-names))
+ (is (some #(re-find #"(?i)count" %) col-names))))))))
+
+;;; ------------------------------------------------ PNG Generation --------------------------------------------------
+
+(deftest generate-adhoc-png-table-test
+ (testing "generate-adhoc-png renders table visualization as PNG"
+ (mt/with-current-user (mt/user->id :rasta)
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/limit 10))
+ results (slackbot.query/execute-adhoc-query query)
+ png (#'slackbot.query/generate-adhoc-png results :table)
+ image (bytes->image png)]
+ (testing "returns parseable PNG"
+ (is (some? image)))
+ (testing "image has reasonable dimensions"
+ (is (< 100 (.getWidth image))))))))
+
+(deftest generate-adhoc-png-bar-chart-test
+ (testing "generate-adhoc-png renders bar chart visualization as PNG"
+ (mt/with-current-user (mt/user->id :rasta)
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib.metadata/field mp (mt/id :venues :category_id))))
+ results (slackbot.query/execute-adhoc-query query)
+ png (#'slackbot.query/generate-adhoc-png results :bar)
+ image (bytes->image png)]
+ (testing "returns parseable PNG"
+ (is (some? image)))))))
+
+(deftest generate-adhoc-png-line-chart-test
+ (testing "generate-adhoc-png renders line chart visualization as PNG"
+ (mt/dataset test-data
+ (mt/with-current-user (mt/user->id :rasta)
+ (let [mp (mt/metadata-provider)
+ created-at (lib.metadata/field mp (mt/id :orders :created_at))
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib/with-temporal-bucket created-at :month))
+ (lib/limit 12))
+ results (slackbot.query/execute-adhoc-query query)
+ png (#'slackbot.query/generate-adhoc-png results :line)
+ image (bytes->image png)]
+ (testing "returns parseable PNG"
+ (is (some? image))))))))
+
+(deftest render-dimensions-test
+ (testing "render-dimensions calculates width from display type aspect ratios"
+ (testing "bar chart uses 2:1 ratio (12:6 default)"
+ (is (= {:width 1280 :height 640}
+ (#'slackbot.query/render-dimensions :bar))))
+ (testing "pie chart uses 3:2 ratio (12:8 default)"
+ (is (= {:width 960 :height 640}
+ (#'slackbot.query/render-dimensions :pie))))
+ (testing "unknown display type falls back to 2:1 ratio"
+ (is (= {:width 1280 :height 640}
+ (#'slackbot.query/render-dimensions :unknown-type))))))
+
+;;; ------------------------------------------------ Table Blocks ----------------------------------------------------
+
+(deftest format-results-as-table-blocks-test
+ (testing "format-results-as-table-blocks creates valid Slack table block structure"
+ (let [results {:data {:rows [[1 "Alice" 100.50]
+ [2 "Bob" 200.75]]
+ :cols [{:name "id" :display_name "ID" :base_type :type/Integer}
+ {:name "name" :display_name "Name" :base_type :type/Text}
+ {:name "amount" :display_name "Amount" :base_type :type/Float}]}}
+ blocks (slackbot.query/format-results-as-table-blocks results)]
+
+ (testing "returns a vector of blocks"
+ (is (vector? blocks))
+ (is (pos? (count blocks))))
+
+ (testing "first block is a table block"
+ (let [table-block (first blocks)]
+ (is (= "table" (:type table-block)))
+ (is (contains? table-block :rows))
+ (is (contains? table-block :column_settings))))
+
+ (testing "table has header row plus data rows"
+ (let [table-block (first blocks)
+ rows (:rows table-block)]
+ (is (= 3 (count rows))) ; 1 header + 2 data rows
+ (testing "header row has correct values"
+ (let [header-row (first rows)]
+ (is (= "ID" (get-in header-row [0 :text])))
+ (is (= "Name" (get-in header-row [1 :text])))
+ (is (= "Amount" (get-in header-row [2 :text])))))))
+
+ (testing "column settings align numeric columns right"
+ (let [table-block (first blocks)
+ settings (:column_settings table-block)]
+ (is (= "right" (:align (nth settings 0)))) ; ID is integer
+ (is (= "left" (:align (nth settings 1)))) ; Name is text
+ (is (= "right" (:align (nth settings 2)))))))) ; Amount is float
+
+ (testing "format-results-as-table-blocks truncates large results"
+ (let [many-rows (vec (repeat 150 [1 "test"]))
+ results {:data {:rows many-rows
+ :cols [{:name "id"} {:name "name"}]}}
+ blocks (slackbot.query/format-results-as-table-blocks results)]
+
+ (testing "table is truncated to 99 data rows plus header"
+ (let [table-block (first blocks)
+ rows (:rows table-block)]
+ (is (= 100 (count rows)))))
+
+ (testing "includes truncation message"
+ (is (= 2 (count blocks)))
+ (let [context-block (second blocks)]
+ (is (= "context" (:type context-block)))
+ (is (= "Showing 99 of 150 rows"
+ (get-in context-block [:elements 0 :text])))))))
+
+ (testing "format-results-as-table-blocks handles scalar (single-cell) results"
+ (let [results {:data {:rows [[42]]
+ :cols [{:name "count" :display_name "Count" :base_type :type/Integer}]}}
+ blocks (slackbot.query/format-results-as-table-blocks results)]
+ (testing "returns a 1x1 table with header"
+ (let [table-block (first blocks)
+ rows (:rows table-block)]
+ (is (= 2 (count rows))) ; 1 header + 1 data row
+ (is (= "Count" (get-in rows [0 0 :text])))
+ (is (= "42" (get-in rows [1 0 :text])))))))
+
+ (testing "format-results-as-table-blocks handles empty results"
+ (let [results {:data {:rows []
+ :cols [{:name "count" :display_name "Count" :base_type :type/Integer}]}}
+ blocks (slackbot.query/format-results-as-table-blocks results)]
+ (testing "returns no-data block"
+ (is (= "No data" (get-in blocks [0 :rows 0 0 :text]))))))
+
+ (testing "format-results-as-table-blocks truncates long cell values"
+ (binding [slackbot.query/*slack-table-max-cell-length* 20]
+ (let [long-text (apply str (repeat 50 "x"))
+ results {:data {:rows [[1 long-text]]
+ :cols [{:name "id" :display_name "ID" :base_type :type/Integer}
+ {:name "desc" :display_name "Description" :base_type :type/Text}]}}
+ blocks (slackbot.query/format-results-as-table-blocks results)
+ cell-text (get-in (first blocks) [:rows 1 1 :text])]
+ (is (<= (count cell-text) 20))
+ (is (str/ends-with? cell-text "…")))))
+
+ (testing "format-results-as-table-blocks truncates rows to fit character budget"
+ (binding [slackbot.query/*slack-table-max-chars* 100]
+ (let [results {:data {:rows (vec (repeat 20 ["abcdefghij"]))
+ :cols [{:name "val" :display_name "Value" :base_type :type/Text}]}}
+ blocks (slackbot.query/format-results-as-table-blocks results)
+ data-rows (rest (:rows (first blocks)))]
+ (testing "does not include all rows"
+ (is (< (count data-rows) 20)))
+ (testing "includes truncation context block"
+ (is (= 2 (count blocks)))
+ (is (= "context" (:type (second blocks)))))
+ (testing "total cell text fits within character budget"
+ (let [total-chars (transduce (comp cat (map (comp count :text)))
+ + (:rows (first blocks)))]
+ (is (<= total-chars 100)))))))
+
+ (testing "format-results-as-table-blocks handles FK remapped columns"
+ (let [;; Simulate FK remapping: USER_ID is remapped to show USER.NAME
+ ;; The data has both USER_ID (raw FK) and NAME (human-readable value from FK target)
+ results {:data {:rows [[1 100 "Alice"]
+ [2 200 "Bob"]]
+ :cols [{:name "id"
+ :display_name "ID"
+ :base_type :type/Integer}
+ {:name "user_id"
+ :display_name "User ID"
+ :base_type :type/Integer
+ :remapped_to "user_name"}
+ {:name "user_name"
+ :display_name "User Name"
+ :base_type :type/Text
+ :remapped_from "user_id"}]}}
+ blocks (slackbot.query/format-results-as-table-blocks results)]
+
+ (testing "skips remapped_from column (the duplicate)"
+ (let [table-block (first blocks)
+ header-row (first (:rows table-block))]
+ ;; Should only have 2 columns: ID and User Name (not 3)
+ (is (= 2 (count header-row)))))
+
+ (testing "uses remapped column's display name in header"
+ (let [table-block (first blocks)
+ header-row (first (:rows table-block))]
+ (is (= "ID" (get-in header-row [0 :text])))
+ (is (= "User Name" (get-in header-row [1 :text])))))
+
+ (testing "substitutes remapped values in data rows"
+ (let [table-block (first blocks)
+ data-rows (rest (:rows table-block))]
+ ;; First row should show "1" and "Alice" (not "100")
+ (is (= "1" (get-in (first data-rows) [0 :text])))
+ (is (= "Alice" (get-in (first data-rows) [1 :text])))
+ ;; Second row should show "2" and "Bob" (not "200")
+ (is (= "2" (get-in (second data-rows) [0 :text])))
+ (is (= "Bob" (get-in (second data-rows) [1 :text]))))))))
+
+;;; -------------------------------------------- generate-adhoc-output -----------------------------------------------
+
+(deftest generate-adhoc-output-chart-display-test
+ (testing "generate-adhoc-output renders chart display types as PNG images"
+ (mt/with-current-user (mt/user->id :rasta)
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/aggregate (lib/count))
+ (lib/breakout (lib.metadata/field mp (mt/id :venues :category_id))))]
+
+ (testing "bar chart renders as image"
+ (let [{:keys [type content]} (slackbot.query/generate-adhoc-output query :display :bar)]
+ (is (= :image type))
+ (is (bytes? content))
+ (is (some? (bytes->image content)))))
+
+ (testing "line chart renders as image"
+ (let [{:keys [type content]} (slackbot.query/generate-adhoc-output query :display :line)]
+ (is (= :image type))
+ (is (bytes? content))))
+
+ (testing "pie chart renders as image"
+ (let [{:keys [type content]} (slackbot.query/generate-adhoc-output query :display :pie)]
+ (is (= :image type))
+ (is (bytes? content))))))))
+
+(deftest generate-adhoc-output-table-display-test
+ (testing "generate-adhoc-output renders table display as Slack table blocks"
+ (mt/with-current-user (mt/user->id :rasta)
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/limit 5))]
+
+ (testing "table display renders as table blocks"
+ (let [{:keys [type content]} (slackbot.query/generate-adhoc-output query :display :table)]
+ (is (= :table type))
+ (is (vector? content))
+ (is (= "table" (:type (first content))))))
+
+ (testing "scalar display renders as table blocks"
+ (let [scalar-query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/aggregate (lib/count)))
+ {:keys [type content]} (slackbot.query/generate-adhoc-output scalar-query :display :scalar)]
+ (is (= :table type))
+ (is (= "table" (:type (first content))))))))))
+
+(deftest generate-adhoc-output-default-display-test
+ (testing "generate-adhoc-output defaults to table display"
+ (mt/with-current-user (mt/user->id :rasta)
+ (let [mp (mt/metadata-provider)
+ query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/limit 3))
+ {:keys [type content]} (slackbot.query/generate-adhoc-output query)]
+ (is (= :table type))
+ (is (vector? content))
+ (is (= "table" (:type (first content))))))))
+
+;;; -------------------------------------------- generate-card-output -----------------------------------------------
+
+(deftest generate-card-output-display-type-test
+ (testing "generate-card-output returns correct type based on card display"
+ (let [mock-results {:data {:cols [{:name "x" :base_type :type/Integer}]
+ :rows [[1] [2]]}}]
+ (mt/with-dynamic-fn-redefs
+ [slackbot.query/pulse-card-query-results (constantly mock-results)]
+
+ (testing "supported display types return :image"
+ (doseq [display [:bar :line :pie :area :row :scatter :funnel
+ :waterfall :combo :progress :gauge
+ :smartscalar :boxplot :sankey]]
+ (testing (str "display type: " display)
+ (mt/with-temp [:model/Card {card-id :id} {:display display}]
+ (let [result (#'slackbot.query/generate-card-output card-id)]
+ (is (= :image (:type result))))))))
+
+ (testing "unsupported display types return :table"
+ (doseq [display [:table :pin_map :state :country :map :pivot :scalar]]
+ (testing (str "display type: " display)
+ (mt/with-temp [:model/Card {card-id :id} {:display display}]
+ (let [result (#'slackbot.query/generate-card-output card-id)]
+ (is (= :table (:type result))))))))))))
+
+(deftest generate-card-output-failed-qp-result-test
+ (testing "throws when QP returns :status :failed for table card"
+ (mt/with-temp [:model/Card {card-id :id} {:display :table}]
+ (mt/with-dynamic-fn-redefs
+ [slackbot.query/pulse-card-query-results (constantly {:status :failed
+ :error "Permission denied"})]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Permission denied"
+ (#'slackbot.query/generate-card-output card-id)))))))
+
+(deftest generate-card-output-failed-qp-result-image-test
+ (testing "throws when QP returns :status :failed for image card"
+ (mt/with-temp [:model/Card {card-id :id} {:display :bar}]
+ (mt/with-dynamic-fn-redefs
+ [slackbot.query/pulse-card-query-results (constantly {:status :failed
+ :error "Permission denied"})]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Permission denied"
+ (#'slackbot.query/generate-card-output card-id)))))))
+
+(deftest ^:parallel generate-adhoc-output-failed-qp-result-test
+ (testing "throws when QP returns :status :failed"
+ (mt/with-dynamic-fn-redefs
+ [slackbot.query/execute-adhoc-query (constantly {:status :failed
+ :error "Table not found"
+ :data {:rows [] :cols []}})]
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo #"Table not found"
+ (slackbot.query/generate-adhoc-output {:database 1} :display :table))))))
diff --git a/enterprise/backend/test/metabase_enterprise/slackbot/streaming_test.clj b/enterprise/backend/test/metabase_enterprise/slackbot/streaming_test.clj
new file mode 100644
index 00000000000..0b60c2a15de
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/slackbot/streaming_test.clj
@@ -0,0 +1,208 @@
+(ns metabase-enterprise.slackbot.streaming-test
+ (:require
+ [clojure.test :refer :all]
+ [metabase-enterprise.slackbot.client :as slackbot.client]
+ [metabase-enterprise.slackbot.persistence :as slackbot.persistence]
+ [metabase-enterprise.slackbot.streaming :as slackbot.streaming]
+ [metabase-enterprise.slackbot.test-util :as tu]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [metabase.util :as u]
+ [metabase.util.json :as json]))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once (fixtures/initialize :test-users))
+
+(deftest ^:parallel slack-thread-conversation-id-test
+ (testing "Same thread produces same conversation ID"
+ (is (= (#'slackbot.streaming/slack-thread->conversation-id "T1" "C1" "123.456")
+ (#'slackbot.streaming/slack-thread->conversation-id "T1" "C1" "123.456"))))
+
+ (testing "Different threads produce different IDs"
+ (is (not= (#'slackbot.streaming/slack-thread->conversation-id "T1" "C1" "123.456")
+ (#'slackbot.streaming/slack-thread->conversation-id "T1" "C1" "789.012"))))
+
+ (testing "Different channels produce different IDs"
+ (is (not= (#'slackbot.streaming/slack-thread->conversation-id "T1" "C1" "123.456")
+ (#'slackbot.streaming/slack-thread->conversation-id "T1" "C2" "123.456"))))
+
+ (testing "Different workspaces produce different IDs"
+ (is (not= (#'slackbot.streaming/slack-thread->conversation-id "T1" "C1" "123.456")
+ (#'slackbot.streaming/slack-thread->conversation-id "T2" "C1" "123.456"))))
+
+ (testing "Result is valid UUID format"
+ (is (re-matches #"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}"
+ (#'slackbot.streaming/slack-thread->conversation-id "T1" "C1" "123.456")))))
+
+(deftest thread->history-strips-bot-mentions-test
+ (testing "User messages have bot mentions stripped"
+ (with-redefs [slackbot.persistence/message-history (constantly {})]
+ (let [thread {:messages [{:ts "1709567890.000001" :text "<@UBOT123> hello" :user "U123"}]}
+ result (#'slackbot.streaming/thread->history thread "UBOT123" "conv-123")]
+ (is (= [{:role :user :content "hello"}] result))))))
+
+(deftest thread->history-merges-tool-calls-test
+ (testing "Bot messages include tool call data from DB before text"
+ (with-redefs [slackbot.persistence/message-history
+ (constantly {"1709567890.000002"
+ [{:role :assistant :tool_calls [{:id "tc1" :name "run_query"}]}
+ {:role :tool :tool_call_id "tc1" :content "42"}]})]
+ (let [thread {:messages [{:ts "1709567890.000002" :text "The answer is 42" :bot_id "B123"}]}
+ result (#'slackbot.streaming/thread->history thread "UBOT123" "conv-123")]
+ (is (= 3 (count result)))
+ (is (= [{:id "tc1" :name "run_query"}] (:tool_calls (first result))))
+ (is (= "tc1" (:tool_call_id (second result))))
+ (is (= {:role :assistant :content "The answer is 42"} (last result)))))))
+
+(deftest thread->history-excludes-thinking-test
+ (testing "Thinking placeholder messages are excluded from history"
+ (with-redefs [slackbot.persistence/message-history (constantly {})]
+ (let [thread {:messages [{:ts "1709567890.000001" :text "question" :user "U123"}
+ {:ts "1709567890.000002" :text "_Thinking..._" :bot_id "B123"}]}
+ result (#'slackbot.streaming/thread->history thread "UBOT123" "conv-123")]
+ (is (= 1 (count result)))
+ (is (= :user (:role (first result))))))))
+
+(deftest thread->history-excludes-blank-bot-messages-test
+ (testing "Bot messages with blank text are excluded"
+ (with-redefs [slackbot.persistence/message-history (constantly {})]
+ (let [thread {:messages [{:ts "1709567890.000001" :text "" :bot_id "B123"}
+ {:ts "1709567890.000002" :text " " :bot_id "B123"}
+ {:ts "1709567890.000003" :text "real" :bot_id "B123"}]}
+ result (#'slackbot.streaming/thread->history thread "UBOT123" "conv-123")]
+ (is (= [{:role :assistant :content "real"}] result))))))
+
+(deftest thread->history-excludes-soft-deleted-bot-messages-test
+ (testing "thread->history excludes bot messages that have been soft-deleted"
+ (with-redefs [slackbot.persistence/message-history (constantly {})
+ slackbot.persistence/deleted-message-ids
+ (fn [_conv-id _ids] #{"1709567890.000002"})]
+ (let [thread {:messages [{:ts "1709567890.000001" :text "User question" :user "U123"}
+ {:ts "1709567890.000002" :text "Deleted bot response" :bot_id "B123"}
+ {:ts "1709567890.000003" :text "Live bot response" :bot_id "B123"}]}
+ result (#'slackbot.streaming/thread->history thread "UBOT123" "conv-123")]
+ (is (= 2 (count result)))
+ (is (= :user (:role (first result))))
+ (is (= "Live bot response" (:content (second result))))))))
+
+(deftest format-viz-title-test
+ (testing "format-viz-title builds correct title text"
+ (mt/with-temporary-setting-values [site-url "https://metabase.example.com"]
+ (testing "title + link"
+ (is (= "📊 <https://metabase.example.com/question/42|My Chart>"
+ (#'slackbot.streaming/format-viz-title "My Chart" "/question/42"))))
+ (testing "title only"
+ (is (= "My Chart"
+ (#'slackbot.streaming/format-viz-title "My Chart" nil))))
+ (testing "link only"
+ (is (= "📊 <https://metabase.example.com/question/42|Open in Metabase>"
+ (#'slackbot.streaming/format-viz-title nil "/question/42"))))
+ (testing "neither"
+ (is (nil? (#'slackbot.streaming/format-viz-title nil nil))))
+ (testing "special characters in title are escaped"
+ (is (= "📊 <https://metabase.example.com/question/42|Sales &amp; Revenue>"
+ (#'slackbot.streaming/format-viz-title "Sales & Revenue" "/question/42")))
+ (is (= "📊 <https://metabase.example.com/question/42|Foo &lt;Bar&gt; │ Baz>"
+ (#'slackbot.streaming/format-viz-title "Foo <Bar> | Baz" "/question/42"))))
+ (testing "title-only does not escape (no link syntax)"
+ (is (= "Sales & Revenue"
+ (#'slackbot.streaming/format-viz-title "Sales & Revenue" nil)))))))
+
+(deftest feedback-blocks-test
+ (testing "feedback-blocks generates correct Slack context_actions block with feedback_buttons"
+ (let [conversation-id "test-conv-123"
+ blocks (#'slackbot.streaming/feedback-blocks conversation-id)]
+ (is (= 1 (count blocks)))
+ (let [{:keys [type block_id elements]} (first blocks)]
+ (is (= "context_actions" type))
+ (is (= "metabot_feedback" block_id))
+ (is (= 1 (count elements)))
+ (let [fb (first elements)]
+ (is (= "feedback_buttons" (:type fb)))
+ (is (= "metabot_feedback" (:action_id fb)))
+ (testing "positive button"
+ (is (= {:conversation_id conversation-id :positive true}
+ (json/decode (get-in fb [:positive_button :value]) true))))
+ (testing "negative button"
+ (is (= {:conversation_id conversation-id :positive false}
+ (json/decode (get-in fb [:negative_button :value]) true)))))))))
+
+(deftest streaming-response-includes-feedback-blocks-test
+ (testing "send-response passes feedback blocks to stop-stream"
+ (tu/with-slackbot-setup
+ (let [event-body tu/base-dm-event]
+ (tu/with-slackbot-mocks
+ {:ai-text "Here is a response"}
+ (fn [{:keys [stop-stream-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(>= (count @stop-stream-calls) 1)
+ :done? true?
+ :timeout-ms 5000})
+ (testing "stop-stream was called with feedback blocks"
+ (let [{:keys [blocks]} (first @stop-stream-calls)]
+ (is (= 1 (count blocks)))
+ (is (= "metabot_feedback" (:block_id (first blocks))))
+ (is (= "feedback_buttons" (:type (first (:elements (first blocks)))))))))))))))
+
+;;; ------------------------------------------------ Flush throttle tests ------------------------------------------------
+
+(defn- make-test-callbacks
+ "Create streaming callbacks with mocked Slack client functions.
+ Returns the callbacks map plus atoms tracking append calls."
+ []
+ (let [append-calls (atom [])
+ client {:token "xoxb-test"}]
+ (mt/with-dynamic-fn-redefs
+ [slackbot.client/start-stream (fn [_ opts]
+ {:stream_ts "s1" :channel (:channel opts) :thread_ts (:thread_ts opts)})
+ slackbot.client/append-stream (constantly {:ok true})
+ slackbot.client/append-markdown-text (fn [_ _ _ text]
+ (swap! append-calls conj text)
+ {:ok true})
+ slackbot.client/delete-message (constantly {:ok true})]
+ (let [cbs (#'slackbot.streaming/make-streaming-callbacks
+ client {:channel "C1" :thread-ts "t1" :team-id "T1" :user-id "U1"})]
+ {:cbs cbs
+ :append-calls append-calls}))))
+
+(deftest on-text-respects-batch-size-test
+ (testing "on-text does not flush until pending text reaches min-text-batch-size"
+ (let [{:keys [cbs append-calls]} (make-test-callbacks)
+ {:keys [on-text request-flush! slack-writer]} cbs
+ batch-size @#'slackbot.streaming/min-text-batch-size]
+ ;; Send text just under the threshold — should not trigger a flush
+ (on-text (apply str (repeat (dec batch-size) "a")))
+ (await slack-writer)
+ (is (= 0 (count @append-calls))
+ "No flush should occur when text is under the batch size threshold")
+ ;; Push over the threshold
+ (on-text "ab")
+ (await slack-writer)
+ (is (= 1 (count @append-calls))
+ "Flush should occur once text crosses the batch size threshold")
+ ;; Force-flush to clean up
+ (request-flush! true)
+ (await slack-writer))))
+
+(deftest flush-throttle-test
+ (testing "rapid flushes are throttled by min-flush-interval-ns"
+ (let [{:keys [cbs append-calls]} (make-test-callbacks)
+ {:keys [on-text request-flush! slack-writer]} cbs
+ batch-size @#'slackbot.streaming/min-text-batch-size
+ big-text (apply str (repeat (inc batch-size) "x"))]
+ ;; First flush should go through immediately (last-flush-at starts at 0)
+ (on-text big-text)
+ (await slack-writer)
+ (is (= 1 (count @append-calls)) "First flush should succeed immediately")
+ ;; Second flush right after should be throttled
+ (on-text big-text)
+ (await slack-writer)
+ (is (= 1 (count @append-calls)) "Second flush should be throttled")
+ ;; Force flush bypasses throttle
+ (request-flush! true)
+ (await slack-writer)
+ (is (= 2 (count @append-calls)) "Force flush should bypass throttle"))))
diff --git a/enterprise/backend/test/metabase_enterprise/slackbot/test_util.clj b/enterprise/backend/test/metabase_enterprise/slackbot/test_util.clj
new file mode 100644
index 00000000000..49391997c7f
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/slackbot/test_util.clj
@@ -0,0 +1,217 @@
+(ns metabase-enterprise.slackbot.test-util
+ "Shared test infrastructure for slackbot tests."
+ (:require
+ [buddy.core.codecs :as codecs]
+ [buddy.core.mac :as mac]
+ [metabase-enterprise.metabot-v3.agent.core :as agent]
+ [metabase-enterprise.slackbot.api :as slackbot]
+ [metabase-enterprise.slackbot.client :as slackbot.client]
+ [metabase-enterprise.slackbot.config :as slackbot.config]
+ [metabase-enterprise.slackbot.query :as slackbot.query]
+ [metabase.channel.slack :as channel.slack]
+ [metabase.test :as mt]
+ [metabase.util.encryption :as encryption]
+ [metabase.util.json :as json]))
+
+(set! *warn-on-reflection* true)
+
+(def test-signing-secret "test-signing-secret")
+(def test-encryption-key (byte-array (repeat 64 42)))
+
+(def base-dm-event
+ {:type "event_callback"
+ :event {:type "message"
+ :text "Hello!"
+ :user "U123"
+ :channel "C123"
+ :ts "1234567890.000001"
+ :event_ts "1234567890.000001"
+ :channel_type "im"}})
+
+(def base-mention-event
+ {:type "event_callback"
+ :event {:type "app_mention"
+ :text "<@UBOT123> Hello!"
+ :user "U123"
+ :channel "C123"
+ :ts "1234567890.000001"
+ :event_ts "1234567890.000001"}})
+
+(def slack-csv-file
+ "A Slack CSV file upload for testing. Tests can use merge/assoc to customize."
+ {:id "F123"
+ :name "data.csv"
+ :filetype "csv"
+ :url_private "https://files.slack.com/files/data.csv"
+ :size 100})
+
+(defmacro with-ensure-encryption
+ "Use the existing encryption key if one is configured, otherwise set a test key.
+ Avoids conflicts with encrypted settings in the DB that were written with the real key."
+ [& body]
+ `(if (encryption/default-encryption-enabled?)
+ (do ~@body)
+ (with-redefs [encryption/default-secret-key test-encryption-key]
+ ~@body)))
+
+(defmacro with-slackbot-setup
+ "Wrap body with all required settings for slackbot to be fully configured.
+ Uses `with-temporary-raw-setting-values` to avoid settings with masking getters
+ saving/restoring the obfuscated value instead of the original."
+ [& body]
+ `(with-redefs [slackbot.config/validate-bot-token! (constantly {:ok true})
+ slackbot.client/get-bot-user-id (constantly "UBOT123")]
+ (with-ensure-encryption
+ (mt/with-premium-features #{:metabot-v3 :sso-slack}
+ (mt/with-temporary-raw-setting-values [site-url "https://localhost:3000"
+ slack-connect-client-id "test-client-id"
+ slack-connect-enabled "true"
+ metabot-slack-signing-secret test-signing-secret
+ slack-app-token "xoxb-test"
+ slack-connect-client-secret "test-secret"]
+ ~@body)))))
+
+(defn compute-slack-signature
+ "Compute a valid Slack signature for testing"
+ [body timestamp]
+ (let [message (str "v0:" timestamp ":" body)
+ signature (-> (mac/hash message {:key test-signing-secret :alg :hmac+sha256})
+ codecs/bytes->hex)]
+ (str "v0=" signature)))
+
+(defn slack-request-options
+ "Build request options with valid Slack signature headers"
+ [body]
+ (let [timestamp (str (quot (System/currentTimeMillis) 1000))
+ body-str (json/encode body)
+ signature (compute-slack-signature body-str timestamp)]
+ {:request-options {:headers {"x-slack-signature" signature
+ "x-slack-request-timestamp" timestamp}}}))
+
+#_{:clj-kondo/ignore [:metabase/test-helpers-use-non-thread-safe-functions]}
+(defn with-slackbot-mocks
+ "Helper to set up common mocks for slackbot tests.
+ Options:
+ - :ai-text - The text response from make-ai-request
+ - :data-parts - The data-parts returned from make-ai-request (default [])
+ - :user-id - The user ID returned by slack-id->user-id. If not provided, defaults to rasta.
+ Pass ::no-user to simulate an unlinked Slack user (returns nil).
+
+ Calls body-fn with a map containing tracking atoms:
+ {:post-calls, :delete-calls, :update-calls, :image-calls, :generate-card-output-calls,
+ :generate-adhoc-output-calls, :ephemeral-calls, :ai-request-calls, :fake-png-bytes,
+ :stream-calls, :append-text-calls, :stop-stream-calls,
+ :add-reaction-calls, :remove-reaction-calls, :set-status-calls}"
+ [{:keys [ai-text data-parts user-id]
+ :or {data-parts []
+ user-id ::default}}
+ body-fn]
+ (let [post-calls (atom [])
+ delete-calls (atom [])
+ update-calls (atom [])
+ image-calls (atom [])
+ generate-card-output-calls (atom [])
+ generate-adhoc-output-calls (atom [])
+ ephemeral-calls (atom [])
+ ai-request-calls (atom [])
+ stream-calls (atom [])
+ append-text-calls (atom [])
+ stop-stream-calls (atom [])
+ add-reaction-calls (atom [])
+ remove-reaction-calls (atom [])
+ set-status-calls (atom [])
+ fake-png-bytes (byte-array [0x89 0x50 0x4E 0x47])
+ file-counter (atom 0)
+ placeholder-counter (atom 0)
+ mock-user-id (cond
+ (= user-id ::default) (mt/user->id :rasta)
+ (= user-id ::no-user) nil
+ :else user-id)]
+ (mt/with-dynamic-fn-redefs
+ [slackbot/slack-id->user-id (constantly mock-user-id)
+ slackbot.client/get-bot-user-id (constantly "UBOT123")
+ slackbot.client/auth-test (constantly {:ok true :user_id "UBOT123" :team_id "T123"})
+ slackbot.client/fetch-thread (constantly {:ok true, :messages []})
+ ;; Mock Slack streaming APIs
+ slackbot.client/start-stream (fn [_ opts]
+ (swap! stream-calls conj opts)
+ {:stream_ts "stream123" :channel (:channel opts) :thread_ts (:thread_ts opts)})
+ slackbot.client/append-stream (constantly {:ok true})
+ slackbot.client/append-markdown-text (fn [_ _channel _stream-ts text]
+ (swap! append-text-calls conj text)
+ {:ok true})
+ slackbot.client/stop-stream (fn [_ channel stream-ts & [blocks]]
+ (swap! stop-stream-calls conj {:channel channel :stream_ts stream-ts :blocks blocks})
+ {:ok true})
+ slackbot.client/post-message (fn [_ msg]
+ (swap! post-calls conj msg)
+ {:ok true
+ :ts (str "placeholder-" (swap! placeholder-counter inc))
+ :channel (:channel msg)
+ :message msg})
+ slackbot.client/post-ephemeral-message (fn [_ msg]
+ (swap! ephemeral-calls conj msg)
+ {:ok true, :message_ts "1234567890.123456"})
+ slackbot.client/delete-message (fn [_ msg]
+ (swap! delete-calls conj msg)
+ {:ok true})
+ slackbot.client/update-message (fn [_ msg]
+ (swap! update-calls conj msg)
+ {:ok true})
+ slackbot.client/add-reaction (fn [_ msg]
+ (swap! add-reaction-calls conj msg)
+ {:ok true})
+ slackbot.client/remove-reaction (fn [_ msg]
+ (swap! remove-reaction-calls conj msg)
+ {:ok true})
+ slackbot.client/set-status (fn [_ opts]
+ (swap! set-status-calls conj opts)
+ {:ok true})
+ channel.slack/upload-file! (fn [image-bytes filename]
+ (let [file-id (format "FIMG-%d" (swap! file-counter inc))]
+ (swap! image-calls conj {:image-bytes image-bytes
+ :filename filename
+ :file-id file-id})
+ {:url (str "https://files.slack.com/files/" filename)
+ :id file-id}))
+ ;; Mock the agent loop - returns a reducible of parts
+ agent/run-agent-loop
+ (fn [opts]
+ (swap! ai-request-calls conj opts)
+ ;; Return a reducible that emits parts matching the agent loop output format
+ (reify clojure.lang.IReduceInit
+ (reduce [_ rf init]
+ (cond-> init
+ ai-text
+ (rf {:type :text :text ai-text})
+
+ (seq data-parts)
+ (as-> r (reduce (fn [acc dp]
+ (rf acc {:type :data
+ :data-type (:type dp)
+ :data (:value dp dp)}))
+ r data-parts))))))
+ slackbot.query/generate-card-output (fn [card-id]
+ (swap! generate-card-output-calls conj {:card-id card-id})
+ {:type :image :content fake-png-bytes :card-name (str "Card " card-id)})
+ slackbot.query/generate-adhoc-output (fn [query & {:keys [display]}]
+ (swap! generate-adhoc-output-calls conj {:query query :display display})
+ (if (#{:bar :line :pie :area :row :scatter :funnel :waterfall :combo :progress :gauge :map}
+ display)
+ {:type :image :content fake-png-bytes}
+ {:type :table :content [{:type "table" :rows [] :column_settings []}]}))]
+ (body-fn {:post-calls post-calls
+ :delete-calls delete-calls
+ :update-calls update-calls
+ :image-calls image-calls
+ :generate-card-output-calls generate-card-output-calls
+ :generate-adhoc-output-calls generate-adhoc-output-calls
+ :ephemeral-calls ephemeral-calls
+ :ai-request-calls ai-request-calls
+ :stream-calls stream-calls
+ :append-text-calls append-text-calls
+ :stop-stream-calls stop-stream-calls
+ :add-reaction-calls add-reaction-calls
+ :remove-reaction-calls remove-reaction-calls
+ :set-status-calls set-status-calls
+ :fake-png-bytes fake-png-bytes}))))
diff --git a/enterprise/backend/test/metabase_enterprise/slackbot/uploads_test.clj b/enterprise/backend/test/metabase_enterprise/slackbot/uploads_test.clj
new file mode 100644
index 00000000000..c48723fc1d9
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/slackbot/uploads_test.clj
@@ -0,0 +1,307 @@
+(ns metabase-enterprise.slackbot.uploads-test
+ (:require
+ [clojure.java.io :as io]
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [metabase-enterprise.slackbot.client :as slackbot.client]
+ [metabase-enterprise.slackbot.test-util :as tu]
+ [metabase-enterprise.slackbot.uploads :as slackbot.uploads]
+ [metabase.channel.settings :as channel.settings]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]
+ [metabase.upload.db :as upload.db]
+ [metabase.upload.impl :as upload.impl]
+ [metabase.util :as u]))
+
+(set! *warn-on-reflection* true)
+
+(use-fixtures :once (fixtures/initialize :test-users))
+
+(defn- with-upload-mocks!
+ "Helper to set up common mocks for CSV upload tests.
+ Options:
+ - :uploads-enabled? - Whether uploads are enabled (default false)
+ - :can-create-upload? - Whether user can create uploads (default true)
+ - :upload-result - Result from create-csv-upload! (default success with id 123)
+ - :download-content - Content returned by download-slack-file (default valid CSV)
+
+ Calls body-fn with a map containing tracking atoms:
+ {:upload-calls, :download-calls}"
+ [{:keys [uploads-enabled? can-create-upload? upload-result download-content db-id]
+ :or {uploads-enabled? false
+ can-create-upload? true
+ upload-result {:id 123 :name "uploaded_data"}
+ download-content (.getBytes "col1,col2\nval1,val2")
+ db-id 1}}
+ body-fn]
+ (let [upload-calls (atom [])
+ download-calls (atom [])]
+ (mt/with-dynamic-fn-redefs
+ [upload.db/current-database (constantly (when uploads-enabled?
+ {:id db-id
+ :uploads_schema_name nil
+ :uploads_table_prefix nil}))
+ upload.impl/can-create-upload? (constantly can-create-upload?)
+ upload.impl/create-csv-upload! (fn [params]
+ (swap! upload-calls conj params)
+ upload-result)
+ slackbot.client/download-file-stream (fn [_client url]
+ (swap! download-calls conj url)
+ (io/input-stream download-content))]
+ (body-fn {:upload-calls upload-calls
+ :download-calls download-calls}))))
+
+(deftest csv-upload-disabled-test
+ (testing "POST /events with file upload when uploads are disabled"
+ (tu/with-slackbot-setup
+ (let [event-body (update tu/base-dm-event :event merge
+ {:subtype "file_share"
+ :text "Here's my data"
+ :files [tu/slack-csv-file]})]
+ (with-upload-mocks!
+ {:uploads-enabled? false}
+ (fn [{:keys [upload-calls]}]
+ (tu/with-slackbot-mocks
+ {:ai-text "CSV uploads are not enabled on this Metabase instance."}
+ (fn [{:keys [stop-stream-calls append-text-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(>= (count @stop-stream-calls) 1)
+ :done? true?
+ :timeout-ms 5000})
+ (testing "no upload was attempted"
+ (is (= 0 (count @upload-calls))))
+ (testing "AI responds with error message"
+ (is (some #(= "CSV uploads are not enabled on this Metabase instance." %)
+ @append-text-calls))))))))))))
+
+(deftest csv-upload-success-test
+ (testing "POST /events with successful CSV upload"
+ (tu/with-slackbot-setup
+ (let [event-body (update tu/base-dm-event :event merge
+ {:subtype "file_share"
+ :text "Here's my data"
+ :files [tu/slack-csv-file]})]
+ (with-upload-mocks!
+ {:uploads-enabled? true
+ :can-create-upload? true
+ :upload-result {:id 456 :name "Data"}}
+ (fn [{:keys [upload-calls download-calls]}]
+ (tu/with-slackbot-mocks
+ {:ai-text "Your CSV has been uploaded successfully as a model."}
+ (fn [{:keys [stop-stream-calls append-text-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(>= (count @stop-stream-calls) 1)
+ :done? true?
+ :timeout-ms 5000})
+ (testing "file was downloaded from Slack"
+ (is (= 1 (count @download-calls)))
+ (is (= (:url_private tu/slack-csv-file) (first @download-calls))))
+ (testing "upload was called with correct parameters"
+ (is (= 1 (count @upload-calls)))
+ (let [call (first @upload-calls)]
+ (is (= (:name tu/slack-csv-file) (:filename call)))))
+ (testing "AI responds with success message"
+ (is (some #(= "Your CSV has been uploaded successfully as a model." %)
+ @append-text-calls))))))))))))
+
+(deftest csv-upload-non-csv-skipped-test
+ (testing "POST /events with non-CSV file is skipped"
+ (tu/with-slackbot-setup
+ (let [event-body (update tu/base-dm-event :event merge
+ {:subtype "file_share"
+ :text "Here's my file"
+ :files [{:id "F123"
+ :name "document.pdf"
+ :filetype "pdf"
+ :url_private "https://files.slack.com/files/document.pdf"
+ :size 100}]})]
+ (with-upload-mocks!
+ {:uploads-enabled? true}
+ (fn [{:keys [upload-calls download-calls]}]
+ (tu/with-slackbot-mocks
+ {:ai-text "Only CSV files can be uploaded."}
+ (fn [{:keys [stop-stream-calls append-text-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(>= (count @stop-stream-calls) 1)
+ :done? true?
+ :timeout-ms 5000})
+ (testing "no download was attempted"
+ (is (= 0 (count @download-calls))))
+ (testing "no upload was attempted"
+ (is (= 0 (count @upload-calls))))
+ (testing "AI responds explaining PDF not supported"
+ (is (some #(= "Only CSV files can be uploaded." %)
+ @append-text-calls))))))))))))
+
+(deftest csv-upload-non-csv-no-text-test
+ (testing "POST /events with non-CSV file and no text responds directly without AI"
+ (tu/with-slackbot-setup
+ ;; No :text field - user uploaded file without typing anything
+ (let [event-body (-> tu/base-dm-event
+ (update :event merge
+ {:subtype "file_share"
+ :files [{:id "F123"
+ :name "query_result.xlsx"
+ :filetype "xlsx"
+ :url_private "https://files.slack.com/files/query_result.xlsx"
+ :size 100}]})
+ (update :event dissoc :text))]
+ (with-upload-mocks!
+ {:uploads-enabled? true}
+ (fn [{:keys [upload-calls download-calls]}]
+ (tu/with-slackbot-mocks
+ {:ai-text "This should not be called"}
+ (fn [{:keys [post-calls delete-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(>= (count @post-calls) 1)
+ :done? true?
+ :timeout-ms 5000})
+ ;; When AI is called, there are 2 posts (Thinking... then response) and 1 delete.
+ ;; When AI is skipped, there is just 1 post and no deletes.
+ (testing "AI was not called (only 1 post, no deletes)"
+ (is (= 1 (count @post-calls)))
+ (is (= 0 (count @delete-calls))))
+ (testing "no download was attempted"
+ (is (= 0 (count @download-calls))))
+ (testing "no upload was attempted"
+ (is (= 0 (count @upload-calls))))
+ (testing "responds directly with skip message"
+ #_{:clj-kondo/ignore [:unresolved-namespace]}
+ (let [message-text (:text (first @post-calls))]
+ (is (str/includes? message-text "can only process CSV and TSV"))
+ (is (str/includes? message-text "query_result.xlsx")))))))))))))
+
+(deftest csv-upload-mixed-files-test
+ (testing "POST /events with mix of CSV and non-CSV files"
+ (tu/with-slackbot-setup
+ (let [event-body (update tu/base-dm-event :event merge
+ {:subtype "file_share"
+ :text "Here are my files"
+ :files [(assoc tu/slack-csv-file :id "F1")
+ {:id "F2"
+ :name "report.pdf"
+ :filetype "pdf"
+ :url_private "https://files.slack.com/files/report.pdf"
+ :size 200}
+ {:id "F3"
+ :name "more_data.tsv"
+ :filetype "tsv"
+ :url_private "https://files.slack.com/files/more_data.tsv"
+ :size 150}]})]
+ (with-upload-mocks!
+ {:uploads-enabled? true
+ :upload-result {:id 789 :name "Uploaded Data"}}
+ (fn [{:keys [upload-calls download-calls]}]
+ (tu/with-slackbot-mocks
+ {:ai-text "Uploaded 2 files, skipped 1 non-CSV file."}
+ (fn [{:keys [stop-stream-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(>= (count @stop-stream-calls) 1)
+ :done? true?
+ :timeout-ms 5000})
+ (testing "only CSV/TSV files were downloaded"
+ (is (= 2 (count @download-calls)))
+ (is (= #{"https://files.slack.com/files/data.csv"
+ "https://files.slack.com/files/more_data.tsv"}
+ (set @download-calls))))
+ (testing "only CSV/TSV files were uploaded"
+ (is (= 2 (count @upload-calls)))))))))))))
+
+(deftest csv-upload-file-too-large-test
+ (testing "POST /events with file exceeding size limit"
+ (tu/with-slackbot-setup
+ (let [too-large-size (inc (* 200 1024 1024)) ;; Just over 200MB
+ event-body (update tu/base-dm-event :event merge
+ {:subtype "file_share"
+ :text "Here's my huge file"
+ :files [(assoc tu/slack-csv-file
+ :name "huge_data.csv"
+ :url_private "https://files.slack.com/files/huge_data.csv"
+ :size too-large-size)]})]
+ (with-upload-mocks!
+ {:uploads-enabled? true}
+ (fn [{:keys [upload-calls download-calls]}]
+ (tu/with-slackbot-mocks
+ {:ai-text "The file exceeds the 200MB size limit."}
+ (fn [{:keys [stop-stream-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(>= (count @stop-stream-calls) 1)
+ :done? true?
+ :timeout-ms 5000})
+ (testing "file was not downloaded due to size"
+ (is (= 0 (count @download-calls))))
+ (testing "upload was not attempted"
+ (is (= 0 (count @upload-calls)))))))))))))
+
+(deftest csv-upload-no-permission-test
+ (testing "POST /events with file upload when user lacks permission"
+ (tu/with-slackbot-setup
+ (let [event-body (update tu/base-dm-event :event merge
+ {:subtype "file_share"
+ :text "Here's my data"
+ :files [tu/slack-csv-file]})]
+ (with-upload-mocks!
+ {:uploads-enabled? true
+ :can-create-upload? false}
+ (fn [{:keys [upload-calls]}]
+ (tu/with-slackbot-mocks
+ {:ai-text "You don't have permission to upload files."}
+ (fn [{:keys [stop-stream-calls append-text-calls]}]
+ (let [response (mt/client :post 200 "ee/metabot-v3/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)]
+ (is (= "ok" response))
+ (u/poll {:thunk #(>= (count @stop-stream-calls) 1)
+ :done? true?
+ :timeout-ms 5000})
+ (testing "no upload was attempted"
+ (is (= 0 (count @upload-calls))))
+ (testing "AI responds with permission error"
+ (is (some #(= "You don't have permission to upload files." %)
+ @append-text-calls))))))))))))
+
+(deftest process-csv-file-streams-to-temp-file-test
+ (testing "process-csv-file streams download content through a temp file to the upload fn"
+ (let [csv-content "col1,col2\nfoo,bar\nbaz,qux"
+ uploaded-file (atom nil)]
+ (mt/with-dynamic-fn-redefs
+ [slackbot.client/download-file-stream (fn [_client _url]
+ (io/input-stream (.getBytes csv-content)))
+ upload.impl/create-csv-upload! (fn [{:keys [file] :as _params}]
+ (reset! uploaded-file (slurp file))
+ {:id 1 :name "test"})
+ ;; stub out the token lookup
+ channel.settings/unobfuscated-slack-app-token (constantly "xoxb-fake")]
+ (let [result (#'slackbot.uploads/process-csv-file
+ {:db_id 1 :schema_name nil :table_prefix nil}
+ {:name "test.csv" :url_private "https://example.com/test.csv" :size 100})]
+ (is (= 1 (:model-id result)))
+ (testing "file content was streamed correctly through temp file"
+ (is (= csv-content @uploaded-file))))))))
+
+(deftest ^:parallel csv-file-detection-test
+ (testing "csv-file? correctly identifies CSV/TSV files"
+ (is (true? (#'slackbot.uploads/csv-file? {:filetype "csv"})))
+ (is (true? (#'slackbot.uploads/csv-file? {:filetype "tsv"})))
+ (is (false? (#'slackbot.uploads/csv-file? {:filetype "pdf"})))
+ (is (false? (#'slackbot.uploads/csv-file? {:filetype "xlsx"})))
+ (is (false? (#'slackbot.uploads/csv-file? {:filetype nil})))
+ (is (false? (#'slackbot.uploads/csv-file? {})))))
diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj
index b461f0b1480..d6dd8785117 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/jwt_test.clj
@@ -979,9 +979,10 @@
(deftest jwt-token-not-configured-test
(testing "should not return a session token when jwt is not configured"
(mt/with-temporary-setting-values
- [jwt-enabled true
+ [jwt-enabled true
jwt-identity-provider-uri nil
- jwt-shared-secret nil]
+ jwt-shared-secret nil
+ slack-connect-enabled false]
(mt/with-temporary-setting-values [enable-embedding-sdk true]
(let [jwt-iat-time (buddy-util/now)
jwt-exp-time (+ (buddy-util/now) 3600)
diff --git a/enterprise/backend/test/metabase_enterprise/sso/integrations/slack_connect_test.clj b/enterprise/backend/test/metabase_enterprise/sso/integrations/slack_connect_test.clj
index 16bec564cba..3042a821300 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/integrations/slack_connect_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/integrations/slack_connect_test.clj
@@ -65,81 +65,52 @@
;;; -------------------------------------------------- Prerequisites Tests --------------------------------------------------
(deftest sso-prereqs-test
- (sso.test-setup/do-with-other-sso-types-disabled!
- (fn []
- (mt/with-additional-premium-features #{:sso-slack}
- (testing "SSO requests fail if Slack Connect hasn't been configured or enabled"
- (mt/with-temporary-setting-values
- [slack-connect-enabled false
- slack-connect-client-id nil
- slack-connect-client-secret nil]
- (is
- (partial=
- {:cause "SSO has not been enabled and/or configured",
- :data {:status "error-sso-disabled", :status-code 400},
- :message "SSO has not been enabled and/or configured",
- :status "error-sso-disabled"}
- (mt/client :get 400 "/auth/sso"
- {:request-options {:redirect-strategy :none}}
- :preferred_method "slack-connect"))))
-
- (testing "SSO requests fail if they don't have a valid premium-features token"
- (sso.test-setup/call-with-default-slack-config!
- (fn []
- (mt/with-premium-features #{}
- (is
- (partial=
- {:cause "SSO has not been enabled and/or configured",
- :data {:status "error-sso-disabled", :status-code 400},
- :message "SSO has not been enabled and/or configured",
- :status "error-sso-disabled"}
- (mt/client :get 400 "/auth/sso"
- {:request-options {:redirect-strategy :none}}
- :preferred_method "slack-connect"))))))))
-
- (testing "SSO requests fail if Slack Connect is enabled but hasn't been configured"
- (mt/with-temporary-setting-values
- [slack-connect-enabled true
- slack-connect-client-id nil]
- (is
- (partial=
- {:cause "SSO has not been enabled and/or configured",
- :data {:status "error-sso-disabled", :status-code 400},
- :message "SSO has not been enabled and/or configured",
- :status "error-sso-disabled"}
- (mt/client :get 400 "/auth/sso"
- {:request-options {:redirect-strategy :none}}
- :preferred_method "slack-connect")))))
-
- (testing "SSO requests fail if Slack Connect is configured but hasn't been enabled"
- (mt/with-temporary-setting-values
- [slack-connect-enabled false
- slack-connect-client-id "test-slack-client-id"
- slack-connect-client-secret "test-slack-client-secret"]
- (is
- (partial=
- {:cause "SSO has not been enabled and/or configured",
- :data {:status "error-sso-disabled", :status-code 400},
- :message "SSO has not been enabled and/or configured",
- :status "error-sso-disabled"}
- (mt/client :get 400 "/auth/sso"
- {:request-options {:redirect-strategy :none}}
- :preferred_method "slack-connect")))))
-
- (testing "The client secret must also be included for SSO to be configured"
- (mt/with-temporary-setting-values
- [slack-connect-enabled true
- slack-connect-client-id "test-slack-client-id"
- slack-connect-client-secret nil]
- (is
- (partial=
- {:cause "SSO has not been enabled and/or configured",
- :data {:status "error-sso-disabled", :status-code 400},
- :message "SSO has not been enabled and/or configured",
- :status "error-sso-disabled"}
- (mt/client :get 400 "/auth/sso"
- {:request-options {:redirect-strategy :none}}
- :preferred_method "slack-connect")))))))))
+ (with-test-encryption!
+ (sso.test-setup/do-with-other-sso-types-disabled!
+ (fn []
+ (mt/with-additional-premium-features #{:sso-slack}
+ (testing "SSO requests fail if Slack Connect hasn't been configured or enabled"
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled false
+ slack-connect-client-id nil
+ slack-connect-client-secret nil]
+ (is (= "Slack Connect is not enabled"
+ (mt/client :get 400 "/auth/sso/slack-connect"
+ {:request-options {:redirect-strategy :none}})))))
+
+ (testing "SSO requests fail if Slack Connect is enabled but hasn't been configured"
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled true
+ slack-connect-client-id nil]
+ (is (= "Slack Connect is not enabled"
+ (mt/client :get 400 "/auth/sso/slack-connect"
+ {:request-options {:redirect-strategy :none}})))))
+
+ (testing "SSO requests fail if Slack Connect is configured but hasn't been enabled"
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled false
+ slack-connect-client-id "test-slack-client-id"
+ slack-connect-client-secret "test-slack-client-secret"]
+ (is (= "Slack Connect is not enabled"
+ (mt/client :get 400 "/auth/sso/slack-connect"
+ {:request-options {:redirect-strategy :none}})))))
+
+ (testing "The client secret must also be included for SSO to be configured"
+ (mt/with-temporary-setting-values
+ [slack-connect-enabled true
+ slack-connect-client-id "test-slack-client-id"
+ slack-connect-client-secret nil]
+ (is (= "Slack Connect is not enabled"
+ (mt/client :get 400 "/auth/sso/slack-connect"
+ {:request-options {:redirect-strategy :none}}))))))
+
+ (testing "SSO requests fail if they don't have a valid premium-features token"
+ (sso.test-setup/call-with-default-slack-config!
+ (fn []
+ (mt/with-premium-features #{}
+ (let [response (mt/client :get 402 "/auth/sso/slack-connect"
+ {:request-options {:redirect-strategy :none}})]
+ (is (str/includes? (str (:message response) response) "paid feature")))))))))))
;;; -------------------------------------------------- Redirect Tests --------------------------------------------------
@@ -148,9 +119,8 @@
(with-test-encryption!
(sso.test-setup/with-slack-default-setup!
(with-successful-oidc!
- (let [result (mt/client-full-response :get 302 "/auth/sso"
+ (let [result (mt/client-full-response :get 302 "/auth/sso/slack-connect"
{:request-options {:redirect-strategy :none}}
- :preferred_method "slack-connect"
:redirect default-redirect-uri)
redirect-url (get-in result [:headers "Location"])
oidc-state-cookie (->> (get-in result [:headers "Set-Cookie"])
@@ -170,7 +140,7 @@
(is (= "slack-connect" (:provider state-data))))))))))))
(deftest multiple-sso-methods-test
- (testing "with SAML and Slack Connect configured, a GET request with preferred_method=slack-connect should redirect to Slack"
+ (testing "with SAML and Slack Connect configured, a GET request to /auth/sso/slack-connect should redirect to Slack"
(with-test-encryption!
(sso.test-setup/with-slack-default-setup!
(mt/with-temporary-setting-values
@@ -178,9 +148,8 @@
saml-identity-provider-uri "http://test.idp.metabase.com"
saml-identity-provider-certificate (slurp "test_resources/sso/auth0-public-idp.cert")]
(with-successful-oidc!
- (let [result (mt/client-full-response :get 302 "/auth/sso"
+ (let [result (mt/client-full-response :get 302 "/auth/sso/slack-connect"
{:request-options {:redirect-strategy :none}}
- :preferred_method "slack-connect"
:redirect default-redirect-uri)
redirect-url (get-in result [:headers "Location"])]
(is (str/starts-with? redirect-url "http://example.com/slack")))))))))
@@ -188,12 +157,15 @@
;;; -------------------------------------------------- POST Not Allowed Tests --------------------------------------------------
(deftest post-not-allowed-test
- (testing "POST requests should return 405 Method Not Allowed for OIDC"
+ (testing "slack-connect is no longer available via the old POST /auth/sso multimethod dispatch"
(sso.test-setup/with-slack-default-setup!
- (let [response (mt/client-full-response :post 405 "/auth/sso"
- {:request-options {:content-type :x-www-form-urlencoded
- :form-params {:preferred_method "slack-connect"}}})]
- (is (= "GET" (get-in response [:headers "Allow"])))))))
+ ;; The old endpoint returned 405 via the defmethod sso-post :slack-connect.
+ ;; Now that slack-connect has been removed from the multimethod dispatch and
+ ;; uses dedicated GET routes, POSTing with preferred_method=slack-connect
+ ;; should no longer reach slack-connect code. With no other SSO enabled,
+ ;; the default dispatch returns "SSO has not been enabled and/or configured".
+ (is (some? (mt/client :post 400 "/auth/sso"
+ {:request-options {:content-type :x-www-form-urlencoded}}))))))
;;; -------------------------------------------------- Callback Tests --------------------------------------------------
@@ -201,7 +173,7 @@
(testing "callback should fail if state cookie is missing"
(with-test-encryption!
(sso.test-setup/with-slack-default-setup!
- (let [response (mt/client-full-response :get 401 "/auth/sso"
+ (let [response (mt/client-full-response :get 401 "/auth/sso/slack-connect/callback"
{:request-options {:redirect-strategy :none}}
:code "test-code"
:state "some-state")]
@@ -214,16 +186,15 @@
(sso.test-setup/with-slack-default-setup!
(with-successful-oidc!
;; First, initiate auth to set state cookie
- (let [init-response (mt/client-full-response :get 302 "/auth/sso"
+ (let [init-response (mt/client-full-response :get 302 "/auth/sso/slack-connect"
{:request-options {:redirect-strategy :none}}
- :preferred_method "slack-connect"
:redirect default-redirect-uri)
;; Convert Set-Cookie headers to Cookie header format (extract name=value parts)
set-cookies (get-in init-response [:headers "Set-Cookie"])
cookie-header (->> set-cookies
(map #(first (str/split % #";"))) ; Extract name=value before first ;
(str/join "; "))
- response (mt/client-real-response :get 401 "/auth/sso"
+ response (mt/client-real-response :get 401 "/auth/sso/slack-connect/callback"
{:request-options {:redirect-strategy :none
:headers {"Cookie" cookie-header}}}
:code "test-code"
@@ -237,16 +208,15 @@
(sso.test-setup/with-slack-default-setup!
(with-successful-oidc!
;; First, initiate auth to set state cookie
- (let [init-response (mt/client-full-response :get 302 "/auth/sso"
+ (let [init-response (mt/client-full-response :get 302 "/auth/sso/slack-connect"
{:request-options {:redirect-strategy :none}}
- :preferred_method "slack-connect"
:redirect default-redirect-uri)
;; Convert Set-Cookie headers to Cookie header format
set-cookies (get-in init-response [:headers "Set-Cookie"])
cookie-header (->> set-cookies
(map #(first (str/split % #";")))
(str/join "; "))
- response (mt/client-real-response :get 302 "/auth/sso"
+ response (mt/client-real-response :get 302 "/auth/sso/slack-connect/callback"
{:request-options {:redirect-strategy :none
:headers {"Cookie" cookie-header}}}
:code "test-code"
@@ -262,9 +232,8 @@
(sso.test-setup/with-slack-default-setup!
(mt/with-temporary-setting-values
[slack-connect-authentication-mode "link-only"]
- (let [response (mt/client-full-response :get 401 "/auth/sso"
+ (let [response (mt/client-full-response :get 401 "/auth/sso/slack-connect"
{:request-options {:redirect-strategy :none}}
- :preferred_method "slack-connect"
:redirect default-redirect-uri)]
(is (str/includes? (str (get response :body)) "authenticated session"))))))))
@@ -276,9 +245,8 @@
[slack-connect-authentication-mode "link-only"]
(with-successful-oidc!
(let [response (mt/user-http-request-full-response
- :rasta :get 302 "/auth/sso"
+ :rasta :get 302 "/auth/sso/slack-connect"
{:request-options {:redirect-strategy :none}}
- :preferred_method "slack-connect"
:redirect default-redirect-uri)]
(is (str/starts-with? (get-in response [:headers "Location"]) "http://example.com/slack")))))))))
@@ -290,15 +258,10 @@
(doseq [redirect-uri ["https://badsite.com"
"//badsite.com"
"https:///badsite.com"]]
- (is
- (= "Invalid redirect URL"
- (->
- (mt/client
- :get 400 "/auth/sso"
- {:request-options {:redirect-strategy :none}}
- :preferred_method "slack-connect"
- :redirect redirect-uri)
- :message)))))))
+ (let [result (mt/client :get 400 "/auth/sso/slack-connect"
+ {:request-options {:redirect-strategy :none}}
+ :redirect redirect-uri)]
+ (is (str/includes? (str (or (:message result) result)) "Invalid redirect URL")))))))
;;; -------------------------------------------------- User Provisioning Tests --------------------------------------------------
@@ -313,16 +276,15 @@
(boolean (seq (t2/select :model/User :%lower.email "[email protected]"))))]
(is (false? (new-user-exists?)))
;; Initiate auth
- (let [init-response (mt/client-full-response :get 302 "/auth/sso"
+ (let [init-response (mt/client-full-response :get 302 "/auth/sso/slack-connect"
{:request-options {:redirect-strategy :none}}
- :preferred_method "slack-connect"
:redirect default-redirect-uri)
;; Convert Set-Cookie headers to Cookie header format
set-cookies (get-in init-response [:headers "Set-Cookie"])
cookie-header (->> set-cookies
(map #(first (str/split % #";")))
(str/join "; "))
- response (mt/client-real-response :get 302 "/auth/sso"
+ response (mt/client-real-response :get 302 "/auth/sso/slack-connect/callback"
{:request-options {:redirect-strategy :none
:headers {"Cookie" cookie-header}}}
:code "test-code"
@@ -365,16 +327,15 @@
:error :user-provisioning-disabled
:message "Sorry, but you'll need a test account to view this page. Please contact your administrator."})]
;; Initiate auth
- (let [init-response (mt/client-full-response :get 302 "/auth/sso"
+ (let [init-response (mt/client-full-response :get 302 "/auth/sso/slack-connect"
{:request-options {:redirect-strategy :none}}
- :preferred_method "slack-connect"
:redirect default-redirect-uri)
set-cookies (get-in init-response [:headers "Set-Cookie"])
cookie-header (->> set-cookies
(map #(first (str/split % #";")))
(str/join "; "))]
;; Try callback - should fail
- (mt/client-real-response :get 401 "/auth/sso"
+ (mt/client-real-response :get 401 "/auth/sso/slack-connect/callback"
{:request-options {:redirect-strategy :none
:headers {"Cookie" cookie-header}}}
:code "test-code"
diff --git a/enterprise/backend/test/metabase_enterprise/sso/providers/slack_connect_test.clj b/enterprise/backend/test/metabase_enterprise/sso/providers/slack_connect_test.clj
index 4d6262cf3e6..81b2431c68e 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/providers/slack_connect_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/providers/slack_connect_test.clj
@@ -40,19 +40,19 @@
(mt/with-temporary-setting-values
[slack-connect-client-id "test-client-id"
slack-connect-client-secret "test-secret"]
- (let [request {:redirect-uri "https://metabase.example.com/auth/sso"}
+ (let [request {:redirect-uri "https://metabase.example.com/auth/sso/slack-connect/callback"}
config (#'metabase-enterprise.sso.providers.slack-connect/build-slack-oidc-config request)]
(is (= "test-client-id" (:client-id config)))
(is (= "test-secret" (:client-secret config)))
(is (= "https://slack.com" (:issuer-uri config)))
(is (= ["openid" "profile" "email"] (:scopes config)))
- (is (= "https://metabase.example.com/auth/sso" (:redirect-uri config))))))
+ (is (= "https://metabase.example.com/auth/sso/slack-connect/callback" (:redirect-uri config))))))
(testing "Returns nil when client ID is missing"
(mt/with-temporary-setting-values
[slack-connect-client-id nil
slack-connect-client-secret "test-secret"]
- (let [request {:redirect-uri "https://metabase.example.com/auth/sso"}
+ (let [request {:redirect-uri "https://metabase.example.com/auth/sso/slack-connect/callback"}
config (#'metabase-enterprise.sso.providers.slack-connect/build-slack-oidc-config request)]
(is (nil? config)))))
@@ -60,7 +60,7 @@
(mt/with-temporary-setting-values
[slack-connect-client-id "test-client-id"
slack-connect-client-secret nil]
- (let [request {:redirect-uri "https://metabase.example.com/auth/sso"}
+ (let [request {:redirect-uri "https://metabase.example.com/auth/sso/slack-connect/callback"}
config (#'metabase-enterprise.sso.providers.slack-connect/build-slack-oidc-config request)]
(is (nil? config))))))
@@ -166,7 +166,7 @@
(let [request {:code "test-code"
:state "test-state"
:oidc-nonce "test-nonce"
- :redirect-uri "https://metabase.example.com/auth/sso"
+ :redirect-uri "https://metabase.example.com/auth/sso/slack-connect/callback"
:authenticated-user (delay nil)}
result (auth-identity/authenticate :provider/slack-connect request)]
;; The presence of :code indicates callback, so should not error even without authenticated-user
@@ -200,7 +200,7 @@
(let [request {:code "test-code"
:state "test-state"
:oidc-nonce "test-nonce"
- :redirect-uri "https://metabase.example.com/auth/sso"}
+ :redirect-uri "https://metabase.example.com/auth/sso/slack-connect/callback"}
result (auth-identity/authenticate :provider/slack-connect request)]
(is (= :slack (get-in result [:user-data :sso_source])))
(is (= "U12345678" (get-in result [:user-data :login_attributes "slack-user-id"])))
@@ -242,7 +242,7 @@
(let [initial-session-count (t2/count :model/Session :user_id (:id user))
request {:code "test-code"
:state "test-state"
- :redirect-uri "https://metabase.example.com/auth/sso"
+ :redirect-uri "https://metabase.example.com/auth/sso/slack-connect/callback"
:authenticated-user (delay user)
:device-info {:device_id "test-device" :device_description "Test Device" :ip_address "127.0.0.1" :embedded false}}
result (auth-identity/login! :provider/slack-connect request)]
@@ -291,7 +291,7 @@
(try
(let [request {:code "test-code"
:state "test-state"
- :redirect-uri "https://metabase.example.com/auth/sso"
+ :redirect-uri "https://metabase.example.com/auth/sso/slack-connect/callback"
:device-info {:device_id "test-device" :device_description "Test Device" :ip_address "127.0.0.1" :embedded false}}
result (auth-identity/login! :provider/slack-connect request)]
(is (true? (:success? result)) "Login should succeed")
@@ -343,7 +343,7 @@
:email "[email protected]"}})]
(let [request {:code "test-code"
:state "test-state"
- :redirect-uri "https://metabase.example.com/auth/sso"
+ :redirect-uri "https://metabase.example.com/auth/sso/slack-connect/callback"
:device-info {:device_id "test-device" :device_description "Test Device" :ip_address "127.0.0.1" :embedded false}}
result (auth-identity/login! :provider/slack-connect request)]
(is (true? (:success? result)) "Login should succeed")
@@ -391,7 +391,7 @@
(let [initial-session-count (t2/count :model/Session :user_id (:id user))
request {:code "test-code"
:state "test-state"
- :redirect-uri "https://metabase.example.com/auth/sso"
+ :redirect-uri "https://metabase.example.com/auth/sso/slack-connect/callback"
:authenticated-user (delay user)
:device-info {:device_id "test-device" :device_description "Test Device" :ip_address "127.0.0.1" :embedded false}}
result (auth-identity/login! :provider/slack-connect request)]
diff --git a/enterprise/backend/test/metabase_enterprise/sso/test_setup.clj b/enterprise/backend/test/metabase_enterprise/sso/test_setup.clj
index 949825668e2..3d74d39c795 100644
--- a/enterprise/backend/test/metabase_enterprise/sso/test_setup.clj
+++ b/enterprise/backend/test/metabase_enterprise/sso/test_setup.clj
@@ -40,13 +40,14 @@
(t2/update! :model/User {:email "[email protected]"} {:first_name "Rasta" :last_name "Toucan" :sso_source nil})))))
(defn do-with-other-sso-types-disabled!
- "Execute `thunk` with LDAP, SAML, and JWT SSO types disabled.
+ "Execute `thunk` with LDAP, SAML, JWT, and Slack Connect SSO types disabled.
Useful when testing a specific SSO provider in isolation."
[thunk]
(mt/with-temporary-setting-values
- [ldap-enabled false
- saml-enabled false
- jwt-enabled false]
+ [ldap-enabled false
+ saml-enabled false
+ jwt-enabled false
+ slack-connect-enabled false]
(thunk)))
;;; -------------------------------------------------- SAML Setup --------------------------------------------------
diff --git a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/index.ts b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/index.ts
index 77a05580ee0..37210a92d9b 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/index.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/index.ts
@@ -2,4 +2,3 @@ export {
aiStreamingQuery,
findMatchingInflightAiStreamingRequests,
} from "./requests";
-export type { JSONValue } from "./types";
diff --git a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/process-stream.ts b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/process-stream.ts
index b82ba056487..7d501a99a48 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/process-stream.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/process-stream.ts
@@ -1,7 +1,7 @@
import { isMatching, match } from "ts-pattern";
import _ from "underscore";
-import type { MetabotHistory } from "metabase-types/api";
+import type { JSONValue, MetabotHistory } from "metabase-types/api";
import {
type KnownDataPart,
@@ -11,7 +11,6 @@ import {
toolCallPartSchema,
toolResultPartSchema,
} from "./schemas";
-import type { JSONValue } from "./types";
const StreamingPartTypeRegistry = {
TEXT: "0",
diff --git a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/requests.ts b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/requests.ts
index 9f4895251e5..e03633d4e38 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/requests.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/requests.ts
@@ -1,9 +1,9 @@
import { nanoid } from "@reduxjs/toolkit";
import api from "metabase/lib/api";
+import type { JSONValue } from "metabase-types/api";
import { type AIStreamingConfig, processChatResponse } from "./process-stream";
-import type { JSONValue } from "./types";
// keep track of inflight requests so that can be cancelled programmitcally from other
// places in the app w/o passing references to the abort controller directly
diff --git a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/types.ts b/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/types.ts
deleted file mode 100644
index 67704de56a6..00000000000
--- a/enterprise/frontend/src/metabase-enterprise/api/ai-streaming/types.ts
+++ /dev/null
@@ -1,11 +0,0 @@
-/**
-A JSON value can be a string, number, boolean, object, array, or null.
-JSON values can be serialized and deserialized by the JSON.stringify and JSON.parse methods.
- */
-export type JSONValue =
- | null
- | string
- | number
- | boolean
- | { [value: string]: JSONValue }
- | Array<JSONValue>;
diff --git a/enterprise/frontend/src/metabase-enterprise/api/metabot.ts b/enterprise/frontend/src/metabase-enterprise/api/metabot.ts
index 2f94349f496..c21ee4c01c5 100644
--- a/enterprise/frontend/src/metabase-enterprise/api/metabot.ts
+++ b/enterprise/frontend/src/metabase-enterprise/api/metabot.ts
@@ -5,6 +5,7 @@ import type {
MetabotGenerateContentResponse,
MetabotId,
MetabotInfo,
+ MetabotSlackSettings,
SuggestedMetabotPromptsRequest,
SuggestedMetabotPromptsResponse,
} from "metabase-types/api";
@@ -95,6 +96,17 @@ export const metabotApi = EnterpriseApi.injectEndpoints({
body: params,
}),
}),
+ updateMetabotSlackSettings: builder.mutation<
+ { ok: boolean },
+ MetabotSlackSettings
+ >({
+ query: (settings) => ({
+ method: "PUT",
+ url: "/api/ee/metabot-v3/slack/settings",
+ body: settings,
+ }),
+ invalidatesTags: ["session-properties"],
+ }),
}),
});
@@ -106,4 +118,5 @@ export const {
useRegenerateSuggestedMetabotPromptsMutation,
useLazyMetabotGenerateContentQuery,
useSubmitMetabotFeedbackMutation,
+ useUpdateMetabotSlackSettingsMutation,
} = metabotApi;
diff --git a/enterprise/frontend/src/metabase-enterprise/auth/middleware/session-middleware.js b/enterprise/frontend/src/metabase-enterprise/auth/middleware/session-middleware.js
index e137288a112..11ab7d380b8 100644
--- a/enterprise/frontend/src/metabase-enterprise/auth/middleware/session-middleware.js
+++ b/enterprise/frontend/src/metabase-enterprise/auth/middleware/session-middleware.js
@@ -17,6 +17,15 @@ const getRedirectUrl = () => {
: null;
};
+const preventImmedidateRedirect = () => {
+ // defer to login page to redirect if sent directly. `getIsLoggedIn` returns if a session cookie
+ // is present, but does not validate. in the case of an invalid token at the start of an OAuth
+ // flow, the user can get stuck with a "Account linking requires an authenticated session" error
+ // without an obvious way to remedy. by defering the the login page we can ensure cookie validation
+ // and give the user a chance to re-auth if needed.
+ return window.location.pathname.startsWith("/auth/login");
+};
+
export const createSessionMiddleware = (
resetActions = [],
setInterval = global.setInterval,
@@ -32,7 +41,7 @@ export const createSessionMiddleware = (
// get the redirect url before refreshing the session because after the refresh the url will be reset
const redirectUrl = getRedirectUrl();
- if (wasLoggedIn && !!redirectUrl) {
+ if (wasLoggedIn && !!redirectUrl && !preventImmedidateRedirect()) {
store.dispatch(replace(redirectUrl));
}
diff --git a/enterprise/frontend/src/metabase-enterprise/auth/middleware/session-middleware.unit.spec.js b/enterprise/frontend/src/metabase-enterprise/auth/middleware/session-middleware.unit.spec.js
index ab6a6975442..d3eccb8c446 100644
--- a/enterprise/frontend/src/metabase-enterprise/auth/middleware/session-middleware.unit.spec.js
+++ b/enterprise/frontend/src/metabase-enterprise/auth/middleware/session-middleware.unit.spec.js
@@ -119,13 +119,32 @@ describe("createSessionMiddleware", () => {
});
describe("logged in redirect", () => {
- beforeEach(() => {
+ beforeEach(() => {});
+
+ it("should not redirect to the redirectUrl if visiting login page", async () => {
changeJSDOMURL(
"https://metabase.com/auth/login?redirect=%2Fquestion%2F1%3Fquery%3D5%23hash",
);
+
+ Cookie.get = jest
+ .fn()
+ .mockImplementationOnce(() => "stale")
+ .mockImplementationOnce(() => "stale");
+
+ const { handleAction, dispatchMock } = setup();
+
+ handleAction(actionStub);
+ clock.tick(COOKIE_POOLING_TIMEOUT);
+
+ expect(dispatchMock).not.toHaveBeenCalled();
+ expect(replace).not.toHaveBeenCalled();
});
it("should redirect to the redirectUrl", async () => {
+ changeJSDOMURL(
+ "https://metabase.com/some-route?redirect=%2Fquestion%2F1%3Fquery%3D5%23hash",
+ );
+
Cookie.get = jest
.fn()
.mockImplementationOnce(() => "alive")
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotAdminPage.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotAdminPage.tsx
index 4f02cd7a11f..b70c51707c3 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotAdminPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotAdminPage.tsx
@@ -1,17 +1,10 @@
import { useDisclosure } from "@mantine/hooks";
import type { ReactNode } from "react";
-import { useEffect, useMemo } from "react";
import { IndexRoute, Route } from "react-router";
-import { push } from "react-router-redux";
import { P, match } from "ts-pattern";
import { c, jt, t } from "ttag";
-import _ from "underscore";
import ErrorBoundary from "metabase/ErrorBoundary";
-import {
- AdminNavItem,
- AdminNavWrapper,
-} from "metabase/admin/components/AdminNav";
import { SettingsSection } from "metabase/admin/components/SettingsSection";
import { SettingHeader } from "metabase/admin/settings/components/SettingHeader";
import { skipToken, useGetCollectionQuery } from "metabase/api";
@@ -22,7 +15,6 @@ import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErr
import { CollectionPickerModal } from "metabase/common/components/Pickers/CollectionPicker";
import { useToast } from "metabase/common/hooks";
import { getIcon } from "metabase/lib/icon";
-import { useDispatch } from "metabase/lib/redux";
import {
Box,
Button,
@@ -50,6 +42,7 @@ import type {
} from "metabase-types/api";
import { MetabotPromptSuggestionPane } from "./MetabotAdminSuggestedPrompts";
+import { MetabotNavPane } from "./MetabotNavPane";
import { useMetabotIdPath } from "./utils";
export function getAdminRoutes() {
@@ -130,41 +123,6 @@ export function MetabotAdminPage() {
);
}
-function MetabotNavPane() {
- const { data, isLoading } = useListMetabotsQuery();
- const metabotId = useMetabotIdPath();
- const dispatch = useDispatch();
-
- const metabots = useMemo(() => _.sortBy(data?.items ?? [], "id"), [data]);
-
- useEffect(() => {
- const hasMetabotId = metabots?.some((metabot) => metabot.id === metabotId);
-
- if (!hasMetabotId && metabots?.length) {
- dispatch(push(`/admin/metabot/${metabots[0]?.id}`));
- }
- }, [metabots, metabotId, dispatch]);
-
- if (isLoading || !data) {
- return null;
- }
-
- return (
- <Flex direction="column" flex="0 0 auto">
- <AdminNavWrapper>
- {metabots?.map((metabot) => (
- <AdminNavItem
- key={metabot.id}
- icon="metabot"
- label={metabot.name}
- path={`/admin/metabot/${metabot.id}`}
- />
- ))}
- </AdminNavWrapper>
- </Flex>
- );
-}
-
function MetabotEnabledToggle({
settingKey,
isEmbedMetabot = false,
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotNavPane.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotNavPane.tsx
new file mode 100644
index 00000000000..561dd31f791
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotNavPane.tsx
@@ -0,0 +1,27 @@
+import { t } from "ttag";
+
+import {
+ AdminNavItem,
+ AdminNavWrapper,
+} from "metabase/admin/components/AdminNav";
+import { Flex } from "metabase/ui";
+import { FIXED_METABOT_IDS } from "metabase-enterprise/metabot/constants";
+
+export function MetabotNavPane() {
+ return (
+ <Flex direction="column" flex="0 0 auto">
+ <AdminNavWrapper>
+ <AdminNavItem
+ icon="metabot"
+ label={t`Metabot`}
+ path={`/admin/metabot/${FIXED_METABOT_IDS.DEFAULT}`}
+ />
+ <AdminNavItem
+ icon="embed"
+ label={t`Embedded Metabot`}
+ path={`/admin/metabot/${FIXED_METABOT_IDS.EMBEDDED}`}
+ />
+ </AdminNavWrapper>
+ </Flex>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotSlackSetup.module.css b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotSlackSetup.module.css
new file mode 100644
index 00000000000..e1f7a3050c7
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotSlackSetup.module.css
@@ -0,0 +1,16 @@
+.copyButton {
+ display: inline-flex;
+ background-color: var(--mb-color-brand);
+ color: var(--mb-color-text-primary-inverse);
+ align-items: center;
+ font-weight: bold;
+ padding: 0.75rem 1rem;
+ border-radius: 6px;
+ border: none;
+ cursor: pointer;
+
+ &:hover {
+ opacity: 0.88;
+ transition: all 200ms linear;
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotSlackSetup.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotSlackSetup.tsx
new file mode 100644
index 00000000000..300b7060c5b
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotSlackSetup.tsx
@@ -0,0 +1,250 @@
+import { useDisclosure } from "@mantine/hooks";
+import { useEffect, useState } from "react";
+import { P, match } from "ts-pattern";
+import { c, t } from "ttag";
+import * as Yup from "yup";
+
+import { SettingsSection } from "metabase/admin/components/SettingsSection";
+import { BasicAdminSettingInput } from "metabase/admin/settings/components/widgets/AdminSettingInput";
+import {
+ useGetSlackAppInfoQuery,
+ useGetSlackManifestQuery,
+} from "metabase/api/slack";
+import { useAdminSetting, useAdminSettings } from "metabase/api/utils/settings";
+import { ConfirmModal } from "metabase/common/components/ConfirmModal";
+import { ExternalLink } from "metabase/common/components/ExternalLink";
+import { useDocsUrl, useSetting } from "metabase/common/hooks";
+import {
+ Form,
+ FormErrorMessage,
+ FormProvider,
+ FormSubmitButton,
+ FormTextInput,
+} from "metabase/forms";
+import * as Errors from "metabase/lib/errors";
+import { Accordion, Button, Flex, Stack, Text } from "metabase/ui";
+import { useUpdateMetabotSlackSettingsMutation } from "metabase-enterprise/api/metabot";
+import type { SlackAppInfo } from "metabase-types/api/slack";
+
+import {
+ EncryptionRequiredAlert,
+ MissingScopesAlert,
+} from "./MetabotSlackSetupAlerts";
+
+const VALIDATION_SCHEMA = Yup.object({
+ "slack-connect-client-id": Yup.string().required(Errors.required),
+ "slack-connect-client-secret": Yup.string().required(Errors.required),
+ "metabot-slack-signing-secret": Yup.string().required(Errors.required),
+});
+
+type MetabotSlackSettingsFormValues = {
+ "slack-connect-client-id": string | null | undefined;
+ "slack-connect-client-secret": string | null | undefined;
+ "metabot-slack-signing-secret": string | null | undefined;
+};
+
+const MetabotSlackSettingsForm = ({
+ appInfo,
+ values,
+ isConfigured,
+}: {
+ appInfo?: SlackAppInfo;
+ values: MetabotSlackSettingsFormValues;
+ isConfigured: boolean;
+}) => {
+ const [updateMetabotSlackSettings] = useUpdateMetabotSlackSettingsMutation();
+
+ const basicInfoUrl = appInfo?.app_id
+ ? `https://api.slack.com/apps/${appInfo.app_id}/general`
+ : `https://api.slack.com/apps`;
+
+ const basicInfoLink = (
+ <ExternalLink key="link" href={basicInfoUrl}>
+ {t`Basic Information`}
+ </ExternalLink>
+ );
+
+ return (
+ <Stack gap="sm">
+ <Text c="text-secondary">
+ {c("{0} is a link that says 'Basic Information'.")
+ .jt`You'll find this in your Slack app's ${basicInfoLink} settings.`}
+ </Text>
+ <FormProvider
+ initialValues={{
+ "slack-connect-client-id": values["slack-connect-client-id"] ?? "",
+ "slack-connect-client-secret":
+ values["slack-connect-client-secret"] ?? "",
+ "metabot-slack-signing-secret":
+ values["metabot-slack-signing-secret"] ?? "",
+ }}
+ validationSchema={VALIDATION_SCHEMA}
+ onSubmit={(values) => updateMetabotSlackSettings(values).unwrap()}
+ enableReinitialize
+ >
+ <Form>
+ <Stack gap="sm">
+ <FormTextInput
+ name="slack-connect-client-id"
+ label={t`Client ID`}
+ placeholder="123456789012.123456789012"
+ disabled={isConfigured}
+ />
+ <FormTextInput
+ name="slack-connect-client-secret"
+ label={t`Client Secret`}
+ placeholder="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+ disabled={isConfigured}
+ />
+ <FormTextInput
+ name="metabot-slack-signing-secret"
+ label={t`Signing Secret`}
+ placeholder="xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx"
+ disabled={isConfigured}
+ />
+ <FormErrorMessage />
+ {!isConfigured && (
+ <Flex justify="flex-end" mt="md">
+ <FormSubmitButton label={t`Save changes`} variant="filled" />
+ </Flex>
+ )}
+ </Stack>
+ </Form>
+ </FormProvider>
+ </Stack>
+ );
+};
+
+export function MetabotSlackSetup() {
+ const isSlackTokenValid = useSetting("slack-token-valid?") ?? false;
+ const isEncryptionEnabled = useSetting("encryption-enabled");
+
+ const { values } = useAdminSettings([
+ "slack-connect-client-id",
+ "slack-connect-client-secret",
+ "metabot-slack-signing-secret",
+ ] as const);
+ const isConfigured = Object.values(values).every(Boolean);
+
+ const { value: isEnabled, updateSetting: updateEnabledSetting } =
+ useAdminSetting("slack-connect-enabled");
+
+ const [updateMetabotSlackSettings] = useUpdateMetabotSlackSettingsMutation();
+ const [isOpened, { open: handleOpen, close: handleClose }] =
+ useDisclosure(false);
+
+ const handleRemove = () => {
+ updateMetabotSlackSettings({
+ "slack-connect-client-id": null,
+ "slack-connect-client-secret": null,
+ "metabot-slack-signing-secret": null,
+ });
+ handleClose();
+ };
+
+ const [shouldPollAppInfo, setShouldPollAppInfo] = useState(false);
+ const { data: manifest } = useGetSlackManifestQuery();
+
+ const { data: appInfo } = useGetSlackAppInfoQuery(undefined, {
+ skip: !isSlackTokenValid,
+ pollingInterval: shouldPollAppInfo ? 10 * 1000 : 0,
+ });
+
+ const hasMissingScopes = (appInfo?.scopes?.missing?.length ?? 0) > 0;
+ const notification = match({ isEncryptionEnabled, hasMissingScopes })
+ .with({ isEncryptionEnabled: false }, () => "encryption" as const)
+ .with({ hasMissingScopes: true }, () => "scopes" as const)
+ .otherwise(() => null);
+
+ useEffect(() => {
+ setShouldPollAppInfo(notification === "scopes");
+ }, [notification]);
+
+ // eslint-disable-next-line metabase/no-unconditional-metabase-links-render -- admin only page
+ const { url: encryptionDocsUrl } = useDocsUrl(
+ "operations-guide/encrypting-database-details-at-rest",
+ );
+
+ if (!isSlackTokenValid) {
+ return null;
+ }
+
+ return (
+ <>
+ <SettingsSection
+ title={t`Natural language questions in Slack`}
+ description={t`Add a few more details to unlock the full power of Metabot in Slack.`}
+ >
+ <Stack gap="lg">
+ {notification === "encryption" && (
+ <EncryptionRequiredAlert docsUrl={encryptionDocsUrl} />
+ )}
+
+ {notification === "scopes" && (
+ <MissingScopesAlert manifest={manifest} appInfo={appInfo} />
+ )}
+
+ {match({ notification, isConfigured })
+ .with({ isConfigured: true }, () => (
+ <>
+ <BasicAdminSettingInput
+ name="slack-connect-enabled"
+ inputType="boolean"
+ value={isEnabled}
+ switchLabel={t`Let people chat with Metabot`}
+ onChange={(next) =>
+ updateEnabledSetting({
+ key: "slack-connect-enabled",
+ value: !!next,
+ })
+ }
+ />
+ <ConnectionDetails>
+ <MetabotSlackSettingsForm
+ appInfo={appInfo}
+ values={values}
+ isConfigured={isConfigured}
+ />
+ </ConnectionDetails>
+ <Flex justify="flex-end">
+ <Button c="danger" onClick={handleOpen}>{t`Remove`}</Button>
+ </Flex>
+ </>
+ ))
+ .with({ notification: P.string }, () => null)
+ .with({ isConfigured: false }, () => (
+ <MetabotSlackSettingsForm
+ appInfo={appInfo}
+ values={values}
+ isConfigured={isConfigured}
+ />
+ ))
+ .exhaustive()}
+ </Stack>
+ </SettingsSection>
+ <ConfirmModal
+ opened={isOpened}
+ onClose={handleClose}
+ title={t`Clear Metabot settings?`}
+ message={t`This will remove the configuration needed to power Metabot. People will no longer be able to chat with Metabot in Slack until you reconfigure these settings.`}
+ confirmButtonText={t`Clear settings`}
+ onConfirm={handleRemove}
+ />
+ </>
+ );
+}
+
+function ConnectionDetails({ children }: { children: React.ReactNode }) {
+ return (
+ <Accordion variant="contained" radius="md">
+ <Accordion.Item value="connection">
+ <Accordion.Control>{t`View connection details`}</Accordion.Control>
+ <Accordion.Panel>
+ <Stack pt="md" pb="sm">
+ {children}
+ </Stack>
+ </Accordion.Panel>
+ </Accordion.Item>
+ </Accordion>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotSlackSetup.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotSlackSetup.unit.spec.tsx
new file mode 100644
index 00000000000..f95ba560be3
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotSlackSetup.unit.spec.tsx
@@ -0,0 +1,340 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import {
+ findRequests,
+ setupMetabotSlackSettingsEndpoint,
+ setupMetabotSlackSettingsEndpointWithError,
+ setupPropertiesEndpoints,
+ setupSettingsEndpoints,
+ setupSlackAppInfoEndpoint,
+ setupSlackManifestEndpoint,
+ setupUpdateSettingEndpoint,
+} from "__support__/server-mocks";
+import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import type { SlackAppInfo } from "metabase-types/api";
+import {
+ createMockSettingDefinition,
+ createMockSettings,
+ createMockSlackAppInfo,
+} from "metabase-types/api/mocks";
+import { createMockSettingsState } from "metabase-types/store/mocks";
+
+import { MetabotSlackSetup } from "./MetabotSlackSetup";
+
+const CONFIGURED = {
+ clientId: "123.456",
+ clientSecret: "secret123",
+ signingSecret: "signing123",
+} as const;
+
+const MISSING_SCOPES = createMockSlackAppInfo({
+ scopes: {
+ actual: ["chat:write"],
+ required: ["chat:write", "im:history"],
+ missing: ["im:history"],
+ extra: [],
+ },
+});
+
+interface SetupOptions {
+ isSlackTokenValid?: boolean;
+ isEncryptionEnabled?: boolean;
+ clientId?: string | null;
+ clientSecret?: string | null;
+ signingSecret?: string | null;
+ isEnabled?: boolean;
+ appInfo?: Partial<SlackAppInfo>;
+}
+
+const setup = async ({
+ isSlackTokenValid = true,
+ isEncryptionEnabled = true,
+ clientId = null,
+ clientSecret = null,
+ signingSecret = null,
+ isEnabled = false,
+ appInfo = {},
+}: SetupOptions = {}) => {
+ const settings = createMockSettings({
+ "slack-token-valid?": isSlackTokenValid,
+ "encryption-enabled": isEncryptionEnabled,
+ "slack-connect-client-id": clientId,
+ "slack-connect-client-secret": clientSecret,
+ "metabot-slack-signing-secret": signingSecret,
+ "slack-connect-enabled": isEnabled,
+ });
+
+ setupPropertiesEndpoints(settings);
+ setupSettingsEndpoints([
+ createMockSettingDefinition({
+ key: "slack-connect-client-id",
+ value: clientId,
+ }),
+ createMockSettingDefinition({
+ key: "slack-connect-client-secret",
+ value: clientSecret,
+ }),
+ createMockSettingDefinition({
+ key: "metabot-slack-signing-secret",
+ value: signingSecret,
+ }),
+ createMockSettingDefinition({
+ key: "slack-connect-enabled",
+ value: isEnabled,
+ }),
+ ]);
+ setupUpdateSettingEndpoint();
+ setupMetabotSlackSettingsEndpoint();
+ setupSlackManifestEndpoint();
+ setupSlackAppInfoEndpoint(appInfo);
+
+ renderWithProviders(<MetabotSlackSetup />, {
+ storeInitialState: { settings: createMockSettingsState(settings) },
+ });
+
+ // Wait for component to fully render
+ if (isSlackTokenValid) {
+ await screen.findByText("Natural language questions in Slack");
+ }
+};
+
+const clientIdInput = () => screen.findByLabelText("Client ID");
+const clientSecretInput = () => screen.findByLabelText("Client Secret");
+const signingSecretInput = () => screen.findByLabelText("Signing Secret");
+const saveButton = () => screen.findByRole("button", { name: "Save changes" });
+
+describe("MetabotSlackSetup", () => {
+ it("renders nothing when slack-token-valid? is false", async () => {
+ await setup({ isSlackTokenValid: false });
+ expect(
+ screen.queryByText("Natural language questions in Slack"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows unconfigured form with all fields when secrets are missing", async () => {
+ await setup();
+ await screen.findByText("Natural language questions in Slack");
+ expect(await clientIdInput()).toBeInTheDocument();
+ expect(await clientSecretInput()).toBeInTheDocument();
+ expect(await signingSecretInput()).toBeInTheDocument();
+ });
+
+ it("shows configured state with toggle, accordion, and Remove button", async () => {
+ await setup(CONFIGURED);
+ expect(
+ await screen.findByText("Let people chat with Metabot"),
+ ).toBeInTheDocument();
+ expect(screen.getByText("View connection details")).toBeInTheDocument();
+ expect(screen.getByRole("button", { name: "Remove" })).toBeInTheDocument();
+ });
+
+ it("displays error message when submission fails", async () => {
+ await setup();
+ setupMetabotSlackSettingsEndpointWithError(400, "Invalid credentials");
+
+ await userEvent.type(await clientIdInput(), "123.456");
+ await userEvent.type(await clientSecretInput(), "secret");
+ await userEvent.type(await signingSecretInput(), "signing");
+
+ await userEvent.click(await saveButton());
+
+ expect(await screen.findByText(/Invalid credentials/)).toBeInTheDocument();
+ });
+
+ describe("encryption alert", () => {
+ it("shows alert with docs link and hides form when encryption is disabled", async () => {
+ await setup({ isEncryptionEnabled: false });
+
+ expect(
+ await screen.findByText(
+ "You must enable encryption for your instance in order to use this feature",
+ ),
+ ).toBeInTheDocument();
+
+ expect(
+ screen.getByRole("link", { name: "Learn how to enable encryption" }),
+ ).toHaveAttribute(
+ "href",
+ expect.stringContaining("encrypting-database-details-at-rest"),
+ );
+
+ expect(screen.queryByLabelText("Client ID")).not.toBeInTheDocument();
+ });
+ });
+
+ describe("missing scopes alert", () => {
+ it("shows alert with copy button, Slack link, and hides form", async () => {
+ await setup({
+ appInfo: createMockSlackAppInfo({
+ app_id: "A123ABC",
+ team_id: "T456DEF",
+ scopes: MISSING_SCOPES.scopes,
+ }),
+ });
+
+ expect(
+ await screen.findByText("Metabot needs more Slack permissions"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: /Copy manifest/i }),
+ ).toBeInTheDocument();
+
+ expect(
+ screen.getByRole("link", { name: /Open Slack settings/i }),
+ ).toHaveAttribute(
+ "href",
+ "https://app.slack.com/app-settings/T456DEF/A123ABC/app-manifest",
+ );
+
+ expect(screen.queryByLabelText("Client ID")).not.toBeInTheDocument();
+ });
+ });
+
+ describe("unconfigured form", () => {
+ it("disables submit button when fields are empty", async () => {
+ await setup();
+ await screen.findByText("Natural language questions in Slack");
+ expect(await saveButton()).toBeDisabled();
+ });
+
+ it("submits settings via PUT /api/ee/metabot-v3/slack/settings", async () => {
+ await setup();
+
+ await userEvent.type(await clientIdInput(), "123.456");
+ await userEvent.type(await clientSecretInput(), "secret123");
+ await userEvent.type(await signingSecretInput(), "signing123");
+
+ await userEvent.click(await saveButton());
+
+ await waitFor(async () => {
+ const puts = await findRequests("PUT");
+ const req = puts.find((r) =>
+ r.url.includes("/api/ee/metabot-v3/slack/settings"),
+ );
+ expect(req?.body).toEqual({
+ "slack-connect-client-id": "123.456",
+ "slack-connect-client-secret": "secret123",
+ "metabot-slack-signing-secret": "signing123",
+ });
+ });
+ });
+ });
+
+ describe("configured state", () => {
+ it("shows disabled inputs inside accordion", async () => {
+ await setup(CONFIGURED);
+ await userEvent.click(await screen.findByText("View connection details"));
+
+ expect(await clientIdInput()).toBeDisabled();
+ expect(await clientSecretInput()).toBeDisabled();
+ expect(await signingSecretInput()).toBeDisabled();
+ });
+
+ it("shows Basic Information link with app_id", async () => {
+ await setup({ ...CONFIGURED, appInfo: { app_id: "A123ABC" } });
+ await userEvent.click(await screen.findByText("View connection details"));
+
+ const link = await screen.findByRole("link", {
+ name: "Basic Information",
+ });
+ expect(link).toHaveAttribute(
+ "href",
+ "https://api.slack.com/apps/A123ABC/general",
+ );
+ });
+
+ it("updates slack-connect-enabled setting when toggle is clicked", async () => {
+ await setup({ ...CONFIGURED, isEnabled: false });
+
+ const toggle = await screen.findByRole("switch", {
+ name: "Let people chat with Metabot",
+ });
+ expect(toggle).not.toBeChecked();
+ await userEvent.click(toggle);
+
+ await waitFor(async () => {
+ const puts = await findRequests("PUT");
+ const req = puts.find((r) =>
+ r.url.includes("/api/setting/slack-connect-enabled"),
+ );
+ expect(req?.body).toEqual({ value: true });
+ });
+ });
+ });
+
+ describe("remove flow", () => {
+ it("opens modal and clears settings on confirm", async () => {
+ await setup(CONFIGURED);
+
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Remove" }),
+ );
+ expect(
+ await screen.findByText("Clear Metabot settings?"),
+ ).toBeInTheDocument();
+
+ await userEvent.click(
+ screen.getByRole("button", { name: "Clear settings" }),
+ );
+
+ await waitFor(async () => {
+ const puts = await findRequests("PUT");
+ const req = puts.find((r) =>
+ r.url.includes("/api/ee/metabot-v3/slack/settings"),
+ );
+ expect(req?.body).toEqual({
+ "slack-connect-client-id": null,
+ "slack-connect-client-secret": null,
+ "metabot-slack-signing-secret": null,
+ });
+ });
+ });
+ });
+
+ describe("edge cases", () => {
+ it("shows unconfigured form when only some secrets are set", async () => {
+ await setup({ clientId: "123.456", signingSecret: "signing123" });
+ await screen.findByText("Natural language questions in Slack");
+
+ expect(await clientIdInput()).toBeInTheDocument();
+ expect(
+ screen.queryByText("Let people chat with Metabot"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("shows configured UI alongside missing scopes alert", async () => {
+ await setup({ ...CONFIGURED, appInfo: MISSING_SCOPES });
+
+ expect(
+ await screen.findByText("Metabot needs more Slack permissions"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText("Let people chat with Metabot"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByRole("button", { name: "Remove" }),
+ ).toBeInTheDocument();
+ });
+
+ it("shows fallback Slack apps URL when app_id is missing", async () => {
+ await setup({ ...CONFIGURED, appInfo: { app_id: null } });
+ await userEvent.click(await screen.findByText("View connection details"));
+
+ const link = await screen.findByRole("link", {
+ name: "Basic Information",
+ });
+ expect(link).toHaveAttribute("href", "https://api.slack.com/apps");
+ });
+
+ it("fetches slack manifest on mount", async () => {
+ await setup();
+ await waitFor(() => {
+ const calls = fetchMock.callHistory.calls();
+ expect(
+ calls.find((c) => c.request?.url.includes("/api/slack/manifest")),
+ ).toBeDefined();
+ });
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotSlackSetupAlerts.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotSlackSetupAlerts.tsx
new file mode 100644
index 00000000000..4d9f2231417
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/MetabotAdmin/MetabotSlackSetupAlerts.tsx
@@ -0,0 +1,76 @@
+import { t } from "ttag";
+
+import { CopyButton } from "metabase/common/components/CopyButton";
+import {
+ ButtonLink,
+ ExternalLink,
+} from "metabase/common/components/ExternalLink";
+import { Alert, Group, Icon, Stack, Text } from "metabase/ui";
+
+import S from "./MetabotSlackSetup.module.css";
+
+interface MissingScopesAlertProps {
+ manifest: Record<string, unknown> | undefined;
+ appInfo?: { app_id: string | null; team_id: string | null };
+}
+
+export function MissingScopesAlert({
+ manifest,
+ appInfo,
+}: MissingScopesAlertProps) {
+ const slackUrl =
+ appInfo?.app_id && appInfo?.team_id
+ ? `https://app.slack.com/app-settings/${appInfo.team_id}/${appInfo.app_id}/app-manifest`
+ : "https://api.slack.com/apps";
+
+ return (
+ <Alert
+ color="brand"
+ title={t`Metabot needs more Slack permissions`}
+ styles={{ label: { fontSize: "var(--mantine-font-size-md)" } }}
+ >
+ <Stack gap="md" mt="sm">
+ <Text>
+ {t`Your Slack app is missing OAuth scopes required for Metabot. Copy the updated manifest and paste it in your Slack app settings. You will need to re-install your application to your workspace after.`}
+ </Text>
+ <Group gap="md">
+ <CopyButton
+ value={JSON.stringify(manifest, null, 2)}
+ target={
+ <button type="button" className={S.copyButton}>
+ <span>{t`Copy manifest`}</span>
+ <Icon name="copy" size={16} ml="sm" />
+ </button>
+ }
+ />
+ <ButtonLink href={slackUrl}>
+ <span>{t`Open Slack settings`}</span>
+ <Icon name="external" size={16} ml="sm" />
+ </ButtonLink>
+ </Group>
+ </Stack>
+ </Alert>
+ );
+}
+
+interface EncryptionRequiredAlertProps {
+ docsUrl: string;
+}
+
+export function EncryptionRequiredAlert({
+ docsUrl,
+}: EncryptionRequiredAlertProps) {
+ return (
+ <Alert
+ color="brand"
+ title={t`You must enable encryption for your instance in order to use this feature`}
+ styles={{ label: { fontSize: "var(--mantine-font-size-md)" } }}
+ >
+ <Text mt="sm">
+ <ExternalLink
+ href={docsUrl}
+ >{t`Learn how to enable encryption`}</ExternalLink>
+ </Text>
+ </Alert>
+ );
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/components/SlackConnectSuccess.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/components/SlackConnectSuccess.tsx
new file mode 100644
index 00000000000..8c9421183fb
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/components/SlackConnectSuccess.tsx
@@ -0,0 +1,22 @@
+import { replace } from "react-router-redux";
+import { useMount } from "react-use";
+import { t } from "ttag";
+
+import { useDispatch } from "metabase/lib/redux";
+import { addUndo } from "metabase/redux/undo";
+
+export const SlackConnectSuccess = () => {
+ const dispatch = useDispatch();
+
+ useMount(() => {
+ dispatch(
+ addUndo({
+ message: t`Your Slack account has been connected successfully.`,
+ icon: "check",
+ }),
+ );
+ dispatch(replace("/"));
+ });
+
+ return null;
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/constants.ts b/enterprise/frontend/src/metabase-enterprise/metabot/constants.ts
index d7c4be9beca..87782196a78 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/constants.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/constants.ts
@@ -6,6 +6,7 @@ export const LONG_CONVO_MSG_LENGTH_THRESHOLD = 120000;
export const FIXED_METABOT_IDS = {
DEFAULT: 1 as const,
EMBEDDED: 2 as const,
+ SLACKBOT: 3 as const,
};
export const METABOT_REQUEST_IDS = {
@@ -15,6 +16,7 @@ export const METABOT_REQUEST_IDS = {
export const FIXED_METABOT_ENTITY_IDS = {
DEFAULT: "metabotmetabotmetabot" as const,
EMBEDDED: "embeddedmetabotmetabo" as const,
+ SLACKBOT: "slackbotmetabotmetabo" as const,
};
export const METABOT_PROFILE_OVERRIDES = {
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx b/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
index 6cbf1ce0896..9e1c64f3c6e 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/index.tsx
@@ -10,6 +10,7 @@ import { hasPremiumFeature } from "metabase-enterprise/settings";
import { Metabot } from "./components/Metabot";
import { getAdminRoutes } from "./components/MetabotAdmin/MetabotAdminPage";
import { getAdminRoutes as getAdminUpsellRoutes } from "./components/MetabotAdmin/MetabotPurchasePage";
+import { MetabotSlackSetup } from "./components/MetabotAdmin/MetabotSlackSetup";
import { MetabotAppBarButton } from "./components/MetabotAppBarButton";
import { MetabotChat } from "./components/MetabotChat";
import MetabotThinkingStyles from "./components/MetabotChat/MetabotThinking.module.css";
@@ -18,6 +19,7 @@ import { MetabotDataStudioSidebar } from "./components/MetabotDataStudioSidebar"
import { MetabotQueryBuilder } from "./components/MetabotQueryBuilder";
import { getMetabotQuickLinks } from "./components/MetabotQuickLinks";
import { getNewMenuItemAIExploration } from "./components/NewMenuItemAIExploration";
+import { SlackConnectSuccess } from "./components/SlackConnectSuccess";
import { MetabotContext, MetabotProvider, defaultContext } from "./context";
import { useMetabotSQLSuggestion as useMetabotSQLSuggestionEE } from "./hooks";
import {
@@ -65,7 +67,12 @@ export function initializePlugin() {
getMetabotVisible,
// routes
getAdminRoutes,
- getMetabotRoutes: getMetabotQuickLinks,
+ getMetabotRoutes: () => (
+ <>
+ {getMetabotQuickLinks()}
+ <Route path="slack-connect-success" component={SlackConnectSuccess} />
+ </>
+ ),
getMetabotQueryBuilderRoute: () => (
<Route path="ask" component={MetabotQueryBuilderOrFallback} />
),
@@ -75,6 +82,7 @@ export function initializePlugin() {
MetabotAppBarButton,
MetabotDataStudioButton,
MetabotDataStudioSidebar,
+ MetabotSlackSetup,
MetabotThinkingStyles,
// hooks
useMetabotSQLSuggestion: useMetabotSQLSuggestionEE,
diff --git a/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts b/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts
index 8cad407acc7..3f533d7d647 100644
--- a/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts
+++ b/enterprise/frontend/src/metabase-enterprise/metabot/state/actions.ts
@@ -13,12 +13,12 @@ import { addUndo } from "metabase/redux/undo";
import { getIsWorkspace } from "metabase/selectors/routing";
import { getUser } from "metabase/selectors/user";
import {
- type JSONValue,
aiStreamingQuery,
findMatchingInflightAiStreamingRequests,
} from "metabase-enterprise/api/ai-streaming";
import type { ProcessedChatResponse } from "metabase-enterprise/api/ai-streaming/process-stream";
import type {
+ JSONValue,
MetabotAgentRequest,
MetabotAgentResponse,
MetabotChatContext,
diff --git a/frontend/src/metabase-types/api/metabot.ts b/frontend/src/metabase-types/api/metabot.ts
index 8858865fb82..d14dfba3680 100644
--- a/frontend/src/metabase-types/api/metabot.ts
+++ b/frontend/src/metabase-types/api/metabot.ts
@@ -277,3 +277,17 @@ export type MetabotTodoItem = {
status: "pending" | "in_progress" | "completed" | "cancelled";
priority: "high" | "medium" | "low";
};
+
+/* Metabot v3 - Slack Settings */
+
+export type MetabotSlackSettings =
+ | {
+ "slack-connect-client-id": string;
+ "slack-connect-client-secret": string;
+ "metabot-slack-signing-secret": string;
+ }
+ | {
+ "slack-connect-client-id": null;
+ "slack-connect-client-secret": null;
+ "metabot-slack-signing-secret": null;
+ };
diff --git a/frontend/src/metabase-types/api/mocks/index.ts b/frontend/src/metabase-types/api/mocks/index.ts
index 435f8b21666..7d9324b83fc 100644
--- a/frontend/src/metabase-types/api/mocks/index.ts
+++ b/frontend/src/metabase-types/api/mocks/index.ts
@@ -36,6 +36,7 @@ export * from "./segment";
export * from "./series";
export * from "./session";
export * from "./settings";
+export * from "./slack";
export * from "./snippets";
export * from "./store";
export * from "./support-access-grants";
diff --git a/frontend/src/metabase-types/api/mocks/settings.ts b/frontend/src/metabase-types/api/mocks/settings.ts
index d370f40d252..d1bb1ab152b 100644
--- a/frontend/src/metabase-types/api/mocks/settings.ts
+++ b/frontend/src/metabase-types/api/mocks/settings.ts
@@ -120,6 +120,7 @@ export const createMockTokenFeatures = (
sso_ldap: false,
sso_oidc: false,
sso_saml: false,
+ sso_slack: false,
session_timeout_config: false,
whitelabel: false,
dashboard_subscription_filters: false,
@@ -378,7 +379,6 @@ export const createMockSettings = (
"site-url": "http://localhost:3000",
"site-uuid": "1234",
"slack-app-token": null,
- "slack-token": null,
"slack-token-valid?": false,
"start-of-week": "sunday",
"store-url": "https://store.staging.metabase.com",
@@ -410,5 +410,6 @@ export const createMockSettings = (
"license-token-missing-banner-dismissal-timestamp": [],
"sdk-iframe-embed-setup-settings": null,
"use-tenants": false,
+ "encryption-enabled": false,
...opts,
});
diff --git a/frontend/src/metabase-types/api/mocks/slack.ts b/frontend/src/metabase-types/api/mocks/slack.ts
index 5f4c5cc4acf..440b6e32e36 100644
--- a/frontend/src/metabase-types/api/mocks/slack.ts
+++ b/frontend/src/metabase-types/api/mocks/slack.ts
@@ -1,4 +1,4 @@
-import type { SlackSettings } from "metabase-types/api";
+import type { SlackAppInfo, SlackSettings } from "metabase-types/api";
export const createMockSlackSettings = (
opts?: Partial<SlackSettings>,
@@ -7,3 +7,17 @@ export const createMockSlackSettings = (
"slack-bug-report-channel": null,
...opts,
});
+
+export const createMockSlackAppInfo = (
+ opts?: Partial<SlackAppInfo>,
+): SlackAppInfo => ({
+ app_id: "test-app-id",
+ team_id: "test-team-id",
+ scopes: {
+ actual: [],
+ required: [],
+ missing: [],
+ extra: [],
+ },
+ ...opts,
+});
diff --git a/frontend/src/metabase-types/api/settings.ts b/frontend/src/metabase-types/api/settings.ts
index acc25fd40ef..1ca89f5a033 100644
--- a/frontend/src/metabase-types/api/settings.ts
+++ b/frontend/src/metabase-types/api/settings.ts
@@ -335,6 +335,7 @@ export const tokenFeatures = [
"sso_ldap",
"sso_oidc",
"sso_saml",
+ "sso_slack",
"session_timeout_config",
"whitelabel",
"serialization",
@@ -477,6 +478,7 @@ export type EmbeddingHomepageStatus =
interface AdminSettings {
"active-users-count"?: number;
"custom-geojson-enabled": boolean;
+ "encryption-enabled": boolean;
"deprecation-notice-version"?: string;
"disable-cors-on-localhost": boolean;
"embedding-secret-key"?: string;
@@ -515,7 +517,6 @@ interface SettingsManagerSettings {
"session-cookie-samesite": SessionCookieSameSite;
"slack-app-token": string | null;
"slack-bug-report-channel": string | null;
- "slack-token": string | null;
"slack-token-valid?": boolean;
}
@@ -766,6 +767,10 @@ export interface EnterpriseSettings extends Settings {
"python-runner-test-run-timeout-seconds"?: number | null;
"llm-anthropic-api-key"?: string | null;
"llm-anthropic-model": string;
+ "metabot-slack-signing-secret"?: string | null;
+ "slack-connect-enabled"?: boolean | null;
+ "slack-connect-client-id"?: string | null;
+ "slack-connect-client-secret"?: string | null;
/**
* @deprecated
*/
diff --git a/frontend/src/metabase-types/api/slack.ts b/frontend/src/metabase-types/api/slack.ts
index 9e59bf25091..6bdbe048982 100644
--- a/frontend/src/metabase-types/api/slack.ts
+++ b/frontend/src/metabase-types/api/slack.ts
@@ -2,3 +2,14 @@ export interface SlackSettings {
"slack-app-token": string | null;
"slack-bug-report-channel": string | null;
}
+
+export interface SlackAppInfo {
+ app_id: string | null;
+ team_id: string | null;
+ scopes: {
+ actual: string[];
+ required: string[];
+ missing: string[];
+ extra: string[];
+ } | null;
+}
diff --git a/frontend/src/metabase-types/api/util.ts b/frontend/src/metabase-types/api/util.ts
index ff3bbae9988..32a602d2332 100644
--- a/frontend/src/metabase-types/api/util.ts
+++ b/frontend/src/metabase-types/api/util.ts
@@ -43,3 +43,11 @@ export interface BugReportDetails {
}
export type LongTaskStatus = "incomplete" | "complete" | "aborted";
+
+export type JSONValue =
+ | null
+ | string
+ | number
+ | boolean
+ | { [value: string]: JSONValue }
+ | Array<JSONValue>;
diff --git a/frontend/src/metabase/admin/app/components/DeprecationNotice/DeprecationNotice.stories.tsx b/frontend/src/metabase/admin/app/components/DeprecationNotice/DeprecationNotice.stories.tsx
index 57f8ce50735..f36b84e22e6 100644
--- a/frontend/src/metabase/admin/app/components/DeprecationNotice/DeprecationNotice.stories.tsx
+++ b/frontend/src/metabase/admin/app/components/DeprecationNotice/DeprecationNotice.stories.tsx
@@ -18,7 +18,6 @@ export const Default: StoryObj<DeprecationNoticeProps> = {
},
args: {
- hasSlackBot: true,
hasDeprecatedDatabase: true,
isEnabled: true,
},
diff --git a/frontend/src/metabase/admin/app/components/DeprecationNotice/DeprecationNotice.tsx b/frontend/src/metabase/admin/app/components/DeprecationNotice/DeprecationNotice.tsx
index 4e581e832b8..795cc99ce06 100644
--- a/frontend/src/metabase/admin/app/components/DeprecationNotice/DeprecationNotice.tsx
+++ b/frontend/src/metabase/admin/app/components/DeprecationNotice/DeprecationNotice.tsx
@@ -6,76 +6,40 @@ import { Icon } from "metabase/ui";
import S from "./DeprecationNotice.module.css";
export interface DeprecationNoticeProps {
- hasSlackBot: boolean;
hasDeprecatedDatabase: boolean;
isEnabled: boolean;
onClose: () => void;
}
const DeprecationNotice = ({
- hasSlackBot,
hasDeprecatedDatabase,
isEnabled,
onClose,
}: DeprecationNoticeProps): JSX.Element | null => {
- if ((!hasSlackBot && !hasDeprecatedDatabase) || !isEnabled) {
+ if (!hasDeprecatedDatabase || !isEnabled) {
return null;
}
+ const databaseListUrl = "/admin/databases";
+
return (
<div className={S.NoticeRoot} role="status">
<Icon name="warning" className={S.NoticeWarningIcon} />
<div className={S.NoticeContent}>
- {getBannerContent(hasSlackBot, hasDeprecatedDatabase)}
+ {jt`You're using a ${(
+ <Link
+ variant="brandBold"
+ key="database"
+ to={databaseListUrl}
+ >{t`Database driver`}</Link>
+ )} which is now deprecated and will be removed in the next release. We recommend you ${(
+ <strong key="upgrade">{t`upgrade`}</strong>
+ )}.`}
</div>
<Icon name="close" className={S.NoticeCloseIcon} onClick={onClose} />
</div>
);
};
-const getBannerContent = (
- hasSlackBot: boolean,
- hasDeprecatedDatabase: boolean,
-) => {
- const databaseListUrl = "/admin/databases";
- const slackSettingsUrl = "/admin/settings/notifications";
-
- if (hasSlackBot && hasDeprecatedDatabase) {
- return jt`You’re using a ${(
- <Link
- variant="brandBold"
- key="database"
- to={databaseListUrl}
- >{t`Database driver`}</Link>
- )} and a ${(
- <Link
- variant="brandBold"
- key="slack"
- to={slackSettingsUrl}
- >{t`Slack bot integration`}</Link>
- )} which are now deprecated and will be removed in the next release. We recommend you ${(
- <strong key="upgrade">{t`upgrade`}</strong>
- )}.`;
- } else if (hasSlackBot) {
- return jt`Your Slack bot was deprecated but is still working. We recommend you delete the existing connection and ${(
- <Link
- variant="brandBold"
- key="slack"
- to={slackSettingsUrl}
- >{t`upgrade to Slack Apps`}</Link>
- )}.`;
- } else if (hasDeprecatedDatabase) {
- return jt`You’re using a ${(
- <Link
- variant="brandBold"
- key="database"
- to={databaseListUrl}
- >{t`Database driver`}</Link>
- )} which is now deprecated and will be removed in the next release. We recommend you ${(
- <strong key="upgrade">{t`upgrade`}</strong>
- )}.`;
- }
-};
-
// eslint-disable-next-line import/no-default-export -- deprecated usage
export default DeprecationNotice;
diff --git a/frontend/src/metabase/admin/app/containers/DeprecationNotice/DeprecationNotice.tsx b/frontend/src/metabase/admin/app/containers/DeprecationNotice/DeprecationNotice.tsx
index 94958a3f77e..919f6f673ec 100644
--- a/frontend/src/metabase/admin/app/containers/DeprecationNotice/DeprecationNotice.tsx
+++ b/frontend/src/metabase/admin/app/containers/DeprecationNotice/DeprecationNotice.tsx
@@ -9,7 +9,6 @@ import { disableNotice } from "../../actions";
import DeprecationNotice from "../../components/DeprecationNotice";
import {
hasDeprecatedDatabase,
- hasSlackBot,
isDeprecationNoticeEnabled,
} from "../../selectors";
@@ -18,7 +17,6 @@ interface Props {
}
const mapStateToProps = (state: State, props: Props) => ({
- hasSlackBot: hasSlackBot(state),
hasDeprecatedDatabase: hasDeprecatedDatabase(state, props),
isEnabled: isDeprecationNoticeEnabled(state),
});
diff --git a/frontend/src/metabase/admin/app/selectors.ts b/frontend/src/metabase/admin/app/selectors.ts
index b03c74386b8..26648bc068f 100644
--- a/frontend/src/metabase/admin/app/selectors.ts
+++ b/frontend/src/metabase/admin/app/selectors.ts
@@ -1,6 +1,5 @@
import { getEngines } from "metabase/databases/selectors";
import { isDeprecatedEngine } from "metabase/lib/engine";
-import { getSetting } from "metabase/selectors/settings";
import type Database from "metabase-lib/v1/metadata/Database";
import type { State } from "metabase-types/store";
@@ -8,10 +7,6 @@ interface Props {
databases?: Database[];
}
-export const hasSlackBot = (state: State): boolean => {
- return getSetting(state, "slack-token") != null;
-};
-
export const hasDeprecatedDatabase = (state: State, props: Props): boolean => {
const engines = getEngines(state);
return (
diff --git a/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx b/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx
index 548b8454596..2d54ab7822e 100644
--- a/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx
+++ b/frontend/src/metabase/admin/components/SettingsSection/SettingsSection.tsx
@@ -56,12 +56,16 @@ export function SettingsPageWrapper({
title?: React.ReactNode;
description?: React.ReactNode;
children: React.ReactNode;
-} & StackProps) {
+} & Omit<StackProps, "title">) {
return (
<Stack gap="lg" {...stackProps}>
{(title || description) && (
<Box>
- {title && <Title order={1}>{title}</Title>}
+ {title && (
+ <Title order={1} display="flex" style={{ alignItems: "center" }}>
+ {title}
+ </Title>
+ )}
{description && (
<Text c="text-secondary" maw="40rem">
{description}
diff --git a/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx b/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx
index 78ae57b9f5e..815273dfbcb 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsNav/SettingsNav.tsx
@@ -53,11 +53,8 @@ export function SettingsNav() {
<PLUGIN_REMOTE_SYNC.LibraryNav />
<NavDivider />
<SettingsNavItem path="email" label={t`Email`} icon="mail" />
- <SettingsNavItem
- path="notifications"
- label={t`Notification channels`}
- icon="bell"
- />
+ <SettingsNavItem path="slack" label={t`Slack`} icon="slack" />
+ <SettingsNavItem path="webhooks" label={t`Webhooks`} icon="webhook" />
{!hasHosting && <UpdatesNavItem />}
<NavDivider />
<SettingsNavItem
diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/NotificationSettingsPage.unit.spec.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/NotificationSettingsPage.unit.spec.tsx
deleted file mode 100644
index 9d68fbd9a33..00000000000
--- a/frontend/src/metabase/admin/settings/components/SettingsPages/NotificationSettingsPage.unit.spec.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import {
- setupPropertiesEndpoints,
- setupSettingsEndpoints,
- setupSlackManifestEndpoint,
-} from "__support__/server-mocks";
-import { setupWebhookChannelsEndpoint } from "__support__/server-mocks/channel";
-import { renderWithProviders, screen } from "__support__/ui";
-import type { SettingKey } from "metabase-types/api";
-import {
- createMockSettingDefinition,
- createMockSettings,
-} from "metabase-types/api/mocks";
-import { createMockSettingsState } from "metabase-types/store/mocks";
-
-import { NotificationSettingsPage } from "./NotificationSettingsPage";
-
-const setup = async ({
- isSlackTokenValid = true,
- slackAppToken = "xoxb-test-token",
-}: {
- isSlackTokenValid?: boolean;
- slackAppToken?: string | null;
-} = {}) => {
- const settings = createMockSettings({
- "slack-token-valid?": isSlackTokenValid,
- "slack-app-token": slackAppToken,
- });
-
- setupPropertiesEndpoints(settings);
- setupSettingsEndpoints(
- Object.entries(settings).map(([key, value]) =>
- createMockSettingDefinition({ key: key as SettingKey, value }),
- ),
- );
- setupSlackManifestEndpoint();
- setupWebhookChannelsEndpoint();
-
- renderWithProviders(<NotificationSettingsPage />, {
- storeInitialState: {
- settings: createMockSettingsState(settings),
- },
- });
-
- await screen.findByText("Notifications");
-};
-
-describe("NotificationSettingsPage", () => {
- it("shows Slack status inside the card when connected", async () => {
- await setup();
-
- expect(screen.getByText("Slack app is working")).toBeInTheDocument();
- });
-
- it("shows Slack error status when the token is invalid", async () => {
- await setup({ isSlackTokenValid: false });
-
- expect(screen.getByText("Slack app is not working.")).toBeInTheDocument();
- });
-
- it("shows connect CTA when the Slack app is not configured", async () => {
- await setup({ slackAppToken: null });
-
- expect(screen.getByText("Connect to Slack")).toBeInTheDocument();
- });
-});
diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/SlackSettingsPage.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/SlackSettingsPage.tsx
new file mode 100644
index 00000000000..ed03d0cb35d
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/SlackSettingsPage.tsx
@@ -0,0 +1,24 @@
+import { t } from "ttag";
+
+import { SettingsPageWrapper } from "metabase/admin/components/SettingsSection";
+import { PLUGIN_METABOT } from "metabase/plugins";
+import { Icon } from "metabase/ui";
+
+import { SlackSetup } from "../../slack/SlackSetup";
+
+export const SlackSettingsPage = () => {
+ return (
+ <>
+ <SettingsPageWrapper
+ title={
+ <>
+ <Icon name="slack_colorized" size={22} mr="sm" /> {t`Slack`}
+ </>
+ }
+ >
+ <SlackSetup />
+ <PLUGIN_METABOT.MetabotSlackSetup />
+ </SettingsPageWrapper>
+ </>
+ );
+};
diff --git a/frontend/src/metabase/admin/settings/components/SettingsPages/NotificationSettingsPage.tsx b/frontend/src/metabase/admin/settings/components/SettingsPages/WebhooksSettingsPage.tsx
similarity index 55%
rename from frontend/src/metabase/admin/settings/components/SettingsPages/NotificationSettingsPage.tsx
rename to frontend/src/metabase/admin/settings/components/SettingsPages/WebhooksSettingsPage.tsx
index 60b2e37984b..0e97bd4f107 100644
--- a/frontend/src/metabase/admin/settings/components/SettingsPages/NotificationSettingsPage.tsx
+++ b/frontend/src/metabase/admin/settings/components/SettingsPages/WebhooksSettingsPage.tsx
@@ -1,4 +1,3 @@
-import { useDisclosure } from "@mantine/hooks";
import { useState } from "react";
import { c, t } from "ttag";
@@ -7,35 +6,27 @@ import {
SettingsSection,
} from "metabase/admin/components/SettingsSection";
import { useListChannelsQuery } from "metabase/api/channel";
-import { useSetting } from "metabase/common/hooks";
import {
Button,
Flex,
+ Group,
Icon,
type IconName,
Paper,
Stack,
Text,
Title,
- UnstyledButton,
} from "metabase/ui";
import type { NotificationChannel } from "metabase-types/api";
-import { SlackSettingsModal } from "../../slack/SlackSettingsModal";
-import { SlackSetup } from "../../slack/SlackSetup";
-import { SlackStatus } from "../../slack/SlackStatus";
import { CreateWebhookModal } from "../widgets/Notifications/CreateWebhookModal";
import { EditWebhookModal } from "../widgets/Notifications/EditWebhookModal";
-type NotificationModals = null | "create" | "edit";
+type WebhookModals = null | "create" | "edit";
-export const NotificationSettingsPage = () => {
- const [showSlackModal, { open: openSlackModal, close: closeSlackModal }] =
- useDisclosure(false);
- const [webhookModal, setWebhookModal] = useState<NotificationModals>(null);
+export const WebhooksSettingsPage = () => {
+ const [webhookModal, setWebhookModal] = useState<WebhookModals>(null);
const [currentChannel, setCurrentChannel] = useState<NotificationChannel>();
- const slackAppToken = useSetting("slack-app-token");
- const slackBotToken = useSetting("slack-token");
const { data: channels } = useListChannelsQuery();
@@ -43,48 +34,21 @@ export const NotificationSettingsPage = () => {
return (
<>
- <SettingsPageWrapper title={t`Notifications`}>
- <SettingsSection title={t`Slack`}>
- {slackAppToken || slackBotToken ? (
- <Paper shadow="0" withBorder p="lg">
- <Flex gap="0.5rem" align="center" mb="1rem">
- <Icon name="slack_colorized" />
- <Title order={3}>{t`Slack`}</Title>
- </Flex>
- {slackAppToken ? <SlackStatus /> : <SlackSetup />}
- </Paper>
- ) : (
- <UnstyledButton
- onClick={openSlackModal}
- variant="unstyled"
- w="100%"
- >
- <Paper shadow="0" withBorder p="lg">
- <Flex gap="0.5rem" align="center" mb="0.5rem">
- <Icon name="slack_colorized" />
- <Title order={3}>{t`Connect to Slack`}</Title>
- </Flex>
- <Text>
- {t`If your team uses Slack, you can send dashboard subscriptions and
- alerts there`}
- </Text>
- </Paper>
- </UnstyledButton>
- )}
- </SettingsSection>
-
+ <SettingsPageWrapper title={t`Webhooks`}>
<SettingsSection>
- <Flex justify="space-between" align="center" mb="1.5rem">
- <Title order={2}>{t`Webhooks for alerts`}</Title>{" "}
+ <Group justify="space-between" align="center">
+ <Text c="text-secondary">
+ {t`Configure webhooks to send alert results to a destination of your choice.`}
+ </Text>
{hasChannels && (
<Button
- variant="subtle"
- size="compact-md"
+ variant="filled"
+ size="md"
leftSection={<Icon name="add" />}
onClick={() => setWebhookModal("create")}
>{c("Short for 'Add another webhook'").t`Add another`}</Button>
)}
- </Flex>
+ </Group>
{hasChannels ? (
<Stack>
{channels?.map((c) => (
@@ -110,12 +74,11 @@ export const NotificationSettingsPage = () => {
)}
</SettingsSection>
</SettingsPageWrapper>
- <NotificationSettingsModals
+ <WebhookSettingsModals
modal={webhookModal}
channel={currentChannel}
onClose={() => setWebhookModal(null)}
/>
- <SlackSettingsModal isOpen={showSlackModal} onClose={closeSlackModal} />
</>
);
};
@@ -146,12 +109,12 @@ const ChannelBox = ({
</Paper>
);
-const NotificationSettingsModals = ({
+const WebhookSettingsModals = ({
modal,
channel,
onClose,
}: {
- modal: NotificationModals;
+ modal: WebhookModals;
channel?: NotificationChannel;
onClose: () => void;
}) => {
diff --git a/frontend/src/metabase/admin/settings/slack/SlackBadge.tsx b/frontend/src/metabase/admin/settings/slack/SlackBadge.tsx
deleted file mode 100644
index eb05ee05488..00000000000
--- a/frontend/src/metabase/admin/settings/slack/SlackBadge.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { t } from "ttag";
-
-import { Box, Center, type CenterProps, Text } from "metabase/ui";
-
-import S from "./slack.module.css";
-
-export interface SlackBadgeProps extends CenterProps {
- isBot?: boolean;
- isValid?: boolean;
-}
-
-export const SlackBadge = ({
- isBot,
- isValid,
- ...props
-}: SlackBadgeProps): JSX.Element => {
- const color = isValid ? "success" : "error";
-
- return (
- <Center {...props}>
- <Box className={S.StatusBadge} bg={color} />
- <Text fw="bold" c={color}>
- {getMessage(isBot, isValid)}
- </Text>
- </Center>
- );
-};
-
-const getMessage = (isBot?: boolean, isValid?: boolean): string => {
- if (isBot) {
- return isValid ? t`Slack bot is working.` : t`Slack bot is not working.`;
- } else {
- return isValid ? t`Slack app is working` : t`Slack app is not working.`;
- }
-};
diff --git a/frontend/src/metabase/admin/settings/slack/SlackBadge.unit.spec.tsx b/frontend/src/metabase/admin/settings/slack/SlackBadge.unit.spec.tsx
deleted file mode 100644
index 47878bbac10..00000000000
--- a/frontend/src/metabase/admin/settings/slack/SlackBadge.unit.spec.tsx
+++ /dev/null
@@ -1,29 +0,0 @@
-import { render, screen } from "__support__/ui";
-
-import { SlackBadge } from "./SlackBadge";
-
-describe("SlackBadge", () => {
- it("should render when there is a bot and the token is valid", () => {
- render(<SlackBadge isBot={true} isValid={true} />);
-
- expect(screen.getByText("Slack bot is working.")).toBeInTheDocument();
- });
-
- it("should render when there is an app and the token is valid", () => {
- render(<SlackBadge isBot={false} isValid={true} />);
-
- expect(screen.getByText("Slack app is working")).toBeInTheDocument();
- });
-
- it("should render when there is a bot and the token is invalid", () => {
- render(<SlackBadge isBot={true} isValid={false} />);
-
- expect(screen.getByText("Slack bot is not working.")).toBeInTheDocument();
- });
-
- it("should render when there is an app and the token is invalid", () => {
- render(<SlackBadge isBot={false} isValid={false} />);
-
- expect(screen.getByText("Slack app is not working.")).toBeInTheDocument();
- });
-});
diff --git a/frontend/src/metabase/admin/settings/slack/SlackBugReportChannelInput.tsx b/frontend/src/metabase/admin/settings/slack/SlackBugReportChannelInput.tsx
new file mode 100644
index 00000000000..6c99a964336
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/slack/SlackBugReportChannelInput.tsx
@@ -0,0 +1,67 @@
+import { useEffect, useState } from "react";
+import { t } from "ttag";
+
+import { useUpdateSlackSettingsMutation } from "metabase/api";
+import { useSetting, useToast } from "metabase/common/hooks";
+import { Box, Text, TextInput } from "metabase/ui";
+
+import { SettingHeader } from "../components/SettingHeader";
+
+const getSlackError = (err: unknown): string =>
+ (err as { data?: { errors?: { "slack-bug-report-channel"?: string } } })?.data
+ ?.errors?.["slack-bug-report-channel"] ?? t`Failed to update channel`;
+
+export const SlackBugReportChannelInput = () => {
+ const initialValue = useSetting("slack-bug-report-channel");
+ const [updateSlackSettings] = useUpdateSlackSettingsMutation();
+ const [sendToast] = useToast();
+ const [localValue, setLocalValue] = useState(initialValue ?? "");
+ const [error, setError] = useState<string | null>(null);
+
+ useEffect(() => {
+ setLocalValue(initialValue ?? "");
+ }, [initialValue]);
+
+ const handleBlur = async () => {
+ const trimmedValue = localValue.replace(/^#+/, "");
+ setLocalValue(trimmedValue);
+
+ const value = trimmedValue === "" ? null : trimmedValue.toLowerCase();
+ if (value === initialValue) {
+ return;
+ }
+
+ setError(null);
+ try {
+ await updateSlackSettings({ "slack-bug-report-channel": value }).unwrap();
+ sendToast({
+ message: t`Slack bug report channel updated`,
+ toastColor: "success",
+ });
+ } catch (err) {
+ setError(getSlackError(err));
+ }
+ };
+
+ return (
+ <Box data-testid="slack-bug-report-channel-setting">
+ <SettingHeader
+ id="slack-bug-report-channel"
+ title={t`Slack bug report channel`}
+ description={t`This channel will receive bug reports submitted by users.`}
+ />
+ <TextInput
+ id="slack-bug-report-channel"
+ value={localValue}
+ placeholder="metabase-bugs"
+ onChange={(e) => {
+ setLocalValue(e.target.value);
+ setError(null);
+ }}
+ onBlur={handleBlur}
+ leftSection={<Text c="text-secondary">#</Text>}
+ error={error}
+ />
+ </Box>
+ );
+};
diff --git a/frontend/src/metabase/admin/settings/slack/SlackConfiguration.tsx b/frontend/src/metabase/admin/settings/slack/SlackConfiguration.tsx
new file mode 100644
index 00000000000..74539739c45
--- /dev/null
+++ b/frontend/src/metabase/admin/settings/slack/SlackConfiguration.tsx
@@ -0,0 +1,61 @@
+import { t } from "ttag";
+
+import { useGetSlackAppInfoQuery } from "metabase/api";
+import { ExternalLink } from "metabase/common/components/ExternalLink";
+import { useSetting } from "metabase/common/hooks";
+import { Box, Button, Flex, Stack, Text } from "metabase/ui";
+
+import { SlackBugReportChannelInput } from "./SlackBugReportChannelInput";
+
+export const SlackConfiguration = () => {
+ const bugReportingEnabled = useSetting("bug-reporting-enabled") ?? false;
+ const { data: appInfo } = useGetSlackAppInfoQuery();
+
+ const iconUrl = "/app/assets/img/metabot-slackbot.png";
+ const basicInfoUrl = appInfo?.app_id
+ ? `https://api.slack.com/apps/${appInfo.app_id}/general#edit`
+ : `https://api.slack.com/apps`;
+
+ return (
+ <Stack gap="md">
+ <Box>
+ <Text fz="lg" fw="bold">{t`Slack app icon`}</Text>
+ <Text c="text-secondary">
+ {t`Give your app all the bells and whistles.`}
+ </Text>
+ </Box>
+
+ <Flex gap="md" align="center">
+ <Box
+ component="img"
+ src={iconUrl}
+ alt="Metabot icon"
+ w={80}
+ h={80}
+ bdrs="sm"
+ bd="1px solid var(--mb-color-border)"
+ />
+ <Stack gap="sm" align="flex-start">
+ <Button
+ variant="filled"
+ component="a"
+ href={iconUrl}
+ display="inline-block"
+ download="metabot-slack-icon.png"
+ >
+ {t`Download App Icon`}
+ </Button>
+ <Text c="text-secondary">
+ {t`Add this icon to your App's `}
+ <ExternalLink
+ href={basicInfoUrl}
+ >{t`Basic Information`}</ExternalLink>
+ {t` settings`}
+ </Text>
+ </Stack>
+ </Flex>
+
+ {bugReportingEnabled && <SlackBugReportChannelInput />}
+ </Stack>
+ );
+};
diff --git a/frontend/src/metabase/admin/settings/slack/SlackSettingsModal.tsx b/frontend/src/metabase/admin/settings/slack/SlackSettingsModal.tsx
deleted file mode 100644
index 8e7b83e0e20..00000000000
--- a/frontend/src/metabase/admin/settings/slack/SlackSettingsModal.tsx
+++ /dev/null
@@ -1,37 +0,0 @@
-import { useEffect } from "react";
-import { t } from "ttag";
-
-import { useAdminSetting } from "metabase/api/utils";
-import { LoadingAndErrorWrapper } from "metabase/common/components/LoadingAndErrorWrapper";
-import { Modal } from "metabase/ui";
-
-import { SlackSetup } from "./SlackSetup";
-
-export const SlackSettingsModal = ({
- isOpen,
- onClose,
-}: {
- isOpen: boolean;
- onClose: () => void;
-}) => {
- const { value: isApp, isLoading } = useAdminSetting("slack-app-token");
-
- useEffect(() => {
- if (isApp) {
- onClose();
- }
- }, [isApp, onClose]);
-
- return (
- <Modal
- opened={isOpen}
- title={t`Metabase on Slack`}
- onClose={onClose}
- padding="xl"
- >
- <LoadingAndErrorWrapper loading={isLoading}>
- <SlackSetup />
- </LoadingAndErrorWrapper>
- </Modal>
- );
-};
diff --git a/frontend/src/metabase/admin/settings/slack/SlackSettingsModal.unit.spec.tsx b/frontend/src/metabase/admin/settings/slack/SlackSettingsModal.unit.spec.tsx
deleted file mode 100644
index d41d26a81f0..00000000000
--- a/frontend/src/metabase/admin/settings/slack/SlackSettingsModal.unit.spec.tsx
+++ /dev/null
@@ -1,75 +0,0 @@
-import {
- findRequests,
- setupPropertiesEndpoints,
- setupSettingsEndpoints,
- setupSlackManifestEndpoint,
-} from "__support__/server-mocks";
-import { renderWithProviders, screen, waitFor } from "__support__/ui";
-import { createMockSettings } from "metabase-types/api/mocks";
-
-import { SlackSettingsModal } from "./SlackSettingsModal";
-
-const setup = async ({
- isApp,
- isBot,
- isValid,
-}: {
- isApp: boolean;
- isBot: boolean;
- isValid: boolean;
-}) => {
- const settings = createMockSettings({
- "slack-app-token": isApp ? "app-token" : null,
- "slack-token-valid?": isValid,
- "slack-token": isBot ? "bot-token" : null,
- });
-
- setupPropertiesEndpoints(settings);
- setupSettingsEndpoints([]);
-
- setupSlackManifestEndpoint();
-
- const onClose = jest.fn();
-
- renderWithProviders(<SlackSettingsModal isOpen onClose={onClose} />);
-
- await screen.findByText("Metabase on Slack");
-
- return { onClose };
-};
-
-describe("SlackSettingsModal", () => {
- it("should request closing when the app is configured", async () => {
- const { onClose } = await setup({
- isApp: true,
- isBot: false,
- isValid: true,
- });
-
- expect(screen.getByText("Metabase on Slack")).toBeInTheDocument();
- await waitFor(() => {
- expect(onClose).toHaveBeenCalled();
- });
- });
-
- it("should render the setup display and load the manifest when the app is not configured", async () => {
- await setup({ isApp: false, isBot: false, isValid: false });
-
- expect(screen.getByText("Metabase on Slack")).toBeInTheDocument();
-
- expect(
- screen.getByText("1. Click the button below and create your Slack App"),
- ).toBeInTheDocument();
-
- await waitFor(async () => {
- const gets = await findRequests("GET");
- expect(gets).toHaveLength(3);
- });
-
- const gets = await findRequests("GET");
- const manifestRequest = gets.find((request) =>
- request.url.includes("manifest"),
- );
- expect(manifestRequest).toBeDefined();
- });
-});
diff --git a/frontend/src/metabase/admin/settings/slack/SlackSetup.tsx b/frontend/src/metabase/admin/settings/slack/SlackSetup.tsx
index 805e41352cb..aefd0f6eba6 100644
--- a/frontend/src/metabase/admin/settings/slack/SlackSetup.tsx
+++ b/frontend/src/metabase/admin/settings/slack/SlackSetup.tsx
@@ -1,101 +1,157 @@
-import type { ReactNode } from "react";
-import { t } from "ttag";
+import { useDisclosure } from "@mantine/hooks";
+import { useMemo } from "react";
+import { jt, t } from "ttag";
-import { useGetSlackManifestQuery } from "metabase/api";
-import { ButtonLink } from "metabase/common/components/ExternalLink";
+import { SettingsSection } from "metabase/admin/components/SettingsSection";
+import {
+ useGetSlackManifestQuery,
+ useUpdateSlackSettingsMutation,
+} from "metabase/api";
+import { ConfirmModal } from "metabase/common/components/ConfirmModal";
+import {
+ ButtonLink,
+ ExternalLink,
+} from "metabase/common/components/ExternalLink";
import { Markdown } from "metabase/common/components/Markdown";
-import { useSetting } from "metabase/common/hooks";
-import { Box, Divider, Icon, Stack, Text, Title } from "metabase/ui";
+import { useDocsUrl, useSetting } from "metabase/common/hooks";
+import {
+ Badge,
+ Box,
+ Button,
+ Divider,
+ Flex,
+ HoverCard,
+ Icon,
+ Stack,
+ Text,
+} from "metabase/ui";
-import { SlackBadge } from "./SlackBadge";
+import { SlackConfiguration } from "./SlackConfiguration";
import { SlackSetupForm } from "./SlackSetupForm";
-import S from "./slack.module.css";
-export const SlackSetup = () => {
- const botToken = useSetting("slack-token");
- const isValid = useSetting("slack-token-valid?");
- return (
- <Stack>
- <SetupHeader isBot={!!botToken} isValid={isValid} />
- <SetupSection
- title={t`1. Click the button below and create your Slack App`}
- >
- <Text>
- <Markdown>
- {t`First, **click the button below to create your Slack App** using the Metabase configuration. Once created, click "**Install to workspace**" to authorize it.`}
- </Markdown>
- </Text>
- <SlackAppsLink />
- </SetupSection>
- <SetupSection
- title={t`2. Activate the OAuth token and create a new slack channel`}
- >
- <Text mb="md">
- <Markdown>
- {t`Click on "**OAuth and Permissions**" in the sidebar, copy the "**Bot User OAuth Token**" and paste it here.`}
- </Markdown>
- </Text>
- <SlackSetupForm />
- </SetupSection>
- </Stack>
- );
-};
-
-const SetupHeader = ({
- isBot,
+const SlackConnectionStatus = ({
isValid,
+ docsUrl,
+ token,
}: {
- isBot?: boolean;
- isValid?: boolean;
+ isValid: boolean;
+ docsUrl: string;
+ token: string | null;
}) => {
- return (
- <Box>
- {isBot ? (
- <Text>
- <SlackBadge isBot={isBot} isValid={isValid} />{" "}
- <Markdown>
- {t`We recommend you **upgrade to Slack Apps** see the instructions below:`}
- </Markdown>
- </Text>
- ) : (
- <Text c="text-secondary">
- {t`Bring the power of Metabase to your Slack #channels.`}{" "}
- {t`Follow these steps to connect to Slack:`}
- </Text>
- )}
- </Box>
- );
-};
+ const [updateSlackSettings] = useUpdateSlackSettingsMutation();
+ const [isOpened, { open: handleOpen, close: handleClose }] =
+ useDisclosure(false);
+
+ const handleDisconnect = () => {
+ updateSlackSettings({ "slack-app-token": null });
+ handleClose();
+ };
-const SetupSection = ({
- title,
- children,
-}: {
- title: string;
- children?: ReactNode;
-}) => {
return (
- <Box className={S.SetupSection}>
- <Title order={4} p="md" c="brand">
- {title}
- </Title>
- <Divider />
- <Box p="md">{children}</Box>
- </Box>
+ <>
+ <Flex justify="space-between" align="center">
+ <Flex align="center" gap="sm">
+ <Badge
+ circle
+ size="12"
+ bg={isValid ? "success" : "error"}
+ style={{ flexShrink: 0 }}
+ />
+ <Text>
+ {isValid ? t`Slack app is working` : t`Slack app is not working.`}
+ </Text>
+ {token && (
+ <HoverCard position="bottom">
+ <HoverCard.Target>
+ <Icon
+ name="info"
+ c="text-secondary"
+ size={14}
+ style={{ cursor: "pointer" }}
+ />
+ </HoverCard.Target>
+ <HoverCard.Dropdown>
+ <Stack gap="xs" p="md">
+ <Text c="text-secondary">{t`Slack Bot OAuth Token`}</Text>
+ <Text fw="bold">{token}</Text>
+ </Stack>
+ </HoverCard.Dropdown>
+ </HoverCard>
+ )}
+ {!isValid && (
+ <Text ml="sm" inline>
+ {jt`Need help? ${(<ExternalLink key="link" href={docsUrl}>{t`See our docs`}</ExternalLink>)}.`}
+ </Text>
+ )}
+ </Flex>
+
+ <Button c="danger" onClick={handleOpen}>{t`Disconnect`}</Button>
+ </Flex>
+ <ConfirmModal
+ opened={isOpened}
+ onClose={handleClose}
+ title={t`Disconnect Slack?`}
+ message={t`This will stop dashboard subscriptions from appearing in Slack until you reconnect.`}
+ confirmButtonText={t`Disconnect`}
+ onConfirm={handleDisconnect}
+ />
+ </>
);
};
-const SlackAppsLink = () => {
+export const SlackSetup = () => {
+ const slackAppToken = useSetting("slack-app-token");
+ const hasCompletedSetup = !!slackAppToken;
+ const isValid = useSetting("slack-token-valid?") ?? false;
+ const { url: docsUrl } = useDocsUrl("configuring-metabase/slack");
+
const { data: manifest } = useGetSlackManifestQuery();
- const link = manifest
- ? `/apps?new_app=1&manifest_yaml=${encodeURIComponent(manifest)}`
- : "/apps";
+ const link = useMemo(() => {
+ if (!manifest) {
+ return "/apps";
+ }
+ const encodedManifest = encodeURIComponent(JSON.stringify(manifest));
+ return `/apps?new_app=1&manifest_json=${encodedManifest}`;
+ }, [manifest]);
+
+ if (!hasCompletedSetup) {
+ return (
+ <SettingsSection title={t`Create a Slack app and connect to it.`}>
+ <Stack gap="md">
+ <Markdown>
+ {t`First, **click the button below** to create your Slack App using the Metabase configuration.`}
+ </Markdown>
+ <Box>
+ <ButtonLink href={`https://api.slack.com${link}`}>
+ <span>{t`Create Slack App`}</span>
+ <Icon name="external" opacity={0.7} ml="md" />
+ </ButtonLink>
+ </Box>
+ <Markdown>
+ {t`First, click "**Install to workspace**" to authorize it, then copy the **Bot User OAuth Token** and paste it here.`}
+ </Markdown>
+ <SlackSetupForm
+ initialValues={{
+ "slack-app-token": slackAppToken ?? "",
+ }}
+ />
+ </Stack>
+ </SettingsSection>
+ );
+ }
return (
- <ButtonLink href={`https://api.slack.com${link}`}>
- <span>{t`Create Slack App`}</span>
- <Icon name="external" opacity={0.7} ml="md" />
- </ButtonLink>
+ <SettingsSection stackProps={{ pt: "lg" }}>
+ <Box>
+ <SlackConnectionStatus
+ isValid={isValid}
+ docsUrl={docsUrl}
+ token={slackAppToken}
+ />
+ <Divider w="calc(100% + 4rem)" ml="-2rem" my="lg" />
+ <SlackConfiguration />
+ </Box>
+ </SettingsSection>
);
};
diff --git a/frontend/src/metabase/admin/settings/slack/SlackSetup.unit.spec.tsx b/frontend/src/metabase/admin/settings/slack/SlackSetup.unit.spec.tsx
index cc566ca4d2a..cab9d740203 100644
--- a/frontend/src/metabase/admin/settings/slack/SlackSetup.unit.spec.tsx
+++ b/frontend/src/metabase/admin/settings/slack/SlackSetup.unit.spec.tsx
@@ -4,41 +4,59 @@ import {
findRequests,
setupPropertiesEndpoints,
setupSettingsEndpoints,
+ setupSlackAppInfoEndpoint,
setupSlackManifestEndpoint,
setupSlackSettingsEndpoint,
} from "__support__/server-mocks";
import { renderWithProviders, screen, waitFor } from "__support__/ui";
import { createMockSettings } from "metabase-types/api/mocks";
+import { createMockSettingsState } from "metabase-types/store/mocks";
import { SlackSetup } from "./SlackSetup";
-const setup = async ({
- bugReporting,
- botToken,
-}: {
+interface SetupOptions {
+ configured?: boolean;
+ isValid?: boolean;
bugReporting?: boolean;
- botToken?: boolean;
-}) => {
+}
+
+const setup = async ({
+ configured = false,
+ isValid = true,
+ bugReporting = false,
+}: SetupOptions = {}) => {
const settings = createMockSettings({
- "slack-app-token": null,
- "slack-token": botToken ? "bot-token" : null,
- "bug-reporting-enabled": !!bugReporting,
+ "slack-app-token": configured ? "xoxb-test-token" : null,
+ "slack-token-valid?": configured && isValid,
+ "bug-reporting-enabled": bugReporting,
});
setupPropertiesEndpoints(settings);
setupSettingsEndpoints([]);
-
setupSlackSettingsEndpoint();
setupSlackManifestEndpoint();
+ setupSlackAppInfoEndpoint();
- renderWithProviders(<SlackSetup />);
+ renderWithProviders(<SlackSetup />, {
+ storeInitialState: {
+ settings: createMockSettingsState(settings),
+ },
+ });
- await screen.findByText(/Activate the OAuth token/i);
+ if (configured) {
+ if (isValid) {
+ await screen.findByText(/Slack app is working/i);
+ } else {
+ await screen.findByText(/Slack app is not working/i);
+ }
+ } else {
+ await screen.findByText(/Create a Slack app and connect to it/i);
+ }
};
describe("SlackSetup", () => {
it("should fetch the slack manifest", async () => {
- await setup({ bugReporting: false });
+ await setup();
await waitFor(async () => {
const gets = await findRequests("GET");
@@ -49,72 +67,123 @@ describe("SlackSetup", () => {
});
});
- it("should show notice about legacy bot tokens", async () => {
- await setup({ bugReporting: false, botToken: true });
- expect(
- await screen.findByText(/upgrade to Slack Apps/),
- ).toBeInTheDocument();
- });
-
it("should show instructions to set up a slack app", async () => {
- await setup({ bugReporting: false });
+ await setup();
expect(
- await screen.findByText(
- "1. Click the button below and create your Slack App",
- ),
+ await screen.findByText("Create a Slack app and connect to it."),
).toBeInTheDocument();
expect(await screen.findByText("Create Slack App")).toBeInTheDocument();
});
it("should show token input", async () => {
- await setup({ bugReporting: false });
+ await setup();
const input = await screen.findByLabelText("Slack bot user OAuth token");
expect(input).toBeInTheDocument();
});
+ it("should submit new slack settings", async () => {
+ await setup();
+
+ const tokenInput = await screen.findByLabelText(
+ "Slack bot user OAuth token",
+ );
+ await userEvent.type(tokenInput, "new-bot-token");
+
+ const submitButton = screen.getByRole("button", { name: "Connect" });
+ expect(submitButton).toBeEnabled();
+ await userEvent.click(submitButton);
+
+ const puts = await findRequests("PUT");
+ expect(puts).toHaveLength(1);
+ const [{ url, body }] = puts;
+ expect(url).toContain("/api/slack/settings");
+ expect(body).toEqual({
+ "slack-app-token": "new-bot-token",
+ });
+ });
+
it("should show bug reporting channel if bug reporting is enabled", async () => {
- await setup({ bugReporting: true });
+ await setup({ configured: true, bugReporting: true });
expect(
- await screen.findByText("Public channel for bug reports"),
+ await screen.findByText("Slack bug report channel"),
).toBeInTheDocument();
});
it("should not show bug reporting channel if bug reporting is disabled", async () => {
- await setup({ bugReporting: false });
+ await setup({ configured: true });
- await screen.findByLabelText("Slack bot user OAuth token");
expect(
- screen.queryByText("Public channel for bug reports"),
+ screen.queryByText("Slack bug report channel"),
).not.toBeInTheDocument();
});
- it("should submit new slack settings", async () => {
- setup({ bugReporting: true });
+ it("should show app icon configuration", async () => {
+ await setup({ configured: true });
- const tokenInput = await screen.findByLabelText(
- "Slack bot user OAuth token",
+ expect(screen.getByText("Slack app icon")).toBeInTheDocument();
+ expect(screen.getByText("Download App Icon")).toBeInTheDocument();
+ });
+
+ it("should show invalid status badge", async () => {
+ await setup({ configured: true, isValid: false });
+
+ expect(
+ await screen.findByText("Slack app is not working."),
+ ).toBeInTheDocument();
+ });
+
+ it("should show docs link when slack app is not working", async () => {
+ await setup({ configured: true, isValid: false });
+ expect(screen.getByText("See our docs")).toBeInTheDocument();
+ });
+
+ it("should disable submit button when token is empty", async () => {
+ await setup();
+ const submitButton = screen.getByRole("button", { name: "Connect" });
+ expect(submitButton).toBeDisabled();
+ });
+
+ it("should have correct download link for app icon", async () => {
+ await setup({ configured: true });
+ const downloadLink = screen.getByRole("link", {
+ name: "Download App Icon",
+ });
+ expect(downloadLink).toHaveAttribute(
+ "href",
+ "/app/assets/img/metabot-slackbot.png",
);
- await userEvent.type(tokenInput, "new-bot-token");
+ });
- const channelInput = await screen.findByLabelText(
- "Public channel for bug reports",
+ it("should show link to Slack app settings", async () => {
+ await setup({ configured: true });
+ const link = screen.getByRole("link", { name: "Basic Information" });
+ expect(link).toHaveAttribute(
+ "href",
+ expect.stringMatching(/^https:\/\/api\.slack\.com\/apps/),
);
- await userEvent.type(channelInput, "new-bot-channel");
+ });
- const submitButton = screen.getByRole("button", { name: "Save changes" });
- expect(submitButton).toBeEnabled();
- await userEvent.click(submitButton);
+ it("should allow disconnecting the slack connection", async () => {
+ await setup({ configured: true });
+
+ const disconnectButton = await screen.findByRole("button", {
+ name: "Disconnect",
+ });
+ await userEvent.click(disconnectButton);
+
+ // Modal opens with another Disconnect button - get all and click the second one (confirm)
+ const disconnectButtons = await screen.findAllByRole("button", {
+ name: "Disconnect",
+ });
+ await userEvent.click(disconnectButtons[1]);
const puts = await findRequests("PUT");
expect(puts).toHaveLength(1);
const [{ url, body }] = puts;
- expect(url).toContain("/api/slack/settings");
- expect(body).toEqual({
- "slack-app-token": "new-bot-token",
- "slack-bug-report-channel": "new-bot-channel",
- });
+ expect(url).toContain("api/slack/settings");
+ expect(body).toEqual({ "slack-app-token": null });
});
});
diff --git a/frontend/src/metabase/admin/settings/slack/SlackSetupForm.tsx b/frontend/src/metabase/admin/settings/slack/SlackSetupForm.tsx
index 6c3bf856e15..62ddeb315f1 100644
--- a/frontend/src/metabase/admin/settings/slack/SlackSetupForm.tsx
+++ b/frontend/src/metabase/admin/settings/slack/SlackSetupForm.tsx
@@ -2,7 +2,6 @@ import { t } from "ttag";
import * as Yup from "yup";
import { useUpdateSlackSettingsMutation } from "metabase/api";
-import { useAdminSetting } from "metabase/api/utils";
import {
Form,
FormErrorMessage,
@@ -12,33 +11,21 @@ import {
} from "metabase/forms";
import * as Errors from "metabase/lib/errors";
import { Flex, Stack } from "metabase/ui";
-import type { SlackSettings } from "metabase-types/api";
+
+type FormValues = { "slack-app-token": string };
const SLACK_SCHEMA = Yup.object({
"slack-app-token": Yup.string().ensure().required(Errors.required),
- "slack-bug-report-channel": Yup.string()
- .nullable()
- .default(null)
- .transform((value, originalValue) => (originalValue === "" ? null : value))
- .lowercase(),
});
-const DEFAULT_SETTINGS: SlackSettings = {
- "slack-app-token": "",
- "slack-bug-report-channel": "",
-};
-
export const SlackSetupForm = ({
- initialValues = DEFAULT_SETTINGS,
+ initialValues = { "slack-app-token": "" },
}: {
- initialValues?: SlackSettings;
+ initialValues?: FormValues;
}) => {
- const { value: isBugReportingEnabled } = useAdminSetting(
- "bug-reporting-enabled",
- );
const [updateSlackSettings] = useUpdateSlackSettingsMutation();
- const handleSubmit = (values: SlackSettings) =>
- updateSlackSettings(SLACK_SCHEMA.cast(values) as SlackSettings).unwrap();
+ const handleSubmit = (values: FormValues) =>
+ updateSlackSettings(SLACK_SCHEMA.cast(values) as FormValues).unwrap();
return (
<FormProvider
@@ -48,24 +35,17 @@ export const SlackSetupForm = ({
enableReinitialize
>
<Form>
- <Stack>
+ <Stack gap="sm">
<FormTextInput
name="slack-app-token"
label={t`Slack bot user OAuth token`}
placeholder="xoxb-123..."
+ style={{ flex: 1 }}
/>
- {isBugReportingEnabled && (
- <FormTextInput
- name="slack-bug-report-channel"
- label={t`Public channel for bug reports`}
- description={t`This channel will receive bug reports submitted by users.`}
- placeholder="metabase-bugs"
- />
- )}
- <Flex justify="end">
- <FormSubmitButton label={t`Save changes`} />
+ <Flex direction="row-reverse" justify="space-between">
+ <FormSubmitButton label={t`Connect`} />
+ <FormErrorMessage />
</Flex>
- <FormErrorMessage />
</Stack>
</Form>
</FormProvider>
diff --git a/frontend/src/metabase/admin/settings/slack/SlackStatus.tsx b/frontend/src/metabase/admin/settings/slack/SlackStatus.tsx
deleted file mode 100644
index 7f12a9f3d36..00000000000
--- a/frontend/src/metabase/admin/settings/slack/SlackStatus.tsx
+++ /dev/null
@@ -1,76 +0,0 @@
-import { useDisclosure } from "@mantine/hooks";
-import { jt, t } from "ttag";
-
-import { AdminSettingInput } from "metabase/admin/settings/components/widgets/AdminSettingInput";
-import {
- useGetSettingsQuery,
- useUpdateSlackSettingsMutation,
-} from "metabase/api";
-import { ConfirmModal } from "metabase/common/components/ConfirmModal";
-import { ExternalLink } from "metabase/common/components/ExternalLink";
-import { useDocsUrl } from "metabase/common/hooks";
-import { Box, Button, Flex, Stack, Text } from "metabase/ui";
-
-import { SlackBadge } from "./SlackBadge";
-
-export const SlackStatus = () => {
- const [isOpened, { open: handleOpen, close: handleClose }] =
- useDisclosure(false);
-
- const { url: docsUrl } = useDocsUrl("configuring-metabase/slack");
-
- const { data: settings } = useGetSettingsQuery();
- const isValid = settings?.["slack-token-valid?"] ?? false;
- const bugReportChannel = settings?.["slack-bug-report-channel"] ?? "";
- const bugReportingEnabled = settings?.["bug-reporting-enabled"] ?? false;
-
- const [updateSlackSettings] = useUpdateSlackSettingsMutation();
- const handleDelete = () => {
- updateSlackSettings({});
- };
-
- return (
- <Box>
- <Flex justify="space-between" align="center">
- <SlackBadge isValid={isValid} />
- {!isValid && (
- <Text ml="sm" inline>
- {jt`Need help? ${(
- <ExternalLink
- key="link"
- href={docsUrl}
- >{t`See our docs`}</ExternalLink>
- )}.`}
- </Text>
- )}
- </Flex>
- <Stack my="xl" gap="lg">
- <AdminSettingInput
- name="slack-app-token"
- title={t`Slack token`}
- description={""}
- inputType="text"
- disabled
- />
- <AdminSettingInput
- name="slack-bug-report-channel"
- title={t`Slack bug report channel`}
- inputType="text"
- hidden={!bugReportingEnabled || !bugReportChannel}
- disabled
- />
- </Stack>
- <Box mt="xl">
- <Button onClick={handleOpen}>{t`Delete Slack App`}</Button>
- <ConfirmModal
- opened={isOpened}
- onClose={handleClose}
- title={t`Are you sure you want to delete your Slack App?`}
- message={t`Doing this may stop your dashboard subscriptions from appearing in Slack until a new connection is set up. Are you sure you want to delete your Slack App integration?`}
- confirmButtonText={t`Delete`}
- onConfirm={handleDelete}
- />
- </Box>
- </Box>
- );
-};
diff --git a/frontend/src/metabase/admin/settings/slack/SlackStatus.unit.spec.tsx b/frontend/src/metabase/admin/settings/slack/SlackStatus.unit.spec.tsx
deleted file mode 100644
index 2bb7437b573..00000000000
--- a/frontend/src/metabase/admin/settings/slack/SlackStatus.unit.spec.tsx
+++ /dev/null
@@ -1,92 +0,0 @@
-import userEvent from "@testing-library/user-event";
-
-import {
- findRequests,
- setupPropertiesEndpoints,
- setupSettingsEndpoints,
- setupSlackSettingsEndpoint,
-} from "__support__/server-mocks";
-import { renderWithProviders, screen } from "__support__/ui";
-import { createMockSettings } from "metabase-types/api/mocks";
-
-import { SlackStatus } from "./SlackStatus";
-
-const setup = async ({
- isValid,
- bugReporting,
-}: {
- isValid: boolean;
- bugReporting?: boolean;
-}) => {
- const settings = createMockSettings({
- "slack-app-token": "app-token",
- "slack-token-valid?": isValid,
- "bug-reporting-enabled": !!bugReporting,
- "slack-bug-report-channel": bugReporting ? "bug-reporting-channel" : null,
- });
-
- setupPropertiesEndpoints(settings);
- setupSettingsEndpoints([]);
-
- setupSlackSettingsEndpoint();
-
- renderWithProviders(<SlackStatus />);
-
- await screen.findByText("Slack token");
-};
-
-describe("SlackStatus", () => {
- it("should show valid status badge", async () => {
- await setup({ isValid: true });
- expect(await screen.findByText("Slack app is working")).toBeInTheDocument();
- });
-
- it("Should show invalid status badge", async () => {
- await setup({ isValid: false });
- expect(
- await screen.findByText("Slack app is not working."),
- ).toBeInTheDocument();
- });
-
- it("Should show disabled token input", async () => {
- await setup({ isValid: true });
-
- const input = await screen.findByLabelText("Slack token");
- expect(input).toBeDisabled();
- });
-
- it("should show bug reporting channel if bug reporting is enabled", async () => {
- await setup({ isValid: true, bugReporting: true });
- await screen.findByLabelText("Slack token");
- expect(
- await screen.findByText("Slack bug report channel"),
- ).toBeInTheDocument();
- });
-
- it("should not show bug reporting channel if bug reporting is disabled", async () => {
- await setup({ isValid: true, bugReporting: false });
- await screen.findByLabelText("Slack token");
- expect(
- screen.queryByText("Slack Bug report channel"),
- ).not.toBeInTheDocument();
- });
-
- it("should allow deleting the slack connection", async () => {
- await setup({ isValid: true, bugReporting: false });
-
- const deleteButton = await screen.findByRole("button", {
- name: "Delete Slack App",
- });
- await userEvent.click(deleteButton);
-
- // modal confirm
- const confirmButton = await screen.findByRole("button", { name: "Delete" });
- await userEvent.click(confirmButton);
-
- const puts = await findRequests("PUT");
- expect(puts).toHaveLength(1);
- const [{ url, body }] = puts;
- expect(url).toContain("api/slack/settings");
- expect(body).toEqual({});
- });
-});
diff --git a/frontend/src/metabase/admin/settings/slack/slack.module.css b/frontend/src/metabase/admin/settings/slack/slack.module.css
deleted file mode 100644
index 80f597d2643..00000000000
--- a/frontend/src/metabase/admin/settings/slack/slack.module.css
+++ /dev/null
@@ -1,11 +0,0 @@
-.SetupSection {
- border: 1px solid var(--mb-color-border);
- border-radius: var(--mantine-radius-md);
-}
-
-.StatusBadge {
- width: 0.75rem;
- height: 0.75rem;
- margin-right: 0.5rem;
- border-radius: 50%;
-}
diff --git a/frontend/src/metabase/admin/settings/tests/setup.tsx b/frontend/src/metabase/admin/settings/tests/setup.tsx
index 20c92089be0..db2c1f64494 100644
--- a/frontend/src/metabase/admin/settings/tests/setup.tsx
+++ b/frontend/src/metabase/admin/settings/tests/setup.tsx
@@ -13,6 +13,7 @@ import {
setupPropertiesEndpoints,
setupSettingEndpoint,
setupSettingsEndpoints,
+ setupSlackAppInfoEndpoint,
setupSlackManifestEndpoint,
setupTokenStatusEndpoint,
setupUploadManagementEndpoint,
@@ -39,7 +40,11 @@ export const ossRoutes: RouteMap = {
root: { path: "", testPattern: /site name/i },
general: { path: "/general", testPattern: /site name/i },
email: { path: "/email", testPattern: /SMTP/i },
- notifications: { path: "/notifications", testPattern: /Connect to Slack/i },
+ slack: {
+ path: "/slack",
+ testPattern: /Create a Slack app and connect to it/i,
+ },
+ webhooks: { path: "/webhooks", testPattern: /Configure webhooks/i },
authentication: {
path: "/authentication",
testPattern: /Sign in with Google/i,
@@ -137,6 +142,7 @@ export const setup = async ({
setupGroupsEndpoint([]);
setupDatabasesEndpoints([]);
setupSlackManifestEndpoint();
+ setupSlackAppInfoEndpoint();
setupUploadManagementEndpoint([]);
setupUserKeyValueEndpoints({
namespace: "user_acknowledgement",
diff --git a/frontend/src/metabase/admin/settingsRoutes.tsx b/frontend/src/metabase/admin/settingsRoutes.tsx
index f827aa48790..96f9b832ce2 100644
--- a/frontend/src/metabase/admin/settingsRoutes.tsx
+++ b/frontend/src/metabase/admin/settingsRoutes.tsx
@@ -19,10 +19,11 @@ import { GeneralSettingsPage } from "./settings/components/SettingsPages/General
import { LicenseSettingsPage } from "./settings/components/SettingsPages/LicenseSettingsPage";
import { LocalizationSettingsPage } from "./settings/components/SettingsPages/LocalizationSettingsPage";
import { MapsSettingsPage } from "./settings/components/SettingsPages/MapsSettingsPage";
-import { NotificationSettingsPage } from "./settings/components/SettingsPages/NotificationSettingsPage";
import { PublicSharingSettingsPage } from "./settings/components/SettingsPages/PublicSharingSettingsPage";
+import { SlackSettingsPage } from "./settings/components/SettingsPages/SlackSettingsPage";
import { UpdatesSettingsPage } from "./settings/components/SettingsPages/UpdatesSettingsPage";
import { UploadSettingsPage } from "./settings/components/SettingsPages/UploadSettingsPage";
+import { WebhooksSettingsPage } from "./settings/components/SettingsPages/WebhooksSettingsPage";
export const getSettingsRoutes = () => (
<Route
@@ -36,7 +37,8 @@ export const getSettingsRoutes = () => (
<Route path="general" component={GeneralSettingsPage} />
<Route path="updates" component={UpdatesSettingsPage} />
<Route path="email" component={EmailSettingsPage} />
- <Route path="notifications" component={NotificationSettingsPage} />
+ <Route path="slack" component={SlackSettingsPage} />
+ <Route path="webhooks" component={WebhooksSettingsPage} />
<Route
path="authentication"
component={() => <AuthenticationSettingsPage tab="authentication" />}
diff --git a/frontend/src/metabase/api/slack.ts b/frontend/src/metabase/api/slack.ts
index 169bb430fa7..f7f81288241 100644
--- a/frontend/src/metabase/api/slack.ts
+++ b/frontend/src/metabase/api/slack.ts
@@ -1,31 +1,35 @@
-import type { EnterpriseSettings } from "metabase-types/api";
+import type { SlackAppInfo, SlackSettings } from "metabase-types/api";
import { Api } from "./api";
-type SlackSettings = Pick<
- EnterpriseSettings,
- "slack-app-token" | "slack-bug-report-channel" | "slack-token"
->;
-
export const slackApi = Api.injectEndpoints({
endpoints: (builder) => ({
- getSlackManifest: builder.query<string, void>({
- query: (params) => ({
+ getSlackManifest: builder.query<Record<string, unknown>, void>({
+ query: () => ({
method: "GET",
url: "/api/slack/manifest",
- params,
}),
}),
+ getSlackAppInfo: builder.query<SlackAppInfo, void>({
+ query: () => ({
+ method: "GET",
+ url: "/api/slack/app-info",
+ }),
+ providesTags: ["slack-app-info"],
+ }),
updateSlackSettings: builder.mutation<void, Partial<SlackSettings>>({
query: (settings) => ({
method: "PUT",
url: `/api/slack/settings`,
body: settings,
}),
- invalidatesTags: ["session-properties"],
+ invalidatesTags: ["session-properties", "slack-app-info"],
}),
}),
});
-export const { useGetSlackManifestQuery, useUpdateSlackSettingsMutation } =
- slackApi;
+export const {
+ useGetSlackManifestQuery,
+ useGetSlackAppInfoQuery,
+ useUpdateSlackSettingsMutation,
+} = slackApi;
diff --git a/frontend/src/metabase/api/tags/constants.ts b/frontend/src/metabase/api/tags/constants.ts
index 76557a17ba6..a754bb955b3 100644
--- a/frontend/src/metabase/api/tags/constants.ts
+++ b/frontend/src/metabase/api/tags/constants.ts
@@ -39,6 +39,7 @@ export const TAG_TYPES = [
"schema",
"segment",
"session-properties",
+ "slack-app-info",
"snippet",
"subscription",
"subscription-channel",
diff --git a/frontend/src/metabase/api/utils/settings.ts b/frontend/src/metabase/api/utils/settings.ts
index cc73db8c368..67d0531b7c2 100644
--- a/frontend/src/metabase/api/utils/settings.ts
+++ b/frontend/src/metabase/api/utils/settings.ts
@@ -1,5 +1,6 @@
import { useCallback, useMemo } from "react";
import { t } from "ttag";
+import _ from "underscore";
import { useToast } from "metabase/common/hooks";
import type {
@@ -131,55 +132,36 @@ export const useAdminSettings = <
async ({
toast = true,
...settings
- }: {
- toast?: boolean;
- } & Partial<EnterpriseSettings>) => {
+ }: { toast?: boolean } & Partial<EnterpriseSettings>) => {
const response = await updateSettings(settings);
- if (!toast) {
- return response;
- }
+ if (toast) {
+ if (response.error) {
+ const message =
+ (response.error as { data?: { message: string } })?.data?.message ||
+ t`Error saving settings`;
- if (response.error) {
- const message =
- (response.error as { data?: { message: string } })?.data?.message ||
- t`Error saving settings`;
-
- sendToast({ message, icon: "warning", toastColor: "danger" });
- } else {
- sendToast({ message: t`Changes saved`, icon: "check_filled" });
+ sendToast({ message, icon: "warning", toastColor: "danger" });
+ } else {
+ sendToast({ message: t`Changes saved`, icon: "check_filled" });
+ }
}
+
return response;
},
[updateSettings, sendToast],
);
+ type Values = { [K in SettingNames[number]]: EnterpriseSettings[K] };
const values = useMemo(() => {
- if (!settings) {
- return {} as Record<SettingNames[number], boolean>;
- }
-
- return settingNames.reduce(
- (acc, key) => {
- acc[key as SettingNames[number]] = !!settings[key];
- return acc;
- },
- {} as Record<SettingNames[number], boolean>,
- );
+ return (settings ? _.pick(settings, ...settingNames) : {}) as Values;
}, [settings, settingNames]);
+ type Details = { [K in SettingNames[number]]: SettingDefinition<K> };
const details = useMemo(() => {
- if (!settingsDetails) {
- return {} as Record<SettingNames[number], SettingDefinition>;
- }
-
- return settingNames.reduce(
- (acc, key) => {
- acc[key as SettingNames[number]] = settingsDetails[key];
- return acc;
- },
- {} as Record<SettingNames[number], SettingDefinition>,
- );
+ return (
+ settingsDetails ? _.pick(settingsDetails, ...settingNames) : {}
+ ) as Details;
}, [settingsDetails, settingNames]);
return {
diff --git a/frontend/src/metabase/api/utils/settings.unit.spec.tsx b/frontend/src/metabase/api/utils/settings.unit.spec.tsx
index cb890709ee7..22f10fffa34 100644
--- a/frontend/src/metabase/api/utils/settings.unit.spec.tsx
+++ b/frontend/src/metabase/api/utils/settings.unit.spec.tsx
@@ -161,7 +161,10 @@ describe("useAdminSettings", () => {
const valuesElement = await screen.findByTestId("values");
expect(valuesElement).toHaveTextContent(
- JSON.stringify({ "site-name": true, "site-url": true }),
+ JSON.stringify({
+ "site-name": "Metabased",
+ "site-url": "https://metabase.com",
+ }),
);
});
diff --git a/frontend/src/metabase/home/components/Onboarding/Onboarding.tsx b/frontend/src/metabase/home/components/Onboarding/Onboarding.tsx
index a2488004960..0dac8886a9a 100644
--- a/frontend/src/metabase/home/components/Onboarding/Onboarding.tsx
+++ b/frontend/src/metabase/home/components/Onboarding/Onboarding.tsx
@@ -523,7 +523,7 @@ export const Onboarding = () => {
<Link
className={CS.link}
key="subscription-slack"
- to="/admin/settings/notifications"
+ to="/admin/settings/slack"
>{t`Slack`}</Link>
)}.`}
</Text>
@@ -587,7 +587,7 @@ export const Onboarding = () => {
<Link
className={CS.link}
key="alert-slack"
- to="/admin/settings/notifications"
+ to="/admin/settings/slack"
>{t`Slack`}</Link>
)}.`}
</Text>
diff --git a/frontend/src/metabase/home/components/Onboarding/tests/common.unit.spec.tsx b/frontend/src/metabase/home/components/Onboarding/tests/common.unit.spec.tsx
index c16919fabd9..67f8ae9e9d1 100644
--- a/frontend/src/metabase/home/components/Onboarding/tests/common.unit.spec.tsx
+++ b/frontend/src/metabase/home/components/Onboarding/tests/common.unit.spec.tsx
@@ -343,7 +343,7 @@ describe("Onboarding", () => {
).toHaveAttribute("href", "/admin/settings/email");
expect(
within(commsSetup).getByRole("link", { name: "Slack" }),
- ).toHaveAttribute("href", "/admin/settings/notifications");
+ ).toHaveAttribute("href", "/admin/settings/slack");
const cta = screen.getByTestId("subscription-cta");
expect(within(cta).getByRole("link")).toHaveAttribute(
@@ -387,7 +387,7 @@ describe("Onboarding", () => {
).toHaveAttribute("href", "/admin/settings/email");
expect(
within(commsSetup).getByRole("link", { name: "Slack" }),
- ).toHaveAttribute("href", "/admin/settings/notifications");
+ ).toHaveAttribute("href", "/admin/settings/slack");
const cta = screen.getByTestId("alert-cta");
expect(within(cta).getByRole("link")).toHaveAttribute(
diff --git a/frontend/src/metabase/notifications/NewPulseSidebar.tsx b/frontend/src/metabase/notifications/NewPulseSidebar.tsx
index a01061fec7e..ad298873cca 100644
--- a/frontend/src/metabase/notifications/NewPulseSidebar.tsx
+++ b/frontend/src/metabase/notifications/NewPulseSidebar.tsx
@@ -50,7 +50,7 @@ export function NewPulseSidebar({
onClick={onNewSlackPulse}
/>
) : (
- <Link to="/admin/settings/notifications">
+ <Link to="/admin/settings/slack">
<ChannelCard title={t`Configure Slack`} channel="slack" />
</Link>
)}
diff --git a/frontend/src/metabase/notifications/modals/ChannelSetupModal.tsx b/frontend/src/metabase/notifications/modals/ChannelSetupModal.tsx
index 15c0e6c43e0..e92d696d8aa 100644
--- a/frontend/src/metabase/notifications/modals/ChannelSetupModal.tsx
+++ b/frontend/src/metabase/notifications/modals/ChannelSetupModal.tsx
@@ -21,14 +21,14 @@ const CHANNELS_CONFIG: {
return t`Set up Slack`;
},
icon: "slack",
- link: "/admin/settings/notifications",
+ link: "/admin/settings/slack",
},
{
get title() {
return t`Add a webhook`;
},
icon: "webhook",
- link: "/admin/settings/notifications",
+ link: "/admin/settings/webhooks",
testId: "alerts-channel-create-webhook",
},
];
diff --git a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
index 578d4ae29b3..9f45d7b5a63 100644
--- a/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
+++ b/frontend/src/metabase/notifications/modals/CreateOrEditQuestionAlertModal/CreateOrEditQuestionAlertModal.unit.spec.tsx
@@ -9,7 +9,7 @@ import {
import { setupWebhookChannelsEndpoint } from "__support__/server-mocks/channel";
import { mockSettings } from "__support__/settings";
import { createMockEntitiesState } from "__support__/store";
-import { renderWithProviders, screen, waitFor } from "__support__/ui";
+import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
import { CreateOrEditQuestionAlertModalWithQuestion } from "metabase/notifications/modals";
import type {
ChannelApiResponse,
@@ -30,17 +30,24 @@ import {
import { createSampleDatabase } from "metabase-types/api/mocks/presets";
import { createMockQueryBuilderState } from "metabase-types/store/mocks";
+const configuredAlerts = () => screen.findByTestId("alert-configured-channel");
+
+const expectConfigured = async (channel: string) =>
+ expect(
+ within(await configuredAlerts()).getByText(channel),
+ ).toBeInTheDocument();
+
+const expectNotConfigured = async (channel: string) =>
+ expect(
+ within(await configuredAlerts()).queryByText(channel),
+ ).not.toBeInTheDocument();
+
describe("CreateOrEditQuestionAlertModalWithQuestion", () => {
it("should display first available channel by default - Email", async () => {
- setup({
- isAdmin: true,
- });
+ setup({ isAdmin: true });
- await waitFor(() => {
- expect(screen.getByTestId("alert-create")).toBeInTheDocument();
- });
-
- expect(screen.getByText("Email")).toBeInTheDocument();
+ expect(await screen.findByTestId("alert-create")).toBeInTheDocument();
+ await expectConfigured("Email");
});
it.each([{ isAdmin: true }, { isAdmin: false, userCanAccessSettings: true }])(
@@ -52,12 +59,9 @@ describe("CreateOrEditQuestionAlertModalWithQuestion", () => {
...setupConfig,
});
- await waitFor(() => {
- expect(screen.getByTestId("alert-create")).toBeInTheDocument();
- });
-
- expect(screen.queryByText("Email")).not.toBeInTheDocument();
- expect(screen.getByText("Slack")).toBeInTheDocument();
+ expect(await screen.findByTestId("alert-create")).toBeInTheDocument();
+ await expectNotConfigured("Email");
+ await expectConfigured("Slack");
},
);
@@ -72,11 +76,8 @@ describe("CreateOrEditQuestionAlertModalWithQuestion", () => {
...setupConfig,
});
- await waitFor(() => {
- expect(screen.getByTestId("alert-create")).toBeInTheDocument();
- });
-
- expect(screen.queryByText("Email")).not.toBeInTheDocument();
+ expect(await screen.findByTestId("alert-create")).toBeInTheDocument();
+ await expectNotConfigured("Email");
expect(screen.getByText(mockWebhook.name)).toBeInTheDocument();
},
);
diff --git a/frontend/src/metabase/notifications/modals/components/NotificationChannelsAddMenu.tsx b/frontend/src/metabase/notifications/modals/components/NotificationChannelsAddMenu.tsx
index ceecaea58de..18ecb24c4d2 100644
--- a/frontend/src/metabase/notifications/modals/components/NotificationChannelsAddMenu.tsx
+++ b/frontend/src/metabase/notifications/modals/components/NotificationChannelsAddMenu.tsx
@@ -1,4 +1,5 @@
import { useMemo } from "react";
+import { match } from "ts-pattern";
import { t } from "ttag";
import { Link } from "metabase/common/components/Link/Link";
@@ -64,6 +65,7 @@ export const NotificationChannelsAddMenu = ({
const hasAddedSlack = channelsSpec.slack?.configured && !!slackHandler;
const canAddEmail = channelsSpec.email?.configured && !emailHandler;
const canAddSlack = channelsSpec.slack?.configured && !slackHandler;
+
const hasChannelsToAdd =
canAddEmail || canAddSlack || notAddedHookChannels.length > 0;
const hasAddedNoChannels = !notificationHandlers.length;
@@ -86,17 +88,31 @@ export const NotificationChannelsAddMenu = ({
</Button>
</Menu.Target>
<Menu.Dropdown>
- {channelsSpec.email?.configured && !emailHandler && (
- <Menu.Item onClick={() => onAddChannel({ type: "channel/email" })}>
- <Text className={CS.textList}>{t`Email`}</Text>
- </Menu.Item>
- )}
+ {match({ canAddEmail, hasAddedEmail, userCanAccessSettings })
+ .with({ canAddEmail: true }, () => (
+ <Menu.Item onClick={() => onAddChannel({ type: "channel/email" })}>
+ <Text className={CS.textList}>{t`Email`}</Text>
+ </Menu.Item>
+ ))
+ .with({ userCanAccessSettings: true, hasAddedEmail: false }, () => (
+ <MenuItemLink to="/admin/settings/email">
+ {t`Setup Email`}
+ </MenuItemLink>
+ ))
+ .otherwise(() => null)}
- {channelsSpec.slack?.configured && !slackHandler && (
- <Menu.Item onClick={() => onAddChannel({ type: "channel/slack" })}>
- <Text className={CS.textList}>{t`Slack`}</Text>
- </Menu.Item>
- )}
+ {match({ canAddSlack, hasAddedSlack, userCanAccessSettings })
+ .with({ canAddSlack: true }, () => (
+ <Menu.Item onClick={() => onAddChannel({ type: "channel/slack" })}>
+ <Text className={CS.textList}>{t`Slack`}</Text>
+ </Menu.Item>
+ ))
+ .with({ userCanAccessSettings: true, hasAddedSlack: false }, () => (
+ <MenuItemLink to="/admin/settings/slack">
+ {t`Setup Slack`}
+ </MenuItemLink>
+ ))
+ .otherwise(() => null)}
{notAddedHookChannels.length > 0 && (
<>
@@ -122,16 +138,9 @@ export const NotificationChannelsAddMenu = ({
)}
{userCanAccessSettings && (
- <Button
- variant="subtle"
- size="xs"
- component={Link}
- to="/admin/settings/notifications"
- target="_blank"
- pl="sm"
- >
- <Text size="sm" c="inherit">{t`Manage destination channels`}</Text>
- </Button>
+ <MenuItemLink to="/admin/settings/webhooks">
+ {t`Manage webhooks`}
+ </MenuItemLink>
)}
</Menu.Dropdown>
</Menu>
@@ -139,13 +148,34 @@ export const NotificationChannelsAddMenu = ({
};
const ManageDestinationsButton = () => (
- <Button
- variant="subtle"
- p={0}
- mt="-0.75rem"
- mb="-0.75rem"
- component={Link}
- to="/admin/settings/notifications"
- target="_blank"
- >{t`Manage destination channels`}</Button>
+ <Text>
+ {t`Set up`}{" "}
+ <Link variant="brand" to="/admin/settings/email">{t`Email`}</Link>
+ {", "}
+ <Link variant="brand" to="/admin/settings/slack">{t`Slack`}</Link>
+ {`, ${t`or add`} `}
+ <Link variant="brand" to="/admin/settings/webhooks">{t`Webhooks`}</Link>
+ </Text>
+);
+
+const MenuItemLink = ({
+ to,
+ children,
+}: {
+ to: string;
+ children: React.ReactNode;
+}) => (
+ <Menu.Item py="0">
+ <Button
+ variant="subtle"
+ size="xs-compact"
+ component={Link}
+ to={to}
+ target="_blank"
+ pl="0"
+ fw="normal"
+ >
+ {children}
+ </Button>
+ </Menu.Item>
);
diff --git a/frontend/src/metabase/notifications/modals/components/NotificationChannelsPicker.tsx b/frontend/src/metabase/notifications/modals/components/NotificationChannelsPicker.tsx
index b48466f9978..7478dc1b7c1 100644
--- a/frontend/src/metabase/notifications/modals/components/NotificationChannelsPicker.tsx
+++ b/frontend/src/metabase/notifications/modals/components/NotificationChannelsPicker.tsx
@@ -129,48 +129,50 @@ export const NotificationChannelsPicker = ({
return (
<Stack gap="xl" align="start">
- {channels.email?.configured && !!emailHandler && (
- <ChannelSettingsBlock
- title={t`Email`}
- iconName="mail"
- onRemoveChannel={() => onRemoveChannel(emailHandler)}
- >
- <EmailChannelEdit
- channel={emailHandler}
- users={usersListOptions}
- invalidRecipientText={getInvalidRecipientText}
- onChange={(newConfig) => onChannelChange(emailHandler, newConfig)}
- />
- </ChannelSettingsBlock>
- )}
-
- {channels.slack?.configured && !!slackHandler && (
- <ChannelSettingsBlock
- title={t`Slack`}
- iconName="int"
- onRemoveChannel={() => onRemoveChannel(slackHandler)}
- >
- <SlackChannelFieldNew
- channel={slackHandler}
- channelSpec={channels.slack}
- onChange={(newConfig) => onChannelChange(slackHandler, newConfig)}
- />
- </ChannelSettingsBlock>
- )}
-
- {userCanAccessSettings &&
- hookHandlers &&
- hookHandlers.map((channel) => (
+ <Stack gap="xl" align="start" data-testid="alert-configured-channel">
+ {channels.email?.configured && !!emailHandler && (
<ChannelSettingsBlock
- key={`webhook-${channel.channel_id}`}
- title={
- httpChannelsConfig.find(({ id }) => id === channel.channel_id)
- ?.name || t`Webhook`
- }
- iconName="webhook"
- onRemoveChannel={() => onRemoveChannel(channel)}
- />
- ))}
+ title={t`Email`}
+ iconName="mail"
+ onRemoveChannel={() => onRemoveChannel(emailHandler)}
+ >
+ <EmailChannelEdit
+ channel={emailHandler}
+ users={usersListOptions}
+ invalidRecipientText={getInvalidRecipientText}
+ onChange={(newConfig) => onChannelChange(emailHandler, newConfig)}
+ />
+ </ChannelSettingsBlock>
+ )}
+
+ {channels.slack?.configured && !!slackHandler && (
+ <ChannelSettingsBlock
+ title={t`Slack`}
+ iconName="int"
+ onRemoveChannel={() => onRemoveChannel(slackHandler)}
+ >
+ <SlackChannelFieldNew
+ channel={slackHandler}
+ channelSpec={channels.slack}
+ onChange={(newConfig) => onChannelChange(slackHandler, newConfig)}
+ />
+ </ChannelSettingsBlock>
+ )}
+
+ {userCanAccessSettings &&
+ hookHandlers &&
+ hookHandlers.map((channel) => (
+ <ChannelSettingsBlock
+ key={`webhook-${channel.channel_id}`}
+ title={
+ httpChannelsConfig.find(({ id }) => id === channel.channel_id)
+ ?.name || t`Webhook`
+ }
+ iconName="webhook"
+ onRemoveChannel={() => onRemoveChannel(channel)}
+ />
+ ))}
+ </Stack>
<NotificationChannelsAddMenu
notificationHandlers={notificationHandlers}
diff --git a/frontend/src/metabase/palette/constants.ts b/frontend/src/metabase/palette/constants.ts
index 15512cddcd7..2dd09dbc0c2 100644
--- a/frontend/src/metabase/palette/constants.ts
+++ b/frontend/src/metabase/palette/constants.ts
@@ -45,8 +45,11 @@ export const getAdminSettingsSections = (
email: {
name: t`Email`,
},
- notifications: {
- name: t`Notification channels`,
+ slack: {
+ name: t`Slack`,
+ },
+ webhooks: {
+ name: t`Webhooks`,
},
authentication: {
name: t`Authentication`,
diff --git a/frontend/src/metabase/plugins/oss/ai.ts b/frontend/src/metabase/plugins/oss/ai.ts
index c5b3896f8be..634f3aa6280 100644
--- a/frontend/src/metabase/plugins/oss/ai.ts
+++ b/frontend/src/metabase/plugins/oss/ai.ts
@@ -87,6 +87,7 @@ type PluginMetabotType = {
MetabotAppBarButton: ComponentType;
MetabotDataStudioButton: ComponentType;
MetabotDataStudioSidebar: ComponentType;
+ MetabotSlackSetup: ComponentType;
useLazyMetabotGenerateContentQuery: TypedUseLazyQuery<
MetabotGenerateContentResponse,
MetabotGenerateContentRequest,
@@ -173,6 +174,7 @@ const getDefaultPluginMetabot = (): PluginMetabotType => ({
MetabotAppBarButton: PluginPlaceholder,
MetabotDataStudioButton: PluginPlaceholder,
MetabotDataStudioSidebar: PluginPlaceholder,
+ MetabotSlackSetup: PluginPlaceholder,
useLazyMetabotGenerateContentQuery:
(() => []) as unknown as PluginMetabotType["useLazyMetabotGenerateContentQuery"],
MetabotThinkingStyles: {},
diff --git a/frontend/src/metabase/routes.jsx b/frontend/src/metabase/routes.jsx
index d1a4a2bb049..4238d3c5e86 100644
--- a/frontend/src/metabase/routes.jsx
+++ b/frontend/src/metabase/routes.jsx
@@ -127,6 +127,13 @@ export const getRoutes = (store) => {
<Route path="logout" component={Logout} />
<Route path="forgot_password" component={ForgotPassword} />
<Route path="reset_password/:token" component={ResetPassword} />
+ {/* FE routes can sometimes be prioritized over BE
+ reloading will correctly pick the SSO flow back up from the BE */}
+ <Route path="sso" onEnter={() => window.location.reload()} />
+ <Route
+ path="sso/:provider"
+ onEnter={() => window.location.reload()}
+ />
</Route>
{/* MAIN */}
diff --git a/frontend/test/__support__/server-mocks/index.ts b/frontend/test/__support__/server-mocks/index.ts
index 4acf241b833..1622a8f8ccc 100644
--- a/frontend/test/__support__/server-mocks/index.ts
+++ b/frontend/test/__support__/server-mocks/index.ts
@@ -31,6 +31,7 @@ export * from "./library";
export * from "./llm";
export * from "./logger";
export * from "./measure";
+export * from "./metabot";
export * from "./metric";
export * from "./model-indexes";
export * from "./native-query-snippet";
diff --git a/frontend/test/__support__/server-mocks/metabot.ts b/frontend/test/__support__/server-mocks/metabot.ts
index 9a708c7cb61..9c83f8c7516 100644
--- a/frontend/test/__support__/server-mocks/metabot.ts
+++ b/frontend/test/__support__/server-mocks/metabot.ts
@@ -96,3 +96,30 @@ export function setupRegenerateMetabotPromptSuggestionsEndpoint(
options,
);
}
+
+const SLACK_SETTINGS_ROUTE_NAME = "metabot-slack-settings";
+
+export function setupMetabotSlackSettingsEndpoint() {
+ fetchMock.removeRoute(SLACK_SETTINGS_ROUTE_NAME);
+ fetchMock.put(
+ "path:/api/ee/metabot-v3/slack/settings",
+ { ok: true },
+ {
+ name: SLACK_SETTINGS_ROUTE_NAME,
+ },
+ );
+}
+
+export function setupMetabotSlackSettingsEndpointWithError(
+ status: number,
+ body: string,
+) {
+ fetchMock.removeRoute(SLACK_SETTINGS_ROUTE_NAME);
+ fetchMock.put(
+ "path:/api/ee/metabot-v3/slack/settings",
+ { status, body },
+ {
+ name: SLACK_SETTINGS_ROUTE_NAME,
+ },
+ );
+}
diff --git a/frontend/test/__support__/server-mocks/slack.ts b/frontend/test/__support__/server-mocks/slack.ts
index 1ac5b70b979..541b0c9a7ad 100644
--- a/frontend/test/__support__/server-mocks/slack.ts
+++ b/frontend/test/__support__/server-mocks/slack.ts
@@ -1,5 +1,8 @@
import fetchMock from "fetch-mock";
+import type { SlackAppInfo } from "metabase-types/api";
+import { createMockSlackAppInfo } from "metabase-types/api/mocks";
+
export function setupSlackManifestEndpoint() {
fetchMock.get("path:/api/slack/manifest", "manifest-content");
}
@@ -7,3 +10,7 @@ export function setupSlackManifestEndpoint() {
export function setupSlackSettingsEndpoint() {
fetchMock.put("path:/api/slack/settings", { status: 204 });
}
+
+export function setupSlackAppInfoEndpoint(appInfo?: Partial<SlackAppInfo>) {
+ fetchMock.get("path:/api/slack/app-info", createMockSlackAppInfo(appInfo));
+}
diff --git a/resources/frontend_client/app/assets/img/metabot-slackbot.png b/resources/frontend_client/app/assets/img/metabot-slackbot.png
new file mode 100644
index 00000000000..53e0fd8f031
Binary files /dev/null and b/resources/frontend_client/app/assets/img/metabot-slackbot.png differ
diff --git a/resources/metabot/prompts/system/slackbot.selmer b/resources/metabot/prompts/system/slackbot.selmer
new file mode 100644
index 00000000000..8c6388c47cc
--- /dev/null
+++ b/resources/metabot/prompts/system/slackbot.selmer
@@ -0,0 +1,414 @@
+You are Metabot, an expert data analyst who operates as a Slack bot and helps users get insights from their Metabase data through natural conversation and natural language queries. You help users get reliable data insights through natural, collaborative interaction in Slack.
+
+**Slack Image Rule**: Don't use markdown image syntax `![anything]()` - it's broken in Slack. Calling the static_viz tool will post visualizations as separate follow-up messages in the thread, so do not try to inline them—just reference them naturally in your response.
+
+Always prioritize business-validated insights over custom analysis. When exploring unvalidated data, clearly communicate the reliability implications to users.
+
+Be direct and concise. Get users to insights efficiently while providing transparent explanations. When you create or find relevant results, navigate users to see them rather than just describing them.
+
+## Core Operating Principles
+
+From your years of experience, you've internalized these fundamental truths about data analysis in business environments:
+
+**Data Reliability Spectrum**: Not all data sources are created equal. You instinctively think in terms of a trust hierarchy:
+- **Verified dashboards and questions** represent the highest reliability—business teams depend on these
+- **Business metrics** are validated formulas that encode institutional knowledge
+- **Curated models and datasets** are structured for analysis but need interpretation
+- **Raw data exploration** is powerful but unvalidated and requires clear disclaimers
+- **Custom analysis** is experimental territory that non-technical users cannot easily verify
+
+**Business-First Mindset**: Your experience has shown you that technical accuracy means nothing without business relevance. Users asking about "revenue" don't want a sum of all transactions—they want the business-validated definition of revenue that their organization actually uses for decision-making.
+
+**Collaborative Discovery**: When business terms don't immediately map to available data, your instinct is to explore what exists first, then collaborate with users to bridge the gap. Users typically don't know their data structure in detail, so the responsibility of discovering field names, formats, and relationships falls on you.
+
+**Transparent Capability Assessment**: You've learned that users need to understand when they're getting authoritative answers versus exploratory analysis. This is especially important for non-technical users who cannot judge the correctness of custom analysis but can easily work with UI-driven, business-validated tools.
+
+**Metadata-First Approach**: Before any data operation, examine the underlying data structure - available fields, their formats, relationships, and actual values. This prevents mismatched filters and ensures accurate results.
+
+**Validated Context Reliance**: Default to the external context you have - available data sources and field metadata—when answering questions. Only lean on your own general knowledge for simple facts you're confident about. If the context doesn't give you enough to answer, respond with "I don't have the information needed to answer that" or ask the user to clarify. Never invent tables, fields, or data that aren't backed by the provided context.
+
+**Query Results Are Invisible to You**: You cannot see the actual results of queries you create—they render directly in Slack for the user. Never state specific values from results or pretend you can see them. When users ask about specific values, direct them to the rendered table or the Metabase link.
+
+# Response Style
+
+**Single Cohesive Response**: Work through your analysis internally using tools, then provide one well-structured response that flows naturally. Present results as a cohesive answer without narrating your process. Any tables or images you generate will appear as separate follow-up messages in the thread, each with their own title — so your text message should focus on context, links, and analysis rather than introducing the visual results.
+
+**No Split Sentences**: When making tool calls, do NOT output partial sentences before the tool call that you plan to complete after. Bad: "I'll analyze the data using" [tool call] "the results show...". Good: [tool call] "Here are the results of my analysis..."
+
+**Be Direct and Efficient**: Get users to insights quickly. Avoid lengthy explanations unless asked for detail but still provided necessary context and transparency to build trust.
+
+**Action Over Description**: When you find or create something useful, provide users with direct links to see it rather than just describing it. For 1-3 questions or metrics, also generate static visualizations to show users what they're looking at inline.
+
+**Visual Context**: Use the static_viz tool to create inline previews when discussing specific questions or metrics (limit to 1-3 items to avoid overwhelming). This creates a more dynamic, visual conversation experience.
+
+**Always Visualize Obvious Answers**: When there's one clear question or metric that directly answers the user's request, ALWAYS use static_viz to render it. Don't just provide the link - show the visualization inline so users can see the answer immediately.
+
+**Clear Communication**: Use simple language. Frame insights in business terms, not technical details.
+
+**No Process Narration — CRITICAL**: Never narrate what you're about to do. Call tools first, then write your response about the results. The user sees progress indicators while tools run, so they already know you're working. Default to no pre-tool text at all. Only add a brief acknowledgment before tool calls when you need clarification or need to set expectations for a long-running query. Never describe the tools you're about to use or narrate your investigation process.
+
+**Minimal Commentary for Query/Chart Requests**: When a straightforward Slack request can be answered by running a query or rendering a chart, execute the tool calls with no narration between them. After the tool work is done, keep your text to the minimum needed to orient the user—often one short sentence is enough.
+
+Banned patterns — never use these or similar phrases:
+- "I'll analyze/search/check/look into..."
+- "Let me find/show/check/create..."
+- "First, I'll..."
+- "I need to..."
+- "Perfect! I found..."
+- "I found exactly what you're looking for..."
+
+Instead: call tools silently, then present results directly.
+
+**Slack Markdown**: Use Slack-specific formatting exclusively:
+
+**Text Formatting**:
+- `*text*` for bold text (single asterisks only)
+- `_text_` for italic text (underscores only)
+- `~text~` for strikethrough text
+- `` `text` `` for inline code
+- ```text``` or ```language\ncode\n``` for code blocks
+
+**Lists**:
+- `• Item` or `- Item` for bullet lists
+- `1. Item` for numbered lists
+- Indent with spaces for nested lists
+- NEVER add extra blank lines after list items - use single line breaks only
+
+**Links**:
+- `<https://example.com>` for plain links
+- `<https://example.com|Link Text>` for links with custom text
+- `<mailto:[email protected]>` for email links
+- `<#C1234567890>` for channel links
+- `<@U1234567890>` for user mentions
+
+**Metabase Links**:
+- Use the metabase:// protocol for all Metabase entity links: `<metabase://dashboard/123|Dashboard Name>`
+- This applies to dashboards, questions, metrics, models, tables, charts, and queries
+
+**Special Formatting**:
+- `> Quote text` for blockquotes
+- `:emoji:` for emoji (e.g., `:thumbsup:`, `:warning:`)
+- Use line breaks for paragraphs
+
+**Don't Use**: These standard markdown formats don't work in Slack:
+- `**text**` (double asterisks for bold)
+- `__text__` (double underscores for bold)
+- `[text](url)` (standard markdown links)
+- `# Headers` (markdown headers)
+- `---` (horizontal rules)
+- `![alt](image.png)` or `![](url)` (markdown image syntax - broken in Slack)
+
+# Behavioral Examples
+
+Clean examples of how to respond to common requests:
+
+<example>
+user: Can we limit to 100 rows?
+assistant: I'll add a row limit to this analysis.
+</example>
+
+<example>
+user: Show me customer insights
+assistant: I found several customer-related analyses that might interest you:
+
+- 📊 <metabase://dashboard/123|Customer Analytics Dashboard>: Complete overview of customer metrics and trends
+- 📈 <metabase://question/456|Customer Lifetime Value Analysis>: CLV calculations and segmentation
+- 📈 <metabase://question/789|Customer Acquisition Trends>: New customer growth patterns
+- 📈 <metabase://question/101|Customer Retention Analysis>: Retention rates and churn analysis
+
+Which of these best matches what you're looking for?
+</example>
+
+<example>
+user: What's our revenue looking like?
+assistant: Here's your revenue overview:
+
+📊 <metabase://dashboard/123|Monthly Revenue Dashboard> - Shows current trends and key metrics
+
+Key revenue metric: 📐 <metabase://metric/456|Monthly Revenue>
+</example>
+
+<example>
+user: Analyze product performance across different regions
+assistant: Here's your regional product performance analysis:
+
+- 📈 <metabase://question/456|Product Performance by Region>: Overall performance comparison
+- 📈 <metabase://question/789|Top Products by Region>: Best performers in each region
+- 📈 <metabase://question/101|Regional Sales Trends>: Performance trends over time
+</example>
+
+<example>
+user: Show customer satisfaction
+assistant: I don't see a direct satisfaction field, but found ratings and NPS data. Which captures what you're looking for?
+</example>
+
+<example>
+user: What are our best selling products?
+assistant: [uses static_viz tool for question 123]
+Your best sellers, ranked by total sales.
+
+For broader context, check out the 📊 <metabase://dashboard/456|E-commerce Insights Dashboard> which includes top products alongside customer demographics.
+</example>
+
+<example>
+user: Can you tell me order volume by month?
+assistant: [calls construct_notebook_query with title="Monthly order volume"]
+Querying the Number of Orders metric, grouped by month.
+</example>
+
+<example>
+user: Show users where first order was more expensive than last order
+assistant: This requires comparing different orders per user, which needs custom analysis. That's less reliable than our curated dashboards, but I can explore it if that works for you.
+</example>
+
+<example>
+user: how can you help me
+assistant: I can search your existing Metabase content, create custom queries and visualizations, and analyze data trends. What type of data insight are you looking for?
+</example>
+
+<example>
+user: Filter by Austria
+assistant: I'll check the country field format first... I see it uses "AT" codes, not full names. I'll filter for "AT" to get Austria data.
+</example>
+
+## Key Decision Points
+
+When you encounter requests, assess them in this order:
+
+1. **Existing Assets First**: Always search for relevant dashboards, questions, metrics, models, and tables before creating new analysis
+2. **Capability Assessment**: Understand what your available tools can handle based on their descriptions
+3. **Field Validation**: For categorical filters, check actual field values before applying filters to make sure you understand the format
+4. **Clear Communication**: When moving from business-validated to exploratory analysis, explain the reliability difference
+
+## Complexity Recognition Patterns
+
+You recognize these as requiring advanced capabilities:
+- **Cross-row comparisons**: "first vs last", "highest vs lowest", "previous vs current"
+- **Complex conditions**: OR logic, multiple table relationships, conditional calculations
+- **Advanced analysis**: Statistical operations, trend analysis, anomaly detection
+
+When you recognize these patterns, immediately assess whether existing business metrics handle this scenario before suggesting custom analysis.
+
+# Key Guidelines
+
+**Match User Intent**: When users explicitly request SQL, go directly to SQL workflow. When they ask for general capabilities, respond based on available tools.
+
+**Check Field Formats**: Before filtering, examine actual field values to understand their format (e.g., "active" vs 1/0).
+
+**Visualize Direct Answers**: When one obvious question answers the user's request, use static_viz to show it inline.
+
+**Navigate to Results**: Since you can't see query results, direct users to view the actual data rather than stating specific values.
+
+# Decision Workflows
+
+Your years of experience have taught you systematic approaches for different types of requests:
+
+## Business Question Workflow
+
+When users ask business questions ("What's our revenue?", "Show customer growth", "How are sales trending?"):
+
+1. Search for existing assets - Use search tools to find dashboards, questions, metrics, models, and tables related to the user's business terms
+2. Prioritize verified content - If multiple options exist, recommend verified dashboards and metrics over unverified ones
+3. Visualize obvious answers - If there's one clear question/metric that answers their request, use static_viz to show it inline
+4. Present multiple options visually - For 1-3 key questions or metrics, use static_viz tool to create inline previews
+5. Provide your complete response - After all tool work is done, present results as one cohesive answer
+
+## Data Exploration Workflow
+
+When users ask for data exploration ("Show me all orders", "List customers", "What fields are available?"):
+
+1. **Understand the scope** - Determine if they want raw data listing or analytical insights
+2. **Find appropriate data source** - Look for models first (curated for analysis), then tables (raw data)
+3. **Start simple** - Use basic aggregations and groupings that provide business value
+4. **Validate field formats** - Before any filtering, check actual field values to understand their structure
+
+## Request Modification Workflow
+
+When users want to modify existing analysis ("Can we limit to 100?", "Add a filter for last month", "Group by region"):
+
+1. **Identify current context** - Look at conversation history to understand what analysis exists
+2. **Use same approach** - Apply modifications using the same tool/method that created the original analysis
+3. **Only escalate when blocked** - Switch to different tools only when current approach genuinely cannot handle the modification
+4. **Maintain user's workflow** - Keep the analysis in the same format/environment the user is already working with
+
+## Ambiguity Resolution Workflow
+
+When requests are unclear or ambiguous ("Show performance", "Customer satisfaction data", "Sales by region"):
+
+1. **Explore available data first** - Use metadata tools to understand what fields, metrics, and assets actually exist
+2. **Map business terms to data** - Find the closest available data that relates to the user's business concept
+3. **Present discovered options** - Show what you found and ask which direction matches their intent
+4. **Avoid technical questions** - Don't ask users about field names or data structure they likely don't know
+
+
+# Communication Style
+
+Your communication reflects your experience as a collaborative data partner. You strike a balance between being confident in your expertise while being transparent about limitations.
+
+## Tone and Approach
+
+**Conversational and Direct**: You communicate like an experienced colleague - friendly but focused on getting users the insights they need. Avoid overly technical language or formal business speak.
+
+**Confident but Transparent**: When working with verified business assets, you speak with confidence. When venturing into exploratory territory, you clearly communicate reliability implications without being overly cautious.
+
+**Collaborative**: You work with users to refine understanding rather than demanding perfect specifications upfront. You present options and guide decisions rather than making assumptions.
+
+## Reliability Signaling
+
+You naturally weave reliability context into your responses:
+
+*High Confidence (Business-Validated Assets)*:
+- "I found this 📊 <metabase://dashboard/123|Monthly Revenue Dashboard> that tracks our key revenue metrics"
+- "Based on the 📐 <metabase://metric/456|Customer Acquisition> metric, which is validated by the business team"
+- "This 📈 <metabase://question/789|verified Sales Analysis> shows the trends you're looking for"
+
+*Medium Confidence (Curated but Unverified)*:
+- "Looking at the 📦 <metabase://model/456|Order Analysis> model, I can see patterns in customer behavior"
+- "The 🗂️ <metabase://table/789|Customer Data> shows some interesting trends, though this hasn't been verified by business teams"
+
+*Exploratory (Custom Analysis)*:
+- "I can explore this with custom analysis, but keep in mind it's less reliable than our curated dashboards"
+- "This custom query shows some patterns, though you'll want to validate these findings with business context"
+- "Raw data exploration suggests... (note this is experimental territory)"
+
+## Natural Integration
+
+*Linking and References*: Use descriptive names that tell users what they'll see, integrated naturally into conversation:
+- "The 📈 <metabase://question/456|Customer Segmentation Analysis> breaks this down by region"
+
+*Never mention technical IDs*: Always use human-readable descriptions. Users don't need to know internal identifiers.
+
+## User Experience Focus
+
+*Business Context First*: Frame everything in business terms. Users care about insights, not technical implementation.
+
+*Assumption Transparency*: When making assumptions, state them clearly as starting points for refinement.
+
+*Reliability Without Jargon*: Make data reliability clear in simple terms, not technical methodologies.
+
+{% if tool_instructions %}
+# Tool-Specific Instructions
+
+The following tools have specific behavioral requirements that you must follow:
+
+<tools>
+{% for tool_instruction in tool_instructions %}
+<tool name="{{ tool_instruction.tool_name }}">
+{{ tool_instruction.instructions }}
+</tool>
+{% endfor %}
+</tools>
+{% endif %}
+
+# Environment Integration
+
+Current date and time: {{ current_time }}
+
+## Data Source Understanding
+
+You work with different types of data sources, each with different reliability levels:
+**Dashboards**: Collections of questions arranged into shareable reports.
+
+**Questions**: Saved queries paired with visualizations—the fundamental analytical unit in Metabase. They can be built from tables, models, metrics, or other questions.
+
+**Metrics**: Business-validated formulas that represent trusted calculations. These are your preferred choice for any aggregation request and can be filtered and grouped as needed.
+
+**Models**: Curated, user-friendly datasets designed for analysis. Excellent for exploration when no specific metric fits the request.
+
+**Tables**: Raw data sources. Use when fundamental data isn't available in curated form, but always communicate the exploratory nature.
+
+**Verified Assets**: Always prioritize verified dashboards, questions, and metrics over unverified ones. They represent domain expert validation and business approval.
+
+## Essential Responses
+
+For specific situations, use these exact responses:
+
+- **When you don't understand the user input**: "Sorry, I didn't understand that. Could you try again, please?"
+- **When the user asks who your favorite person is**: "You, but don't tell anyone" (the asking user is always your favorite)
+- **Questions about BI tool competitors**: "My mom says I'm the best."
+
+## Technical Integration
+
+**Linking Format**: Use `emoji <metabase://type/id|Display Name>` where type is dashboard, question, metric, model, table, chart, or query. Always prefix with the appropriate emoji OUTSIDE the link.
+
+**Link Emojis**: ALWAYS prefix links with the appropriate emoji:
+- 📊 Dashboard: `📊 <metabase://dashboard/123|Sales Dashboard>`
+- 📈 Card/Question: `📈 <metabase://question/456|Revenue Analysis>`
+- 🔄 Transform: `🔄 <metabase://transform/789|Data Transform>`
+- 📁 Collection: `📁 <metabase://collection/112|Marketing Reports>`
+- 📦 Dataset/Model: `📦 <metabase://model/131|Customer Data>`
+- 📐 Metric: `📐 <metabase://metric/161|Monthly Revenue>`
+- 🗂️ Table: `🗂️ <metabase://table/192|Orders Table>`
+
+All Metabase links must use the metabase:// protocol format.
+
+**Direct Access**: Always link users to existing dashboards and assets when they are relevant, using `<metabase://type/id|Name>` format.
+
+**Visual Previews**: Use the static_viz tool when discussing 1-3 specific questions or metrics to show inline visual previews. This creates a more engaging, visual conversation while avoiding information overload.
+
+**No Markdown Images**: Don't use `![anything]()` markdown syntax in Slack. Use the static_viz tool for images.
+
+**Visualize Direct Answers**: When a single question or metric directly answers the user's request, use static_viz to render it inline.
+
+**Always Link Saved Entities**: When you mention a saved question, dashboard, metric, model, or table by name, ALWAYS wrap it in a `<metabase://type/id|Name>` link with the appropriate emoji prefix. Never reference a saved entity by name without linking it.
+
+## Visualization Titles
+
+Visualizations are posted as *separate* follow-up messages in the thread — not embedded in your text. Each visualization message includes an automatic link to open it in Metabase.
+
+**Saved questions and metrics (`static_viz`)**: The entity's actual name is used as the title automatically.
+
+**Ad-hoc queries (`construct_notebook_query`)**: The title you provide is used as the visualization title. Write it like a saved question name — a short, standalone description of what the query shows. Good: "Revenue by region, Q1 2025", "Monthly order volume". Bad: "Showing your revenue breakdown", "Here's what I found".
+
+- **Use future tense.** Visualizations are generated asynchronously and appear after your text. Say "I'll show..." not "Here are..." — the results haven't appeared yet when your text is shown.
+
+**You must call the tool to render tables.** Tables only appear when you call `construct_notebook_query`. Never skip the tool call and just provide a link—the table won't render.
+
+**Prefer tables for data.** Tables are easier to read and copy in Slack. Only use chart display types when users explicitly ask for a chart, graph, or visualization.
+
+**Set `display` explicitly for Slackbot charts.** When you use `construct_notebook_query` to answer with a visualization, explicitly set the tool call's `display`. If the user requests a specific chart type, `display` must match it. Do not omit `display` for chart or graph requests. Only omit `display` when you intentionally want a plain table and the user did not request any visualization type.
+
+**Timing expectations**: When you know a question's average query time (from `get_report_details`), use it to set expectations before rendering:
+- Under 5s: don't mention timing — results appear quickly
+- 5–30s: brief mention, e.g. "This one takes about 15 seconds"
+- 30s–2min: set expectations, e.g. "Hang tight, this usually takes about a minute"
+- Over 2min: warn clearly, e.g. "This is a heavy query — usually takes around 3 minutes"
+Keep it casual and natural. For ad-hoc queries where you don't have timing data, don't guess.
+
+**Field References**: When discussing data fields, use human-readable names from field descriptions, never internal field IDs or technical identifiers.
+
+## CSV File Uploads
+
+Users can upload CSV or TSV files directly through Slack. When uploaded, these files are automatically converted into Metabase models that you can query and analyze.
+
+When you receive a message indicating files have been uploaded:
+- **Successful uploads**: The system will tell you the filename and model ID (e.g., "sales_data.csv (model ID: 123)")
+- **Failed uploads**: The system will provide the filename and error message for you to explain to the user
+- **Skipped files**: Non-CSV/TSV files (PDFs, images, etc.) are not supported; inform the user only CSV and TSV files can be uploaded
+
+When CSV files are successfully uploaded:
+
+1. **Proactively inspect the new models** using `list_available_fields` — don't wait for the user to ask
+2. **Always include model references** in the format below — this is critical for conversation continuity since the model ID is not otherwise preserved in the chat history
+
+**Response format:**
+
+```
+Your data has been uploaded: 📦 <metabase://model/{id}|{display_name}>
+
+{initial_analysis}
+```
+
+For multiple files, list each model on its own line:
+
+```
+Your data has been uploaded:
+• 📦 <metabase://model/{id1}|{display_name1}>
+• 📦 <metabase://model/{id2}|{display_name2}>
+
+{initial_analysis}
+```
+
+Where:
+- `{id}` — the model ID from the upload message
+- `{display_name}` — the model's display name (from `list_available_fields`, not the original filename)
diff --git a/resources/migrations/060/20260303_metabot_slack.yaml b/resources/migrations/060/20260303_metabot_slack.yaml
new file mode 100644
index 00000000000..480be605594
--- /dev/null
+++ b/resources/migrations/060/20260303_metabot_slack.yaml
@@ -0,0 +1,127 @@
+## Metabot Slack integration migrations
+
+databaseChangeLog:
+ - logicalFilePath: migrations/060_update_migrations.yaml
+ - changeSet:
+ id: v60.2026-03-03T21:28:30
+ author: noahmoss
+ comment: Create the Slack Metabot instance
+ preConditions:
+ - onFail: MARK_RAN
+ - sqlCheck:
+ expectedResult: 0
+ sql: >-
+ SELECT COUNT(*) FROM metabot WHERE entity_id = 'slackbotmetabotmetabo';
+ rollback:
+ - sql:
+ sql: >-
+ DELETE FROM metabot WHERE entity_id = 'slackbotmetabotmetabo';
+ changes:
+ - sql:
+ sql: >-
+ INSERT INTO metabot (
+ name
+ , description
+ , entity_id
+ , created_at
+ , updated_at
+ ) VALUES (
+ 'Slack Metabot'
+ , 'Metabot instance for Slack users.'
+ , 'slackbotmetabotmetabo'
+ , now()
+ , now()
+ );
+
+ - changeSet:
+ id: v60.2026-03-04T10:00:00
+ author: sloansparger
+ comment: Add slack_msg_id to metabot_message for tracking Slack message IDs
+ changes:
+ - addColumn:
+ tableName: metabot_message
+ columns:
+ - column:
+ name: slack_msg_id
+ type: varchar(255)
+ remarks: Slack message ID (ts) for correlating with Slack thread history
+ constraints:
+ nullable: true
+
+ - changeSet:
+ id: v60.2026-03-06T18:05:00
+ author: noahmoss
+ comment: Add channel_id to metabot_message for Slack response correlation
+ changes:
+ - addColumn:
+ tableName: metabot_message
+ columns:
+ - column:
+ name: channel_id
+ type: varchar(255)
+ remarks: Slack channel ID for correlating Slack responses
+ constraints:
+ nullable: true
+
+ - changeSet:
+ id: v60.2026-03-06T18:06:00
+ author: noahmoss
+ comment: Index on metabot_message.channel_id and slack_msg_id
+ changes:
+ - createIndex:
+ indexName: idx_metabot_message_channel_id_slack_msg_id
+ tableName: metabot_message
+ columns:
+ - column:
+ name: channel_id
+ - column:
+ name: slack_msg_id
+ rollback:
+ - dropIndex:
+ tableName: metabot_message
+ indexName: idx_metabot_message_channel_id_slack_msg_id
+
+ - changeSet:
+ id: v60.2026-03-06T22:30:00
+ author: noahmoss
+ comment: Add deleted_at to metabot_message for Slack response removal
+ changes:
+ - addColumn:
+ tableName: metabot_message
+ columns:
+ - column:
+ name: deleted_at
+ type: ${timestamp_type}
+ remarks: Soft delete timestamp for removed Slack metabot responses
+ constraints:
+ nullable: true
+
+ - changeSet:
+ id: v60.2026-03-06T22:31:00
+ author: noahmoss
+ comment: Add deleted_by_user_id to metabot_message for Slack response removal
+ changes:
+ - addColumn:
+ tableName: metabot_message
+ columns:
+ - column:
+ name: deleted_by_user_id
+ type: integer
+ remarks: Metabase user ID who removed the Slack metabot response
+ constraints:
+ nullable: true
+
+ - changeSet:
+ id: v60.2026-03-06T22:39:30
+ author: noahmoss
+ comment: Add user_id to metabot_message to track which user each message belongs to
+ changes:
+ - addColumn:
+ tableName: metabot_message
+ columns:
+ - column:
+ name: user_id
+ type: integer
+ remarks: Metabase user ID associated with this message
+ constraints:
+ nullable: true
diff --git a/resources/slack-manifest.yaml b/resources/slack-manifest.yaml
deleted file mode 100644
index c99f4d69a4e..00000000000
--- a/resources/slack-manifest.yaml
+++ /dev/null
@@ -1,21 +0,0 @@
-_metadata:
- major_version: 1
- minor_version: 1
-display_information:
- name: Metabase
- description: Bringing the power of Metabase to your Slack #channels!
- background_color: "#509EE3"
-features:
- bot_user:
- display_name: Metabase
-oauth_config:
- scopes:
- bot:
- - users:read
- - channels:read
- - channels:join
- - files:write
- - chat:write
- - chat:write.customize
- - chat:write.public
- - groups:read
diff --git a/src/metabase/analytics/prometheus.clj b/src/metabase/analytics/prometheus.clj
index ec8c000f619..aa0d8743fdf 100644
--- a/src/metabase/analytics/prometheus.clj
+++ b/src/metabase/analytics/prometheus.clj
@@ -540,6 +540,20 @@
{:description "Duration in milliseconds of sql-tools operations."
:labels [:parser :operation]
:buckets [1 5 10 25 50 100 250 500 1000 2500 5000 10000 30000]})
+ ;; slackbot metrics
+ (prometheus/counter :metabase-slackbot/responses-generated
+ {:description "Number of responses generated by the Slack bot."
+ :labels [:source :result]})
+ (prometheus/histogram :metabase-slackbot/response-duration-ms
+ {:description "Duration in milliseconds of Slack bot response generation."
+ :labels [:source]
+ ;; 100ms -> 5 minutes
+ :buckets [100 500 1000 2500 5000 10000 30000 60000 120000 300000]})
+ (prometheus/counter :metabase-slackbot/responses-deleted
+ {:description "Number of Slack bot responses deleted by users."})
+ (prometheus/counter :metabase-slackbot/file-uploads
+ {:description "Number of file uploads via the Slack bot."
+ :labels [:result]})
;; metabot / LLM agent metrics
(prometheus/counter :metabase-metabot/llm-requests
{:description "LLM provider API requests"
diff --git a/src/metabase/channel/api/slack.clj b/src/metabase/channel/api/slack.clj
index fd061f25e6b..e3e97c535a6 100644
--- a/src/metabase/channel/api/slack.clj
+++ b/src/metabase/channel/api/slack.clj
@@ -1,19 +1,28 @@
(ns metabase.channel.api.slack
"/api/slack endpoints"
(:require
- [clojure.java.io :as io]
+ [clojure.set :as set]
[clojure.string :as str]
[metabase.api.macros :as api.macros]
[metabase.channel.settings :as channel.settings]
[metabase.channel.slack :as slack]
[metabase.config.core :as config]
[metabase.permissions.core :as perms]
+ [metabase.premium-features.core :refer [defenterprise defenterprise-schema]]
+ [metabase.settings.core :as setting]
[metabase.util.i18n :refer [tru]]
[metabase.util.json :as json]
+ [metabase.util.log :as log]
[metabase.util.malli.schema :as ms]))
(set! *warn-on-reflection* true)
+(defenterprise clear-slack-bot-settings!
+ "Clears enterprise slackbot settings when the Slack token is cleared.
+ OSS implementation is a no-op."
+ metabase-enterprise.slackbot.api
+ [])
+
(defn- truncate-url
"Cut length of long URLs to avoid spamming the Slack channel"
[url]
@@ -88,36 +97,37 @@
3. truthy, valid token -> refresh "
[_route-params
_query-params
- {:keys [slack-app-token slack-bug-report-channel]}
+ {:keys [slack-app-token slack-bug-report-channel] :as body}
:- [:map
[:slack-app-token {:optional true} [:maybe ms/NonBlankString]]
[:slack-bug-report-channel {:optional true} [:maybe :string]]]]
(perms/check-has-application-permission :setting)
(try
- ;; Clear settings if no values are provided
- (when (nil? slack-app-token)
- (channel.settings/slack-app-token! nil)
- (slack/clear-channel-cache!))
-
- (when (and slack-app-token
- (not config/is-test?)
- (not (slack/valid-token? slack-app-token)))
- (slack/clear-channel-cache!)
- (throw (ex-info (tru "Invalid Slack token.")
- {:errors {:slack-app-token (tru "invalid token")}})))
- (channel.settings/slack-app-token! slack-app-token)
- (if slack-app-token
- (do (channel.settings/slack-token-valid?! true)
- ;; Clear the deprecated `slack-token` when setting a new `slack-app-token`
- (channel.settings/slack-token! nil)
- ;; refresh user/conversation cache when token is newly valid
- (slack/refresh-channels-and-usernames-when-needed!))
- ;; clear user/conversation cache when token is newly empty
- (slack/clear-channel-cache!))
+ ;; Only handle token changes when the key is explicitly provided in the request
+ (when (contains? body :slack-app-token)
+ (if (nil? slack-app-token)
+ ;; Clear settings when token is explicitly set to nil/empty
+ (do
+ (setting/set-many! {:slack-token-valid? false
+ :slack-app-token nil
+ :slack-bug-report-channel nil})
+ (slack/clear-channel-cache!)
+ (clear-slack-bot-settings!))
+ ;; Set new token
+ (do
+ (when (and (not config/is-test?)
+ (not (slack/valid-token? slack-app-token)))
+ (slack/clear-channel-cache!)
+ (throw (ex-info (tru "Invalid Slack token.")
+ {:errors {:slack-app-token (tru "invalid token")}})))
+ (setting/set-many! {:slack-app-token slack-app-token
+ :slack-token-valid? true})
+ (slack/refresh-channels-and-usernames-when-needed!))))
- (when slack-bug-report-channel
+ (when (contains? body :slack-bug-report-channel)
(let [processed-bug-channel (channel.settings/process-files-channel-name slack-bug-report-channel)]
- (when (not (slack/channel-exists? processed-bug-channel))
+ (when (and processed-bug-channel
+ (not (slack/channel-exists? processed-bug-channel)))
(throw (ex-info (tru "Slack channel not found.")
{:errors {:slack-bug-report-channel (tru "channel not found")}})))
(channel.settings/slack-bug-report-channel! processed-bug-channel)))
@@ -126,18 +136,125 @@
(catch clojure.lang.ExceptionInfo info
{:status 400, :body (ex-data info)})))
-(def ^:private slack-manifest
- (delay (slurp (io/resource "slack-manifest.yaml"))))
+(def SlackManifest
+ "Malli schema for Slack app manifest. OSS uses a simple manifest, while EE with metabot-v3
+ returns a full manifest with additional features like slash commands, event subscriptions, etc."
+ [:map
+ [:display_information [:map
+ [:name :string]
+ [:description :string]
+ [:background_color :string]]]
+ [:features [:map
+ [:bot_user [:map
+ [:display_name :string]
+ [:always_online {:optional true} :boolean]]]
+ [:app_home {:optional true} [:map
+ [:home_tab_enabled :boolean]
+ [:messages_tab_enabled :boolean]
+ [:messages_tab_read_only_enabled :boolean]]]
+ [:assistant_view {:optional true} [:map
+ [:assistant_description :string]]]
+ [:slash_commands {:optional true} [:sequential [:map
+ [:command :string]
+ [:url ms/Url]
+ [:description :string]
+ [:should_escape :boolean]]]]]]
+ [:oauth_config [:map
+ [:redirect_urls {:optional true} [:sequential ms/Url]]
+ [:scopes [:map
+ [:bot [:sequential :string]]]]]]
+ [:settings {:optional true} [:map
+ [:event_subscriptions [:map
+ [:request_url ms/Url]
+ [:bot_events [:sequential :string]]]]
+ [:interactivity [:map
+ [:is_enabled :boolean]
+ [:request_url ms/Url]]]
+ [:org_deploy_enabled :boolean]
+ [:socket_mode_enabled :boolean]
+ [:token_rotation_enabled :boolean]]]])
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :get "/manifest"
- "Returns the YAML manifest file that should be used to bootstrap new Slack apps"
+(defenterprise-schema get-slack-manifest :- SlackManifest
+ "Returns the Slack app manifest. OSS returns basic manifest; EE with metabot-v3 returns full MetaBot manifest."
+ metabase-enterprise.slackbot.api
+ []
+ {:display_information {:name "Metabot"
+ :description "Bringing the power of Metabase to your Slack #channels!"
+ :background_color "#509EE3"}
+ :features {:bot_user {:display_name "Metabot"}}
+ :oauth_config {:scopes {:bot ["users:read"
+ "channels:read"
+ "channels:join"
+ "files:write"
+ "chat:write"
+ "chat:write.customize"
+ "chat:write.public"
+ "groups:read"]}}})
+
+(api.macros/defendpoint :get "/manifest" :- SlackManifest
+ "Returns the JSON manifest file that should be used to bootstrap new Slack apps"
+ []
+ (perms/check-has-application-permission :setting)
+ (get-slack-manifest))
+
+(def SlackAppInfo
+ "Malli schema for Slack app info response. Fields are nullable when
+ Slack is not configured or the token doesn't provide app info."
+ [:map {:closed true}
+ [:app_id [:maybe ms/NonBlankString]]
+ [:team_id [:maybe ms/NonBlankString]]
+ [:scopes [:maybe [:map {:closed true}
+ [:actual [:sequential :string]]
+ [:required [:sequential :string]]
+ [:missing [:sequential :string]]
+ [:extra [:sequential :string]]]]]])
+
+(defn- app-info
+ "Returns the team_id, scopes, and app_id (requires users:read scope) from Slack's API.
+ Returns nil values if Slack is not configured or the info isn't available."
+ []
+ (let [not-configured {:app_id nil :team_id nil :scopes nil}]
+ (if-not (channel.settings/slack-configured?)
+ not-configured
+ (let [auth-response (try
+ (slack/GET "auth.test")
+ (catch Exception e
+ (if (= :slack/invalid-token (:error-type (ex-data e)))
+ nil
+ (throw e))))]
+ (if (nil? auth-response)
+ not-configured
+ (let [team-id (:team_id auth-response)
+ bot-id (:bot_id auth-response)
+ app-id (when bot-id
+ (try
+ (-> (slack/GET "bots.info" :bot bot-id)
+ :bot
+ :app_id)
+ (catch Exception e
+ ;; bots.info requires users:read scope which may not be present
+ (log/warn e "Failed to fetch app_id from bots.info (may require users:read scope)")
+ nil)))
+ scopes-header (get-in auth-response [:metabase.channel.slack/headers "x-oauth-scopes"])
+ actual-scopes (if (str/blank? scopes-header)
+ #{}
+ (set (str/split scopes-header #",")))
+ required-scopes (-> (get-slack-manifest) :oauth_config :scopes :bot set)
+ missing-scopes (set/difference required-scopes actual-scopes)
+ extra-scopes (set/difference actual-scopes required-scopes)]
+ {:app_id app-id
+ :team_id team-id
+ :scopes {:actual (vec (sort actual-scopes))
+ :required (vec (sort required-scopes))
+ :missing (vec (sort missing-scopes))
+ :extra (vec (sort extra-scopes))}}))))))
+
+(api.macros/defendpoint :get "/app-info" :- SlackAppInfo
+ "Returns the Slack app_id and team_id. Used by the frontend to construct
+ direct links to the Slack app settings page."
[]
(perms/check-has-application-permission :setting)
- @slack-manifest)
+ (app-info))
;; Handle bug report submissions to Slack
;;
diff --git a/src/metabase/channel/email/slack_token_error.hbs b/src/metabase/channel/email/slack_token_error.hbs
index 725b64b5d50..43bfae87023 100644
--- a/src/metabase/channel/email/slack_token_error.hbs
+++ b/src/metabase/channel/email/slack_token_error.hbs
@@ -7,6 +7,6 @@
<h2 style="font-weight: normal; color: #4C545B; line-height: 34px;">Your Slack connection stopped working</h2>
<p style="line-height: 22px; margin-bottom: 40px">This may affect existing dashboard subscriptions. Follow the steps in settings to reconnect Slack and get things up and running again.</p>
</div>
- <a style="{{context.style.button}}" href="{{context.site_url}}/admin/settings/notifications">Go to settings</a>
+ <a style="{{context.style.button}}" href="{{context.site_url}}/admin/settings/slack">Go to settings</a>
</div>
{{> metabase/channel/email/_footer.hbs }}
diff --git a/src/metabase/channel/render/body.clj b/src/metabase/channel/render/body.clj
index e2bc0ef4be7..427422f8dc4 100644
--- a/src/metabase/channel/render/body.clj
+++ b/src/metabase/channel/render/body.clj
@@ -9,6 +9,7 @@
[metabase.channel.render.js.svg :as js.svg]
[metabase.channel.render.style :as style]
[metabase.channel.render.table :as table]
+ [metabase.channel.render.table-data :as table-data]
[metabase.channel.render.util :as render.util]
[metabase.channel.settings :as channel.settings]
[metabase.formatter.core :as formatter]
@@ -60,15 +61,6 @@
;; NOTE: hiccup does not escape content by default so be sure to use "h" to escape any user-controlled content :-/
-;;; +----------------------------------------------------------------------------------------------------------------+
-;;; | Helper Fns |
-;;; +----------------------------------------------------------------------------------------------------------------+
-
-(defn show-in-table?
- "Should this column be shown in a rendered table in a Pulse?"
- [{:keys [visibility_type] :as _column}]
- (not (contains? #{:details-only :retired :sensitive} visibility_type)))
-
;;; --------------------------------------------------- Formatting ---------------------------------------------------
(mu/defn- format-scalar-value
@@ -98,15 +90,6 @@
;;; --------------------------------------------------- Rendering ----------------------------------------------------
-(defn- create-remapping-lookup
- "Creates a map with from column names to a column index. This is used to figure out what a given column name or value
- should be replaced with"
- [cols]
- (into {}
- (for [[col-idx {:keys [remapped_from]}] (map vector (range) cols)
- :when remapped_from]
- [remapped_from col-idx])))
-
(defn- column-name
"Returns first column name from a hierarchy of possible column names"
[card col]
@@ -126,7 +109,7 @@
[remapping-lookup card cols]
{:row
(for [maybe-remapped-col cols
- :when (show-in-table? maybe-remapped-col)
+ :when (table-data/show-in-table? maybe-remapped-col)
:let [col (if (:remapped_to maybe-remapped-col)
(nth cols (get remapping-lookup (:name maybe-remapped-col)))
maybe-remapped-col)
@@ -145,7 +128,7 @@
(for [row rows]
{:row (for [[maybe-remapped-col maybe-remapped-row-cell fmt-fn] (map vector cols row formatters)
:when (and (not (:remapped_from maybe-remapped-col))
- (show-in-table? maybe-remapped-col))
+ (table-data/show-in-table? maybe-remapped-col))
:let [[_formatter row-cell] (if (:remapped_to maybe-remapped-col)
(let [remapped-index (get remapping-lookup (:name maybe-remapped-col))]
[(nth formatters remapped-index)
@@ -159,7 +142,7 @@
([timezone-id :- [:maybe :string]
card
{:keys [cols rows viz-settings], :as _data}]
- (let [remapping-lookup (create-remapping-lookup cols)
+ (let [remapping-lookup (table-data/create-remapping-lookup cols)
row-limit (min (channel.settings/attachment-table-row-limit) 100)]
(cons
(query-results->header-row remapping-lookup card cols)
@@ -195,7 +178,7 @@
(mr/def ::RenderedPartCard
"Schema used for functions that operate on pulse card contents and their attachments"
[:map
- [:attachments [:maybe [:map-of :string (ms/InstanceOfClass URL)]]]
+ [:attachments {:optional true} [:maybe [:map-of :string (ms/InstanceOfClass URL)]]]
[:content [:sequential :any]]
[:render/text {:optional true} [:maybe :string]]])
@@ -242,7 +225,7 @@
data (-> unordered-data
(assoc :rows ordered-rows)
(assoc :cols ordered-cols))
- filtered-cols (filter show-in-table? ordered-cols)
+ filtered-cols (filter table-data/show-in-table? ordered-cols)
minibar-cols (minibar-columns (get-in unordered-data [:results_metadata :columns] []) viz-settings)
table-body [:div
(table/render-table
diff --git a/src/metabase/channel/render/card.clj b/src/metabase/channel/render/card.clj
index 4580c53011c..bb94d4c4a9e 100644
--- a/src/metabase/channel/render/card.clj
+++ b/src/metabase/channel/render/card.clj
@@ -26,11 +26,21 @@
[:channel.render/include-title? {:description "default: false", :optional true} :boolean]
[:channel.render/include-description? {:description "default: false", :optional true} :boolean]
[:channel.render/disable-links? {:description "default: false", :optional true} :boolean]
- [:channel.render/include-inline-parameters? {:description "default: false", :optional true} :boolean]])
+ [:channel.render/include-inline-parameters? {:description "default: false", :optional true} :boolean]
+ [:channel.render/padding-x {:description "default: 0, horizontal pixels around image", :optional true} [:maybe :int]]
+ [:channel.render/padding-y {:description "default: 0, vertical pixels around image", :optional true} [:maybe :int]]])
+
+(mr/def ::adhoc-card
+ "Schema for an ad-hoc (unsaved) card."
+ [:map
+ [:display :keyword]
+ [:visualization_settings {:optional true} [:maybe :map]]
+ [:name {:optional true} [:maybe :string]]])
(defn- card-href
[card]
- (h (urls/card-url (u/the-id card))))
+ (when-let [card-id (u/id card)]
+ (h (urls/card-url card-id))))
(mu/defn- make-title-if-needed :- [:maybe ::body/RenderedPartCard]
[render-type card dashcard options :- [:maybe ::options]]
@@ -263,7 +273,22 @@
result
width
options :- [:maybe ::options]]
- (png/render-html-to-png (render-pulse-card :inline timezone-id pulse-card nil result options) width)))
+ (png/render-html-to-png (render-pulse-card :inline timezone-id pulse-card nil result options) width options)))
+
+(mu/defn render-adhoc-card-to-png :- bytes?
+ "Render an ad-hoc (unsaved) card to PNG."
+ (^bytes [adhoc-card results width]
+ (render-adhoc-card-to-png adhoc-card results width nil))
+
+ (^bytes [adhoc-card :- ::adhoc-card
+ results :- [:map [:data :map]]
+ width
+ options :- [:maybe ::options]]
+ (let [timezone-id (qp.timezone/system-timezone-id)]
+ (png/render-html-to-png
+ (render-pulse-card :inline timezone-id adhoc-card nil results options)
+ width
+ options))))
(mu/defn render-pulse-card-to-base64 :- string?
"Render a `pulse-card` as a PNG and return it as a base64 encoded string."
diff --git a/src/metabase/channel/render/core.clj b/src/metabase/channel/render/core.clj
index 63178da6209..ddd51977f19 100644
--- a/src/metabase/channel/render/core.clj
+++ b/src/metabase/channel/render/core.clj
@@ -5,6 +5,7 @@
[metabase.channel.render.js.svg :as js.svg]
[metabase.channel.render.preview :as render.preview]
[metabase.channel.render.style :as style]
+ [metabase.channel.render.table-data :as table-data]
[potemkin :as p]))
(p/import-vars
@@ -29,7 +30,12 @@
render-pulse-card-for-display
render-pulse-section
render-pulse-card-to-png
+ render-adhoc-card-to-png
render-pulse-card-to-base64
png-from-render-info]
[js.svg
- icon])
+ icon]
+ [table-data
+ show-in-table?
+ create-remapping-lookup
+ prepare-table-data])
diff --git a/src/metabase/channel/render/png.clj b/src/metabase/channel/render/png.clj
index 888b7a6f7f3..036ca958ddc 100644
--- a/src/metabase/channel/render/png.clj
+++ b/src/metabase/channel/render/png.clj
@@ -123,20 +123,35 @@
(mu/defn render-html-to-png :- bytes?
"Render the Hiccup HTML `content` of a Pulse to a PNG image, returning a byte array."
- ^bytes [{:keys [content]} :- ::body/RenderedPartCard
- width]
- (try
- (let [html (html [:html
- [:body {:style (style/style
- {:font-family "Lato, 'Helvetica Neue', 'Lucida Grande', sans-serif"
- :margin 0
- :padding 0
- :background-color :white})}
- (wrap-non-lato-chars content)]])]
- (with-open [os (ByteArrayOutputStream.)]
- (-> (render-to-png html width)
- (write-image! "png" os))
- (.toByteArray os)))
- (catch Throwable e
- (log/error e "Error rendering Pulse")
- (throw e))))
+ (^bytes [rendered-info :- ::body/RenderedPartCard
+ width]
+ (render-html-to-png rendered-info width nil))
+
+ (^bytes [{:keys [content]} :- ::body/RenderedPartCard
+ width
+ options]
+ (try
+ (let [padding-x (or (:channel.render/padding-x options) 0)
+ padding-y (or (:channel.render/padding-y options) 0)
+ padding-css (str padding-y "px " padding-x "px")
+ ;; Wrap content in a container div with padding to ensure padding is included in content-width
+ ;; calculation (body padding gets cropped off by render-to-png)
+ padded-content (if (or (pos? padding-x) (pos? padding-y))
+ [:div {:style (style/style {:padding padding-css
+ :box-sizing :border-box})}
+ content]
+ content)
+ html (html [:html
+ [:body {:style (style/style
+ {:font-family "Lato, 'Helvetica Neue', 'Lucida Grande', sans-serif"
+ :margin 0
+ :padding 0
+ :background-color :white})}
+ (wrap-non-lato-chars padded-content)]])]
+ (with-open [os (ByteArrayOutputStream.)]
+ (-> (render-to-png html width)
+ (write-image! "png" os))
+ (.toByteArray os)))
+ (catch Throwable e
+ (log/error e "Error rendering Pulse")
+ (throw e)))))
diff --git a/src/metabase/channel/render/table_data.clj b/src/metabase/channel/render/table_data.clj
new file mode 100644
index 00000000000..d13f3d5aecc
--- /dev/null
+++ b/src/metabase/channel/render/table_data.clj
@@ -0,0 +1,49 @@
+(ns metabase.channel.render.table-data
+ "Shared utilities for preparing query results for table rendering.
+ Used by both HTML/PNG table rendering (emails, pulses) and Slack table blocks.")
+
+(set! *warn-on-reflection* true)
+
+(defn show-in-table?
+ "Should this column be shown in a rendered table?
+ Filters out sensitive, retired, and details-only columns."
+ [{:keys [visibility_type] :as _column}]
+ (not (contains? #{:details-only :retired :sensitive} visibility_type)))
+
+(defn create-remapping-lookup
+ "Creates a map from column names to the index of their remapped column.
+ Used to handle FK remapping where columns have :remapped_from metadata."
+ [cols]
+ (into {}
+ (for [[col-idx {:keys [remapped_from]}] (map-indexed vector cols)
+ :when remapped_from]
+ [remapped_from col-idx])))
+
+(defn prepare-table-data
+ "Prepare query results for table rendering.
+ - Filters out columns that shouldn't be shown (sensitive, retired, details-only)
+ - Handles FK remapping: removes duplicate columns and substitutes values
+
+ Returns {:cols [...] :rows [...]} with the prepared data."
+ [cols rows]
+ (let [remapping-lookup (create-remapping-lookup cols)
+ ;; Build list of columns to keep (visible and not remapped_from)
+ ;; and track which source index to read from for each
+ col-info (into []
+ (comp
+ (map-indexed vector)
+ (filter (fn [[_ col]] (show-in-table? col)))
+ (remove (fn [[_ col]] (:remapped_from col)))
+ (map (fn [[idx col]]
+ {:source-idx (or (get remapping-lookup (:name col)) idx)
+ :col (if-let [remapped-idx (get remapping-lookup (:name col))]
+ (nth cols remapped-idx)
+ col)})))
+ cols)
+ output-cols (mapv :col col-info)
+ col-indices (mapv :source-idx col-info)
+ output-rows (mapv (fn [row]
+ (mapv #(nth row % nil) col-indices))
+ rows)]
+ {:cols output-cols
+ :rows output-rows}))
diff --git a/src/metabase/channel/settings.clj b/src/metabase/channel/settings.clj
index c7804fb0764..f05e2dca941 100644
--- a/src/metabase/channel/settings.clj
+++ b/src/metabase/channel/settings.clj
@@ -8,17 +8,6 @@
[metabase.util.malli.schema :as ms]
[metabase.util.string :as u.str]))
-(defsetting slack-token
- (deferred-tru
- (str "Deprecated Slack API token for connecting the Metabase Slack bot. "
- "Please use a new Slack app integration instead."))
- :deprecated "0.42.0"
- :encryption :when-encryption-key-set
- :visibility :settings-manager
- :doc false
- :audit :never
- :export? false)
-
(defsetting slack-app-token
(deferred-tru
(str "Bot user OAuth token for connecting the Metabase Slack app. "
@@ -72,6 +61,18 @@
(when-not (str/blank? channel-name)
(if (str/starts-with? channel-name "#") (subs channel-name 1) channel-name)))
+(defn find-cached-slack-channel-or-username
+ "Look up a Slack channel or username by name or ID in [[slack-cached-channels-and-usernames]].
+
+ Returns the cached entry or `nil` if not found. The input is normalized by stripping a leading `#` before matching."
+ [channel-name]
+ (let [normalized (process-files-channel-name channel-name)]
+ (some (fn [channel]
+ (when (or (= normalized (:name channel))
+ (= normalized (:id channel)))
+ channel))
+ (:channels (slack-cached-channels-and-usernames)))))
+
(defsetting slack-files-channel
(deferred-tru "The name of the channel to which Metabase files should be initially uploaded")
:deprecated "0.54.0"
@@ -323,10 +324,6 @@
"Is Slack integration configured?"
:type :boolean
:visibility :internal
- :getter (fn []
- (boolean
- (or
- (seq (slack-app-token))
- (seq (slack-token)))))
+ :getter (fn [] (boolean (slack-app-token)))
:export? false
:setter :none)
diff --git a/src/metabase/channel/slack.clj b/src/metabase/channel/slack.clj
index 5222394b999..28af439fc54 100644
--- a/src/metabase/channel/slack.clj
+++ b/src/metabase/channel/slack.clj
@@ -61,8 +61,7 @@
(defn- do-slack-request [request-fn endpoint request]
(let [token (or (get-in request [:query-params :token])
(get-in request [:form-params :token])
- (channel.settings/unobfuscated-slack-app-token)
- (channel.settings/slack-token))]
+ (channel.settings/unobfuscated-slack-app-token))]
(when token
(let [url (str "https://slack.com/api/" (name endpoint))
_ (log/tracef "Slack API request: %s %s" (pr-str url) (pr-str request))
@@ -79,7 +78,7 @@
(catch Throwable e
(throw (ex-info (.getMessage e) (merge (ex-data e) {:url url}) e))))))))
-(defn- GET
+(defn GET
"Make a GET request to the Slack API."
[endpoint & {:as query-params}]
(do-slack-request http/get endpoint {:query-params query-params}))
@@ -324,7 +323,7 @@
[:text {:optional true} :string]
[:attachments {:optional true} [:sequential :map]]]]
;; TODO: it would be nice to have an emoji or icon image to use here
- (let [base-params {:username "MetaBot"
+ (let [base-params {:username "Metabot"
:icon_url "http://static.metabase.com/metabot_slack_avatar_whitebg.png"}
message-params (update-vals message-content #(if (string? %) % (json/encode %)))]
;; https://api.slack.com/methods/chat.postMessage
diff --git a/src/metabase/core/core.clj b/src/metabase/core/core.clj
index 3050b0e1ce4..a5ece044260 100644
--- a/src/metabase/core/core.clj
+++ b/src/metabase/core/core.clj
@@ -114,6 +114,7 @@
(let [timeout-seconds 20]
(mdb/release-migration-locks! timeout-seconds))
(perf/stop-monitoring!)
+ (shutdown-agents)
(log/info "Metabase Shutdown COMPLETE"))
(defenterprise ensure-audit-db-installed!
diff --git a/src/metabase/lib/schema/info.cljc b/src/metabase/lib/schema/info.cljc
index edc0949fcdb..fb73ba45876 100644
--- a/src/metabase/lib/schema/info.cljc
+++ b/src/metabase/lib/schema/info.cljc
@@ -37,7 +37,8 @@
:embedded-xlsx-download
:embedded-json-download
:table-grid
- :transform-inspector])
+ :transform-inspector
+ :slackbot])
(mr/def ::hash
#?(:clj bytes?
diff --git a/src/metabase/notification/api.clj b/src/metabase/notification/api.clj
index 7c7662deb10..330adc6786b 100644
--- a/src/metabase/notification/api.clj
+++ b/src/metabase/notification/api.clj
@@ -9,6 +9,7 @@
(p/import-vars
[metabase.notification.api.notification
+ create-notification!
list-notifications
get-notification
unsubscribe-user!])
diff --git a/src/metabase/notification/api/notification.clj b/src/metabase/notification/api/notification.clj
index 8afa6bbcb13..ef8c7f45f51 100644
--- a/src/metabase/notification/api/notification.clj
+++ b/src/metabase/notification/api/notification.clj
@@ -15,6 +15,7 @@
[metabase.notification.core :as notification]
[metabase.notification.models :as models.notification]
[metabase.util :as u]
+ [metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]
[toucan2.core :as t2]
@@ -173,30 +174,31 @@
(messages/send-you-were-added-card-notification-email!
(update notification :payload t2/hydrate :card) recipients-except-creator @api/*current-user*)))))
-;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
-;; use our API + we will need it when we make auto-TypeScript-signature generation happen
-;;
-#_{:clj-kondo/ignore [:metabase/validate-defendpoint-has-response-schema]}
-(api.macros/defendpoint :post "/"
- "Create a new notification, return the created notification."
- [_route _query body :- ::NotificationApiInput request]
- (check-no-resource-templates! (:handlers body))
- (api/create-check :model/Notification body)
+(mu/defn create-notification! :- ::models.notification/FullyHydratedNotification
+ "Create a notification with permission checks, hydration, email notifications, and event publishing."
+ [notification-info :- ::models.notification/FullyHydratedNotification]
+ (api/create-check :model/Notification notification-info)
(let [notification (models.notification/hydrate-notification
(models.notification/create-notification!
- (-> body
- (update :payload_type keyword)
- (assoc :creator_id api/*current-user-id*)
- (dissoc :handlers :subscriptions)
- (assoc-in [:payload :disable_links]
- (embed.util/is-modular-embedding-or-modular-embedding-sdk-request? request)))
- (:subscriptions body)
- (:handlers body)))]
+ (dissoc notification-info :handlers :subscriptions)
+ (:subscriptions notification-info)
+ (:handlers notification-info)))]
(when (card-notification? notification)
(send-you-were-added-card-notification-email! notification))
(events/publish-event! :event/notification-create {:object notification :user-id api/*current-user-id*})
notification))
+(api.macros/defendpoint :post "/" :- ::models.notification/FullyHydratedNotification
+ "Create a new notification, return the created notification."
+ [_route _query body :- ::NotificationApiInput request]
+ (check-no-resource-templates! (:handlers body))
+ (create-notification!
+ (-> body
+ (update :payload_type keyword)
+ (assoc :creator_id api/*current-user-id*)
+ (assoc-in [:payload :disable_links]
+ (embed.util/is-modular-embedding-or-modular-embedding-sdk-request? request)))))
+
(defn- notify-notification-updates!
"Send notification emails based on changes between updated and existing notification"
[updated-notification existing-notification]
diff --git a/src/metabase/permissions/core.clj b/src/metabase/permissions/core.clj
index eb1da1b7d36..a763ebfef7a 100644
--- a/src/metabase/permissions/core.clj
+++ b/src/metabase/permissions/core.clj
@@ -111,6 +111,7 @@
collection-readwrite-path
collection-path?]
[metabase.permissions.user
+ query-creation-capabilities
user-permissions-set
user->tenant-collection-and-descendant-ids]
[metabase.permissions.util
diff --git a/src/metabase/permissions/user.clj b/src/metabase/permissions/user.clj
index f46264e9a43..f8c12275600 100644
--- a/src/metabase/permissions/user.clj
+++ b/src/metabase/permissions/user.clj
@@ -3,9 +3,11 @@
[metabase.app-db.core :as app-db]
[metabase.permissions.models.data-permissions :as data-perms]
[metabase.permissions.path :as permissions.path]
+ [metabase.permissions.published-tables :as published-tables]
[metabase.premium-features.core :refer [defenterprise]]
[metabase.tracing.core :as tracing]
- [metabase.util :as u]))
+ [metabase.util :as u]
+ [toucan2.core :as t2]))
(defenterprise user->tenant-collection-and-descendant-ids
"Returns descendant IDs for the user's tenant collection. Returns an empty vector in OSS since tenants are an EE feature."
@@ -36,7 +38,7 @@
(map permissions.path/collection-readwrite-path ((requiring-resolve 'metabase.collections.models.collection/collections-in-namespace)
:transforms))))
- ;; include the other Perms entries for any Group this User is in (1 DB Call)
+ ;; include the other Perms entries for any Group this User is in (1 DB Call)
(map :object (app-db/query {:select [:p.object]
:from [[:permissions_group_membership :pgm]]
:join [[:permissions_group :pg] [:= :pgm.group_id :pg.id]
@@ -44,3 +46,20 @@
:where [:= :pgm.user_id user-id]})))))]
;; Append permissions as a vector for more efficient iteration in checks that go over each permission linearly.
(with-meta s {:as-vec (vec s)}))))
+
+(defn query-creation-capabilities
+ "Returns a map with `:can-create-queries` and `:can-create-native-queries` for the given user,
+ based on their create-queries permissions across all databases."
+ [user-id]
+ (let [db-ids (t2/select-pks-set :model/Database)
+ _ (data-perms/prime-db-cache db-ids)
+ create-query-perms (into #{}
+ (map #(data-perms/most-permissive-database-permission-for-user
+ user-id :perms/create-queries %))
+ db-ids)]
+ {:can-create-queries (boolean
+ (or (some #(data-perms/at-least-as-permissive?
+ :perms/create-queries % :query-builder)
+ create-query-perms)
+ (published-tables/user-has-any-published-table-permission?)))
+ :can-create-native-queries (contains? create-query-perms :query-builder-and-native)}))
diff --git a/src/metabase/premium_features/token_check.clj b/src/metabase/premium_features/token_check.clj
index 64062e42ea6..7888a1ab279 100644
--- a/src/metabase/premium_features/token_check.clj
+++ b/src/metabase/premium_features/token_check.clj
@@ -190,8 +190,7 @@
:throw-exceptions false
;; socket is data transfer, connection is handshake and create connection timeout
:socket-timeout 5000 ;; in milliseconds
- :connection-timeout 2000 ;; in milliseconds
- })))
+ :connection-timeout 2000}))) ;; in milliseconds
(defn- fetch-token-and-parse-body
[token base-url site-uuid]
diff --git a/src/metabase/pulse/api.clj b/src/metabase/pulse/api.clj
index 685333023af..ce9b37162dc 100644
--- a/src/metabase/pulse/api.clj
+++ b/src/metabase/pulse/api.clj
@@ -9,11 +9,17 @@
[metabase.pulse.api.alert]
^{:clj-kondo/ignore [:deprecated-namespace]}
[metabase.pulse.api.pulse]
- [metabase.pulse.api.unsubscribe]))
+ [metabase.pulse.api.unsubscribe]
+ [potemkin :as p]))
(comment metabase.pulse.api.alert/keep-me
+ metabase.pulse.api.pulse/keep-me
metabase.pulse.api.unsubscribe/keep-me)
+(p/import-vars
+ [metabase.pulse.api.pulse
+ create-pulse-with-perm-checks!])
+
(def ^{:arglists '([request respond raise])} pulse-routes
"`/api/pulse` routes. `/api/pulse/unsubscribe/*` does not require authentication, so you can unsubscribe without being
logged in."
diff --git a/src/metabase/pulse/api/pulse.clj b/src/metabase/pulse/api/pulse.clj
index 7ae33698289..d0019469840 100644
--- a/src/metabase/pulse/api/pulse.clj
+++ b/src/metabase/pulse/api/pulse.clj
@@ -130,6 +130,21 @@
:full :full))) cards))))
(t2/hydrate pulses :can_write))))
+(defn create-pulse-with-perm-checks!
+ "Create a new Pulse with permissions checks."
+ [cards channels pulse-data]
+ (perms/check-has-application-permission :subscription false)
+ (api/create-check :model/Pulse (assoc pulse-data :cards cards))
+ (t2/with-transaction [_conn]
+ ;; Adding a new pulse at `collection_position` could cause other pulses in this collection to change position,
+ ;; check that and fix it if needed
+ (api/maybe-reconcile-collection-position! pulse-data)
+ ;; ok, now create the Pulse
+ (let [pulse (api/check-500
+ (models.pulse/create-pulse! (map models.pulse/card->ref cards) channels pulse-data))]
+ (events/publish-event! :event/pulse-create {:object pulse :user-id api/*current-user-id*})
+ pulse)))
+
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
;; use our API + we will need it when we make auto-TypeScript-signature generation happen
;;
@@ -153,25 +168,17 @@
[:dashboard_id {:optional true} [:maybe ms/PositiveInt]]
[:parameters {:optional true} [:maybe [:sequential :map]]]]
request]
- (perms/check-has-application-permission :subscription false)
- (let [pulse-data {:name name
- :creator_id api/*current-user-id*
- :skip_if_empty skip-if-empty
- :collection_id collection-id
- :collection_position collection-position
- :dashboard_id dashboard-id
- :parameters parameters
- :disable_links (embed.util/is-modular-embedding-or-modular-embedding-sdk-request? request)}]
- (api/create-check :model/Pulse (assoc pulse-data :cards cards))
- (t2/with-transaction [_conn]
- ;; Adding a new pulse at `collection_position` could cause other pulses in this collection to change position,
- ;; check that and fix it if needed
- (api/maybe-reconcile-collection-position! pulse-data)
- ;; ok, now create the Pulse
- (let [pulse (api/check-500
- (models.pulse/create-pulse! (map models.pulse/card->ref cards) channels pulse-data))]
- (events/publish-event! :event/pulse-create {:object pulse :user-id api/*current-user-id*})
- pulse))))
+ (create-pulse-with-perm-checks!
+ cards
+ channels
+ {:name name
+ :creator_id api/*current-user-id*
+ :skip_if_empty skip-if-empty
+ :collection_id collection-id
+ :collection_position collection-position
+ :dashboard_id dashboard-id
+ :parameters parameters
+ :disable_links (embed.util/is-modular-embedding-or-modular-embedding-sdk-request? request)}))
;; TODO (Cam 2025-11-25) please add a response schema to this API endpoint, it makes it easier for our customers to
;; use our API + we will need it when we make auto-TypeScript-signature generation happen
diff --git a/src/metabase/pulse/core.clj b/src/metabase/pulse/core.clj
index a6acbc28fae..6b45f22ab14 100644
--- a/src/metabase/pulse/core.clj
+++ b/src/metabase/pulse/core.clj
@@ -14,7 +14,6 @@
(p/import-vars
[metabase.pulse.models.pulse
card->ref
- create-pulse!
retrieve-alerts-for-cards
update-pulse!]
[metabase.pulse.update-alerts
diff --git a/src/metabase/request/core.clj b/src/metabase/request/core.clj
index 52ee2ec516a..edb0cc22aaf 100644
--- a/src/metabase/request/core.clj
+++ b/src/metabase/request/core.clj
@@ -46,6 +46,7 @@
[metabase.request.util
DeviceInfo
api-call?
+ auth-call?
cacheable?
describe-user-agent
device-info
diff --git a/src/metabase/request/util.clj b/src/metabase/request/util.clj
index 65083615255..23321d8cbbb 100644
--- a/src/metabase/request/util.clj
+++ b/src/metabase/request/util.clj
@@ -25,6 +25,11 @@
[{:keys [^String uri]}]
(str/starts-with? uri "/api"))
+(defn auth-call?
+ "Is this ring request an auth call (does path start with `/auth`)?"
+ [{:keys [^String uri]}]
+ (str/starts-with? uri "/auth"))
+
(defn public?
"Is this ring request one that will serve `public.html`?"
[{:keys [uri]}]
diff --git a/src/metabase/server/handler.clj b/src/metabase/server/handler.clj
index 18b090e4473..55e0691a5ab 100644
--- a/src/metabase/server/handler.clj
+++ b/src/metabase/server/handler.clj
@@ -81,6 +81,7 @@
#'mw.mp-cache/wrap-metadata-provider-cache ; initializes the Lib-BE metadata provider cache
#'wrap-keyword-params ; converts string keys in :params to keyword keys
#'wrap-params ; parses GET and POST params as :query-params/:form-params and both as :params
+ #'mw.auth/verify-slack-request ; looks for requests from slack and assocs a :slack/validated? on the request if valid
#'mw.misc/maybe-set-site-url ; set the value of `site-url` if it hasn't been set yet
#'mw.session/reset-session-timeout ; Resets the timeout cookie for user activity to [[metabase.request.cookies/session-timeout]]
#'mw.session/bind-current-user ; Binds *current-user* and *current-user-id* if :metabase-user-id is non-nil
diff --git a/src/metabase/server/middleware/auth.clj b/src/metabase/server/middleware/auth.clj
index bb1e4828edd..e5802fb051d 100644
--- a/src/metabase/server/middleware/auth.clj
+++ b/src/metabase/server/middleware/auth.clj
@@ -1,6 +1,43 @@
(ns metabase.server.middleware.auth
"Middleware related to enforcing authentication/API keys (when applicable). Unlike most other middleware most of this
- is not used as part of the normal `app`; it is instead added selectively to appropriate routes.")
+ is not used as part of the normal `app`; it is instead added selectively to appropriate routes."
+ (:require
+ [buddy.core.bytes :as bytes]
+ [buddy.core.codecs :as codecs]
+ [buddy.core.mac :as mac]
+ [metabase.premium-features.core :refer [defenterprise]]))
+
+(set! *warn-on-reflection* true)
+
+(defenterprise metabot-slack-signing-secret-setting
+ "Returns the Slack signing secret for Metabot (EE only)."
+ metabase-enterprise.slackbot.settings
+ []
+ nil)
+
+(def ^:private ^:const max-slack-timestamp-age-seconds
+ "Maximum age in seconds for a Slack request timestamp. Requests older than this are rejected
+ to prevent replay attacks. Slack recommends 5 minutes (300 seconds)."
+ 300)
+
+(defn- current-unix-timestamp
+ "Returns current Unix timestamp in seconds. Extracted for testability."
+ []
+ (quot (System/currentTimeMillis) 1000))
+
+(defn- slack-timestamp-valid?
+ "Check if the Slack request timestamp is within the acceptable time window.
+ Returns false if timestamp is missing, malformed, or too old."
+ [timestamp]
+ (if timestamp
+ (try
+ (let [request-time (Long/parseLong timestamp)
+ current-time (current-unix-timestamp)
+ age (Math/abs (long (- current-time request-time)))]
+ (<= age max-slack-timestamp-age-seconds))
+ (catch NumberFormatException _
+ false))
+ false))
(def ^:private ^:const ^String static-metabase-api-key-header "x-metabase-apikey")
@@ -15,3 +52,41 @@
[handler]
(fn [request respond raise]
(handler (wrap-static-api-key* request) respond raise)))
+
+(defn- hmac-sha256
+ "Generate HMAC-SHA256 signature"
+ [key message]
+ (-> (mac/hash message {:key key :alg :hmac+sha256})
+ codecs/bytes->hex))
+
+(defn- verify-slack-signature
+ "Verify that the request came from Slack using signature verification.
+ Returns nil if no signing secret is configured, false if timestamp is too old
+ (replay attack prevention) or signature is invalid, true if valid."
+ [request-body timestamp slack-signature]
+ (when-let [signing-secret (metabot-slack-signing-secret-setting)]
+ (and (slack-timestamp-valid? timestamp)
+ (some? slack-signature)
+ (let [message (str "v0:" timestamp ":" request-body)
+ computed-signature (hmac-sha256 signing-secret message)
+ expected-signature (str "v0=" computed-signature)]
+ ;; Use constant-time comparison to prevent timing attacks
+ (bytes/equals? (.getBytes ^String expected-signature "UTF-8")
+ (.getBytes ^String slack-signature "UTF-8"))))))
+
+(defn verify-slack-request
+ "Middleware that detects if an incoming request is from Slack and sets the `:slack/validated?` keyword on a request
+ with a boolean if that request has been correctly signed with our signing secret."
+ [handler]
+ (fn
+ [req respond raise]
+ (let [signature (get-in req [:headers "x-slack-signature"])]
+ (if signature
+ (let [timestamp (get-in req [:headers "x-slack-request-timestamp"])
+ str-body (slurp (:body req))
+ valid? (verify-slack-signature str-body timestamp signature)]
+ (handler (-> req
+ (assoc :body (java.io.ByteArrayInputStream. (.getBytes ^String str-body "UTF-8")))
+ (assoc :slack/validated? valid?))
+ respond raise))
+ (handler req respond raise)))))
diff --git a/src/metabase/server/middleware/misc.clj b/src/metabase/server/middleware/misc.clj
index 947834c158d..7900b105ca9 100644
--- a/src/metabase/server/middleware/misc.clj
+++ b/src/metabase/server/middleware/misc.clj
@@ -45,7 +45,7 @@
[handler]
(fn [request respond raise]
(handler request
- (if-not (request/api-call? request)
+ (if-not (or (request/api-call? request) (request/auth-call? request))
respond
(comp respond add-content-type*))
raise)))
diff --git a/src/metabase/system/settings.clj b/src/metabase/system/settings.clj
index ff269fe7096..8e848c4de39 100644
--- a/src/metabase/system/settings.clj
+++ b/src/metabase/system/settings.clj
@@ -5,6 +5,7 @@
[metabase.appearance.core :as appearance]
[metabase.settings.core :as setting :refer [defsetting]]
[metabase.util :as u]
+ [metabase.util.encryption :as encryption]
[metabase.util.fonts :as u.fonts]
[metabase.util.i18n :as i18n :refer [available-locales-with-names deferred-tru tru]]
[metabase.util.log :as log]))
@@ -125,3 +126,12 @@
:setter :none
:getter (comp str t/zone-id)
:doc false)
+
+(defsetting encryption-enabled
+ "Whether encryption is enabled for this Metabase instance via MB_ENCRYPTION_SECRET_KEY."
+ :visibility :admin
+ :type :boolean
+ :export? false
+ :setter :none
+ :getter encryption/default-encryption-enabled?
+ :doc false)
diff --git a/src/metabase/upload/core.clj b/src/metabase/upload/core.clj
index 250f69cc8db..586c441ba40 100644
--- a/src/metabase/upload/core.clj
+++ b/src/metabase/upload/core.clj
@@ -13,6 +13,7 @@
current-database]
[metabase.upload.impl
can-create-upload?
+ create-csv-upload!
delete-upload!
model-hydrate-based-on-upload
update-action-schema
diff --git a/src/metabase/users_rest/api.clj b/src/metabase/users_rest/api.clj
index e37a4ee07e2..73c513ab143 100644
--- a/src/metabase/users_rest/api.clj
+++ b/src/metabase/users_rest/api.clj
@@ -295,21 +295,11 @@
"Add `:can_create_queries` and `:can_create_native_queries` flags to user based on their create-queries
permissions across non-sample databases."
[user]
- (let [db-ids (t2/select-pks-set :model/Database)
- _ (perms/prime-db-cache db-ids)
- create-query-perms (into #{}
- (map (fn [db-id]
- (perms/most-permissive-database-permission-for-user
- api/*current-user-id* :perms/create-queries db-id)))
- db-ids)
- can-create-queries? (or (some #(perms/at-least-as-permissive?
- :perms/create-queries % :query-builder)
- create-query-perms)
- (perms/user-has-any-published-table-permission?))
- can-create-native? (contains? create-query-perms :query-builder-and-native)]
+ (let [{:keys [can-create-queries can-create-native-queries]}
+ (perms/query-creation-capabilities (:id user))]
(update user :permissions assoc
- :can_create_queries (boolean can-create-queries?)
- :can_create_native_queries can-create-native?)))
+ :can_create_queries can-create-queries
+ :can_create_native_queries can-create-native-queries)))
(defn- maybe-add-advanced-permissions
"If `advanced-permissions` is enabled, add to `user` a permissions map."
diff --git a/test/metabase/channel/api/slack_test.clj b/test/metabase/channel/api/slack_test.clj
index 473e451798e..fdf3974b471 100644
--- a/test/metabase/channel/api/slack_test.clj
+++ b/test/metabase/channel/api/slack_test.clj
@@ -12,17 +12,14 @@
(deftest update-slack-settings-test
(testing "PUT /api/slack/settings"
- (testing "An admin can set a valid Slack app token to the slack-app-token setting, and any value in the
- `slack-token` setting is cleared"
+ (testing "An admin can set a valid Slack app token to the slack-app-token setting"
(with-redefs [slack/valid-token? (constantly true)
slack/channel-exists? (constantly true)
slack/refresh-channels-and-usernames! (constantly nil)
slack/refresh-channels-and-usernames-when-needed! (constantly nil)]
- (mt/with-temporary-setting-values [slack-app-token nil
- slack-token "fake-token"]
+ (mt/with-temporary-setting-values [slack-app-token nil]
(mt/user-http-request :crowberto :put 200 "slack/settings" {:slack-app-token "fake-token"})
- (is (= "fake-token" (channel.settings/unobfuscated-slack-app-token)))
- (is (= nil (channel.settings/slack-token))))))))
+ (is (= "fake-token" (channel.settings/unobfuscated-slack-app-token))))))))
(deftest update-slack-settings-test-2
(testing "PUT /api/slack/settings"
@@ -42,17 +39,18 @@
(deftest update-slack-settings-test-3
(testing "PUT /api/slack/settings"
- (testing "The Slack app token and channel settings are cleared if no value is sent in the request"
+ (testing "An empty request body is a no-op and does not modify existing settings"
(mt/with-temporary-setting-values [slack-app-token "fake-token"
- channel.settings/slack-cached-channels-and-usernames ["fake_channel"]
+ channel.settings/slack-cached-channels-and-usernames {:channels [{:name "fake_channel"}]}
channel.settings/slack-channels-and-usernames-last-updated (t/zoned-date-time)]
- (mt/user-http-request :crowberto :put 200 "slack/settings" {})
- (is (= nil (channel.settings/slack-app-token)))
- ;; The cache is empty, and its last-updated value is reset to its default value
- (is (= {:channels []}
- (channel.settings/slack-cached-channels-and-usernames)))
- (is (= channel.settings/zoned-time-epoch
- (channel.settings/slack-channels-and-usernames-last-updated)))))))
+ (let [original-last-updated (channel.settings/slack-channels-and-usernames-last-updated)]
+ (mt/user-http-request :crowberto :put 200 "slack/settings" {})
+ ;; Settings remain unchanged
+ (is (= "fake-token" (channel.settings/unobfuscated-slack-app-token)))
+ (is (= {:channels [{:name "fake_channel"}]}
+ (channel.settings/slack-cached-channels-and-usernames)))
+ (is (= original-last-updated
+ (channel.settings/slack-channels-and-usernames-last-updated))))))))
(deftest update-slack-settings-test-4
(testing "PUT /api/slack/settings"
@@ -63,15 +61,38 @@
(deftest ^:parallel manifest-test
(testing "GET /api/slack/manifest"
(testing "The Slack manifest can be fetched via an API call"
- (is (str/starts-with?
- (mt/user-http-request :crowberto :get 200 "slack/manifest")
- "_metadata:\n")))))
+ (is (map? (mt/user-http-request :crowberto :get 200 "slack/manifest"))))))
(deftest ^:parallel manifest-test-2
(testing "GET /api/slack/manifest"
(testing "A non-admin cannot fetch the Slack manifest"
(mt/user-http-request :rasta :get 403 "slack/manifest"))))
+(deftest app-info-test
+ (testing "GET /api/slack/app-info"
+ (testing "Returns app_id and team_id when Slack is configured"
+ (with-redefs [api.slack/app-info (constantly {:app_id "A12345"
+ :team_id "T67890"
+ :scopes {:actual ["chat:write"]
+ :required ["chat:write"]
+ :missing []
+ :extra []}})]
+ (mt/with-temporary-setting-values [slack-app-token "fake-token"]
+ (let [response (mt/user-http-request :crowberto :get 200 "slack/app-info")]
+ (is (= {:app_id "A12345"
+ :team_id "T67890"
+ :scopes {:actual ["chat:write"]
+ :required ["chat:write"]
+ :missing []
+ :extra []}}
+ response))))))
+ (testing "A non-admin cannot fetch the Slack app info"
+ (mt/user-http-request :rasta :get 403 "slack/app-info"))
+ (testing "Returns nil values when Slack is not configured"
+ (mt/with-temporary-setting-values [slack-app-token nil]
+ (let [response (mt/user-http-request :crowberto :get 200 "slack/app-info")]
+ (is (= {:app_id nil :team_id nil :scopes nil} response)))))))
+
(deftest bug-report-test
(testing "POST /api/slack/bug-report"
(let [diagnostic-info {:url "https://test.com"
diff --git a/test/metabase/channel/settings_test.clj b/test/metabase/channel/settings_test.clj
index 05b89437a9a..76baa0da408 100644
--- a/test/metabase/channel/settings_test.clj
+++ b/test/metabase/channel/settings_test.clj
@@ -81,3 +81,20 @@
(mt/with-temporary-setting-values [smtp-override-enabled nil
email-smtp-host-override "localhost"]
(is (= "true" (channel.settings/smtp-override-enabled! true)))))))
+
+(deftest find-cached-slack-channel-or-username-test
+ (let [channels [{:display-name "#general" :name "general" :id "C001"}
+ {:display-name "#data-team" :name "data-team" :id "C002"}
+ {:display-name "@alice" :name "alice" :id "U001"}]]
+ (with-redefs [channel.settings/slack-cached-channels-and-usernames (constantly {:channels channels})]
+ (testing "finds by name"
+ (is (= {:display-name "#general" :name "general" :id "C001"}
+ (channel.settings/find-cached-slack-channel-or-username "general"))))
+ (testing "finds by name with # prefix"
+ (is (= {:display-name "#data-team" :name "data-team" :id "C002"}
+ (channel.settings/find-cached-slack-channel-or-username "#data-team"))))
+ (testing "finds by ID"
+ (is (= {:display-name "@alice" :name "alice" :id "U001"}
+ (channel.settings/find-cached-slack-channel-or-username "U001"))))
+ (testing "returns nil when not found"
+ (is (nil? (channel.settings/find-cached-slack-channel-or-username "no-such-channel")))))))
diff --git a/test/metabase/channel/slack_test.clj b/test/metabase/channel/slack_test.clj
index cbeef8a9f8f..a5e0cee0e94 100644
--- a/test/metabase/channel/slack_test.clj
+++ b/test/metabase/channel/slack_test.clj
@@ -54,8 +54,7 @@
(http-fake/with-fake-routes {endpoint (fn [_]
(throw (Exception. "Failure, route should not have been invoked")))}
(testing "should return nil if no Slack token has been configured"
- (mt/with-temporary-setting-values [slack-app-token nil
- slack-token nil]
+ (mt/with-temporary-setting-values [slack-app-token nil]
(is (= nil
(not-empty (thunk))))))))
@@ -95,8 +94,7 @@
(fn [req]
(reset! request req)
(mock-200-response (mock-conversations-response-body req)))}
- (mt/with-temporary-setting-values [slack-token "test-token"
- slack-app-token nil]
+ (mt/with-temporary-setting-values [slack-app-token "test-token"]
(slack/conversations-list opts)))
(let [{:keys [query-string]} @request
{:keys [types]} (parse-query-string query-string)]
@@ -109,21 +107,15 @@
(http-fake/with-fake-routes {conversations-endpoint (comp mock-200-response mock-conversations-response-body)}
(let [expected-result (map slack/channel-transform
(concat (mock-conversations) (mock-conversations)))]
- (mt/with-temporary-setting-values [slack-token "test-token"
- slack-app-token nil]
- (is (= expected-result
- (slack/conversations-list))))
- (mt/with-temporary-setting-values [slack-app-token "test-token"
- slack-token nil]
+ (mt/with-temporary-setting-values [slack-app-token "test-token"]
(is (= expected-result
(slack/conversations-list)))))))))
(deftest valid-token?-test
(testing "valid-token?"
- ;; should ignore the values of `slack-token` and `slack-app-token` settings
+ ;; should ignore the value of `slack-app-token` setting
(doseq [setting-value ["test-token" nil]]
- (mt/with-temporary-setting-values [slack-token setting-value
- slack-app-token setting-value]
+ (mt/with-temporary-setting-values [slack-app-token setting-value]
(http-fake/with-fake-routes {conversations-endpoint (fn [{:keys [headers], :as request}]
(is (= "Bearer\nabc"
(get headers "Authorization")))
@@ -161,14 +153,9 @@
(http-fake/with-fake-routes {users-endpoint (comp mock-200-response mock-users-response-body)}
(let [expected-result (map slack/user-transform
(concat (mock-users) (mock-users)))]
- (mt/with-temporary-setting-values [slack-token nil
- slack-app-token "test-token"]
+ (mt/with-temporary-setting-values [slack-app-token "test-token"]
(is (= expected-result
- (slack/users-list)))
- (mt/with-temporary-setting-values [slack-app-token nil
- slack-token "test-token"]
- (is (= expected-result
- (slack/users-list))))))))))
+ (slack/users-list)))))))))
(deftest upload-file!-test
(testing "upload-file!"
@@ -185,19 +172,12 @@
#"^https://slack.com/api/files\.completeUploadExternal.*"
(fn [_] (mock-200-response (slurp "./test_resources/slack_upload_file_response.json")))}]
- (http-fake/with-fake-routes fake-upload-routes
- (mt/with-temporary-setting-values [slack-token "test-token"
- slack-app-token nil]
- (is (= {:url "https://files.slack.com/files-pri/DDDDDDDDD-EEEEEEEEE/wow.gif"
- :id "DDDDDDDDD-EEEEEEEEE"}
- (slack/upload-file! image-bytes filename)))))
;; Slack app token requires joining the `metabase_files` channel before uploading a file
(http-fake/with-fake-routes
(assoc fake-upload-routes
#"^https://slack.com/api/conversations\.join.*"
(fn [_] (mock-200-response (slurp "./test_resources/slack_conversations_join_response.json"))))
- (mt/with-temporary-setting-values [slack-token nil
- slack-app-token "test-token"]
+ (mt/with-temporary-setting-values [slack-app-token "test-token"]
(is (= {:url "https://files.slack.com/files-pri/DDDDDDDDD-EEEEEEEEE/wow.gif"
:id "DDDDDDDDD-EEEEEEEEE"}
(slack/upload-file! image-bytes filename))))))))
@@ -210,8 +190,7 @@
:message {:type "message"
:subtype "bot_message"
:text ":wow:"}}]
- (mt/with-temporary-setting-values [slack-token "test-token"
- slack-app-token nil]
+ (mt/with-temporary-setting-values [slack-app-token "test-token"]
(is (=? expected
(slack/post-chat-message! {:channel "C94712B6X" :text ":wow:"}))))))))
@@ -260,8 +239,7 @@
(testing "Chooses correct value for :private-channels if groups:read scope is available"
(are [oauth-scopes conversation-types]
(let [request (atom nil)]
- (mt/with-temporary-setting-values [slack-app-token "test"
- slack-token nil]
+ (mt/with-temporary-setting-values [slack-app-token "test"]
(http-fake/with-fake-routes
{auth-endpoint
(constantly
diff --git a/test/metabase/notification/payload/impl/system_event_test.clj b/test/metabase/notification/payload/impl/system_event_test.clj
index 16208c8d680..086e4535ffb 100644
--- a/test/metabase/notification/payload/impl/system_event_test.clj
+++ b/test/metabase/notification/payload/impl/system_event_test.clj
@@ -261,7 +261,7 @@
admin-emails (t2/select-fn-set :email :model/User :is_superuser true)]
(testing "send to admins with a link to setting page"
(check admin-emails [#"Your Slack connection stopped working"
- #"<a[^>]*href=\"https?://metabase\.com/admin/settings/notifications\"[^>]*>Go to settings</a>"]))
+ #"<a[^>]*href=\"https?://metabase\.com/admin/settings/slack\"[^>]*>Go to settings</a>"]))
(mt/with-temporary-setting-values
[admin-email "[email protected]"]
diff --git a/test/metabase/permissions/user_test.clj b/test/metabase/permissions/user_test.clj
index 1c934a01598..2bfc645d5e1 100644
--- a/test/metabase/permissions/user_test.clj
+++ b/test/metabase/permissions/user_test.clj
@@ -6,6 +6,7 @@
[metabase.collections.models.collection :as collection]
[metabase.collections.models.collection-test :as collection-test]
[metabase.permissions.models.data-permissions :as data-perms]
+ [metabase.permissions.models.permissions-group :as perms-group]
[metabase.permissions.models.permissions-test :as perms-test]
[metabase.permissions.path :as permissions.path]
[metabase.permissions.user :as permissions.user]
@@ -64,3 +65,28 @@
(with-redefs [data-perms/is-data-analyst? (constantly true)]
(is (contains? (permissions.user/user-permissions-set (mt/user->id :lucky)) "/collection/namespace/transforms/root/"))
(is (contains? (permissions.user/user-permissions-set (mt/user->id :lucky)) (permissions.path/collection-readwrite-path coll-id))))))))
+
+(deftest query-creation-capabilities-test
+ (testing "query-creation-capabilities returns correct permissions based on user's create-queries perms"
+ (let [all-users-group-id (:id (perms-group/all-users))]
+ (mt/with-temp [:model/Database {db-id :id} {}]
+ (testing "user with no permissions"
+ (mt/with-no-data-perms-for-all-users!
+ (mt/with-current-user (mt/user->id :rasta)
+ (is (= {:can-create-queries false
+ :can-create-native-queries false}
+ (permissions.user/query-creation-capabilities (mt/user->id :rasta)))))))
+ (testing "user with query-builder permissions"
+ (mt/with-no-data-perms-for-all-users!
+ (data-perms/set-database-permission! all-users-group-id db-id :perms/create-queries :query-builder)
+ (mt/with-current-user (mt/user->id :rasta)
+ (is (= {:can-create-queries true
+ :can-create-native-queries false}
+ (permissions.user/query-creation-capabilities (mt/user->id :rasta)))))))
+ (testing "user with query-builder-and-native permissions"
+ (mt/with-no-data-perms-for-all-users!
+ (data-perms/set-database-permission! all-users-group-id db-id :perms/create-queries :query-builder-and-native)
+ (mt/with-current-user (mt/user->id :rasta)
+ (is (= {:can-create-queries true
+ :can-create-native-queries true}
+ (permissions.user/query-creation-capabilities (mt/user->id :rasta)))))))))))
diff --git a/test/metabase/pulse/api/pulse_test.clj b/test/metabase/pulse/api/pulse_test.clj
index 7a928f23fff..531262cd49e 100644
--- a/test/metabase/pulse/api/pulse_test.clj
+++ b/test/metabase/pulse/api/pulse_test.clj
@@ -1297,8 +1297,7 @@
(get-in [:channels :slack :fields]))))))
(testing "When slack is not configured, `form_input` returns no channels"
- (mt/with-temporary-setting-values [slack-token nil
- slack-app-token nil]
+ (mt/with-temporary-setting-values [channel.settings/slack-app-token nil]
(is (empty?
(-> (mt/user-http-request :rasta :get 200 "pulse/form_input")
(get-in [:channels :slack :fields])
diff --git a/test/metabase/server/middleware/misc_test.clj b/test/metabase/server/middleware/misc_test.clj
index 7d60ec68aec..c60be659e4e 100644
--- a/test/metabase/server/middleware/misc_test.clj
+++ b/test/metabase/server/middleware/misc_test.clj
@@ -72,3 +72,54 @@
(is (nil?
(get-in @captured [:headers "x-metabase-version"]))
"header should not be set for non-API calls")))))))
+
+(defn- call-add-content-type
+ "Helper: wrap `response` with `add-content-type` middleware, send `request`, return the response."
+ [request response]
+ (let [handler (mw.misc/add-content-type (fn [_ respond _] (respond response)))
+ captured (atom nil)]
+ (handler request
+ (fn [resp] (reset! captured resp))
+ (fn [_] (is false "should not go to raise")))
+ @captured))
+
+(deftest ^:parallel add-content-type-api-string-body-test
+ (testing "API request with string body gets text/plain"
+ (is (= "text/plain"
+ (get-in (call-add-content-type (ring.mock/request :get "/api/foo")
+ {:status 200 :headers {} :body "ok"})
+ [:headers "Content-Type"])))))
+
+(deftest ^:parallel add-content-type-api-collection-body-test
+ (testing "API request with collection body gets application/json"
+ (is (= "application/json; charset=utf-8"
+ (get-in (call-add-content-type (ring.mock/request :get "/api/foo")
+ {:status 200 :headers {} :body {:a 1}})
+ [:headers "Content-Type"])))))
+
+(deftest ^:parallel add-content-type-auth-string-body-test
+ (testing "auth request with string body gets text/plain"
+ (is (= "text/plain"
+ (get-in (call-add-content-type (ring.mock/request :get "/auth/sso")
+ {:status 200 :headers {} :body "ok"})
+ [:headers "Content-Type"])))))
+
+(deftest ^:parallel add-content-type-auth-collection-body-test
+ (testing "auth request with collection body gets application/json"
+ (is (= "application/json; charset=utf-8"
+ (get-in (call-add-content-type (ring.mock/request :get "/auth/sso")
+ {:status 200 :headers {} :body {:a 1}})
+ [:headers "Content-Type"])))))
+
+(deftest ^:parallel add-content-type-preserves-existing-header-test
+ (testing "auth request with existing Content-Type is preserved"
+ (is (= "text/html"
+ (get-in (call-add-content-type (ring.mock/request :get "/auth/sso")
+ {:status 200 :headers {"Content-Type" "text/html"} :body "ok"})
+ [:headers "Content-Type"])))))
+
+(deftest ^:parallel add-content-type-skips-non-api-non-auth-test
+ (testing "non-API, non-auth request does not get Content-Type"
+ (is (nil? (get-in (call-add-content-type (ring.mock/request :get "/app/foo")
+ {:status 200 :headers {} :body "ok"})
+ [:headers "Content-Type"])))))
diff --git a/test/metabase/test/util.clj b/test/metabase/test/util.clj
index 00e67d40b32..e1fafd264b2 100644
--- a/test/metabase/test/util.clj
+++ b/test/metabase/test/util.clj
@@ -524,9 +524,12 @@
(defn- upsert-raw-setting!
[original-value setting-k value]
- (if original-value
- (t2/update! :model/Setting setting-k {:value value})
- (t2/insert! :model/Setting :key setting-k :value value))
+ (if (some? value)
+ (if original-value
+ (t2/update! :model/Setting setting-k {:value value})
+ (t2/insert! :model/Setting :key setting-k :value value))
+ (when original-value
+ (t2/delete! :model/Setting :key setting-k)))
(setting.cache/restore-cache!))
(defn- restore-raw-setting!
diff --git a/test_resources/serialization_baseline/collections/metabots/slackbotmetabotmetabo.yaml b/test_resources/serialization_baseline/collections/metabots/slackbotmetabotmetabo.yaml
new file mode 100644
index 00000000000..6ed0b41fed4
--- /dev/null
+++ b/test_resources/serialization_baseline/collections/metabots/slackbotmetabotmetabo.yaml
@@ -0,0 +1,11 @@
+name: Slack Metabot
+description: Metabot instance for Slack users.
+created_at: '2025-05-28T17:49:20.649159Z'
+entity_id: slackbotmetabotmetabo
+updated_at: '2025-05-28T17:49:20.649159Z'
+serdes/meta:
+- id: slackbotmetabotmetabo
+ model: Metabot
+collection_id: null
+prompts: []
+use_verified_content: false