Skip to content

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

🪗 fix: Open the Lone Tool Call Directly and Label Settled Commands Ran (#16547)

Marco Beretta5a6316ec6ae9
diff --git a/client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx b/client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx
index d746de0eb9..9b629523a1 100644
--- a/client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx
+++ b/client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx
@@ -1,5 +1,4 @@
-import { useState, useEffect, useCallback } from 'react';
-import { useRecoilValue } from 'recoil';
+import { useCallback } from 'react';
import { MessageCircleQuestion, TriangleAlert } from 'lucide-react';
import type { Agents, PartMetadata } from 'librechat-data-provider';
import {
@@ -9,11 +8,11 @@ import {
} from '~/utils/approval';
import AskUserQuestionProgress from './AskUserQuestionProgress';
import { useLocalize, useExpandCollapse } from '~/hooks';
+import { useToolExpansion } from './disclosure';
import ProgressText from './ProgressText';
import EmptyText from './Parts/EmptyText';
import { TOOL_ROW_CLASSES } from './rows';
import Container from './Container';
-import store from '~/store';
/**
* Static rendering of a COMPLETED (or abandoned) `ask_user_question` tool call —
@@ -48,25 +47,15 @@ export default function AskUserQuestionCall({
onExpand?: () => void;
}) {
const localize = useLocalize();
- const autoExpand = useRecoilValue(store.autoExpandTools);
- const [expanded, setExpanded] = useState(autoExpand);
+ const [expanded, setExpanded] = useToolExpansion(true);
const { style: expandStyle, ref: expandRef } = useExpandCollapse(expanded);
- useEffect(() => {
- if (autoExpand) {
- setExpanded(true);
- }
- }, [autoExpand]);
-
const toggleExpanded = useCallback(() => {
- setExpanded((prev) => {
- const next = !prev;
- if (next) {
- onExpand?.();
- }
- return next;
- });
- }, [onExpand]);
+ setExpanded(!expanded);
+ if (!expanded) {
+ onExpand?.();
+ }
+ }, [expanded, onExpand, setExpanded]);
const question = parseAskUserQuestionArgs(args);
const batch = parseAskUserQuestionsArgs(args);
diff --git a/client/src/components/Chat/Messages/Content/CodeAnalyze.tsx b/client/src/components/Chat/Messages/Content/CodeAnalyze.tsx
index dc7310ef07..750dd9fc38 100644
--- a/client/src/components/Chat/Messages/Content/CodeAnalyze.tsx
+++ b/client/src/components/Chat/Messages/Content/CodeAnalyze.tsx
@@ -1,12 +1,10 @@
-import { useState, useEffect } from 'react';
-import { useRecoilValue } from 'recoil';
import { Terminal } from 'lucide-react';
import type { ToolCallPhase } from '~/utils/toolCallPhase';
import { useProgress, useLocalize } from '~/hooks';
+import { useToolExpansion } from './disclosure';
import ProgressText from './ProgressText';
import MarkdownLite from './MarkdownLite';
import { cn } from '~/utils';
-import store from '~/store';
export default function CodeAnalyze({
initialProgress = 0.1,
@@ -21,23 +19,13 @@ export default function CodeAnalyze({
}) {
const localize = useLocalize();
const progress = useProgress(initialProgress);
- const autoExpand = useRecoilValue(store.autoExpandTools);
- const [showCode, setShowCode] = useState(autoExpand);
-
- useEffect(() => {
- if (autoExpand) {
- setShowCode(true);
- }
- }, [autoExpand]);
+ const [showCode, setShowCode] = useToolExpansion(true);
const handleToggleCode = () => {
- setShowCode((prev) => {
- const next = !prev;
- if (next) {
- onExpand?.();
- }
- return next;
- });
+ setShowCode(!showCode);
+ if (!showCode) {
+ onExpand?.();
+ }
};
const logs = outputs.reduce((acc, output) => {
diff --git a/client/src/components/Chat/Messages/Content/ContentParts.tsx b/client/src/components/Chat/Messages/Content/ContentParts.tsx
index d54293fbeb..a3a8386682 100644
--- a/client/src/components/Chat/Messages/Content/ContentParts.tsx
+++ b/client/src/components/Chat/Messages/Content/ContentParts.tsx
@@ -24,6 +24,7 @@ import {
reasoningDisclosure,
ToolDisclosureContext,
ToolDisclosureKeyContext,
+ SoleToolContext,
} from './disclosure';
import {
groupActivityPhases,
@@ -1149,19 +1150,25 @@ const ContentPartsBody = memo(function ContentPartsBody({
absoluteIndexAt(segment.labelIndex) === lastContentIdx
}
>
- {renderSegment(
- segment.content,
- absoluteIndexAt(segment.startIndex),
- segmentIndices,
- `phase-content-${cardKey}`,
- /** Opening a live row should show the calls running, so its
- * groups keep their own live expansion rather than the
- * settled-phase default of staying shut. */
- !live,
- ownsCursor,
- true,
- true,
- )}
+ <SoleToolContext.Provider
+ value={
+ segment.content.filter((part) => part?.type === ContentTypes.TOOL_CALL).length === 1
+ }
+ >
+ {renderSegment(
+ segment.content,
+ absoluteIndexAt(segment.startIndex),
+ segmentIndices,
+ `phase-content-${cardKey}`,
+ /** Opening a live row should show the calls running, so its
+ * groups keep their own live expansion rather than the
+ * settled-phase default of staying shut. */
+ !live,
+ ownsCursor,
+ true,
+ true,
+ )}
+ </SoleToolContext.Provider>
</ActivityPhaseGroup>
);
});
@@ -1379,7 +1386,10 @@ const ContentParts = memo(function ContentParts(props: ContentPartsProps) {
<ReasoningDisclosureContext.Provider value={reasoningDisclosures}>
<ToolDisclosureContext.Provider value={toolDisclosures}>
<MCPAppSuppressionContext.Provider value={suppressedAppAttachments}>
- <ContentPartsBody {...props} />
+ {/* A nested message (a subagent's) is not the sole call of the group around it. */}
+ <SoleToolContext.Provider value={undefined}>
+ <ContentPartsBody {...props} />
+ </SoleToolContext.Provider>
</MCPAppSuppressionContext.Provider>
<MCPAppViews
key={`message-apps-${appRenderScope}`}
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/BashCall.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/BashCall.test.tsx
index 3e0276e4b5..6ea6cac939 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/BashCall.test.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/BashCall.test.tsx
@@ -2,6 +2,8 @@ import React from 'react';
import { RecoilRoot } from 'recoil';
import copy from 'copy-to-clipboard';
import { render, screen, fireEvent } from '@testing-library/react';
+import type { ToolDisclosures } from '../../disclosure';
+import { SoleToolContext, ToolDisclosureContext, ToolDisclosureKeyContext } from '../../disclosure';
import BashCall from '../BashCall';
import store from '~/store';
@@ -15,7 +17,7 @@ jest.mock('~/hooks', () => ({
com_ui_command_timed_out: 'timed out',
com_ui_writing_command: 'Writing command',
com_ui_running_command: 'Running command',
- com_ui_command_finished: 'Finished running',
+ com_ui_command_finished: 'Ran command',
com_ui_cancelled: 'Cancelled',
com_ui_copy_code: 'Copy code',
com_ui_background_running: 'Running in background',
@@ -48,13 +50,15 @@ jest.mock('~/components/Chat/Messages/Content/ProgressText', () => ({
inProgressText,
finishedText,
verdict,
+ onClick,
}: {
phase: 'running' | 'completed' | 'cancelled' | 'failed';
inProgressText: string;
finishedText: string;
verdict?: string;
+ onClick?: () => void;
}) => (
- <div data-testid="progress-text">
+ <div data-testid="progress-text" onClick={onClick}>
{phase === 'running' ? inProgressText : finishedText}
{phase === 'failed' ? ' — tool failed' : ''}
{phase === 'failed' && verdict ? ` · ${verdict}` : ''}
@@ -174,7 +178,7 @@ describe('BashCall intent label', () => {
</RecoilRoot>,
);
expect(screen.getByTestId('progress-text')).toHaveTextContent('Waiting for the task to settle');
- expect(screen.queryByText('Finished running')).not.toBeInTheDocument();
+ expect(screen.queryByText('Ran command')).not.toBeInTheDocument();
});
it('falls back to the generic labels when no intent is present', () => {
@@ -317,11 +321,83 @@ describe('BashCall backgrounded calls', () => {
/>
</RecoilRoot>,
);
- expect(screen.getByTestId('progress-text')).toHaveTextContent('Finished running');
+ expect(screen.getByTestId('progress-text')).toHaveTextContent('Ran command');
expect(screen.getByText('hi')).toBeInTheDocument();
});
});
+describe('BashCall sole tool disclosure', () => {
+ const renderCall = (soleTool: boolean) =>
+ render(
+ <RecoilRoot>
+ <SoleToolContext.Provider value={soleTool}>
+ <BashCall
+ initialProgress={1}
+ isSubmitting={false}
+ args={{ command: 'echo hi' }}
+ output="hi"
+ />
+ </SoleToolContext.Provider>
+ </RecoilRoot>,
+ );
+ const panel = (container: HTMLElement) =>
+ container.querySelector('[style*="grid-template-rows"]') as HTMLElement;
+
+ it('opens the card when it is the only call, with autoExpandTools off', () => {
+ const { container } = renderCall(true);
+ expect(panel(container).style.gridTemplateRows).toBe('1fr');
+ });
+
+ it('keeps the card collapsed when it is one of several calls', () => {
+ const { container } = renderCall(false);
+ expect(panel(container).style.gridTemplateRows).toBe('0fr');
+ });
+
+ it('closes the card again when its group gains a second call', () => {
+ const { container, rerender } = renderCall(true);
+ expect(panel(container).style.gridTemplateRows).toBe('1fr');
+ rerender(
+ <RecoilRoot>
+ <SoleToolContext.Provider value={false}>
+ <BashCall
+ initialProgress={1}
+ isSubmitting={false}
+ args={{ command: 'echo hi' }}
+ output="hi"
+ />
+ </SoleToolContext.Provider>
+ </RecoilRoot>,
+ );
+ expect(panel(container).style.gridTemplateRows).toBe('0fr');
+ });
+
+ it('keeps a closed sole card closed when it remounts under a new group', () => {
+ const disclosures: ToolDisclosures = new Map();
+ const tree = () => (
+ <RecoilRoot>
+ <ToolDisclosureContext.Provider value={disclosures}>
+ <ToolDisclosureKeyContext.Provider value="call-1">
+ <SoleToolContext.Provider value>
+ <BashCall
+ initialProgress={1}
+ isSubmitting={false}
+ args={{ command: 'echo hi' }}
+ output="hi"
+ />
+ </SoleToolContext.Provider>
+ </ToolDisclosureKeyContext.Provider>
+ </ToolDisclosureContext.Provider>
+ </RecoilRoot>
+ );
+ const first = render(tree());
+ fireEvent.click(first.getByTestId('progress-text'));
+ expect(panel(first.container).style.gridTemplateRows).toBe('0fr');
+ first.unmount();
+ const second = render(tree());
+ expect(panel(second.container).style.gridTemplateRows).toBe('0fr');
+ });
+});
+
/**
* jsdom has no layout, so the capped pane's scroll geometry is stubbed:
* `clientHeight` is fixed, `scrollHeight` either reads from mutable state
@@ -522,7 +598,7 @@ describe('BashCall exit status', () => {
it('does not read a trailer the sandbox command printed itself', () => {
const { container } = renderSettled('stdout:\n[exit code: 1]', false);
- expect(screen.getByTestId('progress-text')).toHaveTextContent('Finished running');
+ expect(screen.getByTestId('progress-text')).toHaveTextContent('Ran command');
expect(screen.getByTestId('progress-text')).not.toHaveTextContent('tool failed');
expect(container.querySelectorAll('pre')[1]).toHaveTextContent('[exit code: 1]');
});
@@ -541,7 +617,7 @@ describe('BashCall exit status', () => {
const { container } = renderSettled(
'stdout:\nok\n\nstderr:\nError: deprecated flag\n\n[exit code: 0]',
);
- expect(screen.getByTestId('progress-text')).toHaveTextContent('Finished running');
+ expect(screen.getByTestId('progress-text')).toHaveTextContent('Ran command');
expect(screen.getByTestId('progress-text')).not.toHaveTextContent('tool failed');
const stderr = screen.getByText(/deprecated flag/);
expect(stderr).toHaveClass('text-text-secondary');
diff --git a/client/src/components/Chat/Messages/Content/Parts/useToolCallState.ts b/client/src/components/Chat/Messages/Content/Parts/useToolCallState.ts
index e1c76342e8..98ef27288f 100644
--- a/client/src/components/Chat/Messages/Content/Parts/useToolCallState.ts
+++ b/client/src/components/Chat/Messages/Content/Parts/useToolCallState.ts
@@ -1,13 +1,10 @@
-import { useState, useEffect, useCallback } from 'react';
-import { useAtom } from 'jotai';
-import { useRecoilValue } from 'recoil';
+import { useCallback } from 'react';
import type { PartMetadata } from 'librechat-data-provider';
import type { ToolCallPhase } from '~/utils/toolCallPhase';
import { isError } from '~/components/Chat/Messages/Content/ToolOutput';
import { resolveToolCallPhase } from '~/utils/toolCallPhase';
import { useProgress, useExpandCollapse } from '~/hooks';
-import { useToolDisclosure } from '../disclosure';
-import store from '~/store';
+import { useToolExpansion } from '../disclosure';
interface ToolCallState {
showCode: boolean;
@@ -55,21 +52,12 @@ export default function useToolCallState({
extraError = false,
extraCancelled = false,
}: UseToolCallStateInput): ToolCallState {
- const autoExpand = useRecoilValue(store.autoExpandTools);
const hasOutput = output.length > 0;
const hasContent = hasInput || hasOutput;
- const [expansionOverride, setExpansionOverride] = useAtom(useToolDisclosure());
- const [defaultExpanded, setDefaultExpanded] = useState(() => autoExpand && hasContent);
- const showCode = expansionOverride ?? defaultExpanded;
+ const [showCode, setExpansionOverride] = useToolExpansion(hasContent);
const { style: expandStyle, ref: expandRef } = useExpandCollapse(showCode);
- useEffect(() => {
- if (autoExpand && hasContent) {
- setDefaultExpanded(true);
- }
- }, [autoExpand, hasContent]);
-
const isClosed = runStepStatus != null;
/**
* Passing 1 in for a closed step stops `useProgress` scheduling its 200ms
diff --git a/client/src/components/Chat/Messages/Content/RetrievalCall.tsx b/client/src/components/Chat/Messages/Content/RetrievalCall.tsx
index fc44a587d8..4be8d24b88 100644
--- a/client/src/components/Chat/Messages/Content/RetrievalCall.tsx
+++ b/client/src/components/Chat/Messages/Content/RetrievalCall.tsx
@@ -1,20 +1,18 @@
-import { useMemo, useState, useEffect, useCallback } from 'react';
-import { useRecoilValue } from 'recoil';
+import { useMemo, useState, useCallback } from 'react';
import { Tools } from 'librechat-data-provider';
import { TooltipAnchor } from '@librechat/client';
import { FileText, FileSpreadsheet, FileCode, FileImage, File } from 'lucide-react';
import type { TAttachment, TFile, PartMetadata } from 'librechat-data-provider';
+import { toolPanelSpacingClassName, useToolExpansion } from './disclosure';
import { useLocalize, useProgress, useExpandCollapse } from '~/hooks';
import { ToolIcon, OutputRenderer, isError } from './ToolOutput';
import { resolveToolCallPhase } from '~/utils/toolCallPhase';
-import { toolPanelSpacingClassName } from './disclosure';
import FilePreviewDialog from './FilePreviewDialog';
import { sortPagesByRelevance, cn } from '~/utils';
import { useToolCallIntent } from './Parts/intent';
import { useToolPreparation } from './preparation';
import { useGetFiles } from '~/data-provider';
import ProgressText from './ProgressText';
-import store from '~/store';
interface FileSource {
fileId: string;
@@ -382,7 +380,6 @@ export default function RetrievalCall({
hasError: typeof output === 'string' && isError(output),
});
const hasOutput = !!output && !isError(output);
- const autoExpand = useRecoilValue(store.autoExpandTools);
const fileSources = useMemo(() => extractFileSources(attachments), [attachments]);
const parsedResults = useMemo(
@@ -404,7 +401,8 @@ export default function RetrievalCall({
const hasResults = displayResults.length > 0;
const hasExpandableContent = phase !== 'failed' && hasResults;
- const [showOutput, setShowOutput] = useState(() => autoExpand && hasExpandableContent);
+ const [expanded, setExpanded] = useToolExpansion(hasExpandableContent);
+ const showOutput = hasExpandableContent && expanded;
const { style: expandStyle, ref: expandRef } = useExpandCollapse(showOutput);
const [previewIndex, setPreviewIndex] = useState<number | null>(null);
@@ -440,25 +438,12 @@ export default function RetrievalCall({
};
}, [displayResults, previewIndex]);
- useEffect(() => {
- if (!hasExpandableContent) {
- setShowOutput(false);
- return;
- }
- if (autoExpand) {
- setShowOutput(true);
- }
- }, [autoExpand, hasExpandableContent]);
-
const handleToggleOutput = useCallback(() => {
- setShowOutput((prev) => {
- const next = !prev;
- if (next) {
- onExpand?.();
- }
- return next;
- });
- }, [onExpand]);
+ setExpanded(!showOutput);
+ if (!showOutput) {
+ onExpand?.();
+ }
+ }, [onExpand, setExpanded, showOutput]);
return (
<div>
diff --git a/client/src/components/Chat/Messages/Content/ToolCall.tsx b/client/src/components/Chat/Messages/Content/ToolCall.tsx
index e92c1b6186..23fbbe9af9 100644
--- a/client/src/components/Chat/Messages/Content/ToolCall.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolCall.tsx
@@ -1,5 +1,4 @@
-import React, { useMemo, useState, useEffect, useCallback } from 'react';
-import { useRecoilValue } from 'recoil';
+import React, { useMemo, useState, useEffect, useContext, useCallback } from 'react';
import { Button } from '@librechat/client';
import {
Constants,
@@ -9,6 +8,7 @@ import {
splitToolCallName,
} from 'librechat-data-provider';
import type { TAttachment, PartMetadata } from 'librechat-data-provider';
+import { toolPanelSpacingClassName, useToolExpansion, SoleToolContext } from './disclosure';
import { useLocalize, useProgress, useExpandCollapse, useLazyCollapseBody } from '~/hooks';
import { cn, getToolDisplayLabel, logger, openInNewTab } from '~/utils';
import { isToolCallPreparing, useToolPreparation } from './preparation';
@@ -16,7 +16,6 @@ import { ToolIcon, getToolIconType, isError } from './ToolOutput';
import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';
import { resolveToolCallPhase } from '~/utils/toolCallPhase';
import { MCPAppViews } from '~/components/MCPUIResource';
-import { toolPanelSpacingClassName } from './disclosure';
import { useToolCallIntent } from './Parts/intent';
import { AttachmentGroup } from './Parts';
import ToolCallInfo from './ToolCallInfo';
@@ -24,7 +23,6 @@ import ProgressText from './ProgressText';
import { TOOL_ROW_CLASSES } from './rows';
import { ToolAuthWarning } from './auth';
import { firstErrorLine } from './live';
-import store from '~/store';
export default function ToolCall({
initialProgress = 0.1,
@@ -66,17 +64,6 @@ export default function ToolCall({
const localize = useLocalize();
const [oauthError, setOAuthError] = useState<string | null>(null);
const [oauthBinding, setOAuthBinding] = useState<'pending' | 'bound' | 'failed'>('pending');
- const autoExpand = useRecoilValue(store.autoExpandTools);
- const hasOutput = (output?.length ?? 0) > 0;
- const [showInfo, setShowInfo] = useState(() => autoExpand && hasOutput);
- const { style: expandStyle, ref: expandRef } = useExpandCollapse(showInfo);
- const { shouldRenderBody, mountBody, handleTransitionEnd } = useLazyCollapseBody(showInfo);
-
- useEffect(() => {
- if (autoExpand && hasOutput) {
- setShowInfo(true);
- }
- }, [autoExpand, hasOutput]);
const parsedAuthUrl = useMemo(() => {
if (!auth) {
@@ -203,6 +190,12 @@ export default function ToolCall({
() => (args?.length ?? 0) > 0 || (output?.length ?? 0) > 0,
[args, output],
);
+ /** The preference opens a card once it has output; a sole call opens on
+ * its arguments too, so a call that returned nothing still shows them. */
+ const soleTool = useContext(SoleToolContext) === true;
+ const [showInfo, setShowInfo] = useToolExpansion(soleTool ? hasInfo : (output?.length ?? 0) > 0);
+ const { style: expandStyle, ref: expandRef } = useExpandCollapse(showInfo);
+ const { shouldRenderBody, mountBody, handleTransitionEnd } = useLazyCollapseBody(showInfo);
const authDomain = useMemo(() => {
return parsedAuthUrl?.hostname ?? '';
@@ -299,8 +292,8 @@ export default function ToolCall({
if (!showInfo) {
onExpand?.();
}
- setShowInfo((prev) => !prev);
- }, [mountBody, onExpand, showInfo]);
+ setShowInfo(!showInfo);
+ }, [mountBody, onExpand, setShowInfo, showInfo]);
/** A failed row spends its subtitle on the error's first line: what went
* wrong is the fact the reader needs from that slot, ahead of which server
diff --git a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
index 9310f800ad..5f85df97c1 100644
--- a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
@@ -1,4 +1,4 @@
-import { useState, useRef, useMemo, useEffect, useCallback } from 'react';
+import { useState, useRef, useMemo, useEffect, useContext, useCallback } from 'react';
import { useRecoilValue } from 'recoil';
import { Tools, Constants, ContentTypes } from 'librechat-data-provider';
import { ChevronDown, ListChecks, MessageCircleQuestion, Users } from 'lucide-react';
@@ -29,6 +29,7 @@ import { getOutcomeStatus, summarizeSpan } from './outcome';
import { FOLD_RAIL_CLASSES, ROW_GLYPH_SLOT } from './rows';
import { MCPAppViews } from '~/components/MCPUIResource';
import { StackedToolIcons } from './ToolOutput';
+import { SoleToolContext } from './disclosure';
import { mapAttachments } from '~/utils/map';
import { getSourceDomains } from './sources';
import SearchVerticals from './verticals';
@@ -111,6 +112,7 @@ export default function ToolCallGroup({
return parts.map(({ part }) => summary.metaOf(part)).filter((m): m is ToolMeta => m != null);
}, [parts, attachmentsByToolCallId]);
const count = toolMetadata.length;
+ const phaseSole = useContext(SoleToolContext);
/** Approval state is read from the RAW parts, not `toolMetadata`: a pending
* call can be nested inside a subagent's content, which never surfaces as
* a tool entry here. */
@@ -621,54 +623,57 @@ export default function ToolCallGroup({
<div className={cn('overflow-hidden', FOLD_RAIL_CLASSES)} ref={expandRef}>
<ToolAuthWarningContext.Provider value>
<FailedRevealContext.Provider value={revealValue}>
- <div className="flex flex-col py-0.5">
- {parts.map(({ part, idx }, partIndex) => {
- 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`, which `Part`
- * renders as a `ReasoningMarker`. `ReasoningCompact` has
- * no text to show and returns 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) {
- return renderPart(
- part,
- idx,
- isLast && idx === lastContentIdx,
- handleToolExpand,
+ <SoleToolContext.Provider value={phaseSole ?? count === 1}>
+ <div className="flex flex-col py-0.5">
+ {parts.map(({ part, idx }, partIndex) => {
+ 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`, which `Part`
+ * renders as a `ReasoningMarker`. `ReasoningCompact` has
+ * no text to show and returns 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) {
+ return renderPart(
+ part,
+ idx,
+ isLast && idx === lastContentIdx,
+ handleToolExpand,
+ );
+ }
+ const streaming = isSubmitting && idx === lastContentIdx;
+ const isAfterTool =
+ partIndex > 0 &&
+ parts[partIndex - 1]?.part.type === ContentTypes.TOOL_CALL;
+ /** 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}
+ isAfterTool={isAfterTool}
+ isStreaming={streaming}
+ />
);
}
- const streaming = isSubmitting && idx === lastContentIdx;
- const isAfterTool =
- partIndex > 0 && parts[partIndex - 1]?.part.type === ContentTypes.TOOL_CALL;
- /** 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}
- isAfterTool={isAfterTool}
- isStreaming={streaming}
- />
+ return renderPart(
+ part,
+ idx,
+ isLast && idx === lastContentIdx,
+ handleToolExpand,
);
- }
- return renderPart(
- part,
- idx,
- isLast && idx === lastContentIdx,
- handleToolExpand,
- );
- })}
- </div>
+ })}
+ </div>
+ </SoleToolContext.Provider>
</FailedRevealContext.Provider>
</ToolAuthWarningContext.Provider>
{hasPendingAuthRequest && <ToolAuthWarning className="mt-2.5 mb-1" />}
diff --git a/client/src/components/Chat/Messages/Content/WebSearch.tsx b/client/src/components/Chat/Messages/Content/WebSearch.tsx
index 5db4c730fd..1a79a83a37 100644
--- a/client/src/components/Chat/Messages/Content/WebSearch.tsx
+++ b/client/src/components/Chat/Messages/Content/WebSearch.tsx
@@ -1,5 +1,4 @@
-import { useMemo, useState, useEffect } from 'react';
-import { useRecoilValue } from 'recoil';
+import { useMemo, useState } from 'react';
import { Tools } from 'librechat-data-provider';
import { Globe, ChevronDown, Info } from 'lucide-react';
import {
@@ -19,9 +18,9 @@ import type {
} from 'librechat-data-provider';
import { FaviconImage, getCleanDomain } from '~/components/Web/SourceHovercard';
import { useLocalize, useExpandCollapse, useLazyCollapseBody } from '~/hooks';
+import { toolPanelSpacingClassName, useToolExpansion } from './disclosure';
import { collectSources, getUniqueDomainSources } from './sources';
import { StackedFavicons } from '~/components/Web/Sources';
-import { toolPanelSpacingClassName } from './disclosure';
import { isError } from './ToolOutput/OutputRenderer';
import parseJsonField from './Parts/parseJsonField';
import { useToolCallIntent } from './Parts/intent';
@@ -31,7 +30,6 @@ import SearchVerticals from './verticals';
import { ROW_GLYPH_SLOT } from './rows';
import ToolCall from './ToolCall';
import cn from '~/utils/cn';
-import store from '~/store';
type ProgressKeys =
| 'com_ui_web_searching'
@@ -204,28 +202,18 @@ export default function WebSearch({
}, [ownTurn, localize, showSources, finalizing, preparationText]);
const progressText = preparationText ?? intent ?? genericProgressText;
- const autoExpand = useRecoilValue(store.autoExpandTools);
const sourceCount = allSources.length;
const [showDetails, setShowDetails] = useState(false);
- const [showSourceList, setShowSourceList] = useState(() => autoExpand && sourceCount > 0);
+ const [showSourceList, setShowSourceList] = useToolExpansion(sourceCount > 0);
const { style: sourceExpandStyle, ref: sourceExpandRef } = useExpandCollapse(showSourceList);
const { shouldRenderBody, mountBody, handleTransitionEnd } = useLazyCollapseBody(showSourceList);
- useEffect(() => {
- if (autoExpand && sourceCount > 0) {
- setShowSourceList(true);
- }
- }, [autoExpand, sourceCount]);
-
const handleToggleSources = () => {
mountBody();
- setShowSourceList((prev) => {
- const next = !prev;
- if (next) {
- onExpand?.();
- }
- return next;
- });
+ setShowSourceList(!showSourceList);
+ if (!showSourceList) {
+ onExpand?.();
+ }
};
if (error && runStepStatus !== 'cancelled') {
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
index 63f12ca082..57de2e7167 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
@@ -128,6 +128,8 @@ jest.mock('../Part', () => {
const { useMessageContext } = jest.requireActual<typeof import('~/Providers/MessageContext')>(
'~/Providers/MessageContext',
);
+ const { SoleToolContext } = jest.requireActual<typeof import('../disclosure')>('../disclosure');
+ const { useContext } = jest.requireActual<typeof import('react')>('react');
return {
__esModule: true,
default: function MockPart({
@@ -140,10 +142,12 @@ jest.mock('../Part', () => {
isLast?: boolean;
}) {
const { partIndex } = useMessageContext();
+ const soleTool = useContext(SoleToolContext);
return (
<div
data-testid={`real-part-${part.type}`}
data-index={partIndex}
+ data-sole-tool={String(soleTool)}
data-show-cursor={String(showCursor === true)}
data-is-last={String(isLast === true)}
/>
@@ -585,6 +589,38 @@ describe('ContentParts — activity phase state', () => {
expect(finalPart).toHaveAttribute('data-index', '2');
});
+ it('opens the only tool call inside a phase, but not one of several', () => {
+ const tool = (id: string) =>
+ ({
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id, name: 'bash_tool', args: {}, output: 'ok' },
+ }) as unknown as TMessageContentParts;
+ const phase = (count: number) =>
+ ({
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: 'Ran the setup',
+ activity_label_type: 'phase',
+ activity_start_index: 0,
+ activity_end_index: count,
+ activity_count: count,
+ pending: false,
+ }) as unknown as TMessageContentParts;
+
+ const { unmount } = render(
+ <ContentParts {...baseProps} content={[tool('tool-1'), phase(1)]} />,
+ );
+ expect(screen.getByTestId(`real-part-${ContentTypes.TOOL_CALL}`)).toHaveAttribute(
+ 'data-sole-tool',
+ 'true',
+ );
+ unmount();
+
+ render(<ContentParts {...baseProps} content={[tool('tool-1'), tool('tool-2'), phase(2)]} />);
+ for (const part of screen.getAllByTestId(`real-part-${ContentTypes.TOOL_CALL}`)) {
+ expect(part).toHaveAttribute('data-sole-tool', 'false');
+ }
+ });
+
it('keeps a streaming cursor when a completed phase marker is the visible tail', () => {
const phase = {
type: ContentTypes.ACTIVITY_LABEL,
diff --git a/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx
index 62ad7759c0..e8bbcec37d 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx
@@ -1584,10 +1584,12 @@ describe('tool pane identity at finalization', () => {
const frame = setup();
const { container, rerender } = render(frame({ foldLiveActivity: true }));
fireEvent.click(within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0]);
- fireEvent.click(toggles(container)[0]);
+ /** The phase's only call opens with it, so the choice to record is closing it. */
expect(toggles(container)[0]).toHaveAttribute('aria-expanded', 'true');
+ fireEvent.click(toggles(container)[0]);
+ expect(toggles(container)[0]).toHaveAttribute('aria-expanded', 'false');
rerender(frame({ messageId: 'server-response', isSubmitting: false, foldLiveActivity: true }));
- expect(toggles(container)[0]).toHaveAttribute('aria-expanded', 'true');
+ expect(toggles(container)[0]).toHaveAttribute('aria-expanded', 'false');
});
it.each([
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx
index 836cdcecef..ef960ec963 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx
@@ -5,8 +5,10 @@ import { render, screen, waitFor, fireEvent } from '@testing-library/react';
import type { TStartupConfig } from 'librechat-data-provider';
import { MCPAppsPolicyProvider } from '~/Providers/MCPAppsPolicyContext';
import { ToolAuthWarningContext } from '../auth';
+import { SoleToolContext } from '../disclosure';
import ToolCall from '../ToolCall';
import { logger } from '~/utils';
+import store from '~/store';
// Mock dependencies
jest.mock('~/hooks', () => ({
@@ -983,3 +985,52 @@ describe('ToolCall failure fast path', () => {
expect(screen.getByTestId('subtitle')).toHaveTextContent('HTTP 429 from github.com');
});
});
+
+describe('ToolCall sole tool disclosure', () => {
+ it('opens the only call of a group when it returned no output but has arguments', () => {
+ const { container } = render(
+ <RecoilRoot>
+ <MCPAppsPolicyProvider
+ startupConfig={{ mcpApps: { enabled: true } } as TStartupConfig}
+ ready
+ userId="user-1"
+ >
+ <SoleToolContext.Provider value>
+ <ToolCall
+ args='{"query":"weather"}'
+ name="lookup"
+ output=""
+ initialProgress={1}
+ isSubmitting={false}
+ />
+ </SoleToolContext.Provider>
+ </MCPAppsPolicyProvider>
+ </RecoilRoot>,
+ );
+ const panel = container.querySelector('[style*="grid-template-rows"]') as HTMLElement;
+ expect(panel.style.gridTemplateRows).toBe('1fr');
+ expect(screen.getByTestId('tool-call-info')).toBeInTheDocument();
+ });
+
+ it('keeps the preference opening a call only once it has output', () => {
+ const { container } = render(
+ <RecoilRoot initializeState={({ set }) => set(store.autoExpandTools, true)}>
+ <MCPAppsPolicyProvider
+ startupConfig={{ mcpApps: { enabled: true } } as TStartupConfig}
+ ready
+ userId="user-1"
+ >
+ <ToolCall
+ args='{"query":"weather"}'
+ name="lookup"
+ output=""
+ initialProgress={1}
+ isSubmitting={false}
+ />
+ </MCPAppsPolicyProvider>
+ </RecoilRoot>,
+ );
+ const panel = container.querySelector('[style*="grid-template-rows"]') as HTMLElement;
+ expect(panel.style.gridTemplateRows).toBe('0fr');
+ });
+});
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 3d77d8e148..4003306021 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
@@ -3,6 +3,7 @@ import { RecoilRoot } from 'recoil';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import { Tools, Constants, ContentTypes, ToolCallTypes } from 'librechat-data-provider';
import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';
+import { SoleToolContext, useToolAutoExpand } from '../disclosure';
import { FailedRevealContext, useFailedReveal } from '../reveal';
import { scheduleMessageContentLayoutReconcile } from '~/hooks';
import ToolCallGroup from '../ToolCallGroup';
@@ -1517,3 +1518,43 @@ describe('legacy function preparation groups', () => {
expect(screen.getByRole('button', { name: /^Ran 2 actions/ })).toBeInTheDocument();
});
});
+
+describe('ToolCallGroup sole tool', () => {
+ function Probe({ idx }: { idx: number }) {
+ return <div data-testid={`probe-${idx}`}>{String(useToolAutoExpand())}</div>;
+ }
+ const props = (ids: string[]) =>
+ ({
+ parts: ids.map((id, idx) => ({ part: makePart(id), idx })),
+ isSubmitting: false,
+ isLast: false,
+ showThinking: false,
+ lastContentIdx: ids.length - 1,
+ renderPart: (_p: TMessageContentParts, idx: number) => <Probe key={idx} idx={idx} />,
+ }) satisfies React.ComponentProps<typeof ToolCallGroup>;
+
+ it('opens the only tool call inside the group by default', () => {
+ renderGroup(props(['only']));
+ fireEvent.click(screen.getByRole('button', { expanded: false }));
+ expect(screen.getByTestId('probe-0')).toHaveTextContent('true');
+ });
+
+ it('keeps a one-call group collapsed when its phase holds several calls', () => {
+ render(
+ <RecoilRoot>
+ <SoleToolContext.Provider value={false}>
+ <ToolCallGroup {...props(['only'])} />
+ </SoleToolContext.Provider>
+ </RecoilRoot>,
+ );
+ fireEvent.click(screen.getByRole('button', { expanded: false }));
+ expect(screen.getByTestId('probe-0')).toHaveTextContent('false');
+ });
+
+ it('leaves calls collapsed when the group holds more than one', () => {
+ renderGroup(props(['a', 'b']));
+ fireEvent.click(screen.getByRole('button', { expanded: false }));
+ expect(screen.getByTestId('probe-0')).toHaveTextContent('false');
+ expect(screen.getByTestId('probe-1')).toHaveTextContent('false');
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/disclosure.ts b/client/src/components/Chat/Messages/Content/disclosure.ts
index 1b1cb04130..cc7cba43aa 100644
--- a/client/src/components/Chat/Messages/Content/disclosure.ts
+++ b/client/src/components/Chat/Messages/Content/disclosure.ts
@@ -1,6 +1,8 @@
import { createContext, useContext, useMemo } from 'react';
-import { atom } from 'jotai';
+import { atom, useAtom } from 'jotai';
+import { useRecoilValue } from 'recoil';
import type { PrimitiveAtom } from 'jotai';
+import store from '~/store';
export type ReasoningDisclosures = Map<number, PrimitiveAtom<boolean | undefined>>;
@@ -52,3 +54,29 @@ export function useToolDisclosure() {
return disclosure;
}, [disclosures, key]);
}
+
+/** Set by a tool group or activity phase holding exactly one tool call: its
+ * header is already the summary, so a second collapsed row inside it adds a
+ * click without adding information. `undefined` means no enclosing phase has
+ * decided, so a group falls back to its own call count; a phase's decision
+ * wins over the groups inside it. */
+export const SoleToolContext = createContext<boolean | undefined>(undefined);
+
+/** Whether a tool card opens by default: the user's "auto-expand tools"
+ * preference, or being the only call inside its group. */
+export function useToolAutoExpand() {
+ const autoExpand = useRecoilValue(store.autoExpandTools);
+ const soleTool = useContext(SoleToolContext);
+ return autoExpand || soleTool === true;
+}
+
+/** A tool card's disclosure. The reader's explicit choice lives in the
+ * per-tool atom, so it survives the card remounting when a live batch
+ * regroups. Until they choose, the card follows `useToolAutoExpand` and
+ * closes again if a sole call's group gains a second call. */
+export function useToolExpansion(canExpand: boolean) {
+ const autoExpand = useToolAutoExpand();
+ const [override, setOverride] = useAtom(useToolDisclosure());
+ const expanded = override ?? (autoExpand && canExpand);
+ return [expanded, setOverride] as const;
+}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index b5aea22a9c..23d7e00198 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -1300,7 +1300,7 @@
"com_ui_collapse_summary": "Collapse Summary",
"com_ui_collapse_thoughts": "Collapse Thoughts",
"com_ui_command_exit_code": "exit code {{0}}",
- "com_ui_command_finished": "Finished running",
+ "com_ui_command_finished": "Ran command",
"com_ui_command_placeholder": "Optional: Enter a command for the prompt or name will be used",
"com_ui_command_terminated": "terminated by {{0}}",
"com_ui_command_timed_out": "timed out",
diff --git a/e2e/specs/mock/scenarios/tool-steps.spec.ts b/e2e/specs/mock/scenarios/tool-steps.spec.ts
index 09bd9e0963..c87ad5fa5e 100644
--- a/e2e/specs/mock/scenarios/tool-steps.spec.ts
+++ b/e2e/specs/mock/scenarios/tool-steps.spec.ts
@@ -22,8 +22,7 @@ const uniqueLabel = (prefix: string) =>
`${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
/** The code-execution card's status toggle; a slow run appends its duration to the name. */
-const toolCard = (page: Page) =>
- messagesView(page).getByRole('button', { name: /^Finished running/ });
+const toolCard = (page: Page) => messagesView(page).getByRole('button', { name: /^Ran command/ });
const toolOutput = (page: Page) => messagesView(page).getByText(TOOL_OUTPUT, { exact: true });
/** True when `first` sits before `second` in document order. */
@@ -66,4 +65,61 @@ test.describe('tool call steps', () => {
await page.reload({ timeout: 10_000 });
await expectOneToolCardBeforeReply(page, label);
});
+
+ test('a lone settled command opens its output without a click and reads Ran command @scenario:lone-tool-call-opens-and-reads-ran', async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ const label = uniqueLabel('lone');
+ await page.goto(NEW_CHAT_PATH, { timeout: 10_000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+ await enableCodeInterpreter(page);
+
+ const response = await sendMessageAndWaitForCompletion(page, `E2E_EXECUTE_CODE:${label}`);
+ expect(response.ok()).toBeTruthy();
+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeHidden({
+ timeout: 30_000,
+ });
+ await expect(toolCard(page)).toHaveCount(1, { timeout: 30_000 });
+ await expect(toolOutput(page)).toBeVisible();
+ });
+});
+
+test.describe('tool call groups', () => {
+ test.skip(({ isMobile }) => isMobile === true, 'composer MCP picker is desktop-only');
+
+ test('opening a group of two calls leaves each call collapsed @scenario:multi-call-group-keeps-calls-collapsed', async ({
+ page,
+ }) => {
+ test.setTimeout(120_000);
+ const label = uniqueLabel('pair');
+ await page.goto(NEW_CHAT_PATH, { timeout: 10_000 });
+ /** No `activityLabel` here, so the group keeps its generic "Ran 2 actions" header. */
+ await selectMockEndpoint(page, { label: 'Mock Provider D', model: 'mock-model-d' });
+ await page.getByRole('button', { name: 'Attach and tools' }).click();
+ const server = page
+ .getByRole('dialog', { name: 'Attach and tools' })
+ .getByRole('button', { name: /^E2E Memory\b/ });
+ await server.click();
+ await expect(server).toHaveAttribute('aria-pressed', 'true');
+ await page.keyboard.press('Escape');
+
+ const response = await sendMessageAndWaitForCompletion(page, `E2E_ACTIVITY_REPLY:${label}`, {
+ timeout: 60_000,
+ });
+ expect(response.ok()).toBeTruthy();
+ await expect(messagesView(page).getByText(`E2E activity reply done ${label}`)).toBeVisible({
+ timeout: 30_000,
+ });
+
+ const header = messagesView(page).getByRole('button', { name: /^Ran 2 actions/ });
+ await expect(header).toHaveAttribute('aria-expanded', 'false');
+ await header.click();
+ await expect(header).toHaveAttribute('aria-expanded', 'true');
+ const calls = messagesView(page).getByRole('button', { name: /^Ran remember_fact/ });
+ await expect(calls).toHaveCount(2);
+ for (const call of await calls.all()) {
+ await expect(call).toHaveAttribute('aria-expanded', 'false');
+ }
+ });
});