Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🧑‍🍳 fix: Distinguish Tool Preparation From Execution (#16619)

lia-by-librechat[bot]34df3ace409a
diff --git a/client/src/components/Chat/Messages/Content/AskUserQuestionProgress.tsx b/client/src/components/Chat/Messages/Content/AskUserQuestionProgress.tsx
index 9e921fb36d..3dc98eef05 100644
--- a/client/src/components/Chat/Messages/Content/AskUserQuestionProgress.tsx
+++ b/client/src/components/Chat/Messages/Content/AskUserQuestionProgress.tsx
@@ -4,6 +4,7 @@ import parseJsonField, { parseJsonFieldOccurrences } from './Parts/parseJsonFiel
import { collectLiveAskToolCallIds } from '~/utils/approval';
import { useGetMessagesByConvoId } from '~/data-provider';
import { ChatContext } from '~/Providers/ChatContext';
+import { useToolPreparation } from './preparation';
import { useLocalize } from '~/hooks';
/**
@@ -28,6 +29,7 @@ export default function AskUserQuestionProgress({
toolCallId?: string;
}) {
const localize = useLocalize();
+ const preparationText = useToolPreparation();
const conversationId = useContext(ChatContext)?.conversation?.conversationId;
const enabled = conversationId != null && conversationId !== 'new';
const { data: livePauses } = useGetMessagesByConvoId(enabled ? conversationId : '', {
@@ -68,18 +70,18 @@ export default function AskUserQuestionProgress({
}
return (
- <div className="my-2 flex w-full flex-col gap-1.5 rounded-lg border border-border-light bg-surface-secondary p-3">
+ <div className="border-border-light bg-surface-secondary my-2 flex w-full flex-col gap-1.5 rounded-lg border p-3">
<div
- className="flex items-center gap-2 text-xs font-medium text-text-secondary"
+ className="text-text-secondary flex items-center gap-2 text-xs font-medium"
role="status"
>
<MessageCircleQuestion className="h-4 w-4 animate-pulse" aria-hidden="true" />
- <span className="shimmer">{localize('com_ui_asking')}</span>
+ <span className="shimmer">{preparationText ?? localize('com_ui_asking')}</span>
</div>
{question.length > 0 ? (
- <p className="text-sm font-medium text-text-primary [overflow-wrap:anywhere]">{question}</p>
+ <p className="text-text-primary text-sm font-medium [overflow-wrap:anywhere]">{question}</p>
) : (
- <div className="h-4 w-2/5 animate-pulse rounded bg-surface-tertiary" aria-hidden="true" />
+ <div className="bg-surface-tertiary h-4 w-2/5 animate-pulse rounded" aria-hidden="true" />
)}
</div>
);
diff --git a/client/src/components/Chat/Messages/Content/Part.tsx b/client/src/components/Chat/Messages/Content/Part.tsx
index 8c6f767e19..ceacf05e41 100644
--- a/client/src/components/Chat/Messages/Content/Part.tsx
+++ b/client/src/components/Chat/Messages/Content/Part.tsx
@@ -36,6 +36,7 @@ import { getAskUserQuestionPart } from '~/utils/approval';
import AskUserQuestionCall from './AskUserQuestionCall';
import { isBashProgrammaticToolCall } from './routing';
import { isError } from './ToolOutput/OutputRenderer';
+import { ToolPreparation } from './preparation';
import { useMessageContext } from '~/Providers';
import { ErrorMessage } from './MessageContent';
import AskUserQuestion from './AskUserQuestion';
@@ -474,6 +475,11 @@ const Part = memo(function Part({
/>
);
})();
+ const preparedCard = (
+ <ToolPreparation call={toolCall} isSubmitting={isSubmitting}>
+ {card}
+ </ToolPreparation>
+ );
/** Render approval controls for ANY paused agent tool — not just the generic
* card — so a HITL policy that gates a specialized tool (bash, code, file…)
@@ -482,7 +488,7 @@ const Part = memo(function Part({
if (toolCall.approval != null && (toolCall.output?.length ?? 0) === 0) {
return (
<>
- {card}
+ {preparedCard}
<ToolApproval
approval={toolCall.approval}
toolCallId={toolCall.id ?? ''}
@@ -491,7 +497,7 @@ const Part = memo(function Part({
</>
);
}
- return card;
+ return preparedCard;
} else if (toolCall.type === ToolCallTypes.CODE_INTERPRETER) {
const code_interpreter = toolCall[ToolCallTypes.CODE_INTERPRETER];
return (
@@ -539,14 +545,27 @@ const Part = memo(function Part({
);
}
return (
- <ImageGen
- initialProgress={toolCall.progress ?? 0.1}
- args={toolCall.function.arguments as string}
+ <ToolPreparation
+ call={{
+ args: toolCall.function.arguments as string,
+ name: toolCall.function.name,
+ output: toolCall.function.output,
+ progress: toolCall.progress,
+ runStepStatus: toolCall.runStepStatus,
+ toolPreparationStartedAt: toolCall.toolPreparationStartedAt,
+ toolDispatchedAt: toolCall.toolDispatchedAt,
+ }}
isSubmitting={isSubmitting}
- runStepStatus={toolCall.runStepStatus}
- toolName={toolCall.function.name}
- output={toolCall.function.output ?? ''}
- />
+ >
+ <ImageGen
+ initialProgress={toolCall.progress ?? 0.1}
+ args={toolCall.function.arguments as string}
+ isSubmitting={isSubmitting}
+ runStepStatus={toolCall.runStepStatus}
+ toolName={toolCall.function.name}
+ output={toolCall.function.output ?? ''}
+ />
+ </ToolPreparation>
);
} else if (toolCall.type === ToolCallTypes.FUNCTION && ToolCallTypes.FUNCTION in toolCall) {
if (isImageVisionTool(toolCall)) {
@@ -567,6 +586,12 @@ const Part = memo(function Part({
args={toolCall.function.arguments as string}
name={toolCall.function.name}
output={toolCall.function.output}
+ runStepStatus={toolCall.runStepStatus}
+ runStepDurationMs={toolCall.runStepDurationMs}
+ toolPreparationStartedAt={toolCall.toolPreparationStartedAt}
+ toolDispatchedAt={toolCall.toolDispatchedAt}
+ toolPreparationDurationMs={toolCall.toolPreparationDurationMs}
+ toolExecutionDurationMs={toolCall.toolExecutionDurationMs}
isLast={isLast}
hideAttachments={hideAttachments}
onExpand={onToolExpand}
diff --git a/client/src/components/Chat/Messages/Content/Parts/BackgroundTaskCall.tsx b/client/src/components/Chat/Messages/Content/Parts/BackgroundTaskCall.tsx
index 7488d9e868..b1b5c042ea 100644
--- a/client/src/components/Chat/Messages/Content/Parts/BackgroundTaskCall.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/BackgroundTaskCall.tsx
@@ -9,6 +9,7 @@ import { toolPanelSpacingClassName } from '../disclosure';
import { ToolIcon, OutputRenderer } from '../ToolOutput';
import { MCPAppViews } from '~/components/MCPUIResource';
import BackgroundTaskCard from '../BackgroundTaskCard';
+import { useToolPreparation } from '../preparation';
import useToolCallState from './useToolCallState';
import { AttachmentGroup } from './Attachment';
import { useToolCallIntent } from './intent';
@@ -45,6 +46,7 @@ export default function BackgroundTaskCall({
const mcpIconMap = useMCPIconMap();
const mcpServerNames = useMCPServerNames();
const intent = useToolCallIntent(args);
+ const preparationText = useToolPreparation();
const display = useMemo(() => parseBackgroundTaskOutput(output), [output]);
const input = useMemo(() => {
if (typeof args === 'string') {
@@ -96,7 +98,7 @@ export default function BackgroundTaskCall({
let announcedText = finishedText;
if (phase === 'running') {
- announcedText = localize('com_ui_background_tasks_checking');
+ announcedText = preparationText ?? localize('com_ui_background_tasks_checking');
} else if (phase === 'failed' && (noticeText == null || outcome !== 'failed')) {
announcedText =
display?.kind === 'list'
diff --git a/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/OpenAIImageGen.tsx b/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/OpenAIImageGen.tsx
index 40be280653..1c61c831ea 100644
--- a/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/OpenAIImageGen.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/OpenAIImageGen.tsx
@@ -9,6 +9,7 @@ import type {
} from 'librechat-data-provider';
import { ToolIcon, isError } from '~/components/Chat/Messages/Content/ToolOutput';
import Image from '~/components/Chat/Messages/Content/Image';
+import { useToolPreparation } from '../../preparation';
import { useProgress, useLocalize } from '~/hooks';
import { useToolCallIntent } from '../intent';
import { ROW_GLYPH_SLOT } from '../../rows';
@@ -62,6 +63,7 @@ export default function OpenAIImageGen({
runStepStatus?: PartMetadata['runStepStatus'];
}) {
const localize = useLocalize();
+ const preparationText = useToolPreparation();
/** Model-authored live label (injected when the tool is opted into
* describe_intent); wins over the phase texts. */
const intent = useToolCallIntent(_args);
@@ -248,7 +250,7 @@ export default function OpenAIImageGen({
<span className="sr-only" aria-live="polite" aria-atomic="true">
{(() => {
if (progress < 1 && !cancelled && !reportsError) {
- return '';
+ return preparationText ?? '';
}
if (reportsError) {
return localize('com_ui_image_gen_failed');
@@ -259,7 +261,7 @@ export default function OpenAIImageGen({
return intent ?? localize('com_ui_image_created');
})()}
</span>
- <div className="relative my-1 flex h-5 shrink-0 items-center gap-2 text-text-secondary">
+ <div className="text-text-secondary relative my-1 flex h-5 shrink-0 items-center gap-2">
<span className={ROW_GLYPH_SLOT} aria-hidden="true">
<ToolIcon type="image_gen" isAnimating={isInProgress} />
</span>
diff --git a/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/ProgressText.tsx b/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/ProgressText.tsx
index 58fe8fd95f..64101c10df 100644
--- a/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/ProgressText.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/OpenAIImageGen/ProgressText.tsx
@@ -1,4 +1,5 @@
import { AGENT_STYLE_TOOLS } from '.';
+import { useToolPreparation } from '../../preparation';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
@@ -19,6 +20,7 @@ export default function ProgressText({
intent?: string;
}) {
const localize = useLocalize();
+ const preparationText = useToolPreparation();
const getText = () => {
/** Failure outranks cancellation: the legacy inference folds errors into
@@ -30,6 +32,9 @@ export default function ProgressText({
if (cancelled) {
return localize('com_ui_cancelled');
}
+ if (progress < 1 && preparationText != null) {
+ return preparationText;
+ }
if (intent != null) {
return intent;
}
diff --git a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx
index 9b732e7158..06626817aa 100644
--- a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx
@@ -22,6 +22,7 @@ import { useShareContext } from '~/Providers/ShareContext';
import MessageIcon from '~/components/Share/MessageIcon';
import { parseSubagentBackgroundHandle } from './handle';
import { isError } from '../ToolOutput/OutputRenderer';
+import { useToolPreparation } from '../preparation';
import { useAgentsMapContext } from '~/Providers';
import { useMCPServerNames } from '~/hooks/MCP';
import { AttachmentGroup } from './Attachment';
@@ -267,10 +268,12 @@ export default function SubagentCall({
/** Model-authored live label (subagent carries `intent` natively); wins
* over the generic verb, never over error/cancellation framing. */
const intent = useToolCallIntent(args);
+ const preparationText = useToolPreparation();
const getHeaderText = () => {
if (hasError) return localize('com_ui_subagent_errored');
if (cancelled) return localize('com_ui_subagent_cancelled');
if (detachedStatusUnknown) return localize('com_ui_subagent_activity');
+ if (running && preparationText != null) return preparationText;
if (intent != null) return intent;
if (running) return localize('com_ui_subagent_running');
return localize('com_ui_subagent_complete');
diff --git a/client/src/components/Chat/Messages/Content/Parts/parseJsonField.ts b/client/src/components/Chat/Messages/Content/Parts/parseJsonField.ts
index 5acc8bc11f..7322b1f215 100644
--- a/client/src/components/Chat/Messages/Content/Parts/parseJsonField.ts
+++ b/client/src/components/Chat/Messages/Content/Parts/parseJsonField.ts
@@ -4,7 +4,7 @@ export function areToolCallArgsComplete(args: ToolCallArgs): boolean {
if (typeof args === 'object' && args !== null) {
return true;
}
- if (typeof args !== 'string' || args.trim().length === 0) {
+ if (typeof args !== 'string' || !args.trimEnd().endsWith('}')) {
return false;
}
try {
diff --git a/client/src/components/Chat/Messages/Content/ProgressText.tsx b/client/src/components/Chat/Messages/Content/ProgressText.tsx
index 47d62f8655..fc93aed638 100644
--- a/client/src/components/Chat/Messages/Content/ProgressText.tsx
+++ b/client/src/components/Chat/Messages/Content/ProgressText.tsx
@@ -6,6 +6,7 @@ import { Button, disclosureChevronVariants } from '@librechat/client';
import { isReportableRunStepDuration } from 'librechat-data-provider';
import type { ToolCallPhase } from '~/utils/toolCallPhase';
import { cn, getRunStepDurationLabels } from '~/utils';
+import { useToolPreparation } from './preparation';
import CancelledIcon from './CancelledIcon';
import { useFailedReveal } from './reveal';
import { ElapsedTimer } from '../Elapsed';
@@ -109,6 +110,7 @@ export default function ProgressText({
const localize = useLocalize();
/** For locale-aware decimal formatting of the sub-10s duration value. */
const { i18n } = useTranslation();
+ const preparationText = useToolPreparation();
const isRunning = phase === 'running';
/** A server-authored phase stamp is an identity, not a browser clock origin.
* On reconnect we can only time from local receipt, never infer cross-host skew. */
@@ -149,7 +151,7 @@ export default function ProgressText({
/** Every branch below reads `phase`, so the label, the icon, the shimmer,
* the failure suffix and the duration cannot disagree about what state
* the card is in. */
- const text = isRunning ? (authText ?? inProgressText) : finishedText;
+ const text = isRunning ? (authText ?? preparationText ?? inProgressText) : finishedText;
const icon = phase === 'cancelled' ? <CancelledIcon /> : (iconProp ?? null);
const showShimmer = isRunning;
const errorSuffix = phase === 'failed' ? localize('com_ui_tool_failed') : undefined;
diff --git a/client/src/components/Chat/Messages/Content/RetrievalCall.tsx b/client/src/components/Chat/Messages/Content/RetrievalCall.tsx
index 3cccf25d9f..fc44a587d8 100644
--- a/client/src/components/Chat/Messages/Content/RetrievalCall.tsx
+++ b/client/src/components/Chat/Messages/Content/RetrievalCall.tsx
@@ -11,6 +11,7 @@ import { toolPanelSpacingClassName } from './disclosure';
import FilePreviewDialog from './FilePreviewDialog';
import { sortPagesByRelevance, cn } from '~/utils';
import { useToolCallIntent } from './Parts/intent';
+import { useToolPreparation } from './preparation';
import { useGetFiles } from '~/data-provider';
import ProgressText from './ProgressText';
import store from '~/store';
@@ -365,6 +366,7 @@ export default function RetrievalCall({
* describe_intent); persists as the settled label. The sr-only live
* region below deliberately keeps its stable generic value. */
const intent = useToolCallIntent(args);
+ const preparationText = useToolPreparation();
/**
* One resolution, read by the label, the live region and the icon alike.
@@ -463,7 +465,7 @@ export default function RetrievalCall({
<span className="sr-only" aria-live="polite" aria-atomic="true">
{(() => {
if (phase === 'running') {
- return localize('com_ui_searching_files');
+ return preparationText ?? localize('com_ui_searching_files');
}
if (phase === 'cancelled') {
return localize('com_ui_cancelled');
diff --git a/client/src/components/Chat/Messages/Content/ToolCall.tsx b/client/src/components/Chat/Messages/Content/ToolCall.tsx
index 3fa3d84707..e92c1b6186 100644
--- a/client/src/components/Chat/Messages/Content/ToolCall.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolCall.tsx
@@ -11,6 +11,7 @@ import {
import type { TAttachment, PartMetadata } from 'librechat-data-provider';
import { useLocalize, useProgress, useExpandCollapse, useLazyCollapseBody } from '~/hooks';
import { cn, getToolDisplayLabel, logger, openInNewTab } from '~/utils';
+import { isToolCallPreparing, useToolPreparation } from './preparation';
import { ToolIcon, getToolIconType, isError } from './ToolOutput';
import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';
import { resolveToolCallPhase } from '~/utils/toolCallPhase';
@@ -322,6 +323,19 @@ export default function ToolCall({
* the `tool_intents` capability); persists as the settled label —
* completion is a UI state, not a tense change. */
const intent = useToolCallIntent(_args);
+ const preparationText = useToolPreparation();
+ const preparing = useMemo(
+ () =>
+ isToolCallPreparing({
+ args: _args,
+ output,
+ progress: initialProgress,
+ toolPreparationStartedAt,
+ toolDispatchedAt,
+ runStepStatus,
+ }),
+ [_args, output, initialProgress, toolPreparationStartedAt, toolDispatchedAt, runStepStatus],
+ );
const subject = intent ?? displayFunctionName;
let inProgressText =
intent ??
@@ -330,8 +344,12 @@ export default function ToolCall({
: localize('com_assistants_running_action'));
if (toolDispatchedAt != null) {
inProgressText = localize('com_ui_tool_calling', { 0: subject });
- } else if (toolPreparationStartedAt != null) {
- inProgressText = localize('com_ui_tool_preparing', { 0: subject });
+ } else if (preparing) {
+ inProgressText =
+ preparationText ??
+ (displayFunctionName
+ ? localize('com_ui_tool_preparing', { 0: displayFunctionName })
+ : localize('com_assistants_preparing_action'));
}
const getFinishedText = () => {
@@ -380,8 +398,8 @@ export default function ToolCall({
if (toolDispatchedAt != null) {
return localize('com_ui_tool_calling', { 0: displayFunctionName });
}
- if (toolPreparationStartedAt != null) {
- return localize('com_ui_tool_preparing', { 0: displayFunctionName });
+ if (preparing) {
+ return inProgressText;
}
return displayFunctionName
? localize('com_assistants_running_var', { 0: displayFunctionName })
diff --git a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
index 9d3d750382..9310f800ad 100644
--- a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
@@ -150,8 +150,17 @@ export default function ToolCallGroup({
let taskCheckCount = 0;
let failedCount = 0;
let cancelledCount = 0;
+ let preparingCount = 0;
+ let executingCount = 0;
for (const tool of toolMetadata) {
+ if (!tool.hasOutput && !tool.failed && !tool.cancelled) {
+ if (tool.preparing) {
+ preparingCount++;
+ } else {
+ executingCount++;
+ }
+ }
if (tool.name === Tools.web_search) {
webSearchCount++;
} else if (tool.name === 'file_search' || tool.name === 'retrieval') {
@@ -192,6 +201,8 @@ export default function ToolCallGroup({
taskCheckCount,
failedCount,
cancelledCount,
+ preparingCount,
+ executingCount,
toolNameSummary,
};
}, [toolMetadata, localize, mcpServerNames]);
@@ -396,6 +407,19 @@ export default function ToolCallGroup({
* 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 (isGroupLive && activitySummary.preparingCount > 0 && activitySummary.executingCount === 0) {
+ if (count === 1) {
+ return singleToolLabel
+ ? localize('com_ui_tool_preparing', { 0: singleToolLabel })
+ : localize('com_assistants_preparing_action');
+ }
+ return localize(
+ activitySummary.preparingCount === 1
+ ? 'com_ui_preparing_one_action'
+ : 'com_ui_preparing_n_actions',
+ { 0: String(activitySummary.preparingCount) },
+ );
+ }
if (allSubagents) {
if (count === 1) {
return localize(subagentsDone ? 'com_ui_subagent_complete' : 'com_ui_subagent_running');
diff --git a/client/src/components/Chat/Messages/Content/WebSearch.tsx b/client/src/components/Chat/Messages/Content/WebSearch.tsx
index edbfc755e0..5db4c730fd 100644
--- a/client/src/components/Chat/Messages/Content/WebSearch.tsx
+++ b/client/src/components/Chat/Messages/Content/WebSearch.tsx
@@ -25,6 +25,7 @@ import { toolPanelSpacingClassName } from './disclosure';
import { isError } from './ToolOutput/OutputRenderer';
import parseJsonField from './Parts/parseJsonField';
import { useToolCallIntent } from './Parts/intent';
+import { useToolPreparation } from './preparation';
import { useSearchContext } from '~/Providers';
import SearchVerticals from './verticals';
import { ROW_GLYPH_SLOT } from './rows';
@@ -86,6 +87,7 @@ export default function WebSearch({
/** Model-authored live label (web_search carries `intent` natively);
* persists as the settled label like the other tool cards. */
const intent = useToolCallIntent(args);
+ const preparationText = useToolPreparation();
const { searchResults } = useSearchContext();
const error = (typeof output === 'string' && isError(output)) || runStepStatus === 'failed';
const legacyError =
@@ -187,6 +189,9 @@ export default function WebSearch({
* intent on every delta, so it always gets this value while streaming;
* the settled intent is announced once via the completed branch. */
const genericProgressText = useMemo(() => {
+ if (preparationText != null) {
+ return preparationText;
+ }
let text: ProgressKeys =
ownTurn !== '0' ? 'com_ui_web_searching_again' : 'com_ui_web_searching';
if (showSources) {
@@ -196,8 +201,8 @@ export default function WebSearch({
text = 'com_ui_web_search_reading';
}
return localize(text);
- }, [ownTurn, localize, showSources, finalizing]);
- const progressText = intent ?? genericProgressText;
+ }, [ownTurn, localize, showSources, finalizing, preparationText]);
+ const progressText = preparationText ?? intent ?? genericProgressText;
const autoExpand = useRecoilValue(store.autoExpandTools);
const sourceCount = allSources.length;
diff --git a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionProgress.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionProgress.test.tsx
index 0f87cf23a9..b92010a05d 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionProgress.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionProgress.test.tsx
@@ -1,13 +1,16 @@
import React from 'react';
import { render, screen } from '@testing-library/react';
import AskUserQuestionProgress from '../AskUserQuestionProgress';
+import { ToolPreparation } from '../preparation';
const translations: Record<string, string> = {
com_ui_asking: 'Asking',
+ com_ui_tool_name_ask_user_question: 'Question',
};
jest.mock('~/hooks', () => ({
- useLocalize: () => (key: string) => translations[key] ?? key,
+ useLocalize: () => (key: string, values?: Record<string, string>) =>
+ key === 'com_ui_tool_preparing' ? `Preparing ${values?.[0]}` : (translations[key] ?? key),
}));
jest.mock('~/Providers/ChatContext', () => {
@@ -120,3 +123,27 @@ describe('AskUserQuestionProgress', () => {
expect(container).toBeEmptyDOMElement();
});
});
+
+describe('question preparation transitions', () => {
+ test('announces preparation until measured dispatch, then asking until its interactive pause', () => {
+ mockLivePauses = { ids: [], hasUnattributed: false };
+ const frame = (args: string, toolDispatchedAt?: number) => (
+ <ToolPreparation
+ call={{ name: 'ask_user_question', args, toolPreparationStartedAt: 0, toolDispatchedAt }}
+ isSubmitting
+ >
+ <AskUserQuestionProgress args={args} toolCallId="call_1" />
+ </ToolPreparation>
+ );
+ const { rerender } = render(frame('{"question":"Which environment'));
+ expect(screen.getByRole('status')).toHaveTextContent('Preparing Question');
+ expect(screen.getByText('Which environment')).toBeInTheDocument();
+ rerender(frame('{"question":"Which environment?"}'));
+ expect(screen.getByRole('status')).toHaveTextContent('Preparing Question');
+ rerender(frame('{"question":"Which environment?"}', 100));
+ expect(screen.getByRole('status')).toHaveTextContent('Asking');
+ mockLivePauses = { ids: ['call_1'], hasUnattributed: false };
+ rerender(frame('{"question":"Which environment?"}', 100));
+ expect(screen.queryByRole('status')).not.toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx
index a356861225..b69f846547 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
@@ -1670,7 +1670,7 @@ describe('ContentParts — live activity fold', () => {
const intentCall = (id: string, intent: string, output = ''): TMessageContentParts =>
({
type: ContentTypes.TOOL_CALL,
- [ContentTypes.TOOL_CALL]: { id, name: 'lookup', args: `{"intent":"${intent}`, output },
+ [ContentTypes.TOOL_CALL]: { id, name: 'lookup', args: JSON.stringify({ intent }), output },
}) as unknown as TMessageContentParts;
const liveHeader = () =>
@@ -1692,6 +1692,46 @@ describe('ContentParts — live activity fold', () => {
expect(screen.queryByRole('button', { name: /^Running 2 actions/ })).toBeNull();
});
+ it('keeps the folded status preparing until measured dispatch, then restores its intent', () => {
+ jest.useFakeTimers();
+ const frame = (args: string, toolDispatchedAt?: number) => (
+ <RecoilRoot>
+ <ContentParts
+ {...liveProps}
+ content={[
+ {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: 't1',
+ name: 'lookup',
+ args,
+ output: '',
+ toolPreparationStartedAt: 100,
+ toolDispatchedAt,
+ },
+ },
+ ]}
+ />
+ </RecoilRoot>
+ );
+ const { rerender } = render(frame('{"intent":"Querying the graph","query":"SELECT'));
+ const card = screen.getByTestId('activity-phase-card');
+ expect(liveHeader()).toHaveTextContent('com_ui_tool_preparing');
+ expect(liveHeader()).not.toHaveTextContent('Querying the graph');
+ rerender(frame('{"intent":"Querying the graph","query":"SELECT 1"}'));
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+ expect(liveHeader()).toHaveTextContent('com_ui_tool_preparing');
+ rerender(frame('{"intent":"Querying the graph","query":"SELECT 1"}', 200));
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+ expect(screen.getByTestId('activity-phase-card')).toBe(card);
+ expect(liveHeader()).toHaveTextContent('Querying the graph');
+ expect(liveHeader()).toHaveAttribute('aria-expanded', 'false');
+ });
+
it('folds from the very first call so the block never changes shape as calls arrive', () => {
const { rerender } = renderContentParts({
...liveProps,
diff --git a/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx
index fbea93b2e8..62ad7759c0 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx
@@ -1,6 +1,7 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { Provider, useSetAtom } from 'jotai';
+import { MemoryRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act, fireEvent, render, screen, within } from '@testing-library/react';
import { ContentTypes, Tools, Constants, ToolCallTypes } from 'librechat-data-provider';
@@ -14,6 +15,7 @@ import { resolveAskUserQuestionPart } from '~/utils/approval';
import { sandboxStartingByToolCallId } from '~/store';
import ContentParts from '../ContentParts';
import { getLiveActivity } from '../live';
+import * as mcpHooks from '~/hooks/MCP';
import store from '~/store';
/**
@@ -28,7 +30,11 @@ import store from '~/store';
*/
jest.mock('~/hooks/MCP', () => {
const mcpServerNames: string[] = [];
- return { useMCPIconMap: () => new Map(), useMCPServerNames: () => mcpServerNames };
+ return {
+ __esModule: true,
+ useMCPIconMap: () => new Map(),
+ useMCPServerNames: () => mcpServerNames,
+ };
});
type Verdict = 'running' | 'completed' | 'failed' | 'cancelled';
@@ -157,6 +163,7 @@ const mount = (
/>
</RecoilRoot>
</QueryClientProvider>,
+ { wrapper: MemoryRouter },
);
/** What the real card says, read the way a user would, in the real English
@@ -882,9 +889,9 @@ describe('live fold parity with the cards it hides', () => {
);
const button = within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0];
- expect(button).toHaveTextContent('Querying the graph');
+ expect(button).toHaveTextContent('Preparing lookup');
expect(within(button).getByTestId('live-phase-outcome')).toHaveTextContent('1/2 failed');
- expect(button).toHaveAccessibleName(/Querying the graph.*1\/2 failed/);
+ expect(button).toHaveAccessibleName(/Preparing lookup.*1\/2 failed/);
});
it('announces a failure on the SAME call at once, without waiting for another source', () => {
@@ -1114,11 +1121,20 @@ describe('live activity hardening transitions', () => {
act(() => {
jest.advanceTimersByTime(500);
});
+ expect(header).toHaveAccessibleName('Preparing Code ×2');
+ const dispatched = toPart(
+ { name: Tools.execute_code, args: '{"intent":"Checking the data"}', output: '' },
+ 'sandbox-call',
+ );
+ view.rerender(frame([earlier, dispatched]));
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
expect(header).toHaveAccessibleName('Checking the data');
expect(screen.queryByTestId('live-phase-combo')).toBeNull();
view.rerender(
- frame([earlier, named, toPart({ name: Tools.execute_code, output: '' }, 'next-call')]),
+ frame([earlier, dispatched, toPart({ name: Tools.execute_code, output: '' }, 'next-call')]),
);
act(() => {
jest.advanceTimersByTime(500);
@@ -1161,6 +1177,14 @@ describe('live activity hardening transitions', () => {
jest.advanceTimersByTime(500);
});
expect(screen.getByTestId('activity-phase-card')).toBe(card);
+ expect(screen.getByRole('button')).toHaveAccessibleName('Preparing Code');
+ view.rerender(
+ frame([toPart({ name: Tools.execute_code, args: '{"intent":"Checking the data"}' })]),
+ );
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+ expect(screen.getByTestId('activity-phase-card')).toBe(card);
expect(screen.getByRole('button')).toHaveAccessibleName('Checking the data');
});
@@ -1594,3 +1618,87 @@ describe('tool pane identity at finalization', () => {
expect(toggles(container)[1]).toHaveAttribute('aria-expanded', 'false');
});
});
+
+describe('preparation labels across rendered tool cards', () => {
+ it.each([
+ 'lookup',
+ Tools.bash_tool,
+ Tools.execute_code,
+ 'create_file',
+ 'edit_file',
+ 'read_file',
+ 'set_memory',
+ 'skill',
+ Tools.web_search,
+ 'file_search',
+ Constants.SUBAGENT,
+ 'image_gen_oai',
+ 'ask_user_question',
+ Constants.CHECK_BACKGROUND_TASK,
+ ])('does not present %s as executing while its args are streaming', (name) => {
+ const part = toPart({ name, args: '{"intent":"Checking a record","value":"unfinished' });
+ const { container } = mount([part], undefined, false);
+ expect(container.textContent).toContain('Preparing ');
+ if (name === Constants.SUBAGENT) {
+ expect(screen.getByRole('button', { name: /^Preparing / })).toBeInTheDocument();
+ } else {
+ expect(container.querySelector('.shimmer')).toHaveTextContent(/^Preparing /);
+ }
+ for (const announcement of container.querySelectorAll('[aria-live]')) {
+ expect(announcement).toHaveTextContent(/^Preparing /);
+ }
+ });
+
+ it('keeps collapsed activity in preparation until dispatch, without a sandbox-startup override', () => {
+ const call = {
+ name: Tools.bash_tool,
+ args: '{"command":"echo hi',
+ toolPreparationStartedAt: 100,
+ };
+ const preparing = getLiveActivity([toPart(call)], (key) => key, []);
+ expect(preparing.text).toBe('com_ui_tool_preparing');
+ expect(preparing.pendingToolCallId).toBeUndefined();
+ const dispatched = getLiveActivity(
+ [toPart({ ...call, args: '{"command":"echo hi"}', toolDispatchedAt: 200 })],
+ (key) => key,
+ [],
+ );
+ expect(dispatched.text).toBe('com_assistants_running_var');
+ });
+});
+
+it('keeps delimiter-bearing MCP server names out of preparation labels', () => {
+ const names = jest.spyOn(mcpHooks, 'useMCPServerNames').mockReturnValue(['Google_mcp_Workspace']);
+ try {
+ mount(
+ [toPart({ name: 'search_mcp_Google_mcp_Workspace', args: '{"query":"partial' })],
+ undefined,
+ false,
+ );
+ const card = screen.getByTestId('tool-call');
+ expect(within(card).getByRole('button')).toHaveTextContent('Preparing search');
+ expect(within(card).getByRole('button')).not.toHaveTextContent('Preparing search_mcp_Google');
+ } finally {
+ names.mockRestore();
+ }
+});
+
+it.each(['lookup', 'image_gen_oai'])(
+ 'prepares legacy %s function cards while arguments stream',
+ (name) => {
+ const part: TMessageContentParts = {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id: 'legacy',
+ type: ToolCallTypes.FUNCTION,
+ function: { name, arguments: '{"prompt":"unfinished', output: '' },
+ progress: 0.1,
+ },
+ };
+ const { container } = mount([part], undefined, false);
+ expect(container.querySelector('.shimmer')).toHaveTextContent(/^Preparing /);
+ for (const announcement of container.querySelectorAll('[aria-live]')) {
+ expect(announcement).toHaveTextContent(/^Preparing /);
+ }
+ },
+);
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx
index f08e8d5f9d..836cdcecef 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx
@@ -220,7 +220,7 @@ describe('ToolCall', () => {
/** The aria-live region keeps its STABLE generic value while the intent
* streams — an atomic polite region would otherwise re-announce the
* whole growing sentence on every delta. */
- expect(screen.getByText('Running testFunction')).toBeInTheDocument();
+ expect(screen.getByText('Preparing testFunction')).toBeInTheDocument();
});
it('keeps the intent as the settled label instead of the generic completion text', () => {
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
index 75a8cc6013..3d77d8e148 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
@@ -1,7 +1,7 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
-import { Tools, Constants, ContentTypes } from 'librechat-data-provider';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
+import { Tools, Constants, ContentTypes, ToolCallTypes } from 'librechat-data-provider';
import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';
import { FailedRevealContext, useFailedReveal } from '../reveal';
import { scheduleMessageContentLayoutReconcile } from '~/hooks';
@@ -15,6 +15,9 @@ jest.mock('~/hooks', () => ({
if (key === 'com_ui_ran_n_actions') {
return `Ran ${values?.[0]} actions`;
}
+ if (key === 'com_ui_preparing_n_actions') {
+ return `Preparing ${values?.[0]} actions`;
+ }
if (key === 'com_ui_running_n_actions') {
return `Running ${values?.[0]} actions`;
}
@@ -1416,3 +1419,101 @@ describe('ToolCallGroup failure fast path', () => {
expect(screen.getByTestId('tool-call-group-panel').firstElementChild).toHaveClass('pl-6');
});
});
+
+describe('grouped tool preparation', () => {
+ it('keeps a collapsed group preparing until at least one call dispatches', () => {
+ const first = makePart('first', '', 'lookup', '{"query":"first');
+ const second = makePart('second', '', 'lookup', '{"query":"second');
+ const parts = [
+ { part: first, idx: 0 },
+ { part: second, idx: 1 },
+ ];
+ const props = {
+ parts,
+ isSubmitting: true,
+ isLast: true,
+ showThinking: false,
+ lastContentIdx: 1,
+ renderPart: (_part: TMessageContentParts, idx: number) => <div key={idx} />,
+ };
+ const { rerender } = renderGroup(props);
+ fireEvent.click(screen.getByRole('button', { name: /^Preparing 2 actions/ }));
+ expect(screen.getByRole('button', { name: /^Preparing 2 actions/ })).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ const dispatched =
+ first.type === ContentTypes.TOOL_CALL
+ ? { ...first, tool_call: { ...first.tool_call, toolDispatchedAt: 100 } }
+ : first;
+ rerender(
+ <RecoilRoot>
+ <ToolCallGroup {...props} parts={[{ part: dispatched, idx: 0 }, parts[1]]} />
+ </RecoilRoot>,
+ );
+ expect(screen.getByRole('button', { name: /^Running 2 actions/ })).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ const closed = parts.map(({ part, idx }) => ({
+ idx,
+ part:
+ part.type === ContentTypes.TOOL_CALL
+ ? { ...part, tool_call: { ...part.tool_call, runStepStatus: 'cancelled' as const } }
+ : part,
+ }));
+ rerender(
+ <RecoilRoot>
+ <ToolCallGroup {...props} parts={closed} />
+ </RecoilRoot>,
+ );
+ expect(screen.getByRole('button', { name: /^Ran 2 actions/ })).toBeInTheDocument();
+ expect(screen.queryByText(/^Preparing /)).not.toBeInTheDocument();
+ });
+});
+
+describe('legacy function preparation groups', () => {
+ it('prepares partial function arguments, then runs and settles using each call’s signals', () => {
+ const legacy = (id: string, args: string, progress = 0.1): TMessageContentParts => ({
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ id,
+ type: ToolCallTypes.FUNCTION,
+ function: { name: 'lookup', arguments: args, output: '' },
+ progress,
+ },
+ });
+ const props = (firstArgs: string, secondArgs: string, progress = 0.1) => ({
+ parts: [
+ { part: legacy('first', firstArgs, progress), idx: 0 },
+ { part: legacy('second', secondArgs, progress), idx: 1 },
+ ],
+ isSubmitting: true,
+ isLast: true,
+ showThinking: false,
+ lastContentIdx: 1,
+ renderPart: (_part: TMessageContentParts, idx: number) => <div key={idx} />,
+ });
+ const { rerender } = renderGroup(props('{"query":"first', '{"query":"second'));
+ fireEvent.click(screen.getByRole('button', { name: /^Preparing 2 actions/ }));
+ expect(screen.getByRole('button', { name: /^Preparing 2 actions/ })).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ rerender(
+ <RecoilRoot>
+ <ToolCallGroup {...props('{"query":"first"}', '{"query":"second')} />
+ </RecoilRoot>,
+ );
+ expect(screen.getByRole('button', { name: /^Running 2 actions/ })).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ rerender(
+ <RecoilRoot>
+ <ToolCallGroup {...props('{"query":"first', '{"query":"second', 1)} />
+ </RecoilRoot>,
+ );
+ expect(screen.getByRole('button', { name: /^Ran 2 actions/ })).toBeInTheDocument();
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/__tests__/preparation.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/preparation.test.tsx
new file mode 100644
index 0000000000..2fca482947
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/__tests__/preparation.test.tsx
@@ -0,0 +1,79 @@
+import React from 'react';
+import { render, screen } from '@testing-library/react';
+import type { ToolPreparationInput } from '../preparation';
+import { isToolCallPreparing, ToolPreparation } from '../preparation';
+import { areToolCallArgsComplete } from '../Parts/parseJsonField';
+import ProgressText from '../ProgressText';
+
+jest.mock('~/hooks', () => ({
+ useLocalize: () => (key: string, values?: Record<string, string>) =>
+ key === 'com_ui_tool_preparing' ? `Preparing ${values?.[0]}` : key,
+}));
+
+const partialArgs = '{"intent":"Checking the database","query":"SELECT';
+
+const prepare = (overrides: Partial<ToolPreparationInput> = {}) =>
+ isToolCallPreparing({ args: partialArgs, ...overrides });
+
+describe('tool preparation', () => {
+ it.each([undefined, '', '{', partialArgs, '{"code":"echo }'])(
+ 'keeps incomplete args %s in preparation',
+ (args) => expect(prepare({ args })).toBe(true),
+ );
+
+ it.each(['{}', '{"query":"SELECT 1"}', { query: 'SELECT 1' }])(
+ 'uses complete legacy args %s as the execution fallback',
+ (args) => expect(prepare({ args })).toBe(false),
+ );
+
+ it('waits for explicit dispatch on a measured call even after args become valid JSON', () => {
+ expect(prepare({ args: '{}', toolPreparationStartedAt: 0 })).toBe(true);
+ expect(prepare({ toolPreparationStartedAt: 0, toolDispatchedAt: 100 })).toBe(false);
+ });
+
+ it.each([
+ { output: 'result' },
+ { progress: 1 },
+ { runStepStatus: 'completed' as const },
+ { runStepStatus: 'failed' as const },
+ { runStepStatus: 'cancelled' as const },
+ { toolDispatchedAt: 0 },
+ ])('never demotes execution or a settled call to preparation: %s', (signal) => {
+ expect(prepare({ toolPreparationStartedAt: 0, ...signal })).toBe(false);
+ });
+
+ it('does not confuse a trailing brace inside an unfinished string with complete args', () => {
+ expect(areToolCallArgsComplete('{"code":"echo }')).toBe(false);
+ expect(areToolCallArgsComplete('{"code":"echo }"} ')).toBe(true);
+ });
+
+ it('shows preparation before dispatch and the authored execution label afterwards', () => {
+ const call = { name: 'lookup', args: partialArgs, toolPreparationStartedAt: 0 };
+ const card = (overrides: Partial<ToolPreparationInput> = {}, submitting = true) => (
+ <ToolPreparation call={{ ...call, ...overrides }} isSubmitting={submitting}>
+ <ProgressText phase="running" inProgressText="Checking the database" finishedText="Done" />
+ </ToolPreparation>
+ );
+ const { rerender } = render(card());
+ expect(screen.getByRole('button')).toHaveTextContent('Preparing lookup');
+ rerender(card({ args: '{}' }));
+ expect(screen.getByRole('button')).toHaveTextContent('Preparing lookup');
+ rerender(card({ toolDispatchedAt: 100 }));
+ expect(screen.getByRole('button')).toHaveTextContent('Checking the database');
+ rerender(card({}, false));
+ expect(screen.queryByText('Preparing lookup')).not.toBeInTheDocument();
+ });
+
+ it.each(['failed', 'cancelled', 'completed'] as const)(
+ 'does not overwrite a %s verdict with preparation',
+ (phase) => {
+ render(
+ <ToolPreparation call={{ name: 'lookup', args: partialArgs }} isSubmitting>
+ <ProgressText phase={phase} inProgressText="Running lookup" finishedText="Settled" />
+ </ToolPreparation>,
+ );
+ expect(screen.getByRole('button')).toHaveTextContent('Settled');
+ expect(screen.queryByText('Preparing lookup')).not.toBeInTheDocument();
+ },
+ );
+});
diff --git a/client/src/components/Chat/Messages/Content/live.ts b/client/src/components/Chat/Messages/Content/live.ts
index 30a84e33db..0f43fe5797 100644
--- a/client/src/components/Chat/Messages/Content/live.ts
+++ b/client/src/components/Chat/Messages/Content/live.ts
@@ -133,6 +133,14 @@ function toolCallLine(
generic: false,
};
}
+ if (meta?.preparing === true) {
+ return {
+ text: label
+ ? localize('com_ui_tool_preparing', { 0: label })
+ : localize('com_assistants_preparing_action'),
+ generic: true,
+ };
+ }
if (intent != null) {
return { text: intent, generic: false };
}
@@ -273,6 +281,7 @@ function isAwaitingStartup(
!meta.failed &&
!meta.cancelled &&
meta.background == null &&
+ !meta.preparing &&
getToolCallIntent(toolCall.args) == null
);
}
diff --git a/client/src/components/Chat/Messages/Content/outcome.ts b/client/src/components/Chat/Messages/Content/outcome.ts
index e4899a17c9..3d321d057e 100644
--- a/client/src/components/Chat/Messages/Content/outcome.ts
+++ b/client/src/components/Chat/Messages/Content/outcome.ts
@@ -6,6 +6,7 @@ import type {
FunctionToolCall,
TMessageContentParts,
} from 'librechat-data-provider';
+import type { ToolPreparationInput } from './preparation';
import { backgroundTaskOutcome, parseBackgroundTaskOutput } from './Parts/background';
import { parseBackgroundHandle, splitBackgroundAttachments } from './Parts/handle';
import { resolveToolCallPhase } from '~/utils/toolCallPhase';
@@ -13,6 +14,7 @@ import { isMemoryFailureOutput } from './Parts/MemoryCall';
import { filterAttachmentsForPart } from '~/utils/map';
import { isBashProgrammaticToolCall } from './routing';
import { parseCommandOutput } from './Parts/command';
+import { isToolCallPreparing } from './preparation';
import { isError } from './ToolOutput';
/**
@@ -29,12 +31,20 @@ export interface ToolMeta {
hasOutput: boolean;
failed: boolean;
cancelled: boolean;
+ preparing?: boolean;
/** Set for a detached task: its dispatch step is long closed, so whether the
* WORK is still going is a separate fact — the cards say "Running in
* background" until a status marker or harvested files arrive. */
background?: 'running' | 'finished';
}
+function isPreparingTool(
+ call: ToolPreparationInput,
+ outcome: Pick<ToolMeta, 'hasOutput' | 'failed' | 'cancelled'>,
+): boolean {
+ return !outcome.hasOutput && !outcome.failed && !outcome.cancelled && isToolCallPreparing(call);
+}
+
function hasFailedOutput(output: unknown): boolean {
return typeof output === 'string' && isError(output);
}
@@ -160,17 +170,19 @@ export function getToolMeta(
tc.backgroundTask?.cancelled === true ||
(backgroundHandle != null && backgroundStatus === 'cancelled') ||
polledOutcome === 'cancelled';
+ const outcome = resolveOutcome(
+ backgroundCancelled ? 'cancelled' : runStepStatus,
+ completed,
+ failedOutput || backgroundFailed || polledOutcome === 'failed',
+ );
return {
name,
iconName,
...(backgroundHandle != null && {
background: backgroundSettled ? ('finished' as const) : ('running' as const),
}),
- ...resolveOutcome(
- backgroundCancelled ? 'cancelled' : runStepStatus,
- completed,
- failedOutput || backgroundFailed || polledOutcome === 'failed',
- ),
+ ...outcome,
+ ...(isPreparingTool(tc, outcome) && { preparing: true }),
};
}
@@ -194,10 +206,24 @@ export function getToolMeta(
if (toolCall.type === ToolCallTypes.FUNCTION && ToolCallTypes.FUNCTION in toolCall) {
const fn = (toolCall as FunctionToolCall).function;
+ const outcome = resolveOutcome(
+ runStepStatus,
+ !!fn.output || toolCall.progress === 1,
+ hasFailedOutput(fn.output),
+ );
+ const call = {
+ args: fn.arguments as string,
+ output: fn.output,
+ progress: toolCall.progress,
+ runStepStatus,
+ toolPreparationStartedAt: toolCall.toolPreparationStartedAt,
+ toolDispatchedAt: toolCall.toolDispatchedAt,
+ };
return {
name: fn.name,
iconName: fn.name,
- ...resolveOutcome(runStepStatus, !!fn.output, hasFailedOutput(fn.output)),
+ ...outcome,
+ ...(isPreparingTool(call, outcome) && { preparing: true }),
};
}
diff --git a/client/src/components/Chat/Messages/Content/preparation.tsx b/client/src/components/Chat/Messages/Content/preparation.tsx
new file mode 100644
index 0000000000..816aabedea
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/preparation.tsx
@@ -0,0 +1,57 @@
+import { createContext, useContext } from 'react';
+import { Constants, actionDelimiter } from 'librechat-data-provider';
+import type { PartMetadata } from 'librechat-data-provider';
+import { areToolCallArgsComplete } from './Parts/parseJsonField';
+import { getToolDisplayLabel } from '~/utils/toolLabels';
+import { useLocalize } from '~/hooks';
+
+export interface ToolPreparationInput
+ extends Pick<PartMetadata, 'toolPreparationStartedAt' | 'toolDispatchedAt' | 'runStepStatus'> {
+ args?: string | Record<string, unknown>;
+ output?: string | null;
+ progress?: number;
+}
+
+/** Dispatch and result signals outrank argument completeness on legacy and resumed calls. */
+export function isToolCallPreparing(call: ToolPreparationInput): boolean {
+ if (
+ call.toolDispatchedAt != null ||
+ call.runStepStatus != null ||
+ (call.output?.length ?? 0) > 0 ||
+ (call.progress ?? 0) >= 1
+ ) {
+ return false;
+ }
+ return call.toolPreparationStartedAt != null || !areToolCallArgsComplete(call.args);
+}
+
+const ToolPreparationContext = createContext<string | undefined>(undefined);
+
+export function useToolPreparation(): string | undefined {
+ return useContext(ToolPreparationContext);
+}
+
+/** The host supplies the call's preparation state without widening every specialized card's props. */
+export function ToolPreparation({
+ call,
+ isSubmitting,
+ children,
+}: {
+ call: ToolPreparationInput & { name?: string };
+ isSubmitting: boolean;
+ children: React.ReactNode;
+}) {
+ const localize = useLocalize();
+ const name = call.name ?? '';
+ let text: string | undefined;
+ /** Generic integration cards own their configured MCP/action name parsing. */
+ const usesIntegrationName =
+ name.includes(Constants.mcp_delimiter) || name.includes(actionDelimiter);
+ if (isSubmitting && !usesIntegrationName && isToolCallPreparing(call)) {
+ const label = getToolDisplayLabel(name, localize);
+ text = label
+ ? localize('com_ui_tool_preparing', { 0: label })
+ : localize('com_assistants_preparing_action');
+ }
+ return <ToolPreparationContext.Provider value={text}>{children}</ToolPreparationContext.Provider>;
+}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 80e0258aa2..b5aea22a9c 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -275,6 +275,7 @@
"com_assistants_name_placeholder": "Optional: The name of the assistant",
"com_assistants_non_retrieval_model": "File search is not enabled on this model. Please select another model.",
"com_assistants_retrieval": "Retrieval",
+ "com_assistants_preparing_action": "Preparing action",
"com_assistants_running_action": "Running action",
"com_assistants_running_var": "Running {{0}}",
"com_assistants_search_name": "Search assistants by name",
@@ -2364,6 +2365,8 @@
"com_ui_running": "Running...",
"com_ui_running_chats": "Running",
"com_ui_running_command": "Running command",
+ "com_ui_preparing_n_actions": "Preparing {{0}} actions",
+ "com_ui_preparing_one_action": "Preparing 1 action",
"com_ui_running_n_actions": "Running {{0}} actions",
"com_ui_running_n_agents": "Running {{0}} agents",
"com_ui_sandbox_starting": "Starting sandbox environment",