Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
✂️ refactor: Name Tool Rounds From the Trace, and Match a Cut Response From Its End (#16113)
Danny Avila29ed0993a8bd
diff --git a/client/src/components/Chat/Trace/Inspector.tsx b/client/src/components/Chat/Trace/Inspector.tsxindex 2b9e310f90..76df52d34b 100644--- a/client/src/components/Chat/Trace/Inspector.tsx+++ b/client/src/components/Chat/Trace/Inspector.tsx@@ -223,9 +223,12 @@ function AgentCard({ agent, agentId }: { agent: RecordPresentation['agent']; age/** A tool round's calls as the chat's own tool cards hold them: no trace read, no content gate. */function ToolCalls({calls,+ fromConversation,mcpIconMap,}: {calls: ToolCallView[];+ /** The chat's own message supplied the calls; otherwise they are only the names the trace recorded. */+ fromConversation: boolean;mcpIconMap: Map<string, string>;}) {const localize = useLocalize();@@ -246,7 +249,9 @@ function ToolCalls({<ContentBlock label="com_ui_trace_tool_returned" content={toContent(call.output)} /></div>))}- <p className="text-xs text-text-secondary">{localize('com_ui_trace_from_conversation')}</p>+ {fromConversation && (+ <p className="text-xs text-text-secondary">{localize('com_ui_trace_from_conversation')}</p>+ )}</section>);}@@ -414,7 +419,11 @@ function Inspector({{!leadsWithContent && preview}{leadsWithContent && content}{presentation.calls != null && (- <ToolCalls calls={presentation.calls} mcpIconMap={mcpIconMap} />+ <ToolCalls+ calls={presentation.calls}+ fromConversation={presentation.callsFrom === 'conversation'}+ mcpIconMap={mcpIconMap}+ />)}<Section title="com_ui_trace_timing" fields={timing} /><Sectiondiff --git a/client/src/components/Chat/Trace/Ledger.tsx b/client/src/components/Chat/Trace/Ledger.tsxindex af2f2ac86f..2d6c199bea 100644--- a/client/src/components/Chat/Trace/Ledger.tsx+++ b/client/src/components/Chat/Trace/Ledger.tsx@@ -130,6 +130,7 @@ function Ledger({toolTitleFor,agentOf,unrecordedCalls,+ stepOffsets,mcpIconMap,onSelect,onToggle,@@ -148,6 +149,8 @@ function Ledger({agentOf: (agentId: string) => Agent | undefined;/** Tool calls the trace names no record for, by response, as the chat's messages count them. */unrecordedCalls: ReadonlyMap<string, number>;+ /** Steps of a response that ran before its first loaded one, by response. */+ stepOffsets: ReadonlyMap<string, number>;mcpIconMap: Map<string, string>;onSelect: (id: string) => void;onToggle: (key: string) => void;@@ -419,7 +422,9 @@ function Ledger({label:step.origin === 'title'? localize('com_ui_trace_title_step')- : localize('com_ui_trace_step', { 0: String(step.index) }),+ : localize('com_ui_trace_step', {+ 0: String(step.index + (stepOffsets.get(step.messageId) ?? 0)),+ }),description: stepDescription(step),errorCount: step.errorCount,recordCount: step.recordCount,diff --git a/client/src/components/Chat/Trace/Viewer.tsx b/client/src/components/Chat/Trace/Viewer.tsxindex 6530514f18..162cf19701 100644--- a/client/src/components/Chat/Trace/Viewer.tsx+++ b/client/src/components/Chat/Trace/Viewer.tsx@@ -42,7 +42,7 @@ import {buildTraceModel,collapsibleKeys,} from './model';-import { buildPreviews, buildPreviewIndex, buildActivityIndex } from './preview';+import { alignTurns, buildPreviews, buildPreviewIndex, buildActivityIndex } from './preview';import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';import { traceModeAtom, traceScaleAtom } from './store';import { presentTool, presentRecord } from './present';@@ -167,17 +167,21 @@ export default function Viewer({* its rounds cannot be numbered against the message until they are. */const partialMessageId =recordsQuery.hasNextPage === true ? model.turns[0]?.messageId : undefined;- const previewIndex = useMemo(- () => buildPreviewIndex(model, previews, partialMessageId),+ const alignments = useMemo(+ () => alignTurns(model, previews, partialMessageId),[model, previews, partialMessageId],);+ const previewIndex = useMemo(+ () => buildPreviewIndex(model, previews, partialMessageId, alignments),+ [model, previews, partialMessageId, alignments],+ );const previewOf = useCallback((node: TraceNode) => previewIndex.get(node.record.id),[previewIndex],);const activity = useMemo(- () => buildActivityIndex(model, previews, partialMessageId),- [model, previews, partialMessageId],+ () => buildActivityIndex(model, previews, partialMessageId, alignments),+ [model, previews, partialMessageId, alignments],);const agentsMap = useAgentsMapContext();const mcpIconMap = useMCPIconMap();@@ -530,6 +534,7 @@ export default function Viewer({toolTitleFor={toolTitleFor}agentOf={agentOf}unrecordedCalls={activity.unrecordedCalls}+ stepOffsets={activity.stepOffsets}mcpIconMap={mcpIconMap}onSelect={setSelectedId}onToggle={toggle}diff --git a/client/src/components/Chat/Trace/__tests__/Viewer.test.tsx b/client/src/components/Chat/Trace/__tests__/Viewer.test.tsxindex f02436fb71..64721a752e 100644--- a/client/src/components/Chat/Trace/__tests__/Viewer.test.tsx+++ b/client/src/components/Chat/Trace/__tests__/Viewer.test.tsx@@ -251,12 +251,13 @@ describe('Trace Viewer', () => {expect(screen.queryByRole('treeitem', { name: recordName('later-a') })).not.toBeInTheDocument();});- it('withholds previews for a response split across pages until its earlier steps load', async () => {+ it('previews a response split across pages from its end, then its earlier steps as they load', async () => {const generation = (id: string, offset: number) =>record({id,messageId: 'response-2',traceId: 'trace-2',+ parentId: 'wrapper-the-limit-cut',name: id,kind: 'generation',startTime: at(offset),@@ -286,10 +287,8 @@ describe('Trace Viewer', () => {],),);- await recordRow('later-2,');- expect(- screen.queryByRole('treeitem', { name: /later-2: First round/ }),- ).not.toBeInTheDocument();+ expect(await recordRow('later-2: Second round\\.')).toBeInTheDocument();+ expect(screen.getByRole('treeitem', { name: /^com_ui_trace_step 2,/ })).toBeInTheDocument();await userEvent.click(screen.getByRole('button', { name: 'com_ui_trace_load_older' }));@@ -942,10 +941,10 @@ describe('Trace Viewer', () => {},] as unknown as TMessage[];- function renderSdkRun() {+ function renderSdkRun(listed: TTraceRecord[] = sdkRecords) {jest.spyOn(dataService, 'getConversationTraceRecords')- .mockResolvedValue({ records: sdkRecords, sourceId: 'tenant-project' });+ .mockResolvedValue({ records: listed, sourceId: 'tenant-project' });const client = new QueryClient({defaultOptions: { queries: { retry: false } },logger: { log: () => undefined, warn: () => undefined, error: () => undefined },@@ -988,6 +987,7 @@ describe('Trace Viewer', () => {const inspector = screen.getByTestId('trace-inspector');expect(within(inspector).getByText(/"query": "weather"/)).toBeInTheDocument();expect(within(inspector).getByText('Sunny.')).toBeInTheDocument();+ expect(within(inspector).getByText('com_ui_trace_from_conversation')).toBeInTheDocument();expect(within(inspector).getByText('tool-dispatch')).toBeInTheDocument();expect(dataService.getConversationTraceRecord).not.toHaveBeenCalled();});@@ -1044,6 +1044,21 @@ describe('Trace Viewer', () => {expect(within(inspector).queryByText('com_ui_trace_reply')).not.toBeInTheDocument();});+ it('says a round came from the conversation only when it did', async () => {+ const namedRound = sdkRecords.map((entry) =>+ entry.id === 'round-1' ? { ...entry, tools: ['bash_tool'] } : entry,+ );+ renderSdkRun(namedRound);++ /** The chat's round called web_search, so the trace's bash_tool round stays unmatched. */+ await userEvent.click(await recordRow('com_ui_tool_name_code'));++ const inspector = screen.getByTestId('trace-inspector');+ expect(within(inspector).getAllByText('com_ui_tool_name_code').length).toBeGreaterThan(0);+ expect(within(inspector).queryByText('com_ui_trace_from_conversation')).toBeNull();+ expect(within(inspector).queryByText('Sunny.')).toBeNull();+ });+it('shows the agent by name with its id to copy and a chat one click away', async () => {renderSdkRun();await recordRow('com_ui_model: Let me look that up\\.');diff --git a/client/src/components/Chat/Trace/__tests__/model.test.ts b/client/src/components/Chat/Trace/__tests__/model.test.tsindex 822c33159f..254d7353ec 100644--- a/client/src/components/Chat/Trace/__tests__/model.test.ts+++ b/client/src/components/Chat/Trace/__tests__/model.test.ts@@ -967,3 +967,265 @@ describe('roles', () => {expect(turn.agents).toEqual([{ agentId: 'agent_scout', recordId: 'scout' }]);});});++describe('a response cut by the record limit', () => {+ /** The newest records of a long run: its root, agent and graph started first, so they are the ones not loaded. */+ const round = (index: number): TTraceRecord[] => [+ record({+ id: `node-${index}`,+ parentId: 'unloaded-graph',+ kind: 'agent',+ role: 'plumbing',+ name: 'agent',+ startTime: at(index * 1000),+ }),+ record({+ id: `call-${index}`,+ parentId: `node-${index}`,+ role: 'plumbing',+ name: 'AgentModelCall',+ startTime: at(index * 1000 + 10),+ }),+ record({+ id: `llm-${index}`,+ parentId: `call-${index}`,+ kind: 'generation',+ role: 'model',+ name: 'llm',+ startTime: at(index * 1000 + 20),+ }),+ record({+ id: `round-${index}`,+ parentId: 'unloaded-graph',+ role: 'tools',+ name: 'tool-dispatch',+ startTime: at(index * 1000 + 500),+ }),+ ];++ it('keeps each tool round in the step of the model call that asked for it', () => {+ const model = buildTraceModel([...round(0), ...round(1), ...round(2)], 'simple');+ const [turn] = model.turns;++ expect(turn.steps).toBe(3);+ expect(turn.stepKeys.map((key) => model.steps.get(key)?.rootIds)).toEqual([+ ['llm-0', 'round-0'],+ ['llm-1', 'round-1'],+ ['llm-2', 'round-2'],+ ]);+ });+});++describe('a cut inside a model call’s own wrappers', () => {+ const wrapped = (index: number, withNode: boolean): TTraceRecord[] => [+ ...(withNode+ ? [+ record({+ id: `node-${index}`,+ parentId: 'unloaded-graph',+ kind: 'agent',+ role: 'plumbing',+ name: 'agent',+ startTime: at(index * 1000),+ }),+ ]+ : []),+ record({+ id: `call-${index}`,+ parentId: `node-${index}`,+ role: 'plumbing',+ name: 'AgentModelCall',+ startTime: at(index * 1000 + 10),+ }),+ record({+ id: `llm-${index}`,+ parentId: `call-${index}`,+ kind: 'generation',+ role: 'model',+ name: 'llm',+ startTime: at(index * 1000 + 20),+ }),+ record({+ id: `round-${index}`,+ parentId: 'unloaded-graph',+ role: 'tools',+ name: 'tool-dispatch',+ tools: ['bash_tool', 'read_file'],+ startTime: at(index * 1000 + 500),+ }),+ ];++ it('gives the round to the model call whose wrapper the cut removed', () => {+ const model = buildTraceModel([...wrapped(0, false), ...wrapped(1, true)], 'simple');+ const [turn] = model.turns;++ expect(turn.split).toBe(true);+ expect(turn.stepKeys.map((key) => model.steps.get(key)?.rootIds)).toEqual([+ ['llm-0', 'round-0'],+ ['llm-1', 'round-1'],+ ]);+ });++ it('counts a round’s tools from the names the trace recorded for it', () => {+ const model = buildTraceModel(wrapped(1, true), 'simple');+ const [turn] = model.turns;++ expect(turn.toolCalls).toBe(2);+ expect(model.summary.toolCalls).toBe(2);+ expect([...(model.steps.get(turn.stepKeys[0])?.toolNames ?? [])]).toEqual([+ ['bash_tool', 1],+ ['read_file', 1],+ ]);+ });++ it('does not guess which of two cut model calls asked for a round', () => {+ /** Two parallel agents, both cut inside their wrappers, both model calls before either round. */+ const lane = (name: string, start: number): TTraceRecord[] => [+ record({+ id: `call-${name}`,+ parentId: `node-${name}`,+ role: 'plumbing',+ startTime: at(start),+ }),+ record({+ id: `llm-${name}`,+ parentId: `call-${name}`,+ kind: 'generation',+ role: 'model',+ startTime: at(start + 10),+ }),+ record({+ id: `round-${name}`,+ parentId: `graph-${name}`,+ role: 'tools',+ tools: ['bash_tool'],+ startTime: at(start + 1000),+ }),+ ];+ const model = buildTraceModel([...lane('a', 0), ...lane('b', 100)], 'simple');+ const [turn] = model.turns;+ const steps = turn.stepKeys.map((key) => model.steps.get(key)?.rootIds);++ expect(steps).toEqual([['llm-a'], ['llm-b'], ['round-a'], ['round-b']]);+ expect(turn.toolCalls).toBe(2);+ });++ it('counts recorded tools once when the round that holds them is also named', () => {+ const model = buildTraceModel(+ [+ ...wrapped(1, true),+ record({+ id: 'bash',+ parentId: 'round-1',+ kind: 'tool',+ name: 'bash_tool',+ startTime: at(1600),+ }),+ record({+ id: 'read',+ parentId: 'round-1',+ kind: 'tool',+ name: 'read_file',+ startTime: at(1700),+ }),+ ],+ 'simple',+ );++ expect(model.turns[0].toolCalls).toBe(2);+ expect(model.summary.toolCalls).toBe(2);+ });++ it('does not call a whole response split', () => {+ expect(buildTraceModel(sdkRun, 'simple').turns[0].split).toBe(false);+ });+});++describe('every place a record limit can cut an SDK run', () => {+ /** The order the SDK's spans really start in: each wrapper before what it frames, the round last. */+ const rounds = 6;+ const run: TTraceRecord[] = [+ record({ id: 'root', kind: 'agent', role: 'run', name: 'AgentGraph', startTime: at(0) }),+ record({ id: 'saved', parentId: 'root', role: 'agent', agentId: 'agent_a', startTime: at(1) }),+ record({ id: 'graph', parentId: 'saved', kind: 'agent', role: 'run', startTime: at(2) }),+ ];+ for (let index = 0; index < rounds; index++) {+ const start = 100 + index * 100;+ run.push(+ record({+ id: `node-${index}`,+ parentId: 'graph',+ kind: 'agent',+ role: 'plumbing',+ startTime: at(start),+ }),+ record({+ id: `call-${index}`,+ parentId: `node-${index}`,+ role: 'plumbing',+ startTime: at(start + 1),+ }),+ record({+ id: `prompt-${index}`,+ parentId: `call-${index}`,+ role: 'plumbing',+ startTime: at(start + 2),+ }),+ record({+ id: `llm-${index}`,+ parentId: `call-${index}`,+ kind: 'generation',+ role: 'model',+ startTime: at(start + 3),+ }),+ );+ if (index < rounds - 1) {+ run.push(+ record({+ id: `label-${index}`,+ parentId: 'root',+ kind: 'generation',+ role: 'stepLabel',+ startTime: at(start + 40),+ }),+ record({+ id: `round-${index}`,+ parentId: 'graph',+ role: 'tools',+ startTime: at(start + 50),+ }),+ );+ }+ }+ const newestFirst = [...run].sort((a, b) => b.startTime.localeCompare(a.startTime));++ it.each(newestFirst.map((_, index) => index + 1))(+ 'keeps one step per model call with its own round when the newest %i records load',+ (keep) => {+ const loaded = newestFirst.slice(0, keep);+ const model = buildTraceModel(loaded, 'simple');+ const [turn] = model.turns;+ const steps = turn.stepKeys.map((key) => model.steps.get(key)?.rootIds ?? []);+ const roleOf = (id: string) => model.nodes.get(id)?.record.role;++ const stepOf = new Map(steps.flatMap((rootIds, index) => rootIds.map((id) => [id, index])));+ const loadedModelCalls = loaded.filter((entry) => entry.role === 'model').length;+ let orphans = 0;+ for (const entry of loaded) {+ if (roleOf(entry.id) !== 'tools') {+ continue;+ }+ const asker = `llm-${entry.id.split('-')[1]}`;+ if (model.nodes.has(asker)) {+ expect(stepOf.get(entry.id)).toBe(stepOf.get(asker));+ } else {+ orphans++;+ }+ }+ /** Only the oldest loaded round can have lost its model call to the cut, and it alone adds a step. */+ expect(orphans).toBeLessThanOrEqual(1);+ expect(turn.steps).toBe(loadedModelCalls + orphans);+ expect(turn.split).toBe(keep < run.length);+ },+ );+});diff --git a/client/src/components/Chat/Trace/__tests__/present.test.ts b/client/src/components/Chat/Trace/__tests__/present.test.tsindex 8c94ce43f7..68103238b3 100644--- a/client/src/components/Chat/Trace/__tests__/present.test.ts+++ b/client/src/components/Chat/Trace/__tests__/present.test.ts@@ -130,6 +130,156 @@ describe('buildActivityIndex', () => {});});+describe('a response the record limit split', () => {+ it('names the tool rounds and labels it still holds, counted from its end', () => {+ const loaded = records.filter(+ (entry) => !['run', 'scout', 'llm-1', 'label-1', 'paused', 'round-1'].includes(entry.id),+ );+ const model = buildTraceModel(loaded, 'simple');+ const previews = buildPreviews([response]);++ expect(buildActivityIndex(model, previews).calls.size).toBe(0);++ const activity = buildActivityIndex(model, previews, 'response-1');+ expect(activity.calls.get('round-2')?.map((call) => call.name)).toEqual(['read_file']);+ expect(activity.stepOffsets.get('response-1')).toBe(1);+ expect(activity.unrecordedCalls.get('response-1')).toBe(1);+ });++ it('pairs the labels it holds with the last labels the chat showed', () => {+ const labelled = {+ ...response,+ content: [+ { type: ContentTypes.ACTIVITY_LABEL, activity_label: 'An earlier label' },+ ...(response.content ?? []),+ ],+ } as TMessage;+ const model = buildTraceModel(+ records.filter((entry) => entry.id !== 'run' && entry.id !== 'scout'),+ 'simple',+ );++ expect(+ buildActivityIndex(buildTraceModel(records), buildPreviews([labelled])).labels.size,+ ).toBe(0);+ expect(+ buildActivityIndex(buildTraceModel(records), buildPreviews([labelled]), 'response-1').labels+ .size,+ ).toBe(0);+ expect(+ buildActivityIndex(model, buildPreviews([labelled]), 'response-1').labels.get('label-1'),+ ).toBe('Finding the trace reader');+ });+});++describe('a response with an orphaned record that the record limit did not cut', () => {+ it('pairs no labels when the chat showed more than the trace kept', () => {+ const labelled = {+ ...response,+ content: [+ { type: ContentTypes.ACTIVITY_LABEL, activity_label: 'An earlier label' },+ ...(response.content ?? []),+ ],+ } as TMessage;+ /** Its root never reached the backend, so records hang from nothing loaded, on any page. */+ const model = buildTraceModel(records.filter((entry) => entry.id !== 'run'));++ expect(model.turns[0].split).toBe(true);+ expect(buildActivityIndex(model, buildPreviews([labelled])).labels.size).toBe(0);+ expect(+ buildActivityIndex(model, buildPreviews([labelled]), 'another-response').labels.size,+ ).toBe(0);+ });+});++describe('rounds the trace names itself', () => {+ const named = (tools: Record<string, string[]>) =>+ records.map((entry) => (tools[entry.id] ? { ...entry, tools: tools[entry.id] } : entry));+ const sourcesFor = (model: ReturnType<typeof buildTraceModel>, messages: TMessage[]) => ({+ localize: (key: string) => key,+ activity: buildActivityIndex(model, buildPreviews(messages)),+ previewOf: () => undefined,+ agentOf: () => undefined,+ mcpServerNames: ['github'],+ });++ it('adds what the chat holds for a round when the names agree, a paused round included', () => {+ const model = buildTraceModel(+ named({+ paused: ['web_search', 'search_code_mcp_github'],+ 'round-1': ['web_search', 'search_code_mcp_github'],+ 'round-2': ['read_file'],+ }),+ );+ const activity = buildActivityIndex(model, buildPreviews([response]));++ expect(activity.calls.get('round-1')?.[0]).toMatchObject({ output: 'ten results' });+ expect(activity.unrecordedCalls.size).toBe(0);+ /** The paused round and the one that ran hold the same two calls, which ran once. */+ expect(model.turns[0].toolCalls).toBe(3);+ expect(model.summary.toolCalls).toBe(3);+ expect([...(model.steps.get(model.turns[0].stepKeys[0])?.toolNames ?? [])]).toEqual([+ ['web_search', 1],+ ['search_code_mcp_github', 1],+ ]);+ });++ it('shows the names the trace recorded, and nothing from the chat, when the two disagree', () => {+ const model = buildTraceModel(named({ 'round-1': ['web_search'], 'round-2': ['bash_tool'] }));+ const sources = sourcesFor(model, [response]);+ const node = model.nodes.get('round-2');++ expect(sources.activity.calls.size).toBe(0);+ expect(sources.activity.labels.get('label-1')).toBe('Finding the trace reader');+ expect(node && presentRecord(node, sources)).toEqual({+ title: 'com_ui_tool_name_code',+ technicalName: 'tool-dispatch',+ toolNames: ['bash_tool'],+ calls: [{ name: 'bash_tool', args: '', title: 'com_ui_tool_name_code' }],+ callsFrom: 'trace',+ });+ });++ it('reads two same-name calls in one round as two calls, not as a round that ran twice', () => {+ const twice = buildTraceModel(named({ 'round-2': ['read_file', 'read_file'] }));++ expect(buildActivityIndex(twice, buildPreviews([response])).calls.size).toBe(0);+ expect(twice.turns[0].toolCalls).toBe(2);+ });++ it('knows a call came from the conversation even when the chat holds nothing it sent or returned', () => {+ const pending = {+ ...response,+ content: [+ { type: ContentTypes.TEXT, text: 'Looking.' },+ { type: ContentTypes.TOOL_CALL, tool_call: { name: 'ask_user_question', args: '' } },+ ],+ } as unknown as TMessage;+ const model = buildTraceModel([+ generation('llm-1', 'model', 'llm', 100),+ round('round-1', 1500),+ ]);+ const node = model.nodes.get('round-1');+ const presentation = node && presentRecord(node, sourcesFor(model, [pending]));++ expect(presentation?.calls).toEqual([+ expect.objectContaining({ name: 'ask_user_question', input: undefined, output: undefined }),+ ]);+ expect(presentation?.callsFrom).toBe('conversation');+ });++ it('names a round with no chat message at all', () => {+ const model = buildTraceModel(named({ 'round-1': ['web_search', 'read_file'] }));+ const node = model.nodes.get('round-1');++ expect(node && presentRecord(node, sourcesFor(model, []))).toMatchObject({+ title: 'com_ui_trace_role_tools_count',+ preview: 'com_ui_tool_name_web_search, com_ui_tool_name_read_file',+ toolNames: ['web_search', 'read_file'],+ });+ });+});+describe('presentRecord', () => {it("reads a record in the chat's words and keeps the recorded name for the details", () => {const { of } = present([response]);diff --git a/client/src/components/Chat/Trace/__tests__/preview.test.ts b/client/src/components/Chat/Trace/__tests__/preview.test.tsindex d9a7355dcf..9760c4a7c8 100644--- a/client/src/components/Chat/Trace/__tests__/preview.test.ts+++ b/client/src/components/Chat/Trace/__tests__/preview.test.ts@@ -389,14 +389,64 @@ describe('buildPreviewIndex', () => {]);});- it('withholds previews for the turn a page boundary splits', () => {+ it('matches the turn a record limit splits from its end, where its loaded records are', () => {const one = buildTraceModel([record({ id: 'llm', kind: 'generation', startTime: at(0), endTime: at(100) }),]);const answer = buildPreviews([message({ text: 'Answer.' })]);-expect(buildPreviewIndex(one, answer).get('llm')).toBe('Answer.');- expect(buildPreviewIndex(one, answer, 'response-1').get('llm')).toBeUndefined();+ expect(buildPreviewIndex(one, answer, 'response-1').get('llm')).toBe('Answer.');++ /** Only the last round's records are loaded: the model call that wrote the final text,+ * hanging from a wrapper the limit cut off. */+ const tail = buildTraceModel([+ record({+ id: 'llm-2',+ parentId: 'not-loaded',+ kind: 'generation',+ startTime: at(3000),+ endTime: at(4000),+ }),+ ]);+ expect(buildPreviewIndex(tail, previews).get('llm-2')).toBeUndefined();+ expect(buildPreviewIndex(tail, previews, 'response-1').get('llm-2')).toBe(+ 'Paris is sunny, Lyon is not.',+ );++ /** The oldest loaded response is often whole, the next page holding an older response. One+ * that then disagrees with its message is unmatched, not read as a tail of it. */+ const whole = buildTraceModel([+ record({ id: 'llm-2', kind: 'generation', startTime: at(3000), endTime: at(4000) }),+ ]);+ expect(buildPreviewIndex(whole, previews, 'response-1').get('llm-2')).toBeUndefined();++ /** More steps than the message has rounds cannot be a tail of it. */+ expect(+ buildPreviewIndex(model, buildPreviews([message({ content: [] })]), 'response-1').size,+ ).toBe(0);+ });++ it('gives no tool a preview in the first loaded step of a split response, whose round may be cut', () => {+ const cut = (id: string, kind: TTraceRecord['kind'], name: string, start: number) =>+ record({+ id,+ parentId: 'not-loaded',+ kind,+ name,+ startTime: at(start),+ endTime: at(start + 50),+ });+ /** The limit fell inside the first round: its model call and its first search are not loaded. */+ const split = buildTraceModel([+ cut('search-lyon', 'tool', 'web_search', 1600),+ cut('read', 'tool', 'read_file', 2100),+ cut('llm-2', 'generation', 'llm', 3000),+ ]);+ const index = buildPreviewIndex(split, previews, 'response-1');++ expect(index.get('search-lyon')).toBeUndefined();+ expect(index.get('read')).toBeUndefined();+ expect(index.get('llm-2')).toBe('Paris is sunny, Lyon is not.');});it('keeps text and tool previews for a single attributed lane', () => {diff --git a/client/src/components/Chat/Trace/model.ts b/client/src/components/Chat/Trace/model.tsindex 568725a836..9e8b88fe3d 100644--- a/client/src/components/Chat/Trace/model.ts+++ b/client/src/components/Chat/Trace/model.ts@@ -40,6 +40,12 @@ export type TraceStep = {index: number;origin: 'run' | 'title';generationId: string | null;+ /**+ * The tool round that ran the step's calls. A model call asks for one round, so a step holding+ * several is one an approval paused: the round is recorded again when it resumes, with the same+ * calls, and the last record is the one that ran them.+ */+ roundId: string | null;agentId?: string;rootIds: string[];start: number;@@ -67,6 +73,12 @@ export type TraceTurn = {/** Model calls that wrote an activity label; they are spend, not work of the response. */labels: number;toolCalls: number;+ /**+ * Some of the response's records hang from a parent that is not loaded. Records load newest+ * first and a run's root starts first, so this is what a record limit leaves of a response it+ * cut: its end.+ */+ split: boolean;/** Saved agents that ran in the response, each with the record that stands for it. */agents: Array<{ agentId: string; recordId: string }>;sequence: TraceSpan;@@ -374,7 +386,9 @@ function groupSteps(nodes: Map<string, TraceNode>,steps: Map<string, TraceStep>,rootIds: readonly string[],-): void {+ privateWrappers: ReadonlySet<string>,+): number {+ let namedCalls = 0;const compare = byStart(nodes);const rootsByOrigin = new Map<TraceStep['origin'], string[]>();for (const id of rootIds) {@@ -384,6 +398,17 @@ function groupSteps(rootsByOrigin.set(origin, roots);}+ const unloadedParentOf = (id: string): string | undefined => {+ const parentId = nodes.get(id)?.record.parentId;+ return parentId != null && !nodes.has(parentId) ? parentId : undefined;+ };+ /**+ * A record limit cuts a long response's earliest records, its root and graph among them, so a+ * walk can end at a wrapper that only frames one model call. That wrapper is no lane of its+ * own: the lane is the unloaded parent it shares with the tool round the model call asked for.+ */+ const laneAbove = (id: string): string | undefined =>+ nodes.get(id)?.record.role === 'plumbing' ? unloadedParentOf(id) : undefined;/** A wrapper's branch immediately below its structural root, cached for nested failure rows. */const branches = new Map<string, string>();const branchOf = (id: string): string => {@@ -398,8 +423,15 @@ function groupSteps(}path.push(current);const parent = nodes.get(current)?.parentId;- if (parent == null || nodes.get(parent)?.parentId == null) {- branch = current;+ if (parent == null) {+ branch = laneAbove(current) ?? current;+ break;+ }+ if (nodes.get(parent)?.parentId == null) {+ /** A wrapper framing one model call is never a lane, so when the cut left the graph as+ * the topmost loaded record, the lane is that graph, where its tool rounds hang too. */+ const framing = nodes.get(current)?.record.role === 'plumbing';+ branch = laneAbove(parent) ?? (framing ? parent : current);break;}current = parent;@@ -415,33 +447,50 @@ function groupSteps(if (node?.parentId != null) {return branchOf(node.parentId);}- const unloaded = node?.record.parentId;- return unloaded != null && !nodes.has(unloaded) ? unloaded : '';+ return unloadedParentOf(id) ?? '';};for (const [origin, roots] of rootsByOrigin) {roots.sort(compare);const groups: Array<{ rootIds: string[]; lane: string }> = [];const latestByLane = new Map<string, { rootIds: string[]; lane: string }>();+ /** Model calls whose lane is a private wrapper, until the round each asked for arrives. */+ const waiting = new Set<{ rootIds: string[]; lane: string }>();let leading: string[] = [];for (const id of roots) {const record = nodes.get(id)?.record;const lane = laneOf(id);const current = groups[groups.length - 1];+ /** The cut can fall inside a model call's own wrappers. Its lane is then one of those+ * wrappers, which names no lane at all, so the round it asked for, arriving in a lane no+ * model call holds, is its round rather than a step of its own. That is only known when+ * one such model call is still waiting for its round: with two (parallel agents cut at+ * the same place) nothing says which asked, so the round leads a step of its own. */+ const asked =+ record != null && isToolWork(record) && !latestByLane.has(lane) && waiting.size === 1+ ? waiting.values().next().value+ : undefined;/** A tool whose lane has no model call loaded yet (an older page holds it) leads its own step.* A label's model call describes a step; it never starts one. */if (record != null &&- (isModelCall(record) || (isToolWork(record) && !latestByLane.has(lane)))+ (isModelCall(record) || (isToolWork(record) && !latestByLane.has(lane) && asked == null))) {const group = { rootIds: [...leading, id], lane };groups.push(group);latestByLane.set(lane, group);leading = [];+ if (isModelCall(record) && privateWrappers.has(lane)) {+ waiting.add(group);+ }} else if (current == null) {leading.push(id);} else {- (latestByLane.get(lane) ?? current).rootIds.push(id);+ (latestByLane.get(lane) ?? asked ?? current).rootIds.push(id);+ if (asked != null) {+ latestByLane.set(lane, asked);+ waiting.delete(asked);+ }}}if (leading.length > 0) {@@ -449,6 +498,12 @@ function groupSteps(}groups.forEach(({ rootIds }, index) => {const generationId = rootIds.find(isGenerationId(nodes)) ?? null;+ let roundId: string | null = null;+ for (const id of rootIds) {+ if (nodes.get(id)?.record.role === 'tools') {+ roundId = id;+ }+ }const key = stepKey(turn.messageId, origin, generationId ?? rootIds[0]);const step: TraceStep = {key,@@ -456,6 +511,7 @@ function groupSteps(index: index + 1,origin,generationId,+ roundId,agentId: nodes.get(generationId ?? rootIds[0])?.agentId,rootIds,start: Number.POSITIVE_INFINITY,@@ -479,9 +535,16 @@ function groupSteps(if (node.record.status === 'error') {step.errorCount++;}- if (node.record.kind === 'tool') {+ /** Names stand in for tools that were never recorded, so only for the round that ran, and+ * only when it holds no recorded tool of its own to count instead. */+ const named =+ node.record.id === roundId && !node.childIds.some(isToolWorkId(nodes))+ ? (node.record.tools ?? [])+ : [];+ namedCalls += named.length;+ for (const name of node.record.kind === 'tool' ? [node.record.name] : named) {step.toolCalls++;- step.toolNames.set(node.record.name, (step.toolNames.get(node.record.name) ?? 0) + 1);+ step.toolNames.set(name, (step.toolNames.get(name) ?? 0) + 1);}for (let i = node.viewChildIds.length - 1; i >= 0; i--) {stack.push(node.viewChildIds[i]);@@ -503,8 +566,14 @@ function groupSteps((left?.origin === 'title' ? 1 : 0) - (right?.origin === 'title' ? 1 : 0));});+ return namedCalls;}+const isToolWorkId = (nodes: Map<string, TraceNode>) => (id: string) => {+ const record = nodes.get(id)?.record;+ return record != null && isToolWork(record);+};+const isGenerationId = (nodes: Map<string, TraceNode>) => (id: string) => {const record = nodes.get(id)?.record;return record != null && isModelCall(record);@@ -614,6 +683,7 @@ export function buildTraceModel(generations: 0,labels: 0,toolCalls: 0,+ split: false,agents: [],sequence: EMPTY_SPAN,};@@ -665,6 +735,32 @@ export function buildTraceModel(const compare = byStart(nodes);const turns = [...turnsByMessage.values()].sort((a, b) => a.start - b.start);+ /**+ * Parents a record limit cut off, and which of them frame a single model call. The SDK wraps+ * each model call in wrappers of its own, so an unloaded parent whose loaded children are only+ * such wrappers and a model call is one of those, wherever in the chain the cut fell. A graph+ * is told apart by what else hangs from it: the tool rounds.+ */+ const shared = new Set<string>();+ const privateWrappers = new Set<string>();+ for (const node of nodes.values()) {+ const { parentId, role, origin, messageId } = node.record;+ if (parentId == null || nodes.has(parentId)) {+ continue;+ }+ if (role === 'plumbing' || role === 'model') {+ privateWrappers.add(parentId);+ } else {+ shared.add(parentId);+ }+ const turn = origin == null ? turnsByMessage.get(messageId) : undefined;+ if (turn != null) {+ turn.split = true;+ }+ }+ for (const id of shared) {+ privateWrappers.delete(id);+ }let sequence = 0;for (const turn of turns) {turn.rootIds.sort(compare);@@ -680,7 +776,15 @@ export function buildTraceModel(stack.push(...node.childIds.map((childId) => ({ id: childId, depth: entry.depth + 1 })));}}- groupSteps(turn, nodes, steps, rootsByTurn.get(turn.messageId) ?? []);+ const namedCalls = groupSteps(+ turn,+ nodes,+ steps,+ rootsByTurn.get(turn.messageId) ?? [],+ privateWrappers,+ );+ turn.toolCalls += namedCalls;+ summary.toolCalls += namedCalls;const turnSequenceStart = sequence;if (mode === 'simple') {for (const key of turn.stepKeys) {diff --git a/client/src/components/Chat/Trace/present.ts b/client/src/components/Chat/Trace/present.tsindex 2849c7bdb3..f1808b521a 100644--- a/client/src/components/Chat/Trace/present.ts+++ b/client/src/components/Chat/Trace/present.ts@@ -20,6 +20,8 @@ export type RecordPresentation = {/** The tools a row stands for, for their icons: a recorded tool, or an unrecorded round's calls. */toolNames?: string[];calls?: ToolCallView[];+ /** Where `calls` came from: the chat's own message, or only the names the trace recorded. */+ callsFrom?: 'conversation' | 'trace';};/** A call of an unrecorded tool round, named the way its chat tool card names it. */@@ -58,16 +60,27 @@ export function presentTool(function presentToolRound(record: TTraceRecord, sources: PresentationSources): RecordPresentation {const { localize, activity } = sources;- const calls = activity.calls.get(record.id);+ /** The trace's own names say what ran; the chat's message, when it matches, adds what was sent and returned. */+ const matched = activity.calls.get(record.id);+ const calls = matched ?? record.tools?.map((name) => ({ name, args: '' })) ?? [];+ const callsFrom = matched != null ? ('conversation' as const) : ('trace' as const);const technicalName = record.name;- if (calls == null || calls.length === 0) {+ if (calls.length === 0) {return { title: localize('com_ui_trace_role_tools'), technicalName };}const views = calls.map((call) => ({ ...call, ...presentTool(call.name, sources) }));const toolNames = calls.map((call) => call.name);if (views.length === 1) {const [{ title, caption, args }] = views;- return { title, caption, preview: args, technicalName, toolNames, calls: views };+ return {+ title,+ caption,+ preview: args || undefined,+ technicalName,+ toolNames,+ calls: views,+ callsFrom,+ };}const titles = [...new Set(views.map((view) => view.title))];return {@@ -76,6 +89,7 @@ function presentToolRound(record: TTraceRecord, sources: PresentationSources): RtechnicalName,toolNames,calls: views,+ callsFrom,};}diff --git a/client/src/components/Chat/Trace/preview.ts b/client/src/components/Chat/Trace/preview.tsindex d67612f7e3..f2165c9828 100644--- a/client/src/components/Chat/Trace/preview.ts+++ b/client/src/components/Chat/Trace/preview.ts@@ -220,23 +220,95 @@ export function buildStepPreviews(message: TMessage | undefined): StepPreview[]* tool's nested calls). Tool records are matched to the message's tool calls by* name, in the order they ran within their step; same-name calls that started in* the same millisecond have no reliable order and get none. The turn a page- * boundary splits (`partialMessageId`) gets none until its earlier steps load.+ * boundary splits (`partialMessageId`) is matched from its end (`alignTurns`).*/+/** How a response's steps line up with its message's rounds: `offset` rounds ran before its first loaded step. */+export type TurnAlignment = { message: MessagePreview; offset: number; split: boolean };++/**+ * Lines each response's steps up with its message's rounds, or leaves the response out when the+ * two cannot be trusted to match. There is no call id shared by a trace and a message, so the+ * match is by order, and an order is only evidence when something else agrees with it:+ *+ * - A whole response must match round for round. Filtering, incomplete traces and silent calls+ * can remove rounds on either side, and an unequal count cannot be aligned by ordinal.+ * - The response a record limit split is matched from its end. Records load newest first, so what+ * is loaded is the end of the response and its steps are the message's last rounds. That holds+ * only for a response the limit really cut (`turn.split`): the oldest loaded response is often+ * whole, with the next page holding an older response, and a whole response that disagrees with+ * its message is simply unmatched.+ * - Wherever the trace names the tools of a round, the message's round must name the same tools.+ * One disagreement means the order is off somewhere, so the whole response goes unmatched rather+ * than showing one round's arguments and output under another's name.+ */+export function alignTurns(+ model: TraceModel,+ previewsByMessage: ReadonlyMap<string, MessagePreview>,+ partialMessageId?: string,+): Map<string, TurnAlignment> {+ const alignments = new Map<string, TurnAlignment>();+ for (const turn of model.turns) {+ const message = previewsByMessage.get(turn.messageId);+ if (message == null || message.parallel || message.finalOnly) {+ continue;+ }+ const split = turn.split && turn.messageId === partialMessageId;+ const missing = message.steps.length - turn.steps;+ if (split ? missing < 0 : missing !== 0) {+ continue;+ }+ alignments.set(turn.messageId, { message, offset: missing, split });+ }+ for (const step of model.steps.values()) {+ const alignment = step.origin === 'run' ? alignments.get(step.messageId) : undefined;+ if (alignment == null) {+ continue;+ }+ const round = alignment.message.steps[alignment.offset + step.index - 1];+ if (!namesAgree(model, step.rootIds, round?.toolCalls ?? [])) {+ alignments.delete(step.messageId);+ }+ }+ return alignments;+}++/**+ * Whether every round the trace names in a step names exactly the message round's calls. A round+ * an approval paused is recorded again when it resumes, so a step may hold several records, and+ * each holds the same calls; two same-name calls in one record are two calls, never a repeat.+ */+function namesAgree(+ model: TraceModel,+ rootIds: readonly string[],+ calls: readonly ToolCallPreview[],+): boolean {+ for (const id of rootIds) {+ const tools = model.nodes.get(id)?.record.tools;+ if (tools == null) {+ continue;+ }+ if (tools.length !== calls.length || tools.some((name, at) => name !== calls[at].name)) {+ return false;+ }+ }+ return true;+}+export function buildPreviewIndex(model: TraceModel,previewsByMessage: ReadonlyMap<string, MessagePreview>,partialMessageId?: string,+ alignments: ReadonlyMap<string, TurnAlignment> = alignTurns(+ model,+ previewsByMessage,+ partialMessageId,+ ),): Map<string, string> {const index = new Map<string, string>();const stepsByTurn = new Map(model.turns.map((turn) => [turn.messageId, turn.steps]));for (const step of model.steps.values()) {const message = previewsByMessage.get(step.messageId);- if (- message == null ||- message.parallel ||- step.origin === 'title' ||- step.messageId === partialMessageId- ) {+ if (message == null || message.parallel || step.origin === 'title') {continue;}if (message.finalOnly) {@@ -246,15 +318,15 @@ export function buildPreviewIndex(}continue;}- /** Filtering, incomplete traces and silent calls can remove rounds on either side.- * Without a shared call id, an unequal count cannot be aligned by ordinal. */- if (message.steps.length !== stepsByTurn.get(step.messageId)) {- continue;- }- const round = message.steps[step.index - 1];- if (!round) {+ const alignment = alignments.get(step.messageId);+ const round = alignment?.message.steps[alignment.offset + step.index - 1];+ if (alignment == null || !round) {continue;}+ /** The cut is by record, not by round, so the first loaded step of a split response may hold+ * only the last of its round's tools, and counting those from the round's first call would+ * show one call's arguments under another. */+ const boundary = alignment.split && step.index === 1;const callsByName = new Map<string, string[]>();for (const call of round.toolCalls) {const bucket = callsByName.get(call.name);@@ -286,7 +358,7 @@ export function buildPreviewIndex(}continue;}- if (record.kind !== 'tool') {+ if (record.kind !== 'tool' || boundary) {continue;}const ordinal = ordinals.get(record.name) ?? 0;@@ -323,6 +395,8 @@ export type ActivityIndex = {labels: Map<string, string>;/** Tool calls the trace holds no record of, by response: what a turn's own count misses. */unrecordedCalls: Map<string, number>;+ /** Steps of a response that ran before its first loaded one, so its steps keep their real numbers. */+ stepOffsets: Map<string, number>;};const hasToolRecord = (model: TraceModel) => (id: string) => {@@ -341,44 +415,40 @@ export function buildActivityIndex(model: TraceModel,previewsByMessage: ReadonlyMap<string, MessagePreview>,partialMessageId?: string,+ alignments: ReadonlyMap<string, TurnAlignment> = alignTurns(+ model,+ previewsByMessage,+ partialMessageId,+ ),): ActivityIndex {const calls: ActivityIndex['calls'] = new Map();const labels: ActivityIndex['labels'] = new Map();const unrecordedCalls: ActivityIndex['unrecordedCalls'] = new Map();- const stepsByTurn = new Map(model.turns.map((turn) => [turn.messageId, turn.steps]));- const aligned = (messageId: string): MessagePreview | undefined => {- const message = previewsByMessage.get(messageId);- return message == null || message.parallel || messageId === partialMessageId- ? undefined- : message;- };+ const stepOffsets: ActivityIndex['stepOffsets'] = new Map();for (const step of model.steps.values()) {- const message = aligned(step.messageId);- if (- message == null ||- message.finalOnly ||- step.origin === 'title' ||- message.steps.length !== stepsByTurn.get(step.messageId)- ) {+ const alignment = step.origin === 'run' ? alignments.get(step.messageId) : undefined;+ if (alignment == null) {continue;}- const round = message.steps[step.index - 1];- let target: string | undefined;- for (const id of step.rootIds) {- const node = model.nodes.get(id);- if (node?.record.role === 'tools' && !node.childIds.some(hasToolRecord(model))) {- target = id;- }+ if (alignment.offset > 0) {+ stepOffsets.set(step.messageId, alignment.offset);}+ const round = alignment.message.steps[alignment.offset + step.index - 1];+ /** A round that holds recorded tools is described by them, not by the message. */+ const ran = step.roundId != null ? model.nodes.get(step.roundId) : undefined;+ const target = ran != null && !ran.childIds.some(hasToolRecord(model)) ? step.roundId : null;if (target == null || round == null || round.toolCalls.length === 0) {continue;}calls.set(target, round.toolCalls);- unrecordedCalls.set(- step.messageId,- (unrecordedCalls.get(step.messageId) ?? 0) + round.toolCalls.length,- );+ /** A round the trace names is already counted from its names. */+ if (model.nodes.get(target)?.record.tools == null) {+ unrecordedCalls.set(+ step.messageId,+ (unrecordedCalls.get(step.messageId) ?? 0) + round.toolCalls.length,+ );+ }}const labelRecords = new Map<string, Record<LabelRole, Array<{ id: string; start: number }>>>();@@ -392,19 +462,24 @@ export function buildActivityIndex(labelRecords.set(messageId, byRole);}for (const [messageId, byRole] of labelRecords) {- const message = aligned(messageId);- if (message == null) {+ const message = previewsByMessage.get(messageId);+ if (message == null || message.parallel) {continue;}+ /** One notion of a cut response, the alignment's: its matched rounds are what vouch for reading+ * the labels from the end. A response that merely lost a record is whole, and pairs only when+ * the counts agree. */+ const split = alignments.get(messageId)?.split === true;for (const role of ['stepLabel', 'phaseLabel'] as const) {const records = byRole[role];const texts = message.labels[role];- if (records.length !== texts.length) {+ const missing = texts.length - records.length;+ if (split ? missing < 0 : missing !== 0) {continue;}records.sort((a, b) => a.start - b.start || a.id.localeCompare(b.id));- records.forEach((record, index) => labels.set(record.id, texts[index]));+ records.forEach((record, index) => labels.set(record.id, texts[missing + index]));}}- return { calls, labels, unrecordedCalls };+ return { calls, labels, unrecordedCalls, stepOffsets };}diff --git a/librechat.example.yaml b/librechat.example.yamlindex 3a7ca6470e..de0793c8e7 100644--- a/librechat.example.yaml+++ b/librechat.example.yaml@@ -259,6 +259,12 @@ interface:# # carries system prompts, agent instructions and tool definitions, which a# # user chatting with a shared agent cannot otherwise see.# showInputOutput: false+ # # Name the tools of each tool round from the round's own record. This adds+ # # requests to Langfuse per listed page, and Langfuse returns each round's full+ # # input and output to serve them, though only the tool names are kept and sent+ # # on; arguments and results stay behind showInputOutput. When off, a round is+ # # named only where the conversation's messages can be matched to the trace.+ # showToolNames: false# # Observations read per request (1-10000); older records load on demand.# maxRecords: 1000# # Characters kept from each input, output and metadata value (1-1000000).diff --git a/packages/api/src/langfuse/reader.spec.ts b/packages/api/src/langfuse/reader.spec.tsindex 1236aa7eca..66a7d55fba 100644--- a/packages/api/src/langfuse/reader.spec.ts+++ b/packages/api/src/langfuse/reader.spec.ts@@ -1089,6 +1089,176 @@ describe('createLangfuseTraceReader', () => {]);});+ describe('tool round names', () => {+ const round = (id: string, startTime: string) =>+ observation({+ id,+ parentObservationId: 'obs-root',+ type: 'CHAIN',+ name: 'tool-dispatch',+ startTime,+ });+ const listed = () =>+ jsonResponse({+ data: [+ observation(),+ round('round-1', '2026-09-12T11:30:01.000Z'),+ round('round-2', '2026-09-12T11:30:03.000Z'),+ ],+ });+ const naming = () =>+ createQuery({ settings: resolveTraceViewerConfig({ enabled: true, showToolNames: true }) });+ const toolsOf = (records: Array<{ id: string; tools?: string[] }>) =>+ Object.fromEntries(records.map((record) => [record.id, record.tools]));++ it("names each listed round from the round's own input, in one read scoped to those rounds", async () => {+ const { reader, fetchMock } = setup({+ responses: [+ listed(),+ jsonResponse({+ data: [+ { id: 'round-1', input: '[{"name":"web_search","args":{"query":"secret"}}]' },+ { id: 'round-2', input: [{ name: 'bash_tool' }, { name: 'read_file' }] },+ { id: 'round-elsewhere', input: '[{"name":"not_listed"}]' },+ { id: 'obs-root', input: '[{"name":"not_a_round"}]' },+ { input: 'malformed' },+ ],+ }),+ ],+ });++ const { records } = await reader.listRecords(naming());++ expect(toolsOf(records)).toEqual({+ 'obs-root': undefined,+ 'round-1': ['web_search'],+ 'round-2': ['bash_tool', 'read_file'],+ });+ expect(JSON.stringify(records)).not.toContain('secret');+ expect(fetchMock).toHaveBeenCalledTimes(2);+ expect(requestedUrl(fetchMock, 1).searchParams.get('fields')).toBe('core,io');+ expect(requestedTraceIds(fetchMock, 1)).toEqual(requestedTraceIds(fetchMock, 0));+ expect(requestedFilter(fetchMock, 1)).toEqual(+ expect.arrayContaining([+ { type: 'string', column: 'sessionId', operator: '=', value: 'convo-1' },+ expect.objectContaining({ column: 'userId' }),+ { type: 'string', column: 'name', operator: '=', value: 'tool-dispatch' },+ {+ type: 'datetime',+ column: 'startTime',+ operator: '>=',+ value: '2026-09-12T11:30:01.000Z',+ },+ {+ type: 'datetime',+ column: 'startTime',+ operator: '<=',+ value: '2026-09-12T11:30:03.000Z',+ },+ ]),+ );+ });++ it('leaves the rounds unnamed, and the page intact, when the names cannot be read', async () => {+ const { reader } = setup({ responses: [listed(), new Error('socket hang up')] });++ const { records } = await reader.listRecords(naming());++ expect(records.map((record) => record.id)).toEqual(['obs-root', 'round-1', 'round-2']);+ expect(toolsOf(records)).toEqual({});+ });++ it('leaves a round unnamed when its input is not the list of calls it ran', async () => {+ const { reader } = setup({+ responses: [+ listed(),+ jsonResponse({+ data: [{ id: 'round-1', input: '{"messages":[{"role":"system","content":"x"}]}' }],+ }),+ ],+ });++ const { records } = await reader.listRecords(naming());++ expect(toolsOf(records)).toEqual({});+ });++ it('reads no names unless the deployment asked for them, or when no round is listed', async () => {+ const unset = setup({ responses: [listed()] });+ await unset.reader.listRecords(createQuery());+ expect(unset.fetchMock).toHaveBeenCalledTimes(1);++ const none = setup({ responses: [jsonResponse({ data: [observation()] })] });+ await none.reader.listRecords(naming());+ expect(none.fetchMock).toHaveBeenCalledTimes(1);+ });++ it('reads the rounds a few at a time, following the cursor until every listed round is seen', async () => {+ const { reader, fetchMock } = setup({+ responses: [+ listed(),+ jsonResponse({+ data: [{ id: 'round-2', input: '[{"name":"bash_tool"}]' }],+ meta: { cursor: 'more-rounds' },+ }),+ jsonResponse({ data: [{ id: 'round-1', input: '[{"name":"web_search"}]' }] }),+ ],+ });++ const { records } = await reader.listRecords(naming());++ expect(toolsOf(records)).toMatchObject({+ 'round-1': ['web_search'],+ 'round-2': ['bash_tool'],+ });+ expect(fetchMock).toHaveBeenCalledTimes(3);+ expect(requestedUrl(fetchMock, 1).searchParams.get('limit')).toBe('50');+ expect(requestedUrl(fetchMock, 2).searchParams.get('cursor')).toBe('more-rounds');+ });++ it('stops once every listed round is seen, whatever the cursor offers', async () => {+ const { reader, fetchMock } = setup({+ responses: [+ listed(),+ jsonResponse({+ data: [+ { id: 'round-1', input: '[{"name":"web_search"}]' },+ { id: 'round-2', input: '{"messages":[]}' },+ ],+ meta: { cursor: 'more-rounds' },+ }),+ ],+ });++ await reader.listRecords(naming());++ expect(fetchMock).toHaveBeenCalledTimes(2);+ });++ it('stops at its byte budget, keeping the names it has and the page it was adding to', async () => {+ const huge = 'x'.repeat(9 * 1024 * 1024);+ const { reader, fetchMock } = setup({+ responses: [+ listed(),+ jsonResponse({+ data: [{ id: 'round-2', input: '[{"name":"bash_tool"}]' }],+ meta: { cursor: 'more-rounds' },+ }),+ jsonResponse({+ data: [{ id: 'round-1', input: '[{"name":"web_search"}]', output: huge }],+ }),+ jsonResponse({ data: [] }),+ ],+ });++ const { records } = await reader.listRecords(naming());++ expect(records.map((record) => record.id)).toEqual(['obs-root', 'round-1', 'round-2']);+ expect(toolsOf(records)).toEqual({ 'round-2': ['bash_tool'] });+ expect(fetchMock).toHaveBeenCalledTimes(3);+ });+ });+it('follows Langfuse cursors up to maxRecords and returns the next cursor', async () => {const { reader, fetchMock } = setup({responses: [diff --git a/packages/api/src/langfuse/reader.ts b/packages/api/src/langfuse/reader.tsindex fac7bd4796..64a59d102b 100644--- a/packages/api/src/langfuse/reader.ts+++ b/packages/api/src/langfuse/reader.ts@@ -15,6 +15,7 @@ import type {} from '@librechat/data-schemas';import type { LangfuseScoreDestination } from './destinations';import type { TraceQuery, TraceReader } from '~/traces/types';+import { TOOL_ROUND_NAME, resolveTraceRole } from './roles';import { exportsInternalTraceUserId } from './identity';import { toTracePrompt, toTraceReply } from './prompt';import { getScoreDestinations } from './destinations';@@ -22,7 +23,7 @@ import { TraceReadError } from '~/traces/types';import { mergeHeaders } from '~/utils/headers';import { redirectPolicyFor } from './utils';import { traceIdForMessage } from './trace';-import { resolveTraceRole } from './roles';+import { toolRoundNames } from './rounds';const OBSERVATIONS_PATH = '/api/public/v2/observations';const MAX_PAGE_SIZE = 1000;@@ -35,6 +36,16 @@ const NAME_MAX_LENGTH = 200;const STATUS_MESSAGE_MAX_LENGTH = 1000;const LIST_FIELDS = 'core,basic,time,model,usage';const DETAIL_FIELDS = `${LIST_FIELDS},io,metadata`;+const ROUND_FIELDS = 'core,io';+/**+ * Bounds on naming tool rounds. Langfuse cannot return a round's input without its output, and+ * a round the SDK found no calls for keeps the whole graph state as its input, so the rounds are+ * read a few at a time and the read stops at a byte budget: the newest rounds are named and the+ * rest are left to the chat's messages. These are safety caps on a best-effort addition, as+ * `MAX_PAGE_SIZE` is, not limits an operator tunes; `showToolNames` is the lever.+ */+const ROUND_PAGE_SIZE = 50;+const ROUND_BYTES_BUDGET = 8 * 1024 * 1024;const DESTINATION_PREFERENCE: Record<LangfuseScoreDestination['name'], number> = {connection: 0,tenant: 1,@@ -68,6 +79,8 @@ const pageSchema = z.object({meta: z.object({ cursor: z.string().nullish() }).partial().nullish(),});+const roundSchema = z.object({ id: z.string().min(1), input: z.unknown() });+type LangfuseObservation = z.infer<typeof observationSchema>;/** The response that owns a trace, and whether the trace is its title run rather than the run itself. */type TraceOwner = { messageId: string; origin?: 'title' };@@ -121,6 +134,35 @@ async function release(response: Response): Promise<void> {await response.body?.cancel().catch(() => undefined);}+type ByteBudget = { remaining: number };++/**+ * Parses a JSON body while holding no more of it than the budget has left. `Response.json()`+ * buffers whatever the backend sends, which for a read that returns content is not ours to bound+ * any other way.+ */+async function readBounded(response: Response, budget: ByteBudget): Promise<unknown> {+ const reader = response.body?.getReader();+ if (reader == null) {+ return undefined;+ }+ const decoder = new TextDecoder();+ let text = '';+ for (;;) {+ const { done, value } = await reader.read();+ if (done) {+ break;+ }+ budget.remaining -= value.byteLength;+ if (budget.remaining < 0) {+ await reader.cancel().catch(() => undefined);+ throw new TraceReadError('upstream_error', 'Langfuse returned more than the read allows');+ }+ text += decoder.decode(value, { stream: true });+ }+ return JSON.parse(text + decoder.decode());+}+function clamp(value: string, maxLength: number): string {return value.length > maxLength ? value.slice(0, maxLength) : value;}@@ -489,6 +531,8 @@ export function createLangfuseTraceReader({params: URLSearchParams,query: TraceQuery,hasCursor: boolean,+ /** Spends the body's bytes from this budget, refusing the rest of a body that outruns it. */+ budget?: ByteBudget,): Promise<z.infer<typeof pageSchema>> {const url = `${destination.baseUrl.replace(/\/+$/, '')}${OBSERVATIONS_PATH}?${params.toString()}`;const timeout = AbortSignal.timeout(query.settings.requestTimeoutMs);@@ -524,8 +568,11 @@ export function createLangfuseTraceReader({}let body: unknown;try {- body = await response.json();+ body = budget == null ? await response.json() : await readBounded(response, budget);} catch (error) {+ if (error instanceof TraceReadError) {+ throw error;+ }throw failed(error,new TraceReadError('upstream_error', 'Langfuse returned an invalid response'),@@ -880,6 +927,82 @@ export function createLangfuseTraceReader({}/** Reads a segment from its project until its records or this request's record budget run out. */+ /**+ * Names the tools of the listed tool rounds from the rounds' own input, in one read scoped to+ * those rounds. A list read carries no input, and asking for it on every record would return+ * each model call's whole conversation. The names are an addition to a page already read, so+ * a failure here leaves the rounds unnamed instead of failing the page.+ */+ async function nameToolRounds(+ destination: LangfuseScoreDestination,+ traceIds: string[],+ records: TTraceRecord[],+ ): Promise<void> {+ if (!query.settings.showToolNames) {+ return;+ }+ const rounds = new Map<string, TTraceRecord>();+ let from: string | undefined;+ let to: string | undefined;+ for (const record of records) {+ if (record.role !== 'tools') {+ continue;+ }+ rounds.set(record.id, record);+ from = from == null || record.startTime < from ? record.startTime : from;+ to = to == null || record.startTime > to ? record.startTime : to;+ }+ if (from == null || to == null) {+ return;+ }+ const filter = JSON.stringify([+ ...scopeFilter(traceIds),+ { type: 'string', column: 'name', operator: '=', value: TOOL_ROUND_NAME },+ { type: 'datetime', column: 'startTime', operator: '>=', value: from },+ { type: 'datetime', column: 'startTime', operator: '<=', value: to },+ ]);+ let unnamed = rounds.size;+ const budget: ByteBudget = { remaining: ROUND_BYTES_BUDGET };+ let cursor: string | undefined;+ const followed = new Set<string>();+ try {+ while (unnamed > 0 && budget.remaining > 0) {+ const params = new URLSearchParams({+ fields: ROUND_FIELDS,+ limit: String(ROUND_PAGE_SIZE),+ filter,+ });+ if (cursor) {+ params.set('cursor', cursor);+ }+ const page = await requestPage(destination, params, query, cursor != null, budget);+ for (const row of page.data) {+ const parsed = roundSchema.safeParse(row);+ const round = parsed.success ? rounds.get(parsed.data.id) : undefined;+ const tools = parsed.success ? toolRoundNames(parsed.data.input) : undefined;+ if (round != null && round.tools == null) {+ unnamed--;+ }+ if (round != null && tools != null) {+ round.tools = tools;+ }+ }+ const next = page.meta?.cursor || undefined;+ if (!next || page.data.length === 0 || followed.has(next)) {+ break;+ }+ followed.add(next);+ cursor = next;+ }+ } catch (error) {+ if (query.signal?.aborted) {+ throw error;+ }+ const reason = error instanceof TraceReadError ? error.code : 'unknown';+ logger.debug(`[traces] Tool rounds could not be named: ${reason}`);+ }+ }+async function readFrom(destination: LangfuseScoreDestination,traceIds: string[],@@ -907,6 +1030,7 @@ export function createLangfuseTraceReader({remaining -= page.data.length;const next = page.meta?.cursor || undefined;if (!next || page.data.length === 0) {+ await nameToolRounds(destination, traceIds, records);return { records };}/** A cursor that repeats would hand every later page the same records. */@@ -915,6 +1039,7 @@ export function createLangfuseTraceReader({}followed.add(next);if (remaining <= 0) {+ await nameToolRounds(destination, traceIds, records);return { records, next };}cursor = next;diff --git a/packages/api/src/langfuse/roles.ts b/packages/api/src/langfuse/roles.tsindex 6a61a1aaa1..170b8f7f7c 100644--- a/packages/api/src/langfuse/roles.ts+++ b/packages/api/src/langfuse/roles.ts@@ -13,7 +13,8 @@ import type { TTraceRecord, TTraceRecordRole } from 'librechat-data-provider';const AGENT_NODE_NAME = 'agent';const PROMPT_NAME = 'prompt';const MODEL_CALL_NAME = 'llm';-const TOOL_DISPATCH_NAME = 'tool-dispatch';+/** One round of tool calls; the SDK scopes its input to the calls the round ran. */+export const TOOL_ROUND_NAME = 'tool-dispatch';/** The SDK names an agent's workflow node with the saved agent's bare id. */const SAVED_AGENT_ID = /^agent_[A-Za-z0-9_-]+$/;@@ -25,7 +26,7 @@ const ROLE_BY_NAME: Record<string, TTraceRecordRole> = {[PROMPT_NAME]: 'plumbing',[ACTIVITY_PHASE_RUN_NAME]: 'plumbing',[MODEL_CALL_NAME]: 'model',- [TOOL_DISPATCH_NAME]: 'tools',+ [TOOL_ROUND_NAME]: 'tools',[ACTIVITY_LABEL_RUN_NAME]: 'stepLabel',[REASONING_LABEL_RUN_NAME]: 'reasoningLabel',[ACTIVITY_PHASE_LABEL_RUN_NAME]: 'phaseLabel',diff --git a/packages/api/src/langfuse/rounds.spec.ts b/packages/api/src/langfuse/rounds.spec.tsnew file mode 100644index 0000000000..8a2c7fa7b7--- /dev/null+++ b/packages/api/src/langfuse/rounds.spec.ts@@ -0,0 +1,32 @@+import { toolRoundNames } from './rounds';++describe('toolRoundNames', () => {+ it('reads the names of the calls a round ran, in order, and nothing else', () => {+ expect(+ toolRoundNames(+ '[{"name":"bash_tool","args":{"command":"cat secret"}},{"name":"search_code_mcp_github","args":{}}]',+ ),+ ).toEqual(['bash_tool', 'search_code_mcp_github']);+ expect(toolRoundNames([{ name: 'web_search', args: { query: 'q' } }])).toEqual(['web_search']);+ });++ it('reads nothing from input that is not a list of calls', () => {+ expect(toolRoundNames('{"messages":[{"role":"system","content":"prompt"}]}')).toBeUndefined();+ expect(toolRoundNames('[{"name":"ok"},{"role":"user","content":"hi"}]')).toBeUndefined();+ expect(toolRoundNames('[{"name":""}]')).toBeUndefined();+ expect(toolRoundNames('[{"name":7}]')).toBeUndefined();+ expect(toolRoundNames('[null]')).toBeUndefined();+ expect(toolRoundNames('[]')).toBeUndefined();+ expect(toolRoundNames('[{"name":')).toBeUndefined();+ expect(toolRoundNames(undefined)).toBeUndefined();+ });++ it('returns exact names or none: a round past the bounds is left unnamed, never shortened', () => {+ const calls = (count: number) =>+ Array.from({ length: count }, (_, index) => ({ name: `tool_${index}` }));+ expect(toolRoundNames(calls(256))).toHaveLength(256);+ expect(toolRoundNames(calls(257))).toBeUndefined();+ expect(toolRoundNames([{ name: 'n'.repeat(256) }])).toEqual(['n'.repeat(256)]);+ expect(toolRoundNames([{ name: 'n'.repeat(257) }])).toBeUndefined();+ });+});diff --git a/packages/api/src/langfuse/rounds.ts b/packages/api/src/langfuse/rounds.tsnew file mode 100644index 0000000000..334a2de5a7--- /dev/null+++ b/packages/api/src/langfuse/rounds.ts@@ -0,0 +1,40 @@+const MAX_TOOLS = 256;+const NAME_MAX_LENGTH = 256;++type Call = { name?: string | null };++function parse(input: unknown): unknown {+ if (typeof input !== 'string') {+ return input;+ }+ try {+ return JSON.parse(input);+ } catch {+ return undefined;+ }+}++/**+ * The tools a round called, from the round's own input. The SDK writes that+ * input as the list of calls the round ran, but leaves the whole graph state in+ * place when it finds none, so only a list whose every entry names a tool is+ * read, and only the names leave it: arguments and anything else recorded there+ * stay behind the deployment's content setting. The names are exact or absent: a+ * client checks them against the chat's own record of the round, which a+ * shortened list or a shortened name would fail for a round that matches.+ */+export function toolRoundNames(input: unknown): string[] | undefined {+ const calls = parse(input);+ if (!Array.isArray(calls) || calls.length === 0 || calls.length > MAX_TOOLS) {+ return undefined;+ }+ const names: string[] = [];+ for (const call of calls as Array<Call | null>) {+ const name = call != null && typeof call === 'object' ? call.name : undefined;+ if (typeof name !== 'string' || name === '' || name.length > NAME_MAX_LENGTH) {+ return undefined;+ }+ names.push(name);+ }+ return names;+}diff --git a/packages/data-provider/specs/config-schemas.spec.ts b/packages/data-provider/specs/config-schemas.spec.tsindex 110fdc47a4..6873eec9c4 100644--- a/packages/data-provider/specs/config-schemas.spec.ts+++ b/packages/data-provider/specs/config-schemas.spec.ts@@ -1882,12 +1882,14 @@ describe('interface.traceViewer', () => {parse({enabled: true,showInputOutput: true,+ showToolNames: true,maxRecords: 500,maxContentLength: 2000,requestsPerMinute: 10,requestTimeoutMs: 30_000,}),).toBe(true);+ expect(parse({ showToolNames: 'yes' })).toBe(false);expect(parse({ requestTimeoutMs: 999 })).toBe(false);expect(parse({ requestTimeoutMs: 300_001 })).toBe(false);expect(parse({ maxRecords: 0 })).toBe(false);@@ -1901,11 +1903,19 @@ describe('interface.traceViewer', () => {expect(interfaceSchema.parse({}).traceViewer).toBeUndefined();});+ it('names tool rounds from the tracing backend only when asked to', () => {+ expect(resolveTraceViewerConfig({ enabled: true }).showToolNames).toBe(false);+ expect(resolveTraceViewerConfig({ enabled: true, showToolNames: true }).showToolNames).toBe(+ true,+ );+ });+it('re-validates overrides that bypassed the schema', () => {expect(resolveTraceViewerConfig({enabled: 'true',showInputOutput: 1,+ showToolNames: 'true',maxRecords: 50_000,maxContentLength: -5,requestsPerMinute: Number.NaN,@@ -1914,6 +1924,7 @@ describe('interface.traceViewer', () => {).toEqual({enabled: false,showInputOutput: false,+ showToolNames: false,maxRecords: 10_000,maxContentLength: traceViewerDefaults.maxContentLength,requestsPerMinute: traceViewerDefaults.requestsPerMinute,diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex c3979e6de0..5e51ec86d6 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -1969,6 +1969,7 @@ export type TMcpServersConfig = z.infer<typeof mcpServersSchema>;export const traceViewerDefaults = {enabled: false,showInputOutput: false,+ showToolNames: false,maxRecords: 1000,maxContentLength: 50_000,requestsPerMinute: 30,@@ -1999,6 +2000,12 @@ const traceViewerSchema = z.object({enabled: z.boolean().optional(),/** Returns observation input, output and metadata in the record inspector. */showInputOutput: z.boolean().optional(),+ /**+ * Names the tools of each tool round from the tracing backend's own record of the round, at the+ * cost of further backend reads per listed page, which carry each round's input and output.+ * Off, a round is named only when the chat's messages can be matched to the trace.+ */+ showToolNames: z.boolean().optional(),/** Observations read from the tracing backend per request. */maxRecords: boundedIntegerSchema('maxRecords'),/** Characters kept from each input, output and metadata value before truncation. */@@ -2013,6 +2020,7 @@ export type TTraceViewerConfig = z.infer<typeof traceViewerSchema>;export type TResolvedTraceViewerConfig = {enabled: boolean;showInputOutput: boolean;+ showToolNames: boolean;} & Record<TraceViewerLimitField, number>;function boundedInteger(value: unknown, field: TraceViewerLimitField): number {@@ -2033,6 +2041,7 @@ export function resolveTraceViewerConfig(return {enabled: config?.enabled === true,showInputOutput: config?.showInputOutput === true,+ showToolNames: config?.showToolNames === true,maxRecords: boundedInteger(config?.maxRecords, 'maxRecords'),maxContentLength: boundedInteger(config?.maxContentLength, 'maxContentLength'),requestsPerMinute: boundedInteger(config?.requestsPerMinute, 'requestsPerMinute'),diff --git a/packages/data-provider/src/types/traces.ts b/packages/data-provider/src/types/traces.tsindex b70bb2d49d..57748a07f2 100644--- a/packages/data-provider/src/types/traces.ts+++ b/packages/data-provider/src/types/traces.ts@@ -47,6 +47,8 @@ export type TTraceRecord = {role?: TTraceRecordRole;/** The saved agent a `role: 'agent'` record ran; absent for an agent that was never saved. */agentId?: string;+ /** The tools a `role: 'tools'` round called, in order, as the backend recorded the round. */+ tools?: string[];name: string;model?: string;/** ISO-8601 timestamps. */