From 2d2eced9b731c31ec4dcde7baef5c7c7c888f673 Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Sun, 15 Nov 2026 20:09:25 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=A7=B0=20refactor:=20Extract=20Tool=20Gro?= =?UTF-8?q?up=20Body=20Presentation=20(#18186)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Move grouped tool rows and compact reasoning into the props-only ToolGroupBody component in @librechat/chat, retaining app-owned expansion, approval lifetime and attachment behavior. Select mock model options by exact descendant text so mobile Pin controls do not change the match. Related to berry-13/LibreChat#463. --- .../Chat/Messages/Content/ToolCallGroup.tsx | 86 ++------ .../ContentParts.integration.test.tsx | 7 +- .../Content/__tests__/ToolCallGroup.test.tsx | 92 +++++++- e2e/specs/mock/activity-labels.spec.ts | 13 +- e2e/specs/mock/helpers.ts | 5 +- packages/chat/src/components.ts | 2 + .../chat/src/components/parts/group/Body.tsx | 93 ++++++++ .../parts/group/__tests__/Body.spec.tsx | 201 ++++++++++++++++++ 8 files changed, 416 insertions(+), 83 deletions(-) create mode 100644 packages/chat/src/components/parts/group/Body.tsx create mode 100644 packages/chat/src/components/parts/group/__tests__/Body.spec.tsx diff --git a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx index 406abdee6b..6e245768cf 100644 --- a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx +++ b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx @@ -1,6 +1,6 @@ import { useState, useRef, useMemo, useEffect, useContext, useCallback } from 'react'; +import { Tools, Constants, ContentTypes } from 'librechat-data-provider'; import { ListChecks, MessageCircleQuestion, TriangleAlert, Users } from 'lucide-react'; -import { Tools, Constants, ContentTypes, isOpaqueReasoning } from 'librechat-data-provider'; import { LoneGroupContext, SoleToolContext, @@ -32,20 +32,21 @@ import { ToolAuthWarningContext, useExpandCollapse, ToolGroupHeader, + ToolGroupBody, } from '@librechat/chat/components'; import type { TAttachment, TMessageContentParts } from 'librechat-data-provider'; import type { ToolMeta } from '@librechat/chat'; import type { PartWithIndex } from './ParallelContent'; import { useLocalize, scheduleMessageContentLayoutReconcile } from '~/hooks'; import { useMessagePartsHost } from '~/Providers/MessagePartsHostContext'; -import { cn, getPartKeyIndex, hasPendingAuthInPart } from '~/utils'; import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP'; -import { AttachmentGroup, ReasoningCompact } from './Parts'; import { MCPAppViews } from '~/components/MCPUIResource'; +import { cn, hasPendingAuthInPart } from '~/utils'; import { HeaderActionSlotContext } from './slot'; import { StackedToolIcons } from './ToolOutput'; import { mapAttachments } from '~/utils/map'; import { getSourceDomains } from './sources'; +import { AttachmentGroup } from './Parts'; import SearchVerticals from './verticals'; interface ToolCallGroupProps { @@ -729,73 +730,18 @@ export default function ToolCallGroup({ > -
- {parts.map(({ part, idx }) => { - if (part.type === ContentTypes.THINK) { - const think = part.think; - const reasoning = - typeof think === 'string' ? think : (think?.value ?? ''); - /** A detached-subagent projection carries an empty THINK - * part flagged `reasoning_unavailable`, and encrypted - * reasoning has no readable text; `Part` renders both as a - * `ReasoningMarker`. `ReasoningCompact` would show the - * encoded payload or return null, so the marker has to - * keep going through the standalone path or it vanishes - * the moment its call joins a group. */ - if ( - (reasoning.trim() === '' && part.reasoning_unavailable === true) || - isOpaqueReasoning(reasoning) - ) { - return renderPart( - part, - idx, - isLast && idx === lastContentIdx, - handleToolExpand, - ); - } - /** `lastContentIdx` is the tail of this body, and every - * settled phase body has one. Only the group that holds - * the message's cursor has a thought still being written, - * the rule `PartWithContext` applies to a lone thought. */ - const streaming = isSubmitting && isLast && idx === lastContentIdx; - /** Mirrors the standalone `Reasoning` path: the authored - * label wins, generic text is only a fallback. */ - const generatedLabel = part.reasoning_label?.trim(); - const label = - generatedLabel || - (streaming - ? localize('com_ui_thinking') - : localize('com_ui_thoughts')); - return ( - - ); - } - return ( -
- {renderPart( - part, - idx, - isLast && idx === lastContentIdx, - handleToolExpand, - )} -
- ); - })} -
+
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx index 8e0e2a74c2..7429c4e2df 100644 --- a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx +++ b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx @@ -179,7 +179,6 @@ jest.mock('../Parts', () => ({ ), EmptyText: () =>
, Reasoning: () =>
, - ReasoningCompact: () =>
, Summary: () =>
, SteerPart: () =>
, Text: jest.fn(({ text }: { text?: string }) =>
{text}
), @@ -2160,7 +2159,11 @@ describe('ContentParts — live activity fold', () => { }); expect(screen.queryByTestId('activity-phase-card')).toBeNull(); - expect(screen.getByTestId('compact-reasoning')).toBeInTheDocument(); + expect(screen.getByRole('button', { name: /^com_ui_thinking\b/ })).toHaveAttribute( + 'aria-expanded', + 'true', + ); + expect(screen.getByText('Weighing the refs.')).toBeVisible(); }); it('holds the block at one row from a thought through the calls that follow it', () => { diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx index 3e501cc36d..dc8ad44e76 100644 --- a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx +++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx @@ -132,12 +132,13 @@ jest.mock('../ToolOutput', () => ({ })); jest.mock('lucide-react', () => ({ - ChevronDown: ({ className }: { className?: string }) => ( - + ChevronDown: ({ className, ...props }: React.SVGProps) => ( + {'chevron'} ), Users: () => {'users'}, + Lightbulb: () => {'thoughts'}, MessageCircleQuestion: () => {'question'}, ListChecks: () => {'checks'}, TriangleAlert: () => {'warning'}, @@ -189,9 +190,6 @@ jest.mock('../Parts', () => ({ AttachmentGroup: ({ attachments }: { attachments?: TAttachment[] }) => (
), - ReasoningCompact: ({ isStreaming = false }: { isStreaming?: boolean }) => ( -
- ), })); const makePart = ( @@ -312,12 +310,88 @@ describe('ToolCallGroup folded-in thought', () => { it('streams the thought at the tail of the group that holds the message cursor', () => { renderGroup({ ...baseProps, isLast: true }); - expect(screen.getByTestId('compact-reasoning')).toHaveAttribute('data-streaming', 'true'); + expect(screen.getByRole('button', { name: 'com_ui_thinking' })).toHaveAttribute( + 'aria-expanded', + 'false', + ); + expect(screen.getByTestId('streaming-thought-peek')).toHaveTextContent('Weighing the result'); }); it('settles the thought at the tail of a body the run has moved past', () => { renderGroup({ ...baseProps, isLast: false }); - expect(screen.getByTestId('compact-reasoning')).toHaveAttribute('data-streaming', 'false'); + expect(screen.getByRole('button', { name: 'com_ui_thoughts' })).toBeInTheDocument(); + expect(screen.queryByTestId('streaming-thought-peek')).not.toBeInTheDocument(); + }); +}); + +describe('ToolCallGroup package body adapter', () => { + it('preserves the renderer child, expansion callback and reasoning disclosure across updates', () => { + const element = ; + const renderPart = jest.fn< + ReturnType['renderPart']>, + Parameters['renderPart']> + >(() => element); + const parts = [ + { part: makePart('tool', ''), idx: 0 }, + { + part: { + type: ContentTypes.THINK, + think: 'Checking', + reasoning_label: 'Analysis', + } as TMessageContentParts, + idx: 1, + }, + ]; + const props = { + parts, + renderPart, + isSubmitting: true, + isLast: true, + showThinking: false, + lastContentIdx: 1, + }; + const { rerender } = renderGroup(props); + const draft = screen.getByRole('textbox', { name: 'Tool draft' }); + const wrapper = draft.parentElement; + const expand = renderPart.mock.calls[0][3]; + const disclosure = screen.getByRole('button', { name: 'Analysis' }); + fireEvent.change(draft, { target: { value: 'unsent' } }); + fireEvent.click(disclosure); + const controls = disclosure.getAttribute('aria-controls'); + rerender( + + + , + ); + expect(screen.getByRole('textbox', { name: 'Tool draft' })).toBe(draft); + expect(draft).toHaveValue('unsent'); + expect(draft.parentElement).toBe(wrapper); + expect(renderPart.mock.results.every(({ value }) => value === element)).toBe(true); + expect(renderPart.mock.calls.every((call) => call[3] === expand)).toBe(true); + expect(screen.getByRole('button', { name: 'Analysis' })).toBe(disclosure); + expect(disclosure).toHaveAttribute('aria-expanded', 'true'); + expect(disclosure).toHaveAttribute('aria-controls', controls); + expect(screen.getByText('Checked')).toBeInTheDocument(); + const header = screen.getByRole('button', { name: /^Fetch_image/ }); + fireEvent.click(header); + fireEvent.transitionEnd(screen.getByTestId('tool-call-group-panel')); + expect(screen.queryByRole('textbox')).not.toBeInTheDocument(); + fireEvent.click(header); + expect(renderPart.mock.calls.at(-1)?.[3]).toBe(expand); + expect(screen.getByRole('textbox', { name: 'Tool draft' })).toHaveValue('draft'); }); }); @@ -647,7 +721,7 @@ describe('ToolCallGroup image hoisting', () => { fireEvent.click(screen.getByRole('button', { name: /^Fetch_image/ })); expect(screen.getByTestId('inner-1')).toBeInTheDocument(); - expect(screen.queryByTestId('compact-reasoning')).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'com_ui_thoughts' })).not.toBeInTheDocument(); }); it('delegates an encrypted-reasoning part to the standalone renderer', () => { @@ -669,7 +743,7 @@ describe('ToolCallGroup image hoisting', () => { fireEvent.click(screen.getByRole('button', { name: /^Fetch_image/ })); expect(screen.getByTestId('inner-1')).toBeInTheDocument(); - expect(screen.queryByTestId('compact-reasoning')).not.toBeInTheDocument(); + expect(screen.queryByRole('button', { name: 'com_ui_thoughts' })).not.toBeInTheDocument(); }); it('unmounts tool bodies after a collapsed group finishes transitioning', () => { diff --git a/e2e/specs/mock/activity-labels.spec.ts b/e2e/specs/mock/activity-labels.spec.ts index f7785c1520..10edd074a9 100644 --- a/e2e/specs/mock/activity-labels.spec.ts +++ b/e2e/specs/mock/activity-labels.spec.ts @@ -86,7 +86,10 @@ test.describe('activity labels', () => { * The header is the feature: once a label lands it REPLACES the generic * "Ran N actions" verb above the same tool cards. */ - test('renders the generated label as the tool-group header', async ({ page, request }) => { + test('renders the generated label as the tool-group header @scenario:tool-group-body-mounts-on-disclosure', async ({ + page, + request, + }) => { test.setTimeout(120000); const label = uniqueLabel('activity'); await setLabelBehavior(request, { label: 'Stored two facts in memory' }); @@ -97,6 +100,14 @@ test.describe('activity labels', () => { messagesView(page).getByRole('button', { name: 'Stored two facts in memory' }), ).toBeVisible({ timeout: 30000 }); await expect(messagesView(page).getByRole('button', { name: /^Ran 2 actions/ })).toHaveCount(0); + const header = messagesView(page).getByRole('button', { name: 'Stored two facts in memory' }); + const panel = header.locator('xpath=../following-sibling::div[1]'); + await expect(header).toHaveAttribute('aria-expanded', 'false'); + await expect(panel.getByTestId('tool-call')).toHaveCount(0); + await header.click(); + await expect(panel.getByTestId('tool-call')).toHaveCount(2); + await header.click(); + await expect(panel.getByTestId('tool-call')).toHaveCount(0); }); /** diff --git a/e2e/specs/mock/helpers.ts b/e2e/specs/mock/helpers.ts index 93f8f0c20d..cd7a7ef25c 100644 --- a/e2e/specs/mock/helpers.ts +++ b/e2e/specs/mock/helpers.ts @@ -67,7 +67,10 @@ export async function selectMockEndpoint(page: Page, endpoint: MockEndpoint) { const expands = (await option.getAttribute('aria-expanded')) != null; await option.click(); if (expands) { - await page.getByRole('option', { name: endpoint.model, exact: true }).click(); + await page + .getByRole('option') + .filter({ has: page.getByText(endpoint.model, { exact: true }) }) + .click(); } await expect(trigger).toContainText(expands ? endpoint.model : endpoint.label); await expect(trigger).toHaveAttribute('aria-expanded', 'false'); diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts index 8d3ae85058..7777f4f9e3 100644 --- a/packages/chat/src/components.ts +++ b/packages/chat/src/components.ts @@ -129,6 +129,8 @@ export { getMessageAriaLabel, getHeaderPrefixForScreenReader } from './component export { default as PhaseLabel, FOLD_EASING } from './components/parts/PhaseLabel'; export { default as ToolGroupHeader } from './components/parts/group/Header'; export type { ToolGroupHeaderProps } from './components/parts/group/Header'; +export { default as ToolGroupBody } from './components/parts/group/Body'; +export type { ToolGroupBodyProps } from './components/parts/group/Body'; /** Parts: the leaf components and row classes tool cards share. */ export { default as Stdout } from './components/parts/Stdout'; diff --git a/packages/chat/src/components/parts/group/Body.tsx b/packages/chat/src/components/parts/group/Body.tsx new file mode 100644 index 0000000000..b9e522b31f --- /dev/null +++ b/packages/chat/src/components/parts/group/Body.tsx @@ -0,0 +1,93 @@ +import { cn } from '@librechat/client'; +import { ContentTypes, isOpaqueReasoning } from 'librechat-data-provider'; +import type { TMessageContentParts } from 'librechat-data-provider'; +import type { ReactElement, ReactNode } from 'react'; +import { getPartKeyIndex } from '../../../core/content'; +import { ReasoningCompact } from '../Reasoning'; + +export type ToolGroupBodyProps = { + parts: { part: TMessageContentParts; idx: number }[]; + isSubmitting: boolean; + isLast: boolean; + showThinking: boolean; + smoothStreaming: boolean; + lastContentIdx: number; + thinkingLabel: string; + thoughtsLabel: string; + renderPart: ( + part: TMessageContentParts, + idx: number, + isLastPart: boolean, + onToolExpand?: () => void, + ) => ReactNode; + onToolExpand: () => void; +}; + +/** Inner rows only; the app owns disclosure, providers and the body mount lifetime. */ +export default function ToolGroupBody({ + parts, + isSubmitting, + isLast, + showThinking, + smoothStreaming, + lastContentIdx, + thinkingLabel, + thoughtsLabel, + renderPart, + onToolExpand, +}: ToolGroupBodyProps): ReactElement { + return ( +
+ {parts.map(({ part, idx }) => { + if (part.type === ContentTypes.THINK) { + const think = part.think; + const reasoning = typeof think === 'string' ? think : (think?.value ?? ''); + /** A detached-subagent projection carries an empty THINK + * part flagged `reasoning_unavailable`, and encrypted + * reasoning has no readable text; `Part` renders both as a + * `ReasoningMarker`. `ReasoningCompact` would show the + * encoded payload or return null, so the marker has to + * keep going through the standalone path or it vanishes + * the moment its call joins a group. */ + if ( + (reasoning.trim() === '' && part.reasoning_unavailable === true) || + isOpaqueReasoning(reasoning) + ) { + return renderPart(part, idx, isLast && idx === lastContentIdx, onToolExpand); + } + /** `lastContentIdx` is the tail of this body, and every + * settled phase body has one. Only the group that holds + * the message's cursor has a thought still being written, + * the rule `PartWithContext` applies to a lone thought. */ + const streaming = isSubmitting && isLast && idx === lastContentIdx; + /** Mirrors the standalone `Reasoning` path: the authored + * label wins, generic text is only a fallback. */ + const generatedLabel = part.reasoning_label?.trim(); + const label = generatedLabel || (streaming ? thinkingLabel : thoughtsLabel); + return ( + + ); + } + return ( +
+ {renderPart(part, idx, isLast && idx === lastContentIdx, onToolExpand)} +
+ ); + })} +
+ ); +} diff --git a/packages/chat/src/components/parts/group/__tests__/Body.spec.tsx b/packages/chat/src/components/parts/group/__tests__/Body.spec.tsx new file mode 100644 index 0000000000..2d15efb0d8 --- /dev/null +++ b/packages/chat/src/components/parts/group/__tests__/Body.spec.tsx @@ -0,0 +1,201 @@ +/** @jest-environment jsdom */ +import { useEffect } from 'react'; +import { ContentTypes } from 'librechat-data-provider'; +import { fireEvent, render, screen } from '@testing-library/react'; +import type { TMessageContentParts } from 'librechat-data-provider'; +import type { ToolGroupBodyProps } from '../Body'; +import { createMessagePartsHost } from '../../../../__fixtures__/partsHost'; +import { MessagePartsHostProvider } from '../../../../react/host'; +import { initEnglish } from '../../../../__fixtures__/i18n'; +import Body from '../Body'; + +beforeAll(initEnglish); + +const tool = (streamedIndex?: number): TMessageContentParts => ({ + type: ContentTypes.TEXT, + text: 'Tool renderer content', + streamedIndex, +}); +const thought = ( + think: string | { value: string }, + reasoning_label?: string, +): TMessageContentParts => + ({ type: ContentTypes.THINK, think, reasoning_label }) as TMessageContentParts; +const defaults = { + parts: [], + isSubmitting: false, + isLast: false, + showThinking: false, + smoothStreaming: true, + lastContentIdx: 0, + thinkingLabel: 'Thinking now', + thoughtsLabel: 'Finished thoughts', + renderPart: jest.fn((_part, idx) => {`Part ${idx}`}), + onToolExpand: jest.fn(), +} satisfies ToolGroupBodyProps; +const host = createMessagePartsHost(); + +function reasoningBody(props: Partial) { + return ( + + + + ); +} + +describe('ToolGroupBody', () => { + it('renders an empty body without an app host', () => { + const { container } = render(); + expect(container.firstElementChild).toHaveClass('flex', 'flex-col', 'py-0.5'); + expect(container.firstElementChild).toBeEmptyDOMElement(); + }); + + it.each([ + [false, false, false], + [false, true, false], + [true, false, false], + [true, true, true], + ])( + 'keeps mount animation gated by submitting=%s and smoothing=%s', + (isSubmitting, smoothStreaming, animated) => { + const part = tool(); + render( + , + ); + const wrapper = screen.getByText('Part 3').parentElement; + expect(wrapper?.className).toBe( + animated + ? 'animate-in fade-in-0 slide-in-from-top-1 duration-200 motion-reduce:animate-none' + : '', + ); + expect(defaults.renderPart).toHaveBeenLastCalledWith(part, 3, true, defaults.onToolExpand); + }, + ); + + it('keeps stamped tool keys and child state through index compaction', () => { + const onMount = jest.fn(); + const onUnmount = jest.fn(); + function Child() { + useEffect(() => { + onMount(); + return onUnmount; + }, []); + return ; + } + const renderPart = jest.fn(() => ); + const part = tool(7); + const { rerender } = render( + , + ); + const input = screen.getByRole('textbox'); + const wrapper = input.parentElement; + fireEvent.change(input, { target: { value: 'retained draft' } }); + rerender( + , + ); + expect(screen.getByRole('textbox')).toBe(input); + expect(input.parentElement).toBe(wrapper); + expect(input).toHaveValue('retained draft'); + expect(onMount).toHaveBeenCalledTimes(1); + expect(onUnmount).not.toHaveBeenCalled(); + }); + + it.each([ + { type: ContentTypes.THINK, think: '', reasoning_unavailable: true }, + { type: ContentTypes.THINK, think: { value: ' ' }, reasoning_unavailable: true }, + { + type: ContentTypes.THINK, + think: Buffer.from(Array.from({ length: 900 }, (_, i) => (i * 37 + 3) % 256)).toString( + 'base64', + ), + }, + ])('delegates unreadable reasoning unchanged without an app host: %#', (part) => { + const renderPart = jest.fn(() => {'Reasoning marker'}); + const { container } = render( + , + ); + expect(renderPart).toHaveBeenCalledWith(part, 2, true, defaults.onToolExpand); + expect(container.firstElementChild?.firstElementChild).toBe( + screen.getByText('Reasoning marker'), + ); + }); + + it.each([ + [true, true, 2, 'Thinking now', true], + [true, false, 2, 'Finished thoughts', false], + [false, true, 2, 'Finished thoughts', false], + [true, true, 3, 'Finished thoughts', false], + ])( + 'streams only the message cursor: submitting=%s last=%s cursor=%s', + (isSubmitting, isLast, lastContentIdx, label, streaming) => { + render( + reasoningBody({ + parts: [{ part: thought({ value: 'Checking the result.' }), idx: 2 }], + isSubmitting, + isLast, + lastContentIdx, + }), + ); + expect(screen.getByRole('button', { name: label })).toHaveAttribute('aria-expanded', 'false'); + expect(screen.queryByTestId('streaming-thought-peek') != null).toBe(streaming); + }, + ); + + it('preserves an authored label and disclosure identity while reasoning settles', () => { + const parts = [{ part: thought('Checking the result.', ' Result analysis '), idx: 2 }]; + const { rerender } = render( + reasoningBody({ parts, isSubmitting: true, isLast: true, lastContentIdx: 2 }), + ); + const disclosure = screen.getByRole('button', { name: 'Result analysis' }); + fireEvent.click(disclosure); + const panelId = disclosure.getAttribute('aria-controls'); + expect(screen.getByText('Checking the result.')).toBeInTheDocument(); + rerender( + reasoningBody({ + parts: [{ part: thought('Result checked.', 'Result analysis'), idx: 2 }], + showThinking: false, + }), + ); + expect(screen.getByRole('button', { name: 'Result analysis' })).toBe(disclosure); + expect(disclosure).toHaveAttribute('aria-expanded', 'true'); + expect(disclosure).toHaveAttribute('aria-controls', panelId); + expect(screen.getByText('Result checked.')).toBeInTheDocument(); + }); + + it('keeps mixed row order, empty thoughts and the supplied renderer element', () => { + const element = {'Supplied tool'}; + const renderPart = jest.fn(() => element); + const { container } = render( + reasoningBody({ + parts: [ + { part: thought(''), idx: 0 }, + { part: tool(), idx: 1 }, + { part: thought('Readable thought', ' '), idx: 2 }, + ], + renderPart, + showThinking: true, + }), + ); + const rows = container.firstElementChild; + expect(rows?.children).toHaveLength(2); + expect(rows?.firstElementChild).toContainElement(screen.getByText('Supplied tool')); + expect(rows?.lastElementChild).toContainElement( + screen.getByRole('button', { name: 'Finished thoughts' }), + ); + expect(renderPart).toHaveBeenCalledTimes(1); + expect(screen.getByText('Readable thought')).toBeInTheDocument(); + }); +});