Skip to content

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

Carry a Metabot turn's finish reason through reload, fork, Slack and structured output (#82584)

Paolo Rascunà33dd5ca781d9
diff --git a/enterprise/backend/test/metabase_enterprise/metabot_analytics/api_test.clj b/enterprise/backend/test/metabase_enterprise/metabot_analytics/api_test.clj
index f76b4b33639..c6d26af5ca1 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot_analytics/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot_analytics/api_test.clj
@@ -22,7 +22,7 @@
(defn- insert-message!
[{:keys [conversation-id created-at role profile-id total-tokens data data-version
- deleted-at external-id finished]
+ deleted-at external-id finished finish-reason context-window-full]
:as options
:or {data-version 2}}]
(first (t2/insert-returning-pks!
@@ -34,8 +34,10 @@
:data data
:data_version data-version
:external_id (or external-id (str (random-uuid)))}
- created-at (assoc :created_at created-at)
- deleted-at (assoc :deleted_at deleted-at)
+ created-at (assoc :created_at created-at)
+ deleted-at (assoc :deleted_at deleted-at)
+ finish-reason (assoc :finish_reason finish-reason)
+ context-window-full (assoc :context_window_full context-window-full)
(contains? options :finished) (assoc :finished finished)))))
(defn- insert-usage!
@@ -603,6 +605,27 @@
(is (= [] (:parts (second messages))))
(is (= 2 message_count)))))))
+(deftest get-conversation-detail-incomplete-status-test
+ (testing "a reply the provider cut off surfaces as an incomplete message"
+ (with-detail-conversation!
+ (fn [{:keys [insert! day fetch]}]
+ (insert! {:created-at (day 1) :role "user" :profile-id "p" :total-tokens 3
+ :data [{:type "text" :text "a long question"}]})
+ (insert! {:created-at (day 2) :role "assistant" :profile-id "internal" :total-tokens 9 :finished true
+ :finish-reason "length" :data [{:type "text" :text "cut o"}]})
+ (insert! {:created-at (day 3) :role "user" :profile-id "p" :total-tokens 3
+ :data [{:type "text" :text "go on"}]})
+ (insert! {:created-at (day 4) :role "assistant" :profile-id "internal" :total-tokens 9 :finished true
+ :finish-reason "length" :context-window-full true
+ :data [{:type "text" :text "cut again"}]})
+ (let [messages (:messages (fetch))]
+ (testing "a row with no full-window verdict is a plain length stop"
+ (is (= {:type "incomplete" :finishReason "length"}
+ (:status (message-by-text messages "cut o")))))
+ (testing "a row saved as full reads as full here too, the same as on chat reload"
+ (is (= {:type "incomplete" :finishReason "length" :contextWindowFull true}
+ (:status (message-by-text messages "cut again"))))))))))
+
(deftest get-conversation-detail-feedback-on-discarded-attempt-test
(testing "feedback on a regenerated-away attempt still resolves to that attempt's message"
(with-detail-conversation!
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.unit.spec.tsx
index 0c85c5d9655..2ea61225ace 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.unit.spec.tsx
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.unit.spec.tsx
@@ -562,6 +562,12 @@ describe("useMetabot", () => {
reason: "max-length",
continuable: true,
},
+ {
+ finishReason: "tool-calls",
+ messageMetadata: fullContextWindow,
+ reason: "step-limit",
+ continuable: false,
+ },
{
finishReason: "length",
messageMetadata: fullContextWindow,
diff --git a/frontend/src/metabase/metabot/hooks/use-metabot-conversation.ts b/frontend/src/metabase/metabot/hooks/use-metabot-conversation.ts
index ae176ef4665..51cd640cbab 100644
--- a/frontend/src/metabase/metabot/hooks/use-metabot-conversation.ts
+++ b/frontend/src/metabase/metabot/hooks/use-metabot-conversation.ts
@@ -145,12 +145,20 @@ export const useMetabotConversation = (conversationId: string) => {
getIncompleteTurn(state, conversationId),
);
+ const longChatNotice = useSelector((state) =>
+ getLongChatNotice(state, conversationId),
+ );
+ const isContextWindowFull = longChatNotice === "full";
+
const continueResponse = useMemo(() => {
const resumePrompt = incompleteTurn?.resumePrompt;
- return resumePrompt
+ // A full window is judged against the current model, so a turn that could
+ // be resumed when it ran may not fit anymore; the composer hides for the
+ // same reason.
+ return resumePrompt && !isContextWindowFull
? (options?: SubmitInputOptions) => submitInput(resumePrompt, options)
: undefined;
- }, [incompleteTurn, submitInput]);
+ }, [incompleteTurn, isContextWindowFull, submitInput]);
const cancelRequest = useCallback(() => {
dispatch(cancelInflightConversationRequests(conversationId));
@@ -160,10 +168,6 @@ export const useMetabotConversation = (conversationId: string) => {
dispatch(fetchConversationSnapshot(conversationId));
}, [dispatch, conversationId]);
- const longChatNotice = useSelector((state) =>
- getLongChatNotice(state, conversationId),
- );
-
return {
conversationId,
prompt,
@@ -187,7 +191,7 @@ export const useMetabotConversation = (conversationId: string) => {
),
longChatNotice,
incompleteTurn,
- isContextWindowFull: longChatNotice === "full",
+ isContextWindowFull,
contextWindowPercentUsage: useSelector((state) =>
getContextUsagePercent(state, conversationId),
),
diff --git a/frontend/src/metabase/metabot/tests/message.unit.spec.tsx b/frontend/src/metabase/metabot/tests/message.unit.spec.tsx
index efc2ba119db..f796bfe7cb0 100644
--- a/frontend/src/metabase/metabot/tests/message.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/tests/message.unit.spec.tsx
@@ -112,12 +112,13 @@ describe("metabot > message", () => {
const incompleteResponse = (
finishReason: "length" | "tool-calls",
+ messageMetadata?: { contextTokens: number; contextWindowTokens: number },
): SSEEvent[] => [
{ type: "start", messageId: "msg_incomplete" },
{ type: "text-start", id: "t1" },
{ type: "text-delta", id: "t1", delta: "Here is the start of a long answer" },
{ type: "text-end", id: "t1" },
- { type: "finish", finishReason },
+ { type: "finish", finishReason, messageMetadata },
];
describe("metabot > finish reason", () => {
@@ -188,6 +189,26 @@ describe("metabot > finish reason", () => {
});
});
+ it("should not offer continue when the step limit left the context window full", async () => {
+ setup();
+ mockAgentEndpoint({
+ events: incompleteResponse("tool-calls", {
+ contextTokens: 11000,
+ contextWindowTokens: 11000,
+ }),
+ });
+
+ await enterChatMessage("Tell me everything");
+
+ await assertConversation([
+ ["user", "Tell me everything"],
+ ["agent", "Here is the start of a long answer"],
+ ["agent", /paused after reaching its step limit/],
+ ]);
+ expect(screen.queryByTestId("metabot-chat-input")).not.toBeInTheDocument();
+ expect(queryContinueResponseButton()).not.toBeInTheDocument();
+ });
+
describe("content-filter", () => {
it("should explain a content-filtered response", async () => {
setup();
diff --git a/resources/migrations/065/20261008_metabot_message_finish_reason.yaml b/resources/migrations/065/20261008_metabot_message_finish_reason.yaml
new file mode 100644
index 00000000000..e01f32f13f2
--- /dev/null
+++ b/resources/migrations/065/20261008_metabot_message_finish_reason.yaml
@@ -0,0 +1,46 @@
+# Record why a Metabot turn stopped early, so that a truncated, content-filtered or step-limited turn
+# reloads as incomplete instead of as a normal completed turn. `finished` is untouched and keeps its
+# meaning: NULL while in flight, true once completed, false if the client aborted.
+#
+# The second changeset records, once at save time, whether a turn that stopped at `length` had filled
+# the context window of the model that ran it. Reload, fork and analytics read that verdict back, so a
+# later change of the configured model does not change how an old turn reads.
+
+databaseChangeLog:
+ - changeSet:
+ id: v65.2026-10-08T00:00:00
+ author: prascuna
+ comment: Add finish_reason to metabot_message
+ changes:
+ - addColumn:
+ tableName: metabot_message
+ columns:
+ - column:
+ name: finish_reason
+ remarks: "Why a turn stopped early: length, content-filter or tool-calls. NULL when it ran to a normal stop."
+ type: varchar(254)
+ constraints:
+ nullable: true
+ rollback:
+ - dropColumn:
+ tableName: metabot_message
+ columnName: finish_reason
+
+ - changeSet:
+ id: v65.2026-10-08T00:00:01
+ author: prascuna
+ comment: Add context_window_full to metabot_message
+ changes:
+ - addColumn:
+ tableName: metabot_message
+ columns:
+ - column:
+ name: context_window_full
+ remarks: "True when the turn stopped at length with its context at or past the window of the model that ran it, so the next turn cannot fit. Metabase's judgement at save time, not a provider value. NULL otherwise."
+ type: ${boolean.type}
+ constraints:
+ nullable: true
+ rollback:
+ - dropColumn:
+ tableName: metabot_message
+ columnName: context_window_full
diff --git a/src/metabase/metabot/api.clj b/src/metabase/metabot/api.clj
index a5055de9ad8..4ae07a77d76 100644
--- a/src/metabase/metabot/api.clj
+++ b/src/metabase/metabot/api.clj
@@ -218,12 +218,12 @@
;; this, such turns finalize as `:finished true :error nil` — indistinguishable
;; from a clean success.
thrown (volatile! nil)
+ ;; Read once, so the stream reports the same window the row's verdict is judged against.
+ window (metabot.self/context-window-tokens (metabot.settings/llm-metabot-provider))
xf (comp (u/tee-xf parts-atom)
(self.core/parts->aisdk-sse-xf
- (cond-> {:message-id external-id
- :context-window-tokens
- (metabot.self/context-window-tokens
- (metabot.settings/llm-metabot-provider))}
+ (cond-> {:message-id external-id
+ :context-window-tokens window}
user-external-id (assoc :message-metadata {:userMessageId user-external-id})))
(inject-title-events-xf title-job conversation-id))]
(try
@@ -283,10 +283,11 @@
:else (:error (u/seek #(= :error (:type %)) combined-parts)))]
(metabot.persistence/finalize-assistant-turn!
assistant-msg-id combined-parts
- :profile-id profile-id
- :finished? (not aborted?)
- :error error-data
- :turn-state (some-> @memory-atom memory/turn-state)))
+ :profile-id profile-id
+ :finished? (not aborted?)
+ :error error-data
+ :turn-state (some-> @memory-atom memory/turn-state)
+ :context-window-tokens window))
(catch Exception e
(log/error "Failed to finalize assistant turn"
{:conversation-id conversation-id
diff --git a/src/metabase/metabot/api/conversations.clj b/src/metabase/metabot/api/conversations.clj
index a1d8fac3baa..31b4ba24158 100644
--- a/src/metabase/metabot/api/conversations.clj
+++ b/src/metabase/metabot/api/conversations.clj
@@ -158,9 +158,11 @@
(conversation-title/title-status id (:title conversation))))
(defn- with-context-window
- "Attach the window each message's `contextTokens` should be read against. It comes
- from the model currently serving requests rather than the one that served the
- turn, because the client uses it to judge whether the *next* message will fit."
+ "Attach the window each message's `contextTokens` should be read against.
+
+ It comes from the model currently serving requests rather than the one that served the turn,
+ because the client uses it to judge whether the *next* message will fit. Whether a past turn
+ filled its own window is stored on that turn's row instead, so this window does not change it."
[detail]
(let [window (metabot.self/context-window-tokens (metabot.settings/llm-metabot-provider))]
(cond-> detail
diff --git a/src/metabase/metabot/persistence.clj b/src/metabase/metabot/persistence.clj
index 92c02701daf..ed5190b1367 100644
--- a/src/metabase/metabot/persistence.clj
+++ b/src/metabase/metabot/persistence.clj
@@ -11,6 +11,7 @@
[metabase.metabot.schema :as metabot.schema]
[metabase.metabot.schema.migrate-v1-to-v2 :as migrate]
[metabase.metabot.schema.v2 :as schema.v2]
+ [metabase.metabot.self.core :as self.core]
[metabase.metabot.settings :as metabot.settings]
[metabase.metabot.used-tables :as used-tables]
[metabase.util :as u]
@@ -372,6 +373,17 @@
(keep :state)
(reduce memory/merge-states {})))
+(defn- filled-context-window?
+ "Whether a turn that stopped for `finish-reason` with `context-tokens` reached `window`.
+
+ True only for a `length` stop whose context is at or past `window`, so the next turn cannot fit.
+ False when either count is unknown."
+ [finish-reason context-tokens window]
+ (and (= "length" finish-reason)
+ (pos-int? context-tokens)
+ (pos-int? window)
+ (>= context-tokens window)))
+
(defn finalize-assistant-turn!
"UPDATE the placeholder assistant row created by [[start-turn!]] with the final
streamed parts.
@@ -380,7 +392,10 @@
(`:start`/`:usage`/`:finish`/`:error`) is filtered out and the rest is converted to
the v2 at-rest format (see [[parts->storable-content]]) before storage; usage is
accumulated separately into the `usage` column; the error part body, if any,
- is captured into the `error` column via the `:error` kwarg.
+ is captured into the `error` column via the `:error` kwarg; why the turn
+ stopped early, if it did, is derived from those same parts into the
+ `finish_reason` column, and whether a `length` stop filled the context window
+ into `context_window_full`.
Keyword args:
- `:profile-id` — same value passed to [[start-turn!]]; tags the
@@ -393,18 +408,23 @@
- `:turn-state` — the state this turn produced; stored in the `state` column
when non-empty.
- `:slack-msg-id`, `:channel-id` — backfill onto the assistant row when known
- at completion (Slack response posts mid-stream)."
+ at completion (Slack response posts mid-stream).
+ - `:context-window-tokens` — window of the model the turn ran on. When the turn
+ stopped at `length` with its context at or past it, `context_window_full` is
+ set, so the turn reads as full later whatever model is configured then."
[assistant-msg-id parts
- & {:keys [profile-id finished? error slack-msg-id channel-id turn-state]
+ & {:keys [profile-id finished? error slack-msg-id channel-id turn-state context-window-tokens]
:or {finished? true}}]
- (let [turn-state (not-empty turn-state)
- usage (extract-usage parts)
+ (let [turn-state (not-empty turn-state)
+ usage (extract-usage parts)
+ context-tokens (extract-context-tokens parts)
+ finish-reason (self.core/parts->incomplete-finish-reason parts)
;; used-table extraction needs the raw internal parts before conversion trims
;; tool outputs, so it can see keys the stored format discards, e.g. `:transform`
- kept-parts (->> parts
- (remove #(#{:start :usage :finish :error} (:type %)))
- (filter streaming/persistable-data-part?))
- content (parts->storable-content parts)]
+ kept-parts (->> parts
+ (remove #(#{:start :usage :finish :error} (:type %)))
+ (filter streaming/persistable-data-part?))
+ content (parts->storable-content parts)]
(analytics/observe! :metabase-metabot/message-persist-bytes
{:profile-id (or profile-id "unknown")}
(u/string-byte-count (json/encode content)))
@@ -415,12 +435,21 @@
:total_tokens (->> (vals usage)
(map #(+ (:prompt %) (:completion %)))
(reduce + 0))
- :context_tokens (extract-context-tokens parts)
+ :context_tokens context-tokens
:finished (boolean finished?)
+ ;; Recorded whatever else the turn did: a turn the client
+ ;; abandoned, or one that also errored, was still truncated
+ ;; or filtered, and support and EE analytics read that back.
+ ;; `row->status` ranks aborted and errored ahead of it, so
+ ;; the status the client sees is unchanged.
+ :finish_reason finish-reason
:error (safe-encode-error error)}
turn-state (assoc :state turn-state)
slack-msg-id (assoc :slack_msg_id slack-msg-id)
- channel-id (assoc :channel_id channel-id)))
+ channel-id (assoc :channel_id channel-id)
+ ;; Set only on a full turn, so every other row keeps NULL.
+ (filled-context-window? finish-reason context-tokens context-window-tokens)
+ (assoc :context_window_full true)))
;; Hand the (potentially slow) used-table extraction + insert off to a background worker *after* the message
;; UPDATE commits, so it neither blocks nor fails the turn. The assistant row already exists, so its
;; `message_id` FK is valid even before the UPDATE completes.
@@ -664,23 +693,45 @@
(< (.toMillis (java.time.Duration/between then (Instant/now)))
placeholder-grace-period-ms))))
+(def ^:private known-finish-reason
+ "The stopped-early reasons this build can render, as a lookup. Any other stored value — one written
+ by a newer build — reads as a plain completed turn rather than reaching the client as a status
+ variant it cannot model."
+ #{"length" "content-filter" "tool-calls"})
+
(defn- row->status
- "The message's status, from its own `finished` / `error` columns. Absent
- `:finished` means success; explicit `nil` past the grace window is a crashed
+ "The message's status, from its own `finished` / `error` / `finish_reason` / `context_window_full` columns.
+
+ Absent `:finished` means success; explicit `nil` past the grace window is a crashed
placeholder and reads as aborted."
[row]
- (cond
- (placeholder-still-active? row)
- {:type "in_progress"}
-
- (some? (:error row))
- {:type "errored" :error (decode-error (:error row))}
-
- (and (contains? row :finished) (not (true? (:finished row))))
- {:type "aborted"}
-
- :else
- {:type "done"}))
+ ;; Branch order is the precedence: a row can carry a reason and still be aborted or errored, and
+ ;; what the client saw happen to the turn outranks why the model stopped.
+ (let [stored-reason (:finish_reason row)
+ finish-reason (known-finish-reason stored-reason)]
+ (cond
+ (placeholder-still-active? row)
+ {:type "in_progress"}
+
+ (some? (:error row))
+ {:type "errored" :error (decode-error (:error row))}
+
+ (and (contains? row :finished) (not (true? (:finished row))))
+ {:type "aborted"}
+
+ finish-reason
+ (cond-> {:type "incomplete" :finishReason finish-reason}
+ (and (= "length" finish-reason) (:context_window_full row)) (assoc :contextWindowFull true))
+
+ :else
+ (do
+ (when (some? stored-reason)
+ ;; This build has no copy to show for a reason it doesn't know, so the turn reads as a
+ ;; normal completed one and the reason is thrown away. Warn so it leaves a trace: the
+ ;; row came either from a newer build or from a bad write.
+ (log/warnf "Unknown metabot_message.finish_reason %s on message %s; reading it as a completed turn"
+ (pr-str stored-reason) (:id row)))
+ {:type "done"}))))
(defn- message->client-message
"Convert one `MetabotMessage` row into its client shape: the row's parts, plus
@@ -768,7 +819,7 @@
the source row so the copied prefix can be told apart from messages added after
the fork."
[new-conversation-id user-id {:keys [id data data_version role profile_id ai_proxied finished error state
- context_tokens]}]
+ context_tokens finish_reason context_window_full]}]
(cond-> {:conversation_id new-conversation-id
:data data
:data_version data_version
@@ -781,9 +832,11 @@
:ai_proxied (boolean ai_proxied)
:user_id user-id
:forked_from_message_id id}
- (some? finished) (assoc :finished finished)
- (some? error) (assoc :error error)
- (some? state) (assoc :state state)))
+ (some? finished) (assoc :finished finished)
+ (some? error) (assoc :error error)
+ (some? state) (assoc :state state)
+ (some? finish_reason) (assoc :finish_reason finish_reason)
+ (some? context_window_full) (assoc :context_window_full context_window_full)))
(mu/defn fork-conversation!
"Fork `conversation-id` at the assistant message identified by `fork-external-id`,
diff --git a/src/metabase/metabot/schema.clj b/src/metabase/metabot/schema.clj
index 315ba64d2e1..63fa0902749 100644
--- a/src/metabase/metabot/schema.clj
+++ b/src/metabase/metabot/schema.clj
@@ -199,6 +199,13 @@
["done" [:map [:type [:= "done"]]]]
["aborted" [:map [:type [:= "aborted"]]]]
["in_progress" [:map [:type [:= "in_progress"]]]]
+ ["incomplete"
+ [:map
+ [:type [:= "incomplete"]]
+ ;; why the model stopped before finishing; the client turns it into its own copy
+ [:finishReason [:enum "length" "content-filter" "tool-calls"]]
+ ;; the turn stopped at `length` because the context window was full
+ [:contextWindowFull {:optional true} :boolean]]]
["errored"
[:map
[:type [:= "errored"]]
@@ -356,7 +363,9 @@
[:data_version {:optional true} [:maybe :int]]
[:state {:optional true} [:maybe ::metabot-message.state]]
[:forked_from_message_id {:optional true} [:maybe ms/PositiveInt]]
- [:context_tokens {:optional true} [:maybe :int]]])
+ [:context_tokens {:optional true} [:maybe :int]]
+ [:finish_reason {:optional true} [:maybe :string]]
+ [:context_window_full {:optional true} [:maybe :boolean]]])
(mr/def ::metabot-prompt
"A MetabotPrompt as selected from the app DB: every column of `:metabot_prompt`."
diff --git a/src/metabase/metabot/self.clj b/src/metabase/metabot/self.clj
index 5edce0497f0..9737d7d034d 100644
--- a/src/metabase/metabot/self.clj
+++ b/src/metabase/metabot/self.clj
@@ -572,6 +572,32 @@
value)))
(cons text (reverse (map second (re-seq #"(?is)```(?:json)?\s*(.*?)```" text)))))))
+(defn- incomplete-structured-output-error
+ "The error for a structured call whose turn stopped early without a usable result.
+
+ Two cases use it: the tool call was cut off, or the turn made no tool call and its text held no JSON that
+ matches the schema.
+
+ Reports `:error-code \"structured-output-incomplete\"` with `:finish-reason` and `:raw-finish-reason` in
+ ex-data, so callers can tell it from a model that simply did not call the tool. It carries no `:status`
+ and no cause, so [[retryable-error?]] is false — a replay would stop at the same ceiling."
+ [parts reason]
+ (ex-info "LLM stopped before completing its structured response"
+ {:parts parts
+ :error-code "structured-output-incomplete"
+ :finish-reason reason
+ :raw-finish-reason (core/parts->raw-finish-reason parts)}))
+
+(defn- no-structured-output-error
+ "The error for a structured call with no tool call and no text JSON that matches the schema.
+
+ When the turn stopped early, this is [[incomplete-structured-output-error]], so the caller sees why.
+ Otherwise the model chose not to call the tool, and the error says so."
+ [parts incomplete-reason]
+ (if incomplete-reason
+ (incomplete-structured-output-error parts incomplete-reason)
+ (ex-info "LLM returned no tool call in structured response" {:parts parts})))
+
(defn call-llm-structured-with-trace
"Like [[call-llm-structured]], but returns `{:result <map> :parts [<part>...]}`
so callers can inspect everything the model emitted — any non-tool text, the
@@ -638,12 +664,22 @@
error (some (fn [{:keys [type error]}]
(when (= type :error)
error))
- parts)]
+ parts)
+ ;; Only `length` or `content-filter` can turn up here: `"tool-calls"` needs a `:finish`
+ ;; part, which the agent loop emits and this single-shot path never runs.
+ incomplete-reason (core/parts->incomplete-finish-reason parts)
+ malformed? (and (map? result) (contains? result :_raw_arguments))]
(cond
+ ;; A tool call cut off mid-JSON is not a model emitting bad JSON — the turn ran out of
+ ;; room — so report why it stopped. Only `length` reroutes this branch: a content filter
+ ;; ends the turn without truncating the JSON it already sent.
+ (and malformed? (= incomplete-reason "length"))
+ (throw (incomplete-structured-output-error parts incomplete-reason))
+
;; The tool call's JSON failed to parse; `parse-tool-arguments` returned the
;; `{:_raw_arguments ...}` sentinel. Reject it as invalid rather than handing a
;; bogus map back to the caller as if it were a valid structured result.
- (and (map? result) (contains? result :_raw_arguments))
+ malformed?
(throw (ex-info "LLM returned malformed JSON in its structured tool call"
{:parts parts
:error-code "structured-output-invalid"
@@ -659,13 +695,19 @@
(throw (ex-info (or (:message error) "LLM stream returned an error")
{:parts parts :error error :error-code "llm-stream-error"}))
+ ;; No tool call. Use JSON from the text when it matches the schema, also when the turn
+ ;; stopped early: JSON that the model completed before the stop, in the whole reply or in
+ ;; a fenced block, is usable.
:else
(if-let [output (structured-output-in-text parts json-schema)]
(do (log/info "LLM answered in text instead of calling the structured-output tool"
- {:provider provider :model model :tag (:tag opts)})
+ {:provider provider
+ :model model
+ :tag (:tag opts)
+ :finish-reason incomplete-reason
+ :raw-finish-reason (core/parts->raw-finish-reason parts)})
{:result output :parts parts})
- (throw (ex-info "LLM returned no tool call in structured response"
- {:parts parts}))))))))))
+ (throw (no-structured-output-error parts incomplete-reason))))))))))
(defn call-llm-structured
"Make an LLM call that returns structured JSON output.
@@ -688,6 +730,9 @@
Returns the parsed JSON map from the forced tool call. When the model answers
in text instead, the JSON in that text is returned if it matches `json-schema`.
+ This is also true after an early stop, but not when the stop truncated the JSON
+ of a tool call. That case, and an early stop with no matching JSON, throw
+ `structured-output-incomplete`.
For access to the full streamed trace (non-tool text), see
[[call-llm-structured-with-trace]]."
[provider-and-model messages json-schema temperature max-tokens opts]
diff --git a/src/metabase/metabot/self/core.clj b/src/metabase/metabot/self/core.clj
index 66e7b0609a2..0065a527983 100644
--- a/src/metabase/metabot/self/core.clj
+++ b/src/metabase/metabot/self/core.clj
@@ -613,18 +613,47 @@
context-window-tokens (assoc :contextWindowTokens context-window-tokens)
promptTokens (assoc :contextTokens (+ promptTokens (or completionTokens 0)))))))
-(defn- completion-finish-reason
- "The wire `finishReason` for a completed turn. A provider `tool-calls` stop collapses to
- `stop`: a turn that ends on a terminal tool call is a normal completion, not an incomplete
- one. A loop stopped at max iterations surfaces as `tool-calls` instead, so the client can
- offer to continue."
- [finish-reason error? loop-finish-reason]
+(defn- last-part-value
+ "The last non-nil `k` among the `part-type` parts of `parts`."
+ [parts part-type k]
+ (last (keep #(when (= part-type (:type %)) (k %)) parts)))
+
+(defn incomplete-finish-reason
+ "Why a turn stopped early — `\"length\"`, `\"content-filter\"` or `\"tool-calls\"` — or nil when it ran
+ to a normal stop.
+
+ A provider `length` or `content-filter` outranks a loop that stopped at `:max-iterations`, which is
+ what surfaces as `\"tool-calls\"`. A provider `tool-calls` is not incomplete on its own: a turn ending
+ on a terminal tool call is a normal completion."
+ [finish-reason loop-finish-reason]
(cond
(= finish-reason "length") "length"
- error? "error"
(= finish-reason "content-filter") "content-filter"
- (= loop-finish-reason :max-iterations) "tool-calls"
- :else "stop"))
+ (= loop-finish-reason :max-iterations) "tool-calls"))
+
+(defn parts->incomplete-finish-reason
+ "[[incomplete-finish-reason]] for a finished turn's `parts`.
+
+ Takes the provider reason from the last `:usage` part carrying one and the loop reason from the last
+ `:finish` part carrying one, so a turn read back from storage reports what the live SSE stream did."
+ [parts]
+ (incomplete-finish-reason (last-part-value parts :usage :finish-reason)
+ (last-part-value parts :finish :finish-reason)))
+
+(defn parts->raw-finish-reason
+ "The provider's own stop reason for a finished turn, before translation to a [[finish-reasons]]
+ value, or nil. Taken from the last `:usage` part carrying one."
+ [parts]
+ (last-part-value parts :usage :raw-finish-reason))
+
+(defn- completion-finish-reason
+ "The wire `finishReason` for a completed turn: an [[incomplete-finish-reason]], `\"error\"` or `\"stop\"`.
+ A `length` truncation outranks an in-turn error; every other error outranks an incomplete reason."
+ [finish-reason error? loop-finish-reason]
+ (cond
+ (= finish-reason "length") "length"
+ error? "error"
+ :else (or (incomplete-finish-reason finish-reason loop-finish-reason) "stop")))
(defn- tool-output->wire-output
"The `tool-output-available` event's `:output` value: the LLM-facing output
diff --git a/src/metabase/metabot/self/openai.clj b/src/metabase/metabot/self/openai.clj
index b714dc16da0..b2564e309c3 100644
--- a/src/metabase/metabot/self/openai.clj
+++ b/src/metabase/metabot/self/openai.clj
@@ -16,10 +16,15 @@
#{:text :function_call :reasoning})
(def ^:private stop-reasons
- "Responses API `incomplete_details.reason` → AI SDK v5 `FinishReason`. Only an incomplete response carries a reason,
- so there is nothing here for a normal or tool-call finish."
+ "Responses API stop reason → AI SDK v5 `FinishReason`.
+
+ An incomplete response carries its `incomplete_details.reason`. A completed response has no reason, only its
+ `status`, so the adapter reports that status, `\"completed\"`. Every step then carries a reason, so a normal step
+ replaces an earlier step's `content-filter`, as it does for the other adapters.
+ https://platform.openai.com/docs/api-reference/responses/object"
{"max_output_tokens" "length"
- "content_filter" "content-filter"})
+ "content_filter" "content-filter"
+ "completed" "stop"})
(defn- openai-usage->aisdk-usage
"Convert an OpenAI Responses API `usage` block into the AISDK `:usage` shape.
@@ -168,7 +173,9 @@
;; An incomplete response (e.g. truncated at max_output_tokens or stopped by a content filter)
;; still has valid partial output, so we record its usage rather than treating it as an error.
(contains? #{"response.completed" "response.incomplete"} t)
- (rf (let [raw (get-in response [:incomplete_details :reason])]
+ (rf (let [raw (if (= t "response.completed")
+ "completed"
+ (get-in response [:incomplete_details :reason]))]
(cond-> {:type :usage
:usage (openai-usage->aisdk-usage (:usage response))
;; non-standard extension, not in AISDK5
diff --git a/src/metabase/metabot/self/openai/chat_completions.clj b/src/metabase/metabot/self/openai/chat_completions.clj
index 6efa97d6db7..3c42019d623 100644
--- a/src/metabase/metabot/self/openai/chat_completions.clj
+++ b/src/metabase/metabot/self/openai/chat_completions.clj
@@ -292,7 +292,9 @@
delta (:delta choice)
finish-reason (:finish_reason choice)
error-text (when (or (some? error)
- (= "error" (core/stop-reason->finish-reason stop-reasons finish-reason)))
+ ;; OpenRouter repeats the finish reason on its usage chunk; only the first may raise the error.
+ (and (nil? @stop-reason)
+ (= "error" (core/stop-reason->finish-reason stop-reasons finish-reason))))
(or (:message error)
(some-> error pr-str)
(tru "The model provider failed to complete the response")))
diff --git a/src/metabase/slackbot/channel.clj b/src/metabase/slackbot/channel.clj
index 929b2b261a4..02881677777 100644
--- a/src/metabase/slackbot/channel.clj
+++ b/src/metabase/slackbot/channel.clj
@@ -4,6 +4,7 @@
[clojure.string :as str]
[metabase.analytics-interface.core :as analytics]
[metabase.metabot.persistence :as metabot.persistence]
+ [metabase.metabot.settings :as metabot.settings]
[metabase.slackbot.client :as slackbot.client]
[metabase.system.core :as system]
[metabase.util.log :as log]
@@ -72,6 +73,37 @@
:elements [{:type "mrkdwn"
:text (truncation-notice (system/site-url))}]})
+(defn- escape-mrkdwn
+ "Escape the characters Slack reads as markup when they appear in mrkdwn text."
+ [s]
+ (-> s
+ (str/replace "&" "&amp;")
+ (str/replace "<" "&lt;")
+ (str/replace ">" "&gt;")))
+
+(defn- finish-reason-notice
+ "Copy explaining that a turn stopped before it finished, or nil for a reason this build does not
+ recognize. Mirrors the web strings, so the same turn reads the same way in Slack and on the web."
+ [reason bot-name]
+ (case reason
+ "length" (str "Response from " bot-name " was cut off because it hit the maximum length")
+ "content-filter" (str "Response from " bot-name " was stopped by a content filter. Try rephrasing your question.")
+ "tool-calls" (str bot-name " paused after reaching its step limit for this response")
+ nil))
+
+(defn finish-reason-block
+ "A muted aside explaining that `reason` stopped a turn early, or nil when there is nothing to say.
+
+ A block rather than message text: [[metabase.slackbot.streaming/thread->history]] replays a bot
+ message's `:text` back to the model as its own words, and this sentence is Metabase describing the
+ model, not the model speaking."
+ [reason]
+ ;; `metabot-name` is admin-set and lands in mrkdwn, where `<!channel>` is a broadcast to everyone
+ ;; in the channel -- so it is escaped rather than interpolated raw.
+ (when-let [notice (finish-reason-notice reason (escape-mrkdwn (metabot.settings/metabot-name)))]
+ {:type "context"
+ :elements [{:type "mrkdwn" :text (str "_" notice "_")}]}))
+
(defn- make-channel-callbacks
"Create callback functions for channel replies.
Uses the Slack assistant setStatus API for progress indication.
@@ -109,7 +141,7 @@
on-data (make-viz-prefetch-callback prefetched-viz)]
(set-status! "Thinking...")
(try
- (let [{message-external-id :external-id assistant-msg-id :msg-id}
+ (let [{message-external-id :external-id assistant-msg-id :msg-id finish-reason :finish-reason}
(make-streaming-ai-request
conversation-id
prompt
@@ -140,8 +172,10 @@
;; Derived rather than re-tested: `elide` returns `answer` itself when it fits, so
;; the notice cannot disagree with whether a cut actually happened.
truncated? (not= final-text answer)
+ notice-block (finish-reason-block finish-reason)
final-blocks (-> (final-text-blocks final-text)
- (cond-> truncated? (conj (truncation-block)))
+ (cond-> truncated? (conj (truncation-block)))
+ (cond-> notice-block (conj notice-block))
(into blocks)
(into (feedback-blocks conversation-id message-external-id)))
res (slackbot.client/post-thread-reply client {:channel channel :thread_ts thread-ts}
diff --git a/src/metabase/slackbot/streaming.clj b/src/metabase/slackbot/streaming.clj
index bf16b150ff0..2fe539988a1 100644
--- a/src/metabase/slackbot/streaming.clj
+++ b/src/metabase/slackbot/streaming.clj
@@ -14,6 +14,8 @@
[metabase.metabot.context :as metabot.context]
[metabase.metabot.envelope :as metabot.envelope]
[metabase.metabot.persistence :as metabot.persistence]
+ [metabase.metabot.self :as metabot.self]
+ [metabase.metabot.self.core :as self.core]
[metabase.metabot.settings :as metabot.settings]
[metabase.metabot.usage :as metabot.usage]
[metabase.permissions.core :as perms]
@@ -203,6 +205,18 @@
(def ^:private generic-error-message
"Something went wrong. Please try again.")
+(def ^:private no-response-copy
+ "Shown when a turn left nothing to show: no streamed text, no tool progress and no visualization."
+ "I wasn't able to generate a response. Please try again.")
+
+(def ^:private no-response-block
+ "[[no-response-copy]] as a muted aside, for a streamed DM reply that showed nothing.
+
+ A block for the same reason as [[metabase.slackbot.channel/finish-reason-block]]: [[thread->history]]
+ replays a bot message's text to the model as its own words, and this is Metabase speaking."
+ {:type "context"
+ :elements [{:type "mrkdwn" :text (str "_" no-response-copy "_")}]})
+
(def ^:private provider-config-error-codes
"Error codes that mean the LLM provider connection is misconfigured.
@@ -256,15 +270,19 @@
- 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
- Returns `{:msg-id <pk> :external-id <uuid-str>}` so callers can both reference
- the assistant `metabot_message` row by primary key (e.g. to backfill
- `slack_msg_id` after `chat.postMessage` returns) and bake the `external_id`
- into feedback button payloads."
+ Returns `{:msg-id <pk> :external-id <uuid-str> :finish-reason <reason-or-nil>}`. The ids let
+ callers reference the assistant `metabot_message` row by primary key (e.g. to backfill
+ `slack_msg_id` after `chat.postMessage` returns) and bake the `external_id` into feedback
+ button payloads. `:finish-reason` is why the turn stopped early, for the notice the reply
+ carries; it is nil when the turn also produced an `:error` part."
[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 team-id thread-ts]}]
(let [message (metabot.envelope/user-message prompt)
- ai-proxy? (llm.provider/managed-model-ref? (metabot.settings/llm-metabot-provider))
+ model-ref (metabot.settings/llm-metabot-provider)
+ ai-proxy? (llm.provider/managed-model-ref? model-ref)
+ ;; Read with `ai-proxy?`, before the loop, so the row's verdict uses the model the turn ran on.
+ window (metabot.self/context-window-tokens model-ref)
;; Persist a placeholder assistant row up front so its `created_at` pins
;; turn ordering before any retry can sneak in earlier-timestamped rows.
;; `:user-id` stamps the author on both rows so participation-based
@@ -363,17 +381,24 @@
(metabot.persistence/finalize-assistant-turn!
assistant-msg-id
combined-parts
- :profile-id "slackbot"
- :slack-msg-id (when get-res-slack-msg-id (get-res-slack-msg-id))
- :turn-state (some-> @memory-atom memory/turn-state)
+ :profile-id "slackbot"
+ :slack-msg-id (when get-res-slack-msg-id (get-res-slack-msg-id))
+ :turn-state (some-> @memory-atom memory/turn-state)
+ :context-window-tokens window
;; A thrown error is more authoritative, but the agent loop catches most
;; failures internally and emits an `:error` part instead of throwing. Without
;; the fallback such a turn persists as a clean `finished` row, and
;; `conversation-state` then merges its partial state into every later turn.
- :error (or (some-> @thrown metabot.persistence/throwable->error-payload)
- (:error (u/seek #(= :error (:type %)) combined-parts)))))))
- {:msg-id assistant-msg-id
- :external-id assistant-external-id}))
+ :error (or (some-> @thrown metabot.persistence/throwable->error-payload)
+ (:error (u/seek #(= :error (:type %)) combined-parts)))))))
+ {:msg-id assistant-msg-id
+ :external-id assistant-external-id
+ ;; Suppressed when the turn also errored: the error copy already explains the failure, and a
+ ;; second aside about truncation would only muddy it -- the same reading web reload takes, where
+ ;; an errored turn is errored whatever else it did. Persistence derives its own reason and stores
+ ;; both, so nothing is lost here.
+ :finish-reason (when-not (some #(= :error (:type %)) @parts-atom)
+ (self.core/parts->incomplete-finish-reason @parts-atom))}))
(def ^:private viz-data-types
"DATA part types that represent visualizations."
@@ -507,7 +532,7 @@
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.
+ is sent to the stream, or explicitly via `:dismiss-thinking!` for a reply that sends neither.
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
@@ -517,6 +542,9 @@
- `: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
+ - `:dismiss-thinking!` — schedules deletion of that placeholder, for a reply that streamed no text
+ - `:text-streamed?` — atom, true once any non-blank text has reached the stream
+ - `:tools-streamed?` — atom, true once any tool progress (a task update) has reached the stream
- `: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"
@@ -527,6 +555,12 @@
;; 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 "")
+ ;; Whether any text ever reached the stream. A reply with none may have left the placeholder
+ ;; standing, so the DM path deletes it before it finalizes.
+ text-streamed? (atom false)
+ ;; Whether any tool progress reached the stream. The user watched it, so a reply that ends with
+ ;; no text is still not an empty one.
+ tools-streamed? (atom false)
;; Holds the ts of the "Thinking..." placeholder message, or nil if not posted / already dismissed.
thinking-ts (atom nil)
slack-writer (agent nil
@@ -559,14 +593,21 @@
(when (:ok response)
(reset! thinking-ts (:ts response)))))
+ dismiss-thinking! (fn []
+ (send-off slack-writer
+ (bound-fn* (fn [_] (dismiss-thinking-msg! client channel thinking-ts) nil))))
+
on-text (fn [text]
(when (seq text)
+ (when-not (str/blank? text)
+ (reset! text-streamed? true))
(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]
+ (reset! tools-streamed? true)
(send-off slack-writer
(fn [_]
(drain-pending-text! client stream-state pending-text thinking-ts)
@@ -598,6 +639,9 @@
:on-data on-data
:request-flush! (bound-fn* request-flush!)
:start-with-thinking! start-with-thinking!
+ :dismiss-thinking! dismiss-thinking!
+ :text-streamed? text-streamed?
+ :tools-streamed? tools-streamed?
:stream-state stream-state
:slack-writer slack-writer
:prefetched-viz prefetched-viz}))
@@ -657,7 +701,8 @@
(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]}
+ request-flush! start-with-thinking! stream-state slack-writer prefetched-viz
+ dismiss-thinking! text-streamed? tools-streamed?]}
(make-streaming-callbacks client {:channel channel
:thread-ts thread-ts
:team-id (:team_id auth-info)
@@ -666,7 +711,7 @@
(try
;; Start stream early so assistant persistence has :slack_msg_id.
(request-flush! true)
- (let [{message-external-id :external-id}
+ (let [{message-external-id :external-id finish-reason :finish-reason}
(make-streaming-ai-request
conversation-id
prompt
@@ -683,13 +728,26 @@
:req-slack-msg-id (:ts event)
:get-res-slack-msg-id (fn [] (:stream_ts @stream-state))})]
(request-flush! true)
+ ;; With no text there was nothing to drain, so at most a tool update has taken the placeholder
+ ;; down; deleting it again is a no-op.
+ (when-not @text-streamed?
+ (dismiss-thinking!))
(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 message-external-id))
+ ;; A reply is empty only when the user saw nothing: no text, no tool progress and no
+ ;; visualization. Only then does it get the "couldn't answer" copy -- and not even then
+ ;; when a finish-reason notice already says why it is empty.
+ empty-reply? (not (or @text-streamed? @tools-streamed? (seq blocks)))
+ notice-block (or (slackbot.channel/finish-reason-block finish-reason)
+ (when empty-reply? no-response-block))
+ final-blocks (-> []
+ (cond-> notice-block (conj notice-block))
+ (into blocks)
+ (into (feedback-blocks conversation-id message-external-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)))
@@ -704,7 +762,7 @@
(analytics/inc! :metabase-slackbot/responses-undeliverable))))
(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.")))
+ (slackbot.client/post-thread-reply client message-ctx no-response-copy)))
(catch Exception e
(cancel-prefetched-viz! prefetched-viz)
(log/errorf "[slackbot] Error in streaming response: %s" (ex-message e))
diff --git a/test/metabase/app_db/schema_migrations_test.clj b/test/metabase/app_db/schema_migrations_test.clj
index 92193978507..13c1508dd4b 100644
--- a/test/metabase/app_db/schema_migrations_test.clj
+++ b/test/metabase/app_db/schema_migrations_test.clj
@@ -3687,3 +3687,86 @@
(impl/test-migrations ["v65.2026-10-06T16:00:00" "v65.2026-10-06T16:00:02"] [migrate!]
(migrate!)
(is (not (t2/exists? :collection :entity_id "librarylibrarydashbrd"))))))
+(deftest metabot-message-finish-reason-column-test
+ (testing "v65.2026-10-08T00:00:00: metabot_message gains a nullable finish_reason, and finished is left alone"
+ (impl/test-migrations ["v65.2026-10-08T00:00:00"] [migrate!]
+ (let [user-id (t2/insert-returning-pk! :core_user {:first_name "Finish"
+ :last_name "Reason"
+ :date_joined :%now
+ :password "password"
+ :password_salt "salt"
+ ;; NOT NULL since v64.2026-07-23T12:00:05
+ :entity_id (u/generate-nano-id)})
+ conversation-id (str (random-uuid))
+ _ (t2/insert! :metabot_conversation {:id conversation-id :user_id user-id})
+ new-message! (fn [finished]
+ (t2/insert-returning-pk! :metabot_message {:conversation_id conversation-id
+ :created_at :%now
+ :profile_id "internal"
+ :role "assistant"
+ :data "[]"
+ :total_tokens 0
+ :data_version 2
+ :finished finished}))
+ completed (new-message! true)
+ aborted (new-message! false)
+ in-flight (new-message! nil)
+ ;; Read whole rows: naming finish_reason in the query would make the pre-migration run a SQL
+ ;; error, which says nothing about whether the migration added the column.
+ message (fn [id] (t2/select-one :metabot_message :id id))]
+ (migrate!)
+ (testing "the column exists and every pre-migration row reads NULL"
+ (is (contains? (message completed) :finish_reason))
+ (is (nil? (:finish_reason (message completed))))
+ (is (nil? (:finish_reason (message aborted))))
+ (is (nil? (:finish_reason (message in-flight)))))
+ (testing "finished keeps its value: true completed, false client-aborted, NULL in flight"
+ (is (true? (:finished (message completed))))
+ (is (false? (:finished (message aborted))))
+ (is (nil? (:finished (message in-flight)))))
+ (testing "the column stores a reason"
+ (t2/update! :metabot_message completed {:finish_reason "content-filter"})
+ (is (= "content-filter" (:finish_reason (message completed)))))
+ (testing "rolling back drops the column and keeps the rows"
+ (migrate! :down 64)
+ (is (not (contains? (message completed) :finish_reason)))
+ (is (true? (:finished (message completed)))))))))
+
+(deftest metabot-message-context-window-full-column-test
+ (testing "v65.2026-10-08T00:00:01: metabot_message gains a nullable context_window_full"
+ (impl/test-migrations ["v65.2026-10-08T00:00:01"] [migrate!]
+ (let [user-id (t2/insert-returning-pk! :core_user {:first_name "Context"
+ :last_name "Window"
+ :date_joined :%now
+ :password "password"
+ :password_salt "salt"
+ ;; NOT NULL since v64.2026-07-23T12:00:05
+ :entity_id (u/generate-nano-id)})
+ conversation-id (str (random-uuid))
+ _ (t2/insert! :metabot_conversation {:id conversation-id :user_id user-id})
+ ;; `finish_reason` exists already: its changeset runs before this one
+ message-id (t2/insert-returning-pk! :metabot_message {:conversation_id conversation-id
+ :created_at :%now
+ :profile_id "internal"
+ :role "assistant"
+ :data "[]"
+ :total_tokens 0
+ :data_version 2
+ :finished true
+ :finish_reason "length"})
+ ;; Read whole rows: naming the column in the query would make the pre-migration run a SQL error,
+ ;; which says nothing about whether the migration added it.
+ message #(t2/select-one :metabot_message :id message-id)]
+ (migrate!)
+ (testing "the column exists and a pre-migration row reads NULL"
+ (is (contains? (message) :context_window_full))
+ (is (nil? (:context_window_full (message)))))
+ (testing "the column stores the verdict"
+ (t2/update! :metabot_message message-id {:context_window_full true})
+ (is (true? (:context_window_full (message)))))
+ (testing "rolling back drops the column and keeps the row"
+ (migrate! :down 64)
+ (is (not (contains? (message) :context_window_full)))
+ (is (true? (:finished (message)))))))))
diff --git a/test/metabase/metabot/api/conversations_test.clj b/test/metabase/metabot/api/conversations_test.clj
index 8933dad7163..a7b8b44561f 100644
--- a/test/metabase/metabot/api/conversations_test.clj
+++ b/test/metabase/metabot/api/conversations_test.clj
@@ -8,6 +8,7 @@
[metabase.metabot.api :as metabot.api]
[metabase.metabot.conversation-title :as conversation-title]
[metabase.metabot.persistence :as metabot.persistence]
+ [metabase.metabot.self :as metabot.self]
[metabase.test :as mt]
[toucan2.core :as t2]))
@@ -515,18 +516,93 @@
(t2/delete! :model/MetabotMessage :conversation_id new-id)
(t2/delete! :model/MetabotConversation :id new-id))))))))
+(deftest conversation-detail-returns-incomplete-status-test
+ (testing "GET /api/metabot/conversations/:id reports a turn that stopped early as incomplete"
+ (let [user-id (mt/user->id :rasta)]
+ (mt/with-temp [:model/MetabotConversation {convo-id :id} {:user_id user-id :title "truncated"}
+ :model/MetabotMessage _u {:conversation_id convo-id :user_id user-id :role "user"
+ :external_id (str (random-uuid))
+ :data [{:type "text" :text "hi"}]
+ :created_at (seconds-ago 60)}
+ :model/MetabotMessage _a {:conversation_id convo-id :user_id user-id :role "assistant"
+ :external_id (str (random-uuid))
+ :finished true :finish_reason "length"
+ :context_tokens 150
+ :data [{:type "text" :text "cut o"}]
+ :created_at (seconds-ago 50)}
+ :model/MetabotMessage _u2 {:conversation_id convo-id :user_id user-id :role "user"
+ :external_id (str (random-uuid))
+ :data [{:type "text" :text "go on"}]
+ :created_at (seconds-ago 40)}
+ :model/MetabotMessage _a2 {:conversation_id convo-id :user_id user-id :role "assistant"
+ :external_id (str (random-uuid))
+ :finished true :finish_reason "length"
+ :context_tokens 200 :context_window_full true
+ :data [{:type "text" :text "cut o"}]
+ :created_at (seconds-ago 30)}]
+ (let [statuses-at-window (fn [window]
+ (mt/with-dynamic-fn-redefs [metabot.self/context-window-tokens (constantly window)]
+ (let [{:keys [messages]} (mt/user-http-request
+ :rasta :get 200 (str "metabot/conversations/" convo-id))]
+ (mapv :status [(nth messages 1) (nth messages 3)]))))
+ plain-length {:type "incomplete" :finishReason "length"}
+ full-window (assoc plain-length :contextWindowFull true)]
+ (testing "each turn reads as its row recorded it: a plain length stop, and one that filled its window"
+ (is (= [plain-length full-window] (statuses-at-window 1000))))
+ (testing "the current model's window does not change a past turn's verdict"
+ (testing "a smaller window does not make the plain stop full"
+ (is (= [plain-length full-window] (statuses-at-window 100))))
+ (testing "a bigger window does not clear the full one"
+ (is (= [plain-length full-window] (statuses-at-window 1000000))))))))))
+
+(deftest fork-conversation-from-incomplete-turn-test
+ (testing "POST /api/metabot/conversations/:id/fork forks from a turn that stopped early"
+ (let [user-id (mt/user->id :rasta)
+ a1 (str (random-uuid))]
+ (mt/with-temp [:model/MetabotConversation {convo-id :id} {:user_id user-id :title "truncated"}
+ :model/MetabotMessage _u {:conversation_id convo-id :user_id user-id :role "user"
+ :external_id (str (random-uuid))
+ :data [{:type "text" :text "hi"}]
+ :created_at (seconds-ago 60)}
+ :model/MetabotMessage _a {:conversation_id convo-id :user_id user-id :role "assistant"
+ :external_id a1 :finished true :finish_reason "length"
+ :context_tokens 150 :context_window_full true
+ :data [{:type "text" :text "cut o"}]
+ :created_at (seconds-ago 50)}]
+ ;; a current window far bigger than the turn's context: the verdict must come from the row
+ (let [response (mt/with-dynamic-fn-redefs [metabot.self/context-window-tokens (constantly 1000000)]
+ (mt/user-http-request :rasta :post 200
+ (str "metabot/conversations/" convo-id "/fork")
+ {:message_id a1}))
+ new-id (:conversation_id response)]
+ (try
+ (testing "the clone keeps the reason and the full-window verdict"
+ (is (=? [{:finish_reason nil :context_window_full nil}
+ {:finish_reason "length" :context_window_full true}]
+ (metabot.persistence/live-messages new-id))))
+ (testing "so the forked conversation still reads as incomplete, with a full window"
+ (is (= {:type "incomplete" :finishReason "length" :contextWindowFull true}
+ (:status (second (:messages response))))))
+ (finally
+ (t2/delete! :model/MetabotMessage :conversation_id new-id)
+ (t2/delete! :model/MetabotConversation :id new-id))))))))
+
(deftest fork-conversation-validation-test
(testing "POST /api/metabot/conversations/:id/fork rejects invalid fork targets"
- (let [user-id (mt/user->id :rasta)
- user-ext (str (random-uuid))
- err-ext (str (random-uuid))
- live-ext (str (random-uuid))]
+ (let [user-id (mt/user->id :rasta)
+ user-ext (str (random-uuid))
+ err-ext (str (random-uuid))
+ live-ext (str (random-uuid))
+ abort-ext (str (random-uuid))]
(mt/with-temp [:model/MetabotConversation {convo-id :id} {:user_id user-id :title "c"}
:model/MetabotMessage _u {:conversation_id convo-id :user_id user-id :role "user"
:external_id user-ext :created_at (seconds-ago 60)}
:model/MetabotMessage _errored {:conversation_id convo-id :user_id user-id :role "assistant"
:external_id err-ext :finished true
:error "{\"message\":\"boom\"}" :created_at (seconds-ago 50)}
+ :model/MetabotMessage _aborted {:conversation_id convo-id :user_id user-id :role "assistant"
+ :external_id abort-ext :finished false
+ :finish_reason "length" :created_at (seconds-ago 45)}
:model/MetabotMessage _inflight {:conversation_id convo-id :user_id user-id :role "assistant"
:external_id live-ext :finished nil :created_at (seconds-ago 40)}]
(let [convo-count #(t2/count :model/MetabotConversation)
@@ -539,6 +615,8 @@
(fork! user-ext))
(testing "an errored assistant message cannot be a fork target"
(fork! err-ext))
+ (testing "an aborted assistant message that stored a reason cannot be a fork target"
+ (fork! abort-ext))
(testing "an in-flight placeholder cannot be a fork target"
(fork! live-ext))
(testing "an unknown message id cannot be a fork target"
diff --git a/test/metabase/metabot/api_test.clj b/test/metabase/metabot/api_test.clj
index 7e5088da81c..5d72c0f923c 100644
--- a/test/metabase/metabot/api_test.clj
+++ b/test/metabase/metabot/api_test.clj
@@ -93,12 +93,104 @@
:role :user
:data [{:type "text" :text (:content question)}]
:data_version 2}
- {:total_tokens pos-int?
- :role :assistant
- :data [{:type "step-start"}
- {:type "text" :text "Hello from native agent!" :state "done"}]
- :data_version 2}]
- messages)))))))))))
+ {:total_tokens pos-int?
+ :role :assistant
+ :data [{:type "step-start"}
+ {:type "text" :text "Hello from native agent!" :state "done"}]
+ :data_version 2
+ ;; the provider truncated this turn, so the row records why it stopped
+ :finished true
+ :finish_reason "length"}]
+ messages))
+ (is (nil? (:context_window_full (second messages)))
+ "15 context tokens against a 1000-token window leave room, so the row is not full"))))))))))
+
+(deftest native-agent-streaming-records-context-window-full-test
+ (testing "a length stop whose context reached the streamed window is saved as full"
+ (mt/with-temporary-setting-values [llm.settings/llm-providers llm.tu/default-connections
+ metabot.settings/llm-metabot-provider test-provider]
+ (binding [scope/*current-user-metabot-permissions* scope/all-yes-permissions]
+ (let [conversation-id (str (random-uuid))]
+ (mt/with-dynamic-fn-redefs [openrouter/openrouter (fn [_]
+ (mut/mock-llm-response
+ [{:type :start :id "msg-1"}
+ {:type :text :text "cut o"}
+ {:type :usage :usage {:promptTokens 10 :completionTokens 5}
+ :model "test-model" :id "msg-1"
+ :finish-reason "length"}]))
+ metabot.self/context-window-tokens (constantly 15)
+ conversation-title/ensure-title! (constantly {:status :ready
+ :title "Orders by Month"})]
+ (mt/with-model-cleanup [:model/MetabotMessage
+ [:model/MetabotConversation :created_at]]
+ (let [response (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
+ {:message "Test full window"
+ :context {}
+ :conversation_id conversation-id
+ :state {}})
+ finish (->> (str/split-lines response)
+ (filter #(str/starts-with? % "data: "))
+ (remove #(= "data: [DONE]" %))
+ (map #(json/decode+kw (subs % 6)))
+ (u/seek #(= "finish" (:type %))))]
+ (testing "the stream reports the same window the row is judged against"
+ (is (=? {:finishReason "length"
+ :messageMetadata {:contextTokens 15 :contextWindowTokens 15}}
+ finish)))
+ (is (=? {:finish_reason "length" :context_tokens 15 :context_window_full true}
+ (t2/select-one :model/MetabotMessage
+ :conversation_id conversation-id :role "assistant")))))))))))
+
+(def ^:private openrouter-error-chunks
+ "Raw OpenRouter chunks for a generation the upstream model abandoned: OpenRouter reports that as
+ `finish_reason \"error\"` rather than as an error event."
+ [{:id "gen-error-1"
+ :model "anthropic/claude-haiku-4-5"
+ :choices [{:index 0 :delta {:role "assistant" :content "Here's what I fou"} :finish_reason nil}]}
+ {:choices [{:index 0 :delta {} :finish_reason "error"}]}
+ {:choices [] :usage {:prompt_tokens 12 :completion_tokens 3}}])
+
+(deftest native-agent-streaming-openrouter-error-finish-persists-errored-turn-test
+ (testing "a provider failure reported as a finish reason ends the stream as an error and persists as one"
+ (mt/with-temporary-setting-values [llm.settings/llm-providers llm.tu/default-connections
+ metabot.settings/llm-metabot-provider test-provider]
+ (binding [scope/*current-user-metabot-permissions* scope/all-yes-permissions]
+ (with-redefs [config/is-dev? true]
+ (let [conversation-id (str (random-uuid))]
+ (mt/with-dynamic-fn-redefs [openrouter/openrouter (fn [_]
+ (eduction (openrouter/openrouter->aisdk-chunks-xf)
+ openrouter-error-chunks))
+ metabot.self/context-window-tokens (constantly 1000)
+ conversation-title/ensure-title! (constantly {:status :ready
+ :title "Orders by Month"})]
+ (mt/with-model-cleanup [:model/MetabotMessage
+ [:model/MetabotConversation :created_at]]
+ (let [response (mt/user-http-request :rasta :post 202 "metabot/agent-streaming"
+ {:message "Test provider failure"
+ :context {}
+ :conversation_id conversation-id
+ :state {}})
+ events (->> (str/split-lines response)
+ (filter #(str/starts-with? % "data: "))
+ (remove #(= "data: [DONE]" %))
+ (mapv #(json/decode+kw (subs % 6))))
+ messages (t2/select :model/MetabotMessage :conversation_id conversation-id)
+ assistant (u/seek #(= :assistant (:role %)) messages)]
+ (testing "the SSE stream carries an error event and finishes as an error"
+ (is (= 1 (count (filterv #(= "error" (:type %)) events))))
+ (is (=? {:type "finish" :finishReason "error"}
+ (u/seek #(= "finish" (:type %)) events))))
+ (testing "so the turn is persisted as errored, not as a clean stop"
+ ;; the error column is filled by api.clj's own seek over the finalized parts
+ (is (some? (:error assistant)))
+ (is (=? {:message string?} (json/decode+kw (:error assistant))))
+ (is (true? (:finished assistant)))
+ (is (nil? (:finish_reason assistant))
+ "an errored turn is not also an incomplete one"))
+ (testing "and the conversation endpoint drops the errored pair"
+ (is (= []
+ (:messages (mt/user-http-request :rasta :get 200
+ (str "metabot/conversations/" conversation-id)))))))))))))))
(deftest emits-title-event-inline-when-ready-during-stream-test
(testing "when the title becomes ready while streaming, the real title event is injected inline before the finish event"
diff --git a/test/metabase/metabot/example_question_generator_test.clj b/test/metabase/metabot/example_question_generator_test.clj
index 1bc73e17520..e8df5a04d7e 100644
--- a/test/metabase/metabot/example_question_generator_test.clj
+++ b/test/metabase/metabot/example_question_generator_test.clj
@@ -137,6 +137,29 @@
{:model "anthropic/claude-haiku-4-5"}]
@captured-opts))))))))
+(deftest example-questions-surface-incomplete-structured-output-test
+ (testing "a generation truncated before its tool call surfaces the incomplete finish reason to the caller"
+ (mt/with-temporary-setting-values [llm-providers llm.tu/default-connections
+ llm-metabot-provider "openrouter/anthropic/claude-haiku-4-5"]
+ (mt/with-dynamic-fn-redefs [openrouter/openrouter (constantly
+ (test-util/mock-llm-response
+ [{:type :start :id "msg-1"}
+ {:type :text :id "t1" :text "Here are some quest"}
+ {:type :usage
+ :model "m"
+ :usage {:promptTokens 1 :completionTokens 2}
+ :finish-reason "length"
+ :raw-finish-reason "max_tokens"}]))]
+ (mt/with-log-level [metabase.metabot.example-question-generator :fatal]
+ (let [e (try
+ (native-generator/generate-example-questions
+ {:tables [{:name "Orders" :fields [{:name "total" :type "number"}]}]
+ :metrics []})
+ (catch clojure.lang.ExceptionInfo e e))]
+ (is (instance? clojure.lang.ExceptionInfo e))
+ (is (= "structured-output-incomplete" (:error-code (ex-data e))))
+ (is (= "length" (:finish-reason (ex-data e))))))))))
+
(deftest template-cache-test
(testing "template is cached after first load"
(native-generator/clear-template-cache!)
diff --git a/test/metabase/metabot/persistence_test.clj b/test/metabase/metabot/persistence_test.clj
index 1ed4b452791..dbf841fc306 100644
--- a/test/metabase/metabot/persistence_test.clj
+++ b/test/metabase/metabot/persistence_test.clj
@@ -971,6 +971,45 @@
(is (= {:type "errored" :error {:message "boom"}} (:status message)))
(is (not-any? annotated? (:parts message))))))
+(deftest ^:parallel message->client-message-incomplete-status-test
+ (testing "a turn that stopped early reloads as incomplete, carrying the reason"
+ (doseq [reason ["length" "content-filter" "tool-calls"]]
+ (testing reason
+ (let [status (:status (client-message {:role :assistant :finished true :finish_reason reason
+ :data [{:type "text" :text "partial"}]}))]
+ (is (= {:type "incomplete" :finishReason reason} status))
+ (is (not (contains? status :contextWindowFull))
+ "a row without `context_window_full` is not a full-window stop")))))
+ (testing "a length stop whose row records a full window carries the flag the client alerts on"
+ (is (= {:type "incomplete" :finishReason "length" :contextWindowFull true}
+ (:status (client-message {:role :assistant :finished true :finish_reason "length"
+ :context_window_full true :data []})))))
+ (testing "the flag is ignored on any other reason"
+ (is (= {:type "incomplete" :finishReason "content-filter"}
+ (:status (client-message {:role :assistant :finished true :finish_reason "content-filter"
+ :context_window_full true :data []})))))
+ (testing "a content-filtered turn with no text still carries the status the FE alerts on"
+ (let [message (client-message {:role :assistant :finished true :finish_reason "content-filter"
+ :data []})]
+ (is (= [] (:parts message)))
+ (is (= {:type "incomplete" :finishReason "content-filter"} (:status message)))))
+ (testing "an aborted row that also stored a reason still reads aborted — aborted outranks incomplete"
+ (is (= {:type "aborted"}
+ (:status (client-message {:role :assistant :finished false :finish_reason "length"
+ :data []})))))
+ (testing "a reason written by a newer build reads as done rather than failing the read"
+ (log.capture/with-log-messages-for-level [logs [metabase.metabot.persistence :warn]]
+ (is (= {:type "done"}
+ (:status (client-message {:role :assistant :finished true :finish_reason "quantum-foam"
+ :data []}))))
+ (is (some #(re-find #"Unknown metabot_message.finish_reason" (:message %)) (logs)))))
+ (testing "an unknown reason on an aborted row does not warn: the reason is unused there"
+ (log.capture/with-log-messages-for-level [logs [metabase.metabot.persistence :warn]]
+ (is (= {:type "aborted"}
+ (:status (client-message {:role :assistant :finished false :finish_reason "quantum-foam"
+ :data []}))))
+ (is (not-any? #(re-find #"Unknown metabot_message.finish_reason" (:message %)) (logs))))))
+
(deftest messages->client-messages-errored-pairs-test
(testing "by default, errored assistant rows and the preceding user prompt are dropped"
(is (= ["first" "first reply" "third" "third reply"]
@@ -1117,6 +1156,95 @@
(is (true? (:finished row))
"an errored turn still finalizes as finished"))))))
+(defn- usage-part
+ "A `:usage` part carrying `finish-reason`, or none when it is nil."
+ [finish-reason]
+ (cond-> {:type :usage :model "claude" :usage {:promptTokens 10 :completionTokens 5}}
+ finish-reason (assoc :finish-reason finish-reason)))
+
+(defn- finalize-parts!
+ "Run start-turn! then finalize-assistant-turn! over `parts` (as :rasta).
+ Returns the assistant row."
+ [parts & finalize-opts]
+ (mt/with-current-user (mt/user->id :rasta)
+ (let [{:keys [assistant-msg-id]} (metabot-persistence/start-turn!
+ (str (random-uuid)) "metabot-1"
+ {:role "user" :content "go"})]
+ (apply metabot-persistence/finalize-assistant-turn! assistant-msg-id parts finalize-opts)
+ (t2/select-one :model/MetabotMessage assistant-msg-id))))
+
+(deftest finalize-assistant-turn-persists-finish-reason-test
+ (testing "finalize-assistant-turn! records why a turn stopped early"
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (testing "a provider truncation"
+ (is (=? {:finish_reason "length" :finished true}
+ (finalize-parts! [{:type :text :text "cut o"} (usage-part "length")]))))
+ (testing "a content filter"
+ (is (=? {:finish_reason "content-filter" :finished true}
+ (finalize-parts! [(usage-part "content-filter")]))))
+ (testing "the agent loop stopping at its step limit"
+ (is (=? {:finish_reason "tool-calls" :finished true}
+ (finalize-parts! [{:type :text :text "partial"}
+ {:type :finish :finish-reason :max-iterations}]))))
+ (testing "the last usage part carrying a reason decides"
+ (is (=? {:finish_reason "length"}
+ (finalize-parts! [(usage-part "length") (usage-part nil)]))))
+ (testing "an aborted turn keeps the reason for diagnostics, and still finalizes as not finished"
+ (is (=? {:finish_reason "length" :finished false}
+ (finalize-parts! [(usage-part "length")] :finished? false)))))))
+
+(deftest finalize-assistant-turn-persists-context-window-full-test
+ (testing "finalize-assistant-turn! records whether a length stop filled the window of the model that ran it"
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ ;; `usage-part` puts 10 prompt + 5 completion = 15 tokens in the context
+ (let [truncated [{:type :text :text "cut o"} (usage-part "length")]]
+ (testing "context at the window"
+ (is (=? {:finish_reason "length" :context_tokens 15 :context_window_full true}
+ (finalize-parts! truncated :context-window-tokens 15))))
+ (testing "context past the window"
+ (is (true? (:context_window_full (finalize-parts! truncated :context-window-tokens 10)))))
+ (testing "room left in the window: a plain output-cap stop, and the column stays NULL"
+ (is (nil? (:context_window_full (finalize-parts! truncated :context-window-tokens 16)))))
+ (testing "no known window: nothing to judge"
+ (is (nil? (:context_window_full (finalize-parts! truncated)))))
+ (testing "no usage observed: nothing to judge"
+ (is (nil? (:context_window_full (finalize-parts! [{:type :text :text "cut o"}]
+ :context-window-tokens 15))))))
+ (testing "only a length stop can fill the window"
+ (doseq [parts [[(usage-part "content-filter")]
+ [(usage-part nil)]]]
+ (is (nil? (:context_window_full (finalize-parts! parts :context-window-tokens 10)))))))))
+
+(deftest finalize-assistant-turn-persists-error-and-finish-reason-test
+ (testing "a turn with both an error and an incomplete reason persists both, and still reloads as errored"
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (let [error-data {:message "boom" :type "java.lang.RuntimeException"}
+ row (finalize-parts! [{:type :text :text "partial"} (usage-part "length")]
+ :error error-data)]
+ (is (= "length" (:finish_reason row)))
+ (is (= error-data (json/decode+kw (:error row))))
+ (is (= {:type "errored" :error error-data}
+ (:status (first (metabot-persistence/messages->client-messages
+ [row] {:include-errored? true}))))
+ "errored outranks incomplete on reload")))))
+
+(deftest finalize-stores-no-reason-for-complete-outcomes-test
+ (testing "a turn that ran to a normal end stores no reason"
+ (t2/with-transaction [_conn nil {:rollback-only true}]
+ (doseq [[label parts]
+ [["a provider stop"
+ [{:type :text :text "done"} (usage-part "stop")]]
+ ["a provider reason that maps to `other`"
+ [(usage-part "other")]]
+ ["a terminal tool call"
+ [(usage-part "tool-calls") {:type :finish :finish-reason :terminal-tool}]]
+ ["an empty response"
+ [{:type :finish :finish-reason :empty-response}]]
+ ["a content filter superseded by a later stop"
+ [(usage-part "content-filter") (usage-part "stop")]]]]
+ (testing label
+ (is (nil? (:finish_reason (finalize-parts! parts)))))))))
+
(deftest messages-client-messages-in-flight-placeholders-test
(testing "in-flight placeholders (assistant role, finished=nil, recent created_at)
become an in-progress message envelope"
diff --git a/test/metabase/metabot/self/claude_test.clj b/test/metabase/metabot/self/claude_test.clj
index 157f610e412..9c767af1706 100644
--- a/test/metabase/metabot/self/claude_test.clj
+++ b/test/metabase/metabot/self/claude_test.clj
@@ -208,10 +208,12 @@
(testing "the AI SDK finish reason rides the usage chunk alongside the raw provider value"
(are [raw finish-reason] (=? {:finish-reason finish-reason :raw-finish-reason raw}
(usage-chunk raw))
- "max_tokens" "length"
- "end_turn" "stop"
- "pause_turn" "stop"
- "compaction" "other"))))
+ "max_tokens" "length"
+ "model_context_window_exceeded" "length"
+ "refusal" "content-filter"
+ "end_turn" "stop"
+ "pause_turn" "stop"
+ "compaction" "other"))))
(deftest ^:parallel claude-thinking-blocks-translated-test
(testing "thinking content blocks become reasoning chunks; signature rides the end"
diff --git a/test/metabase/metabot/self/openai/chat_completions_test.clj b/test/metabase/metabot/self/openai/chat_completions_test.clj
index 615cac6d12e..d04c8e0322c 100644
--- a/test/metabase/metabot/self/openai/chat_completions_test.clj
+++ b/test/metabase/metabot/self/openai/chat_completions_test.clj
@@ -1,5 +1,6 @@
(ns metabase.metabot.self.openai.chat-completions-test
(:require
+ [clojure.string :as str]
[clojure.test :refer :all]
[metabase.metabot.self.core :as self.core]
[metabase.metabot.self.mistral :as mistral]
@@ -698,6 +699,100 @@
:function {:name "search" :arguments "{\"query\": \"rev"}}]}}]}
error-chunk]))))))))
+;;; ──────────────────────────────────────────────────────────────────
+;;; Error finish reason tests
+;;;
+;;; OpenRouter, Mistral and Z.AI report a mid-generation upstream failure
+;;; as a `finish_reason` instead of an error event, and their dialect
+;;; tables translate it to the AI SDK reason "error".
+;;; ──────────────────────────────────────────────────────────────────
+
+(defn- error-finish-chunks
+ "Chat Completions chunks for a stream whose last choice finishes on `raw-reason`."
+ [raw-reason]
+ [{:id "chatcmpl-err"
+ :model "m"
+ :choices [{:index 0 :delta {:role "assistant" :content "Here's what I fou"} :finish_reason nil}]}
+ {:choices [{:index 0 :delta {} :finish_reason raw-reason}]}
+ {:choices [] :usage {:prompt_tokens 12 :completion_tokens 3}}])
+
+(defn- chunks-of-type
+ [t chunks]
+ (filterv #(= t (:type %)) chunks))
+
+(deftest ^:parallel chunks-xf-error-finish-reason-emits-error-chunk-test
+ (testing "a dialect that maps its raw finish reason to \"error\" emits one :error chunk"
+ ;; Without it the failure reaches the client as a clean stop: nothing else downstream says the
+ ;; turn failed, so the web client marks it done and persistence records no error.
+ (doseq [[dialect xf raw] [["OpenRouter" (openrouter/openrouter->aisdk-chunks-xf) "error"]
+ ["Mistral" (mistral/mistral->aisdk-chunks-xf) "error"]
+ ["Z.AI" (zai/zai->aisdk-chunks-xf) "network_error"]]]
+ (testing dialect
+ (let [chunks (into [] xf (error-finish-chunks raw))]
+ (testing "exactly one"
+ (is (=? [{:type :error :errorText "The model provider failed to complete the response"}]
+ (chunks-of-type :error chunks))))
+ (testing "and the :usage chunk is unchanged"
+ (is (=? [{:type :usage
+ :id "chatcmpl-err"
+ :finish-reason "error"
+ :raw-finish-reason raw
+ :usage {:promptTokens 12 :completionTokens 3}}]
+ (chunks-of-type :usage chunks)))))))))
+
+(deftest ^:parallel chunks-xf-repeated-error-finish-reason-emits-one-error-test
+ (testing "a finish reason repeated on the usage chunk, as OpenRouter sends it, still emits one :error chunk"
+ (let [chunks (into [] (openrouter/openrouter->aisdk-chunks-xf)
+ [{:id "chatcmpl-err"
+ :model "m"
+ :choices [{:index 0 :delta {:role "assistant" :content "Here's what I fou"} :finish_reason nil}]}
+ {:choices [{:index 0 :delta {} :finish_reason "error"}]}
+ {:choices [{:index 0 :delta {} :finish_reason "error"}]
+ :usage {:prompt_tokens 12 :completion_tokens 3}}])]
+ (is (= 1 (count (chunks-of-type :error chunks))))
+ (is (=? [{:type :usage :finish-reason "error" :raw-finish-reason "error"}]
+ (chunks-of-type :usage chunks))))))
+
+(deftest ^:parallel chunks-xf-non-error-finish-reasons-emit-no-error-test
+ (testing "a finish reason that does not translate to \"error\" emits no :error chunk"
+ (doseq [raw ["stop" "length" "tool_calls" "content_filter"]]
+ (testing raw
+ (is (empty? (chunks-of-type :error (into [] (openrouter/openrouter->aisdk-chunks-xf)
+ (error-finish-chunks raw))))))))
+ (testing "a dialect whose table has no \"error\" entry translates a raw \"error\" to \"other\" and stays quiet"
+ ;; The base table is what vLLM and Moonshot use.
+ (let [chunks (into [] (chat-completions/chat-completions->aisdk-chunks-xf) (error-finish-chunks "error"))]
+ (is (empty? (chunks-of-type :error chunks)))
+ (is (=? [{:type :usage :finish-reason "other" :raw-finish-reason "error"}]
+ (chunks-of-type :usage chunks))))))
+
+(deftest ^:parallel chunks-xf-incomplete-finish-reason-on-usage-chunk-test
+ (testing "a truncation or content filter rides the :usage chunk, in each dialect's own spelling"
+ ;; `parts->incomplete-finish-reason` reads exactly this to mark a reloaded turn incomplete, so a
+ ;; dialect whose own spelling were missing from its table would read back as a completed turn.
+ (are [xf raw finish-reason] (=? [{:type :usage :finish-reason finish-reason :raw-finish-reason raw}]
+ (chunks-of-type :usage (into [] xf (error-finish-chunks raw))))
+ ;; the base table, used unchanged by vLLM and Moonshot
+ (chat-completions/chat-completions->aisdk-chunks-xf) "length" "length"
+ (chat-completions/chat-completions->aisdk-chunks-xf) "content_filter" "content-filter"
+ (openrouter/openrouter->aisdk-chunks-xf) "length" "length"
+ ;; Mistral's own name for hitting the model's context limit
+ (mistral/mistral->aisdk-chunks-xf) "model_length" "length"
+ ;; Z.AI spells a filtered response `sensitive`
+ (zai/zai->aisdk-chunks-xf) "sensitive" "content-filter")))
+
+(deftest ^:parallel sse-chat-completions-error-finish-is-error-test
+ (testing "the failure reaches the client as an error event and finishReason \"error\", not \"stop\""
+ (let [lines (into [] (comp (openrouter/openrouter->aisdk-chunks-xf)
+ (self.core/aisdk-xf)
+ (self.core/parts->aisdk-sse-xf))
+ (error-finish-chunks "error"))
+ events (->> (butlast lines)
+ (mapv #(json/decode+kw (subs (str/trimr %) 6))))]
+ (is (= "data: [DONE]\n" (last lines)))
+ (is (= 1 (count (filterv #(= "error" (:type %)) events))))
+ (is (=? {:type "finish" :finishReason "error"} (last events))))))
+
;;; ──────────────────────────────────────────────────────────────────
;;; models-catalog tests
;;; ──────────────────────────────────────────────────────────────────
diff --git a/test/metabase/metabot/self/openai_test.clj b/test/metabase/metabot/self/openai_test.clj
index 1ebe5d803b8..350471d8006 100644
--- a/test/metabase/metabot/self/openai_test.clj
+++ b/test/metabase/metabot/self/openai_test.clj
@@ -210,6 +210,20 @@
(testing "no error chunk is produced for an incomplete (partial-but-valid) response"
(is (empty? (filter #(= :error (:type %)) parts)))))))
+(deftest ^:parallel openai-response-completed-reports-stop-test
+ (testing "a terminal response.completed event reports a \"stop\" finish reason on its usage part"
+ ;; Without it, a normal step would leave an earlier step's content-filter in place as the turn's reason.
+ (doseq [[fixture-name opts] [["openai-text"
+ {:input [{:role :user :content "Say hello briefly, in under 10 words."}]}]
+ ["openai-tool-calls"
+ {:input [{:role :user :content "What time is it in Kyiv?"}]
+ :tools [(metabot.tu/get-time-tool)]}]]]
+ (testing fixture-name
+ (is (=? {:type :usage
+ :finish-reason "stop"
+ :raw-finish-reason "completed"}
+ (last (into [] (openai/openai->aisdk-chunks-xf) (fixture fixture-name opts)))))))))
+
;;; ──────────────────────────────────────────────────────────────────
;;; Usage normalization tests
;;; ──────────────────────────────────────────────────────────────────
diff --git a/test/metabase/metabot/self_test.clj b/test/metabase/metabot/self_test.clj
index 5e7d756ab7a..75ee671af88 100644
--- a/test/metabase/metabot/self_test.clj
+++ b/test/metabase/metabot/self_test.clj
@@ -1000,6 +1000,26 @@
(is (=? {:type "finish" :finishReason "length"}
(last (sse-events [(usage-part "length" "max_tokens")
{:type :finish :finish-reason :max-iterations}])))))
+ (testing "a content-filter finish outranks a max-iterations stop"
+ (is (=? {:type "finish" :finishReason "content-filter"}
+ (last (sse-events [(usage-part "content-filter" "refusal")
+ {:type :finish :finish-reason :max-iterations}])))))
+ (testing "the last non-nil usage finish reason decides"
+ (testing "a later stop supersedes an earlier content-filter"
+ (is (=? {:type "finish" :finishReason "stop"}
+ (last (sse-events [(usage-part "content-filter" "refusal")
+ (usage-part "stop" "end_turn")])))))
+ (testing "a later usage carrying no finish reason leaves an earlier length in place"
+ (is (=? {:type "finish" :finishReason "length"}
+ (last (sse-events [(usage-part "length" "max_tokens")
+ (usage-part nil nil)])))))
+ (testing "a filtered step with a tool call, then a completed OpenAI Responses step, is a normal stop"
+ (let [parts [(usage-part "content-filter" "content_filter")
+ {:type :tool-input :id "call-1" :function "search" :arguments {:query "test"}}
+ (usage-part "stop" "completed")]]
+ (is (nil? (self.core/parts->incomplete-finish-reason parts)))
+ (is (=? {:type "finish" :finishReason "stop"}
+ (last (sse-events parts)))))))
(testing "a turn ending on a terminal tool call is a normal stop, not an incomplete turn"
(is (=? {:type "finish" :finishReason "stop"}
(last (sse-events [(usage-part "tool-calls" "tool_use")])))))
@@ -1385,17 +1405,53 @@
(defn- malformed-tool-input-response
"A reducible LLM stream whose forced tool call streams invalid JSON, so
- `parse-tool-arguments` yields the `{:_raw_arguments ...}` sentinel."
+ `parse-tool-arguments` yields the `{:_raw_arguments ...}` sentinel.
+ `trailing-parts` are appended after it, e.g. a [[usage-part]] carrying a finish reason."
+ [& trailing-parts]
+ (let [chunks (concat [{:type :start :messageId "m1"}
+ {:type :tool-input-start :toolCallId "c1" :toolName "json"}
+ {:type :tool-input-delta :toolCallId "c1" :inputTextDelta "{not valid json"}
+ {:type :tool-input-available :toolCallId "c1" :toolName "json"}]
+ (test-util/parts->aisdk-chunks trailing-parts))]
+ (reify clojure.lang.IReduceInit
+ (reduce [_ rf init]
+ (reduce rf init chunks)))))
+
+(defn- structured-call-error
+ "Run a structured call against whatever `openrouter/openrouter` is currently redefined to, and return the
+ exception it threw. Returns the call's result instead when it did not throw, so a test that expects a
+ failure fails on its assertions rather than propagating."
[]
- (reify clojure.lang.IReduceInit
- (reduce [_ rf init]
- (reduce rf init [{:type :start :messageId "m1"}
- {:type :tool-input-start :toolCallId "c1" :toolName "json"}
- {:type :tool-input-delta :toolCallId "c1" :inputTextDelta "{not valid json"}
- {:type :tool-input-available :toolCallId "c1" :toolName "json"}]))))
+ (try
+ (self/call-llm-structured "openrouter/test-model"
+ [{:role "user" :content "test"}]
+ {:type "object" :properties {:answer {:type "string"}}}
+ 0.3 1024 {:tag "metabot_agent"})
+ (catch clojure.lang.ExceptionInfo e e)))
+
+(defn- text-turn-response
+ "A mocked LLM stream for a turn that answers in text: a `:start` part, one `:text` part per string in
+ `texts`, then `trailing-parts`, e.g. a [[usage-part]]."
+ [texts & trailing-parts]
+ (test-util/mock-llm-response
+ (concat [{:type :start :id "m1"}]
+ (map-indexed (fn [i text] {:type :text :id (str "t" i) :text text}) texts)
+ trailing-parts)))
+
+(def ^:private answer-text "Here you go:\n```json\n{\"answer\": \"42\"}\n```")
+
+(def ^:private more-text "\n\nI could also explain how I got there, step by st")
(deftest call-llm-structured-rejects-malformed-json-test
(llm.tu/with-default-connections
+ (testing "a content-filter finish does not reroute malformed JSON — only a truncation does"
+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)
+ openrouter/openrouter (constantly
+ (malformed-tool-input-response
+ (usage-part "content-filter" "refusal")))]
+ (mt/with-log-level [metabase.metabot.self :fatal]
+ (let [e (structured-call-error)]
+ (is (= "structured-output-invalid" (:error-code (ex-data e))))))))
(testing "malformed tool-call JSON is rejected as an error, not returned as a bogus result"
(mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)
openrouter/openrouter (constantly (malformed-tool-input-response))]
@@ -1412,6 +1468,15 @@
(deftest call-llm-structured-surfaces-provider-error-test
(llm.tu/with-default-connections
+ (testing "with no tool call, a provider :error part outranks an incomplete finish reason"
+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)
+ openrouter/openrouter (constantly
+ (test-util/mock-llm-response
+ [{:type :error :errorText "content policy violation"}
+ (usage-part "length" "max_tokens")]))]
+ (mt/with-log-level [metabase.metabot.self :fatal]
+ (let [e (structured-call-error)]
+ (is (= "llm-stream-error" (:error-code (ex-data e))))))))
(testing "a provider mid-stream :error part surfaces its message, not a generic 'no tool call' error"
(mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)
openrouter/openrouter (constantly
@@ -1481,6 +1546,166 @@
:function "structured_output"
:arguments {:title "From the tool"}})))))))
+(deftest call-llm-structured-incomplete-without-tool-call-test
+ (llm.tu/with-default-connections
+ (testing "a turn that stopped early, with no tool call and no JSON in its text, reports why, not a generic 'no tool call' error"
+ (doseq [[reason raw] [["length" "max_tokens"] ["content-filter" "refusal"]]]
+ (testing reason
+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)
+ openrouter/openrouter (constantly
+ (test-util/mock-llm-response
+ [{:type :start :id "m1"}
+ {:type :text :id "t1" :text "partial answer"}
+ (usage-part reason raw)]))]
+ (let [e (structured-call-error)]
+ (is (instance? clojure.lang.ExceptionInfo e))
+ (is (= "structured-output-incomplete" (:error-code (ex-data e))))
+ (is (= reason (:finish-reason (ex-data e))))
+ (is (= raw (:raw-finish-reason (ex-data e))))
+ (is (not (re-find #"no tool call" (ex-message e)))
+ "the message must distinguish an incomplete turn from a model that simply did not call the tool"))))))))
+
+(deftest call-llm-structured-incomplete-truncated-json-test
+ (llm.tu/with-default-connections
+ (mt/with-log-level [metabase.metabot.self :fatal]
+ (testing "a tool call cut off mid-JSON by a length finish is incomplete, not invalid"
+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)
+ openrouter/openrouter (constantly
+ (malformed-tool-input-response
+ (usage-part "length" "max_tokens")))]
+ (let [e (structured-call-error)]
+ (is (= "structured-output-incomplete" (:error-code (ex-data e))))
+ (is (= "length" (:finish-reason (ex-data e))))
+ (is (= "max_tokens" (:raw-finish-reason (ex-data e)))))))
+ (testing "the truncated tool call outranks an :error part in the same turn"
+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)
+ openrouter/openrouter (constantly
+ (malformed-tool-input-response
+ {:type :error :errorText "provider exploded"}
+ (usage-part "length" "max_tokens")))]
+ (let [e (structured-call-error)]
+ (is (= "structured-output-incomplete" (:error-code (ex-data e))))))))))
+
+(deftest call-llm-structured-incomplete-is-not-retried-test
+ (llm.tu/with-default-connections
+ (testing "an incomplete structured response is not transient, so the provider is called exactly once"
+ (let [calls (atom 0)]
+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)
+ openrouter/openrouter (fn [_opts]
+ (swap! calls inc)
+ (test-util/mock-llm-response
+ [{:type :start :id "m1"}
+ (usage-part "length" "max_tokens")]))]
+ (structured-call-error)
+ (is (= 1 @calls)))))))
+
+(deftest call-llm-structured-text-json-on-early-stop-test
+ (llm.tu/with-default-connections
+ (testing "a text reply with a closed JSON block that matches the schema is used, also after an early stop"
+ (doseq [[reason raw] [["length" "max_tokens"] ["content-filter" "refusal"]]]
+ (testing reason
+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)
+ openrouter/openrouter (constantly
+ (text-turn-response
+ [answer-text more-text]
+ (usage-part reason raw)))]
+ (is (= {:answer "42"} (structured-call-error)))))))))
+
+(deftest call-llm-structured-text-json-logs-finish-reason-test
+ (llm.tu/with-default-connections
+ (testing "a text JSON result after an early stop logs the finish reasons"
+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)
+ openrouter/openrouter (constantly
+ (text-turn-response
+ [answer-text more-text]
+ (usage-part "length" "max_tokens")))]
+ (log.capture/with-log-messages-for-level [messages [metabase.metabot.self :info]]
+ (structured-call-error)
+ (let [msg (some #(when (str/includes? (str (:message %)) "LLM answered in text") (:message %))
+ (messages))]
+ (is (some? msg))
+ (is (re-find #":finish-reason \"?length" (str msg)))
+ (is (re-find #":raw-finish-reason \"?max_tokens" (str msg)))))))))
+
+(defn- empty-tool-call-response
+ "A reducible LLM stream for a turn that answers in `text`, then starts a `json` tool call and stops with a
+ `length` finish after the argument deltas `arg-deltas` (none by default)."
+ [text & arg-deltas]
+ (let [chunks (concat (test-util/parts->aisdk-chunks [{:type :start :id "m1"}
+ {:type :text :id "t1" :text text}])
+ [{:type :tool-input-start :toolCallId "c1" :toolName "json"}]
+ (for [delta arg-deltas]
+ {:type :tool-input-delta :toolCallId "c1" :inputTextDelta delta})
+ (test-util/parts->aisdk-chunks [(usage-part "length" "max_tokens")]))]
+ (reify clojure.lang.IReduceInit
+ (reduce [_ rf init]
+ (reduce rf init chunks)))))
+
+(deftest call-llm-structured-empty-tool-call-on-length-stop-uses-text-json-test
+ (llm.tu/with-default-connections
+ (testing "a tool call cut off before its first argument byte has no arguments, so the text JSON is used"
+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)
+ openrouter/openrouter (constantly (empty-tool-call-response answer-text))]
+ (is (= {:answer "42"} (structured-call-error)))))))
+
+(deftest call-llm-structured-truncated-tool-call-outranks-text-json-test
+ (llm.tu/with-default-connections
+ (testing "a tool call cut off after its first argument byte throws, even when the text holds valid JSON"
+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)
+ openrouter/openrouter (constantly (empty-tool-call-response answer-text "{"))]
+ (is (=? {:error-code "structured-output-incomplete"
+ :finish-reason "length"}
+ (ex-data (structured-call-error))))))))
+
+(deftest call-llm-structured-draft-json-before-unclosed-block-test
+ (llm.tu/with-default-connections
+ (testing "a closed JSON block is used when an unclosed block after it was cut off by a length stop"
+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)
+ openrouter/openrouter (constantly
+ (text-turn-response
+ ["Here you go:\n```json\n{\"answer\": \"draft\"}\n```"
+ "\n\nRevised:\n```json\n{\"answer\": \"fin"]
+ (usage-part "length" "max_tokens")))]
+ (is (= {:answer "draft"} (structured-call-error)))))))
+
+(deftest call-llm-structured-schema-invalid-text-json-on-length-stop-test
+ (llm.tu/with-default-connections
+ (testing "text JSON that does not match the schema is not used, so a length stop reports why"
+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)
+ openrouter/openrouter (constantly
+ (text-turn-response
+ ["Here you go:\n```json\n{\"answer\": 42}\n```" more-text]
+ (usage-part "length" "max_tokens")))]
+ (let [e (structured-call-error)]
+ (is (= "structured-output-incomplete" (:error-code (ex-data e))))
+ (is (= "length" (:finish-reason (ex-data e))))
+ (is (= "max_tokens" (:raw-finish-reason (ex-data e)))))))))
+
+(deftest call-llm-structured-error-part-outranks-text-json-test
+ (llm.tu/with-default-connections
+ (testing "a provider :error part outranks JSON in the text reply"
+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)
+ openrouter/openrouter (constantly
+ (text-turn-response
+ [answer-text]
+ {:type :error :errorText "content policy violation"}
+ (usage-part "length" "max_tokens")))]
+ (mt/with-log-level [metabase.metabot.self :fatal]
+ (let [e (structured-call-error)]
+ (is (= "llm-stream-error" (:error-code (ex-data e))))))))))
+
+(deftest call-llm-structured-unclosed-json-on-length-stop-test
+ (llm.tu/with-default-connections
+ (testing "JSON in an unclosed block is never used, so a length stop reports why"
+ (mt/with-dynamic-fn-redefs [self/retry-delay-ms (constantly 0)
+ openrouter/openrouter (constantly
+ (text-turn-response
+ ["Here you go:\n```json\n{\"answer\": \"4"]
+ (usage-part "length" "max_tokens")))]
+ (let [e (structured-call-error)]
+ (is (= "structured-output-incomplete" (:error-code (ex-data e))))
+ (is (= "length" (:finish-reason (ex-data e)))))))))
+
(deftest call-llm-does-not-replay-after-partial-emission-test
(llm.tu/with-default-connections
(testing "a retryable failure AFTER parts were emitted does not replay the stream (no duplicate output / re-run tools)"
diff --git a/test/metabase/slackbot/channel_test.clj b/test/metabase/slackbot/channel_test.clj
index 5429a803eb7..1c8d7ed458d 100644
--- a/test/metabase/slackbot/channel_test.clj
+++ b/test/metabase/slackbot/channel_test.clj
@@ -212,6 +212,97 @@
(constantly {:ok true :ts "1700000000.000002"}))]
(is (= 1 (count posts))))))
+;;; -------------------------------- BOT-2063: incomplete finish reasons --------------------------------
+
+(defn- channel-post-with-finish-reason!
+ "Drive [[slackbot.channel/send-channel-response]] for a turn that stopped early.
+
+ `answer` is the model's streamed text, or nil when it streamed none; `finish-reason` is what
+ `make-streaming-ai-request` reports. No visualizations, so the posted blocks are only the ones this
+ path builds itself. Returns `{:text .. :blocks ..}` as posted."
+ [answer finish-reason]
+ (let [posts (atom [])]
+ (mt/with-dynamic-fn-redefs [slackbot.client/set-status (constantly {:ok true})
+ slackbot.client/post-thread-reply
+ (fn [_client _message-ctx text & {:keys [blocks]}]
+ (swap! posts conj {:text text :blocks blocks})
+ {:ok true :ts "1700000000.000002"})
+ metabot.persistence/set-response-slack-msg-id! (fn [& _] nil)]
+ (slackbot.channel/send-channel-response
+ {}
+ {:ts "1700000000.000001"}
+ nil
+ {:channel-id "C123"
+ :message-ctx {:channel "C123" :thread_ts "1700000000.000001"}
+ :channel "C123"
+ :thread-ts "1700000000.000001"
+ :auth-info {:team_id "T123"}
+ :thread {:messages []}
+ :bot-user-id "U999"
+ :prompt "hello"
+ :conversation-id conversation-id}
+ {:tool-name->friendly {}
+ :make-streaming-ai-request (fn [& args]
+ (when answer
+ ((:on-text (last args)) answer))
+ {:msg-id 42
+ :external-id "message-external-id"
+ :finish-reason finish-reason})
+ :collect-viz-blocks (constantly {:blocks [] :errors []})
+ :feedback-blocks (constantly feedback-blocks)
+ :post-viz-error! (constantly nil)
+ :make-viz-prefetch-callback (constantly (fn [& _]))
+ :cancel-prefetched-viz! (constantly nil)}))
+ (last @posts)))
+
+(defn- context-texts
+ "The mrkdwn text of every `context` block in `blocks`."
+ [blocks]
+ (for [block blocks
+ :when (= "context" (:type block))
+ element (:elements block)]
+ (:text element)))
+
+(deftest slackbot-channel-finish-reason-notice-test
+ (testing "a truncated answer carries a notice block, and the answer itself is untouched"
+ (let [{:keys [text blocks]} (channel-post-with-finish-reason! "Orders peaked in March." "length")]
+ (is (= ["markdown" "context" "context_actions"] (mapv :type blocks))
+ "the notice rides between the answer and the feedback buttons")
+ (is (= ["_Response from Metabot was cut off because it hit the maximum length_"]
+ (context-texts blocks)))
+ (testing "the notice stays out of `:text`, which `thread->history` replays back to the model"
+ (is (= "Orders peaked in March." text))
+ (is (not (str/includes? text "cut off"))))))
+ (testing "a content-filtered turn with no text keeps the existing fallback copy, plus the notice"
+ (let [{:keys [text blocks]} (channel-post-with-finish-reason! nil "content-filter")]
+ (is (= "I wasn't able to generate a response. Please try again." text))
+ (is (= ["_Response from Metabot was stopped by a content filter. Try rephrasing your question._"]
+ (context-texts blocks)))))
+ (testing "a step-limited turn names the step limit"
+ (let [{:keys [blocks]} (channel-post-with-finish-reason! "Partial answer." "tool-calls")]
+ (is (= ["_Metabot paused after reaching its step limit for this response_"]
+ (context-texts blocks)))))
+ (testing "a turn that ran to a normal stop gets no notice -- the guard for the three above"
+ (let [{:keys [blocks]} (channel-post-with-finish-reason! "Orders peaked in March." nil)]
+ (is (= ["markdown" "context_actions"] (mapv :type blocks)))
+ (is (empty? (context-texts blocks)))))
+ (testing "a reason this build does not know stays silent rather than posting an empty aside"
+ (let [{:keys [blocks]} (channel-post-with-finish-reason! "Orders peaked in March." "from-a-newer-build")]
+ (is (= ["markdown" "context_actions"] (mapv :type blocks))))))
+
+(deftest slackbot-channel-notice-escapes-metabot-name-test
+ (testing "an admin-set Metabot name cannot smuggle Slack markup into the notice"
+ ;; The setter bypasses the feature gate, but the *getter* still returns the default without
+ ;; :ai-controls -- so without this the block would read "Metabot" and prove nothing.
+ (mt/with-premium-features #{:ai-controls}
+ (mt/with-temporary-setting-values [metabot-name "<!channel> & co"]
+ (let [{:keys [blocks]} (channel-post-with-finish-reason! "Orders peaked in March." "length")
+ notices (context-texts blocks)]
+ (is (= ["_Response from &lt;!channel&gt; &amp; co was cut off because it hit the maximum length_"]
+ notices))
+ (is (not (str/includes? (str/join notices) "<!channel>"))
+ "an unescaped <!channel> would notify everyone in the channel"))))))
+
;; Not ^:parallel: `with-prometheus-system!` redefs a process-global var.
(deftest channel-response-undeliverable-metric-test
(mt/with-prometheus-system! [_ system]
diff --git a/test/metabase/slackbot/streaming_test.clj b/test/metabase/slackbot/streaming_test.clj
index a5620aacb4a..42cd3560e00 100644
--- a/test/metabase/slackbot/streaming_test.clj
+++ b/test/metabase/slackbot/streaming_test.clj
@@ -8,6 +8,7 @@
[metabase.metabot.agent.core :as agent]
[metabase.metabot.persistence :as metabot.persistence]
[metabase.metabot.scope :as metabot.scope]
+ [metabase.metabot.self :as metabot.self]
[metabase.metabot.settings :as metabot.settings]
[metabase.premium-features.core :as premium-features]
[metabase.slackbot.client :as slackbot.client]
@@ -619,6 +620,182 @@
(testing "start-turn! received ai-proxy? = false"
(is (=? [{:ai-proxy? false}] @start-opts)))))))))
+;;; -------------------------------- BOT-2063: incomplete finish reasons --------------------------------
+
+(defn- dm-turn-with-parts!
+ "Run a DM turn whose agent loop emits `parts`, with the turn's own persistence stubbed out.
+
+ Returns what the Slack client saw: `:appended` (every chunk of streamed text, joined),
+ `:task-updates` (every non-text chunk appended to the stream), `:blocks` (the finalized
+ `stop-stream` blocks), `:deleted` (the ts of every deleted message) and `:posts` (the text of
+ every posted message)."
+ [parts]
+ (tu/with-slackbot-setup
+ (let [event-body tu/base-dm-event
+ task-updates (atom [])]
+ (tu/with-slackbot-mocks
+ {}
+ (fn [{:keys [append-text-calls stop-stream-calls delete-calls post-calls]}]
+ (mt/with-dynamic-fn-redefs [agent/run-agent-loop
+ (fn [_opts]
+ (reify clojure.lang.IReduceInit
+ (reduce [_ rf init]
+ (reduce rf init parts))))
+ metabot.persistence/start-turn!
+ (fn [& _] {:assistant-msg-id 1 :assistant-external-id "ext"})
+ metabot.persistence/finalize-assistant-turn!
+ (fn [& _] nil)
+ ;; Text goes through the mocked `append-markdown-text`, so this sees
+ ;; only the task updates.
+ slackbot.client/append-stream
+ (fn [_client _channel _stream-ts chunks]
+ (swap! task-updates into chunks)
+ {:ok true})]
+ (mt/client :post 200 "metabot/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)
+ (u/poll {:thunk #(pos? (count @stop-stream-calls))
+ :done? true?
+ :timeout-ms 5000})
+ {:appended (str/join "\n" @append-text-calls)
+ :task-updates @task-updates
+ :blocks (:blocks (first @stop-stream-calls))
+ :deleted (mapv :ts @delete-calls)
+ :posts (mapv :text @post-calls)}))))))
+
+(defn- context-texts
+ "The mrkdwn text of every `context` block in `blocks`."
+ [blocks]
+ (for [block blocks
+ :when (= "context" (:type block))
+ element (:elements block)]
+ (:text element)))
+
+(def ^:private no-response-copy
+ "I wasn't able to generate a response. Please try again.")
+
+(deftest ^:synchronized slackbot-dm-length-reply-has-notice-block-test
+ (testing "a truncated DM reply carries the notice as a block, and persists the reason (AC1, AC6)"
+ (tu/with-slackbot-setup
+ (let [event-body tu/base-dm-event
+ real-finalize (mt/original-fn #'metabot.persistence/finalize-assistant-turn!)
+ assistant-pk (promise)]
+ ;; Real persistence, so the row this asserts on is the one production would write.
+ (mt/with-model-cleanup [:model/MetabotMessage [:model/MetabotConversation :created_at]]
+ (tu/with-slackbot-mocks
+ {}
+ (fn [{:keys [append-text-calls stop-stream-calls]}]
+ (mt/with-dynamic-fn-redefs [agent/run-agent-loop
+ (fn [_opts]
+ (reify clojure.lang.IReduceInit
+ (reduce [_ rf init]
+ (-> init
+ (rf {:type :text :text "Orders peaked in"})
+ (rf {:type :usage :finish-reason "length"
+ :model "m" :usage {:promptTokens 10 :completionTokens 5}})))))
+ metabot.self/context-window-tokens (constantly 15)
+ metabot.persistence/finalize-assistant-turn!
+ (fn [msg-id parts & opts]
+ (deliver assistant-pk msg-id)
+ (apply real-finalize msg-id parts opts))]
+ (mt/client :post 200 "metabot/slack/events"
+ (tu/slack-request-options event-body)
+ event-body)
+ (u/poll {:thunk #(pos? (count @stop-stream-calls))
+ :done? true?
+ :timeout-ms 5000})
+ (let [blocks (:blocks (first @stop-stream-calls))
+ appended (str/join "\n" @append-text-calls)
+ pk (deref assistant-pk 5000 ::timeout)]
+ (testing "the notice is a context block, ahead of the feedback buttons"
+ (is (= ["context" "context_actions"] (mapv :type blocks)))
+ (is (= ["_Response from Metabot was cut off because it hit the maximum length_"]
+ (context-texts blocks))))
+ (testing "and never reaches the streamed text `thread->history` replays to the model"
+ (is (str/includes? appended "Orders peaked in"))
+ (is (not (str/includes? appended "cut off"))))
+ (testing "the turn persists the reason and the full window, and stays a finished turn"
+ (is (not= ::timeout pk))
+ (is (=? {:finish_reason "length" :finished true :context_window_full true}
+ (t2/select-one :model/MetabotMessage :id pk)))))))))))))
+
+(deftest ^:synchronized slackbot-dm-textless-content-filter-reply-test
+ (testing "a filtered reply with no text drops the placeholder, says so, and explains why (AC6, AC7)"
+ (let [{:keys [appended blocks deleted]}
+ (dm-turn-with-parts! [{:type :usage :finish-reason "content-filter"}])]
+ (is (some #{"placeholder-1"} deleted)
+ "the _Thinking..._ placeholder is deleted rather than left standing")
+ (is (not (str/includes? appended no-response-copy))
+ "the copy is a block, never streamed text `thread->history` would replay to the model")
+ (is (= ["_Response from Metabot was stopped by a content filter. Try rephrasing your question._"]
+ (context-texts blocks))
+ "the notice already says why the reply is empty, so the \"couldn't answer\" copy is not stacked on it"))))
+
+(deftest ^:synchronized slackbot-dm-max-iterations-reply-has-notice-block-test
+ (testing "a turn the agent loop stopped at its step limit says so"
+ (let [{:keys [blocks]} (dm-turn-with-parts! [{:type :text :text "Working on it"}
+ {:type :finish :finish-reason :max-iterations}])]
+ (is (= ["_Metabot paused after reaching its step limit for this response_"]
+ (context-texts blocks))))))
+
+(deftest ^:synchronized slackbot-dm-textless-stop-reply-test
+ (testing "a reply with no text and no reason still drops the placeholder and says something (AC7)"
+ (let [{:keys [appended blocks deleted]} (dm-turn-with-parts! [])]
+ (is (some #{"placeholder-1"} deleted))
+ (is (not (str/includes? appended no-response-copy))
+ "the copy is a block, never streamed text `thread->history` would replay to the model")
+ (is (= [(str "_" no-response-copy "_")] (context-texts blocks))
+ "nothing stopped this turn early, so the \"couldn't answer\" copy is the only aside"))))
+
+(deftest ^:synchronized slackbot-dm-whitespace-only-reply-test
+ (testing "a reply of only whitespace is an empty reply, like the channel path, which trims first"
+ (let [{:keys [blocks deleted]} (dm-turn-with-parts! [{:type :text :text "\n\n"}])]
+ (is (some #{"placeholder-1"} deleted))
+ (is (= [(str "_" no-response-copy "_")] (context-texts blocks))
+ "whitespace is invisible in Slack, so the \"couldn't answer\" copy still shows"))))
+
+(deftest ^:synchronized slackbot-dm-textless-reply-with-viz-has-no-fallback-test
+ (testing "a reply that is only a visualization is not an empty reply -- no fallback copy (AC7)"
+ (let [{:keys [appended blocks deleted]}
+ (dm-turn-with-parts! [{:type :data :data-type "static_viz" :data {:entity_id 101}}])]
+ (is (some #{"placeholder-1"} deleted))
+ (is (not (str/includes? appended no-response-copy))
+ "the chart is the answer, so claiming no response would contradict it")
+ (is (= ["section" "image" "context_actions"] (mapv :type blocks))))))
+
+(def ^:private search-tool-parts
+ "A tool call and its result, which the DM path shows as a task update."
+ [{:type :tool-input :id "call-1" :function "search" :arguments {:term_queries ["orders"]}}
+ {:type :tool-output :id "call-1" :result {:output "No results."}}])
+
+(deftest ^:synchronized slackbot-dm-textless-reply-with-tool-progress-has-no-fallback-test
+ (testing "a reply that showed tool progress is not an empty reply -- no fallback copy"
+ (let [{:keys [appended blocks task-updates deleted]} (dm-turn-with-parts! search-tool-parts)]
+ (is (= [["task_update" "in_progress"] ["task_update" "complete"]]
+ (mapv (juxt :type :status) task-updates))
+ "the user watched the tool run")
+ (is (some #{"placeholder-1"} deleted))
+ (is (not (str/includes? appended no-response-copy))
+ "claiming no response would contradict the progress the user just watched")
+ (is (empty? (context-texts blocks))
+ "nor as a block")))
+ (testing "a step-limited turn that only ran tools keeps its notice, still without the fallback"
+ (let [{:keys [appended blocks]}
+ (dm-turn-with-parts! (conj search-tool-parts {:type :finish :finish-reason :max-iterations}))]
+ (is (= ["_Metabot paused after reaching its step limit for this response_"]
+ (context-texts blocks)))
+ (is (not (str/includes? appended no-response-copy))))))
+
+(deftest ^:synchronized slackbot-dm-error-part-suppresses-finish-reason-notice-test
+ (testing "a turn that errored shows only the error copy, never a second notice about the reason"
+ (let [{:keys [appended blocks]}
+ (dm-turn-with-parts! [{:type :error :error {:message "nope"
+ :error-code "permission_denied"}}
+ {:type :usage :finish-reason "length"}])]
+ (is (str/includes? appended "You do not have permission to use the AI assistant."))
+ (is (empty? (context-texts blocks))
+ "the error is the whole story; web reload treats such a turn as errored too"))))
+
;;; ------------------------------------------------ Flush throttle tests ------------------------------------------------
(defn- make-test-callbacks