🪢 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(trace-ui): collapse tool calls when there are many (#14718)
Nimarffb9bdb1175d
diff --git a/web/src/components/trace/components/IOPreview/components/ToolCallDefinitionCard.clienttest.tsx b/web/src/components/trace/components/IOPreview/components/ToolCallDefinitionCard.clienttest.tsxnew file mode 100644index 0000000000..0ea87c6928--- /dev/null+++ b/web/src/components/trace/components/IOPreview/components/ToolCallDefinitionCard.clienttest.tsx@@ -0,0 +1,159 @@+import { fireEvent, render, screen } from "@testing-library/react";+import { vi } from "vitest";++import {+ ToolCallDefinitionCard,+ type ToolDefinition,+} from "./ToolCallDefinitionCard";+import type { ToolCallInvocation } from "../hooks/useChatMLParser";++function createMemoryStorage(): Storage {+ const store = new Map<string, string>();++ return {+ get length() {+ return store.size;+ },+ clear: () => store.clear(),+ getItem: (key) => store.get(key) ?? null,+ key: (index) => Array.from(store.keys())[index] ?? null,+ removeItem: (key) => {+ store.delete(key);+ },+ setItem: (key, value) => {+ store.set(key, value);+ },+ };+}++const makeTool = (name: string): ToolDefinition => ({+ name,+ description: `${name} description`,+ parameters: { type: "object" },+});++function renderTools({+ calledToolCount,+ availableToolCount,+}: {+ calledToolCount: number;+ availableToolCount: number;+}) {+ const calledTools = Array.from({ length: calledToolCount }, (_, index) =>+ makeTool(`called_tool_${index + 1}`),+ );+ const availableTools = Array.from(+ { length: availableToolCount },+ (_, index) => makeTool(`available_tool_${index + 1}`),+ );+ const tools = [...calledTools, ...availableTools];+ const toolCallCounts = new Map<string, number>();+ const toolCallsByName = new Map<string, ToolCallInvocation[]>();+ const toolNameToDefinitionNumber = new Map<string, number>();++ tools.forEach((tool, index) => {+ toolNameToDefinitionNumber.set(tool.name, index + 1);+ });++ calledTools.forEach((tool, index) => {+ toolCallCounts.set(tool.name, 1);+ toolCallsByName.set(tool.name, [+ {+ id: `call-${index + 1}`,+ name: tool.name,+ arguments: "{}",+ invocationNumber: index + 1,+ },+ ]);+ });++ return render(+ <ToolCallDefinitionCard+ tools={tools}+ toolCallCounts={toolCallCounts}+ toolCallsByName={toolCallsByName}+ toolNameToDefinitionNumber={toolNameToDefinitionNumber}+ />,+ );+}++describe("ToolCallDefinitionCard", () => {+ beforeEach(() => {+ vi.stubGlobal("localStorage", createMemoryStorage());+ vi.stubGlobal("sessionStorage", createMemoryStorage());+ });++ it("renders up to five called tools individually", () => {+ renderTools({ calledToolCount: 5, availableToolCount: 0 });++ expect(+ screen.queryByRole("button", { name: /tools were called/i }),+ ).not.toBeInTheDocument();+ expect(screen.getByText(/called_tool_1/)).toBeInTheDocument();+ expect(screen.getByText(/called_tool_5/)).toBeInTheDocument();+ });++ it("collapses more than five called tools and expands them on click", () => {+ renderTools({ calledToolCount: 6, availableToolCount: 0 });++ expect(+ screen.getByRole("button", { name: /6 tools were called/i }),+ ).toBeInTheDocument();+ expect(screen.queryByText(/called_tool_1/)).not.toBeInTheDocument();++ fireEvent.click(+ screen.getByRole("button", { name: /6 tools were called/i }),+ );++ expect(screen.getByText(/called_tool_1/)).toBeInTheDocument();+ expect(screen.getByText(/called_tool_6/)).toBeInTheDocument();+ });++ it("persists called tool group expansion in session storage", () => {+ const { unmount } = renderTools({+ calledToolCount: 6,+ availableToolCount: 0,+ });++ fireEvent.click(+ screen.getByRole("button", { name: /6 tools were called/i }),+ );+ unmount();++ renderTools({ calledToolCount: 6, availableToolCount: 0 });++ expect(screen.getByText(/called_tool_1/)).toBeInTheDocument();+ });++ it("renders up to three available tools individually", () => {+ renderTools({ calledToolCount: 0, availableToolCount: 3 });++ expect(+ screen.queryByRole("button", {+ name: /available tools were not called/i,+ }),+ ).not.toBeInTheDocument();+ expect(screen.getByText(/available_tool_1/)).toBeInTheDocument();+ expect(screen.getByText(/available_tool_3/)).toBeInTheDocument();+ });++ it("collapses more than three available tools and expands them on click", () => {+ renderTools({ calledToolCount: 0, availableToolCount: 4 });++ expect(+ screen.getByRole("button", {+ name: /4 available tools were not called/i,+ }),+ ).toBeInTheDocument();+ expect(screen.queryByText(/available_tool_1/)).not.toBeInTheDocument();++ fireEvent.click(+ screen.getByRole("button", {+ name: /4 available tools were not called/i,+ }),+ );++ expect(screen.getByText(/available_tool_1/)).toBeInTheDocument();+ expect(screen.getByText(/available_tool_4/)).toBeInTheDocument();+ });+});diff --git a/web/src/components/trace/components/IOPreview/components/ToolCallDefinitionCard.tsx b/web/src/components/trace/components/IOPreview/components/ToolCallDefinitionCard.tsxindex 310dd6894b..6c89a7739c 100644--- a/web/src/components/trace/components/IOPreview/components/ToolCallDefinitionCard.tsx+++ b/web/src/components/trace/components/IOPreview/components/ToolCallDefinitionCard.tsx@@ -4,7 +4,8 @@ import { cn } from "@/src/utils/tailwind";import { PrettyJsonView } from "@/src/components/ui/PrettyJsonView";import { Tabs, TabsList, TabsTrigger } from "@/src/components/ui/tabs";import useLocalStorage from "@/src/components/useLocalStorage";-import { useState } from "react";+import useSessionStorage from "@/src/components/useSessionStorage";+import { useMemo, useState } from "react";import {HoverCard,HoverCardContent,@@ -28,6 +29,17 @@ export interface ToolCallDefinitionCardProps {className?: string;}+const CALLED_TOOLS_COLLAPSE_THRESHOLD = 5;+const AVAILABLE_TOOLS_COLLAPSE_THRESHOLD = 3;+const TOOL_GROUP_EXPANSION_STORAGE_KEY = "trace2-expansion:tools";++type ToolGroupExpansionState = {+ calledToolsExpanded: boolean;+ availableToolsExpanded: boolean;+};++type ToolGroupKind = "called" | "available";+function parseToolCallArguments(argumentsValue: unknown): unknown {if (typeof argumentsValue !== "string") {return argumentsValue;@@ -96,6 +108,154 @@ function ToolCallArgumentsList({);}+function getStatusText(callCount: number) {+ if (callCount === 0) return "not called";+ if (callCount === 1) return "called";+ return `called ${callCount}x`;+}++function ToolGroupHoverContent({+ tools,+ toolCallCounts,+ toolNameToDefinitionNumber,+}: {+ tools: ToolDefinition[];+ toolCallCounts: Map<string, number>;+ toolNameToDefinitionNumber?: Map<string, number>;+}) {+ return (+ <HoverCardContent+ side="bottom"+ align="start"+ sideOffset={6}+ className="max-h-96 w-80 max-w-[calc(100vw-2rem)] overflow-auto p-0"+ >+ <div className="flex flex-col gap-1 p-2">+ {tools.map((tool, index) => {+ const callCount = toolCallCounts.get(tool.name) ?? 0;+ const toolDefinitionNumber = toolNameToDefinitionNumber?.get(+ tool.name,+ );++ return (+ <div+ key={`${tool.name}-${index}`}+ className="flex min-w-0 items-center justify-between gap-2 rounded-sm px-2 py-1"+ >+ <div className="flex min-w-0 items-center gap-2">+ <Wrench className="text-muted-foreground h-3.5 w-3.5 shrink-0" />+ <span+ className="text-foreground block truncate font-mono text-xs font-medium"+ title={tool.name}+ >+ {toolDefinitionNumber !== undefined && (+ <span className="mr-1">{toolDefinitionNumber}.</span>+ )}+ {tool.name}+ </span>+ </div>+ <Badge+ variant={callCount > 0 ? undefined : "secondary"}+ className={cn(+ "shrink-0 text-xs font-medium",+ callCount > 0 &&+ "bg-light-green text-dark-green hover:bg-light-green border-transparent select-none",+ )}+ >+ {getStatusText(callCount)}+ </Badge>+ </div>+ );+ })}+ </div>+ </HoverCardContent>+ );+}++function ToolGroupSummary({+ kind,+ tools,+ expanded,+ onToggle,+ toolCallCounts,+ toolNameToDefinitionNumber,+}: {+ kind: ToolGroupKind;+ tools: ToolDefinition[];+ expanded: boolean;+ onToggle: () => void;+ toolCallCounts: Map<string, number>;+ toolNameToDefinitionNumber?: Map<string, number>;+}) {+ const isCalledGroup = kind === "called";+ const summaryText = isCalledGroup+ ? `${tools.length} ${tools.length === 1 ? "tool was" : "tools were"} called`+ : `${tools.length} available ${tools.length === 1 ? "tool was" : "tools were"} not called`;++ const summaryButton = (+ <button+ type="button"+ className={cn(+ "hover:bg-muted/20 flex w-full items-center justify-between gap-2 rounded-sm border px-3 py-2 text-left",+ isCalledGroup &&+ "border-light-green bg-accent-light-green hover:bg-accent-light-green/80",+ )}+ aria-expanded={expanded}+ onClick={onToggle}+ >+ <div className="flex min-w-0 items-center gap-2">+ <Wrench+ className={cn(+ "text-muted-foreground h-3.5 w-3.5 shrink-0",+ isCalledGroup && "text-dark-green",+ )}+ />+ <span+ className={cn(+ "truncate text-sm font-medium",+ isCalledGroup ? "text-dark-green" : "text-foreground",+ )}+ title={summaryText}+ >+ {summaryText}+ </span>+ </div>+ <div className="flex shrink-0 items-center gap-1.5">+ <Badge+ variant={isCalledGroup ? undefined : "secondary"}+ className={cn(+ "text-xs font-medium",+ isCalledGroup &&+ "bg-light-green text-dark-green hover:bg-light-green border-transparent select-none",+ )}+ >+ {expanded ? "hide" : "show"}+ </Badge>+ {expanded ? (+ <ChevronDown className="text-muted-foreground h-3.5 w-3.5" />+ ) : (+ <ChevronRight className="text-muted-foreground h-3.5 w-3.5" />+ )}+ </div>+ </button>+ );++ if (expanded) {+ return summaryButton;+ }++ return (+ <HoverCard openDelay={200} closeDelay={100}>+ <HoverCardTrigger asChild>{summaryButton}</HoverCardTrigger>+ <ToolGroupHoverContent+ tools={tools}+ toolCallCounts={toolCallCounts}+ toolNameToDefinitionNumber={toolNameToDefinitionNumber}+ />+ </HoverCard>+ );+}+function ToolCallStatusBadge({isCalled,statusText,@@ -147,6 +307,143 @@ function ToolCallStatusBadge({);}+function ToolDefinitionRow({+ tool,+ isExpanded,+ onToggle,+ callCount,+ toolCalls,+ toolDefinitionNumber,+ currentView,+ setCurrentView,+}: {+ tool: ToolDefinition;+ isExpanded: boolean;+ onToggle: () => void;+ callCount: number;+ toolCalls: ToolCallInvocation[];+ toolDefinitionNumber?: number;+ currentView: "formatted" | "json";+ setCurrentView: (value: "formatted" | "json") => void;+}) {+ const isCalled = callCount > 0;+ const statusText = getStatusText(callCount);++ return (+ <div className="w-full overflow-hidden rounded-sm border">+ <button+ type="button"+ className="hover:bg-muted/20 flex w-full cursor-pointer items-center justify-between gap-2 px-3 py-1.5 text-left"+ onClick={onToggle}+ aria-expanded={isExpanded}+ >+ <div className="flex min-w-0 items-center gap-2">+ <Wrench className="text-muted-foreground h-3.5 w-3.5 shrink-0" />+ <span+ className="text-foreground block truncate font-mono text-xs font-medium"+ title={tool.name}+ >+ {toolDefinitionNumber !== undefined && (+ <span className="mr-1">{toolDefinitionNumber}.</span>+ )}+ {tool.name}+ </span>+ </div>++ <div className="flex shrink-0 items-center gap-1.5">+ <ToolCallStatusBadge+ isCalled={isCalled}+ statusText={statusText}+ toolCalls={toolCalls}+ />++ {isExpanded ? (+ <ChevronDown className="text-muted-foreground h-3.5 w-3.5" />+ ) : (+ <ChevronRight className="text-muted-foreground h-3.5 w-3.5" />+ )}+ </div>+ </button>++ {isExpanded && (+ <div className="border-border bg-muted/30 relative border-t px-4 py-3">+ <div className="absolute top-1 right-4">+ <Tabs+ className="h-fit py-0.5"+ value={currentView}+ onValueChange={(value) =>+ setCurrentView(value as "formatted" | "json")+ }+ >+ <TabsList className="h-fit p-0.5">+ <TabsTrigger value="formatted" className="h-fit px-1 text-xs">+ Formatted+ </TabsTrigger>+ <TabsTrigger value="json" className="h-fit px-1 text-xs">+ JSON+ </TabsTrigger>+ </TabsList>+ </Tabs>+ </div>++ {currentView === "formatted" && (+ <div className="space-y-4">+ {tool.description && (+ <div>+ <div className="text-muted-foreground mb-1.5 text-xs font-medium">+ Description+ </div>+ <div className="text-foreground text-sm">+ {tool.description}+ </div>+ </div>+ )}++ {tool.parameters && (+ <div>+ <div className="text-muted-foreground mb-1.5 text-xs font-medium">+ Parameters+ </div>+ <PrettyJsonView+ json={tool.parameters}+ currentView="pretty"+ codeClassName="text-xs"+ />+ </div>+ )}++ {toolCalls.length > 0 && (+ <div>+ <div className="text-muted-foreground mb-1.5 text-xs font-medium">+ Tool call arguments+ </div>+ <ToolCallArgumentsList toolCalls={toolCalls} />+ </div>+ )}++ {!tool.description &&+ !tool.parameters &&+ toolCalls.length === 0 && (+ <div className="text-muted-foreground text-sm">+ No additional details available+ </div>+ )}+ </div>+ )}++ {currentView === "json" && (+ <PrettyJsonView+ json={tool}+ currentView="json"+ codeClassName="text-xs"+ />+ )}+ </div>+ )}+ </div>+ );+}+/*** ToolCallDefinitionCard renders expandable cards for tool definitions.*@@ -163,163 +460,118 @@ export function ToolCallDefinitionCard({toolNameToDefinitionNumber,className,}: ToolCallDefinitionCardProps) {- const [expandedIndex, setExpandedIndex] = useState<number | null>(null);+ const [expandedToolKey, setExpandedToolKey] = useState<string | null>(null);+ const [toolGroupExpansion, setToolGroupExpansion] =+ useSessionStorage<ToolGroupExpansionState>(+ TOOL_GROUP_EXPANSION_STORAGE_KEY,+ {+ calledToolsExpanded: false,+ availableToolsExpanded: false,+ },+ );const [currentView, setCurrentView] = useLocalStorage<"formatted" | "json">("toolCallPillViewPreference","formatted",);+ const { calledTools, availableTools } = useMemo(+ () =>+ tools.reduce(+ (groups, tool) => {+ const callCount = toolCallCounts.get(tool.name) ?? 0;+ if (callCount > 0) {+ groups.calledTools.push(tool);+ } else {+ groups.availableTools.push(tool);+ }+ return groups;+ },+ {+ calledTools: [] as ToolDefinition[],+ availableTools: [] as ToolDefinition[],+ },+ ),+ [tools, toolCallCounts],+ );+if (!tools || tools.length === 0) {return null;}- return (- <div className={cn("flex flex-col gap-2", className)}>- {tools.map((tool, index) => {- const isExpanded = expandedIndex === index;- const callCount = toolCallCounts.get(tool.name) || 0;- const isCalled = callCount > 0;- const toolCalls = toolCallsByName?.get(tool.name) ?? [];- const toolDefinitionNumber = toolNameToDefinitionNumber?.get(tool.name);- const statusText =- callCount === 0- ? "not called"- : callCount === 1- ? "called"- : `called ${callCount}x`;-- return (- <div- key={`${tool.name}-${index}`}- className="w-full overflow-hidden rounded-sm border"- >- {/* Card header */}- <div- className="hover:bg-muted/20 flex w-full cursor-pointer items-center justify-between gap-2 px-3 py-1.5"- onClick={() => {- setExpandedIndex(isExpanded ? null : index);- }}- >- {/* Left: Tool icon + definition number + name */}- <div className="flex min-w-0 items-center gap-2">- <Wrench className="text-muted-foreground h-3.5 w-3.5 shrink-0" />- <span- className="text-foreground block truncate font-mono text-xs font-medium"- title={tool.name}- >- {toolDefinitionNumber !== undefined && (- <span className="mr-1">{toolDefinitionNumber}.</span>- )}- {tool.name}- </span>- </div>+ const calledToolsShouldCollapse =+ calledTools.length > CALLED_TOOLS_COLLAPSE_THRESHOLD;+ const availableToolsShouldCollapse =+ availableTools.length > AVAILABLE_TOOLS_COLLAPSE_THRESHOLD;+ const showCalledTools =+ !calledToolsShouldCollapse || toolGroupExpansion.calledToolsExpanded;+ const showAvailableTools =+ !availableToolsShouldCollapse || toolGroupExpansion.availableToolsExpanded;- {/* Right: Status badge + chevron indicator */}- <div className="flex shrink-0 items-center gap-1.5">- <ToolCallStatusBadge- isCalled={isCalled}- statusText={statusText}- toolCalls={toolCalls}- />-- {/* Chevron indicator */}- {isExpanded ? (- <ChevronDown className="text-muted-foreground h-3.5 w-3.5" />- ) : (- <ChevronRight className="text-muted-foreground h-3.5 w-3.5" />- )}- </div>- </div>+ const renderToolRows = (+ toolsToRender: ToolDefinition[],+ groupKind: ToolGroupKind,+ ) =>+ toolsToRender.map((tool, index) => {+ const callCount = toolCallCounts.get(tool.name) || 0;+ const toolCalls = toolCallsByName?.get(tool.name) ?? [];+ const toolDefinitionNumber = toolNameToDefinitionNumber?.get(tool.name);+ const toolKey = `${groupKind}-${tool.name}-${index}`;+ const isExpanded = expandedToolKey === toolKey;- {/* Expanded details view */}- {isExpanded && (- <div className="border-border bg-muted/30 relative border-t px-4 py-3">- {/* View toggle tabs - positioned top right */}- <div className="absolute top-1 right-4">- <Tabs- className="h-fit py-0.5"- value={currentView}- onValueChange={(value) =>- setCurrentView(value as "formatted" | "json")- }- >- <TabsList className="h-fit p-0.5">- <TabsTrigger- value="formatted"- className="h-fit px-1 text-xs"- >- Formatted- </TabsTrigger>- <TabsTrigger value="json" className="h-fit px-1 text-xs">- JSON- </TabsTrigger>- </TabsList>- </Tabs>- </div>+ return (+ <ToolDefinitionRow+ key={toolKey}+ tool={tool}+ isExpanded={isExpanded}+ onToggle={() =>+ setExpandedToolKey((current) =>+ current === toolKey ? null : toolKey,+ )+ }+ callCount={callCount}+ toolCalls={toolCalls}+ toolDefinitionNumber={toolDefinitionNumber}+ currentView={currentView}+ setCurrentView={setCurrentView}+ />+ );+ });- {/* Formatted view */}- {currentView === "formatted" && (- <div className="space-y-4">- {/* Description */}- {tool.description && (- <div>- <div className="text-muted-foreground mb-1.5 text-xs font-medium">- Description- </div>- <div className="text-foreground text-sm">- {tool.description}- </div>- </div>- )}-- {/* Parameters */}- {tool.parameters && (- <div>- <div className="text-muted-foreground mb-1.5 text-xs font-medium">- Parameters- </div>- <PrettyJsonView- json={tool.parameters}- currentView="pretty"- codeClassName="text-xs"- />- </div>- )}-- {/* Tool call arguments */}- {toolCalls.length > 0 && (- <div>- <div className="text-muted-foreground mb-1.5 text-xs font-medium">- Tool call arguments- </div>- <ToolCallArgumentsList toolCalls={toolCalls} />- </div>- )}-- {/* Show message if no additional details */}- {!tool.description &&- !tool.parameters &&- toolCalls.length === 0 && (- <div className="text-muted-foreground text-sm">- No additional details available- </div>- )}- </div>- )}+ return (+ <div className={cn("flex flex-col gap-2", className)}>+ {calledToolsShouldCollapse && (+ <ToolGroupSummary+ kind="called"+ tools={calledTools}+ expanded={toolGroupExpansion.calledToolsExpanded}+ onToggle={() =>+ setToolGroupExpansion((current) => ({+ ...current,+ calledToolsExpanded: !current.calledToolsExpanded,+ }))+ }+ toolCallCounts={toolCallCounts}+ toolNameToDefinitionNumber={toolNameToDefinitionNumber}+ />+ )}+ {showCalledTools && renderToolRows(calledTools, "called")}- {/* JSON view - full tool object */}- {currentView === "json" && (- <PrettyJsonView- json={tool}- currentView="json"- codeClassName="text-xs"- />- )}- </div>- )}- </div>- );- })}+ {availableToolsShouldCollapse && (+ <ToolGroupSummary+ kind="available"+ tools={availableTools}+ expanded={toolGroupExpansion.availableToolsExpanded}+ onToggle={() =>+ setToolGroupExpansion((current) => ({+ ...current,+ availableToolsExpanded: !current.availableToolsExpanded,+ }))+ }+ toolCallCounts={toolCallCounts}+ toolNameToDefinitionNumber={toolNameToDefinitionNumber}+ />+ )}+ {showAvailableTools && renderToolRows(availableTools, "available")}</div>);}