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

🪜 feat: Title an Open Activity Fold and Reach Failed Calls in One Click (#16390)

Danny Avilaa047548fa7c6
diff --git a/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx b/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx
index 315dbb886e..0ca2a73cfe 100644
--- a/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx
+++ b/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx
@@ -21,13 +21,19 @@ import {
scheduleMessageContentLayoutReconcile,
EXPAND_TRANSITION,
} from '~/hooks';
-import { getLiveActivity, getSpanIconNames, LIVE_ACTIVITY_THROTTLE_MS } from './live';
+import {
+ getFailedLines,
+ getLiveActivity,
+ getSpanIconNames,
+ LIVE_ACTIVITY_THROTTLE_MS,
+} from './live';
+import { FailedRevealContext, FailedRevealPill, useFailedRevealTrigger } from './reveal';
+import { FOLD_RAIL_CLASSES, ROW_GLYPH_SLOT, TOOL_ROW_CLASSES } from './rows';
import useSmoothStreaming from '~/hooks/Messages/useSmoothStreaming';
import useThrottledValue from '~/hooks/Messages/useThrottledValue';
import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';
import { getActivityLabelText } from '~/utils/activityLabels';
import { getOutcomeStatus, summarizeSpan } from './outcome';
-import { ROW_GLYPH_SLOT, TOOL_ROW_CLASSES } from './rows';
import { sandboxStartingByToolCallId } from '~/store';
import { StackedToolIcons } from './ToolOutput';
import { getSourceDomains } from './sources';
@@ -345,24 +351,19 @@ function LivePhaseHeader({
* hidden group header carries the same counts in the same words. */
const { failed, cancelled } = activity.outcome;
const combo = painted.comboCount > 1 ? `×${painted.comboCount}` : '';
- const detail = useMemo(() => {
- const notes: string[] = [];
- if (failed > 0) {
- notes.push(
- localize(failed === 1 ? 'com_ui_one_action_failed' : 'com_ui_n_actions_failed', {
+ const failedNote =
+ failed > 0
+ ? localize(failed === 1 ? 'com_ui_one_action_failed' : 'com_ui_n_actions_failed', {
0: String(failed),
- }),
- );
- }
- if (cancelled > 0) {
- notes.push(
- localize(cancelled === 1 ? 'com_ui_one_action_cancelled' : 'com_ui_n_actions_cancelled', {
+ })
+ : '';
+ const cancelledNote =
+ cancelled > 0
+ ? localize(cancelled === 1 ? 'com_ui_one_action_cancelled' : 'com_ui_n_actions_cancelled', {
0: String(cancelled),
- }),
- );
- }
- return notes.join(' · ');
- }, [failed, cancelled, localize]);
+ })
+ : '';
+ const detail = [failedNote, cancelledNote].filter(Boolean).join(' · ');
/** Announcements have their own identity, apart from the ticker's. A line
* is spoken once, when it is left and therefore complete; an outcome is
@@ -437,16 +438,83 @@ function LivePhaseHeader({
className="shrink-0 text-xs font-normal text-text-warning"
data-testid="live-phase-outcome"
>
- {/** The verdict is the span's, not the newest line's, so it keeps its
+ {/** The failure count is spoken here, as part of the header's name,
+ * and SHOWN by the pill beside the header, which is also the way to
+ * the failed rows. Only a stop count has no pill and stays visible.
+ * The verdict is the span's, not the newest line's, so it keeps its
* own separator from whatever the row happens to be saying. */}
- <span className="mr-1 text-text-secondary">·</span>
- <span>{detail}</span>
+ {failedNote !== '' && <span className="sr-only">· {failedNote}</span>}
+ {cancelledNote !== '' && (
+ <>
+ <span className="mr-1 text-text-secondary">·</span>
+ <span>{cancelledNote}</span>
+ </>
+ )}
</span>
)}
</>
);
}
+/**
+ * The first failed call of a collapsed card, on a row of its own beneath the
+ * header, the way the cursor row peeks while streaming: the failure is
+ * readable, and one click away, without unfolding. Its own component so only
+ * a collapsed card with a failure pays for the line's lookups.
+ */
+function FailedPeek({
+ parts,
+ attachmentsById,
+ count,
+ onReveal,
+}: {
+ parts: ReadonlyArray<TMessageContentParts | undefined>;
+ attachmentsById: Record<string, TAttachment[] | undefined>;
+ count: number;
+ onReveal: () => void;
+}) {
+ const localize = useLocalize();
+ const mcpServerNames = useMCPServerNames();
+ const first = useMemo(
+ () => getFailedLines(parts, localize, mcpServerNames, attachmentsById)[0],
+ [parts, localize, mcpServerNames, attachmentsById],
+ );
+ if (first == null) {
+ return null;
+ }
+ return (
+ <button
+ type="button"
+ className={cn(
+ TOOL_ROW_CLASSES,
+ 'w-full pl-6 text-left text-text-secondary hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-border-heavy',
+ )}
+ onClick={onReveal}
+ data-testid="activity-phase-failed-peek"
+ >
+ <span className={cn(ROW_GLYPH_SLOT, 'text-status-error')} aria-hidden="true">
+ <TriangleAlert size={14} />
+ </span>
+ <span className="tool-status-text flex min-w-0 items-center gap-2">
+ <span className="min-w-0 max-w-full shrink-0 truncate font-medium text-status-error">
+ {first.text}
+ </span>
+ {first.detail !== '' && (
+ <span className="min-w-0 shrink truncate font-normal">{first.detail}</span>
+ )}
+ </span>
+ {count > 1 && (
+ <span className="shrink-0 text-xs font-normal">
+ {localize('com_ui_plus_n_more', { 0: String(count - 1) })}
+ </span>
+ )}
+ <span className="ml-auto shrink-0 text-xs font-medium underline underline-offset-2">
+ {localize('com_ui_show_error')}
+ </span>
+ </button>
+ );
+}
+
export default function ActivityPhaseGroup({
labelPart,
children,
@@ -483,6 +551,16 @@ export default function ActivityPhaseGroup({
const isLive = liveParts != null;
const label = getActivityLabelText(labelPart);
const hasFailure = labelPart.status === 'failed' || labelPart.status === 'partial';
+ const outcomeParts = spanParts ?? liveParts;
+ const attachmentsById = useMemo(() => mapAttachments(attachments ?? []), [attachments]);
+ /** The span's failed calls, for the peek under a collapsed header and the
+ * pill beside it. Read from the same parts the header's glyph and live
+ * line read, so the three can never disagree about the count. */
+ const failedCount = useMemo(
+ () => (outcomeParts == null ? 0 : summarizeSpan(outcomeParts, attachmentsById).failed),
+ [outcomeParts, attachmentsById],
+ );
+
/** Already `smoothStreaming && !reducedMotion` — it owns the media query, so
* a second subscription here would install one `matchMedia` listener per
* phase card without changing the answer. */
@@ -535,6 +613,9 @@ export default function ActivityPhaseGroup({
isExpanded,
hasPendingApproval,
);
+ const { value: revealValue, requestReveal } = useFailedRevealTrigger(
+ isExpanded && shouldRenderBody,
+ );
useEffect(() => {
if (!foldsIn || userOverrideRef.current) {
@@ -580,6 +661,36 @@ export default function ActivityPhaseGroup({
setIsExpanded(!isExpanded);
}, [mountBody, isExpanded, onExpansionChange]);
+ /** One click to the error from a closed card: open the card the way a
+ * toggle would, then ask every failed row below to open its own panel. */
+ const handleRevealFailed = useCallback(() => {
+ userOverrideRef.current = true;
+ cancelEntranceRef.current?.();
+ cancelEntranceRef.current = null;
+ mountBody();
+ setIsSettled(true);
+ if (!isExpanded) {
+ onExpansionChange?.(true);
+ setIsExpanded(true);
+ }
+ requestReveal();
+ }, [mountBody, isExpanded, onExpansionChange, requestReveal]);
+
+ /** An open card is titled by its stable label: the rows themselves carry
+ * the live line now, and a header that kept tickering above them would
+ * swap its text under a reader who is looking at the list. A live span
+ * with no label yet keeps the live line, which is all it has. */
+ const showLiveHeader = isLive && (!isExpanded || label.length === 0);
+ const peek =
+ hasContent && !isExpanded && failedCount > 0 && outcomeParts != null ? (
+ <FailedPeek
+ parts={outcomeParts}
+ attachmentsById={attachmentsById}
+ count={failedCount}
+ onReveal={handleRevealFailed}
+ />
+ ) : null;
+
/** Only the folding entrance drives the header off its natural height.
* History and reduced-motion render the plain, unstyled row. */
const headerStyle = useMemo<CSSProperties | undefined>(() => {
@@ -662,8 +773,14 @@ export default function ActivityPhaseGroup({
<span className="sr-only" role="status" data-testid="activity-phase-announcer">
{announcement}
</span>
- <div style={headerStyle}>
- <div className="overflow-hidden">
+ <div
+ style={headerStyle}
+ /** Pinned while open, so a run long enough to scroll keeps its name
+ * at the top of the viewport. The containing block is this card, so
+ * the header stops pinning where its own rows end. */
+ className={cn(isExpanded && 'sticky top-0 z-[1] bg-presentation')}
+ >
+ <div className="flex items-center gap-2 overflow-hidden">
<Button
variant="ghost"
type="button"
@@ -673,7 +790,12 @@ export default function ActivityPhaseGroup({
* keyboard users with no focus indicator. The ghost variant
* supplies it today; stating it here keeps the requirement with
* the element that depends on it. */
- className="flex h-auto min-h-7 w-full items-center justify-start gap-2 rounded-none bg-transparent p-0 py-1 text-left font-medium text-text-secondary hover:bg-transparent hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-border-heavy focus-visible:ring-offset-0"
+ className={cn(
+ 'flex h-auto min-h-7 min-w-0 flex-1 items-center justify-start gap-2 rounded-none bg-transparent p-0 py-1 text-left font-medium text-text-secondary hover:bg-transparent hover:text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-border-heavy focus-visible:ring-offset-0',
+ /** The open card's title: the one semibold, primary-colour line
+ * in the fold, so the rows under it read as its contents. */
+ isExpanded && 'font-semibold text-text-primary',
+ )}
onClick={handleToggle}
aria-expanded={isExpanded}
aria-controls={panelId}
@@ -682,12 +804,12 @@ export default function ActivityPhaseGroup({
* is named by that line ALONE: the polite region beside it holds
* the previous line, and `sr-only` text still counts toward a
* button's computed name. */
- aria-label={isLive ? undefined : label}
+ aria-label={showLiveHeader ? undefined : label}
/** Unresolved ids are skipped, so one list covers a row with no
* multiplier and no outcome note as well as a row with both. */
- aria-labelledby={isLive ? `${lineId} ${comboId} ${detailId}` : undefined}
+ aria-labelledby={showLiveHeader ? `${lineId} ${comboId} ${detailId}` : undefined}
>
- {isLive ? (
+ {showLiveHeader ? (
<LivePhaseHeader
parts={liveParts}
animate={smoothStreaming}
@@ -699,8 +821,8 @@ export default function ActivityPhaseGroup({
/>
) : (
<>
- {spanParts != null && !hasFailure ? (
- <SpanGlyph parts={spanParts} attachments={attachments} />
+ {outcomeParts != null && !hasFailure ? (
+ <SpanGlyph parts={outcomeParts} attachments={attachments} />
) : (
<PhaseGlyph failed={hasFailure} />
)}
@@ -715,8 +837,10 @@ export default function ActivityPhaseGroup({
aria-hidden="true"
/>
</Button>
+ <FailedRevealPill count={failedCount} onReveal={handleRevealFailed} />
</div>
</div>
+ {peek}
<div
id={panelId}
style={expandStyle}
@@ -725,8 +849,10 @@ export default function ActivityPhaseGroup({
data-testid="activity-phase-panel"
>
{shouldRenderBody && (
- <div className="overflow-hidden" ref={expandRef}>
- {children}
+ <div className={cn('overflow-hidden', FOLD_RAIL_CLASSES)} ref={expandRef}>
+ <FailedRevealContext.Provider value={revealValue}>
+ {children}
+ </FailedRevealContext.Provider>
</div>
)}
</div>
diff --git a/client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx b/client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx
index e008f7130a..e3e300d4ab 100644
--- a/client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx
+++ b/client/src/components/Chat/Messages/Content/AskUserQuestionCall.tsx
@@ -150,7 +150,7 @@ export default function AskUserQuestionCall({
<>
<div className={TOOL_ROW_CLASSES} data-testid="ask-user-question-call">
<ProgressText
- phase="completed"
+ phase={terminalFailure ? 'failed' : 'completed'}
onClick={toggleExpanded}
inProgressText={statusLabel}
finishedText={statusLabel}
diff --git a/client/src/components/Chat/Messages/Content/Part.tsx b/client/src/components/Chat/Messages/Content/Part.tsx
index 5948a1a992..59e0625503 100644
--- a/client/src/components/Chat/Messages/Content/Part.tsx
+++ b/client/src/components/Chat/Messages/Content/Part.tsx
@@ -7,7 +7,7 @@ import {
imageGenTools,
isImageVisionTool,
} from 'librechat-data-provider';
-import type { TMessageContentParts, TAttachment } from 'librechat-data-provider';
+import type { TMessageContentParts, TAttachment, PartMetadata } from 'librechat-data-provider';
import {
ImageGen,
ExecuteCode,
@@ -34,6 +34,7 @@ import {
import { getAskUserQuestionPart } from '~/utils/approval';
import AskUserQuestionCall from './AskUserQuestionCall';
import { isBashProgrammaticToolCall } from './routing';
+import { isError } from './ToolOutput/OutputRenderer';
import { useMessageContext } from '~/Providers';
import { ErrorMessage } from './MessageContent';
import AskUserQuestion from './AskUserQuestion';
@@ -46,6 +47,13 @@ import WebSearch from './WebSearch';
import ToolCall from './ToolCall';
import Image from './Image';
+const isFailedImageCall = (
+ output: string | null | undefined,
+ runStepStatus: PartMetadata['runStepStatus'],
+): boolean =>
+ runStepStatus !== 'cancelled' &&
+ (runStepStatus === 'failed' || (typeof output === 'string' && isError(output)));
+
type PartProps = {
part?: TMessageContentParts;
isLast?: boolean;
@@ -251,6 +259,22 @@ const Part = memo(function Part({
toolCall.name === 'image_edit_oai' ||
toolCall.name === 'gemini_image_gen'
) {
+ if (isFailedImageCall(toolCall.output, toolCall.runStepStatus)) {
+ return (
+ <ToolCall
+ name={toolCall.name}
+ args={toolCall.args ?? ''}
+ output={toolCall.output}
+ initialProgress={toolCall.progress ?? 0.1}
+ isSubmitting={isSubmitting}
+ isLast={isLast}
+ runStepStatus={toolCall.runStepStatus}
+ attachments={attachments}
+ hideAttachments={hideAttachments}
+ onExpand={onToolExpand}
+ />
+ );
+ }
return (
<ImageGen
initialProgress={toolCall.progress ?? 0.1}
@@ -477,6 +501,22 @@ const Part = memo(function Part({
ToolCallTypes.FUNCTION in toolCall &&
imageGenTools.has(toolCall.function.name)
) {
+ if (isFailedImageCall(toolCall.function.output, toolCall.runStepStatus)) {
+ return (
+ <ToolCall
+ name={toolCall.function.name}
+ args={toolCall.function.arguments as string}
+ output={toolCall.function.output}
+ initialProgress={toolCall.progress ?? 0.1}
+ isSubmitting={isSubmitting}
+ isLast={isLast}
+ runStepStatus={toolCall.runStepStatus}
+ attachments={attachments}
+ hideAttachments={hideAttachments}
+ onExpand={onToolExpand}
+ />
+ );
+ }
return (
<ImageGen
initialProgress={toolCall.progress ?? 0.1}
diff --git a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx
index a58a27d5f4..da7f31a633 100644
--- a/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/SubagentCall.tsx
@@ -21,10 +21,12 @@ import { MessageContext } from '~/Providers/MessageContext';
import { useShareContext } from '~/Providers/ShareContext';
import MessageIcon from '~/components/Share/MessageIcon';
import { parseSubagentBackgroundHandle } from './handle';
+import { isError } from '../ToolOutput/OutputRenderer';
import { useAgentsMapContext } from '~/Providers';
import { useMCPServerNames } from '~/hooks/MCP';
import { AttachmentGroup } from './Attachment';
import { useToolCallIntent } from './intent';
+import { useFailedReveal } from '../reveal';
import { cn, parseToolName } from '~/utils';
import { useLocalize } from '~/hooks';
@@ -218,7 +220,10 @@ export default function SubagentCall({
* status is the authority on why it stopped.
*/
const hasError =
- (progress?.status === 'error' || runStepStatus === 'failed') && runStepStatus !== 'cancelled';
+ runStepStatus !== 'cancelled' &&
+ (progress?.status === 'error' ||
+ runStepStatus === 'failed' ||
+ (typeof output === 'string' && isError(output)));
const finished = isClosed
? runStepStatus !== 'cancelled'
: initialProgress >= 1 || progress?.status === 'stop' || hasError;
@@ -374,6 +379,15 @@ export default function SubagentCall({
if (!canOpenDetails || openPanel == null) return;
openPanel(panelSelection);
}, [canOpenDetails, openPanel, panelSelection]);
+ const revealFailure = useCallback(
+ (claimFocus: () => boolean) => {
+ if (claimFocus()) {
+ openDetails();
+ }
+ },
+ [openDetails],
+ );
+ useFailedReveal(hasError && canOpenDetails, revealFailure);
return (
<>
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.tsx
index 10599f64a1..51f42d3772 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
@@ -3,7 +3,7 @@ import { RecoilRoot } from 'recoil';
import { useAtomValue, useStore } from 'jotai';
import { MemoryRouter } from 'react-router-dom';
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react';
-import type { SubagentUpdateEvent, SubagentIdentity } from 'librechat-data-provider';
+import type { SubagentUpdateEvent, SubagentIdentity, PartMetadata } from 'librechat-data-provider';
import type {
SubagentAggregatorState,
SubagentContentPart,
@@ -23,6 +23,7 @@ import {
} from '~/components/Chat/Subagents/state';
import SubagentCall, { SUBAGENT_TICKER_THROTTLE_MS } from '../SubagentCall';
import { MessageContext } from '~/Providers/MessageContext';
+import { FailedRevealContext } from '../../reveal';
import { ChatSurfaceHarness } from 'test/harness';
const mockMCPServerNames: string[] = [];
@@ -121,6 +122,7 @@ function renderWithState(args: {
output?: string;
toolArgs?: Record<string, unknown>;
subagentIdentity?: SubagentIdentity;
+ runStepStatus?: PartMetadata['runStepStatus'];
}) {
const setter = { current: null as null | ((next: SubagentProgress | null) => void) };
let selection: ActiveSubagentPanel | null = null;
@@ -137,7 +139,7 @@ function renderWithState(args: {
selection = useAtomValue(activeSubagentPanel);
return null;
};
- const rendered = render(
+ const tree = (tick: number) => (
<MemoryRouter>
<ChatSurfaceHarness>
<RecoilRoot>
@@ -150,24 +152,29 @@ function renderWithState(args: {
isExpanded: false,
}}
>
- <SubagentCall
- toolCallId={args.toolCallId}
- initialProgress={args.initialProgress}
- isSubmitting={args.isSubmitting ?? false}
- args={args.toolArgs ?? { subagent_type: 'self', description: 'compute' }}
- output={args.output}
- subagentIdentity={args.subagentIdentity}
- />
+ <FailedRevealContext.Provider value={{ tick, claimFocus: () => true }}>
+ <SubagentCall
+ toolCallId={args.toolCallId}
+ initialProgress={args.initialProgress}
+ isSubmitting={args.isSubmitting ?? false}
+ args={args.toolArgs ?? { subagent_type: 'self', description: 'compute' }}
+ output={args.output}
+ runStepStatus={args.runStepStatus}
+ subagentIdentity={args.subagentIdentity}
+ />
+ </FailedRevealContext.Provider>
</MessageContext.Provider>
</RecoilRoot>
</ChatSurfaceHarness>
- </MemoryRouter>,
+ </MemoryRouter>
);
+ const rendered = render(tree(0));
act(() => setter.current?.(args.progress ?? null));
return {
...rendered,
getSelection: () => selection,
setProgress: (next: SubagentProgress | null) => act(() => setter.current?.(next)),
+ reveal: () => rendered.rerender(tree(1)),
};
}
@@ -260,6 +267,37 @@ describe('SubagentCall', () => {
expect(screen.getByText(label)).toBeInTheDocument();
});
+ it.each([
+ { output: 'Error: tool call failed: child crashed', runStepStatus: 'completed' as const },
+ { output: 'Partial output', runStepStatus: 'failed' as const },
+ ])('opens a failed subagent panel from its parent reveal (%p)', (failure) => {
+ const rendered = renderWithState({
+ toolCallId: 'failed-child',
+ initialProgress: 1,
+ ...failure,
+ });
+ expect(screen.getByRole('button', { name: 'Agent errored' })).toBeInTheDocument();
+ expect(rendered.getSelection()).toBeNull();
+
+ rendered.reveal();
+
+ expect(rendered.getSelection()).toEqual(
+ expect.objectContaining({ toolCallId: 'failed-child' }),
+ );
+ });
+
+ it('does not reveal a cancelled subagent with error-shaped output', () => {
+ const rendered = renderWithState({
+ toolCallId: 'cancelled-child',
+ initialProgress: 1,
+ output: 'Error: tool call failed: abort',
+ runStepStatus: 'cancelled',
+ });
+ expect(screen.getByRole('button', { name: 'Cancelled agent' })).toBeInTheDocument();
+ rendered.reveal();
+ expect(rendered.getSelection()).toBeNull();
+ });
+
it('keeps the compact semantic ticker while selecting the shared panel', async () => {
const progress = progressFromEvents({
subagentRunId: 'child-run',
diff --git a/client/src/components/Chat/Messages/Content/ProgressText.tsx b/client/src/components/Chat/Messages/Content/ProgressText.tsx
index 0ae3e70c1c..fba3dcc3cc 100644
--- a/client/src/components/Chat/Messages/Content/ProgressText.tsx
+++ b/client/src/components/Chat/Messages/Content/ProgressText.tsx
@@ -1,3 +1,4 @@
+import { useCallback, useRef } from 'react';
import { ChevronDown } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import * as Popover from '@radix-ui/react-popover';
@@ -6,6 +7,7 @@ import { isReportableRunStepDuration } from 'librechat-data-provider';
import type { ToolCallPhase } from '~/utils/toolCallPhase';
import { cn, getRunStepDurationLabels } from '~/utils';
import CancelledIcon from './CancelledIcon';
+import { useFailedReveal } from './reveal';
import { ROW_GLYPH_SLOT } from './rows';
import { useLocalize } from '~/hooks';
@@ -18,10 +20,28 @@ const wrapperClass =
const contentClass =
'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 }) => {
+/** A failed row is marked at its left edge, in the rail's column when the row
+ * sits under a header and in the gutter when it stands alone, so a failure
+ * is findable by shape before its text is read. A pseudo-element rather than
+ * a border: the row's content is absolutely positioned against the padding
+ * box, so a border would push it and change the row's geometry. */
+const failedStripeClass =
+ "before:absolute before:-left-3 before:top-0 before:h-full before:w-0.5 before:rounded-full before:bg-status-error before:content-['']";
+
+const Wrapper = ({
+ popover,
+ failed,
+ rootRef,
+ children,
+}: {
+ popover: boolean;
+ failed: boolean;
+ rootRef: React.RefObject<HTMLDivElement>;
+ children: React.ReactNode;
+}) => {
if (popover) {
return (
- <div className={wrapperClass}>
+ <div className={cn(wrapperClass, failed && failedStripeClass)} ref={rootRef}>
<Popover.Trigger asChild>
<div className={contentClass} style={{ opacity: 1, transform: 'none' }}>
{children}
@@ -32,7 +52,7 @@ const Wrapper = ({ popover, children }: { popover: boolean; children: React.Reac
}
return (
- <div className={wrapperClass}>
+ <div className={cn(wrapperClass, failed && failedStripeClass)} ref={rootRef}>
<div className={contentClass} style={{ opacity: 1, transform: 'none' }}>
{children}
</div>
@@ -79,6 +99,32 @@ export default function ProgressText({
/** For locale-aware decimal formatting of the sub-10s duration value. */
const { i18n } = useTranslation();
const isRunning = phase === 'running';
+ const rootRef = useRef<HTMLDivElement>(null);
+ /** A header above asked for its failures. This control is the disclosure
+ * every card renders, so answering here reaches a failed bash, code,
+ * memory or file card the same as a generic one: open through the card's
+ * own toggle, and, for the one row the request lets take focus, land the
+ * reader on the labeled button rather than on a wrapper. */
+ const revealFailure = useCallback(
+ (claimFocus: () => boolean) => {
+ if (!isExpanded) {
+ onClick?.();
+ }
+ if (!claimFocus()) {
+ return;
+ }
+ const button = rootRef.current?.querySelector('button');
+ if (button == null) {
+ return;
+ }
+ if (typeof button.scrollIntoView === 'function') {
+ button.scrollIntoView({ block: 'nearest' });
+ }
+ button.focus({ preventScroll: true });
+ },
+ [isExpanded, onClick],
+ );
+ useFailedReveal(phase === 'failed' && hasInput, revealFailure);
/** Every branch below reads `phase`, so the label, the icon, the shimmer,
* the failure suffix and the duration cannot disagree about what state
@@ -99,7 +145,7 @@ export default function ProgressText({
: undefined;
return (
- <Wrapper popover={popover}>
+ <Wrapper popover={popover} failed={phase === 'failed'} rootRef={rootRef}>
<Button
type="button"
variant="ghost"
@@ -119,19 +165,35 @@ export default function ProgressText({
{icon}
</span>
)}
- <span className={cn(showShimmer ? 'shimmer' : '', 'min-w-0 truncate font-medium')}>
- {text}
- </span>
{/* The label names the card and stays whole; a subtitle can be
- arbitrary authored text (a question, a server name), so it takes
- essentially all of the shrink and ellipsizes instead of pushing
- the line past the message column. */}
- {subtitle && (
- <span className="min-w-0 shrink-[100] truncate font-normal text-text-secondary">
- {subtitle}
+ arbitrary authored text (a question, an error line), so it takes
+ ALL of the shrink and ellipsizes instead of pushing the line past
+ the message column. All, not most: a weighted share left the label
+ a fraction of a pixel short of its text, and that fraction is
+ enough for `truncate` to swap its last letters for an ellipsis.
+ The pair sits in its own shrinking box so the verdict, the
+ duration and the chevron after it never lose width: the box gives
+ up the subtitle first, and a label wider than the box truncates at
+ the box (`max-w-full`), not past the row. */}
+ <span className="flex min-w-0 items-center gap-2">
+ <span
+ className={cn(
+ showShimmer ? 'shimmer' : '',
+ 'min-w-0 max-w-full truncate font-medium',
+ subtitle && 'shrink-0',
+ )}
+ >
+ {text}
</span>
+ {subtitle && (
+ <span className="min-w-0 shrink truncate font-normal text-text-secondary">
+ {subtitle}
+ </span>
+ )}
+ </span>
+ {errorSuffix && (
+ <span className="shrink-0 font-normal text-status-error">· {errorSuffix}</span>
)}
- {errorSuffix && <span className="font-normal text-status-error">· {errorSuffix}</span>}
{duration && (
<>
{/* The compact form is the readable one on screen but a poor
@@ -140,7 +202,7 @@ export default function ProgressText({
Both live inside the button, so its accessible name carries
the duration — this is not an `aria-live` region and does not
re-announce. */}
- <span className="font-normal text-text-secondary" aria-hidden="true">
+ <span className="shrink-0 font-normal text-text-secondary" aria-hidden="true">
· {localize(duration.key, duration.values)}
</span>
<span className="sr-only">
@@ -152,7 +214,7 @@ export default function ProgressText({
<ChevronDown
className={cn(
disclosureChevronVariants({ expanded: isExpanded }),
- 'size-4 translate-y-[1px]',
+ 'size-4 shrink-0 translate-y-[1px]',
)}
aria-hidden="true"
/>
diff --git a/client/src/components/Chat/Messages/Content/ToolCall.tsx b/client/src/components/Chat/Messages/Content/ToolCall.tsx
index 272c35952d..63b97d03ec 100644
--- a/client/src/components/Chat/Messages/Content/ToolCall.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolCall.tsx
@@ -21,6 +21,7 @@ import ToolCallInfo from './ToolCallInfo';
import ProgressText from './ProgressText';
import { TOOL_ROW_CLASSES } from './rows';
import { ToolAuthWarning } from './auth';
+import { firstErrorLine } from './live';
import store from '~/store';
export default function ToolCall({
@@ -291,7 +292,14 @@ export default function ToolCall({
setShowInfo((prev) => !prev);
}, [mountBody, onExpand, showInfo]);
+ /** A failed row spends its subtitle on the error's first line: what went
+ * wrong is the fact the reader needs from that slot, ahead of which server
+ * the call went through. */
const subtitle = useMemo(() => {
+ const errorLine = phase === 'failed' ? firstErrorLine(output) : '';
+ if (errorLine.length > 0) {
+ return errorLine;
+ }
if (isMCPToolCall && mcpServerName) {
return localize('com_ui_via_server', { 0: mcpServerName });
}
@@ -299,7 +307,7 @@ export default function ToolCall({
return localize('com_ui_via_server', { 0: domain });
}
return undefined;
- }, [isMCPToolCall, mcpServerName, domain, localize]);
+ }, [phase, output, isMCPToolCall, mcpServerName, domain, localize]);
/** Model-authored live label, streamed as the first args key (injected by
* the `tool_intents` capability); persists as the settled label —
@@ -316,8 +324,12 @@ export default function ToolCall({
* a screen-reader user the opposite of what the card shows.
*/
if (phase === 'failed') {
- return function_name
- ? localize('com_ui_failed_subject', { 0: function_name })
+ /** The subject is the work the call named for itself, as on the live
+ * header and the collapsed card's peek, so the same failure reads the
+ * same wherever it is summarized. */
+ const subject = intent ?? displayFunctionName;
+ return subject
+ ? localize('com_ui_failed_subject', { 0: subject })
: localize('com_ui_failed');
}
if (intent != null) {
diff --git a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
index e247a03c1e..1a47e3a701 100644
--- a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
@@ -15,17 +15,23 @@ import {
getBatchActivityLabelPart,
getActivityLabelText,
} from '~/utils';
+import {
+ FailedRevealContext,
+ FailedRevealPill,
+ useFailedReveal,
+ useFailedRevealTrigger,
+} from './reveal';
import { useLocalize, useExpandCollapse, scheduleMessageContentLayoutReconcile } from '~/hooks';
import { ASK_USER_QUESTION, getSubmittedAskAnswer } from '~/utils/approval';
import { ToolAuthWarning, ToolAuthWarningContext } from './auth';
import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';
import { AttachmentGroup, ReasoningCompact } from './Parts';
import { getOutcomeStatus, summarizeSpan } from './outcome';
+import { FOLD_RAIL_CLASSES, ROW_GLYPH_SLOT } from './rows';
import { StackedToolIcons } from './ToolOutput';
import { mapAttachments } from '~/utils/map';
import { getSourceDomains } from './sources';
import SearchVerticals from './verticals';
-import { ROW_GLYPH_SLOT } from './rows';
import store from '~/store';
interface ToolCallGroupProps {
@@ -325,6 +331,19 @@ export default function ToolCallGroup({
onExpansionChange?.({ isExpanded: true, userOverride: true });
}, [onExpansionChange]);
+ /** The group relays a request for its failures: from the pill beside its
+ * own header when it stands alone, or from a phase above. Either way it
+ * opens, then issues the request to its rows once they are mounted — a
+ * request passed straight through would reach rows that do not exist yet. */
+ const { value: revealValue, requestReveal } = useFailedRevealTrigger(
+ isExpanded && shouldRenderBody,
+ );
+ const handleRevealFailed = useCallback(() => {
+ handleToolExpand();
+ requestReveal();
+ }, [handleToolExpand, requestReveal]);
+ useFailedReveal(activitySummary.failedCount > 0, handleRevealFailed);
+
const handleTransitionEnd = useCallback(
(event: React.TransitionEvent<HTMLDivElement>) => {
if (event.target !== event.currentTarget) {
@@ -414,13 +433,17 @@ export default function ToolCallGroup({
} 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) },
- ),
- );
+ const failedNote =
+ activitySummary.failedCount > 0
+ ? localize(
+ activitySummary.failedCount === 1
+ ? 'com_ui_one_action_failed'
+ : 'com_ui_n_actions_failed',
+ { 0: String(activitySummary.failedCount) },
+ )
+ : '';
+ if (failedNote !== '') {
+ groupDetailParts.push(failedNote);
}
/** 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
@@ -439,6 +462,14 @@ export default function ToolCallGroup({
const groupAriaLabel = [groupLabel, groupDetail, hasReasoning ? localize('com_ui_thoughts') : '']
.filter(Boolean)
.join(', ');
+ /** Standing alone, the group shows its failure count on the pill beside
+ * the header, which is also the way to the failed rows; the text keeps it
+ * only for the accessible name. Inside a phase the pill is the phase's,
+ * so the group's detail says it in text. */
+ const showsFailurePill = !withinActivityPhase && activitySummary.failedCount > 0;
+ const visibleGroupDetail = showsFailurePill
+ ? groupDetailParts.filter((part) => part && part !== failedNote).join(' · ')
+ : groupDetail;
/** Single category glyph for homogeneous groups (else StackedToolIcons). */
const CategoryIcon = allSubagents ? Users : MessageCircleQuestion;
const iconStatus = getOutcomeStatus({
@@ -464,68 +495,78 @@ export default function ToolCallGroup({
return (
<div className="mb-2 mt-1" ref={rootRef}>
- <Button
- variant="ghost"
- type="button"
- 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={groupAriaLabel}
- >
- {iconStatus == null && (allSubagents || allAskQuestions) ? (
- /** Homogeneous category groups get a single category glyph instead
- * of StackedToolIcons' generic wrenches: a Users glyph for
- * subagents, a question glyph for ask_user_question — matching
- * their individual card headers and reading as the category
- * rather than "tools". */
- <div
- className={cn(
- ROW_GLYPH_SLOT,
- 'text-text-secondary',
- isGroupLive && 'animate-pulse text-text-primary',
- )}
- aria-hidden="true"
- >
- <CategoryIcon size={14} />
- </div>
- ) : (
- <div className={ROW_GLYPH_SLOT} aria-hidden="true">
- <StackedToolIcons
- toolNames={iconToolNames}
- mcpIconMap={mcpIconMap}
- maxIcons={4}
- sourceDomains={sourceDomains}
- status={iconStatus}
- isAnimating={isGroupLive}
- />
- </div>
- )}
- <span
+ <div className="flex w-full items-center gap-2">
+ <Button
+ variant="ghost"
+ type="button"
className={cn(
- 'tool-status-text min-w-0 truncate font-medium',
- activityFailed && 'text-text-warning',
+ 'inline-flex h-auto min-w-0 flex-1 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',
+ /** An open header is the title of the rows under it, so it is the
+ * one line in the fold set in the primary colour. */
+ isExpanded && 'text-text-primary hover:text-text-primary',
)}
- role="status"
- title={groupLabel}
+ onClick={handleToggle}
+ aria-expanded={isExpanded}
+ aria-label={groupAriaLabel}
>
- {groupLabel}
- </span>
- {groupDetail && (
+ {iconStatus == null && (allSubagents || allAskQuestions) ? (
+ /** Homogeneous category groups get a single category glyph instead
+ * of StackedToolIcons' generic wrenches: a Users glyph for
+ * subagents, a question glyph for ask_user_question — matching
+ * their individual card headers and reading as the category
+ * rather than "tools". */
+ <div
+ className={cn(
+ ROW_GLYPH_SLOT,
+ 'text-text-secondary',
+ isGroupLive && 'animate-pulse text-text-primary',
+ )}
+ aria-hidden="true"
+ >
+ <CategoryIcon size={14} />
+ </div>
+ ) : (
+ <div className={ROW_GLYPH_SLOT} aria-hidden="true">
+ <StackedToolIcons
+ toolNames={iconToolNames}
+ mcpIconMap={mcpIconMap}
+ maxIcons={4}
+ sourceDomains={sourceDomains}
+ status={iconStatus}
+ isAnimating={isGroupLive}
+ />
+ </div>
+ )}
<span
- className="min-w-0 max-w-[40%] truncate text-xs font-normal text-text-secondary"
- title={groupDetail}
+ className={cn(
+ 'tool-status-text min-w-0 truncate font-medium',
+ activityFailed && 'text-text-warning',
+ )}
+ role="status"
+ title={groupLabel}
>
- · {groupDetail}
+ {groupLabel}
</span>
- )}
- <ChevronDown
- className={cn(
- 'size-4 shrink-0 text-text-secondary transition-transform duration-200 ease-out',
- isExpanded && 'rotate-180',
+ {visibleGroupDetail && (
+ <span
+ className="min-w-0 max-w-[40%] truncate text-xs font-normal text-text-secondary"
+ title={visibleGroupDetail}
+ >
+ · {visibleGroupDetail}
+ </span>
)}
- aria-hidden="true"
- />
- </Button>
+ <ChevronDown
+ className={cn(
+ 'size-4 shrink-0 text-text-secondary transition-transform duration-200 ease-out',
+ isExpanded && 'rotate-180',
+ )}
+ aria-hidden="true"
+ />
+ </Button>
+ {!withinActivityPhase && (
+ <FailedRevealPill count={activitySummary.failedCount} onReveal={handleRevealFailed} />
+ )}
+ </div>
<div
style={expandStyle}
onTransitionEnd={handleTransitionEnd}
@@ -533,51 +574,58 @@ export default function ToolCallGroup({
data-testid="tool-call-group-panel"
>
{shouldRenderBody && (
- <div className="overflow-hidden" ref={expandRef}>
+ <div className={cn('overflow-hidden', FOLD_RAIL_CLASSES)} ref={expandRef}>
<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,
+ <FailedRevealContext.Provider value={revealValue}>
+ <div className="flex flex-col py-0.5">
+ {parts.map(({ part, idx }, partIndex) => {
+ if (part.type === ContentTypes.THINK) {
+ const think = part.think;
+ const reasoning = typeof think === 'string' ? think : (think?.value ?? '');
+ /** A detached-subagent projection carries an empty THINK
+ * part flagged `reasoning_unavailable`, which `Part`
+ * renders as a `ReasoningMarker`. `ReasoningCompact` has
+ * no text to show and returns null, so the marker has to
+ * keep going through the standalone path or it vanishes
+ * the moment its call joins a group. */
+ if (reasoning.trim() === '' && part.reasoning_unavailable === true) {
+ return renderPart(
+ part,
+ idx,
+ isLast && idx === lastContentIdx,
+ handleToolExpand,
+ );
+ }
+ const streaming = isSubmitting && idx === lastContentIdx;
+ const isAfterTool =
+ partIndex > 0 && parts[partIndex - 1]?.part.type === ContentTypes.TOOL_CALL;
+ /** Mirrors the standalone `Reasoning` path: the authored
+ * label wins, generic text is only a fallback. */
+ const generatedLabel = part.reasoning_label?.trim();
+ const label =
+ generatedLabel ||
+ (streaming ? localize('com_ui_thinking') : localize('com_ui_thoughts'));
+ return (
+ <ReasoningCompact
+ key={`reasoning-${idx}`}
+ partKeyIndex={getPartKeyIndex(part, idx)}
+ reasoning={reasoning}
+ label={label}
+ showThinking={showThinking}
+ isAfterTool={isAfterTool}
+ isStreaming={streaming}
+ />
);
}
- const streaming = isSubmitting && idx === lastContentIdx;
- const isAfterTool =
- partIndex > 0 && parts[partIndex - 1]?.part.type === ContentTypes.TOOL_CALL;
- /** Mirrors the standalone `Reasoning` path: the authored
- * label wins, generic text is only a fallback. */
- const generatedLabel = part.reasoning_label?.trim();
- const label =
- generatedLabel ||
- (streaming ? localize('com_ui_thinking') : localize('com_ui_thoughts'));
- return (
- <ReasoningCompact
- key={`reasoning-${idx}`}
- partKeyIndex={getPartKeyIndex(part, idx)}
- reasoning={reasoning}
- label={label}
- showThinking={showThinking}
- isAfterTool={isAfterTool}
- isStreaming={streaming}
- />
+ return renderPart(
+ part,
+ idx,
+ isLast && idx === lastContentIdx,
+ handleToolExpand,
);
- }
- return renderPart(part, idx, isLast && idx === lastContentIdx, handleToolExpand);
- })}
- </div>
+ })}
+ </div>
+ </FailedRevealContext.Provider>
</ToolAuthWarningContext.Provider>
{hasPendingAuthRequest && <ToolAuthWarning className="mb-1 mt-2.5" />}
</div>
diff --git a/client/src/components/Chat/Messages/Content/ToolOutput/OutputRenderer.tsx b/client/src/components/Chat/Messages/Content/ToolOutput/OutputRenderer.tsx
index 9af2dae1e9..1b71b8923c 100644
--- a/client/src/components/Chat/Messages/Content/ToolOutput/OutputRenderer.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolOutput/OutputRenderer.tsx
@@ -22,8 +22,19 @@ function cleanError(text: string): string {
return cleaned;
}
+/** The feedback a call gets when its input fails schema validation: the SDK
+ * returns it to the model as a plain `Error:` block closed by this sentence,
+ * with the run step still `completed`. Mirrors the server's own verdict in
+ * `completedToolExecutionStatus`, so a card, a group header and a phase
+ * agree with the label the server wrote for the same call. */
+const VALIDATION_FEEDBACK = /^Error:[\s\S]*\n Please fix your mistakes\.$/i;
+
export function isError(text: string): boolean {
- return hasToolCallErrorPrefix(text) || text.startsWith('Error processing tool');
+ return (
+ hasToolCallErrorPrefix(text) ||
+ text.startsWith('Error processing tool') ||
+ VALIDATION_FEEDBACK.test(text)
+ );
}
function isStructuredText(text: string): boolean {
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.tsx
index 2e4dd0d5e3..77ff54aaee 100644
--- a/client/src/components/Chat/Messages/Content/ToolOutput/__tests__/OutputRenderer.test.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolOutput/__tests__/OutputRenderer.test.tsx
@@ -25,4 +25,17 @@ describe('OutputRenderer', () => {
it('does not treat text between bracketed prefixes as a tool-call error', () => {
expect(isError('Error: [agent] unexpected [search] tool call failed: unavailable')).toBe(false);
});
+
+ /** The server's `completedToolExecutionStatus` counts this shape as a
+ * failure while the run step stays `completed`; the card must agree with
+ * the label the server wrote for the same call. */
+ it('treats schema-validation feedback as a failed call', () => {
+ expect(
+ isError(
+ 'Error: Tool "slow_echo" input failed schema validation. Missing required fields: text.' +
+ "Use this tool's declared arguments.\n Please fix your mistakes.",
+ ),
+ ).toBe(true);
+ expect(isError('Error: something went wrong, then it recovered')).toBe(false);
+ });
});
diff --git a/client/src/components/Chat/Messages/Content/WebSearch.tsx b/client/src/components/Chat/Messages/Content/WebSearch.tsx
index 6ecaad54a8..9cec40db64 100644
--- a/client/src/components/Chat/Messages/Content/WebSearch.tsx
+++ b/client/src/components/Chat/Messages/Content/WebSearch.tsx
@@ -22,11 +22,13 @@ import { useLocalize, useExpandCollapse, useLazyCollapseBody } from '~/hooks';
import { collectSources, getUniqueDomainSources } from './sources';
import { StackedFavicons } from '~/components/Web/Sources';
import { toolPanelSpacingClassName } from './disclosure';
+import { isError } from './ToolOutput/OutputRenderer';
import parseJsonField from './Parts/parseJsonField';
import { useToolCallIntent } from './Parts/intent';
import { useSearchContext } from '~/Providers';
import SearchVerticals from './verticals';
import { ROW_GLYPH_SLOT } from './rows';
+import ToolCall from './ToolCall';
import cn from '~/utils/cn';
import store from '~/store';
@@ -85,9 +87,9 @@ export default function WebSearch({
* persists as the settled label like the other tool cards. */
const intent = useToolCallIntent(args);
const { searchResults } = useSearchContext();
- const error =
- (typeof output === 'string' && output.toLowerCase().includes('error processing')) ||
- runStepStatus === 'failed';
+ const error = (typeof output === 'string' && isError(output)) || runStepStatus === 'failed';
+ const legacyError =
+ !error && typeof output === 'string' && output.toLowerCase().includes('error processing');
const isClosed = runStepStatus != null;
// Server tool calls (srvtoolu_) never receive ON_RUN_STEP_COMPLETED, so progress
@@ -98,16 +100,13 @@ export default function WebSearch({
[attachments],
);
const effectiveProgress = isClosed || (hasResults && !isSubmitting) ? 1 : progress;
- /**
- * `error` folds into this branch deliberately: an errored search has always
- * rendered as nothing (the `cancelled` early-return below), so a step closed
- * as `failed` lands in the same place rather than inventing a failure UI
- * this component has never had — or worse, falling through to the streaming
- * branch and shimmering forever.
- */
+ /** Older search errors with only the loose "error processing" text were
+ * hidden, not counted as failures. Preserve that legacy behavior rather
+ * than labeling them completed; recognized failures get a real disclosure
+ * below so the group pill can reach their error. */
const cancelled = isClosed
- ? runStepStatus === 'cancelled' || error
- : (!isSubmitting && effectiveProgress < 1) || error === true;
+ ? runStepStatus === 'cancelled' || legacyError
+ : (!isSubmitting && effectiveProgress < 1) || legacyError;
const finalizing = !isClosed && isSubmitting && isLast && effectiveProgress === 1;
/** A search that is the message's FINAL part stays "finalizing" only while
@@ -224,6 +223,23 @@ export default function WebSearch({
});
};
+ if (error && runStepStatus !== 'cancelled') {
+ return (
+ <ToolCall
+ name={Tools.web_search}
+ args={args ?? ''}
+ output={output}
+ initialProgress={progress}
+ isSubmitting={isSubmitting}
+ isLast={isLast}
+ runStepStatus={runStepStatus}
+ attachments={attachments}
+ hideAttachments={hideAttachments}
+ onExpand={onExpand}
+ />
+ );
+ }
+
if (cancelled) {
return null;
}
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ActivityPhaseGroup.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ActivityPhaseGroup.test.tsx
index 4bba28c065..87701cbb26 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ActivityPhaseGroup.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ActivityPhaseGroup.test.tsx
@@ -3,6 +3,7 @@ import { act, fireEvent, render, screen, within } from '@testing-library/react';
import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';
import { ROW_GLYPH_SLOT, TOOL_ROW_CLASSES } from '../rows';
import ActivityPhaseGroup from '../ActivityPhaseGroup';
+import { useFailedReveal } from '../reveal';
const mockUseSmoothStreaming = jest.fn(() => true);
const mockScheduleLayoutReconcile = jest.fn((_target: HTMLElement | null) => jest.fn());
@@ -12,6 +13,11 @@ jest.mock('~/hooks/Messages/useSmoothStreaming', () => ({
default: () => mockUseSmoothStreaming(),
}));
+jest.mock('~/hooks/MCP', () => ({
+ useMCPIconMap: () => new Map(),
+ useMCPServerNames: () => [],
+}));
+
jest.mock('~/hooks', () => {
const expandCollapse = jest.requireActual('~/hooks/Messages/useExpandCollapse');
const lazyCollapseBody = jest.requireActual('~/hooks/Messages/useLazyCollapseBody');
@@ -407,3 +413,137 @@ describe('ActivityPhaseGroup', () => {
expect(screen.getByTestId('activity-phase-panel')).not.toContainElement(image);
});
});
+
+describe('ActivityPhaseGroup failure fast path', () => {
+ const toPart = (call: Record<string, unknown>, id: string): TMessageContentParts =>
+ ({
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id, args: '{}', type: 'tool_call', progress: 1, ...call },
+ }) as unknown as TMessageContentParts;
+ const okCall = toPart({ name: 'lookup', output: 'rows' }, 'ok');
+ const failedCall = toPart(
+ { name: 'fetch_page', output: 'Error: tool call failed: HTTP 429\nretry after 60' },
+ 'f1',
+ );
+ const RevealProbe = ({ onReveal }: { onReveal: () => void }) => {
+ useFailedReveal(true, onReveal);
+ return <div data-testid="phase-content" />;
+ };
+
+ test('peeks the first failed call under a collapsed card and reaches it in one click', () => {
+ const onReveal = jest.fn();
+ render(
+ <ActivityPhaseGroup labelPart={labelPart} hasContent spanParts={[okCall, failedCall]}>
+ <RevealProbe onReveal={onReveal} />
+ </ActivityPhaseGroup>,
+ );
+ const peek = screen.getByTestId('activity-phase-failed-peek');
+ expect(peek).toHaveTextContent('HTTP 429');
+ expect(peek).toHaveTextContent('com_ui_show_error');
+ expect(screen.queryByTestId('phase-content')).not.toBeInTheDocument();
+
+ fireEvent.click(peek);
+
+ expect(screen.getByRole('button', { name: LABEL })).toHaveAttribute('aria-expanded', 'true');
+ expect(screen.queryByTestId('activity-phase-failed-peek')).not.toBeInTheDocument();
+ expect(onReveal).toHaveBeenCalledTimes(1);
+ });
+
+ test('keeps the error action and remaining count outside the shrinking peek label', () => {
+ render(
+ <ActivityPhaseGroup labelPart={labelPart} hasContent spanParts={[failedCall, failedCall]}>
+ <div />
+ </ActivityPhaseGroup>,
+ );
+
+ const peek = screen.getByTestId('activity-phase-failed-peek');
+ const label = screen.getByText('com_ui_failed_subject');
+ const box = label.parentElement;
+ expect(box).toHaveClass('min-w-0', 'flex');
+ expect(label).toHaveClass('max-w-full', 'shrink-0', 'truncate');
+ expect(box).toContainElement(screen.getByText('HTTP 429'));
+ expect(screen.getByText('com_ui_plus_n_more')).toHaveClass('shrink-0');
+ expect(screen.getByText('com_ui_show_error')).toHaveClass('shrink-0');
+ expect(peek.firstElementChild).toHaveClass('shrink-0');
+ });
+
+ test('the pill beside the header does the same on an open card', () => {
+ const onReveal = jest.fn();
+ render(
+ <ActivityPhaseGroup labelPart={labelPart} hasContent spanParts={[failedCall, failedCall]}>
+ <RevealProbe onReveal={onReveal} />
+ </ActivityPhaseGroup>,
+ );
+ fireEvent.click(screen.getByRole('button', { name: LABEL }));
+ const pill = screen.getByRole('button', { name: 'com_ui_show_failed_n' });
+ fireEvent.click(pill);
+ expect(onReveal).toHaveBeenCalledTimes(1);
+ expect(screen.getByRole('button', { name: LABEL })).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ test('a card with no failure shows neither pill nor peek', () => {
+ render(
+ <ActivityPhaseGroup labelPart={labelPart} hasContent spanParts={[okCall]}>
+ <div data-testid="phase-content" />
+ </ActivityPhaseGroup>,
+ );
+ expect(screen.queryByTestId('failed-reveal-pill')).not.toBeInTheDocument();
+ expect(screen.queryByTestId('activity-phase-failed-peek')).not.toBeInTheDocument();
+ });
+});
+
+describe('ActivityPhaseGroup open header', () => {
+ const runningCall = {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id: 'r1',
+ name: 'lookup',
+ args: '{"intent":"Checking the rollback path"}',
+ type: 'tool_call',
+ progress: 0.5,
+ output: '',
+ },
+ } as unknown as TMessageContentParts;
+
+ test('titles an open card by its label instead of the live line', () => {
+ render(
+ <ActivityPhaseGroup labelPart={labelPart} hasContent liveParts={[runningCall]}>
+ <div data-testid="phase-content" />
+ </ActivityPhaseGroup>,
+ );
+ const live = screen.getByRole('button');
+ expect(live).toHaveAttribute('aria-labelledby');
+ expect(live).toHaveTextContent('Checking the rollback path');
+
+ fireEvent.click(live);
+
+ const open = screen.getByRole('button', { name: LABEL });
+ expect(open).not.toHaveAttribute('aria-labelledby');
+ expect(open).toHaveClass('font-semibold', 'text-text-primary');
+ expect(open).not.toHaveTextContent('Checking the rollback path');
+ });
+
+ test('keeps the live line open when the span has no label yet', () => {
+ render(
+ <ActivityPhaseGroup labelPart={makeLabelPart('')} hasContent liveParts={[runningCall]}>
+ <div data-testid="phase-content" />
+ </ActivityPhaseGroup>,
+ );
+ fireEvent.click(screen.getByRole('button'));
+ expect(screen.getByRole('button')).toHaveTextContent('Checking the rollback path');
+ });
+
+ test('pins the open header and rails the rows under it', () => {
+ render(
+ <ActivityPhaseGroup labelPart={labelPart} hasContent>
+ <div data-testid="phase-content" />
+ </ActivityPhaseGroup>,
+ );
+ const header = screen.getByRole('button', { name: LABEL });
+ const pinned = header.parentElement?.parentElement;
+ expect(pinned).not.toHaveClass('sticky');
+ fireEvent.click(header);
+ expect(pinned).toHaveClass('sticky', 'top-0');
+ expect(screen.getByTestId('activity-phase-panel').firstElementChild).toHaveClass('pl-6');
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCall.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCall.test.tsx
index bc40cb91b3..042d409fa3 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCall.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/AskUserQuestionCall.test.tsx
@@ -2,6 +2,7 @@ import React from 'react';
import { RecoilRoot } from 'recoil';
import { fireEvent, render, screen } from '@testing-library/react';
import AskUserQuestionCall from '../AskUserQuestionCall';
+import { FailedRevealContext } from '../reveal';
import store from '~/store';
const translations: Record<string, string> = {
@@ -110,6 +111,29 @@ describe('AskUserQuestionCall', () => {
expect(header).toHaveAttribute('aria-expanded', 'true');
});
+ test.each([
+ { failed: true, runStepStatus: 'completed' as const },
+ { failed: false, runStepStatus: 'failed' as const },
+ ])('reveals a terminal question failure from its parent fold (%p)', (failure) => {
+ const call = <AskUserQuestionCall args={args} output="" {...failure} />;
+ const tree = (tick: number) => (
+ <RecoilRoot>
+ <FailedRevealContext.Provider value={{ tick, claimFocus: () => true }}>
+ {call}
+ </FailedRevealContext.Provider>
+ </RecoilRoot>
+ );
+ const { rerender } = render(tree(0));
+ const button = screen.getByRole('button', { name: /Question wasn't shown/ });
+ expect(button).toHaveAttribute('aria-expanded', 'false');
+
+ rerender(tree(1));
+
+ expect(button).toHaveAttribute('aria-expanded', 'true');
+ expect(button).toHaveFocus();
+ expect(button).toHaveTextContent('failed');
+ });
+
test('opens at mount when auto-expand is on', () => {
renderCall(<AskUserQuestionCall args={args} output="public" />, true);
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 f40763a1b2..8fad9144f9 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx
@@ -740,8 +740,7 @@ describe('live fold parity with the cards it hides', () => {
true,
);
fireEvent.click(screen.getByRole('button', { name: 'Reviewed the work' }));
- const group = screen.getByTestId('tool-call-group-panel')
- .previousElementSibling as HTMLElement;
+ const group = screen.getByRole('button', { name: /Ran 2 actions.*1 failed/ });
expect(group).toHaveAccessibleName(/1 failed/);
expect(group.querySelector('.lucide-triangle-alert')).not.toBeNull();
});
@@ -1244,7 +1243,8 @@ describe('live activity hardening transitions', () => {
cancelled: /Cancelled.*1 cancelled/,
completed: 'Finished in background',
}[status];
- expect(screen.getByRole('button')).toHaveAccessibleName(expected);
+ /** The header is the first button; a failure adds the pill after it. */
+ expect(screen.getAllByRole('button')[0]).toHaveAccessibleName(expected);
},
);
@@ -1268,7 +1268,7 @@ describe('live activity hardening transitions', () => {
...calls.slice(1),
]),
);
- expect(screen.getByRole('button')).toHaveAccessibleName(/Looking up item 1023.*1 failed/);
+ expect(screen.getAllByRole('button')[0]).toHaveAccessibleName(/Looking up item 1023.*1 failed/);
expect(screen.getByTestId('activity-phase-announcer')).toHaveTextContent('1 failed');
});
diff --git a/client/src/components/Chat/Messages/Content/__tests__/Part.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/Part.test.tsx
index 7ad9f1b729..f8be067fdc 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/Part.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/Part.test.tsx
@@ -88,6 +88,68 @@ const toolCallPart = (name: string, args = '{"code":"echo hi"}'): TMessageConten
}) as unknown as TMessageContentParts;
describe('Part tool renderer selection', () => {
+ it.each(['image_gen_oai', 'image_edit_oai', 'gemini_image_gen'])(
+ 'keeps a successful %s call on the image renderer',
+ (name) => {
+ renderPart(toolCallPart(name));
+ expect(screen.getByTestId('image-gen')).toBeInTheDocument();
+ },
+ );
+
+ it.each(['completed', 'failed'] as const)(
+ 'makes a failed image-generation step with %s status revealable',
+ (runStepStatus) => {
+ renderPart({
+ ...toolCallPart('image_gen_oai'),
+ tool_call: {
+ id: 'call_1',
+ name: 'image_gen_oai',
+ args: '{}',
+ output: 'Error: Invalid image arguments\n Please fix your mistakes.',
+ progress: 1,
+ runStepStatus,
+ },
+ } as TMessageContentParts);
+ expect(screen.getByTestId('tool-call')).toHaveAttribute(
+ 'data-run-step-status',
+ runStepStatus,
+ );
+ expect(screen.queryByTestId('image-gen')).not.toBeInTheDocument();
+ },
+ );
+
+ it('keeps a cancelled image-generation step out of the failed disclosure', () => {
+ renderPart({
+ ...toolCallPart('image_gen_oai'),
+ tool_call: {
+ id: 'call_1',
+ name: 'image_gen_oai',
+ args: '{}',
+ output: 'Error: Invalid image arguments\n Please fix your mistakes.',
+ progress: 1,
+ runStepStatus: 'cancelled',
+ },
+ } as TMessageContentParts);
+ expect(screen.getByTestId('image-gen')).toBeInTheDocument();
+ expect(screen.queryByTestId('tool-call')).not.toBeInTheDocument();
+ });
+
+ it('routes a failed function-style image call through the shared disclosure', () => {
+ renderPart({
+ type: ContentTypes.TOOL_CALL,
+ tool_call: {
+ type: 'function',
+ progress: 1,
+ function: {
+ name: 'image_gen_oai',
+ arguments: '{}',
+ output: 'Error: Invalid image arguments\n Please fix your mistakes.',
+ },
+ },
+ } as TMessageContentParts);
+ expect(screen.getByTestId('tool-call')).toBeInTheDocument();
+ });
+
it('routes bash PTC tool calls through the BashCall renderer', () => {
renderPart(toolCallPart(Constants.BASH_PROGRAMMATIC_TOOL_CALLING));
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ProgressText.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ProgressText.test.tsx
index ecf0a50c1f..cf6f1c0569 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,6 @@
import React from 'react';
import { fireEvent, render, screen } from '@testing-library/react';
+import { FailedRevealContext } from '../reveal';
import ProgressText from '../ProgressText';
jest.mock('~/hooks', () => ({
@@ -143,3 +144,96 @@ describe('ProgressText disclosure', () => {
expect(button.querySelector('svg')).toBeNull();
});
});
+
+describe('ProgressText subtitle', () => {
+ it('gives the subtitle every bit of the shrink so the label keeps its last letters', () => {
+ renderProgressText({ subtitle: 'HTTP 429 from github.com' });
+ const label = screen.getByText('Completed foo');
+ const subtitle = screen.getByText('HTTP 429 from github.com');
+ expect(label).toHaveClass('shrink-0', 'max-w-full', 'truncate');
+ expect(subtitle).toHaveClass('shrink', 'min-w-0', 'truncate');
+ });
+
+ it('lets a lone label shrink into its own ellipsis', () => {
+ renderProgressText();
+ expect(screen.getByText('Completed foo')).not.toHaveClass('shrink-0');
+ });
+});
+
+describe('ProgressText failure', () => {
+ it('keeps the verdict word on a failed row, open or not', () => {
+ renderProgressText({ phase: 'failed', hasInput: true, isExpanded: true });
+ expect(screen.getByText('· com_ui_tool_failed')).toBeInTheDocument();
+ });
+
+ it('marks a failed row at its left edge and nothing else', () => {
+ const { container, rerender } = renderProgressText({ phase: 'failed' });
+ expect(container.querySelector('.progress-text-wrapper')).toHaveClass('before:bg-status-error');
+ rerender(<ProgressText {...defaults} phase="completed" />);
+ expect(container.querySelector('.progress-text-wrapper')).not.toHaveClass(
+ 'before:bg-status-error',
+ );
+ });
+});
+
+describe('ProgressText failed reveal', () => {
+ const reveal = (tick: number, claim = true) => ({ tick, claimFocus: () => claim });
+ let onClick: jest.Mock;
+ beforeEach(() => {
+ onClick = jest.fn();
+ });
+ const tree = (value: { tick: number; claimFocus: () => boolean }, props = {}) => (
+ <FailedRevealContext.Provider value={value}>
+ <ProgressText {...defaults} phase="failed" onClick={onClick} {...props} />
+ </FailedRevealContext.Provider>
+ );
+
+ it('opens through its own toggle and takes focus on the labeled button', () => {
+ const { rerender } = render(tree(reveal(0)));
+ expect(onClick).not.toHaveBeenCalled();
+ rerender(tree(reveal(1)));
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(screen.getByRole('button')).toHaveFocus();
+ });
+
+ it('opens but leaves focus alone when another row already claimed it', () => {
+ const { rerender } = render(tree(reveal(0, false)));
+ rerender(tree(reveal(1, false)));
+ expect(onClick).toHaveBeenCalledTimes(1);
+ expect(screen.getByRole('button')).not.toHaveFocus();
+ });
+
+ it('does not toggle a panel that is already open', () => {
+ const { rerender } = render(tree(reveal(0), { isExpanded: true }));
+ rerender(tree(reveal(1), { isExpanded: true }));
+ expect(onClick).not.toHaveBeenCalled();
+ expect(screen.getByRole('button')).toHaveFocus();
+ });
+
+ it('ignores the request on a row that did not fail or cannot open', () => {
+ const pair = (tick: number) => (
+ <FailedRevealContext.Provider value={reveal(tick)}>
+ <ProgressText {...defaults} phase="completed" onClick={onClick} />
+ <ProgressText {...defaults} phase="failed" hasInput={false} onClick={onClick} />
+ </FailedRevealContext.Provider>
+ );
+ const { rerender } = render(pair(0));
+ rerender(pair(1));
+ expect(onClick).not.toHaveBeenCalled();
+ });
+});
+
+describe('ProgressText fixed siblings', () => {
+ it('keeps the verdict, duration and chevron out of the shrinking label box', () => {
+ const { container } = renderProgressText({
+ phase: 'completed',
+ subtitle: 'a very long subtitle',
+ durationMs: 3500,
+ });
+ const box = screen.getByText('Completed foo').parentElement;
+ expect(box).toHaveClass('min-w-0');
+ expect(box).toContainElement(screen.getByText('a very long subtitle'));
+ expect(screen.getByText('· 3.5s')).toHaveClass('shrink-0');
+ expect(container.querySelector('svg')).toHaveClass('shrink-0');
+ });
+});
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 aa60aedfd2..6bca11a0cc 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCall.test.tsx
@@ -762,3 +762,22 @@ describe('ToolCall', () => {
});
});
});
+
+describe('ToolCall failure fast path', () => {
+ const failedProps = {
+ args: '{"url":"https://x"}',
+ name: 'fetch_page',
+ output: 'Error: tool call failed: HTTP 429 from github.com\nretry after 60',
+ initialProgress: 1,
+ isSubmitting: false,
+ };
+
+ it('spends the subtitle on the first line of the error', () => {
+ render(
+ <RecoilRoot>
+ <ToolCall {...failedProps} />
+ </RecoilRoot>,
+ );
+ expect(screen.getByTestId('subtitle')).toHaveTextContent('HTTP 429 from github.com');
+ });
+});
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 726f047700..4013817d09 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
@@ -3,6 +3,7 @@ import { RecoilRoot } from 'recoil';
import { Tools, Constants, ContentTypes } from 'librechat-data-provider';
import { fireEvent, render, screen, waitFor } from '@testing-library/react';
import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';
+import { FailedRevealContext, useFailedReveal } from '../reveal';
import { scheduleMessageContentLayoutReconcile } from '~/hooks';
import ToolCallGroup from '../ToolCallGroup';
import { ToolAuthWarning } from '../auth';
@@ -541,7 +542,7 @@ describe('ToolCallGroup image hoisting', () => {
renderGroup(baseProps);
const button = screen.getByRole('button', { name: /^Ran 2 actions/ });
- const collapsible = button.nextElementSibling as HTMLElement;
+ const collapsible = screen.getByTestId('tool-call-group-panel');
fireEvent.click(button);
fireEvent.click(button);
expect(screen.getByTestId('inner-0')).toBeInTheDocument();
@@ -567,7 +568,7 @@ describe('ToolCallGroup image hoisting', () => {
});
const button = screen.getByRole('button', { name: /^Ran 2 actions/ });
- const collapsible = button.nextElementSibling as HTMLElement;
+ const collapsible = screen.getByTestId('tool-call-group-panel');
expect(screen.getByTestId('approval-0')).toBeInTheDocument();
fireEvent.click(button);
@@ -599,7 +600,7 @@ describe('ToolCallGroup image hoisting', () => {
});
const button = screen.getByRole('button', { name: /^Ran 2 actions/ });
- const collapsible = button.nextElementSibling as HTMLElement;
+ const collapsible = screen.getByTestId('tool-call-group-panel');
fireEvent.click(button);
fireEvent.transitionEnd(collapsible);
@@ -629,7 +630,7 @@ describe('ToolCallGroup image hoisting', () => {
});
const button = screen.getByRole('button', { name: /^Ran 2 actions/ });
- const collapsible = button.nextElementSibling as HTMLElement;
+ const collapsible = screen.getByTestId('tool-call-group-panel');
fireEvent.click(button);
fireEvent.transitionEnd(collapsible);
@@ -657,7 +658,7 @@ describe('ToolCallGroup image hoisting', () => {
const { rerender } = renderGroup(propsFor());
const button = screen.getByRole('button', { name: /^Ran 2 actions/ });
- const collapsible = button.nextElementSibling as HTMLElement;
+ const collapsible = screen.getByTestId('tool-call-group-panel');
fireEvent.click(button);
fireEvent.transitionEnd(collapsible);
expect(screen.getByTestId('retained-0')).toBeInTheDocument();
@@ -698,7 +699,7 @@ describe('ToolCallGroup image hoisting', () => {
const { rerender } = renderGroup(propsFor());
const button = screen.getByRole('button', { name: /^Ran 2 actions/ });
- const collapsible = button.nextElementSibling as HTMLElement;
+ const collapsible = screen.getByTestId('tool-call-group-panel');
fireEvent.click(button);
rerender(
@@ -1119,3 +1120,85 @@ describe('ToolCallGroup image hoisting', () => {
expect(screen.getByTestId('stacked-icons')).toBeInTheDocument();
});
});
+
+describe('ToolCallGroup failure fast path', () => {
+ const RevealProbe = ({ onReveal }: { onReveal: () => void }) => {
+ useFailedReveal(true, onReveal);
+ return <div data-testid="probe" />;
+ };
+ const failedParts = [
+ { part: makePart('c1', 'created', 'create_file'), idx: 0 },
+ { part: makePart('c2', 'Error processing tool: disk full', 'create_file'), idx: 1 },
+ ];
+ const props = (onReveal: () => void) =>
+ ({
+ parts: failedParts,
+ isSubmitting: false,
+ isLast: false,
+ showThinking: false,
+ lastContentIdx: 1,
+ renderPart: (_p: TMessageContentParts, idx: number) => (
+ <RevealProbe key={idx} onReveal={onReveal} />
+ ),
+ }) satisfies React.ComponentProps<typeof ToolCallGroup>;
+
+ it('opens the group and asks its rows to open from the pill beside a standalone header', () => {
+ const onReveal = jest.fn();
+ renderGroup(props(onReveal));
+ const header = screen.getByRole('button', { name: /· 1 failed$/ });
+ expect(header).toHaveAttribute('aria-expanded', 'false');
+
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_show_failed_one' }));
+
+ expect(header).toHaveAttribute('aria-expanded', 'true');
+ /** Once per row the group rendered, after those rows mounted. */
+ expect(onReveal).toHaveBeenCalledTimes(failedParts.length);
+ });
+
+ it('shows the failure count once, on the pill, when it stands alone', () => {
+ renderGroup(props(jest.fn()));
+ const header = screen.getByRole('button', { name: /· 1 failed$/ });
+ expect(header).not.toHaveTextContent('1 failed');
+ expect(screen.getByTestId('failed-reveal-pill')).toHaveTextContent('1 failed');
+ });
+
+ it("keeps the count in text inside a phase, where the pill is the phase's", () => {
+ renderGroup({ ...props(jest.fn()), withinActivityPhase: true });
+ expect(screen.getByRole('button', { name: /· 1 failed$/ })).toHaveTextContent('1 failed');
+ });
+
+ it('leaves the pill to the phase header when nested in one', () => {
+ renderGroup({ ...props(jest.fn()), withinActivityPhase: true });
+ expect(screen.queryByTestId('failed-reveal-pill')).not.toBeInTheDocument();
+ });
+
+ it('opens for a request from a phase above when it holds a failure', () => {
+ const onReveal = jest.fn();
+ const { rerender } = render(
+ <RecoilRoot>
+ <FailedRevealContext.Provider value={{ tick: 0, claimFocus: null }}>
+ <ToolCallGroup {...props(onReveal)} withinActivityPhase />
+ </FailedRevealContext.Provider>
+ </RecoilRoot>,
+ );
+ const header = screen.getByRole('button', { name: /· 1 failed$/ });
+ expect(header).toHaveAttribute('aria-expanded', 'false');
+ rerender(
+ <RecoilRoot>
+ <FailedRevealContext.Provider value={{ tick: 1, claimFocus: null }}>
+ <ToolCallGroup {...props(onReveal)} withinActivityPhase />
+ </FailedRevealContext.Provider>
+ </RecoilRoot>,
+ );
+ expect(header).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('sets an open header in the primary colour over railed rows', () => {
+ renderGroup(props(jest.fn()));
+ const header = screen.getByRole('button', { name: /· 1 failed$/ });
+ expect(header).not.toHaveClass('text-text-primary');
+ fireEvent.click(header);
+ expect(header).toHaveClass('text-text-primary');
+ expect(screen.getByTestId('tool-call-group-panel').firstElementChild).toHaveClass('pl-6');
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/__tests__/WebSearch.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/WebSearch.test.tsx
index 33b2b9ebc8..42d7555d7a 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/WebSearch.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/WebSearch.test.tsx
@@ -2,7 +2,13 @@ import React from 'react';
import { RecoilRoot } from 'recoil';
import { Tools } from 'librechat-data-provider';
import { fireEvent, render, screen } from '@testing-library/react';
-import type { TAttachment, SearchResultData, ValidSource } from 'librechat-data-provider';
+import type {
+ TAttachment,
+ SearchResultData,
+ ValidSource,
+ PartMetadata,
+} from 'librechat-data-provider';
+import { FailedRevealContext } from '../reveal';
import { SearchContext } from '~/Providers';
import { ROW_GLYPH_SLOT } from '../rows';
import WebSearch from '../WebSearch';
@@ -23,6 +29,7 @@ jest.mock('~/hooks', () => ({
return translations[key] || key;
},
useLazyCollapseBody: jest.requireActual('~/hooks/Messages/useLazyCollapseBody').default,
+ useProgress: (progress: number) => progress,
useExpandCollapse: (isExpanded: boolean) => ({
style: {
display: 'grid',
@@ -33,6 +40,11 @@ jest.mock('~/hooks', () => ({
}),
}));
+jest.mock('~/hooks/MCP', () => ({
+ useMCPIconMap: () => new Map(),
+ useMCPServerNames: () => [],
+}));
+
jest.mock('~/utils/cn', () => ({
__esModule: true,
default: (...classes: unknown[]) => classes.filter(Boolean).join(' '),
@@ -96,6 +108,8 @@ function renderWebSearch({
initialProgress = 1,
args,
output,
+ runStepStatus,
+ revealTick = 0,
}: {
searchResults?: Record<string, SearchResultData>;
attachments?: TAttachment[];
@@ -104,21 +118,28 @@ function renderWebSearch({
initialProgress?: number;
args?: string | Record<string, unknown>;
output?: string | null;
+ runStepStatus?: PartMetadata['runStepStatus'];
+ revealTick?: number;
}) {
- return render(
+ const tree = (tick: number) => (
<RecoilRoot>
<SearchContext.Provider value={{ searchResults }}>
- <WebSearch
- initialProgress={initialProgress}
- isSubmitting={isSubmitting}
- isLast={isLast}
- args={args}
- output={output}
- attachments={attachments}
- />
+ <FailedRevealContext.Provider value={{ tick, claimFocus: () => true }}>
+ <WebSearch
+ initialProgress={initialProgress}
+ isSubmitting={isSubmitting}
+ isLast={isLast}
+ args={args}
+ output={output}
+ attachments={attachments}
+ runStepStatus={runStepStatus}
+ />
+ </FailedRevealContext.Provider>
</SearchContext.Provider>
- </RecoilRoot>,
+ </RecoilRoot>
);
+ const result = render(tree(revealTick));
+ return { ...result, reveal: (tick: number) => result.rerender(tree(tick)) };
}
describe('WebSearch', () => {
@@ -298,6 +319,53 @@ describe('WebSearch', () => {
expect(container.innerHTML).toBe('');
});
+ it('reveals schema-validation feedback even if the step closed as completed', () => {
+ const output = 'Error: Invalid search arguments\n Please fix your mistakes.';
+ const { reveal } = renderWebSearch({
+ output,
+ args: '{"query":"x"}',
+ runStepStatus: 'completed',
+ });
+ const button = screen.getByTestId('tool-call').querySelector('button');
+ expect(button).toHaveAttribute('aria-expanded', 'false');
+ expect(button).toHaveTextContent('failed');
+ expect(screen.queryByText('Searched the web')).not.toBeInTheDocument();
+
+ reveal(1);
+
+ expect(button).toHaveAttribute('aria-expanded', 'true');
+ expect(button).toHaveFocus();
+ expect(screen.getByText('Error: Invalid search arguments')).toBeInTheDocument();
+ });
+
+ it('keeps a status-failed search visible even with ordinary output', () => {
+ const { reveal } = renderWebSearch({
+ output: 'Partial data',
+ args: '{"query":"x"}',
+ runStepStatus: 'failed',
+ });
+ const button = screen.getByTestId('tool-call').querySelector('button');
+ expect(button).toHaveTextContent('failed');
+ reveal(1);
+ expect(button).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('honors a cancelled step over error-shaped output', () => {
+ const { container } = renderWebSearch({
+ output: 'Error: Invalid search arguments\n Please fix your mistakes.',
+ runStepStatus: 'cancelled',
+ });
+ expect(container.innerHTML).toBe('');
+ });
+
+ it('still hides unclassified legacy search errors on a completed step', () => {
+ const { container } = renderWebSearch({
+ output: 'Error processing search results',
+ runStepStatus: 'completed',
+ });
+ expect(container.innerHTML).toBe('');
+ });
+
it('renders completed state with source count', () => {
const searchResults = makeSearchResults({
0: { organic: [makeSource('https://example.com', 'Example')] },
diff --git a/client/src/components/Chat/Messages/Content/__tests__/failed.test.ts b/client/src/components/Chat/Messages/Content/__tests__/failed.test.ts
new file mode 100644
index 0000000000..36e9119212
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/__tests__/failed.test.ts
@@ -0,0 +1,69 @@
+import { ContentTypes } from 'librechat-data-provider';
+import type { TMessageContentParts } from 'librechat-data-provider';
+import type { TOptions } from 'i18next';
+import type { TranslationKeys } from '~/hooks';
+import { firstErrorLine, getFailedLines } from '../live';
+
+const localize = (key: TranslationKeys, values?: TOptions): string =>
+ key === 'com_ui_failed_subject' ? `Failed: ${String(values?.[0])}` : key;
+
+const toPart = (call: Record<string, unknown>, id: string): TMessageContentParts =>
+ ({
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id, args: '{}', type: 'tool_call', progress: 1, ...call },
+ }) as unknown as TMessageContentParts;
+
+describe('firstErrorLine', () => {
+ it('strips the tool-call error prefix and keeps the first line', () => {
+ expect(
+ firstErrorLine('Error: tool call failed: HTTP 429 from github.com\nretry after 60'),
+ ).toBe('HTTP 429 from github.com');
+ });
+
+ it('strips the generic processing prefix', () => {
+ expect(firstErrorLine('Error processing tool: disk full')).toBe('disk full');
+ });
+
+ it('strips a bare error prefix such as schema-validation feedback', () => {
+ expect(
+ firstErrorLine(
+ 'Error: Tool "slow_echo" input failed schema validation.\n Please fix your mistakes.',
+ ),
+ ).toBe('Tool "slow_echo" input failed schema validation.');
+ });
+
+ it('is empty for no output or output that is not an error', () => {
+ expect(firstErrorLine(undefined)).toBe('');
+ expect(firstErrorLine('')).toBe('');
+ expect(firstErrorLine('{"background_task_id":"bg1","status":"running"}')).toBe('');
+ });
+});
+
+describe('getFailedLines', () => {
+ it('lists every failed call in order with its row label and first error line', () => {
+ const parts = [
+ toPart({ name: 'lookup', output: 'rows' }, 'ok'),
+ toPart(
+ {
+ name: 'fetch_page',
+ args: { intent: 'Read a page', url: 'https://x' },
+ output: 'Error: tool call failed: HTTP 429\nmore',
+ },
+ 'f1',
+ ),
+ undefined,
+ toPart({ name: 'lookup', output: 'rows', runStepStatus: 'failed' }, 'f2'),
+ ];
+ expect(getFailedLines(parts, localize, [])).toEqual([
+ { text: 'Failed: Read a page', detail: 'HTTP 429', iconName: 'fetch_page' },
+ /** Failed by its run step, with ordinary output: no line of it is the reason. */
+ { text: 'Failed: lookup', detail: '', iconName: 'lookup' },
+ ]);
+ });
+
+ it('is empty when nothing failed', () => {
+ expect(
+ getFailedLines([toPart({ name: 'lookup', output: 'rows' }, 'ok')], localize, []),
+ ).toEqual([]);
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/live.ts b/client/src/components/Chat/Messages/Content/live.ts
index c79852a07c..fcfe0b7bdf 100644
--- a/client/src/components/Chat/Messages/Content/live.ts
+++ b/client/src/components/Chat/Messages/Content/live.ts
@@ -1,4 +1,4 @@
-import { Tools, Constants, ContentTypes } from 'librechat-data-provider';
+import { Tools, Constants, ContentTypes, stripToolCallErrorPrefix } from 'librechat-data-provider';
import type {
Agents,
TAttachment,
@@ -11,10 +11,11 @@ import type { TranslationKeys } from '~/hooks';
import { getBatchActivityLabelPart, getActivityLabelText } from '~/utils/activityLabels';
import { hasPendingApprovalInPart, hasPendingAuthInPart } from '~/utils/groupToolCalls';
import { ASK_USER_QUESTION, getSubmittedAskAnswer } from '~/utils/approval';
+import { getToolDisplayLabel, parseToolName } from '~/utils/toolLabels';
import { boundIntentLabel, getToolCallIntent } from './Parts/intent';
-import { getToolDisplayLabel } from '~/utils/toolLabels';
import { isBashProgrammaticToolCall } from './routing';
import { getToolMeta, summarizeSpan } from './outcome';
+import { isError } from './ToolOutput';
/** How often a live fold's header may repaint. A streamed intent moves the
* newest line on nearly every delta; the header is a glanceable status, not a
@@ -342,3 +343,71 @@ export function getLiveActivity(
iconNames: getSpanIconNames(parts),
};
}
+
+export type FailedLine = {
+ /** The row's own failed label: `Failed: <intent or tool>`. */
+ text: string;
+ /** The first line of what the tool returned, with the error prefix removed. */
+ detail: string;
+ iconName: string;
+};
+
+const PROCESSING_PREFIX = /^Error processing tool:?\s*/i;
+/** Whatever prefix survives the two above, so a peek row does not spend its
+ * one line on the word the red glyph beside it already says. */
+const GENERIC_ERROR_PREFIX = /^Error:\s*/i;
+
+/** The opening line of an error, for a peek row that has one line to spend. */
+export function firstErrorLine(output: string | null | undefined): string {
+ /** Only output that IS an error. A step the run closed as failed, or a
+ * task failed by its status attachment, can carry ordinary output, and
+ * showing that in red as the reason would misreport the failure. */
+ if (!output || !isError(output)) {
+ return '';
+ }
+ const cleaned = stripToolCallErrorPrefix(output)
+ .replace(PROCESSING_PREFIX, '')
+ .replace(GENERIC_ERROR_PREFIX, '')
+ .trim();
+ const newline = cleaned.indexOf('\n');
+ return newline === -1 ? cleaned : cleaned.slice(0, newline).trim();
+}
+
+/**
+ * Every failed call in a span, in order, as the line its card shows plus the
+ * first line of its error. A collapsed header peeks the first of these so the
+ * failure is readable without unfolding; the count of the rest rides beside it.
+ */
+export function getFailedLines(
+ parts: ReadonlyArray<TMessageContentParts | undefined>,
+ localize: Localize,
+ serverNames: readonly string[],
+ attachmentsById?: Record<string, TAttachment[] | undefined>,
+): FailedLine[] {
+ const span = summarizeSpan(parts, attachmentsById);
+ const lines: FailedLine[] = [];
+ for (const part of parts) {
+ if (part == null) {
+ continue;
+ }
+ const meta = span.metaOf(part);
+ const toolCall = getStandardToolCall(part);
+ if (meta?.failed !== true || toolCall == null) {
+ continue;
+ }
+ /** Named as the ROW names itself, since the peek stands in for the row:
+ * the model's intent, else the bare tool for an MCP call (`ToolCall`
+ * shows the server as a subtitle), else the tool's display label. The
+ * live ticker names the server instead, as its group header does. */
+ const parsed = parseToolName(toolCall.name ?? '', serverNames);
+ const subject =
+ getToolCallIntent(toolCall.args) ??
+ (parsed.mcpServer ? parsed.toolName : getToolDisplayLabel(parsed.raw, localize, serverNames));
+ lines.push({
+ text: subject ? localize('com_ui_failed_subject', { 0: subject }) : localize('com_ui_failed'),
+ detail: firstErrorLine(toolCall.output),
+ iconName: meta.iconName,
+ });
+ }
+ return lines;
+}
diff --git a/client/src/components/Chat/Messages/Content/reveal.tsx b/client/src/components/Chat/Messages/Content/reveal.tsx
new file mode 100644
index 0000000000..8692ce6671
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/reveal.tsx
@@ -0,0 +1,137 @@
+import {
+ createContext,
+ useCallback,
+ useContext,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from 'react';
+import { TriangleAlert } from 'lucide-react';
+import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+/**
+ * A request to show the failed calls under a header, travelling DOWN the fold
+ * tree. Expansion otherwise flows up (`onToolExpand` opens the group around a
+ * row a reader clicked), so a header that wants to open a failed row three
+ * disclosures below it needs its own channel. The value is a counter: each
+ * request is a new number, and a consumer opens once per number it has not
+ * seen. Zero is the resting value and never opens anything.
+ */
+export type FailedReveal = {
+ tick: number;
+ /** One row per request takes scroll and focus: the first failed row in
+ * document order to ask. Every other failed row still opens its panel.
+ * Null outside any provider. */
+ claimFocus: (() => boolean) | null;
+};
+
+export const FailedRevealContext = createContext<FailedReveal>({ tick: 0, claimFocus: null });
+
+/**
+ * Issues requests to the consumers below. A request made while the body is
+ * still unmounted waits for `ready`: a collapsed card mounts its rows in the
+ * same commit that opens it, and a row that mounts under an already-advanced
+ * counter would take it as the resting value and never open. Deferring the
+ * increment to the commit after the rows exist is what lets one click on a
+ * closed card reach an error three disclosures down.
+ *
+ * A provider nested under another (a group inside a phase) relays the outer
+ * focus claim, so one click on the phase focuses one row across all of its
+ * groups rather than one per group.
+ */
+export function useFailedRevealTrigger(ready: boolean): {
+ value: FailedReveal;
+ requestReveal: () => void;
+} {
+ const outer = useContext(FailedRevealContext);
+ const [tick, setTick] = useState(0);
+ const [pending, setPending] = useState(false);
+ const claimedRef = useRef(false);
+ const requestReveal = useCallback(() => {
+ claimedRef.current = false;
+ setPending(true);
+ }, []);
+ const ownClaim = useCallback(() => {
+ if (claimedRef.current) {
+ return false;
+ }
+ claimedRef.current = true;
+ return true;
+ }, []);
+ useEffect(() => {
+ if (!pending || !ready) {
+ return;
+ }
+ setPending(false);
+ setTick((previous) => previous + 1);
+ }, [pending, ready]);
+ const claimFocus = outer.claimFocus ?? ownClaim;
+ const value = useMemo(() => ({ tick, claimFocus }), [tick, claimFocus]);
+ return { value, requestReveal };
+}
+
+/**
+ * Runs `onReveal` once for each request above this consumer, when the
+ * consumer holds a failure, handing it the request's focus claim. The seen
+ * counter is a ref, so a call that fails AFTER an earlier request does not
+ * open itself on that stale request.
+ */
+export function useFailedReveal(
+ hasFailure: boolean,
+ onReveal: (claimFocus: () => boolean) => void,
+): void {
+ const { tick, claimFocus } = useContext(FailedRevealContext);
+ const seenRef = useRef(tick);
+ useEffect(() => {
+ if (tick === seenRef.current) {
+ return;
+ }
+ seenRef.current = tick;
+ if (hasFailure) {
+ onReveal(claimFocus ?? (() => true));
+ }
+ }, [tick, hasFailure, onReveal, claimFocus]);
+}
+
+/**
+ * The header's failure count as the control that reaches the failures. It sits
+ * BESIDE the disclosure button, never inside it: a button cannot contain a
+ * button, and its name says what it does rather than repeating the count the
+ * header already carries.
+ */
+export function FailedRevealPill({
+ count,
+ onReveal,
+ className,
+}: {
+ count: number;
+ onReveal: () => void;
+ className?: string;
+}) {
+ const localize = useLocalize();
+ if (count === 0) {
+ return null;
+ }
+ return (
+ <button
+ type="button"
+ className={cn(
+ 'inline-flex h-5 shrink-0 items-center gap-1 rounded-full border border-transparent bg-status-error-subtle px-2 text-[11.5px] font-semibold leading-none text-status-error',
+ 'hover:border-status-error-border focus-visible:border-status-error focus-visible:outline-none',
+ className,
+ )}
+ onClick={onReveal}
+ aria-label={localize(count === 1 ? 'com_ui_show_failed_one' : 'com_ui_show_failed_n', {
+ 0: String(count),
+ })}
+ data-testid="failed-reveal-pill"
+ >
+ <TriangleAlert size={12} aria-hidden="true" />
+ {localize(count === 1 ? 'com_ui_one_action_failed' : 'com_ui_n_actions_failed', {
+ 0: String(count),
+ })}
+ </button>
+ );
+}
diff --git a/client/src/components/Chat/Messages/Content/rows.ts b/client/src/components/Chat/Messages/Content/rows.ts
index 38eaff6542..dab9bf588f 100644
--- a/client/src/components/Chat/Messages/Content/rows.ts
+++ b/client/src/components/Chat/Messages/Content/rows.ts
@@ -18,3 +18,16 @@ export const TOOL_ROW_CLASSES = 'relative my-1.5 flex h-5 shrink-0 items-center
* and would carry a taller slot 2px below the row's center.
*/
export const ROW_GLYPH_SLOT = 'flex h-5 min-w-6 shrink-0 items-center justify-center';
+
+/**
+ * The panel under an open header: its rows step in by one glyph slot and a
+ * hairline hangs from the header's glyph down their left, so what is under the
+ * header reads as under it. Carried by the panel's clipping wrapper, the one
+ * `overflow-hidden` element the fold animation needs: the inset then lies
+ * INSIDE the clip, which is what lets a failed row's stripe, drawn 12px left
+ * of the row, show at all. The line is a pseudo-element, out of flow, so the
+ * height animation is untouched; it starts at the wrapper's top and stops
+ * short of the last row's bottom margin.
+ */
+export const FOLD_RAIL_CLASSES =
+ "relative pl-6 before:absolute before:bottom-1.5 before:left-[11px] before:top-0.5 before:w-px before:bg-border-medium before:content-['']";
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index a6fcf61481..67b09ec258 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -2317,6 +2317,9 @@
"com_ui_show_image_details": "Show Image Details",
"com_ui_show_less": "Show less",
"com_ui_show_more": "Show more",
+ "com_ui_show_error": "Show error",
+ "com_ui_show_failed_one": "Show failed call",
+ "com_ui_show_failed_n": "Show {{0}} failed calls",
"com_ui_show_n_files": "Show {{0}} files",
"com_ui_show_qr": "Show QR Code",
"com_ui_sibling_navigation": "Sibling message navigation",
diff --git a/e2e/setup/fake-model.js b/e2e/setup/fake-model.js
index 51db43d721..b4b6dcd51b 100644
--- a/e2e/setup/fake-model.js
+++ b/e2e/setup/fake-model.js
@@ -49,6 +49,7 @@ const STEER_SPLIT_REPLY_MARKER = 'E2E_STEER_SPLIT_REPLY:';
const STEER_LATE_REPLY_MARKER = 'E2E_STEER_LATE_REPLY:';
const ACTIVITY_REPLY_MARKER = 'E2E_ACTIVITY_REPLY:';
const ACTIVITY_PHASE_REPLY_MARKER = 'E2E_ACTIVITY_PHASE_REPLY:';
+const ACTIVITY_FAILED_REPLY_MARKER = 'E2E_ACTIVITY_FAILED_REPLY:';
const ASK_USER_QUESTION_MARKER = 'E2E_ASK_USER_QUESTION:';
const RESUME_ICON_REPLY_MARKER = 'E2E_RESUME_ICON_REPLY:';
const FORCED_ERROR_MARKER = 'E2E_FORCED_ERROR:';
@@ -100,6 +101,8 @@ const STEER_LATE_FINAL_TEXT = 'E2E steer late reply done';
const SLOW_REPLY_CONTINUATION_TEXT = 'E2E slow reply continued';
const ACTIVITY_FINAL_TEXT = 'E2E activity reply done';
const ACTIVITY_PHASE_FINAL_TEXT = 'E2E activity phase reply done';
+const ACTIVITY_FAILED_FINAL_TEXT = 'E2E activity failed reply done';
+const SLOW_ECHO_TOOL_NAME_PREFIX = 'slow_echo';
const STEER_TOOL_NAME_PREFIX = 'remember_fact';
const ASK_USER_QUESTION_TOOL_NAME = 'ask_user_question';
const SLOW_CHUNK_DELAY_MS = Number(process.env.MOCK_LLM_SLOW_CHUNK_DELAY_MS) || 35;
@@ -1468,6 +1471,81 @@ function activityPhaseReplyResponses(label, toolNames) {
};
}
+/**
+ * A phase whose middle batch holds a failed call beside a slow one: `slow_echo`
+ * called without its required `text` fails schema validation before the tool
+ * runs, and a second `slow_echo` keeps the batch live for `delay` ms so a spec
+ * can watch the fold while it streams.
+ */
+function activityFailedReplyResponses(label, toolNames) {
+ const rememberTool = Array.from(toolNames).find((name) =>
+ name.startsWith(STEER_TOOL_NAME_PREFIX),
+ );
+ const slowTool = Array.from(toolNames).find((name) =>
+ name.startsWith(SLOW_ECHO_TOOL_NAME_PREFIX),
+ );
+ if (!rememberTool || !slowTool) {
+ return {
+ responses: [
+ `E2E activity failed reply unavailable: ${STEER_TOOL_NAME_PREFIX} and ${SLOW_ECHO_TOOL_NAME_PREFIX} tools required.`,
+ ],
+ };
+ }
+ let invocation = 0;
+ return {
+ responses: [''],
+ resolveInvocation: async () => {
+ invocation += 1;
+ if (invocation === 1) {
+ return {
+ response: '',
+ toolCalls: [
+ {
+ id: `call_e2e_activity_failed_alpha_${label}`,
+ name: rememberTool,
+ args: { fact: `activity failed alpha ${label}` },
+ type: 'tool_call',
+ },
+ ],
+ };
+ }
+ if (invocation === 2) {
+ return {
+ response: '',
+ toolCalls: [
+ {
+ id: `call_e2e_activity_failed_broken_${label}`,
+ name: slowTool,
+ args: { delay_ms: 10 },
+ type: 'tool_call',
+ },
+ {
+ id: `call_e2e_activity_failed_slow_${label}`,
+ name: slowTool,
+ args: { text: `activity failed slow ${label}`, delay_ms: 4000 },
+ type: 'tool_call',
+ },
+ ],
+ };
+ }
+ if (invocation === 3) {
+ return {
+ response: '',
+ toolCalls: [
+ {
+ id: `call_e2e_activity_failed_beta_${label}`,
+ name: rememberTool,
+ args: { fact: `activity failed beta ${label}` },
+ type: 'tool_call',
+ },
+ ],
+ };
+ }
+ return { response: `${ACTIVITY_FAILED_FINAL_TEXT} ${label}` };
+ },
+ };
+}
+
/**
* Pause a real agent run at the ask_user_question tool. The resume controller
* rebuilds the graph with an empty input-message list, so the test hook selects
@@ -2981,6 +3059,11 @@ function resolveResponses({ graph, messages, text, toolNames }) {
return activityPhaseReplyResponses(activityPhaseLabel, toolNames);
}
+ const activityFailedLabel = getMarkerValue(text, ACTIVITY_FAILED_REPLY_MARKER);
+ if (activityFailedLabel) {
+ return activityFailedReplyResponses(activityFailedLabel, toolNames);
+ }
+
const askUserQuestionLabel = getMarkerValue(text, ASK_USER_QUESTION_MARKER);
if (askUserQuestionLabel) {
return askUserQuestionResponses(askUserQuestionLabel, toolNames);
diff --git a/e2e/specs/mock/activity-fold.spec.ts b/e2e/specs/mock/activity-fold.spec.ts
new file mode 100644
index 0000000000..05d689900c
--- /dev/null
+++ b/e2e/specs/mock/activity-fold.spec.ts
@@ -0,0 +1,189 @@
+import fs from 'fs';
+import path from 'path';
+import { expect, test } from '@playwright/test';
+import type { APIRequestContext, Page } from '@playwright/test';
+import { NEW_CHAT_PATH, messagesView, selectMockEndpoint, sendMessage } from './helpers';
+
+const PHASE_ENDPOINT = { label: 'Mock Provider F', model: 'mock-model-f' };
+const MCP_SERVER_TITLE = 'E2E Memory';
+const LABEL_SERVER = `http://127.0.0.1:${process.env.E2E_LABEL_PORT || '8889'}`;
+const PHASE_LABEL = 'Gathered both facts around a broken echo';
+const SHOT_DIR = process.env.E2E_FOLD_SHOTS || '';
+
+const uniqueLabel = () => `fold-${Date.now()}-${Math.floor(Math.random() * 1e4)}`;
+
+async function shot(page: Page, name: string) {
+ if (!SHOT_DIR) {
+ return;
+ }
+ fs.mkdirSync(SHOT_DIR, { recursive: true });
+ await page.screenshot({ path: path.join(SHOT_DIR, `${name}.png`) });
+}
+
+async function setPhaseLabel(request: APIRequestContext) {
+ await request.post(`${LABEL_SERVER}/__e2e/reset`);
+ const response = await request.post(`${LABEL_SERVER}/__e2e/behavior`, {
+ data: { phaseLabel: PHASE_LABEL, labelsByPrompt: {} },
+ });
+ expect(response.ok()).toBeTruthy();
+}
+
+async function selectEphemeralMCP(page: Page) {
+ await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();
+ const serverItem = page.getByRole('menuitemcheckbox', { name: new RegExp(MCP_SERVER_TITLE) });
+ await expect(serverItem).toBeVisible();
+ await serverItem.click();
+ await expect(serverItem).toHaveAttribute('aria-checked', 'true');
+ await page.keyboard.press('Escape');
+ await expect(page.getByRole('button', { name: new RegExp(MCP_SERVER_TITLE) })).toBeVisible();
+}
+
+function collectPageProblems(page: Page): string[] {
+ const problems: string[] = [];
+ page.on('pageerror', (error) => problems.push(`pageerror: ${error.message}`));
+ page.on('console', (message) => {
+ if (message.type() === 'error' || message.text().includes('Warning:')) {
+ problems.push(`console.${message.type()}: ${message.text().slice(0, 300)}`);
+ }
+ });
+ return problems;
+}
+
+test.describe('activity fold', () => {
+ test('titles the open fold, rails its rows and reaches the failed call in one click', async ({
+ page,
+ request,
+ }) => {
+ test.setTimeout(120000);
+ const problems = collectPageProblems(page);
+ const label = uniqueLabel();
+ const finalText = `E2E activity failed reply done ${label}`;
+ await setPhaseLabel(request);
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, PHASE_ENDPOINT);
+ await selectEphemeralMCP(page);
+ const run = await sendMessage(page, `E2E_ACTIVITY_FAILED_REPLY:${label}`);
+ expect(run.ok()).toBeTruthy();
+
+ /** The live span: sample the fold while the slow echo keeps the batch
+ * open, so the streaming header and any pill it grows are on record. */
+ const liveHeaders: string[] = [];
+ for (let index = 0; index < 8; index += 1) {
+ await page.waitForTimeout(600);
+ const card = messagesView(page).getByTestId('activity-phase-card').first();
+ if (await card.isVisible().catch(() => false)) {
+ liveHeaders.push((await card.innerText()).replace(/\s+/g, ' ').trim());
+ await shot(page, `live-${index}`);
+ }
+ }
+ /** The header ticks through the run's live lines before the label lands. */
+ expect(liveHeaders.some((line) => /Running/.test(line))).toBe(true);
+
+ await expect(messagesView(page).getByText(finalText)).toBeVisible({ timeout: 60000 });
+ const header = messagesView(page).getByRole('button', { name: PHASE_LABEL, exact: true });
+ await expect(header).toBeVisible({ timeout: 30000 });
+ await expect(header).toHaveAttribute('aria-expanded', 'false');
+ await shot(page, 'settled-collapsed');
+
+ const pill = messagesView(page).getByTestId('failed-reveal-pill');
+ const peek = messagesView(page).getByTestId('activity-phase-failed-peek');
+ await expect(pill).toBeVisible();
+ await expect(pill).toHaveAccessibleName('Show failed call');
+ await expect(peek).toBeVisible();
+ await expect(peek).toContainText('Failed:');
+ await expect(peek).toContainText('Show error');
+
+ /** One click from the closed card to the open error panel. */
+ await peek.click();
+ await expect(header).toHaveAttribute('aria-expanded', 'true');
+ await expect(peek).toBeHidden();
+ const failedRow = messagesView(page)
+ .locator('[data-testid="tool-call"]')
+ .filter({ hasText: /^Failed:/ });
+ await expect(failedRow).toBeVisible();
+ await expect(failedRow).toContainText('failed');
+ const failedId = await failedRow.getAttribute('data-tool-call-id');
+ const panel = messagesView(page).locator(`[data-tool-call-output-id="${failedId}"]`);
+ await expect(panel).toContainText(/error/i, { timeout: 5000 });
+ /** Focus lands on the failed row's own disclosure button, not a wrapper. */
+ expect(
+ await page.evaluate(() => {
+ const active = document.activeElement;
+ return {
+ tag: active?.tagName,
+ row: active?.closest('[data-testid="tool-call"]')?.getAttribute('data-tool-call-id'),
+ };
+ }),
+ ).toEqual({ tag: 'BUTTON', row: failedId });
+ await shot(page, 'revealed');
+
+ /** The open header is the title: primary, semibold, over railed rows. */
+ await expect(header).toHaveClass(/font-semibold/);
+ await expect(header).toHaveClass(/text-text-primary/);
+ const rail = messagesView(page).getByTestId('activity-phase-panel').locator('> div').first();
+ await expect(rail).toHaveClass(/pl-6/);
+ /** Only the group holding the failure opened; its sibling groups stay
+ * folded under the phase. The slow echo shares that batch. */
+ expect(await messagesView(page).locator('[data-testid="tool-call"]').count()).toBe(2);
+ await expect(messagesView(page).getByTestId('tool-call-group-panel')).toHaveCount(3);
+
+ /** Closing by the header brings the peek back; the pill then does the
+ * same reveal from the closed state. */
+ await header.click();
+ await expect(header).toHaveAttribute('aria-expanded', 'false');
+ await expect(peek).toBeVisible();
+ await pill.click();
+ await expect(header).toHaveAttribute('aria-expanded', 'true');
+ await expect(panel).toContainText(/error/i);
+ await shot(page, 'revealed-by-pill');
+
+ /** Survives a reload from the persisted message. */
+ await page.reload();
+ const reloaded = messagesView(page).getByRole('button', { name: PHASE_LABEL, exact: true });
+ await expect(reloaded).toBeVisible({ timeout: 30000 });
+ await expect(messagesView(page).getByTestId('failed-reveal-pill')).toBeVisible();
+ await expect(messagesView(page).getByTestId('activity-phase-failed-peek')).toBeVisible();
+ await shot(page, 'reloaded-collapsed');
+ await messagesView(page).getByTestId('activity-phase-failed-peek').click();
+ await expect(
+ messagesView(page).locator('[data-tool-call-output-id]').filter({ hasText: /error/i }),
+ ).toBeVisible();
+ await page.emulateMedia({ colorScheme: 'dark' });
+ await page.waitForTimeout(400);
+ await shot(page, 'reloaded-revealed-dark');
+ await page.emulateMedia({ colorScheme: 'light' });
+
+ expect(problems.filter((line) => !line.includes('favicon'))).toEqual([]);
+ });
+
+ test('a phase without failures shows neither pill nor peek', async ({ page, request }) => {
+ test.setTimeout(120000);
+ const problems = collectPageProblems(page);
+ const label = uniqueLabel();
+ const finalText = `E2E activity phase reply done ${label}`;
+ await setPhaseLabel(request);
+
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, PHASE_ENDPOINT);
+ await selectEphemeralMCP(page);
+ const run = await sendMessage(page, `E2E_ACTIVITY_PHASE_REPLY:${label}`);
+ expect(run.ok()).toBeTruthy();
+ await expect(messagesView(page).getByText(finalText)).toBeVisible({ timeout: 60000 });
+ const header = messagesView(page).getByRole('button', { name: PHASE_LABEL, exact: true });
+ await expect(header).toBeVisible({ timeout: 30000 });
+ await expect(messagesView(page).getByTestId('failed-reveal-pill')).toHaveCount(0);
+ await expect(messagesView(page).getByTestId('activity-phase-failed-peek')).toHaveCount(0);
+ await shot(page, 'clean-collapsed');
+ await header.click();
+ await expect(header).toHaveAttribute('aria-expanded', 'true');
+ await shot(page, 'clean-open');
+ /** Groups inside a settled phase start collapsed; the phase summary speaks for them. */
+ const group = messagesView(page).getByTestId('tool-call-group-panel').first();
+ const groupHeader = group.locator('xpath=preceding-sibling::div[1]//button').first();
+ await groupHeader.click();
+ await expect(messagesView(page).locator('[data-testid="tool-call"]').first()).toBeVisible();
+ await shot(page, 'clean-open-group');
+ expect(problems.filter((line) => !line.includes('favicon'))).toEqual([]);
+ });
+});