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: Preserve Tool Pane Choices Through Response Finalization (#16152)

lia-by-librechat[bot]9b497ac17e2b
diff --git a/client/src/components/Chat/Messages/Content/ContentParts.tsx b/client/src/components/Chat/Messages/Content/ContentParts.tsx
index cf7a27bbb4..70bd2ea46c 100644
--- a/client/src/components/Chat/Messages/Content/ContentParts.tsx
+++ b/client/src/components/Chat/Messages/Content/ContentParts.tsx
@@ -8,9 +8,9 @@ import type {
Agents,
} from 'librechat-data-provider';
import type { ReactNode, ReactElement } from 'react';
+import type { ReasoningDisclosures, ToolDisclosures } from './disclosure';
import type { ToolCallGroupExpansionState } from './ToolCallGroup';
import type { ActivityPhaseSegment } from '~/utils/activityLabels';
-import type { ReasoningDisclosures } from './disclosure';
import {
mapAttachments,
getPartKeyIndex,
@@ -19,6 +19,12 @@ import {
filterAttachmentsForPart,
groupSequentialToolCalls,
} from '~/utils';
+import {
+ ReasoningDisclosureContext,
+ reasoningDisclosure,
+ ToolDisclosureContext,
+ ToolDisclosureKeyContext,
+} from './disclosure';
import {
groupActivityPhases,
lastCursorContentIdx,
@@ -26,7 +32,6 @@ import {
} from '~/utils/activityLabels';
import WorkspaceChanges, { partitionWorkspaceChanges } from './Parts/WorkspaceChanges';
import { ParallelContentRenderer, type PartWithIndex } from './ParallelContent';
-import { ReasoningDisclosureContext, reasoningDisclosure } from './disclosure';
import { MediaContext, MessageContext, SearchContext } from '~/Providers';
import MemoryArtifacts, { hasMemoryArtifacts } from './MemoryArtifacts';
import { hasParallelLanes, parallelLaneGroups } from '~/utils/lanes';
@@ -175,20 +180,32 @@ const PartWithContext = memo(function PartWithContext({
* own a live part — otherwise a phase from minutes ago keeps its reasoning
* shimmering and its peek scrolling while later phases stream. */
const holdsCursor = isLastPart && isLast;
+ /** Position distinguishes provider-id reuse within a response. Neither the
+ * final-only stepId nor messageId belongs in the card's disclosure identity. */
+ const toolDisclosureKey =
+ part.type === ContentTypes.TOOL_CALL
+ ? JSON.stringify([
+ getPartAgentId(part) ?? '',
+ getToolCallId(part),
+ getPartKeyIndex(part, idx),
+ ])
+ : undefined;
return (
<MessageContext.Provider value={contextValue}>
- <Part
- part={part}
- attachments={partAttachments}
- isSubmitting={isSubmitting}
- key={`part-${messageId}-${getPartKeyIndex(part, idx)}`}
- isCreatedByUser={isCreatedByUser}
- isLast={holdsCursor}
- showCursor={holdsCursor}
- hideAttachments={hideAttachments}
- onToolExpand={onToolExpand}
- />
+ <ToolDisclosureKeyContext.Provider value={toolDisclosureKey}>
+ <Part
+ part={part}
+ attachments={partAttachments}
+ isSubmitting={isSubmitting}
+ key={`part-${messageId}-${getPartKeyIndex(part, idx)}`}
+ isCreatedByUser={isCreatedByUser}
+ isLast={holdsCursor}
+ showCursor={holdsCursor}
+ hideAttachments={hideAttachments}
+ onToolExpand={onToolExpand}
+ />
+ </ToolDisclosureKeyContext.Provider>
</MessageContext.Provider>
);
});
@@ -1174,7 +1191,30 @@ const ContentPartsBody = memo(function ContentPartsBody({
});
const ContentParts = memo(function ContentParts(props: ContentPartsProps) {
- const { attachments, messageId } = props;
+ const { attachments, messageId, conversationId } = props;
+ const toolState = useRef<{
+ messageId: string;
+ conversationId: string | null | undefined;
+ disclosures: ToolDisclosures;
+ } | null>(null);
+ const previous = toolState.current;
+ /** The optimistic assistant id ends in `_`. Finalization replaces it with
+ * the server id, not a new response. Ordinary sibling/conversation switches
+ * get a fresh map, even if a provider reuses the same tool-call ids. */
+ const finalizing =
+ previous?.messageId.endsWith('_') === true &&
+ !messageId.endsWith('_') &&
+ props.isLatestMessage === true;
+ if (
+ previous == null ||
+ previous.conversationId !== conversationId ||
+ (previous.messageId !== messageId && !finalizing)
+ ) {
+ toolState.current = { messageId, conversationId, disclosures: new Map() };
+ } else {
+ previous.messageId = messageId;
+ }
+ const toolDisclosures = toolState.current!.disclosures;
const reasoningState = useRef<{ messageId: string; disclosures: ReasoningDisclosures } | null>(
null,
);
@@ -1200,7 +1240,9 @@ const ContentParts = memo(function ContentParts(props: ContentPartsProps) {
return (
<MediaContext.Provider value={media}>
<ReasoningDisclosureContext.Provider value={reasoningDisclosures}>
- <ContentPartsBody {...props} />
+ <ToolDisclosureContext.Provider value={toolDisclosures}>
+ <ContentPartsBody {...props} />
+ </ToolDisclosureContext.Provider>
</ReasoningDisclosureContext.Provider>
</MediaContext.Provider>
);
diff --git a/client/src/components/Chat/Messages/Content/Parts/useToolCallState.ts b/client/src/components/Chat/Messages/Content/Parts/useToolCallState.ts
index fc5d53bc03..e1c76342e8 100644
--- a/client/src/components/Chat/Messages/Content/Parts/useToolCallState.ts
+++ b/client/src/components/Chat/Messages/Content/Parts/useToolCallState.ts
@@ -1,10 +1,12 @@
import { useState, useEffect, useCallback } from 'react';
+import { useAtom } from 'jotai';
import { useRecoilValue } from 'recoil';
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';
interface ToolCallState {
@@ -57,12 +59,14 @@ export default function useToolCallState({
const hasOutput = output.length > 0;
const hasContent = hasInput || hasOutput;
- const [showCode, setShowCode] = useState(() => autoExpand && hasContent);
+ const [expansionOverride, setExpansionOverride] = useAtom(useToolDisclosure());
+ const [defaultExpanded, setDefaultExpanded] = useState(() => autoExpand && hasContent);
+ const showCode = expansionOverride ?? defaultExpanded;
const { style: expandStyle, ref: expandRef } = useExpandCollapse(showCode);
useEffect(() => {
if (autoExpand && hasContent) {
- setShowCode(true);
+ setDefaultExpanded(true);
}
}, [autoExpand, hasContent]);
@@ -76,14 +80,12 @@ export default function useToolCallState({
*/
const rawProgress = useProgress(isClosed ? 1 : initialProgress);
const toggleCode = useCallback(() => {
- setShowCode((prev) => {
- const next = !prev;
- if (next) {
- onExpand?.();
- }
- return next;
- });
- }, [onExpand]);
+ const next = !showCode;
+ setExpansionOverride(next);
+ if (next) {
+ onExpand?.();
+ }
+ }, [onExpand, setExpansionOverride, showCode]);
/**
* One resolution; everything the card shows is a read of this value. The
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 4be9ce3c90..1faae36721 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
@@ -18,17 +18,12 @@ jest.mock('~/utils', () => ({
}));
jest.mock('~/Providers', () => {
- const react = jest.requireActual<typeof import('react')>('react');
return {
- MessageContext: {
- Provider: ({
- children,
- value,
- }: {
- children: React.ReactElement<{ idx?: number }>;
- value: { partIndex: number };
- }) => react.cloneElement(children, { idx: value.partIndex }),
- },
+ /** Use the real context: cloning the immediate child assumes Part has no
+ * intervening providers and does not exercise context propagation. */
+ MessageContext: jest.requireActual<typeof import('~/Providers/MessageContext')>(
+ '~/Providers/MessageContext',
+ ).MessageContext,
SearchContext: {
Provider: ({ children }: { children: React.ReactNode }) => <>{children}</>,
},
@@ -129,27 +124,33 @@ jest.mock('../Container', () => ({
),
}));
-jest.mock('../Part', () => ({
- __esModule: true,
- default: ({
- part,
- idx,
- showCursor,
- isLast,
- }: {
- part: TMessageContentParts;
- idx: number;
- showCursor?: boolean;
- isLast?: boolean;
- }) => (
- <div
- data-testid={`real-part-${part.type}`}
- data-index={idx}
- data-show-cursor={String(showCursor === true)}
- data-is-last={String(isLast === true)}
- />
- ),
-}));
+jest.mock('../Part', () => {
+ const { useMessageContext } = jest.requireActual<typeof import('~/Providers/MessageContext')>(
+ '~/Providers/MessageContext',
+ );
+ return {
+ __esModule: true,
+ default: function MockPart({
+ part,
+ showCursor,
+ isLast,
+ }: {
+ part: TMessageContentParts;
+ showCursor?: boolean;
+ isLast?: boolean;
+ }) {
+ const { partIndex } = useMessageContext();
+ return (
+ <div
+ data-testid={`real-part-${part.type}`}
+ data-index={partIndex}
+ data-show-cursor={String(showCursor === true)}
+ data-is-last={String(isLast === true)}
+ />
+ );
+ },
+ };
+});
jest.mock('../ParallelContent', () => ({
/** Invokes `renderResumeAttribution` per content index like the real
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 394e7acb66..2f2dcce2ec 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx
@@ -13,6 +13,7 @@ import type {
import { resolveAskUserQuestionPart } from '~/utils/approval';
import { sandboxStartingByToolCallId } from '~/store';
import ContentParts from '../ContentParts';
+import store from '~/store';
/**
* Parity between a live fold and the cards it unmounts.
@@ -1007,3 +1008,131 @@ describe('live disclosure ownership', () => {
expect(within(card).getAllByRole('button')[0]).toHaveAttribute('aria-expanded', 'true');
});
});
+
+describe('tool pane identity at finalization', () => {
+ const call = (id = 't1', extra: Record<string, unknown> = {}) =>
+ toPart(
+ {
+ name: 'bash_tool',
+ args: { command: 'printf hello' },
+ output: '',
+ ...extra,
+ },
+ id,
+ );
+
+ function setup(autoExpand = false) {
+ const client = new QueryClient();
+ const frame = (props: Partial<React.ComponentProps<typeof ContentParts>> = {}) => (
+ <QueryClientProvider client={client}>
+ <Provider>
+ <RecoilRoot initializeState={({ set }) => set(store.autoExpandTools, autoExpand)}>
+ <ContentParts
+ messageId="user-message_"
+ conversationId="c1"
+ content={[call()]}
+ isCreatedByUser={false}
+ isLast
+ isLatestMessage
+ isSubmitting
+ showThinking={false}
+ foldLiveActivity={false}
+ {...props}
+ />
+ </RecoilRoot>
+ </Provider>
+ </QueryClientProvider>
+ );
+ return frame;
+ }
+
+ const toggles = (container: HTMLElement) =>
+ Array.from(
+ container.querySelectorAll<HTMLButtonElement>('.progress-text-wrapper button[aria-expanded]'),
+ );
+
+ it.each(['completed', 'cancelled', 'failed'] as const)(
+ 'keeps the opened pane after %s and sparse content compaction',
+ async (status) => {
+ const frame = setup();
+ const { container, rerender } = render(frame({ content: [undefined, call()] }));
+ fireEvent.click(toggles(container)[0]);
+ expect(toggles(container)[0]).toHaveAttribute('aria-expanded', 'true');
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(container.querySelector('code.hljs span')).not.toBeNull();
+ rerender(
+ frame({
+ messageId: 'server-response',
+ isSubmitting: false,
+ content: [
+ {
+ ...call('t1', { output: 'hello', runStepStatus: status, stepId: 'final-step' }),
+ streamedIndex: 1,
+ },
+ ],
+ }),
+ );
+ expect(toggles(container)[0]).toHaveAttribute('aria-expanded', 'true');
+ await act(async () => {
+ await Promise.resolve();
+ });
+ expect(container.querySelector('code.hljs span')).not.toBeNull();
+ },
+ );
+
+ it('keeps an explicitly closed pane closed when auto-expand is enabled', () => {
+ const frame = setup(true);
+ const { container, rerender } = render(frame());
+ expect(toggles(container)[0]).toHaveAttribute('aria-expanded', 'true');
+ fireEvent.click(toggles(container)[0]);
+ rerender(frame({ messageId: 'server-response', isSubmitting: false }));
+ expect(toggles(container)[0]).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('keeps an untouched pane closed at completion', () => {
+ const frame = setup();
+ const { container, rerender } = render(frame());
+ rerender(frame({ messageId: 'server-response', isSubmitting: false }));
+ expect(toggles(container)[0]).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('keeps the tool choice when a live phase unwraps into settled content', () => {
+ 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]);
+ expect(toggles(container)[0]).toHaveAttribute('aria-expanded', 'true');
+ rerender(frame({ messageId: 'server-response', isSubmitting: false, foldLiveActivity: true }));
+ expect(toggles(container)[0]).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it.each([
+ { messageId: 'other-response', isSubmitting: false },
+ { messageId: 'regenerated-response_', isSubmitting: true },
+ { messageId: 'server-response', conversationId: 'c2', isSubmitting: false },
+ ])('does not leak the choice into another response: %j', (next) => {
+ const frame = setup();
+ const { container, rerender } = render(
+ frame({ messageId: 'server-response', isSubmitting: false }),
+ );
+ fireEvent.click(toggles(container)[0]);
+ rerender(frame(next));
+ expect(toggles(container)[0]).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('keeps repeated provider ids independent by content position', () => {
+ const frame = setup();
+ const content = [
+ call(),
+ { type: ContentTypes.TEXT, text: 'Between calls' } as TMessageContentParts,
+ call(),
+ ];
+ const { container, rerender } = render(frame({ content }));
+ fireEvent.click(toggles(container)[0]);
+ rerender(frame({ content, messageId: 'server-response', isSubmitting: false }));
+ expect(toggles(container)[0]).toHaveAttribute('aria-expanded', 'true');
+ expect(toggles(container)[1]).toHaveAttribute('aria-expanded', 'false');
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/disclosure.ts b/client/src/components/Chat/Messages/Content/disclosure.ts
index e4a546cc32..1b1cb04130 100644
--- a/client/src/components/Chat/Messages/Content/disclosure.ts
+++ b/client/src/components/Chat/Messages/Content/disclosure.ts
@@ -30,3 +30,25 @@ export function useReasoningDisclosure(index: number) {
/** Panel spacing is genuine feature layout, so it stays here. The chevron
* appearance lives in `@librechat/client` as `disclosureChevronVariants`. */
export const toolPanelSpacingClassName = 'mb-2 mt-0';
+
+export type ToolDisclosures = Map<string, PrimitiveAtom<boolean | undefined>>;
+
+/** Kept above part keys and activity layouts; never shared between message views. */
+export const ToolDisclosureContext = createContext<ToolDisclosures | null>(null);
+export const ToolDisclosureKeyContext = createContext<string | undefined>(undefined);
+
+export function useToolDisclosure() {
+ const disclosures = useContext(ToolDisclosureContext);
+ const key = useContext(ToolDisclosureKeyContext);
+ return useMemo(() => {
+ if (disclosures == null || key == null) {
+ return atom<boolean | undefined>(undefined);
+ }
+ let disclosure = disclosures.get(key);
+ if (disclosure == null) {
+ disclosure = atom<boolean | undefined>(undefined);
+ disclosures.set(key, disclosure);
+ }
+ return disclosure;
+ }, [disclosures, key]);
+}