Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

fix(agent): Improve tool call styling (#15084)

Ben Bachemc43e15df87f8
diff --git a/web/src/__tests__/server/in-app-agent-stream.servertest.ts b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
index 78bb1614e5..f22d86d581 100644
--- a/web/src/__tests__/server/in-app-agent-stream.servertest.ts
+++ b/web/src/__tests__/server/in-app-agent-stream.servertest.ts
@@ -8,6 +8,7 @@ import type { AgUiEvent } from "@/src/ee/features/in-app-agent/schema";
import {
IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER,
IN_APP_AGENT_REDIRECT_TOOL_NAME,
+ IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE,
} from "@/src/ee/features/in-app-agent/constants";
import { patchMastraToolCallInputStreaming } from "@/src/ee/features/in-app-agent/server/agent";
import {
@@ -1709,6 +1710,10 @@ describe("createAgUiStream", () => {
const { createAgUiStream } =
await import("@/src/ee/features/in-app-agent/server/agent");
const input = createToolApprovalResumeInput(false);
+ const rejectionError = JSON.stringify({
+ code: IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE,
+ message: "Tool call was not approved by the user.",
+ });
adapterEvents.inputs = [];
adapterEvents.items = [
{
@@ -1789,7 +1794,7 @@ describe("createAgUiStream", () => {
role: "tool",
toolCallId: "tool-call-1",
content: "Tool call was not approved by the user.",
- error: "Tool call was not approved by the user.",
+ error: rejectionError,
}),
expect.objectContaining({
id: "tool-call-1-approval-rejection-guidance",
@@ -1836,7 +1841,7 @@ describe("createAgUiStream", () => {
toolCallId: "tool-call-1",
content: "Tool call was not approved by the user.",
role: "tool",
- error: "Tool call was not approved by the user.",
+ error: rejectionError,
},
{
type: EventType.TEXT_MESSAGE_START,
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.tsx
index 583c6ec4ea..76026b5818 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
@@ -292,12 +292,14 @@ export const ToolCallGroup = meta.story({
{
type: "tool",
name: "langfuse_queryMetrics",
+ status: "succeeded",
args: JSON.stringify({ view: "observations" }),
result: JSON.stringify({ data: [{ count_count: 0 }] }),
},
{
type: "tool",
name: "langfuse_getTraces",
+ status: "succeeded",
args: JSON.stringify({ limit: 10 }),
result: JSON.stringify({ data: [] }),
},
@@ -306,6 +308,73 @@ export const ToolCallGroup = meta.story({
},
});
+export const MixedToolCallStatuses = meta.story({
+ args: {
+ role: "assistant",
+ content: {
+ type: "toolGroup",
+ tools: [
+ {
+ type: "tool",
+ name: "langfuse_queryMetrics",
+ status: "succeeded",
+ args: JSON.stringify({ view: "observations" }),
+ result: JSON.stringify({ data: [{ count_count: 42 }] }),
+ },
+ {
+ type: "tool",
+ name: "langfuse_getTraces",
+ status: "failed",
+ args: JSON.stringify({ limit: 10 }),
+ error: "Failed to load traces: missing project access.",
+ },
+ {
+ type: "tool",
+ name: "langfuse_upsertDataset",
+ status: "denied",
+ args: JSON.stringify({ name: "regression-examples" }),
+ result: "Tool call was not approved by the user.",
+ error: "Tool call was not approved by the user.",
+ },
+ ],
+ },
+ },
+});
+
+export const CompactMixedToolCallStatuses = meta.story({
+ args: {
+ role: "assistant",
+ content: {
+ type: "toolGroup",
+ tools: [
+ {
+ type: "tool",
+ name: "langfuse_queryMetrics",
+ status: "succeeded",
+ args: JSON.stringify({ view: "observations" }),
+ result: JSON.stringify({ data: [{ count_count: 42 }] }),
+ },
+ {
+ type: "tool",
+ name: "langfuse_getTraces",
+ status: "failed",
+ args: JSON.stringify({ limit: 10 }),
+ error: "Failed to load traces: missing project access.",
+ },
+ {
+ type: "tool",
+ name: "langfuse_upsertDataset",
+ status: "denied",
+ args: JSON.stringify({ name: "regression-examples" }),
+ result: "Tool call was not approved by the user.",
+ error: "Tool call was not approved by the user.",
+ },
+ ],
+ },
+ isCompact: true,
+ },
+});
+
export const SingleToolCallGroup = meta.story({
args: {
role: "assistant",
@@ -315,6 +384,7 @@ export const SingleToolCallGroup = meta.story({
{
type: "tool",
name: "langfuse_queryMetrics",
+ status: "succeeded",
args: JSON.stringify(
{
view: "observations",
@@ -373,12 +443,14 @@ export const LoadingToolCallGroup = meta.story({
{
type: "tool",
name: "langfuse_queryMetrics",
+ status: "succeeded",
args: JSON.stringify({ view: "observations" }),
result: JSON.stringify({ data: [{ count_count: 0 }] }),
},
{
type: "tool",
name: "langfuse_getTraces",
+ status: "running",
args: JSON.stringify({ limit: 10 }),
},
],
diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx
index 3c0a670db4..fc022a3582 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentMessage.tsx
@@ -1,14 +1,15 @@
"use client";
import {
ArrowRight,
+ Ban,
Check,
ChevronDown,
+ CircleX,
Copy,
BookOpenText,
Loader2,
ThumbsDown,
ThumbsUp,
- Wrench,
} from "lucide-react";
import Link from "next/link";
import { useRouter } from "next/router";
@@ -25,10 +26,10 @@ import {
type ButtonHTMLAttributes,
type ReactNode,
} from "react";
-import type {
- InAppAgentMessageFeedback,
- InAppAgentMessageFeedbackValue,
- InAppAgentMessageSource,
+import {
+ type InAppAgentMessageFeedback,
+ type InAppAgentMessageFeedbackValue,
+ type InAppAgentMessageSource,
} from "@/src/ee/features/in-app-agent/schema";
import {
Popover,
@@ -47,6 +48,7 @@ import {
} from "./utils/markdown";
import styles from "./InAppAgentMessage.module.css";
import { InAppAgentToolPayload } from "./InAppAgentToolPayload";
+import { InAppAgentToolResultPayload } from "./InAppAgentToolResultPayload";
import { type InAppAgentToolCallContent } from "@/src/ee/features/in-app-agent/components/utils/utils";
export type InAppAgentMessageRole = "assistant" | "user";
@@ -166,20 +168,11 @@ export function InAppAgentMessage({
if (content.type === "toolGroup") {
return (
- <div
- className={cn(
- "bg-card dark:bg-header text-foreground border-border rounded-2xl border py-2 shadow-xs",
- isCompact
- ? "rounded-xl py-1 text-[0.775rem]"
- : "rounded-2xl py-1.5 text-sm",
- )}
- >
- <ToolCallGroup
- tools={content.tools}
- isLoading={content.isLoading}
- isCompact={isCompact}
- />
- </div>
+ <ToolCallGroup
+ tools={content.tools}
+ isLoading={content.isLoading}
+ isCompact={isCompact}
+ />
);
}
@@ -683,82 +676,108 @@ function ToolCallGroup({
const label = `${isLoading ? "Calling" : "Called"} ${tools.length} ${
tools.length === 1 ? "tool" : "tools"
}`;
+ const [userToggled, setUserToggled] = useState<boolean | null>(null);
+ const isOpen = userToggled ?? isLoading;
- const paddingX = cn(isCompact ? "px-2.5" : "px-3");
- const iconSize = isCompact ? "size-3" : "size-4";
+ return (
+ <details
+ open={isOpen}
+ onToggle={(event) => {
+ 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="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-4 font-medium outline-none focus-visible:ring-2 focus-visible:ring-offset-2 [&::-webkit-details-marker]:hidden">
+ <span className={cn(isLoading && styles.thinkingShimmer)}>{label}</span>
+ <ChevronDown
+ className={cn(
+ "size-3.5 shrink-0 transition-transform",
+ !isOpen && "-rotate-90",
+ )}
+ />
+ </summary>
+ <div className="mt-0.5 flex flex-col gap-0">
+ {tools.map((tool, index) => (
+ <ToolCallDisclosure
+ key={`${tool.name}-${index}`}
+ tool={tool}
+ isCompact={isCompact}
+ />
+ ))}
+ </div>
+ </details>
+ );
+}
+
+function ToolCallDisclosure({
+ tool,
+ isCompact,
+}: {
+ tool: InAppAgentToolCallContent;
+ isCompact: boolean;
+}) {
+ const status = tool.status;
return (
- <details className="group/tool-group min-w-0">
+ <details className="group/tool min-w-0">
<summary
+ aria-label={`${tool.name}: ${status}`}
className={cn(
- "flex cursor-pointer list-none items-center gap-2 text-xs leading-none font-medium [&::-webkit-details-marker]:hidden",
- paddingX,
+ "hover:text-foreground focus-visible:ring-ring flex cursor-pointer list-none items-center gap-1.5 rounded-md px-1 py-0.5 text-xs leading-4 font-medium outline-none focus-visible:ring-2 focus-visible:ring-offset-2 [&::-webkit-details-marker]:hidden",
+ isCompact && "px-0.5",
)}
>
- {isLoading ? (
- <Loader2
- className={cn(
- "text-muted-foreground shrink-0 animate-spin",
- iconSize,
- )}
- />
- ) : (
- <Wrench className={cn("text-muted-foreground shrink-0", iconSize)} />
- )}
- <span className="min-w-0 flex-1 truncate py-0.5" title={label}>
- {label}
- </span>
- <span className="text-muted-foreground text-xs group-open/tool-group:hidden">
- Show
- </span>
- <span className="text-muted-foreground hidden text-xs group-open/tool-group:inline">
- Hide
+ <ToolCallStatusIcon status={status} />
+ <span
+ className={cn(
+ "min-w-0 flex-1 truncate py-0.5",
+ status === "failed" && "text-destructive",
+ status === "denied" && "text-dark-yellow",
+ )}
+ title={tool.name}
+ >
+ {tool.name}
</span>
</summary>
- <div
- className={cn("border-border mt-2 space-y-2 border-t pt-2", paddingX)}
- >
- {tools.map((tool, index) => {
- const resultLabel = tool.error ? "Error" : "Result";
- const toolLabel = `Used ${tool.name}`;
-
- return (
- <div key={`${tool.name}-${index}`} className="rounded-lg">
- <details className="group/tool min-w-0">
- <summary className="flex cursor-pointer list-none items-center gap-2 text-xs leading-none font-medium [&::-webkit-details-marker]:hidden">
- <Wrench className="text-muted-foreground h-3.5 w-3.5 shrink-0" />
- <span
- className="min-w-0 flex-1 truncate py-0.5"
- title={toolLabel}
- >
- {toolLabel}
- </span>
- <span className="text-muted-foreground text-xs group-open/tool:hidden">
- Show
- </span>
- <span className="text-muted-foreground hidden text-xs group-open/tool:inline">
- Hide
- </span>
- </summary>
- <div className="mt-2 space-y-2">
- <InAppAgentToolPayload label="Arguments" value={tool.args} />
- {tool.result !== undefined || tool.error !== undefined ? (
- <InAppAgentToolPayload
- label={resultLabel}
- value={tool.error ?? tool.result ?? ""}
- isError={Boolean(tool.error)}
- />
- ) : null}
- </div>
- </details>
- </div>
- );
- })}
+ <div className={cn("mt-1.5 mb-1 ml-3 px-3", isCompact && "px-2.5")}>
+ <div className="flex flex-col gap-2">
+ <InAppAgentToolPayload
+ label="Arguments"
+ value={tool.args}
+ variant="default"
+ />
+ <InAppAgentToolResultPayload tool={tool} />
+ </div>
</div>
</details>
);
}
+function ToolCallStatusIcon({
+ status,
+}: {
+ status: InAppAgentToolCallContent["status"];
+}) {
+ if (status === "running") {
+ return <Loader2 className="size-3.5 shrink-0 animate-spin" />;
+ }
+
+ if (status === "succeeded") {
+ return <Check className="text-dark-green size-3.5 shrink-0" />;
+ }
+
+ if (status === "failed") {
+ return <CircleX className="text-destructive size-3.5 shrink-0" />;
+ }
+
+ return <Ban className="text-dark-yellow size-3.5 shrink-0" />;
+}
+
function MessageText({
role,
text,
diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentToolCallCard.stories.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentToolCallCard.stories.tsx
index ae43f37fc7..0857fb08e0 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAgentToolCallCard.stories.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentToolCallCard.stories.tsx
@@ -12,6 +12,7 @@ export const Default = meta.story({
tool: {
type: "tool",
name: "langfuse_queryMetrics",
+ status: "succeeded",
args: JSON.stringify(
{
view: "observations",
@@ -31,6 +32,7 @@ export const Error = meta.story({
tool: {
type: "tool",
name: "langfuse_getTraces",
+ status: "failed",
args: JSON.stringify({ limit: 10 }, null, 2),
error: "Failed to load traces: missing project access.",
},
@@ -43,6 +45,7 @@ export const ApprovalRequired = meta.story({
tool: {
type: "tool",
name: "langfuse_upsertDataset",
+ status: "running",
args: JSON.stringify(
{
name: "regression-examples",
@@ -67,6 +70,7 @@ export const ApprovalSubmitting = meta.story({
tool: {
type: "tool",
name: "langfuse_upsertDataset",
+ status: "running",
args: JSON.stringify(
{
name: "regression-examples",
@@ -92,6 +96,7 @@ export const ApprovalDisabled = meta.story({
tool: {
type: "tool",
name: "langfuse_upsertDataset",
+ status: "running",
args: JSON.stringify(
{
name: "regression-examples",
diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentToolCallCard.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentToolCallCard.tsx
index a08171b001..c21223a9be 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAgentToolCallCard.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentToolCallCard.tsx
@@ -4,6 +4,7 @@ import { Check, Loader2, Wrench } from "lucide-react";
import { Button } from "@/src/components/ui/button";
import { cn } from "@/src/utils/tailwind";
import { InAppAgentToolPayload } from "./InAppAgentToolPayload";
+import { InAppAgentToolResultPayload } from "./InAppAgentToolResultPayload";
import { type InAppAgentToolCallContent } from "@/src/ee/features/in-app-agent/components/utils/utils";
export function InAppAgentToolCallCard({
@@ -22,7 +23,6 @@ export function InAppAgentToolCallCard({
const approval = tool.approval;
const isApprovalPending = approval?.status === "pending";
const isApprovalSubmitting = approval?.status === "submitting";
- const resultLabel = tool.error ? "Error" : "Result";
const approveLabel = `Approve ${tool.name}?`;
const usedLabel = `Used ${tool.name}`;
@@ -47,7 +47,11 @@ export function InAppAgentToolCallCard({
</span>
</div>
<div className="mt-2 space-y-2">
- <InAppAgentToolPayload label="Arguments" value={tool.args} />
+ <InAppAgentToolPayload
+ label="Arguments"
+ value={tool.args}
+ variant="default"
+ />
<div className="flex flex-wrap items-center gap-2">
<Button
type="button"
@@ -104,14 +108,12 @@ export function InAppAgentToolCallCard({
</span>
</summary>
<div className="mt-2 space-y-2">
- <InAppAgentToolPayload label="Arguments" value={tool.args} />
- {tool.result !== undefined || tool.error !== undefined ? (
- <InAppAgentToolPayload
- label={resultLabel}
- value={tool.error ?? tool.result ?? ""}
- isError={Boolean(tool.error)}
- />
- ) : null}
+ <InAppAgentToolPayload
+ label="Arguments"
+ value={tool.args}
+ variant="default"
+ />
+ <InAppAgentToolResultPayload tool={tool} />
</div>
</details>
)}
diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentToolPayload.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentToolPayload.tsx
index cb5185c48f..fee7ed731f 100644
--- a/web/src/ee/features/in-app-agent/components/InAppAgentToolPayload.tsx
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentToolPayload.tsx
@@ -6,11 +6,11 @@ import { cn } from "@/src/utils/tailwind";
export function InAppAgentToolPayload({
label,
value,
- isError = false,
+ variant,
}: {
label: string;
value: string;
- isError?: boolean;
+ variant: "default" | "failed" | "denied";
}) {
const toolPayload = useMemo(() => {
const trimmedValue = value.trim();
@@ -28,11 +28,22 @@ export function InAppAgentToolPayload({
return (
<div className="space-y-1">
- <p className="text-muted-foreground text-xs font-medium">{label}</p>
+ <p
+ className={cn(
+ "text-xs font-medium",
+ variant === "default" && "text-muted-foreground",
+ variant === "failed" && "text-destructive",
+ variant === "denied" && "text-dark-yellow",
+ )}
+ >
+ {label}
+ </p>
<pre
className={cn(
- "bg-muted text-muted-foreground max-h-64 overflow-auto rounded-md p-2 text-xs whitespace-pre-wrap",
- isError && "text-destructive",
+ "max-h-64 overflow-auto rounded-md p-2 text-xs whitespace-pre-wrap",
+ variant === "default" && "bg-muted text-muted-foreground",
+ variant === "failed" && "bg-destructive/10 text-destructive",
+ variant === "denied" && "bg-light-yellow text-dark-yellow",
)}
>
{toolPayload}
diff --git a/web/src/ee/features/in-app-agent/components/InAppAgentToolResultPayload.tsx b/web/src/ee/features/in-app-agent/components/InAppAgentToolResultPayload.tsx
new file mode 100644
index 0000000000..885b1441e9
--- /dev/null
+++ b/web/src/ee/features/in-app-agent/components/InAppAgentToolResultPayload.tsx
@@ -0,0 +1,37 @@
+"use client";
+
+import { InAppAgentToolPayload } from "./InAppAgentToolPayload";
+import type { InAppAgentToolCallContent } from "./utils/utils";
+
+const TOOL_CALL_RESULT_PRESENTATION = {
+ running: { label: "Result", variant: "default" },
+ succeeded: { label: "Result", variant: "default" },
+ failed: { label: "Error", variant: "failed" },
+ denied: { label: "Denied", variant: "denied" },
+} as const satisfies Record<
+ InAppAgentToolCallContent["status"],
+ {
+ label: string;
+ variant: "default" | "failed" | "denied";
+ }
+>;
+
+export function InAppAgentToolResultPayload({
+ tool,
+}: {
+ tool: InAppAgentToolCallContent;
+}) {
+ if (tool.result === undefined && tool.error === undefined) {
+ return null;
+ }
+
+ const presentation = TOOL_CALL_RESULT_PRESENTATION[tool.status];
+
+ return (
+ <InAppAgentToolPayload
+ label={presentation.label}
+ value={tool.error ?? tool.result ?? ""}
+ variant={presentation.variant}
+ />
+ );
+}
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.tsx
index cecd4e435c..ef58fc5abc 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
@@ -82,6 +82,7 @@ const streamingSeedMessages: InAppAgentWindowMessage[] = [
{
type: "tool",
name: "langfuse_queryMetrics",
+ status: "succeeded",
args: JSON.stringify({
view: "observations",
metrics: [{ measure: "latency", aggregation: "p95" }],
@@ -132,6 +133,21 @@ const streamingInvestigations = [
{ traceId: "trace-ret-219", latencyMs: 5410 },
],
},
+ subsequentTools: [
+ {
+ name: "langfuse_getObservations",
+ args: {
+ traceIds: ["trace-ret-104", "trace-ret-219"],
+ columns: ["name", "latency"],
+ },
+ result: {
+ data: [
+ { name: "document-reranking", latencyMs: 3910 },
+ { name: "vector-search", latencyMs: 480 },
+ ],
+ },
+ },
+ ],
conclusion:
"The slowest traces are retrieval-heavy. The expensive step is document reranking, not the initial vector search.",
},
@@ -155,6 +171,21 @@ const streamingInvestigations = [
{ scoreName: "groundedness", avg_value: 0.68 },
],
},
+ subsequentTools: [
+ {
+ name: "langfuse_getTraces",
+ args: {
+ limit: 5,
+ filter: "scoreName equals groundedness and scoreValue below 0.7",
+ },
+ result: {
+ data: [
+ { traceId: "trace-ret-104", groundedness: 0.61 },
+ { traceId: "trace-ret-219", groundedness: 0.65 },
+ ],
+ },
+ },
+ ],
conclusion:
"Quality moved down in the same segment. The groundedness score dropped most, which fits a retrieval or reranking regression.",
},
@@ -178,6 +209,17 @@ const streamingInvestigations = [
{ providedModelName: "gpt-4.1", totalTokens: 17610, latencyMs: 3610 },
],
},
+ subsequentTools: [
+ {
+ name: "langfuse_queryMetrics",
+ args: {
+ view: "observations",
+ metrics: [{ measure: "totalTokens", aggregation: "avg" }],
+ filter: "name contains retrieval",
+ },
+ result: { data: [{ avg_totalTokens: 8940 }] },
+ },
+ ],
conclusion:
"Model choice is stable, but token counts are much higher than the baseline. The reranker is likely passing too many documents forward.",
},
@@ -213,6 +255,7 @@ function StreamingInAppAgentWindow(args: InAppAgentWindowProps) {
cycle: number;
phase: StreamingPhase;
phaseTicks: number;
+ toolIndex: number;
reasoningMessageId: string;
introMessageId: string;
toolMessageId: string;
@@ -221,6 +264,7 @@ function StreamingInAppAgentWindow(args: InAppAgentWindowProps) {
cycle: 0,
phase: "start",
phaseTicks: 0,
+ toolIndex: 0,
reasoningMessageId: "",
introMessageId: "",
toolMessageId: "",
@@ -232,6 +276,15 @@ function StreamingInAppAgentWindow(args: InAppAgentWindowProps) {
const stream = streamRef.current;
const investigation =
streamingInvestigations[stream.cycle % streamingInvestigations.length];
+ const toolCalls = [
+ {
+ name: investigation.toolName,
+ args: investigation.toolArgs,
+ result: investigation.toolResult,
+ },
+ ...investigation.subsequentTools,
+ ];
+ const activeTool = toolCalls[stream.toolIndex];
if (stream.phase === "start") {
const cycleId = `stream-${stream.cycle}`;
@@ -241,6 +294,7 @@ function StreamingInAppAgentWindow(args: InAppAgentWindowProps) {
stream.conclusionMessageId = `${cycleId}-conclusion`;
stream.phase = "reasoning";
stream.phaseTicks = 0;
+ stream.toolIndex = 0;
setMessages((currentMessages) => [
...currentMessages,
@@ -349,8 +403,9 @@ function StreamingInAppAgentWindow(args: InAppAgentWindowProps) {
tools: [
{
type: "tool",
- name: investigation.toolName,
- args: JSON.stringify(investigation.toolArgs, null, 2),
+ name: activeTool.name,
+ status: "running",
+ args: JSON.stringify(activeTool.args, null, 2),
},
],
},
@@ -367,11 +422,18 @@ function StreamingInAppAgentWindow(args: InAppAgentWindowProps) {
return;
}
- stream.phase = "conclusion";
+ const completedToolIndex = stream.toolIndex;
+ const nextTool = toolCalls[completedToolIndex + 1];
+
+ if (nextTool) {
+ stream.toolIndex += 1;
+ } else {
+ stream.phase = "conclusion";
+ }
stream.phaseTicks = 0;
- setMessages((currentMessages) => [
- ...currentMessages.map((message) => {
+ setMessages((currentMessages) => {
+ const nextMessages = currentMessages.map((message) => {
if (
message.id !== stream.toolMessageId ||
message.content.type !== "toolGroup"
@@ -379,27 +441,49 @@ function StreamingInAppAgentWindow(args: InAppAgentWindowProps) {
return message;
}
+ const completedTools = message.content.tools.map((tool, index) =>
+ index === completedToolIndex
+ ? {
+ ...tool,
+ status: "succeeded" as const,
+ result: JSON.stringify(activeTool.result, null, 2),
+ }
+ : tool,
+ );
+
return {
...message,
content: {
type: "toolGroup" as const,
- tools: [
- {
- type: "tool" as const,
- name: investigation.toolName,
- args: JSON.stringify(investigation.toolArgs, null, 2),
- result: JSON.stringify(investigation.toolResult, null, 2),
- },
- ],
+ ...(nextTool ? { isLoading: true } : {}),
+ tools: nextTool
+ ? [
+ ...completedTools,
+ {
+ type: "tool" as const,
+ name: nextTool.name,
+ status: "running" as const,
+ args: JSON.stringify(nextTool.args, null, 2),
+ },
+ ]
+ : completedTools,
},
};
- }),
- {
- id: stream.conclusionMessageId,
- role: "assistant",
- content: { type: "text", text: "" },
- },
- ]);
+ });
+
+ if (nextTool) {
+ return nextMessages;
+ }
+
+ return [
+ ...nextMessages,
+ {
+ id: stream.conclusionMessageId,
+ role: "assistant",
+ content: { type: "text", text: "" },
+ },
+ ];
+ });
return;
}
@@ -550,6 +634,7 @@ export const ToolApprovalRequired = meta.story({
{
type: "tool",
name: "langfuse_upsertDataset",
+ status: "running",
args: JSON.stringify({
name: "regression-examples",
description: "Examples used for release regression tests",
@@ -603,6 +688,7 @@ export const Conversation = meta.story({
{
type: "tool",
name: "langfuse_queryMetrics",
+ status: "succeeded",
args: JSON.stringify({
view: "observations",
dimensions: [],
@@ -616,6 +702,7 @@ export const Conversation = meta.story({
{
type: "tool",
name: "langfuse_getTraces",
+ status: "succeeded",
args: JSON.stringify({ limit: 10 }),
result: JSON.stringify({ data: [] }),
},
@@ -796,6 +883,7 @@ export const LoadingAfterToolCall = meta.story({
{
type: "tool",
name: "langfuse_queryMetrics",
+ status: "succeeded",
args: JSON.stringify({
view: "observations",
metrics: [{ measure: "totalTokens", aggregation: "sum" }],
@@ -833,6 +921,7 @@ export const LoadingAfterToolCall = meta.story({
{
type: "tool",
name: "langfuse_getObservationFilterValues",
+ status: "succeeded",
args: JSON.stringify({
column: "providedModelName",
limit: 50,
@@ -1000,6 +1089,7 @@ export const RateLimited = meta.story({
{
type: "tool",
name: "langfuse_upsertDataset",
+ status: "running",
args: JSON.stringify({ name: "regression-examples" }),
approval: {
id: "approval-1",
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.ts
index d57d15ed2d..a748e586e6 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
@@ -127,12 +127,14 @@ describe("extractLangfuseDocsSources", () => {
type: "tool",
name: "langfuseDocs_search",
args: "{}",
+ status: "succeeded",
result,
},
{
type: "tool",
name: "langfuse_queryMetrics",
args: "{}",
+ status: "succeeded",
result,
},
]),
@@ -186,6 +188,7 @@ describe("extractLangfuseDocsSources", () => {
type: "tool",
name: "langfuseDocs_search",
args: "{}",
+ status: "succeeded",
result,
},
]),
@@ -194,6 +197,145 @@ describe("extractLangfuseDocsSources", () => {
});
describe("getDrawerMessages", () => {
+ it("maps tool results to explicit display statuses", () => {
+ const rejectionMessage = "Tool call was not approved by the user.";
+ const mappedMessages = getDrawerMessages({
+ error: null,
+ isRunning: true,
+ messages: [
+ {
+ id: "assistant-1",
+ role: "assistant",
+ content: "",
+ toolCalls: [
+ {
+ id: "tool-call-running",
+ type: "function",
+ function: { name: "running-tool", arguments: "{}" },
+ },
+ {
+ id: "tool-call-succeeded",
+ type: "function",
+ function: { name: "succeeded-tool", arguments: "{}" },
+ },
+ {
+ id: "tool-call-failed",
+ type: "function",
+ function: { name: "failed-tool", arguments: "{}" },
+ },
+ {
+ id: "tool-call-denied",
+ type: "function",
+ function: { name: "denied-tool", arguments: "{}" },
+ },
+ {
+ id: "tool-call-legacy-denied",
+ type: "function",
+ function: { name: "legacy-denied-tool", arguments: "{}" },
+ },
+ ],
+ },
+ {
+ id: "result-succeeded",
+ role: "tool",
+ toolCallId: "tool-call-succeeded",
+ content: JSON.stringify({ success: true }),
+ },
+ {
+ id: "result-failed",
+ role: "tool",
+ toolCallId: "tool-call-failed",
+ content: "Tool execution failed.",
+ error: "Tool execution failed.",
+ },
+ {
+ id: "result-denied",
+ role: "tool",
+ toolCallId: "tool-call-denied",
+ content: rejectionMessage,
+ error: JSON.stringify({
+ code: "tool_call_rejected",
+ message: rejectionMessage,
+ }),
+ },
+ {
+ id: "result-legacy-denied",
+ role: "tool",
+ toolCallId: "tool-call-legacy-denied",
+ content: rejectionMessage,
+ error: rejectionMessage,
+ },
+ ] satisfies AgUiMessage[],
+ });
+
+ expect(mappedMessages).toMatchObject([
+ {
+ content: {
+ type: "toolGroup",
+ tools: [
+ { name: "running-tool", status: "running" },
+ { name: "succeeded-tool", status: "succeeded" },
+ {
+ name: "failed-tool",
+ status: "failed",
+ error: "Tool execution failed.",
+ },
+ {
+ name: "denied-tool",
+ status: "denied",
+ error: rejectionMessage,
+ },
+ {
+ name: "legacy-denied-tool",
+ status: "denied",
+ error: rejectionMessage,
+ },
+ ],
+ },
+ },
+ ]);
+ });
+
+ it.each([
+ { error: null, isRunning: false, scenario: "the run stops" },
+ {
+ error: "The run was interrupted before the tool returned.",
+ isRunning: true,
+ scenario: "the run errors",
+ },
+ ])(
+ "marks result-less tools failed when $scenario",
+ ({ error, isRunning }) => {
+ const mappedMessages = getDrawerMessages({
+ error,
+ isRunning,
+ messages: [
+ {
+ id: "assistant-1",
+ role: "assistant",
+ content: "",
+ toolCalls: [
+ {
+ id: "tool-call-1",
+ type: "function",
+ function: { name: "interrupted-tool", arguments: "{}" },
+ },
+ ],
+ },
+ ] satisfies AgUiMessage[],
+ });
+
+ expect(mappedMessages).toMatchObject([
+ {
+ content: {
+ type: "toolGroup",
+ tools: [{ name: "interrupted-tool", status: "failed" }],
+ },
+ },
+ ]);
+ },
+ );
+
it("attaches docs sources to the answer after a search preamble", () => {
const docsResult = JSON.stringify({
_meta: {
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.ts
index 91fced1bf8..2aa5fbf38a 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
@@ -3,7 +3,11 @@ import type { InAppAgentWindowMessage } from "../InAppAgentWindow";
import type { InAppAgentPendingToolApproval } from "../InAppAiAgentProvider";
import type { InAppAgentMessageContent } from "../InAppAgentMessage";
import { deduplicateBy } from "@/src/utils/arrays";
-import { stableJsonStringify } from "@/src/utils/json";
+import { safeJsonParse, stableJsonStringify } from "@/src/utils/json";
+import {
+ IN_APP_AGENT_REDIRECT_TOOL_NAME,
+ IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE,
+} from "@/src/ee/features/in-app-agent/constants";
import {
AgUiMessageSchema,
type AgUiMessage,
@@ -12,7 +16,6 @@ import {
InAppAgentRedirectActionToolResultSchema,
InAppAgentMessageSourceSchema,
} from "@/src/ee/features/in-app-agent/schema";
-import { IN_APP_AGENT_REDIRECT_TOOL_NAME } from "@/src/ee/features/in-app-agent/constants";
export type InAppAgentError =
| { type: "generic"; message: string }
@@ -28,6 +31,7 @@ export type InAppAgentToolCallContent = {
type: "tool";
name: string;
args: string;
+ status: "running" | "succeeded" | "failed" | "denied";
result?: string;
error?: string;
approval?: {
@@ -36,6 +40,23 @@ export type InAppAgentToolCallContent = {
};
};
+const InAppAgentToolRejectionErrorSchema = z.object({
+ code: z.literal(IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE),
+ message: z.string(),
+});
+
+// Rejections persisted before structured error codes must remain readable.
+const LEGACY_IN_APP_AGENT_TOOL_REJECTION_MESSAGE =
+ "Tool call was not approved by the user.";
+
+const TOOL_CALL_STATUS_BY_RESULT_STATE = {
+ rejected: "denied",
+ error: "failed",
+ result: "succeeded",
+ pending: "running",
+ incomplete: "failed",
+} as const satisfies Record<string, InAppAgentToolCallContent["status"]>;
+
const InAppAgentTransportErrorSchema = z.object({
message: z.string().optional(),
payload: z.unknown().optional(),
@@ -316,11 +337,38 @@ export function getDrawerMessages({
mappedPendingApprovalIds.add(pendingApproval.id);
}
+ const rejectionError =
+ InAppAgentToolRejectionErrorSchema.safeParse(
+ result?.error ? safeJsonParse(result.error) : undefined,
+ );
+ const isRejected =
+ rejectionError.success ||
+ result?.error === LEGACY_IN_APP_AGENT_TOOL_REJECTION_MESSAGE;
+ let toolError = result?.error;
+ if (rejectionError.success) {
+ toolError = rejectionError.data.message;
+ }
+
+ let resultState: keyof typeof TOOL_CALL_STATUS_BY_RESULT_STATE;
+ if (isRejected) {
+ resultState = "rejected";
+ } else if (toolError !== undefined) {
+ resultState = "error";
+ } else if (result?.content !== undefined) {
+ resultState = "result";
+ } else if (isRunning && !error) {
+ resultState = "pending";
+ } else {
+ resultState = "incomplete";
+ }
+ const status = TOOL_CALL_STATUS_BY_RESULT_STATE[resultState];
+
return [
{
type: "tool",
name: toolCall.function.name,
args: toolCall.function.arguments,
+ status,
...(pendingApproval
? {
approval: {
@@ -332,9 +380,7 @@ export function getDrawerMessages({
...(result?.content !== undefined
? { result: result.content }
: {}),
- ...(result?.error !== undefined
- ? { error: result.error }
- : {}),
+ ...(toolError !== undefined ? { error: toolError } : {}),
},
];
},
@@ -430,6 +476,7 @@ export function getDrawerMessages({
type: "tool",
name: approval.approvalRequest.toolName,
args: stringifyToolArgs(approval.approvalRequest.args),
+ status: "running",
approval: {
id: approval.id,
status: approval.status,
diff --git a/web/src/ee/features/in-app-agent/constants.ts b/web/src/ee/features/in-app-agent/constants.ts
index 3ddfcba8af..c8c5b9bc1a 100644
--- a/web/src/ee/features/in-app-agent/constants.ts
+++ b/web/src/ee/features/in-app-agent/constants.ts
@@ -1,6 +1,8 @@
// Avoid renaming this as the FE is aware of this when rendering, renaming it would cause history issues
export const IN_APP_AGENT_REDIRECT_TOOL_NAME = "langfuse_proposeRedirect";
+export const IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE = "tool_call_rejected";
+
// Header used only by Langfuse's server-side in-app agent when it calls the
// Langfuse MCP endpoint with a temporary in-app-agent API key and run override.
export const IN_APP_AGENT_MCP_TOOL_OVERRIDE_HEADER =
diff --git a/web/src/ee/features/in-app-agent/server/human-in-the-loop.ts b/web/src/ee/features/in-app-agent/server/human-in-the-loop.ts
index 8203a9a392..5fc91eb3d9 100644
--- a/web/src/ee/features/in-app-agent/server/human-in-the-loop.ts
+++ b/web/src/ee/features/in-app-agent/server/human-in-the-loop.ts
@@ -4,6 +4,7 @@ import { z } from "zod";
import { InvalidRequestError } from "@langfuse/shared";
import { prisma } from "@langfuse/shared/src/db";
import type { McpToolName } from "@/src/features/mcp/server/bootstrap";
+import { IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE } from "@/src/ee/features/in-app-agent/constants";
import { IN_APP_AGENT_LANGFUSE_MCP_TOOL_NAMES } from "@/src/ee/features/in-app-agent/server/tools";
import { safeJsonParse, stableJsonStringify } from "@/src/utils/json";
import {
@@ -14,9 +15,14 @@ import {
type ResumeForwardedProps,
} from "@/src/ee/features/in-app-agent/schema";
-export const IN_APP_AGENT_PENDING_TOOL_APPROVAL_TTL_SECONDS = 60 * 60;
const MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE =
"Tool call was not approved by the user.";
+const MANUAL_TOOL_APPROVAL_REJECTION_ERROR = JSON.stringify({
+ code: IN_APP_AGENT_TOOL_REJECTION_ERROR_CODE,
+ message: MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE,
+});
+
+export const IN_APP_AGENT_PENDING_TOOL_APPROVAL_TTL_SECONDS = 60 * 60;
const PendingToolApprovalSchema = z.object({
toolCallId: z.string().min(1),
@@ -183,7 +189,7 @@ export async function createManualToolApprovalRunInput(params: {
role: "tool",
content: MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE,
toolCallId: approvalRequest.toolCallId,
- error: MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE,
+ error: MANUAL_TOOL_APPROVAL_REJECTION_ERROR,
};
return {
@@ -200,7 +206,7 @@ export async function createManualToolApprovalRunInput(params: {
syntheticEvents: createManualToolApprovalEvents({
approvalRequest,
toolResultContent: MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE,
- toolError: MANUAL_TOOL_APPROVAL_REJECTION_MESSAGE,
+ toolError: MANUAL_TOOL_APPROVAL_REJECTION_ERROR,
}),
toolCallApproval: {
toolCallId: approvalRequest.toolCallId,