🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
feat(assistant): show live reasoning in the in-app agent (LFE-10706) (#14878)
Lysander Kieselfdec4675e517
diff --git a/.env.dev.example b/.env.dev.exampleindex fcdfd5bc1a..c77b15ac32 100644--- a/.env.dev.example+++ b/.env.dev.example@@ -189,7 +189,7 @@ LANGFUSE_AWS_BEDROCK_REGION="eu-west-1"# `eu.anthropic.claude-opus-4-8`. Set that here to match prod exactly. Weak/old# models (e.g. `eu.anthropic.claude-3-haiku-20240307-v1:0`) degrade refine quality# — they tend to ignore the existing filters and replace instead of narrowing.-LANGFUSE_AWS_BEDROCK_MODEL="eu.anthropic.claude-haiku-4-5-20251001-v1:0"+LANGFUSE_AWS_BEDROCK_MODEL="eu.anthropic.claude-opus-4-8"LANGFUSE_AWS_BEDROCK_SMALL_MODEL="eu.anthropic.claude-haiku-4-5-20251001-v1:0"LANGFUSE_IN_APP_AGENT_AWS_PROFILE="playground"diff --git a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts b/web/src/__tests__/server/in-app-agent-persistence.servertest.tsindex a6a7d92e2c..f6a47c924f 100644--- a/web/src/__tests__/server/in-app-agent-persistence.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-persistence.servertest.ts@@ -769,6 +769,20 @@ describe("in-app agent persistence", () => {where: { projectId, conversationId: conversation.id, runId: run.id },}),).resolves.toBe(9);++ const persistedEventTypes = (+ await prisma.inAppAgentEvent.findMany({+ where: { projectId, conversationId: conversation.id, runId: run.id },+ select: { type: true },+ })+ ).map((event) => event.type);+ expect(persistedEventTypes).not.toContain(+ EventType.REASONING_MESSAGE_START,+ );+ expect(persistedEventTypes).not.toContain(+ EventType.REASONING_MESSAGE_CONTENT,+ );+ expect(persistedEventTypes).not.toContain(EventType.REASONING_MESSAGE_END);});it("stores only compact events and skips raw adapter payloads", async () => {diff --git a/web/src/__tests__/server/in-app-agent-stream.servertest.ts b/web/src/__tests__/server/in-app-agent-stream.servertest.tsindex b000faa150..e8ebdf5edb 100644--- a/web/src/__tests__/server/in-app-agent-stream.servertest.ts+++ b/web/src/__tests__/server/in-app-agent-stream.servertest.ts@@ -522,7 +522,7 @@ describe("createAgUiStream", () => {});});- it("serializes valid events including adapter message snapshots", async () => {+ it("serializes valid events including adapter snapshots and reasoning messages", async () => {const { createAgUiStream } =await import("@/src/ee/features/in-app-agent/server/agent");const input = {@@ -584,6 +584,20 @@ describe("createAgUiStream", () => {},],},+ {+ type: EventType.REASONING_MESSAGE_START,+ messageId: "reasoning-message-1",+ role: "reasoning",+ },+ {+ type: EventType.REASONING_MESSAGE_CONTENT,+ messageId: "reasoning-message-1",+ delta: "Checking the current trace context.",+ },+ {+ type: EventType.REASONING_MESSAGE_END,+ messageId: "reasoning-message-1",+ },{type: EventType.TEXT_MESSAGE_START,messageId: "assistant-message-1",@@ -614,7 +628,9 @@ describe("createAgUiStream", () => {eventOrder.push(`persist:${event.type}`);await Promise.resolve();},- awsBedrock: { modelId: "test-model" },+ awsBedrock: {+ modelId: "eu.anthropic.claude-opus-4-8",+ },langfuseMcp: {url: "https://example.com/api/public/mcp",publicKey: "pk",@@ -642,6 +658,7 @@ describe("createAgUiStream", () => {});expect(streamedText).toContain(EventType.MESSAGES_SNAPSHOT);+ expect(streamedText).toContain(EventType.REASONING_MESSAGE_CONTENT);expect(adapterEvents.inputs).toEqual([input]);const { Agent } = await import("@mastra/core/agent");expect(Agent).toHaveBeenCalledWith(@@ -673,6 +690,16 @@ describe("createAgUiStream", () => {}),);const agentConfig = vi.mocked(Agent).mock.calls[0]?.[0];+ expect(agentConfig?.defaultOptions).toMatchObject({+ maxSteps: 10,+ providerOptions: {+ bedrock: {+ additionalModelRequestFields: {+ thinking: { type: "adaptive", display: "summarized" },+ },+ },+ },+ });expect(agentConfig?.tools).not.toHaveProperty("langfuse_search");expect(agentConfig?.tools?.langfuse_getHealth).not.toHaveProperty("requireApproval",@@ -760,6 +787,9 @@ describe("createAgUiStream", () => {expect(persistedEvents.map((event) => event.type)).toEqual([EventType.RUN_STARTED,EventType.MESSAGES_SNAPSHOT,+ EventType.REASONING_MESSAGE_START,+ EventType.REASONING_MESSAGE_CONTENT,+ EventType.REASONING_MESSAGE_END,EventType.TEXT_MESSAGE_START,EventType.TEXT_MESSAGE_CONTENT,EventType.TEXT_MESSAGE_END,@@ -774,6 +804,12 @@ describe("createAgUiStream", () => {`stream:${EventType.RUN_STARTED}`,`persist:${EventType.MESSAGES_SNAPSHOT}`,`stream:${EventType.MESSAGES_SNAPSHOT}`,+ `persist:${EventType.REASONING_MESSAGE_START}`,+ `stream:${EventType.REASONING_MESSAGE_START}`,+ `persist:${EventType.REASONING_MESSAGE_CONTENT}`,+ `stream:${EventType.REASONING_MESSAGE_CONTENT}`,+ `persist:${EventType.REASONING_MESSAGE_END}`,+ `stream:${EventType.REASONING_MESSAGE_END}`,`persist:${EventType.TEXT_MESSAGE_START}`,`stream:${EventType.TEXT_MESSAGE_START}`,`persist:${EventType.TEXT_MESSAGE_CONTENT}`,@@ -803,6 +839,9 @@ describe("createAgUiStream", () => {).toEqual([EventType.RUN_STARTED,EventType.MESSAGES_SNAPSHOT,+ EventType.REASONING_MESSAGE_START,+ EventType.REASONING_MESSAGE_CONTENT,+ EventType.REASONING_MESSAGE_END,EventType.TEXT_MESSAGE_START,EventType.TEXT_MESSAGE_CONTENT,EventType.TEXT_MESSAGE_END,@@ -812,6 +851,78 @@ describe("createAgUiStream", () => {expect(instrumentationMocks.instrumentation.flush).toHaveBeenCalled();});+ it("does not enable Bedrock reasoning for non-Claude models", async () => {+ const { createAgUiStream } =+ await import("@/src/ee/features/in-app-agent/server/agent");+ const input = {+ threadId: "conversation-1",+ runId: "run-1",+ messages: [+ {+ id: "user-message-1",+ role: "user" as const,+ content: "hello",+ },+ ],+ tools: [],+ context: [],+ state: {+ type: "existingConversation" as const,+ projectId: "project-1",+ conversationId: "conversation-1",+ },+ forwardedProps: {},+ };+ const langfuseClient = {+ getPrompt: promptMocks.getPrompt,+ };++ adapterEvents.items = [+ {+ type: EventType.RUN_STARTED,+ threadId: input.threadId,+ runId: input.runId,+ },+ {+ type: EventType.RUN_FINISHED,+ threadId: input.threadId,+ runId: input.runId,+ },+ ];++ const stream = await createAgUiStream({+ input,+ signal: new AbortController().signal,+ options: {+ awsBedrock: {+ modelId: "meta.llama3-70b-instruct-v1:0",+ },+ langfuseMcp: {+ url: "https://example.com/api/public/mcp",+ publicKey: "pk",+ secretKey: "sk",+ userAccess: defaultInAppAgentUserAccess,+ runOverride: "run-override",+ },+ redirectAction: {+ projectId: "project-1",+ isV4Enabled: false,+ },+ langfuseClient,+ useLocalPrompt: false,+ },+ });++ await readStream(stream);++ const { Agent } = await import("@mastra/core/agent");+ const agentConfig = vi.mocked(Agent).mock.calls[0]?.[0];+ expect(agentConfig?.defaultOptions).toMatchObject({+ maxSteps: 10,+ });+ expect(agentConfig?.defaultOptions).not.toHaveProperty("providerOptions");+ });+it("executes approved tools manually and continues with tool result history", async () => {const { createAgUiStream } =await import("@/src/ee/features/in-app-agent/server/agent");diff --git a/web/src/__tests__/server/unit/in-app-agent-reasoning.servertest.ts b/web/src/__tests__/server/unit/in-app-agent-reasoning.servertest.tsnew file mode 100644index 0000000000..ee43ec685e--- /dev/null+++ b/web/src/__tests__/server/unit/in-app-agent-reasoning.servertest.ts@@ -0,0 +1,33 @@+import { getBedrockReasoningProviderOptions } from "@/src/ee/features/in-app-agent/server/agent";++describe("getBedrockReasoningProviderOptions", () => {+ it("sends adaptive thinking with summarized display to Claude models by default", () => {+ // Adaptive thinking is the default for every Claude model, including+ // unrecognized future generations, so no model list needs maintenance.+ // The config must go through additionalModelRequestFields, not+ // reasoningConfig — @ai-sdk/amazon-bedrock overwrites+ // additionalModelRequestFields.thinking when reasoningConfig is set,+ // which would silently drop the summarized display and blank the+ // reasoning UI.+ for (const modelId of [+ "eu.anthropic.claude-opus-4-8",+ "us.anthropic.claude-sonnet-5",+ "eu.anthropic.claude-fable-5",+ "anthropic.claude-sonnet-6-20270101-v1:0",+ ]) {+ expect(getBedrockReasoningProviderOptions(modelId)).toEqual({+ bedrock: {+ additionalModelRequestFields: {+ thinking: { type: "adaptive", display: "summarized" },+ },+ },+ });+ }+ });++ it("sends no thinking config for non-Claude models", () => {+ expect(+ getBedrockReasoningProviderOptions("meta.llama3-70b-instruct-v1:0"),+ ).toBeUndefined();+ });+});diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.module.css b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.module.cssindex 31d8acb51c..04128f8d00 100644--- a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.module.css+++ b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.module.css@@ -111,3 +111,37 @@.Streamdown:not(.compact) table {@apply my-2.5;}++/* Label of a live reasoning block: a highlight sweeping left to right. */+.thinkingShimmer {+ animation: thinking-shimmer 2s linear infinite;+ background-image: linear-gradient(+ 90deg,+ hsl(var(--muted-foreground)) 35%,+ hsl(var(--foreground)) 50%,+ hsl(var(--muted-foreground)) 65%+ );+ background-size: 200% 100%;+ -webkit-background-clip: text;+ background-clip: text;+ color: transparent;+ padding-block: 0.25em;+ margin-block: -0.25em;+}++@keyframes thinking-shimmer {+ from {+ background-position: 200% 0;+ }+ to {+ background-position: -200% 0;+ }+}++@media (prefers-reduced-motion: reduce) {+ .thinkingShimmer {+ animation: none;+ background-image: none;+ color: inherit;+ }+}diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.stories.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.stories.tsxindex e48ccbff4c..583c6ec4ea 100644--- a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.stories.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.stories.tsx@@ -386,6 +386,60 @@ export const LoadingToolCallGroup = meta.story({},});+const longReasoningText = [+ "Reading the current trace context and the visible filters.",+ "Checking whether the user is asking about latency, quality, or cost first.",+ "Comparing recent observations with error levels and score names.",+ "Looking for a small query that can answer the next step without changing project state.",+ "Keeping this text long enough to span several lines so the block visibly grows with its content.",+ "The last line should be visible after mount and after streamed updates.",+].join("\n");++export const Reasoning = meta.story({+ args: {+ role: "assistant",+ content: {+ type: "reasoning",+ text: "Checking recent traces before querying metrics.",+ isStreaming: false,+ },+ },+});++export const CompletedReasoning = meta.story({+ args: {+ role: "assistant",+ content: {+ type: "reasoning",+ text: longReasoningText,+ isStreaming: false,+ },+ },+});++export const StreamingReasoning = meta.story({+ args: {+ role: "assistant",+ content: {+ type: "reasoning",+ text: longReasoningText,+ isStreaming: true,+ },+ },+});++export const CompactStreamingReasoning = meta.story({+ args: {+ role: "assistant",+ isCompact: true,+ content: {+ type: "reasoning",+ text: longReasoningText,+ isStreaming: true,+ },+ },+});+export const Loading = meta.story({args: {role: "assistant",diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsxindex a99489953f..3c0a670db4 100644--- a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx@@ -2,6 +2,7 @@import {ArrowRight,Check,+ ChevronDown,Copy,BookOpenText,Loader2,@@ -58,6 +59,7 @@ type InAppAgentRedirectActionContent = {export type InAppAgentMessageContent =| { type: "loading"; label?: string }+ | { type: "reasoning"; text: string; isStreaming: boolean }| {type: "text";text: string;@@ -181,6 +183,10 @@ export function InAppAgentMessage({);}+ if (content.type === "reasoning") {+ return <InAppAgentReasoningBlock content={content} isCompact={isCompact} />;+ }+if (content.type === "text" && role === "assistant") {return (<AssistantMessageWithFeedback@@ -201,7 +207,7 @@ const MessageCard = forwardRef<role: InAppAgentMessageRole;content: Exclude<InAppAgentMessageContent,- { type: "toolGroup" | "redirectAction" }+ { type: "toolGroup" | "redirectAction" | "reasoning" }>;isCompact: boolean;}@@ -298,6 +304,75 @@ function AssistantMessageWithFeedback({);}+function InAppAgentReasoningBlock({+ content,+ isCompact,+}: {+ content: Extract<InAppAgentMessageContent, { type: "reasoning" }>;+ isCompact: boolean;+}) {+ // null until the user toggles manually; until then the disclosure follows+ // the streaming state (open while streaming, collapsed when done).+ const [userToggled, setUserToggled] = useState<boolean | null>(null);+ const isOpen = userToggled ?? content.isStreaming;++ return (+ <details+ open={isOpen}+ onToggle={(event) => {+ // The browser also fires toggle when React flips `open` at stream+ // start/end; only record toggles that diverge from the current state.+ if (event.currentTarget.open !== isOpen) {+ setUserToggled(event.currentTarget.open);+ }+ }}+ className={cn(+ "text-muted-foreground max-w-full",+ isCompact ? "text-[0.775rem]" : "text-sm",+ )}+ >+ <summary+ className={cn(+ "hover:text-foreground focus-visible:ring-ring flex w-fit cursor-pointer list-none items-center gap-1.5 rounded-md px-1 py-0.5 text-xs leading-none font-medium outline-none focus-visible:ring-2 focus-visible:ring-offset-2 [&::-webkit-details-marker]:hidden",+ isCompact && "px-0.5",+ )}+ >+ <span+ className={cn(+ "min-w-0 flex-1",+ content.isStreaming && styles.thinkingShimmer,+ )}+ >+ {content.isStreaming ? "Thinking" : "Thought"}+ </span>+ <ChevronDown+ className={cn(+ "size-3.5 shrink-0 transition-transform",+ !isOpen && "-rotate-90",+ )}+ />+ </summary>+ {isOpen ? (+ // The block grows with its content instead of scrolling internally;+ // the drawer's auto-follow keeps the newest text visible while+ // streaming, and the block collapses when streaming ends.+ <div+ aria-label="Assistant reasoning"+ data-testid="in-app-agent-reasoning-content"+ className={cn(+ // Vertical spacing is margin, not padding, so the left border+ // hugs the text instead of extending past it.+ "border-border/70 mt-2 mb-1 border-l px-3 leading-5 wrap-break-word whitespace-pre-wrap",+ isCompact && "px-2.5 leading-4",+ )}+ >+ {content.text || "Thinking..."}+ </div>+ ) : null}+ </details>+ );+}+function MessageFeedbackControls({feedback,isCompact,diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.stories.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.stories.tsxindex f03761adc3..950c93ecdb 100644--- a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.stories.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.stories.tsx@@ -113,6 +113,11 @@ const streamingSeedMessages: InAppAgentWindowMessage[] = [const streamingInvestigations = [{prompt: "Check whether the spike is isolated to retrieval.",+ reasoning: [+ "The user suspects retrieval, so I should isolate retrieval-heavy traces before looking anywhere else.",+ "Sorting by latency and filtering on the trace name keeps the query small and read-only.",+ "If the slowest traces are all retrieval traces, the next step is comparing them against quality scores.",+ ].join("\n"),intro:"I am checking retrieval-heavy traces first because their p95 latency moved before generation latency changed.",toolName: "langfuse_getTraces",@@ -132,6 +137,10 @@ const streamingInvestigations = [},{prompt: "Compare the same window against quality scores.",+ reasoning: [+ "Latency alone does not tell us whether users were affected, so I am joining the slow segment with scores.",+ "Averaging per score name is enough resolution to spot a quality regression without a heavy query.",+ ].join("\n"),intro:"Next I am joining the slow traces with score distributions so we can see whether the latency spike also changed output quality.",toolName: "langfuse_queryMetrics",@@ -151,6 +160,11 @@ const streamingInvestigations = [},{prompt: "Inspect model usage for the outlier traces.",+ reasoning: [+ "A fallback model or a larger context window can explain slow traces even when retrieval is healthy.",+ "Fetching model name, token counts, and latency for just the two outlier traces keeps this cheap.",+ "High token counts with a stable model would point back at the reranker passing too many documents.",+ ].join("\n"),intro:"I am checking model and token usage because a fallback model or larger context window can make otherwise healthy traces slow.",toolName: "langfuse_getObservations",@@ -189,6 +203,7 @@ function StreamingInAppAgentWindow(args: InAppAgentWindowProps) {);type StreamingPhase =| "start"+ | "reasoning"| "intro"| "tool-loading"| "tool-done"@@ -198,6 +213,7 @@ function StreamingInAppAgentWindow(args: InAppAgentWindowProps) {cycle: number;phase: StreamingPhase;phaseTicks: number;+ reasoningMessageId: string;introMessageId: string;toolMessageId: string;conclusionMessageId: string;@@ -205,6 +221,7 @@ function StreamingInAppAgentWindow(args: InAppAgentWindowProps) {cycle: 0,phase: "start",phaseTicks: 0,+ reasoningMessageId: "",introMessageId: "",toolMessageId: "",conclusionMessageId: "",@@ -218,10 +235,11 @@ function StreamingInAppAgentWindow(args: InAppAgentWindowProps) {if (stream.phase === "start") {const cycleId = `stream-${stream.cycle}`;+ stream.reasoningMessageId = `${cycleId}-reasoning`;stream.introMessageId = `${cycleId}-intro`;stream.toolMessageId = `${cycleId}-tool`;stream.conclusionMessageId = `${cycleId}-conclusion`;- stream.phase = "intro";+ stream.phase = "reasoning";stream.phaseTicks = 0;setMessages((currentMessages) => [@@ -232,15 +250,66 @@ function StreamingInAppAgentWindow(args: InAppAgentWindowProps) {content: { type: "text", text: investigation.prompt },},{- id: stream.introMessageId,+ id: stream.reasoningMessageId,role: "assistant",- content: { type: "text", text: "" },+ content: { type: "reasoning", text: "", isStreaming: true },},]);return;}+ if (stream.phase === "reasoning") {+ setMessages((currentMessages) => {+ const nextMessages = currentMessages.map((message) => {+ if (+ message.id !== stream.reasoningMessageId ||+ message.content.type !== "reasoning"+ ) {+ return message;+ }++ const text = appendToken(+ message.content.text,+ investigation.reasoning,+ );++ // The block collapses once the assistant's text answer arrives,+ // mirroring getDrawerMessages semantics.+ const isDone = text === investigation.reasoning;++ if (isDone) {+ stream.phase = "intro";+ stream.phaseTicks = 0;+ }++ return {+ ...message,+ content: {+ type: "reasoning" as const,+ text,+ isStreaming: !isDone,+ },+ };+ });++ if (stream.phase !== "intro") {+ return nextMessages;+ }++ return [+ ...nextMessages,+ {+ id: stream.introMessageId,+ role: "assistant",+ content: { type: "text", text: "" },+ },+ ];+ });++ return;+ }+if (stream.phase === "intro") {setMessages((currentMessages) =>currentMessages.map((message) => {@@ -411,6 +480,14 @@ const conversations = [const longUnbrokenWord = `trace-${"0123456789abcdef".repeat(18)}`;const longUnbrokenTableValue = `observation-${"abcdefghijklmnopqrstuvwxyz".repeat(10)}`;+const longReasoningText = [+ "Reading the current drawer context and selected project state.",+ "Checking active filters before choosing the smallest safe query.",+ "Comparing recent traces, observations, and score names for a matching latency signal.",+ "Waiting for the first tool call result before drafting a final answer.",+ "Keeping this text intentionally long so the reasoning block spans several lines while the drawer follows the conversation bottom.",+ "The final streamed line should remain visible inside the reasoning block.",+].join("\n");const meta = preview.meta({component: InAppAgentWindow,@@ -504,6 +581,15 @@ export const Conversation = meta.story({text: "Which traces had the highest latency today?",},},+ {+ id: "assistant-reasoning-1",+ role: "assistant",+ content: {+ type: "reasoning",+ text: longReasoningText,+ isStreaming: false,+ },+ },{id: "assistant-tool-1",role: "assistant",diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsxindex 17a48939f5..b8bd08a1c9 100644--- a/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx+++ b/web/src/ee/features/in-app-agent/components/InAppAgentWindow.tsx@@ -486,7 +486,8 @@ export function InAppAgentWindow(props: InAppAgentWindowProps) {{visibleMessages.map((message, index) => {const hasFullWidthContent =message.content.type === "toolGroup" ||- message.content.type === "redirectAction";+ message.content.type === "redirectAction" ||+ message.content.type === "reasoning";const nextUserMessageIndex = visibleMessages.findIndex((nextMessage, nextIndex) =>diff --git a/web/src/ee/features/in-app-agent/components/utils/utils.clienttest.ts b/web/src/ee/features/in-app-agent/components/utils/utils.clienttest.tsindex 57231d81ca..87ce17cd03 100644--- a/web/src/ee/features/in-app-agent/components/utils/utils.clienttest.ts+++ b/web/src/ee/features/in-app-agent/components/utils/utils.clienttest.ts@@ -223,6 +223,278 @@ describe("getDrawerMessages", () => {expect(mappedMessages[1]?.content).not.toHaveProperty("sources");});+ it("shows live reasoning messages while the run is active", () => {+ const mappedMessages = getDrawerMessages({+ error: null,+ isRunning: true,+ messages: [+ {+ id: "user-1",+ role: "user",+ content: "Investigate latency spikes",+ },+ {+ id: "reasoning-1",+ role: "reasoning",+ content: "Checking recent traces before querying metrics.",+ },+ ] satisfies AgUiMessage[],+ });++ expect(mappedMessages).toMatchObject([+ {+ id: "user-1",+ role: "user",+ content: {+ type: "text",+ text: "Investigate latency spikes",+ },+ },+ {+ id: "reasoning-1",+ role: "assistant",+ content: {+ type: "reasoning",+ text: "Checking recent traces before querying metrics.",+ isStreaming: true,+ },+ },+ ]);+ expect(mappedMessages).toHaveLength(2);+ });++ it("marks reasoning complete when a run stops before assistant text arrives", () => {+ const mappedMessages = getDrawerMessages({+ error: "The run was interrupted before an answer was generated.",+ isRunning: false,+ messages: [+ {+ id: "user-1",+ role: "user",+ content: "Investigate latency spikes",+ },+ {+ id: "reasoning-1",+ role: "reasoning",+ content: "Checking recent traces before querying metrics.",+ },+ ] satisfies AgUiMessage[],+ });++ expect(mappedMessages).toMatchObject([+ {+ id: "user-1",+ role: "user",+ content: {+ type: "text",+ text: "Investigate latency spikes",+ },+ },+ {+ id: "reasoning-1",+ role: "assistant",+ content: {+ type: "reasoning",+ text: "Checking recent traces before querying metrics.",+ isStreaming: false,+ },+ },+ ]);+ expect(mappedMessages).toHaveLength(2);+ });++ it("keeps reasoning open while later tool calls run before the assistant response", () => {+ const mappedMessages = getDrawerMessages({+ error: null,+ isRunning: true,+ messages: [+ {+ id: "user-1",+ role: "user",+ content: "Find failed traces",+ },+ {+ id: "reasoning-1",+ role: "reasoning",+ content: "Looking for error-level traces first.",+ },+ {+ id: "assistant-1",+ role: "assistant",+ content: "",+ toolCalls: [+ {+ id: "tool-call-1",+ type: "function",+ function: {+ name: "langfuse_queryMetrics",+ arguments: JSON.stringify({ view: "traces" }),+ },+ },+ ],+ },+ ] satisfies AgUiMessage[],+ });++ expect(mappedMessages).toMatchObject([+ {+ id: "user-1",+ content: { type: "text" },+ },+ {+ id: "reasoning-1",+ content: {+ type: "reasoning",+ text: "Looking for error-level traces first.",+ isStreaming: true,+ },+ },+ {+ id: "tools-assistant-1",+ content: {+ type: "toolGroup",+ isLoading: true,+ },+ },+ ]);+ });++ it("keeps only the latest reasoning block streaming in a multi-step tool loop", () => {+ const mappedMessages = getDrawerMessages({+ error: null,+ isRunning: true,+ messages: [+ {+ id: "user-1",+ role: "user",+ content: "Find failed traces",+ },+ {+ id: "reasoning-1",+ role: "reasoning",+ content: "Looking for error-level traces first.",+ },+ {+ id: "assistant-1",+ role: "assistant",+ content: "",+ toolCalls: [+ {+ id: "tool-call-1",+ type: "function",+ function: {+ name: "langfuse_queryMetrics",+ arguments: JSON.stringify({ view: "traces" }),+ },+ },+ ],+ },+ {+ id: "tool-result-1",+ role: "tool",+ toolCallId: "tool-call-1",+ content: JSON.stringify({ error: "Metrics API unavailable" }),+ },+ {+ id: "reasoning-2",+ role: "reasoning",+ content: "The metrics query failed, retrying with a smaller window.",+ },+ {+ id: "assistant-2",+ role: "assistant",+ content: "",+ toolCalls: [+ {+ id: "tool-call-2",+ type: "function",+ function: {+ name: "langfuse_queryMetrics",+ arguments: JSON.stringify({ view: "traces", limit: 10 }),+ },+ },+ ],+ },+ ] satisfies AgUiMessage[],+ });++ expect(mappedMessages).toMatchObject([+ {+ id: "user-1",+ content: { type: "text" },+ },+ {+ id: "reasoning-1",+ content: {+ type: "reasoning",+ isStreaming: false,+ },+ },+ {+ id: "tools-assistant-1",+ content: { type: "toolGroup" },+ },+ {+ id: "reasoning-2",+ content: {+ type: "reasoning",+ isStreaming: true,+ },+ },+ {+ id: "tools-assistant-2",+ content: { type: "toolGroup" },+ },+ ]);+ });++ it("drops completed reasoning messages without content but keeps streaming ones", () => {+ const mappedMessages = getDrawerMessages({+ error: null,+ isRunning: true,+ messages: [+ {+ id: "user-1",+ role: "user",+ content: "Find failed traces",+ },+ {+ // Adaptive thinking can emit a reasoning start/end pair without any+ // content; once completed there is nothing to disclose.+ id: "reasoning-empty",+ role: "reasoning",+ content: "",+ },+ {+ id: "assistant-1",+ role: "assistant",+ content: "I found 12 failed traces in the selected window.",+ },+ {+ id: "user-2",+ role: "user",+ content: "And in the week before?",+ },+ {+ id: "reasoning-live",+ role: "reasoning",+ content: "",+ },+ ] satisfies AgUiMessage[],+ });++ expect(mappedMessages).toMatchObject([+ { id: "user-1" },+ { id: "assistant-1" },+ { id: "user-2" },+ {+ id: "reasoning-live",+ content: { type: "reasoning", text: "", isStreaming: true },+ },+ ]);+ expect(mappedMessages).toHaveLength(4);+ });+it("adds pending tool approvals as approval tool groups", () => {const mappedMessages = getDrawerMessages({error: null,diff --git a/web/src/ee/features/in-app-agent/components/utils/utils.ts b/web/src/ee/features/in-app-agent/components/utils/utils.tsindex 6c0800ee65..4cb33cc949 100644--- a/web/src/ee/features/in-app-agent/components/utils/utils.ts+++ b/web/src/ee/features/in-app-agent/components/utils/utils.ts@@ -158,24 +158,30 @@ export function getDrawerMessages({}const role = message.role === "user" ? "user" : "assistant";- const isLoading = message.role === "reasoning";- if (isLoading) {+ if (message.role === "reasoning") {flushPendingTools();- const hasLaterAssistantMessage = parsedMessages.some(- (message, messageIndex) =>- messageIndex > index && message.role === "assistant",- );+ const isStreaming =+ isRunning &&+ !error &&+ !hasLaterConversationMessageAfter(parsedMessages, index);- if (!isRunning || hasLaterAssistantMessage) {+ // Adaptive thinking can emit a reasoning start/end pair without any+ // content; a completed empty block has nothing to disclose, so only a+ // still-streaming one is rendered (as its "Thinking..." placeholder).+ if (!message.content.trim() && !isStreaming) {return;}mappedMessages.push({id: message.id,role,- content: { type: "loading" },+ content: {+ type: "reasoning",+ text: message.content,+ isStreaming,+ },});return;}@@ -341,6 +347,7 @@ export function getDrawerMessages({latestUserMessageIndex >= 0 &&latestAssistantMessage?.content.type !== "text" &&latestAssistantMessage?.content.type !== "loading" &&+ latestAssistantMessage?.content.type !== "reasoning" &&latestAssistantMessage?.content.type !== "redirectAction") {if (latestAssistantMessage?.content.type === "toolGroup") {@@ -374,6 +381,31 @@ export function getDrawerMessages({return mappedMessages;}+// A reasoning block stays live while the model is still acting on it — the+// tool calls and tool results it triggered keep it open. It only collapses+// once the model has visibly moved on: a newer reasoning block, an assistant+// message with text, or a new user turn.+function hasLaterConversationMessageAfter(+ messages: readonly AgUiMessage[],+ currentIndex: number,+) {+ return messages.some((message, messageIndex) => {+ if (messageIndex <= currentIndex) {+ return false;+ }++ if (message.role === "reasoning" || message.role === "user") {+ return true;+ }++ return (+ message.role === "assistant" &&+ typeof message.content === "string" &&+ message.content.trim().length > 0+ );+ });+}+function stringifyToolArgs(args: unknown) {if (typeof args === "string") {return args;diff --git a/web/src/ee/features/in-app-agent/server/agent.ts b/web/src/ee/features/in-app-agent/server/agent.tsindex a4f4b15af4..4bc6671c73 100644--- a/web/src/ee/features/in-app-agent/server/agent.ts+++ b/web/src/ee/features/in-app-agent/server/agent.ts@@ -44,6 +44,7 @@ const LOCAL_IN_APP_AGENT_SYSTEM_PROMPT_DIR = path.join("src/ee/features/in-app-agent/prompts/",);const MAX_AGENT_STEPS = 10;+const BEDROCK_CLAUDE_MODEL_ID_PART = "anthropic.claude";const LANGFUSE_DOCS_MCP_URL = "https://langfuse.com/api/mcp";// Screen context is included as data only. Tool execution safety is enforced by@@ -116,6 +117,29 @@ ${serializedContext}`;}+// Adaptive thinking is the default for every Claude model so new generations+// work without maintaining a model list. Older models that only support+// thinking.type.enabled (e.g. haiku 4.5) reject adaptive with a 400 — the+// in-app agent must run on a model generation that supports it.+export function getBedrockReasoningProviderOptions(modelId: string) {+ if (!modelId.includes(BEDROCK_CLAUDE_MODEL_ID_PART)) {+ return undefined;+ }++ return {+ bedrock: {+ // Passed as raw request fields instead of reasoningConfig because+ // @ai-sdk/amazon-bedrock overwrites additionalModelRequestFields+ // .thinking when reasoningConfig is set, and these models default+ // display to "omitted" (empty thinking text) — without "summarized"+ // the reasoning UI would render blank blocks.+ additionalModelRequestFields: {+ thinking: { type: "adaptive" as const, display: "summarized" },+ },+ },+ };+}+type CreateAgUiStreamOptions = {onEvent?: (event: AgUiEvent) => void | Promise<void>;onApprovedToolCallExecuted?: () => void | Promise<void>;@@ -768,6 +792,10 @@ async function createMastraAdapter(params: {});params.onToolsAvailable?.(tools);+ const reasoningProviderOptions = getBedrockReasoningProviderOptions(+ params.options.awsBedrock.modelId,+ );+const agent = new Agent({id: "langfuse-in-app-assistant",name: ASSISTANT_TITLE,@@ -780,6 +808,9 @@ async function createMastraAdapter(params: {defaultOptions: {abortSignal: params.signal,maxSteps: MAX_AGENT_STEPS,+ ...(reasoningProviderOptions+ ? { providerOptions: reasoningProviderOptions }+ : {}),},});diff --git a/web/src/ee/features/in-app-agent/server/persistence.ts b/web/src/ee/features/in-app-agent/server/persistence.tsindex be39825030..9a1093070f 100644--- a/web/src/ee/features/in-app-agent/server/persistence.ts+++ b/web/src/ee/features/in-app-agent/server/persistence.ts@@ -655,6 +655,8 @@ export function toPersistableAgentEvent(event: AgUiEvent): AgUiEvent | null {event.type === EventType.STEP_STARTED ||event.type === EventType.STEP_FINISHED ||event.type === EventType.TOOL_CALL_CHUNK ||+ // Reasoning is a live responsiveness signal. Keep plaintext reasoning out+ // of persisted conversation history and replay.event.type === EventType.REASONING_START ||event.type === EventType.REASONING_MESSAGE_START ||event.type === EventType.REASONING_MESSAGE_CHUNK ||@@ -910,6 +912,7 @@ export function createConversationMessageAccumulator(event.type === EventType.STEP_STARTED ||event.type === EventType.STEP_FINISHED ||event.type === EventType.TOOL_CALL_CHUNK ||+ // Reasoning is live-only; do not reconstruct it from persisted history.event.type === EventType.REASONING_START ||event.type === EventType.REASONING_MESSAGE_START ||event.type === EventType.REASONING_MESSAGE_CHUNK ||