Skip to content

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

[Metabot] Frontend convo message shape refactor (#80967)

Sloan Sparger2d6db97c9d88
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_analytics/api.clj b/enterprise/backend/src/metabase_enterprise/metabot_analytics/api.clj
index d291baf2458..2a9ae3d8e8e 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_analytics/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_analytics/api.clj
@@ -9,6 +9,7 @@
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.api.routes.common :refer [+auth]]
+ [metabase.metabot.schema :as metabot.schema]
[metabase.metabot.tools :as metabot.tools]
[metabase.request.core :as request]
[metabase.util.malli.schema :as ms]))
@@ -100,11 +101,11 @@
[:updated_at ms/TemporalInstant]])
(def ^:private ConversationMessage
- [:map
- [:id :string]
- [:parent_message_id [:maybe :string]]
- [:role [:enum "user" "agent"]]
- [:type :string]])
+ "A client message plus the parent pointer that threads the conversation — with
+ regenerated replies as siblings — into the tree the detail page walks."
+ [:merge
+ ::metabot.schema/client-message
+ [:map [:parent_message_id [:maybe :string]]]])
(def ^:private ConversationDetail
"Schema for full conversation detail response."
diff --git a/enterprise/backend/src/metabase_enterprise/metabot_analytics/conversations.clj b/enterprise/backend/src/metabase_enterprise/metabot_analytics/conversations.clj
index 75fa4758bad..db12962ae89 100644
--- a/enterprise/backend/src/metabase_enterprise/metabot_analytics/conversations.clj
+++ b/enterprise/backend/src/metabase_enterprise/metabot_analytics/conversations.clj
@@ -133,7 +133,7 @@
:total_tokens (transduce (keep :total_tokens) + 0 all-messages)
:profile_id (some #(when (= :assistant (:role %)) (:profile_id %)) all-messages)
:slack_permalink (slack-permalink conversation)
- :messages (metabot-persistence/messages->flat-messages
+ :messages (metabot-persistence/messages->threaded-client-messages
all-messages {:include-rewound-errors? true})
:queries (analytics.queries/messages->generated-queries all-messages)
:search_count (analytics.queries/count-tool-invocations all-messages "search")
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 7f64288ebde..f76b4b33639 100644
--- a/enterprise/backend/test/metabase_enterprise/metabot_analytics/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/metabot_analytics/api_test.clj
@@ -491,15 +491,20 @@
(is (= 2 (:message_count response)))
(is (= [] (:feedback response)))
(is (= 2 (count (:messages response)))
- "one user prompt + one assistant reply, as flat single-level chat messages")
+ "one user prompt + one assistant reply, as row-level messages")
(let [[user-msg asst-msg] (:messages response)]
- (is (= ["user" "text" "hello"] [(:role user-msg) (:type user-msg) (:message user-msg)]))
+ (is (= ["user" "text" "hello" {:type "done"}]
+ [(:role user-msg)
+ (-> user-msg :parts first :type)
+ (-> user-msg :parts first :message)
+ (:status user-msg)]))
(is (nil? (:parent_message_id user-msg)) "the root prompt has no parent")
(is (not (contains? asst-msg :kept))
"no :kept on the wire; the client derives the current path from sibling order")
- (is (= ["agent" "text"] [(:role asst-msg) (:type asst-msg)]))
+ (is (= ["agent" "text" {:type "done"}]
+ [(:role asst-msg) (-> asst-msg :parts first :type) (:status asst-msg)]))
(is (= (:id user-msg) (:parent_message_id asst-msg))
- "the reply points at its prompt's message id")
+ "the reply points at its prompt's row message id")
(is (string? (:externalId asst-msg)) "the agent message keeps its feedback external id")))
(finally
(delete-conversations! [conversation-id])))))))
@@ -521,7 +526,10 @@
(defn- message-by-text
[messages text]
- (or (some #(when (= text (:message %)) %) messages)
+ (or (some (fn [message]
+ (when (some #(= text (:message %)) (:parts message))
+ message))
+ messages)
(throw (ex-info (str "Message not found: " text) {:text text}))))
(deftest get-conversation-detail-attempts-test
@@ -538,7 +546,8 @@
:data [{:type "text" :text "kept answer"}]})
(let [{:keys [messages total_tokens message_count]} (fetch)
[prompt & attempts] messages]
- (is (= ["first try" "second try" "kept answer"] (map :message attempts)))
+ (is (= ["first try" "second try" "kept answer"]
+ (map #(-> % :parts first :message) attempts)))
(is (every? #(= (:id prompt) (:parent_message_id %)) attempts))
(is (= [62 4] [total_tokens message_count])))))))
@@ -590,7 +599,8 @@
(insert! {:role "assistant" :profile-id "internal" :total-tokens 0 :data [] :finished nil})
(let [{:keys [messages message_count]} (fetch)]
(is (= ["user" "agent"] (map :role messages)))
- (is (= "turn_in_progress" (:type (second messages))))
+ (is (= {:type "in_progress"} (:status (second messages))))
+ (is (= [] (:parts (second messages))))
(is (= 2 message_count)))))))
(deftest get-conversation-detail-feedback-on-discarded-attempt-test
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx
index 008889bcb7c..4c5ef899827 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.tsx
@@ -4,18 +4,16 @@ import { Messages } from "metabase/metabot/components/MetabotChat/MetabotChatMes
import { MetabotLongChatNotice } from "metabase/metabot/components/MetabotChat/MetabotLongChatNotice";
import { useMetabotAgent } from "metabase/metabot/hooks";
import { useMetabotReactions } from "metabase/metabot/hooks/use-metabot-reactions";
-import type { MetabotChatMessage } from "metabase/metabot/state";
+import {
+ type MetabotMessagePart,
+ isGeneratedCardPart,
+} from "metabase/metabot/state";
import { Stack } from "metabase/ui";
import S from "./MetabotQuestion.module.css";
-const isQuestionNavigationMessage = (message: MetabotChatMessage) =>
- message.type === "data_part" &&
- message.part.type === "data-generated_entity" &&
- message.part.data.type === "card";
-
-const isHiddenInEmbedding = (message: MetabotChatMessage) =>
- message.type === "chain_of_thought";
+const isHiddenInEmbedding = (part: MetabotMessagePart) =>
+ part.type === "chain_of_thought";
const AGENT_ID = "omnibot";
@@ -27,15 +25,20 @@ export function MetabotChatHistory() {
const chatMessages = useMemo(
() =>
- messages.filter(
- (message) =>
- !isQuestionNavigationMessage(message) &&
- !isHiddenInEmbedding(message),
- ),
+ messages.map((message) => ({
+ ...message,
+ parts: message.parts.filter(
+ (part) => !isGeneratedCardPart(part) && !isHiddenInEmbedding(part),
+ ),
+ })),
[messages],
);
- const hasMessages = chatMessages.length > 0;
+ const messagePartCount = useMemo(
+ () => chatMessages.reduce((count, msg) => count + msg.parts.length, 0),
+ [chatMessages],
+ );
+ const hasMessages = messagePartCount > 0;
// Auto-scroll to bottom when new messages are received
useEffect(() => {
@@ -43,7 +46,7 @@ export function MetabotChatHistory() {
scrollContainerRef.current.scrollTop =
scrollContainerRef.current.scrollHeight;
}
- }, [chatMessages.length, metabot.isDoingScience]);
+ }, [messagePartCount, metabot.isDoingScience]);
return (
<Stack
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.unit.spec.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.unit.spec.tsx
index 2322e2285f5..22ef4bce815 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.unit.spec.tsx
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/MetabotChatHistory.unit.spec.tsx
@@ -2,7 +2,7 @@ import { assocIn } from "icepick";
import { act, screen } from "__support__/ui";
import { metabotActions } from "metabase/metabot/state";
-import type { MetabotChatMessage } from "metabase/metabot/state/types";
+import type { MetabotMessagePart } from "metabase/metabot/state/types";
import {
createTestMetabotState,
setup,
@@ -11,11 +11,16 @@ import {
import { MetabotChatHistory } from "./MetabotChatHistory";
-const makeVisibleState = (messages: MetabotChatMessage[]) =>
+const makeVisibleState = (parts: MetabotMessagePart[]) =>
assocIn(
assocIn(createTestMetabotState(), ["agents", "omnibot", "visible"], true),
["conversations", testConversationId("omnibot"), "messages"],
- messages,
+ parts.map((part, index) => ({
+ id: `message-${index}`,
+ role: part.role,
+ parts: [part],
+ status: { type: "done" },
+ })),
);
describe("MetabotChatHistory", () => {
@@ -47,12 +52,18 @@ describe("MetabotChatHistory", () => {
).not.toBeInTheDocument();
});
- it("should not render generated_entity card data_part messages in the message list", () => {
+ it("does not render an agent message for a card-only reply", () => {
setup({
ui: <MetabotChatHistory />,
metabotInitialState: makeVisibleState([
{
- id: "1",
+ id: "prompt",
+ role: "user",
+ type: "text",
+ message: "Show me orders",
+ },
+ {
+ id: "card",
role: "agent",
type: "data_part",
part: {
@@ -76,9 +87,8 @@ describe("MetabotChatHistory", () => {
]),
});
- expect(
- screen.queryByTestId("metabot-chat-message"),
- ).not.toBeInTheDocument();
+ expect(screen.getByText("Show me orders")).toBeInTheDocument();
+ expect(screen.getAllByTestId("metabot-chat-message")).toHaveLength(1);
});
it("should not render chain_of_thought messages (app-only reasoning UI)", () => {
@@ -90,6 +100,7 @@ describe("MetabotChatHistory", () => {
role: "agent",
type: "chain_of_thought",
steps: [{ kind: "reasoning", text: "Let me think about this" }],
+ finished: true,
},
]),
});
diff --git a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.tsx b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.tsx
index b04686bd53c..a82776eccce 100644
--- a/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.tsx
+++ b/enterprise/frontend/src/embedding-sdk-ee/metabot/hooks/use-metabot.tsx
@@ -17,10 +17,13 @@ import type {
import { useMetabotAgent } from "metabase/metabot/hooks";
import { useMetabotReactions } from "metabase/metabot/hooks/use-metabot-reactions";
import {
+ type MetabotGeneratedCardPart,
+ type MetabotMessagePart,
getFinalChartMessageIdsPerTurn,
getMetabotConversationId,
+ isGeneratedCardPart,
+ isTextPart,
} from "metabase/metabot/state";
-import type { MetabotChatMessage } from "metabase/metabot/state/types";
import { useSelector } from "metabase/redux";
import * as Urls from "metabase/urls";
@@ -94,9 +97,10 @@ export const useMetabot = (): UseMetabotResult => {
const messages = useMemo<MetabotMessage[]>(
() =>
agent.messages
- .filter((message) => isPublicMessage(message, finalChartIds))
- .map((message) =>
- mapMessage(message, chartComponentsCache.current, authConfig),
+ .flatMap((message) => message.parts)
+ .filter((part) => isPublicPart(part, finalChartIds))
+ .map((part) =>
+ mapMessage(part, chartComponentsCache.current, authConfig),
),
[agent.messages, finalChartIds, authConfig],
);
@@ -104,10 +108,13 @@ export const useMetabot = (): UseMetabotResult => {
const errorMessages = useMemo<SdkMetabotErrorMessage[]>(
() =>
agent.messages
- .filter((m) => m.role === "agent" && m.type === "turn_errored")
+ .filter((m) => m.status.type === "errored")
.map(
(m) =>
- m.display ?? { type: "message", message: t`Something went wrong` },
+ (m.status.type === "errored" && m.status.display) || {
+ type: "message",
+ message: t`Something went wrong`,
+ },
),
[agent.messages],
);
@@ -167,20 +174,14 @@ function getCachedChartComponent(
// see the comment on `MetabotMessage` in `embedding-sdk-bundle/types/metabot.ts`
// for the full rationale.
type PublicChatMessage =
- | Extract<MetabotChatMessage, { type: "text" }>
- | (Extract<MetabotChatMessage, { type: "data_part" }> & {
- part: { type: "data-generated_entity"; data: { type: "card" } };
- });
+ | Extract<MetabotMessagePart, { type: "text" }>
+ | MetabotGeneratedCardPart;
-const isPublicMessage = (
- message: MetabotChatMessage,
+const isPublicPart = (
+ part: MetabotMessagePart,
finalChartIds: Set<string>,
-): message is PublicChatMessage =>
- message.type === "text" ||
- (message.type === "data_part" &&
- message.part.type === "data-generated_entity" &&
- message.part.data.type === "card" &&
- finalChartIds.has(message.id));
+): part is PublicChatMessage =>
+ isTextPart(part) || (isGeneratedCardPart(part) && finalChartIds.has(part.id));
const mapMessage = (
message: PublicChatMessage,
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 ee518f36dec..e69094ad0f4 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
@@ -11,6 +11,7 @@ import {
lastReqBody,
mockAgentEndpoint,
setup,
+ startRequestlessAgentTurn,
testConversationId,
whoIsYourFavoriteResponse,
} from "metabase/metabot/tests/utils";
@@ -35,11 +36,30 @@ const makeCard = (id: string, sourceTable = 1): GeneratedCard => ({
const conversationId = testConversationId("omnibot");
+const addAgentMessage = (
+ store: { dispatch: (action: unknown) => unknown },
+ ...parts: unknown[]
+) => {
+ startRequestlessAgentTurn(store, conversationId);
+ parts.forEach((part) =>
+ // `addAgentMessage`/`addUserMessage` in reducer.ts type their payload
+ // as `Omit<UnionType, ...>`. Non-distributive `Omit` collapses the
+ // discriminated union to common keys only, so branch-specific fields
+ // (message, navigateTo, payload, ...) fail excess-property checks
+ // without `as any`. Switching to a DistributiveOmit would unblock
+ // call sites here but surfaces more errors elsewhere (e.g. the
+ // edit_suggestion payload hits the "infinite TS errors" noted in
+ // reducer.ts). Keeping `as any` for now — applies to every dispatch
+ // here.
+ store.dispatch(metabotActions.addAgentMessage(part as any)),
+ );
+};
+
const cardMessage = (id: string, sourceTable = 1) =>
// `addAgentMessage` types its payload with a non-distributive `Omit` that
// collapses the message union to common keys, so the branch-specific `part`
- // field fails excess-property checks (see the fuller note in the
- // "maps agent.text passthrough" test below).
+ // field fails excess-property checks (see the fuller note on `addAgentMessage`
+ // above).
({
conversationId,
type: "data_part",
@@ -252,22 +272,7 @@ describe("useMetabot", () => {
const { store } = setup({ ui: <TestMessages /> });
act(() => {
- store.dispatch(
- // `addAgentMessage`/`addUserMessage` in reducer.ts type their payload
- // as `Omit<UnionType, ...>`. Non-distributive `Omit` collapses the
- // discriminated union to common keys only, so branch-specific fields
- // (message, navigateTo, payload, ...) fail excess-property checks
- // without `as any`. Switching to a DistributiveOmit would unblock
- // call sites here but surfaces more errors elsewhere (e.g. the
- // edit_suggestion payload hits the "infinite TS errors" noted in
- // reducer.ts). Keeping `as any` for now — applies to every dispatch
- // below.
- metabotActions.addAgentMessage({
- conversationId,
- type: "text",
- message: "ok",
- } as any),
- );
+ addAgentMessage(store, { conversationId, type: "text", message: "ok" });
});
const [message] = await readMessages();
@@ -283,7 +288,7 @@ describe("useMetabot", () => {
const { store } = setup({ ui: <TestMessages /> });
act(() => {
- store.dispatch(metabotActions.addAgentMessage(cardMessage("card-1")));
+ addAgentMessage(store, cardMessage("card-1"));
});
const [message] = await readMessages();
@@ -304,18 +309,10 @@ describe("useMetabot", () => {
act(() => {
store.dispatch(metabotActions.setDebugMode(true));
- store.dispatch(
- // Unjustified type cast. FIXME
- metabotActions.addAgentMessage({
- conversationId,
- type: "tool_call",
- name: "fn",
- status: "started",
- } as any),
- );
- store.dispatch(
- // Unjustified type cast. FIXME
- metabotActions.addAgentMessage({
+ addAgentMessage(
+ store,
+ { conversationId, type: "tool_call", name: "fn", status: "started" },
+ {
conversationId,
type: "edit_suggestion",
model: "transform",
@@ -330,11 +327,8 @@ describe("useMetabot", () => {
suggestionId: "s1",
},
},
- } as any),
- );
- store.dispatch(
- // Unjustified type cast. FIXME
- metabotActions.addAgentMessage({
+ },
+ {
conversationId,
type: "todo_list",
payload: [
@@ -345,15 +339,8 @@ describe("useMetabot", () => {
priority: "high",
},
],
- } as any),
- );
- store.dispatch(
- // Unjustified type cast. FIXME
- metabotActions.addAgentMessage({
- conversationId,
- type: "text",
- message: "ok",
- } as any),
+ },
+ { conversationId, type: "text", message: "ok" },
);
});
@@ -379,11 +366,10 @@ describe("useMetabot", () => {
message: "first",
}),
);
- store.dispatch(
- metabotActions.addAgentMessage(cardMessage("card-1A", 1)),
- );
- store.dispatch(
- metabotActions.addAgentMessage(cardMessage("card-1B", 2)),
+ addAgentMessage(
+ store,
+ cardMessage("card-1A", 1),
+ cardMessage("card-1B", 2),
);
store.dispatch(
metabotActions.addUserMessage({
@@ -393,9 +379,7 @@ describe("useMetabot", () => {
message: "second",
}),
);
- store.dispatch(
- metabotActions.addAgentMessage(cardMessage("card-2", 3)),
- );
+ addAgentMessage(store, cardMessage("card-2", 3));
});
const messages = await readMessages();
@@ -490,7 +474,7 @@ describe("useMetabot", () => {
const { store } = setup({ ui: <TestChart /> });
act(() => {
- store.dispatch(metabotActions.addAgentMessage(cardMessage("card-1")));
+ addAgentMessage(store, cardMessage("card-1"));
});
expect(await screen.findByTestId("mock-static-question")).toBeVisible();
@@ -500,7 +484,7 @@ describe("useMetabot", () => {
const { store } = setup({ ui: <TestChart drills /> });
act(() => {
- store.dispatch(metabotActions.addAgentMessage(cardMessage("card-1")));
+ addAgentMessage(store, cardMessage("card-1"));
});
expect(
@@ -533,9 +517,7 @@ describe("useMetabot", () => {
message: "first",
}),
);
- store.dispatch(
- metabotActions.addAgentMessage(cardMessage("card-abc", 1)),
- );
+ addAgentMessage(store, cardMessage("card-abc", 1));
});
await waitFor(() => {
@@ -554,9 +536,7 @@ describe("useMetabot", () => {
message: "second",
}),
);
- store.dispatch(
- metabotActions.addAgentMessage(cardMessage("card-xyz", 2)),
- );
+ addAgentMessage(store, cardMessage("card-xyz", 2));
});
await waitFor(() => {
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationDetailPage/ConversationDetailPage.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationDetailPage/ConversationDetailPage.tsx
index 99b31be3440..d68ea1c0e9c 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationDetailPage/ConversationDetailPage.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationDetailPage/ConversationDetailPage.tsx
@@ -12,12 +12,12 @@ import {
} from "metabase/metabot/components/MetabotChat/MetabotChatMessage";
import { getIssueTypeLabel } from "metabase/metabot/components/MetabotChat/feedback-issue-types";
import { useBranchableMessages } from "metabase/metabot/hooks";
+import { isTextPart } from "metabase/metabot/state";
import type {
- MetabotAgentTextChatMessage,
- MetabotChatMessage,
MetabotDebugToolCallMessage,
+ MetabotMessage,
} from "metabase/metabot/state/types";
-import { normalizeFetchedChatMessages } from "metabase/metabot/utils/normalize-fetched-chat-messages";
+import { convertSlackMessage } from "metabase/metabot/utils/slack-mrkdwn";
import { getMetadata } from "metabase/metadata-store";
import { MonitorMain } from "metabase/monitor/components/MonitorLayout";
import { Sidebar } from "metabase/monitor/components/MonitorLayout/Sidebar";
@@ -45,6 +45,7 @@ import { checkNotNull } from "metabase/utils/types";
import { getUserName } from "metabase/utils/user";
import { useGetMetabotAnalyticsConversationQuery } from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/api";
import type {
+ ConversationDetail,
ConversationFeedback,
GeneratedQuery,
} from "metabase-enterprise/monitor/ai-auditing/metabot-analytics/types";
@@ -55,6 +56,19 @@ import { ConversationHeader } from "./ConversationHeader";
import { ForkBoundary } from "./ForkBoundary";
import { ToolCallDetailsSidebar } from "./ToolCallDetailsSidebar";
+const SLACK_PROFILE_IDS = ["slackbot", "slack"];
+
+function normalizeMessages(conversation: ConversationDetail | undefined) {
+ const messages = conversation?.messages ?? [];
+ if (!SLACK_PROFILE_IDS.includes(conversation?.profile_id ?? "")) {
+ return messages;
+ }
+ return messages.map((message) => ({
+ ...convertSlackMessage(message),
+ parent_message_id: message.parent_message_id,
+ }));
+}
+
export function ConversationDetailPage() {
const params = useParams();
// The route always matches with a :convoId segment.
@@ -91,24 +105,13 @@ export function ConversationDetailPage() {
refetchOnMountOrArgChange: true,
});
- const isSlack =
- conversation?.profile_id === "slackbot" ||
- conversation?.profile_id === "slack";
-
const conversationMessages = useMemo(
- () => conversation?.messages ?? [],
- [conversation?.messages],
- );
-
- const { messages, getExtraActions } = useBranchableMessages(
- conversationMessages,
- { isSlack },
+ () => normalizeMessages(conversation),
+ [conversation],
);
- const feedbackChatMessages = normalizeFetchedChatMessages(
- conversationMessages,
- { isSlack },
- );
+ const { messages, getExtraActions } =
+ useBranchableMessages(conversationMessages);
if (isLoading || error) {
return (
@@ -139,9 +142,7 @@ export function ConversationDetailPage() {
const forkBoundaryMessage = fork_boundary_message_id
? messages.findLast(
- (message) =>
- "externalId" in message &&
- message.externalId === fork_boundary_message_id,
+ (message) => message.externalId === fork_boundary_message_id,
)
: undefined;
@@ -179,7 +180,7 @@ export function ConversationDetailPage() {
<FeedbackCard
key={item.id}
feedback={item}
- chatMessages={feedbackChatMessages}
+ messages={conversationMessages}
conversationId={convoId}
/>
))}
@@ -257,21 +258,21 @@ function StatCard({ label, value }: { label: string; value: string }) {
function FeedbackCard({
feedback,
- chatMessages,
+ messages,
conversationId,
}: {
feedback: ConversationFeedback;
- chatMessages: MetabotChatMessage[];
+ messages: MetabotMessage[];
conversationId: string;
}) {
- const agentResponse = feedback.external_id
- ? chatMessages.find(
- (message): message is MetabotAgentTextChatMessage =>
- message.role === "agent" &&
- message.type === "text" &&
- message.externalId === feedback.external_id,
- )
- : undefined;
+ const agentResponse = useMemo(() => {
+ const message = feedback.external_id
+ ? messages.find(({ externalId }) => externalId === feedback.external_id)
+ : undefined;
+ return message
+ ? { ...message, parts: message.parts.filter(isTextPart) }
+ : undefined;
+ }, [feedback.external_id, messages]);
const submitterName = feedback.user
? getUserName(feedback.user) || null
@@ -301,11 +302,10 @@ function FeedbackCard({
{agentResponse && (
<AgentMessage
message={agentResponse}
- debug
+ debug={false}
readonly
- conversationId={conversationId}
hideActions
- getCopyText={noopGetCopyText}
+ conversationId={conversationId}
submittedFeedback={undefined}
bg="background_page-secondary"
p="lg"
@@ -498,7 +498,3 @@ function NotebookGeneratedQueryCard({
function noopUpdateQuestion(): Promise<void> {
return Promise.resolve();
}
-
-function noopGetCopyText() {
- return "";
-}
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationDetailPage/ConversationDetailPage.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationDetailPage/ConversationDetailPage.unit.spec.tsx
index 2f4a9240e88..a5b35be0940 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationDetailPage/ConversationDetailPage.unit.spec.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationDetailPage/ConversationDetailPage.unit.spec.tsx
@@ -1,6 +1,9 @@
import userEvent from "@testing-library/user-event";
import {
+ createMockMetabotTextPart,
+ createMockMetabotToolCallPart,
+ createMockParentedMessage,
setupGroupsEndpoint,
setupMetabotConversationEndpoint,
setupPermissionMembershipEndpoint,
@@ -25,57 +28,53 @@ jest.mock("metabase/monitor/components/MonitorLayout/Sidebar", () => ({
}));
type ConversationMessage = ConversationDetail["messages"][number];
+type AgentMessagePart = Extract<
+ ConversationMessage["parts"][number],
+ { role: "agent" }
+>;
function userMessage(
id: string,
parentId: string | null,
- message: string,
+ text: string,
): ConversationMessage {
- return {
- id,
- parent_message_id: parentId,
+ return createMockParentedMessage(id, parentId, {
role: "user",
- type: "text",
- message,
- };
+ parts: [{ id: `${id}-text`, role: "user", type: "text", message: text }],
+ });
}
function agentMessage(
id: string,
parentId: string,
- message: string,
+ ...parts: (string | AgentMessagePart)[]
): ConversationMessage {
- return {
- id,
- parent_message_id: parentId,
- role: "agent",
- type: "text",
- message,
+ return createMockParentedMessage(id, parentId, {
externalId: id,
- };
+ parts: parts.map((part, index) =>
+ typeof part === "string"
+ ? createMockMetabotTextPart({
+ id: `${id}-text-${index}`,
+ message: part,
+ })
+ : part,
+ ),
+ });
}
function inProgressMessage(id: string, parentId: string): ConversationMessage {
- return {
- id,
- parent_message_id: parentId,
- role: "agent",
- type: "turn_in_progress",
+ return createMockParentedMessage(id, parentId, {
externalId: id,
- };
+ status: { type: "in_progress" },
+ });
}
-function toolCallMessage(id: string, parentId: string): ConversationMessage {
- return {
- id,
- parent_message_id: parentId,
- role: "agent",
- type: "tool_call",
- name: "search",
- status: "ended",
+function toolCallPart(id: string): AgentMessagePart {
+ return createMockMetabotToolCallPart({
+ id: `${id}-tool-call`,
args: JSON.stringify({ query: "orders" }),
result: JSON.stringify({ count: 3 }),
- };
+ });
}
function createConversation(
@@ -354,8 +353,7 @@ describe("ConversationDetailPage", () => {
setup(
createConversation([
userMessage("u1", null, "search orders"),
- toolCallMessage("t1", "u1"),
- agentMessage("a1", "t1", "found 3 orders"),
+ agentMessage("a1", "u1", toolCallPart("a1"), "found 3 orders"),
]),
);
@@ -383,8 +381,7 @@ describe("ConversationDetailPage", () => {
setup(
createConversation([
userMessage("u1", null, "search orders"),
- toolCallMessage("t1", "u1"),
- agentMessage("a1", "t1", "found 3 orders"),
+ agentMessage("a1", "u1", toolCallPart("a1"), "found 3 orders"),
]),
);
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationDetailPage/ToolCallDetailsSidebar.tsx b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationDetailPage/ToolCallDetailsSidebar.tsx
index 3cb433043ce..4ff97ab4410 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationDetailPage/ToolCallDetailsSidebar.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/components/ConversationDetailPage/ToolCallDetailsSidebar.tsx
@@ -1,7 +1,7 @@
import { useEffect, useId, useRef } from "react";
import { t } from "ttag";
-import { ToolCallDetailsContent } from "metabase/metabot/components/MetabotChat/MetabotAgentToolCallMessage";
+import { ToolCallDetailsContent } from "metabase/metabot/components/MetabotChat/MetabotAgentToolCallPart";
import type { MetabotDebugToolCallMessage } from "metabase/metabot/state";
import { ActionIcon, Badge, Flex, Icon, Stack, Text } from "metabase/ui";
diff --git a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/types.ts b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/types.ts
index 295e3d1a463..381650289b8 100644
--- a/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/types.ts
+++ b/enterprise/frontend/src/metabase-enterprise/monitor/ai-auditing/metabot-analytics/types.ts
@@ -1,5 +1,5 @@
import type { MetabotProfileId } from "metabase/metabot/constants";
-import type { ParentedChatMessage } from "metabase/metabot/utils/message-tree";
+import type { ParentedMessage } from "metabase/metabot/utils/message-tree";
import type {
DatasetQuery,
MetabotFeedback,
@@ -97,7 +97,7 @@ export type ConversationDetail = {
total_tokens: number;
profile_id: MetabotProfileId | null;
slack_permalink: string | null;
- messages: ParentedChatMessage[];
+ messages: ParentedMessage[];
queries: GeneratedQuery[];
search_count: number;
query_count: number;
diff --git a/frontend/src/metabase-types/api/metabot.ts b/frontend/src/metabase-types/api/metabot.ts
index 4fa730878a8..2e3de29fca8 100644
--- a/frontend/src/metabase-types/api/metabot.ts
+++ b/frontend/src/metabase-types/api/metabot.ts
@@ -156,7 +156,7 @@ export type MetabotAgentRequest = {
parent_message_id?: string;
retry_message_id?: string;
user_message_id?: string; // uuid
- assistant_message_id?: string; // uuid
+ assistant_message_id: string; // uuid
metabot_id?: string;
profile_id?: string;
};
diff --git a/frontend/src/metabase/admin/ai/MetabotSettingsPanel.unit.spec.tsx b/frontend/src/metabase/admin/ai/MetabotSettingsPanel.unit.spec.tsx
index 54eee8a1dc3..0deeb6c4435 100644
--- a/frontend/src/metabase/admin/ai/MetabotSettingsPanel.unit.spec.tsx
+++ b/frontend/src/metabase/admin/ai/MetabotSettingsPanel.unit.spec.tsx
@@ -95,7 +95,6 @@ const setup = async (
seedCollections = defaultSeedCollections,
settings = createMockSettings({ "llm-metabot-configured?": true }),
) => {
- mockGetBoundingClientRect();
setupPropertiesEndpoints(settings);
setupSettingsEndpoints([]);
setupMetabotsEndpoints(metabots);
@@ -130,7 +129,9 @@ const setup = async (
},
});
- await screen.findByTestId("metabot-enabled-toggle");
+ await waitFor(() => {
+ expect(screen.getByTestId("metabot-enabled-toggle")).toBeEnabled();
+ });
return view;
};
@@ -162,6 +163,8 @@ const setupContentVerificationPlugin = () => {
};
describe("MetabotSettingsPanel", () => {
+ mockGetBoundingClientRect();
+
afterEach(() => {
reinitialize();
});
diff --git a/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.tsx b/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.tsx
index 3ce6d1322c2..a3e1fe942d2 100644
--- a/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.tsx
+++ b/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.tsx
@@ -22,9 +22,9 @@ import {
} from "metabase/metabot/hooks";
import type {
MetabotAgentDataPartMessage,
- MetabotChatMessage,
MetabotDataPart,
MetabotDebugToolCallMessage,
+ MetabotMessagePart,
} from "metabase/metabot/state";
import { Box, Flex, Stack, Text } from "metabase/ui";
import type { RemoveFromResearchPlanResponse } from "metabase-types/api";
@@ -244,24 +244,24 @@ export function NewExplorationChat({ selection }: NewExplorationChatProps) {
return;
}
- const unprocessedMessages = messages.filter(
- (message) => !processedMessageIdsRef.current.has(message.id),
- );
- for (const message of unprocessedMessages) {
- processedMessageIdsRef.current.add(message.id);
+ const unprocessedParts = messages
+ .flatMap((message) => message.parts)
+ .filter((part) => !processedMessageIdsRef.current.has(part.id));
+ for (const part of unprocessedParts) {
+ processedMessageIdsRef.current.add(part.id);
}
handleResearchPlanUpdateMessages(
- unprocessedMessages.filter(isResearchPlanUpdateMessage),
+ unprocessedParts.filter(isResearchPlanUpdateMessage),
);
handleRemoveFromResearchPlanToolCallMessages(
- unprocessedMessages.filter(isRemoveFromResearchPlanToolCallMessage),
+ unprocessedParts.filter(isRemoveFromResearchPlanToolCallMessage),
);
handleSetExplorationNameToolCallMessages(
- unprocessedMessages.filter(isSetExplorationNameToolCallMessage),
+ unprocessedParts.filter(isSetExplorationNameToolCallMessage),
);
handleSelectExplorationTimelinesToolCallMessages(
- unprocessedMessages.filter(isSelectExplorationTimelinesToolCallMessage),
+ unprocessedParts.filter(isSelectExplorationTimelinesToolCallMessage),
);
}, [
isDoingScience,
@@ -351,7 +351,7 @@ export function NewExplorationChat({ selection }: NewExplorationChatProps) {
}
function isResearchPlanUpdateMessage(
- message: MetabotChatMessage,
+ message: MetabotMessagePart,
): message is ResearchPlanUpdateMessage {
return (
message.role === "agent" &&
@@ -361,7 +361,7 @@ function isResearchPlanUpdateMessage(
}
function isRemoveFromResearchPlanToolCallMessage(
- message: MetabotChatMessage,
+ message: MetabotMessagePart,
): message is MetabotToolCallMessageWithResult {
return (
message.role === "agent" &&
@@ -373,7 +373,7 @@ function isRemoveFromResearchPlanToolCallMessage(
}
function isSetExplorationNameToolCallMessage(
- message: MetabotChatMessage,
+ message: MetabotMessagePart,
): message is MetabotToolCallMessageWithResult {
return (
message.role === "agent" &&
@@ -385,7 +385,7 @@ function isSetExplorationNameToolCallMessage(
}
function isSelectExplorationTimelinesToolCallMessage(
- message: MetabotChatMessage,
+ message: MetabotMessagePart,
): message is MetabotToolCallMessageWithResult {
return (
message.role === "agent" &&
diff --git a/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.unit.spec.tsx b/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.unit.spec.tsx
index 4d2e79bcd0a..56d1558b2ef 100644
--- a/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.unit.spec.tsx
+++ b/frontend/src/metabase/explorations/components/NewExplorationChat/NewExplorationChat.unit.spec.tsx
@@ -12,8 +12,9 @@ import { makeMockSelection } from "metabase/explorations/test-utils";
import { useMetabotAgent } from "metabase/metabot/hooks";
import type {
MetabotAgentDataPartMessage,
- MetabotChatMessage,
MetabotDebugToolCallMessage,
+ MetabotMessage,
+ MetabotMessagePart,
} from "metabase/metabot/state";
import { createMockState } from "metabase/redux/store/mocks";
import type {
@@ -101,7 +102,7 @@ const metricChurn: GetExplorationDataResponse["metrics"][number] = {
dimensions: [customerSegmentDimension],
};
-const userMessage: MetabotChatMessage = {
+const userMessage: MetabotMessagePart = {
id: "user-1",
role: "user",
type: "text",
@@ -179,13 +180,34 @@ const removeFromResearchPlanToolCallMessage: MetabotDebugToolCallMessage = {
}),
};
-const agentMessage: MetabotChatMessage = {
+const agentMessage: MetabotMessagePart = {
id: "agent-1",
role: "agent",
type: "text",
message: "I selected these metrics because they are related to revenue.",
};
+/**
+ * Group the fixture parts the way a stream would: each user prompt is its own
+ * message, and the agent parts that follow belong to one reply.
+ */
+function toMessages(parts: MetabotMessagePart[]): MetabotMessage[] {
+ return parts.reduce<MetabotMessage[]>((messages, part) => {
+ const open = messages.at(-1);
+ if (open && part.role === "agent" && open.role === "agent") {
+ open.parts.push(part);
+ return messages;
+ }
+ messages.push({
+ id: `message-${messages.length}`,
+ role: part.role,
+ parts: [part],
+ status: { type: "done" },
+ });
+ return messages;
+ }, []);
+}
+
function mockMetabotAgentState({
messages,
isDoingScience,
@@ -193,18 +215,19 @@ function mockMetabotAgentState({
submitInput = jest.fn(),
retryMessage = jest.fn(),
}: {
- messages: MetabotChatMessage[];
+ messages: MetabotMessagePart[];
isDoingScience: boolean;
prompt?: string;
submitInput?: jest.Mock;
retryMessage?: jest.Mock;
}) {
+ const groupedMessages = toMessages(messages);
// Unjustified type cast. FIXME
jest.mocked(useMetabotAgent).mockReturnValue({
prompt,
setPrompt: jest.fn(),
- conversation: { messages },
- messages,
+ conversation: { messages: groupedMessages },
+ messages: groupedMessages,
errorMessages: [],
retryMessage,
isDoingScience,
@@ -222,7 +245,7 @@ function setup({
isDoingScience = true,
prompt = "",
}: {
- messages?: MetabotChatMessage[];
+ messages?: MetabotMessagePart[];
isDoingScience?: boolean;
prompt?: string;
} = {}) {
@@ -261,7 +284,7 @@ function setup({
messages,
isDoingScience,
}: {
- messages: MetabotChatMessage[];
+ messages: MetabotMessagePart[];
isDoingScience: boolean;
}) => {
mockMetabotAgentState({
@@ -536,13 +559,13 @@ describe("NewExplorationChat", () => {
it("does not re-apply tool calls that survive a conversation rewind/retry", async () => {
const { selection, rerender } = setup();
- const secondUserMessage: MetabotChatMessage = {
+ const secondUserMessage: MetabotMessagePart = {
id: "user-2",
role: "user",
type: "text",
message: "Remove the churn block",
};
- const secondAgentMessage: MetabotChatMessage = {
+ const secondAgentMessage: MetabotMessagePart = {
id: "agent-2",
role: "agent",
type: "text",
@@ -581,7 +604,7 @@ describe("NewExplorationChat", () => {
id: "tool-call-4-retry",
result: JSON.stringify({ block_ids: ["metric:1"] }),
};
- const retriedSecondAgentMessage: MetabotChatMessage = {
+ const retriedSecondAgentMessage: MetabotMessagePart = {
...secondAgentMessage,
id: "agent-2-retry",
};
diff --git a/frontend/src/metabase/explorations/components/NewExplorationData/NewExplorationData.tsx b/frontend/src/metabase/explorations/components/NewExplorationData/NewExplorationData.tsx
index c0269801896..e4c781e0239 100644
--- a/frontend/src/metabase/explorations/components/NewExplorationData/NewExplorationData.tsx
+++ b/frontend/src/metabase/explorations/components/NewExplorationData/NewExplorationData.tsx
@@ -15,6 +15,7 @@ import type {
ExplorationSelection,
} from "metabase/explorations/hooks";
import { useMetabotAgent } from "metabase/metabot/hooks";
+import { getPromptText } from "metabase/metabot/state";
import { useNavigate } from "metabase/router";
import {
Box,
@@ -116,7 +117,7 @@ export function NewExplorationData({ selection }: NewExplorationDataProps) {
const { messages, isDoingScience } = useMetabotAgent(EXPLORATIONS_AGENT_ID);
const hasUserPrompt = messages.some(
- (message) => message.role === "user" && message.message.trim().length > 0,
+ (message) => message.role === "user" && getPromptText(message).trim(),
);
const canStart = blocks.some(isNonEmptyBlock);
@@ -159,7 +160,7 @@ export function NewExplorationData({ selection }: NewExplorationDataProps) {
hasUserPrompt && useContextualInterestingness
? messages
.filter((message) => message.role === "user")
- .map((message) => message.message)
+ .map(getPromptText)
.join("\n---\n")
: "";
const request = buildCreateExplorationRequest(
diff --git a/frontend/src/metabase/explorations/components/NewExplorationData/NewExplorationData.unit.spec.tsx b/frontend/src/metabase/explorations/components/NewExplorationData/NewExplorationData.unit.spec.tsx
index e27965780a1..a6d230e35db 100644
--- a/frontend/src/metabase/explorations/components/NewExplorationData/NewExplorationData.unit.spec.tsx
+++ b/frontend/src/metabase/explorations/components/NewExplorationData/NewExplorationData.unit.spec.tsx
@@ -71,11 +71,23 @@ function setup({
}: {
blocks?: ExplorationBlock[];
timelines?: Timeline[];
- messages?: { role: string; message: string }[];
+ messages?: { role: "user" | "agent"; message: string }[];
} = {}) {
// Unjustified type cast. FIXME
jest.mocked(useMetabotAgent).mockReturnValue({
- messages,
+ messages: messages.map((message, index) => ({
+ id: `message-${index}`,
+ role: message.role,
+ parts: [
+ {
+ id: `part-${index}`,
+ role: message.role,
+ type: "text",
+ message: message.message,
+ },
+ ],
+ outcome: { type: "done" },
+ })),
} as any);
createExplorationMock.mockReturnValue({
diff --git a/frontend/src/metabase/metabot/api.ts b/frontend/src/metabase/metabot/api.ts
index 0d3294db1ac..b8b9a581c4e 100644
--- a/frontend/src/metabase/metabot/api.ts
+++ b/frontend/src/metabase/metabot/api.ts
@@ -1,5 +1,6 @@
import { Api } from "metabase/api";
import { idTag, invalidateTags, listTag } from "metabase/api/tags";
+import type { MetabotMessage } from "metabase/metabot/state/types";
import type {
Card,
DeleteSuggestedMetabotPromptRequest,
@@ -14,6 +15,7 @@ import type {
MetabotInfo,
MetabotSlackSettings,
MetabotSourceFeedback,
+ MetabotStateContext,
RegenerateSuggestedMetabotPromptsResponse,
SaveMetabotEntityRequest,
SuggestedMetabotPromptsRequest,
@@ -21,7 +23,15 @@ import type {
UserMetabotPermissionsResponse,
} from "metabase-types/api";
-import type { MetabotConversationDetail } from "./utils/normalize-fetched-chat-messages";
+export type MetabotConversationDetail = {
+ conversation_id: string;
+ created_at: string;
+ title: string | null;
+ user_id: number | null;
+ forked_from_conversation_id: string | null;
+ state?: MetabotStateContext;
+ messages: MetabotMessage[];
+};
export const metabotApi = Api.injectEndpoints({
endpoints: (builder) => ({
diff --git a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.unit.spec.tsx
index 2c5bb9e347e..e43c557f0e6 100644
--- a/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotAsk/MetabotAsk.unit.spec.tsx
@@ -1,6 +1,7 @@
import userEvent from "@testing-library/user-event";
import { assocIn } from "icepick";
+import { createMockMetabotTextMessage } from "__support__/server-mocks";
import { screen, waitFor } from "__support__/ui";
import { getMetabotVisible } from "metabase/metabot/state";
import {
@@ -110,12 +111,7 @@ describe("MetabotAsk", () => {
it("shows the conversation history control in the chat header", async () => {
setupMetabotAsk({
metabotInitialState: askConversation("messages", [
- {
- id: "seed-message",
- role: "user",
- type: "text",
- message: "Earlier question",
- },
+ createMockMetabotTextMessage("user", "Earlier question"),
]),
});
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPartMessage.module.css b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPart.module.css
similarity index 100%
rename from frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPartMessage.module.css
rename to frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPart.module.css
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPartMessage.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPart.tsx
similarity index 94%
rename from frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPartMessage.tsx
rename to frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPart.tsx
index 3b43938793d..f42e7d623bf 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPartMessage.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataPart.tsx
@@ -40,31 +40,33 @@ import Styles from "./MetabotChat.module.css";
import { MetabotInlineChart } from "./MetabotInlineChart";
import { MetabotInlineDashboardLink } from "./MetabotInlineDashboardLink";
-type AgentDataPartMessageProps = {
- message: MetabotAgentDataPartMessage;
+type AgentDataPartProps = {
+ dataPart: MetabotAgentDataPartMessage;
+ externalId?: string;
readonly: boolean;
debug: boolean;
conversationId: string;
};
-export const AgentDataPartMessage = ({
- message,
+export const AgentDataPart = ({
+ dataPart,
+ externalId,
readonly,
debug,
conversationId,
-}: AgentDataPartMessageProps) =>
- match(message)
+}: AgentDataPartProps) =>
+ match(dataPart)
.with({ part: { type: "data-todo_list" } }, ({ part }) => (
<AgentTodoListMessage todos={part.data} />
))
- .with({ part: { type: "data-transform_suggestion" } }, (msg) => (
- <AgentSuggestionMessage message={msg} readonly={readonly} />
+ .with({ part: { type: "data-transform_suggestion" } }, (dataPart) => (
+ <AgentSuggestionMessage message={dataPart} readonly={readonly} />
))
.with({ part: { type: "data-navigate_to" } }, ({ part }) => {
const sourcePills = (
<NavigateToTablePills
path={part.data}
- messageId={readonly ? undefined : message.externalId}
+ messageId={readonly ? undefined : externalId}
/>
);
@@ -80,7 +82,7 @@ export const AgentDataPartMessage = ({
<CodeEditTablePills
value={part.data}
buffer={metadata?.codeEditBuffer}
- messageId={readonly ? undefined : message.externalId}
+ messageId={readonly ? undefined : externalId}
/>
);
@@ -103,7 +105,7 @@ export const AgentDataPartMessage = ({
/>
<GeneratedCardTablePills
value={part.data}
- messageId={readonly ? undefined : message.externalId}
+ messageId={readonly ? undefined : externalId}
/>
</Stack>
),
@@ -132,8 +134,8 @@ export const AgentDataPartMessage = ({
.with({ part: { type: "data-research_plan_update" } }, ({ part }) =>
debug ? <DataPartJsonCard type={part.type} value={part.data} /> : null,
)
- .exhaustive((msg: unknown) => {
- console.warn("AgentDataPartMessage received an unexpected value:", msg);
+ .exhaustive((dataPart: unknown) => {
+ console.warn("AgentDataPart received an unexpected value:", dataPart);
return null;
});
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx
index 546f1708f83..380150b7c7c 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx
@@ -45,7 +45,7 @@ import type {
import { useSubmitMetabotSourceFeedbackMutation } from "../../api";
-import S from "./MetabotAgentDataPartMessage.module.css";
+import S from "./MetabotAgentDataPart.module.css";
type DecodedQuery =
| {
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentToolCallMessage.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentToolCallPart.tsx
similarity index 91%
rename from frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentToolCallMessage.tsx
rename to frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentToolCallPart.tsx
index 87d84d657ca..344efb67430 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentToolCallMessage.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentToolCallPart.tsx
@@ -163,17 +163,17 @@ const ToolCallDetailsModal = ({
</Modal>
);
-export const AgentToolCallMessage = ({
- message,
+export const AgentToolCallPart = ({
+ part,
onSelect,
}: {
- message: MetabotDebugToolCallMessage;
- onSelect?: (message: MetabotDebugToolCallMessage) => void;
+ part: MetabotDebugToolCallMessage;
+ onSelect?: (part: MetabotDebugToolCallMessage) => void;
}) => {
const [isModalOpen, { open, close }] = useDisclosure(false);
const clipboard = useClipboard();
- const handleCopy = () => clipboard.copy(JSON.stringify(message, null, 2));
- const handleClick = () => (onSelect ? onSelect(message) : open());
+ const handleCopy = () => clipboard.copy(JSON.stringify(part, null, 2));
+ const handleClick = () => (onSelect ? onSelect(part) : open());
return (
<>
@@ -198,7 +198,7 @@ export const AgentToolCallMessage = ({
>
<Flex align="center">
<Icon name="gear" c="text-secondary" mr="sm" />
- <Text fw="bold">{message.name}</Text>
+ <Text fw="bold">{part.name}</Text>
</Flex>
<Flex align="center" gap="xxs" className={Styles.agentPartActions}>
<Tooltip label={clipboard.copied ? t`Copied!` : t`Copy`}>
@@ -216,9 +216,7 @@ export const AgentToolCallMessage = ({
</Tooltip>
</Flex>
</Flex>
- {isModalOpen && (
- <ToolCallDetailsModal message={message} onClose={close} />
- )}
+ {isModalOpen && <ToolCallDetailsModal message={part} onClose={close} />}
</>
);
};
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentToolCallMessage.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentToolCallPart.unit.spec.tsx
similarity index 96%
rename from frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentToolCallMessage.unit.spec.tsx
rename to frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentToolCallPart.unit.spec.tsx
index c5e72784260..90810ae1542 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentToolCallMessage.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentToolCallPart.unit.spec.tsx
@@ -3,7 +3,7 @@ import userEvent from "@testing-library/user-event";
import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
import type { MetabotDebugToolCallMessage } from "metabase/metabot/state";
-import { AgentToolCallMessage } from "./MetabotAgentToolCallMessage";
+import { AgentToolCallPart } from "./MetabotAgentToolCallPart";
const createMockToolCall = (
overrides: Partial<MetabotDebugToolCallMessage> = {},
@@ -25,13 +25,11 @@ const setup = ({
message?: MetabotDebugToolCallMessage;
onSelect?: (message: MetabotDebugToolCallMessage) => void;
} = {}) => {
- renderWithProviders(
- <AgentToolCallMessage message={message} onSelect={onSelect} />,
- );
+ renderWithProviders(<AgentToolCallPart part={message} onSelect={onSelect} />);
return { message };
};
-describe("AgentToolCallMessage", () => {
+describe("AgentToolCallPart", () => {
describe("without onSelect (normal Metabot chat)", () => {
it("opens the details modal on click", async () => {
const { message } = setup();
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotChainOfThought.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotChainOfThought.tsx
index 397362e8f48..768fe314513 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotChainOfThought.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotChainOfThought.tsx
@@ -8,6 +8,7 @@ import type { MetabotAgentChainOfThoughtMessage } from "metabase/metabot/state";
import { Collapse, Icon, Stack, Text, UnstyledButton } from "metabase/ui";
import S from "./MetabotChainOfThought.module.css";
+import { MetabotToolProgress } from "./MetabotToolProgress";
import { ReasoningStep } from "./ReasoningStep";
import { ResourceGroupStep, ToolStep } from "./ToolStep";
import { useAutoCollapseOnSettle, useMeteredLabel, useNow } from "./hooks";
@@ -21,33 +22,45 @@ import {
soleReasoningStep,
} from "./utils";
+type MetabotChainOfThoughtProps = {
+ part: MetabotAgentChainOfThoughtMessage;
+ supportsReasoning?: boolean;
+};
+
export const MetabotChainOfThought = ({
- message,
- isStreaming,
-}: {
- message: MetabotAgentChainOfThoughtMessage;
- isStreaming: boolean;
-}) => {
+ part,
+ supportsReasoning = true,
+}: MetabotChainOfThoughtProps) => {
+ if (!supportsReasoning) {
+ return <MetabotToolProgress part={part} />;
+ }
+ return <ChainOfThought part={part} />;
+};
+
+const ChainOfThought = ({
+ part,
+}: Omit<MetabotChainOfThoughtProps, "supportsReasoning">) => {
+ const isStreaming = !part.finished;
const { open, toggle } = useAutoCollapseOnSettle(isStreaming);
const now = useNow(isStreaming);
- const preview = useMeteredLabel(latestPreviewLabel(message.steps), !open);
+ const preview = useMeteredLabel(latestPreviewLabel(part.steps), !open);
- const renderableItems = buildDisplayItems(message.steps);
+ const renderableItems = buildDisplayItems(part.steps);
if (!isStreaming && renderableItems.length === 0) {
return null;
}
const durationMs =
- message.startedAtMs != null && message.endedAtMs != null
- ? message.endedAtMs - message.startedAtMs
+ part.startedAtMs != null && part.endedAtMs != null
+ ? part.endedAtMs - part.startedAtMs
: undefined;
- const thinkingOnly = !message.steps.some(
+ const thinkingOnly = !part.steps.some(
(step) => isToolStep(step) && isRenderableStep(step),
);
- const activeIndex = message.steps.reduce(
+ const activeIndex = part.steps.reduce(
(acc, step, i) => (isRenderableStep(step) ? i : acc),
-1,
);
@@ -58,10 +71,10 @@ export const MetabotChainOfThought = ({
: settledHeader(durationMs, thinkingOnly);
const stepReasoningLabel = (index: number): string => {
- const start = message.steps[index].startedAtMs;
+ const start = part.steps[index].startedAtMs;
const end =
- message.steps[index + 1]?.startedAtMs ??
- message.endedAtMs ??
+ part.steps[index + 1]?.startedAtMs ??
+ part.endedAtMs ??
(isStreaming ? now : undefined);
return reasoningLabel(
start != null && end != null ? end - start : undefined,
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotChainOfThought.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotChainOfThought.unit.spec.tsx
index 832fb7df8cd..b036ba67ebe 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotChainOfThought.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotChainOfThought.unit.spec.tsx
@@ -17,6 +17,7 @@ const chain = (
role: "agent",
type: "chain_of_thought",
steps: [],
+ finished: false,
...overrides,
});
@@ -31,7 +32,7 @@ const setup = (
createMockDashboard({ id: 123, name: "Orders" }),
);
return renderWithProviders(
- <MetabotChainOfThought message={message} isStreaming={isStreaming} />,
+ <MetabotChainOfThought part={{ ...message, finished: !isStreaming }} />,
{ storeInitialState: createMockState({ settings }) },
);
};
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotToolProgress.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotToolProgress.tsx
index 2fad3146520..4aa11452491 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotToolProgress.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotToolProgress.tsx
@@ -10,21 +10,19 @@ import { ResourceGroupStep, ToolStep } from "./ToolStep";
import { buildDisplayItems, isRenderableStep } from "./utils";
export const MetabotToolProgress = ({
- message,
- isStreaming,
+ part,
}: {
- message: MetabotAgentChainOfThoughtMessage;
- isStreaming: boolean;
+ part: MetabotAgentChainOfThoughtMessage;
}) => {
- if (!isStreaming) {
+ if (part.finished) {
return null;
}
- const activeIndex = message.steps.findLastIndex(isRenderableStep);
+ const activeIndex = part.steps.findLastIndex(isRenderableStep);
return (
<Stack gap="0.5rem" data-testid="metabot-tool-progress">
- {buildDisplayItems(message.steps).map((item) =>
+ {buildDisplayItems(part.steps).map((item) =>
match(item)
.with({ kind: "resourceGroup" }, ({ steps, index }) => (
<div
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotToolProgress.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotToolProgress.unit.spec.tsx
index 0b865a508a9..c8da01fec84 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotToolProgress.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChainOfThought/MetabotToolProgress.unit.spec.tsx
@@ -19,13 +19,13 @@ const setupToolProgress = (steps: MetabotChainStep[], isStreaming = true) =>
setup({
ui: (
<MetabotToolProgress
- message={{
+ part={{
id: "chain-1",
role: "agent",
type: "chain_of_thought",
steps,
+ finished: !isStreaming,
}}
- isStreaming={isStreaming}
/>
),
});
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatMessage.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatMessage.tsx
index 082585682e8..f6785ef30dc 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatMessage.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotChatMessage.tsx
@@ -8,19 +8,19 @@ import { t } from "ttag";
import { useToast } from "metabase/common/hooks";
import { MetabotManagedProviderLimitActions } from "metabase/metabot/components/MetabotManagedProviderLimit";
import {
- type MetabotAgentChatMessage,
type MetabotAgentDataPartMessage,
type MetabotAgentId,
- type MetabotAgentTextChatMessage,
+ type MetabotAgentTurnDisplayError,
type MetabotAgentTurnError,
- type MetabotAgentTurnErroredMessage,
- type MetabotAgentTurnIncompleteMessage,
- type MetabotChatMessage,
type MetabotDataPart,
type MetabotDebugToolCallMessage,
- type MetabotUserChatMessage,
+ type MetabotIncompleteFinishReason,
+ type MetabotMessage,
+ type MetabotMessagePart,
+ type MetabotMessageStatus,
forkConversation,
isChainOfThoughtMessage,
+ isTextPart,
} from "metabase/metabot/state";
import { useDispatch } from "metabase/redux";
import { useSetting } from "metabase/settings";
@@ -41,12 +41,9 @@ import type { IconName, MetabotFeedback } from "metabase-types/api";
import { useSubmitMetabotFeedbackMutation } from "../../api";
import { AIMarkdown } from "../AIMarkdown/AIMarkdown";
-import { AgentDataPartMessage } from "./MetabotAgentDataPartMessage";
-import { AgentToolCallMessage } from "./MetabotAgentToolCallMessage";
-import {
- MetabotChainOfThought,
- MetabotToolProgress,
-} from "./MetabotChainOfThought";
+import { AgentDataPart } from "./MetabotAgentDataPart";
+import { AgentToolCallPart } from "./MetabotAgentToolCallPart";
+import { MetabotChainOfThought } from "./MetabotChainOfThought";
import Styles from "./MetabotChat.module.css";
import { MetabotFeedbackModal } from "./MetabotFeedbackModal";
@@ -63,43 +60,39 @@ const isUserVisibleDataPart = (part: MetabotDataPart): boolean =>
.with({ type: "data-research_plan_update" }, () => false)
.exhaustive();
-const isUserVisibleDataPartMessage = (
- message: MetabotAgentDataPartMessage,
+const isUserVisibleAgentDataPart = (
+ part: MetabotAgentDataPartMessage,
): boolean =>
- match(message)
+ match(part)
.with({ part: { type: "data-code_edit" } }, ({ metadata }) => {
return metadata?.codeEditBuffer?.source.database_id != null;
})
.otherwise(({ part }) => isUserVisibleDataPart(part));
-const isUserVisibleMessage = (message: MetabotChatMessage): boolean =>
- match(message)
+const isUserVisiblePart = (part: MetabotMessagePart): boolean =>
+ match(part)
.with({ type: "text" }, () => true)
- .with({ type: "data_part" }, (message) =>
- isUserVisibleDataPartMessage(message),
- )
+ .with({ type: "data_part" }, (part) => isUserVisibleAgentDataPart(part))
.with({ type: "tool_call" }, () => false)
.with({ type: "chain_of_thought" }, () => true)
- .with({ type: "turn_aborted" }, () => true)
- .with({ type: "turn_incomplete" }, () => true)
- .with({ type: "turn_errored" }, () => true)
- .with({ type: "turn_in_progress" }, () => false)
.exhaustive();
-const isConversationContent = (message: MetabotChatMessage) =>
- !isChainOfThoughtMessage(message) && message.type !== "tool_call";
-
-interface BaseMessageProps extends Omit<FlexProps, "onCopy"> {
- message: MetabotChatMessage;
- hideActions: boolean;
-}
+const useMessageText = (message: MetabotMessage) =>
+ useMemo(
+ () =>
+ message.parts
+ .filter(isTextPart)
+ .map((part) => part.message)
+ .join("\n\n"),
+ [message.parts],
+ );
-export const MessageContainer = ({
+export const PartContainer = ({
chatRole,
className,
...props
}: FlexProps & {
- chatRole: MetabotChatMessage["role"];
+ chatRole: MetabotMessage["role"];
}) => (
<Flex
className={cx(
@@ -115,8 +108,29 @@ export const MessageContainer = ({
/>
);
-interface UserMessageProps extends Omit<BaseMessageProps, "message"> {
- message: MetabotUserChatMessage;
+const CopyAction = ({ text }: { text: string }) => {
+ const clipboard = useClipboard({ timeout: 2000 });
+
+ if (!text) {
+ return null;
+ }
+
+ return (
+ <Tooltip label={clipboard.copied ? t`Copied!` : t`Copy`}>
+ <ActionIcon
+ h="sm"
+ data-testid="metabot-chat-message-copy"
+ onClick={() => clipboard.copy(text)}
+ >
+ <Icon name="copy" size="1rem" />
+ </ActionIcon>
+ </Tooltip>
+ );
+};
+
+interface UserMessageProps extends Omit<FlexProps, "onCopy"> {
+ message: MetabotMessage;
+ hideActions: boolean;
extraActions?: ReactNode;
}
@@ -127,34 +141,28 @@ export const UserMessage = ({
extraActions,
...props
}: UserMessageProps) => {
- const clipboard = useClipboard({ timeout: 2000 });
+ const text = useMessageText(message);
return (
- <MessageContainer chatRole={message.role} {...props}>
- {message.type === "text" && (
+ <PartContainer
+ chatRole="user"
+ data-testid="metabot-chat-message"
+ {...props}
+ >
+ {text && (
<AIMarkdown
className={cx(Styles.message, Styles.messageUser)}
singleNewlinesAreParagraphs
>
- {message.message}
+ {text}
</AIMarkdown>
)}
<Flex className={Styles.messageActions}>
- {!hideActions && (
- <Tooltip label={clipboard.copied ? t`Copied!` : t`Copy`}>
- <ActionIcon
- h="sm"
- data-testid="metabot-chat-message-copy"
- onClick={() => clipboard.copy(message.message)}
- >
- <Icon name="copy" size="1rem" />
- </ActionIcon>
- </Tooltip>
- )}
+ {!hideActions && <CopyAction text={text} />}
{extraActions}
</Flex>
- </MessageContainer>
+ </PartContainer>
);
};
@@ -188,40 +196,187 @@ const FeedbackButton = forwardRef<HTMLButtonElement, FeedbackButtonProps>(
},
);
-interface AgentMessageProps extends Omit<BaseMessageProps, "message"> {
- message: MetabotAgentChatMessage;
+type AgentPartProps = {
+ part: MetabotMessagePart;
+ externalId?: string;
+ debug: boolean;
+ readonly: boolean;
+ conversationId: string;
+ isStreaming: boolean;
+ supportsReasoning: boolean;
+ onInternalLinkClick?: (link: string) => void;
+ onToolCallSelect?: (part: MetabotDebugToolCallMessage) => void;
+};
+
+const AgentPart = ({
+ part,
+ externalId,
+ debug,
+ readonly,
+ conversationId,
+ isStreaming,
+ supportsReasoning,
+ onInternalLinkClick,
+ onToolCallSelect,
+}: AgentPartProps) =>
+ match(part)
+ .with({ type: "text" }, (p) => (
+ <AIMarkdown
+ className={Styles.message}
+ onInternalLinkClick={onInternalLinkClick}
+ isStreaming={isStreaming}
+ >
+ {p.message}
+ </AIMarkdown>
+ ))
+ .with({ type: "data_part" }, (p) => (
+ <AgentDataPart
+ dataPart={p}
+ externalId={externalId}
+ debug={debug}
+ readonly={readonly}
+ conversationId={conversationId}
+ />
+ ))
+ .with({ type: "tool_call" }, (p) => (
+ <AgentToolCallPart part={p} onSelect={onToolCallSelect} />
+ ))
+ .with({ type: "chain_of_thought" }, (p) => (
+ <MetabotChainOfThought part={p} supportsReasoning={supportsReasoning} />
+ ))
+ .exhaustive();
+
+interface AgentMessageProps extends Omit<FlexProps, "onCopy"> {
+ message: MetabotMessage;
debug: boolean;
readonly: boolean;
conversationId: string;
- onRetry?: (messageId: string) => void;
+ onRetry?: () => void;
onContinue?: (resumePrompt: string) => void;
onRefreshConversation?: () => void;
- getCopyText: () => string;
setFeedbackMessage?: (data: { messageId: string; positive: boolean }) => void;
submittedFeedback: "positive" | "negative" | undefined;
onInternalLinkClick?: (link: string) => void;
+ hideActions?: boolean;
extraActions?: ReactNode;
isStreaming?: boolean;
supportsReasoning?: boolean;
onFork?: (messageId: string) => void;
isForking?: boolean;
- onToolCallSelect?: (message: MetabotDebugToolCallMessage) => void;
+ onToolCallSelect?: (part: MetabotDebugToolCallMessage) => void;
}
+type MessageActionsProps = {
+ message: MetabotMessage;
+ canGiveFeedback: boolean;
+ canFork: boolean;
+ isForking?: boolean;
+ submittedFeedback: "positive" | "negative" | undefined;
+ setFeedbackMessage?: (data: { messageId: string; positive: boolean }) => void;
+ onRetry?: () => void;
+ onFork?: (messageId: string) => void;
+ extraActions?: ReactNode;
+};
+
+const MessageActions = ({
+ message,
+ canGiveFeedback,
+ canFork,
+ isForking,
+ submittedFeedback,
+ setFeedbackMessage,
+ onRetry,
+ onFork,
+ extraActions,
+}: MessageActionsProps) => {
+ const messageId = message.externalId ?? "";
+ const text = useMessageText(message);
+ const actions: ReactNode[] = [];
+
+ if (text) {
+ actions.push(<CopyAction key="copy" text={text} />);
+ }
+
+ if (canGiveFeedback && setFeedbackMessage) {
+ actions.push(
+ <Tooltip key="positive-feedback" label={t`Give positive feedback`}>
+ <FeedbackButton
+ data-testid="metabot-chat-message-thumbs-up"
+ icon="thumbs_up"
+ hasBeenClicked={submittedFeedback === "positive"}
+ disabled={!!submittedFeedback}
+ onClick={() => setFeedbackMessage({ messageId, positive: true })}
+ />
+ </Tooltip>,
+ <Tooltip key="negative-feedback" label={t`Give negative feedback`}>
+ <FeedbackButton
+ data-testid="metabot-chat-message-thumbs-down"
+ icon="thumbs_down"
+ hasBeenClicked={submittedFeedback === "negative"}
+ disabled={!!submittedFeedback}
+ onClick={() => setFeedbackMessage({ messageId, positive: false })}
+ />
+ </Tooltip>,
+ );
+ }
+
+ if (onRetry) {
+ actions.push(
+ <Tooltip key="retry" label={t`Retry`}>
+ <ActionIcon
+ onClick={onRetry}
+ h="sm"
+ data-testid="metabot-chat-message-retry"
+ >
+ <Icon name="revert" size="1rem" />
+ </ActionIcon>
+ </Tooltip>,
+ );
+ }
+
+ if (extraActions) {
+ actions.push(<Fragment key="extra-actions">{extraActions}</Fragment>);
+ }
+
+ if (canFork && onFork) {
+ actions.push(
+ <Tooltip key="fork" label={t`Fork conversation`}>
+ <ActionIcon
+ h="sm"
+ data-testid="metabot-chat-message-fork"
+ loading={isForking}
+ disabled={isForking}
+ onClick={() => onFork(messageId)}
+ >
+ <Icon name="git_branch" size="1rem" />
+ </ActionIcon>
+ </Tooltip>,
+ );
+ }
+
+ if (actions.length === 0) {
+ return null;
+ }
+
+ return (
+ <Flex className={Styles.messageActions} align="center">
+ {actions}
+ </Flex>
+ );
+};
+
export const AgentMessage = ({
message,
- className,
debug,
readonly,
conversationId,
- getCopyText,
onRetry,
onContinue,
onRefreshConversation,
setFeedbackMessage,
submittedFeedback,
onInternalLinkClick,
- hideActions,
+ hideActions = false,
extraActions,
isStreaming = false,
supportsReasoning = true,
@@ -230,140 +385,81 @@ export const AgentMessage = ({
onToolCallSelect,
...props
}: AgentMessageProps) => {
- const messageId = "externalId" in message ? (message.externalId ?? "") : "";
- const isInProgress = message.type === "turn_in_progress";
- const isFailedTurn =
- message.type === "turn_errored" || message.type === "turn_aborted";
- const canActOnMessage = !readonly && !isInProgress && !!messageId;
- const canGiveFeedback = canActOnMessage && !!setFeedbackMessage;
- const canFork = canActOnMessage && !isFailedTurn && !!onFork;
- const clipboard = useClipboard({ timeout: 2000 });
- const copyText = getCopyText();
- const canCopy = !isInProgress && copyText.length > 0;
+ const messageId = message.externalId ?? "";
+ const isFailed =
+ message.status.type === "errored" || message.status.type === "aborted";
+ const canActOnMessage = !readonly && !!messageId;
+
+ const visibleParts = debug
+ ? message.parts
+ : message.parts.filter(isUserVisiblePart);
+ // the action bar belongs on the reply's final rendered content, and only once
+ // the reply has stopped growing
+ const actionsIndex =
+ isStreaming || hideActions
+ ? -1
+ : visibleParts.findLastIndex((part) => !isChainOfThoughtMessage(part));
+
+ const actions = (
+ <MessageActions
+ message={message}
+ canGiveFeedback={canActOnMessage && !!setFeedbackMessage}
+ canFork={canActOnMessage && !isFailed}
+ isForking={isForking}
+ submittedFeedback={submittedFeedback}
+ setFeedbackMessage={setFeedbackMessage}
+ onRetry={onRetry}
+ onFork={onFork}
+ extraActions={extraActions}
+ />
+ );
+
+ const status = (
+ <MessageStatus
+ status={message.status}
+ debug={debug}
+ onRetry={onRetry}
+ onContinue={onContinue}
+ onRefreshConversation={onRefreshConversation}
+ />
+ );
+ const needsStatusRow =
+ message.status.type !== "done" &&
+ message.status.type !== "streaming" &&
+ !(message.status.type === "in_progress" && visibleParts.length > 0);
+ const showActionsInStatusRow =
+ needsStatusRow && !isStreaming && !hideActions && actionsIndex === -1;
return (
- <MessageContainer chatRole={message.role} {...props}>
- {match(message)
- .with({ type: "text" }, (m) => (
- <AIMarkdown
- className={Styles.message}
- onInternalLinkClick={onInternalLinkClick}
- isStreaming={isStreaming}
- >
- {m.message}
- </AIMarkdown>
- ))
- .with({ type: "data_part" }, (m) => (
- <AgentDataPartMessage
- message={m}
+ <>
+ {visibleParts.map((part, index) => (
+ <PartContainer
+ key={part.id}
+ chatRole="agent"
+ data-testid="metabot-chat-message"
+ {...props}
+ >
+ <AgentPart
+ part={part}
+ externalId={message.externalId}
debug={debug}
readonly={readonly}
conversationId={conversationId}
+ isStreaming={isStreaming && index === visibleParts.length - 1}
+ supportsReasoning={supportsReasoning}
+ onInternalLinkClick={onInternalLinkClick}
+ onToolCallSelect={onToolCallSelect}
/>
- ))
- .with({ type: "tool_call" }, (m) => (
- <AgentToolCallMessage message={m} onSelect={onToolCallSelect} />
- ))
- .with({ type: "chain_of_thought" }, (m) =>
- supportsReasoning ? (
- <MetabotChainOfThought message={m} isStreaming={isStreaming} />
- ) : (
- <MetabotToolProgress message={m} isStreaming={isStreaming} />
- ),
- )
- .with({ type: "turn_aborted" }, (m) => (
- <AbortedTurnAlert messageId={m.id} debug={debug} onRetry={onRetry} />
- ))
- .with({ type: "turn_incomplete" }, (m) => (
- <IncompleteTurnAlert
- finishReason={m.finishReason}
- contextWindowFull={m.contextWindowFull}
- onContinue={onContinue}
- />
- ))
- .with({ type: "turn_errored" }, (m) => (
- <AgentErroredTurnAlert
- message={m}
- debug={debug}
- onRefreshConversation={onRefreshConversation}
- />
- ))
- .with({ type: "turn_in_progress" }, () => (
- <Loader
- type="dots"
- size="lg"
- color="core-brand"
- data-testid="metabot-response-loader"
- />
- ))
- .exhaustive()}
- {!hideActions && (
- <Flex className={Styles.messageActions} align="center">
- {canCopy && (
- <Tooltip label={clipboard.copied ? t`Copied!` : t`Copy`}>
- <ActionIcon
- h="sm"
- data-testid="metabot-chat-message-copy"
- onClick={() => clipboard.copy(copyText)}
- >
- <Icon name="copy" size="1rem" />
- </ActionIcon>
- </Tooltip>
- )}
- {canGiveFeedback && (
- <>
- <Tooltip label={t`Give positive feedback`}>
- <FeedbackButton
- data-testid="metabot-chat-message-thumbs-up"
- icon="thumbs_up"
- hasBeenClicked={submittedFeedback === "positive"}
- disabled={!!submittedFeedback}
- onClick={() =>
- setFeedbackMessage({ messageId, positive: true })
- }
- />
- </Tooltip>
- <Tooltip label={t`Give negative feedback`}>
- <FeedbackButton
- data-testid="metabot-chat-message-thumbs-down"
- icon="thumbs_down"
- hasBeenClicked={submittedFeedback === "negative"}
- disabled={!!submittedFeedback}
- onClick={() =>
- setFeedbackMessage({ messageId, positive: false })
- }
- />
- </Tooltip>
- </>
- )}
- {onRetry && (
- <Tooltip label={t`Retry`}>
- <ActionIcon
- onClick={() => onRetry(message.id)}
- h="sm"
- data-testid="metabot-chat-message-retry"
- >
- <Icon name="revert" size="1rem" />
- </ActionIcon>
- </Tooltip>
- )}
- {extraActions}
- {canFork && (
- <Tooltip label={t`Fork conversation`}>
- <ActionIcon
- h="sm"
- data-testid="metabot-chat-message-fork"
- loading={isForking}
- disabled={isForking}
- onClick={() => onFork(messageId)}
- >
- <Icon name="git_branch" size="1rem" />
- </ActionIcon>
- </Tooltip>
- )}
- </Flex>
+ {index === actionsIndex && actions}
+ </PartContainer>
+ ))}
+ {needsStatusRow && (
+ <PartContainer chatRole="agent" data-testid="metabot-chat-message">
+ {status}
+ {showActionsInStatusRow && actions}
+ </PartContainer>
)}
- </MessageContainer>
+ </>
);
};
@@ -422,20 +518,22 @@ const AgentTurnAlert = ({
);
const AgentErroredTurnAlert = ({
- message,
+ error,
+ display,
debug,
onRefreshConversation,
}: {
- message: MetabotAgentTurnErroredMessage;
+ error: MetabotAgentTurnError;
+ display?: MetabotAgentTurnDisplayError;
debug: boolean;
onRefreshConversation?: () => void;
}) => {
- const isOutOfSync = message.error.type === "conversation_out_of_sync";
+ const isOutOfSync = error.type === "conversation_out_of_sync";
return (
<AgentTurnAlert
variant="error"
- message={message.display?.message ?? t`Something went wrong`}
+ message={display?.message ?? t`Something went wrong`}
cta={
isOutOfSync && onRefreshConversation ? (
<Button
@@ -450,23 +548,65 @@ const AgentErroredTurnAlert = ({
) : undefined
}
footer={
- message.error.type === "metabase_ai_managed_locked" && (
+ error.type === "metabase_ai_managed_locked" && (
<MetabotManagedProviderLimitActions inline />
)
}
- debugDetails={debug ? message.error : undefined}
+ debugDetails={debug ? error : undefined}
/>
);
};
+const MessageStatus = ({
+ status,
+ debug,
+ onRetry,
+ onContinue,
+ onRefreshConversation,
+}: {
+ status: MetabotMessageStatus;
+ debug: boolean;
+ onRetry?: () => void;
+ onContinue?: (resumePrompt: string) => void;
+ onRefreshConversation?: () => void;
+}) =>
+ match(status)
+ .with({ type: "done" }, () => null)
+ .with({ type: "streaming" }, () => null)
+ .with({ type: "errored" }, (o) => (
+ <AgentErroredTurnAlert
+ error={o.error}
+ display={o.display}
+ debug={debug}
+ onRefreshConversation={onRefreshConversation}
+ />
+ ))
+ .with({ type: "aborted" }, () => (
+ <AbortedTurnAlert debug={debug} onRetry={onRetry} />
+ ))
+ .with({ type: "incomplete" }, (o) => (
+ <IncompleteTurnAlert
+ finishReason={o.finishReason}
+ contextWindowFull={o.contextWindowFull}
+ onContinue={onContinue}
+ />
+ ))
+ .with({ type: "in_progress" }, () => (
+ <Loader
+ type="dots"
+ size="lg"
+ color="core-brand"
+ data-testid="metabot-response-loader"
+ />
+ ))
+ .exhaustive();
+
const AbortedTurnAlert = ({
- messageId,
debug,
onRetry,
}: {
- messageId: string;
debug: boolean;
- onRetry?: (messageId: string) => void;
+ onRetry?: () => void;
}) => {
const metabotName = useSetting("metabot-name");
return (
@@ -479,7 +619,7 @@ const AbortedTurnAlert = ({
variant="default"
size="compact-xs"
fz="xs"
- onClick={() => onRetry(messageId)}
+ onClick={onRetry}
data-testid="metabot-chat-message-retry"
>
{t`Retry`}
@@ -491,7 +631,7 @@ const AbortedTurnAlert = ({
};
const getIncompleteTurnConfig = (
- finishReason: MetabotAgentTurnIncompleteMessage["finishReason"],
+ finishReason: MetabotIncompleteFinishReason,
metabotName: string,
): { message: string; resumePrompt?: string } =>
match(finishReason)
@@ -516,7 +656,7 @@ const IncompleteTurnAlert = ({
contextWindowFull,
onContinue,
}: {
- finishReason: MetabotAgentTurnIncompleteMessage["finishReason"];
+ finishReason: MetabotIncompleteFinishReason;
contextWindowFull?: boolean;
onContinue?: (resumePrompt: string) => void;
}) => {
@@ -551,34 +691,6 @@ const IncompleteTurnAlert = ({
);
};
-export const getFullAgentReply = (
- messages: MetabotChatMessage[],
- messageId: string,
-) => {
- const messageIndex = messages.findLastIndex((m) => m.id === messageId);
- const message = messages[messageIndex];
- if (!message) {
- return [];
- }
-
- if (message.role === "user") {
- console.warn("getFullAgentReply requires a user message id");
- return [];
- }
-
- const firstMessageIndex =
- (messages.slice(0, messageIndex).findLastIndex((m) => m.role === "user") ??
- 0) + 1;
- const lastMessageIndex =
- messageIndex +
- Math.max(
- messages.slice(messageIndex).findIndex((m) => m.role === "user"),
- 0,
- );
-
- return messages.slice(firstMessageIndex, lastMessageIndex + 1);
-};
-
export const Messages = ({
messages,
onRetryMessage,
@@ -595,7 +707,7 @@ export const Messages = ({
renderAfterMessage,
onToolCallSelect,
}: {
- messages: MetabotChatMessage[];
+ messages: MetabotMessage[];
onRetryMessage?: (messageId: string) => void;
onContinueMessage?: (resumePrompt: string) => void;
onRefreshConversation?: () => void;
@@ -607,18 +719,10 @@ export const Messages = ({
conversationId: string;
onInternalLinkClick?: (navigateToPath: string) => void;
getExtraActions?: (messageId: string) => ReactNode;
- renderAfterMessage?: (message: MetabotChatMessage) => ReactNode;
+ renderAfterMessage?: (message: MetabotMessage) => ReactNode;
onToolCallSelect?: (message: MetabotDebugToolCallMessage) => void;
}) => {
const dispatch = useDispatch();
- const visibleMessages = useMemo(
- () => (debug ? messages : messages.filter(isUserVisibleMessage)),
- [debug, messages],
- );
- const lastUserIndex = useMemo(
- () => visibleMessages.findLastIndex((m) => m.role === "user"),
- [visibleMessages],
- );
const [sendToast] = useToast();
const [forkingMessageId, setForkingMessageId] = useState<string | null>(null);
@@ -671,84 +775,52 @@ export const Messages = ({
}
};
- const getAgentReplyCopyText = useCallback(
- (messageId: string) => {
- const allMessages = getFullAgentReply(messages, messageId);
- const textMessages = allMessages.filter(
- (msg): msg is MetabotAgentTextChatMessage =>
- msg.role === "agent" && msg.type === "text",
- );
- return textMessages.map((msg) => msg.message).join("\n\n");
- },
- [messages],
- );
-
return (
<>
- {visibleMessages.map((message, index) => {
- const next = visibleMessages[index + 1];
- const nextContent = visibleMessages
- .slice(index + 1)
- .find(isConversationContent);
- const isLastUserMessage = index > lastUserIndex;
-
- const messageElement =
- message.role === "agent" ? (
- <AgentMessage
- data-testid="metabot-chat-message"
- message={message}
- debug={debug}
- readonly={readonly}
- conversationId={conversationId}
- onRetry={isLastUserMessage ? onRetryMessage : undefined}
- onContinue={isLastUserMessage ? onContinueMessage : undefined}
- onRefreshConversation={onRefreshConversation}
- getCopyText={() => getAgentReplyCopyText(message.id)}
- setFeedbackMessage={(data) =>
- setFeedbackState((prev) => ({ ...prev, modal: data }))
- }
- submittedFeedback={
- "externalId" in message && message.externalId
- ? feedbackState.submitted[message.externalId]
- : undefined
- }
- hideActions={
- isChainOfThoughtMessage(message) ||
- nextContent?.role === "agent" ||
- (isDoingScience && !nextContent)
- }
- extraActions={getExtraActions?.(message.id)}
- onFork={
- agentId && !readonly && !isDoingScience ? handleFork : undefined
- }
- isForking={
- "externalId" in message &&
- !!message.externalId &&
- forkingMessageId === message.externalId
- }
- onInternalLinkClick={onInternalLinkClick}
- supportsReasoning={supportsReasoning}
- onToolCallSelect={onToolCallSelect}
- isStreaming={
- isChainOfThoughtMessage(message)
- ? isDoingScience && !nextContent
- : isDoingScience && !next
- }
- />
- ) : (
- <UserMessage
- data-testid="metabot-chat-message"
- message={message}
- hideActions={
- isDoingScience && visibleMessages.length === index + 1
- }
- extraActions={getExtraActions?.(message.id)}
- />
- );
+ {messages.map((message, index) => {
+ const isLastMessage = index === messages.length - 1;
+ const externalId = message.externalId ?? "";
return (
- <Fragment key={"msg-" + message.id}>
- {messageElement}
+ <Fragment key={message.id}>
+ {message.role === "agent" ? (
+ <AgentMessage
+ message={message}
+ debug={debug}
+ readonly={readonly}
+ conversationId={conversationId}
+ isStreaming={isDoingScience && isLastMessage}
+ onRetry={
+ isLastMessage && onRetryMessage
+ ? () => onRetryMessage(message.id)
+ : undefined
+ }
+ onContinue={isLastMessage ? onContinueMessage : undefined}
+ onRefreshConversation={onRefreshConversation}
+ setFeedbackMessage={(data) =>
+ setFeedbackState((prev) => ({ ...prev, modal: data }))
+ }
+ submittedFeedback={
+ externalId ? feedbackState.submitted[externalId] : undefined
+ }
+ extraActions={getExtraActions?.(message.id)}
+ onFork={
+ agentId && !readonly && !isDoingScience
+ ? handleFork
+ : undefined
+ }
+ isForking={!!externalId && forkingMessageId === externalId}
+ onInternalLinkClick={onInternalLinkClick}
+ supportsReasoning={supportsReasoning}
+ onToolCallSelect={onToolCallSelect}
+ />
+ ) : (
+ <UserMessage
+ message={message}
+ hideActions={isDoingScience && isLastMessage}
+ extraActions={getExtraActions?.(message.id)}
+ />
+ )}
{renderAfterMessage?.(message)}
</Fragment>
);
diff --git a/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.tsx b/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.tsx
index 174b0d89ad7..aed9c1c89ee 100644
--- a/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.tsx
@@ -13,7 +13,6 @@ import {
getIsConversationInProgress,
setConversationSnapshot,
} from "metabase/metabot/state";
-import { normalizeFetchedChatMessages } from "metabase/metabot/utils/normalize-fetched-chat-messages";
import { useDispatch, useSelector } from "metabase/redux";
import { Navigate, useParams } from "metabase/router";
import { getSettingsLoading } from "metabase/settings";
@@ -61,7 +60,7 @@ export const MetabotConversationPage = () => {
title: conversation.title ?? undefined,
forkedFromConversationId:
conversation.forked_from_conversation_id ?? undefined,
- messages: normalizeFetchedChatMessages(conversation.messages),
+ messages: conversation.messages,
state: conversation.state,
activeToolCalls: [],
}),
diff --git a/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.unit.spec.tsx
index 6c80ae0ab67..e351512fa0c 100644
--- a/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotConversationPage/MetabotConversationPage.unit.spec.tsx
@@ -4,6 +4,8 @@ import { assocIn } from "icepick";
import { setupEnterprisePlugins } from "__support__/enterprise";
import {
createMockMetabotConversationDetail,
+ createMockMetabotMessage,
+ createMockMetabotTextMessage,
setupDatabaseListEndpoint,
setupGetMetabotConversationEndpoint,
setupListMetabotConversationsEndpoint,
@@ -59,9 +61,7 @@ const stateWithConversation = ({
["conversations", conversationId],
createConversation({
conversationId,
- messages: message
- ? [{ id: "seed-message", role: "user", type: "text", message }]
- : [],
+ messages: message ? [createMockMetabotTextMessage("user", message)] : [],
}),
);
@@ -110,8 +110,11 @@ const inProgressDetail = () =>
createMockMetabotConversationDetail({
conversation_id: CONVERSATION_ID,
messages: [
- { id: "m1", role: "user", type: "text", message: "Loaded question" },
- { id: "m2", role: "agent", type: "turn_in_progress" },
+ createMockMetabotTextMessage("user", "Loaded question"),
+ createMockMetabotMessage({
+ role: "agent",
+ status: { type: "in_progress" },
+ }),
],
});
@@ -119,8 +122,8 @@ const finishedDetail = () =>
createMockMetabotConversationDetail({
conversation_id: CONVERSATION_ID,
messages: [
- { id: "m1", role: "user", type: "text", message: "Loaded question" },
- { id: "m3", role: "agent", type: "text", message: "Here is the answer" },
+ createMockMetabotTextMessage("user", "Loaded question"),
+ createMockMetabotTextMessage("agent", "Here is the answer"),
],
});
@@ -133,14 +136,7 @@ describe("MetabotConversationPage", () => {
mockConversationDetail(
createMockMetabotConversationDetail({
conversation_id: CONVERSATION_ID,
- messages: [
- {
- id: "m1",
- role: "user",
- type: "text",
- message: "Loaded question",
- },
- ],
+ messages: [createMockMetabotTextMessage("user", "Loaded question")],
}),
150,
);
@@ -214,6 +210,9 @@ describe("MetabotConversationPage", () => {
expect(await screen.findByText("Loaded question")).toBeInTheDocument();
expect(await screen.findByText("Thinking")).toBeInTheDocument();
+ expect(
+ screen.queryByTestId("metabot-response-loader"),
+ ).not.toBeInTheDocument();
expect(screen.getByTestId("metabot-stop-response")).toBeInTheDocument();
expect(
screen.queryByTestId("metabot-send-message"),
diff --git a/frontend/src/metabase/metabot/hooks/use-branchable-messages.tsx b/frontend/src/metabase/metabot/hooks/use-branchable-messages.tsx
index 36f6ca28a04..2e5d7697aef 100644
--- a/frontend/src/metabase/metabot/hooks/use-branchable-messages.tsx
+++ b/frontend/src/metabase/metabot/hooks/use-branchable-messages.tsx
@@ -1,19 +1,15 @@
import { type ReactNode, useMemo, useState } from "react";
import { MetabotBranchPicker } from "metabase/metabot/components/MetabotBranchPicker";
-import type { MetabotChatMessage } from "metabase/metabot/state/types";
+import type { MetabotMessage } from "metabase/metabot/state/types";
import {
- type ParentedChatMessage,
+ type ActiveResponse,
+ type ParentedMessage,
activeResponses,
} from "metabase/metabot/utils/message-tree";
-type ActiveResponse = ReturnType<typeof activeResponses>[number];
-
-export function useBranchableMessages(
- sourceMessages: ParentedChatMessage[],
- { isSlack = false }: { isSlack?: boolean } = {},
-): {
- messages: MetabotChatMessage[];
+export function useBranchableMessages(sourceMessages: ParentedMessage[]): {
+ messages: MetabotMessage[];
getExtraActions: (messageId: string) => ReactNode;
} {
const [selectedReplyByParentId, setSelectedReplyByParentId] = useState<
@@ -26,16 +22,15 @@ export function useBranchableMessages(
...selected,
[parentId]: replyId,
}));
- const responses = activeResponses(sourceMessages, selectedReplyByParentId, {
- isSlack,
- });
+ const responses = activeResponses(sourceMessages, selectedReplyByParentId);
+ const messages = responses.map(({ message }) => message);
const branchPickers = buildBranchPickers(responses, selectBranch);
return {
- messages: responses.flatMap(({ messages }) => messages),
+ messages,
getExtraActions: (messageId: string) => branchPickers[messageId],
};
- }, [sourceMessages, selectedReplyByParentId, isSlack]);
+ }, [sourceMessages, selectedReplyByParentId]);
}
function buildBranchPickers(
@@ -43,14 +38,12 @@ function buildBranchPickers(
selectBranch: (parentId: string, replyId: string) => void,
): Record<string, ReactNode> {
const pickers: Record<string, ReactNode> = {};
- for (const { branch, messages } of responses) {
- const lastMessage = messages.at(-1);
- if (!branch || !lastMessage) {
+ for (const { message, branch } of responses) {
+ if (!branch) {
continue;
}
- // Agent actions render on the final message in a response.
- pickers[lastMessage.id] = (
+ pickers[message.id] = (
<MetabotBranchPicker
index={branch.currentIndex}
count={branch.replyIds.length}
diff --git a/frontend/src/metabase/metabot/state/actions.ts b/frontend/src/metabase/metabot/state/actions.ts
index 2dc73dfdba9..12d8d4c8a40 100644
--- a/frontend/src/metabase/metabot/state/actions.ts
+++ b/frontend/src/metabase/metabot/state/actions.ts
@@ -42,7 +42,6 @@ import {
type MetabotProfileId,
isHistoryEnabledProfile,
} from "../constants";
-import { normalizeFetchedChatMessages } from "../utils/normalize-fetched-chat-messages";
import { metabot } from "./reducer";
import {
@@ -54,8 +53,10 @@ import {
getIsConversationProcessing,
getIsPollingForTitle,
getMessageIdToRewind,
+ getMessages,
getMetabotConversationId,
- getUserPromptForMessageId,
+ getPromptText,
+ getUserPromptMessage,
} from "./selectors";
import type {
MetabotAgentDataPartMessage,
@@ -73,7 +74,6 @@ export const {
addDeveloperMessage,
addUserMessage,
setIsProcessing,
- setMessageExternalIds,
setConversationSnapshot,
setConversationTitle,
setNavigateToPath,
@@ -398,6 +398,7 @@ export const submitInput = createAsyncThunk<
dispatch(
addUserMessage({
id: messageId,
+ externalId: userMessageId,
..._.omit(data, ["context", "metabot_id"]),
message: prompt,
conversationId,
@@ -454,6 +455,7 @@ type SendAgentRequestError =
type: "error";
conversation_id: string;
shouldRetry: boolean;
+ serverStarted: boolean;
error: MetabotAgentTurnError;
display?: MetabotAgentTurnDisplayError;
}
@@ -495,6 +497,7 @@ export const sendAgentRequest = createAsyncThunk<
let state: MetabotStateContext | undefined;
let response: ProcessedChatResponse | undefined;
let receivedTitle = false;
+ let serverStarted = false;
const hadTitleBeforeTurn = Boolean(
getConversationTitle(getState(), conversationId),
);
@@ -514,10 +517,7 @@ export const sendAgentRequest = createAsyncThunk<
{
onDataPart: function handleDataPart(part) {
const pushDataPart = (
- message: Omit<
- MetabotAgentDataPartMessage,
- "id" | "role" | "externalId"
- >,
+ message: Omit<MetabotAgentDataPartMessage, "id" | "role">,
) => dispatch(addAgentMessage({ ...message, conversationId }));
match(part)
@@ -639,14 +639,8 @@ export const sendAgentRequest = createAsyncThunk<
})
.exhaustive();
},
- onStart: function handleStart(event) {
- dispatch(
- setMessageExternalIds({
- conversationId,
- agentMessageId: event.messageId,
- userMessageId: event.messageMetadata?.userMessageId,
- }),
- );
+ onStart: function handleStart() {
+ serverStarted = true;
},
onTextPart: function handleTextPart(delta) {
dispatch(
@@ -737,6 +731,7 @@ export const sendAgentRequest = createAsyncThunk<
type: "error",
conversation_id: request.conversation_id,
shouldRetry: true,
+ serverStarted,
error: streamedError,
display: isMatching(
{ type: "ai_usage_limit_reached", message: P.string },
@@ -786,6 +781,7 @@ export const sendAgentRequest = createAsyncThunk<
type: "error" as const,
conversation_id: request.conversation_id,
shouldRetry: true,
+ serverStarted,
error: handled.error,
display: handled.display,
});
@@ -826,12 +822,12 @@ const rewindConversation = createAsyncThunk(
},
{ dispatch, getState },
) => {
- const promptMessage = getUserPromptForMessageId(
+ const userTurn = getUserPromptMessage(
getState(),
conversationId,
messageId,
);
- if (!promptMessage) {
+ if (!userTurn) {
throw new Error(
`Unable to find the prompt for message ${messageId} in conversation ${conversationId}`,
);
@@ -841,7 +837,7 @@ const rewindConversation = createAsyncThunk(
dispatch(
metabot.actions.rewindStateToMessageId({
conversationId,
- messageId: promptMessage.id,
+ messageId: userTurn.id,
}),
);
},
@@ -874,31 +870,37 @@ export const retryPrompt = createAsyncThunk<
) => {
const state = getState();
- const prompt = getUserPromptForMessageId(state, conversationId, messageId);
- if (!prompt) {
+ const userTurn = getUserPromptMessage(state, conversationId, messageId);
+ if (!userTurn) {
throw new Error("Agent message was not proceeded by a user message");
}
+ const promptText = getPromptText(userTurn);
if (getIsConversationProcessing(state, conversationId)) {
console.error("Metabot is actively serving a request");
- return { prompt: prompt.message, success: false, shouldRetry: false };
+ return { prompt: promptText, success: false, shouldRetry: false };
}
- dispatch(rewindConversation({ conversationId, messageId: prompt.id }));
+ // a turn the server never started has no rows to regenerate
+ const failedTurn = getMessages(state, conversationId).at(-1);
+ const retryMessageId =
+ failedTurn?.status.type === "errored" &&
+ failedTurn.status.serverStarted === false
+ ? undefined
+ : userTurn.externalId;
+
+ dispatch(rewindConversation({ conversationId, messageId: userTurn.id }));
dispatch(cancelInflightConversationRequests(conversationId));
- dispatch(
- metabot.actions.rewindStateToMessageId({ conversationId, messageId }),
- );
return await dispatch(
submitInput({
conversationId,
type: "text",
- message: prompt.message,
+ message: promptText,
context,
metabot_id,
profile,
- retryMessageId: prompt.externalId,
+ retryMessageId,
isTransformsPage,
isFullPageMetabot,
}),
@@ -906,9 +908,24 @@ export const retryPrompt = createAsyncThunk<
},
);
+const assertConversationIsNotStreaming = (conversationId: string) => {
+ const isStreaming =
+ findMatchingInflightAiStreamingRequests(
+ "/api/metabot/agent-streaming",
+ conversationId,
+ ).length > 0;
+ if (isStreaming) {
+ throw new Error(
+ `Cannot load conversation ${conversationId} while it is streaming`,
+ );
+ }
+};
+
export const fetchConversationSnapshot = createAsyncThunk(
"metabase/metabot/fetchConversationSnapshot",
async (conversationId: string, { dispatch }) => {
+ assertConversationIsNotStreaming(conversationId);
+
const { data: detail, error } = await dispatch(
metabotApi.endpoints.getMetabotConversation.initiate(conversationId, {
forceRefetch: true,
@@ -933,7 +950,7 @@ export const fetchConversationSnapshot = createAsyncThunk(
title: detail.title ?? undefined,
forkedFromConversationId:
detail.forked_from_conversation_id ?? undefined,
- messages: normalizeFetchedChatMessages(detail.messages),
+ messages: detail.messages,
state: detail.state,
activeToolCalls: [],
}),
@@ -950,10 +967,12 @@ export const loadConversation = createAsyncThunk(
}: { agentId: MetabotAgentId; conversationId: string },
{ dispatch },
) => {
+ assertConversationIsNotStreaming(conversationId);
+
// NOTE: deliberately doesn't cancel the inflight streaming-request;
// as we do not want to record it as an aborted response.
dispatch(attachAgentToConversation({ agentId, conversationId }));
- await dispatch(fetchConversationSnapshot(conversationId));
+ await dispatch(fetchConversationSnapshot(conversationId)).unwrap();
},
);
@@ -989,7 +1008,7 @@ export const forkConversation = createAsyncThunk(
title: conversation.title ?? undefined,
forkedFromConversationId:
conversation.forked_from_conversation_id ?? undefined,
- messages: normalizeFetchedChatMessages(conversation.messages),
+ messages: conversation.messages,
state: conversation.state,
activeToolCalls: [],
}),
diff --git a/frontend/src/metabase/metabot/state/reducer-utils.ts b/frontend/src/metabase/metabot/state/reducer-utils.ts
index a02d16867c1..624b0a7b8cb 100644
--- a/frontend/src/metabase/metabot/state/reducer-utils.ts
+++ b/frontend/src/metabase/metabot/state/reducer-utils.ts
@@ -13,11 +13,10 @@ import {
type MetabotAgentChainOfThoughtMessage,
type MetabotAgentId,
type MetabotAgentState,
- type MetabotAgentTurnDisplayError,
- type MetabotAgentTurnError,
- type MetabotAgentTurnIncompleteMessage,
type MetabotConversationState,
type MetabotDebugToolCallMessage,
+ type MetabotMessage,
+ type MetabotMessagePart,
type MetabotSearchResults,
type MetabotState,
fixedMetabotAgentIds,
@@ -32,13 +31,55 @@ export type AgentPayloadAction<
Value extends Record<string, any> = Record<string, any>,
> = PayloadAction<{ agentId: MetabotAgentId } & Value>;
-export const findLastToolCallMessage = (
+export const openAgentMessage = (
+ convo: WritableDraft<MetabotConversationState>,
+): WritableDraft<MetabotMessage> => {
+ const message = convo.messages.at(-1);
+ const statusType = message?.status.type;
+ const isOpenAgentMessage =
+ message?.role === "agent" &&
+ (statusType === "streaming" || statusType === "in_progress");
+ if (!isOpenAgentMessage) {
+ throw new Error("Metabot conversation has no open agent message");
+ }
+ return message;
+};
+
+export const startUserMessage = (
+ convo: WritableDraft<MetabotConversationState>,
+ { id, externalId }: { id: string; externalId?: string },
+) => {
+ // push literal and access to prevent TS2589 / immer excessively deep type
+ convo.messages.push({
+ id,
+ role: "user",
+ externalId,
+ parts: [],
+ status: { type: "done" },
+ });
+ return convo.messages[convo.messages.length - 1];
+};
+
+export const startAgentMessage = (
+ convo: WritableDraft<MetabotConversationState>,
+ externalId?: string,
+) => {
+ convo.messages.push({
+ id: createMessageId(),
+ role: "agent",
+ externalId,
+ parts: [],
+ status: { type: "streaming" },
+ });
+};
+
+export const findLastToolCallPart = (
convo: WritableDraft<MetabotConversationState>,
toolCallId: string,
) =>
- convo.messages.findLast(
- (m): m is MetabotDebugToolCallMessage =>
- m.type === "tool_call" && m.id === toolCallId,
+ openAgentMessage(convo).parts.findLast(
+ (p): p is WritableDraft<MetabotDebugToolCallMessage> =>
+ p.type === "tool_call" && p.id === toolCallId,
);
export const pushNewToolCall = (
@@ -49,7 +90,7 @@ export const pushNewToolCall = (
args,
}: { toolCallId: string; toolName: string; args?: string },
) => {
- convo.messages.push({
+ openAgentMessage(convo).parts.push({
id: toolCallId,
role: "agent",
type: "tool_call",
@@ -65,12 +106,13 @@ export const pushNewToolCall = (
});
};
-const activeChain = (convo: WritableDraft<MetabotConversationState>) => {
- const chain = convo.activeChainId
- ? convo.messages.find((m) => m.id === convo.activeChainId)
- : undefined;
- return chain?.type === "chain_of_thought" ? chain : undefined;
-};
+const isOpenChain = (
+ part: WritableDraft<MetabotMessagePart>,
+): part is WritableDraft<MetabotAgentChainOfThoughtMessage> =>
+ part.type === "chain_of_thought" && !part.finished;
+
+const activeChain = (convo: WritableDraft<MetabotConversationState>) =>
+ openAgentMessage(convo).parts.findLast(isOpenChain);
const stampChainSpan = (
chain: WritableDraft<MetabotAgentChainOfThoughtMessage>,
@@ -83,7 +125,7 @@ const stampChainSpan = (
chain.endedAtMs = nowMs;
};
-const ensureChain = (
+export const ensureChain = (
convo: WritableDraft<MetabotConversationState>,
nowMs?: number,
): WritableDraft<MetabotAgentChainOfThoughtMessage> => {
@@ -97,23 +139,20 @@ const ensureChain = (
role: "agent",
type: "chain_of_thought",
steps: [],
+ finished: false,
startedAtMs: nowMs,
endedAtMs: nowMs,
};
- convo.messages.push(chain);
- convo.activeChainId = chain.id;
+ openAgentMessage(convo).parts.push(chain);
return chain;
};
-export const openChain = (convo: WritableDraft<MetabotConversationState>) => {
- ensureChain(convo);
-};
-
const dropChain = (
convo: WritableDraft<MetabotConversationState>,
id: string,
) => {
- convo.messages = convo.messages.filter((m) => m.id !== id);
+ const message = openAgentMessage(convo);
+ message.parts = message.parts.filter((p) => p.id !== id);
};
export const startChainReasoning = (
@@ -165,22 +204,22 @@ export const addChainTool = (
if (title) {
existing.step.title = title;
}
- if (existing.chain.id === convo.activeChainId) {
+ if (!existing.chain.finished) {
stampChainSpan(existing.chain, nowMs);
}
};
-const findChainToolStep = (
+export const findChainToolStep = (
convo: WritableDraft<MetabotConversationState>,
toolCallId: string,
) => {
- for (const message of convo.messages) {
- if (message.type === "chain_of_thought") {
- const step = message.steps.find(
+ for (const part of openAgentMessage(convo).parts) {
+ if (part.type === "chain_of_thought") {
+ const step = part.steps.find(
(s) => s.kind === "tool" && s.id === toolCallId,
);
if (step?.kind === "tool") {
- return { chain: message, step };
+ return { chain: part, step };
}
}
}
@@ -219,8 +258,7 @@ export const endChainTool = (
return;
}
found.step.status = "ended";
- const chainStillActive = found.chain.id === convo.activeChainId;
- if (chainStillActive && nowMs != null) {
+ if (!found.chain.finished && nowMs != null) {
found.chain.endedAtMs = nowMs;
}
};
@@ -232,10 +270,12 @@ export const closeChain = (
const chain = activeChain(convo);
if (chain && chain.steps.length === 0) {
dropChain(convo, chain.id);
- } else if (chain && nowMs != null) {
- chain.endedAtMs = nowMs;
+ } else if (chain) {
+ chain.finished = true;
+ if (nowMs != null) {
+ chain.endedAtMs = nowMs;
+ }
}
- convo.activeChainId = undefined;
};
export const getRequestConversation = (
@@ -247,6 +287,7 @@ export const getRequestConversation = (
if (!convo) {
console.warn(`Unable to find metabot conversation ${conversation_id}`);
+ return undefined;
}
return convo;
@@ -272,9 +313,7 @@ export const createConversation = (
messages: [],
state: {},
activeToolCalls: [],
- activeChainId: undefined,
profileOverride: undefined,
- pendingMessageExternalId: undefined,
forkedFromConversationId: undefined,
...overrides,
conversationId: overrides?.conversationId ?? uuid(),
@@ -411,47 +450,6 @@ export const agentReducer =
);
};
-export const appendAgentTurnAborted = (
- convo: WritableDraft<MetabotConversationState>,
-) => {
- convo.messages.push({
- id: createMessageId(),
- role: "agent",
- type: "turn_aborted",
- externalId: convo.pendingMessageExternalId,
- });
-};
-
-export const appendAgentTurnIncomplete = (
- convo: WritableDraft<MetabotConversationState>,
- finishReason: MetabotAgentTurnIncompleteMessage["finishReason"],
- contextWindowFull?: boolean,
-) => {
- convo.messages.push({
- id: createMessageId(),
- role: "agent",
- type: "turn_incomplete",
- finishReason,
- contextWindowFull,
- externalId: convo.pendingMessageExternalId,
- });
-};
-
-export const appendAgentTurnErrored = (
- convo: WritableDraft<MetabotConversationState>,
- error: MetabotAgentTurnError,
- display?: MetabotAgentTurnDisplayError,
-) => {
- convo.messages.push({
- id: createMessageId(),
- role: "agent",
- type: "turn_errored",
- error,
- display,
- externalId: convo.pendingMessageExternalId,
- });
-};
-
export const getMetabotInitialState = (): MetabotState => {
const conversations: MetabotState["conversations"] = {};
const agents: MetabotState["agents"] = {};
diff --git a/frontend/src/metabase/metabot/state/reducer-utils.unit.spec.ts b/frontend/src/metabase/metabot/state/reducer-utils.unit.spec.ts
index efc3e8b7b9b..7b77bd6bbb5 100644
--- a/frontend/src/metabase/metabot/state/reducer-utils.unit.spec.ts
+++ b/frontend/src/metabase/metabot/state/reducer-utils.unit.spec.ts
@@ -1,22 +1,32 @@
import { produce } from "immer";
import {
+ createConversation as _createConversation,
addChainTool,
appendChainReasoning,
closeChain,
- createConversation,
endChainTool,
- openChain,
+ ensureChain,
+ startAgentMessage,
startChainReasoning,
} from "./reducer-utils";
import type { MetabotConversationState } from "./types";
+// the chain lives on the message being streamed into, so open one first
+const createConversation = () =>
+ produce(_createConversation(), (d) => startAgentMessage(d));
+
+const partsOf = (convo: MetabotConversationState) =>
+ convo.messages.flatMap((t) => t.parts);
+
const chainOf = (convo: MetabotConversationState) =>
- convo.messages.find((m) => m.type === "chain_of_thought");
+ partsOf(convo).find((p) => p.type === "chain_of_thought");
describe("chain of thought duration timing", () => {
it("stamps and advances endedAtMs on each step so the span lives in redux", () => {
- const opened = produce(createConversation(), (d) => openChain(d));
+ const opened = produce(createConversation(), (d) => {
+ ensureChain(d);
+ });
const started = produce(opened, (d) => startChainReasoning(d, 1000));
expect(chainOf(started)).toMatchObject({
startedAtMs: 1000,
@@ -34,7 +44,7 @@ describe("chain of thought duration timing", () => {
it("keeps the last step's end time when the answer closes the chain without a clock", () => {
const convo = produce(createConversation(), (d) => {
- openChain(d);
+ ensureChain(d);
startChainReasoning(d, 1000);
appendChainReasoning(d, "x", 3000);
closeChain(d); // e.g. a data-part answer arrives with no nowMs
@@ -44,11 +54,10 @@ describe("chain of thought duration timing", () => {
it("drops a shell that never gathered a step at turn teardown", () => {
const convo = produce(createConversation(), (d) => {
- openChain(d);
+ ensureChain(d);
closeChain(d);
});
expect(chainOf(convo)).toBeUndefined();
- expect(convo.activeChainId).toBeUndefined();
});
it("advances endedAtMs when a tool ends, so a turn ending on a tool counts its runtime", () => {
@@ -81,11 +90,11 @@ describe("chain tool step dedupe", () => {
closeChain(d, 2000);
addChainTool(d, { id: "t1", name: "search", title: "revenue" });
});
- const chains = convo.messages.filter((m) => m.type === "chain_of_thought");
+ const chains = partsOf(convo).filter((p) => p.type === "chain_of_thought");
expect(chains).toHaveLength(1);
expect(chains[0].steps).toEqual([
expect.objectContaining({ kind: "tool", id: "t1", title: "revenue" }),
]);
- expect(convo.activeChainId).toBeUndefined();
+ expect(chains[0].finished).toBe(true);
});
});
diff --git a/frontend/src/metabase/metabot/state/reducer.ts b/frontend/src/metabase/metabot/state/reducer.ts
index 6dc00af0f07..7e219bfde87 100644
--- a/frontend/src/metabase/metabot/state/reducer.ts
+++ b/frontend/src/metabase/metabot/state/reducer.ts
@@ -26,9 +26,6 @@ import {
type ConvoPayloadAction,
addChainTool,
agentReducer,
- appendAgentTurnAborted,
- appendAgentTurnErrored,
- appendAgentTurnIncomplete,
appendChainReasoning,
closeChain,
convoReducer,
@@ -36,26 +33,29 @@ import {
createConversation,
createConversationForAgent,
endChainTool,
+ ensureChain,
evictConversationIfUnused,
- findLastToolCallMessage,
+ findLastToolCallPart,
getAgentOrThrow,
getMetabotInitialState,
getRequestConversation,
- openChain,
+ openAgentMessage,
pushNewToolCall,
resetReactionState,
resetReactionStateForConversation,
setChainToolSearchResults,
setChainToolTitle,
+ startAgentMessage,
startChainReasoning,
+ startUserMessage,
} from "./reducer-utils";
import type {
- MetabotAgentChatMessage,
MetabotAgentId,
- MetabotChatMessage,
+ MetabotMessage,
+ MetabotMessagePart,
MetabotState,
MetabotToolCall,
- MetabotUserChatMessage,
+ MetabotUserTextChatMessage,
} from "./types";
import { createMessageId, hasInProgressMessage } from "./utils";
@@ -165,30 +165,30 @@ export const metabot = createSlice({
addUserMessage: convoReducer(
(
convo,
- action: ConvoPayloadAction<Omit<MetabotUserChatMessage, "role">>,
+ action: ConvoPayloadAction<
+ Omit<MetabotUserTextChatMessage, "role"> & { externalId?: string }
+ >,
) => {
- const { id, message, conversationId, ...rest } = action.payload;
+ const { id, message, conversationId, externalId, ...rest } =
+ action.payload;
convo.hasMessagedInSession = true;
+ const userMessage = startUserMessage(convo, { id, externalId });
// Unjustified type cast. FIXME
- convo.messages.push({ id, role: "user", ...rest, message } as any);
+ userMessage.parts.push({ id, role: "user", ...rest, message } as any);
},
),
addAgentMessage: convoReducer(
(
convo,
- action: ConvoPayloadAction<
- Omit<MetabotAgentChatMessage, "id" | "role" | "externalId">
- >,
+ action: ConvoPayloadAction<Omit<MetabotMessagePart, "id" | "role">>,
) => {
convo.activeToolCalls = [];
closeChain(convo);
- const externalId = convo.pendingMessageExternalId;
// Unjustified type cast. FIXME
- convo.messages.push({
+ openAgentMessage(convo).parts.push({
id: createMessageId(),
role: "agent",
...action.payload,
- ...(externalId ? { externalId } : {}),
// transforms in message is making this flakily produce possibly infinite
// typescript errors. since unused ts-expect-error directives produces
// errors, casting this as any to avoid having to add / remove constantly.
@@ -208,49 +208,26 @@ export const metabot = createSlice({
addAgentTextDelta: convoReducer(
(convo, action: ConvoPayloadAction<{ text: string; nowMs?: number }>) => {
const hasToolCalls = convo.activeToolCalls.length > 0;
- const lastMessage = _.last(convo.messages);
+ const message = openAgentMessage(convo);
+ const last = message.parts.at(-1);
const canAppend =
- !hasToolCalls &&
- lastMessage?.role === "agent" &&
- lastMessage.type === "text";
+ !hasToolCalls && last?.role === "agent" && last.type === "text";
if (canAppend) {
- lastMessage.message = lastMessage.message + action.payload.text;
+ last.message = last.message + action.payload.text;
} else {
closeChain(convo, action.payload.nowMs);
- const externalId = convo.pendingMessageExternalId;
- convo.messages.push({
+ message.parts.push({
id: createMessageId(),
role: "agent",
type: "text",
message: action.payload.text,
- ...(externalId ? { externalId } : {}),
});
}
convo.activeToolCalls = hasToolCalls ? [] : convo.activeToolCalls;
},
),
- setMessageExternalIds: convoReducer(
- (
- convo,
- action: ConvoPayloadAction<{
- agentMessageId?: string;
- userMessageId?: string;
- }>,
- ) => {
- const { agentMessageId, userMessageId } = action.payload;
- if (agentMessageId) {
- convo.pendingMessageExternalId = agentMessageId;
- }
- const lastUserMessage = convo.messages.findLast(
- (m) => m.role === "user",
- );
- if (userMessageId && lastUserMessage) {
- lastUserMessage.externalId = userMessageId;
- }
- },
- ),
toolCallStart: convoReducer(
(
convo,
@@ -285,7 +262,7 @@ export const metabot = createSlice({
) => {
const { toolCallId, toolName, title, args, nowMs } = action.payload;
addChainTool(convo, { id: toolCallId, name: toolName, title, nowMs });
- const existingMsg = findLastToolCallMessage(convo, toolCallId);
+ const existingMsg = findLastToolCallPart(convo, toolCallId);
if (existingMsg) {
// if toolCallStart was called (tool-input-start event is optional)
// update the existing tool call record to include the args received
@@ -311,10 +288,7 @@ export const metabot = createSlice({
endChainTool(convo, action.payload.toolCallId, action.payload.nowMs);
// Update the message in messages array with result for debug history
- const message = findLastToolCallMessage(
- convo,
- action.payload.toolCallId,
- );
+ const message = findLastToolCallPart(convo, action.payload.toolCallId);
if (message) {
message.status = "ended";
message.result = action.payload.result;
@@ -353,7 +327,9 @@ export const metabot = createSlice({
convo.isProcessing = false;
const id = action.payload.messageId;
- const messageIndex = convo.messages.findLastIndex((m) => id === m.id);
+ const messageIndex = convo.messages.findLastIndex(
+ (t) => t.id === id || t.parts.some((p) => p.id === id),
+ );
if (messageIndex > -1) {
convo.messages = convo.messages.slice(0, messageIndex);
}
@@ -459,7 +435,7 @@ export const metabot = createSlice({
setConversationSnapshot: (
state,
action: PayloadAction<{
- messages: MetabotChatMessage[];
+ messages: MetabotMessage[];
state?: MetabotStateContext;
activeToolCalls?: MetabotToolCall[];
conversationId: string;
@@ -480,19 +456,19 @@ export const metabot = createSlice({
state.conversations[conversationId] ??
castDraft(createConversation({ conversationId }));
- convo.messages = castDraft(messages);
+ convo.messages = castDraft(
+ messages.map((t) => ({ ...t, parts: [...t.parts] })),
+ );
convo.state = snapshotState ?? {};
convo.activeToolCalls = activeToolCalls ?? [];
- convo.activeChainId = undefined;
convo.title = title;
convo.forkedFromConversationId = forkedFromConversationId;
convo.lastTokenUsage = undefined;
convo.isProcessing = hasInProgressMessage(messages);
if (convo.isProcessing) {
- openChain(convo); // resuming mid-response
+ ensureChain(convo); // resuming mid-response
}
convo.stateBeforeTurn = undefined;
- convo.pendingMessageExternalId = undefined;
state.conversations[conversationId] = convo;
// NOTE: live reactions aren't reconstructed from a fetched snapshot
@@ -515,9 +491,8 @@ export const metabot = createSlice({
convo.isProcessing = true;
convo.hasMessagedInSession = true;
convo.stateBeforeTurn = convo.state;
- convo.activeChainId = undefined;
- openChain(convo);
- convo.pendingMessageExternalId = action.meta.arg.assistant_message_id;
+ startAgentMessage(convo, action.meta.arg.assistant_message_id);
+ ensureChain(convo);
}
})
.addCase(sendAgentRequest.fulfilled, (state, action) => {
@@ -538,59 +513,58 @@ export const metabot = createSlice({
const finishReason = action.payload?.processedResponse.finishReason;
const isResumableFinishReason =
finishReason && finishReason !== "stop" && finishReason !== "error";
- if (isResumableFinishReason) {
- const contextWindowFull =
- finishReason === "length" &&
- isContextWindowFull(convo.lastTokenUsage);
- appendAgentTurnIncomplete(convo, finishReason, contextWindowFull);
- }
+ closeChain(convo);
+ openAgentMessage(convo).status = isResumableFinishReason
+ ? {
+ type: "incomplete",
+ finishReason,
+ contextWindowFull:
+ finishReason === "length" &&
+ isContextWindowFull(convo.lastTokenUsage),
+ }
+ : { type: "done" };
convo.activeToolCalls = [];
- closeChain(convo);
convo.isProcessing = false;
convo.experimental.developerMessage = "";
- convo.pendingMessageExternalId = undefined;
}
})
.addCase(sendAgentRequest.rejected, (state, action) => {
const convo = getRequestConversation(state, action);
if (convo) {
+ // the chain lives on the open message, so close it before settling
+ closeChain(convo);
+ const message = openAgentMessage(convo);
+
// aborted requests needs special state adjustments
if (action.payload?.type === "abort") {
if (action.payload?.state) {
convo.state = { ...action.payload.state };
}
- // an abort means the request (almost certainly) reached the server,
- // so the turn's rows exist under the client-minted id even when the
- // start event never arrived — stamp it so retry can target the prompt
- const lastUserMessage = convo.messages.findLast(
- (m) => m.role === "user",
- );
- if (lastUserMessage && !lastUserMessage.externalId) {
- lastUserMessage.externalId = action.meta.arg.user_message_id;
- }
- appendAgentTurnAborted(convo);
+ message.status = { type: "aborted" };
if (action.payload.unresolved_tool_calls.length > 0) {
- // update message state so that unresolved tools are marked as ended
- convo.messages.forEach((msg) => {
- if (msg.type === "tool_call" && msg.status === "started") {
- msg.status = "ended";
- msg.result = "Tool execution interrupted by user";
- msg.is_error = true;
+ message.parts.forEach((part) => {
+ if (part.type === "tool_call" && part.status === "started") {
+ part.status = "ended";
+ part.result = "Tool execution interrupted by user";
+ part.is_error = true;
}
});
}
} else if (action.payload?.type === "error") {
- appendAgentTurnErrored(
- convo,
- action.payload.error,
- action.payload.display,
- );
+ message.status = {
+ type: "errored",
+ error: action.payload.error,
+ display: action.payload.display,
+ serverStarted: action.payload.serverStarted,
+ };
+ } else {
+ message.status = action.meta.aborted
+ ? { type: "aborted" }
+ : { type: "errored", error: { message: action.error?.message } };
}
- convo.pendingMessageExternalId = undefined;
convo.activeToolCalls = [];
- closeChain(convo);
convo.isProcessing = false;
}
})
diff --git a/frontend/src/metabase/metabot/state/selectors.ts b/frontend/src/metabase/metabot/state/selectors.ts
index 974e768dab1..75517505145 100644
--- a/frontend/src/metabase/metabot/state/selectors.ts
+++ b/frontend/src/metabase/metabot/state/selectors.ts
@@ -1,6 +1,5 @@
import { createSelector } from "@reduxjs/toolkit";
import { match } from "ts-pattern";
-import _ from "underscore";
import { isEmbedding } from "metabase/embedding/config";
import type { State } from "metabase/redux/store";
@@ -18,12 +17,8 @@ import {
isContextWindowFull,
} from "../utils/context-usage";
-import type {
- MetabotAgentId,
- MetabotChatMessage,
- MetabotUserChatMessage,
-} from "./types";
-import { hasInProgressMessage } from "./utils";
+import type { MetabotAgentId, MetabotMessage } from "./types";
+import { hasInProgressMessage, isGeneratedCardPart, isTextPart } from "./utils";
/*
* Top Level Selectors
@@ -180,78 +175,54 @@ export const getActiveToolCalls = createSelector(
(convo) => convo.activeToolCalls,
);
-export const getLastMessage = createSelector(getMessages, (messages) =>
- _.last(messages),
-);
-
export const getLastAgentMessageExternalId = createSelector(
getMessages,
- (messages) => {
- const lastAgentMessage = messages.findLast(
- (m) => m.role === "agent" && "externalId" in m,
- );
- return lastAgentMessage && "externalId" in lastAgentMessage
- ? lastAgentMessage.externalId
- : undefined;
- },
+ (messages) => messages.findLast((t) => t.role === "agent")?.externalId,
);
-const splitByTurn = (messages: MetabotChatMessage[]): MetabotChatMessage[][] =>
- messages.reduce<MetabotChatMessage[][]>((turns, m) => {
- if (m.role === "user" || turns.length === 0) {
- turns.push([m]);
- } else {
- turns[turns.length - 1].push(m);
- }
- return turns;
- }, []);
-
export const getFinalChartMessageIdsPerTurn = createSelector(
getMessages,
(messages) =>
new Set(
- splitByTurn(messages).flatMap((turn) => {
- const lastChart = turn.findLast(
- (m) =>
- m.type === "data_part" &&
- m.part.type === "data-generated_entity" &&
- m.part.data.type === "card",
- );
+ messages.flatMap((message) => {
+ const lastChart = message.parts.findLast(isGeneratedCardPart);
return lastChart ? [lastChart.id] : [];
}),
),
);
-// if the message id provided is an agent id the first user message
-// that precedes it will be returned. if a user message id is provided
-// that exact message will be returned.
-export const getUserPromptForMessageId = createSelector(
+/**
+ * The user message that prompted `messageId` — the message itself when `messageId`
+ * addresses a user message or one of its parts, otherwise the nearest preceding
+ * one. Retry and rewind both target the message, since that is what the server
+ * regenerates.
+ */
+export const getUserPromptMessage = createSelector(
[getMessages, (_, __, messageId: string) => messageId],
- (messages, messageId): MetabotUserChatMessage | undefined => {
- const messageIndex = messages.findLastIndex((m) => m.id === messageId);
- const message = messages[messageIndex];
- if (!message) {
+ (messages, messageId): MetabotMessage | undefined => {
+ const messageIndex = messages.findLastIndex(
+ (t) => t.id === messageId || t.parts.some((p) => p.id === messageId),
+ );
+ if (messageIndex === -1) {
return undefined;
}
-
- if (message.role === "user") {
- return message;
- } else {
- return messages
- .slice(0, messageIndex)
- .findLast<MetabotUserChatMessage>((m) => m.role === "user");
- }
+ return messages[messageIndex].role === "user"
+ ? messages[messageIndex]
+ : messages.slice(0, messageIndex).findLast((t) => t.role === "user");
},
);
+export const getPromptText = (message: MetabotMessage) =>
+ message.parts.find(isTextPart)?.message ?? "";
+
export const getMessageIdToRewind = createSelector(
[getMessages],
(messages) => {
- const lastMessage = messages.at(-1);
- if (lastMessage?.type === "turn_errored") {
- return messages.findLast((m) => m.role === "user")?.id;
+ if (messages.at(-1)?.status.type !== "errored") {
+ return undefined;
}
- return undefined;
+ const promptMessage = messages.findLast((t) => t.role === "user");
+ return promptMessage?.parts.at(0)?.id;
},
);
diff --git a/frontend/src/metabase/metabot/state/selectors.unit.spec.ts b/frontend/src/metabase/metabot/state/selectors.unit.spec.ts
index b1d5bb3a85d..70a97189cad 100644
--- a/frontend/src/metabase/metabot/state/selectors.unit.spec.ts
+++ b/frontend/src/metabase/metabot/state/selectors.unit.spec.ts
@@ -1,6 +1,7 @@
import { assocIn } from "icepick";
import { setupEnterprisePlugins } from "__support__/enterprise";
+import { createMockMetabotMessage } from "__support__/server-mocks";
import type { State } from "metabase/redux/store";
import { createMockState } from "metabase/redux/store/mocks";
@@ -9,30 +10,37 @@ import { CONTEXT_WINDOW_WARNING_PERCENT } from "../constants";
import { getMetabotInitialState } from "./reducer-utils";
import {
- type MetabotChatMessage,
type MetabotConversationState,
+ type MetabotMessage,
getContextUsagePercent,
+ getIsConversationInProgress,
getLastAgentMessageExternalId,
getLongChatNotice,
- getUserPromptForMessageId,
+ getUserPromptMessage,
} from "./index";
function setup(
- messages: MetabotChatMessage[],
- convoState?: Partial<Pick<MetabotConversationState, "lastTokenUsage">>,
+ messages: MetabotMessage[],
+ convoState?: Partial<
+ Pick<
+ MetabotConversationState,
+ "conversationId" | "lastTokenUsage" | "profileOverride"
+ >
+ >,
): State {
setupEnterprisePlugins();
+ const conversationId = convoState?.conversationId ?? "omnibot";
const state = getMetabotInitialState();
const visibleState = assocIn(state, ["agents", "omnibot", "visible"], true);
const withMessages = assocIn(
visibleState,
- ["conversations", "omnibot", "messages"],
+ ["conversations", conversationId, "messages"],
messages,
);
const withConvoState = Object.entries(convoState ?? {}).reduce(
(acc, [key, value]) =>
- assocIn(acc, ["conversations", "omnibot", key], value),
+ assocIn(acc, ["conversations", conversationId, key], value),
withMessages,
);
@@ -40,75 +48,110 @@ function setup(
}
describe("metabot selectors", () => {
- describe("getUserPromptForMessageId", () => {
- it("should return the message with the matching id if id is for a user message", () => {
+ describe("getUserPromptMessage", () => {
+ it("returns the message itself when the id addresses a user message", () => {
const state = setup([
- { id: "1", role: "user", type: "text", message: "bleh" },
- { id: "2", role: "agent", type: "text", message: "blah" },
+ createMockMetabotMessage({
+ role: "user",
+ parts: [{ id: "1", role: "user", type: "text", message: "bleh" }],
+ }),
+ createMockMetabotMessage({
+ parts: [{ id: "2", role: "agent", type: "text", message: "blah" }],
+ }),
]);
- const message = getUserPromptForMessageId(state, "omnibot", "1");
- expect(message).toEqual({
- id: "1",
+ expect(getUserPromptMessage(state, "omnibot", "1")).toMatchObject({
role: "user",
- type: "text",
- message: "bleh",
+ parts: [{ id: "1", type: "text", message: "bleh" }],
});
});
- it("should return the message with the matching id if id is for an agent message", () => {
+ it("returns the preceding user message when the id addresses an agent message", () => {
const state = setup([
- { id: "1", type: "text", role: "user", message: "bleh" },
- { id: "2", type: "text", role: "agent", message: "blah" },
- { id: "3", type: "text", role: "user", message: "bleh bleh" },
- { id: "4", type: "text", role: "agent", message: "blah blah" },
+ createMockMetabotMessage({
+ role: "user",
+ parts: [{ id: "1", role: "user", type: "text", message: "bleh" }],
+ }),
+ createMockMetabotMessage({
+ parts: [{ id: "2", role: "agent", type: "text", message: "blah" }],
+ }),
+ createMockMetabotMessage({
+ role: "user",
+ parts: [
+ { id: "3", role: "user", type: "text", message: "bleh bleh" },
+ ],
+ }),
+ createMockMetabotMessage({
+ parts: [
+ { id: "4", role: "agent", type: "text", message: "blah blah" },
+ ],
+ }),
]);
- const message1 = getUserPromptForMessageId(state, "omnibot", "2");
- expect(message1).toEqual({
- id: "1",
- role: "user",
- type: "text",
- message: "bleh",
+ expect(getUserPromptMessage(state, "omnibot", "2")).toMatchObject({
+ parts: [{ id: "1", message: "bleh" }],
});
- const message2 = getUserPromptForMessageId(state, "omnibot", "4");
- expect(message2).toEqual({
- id: "3",
- role: "user",
- type: "text",
- message: "bleh bleh",
+ expect(getUserPromptMessage(state, "omnibot", "4")).toMatchObject({
+ parts: [{ id: "3", message: "bleh bleh" }],
});
});
});
describe("getLastAgentMessageExternalId", () => {
- it("skips a trailing tool_call and returns the last agent message that carries an externalId", () => {
+ it("returns the last agent message's id", () => {
const state = setup([
- { id: "1", role: "user", type: "text", message: "hi" },
- {
- id: "2",
- role: "agent",
- type: "text",
- message: "working on it",
+ createMockMetabotMessage({
+ role: "user",
+ parts: [{ id: "1", role: "user", type: "text", message: "hi" }],
+ }),
+ createMockMetabotMessage({
externalId: "ext-2",
- },
- {
- id: "3",
- role: "agent",
- type: "tool_call",
- name: "search",
- status: "ended",
- },
+ parts: [
+ { id: "2", role: "agent", type: "text", message: "working on it" },
+ ],
+ }),
]);
expect(getLastAgentMessageExternalId(state, "omnibot")).toBe("ext-2");
});
+
+ it("returns the id of a message made only of tool calls", () => {
+ const state = setup([
+ createMockMetabotMessage({
+ role: "user",
+ parts: [{ id: "1", role: "user", type: "text", message: "hi" }],
+ }),
+ createMockMetabotMessage({
+ externalId: "ext-2",
+ parts: [{ id: "2", role: "agent", type: "text", message: "on it" }],
+ }),
+ createMockMetabotMessage({
+ role: "user",
+ parts: [
+ { id: "3", role: "user", type: "text", message: "top customers?" },
+ ],
+ }),
+ // a clarification message renders nothing but a tool call — it still has
+ // to anchor the next request's parent_message_id
+ createMockMetabotMessage({
+ externalId: "ext-4",
+ parts: [
+ {
+ id: "call-1",
+ role: "agent",
+ type: "tool_call",
+ name: "ask_for_sql_clarification",
+ status: "ended",
+ },
+ ],
+ }),
+ ]);
+ expect(getLastAgentMessageExternalId(state, "omnibot")).toBe("ext-4");
+ });
});
describe("getLongChatNotice", () => {
- const shortMessage: MetabotChatMessage = {
- id: "1",
+ const shortMessage = createMockMetabotMessage({
role: "user",
- type: "text",
- message: "hi",
- };
+ parts: [{ id: "1", role: "user", type: "text", message: "hi" }],
+ });
const CONTEXT_WINDOW = 200000;
const usage = (contextTokens: number) => ({
lastTokenUsage: { contextTokens, contextWindowTokens: CONTEXT_WINDOW },
@@ -159,4 +202,19 @@ describe("metabot selectors", () => {
});
});
});
+
+ describe("getIsConversationInProgress", () => {
+ it("detects a mid-thread in-progress message for profiles like slackbot", () => {
+ const conversationId = "slackbot";
+ const state = setup(
+ [
+ createMockMetabotMessage({ status: { type: "in_progress" } }),
+ createMockMetabotMessage({ status: { type: "done" } }),
+ ],
+ { conversationId, profileOverride: "slackbot" },
+ );
+
+ expect(getIsConversationInProgress(state, conversationId)).toBe(true);
+ });
+ });
});
diff --git a/frontend/src/metabase/metabot/state/types.ts b/frontend/src/metabase/metabot/state/types.ts
index d1a50b1b93f..e12d8b53502 100644
--- a/frontend/src/metabase/metabot/state/types.ts
+++ b/frontend/src/metabase/metabot/state/types.ts
@@ -42,7 +42,6 @@ export type MetabotUserTextChatMessage = {
role: "user";
type: "text";
message: string;
- externalId?: string;
};
export type MetabotAgentTextChatMessage = {
@@ -50,7 +49,6 @@ export type MetabotAgentTextChatMessage = {
role: "agent";
type: "text";
message: string;
- externalId?: string;
};
export type MetabotAgentDataPartMessage = {
@@ -59,7 +57,10 @@ export type MetabotAgentDataPartMessage = {
type: "data_part";
part: MetabotDataPart;
metadata?: MetabotDataPartMetadata;
- externalId?: string;
+};
+
+export type MetabotGeneratedCardPart = MetabotAgentDataPartMessage & {
+ part: { type: "data-generated_entity"; data: { type: "card" } };
};
export type MetabotDebugToolCallMessage = {
@@ -73,70 +74,59 @@ export type MetabotDebugToolCallMessage = {
is_error?: boolean;
};
-export type MetabotAgentTurnAbortedMessage = {
- id: string;
- role: "agent";
- type: "turn_aborted";
- externalId?: string;
-};
-
-export type MetabotAgentTurnIncompleteMessage = {
- id: string;
- role: "agent";
- type: "turn_incomplete";
- finishReason: Exclude<FinishReason, "stop" | "error">;
- contextWindowFull?: boolean;
- externalId?: string;
-};
-
export type MetabotAgentTurnDisplayError = {
type: "alert" | "locked" | "message";
message: string;
};
-export type MetabotAgentTurnErroredMessage = {
- id: string;
- role: "agent";
- type: "turn_errored";
- error: MetabotAgentTurnError;
- display?: MetabotAgentTurnDisplayError;
- externalId?: string;
-};
-
-export type MetabotAgentTurnInProgressMessage = {
- id: string;
- role: "agent";
- type: "turn_in_progress";
- externalId?: string;
-};
-
export type MetabotAgentChainOfThoughtMessage = {
id: string;
role: "agent";
type: "chain_of_thought";
steps: MetabotChainStep[];
+ finished: boolean;
startedAtMs?: number;
endedAtMs?: number;
};
-export type MetabotAgentChatMessage =
+export type MetabotUserChatMessage = MetabotUserTextChatMessage;
+
+export type MetabotIncompleteFinishReason = Exclude<
+ FinishReason,
+ "stop" | "error"
+>;
+
+export type MetabotMessageStatus =
+ | { type: "streaming" }
+ | { type: "in_progress" }
+ | { type: "done" }
+ | { type: "aborted" }
+ | {
+ type: "incomplete";
+ finishReason: MetabotIncompleteFinishReason;
+ contextWindowFull?: boolean;
+ }
+ | {
+ type: "errored";
+ error: MetabotAgentTurnError;
+ display?: MetabotAgentTurnDisplayError;
+ serverStarted?: boolean;
+ };
+
+export type MetabotMessagePart =
+ | MetabotUserTextChatMessage
| MetabotAgentTextChatMessage
| MetabotAgentDataPartMessage
| MetabotDebugToolCallMessage
- | MetabotAgentChainOfThoughtMessage
- | MetabotAgentTurnAbortedMessage
- | MetabotAgentTurnIncompleteMessage
- | MetabotAgentTurnErroredMessage
- | MetabotAgentTurnInProgressMessage;
-
-export type MetabotUserChatMessage = MetabotUserTextChatMessage;
+ | MetabotAgentChainOfThoughtMessage;
-export type MetabotDebugChatMessage = MetabotDebugToolCallMessage;
-
-export type MetabotChatMessage =
- | MetabotUserChatMessage
- | MetabotAgentChatMessage
- | MetabotDebugChatMessage;
+export type MetabotMessage = {
+ id: string;
+ externalId?: string;
+ role: "user" | "agent";
+ parts: MetabotMessagePart[];
+ status: MetabotMessageStatus;
+};
export type MetabotToolCall = {
id: string;
@@ -176,14 +166,12 @@ export interface MetabotConversationState {
forkedFromConversationId: string | undefined;
isProcessing: boolean;
hasMessagedInSession: boolean;
- messages: MetabotChatMessage[];
+ messages: MetabotMessage[];
state: MetabotStateContext;
stateBeforeTurn?: MetabotStateContext;
activeToolCalls: MetabotToolCall[];
- activeChainId: string | undefined;
lastTokenUsage?: MetabotContextUsage;
profileOverride: MetabotProfileId | undefined;
- pendingMessageExternalId: string | undefined;
experimental: {
developerMessage: string;
metabotReqIdOverride: string | undefined;
diff --git a/frontend/src/metabase/metabot/state/utils.ts b/frontend/src/metabase/metabot/state/utils.ts
index 26a910133da..42b0d0ea620 100644
--- a/frontend/src/metabase/metabot/state/utils.ts
+++ b/frontend/src/metabase/metabot/state/utils.ts
@@ -2,7 +2,11 @@ import { nanoid } from "@reduxjs/toolkit";
import type {
MetabotAgentChainOfThoughtMessage,
- MetabotChatMessage,
+ MetabotAgentTextChatMessage,
+ MetabotGeneratedCardPart,
+ MetabotMessage,
+ MetabotMessagePart,
+ MetabotUserTextChatMessage,
SlashCommand,
} from "./types";
@@ -11,12 +15,24 @@ export const createMessageId = () => {
};
export const isChainOfThoughtMessage = (
- message: MetabotChatMessage,
-): message is MetabotAgentChainOfThoughtMessage =>
- message.type === "chain_of_thought";
+ part: MetabotMessagePart,
+): part is MetabotAgentChainOfThoughtMessage =>
+ part.type === "chain_of_thought";
-export const hasInProgressMessage = (messages: MetabotChatMessage[]): boolean =>
- messages.some((message) => message.type === "turn_in_progress");
+export const isTextPart = (
+ part: MetabotMessagePart,
+): part is MetabotUserTextChatMessage | MetabotAgentTextChatMessage =>
+ part.type === "text";
+
+export const isGeneratedCardPart = (
+ part: MetabotMessagePart,
+): part is MetabotGeneratedCardPart =>
+ part.type === "data_part" &&
+ part.part.type === "data-generated_entity" &&
+ part.part.data.type === "card";
+
+export const hasInProgressMessage = (messages: MetabotMessage[]): boolean =>
+ messages.some((message) => message.status.type === "in_progress");
export const parseSlashCommand = (
message: string,
diff --git a/frontend/src/metabase/metabot/tests/chat-message-rendering.unit.spec.tsx b/frontend/src/metabase/metabot/tests/chat-message-rendering.unit.spec.tsx
index 9e9738a23e5..631b4fb1122 100644
--- a/frontend/src/metabase/metabot/tests/chat-message-rendering.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/tests/chat-message-rendering.unit.spec.tsx
@@ -5,6 +5,9 @@ import type { ComponentProps } from "react";
import {
createMockMetabotConversationDetail,
+ createMockMetabotMessage,
+ createMockMetabotTextMessage,
+ createMockMetabotToolCallPart,
setupCardEndpoints,
setupCollectionByIdEndpoint,
setupDocumentEndpoints,
@@ -13,9 +16,9 @@ import {
import { renderWithProviders, screen, within } from "__support__/ui";
import { METABOT_ERR_MSG } from "metabase/metabot/constants";
import type {
- MetabotAgentChatMessage,
- MetabotAgentTurnIncompleteMessage,
- MetabotChatMessage,
+ MetabotIncompleteFinishReason,
+ MetabotMessage,
+ MetabotMessageStatus,
} from "metabase/metabot/state";
import { getMetabotInitialState } from "metabase/metabot/state/reducer-utils";
import {
@@ -29,7 +32,6 @@ import {
thumbsDown,
thumbsUp,
} from "metabase/metabot/tests/utils";
-import type { FetchedChatMessage } from "metabase/metabot/utils/normalize-fetched-chat-messages";
import { createMockState } from "metabase/redux/store/mocks";
import { registerVisualizations } from "metabase/visualizations/register";
import {
@@ -47,13 +49,8 @@ import {
registerVisualizations();
-const textMessage = (
- role: "user" | "agent",
- message: string,
-): FetchedChatMessage => ({ id: message, role, type: "text", message });
-
const setup = (
- message: MetabotAgentChatMessage,
+ message: Partial<MetabotMessage>,
props?: Partial<ComponentProps<typeof AgentMessage>>,
) =>
renderWithProviders(
@@ -61,11 +58,16 @@ const setup = (
debug={false}
readonly={false}
conversationId="convo-1"
- hideActions
setFeedbackMessage={() => {}}
submittedFeedback={undefined}
- getCopyText={() => ""}
- message={message}
+ message={{
+ id: "m1",
+ externalId: "msg-1",
+ role: "agent",
+ parts: [],
+ status: { type: "done" },
+ ...message,
+ }}
{...props}
/>,
{
@@ -80,8 +82,8 @@ describe("AgentMessage", () => {
renderWithProviders(
<Messages
messages={[
- { id: "u1", role: "user", type: "text", message: "hi" },
- { id: "a1", role: "agent", type: "text", message: "hello" },
+ createMockMetabotTextMessage("user", "hi"),
+ createMockMetabotTextMessage("agent", "hello"),
]}
isDoingScience
debug={false}
@@ -99,13 +101,17 @@ describe("AgentMessage", () => {
renderWithProviders(
<Messages
messages={[
- { id: "u1", role: "user", type: "text", message: "hi" },
- {
- id: "a1",
- role: "agent",
- type: "data_part",
- part: { type: "data-todo_list", data: [] },
- },
+ createMockMetabotTextMessage("user", "hi"),
+ createMockMetabotMessage({
+ parts: [
+ {
+ id: "a1",
+ role: "agent",
+ type: "data_part",
+ part: { type: "data-todo_list", data: [] },
+ },
+ ],
+ }),
]}
isDoingScience={false}
debug={false}
@@ -119,16 +125,36 @@ describe("AgentMessage", () => {
).not.toBeInTheDocument();
});
+ it("renders nothing for a done reply with no visible parts", () => {
+ setup({ parts: [createMockMetabotToolCallPart()] }, { onFork: jest.fn() });
+
+ expect(
+ screen.queryByTestId("metabot-chat-message"),
+ ).not.toBeInTheDocument();
+ });
+
+ it("renders extra actions on a tool-only reply in debug mode", () => {
+ setup(
+ { parts: [createMockMetabotToolCallPart()] },
+ { debug: true, extraActions: <span data-testid="picker" /> },
+ );
+
+ expect(screen.getByTestId("picker")).toBeInTheDocument();
+ });
+
+ it("does not render extra actions on a tool-only reply outside debug mode", () => {
+ setup(
+ { parts: [createMockMetabotToolCallPart()] },
+ { debug: false, extraActions: <span data-testid="picker" /> },
+ );
+
+ expect(screen.queryByTestId("picker")).not.toBeInTheDocument();
+ });
+
describe("feedback controls", () => {
- const conversation: MetabotChatMessage[] = [
- { id: "u1", role: "user", type: "text", message: "hi" },
- {
- id: "a1",
- role: "agent",
- type: "text",
- message: "hello",
- externalId: "a1-ext",
- },
+ const conversation = [
+ createMockMetabotTextMessage("user", "hi"),
+ createMockMetabotTextMessage("agent", "hello", { externalId: "a1-ext" }),
];
it("shows feedback ratings in an interactive conversation", async () => {
@@ -175,17 +201,21 @@ describe("AgentMessage", () => {
});
setupCardEndpoints(createMockCard({ id: 99, name: "Accounts by Day" }));
setup({
- id: "s1",
- role: "agent",
- type: "data_part",
- part: {
- type: "data-entity_saved",
- data: {
- chart_id: "chart-1",
- card_id: 99,
- destination: { type: "collection", id: 5 },
+ parts: [
+ {
+ id: "s1",
+ role: "agent",
+ type: "data_part",
+ part: {
+ type: "data-entity_saved",
+ data: {
+ chart_id: "chart-1",
+ card_id: 99,
+ destination: { type: "collection", id: 5 },
+ },
+ },
},
- },
+ ],
});
expect(
@@ -198,17 +228,21 @@ describe("AgentMessage", () => {
fetchMock.get("path:/api/collection/5", { status: 404 });
setupCardEndpoints(createMockCard({ id: 99, name: "Accounts by Day" }));
setup({
- id: "s1",
- role: "agent",
- type: "data_part",
- part: {
- type: "data-entity_saved",
- data: {
- chart_id: "chart-1",
- card_id: 99,
- destination: { type: "collection", id: 5 },
+ parts: [
+ {
+ id: "s1",
+ role: "agent",
+ type: "data_part",
+ part: {
+ type: "data-entity_saved",
+ data: {
+ chart_id: "chart-1",
+ card_id: 99,
+ destination: { type: "collection", id: 5 },
+ },
+ },
},
- },
+ ],
});
expect(await screen.findByText("Accounts by Day")).toBeInTheDocument();
@@ -220,17 +254,21 @@ describe("AgentMessage", () => {
setupDocumentEndpoints(createMockDocument({ id: 7, name: "Q3 report" }));
setupCardEndpoints(createMockCard({ id: 99, name: "Accounts by Day" }));
setup({
- id: "s1",
- role: "agent",
- type: "data_part",
- part: {
- type: "data-entity_saved",
- data: {
- chart_id: "chart-1",
- card_id: 99,
- destination: { type: "document", id: 7 },
+ parts: [
+ {
+ id: "s1",
+ role: "agent",
+ type: "data_part",
+ part: {
+ type: "data-entity_saved",
+ data: {
+ chart_id: "chart-1",
+ card_id: 99,
+ destination: { type: "document", id: 7 },
+ },
+ },
},
- },
+ ],
});
expect(await screen.findByText("Q3 report")).toBeInTheDocument();
@@ -238,16 +276,16 @@ describe("AgentMessage", () => {
});
});
- describe("turn_errored", () => {
+ describe("errored status", () => {
it("shows locked message for metabase_ai_managed_locked errors", () => {
setup({
- id: "msg",
- role: "agent",
- type: "turn_errored",
- error: { type: "metabase_ai_managed_locked" },
- display: {
- type: "locked",
- message: "You've used all of your included AI service tokens.",
+ status: {
+ type: "errored",
+ error: { type: "metabase_ai_managed_locked" },
+ display: {
+ type: "locked",
+ message: "You've used all of your included AI service tokens.",
+ },
},
});
@@ -266,13 +304,13 @@ describe("AgentMessage", () => {
it("shows the custom display message when provided", () => {
setup({
- id: "msg",
- role: "agent",
- type: "turn_errored",
- error: { type: "stream_error" },
- display: {
- type: "alert",
- message: "The model is overloaded, please try again.",
+ status: {
+ type: "errored",
+ error: { type: "stream_error" },
+ display: {
+ type: "alert",
+ message: "The model is overloaded, please try again.",
+ },
},
});
@@ -282,12 +320,7 @@ describe("AgentMessage", () => {
});
it("shows generic alert message when display message is missing", () => {
- setup({
- id: "msg",
- role: "agent",
- type: "turn_errored",
- error: { type: "stream_error" },
- });
+ setup({ status: { type: "errored", error: { type: "stream_error" } } });
expect(screen.getByText(/Something went wrong/)).toBeInTheDocument();
});
@@ -315,7 +348,7 @@ describe("AgentMessage", () => {
createMockMetabotConversationDetail({
conversation_id: conversationId,
messages: reloaded.map(([role, message]) =>
- textMessage(role, message),
+ createMockMetabotTextMessage(role, message),
),
}),
);
@@ -329,22 +362,14 @@ describe("AgentMessage", () => {
});
it("renders the raw error payload as a debug card when debug is true", () => {
- renderWithProviders(
- <AgentMessage
- debug
- readonly={false}
- conversationId="convo-1"
- hideActions
- setFeedbackMessage={() => {}}
- submittedFeedback={undefined}
- getCopyText={() => ""}
- message={{
- id: "msg",
- role: "agent",
- type: "turn_errored",
+ setup(
+ {
+ status: {
+ type: "errored",
error: { type: "stream_error", message: "boom" },
- }}
- />,
+ },
+ },
+ { debug: true },
);
const debugCard = screen.getByTestId(
@@ -355,19 +380,14 @@ describe("AgentMessage", () => {
});
});
- describe("turn_incomplete", () => {
- const incompleteMessage = (
- finishReason: MetabotAgentTurnIncompleteMessage["finishReason"],
- ): MetabotAgentTurnIncompleteMessage => ({
- id: "msg",
- role: "agent",
- type: "turn_incomplete",
- finishReason,
- });
+ describe("incomplete status", () => {
+ const incompleteStatus = (
+ finishReason: MetabotIncompleteFinishReason,
+ ): MetabotMessageStatus => ({ type: "incomplete", finishReason });
it("offers to continue a length-limited response", async () => {
const onContinue = jest.fn();
- setup(incompleteMessage("length"), { onContinue });
+ setup({ status: incompleteStatus("length") }, { onContinue });
expect(
screen.getByText(/was cut off because it hit the maximum length/),
@@ -380,7 +400,7 @@ describe("AgentMessage", () => {
it("offers to continue a step-limited response", async () => {
const onContinue = jest.fn();
- setup(incompleteMessage("tool-calls"), { onContinue });
+ setup({ status: incompleteStatus("tool-calls") }, { onContinue });
expect(
screen.getByText(/paused after reaching its step limit/),
@@ -393,7 +413,13 @@ describe("AgentMessage", () => {
it("shows a terminal notice when the context window is full", () => {
setup(
- { ...incompleteMessage("length"), contextWindowFull: true },
+ {
+ status: {
+ type: "incomplete",
+ finishReason: "length",
+ contextWindowFull: true,
+ },
+ },
{ onContinue: jest.fn() },
);
@@ -404,7 +430,12 @@ describe("AgentMessage", () => {
});
it("explains a content-filtered response without offering to continue", () => {
- setup(incompleteMessage("content-filter"), { onContinue: jest.fn() });
+ setup(
+ { status: incompleteStatus("content-filter") },
+ {
+ onContinue: jest.fn(),
+ },
+ );
expect(
screen.getByText(/was stopped by a content filter/),
@@ -413,7 +444,7 @@ describe("AgentMessage", () => {
});
it("falls back to a generic notice for other reasons", () => {
- setup(incompleteMessage("other"));
+ setup({ status: incompleteStatus("other") });
expect(
screen.getByText(/stopped before it finished/),
@@ -441,13 +472,10 @@ describe("UserMessage chart mentions", () => {
renderWithProviders(
<Messages
messages={[
- {
- id: "u1",
- role: "user",
- type: "text",
- message:
- "[Revenue by Product Category](metabase://chart/chart-1) test",
- },
+ createMockMetabotTextMessage(
+ "user",
+ "[Revenue by Product Category](metabase://chart/chart-1) test",
+ ),
]}
isDoingScience={false}
debug={false}
diff --git a/frontend/src/metabase/metabot/tests/convo-state.unit.spec.tsx b/frontend/src/metabase/metabot/tests/convo-state.unit.spec.tsx
index 7a4fc754b86..15a37fd097b 100644
--- a/frontend/src/metabase/metabot/tests/convo-state.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/tests/convo-state.unit.spec.tsx
@@ -1,11 +1,21 @@
import userEvent from "@testing-library/user-event";
-import _ from "underscore";
+import fetchMock from "fetch-mock";
+import {
+ createMockMetabotConversationDetail,
+ createMockMetabotMessage,
+ createMockMetabotTextMessage,
+ setupGetMetabotConversationEndpoint,
+} from "__support__/server-mocks/metabot";
import { act, waitFor } from "__support__/ui";
import {
attachAgentToConversation,
+ fetchConversationSnapshot,
+ getIsConversationProcessing,
+ getMessages,
getMetabotConversation,
getMetabotRequestState,
+ loadConversation,
} from "metabase/metabot/state";
import {
@@ -189,13 +199,14 @@ describe("metabot > convo state", () => {
await enterChatMessage("Who is your favorite?");
await waitFor(() => expect(agentSpy).toHaveBeenCalledTimes(1));
+ const firstReqBody = await lastReqBody(agentSpy);
hideMetabot(store.dispatch);
showMetabot(store.dispatch);
await enterChatMessage("Hi!");
const reqBody = await lastReqBody(agentSpy);
// the thread survives hide/show: the next request still points at the prior turn
- expect(reqBody.parent_message_id).toBe("msg_test_favorite");
+ expect(reqBody.parent_message_id).toBe(firstReqBody.assistant_message_id);
});
it("should start a new conversation when the new conversation button is clicked", async () => {
@@ -210,18 +221,16 @@ describe("metabot > convo state", () => {
]);
const beforeResetState = getState();
- expect(_.omit(beforeResetState.messages[0], ["id"])).toStrictEqual({
- role: "user",
- type: "text",
- message: "Who is your favorite?",
- });
- expect(
- _.omit(beforeResetState.messages[1], ["id", "externalId"]),
- ).toStrictEqual({
- role: "agent",
- type: "text",
- message: "You, but don't tell anyone.",
- });
+ expect(beforeResetState.messages).toMatchObject([
+ {
+ role: "user",
+ parts: [{ type: "text", message: "Who is your favorite?" }],
+ },
+ {
+ role: "agent",
+ parts: [{ type: "text", message: "You, but don't tell anyone." }],
+ },
+ ]);
await userEvent.click(await newConversationButton());
@@ -231,4 +240,81 @@ describe("metabot > convo state", () => {
);
expect(afterResetState.messages).toStrictEqual([]);
});
+
+ it("should refuse to load a conversation that is currently streaming", async () => {
+ const { store } = setup();
+ const [pause] = createPauses(1);
+ mockAgentEndpoint({
+ stream: createMockSSEStream(
+ (async function* () {
+ yield { type: "text-delta", id: "t1", delta: "live reply" };
+ await pause.promise;
+ yield { type: "finish", finishReason: "stop" };
+ })(),
+ ),
+ });
+
+ await enterChatMessage("hello");
+ await assertConversation([
+ ["user", "hello"],
+ ["agent", "live reply"],
+ ]);
+ const { conversationId } = getMetabotConversation(
+ store.getState(),
+ "omnibot",
+ );
+ setupGetMetabotConversationEndpoint(
+ createMockMetabotConversationDetail({
+ conversation_id: conversationId,
+ messages: [
+ createMockMetabotTextMessage("user", "hello"),
+ createMockMetabotMessage({ status: { type: "in_progress" } }),
+ ],
+ }),
+ );
+ const expectedError = {
+ message: `Cannot load conversation ${conversationId} while it is streaming`,
+ };
+
+ try {
+ await expect(
+ store.dispatch(fetchConversationSnapshot(conversationId)).unwrap(),
+ ).rejects.toMatchObject(expectedError);
+
+ act(() => {
+ store.dispatch(
+ attachAgentToConversation({
+ agentId: "omnibot",
+ conversationId: "some-other-conversation",
+ }),
+ );
+ });
+
+ await expect(
+ store
+ .dispatch(loadConversation({ agentId: "omnibot", conversationId }))
+ .unwrap(),
+ ).rejects.toMatchObject(expectedError);
+ expect(
+ getMetabotConversation(store.getState(), "omnibot").conversationId,
+ ).toBe("some-other-conversation");
+ expect(
+ fetchMock.callHistory.calls(
+ `path:/api/metabot/conversations/${conversationId}`,
+ ),
+ ).toHaveLength(0);
+ } finally {
+ pause.resolve();
+ }
+
+ await waitFor(() => {
+ expect(
+ getIsConversationProcessing(store.getState(), conversationId),
+ ).toBe(false);
+ });
+ expect(getMessages(store.getState(), conversationId).at(-1)).toMatchObject({
+ status: { type: "done" },
+ parts: [{ type: "text", message: "live reply" }],
+ });
+ });
});
diff --git a/frontend/src/metabase/metabot/tests/feedback.unit.spec.ts b/frontend/src/metabase/metabot/tests/feedback.unit.spec.ts
index de26bfe58de..c0472552b2f 100644
--- a/frontend/src/metabase/metabot/tests/feedback.unit.spec.ts
+++ b/frontend/src/metabase/metabot/tests/feedback.unit.spec.ts
@@ -6,6 +6,7 @@ import {
enterChatMessage,
feedbackModal,
lastChatMessage,
+ lastReqBody,
mockAgentEndpoint,
mockFeedbackEndpoint,
setup,
@@ -54,9 +55,12 @@ describe("metabot > feedback", () => {
it("should present the user an option to provide feedback", async () => {
setup();
const feedbackEndpoint = mockFeedbackEndpoint();
- mockAgentEndpoint({ events: whoIsYourFavoriteResponse });
+ const agentEndpoint = mockAgentEndpoint({
+ events: whoIsYourFavoriteResponse,
+ });
await enterChatMessage("Who is your favorite?");
+ const agentRequestBody = await lastReqBody(agentEndpoint);
const lastMessage = (await lastChatMessage())!;
expect(lastMessage).toHaveTextContent(/You, but don't tell anyone./);
@@ -72,7 +76,7 @@ describe("metabot > feedback", () => {
const body = await feedbackEndpoint.calls()[0].request?.json();
expect(body).toEqual({
metabot_id: expect.any(Number),
- message_id: "msg_test_favorite",
+ message_id: agentRequestBody.assistant_message_id,
positive: false,
freeform_feedback: "",
});
@@ -123,9 +127,12 @@ describe("metabot > feedback", () => {
it("should submit positive feedback", async () => {
setup();
const feedbackEndpoint = mockFeedbackEndpoint();
- mockAgentEndpoint({ events: whoIsYourFavoriteResponse });
+ const agentEndpoint = mockAgentEndpoint({
+ events: whoIsYourFavoriteResponse,
+ });
await enterChatMessage("Who is your favorite?");
+ const agentRequestBody = await lastReqBody(agentEndpoint);
const lastMessage = (await lastChatMessage())!;
await userEvent.click(await thumbsUp(lastMessage));
@@ -136,7 +143,7 @@ describe("metabot > feedback", () => {
const body = await feedbackEndpoint.calls()[0].request?.json();
expect(body).toEqual({
metabot_id: expect.any(Number),
- message_id: "msg_test_favorite",
+ message_id: agentRequestBody.assistant_message_id,
positive: true,
freeform_feedback: "",
});
diff --git a/frontend/src/metabase/metabot/tests/fork.unit.spec.ts b/frontend/src/metabase/metabot/tests/fork.unit.spec.ts
index 5e5d12fa97a..7369703c849 100644
--- a/frontend/src/metabase/metabot/tests/fork.unit.spec.ts
+++ b/frontend/src/metabase/metabot/tests/fork.unit.spec.ts
@@ -1,6 +1,9 @@
import userEvent from "@testing-library/user-event";
-import { createMockMetabotConversationDetail } from "__support__/server-mocks";
+import {
+ createMockMetabotConversationDetail,
+ createMockMetabotTextMessage,
+} from "__support__/server-mocks";
import { screen, waitFor, within } from "__support__/ui";
import { forkConversation } from "metabase/metabot/state";
import * as Urls from "metabase/urls";
@@ -13,6 +16,7 @@ import {
enterChatMessage,
forkButton,
lastChatMessage,
+ lastReqBody,
mockAgentEndpoint,
mockForkEndpoint,
setup,
@@ -25,46 +29,43 @@ const forkedConversation = createMockMetabotConversationDetail({
title: null,
forked_from_conversation_id: "original-convo-id",
messages: [
- {
- id: "m1",
- role: "user",
- type: "text",
- message: "Who is your favorite?",
+ createMockMetabotTextMessage("user", "Who is your favorite?", {
externalId: "u1",
- },
- {
- id: "m2",
- role: "agent",
- type: "text",
- message: "You, but don't tell anyone.",
+ }),
+ createMockMetabotTextMessage("agent", "You, but don't tell anyone.", {
externalId: "msg_test_favorite",
- finished: true,
- },
+ }),
],
});
const setupWithReply = async () => {
const { store } = setup();
- mockAgentEndpoint({ events: whoIsYourFavoriteResponse });
+ const agentEndpoint = mockAgentEndpoint({
+ events: whoIsYourFavoriteResponse,
+ });
await enterChatMessage("Who is your favorite?");
+ const agentRequestBody = await lastReqBody(agentEndpoint);
const lastMessage = (await lastChatMessage())!;
- return { store, lastMessage };
+ return {
+ store,
+ lastMessage,
+ assistantMessageId: agentRequestBody.assistant_message_id,
+ };
};
describe("metabot > fork", () => {
it("forks the conversation from an assistant message", async () => {
- const { store, lastMessage } = await setupWithReply();
+ const { store, lastMessage, assistantMessageId } = await setupWithReply();
const forkEndpoint = mockForkEndpoint(forkedConversation);
await userEvent.click(await forkButton(lastMessage));
- await waitFor(() =>
- expect(
- forkEndpoint.calls({ body: { message_id: "msg_test_favorite" } }),
- ).toHaveLength(1),
- );
+ await waitFor(() => expect(forkEndpoint.calls()).toHaveLength(1));
+ expect(await forkEndpoint.calls()[0].request?.json()).toEqual({
+ message_id: assistantMessageId,
+ });
await waitFor(() =>
expect(conversationIdForAgent(store)).toBe("forked-convo-id"),
diff --git a/frontend/src/metabase/metabot/tests/multi-convo.unit.spec.tsx b/frontend/src/metabase/metabot/tests/multi-convo.unit.spec.tsx
index bacba5cb53c..001d2cd84b0 100644
--- a/frontend/src/metabase/metabot/tests/multi-convo.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/tests/multi-convo.unit.spec.tsx
@@ -123,12 +123,12 @@ describe("multi-convo support", () => {
// ASSERT
expect(convoForAgent(store, "test_1").messages).toMatchObject([
- { message: "test1", role: "user", type: "text" },
- { message: "Test 1 response", role: "agent", type: "text" },
+ { role: "user", parts: [{ type: "text", message: "test1" }] },
+ { role: "agent", parts: [{ type: "text", message: "Test 1 response" }] },
]);
expect(convoForAgent(store, "test_2").messages).toMatchObject([
- { message: "test2", role: "user", type: "text" },
- { message: "Test 2 response", role: "agent", type: "text" },
+ { role: "user", parts: [{ type: "text", message: "test2" }] },
+ { role: "agent", parts: [{ type: "text", message: "Test 2 response" }] },
]);
});
diff --git a/frontend/src/metabase/metabot/tests/query-builder-code-edit.unit.spec.tsx b/frontend/src/metabase/metabot/tests/query-builder-code-edit.unit.spec.tsx
index 4f6096803bc..6fc89a36121 100644
--- a/frontend/src/metabase/metabot/tests/query-builder-code-edit.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/tests/query-builder-code-edit.unit.spec.tsx
@@ -1,4 +1,5 @@
import type { ThunkDispatch, UnknownAction } from "@reduxjs/toolkit";
+import userEvent from "@testing-library/user-event";
import fetchMock from "fetch-mock";
import { assocIn } from "icepick";
@@ -10,7 +11,9 @@ import {
aiStreamingQuery,
findMatchingInflightAiStreamingRequests,
} from "metabase/api/ai-streaming";
+import { Messages } from "metabase/metabot/components/MetabotChat/MetabotChatMessage";
import { useInlineSQLPrompt } from "metabase/metabot/components/MetabotInlineSQLPrompt";
+import { useMetabotAgent } from "metabase/metabot/hooks";
import { getMetadata } from "metabase/metadata-store";
import type { State } from "metabase/redux/store";
import { createMockState } from "metabase/redux/store/mocks";
@@ -64,6 +67,19 @@ const QuerySuggestionProbe = ({ question }: { question: Question }) => {
return <div data-testid="qb-proposed-sql">{proposedSql}</div>;
};
+const ChatMessagesProbe = () => {
+ const { conversationId, messages } = useMetabotAgent("omnibot");
+
+ return (
+ <Messages
+ messages={messages}
+ isDoingScience={false}
+ debug={false}
+ conversationId={conversationId}
+ />
+ );
+};
+
describe("query builder code edits from omnibot", () => {
beforeEach(() => {
setupEnterprisePlugins();
@@ -73,6 +89,20 @@ describe("query builder code edits from omnibot", () => {
"path:/api/metabot/permissions/user-permissions",
createMockUserMetabotPermissions(),
);
+ fetchMock.post("path:/api/llm/extract-sources", {
+ tables: [
+ {
+ id: 2,
+ name: "ORDERS",
+ schema: "PUBLIC",
+ display_name: "Orders",
+ description: null,
+ columns: [],
+ },
+ ],
+ card_ids: [],
+ });
+ fetchMock.get(`path:/api/database/${TEST_DB.id}`, TEST_DB);
});
afterEach(() => {
@@ -126,6 +156,7 @@ describe("query builder code edits from omnibot", () => {
const { store } = renderWithProviders(
<MetabotProvider>
<QuerySuggestionProbe question={question} />
+ <ChatMessagesProbe />
</MetabotProvider>,
{
storeInitialState: storeInitialState,
@@ -145,6 +176,7 @@ describe("query builder code edits from omnibot", () => {
sendAgentRequest({
message: "Please rewrite this query",
conversation_id: convo.conversationId,
+ assistant_message_id: "msg_test_code_edit",
isFullPageMetabot: false,
context: {
user_is_viewing: [
@@ -179,20 +211,30 @@ describe("query builder code edits from omnibot", () => {
});
expect(
- typedStore.getState().metabot.conversations[conversationId]?.messages,
- ).toEqual(
- expect.arrayContaining([
- expect.objectContaining({
- type: "text",
- externalId: "msg_test_code_edit",
- }),
+ typedStore
+ .getState()
+ .metabot.conversations[conversationId]?.messages.at(-1),
+ ).toMatchObject({
+ role: "agent",
+ externalId: "msg_test_code_edit",
+ parts: expect.arrayContaining([
+ expect.objectContaining({ type: "text" }),
expect.objectContaining({
type: "data_part",
- externalId: "msg_test_code_edit",
part: expect.objectContaining({ type: "data-code_edit" }),
}),
]),
+ });
+ fetchMock.post("path:/api/metabot/source-feedback", 200);
+ await userEvent.click(
+ await screen.findByRole("button", { name: "Source is correct" }),
);
+ const feedbackRequest = fetchMock.callHistory.lastCall(
+ "path:/api/metabot/source-feedback",
+ )?.options;
+ expect(JSON.parse(String(feedbackRequest?.body))).toMatchObject({
+ message_id: "msg_test_code_edit",
+ });
expect(requestBody?.context).toEqual(
expect.objectContaining({
diff --git a/frontend/src/metabase/metabot/tests/reducer.unit.spec.ts b/frontend/src/metabase/metabot/tests/reducer.unit.spec.ts
index bf8260d5468..306c4a46644 100644
--- a/frontend/src/metabase/metabot/tests/reducer.unit.spec.ts
+++ b/frontend/src/metabase/metabot/tests/reducer.unit.spec.ts
@@ -14,6 +14,7 @@ import type { MetabotSuggestedTransform } from "metabase-types/api";
import { createMockTransform } from "metabase-types/api/mocks/transform";
import { METABOT_PROFILE_OVERRIDES } from "../constants";
+import { sendAgentRequest } from "../state/actions";
import {
createConversation,
getMetabotInitialState,
@@ -24,6 +25,7 @@ import {
conversationIdForAgent,
convoForAgent,
createTestMetabotState,
+ startRequestlessAgentTurn,
testConversationId,
} from "./utils";
@@ -50,6 +52,14 @@ const requestAction = (arg: Partial<{ conversation_id: string }> = {}) => ({
meta: { arg: { conversation_id: "matching-id", ...arg } },
});
+// tool-call and chain-of-thought events only ever arrive inside a message the
+// stream has already opened
+const createStreamingStore = () => {
+ const store = createTestStore();
+ startRequestlessAgentTurn(store, testConversationId("omnibot"));
+ return store;
+};
+
describe("metabot reducer", () => {
describe("transforms", () => {
describe("addSuggestedTransform", () => {
@@ -434,15 +444,34 @@ describe("metabot reducer", () => {
});
});
+ it("settles an aborted rejection that carries no payload", () => {
+ const conversationId = testConversationId("omnibot");
+ const store = createTestStore();
+ startRequestlessAgentTurn(store, conversationId);
+
+ store.dispatch({
+ type: sendAgentRequest.rejected.type,
+ error: { message: "Aborted" },
+ meta: {
+ aborted: true,
+ arg: { conversation_id: conversationId },
+ },
+ });
+
+ expect(convoForAgent(store, "omnibot").messages.at(-1)?.status).toEqual({
+ type: "aborted",
+ });
+ });
+
describe("tool calls", () => {
const conversationId = testConversationId("omnibot");
const getToolCallMessages = (store: ReturnType<typeof createTestStore>) =>
- convoForAgent(store, "omnibot").messages.filter(
- (m) => m.type === "tool_call",
- );
+ convoForAgent(store, "omnibot")
+ .messages.flatMap((t) => t.parts)
+ .filter((p) => p.type === "tool_call");
it("toolCallStart is idempotent for the same toolCallId", () => {
- const store = createTestStore();
+ const store = createStreamingStore();
store.dispatch(
metabotActions.toolCallStart({
conversationId,
@@ -464,7 +493,7 @@ describe("metabot reducer", () => {
});
it("toolCallArgs updates the existing tool-call message when toolCallStart preceded it", () => {
- const store = createTestStore();
+ const store = createStreamingStore();
store.dispatch(
metabotActions.toolCallStart({
conversationId,
@@ -494,7 +523,7 @@ describe("metabot reducer", () => {
});
it("toolCallArgs creates a tool-call message when no tool-input-start preceded it", () => {
- const store = createTestStore();
+ const store = createStreamingStore();
store.dispatch(
metabotActions.toolCallArgs({
conversationId,
@@ -517,7 +546,7 @@ describe("metabot reducer", () => {
});
it("toolCallEnd marks the tool-call message as errored", () => {
- const store = createTestStore();
+ const store = createStreamingStore();
store.dispatch(
metabotActions.toolCallStart({
conversationId,
@@ -555,10 +584,12 @@ describe("metabot reducer", () => {
const getConvo = (store: ReturnType<typeof createTestStore>) =>
convoForAgent(store, "omnibot");
const getChain = (store: ReturnType<typeof createTestStore>) =>
- getConvo(store).messages.find((m) => m.type === "chain_of_thought");
+ getConvo(store)
+ .messages.flatMap((t) => t.parts)
+ .find((p) => p.type === "chain_of_thought");
it("accumulates reasoning deltas into one chain step", () => {
- const store = createTestStore();
+ const store = createStreamingStore();
store.dispatch(metabotActions.reasoningStart({ conversationId }));
store.dispatch(
metabotActions.reasoningDelta({ conversationId, text: "Think" }),
@@ -571,11 +602,11 @@ describe("metabot reducer", () => {
expect(chain?.type === "chain_of_thought" && chain.steps).toEqual([
{ kind: "reasoning", text: "Thinking" },
]);
- expect(getConvo(store)?.activeChainId).toBe(chain?.id);
+ expect(chain?.finished).toBe(false);
});
it("interleaves tool calls between reasoning blocks in order", () => {
- const store = createTestStore();
+ const store = createStreamingStore();
store.dispatch(metabotActions.reasoningStart({ conversationId }));
store.dispatch(
metabotActions.reasoningDelta({ conversationId, text: "look" }),
@@ -601,7 +632,7 @@ describe("metabot reducer", () => {
});
it("marks a tool step ended when its result arrives", () => {
- const store = createTestStore();
+ const store = createStreamingStore();
store.dispatch(
metabotActions.toolCallStart({
conversationId,
@@ -624,7 +655,7 @@ describe("metabot reducer", () => {
});
it("persists the chain but closes it when the answer text starts", () => {
- const store = createTestStore();
+ const store = createStreamingStore();
store.dispatch(metabotActions.reasoningStart({ conversationId }));
store.dispatch(
metabotActions.reasoningDelta({ conversationId, text: "hmm" }),
@@ -635,18 +666,18 @@ describe("metabot reducer", () => {
// the chain message stays in history, and its id is released
expect(getChain(store)).toBeDefined();
- expect(getConvo(store)?.activeChainId).toBeUndefined();
+ expect(getChain(store)?.finished).toBe(true);
// later reasoning starts a fresh chain after the answer text
store.dispatch(metabotActions.reasoningStart({ conversationId }));
- const chains = getConvo(store)?.messages.filter(
- (m) => m.type === "chain_of_thought",
- );
+ const chains = getConvo(store)
+ ?.messages.flatMap((t) => t.parts)
+ .filter((p) => p.type === "chain_of_thought");
expect(chains).toHaveLength(2);
});
it("attaches search results to their tool step, even after the chain closed", () => {
- const store = createTestStore();
+ const store = createStreamingStore();
store.dispatch(
metabotActions.toolCallStart({
conversationId,
@@ -673,7 +704,7 @@ describe("metabot reducer", () => {
});
it("stamps a save_entity step title from its saved-entity data part", () => {
- const store = createTestStore();
+ const store = createStreamingStore();
store.dispatch(
metabotActions.toolCallStart({
conversationId,
@@ -704,7 +735,7 @@ describe("metabot reducer", () => {
});
it("backfills a title arriving on tool-input-available", () => {
- const store = createTestStore();
+ const store = createStreamingStore();
store.dispatch(
metabotActions.toolCallStart({
conversationId,
@@ -738,6 +769,7 @@ describe("metabot reducer", () => {
}),
},
});
+ startRequestlessAgentTurn(store, conversationId);
store.dispatch(metabotActions.reasoningStart({ conversationId }));
store.dispatch(
metabotActions.setConversationSnapshot({
@@ -746,7 +778,7 @@ describe("metabot reducer", () => {
}),
);
- expect(getConvo(store)?.activeChainId).toBeUndefined();
+ expect(getConvo(store)?.messages).toEqual([]);
expect(getConvo(store)?.lastTokenUsage).toBeUndefined();
});
});
diff --git a/frontend/src/metabase/metabot/tests/retry.unit.spec.tsx b/frontend/src/metabase/metabot/tests/retry.unit.spec.tsx
index 9d3b44656e1..1f9c658a480 100644
--- a/frontend/src/metabase/metabot/tests/retry.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/tests/retry.unit.spec.tsx
@@ -1,5 +1,6 @@
import type { ThunkDispatch, UnknownAction } from "@reduxjs/toolkit";
import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
import { assocIn } from "icepick";
import { act, screen, waitFor, within } from "__support__/ui";
@@ -37,18 +38,8 @@ const emptyContext = {
capabilities: [],
};
-const turnEvents = (opts: {
- messageId: string;
- userMessageId?: string;
- text: string;
-}): SSEEvent[] => [
- {
- type: "start",
- messageId: opts.messageId,
- ...(opts.userMessageId
- ? { messageMetadata: { userMessageId: opts.userMessageId } }
- : {}),
- },
+const turnEvents = (opts: { messageId: string; text: string }): SSEEvent[] => [
+ { type: "start", messageId: opts.messageId },
{ type: "text-start", id: "t1" },
{ type: "text-delta", id: "t1", delta: opts.text },
{ type: "text-end", id: "t1" },
@@ -79,18 +70,17 @@ describe("metabot > retry", () => {
const firstSpy = mockAgentEndpoint({
events: turnEvents({
messageId: "msg_1",
- userMessageId: "user_msg_1",
text: "first reply",
}),
});
await enterChatMessage("first prompt");
expect(await screen.findByText("first reply")).toBeInTheDocument();
- expect((await lastReqBody(firstSpy)).profile_id).toBe("nlq");
+ const firstBody = await lastReqBody(firstSpy);
+ expect(firstBody.profile_id).toBe("nlq");
const retrySpy = mockAgentEndpoint({
events: turnEvents({
messageId: "msg_2",
- userMessageId: "user_msg_1",
text: "regenerated reply",
}),
});
@@ -100,7 +90,7 @@ describe("metabot > retry", () => {
const retryBody = await lastReqBody(retrySpy);
expect(retryBody.profile_id).toBe("nlq");
- expect(retryBody.retry_message_id).toBe("user_msg_1");
+ expect(retryBody.retry_message_id).toBe(firstBody.user_message_id);
});
it("should send an explicit profile on both the original prompt and the retry", async () => {
@@ -116,7 +106,6 @@ describe("metabot > retry", () => {
const firstSpy = mockAgentEndpoint({
events: turnEvents({
messageId: "msg_1",
- userMessageId: "user_msg_1",
text: "first reply",
}),
});
@@ -131,7 +120,8 @@ describe("metabot > retry", () => {
}),
);
});
- expect((await lastReqBody(firstSpy)).profile_id).toBe("explorations");
+ const firstBody = await lastReqBody(firstSpy);
+ expect(firstBody.profile_id).toBe("explorations");
const messageId = checkNotNull(
getMessages(store.getState(), conversationId).at(-1),
@@ -140,7 +130,6 @@ describe("metabot > retry", () => {
const retrySpy = mockAgentEndpoint({
events: turnEvents({
messageId: "msg_2",
- userMessageId: "user_msg_1",
text: "regenerated reply",
}),
});
@@ -157,7 +146,7 @@ describe("metabot > retry", () => {
const retryBody = await lastReqBody(retrySpy);
expect(retryBody.profile_id).toBe("explorations");
- expect(retryBody.retry_message_id).toBe("user_msg_1");
+ expect(retryBody.retry_message_id).toBe(firstBody.user_message_id);
});
it("should show retry option for error messages", async () => {
@@ -252,7 +241,6 @@ describe("metabot > retry", () => {
events: [
...turnEvents({
messageId: "msg_1",
- userMessageId: "user_msg_1",
text: "first reply",
}).slice(0, -1),
{ type: "data-state", data: { todos: [{ id: "a" }] } },
@@ -267,7 +255,6 @@ describe("metabot > retry", () => {
events: [
...turnEvents({
messageId: "msg_2",
- userMessageId: "user_msg_2",
text: "second reply",
}).slice(0, -1),
{ type: "data-state", data: { todos: [{ id: "b" }] } },
@@ -283,7 +270,6 @@ describe("metabot > retry", () => {
mockAgentEndpoint({
events: turnEvents({
messageId: "msg_3",
- userMessageId: "user_msg_2",
text: "regenerated reply",
}),
});
@@ -295,22 +281,18 @@ describe("metabot > retry", () => {
expect(getConvoReqState()).toEqual({ todos: [{ id: "a" }] });
});
- it("should stamp the user message with the start event's userMessageId", async () => {
+ it("should stamp the user message with the id it sent", async () => {
const { store } = setup();
- mockAgentEndpoint({
- events: turnEvents({
- messageId: "msg_1",
- userMessageId: "user_msg_1",
- text: "hello!",
- }),
+ const spy = mockAgentEndpoint({
+ events: turnEvents({ messageId: "msg_1", text: "hello!" }),
});
await enterChatMessage("hi");
expect(await screen.findByText("hello!")).toBeInTheDocument();
const convo = getMetabotConversation(store.getState(), "omnibot");
- expect(convo.messages.find((m) => m.role === "user")).toMatchObject({
- externalId: "user_msg_1",
+ expect(convo.messages.find((t) => t.role === "user")).toMatchObject({
+ externalId: (await lastReqBody(spy)).user_message_id,
});
});
@@ -319,22 +301,18 @@ describe("metabot > retry", () => {
mockAgentEndpoint({
events: turnEvents({
messageId: "msg_1",
- userMessageId: "user_msg_1",
text: "first reply",
}),
});
await enterChatMessage("first prompt");
expect(await screen.findByText("first reply")).toBeInTheDocument();
- mockAgentEndpoint({
- events: turnEvents({
- messageId: "msg_2",
- userMessageId: "user_msg_2",
- text: "second reply",
- }),
+ const secondSpy = mockAgentEndpoint({
+ events: turnEvents({ messageId: "msg_2", text: "second reply" }),
});
await enterChatMessage("second prompt");
expect(await screen.findByText("second reply")).toBeInTheDocument();
+ const secondBody = await lastReqBody(secondSpy);
const retrySpy = mockAgentEndpoint({ events: [] });
const messages = await chatMessages();
@@ -343,26 +321,23 @@ describe("metabot > retry", () => {
);
const body = await lastReqBody(retrySpy);
- expect(body.retry_message_id).toBe("user_msg_2");
- expect(body.user_message_id).toBe("user_msg_2");
+ expect(body.retry_message_id).toBe(secondBody.user_message_id);
+ expect(body.user_message_id).toBe(secondBody.user_message_id);
expect(body.parent_message_id).toBeUndefined();
expect(body.message).toBe("second prompt");
});
it("should send retry_message_id when retrying an errored turn", async () => {
setup();
- mockAgentEndpoint({
+ const firstSpy = mockAgentEndpoint({
events: [
- {
- type: "start",
- messageId: "msg_err",
- messageMetadata: { userMessageId: "user_msg_err" },
- },
+ { type: "start", messageId: "msg_err" },
{ type: "error", errorText: "boom" },
],
});
await enterChatMessage("first prompt");
expect(await screen.findByText(/Something went wrong/)).toBeInTheDocument();
+ const firstBody = await lastReqBody(firstSpy);
const retrySpy = mockAgentEndpoint({ events: [] });
await userEvent.click(
@@ -370,21 +345,17 @@ describe("metabot > retry", () => {
);
const body = await lastReqBody(retrySpy);
- expect(body.retry_message_id).toBe("user_msg_err");
+ expect(body.retry_message_id).toBe(firstBody.user_message_id);
expect(body.parent_message_id).toBeUndefined();
});
it("should send retry_message_id when retrying an aborted turn", async () => {
setup();
const [pause] = createPauses(1);
- mockAgentEndpoint({
+ const firstSpy = mockAgentEndpoint({
stream: createMockSSEStream(
(async function* () {
- yield {
- type: "start",
- messageId: "msg_aborted",
- messageMetadata: { userMessageId: "user_msg_aborted" },
- };
+ yield { type: "start", messageId: "msg_aborted" };
yield { type: "text-start", id: "t1" };
yield { type: "text-delta", id: "t1", delta: "Let me think" };
await pause.promise;
@@ -406,10 +377,12 @@ describe("metabot > retry", () => {
);
const body = await lastReqBody(retrySpy);
- expect(body.retry_message_id).toBe("user_msg_aborted");
+ expect(body.retry_message_id).toBe(
+ (await lastReqBody(firstSpy)).user_message_id,
+ );
});
- it("should retry with the minted user id when aborted before the start event", async () => {
+ it("should retry with the minted user id when aborted before any response", async () => {
setup();
const [pause] = createPauses(1);
const firstSpy = mockAgentEndpoint({
@@ -440,13 +413,14 @@ describe("metabot > retry", () => {
expect(body.retry_message_id).toBe(firstReqBody.user_message_id);
});
- it("should fall back to a plain send when the failed turn has no userMessageId", async () => {
+ it("should fall back to a plain send when the request failed before the server started the turn", async () => {
setup();
- mockAgentEndpoint({
- events: [{ type: "error", errorText: "boom" }],
+ fetchMock.post(`path:/api/metabot/agent-streaming`, {
+ status: 500,
+ body: { message: "boom" },
});
await enterChatMessage("first prompt");
- expect(await screen.findByText(/Something went wrong/)).toBeInTheDocument();
+ expect(await screen.findByText(/boom/)).toBeInTheDocument();
const retrySpy = mockAgentEndpoint({ events: [] });
await userEvent.click(
diff --git a/frontend/src/metabase/metabot/tests/threading.unit.spec.tsx b/frontend/src/metabase/metabot/tests/threading.unit.spec.tsx
index ab61c0e618e..a76bdbeca09 100644
--- a/frontend/src/metabase/metabot/tests/threading.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/tests/threading.unit.spec.tsx
@@ -90,18 +90,21 @@ describe("metabot > threading", () => {
await enterChatMessage("Are you sure?");
second.sendResponse();
expect(await screen.findByText("Sure.")).toBeInTheDocument();
+ const secondReqBody = await lastReqBody(second);
const agentSpy = mockAgentEndpoint({ events: [] });
await enterChatMessage("Hi again!");
const reqBody = await lastReqBody(agentSpy);
- expect(reqBody?.parent_message_id).toBe("msg_second_turn");
+ expect(reqBody?.parent_message_id).toBe(
+ secondReqBody?.assistant_message_id,
+ );
});
it("should send the aborted turn's message id as parent_message_id on the next message", async () => {
setup();
const [pause] = createPauses(1);
- mockAgentEndpoint({
+ const firstSpy = mockAgentEndpoint({
stream: createMockSSEStream(
(async function* () {
yield { type: "start", messageId: "msg_aborted_turn" };
@@ -119,18 +122,19 @@ describe("metabot > threading", () => {
screen.queryByTestId("metabot-stop-response"),
).not.toBeInTheDocument();
});
+ const firstReqBody = await lastReqBody(firstSpy);
const agentSpy = mockAgentEndpoint({ events: [] });
await enterChatMessage("Nevermind, hi!");
const reqBody = await lastReqBody(agentSpy);
- expect(reqBody?.parent_message_id).toBe("msg_aborted_turn");
+ expect(reqBody?.parent_message_id).toBe(firstReqBody?.assistant_message_id);
});
it("should thread onto the prior successful turn after an errored turn is rewound", async () => {
setup();
// a first successful turn establishes the pointer to fall back to
- mockAgentEndpoint({
+ const first = mockAgentEndpoint({
events: [
{ type: "start", messageId: "msg_good_turn" },
{ type: "text-start", id: "t1" },
@@ -141,6 +145,7 @@ describe("metabot > threading", () => {
});
await enterChatMessage("first prompt");
expect(await screen.findByText("First answer.")).toBeInTheDocument();
+ const firstReqBody = await lastReqBody(first);
// a second turn fails at the stream level
mockAgentEndpoint({ events: erroredResponse });
@@ -152,6 +157,6 @@ describe("metabot > threading", () => {
const agentSpy = mockAgentEndpoint({ events: [] });
await enterChatMessage("third prompt");
const reqBody = await lastReqBody(agentSpy);
- expect(reqBody?.parent_message_id).toBe("msg_good_turn");
+ expect(reqBody?.parent_message_id).toBe(firstReqBody?.assistant_message_id);
});
});
diff --git a/frontend/src/metabase/metabot/tests/tool-calls.unit.spec.tsx b/frontend/src/metabase/metabot/tests/tool-calls.unit.spec.tsx
index ea98a37fd0a..7ebf7c165e6 100644
--- a/frontend/src/metabase/metabot/tests/tool-calls.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/tests/tool-calls.unit.spec.tsx
@@ -240,7 +240,7 @@ describe("metabot > tool calls", () => {
pause1.resolve();
await waitFor(() => {
const { messages } = getMetabotConversation(store.getState(), "omnibot");
- expect(messages).toContainEqual(
+ expect(messages.flatMap((t) => t.parts)).toContainEqual(
expect.objectContaining({
type: "tool_call",
status: "ended",
diff --git a/frontend/src/metabase/metabot/tests/ui.unit.spec.tsx b/frontend/src/metabase/metabot/tests/ui.unit.spec.tsx
index 62206373778..c42aa8e1599 100644
--- a/frontend/src/metabase/metabot/tests/ui.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/tests/ui.unit.spec.tsx
@@ -5,6 +5,7 @@ import { assocIn } from "icepick";
import {
createMockMetabotConversationDetail,
+ createMockMetabotTextMessage,
setupGetMetabotConversationEndpoint,
setupGetMetabotConversationEndpointError,
} from "__support__/server-mocks";
@@ -649,18 +650,8 @@ describe("metabot > ui", () => {
conversation_id: PAST_CONVERSATION_ID,
title: "Orders by month",
messages: [
- {
- id: "u1",
- role: "user",
- type: "text",
- message: "How many orders?",
- },
- {
- id: "a1",
- role: "agent",
- type: "text",
- message: "There are 42 orders.",
- },
+ createMockMetabotTextMessage("user", "How many orders?"),
+ createMockMetabotTextMessage("agent", "There are 42 orders."),
],
}),
);
@@ -715,12 +706,7 @@ describe("metabot > ui", () => {
metabotActions.setConversationSnapshot({
conversationId: "current-conversation",
messages: [
- {
- id: "current-user",
- role: "user",
- type: "text",
- message: "Current question",
- },
+ createMockMetabotTextMessage("user", "Current question"),
],
activeToolCalls: [],
}),
diff --git a/frontend/src/metabase/metabot/tests/utils.tsx b/frontend/src/metabase/metabot/tests/utils.tsx
index ac44f9178e1..7a9cf557516 100644
--- a/frontend/src/metabase/metabot/tests/utils.tsx
+++ b/frontend/src/metabase/metabot/tests/utils.tsx
@@ -52,6 +52,7 @@ import {
metabotReducer,
setVisible,
} from "../state";
+import { sendAgentRequest } from "../state/actions";
import {
createAgentState,
createConversationForAgent,
@@ -78,6 +79,22 @@ export const convoForAgent = (
agentId: MetabotAgentId = "omnibot",
) => convoIn(store.getState().metabot, conversationIdForAgent(store, agentId));
+// starts turns without making an API request
+export const startRequestlessAgentTurn = (
+ store: { dispatch: (action: unknown) => unknown },
+ conversationId: string,
+ assistantMessageId?: string,
+) =>
+ store.dispatch({
+ type: sendAgentRequest.pending.type,
+ meta: {
+ arg: {
+ conversation_id: conversationId,
+ assistant_message_id: assistantMessageId,
+ },
+ },
+ });
+
// make ids easer to address than production's random uuids
export const testConversationId = (agentId: MetabotAgentId) =>
`convo-${agentId}`;
diff --git a/frontend/src/metabase/metabot/utils/message-tree.ts b/frontend/src/metabase/metabot/utils/message-tree.ts
index 1202bf41f3e..7de49ac0306 100644
--- a/frontend/src/metabase/metabot/utils/message-tree.ts
+++ b/frontend/src/metabase/metabot/utils/message-tree.ts
@@ -1,15 +1,10 @@
-import type { MetabotChatMessage } from "metabase/metabot/state/types";
+import type { MetabotMessage } from "metabase/metabot/state/types";
-import {
- type FetchedChatMessage,
- normalizeFetchedChatMessages,
-} from "./normalize-fetched-chat-messages";
-
-export type ParentedChatMessage = FetchedChatMessage & {
+export type ParentedMessage = MetabotMessage & {
parent_message_id: string | null;
};
-type BranchIndex = Map<string | null, ParentedChatMessage[]>;
+type BranchIndex = Map<string | null, ParentedMessage[]>;
type SelectedReplyByParentId = Record<string, string>;
@@ -21,12 +16,12 @@ type ResponseBranch = {
replyIds: string[];
};
-type ActiveResponse = {
- messages: MetabotChatMessage[];
+export type ActiveResponse = {
+ message: MetabotMessage;
branch: ResponseBranch | null;
};
-function indexChildrenByParent(messages: ParentedChatMessage[]): BranchIndex {
+function indexChildrenByParent(messages: ParentedMessage[]): BranchIndex {
const index: BranchIndex = new Map();
for (const message of messages) {
const siblings = index.get(message.parent_message_id);
@@ -42,8 +37,8 @@ function indexChildrenByParent(messages: ParentedChatMessage[]): BranchIndex {
function activePath(
index: BranchIndex,
selectedReplyByParentId: SelectedReplyByParentId,
-): ParentedChatMessage[] {
- const path: ParentedChatMessage[] = [];
+): ParentedMessage[] {
+ const path: ParentedMessage[] = [];
let parentId: string | null = null;
while (true) {
@@ -55,7 +50,7 @@ function activePath(
const selectedId: string | undefined =
selectedReplyByParentId[parentId ?? ROOT_KEY];
// Siblings arrive oldest first; default to the newest.
- const node: ParentedChatMessage =
+ const node: ParentedMessage =
siblings.find(({ id }) => id === selectedId) ??
siblings[siblings.length - 1];
path.push(node);
@@ -64,46 +59,29 @@ function activePath(
}
export function activeResponses(
- messages: ParentedChatMessage[],
+ messages: ParentedMessage[],
selectedReplyByParentId: SelectedReplyByParentId,
- { isSlack }: { isSlack: boolean },
): ActiveResponse[] {
const index = indexChildrenByParent(messages);
const path = activePath(index, selectedReplyByParentId);
- return groupIntoResponses(path).map((response) => ({
- messages: normalizeFetchedChatMessages(response, { isSlack }),
- branch: branchAt(index, response),
+ return path.map((message) => ({
+ message,
+ branch: branchAt(index, message),
}));
}
-function groupIntoResponses(
- path: ParentedChatMessage[],
-): ParentedChatMessage[][] {
- const responses: ParentedChatMessage[][] = [];
- for (const node of path) {
- const current = responses.at(-1);
- if (current?.[0].role === "agent" && node.role === "agent") {
- current.push(node);
- } else {
- responses.push([node]);
- }
- }
- return responses;
-}
-
function branchAt(
index: BranchIndex,
- response: ParentedChatMessage[],
+ message: ParentedMessage,
): ResponseBranch | null {
- const head = response[0];
- const siblings = index.get(head.parent_message_id) ?? [];
+ const siblings = index.get(message.parent_message_id) ?? [];
if (siblings.length < 2) {
return null;
}
return {
- parentId: head.parent_message_id ?? ROOT_KEY,
- currentIndex: siblings.findIndex(({ id }) => id === head.id),
+ parentId: message.parent_message_id ?? ROOT_KEY,
+ currentIndex: siblings.findIndex(({ id }) => id === message.id),
replyIds: siblings.map(({ id }) => id),
};
}
diff --git a/frontend/src/metabase/metabot/utils/message-tree.unit.spec.ts b/frontend/src/metabase/metabot/utils/message-tree.unit.spec.ts
index 62e1f59ef20..3bd2236a1dd 100644
--- a/frontend/src/metabase/metabot/utils/message-tree.unit.spec.ts
+++ b/frontend/src/metabase/metabot/utils/message-tree.unit.spec.ts
@@ -1,27 +1,22 @@
-import { type ParentedChatMessage, activeResponses } from "./message-tree";
-
-function user(id: string, parentId: string | null): ParentedChatMessage {
- return {
- id,
- parent_message_id: parentId,
- role: "user",
- type: "text",
- message: id,
- };
-}
-
-function agent(id: string, parentId: string | null): ParentedChatMessage {
- return {
- id,
- parent_message_id: parentId,
- role: "agent",
- type: "text",
- message: id,
- externalId: id,
- };
-}
-
-const regenerated: ParentedChatMessage[] = [
+import {
+ createMockMetabotTextPart,
+ createMockMetabotToolCallPart,
+ createMockParentedMessage,
+} from "__support__/server-mocks";
+import type { MetabotMessage } from "metabase/metabot/state/types";
+
+import { type ParentedMessage, activeResponses } from "./message-tree";
+
+const user = (id: string, parentId: string | null) =>
+ createMockParentedMessage(id, parentId, { role: "user" });
+
+const agent = (
+ id: string,
+ parentId: string | null,
+ overrides?: Partial<Omit<MetabotMessage, "id">>,
+) => createMockParentedMessage(id, parentId, { ...overrides, role: "agent" });
+
+const regenerated: ParentedMessage[] = [
user("u1", null),
agent("a1", "u1"),
agent("a2", "u1"),
@@ -29,35 +24,22 @@ const regenerated: ParentedChatMessage[] = [
agent("b1", "u2"),
];
+const responseIds = (messages: ParentedMessage[]) =>
+ activeResponses(messages, {}).map(({ message }) => message.id);
+
describe("activeResponses", () => {
it("defaults each branch to its newest reply", () => {
- const responses = activeResponses(regenerated, {}, { isSlack: false });
-
- expect(
- responses.flatMap(({ messages }) => messages.map(({ id }) => id)),
- ).toEqual(["u1", "a2", "u2", "b1"]);
+ expect(responseIds(regenerated)).toEqual(["u1", "a2", "u2", "b1"]);
});
it("follows a selected older reply and truncates everything downstream", () => {
- const responses = activeResponses(
- regenerated,
- { u1: "a1" },
- { isSlack: false },
- );
+ const responses = activeResponses(regenerated, { u1: "a1" });
- expect(
- responses.flatMap(({ messages }) => messages.map(({ id }) => id)),
- ).toEqual(["u1", "a1"]);
+ expect(responses.map(({ message }) => message.id)).toEqual(["u1", "a1"]);
});
it("marks a regenerated reply with its branch and alternatives", () => {
- const [prompt, reply] = activeResponses(
- regenerated,
- {},
- {
- isSlack: false,
- },
- );
+ const [prompt, reply] = activeResponses(regenerated, {});
expect(prompt.branch).toBeNull();
expect(reply.branch).toEqual({
@@ -71,33 +53,26 @@ describe("activeResponses", () => {
const [, reply] = activeResponses(
[user("u1", null), agent("a1", "u1")],
{},
- { isSlack: false },
);
expect(reply.branch).toBeNull();
});
- it("groups a multi-message reply", () => {
- const messages = [
- user("u1", null),
- agent("a1", "u1"),
- agent("a2", "u1"),
- agent("a2-tool", "a2"),
- user("u2", "a2-tool"),
- ];
- const [, reply, followUp] = activeResponses(
- messages,
- {},
- { isSlack: false },
- );
-
- expect(reply.messages.map(({ id }) => id)).toEqual(["a2", "a2-tool"]);
- expect(reply.branch).toEqual({
- parentId: "u1",
- currentIndex: 1,
- replyIds: ["a1", "a2"],
+ it("keeps all parts in a row as one response", () => {
+ const reply = agent("a1", "u1", {
+ parts: [
+ createMockMetabotToolCallPart({ id: "a1-tool" }),
+ createMockMetabotTextPart({ id: "a1-text" }),
+ ],
});
- expect(followUp.messages[0].id).toBe("u2");
+
+ const [, response] = activeResponses([user("u1", null), reply], {});
+
+ expect(response.message.id).toBe("a1");
+ expect(response.message.parts.map(({ id }) => id)).toEqual([
+ "a1-tool",
+ "a1-text",
+ ]);
});
describe("user-prompt branches (rewound errored turn)", () => {
@@ -109,31 +84,24 @@ describe("activeResponses", () => {
];
it("defaults to the newest root prompt and marks it with a branch on the prompt", () => {
- const [prompt, reply] = activeResponses(
- rewoundAtRoot,
- {},
- { isSlack: false },
- );
+ const [prompt, reply] = activeResponses(rewoundAtRoot, {});
- expect(prompt.messages.map(({ id }) => id)).toEqual(["uLive"]);
+ expect(prompt.message.id).toBe("uLive");
expect(prompt.branch).toEqual({
parentId: "__root__",
currentIndex: 1,
replyIds: ["uErr", "uLive"],
});
- expect(reply.messages.map(({ id }) => id)).toEqual(["aLive"]);
+ expect(reply.message.id).toBe("aLive");
});
it("follows a selected older root prompt to reveal the rewound errored turn", () => {
- const responses = activeResponses(
- rewoundAtRoot,
- { __root__: "uErr" },
- { isSlack: false },
- );
+ const responses = activeResponses(rewoundAtRoot, { __root__: "uErr" });
- expect(
- responses.flatMap(({ messages }) => messages.map(({ id }) => id)),
- ).toEqual(["uErr", "aErr"]);
+ expect(responses.map(({ message }) => message.id)).toEqual([
+ "uErr",
+ "aErr",
+ ]);
});
it("branches user prompts mid-thread too", () => {
@@ -146,25 +114,22 @@ describe("activeResponses", () => {
agent("aLive", "uLive"),
];
- const promptResponse = activeResponses(
- messages,
- {},
- { isSlack: false },
- ).find(({ messages }) => messages[0]?.id === "uLive");
+ const promptResponse = activeResponses(messages, {}).find(
+ ({ message }) => message.id === "uLive",
+ );
expect(promptResponse?.branch).toEqual({
parentId: "a1",
currentIndex: 1,
replyIds: ["uErr", "uLive"],
});
- const selected = activeResponses(
- messages,
- { a1: "uErr" },
- { isSlack: false },
- );
- expect(
- selected.flatMap(({ messages }) => messages.map(({ id }) => id)),
- ).toEqual(["u1", "a1", "uErr", "aErr"]);
+ const selected = activeResponses(messages, { a1: "uErr" });
+ expect(selected.map(({ message }) => message.id)).toEqual([
+ "u1",
+ "a1",
+ "uErr",
+ "aErr",
+ ]);
});
});
});
diff --git a/frontend/src/metabase/metabot/utils/normalize-fetched-chat-messages.ts b/frontend/src/metabase/metabot/utils/normalize-fetched-chat-messages.ts
deleted file mode 100644
index 9aa8ce5ba99..00000000000
--- a/frontend/src/metabase/metabot/utils/normalize-fetched-chat-messages.ts
+++ /dev/null
@@ -1,67 +0,0 @@
-import { createMessageId } from "metabase/metabot/state/utils";
-import type { MetabotStateContext } from "metabase-types/api";
-
-import type { MetabotAgentTurnError, MetabotChatMessage } from "../state/types";
-
-import { convertSlackChatMessage } from "./slack-mrkdwn";
-
-export type FetchedChatMessage = MetabotChatMessage & {
- finished?: boolean | null;
- error?: MetabotAgentTurnError | null;
-};
-
-/**
- * A single conversation with its flattened chat messages, as returned by
- * `GET /api/metabot/conversations/:id`.
- */
-export type MetabotConversationDetail = {
- conversation_id: string;
- created_at: string;
- title: string | null;
- user_id: number | null;
- forked_from_conversation_id: string | null;
- state?: MetabotStateContext;
- messages: FetchedChatMessage[];
-};
-
-// NOTE: this should go away long-term. The FE should refactor around turns instead of a flat list of message.
-// this would allow for annotations like error / finished at this higher level abstraction.
-
-/**
- * Convert a fetched conversation's `messages` payload into the shape the
- * live chat UI expects: strip the BE's `finished` / `error` annotations off
- * the last agent message of each turn and re-emit them as dedicated trailing
- * `turn_aborted` / `turn_errored` messages.
- */
-export function normalizeFetchedChatMessages(
- msgs: FetchedChatMessage[],
- { isSlack = false }: { isSlack?: boolean } = {},
-): MetabotChatMessage[] {
- return msgs.flatMap((inputMsg) => {
- const msg = isSlack ? convertSlackChatMessage(inputMsg) : inputMsg;
- if (inputMsg.error != null) {
- return [
- msg,
- {
- id: createMessageId(),
- role: "agent",
- type: "turn_errored",
- error: inputMsg.error,
- externalId: "externalId" in msg ? msg.externalId : undefined,
- },
- ];
- }
- if (inputMsg.finished === false) {
- return [
- msg,
- {
- id: createMessageId(),
- role: "agent",
- type: "turn_aborted",
- externalId: "externalId" in msg ? msg.externalId : undefined,
- },
- ];
- }
- return msg;
- });
-}
diff --git a/frontend/src/metabase/metabot/utils/normalize-fetched-chat-messages.unit.spec.ts b/frontend/src/metabase/metabot/utils/normalize-fetched-chat-messages.unit.spec.ts
deleted file mode 100644
index fbe34974c99..00000000000
--- a/frontend/src/metabase/metabot/utils/normalize-fetched-chat-messages.unit.spec.ts
+++ /dev/null
@@ -1,86 +0,0 @@
-import type { FetchedChatMessage } from "./normalize-fetched-chat-messages";
-import { normalizeFetchedChatMessages } from "./normalize-fetched-chat-messages";
-
-const agentText = (
- id: string,
- message: string,
- extras: {
- finished?: boolean | null;
- error?: { message: string } | null;
- } = {},
-): FetchedChatMessage => ({
- id,
- role: "agent",
- type: "text",
- message,
- externalId: id,
- ...extras,
-});
-
-describe("normalizeFetchedChatMessages", () => {
- describe("slack", () => {
- it("converts slack mrkdwn to markdown when isSlack is true", () => {
- const result = normalizeFetchedChatMessages(
- [
- agentText("a1", "see <https://example.com|the docs>", {
- finished: true,
- }),
- ],
- { isSlack: true },
- );
- expect(result[0]).toMatchObject({
- type: "text",
- message: "see [the docs](https://example.com)",
- });
- });
- });
-
- describe("message states", () => {
- it("appends a turn_aborted after an aborted agent message", () => {
- const result = normalizeFetchedChatMessages([
- agentText("a1", "partial", { finished: false }),
- ]);
- expect(result).toHaveLength(2);
- expect(result[1]).toMatchObject({
- role: "agent",
- type: "turn_aborted",
- externalId: "a1",
- });
- });
-
- it("appends a turn_errored carrying the error payload", () => {
- const err = { message: "boom" };
- const result = normalizeFetchedChatMessages([
- agentText("a1", "partial", { error: err }),
- ]);
- expect(result).toHaveLength(2);
- expect(result[1]).toMatchObject({
- role: "agent",
- type: "turn_errored",
- error: err,
- externalId: "a1",
- });
- });
-
- it("does not append a trailing turn message finished agent messages w/o error", () => {
- const result = normalizeFetchedChatMessages([
- agentText("a1", "hello", { finished: true }),
- ]);
- expect(result).toHaveLength(1);
- expect(result[0]).toMatchObject({
- id: "a1",
- role: "agent",
- type: "text",
- message: "hello",
- });
- });
-
- it("treats finished=null as not-aborted (no trailing turn_aborted)", () => {
- const result = normalizeFetchedChatMessages([
- agentText("a1", "hello", { finished: null }),
- ]);
- expect(result).toHaveLength(1);
- expect(result[0]).toMatchObject({ type: "text", message: "hello" });
- });
- });
-});
diff --git a/frontend/src/metabase/metabot/utils/slack-mrkdwn.ts b/frontend/src/metabase/metabot/utils/slack-mrkdwn.ts
index 59516235f5d..7a71eefac5a 100644
--- a/frontend/src/metabase/metabot/utils/slack-mrkdwn.ts
+++ b/frontend/src/metabase/metabot/utils/slack-mrkdwn.ts
@@ -1,6 +1,7 @@
-import { match } from "ts-pattern";
-
-import type { MetabotChatMessage } from "metabase/metabot/state/types";
+import type {
+ MetabotMessage,
+ MetabotMessagePart,
+} from "metabase/metabot/state/types";
const URL_WITH_LABEL = /<((?:https?|mailto|tel):[^|>\s]+)\|([^>]+)>/g;
const BARE_URL = /<((?:https?|mailto|tel):[^|>\s]+)>/g;
@@ -21,24 +22,17 @@ export function slackMrkdwnToMarkdown(text: string): string {
.replace(SPECIAL_MENTION, "@$1");
}
-export function convertSlackChatMessage(
- message: MetabotChatMessage,
-): MetabotChatMessage {
- return match(message)
- .with({ role: "user", type: "text" }, (m) => ({
- ...m,
- message: slackMrkdwnToMarkdown(m.message),
- }))
- .with({ role: "agent", type: "text" }, (m) => ({
- ...m,
- message: slackMrkdwnToMarkdown(m.message),
- }))
- .with({ role: "agent", type: "data_part" }, (m) => m)
- .with({ role: "agent", type: "tool_call" }, (m) => m)
- .with({ role: "agent", type: "chain_of_thought" }, (m) => m)
- .with({ role: "agent", type: "turn_aborted" }, (m) => m)
- .with({ role: "agent", type: "turn_incomplete" }, (m) => m)
- .with({ role: "agent", type: "turn_errored" }, (m) => m)
- .with({ role: "agent", type: "turn_in_progress" }, (m) => m)
- .exhaustive();
+function convertSlackMessagePart(part: MetabotMessagePart): MetabotMessagePart {
+ if (part.type !== "text") {
+ return part;
+ }
+ const message = slackMrkdwnToMarkdown(part.message);
+ return message === part.message ? part : { ...part, message };
+}
+
+export function convertSlackMessage(message: MetabotMessage): MetabotMessage {
+ const parts = message.parts.map(convertSlackMessagePart);
+ return parts.some((part, index) => part !== message.parts[index])
+ ? { ...message, parts }
+ : message;
}
diff --git a/frontend/test/__support__/server-mocks/metabot.ts b/frontend/test/__support__/server-mocks/metabot.ts
index d402f19420a..53571a776a4 100644
--- a/frontend/test/__support__/server-mocks/metabot.ts
+++ b/frontend/test/__support__/server-mocks/metabot.ts
@@ -3,7 +3,15 @@ import fetchMock, {
type UserRouteConfig,
} from "fetch-mock";
-import type { MetabotConversationDetail } from "metabase/metabot/utils/normalize-fetched-chat-messages";
+import type { MetabotConversationDetail } from "metabase/metabot/api";
+import type {
+ MetabotAgentChainOfThoughtMessage,
+ MetabotAgentDataPartMessage,
+ MetabotAgentTextChatMessage,
+ MetabotDebugToolCallMessage,
+ MetabotMessage,
+} from "metabase/metabot/state/types";
+import type { ParentedMessage } from "metabase/metabot/utils/message-tree";
import type {
LlmConnectionModels,
LlmProviderConnection,
@@ -22,6 +30,7 @@ import type {
SuggestedMetabotPromptsResponse,
UserMetabotPermissionsResponse,
} from "metabase-types/api";
+import { createMockStructuredDatasetQuery } from "metabase-types/api/mocks";
import { createMockLlmProviderConnection } from "metabase-types/api/mocks/llm";
import { createMockUserMetabotPermissions } from "metabase-types/api/mocks/metabot";
@@ -74,6 +83,114 @@ export function setupGetMetabotConversationTitleEndpoint(
);
}
+let messageCount = 0;
+
+export function createMockMetabotMessage(
+ opts?: Partial<MetabotMessage>,
+): MetabotMessage {
+ return {
+ id: `message-${++messageCount}`,
+ role: "agent",
+ parts: [],
+ status: { type: "done" },
+ ...opts,
+ };
+}
+
+export function createMockMetabotTextMessage(
+ role: "user" | "agent",
+ text: string,
+ opts?: Partial<MetabotMessage>,
+): MetabotMessage {
+ const message = createMockMetabotMessage({ role, ...opts });
+ return {
+ ...message,
+ parts: [{ id: `${message.id}-text`, role, type: "text", message: text }],
+ };
+}
+
+let partCount = 0;
+
+export function createMockParentedMessage(
+ id: string,
+ parentMessageId: string | null,
+ opts?: Partial<Omit<MetabotMessage, "id">>,
+): ParentedMessage {
+ return {
+ ...createMockMetabotMessage({ ...opts, id }),
+ parent_message_id: parentMessageId,
+ };
+}
+
+export function createMockMetabotTextPart(
+ opts?: Partial<MetabotAgentTextChatMessage>,
+): MetabotAgentTextChatMessage {
+ return {
+ id: `part-${++partCount}`,
+ role: "agent",
+ type: "text",
+ message: "answer",
+ ...opts,
+ };
+}
+
+export function createMockMetabotToolCallPart(
+ opts?: Partial<MetabotDebugToolCallMessage>,
+): MetabotDebugToolCallMessage {
+ return {
+ id: `part-${++partCount}`,
+ role: "agent",
+ type: "tool_call",
+ name: "search",
+ status: "ended",
+ ...opts,
+ };
+}
+
+export function createMockMetabotChainOfThoughtPart(
+ opts?: Partial<MetabotAgentChainOfThoughtMessage>,
+): MetabotAgentChainOfThoughtMessage {
+ return {
+ id: `part-${++partCount}`,
+ role: "agent",
+ type: "chain_of_thought",
+ steps: [],
+ finished: true,
+ ...opts,
+ };
+}
+
+export function createMockMetabotGeneratedCardPart({
+ databaseId = 1,
+ tableId = 2,
+ ...opts
+}: Partial<MetabotAgentDataPartMessage> & {
+ databaseId?: number;
+ tableId?: number;
+} = {}): MetabotAgentDataPartMessage {
+ return {
+ id: `part-${++partCount}`,
+ role: "agent",
+ type: "data_part",
+ part: {
+ type: "data-generated_entity",
+ data: {
+ type: "card",
+ id: "card-1",
+ title: "Orders",
+ query: {
+ id: "query-1",
+ query: createMockStructuredDatasetQuery({
+ database: databaseId,
+ query: { "source-table": tableId },
+ }),
+ },
+ },
+ },
+ ...opts,
+ };
+}
+
export function createMockMetabotConversationDetail(
opts?: Partial<MetabotConversationDetail>,
): MetabotConversationDetail {
diff --git a/src/metabase/metabot/api.clj b/src/metabase/metabot/api.clj
index 6e655473b59..2ae81d1d630 100644
--- a/src/metabase/metabot/api.clj
+++ b/src/metabase/metabot/api.clj
@@ -192,9 +192,10 @@
`:assistant-msg-id` is the PK of the placeholder assistant row created by
[[metabot.persistence/start-turn!]]; the finally block UPDATEs that row.
- `:external-id` is the assistant row's `external_id`, emitted as the SSE
- `start` event's `messageId` so the client can correlate streamed messages
- with feedback. `:user-external-id` is the turn's user row `external_id`,
+ `:external-id` is the assistant row's `external_id` — the client-minted
+ `assistant_message_id` when the request supplied one — echoed as the SSE
+ `start` event's `messageId` so a client that omitted one can still tell what
+ was persisted. `:user-external-id` is the turn's user row `external_id`,
emitted as the `start` event's `messageMetadata.userMessageId`.
`:state` is the reconstructed [[metabot.persistence/conversation-state]] —
it seeds the agent loop as the immutable baseline for this turn's state."
diff --git a/src/metabase/metabot/api/conversations.clj b/src/metabase/metabot/api/conversations.clj
index f00e2870e47..3eadf267efd 100644
--- a/src/metabase/metabot/api/conversations.clj
+++ b/src/metabase/metabot/api/conversations.clj
@@ -60,7 +60,7 @@
[:map
[:card_id ms/PositiveInt]
[:chart_id [:maybe :string]]]]]
- [:messages [:sequential :map]]])
+ [:messages [:sequential ::metabot.schema/client-message]]])
(def ^:private ConversationTitleResponse
[:map
diff --git a/src/metabase/metabot/persistence.clj b/src/metabase/metabot/persistence.clj
index dd0110dc441..d391d1dec59 100644
--- a/src/metabase/metabot/persistence.clj
+++ b/src/metabase/metabot/persistence.clj
@@ -64,7 +64,7 @@
"Convert internal agent-loop parts to v2 at-rest parts
(`:metabase.metabot.schema.v2/message-data`). `:tool-input`/`:tool-output`
pairs merge into a single `tool-<name>` part whose `:state` reflects the
- outcome; the stored `:output` is the trimmed result map
+ status; the stored `:output` is the trimmed result map
(see [[tool-result->storable-output]])."
[parts]
(let [outputs (into {}
@@ -548,25 +548,19 @@
;;; ---------------------------------------- Chat message conversion ----------------------------------------
(defn- convert-content-block
- "Convert a single v2 part from `:data` into a frontend `MetabotChatMessage` map.
+ "Convert a single v2 part from `:data` into a frontend message part.
Returns nil for parts that should be skipped (unknown types).
- `row-role` decides whether text parts render as user or agent messages — v2
- text parts carry no role of their own. `external-id` (the parent row's
- `metabot_message.external_id`) is attached to text and data part chat
- messages as `:externalId` — the stable key for feedback and retry; the
- per-block `:id` stays unique."
- [row-role external-id part]
+ `row-role` decides whether text parts render as user or agent parts — v2
+ text parts carry no role of their own. The owning message carries the row's
+ `external_id`; the per-block `:id` stays unique."
+ [row-role part]
(cond
(schema.v2/text-part? part)
- (if (= :user row-role)
- (cond-> {:id (str (random-uuid)) :role "user" :type "text" :message (:text part)}
- external-id (assoc :externalId external-id))
- (cond-> {:id (str (random-uuid))
- :role "agent"
- :type "text"
- :message (:text part)}
- external-id (assoc :externalId external-id)))
+ {:id (str (random-uuid))
+ :role (if (= :user row-role) "user" "agent")
+ :type "text"
+ :message (:text part)}
(schema.v2/tool-part? part)
(cond-> {:id (:toolCallId part)
@@ -584,15 +578,19 @@
(assoc :result nil :is_error true))
(schema.v2/data-part? part)
- (cond-> {:id (str (random-uuid))
- :role "agent"
- :type "data_part"
- :part {:type (:type part)
- :data (:data part)}}
- external-id (assoc :externalId external-id))
+ {:id (str (random-uuid))
+ :role "agent"
+ :type "data_part"
+ :part {:type (:type part)
+ :data (:data part)}}
:else nil))
+(defn- message->parts
+ "The row's `:data` blocks as frontend message parts."
+ [message]
+ (into [] (keep #(convert-content-block (:role message) %)) (:data message)))
+
(defn- decode-error
"JSON-decode a row's `:error` column value (a string written by
`finalize-assistant-turn!`). Falls back to the raw value if it's not a JSON object."
@@ -602,65 +600,6 @@
(catch Exception _ error))
error))
-;; TODO (sloansparger 2026-05-12) -- chat_messages should be replaced with turns
-;; so that we have a higher-level abstraction to annotate. this is fine, but a
-;; bit of a hack.
-(defn- annotate-agent-messages
- "Stamp `:finished` and `:error` from the parent row onto the
- *last* agent-role chat message produced from it. The annotation describes the
- row's outcome, so it belongs on a single message — the FE expands it into a
- trailing `turn_aborted` / `turn_errored` chat message.
-
- Parent `:finished nil` (stale placeholder past the grace window) becomes
- `:finished false` so the FE renders it as aborted."
- [chat-messages message]
- (let [finished (if (contains? message :finished)
- (or (:finished message) false)
- true)
- decoded-error (some-> (:error message) decode-error)
- last-agent-idx (->> chat-messages
- (keep-indexed (fn [i m] (when (= "agent" (:role m)) i)))
- last)]
- (if (nil? last-agent-idx)
- chat-messages
- (update chat-messages last-agent-idx
- (fn [m]
- (cond-> (assoc m :finished finished)
- (some? decoded-error) (assoc :error decoded-error)))))))
-
-(defn- empty-agent-placeholder
- "Stub chat message for an assistant row whose `:data` produced no chat messages
- (typical for errored turns where the agent failed before emitting any text/
- tool parts). Without this the FE has nowhere to render the error alert."
- [{:keys [external_id]}]
- (cond-> {:id (or external_id (str (random-uuid)))
- :role "agent"
- :type "text"
- :message ""}
- external_id (assoc :externalId external_id)))
-
-(defn message->chat-messages
- "Convert a single `MetabotMessage` model instance into a seq of `MetabotChatMessage` maps.
- Each message's `:data` (vector of content blocks) is flattened into typed chat messages.
- Assistant rows that produced zero chat messages but carry `:error`,
- `:finished false`, or `:finished nil` (a stale placeholder past the grace
- window) get a synthetic empty text message so the FE has something to render
- the alert on."
- [message]
- (let [blocks (or (:data message) [])
- external-id (:external_id message)
- chat-msgs (into [] (keep #(convert-content-block (:role message) external-id %)) blocks)
- ;; Absent :finished is treated as true (success); only explicit nil
- ;; (stale placeholder) or false (aborted) should drive the stub branch.
- not-finished (and (contains? message :finished)
- (not (true? (:finished message))))
- with-stub (if (and (= :assistant (:role message))
- (empty? chat-msgs)
- (or (some? (:error message)) not-finished))
- [(empty-agent-placeholder message)]
- chat-msgs)]
- (annotate-agent-messages with-stub message)))
-
(defn- errored-agent-row?
[m]
(and (= :assistant (:role m))
@@ -682,8 +621,7 @@
than a crashed/aborted turn. Generous enough to cover any plausible live agent
loop — the `transforms_codegen` profile allows 30 iterations and there is no
client-independent LLM timeout, so a long-running turn can easily exceed
- several minutes. Readers older than this fall back to rendering the trailing
- `turn_aborted` alert.
+ several minutes. Readers older than this expose an aborted status.
Bias: this is the 'show a still-running stream as aborted' window vs. the
'show a crashed turn as absent' window. The first is more user-visible (a
@@ -713,65 +651,74 @@
(< (.toMillis (java.time.Duration/between then (Instant/now)))
placeholder-grace-period-ms))))
-(defn- turn-in-progress-message
- "Synthetic chat message emitted for an assistant row that is still streaming
- (an active placeholder). The FE renders it as a 'Response in progress…' row."
+(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
+ 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"}))
+
+(defn- message->client-message
+ "Convert one `MetabotMessage` row into its client shape: the row's parts, plus
+ the optional `external_id` and status the row itself carries. Rows with no
+ renderable parts are still fully represented."
[row]
- (cond-> {:id (or (:external_id row) (str (:id row)))
- :role "agent"
- :type "turn_in_progress"}
- (:external_id row) (assoc :externalId (:external_id row))))
-
-(defn messages->chat-messages
- "Convert a seq of `MetabotMessage` model instances into a flat vector of `MetabotChatMessage` maps.
- In-flight placeholder rows (assistant rows still streaming) become a trailing
- `turn_in_progress` message. Errored pairs are dropped unless `:include-errored? true`."
- ([messages] (messages->chat-messages messages nil))
+ (let [status (row->status row)]
+ (cond-> {:id (or (:external_id row) (str (:id row)))
+ :role (if (= :user (:role row)) "user" "agent")
+ :parts (if (= "in_progress" (:type status))
+ []
+ (message->parts row))
+ :status status}
+ (:external_id row) (assoc :externalId (:external_id row)))))
+
+(defn messages->client-messages
+ "Convert a seq of `MetabotMessage` model instances into their client shape, one
+ per row. Errored pairs are dropped unless `:include-errored? true`."
+ ([messages] (messages->client-messages messages nil))
([messages {:keys [include-errored?]}]
- (into []
- (mapcat (fn [message]
- (if (placeholder-still-active? message)
- [(turn-in-progress-message message)]
- (message->chat-messages message))))
+ (mapv message->client-message
(if include-errored? messages (drop-errored-pairs messages)))))
-(defn- row->flat-messages
- [row parent-id]
- (let [messages (if (placeholder-still-active? row)
- [(turn-in-progress-message row)]
- (message->chat-messages row))]
- (reduce (fn [[messages parent-id] message]
- (let [message (assoc message :parent_message_id parent-id)]
- [(conj messages message) (:id message)]))
- [[] parent-id]
- messages)))
-
-(defn messages->flat-messages
- "Convert ordered live and deleted rows to chat messages with parent pointers.
+(defn messages->threaded-client-messages
+ "Convert ordered live and deleted rows to client messages with parent pointers.
With `:include-rewound-errors?`, a turn whose prompt was soft-deleted is also
kept when it errored (a rewound failed turn), as a dead branch the main thread
does not descend from; by default such turns are dropped."
- ([messages] (messages->flat-messages messages nil))
+ ([messages] (messages->threaded-client-messages messages nil))
([messages {:keys [include-rewound-errors?]}]
- (loop [turns (rows->turns messages), parent-id nil, flat-messages []]
+ (loop [turns (rows->turns messages), parent-id nil, client-messages []]
(if-let [turn (first turns)]
(let [prompt-row (u/seek #(= :user (:role %)) turn)
prompt-live? (and prompt-row (nil? (:deleted_at prompt-row)))
errored? (and include-rewound-errors?
(some #(and (= :assistant (:role %)) (some? (:error %))) turn))]
(if (and prompt-row (or prompt-live? errored?))
- (let [[prompt-messages prompt-last-id] (row->flat-messages prompt-row parent-id)
- assistant-rows (filterv #(= :assistant (:role %)) turn)
- attempts (mapv #(row->flat-messages % prompt-last-id) assistant-rows)
- kept-last-id (->> (map vector assistant-rows attempts)
- (keep (fn [[row [_ last-id]]]
- (when (nil? (:deleted_at row)) last-id)))
- last)]
+ (let [prompt-message (assoc (message->client-message prompt-row) :parent_message_id parent-id)
+ assistant-rows (filterv #(= :assistant (:role %)) turn)
+ attempts (mapv #(assoc (message->client-message %)
+ :parent_message_id (:id prompt-message))
+ assistant-rows)
+ kept-last-id (->> (map vector assistant-rows attempts)
+ (keep (fn [[row message]]
+ (when (nil? (:deleted_at row)) (:id message))))
+ last)]
(recur (rest turns)
- (if prompt-live? (or kept-last-id prompt-last-id) parent-id)
- (into (into flat-messages prompt-messages) (mapcat first) attempts)))
- (recur (rest turns) parent-id flat-messages)))
- flat-messages))))
+ (if prompt-live? (or kept-last-id (:id prompt-message)) parent-id)
+ (into (conj client-messages prompt-message) attempts)))
+ (recur (rest turns) parent-id client-messages)))
+ client-messages))))
(defn conversation-detail
"Conversation-with-chat-messages snapshot. Nil if not found.
@@ -795,7 +742,7 @@
{:card_id id
:chart_id metabot_chart_id})
(metabot.db/saved-cards-for-conversation conversation-id))
- :messages (messages->chat-messages messages)})))
+ :messages (messages->client-messages messages)})))
;;; ---------------------------------------- Forking ----------------------------------------
diff --git a/src/metabase/metabot/schema.clj b/src/metabase/metabot/schema.clj
index 1d6236ad1b3..f1d6ad92768 100644
--- a/src/metabase/metabot/schema.clj
+++ b/src/metabase/metabot/schema.clj
@@ -44,3 +44,61 @@
"Normalize dynamic state-map keys to strings according to [[::state]]."
[state]
(mc/decode ::state state (mtx/transformer {:name :normalize})))
+
+;;; ------------------------------- Client message shape -------------------------------
+
+(mr/def ::client-message-part
+ "One part of a persisted message: its a text, tool call, or data blob."
+ [:multi {:dispatch :type}
+ ["text"
+ [:map
+ [:id :string]
+ [:role [:enum "user" "agent"]]
+ [:type [:= "text"]]
+ [:message :string]]]
+ ["tool_call"
+ [:map
+ [:id :string]
+ [:role [:= "agent"]]
+ [:type [:= "tool_call"]]
+ [:name :string]
+ [:args [:maybe :string]]
+ [:status [:enum "started" "ended"]]
+ ;; both can be absent if a call is unresolved and
+ ;; conversation is loaded while agent loop is still running
+ [:result {:optional true} [:maybe :string]]
+ [:is_error {:optional true} :boolean]]]
+ ["data_part"
+ [:map
+ [:id :string]
+ [:role [:= "agent"]]
+ [:type [:= "data_part"]]
+ [:part [:map
+ [:type :string]
+ [:data :any]]]]]])
+
+(mr/def ::client-message-status
+ "Where a message's turn got to."
+ [:multi {:dispatch :type}
+ ["done" [:map [:type [:= "done"]]]]
+ ["aborted" [:map [:type [:= "aborted"]]]]
+ ["in_progress" [:map [:type [:= "in_progress"]]]]
+ ["errored"
+ [:map
+ [:type [:= "errored"]]
+ ;; the decoded `error` column, or its raw text when it isn't JSON
+ [:error [:or
+ :string
+ [:map
+ [:message {:optional true} [:maybe :string]]
+ [:type {:optional true} :string]
+ [:data {:optional true} :any]]]]]]])
+
+(mr/def ::client-message
+ "One persisted message as the client models it."
+ [:map
+ [:id :string]
+ [:externalId {:optional true} :string]
+ [:role [:enum "user" "agent"]]
+ [:parts [:sequential ::client-message-part]]
+ [:status ::client-message-status]])
diff --git a/test/metabase/metabot/api/conversations_test.clj b/test/metabase/metabot/api/conversations_test.clj
index aa066a329e1..002d2be8d36 100644
--- a/test/metabase/metabot/api/conversations_test.clj
+++ b/test/metabase/metabot/api/conversations_test.clj
@@ -491,7 +491,8 @@
(is (= convo-id (:forked_from_conversation_id response))))
(is (= user-id (:user_id response))))
(testing "only the thread up to and including the target is copied"
- (is (= ["hi" "hello"] (mapv :message (:messages response)))))
+ (is (= ["hi" "hello"]
+ (mapv #(-> % :parts first :message) (:messages response)))))
(let [rows (metabot.persistence/live-messages new-id)
orig-a1-at (t2/select-one-fn :created_at :model/MetabotMessage :external_id a1)]
(testing "cloned rows are fresh copies"
diff --git a/test/metabase/metabot/persistence_test.clj b/test/metabase/metabot/persistence_test.clj
index 07f28532af8..82f9a6266f8 100644
--- a/test/metabase/metabot/persistence_test.clj
+++ b/test/metabase/metabot/persistence_test.clj
@@ -69,170 +69,174 @@
:data [{:type "text" :text "inherited prompt"}]}
{:id 2 :role :assistant :finished true :forked_from_message_id 101 :data []}])))))
-(deftest ^:parallel message->chat-messages-test
- (testing "text part on a user row renders as a user message"
- (let [result (metabot-persistence/message->chat-messages
- {:role :user
- :data [{:type "text" :text "hello"}]})]
- (is (= 1 (count result)))
+(defn- client-message
+ [row]
+ (first (metabot-persistence/messages->client-messages
+ [(merge {:id 1} row)]
+ {:include-errored? true})))
+
+(defn- part-messages
+ [message]
+ (mapv :message (:parts message)))
+
+(deftest ^:parallel messages->client-messages-user-text-part-test
+ (testing "text part on a user row renders as a user part"
+ (let [[part] (:parts (client-message {:role :user
+ :data [{:type "text" :text "hello"}]}))]
(is (= {:role "user" :type "text" :message "hello"}
- (select-keys (first result) [:role :type :message])))
- (is (string? (:id (first result)))))))
-
-(deftest ^:parallel message->chat-messages-test-2
- (testing "text part on an assistant row renders as an agent message with a generated id"
- (let [result (metabot-persistence/message->chat-messages
- {:role :assistant
- :data [{:type "text" :text "hi there"}]})]
- (is (= [{:role "agent" :type "text" :message "hi there"}]
- (mapv #(select-keys % [:role :type :message]) result)))
- (is (string? (:id (first result)))))))
-
-(deftest ^:parallel message->chat-messages-test-5
+ (select-keys part [:role :type :message])))
+ (is (string? (:id part))))))
+
+(deftest ^:parallel messages->client-messages-assistant-text-part-test
+ (testing "text part on an assistant row renders as an agent part with a generated id"
+ (let [[part] (:parts (client-message {:role :assistant
+ :data [{:type "text" :text "hi there"}]}))]
+ (is (= {:role "agent" :type "text" :message "hi there"}
+ (select-keys part [:role :type :message])))
+ (is (string? (:id part))))))
+
+(deftest ^:parallel messages->client-messages-resolved-tool-part-test
(testing "resolved tool part carries args and result"
- (let [result (metabot-persistence/message->chat-messages
- {:role :assistant
- :data [{:type "tool-search" :toolCallId "call-1" :state "output-available"
- :input {:query "foo"} :output {:output "rows!" :structured_output {:query-id "q"}}}]})]
- (is (= 1 (count result)))
+ (let [[part] (:parts (client-message
+ {:role :assistant
+ :data [{:type "tool-search" :toolCallId "call-1" :state "output-available"
+ :input {:query "foo"}
+ :output {:output "rows!" :structured_output {:query-id "q"}}}]}))]
(is (= {:id "call-1"
:role "agent"
:type "tool_call"
:name "search"
:status "ended"
:is_error false}
- (select-keys (first result) [:id :role :type :name :status :is_error])))
- (is (= {:query "foo"} (json/decode+kw (:args (first result)))))
+ (select-keys part [:id :role :type :name :status :is_error])))
+ (is (= {:query "foo"} (json/decode+kw (:args part))))
(is (= {:output "rows!" :structured_output {:query-id "q"}}
- (json/decode+kw (:result (first result))))))))
+ (json/decode+kw (:result part)))))))
-(deftest ^:parallel message->chat-messages-test-6
+(deftest ^:parallel messages->client-messages-errored-tool-part-test
(testing "errored tool part is flagged and carries no result"
- (let [result (metabot-persistence/message->chat-messages
- {:role :assistant
- :data [{:type "tool-boom" :toolCallId "call-2" :state "output-error"
- :input {} :errorText "exploded"}]})]
- (is (true? (:is_error (first result))))
- (is (nil? (:result (first result)))))))
-
-(deftest ^:parallel message->chat-messages-test-7
+ (let [[part] (:parts (client-message
+ {:role :assistant
+ :data [{:type "tool-boom" :toolCallId "call-2" :state "output-error"
+ :input {} :errorText "exploded"}]}))]
+ (is (true? (:is_error part)))
+ (is (nil? (:result part))))))
+
+(deftest ^:parallel messages->client-messages-unresolved-tool-part-test
(testing "unresolved tool part renders without result/error fields"
- (let [result (metabot-persistence/message->chat-messages
- {:role :assistant
- :data [{:type "tool-search" :toolCallId "call-3" :state "input-available" :input {}}]})]
- (is (= 1 (count result)))
- (is (= "tool_call" (:type (first result))))
- (is (not (contains? (first result) :result)))
- (is (not (contains? (first result) :is_error))))))
-
-(deftest ^:parallel message->chat-messages-test-11
+ (let [[part] (:parts (client-message
+ {:role :assistant
+ :data [{:type "tool-search" :toolCallId "call-3"
+ :state "input-available" :input {}}]}))]
+ (is (= "tool_call" (:type part)))
+ (is (not (contains? part :result)))
+ (is (not (contains? part :is_error))))))
+
+(deftest ^:parallel messages->client-messages-nil-tool-result-test
(testing "resolved tool part with a nil :output yields a nil :result, not the string \"null\""
- (let [result (metabot-persistence/message->chat-messages
- {:role :assistant
- :data [{:type "tool-search" :toolCallId "call-4" :state "output-available"
- :input {} :output nil}]})]
- (is (false? (:is_error (first result))))
- (is (nil? (:result (first result)))))))
-
-(deftest ^:parallel message->chat-messages-test-8
+ (let [[part] (:parts (client-message
+ {:role :assistant
+ :data [{:type "tool-search" :toolCallId "call-4" :state "output-available"
+ :input {} :output nil}]}))]
+ (is (false? (:is_error part)))
+ (is (nil? (:result part))))))
+
+(deftest ^:parallel messages->client-messages-unknown-part-test
(testing "unknown part types are dropped"
- (is (= []
- (metabot-persistence/message->chat-messages
- {:role :assistant
- :data [{:type "mystery"}]})))))
+ (is (= [] (:parts (client-message {:role :assistant :data [{:type "mystery"}]}))))))
-(deftest ^:parallel message->chat-messages-test-9
- (testing "data parts are converted to data_part chat messages"
+(deftest ^:parallel messages->client-messages-data-parts-test
+ (testing "data parts are converted to data_part message parts"
(let [blocks [{:type "data-generated_entity" :data {:type "dashboard" :url "/auto/dashboard/table/1"}}
{:type "data-todo_list" :data [{:id "t1"}]}
{:type "data-code_edit" :data {:buffer_id "b" :value "v"}}]]
- (is (=? [{:role "agent" :type "data_part" :part {:type "data-generated_entity" :data {:type "dashboard" :url "/auto/dashboard/table/1"}}}
- {:role "agent" :type "data_part" :part {:type "data-todo_list" :data [{:id "t1"}]}}
- {:role "agent" :type "data_part" :part {:type "data-code_edit" :data {:buffer_id "b" :value "v"}}}]
- (metabot-persistence/message->chat-messages {:role :assistant :data blocks}))))))
-
-(deftest ^:parallel message->chat-messages-test-10
- (testing "nil :data yields no messages"
- (is (= [] (metabot-persistence/message->chat-messages {:role :user :data nil})))))
-
-(deftest ^:parallel messages->chat-messages-flattens-across-messages-test
- (let [result (metabot-persistence/messages->chat-messages
- [{:role :user :data [{:type "text" :text "hi"}]}
- {:role :assistant :data [{:type "text" :text "hello!"}
- {:type "tool-f" :toolCallId "t1" :state "output-available"
- :input {:x 1} :output {:output "ok"}}]}])]
- (is (= 3 (count result)))
- (is (= ["user" "agent" "agent"] (map :role result)))
- (is (= ["text" "text" "tool_call"] (map :type result)))
- (is (= "hi" (:message (nth result 0))))
- (is (= "hello!" (:message (nth result 1))))
- (is (= {:output "ok"} (json/decode+kw (:result (nth result 2)))))))
-
-(deftest ^:parallel messages->chat-messages-active-placeholder-test
- (testing "an in-flight assistant placeholder becomes a trailing turn_in_progress message"
- (let [result (metabot-persistence/messages->chat-messages
- [{:role :user :data [{:type "text" :text "hi"}]}
- {:id 2 :role :assistant :external_id "a1"
+ (is (=? [{:role "agent" :type "data_part"
+ :part {:type "data-generated_entity"
+ :data {:type "dashboard" :url "/auto/dashboard/table/1"}}}
+ {:role "agent" :type "data_part"
+ :part {:type "data-todo_list" :data [{:id "t1"}]}}
+ {:role "agent" :type "data_part"
+ :part {:type "data-code_edit" :data {:buffer_id "b" :value "v"}}}]
+ (:parts (client-message {:role :assistant :data blocks})))))))
+
+(deftest ^:parallel messages->client-messages-nil-data-test
+ (testing "nil :data yields no parts"
+ (is (= [] (:parts (client-message {:role :user :data nil}))))))
+
+(deftest ^:parallel messages->client-messages-external-id-test
+ (testing "a row external id is represented on its message envelope, not its parts"
+ (let [message (client-message {:role :assistant :external_id "a1"
+ :data [{:type "text" :text "hello"}]})]
+ (is (= "a1" (:externalId message)))
+ (is (not-any? #(contains? % :externalId) (:parts message)))))
+ (testing "a legacy row without an external id omits the optional key"
+ (is (not (contains? (client-message {:role :assistant :data []}) :externalId)))))
+
+(deftest ^:parallel messages->client-messages-groups-parts-by-row-test
+ (let [result (metabot-persistence/messages->client-messages
+ [{:id 1 :external_id "u1" :role :user
+ :data [{:type "text" :text "hi"}]}
+ {:id 2 :external_id "a1" :role :assistant
+ :data [{:type "text" :text "hello!"}
+ {:type "tool-f" :toolCallId "t1" :state "output-available"
+ :input {:x 1} :output {:output "ok"}}]}])]
+ (is (= ["user" "agent"] (map :role result)))
+ (is (= [["text"] ["text" "tool_call"]] (mapv #(mapv :type (:parts %)) result)))
+ (is (= "hi" (-> result first :parts first :message)))
+ (is (= "hello!" (-> result second :parts first :message)))
+ (is (= {:output "ok"} (json/decode+kw (-> result second :parts second :result))))))
+
+(deftest ^:parallel messages->client-messages-placeholder-status-test
+ (testing "an in-flight assistant placeholder is an in-progress row"
+ (let [result (metabot-persistence/messages->client-messages
+ [{:id 1 :external_id "u1" :role :user :data [{:type "text" :text "hi"}]}
+ {:id 2 :external_id "a1" :role :assistant
:created_at (t/offset-date-time) :finished nil :data []}])]
(is (= ["user" "agent"] (map :role result)))
- (is (= ["text" "turn_in_progress"] (map :type result)))
- (is (= "a1" (:externalId (second result)))))))
-
-(deftest ^:parallel messages->chat-messages-stale-placeholder-test
- (testing "a placeholder past the grace window is an aborted (finished=false) turn, not in-progress"
- (let [result (metabot-persistence/messages->chat-messages
- [{:role :user :data [{:type "text" :text "hi"}]}
- {:id 2 :role :assistant :external_id "a1"
+ (is (= {:type "in_progress"} (:status (second result))))
+ (is (= [] (:parts (second result))))
+ (is (= "a1" (:externalId (second result))))))
+ (testing "a placeholder past the grace window is aborted, not in-progress"
+ (let [result (metabot-persistence/messages->client-messages
+ [{:id 1 :external_id "u1" :role :user :data [{:type "text" :text "hi"}]}
+ {:id 2 :external_id "a1" :role :assistant
:created_at (t/minus (t/offset-date-time) (t/hours 1))
:finished nil :data []}])]
- (is (not-any? #(= "turn_in_progress" (:type %)) result))
- (is (false? (:finished (last result)))))))
+ (is (= {:type "aborted"} (:status (second result)))))))
-(deftest ^:parallel messages->flat-messages-test
+(deftest ^:parallel messages->threaded-client-messages-test
(let [deleted-at (t/offset-date-time)
- messages (metabot-persistence/messages->flat-messages
- [{:role :user :data [{:type "text" :text "q1"}]}
- {:role :assistant
- :deleted_at deleted-at
- :data [{:type "text" :text "discarded-1"}
- {:type "text" :text "discarded-2"}]}
- {:role :assistant :data [{:type "text" :text "older-live"}]}
- {:role :assistant :data [{:type "text" :text "kept-1"}
- {:type "text" :text "kept-2"}]}
- {:role :user :data [{:type "text" :text "q2"}]}])
- by-text #(u/seek (fn [message] (= % (:message message))) messages)
- q1 (by-text "q1")
- discarded-1 (by-text "discarded-1")
- discarded-2 (by-text "discarded-2")
- older-live (by-text "older-live")
- kept-1 (by-text "kept-1")
- kept-2 (by-text "kept-2")
- q2 (by-text "q2")]
- (is (= ["q1" "discarded-1" "discarded-2" "older-live" "kept-1" "kept-2" "q2"]
- (map :message messages)))
+ messages (metabot-persistence/messages->threaded-client-messages
+ [{:id 1 :external_id "u1" :role :user :data [{:type "text" :text "q1"}]}
+ {:id 2 :external_id "a1" :role :assistant :deleted_at deleted-at
+ :data [{:type "text" :text "discarded-1"}
+ {:type "text" :text "discarded-2"}]}
+ {:id 3 :external_id "a2" :role :assistant
+ :data [{:type "text" :text "older-live"}]}
+ {:id 4 :external_id "a3" :role :assistant
+ :data [{:type "text" :text "kept-1"}
+ {:type "text" :text "kept-2"}]}
+ {:id 5 :external_id "u2" :role :user :data [{:type "text" :text "q2"}]}])
+ [q1 discarded older-live kept q2] messages]
+ (is (= ["u1" "a1" "a2" "a3" "u2"] (map :id messages)))
+ (is (= [["q1"] ["discarded-1" "discarded-2"] ["older-live"] ["kept-1" "kept-2"] ["q2"]]
+ (mapv part-messages messages)))
(is (nil? (:parent_message_id q1)))
- (is (= (:id q1) (:parent_message_id discarded-1)))
- (is (= (:id discarded-1) (:parent_message_id discarded-2)))
- (is (= (:id q1) (:parent_message_id older-live)))
- (is (= (:id q1) (:parent_message_id kept-1)))
- (is (= (:id kept-1) (:parent_message_id kept-2)))
- (is (= (:id kept-2) (:parent_message_id q2)))))
-
-(deftest ^:parallel messages->flat-messages-deleted-placeholder-test
+ (is (= "u1" (:parent_message_id discarded)))
+ (is (= "u1" (:parent_message_id older-live)))
+ (is (= "u1" (:parent_message_id kept)))
+ (is (= "a3" (:parent_message_id q2)))))
+
+(deftest ^:parallel messages->threaded-client-messages-deleted-placeholder-test
(let [now (t/offset-date-time)
- messages (metabot-persistence/messages->flat-messages
- [{:role :user :data [{:type "text" :text "q1"}]}
- {:id 1
- :role :assistant
- :external_id "a1"
- :created_at now
- :deleted_at now
- :finished nil
- :data []}])]
- (is (= ["text" "text"] (map :type messages)))
- (is (false? (:finished (second messages))))))
-
-(deftest ^:parallel messages->flat-messages-keeps-rewound-errored-turn-test
+ messages (metabot-persistence/messages->threaded-client-messages
+ [{:id 1 :external_id "u1" :role :user :data [{:type "text" :text "q1"}]}
+ {:id 2 :external_id "a1" :role :assistant :created_at now :deleted_at now
+ :finished nil :data []}])]
+ (is (= [{:type "done"} {:type "aborted"}] (mapv :status messages)))
+ (is (= [] (:parts (second messages))))))
+
+(deftest ^:parallel messages->threaded-client-messages-keeps-rewound-errored-turn-test
(let [deleted-at (t/offset-date-time)
rows [{:id 1 :role :user :external_id "u1" :deleted_at deleted-at
:data [{:type "text" :text "revenue"}]}
@@ -241,23 +245,25 @@
{:id 3 :role :user :external_id "u2" :data [{:type "text" :text "orders"}]}
{:id 4 :role :assistant :external_id "a2" :finished true
:data [{:type "text" :text "here"}]}]]
- (testing "with :include-rewound-errors? the rewound errored turn shows its prompt and error,
- threaded as a dead branch the live follow-up does not descend from"
- (let [messages (metabot-persistence/messages->flat-messages rows {:include-rewound-errors? true})
- by-text #(u/seek (fn [m] (= % (:message m))) messages)]
- (is (= ["revenue" "" "orders" "here"] (map :message messages)))
- (is (some (fn [m] (and (= "agent" (:role m)) (some? (:error m)))) messages)
- "the errored reply's error survives")
- (is (nil? (:parent_message_id (by-text "orders")))
- "the live follow-up parents onto the root, not the rewound errored turn")))
+ (testing "with :include-rewound-errors? the rewound errored turn is a dead branch"
+ (let [messages (metabot-persistence/messages->threaded-client-messages
+ rows {:include-rewound-errors? true})
+ [rewound-prompt errored-attempt live-prompt live-attempt] messages]
+ (is (= ["u1" "a1" "u2" "a2"] (map :id messages)))
+ (is (= {:type "errored" :error {:message "boom"}} (:status errored-attempt)))
+ (is (= [] (:parts errored-attempt)))
+ (is (= (:id rewound-prompt) (:parent_message_id errored-attempt)))
+ (is (nil? (:parent_message_id live-prompt))
+ "the live follow-up parents onto the root, not the rewound errored turn")
+ (is (= (:id live-prompt) (:parent_message_id live-attempt)))))
(testing "by default the rewound errored turn is dropped"
- (is (= ["orders" "here"]
- (map :message (metabot-persistence/messages->flat-messages rows)))))))
+ (is (= ["u2" "a2"]
+ (map :id (metabot-persistence/messages->threaded-client-messages rows)))))))
-(deftest ^:parallel messages->flat-messages-drops-cleanly-superseded-turn-test
+(deftest ^:parallel messages->threaded-client-messages-drops-cleanly-superseded-turn-test
(testing "even with :include-rewound-errors?, a soft-deleted prompt with no error is dropped"
(let [deleted-at (t/offset-date-time)
- messages (metabot-persistence/messages->flat-messages
+ messages (metabot-persistence/messages->threaded-client-messages
[{:id 1 :role :user :external_id "u1" :deleted_at deleted-at
:data [{:type "text" :text "stale-prompt"}]}
{:id 2 :role :assistant :external_id "a1" :deleted_at deleted-at
@@ -266,7 +272,7 @@
{:id 4 :role :assistant :external_id "a2" :finished true
:data [{:type "text" :text "here"}]}]
{:include-rewound-errors? true})]
- (is (= ["orders" "here"] (map :message messages))))))
+ (is (= ["u2" "a2"] (map :id messages))))))
(deftest start-turn-persists-slack-conversation-metadata-test
(t2/with-transaction [_conn nil {:rollback-only true}]
@@ -356,10 +362,10 @@
(testing "step-start renders no chat message on read"
(is (= [{:role "agent" :type "text" :message "Hello"}]
(mapv #(select-keys % [:role :type :message])
- (metabot-persistence/message->chat-messages
- {:role :assistant
- :data [{:type "step-start"}
- {:type "text" :text "Hello"}]}))))))
+ (:parts (client-message
+ {:role :assistant
+ :data [{:type "step-start"}
+ {:type "text" :text "Hello"}]})))))))
(deftest start-turn-persists-slack-metadata-on-rows-test
(testing "start-turn! lands slack-team-id / channel-id / slack-thread-ts on the conversation row,
@@ -569,29 +575,38 @@
;; leaving just the retry turn.
(let [{:keys [messages]} (metabot-persistence/conversation-detail conversation-id)]
(is (= [["user" "retry"] ["agent" "ok"]]
- (mapv (juxt :role :message) messages))))))))
+ (mapv (fn [message]
+ [(:role message) (-> message :parts first :message)])
+ messages))))))))
(deftest placeholder-still-active-uses-nil-finished-marker-test
(testing "the in-flight predicate keys off finished IS NULL (not :data emptiness or :error)"
(let [recent (java.time.OffsetDateTime/now)
stale (.minusHours recent 2)
- base {:role :assistant :data [] :error nil}]
+ base {:id 1 :role :assistant :data [] :error nil}]
(testing "finished=nil + recent created_at → in-progress turn"
- (is (=? [{:type "turn_in_progress" :role "agent"}]
- (metabot-persistence/messages->chat-messages
- [(assoc base :finished nil :created_at recent)]))))
- (testing "finished=nil + stale created_at → not filtered (renders aborted stub)"
- (is (=? [{:type "text" :message "" :finished false}]
- (metabot-persistence/messages->chat-messages
- [(assoc base :finished nil :created_at stale)]))))
+ (is (= {:type "in_progress"}
+ (-> (metabot-persistence/messages->client-messages
+ [(assoc base :finished nil :created_at recent)])
+ first
+ :status))))
+ (testing "finished=nil + stale created_at → aborted"
+ (is (= {:type "aborted"}
+ (-> (metabot-persistence/messages->client-messages
+ [(assoc base :finished nil :created_at stale)])
+ first
+ :status))))
(testing "finished=false → never filtered, even within grace"
- (is (=? [{:type "text" :message "" :finished false}]
- (metabot-persistence/messages->chat-messages
- [(assoc base :finished false :created_at recent)]))))
+ (is (= {:type "aborted"}
+ (-> (metabot-persistence/messages->client-messages
+ [(assoc base :finished false :created_at recent)])
+ first
+ :status))))
(testing "finished=true → never filtered"
- (is (= [] (metabot-persistence/messages->chat-messages
- [(assoc base :finished true :created_at recent)]))
- "no stub: finished=true with no error is a successful empty turn")))))
+ (let [message (first (metabot-persistence/messages->client-messages
+ [(assoc base :finished true :created_at recent)]))]
+ (is (= {:type "done"} (:status message)))
+ (is (= [] (:parts message))))))))
(deftest conversation-detail-filters-soft-deleted-messages-and-orders-ascending-test
(testing "conversation-detail returns only non-deleted messages, ordered by :created_at ascending"
@@ -620,7 +635,7 @@
:created-at (.plusSeconds now 3)
:deleted-at now})
(let [detail (metabot-persistence/conversation-detail conversation-id)
- texts (mapv :message (:messages detail))]
+ texts (mapv #(-> % :parts first :message) (:messages detail))]
(is (= conversation-id (:conversation_id detail)))
(is (= ["first" "second"] texts)))))))
@@ -798,7 +813,8 @@
(metabot-persistence/finalize-assistant-turn!
assistant-msg-id [{:type :text :text "retried reply"}])
(let [messages (:messages (metabot-persistence/conversation-detail conversation-id))]
- (is (= ["hi" "retried reply"] (map :message messages)))))))))))
+ (is (= ["hi" "retried reply"]
+ (map #(-> % :parts first :message) messages)))))))))))
(deftest retry-turn-deletes-all-trailing-assistant-rows-test
(testing "retry-turn! soft-deletes every live assistant row after the retried prompt"
@@ -868,48 +884,47 @@
(is (= assistant-external-id
(metabot-persistence/leaf-external-id conversation-id)))))))))
-(deftest message->chat-messages-annotates-agent-row-test
- (testing "empty :data on errored row emits a stub agent message so the FE can render the alert"
- (is (=? [{:id "ext-1" :role "agent" :type "text" :message ""
- :finished true :error {:message "boom"} :externalId "ext-1"}]
- (metabot-persistence/message->chat-messages
- {:role :assistant :error (json/encode {:message "boom"}) :finished true :data []
- :external_id "ext-1"}))))
- (testing "empty :data on aborted row also gets a stub"
- (is (=? [{:role "agent" :type "text" :message "" :finished false}]
- (metabot-persistence/message->chat-messages
- {:role :assistant :finished false :data []}))))
- (testing "empty :data on healthy row produces no messages"
- (is (= [] (metabot-persistence/message->chat-messages
- {:role :assistant :finished true :data []}))))
- (testing "agent message gets :finished true and no :error by default"
- (let [[msg] (metabot-persistence/message->chat-messages
- {:role :assistant :data [{:type "text" :text "ok"}]})]
- (is (=? {:finished true} msg))
- (is (not (contains? msg :error)))))
- (testing "agent message inherits :finished false from parent row"
- (is (=? [{:finished false}]
- (metabot-persistence/message->chat-messages
- {:role :assistant :finished false
- :data [{:type "text" :text "interrupted"}]}))))
- (testing "agent message inherits JSON-decoded :error from parent row"
- (is (=? [{:error {:message "boom" :type "RuntimeException"}}]
- (metabot-persistence/message->chat-messages
+(deftest message->client-message-status-test
+ (testing "empty :data on an errored row needs no stub because the row carries the alert status"
+ (let [message (client-message
+ {:role :assistant :error (json/encode {:message "boom"}) :finished true :data []
+ :external_id "ext-1"})]
+ (is (= [] (:parts message)))
+ (is (= {:type "errored" :error {:message "boom"}} (:status message)))))
+ (testing "empty :data on an aborted row needs no stub"
+ (let [message (client-message {:role :assistant :finished false :data []})]
+ (is (= [] (:parts message)))
+ (is (= {:type "aborted"} (:status message)))))
+ (testing "empty :data on a healthy row is a done message with no parts"
+ (let [message (client-message {:role :assistant :finished true :data []})]
+ (is (= [] (:parts message)))
+ (is (= {:type "done"} (:status message)))))
+ (testing "agent message is done by default"
+ (is (= {:type "done"}
+ (:status (client-message {:role :assistant :data [{:type "text" :text "ok"}]})))))
+ (testing "agent message inherits an aborted status from its row"
+ (let [message (client-message {:role :assistant :finished false
+ :data [{:type "text" :text "interrupted"}]})]
+ (is (= ["interrupted"] (part-messages message)))
+ (is (= {:type "aborted"} (:status message)))))
+ (testing "agent message inherits a JSON-decoded error status from its row"
+ (is (= {:type "errored" :error {:message "boom" :type "RuntimeException"}}
+ (:status
+ (client-message
{:role :assistant :finished true
:error (json/encode {:message "boom" :type "RuntimeException"})
- :data [{:type "text" :text "partial"}]}))))
+ :data [{:type "text" :text "partial"}]})))))
(testing "non-JSON :error column values fall through unchanged"
- (is (=? [{:error "raw legacy text"}]
- (metabot-persistence/message->chat-messages
- {:role :assistant :finished true :error "raw legacy text"
- :data [{:type "text" :text "partial"}]}))))
- (testing "user messages do not receive agent-only status fields"
- (let [[msg] (metabot-persistence/message->chat-messages
- {:role :user :data [{:type "text" :text "hi"}]})]
- (is (not-any? #(contains? msg %) [:finished :error]))))
- (testing "multi-block assistant row: only the last agent message is annotated"
- (let [result (metabot-persistence/message->chat-messages
- {:role :assistant :finished false
+ (is (= {:type "errored" :error "raw legacy text"}
+ (:status (client-message
+ {:role :assistant :finished true :error "raw legacy text"
+ :data [{:type "text" :text "partial"}]})))))
+ (testing "user messages have a done status"
+ (is (= {:type "done"}
+ (:status (client-message {:role :user :data [{:type "text" :text "hi"}]})))))
+ (testing "a multi-block assistant row carries one status without annotating its parts"
+ (let [message (client-message
+ {:role :assistant :finished true
:error (json/encode {:message "boom"})
:data [{:type "text" :text "first"}
{:type "tool-search" :toolCallId "call-1" :state "input-available" :input nil}
@@ -917,35 +932,40 @@
annotated? #(or (contains? % :finished) (contains? % :error))]
(is (=? [{:message "first"}
{:type "tool_call" :name "search"}
- {:message "last" :finished false :error {:message "boom"}}]
- result))
- (is (= [false false true] (mapv annotated? result))))))
+ {:message "last"}]
+ (:parts message)))
+ (is (= {:type "errored" :error {:message "boom"}} (:status message)))
+ (is (not-any? annotated? (:parts message))))))
-(deftest messages->chat-messages-errored-pairs-test
+(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"]
- (mapv :message
- (metabot-persistence/messages->chat-messages
- [{:role :user :data [{:type "text" :text "first"}]}
- {:role :assistant :data [{:type "text" :text "first reply"}]}
- {:role :user :data [{:type "text" :text "broken"}]}
- {:role :assistant :error (json/encode {:message "boom"}) :data []}
- {:role :user :data [{:type "text" :text "third"}]}
- {:role :assistant :data [{:type "text" :text "third reply"}]}])))))
- (testing "with :include-errored? true, errored pairs stay and :error surfaces on the agent message"
- (let [result (metabot-persistence/messages->chat-messages
- [{:role :user :data [{:type "text" :text "broken"}]}
- {:role :assistant :error (json/encode {:message "boom"}) :finished true
+ (mapv #(-> % :parts first :message)
+ (metabot-persistence/messages->client-messages
+ [{:id 1 :role :user :data [{:type "text" :text "first"}]}
+ {:id 2 :role :assistant :data [{:type "text" :text "first reply"}]}
+ {:id 3 :role :user :data [{:type "text" :text "broken"}]}
+ {:id 4 :role :assistant :error (json/encode {:message "boom"}) :data []}
+ {:id 5 :role :user :data [{:type "text" :text "third"}]}
+ {:id 6 :role :assistant :data [{:type "text" :text "third reply"}]}])))))
+ (testing "with :include-errored? true, errored pairs stay and the status carries the error"
+ (let [result (metabot-persistence/messages->client-messages
+ [{:id 1 :role :user :data [{:type "text" :text "broken"}]}
+ {:id 2 :role :assistant :error (json/encode {:message "boom"}) :finished true
:data [{:type "text" :text "partial"}]}
- {:role :user :data [{:type "text" :text "ok"}]}
- {:role :assistant :data [{:type "text" :text "fine"}]}]
+ {:id 3 :role :user :data [{:type "text" :text "ok"}]}
+ {:id 4 :role :assistant :data [{:type "text" :text "fine"}]}]
{:include-errored? true})]
- (is (= ["broken" "partial" "ok" "fine"] (mapv :message result)))
- (is (= [nil {:message "boom"} nil nil] (mapv :error result))))))
+ (is (= ["broken" "partial" "ok" "fine"] (mapv #(-> % :parts first :message) result)))
+ (is (= [{:type "done"}
+ {:type "errored" :error {:message "boom"}}
+ {:type "done"}
+ {:type "done"}]
+ (mapv :status result))))))
(defn- start-and-finalize!
"Run start-turn! then finalize-assistant-turn! with a one-text-part body (as :rasta).
- Returns `[asst-row chat-msg]`."
+ Returns `[asst-row client-message]`."
[& finalize-opts]
(let [conversation-id (str (random-uuid))]
(mt/with-current-user (mt/user->id :rasta)
@@ -957,7 +977,8 @@
[{:type :text :text "x"}]
finalize-opts)
(let [row (t2/select-one :model/MetabotMessage assistant-msg-id)]
- [row (first (metabot-persistence/message->chat-messages row))])))))
+ [row (first (metabot-persistence/messages->client-messages
+ [row] {:include-errored? true}))])))))
(deftest throwable->error-payload-test
(testing "matches the streamed :error part shape produced by the agent loop's
@@ -1020,18 +1041,18 @@
(testing "aborted: finished false flows through, no error"
(let [[row] (start-and-finalize! :finished? false)]
(is (=? {:finished false :error nil} row))))
- (testing "errored map: JSON-encoded into column, decoded onto chat msg; partial parts persisted"
+ (testing "errored map: JSON-encoded into column, decoded onto status; partial parts persisted"
(let [error-data {:message "agent loop API error: 503"
:type "java.lang.RuntimeException"
:data {:status 503}}
- [row chat-msg] (start-and-finalize! :error error-data)]
+ [row message] (start-and-finalize! :error error-data)]
(is (=? {:finished true :error string? :data seq} row))
(is (= error-data (json/decode+kw (:error row))))
- (is (= error-data (:error chat-msg)))))
+ (is (= {:type "errored" :error error-data} (:status message)))))
(testing "errored string: any JSON-serializable value accepted"
- (let [[row chat-msg] (start-and-finalize! :error "boom")]
+ (let [[row message] (start-and-finalize! :error "boom")]
(is (= "\"boom\"" (:error row)))
- (is (= "boom" (:error chat-msg)))))))
+ (is (= {:type "errored" :error "boom"} (:status message)))))))
(deftest finalize-persists-streamed-error-text-part-to-error-column-test
;; Regression guard: before the `aisdk-chunks->part` fix the error chunk passed through unchanged, so the
@@ -1062,38 +1083,39 @@
(is (true? (:finished row))
"an errored turn still finalizes as finished"))))))
-(deftest messages-chat-messages-in-flight-placeholders-test
+(deftest messages-client-messages-in-flight-placeholders-test
(testing "in-flight placeholders (assistant role, finished=nil, recent created_at)
- become a trailing turn_in_progress message, so a resumed mid-stream read
- renders a 'Response in progress…' row"
+ become an in-progress message envelope"
(let [recent (java.time.OffsetDateTime/now)
;; Comfortably outside the grace window so the test isn't sensitive
;; to the exact value of `placeholder-grace-period-ms`.
stale (.minusHours recent 2)
- placeholder {:role :assistant :data [] :finished nil :error nil :created_at recent}
- stale-stub {:role :assistant :data [] :finished nil :error nil :created_at stale}
- user-msg {:role :user :data [{:type "text" :text "hi"}]}
- done-asst {:role :assistant :data [{:type "text" :text "done"}] :finished true}]
- (testing "in-flight placeholder renders as turn_in_progress; surrounding messages still render"
- (let [out (metabot-persistence/messages->chat-messages [user-msg done-asst placeholder])]
- (is (= ["hi" "done" nil] (mapv :message out)))
- (is (= ["text" "text" "turn_in_progress"] (mapv :type out)))))
- (testing "stale placeholder (older than grace window) still renders as the aborted-turn stub"
- (let [out (metabot-persistence/messages->chat-messages [user-msg stale-stub])]
+ placeholder {:id 3 :role :assistant :data [] :finished nil :error nil :created_at recent}
+ stale-stub {:id 2 :role :assistant :data [] :finished nil :error nil :created_at stale}
+ user-msg {:id 1 :role :user :data [{:type "text" :text "hi"}]}
+ done-asst {:id 2 :role :assistant :data [{:type "text" :text "done"}] :finished true}]
+ (testing "in-flight placeholder carries the in-progress status; surrounding messages still render"
+ (let [out (metabot-persistence/messages->client-messages [user-msg done-asst placeholder])]
+ (is (= [["hi"] ["done"] []] (mapv part-messages out)))
+ (is (= [{:type "done"} {:type "done"} {:type "in_progress"}]
+ (mapv :status out)))))
+ (testing "stale placeholder (older than grace window) carries the aborted status"
+ (let [out (metabot-persistence/messages->client-messages [user-msg stale-stub])]
(is (= 2 (count out)))
- (is (=? [{:message "hi"} {:type "text" :message "" :finished false}] out))))
+ (is (= {:type "aborted"} (:status (second out))))
+ (is (= [] (:parts (second out))))))
(testing "row with :error set is treated as errored (not in-flight) — the errored pair is dropped from default reads but visible to the audit path"
- (let [errored {:role :assistant :data [] :finished true
+ (let [errored {:id 2 :role :assistant :data [] :finished true
:error (json/encode {:message "boom"})
:created_at recent}]
(is (= []
- (metabot-persistence/messages->chat-messages
+ (metabot-persistence/messages->client-messages
[user-msg errored] {:include-errored? false}))
"default read drops the errored row AND the preceding user prompt")
- (is (= ["hi" ""]
- (mapv :message (metabot-persistence/messages->chat-messages
- [user-msg errored] {:include-errored? true})))
- "audit read keeps both rows; the empty-data stub renders so the FE has somewhere to hang the error alert"))))))
+ (let [out (metabot-persistence/messages->client-messages
+ [user-msg errored] {:include-errored? true})]
+ (is (= [["hi"] []] (mapv part-messages out)))
+ (is (= {:type "errored" :error {:message "boom"}} (:status (second out))))))))))
;;; ---------------------------------------- used-table recording ----------------------------------------