🧰 refactor: Extract Tool Group Body Presentation (#18186)

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.
This commit is contained in:
Marco Beretta 2026-11-15 20:09:25 +01:00 • committed by GitHub
parent b103ac622e
commit 2d2eced9b7
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
8 changed files with 416 additions and 83 deletions

View file

@ -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({
>
<LoneGroupContext.Provider value={count === 1 && !hasReasoning}>
<SoleToolContext.Provider value={!hasReasoning && (phaseSole ?? count === 1)}>
<div className="flex flex-col py-0.5">
{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 (
<ReasoningCompact
key={`reasoning-${idx}`}
partKeyIndex={getPartKeyIndex(part, idx)}
reasoning={reasoning}
label={label}
showThinking={showThinking}
isStreaming={streaming}
/>
);
}
return (
<div
key={`tool-${getPartKeyIndex(part, idx)}`}
className={cn(
isSubmitting &&
smoothStreaming &&
'animate-in fade-in-0 slide-in-from-top-1 duration-200 motion-reduce:animate-none',
)}
>
{renderPart(
part,
idx,
isLast && idx === lastContentIdx,
handleToolExpand,
)}
</div>
);
})}
</div>
<ToolGroupBody
parts={parts}
isSubmitting={isSubmitting}
isLast={isLast}
showThinking={showThinking}
smoothStreaming={smoothStreaming}
lastContentIdx={lastContentIdx}
thinkingLabel={localize('com_ui_thinking')}
thoughtsLabel={localize('com_ui_thoughts')}
renderPart={renderPart}
onToolExpand={handleToolExpand}
/>
</SoleToolContext.Provider>
</LoneGroupContext.Provider>
</GeneratedToolLabelContext.Provider>

View file

@ -179,7 +179,6 @@ jest.mock('../Parts', () => ({
),
EmptyText: () => <div data-testid="empty-text" />,
Reasoning: () => <div data-testid="reasoning" />,
ReasoningCompact: () => <div data-testid="compact-reasoning" />,
Summary: () => <div data-testid="summary" />,
SteerPart: () => <div data-testid="steer" />,
Text: jest.fn(({ text }: { text?: string }) => <div data-testid="text">{text}</div>),
@ -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', () => {

View file

@ -132,12 +132,13 @@ jest.mock('../ToolOutput', () => ({
}));
jest.mock('lucide-react', () => ({
ChevronDown: ({ className }: { className?: string }) => (
<span data-testid="group-chevron" className={className}>
ChevronDown: ({ className, ...props }: React.SVGProps<SVGSVGElement>) => (
<span data-testid="group-chevron" className={className} aria-hidden={props['aria-hidden']}>
{'chevron'}
</span>
),
Users: () => <span>{'users'}</span>,
Lightbulb: () => <span>{'thoughts'}</span>,
MessageCircleQuestion: () => <span data-testid="question-icon">{'question'}</span>,
ListChecks: () => <span data-testid="task-check-icon">{'checks'}</span>,
TriangleAlert: () => <span>{'warning'}</span>,
@ -189,9 +190,6 @@ jest.mock('../Parts', () => ({
AttachmentGroup: ({ attachments }: { attachments?: TAttachment[] }) => (
<div data-testid="attachment-group" data-count={attachments?.length ?? 0} />
),
ReasoningCompact: ({ isStreaming = false }: { isStreaming?: boolean }) => (
<div data-testid="compact-reasoning" data-streaming={String(isStreaming)} />
),
}));
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 = <input key="tool-child" aria-label="Tool draft" defaultValue="draft" />;
const renderPart = jest.fn<
ReturnType<React.ComponentProps<typeof ToolCallGroup>['renderPart']>,
Parameters<React.ComponentProps<typeof ToolCallGroup>['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(
<RecoilRoot>
<ToolCallGroup
{...props}
parts={[
{ part: makePart('tool', 'done'), idx: 0 },
{
part: {
type: ContentTypes.THINK,
think: { value: 'Checked' },
reasoning_label: 'Analysis',
} as TMessageContentParts,
idx: 1,
},
]}
/>
</RecoilRoot>,
);
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', () => {

View file

@ -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);
});
/**

View file

@ -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');

View file

@ -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';

View file

@ -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 (
<div className="flex flex-col py-0.5">
{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 (
<ReasoningCompact
key={`reasoning-${idx}`}
partKeyIndex={getPartKeyIndex(part, idx)}
reasoning={reasoning}
label={label}
showThinking={showThinking}
isStreaming={streaming}
/>
);
}
return (
<div
key={`tool-${getPartKeyIndex(part, idx)}`}
className={cn(
isSubmitting &&
smoothStreaming &&
'animate-in fade-in-0 slide-in-from-top-1 duration-200 motion-reduce:animate-none',
)}
>
{renderPart(part, idx, isLast && idx === lastContentIdx, onToolExpand)}
</div>
);
})}
</div>
);
}

View file

@ -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) => <span key={idx}>{`Part ${idx}`}</span>),
onToolExpand: jest.fn(),
} satisfies ToolGroupBodyProps;
const host = createMessagePartsHost();
function reasoningBody(props: Partial<ToolGroupBodyProps>) {
return (
<MessagePartsHostProvider host={host}>
<Body {...defaults} {...props} />
</MessagePartsHostProvider>
);
}
describe('ToolGroupBody', () => {
it('renders an empty body without an app host', () => {
const { container } = render(<Body {...defaults} />);
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(
<Body
{...defaults}
parts={[{ part, idx: 3 }]}
isSubmitting={isSubmitting}
smoothStreaming={smoothStreaming}
isLast
lastContentIdx={3}
/>,
);
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 <input aria-label="Tool input" defaultValue="original" />;
}
const renderPart = jest.fn(() => <Child />);
const part = tool(7);
const { rerender } = render(
<Body {...defaults} parts={[{ part, idx: 7 }]} renderPart={renderPart} />,
);
const input = screen.getByRole('textbox');
const wrapper = input.parentElement;
fireEvent.change(input, { target: { value: 'retained draft' } });
rerender(
<Body {...defaults} parts={[{ part: { ...part }, idx: 1 }]} renderPart={renderPart} />,
);
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(() => <span key="marker">{'Reasoning marker'}</span>);
const { container } = render(
<Body
{...defaults}
parts={[{ part: part as TMessageContentParts, idx: 2 }]}
isLast
lastContentIdx={2}
renderPart={renderPart}
/>,
);
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 = <span key="tool">{'Supplied tool'}</span>;
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();
});
});