Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🧰 feat: Unify Tool Activity, Reasoning, Search, and Agent Workflows (#14546)
Marco Berettac9d208ad3bb6
diff --git a/.github/workflows/codegraph-select.yml b/.github/workflows/codegraph-select.ymlindex e74a86e270..d76d673a8a 100644--- a/.github/workflows/codegraph-select.yml+++ b/.github/workflows/codegraph-select.yml@@ -59,7 +59,7 @@ jobs:RESP=$(curl -sS --fail-with-body -m 45 -H "Authorization: Bearer $TOKEN" \-H 'content-type: application/json' --data-binary @body.json "$URL/v1/select"); RC=$?if [ "$RC" -ne 0 ] || [ -z "$RESP" ] || ! echo "$RESP" | jq -e .selected >/dev/null 2>&1; then- note "_codegraph unavailable (curl exit $RC: ${RESP:0:120}); skipped — full CI runs as always_"+ note "_codegraph unavailable (curl exit $RC: ${RESP:0:120}); skipped, full CI runs as always_"exit 0fidiff --git a/api/server/controllers/agents/__tests__/callbacks.spec.js b/api/server/controllers/agents/__tests__/callbacks.spec.jsindex 34bab04619..1d76042381 100644--- a/api/server/controllers/agents/__tests__/callbacks.spec.js+++ b/api/server/controllers/agents/__tests__/callbacks.spec.js@@ -8,6 +8,7 @@ jest.mock('nanoid', () => ({jest.mock('@librechat/api', () => ({sendEvent: jest.fn(),writeAttachmentEvent: jest.fn(),+ createOwnedToolEndHandler: jest.fn((callback) => ({ handle: callback })),GenerationJobManager: {emitChunk: jest.fn(),},@@ -468,6 +469,73 @@ describe('createToolEndCallback', () => {artifactPromises = [];});+ it('preserves separate owners for final search artifacts with repeated tool-call IDs', async () => {+ const toolEndCallback = createToolEndCallback({ req, res, artifactPromises });+ for (const agentId of ['agent-a', 'agent-b']) {+ await toolEndCallback(+ {+ output: {+ tool_call_id: 'call_0',+ artifact: {+ [Tools.web_search]: {+ turn: 0,+ organic: [{ link: `https://example.com/${agentId}` }],+ },+ },+ },+ },+ { run_id: 'run456', thread_id: 'thread789', agent_id: agentId },+ );+ }+ const results = await Promise.all(artifactPromises);+ expect(+ results.map((attachment) => ({+ owner: attachment.agentId,+ link: attachment[Tools.web_search].organic[0].link,+ })),+ ).toEqual([+ { owner: 'agent-a', link: 'https://example.com/agent-a' },+ { owner: 'agent-b', link: 'https://example.com/agent-b' },+ ]);+ });++ it.each(['createToolEndCallback', 'createResponsesToolEndCallback'])(+ '%s preserves memory payloads and their execution owner',+ async (factoryName) => {+ const toolEndCallback = require('../callbacks')[factoryName]({ req, res, artifactPromises });+ await toolEndCallback(+ {+ output: {+ tool_call_id: 'call_0',+ artifact: {+ [Tools.memory]: {+ key: 'project',+ type: 'update',+ value: 'owned',+ },+ },+ },+ },+ {+ run_id: 'run456',+ thread_id: 'thread789',+ agent_id: 'outer-agent',+ executingAgentId: 'agent-a',+ stepId: 'step-memory-1',+ },+ );++ const [attachment] = await Promise.all(artifactPromises);+ expect(attachment).toMatchObject({+ type: Tools.memory,+ toolCallId: 'call_0',+ agentId: 'agent-a',+ stepId: 'step-memory-1',+ [Tools.memory]: { key: 'project', type: 'update', value: 'owned' },+ });+ },+ );+describe('ui_resources artifact handling', () => {it('should process ui_resources artifact and return attachment when headers not sent', async () => {const toolEndCallback = createToolEndCallback({ req, res, artifactPromises });diff --git a/api/server/controllers/agents/__tests__/openai.spec.js b/api/server/controllers/agents/__tests__/openai.spec.jsindex 90fdabe516..8c8960b2d5 100644--- a/api/server/controllers/agents/__tests__/openai.spec.js+++ b/api/server/controllers/agents/__tests__/openai.spec.js@@ -194,6 +194,9 @@ jest.mock('@librechat/api', () => ({* export or the call throws before the assertions run. */stripActivityLabelParts: jest.fn((payload) => payload),writeSSE: jest.fn(),+ createOwnedToolEndHandler: jest.fn(+ (...args) => new (require('@librechat/agents').ToolEndHandler)(...args),+ ),createRun: jest.fn().mockResolvedValue({processStream: mockProcessStream,}),diff --git a/api/server/controllers/agents/__tests__/responses.unit.spec.js b/api/server/controllers/agents/__tests__/responses.unit.spec.jsindex 584b4c8e56..5ea0d8628a 100644--- a/api/server/controllers/agents/__tests__/responses.unit.spec.js+++ b/api/server/controllers/agents/__tests__/responses.unit.spec.js@@ -203,6 +203,9 @@ jest.mock('@librechat/api', () => ({* before SDK formatting; the mock must expose it like any other used* export or the call throws before the assertions run. */stripActivityLabelParts: jest.fn((payload) => payload),+ createOwnedToolEndHandler: jest.fn(+ (...args) => new (require('@librechat/agents').ToolEndHandler)(...args),+ ),collectReachableAgents: (roots) => {const agents = [];const pending = [...roots];diff --git a/api/server/controllers/agents/callbacks.js b/api/server/controllers/agents/callbacks.jsindex c97a196aad..89db7e4509 100644--- a/api/server/controllers/agents/callbacks.js+++ b/api/server/controllers/agents/callbacks.js@@ -13,7 +13,6 @@ const {const {GraphEvents,GraphNodeKeys,- ToolEndHandler,createContentAggregator,summarizeEvent,} = require('@librechat/agents');@@ -23,6 +22,7 @@ const {GenerationJobManager,writeAttachmentEvent,createToolExecuteHandler,+ createOwnedToolEndHandler,createBackgroundCodeResultHandler: createCodeHarvestHandler,HOST_FILE_AUTHORING_ARTIFACT_KEY,isCodeSessionToolName,@@ -42,6 +42,15 @@ function isCodeArtifactToolOutput(output) {return isCodeSessionToolName(output.name) || isHostFileAuthoringArtifact(output.artifact);}+function getAttachmentOwnership(metadata) {+ const agentId = metadata?.executingAgentId ?? metadata?.agentId ?? metadata?.agent_id;+ const stepId = metadata?.stepId;+ return {+ ...(typeof agentId === 'string' && agentId.length > 0 ? { agentId } : {}),+ ...(typeof stepId === 'string' && stepId.length > 0 ? { stepId } : {}),+ };+}+function addStatefulWorkspaceChange(attachment, artifact, executionProfile) {if (!attachment || executionProfile !== 'stateful' || !isHostFileAuthoringArtifact(artifact)) {return attachment;@@ -506,7 +515,7 @@ function getDefaultHandlers({collectedThoughtSignatures,emitTokenUsage,),- [GraphEvents.TOOL_END]: new ToolEndHandler(toolEndCallback, logger),+ [GraphEvents.TOOL_END]: createOwnedToolEndHandler(toolEndCallback, logger),[GraphEvents.ON_RUN_STEP]: {/*** Handle ON_RUN_STEP event.@@ -785,6 +794,23 @@ function getDefaultHandlers({handlers[GraphEvents.ON_SUMMARIZE_COMPLETE] = {handle: async (_event, data) => {aggregateContent({ event: GraphEvents.ON_SUMMARIZE_COMPLETE, data });+ /**+ * Stamped onto the aggregated part for the same reason as+ * `runStepStatus` above: an errored round keeps whatever deltas it+ * already streamed, and the SDK's aggregator ignores a complete event+ * that carries no `summary`, so nothing records the failure. Without+ * this the flag exists only on the live client message and a reload+ * re-renders the truncated text under "Conversation summarized".+ * Resolved through `stepMap` only, so a missing step degrades to the+ * old behavior rather than marking an unrelated part.+ */+ if (data?.error && contentParts) {+ const index = stepMap?.get(data?.id)?.index;+ const part = typeof index === 'number' ? contentParts[index] : undefined;+ if (part?.type === ContentTypes.SUMMARY) {+ part.failed = true;+ }+ }await emitForJob({event: GraphEvents.ON_SUMMARIZE_COMPLETE,data,@@ -987,6 +1013,7 @@ function createToolEndCallback({ req, res, artifactPromises, streamId = null, jo(async () => {const attachment = {type: Tools.web_search,+ ...getAttachmentOwnership(metadata),messageId: metadata.run_id,toolCallId: output.tool_call_id,conversationId: metadata.thread_id,@@ -1009,6 +1036,7 @@ function createToolEndCallback({ req, res, artifactPromises, streamId = null, jo(async () => {const attachment = {type: Tools.memory,+ ...getAttachmentOwnership(metadata),messageId: metadata.run_id,toolCallId: output.tool_call_id,conversationId: metadata.thread_id,@@ -1350,6 +1378,7 @@ function createResponsesToolEndCallback({ req, res, tracker, artifactPromises })const attachment = {type: Tools.web_search,toolCallId: output.tool_call_id,+ ...getAttachmentOwnership(metadata),[Tools.web_search]: { ...output.artifact[Tools.web_search] },};// For Responses API, always emit attachment during streaming@@ -1364,6 +1393,26 @@ function createResponsesToolEndCallback({ req, res, tracker, artifactPromises }));}+ if (output.artifact[Tools.memory]) {+ artifactPromises.push(+ (async () => {+ const attachment = {+ type: Tools.memory,+ toolCallId: output.tool_call_id,+ ...getAttachmentOwnership(metadata),+ [Tools.memory]: output.artifact[Tools.memory],+ };+ if (res.headersSent && !res.writableEnded) {+ writeResponsesAttachment(res, tracker, attachment, metadata);+ }+ return attachment;+ })().catch((error) => {+ logger.error('Error processing memory artifact content:', error);+ return null;+ }),+ );+ }+if (output.artifact.content) {/** @type {FormattedContent[]} */const content = output.artifact.content;diff --git a/api/server/controllers/agents/openai.js b/api/server/controllers/agents/openai.jsindex b57cce7493..de275905ad 100644--- a/api/server/controllers/agents/openai.js+++ b/api/server/controllers/agents/openai.js@@ -1,6 +1,6 @@const { nanoid } = require('nanoid');const { logger } = require('@librechat/data-schemas');-const { Callback, ToolEndHandler, formatAgentMessages } = require('@librechat/agents');+const { Callback, formatAgentMessages } = require('@librechat/agents');const {EModelEndpoint,ResourceType,@@ -56,6 +56,7 @@ const {getUserFacingProviderError,getRemoteAgentPermissions,createToolExecuteHandler,+ createOwnedToolEndHandler,buildNonStreamingResponse,createOpenAIStreamTracker,resolveAgentScopedSkillIds,@@ -1001,7 +1002,7 @@ const executeOpenAIChatCompletion = async (envelope, { req, res }) => {},on_run_step_completed: createHandler(),// Use proper ToolEndHandler for processing artifacts (images, file citations, code output)- on_tool_end: new ToolEndHandler(toolEndCallback, logger),+ on_tool_end: createOwnedToolEndHandler(toolEndCallback, logger),on_chain_stream: createHandler(),on_chain_end: createHandler(),on_agent_update: createHandler(),diff --git a/api/server/controllers/agents/responses.js b/api/server/controllers/agents/responses.jsindex 4903abf569..c3632f89c6 100644--- a/api/server/controllers/agents/responses.js+++ b/api/server/controllers/agents/responses.js@@ -1,7 +1,7 @@const { nanoid } = require('nanoid');const { v4: uuidv4 } = require('uuid');const { logger } = require('@librechat/data-schemas');-const { Callback, ToolEndHandler, formatAgentMessages } = require('@librechat/agents');+const { Callback, formatAgentMessages } = require('@librechat/agents');const {EModelEndpoint,ResourceType,@@ -53,6 +53,7 @@ const {getSafeErrorMetadata,getUserFacingProviderError,createToolExecuteHandler,+ createOwnedToolEndHandler,resolveRecursionLimit,getRemoteAgentPermissions,resolveAgentScopedSkillIds,@@ -1155,7 +1156,7 @@ const executeResponse = async (envelope, { req, res }) => {}},},- on_tool_end: new ToolEndHandler(toolEndCallback, logger),+ on_tool_end: createOwnedToolEndHandler(toolEndCallback, logger),on_run_step_completed: { handle: () => {} },on_chain_stream: { handle: () => {} },on_chain_end: { handle: () => {} },@@ -1368,7 +1369,7 @@ const executeResponse = async (envelope, { req, res }) => {}},},- on_tool_end: new ToolEndHandler(toolEndCallback, logger),+ on_tool_end: createOwnedToolEndHandler(toolEndCallback, logger),on_run_step_completed: { handle: () => {} },on_chain_stream: { handle: () => {} },on_chain_end: { handle: () => {} },diff --git a/api/server/routes/agents/__tests__/responses.spec.js b/api/server/routes/agents/__tests__/responses.spec.jsindex 4d83219b84..cddeaf95b7 100644--- a/api/server/routes/agents/__tests__/responses.spec.js+++ b/api/server/routes/agents/__tests__/responses.spec.js@@ -4,6 +4,9 @@* Tests the /v1/responses endpoint against the Open Responses specification* compliance tests. Uses real Anthropic API for LLM calls.*+ * Run with:+ * NODE_OPTIONS=--experimental-vm-modules RUN_RESPONSES_LIVE_TESTS=1 npx jest responses.spec --runInBand+ ** @see https://openresponses.org/specification* @see https://github.com/openresponses/openresponses/blob/main/src/lib/compliance-tests.ts*/@@ -19,11 +22,10 @@ const originalEnv = {process.env.CREDS_KEY = '0123456789abcdef0123456789abcdef';process.env.CREDS_IV = '0123456789abcdef';-/** Skip tests if ANTHROPIC_API_KEY is not available */-const SKIP_INTEGRATION_TESTS = !process.env.ANTHROPIC_API_KEY;-if (SKIP_INTEGRATION_TESTS) {- console.warn('ANTHROPIC_API_KEY not found - skipping integration tests');-}+const shouldRunLive =+ process.env.RUN_RESPONSES_LIVE_TESTS === '1' &&+ process.env.ANTHROPIC_API_KEY != null &&+ process.env.ANTHROPIC_API_KEY !== '';jest.mock('meilisearch', () => ({MeiliSearch: jest.fn().mockImplementation(() => ({@@ -69,9 +71,13 @@ jest.mock('~/app/clients/tools', () => ({jest.mock('~/config', () => ({createMCPServersRegistry: jest.fn(),+ getMCPServersRegistry: jest.fn().mockReturnValue({+ ensureConfigServers: jest.fn().mockResolvedValue({}),+ }),createMCPManager: jest.fn().mockResolvedValue({getAppToolFunctions: jest.fn().mockResolvedValue({}),}),+ getMCPManager: jest.fn().mockReturnValue({}),}));const express = require('express');@@ -369,9 +375,9 @@ async function createThinkingAgent(overrides = {}) {});}-const describeWithApiKey = SKIP_INTEGRATION_TESTS ? describe.skip : describe;+const describeIfLive = shouldRunLive ? describe : describe.skip;-describeWithApiKey('Open Responses API Integration Tests', () => {+describeIfLive('Open Responses API Integration Tests', () => {// Increase timeout for real API callsjest.setTimeout(120000);diff --git a/api/server/services/Tools/search.js b/api/server/services/Tools/search.jsindex c6e031e9ee..e0ded1268b 100644--- a/api/server/services/Tools/search.js+++ b/api/server/services/Tools/search.js@@ -34,6 +34,8 @@ function createOnSearchResults(res, streamId = null, jobCreatedAt) {sourceMap: new Map(),searchResultData: undefined,toolCallId: undefined,+ agentId: undefined,+ stepId: undefined,attachmentName: undefined,messageId: undefined,conversationId: undefined,@@ -83,6 +85,8 @@ function createOnSearchResults(res, streamId = null, jobCreatedAt) {}context.toolCallId = runnableConfig.toolCall.id;+ context.agentId = runnableConfig.metadata.agent_id ?? runnableConfig.metadata.agentId;+ context.stepId = runnableConfig.toolCall?.stepId;context.messageId = runnableConfig.metadata.run_id;context.conversationId = runnableConfig.metadata.thread_id;context.attachmentName = `${runnableConfig.toolCall.name}_${context.toolCallId}_${nanoid()}`;@@ -132,6 +136,8 @@ function buildAttachment(context) {return {messageId: context.messageId,toolCallId: context.toolCallId,+ agentId: context.agentId,+ stepId: context.stepId,conversationId: context.conversationId,name: context.attachmentName,type: Tools.web_search,diff --git a/api/server/services/Tools/search.spec.js b/api/server/services/Tools/search.spec.jsindex 8925d84062..adb864ab7b 100644--- a/api/server/services/Tools/search.spec.js+++ b/api/server/services/Tools/search.spec.js@@ -28,6 +28,7 @@ describe('createOnSearchResults', () => {toolCall: {id: 'tool-call-1',name: 'web_search',+ stepId: 'step-search-1',turn: 0,},};@@ -53,6 +54,7 @@ describe('createOnSearchResults', () => {data: expect.objectContaining({messageId: 'response-1',toolCallId: 'tool-call-1',+ stepId: 'step-search-1',conversationId: 'conversation-1',}),},@@ -60,4 +62,35 @@ describe('createOnSearchResults', () => {]);}});++ it('keeps repeated search calls owned by their handoff agent through highlights', () => {+ const snapshots = [];+ const res = {+ headersSent: true,+ write: (event) => snapshots.push(JSON.parse(event.split('\ndata: ')[1])),+ };+ for (const agentId of ['agent-a', 'agent-b']) {+ const callbacks = createOnSearchResults(res);+ callbacks.onSearchResults(+ {+ success: true,+ data: { organic: [{ link: `https://example.com/${agentId}` }], topStories: [] },+ },+ {+ metadata: { agent_id: agentId, run_id: 'response-1', thread_id: 'conversation-1' },+ toolCall: { id: 'call_0', name: 'web_search', turn: 0 },+ },+ );+ callbacks.onGetHighlights(`https://example.com/${agentId}`);+ }++ expect(snapshots.map(({ agentId }) => agentId)).toEqual([+ 'agent-a',+ 'agent-a',+ 'agent-b',+ 'agent-b',+ ]);+ expect(snapshots[1].web_search.organic[0].processed).toBe(true);+ expect(snapshots[3].web_search.organic[0].processed).toBe(true);+ });});diff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsxindex c0bceec1b8..7647e99bea 100644--- a/client/src/components/Chat/ChatView.tsx+++ b/client/src/components/Chat/ChatView.tsx@@ -17,6 +17,7 @@ import {import { ChatContext, AddedChatContext, ChatFormProvider, useFileMapContext } from '~/Providers';import ConversationStarters from './Input/ConversationStarters';import { useGetMessagesByConvoId } from '~/data-provider';+import { AskAnswerHostProvider } from './ask/state';import MessagesView from './Messages/MessagesView';import Presentation from './Presentation';import ChatForm from './Input/ChatForm';@@ -41,6 +42,7 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProjeconst localize = useLocalize();const rootSubmission = useRecoilValue(store.submissionByIndex(index));const isSubmitting = useRecoilValue(store.isSubmittingFamily(index));+ const saveDrafts = useRecoilValue(store.saveDrafts);const centerFormOnLanding = useRecoilValue(store.centerFormOnLanding);const methods = useForm<ChatFormValues>({@@ -126,58 +128,65 @@ function ChatView({ index = 0, project }: { index?: number; project?: TChatProjeconst isSubagentThreadReadOnly = activeSubagentThread != null;return (- <ChatFormProvider {...methods}>- <ChatContext.Provider value={chatHelpers}>- <AddedChatContext.Provider value={addedChatHelpers}>- <Presentation>- <div className="relative flex h-full w-full flex-col">- <h1 className="sr-only">{pageHeading}</h1>- <Header- parentConversationId={parentConversationId}- readOnly={isSubagentThreadReadOnly}- />- <>- <div- className={cn(- 'flex flex-col',- isLandingPage- ? 'flex-1 items-center justify-end sm:justify-center'- : 'h-full overflow-y-auto',- )}- >- {content}+ <AskAnswerHostProvider saveDrafts={saveDrafts}>+ <ChatFormProvider {...methods}>+ <ChatContext.Provider value={chatHelpers}>+ <AddedChatContext.Provider value={addedChatHelpers}>+ <Presentation>+ <div className="relative flex h-full w-full flex-col">+ <h1 className="sr-only">{pageHeading}</h1>+ <Header+ parentConversationId={parentConversationId}+ readOnly={isSubagentThreadReadOnly}+ />+ <><divclassName={cn(- 'w-full',- !isLandingPage && 'scrollbar-gutter-spacer',- isLandingPage && 'max-w-3xl transition-all duration-200 xl:max-w-4xl',+ 'flex flex-col',+ isLandingPage+ ? 'flex-1 items-center justify-end sm:justify-center'+ : 'h-full overflow-y-auto',)}>- {isLandingPage && <ConversationStarters />}- {isSubagentThreadReadOnly ? (- <div- className="mx-auto w-full max-w-3xl px-4 py-3 text-center text-sm text-text-secondary xl:max-w-4xl"- role="note"- >- {localize('com_ui_subagent_thread_read_only')}- </div>- ) : (- <ChatForm- index={index}- placeholder={chatFormPlaceholder}- project={isProjectLandingPage ? project : undefined}- />- )}- {!isLandingPage && <Footer />}+ {content}+ {/* Named + opaque so a view transition (the ask_user_question+ popover ⇄ chat-card morph) paints the whole composer band+ over the travelling card instead of letting it show+ through below the composer. The background matches the+ page, so normal rendering is unchanged. */}+ <div+ className={cn(+ 'w-full bg-presentation [view-transition-name:chat-form]',+ !isLandingPage && 'scrollbar-gutter-spacer',+ isLandingPage && 'max-w-3xl transition-all duration-200 xl:max-w-4xl',+ )}+ >+ {isLandingPage && <ConversationStarters />}+ {isSubagentThreadReadOnly ? (+ <div+ className="mx-auto w-full max-w-3xl px-4 py-3 text-center text-sm text-text-secondary xl:max-w-4xl"+ role="note"+ >+ {localize('com_ui_subagent_thread_read_only')}+ </div>+ ) : (+ <ChatForm+ index={index}+ placeholder={chatFormPlaceholder}+ project={isProjectLandingPage ? project : undefined}+ />+ )}+ {!isLandingPage && <Footer />}+ </div></div>- </div>- {isLandingPage && <Footer />}- </>- </div>- </Presentation>- </AddedChatContext.Provider>- </ChatContext.Provider>- </ChatFormProvider>+ {isLandingPage && <Footer />}+ </>+ </div>+ </Presentation>+ </AddedChatContext.Provider>+ </ChatContext.Provider>+ </ChatFormProvider>+ </AskAnswerHostProvider>);}diff --git a/client/src/components/Chat/Input/AskUserQuestionPopover.tsx b/client/src/components/Chat/Input/AskUserQuestionPopover.tsxindex 66c73e2654..1c967d48d0 100644--- a/client/src/components/Chat/Input/AskUserQuestionPopover.tsx+++ b/client/src/components/Chat/Input/AskUserQuestionPopover.tsx@@ -1,12 +1,12 @@import { memo, useEffect, useRef } from 'react';import { useWatch } from 'react-hook-form';-import { Button } from '@librechat/client';-import { Check, ChevronDown, CornerDownLeft, TriangleAlert, X } from 'lucide-react';+import { Button, TooltipAnchor } from '@librechat/client';+import { ChevronDown, CornerDownLeft, TriangleAlert } from 'lucide-react';import AskUserQuestions from '~/components/Chat/Messages/Content/AskUserQuestions';import useAskAnswerMode from '~/hooks/Input/useAskAnswerMode';+import AskOptions from '~/components/Chat/ask/options';import { useChatFormContext } from '~/Providers';import { useLocalize } from '~/hooks';-import { cn } from '~/utils';/*** Composer popover for a live `ask_user_question` pause. Single-select rows@@ -16,10 +16,10 @@ import { cn } from '~/utils';* Submit confirms —* folding in any free-form text typed in the composer, exactly like Enter* would. The footer hint is a button that focuses the composer — the- * free-form answer box. Collapse (chevron) hides the popover but keeps- * answer mode live via the chat card; × dismisses it entirely. Pure- * rendering off {@link useAskAnswerMode}; disappears the moment an answer- * submits from any surface, and locks while one is in flight.+ * free-form answer box. The chevron moves the question to the chat card and+ * releases the composer (the card's chevron moves it back). Pure rendering+ * off {@link useAskAnswerMode}; disappears the moment an answer submits from+ * any surface, and locks while one is in flight.*/function AskUserQuestionPopoverContent({conversationId,@@ -43,7 +43,7 @@ function AskUserQuestionPopoverContent({function AskUserQuestionsPopoverPanel({ ask }: { ask: ReturnType<typeof useAskAnswerMode> }) {const localize = useLocalize();- const { liveAsk, collapse, dismiss } = ask;+ const { liveAsk, collapse } = ask;const questions = liveAsk?.questions;if (liveAsk == null || questions == null || questions.length === 0) {return null;@@ -59,24 +59,21 @@ function AskUserQuestionsPopoverPanel({ ask }: { ask: ReturnType<typeof useAskAn{ 0: questions.length },)}</p>- <div className="flex items-center">- <button- type="button"- aria-label={localize('com_ui_collapse')}- className="rounded p-1 text-text-secondary hover:bg-surface-hover"- onClick={collapse}- >- <ChevronDown className="h-4 w-4" aria-hidden="true" />- </button>- <button- type="button"- aria-label={localize('com_ui_close')}- className="rounded p-1 text-text-secondary hover:bg-surface-hover"- onClick={dismiss}- >- <X className="h-4 w-4" aria-hidden="true" />- </button>- </div>+ <TooltipAnchor+ description={localize('com_ui_ask_move_to_chat')}+ side="top"+ render={+ <Button+ variant="ghost"+ size="icon"+ aria-label={localize('com_ui_ask_move_to_chat')}+ className="size-auto rounded-md p-1 text-text-secondary"+ onClick={collapse}+ >+ <ChevronDown className="size-4" aria-hidden="true" />+ </Button>+ }+ /></div><AskUserQuestions actionId={liveAsk.actionId} questions={questions} /></div>@@ -114,7 +111,6 @@ function AskUserQuestionPopoverPanel({submit,submitOption,skip,- dismiss,collapse,handlePopoverKeyDown,} = ask;@@ -156,7 +152,7 @@ function AskUserQuestionPopoverPanel({scroll region: the panel is absolutely positioned, so anything thatoverflows it is unreachable by page scroll. */}<div- className="popover border-token-border-light flex max-h-[60vh] flex-col rounded-2xl border bg-surface-primary-alt p-2 shadow-lg"+ className="popover border-token-border-light flex max-h-[60vh] flex-col rounded-2xl border bg-surface-primary-alt p-2 shadow-lg [view-transition-name:ask-question]"onKeyDown={handlePopoverKeyDown}><div className="flex shrink-0 items-start justify-between gap-2 p-2">@@ -170,64 +166,35 @@ function AskUserQuestionPopoverPanel({</p>)}</div>- <div className="flex items-center">- <button- type="button"- aria-label={localize('com_ui_collapse')}- className="rounded p-1 text-text-secondary hover:bg-surface-hover"- onClick={collapse}- >- <ChevronDown className="h-4 w-4" aria-hidden="true" />- </button>- <button- type="button"- aria-label={localize('com_ui_close')}- className="rounded p-1 text-text-secondary hover:bg-surface-hover"- onClick={dismiss}- >- <X className="h-4 w-4" aria-hidden="true" />- </button>- </div>- </div>- <div ref={listRef} className="relative min-h-0 flex-1 overflow-y-auto">- {options.map((option, index) => {- const isChecked = multiSelect && checked.includes(index);- return (+ {/* Single exit: moves the question to the chat card and hands the+ composer back for normal messages. */}+ <TooltipAnchor+ description={localize('com_ui_ask_move_to_chat')}+ side="top"+ render={<Button- key={option.value}- ref={(el) => {- optionRefs.current[index] = el;- }}- type="button"- size="sm"- variant="choice"- role={multiSelect ? 'checkbox' : undefined}- aria-checked={multiSelect ? isChecked : undefined}- disabled={locked}- /** Layout and the keyboard highlight are the only things the- * popover owns here — these rows are the same answer controls- * as the cards', so their appearance stays in the variant. */- className={cn(- 'mt-1 h-auto min-h-9 w-full justify-start gap-3 whitespace-normal p-2 text-left',- selected === index && 'bg-surface-active hover:bg-surface-active',- )}- onClick={() => (multiSelect ? toggleChecked(index) : submitOption(index))}+ variant="ghost"+ size="icon"+ aria-label={localize('com_ui_ask_move_to_chat')}+ className="size-auto rounded-md p-1 text-text-secondary"+ onClick={collapse}>- <span- className={cn(- 'flex h-5 w-5 shrink-0 items-center justify-center rounded text-xs',- isChecked- ? 'bg-surface-submit text-text-on-status'- : 'border border-border-xheavy text-text-secondary',- )}- >- {isChecked ? <Check className="h-3.5 w-3.5" aria-hidden="true" /> : index + 1}- </span>- <span className="min-w-0 flex-1 [overflow-wrap:anywhere]">{option.label}</span>+ <ChevronDown className="size-4" aria-hidden="true" /></Button>- );- })}+ }+ /></div>+ <AskOptions+ options={options}+ multiSelect={multiSelect}+ checked={checked}+ selected={selected}+ locked={locked}+ onActivate={(index) => (multiSelect ? toggleChecked(index) : submitOption(index))}+ optionRefs={optionRefs}+ listRef={listRef}+ className="relative min-h-0 flex-1 overflow-y-auto"+ />{/** A failed submission keeps the question answerable (controls stay* enabled), but the chat card that would show the error is hidden* while the popover is up — so surface it here for retry guidance. */}@@ -238,15 +205,19 @@ function AskUserQuestionPopoverPanel({</div>)}<div className="flex shrink-0 items-center justify-between gap-2 p-2">- <button- type="button"- className="text-xs italic text-text-secondary hover:text-text-primary hover:underline"+ {/* Shared primitive with the fill suppressed, the same way Summary's+ quiet text buttons compose it: this reads as a hint, not a+ control with a surface, but the focus ring and disabled handling+ should still come from the recipe. */}+ <Button+ variant="ghost"+ className="h-auto cursor-text rounded-md p-0 text-xs font-normal text-text-secondary hover:bg-transparent hover:text-text-primary"onClick={() => textAreaRef?.current?.focus()}>{options.length === 0? localize('com_ui_ask_type_below_only'): localize('com_ui_ask_type_below')}- </button>+ </Button><div className="flex items-center gap-2"><Button size="sm" variant="outline" disabled={locked} onClick={() => skip()}>{localize('com_ui_skip')}diff --git a/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx b/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsxindex f31f39b245..dd51f89f8f 100644--- a/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx+++ b/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx@@ -13,6 +13,7 @@ import {import useSmoothStreaming from '~/hooks/Messages/useSmoothStreaming';import { getActivityLabelText } from '~/utils/activityLabels';import { ROW_GLYPH_SLOT, TOOL_ROW_CLASSES } from './rows';+import SearchVerticals from './verticals';import { AttachmentGroup } from './Parts';import { cn } from '~/utils';@@ -285,9 +286,17 @@ export default function ActivityPhaseGroup({</span></div>) : null;+ /** `AttachmentGroup` drops `web_search` attachments, and the nested segment+ * renders with `hideAttachments` so its own `WebSearch` row stands down+ * for this hoist — so without `SearchVerticals` here a phase containing a+ * search would swallow its images, products and places instead of lifting+ * them out of the fold. Mirrors `ToolCallGroup`'s own hoist. */const media =attachments != null && attachments.length > 0 ? (- <AttachmentGroup attachments={attachments} />+ <>+ <SearchVerticals attachments={attachments} />+ <AttachmentGroup attachments={attachments} />+ </>) : null;if (!label) {return (diff --git a/client/src/components/Chat/Messages/Content/AgentHandoff.tsx b/client/src/components/Chat/Messages/Content/AgentHandoff.tsxindex 29a577eef8..b4c0004273 100644--- a/client/src/components/Chat/Messages/Content/AgentHandoff.tsx+++ b/client/src/components/Chat/Messages/Content/AgentHandoff.tsx@@ -1,8 +1,14 @@-import React, { useMemo, useState } from 'react';+import React, { useEffect, useId, useMemo, useRef, useState, useCallback } from 'react';+import copy from 'copy-to-clipboard';import { ChevronDown } from 'lucide-react';+import { Button } from '@librechat/client';import { EModelEndpoint, Constants } from 'librechat-data-provider';import type { TMessage } from 'librechat-data-provider';+import type { TranslationKeys } from '~/hooks';+import CopyButton from '~/components/Messages/Content/CopyButton';+import { unescapeJsonString } from './Parts/parseJsonField';import MessageIcon from '~/components/Share/MessageIcon';+import { toolPanelSpacingClassName } from './disclosure';import { useLocalize, useExpandCollapse } from '~/hooks';import { useAgentsMapContext } from '~/Providers';import { cn } from '~/utils';@@ -12,12 +18,103 @@ interface AgentHandoffProps {args: string | Record<string, unknown>;}+interface HandoffField {+ key?: string;+ value: string;+}++const PARTIAL_STRING_FIELD = /^\s*\{\s*"([^"\\]+)"\s*:\s*"((?:[^"\\]|\\.)*)/s;++function formatValue(value: unknown): string {+ if (typeof value === 'string') {+ return value.trim();+ }+ if (value == null) {+ return '';+ }+ if (typeof value === 'number' || typeof value === 'boolean' || typeof value === 'bigint') {+ return String(value);+ }+ try {+ return JSON.stringify(value, null, 2);+ } catch {+ return '';+ }+}++function fieldsFromRecord(record: Record<string, unknown>): HandoffField[] {+ return Object.entries(record).reduce<HandoffField[]>((fields, [key, rawValue]) => {+ const value = formatValue(rawValue);+ if (value) {+ fields.push({ key, value });+ }+ return fields;+ }, []);+}++function parseHandoffFields(args: string | Record<string, unknown>): HandoffField[] {+ if (typeof args !== 'string') {+ return fieldsFromRecord(args);+ }++ const trimmed = args.trim();+ if (!trimmed) {+ return [];+ }++ try {+ const parsed: unknown = JSON.parse(trimmed);+ if (typeof parsed === 'object' && parsed !== null && !Array.isArray(parsed)) {+ return fieldsFromRecord(parsed as Record<string, unknown>);+ }+ const value = formatValue(parsed);+ return value ? [{ value }] : [];+ } catch {+ const partialField = trimmed.match(PARTIAL_STRING_FIELD);+ if (partialField) {+ const value = unescapeJsonString(partialField[2]);+ return value ? [{ key: partialField[1], value }] : [];+ }+ return trimmed.startsWith('{') ? [] : [{ value: trimmed }];+ }+}++/**+ * The SDK's own prompt keys, which are the ones that carry product meaning.+ * Any other key is an admin-authored `promptKey` from the agent graph (see+ * `handoffPromptKeyCompatibility`), so it is author content with no+ * localization key to map to and is left as written, like an agent's own name.+ */+const HANDOFF_FIELD_LABELS: Record<string, TranslationKeys> = {+ instruction: 'com_ui_handoff_field_instructions',+ instructions: 'com_ui_handoff_field_instructions',+ context: 'com_ui_handoff_field_context',+};++function fieldLabel(key: string, localize: (translationKey: TranslationKeys) => string): string {+ const known = HANDOFF_FIELD_LABELS[key.toLowerCase()];+ if (known) {+ return localize(known);+ }+ const words = key+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')+ .replace(/[_-]+/g, ' ')+ .trim();+ return words ? words.charAt(0).toUpperCase() + words.slice(1) : key;+}+const AgentHandoff: React.FC<AgentHandoffProps> = ({ name, args: _args = '' }) => {const localize = useLocalize();const agentsMap = useAgentsMapContext();const [showInfo, setShowInfo] = useState(false);+ const [isCopied, setIsCopied] = useState(false);+ const copiedTimerRef = useRef<ReturnType<typeof setTimeout>>();+ const contentId = useId();+ const headingId = `${contentId}-heading`;const { style: expandStyle, ref: expandRef } = useExpandCollapse(showInfo);+ useEffect(() => () => clearTimeout(copiedTimerRef.current), []);+const targetAgentId = useMemo(() => {if (typeof name !== 'string' || !name.startsWith(Constants.LC_TRANSFER_TO_)) {return null;@@ -32,35 +129,48 @@ const AgentHandoff: React.FC<AgentHandoffProps> = ({ name, args: _args = '' }) =return agentsMap[targetAgentId];}, [agentsMap, targetAgentId]);- const args = useMemo(() => {- if (typeof _args === 'string') {- return _args;- }- try {- return JSON.stringify(_args, null, 2);- } catch {- return '';- }- }, [_args]) as string;+ const fields = useMemo(() => parseHandoffFields(_args), [_args]);+ const copyText = useMemo(+ () =>+ fields.length === 1+ ? fields[0].value+ : fields+ .map(({ key, value }) => `${key ? `${fieldLabel(key, localize)}\n` : ''}${value}`)+ .join('\n\n'),+ [fields, localize],+ );+ const hasInfo = fields.length > 0;+ const agentName = targetAgent?.name || localize('com_ui_agent');- const hasInfo = useMemo(() => (args?.trim()?.length ?? 0) > 2, [args]);+ /** `copy-to-clipboard` rather than `navigator.clipboard`, matching the other+ * message-content copy controls: the async API is undefined on a+ * non-secure origin (a LAN deployment served over http), where+ * dereferencing it throws before any rejection handler can run and the+ * button silently does nothing. */+ const handleCopy = useCallback(() => {+ if (!copy(copyText, { format: 'text/plain' })) {+ return;+ }+ clearTimeout(copiedTimerRef.current);+ setIsCopied(true);+ copiedTimerRef.current = setTimeout(() => setIsCopied(false), 2000);+ }, [copyText]);return (- <div className="my-1">- <button- type="button"+ <div className="my-2">+ <Button+ variant="ghost"className={cn(- 'tool-status-text flex appearance-none items-center gap-2 bg-transparent text-text-secondary',- hasInfo- ? 'transition-colors hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy'- : 'pointer-events-none',+ 'tool-status-text h-auto justify-start gap-2 rounded-none p-0 font-normal text-text-secondary hover:bg-transparent hover:text-text-primary',+ !hasInfo && 'pointer-events-none disabled:opacity-100',)}disabled={!hasInfo}onClick={hasInfo ? () => setShowInfo(!showInfo) : undefined}aria-expanded={hasInfo ? showInfo : undefined}- aria-label={`${localize('com_ui_transferred_to')} ${targetAgent?.name || localize('com_ui_agent')}`}+ aria-controls={hasInfo ? contentId : undefined}+ aria-label={`${localize('com_ui_transferred_to')} ${agentName}`}>- <div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full ring-1 ring-border-light">+ <div className="flex h-6 w-6 shrink-0 items-center justify-center overflow-hidden rounded-full ring-1 ring-border-light"><MessageIconmessage={{@@ -72,25 +182,67 @@ const AgentHandoff: React.FC<AgentHandoffProps> = ({ name, args: _args = '' }) =/></div><span className="select-none">{localize('com_ui_transferred_to')}</span>- <span className="select-none font-medium text-text-primary">- {targetAgent?.name || localize('com_ui_agent')}- </span>+ <span className="select-none font-medium text-text-primary">{agentName}</span>{hasInfo && (<ChevronDown- className={cn('ml-1 h-3 w-3 transition-transform', showInfo && 'rotate-180')}+ className={cn(+ 'size-4 shrink-0 translate-y-[1px] text-text-secondary transition-transform duration-200 ease-out',+ showInfo && 'rotate-180',+ )}aria-hidden="true"/>)}- </button>- <div style={expandStyle}>+ </Button>+ <div id={contentId} style={expandStyle} aria-hidden={!showInfo || undefined}><div className="overflow-hidden" ref={expandRef}>{hasInfo && (- <div className="ml-8 mt-2 rounded-lg border border-border-light bg-surface-secondary p-3 text-xs">- <div className="mb-1 font-medium text-text-secondary">- {localize('com_ui_handoff_instructions')}:+ <section+ aria-labelledby={headingId}+ className={cn(+ toolPanelSpacingClassName,+ 'group/handoff ml-8 max-w-3xl border-l-2 border-border-medium py-1 pl-4 pr-1',+ )}+ >+ <div className="mb-1.5 flex min-h-5 items-center justify-between gap-2">+ <span+ id={headingId}+ className="text-[11px] font-semibold uppercase tracking-wide text-text-secondary"+ >+ {localize('com_ui_handoff_instructions')}+ </span>+ <CopyButton+ isCopied={isCopied}+ iconOnly+ onClick={handleCopy}+ label={localize('com_ui_copy_to_clipboard')}+ copiedLabel={localize('com_ui_copied_to_clipboard')}+ /** Only the reveal-on-hover behavior is local; the icon+ * crossfade, tooltip, hover and focus ring come from the+ * shared primitive. */+ className="shrink-0 opacity-60 focus-visible:opacity-100 group-focus-within/handoff:opacity-100 group-hover/handoff:opacity-100"+ /></div>- <pre className="overflow-x-auto whitespace-pre-wrap text-text-primary">{args}</pre>- </div>+ {fields.length === 1 ? (+ <p className="whitespace-pre-wrap break-words text-sm leading-6 text-text-primary">+ {fields[0].value}+ </p>+ ) : (+ <dl className="space-y-3">+ {fields.map(({ key, value }, index) => (+ <div key={`${key ?? 'field'}-${index}`}>+ {key && (+ <dt className="mb-0.5 text-xs font-medium text-text-secondary">+ {fieldLabel(key, localize)}+ </dt>+ )}+ <dd className="whitespace-pre-wrap break-words text-sm leading-6 text-text-primary">+ {value}+ </dd>+ </div>+ ))}+ </dl>+ )}+ </section>)}</div></div>diff --git a/client/src/components/Chat/Messages/Content/ApprovalContext.tsx b/client/src/components/Chat/Messages/Content/ApprovalContext.tsxindex 6c0e2ee8ed..eb4ce6bf13 100644--- a/client/src/components/Chat/Messages/Content/ApprovalContext.tsx+++ b/client/src/components/Chat/Messages/Content/ApprovalContext.tsx@@ -1,49 +1,32 @@import { createContext, useCallback, useContext, useMemo, useRef, useState } from 'react';+import { useAtom } from 'jotai';+import { useRecoilValue } from 'recoil';import { Constants } from 'librechat-data-provider';-import { atom, useRecoilState, useRecoilValue } from 'recoil';import type { Agents } from 'librechat-data-provider';+import type { AskAnswerStatus } from '~/components/Chat/ask/state';import {useSubmitToolApprovalMutation,useSubmitAskAnswerMutation,type ResumeAgentFields,} from '~/data-provider';+import { askSubmitStatusAtom } from '~/components/Chat/ask/state';import { resolveAskUserQuestionPart } from '~/utils/approval';import { ChatContext } from '~/Providers/ChatContext';import { useGetEphemeralAgent } from '~/store/agents';import store from '~/store';-/** Per-action submission lifecycle, surfaced to the cards so they can disable- * controls and explain a terminal outcome. */-type ActionStatus = 'idle' | 'submitting' | 'submitted' | 'expired' | 'error';--/**- * Ask-answer submit status keyed by `actionId`. This lives in Recoil, NOT the- * {@link ApprovalContext} React state, because the PRIMARY answer surface is- * the composer in `ChatForm` — which renders OUTSIDE `ApprovalProvider` (that- * only wraps message content). A React context read there degrades to the- * inert {@link FALLBACK}, so an in-flight lock / expired status tracked in the- * context would never engage for the composer. A global atom is visible to- * both the composer (`useAskAnswerMode`) and the message-content card- * (`AskUserQuestion`), so a fast double-submit is actually blocked and a- * terminal (expired/error) state surfaces on either surface.- */-const askSubmitStatusAtom = atom<Record<string, ActionStatus>>({- key: 'askAnswerSubmitStatus',- default: {},-});-/** Shared read/write for the ask-answer submit status. */export function useAskSubmitStatus(): {- getAskStatus: (actionId: string) => ActionStatus;- setAskStatus: (actionId: string, status: ActionStatus) => void;+ getAskStatus: (actionId: string) => AskAnswerStatus;+ setAskStatus: (actionId: string, status: AskAnswerStatus) => void;} {- const [statusMap, setStatusMap] = useRecoilState(askSubmitStatusAtom);+ const [statusMap, setStatusMap] = useAtom(askSubmitStatusAtom);const getAskStatus = useCallback(- (actionId: string): ActionStatus => statusMap[actionId] ?? 'idle',+ (actionId: string): AskAnswerStatus => statusMap[actionId] ?? 'idle',[statusMap],);const setAskStatus = useCallback(- (actionId: string, status: ActionStatus) =>+ (actionId: string, status: AskAnswerStatus) =>setStatusMap((prev) => ({ ...prev, [actionId]: status })),[setStatusMap],);@@ -81,9 +64,9 @@ interface ApprovalContextValue {/** True once every registered tool_call in the action has a decision. */isReady: (actionId: string) => boolean;/** Lifecycle status for an action (so cards can disable / show messages). */- getStatus: (actionId: string) => ActionStatus;+ getStatus: (actionId: string) => AskAnswerStatus;/** Set an action's submission status (driven by the cards' submit via `useResumeSubmit`). */- setStatus: (actionId: string, status: ActionStatus) => void;+ setStatus: (actionId: string, status: AskAnswerStatus) => void;/** Restore a free-form question answer after transient phase-slice remounts. */getAskAnswerDraft: (actionId: string) => string;/** Retain a free-form question answer for this response message's lifetime. */@@ -145,7 +128,7 @@ export default function ApprovalProvider({ children }: { children: React.ReactNoconst askAnswerDraftsRef = useRef(new Map<string, string>());const [version, bump] = useState(0);const rerender = useCallback(() => bump((v) => v + 1), []);- const [statusByAction, setStatusByAction] = useState<Record<string, ActionStatus>>({});+ const [statusByAction, setStatusByAction] = useState<Record<string, AskAnswerStatus>>({});const registerToolCall = useCallback((actionId: string, toolCallId: string) => {@@ -238,11 +221,11 @@ export default function ApprovalProvider({ children }: { children: React.ReactNo}, []);const getStatus = useCallback(- (actionId: string): ActionStatus => statusByAction[actionId] ?? 'idle',+ (actionId: string): AskAnswerStatus => statusByAction[actionId] ?? 'idle',[statusByAction],);- const setStatus = useCallback((actionId: string, status: ActionStatus) => {+ const setStatus = useCallback((actionId: string, status: AskAnswerStatus) => {setStatusByAction((prev) => ({ ...prev, [actionId]: status }));}, []);@@ -319,7 +302,7 @@ export function useResumeSubmit() {* synchronous action-id guard alongside the rendered submission status. */const submittingToolActionIdsRef = useRef(new Set<string>());const submittingAskActionIdsRef = useRef(new Set<string>());- /** Ask status lives in Recoil so it works from the composer (outside the+ /** Ask status lives in Jotai so it works from the composer (outside the* provider); tool-approval status stays on the context. */const { setAskStatus } = useAskSubmitStatus();const activeGenerationCreatedAt = useRecoilValue(diff --git a/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx b/client/src/components/Chat/Messages/Content/AskUserQuestion.tsxindex a4d3ad1383..016872666c 100644--- a/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx+++ b/client/src/components/Chat/Messages/Content/AskUserQuestion.tsx@@ -1,13 +1,15 @@import { useContext, useMemo, useState } from 'react';-import { ChevronUp, TriangleAlert, X } from 'lucide-react';-import { Button, TextareaAutosize } from '@librechat/client';+import { Button, TextareaAutosize, TooltipAnchor } from '@librechat/client';+import { ChevronUp, MessageCircleQuestion, TriangleAlert } from 'lucide-react';import type { Agents } from 'librechat-data-provider';import { useApprovalContext, useAskSubmitStatus, useResumeSubmit } from './ApprovalContext';+import { splitOtherOption, ASK_USER_DECLINED_ANSWER } from '~/utils/approval';import useAskAnswerMode from '~/hooks/Input/useAskAnswerMode';+import AskOptions from '~/components/Chat/ask/options';import { ChatContext } from '~/Providers/ChatContext';-import { splitOtherOption } from '~/utils/approval';import AskUserQuestions from './AskUserQuestions';import { useLocalize } from '~/hooks';+import { cn } from '~/utils';/*** Renders an `ask_user_question` pause: the prompt, optional description, any@@ -40,7 +42,6 @@ export default function AskUserQuestion({questions={questions}className="my-2 max-h-[70vh] w-full rounded-lg border border-border-light bg-surface-secondary"onExpand={answerMode.collapsed && isLivePause ? answerMode.expand : undefined}- onDismiss={answerMode.collapsed && isLivePause ? answerMode.dismiss : undefined}/>);}@@ -65,11 +66,11 @@ function AskUserQuestionSingle({/*** The composer popover is the primary answer surface — while it's VISIBLE* for this pause, rendering the card too duplicates the question. The card- * takes over when the popover is collapsed (answer mode stays live; the- * chevron re-expands it) or dismissed (and in contexts without a- * ChatContext, where the popover can't exist).+ * takes over once the question is moved to the chat (the popover's chevron,+ * which also releases the composer; this card's chevron moves it back), and+ * in contexts without a ChatContext, where the popover can't exist.*/- const { popoverVisible, collapsed, expand, dismiss, liveAsk } = answerMode;+ const { popoverVisible, collapsed, expand, liveAsk } = answerMode;const isLivePause = liveAsk?.actionId === actionId;/** Same fold as the popover: a model-supplied catch-all "Other" option@@ -80,10 +81,8 @@ function AskUserQuestionSingle({);const status = getAskStatus(actionId);- if (popoverVisible && isLivePause) {- return null;- }const locked = status === 'submitting' || status === 'submitted' || status === 'expired';+ const showPlaceholder = popoverVisible && isLivePause;if (status === 'submitted') {return null;@@ -93,6 +92,14 @@ function AskUserQuestionSingle({/** Live pause: share the hook's checked set so the composer's Enter and* this card submit exactly what the card displays. */const checkedIndices = isLivePause ? answerMode.checked : localChecked;+ const answerValue = isLivePause ? answerMode.answerText : answer;+ const setAnswerValue = (value: string) => {+ if (isLivePause) {+ answerMode.setAnswerText(value);+ return;+ }+ setAnswer(value);+ };const toggleIndex = (index: number) => {if (isLivePause) {answerMode.toggleChecked(index);@@ -103,7 +110,7 @@ function AskUserQuestionSingle({);};- const trimmed = answer.trim();+ const trimmed = answerValue.trim();const canSubmit = multiSelect? checkedIndices.length > 0 || trimmed.length > 0: trimmed.length > 0;@@ -119,6 +126,18 @@ function AskUserQuestionSingle({}};+ /** `answerMode.skip()` is gated on answer mode being ACTIVE, which a+ * question moved to the chat is not. That is precisely when this card+ * is the only surface left. Decline through the answer path instead,+ * which is gated on the live pause rather than on answer mode. */+ const handleSkip = () => {+ if (isLivePause) {+ answerMode.submitAnswer([ASK_USER_DECLINED_ANSWER]);+ return;+ }+ submitAskAnswer(actionId, ASK_USER_DECLINED_ANSWER);+ };+const submitCombined = () => {const values = multiSelect? checkedIndices@@ -138,90 +157,116 @@ function AskUserQuestionSingle({submitAskAnswer(actionId, values.join(', '));};- return (- <div className="my-2 flex w-full flex-col gap-2 rounded-lg border border-border-light bg-surface-secondary p-3">+ /**+ * The live card shares its view-transition-name with the popover panel, so+ * collapse/expand morphs one surface into the other. The placeholder copy+ * is `visibility: hidden` (out of the tab order and the a11y tree) and+ * carries NO transition name because duplicate names would void the morph, but+ * it still occupies the card's exact footprint, so the thread reserves the+ * space while the question lives in the composer and nothing reflows when+ * it moves back.+ */+ const card = (+ <div+ className={cn(+ 'my-2 flex w-full flex-col gap-2.5 rounded-xl border border-border-light bg-surface-secondary p-3',+ showPlaceholder && 'invisible',+ )}+ aria-hidden={showPlaceholder || undefined}+ style={isLivePause && !showPlaceholder ? { viewTransitionName: 'ask-question' } : undefined}+ ><div className="flex items-start justify-between gap-2">- <p className="min-w-0 text-sm font-medium text-text-primary [overflow-wrap:anywhere]">- {question.question}- </p>+ <div className="min-w-0">+ <p className="text-sm font-medium text-text-primary [overflow-wrap:anywhere]">+ {question.question}+ </p>+ {question.description != null && question.description.length > 0 && (+ <p className="mt-0.5 text-xs text-text-secondary [overflow-wrap:anywhere]">+ {question.description}+ </p>+ )}+ </div>{collapsed && isLivePause && (- <div className="flex shrink-0 items-center">- <button- type="button"- aria-label={localize('com_ui_expand')}- className="rounded p-1 text-text-secondary hover:bg-surface-hover"- onClick={expand}- >- <ChevronUp className="h-4 w-4" aria-hidden="true" />- </button>- {/** Mirrors the popover's ×: the collapsed card is the only chrome- * left, so the way out of answer mode has to live here too. */}- <button- type="button"- aria-label={localize('com_ui_close')}- className="rounded p-1 text-text-secondary hover:bg-surface-hover"- onClick={dismiss}- >- <X className="h-4 w-4" aria-hidden="true" />- </button>- </div>+ <TooltipAnchor+ description={localize('com_ui_ask_move_to_composer')}+ side="top"+ render={+ <Button+ variant="ghost"+ size="icon"+ aria-label={localize('com_ui_ask_move_to_composer')}+ className="size-auto rounded-md p-1 text-text-secondary"+ onClick={expand}+ >+ <ChevronUp className="size-4" aria-hidden="true" />+ </Button>+ }+ />)}</div>- {question.description != null && question.description.length > 0 && (- <p className="text-sm text-text-secondary [overflow-wrap:anywhere]">- {question.description}- </p>- )}{choices.length > 0 && (- <div className="flex flex-wrap gap-2">- {choices.map((option, index) => (- <Button- key={option.value}- size="sm"- variant={multiSelect && checkedIndices.includes(index) ? 'submit' : 'choice'}- role={multiSelect ? 'checkbox' : undefined}- aria-checked={multiSelect ? checkedIndices.includes(index) : undefined}- disabled={locked}- className="h-auto min-h-9 max-w-full whitespace-normal py-1.5 text-left [overflow-wrap:anywhere]"- onClick={() => (multiSelect ? toggleIndex(index) : submitSingle(index))}- >- {option.label}- </Button>- ))}- </div>+ <AskOptions+ options={choices}+ multiSelect={multiSelect}+ checked={checkedIndices}+ locked={locked}+ onActivate={(index) => (multiSelect ? toggleIndex(index) : submitSingle(index))}+ />)}<TextareaAutosize- value={answer}+ value={answerValue}disabled={locked}onChange={(e) => {- setAnswer(e.target.value);+ setAnswerValue(e.target.value);setAskAnswerDraft(actionId, e.target.value);}}minRows={2}maxRows={12}placeholder={otherLabel ?? localize('com_ui_your_answer')}- className="w-full resize-none rounded-md border border-border-xheavy bg-surface-primary p-2 text-sm text-text-primary"+ className="w-full resize-none rounded-lg border border-border-light bg-surface-chat px-3 py-2 text-sm text-text-primary placeholder:text-text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-text-primary"aria-label={localize('com_ui_your_answer')}/><div className="flex items-center gap-3">- <Button size="sm" variant="submit" disabled={!canSubmit || locked} onClick={submitCombined}>- {status === 'submitting' ? localize('com_ui_submitting') : localize('com_ui_submit')}+ <Button size="sm" variant="outline" disabled={locked} onClick={handleSkip}>+ {localize('com_ui_skip')}</Button>- {status === 'expired' && (- <span className="flex items-center text-xs text-text-warning">- <TriangleAlert className="mr-1.5 h-4 w-4" aria-hidden="true" />- {localize('com_ui_approval_expired')}- </span>- )}- {status === 'error' && (- <span className="flex items-center text-xs text-text-warning">- <TriangleAlert className="mr-1.5 h-4 w-4" aria-hidden="true" />- {localize('com_ui_approval_error')}+ {(status === 'expired' || status === 'error') && (+ <span className="flex min-w-0 items-center text-xs text-text-warning">+ <TriangleAlert className="mr-1.5 size-4 shrink-0" aria-hidden="true" />+ {localize(status === 'expired' ? 'com_ui_approval_expired' : 'com_ui_approval_error')}</span>)}+ <Button+ size="sm"+ variant="submit"+ className="ml-auto"+ disabled={!canSubmit || locked}+ onClick={submitCombined}+ >+ {status === 'submitting' ? localize('com_ui_submitting') : localize('com_ui_submit')}+ </Button>+ </div>+ </div>+ );++ if (!showPlaceholder) {+ return card;+ }++ /** Popover has the question: the reserved card sits hidden underneath the+ * same compact in-progress row the other tools use, so the turn still+ * shows the call is running. */+ return (+ <div className="relative">+ {card}+ <div className="absolute inset-x-0 top-0 my-1 flex h-5 items-center gap-2.5">+ <MessageCircleQuestion className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />+ <span className="tool-status-text shimmer font-medium text-text-secondary">+ {localize('com_ui_asking')}+ </span></div></div>);diff --git a/client/src/components/Chat/Messages/Content/AskUserQuestions.tsx b/client/src/components/Chat/Messages/Content/AskUserQuestions.tsxindex 30b44568b6..384cfd9430 100644--- a/client/src/components/Chat/Messages/Content/AskUserQuestions.tsx+++ b/client/src/components/Chat/Messages/Content/AskUserQuestions.tsx@@ -107,27 +107,29 @@ export default function AskUserQuestions({{(onExpand != null || onDismiss != null) && (<div className="flex shrink-0 items-center justify-end border-b border-border-light px-2 py-1">{onExpand != null && (- <button- type="button"+ <Button+ variant="ghost"+ size="icon-sm"aria-label={localize('com_ui_expand')}- className="rounded p-1 text-text-secondary hover:bg-surface-hover"+ className="text-text-secondary"onClick={onExpand}><ChevronUp className="h-4 w-4" aria-hidden="true" />- </button>+ </Button>)}{/** The collapsed card is the ONLY surface left for a collapsed* batch, so it has to carry the popover's dismiss too — without it* the pause can only be answered or skipped. */}{onDismiss != null && (- <button- type="button"+ <Button+ variant="ghost"+ size="icon-sm"aria-label={localize('com_ui_close')}- className="rounded p-1 text-text-secondary hover:bg-surface-hover"+ className="text-text-secondary"onClick={onDismiss}><X className="h-4 w-4" aria-hidden="true" />- </button>+ </Button>)}</div>)}diff --git a/client/src/components/Chat/Messages/Content/CodeAnalyze.tsx b/client/src/components/Chat/Messages/Content/CodeAnalyze.tsxindex 26176ba410..e960a7201e 100644--- a/client/src/components/Chat/Messages/Content/CodeAnalyze.tsx+++ b/client/src/components/Chat/Messages/Content/CodeAnalyze.tsx@@ -60,7 +60,7 @@ export default function CodeAnalyze({<span className="sr-only" aria-live="polite" aria-atomic="true">{phase === 'running' ? localize('com_ui_analyzing') : localize('com_ui_analyzing_finished')}</span>- <div className="my-1 flex items-center gap-2.5">+ <div className="relative my-1 flex h-5 shrink-0 items-center gap-2.5"><ProgressTextphase={phase}onClick={handleToggleCode}diff --git a/client/src/components/Chat/Messages/Content/ContentParts.tsx b/client/src/components/Chat/Messages/Content/ContentParts.tsxindex 361b029fd4..0db9c2b8c5 100644--- a/client/src/components/Chat/Messages/Content/ContentParts.tsx+++ b/client/src/components/Chat/Messages/Content/ContentParts.tsx@@ -206,6 +206,7 @@ type ContentPartsProps = {attachments?: TAttachment[];searchResults?: { [key: string]: SearchResultData };isCreatedByUser: boolean;+ showThinking: boolean;isLast: boolean;isSubmitting: boolean;isLatestMessage?: boolean;@@ -269,6 +270,7 @@ const ContentPartsBody = memo(function ContentPartsBody({authorHeader,conversationId,isCreatedByUser,+ showThinking,isLatestMessage,createdAt,nestedActivityPhase = false,@@ -661,15 +663,16 @@ const ContentPartsBody = memo(function ContentPartsBody({const baseGroupId = getToolGroupId(group.parts, fallbackScope);const occurrence =resolvedToolGroupOccurrences.get(getToolGroupAnchorIndex(group.parts)) ?? 1;- /** Legacy rows lack run-step identity. Their provider ids may repeat,- * so preserve the first group's historic stable key and distinguish- * later occurrences by sequence rather than a shifting content index. */const groupId = occurrence === 1 ? baseGroupId : `${baseGroupId}:occurrence:${occurrence}`;- /** Hoisted a level higher when a phase card owns the media row, so the- * same file is not offered by both the block and the card. */- const groupAttachments = hideAttachments- ? undefined- : group.parts.flatMap(({ part }) => attachmentsForPart(part) ?? []);+ const seenAttachments = new Set<TAttachment>();+ if (!hideAttachments) {+ for (const { part } of group.parts) {+ for (const attachment of attachmentsForPart(part) ?? []) {+ seenAttachments.add(attachment);+ }+ }+ }+ const groupAttachments = hideAttachments ? undefined : Array.from(seenAttachments);return { ...group, groupId, groupAttachments };});}, [@@ -810,6 +813,7 @@ const ContentPartsBody = memo(function ContentPartsBody({isSubmitting={isSubmitting}isLatestMessage={isLatestMessage}nestedActivityPhase+ showThinking={showThinking}withinActivityPhase={withinPhase}cursorOwnedElsewhere={cursorOwnedByCard}hideAttachments={hoisted}@@ -1056,6 +1060,7 @@ const ContentPartsBody = memo(function ContentPartsBody({lastContentIdx={lastContentIdx}groupAttachments={group.groupAttachments}initialExpansionState={expansionState.get(groupId)}+ showThinking={showThinking}onExpansionChange={(state) => handleGroupExpansionChange(groupId, state)}labelPart={group.labelPart}withinActivityPhase={withinActivityPhase}diff --git a/client/src/components/Chat/Messages/Content/MemoryArtifacts.tsx b/client/src/components/Chat/Messages/Content/MemoryArtifacts.tsxindex 922cd7005d..d1538d313d 100644--- a/client/src/components/Chat/Messages/Content/MemoryArtifacts.tsx+++ b/client/src/components/Chat/Messages/Content/MemoryArtifacts.tsx@@ -1,25 +1,37 @@-import { useState, useRef, useMemo, useLayoutEffect, useEffect } from 'react';+import { useId, useMemo, useState } from 'react';+import { ChevronDown } from 'lucide-react';import { Tools } from 'librechat-data-provider';+import { Button, disclosureChevronVariants } from '@librechat/client';import type { MemoryArtifact, TAttachment } from 'librechat-data-provider';+import { toolPanelSpacingClassName } from './disclosure';+import { useExpandCollapse, useLocalize } from '~/hooks';import MemoryInfo from './MemoryInfo';-import { useLocalize } from '~/hooks';import { cn } from '~/utils';+/** True for a memory attachment with no originating tool call. A call rendered+ * inline as a `MemoryCall` card already shows the same key, value and outcome,+ * so counting its attachment here too rendered one mutation twice ("Saved+ * memory" beside "Updated saved memory"), on reload as well as live. Legacy+ * attachments carry no `toolCallId` and keep this decoration as their only+ * surface. */+const isUnlinkedMemoryArtifact = (+ attachment?: TAttachment,+): attachment is TAttachment & { [Tools.memory]: MemoryArtifact } =>+ attachment?.[Tools.memory] != null && !attachment.toolCallId;+/** Layout-gate predicate for callers that arrange around this component* (e.g. the thinking-dot nudge). Must stay in agreement with the memo's- * collection condition inside the component — both key on- * `attachment[Tools.memory]`. The component itself guards on its memoized+ * collection condition inside the component: both key on+ * `isUnlinkedMemoryArtifact`. The component itself guards on its memoized* list instead, avoiding a second pass per render. */export const hasMemoryArtifacts = (attachments?: TAttachment[]): boolean =>- attachments?.some((attachment) => attachment?.[Tools.memory] != null) ?? false;+ attachments?.some(isUnlinkedMemoryArtifact) ?? false;export default function MemoryArtifacts({ attachments }: { attachments?: TAttachment[] }) {+ const contentId = useId();const localize = useLocalize();const [showInfo, setShowInfo] = useState(false);- const contentRef = useRef<HTMLDivElement>(null);- const [contentHeight, setContentHeight] = useState<number | undefined>(0);- const [isAnimating, setIsAnimating] = useState(false);- const prevShowInfoRef = useRef<boolean>(showInfo);+ const { style: expandStyle, ref: expandRef } = useExpandCollapse(showInfo);const { hasErrors, memoryArtifacts } = useMemo(() => {let hasErrors = false;@@ -30,7 +42,7 @@ export default function MemoryArtifacts({ attachments }: { attachments?: TAttach}for (const attachment of attachments) {- if (attachment?.[Tools.memory] != null) {+ if (isUnlinkedMemoryArtifact(attachment)) {result.push(attachment[Tools.memory]);if (!hasErrors && attachment[Tools.memory].type === 'error') {@@ -42,120 +54,72 @@ export default function MemoryArtifacts({ attachments }: { attachments?: TAttachreturn { hasErrors, memoryArtifacts: result };}, [attachments]);- useLayoutEffect(() => {- if (showInfo !== prevShowInfoRef.current) {- prevShowInfoRef.current = showInfo;- setIsAnimating(true);-- if (showInfo && contentRef.current) {- requestAnimationFrame(() => {- if (contentRef.current) {- const height = contentRef.current.scrollHeight;- setContentHeight(height + 4);- }- });- } else {- setContentHeight(0);- }-- const timer = setTimeout(() => {- setIsAnimating(false);- }, 400);-- return () => clearTimeout(timer);- }- }, [showInfo]);-- useEffect(() => {- if (!contentRef.current) {- return;- }- const resizeObserver = new ResizeObserver((entries) => {- if (showInfo && !isAnimating) {- for (const entry of entries) {- if (entry.target === contentRef.current) {- setContentHeight(entry.contentRect.height + 4);- }- }- }- });- resizeObserver.observe(contentRef.current);- return () => {- resizeObserver.disconnect();- };- }, [showInfo, isAnimating]);-if (memoryArtifacts.length === 0) {return null;}return (<>- <div className="flex items-center">- <div className="inline-block">- <button- className={cn(- 'my-1 flex items-center gap-1 text-sm font-semibold transition-colors',- hasErrors ? 'text-status-error' : 'text-text-secondary-alt hover:text-text-primary',- )}- type="button"- onClick={() => setShowInfo((prev) => !prev)}- aria-expanded={showInfo}- aria-label={localize('com_ui_memory_updated')}+ <div className="relative my-1 flex h-5 shrink-0 items-center gap-2.5">+ <Button+ variant="ghost"+ className={cn(+ 'group/disclosure h-auto w-full justify-start gap-2 rounded-none p-0 font-normal hover:bg-transparent',+ hasErrors ? 'text-status-error' : 'text-text-secondary',+ )}+ onClick={() => setShowInfo((prev) => !prev)}+ aria-expanded={showInfo}+ aria-controls={contentId}+ aria-label={localize('com_ui_memory_updated')}+ >+ <svg+ width="18"+ height="18"+ viewBox="0 0 18 18"+ fill="none"+ xmlns="http://www.w3.org/2000/svg"+ className="size-4 shrink-0"+ aria-hidden="true">- <svg- width="18"- height="18"- viewBox="0 0 18 18"- fill="none"- xmlns="http://www.w3.org/2000/svg"- className="mb-[-1px]"- >- <path- d="M6 3C4.89543 3 4 3.89543 4 5V13C4 14.1046 4.89543 15 6 15L6 3Z"- fill="currentColor"- />- <path- d="M7 3V15H8.18037L8.4899 13.4523C8.54798 13.1619 8.69071 12.8952 8.90012 12.6858L12.2931 9.29289C12.7644 8.82153 13.3822 8.58583 14 8.58578V3.5C14 3.22386 13.7761 3 13.5 3H7Z"- fill="currentColor"- />- <path- d="M11.3512 15.5297L9.73505 15.8529C9.38519 15.9229 9.07673 15.6144 9.14671 15.2646L9.46993 13.6484C9.48929 13.5517 9.53687 13.4628 9.60667 13.393L12.9996 10C13.5519 9.44771 14.4473 9.44771 14.9996 10C15.5519 10.5523 15.5519 11.4477 14.9996 12L11.6067 15.393C11.5369 15.4628 11.448 15.5103 11.3512 15.5297Z"- fill="currentColor"- />- </svg>+ <path+ d="M6 3C4.89543 3 4 3.89543 4 5V13C4 14.1046 4.89543 15 6 15L6 3Z"+ fill="currentColor"+ />+ <path+ d="M7 3V15H8.18037L8.4899 13.4523C8.54798 13.1619 8.69071 12.8952 8.90012 12.6858L12.2931 9.29289C12.7644 8.82153 13.3822 8.58583 14 8.58578V3.5C14 3.22386 13.7761 3 13.5 3H7Z"+ fill="currentColor"+ />+ <path+ d="M11.3512 15.5297L9.73505 15.8529C9.38519 15.9229 9.07673 15.6144 9.14671 15.2646L9.46993 13.6484C9.48929 13.5517 9.53687 13.4628 9.60667 13.393L12.9996 10C13.5519 9.44771 14.4473 9.44771 14.9996 10C15.5519 10.5523 15.5519 11.4477 14.9996 12L11.6067 15.393C11.5369 15.4628 11.448 15.5103 11.3512 15.5297Z"+ fill="currentColor"+ />+ </svg>+ <span className="tool-status-text font-medium">{hasErrors ? localize('com_ui_memory_error') : localize('com_ui_memory_updated')}- </button>- </div>+ </span>+ <ChevronDown+ className={cn(+ disclosureChevronVariants({ expanded: showInfo }),+ 'size-4 translate-y-[1px]',+ )}+ aria-hidden="true"+ />+ </Button></div><div- className="relative"- style={{- height: showInfo ? contentHeight : 0,- overflow: 'hidden',- transition:- 'height 0.4s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.4s cubic-bezier(0.16, 1, 0.3, 1)',- opacity: showInfo ? 1 : 0,- transformOrigin: 'top',- willChange: 'height, opacity',- perspective: '1000px',- backfaceVisibility: 'hidden',- WebkitFontSmoothing: 'subpixel-antialiased',- }}+ id={contentId}+ style={expandStyle}+ role="group"+ aria-label={localize('com_ui_memory_updated')}+ aria-hidden={!showInfo || undefined}>- <div- className={cn(- 'overflow-hidden rounded-xl border border-border-light bg-surface-primary-alt shadow-md',- showInfo && 'shadow-lg',- )}- style={{- transform: showInfo ? 'translateY(0) scale(1)' : 'translateY(-8px) scale(0.98)',- opacity: showInfo ? 1 : 0,- transition:- 'transform 0.4s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.4s cubic-bezier(0.16, 1, 0.3, 1)',- }}- >- <div ref={contentRef}>+ <div className="overflow-hidden" ref={expandRef}>+ <div+ className={cn(+ toolPanelSpacingClassName,+ 'overflow-hidden rounded-lg border border-border-light bg-surface-secondary',+ )}+ >{showInfo && <MemoryInfo key="memory-info" memoryArtifacts={memoryArtifacts} />}</div></div>diff --git a/client/src/components/Chat/Messages/Content/MemoryInfo.tsx b/client/src/components/Chat/Messages/Content/MemoryInfo.tsxindex 59aa5d6736..c81d02f895 100644--- a/client/src/components/Chat/Messages/Content/MemoryInfo.tsx+++ b/client/src/components/Chat/Messages/Content/MemoryInfo.tsx@@ -47,52 +47,40 @@ export default function MemoryInfo({ memoryArtifacts }: { memoryArtifacts: Memor}return (- <div className="space-y-4 p-4">+ <div className="space-y-3 p-3">{updatedMemories.length > 0 && (- <div>- <h4 className="mb-2 text-sm font-semibold text-text-primary">- {localize('com_ui_memory_updated_items')}- </h4>- <div className="space-y-2">- {updatedMemories.map((artifact) => (- <div key={`update-${artifact.key}`} className="rounded-lg p-3">- <div className="mb-1 text-xs font-medium uppercase tracking-wide text-text-secondary">- {artifact.key}- </div>- <div className="whitespace-pre-wrap text-sm text-text-primary">- {artifact.value}- </div>+ <div className="space-y-3">+ {updatedMemories.map((artifact) => (+ <div key={`update-${artifact.key}`}>+ <div className="mb-1 text-xs font-bold uppercase tracking-wide text-text-secondary">+ {artifact.key}</div>- ))}- </div>+ <div className="whitespace-pre-wrap text-sm text-text-primary">{artifact.value}</div>+ </div>+ ))}</div>)}{deletedMemories.length > 0 && (- <div>- <h4 className="mb-2 text-sm font-semibold text-text-primary">- {localize('com_ui_memory_deleted_items')}- </h4>- <div className="space-y-2">- {deletedMemories.map((artifact) => (- <div key={`delete-${artifact.key}`} className="rounded-lg p-3 opacity-60">- <div className="mb-1 text-xs font-medium uppercase tracking-wide text-text-secondary">- {artifact.key}- </div>- <div className="text-sm italic text-text-secondary">- {localize('com_ui_memory_deleted')}- </div>+ <div className="space-y-3">+ {deletedMemories.map((artifact) => (+ <div key={`delete-${artifact.key}`} className="opacity-60">+ <div className="mb-1 text-xs font-bold uppercase tracking-wide text-text-secondary">+ {artifact.key}</div>- ))}- </div>+ <div className="text-sm italic text-text-secondary">+ {localize('com_ui_memory_deleted')}+ </div>+ </div>+ ))}</div>)}{errorMessages.length > 0 && (<div>- <h4 className="mb-2 text-sm font-semibold text-text-destructive">+ <p className="mb-2 text-sm font-semibold text-status-error">{localize('com_ui_memory_storage_full')}- </h4>+ </p><div className="space-y-2">{errorMessages.map((errorMessage) => (<Alert key={errorMessage} variant="error" icon={false} className="rounded-md p-3">diff --git a/client/src/components/Chat/Messages/Content/Part.tsx b/client/src/components/Chat/Messages/Content/Part.tsxindex 67f7bb75b1..a4b3be7e1c 100644--- a/client/src/components/Chat/Messages/Content/Part.tsx+++ b/client/src/components/Chat/Messages/Content/Part.tsx@@ -18,6 +18,7 @@ import {Summary,Text,SkillCall,+ MemoryCall,ReadFileCall,FileAuthoringCall,BashCall,@@ -165,6 +166,7 @@ const Part = memo(function Part({provider={part.provider}tokenCount={part.tokenCount}summarizing={part.summarizing}+ failed={part.failed}/>);} else if (part.type === ContentTypes.ACTIVITY_LABEL) {@@ -304,6 +306,21 @@ const Part = memo(function Part({hideAttachments={hideAttachments}/>);+ } else if (toolCall.name === 'set_memory' || toolCall.name === 'delete_memory') {+ return (+ <MemoryCall+ toolName={toolCall.name}+ args={toolCall.args}+ output={toolCall.output ?? ''}+ initialProgress={toolCall.progress ?? 0.1}+ isSubmitting={isSubmitting}+ runStepStatus={toolCall.runStepStatus}+ runStepDurationMs={toolCall.runStepDurationMs}+ attachments={attachments}+ hideAttachments={hideAttachments}+ onExpand={onToolExpand}+ />+ );} else if (toolCall.name === 'read_file') {return (<ReadFileCall@@ -358,6 +375,7 @@ const Part = memo(function Part({isSubmitting={isSubmitting}runStepStatus={toolCall.runStepStatus}attachments={attachments}+ hideAttachments={hideAttachments}isLast={isLast}onExpand={onToolExpand}/>diff --git a/client/src/components/Chat/Messages/Content/Parts/BashCall.tsx b/client/src/components/Chat/Messages/Content/Parts/BashCall.tsxindex 8c973bdba3..11156abc9a 100644--- a/client/src/components/Chat/Messages/Content/Parts/BashCall.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/BashCall.tsx@@ -7,6 +7,7 @@ import ProgressText from '~/components/Chat/Messages/Content/ProgressText';import parseJsonField, { areToolCallArgsComplete } from './parseJsonField';import CopyButton from '~/components/Messages/Content/CopyButton';import LangIcon from '~/components/Messages/Content/LangIcon';+import { toolPanelSpacingClassName } from '../disclosure';import { sandboxStartingByToolCallId } from '~/store';import useToolCallState from './useToolCallState';import useLazyHighlight from './useLazyHighlight';@@ -156,26 +157,33 @@ export default function BashCall({</div><div style={expandStyle}><div className="overflow-hidden" ref={expandRef}>- <div className="my-2 overflow-hidden rounded-lg border border-border-light">+ <div+ className={cn(+ toolPanelSpacingClassName,+ 'overflow-hidden rounded-lg border border-border-light',+ )}+ >{command && (- <div- ref={commandPaneRef}- onScroll={onCommandPaneScroll}- className="relative max-h-[300px] overflow-auto bg-surface-tertiary dark:bg-gray-950"- >+ <div className="relative bg-surface-tertiary dark:bg-gray-950"><CopyButtoniconOnlyisCopied={isCopied}onClick={handleCopy}- className="sticky right-0 top-1 float-right mr-1.5 mt-1"+ className="absolute right-1.5 top-1"label={localize('com_ui_copy_code')}/>- <pre className="whitespace-pre-wrap break-words px-3 py-2.5 pr-10 font-mono text-xs">- <span className="select-none text-text-tertiary" aria-hidden="true">- {'$ '}- </span>- <code className="hljs language-bash">{highlighted ?? command}</code>- </pre>+ <div+ ref={commandPaneRef}+ onScroll={onCommandPaneScroll}+ className="max-h-[300px] overflow-auto"+ >+ <pre className="whitespace-pre-wrap break-words px-3 py-2.5 pr-10 font-mono text-xs">+ <span className="select-none text-text-tertiary" aria-hidden="true">+ {'$ '}+ </span>+ <code className="hljs language-bash">{highlighted ?? command}</code>+ </pre>+ </div></div>)}<PtcToolTracediff --git a/client/src/components/Chat/Messages/Content/Parts/CodeWindowHeader.tsx b/client/src/components/Chat/Messages/Content/Parts/CodeWindowHeader.tsxindex a65fe5ca5f..93ee1851f2 100644--- a/client/src/components/Chat/Messages/Content/Parts/CodeWindowHeader.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/CodeWindowHeader.tsx@@ -7,9 +7,10 @@ import { useLocalize } from '~/hooks';interface CodeWindowHeaderProps {language: string;code: string;+ diffStats?: { additions: number; deletions: number };}-export default function CodeWindowHeader({ language, code }: CodeWindowHeaderProps) {+export default function CodeWindowHeader({ language, code, diffStats }: CodeWindowHeaderProps) {const localize = useLocalize();const [isCopied, setIsCopied] = useState(false);const timerRef = useRef<ReturnType<typeof setTimeout>>();@@ -25,9 +26,26 @@ export default function CodeWindowHeader({ language, code }: CodeWindowHeaderProreturn (<div className="flex items-center justify-between bg-surface-primary-alt px-1.5 py-1.5 font-sans text-xs text-text-secondary dark:bg-transparent">- <span className="flex items-center gap-1.5 text-xs font-medium">+ <span className="flex items-center gap-1.5 pl-1.5 text-xs font-medium"><LangIcon lang={language} className="size-3.5 shrink-0" />{language}+ {diffStats && (+ <>+ <span className="flex items-center gap-1 font-normal tabular-nums" aria-hidden="true">+ <span className="text-status-success">+{diffStats.additions}</span>+ <span className="text-status-error">-{diffStats.deletions}</span>+ </span>+ {/* The glyphs above carry the meaning visually through color and+ sign, which neither reaches a screen reader, so the counts are+ announced as words instead of being dropped. */}+ <span className="sr-only">+ {localize('com_ui_diff_stats', {+ 0: String(diffStats.additions),+ 1: String(diffStats.deletions),+ })}+ </span>+ </>+ )}</span><CopyButton isCopied={isCopied} onClick={handleCopy} label={localize('com_ui_copy_code')} /></div>diff --git a/client/src/components/Chat/Messages/Content/Parts/DiffView.tsx b/client/src/components/Chat/Messages/Content/Parts/DiffView.tsxnew file mode 100644index 0000000000..1d785550a4--- /dev/null+++ b/client/src/components/Chat/Messages/Content/Parts/DiffView.tsx@@ -0,0 +1,217 @@+import { cn } from '~/utils';++const HUNK_HEADER = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/;++export interface DiffLine {+ type: 'add' | 'del' | 'context' | 'hunk';+ text: string;+ oldLine?: number;+ newLine?: number;+}++export interface ParsedDiff {+ lines: DiffLine[];+ additions: number;+ deletions: number;+ hasLineNumbers: boolean;+}++/**+ * Parses REAL unified-diff text (a tool's own output) into typed lines with+ * old/new line numbers when the hunk headers carry them. File headers and+ * `\ No newline` markers are dropped, since the window header already names+ * the file.+ *+ * Deliberately knows nothing about the args preview. That preview is built+ * from structured edits by `buildEditPreviewDiff`, so it never round-trips+ * through diff text: there are no synthetic separators to recognize, and+ * therefore no byte sequence a real changed line could be mistaken for. An+ * earlier version emitted `--- old_text` / `+++ new_text` separators and tried+ * to spot them here, which could not be made safe, because replacing a source+ * line `-- old_text` with `++ new_text` produces exactly those strings.+ */+export function parseUnifiedDiff(diff: string): ParsedDiff {+ const lines: DiffLine[] = [];+ let additions = 0;+ let deletions = 0;+ let hasLineNumbers = false;+ let oldLine: number | undefined;+ let newLine: number | undefined;+ let inHunk = false;++ for (const raw of diff.replace(/\n$/, '').split('\n')) {+ if (!inHunk && (raw.startsWith('--- ') || raw.startsWith('+++ '))) {+ continue;+ }+ if (raw.startsWith('\\')) {+ continue;+ }+ const hunk = HUNK_HEADER.exec(raw);+ if (hunk) {+ inHunk = true;+ oldLine = Number(hunk[1]);+ newLine = Number(hunk[2]);+ hasLineNumbers = true;+ lines.push({ type: 'hunk', text: raw });+ continue;+ }+ if (raw === '@@') {+ inHunk = true;+ oldLine = undefined;+ newLine = undefined;+ lines.push({ type: 'hunk', text: '' });+ continue;+ }+ if (raw.startsWith('+')) {+ additions += 1;+ lines.push({ type: 'add', text: raw.slice(1), newLine });+ newLine = newLine == null ? undefined : newLine + 1;+ continue;+ }+ if (raw.startsWith('-')) {+ deletions += 1;+ lines.push({ type: 'del', text: raw.slice(1), oldLine });+ oldLine = oldLine == null ? undefined : oldLine + 1;+ continue;+ }+ lines.push({+ type: 'context',+ text: raw.startsWith(' ') ? raw.slice(1) : raw,+ oldLine,+ newLine,+ });+ oldLine = oldLine == null ? undefined : oldLine + 1;+ newLine = newLine == null ? undefined : newLine + 1;+ }++ return { lines, additions, deletions, hasLineNumbers };+}++export interface TextEditPreview {+ oldText: string;+ newText: string;+}++/**+ * Rows one side of an edit contributes. An empty side means "nothing here",+ * not one blank line, and a trailing newline terminates the last line rather+ * than starting an empty one: plain `split('\n')` would render a blank row and+ * count it as a change, so a pure deletion (`new_text: ""`) claimed one+ * addition.+ */+const previewRows = (text: string): string[] => (text ? text.replace(/\n$/, '').split('\n') : []);++/**+ * Builds the diff for an `edit_file` args preview straight from the structured+ * edits, instead of formatting them into diff text for `parseUnifiedDiff` to+ * read back.+ *+ * That round trip is what made batched previews ambiguous: the separators it+ * needed between edits were byte-identical to a real changed line, since+ * deleting a source line `-- old_text` prefixes to exactly `--- old_text`. No+ * parser can tell those apart from position or bytes alone. Built here, each+ * edit boundary is structural and no separator is ever emitted.+ *+ * A boundary between edits becomes an empty `hunk` line, which `DiffView`+ * renders as its divider rule. There are no line numbers: args previews carry+ * the replacement text, never its position in the file.+ */+export function buildEditPreviewDiff(edits: TextEditPreview[]): ParsedDiff {+ const lines: DiffLine[] = [];+ let additions = 0;+ let deletions = 0;++ edits.forEach((edit, index) => {+ if (index > 0) {+ lines.push({ type: 'hunk', text: '' });+ }+ for (const text of previewRows(edit.oldText)) {+ deletions += 1;+ lines.push({ type: 'del', text });+ }+ for (const text of previewRows(edit.newText)) {+ additions += 1;+ lines.push({ type: 'add', text });+ }+ });++ return { lines, additions, deletions, hasLineNumbers: false };+}++/** One-way serialization for the copy button. Never parsed back, so it is free+ * to be lossy about hunk boundaries. */+export function diffPreviewText(parsed: ParsedDiff): string {+ return parsed.lines+ .map((line) => (line.type === 'hunk' ? '' : `${LINE_MARKERS[line.type]}${line.text}`))+ .join('\n');+}++const LINE_MARKERS: Record<DiffLine['type'], string> = {+ add: '+',+ del: '-',+ context: '',+ hunk: '',+};++/** One number per row keeps the gutter compact: the old line for removals+ * (it no longer exists in the new file) and the new line otherwise. */+function lineNumber(line: DiffLine): number | undefined {+ return line.type === 'del' ? line.oldLine : (line.newLine ?? line.oldLine);+}++export default function DiffView({ parsed }: { parsed: ParsedDiff }) {+ const { lines, hasLineNumbers } = parsed;+ const firstContentIndex = lines.findIndex((line) => line.type !== 'hunk');++ return (+ <div+ data-testid="diff-view"+ className="max-h-[300px] overflow-y-auto bg-surface-code py-2 font-mono text-xs leading-5"+ >+ {lines.map((line, index) => {+ if (line.type === 'hunk') {+ if (index < firstContentIndex || firstContentIndex === -1) {+ return null;+ }+ if (!line.text) {+ return <div key={index} className="mx-3 my-1.5 border-t border-border-light" />;+ }+ return (+ <div key={index} className="select-none px-3 py-0.5 text-[11px] text-text-tertiary">+ {line.text}+ </div>+ );+ }+ return (+ <div+ key={index}+ className={cn(+ 'flex',+ line.type === 'add' && 'bg-status-success-subtle',+ line.type === 'del' && 'bg-status-error-subtle',+ )}+ >+ {hasLineNumbers && (+ <span className="w-9 shrink-0 select-none pr-1 text-right text-[11px] text-text-tertiary">+ {lineNumber(line) ?? ''}+ </span>+ )}+ <span+ className={cn(+ 'shrink-0 select-none text-center font-semibold',+ hasLineNumbers ? 'w-5' : 'w-6',+ line.type === 'add' && 'text-status-success',+ line.type === 'del' && 'text-status-error',+ )}+ >+ {LINE_MARKERS[line.type]}+ </span>+ <span className="min-w-0 flex-1 whitespace-pre-wrap break-words pr-3 text-text-primary">+ {line.text || ' '}+ </span>+ </div>+ );+ })}+ </div>+ );+}diff --git a/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx b/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsxindex 607b5dfc14..f969df1897 100644--- a/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx@@ -4,6 +4,7 @@ import { SquareTerminal } from 'lucide-react';import type { TAttachment, PartMetadata } from 'librechat-data-provider';import { parseBackgroundHandle, splitBackgroundAttachments } from './handle';import ProgressText from '~/components/Chat/Messages/Content/ProgressText';+import { toolPanelSpacingClassName } from '../disclosure';import { sandboxStartingByToolCallId } from '~/store';import useLazyHighlight from './useLazyHighlight';import useToolCallState from './useToolCallState';@@ -168,7 +169,12 @@ export default function ExecuteCode({</div><div style={expandStyle}><div className="overflow-hidden" ref={expandRef}>- <div className="my-2 overflow-hidden rounded-lg border border-border-light bg-surface-secondary">+ <div+ className={cn(+ toolPanelSpacingClassName,+ 'overflow-hidden rounded-lg border border-border-light bg-surface-secondary',+ )}+ >{code && <CodeWindowHeader language={lang} code={code} />}{code && (<prediff --git a/client/src/components/Chat/Messages/Content/Parts/FileAuthoringCall.tsx b/client/src/components/Chat/Messages/Content/Parts/FileAuthoringCall.tsxindex 331677a00e..0fb96450b9 100644--- a/client/src/components/Chat/Messages/Content/Parts/FileAuthoringCall.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/FileAuthoringCall.tsx@@ -1,8 +1,15 @@import { useMemo } from 'react';import { FilePenLine, FilePlus2 } from 'lucide-react';import type { TAttachment, PartMetadata } from 'librechat-data-provider';+import DiffView, {+ parseUnifiedDiff,+ buildEditPreviewDiff,+ diffPreviewText,+ type TextEditPreview,+} from './DiffView';import parseJsonField, { parseJsonFieldOccurrences } from './parseJsonField';import ProgressText from '~/components/Chat/Messages/Content/ProgressText';+import { toolPanelSpacingClassName } from '../disclosure';import useToolCallState from './useToolCallState';import useLazyHighlight from './useLazyHighlight';import CodeWindowHeader from './CodeWindowHeader';@@ -18,11 +25,6 @@ type FileAuthoringToolName = 'create_file' | 'edit_file';type ToolCallArgs = string | Record<string, unknown> | undefined;-interface TextEditPreview {- oldText: string;- newText: string;-}-function hasDiff(output: string): boolean {return /\n@@\s/.test(output) || output.includes('\n--- ') || output.includes('\n+++ ');}@@ -49,60 +51,52 @@ function textValue(value: unknown): string {return typeof value === 'string' ? value : '';}-function editPreviewLines(prefix: '-' | '+', text: string): string {- return text- .split('\n')- .map((line) => `${prefix}${line}`)- .join('\n');-}--function formatEditPreview(edits: TextEditPreview[]): string {- return edits- .map((edit, index) => {- const suffix = edits.length > 1 ? ` ${index + 1}` : '';- return [- `--- old_text${suffix}`,- `+++ new_text${suffix}`,- '@@',- editPreviewLines('-', edit.oldText),- editPreviewLines('+', edit.newText),- ].join('\n');- })- .join('\n\n');+function coerceJsonValue(value: unknown): unknown {+ if (typeof value !== 'string') {+ return value;+ }+ try {+ return JSON.parse(value);+ } catch {+ return value;+ }}-function buildEditArgsPreview(args: ToolCallArgs): string {+/** Structured edits for the args preview. Never formatted into diff text:+ * `buildEditPreviewDiff` renders them directly, so no separator has to be+ * invented and later told apart from real content. */+function buildEditArgsPreview(args: ToolCallArgs): TextEditPreview[] {const parsed = parseArgsObject(args);- if (Array.isArray(parsed?.edits) && parsed.edits.length > 0) {- const edits = parsed.edits+ const edits = coerceJsonValue(parsed?.edits);+ if (Array.isArray(edits) && edits.length > 0) {+ return edits.map((edit): TextEditPreview | undefined => {- if (typeof edit !== 'object' || edit === null || Array.isArray(edit)) {+ const coercedEdit = coerceJsonValue(edit);+ if (typeof coercedEdit !== 'object' || coercedEdit === null || Array.isArray(coercedEdit)) {return undefined;}- const entry = edit as Record<string, unknown>;+ const entry = coercedEdit as Record<string, unknown>;const oldText = textValue(entry.old_text);const newText = textValue(entry.new_text);return oldText || newText ? { oldText, newText } : undefined;}).filter((edit): edit is TextEditPreview => !!edit);- return formatEditPreview(edits);}if (parsed) {const oldText = textValue(parsed.old_text);const newText = textValue(parsed.new_text);- return oldText || newText ? formatEditPreview([{ oldText, newText }]) : '';+ return oldText || newText ? [{ oldText, newText }] : [];}/** Partial JSON during streaming: pair up field occurrences in document order, covering both single-replacement and batched `edits` args */const oldTexts = parseJsonFieldOccurrences(args, 'old_text');const newTexts = parseJsonFieldOccurrences(args, 'new_text');const editCount = Math.max(oldTexts.length, newTexts.length);- const edits = Array.from({ length: editCount }, (_, index) => ({+ return Array.from({ length: editCount }, (_, index) => ({oldText: oldTexts[index] ?? '',newText: newTexts[index] ?? '',})).filter((edit) => edit.oldText || edit.newText);- return formatEditPreview(edits);}export default function FileAuthoringCall({@@ -134,22 +128,44 @@ export default function FileAuthoringCall({* or skill SKILL.md updates). The host-authored summary always opens with* `Created`/`Updated`, so key the finished label off it for truthfulness. */const overwrote = isCreate && output.startsWith('Updated ');- const filePath = useMemo(() => parseJsonField(args, 'file_path'), [args]);+ const filePath = useMemo(+ () => parseJsonField(args, 'path') || parseJsonField(args, 'file_path'),+ [args],+ );const intent = useToolCallIntent(args);const authoredContent = useMemo(() => parseJsonField(args, 'content'), [args]);- const editArgsPreview = useMemo(() => buildEditArgsPreview(args), [args]);- const fileName = filePath.split('/').pop() || filePath;+ const editArgs = useMemo(() => buildEditArgsPreview(args), [args]);+ const fileName = filePath.split('/').pop() || filePath || localize('com_ui_file').toLowerCase();const fileLang = useMemo(() => langFromPath(filePath), [filePath]);- const argsPreview = isCreate ? authoredContent : editArgsPreview;const outputIsDiff = hasDiff(output);- /** A diff in the output supersedes the args preview — it carries the input with real file context */- const preview = outputIsDiff ? output : argsPreview || output;+ /** A diff in the output supersedes the args preview: it carries the input+ * with real file context. Only the output is ever PARSED; the args preview+ * is built from structured edits, so it never round-trips through diff text+ * where a separator could be confused with a real changed line. */+ const parsedDiff = useMemo(() => {+ if (outputIsDiff) {+ return parseUnifiedDiff(output);+ }+ return !isCreate && editArgs.length > 0 ? buildEditPreviewDiff(editArgs) : null;+ }, [outputIsDiff, output, isCreate, editArgs]);+ /** Plain text for the non-diff pane, and the copy payload either way. A diff+ * in the output supersedes everything, including a create's authored+ * content: `create_file` overwriting an existing file returns a summary plus+ * a unified diff, and preferring the authored content there rendered that+ * diff twice, once through `DiffView` and again verbatim as the raw output+ * section. */+ const preview = useMemo(() => {+ if (outputIsDiff) {+ return output;+ }+ if (isCreate) {+ return authoredContent || output;+ }+ return parsedDiff ? diffPreviewText(parsedDiff) : output;+ }, [isCreate, authoredContent, outputIsDiff, output, parsedDiff]);const showOutputSection = !!output && preview !== output;- const previewIsDiff = outputIsDiff || (!isCreate && !!editArgsPreview && preview !== output);let previewLang = 'plaintext';- if (previewIsDiff) {- previewLang = 'diff';- } else if (isCreate && authoredContent && preview === authoredContent) {+ if (isCreate && authoredContent && preview === authoredContent) {previewLang = fileLang;}@@ -162,7 +178,7 @@ export default function FileAuthoringCall({runStepStatus,});- const highlighted = useLazyHighlight(preview || undefined, previewLang);+ const highlighted = useLazyHighlight(!parsedDiff && preview ? preview : undefined, previewLang);const { ref: previewPaneRef, onScroll: onPreviewPaneScroll } = useFollowScroll<HTMLPreElement>(highlighted ?? preview,phase === 'running',@@ -209,22 +225,39 @@ export default function FileAuthoringCall({<div style={expandStyle}><div className="overflow-hidden" ref={expandRef}>{!!preview && (- <div className="my-2 overflow-hidden rounded-lg border border-border-light bg-surface-secondary">- <CodeWindowHeader language={previewIsDiff ? 'diff' : fileName} code={preview} />- <pre- ref={previewPaneRef}- onScroll={onPreviewPaneScroll}- className="max-h-[300px] overflow-auto bg-surface-chat p-4 font-mono text-xs dark:bg-surface-primary-alt"- >- <code className={`hljs language-${previewLang} !whitespace-pre`}>- {highlighted ?? preview}- </code>- </pre>+ <div+ className={cn(+ toolPanelSpacingClassName,+ 'overflow-hidden rounded-lg border border-border-light bg-surface-secondary',+ )}+ >+ <CodeWindowHeader+ language={fileName}+ code={preview}+ diffStats={+ parsedDiff+ ? { additions: parsedDiff.additions, deletions: parsedDiff.deletions }+ : undefined+ }+ />+ {parsedDiff ? (+ <DiffView parsed={parsedDiff} />+ ) : (+ <pre+ ref={previewPaneRef}+ onScroll={onPreviewPaneScroll}+ className="max-h-[300px] overflow-auto bg-surface-chat p-4 font-mono text-xs dark:bg-surface-primary-alt"+ >+ <code className={`hljs language-${previewLang} !whitespace-pre`}>+ {highlighted ?? preview}+ </code>+ </pre>+ )}{showOutputSection && (<preclassName={cn(- 'max-h-[300px] overflow-auto whitespace-pre-wrap break-words border-t border-border-light px-3 py-2.5 font-mono text-xs',- phase === 'failed' ? 'text-status-error' : 'text-text-primary',+ 'max-h-[300px] overflow-auto whitespace-pre-wrap break-words border-t border-border-light px-3 py-2 font-mono text-xs',+ phase === 'failed' ? 'text-status-error' : 'text-text-secondary',)}>{output}diff --git a/client/src/components/Chat/Messages/Content/Parts/MemoryCall.tsx b/client/src/components/Chat/Messages/Content/Parts/MemoryCall.tsxnew file mode 100644index 0000000000..9b67b57e81--- /dev/null+++ b/client/src/components/Chat/Messages/Content/Parts/MemoryCall.tsx@@ -0,0 +1,154 @@+import { useMemo } from 'react';+import { Brain } from 'lucide-react';+import { Tools } from 'librechat-data-provider';+import type { PartMetadata, TAttachment, MemoryArtifact } from 'librechat-data-provider';+import ProgressText from '~/components/Chat/Messages/Content/ProgressText';+import { toolPanelSpacingClassName } from '../disclosure';+import useToolCallState from './useToolCallState';+import { AttachmentGroup } from './Attachment';+import parseJsonField from './parseJsonField';+import MemoryInfo from '../MemoryInfo';+import { useLocalize } from '~/hooks';+import { cn } from '~/utils';++type MemoryToolName = 'set_memory' | 'delete_memory';++export function isMemoryFailureOutput(toolName: MemoryToolName, output: string): boolean {+ const trimmed = output.trim();+ if (!trimmed) {+ return false;+ }+ return toolName === 'set_memory'+ ? !/^(?:Memory set for key|Memory saved\b)/i.test(trimmed)+ : !/^Memory deleted(?: for key|\.)/i.test(trimmed);+}++export default function MemoryCall({+ toolName,+ isSubmitting,+ runStepStatus,+ runStepDurationMs,+ initialProgress = 0.1,+ args,+ output = '',+ attachments,+ hideAttachments = false,+ onExpand,+}: {+ toolName: MemoryToolName;+ initialProgress: number;+ isSubmitting: boolean;+ runStepStatus?: PartMetadata['runStepStatus'];+ runStepDurationMs?: PartMetadata['runStepDurationMs'];+ args?: string | Record<string, unknown>;+ output?: string;+ attachments?: TAttachment[];+ hideAttachments?: boolean;+ onExpand?: () => void;+}) {+ const localize = useLocalize();+ const isSave = toolName === 'set_memory';+ const memoryKey = useMemo(() => parseJsonField(args, 'key'), [args]);+ const memoryValue = useMemo(() => parseJsonField(args, 'value'), [args]);+ const hasPanel = !!memoryKey || !!memoryValue;+ const memoryErrors = useMemo(() => {+ const errors: MemoryArtifact[] = [];+ for (const attachment of attachments ?? []) {+ const artifact = attachment[Tools.memory];+ if (artifact?.type === 'error') {+ errors.push(artifact);+ }+ }+ return errors;+ }, [attachments]);+ const memoryFailed = isMemoryFailureOutput(toolName, output) || memoryErrors.length > 0;++ const { showCode, toggleCode, expandStyle, expandRef, phase } = useToolCallState({+ initialProgress,+ isSubmitting,+ output,+ hasInput: hasPanel || memoryFailed || runStepStatus === 'failed',+ onExpand,+ runStepStatus,+ extraError: memoryFailed,+ });+ let finishedText = localize(isSave ? 'com_ui_memory_saved' : 'com_ui_memory_removed');+ if (phase === 'cancelled') {+ finishedText = localize('com_ui_cancelled');+ } else if (phase === 'failed') {+ finishedText = localize('com_ui_memory');+ }++ return (+ <>+ <div className="relative my-1 flex h-5 shrink-0 items-center gap-2.5">+ <ProgressText+ phase={phase}+ onClick={toggleCode}+ inProgressText={localize(isSave ? 'com_ui_memory_saving' : 'com_ui_memory_deleting')}+ finishedText={finishedText}+ durationMs={runStepDurationMs}+ subtitle={memoryKey || undefined}+ icon={+ <Brain+ className={cn(+ 'size-4 shrink-0 text-text-secondary',+ phase === 'running' && 'animate-pulse',+ )}+ aria-hidden="true"+ />+ }+ hasInput={hasPanel || phase === 'failed'}+ isExpanded={showCode}+ />+ </div>+ <div style={expandStyle}>+ <div className="overflow-hidden" ref={expandRef}>+ {(hasPanel || phase === 'failed') && (+ <div+ className={cn(+ toolPanelSpacingClassName,+ 'overflow-hidden rounded-lg border border-border-light bg-surface-secondary p-3',+ )}+ >+ {phase === 'failed' ? (+ <>+ <pre className="whitespace-pre-wrap break-words font-mono text-xs text-status-error">+ {output}+ </pre>+ <MemoryInfo memoryArtifacts={memoryErrors} />+ </>+ ) : (+ <>+ {memoryKey && (+ <div className="mb-1 text-xs font-bold uppercase tracking-wide text-text-secondary">+ {memoryKey}+ </div>+ )}+ {isSave && memoryValue && (+ <div className="whitespace-pre-wrap text-sm text-text-primary">+ {memoryValue}+ </div>+ )}+ {/* Only a completed delete actually removed anything. The+ panel opens as soon as the key streams in, and the phase+ can still land on cancelled, so an ungated confirmation+ claimed the memory was gone while the header said+ Cancelled. The key above already shows what was tried. */}+ {!isSave && phase === 'completed' && (+ <div className="text-sm italic text-text-secondary">+ {localize('com_ui_memory_deleted')}+ </div>+ )}+ </>+ )}+ </div>+ )}+ </div>+ </div>+ {!hideAttachments && attachments && attachments.length > 0 && (+ <AttachmentGroup attachments={attachments} />+ )}+ </>+ );+}diff --git a/client/src/components/Chat/Messages/Content/Parts/PendingSkillCall.tsx b/client/src/components/Chat/Messages/Content/Parts/PendingSkillCall.tsxindex cda1cafb4b..01db1f03e5 100644--- a/client/src/components/Chat/Messages/Content/Parts/PendingSkillCall.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/PendingSkillCall.tsx@@ -37,7 +37,7 @@ export default function PendingSkillCall({<div className={TOOL_ROW_CLASSES}><div className="progress-text-wrapper text-token-text-secondary relative -mt-[0.75px] h-5 w-full leading-5"><div- className="progress-text-content absolute left-0 top-0 max-w-full overflow-visible whitespace-nowrap"+ className="progress-text-content absolute left-0 right-0 top-0 max-w-full overflow-visible whitespace-nowrap"style={{ opacity: 1, transform: 'none' }}><div className="inline-flex w-full items-center gap-2">diff --git a/client/src/components/Chat/Messages/Content/Parts/ReadFileCall.tsx b/client/src/components/Chat/Messages/Content/Parts/ReadFileCall.tsxindex bcb5b4d11a..27a114b030 100644--- a/client/src/components/Chat/Messages/Content/Parts/ReadFileCall.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/ReadFileCall.tsx@@ -2,6 +2,7 @@ import { useMemo } from 'react';import { FileText } from 'lucide-react';import type { TAttachment, PartMetadata } from 'librechat-data-provider';import ProgressText from '~/components/Chat/Messages/Content/ProgressText';+import { toolPanelSpacingClassName } from '../disclosure';import useToolCallState from './useToolCallState';import useLazyHighlight from './useLazyHighlight';import CodeWindowHeader from './CodeWindowHeader';@@ -85,7 +86,10 @@ export default function ReadFileCall({onExpand?: () => void;}) {const localize = useLocalize();- const filePath = useMemo(() => parseJsonField(args, 'file_path'), [args]);+ const filePath = useMemo(+ () => parseJsonField(args, 'path') || parseJsonField(args, 'file_path'),+ [args],+ );const intent = useToolCallIntent(args);const fileName = filePath.split('/').pop() || filePath;const lang = useMemo(() => langFromPath(filePath), [filePath]);@@ -130,7 +134,12 @@ export default function ReadFileCall({<div style={expandStyle}><div className="overflow-hidden" ref={expandRef}>{hasOutput && (- <div className="my-2 overflow-hidden rounded-lg border border-border-light bg-surface-secondary">+ <div+ className={cn(+ toolPanelSpacingClassName,+ 'overflow-hidden rounded-lg border border-border-light bg-surface-secondary',+ )}+ ><CodeWindowHeader language={fileName} code={output} /><pre className="max-h-[300px] overflow-auto bg-surface-chat p-4 font-mono text-xs dark:bg-surface-primary-alt"><code className={`hljs language-${lang} !whitespace-pre`}>diff --git a/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx b/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsxindex bf2dd73e70..01bff0c253 100644--- a/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx@@ -1,14 +1,111 @@-import { memo, useMemo, useState, useCallback, useRef, useId } from 'react';+import { memo, useMemo, useState, useEffect, useCallback, useRef, useId } from 'react';+import copy from 'copy-to-clipboard';import { useAtomValue } from 'jotai';+import { Lightbulb, ChevronDown } from 'lucide-react';import { ContentTypes } from 'librechat-data-provider';+import { Button, disclosureChevronVariants } from '@librechat/client';import type { MouseEvent, FocusEvent } from 'react';-import { ThinkingContent, ThinkingButton, ThinkingLabel, FloatingThinkingBar } from './Thinking';+import {+ ThinkingContent,+ ThinkingButton,+ ThinkingLabel,+ FloatingThinkingBar,+ useInViewport,+} from './Thinking';import { useLocalize, useExpandCollapse, useLazyCollapseBody } from '~/hooks';import useSmoothStreaming from '~/hooks/Messages/useSmoothStreaming';+import CopyButton from '~/components/Messages/Content/CopyButton';import { showThinkingAtom } from '~/store/showThinking';+import { fontSizeAtom } from '~/store/fontSize';import { useMessageContext } from '~/Providers';import { cn } from '~/utils';+const stripThinkTags = (reasoning: string): string =>+ reasoning+ .replace(/^<think>\s*/, '')+ .replace(/\s*<\/think>$/, '')+ .trim();++const PEEK_SENTENCES = 4;++/** Tail of streaming reasoning, specifically the last few sentences, for the collapsed+ * live peek. Bounds work on long reasoning by scanning only the trailing+ * slice before splitting on sentence boundaries. */+const lastSentences = (text: string): string => {+ const tail = text.trim().slice(-1200);+ if (!tail) {+ return '';+ }+ const sentences = tail.split(/(?<=[.!?])\s+/);+ return sentences.slice(-PEEK_SENTENCES).join(' ').trim();+};++/** Symmetric top + bottom edge fade so streaming text dissolves in at the+ * bottom and out at the top, framed by the same rounded outline the expanded+ * panel uses.+ *+ * Custom-CSS exception, narrowly scoped: this is a `mask-image` stencil, not+ * paint. Only the alpha channel is read, so `#000` means "keep this pixel"+ * and `transparent` means "hide it". The hue never reaches the screen and no+ * theme could meaningfully restyle it. Routing it through a theme role would+ * invite a token with alpha, which would silently wash out the text the mask+ * is supposed to keep. Tailwind has no mask-image utility that expresses a+ * four-stop gradient with `calc()` offsets, hence the inline style. */+const PEEK_FADE =+ 'linear-gradient(to bottom, transparent, #000 1.25rem, #000 calc(100% - 1.25rem), transparent)';++/**+ * Collapsed live preview of streaming reasoning. Mirrors the expanded thought+ * panel. It uses the same rounded outline and text treatment, but with a border instead+ * of a surface fill, showing the trailing few sentences in a short,+ * bottom-pinned window whose top and bottom edges fade out, so the newest+ * thought stays in view while older lines scroll up and dissolve (the "thinking+ * out loud" treatment popularized by Grok). Decorative only (aria-hidden); the+ * toggle button above it provides the accessible control.+ */+const StreamingThoughtPeek = memo(({ text }: { text: string }) => {+ const ref = useRef<HTMLDivElement>(null);+ const fontSize = useAtomValue(fontSizeAtom);+ const peek = useMemo(() => lastSentences(text), [text]);++ /** Pin to the newest content as tokens arrive. `overflow-hidden` elements+ * are still scrollable programmatically, so the tail stays in view without+ * exposing a scrollbar. */+ useEffect(() => {+ const el = ref.current;+ if (el) {+ el.scrollTop = el.scrollHeight;+ }+ }, [peek]);++ if (!peek) {+ return null;+ }++ return (+ <div+ aria-hidden="true"+ className="mt-1 overflow-hidden rounded-2xl border border-border-light px-4 py-3"+ >+ <div+ ref={ref}+ className={cn(+ /** Fixed-height window the text scrolls through. The one-line top pad+ * keeps the first streaming line below the top fade (a blank line+ * above it) instead of jammed against the faded edge. */+ 'h-[5.5rem] overflow-hidden whitespace-pre-wrap break-words pt-[26px] leading-[26px] text-text-primary',+ fontSize,+ )}+ style={{ maskImage: PEEK_FADE, WebkitMaskImage: PEEK_FADE }}+ >+ {peek}+ </div>+ </div>+ );+});++StreamingThoughtPeek.displayName = 'StreamingThoughtPeek';+type ReasoningProps = {reasoning: string;isLast: boolean;@@ -57,17 +154,13 @@ const Reasoning = memo((props: ReasoningProps) => {const [isExpanded, setIsExpanded] = useState(showThinking);const [isBarVisible, setIsBarVisible] = useState(false);const containerRef = useRef<HTMLDivElement>(null);+ const { ref: headerRef, inViewport: headerInViewport } = useInViewport();const { style: expandStyle, ref: expandRef } = useExpandCollapse(isExpanded);const { shouldRenderBody, mountBody, handleTransitionEnd } = useLazyCollapseBody(isExpanded);const { isSubmitting, isLatestMessage, nextType } = useMessageContext();// Strip <think> tags from the reasoning content (modern format)- const reasoningText = useMemo(() => {- return reasoning- .replace(/^<think>\s*/, '')- .replace(/\s*<\/think>$/, '')- .trim();- }, [reasoning]);+ const reasoningText = useMemo(() => stripThinkTags(reasoning), [reasoning]);const handleClick = useCallback((e: MouseEvent<HTMLButtonElement>) => {@@ -124,7 +217,7 @@ const Reasoning = memo((props: ReasoningProps) => {onBlur={handleBlur}><div className="group/thinking-container">- <div className="mb-2 pb-2 pt-2">+ <div className="mb-2 pb-2 pt-2" ref={headerRef}><ThinkingButtonisExpanded={isExpanded}onClick={handleClick}@@ -136,32 +229,37 @@ const Reasoning = memo((props: ReasoningProps) => {}shimmerLabel={effectiveIsSubmitting && isLast}/>+ {!isExpanded && effectiveIsSubmitting && isLast && (+ <StreamingThoughtPeek text={reasoningText} />+ )}</div><divid={contentId}role="group"aria-label={label}aria-hidden={!isExpanded || undefined}- className={cn(nextType !== ContentTypes.THINK && isExpanded && 'mb-4')}style={expandStyle}onTransitionEnd={handleTransitionEnd}>- <div className="relative overflow-hidden" ref={expandRef}>+ <div+ className={cn('overflow-hidden', nextType !== ContentTypes.THINK && 'pb-4')}+ ref={expandRef}+ >{shouldRenderBody && (- <>+ <div className="relative"><ThinkingContentanimate={smoothStreaming && effectiveIsSubmitting && isLast && isExpanded}>{reasoningText}</ThinkingContent><FloatingThinkingBar- isVisible={isBarVisible && isExpanded}+ isVisible={isBarVisible && isExpanded && !headerInViewport}isExpanded={isExpanded}onClick={handleClick}content={reasoningText}contentId={contentId}/>- </>+ </div>)}</div></div>@@ -170,4 +268,159 @@ const Reasoning = memo((props: ReasoningProps) => {);});+Reasoning.displayName = 'Reasoning';++type ReasoningCompactProps = {+ reasoning: string;+ label: string;+ /** The host's thoughts-visible preference, supplied by the group rather+ * than read from the app store, so a grouped thought stays movable with+ * the feature that renders it. */+ showThinking: boolean;+ isAfterTool?: boolean;+ /** True while this is the reasoning part currently streaming. Drives the+ * collapsed grok-style live peek. */+ isStreaming?: boolean;+};++/**+ * Compact reasoning row for use INSIDE a ToolCallGroup. Keeps the tool-row+ * header rhythm (icon + label + chevron) so an interleaved thought reads as a+ * sibling of the surrounding tool calls, while retaining the standalone+ * {@link Reasoning} affordances: a hover-revealed copy button on the header and+ * a floating collapse + copy bar inside the rounded content panel.+ */+export const ReasoningCompact = memo(+ ({+ reasoning,+ label,+ showThinking,+ isAfterTool = false,+ isStreaming = false,+ }: ReasoningCompactProps) => {+ const contentId = useId();+ const localize = useLocalize();+ const fontSize = useAtomValue(fontSizeAtom);+ const [isExpanded, setIsExpanded] = useState(showThinking);+ const [isBarVisible, setIsBarVisible] = useState(false);+ const [isCopied, setIsCopied] = useState(false);+ const containerRef = useRef<HTMLDivElement>(null);+ const { ref: headerRef, inViewport: headerInViewport } = useInViewport();+ const { style: expandStyle, ref: expandRef } = useExpandCollapse(isExpanded);+ /** Collapsed is the default whenever thoughts are hidden, and a streaming+ * THINK part re-renders on every delta. Keeping the full text mounted+ * behind the invisible panel made long reasoning streams progressively+ * more expensive on top of the visible peek. */+ const { shouldRenderBody, mountBody, handleTransitionEnd } = useLazyCollapseBody(isExpanded);++ const reasoningText = useMemo(() => stripThinkTags(reasoning), [reasoning]);++ const handleToggle = useCallback(+ (e: MouseEvent<HTMLButtonElement>) => {+ e.preventDefault();+ mountBody();+ setIsExpanded((prev) => !prev);+ },+ [mountBody],+ );++ const handleCopy = useCallback(() => {+ if (!copy(reasoningText, { format: 'text/plain' })) {+ return;+ }+ setIsCopied(true);+ setTimeout(() => setIsCopied(false), 2000);+ }, [reasoningText]);++ const revealBar = useCallback(() => setIsBarVisible(true), []);+ const hideBar = useCallback(() => {+ if (!containerRef.current?.contains(document.activeElement)) {+ setIsBarVisible(false);+ }+ }, []);+ const handleBlur = useCallback((e: FocusEvent) => {+ if (!containerRef.current?.contains(e.relatedTarget as Node)) {+ setIsBarVisible(false);+ }+ }, []);++ if (!reasoningText) {+ return null;+ }++ return (+ <div+ ref={containerRef}+ className={cn('group/reasoning-compact mb-1', isAfterTool ? 'mt-0' : 'mt-1')}+ onMouseEnter={revealBar}+ onMouseLeave={hideBar}+ onFocus={revealBar}+ onBlur={handleBlur}+ >+ <div ref={headerRef} className="relative flex h-5 shrink-0 items-center gap-1.5">+ <Button+ variant="ghost"+ onClick={handleToggle}+ aria-expanded={isExpanded}+ aria-controls={contentId}+ className="group/disclosure h-auto min-w-0 flex-1 justify-start gap-2 rounded-none p-0 font-normal text-text-secondary hover:bg-transparent"+ >+ <Lightbulb className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />+ <span className="tool-status-text font-medium">{label}</span>+ <ChevronDown+ className={cn(+ disclosureChevronVariants({ expanded: isExpanded }),+ 'size-4 translate-y-[1px]',+ )}+ aria-hidden="true"+ />+ </Button>+ {isExpanded && (+ <CopyButton+ isCopied={isCopied}+ iconOnly+ onClick={handleCopy}+ label={localize('com_ui_copy_thoughts_to_clipboard')}+ copiedLabel={localize('com_ui_copied_to_clipboard')}+ className={cn(+ 'shrink-0 opacity-0 transition-opacity',+ 'group-focus-within/reasoning-compact:opacity-100 group-hover/reasoning-compact:opacity-100',+ 'focus-visible:opacity-100',+ )}+ />+ )}+ </div>+ {!isExpanded && isStreaming && <StreamingThoughtPeek text={reasoningText} />}+ <div+ id={contentId}+ role="group"+ aria-label={label}+ aria-hidden={!isExpanded || undefined}+ style={expandStyle}+ onTransitionEnd={handleTransitionEnd}+ >+ <div className="overflow-hidden" ref={expandRef}>+ {shouldRenderBody && (+ <div className="relative my-2 rounded-2xl border border-border-light bg-surface-secondary p-4 pb-9 text-text-secondary">+ <p className={cn('whitespace-pre-wrap leading-[26px]', fontSize)}>+ {reasoningText}+ </p>+ <FloatingThinkingBar+ isVisible={isBarVisible && isExpanded && !headerInViewport}+ isExpanded={isExpanded}+ onClick={handleToggle}+ content={reasoningText}+ contentId={contentId}+ />+ </div>+ )}+ </div>+ </div>+ </div>+ );+ },+);++ReasoningCompact.displayName = 'ReasoningCompact';+export default Reasoning;diff --git a/client/src/components/Chat/Messages/Content/Parts/SkillCall.tsx b/client/src/components/Chat/Messages/Content/Parts/SkillCall.tsxindex 859605a33a..8a58ad08dc 100644--- a/client/src/components/Chat/Messages/Content/Parts/SkillCall.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/SkillCall.tsx@@ -2,6 +2,7 @@ import { useMemo } from 'react';import { ScrollText } from 'lucide-react';import type { TAttachment, PartMetadata } from 'librechat-data-provider';import ProgressText from '~/components/Chat/Messages/Content/ProgressText';+import { toolPanelSpacingClassName } from '../disclosure';import useToolCallState from './useToolCallState';import { AttachmentGroup } from './Attachment';import parseJsonField from './parseJsonField';@@ -33,14 +34,15 @@ export default function SkillCall({onExpand?: () => void;}) {const localize = useLocalize();- const skillName = useMemo(() => parseJsonField(args, 'skillName'), [args]);+ const parsedSkillName = useMemo(() => parseJsonField(args, 'skillName'), [args]);+ const skillName = parsedSkillName || localize('com_ui_skill').toLowerCase();const intent = useToolCallIntent(args);const { showCode, toggleCode, expandStyle, expandRef, phase, hasOutput } = useToolCallState({initialProgress,isSubmitting,output,- hasInput: !!skillName,+ hasInput: !!parsedSkillName,onExpand,runStepStatus,});@@ -67,14 +69,19 @@ export default function SkillCall({aria-hidden="true"/>}- hasInput={!!skillName || hasOutput}+ hasInput={!!parsedSkillName || hasOutput}isExpanded={showCode}/></div><div style={expandStyle}><div className="overflow-hidden" ref={expandRef}>{hasOutput && (- <div className="my-2 overflow-hidden rounded-lg border border-border-light bg-surface-secondary">+ <div+ className={cn(+ toolPanelSpacingClassName,+ 'overflow-hidden rounded-lg border border-border-light bg-surface-secondary',+ )}+ ><div className="bg-surface-primary-alt p-4 text-xs dark:bg-transparent"><div className="mb-1.5 text-[10px] font-medium uppercase tracking-wide text-text-secondary">{localize('com_ui_output')}diff --git a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsxindex c87cb854d3..fa6d35b048 100644--- a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx@@ -388,7 +388,7 @@ export default function SubagentCall({data-subagent-parent-message={parentMessageId}data-subagent-part-index={partIndex}className={cn(- 'my-1.5 flex w-full flex-col gap-1 rounded-lg border border-border-light bg-surface-secondary px-3 py-2 text-left transition',+ 'my-2 flex w-full flex-col gap-1 rounded-lg border border-border-light bg-surface-secondary px-3 py-2 text-left transition',canOpenDetails ? 'group hover:bg-surface-tertiary' : 'cursor-default opacity-80',running && !detachedStatusUnknown && 'animate-pulse-slow',)}diff --git a/client/src/components/Chat/Messages/Content/Parts/Summary.tsx b/client/src/components/Chat/Messages/Content/Parts/Summary.tsxindex 1398ec286f..770a98a9e1 100644--- a/client/src/components/Chat/Messages/Content/Parts/Summary.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/Summary.tsx@@ -12,7 +12,7 @@ import { cn } from '~/utils';type SummaryProps = Pick<SummaryContentPart,- 'content' | 'model' | 'provider' | 'tokenCount' | 'summarizing'+ 'content' | 'model' | 'provider' | 'tokenCount' | 'summarizing' | 'failed'>;function useCopyToClipboard(content?: string) {@@ -203,115 +203,120 @@ const FloatingSummaryBar = memo(},);-const Summary = memo(({ content, model, provider, tokenCount, summarizing }: SummaryProps) => {- const contentId = useId();- const localize = useLocalize();- const [isExpanded, setIsExpanded] = useState(false);- const [isBarVisible, setIsBarVisible] = useState(false);- const containerRef = useRef<HTMLDivElement>(null);- const { isSubmitting, isLatestMessage } = useMessageContext();+const Summary = memo(+ ({ content, model, provider, tokenCount, summarizing, failed }: SummaryProps) => {+ const contentId = useId();+ const localize = useLocalize();+ const [isExpanded, setIsExpanded] = useState(false);+ const [isBarVisible, setIsBarVisible] = useState(false);+ const containerRef = useRef<HTMLDivElement>(null);+ const { isSubmitting, isLatestMessage } = useMessageContext();- const text = useMemo(- () =>- (content ?? [])- .map((block) => ('text' in block && typeof block.text === 'string' ? block.text : ''))- .join(''),- [content],- );- const { isCopied, handleCopy } = useCopyToClipboard(text);+ const text = useMemo(+ () =>+ (content ?? [])+ .map((block) => ('text' in block && typeof block.text === 'string' ? block.text : ''))+ .join(''),+ [content],+ );+ const { isCopied, handleCopy } = useCopyToClipboard(text);- const handleClick = useCallback((e: MouseEvent<HTMLButtonElement>) => {- e.preventDefault();- setIsExpanded((prev) => !prev);- }, []);+ const handleClick = useCallback((e: MouseEvent<HTMLButtonElement>) => {+ e.preventDefault();+ setIsExpanded((prev) => !prev);+ }, []);- const handleFocus = useCallback(() => setIsBarVisible(true), []);- const handleBlur = useCallback((e: FocusEvent) => {- if (!containerRef.current?.contains(e.relatedTarget as Node)) {- setIsBarVisible(false);- }- }, []);- const handleMouseEnter = useCallback(() => setIsBarVisible(true), []);- const handleMouseLeave = useCallback(() => {- if (!containerRef.current?.contains(document.activeElement)) {- setIsBarVisible(false);- }- }, []);+ const handleFocus = useCallback(() => setIsBarVisible(true), []);+ const handleBlur = useCallback((e: FocusEvent) => {+ if (!containerRef.current?.contains(e.relatedTarget as Node)) {+ setIsBarVisible(false);+ }+ }, []);+ const handleMouseEnter = useCallback(() => setIsBarVisible(true), []);+ const handleMouseLeave = useCallback(() => {+ if (!containerRef.current?.contains(document.activeElement)) {+ setIsBarVisible(false);+ }+ }, []);- const effectiveIsSubmitting = isLatestMessage ? isSubmitting : false;- const isActivelyStreaming = !!summarizing && !!effectiveIsSubmitting;+ const effectiveIsSubmitting = isLatestMessage ? isSubmitting : false;+ const isActivelyStreaming = !!summarizing && !!effectiveIsSubmitting;- const meta = useMemo(() => {- const parts: string[] = [];- if (provider || model) {- parts.push([provider, model].filter(Boolean).join('/'));- }- if (tokenCount != null && tokenCount > 0) {- parts.push(`${tokenCount} ${localize('com_ui_tokens')}`);- }- return parts.length > 0 ? parts.join(' \u00b7 ') : undefined;- }, [model, provider, tokenCount, localize]);+ const meta = useMemo(() => {+ const parts: string[] = [];+ if (provider || model) {+ parts.push([provider, model].filter(Boolean).join('/'));+ }+ if (tokenCount != null && tokenCount > 0) {+ parts.push(`${tokenCount} ${localize('com_ui_tokens')}`);+ }+ return parts.length > 0 ? parts.join(' \u00b7 ') : undefined;+ }, [model, provider, tokenCount, localize]);- const label = useMemo(- () =>- isActivelyStreaming- ? localize('com_ui_summarizing')- : localize('com_ui_conversation_summarized'),- [isActivelyStreaming, localize],- );+ /** A failed round keeps whatever deltas already streamed in, so the label+ * must not claim the conversation was summarized. */+ const label = useMemo(() => {+ if (isActivelyStreaming) {+ return localize('com_ui_summarizing');+ }+ return failed+ ? localize('com_ui_summarize_failed')+ : localize('com_ui_conversation_summarized');+ }, [isActivelyStreaming, failed, localize]);- if (!summarizing && !text) {- return null;- }+ if (!summarizing && !text) {+ return null;+ }- return (- <div- ref={containerRef}- className="group/summary"- onMouseEnter={handleMouseEnter}- onMouseLeave={handleMouseLeave}- onFocus={handleFocus}- onBlur={handleBlur}- >- <div className="group/summary-container">- <div className="mb-2 pb-2 pt-2">- <SummaryButton- isExpanded={isExpanded}- onClick={handleClick}- label={label}- content={text}- contentId={contentId}- showCopyButton={!isActivelyStreaming}- isCopied={isCopied}- onCopy={handleCopy}- />- </div>- <div- id={contentId}- role="region"- aria-label={label}- aria-hidden={!isExpanded || undefined}- className={cn('grid transition-all duration-300 ease-out', isExpanded && 'mb-4')}- style={{- gridTemplateRows: isExpanded ? '1fr' : '0fr',- }}- >- <div className="relative overflow-hidden">- <SummaryContent meta={meta}>{text}</SummaryContent>- <FloatingSummaryBar- isVisible={isBarVisible && isExpanded}+ return (+ <div+ ref={containerRef}+ className="group/summary"+ onMouseEnter={handleMouseEnter}+ onMouseLeave={handleMouseLeave}+ onFocus={handleFocus}+ onBlur={handleBlur}+ >+ <div className="group/summary-container">+ <div className="mb-2 pb-2 pt-2">+ <SummaryButton+ isExpanded={isExpanded}onClick={handleClick}+ label={label}content={text}contentId={contentId}+ showCopyButton={!isActivelyStreaming}isCopied={isCopied}onCopy={handleCopy}/></div>+ <div+ id={contentId}+ role="region"+ aria-label={label}+ aria-hidden={!isExpanded || undefined}+ className={cn('grid transition-all duration-300 ease-out', isExpanded && 'mb-4')}+ style={{+ gridTemplateRows: isExpanded ? '1fr' : '0fr',+ }}+ >+ <div className="relative overflow-hidden">+ <SummaryContent meta={meta}>{text}</SummaryContent>+ <FloatingSummaryBar+ isVisible={isBarVisible && isExpanded}+ onClick={handleClick}+ content={text}+ contentId={contentId}+ isCopied={isCopied}+ onCopy={handleCopy}+ />+ </div>+ </div></div></div>- </div>- );-});+ );+ },+);SummaryContent.displayName = 'SummaryContent';SummaryButton.displayName = 'SummaryButton';diff --git a/client/src/components/Chat/Messages/Content/Parts/Thinking.tsx b/client/src/components/Chat/Messages/Content/Parts/Thinking.tsxindex 6cac5568d9..5b8bc23155 100644--- a/client/src/components/Chat/Messages/Content/Parts/Thinking.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/Thinking.tsx@@ -1,9 +1,19 @@-import { useState, useMemo, memo, useCallback, useRef, useId, type MouseEvent } from 'react';+import {+ useState,+ useMemo,+ memo,+ useEffect,+ useCallback,+ useRef,+ useId,+ type MouseEvent,+} from 'react';import { useAtomValue } from 'jotai';import { Lightbulb, ChevronDown } from 'lucide-react';import { Button, MorphIcon, TooltipAnchor } from '@librechat/client';-import { Copy, Check, ChevronUp as ChevronUpNode, ChevronDown as ChevronDownNode } from 'lucide';+import { ChevronUp as ChevronUpNode, ChevronDown as ChevronDownNode } from 'lucide';import type { FocusEvent, FC } from 'react';+import CopyButton from '~/components/Messages/Content/CopyButton';import { useLocalize, useExpandCollapse } from '~/hooks';import { showThinkingAtom } from '~/store/showThinking';import { fontSizeAtom } from '~/store/fontSize';@@ -11,6 +21,34 @@ import { AnimatedText } from '../animate';import { ROW_GLYPH_SLOT } from '../rows';import { cn } from '~/utils';+/**+ * Tracks whether the referenced element is within the viewport. Mirrors the+ * CodeBlock pattern: the header copy/collapse controls live at the top, and the+ * floating bottom-right bar only takes over once the header scrolls out of view.+ */+export function useInViewport(): {+ ref: React.RefObject<HTMLDivElement>;+ inViewport: boolean;+} {+ const ref = useRef<HTMLDivElement>(null);+ const [inViewport, setInViewport] = useState(true);++ useEffect(() => {+ const el = ref.current;+ if (!el) {+ return;+ }+ const observer = new IntersectionObserver(([entry]) => setInViewport(entry.isIntersecting), {+ root: null,+ threshold: 0,+ });+ observer.observe(el);+ return () => observer.disconnect();+ }, []);++ return { ref, inViewport };+}+/*** ThinkingContent - Displays the actual thinking/reasoning content* Used by both legacy text-based messages and modern content parts@@ -63,27 +101,23 @@ export const ThinkingButton = memo(const [isCopied, setIsCopied] = useState(false);- const handleCopy = useCallback(- (e: MouseEvent<HTMLButtonElement>) => {- e.stopPropagation();- if (content) {- navigator.clipboard.writeText(content);- setIsCopied(true);- setTimeout(() => setIsCopied(false), 2000);- }- },- [content],- );+ const handleCopy = useCallback(() => {+ if (content) {+ navigator.clipboard.writeText(content);+ setIsCopied(true);+ setTimeout(() => setIsCopied(false), 2000);+ }+ }, [content]);return (- <div className="group/thinking flex w-full items-center justify-between gap-2">+ <div className="group/thinking relative flex w-full items-center"><buttontype="button"onClick={onClick}aria-expanded={isExpanded}aria-controls={contentId}className={cn(- 'group/button flex flex-1 items-center justify-start rounded-lg leading-[18px]',+ 'group/button flex flex-1 items-center justify-start rounded-lg pr-10 leading-[18px]',fontSize,)}>@@ -135,32 +169,19 @@ export const ThinkingButton = memo()}</span></button>- {content && showCopyButton && (- <Button- variant="ghost"- size="icon"+ {content && showCopyButton && isExpanded && (+ <CopyButton+ isCopied={isCopied}+ iconOnlyonClick={handleCopy}- aria-label={- isCopied- ? localize('com_ui_copied_to_clipboard')- : localize('com_ui_copy_thoughts_to_clipboard')- }+ label={localize('com_ui_copy_thoughts_to_clipboard')}+ copiedLabel={localize('com_ui_copied_to_clipboard')}className={cn(- 'size-auto gap-0 rounded-lg p-1.5 text-text-secondary-alt',- isExpanded- ? 'opacity-0 group-focus-within/thinking-container:opacity-100 group-hover/thinking-container:opacity-100'- : 'opacity-0',- 'hover:bg-surface-hover hover:text-text-primary',- 'focus-visible:opacity-100 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-text-primary',+ 'absolute right-0 top-1/2 -translate-y-1/2 opacity-0 transition-opacity',+ 'group-focus-within/thinking-container:opacity-100 group-hover/thinking-container:opacity-100',+ 'focus-visible:opacity-100',)}- >- <span className="sr-only">- {isCopied- ? localize('com_ui_copied_to_clipboard')- : localize('com_ui_copy_thoughts_to_clipboard')}- </span>- <MorphIcon icon={isCopied ? Check : Copy} size={18} />- </Button>+ />)}</div>);@@ -212,26 +233,18 @@ export const FloatingThinkingBar = memo(const localize = useLocalize();const [isCopied, setIsCopied] = useState(false);- const handleCopy = useCallback(- (e: MouseEvent<HTMLButtonElement>) => {- e.stopPropagation();- if (content) {- navigator.clipboard.writeText(content);- setIsCopied(true);- setTimeout(() => setIsCopied(false), 2000);- }- },- [content],- );+ const handleCopy = useCallback(() => {+ if (content) {+ navigator.clipboard.writeText(content);+ setIsCopied(true);+ setTimeout(() => setIsCopied(false), 2000);+ }+ }, [content]);const collapseTooltip = isExpanded? localize('com_ui_collapse_thoughts'): localize('com_ui_expand_thoughts');- const copyTooltip = isCopied- ? localize('com_ui_copied_to_clipboard')- : localize('com_ui_copy_thoughts_to_clipboard');-return (<divclassName={cn(@@ -242,44 +255,31 @@ export const FloatingThinkingBar = memo(<TooltipAnchordescription={collapseTooltip}render={- <button+ <Button+ variant="ghost"+ size="icon-sm"type="button"tabIndex={isVisible ? 0 : -1}onClick={onClick}aria-label={collapseTooltip}aria-expanded={isExpanded}aria-controls={contentId}- className={cn(- 'flex items-center justify-center rounded p-1.5 text-text-tertiary',- 'hover:bg-surface-hover hover:text-text-primary',- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy',- )}><MorphIconicon={isExpanded ? ChevronUpNode : ChevronDownNode}className="h-[18px] w-[18px]"/>- </button>+ </Button>}/>{content && (- <TooltipAnchor- description={copyTooltip}- render={- <button- type="button"- tabIndex={isVisible ? 0 : -1}- onClick={handleCopy}- aria-label={copyTooltip}- className={cn(- 'flex items-center justify-center rounded p-1.5 text-text-tertiary',- 'hover:bg-surface-hover hover:text-text-primary',- 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy',- )}- >- <MorphIcon icon={isCopied ? Check : Copy} size={18} />- </button>- }+ <CopyButton+ isCopied={isCopied}+ iconOnly+ tabIndex={isVisible ? 0 : -1}+ onClick={handleCopy}+ label={localize('com_ui_copy_thoughts_to_clipboard')}+ copiedLabel={localize('com_ui_copied_to_clipboard')}/>)}</div>@@ -308,6 +308,7 @@ const Thinking: React.ElementType = memo(({ children }: { children: React.ReactNconst [isExpanded, setIsExpanded] = useState(showThinking);const [isBarVisible, setIsBarVisible] = useState(false);const containerRef = useRef<HTMLDivElement>(null);+ const { ref: headerRef, inViewport: headerInViewport } = useInViewport();const contentId = useId();const { style: expandStyle, ref: expandRef } = useExpandCollapse(isExpanded);@@ -359,7 +360,7 @@ const Thinking: React.ElementType = memo(({ children }: { children: React.ReactNonFocus={handleFocus}onBlur={handleBlur}>- <div className="mb-4 pb-2 pt-2">+ <div className="mb-4 pb-2 pt-2" ref={headerRef}><ThinkingButtonisExpanded={isExpanded}onClick={handleClick}@@ -373,18 +374,22 @@ const Thinking: React.ElementType = memo(({ children }: { children: React.ReactNrole="group"aria-label={label}aria-hidden={!isExpanded || undefined}- className={cn(isExpanded && 'mb-8')}style={expandStyle}>- <div className="relative overflow-hidden" ref={expandRef}>- <ThinkingContent>{children}</ThinkingContent>- <FloatingThinkingBar- isVisible={isBarVisible && isExpanded}- isExpanded={isExpanded}- onClick={handleClick}- content={textContent}- contentId={contentId}- />+ {/** Trailing gap lives inside the animated grid track (padding), not as+ * an expand-only margin on the grid container, so it grows with the+ * height instead of snapping in and jumping the content below. */}+ <div className="overflow-hidden pb-8" ref={expandRef}>+ <div className="relative">+ <ThinkingContent>{children}</ThinkingContent>+ <FloatingThinkingBar+ isVisible={isBarVisible && isExpanded && !headerInViewport}+ isExpanded={isExpanded}+ onClick={handleClick}+ content={textContent}+ contentId={contentId}+ />+ </div></div></div></div>diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/DiffView.test.ts b/client/src/components/Chat/Messages/Content/Parts/__tests__/DiffView.test.tsnew file mode 100644index 0000000000..c8c031dcd6--- /dev/null+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/DiffView.test.ts@@ -0,0 +1,105 @@+import { parseUnifiedDiff, buildEditPreviewDiff } from '../DiffView';++describe('parseUnifiedDiff', () => {+ it('drops file headers but keeps changed lines that begin with header markers', () => {+ const parsed = parseUnifiedDiff(+ [+ '--- a/example.txt',+ '+++ b/example.txt',+ '@@ -4,2 +4,2 @@',+ '--- deleted text',+ '+++ added text',+ ' unchanged',+ ].join('\n'),+ );++ expect(parsed).toEqual({+ additions: 1,+ deletions: 1,+ hasLineNumbers: true,+ lines: [+ { type: 'hunk', text: '@@ -4,2 +4,2 @@' },+ { type: 'del', text: '-- deleted text', oldLine: 4 },+ { type: 'add', text: '++ added text', newLine: 4 },+ { type: 'context', text: 'unchanged', oldLine: 5, newLine: 5 },+ ],+ });+ });++ it('keeps the same changed lines after an argless streaming hunk marker', () => {+ const parsed = parseUnifiedDiff(+ ['--- old_text', '+++ new_text', '@@', '--- deleted text', '+++ added text'].join('\n'),+ );++ expect(parsed.lines).toEqual([+ { type: 'hunk', text: '' },+ { type: 'del', text: '-- deleted text', oldLine: undefined },+ { type: 'add', text: '++ added text', newLine: undefined },+ ]);+ expect(parsed.additions).toBe(1);+ expect(parsed.deletions).toBe(1);+ });++ it('counts a batched edit preview from its structured edits', () => {+ /** Built directly rather than formatted into diff text and parsed back:+ * the separators that round trip needed were byte-identical to a real+ * changed line, so no parser could tell them apart. */+ const parsed = buildEditPreviewDiff([+ { oldText: 'first old', newText: 'first new' },+ { oldText: 'second old', newText: 'second new' },+ ]);++ expect(parsed.deletions).toBe(2);+ expect(parsed.additions).toBe(2);+ expect(parsed.hasLineNumbers).toBe(false);+ expect(parsed.lines).toEqual([+ { type: 'del', text: 'first old' },+ { type: 'add', text: 'first new' },+ { type: 'hunk', text: '' },+ { type: 'del', text: 'second old' },+ { type: 'add', text: 'second new' },+ ]);+ });++ it('keeps multi-line replacement text as separate rows', () => {+ const parsed = buildEditPreviewDiff([{ oldText: 'a\nb', newText: 'c' }]);++ expect(parsed.deletions).toBe(2);+ expect(parsed.additions).toBe(1);+ expect(parsed.lines.map((line) => line.text)).toEqual(['a', 'b', 'c']);+ });++ it('does not count an empty replacement as an added line', () => {+ /** A pure deletion (`new_text: ""`) must not render a blank green row or+ * report an addition; `''.split('\n')` yields one element. */+ const parsed = buildEditPreviewDiff([{ oldText: 'gone', newText: '' }]);++ expect(parsed.deletions).toBe(1);+ expect(parsed.additions).toBe(0);+ expect(parsed.lines).toEqual([{ type: 'del', text: 'gone' }]);+ });++ it('treats a trailing newline as a terminator, not an empty final line', () => {+ const parsed = buildEditPreviewDiff([{ oldText: 'a\n', newText: 'b\n' }]);++ expect(parsed.deletions).toBe(1);+ expect(parsed.additions).toBe(1);+ expect(parsed.lines.map((line) => line.text)).toEqual(['a', 'b']);+ });++ it('keeps changed lines that look like the old synthetic header names', () => {+ /** Deleting a real `-- old_text` comment (SQL, Lua) and adding+ * `++ new_text` prefixes to exactly the text the removed separators used.+ * Nothing emits those separators any more, so these are unambiguously+ * content and must survive. */+ const parsed = parseUnifiedDiff(['@@ -1,2 +1,2 @@', '--- old_text', '+++ new_text'].join('\n'));++ expect(parsed.deletions).toBe(1);+ expect(parsed.additions).toBe(1);+ expect(parsed.lines).toEqual([+ { type: 'hunk', text: '@@ -1,2 +1,2 @@' },+ { type: 'del', text: '-- old_text', oldLine: 1 },+ { type: 'add', text: '++ new_text', newLine: 1 },+ ]);+ });+});diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/ExecuteCode.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/ExecuteCode.test.tsxindex 8b0c39b14c..e97803660b 100644--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/ExecuteCode.test.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/ExecuteCode.test.tsx@@ -172,7 +172,6 @@ describe('ExecuteCode programmatic tool trace', () => {{ callId: 'a', name: 'read_file', status: 'success', args: 'path=a.ts', durationMs: 1200 },]);- expect(getByText('read_file')).toBeInTheDocument();expect(getByText('path=a.ts')).toBeInTheDocument();});diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/FileAuthoringCall.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/FileAuthoringCall.test.tsxindex db8266c33a..7fa74e2e96 100644--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/FileAuthoringCall.test.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/FileAuthoringCall.test.tsx@@ -158,9 +158,8 @@ describe('FileAuthoringCall', () => {/>,);- const preview = screen.getByText((_, element) => element?.tagName.toLowerCase() === 'code');- expect(preview).toHaveTextContent('-old line');- expect(preview).toHaveTextContent('+new line');+ expect(screen.getByText('old line')).toBeInTheDocument();+ expect(screen.getByText('new line')).toBeInTheDocument();expect(screen.queryByText(/--- old_text/)).not.toBeInTheDocument();});@@ -179,9 +178,8 @@ describe('FileAuthoringCall', () => {/>,);- const preview = screen.getByText((_, element) => element?.tagName.toLowerCase() === 'code');- expect(preview).toHaveTextContent('-missing text');- expect(preview).toHaveTextContent('+replacement');+ expect(screen.getByText('missing text')).toBeInTheDocument();+ expect(screen.getByText('replacement')).toBeInTheDocument();expect(screen.getByText(/matched 0 locations/)).toBeInTheDocument();});@@ -201,12 +199,10 @@ describe('FileAuthoringCall', () => {);expect(screen.getByTestId('progress-text')).toHaveTextContent('Editing SKILL.md');- expect(screen.getByTestId('code-window-header')).toHaveAttribute('data-language', 'diff');- const preview = screen.getByText((_, element) => element?.tagName.toLowerCase() === 'code');- expect(preview).toHaveTextContent('--- old_text');- expect(preview).toHaveTextContent('+++ new_text');- expect(preview).toHaveTextContent('-description: Old behavior');- expect(preview).toHaveTextContent('+description: New behavior');+ expect(screen.getByTestId('code-window-header')).toHaveAttribute('data-language', 'SKILL.md');+ expect(screen.queryByText(/--- old_text/)).not.toBeInTheDocument();+ expect(screen.getByText('description: Old behavior')).toBeInTheDocument();+ expect(screen.getByText('description: New behavior')).toBeInTheDocument();});it('streams create_file content from partial JSON string args during run_step_delta', () => {@@ -238,9 +234,8 @@ describe('FileAuthoringCall', () => {/>,);- const preview = screen.getByText((_, element) => element?.tagName.toLowerCase() === 'code');- expect(preview).toHaveTextContent('-description: Old behavior');- expect(preview).toHaveTextContent('+description: New beh');+ expect(screen.getByText('description: Old behavior')).toBeInTheDocument();+ expect(screen.getByText('description: New beh')).toBeInTheDocument();});it('streams batched edit_file previews from a partial edits array', () => {@@ -258,13 +253,12 @@ describe('FileAuthoringCall', () => {/>,);- const preview = screen.getByText((_, element) => element?.tagName.toLowerCase() === 'code');- expect(preview).toHaveTextContent('--- old_text 1');- expect(preview).toHaveTextContent('-first old');- expect(preview).toHaveTextContent('+first new');- expect(preview).toHaveTextContent('--- old_text 2');- expect(preview).toHaveTextContent('-second old');- expect(preview).toHaveTextContent('+second n');+ const diff = screen.getByTestId('diff-view');+ expect(screen.getByText('first old')).toBeInTheDocument();+ expect(screen.getByText('first new')).toBeInTheDocument();+ expect(screen.getByText('second old')).toBeInTheDocument();+ expect(screen.getByText('second n')).toBeInTheDocument();+ expect(diff).toBeInTheDocument();});it('shows batched edit_file replacements from edits args while the call is in progress', () => {@@ -284,11 +278,56 @@ describe('FileAuthoringCall', () => {/>,);- const preview = screen.getByText((_, element) => element?.tagName.toLowerCase() === 'code');- expect(preview).toHaveTextContent('--- old_text 1');- expect(preview).toHaveTextContent('+++ new_text 2');- expect(preview).toHaveTextContent('-first old');- expect(preview).toHaveTextContent('+second new');+ expect(screen.getByText('first old')).toBeInTheDocument();+ expect(screen.getByText('second new')).toBeInTheDocument();+ });+ it('renders replacements from a JSON-stringified edits batch after workspace update', () => {+ render(+ <FileAuthoringCall+ toolName="edit_file"+ initialProgress={1}+ isSubmitting={false}+ args={{+ file_path: 'workspace/demo/SKILL.md',+ edits: JSON.stringify([+ { old_text: 'description: Old behavior', new_text: 'description: New behavior' },+ { old_text: 'status: draft', new_text: 'status: published' },+ ]),+ }}+ output="Updated workspace/demo/SKILL.md with 2 exact replacements."+ />,+ );++ expect(screen.getByText('description: Old behavior')).toBeInTheDocument();+ expect(screen.getByText('description: New behavior')).toBeInTheDocument();+ expect(screen.getByText('status: draft')).toBeInTheDocument();+ expect(screen.getByText('status: published')).toBeInTheDocument();+ expect(+ screen.getByText('Updated workspace/demo/SKILL.md with 2 exact replacements.'),+ ).toBeInTheDocument();+ });++ it('renders replacements from JSON-stringified edits entries after workspace update', () => {+ render(+ <FileAuthoringCall+ toolName="edit_file"+ initialProgress={1}+ isSubmitting={false}+ args={{+ file_path: 'workspace/demo/SKILL.md',+ edits: [+ JSON.stringify({ old_text: 'enabled: false', new_text: 'enabled: true' }),+ JSON.stringify({ old_text: 'tier: free', new_text: 'tier: pro' }),+ ],+ }}+ output="Updated workspace/demo/SKILL.md with 2 exact replacements."+ />,+ );++ expect(screen.getByText('enabled: false')).toBeInTheDocument();+ expect(screen.getByText('enabled: true')).toBeInTheDocument();+ expect(screen.getByText('tier: free')).toBeInTheDocument();+ expect(screen.getByText('tier: pro')).toBeInTheDocument();});});diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/MemoryCall.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/MemoryCall.test.tsxnew file mode 100644index 0000000000..7293aba696--- /dev/null+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/MemoryCall.test.tsx@@ -0,0 +1,202 @@+import React from 'react';+import { Tools } from 'librechat-data-provider';+import { render, screen } from '@testing-library/react';+import type { TAttachment } from 'librechat-data-provider';+import MemoryCall from '../MemoryCall';++jest.mock('~/hooks', () => ({+ useLocalize:+ () =>+ (key: string, params?: { tokens?: number }): string => {+ const translations: Record<string, string> = {+ com_ui_memory_saving: 'Saving memory',+ com_ui_memory_saved: 'Saved memory',+ com_ui_memory_deleting: 'Deleting memory',+ com_ui_memory_removed: 'Deleted memory',+ com_ui_memory_deleted: 'Memory deleted',+ com_ui_memory: 'Memory',+ com_ui_cancelled: 'Cancelled',+ com_ui_tool_failed: 'failed',+ com_ui_memory_would_exceed: `Cannot save: remove ${params?.tokens} tokens to make space.`,+ };+ return translations[key] ?? key;+ },+}));++jest.mock('~/utils', () => ({+ cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),+}));++jest.mock('~/components/Chat/Messages/Content/ProgressText', () => ({+ __esModule: true,+ default: ({+ phase,+ inProgressText,+ finishedText,+ subtitle,+ hasInput,+ }: {+ phase: 'running' | 'completed' | 'cancelled' | 'failed';+ inProgressText: string;+ finishedText: string;+ subtitle?: string;+ hasInput?: boolean;+ }) => (+ <div data-testid="progress-text" data-has-input={String(!!hasInput)}>+ {phase === 'running' ? inProgressText : finishedText}+ {subtitle ? ` ${subtitle}` : ''}+ {phase === 'failed' ? ' failed' : ''}+ </div>+ ),+}));++jest.mock('../Attachment', () => ({+ AttachmentGroup: () => <div data-testid="attachment-group" />,+}));++jest.mock('../useToolCallState', () => ({+ __esModule: true,+ default: ({+ initialProgress,+ runStepStatus,+ extraError,+ }: {+ initialProgress: number;+ runStepStatus?: 'completed' | 'cancelled' | 'failed';+ extraError?: boolean;+ }) => {+ let phase: 'running' | 'completed' | 'cancelled' | 'failed' =+ initialProgress < 1 ? 'running' : 'completed';+ if (runStepStatus === 'cancelled') {+ phase = 'cancelled';+ } else if (runStepStatus === 'failed' || extraError) {+ phase = 'failed';+ }+ return {+ showCode: true,+ toggleCode: jest.fn(),+ expandStyle: {},+ expandRef: { current: null },+ phase,+ };+ },+}));++describe('MemoryCall', () => {+ it('labels a completed save with the memory key and shows the value', () => {+ render(+ <MemoryCall+ toolName="set_memory"+ initialProgress={1}+ isSubmitting={false}+ args={{ key: 'preferences', value: 'Prefers dark mode.' }}+ output={'Memory set for key "preferences" (4 tokens)'}+ />,+ );++ expect(screen.getByTestId('progress-text')).toHaveTextContent('Saved memory preferences');+ expect(screen.getByText('preferences')).toHaveClass('font-bold', 'uppercase');+ expect(screen.getByText('Prefers dark mode.')).toBeInTheDocument();+ expect(screen.queryByText(/Memory set for key/)).not.toBeInTheDocument();+ });++ it('labels an in-flight save without a parsed key', () => {+ render(+ <MemoryCall+ toolName="set_memory"+ initialProgress={0.5}+ isSubmitting={true}+ args={'{"ke'}+ output=""+ />,+ );++ expect(screen.getByTestId('progress-text')).toHaveTextContent('Saving memory');+ expect(screen.getByTestId('progress-text')).toHaveAttribute('data-has-input', 'false');+ });++ it('renders a delete as the key with a deletion note', () => {+ render(+ <MemoryCall+ toolName="delete_memory"+ initialProgress={1}+ isSubmitting={false}+ args={{ key: 'outdated_note' }}+ output={'Memory deleted for key "outdated_note"'}+ />,+ );++ expect(screen.getByTestId('progress-text')).toHaveTextContent('Deleted memory outdated_note');+ expect(screen.getByText('outdated_note')).toHaveClass('font-bold', 'uppercase');+ expect(screen.getByText('Memory deleted')).toBeInTheDocument();+ });++ it.each([+ ['set_memory', 'Invalid key "invalid". Must be one of: preferences'],+ ['set_memory', 'Memory storage would exceed limit. Cannot save this memory.'],+ ['set_memory', 'Failed to set memory for key "preferences"'],+ ['set_memory', '{"type":"content_filter","message":"Blocked"}'],+ ['delete_memory', 'Failed to delete memory for key "preferences"'],+ ] as const)('surfaces %s failure output instead of optimistic content', (toolName, output) => {+ render(+ <MemoryCall+ toolName={toolName}+ initialProgress={1}+ isSubmitting={false}+ args={{ key: 'preferences', value: 'requested value' }}+ output={output}+ />,+ );++ expect(screen.getByTestId('progress-text')).toHaveTextContent('Memory preferences failed');+ expect(screen.getByText(output)).toBeInTheDocument();+ expect(screen.queryByText('requested value')).not.toBeInTheDocument();+ expect(screen.queryByText('Memory deleted')).not.toBeInTheDocument();+ });++ it('honors an explicit failed run step even when the output resembles success', () => {+ render(+ <MemoryCall+ toolName="set_memory"+ initialProgress={1}+ isSubmitting={false}+ runStepStatus="failed"+ args={{ key: 'preferences', value: 'requested value' }}+ output={'Memory set for key "preferences" (4 tokens)'}+ />,+ );++ expect(screen.getByTestId('progress-text')).toHaveTextContent('Memory preferences failed');+ expect(screen.getByText(/Memory set for key/)).toBeInTheDocument();+ expect(screen.queryByText('requested value')).not.toBeInTheDocument();+ });++ it('shows the actionable overage from a linked memory error artifact', () => {+ const attachment: TAttachment = {+ type: Tools.memory,+ toolCallId: 'call_0',+ messageId: 'message-1',+ [Tools.memory]: {+ type: 'error',+ key: 'preferences',+ value: JSON.stringify({ errorType: 'would_exceed', tokenCount: 47 }),+ },+ };+ render(+ <MemoryCall+ toolName="set_memory"+ initialProgress={1}+ isSubmitting={false}+ args={{ key: 'preferences', value: 'requested value' }}+ output="Memory storage would exceed limit. Cannot save this memory."+ attachments={[attachment]}+ hideAttachments+ />,+ );++ expect(screen.getByRole('alert')).toHaveTextContent(+ 'Cannot save: remove 47 tokens to make space.',+ );+ expect(screen.queryByText('requested value')).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/PtcToolTrace.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/PtcToolTrace.test.tsxindex bab6809622..9a73aa0c76 100644--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/PtcToolTrace.test.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/PtcToolTrace.test.tsx@@ -71,11 +71,9 @@ describe('PtcToolTrace', () => {]);expect(screen.getByText('Tool calls')).toBeInTheDocument();- expect(screen.getByText('read_file')).toBeInTheDocument();expect(screen.getByText('path=a.ts')).toBeInTheDocument();- expect(screen.getByText('write_file')).toBeInTheDocument();- /* Twice by design: the visible cell plus the screen-reader status. */- expect(screen.getAllByText('running')).toHaveLength(2);+ expect(screen.getByText('path=b.ts')).toBeInTheDocument();+ expect(screen.getByRole('list')).toHaveTextContent('running');});it('splits an MCP tool id into its server and tool name', () => {@@ -135,6 +133,6 @@ describe('PtcToolTrace', () => {it('does not show another message\u2019s trace in this card', () => {renderTrace([{ callId: 'a', name: 'read_file', status: 'success' }], 'a-different-message');- expect(screen.queryByText('read_file')).not.toBeInTheDocument();+ expect(screen.queryByRole('list')).not.toBeInTheDocument();});});diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/Reasoning.spec.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/Reasoning.spec.tsxdeleted file mode 100644index 6a77cca744..0000000000--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/Reasoning.spec.tsx+++ /dev/null@@ -1,57 +0,0 @@-import React from 'react';-import { render, screen } from '@testing-library/react';-import { MessageContext } from '~/Providers';-import Reasoning from '../Reasoning';--type ContextOverrides = {- isSubmitting?: boolean;- isLatestMessage?: boolean;-};--function renderReasoning(- { isSubmitting = true, isLatestMessage = true }: ContextOverrides = {},- isLast = true,-) {- return render(- <MessageContext.Provider- value={{ messageId: 'msg-1', isExpanded: false, isSubmitting, isLatestMessage }}- >- <Reasoning reasoning="<think>weighing the options</think>" isLast={isLast} />- </MessageContext.Provider>,- );-}--describe('Reasoning label shimmer', () => {- it('shimmers the label while the reasoning is still being generated', () => {- renderReasoning();- expect(screen.getByText('Thinking...')).toHaveClass('shimmer');- });-- /** The sweep has to ride the label row itself rather than a span nested inside- * it. That row is a flex item, so `.shimmer`'s `inline-block` is blockified- * away; nested, it is an inline-block whose `truncate` moves its baseline to- * its bottom margin edge, which grew the line box 18px -> 23px and lifted the- * label 2px off the lightbulb's axis for the whole of a generation. */- it('keeps the sweep on the label row instead of a nested span', () => {- renderReasoning();- const label = screen.getByText('Thinking...');-- expect(label).toHaveClass('truncate');- expect(label.querySelector('.shimmer')).toBeNull();- });-- it('leaves settled thoughts unanimated', () => {- renderReasoning({ isSubmitting: false });- expect(screen.getByText('Thoughts')).not.toHaveClass('shimmer');- });-- it('leaves an older row unanimated while a newer one streams', () => {- renderReasoning({ isLatestMessage: false });- expect(screen.getByText('Thoughts')).not.toHaveClass('shimmer');- });-- it('leaves reasoning that has been overtaken by later content unanimated', () => {- renderReasoning({}, false);- expect(screen.getByText('Thoughts')).not.toHaveClass('shimmer');- });-});diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/ReasoningCompact.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/ReasoningCompact.test.tsxnew file mode 100644index 0000000000..2a9f2e9cb7--- /dev/null+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/ReasoningCompact.test.tsx@@ -0,0 +1,102 @@+import React from 'react';+import { render, screen } from '@testing-library/react';+import { ReasoningCompact } from '../Reasoning';++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+ useExpandCollapse: (isExpanded: boolean) => ({+ style: { display: 'grid', gridTemplateRows: isExpanded ? '1fr' : '0fr' },+ ref: { current: null },+ }),+ useLazyCollapseBody: (isExpanded: boolean) => ({+ shouldRenderBody: isExpanded,+ mountBody: jest.fn(),+ handleTransitionEnd: jest.fn(),+ }),+}));++jest.mock('../Thinking', () => ({+ ThinkingContent: ({ children }: { children?: React.ReactNode }) => <div>{children}</div>,+ ThinkingButton: () => <button type="button">{'thinking'}</button>,+ FloatingThinkingBar: () => null,+ useInViewport: () => ({ ref: { current: null }, inViewport: true }),+}));++jest.mock('~/components/Messages/Content/CopyButton', () => ({+ __esModule: true,+ default: () => <button type="button">{'copy'}</button>,+}));++jest.mock('lucide-react', () => ({+ Lightbulb: () => <span data-testid="thoughts-icon" />,+ ChevronDown: ({ className }: { className?: string }) => (+ <span data-testid="thoughts-chevron" className={className} />+ ),+}));++describe('ReasoningCompact', () => {+ it('reveals its own Thoughts chevron instantly on row hover or focus', () => {+ render(<ReasoningCompact reasoning="A useful thought" label="Thoughts" showThinking={false} />);++ const button = screen.getByRole('button', { name: 'Thoughts' });+ const chevron = screen.getByTestId('thoughts-chevron');+ const row = button.closest('.group\\/reasoning-compact');++ expect(row).toHaveClass('mb-1', 'mt-1');+ expect(button.parentElement).not.toHaveClass('my-1.5');+ expect(button).toHaveClass('group/disclosure');+ expect(chevron).toHaveClass(+ 'opacity-0',+ 'group-hover/disclosure:opacity-100',+ 'group-focus-within/disclosure:opacity-100',+ );+ expect(chevron).toHaveClass('transition-transform');+ expect(chevron.className).not.toContain('transition-opacity');+ });++ it('removes the extra top margin when Thoughts follows a tool', () => {+ render(+ <ReasoningCompact+ reasoning="A useful thought"+ label="Thoughts"+ isAfterTool+ showThinking={false}+ />,+ );++ const row = screen+ .getByRole('button', { name: 'Thoughts' })+ .closest('.group\\/reasoning-compact');++ expect(row).toHaveClass('mb-1', 'mt-0');+ expect(row).not.toHaveClass('mt-1');+ });++ it('leaves the full reasoning text unmounted while collapsed', () => {+ /** Collapsed is the default whenever thoughts are hidden, and a streaming+ * THINK part re-renders on every delta, so keeping the whole text mounted+ * behind the invisible panel cost layout work for nothing. */+ render(+ <ReasoningCompact+ reasoning="A long stream of reasoning"+ label="Thoughts"+ showThinking={false}+ />,+ );++ expect(screen.getByRole('button', { name: 'Thoughts' })).toBeInTheDocument();+ expect(screen.queryByText('A long stream of reasoning')).not.toBeInTheDocument();+ });++ it('opens from the host preference rather than the app store', () => {+ render(+ <ReasoningCompact+ reasoning="A long stream of reasoning"+ label="Thoughts"+ showThinking={true}+ />,+ );++ expect(screen.getByText('A long stream of reasoning')).toBeInTheDocument();+ });+});diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsxindex 80e6da7654..5749b155f0 100644--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/SubagentCall.test.tsx@@ -25,6 +25,8 @@ import SubagentCall, { SUBAGENT_TICKER_THROTTLE_MS } from '../SubagentCall';import { MessageContext } from '~/Providers/MessageContext';import { ChatSurfaceHarness } from 'test/harness';+const mockMCPServerNames: string[] = [];+jest.mock('~/hooks', () => ({useLocalize:() =>@@ -61,14 +63,17 @@ jest.mock('lucide-react', () => ({jest.mock('~/Providers', () => ({ useAgentsMapContext: () => ({}) }));jest.mock('~/components/Share/MessageIcon', () => ({ __esModule: true, default: () => null }));-jest.mock('~/hooks/MCP', () => ({ useMCPServerNames: () => [] }));+jest.mock('~/hooks/MCP', () => ({ useMCPServerNames: () => mockMCPServerNames }));jest.mock('~/utils', () => ({...jest.requireActual('~/utils/toolLabels'),cn: (...classes: unknown[]) => classes.filter(Boolean).join(' '),logger: { log: jest.fn() },}));-afterEach(() => jest.useRealTimers());+afterEach(() => {+ jest.useRealTimers();+ mockMCPServerNames.length = 0;+});function foldEvents(events: SubagentUpdateEvent[]): {contentParts: SubagentContentPart[];@@ -231,6 +236,42 @@ describe('SubagentCall', () => {expect(rendered.getSelection()?.durable).toBeUndefined();});+ it('preserves a configured MCP server boundary in the live ticker', () => {+ mockMCPServerNames.push('Google_mcp_Workspace');+ renderWithState({+ toolCallId: 'call_mcp_ticker',+ initialProgress: 0.3,+ isSubmitting: true,+ progress: progressFromEvents({+ subagentRunId: 'run_a',+ subagentType: 'self',+ status: 'run_step',+ events: [+ {+ runId: 'p',+ subagentRunId: 'run_a',+ subagentType: 'self',+ phase: 'run_step',+ data: {+ stepDetails: {+ type: 'tool_calls',+ tool_calls: [+ {+ id: 'c1',+ name: 'search_documents_mcp_Google_mcp_Workspace',+ },+ ],+ },+ },+ timestamp: '',+ } as SubagentUpdateEvent,+ ],+ }),+ });++ expect(screen.getByText('Google_mcp_Workspace')).toBeInTheDocument();+ });+it('refreshes a long ticker preview only after the throttle window', () => {jest.useFakeTimers();const progressFor = (text: string) =>diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/Summary.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/Summary.test.tsxnew file mode 100644index 0000000000..828346c124--- /dev/null+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/Summary.test.tsx@@ -0,0 +1,50 @@+import React from 'react';+import { render, screen } from '@testing-library/react';+import Summary from '../Summary';++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++const mockMessageContext = { current: { isSubmitting: false, isLatestMessage: false } };++jest.mock('~/Providers', () => ({+ useMessageContext: () => mockMessageContext.current,+}));++const partialSummary = [{ type: 'text', text: 'Half a summary before the error' }] as never;++describe('Summary', () => {+ beforeEach(() => {+ mockMessageContext.current = { isSubmitting: false, isLatestMessage: false };+ });++ it('does not present a failed round as a completed summary', () => {+ /** A failed summarize round keeps the deltas that already streamed in, so+ * the only thing separating it from a success is this flag. */+ render(<Summary content={partialSummary} summarizing={false} failed />);++ expect(screen.getByText('com_ui_summarize_failed')).toBeInTheDocument();+ expect(screen.queryByText('com_ui_conversation_summarized')).not.toBeInTheDocument();+ });++ it('labels a settled round with partial text as summarized when it did not fail', () => {+ render(<Summary content={partialSummary} summarizing={false} />);++ expect(screen.getByText('com_ui_conversation_summarized')).toBeInTheDocument();+ expect(screen.queryByText('com_ui_summarize_failed')).not.toBeInTheDocument();+ });++ it('keeps the in-flight label while the round is still streaming', () => {+ mockMessageContext.current = { isSubmitting: true, isLatestMessage: true };+ render(<Summary content={partialSummary} summarizing />);++ expect(screen.getByText('com_ui_summarizing')).toBeInTheDocument();+ });++ it('renders nothing when a failed round produced no text at all', () => {+ const { container } = render(<Summary content={[]} summarizing={false} failed />);++ expect(container).toBeEmptyDOMElement();+ });+});diff --git a/client/src/components/Chat/Messages/Content/Parts/index.ts b/client/src/components/Chat/Messages/Content/Parts/index.tsindex 0127e6ec2a..229db2fe36 100644--- a/client/src/components/Chat/Messages/Content/Parts/index.ts+++ b/client/src/components/Chat/Messages/Content/Parts/index.ts@@ -3,13 +3,14 @@ export * from './OpenAIImageGen';export { default as Text } from './Text';export { default as CollapsibleText } from './CollapsibleText';-export { default as Reasoning, ReasoningMarker } from './Reasoning';+export { default as Reasoning, ReasoningMarker, ReasoningCompact } from './Reasoning';export { default as EmptyText } from './EmptyText';export { default as LogContent } from './LogContent';export { default as ExecuteCode } from './ExecuteCode';export { default as Summary } from './Summary';export { default as AgentUpdate } from './AgentUpdate';export { default as SkillCall } from './SkillCall';+export { default as MemoryCall } from './MemoryCall';export { default as ReadFileCall } from './ReadFileCall';export { default as FileAuthoringCall } from './FileAuthoringCall';export { default as BashCall } from './BashCall';diff --git a/client/src/components/Chat/Messages/Content/ProgressText.tsx b/client/src/components/Chat/Messages/Content/ProgressText.tsxindex 6c83492101..0ae3e70c1c 100644--- a/client/src/components/Chat/Messages/Content/ProgressText.tsx+++ b/client/src/components/Chat/Messages/Content/ProgressText.tsx@@ -1,7 +1,7 @@import { ChevronDown } from 'lucide-react';-import { Button } from '@librechat/client';import { useTranslation } from 'react-i18next';import * as Popover from '@radix-ui/react-popover';+import { Button, disclosureChevronVariants } from '@librechat/client';import { isReportableRunStepDuration } from 'librechat-data-provider';import type { ToolCallPhase } from '~/utils/toolCallPhase';import { cn, getRunStepDurationLabels } from '~/utils';@@ -12,11 +12,11 @@ import { useLocalize } from '~/hooks';const wrapperClass ='progress-text-wrapper text-token-text-secondary relative -mt-[0.75px] h-5 w-full leading-5';-/** `max-w-full` caps the absolutely-positioned line at the message column;- * the label span truncates itself, so overflow stays visible for the+/** `right-0` and `max-w-full` cap the absolutely-positioned line at the message+ * column; the label span truncates itself, so overflow stays visible for the* button's focus ring. */const contentClass =- 'progress-text-content absolute left-0 top-0 max-w-full overflow-visible whitespace-nowrap';+ 'progress-text-content absolute left-0 right-0 top-0 max-w-full overflow-visible whitespace-nowrap';const Wrapper = ({ popover, children }: { popover: boolean; children: React.ReactNode }) => {if (popover) {@@ -104,7 +104,7 @@ export default function ProgressText({type="button"variant="ghost"className={cn(- 'h-auto w-full justify-start gap-2 rounded-none p-0 hover:bg-transparent hover:text-inherit disabled:opacity-100',+ 'group/disclosure inline-flex h-auto w-full items-center justify-start gap-2 rounded-none p-0 hover:bg-transparent hover:text-inherit disabled:opacity-100',hasInput? 'focus-visible:ring-border-heavy focus-visible:ring-offset-0': 'pointer-events-none',@@ -151,8 +151,8 @@ export default function ProgressText({{hasInput && (<ChevronDownclassName={cn(- 'size-4 shrink-0 translate-y-[1px] transition-transform duration-200 ease-out',- isExpanded && 'rotate-180',+ disclosureChevronVariants({ expanded: isExpanded }),+ 'size-4 translate-y-[1px]',)}aria-hidden="true"/>diff --git a/client/src/components/Chat/Messages/Content/RetrievalCall.tsx b/client/src/components/Chat/Messages/Content/RetrievalCall.tsxindex ea596b97fe..8a777b0b40 100644--- a/client/src/components/Chat/Messages/Content/RetrievalCall.tsx+++ b/client/src/components/Chat/Messages/Content/RetrievalCall.tsx@@ -7,6 +7,7 @@ import type { TAttachment, TFile, PartMetadata } from 'librechat-data-provider';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';@@ -311,10 +312,10 @@ function FileHeader({<TooltipAnchordescription={localize('com_ui_relevance')}side="top"- className="flex items-center"+ className="flex cursor-help items-center"><span- className="shrink-0 rounded bg-surface-tertiary px-1.5 py-0.5 text-[11px] tabular-nums leading-none text-text-secondary"+ className="shrink-0 cursor-help rounded bg-surface-tertiary px-1.5 py-0.5 text-[11px] tabular-nums leading-none text-text-secondary"aria-label={`${localize('com_ui_relevance')}: ${Math.round(relevance * 100)}%`}>{Math.round(relevance * 100)}%@@ -380,8 +381,6 @@ export default function RetrievalCall({});const hasOutput = !!output && !isError(output);const autoExpand = useRecoilValue(store.autoExpandTools);- const [showOutput, setShowOutput] = useState(() => autoExpand && hasOutput);- const { style: expandStyle, ref: expandRef } = useExpandCollapse(showOutput);const fileSources = useMemo(() => extractFileSources(attachments), [attachments]);const parsedResults = useMemo(@@ -402,6 +401,9 @@ export default function RetrievalCall({);const hasResults = displayResults.length > 0;+ const hasExpandableContent = phase !== 'failed' && hasResults;+ const [showOutput, setShowOutput] = useState(() => autoExpand && hasExpandableContent);+ const { style: expandStyle, ref: expandRef } = useExpandCollapse(showOutput);const [previewIndex, setPreviewIndex] = useState<number | null>(null);@@ -437,10 +439,14 @@ export default function RetrievalCall({}, [displayResults, previewIndex]);useEffect(() => {- if (autoExpand && hasOutput) {+ if (!hasExpandableContent) {+ setShowOutput(false);+ return;+ }+ if (autoExpand) {setShowOutput(true);}- }, [autoExpand, hasOutput]);+ }, [autoExpand, hasExpandableContent]);const handleToggleOutput = useCallback(() => {setShowOutput((prev) => {@@ -453,7 +459,7 @@ export default function RetrievalCall({}, [onExpand]);return (- <div className="my-1">+ <div><span className="sr-only" aria-live="polite" aria-atomic="true">{(() => {if (phase === 'running') {@@ -474,7 +480,7 @@ export default function RetrievalCall({<div className="relative my-1 flex h-5 shrink-0 items-center gap-2.5"><ProgressTextphase={phase}- onClick={hasOutput ? handleToggleOutput : undefined}+ onClick={hasExpandableContent ? handleToggleOutput : undefined}inProgressText={intent ?? localize('com_ui_searching_files')}/** A cancelled step must not read "Retrieved files" beside a* cancellation icon while the live region says "Cancelled". */@@ -485,14 +491,14 @@ export default function RetrievalCall({}durationMs={runStepDurationMs}icon={<ToolIcon type="file_search" isAnimating={phase === 'running'} />}- hasInput={hasOutput}+ hasInput={hasExpandableContent}isExpanded={showOutput}/></div><div style={expandStyle}><div className="overflow-hidden" ref={expandRef}>- {hasOutput && hasResults && (- <div className="my-2 flex flex-col gap-2">+ {hasExpandableContent && (+ <div className={cn(toolPanelSpacingClassName, 'flex flex-col gap-2')}>{displayResults.map((item, i) => {return (<divdiff --git a/client/src/components/Chat/Messages/Content/ToolCall.tsx b/client/src/components/Chat/Messages/Content/ToolCall.tsxindex 3ca18c3771..59278dcf6f 100644--- a/client/src/components/Chat/Messages/Content/ToolCall.tsx+++ b/client/src/components/Chat/Messages/Content/ToolCall.tsx@@ -1,7 +1,6 @@import { useMemo, useState, useEffect, useCallback } from 'react';import { useRecoilValue } from 'recoil';import { Button } from '@librechat/client';-import { TriangleAlert } from 'lucide-react';import {Constants,dataService,@@ -14,12 +13,14 @@ import { useLocalize, useProgress, useExpandCollapse, useLazyCollapseBody } fromimport { ToolIcon, getToolIconType, isError } from './ToolOutput';import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';import { resolveToolCallPhase } from '~/utils/toolCallPhase';+import { cn, getToolDisplayLabel, logger } from '~/utils';+import { toolPanelSpacingClassName } from './disclosure';import { useToolCallIntent } from './Parts/intent';import { AttachmentGroup } from './Parts';import ToolCallInfo from './ToolCallInfo';import ProgressText from './ProgressText';import { TOOL_ROW_CLASSES } from './rows';-import { logger } from '~/utils';+import { ToolAuthWarning } from './auth';import store from '~/store';export default function ToolCall({@@ -116,6 +117,15 @@ export default function ToolCall({}, [name, parsedAuthUrl, mcpServerNames]);const toolIconType = useMemo(() => getToolIconType(name), [name]);+ const displayFunctionName = useMemo(+ () =>+ /** `function_name` has already had the MCP delimiter and server stripped+ * above, so re-parsing it would classify an MCP function that happens to+ * share a built-in's name (`read_file`, `set_memory`) as that native+ * tool and show, and announce, an unrelated label. */+ isMCPToolCall ? function_name : getToolDisplayLabel(function_name, localize, mcpServerNames),+ [function_name, isMCPToolCall, localize, mcpServerNames],+ );const mcpIconMap = useMCPIconMap();const mcpIconUrl = isMCPToolCall ? mcpIconMap.get(mcpServerName) : undefined;@@ -205,14 +215,11 @@ export default function ToolCall({const handleToggleInfo = useCallback(() => {mountBody();- setShowInfo((prev) => {- const next = !prev;- if (next) {- onExpand?.();- }- return next;- });- }, [mountBody, onExpand]);+ if (!showInfo) {+ onExpand?.();+ }+ setShowInfo((prev) => !prev);+ }, [mountBody, onExpand, showInfo]);const subtitle = useMemo(() => {if (isMCPToolCall && mcpServerName) {@@ -247,12 +254,12 @@ export default function ToolCall({return intent;}if (isMCPToolCall === true) {- return localize('com_assistants_completed_function', { 0: function_name });+ return localize('com_assistants_completed_function', { 0: displayFunctionName });}if (domain != null && domain && domain.length !== Constants.ENCODED_DOMAIN_LENGTH) {return localize('com_assistants_completed_action', { 0: domain });}- return localize('com_assistants_completed_function', { 0: function_name });+ return localize('com_assistants_completed_function', { 0: displayFunctionName });};if (!isLast && (!function_name || function_name.length === 0) && !output) {@@ -268,8 +275,8 @@ export default function ToolCall({<span className="sr-only" aria-live="polite" aria-atomic="true">{(() => {if (phase === 'running') {- return function_name- ? localize('com_assistants_running_var', { 0: function_name })+ return displayFunctionName+ ? localize('com_assistants_running_var', { 0: displayFunctionName }): localize('com_assistants_running_action');}return getFinishedText();@@ -281,8 +288,8 @@ export default function ToolCall({onClick={handleToggleInfo}inProgressText={intent ??- (function_name- ? localize('com_assistants_running_var', { 0: function_name })+ (displayFunctionName+ ? localize('com_assistants_running_var', { 0: displayFunctionName }): localize('com_assistants_running_action'))}authText={@@ -307,7 +314,12 @@ export default function ToolCall({><div className="overflow-hidden" ref={expandRef}>{hasInfo && shouldRenderBody && (- <div className="my-2 overflow-hidden rounded-lg border border-border-light bg-surface-secondary">+ <div+ className={cn(+ toolPanelSpacingClassName,+ 'overflow-hidden rounded-lg border border-border-light bg-surface-secondary',+ )}+ ><ToolCallInfo input={args ?? ''} output={output} attachments={attachments} /></div>)}@@ -325,10 +337,7 @@ export default function ToolCall({{localize('com_ui_sign_in_to_domain', { 0: authDomain })}</Button></div>- <p className="flex items-center text-xs text-text-warning">- <TriangleAlert className="mr-1.5 inline-block h-4 w-4" aria-hidden="true" />- {localize('com_assistants_allow_sites_you_trust')}- </p>+ <ToolAuthWarning /></div>)}{!hideAttachments && attachments && attachments.length > 0 && (diff --git a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsxindex cdd541aaa1..10505e94c7 100644--- a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx+++ b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx@@ -8,6 +8,7 @@ import type {TMessageContentParts,Agents,FunctionToolCall,+ PartMetadata,} from 'librechat-data-provider';import type { PartWithIndex } from './ParallelContent';import {@@ -18,11 +19,17 @@ import {getActivityLabelText,} from '~/utils';import { useLocalize, useExpandCollapse, scheduleMessageContentLayoutReconcile } from '~/hooks';+import { parseBackgroundHandle, splitBackgroundAttachments } from './Parts/handle';+import { mapAttachments, filterAttachmentsForPart } from '~/utils/map';+import { ToolAuthWarning, ToolAuthWarningContext } from './auth';import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';+import { resolveToolCallPhase } from '~/utils/toolCallPhase';+import { AttachmentGroup, ReasoningCompact } from './Parts';+import { isMemoryFailureOutput } from './Parts/MemoryCall';+import { isError, StackedToolIcons } from './ToolOutput';import { isBashProgrammaticToolCall } from './routing';import { ASK_USER_QUESTION } from '~/utils/approval';-import { StackedToolIcons } from './ToolOutput';-import { AttachmentGroup } from './Parts';+import SearchVerticals from './verticals';import { ROW_GLYPH_SLOT } from './rows';import store from '~/store';@@ -30,9 +37,77 @@ interface ToolMeta {name: string;iconName: string;hasOutput: boolean;+ failed: boolean;+ cancelled: boolean;}-function getToolMeta(part: TMessageContentParts): ToolMeta | null {+function hasFailedOutput(output: unknown): boolean {+ return typeof output === 'string' && isError(output);+}++/**+ * Group metadata must agree with the individual card, which resolves its+ * outcome from the run step's terminal verdict through `resolveToolCallPhase`.+ * Reading output alone leaves a step the run closed as `failed` with empty or+ * benign output counted as neither failed nor finished, so the group sits on+ * "Running" until the response ends and then reports that it ran successfully+ * with no failures while the card beside it shows the failure. A closed step+ * is never running. Parts carrying no terminal status keep the legacy+ * output/progress signal, which is all the older endpoints emit.+ */+function resolveOutcome(+ runStepStatus: PartMetadata['runStepStatus'],+ completed: boolean,+ hasError: boolean,+): Pick<ToolMeta, 'hasOutput' | 'failed' | 'cancelled'> {+ if (runStepStatus == null) {+ return { hasOutput: completed, failed: hasError, cancelled: false };+ }+ const phase = resolveToolCallPhase({+ runStepStatus,+ displayProgress: 1,+ reportedProgress: 1,+ isSubmitting: false,+ hasError,+ });+ return {+ hasOutput: phase !== 'running',+ failed: phase === 'failed',+ /** Tracked separately from `failed`: a stopped step is settled and not an+ * error, but the group still must not auto-collapse under a+ * success-sounding header with the only cancellation notice hidden in the+ * panel. */+ cancelled: phase === 'cancelled',+ };+}++function hasPendingAuth(part: TMessageContentParts): boolean {+ if (part.type !== ContentTypes.TOOL_CALL) {+ return false;+ }+ const toolCall = part[ContentTypes.TOOL_CALL];+ if (!toolCall || !('args' in toolCall)) {+ return false;+ }+ /** A step the run already closed can never be waiting on a sign-in, whatever+ * its progress says. `ToolCall` hides the sign-in button on a terminal+ * status, so counting it as pending here left the group showing a trust+ * warning with no authentication action behind it. */+ if (toolCall.runStepStatus != null) {+ return false;+ }+ const standardToolCall = toolCall as Agents.ToolCall & { progress?: number };+ const progress = standardToolCall.progress ?? 0.1;++ return (+ typeof standardToolCall.auth === 'string' && standardToolCall.auth.length > 0 && progress < 1+ );+}++function getToolMeta(+ part: TMessageContentParts,+ attachmentsByToolCallId?: Record<string, TAttachment[] | undefined>,+): ToolMeta | null {if (part.type !== ContentTypes.TOOL_CALL) {return null;}@@ -40,11 +115,17 @@ function getToolMeta(part: TMessageContentParts): ToolMeta | null {if (!toolCall) {return null;}+ /** Terminal verdict lives on the outer `tool_call` object (`PartMetadata`),+ * not on the per-variant payload, so it is read before any narrowing cast. */+ const runStepStatus = toolCall.runStepStatus;const isStandard ='args' in toolCall && (!toolCall.type || toolCall.type === ToolCallTypes.TOOL_CALL);if (isStandard) {- const tc = toolCall as Agents.ToolCall & { progress?: number };+ /** `agentId` disambiguates attachments when a handoff response repeats a+ * provider tool-call id across agents; `filterAttachmentsForPart` reads it+ * the same way. */+ const tc = toolCall as Agents.ToolCall & { progress?: number; agentId?: string };/** Subagents can finish with `progress === 1` and no final output* text (the parent saw "" / undefined back). Fall back to progress* so the group header flips from "Running N agents" to "Ran N@@ -52,7 +133,36 @@ function getToolMeta(part: TMessageContentParts): ToolMeta | null {const completed = !!tc.output || tc.progress === 1;const name = tc.name ?? '';const iconName = isBashProgrammaticToolCall(name, tc.args) ? Tools.bash_tool : name;- return { name, iconName, hasOutput: completed };+ /** Memory tools report failure in prose ("Invalid key ...") that generic+ * `isError` parsing does not recognize, so `MemoryCall` classifies it with+ * its own predicate. Reuse that here or a persisted call with no terminal+ * status shows a failed card inside a group claiming success. */+ const failedOutput =+ name === 'set_memory' || name === 'delete_memory'+ ? isMemoryFailureOutput(name, tc.output ?? '')+ : hasFailedOutput(tc.output);+ /** A backgrounded bash/code task reports its verdict through a+ * `background_task_status` attachment, not its output: the dispatch step+ * keeps a benign handle and usually closes as `completed`. The child card+ * folds that marker in as `extraError`, so without it here the group+ * reported no failed action beside a card showing failure. Correlated the+ * same way the child is, since provider tool-call ids repeat across agents+ * and execution steps in handoff responses. */+ const backgroundFailed =+ parseBackgroundHandle(tc.output) != null &&+ splitBackgroundAttachments(+ filterAttachmentsForPart(+ attachmentsByToolCallId?.[tc.id ?? ''],+ tc.agentId,+ toolCall.stepId,+ ),+ tc.id,+ ).backgroundStatus === 'error';+ return {+ name,+ iconName,+ ...resolveOutcome(runStepStatus, completed, failedOutput || backgroundFailed),+ };}if (toolCall.type === ToolCallTypes.CODE_INTERPRETER) {@@ -60,21 +170,26 @@ function getToolMeta(part: TMessageContentParts): ToolMeta | null {return {name: 'code_interpreter',iconName: 'code_interpreter',- hasOutput: (ci?.outputs?.length ?? 0) > 0,+ ...resolveOutcome(runStepStatus, (ci?.outputs?.length ?? 0) > 0, false),};}if (toolCall.type === ToolCallTypes.RETRIEVAL || toolCall.type === ToolCallTypes.FILE_SEARCH) {+ const output = (toolCall as { output?: string }).output;return {name: 'file_search',iconName: 'file_search',- hasOutput: !!(toolCall as { output?: string }).output,+ ...resolveOutcome(runStepStatus, !!output, hasFailedOutput(output)),};}if (toolCall.type === ToolCallTypes.FUNCTION && ToolCallTypes.FUNCTION in toolCall) {const fn = (toolCall as FunctionToolCall).function;- return { name: fn.name, iconName: fn.name, hasOutput: !!fn.output };+ return {+ name: fn.name,+ iconName: fn.name,+ ...resolveOutcome(runStepStatus, !!fn.output, hasFailedOutput(fn.output)),+ };}return null;@@ -84,6 +199,7 @@ interface ToolCallGroupProps {parts: PartWithIndex[];isSubmitting: boolean;isLast: boolean;+ showThinking: boolean;renderPart: (part: TMessageContentParts,idx: number,@@ -116,6 +232,7 @@ export default function ToolCallGroup({parts,isSubmitting,isLast,+ showThinking,renderPart,lastContentIdx,groupAttachments,@@ -131,13 +248,21 @@ export default function ToolCallGroup({const cancelLayoutReconcileRef = useRef<(() => void) | null>(null);const retainedForPendingApprovalRef = useRef(false);- /** Labeled activity blocks also contain THINK parts, which yield null- * metadata. Narrow to tool entries once: they alone drive the count, the- * completion check, and the icon strip — passing a null-derived empty- * name to StackedToolIcons would render a phantom generic tool icon. */+ /** Re-keyed by tool-call id so each part's metadata sees only its own+ * attachments: `groupAttachments` arrives flattened across the group. */+ const attachmentsByToolCallId = useMemo(+ () => mapAttachments(groupAttachments ?? []),+ [groupAttachments],+ );+ /** `parts` may include interleaved reasoning ("Thoughts") parts that render+ * inside the body but are not actions. Count and summarize only the real+ * tool calls so the header and stacked icons stay accurate. */const toolMetadata = useMemo(- () => parts.map((p) => getToolMeta(p.part)).filter((m): m is ToolMeta => m != null),- [parts],+ () =>+ parts+ .map((p) => getToolMeta(p.part, attachmentsByToolCallId))+ .filter((m): m is ToolMeta => m != null),+ [parts, attachmentsByToolCallId],);const count = toolMetadata.length;/** Approval state is read from the RAW parts, not `toolMetadata`: a pending@@ -161,17 +286,74 @@ export default function ToolCallGroup({() => labelSettled || toolMetadata.every((m) => m.hasOutput === true),[toolMetadata, labelSettled],);- const toolNames = useMemo(() => toolMetadata.map((m) => m.name), [toolMetadata]);const iconToolNames = useMemo(() => toolMetadata.map((m) => m.iconName), [toolMetadata]);+ /** Turn raw tool ids into an activity summary. Repeated calls retain their+ * count (`Web Search ×3`) instead of disappearing behind de-duplication,+ * while the primary label can use an outcome verb such as "Searched". */+ const activitySummary = useMemo(() => {+ const labelCounts = new Map<string, number>();+ let webSearchCount = 0;+ let fileSearchCount = 0;+ let subagentCount = 0;+ let askQuestionCount = 0;+ let failedCount = 0;+ let cancelledCount = 0;++ for (const tool of toolMetadata) {+ if (tool.name === Tools.web_search) {+ webSearchCount++;+ } else if (tool.name === 'file_search' || tool.name === 'retrieval') {+ fileSearchCount++;+ } else if (tool.name === Constants.SUBAGENT) {+ subagentCount++;+ } else if (tool.name === ASK_USER_QUESTION) {+ askQuestionCount++;+ }+ if (tool.failed) {+ failedCount++;+ }+ if (tool.cancelled) {+ cancelledCount++;+ }+ if (!tool.name) {+ continue;+ }+ const label = getToolDisplayLabel(tool.name, localize, mcpServerNames);+ labelCounts.set(label, (labelCounts.get(label) ?? 0) + 1);+ }++ const labels = Array.from(labelCounts, ([label, labelCount]) =>+ labelCount > 1 ? `${label} ×${labelCount}` : label,+ );+ const toolNameSummary =+ labels.length <= 3+ ? labels.join(', ')+ : `${labels.slice(0, 3).join(', ')}, +${labels.length - 3}`;++ return {+ webSearchCount,+ fileSearchCount,+ subagentCount,+ askQuestionCount,+ failedCount,+ cancelledCount,+ toolNameSummary,+ };+ }, [toolMetadata, localize, mcpServerNames]);++ /** Reasoning interleaved with the tool calls renders inside the body but is+ * hidden while collapsed. Note it in the header's accessible label so screen+ * readers know the group also contains thoughts. */+ const hasReasoning = useMemo(+ () => parts.some((p) => p.part.type === ContentTypes.THINK),+ [parts],+ );+/** Subagent tool calls get their own label verb ("Running/Ran N agents")* since "Used N tools" reads oddly when the "tools" are actually child* agents. `subagentCount === count` ⇒ the group is 100% subagents. */- const subagentCount = useMemo(- () => toolNames.filter((n) => n === Constants.SUBAGENT).length,- [toolNames],- );- const allSubagents = subagentCount > 0 && subagentCount === count;+ const allSubagents = activitySummary.subagentCount > 0 && activitySummary.subagentCount === count;/** Past-tense label once the parent stream is no longer live OR every* child has a terminal signal (output / progress === 1). Without the* `!isSubmitting` branch, a cancelled or errored subagent that never@@ -183,40 +365,37 @@ export default function ToolCallGroup({/** `ask_user_question` calls form their own category, mirroring subagents:* a homogeneous group reads "Asking/Asked N questions" (never "Used N- * tools — ask_user_question") with a question glyph. A group only exists- * at count >= 2, so the plural is always grammatical. */- const askQuestionCount = useMemo(- () => toolNames.filter((n) => n === ASK_USER_QUESTION).length,- [toolNames],- );- const allAskQuestions = askQuestionCount > 0 && askQuestionCount === count;+ * tools: ask_user_question") with a question glyph. */+ const allAskQuestions =+ activitySummary.askQuestionCount > 0 && activitySummary.askQuestionCount === count;/** Past tense once the turn is settled — matches the Asking/Asked record* card. While a multi-question turn streams, the still-open question's* tool_call part has no output yet, so keep the present tense. */const askQuestionsDone = allAskQuestions && (allCompleted || !isSubmitting);- const toolNameSummary = useMemo(() => {- const seen = new Set<string>();- const labels: string[] = [];- for (const rawName of toolNames) {- if (!rawName) continue;- const label = getToolDisplayLabel(rawName, localize, mcpServerNames);- if (!seen.has(label)) {- seen.add(label);- labels.push(label);- }- }- if (labels.length <= 3) {- return labels.join(', ');- }- return `${labels.slice(0, 3).join(', ')}, +${labels.length - 3}`;- }, [toolNames, localize, mcpServerNames]);+ /** For a single-tool group, lead with the tool's own (capitalized) label+ * instead of the generic "Used 1 tool: name", which reads awkwardly. */+ const singleToolLabel = useMemo(() => {+ const raw = getToolDisplayLabel(toolMetadata[0]?.name ?? '', localize, mcpServerNames);+ return raw ? raw.charAt(0).toUpperCase() + raw.slice(1) : '';+ }, [toolMetadata, localize, mcpServerNames]);const autoExpand = useRecoilValue(store.autoExpandTools);/** A labeled activity block is summarized by its header, so it collapses* even at a single tool call — agent runs are full of one-call batches,* and leaving those expanded defeats the grouping. */- const autoCollapse = !autoExpand && allCompleted && (count >= 2 || activityLabelText.length > 0);+ /** Every group has >= 1 tool; collapse a completed one by default just like+ * a multi-tool group, so a lone tool-with-thinking group (a skill, say)+ * stays visually consistent with the larger groups around it. */+ /** A folded-in THINK part only renders inside this body, so auto-collapsing+ * a completed reasoning-bearing group leaves "Open Thinking Dropdowns by+ * Default" with no visible effect until the user opens the action group by+ * hand (on reload the body is not even mounted). */+ const autoCollapse =+ !autoExpand &&+ !(showThinking && hasReasoning) &&+ allCompleted &&+ (count >= 1 || activityLabelText.length > 0);const suppressAutoExpand = withinActivityPhase && !hasPendingApproval;const initialState = initialExpansionState?.userOverride === true ? initialExpansionState : null;const [isExpanded, setIsExpanded] = useState(@@ -305,25 +484,85 @@ export default function ToolCallGroup({}}, [hasPendingApproval, isExpanded, notifyLayoutChange]);- /** Category-aware header verb: subagents and questions read as their own- * category (with tense), everything else is the generic "Used N tools". */+ const searchCount = activitySummary.webSearchCount + activitySummary.fileSearchCount;+ const searchesOnly = count > 0 && searchCount === count;+ const groupDone = allCompleted || !isSubmitting;++ /** Outcome-first header verb. Homogeneous searches, subagents, and questions+ * read as the activity the assistant performed. Mixed implementation-level+ * tool calls fall back to the user-facing concept of "actions". */const resolveGroupLabel = (): string => {if (allSubagents) {+ if (count === 1) {+ return localize(subagentsDone ? 'com_ui_subagent_complete' : 'com_ui_subagent_running');+ }return subagentsDone? localize('com_ui_ran_n_agents', { 0: String(count) }): localize('com_ui_running_n_agents', { 0: String(count) });}if (allAskQuestions) {+ if (count === 1) {+ return localize(+ askQuestionsDone ? 'com_ui_asked_one_question' : 'com_ui_asking_one_question',+ );+ }return askQuestionsDone? localize('com_ui_asked_n_questions', { 0: String(count) }): localize('com_ui_asking_n_questions', { 0: String(count) });}- return localize('com_ui_used_n_tools', { 0: String(count) });+ if (activitySummary.webSearchCount === count) {+ return localize(groupDone ? 'com_ui_web_searched' : 'com_ui_web_searching');+ }+ if (activitySummary.fileSearchCount === count) {+ return localize(groupDone ? 'com_ui_retrieved_files' : 'com_ui_searching_files');+ }+ if (searchesOnly) {+ return localize(+ groupDone ? 'com_ui_searched_web_and_files' : 'com_ui_searching_web_and_files',+ );+ }+ if (count === 1) {+ return singleToolLabel || localize('com_ui_used_one_tool');+ }+ return localize(groupDone ? 'com_ui_ran_n_actions' : 'com_ui_running_n_actions', {+ 0: String(count),+ });};/** The generated line wins over the generic category verb — but only once* it exists. An unfilled label part leaves the block rendering exactly as* it would without the feature. */const groupLabel = activityLabelText.length > 0 ? activityLabelText : resolveGroupLabel();+ const groupDetailParts: string[] = [];+ if (searchesOnly && count > 1) {+ groupDetailParts.push(localize('com_ui_n_searches', { 0: String(count) }));+ } else if (!allSubagents && !allAskQuestions && count > 1) {+ groupDetailParts.push(activitySummary.toolNameSummary);+ }+ if (activitySummary.failedCount > 0) {+ groupDetailParts.push(+ localize(+ activitySummary.failedCount === 1 ? 'com_ui_one_action_failed' : 'com_ui_n_actions_failed',+ { 0: String(activitySummary.failedCount) },+ ),+ );+ }+ /** A stopped action is settled but not successful, and its only other notice+ * lives inside the panel the group is about to collapse, so the header has+ * to say so. */+ if (activitySummary.cancelledCount > 0) {+ groupDetailParts.push(+ localize(+ activitySummary.cancelledCount === 1+ ? 'com_ui_one_action_cancelled'+ : 'com_ui_n_actions_cancelled',+ { 0: String(activitySummary.cancelledCount) },+ ),+ );+ }+ const groupDetail = groupDetailParts.filter(Boolean).join(' · ');+ const groupAriaLabel = [groupLabel, groupDetail, hasReasoning ? localize('com_ui_thoughts') : '']+ .filter(Boolean)+ .join(', ');/** Single category glyph for homogeneous groups (else StackedToolIcons). */const CategoryIcon = allSubagents ? Users : MessageCircleQuestion;@@ -331,6 +570,10 @@ export default function ToolCallGroup({() => isSubmitting && toolMetadata.some((m) => m && !m.hasOutput),[toolMetadata, isSubmitting],);+ const hasPendingAuthRequest = useMemo(+ () => parts.some(({ part }) => hasPendingAuth(part)),+ [parts],+ );useEffect(() => {if (hasActiveToolCall && !userOverride && !suppressAutoExpand) {@@ -347,7 +590,7 @@ export default function ToolCallGroup({className="inline-flex h-auto w-full items-center justify-start gap-2 rounded-none bg-transparent p-0 py-1 text-text-secondary hover:bg-transparent hover:text-text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy focus-visible:ring-offset-0"onClick={handleToggle}aria-expanded={isExpanded}- aria-label={groupLabel}+ aria-label={groupAriaLabel}>{allSubagents || allAskQuestions ? (/** Homogeneous category groups get a single category glyph instead@@ -385,12 +628,12 @@ export default function ToolCallGroup({>{groupLabel}</span>- {/** Hide the tool-name summary for pure-category groups (subagents /- * questions) — every entry deduplicates to the same token, which- * adds noise without info. Mixed groups keep the summary. */}- {toolNameSummary && !allSubagents && !allAskQuestions && (- <span className="min-w-0 max-w-[40%] truncate text-xs font-normal text-text-secondary">- · {toolNameSummary}+ {groupDetail && (+ <span+ className="min-w-0 max-w-[40%] truncate text-xs font-normal text-text-secondary"+ title={groupDetail}+ >+ · {groupDetail}</span>)}<ChevronDown@@ -409,16 +652,59 @@ export default function ToolCallGroup({>{shouldRenderBody && (<div className="overflow-hidden" ref={expandRef}>- <div className="py-0.5 pl-4">- {parts.map(({ part, idx }) =>- renderPart(part, idx, isLast && idx === lastContentIdx, handleToolExpand),- )}- </div>+ <ToolAuthWarningContext.Provider value>+ <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}`}+ reasoning={reasoning}+ label={label}+ showThinking={showThinking}+ isAfterTool={isAfterTool}+ isStreaming={streaming}+ />+ );+ }+ return renderPart(part, idx, isLast && idx === lastContentIdx, handleToolExpand);+ })}+ </div>+ </ToolAuthWarningContext.Provider>+ {hasPendingAuthRequest && <ToolAuthWarning className="mb-1 mt-2.5" />}</div>)}</div>{groupAttachments && groupAttachments.length > 0 && (- <AttachmentGroup attachments={groupAttachments} />+ <>+ <SearchVerticals attachments={groupAttachments} />+ <AttachmentGroup attachments={groupAttachments} />+ </>)}</div>);diff --git a/client/src/components/Chat/Messages/Content/ToolOutput/OutputRenderer.tsx b/client/src/components/Chat/Messages/Content/ToolOutput/OutputRenderer.tsxindex 13015cac4e..6d18065ea1 100644--- a/client/src/components/Chat/Messages/Content/ToolOutput/OutputRenderer.tsx+++ b/client/src/components/Chat/Messages/Content/ToolOutput/OutputRenderer.tsx@@ -114,32 +114,34 @@ export default function OutputRenderer({ text }: OutputRendererProps) {const structured = !isJson && isStructuredText(displayText);return (- <div className="relative">- {isJson ? (- <pre className="max-h-[300px] overflow-auto rounded text-xs">- <code className="hljs language-json !whitespace-pre-wrap !break-words">+ <div>+ <div className="relative pr-10">+ {isJson ? (+ <pre className="max-h-[300px] overflow-auto rounded text-xs">+ <code className="hljs language-json !whitespace-pre-wrap !break-words">+ {visibleText}+ </code>+ </pre>+ ) : (+ <pre+ className={cn(+ 'max-h-[300px] overflow-auto whitespace-pre-wrap break-words text-xs',+ error && 'font-mono text-status-error',+ !error && structured && 'font-mono text-text-secondary',+ !error && !structured && 'font-sans text-sm text-text-primary',+ )}+ >{visibleText}- </code>- </pre>- ) : (- <pre- className={cn(- 'max-h-[300px] overflow-auto whitespace-pre-wrap break-words text-xs',- error && 'font-mono text-status-error',- !error && structured && 'font-mono text-text-secondary',- !error && !structured && 'font-sans text-sm text-text-primary',- )}- >- {visibleText}- </pre>- )}- <div className="absolute bottom-0 right-0">- <CopyButton- isCopied={isCopied}- onClick={handleCopy}- iconOnly- label={localize('com_ui_copy')}- />+ </pre>+ )}+ <div className="absolute right-0 top-1/2 -translate-y-1/2">+ <CopyButton+ isCopied={isCopied}+ onClick={handleCopy}+ iconOnly+ label={localize('com_ui_copy')}+ />+ </div></div>{needsTruncation && (<Buttondiff --git a/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx b/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsxindex 0c13b73f37..21ec24fdfc 100644--- a/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx+++ b/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx@@ -8,6 +8,7 @@ import {FileText,MessageCircleQuestion,ScrollText,+ Brain,Zap,Wrench,} from 'lucide-react';@@ -30,6 +31,7 @@ export type ToolIconType =| 'read_file'| 'bash_tool'| 'ask_user_question'+ | 'memory'| 'action'| 'generic';@@ -44,6 +46,7 @@ const ICON_MAP: Record<ToolIconType, React.ComponentType<{ className?: string }>read_file: FileText,bash_tool: BashIcon,ask_user_question: MessageCircleQuestion,+ memory: Brain,action: Zap,generic: Wrench,};@@ -82,6 +85,9 @@ export function getToolIconType(name: string): ToolIconType {if (name === 'ask_user_question') {return 'ask_user_question';}+ if (name === 'set_memory' || name === 'delete_memory') {+ return 'memory';+ }if (name.startsWith(Constants.LC_TRANSFER_TO_)) {return 'agent_handoff';}diff --git a/client/src/components/Chat/Messages/Content/ToolOutput/__tests__/OutputRenderer.test.tsx b/client/src/components/Chat/Messages/Content/ToolOutput/__tests__/OutputRenderer.test.tsxnew file mode 100644index 0000000000..4a4df41eab--- /dev/null+++ b/client/src/components/Chat/Messages/Content/ToolOutput/__tests__/OutputRenderer.test.tsx@@ -0,0 +1,24 @@+import React from 'react';+import { render, screen } from '@testing-library/react';+import OutputRenderer from '../OutputRenderer';++jest.mock('copy-to-clipboard', () => jest.fn());++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++jest.mock('~/components/Messages/Content/CopyButton', () => ({+ __esModule: true,+ default: () => <button type="button" data-testid="copy-output" />,+}));++describe('OutputRenderer', () => {+ it('vertically centers the copy control beside the output', () => {+ render(<OutputRenderer text={'First line\nSecond line'} />);++ const copyPositioner = screen.getByTestId('copy-output').parentElement;+ expect(copyPositioner).toHaveClass('absolute', 'right-0', 'top-1/2', '-translate-y-1/2');+ expect(copyPositioner?.parentElement).toHaveClass('relative', 'pr-10');+ });+});diff --git a/client/src/components/Chat/Messages/Content/WebSearch.tsx b/client/src/components/Chat/Messages/Content/WebSearch.tsxindex 42cc72b3ab..342910b39d 100644--- a/client/src/components/Chat/Messages/Content/WebSearch.tsx+++ b/client/src/components/Chat/Messages/Content/WebSearch.tsx@@ -1,18 +1,30 @@import { useMemo, useState, useEffect } from 'react';import { useRecoilValue } from 'recoil';import { Tools } from 'librechat-data-provider';-import { Globe, ChevronDown } from 'lucide-react';+import { Globe, ChevronDown, Info } from 'lucide-react';+import {+ Button,+ HoverCard,+ HoverCardTrigger,+ HoverCardPortal,+ HoverCardContent,+ disclosureChevronVariants,+} from '@librechat/client';import type {TAttachment,ValidSource,SearchResultData,PartMetadata,+ AnswerBoxResult,} from 'librechat-data-provider';import { FaviconImage, getCleanDomain } from '~/components/Web/SourceHovercard';import { useLocalize, useExpandCollapse, useLazyCollapseBody } from '~/hooks';import { StackedFavicons } from '~/components/Web/Sources';+import { toolPanelSpacingClassName } from './disclosure';+import parseJsonField from './Parts/parseJsonField';import { useToolCallIntent } from './Parts/intent';import { useSearchContext } from '~/Providers';+import SearchVerticals from './verticals';import { ROW_GLYPH_SLOT } from './rows';import cn from '~/utils/cn';import store from '~/store';@@ -90,6 +102,7 @@ export default function WebSearch({args,output,attachments,+ hideAttachments = false,onExpand,runStepStatus,}: {@@ -99,6 +112,7 @@ export default function WebSearch({output?: string | null;initialProgress: number;attachments?: TAttachment[];+ hideAttachments?: boolean;onExpand?: () => void;runStepStatus?: PartMetadata['runStepStatus'];}) {@@ -155,7 +169,7 @@ export default function WebSearch({}, [attachments]);const allSources = useMemo((): ValidSource[] => {- if (attachments) {+ if (attachments != null) {const turnMap: Record<string, SearchResultData> = {};for (const att of attachments) {if (att.type === Tools.web_search && att[Tools.web_search]) {@@ -164,9 +178,7 @@ export default function WebSearch({turnMap[key] = data;}}- if (Object.keys(turnMap).length > 0) {- return collectSources(turnMap);- }+ return collectSources(turnMap);}if (searchResults?.[ownTurn]) {return collectSources({ [ownTurn]: searchResults[ownTurn] });@@ -174,6 +186,29 @@ export default function WebSearch({return [];}, [searchResults, attachments, ownTurn]);+ /** Direct-answer card shown at the top of the source list. Attachment-only:+ * answer boxes are provider extras (Serper) that never carry citations, so+ * the streaming path does not need them. */+ const answerBox = useMemo((): AnswerBoxResult | undefined => {+ if (!attachments) {+ return undefined;+ }+ for (const att of attachments) {+ const answer = att.type === Tools.web_search ? att[Tools.web_search]?.answerBox : undefined;+ if (answer) {+ return answer;+ }+ }+ return undefined;+ }, [attachments]);+ /** `snippet` and `snippetHighlighted` are independently optional, and+ * `hasDetails` opens the card for ANY answer box, so a provider result+ * carrying only highlights rendered a heading with an empty body. */+ const answerText = useMemo(+ () => answerBox?.snippet || answerBox?.snippetHighlighted?.join(' ') || undefined,+ [answerBox],+ );+// Show favicons from the raw SERP results immediately rather than waiting for// each source to flip to `processed`; the agents scrape barrier would otherwise// freeze the stack on "Searching the web" for the slowest scrape's duration.@@ -181,12 +216,8 @@ export default function WebSearch({if (complete && !finalizing) {return [];}- const result = searchResults?.[ownTurn];- if (!result) {- return [];- }- return [...(result.organic || []), ...(result.topStories || [])];- }, [searchResults, complete, finalizing, ownTurn]);+ return allSources;+ }, [allSources, complete, finalizing]);const showSources = streamingSources.length > 0;/** Stable phase text: the live region must not re-announce the growing@@ -207,6 +238,7 @@ export default function WebSearch({const autoExpand = useRecoilValue(store.autoExpandTools);const sourceCount = allSources.length;+ const [showDetails, setShowDetails] = useState(false);const [showSourceList, setShowSourceList] = useState(() => autoExpand && sourceCount > 0);const { style: sourceExpandStyle, ref: sourceExpandRef } = useExpandCollapse(showSourceList);const { shouldRenderBody, mountBody, handleTransitionEnd } = useLazyCollapseBody(showSourceList);@@ -235,54 +267,123 @@ export default function WebSearch({if (complete) {const hasSourceData = sourceCount > 0;const completedText = intent ?? localize('com_ui_web_searched');+ const query = parseJsonField(args, 'query');+ const hasDetails = !!query || !!answerBox;return (- <div className="mb-2">+ <div className="group/websearch my-1"><span className="sr-only" aria-live="polite" aria-atomic="true">{completedText}</span>- <button- type="button"- className={cn(- 'tool-status-text group flex items-center gap-2 rounded-full py-1 transition-colors',- hasSourceData- ? 'text-text-secondary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy'- : 'pointer-events-none text-text-secondary',- )}- disabled={!hasSourceData}- onClick={hasSourceData ? handleToggleSources : undefined}- aria-expanded={hasSourceData ? showSourceList : undefined}- aria-label={- hasSourceData- ? `${completedText} - ${localize(sourceCount === 1 ? 'com_ui_web_search_source' : 'com_ui_web_search_sources', { count: sourceCount })}`- : completedText- }- >- <span className={ROW_GLYPH_SLOT} aria-hidden="true">- {hasSourceData ? (- <SourceFaviconStack sources={allSources} />- ) : (- <Globe className="size-4 shrink-0 text-text-secondary" />+ <div className="relative flex h-5 items-center gap-1.5">+ <Button+ variant="ghost"+ className={cn(+ 'tool-status-text group/disclosure h-5 min-w-0 justify-start gap-2 rounded-full p-0 font-normal text-text-secondary hover:bg-transparent',+ /** This row is a status line, not a padded control: the shared+ * recipe's color transition would turn its hover into a fade,+ * and the chevron reveal beside it is deliberately instant. */+ 'transition-none',+ !hasSourceData && 'pointer-events-none disabled:opacity-100',)}- </span>- <span className="min-w-0 truncate font-medium">{completedText}</span>- {hasSourceData && (- <ChevronDown- className={cn(- 'size-3.5 shrink-0 text-text-secondary transition-transform duration-200',- showSourceList && 'rotate-180',+ disabled={!hasSourceData}+ onClick={hasSourceData ? handleToggleSources : undefined}+ aria-expanded={hasSourceData ? showSourceList : undefined}+ aria-label={+ hasSourceData+ ? `${completedText} - ${localize(sourceCount === 1 ? 'com_ui_web_search_source' : 'com_ui_web_search_sources', { count: sourceCount })}`+ : completedText+ }+ >+ <span className={ROW_GLYPH_SLOT} aria-hidden="true">+ {hasSourceData ? (+ <SourceFaviconStack sources={allSources} />+ ) : (+ <Globe className="size-4 shrink-0 text-text-secondary" />)}- aria-hidden="true"- />+ </span>+ <span className="min-w-0 truncate font-medium">{completedText}</span>+ {hasSourceData && (+ <ChevronDown+ className={cn(disclosureChevronVariants({ expanded: showSourceList }), 'size-3.5')}+ aria-hidden="true"+ />+ )}+ </Button>+ {hasDetails && (+ <HoverCard openDelay={50} open={showDetails} onOpenChange={setShowDetails}>+ {/* Composed through `asChild` so the shared Button owns the+ rounding, hover fill, focus ring and motion (and gives a real+ <button> instead of Radix's default anchor). Only the+ hover-card reveal and the icon geometry stay local. */}+ <HoverCardTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ className={cn(+ 'ml-auto size-auto cursor-help rounded-md p-1 text-text-secondary opacity-0',+ 'group-focus-within/websearch:opacity-100 group-hover/websearch:opacity-100',+ 'focus-visible:opacity-100',+ )}+ onFocus={() => setShowDetails(true)}+ onBlur={() => setShowDetails(false)}+ aria-label={localize('com_ui_web_search_details')}+ >+ <Info className="size-3.5" aria-hidden="true" />+ </Button>+ </HoverCardTrigger>+ <HoverCardPortal>+ <HoverCardContent side="top" className="z-[999] w-80">+ <div className="max-h-[60vh] space-y-2 overflow-y-auto">+ {query && (+ <div>+ <div className="text-[10px] font-medium uppercase tracking-wide text-text-secondary">+ {localize('com_ui_search_query')}+ </div>+ <div className="mt-0.5 text-sm text-text-primary">{query}</div>+ </div>+ )}+ <div className="text-xs text-text-secondary">+ {localize(+ sourceCount === 1+ ? 'com_ui_web_search_source'+ : 'com_ui_web_search_sources',+ { count: sourceCount },+ )}+ </div>+ {answerBox && (answerBox.title || answerText) && (+ <div className="border-t border-border-light pt-2">+ {answerBox.title && (+ <div className="text-sm font-medium text-text-primary">+ {answerBox.title}+ </div>+ )}+ {answerText && (+ <div className="mt-1 text-xs leading-relaxed text-text-secondary">+ {answerText}+ </div>+ )}+ </div>+ )}+ </div>+ </HoverCardContent>+ </HoverCardPortal>+ </HoverCard>)}- </button>+ </div>{hasSourceData && (<div style={sourceExpandStyle} onTransitionEnd={handleTransitionEnd}><div className="overflow-hidden" ref={sourceExpandRef}>{shouldRenderBody && (- <div className="my-2 max-h-[280px] overflow-y-auto rounded-lg border border-border-light">+ <div+ className={cn(+ toolPanelSpacingClassName,+ 'mt-1.5 max-h-[280px] overflow-y-auto rounded-lg border border-border-light',+ )}+ >{allSources.map((source, i) => {const domain = getCleanDomain(source.link);+ const snippet = 'snippet' in source ? source.snippet : undefined;return (<akey={source.link}@@ -290,15 +391,33 @@ export default function WebSearch({target="_blank"rel="noopener noreferrer"className={cn(- 'flex items-center gap-2.5 px-3 py-2 transition-colors hover:bg-surface-hover',+ 'flex gap-2.5 px-3 py-2 transition-colors hover:bg-surface-hover',+ snippet ? 'items-start' : 'items-center',i > 0 && 'border-t border-border-light',)}>- <FaviconImage domain={domain} className="size-4 shrink-0 rounded-sm" />- <span className="min-w-0 flex-1 truncate text-xs font-medium text-text-primary">- {source.title || domain}+ <FaviconImage+ domain={domain}+ className={cn('size-4 shrink-0 rounded-sm', snippet && 'mt-0.5')}+ />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-xs font-medium text-text-primary">+ {source.title || domain}+ </span>+ {snippet && (+ <span className="mt-0.5 line-clamp-2 block text-[11px] leading-relaxed text-text-secondary">+ {snippet}+ </span>+ )}+ </span>+ <span className="shrink-0 text-right">+ <span className="block text-[11px] text-text-secondary">{domain}</span>+ {source.date && (+ <span className="block text-[10px] text-text-secondary">+ {source.date}+ </span>+ )}</span>- <span className="shrink-0 text-[11px] text-text-secondary">{domain}</span></a>);})}@@ -307,12 +426,13 @@ export default function WebSearch({</div></div>)}+ {!hideAttachments && <SearchVerticals attachments={attachments} />}</div>);}return (- <div className="my-1 flex items-center gap-2">+ <div className="relative my-1 flex h-5 shrink-0 items-center gap-2"><span className="sr-only" aria-live="polite" aria-atomic="true">{genericProgressText}</span>diff --git a/client/src/components/Chat/Messages/Content/__tests__/ActivityPhaseGroup.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ActivityPhaseGroup.test.tsxindex f11898f86b..172bcd94aa 100644--- a/client/src/components/Chat/Messages/Content/__tests__/ActivityPhaseGroup.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/ActivityPhaseGroup.test.tsx@@ -1,6 +1,6 @@-import { ContentTypes } from 'librechat-data-provider';+import { ContentTypes, Tools } from 'librechat-data-provider';import { act, fireEvent, render, screen } from '@testing-library/react';-import type { TMessageContentParts } from 'librechat-data-provider';+import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';import { ROW_GLYPH_SLOT, TOOL_ROW_CLASSES } from '../rows';import ActivityPhaseGroup from '../ActivityPhaseGroup';@@ -16,6 +16,7 @@ jest.mock('~/hooks', () => {const expandCollapse = jest.requireActual('~/hooks/Messages/useExpandCollapse');const lazyCollapseBody = jest.requireActual('~/hooks/Messages/useLazyCollapseBody');return {+ useLocalize: () => (key: string) => key,useExpandCollapse: expandCollapse.default,useLazyCollapseBody: lazyCollapseBody.default,EXPAND_TRANSITION: expandCollapse.EXPAND_TRANSITION,@@ -40,6 +41,22 @@ const makeLabelPart = (const labelPart = makeLabelPart(LABEL);const nextLabelPart = makeLabelPart(NEXT_LABEL);+/** A completed web search inside the phase: `AttachmentGroup` discards the+ * `web_search` type, so only `SearchVerticals` can surface these. */+const searchAttachment = {+ type: Tools.web_search,+ [Tools.web_search]: {+ images: [+ {+ title: 'A pictured result',+ imageUrl: 'https://example.com/pic.png',+ thumbnailUrl: 'https://example.com/thumb.png',+ link: 'https://example.com/page',+ },+ ],+ },+} as unknown as TAttachment;+describe('ActivityPhaseGroup', () => {let frames: Array<FrameRequestCallback | undefined>;const originalRequestAnimationFrame = window.requestAnimationFrame;@@ -366,4 +383,21 @@ describe('ActivityPhaseGroup', () => {fireEvent.transitionEnd(screen.getByTestId('activity-phase-panel'));expect(screen.queryByTestId('phase-content')).not.toBeInTheDocument();});++ test('hoists a folded search call verticals out of the card', () => {+ /** The nested segment renders with `hideAttachments`, standing its own+ * `WebSearch` verticals down for this hoist, and `AttachmentGroup` drops+ * `web_search` attachments outright — so the card is the only surface+ * left for a folded search's images, products and places. */+ render(+ <ActivityPhaseGroup labelPart={labelPart} hasContent attachments={[searchAttachment]}>+ <div data-testid="phase-content" />+ </ActivityPhaseGroup>,+ );++ const image = screen.getByRole('link', { name: 'A pictured result' });+ expect(image).toHaveAttribute('href', 'https://example.com/page');+ /** Outside the fold: collapsing the card must not take the media with it. */+ expect(screen.getByTestId('activity-phase-panel')).not.toContainElement(image);+ });});diff --git a/client/src/components/Chat/Messages/Content/__tests__/AgentHandoff.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/AgentHandoff.test.tsxindex 7a68d0a182..8281ac43bf 100644--- a/client/src/components/Chat/Messages/Content/__tests__/AgentHandoff.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/AgentHandoff.test.tsx@@ -1,6 +1,6 @@import React from 'react';import { RecoilRoot } from 'recoil';-import { render, screen } from '@testing-library/react';+import { fireEvent, render, screen } from '@testing-library/react';import AgentHandoff from '../AgentHandoff';jest.mock('~/hooks', () => ({@@ -9,6 +9,8 @@ jest.mock('~/hooks', () => ({com_ui_transferred_to: 'Transferred to',com_ui_agent: 'Agent',com_ui_handoff_instructions: 'Handoff instructions',+ com_ui_copy_to_clipboard: 'Copy to clipboard',+ com_ui_copied_to_clipboard: 'Copied to clipboard',};return translations[key] || key;},@@ -35,12 +37,21 @@ jest.mock('~/components/Share/MessageIcon', () => ({jest.mock('lucide-react', () => ({ChevronDown: () => <span data-testid="chevron-down" />,+ /** The shared CopyButton/ActionButton composition renders both. */+ Copy: () => <span data-testid="copy-icon" />,+ Check: () => <span data-testid="check-icon" />,}));jest.mock('~/utils', () => ({cn: (...classes: (string | boolean | undefined)[]) => classes.filter(Boolean).join(' '),}));+const mockCopy = jest.fn(() => true);+jest.mock('copy-to-clipboard', () => ({+ __esModule: true,+ default: (...args: unknown[]) => mockCopy(...(args as [])),+}));+const renderAgentHandoff = (props: {name: string;args: string | Record<string, unknown>;@@ -52,14 +63,19 @@ const renderAgentHandoff = (props: {</RecoilRoot>,);-describe('AgentHandoff - A11Y accessibility stubs', () => {+describe('AgentHandoff', () => {+ beforeEach(() => {+ mockCopy.mockClear();+ mockCopy.mockReturnValue(true);+ });+it('A11Y-01: renders a semantic button element when hasInfo is true', () => {renderAgentHandoff({name: 'lc_transfer_to_agent-123',args: '{"key":"value"}',});- const button = screen.getByRole('button');+ const button = screen.getByRole('button', { name: /Transferred to/i });expect(button.tagName).toBe('BUTTON');});@@ -69,7 +85,7 @@ describe('AgentHandoff - A11Y accessibility stubs', () => {args: '{"key":"value"}',});- const button = screen.getByRole('button');+ const button = screen.getByRole('button', { name: /Transferred to/i });expect(button).toHaveAttribute('aria-label');expect(button.getAttribute('aria-label')).toContain('Transferred to');expect(button.getAttribute('aria-label')).toContain('Test Agent');@@ -81,17 +97,104 @@ describe('AgentHandoff - A11Y accessibility stubs', () => {args: '{"key":"value"}',});- const button = screen.getByRole('button');+ const button = screen.getByRole('button', { name: /Transferred to/i });expect(button.className).toContain('focus-visible:ring-2');});- it('A11Y-03: disabled button is rendered when hasInfo is false', () => {+ it('A11Y-04: disabled button is rendered when hasInfo is false', () => {renderAgentHandoff({name: 'lc_transfer_to_agent-123',args: '',});- const button = screen.getByRole('button');+ const button = screen.getByRole('button', { name: /Transferred to/i });expect(button).toBeDisabled();});++ it('renders the handoff instruction as prose instead of JSON', () => {+ const { container } = renderAgentHandoff({+ name: 'lc_transfer_to_agent-123',+ args: JSON.stringify({+ instructions: 'Review the rollout, validate retention, and report blockers.',+ }),+ });++ fireEvent.click(screen.getByRole('button', { name: /Transferred to/i }));++ expect(+ screen.getByText('Review the rollout, validate retention, and report blockers.'),+ ).toBeInTheDocument();+ expect(container.querySelector('pre')).not.toBeInTheDocument();+ expect(screen.queryByText(/"instructions"/)).not.toBeInTheDocument();+ });++ it('copies the readable instruction rather than its JSON wrapper', async () => {+ renderAgentHandoff({+ name: 'lc_transfer_to_agent-123',+ args: JSON.stringify({ instructions: 'Review the rollout.' }),+ });++ fireEvent.click(screen.getByRole('button', { name: /Transferred to/i }));+ fireEvent.click(screen.getByRole('button', { name: 'Copy to clipboard' }));++ expect(mockCopy).toHaveBeenCalledWith('Review the rollout.', { format: 'text/plain' });+ expect(await screen.findByRole('button', { name: 'Copied to clipboard' })).toBeInTheDocument();+ });++ it('leaves the control idle when the clipboard is unavailable', () => {+ /** `copy-to-clipboard` returns false when it cannot reach a clipboard,+ * which is the case the async API turns into a synchronous throw. */+ mockCopy.mockReturnValueOnce(false);+ renderAgentHandoff({+ name: 'lc_transfer_to_agent-123',+ args: JSON.stringify({ instructions: 'Review the rollout.' }),+ });++ fireEvent.click(screen.getByRole('button', { name: /Transferred to/i }));+ fireEvent.click(screen.getByRole('button', { name: 'Copy to clipboard' }));++ expect(screen.getByRole('button', { name: 'Copy to clipboard' })).toBeInTheDocument();+ expect(screen.queryByRole('button', { name: 'Copied to clipboard' })).not.toBeInTheDocument();+ });++ it('supports object args and a custom handoff prompt key', () => {+ renderAgentHandoff({+ name: 'lc_transfer_to_agent-123',+ args: { work_items: 'Verify the migration plan.' },+ });++ fireEvent.click(screen.getByRole('button', { name: /Transferred to/i }));++ expect(screen.getByText('Verify the migration plan.')).toBeInTheDocument();+ expect(screen.queryByText('Work items')).not.toBeInTheDocument();+ });++ it('labels each value when a legacy handoff contains multiple fields', () => {+ renderAgentHandoff({+ name: 'lc_transfer_to_agent-123',+ args: JSON.stringify({+ work_items: 'Verify the migration plan.',+ priority: 'High',+ }),+ });++ fireEvent.click(screen.getByRole('button', { name: /Transferred to/i }));++ expect(screen.getByText('Work items')).toBeInTheDocument();+ expect(screen.getByText('Verify the migration plan.')).toBeInTheDocument();+ expect(screen.getByText('Priority')).toBeInTheDocument();+ expect(screen.getByText('High')).toBeInTheDocument();+ });++ it('renders a partially streamed instruction without exposing JSON syntax', () => {+ renderAgentHandoff({+ name: 'lc_transfer_to_agent-123',+ args: '{"instructions":"Review the rollout and report',+ });++ fireEvent.click(screen.getByRole('button', { name: /Transferred to/i }));++ expect(screen.getByText('Review the rollout and report')).toBeInTheDocument();+ expect(screen.queryByText(/"instructions"/)).not.toBeInTheDocument();+ });});diff --git a/client/src/components/Chat/Messages/Content/__tests__/ApprovalContext.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ApprovalContext.test.tsxindex fae45878a2..bbfee64788 100644--- a/client/src/components/Chat/Messages/Content/__tests__/ApprovalContext.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/ApprovalContext.test.tsx@@ -1,6 +1,7 @@import React from 'react';import { RecoilRoot } from 'recoil';import { act, renderHook } from '@testing-library/react';+import { Provider as JotaiProvider, createStore } from 'jotai';import type { MutableSnapshot } from 'recoil';import ApprovalProvider, { useApprovalContext, useResumeSubmit } from '../ApprovalContext';import { ChatContext } from '~/Providers/ChatContext';@@ -28,6 +29,7 @@ const chatContextValue = {const createWrapper = (generationCreatedAt: number | null) =>function ResumeWrapper({ children }: { children: React.ReactNode }) {+ const jotaiStore = React.useRef(createStore()).current;const initializeState = (snapshot: MutableSnapshot) => {if (generationCreatedAt != null) {snapshot.set(@@ -38,9 +40,11 @@ const createWrapper = (generationCreatedAt: number | null) =>};return (<RecoilRoot initializeState={initializeState}>- <ChatContext.Provider value={chatContextValue}>- <ApprovalProvider>{children}</ApprovalProvider>- </ChatContext.Provider>+ <JotaiProvider store={jotaiStore}>+ <ChatContext.Provider value={chatContextValue}>+ <ApprovalProvider>{children}</ApprovalProvider>+ </ChatContext.Provider>+ </JotaiProvider></RecoilRoot>);};diff --git a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestion.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestion.test.tsxindex 6601684dd4..ea47135432 100644--- a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestion.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestion.test.tsx@@ -1,13 +1,23 @@import React from 'react';import { RecoilRoot } from 'recoil';import { fireEvent, render, screen } from '@testing-library/react';+import type { Agents } from 'librechat-data-provider';import ApprovalProvider from '../ApprovalContext';import AskUserQuestion from '../AskUserQuestion';+const mockSubmitAnswer = jest.fn();+const mockSetAnswerText = jest.fn();+let mockPopoverVisible = false;+let mockCollapsed = false;+let mockLiveActionId: string | null = null;+let mockChecked: number[] = [];+let mockAnswerText = '';+jest.mock('~/hooks', () => ({useLocalize: () => (key: string) => {const labels: Record<string, string> = {com_ui_your_answer: 'Your answer',+ com_ui_skip: 'Skip',com_ui_submit: 'Submit',com_ui_submitting: 'Submitting',};@@ -18,14 +28,16 @@ jest.mock('~/hooks', () => ({jest.mock('~/hooks/Input/useAskAnswerMode', () => ({__esModule: true,default: () => ({- popoverVisible: false,- collapsed: false,+ popoverVisible: mockPopoverVisible,+ collapsed: mockCollapsed,expand: jest.fn(),- liveAsk: null,- checked: [],+ liveAsk: mockLiveActionId == null ? null : { actionId: mockLiveActionId },+ checked: mockChecked,toggleChecked: jest.fn(),submitOption: jest.fn(),- submitAnswer: jest.fn(),+ submitAnswer: mockSubmitAnswer,+ answerText: mockAnswerText,+ setAnswerText: mockSetAnswerText,}),}));@@ -39,18 +51,32 @@ jest.mock('~/store/agents', () => ({}));jest.mock('~/Providers/ChatContext', () => ({- ChatContext: jest.requireActual('react').createContext(null),+ ChatContext: jest.requireActual('react').createContext({+ conversation: { conversationId: 'conversation-1' },+ }),}));-const tree = (key: string) => (+const tree = (+ key: string,+ question: Agents.AskUserQuestionRequest = { question: 'Which environment?' },+) => (<RecoilRoot><ApprovalProvider>- <AskUserQuestion key={key} actionId="ask-1" question={{ question: 'Which environment?' }} />+ <AskUserQuestion key={key} actionId="ask-1" question={question} /></ApprovalProvider></RecoilRoot>);describe('AskUserQuestion', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockPopoverVisible = false;+ mockCollapsed = false;+ mockLiveActionId = null;+ mockChecked = [];+ mockAnswerText = '';+ });+test('restores a typed answer after the card remounts inside the same message', () => {const view = render(tree('direct'));fireEvent.change(screen.getByRole('textbox', { name: 'Your answer' }), {@@ -61,4 +87,26 @@ describe('AskUserQuestion', () => {expect(screen.getByRole('textbox', { name: 'Your answer' })).toHaveValue('Use staging first');});++ test('submits checked options together with free text carried from the composer', () => {+ mockCollapsed = true;+ mockLiveActionId = 'ask-1';+ mockChecked = [0];+ mockAnswerText = 'carried free-form answer';++ render(+ tree('live', {+ question: 'Choose a source',+ multiSelect: true,+ options: [{ label: 'Public data', value: 'public' }],+ }),+ );++ expect(screen.getByRole('textbox', { name: 'Your answer' })).toHaveValue(+ 'carried free-form answer',+ );+ fireEvent.click(screen.getByRole('button', { name: 'Submit' }));++ expect(mockSubmitAnswer).toHaveBeenCalledWith(['public', 'carried free-form answer']);+ });});diff --git a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCollapse.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCollapse.test.tsxindex eedb7287b3..2f3d9e7dfe 100644--- a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCollapse.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCollapse.test.tsx@@ -95,23 +95,24 @@ describe('collapsing a live ask_user_question', () => {fireEvent.click(screen.getByTestId('collapse-from-popover'));expect(screen.getByTestId('popover-visible').textContent).toBe('false');- /** The pause is still live — the card has it now... */- expect(screen.getByTestId('active').textContent).toBe('true');+ /** The pause is still live, but the card owns it outside answer mode. */+ expect(screen.getByTestId('active').textContent).toBe('false');expect(screen.getByText('North star or full funnel?')).toBeInTheDocument();- /** ...and the composer is a composer again. */+ /** The composer is a normal composer again. */expect(screen.getByTestId('composer-locked').textContent).toBe('false');expect(screen.getByTestId('composer-answers').textContent).toBe('false');});- it('gives the collapsed card the popover’s dismiss', () => {+ it('moves the collapsed card back to the popover', () => {renderPause();fireEvent.click(screen.getByTestId('collapse-from-popover'));- expect(screen.getByLabelText('Expand')).toBeInTheDocument();- fireEvent.click(screen.getByLabelText('Close'));+ fireEvent.click(screen.getByLabelText('Expand'));- /** Dismiss exits answer mode entirely, exactly as the popover’s × did. */- expect(screen.getByTestId('active').textContent).toBe('false');+ expect(screen.getByTestId('active').textContent).toBe('true');+ expect(screen.getByTestId('popover-visible').textContent).toBe('true');+ expect(screen.getByTestId('composer-locked').textContent).toBe('true');+ expect(screen.queryByLabelText('Expand')).not.toBeInTheDocument();});});@@ -120,22 +121,22 @@ describe('collapsing a live ask_user_question', () => {mockLiveAsk = { actionId: 'act-1', question: mockSingle, messageId: 'message-1' };});- it('keeps the composer as the answer box, and still offers a dismiss', () => {+ it('releases the composer until the card moves back to the popover', () => {renderPause();expect(screen.getByTestId('composer-answers').textContent).toBe('true');expect(screen.getByTestId('composer-locked').textContent).toBe('false');fireEvent.click(screen.getByTestId('collapse-from-popover'));- /** A single question is answered IN the composer, so it stays the answer- * box past collapse — the card is only the display handing over. */- expect(screen.getByTestId('composer-answers').textContent).toBe('true');+ /** The card now owns the answer, so the normal composer is available. */+ expect(screen.getByTestId('composer-answers').textContent).toBe('false');expect(screen.getByText('Which environment?')).toBeInTheDocument();- fireEvent.click(screen.getByLabelText('Close'));+ fireEvent.click(screen.getByLabelText('Answer from the message box'));- expect(screen.getByTestId('active').textContent).toBe('false');- expect(screen.getByTestId('composer-answers').textContent).toBe('false');+ expect(screen.getByTestId('active').textContent).toBe('true');+ expect(screen.getByTestId('composer-answers').textContent).toBe('true');+ expect(screen.getByTestId('popover-visible').textContent).toBe('true');});});});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.tsxindex 45a5fa814f..6ac97dad44 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@@ -1,14 +1,17 @@import React from 'react';import { RecoilRoot } from 'recoil';-import { ContentTypes } from 'librechat-data-provider';+import { ContentTypes, Tools } from 'librechat-data-provider';import { fireEvent, render, screen, within } from '@testing-library/react';import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';import ContentParts from '../ContentParts';jest.mock('~/hooks', () => ({useLocalize: () => (key: string, values?: Record<string | number, string>) => {- if (key === 'com_ui_used_n_tools') {- return `Used ${values?.[0]} tools`;+ if (key === 'com_ui_ran_n_actions') {+ return `Ran ${values?.[0]} actions`;+ }+ if (key === 'com_ui_running_n_actions') {+ return `Running ${values?.[0]} actions`;}return key;},@@ -87,6 +90,9 @@ jest.mock('../Parts', () => ({Reasoning: () => <div data-testid="reasoning" />,Summary: () => <div data-testid="summary" />,Text: ({ text }: { text?: string }) => <div data-testid="text">{text}</div>,+ MemoryCall: ({ attachments }: { attachments?: TAttachment[] }) => (+ <div data-testid="memory-call" data-count={attachments?.length ?? 0} />+ ),}));jest.mock('../MemoryArtifacts', () => ({@@ -96,7 +102,9 @@ jest.mock('../MemoryArtifacts', () => ({jest.mock('../WebSearch', () => ({__esModule: true,- default: () => <div data-testid="web-search" />,+ default: ({ attachments }: { attachments?: TAttachment[] }) => (+ <div data-testid="web-search" data-count={attachments?.length ?? 0} />+ ),}));jest.mock('../RetrievalCall', () => ({@@ -160,6 +168,24 @@ const makeMcpToolCall = (},}) as unknown as TMessageContentParts;+const makeOwnedToolCall = (+ name: string,+ id: string,+ stepId?: string,+ agentId?: string,+): TMessageContentParts =>+ ({+ type: ContentTypes.TOOL_CALL,+ [ContentTypes.TOOL_CALL]: {+ id,+ name,+ args: '{}',+ output: 'completed',+ ...(stepId == null ? {} : { stepId }),+ ...(agentId == null ? {} : { agentId }),+ },+ }) as unknown as TMessageContentParts;+const makeMcpToolCallWithoutId = (name: string, hasOutput = true): TMessageContentParts =>({type: ContentTypes.TOOL_CALL,@@ -208,6 +234,7 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {isCreatedByUser: false,isLast: true,isSubmitting: false,+ showThinking: false,isLatestMessage: true,};@@ -302,6 +329,75 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {expect(groups[0]).toHaveAttribute('data-count', '1');});+ it('routes producer-shaped search snapshots by agent and host step', () => {+ const content = [+ makeOwnedToolCall(Tools.web_search, 'call_0', 'step-search-1', 'agent-a'),+ makeTextPart('between searches'),+ makeOwnedToolCall(Tools.web_search, 'call_0', undefined, 'agent-a'),+ ];+ const attachments = [+ {+ type: Tools.web_search,+ messageId: 'm1',+ toolCallId: 'call_0',+ agentId: 'agent-a',+ stepId: 'step-search-1',+ conversationId: 'c1',+ [Tools.web_search]: { turn: 0, organic: [{ link: 'https://first.example' }] },+ },+ {+ type: Tools.web_search,+ messageId: 'm1',+ toolCallId: 'call_0',+ agentId: 'agent-a',+ stepId: 'step-search-2',+ conversationId: 'c1',+ [Tools.web_search]: { turn: 0, organic: [{ link: 'https://second.example' }] },+ },+ ] as unknown as TAttachment[];++ renderContentParts({ ...baseProps, content, attachments });++ expect(screen.getAllByTestId('web-search').map((card) => card.dataset.count)).toEqual([+ '1',+ '1',+ ]);+ });++ it('routes producer-shaped memory artifacts by agent and host step', () => {+ const content = [+ makeOwnedToolCall('set_memory', 'call_0', 'step-memory-1', 'agent-a'),+ makeTextPart('between memory writes'),+ makeOwnedToolCall('set_memory', 'call_0', undefined, 'agent-a'),+ ];+ const attachments = [+ {+ type: Tools.memory,+ messageId: 'm1',+ toolCallId: 'call_0',+ agentId: 'agent-a',+ stepId: 'step-memory-1',+ conversationId: 'c1',+ [Tools.memory]: { key: 'first', type: 'update' },+ },+ {+ type: Tools.memory,+ messageId: 'm1',+ toolCallId: 'call_0',+ agentId: 'agent-a',+ stepId: 'step-memory-2',+ conversationId: 'c1',+ [Tools.memory]: { key: 'second', type: 'update' },+ },+ ] as unknown as TAttachment[];++ renderContentParts({ ...baseProps, content, attachments });++ expect(screen.getAllByTestId('memory-call').map((card) => card.dataset.count)).toEqual([+ '1',+ '1',+ ]);+ });it('keeps a manually expanded completed tool group open when its content index shifts', () => {const content = [makeMcpToolCall('t1'), makeMcpToolCall('t2')];const nextContent = [makeTextPart('streamed preface'), ...content];@@ -312,7 +408,7 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {</RecoilRoot>,);- const toggle = screen.getByRole('button', { name: 'Used 2 tools' });+ const toggle = screen.getByRole('button', { name: /^Ran 2 actions/ });expect(toggle).toHaveAttribute('aria-expanded', 'false');fireEvent.click(toggle);@@ -324,7 +420,7 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {</RecoilRoot>,);- expect(screen.getByRole('button', { name: 'Used 2 tools' })).toHaveAttribute(+ expect(screen.getByRole('button', { name: /^Ran 2 actions/ })).toHaveAttribute('aria-expanded','true',);@@ -345,7 +441,7 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {</RecoilRoot>,);- const toggles = screen.getAllByRole('button', { name: 'Used 2 tools' });+ const toggles = screen.getAllByRole('button', { name: /Everything/ });fireEvent.click(toggles[1]);expect(toggles[0]).toHaveAttribute('aria-expanded', 'false');expect(toggles[1]).toHaveAttribute('aria-expanded', 'true');@@ -355,7 +451,7 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {<ContentParts {...baseProps} content={nextContent} /></RecoilRoot>,);- const shiftedToggles = screen.getAllByRole('button', { name: 'Used 2 tools' });+ const shiftedToggles = screen.getAllByRole('button', { name: /Everything/ });expect(shiftedToggles[0]).toHaveAttribute('aria-expanded', 'false');expect(shiftedToggles[1]).toHaveAttribute('aria-expanded', 'true');});@@ -386,7 +482,7 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {fireEvent.click(screen.getByRole('button', { name: 'First phase' }));fireEvent.click(screen.getByRole('button', { name: 'Second phase' }));- const toggles = screen.getAllByRole('button', { name: 'Used 2 tools' });+ const toggles = screen.getAllByRole('button', { name: /Everything/ });fireEvent.click(toggles[1]);rerender(@@ -400,7 +496,7 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {fireEvent.click(phaseToggle);}}- const shiftedToggles = screen.getAllByRole('button', { name: 'Used 2 tools' });+ const shiftedToggles = screen.getAllByRole('button', { name: /Everything/ });expect(shiftedToggles[0]).toHaveAttribute('aria-expanded', 'false');expect(shiftedToggles[1]).toHaveAttribute('aria-expanded', 'true');});@@ -418,7 +514,7 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {</RecoilRoot>,);- const toggle = screen.getByRole('button', { name: 'Used 2 tools' });+ const toggle = screen.getByRole('button', { name: /^Running 2 actions/ });expect(toggle).toHaveAttribute('aria-expanded', 'true');fireEvent.click(screen.getAllByTestId('progress-text')[0]);@@ -434,7 +530,7 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {</RecoilRoot>,);- expect(screen.getByRole('button', { name: 'Used 2 tools' })).toHaveAttribute(+ expect(screen.getByRole('button', { name: /^Ran 2 actions/ })).toHaveAttribute('aria-expanded','true',);@@ -449,7 +545,7 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {</RecoilRoot>,);- const toggle = screen.getByRole('button', { name: 'Used 2 tools' });+ const toggle = screen.getByRole('button', { name: /^Ran 2 actions/ });expect(toggle).toHaveAttribute('aria-expanded', 'false');fireEvent.click(toggle);@@ -461,7 +557,7 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {</RecoilRoot>,);- expect(screen.getByRole('button', { name: 'Used 2 tools' })).toHaveAttribute(+ expect(screen.getByRole('button', { name: /^Ran 2 actions/ })).toHaveAttribute('aria-expanded','false',);@@ -476,7 +572,7 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {</RecoilRoot>,);- const toggle = screen.getByRole('button', { name: 'Used 2 tools' });+ const toggle = screen.getByRole('button', { name: /^Ran 2 actions/ });expect(toggle).toHaveAttribute('aria-expanded', 'false');fireEvent.click(toggle);@@ -488,7 +584,7 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {</RecoilRoot>,);- expect(screen.getByRole('button', { name: 'Used 2 tools' })).toHaveAttribute(+ expect(screen.getByRole('button', { name: /^Ran 2 actions/ })).toHaveAttribute('aria-expanded','true',);@@ -502,6 +598,7 @@ describe('ContentParts — synthesized activity folds', () => {messageId: 'msg1',isCreatedByUser: false,isLast: true,+ showThinking: false,isSubmitting: false,isLatestMessage: true,};@@ -846,7 +943,7 @@ describe('ContentParts — synthesized activity folds', () => {content: [makeMcpToolCall('t1'), makeMcpToolCall('t2')],});- expect(screen.getByRole('button', { name: 'Used 2 tools' })).toBeInTheDocument();+ expect(screen.getByRole('button')).toHaveAttribute('aria-expanded', 'false');expect(screen.queryByTestId('activity-phase-panel')).toBeNull();});});@@ -857,6 +954,7 @@ describe('ContentParts integration: phase media row', () => {isCreatedByUser: false,isLast: true,isSubmitting: false,+ showThinking: false,isLatestMessage: true,};@@ -935,6 +1033,7 @@ describe('ContentParts integration: lane groups backed by one agent', () => {isCreatedByUser: false,isLast: true,isSubmitting: false,+ showThinking: false,isLatestMessage: true,};@@ -972,7 +1071,10 @@ describe('ContentParts integration: lane groups backed by one agent', () => {renderContentParts({ ...baseProps, content });- expect(screen.getByRole('button', { name: 'Used 2 tools' })).toBeInTheDocument();+ const toggle = screen.getByRole('button');+ expect(toggle).toHaveAttribute('aria-expanded', 'false');+ fireEvent.click(toggle);+ expect(toggle).toHaveAttribute('aria-expanded', 'true');});it('still renders columns once a second agent shares the group', () => {diff --git a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsxindex 7e3e96c855..bd5a2fb7ec 100644--- a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx@@ -174,6 +174,7 @@ const baseProps = {isSubmitting: false,isLatestMessage: false,isCreatedByUser: false,+ showThinking: false,content: [],};diff --git a/client/src/components/Chat/Messages/Content/__tests__/MemoryArtifacts.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/MemoryArtifacts.test.tsxindex 59bd54a093..98e1cc5158 100644--- a/client/src/components/Chat/Messages/Content/__tests__/MemoryArtifacts.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/MemoryArtifacts.test.tsx@@ -14,6 +14,14 @@ jest.mock('~/hooks', () => ({};return translations[key] || key;},+ useExpandCollapse: (isExpanded: boolean) => ({+ style: {+ display: 'grid',+ gridTemplateRows: isExpanded ? '1fr' : '0fr',+ opacity: isExpanded ? 1 : 0,+ },+ ref: { current: null },+ }),}));// Mock the MemoryInfo component@@ -66,8 +74,7 @@ describe('MemoryArtifacts', () => {render(<MemoryArtifacts attachments={attachments} />);const button = screen.getByRole('button');- expect(button).toHaveClass('text-text-secondary-alt');- expect(button).toHaveClass('hover:text-text-primary');+ expect(button).toHaveClass('text-text-secondary');expect(button).not.toHaveClass('text-status-error');});@@ -121,9 +128,50 @@ describe('MemoryArtifacts', () => {expect(button).toHaveClass('text-status-error');expect(screen.getByText('Memory Error')).toBeInTheDocument();});++ test('ignores attachments already rendered as an inline memory tool card', () => {+ /** A `set_memory`/`delete_memory` call routes to `MemoryCall`, which+ * shows the same key, value and outcome. Counting its attachment here+ * too rendered one mutation twice. `toolCallId` is the discriminator. */+ const linked = {+ ...createMemoryAttachment('update', 'memory1'),+ toolCallId: 'call_abc123',+ } as TAttachment;++ const { container } = render(<MemoryArtifacts attachments={[linked]} />);++ expect(container).toBeEmptyDOMElement();+ });++ test('still renders a memory attachment carrying no tool call id', () => {+ render(<MemoryArtifacts attachments={[createMemoryAttachment('update', 'memory1')]} />);++ fireEvent.click(screen.getByRole('button'));++ expect(screen.getByTestId('memory-artifact-update')).toBeInTheDocument();+ });});describe('Collapse/Expand Functionality', () => {+ test('uses the standard tool row and expanded panel styling', () => {+ const attachments = [createMemoryAttachment('update', 'memory1')];++ render(<MemoryArtifacts attachments={attachments} />);++ const button = screen.getByRole('button');+ expect(button.parentElement).toHaveClass('my-1', 'h-5');+ expect(button).toHaveClass('group/disclosure');++ fireEvent.click(button);++ expect(screen.getByTestId('memory-info').parentElement).toHaveClass(+ 'mb-2',+ 'mt-0',+ 'rounded-lg',+ 'bg-surface-secondary',+ );+ });+test('toggles memory info visibility on button click', () => {const attachments = [createMemoryAttachment('update', 'memory1')];diff --git a/client/src/components/Chat/Messages/Content/__tests__/MemoryInfo.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/MemoryInfo.test.tsxindex 5202b048c1..5efbc54d54 100644--- a/client/src/components/Chat/Messages/Content/__tests__/MemoryInfo.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/MemoryInfo.test.tsx@@ -8,8 +8,6 @@ import MemoryInfo from '../MemoryInfo';jest.mock('~/hooks', () => ({useLocalize: () => (key: string, params?: Record<string, any>) => {const translations: Record<string, string> = {- com_ui_memory_updated_items: 'Updated Memories',- com_ui_memory_deleted_items: 'Deleted Memories',com_ui_memory_already_exceeded: `Memory storage already full - exceeded by ${params?.tokens || 0} tokens. Delete existing memories before adding new ones.`,com_ui_memory_would_exceed: `Cannot save - would exceed limit by ${params?.tokens || 0} tokens. Delete existing memories to make space.`,com_ui_memory_deleted: 'This memory has been deleted',@@ -99,28 +97,6 @@ describe('MemoryInfo', () => {),).toBeInTheDocument();});-- test('applies correct styling to error messages', () => {- const memoryArtifacts: MemoryArtifact[] = [- {- type: 'error',- key: 'system',- value: JSON.stringify({ errorType: 'would_exceed', tokenCount: 50 }),- },- ];-- render(<MemoryInfo memoryArtifacts={memoryArtifacts} />);-- const errorMessage = screen.getByText(- 'Cannot save - would exceed limit by 50 tokens. Delete existing memories to make space.',- );- const errorContainer = errorMessage.closest('[role="alert"]');-- expect(errorContainer).toHaveClass('bg-status-error-subtle');- expect(errorContainer).toHaveClass('text-status-error');- expect(errorContainer).toHaveClass('border-status-error-border');- expect(errorContainer).toHaveClass('p-3');- });});describe('Mixed Memory Types', () => {@@ -137,9 +113,9 @@ describe('MemoryInfo', () => {render(<MemoryInfo memoryArtifacts={memoryArtifacts} />);- // Check all sections are present- expect(screen.getByText('Updated Memories')).toBeInTheDocument();- expect(screen.getByText('Deleted Memories')).toBeInTheDocument();+ // Entries render without section headings; only the error section keeps one+ expect(screen.queryByText('Updated Memories')).not.toBeInTheDocument();+ expect(screen.queryByText('Deleted Memories')).not.toBeInTheDocument();expect(screen.getByText('Memory Storage Full')).toBeInTheDocument();// Check content@@ -241,7 +217,7 @@ describe('MemoryInfo', () => {render(<MemoryInfo memoryArtifacts={memoryArtifacts} />);- expect(screen.getByText('Updated Memories')).toBeInTheDocument();+ expect(screen.queryByText('Updated Memories')).not.toBeInTheDocument();expect(screen.getByText('preferences')).toBeInTheDocument();expect(screen.getByText('User prefers dark mode')).toBeInTheDocument();expect(screen.getByText('location')).toBeInTheDocument();@@ -256,7 +232,7 @@ describe('MemoryInfo', () => {render(<MemoryInfo memoryArtifacts={memoryArtifacts} />);- expect(screen.getByText('Deleted Memories')).toBeInTheDocument();+ expect(screen.queryByText('Deleted Memories')).not.toBeInTheDocument();expect(screen.getByText('old_preference')).toBeInTheDocument();expect(screen.getByText('outdated_info')).toBeInTheDocument();});diff --git a/client/src/components/Chat/Messages/Content/__tests__/ProgressText.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ProgressText.test.tsxindex 3ef9fd2a5c..ecf0a50c1f 100644--- a/client/src/components/Chat/Messages/Content/__tests__/ProgressText.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/ProgressText.test.tsx@@ -1,5 +1,5 @@import React from 'react';-import { render, screen } from '@testing-library/react';+import { fireEvent, render, screen } from '@testing-library/react';import ProgressText from '../ProgressText';jest.mock('~/hooks', () => ({@@ -111,3 +111,35 @@ describe('ProgressText duration', () => {});});});++describe('ProgressText disclosure', () => {+ it('shows an expandable chevron only on hover or focus', () => {+ const onClick = jest.fn();+ renderProgressText({ hasInput: true, onClick });++ const button = screen.getByRole('button', { name: 'Completed foo' });+ const chevron = button.querySelector('svg');++ expect(button).toHaveClass('group/disclosure');+ expect(chevron).toHaveClass(+ 'opacity-0',+ 'group-hover/disclosure:opacity-100',+ 'group-focus-within/disclosure:opacity-100',+ );+ expect(chevron).toHaveClass('transition-transform');+ expect(chevron?.getAttribute('class')).not.toContain('transition-opacity');++ fireEvent.click(button);+ expect(onClick).toHaveBeenCalledTimes(1);+ });++ it('renders no chevron or disclosure state without expandable content', () => {+ renderProgressText({ hasInput: false });++ const button = screen.getByRole('button', { name: 'Completed foo' });++ expect(button).toBeDisabled();+ expect(button).not.toHaveAttribute('aria-expanded');+ expect(button.querySelector('svg')).toBeNull();+ });+});diff --git a/client/src/components/Chat/Messages/Content/__tests__/RetrievalCall.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/RetrievalCall.test.tsxindex 19b8c3296d..5f28b4322f 100644--- a/client/src/components/Chat/Messages/Content/__tests__/RetrievalCall.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/RetrievalCall.test.tsx@@ -73,6 +73,7 @@ jest.mock('../ToolOutput', () => ({jest.mock('~/utils', () => ({cn: (...classes: (string | boolean | undefined)[]) => classes.filter(Boolean).join(' '),+ sortPagesByRelevance: (pages: number[]) => pages,logger: { error: jest.fn(), debug: jest.fn() },}));@@ -168,6 +169,51 @@ describe('RetrievalCall - LGCY-02: Collapsible output panel', () => {expect(screen.queryByText('file results here')).not.toBeInTheDocument();});+ it('does not offer expansion when output has no renderable results', () => {+ renderRetrievalCall({+ output: 'Search completed without matches',+ initialProgress: 1,+ isSubmitting: false,+ });++ const progressText = screen.getByTestId('progress-text');+ expect(progressText).toHaveAttribute('data-has-input', 'false');++ fireEvent.click(progressText);+ expect(progressText).toHaveAttribute('data-expanded', 'false');+ });++ it('offers attachment results even when the tool has no text output', () => {+ renderRetrievalCall({+ initialProgress: 1,+ isSubmitting: false,+ attachments: [+ {+ type: 'file_search',+ toolCallId: 'call-1',+ file_search: {+ sources: [+ {+ fileId: 'file-123',+ fileName: 'notes.txt',+ relevance: 0.8,+ content: 'Attachment result content',+ pages: [],+ pageRelevance: {},+ },+ ],+ },+ },+ ] as unknown as TAttachment[],+ });++ const progressText = screen.getByTestId('progress-text');+ expect(progressText).toHaveAttribute('data-has-input', 'true');++ fireEvent.click(progressText);+ expect(screen.getByText('Attachment result content')).toBeInTheDocument();+ });+it('does not show panel when output contains error', () => {renderRetrievalCall({output: 'error processing tool',diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsxindex 967a66cfa4..ea68deae29 100644--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx@@ -2,6 +2,7 @@ import React from 'react';import { RecoilRoot } from 'recoil';import { Tools, Constants } from 'librechat-data-provider';import { render, screen, fireEvent } from '@testing-library/react';+import { ToolAuthWarningContext } from '../auth';import ToolCall from '../ToolCall';// Mock dependencies@@ -19,6 +20,7 @@ jest.mock('~/hooks', () => ({com_assistants_allow_sites_you_trust: 'Only allow sites you trust',com_ui_via_server: `via ${values?.[0]}`,com_ui_tool_failed: 'failed',+ com_ui_tool_name_set_memory: 'Save Memory',};return translations[key] || key;},@@ -101,6 +103,8 @@ jest.mock('~/utils', () => ({error: jest.fn(),},cn: (...classes: any[]) => classes.filter(Boolean).join(' '),+ getToolDisplayLabel: (name: string, localize: (key: string) => string) =>+ name === 'set_memory' ? localize('com_ui_tool_name_set_memory') : name,}));describe('ToolCall', () => {@@ -154,6 +158,21 @@ describe('ToolCall', () => {});});+ it('uses a friendly label for the set_memory tool', () => {+ renderWithRecoil(<ToolCall {...mockProps} name="set_memory" />);++ expect(screen.getByTestId('progress-text')).toHaveTextContent('Completed Save Memory');+ expect(screen.queryByText(/set_memory/)).not.toBeInTheDocument();+ });++ it('keeps expanded tool content close to its header', () => {+ renderWithRecoil(<ToolCall {...mockProps} />);++ fireEvent.click(screen.getByTestId('progress-text'));++ expect(screen.getByTestId('tool-call-info').parentElement).toHaveClass('mb-2', 'mt-0');+ });+describe('attachments prop passing', () => {it('should pass attachments to ToolCallInfo when provided', () => {const attachments = [@@ -432,6 +451,42 @@ describe('ToolCall', () => {describe('MCP OAuth detection', () => {const d = Constants.mcp_delimiter;+ it('shows the trust warning for an ungrouped authentication call', () => {+ renderWithRecoil(+ <ToolCall+ {...mockProps}+ initialProgress={0.5}+ isSubmitting={true}+ output=""+ auth="https://auth.example.com"+ />,+ );++ expect(+ screen.getByRole('button', { name: 'Sign in to auth.example.com' }),+ ).toBeInTheDocument();+ expect(screen.getByText('Only allow sites you trust')).toBeInTheDocument();+ });++ it('keeps the sign-in action while a group suppresses the repeated warning', () => {+ renderWithRecoil(+ <ToolAuthWarningContext.Provider value>+ <ToolCall+ {...mockProps}+ initialProgress={0.5}+ isSubmitting={true}+ output=""+ auth="https://auth.example.com"+ />+ </ToolAuthWarningContext.Provider>,+ );++ expect(+ screen.getByRole('button', { name: 'Sign in to auth.example.com' }),+ ).toBeInTheDocument();+ expect(screen.queryByText('Only allow sites you trust')).not.toBeInTheDocument();+ });+it('should detect MCP OAuth from delimiter in tool-call name', () => {renderWithRecoil(<ToolCalldiff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsxindex 147988a6b2..04a5ae9180 100644--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx@@ -5,11 +5,50 @@ import { fireEvent, render, screen, waitFor } from '@testing-library/react';import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';import { scheduleMessageContentLayoutReconcile } from '~/hooks';import ToolCallGroup from '../ToolCallGroup';+import { ToolAuthWarning } from '../auth';++const mockMCPServerNames: string[] = [];jest.mock('~/hooks', () => ({useLocalize: () => (key: string, values?: Record<string | number, string>) => {- if (key === 'com_ui_used_n_tools') {- return `Used ${values?.[0]} tools`;+ if (key === 'com_ui_ran_n_actions') {+ return `Ran ${values?.[0]} actions`;+ }+ if (key === 'com_ui_running_n_actions') {+ return `Running ${values?.[0]} actions`;+ }+ if (key === 'com_ui_n_searches') {+ return `${values?.[0]} searches`;+ }+ if (key === 'com_ui_n_actions_failed') {+ return `${values?.[0]} failed`;+ }+ if (key === 'com_ui_one_action_failed') {+ return '1 failed';+ }+ if (key === 'com_ui_n_actions_cancelled') {+ return `${values?.[0]} cancelled`;+ }+ if (key === 'com_ui_one_action_cancelled') {+ return '1 cancelled';+ }+ if (key === 'com_ui_web_searched') {+ return 'Searched the web';+ }+ if (key === 'com_ui_web_searching') {+ return 'Searching the web';+ }+ if (key === 'com_ui_retrieved_files') {+ return 'Searched your files';+ }+ if (key === 'com_ui_searching_files') {+ return 'Searching your files';+ }+ if (key === 'com_ui_searched_web_and_files') {+ return 'Searched web and files';+ }+ if (key === 'com_ui_searching_web_and_files') {+ return 'Searching web and files';}if (key === 'com_ui_asked_n_questions') {return `Asked ${values?.[0]} questions`;@@ -17,9 +56,24 @@ jest.mock('~/hooks', () => ({if (key === 'com_ui_asking_n_questions') {return `Asking ${values?.[0]} questions`;}+ if (key === 'com_ui_asked_one_question') {+ return 'Asked 1 question';+ }+ if (key === 'com_ui_asking_one_question') {+ return 'Asking 1 question';+ }+ if (key === 'com_ui_subagent_complete') {+ return 'Ran agent';+ }+ if (key === 'com_ui_subagent_running') {+ return 'Running agent';+ }if (key === 'com_ui_via_server') {return `via ${values?.[0]}`;}+ if (key === 'com_assistants_allow_sites_you_trust') {+ return 'Only allow sites you trust';+ }return key;},useExpandCollapse: (isExpanded: boolean) => ({@@ -33,10 +87,9 @@ jest.mock('~/hooks', () => ({}));jest.mock('~/hooks/MCP', () => {- const mcpServerNames: string[] = [];return {useMCPIconMap: () => new Map(),- useMCPServerNames: () => mcpServerNames,+ useMCPServerNames: () => mockMCPServerNames,};});@@ -45,12 +98,18 @@ jest.mock('../ToolOutput', () => ({<span data-testid="stacked-icons" data-tool-names={toolNames.join(',')} />),getMCPServerName: () => '',+ isError: (output: string) => output.startsWith('Error processing tool'),}));jest.mock('lucide-react', () => ({- ChevronDown: () => <span>{'chevron'}</span>,+ ChevronDown: ({ className }: { className?: string }) => (+ <span data-testid="group-chevron" className={className}>+ {'chevron'}+ </span>+ ),Users: () => <span>{'users'}</span>,MessageCircleQuestion: () => <span data-testid="question-icon">{'question'}</span>,+ TriangleAlert: () => <span>{'warning'}</span>,}));jest.mock('~/utils/approval', () => ({@@ -59,10 +118,29 @@ jest.mock('~/utils/approval', () => ({jest.mock('~/utils', () => ({cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),- getToolDisplayLabel: (name: string) =>- ['execute_code', 'bash_tool', 'run_tools_with_code', 'run_tools_with_bash'].includes(name)- ? 'Code'- : name,+ getToolDisplayLabel: (name: string, _localize: unknown, knownServerNames?: readonly string[]) => {+ const configuredServer = knownServerNames?.find((server) => name.endsWith(`_mcp_${server}`));+ if (configuredServer) {+ return configuredServer;+ }+ if (name.includes('_mcp_')) {+ return name.slice(name.lastIndexOf('_mcp_') + '_mcp_'.length);+ }+ if (+ ['execute_code', 'bash_tool', 'run_tools_with_code', 'run_tools_with_bash'].includes(name)+ ) {+ return 'Code';+ }+ const friendlyNames: Record<string, string> = {+ web_search: 'Web Search',+ file_search: 'File Search',+ retrieval: 'File Search',+ create_file: 'Create File',+ edit_file: 'Edit File',+ ask_user_question: 'Question',+ };+ return friendlyNames[name] ?? name;+ },/** Real implementations: the group header resolves its text through these,* so stubbing them out would hide the header logic under test. */getBatchActivityLabelPart: jest.requireActual('~/utils/activityLabels').getBatchActivityLabelPart,@@ -74,6 +152,9 @@ jest.mock('../Parts', () => ({AttachmentGroup: ({ attachments }: { attachments?: TAttachment[] }) => (<div data-testid="attachment-group" data-count={attachments?.length ?? 0} />),+ ReasoningCompact: ({ isAfterTool }: { isAfterTool?: boolean }) => (+ <div data-testid="compact-reasoning" data-after-tool={String(isAfterTool)} />+ ),}));const makePart = (@@ -122,6 +203,24 @@ const makeSubagentPart = (},}) as unknown as TMessageContentParts;+const makeAuthPart = (+ id: string,+ name: string,+ progress = 0.1,+ output = '',+): TMessageContentParts =>+ ({+ type: ContentTypes.TOOL_CALL,+ [ContentTypes.TOOL_CALL]: {+ id,+ name,+ args: '{}',+ output,+ progress,+ auth: `https://${name}.example.com/oauth`,+ },+ }) as unknown as TMessageContentParts;+const imageAttachment: TAttachment = {filename: 'foo.png',filepath: '/files/foo.png',@@ -160,6 +259,7 @@ describe('ToolCallGroup image hoisting', () => {parts,isSubmitting: false,isLast: false,+ showThinking: false,lastContentIdx: 1,renderPart: (_p: TMessageContentParts, idx: number) => (<div data-testid={`inner-${idx}`} key={idx}>@@ -170,6 +270,7 @@ describe('ToolCallGroup image hoisting', () => {beforeEach(() => {mockScheduleMessageContentLayoutReconcile.mockClear();+ mockMCPServerNames.length = 0;});it('renders an AttachmentGroup outside the collapsible container with all attachments', () => {@@ -199,6 +300,51 @@ describe('ToolCallGroup image hoisting', () => {expect(screen.queryByTestId('attachment-group')).not.toBeInTheDocument();});+ it('renders one shared trust warning for multiple pending authentication calls', () => {+ const authParts = ['zapier', 'test', 'vercel', 'spotify'].map((name, idx) => ({+ part: makeAuthPart(`auth-${idx}`, name),+ idx,+ }));++ renderGroup({+ ...baseProps,+ parts: authParts,+ isSubmitting: true,+ lastContentIdx: authParts.length - 1,+ renderPart: (_part, idx) => <ToolAuthWarning key={idx} />,+ });++ expect(screen.getAllByText('Only allow sites you trust')).toHaveLength(1);+ });++ it('keeps the trust warning for a persisted incomplete authentication call', () => {+ renderGroup({+ ...baseProps,+ parts: [{ part: makeAuthPart('auth-persisted', 'zapier'), idx: 0 }],+ lastContentIdx: 0,+ renderPart: () => <ToolAuthWarning key="auth-persisted" />,+ });++ expect(screen.getByText('Only allow sites you trust')).toBeInTheDocument();+ });++ it('does not render a shared trust warning for completed authentication calls', () => {+ renderGroup({+ ...baseProps,+ parts: [{ part: makeAuthPart('auth-complete', 'zapier', 1, 'done'), idx: 0 }],+ lastContentIdx: 0,+ renderPart: () => null,+ });++ expect(screen.queryByText('Only allow sites you trust')).not.toBeInTheDocument();+ });++ it('keeps the group disclosure chevron visible', () => {+ renderGroup(baseProps);++ expect(screen.getByTestId('group-chevron')).not.toHaveClass('opacity-0');+ });+it('does not reconcile layout for an initially collapsed completed group', () => {renderGroup(baseProps);expect(mockScheduleMessageContentLayoutReconcile).not.toHaveBeenCalled();@@ -295,10 +441,7 @@ describe('ToolCallGroup image hoisting', () => {withinActivityPhase: true,});- expect(screen.getByRole('button', { name: 'Used 2 tools' })).toHaveAttribute(- 'aria-expanded',- 'true',- );+ expect(screen.getByRole('button')).toHaveAttribute('aria-expanded', 'true');expect(screen.getByTestId('inner-0')).toBeInTheDocument();expect(screen.getByTestId('inner-1')).toBeInTheDocument();});@@ -306,7 +449,7 @@ describe('ToolCallGroup image hoisting', () => {it('still expands on user toggle inside a completed phase', () => {renderGroup({ ...baseProps, withinActivityPhase: true });- fireEvent.click(screen.getByRole('button', { name: 'Used 2 tools' }));+ fireEvent.click(screen.getByRole('button'));expect(screen.getByTestId('inner-0')).toBeInTheDocument();expect(screen.getByTestId('inner-1')).toBeInTheDocument();@@ -330,7 +473,7 @@ describe('ToolCallGroup image hoisting', () => {renderPart,});- expect(screen.getByRole('button', { name: 'Used 59 tools' })).toBeInTheDocument();+ expect(screen.getByRole('button', { name: /^Ran 59 actions/ })).toBeInTheDocument();expect(renderPart).not.toHaveBeenCalled();expect(screen.queryByTestId('inner-0')).not.toBeInTheDocument();});@@ -338,16 +481,59 @@ describe('ToolCallGroup image hoisting', () => {it('mounts tool bodies when a collapsed group is expanded', () => {renderGroup(baseProps);- fireEvent.click(screen.getByRole('button', { name: 'Used 2 tools' }));+ fireEvent.click(screen.getByRole('button', { name: /^Ran 2 actions/ }));expect(screen.getByTestId('inner-0')).toBeInTheDocument();expect(screen.getByTestId('inner-1')).toBeInTheDocument();});+ it('removes the extra Thoughts top margin after a tool row', () => {+ const reasoningPart = {+ type: ContentTypes.THINK,+ [ContentTypes.THINK]: 'A useful thought',+ } as TMessageContentParts;++ renderGroup({+ ...baseProps,+ parts: [+ { part: makePart('t1'), idx: 0 },+ { part: reasoningPart, idx: 1 },+ ],+ });++ fireEvent.click(screen.getByRole('button', { name: /^Fetch_image/ }));++ expect(screen.getByTestId('compact-reasoning')).toHaveAttribute('data-after-tool', 'true');+ });++ it('delegates an unavailable-reasoning part to the standalone renderer', () => {+ /** A detached-subagent projection has no text to compact, so `Part`'s+ * `ReasoningMarker` is the only thing that stands for it. Rendering it+ * as a compact row drops the marker the moment the call joins a group. */+ const unavailablePart = {+ type: ContentTypes.THINK,+ [ContentTypes.THINK]: '',+ reasoning_unavailable: true,+ } as TMessageContentParts;++ renderGroup({+ ...baseProps,+ parts: [+ { part: makePart('t1'), idx: 0 },+ { part: unavailablePart, idx: 1 },+ ],+ });++ fireEvent.click(screen.getByRole('button', { name: /^Fetch_image/ }));++ expect(screen.getByTestId('inner-1')).toBeInTheDocument();+ expect(screen.queryByTestId('compact-reasoning')).not.toBeInTheDocument();+ });+it('unmounts tool bodies after a collapsed group finishes transitioning', () => {renderGroup(baseProps);- const button = screen.getByRole('button', { name: 'Used 2 tools' });+ const button = screen.getByRole('button', { name: /^Ran 2 actions/ });const collapsible = button.nextElementSibling as HTMLElement;fireEvent.click(button);fireEvent.click(button);@@ -373,7 +559,7 @@ describe('ToolCallGroup image hoisting', () => {),});- const button = screen.getByRole('button', { name: 'Used 2 tools' });+ const button = screen.getByRole('button', { name: /^Ran 2 actions/ });const collapsible = button.nextElementSibling as HTMLElement;expect(screen.getByTestId('approval-0')).toBeInTheDocument();@@ -405,7 +591,7 @@ describe('ToolCallGroup image hoisting', () => {),});- const button = screen.getByRole('button', { name: 'Used 2 tools' });+ const button = screen.getByRole('button', { name: /^Ran 2 actions/ });const collapsible = button.nextElementSibling as HTMLElement;fireEvent.click(button);fireEvent.transitionEnd(collapsible);@@ -435,7 +621,7 @@ describe('ToolCallGroup image hoisting', () => {),});- const button = screen.getByRole('button', { name: 'Used 2 tools' });+ const button = screen.getByRole('button', { name: /^Ran 2 actions/ });const collapsible = button.nextElementSibling as HTMLElement;fireEvent.click(button);fireEvent.transitionEnd(collapsible);@@ -463,7 +649,7 @@ describe('ToolCallGroup image hoisting', () => {});const { rerender } = renderGroup(propsFor());- const button = screen.getByRole('button', { name: 'Used 2 tools' });+ const button = screen.getByRole('button', { name: /^Ran 2 actions/ });const collapsible = button.nextElementSibling as HTMLElement;fireEvent.click(button);fireEvent.transitionEnd(collapsible);@@ -504,7 +690,7 @@ describe('ToolCallGroup image hoisting', () => {});const { rerender } = renderGroup(propsFor());- const button = screen.getByRole('button', { name: 'Used 2 tools' });+ const button = screen.getByRole('button', { name: /^Ran 2 actions/ });const collapsible = button.nextElementSibling as HTMLElement;fireEvent.click(button);@@ -524,10 +710,10 @@ describe('ToolCallGroup image hoisting', () => {it('reconciles layout after the group collapses from an expanded state', async () => {renderGroup(baseProps);- fireEvent.click(screen.getByRole('button', { name: 'Used 2 tools' }));+ fireEvent.click(screen.getByRole('button', { name: /^Ran 2 actions/ }));expect(mockScheduleMessageContentLayoutReconcile).not.toHaveBeenCalled();- fireEvent.click(screen.getByRole('button', { name: 'Used 2 tools' }));+ fireEvent.click(screen.getByRole('button', { name: /^Ran 2 actions/ }));await waitFor(() => {expect(mockScheduleMessageContentLayoutReconcile).toHaveBeenCalledTimes(1);@@ -567,7 +753,7 @@ describe('ToolCallGroup image hoisting', () => {],});- expect(screen.getByText('· Code')).toBeInTheDocument();+ expect(screen.getByText('· Code ×2')).toBeInTheDocument();expect(screen.queryByText(/Code, bash_tool/)).not.toBeInTheDocument();expect(screen.getByTestId('stacked-icons')).toHaveAttribute('data-tool-names',@@ -575,6 +761,201 @@ describe('ToolCallGroup image hoisting', () => {);});+ it('preserves a configured MCP server boundary in a single-tool label', () => {+ mockMCPServerNames.push('Google_mcp_Workspace');+ renderGroup({+ ...baseProps,+ parts: [+ {+ part: makePart('mcp-1', 'result', 'search_documents_mcp_Google_mcp_Workspace'),+ idx: 0,+ },+ ],+ lastContentIdx: 0,+ });++ expect(screen.getByRole('button', { name: /^Google_mcp_Workspace$/ })).toBeInTheDocument();+ });++ it('summarizes repeated completed web searches as an outcome and count', () => {+ const searchParts = Array.from({ length: 9 }, (_, idx) => ({+ part: makePart(`w${idx}`, 'result', 'web_search'),+ idx,+ }));++ renderGroup({+ ...baseProps,+ parts: searchParts,+ lastContentIdx: searchParts.length - 1,+ });++ expect(+ screen.getByRole('button', { name: 'Searched the web, 9 searches' }),+ ).toBeInTheDocument();+ expect(screen.getByText('Searched the web')).toBeInTheDocument();+ expect(screen.getByText('· 9 searches')).toBeInTheDocument();+ });++ it('uses the active tense while a web-search group is running', () => {+ renderGroup({+ ...baseProps,+ isSubmitting: true,+ parts: [+ { part: makePart('w1', 'result', 'web_search'), idx: 0 },+ { part: makePart('w2', '', 'web_search'), idx: 1 },+ ],+ });++ expect(+ screen.getByRole('button', { name: 'Searching the web, 2 searches' }),+ ).toBeInTheDocument();+ });++ it('summarizes mixed web and file searches without exposing tool ids', () => {+ renderGroup({+ ...baseProps,+ parts: [+ { part: makePart('w1', 'result', 'web_search'), idx: 0 },+ { part: makePart('f1', 'result', 'file_search'), idx: 1 },+ { part: makePart('f2', 'result', 'retrieval'), idx: 2 },+ ],+ lastContentIdx: 2,+ });++ expect(+ screen.getByRole('button', { name: 'Searched web and files, 3 searches' }),+ ).toBeInTheDocument();+ expect(screen.queryByText(/web_search|file_search|retrieval/)).not.toBeInTheDocument();+ });++ it('keeps repeated action counts and failed-call status in the compact summary', () => {+ renderGroup({+ ...baseProps,+ parts: [+ { part: makePart('c1', 'created', 'create_file'), idx: 0 },+ {+ part: makePart('c2', 'Error processing tool: disk full', 'create_file'),+ idx: 1,+ },+ { part: makePart('e1', 'edited', 'edit_file'), idx: 2 },+ ],+ lastContentIdx: 2,+ });++ expect(+ screen.getByRole('button', {+ name: 'Ran 3 actions, Create File ×2, Edit File · 1 failed',+ }),+ ).toBeInTheDocument();+ });++ it('counts background failures per step when provider call IDs repeat', () => {+ const executions = [+ { stepId: 'step-success', status: 'completed' },+ { stepId: 'step-failure', status: 'error' },+ ];+ const groupAttachments = executions.map(({ stepId, status }) => ({+ type: 'background_task_status',+ messageId: 'message-1',+ toolCallId: 'call_0',+ agentId: 'agent-a',+ stepId,+ status,+ })) as unknown as TAttachment[];+ const props = {+ ...baseProps,+ groupAttachments,+ parts: executions.map(({ stepId }, idx) => ({+ idx,+ part: {+ type: ContentTypes.TOOL_CALL,+ [ContentTypes.TOOL_CALL]: {+ id: 'call_0',+ name: 'execute_code',+ args: '{}',+ agentId: 'agent-a',+ stepId,+ runStepStatus: 'completed',+ output: JSON.stringify({+ background_task_id: stepId,+ tool: 'execute_code',+ status: 'running',+ message: 'Use check_background_task to poll.',+ }),+ },+ } as unknown as TMessageContentParts,+ })),+ };+ const { rerender } = renderGroup(props);+ expect(screen.getByRole('button', { name: /· 1 failed$/ })).toBeInTheDocument();++ rerender(+ <RecoilRoot>+ <ToolCallGroup {...props} groupAttachments={[...groupAttachments].reverse()} />+ </RecoilRoot>,+ );+ expect(screen.getByRole('button', { name: /· 1 failed$/ })).toBeInTheDocument();+ });++ it('honors a terminal failed run step whose output reads as benign', () => {+ const closedFailure = {+ type: ContentTypes.TOOL_CALL,+ [ContentTypes.TOOL_CALL]: {+ id: 'c2',+ name: 'create_file',+ args: '{}',+ output: '',+ runStepStatus: 'failed',+ },+ } as unknown as TMessageContentParts;++ renderGroup({+ ...baseProps,+ isSubmitting: true,+ parts: [+ { part: makePart('c1', 'created', 'create_file'), idx: 0 },+ { part: closedFailure, idx: 1 },+ ],+ lastContentIdx: 1,+ });++ /** The run closed this step as failed, so the group must read it as+ * settled (past tense while still submitting) and count it as a+ * failure even though the empty output never parses as an error. */+ expect(+ screen.getByRole('button', { name: 'Ran 2 actions, Create File ×2 · 1 failed' }),+ ).toBeInTheDocument();+ });++ it('names a cancelled action in the header before collapsing', () => {+ const cancelled = {+ type: ContentTypes.TOOL_CALL,+ [ContentTypes.TOOL_CALL]: {+ id: 'c2',+ name: 'create_file',+ args: '{}',+ output: '',+ runStepStatus: 'cancelled',+ },+ } as unknown as TMessageContentParts;++ renderGroup({+ ...baseProps,+ parts: [+ { part: makePart('c1', 'created', 'create_file'), idx: 0 },+ { part: cancelled, idx: 1 },+ ],+ lastContentIdx: 1,+ });++ /** A stopped action is settled but not successful, and the group collapses+ * over the only other notice, so the header must carry it and must not+ * count it as a failure. */+ expect(+ screen.getByRole('button', { name: 'Ran 2 actions, Create File ×2 · 1 cancelled' }),+ ).toBeInTheDocument();+ });+it('labels a homogeneous ask_user_question group as its own category', () => {renderGroup({...baseProps,@@ -587,7 +968,7 @@ describe('ToolCallGroup image hoisting', () => {// Own verb, not "Used N tools"; question glyph instead of stacked wrenches;// raw-name summary suppressed (like subagent groups).expect(screen.getByRole('button', { name: 'Asked 2 questions' })).toBeInTheDocument();- expect(screen.queryByText('Used 2 tools')).not.toBeInTheDocument();+ expect(screen.queryByText('Ran 2 actions')).not.toBeInTheDocument();expect(screen.getByTestId('question-icon')).toBeInTheDocument();expect(screen.queryByTestId('stacked-icons')).not.toBeInTheDocument();expect(screen.queryByText(/· ask_user_question/)).not.toBeInTheDocument();@@ -607,7 +988,49 @@ describe('ToolCallGroup image hoisting', () => {expect(screen.getByRole('button', { name: 'Asking 2 questions' })).toBeInTheDocument();});- it('keeps the generic "Used N tools" label for a mixed group containing a question', () => {+ it('uses a singular completed label for one question grouped with reasoning', () => {+ renderGroup({+ ...baseProps,+ parts: [{ part: makePart('q1', 'blue', 'ask_user_question'), idx: 0 }],+ lastContentIdx: 0,+ });++ expect(screen.getByRole('button', { name: 'Asked 1 question' })).toBeInTheDocument();+ });++ it('uses a singular active label for one question grouped with reasoning', () => {+ renderGroup({+ ...baseProps,+ isSubmitting: true,+ parts: [{ part: makePart('q1', '', 'ask_user_question'), idx: 0 }],+ lastContentIdx: 0,+ });++ expect(screen.getByRole('button', { name: 'Asking 1 question' })).toBeInTheDocument();+ });++ it('uses a singular completed label for one subagent grouped with reasoning', () => {+ renderGroup({+ ...baseProps,+ parts: [{ part: makePart('a1', 'done', Constants.SUBAGENT), idx: 0 }],+ lastContentIdx: 0,+ });++ expect(screen.getByRole('button', { name: 'Ran agent' })).toBeInTheDocument();+ });++ it('uses a singular active label for one subagent grouped with reasoning', () => {+ renderGroup({+ ...baseProps,+ isSubmitting: true,+ parts: [{ part: makePart('a1', '', Constants.SUBAGENT), idx: 0 }],+ lastContentIdx: 0,+ });++ expect(screen.getByRole('button', { name: 'Running agent' })).toBeInTheDocument();+ });++ it('uses an action summary for a mixed group containing a question', () => {renderGroup({...baseProps,parts: [@@ -616,7 +1039,9 @@ describe('ToolCallGroup image hoisting', () => {],});- expect(screen.getByRole('button', { name: 'Used 2 tools' })).toBeInTheDocument();+ expect(+ screen.getByRole('button', { name: 'Ran 2 actions, Web Search, Question' }),+ ).toBeInTheDocument();expect(screen.getByTestId('stacked-icons')).toBeInTheDocument();});});diff --git a/client/src/components/Chat/Messages/Content/__tests__/WebSearch.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/WebSearch.test.tsxindex a0fef95cc4..33b2b9ebc8 100644--- a/client/src/components/Chat/Messages/Content/__tests__/WebSearch.test.tsx+++ b/client/src/components/Chat/Messages/Content/__tests__/WebSearch.test.tsx@@ -4,6 +4,7 @@ import { Tools } from 'librechat-data-provider';import { fireEvent, render, screen } from '@testing-library/react';import type { TAttachment, SearchResultData, ValidSource } from 'librechat-data-provider';import { SearchContext } from '~/Providers';+import { ROW_GLYPH_SLOT } from '../rows';import WebSearch from '../WebSearch';jest.mock('~/hooks', () => ({@@ -16,6 +17,8 @@ jest.mock('~/hooks', () => ({com_ui_web_searched: 'Searched the web',com_ui_web_search_source: `${values?.count ?? 1} source`,com_ui_web_search_sources: `${values?.count ?? 0} sources`,+ com_ui_web_search_details: 'Search details',+ com_ui_search_query: 'Query',};return translations[key] || key;},@@ -56,7 +59,12 @@ jest.mock('~/components/Web/Sources', () => ({jest.mock('lucide-react', () => ({Globe: () => <span data-testid="globe-icon" />,- ChevronDown: () => <span data-testid="chevron-icon" />,+ Info: () => <span data-testid="info-icon" />,+ Star: () => <span data-testid="star-icon" />,+ MapPin: () => <span data-testid="map-pin-icon" />,+ ChevronDown: ({ className }: { className?: string }) => (+ <span data-testid="chevron-icon" className={className} />+ ),}));function makeSource(link: string, title: string): ValidSource {@@ -86,6 +94,7 @@ function renderWebSearch({isSubmitting = false,isLast = false,initialProgress = 1,+ args,output,}: {searchResults?: Record<string, SearchResultData>;@@ -93,6 +102,7 @@ function renderWebSearch({isSubmitting?: boolean;isLast?: boolean;initialProgress?: number;+ args?: string | Record<string, unknown>;output?: string | null;}) {return render(@@ -102,6 +112,7 @@ function renderWebSearch({initialProgress={initialProgress}isSubmitting={isSubmitting}isLast={isLast}+ args={args}output={output}attachments={attachments}/>@@ -210,6 +221,15 @@ describe('WebSearch', () => {expect(hrefs).toContain('https://pi.example.com/2');expect(hrefs).not.toContain('https://neutrino.example.com/1');});++ it('does not fall back to another execution when filtered attachments are empty', () => {+ renderWebSearch({+ searchResults,+ attachments: [],+ });++ expect(screen.getByRole('button', { name: 'Searched the web' })).toBeDisabled();+ });});describe('streaming favicons', () => {@@ -289,6 +309,179 @@ describe('WebSearch', () => {expect(matches.length).toBeGreaterThanOrEqual(1);});+ it('renders snippets and dates in the source list', () => {+ const attachment = {+ type: Tools.web_search,+ [Tools.web_search]: {+ turn: 0,+ organic: [+ {+ link: 'https://example.com/context',+ title: 'Context windows explained',+ snippet: 'How context windows change what assistants can do.',+ date: 'Jun 12, 2026',+ },+ ],+ },+ } as unknown as TAttachment;++ renderWebSearch({ attachments: [attachment] });+ fireEvent.click(screen.getByRole('button', { name: /Searched the web/ }));++ expect(+ screen.getByText('How context windows change what assistants can do.'),+ ).toBeInTheDocument();+ expect(screen.getByText('Jun 12, 2026')).toBeInTheDocument();+ expect(screen.getByText('example.com')).toBeInTheDocument();+ });++ it('tucks the query and answer box behind the details hover card', async () => {+ const attachment = {+ type: Tools.web_search,+ [Tools.web_search]: {+ turn: 0,+ organic: [{ link: 'https://example.com/context', title: 'Context windows explained' }],+ answerBox: {+ title: 'What is a context window?',+ snippet: 'The amount of text a model can consider at once.',+ },+ },+ } as unknown as TAttachment;++ renderWebSearch({+ attachments: [attachment],+ args: { query: 'largest context window LLM 2026' },+ });++ expect(screen.queryByText('What is a context window?')).not.toBeInTheDocument();++ const trigger = screen.getByLabelText('Search details');+ fireEvent.focus(trigger);++ expect(await screen.findByText('What is a context window?')).toBeInTheDocument();+ expect(+ screen.getByText('The amount of text a model can consider at once.'),+ ).toBeInTheDocument();+ expect(screen.getByText('largest context window LLM 2026')).toBeInTheDocument();+ expect(screen.getByText('1 source')).toBeInTheDocument();+ });++ it('renders shopping, image, and place verticals in the expanded panel', () => {+ const attachment = {+ type: Tools.web_search,+ [Tools.web_search]: {+ turn: 0,+ organic: [{ link: 'https://example.com/a', title: 'A source' }],+ images: [+ {+ title: 'Rain vortex',+ imageUrl: 'https://img.example.com/full.jpg',+ thumbnailUrl: 'https://img.example.com/thumb.jpg',+ thumbnailWidth: 300,+ thumbnailHeight: 200,+ link: 'https://host.example.com/page',+ },+ ],+ shopping: [+ {+ title: 'Gingko Mini Smart Book',+ link: 'https://shop.example.com/book',+ price: '35,70 \u20ac',+ source: 'Amazon',+ rating: 4.7,+ ratingCount: 1284,+ delivery: 'Free delivery',+ },+ ],+ places: [+ {+ name: 'Blue Bottle Coffee',+ category: 'Coffee shop',+ address: '300 S Broadway',+ rating: 4.6,+ ratingCount: 812,+ },+ ],+ },+ } as unknown as TAttachment;++ renderWebSearch({ attachments: [attachment] });++ const imageLink = screen.getByLabelText('Rain vortex');+ expect(imageLink).toHaveAttribute('href', 'https://host.example.com/page');+ expect(imageLink.querySelector('img')).toHaveAttribute(+ 'src',+ 'https://img.example.com/thumb.jpg',+ );++ const product = screen.getByText('Gingko Mini Smart Book').closest('a');+ expect(product).toHaveAttribute('href', 'https://shop.example.com/book');+ expect(screen.getByText('35,70 \u20ac \u00b7 Amazon')).toBeInTheDocument();+ expect(screen.getByText('Free delivery')).toBeInTheDocument();+ expect(screen.getByText('4.7')).toBeInTheDocument();++ expect(screen.getByText('Blue Bottle Coffee')).toBeInTheDocument();+ const placeLink = screen.getByText('Blue Bottle Coffee').closest('a');+ expect(placeLink?.getAttribute('href')).toContain('google.com/maps');+ expect(placeLink?.getAttribute('href')).toContain(+ encodeURIComponent('Blue Bottle Coffee, 300 S Broadway'),+ );+ expect(screen.getByText('Coffee shop \u00b7 300 S Broadway')).toBeInTheDocument();+ expect(screen.getByText('4.6')).toBeInTheDocument();+ expect(screen.getByText('(812)')).toBeInTheDocument();+ });++ it('uses standard tool-row spacing and reveals its chevron on hover or focus', () => {+ const searchResults = makeSearchResults({+ 0: { organic: [makeSource('https://example.com', 'Example')] },+ });++ renderWebSearch({ searchResults });++ const button = screen.getByRole('button', { name: /Searched the web/ });+ expect(button.parentElement).toHaveClass('h-5');+ expect(button.parentElement?.parentElement).toHaveClass('my-1');+ expect(button).not.toHaveClass('py-1');+ expect(button).not.toHaveClass('transition-colors');+ const chevron = screen.getByTestId('chevron-icon');+ expect(chevron).toHaveClass(+ 'opacity-0',+ 'group-hover/disclosure:opacity-100',+ 'group-focus-within/disclosure:opacity-100',+ );+ expect(chevron).toHaveClass('transition-transform');+ expect(chevron.className).not.toContain('transition-opacity');+ });++ it('puts both rows glyph on the shared row rail', () => {+ /** `Part.tsx` routes web search past `ProgressText`, so this renderer+ * draws its own glyph and has to take the shared slot itself or its+ * favicon stack sits left of every other row under the header. */+ const searchResults = makeSearchResults({+ 0: { organic: [makeSource('https://example.com', 'Example')] },+ });++ const { unmount } = renderWebSearch({ searchResults });++ const completedRow = screen.getByRole('button', { name: /Searched the web/ });+ const completedSlot = completedRow.firstElementChild;+ expect(completedSlot).toContainElement(screen.getByTestId('favicon'));+ for (const token of ROW_GLYPH_SLOT.split(' ')) {+ expect(completedSlot).toHaveClass(token);+ }+ unmount();++ renderWebSearch({ isSubmitting: true, isLast: true, initialProgress: 0.5 });++ const streamingSlot = screen.getByTestId('globe-icon').parentElement;+ for (const token of ROW_GLYPH_SLOT.split(' ')) {+ expect(streamingSlot).toHaveClass(token);+ }+ /** 24px slot plus an 8px gap puts the label where the header's name+ * starts; 10px would leave the streaming row 2px off the rail. */+ expect(streamingSlot?.parentElement).toHaveClass('gap-2');+ });+it('renders searching state during streaming', () => {renderWebSearch({isSubmitting: true,diff --git a/client/src/components/Chat/Messages/Content/auth.tsx b/client/src/components/Chat/Messages/Content/auth.tsxnew file mode 100644index 0000000000..b2b03a7118--- /dev/null+++ b/client/src/components/Chat/Messages/Content/auth.tsx@@ -0,0 +1,22 @@+import { createContext, useContext } from 'react';+import { TriangleAlert } from 'lucide-react';+import { useLocalize } from '~/hooks';+import { cn } from '~/utils';++export const ToolAuthWarningContext = createContext(false);++export function ToolAuthWarning({ className }: { className?: string }) {+ const localize = useLocalize();+ const suppressed = useContext(ToolAuthWarningContext);++ if (suppressed) {+ return null;+ }++ return (+ <p className={cn('flex items-center text-xs text-text-warning', className)}>+ <TriangleAlert className="mr-1.5 inline-block h-4 w-4" aria-hidden="true" />+ {localize('com_assistants_allow_sites_you_trust')}+ </p>+ );+}diff --git a/client/src/components/Chat/Messages/Content/disclosure.ts b/client/src/components/Chat/Messages/Content/disclosure.tsnew file mode 100644index 0000000000..517a7ab4c0--- /dev/null+++ b/client/src/components/Chat/Messages/Content/disclosure.ts@@ -0,0 +1,3 @@+/** 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';diff --git a/client/src/components/Chat/Messages/Content/verticals.tsx b/client/src/components/Chat/Messages/Content/verticals.tsxnew file mode 100644index 0000000000..3887dc7391--- /dev/null+++ b/client/src/components/Chat/Messages/Content/verticals.tsx@@ -0,0 +1,259 @@+import { Star, MapPin } from 'lucide-react';+import { Tools } from 'librechat-data-provider';+import type {+ TAttachment,+ ImageResult,+ PlaceResult,+ ShoppingResult,+} from 'librechat-data-provider';+import { isMacPlatform } from '~/utils/shortcuts';+import { isSafeUrl } from '~/utils/markdown';+import { useLocalize } from '~/hooks';+import { cn } from '~/utils';++/**+ * Provider result payloads are copied into the attachment without URL+ * validation, so a result can carry a `javascript:` or other non-network+ * target. Anything a card turns into an `href` or an `img` src clears the same+ * allowlist the markdown renderer uses, both when admitting the result and+ * when rendering it, so the two can never disagree.+ */+const safeUrl = (value?: string): string | undefined =>+ value != null && isSafeUrl(value) ? value : undefined;++const imageSource = (image: ImageResult): string | undefined =>+ safeUrl(image.thumbnailUrl) ?? safeUrl(image.imageUrl);++const imageTarget = (image: ImageResult): string | undefined =>+ safeUrl(image.link) ?? safeUrl(image.googleUrl) ?? safeUrl(image.imageUrl);++const MAX_VERTICAL_ITEMS = 8;+const MAX_PLACES = 5;++/** Platform-native map link: Apple devices open Apple Maps, everything else+ * Google Maps. Both are keyless https links that fall back to a web map when+ * the native app is unavailable, so a misdetected platform still works. */+export function mapLink(place: PlaceResult): string {+ const query = [place.name, place.address].filter(Boolean).join(', ');+ const coords =+ place.latitude != null && place.longitude != null ? `${place.latitude},${place.longitude}` : '';+ if (isMacPlatform) {+ const params = new URLSearchParams();+ if (query) {+ params.set('q', query);+ }+ if (coords) {+ params.set('ll', coords);+ }+ return `https://maps.apple.com/?${params.toString()}`;+ }+ return `https://www.google.com/maps/search/?api=1&query=${encodeURIComponent(query || coords)}`;+}++export interface SearchVerticalData {+ images: ImageResult[];+ shopping: ShoppingResult[];+ places: PlaceResult[];+}++/** Serper vertical results (image/shopping/place) merged across a call's+ * `web_search` attachments. Attachment-only: verticals never stream. */+export function collectSearchVerticals(attachments?: TAttachment[]): SearchVerticalData {+ const images: ImageResult[] = [];+ const shopping: ShoppingResult[] = [];+ const places: PlaceResult[] = [];+ for (const att of attachments ?? []) {+ const data = att.type === Tools.web_search ? att[Tools.web_search] : undefined;+ if (!data) {+ continue;+ }+ /** Every field of these provider records is optional, and each strip+ * renders one as a link. An unusable entry still makes the array+ * nonempty, so the card shows a broken tile or an anchor with no+ * destination that looks actionable but cannot be opened. Drop them+ * here rather than teaching three strips to render half a result:+ * an image needs both a src and somewhere to go, a product needs+ * somewhere to go, and a place needs something to name. */+ for (const image of data.images ?? []) {+ if (imageSource(image) && imageTarget(image)) {+ images.push(image);+ }+ }+ for (const item of data.shopping ?? []) {+ /** A card with no title has no accessible name and no visible identity:+ * the anchor carries no label, the image is decorative, and the title+ * span renders empty. */+ if (safeUrl(item.link) && item.title) {+ shopping.push(item);+ }+ }+ for (const place of data.places ?? []) {+ if (place.name || place.address) {+ places.push(place);+ }+ }+ }+ return { images, shopping, places };+}++function RatingBadge({ rating, ratingCount }: { rating?: number; ratingCount?: number }) {+ if (rating == null) {+ return null;+ }+ return (+ <span className="flex items-center gap-1 text-[11px] text-text-secondary">+ <Star className="size-3 fill-current" aria-hidden="true" />+ {rating}+ {ratingCount != null && <span className="text-text-secondary">({ratingCount})</span>}+ </span>+ );+}++function ImageStrip({ images, label }: { images: ImageResult[]; label: string }) {+ return (+ <ul className="flex list-none gap-2 overflow-x-auto pb-1" aria-label={label}>+ {images.slice(0, MAX_VERTICAL_ITEMS).map((image, i) => {+ const href = imageTarget(image);+ const ratio =+ image.thumbnailWidth && image.thumbnailHeight+ ? `${image.thumbnailWidth} / ${image.thumbnailHeight}`+ : '1 / 1';+ return (+ /** Syndicated images reuse one thumbnail across results that link to+ * different pages, and grouped searches merge attachments, so the+ * source alone collides. The target plus the index is unique. */+ <li key={`${imageSource(image) ?? ''}|${href ?? ''}|${i}`} className="shrink-0">+ <a+ href={href}+ target="_blank"+ rel="noopener noreferrer"+ aria-label={image.title || image.domain || label}+ className="block h-28 overflow-hidden rounded-xl border border-border-light no-underline focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy"+ style={{ aspectRatio: ratio }}+ >+ <img+ src={imageSource(image)}+ alt={image.title || ''}+ className="h-full w-full object-cover"+ loading="lazy"+ />+ </a>+ </li>+ );+ })}+ </ul>+ );+}++function ShoppingStrip({ items, label }: { items: ShoppingResult[]; label: string }) {+ return (+ <ul className="flex list-none gap-2.5 overflow-x-auto pb-1" aria-label={label}>+ {items.slice(0, MAX_VERTICAL_ITEMS).map((item, i) => (+ <li+ key={`${item.productId ?? ''}|${safeUrl(item.link) ?? ''}|${i}`}+ className="flex w-40 shrink-0"+ >+ <a+ href={safeUrl(item.link)}+ target="_blank"+ rel="noopener noreferrer"+ className="flex w-full flex-col rounded-xl border border-border-light p-2 no-underline transition-colors hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy"+ >+ {safeUrl(item.imageUrl) && (+ <div className="mb-2 aspect-square w-full shrink-0 overflow-hidden rounded-lg bg-surface-tertiary">+ <img+ src={safeUrl(item.imageUrl)}+ alt=""+ className="h-full w-full object-cover"+ loading="lazy"+ />+ </div>+ )}+ <span className="mt-auto block truncate text-xs font-medium text-text-primary">+ {item.title}+ </span>+ {(item.price || item.source) && (+ <span className="mt-0.5 block truncate text-[11px] text-text-secondary">+ {[item.price, item.source].filter(Boolean).join(' · ')}+ </span>+ )}+ {item.delivery && (+ <span className="block truncate text-[11px] text-text-secondary">+ {item.delivery}+ </span>+ )}+ <span className="mt-0.5 block">+ <RatingBadge rating={item.rating} ratingCount={item.ratingCount} />+ </span>+ </a>+ </li>+ ))}+ </ul>+ );+}++function PlaceList({ places, label }: { places: PlaceResult[]; label: string }) {+ return (+ <ul+ className="list-none overflow-hidden rounded-lg border border-border-light"+ aria-label={label}+ >+ {places.slice(0, MAX_PLACES).map((place, i) => (+ <li+ /** The same provider place can appear in several grouped searches;+ * discriminate each occurrence even when its identifier is present. */+ key={`${place.identifier || `${place.name ?? ''}|${place.address ?? ''}`}|${i}`}+ className={cn(i > 0 && 'border-t border-border-light')}+ >+ <a+ href={mapLink(place)}+ target="_blank"+ rel="noopener noreferrer"+ className="flex items-center gap-2.5 px-3 py-2 no-underline transition-colors hover:bg-surface-hover focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-border-heavy"+ >+ <MapPin className="size-4 shrink-0 text-text-secondary" aria-hidden="true" />+ <span className="min-w-0 flex-1">+ <span className="block truncate text-xs font-medium text-text-primary">+ {place.name}+ </span>+ {(place.category || place.address) && (+ <span className="block truncate text-[11px] text-text-secondary">+ {[place.category, place.address].filter(Boolean).join(' · ')}+ </span>+ )}+ </span>+ <span className="shrink-0">+ <RatingBadge rating={place.rating} ratingCount={place.ratingCount} />+ </span>+ </a>+ </li>+ ))}+ </ul>+ );+}++/** Always-visible search verticals. Rendered under the web search row when+ * ungrouped, and hoisted below the group (like attachments) when the call+ * lives inside a collapsed tool group. */+export default function SearchVerticals({ attachments }: { attachments?: TAttachment[] }) {+ const localize = useLocalize();+ const { images, shopping, places } = collectSearchVerticals(attachments);++ if (images.length === 0 && shopping.length === 0 && places.length === 0) {+ return null;+ }++ return (+ <div className="my-1.5 space-y-2">+ {images.length > 0 && (+ <ImageStrip images={images} label={localize('com_ui_web_search_images')} />+ )}+ {shopping.length > 0 && (+ <ShoppingStrip items={shopping} label={localize('com_ui_web_search_shopping')} />+ )}+ {places.length > 0 && (+ <PlaceList places={places} label={localize('com_ui_web_search_places')} />+ )}+ </div>+ );+}diff --git a/client/src/components/Chat/Messages/MessageNav.tsx b/client/src/components/Chat/Messages/MessageNav.tsxindex 4cef105caa..d5dba9bdd1 100644--- a/client/src/components/Chat/Messages/MessageNav.tsx+++ b/client/src/components/Chat/Messages/MessageNav.tsx@@ -1709,7 +1709,7 @@ function MessageNav({ scrollableRef }: { scrollableRef: React.RefObject<HTMLDivEtransform: 'translateY(-50%)',zIndex: 999,}}- className="pointer-events-none max-w-[280px] rounded-md border border-border-medium bg-surface-secondary px-3 py-2 text-text-secondary shadow-lg"+ className="pointer-events-none max-w-[280px] rounded-xl border border-border-light bg-surface-secondary px-3 py-2 text-text-secondary shadow-lg"><p className="line-clamp-3 text-xs">{tipText}</p></div>,diff --git a/client/src/components/Chat/Messages/MessageParts.tsx b/client/src/components/Chat/Messages/MessageParts.tsxindex 60a4754e33..19aee8b90c 100644--- a/client/src/components/Chat/Messages/MessageParts.tsx+++ b/client/src/components/Chat/Messages/MessageParts.tsx@@ -1,4 +1,5 @@import React, { useMemo } from 'react';+import { useAtomValue } from 'jotai';import { useRecoilValue } from 'recoil';import type { TMessageContentParts } from 'librechat-data-provider';import type { TMessageProps, TMessageIcon } from '~/common';@@ -14,6 +15,7 @@ import { getHeaderModelName } from '~/components/Chat/Messages/ui/HeaderLabel';import { revealOnRowHoverClasses, messageFooterClasses } from './styles';import MessageRow from '~/components/Chat/Messages/ui/MessageRow';import MessageIcon from '~/components/Chat/Messages/MessageIcon';+import { showThinkingAtom } from '~/store/showThinking';import Elapsed, { shouldShowElapsed } from './Elapsed';import ContentParts from './Content/ContentParts';import SiblingSwitch from './SiblingSwitch';@@ -46,6 +48,7 @@ function MessageParts(props: TMessageProps) {} = useMessageHelpers(props, searchResults);const maximizeChatSpace = useRecoilValue(store.maximizeChatSpace);+ const showThinking = useAtomValue(showThinkingAtom);const { messageId = null, isCreatedByUser } = message ?? {};const name = useMemo(() => {@@ -173,6 +176,7 @@ function MessageParts(props: TMessageProps) {setSiblingIdx={setSiblingIdx}isCreatedByUser={message.isCreatedByUser}conversationId={conversation?.conversationId}+ showThinking={showThinking}isLatestMessage={messageId === latestMessageId}content={message.content as Array<TMessageContentParts | undefined>}/>diff --git a/client/src/components/Chat/Subagents/SubagentActivity.tsx b/client/src/components/Chat/Subagents/SubagentActivity.tsxindex f278bc1e9f..5811afacd7 100644--- a/client/src/components/Chat/Subagents/SubagentActivity.tsx+++ b/client/src/components/Chat/Subagents/SubagentActivity.tsx@@ -1,4 +1,5 @@import { useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';+import { useAtomValue } from 'jotai';import { Button } from '@librechat/client';import { ContentTypes } from 'librechat-data-provider';import { CSSTransition } from 'react-transition-group';@@ -17,6 +18,7 @@ import ContentParts from '~/components/Chat/Messages/Content/ContentParts';import Container from '~/components/Chat/Messages/Content/Container';import { EmptyText } from '~/components/Chat/Messages/Content/Parts';import ScrollToBottom from '~/components/Messages/ScrollToBottom';+import { showThinkingAtom } from '~/store/showThinking';import { useChatSurface } from './surface';import { useLocalize } from '~/hooks';import { cn } from '~/utils';@@ -322,6 +324,7 @@ export function SubagentActivityContent({onCancelControl?: (controlId: string) => void;}) {const localize = useLocalize();+ const showThinking = useAtomValue(showThinkingAtom);const isSubmitting = isLiveSubagentStatus(activity.status);const parts = useMemo(() => activity.items.map(toContentPart), [activity.items]);@@ -353,6 +356,7 @@ export function SubagentActivityContent({isCreatedByUser={false}isLastisSubmitting={isSubmitting}+ showThinking={showThinking}isLatestMessage={isSubmitting}/>);diff --git a/client/src/components/Chat/Subagents/SubagentConversation.tsx b/client/src/components/Chat/Subagents/SubagentConversation.tsxindex 3ddf673bf9..f39c6efe7b 100644--- a/client/src/components/Chat/Subagents/SubagentConversation.tsx+++ b/client/src/components/Chat/Subagents/SubagentConversation.tsx@@ -1,4 +1,5 @@import { useMemo, useState } from 'react';+import { useAtomValue } from 'jotai';import { ChevronDown, CornerDownRight, Radio } from 'lucide-react';import { ContentTypes, EModelEndpoint } from 'librechat-data-provider';import { Button, Collapsible, CollapsibleContent, CollapsibleTrigger } from '@librechat/client';@@ -13,6 +14,7 @@ import { messageFooterClasses } from '~/components/Chat/Messages/styles';import MessageRow from '~/components/Chat/Messages/ui/MessageRow';import { ElapsedTimer } from '~/components/Chat/Messages/Elapsed';import MessageIcon from '~/components/Chat/Messages/MessageIcon';+import { showThinkingAtom } from '~/store/showThinking';import { useAgentsMapContext } from '~/Providers';import { useChatSurface } from './surface';import { useLocalize } from '~/hooks';@@ -113,6 +115,7 @@ function ExternalEventTrigger({}function TriggerMessage({ turn, fullWidth }: { turn: ChildConversationTurn; fullWidth: boolean }) {+ const showThinking = useAtomValue(showThinkingAtom);const localize = useLocalize();const label = localize(TRIGGER_LABELS[turn.trigger.kind]);const content = useMemo<TMessageContentParts[]>(@@ -152,6 +155,7 @@ function TriggerMessage({ turn, fullWidth }: { turn: ChildConversationTurn; fullmessageId={`${turn.taskId}:trigger`}conversationId={null}isCreatedByUser={true}+ showThinking={showThinking}isLast={false}isSubmitting={false}isLatestMessage={false}diff --git a/client/src/components/Chat/ask/options.tsx b/client/src/components/Chat/ask/options.tsxnew file mode 100644index 0000000000..88301c58fd--- /dev/null+++ b/client/src/components/Chat/ask/options.tsx@@ -0,0 +1,80 @@+import { Check } from 'lucide-react';+import { Button } from '@librechat/client';+import { cn } from '~/utils';++export interface AskOption {+ label: string;+ value: string;+}++/**+ * The single option-row list shared by every `ask_user_question` surface+ * (composer popover and chat card), so the same question looks and behaves+ * identically wherever it renders. Numbered badges double as the popover's+ * digit shortcuts; multi-select swaps the number for a check.+ *+ * Hover, focus-visible and disabled appearance come from the shared `Button`+ * primitive rather than being recreated here, so these rows cannot drift from+ * it. Only the row geometry and the selected fill stay local, both on+ * semantic roles so a customized theme moves them too.+ */+export default function AskOptions({+ options,+ multiSelect,+ checked,+ selected,+ locked,+ onActivate,+ optionRefs,+ listRef,+ className,+}: {+ options: AskOption[];+ multiSelect: boolean;+ checked: number[];+ selected?: number | null;+ locked: boolean;+ onActivate: (index: number) => void;+ optionRefs?: React.MutableRefObject<(HTMLButtonElement | null)[]>;+ listRef?: React.RefObject<HTMLDivElement>;+ className?: string;+}) {+ return (+ <div ref={listRef} className={className}>+ {options.map((option, index) => {+ const isChecked = multiSelect && checked.includes(index);+ return (+ <Button+ key={option.value}+ ref={(el) => {+ if (optionRefs) {+ optionRefs.current[index] = el;+ }+ }}+ variant="ghost"+ role={multiSelect ? 'checkbox' : undefined}+ aria-checked={multiSelect ? isChecked : undefined}+ disabled={locked}+ className={cn(+ 'flex h-auto w-full justify-start gap-2.5 whitespace-normal px-2.5 py-2 text-left text-sm font-normal text-text-primary',+ selected === index && 'bg-surface-active hover:bg-surface-active',+ )}+ onClick={() => onActivate(index)}+ >+ <span+ className={cn(+ 'flex size-5 shrink-0 items-center justify-center rounded-md text-[11px] font-medium tabular-nums transition-colors',+ isChecked+ ? 'bg-surface-submit text-text-on-status'+ : 'bg-surface-tertiary text-text-secondary',+ )}+ >+ {isChecked ? <Check className="size-3.5" aria-hidden="true" /> : index + 1}+ </span>+ <span className="min-w-0 flex-1 [overflow-wrap:anywhere]">{option.label}</span>+ </Button>+ );+ })}+ </div>+ );+}diff --git a/client/src/components/Chat/ask/state.tsx b/client/src/components/Chat/ask/state.tsxnew file mode 100644index 0000000000..65a69eaa98--- /dev/null+++ b/client/src/components/Chat/ask/state.tsx@@ -0,0 +1,50 @@+import { createContext, useContext } from 'react';+import { atom } from 'jotai';+import type { ReactNode } from 'react';++/**+ * Action ids the user moved into the chat: the popover is hidden and the+ * composer is released, so the chat card is the question's only surface.+ */+export const collapsedAskActionsAtom = atom<string[]>([]);++/** Currently highlighted option row (keyboard cursor), or nothing. */+export const askAnswerSelectionAtom = atom<number | null>(null);++/** Checked option rows for a multi-select question. */+export const askAnswerCheckedAtom = atom<number[]>([]);++/** Free-form answers keyed by pending action id. */+export const askAnswerTextAtom = atom<Record<string, string>>({});++/**+ * Ordinary composer text stashed while the card owns the composer, keyed by+ * pending action id. The conversation rides along because every hand-back is+ * scoped to it: a resume that settles after the user navigated away leaves no+ * one watching the exit, so returning to that conversation is the only+ * remaining chance to give the message back.+ */+export type ReleasedComposerStash = { conversationId: string | null; text: string };+export const releasedComposerTextAtom = atom<Record<string, ReleasedComposerStash>>({});++/** Submission lifecycle shared by composer and message-content surfaces. */+export type AskAnswerStatus = 'idle' | 'submitting' | 'submitted' | 'expired' | 'error';+export const askSubmitStatusAtom = atom<Record<string, AskAnswerStatus>>({});++const AskAnswerHostContext = createContext(false);++export function AskAnswerHostProvider({+ saveDrafts,+ children,+}: {+ saveDrafts: boolean;+ children?: ReactNode;+}) {+ return (+ <AskAnswerHostContext.Provider value={saveDrafts}>{children}</AskAnswerHostContext.Provider>+ );+}++export function useAskAnswerHost(): boolean {+ return useContext(AskAnswerHostContext);+}diff --git a/client/src/components/Messages/Content/Error.tsx b/client/src/components/Messages/Content/Error.tsxindex d282fd399e..ccd9f305ac 100644--- a/client/src/components/Messages/Content/Error.tsx+++ b/client/src/components/Messages/Content/Error.tsx@@ -58,6 +58,22 @@ type TGenericError = {info: string;};+type TContextOverflow = {+ info?: string;+ provider?: string;+ projectedMessageTokens?: number;+ availableMessageTokens?: number;+};++/**+ * SDK boilerplate already covered by the localized headline; whatever remains+ * (specific guidance and the token budget breakdown) renders as details.+ */+const emptyMessagesBoilerplate = [+ 'Message pruning removed all messages as none fit in the context window.',+ 'Please increase the context window size or make your message shorter.',+];+const errorMessages = {[ErrorTypes.MODERATION]: 'com_error_moderation',[ErrorTypes.NO_USER_KEY]: 'com_error_no_user_key',@@ -102,6 +118,39 @@ const errorMessages = {[ErrorTypes.STREAM_EXPIRED]: 'com_error_stream_expired',[ErrorTypes.MODEL_NOT_FOUND]: langChainErrorKeys.MODEL_NOT_FOUND,[ErrorTypes.MODEL_RATE_LIMIT]: langChainErrorKeys.MODEL_RATE_LIMIT,+ [ErrorTypes.EMPTY_MESSAGES]: (json: TGenericError, localize: LocalizeFunction) => {+ const detail = emptyMessagesBoilerplate+ .reduce((info, sentence) => info.replace(sentence, ''), json.info ?? '')+ .trim();+ return (+ <>+ {localize('com_error_empty_messages')}+ {detail && (+ <>+ <br />+ <br />+ <CodeBlock+ lang={localize('com_ui_details')}+ error={true}+ allowExecution={false}+ codeChildren={detail}+ />+ </>+ )}+ </>+ );+ },+ [ErrorTypes.FINAL_CONTEXT_OVERFLOW]: (json: TContextOverflow, localize: LocalizeFunction) => {+ const { projectedMessageTokens: projected, availableMessageTokens: available } = json;+ const message = localize('com_error_final_context_overflow');+ if (typeof projected !== 'number' || typeof available !== 'number') {+ return message;+ }+ return `${message} ${localize('com_error_context_tokens_detail', {+ 0: projected,+ 1: available,+ })}`;+ },[ViolationTypes.BAN]:'Your account has been temporarily banned due to violations of our service.',[ViolationTypes.ILLEGAL_MODEL_REQUEST]: (json: TGenericError, localize: LocalizeFunction) => {diff --git a/client/src/components/Messages/Content/__tests__/Error.spec.tsx b/client/src/components/Messages/Content/__tests__/Error.spec.tsxindex 3c6e3069dc..46c68d3585 100644--- a/client/src/components/Messages/Content/__tests__/Error.spec.tsx+++ b/client/src/components/Messages/Content/__tests__/Error.spec.tsx@@ -11,8 +11,16 @@ import Error from '../Error';jest.mock('~/hooks', () => ({useLocalize:() =>- (key: string): string =>- (jest.requireActual('~/locales/en/translation.json') as Record<string, string>)[key] ?? key,+ (key: string, values?: Record<string, unknown>): string => {+ const template =+ (jest.requireActual('~/locales/en/translation.json') as Record<string, string>)[key] ?? key;+ if (!values) {+ return template;+ }+ return template.replace(/\{\{(\w+)\}\}/g, (match, name) =>+ values[name] != null ? String(values[name]) : match,+ );+ },}));const catalog = translation as Record<string, string>;@@ -69,3 +77,56 @@ describe('Error — typed provider errors', () => {).toBeInTheDocument();});});++describe('Error: agent context budget errors', () => {+ beforeAll(() => {+ /** CodeBlock observes its code bar; jsdom ships no IntersectionObserver. */+ (global as { IntersectionObserver?: unknown }).IntersectionObserver = class {+ observe() {}+ unobserve() {}+ disconnect() {}+ };+ });++ it('renders localized copy and the token breakdown for empty_messages', () => {+ /** Mirrors the SDK payload as embedded by the agents controller's error prefix. */+ const info =+ 'Message pruning removed all messages as none fit in the context window. Please increase the context window size or make your message shorter.\nToken budget breakdown:\n maxContextTokens: 10\n messageTokens: 32 (4 messages)\n availableForMessages: 9';+ const payload = `An error occurred while processing the request: ${JSON.stringify({+ type: ErrorTypes.EMPTY_MESSAGES,+ info,+ })}`;+ render(<Error text={payload} />);++ expect(screen.getByText(catalog.com_error_empty_messages)).toBeInTheDocument();+ expect(screen.getByText(/Token budget breakdown/)).toBeInTheDocument();+ expect(screen.queryByText(/Something went wrong/)).not.toBeInTheDocument();+ });++ it('renders localized copy with token counts for final_context_overflow', () => {+ const payload = `An error occurred while processing the request: ${JSON.stringify({+ type: ErrorTypes.FINAL_CONTEXT_OVERFLOW,+ info: 'Provider message formatting exceeded the context budget and no safe synthetic-context compaction could make it fit.',+ provider: 'openAI',+ projectedMessageTokens: 3,+ availableMessageTokens: 0,+ })}`;+ render(<Error text={payload} />);++ expect(+ screen.getByText(new RegExp(catalog.com_error_final_context_overflow.slice(0, 40))),+ ).toBeInTheDocument();+ expect(screen.getByText(/need 3 tokens, but only 0 are available/)).toBeInTheDocument();+ expect(screen.queryByText(/Something went wrong/)).not.toBeInTheDocument();+ });++ it('falls back to the plain sentence when overflow token counts are absent', () => {+ const payload = JSON.stringify({+ type: ErrorTypes.FINAL_CONTEXT_OVERFLOW,+ info: 'Fallback provider message formatting exceeded the context budget before invocation.',+ });+ render(<Error text={payload} />);++ expect(screen.getByText(catalog.com_error_final_context_overflow)).toBeInTheDocument();+ });+});diff --git a/client/src/components/Messages/ContentRender.tsx b/client/src/components/Messages/ContentRender.tsxindex 51a9279e27..7d0138891a 100644--- a/client/src/components/Messages/ContentRender.tsx+++ b/client/src/components/Messages/ContentRender.tsx@@ -1,4 +1,5 @@import { useCallback, useMemo, memo } from 'react';+import { useAtomValue } from 'jotai';import { useRecoilValue } from 'recoil';import { Constants } from 'librechat-data-provider';import type { TMessage, TMessageContentParts } from 'librechat-data-provider';@@ -20,6 +21,7 @@ import SiblingSwitch from '~/components/Chat/Messages/SiblingSwitch';import HoverButtons from '~/components/Chat/Messages/HoverButtons';import MessageRow from '~/components/Chat/Messages/ui/MessageRow';import MessageIcon from '~/components/Chat/Messages/MessageIcon';+import { showThinkingAtom } from '~/store/showThinking';import SubRow from '~/components/Chat/Messages/SubRow';import store from '~/store';@@ -106,6 +108,7 @@ const ContentRender = memo(function ContentRender({chatContext,});const maximizeChatSpace = useRecoilValue(store.maximizeChatSpace);+ const showThinking = useAtomValue(showThinkingAtom);const handleRegenerateMessage = useCallback(() => regenerateMessage(), [regenerateMessage]);const isLast = useMemo(@@ -219,6 +222,7 @@ const ContentRender = memo(function ContentRender({isSubmitting={isSubmitting}isCreatedByUser={msg.isCreatedByUser}createdAt={msg.createdAt ?? msg.clientTimestamp}+ showThinking={showThinking}conversationId={conversation?.conversationId}content={msg.content as Array<TMessageContentParts | undefined>}/>diff --git a/client/src/components/Skills/dialogs/__tests__/UploadSkillDialog.spec.tsx b/client/src/components/Skills/dialogs/__tests__/UploadSkillDialog.spec.tsxindex 7f910399ad..5e20ca4f56 100644--- a/client/src/components/Skills/dialogs/__tests__/UploadSkillDialog.spec.tsx+++ b/client/src/components/Skills/dialogs/__tests__/UploadSkillDialog.spec.tsx@@ -20,11 +20,17 @@ jest.mock('react-router-dom', () => ({jest.mock('@librechat/client', () => {const React = jest.requireActual<typeof import('react')>('react');+ const ReactDOM = jest.requireActual<typeof import('react-dom')>('react-dom');return {OGDialog: ({ open, children }: { open: boolean; children: ReactNode }) =>- open ? React.createElement('div', null, children) : null,+ open+ ? ReactDOM.createPortal(+ React.createElement('div', null, children),+ globalThis.document.body,+ )+ : null,OGDialogContent: ({ children }: { children: ReactNode }) =>- React.createElement('div', null, children),+ React.createElement('div', { role: 'dialog', 'data-state': 'open' }, children),Spinner: () => React.createElement('div', { 'data-testid': 'spinner' }),useToastContext: () => ({showToast: mockShowToast,@@ -67,8 +73,14 @@ jest.mock('~/utils', () => ({}));function getFileInput(container: HTMLElement): HTMLInputElement {- const input = container.querySelector('input[type="file"]');- if (!(input instanceof HTMLInputElement)) {+ /** Prefer the local render container used by the lightweight dialog mock,+ * then the active portal. Exiting Headless UI portals can leave older file+ * inputs in `document.body`; a document-wide first/last match is unstable. */+ const selector = 'input[type="file"][accept=".zip,.skill,.md"]';+ const input =+ container.querySelector<HTMLInputElement>(selector) ??+ document.querySelector<HTMLInputElement>(`[role="dialog"][data-state="open"] ${selector}`);+ if (input == null) {throw new Error('Upload input was not rendered');}return input;@@ -102,6 +114,18 @@ describe('UploadSkillDialog', () => {expect(screen.getByText('File size must not exceed 1.06 MB')).toBeInTheDocument();});+ it('targets the current upload input when an exiting portal still has one', () => {+ const staleInput = document.createElement('input');+ staleInput.type = 'file';+ staleInput.accept = '.zip,.skill,.md';+ document.body.appendChild(staleInput);++ const { container } = render(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);++ expect(getFileInput(container)).not.toBe(staleInput);+ staleInput.remove();+ });+it('rejects files above the configured skill import limit before upload', () => {const { container } = render(<UploadSkillDialog isOpen={true} setIsOpen={mockSetIsOpen} />);const file = new File([new Uint8Array(1024 * 1024 + 1)], 'too-large.skill', {diff --git a/client/src/components/UnifiedSidebar/mobile/__tests__/BottomBar.spec.tsx b/client/src/components/UnifiedSidebar/mobile/__tests__/BottomBar.spec.tsxindex 96e2a0ecfe..d2fe5e5c36 100644--- a/client/src/components/UnifiedSidebar/mobile/__tests__/BottomBar.spec.tsx+++ b/client/src/components/UnifiedSidebar/mobile/__tests__/BottomBar.spec.tsx@@ -1,7 +1,7 @@import React from 'react';import { RecoilRoot } from 'recoil';-import { render, screen, fireEvent } from '@testing-library/react';import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import { act, cleanup, render, screen, fireEvent } from '@testing-library/react';import type { NavLink } from '~/common';jest.mock('~/hooks', () => ({@@ -47,12 +47,19 @@ jest.mock('~/hooks/useNewConvo', () => ({import BottomBar from '../BottomBar';const links = [] as NavLink[];+let queryClient: QueryClient;describe('mobile bottom bar — new chat ordering', () => {beforeEach(() => {+ queryClient = new QueryClient();jest.clearAllMocks();});+ afterEach(() => {+ cleanup();+ queryClient.clear();+ });+/*** The drawer close must start BEFORE the conversation reset: run* synchronously, the reset's cache clearing and navigation flush in the@@ -71,7 +78,7 @@ describe('mobile bottom bar — new chat ordering', () => {});render(- <QueryClientProvider client={new QueryClient()}>+ <QueryClientProvider client={queryClient}><RecoilRoot><BottomBar links={links} onNewChat={onNewChat} /></RecoilRoot>@@ -82,14 +89,14 @@ describe('mobile bottom bar — new chat ordering', () => {expect(order).toEqual(['close']);expect(afterSlide).toBeDefined();- afterSlide?.();+ act(() => afterSlide?.());expect(order).toEqual(['close', 'reset']);});it('leaves modified clicks to the browser (new tab)', () => {const onNewChat = jest.fn();render(- <QueryClientProvider client={new QueryClient()}>+ <QueryClientProvider client={queryClient}><RecoilRoot><BottomBar links={links} onNewChat={onNewChat} /></RecoilRoot>diff --git a/client/src/hooks/Input/useAskAnswerMode.spec.ts b/client/src/hooks/Input/useAskAnswerMode.spec.tsindex 691275ea12..12e5cf0745 100644--- a/client/src/hooks/Input/useAskAnswerMode.spec.ts+++ b/client/src/hooks/Input/useAskAnswerMode.spec.ts@@ -1,38 +1,49 @@+import React from 'react';+import { Provider, createStore } from 'jotai';+import { act, renderHook } from '@testing-library/react';+import {+ AskAnswerHostProvider,+ collapsedAskActionsAtom,+ askAnswerSelectionAtom,+ askAnswerCheckedAtom,+ askAnswerTextAtom,+ releasedComposerTextAtom,+} from '~/components/Chat/ask/state';+const mockSubmitAskAnswer = jest.fn();const mockResetComposer = jest.fn();const mockGetComposerText = jest.fn(() => 'answer from A');-const mockSetSelected = jest.fn();-const mockSetChecked = jest.fn();+const mockSetComposerText = jest.fn();+const mockSetDraft = jest.fn();let mockSaveDrafts = false;+let mockAskStatus = 'idle';+let jotaiStore = createStore();++const JotaiWrapper = ({ children }: { children: React.ReactNode }) =>+ React.createElement(+ Provider,+ { store: jotaiStore },+ React.createElement(AskAnswerHostProvider, { saveDrafts: mockSaveDrafts }, children),+ );jest.mock('~/data-provider', () => ({ useGetMessagesByConvoId: jest.fn() }));jest.mock('~/components/Chat/Messages/Content/ApprovalContext', () => ({- useAskSubmitStatus: () => ({ getAskStatus: () => 'idle' }),+ useAskSubmitStatus: () => ({ getAskStatus: () => mockAskStatus }),useResumeSubmit: () => ({ submitAskAnswer: mockSubmitAskAnswer }),}));jest.mock('~/Providers', () => ({useOptionalChatFormContext: () => ({reset: mockResetComposer,getValues: mockGetComposerText,+ setValue: mockSetComposerText,}),}));-jest.mock('~/utils', () => ({ getAskAnswerDraftId: (id: string) => `draft-${id}` }));-jest.mock('recoil', () => ({- atom: (cfg: unknown) => cfg,- useRecoilState: (state: { key?: string }) => {- if (state.key === 'askAnswerModeSelection') {- return [null, mockSetSelected];- }- if (state.key === 'askAnswerModeChecked') {- return [[], mockSetChecked];- }- return [[], jest.fn()];- },- useRecoilValue: () => mockSaveDrafts,+jest.mock('~/utils', () => ({+ getAskAnswerDraftId: (id: string) => `draft-${id}`,+ morphTransition: (update: () => void) => update(),+ setDraft: (...args: unknown[]) => mockSetDraft(...args),}));-jest.mock('~/store', () => ({ __esModule: true, default: { saveDrafts: 'saveDrafts' } }));-import { renderHook } from '@testing-library/react';import { useGetMessagesByConvoId } from '~/data-provider';import { findLiveAskUserQuestion } from '~/utils/approval';import useAskAnswerMode from './useAskAnswerMode';@@ -44,31 +55,43 @@ const liveAsk = {question: { question: 'Pick one', options: [], multiSelect: false },} as unknown as ReturnType<typeof findLiveAskUserQuestion>;+const batchAsk = {+ ...liveAsk,+ questions: [+ { id: 'environment', question: 'Which environment?' },+ { id: 'window', question: 'Which window?' },+ ],+} as typeof liveAsk;+describe('useAskAnswerMode', () => {beforeEach(() => {jest.clearAllMocks();mockSaveDrafts = false;+ mockAskStatus = 'idle';+ jotaiStore = createStore();mockGetComposerText.mockReturnValue('answer from A');+ mockSetComposerText.mockReset();+ mockSubmitAskAnswer.mockReset();});- it('projects the live ask via the findLiveAskUserQuestion select over the conversation cache', () => {+ it('is active when a live ask is available', () => {mockUseGetMessages.mockReturnValue({ data: liveAsk });- const { result } = renderHook(() => useAskAnswerMode('conversation-1'));+ const { result } = renderHook(() => useAskAnswerMode('conversation-1'), {+ wrapper: JotaiWrapper,+ });- expect(mockUseGetMessages).toHaveBeenCalledWith(- 'conversation-1',- expect.objectContaining({ enabled: true, select: findLiveAskUserQuestion }),- );expect(result.current.liveAsk).toBe(liveAsk);expect(result.current.active).toBe(true);expect(result.current.popoverVisible).toBe(true);});- it('is inactive when the select finds no live ask', () => {+ it('is inactive without a live ask', () => {mockUseGetMessages.mockReturnValue({ data: undefined });- const { result } = renderHook(() => useAskAnswerMode('conversation-1'));+ const { result } = renderHook(() => useAskAnswerMode('conversation-1'), {+ wrapper: JotaiWrapper,+ });expect(result.current.liveAsk).toBeNull();expect(result.current.active).toBe(false);@@ -76,17 +99,11 @@ describe('useAskAnswerMode', () => {});it('locks the composer for a batch, and hands it back the moment it collapses', () => {- mockUseGetMessages.mockReturnValue({- data: {- ...liveAsk,- questions: [- { id: 'environment', question: 'Which environment?' },- { id: 'window', question: 'Which window?' },- ],- },- });+ mockUseGetMessages.mockReturnValue({ data: batchAsk });- const { result } = renderHook(() => useAskAnswerMode('conversation-1'));+ const { result } = renderHook(() => useAskAnswerMode('conversation-1'), {+ wrapper: JotaiWrapper,+ });expect(result.current.active).toBe(true);expect(result.current.batchMode).toBe(true);@@ -101,15 +118,37 @@ describe('useAskAnswerMode', () => {expect(mockSubmitAskAnswer).not.toHaveBeenCalled();});- it('disables the query and forces liveAsk null for a new (unsaved) conversation', () => {- mockUseGetMessages.mockReturnValue({ data: liveAsk });+ it('does not move the normal composer draft into a collapsed batch answer', () => {+ mockUseGetMessages.mockReturnValue({ data: batchAsk });+ const { result } = renderHook(() => useAskAnswerMode('conversation-1'), {+ wrapper: JotaiWrapper,+ });- const { result } = renderHook(() => useAskAnswerMode('new'));+ act(() => result.current.collapse());- expect(mockUseGetMessages).toHaveBeenCalledWith(- '',- expect.objectContaining({ enabled: false }),- );+ expect(jotaiStore.get(askAnswerTextAtom)).toEqual({});+ expect(mockResetComposer).not.toHaveBeenCalled();+ });++ it('does not overwrite normal composer text when expanding a batch', () => {+ jotaiStore.set(collapsedAskActionsAtom, ['a1']);+ jotaiStore.set(askAnswerTextAtom, { a1: 'stale batch handoff' });+ mockUseGetMessages.mockReturnValue({ data: batchAsk });+ const { result } = renderHook(() => useAskAnswerMode('conversation-1'), {+ wrapper: JotaiWrapper,+ });++ act(() => result.current.expand());++ expect(mockSetComposerText).not.toHaveBeenCalled();+ });++ it('is inactive for a new unsaved conversation', () => {+ mockUseGetMessages.mockReturnValue({ data: liveAsk });++ const { result } = renderHook(() => useAskAnswerMode('new'), {+ wrapper: JotaiWrapper,+ });expect(result.current.liveAsk).toBeNull();expect(result.current.active).toBe(false);});@@ -117,11 +156,245 @@ describe('useAskAnswerMode', () => {it('forces liveAsk null when there is no conversation id', () => {mockUseGetMessages.mockReturnValue({ data: liveAsk });- const { result } = renderHook(() => useAskAnswerMode(null));+ const { result } = renderHook(() => useAskAnswerMode(null), {+ wrapper: JotaiWrapper,+ });expect(result.current.liveAsk).toBeNull();});+ it('moves the composer answer into the card and clears it when drafts are disabled', () => {+ mockUseGetMessages.mockReturnValue({ data: liveAsk });+ const { result } = renderHook(() => useAskAnswerMode('conversation-1'), {+ wrapper: JotaiWrapper,+ });++ act(() => result.current.collapse());++ expect(jotaiStore.get(askAnswerTextAtom)).toEqual({ a1: 'answer from A' });+ expect(mockResetComposer).toHaveBeenCalledTimes(1);+ });++ it('lets draft handoff restore the conversation composer when drafts are enabled', () => {+ mockSaveDrafts = true;+ mockUseGetMessages.mockReturnValue({ data: liveAsk });+ const { result } = renderHook(() => useAskAnswerMode('conversation-1'), {+ wrapper: JotaiWrapper,+ });++ act(() => result.current.collapse());++ expect(mockResetComposer).not.toHaveBeenCalled();+ });++ it('restores the card answer into the composer when drafts are disabled', () => {+ jotaiStore.set(collapsedAskActionsAtom, ['a1']);+ jotaiStore.set(askAnswerTextAtom, { a1: 'answer edited in the card' });+ mockUseGetMessages.mockReturnValue({ data: liveAsk });+ const { result } = renderHook(() => useAskAnswerMode('conversation-1'), {+ wrapper: JotaiWrapper,+ });++ act(() => result.current.expand());++ expect(mockSetComposerText).toHaveBeenCalledWith('text', 'answer edited in the card');+ });++ it('keeps the ask-specific draft current while editing the card', () => {+ mockSaveDrafts = true;+ mockUseGetMessages.mockReturnValue({ data: liveAsk });+ const { result } = renderHook(() => useAskAnswerMode('conversation-1'), {+ wrapper: JotaiWrapper,+ });++ act(() => result.current.setAnswerText('answer edited in the card'));++ expect(jotaiStore.get(askAnswerTextAtom)).toEqual({ a1: 'answer edited in the card' });+ expect(mockSetDraft).toHaveBeenCalledWith({+ id: 'draft-a1',+ value: 'answer edited in the card',+ });+ });++ it("preserves another paused question's answer when a second one is edited", () => {+ jotaiStore.set(askAnswerTextAtom, { a1: 'answer from A' });+ const otherAsk = {+ actionId: 'a2',+ question: { question: 'Pick one', options: [], multiSelect: false },+ } as unknown as typeof liveAsk;+ mockUseGetMessages.mockReturnValue({ data: otherAsk });+ const { result } = renderHook(() => useAskAnswerMode('conversation-2'), {+ wrapper: JotaiWrapper,+ });++ act(() => result.current.setAnswerText('answer from B'));++ /** A single shared slot dropped A's unsent answer the moment B claimed+ * it, and the action-scoped reader then showed A an empty box. */+ expect(jotaiStore.get(askAnswerTextAtom)).toEqual({+ a1: 'answer from A',+ a2: 'answer from B',+ });+ });++ it.each(['expired', 'submitted', 'removed'])(+ 'restores the released message when the question is %s',+ (terminal) => {+ let composerText = 'answer from A';+ mockGetComposerText.mockImplementation(() => composerText);+ mockSetComposerText.mockImplementation((_name: string, text: string) => {+ composerText = text;+ });+ mockUseGetMessages.mockReturnValue({ data: liveAsk });+ const { result, rerender } = renderHook(() => useAskAnswerMode('conversation-1'), {+ wrapper: JotaiWrapper,+ });+ act(() => result.current.collapse());+ composerText = 'an ordinary unsent message';+ act(() => result.current.expand());+ expect(composerText).toBe('answer from A');++ if (terminal === 'removed') {+ mockUseGetMessages.mockReturnValue({ data: null });+ } else {+ mockAskStatus = terminal;+ }+ rerender();++ expect(result.current.active).toBe(false);+ expect(composerText).toBe('an ordinary unsent message');+ expect(jotaiStore.get(releasedComposerTextAtom)).toEqual({});+ },+ );++ it('preserves newer composer edits when an in-flight question expires', () => {+ jotaiStore.set(releasedComposerTextAtom, {+ a1: { conversationId: 'conversation-1', text: 'an older message' },+ });+ mockUseGetMessages.mockReturnValue({ data: liveAsk });+ const { rerender } = renderHook(() => useAskAnswerMode('conversation-1'), {+ wrapper: JotaiWrapper,+ });+ mockAskStatus = 'submitting';+ rerender();+ mockGetComposerText.mockReturnValue('newer message typed during submission');+ mockAskStatus = 'expired';+ rerender();++ expect(mockSetComposerText).not.toHaveBeenCalled();+ expect(jotaiStore.get(releasedComposerTextAtom)).toEqual({});+ });++ it('does not restore a departed conversation stash into a different composer', () => {+ jotaiStore.set(releasedComposerTextAtom, {+ a1: { conversationId: 'conversation-1', text: 'message for conversation A' },+ });+ mockUseGetMessages.mockReturnValue({ data: liveAsk });+ const { rerender } = renderHook(({ id }) => useAskAnswerMode(id), {+ initialProps: { id: 'conversation-1' },+ wrapper: JotaiWrapper,+ });+ mockUseGetMessages.mockReturnValue({ data: null });+ rerender({ id: 'conversation-2' });++ expect(mockSetComposerText).not.toHaveBeenCalled();+ expect(jotaiStore.get(releasedComposerTextAtom)).toEqual({+ a1: { conversationId: 'conversation-1', text: 'message for conversation A' },+ });+ });++ it('hands a stash back when its conversation is revisited after the answer settled', () => {+ /** Navigating away mid-resume leaves nobody watching the exit, so the+ * settle drops the question without restoring anything. The stash has to+ * survive until its own conversation comes back, or the ordinary unsent+ * message is unreachable for the rest of the session. */+ jotaiStore.set(releasedComposerTextAtom, {+ a1: { conversationId: 'conversation-1', text: 'message for conversation A' },+ });+ mockUseGetMessages.mockReturnValue({ data: liveAsk });+ mockAskStatus = 'submitting';+ const { rerender } = renderHook(({ id }) => useAskAnswerMode(id), {+ initialProps: { id: 'conversation-1' },+ wrapper: JotaiWrapper,+ });+ mockUseGetMessages.mockReturnValue({ data: null });+ rerender({ id: 'conversation-2' });+ expect(mockSetComposerText).not.toHaveBeenCalled();++ /** Drafts are off, so the revisited composer opens empty — the only state+ * in which handing the stash back cannot overwrite something newer. */+ mockGetComposerText.mockReturnValue('');+ mockAskStatus = 'submitted';+ rerender({ id: 'conversation-1' });++ expect(mockSetComposerText).toHaveBeenLastCalledWith('text', 'message for conversation A');+ expect(jotaiStore.get(releasedComposerTextAtom)).toEqual({});+ });++ it('hands the released composer text back when the answer is submitted', () => {+ /** Stashed by a prior expand: the question was collapsed, an ordinary+ * message was typed in the released composer, then the question was moved+ * back. Submitting from there never goes through `collapse`, so the+ * message has to be restored here or it dies with the question. */+ jotaiStore.set(releasedComposerTextAtom, {+ a1: { conversationId: 'conversation-1', text: 'an ordinary unsent message' },+ });+ mockUseGetMessages.mockReturnValue({ data: liveAsk });+ mockSubmitAskAnswer.mockImplementation(+ (_actionId: string, _answer: string, options?: { onSuccess?: () => void }) => {+ options?.onSuccess?.();+ },+ );+ const { result } = renderHook(() => useAskAnswerMode('conversation-1'), {+ wrapper: JotaiWrapper,+ });++ act(() => {+ result.current.submitText('answer from A');+ });++ expect(mockSetComposerText).toHaveBeenLastCalledWith('text', 'an ordinary unsent message');+ expect(mockResetComposer).not.toHaveBeenCalled();+ expect(jotaiStore.get(releasedComposerTextAtom)).toEqual({});+ });++ it('hands the released text back for an option answer too', () => {+ /** Only the free-text path sets `consumedComposerText`, so gating the+ * restore on it discarded the stash whenever the user answered by+ * clicking an option (or skipping) instead of typing. */+ jotaiStore.set(releasedComposerTextAtom, {+ a1: { conversationId: 'conversation-1', text: 'an ordinary unsent message' },+ });+ const askWithOptions = {+ actionId: 'a1',+ question: {+ question: 'Pick one',+ options: [+ { label: 'Blue', value: 'blue' },+ { label: 'Green', value: 'green' },+ ],+ multiSelect: false,+ },+ } as unknown as typeof liveAsk;+ mockUseGetMessages.mockReturnValue({ data: askWithOptions });+ mockSubmitAskAnswer.mockImplementation(+ (_actionId: string, _answer: string, options?: { onSuccess?: () => void }) => {+ options?.onSuccess?.();+ },+ );+ const { result } = renderHook(() => useAskAnswerMode('conversation-1'), {+ wrapper: JotaiWrapper,+ });++ act(() => {+ result.current.submitOption(0);+ });++ expect(mockSubmitAskAnswer).toHaveBeenCalledWith('a1', 'blue', expect.anything());+ expect(mockSetComposerText).toHaveBeenLastCalledWith('text', 'an ordinary unsent message');+ expect(jotaiStore.get(releasedComposerTextAtom)).toEqual({});+ });+it('does not let a delayed answer success clear the composer or selection after navigation', () => {let finishAnswer: (() => void) | undefined;mockUseGetMessages.mockReturnValue({ data: liveAsk });@@ -132,7 +405,7 @@ describe('useAskAnswerMode', () => {);const { result, rerender } = renderHook(({ conversationId }) => useAskAnswerMode(conversationId),- { initialProps: { conversationId: 'conversation-A' } },+ { initialProps: { conversationId: 'conversation-A' }, wrapper: JotaiWrapper },);expect(result.current.submitText('answer from A')).toBe(true);@@ -149,14 +422,15 @@ describe('useAskAnswerMode', () => {mockUseGetMessages.mockReturnValue({ data: nextAsk });mockGetComposerText.mockReturnValue('draft typed in B');rerender({ conversationId: 'conversation-B' });- mockSetSelected.mockClear();- mockSetChecked.mockClear();-- finishAnswer?.();+ act(() => {+ jotaiStore.set(askAnswerSelectionAtom, 1);+ jotaiStore.set(askAnswerCheckedAtom, [0]);+ });+ act(() => finishAnswer?.());expect(mockResetComposer).not.toHaveBeenCalled();- expect(mockSetSelected).not.toHaveBeenCalled();- expect(mockSetChecked).not.toHaveBeenCalled();+ expect(jotaiStore.get(askAnswerSelectionAtom)).toBe(1);+ expect(jotaiStore.get(askAnswerCheckedAtom)).toEqual([0]);});it('keeps newer composer text when the answer settles on the same question', () => {@@ -167,18 +441,21 @@ describe('useAskAnswerMode', () => {finishAnswer = options?.onSuccess;},);- const { result } = renderHook(() => useAskAnswerMode('conversation-A'));+ const { result } = renderHook(() => useAskAnswerMode('conversation-A'), {+ wrapper: JotaiWrapper,+ });expect(result.current.submitText('answer from A')).toBe(true);mockGetComposerText.mockReturnValue('new text typed while resuming');- mockSetSelected.mockClear();- mockSetChecked.mockClear();-- finishAnswer?.();+ act(() => {+ jotaiStore.set(askAnswerSelectionAtom, 1);+ jotaiStore.set(askAnswerCheckedAtom, [0]);+ });+ act(() => finishAnswer?.());expect(mockResetComposer).not.toHaveBeenCalled();- expect(mockSetSelected).toHaveBeenCalledWith(null);- expect(mockSetChecked).toHaveBeenCalledWith([]);+ expect(jotaiStore.get(askAnswerSelectionAtom)).toBeNull();+ expect(jotaiStore.get(askAnswerCheckedAtom)).toEqual([]);});it('clears the consumed answer when the same question and composer value still own it', () => {@@ -189,14 +466,16 @@ describe('useAskAnswerMode', () => {finishAnswer = options?.onSuccess;},);- const { result } = renderHook(() => useAskAnswerMode('conversation-A'));+ const { result } = renderHook(() => useAskAnswerMode('conversation-A'), {+ wrapper: JotaiWrapper,+ });expect(result.current.submitText('answer from A')).toBe(true);- finishAnswer?.();+ act(() => finishAnswer?.());expect(mockResetComposer).toHaveBeenCalledTimes(1);- expect(mockSetSelected).toHaveBeenCalledWith(null);- expect(mockSetChecked).toHaveBeenCalledWith([]);+ expect(jotaiStore.get(askAnswerSelectionAtom)).toBeNull();+ expect(jotaiStore.get(askAnswerCheckedAtom)).toEqual([]);});it('ignores a delayed answer success after its answer-mode owner unmounts', () => {@@ -207,16 +486,18 @@ describe('useAskAnswerMode', () => {finishAnswer = options?.onSuccess;},);- const { result, unmount } = renderHook(() => useAskAnswerMode('conversation-A'));-- expect(result.current.submitText('answer from A')).toBe(true);+ const { unmount } = renderHook(() => useAskAnswerMode('conversation-A'), {+ wrapper: JotaiWrapper,+ });+ act(() => {+ jotaiStore.set(askAnswerSelectionAtom, 1);+ jotaiStore.set(askAnswerCheckedAtom, [0]);+ });unmount();- mockSetSelected.mockClear();- mockSetChecked.mockClear();- finishAnswer?.();+ act(() => finishAnswer?.());expect(mockResetComposer).not.toHaveBeenCalled();- expect(mockSetSelected).not.toHaveBeenCalled();- expect(mockSetChecked).not.toHaveBeenCalled();+ expect(jotaiStore.get(askAnswerSelectionAtom)).toBe(1);+ expect(jotaiStore.get(askAnswerCheckedAtom)).toEqual([0]);});});diff --git a/client/src/hooks/Input/useAskAnswerMode.ts b/client/src/hooks/Input/useAskAnswerMode.tsindex a78b3afb6e..561830d229 100644--- a/client/src/hooks/Input/useAskAnswerMode.ts+++ b/client/src/hooks/Input/useAskAnswerMode.ts@@ -1,5 +1,13 @@import { useCallback, useEffect, useMemo, useRef } from 'react';-import { atom, useRecoilState, useRecoilValue } from 'recoil';+import { useAtom } from 'jotai';+import {+ collapsedAskActionsAtom,+ askAnswerSelectionAtom,+ askAnswerCheckedAtom,+ askAnswerTextAtom,+ releasedComposerTextAtom,+ useAskAnswerHost,+} from '~/components/Chat/ask/state';import {useAskSubmitStatus,useResumeSubmit,@@ -9,36 +17,9 @@ import {findLiveAskUserQuestion,splitOtherOption,} from '~/utils/approval';+import { getAskAnswerDraftId, morphTransition, setDraft } from '~/utils';import { useGetMessagesByConvoId } from '~/data-provider';import { useOptionalChatFormContext } from '~/Providers';-import { getAskAnswerDraftId } from '~/utils';-import store from '~/store';--/** Dismissed action ids — recoil so every consumer reacts. */-const dismissedAskActionsAtom = atom<string[]>({- key: 'askAnswerModeDismissedActions',- default: [],-});--/** Collapsed action ids: popover chrome hidden, answer mode still live. */-const collapsedAskActionsAtom = atom<string[]>({- key: 'askAnswerModeCollapsedActions',- default: [],-});--/** Currently highlighted option row (keyboard cursor), or nothing. */-const askAnswerSelectionAtom = atom<number | null>({- key: 'askAnswerModeSelection',- default: null,-});--/** Checked option rows for a multi-select question — shared across the- * popover, the composer, and the chat card so every surface shows (and- * submits) the same set. */-const askAnswerCheckedAtom = atom<number[]>({- key: 'askAnswerModeChecked',- default: [],-});/*** First-class "answer mode" for a live `ask_user_question` pause. Clicking an@@ -51,11 +32,10 @@ const askAnswerCheckedAtom = atom<number[]>({* conversation draft is stashed on entry and restored once the question* resolves.*- * Two ways out short of answering: `collapse` hides the popover chrome but- * KEEPS the pause live (the question renders in the chat card, which still- * answers it), while the × `dismiss` exits answer mode entirely. `Skip`- * resumes the run with a canned decline notice. Collapsing always returns the- * composer to normal chat — see `composerLocked`.+ * One way out short of answering: `collapse` (the popover's chevron, or+ * Escape) moves the question to the chat card AND releases the composer, so+ * the user can type a normal message; the card's chevron moves it back.+ * `Skip` resumes the run with a canned decline notice.** `handleComposerKeyDown` only steers selection from the EMPTY composer and* reports whether it consumed the key.@@ -71,17 +51,16 @@ export default function useAskAnswerMode(conversationId?: string | null) {select: findLiveAskUserQuestion,});const liveAsk = enabled ? (liveAskData ?? null) : null;- const [dismissedIds, setDismissedIds] = useRecoilState(dismissedAskActionsAtom);- const [collapsedIds, setCollapsedIds] = useRecoilState(collapsedAskActionsAtom);- const [selected, setSelected] = useRecoilState(askAnswerSelectionAtom);- const [checked, setChecked] = useRecoilState(askAnswerCheckedAtom);- const saveDrafts = useRecoilValue<boolean>(store.saveDrafts);+ const [collapsedIds, setCollapsedIds] = useAtom(collapsedAskActionsAtom);+ const [selected, setSelected] = useAtom(askAnswerSelectionAtom);+ const [checked, setChecked] = useAtom(askAnswerCheckedAtom);+ const [answerDrafts, setAnswerDrafts] = useAtom(askAnswerTextAtom);+ const [releasedComposerText, setReleasedComposerText] = useAtom(releasedComposerTextAtom);+ const saveDrafts = useAskAnswerHost();const { submitAskAnswer } = useResumeSubmit();- /** Recoil-backed so the lock/status works from the composer, which renders+ /** Jotai-backed so the lock/status works from the composer, which renders* outside `ApprovalProvider` (where the context status would be inert). */const { getAskStatus } = useAskSubmitStatus();- /** Absent outside ChatView (Share/search render the answer card without the- * composer form) — resets are simply skipped there. */const formContext = useOptionalChatFormContext();/** Resume callbacks may settle after this ChatForm has navigated to another* conversation (the form instance is intentionally reused across routes).@@ -97,6 +76,10 @@ export default function useAskAnswerMode(conversationId?: string | null) {actionId: liveAsk?.actionId,formContext,};+ /** Read by the resume success callback, which settles long after the render+ * that armed it, so it must not close over a stale stash. */+ const releasedComposerTextRef = useRef(releasedComposerText);+ releasedComposerTextRef.current = releasedComposerText;const mountedRef = useRef(true);useEffect(() => {// Strict Mode runs setup, cleanup, then setup again in development; each@@ -111,7 +94,6 @@ export default function useAskAnswerMode(conversationId?: string | null) {* no-op so a double-click or a stray Skip can't race a second resume. */const status = liveAsk != null ? getAskStatus(liveAsk.actionId) : 'idle';const locked = status === 'submitting' || status === 'submitted' || status === 'expired';- const dismissed = liveAsk != null && dismissedIds.includes(liveAsk.actionId);/*** An EXPIRED question can no longer be answered, so it drops out of answer* mode entirely: the popover closes, the composer reverts to a normal@@ -127,22 +109,17 @@ export default function useAskAnswerMode(conversationId?: string | null) {* submit whose store write couldn't run) holds the popover open over an* answered question with every option greyed out.*/- const active = liveAsk != null && !dismissed && status !== 'expired' && status !== 'submitted';- const collapsed = active && collapsedIds.includes(liveAsk.actionId);- /** The popover renders only while expanded; collapse keeps `active` but- * hands the question display to the chat card. */- const popoverVisible = active && !collapsed;- const batchMode = (liveAsk?.questions?.length ?? 0) > 0;+ const answerable = liveAsk != null && status !== 'expired' && status !== 'submitted';+ /** Moved to the chat: the card owns the question and the composer is free. */+ const collapsed = answerable && collapsedIds.includes(liveAsk.actionId);/**- * Which role the composer plays for this pause. A single question is- * answered IN the composer, so it stays live for as long as the pause does.- * A batch is answered in its own card, so the composer has nothing to- * contribute and locks — but ONLY while the popover is up. Collapsing has to- * hand the composer back, because every other way out is gone once the- * popover closes: the stop button hides behind `composerAnswers` and Escape- * would reach a disabled textarea. Staying locked past collapse left no way- * to type, send, or stop the run short of reloading the page.+ * Answer mode: the popover is up AND the composer is the free-form answer+ * box. The two are deliberately the same condition because the composer's answer+ * role is only discoverable while the popover explains it.*/+ const active = answerable && !collapsed;+ const popoverVisible = active;+ const batchMode = (liveAsk?.questions?.length ?? 0) > 0;const composerAnswers = active && !batchMode;const composerLocked = popoverVisible && batchMode;const multiSelect = !batchMode && liveAsk != null && liveAsk.question.multiSelect === true;@@ -156,6 +133,93 @@ export default function useAskAnswerMode(conversationId?: string | null) {[batchMode, liveAsk],);+ const lastAnswerableRef = useRef<{+ conversationId: typeof conversationId;+ actionId: string;+ submitting: boolean;+ composerText: string;+ } | null>(null);+ /** Expiration and server-side removal bypass the success callback. Recover+ * the in-memory message on those exits too, without crossing conversations+ * or replacing text edited while a resume was in flight. */+ useEffect(() => {+ const previous = lastAnswerableRef.current;+ if (answerable && liveAsk) {+ const sameAction =+ previous != null &&+ previous.conversationId === conversationId &&+ previous.actionId === liveAsk.actionId;+ const submitting = status === 'submitting';+ lastAnswerableRef.current = {+ conversationId,+ actionId: liveAsk.actionId,+ submitting,+ composerText:+ sameAction && submitting && previous.submitting+ ? previous.composerText+ : (formContext?.getValues('text') ?? ''),+ };+ return;+ }+ lastAnswerableRef.current = null;+ /** Recovery is keyed by the stash's own conversation, not by what this+ * hook happened to observe. Navigating away mid-resume clears the ref+ * while the stash rightly stays put, and the settle then lands with+ * nobody watching that exit — so coming back is the last chance to hand+ * the message over, and gating on the ref stranded it in the atom. */+ const stashed = Object.entries(releasedComposerText).find(+ ([, stash]) => stash.conversationId === conversationId,+ );+ if (!stashed) {+ return;+ }+ const [actionId, stash] = stashed;+ const composerText = formContext?.getValues('text') ?? '';+ /** Only the exit this hook armed knows what the composer held when the+ * resume started. On a revisit the composer is whatever the route+ * restored, so an empty one is the only target that cannot clobber+ * something newer. Either way the entry goes: anything the user typed+ * since is newer than the stash. */+ const restorable =+ previous != null && previous.actionId === actionId+ ? !previous.submitting || composerText === previous.composerText+ : composerText === '';+ if (restorable) {+ formContext?.setValue('text', stash.text);+ }+ setReleasedComposerText((current) => {+ if (current[actionId] == null) {+ return current;+ }+ const next = { ...current };+ delete next[actionId];+ return next;+ });+ }, [+ answerable,+ conversationId,+ liveAsk,+ status,+ formContext,+ releasedComposerText,+ setReleasedComposerText,+ ]);+ const answerText = liveAsk != null ? (answerDrafts[liveAsk.actionId] ?? '') : '';+ const setAnswerText = useCallback(+ (text: string) => {+ if (liveAsk && !batchMode) {+ setAnswerDrafts((current) => ({ ...current, [liveAsk.actionId]: text }));+ /** While the card owns the answer, `useAutoSave` is tracking the+ * conversation draft instead. Keep the dormant ask draft current so+ * expanding can restore this edit without clobbering that message. */+ if (saveDrafts) {+ setDraft({ id: getAskAnswerDraftId(liveAsk.actionId), value: text });+ }+ }+ },+ [batchMode, liveAsk, saveDrafts, setAnswerDrafts],+ );+/** Selection state is per-question: a new pause must never inherit a stale* highlight (or checks) whose Enter would submit the previous question's* choice. */@@ -164,36 +228,121 @@ export default function useAskAnswerMode(conversationId?: string | null) {setChecked([]);}, [liveAsk?.actionId, setSelected, setChecked]);- const dismiss = useCallback(() => {- if (liveAsk) {- setDismissedIds((prev) =>- prev.includes(liveAsk.actionId) ? prev : [...prev, liveAsk.actionId],- );- }- }, [liveAsk, setDismissedIds]);+ /** Popover ⇄ chat-card handoffs run inside a view transition: both+ * surfaces carry the same `view-transition-name`, so the browser morphs+ * one into the other instead of swapping. Both are user-event driven,+ * which morphTransition's synchronous flush requires.+ *+ * Batches opt out: only the single-question surfaces declare+ * `view-transition-name: ask-question`, so wrapping a batch handoff would+ * give the browser nothing to pair and it would cross-fade the whole root+ * (chat plus composer) instead. */+ const runHandoff = useCallback(+ (update: () => void) => {+ if (batchMode) {+ update();+ return;+ }+ morphTransition(update);+ },+ [batchMode],+ );const collapse = useCallback(() => {if (liveAsk) {- setCollapsedIds((prev) =>- prev.includes(liveAsk.actionId) ? prev : [...prev, liveAsk.actionId],- );+ const composerAnswer = !batchMode ? (formContext?.getValues('text') ?? answerText) : '';+ runHandoff(() => {+ if (!batchMode) {+ setAnswerDrafts((current) => ({ ...current, [liveAsk.actionId]: composerAnswer }));+ /** An existing stash is restored regardless of the CURRENT+ * preference: it was captured while saving was off, so it never+ * reached the conversation draft and this is its only recovery path.+ * Gating on `!saveDrafts` dropped it whenever the user enabled+ * saving between expanding and collapsing. */+ const released = releasedComposerText[liveAsk.actionId];+ if (released) {+ formContext?.setValue('text', released.text);+ setReleasedComposerText((current) => {+ if (current[liveAsk.actionId] == null) {+ return current;+ }+ const next = { ...current };+ delete next[liveAsk.actionId];+ return next;+ });+ } else if (!saveDrafts) {+ formContext?.reset();+ }+ }+ setCollapsedIds((prev) =>+ prev.includes(liveAsk.actionId) ? prev : [...prev, liveAsk.actionId],+ );+ });}- }, [liveAsk, setCollapsedIds]);+ }, [+ liveAsk,+ batchMode,+ formContext,+ answerText,+ saveDrafts,+ releasedComposerText,+ setReleasedComposerText,+ setAnswerDrafts,+ setCollapsedIds,+ runHandoff,+ ]);const expand = useCallback(() => {if (liveAsk) {- setCollapsedIds((prev) => prev.filter((id) => id !== liveAsk.actionId));+ /** Read before the transition: the composer is about to be handed back+ * to the answer, and an ordinary unsent message typed while the card+ * owned the question must survive the round trip. */+ const released = !batchMode && !saveDrafts ? (formContext?.getValues('text') ?? '') : '';+ runHandoff(() => {+ /** Autosave restores the ask-specific draft after the key switch. If+ * drafts are disabled, perform that handoff directly. */+ if (!batchMode && !saveDrafts) {+ if (released) {+ setReleasedComposerText((current) => ({+ ...current,+ [liveAsk.actionId]: { conversationId: conversationId ?? null, text: released },+ }));+ }+ formContext?.setValue('text', answerText);+ } else if (!batchMode && answerText) {+ /** Drafts were re-enabled after this answer was captured with saving+ * off, so no ask draft exists for autosave to restore: the composer+ * would open empty and the next collapse would read that empty+ * value back over the in-memory answer. Seed it so the handoff has+ * something to read. The in-memory value is authoritative because+ * `setAnswerText` writes both while saving is on. */+ setDraft({ id: getAskAnswerDraftId(liveAsk.actionId), value: answerText });+ }+ setCollapsedIds((prev) => prev.filter((id) => id !== liveAsk.actionId));+ });}- }, [liveAsk, setCollapsedIds]);+ }, [+ liveAsk,+ conversationId,+ batchMode,+ saveDrafts,+ formContext,+ answerText,+ setReleasedComposerText,+ setCollapsedIds,+ runHandoff,+ ]);+ /** Pure check toggle: the keyboard highlight is steered only by the+ * composer's digit/arrow shortcuts, so a mouse toggle never leaves a+ * row painted `selected` after it is unchecked. */const toggleChecked = useCallback((index: number) => {- setSelected(index);setChecked((prev) =>prev.includes(index) ? prev.filter((i) => i !== index) : [...prev, index],);},- [setSelected, setChecked],+ [setChecked],);const canSubmit =@@ -203,15 +352,15 @@ export default function useAskAnswerMode(conversationId?: string | null) {/*** Shared answer dispatch: sends the run's resume and clears the phase.- * Gated on the live pause (NOT `active` — the chat card must still answer a- * dismissed question) and on `locked` (no duplicate resumes while one is in+ * Gated on the live pause (NOT `active`, because the chat card must still+ * answer a collapsed question) and on `locked` (no duplicate resumes while one is in* flight).** The selection/composer cleanup runs ONLY after the resume is accepted (in- * `submitAskAnswer`'s success path): a failed resume — the 16k answer-cap- * 400, an expired action, a network error — leaves `status` re-answerable,- * so wiping the composer (the user's only copy of a free-form answer) up- * front would lose it. The composer only resets when its text was consumed+ * `submitAskAnswer`'s success path): a retryable failed resume — the 16k+ * answer-cap 400 or a network error — must preserve the user's free-form+ * answer. Terminal exits separately restore any released normal message.+ * The composer only resets when its text was consumed* by the answer or when the draft machinery will restore the stashed* conversation draft; with drafts disabled and an option-click answer the* typed text is left alone.@@ -237,12 +386,43 @@ export default function useAskAnswerMode(conversationId?: string | null) {}setSelected(null);setChecked([]);- if (- (consumedComposerText || (wasActive && saveDrafts)) &&- currentScope.formContext?.getValues('text') === submittedComposerText- ) {- currentScope.formContext.reset();+ /** Drop only the answered question's entry, so a draft belonging to+ * another paused conversation survives and the map stays bounded. */+ setAnswerDrafts((current) => {+ if (current[submittedActionId] == null) {+ return current;+ }+ const next = { ...current };+ delete next[submittedActionId];+ return next;+ });+ /** A successful answer never goes through `collapse`, so the released+ * text has to be handed back here too or the user's ordinary message+ * dies with the question. Restored on EVERY submission path, not+ * just the free-text one: only that path sets+ * `consumedComposerText`, so gating on it discarded the stash on an+ * option click or Skip.+ *+ * Both writes require the composer to still hold what was+ * submitted. The textarea stays editable while the resume is in+ * flight, and anything typed since is newer than both the stash and+ * the answer, so it wins. */+ const released = releasedComposerTextRef.current[submittedActionId];+ if (currentScope.formContext?.getValues('text') === submittedComposerText) {+ if (released) {+ currentScope.formContext.setValue('text', released.text);+ } else if (consumedComposerText || (wasActive && saveDrafts)) {+ currentScope.formContext.reset();+ }}+ setReleasedComposerText((current) => {+ if (current[submittedActionId] == null) {+ return current;+ }+ const next = { ...current };+ delete next[submittedActionId];+ return next;+ });},});return true;@@ -253,10 +433,12 @@ export default function useAskAnswerMode(conversationId?: string | null) {active,saveDrafts,conversationId,+ setReleasedComposerText,formContext,submitAskAnswer,setSelected,setChecked,+ setAnswerDrafts,],);@@ -339,8 +521,7 @@ export default function useAskAnswerMode(conversationId?: string | null) {/*** Explicitly decline: resumes the run with a canned notice so the model- * knows the user chose not to answer. A client-side dismiss alone would- * leave the run paused until expiry — a hung turn.+ * knows the user chose not to answer.*/const skip = useCallback((): boolean => {if (!active) {@@ -389,7 +570,7 @@ export default function useAskAnswerMode(conversationId?: string | null) {*/if (options.length === 0 || !popoverVisible) {if (e.key === 'Escape') {- dismiss();+ collapse();return true;}return false;@@ -398,6 +579,7 @@ export default function useAskAnswerMode(conversationId?: string | null) {if (!Number.isNaN(digit) && digit >= 1 && digit <= Math.min(options.length, 9)) {e.preventDefault();if (multiSelect) {+ setSelected(digit - 1);toggleChecked(digit - 1);} else {setSelected(digit - 1);@@ -420,7 +602,7 @@ export default function useAskAnswerMode(conversationId?: string | null) {return true;}if (e.key === 'Escape') {- dismiss();+ collapse();return true;}return false;@@ -436,7 +618,7 @@ export default function useAskAnswerMode(conversationId?: string | null) {submit,submitText,toggleChecked,- dismiss,+ collapse,setSelected,],);@@ -475,8 +657,6 @@ export default function useAskAnswerMode(conversationId?: string | null) {batchMode,liveAsk,options,- dismissed,- dismiss,collapsed,collapse,expand,@@ -489,6 +669,8 @@ export default function useAskAnswerMode(conversationId?: string | null) {setSelected,checked,toggleChecked,+ answerText,+ setAnswerText,canSubmit,submit,submitOption,diff --git a/client/src/hooks/SSE/__tests__/useAttachmentHandler.spec.tsx b/client/src/hooks/SSE/__tests__/useAttachmentHandler.spec.tsxindex a23abe41fa..c51f783b99 100644--- a/client/src/hooks/SSE/__tests__/useAttachmentHandler.spec.tsx+++ b/client/src/hooks/SSE/__tests__/useAttachmentHandler.spec.tsx@@ -127,23 +127,84 @@ describe('useAttachmentHandler upsert-by-file_id', () => {]);});- it('appends (does NOT merge) attachments with no file_id', () => {- /* Lightweight attachments like file_search citations and web_search- * results don't carry file_id. The handler must keep its legacy- * append behavior for them — merging would lose distinct citations- * and is unnecessary because they're never the target of a- * deferred preview update. */+ it('appends (does NOT merge) citation attachments with no file_id', () => {+ /* Lightweight attachments like file_search citations don't carry file_id.+ * The handler must keep its legacy append behavior for them: merging+ * would lose distinct citations and is unnecessary because they're never+ * the target of a deferred preview update. */const ctx = setup();const noFileId = {messageId,toolCallId: 'tc-1',- type: Tools.web_search,+ type: Tools.file_search,} as unknown as TAttachment;ctx.handle(noFileId);ctx.handle(noFileId);expect(ctx.list).toHaveLength(2);});+ it('replaces a re-emitted web-search snapshot instead of stacking it', () => {+ /* The search helper rewrites and re-emits the WHOLE payload after every+ * highlight update, keeping the same toolCallId and turn. Appending those+ * stacked one copy of every image, product and place per update. */+ const ctx = setup();+ const snapshot = (processed: boolean) =>+ ({+ messageId,+ toolCallId: 'tc-1',+ type: Tools.web_search,+ [Tools.web_search]: { turn: 0, organic: [{ link: 'https://example.com', processed }] },+ }) as unknown as TAttachment;++ ctx.handle(snapshot(false));+ ctx.handle(snapshot(true));++ expect(ctx.list).toHaveLength(1);+ expect(+ (ctx.list[0] as unknown as { web_search: { organic: Array<{ processed: boolean }> } })+ .web_search.organic[0].processed,+ ).toBe(true);+ });++ it('keeps web-search snapshots from distinct tool calls separate', () => {+ const ctx = setup();+ const snapshot = (toolCallId: string) =>+ ({+ messageId,+ toolCallId,+ type: Tools.web_search,+ [Tools.web_search]: { turn: 0 },+ }) as unknown as TAttachment;++ ctx.handle(snapshot('tc-1'));+ ctx.handle(snapshot('tc-2'));++ expect(ctx.list).toHaveLength(2);+ });++ it('keeps same-agent executions separate when provider id and turn repeat', () => {+ const ctx = setup();+ const snapshot = (stepId: string, link: string) =>+ ({+ messageId,+ toolCallId: 'call_0',+ agentId: 'agent-a',+ stepId,+ type: Tools.web_search,+ [Tools.web_search]: { turn: 0, organic: [{ link }] },+ }) as unknown as TAttachment;++ ctx.handle(snapshot('step-1', 'https://first.example'));+ ctx.handle(snapshot('step-2', 'https://second.example'));+ ctx.handle(snapshot('step-1', 'https://first-updated.example'));++ expect(ctx.list).toHaveLength(2);+ expect(ctx.list.map((attachment) => attachment[Tools.web_search]?.organic?.[0]?.link)).toEqual([+ 'https://first-updated.example',+ 'https://second.example',+ ]);+ });+it('keeps sibling tool calls separate when they share a file_id (distinct toolCallIds)', () => {/* Two background code calls regenerated the same filename — same* claimed file_id, different toolCallId. Each card anchors its owndiff --git a/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts b/client/src/hooks/SSE/__tests__/useStepHandler.spec.tsindex a7a69357b2..8951a04b80 100644--- a/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts+++ b/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts@@ -2711,7 +2711,7 @@ describe('useStepHandler', () => {expect(summaryPart).toMatchObject({ summarizing: false });});- it('ON_SUMMARIZE_COMPLETE error removes summarizing parts', () => {+ it('ON_SUMMARIZE_COMPLETE error finalizes the part in place without splicing it out', () => {mockLastAnnouncementTimeRef.current = Date.now();const responseMessage = createResponseMessage();mockGetMessages.mockReturnValue([responseMessage]);@@ -2782,11 +2782,21 @@ describe('useStepHandler', () => {expect(mockSetMessages).toHaveBeenCalled();const lastCall = mockSetMessages.mock.calls[mockSetMessages.mock.calls.length - 1][0];const responseMsg = lastCall.find((m: TMessage) => m.messageId === 'response-msg-1');+ /**+ * Failed rounds must keep their slot: splicing shifts every later part+ * under the index-keyed renderer and breaks the position == step-index+ * invariant that updateContent writes rely on. The part is finalized in+ * place with its streamed content preserved.+ */const summaryParts =responseMsg?.content?.filter((c: TMessageContentParts) => c.type === ContentTypes.SUMMARY,) ?? [];- expect(summaryParts).toHaveLength(0);+ expect(summaryParts).toHaveLength(1);+ expect((summaryParts[0] as SummaryContentPart).summarizing).toBe(false);+ expect((summaryParts[0] as SummaryContentPart).content).toEqual([+ { type: ContentTypes.TEXT, text: 'partial' },+ ]);});it('ON_SUMMARIZE_COMPLETE returns early when target message not in messageMap', () => {diff --git a/client/src/hooks/SSE/useAttachmentHandler.ts b/client/src/hooks/SSE/useAttachmentHandler.tsindex 2431fcb96a..5eb218d43c 100644--- a/client/src/hooks/SSE/useAttachmentHandler.ts+++ b/client/src/hooks/SSE/useAttachmentHandler.ts@@ -10,6 +10,25 @@ import type { QueryClient } from '@tanstack/react-query';import { handleMemoryArtifact } from '~/utils/memory';import store from '~/store';+/** Identity of a re-emitted web-search snapshot: its tool call, turn, agent,+ * and host step. Scoped to `web_search` because that is the flow whose server+ * helper rebuilds and rewrites the whole payload on each highlight. The+ * provider reuses ids such as `call_0` across turns and the host can reuse a+ * turn number within one message, so the SDK step is part of the identity. */+const searchSnapshotKeyOf = (attachment: TAttachment): string | undefined => {+ if (attachment.type !== Tools.web_search) {+ return undefined;+ }+ const toolCallId = (attachment as { toolCallId?: string }).toolCallId;+ if (!toolCallId) {+ return undefined;+ }+ const agentId = (attachment as { agentId?: string }).agentId ?? '';+ const turn = attachment[Tools.web_search]?.turn;+ const stepId = attachment.stepId ?? '';+ return `${Tools.web_search}:${agentId}:${toolCallId}:${turn ?? 0}:${stepId}`;+};+export default function useAttachmentHandler(queryClient?: QueryClient) {const setAttachmentsMap = useSetRecoilState(store.messageAttachmentsMap);@@ -141,6 +160,24 @@ export default function useAttachmentHandler(queryClient?: QueryClient) {return { ...prevMap, [messageId]: merged };}}+ /** Search attachments are full snapshots rather than deltas: the server+ * re-emits the entire payload after every highlight update, keeping the+ * same type, toolCallId and turn. They carry no `file_id`, so the upsert+ * above never saw them and each snapshot was appended, stacking one copy+ * of every image, product and place per update. Replace the previous+ * snapshot in place; a wholesale swap is right because the incoming+ * payload is complete. */+ const searchSnapshotKey = searchSnapshotKeyOf(data);+ if (searchSnapshotKey) {+ const existingIndex = messageAttachments.findIndex(+ (a) => searchSnapshotKeyOf(a) === searchSnapshotKey,+ );+ if (existingIndex > -1) {+ const merged = [...messageAttachments];+ merged[existingIndex] = data;+ return { ...prevMap, [messageId]: merged };+ }+ }return {...prevMap,[messageId]: [...messageAttachments, data],diff --git a/client/src/hooks/SSE/useStepHandler.ts b/client/src/hooks/SSE/useStepHandler.tsindex 27e727ad8f..78f6894e09 100644--- a/client/src/hooks/SSE/useStepHandler.ts+++ b/client/src/hooks/SSE/useStepHandler.ts@@ -1439,37 +1439,52 @@ export default function useStepHandler({return;}- if (completeData.error) {- const filtered = targetMessage.content.filter(- (part) =>- part?.type !== ContentTypes.SUMMARY || !(part as SummaryContentPart).summarizing,- );- if (filtered.length !== targetMessage.content.length) {- announcePolite({ message: 'summarize_failed', isStatus: true });- const cleaned = { ...targetMessage, content: filtered };- const currentMessages = submission.isRegenerate ? messages : getMessages() || [];- messageMap.current.set(completeMessageId, cleaned);- setMessages(mergeResponseMessage(currentMessages, cleaned, completeMessageId));+ /**+ * Scoped to the owning step's slot when the step is known: a global+ * scan finalizes a NEWER round's in-flight part when summarize+ * cycles run back-to-back (tiny context windows re-trigger+ * summarization every graph step). Unknown step falls back to+ * finalizing every in-flight part.+ */+ const completeIndex =+ completeRunStep != null ? completeRunStep.index + editPrefixOffset : -1;+ let didFinalize = false;+ const updatedContent = targetMessage.content.map((part, index) => {+ if (part?.type !== ContentTypes.SUMMARY || !(part as SummaryContentPart).summarizing) {+ return part;}- } else {- let didFinalize = false;- const updatedContent = targetMessage.content.map((part) => {- if (part?.type === ContentTypes.SUMMARY && (part as SummaryContentPart).summarizing) {- didFinalize = true;- if (!completeData.summary) {- return { ...part, summarizing: false } as SummaryContentPart;- }- return { ...completeData.summary, summarizing: false } as SummaryContentPart;- }+ if (completeIndex >= 0 && index !== completeIndex) {return part;- });- if (didFinalize) {- announcePolite({ message: 'summarize_completed', isStatus: true });- const finalized = { ...targetMessage, content: updatedContent };- const currentMessages = submission.isRegenerate ? messages : getMessages() || [];- messageMap.current.set(completeMessageId, finalized);- setMessages(mergeResponseMessage(currentMessages, finalized, completeMessageId));}+ didFinalize = true;+ if (!completeData.error && completeData.summary) {+ return { ...completeData.summary, summarizing: false } as SummaryContentPart;+ }+ /**+ * Failed rounds keep their slot. Splicing the part out shifts every+ * later part under the index-keyed renderer (remounting rows and+ * collapsing whatever the user expanded mid-stream) and breaks the+ * content-position == step-index invariant that `updateContent`+ * writes rely on. Flipping the flag alone hides an empty row+ * (`Summary` renders null without text) and matches the persisted+ * message, which retains the part server-side. An errored round+ * carries `failed` so partial deltas that already streamed in are+ * not presented as a completed summary.+ */+ if (completeData.error) {+ return { ...part, summarizing: false, failed: true } as SummaryContentPart;+ }+ return { ...part, summarizing: false } as SummaryContentPart;+ });+ if (didFinalize) {+ announcePolite({+ message: completeData.error ? 'summarize_failed' : 'summarize_completed',+ isStatus: true,+ });+ const finalized = { ...targetMessage, content: updatedContent };+ const currentMessages = submission.isRegenerate ? messages : getMessages() || [];+ messageMap.current.set(completeMessageId, finalized);+ setMessages(mergeResponseMessage(currentMessages, finalized, completeMessageId));}} else {const _exhaustive: never = stepEvent;diff --git a/client/src/hooks/useKeyboardShortcuts.spec.tsx b/client/src/hooks/useKeyboardShortcuts.spec.tsxindex ae9c70f0c8..4155e92dd1 100644--- a/client/src/hooks/useKeyboardShortcuts.spec.tsx+++ b/client/src/hooks/useKeyboardShortcuts.spec.tsx@@ -29,6 +29,7 @@ jest.mock('./useNewConvo', () => ({const STORAGE_KEY = 'customKeyboardShortcuts';const copyMock = copy as jest.MockedFunction<typeof copy>;+let queryClient: QueryClient;function buildConversation(conversationId: string, title: string): TConversation {return { conversationId, title, endpoint: 'agents' } as TConversation;@@ -67,7 +68,7 @@ function renderHarness(};return render(<Harness />, {wrapper: ({ children }: { children: ReactNode }) => (- <QueryClientProvider client={new QueryClient()}>+ <QueryClientProvider client={queryClient}><RecoilRoot initializeState={initializeState}><MemoryRouter initialEntries={[route]}>{children}</MemoryRouter></RecoilRoot>@@ -77,12 +78,14 @@ function renderHarness(}beforeEach(() => {+ queryClient = new QueryClient();window.localStorage.clear();copyMock.mockClear();});afterEach(() => {cleanup();+ queryClient.clear();document.body.replaceChildren();});diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 93d4245365..9e3b9356fd 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -378,6 +378,8 @@"com_error_expired_user_key": "Provided key for {{0}} expired at {{1}}. Please provide a new key and try again.","com_error_files_dupe": "Duplicate file detected.","com_error_files_empty": "Empty files are not allowed.",+ "com_error_context_tokens_detail": "Your messages need {{0}} tokens, but only {{1}} are available.",+ "com_error_empty_messages": "Your messages do not fit in the current context window, so there was nothing left to send to the model. Increase the max context size from the conversation parameters, shorten your message, or start a new conversation.","com_error_files_process": "An error occurred while processing the file.","com_error_files_skipped_dupe": "Skipped duplicate file(s): {{0}}","com_error_files_skipped_size": "Skipped file(s) over the {{0}} MB size limit: {{1}}",@@ -386,6 +388,7 @@"com_error_files_upload_canceled": "The file upload request was canceled. Note: the file upload may still be processing and will need to be manually deleted.","com_error_files_upload_too_large": "The file is too large. Please upload a file smaller than {{0}} MB","com_error_files_validation": "An error occurred while validating the file.",+ "com_error_final_context_overflow": "The request exceeds the current context window and could not be reduced to fit. Increase the max context size from the conversation parameters or shorten your message.","com_error_google_tool_conflict": "Usage of built-in Google tools are not supported with external tools. Please disable either the built-in tools or the external tools.","com_error_google_video_unprocessable": "The linked video could not be processed. It is most likely too long for this model, but it may also be unavailable in this region or restricted. Try a shorter video, or describe the relevant parts in your message instead.","com_error_heic_conversion": "Failed to convert HEIC image to JPEG. Please try converting the image manually or use a different format.",@@ -916,12 +919,16 @@"com_ui_artifacts_subtext": "Lets the agent render React, HTML, SVG, Markdown, and Mermaid as interactive artifacts in a side panel instead of plain code blocks.","com_ui_ascending": "Asc","com_ui_ask_answer_error": "Your answer couldn't be sent. Try again.",+ "com_ui_ask_move_to_chat": "Answer later in the chat",+ "com_ui_ask_move_to_composer": "Answer from the message box","com_ui_ask_type_below": "Or type your answer below","com_ui_ask_type_below_only": "Type your answer below","com_ui_ask_user": "Ask User","com_ui_asked": "Asked",+ "com_ui_asked_one_question": "Asked 1 question","com_ui_asked_n_questions": "Asked {{0}} questions","com_ui_asking": "Asking",+ "com_ui_asking_one_question": "Asking 1 question","com_ui_asking_n_questions": "Asking {{0}} questions","com_ui_assistant": "Assistant","com_ui_assistant_delete_error": "There was an error deleting the assistant",@@ -1190,6 +1197,7 @@"com_ui_description_placeholder": "Optional: Enter a description to display for the prompt","com_ui_detailed": "Detailed","com_ui_details": "Details",+ "com_ui_diff_stats": "{{0}} additions, {{1}} deletions","com_ui_disabled": "Disabled","com_ui_disabling": "Disabling...","com_ui_dismiss": "Dismiss",@@ -1398,6 +1406,8 @@"com_ui_greeting_working_on": "What are we working on?","com_ui_greeting_working_on_named": "What are we working on, {{name}}?","com_ui_group": "Group",+ "com_ui_handoff_field_context": "Context",+ "com_ui_handoff_field_instructions": "Instructions","com_ui_handoff_instructions": "Handoff instructions","com_ui_happy_birthday": "It's my 1st birthday!","com_ui_header_format": "Header Format",@@ -1579,14 +1589,16 @@"com_ui_memory_already_exceeded": "Memory storage already full - exceeded by {{tokens}} tokens. Delete existing memories before adding new ones.","com_ui_memory_created": "Memory created successfully","com_ui_memory_deleted": "Memory deleted",- "com_ui_memory_deleted_items": "Deleted Memories",+ "com_ui_memory_deleting": "Deleting memory","com_ui_memory_error": "Memory Error","com_ui_memory_key_exists": "A memory with this key already exists. Please use a different key.","com_ui_memory_key_hint": "Use lowercase letters and underscores only","com_ui_memory_key_validation": "Memory key must only contain lowercase letters and underscores.",+ "com_ui_memory_removed": "Deleted memory",+ "com_ui_memory_saved": "Saved memory",+ "com_ui_memory_saving": "Saving memory","com_ui_memory_storage_full": "Memory Storage Full","com_ui_memory_updated": "Updated saved memory",- "com_ui_memory_updated_items": "Updated Memories","com_ui_memory_would_exceed": "Cannot save - would exceed limit by {{tokens}} tokens. Delete existing memories to make space.","com_ui_mention": "Mention an endpoint, assistant, or preset to quickly switch to it","com_ui_mermaid": "mermaid",@@ -1619,8 +1631,11 @@"com_ui_more_options": "More options","com_ui_my_prompts": "My Prompts","com_ui_my_skills": "My Skills",+ "com_ui_n_actions_cancelled": "{{0}} cancelled",+ "com_ui_n_actions_failed": "{{0}} failed","com_ui_n_files": "{{0}} files","com_ui_n_files_changed": "{{0}} files changed",+ "com_ui_n_searches": "{{0}} searches","com_ui_name": "Name","com_ui_name_sort": "Sort by Name","com_ui_navigate_results": "Navigate results",@@ -1687,6 +1702,8 @@"com_ui_omitted": "Omitted","com_ui_on": "On","com_ui_one_file_changed": "1 file changed",+ "com_ui_one_action_cancelled": "1 cancelled",+ "com_ui_one_action_failed": "1 failed","com_ui_open_archived_chat_new_tab_title": "{{title}} (opens in new tab)","com_ui_open_artifact": "Open artifact","com_ui_open_as_artifact": "Open as artifact",@@ -1805,6 +1822,7 @@"com_ui_queued_turn_reconciliation_required": "Awaiting reconciliation","com_ui_quote_selections": "{{0}} selections","com_ui_quotes_queued": "Quotes added for your next message",+ "com_ui_ran_n_actions": "Ran {{0}} actions","com_ui_ran_n_agents": "Ran {{0}} agents","com_ui_read_aloud": "Read aloud","com_ui_read_file": "Read {{0}}",@@ -1891,6 +1909,7 @@"com_ui_run_code_error": "There was an error running the code","com_ui_running": "Running...","com_ui_running_command": "Running command",+ "com_ui_running_n_actions": "Running {{0}} actions","com_ui_running_n_agents": "Running {{0}} agents","com_ui_sandbox_starting": "Starting sandbox environment","com_ui_save": "Save",@@ -1974,12 +1993,15 @@"com_ui_search_language": "Search languages...","com_ui_search_people_placeholder": "Search for people or groups by name or email","com_ui_search_projects": "Search projects",+ "com_ui_search_query": "Query","com_ui_search_result_count": "{{count}} result found","com_ui_search_results_count": "{{count}} results found","com_ui_search_skills": "Search skills...","com_ui_search_table": "Search table","com_ui_search_table_description": "Type to filter results",+ "com_ui_searched_web_and_files": "Searched web and files","com_ui_searching_files": "Searching your files",+ "com_ui_searching_web_and_files": "Searching web and files","com_ui_seconds": "seconds","com_ui_secret_key": "Secret Key","com_ui_select": "Select",@@ -2102,7 +2124,7 @@"com_ui_skill_file_binary": "Binary file — cannot preview inline","com_ui_skill_file_download": "Download","com_ui_skill_file_load_error": "Failed to load file content",- "com_ui_skill_finished": "Ran {{0}}",+ "com_ui_skill_finished": "Loaded {{0}}","com_ui_skill_instructions": "Instructions","com_ui_skill_instructions_placeholder": "Enter your skill instructions in markdown...","com_ui_skill_name_invalid": "Use lowercase letters, digits, and dashes only (kebab-case)",@@ -2124,7 +2146,7 @@"com_ui_skill_role_editor_desc": "Can view and edit the skill","com_ui_skill_role_owner_desc": "Full control over the skill including sharing and deletion","com_ui_skill_role_viewer_desc": "Can view and use the skill but cannot edit it",- "com_ui_skill_running": "Running {{0}}",+ "com_ui_skill_running": "Loading {{0}}","com_ui_skill_sr_public": "Public skill","com_ui_skill_states_limit": "You've reached the limit of {{0}} active/inactive skill overrides. Remove some overrides to toggle new skills.","com_ui_skill_unavailable": "Unavailable skill",@@ -2279,7 +2301,7 @@"com_ui_subagent_count_cancelled_one": "{{0}} cancelled","com_ui_subagent_count_cancelled_other": "{{0}} cancelled","com_ui_subagent_actor": "Agent",- "com_ui_subagent_cancelled": "Cancelled agent",+ "com_ui_subagent_cancelled": "Agent stopped","com_ui_subagent_complete": "Ran agent","com_ui_subagent_dialog_title": "\"{{0}}\" agent","com_ui_subagent_dialog_title_self": "Agent",@@ -2317,7 +2339,7 @@"com_ui_subagent_control_withdraw": "Withdraw","com_ui_subagent_interrupt": "Interrupt","com_ui_subagent_empty_result": "No text returned.",- "com_ui_subagent_errored": "Agent errored",+ "com_ui_subagent_errored": "Agent failed","com_ui_subagent_no_result_yet": "Still running — no final result yet.","com_ui_subagent_thread_history_truncated": "Some earlier activity is unavailable.","com_ui_subagent_thread_load_error": "The agent activity could not be loaded.",@@ -2341,10 +2363,11 @@"com_ui_subagent_ticker_tool_done": "done","com_ui_subagent_ticker_using": "Using","com_ui_subagent_ticker_writing": "Writing",- "com_ui_subagent_waiting": "Waiting for first update…",+ "com_ui_subagent_waiting": "Working…","com_ui_submit": "Submit","com_ui_submit_decisions": "Submit {{0}} decisions","com_ui_submitting": "Submitting…",+ "com_ui_summarize_failed": "Summarization failed","com_ui_summarized": "Summarized","com_ui_summarizing": "Summarizing...","com_ui_support_contact": "Support Contact",@@ -2384,9 +2407,14 @@"com_ui_tool_name_ask_user_question": "Question","com_ui_tool_name_code": "Code","com_ui_tool_name_code_analysis": "Code Analysis",+ "com_ui_tool_name_create_file": "Create File",+ "com_ui_tool_name_delete_memory": "Delete Memory",+ "com_ui_tool_name_edit_file": "Edit File","com_ui_tool_name_file_search": "File Search","com_ui_tool_name_image_edit": "Image Edit",+ "com_ui_tool_name_read_file": "Read File","com_ui_tool_name_image_gen": "Image Generation",+ "com_ui_tool_name_set_memory": "Save Memory","com_ui_tool_name_web_search": "Web Search","com_ui_tool_response_placeholder": "Type a substitute result to return to the agent","com_ui_tools": "Tools",@@ -2482,7 +2510,7 @@"com_ui_use_micrphone": "Use microphone","com_ui_use_prompt": "Use Prompt","com_ui_used": "Used",- "com_ui_used_n_tools": "Used {{0}} tools",+ "com_ui_used_one_tool": "Used 1 tool","com_ui_user": "User","com_ui_user_group_permissions": "User & Group Permissions","com_ui_user_provides_key": "Each user provides their own key",@@ -2536,6 +2564,10 @@"com_ui_web_search_scraper_tavily_key": "Get your Tavily API key","com_ui_web_search_searxng_api_key": "Enter SearXNG API Key (optional)","com_ui_web_search_searxng_instance_url": "SearXNG Instance URL",+ "com_ui_web_search_details": "Search details",+ "com_ui_web_search_images": "Image results",+ "com_ui_web_search_places": "Places",+ "com_ui_web_search_shopping": "Shopping results","com_ui_web_search_source": "{{count}} source","com_ui_web_search_sources": "{{count}} sources","com_ui_web_searched": "Searched the web",diff --git a/client/src/style.css b/client/src/style.cssindex d877c5bb8b..281578894b 100644--- a/client/src/style.css+++ b/client/src/style.css@@ -2676,3 +2676,17 @@ html[data-input-modality='keyboard'].sharepoint-picker-bg {background-color: rgb(var(--surface-dialog));}++/* ask_user_question popover <-> chat-card morph (view transition) */+::view-transition-group(ask-question),+::view-transition-old(ask-question),+::view-transition-new(ask-question) {+ animation-duration: 280ms;+ animation-timing-function: cubic-bezier(0.32, 0.72, 0.22, 1);+}++/* The composer keeps its own snapshot group stacked above the morphing+ question card, so the card travels behind the ChatForm, not over it. */+::view-transition-group(chat-form) {+ z-index: 2;+}diff --git a/client/src/utils/__tests__/groupToolCalls.test.ts b/client/src/utils/__tests__/groupToolCalls.test.tsindex 2c02356600..40012b8a7a 100644--- a/client/src/utils/__tests__/groupToolCalls.test.ts+++ b/client/src/utils/__tests__/groupToolCalls.test.ts@@ -22,26 +22,33 @@ const label = (text: string): TMessageContentParts =>pending: text.length === 0,}) as unknown as TMessageContentParts;+const textPart = (text = 'answer'): TMessageContentParts =>+ ({ type: ContentTypes.TEXT, text }) as unknown as TMessageContentParts;++const transferPart = (): TMessageContentParts =>+ ({+ type: ContentTypes.TOOL_CALL,+ [ContentTypes.TOOL_CALL]: { id: 'x', name: 'lc_transfer_to_agent', args: '{}' },+ }) as unknown as TMessageContentParts;+const withIndex = (parts: TMessageContentParts[]): PartWithIndex[] =>parts.map((part, idx) => ({ part, idx }));describe('groupSequentialToolCalls with activity labels', () => {/*** Every batch publishes its reservation the moment the batch ends, so an- * empty label is the NORMAL state while generation is in flight. It must- * render exactly as the feature-off path does: a lone tool call stays a- * single (no group wrapper) and THINK parts stay standalone.+ * empty label is the NORMAL state while generation is in flight. Reasoning+ * folds into the run either way, so a lone tool call with its thinking+ * still groups, just without a labelPart.*/- it('leaves a single tool call and its reasoning untouched while the label is empty', () => {+ it('groups a single tool call with its reasoning while the label is empty', () => {const grouped = groupSequentialToolCalls(withIndex([think('deciding what to search'), toolCall('t1'), label('')]),);- expect(grouped).toHaveLength(2);- expect(grouped[0]).toMatchObject({ type: 'single' });- expect(grouped[1]).toMatchObject({ type: 'single' });- /** No labelPart anywhere, and crucially no 'tool-group' wrapper. */- expect(grouped.some((entry) => entry.type === 'tool-group')).toBe(false);+ expect(grouped).toHaveLength(1);+ expect(grouped[0]).toMatchObject({ type: 'tool-group' });+ expect((grouped[0] as { labelPart?: PartWithIndex }).labelPart).toBeUndefined();});/** A blank/failed fill is permanent, and must stay equally invisible. */@@ -198,3 +205,105 @@ describe('groupSequentialToolCalls with activity labels', () => {});});});++describe('groupSequentialToolCalls reasoning transparency', () => {+ it('groups two adjacent tool calls', () => {+ const result = groupSequentialToolCalls(withIndex([toolCall('a'), toolCall('b')]));+ expect(result).toHaveLength(1);+ expect(result[0]).toMatchObject({ type: 'tool-group' });+ expect(result[0].type === 'tool-group' && result[0].parts).toHaveLength(2);+ });++ it('keeps a single tool call ungrouped', () => {+ const result = groupSequentialToolCalls(withIndex([toolCall('a')]));+ expect(result).toEqual([{ type: 'single', part: { part: expect.anything(), idx: 0 } }]);+ });++ it('absorbs reasoning interleaved between tool calls into one group', () => {+ const result = groupSequentialToolCalls(+ withIndex([toolCall('a'), think('mid'), toolCall('b')]),+ );+ expect(result).toHaveLength(1);+ expect(result[0].type).toBe('tool-group');+ expect(result[0].type === 'tool-group' && result[0].parts.map((p) => p.idx)).toEqual([0, 1, 2]);+ });++ it('absorbs leading and trailing reasoning around a tool run', () => {+ const result = groupSequentialToolCalls(+ withIndex([think('lead'), toolCall('a'), toolCall('b'), think('trail')]),+ );+ expect(result).toHaveLength(1);+ expect(result[0].type).toBe('tool-group');+ expect(result[0].type === 'tool-group' && result[0].parts).toHaveLength(4);+ });++ it('groups a lone tool call wrapped in reasoning', () => {+ const result = groupSequentialToolCalls(+ withIndex([think('lead'), toolCall('a'), think('trail')]),+ );+ expect(result).toHaveLength(1);+ expect(result[0].type).toBe('tool-group');+ expect(result[0].type === 'tool-group' && result[0].parts.map((p) => p.idx)).toEqual([0, 1, 2]);+ });++ it('keeps a lone tool call without reasoning inline', () => {+ const result = groupSequentialToolCalls(withIndex([toolCall('a'), textPart()]));+ expect(result.map((g) => g.type)).toEqual(['single', 'single']);+ });++ it('keeps pure reasoning (no tool call) standalone', () => {+ const result = groupSequentialToolCalls(withIndex([think('only'), textPart()]));+ expect(result.map((g) => g.type)).toEqual(['single', 'single']);+ });++ it('does not pull a thought-then-answer tail into a preceding group', () => {+ const result = groupSequentialToolCalls(+ withIndex([toolCall('a'), toolCall('b'), textPart(), think('tail'), textPart('final')]),+ );+ expect(result.map((g) => g.type)).toEqual(['tool-group', 'single', 'single', 'single']);+ });++ it('splits tool runs separated by a non-reasoning part', () => {+ const result = groupSequentialToolCalls(+ withIndex([toolCall('a'), toolCall('b'), textPart(), toolCall('c'), toolCall('d')]),+ );+ expect(result.map((g) => g.type)).toEqual(['tool-group', 'single', 'tool-group']);+ });++ /** An unlabeled group auto-collapses once complete, so commentary folded+ * into it would hide the assistant's prose behind a generic action+ * header. Reasoning still folds in; only commentary splits the run. */+ it('keeps unlabeled commentary out of the collapsing tool group', () => {+ const result = groupSequentialToolCalls(+ withIndex([+ toolCall('a'),+ toolCall('b'),+ text('here is what I found so far', 'commentary'),+ toolCall('c'),+ toolCall('d'),+ label(''),+ ]),+ );+ expect(result.map((g) => g.type)).toEqual(['tool-group', 'single', 'tool-group']);+ });++ it('still folds reasoning into a run that commentary split', () => {+ const result = groupSequentialToolCalls(+ withIndex([+ think('deciding'),+ toolCall('a'),+ text('a note mid-run', 'commentary'),+ think('reconsidering'),+ toolCall('b'),+ label(''),+ ]),+ );++ expect(result.map((g) => g.type)).toEqual(['tool-group', 'single', 'tool-group']);+ });++ it('does not group transfer/handoff tool calls', () => {+ const result = groupSequentialToolCalls(withIndex([transferPart(), transferPart()]));+ expect(result.map((g) => g.type)).toEqual(['single', 'single']);+ });+});diff --git a/client/src/utils/__tests__/toolLabels.test.ts b/client/src/utils/__tests__/toolLabels.test.tsindex b22413395e..e0d1f9ee44 100644--- a/client/src/utils/__tests__/toolLabels.test.ts+++ b/client/src/utils/__tests__/toolLabels.test.ts@@ -74,6 +74,10 @@ describe('getToolDisplayLabel', () => {);});+ it.each(['set_memory', 'delete_memory'])('returns a friendly memory label for %s', (toolName) => {+ expect(getToolDisplayLabel(toolName, identityLocalize)).toBe(TOOL_FRIENDLY_NAME_KEYS[toolName]);+ });+it('returns the raw name for an unknown native tool', () => {expect(getToolDisplayLabel('custom_tool', identityLocalize)).toBe('custom_tool');});diff --git a/client/src/utils/groupToolCalls.ts b/client/src/utils/groupToolCalls.tsindex f924a84a9e..ec5d85fb37 100644--- a/client/src/utils/groupToolCalls.ts+++ b/client/src/utils/groupToolCalls.ts@@ -50,6 +50,36 @@ function isGroupableToolCall(part: TMessageContentParts): boolean {return true;}+/** Reasoning ("Thoughts") parts are transparent to grouping: a thought+ * interleaved between tool calls joins the run instead of splitting it, so+ * reasoning models that think between every call still collapse into a single+ * tool group. A run becomes a group once it holds >= 2 tool calls, OR a single+ * tool call accompanied by reasoning, so a lone tool wrapped in thinking+ * (a skill invocation, say) still gets the grouped chrome with its thoughts+ * folded in. A run of pure reasoning (no tool call) keeps rendering as its own+ * standalone card. */+function isReasoningPart(part: TMessageContentParts): boolean {+ return part.type === ContentTypes.THINK;+}++/** Assistant prose emitted mid-run. Grouping treats it as block-joining so a+ * labeled batch can still claim the tools around it, but an UNLABELED group+ * must never swallow it: that group auto-collapses once complete, which would+ * hide the prose behind a generic action header. */+function isCommentaryPart(part: TMessageContentParts): boolean {+ return part.type === ContentTypes.TEXT && (part as { phase?: string }).phase === 'commentary';+}++function countToolCalls(parts: PartWithIndex[]): number {+ let count = 0;+ for (const { part } of parts) {+ if (isGroupableToolCall(part)) {+ count += 1;+ }+ }+ return count;+}+/*** True when the label covers ANY `transfer_to_*` handoff call. Transfer* parts are never groupable, so the flush at the handoff card leaves such a@@ -83,10 +113,9 @@ function coversTransferCall(labelPart: TMessageContentParts, allParts: PartWithI* calls) becomes one labeled group — the claude.ai-style hierarchy. Any* other part type breaks the block.*- * Legacy behavior is preserved exactly when no ACTIVITY_LABEL part arrives- * (feature off, older conversations): the tentative block is re-split so- * THINK parts render standalone in their original positions and only runs- * of >= 2 tool calls group.+ * Without an ACTIVITY_LABEL part (feature off, older conversations), the+ * block still groups: reasoning stays folded in with its tool calls, and a+ * run groups at >= 2 tool calls or a single call accompanied by reasoning.*/export function groupSequentialToolCalls(parts: PartWithIndex[]): GroupedPart[] {const result: GroupedPart[] = [];@@ -96,36 +125,42 @@ export function groupSequentialToolCalls(parts: PartWithIndex[]): GroupedPart[]* before it belongs to earlier batches whose labels stayed empty. */let claimStart = 0;+ /** Splits the block at commentary so an unlabeled group only ever holds+ * reasoning and tool calls; each surrounding run still has to earn the+ * grouped chrome on its own. */const flushWithoutLabel = () => {- let toolRun: PartWithIndex[] = [];- const flushToolRun = () => {- if (toolRun.length >= 2) {- result.push({ type: 'tool-group', parts: [...toolRun] });+ let run: PartWithIndex[] = [];+ const emitRun = () => {+ const toolCallCount = countToolCalls(run);+ const hasReasoning = run.some((p) => isReasoningPart(p.part));+ if (toolCallCount >= 2 || (toolCallCount >= 1 && hasReasoning)) {+ result.push({ type: 'tool-group', parts: run });} else {- for (const p of toolRun) {+ for (const p of run) {result.push({ type: 'single', part: p });}}- toolRun = [];+ run = [];};for (const p of currentBlock) {- if (isGroupableToolCall(p.part)) {- toolRun.push(p);- } else {- flushToolRun();+ if (isCommentaryPart(p.part)) {+ emitRun();result.push({ type: 'single', part: p });+ continue;}+ run.push(p);}- flushToolRun();+ emitRun();currentBlock = [];claimStart = 0;};for (const item of parts) {- const isCommentary =- item.part.type === ContentTypes.TEXT &&- (item.part as { phase?: string }).phase === 'commentary';- if (isGroupableToolCall(item.part) || item.part.type === ContentTypes.THINK || isCommentary) {+ if (+ isGroupableToolCall(item.part) ||+ item.part.type === ContentTypes.THINK ||+ isCommentaryPart(item.part)+ ) {currentBlock.push(item);continue;}diff --git a/client/src/utils/index.ts b/client/src/utils/index.tsindex e173bdb5f2..cc2ddd1ae7 100644--- a/client/src/utils/index.ts+++ b/client/src/utils/index.ts@@ -14,6 +14,7 @@ export * from './media';export * from './greeting';export * from './latex';export * from './tilde';+export * from './morph';export * from './forms';export * from './roles';export * from './errors';diff --git a/client/src/utils/morph.ts b/client/src/utils/morph.tsnew file mode 100644index 0000000000..8ffa2b4f08--- /dev/null+++ b/client/src/utils/morph.ts@@ -0,0 +1,21 @@+import { flushSync } from 'react-dom';++/**+ * Runs a state update inside a same-document view transition when supported,+ * so elements sharing a `view-transition-name` morph (position, size, shape)+ * between the two states instead of swapping. Falls back to applying the+ * update directly. Call from user-event handlers only: the update is flushed+ * synchronously so the browser can snapshot the old and new layouts.+ */+export function morphTransition(update: () => void): void {+ if (+ typeof document.startViewTransition !== 'function' ||+ window.matchMedia('(prefers-reduced-motion: reduce)').matches+ ) {+ update();+ return;+ }+ document.startViewTransition(() => {+ flushSync(update);+ });+}diff --git a/client/src/utils/toolLabels.ts b/client/src/utils/toolLabels.tsindex 58757b9ce8..d0dbe41c2a 100644--- a/client/src/utils/toolLabels.ts+++ b/client/src/utils/toolLabels.ts@@ -22,6 +22,12 @@ export const TOOL_FRIENDLY_NAME_KEYS: Record<string, TranslationKeys> = {code_interpreter: 'com_ui_tool_name_code_analysis',retrieval: 'com_ui_tool_name_file_search',ask_user_question: 'com_ui_tool_name_ask_user_question',+ create_file: 'com_ui_tool_name_create_file',+ set_memory: 'com_ui_tool_name_set_memory',+ edit_file: 'com_ui_tool_name_edit_file',+ delete_memory: 'com_ui_tool_name_delete_memory',+ skill: 'com_ui_skill',+ read_file: 'com_ui_tool_name_read_file',};export interface ParsedToolName {diff --git a/e2e/specs/mock/activity-labels.spec.ts b/e2e/specs/mock/activity-labels.spec.tsindex b447953cd0..b0096115ec 100644--- a/e2e/specs/mock/activity-labels.spec.ts+++ b/e2e/specs/mock/activity-labels.spec.ts@@ -82,7 +82,7 @@ test.describe('activity labels', () => {/*** The header is the feature: once a label lands it REPLACES the generic- * "Used N tools" verb above the same tool cards.+ * "Ran N actions" verb above the same tool cards.*/test('renders the generated label as the tool-group header', async ({ page, request }) => {test.setTimeout(120000);@@ -94,7 +94,7 @@ test.describe('activity labels', () => {await expect(messagesView(page).getByRole('button', { name: 'Stored two facts in memory' }),).toBeVisible({ timeout: 30000 });- await expect(messagesView(page).getByRole('button', { name: 'Used 2 tools' })).toHaveCount(0);+ await expect(messagesView(page).getByRole('button', { name: /^Ran 2 actions/ })).toHaveCount(0);});/**@@ -141,7 +141,7 @@ test.describe('activity labels', () => {/*** A whitespace-only label must fill null. There is deliberately no templated- * stand-in ("ran 2 tools" only restates the cards), so the block renders+ * stand-in ("Ran 2 actions" only restates the cards), so the block renders* exactly as it would without the feature.*/test('leaves the generic header when the model returns a blank label', async ({@@ -154,7 +154,7 @@ test.describe('activity labels', () => {await runLabeledTurn(page, label);- await expect(messagesView(page).getByRole('button', { name: 'Used 2 tools' })).toBeVisible({+ await expect(messagesView(page).getByRole('button', { name: /^Ran 2 actions/ })).toBeVisible({timeout: 30000,});});@@ -169,7 +169,7 @@ test.describe('activity labels', () => {/** The turn still finished (asserted in runLabeledTurn) and the block kept* its generic header rather than rendering an empty row. */- await expect(messagesView(page).getByRole('button', { name: 'Used 2 tools' })).toBeVisible({+ await expect(messagesView(page).getByRole('button', { name: /^Ran 2 actions/ })).toBeVisible({timeout: 30000,});/** At least one attempt was made and failed; the client may retry a 5xx,@@ -191,7 +191,7 @@ test.describe('activity labels', () => {timeout: 60000,});- await expect(messagesView(page).getByRole('button', { name: 'Used 2 tools' })).toBeVisible();+ await expect(messagesView(page).getByRole('button', { name: /^Ran 2 actions/ })).toBeVisible();expect(await getLabelRequestsFor(request, label)).toHaveLength(0);});diff --git a/e2e/specs/mock/agent-handoffs.spec.ts b/e2e/specs/mock/agent-handoffs.spec.tsindex df3cbe3208..00ac352a6c 100644--- a/e2e/specs/mock/agent-handoffs.spec.ts+++ b/e2e/specs/mock/agent-handoffs.spec.ts@@ -757,12 +757,11 @@ test.describe('agent handoffs', () => {});await expect(transferCard).toBeEnabled();await transferCard.click();- await expect(- messagesView(page).getByText('Handoff instructions:', { exact: true }),- ).toBeVisible();- await expect(- messagesView(page).getByText(JSON.stringify({ brief: payload }), { exact: true }),- ).toBeVisible();+ const handoffDetails = messagesView(page).getByRole('region', {+ name: 'Handoff instructions',+ });+ await expect(handoffDetails).toBeVisible();+ await expect(handoffDetails.getByText(payload, { exact: true })).toBeVisible();await expect(page).toHaveURL(/\/c\/(?!new)/, { timeout: 15000 });const conversationUrl = page.url();diff --git a/e2e/specs/mock/tool-approvals.spec.ts b/e2e/specs/mock/tool-approvals.spec.tsindex 21517fb4ea..f60c78f61e 100644--- a/e2e/specs/mock/tool-approvals.spec.ts+++ b/e2e/specs/mock/tool-approvals.spec.ts@@ -162,7 +162,7 @@ async function submitAndCapture(page: Page, submit: Locator) {async function expectCompletedApprovalToolOutput(page: Page, toolCallId: string, output: string) {const view = messagesView(page);- const groupToggle = view.getByRole('button', { name: /^Used \d+ tools$/ }).last();+ const groupToggle = view.getByRole('button', { name: /^Ran \d+ actions/ }).last();const toolCall = view.locator(`[data-testid="tool-call"][data-tool-call-id="${toolCallId}"]`);// On reload, the conversation arrives asynchronously and multi-tool groups@@ -511,8 +511,7 @@ test.describe('tool approvals', () => {await expect(submit).toBeEnabled();const groupToggle = messagesView(page).getByRole('button', {- name: 'Used 2 tools',- exact: true,+ name: /^Running 2 actions/,});const groupPanel = messagesView(page).getByTestId('tool-call-group-panel').last();await Promise.all([diff --git a/packages/api/src/agents/__tests__/run-summarization.test.ts b/packages/api/src/agents/__tests__/run-summarization.test.tsindex bfb9ab13cd..6d3e923f23 100644--- a/packages/api/src/agents/__tests__/run-summarization.test.ts+++ b/packages/api/src/agents/__tests__/run-summarization.test.ts@@ -648,6 +648,35 @@ describe('summarizationEnabled resolution', () => {expect(config.provider).toBe('openAI');expect(config.model).toBe('gpt-4o');});++ it('false when the effective context budget is below the viable minimum', async () => {+ /**+ * A tiny user-set maxContextTokens re-triggers summarization on every+ * graph step until the recursion limit aborts the run; the guard falls+ * back to plain pruning instead.+ */+ const agents = await callAndCapture({+ agents: [makeAgent({ maxContextTokens: 10 })],+ summarizationConfig: {+ enabled: true,+ provider: 'anthropic',+ model: 'claude-3-haiku',+ },+ });+ expect(agents[0].summarizationEnabled).toBe(false);+ });++ it('true at exactly the 1024-token viable minimum', async () => {+ const agents = await callAndCapture({+ agents: [makeAgent({ maxContextTokens: 1024 })],+ summarizationConfig: {+ enabled: true,+ provider: 'anthropic',+ model: 'claude-3-haiku',+ },+ });+ expect(agents[0].summarizationEnabled).toBe(true);+ });});// ---------------------------------------------------------------------------diff --git a/packages/api/src/agents/handlers.spec.ts b/packages/api/src/agents/handlers.spec.tsindex 447b0ac880..f3b1ca632c 100644--- a/packages/api/src/agents/handlers.spec.ts+++ b/packages/api/src/agents/handlers.spec.ts@@ -12,7 +12,11 @@ import type {} from '@librechat/agents';import type { PtcToolCallEvent } from 'librechat-data-provider';import type { CodeExecutionContext } from './execution';-import { createToolExecuteHandler, ToolExecuteOptions } from './handlers';+import {+ createOwnedToolEndHandler,+ createToolExecuteHandler,+ ToolExecuteOptions,+} from './handlers';import { markSandboxReady } from './prewarm';import { ContentFilterError } from '../middleware/contentFilter';import { WorkspaceToolHttpError } from '../code/workspace';@@ -124,6 +128,28 @@ function protectedToolOutputRequest() {} as never;}+describe('createOwnedToolEndHandler', () => {+ it('forwards the graph-owned step identity to the tool callback', async () => {+ const callback = jest.fn(async () => undefined);+ const handler = createOwnedToolEndHandler(callback as never, logger);+ const graph = {+ toolCallStepIds: new Map([['call_1', 'step-1']]),+ } as never;++ await handler.handle(+ 'on_tool_end',+ { output: { tool_call_id: 'call_1', content: 'ok' } } as never,+ { agent_id: 'agent-a' },+ graph,+ );++ expect(callback).toHaveBeenCalledWith(+ expect.anything(),+ expect.objectContaining({ agent_id: 'agent-a', stepId: 'step-1' }),+ );+ });+});+describe('createToolExecuteHandler', () => {describe('code execution session context passthrough', () => {it('passes session_id and _injected_files from codeSessionContext to toolCallConfig', async () => {diff --git a/packages/api/src/agents/handlers.ts b/packages/api/src/agents/handlers.tsindex 8e6cb93d16..b9110d1a1b 100644--- a/packages/api/src/agents/handlers.ts+++ b/packages/api/src/agents/handlers.ts@@ -1,6 +1,6 @@import yaml from 'js-yaml';import { Types } from 'mongoose';-import { GraphEvents, Constants } from '@librechat/agents';+import { GraphEvents, Constants, ToolEndHandler } from '@librechat/agents';import { logger, normalizeSkillFrontmatterKeys } from '@librechat/data-schemas';import { hasActivePiiFields, hasActivePiiPatterns } from 'librechat-data-provider';import type {@@ -14,6 +14,8 @@ import type {ToolExecuteBatchRequest,SubagentTaskConfig,CallerCapabilityProjectionSnapshot,+ StreamEventData,+ ToolEndCallback as SdkToolEndCallback,} from '@librechat/agents';import type { StructuredToolInterface } from '@librechat/agents/langchain/tools';import type { CodeEnvRef, PtcToolCallEvent } from 'librechat-data-provider';@@ -185,6 +187,35 @@ export type ToolEndCallback = (metadata: ToolEndCallbackMetadata,) => Promise<void>;+/**+ * Preserve the SDK's event-handler contract while attaching the graph-owned+ * step identity to legacy artifact callbacks. `toolCallStepIds` is populated+ * by ToolNode for the actual provider tool call; this wrapper never invents a+ * fallback identity.+ */+export function createOwnedToolEndHandler(+ callback: SdkToolEndCallback,+ loggerArg: typeof logger = logger,+): EventHandler {+ const toolEndHandler = new ToolEndHandler(callback, loggerArg);+ return {+ handle: async (event, data: StreamEventData, metadata, graph) => {+ const output = data?.output;+ const toolCallId =+ typeof output === 'object' && output != null+ ? (output as { tool_call_id?: unknown }).tool_call_id+ : undefined;+ const stepId =+ typeof toolCallId === 'string' ? graph?.toolCallStepIds?.get(toolCallId) : undefined;+ const ownedMetadata =+ typeof stepId === 'string' && stepId.length > 0+ ? { ...(metadata ?? {}), stepId }+ : metadata;+ return toolEndHandler.handle(event, data, ownedMetadata, graph);+ },+ };+}+export interface ToolExecuteOptions {/** Loads tools by name, using agentId to look up agent-specific context */loadTools: (@@ -6091,6 +6122,7 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand{...(metadata ?? {}),executingAgentId: agentId,+ stepId: tc.stepId,} as ToolEndCallbackMetadata,);} catch (callbackError) {@@ -6413,6 +6445,7 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand| undefined,...metadata,executingAgentId: agentId,+ stepId: tc.stepId,codeExecutionContext,},);@@ -6697,6 +6730,7 @@ export function createToolExecuteHandler(options: ToolExecuteOptions): EventHand| undefined,...metadata,executingAgentId: agentId,+ stepId: tc.stepId,codeExecutionContext,},);diff --git a/packages/api/src/agents/run.ts b/packages/api/src/agents/run.tsindex 77cff7a4e7..66bb4f4fca 100644--- a/packages/api/src/agents/run.ts+++ b/packages/api/src/agents/run.ts@@ -941,6 +941,18 @@ function shapeSummarizationConfig(};}+/**+ * Below this context budget a summarization cycle cannot make progress: the+ * summary allocation rounds down to a handful of tokens, the rewritten history+ * still overflows, and the graph re-triggers summarization on every step until+ * the recursion limit aborts the run. Dozens of wasted LLM calls surfaced to+ * the user as an opaque LangGraph error. Falling back to plain pruning instead+ * either fits the request or fails fast with the actionable `empty_messages`+ * token-budget breakdown. Matches the floor `initializeAgent` applies when the+ * user supplies no override.+ */+const MIN_SUMMARIZATION_CONTEXT_TOKENS = 1024;+/*** Applies `reserveRatio` against the pre-ratio base context budget, falling* back to the pre-computed `maxContextTokens` from initializeAgent.@@ -1879,6 +1891,20 @@ export async function createRun({agent.maxContextTokens,);+ const summarizationViable =+ effectiveMaxContextTokens == null ||+ effectiveMaxContextTokens >= MIN_SUMMARIZATION_CONTEXT_TOKENS;+ if (summarization.enabled && !summarizationViable) {+ logger.warn(+ '[createRun] Summarization disabled for this run: context budget below viable minimum',+ {+ agentId: agent.id,+ effectiveMaxContextTokens,+ minimum: MIN_SUMMARIZATION_CONTEXT_TOKENS,+ },+ );+ }+const reasoningKey = getReasoningKey(provider, llmConfig, agent.endpoint, agent.reasoningKey);const agentInput: AgentInputs = {provider,@@ -1896,7 +1922,7 @@ export async function createRun({useLegacyContent: agent.useLegacyContent ?? false,discoveredTools:!isSubagent && discoveredTools.size > 0 ? Array.from(discoveredTools) : undefined,- summarizationEnabled: summarization.enabled,+ summarizationEnabled: summarization.enabled && summarizationViable,summarizationConfig: summarization.config,...(!isSubagent && compactionSemanticIndex != null ? { compactionSemanticIndex } : {}),initialSummary: isSubagent ? undefined : initialSummary,diff --git a/packages/client/src/components/DisclosureChevron.tsx b/packages/client/src/components/DisclosureChevron.tsxnew file mode 100644index 0000000000..dd48b5d987--- /dev/null+++ b/packages/client/src/components/DisclosureChevron.tsx@@ -0,0 +1,29 @@+import { cva } from 'class-variance-authority';+import type { ClassProp } from 'class-variance-authority/types';++type DisclosureChevronVariantOptions = ({ expanded?: boolean } & ClassProp) | undefined;++/**+ * Appearance for the chevron that opens a disclosure row: it stays invisible+ * until the row (`group/disclosure`) is hovered or holds focus, then rotates+ * once the panel is open.+ *+ * Owned here rather than in the feature so a change to the reveal, the focus+ * behaviour, the motion, or the theme role reaches every disclosure surface at+ * once. Callers keep only geometry (the icon size and any optical offset),+ * which legitimately differs per row.+ */+export const disclosureChevronVariants: (props?: DisclosureChevronVariantOptions) => string = cva(+ 'shrink-0 text-text-secondary opacity-0 transition-transform duration-200 ease-out group-focus-within/disclosure:opacity-100 group-hover/disclosure:opacity-100 motion-reduce:transition-none',+ {+ variants: {+ expanded: {+ true: 'rotate-180',+ false: '',+ },+ },+ defaultVariants: {+ expanded: false,+ },+ },+);diff --git a/packages/client/src/components/index.ts b/packages/client/src/components/index.tsindex 4fbdf95e7b..87c9d7140e 100644--- a/packages/client/src/components/index.ts+++ b/packages/client/src/components/index.ts@@ -6,6 +6,7 @@ export * from './Breadcrumb';export * from './Button';export * from './Chip';export * from './Checkbox';+export * from './DisclosureChevron';export * from './Dialog';export * from './DropdownMenu';export * from './HoverCard';diff --git a/packages/client/src/theme/registry.spec.ts b/packages/client/src/theme/registry.spec.tsindex 27a52fa755..a6216c02e0 100644--- a/packages/client/src/theme/registry.spec.ts+++ b/packages/client/src/theme/registry.spec.ts@@ -50,6 +50,52 @@ describe('theme registry', () => {expect(dark.appearance).toEqual(defaultAppearance);});+ it('derives omitted code surfaces from the mode-specific legacy canvas', () => {+ const theme = fromLegacyTheme(+ {+ 'rgb-surface-primary-alt': '12 34 56',+ 'rgb-presentation': '210 211 212',+ },+ 'legacy-code-reference',+ );++ expect(resolveTheme(theme, 'light').colors['rgb-surface-code']).toBe('12 34 56');+ expect(resolveTheme(theme, 'dark').colors['rgb-surface-code']).toBe('210 211 212');+ });++ it('preserves explicit code surfaces instead of deriving them', () => {+ const theme: ThemeDefinition = {+ version: 1,+ name: 'explicit-code-reference',+ modes: {+ light: {+ colors: {+ 'rgb-surface-primary-alt': '12 34 56',+ 'rgb-surface-code': '65 43 21',+ },+ },+ dark: {+ colors: {+ 'rgb-presentation': '210 211 212',+ 'rgb-surface-code': '98 76 54',+ },+ },+ },+ };++ expect(resolveTheme(theme, 'light').colors['rgb-surface-code']).toBe('65 43 21');+ expect(resolveTheme(theme, 'dark').colors['rgb-surface-code']).toBe('98 76 54');+ });++ it('keeps the bundled code surfaces unchanged for the default appearances', () => {+ expect(resolveTheme(libreChatTheme, 'light').colors['rgb-surface-code']).toBe(+ defaultTheme['rgb-surface-code'],+ );+ expect(resolveTheme(libreChatTheme, 'dark').colors['rgb-surface-code']).toBe(+ darkTheme['rgb-surface-code'],+ );+ });+/** Themes predate the shimmer stops, so an omission means "not written yet",* not "wants LibreChat's sweep". Filling it from the bundled base would light* a white-text theme's in-flight labels in the stock near-black. */diff --git a/packages/client/src/theme/registry.ts b/packages/client/src/theme/registry.tsindex 114b1bd6c4..8220b2fd4d 100644--- a/packages/client/src/theme/registry.ts+++ b/packages/client/src/theme/registry.ts@@ -349,6 +349,20 @@ export function resolveTheme(theme: ThemeDefinition, mode: ThemeMode): ResolvedTcustomColors?.['rgb-surface-hover'] !== undefined? { 'rgb-surface-composer-hover': customColors['rgb-surface-hover'] }: {};+ /**+ * Code blocks are tied to the same mode-specific surfaces by the legacy CSS:+ * `surface-primary-alt` in light and `presentation` in dark. Keep that+ * relationship for themes created before `surface-code` was registered,+ * rather than pinning their syntax colours to the bundled code surface.+ */+ const codeSurfaceSource =+ mode === 'dark'+ ? customColors?.['rgb-presentation']+ : customColors?.['rgb-surface-primary-alt'];+ const codeSurfaceFallback =+ customColors?.['rgb-surface-code'] === undefined && codeSurfaceSource !== undefined+ ? { 'rgb-surface-code': codeSurfaceSource }+ : {};/*** Themes written before the shimmer stops existed cannot name them, and* filling the omission from the bundled base would pin their in-flight labels@@ -385,6 +399,7 @@ export function resolveTheme(theme: ThemeDefinition, mode: ThemeMode): ResolvedTcolors: {...baseColors,...customColors,+ ...codeSurfaceFallback,...composerHoverFallback,...shimmerBaseFallback,...textMutedFallback,diff --git a/packages/client/src/theme/semanticTokens.spec.ts b/packages/client/src/theme/semanticTokens.spec.tsindex ec7f1f4150..7eb06a0378 100644--- a/packages/client/src/theme/semanticTokens.spec.ts+++ b/packages/client/src/theme/semanticTokens.spec.ts@@ -166,6 +166,7 @@ const canvasSurfaces: Array<keyof IThemeRGB> = ['rgb-surface-secondary','rgb-surface-dialog','rgb-surface-chat',+ 'rgb-surface-code','rgb-presentation',];diff --git a/packages/client/src/theme/themes/dark.ts b/packages/client/src/theme/themes/dark.tsindex e4960c78d5..d16ecc3d61 100644--- a/packages/client/src/theme/themes/dark.ts+++ b/packages/client/src/theme/themes/dark.ts@@ -53,6 +53,7 @@ export const darkTheme: IThemeRGB = {'rgb-surface-destructive': '153 27 27', // #991b1b (red-800)'rgb-surface-destructive-hover': '127 29 29', // #7f1d1d (red-900)'rgb-surface-chat': '47 47 47', // #2f2f2f (gray-700)+ 'rgb-surface-code': '33 33 33', // #212121 (gray-800)'rgb-surface-inverted': '255 255 255', // #fff (white)'rgb-surface-inverted-hover': '236 236 236', // #ececec (gray-100)'rgb-text-inverted': '23 23 23', // #171717 (gray-850)diff --git a/packages/client/src/theme/themes/default.ts b/packages/client/src/theme/themes/default.tsindex 2bf971582b..9e688ff446 100644--- a/packages/client/src/theme/themes/default.ts+++ b/packages/client/src/theme/themes/default.ts@@ -53,6 +53,7 @@ export const defaultTheme: IThemeRGB = {'rgb-surface-destructive': '185 28 28', // #b91c1c (red-700)'rgb-surface-destructive-hover': '153 27 27', // #991b1b (red-800)'rgb-surface-chat': '255 255 255', // #fff (white)+ 'rgb-surface-code': '247 247 248', // #f7f7f8 (gray-50)'rgb-surface-inverted': '23 23 23', // #171717 (gray-850)'rgb-surface-inverted-hover': '47 47 47', // #2f2f2f (gray-700)'rgb-text-inverted': '255 255 255', // #fff (white)diff --git a/packages/client/src/theme/themes/highContrast.spec.ts b/packages/client/src/theme/themes/highContrast.spec.tsindex 3ddd161dd6..2ec32c4055 100644--- a/packages/client/src/theme/themes/highContrast.spec.ts+++ b/packages/client/src/theme/themes/highContrast.spec.ts@@ -71,10 +71,9 @@ const textTokens: Array<keyof IThemeRGB> = ['rgb-text-muted',];-/** `--surface-code` resolves to `surface-primary-alt` in light mode and- * `presentation` in dark, so asserting against both covers either mode without- * the table needing to know which one it is holding. */-const codeSurfaces: Array<keyof IThemeRGB> = ['rgb-surface-primary-alt', 'rgb-presentation'];+/** Code blocks share the mode's own high-contrast canvas rather than a bundled+ * fallback that would reintroduce a grey surface. */+const codeSurfaces: Array<keyof IThemeRGB> = ['rgb-surface-code'];const syntaxTokens: Array<keyof IThemeRGB> = ['rgb-syntax-text',@@ -168,6 +167,17 @@ describe.each([expect(Object.keys(theme).sort()).toEqual([...themeColorTokens].sort());});+ it('uses the mode canvas for code blocks instead of the stock grey', () => {+ const expected = theme === highContrastDarkTheme ? '0 0 0' : '255 255 255';+ const source =+ theme === highContrastDarkTheme+ ? theme['rgb-presentation']+ : theme['rgb-surface-primary-alt'];++ expect(theme['rgb-surface-code']).toBe(expected);+ expect(theme['rgb-surface-code']).toBe(source);+ });+it('keeps neutral text at WCAG AAA on every canvas and hover fill', () => {expect(below(theme, WCAG_AAA_NORMAL, textTokens, surfaces)).toEqual([]);});diff --git a/packages/client/src/theme/themes/highContrast.ts b/packages/client/src/theme/themes/highContrast.tsindex e5e6fc2f7c..fd07d37d54 100644--- a/packages/client/src/theme/themes/highContrast.ts+++ b/packages/client/src/theme/themes/highContrast.ts@@ -89,6 +89,7 @@ export const highContrastLightTheme: IThemeRGB = {'rgb-surface-destructive': '161 0 0', // #a10000'rgb-surface-destructive-hover': '122 0 0', // #7a0000'rgb-surface-chat': '255 255 255', // #ffffff+ 'rgb-surface-code': '255 255 255', // #ffffff, matching surface-primary-alt'rgb-surface-inverted': '0 0 0', // #000000'rgb-surface-inverted-hover': '51 51 51', // #333333'rgb-text-inverted': '255 255 255', // #ffffff@@ -220,6 +221,7 @@ export const highContrastDarkTheme: IThemeRGB = {'rgb-surface-destructive': '255 143 143', // #ff8f8f'rgb-surface-destructive-hover': '255 179 179', // #ffb3b3'rgb-surface-chat': '0 0 0', // #000000+ 'rgb-surface-code': '0 0 0', // #000000, matching presentation'rgb-surface-inverted': '255 255 255', // #ffffff'rgb-surface-inverted-hover': '212 212 212', // #d4d4d4'rgb-text-inverted': '0 0 0', // #000000diff --git a/packages/client/src/theme/types/index.ts b/packages/client/src/theme/types/index.tsindex 5848850b58..94fde9189a 100644--- a/packages/client/src/theme/types/index.ts+++ b/packages/client/src/theme/types/index.ts@@ -54,6 +54,7 @@ export interface IThemeRGB {'rgb-surface-destructive'?: string;'rgb-surface-destructive-hover'?: string;'rgb-surface-chat'?: string;+ 'rgb-surface-code'?: string;'rgb-surface-inverted'?: string;'rgb-surface-inverted-hover'?: string;'rgb-text-inverted'?: string;@@ -176,6 +177,7 @@ export interface IThemeVariables {'--surface-destructive': string;'--surface-destructive-hover': string;'--surface-chat': string;+ '--surface-code': string;'--surface-inverted': string;'--surface-inverted-hover': string;'--text-inverted': string;@@ -277,6 +279,7 @@ export interface IThemeColors {'surface-destructive'?: string;'surface-destructive-hover'?: string;'surface-chat'?: string;+ 'surface-code'?: string;'surface-inverted'?: string;'surface-inverted-hover'?: string;'text-inverted'?: string;diff --git a/packages/client/src/theme/utils/applyTheme.spec.ts b/packages/client/src/theme/utils/applyTheme.spec.tsindex 8aaeebdb59..a27c348bc0 100644--- a/packages/client/src/theme/utils/applyTheme.spec.ts+++ b/packages/client/src/theme/utils/applyTheme.spec.ts@@ -4,8 +4,8 @@ import applyTheme, {clearAppliedTheme,themeOwnedProperties,} from './applyTheme';+import { highContrastTheme, resolveTheme } from '../registry';import { defaultTheme } from '../themes/default';-import { resolveTheme } from '../registry';const semanticProperties = ['--link',@@ -137,6 +137,14 @@ describe('applyTheme', () => {expect(root.style.getPropertyValue('--theme-motion-fast')).toBe('80ms');});+ it('applies the resolved high-contrast code surface instead of the stock grey', () => {+ const root = document.documentElement;++ applyResolvedTheme(resolveTheme(highContrastTheme, 'dark'), root);++ expect(root.style.getPropertyValue('--surface-code')).toBe('0 0 0');+ });+/** The sweep under an in-flight label is painted in CSS, so it is only* themeable if its stops are theme-owned properties. A dark theme is the* case that matters: `style.css` declares a `.dark` base outright, which adiff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.tsindex 94e15a7a9f..f7a7989e49 100644--- a/packages/data-provider/src/config.ts+++ b/packages/data-provider/src/config.ts@@ -3309,6 +3309,14 @@ export enum ErrorTypes {* Provider throttled or refused the request for exceeding a rate/spend allowance*/MODEL_RATE_LIMIT = 'model_rate_limit',+ /**+ * Context pruning removed every message; nothing fits the configured context window+ */+ EMPTY_MESSAGES = 'empty_messages',+ /**+ * Formatted provider payload exceeded the context budget before invocation+ */+ FINAL_CONTEXT_OVERFLOW = 'final_context_overflow',}/**diff --git a/packages/data-provider/src/types/assistants.ts b/packages/data-provider/src/types/assistants.tsindex 672d262834..28b45bc904 100644--- a/packages/data-provider/src/types/assistants.ts+++ b/packages/data-provider/src/types/assistants.ts@@ -714,6 +714,10 @@ export type SummaryContentPart = {content?: Array<{ type: ContentTypes.TEXT; text: string }>;tokenCount?: number;summarizing?: boolean;+ /** A summarize round that ended in error. Partial deltas already streamed+ * into this slot are kept, so the renderer needs this to avoid presenting+ * truncated text under the "Conversation summarized" label. */+ failed?: boolean;summaryVersion?: number;model?: string;provider?: string;