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: Hold a Live Run's Activity at One Row (#16118)

Danny Avila1f66e9a8e579
diff --git a/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx b/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx
index dd51f89f8f..dfae90a0c1 100644
--- a/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx
+++ b/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx
@@ -1,18 +1,26 @@
-import { useId, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { memo, useId, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { Button } from '@librechat/client';
import { ContentTypes } from 'librechat-data-provider';
import { Check, ChevronDown, TriangleAlert } from 'lucide-react';
import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';
import type { CSSProperties, ReactNode } from 'react';
import {
+ useLocalize,
useExpandCollapse,
useLazyCollapseBody,
scheduleMessageContentLayoutReconcile,
EXPAND_TRANSITION,
} from '~/hooks';
+import { getLiveActivity, getSpanIconNames, LIVE_ACTIVITY_THROTTLE_MS } from './live';
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 { StackedToolIcons } from './ToolOutput';
+import { getSourceDomains } from './sources';
+import { mapAttachments } from '~/utils/map';
import SearchVerticals from './verticals';
import { AttachmentGroup } from './Parts';
import { cn } from '~/utils';
@@ -82,26 +90,57 @@ function PhaseGlyph({ failed }: { failed: boolean }) {
* row while the new summary comes up from below, so the work visibly moves
* into the line that now stands for it.
*/
-function PhaseLabel({
+/**
+ * The shimmering text of a live line, on its own element. `.shimmer` declares
+ * `animation`, `position` and `display`, so sharing an element with the ticker
+ * would replace the slide with the sweep — the retired line would never leave,
+ * and would sit inline beside its successor. `align-top` keeps the inline box
+ * from adding descender space, which made a live row 2px taller than the
+ * settled row it becomes.
+ */
+function LiveLine({ text }: { text: string }) {
+ return <span className="shimmer max-w-full truncate align-top">{text}</span>;
+}
+
+const PhaseLabel = memo(function PhaseLabel({
text,
animate,
failed,
+ source,
+ live = false,
+ lineId,
}: {
text: string;
animate: boolean;
failed: boolean;
+ /** Identity of what produced `text`. A streamed sentence keeps its source
+ * while it grows, and sliding a line out to bring a longer copy of itself
+ * in would read as flicker — so an unchanged source extends in place. */
+ source?: string;
+ live?: boolean;
+ /** Id for the current line, so a live disclosure can be named by it alone. */
+ lineId?: string;
}) {
- const [lines, setLines] = useState<{ current: string; retired: string | null; entered: boolean }>(
- { current: text, retired: null, entered: false },
- );
+ const [lines, setLines] = useState<{
+ current: string;
+ retired: string | null;
+ entered: boolean;
+ source?: string;
+ }>({ current: text, retired: null, entered: false, source });
/** Adjusted during render rather than in an effect. A passive effect runs
* after paint, so a swap with no animation would leave the previous summary
* on screen for a frame while the button's `aria-label` already carried the
* new one. React re-renders this component immediately instead. */
- if (lines.current !== text) {
- const swaps = animate && lines.current.length > 0;
- setLines({ current: text, retired: swaps ? lines.current : null, entered: swaps });
+ if (lines.current !== text || lines.source !== source) {
+ const moved = source == null || source !== lines.source;
+ const swaps = animate && lines.current.length > 0 && moved;
+ setLines({
+ current: text,
+ retired: swaps ? lines.current : null,
+ entered: swaps || (lines.entered && source != null && source === lines.source),
+ source,
+ });
}
/** Clears only the retired line. `entered` outlives it on purpose: dropping
@@ -116,7 +155,6 @@ function PhaseLabel({
return (
<span
className="tool-status-text relative block min-w-0 flex-1 overflow-hidden text-left"
- role="status"
title={text}
>
{lines.retired != null && (
@@ -128,24 +166,182 @@ function PhaseLabel({
FOLD_EASING,
failed && 'text-text-warning',
)}
- onAnimationEnd={clearRetired}
+ /** The sweep on the inner span loops forever and its `animationend`
+ * never comes; only this element's own slide may clear the line. */
+ onAnimationEnd={(event) => event.target === event.currentTarget && clearRetired()}
aria-hidden="true"
>
- {lines.retired}
+ {live ? <LiveLine text={lines.retired} /> : lines.retired}
</span>
)}
<span
- key={`current-${lines.current}`}
+ /** Keyed by source while live, so a growing sentence updates one
+ * element instead of remounting — and replaying its slide — per paint. */
+ key={`current-${source ?? lines.current}`}
+ id={lineId}
className={cn(
'block truncate',
lines.entered && `animate-in fade-in-0 slide-in-from-bottom-5 ${FOLD_EASING}`,
failed && 'text-text-warning',
)}
>
- {lines.current}
+ {live ? <LiveLine text={lines.current} /> : lines.current}
</span>
</span>
);
+});
+
+/** Glyphs a span header shows: up to this many, of which at most `SPAN_SITES`
+ * are the sites a web search read. */
+const SPAN_ICONS = 4;
+const SPAN_SITES = 3;
+
+/**
+ * The settled header's glyph: what the span USED, not a bare check. A header
+ * stands for the rows it hides, so it carries the most specific glyphs they
+ * show — tool and MCP server icons, and the sites a web search read — and the
+ * row keeps the icons it had while live instead of trading them for a tick.
+ * Its own component so only a card that was handed its parts pays for the MCP
+ * lookup. A failed phase keeps the warning glyph: status outranks identity.
+ */
+function SpanGlyph({
+ parts,
+ attachments,
+}: {
+ parts: ReadonlyArray<TMessageContentParts | undefined>;
+ attachments?: TAttachment[];
+}) {
+ const mcpIconMap = useMCPIconMap();
+ const iconNames = useMemo(() => getSpanIconNames(parts), [parts]);
+ const outcome = useMemo(
+ () => summarizeSpan(parts, mapAttachments(attachments ?? [])),
+ [parts, attachments],
+ );
+ const sourceDomains = useMemo(() => getSourceDomains(attachments, SPAN_SITES), [attachments]);
+ if (iconNames.length === 0 && outcome.failed === 0 && outcome.cancelled === 0) {
+ return <PhaseGlyph failed={false} />;
+ }
+ return (
+ <span className={cn(ROW_GLYPH_SLOT, 'text-text-secondary')} aria-hidden="true">
+ <StackedToolIcons
+ toolNames={iconNames}
+ mcpIconMap={mcpIconMap}
+ maxIcons={SPAN_ICONS}
+ sourceDomains={sourceDomains}
+ status={getOutcomeStatus(outcome)}
+ />
+ </span>
+ );
+}
+
+/**
+ * The header of a span the run is still writing: the span's tool icons,
+ * pulsing, in the slot the settled check takes over, beside the newest line.
+ *
+ * Its own component so only a live card pays for it — the localization and MCP
+ * lookups, and the throttle. `liveParts` is rebuilt on every streamed delta;
+ * the throttle is what keeps that from reaching the DOM more than twice a
+ * second.
+ */
+function LivePhaseHeader({
+ parts,
+ animate,
+ lineId,
+ detailId,
+ attachments,
+ onAnnounce,
+}: {
+ parts: ReadonlyArray<TMessageContentParts | undefined>;
+ animate: boolean;
+ lineId: string;
+ detailId: string;
+ attachments?: TAttachment[];
+ onAnnounce: (text: string) => void;
+}) {
+ const localize = useLocalize();
+ const mcpIconMap = useMCPIconMap();
+ const mcpServerNames = useMCPServerNames();
+ const attachmentsById = useMemo(() => mapAttachments(attachments ?? []), [attachments]);
+ const activity = useMemo(
+ () => getLiveActivity(parts, localize, mcpServerNames, attachmentsById),
+ [parts, localize, mcpServerNames, attachmentsById],
+ );
+ const { text, source } = activity;
+ const line = useMemo(() => ({ text, source }), [text, source]);
+ const painted = useThrottledValue(line, LIVE_ACTIVITY_THROTTLE_MS);
+ const iconKey = activity.iconNames.join('|');
+ const iconNames = useMemo(() => (iconKey ? iconKey.split('|') : []), [iconKey]);
+ const sourceDomains = useMemo(() => getSourceDomains(attachments, SPAN_SITES), [attachments]);
+
+ /** The span's verdict, separate from its newest line: an earlier call can
+ * fail while a later one runs, and the line alone would never say so. The
+ * hidden group header carries the same counts in the same words. */
+ const { failed, cancelled } = activity.outcome;
+ const detail = useMemo(() => {
+ const notes: string[] = [];
+ if (failed > 0) {
+ notes.push(
+ 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', {
+ 0: String(cancelled),
+ }),
+ );
+ }
+ return notes.join(' · ');
+ }, [failed, cancelled, localize]);
+
+ /** 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
+ * spoken the moment it changes, because `running → failed` on one call
+ * keeps its source and would otherwise wait for the next call to be heard. */
+ const spokenRef = useRef({ source: painted.source, text: painted.text, detail: '' });
+ useEffect(() => {
+ const spoken = spokenRef.current;
+ if (detail !== spoken.detail && detail) {
+ onAnnounce(detail);
+ } else if (painted.source !== spoken.source && spoken.text) {
+ onAnnounce(spoken.text);
+ }
+ spokenRef.current = { source: painted.source, text: painted.text, detail };
+ }, [painted, detail, onAnnounce]);
+
+ return (
+ <>
+ <span className={ROW_GLYPH_SLOT} aria-hidden="true">
+ <StackedToolIcons
+ toolNames={iconNames}
+ mcpIconMap={mcpIconMap}
+ maxIcons={SPAN_ICONS}
+ sourceDomains={sourceDomains}
+ status={getOutcomeStatus(activity.outcome)}
+ isAnimating
+ />
+ </span>
+ <PhaseLabel
+ text={painted.text}
+ source={painted.source}
+ failed={false}
+ animate={animate}
+ live
+ lineId={lineId}
+ />
+ {detail && (
+ <span
+ id={detailId}
+ className="shrink-0 text-xs font-normal text-text-warning"
+ data-testid="live-phase-outcome"
+ >
+ · {detail}
+ </span>
+ )}
+ </>
+ );
}
export default function ActivityPhaseGroup({
@@ -156,6 +352,8 @@ export default function ActivityPhaseGroup({
showCursor = false,
animateEntrance = false,
hasPendingApproval = false,
+ liveParts,
+ spanParts,
}: {
labelPart: ActivityPhasePart;
children: ReactNode;
@@ -170,7 +368,14 @@ export default function ActivityPhaseGroup({
showCursor?: boolean;
animateEntrance?: boolean;
hasPendingApproval?: boolean;
+ /** The span's parts while the run is still writing it. Present, the header
+ * reads the newest activity out of them — throttled — instead of a
+ * generated label, and renders as a live row rather than a settled one. */
+ liveParts?: ReadonlyArray<TMessageContentParts | undefined>;
+ /** The span's parts once settled, for the header's icon stack. */
+ spanParts?: ReadonlyArray<TMessageContentParts | undefined>;
}) {
+ const isLive = liveParts != null;
const label = getActivityLabelText(labelPart);
const hasFailure = labelPart.status === 'failed' || labelPart.status === 'partial';
/** Already `smoothStreaming && !reducedMotion` — it owns the media query, so
@@ -196,6 +401,21 @@ export default function ActivityPhaseGroup({
const [isSettled, setIsSettled] = useState(!foldsIn);
const rootRef = useRef<HTMLDivElement | null>(null);
const panelId = useId();
+ const lineId = useId();
+ const detailId = useId();
+ /** One polite region for the card's whole life. It sits outside the button,
+ * so it never joins the disclosure's name, and it outlives the live header:
+ * a region that mounts already holding text is not announced, so the
+ * generated summary is spoken through the region that was there before. */
+ const [announcement, setAnnouncement] = useState('');
+ const previousHeader = useRef({ isLive, label });
+ useEffect(() => {
+ const previous = previousHeader.current;
+ previousHeader.current = { isLive, label };
+ if (!isLive && label && (previous.isLive || previous.label !== label)) {
+ setAnnouncement(label);
+ }
+ }, [isLive, label]);
const cancelEntranceRef = useRef<(() => void) | null>(null);
const cancelLayoutReconcileRef = useRef<(() => void) | null>(null);
const previousIsExpandedRef = useRef(isExpanded);
@@ -298,7 +518,7 @@ export default function ActivityPhaseGroup({
<AttachmentGroup attachments={attachments} />
</>
) : null;
- if (!label) {
+ if (!label && !isLive) {
return (
<>
{children}
@@ -332,6 +552,9 @@ export default function ActivityPhaseGroup({
* gap, no inset. Boxing it was what put its text on a third left edge and
* forced every folded row 13px sideways as the box materialized. */
<div className="mb-2 mt-1 w-full" ref={rootRef} data-testid="activity-phase-card">
+ <span className="sr-only" role="status" data-testid="activity-phase-announcer">
+ {announcement}
+ </span>
<div style={headerStyle}>
<div className="overflow-hidden">
<Button
@@ -343,14 +566,37 @@ 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="inline-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="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"
onClick={handleToggle}
aria-expanded={isExpanded}
aria-controls={panelId}
- aria-label={label}
+ /** A live header is named by its own content: the line it shows
+ * is resolved inside `LivePhaseHeader`, below this component. It
+ * 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-labelledby={isLive ? `${lineId} ${detailId}` : undefined}
>
- <PhaseGlyph failed={hasFailure} />
- <PhaseLabel text={label} failed={hasFailure} animate={smoothStreaming} />
+ {isLive ? (
+ <LivePhaseHeader
+ parts={liveParts}
+ animate={smoothStreaming}
+ lineId={lineId}
+ detailId={detailId}
+ attachments={attachments}
+ onAnnounce={setAnnouncement}
+ />
+ ) : (
+ <>
+ {spanParts != null && !hasFailure ? (
+ <SpanGlyph parts={spanParts} attachments={attachments} />
+ ) : (
+ <PhaseGlyph failed={hasFailure} />
+ )}
+ <PhaseLabel text={label} failed={hasFailure} animate={smoothStreaming} />
+ </>
+ )}
<ChevronDown
className={cn(
'size-4 shrink-0 transition-transform duration-200 ease-out motion-reduce:transition-none',
diff --git a/client/src/components/Chat/Messages/Content/ContentParts.bench.tsx b/client/src/components/Chat/Messages/Content/ContentParts.bench.tsx
new file mode 100644
index 0000000000..b5e56dc1e1
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/ContentParts.bench.tsx
@@ -0,0 +1,231 @@
+import React, { Profiler } from 'react';
+import { RecoilRoot } from 'recoil';
+import { act, render } from '@testing-library/react';
+import { ContentTypes, Tools } from 'librechat-data-provider';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { TMessageContentParts } from 'librechat-data-provider';
+import ContentParts from './ContentParts';
+
+/**
+ * Render benchmark for a live agent run: one recorded-shape stream (batches of
+ * tool calls whose `intent` and args grow per delta, then outputs, then the
+ * batch label, then the phase summary and the answer) replayed through the
+ * real `ContentParts` tree. Lives outside `__tests__/` and is named
+ * `.bench.tsx` so the default jest run skips it; execute it explicitly with:
+ *
+ * node node_modules/jest/bin/jest.js --runInBand --coverage=false \
+ * --testMatch '**\/ContentParts.bench.tsx'
+ *
+ * Reported per scenario:
+ * - commits / totalMs: React Profiler commit count and summed actualDuration
+ * (jsdom wall-clock is not browser-accurate; the before/after ratio is).
+ * - peakNodes / nodeSteps: the largest DOM the run reached and the summed DOM
+ * size over every snapshot — deterministic stand-ins for mounted work.
+ * - shapeChanges: snapshots at which the element count moved, the closest
+ * jsdom gets to "the block changed height".
+ */
+
+jest.mock('~/hooks/MCP', () => {
+ const mcpServerNames: string[] = ['clickhouse'];
+ return {
+ useMCPIconMap: () => new Map(),
+ useMCPServerNames: () => mcpServerNames,
+ };
+});
+
+type Snapshot = TMessageContentParts[];
+
+const BATCHES = 4;
+const DELTAS_PER_TOOL = 12;
+const TEXT_DELTAS = 40;
+
+const INTENTS = [
+ 'Reading the lens reference to confirm which recovery section is missing.',
+ 'Querying the indexed graph for both Redis recovery references.',
+ 'Checking the current PR head and repository design guidance before selecting an execution model.',
+];
+const NAMES = ['read_file', 'run_select_query_mcp_clickhouse', Tools.execute_code];
+const LABELS = [
+ 'Loaded architecture workflow for Redis script execution',
+ 'Confirmed PR 16069 head and missing lens reference',
+ 'Confirmed both Redis recovery refs share commit',
+ 'Compared script caching against operation ordering',
+];
+const SUMMARY =
+ 'Validated Redis recovery references against PR 16069, identifying the missing lens reference';
+const ANSWER =
+ 'Yes, we can aim to merge before release. But the design needs to separate script caching from operation ordering, rather than make the cache helper responsible for both. '.repeat(
+ 4,
+ );
+
+const toolPart = (id: string, name: string, args: string, output: string): TMessageContentParts =>
+ ({
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id,
+ name,
+ args,
+ output,
+ type: 'tool_call',
+ progress: output ? 1 : 0.1,
+ },
+ }) as unknown as TMessageContentParts;
+
+const labelPart = (text: string, ids: string[]): TMessageContentParts =>
+ ({
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: text,
+ tool_call_ids: ids,
+ pending: text.length === 0,
+ }) as unknown as TMessageContentParts;
+
+const argsAt = (tool: number, delta: number): string => {
+ const intent = INTENTS[tool];
+ const head = intent.slice(0, Math.ceil((intent.length * Math.min(delta, 6)) / 6));
+ if (delta <= 6) {
+ return `{"intent":"${head}`;
+ }
+ return `{"intent":"${intent}","code":"${'x = compute(1)\\n'.repeat(delta - 6)}`;
+};
+
+function buildStream(labelled: boolean): Snapshot[] {
+ const snapshots: Snapshot[] = [];
+ let content: Snapshot = [];
+ const commit = (next: Snapshot) => {
+ content = next;
+ snapshots.push(next);
+ };
+ const replace = (index: number, part: TMessageContentParts) => {
+ const next = content.slice();
+ next[index] = part;
+ commit(next);
+ };
+ for (let batch = 0; batch < BATCHES; batch += 1) {
+ const base = content.length;
+ const ids = NAMES.map((_, tool) => `call_${batch}_${tool}`);
+ for (let tool = 0; tool < NAMES.length; tool += 1) {
+ commit([...content, toolPart(ids[tool], NAMES[tool], '', '')]);
+ }
+ for (let delta = 1; delta <= DELTAS_PER_TOOL; delta += 1) {
+ for (let tool = 0; tool < NAMES.length; tool += 1) {
+ replace(base + tool, toolPart(ids[tool], NAMES[tool], argsAt(tool, delta), ''));
+ }
+ }
+ for (let tool = 0; tool < NAMES.length; tool += 1) {
+ const args = `${argsAt(tool, DELTAS_PER_TOOL)}"}`;
+ replace(base + tool, toolPart(ids[tool], NAMES[tool], args, 'ok: 3 rows'));
+ }
+ commit([...content, labelPart('', ids)]);
+ if (labelled) {
+ replace(content.length - 1, labelPart(LABELS[batch], ids));
+ }
+ }
+ if (labelled) {
+ commit([
+ ...content,
+ {
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: SUMMARY,
+ activity_label_type: 'phase',
+ activity_start_index: 0,
+ activity_end_index: content.length,
+ activity_count: BATCHES,
+ pending: false,
+ } as unknown as TMessageContentParts,
+ ]);
+ }
+ const textIndex = content.length;
+ for (let delta = 1; delta <= TEXT_DELTAS; delta += 1) {
+ const text = ANSWER.slice(0, Math.ceil((ANSWER.length * delta) / TEXT_DELTAS));
+ const next = content.slice();
+ next[textIndex] = { type: ContentTypes.TEXT, text } as unknown as TMessageContentParts;
+ commit(next);
+ }
+ return snapshots;
+}
+
+type Result = {
+ commits: number;
+ totalMs: number;
+ peakNodes: number;
+ nodeSteps: number;
+ shapeChanges: number;
+};
+
+function replay(snapshots: Snapshot[]): Result {
+ const result: Result = { commits: 0, totalMs: 0, peakNodes: 0, nodeSteps: 0, shapeChanges: 0 };
+ const queryClient = new QueryClient();
+ const tree = (content: Snapshot, isSubmitting: boolean) => (
+ <QueryClientProvider client={queryClient}>
+ <RecoilRoot>
+ <Profiler
+ id="run"
+ onRender={(_id, _phase, actualDuration) => {
+ result.commits += 1;
+ result.totalMs += actualDuration;
+ }}
+ >
+ <ContentParts
+ content={content}
+ messageId="bench-message"
+ conversationId="bench-convo"
+ isCreatedByUser={false}
+ isLast
+ isLatestMessage
+ isSubmitting={isSubmitting}
+ showThinking={false}
+ />
+ </Profiler>
+ </RecoilRoot>
+ </QueryClientProvider>
+ );
+ jest.useFakeTimers();
+ const view = render(tree([], true));
+ let previousNodes = -1;
+ for (const content of snapshots) {
+ view.rerender(tree(content, true));
+ /** A delta every 50ms, so anything time-based sees a realistic stream. */
+ act(() => {
+ jest.advanceTimersByTime(50);
+ });
+ const nodes = view.container.getElementsByTagName('*').length;
+ result.peakNodes = Math.max(result.peakNodes, nodes);
+ result.nodeSteps += nodes;
+ if (previousNodes >= 0 && nodes !== previousNodes) {
+ result.shapeChanges += 1;
+ }
+ previousNodes = nodes;
+ }
+ view.rerender(tree(snapshots[snapshots.length - 1], false));
+ act(() => {
+ jest.advanceTimersByTime(1000);
+ });
+ view.unmount();
+ jest.useRealTimers();
+ return result;
+}
+
+const median = (values: number[]): number =>
+ values.slice().sort((a, b) => a - b)[values.length >> 1];
+
+describe('ContentParts live-run render benchmark', () => {
+ it.each([
+ ['labelled run (activity labels on)', true],
+ ['unlabelled run (feature off)', false],
+ ])('%s', (name, labelled) => {
+ const snapshots = buildStream(labelled);
+ replay(snapshots);
+ const runs = [replay(snapshots), replay(snapshots), replay(snapshots)];
+ const report = {
+ scenario: name,
+ snapshots: snapshots.length,
+ commits: runs[0].commits,
+ totalMs: Number(median(runs.map((run) => run.totalMs)).toFixed(1)),
+ peakNodes: runs[0].peakNodes,
+ nodeSteps: runs[0].nodeSteps,
+ shapeChanges: runs[0].shapeChanges,
+ };
+ console.log(`BENCH ${JSON.stringify(report)}`);
+ expect(report.commits).toBeGreaterThan(0);
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/ContentParts.tsx b/client/src/components/Chat/Messages/Content/ContentParts.tsx
index 28edd1f613..8a72411bbe 100644
--- a/client/src/components/Chat/Messages/Content/ContentParts.tsx
+++ b/client/src/components/Chat/Messages/Content/ContentParts.tsx
@@ -35,6 +35,7 @@ import { EmptyText, AgentUpdate } from './Parts';
import ApprovalProvider from './ApprovalContext';
import Sources from '~/components/Web/Sources';
import ToolCallGroup from './ToolCallGroup';
+import { blocksLiveFold } from './live';
import Container from './Container';
import Part from './Part';
@@ -224,6 +225,11 @@ type ContentPartsProps = {
| ((value: number) => void | React.Dispatch<React.SetStateAction<number>>)
| null
| undefined;
+ /** Whether the span a run is still writing folds into one row. The host
+ * decides: false when the reader asked for tools expanded by default, and
+ * for a surface that IS the detail view of a run — a subagent's activity
+ * panel — where one row would hide what the panel was opened to watch. */
+ foldLiveActivity?: boolean;
/** Internal recursion guard for nested phase segments. */
nestedActivityPhase?: boolean;
/** Internal signal that the parent phase card lifted this segment's
@@ -280,6 +286,7 @@ const ContentPartsBody = memo(function ContentPartsBody({
showThinking,
isLatestMessage,
createdAt,
+ foldLiveActivity = true,
nestedActivityPhase = false,
withinActivityPhase = false,
cursorOwnedElsewhere = false,
@@ -364,9 +371,13 @@ const ContentPartsBody = memo(function ContentPartsBody({
[laneGroups, content],
);
+ const foldsLiveTail = foldLiveActivity && isLast && effectiveIsSubmitting;
const phaseSegments = useMemo(
- () => (nestedActivityPhase ? undefined : groupActivityPhases(content, messageLaneGroups)),
- [nestedActivityPhase, content, messageLaneGroups],
+ () =>
+ nestedActivityPhase
+ ? undefined
+ : groupActivityPhases(content, messageLaneGroups, foldsLiveTail),
+ [nestedActivityPhase, content, messageLaneGroups, foldsLiveTail],
);
/** Every file a phase's parts produced, in transcript order, deduplicated
* across parts that share a tool call. */
@@ -671,16 +682,21 @@ const ContentPartsBody = memo(function ContentPartsBody({
const occurrence =
resolvedToolGroupOccurrences.get(getToolGroupAnchorIndex(group.parts)) ?? 1;
const groupId = occurrence === 1 ? baseGroupId : `${baseGroupId}:occurrence:${occurrence}`;
+ /** Collected even when a parent phase hoists the files: the header still
+ * reads them for the sites a web search visited. */
const seenAttachments = new Set<TAttachment>();
- if (!hideAttachments) {
- for (const { part } of group.parts) {
- for (const attachment of attachmentsForPart(part) ?? []) {
- seenAttachments.add(attachment);
- }
+ for (const { part } of group.parts) {
+ for (const attachment of attachmentsForPart(part) ?? []) {
+ seenAttachments.add(attachment);
}
}
const groupAttachments = hideAttachments ? undefined : Array.from(seenAttachments);
- return { ...group, groupId, groupAttachments };
+ return {
+ ...group,
+ groupId,
+ groupAttachments,
+ sourceAttachments: Array.from(seenAttachments),
+ };
});
}, [
sequentialParts,
@@ -854,6 +870,7 @@ const ContentPartsBody = memo(function ContentPartsBody({
);
}
const synthesized = segment.synthesized === true;
+ const live = segment.live === true;
/** Entrance bookkeeping still keys on the marker. */
const phaseKeyIndex = getPartKeyIndex(segment.labelPart, segment.labelIndex);
/** The RENDER key is the span, not the header. A synthesized card's
@@ -911,7 +928,18 @@ const ContentPartsBody = memo(function ContentPartsBody({
* can raise one long after its parent's label filled. The span
* renders exactly as it would without the feature until it
* clears, then folds. */
- if (synthesized && hasPendingApproval) {
+ /** "Open thinking dropdowns by default" is the reader asking to
+ * see reasoning as it streams. A collapsed live row would unmount
+ * it, so a reasoning-bearing span stays unfolded for them — the
+ * same exception `ToolCallGroup` makes to its auto-collapse. */
+ const keepsThinkingOpen =
+ live &&
+ showThinking &&
+ segment.content.some((part) => part?.type === ContentTypes.THINK);
+ const awaitsReader = live
+ ? keepsThinkingOpen || segment.content.some(blocksLiveFold)
+ : hasPendingApproval;
+ if (synthesized && awaitsReader) {
return renderSegment(
segment.content,
absoluteIndexAt(segment.startIndex),
@@ -926,6 +954,8 @@ const ContentPartsBody = memo(function ContentPartsBody({
hasContent={segment.hasContent}
attachments={phaseAttachments}
hasPendingApproval={hasPendingApproval}
+ liveParts={live ? segment.content : undefined}
+ spanParts={segment.hasContent ? segment.content : undefined}
animateEntrance={
/** Never for a synthesized card. The entrance mounts a card
* OPEN and folds it shut, and this component remounts
@@ -943,8 +973,10 @@ const ContentPartsBody = memo(function ContentPartsBody({
(previousPhases.labels.get(labelText) ?? 0))
}
showCursor={
+ /** A live header shimmers; a cursor row beneath it would be
+ * a second liveness signal and a second row. */
synthesized
- ? ownsCursor
+ ? ownsCursor && !live
: isLast &&
effectiveIsSubmitting &&
absoluteIndexAt(segment.labelIndex) === globalLastContentIdx
@@ -955,7 +987,10 @@ const ContentPartsBody = memo(function ContentPartsBody({
absoluteIndexAt(segment.startIndex),
segmentIndices,
`phase-content-${cardKey}`,
- true,
+ /** Opening a live row should show the calls running, so its
+ * groups keep their own live expansion rather than the
+ * settled-phase default of staying shut. */
+ !live,
ownsCursor,
true,
)}
@@ -1067,6 +1102,7 @@ const ContentPartsBody = memo(function ContentPartsBody({
renderPart={renderGroupedPart}
lastContentIdx={lastContentIdx}
groupAttachments={group.groupAttachments}
+ sourceAttachments={group.sourceAttachments}
initialExpansionState={expansionState.get(groupId)}
showThinking={showThinking}
onExpansionChange={(state) => handleGroupExpansionChange(groupId, state)}
diff --git a/client/src/components/Chat/Messages/Content/Parts/intent.ts b/client/src/components/Chat/Messages/Content/Parts/intent.ts
index 25e8b16311..d9ecf9f68d 100644
--- a/client/src/components/Chat/Messages/Content/Parts/intent.ts
+++ b/client/src/components/Chat/Messages/Content/Parts/intent.ts
@@ -29,7 +29,7 @@ const INTENT_SCAN_CHARS = 2048;
*/
const INTENT_PREFIX_REGEX = /^\s*\{\s*"intent"\s*:\s*"((?:[^"\\]|\\.)*)(")?/;
-function boundIntentLabel(label: string): string | undefined {
+export function boundIntentLabel(label: string): string | undefined {
const singleLine = label.replace(/\s+/g, ' ').trim();
if (singleLine === '') {
return undefined;
@@ -64,25 +64,27 @@ function boundIntentLabel(label: string): string | undefined {
* state (the shimmer stopping), not a tense change (see `applyOutcome` in
* `@librechat/agents` for why there is deliberately no rewrite).
*/
-export function useToolCallIntent(args?: string | Record<string, unknown>): string | undefined {
- return useMemo(() => {
- if (args == null) {
- return undefined;
- }
- if (typeof args === 'object') {
- if (Object.keys(args)[0] !== 'intent') {
- return undefined;
- }
- const value = args.intent;
- return typeof value === 'string' ? boundIntentLabel(value) : undefined;
- }
- const match = INTENT_PREFIX_REGEX.exec(args.slice(0, INTENT_SCAN_CHARS));
- if (!match) {
+export function getToolCallIntent(args?: string | Record<string, unknown>): string | undefined {
+ if (args == null) {
+ return undefined;
+ }
+ if (typeof args === 'object') {
+ if (Object.keys(args)[0] !== 'intent') {
return undefined;
}
- /** A captured closing quote means the value is settled: decode it
- * without the stream-edge hold-backs, so a value genuinely ending in
- * a lone high surrogate matches its JSON.parse rendering. */
- return boundIntentLabel(unescapeJsonString(match[1], match[2] !== '"'));
- }, [args]);
+ const value = args.intent;
+ return typeof value === 'string' ? boundIntentLabel(value) : undefined;
+ }
+ const match = INTENT_PREFIX_REGEX.exec(args.slice(0, INTENT_SCAN_CHARS));
+ if (!match) {
+ return undefined;
+ }
+ /** A captured closing quote means the value is settled: decode it
+ * without the stream-edge hold-backs, so a value genuinely ending in
+ * a lone high surrogate matches its JSON.parse rendering. */
+ return boundIntentLabel(unescapeJsonString(match[1], match[2] !== '"'));
+}
+
+export function useToolCallIntent(args?: string | Record<string, unknown>): string | undefined {
+ return useMemo(() => getToolCallIntent(args), [args]);
}
diff --git a/client/src/components/Chat/Messages/Content/ToolCall.tsx b/client/src/components/Chat/Messages/Content/ToolCall.tsx
index 6bd9e52230..272c35952d 100644
--- a/client/src/components/Chat/Messages/Content/ToolCall.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolCall.tsx
@@ -317,7 +317,7 @@ export default function ToolCall({
*/
if (phase === 'failed') {
return function_name
- ? `${localize('com_ui_failed')}: ${function_name}`
+ ? localize('com_ui_failed_subject', { 0: function_name })
: 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 89aa5d3edf..573a8f4e45 100644
--- a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
@@ -2,202 +2,31 @@ import { useState, useRef, useMemo, useEffect, useCallback } from 'react';
import { useRecoilValue } from 'recoil';
import { Button } from '@librechat/client';
import { ChevronDown, MessageCircleQuestion, Users } from 'lucide-react';
-import { Tools, Constants, ContentTypes, ToolCallTypes } from 'librechat-data-provider';
-import type {
- TAttachment,
- TMessageContentParts,
- Agents,
- FunctionToolCall,
- PartMetadata,
-} from 'librechat-data-provider';
+import { Tools, Constants, ContentTypes } from 'librechat-data-provider';
+import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';
import type { PartWithIndex } from './ParallelContent';
+import type { ToolMeta } from './outcome';
import {
cn,
getToolDisplayLabel,
+ hasPendingAuthInPart,
hasPendingApprovalInPart,
getBatchActivityLabelPart,
getActivityLabelText,
} from '~/utils';
import { useLocalize, useExpandCollapse, scheduleMessageContentLayoutReconcile } from '~/hooks';
-import { parseBackgroundHandle, splitBackgroundAttachments } from './Parts/handle';
import { ASK_USER_QUESTION, getSubmittedAskAnswer } from '~/utils/approval';
-import { mapAttachments, filterAttachmentsForPart } from '~/utils/map';
import { ToolAuthWarning, ToolAuthWarningContext } from './auth';
import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';
-import { resolveToolCallPhase } from '~/utils/toolCallPhase';
import { AttachmentGroup, ReasoningCompact } from './Parts';
-import { isMemoryFailureOutput } from './Parts/MemoryCall';
-import { isError, StackedToolIcons } from './ToolOutput';
-import { isBashProgrammaticToolCall } from './routing';
+import { getOutcomeStatus, summarizeSpan } from './outcome';
+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 ToolMeta {
- name: string;
- iconName: string;
- hasOutput: boolean;
- failed: boolean;
- cancelled: boolean;
-}
-
-function hasFailedOutput(output: unknown): boolean {
- return typeof output === 'string' && isError(output);
-}
-
-/**
- * Group metadata must agree with the individual card, which resolves its
- * outcome from the run step's terminal verdict through `resolveToolCallPhase`.
- * Reading output alone leaves a step the run closed as `failed` with empty or
- * benign output counted as neither failed nor finished, so the group sits on
- * "Running" until the response ends and then reports that it ran successfully
- * with no failures while the card beside it shows the failure. A closed step
- * is never running. Parts carrying no terminal status keep the legacy
- * output/progress signal, which is all the older endpoints emit.
- */
-function resolveOutcome(
- runStepStatus: PartMetadata['runStepStatus'],
- completed: boolean,
- hasError: boolean,
-): Pick<ToolMeta, 'hasOutput' | 'failed' | 'cancelled'> {
- if (runStepStatus == null) {
- return { hasOutput: completed, failed: hasError, cancelled: false };
- }
- const phase = resolveToolCallPhase({
- runStepStatus,
- displayProgress: 1,
- reportedProgress: 1,
- isSubmitting: false,
- hasError,
- });
- return {
- hasOutput: phase !== 'running',
- failed: phase === 'failed',
- /** Tracked separately from `failed`: a stopped step is settled and not an
- * error, but the group still must not auto-collapse under a
- * success-sounding header with the only cancellation notice hidden in the
- * panel. */
- cancelled: phase === 'cancelled',
- };
-}
-
-function hasPendingAuth(part: TMessageContentParts): boolean {
- if (part.type !== ContentTypes.TOOL_CALL) {
- return false;
- }
- const toolCall = part[ContentTypes.TOOL_CALL];
- if (!toolCall || !('args' in toolCall)) {
- return false;
- }
- /** A step the run already closed can never be waiting on a sign-in, whatever
- * its progress says. `ToolCall` hides the sign-in button on a terminal
- * status, so counting it as pending here left the group showing a trust
- * warning with no authentication action behind it. */
- if (toolCall.runStepStatus != null) {
- return false;
- }
- const standardToolCall = toolCall as Agents.ToolCall & { progress?: number };
- const progress = standardToolCall.progress ?? 0.1;
-
- return (
- typeof standardToolCall.auth === 'string' && standardToolCall.auth.length > 0 && progress < 1
- );
-}
-
-function getToolMeta(
- part: TMessageContentParts,
- attachmentsByToolCallId?: Record<string, TAttachment[] | undefined>,
-): ToolMeta | null {
- if (part.type !== ContentTypes.TOOL_CALL) {
- return null;
- }
- const toolCall = part[ContentTypes.TOOL_CALL];
- if (!toolCall) {
- return null;
- }
- /** Terminal verdict lives on the outer `tool_call` object (`PartMetadata`),
- * not on the per-variant payload, so it is read before any narrowing cast. */
- const runStepStatus = toolCall.runStepStatus;
-
- const isStandard =
- 'args' in toolCall && (!toolCall.type || toolCall.type === ToolCallTypes.TOOL_CALL);
- if (isStandard) {
- /** `agentId` disambiguates attachments when a handoff response repeats a
- * provider tool-call id across agents; `filterAttachmentsForPart` reads it
- * the same way. */
- const tc = toolCall as Agents.ToolCall & { progress?: number; agentId?: string };
- /** Subagents can finish with `progress === 1` and no final output
- * text (the parent saw "" / undefined back). Fall back to progress
- * so the group header flips from "Running N agents" to "Ran N
- * agents" on completion even when the child returned no text. */
- const completed = !!tc.output || tc.progress === 1;
- const name = tc.name ?? '';
- const iconName = isBashProgrammaticToolCall(name, tc.args) ? Tools.bash_tool : name;
- /** Memory tools report failure in prose ("Invalid key ...") that generic
- * `isError` parsing does not recognize, so `MemoryCall` classifies it with
- * its own predicate. Reuse that here or a persisted call with no terminal
- * status shows a failed card inside a group claiming success. */
- const failedOutput =
- name === 'set_memory' || name === 'delete_memory'
- ? isMemoryFailureOutput(name, tc.output ?? '')
- : hasFailedOutput(tc.output);
- /** A backgrounded bash/code task reports its verdict through a
- * `background_task_status` attachment, not its output: the dispatch step
- * keeps a benign handle and usually closes as `completed`. The child card
- * folds that marker in as `extraError`, so without it here the group
- * reported no failed action beside a card showing failure. Correlated the
- * same way the child is, since provider tool-call ids repeat across agents
- * and execution steps in handoff responses. */
- const backgroundHandle = parseBackgroundHandle(tc.output);
- const backgroundStatus = splitBackgroundAttachments(
- filterAttachmentsForPart(attachmentsByToolCallId?.[tc.id ?? ''], tc.agentId, toolCall.stepId),
- tc.id,
- ).backgroundStatus;
- const backgroundFailed = backgroundHandle != null && backgroundStatus === 'error';
- const backgroundCancelled =
- tc.backgroundTask?.cancelled === true ||
- (backgroundHandle != null && backgroundStatus === 'cancelled');
- return {
- name,
- iconName,
- ...resolveOutcome(
- backgroundCancelled ? 'cancelled' : runStepStatus,
- completed,
- failedOutput || backgroundFailed,
- ),
- };
- }
-
- if (toolCall.type === ToolCallTypes.CODE_INTERPRETER) {
- const ci = (toolCall as { code_interpreter?: { outputs?: unknown[] } }).code_interpreter;
- return {
- name: 'code_interpreter',
- iconName: 'code_interpreter',
- ...resolveOutcome(runStepStatus, (ci?.outputs?.length ?? 0) > 0, false),
- };
- }
-
- if (toolCall.type === ToolCallTypes.RETRIEVAL || toolCall.type === ToolCallTypes.FILE_SEARCH) {
- const output = (toolCall as { output?: string }).output;
- return {
- name: 'file_search',
- iconName: 'file_search',
- ...resolveOutcome(runStepStatus, !!output, hasFailedOutput(output)),
- };
- }
-
- if (toolCall.type === ToolCallTypes.FUNCTION && ToolCallTypes.FUNCTION in toolCall) {
- const fn = (toolCall as FunctionToolCall).function;
- return {
- name: fn.name,
- iconName: fn.name,
- ...resolveOutcome(runStepStatus, !!fn.output, hasFailedOutput(fn.output)),
- };
- }
-
- return null;
-}
-
interface ToolCallGroupProps {
parts: PartWithIndex[];
isSubmitting: boolean;
@@ -211,6 +40,9 @@ interface ToolCallGroupProps {
) => React.ReactNode;
lastContentIdx: number;
groupAttachments?: TAttachment[];
+ /** The group's owned attachments for header glyphs AND outcomes, even when
+ * a parent phase hoists the files and `groupAttachments` is withheld. */
+ sourceAttachments?: TAttachment[];
initialExpansionState?: ToolCallGroupExpansionState;
onExpansionChange?: (state: ToolCallGroupExpansionState) => void;
/** Activity-label part terminating this block; when it carries generated
@@ -239,6 +71,7 @@ export default function ToolCallGroup({
renderPart,
lastContentIdx,
groupAttachments,
+ sourceAttachments,
initialExpansionState,
onExpansionChange,
labelPart,
@@ -254,19 +87,19 @@ export default function ToolCallGroup({
/** Re-keyed by tool-call id so each part's metadata sees only its own
* attachments: `groupAttachments` arrives flattened across the group. */
const attachmentsByToolCallId = useMemo(
- () => mapAttachments(groupAttachments ?? []),
- [groupAttachments],
+ () => mapAttachments(sourceAttachments ?? groupAttachments ?? []),
+ [sourceAttachments, groupAttachments],
);
/** `parts` may include interleaved reasoning ("Thoughts") parts that render
* inside the body but are not actions. Count and summarize only the real
* tool calls so the header and stacked icons stay accurate. */
- const toolMetadata = useMemo(
- () =>
- parts
- .map((p) => getToolMeta(p.part, attachmentsByToolCallId))
- .filter((m): m is ToolMeta => m != null),
- [parts, attachmentsByToolCallId],
- );
+ const toolMetadata = useMemo(() => {
+ const summary = summarizeSpan(
+ parts.map(({ part }) => part),
+ attachmentsByToolCallId,
+ );
+ return parts.map(({ part }) => summary.metaOf(part)).filter((m): m is ToolMeta => m != null);
+ }, [parts, attachmentsByToolCallId]);
const count = toolMetadata.length;
/** Approval state is read from the RAW parts, not `toolMetadata`: a pending
* call can be nested inside a subagent's content, which never surfaces as
@@ -289,6 +122,10 @@ export default function ToolCallGroup({
() => labelSettled || toolMetadata.every((m) => m.hasOutput === true),
[toolMetadata, labelSettled],
);
+ const sourceDomains = useMemo(
+ () => getSourceDomains(sourceAttachments ?? groupAttachments, 3),
+ [sourceAttachments, groupAttachments],
+ );
const iconToolNames = useMemo(() => toolMetadata.map((m) => m.iconName), [toolMetadata]);
/** Turn raw tool ids into an activity summary. Repeated calls retain their
@@ -603,13 +440,17 @@ export default function ToolCallGroup({
.join(', ');
/** Single category glyph for homogeneous groups (else StackedToolIcons). */
const CategoryIcon = allSubagents ? Users : MessageCircleQuestion;
+ const iconStatus = getOutcomeStatus({
+ failed: activityFailed ? 1 : activitySummary.failedCount,
+ cancelled: activitySummary.cancelledCount,
+ });
const hasActiveToolCall = useMemo(
() => isSubmitting && toolMetadata.some((m) => m && !m.hasOutput),
[toolMetadata, isSubmitting],
);
const hasPendingAuthRequest = useMemo(
- () => parts.some(({ part }) => hasPendingAuth(part)),
+ () => parts.some(({ part }) => hasPendingAuthInPart(part)),
[parts],
);
@@ -630,7 +471,7 @@ export default function ToolCallGroup({
aria-expanded={isExpanded}
aria-label={groupAriaLabel}
>
- {allSubagents || allAskQuestions ? (
+ {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
@@ -652,6 +493,8 @@ export default function ToolCallGroup({
toolNames={iconToolNames}
mcpIconMap={mcpIconMap}
maxIcons={4}
+ sourceDomains={sourceDomains}
+ status={iconStatus}
isAnimating={isGroupLive}
/>
</div>
diff --git a/client/src/components/Chat/Messages/Content/ToolOutput/StackedToolIcons.tsx b/client/src/components/Chat/Messages/Content/ToolOutput/StackedToolIcons.tsx
index 6ffd0d4c9d..cae3bee14f 100644
--- a/client/src/components/Chat/Messages/Content/ToolOutput/StackedToolIcons.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolOutput/StackedToolIcons.tsx
@@ -1,6 +1,8 @@
import { useMemo } from 'react';
+import { TriangleAlert, X } from 'lucide-react';
import type { ToolIconType } from './ToolIcon';
import ToolIcon, { getToolIconType, getMCPServerName } from './ToolIcon';
+import { FaviconImage } from '~/components/Web/SourceHovercard';
import { useMCPServerNames } from '~/hooks/MCP';
import { cn } from '~/utils';
@@ -8,6 +10,8 @@ interface ResolvedIcon {
key: string;
type: ToolIconType;
iconUrl?: string;
+ /** A site a web search read, shown as its favicon. */
+ domain?: string;
}
interface StackedToolIconsProps {
@@ -15,6 +19,12 @@ interface StackedToolIconsProps {
mcpIconMap?: Map<string, string>;
maxIcons?: number;
isAnimating?: boolean;
+ /** A hidden action's terminal warning takes precedence over its identity. */
+ status?: 'failed' | 'cancelled';
+ /** Sites the stack's web searches read. They take the generic search
+ * glyph's place: a header stands for rows it hides, so it shows the most
+ * specific glyph those rows do. */
+ sourceDomains?: readonly string[];
}
export default function StackedToolIcons({
@@ -22,6 +32,8 @@ export default function StackedToolIcons({
mcpIconMap,
maxIcons = 3,
isAnimating = false,
+ sourceDomains,
+ status,
}: StackedToolIconsProps) {
const mcpServerNames = useMCPServerNames();
const uniqueIcons = useMemo(() => {
@@ -31,6 +43,15 @@ export default function StackedToolIcons({
const type = getToolIconType(name);
const serverName = getMCPServerName(name, mcpServerNames);
const iconUrl = serverName ? mcpIconMap?.get(serverName) : undefined;
+ if (type === 'web_search' && sourceDomains != null && sourceDomains.length > 0) {
+ for (const domain of sourceDomains) {
+ if (!seen.has(`site-${domain}`)) {
+ seen.add(`site-${domain}`);
+ result.push({ key: `site-${domain}`, type, domain });
+ }
+ }
+ continue;
+ }
const key = iconUrl ? `mcp-${serverName}` : type;
if (!seen.has(key)) {
seen.add(key);
@@ -38,12 +59,17 @@ export default function StackedToolIcons({
}
}
return result;
- }, [toolNames, mcpIconMap, mcpServerNames]);
+ }, [toolNames, mcpIconMap, mcpServerNames, sourceDomains]);
+
+ if (status != null) {
+ const StatusIcon = status === 'failed' ? TriangleAlert : X;
+ return <StatusIcon className="size-4 shrink-0 text-text-warning" aria-hidden="true" />;
+ }
const visibleIcons = uniqueIcons.slice(0, maxIcons);
const overflowCount = uniqueIcons.length - visibleIcons.length;
- if (visibleIcons.length <= 1) {
+ if (visibleIcons.length <= 1 && visibleIcons[0]?.domain == null) {
const icon = visibleIcons[0];
return (
<ToolIcon type={icon?.type ?? 'generic'} iconUrl={icon?.iconUrl} isAnimating={isAnimating} />
@@ -62,12 +88,16 @@ export default function StackedToolIcons({
)}
style={{ zIndex: visibleIcons.length - index }}
>
- <ToolIcon
- type={icon.type}
- iconUrl={icon.iconUrl}
- isAnimating={isAnimating}
- className="size-3"
- />
+ {icon.domain != null ? (
+ <FaviconImage domain={icon.domain} className="size-3 rounded-full" />
+ ) : (
+ <ToolIcon
+ type={icon.type}
+ iconUrl={icon.iconUrl}
+ isAnimating={isAnimating}
+ className="size-3"
+ />
+ )}
</div>
))}
{overflowCount > 0 && (
diff --git a/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx b/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx
index 21ec24fdfc..61babdc270 100644
--- a/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolOutput/ToolIcon.tsx
@@ -1,6 +1,7 @@
import { Constants, isActionTool, splitToolCallName } from 'librechat-data-provider';
import {
Terminal,
+ Users,
Globe,
ImageIcon,
ArrowRightLeft,
@@ -25,6 +26,7 @@ export type ToolIconType =
| 'execute_code'
| 'web_search'
| 'image_gen'
+ | 'subagent'
| 'agent_handoff'
| 'file_search'
| 'skill'
@@ -41,6 +43,7 @@ const ICON_MAP: Record<ToolIconType, React.ComponentType<{ className?: string }>
web_search: Globe,
image_gen: ImageIcon,
agent_handoff: ArrowRightLeft,
+ subagent: Users,
file_search: FileSearch,
skill: ScrollText,
read_file: FileText,
@@ -82,6 +85,9 @@ export function getToolIconType(name: string): ToolIconType {
if (name === 'bash_tool' || name === Constants.BASH_PROGRAMMATIC_TOOL_CALLING) {
return 'bash_tool';
}
+ if (name === Constants.SUBAGENT) {
+ return 'subagent';
+ }
if (name === 'ask_user_question') {
return 'ask_user_question';
}
diff --git a/client/src/components/Chat/Messages/Content/WebSearch.tsx b/client/src/components/Chat/Messages/Content/WebSearch.tsx
index 342910b39d..6ecaad54a8 100644
--- a/client/src/components/Chat/Messages/Content/WebSearch.tsx
+++ b/client/src/components/Chat/Messages/Content/WebSearch.tsx
@@ -19,6 +19,7 @@ import type {
} from 'librechat-data-provider';
import { FaviconImage, getCleanDomain } from '~/components/Web/SourceHovercard';
import { useLocalize, useExpandCollapse, useLazyCollapseBody } from '~/hooks';
+import { collectSources, getUniqueDomainSources } from './sources';
import { StackedFavicons } from '~/components/Web/Sources';
import { toolPanelSpacingClassName } from './disclosure';
import parseJsonField from './Parts/parseJsonField';
@@ -37,43 +38,6 @@ type ProgressKeys =
const MAX_VISIBLE_FAVICONS = 3;
-function collectSources(results: Record<string, SearchResultData>): ValidSource[] {
- const sourceMap = new Map<string, ValidSource>();
- for (const result of Object.values(results)) {
- if (!result) {
- continue;
- }
- result.organic?.forEach((s) => {
- if (s.link) {
- sourceMap.set(s.link, s);
- }
- });
- result.topStories?.forEach((s) => {
- if (s.link) {
- sourceMap.set(s.link, s);
- }
- });
- }
- return Array.from(sourceMap.values());
-}
-
-function getUniqueDomainSources(sources: ValidSource[], max: number): ValidSource[] {
- const seen = new Set<string>();
- const result: ValidSource[] = [];
- for (const source of sources) {
- const domain = getCleanDomain(source.link);
- if (seen.has(domain)) {
- continue;
- }
- seen.add(domain);
- result.push(source);
- if (result.length >= max) {
- break;
- }
- }
- return result;
-}
-
function SourceFaviconStack({ sources }: { sources: ValidSource[] }) {
const visible = getUniqueDomainSources(sources, MAX_VISIBLE_FAVICONS);
return (
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 172bcd94aa..4bba28c065 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ActivityPhaseGroup.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ActivityPhaseGroup.test.tsx
@@ -1,5 +1,5 @@
import { ContentTypes, Tools } from 'librechat-data-provider';
-import { act, fireEvent, render, screen } from '@testing-library/react';
+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';
@@ -225,14 +225,18 @@ describe('ActivityPhaseGroup', () => {
const retired = screen.getByText(LABEL);
expect(retired).toHaveClass('animate-out', 'slide-out-to-top-5');
expect(retired).toHaveAttribute('aria-hidden', 'true');
- expect(screen.getByText(NEXT_LABEL)).toHaveClass('animate-in', 'slide-in-from-bottom-5');
+ expect(
+ within(screen.getByRole('button', { name: NEXT_LABEL })).getByText(NEXT_LABEL),
+ ).toHaveClass('animate-in', 'slide-in-from-bottom-5');
/** Retiring the outgoing line must not strip the incoming one's animation
* class: both run for the same 300ms, so removing it on the partner's
* `animationend` would snap a slide that is still in flight. */
fireEvent.animationEnd(retired);
expect(screen.queryByText(LABEL)).not.toBeInTheDocument();
- expect(screen.getByText(NEXT_LABEL)).toHaveClass('animate-in', 'slide-in-from-bottom-5');
+ expect(
+ within(screen.getByRole('button', { name: NEXT_LABEL })).getByText(NEXT_LABEL),
+ ).toHaveClass('animate-in', 'slide-in-from-bottom-5');
});
test('swaps the header outright when smooth streaming is off', () => {
@@ -251,7 +255,9 @@ describe('ActivityPhaseGroup', () => {
);
expect(screen.queryByText(LABEL)).not.toBeInTheDocument();
- expect(screen.getByText(NEXT_LABEL)).not.toHaveClass('animate-in');
+ expect(
+ within(screen.getByRole('button', { name: NEXT_LABEL })).getByText(NEXT_LABEL),
+ ).not.toHaveClass('animate-in');
});
test('keeps historical phases closed without replaying the entrance', () => {
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx
index 6ac97dad44..25358086f2 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx
@@ -1,7 +1,7 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { ContentTypes, Tools } from 'librechat-data-provider';
-import { fireEvent, render, screen, within } from '@testing-library/react';
+import { act, fireEvent, render, screen, within } from '@testing-library/react';
import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';
import ContentParts from '../ContentParts';
@@ -88,6 +88,7 @@ jest.mock('../Parts', () => ({
AgentUpdate: () => <div data-testid="agent-update" />,
EmptyText: () => <div data-testid="empty-text" />,
Reasoning: () => <div data-testid="reasoning" />,
+ ReasoningCompact: () => <div data-testid="compact-reasoning" />,
Summary: () => <div data-testid="summary" />,
Text: ({ text }: { text?: string }) => <div data-testid="text">{text}</div>,
MemoryCall: ({ attachments }: { attachments?: TAttachment[] }) => (
@@ -514,6 +515,9 @@ describe('ContentParts integration: MCP image hoist and grouping', () => {
</RecoilRoot>,
);
+ /** A live run is one collapsed row; the reader opens it to reach the group,
+ * which still auto-expands around its running calls. */
+ fireEvent.click(screen.getByRole('button', { name: /com_assistants_running_var/ }));
const toggle = screen.getByRole('button', { name: /^Running 2 actions/ });
expect(toggle).toHaveAttribute('aria-expanded', 'true');
@@ -645,15 +649,29 @@ describe('ContentParts — synthesized activity folds', () => {
);
});
- it('leaves the in-flight tool call outside the card', () => {
+ it('keeps the in-flight tool call inside the card while the run streams', () => {
renderContentParts({
...baseProps,
isSubmitting: true,
content: [...labeledRun(), makeMcpToolCall('t3', false)],
});
- /** The call the reader is watching stays a sibling of the card, so it is
- * still on screen once the fold settles shut over everything before it. */
+ /** The header speaks for the call the reader is watching, so the block
+ * stays one row instead of growing a sibling row per call. */
+ expect(screen.getAllByTestId('activity-phase-card')).toHaveLength(1);
+ expect(screen.queryByTestId('tool-call')).toBeNull();
+ expect(screen.getByRole('button', { name: /com_assistants_running_var/ })).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ });
+
+ it('leaves the in-flight tool call outside a settled card', () => {
+ renderContentParts({
+ ...baseProps,
+ content: [...labeledRun(), makeMcpToolCall('t3', false)],
+ });
+
const panel = screen.getByTestId('activity-phase-panel');
expect(panel.contains(screen.getByTestId('tool-call'))).toBe(false);
});
@@ -791,7 +809,11 @@ describe('ContentParts — synthesized activity folds', () => {
* the whole fold back open partway through the run. */
renderContentParts({ ...baseProps, isSubmitting: true, content: labeledRun() });
- expect(foldHeader()).toHaveAttribute('aria-expanded', 'false');
+ /** A live header is named by the line it shows rather than an `aria-label`. */
+ expect(screen.getByRole('button', { name: new RegExp(TICKER) })).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
expect(screen.queryByRole('button', { name: FIRST })).toBeNull();
});
@@ -919,22 +941,21 @@ describe('ContentParts — synthesized activity folds', () => {
expect(foldHeader()).toHaveAttribute('aria-expanded', 'true');
});
- it('shows exactly one streaming cursor when a placeholder trails the fold', () => {
- /** Providers append an empty TEXT slot after visible output. The cursor
- * belongs to the card (the run's tail is inside its span), and that
- * trailing slot looks like the initial waiting state from inside its own
- * segment — so without the ownership signal both render one. The card
- * draws its own in-flow dot; the segment's `EmptyText` must stay out. */
+ it('lets the live header stand in for the cursor when a placeholder trails the fold', () => {
+ /** Providers append an empty TEXT slot after visible output. The run's
+ * tail is inside the card's span, and that trailing slot looks like the
+ * initial waiting state from inside its own segment. The live header's
+ * shimmer is the liveness signal: a cursor row under it would be a second
+ * row, and the segment's `EmptyText` a third. */
const { container } = renderContentParts({
...baseProps,
isSubmitting: true,
content: [...labeledRun(), makeTextPart('')],
});
- const dots = container.querySelectorAll('.result-thinking');
- expect(dots).toHaveLength(1);
- expect(dots[0]).toHaveClass('after:!static');
+ expect(container.querySelectorAll('.result-thinking')).toHaveLength(0);
expect(screen.queryAllByTestId('empty-text')).toHaveLength(0);
+ expect(screen.getByTestId('activity-phase-card').querySelector('.shimmer')).not.toBeNull();
});
it('leaves an unlabeled run rendering exactly as before', () => {
@@ -1133,3 +1154,442 @@ describe('ContentParts integration: lane groups backed by one agent', () => {
);
});
});
+
+describe('ContentParts — live activity fold', () => {
+ const liveProps = {
+ messageId: 'msg1',
+ isCreatedByUser: false,
+ isLast: true,
+ showThinking: false,
+ isSubmitting: true,
+ isLatestMessage: true,
+ };
+
+ const intentCall = (id: string, intent: string, output = ''): TMessageContentParts =>
+ ({
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id, name: 'lookup', args: `{"intent":"${intent}`, output },
+ }) as unknown as TMessageContentParts;
+
+ const liveHeader = () =>
+ within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0];
+
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it('holds an unlabeled running batch at one collapsed row without mounting its cards', () => {
+ renderContentParts({
+ ...liveProps,
+ content: [intentCall('t1', 'Reading the lens file'), intentCall('t2', 'Querying the graph')],
+ });
+
+ expect(liveHeader()).toHaveAttribute('aria-expanded', 'false');
+ expect(liveHeader()).toHaveTextContent('Querying the graph');
+ expect(screen.queryByTestId('tool-call')).toBeNull();
+ expect(screen.queryByRole('button', { name: /^Running 2 actions/ })).toBeNull();
+ });
+
+ it('folds from the very first call so the block never changes shape as calls arrive', () => {
+ const { rerender } = renderContentParts({
+ ...liveProps,
+ content: [intentCall('t1', 'Reading the lens file')],
+ });
+ expect(screen.getAllByRole('button')).toHaveLength(1);
+
+ rerender(
+ <RecoilRoot>
+ <ContentParts
+ {...liveProps}
+ content={[intentCall('t1', 'Reading the lens file', 'ok'), intentCall('t2', 'Next')]}
+ />
+ </RecoilRoot>,
+ );
+ expect(screen.getAllByRole('button')).toHaveLength(1);
+ });
+
+ it('paints the first line at once, then at most one newer line per interval', () => {
+ jest.useFakeTimers();
+ const frame = (content: TMessageContentParts[]) => (
+ <RecoilRoot>
+ <ContentParts {...liveProps} content={content} />
+ </RecoilRoot>
+ );
+ const { rerender } = render(frame([intentCall('t1', 'Reading')]));
+ expect(liveHeader()).toHaveTextContent('Reading');
+
+ rerender(frame([intentCall('t1', 'Reading the lens')]));
+ rerender(frame([intentCall('t1', 'Reading the lens file')]));
+ expect(liveHeader()).not.toHaveTextContent('Reading the lens');
+
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+ expect(liveHeader()).toHaveTextContent('Reading the lens file');
+ });
+
+ it('lets a filled batch label take the line over from the call it describes', () => {
+ renderContentParts({
+ ...liveProps,
+ content: [
+ intentCall('t1', 'Reading the lens file', 'ok'),
+ {
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: 'Confirmed the missing lens',
+ pending: false,
+ } as unknown as TMessageContentParts,
+ ],
+ });
+
+ expect(liveHeader()).toHaveTextContent('Confirmed the missing lens');
+ });
+
+ it('previews reasoning between calls one sentence at a time, in the same single row', () => {
+ jest.useFakeTimers();
+ const frame = (think: string) => (
+ <RecoilRoot>
+ <ContentParts
+ {...liveProps}
+ content={[
+ intentCall('t1', 'Reading the lens file', 'ok'),
+ { type: ContentTypes.THINK, think } as unknown as TMessageContentParts,
+ ]}
+ />
+ </RecoilRoot>
+ );
+ const { rerender } = render(frame('Both refs share a commit.'));
+ expect(liveHeader()).toHaveTextContent('Both refs share a commit.');
+ expect(screen.queryByTestId('reasoning')).toBeNull();
+
+ rerender(frame('Both refs share a commit. That leaves the ordering'));
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+ expect(liveHeader()).toHaveTextContent('That leaves the ordering');
+ /** The previous sentence is the `aria-hidden` line sliding out, which is
+ * the tick itself; the row's current line is the new sentence alone. */
+ expect(within(liveHeader()).getByTitle('That leaves the ordering')).toBeInTheDocument();
+ expect(screen.getAllByRole('button')).toHaveLength(1);
+ });
+
+ it('leaves a reasoning-bearing span unfolded when thinking opens by default', () => {
+ renderContentParts({
+ ...liveProps,
+ showThinking: true,
+ content: [
+ intentCall('t1', 'Reading the lens file', 'ok'),
+ {
+ type: ContentTypes.THINK,
+ think: 'Weighing the refs.',
+ } as unknown as TMessageContentParts,
+ ],
+ });
+
+ expect(screen.queryByTestId('activity-phase-card')).toBeNull();
+ expect(screen.getByTestId('compact-reasoning')).toBeInTheDocument();
+ });
+
+ it('leaves reasoning that has not reached a tool call on its own row', () => {
+ renderContentParts({
+ ...liveProps,
+ content: [
+ { type: ContentTypes.THINK, think: 'Planning.' } as unknown as TMessageContentParts,
+ ],
+ });
+
+ expect(screen.queryByTestId('activity-phase-card')).toBeNull();
+ expect(screen.getByTestId('reasoning')).toBeInTheDocument();
+ });
+
+ it('renders a span that is waiting on a sign-in unfolded', () => {
+ const authCall = {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id: 't1',
+ name: `getTinyImage${MCP_DELIMITER}Everything`,
+ args: '{}',
+ output: '',
+ auth: 'https://example.com/oauth',
+ },
+ } as unknown as TMessageContentParts;
+ renderContentParts({ ...liveProps, content: [authCall] });
+
+ expect(screen.queryByTestId('activity-phase-card')).toBeNull();
+ expect(screen.getByTestId('tool-call')).toBeInTheDocument();
+ });
+
+ it('leaves the run unfolded when the host opts out (tools expanded by default, subagent panel)', () => {
+ renderContentParts({
+ ...liveProps,
+ foldLiveActivity: false,
+ content: [makeMcpToolCall('t1', false), makeMcpToolCall('t2', false)],
+ });
+
+ expect(screen.queryByTestId('activity-phase-card')).toBeNull();
+ expect(screen.getAllByTestId('tool-call')).toHaveLength(2);
+ });
+
+ it('names short commentary streamed after a call instead of holding the stale call', () => {
+ renderContentParts({
+ ...liveProps,
+ content: [
+ intentCall('t1', 'Reading the lens file', 'ok'),
+ { type: ContentTypes.TEXT, text: 'Now checking the callers.', phase: 'commentary' },
+ ] as TMessageContentParts[],
+ });
+
+ expect(liveHeader()).toHaveTextContent('Now checking the callers.');
+ });
+
+ it('reports a call the run closed as failed or cancelled, never as completed', () => {
+ const closed = (runStepStatus: string): TMessageContentParts =>
+ ({
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id: 't1',
+ name: 'lookup',
+ args: '{}',
+ output: '',
+ runStepStatus,
+ },
+ }) as unknown as TMessageContentParts;
+ const { unmount } = renderContentParts({ ...liveProps, content: [closed('failed')] });
+ expect(liveHeader()).toHaveTextContent('com_ui_failed_subject');
+ unmount();
+
+ renderContentParts({ ...liveProps, content: [closed('cancelled')] });
+ expect(liveHeader()).toHaveTextContent('com_ui_cancelled');
+ });
+
+ it('reports a cancelled background task even though its dispatch step completed', () => {
+ const dispatched = {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id: 't1',
+ name: 'lookup',
+ args: '{}',
+ output: 'dispatched',
+ runStepStatus: 'completed',
+ backgroundTask: { cancelled: true },
+ },
+ } as unknown as TMessageContentParts;
+ renderContentParts({ ...liveProps, content: [dispatched] });
+
+ expect(liveHeader()).toHaveTextContent('com_ui_cancelled');
+ });
+
+ it('renders unfolded while a subagent’s own call waits on a sign-in', () => {
+ const subagent = {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id: 's1',
+ name: 'lookup',
+ args: '{}',
+ output: '',
+ subagent_content: [
+ {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id: 'n1',
+ name: `getTinyImage${MCP_DELIMITER}Everything`,
+ args: '{}',
+ output: '',
+ auth: 'https://example.com/oauth',
+ },
+ },
+ ],
+ },
+ } as unknown as TMessageContentParts;
+ renderContentParts({ ...liveProps, content: [subagent] });
+
+ expect(screen.queryByTestId('activity-phase-card')).toBeNull();
+ });
+
+ it('reports a detached task that failed through its status attachment', () => {
+ const handle = JSON.stringify({
+ background_task_id: 'bg1',
+ tool: 'lookup',
+ status: 'running',
+ message: 'Dispatched. Poll with check_background_task.',
+ });
+ const dispatched = {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id: 't1',
+ name: 'lookup',
+ args: '{}',
+ output: handle,
+ runStepStatus: 'completed',
+ },
+ } as unknown as TMessageContentParts;
+ const failed = {
+ type: 'background_task_status',
+ status: 'error',
+ toolCallId: 't1',
+ messageId: 'msg1',
+ } as unknown as TAttachment;
+ renderContentParts({ ...liveProps, content: [dispatched], attachments: [failed] });
+
+ expect(liveHeader()).toHaveTextContent('com_ui_failed_subject');
+ });
+
+ it('keeps a handoff card out of the live row and folds the next agent’s calls after it', () => {
+ const transfer = {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id: 'h1',
+ name: 'lc_transfer_to_agent_b',
+ args: '{}',
+ output: '',
+ },
+ } as unknown as TMessageContentParts;
+ renderContentParts({
+ ...liveProps,
+ content: [makeMcpToolCall('t1'), transfer, intentCall('t2', 'Picking up the task')],
+ });
+
+ expect(screen.getByTestId('agent-handoff')).toBeInTheDocument();
+ expect(liveHeader()).toHaveTextContent('Picking up the task');
+ });
+
+ it('announces each finished line once through a polite region', () => {
+ jest.useFakeTimers();
+ const frame = (content: TMessageContentParts[]) => (
+ <RecoilRoot>
+ <ContentParts {...liveProps} content={content} />
+ </RecoilRoot>
+ );
+ const { rerender } = render(frame([intentCall('t1', 'Reading the lens file')]));
+ const status = () => screen.getByTestId('activity-phase-announcer');
+ expect(status()).toBeEmptyDOMElement();
+
+ rerender(
+ frame([intentCall('t1', 'Reading the lens file', 'ok'), intentCall('t2', 'Querying')]),
+ );
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+ expect(status()).toHaveTextContent('Reading the lens file');
+ });
+
+ /** One fixture per channel a call can report its outcome through. The live
+ * line reads the same resolver as the group header, so each must surface. */
+ const handleOutput = JSON.stringify({
+ background_task_id: 'bg1',
+ tool: 'lookup',
+ status: 'running',
+ message: 'Dispatched. Poll with check_background_task.',
+ });
+ const statusAttachment = (status: string) =>
+ ({
+ type: 'background_task_status',
+ status,
+ toolCallId: 't1',
+ messageId: 'msg1',
+ }) as unknown as TAttachment;
+ it.each([
+ [
+ 'a cancelled status attachment',
+ { name: 'lookup', output: handleOutput, runStepStatus: 'completed' },
+ [statusAttachment('cancelled')],
+ 'com_ui_cancelled',
+ ],
+ [
+ 'a memory tool failing in prose',
+ { name: 'set_memory', output: 'Invalid key "x". Must be one of: a' },
+ [],
+ 'com_ui_failed',
+ ],
+ ])('surfaces %s in the collapsed row', (_name, call, attachments, expected) => {
+ const part = {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id: 't1', args: '{}', ...call },
+ } as unknown as TMessageContentParts;
+ renderContentParts({ ...liveProps, content: [part], attachments });
+
+ expect(liveHeader()).toHaveTextContent(expected);
+ });
+
+ it('ends the live span at a legacy call mixed into an agents run', () => {
+ const codeInterpreter = {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id: 'ci1',
+ type: 'code_interpreter',
+ code_interpreter: { input: 'print(1)', outputs: [] },
+ },
+ } as unknown as TMessageContentParts;
+ renderContentParts({ ...liveProps, content: [makeMcpToolCall('t1'), codeInterpreter] });
+
+ expect(screen.queryByTestId('activity-phase-card')).toBeNull();
+ });
+
+ it('names the live disclosure by its current line alone, not the announced one', () => {
+ jest.useFakeTimers();
+ const frame = (content: TMessageContentParts[]) => (
+ <RecoilRoot>
+ <ContentParts {...liveProps} content={content} />
+ </RecoilRoot>
+ );
+ const { rerender } = render(frame([intentCall('t1', 'Reading the lens file')]));
+ rerender(
+ frame([intentCall('t1', 'Reading the lens file', 'ok'), intentCall('t2', 'Querying')]),
+ );
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+
+ expect(screen.getByTestId('activity-phase-announcer')).toHaveTextContent(
+ 'Reading the lens file',
+ );
+ expect(liveHeader()).toHaveAccessibleName('Querying');
+ });
+
+ it('leaves a span of legacy Assistants calls, which the header cannot name, unfolded', () => {
+ const codeInterpreter = {
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id: 'ci1',
+ type: 'code_interpreter',
+ code_interpreter: { input: 'print(1)', outputs: [] },
+ },
+ } as unknown as TMessageContentParts;
+ renderContentParts({ ...liveProps, content: [codeInterpreter] });
+
+ expect(screen.queryByTestId('activity-phase-card')).toBeNull();
+ });
+
+ it('stops folding once the answer starts, leaving the settled rendering', () => {
+ renderContentParts({
+ ...liveProps,
+ content: [makeMcpToolCall('t1'), makeMcpToolCall('t2'), makeTextPart('Here is the answer.')],
+ });
+
+ expect(screen.queryByTestId('activity-phase-card')).toBeNull();
+ expect(screen.getByRole('button', { name: /^Ran 2 actions/ })).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ });
+
+ it('keeps the reader’s toggle when the server summary replaces the live line', () => {
+ const calls = [makeMcpToolCall('t1'), makeMcpToolCall('t2')];
+ const { rerender } = renderContentParts({ ...liveProps, content: calls });
+ fireEvent.click(liveHeader());
+ expect(liveHeader()).toHaveAttribute('aria-expanded', 'true');
+
+ rerender(
+ <RecoilRoot>
+ <ContentParts
+ {...liveProps}
+ content={[...calls, makePhasePart(0, 2, 'Fetched two images')]}
+ />
+ </RecoilRoot>,
+ );
+
+ expect(screen.getByRole('button', { name: 'Fetched two images' })).toHaveAttribute(
+ 'aria-expanded',
+ '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
new file mode 100644
index 0000000000..453b46ec19
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx
@@ -0,0 +1,850 @@
+import React from 'react';
+import { RecoilRoot, useSetRecoilState } from 'recoil';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { act, fireEvent, render, screen, within } from '@testing-library/react';
+import { ContentTypes, Tools, Constants, ToolCallTypes } from 'librechat-data-provider';
+import type {
+ TAttachment,
+ TMessage,
+ TMessageContentParts,
+ SearchResultData,
+} from 'librechat-data-provider';
+import { resolveAskUserQuestionPart } from '~/utils/approval';
+import { sandboxStartingByToolCallId } from '~/store';
+import ContentParts from '../ContentParts';
+
+/**
+ * Parity between a live fold and the cards it unmounts.
+ *
+ * The folded row takes over everything its hidden cards used to say, so the
+ * contract is agreement, not a list of examples: given the same call and the
+ * attachments it owns, the REAL card and the folded summary must reach the
+ * same verdict. Nothing that decides an outcome is mocked here — the error
+ * parser, the phase resolver and the specialized cards are the real ones; only
+ * the MCP lookups, which need a server, are replaced.
+ */
+jest.mock('~/hooks/MCP', () => {
+ const mcpServerNames: string[] = [];
+ return { useMCPIconMap: () => new Map(), useMCPServerNames: () => mcpServerNames };
+});
+
+type Verdict = 'running' | 'completed' | 'failed' | 'cancelled';
+
+type Fixture = {
+ name: string;
+ call: Record<string, unknown>;
+ attachments?: TAttachment[];
+ verdict: Verdict;
+};
+
+const HANDLE = JSON.stringify({
+ background_task_id: 'bg1',
+ tool: 'lookup',
+ status: 'running',
+ message: 'Dispatched. Poll with check_background_task.',
+});
+
+const statusAttachment = (status: string, toolCallId = 't1'): TAttachment =>
+ ({
+ type: 'background_task_status',
+ status,
+ toolCallId,
+ messageId: 'm1',
+ }) as unknown as TAttachment;
+
+const memoryErrorAttachment = {
+ type: Tools.memory,
+ toolCallId: 't1',
+ messageId: 'm1',
+ [Tools.memory]: { type: 'error', key: 'diet', value: 'over the limit' },
+} as unknown as TAttachment;
+
+const FIXTURES: Fixture[] = [
+ { name: 'a call still running', call: { name: 'lookup', output: '' }, verdict: 'running' },
+ { name: 'a completed call', call: { name: 'lookup', output: 'rows' }, verdict: 'completed' },
+ {
+ name: 'a step the run closed as failed with benign output',
+ call: { name: 'lookup', output: 'rows', runStepStatus: 'failed' },
+ verdict: 'failed',
+ },
+ {
+ name: 'a step the run closed as cancelled',
+ call: { name: 'lookup', output: '', runStepStatus: 'cancelled' },
+ verdict: 'cancelled',
+ },
+ {
+ name: 'error-shaped output with no terminal status',
+ call: { name: 'lookup', output: 'Error processing tool: connection refused' },
+ verdict: 'failed',
+ },
+ {
+ name: 'a memory tool failing in prose',
+ call: { name: 'set_memory', output: 'Invalid key "x". Must be one of: diet' },
+ verdict: 'failed',
+ },
+ {
+ name: 'a memory tool failing through its error artifact',
+ call: { name: 'set_memory', output: 'Memory set for key "diet"' },
+ attachments: [memoryErrorAttachment],
+ verdict: 'failed',
+ },
+ {
+ name: 'a detached task that failed through its status attachment',
+ call: { name: Tools.execute_code, output: HANDLE, runStepStatus: 'completed' },
+ attachments: [statusAttachment('error')],
+ verdict: 'failed',
+ },
+ {
+ name: 'a detached task cancelled through its status attachment',
+ call: { name: Tools.execute_code, output: HANDLE, runStepStatus: 'completed' },
+ attachments: [statusAttachment('cancelled')],
+ verdict: 'cancelled',
+ },
+ {
+ name: 'a detached task carrying the cancelled flag',
+ call: {
+ name: Tools.execute_code,
+ output: HANDLE,
+ runStepStatus: 'completed',
+ backgroundTask: { cancelled: true },
+ },
+ verdict: 'cancelled',
+ },
+ {
+ name: 'a status attachment that belongs to a different call',
+ call: { name: Tools.execute_code, output: HANDLE, runStepStatus: 'completed' },
+ attachments: [statusAttachment('error', 'someone-else')],
+ verdict: 'completed',
+ },
+];
+
+const toPart = (call: Record<string, unknown>, id = 't1'): TMessageContentParts =>
+ ({
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: {
+ id,
+ args: '{}',
+ type: 'tool_call',
+ progress: call.output ? 1 : 0.1,
+ ...call,
+ },
+ }) as unknown as TMessageContentParts;
+
+const mount = (
+ content: TMessageContentParts[],
+ attachments: TAttachment[] | undefined,
+ fold: boolean,
+ searchResults?: Record<string, SearchResultData>,
+) =>
+ render(
+ <QueryClientProvider client={new QueryClient()}>
+ <RecoilRoot>
+ <ContentParts
+ content={content}
+ attachments={attachments}
+ searchResults={searchResults}
+ messageId="m1"
+ conversationId="c1"
+ isCreatedByUser={false}
+ isLast
+ isLatestMessage
+ isSubmitting
+ showThinking={false}
+ foldLiveActivity={fold}
+ />
+ </RecoilRoot>
+ </QueryClientProvider>,
+ );
+
+/** What the real card says, read the way a user would, in the real English
+ * strings: `ProgressText` appends "failed" on `failed`, swaps in the stop
+ * glyph on `cancelled`, and shimmers while `running`. */
+const cardVerdict = (container: HTMLElement): Verdict => {
+ if (/failed/i.test(container.textContent ?? '')) {
+ return 'failed';
+ }
+ if (container.querySelector('.lucide-x') != null) {
+ return 'cancelled';
+ }
+ return container.querySelector('.shimmer') != null ? 'running' : 'completed';
+};
+
+const foldVerdict = (): Verdict => {
+ const card = screen.getByTestId('activity-phase-card');
+ const outcome = within(card).queryByTestId('live-phase-outcome')?.textContent ?? '';
+ if (outcome.includes('failed')) {
+ return 'failed';
+ }
+ if (outcome.includes('cancelled')) {
+ return 'cancelled';
+ }
+ return /^Running (?!in background)/.test(within(card).getAllByRole('button')[0].textContent ?? '')
+ ? 'running'
+ : 'completed';
+};
+
+describe('live fold parity with the cards it hides', () => {
+ afterEach(() => {
+ jest.useRealTimers();
+ });
+
+ it.each(FIXTURES)('agrees with the real card on $name', ({ call, attachments, verdict }) => {
+ jest.useFakeTimers();
+ const cards = mount([toPart(call)], attachments, false);
+ /** A card eases its progress to completion over a few hundred ms; the
+ * verdict compared is the one it settles on, not the animation's lag. */
+ act(() => {
+ jest.advanceTimersByTime(2000);
+ });
+ expect(cardVerdict(cards.container)).toBe(verdict);
+ cards.unmount();
+
+ mount([toPart(call)], attachments, true);
+ expect(foldVerdict()).toBe(verdict);
+ });
+
+ it('does not charge a reused provider id with what an earlier step produced', () => {
+ /** Provider ids repeat across steps. The first save failed through an
+ * error artifact owned by its step; the second, with no step of its own
+ * yet, succeeded and must not inherit that artifact. */
+ const earlier = toPart(
+ { name: 'set_memory', output: 'Memory set for key "diet"', stepId: 's1' },
+ 'dup',
+ );
+ const later = toPart({ name: 'set_memory', output: 'Memory set for key "diet"' }, 'dup');
+ const artifact = { ...memoryErrorAttachment, toolCallId: 'dup', stepId: 's1' } as TAttachment;
+ mount([earlier, later], [artifact], true);
+ const button = within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0];
+
+ expect(within(button).getByTestId('live-phase-outcome')).toHaveTextContent('1 failed');
+ expect(button).not.toHaveTextContent(/^Failed/);
+ });
+
+ it('keeps a subagent card available even after its dispatch settles', () => {
+ /** Its card follows the subagent progress atom, which the row cannot. */
+ const running = mount([toPart({ name: 'subagent', output: '' })], undefined, true);
+ expect(screen.queryByTestId('activity-phase-card')).toBeNull();
+ running.unmount();
+
+ mount([toPart({ name: 'subagent', output: 'done' })], undefined, true);
+ expect(screen.queryByTestId('activity-phase-card')).toBeNull();
+ });
+
+ it('treats a second call that reuses a provider id as a new line', () => {
+ jest.useFakeTimers();
+ const first = toPart({ name: 'lookup', args: '{"intent":"First pass"}', output: 'ok' }, 'dup');
+ const second = toPart({ name: 'lookup', args: '{"intent":"Second pass"}', output: '' }, 'dup');
+ const view = mount([first], undefined, true);
+ view.rerender(
+ <QueryClientProvider client={new QueryClient()}>
+ <RecoilRoot>
+ <ContentParts
+ content={[first, second]}
+ messageId="m1"
+ conversationId="c1"
+ isCreatedByUser={false}
+ isLast
+ isLatestMessage
+ isSubmitting
+ showThinking={false}
+ />
+ </RecoilRoot>
+ </QueryClientProvider>,
+ );
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+
+ expect(screen.getByTestId('activity-phase-announcer')).toHaveTextContent('First pass');
+ });
+
+ it('previews CJK reasoning sentence by sentence', () => {
+ const think = {
+ type: ContentTypes.THINK,
+ think: '两个引用共享一个提交。接下来检查顺序约定',
+ } as unknown as TMessageContentParts;
+ mount([toPart({ name: 'lookup', output: 'rows' }), think], undefined, true);
+ const button = within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0];
+
+ expect(button).toHaveTextContent('接下来检查顺序约定');
+ expect(button).not.toHaveTextContent('两个引用');
+ });
+
+ it('keeps a CJK sentence that ends exactly at the tail instead of reverting to the call', () => {
+ const think = {
+ type: ContentTypes.THINK,
+ think: '两个引用共享一个提交。接下来检查顺序约定。',
+ } as unknown as TMessageContentParts;
+ mount([toPart({ name: 'lookup', output: 'rows' }), think], undefined, true);
+ const button = within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0];
+
+ expect(button).toHaveTextContent('接下来检查顺序约定。');
+ });
+
+ it.each([
+ ['still running, with no status marker yet', undefined, 'Running in background'],
+ [
+ 'finished, once its status marker arrives',
+ [statusAttachment('completed')],
+ 'Finished in background',
+ ],
+ ])('says what the real card says for a detached task %s', (_name, attachments, text) => {
+ const call = { name: Tools.execute_code, output: HANDLE, runStepStatus: 'completed' };
+ jest.useFakeTimers();
+ const cards = mount([toPart(call)], attachments, false);
+ act(() => {
+ jest.advanceTimersByTime(2000);
+ });
+ expect(cards.container).toHaveTextContent(text);
+ cards.unmount();
+
+ mount([toPart(call)], attachments, true);
+ expect(
+ within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0],
+ ).toHaveTextContent(text);
+ });
+
+ it('does not re-announce a sentence when the stream pauses after a space', () => {
+ jest.useFakeTimers();
+ const frame = (think: string) => (
+ <QueryClientProvider client={new QueryClient()}>
+ <RecoilRoot>
+ <ContentParts
+ content={[
+ toPart({ name: 'lookup', output: 'rows' }),
+ { type: ContentTypes.THINK, think } as unknown as TMessageContentParts,
+ ]}
+ messageId="m1"
+ conversationId="c1"
+ isCreatedByUser={false}
+ isLast
+ isLatestMessage
+ isSubmitting
+ showThinking={false}
+ />
+ </RecoilRoot>
+ </QueryClientProvider>
+ );
+ const view = render(frame('Both refs share'));
+ for (const next of ['Both refs share ', 'Both refs share a', 'Both refs share a ']) {
+ view.rerender(frame(next));
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+ }
+
+ expect(screen.getByTestId('activity-phase-announcer')).toBeEmptyDOMElement();
+ });
+
+ describe('glyphs the collapsed header surfaces', () => {
+ const searchAttachment = {
+ type: Tools.web_search,
+ toolCallId: 't1',
+ messageId: 'm1',
+ [Tools.web_search]: {
+ turn: 0,
+ organic: [
+ { link: 'https://www.youtube.com/watch?v=1', title: 'a' },
+ { link: 'https://www.cnbc.com/story', title: 'b' },
+ { link: 'https://www.cnbc.com/other', title: 'c' },
+ ],
+ },
+ } as unknown as TAttachment;
+ const search = toPart({ name: Tools.web_search, output: 'results' });
+ const sites = (root: HTMLElement) =>
+ Array.from(root.querySelectorAll('img')).map((image) => image.getAttribute('alt'));
+
+ const summary = (end: number, label = 'Reviewed the work'): TMessageContentParts =>
+ ({
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: label,
+ activity_label_type: 'phase',
+ activity_start_index: 0,
+ activity_end_index: end,
+ activity_count: end,
+ pending: false,
+ }) as TMessageContentParts;
+
+ it.each([true, false])('does not borrow another span’s streamed sites (fold=%s)', (fold) => {
+ const content = [search, toPart({ name: Tools.web_search }, 't2')];
+ const view = mount(content, [], fold, {
+ 0: searchAttachment[Tools.web_search] as SearchResultData,
+ });
+ const header = within(view.container).getAllByRole('button')[0];
+ expect(sites(header)).toEqual([]);
+ expect(header.querySelector('.lucide-globe')).not.toBeNull();
+ });
+
+ it('keeps sources from different calls whose search turn numbers repeat', () => {
+ const second = toPart({ name: Tools.web_search, output: 'results' }, 't2');
+ const secondAttachment = {
+ ...searchAttachment,
+ toolCallId: 't2',
+ [Tools.web_search]: {
+ turn: 0,
+ organic: [{ link: 'https://example.com/story', title: 'd' }],
+ },
+ } as TAttachment;
+ mount([search, second], [searchAttachment, secondAttachment], true);
+ const header = within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0];
+ expect(sites(header)).toEqual(['youtube.com', 'cnbc.com', 'example.com']);
+ });
+
+ it.each([
+ [ToolCallTypes.CODE_INTERPRETER, { code_interpreter: { outputs: [] } }, '.lucide-terminal'],
+ [ToolCallTypes.RETRIEVAL, {}, '.lucide-file-search'],
+ [ToolCallTypes.FILE_SEARCH, {}, '.lucide-file-search'],
+ [
+ ToolCallTypes.FUNCTION,
+ { function: { name: 'read_file', output: 'done' } },
+ '.lucide-file-text',
+ ],
+ ])('retains the real glyph for a settled legacy %s call', (type, payload, selector) => {
+ const legacy = {
+ type: ContentTypes.TOOL_CALL,
+ tool_call: { id: 'legacy', type, ...payload },
+ } as TMessageContentParts;
+ mount([legacy, summary(1)], undefined, true);
+ expect(
+ screen.getByRole('button', { name: 'Reviewed the work' }).querySelector(selector),
+ ).not.toBeNull();
+ });
+
+ it('retains the subagent glyph inside a mixed settled span', () => {
+ mount(
+ [
+ toPart({ name: Constants.SUBAGENT, output: 'done' }),
+ toPart({ name: 'read_file', output: 'done' }, 't2'),
+ summary(2),
+ ],
+ undefined,
+ true,
+ );
+ const header = screen.getByRole('button', { name: 'Reviewed the work' });
+ expect(header.querySelector('.lucide-users')).not.toBeNull();
+ expect(header.querySelector('.lucide-file-text')).not.toBeNull();
+ });
+
+ it.each([true, false])('puts failure ahead of site identity (fold=%s)', (fold) => {
+ const failed = toPart({ name: Tools.web_search, output: 'results', runStepStatus: 'failed' });
+ const view = mount(
+ [failed, toPart({ name: 'lookup', output: 'ok' }, 't2')],
+ [searchAttachment],
+ fold,
+ );
+ const header = within(view.container).getAllByRole('button')[0];
+ expect(header.querySelector('.lucide-triangle-alert')).not.toBeNull();
+ expect(sites(header)).toEqual([]);
+ });
+
+ it.each([true, false])('puts cancellation ahead of tool identity (fold=%s)', (fold) => {
+ const cancelled = toPart({ name: 'lookup', runStepStatus: 'cancelled' });
+ const view = mount(
+ [cancelled, toPart({ name: 'read_file', output: 'ok' }, 't2')],
+ undefined,
+ fold,
+ );
+ const header = within(view.container).getAllByRole('button')[0];
+ expect(header.querySelector('.lucide-x')).not.toBeNull();
+ });
+
+ it.each(['failed', 'cancelled'] as const)('retains %s after a span settles', (status) => {
+ mount(
+ [toPart({ name: 'read_file', output: 'done', runStepStatus: status }), summary(1)],
+ undefined,
+ true,
+ );
+ const header = screen.getByRole('button', { name: 'Reviewed the work' });
+ expect(
+ header.querySelector(status === 'failed' ? '.lucide-triangle-alert' : '.lucide-x'),
+ ).not.toBeNull();
+ });
+
+ it('retains attachment-backed failure on the nested group after files are hoisted', () => {
+ mount(
+ [
+ toPart({ name: 'set_memory', output: 'Memory saved' }),
+ toPart({ name: 'lookup', output: 'ok' }, 't2'),
+ summary(2),
+ ],
+ [memoryErrorAttachment],
+ true,
+ );
+ fireEvent.click(screen.getByRole('button', { name: 'Reviewed the work' }));
+ const group = screen.getByTestId('tool-call-group-panel')
+ .previousElementSibling as HTMLElement;
+ expect(group).toHaveAccessibleName(/1 failed/);
+ expect(group.querySelector('.lucide-triangle-alert')).not.toBeNull();
+ });
+
+ it('shows the sites a search read on the live row, one per domain, with no card mounted', () => {
+ mount([search], [searchAttachment], true);
+ const button = within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0];
+
+ expect(sites(button)).toEqual(['youtube.com', 'cnbc.com']);
+ expect(screen.queryByTestId('tool-call')).toBeNull();
+ });
+
+ it('keeps them on the settled summary instead of trading them for a check', () => {
+ const summary = {
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: 'Checked the announcement',
+ activity_label_type: 'phase',
+ activity_start_index: 0,
+ activity_end_index: 1,
+ activity_count: 1,
+ pending: false,
+ } as unknown as TMessageContentParts;
+ mount([search, summary], [searchAttachment], true);
+ const button = screen.getByRole('button', { name: 'Checked the announcement' });
+
+ expect(sites(button)).toEqual(['youtube.com', 'cnbc.com']);
+ });
+
+ it('shows them on an unfolded group header too', () => {
+ const second = toPart({ name: Tools.web_search, output: 'results' }, 't2');
+ const view = mount([search, second], [searchAttachment], false);
+ const header = within(view.container).getAllByRole('button')[0];
+
+ expect(sites(header)).toEqual(['youtube.com', 'cnbc.com']);
+ });
+
+ it('keeps the warning glyph on a failed summary: status outranks identity', () => {
+ const failed = {
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: 'Could not reach the site',
+ activity_label_type: 'phase',
+ activity_start_index: 0,
+ activity_end_index: 1,
+ activity_count: 1,
+ status: 'failed',
+ pending: false,
+ } as unknown as TMessageContentParts;
+ mount([search, failed], [searchAttachment], true);
+ const button = screen.getByRole('button', { name: 'Could not reach the site' });
+
+ expect(sites(button)).toEqual([]);
+ expect(button.querySelector('.lucide-triangle-alert')).not.toBeNull();
+ });
+ });
+
+ it('keeps an earlier failure on the row while a newer call is the line', () => {
+ mount(
+ [
+ toPart({ name: 'lookup', output: 'rows', runStepStatus: 'failed' }, 't1'),
+ toPart({ name: 'lookup', args: '{"intent":"Querying the graph', output: '' }, 't2'),
+ ],
+ undefined,
+ true,
+ );
+ const button = within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0];
+
+ expect(button).toHaveTextContent('Querying the graph');
+ expect(within(button).getByTestId('live-phase-outcome')).toHaveTextContent('1 failed');
+ expect(button).toHaveAccessibleName(/Querying the graph.*1 failed/);
+ });
+
+ it('announces a failure on the SAME call at once, without waiting for another source', () => {
+ jest.useFakeTimers();
+ const frame = (call: Record<string, unknown>) => (
+ <QueryClientProvider client={new QueryClient()}>
+ <RecoilRoot>
+ <ContentParts
+ content={[toPart(call)]}
+ messageId="m1"
+ conversationId="c1"
+ isCreatedByUser={false}
+ isLast
+ isLatestMessage
+ isSubmitting
+ showThinking={false}
+ />
+ </RecoilRoot>
+ </QueryClientProvider>
+ );
+ const view = render(frame({ name: 'lookup', output: '' }));
+ const announcer = () => screen.getByTestId('activity-phase-announcer');
+ expect(announcer()).toBeEmptyDOMElement();
+
+ view.rerender(frame({ name: 'lookup', output: '', runStepStatus: 'failed' }));
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+
+ expect(announcer()).toHaveTextContent('1 failed');
+ expect(announcer().closest('button')).toBeNull();
+ });
+
+ it('speaks the generated summary through the region that was already mounted', () => {
+ const calls = [toPart({ name: 'lookup', output: 'rows' }, 't1')];
+ const frame = (content: TMessageContentParts[]) => (
+ <QueryClientProvider client={new QueryClient()}>
+ <RecoilRoot>
+ <ContentParts
+ content={content}
+ messageId="m1"
+ conversationId="c1"
+ isCreatedByUser={false}
+ isLast
+ isLatestMessage
+ isSubmitting
+ showThinking={false}
+ />
+ </RecoilRoot>
+ </QueryClientProvider>
+ );
+ const view = render(frame(calls));
+ const before = screen.getByTestId('activity-phase-announcer');
+
+ view.rerender(
+ frame([
+ ...calls,
+ {
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: 'Fetched the rows',
+ activity_label_type: 'phase',
+ activity_start_index: 0,
+ activity_end_index: 1,
+ activity_count: 1,
+ pending: false,
+ } as unknown as TMessageContentParts,
+ ]),
+ );
+
+ const after = screen.getByTestId('activity-phase-announcer');
+ expect(after).toBe(before);
+ expect(after).toHaveTextContent('Fetched the rows');
+ });
+});
+
+describe('live activity hardening transitions', () => {
+ afterEach(() => jest.useRealTimers());
+
+ const frame = (content: TMessageContentParts[], extra?: React.ReactNode) => (
+ <QueryClientProvider client={new QueryClient()}>
+ <RecoilRoot>
+ {extra}
+ <ContentParts
+ content={content}
+ messageId="m1"
+ conversationId="c1"
+ isCreatedByUser={false}
+ isLast
+ isLatestMessage
+ isSubmitting
+ showThinking={false}
+ />
+ </RecoilRoot>
+ </QueryClientProvider>
+ );
+
+ function SandboxEvent() {
+ const setStarting = useSetRecoilState(sandboxStartingByToolCallId('sandbox-call'));
+ return <button onClick={() => setStarting(true)}>{'Start sandbox'}</button>;
+ }
+
+ it.each([
+ [Tools.bash_tool, { command: 'echo ready' }],
+ [Tools.execute_code, { lang: 'py', code: 'print(1)' }],
+ [Constants.PROGRAMMATIC_TOOL_CALLING, { lang: 'python', code: 'print(1)' }],
+ [Constants.BASH_PROGRAMMATIC_TOOL_CALLING, { code: 'echo ready' }],
+ ])('keeps %s subscribed through sandbox startup, then folds its result', (name, args) => {
+ jest.useFakeTimers();
+ const call = { name, args, output: '' };
+ const view = render(frame([toPart(call, 'sandbox-call')], <SandboxEvent />));
+ expect(screen.queryByTestId('activity-phase-card')).toBeNull();
+ fireEvent.click(screen.getByRole('button', { name: 'Start sandbox' }));
+ expect(view.container).toHaveTextContent('Starting sandbox');
+ view.rerender(
+ frame([toPart({ ...call, output: 'ok', runStepStatus: 'completed' }, 'sandbox-call')]),
+ );
+ expect(screen.getByTestId('activity-phase-card')).toBeInTheDocument();
+ });
+
+ it('folds an early code delta and keeps folding once its intent arrives', () => {
+ jest.useFakeTimers();
+ const view = render(frame([toPart({ name: Tools.execute_code, args: '', output: '' })]));
+ const card = screen.getByTestId('activity-phase-card');
+ view.rerender(
+ frame([
+ toPart({ name: Tools.execute_code, args: '{"intent":"Checking the data', output: '' }),
+ ]),
+ );
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+ expect(screen.getByTestId('activity-phase-card')).toBe(card);
+ expect(screen.getByRole('button')).toHaveAccessibleName('Checking the data');
+ });
+
+ it('keeps the optimistic question record visible through stale SSE copies and folds subsequent work', () => {
+ const question = { question: 'Which region?' };
+ const call = toPart({ name: 'ask_user_question', args: question, output: '' }, 'answered-ask');
+ const message = {
+ messageId: 'm1',
+ content: [
+ call,
+ {
+ type: 'ask_user_question',
+ ask_user_question: { actionId: 'answer-action', tool_call_id: 'answered-ask', question },
+ },
+ ],
+ } as TMessage;
+ resolveAskUserQuestionPart(message, 'answer-action', 'Europe');
+ const view = render(frame([call]));
+ expect(screen.queryByTestId('activity-phase-card')).toBeNull();
+ expect(screen.getByTestId('ask-user-question-call')).toHaveTextContent('Asked');
+ view.rerender(
+ frame([call, toPart({ name: 'lookup', args: { intent: 'Checking Europe' } }, 'next')]),
+ );
+ expect(screen.getByTestId('ask-user-question-call')).toHaveTextContent('Asked');
+ expect(screen.getByTestId('activity-phase-card')).toHaveTextContent('Checking Europe');
+ });
+
+ it('keeps a detached subagent outside the next live span', () => {
+ const output = JSON.stringify({
+ background_task_id: 'bg-child',
+ subagent_thread_id: 'thread',
+ tool: 'subagent',
+ subagent_type: 'self',
+ status: 'running',
+ message: 'Poll background_task_id',
+ });
+ render(
+ frame([
+ toPart({
+ name: 'subagent',
+ args: { run_in_background: true },
+ output,
+ runStepStatus: 'completed',
+ }),
+ toPart({ name: 'lookup', args: { intent: 'Continuing the parent' } }, 'next'),
+ ]),
+ );
+ const fold = screen.getByTestId('activity-phase-card');
+ expect(fold).toHaveTextContent('Continuing the parent');
+ expect(screen.getByText('Ran agent').closest('[data-testid="activity-phase-card"]')).toBeNull();
+ });
+
+ it.each(['x'.repeat(1199), 'Earlier sentence. ' + 'x'.repeat(1199)])(
+ 'does not repeatedly announce one thought as its bounded preview window moves',
+ (initial) => {
+ jest.useFakeTimers();
+ const content = (think: string) => [
+ toPart({ name: 'lookup', output: 'rows' }),
+ { type: ContentTypes.THINK, think } as TMessageContentParts,
+ ];
+ const view = render(frame(content(initial)));
+ for (const suffix of [' ', ' more', ' more text', ' more text. Next sentence']) {
+ view.rerender(frame(content(initial + suffix)));
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+ }
+ expect(screen.getByTestId('activity-phase-announcer')).toBeEmptyDOMElement();
+ expect(screen.getByRole('button')).toHaveAccessibleName('Next sentence');
+ },
+ );
+
+ it('does not replay a source change when two consecutive calls begin with identical text', () => {
+ jest.useFakeTimers();
+ const first = toPart({ name: 'lookup', args: { intent: 'Checking' }, output: 'ok' }, 'first');
+ const second = (intent: string) => toPart({ name: 'lookup', args: { intent } }, 'second');
+ const view = render(frame([first]));
+ view.rerender(frame([first, second('Checking')]));
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+ view.rerender(frame([first, second('Checking the next file')]));
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+ const header = screen.getByRole('button');
+ expect(header).toHaveAccessibleName('Checking the next file');
+ expect(header.querySelector('.absolute[aria-hidden="true"]')).toBeNull();
+ });
+
+ it.each(['error', 'cancelled', 'completed'] as const)(
+ 'updates a cached detached outcome on a late %s attachment',
+ (status) => {
+ jest.useFakeTimers();
+ const part = toPart({ name: Tools.execute_code, output: HANDLE, runStepStatus: 'completed' });
+ const client = new QueryClient();
+ const tree = (attachments?: TAttachment[]) => (
+ <QueryClientProvider client={client}>
+ <RecoilRoot>
+ <ContentParts
+ content={[part]}
+ attachments={attachments}
+ messageId="m1"
+ conversationId="c1"
+ isCreatedByUser={false}
+ isLast
+ isLatestMessage
+ isSubmitting
+ showThinking={false}
+ />
+ </RecoilRoot>
+ </QueryClientProvider>
+ );
+ const view = render(tree());
+ expect(screen.getByRole('button')).toHaveAccessibleName('Running in background');
+ view.rerender(tree([statusAttachment(status)]));
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+ const expected = {
+ error: /Failed.*1 failed/,
+ cancelled: /Cancelled.*1 cancelled/,
+ completed: 'Finished in background',
+ }[status];
+ expect(screen.getByRole('button')).toHaveAccessibleName(expected);
+ },
+ );
+
+ it('does not lose a late failure at the start of a long unlabelled span', () => {
+ jest.useFakeTimers();
+ const calls = Array.from({ length: 1024 }, (_, index) =>
+ toPart(
+ {
+ name: 'lookup',
+ args: { intent: `Looking up item ${index}` },
+ output: 'ok',
+ },
+ `call-${index}`,
+ ),
+ );
+ const view = render(frame(calls));
+ expect(screen.queryByTestId('live-phase-outcome')).toBeNull();
+ view.rerender(
+ frame([
+ toPart({ name: 'lookup', output: 'ok', runStepStatus: 'failed' }, 'call-0'),
+ ...calls.slice(1),
+ ]),
+ );
+ expect(screen.getByRole('button')).toHaveAccessibleName(/Looking up item 1023.*1 failed/);
+ expect(screen.getByTestId('activity-phase-announcer')).toHaveTextContent('1 failed');
+ });
+
+ it('owns exactly one polite region across live-to-settled replacement', () => {
+ const calls = [toPart({ name: 'lookup', output: 'ok' })];
+ const view = render(frame(calls));
+ const announcer = screen.getByTestId('activity-phase-announcer');
+ view.rerender(
+ frame([
+ ...calls,
+ {
+ type: ContentTypes.ACTIVITY_LABEL,
+ activity_label: 'Completed lookup',
+ activity_label_type: 'phase',
+ activity_start_index: 0,
+ activity_end_index: 1,
+ activity_count: 1,
+ pending: false,
+ } as TMessageContentParts,
+ ]),
+ );
+ expect(screen.getAllByRole('status')).toEqual([announcer]);
+ expect(announcer).toHaveTextContent('Completed lookup');
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/__tests__/StackedToolIcons.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/StackedToolIcons.test.tsx
new file mode 100644
index 0000000000..b04b25b894
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/__tests__/StackedToolIcons.test.tsx
@@ -0,0 +1,62 @@
+import { Constants } from 'librechat-data-provider';
+import { render, screen } from '@testing-library/react';
+import StackedToolIcons from '../ToolOutput/StackedToolIcons';
+
+jest.mock('~/hooks/MCP', () => ({
+ useMCPServerNames: () => ['weather'],
+}));
+
+describe('shared header glyphs', () => {
+ it('keeps MCP identity alongside a subagent and owned search sites', () => {
+ const { container } = render(
+ <StackedToolIcons
+ toolNames={[
+ `forecast${Constants.mcp_delimiter}weather`,
+ `conditions${Constants.mcp_delimiter}weather`,
+ String(Constants.SUBAGENT),
+ 'web_search',
+ ]}
+ mcpIconMap={new Map([['weather', 'https://example.com/weather.svg']])}
+ sourceDomains={['source.example']}
+ maxIcons={4}
+ />,
+ );
+ const images = Array.from(container.querySelectorAll('img'));
+ expect(images).toHaveLength(2);
+ expect(images[0]).toHaveAttribute('src', 'https://example.com/weather.svg');
+ expect(images[1]).toHaveAttribute('alt', 'source.example');
+ expect(container.querySelector('.lucide-users')).not.toBeNull();
+ expect(container.querySelector('.lucide-globe')).toBeNull();
+ });
+
+ it.each(['failed', 'cancelled'] as const)(
+ 'lets %s replace identity without animating',
+ (status) => {
+ const { container } = render(
+ <StackedToolIcons
+ toolNames={['web_search']}
+ sourceDomains={['source.example']}
+ status={status}
+ isAnimating
+ />,
+ );
+ expect(container.querySelector('img')).toBeNull();
+ expect(container.querySelector('.animate-pulse')).toBeNull();
+ expect(
+ container.querySelector(status === 'failed' ? '.lucide-triangle-alert' : '.lucide-x'),
+ ).not.toBeNull();
+ },
+ );
+
+ it('retains a bounded stack and overflow count', () => {
+ const { container } = render(
+ <StackedToolIcons
+ toolNames={['web_search', 'read_file']}
+ sourceDomains={['one.example', 'two.example']}
+ maxIcons={2}
+ />,
+ );
+ expect(container.querySelectorAll('img')).toHaveLength(2);
+ expect(screen.getByText('+1')).toBeInTheDocument();
+ });
+});
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 e86e97ba82..c8dce56f0c 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
@@ -150,6 +150,7 @@ jest.mock('~/utils', () => ({
getBatchActivityLabelPart: jest.requireActual('~/utils/activityLabels').getBatchActivityLabelPart,
getActivityLabelText: jest.requireActual('~/utils/activityLabels').getActivityLabelText,
hasPendingApprovalInPart: jest.requireActual('~/utils/groupToolCalls').hasPendingApprovalInPart,
+ hasPendingAuthInPart: jest.requireActual('~/utils/groupToolCalls').hasPendingAuthInPart,
}));
jest.mock('../Parts', () => ({
diff --git a/client/src/components/Chat/Messages/Content/__tests__/sources.test.ts b/client/src/components/Chat/Messages/Content/__tests__/sources.test.ts
new file mode 100644
index 0000000000..75e7106fd9
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/__tests__/sources.test.ts
@@ -0,0 +1,67 @@
+import { Tools } from 'librechat-data-provider';
+import type { TAttachment } from 'librechat-data-provider';
+import { getSourceDomains } from '../sources';
+
+const search = (
+ toolCallId: string,
+ links: string[],
+ agentId = 'agent-a',
+ stepId = 'step-a',
+): TAttachment =>
+ ({
+ type: Tools.web_search,
+ toolCallId,
+ agentId,
+ stepId,
+ messageId: 'message',
+ [Tools.web_search]: {
+ turn: 0,
+ organic: links.map((link) => ({ link, title: link })),
+ },
+ }) as TAttachment;
+
+describe('source domains for a collapsed header', () => {
+ it.each([
+ ['another call', 'second', 'agent-a', 'step-a'],
+ ['another agent', 'first', 'agent-b', 'step-a'],
+ ['another step', 'first', 'agent-a', 'step-b'],
+ ])('retains a repeated turn owned by %s', (_, id, agent, step) => {
+ expect(
+ getSourceDomains(
+ [
+ search('first', ['https://one.example/a']),
+ search(id, ['https://two.example/b'], agent, step),
+ ],
+ 3,
+ ),
+ ).toEqual(['one.example', 'two.example']);
+ });
+
+ it('uses the latest snapshot for the same owner and turn', () => {
+ expect(
+ getSourceDomains(
+ [
+ search('first', ['https://stale.example/a']),
+ search('first', ['https://fresh.example/b']),
+ ],
+ 3,
+ ),
+ ).toEqual(['fresh.example']);
+ });
+
+ it('deduplicates domains across searches and respects the display cap', () => {
+ expect(
+ getSourceDomains(
+ [
+ search('first', ['https://www.one.example/a', 'https://one.example/b']),
+ search('second', ['https://two.example/a', 'https://three.example/a']),
+ ],
+ 2,
+ ),
+ ).toEqual(['one.example', 'two.example']);
+ });
+
+ it('returns a stable empty result when there are no owned sources', () => {
+ expect(getSourceDomains(undefined, 3)).toBe(getSourceDomains([], 3));
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/live.ts b/client/src/components/Chat/Messages/Content/live.ts
new file mode 100644
index 0000000000..886b6d70e6
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/live.ts
@@ -0,0 +1,307 @@
+import { Tools, Constants, ContentTypes } from 'librechat-data-provider';
+import type {
+ Agents,
+ TAttachment,
+ PartMetadata,
+ TMessageContentParts,
+} from 'librechat-data-provider';
+import type { TOptions } from 'i18next';
+import type { SpanOutcome, SpanSummary } from './outcome';
+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 { boundIntentLabel, getToolCallIntent } from './Parts/intent';
+import { areToolCallArgsComplete } from './Parts/parseJsonField';
+import { getToolDisplayLabel } from '~/utils/toolLabels';
+import { isBashProgrammaticToolCall } from './routing';
+import { getToolMeta, summarizeSpan } from './outcome';
+
+/** 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
+ * transcript, so it takes the latest value at most twice a second. */
+export const LIVE_ACTIVITY_THROTTLE_MS = 500;
+
+export type LiveActivity = {
+ /** The newest line of the span, or empty before anything nameable exists. */
+ text: string;
+ /** Identity of whatever produced `text`. A sentence still streaming keeps
+ * its source, so the header can extend it in place and reserve the ticker
+ * transition for a genuinely different line. */
+ source: string;
+ iconNames: string[];
+ /** Failed and stopped calls anywhere in the span, not just the newest line. */
+ outcome: SpanOutcome;
+};
+
+type Localize = (phraseKey: TranslationKeys, options?: TOptions) => string;
+
+type LiveToolCall = Agents.ToolCall & { subagent_content?: TMessageContentParts[] } & Pick<
+ PartMetadata,
+ 'runStepStatus'
+ > & { progress?: number };
+
+/**
+ * The agents-shaped call — the only variant a live header can name. The
+ * legacy Assistants variants (code interpreter, retrieval, function) carry no
+ * top-level `args`; a span made only of those is left unfolded.
+ */
+export const getStandardToolCall = (part: TMessageContentParts): LiveToolCall | undefined => {
+ if (part.type !== ContentTypes.TOOL_CALL) {
+ return undefined;
+ }
+ const toolCall = part[ContentTypes.TOOL_CALL];
+ return toolCall != null && 'args' in toolCall ? (toolCall as LiveToolCall) : undefined;
+};
+
+/**
+ * True when the run is waiting on the reader: an unresolved approval, a
+ * sign-in, or an open question. A live fold must never hold one of these — the
+ * span renders unfolded until it clears.
+ */
+export function needsReader(part: TMessageContentParts | undefined): boolean {
+ if (part == null) {
+ return false;
+ }
+ if (hasPendingApprovalInPart(part) || hasPendingAuthInPart(part)) {
+ return true;
+ }
+ const toolCall = getStandardToolCall(part);
+ if (toolCall == null) {
+ return false;
+ }
+ if (toolCall.name === ASK_USER_QUESTION) {
+ return (toolCall.output?.length ?? 0) === 0 && getSubmittedAskAnswer(toolCall.id) === undefined;
+ }
+ /** A subagent's own calls can wait on the reader too, and the collapsed row
+ * unmounts the card that leads to them. */
+ return Array.isArray(toolCall.subagent_content) && toolCall.subagent_content.some(needsReader);
+}
+
+function toolCallLine(
+ part: TMessageContentParts,
+ toolCall: LiveToolCall,
+ localize: Localize,
+ serverNames: readonly string[],
+ span: SpanSummary,
+): string {
+ const intent = getToolCallIntent(toolCall.args);
+ const label = getToolDisplayLabel(toolCall.name ?? '', localize, serverNames);
+ /** The verdict comes from the resolver the group header uses, so a collapsed
+ * row can never read as a success while the card it hides shows a failure
+ * or a stop — whichever channel reported it. */
+ const meta = span.metaOf(part);
+ if (meta?.cancelled === true) {
+ return localize('com_ui_cancelled');
+ }
+ if (meta?.failed === true) {
+ /** Reads as the hidden card does: `ToolCall` uses the same template. */
+ const subject = intent ?? label;
+ return subject ? localize('com_ui_failed_subject', { 0: subject }) : localize('com_ui_failed');
+ }
+ /** Ahead of the intent, as on `BashCall`/`ExecuteCode`: a returned handle
+ * is not a result, and "Ran …" would turn ongoing work into a success. */
+ if (meta?.background != null) {
+ return localize(
+ meta.background === 'running' ? 'com_ui_background_running' : 'com_ui_background_finished',
+ );
+ }
+ if (intent != null) {
+ return intent;
+ }
+ if (!label) {
+ return localize('com_assistants_running_action');
+ }
+ return localize(
+ meta?.hasOutput === true ? 'com_assistants_completed_function' : 'com_assistants_running_var',
+ { 0: label },
+ );
+}
+
+/** Bounds the sentence scan on long reasoning, like the streaming peek. */
+const REASONING_TAIL_CHARS = 1200;
+
+/**
+ * A bounded preview of the sentence the thought is currently writing.
+ * Preview offsets are not activity identities: a sliding window, whitespace
+ * or a resumed snapshot can move them without starting a new thought.
+ */
+function lastReasoningSentence(reasoning: string): string | undefined {
+ const tail = reasoning
+ .slice(-REASONING_TAIL_CHARS)
+ .replace(/^\s*<think>\s*/, '')
+ .replace(/\s*<\/think>\s*$/, '')
+ .trimEnd();
+ if (!tail) {
+ return undefined;
+ }
+ let start = 0;
+ /** CJK sentences end in full-width marks with no space after them. */
+ const boundary = /[.!?]\s+|[。!?]\s*/g;
+ for (let match = boundary.exec(tail); match != null; match = boundary.exec(tail)) {
+ const end = match.index + match[0].length;
+ /** A mark that closes the tail ends the CURRENT sentence; it does not
+ * start an empty one. The finished sentence stays until the next begins. */
+ if (end < tail.length) {
+ start = end;
+ }
+ }
+ return boundIntentLabel(tail.slice(start));
+}
+
+/**
+ * A foreground subagent still running. Its card is a live surface of its own:
+ * the ticker and the terminal error/stop state come from the subagent progress
+ * atom, not from the outer tool-call part, so a folded header could not follow
+ * it. The span stays unfolded until the subagent settles.
+ */
+function isLiveSubagent(part: TMessageContentParts): boolean {
+ const toolCall = getStandardToolCall(part);
+ return (
+ toolCall?.name === Constants.SUBAGENT &&
+ (toolCall.output?.length ?? 0) === 0 &&
+ toolCall.progress !== 1 &&
+ toolCall.runStepStatus == null
+ );
+}
+
+/** True when a live fold cannot stand for this part right now. */
+export function blocksLiveFold(part: TMessageContentParts | undefined): boolean {
+ if (part == null) {
+ return false;
+ }
+ if (needsReader(part) || isLiveSubagent(part)) {
+ return true;
+ }
+ const toolCall = getStandardToolCall(part);
+ /** Dispatch cannot start until arguments are complete. With no intent at
+ * that point, code cards own startup labels driven by sandbox events
+ * outside the content array. Keep those subscribers mounted until the
+ * part itself can represent their result. */
+ return (
+ toolCall != null &&
+ (toolCall.name === Tools.bash_tool ||
+ toolCall.name === Tools.execute_code ||
+ toolCall.name === Constants.PROGRAMMATIC_TOOL_CALLING ||
+ toolCall.name === Constants.BASH_PROGRAMMATIC_TOOL_CALLING) &&
+ toolCall.runStepStatus == null &&
+ toolCall.progress !== 1 &&
+ (toolCall.output?.length ?? 0) === 0 &&
+ getToolCallIntent(toolCall.args) == null &&
+ areToolCallArgsComplete(toolCall.args)
+ );
+}
+
+/** Icons the header stack can show. */
+const MAX_LIVE_ICONS = 4;
+
+/** How far back from the tail the icon scan looks. This runs on every streamed
+ * delta, so its cost must not grow with the run; the stack then shows the
+ * tools of the recent stretch, which is also what the line beside it names. */
+const LIVE_ICON_WINDOW = 24;
+
+/**
+ * Tool names for a span's icon stack, oldest first, read from a fixed window
+ * behind the tail so the cost does not grow with the run.
+ */
+export function getSpanIconNames(parts: ReadonlyArray<TMessageContentParts | undefined>): string[] {
+ const icons = new Set<string>();
+ const floor = Math.max(0, parts.length - LIVE_ICON_WINDOW);
+ for (let position = parts.length - 1; position >= floor; position -= 1) {
+ if (icons.size === MAX_LIVE_ICONS) {
+ break;
+ }
+ const part = parts[position];
+ const toolCall = part == null ? undefined : getStandardToolCall(part);
+ if (toolCall != null) {
+ const name = toolCall.name ?? '';
+ icons.add(isBashProgrammaticToolCall(name, toolCall.args) ? Tools.bash_tool : name);
+ continue;
+ }
+ const legacy = part == null ? null : getToolMeta(part);
+ if (legacy != null) {
+ icons.add(legacy.iconName);
+ }
+ }
+ return Array.from(icons).reverse();
+}
+
+function newestLine(
+ parts: ReadonlyArray<TMessageContentParts | undefined>,
+ localize: Localize,
+ serverNames: readonly string[],
+ span: SpanSummary,
+): Pick<LiveActivity, 'text' | 'source'> {
+ for (let position = parts.length - 1; position >= 0; position -= 1) {
+ const part = parts[position];
+ if (part == null) {
+ continue;
+ }
+ if (part.type === ContentTypes.THINK) {
+ /** Reached before any call or label, this thought IS the tail — the
+ * model is reasoning about its next step. Its multi-line peek stays
+ * inside the fold, so the header previews it one sentence at a time. */
+ const reasoning = typeof part.think === 'string' ? part.think : (part.think?.value ?? '');
+ const sentence = lastReasoningSentence(reasoning);
+ if (sentence != null) {
+ return { text: sentence, source: `think:${position}` };
+ }
+ const label = part.reasoning_label?.trim();
+ if (label || reasoning.trim()) {
+ return { text: label || localize('com_ui_thinking'), source: `think:${position}` };
+ }
+ continue;
+ }
+ if (part.type === ContentTypes.TEXT) {
+ /** Only short commentary can sit inside a fold. It is the model talking
+ * about what it is doing, which is exactly what this line is for —
+ * leaving it unnamed would hold a stale call on screen while new prose
+ * piles up behind the disclosure. */
+ const value = typeof part.text === 'string' ? part.text : (part.text?.value ?? '');
+ const commentary = boundIntentLabel(value);
+ if (commentary != null) {
+ return { text: commentary, source: `text:${position}` };
+ }
+ continue;
+ }
+ const labelText = getActivityLabelText(getBatchActivityLabelPart(part));
+ if (labelText) {
+ return { text: labelText, source: `label:${position}` };
+ }
+ const toolCall = getStandardToolCall(part);
+ if (toolCall != null) {
+ return {
+ text: toolCallLine(part, toolCall, localize, serverNames, span),
+ /** Provider ids repeat across batches, so the position is part of the
+ * identity: a second call reusing an id is a new line, not the first
+ * one still growing. */
+ source: `tool:${toolCall.id ?? ''}:${position}`,
+ };
+ }
+ }
+ return { text: '', source: '' };
+}
+
+/**
+ * The newest nameable activity in a span: the last tool call's own line (its
+ * streamed intent, else the generic text its card would show), a filled batch
+ * label once one lands after it, or the thought streaming after both. Later parts win, so the
+ * header always reads as the bottom line of the list it stands for.
+ *
+ * Runs on every streamed delta. Outcome aggregation visits the full span so
+ * late failures cannot disappear; the line stops at the newest nameable part
+ * and icons only inspect a fixed tail window.
+ */
+export function getLiveActivity(
+ parts: ReadonlyArray<TMessageContentParts | undefined>,
+ localize: Localize,
+ serverNames: readonly string[],
+ attachmentsById?: Record<string, TAttachment[] | undefined>,
+): LiveActivity {
+ const span = summarizeSpan(parts, attachmentsById);
+ return {
+ ...newestLine(parts, localize, serverNames, span),
+ outcome: { failed: span.failed, cancelled: span.cancelled },
+ iconNames: getSpanIconNames(parts),
+ };
+}
diff --git a/client/src/components/Chat/Messages/Content/outcome.ts b/client/src/components/Chat/Messages/Content/outcome.ts
new file mode 100644
index 0000000000..67a8800d56
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/outcome.ts
@@ -0,0 +1,287 @@
+import { Tools, ContentTypes, ToolCallTypes } from 'librechat-data-provider';
+import type {
+ Agents,
+ TAttachment,
+ PartMetadata,
+ FunctionToolCall,
+ TMessageContentParts,
+} from 'librechat-data-provider';
+import { parseBackgroundHandle, splitBackgroundAttachments } from './Parts/handle';
+import { resolveToolCallPhase } from '~/utils/toolCallPhase';
+import { isMemoryFailureOutput } from './Parts/MemoryCall';
+import { filterAttachmentsForPart } from '~/utils/map';
+import { isBashProgrammaticToolCall } from './routing';
+import { isError } from './ToolOutput';
+
+/**
+ * The one place a tool call's outcome is decided for anything that SUMMARIZES
+ * calls — a group header, a live fold's line. Each signal below was added
+ * because a summary disagreed with the card it stood for: the run step's
+ * terminal verdict, memory tools' prose failures, a backgrounded task's status
+ * attachment and its cancelled flag. A summary that derives its own verdict
+ * re-learns those one review at a time, so it reads this instead.
+ */
+export interface ToolMeta {
+ name: string;
+ iconName: string;
+ hasOutput: boolean;
+ failed: boolean;
+ cancelled: boolean;
+ /** Set for a detached task: its dispatch step is long closed, so whether the
+ * WORK is still going is a separate fact — the cards say "Running in
+ * background" until a status marker or harvested files arrive. */
+ background?: 'running' | 'finished';
+}
+
+function hasFailedOutput(output: unknown): boolean {
+ return typeof output === 'string' && isError(output);
+}
+
+/**
+ * Group metadata must agree with the individual card, which resolves its
+ * outcome from the run step's terminal verdict through `resolveToolCallPhase`.
+ * Reading output alone leaves a step the run closed as `failed` with empty or
+ * benign output counted as neither failed nor finished, so the group sits on
+ * "Running" until the response ends and then reports that it ran successfully
+ * with no failures while the card beside it shows the failure. A closed step
+ * is never running. Parts carrying no terminal status keep the legacy
+ * output/progress signal, which is all the older endpoints emit.
+ */
+function resolveOutcome(
+ runStepStatus: PartMetadata['runStepStatus'],
+ completed: boolean,
+ hasError: boolean,
+): Pick<ToolMeta, 'hasOutput' | 'failed' | 'cancelled'> {
+ if (runStepStatus == null) {
+ return { hasOutput: completed, failed: hasError, cancelled: false };
+ }
+ const phase = resolveToolCallPhase({
+ runStepStatus,
+ displayProgress: 1,
+ reportedProgress: 1,
+ isSubmitting: false,
+ hasError,
+ });
+ return {
+ hasOutput: phase !== 'running',
+ failed: phase === 'failed',
+ /** Tracked separately from `failed`: a stopped step is settled and not an
+ * error, but the group still must not auto-collapse under a
+ * success-sounding header with the only cancellation notice hidden in the
+ * panel. */
+ cancelled: phase === 'cancelled',
+ };
+}
+
+export function getToolMeta(
+ part: TMessageContentParts,
+ attachmentsByToolCallId?: Record<string, TAttachment[] | undefined>,
+ /** Step ids other parts with this provider id already own. A call that has
+ * no step yet must not inherit what an earlier occurrence produced. */
+ siblingStepIds?: ReadonlySet<string>,
+): ToolMeta | null {
+ if (part.type !== ContentTypes.TOOL_CALL) {
+ return null;
+ }
+ const toolCall = part[ContentTypes.TOOL_CALL];
+ if (!toolCall) {
+ return null;
+ }
+ /** Terminal verdict lives on the outer `tool_call` object (`PartMetadata`),
+ * not on the per-variant payload, so it is read before any narrowing cast. */
+ const runStepStatus = toolCall.runStepStatus;
+
+ const isStandard =
+ 'args' in toolCall && (!toolCall.type || toolCall.type === ToolCallTypes.TOOL_CALL);
+ if (isStandard) {
+ /** `agentId` disambiguates attachments when a handoff response repeats a
+ * provider tool-call id across agents; `filterAttachmentsForPart` reads it
+ * the same way. */
+ const tc = toolCall as Agents.ToolCall & { progress?: number; agentId?: string };
+ /** Subagents can finish with `progress === 1` and no final output
+ * text (the parent saw "" / undefined back). Fall back to progress
+ * so the group header flips from "Running N agents" to "Ran N
+ * agents" on completion even when the child returned no text. */
+ const completed = !!tc.output || tc.progress === 1;
+ const name = tc.name ?? '';
+ const iconName = isBashProgrammaticToolCall(name, tc.args) ? Tools.bash_tool : name;
+ /** Memory tools report failure in prose ("Invalid key ...") that generic
+ * `isError` parsing does not recognize, so `MemoryCall` classifies it with
+ * its own predicate. Reuse that here or a persisted call with no terminal
+ * status shows a failed card inside a group claiming success. */
+ const ownAttachments = filterAttachmentsForPart(
+ attachmentsByToolCallId?.[tc.id ?? ''],
+ tc.agentId,
+ toolCall.stepId,
+ toolCall.stepId == null ? siblingStepIds : undefined,
+ );
+ /** `MemoryCall` also fails on a memory-error ARTIFACT, which arrives as an
+ * attachment beside output that can read as a success. */
+ const failedOutput =
+ name === 'set_memory' || name === 'delete_memory'
+ ? isMemoryFailureOutput(name, tc.output ?? '') ||
+ (ownAttachments ?? []).some((attachment) => attachment[Tools.memory]?.type === 'error')
+ : hasFailedOutput(tc.output);
+ /** A backgrounded bash/code task reports its verdict through a
+ * `background_task_status` attachment, not its output: the dispatch step
+ * keeps a benign handle and usually closes as `completed`. The child card
+ * folds that marker in as `extraError`, so without it here the group
+ * reported no failed action beside a card showing failure. Correlated the
+ * same way the child is, since provider tool-call ids repeat across agents
+ * and execution steps in handoff responses. */
+ const backgroundHandle = parseBackgroundHandle(tc.output);
+ const { backgroundStatus, fileAttachments } = splitBackgroundAttachments(ownAttachments, tc.id);
+ const backgroundSettled = backgroundStatus != null || (fileAttachments?.length ?? 0) > 0;
+ const backgroundFailed = backgroundHandle != null && backgroundStatus === 'error';
+ const backgroundCancelled =
+ tc.backgroundTask?.cancelled === true ||
+ (backgroundHandle != null && backgroundStatus === 'cancelled');
+ return {
+ name,
+ iconName,
+ ...(backgroundHandle != null && {
+ background: backgroundSettled ? ('finished' as const) : ('running' as const),
+ }),
+ ...resolveOutcome(
+ backgroundCancelled ? 'cancelled' : runStepStatus,
+ completed,
+ failedOutput || backgroundFailed,
+ ),
+ };
+ }
+
+ if (toolCall.type === ToolCallTypes.CODE_INTERPRETER) {
+ const ci = (toolCall as { code_interpreter?: { outputs?: unknown[] } }).code_interpreter;
+ return {
+ name: 'code_interpreter',
+ iconName: 'code_interpreter',
+ ...resolveOutcome(runStepStatus, (ci?.outputs?.length ?? 0) > 0, false),
+ };
+ }
+
+ if (toolCall.type === ToolCallTypes.RETRIEVAL || toolCall.type === ToolCallTypes.FILE_SEARCH) {
+ const output = (toolCall as { output?: string }).output;
+ return {
+ name: 'file_search',
+ iconName: 'file_search',
+ ...resolveOutcome(runStepStatus, !!output, hasFailedOutput(output)),
+ };
+ }
+
+ if (toolCall.type === ToolCallTypes.FUNCTION && ToolCallTypes.FUNCTION in toolCall) {
+ const fn = (toolCall as FunctionToolCall).function;
+ return {
+ name: fn.name,
+ iconName: fn.name,
+ ...resolveOutcome(runStepStatus, !!fn.output, hasFailedOutput(fn.output)),
+ };
+ }
+
+ return null;
+}
+
+export type SpanOutcome = { failed: number; cancelled: number };
+
+/** The most severe terminal outcome replaces identity glyphs on every summary. */
+export function getOutcomeStatus({
+ failed,
+ cancelled,
+}: SpanOutcome): 'failed' | 'cancelled' | undefined {
+ if (failed > 0) {
+ return 'failed';
+ }
+ if (cancelled > 0) {
+ return 'cancelled';
+ }
+ return undefined;
+}
+
+export type SpanSummary = SpanOutcome & {
+ /** The verdict for one part of the span, scoped the way the count was. */
+ metaOf: (part: TMessageContentParts) => ToolMeta | null;
+};
+
+type CachedMeta = {
+ attachments: TAttachment[] | undefined;
+ siblings: string;
+ meta: ToolMeta | null;
+};
+
+/** Content parts are immutable and a streamed delta replaces only the part it
+ * touched, so a verdict is good for as long as the part object, its
+ * attachment list and its sibling steps are the same ones. */
+const metaCache = new WeakMap<TMessageContentParts, CachedMeta>();
+
+const toolCallIdentity = (part: TMessageContentParts): { id: string; stepId?: string } => {
+ const toolCall = part[ContentTypes.TOOL_CALL] as { id?: string; stepId?: string } | undefined;
+ return { id: toolCall?.id ?? '', stepId: toolCall?.stepId };
+};
+
+/**
+ * Outcome of a span for a summary that shows only its newest line: how many
+ * calls failed or were stopped — an earlier call can fail while a later one is
+ * still running, and the line alone would never say so — plus the verdict for
+ * any single part.
+ *
+ * Attachment ownership follows `ContentParts`: provider ids repeat across
+ * steps, so a call with no step yet excludes what an earlier occurrence of its
+ * id already owns. Runs per streamed delta; unchanged parts answer from the
+ * cache.
+ */
+export function summarizeSpan(
+ parts: ReadonlyArray<TMessageContentParts | undefined>,
+ attachmentsByToolCallId?: Record<string, TAttachment[] | undefined>,
+): SpanSummary {
+ /** Step ownership only matters when there are attachments to route, which
+ * most runs never have — so the extra walk is paid on first need, once. */
+ let stepsById: Map<string, Set<string>> | undefined;
+ const ownedSteps = (id: string): Set<string> | undefined => {
+ if (attachmentsByToolCallId?.[id] == null) {
+ return undefined;
+ }
+ if (stepsById == null) {
+ stepsById = new Map();
+ for (const part of parts) {
+ if (part?.type !== ContentTypes.TOOL_CALL) {
+ continue;
+ }
+ const owner = toolCallIdentity(part);
+ if (owner.id === '' || owner.stepId == null) {
+ continue;
+ }
+ const steps = stepsById.get(owner.id) ?? new Set<string>();
+ steps.add(owner.stepId);
+ stepsById.set(owner.id, steps);
+ }
+ }
+ return stepsById.get(id);
+ };
+ const metaOf = (part: TMessageContentParts): ToolMeta | null => {
+ if (part.type !== ContentTypes.TOOL_CALL) {
+ return null;
+ }
+ const { id } = toolCallIdentity(part);
+ const attachments = attachmentsByToolCallId?.[id];
+ const siblingSteps = ownedSteps(id);
+ const siblings = siblingSteps == null ? '' : Array.from(siblingSteps).join('|');
+ const cached = metaCache.get(part);
+ if (cached != null && cached.attachments === attachments && cached.siblings === siblings) {
+ return cached.meta;
+ }
+ const meta = getToolMeta(part, attachmentsByToolCallId, siblingSteps);
+ metaCache.set(part, { attachments, siblings, meta });
+ return meta;
+ };
+ let failed = 0;
+ let cancelled = 0;
+ for (const part of parts) {
+ const meta = part == null ? null : metaOf(part);
+ if (meta?.failed === true) {
+ failed += 1;
+ }
+ if (meta?.cancelled === true) {
+ cancelled += 1;
+ }
+ }
+ return { failed, cancelled, metaOf };
+}
diff --git a/client/src/components/Chat/Messages/Content/sources.ts b/client/src/components/Chat/Messages/Content/sources.ts
new file mode 100644
index 0000000000..a4f9627b5f
--- /dev/null
+++ b/client/src/components/Chat/Messages/Content/sources.ts
@@ -0,0 +1,72 @@
+import { Tools } from 'librechat-data-provider';
+import type { TAttachment, ValidSource, SearchResultData } from 'librechat-data-provider';
+import { getCleanDomain } from '~/components/Web/SourceHovercard';
+
+/** Every distinct source across the given search turns, last write wins per link. */
+export function collectSources(results: Record<string, SearchResultData>): ValidSource[] {
+ const sourceMap = new Map<string, ValidSource>();
+ for (const result of Object.values(results)) {
+ if (!result) {
+ continue;
+ }
+ result.organic?.forEach((s) => {
+ if (s.link) {
+ sourceMap.set(s.link, s);
+ }
+ });
+ result.topStories?.forEach((s) => {
+ if (s.link) {
+ sourceMap.set(s.link, s);
+ }
+ });
+ }
+ return Array.from(sourceMap.values());
+}
+
+/** The first `max` sources with distinct domains, in result order. */
+export function getUniqueDomainSources(sources: ValidSource[], max: number): ValidSource[] {
+ const seen = new Set<string>();
+ const result: ValidSource[] = [];
+ for (const source of sources) {
+ const domain = getCleanDomain(source.link);
+ if (seen.has(domain)) {
+ continue;
+ }
+ seen.add(domain);
+ result.push(source);
+ if (result.length >= max) {
+ break;
+ }
+ }
+ return result;
+}
+
+const NO_DOMAINS: string[] = [];
+
+/**
+ * The domains a collapsed header can show in place of the generic search
+ * glyph. A header stands for rows it hides, so it should carry the most
+ * specific glyph those rows show — for a web search, the sites it read.
+ * Only ownership-filtered attachments qualify, including live SSE snapshots.
+ * Message-wide search context is derived from those same attachments but loses
+ * call/agent/step ownership. Repeated turn numbers are local to each owner.
+ * Returns a shared empty array when there are none, so a memoized consumer
+ * does not see a new value on every attachment churn.
+ */
+export function getSourceDomains(attachments: TAttachment[] | undefined, max: number): string[] {
+ const turns: Record<string, SearchResultData> = {};
+ for (const attachment of attachments ?? []) {
+ const data = attachment.type === Tools.web_search ? attachment[Tools.web_search] : undefined;
+ if (data != null) {
+ const owner = JSON.stringify([
+ attachment.toolCallId,
+ attachment.agentId,
+ attachment.stepId,
+ data.turn ?? 0,
+ ]);
+ turns[owner] = data;
+ }
+ }
+ const sources = getUniqueDomainSources(collectSources(turns), max);
+ return sources.length === 0 ? NO_DOMAINS : sources.map((source) => getCleanDomain(source.link));
+}
diff --git a/client/src/components/Chat/Messages/MessageParts.tsx b/client/src/components/Chat/Messages/MessageParts.tsx
index 64c1b9d1f4..efd1f8bc35 100644
--- a/client/src/components/Chat/Messages/MessageParts.tsx
+++ b/client/src/components/Chat/Messages/MessageParts.tsx
@@ -57,6 +57,7 @@ function MessageParts(props: TMessageProps) {
} = useMessageHelpers(props, searchResults);
const maximizeChatSpace = useRecoilValue(store.maximizeChatSpace);
+ const autoExpandTools = useRecoilValue(store.autoExpandTools);
const showThinking = useAtomValue(showThinkingAtom);
const { messageId = null, isCreatedByUser } = message ?? {};
@@ -189,6 +190,7 @@ function MessageParts(props: TMessageProps) {
setSiblingIdx={setSiblingIdx}
isCreatedByUser={message.isCreatedByUser}
conversationId={conversation?.conversationId}
+ foldLiveActivity={!autoExpandTools}
showThinking={showThinking}
isLatestMessage={messageId === latestMessageId}
content={message.content as Array<TMessageContentParts | undefined>}
diff --git a/client/src/components/Chat/Subagents/SubagentActivity.tsx b/client/src/components/Chat/Subagents/SubagentActivity.tsx
index ad6d90f255..e3ec2fca4e 100644
--- a/client/src/components/Chat/Subagents/SubagentActivity.tsx
+++ b/client/src/components/Chat/Subagents/SubagentActivity.tsx
@@ -359,6 +359,7 @@ export function SubagentActivityContent({
isSubmitting={isSubmitting}
showThinking={showThinking}
isLatestMessage={isSubmitting}
+ foldLiveActivity={false}
/>
);
}
diff --git a/client/src/components/Messages/ContentRender.tsx b/client/src/components/Messages/ContentRender.tsx
index e2dba90a29..8207d59440 100644
--- a/client/src/components/Messages/ContentRender.tsx
+++ b/client/src/components/Messages/ContentRender.tsx
@@ -117,6 +117,7 @@ const ContentRender = memo(function ContentRender({
chatContext,
});
const maximizeChatSpace = useRecoilValue(store.maximizeChatSpace);
+ const autoExpandTools = useRecoilValue(store.autoExpandTools);
const showThinking = useAtomValue(showThinkingAtom);
const handleRegenerateMessage = useCallback(() => regenerateMessage(), [regenerateMessage]);
@@ -235,6 +236,7 @@ const ContentRender = memo(function ContentRender({
isSubmitting={isSubmitting}
isCreatedByUser={msg.isCreatedByUser}
createdAt={msg.createdAt ?? msg.clientTimestamp}
+ foldLiveActivity={!autoExpandTools}
showThinking={showThinking}
conversationId={conversation?.conversationId}
content={msg.content as Array<TMessageContentParts | undefined>}
diff --git a/client/src/hooks/Messages/__tests__/useThrottledValue.spec.tsx b/client/src/hooks/Messages/__tests__/useThrottledValue.spec.tsx
new file mode 100644
index 0000000000..1ffd885d16
--- /dev/null
+++ b/client/src/hooks/Messages/__tests__/useThrottledValue.spec.tsx
@@ -0,0 +1,51 @@
+import React from 'react';
+import { act, renderHook } from '@testing-library/react';
+import useThrottledValue from '../useThrottledValue';
+
+describe('useThrottledValue', () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ jest.setSystemTime(0);
+ });
+ afterEach(() => jest.useRealTimers());
+
+ it('keeps trailing updates alive after Strict Mode effect cleanup', () => {
+ const { result, rerender } = renderHook(({ value }) => useThrottledValue(value, 500), {
+ initialProps: { value: 'first' },
+ wrapper: ({ children }) => <React.StrictMode>{children}</React.StrictMode>,
+ });
+ act(() => {
+ jest.advanceTimersByTime(100);
+ });
+ rerender({ value: 'latest' });
+ act(() => {
+ jest.advanceTimersByTime(400);
+ });
+ expect(result.current).toBe('latest');
+ });
+
+ it('paints the leading change and the latest trailing value, then releases its timer', () => {
+ jest.setSystemTime(1000);
+ const { result, rerender, unmount } = renderHook(({ value }) => useThrottledValue(value, 500), {
+ initialProps: { value: 'first' },
+ });
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+ rerender({ value: 'leading' });
+ expect(result.current).toBe('leading');
+ rerender({ value: 'middle' });
+ act(() => {
+ jest.advanceTimersByTime(100);
+ });
+ rerender({ value: 'trailing' });
+ expect(result.current).toBe('leading');
+ act(() => {
+ jest.advanceTimersByTime(400);
+ });
+ expect(result.current).toBe('trailing');
+ rerender({ value: 'pending' });
+ unmount();
+ expect(jest.getTimerCount()).toBe(0);
+ });
+});
diff --git a/client/src/hooks/Messages/index.ts b/client/src/hooks/Messages/index.ts
index 7ec352d294..6015ed83f2 100644
--- a/client/src/hooks/Messages/index.ts
+++ b/client/src/hooks/Messages/index.ts
@@ -12,6 +12,7 @@ export { default as useSubmitMessage } from './useSubmitMessage';
export type { ContentMetadataResult } from './useContentMetadata';
export { default as useExpandCollapse } from './useExpandCollapse';
export { default as useLazyCollapseBody } from './useLazyCollapseBody';
+export { default as useThrottledValue } from './useThrottledValue';
export {
RowMountProvider,
useRowMountWindow,
diff --git a/client/src/hooks/Messages/useThrottledValue.ts b/client/src/hooks/Messages/useThrottledValue.ts
new file mode 100644
index 0000000000..330aa87ef1
--- /dev/null
+++ b/client/src/hooks/Messages/useThrottledValue.ts
@@ -0,0 +1,44 @@
+import { useEffect, useRef, useState } from 'react';
+
+/**
+ * Leading + trailing throttle for a rendered value: the first change paints at
+ * once, later ones at most once per `intervalMs`, and the last value always
+ * lands. A debounce would hold the display still for as long as changes keep
+ * arriving, which is exactly when a streamed status line is worth reading.
+ */
+export default function useThrottledValue<T>(value: T, intervalMs: number): T {
+ const [throttled, setThrottled] = useState(value);
+ const latestRef = useRef(value);
+ const paintedAtRef = useRef(0);
+ const timerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ latestRef.current = value;
+
+ useEffect(() => {
+ const elapsed = Date.now() - paintedAtRef.current;
+ if (elapsed >= intervalMs) {
+ paintedAtRef.current = Date.now();
+ setThrottled(value);
+ return;
+ }
+ if (timerRef.current != null) {
+ return;
+ }
+ timerRef.current = setTimeout(() => {
+ timerRef.current = null;
+ paintedAtRef.current = Date.now();
+ setThrottled(latestRef.current);
+ }, intervalMs - elapsed);
+ }, [value, intervalMs]);
+
+ useEffect(
+ () => () => {
+ if (timerRef.current != null) {
+ clearTimeout(timerRef.current);
+ timerRef.current = null;
+ }
+ },
+ [],
+ );
+
+ return throttled;
+}
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index a97a9bdcd7..61a40b034d 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -1462,6 +1462,7 @@
"com_ui_export_tool": "Tool",
"com_ui_export_video": "Video",
"com_ui_failed": "Failed",
+ "com_ui_failed_subject": "Failed: {{0}}",
"com_ui_favorite": "Add to favorites",
"com_ui_feedback_more": "More...",
"com_ui_feedback_more_information": "Provide additional feedback",
diff --git a/client/src/utils/__tests__/activityLabels.spec.ts b/client/src/utils/__tests__/activityLabels.spec.ts
index 97b14b1f90..207ba61571 100644
--- a/client/src/utils/__tests__/activityLabels.spec.ts
+++ b/client/src/utils/__tests__/activityLabels.spec.ts
@@ -860,3 +860,68 @@ describe('findActivityLabelMessageIndex', () => {
expect(findActivityLabelMessageIndex([user, older], event, ['user-1'])).toBe(-1);
});
});
+
+describe('groupActivityPhases — live tail', () => {
+ const tool = (id: string, name = 'lookup'): TMessageContentParts =>
+ ({
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id, name, args: '{}', output: '' },
+ }) as unknown as TMessageContentParts;
+ const text = (value: string): TMessageContentParts =>
+ ({ type: ContentTypes.TEXT, text: value }) as unknown as TMessageContentParts;
+ const think = { type: ContentTypes.THINK, think: 'hm' } as unknown as TMessageContentParts;
+
+ it('folds the span being written from its first tool call, tail included', () => {
+ const segments = groupActivityPhases([think, tool('t1')], undefined, true);
+ expect(segments).toHaveLength(1);
+ expect(segments?.[0]).toMatchObject({
+ type: 'phase',
+ live: true,
+ synthesized: true,
+ contentIndices: [0, 1],
+ });
+ });
+
+ it('leaves the same content untouched when the message is not live', () => {
+ expect(groupActivityPhases([think, tool('t1')])).toBeUndefined();
+ });
+
+ it('does not fold reasoning that has not reached a tool call yet', () => {
+ expect(groupActivityPhases([think], undefined, true)).toBeUndefined();
+ });
+
+ it('does not fold a span the stream has already moved past', () => {
+ expect(groupActivityPhases([tool('t1'), text('The answer.')], undefined, true)).toBeUndefined();
+ });
+
+ it('folds only the tail span when an answer separates two runs', () => {
+ const segments = groupActivityPhases(
+ [tool('t1'), text('A first answer.'), tool('t2')],
+ undefined,
+ true,
+ );
+ expect(segments?.map((segment) => segment.type)).toEqual(['content', 'phase']);
+ expect(segments?.[1]).toMatchObject({ live: true, contentIndices: [2] });
+ });
+
+ it('never folds a handoff on its own', () => {
+ const transfer = tool('t1', `${Constants.LC_TRANSFER_TO_}agent_b`);
+ expect(groupActivityPhases([transfer], undefined, true)).toBeUndefined();
+ });
+});
+
+describe('groupActivityPhases — live tail and handoffs', () => {
+ const tool = (id: string, name = 'lookup'): TMessageContentParts =>
+ ({
+ type: ContentTypes.TOOL_CALL,
+ [ContentTypes.TOOL_CALL]: { id, name, args: '{}', output: '' },
+ }) as unknown as TMessageContentParts;
+
+ it('ends the span at a handoff and starts a new live span for the next agent', () => {
+ const transfer = tool('h1', `${Constants.LC_TRANSFER_TO_}agent_b`);
+ const segments = groupActivityPhases([tool('t1'), transfer, tool('t2')], undefined, true);
+ expect(segments?.map((segment) => segment.type)).toEqual(['content', 'phase']);
+ expect(segments?.[0].contentIndices).toEqual([0, 1]);
+ expect(segments?.[1]).toMatchObject({ live: true, contentIndices: [2] });
+ });
+});
diff --git a/client/src/utils/activityLabels.ts b/client/src/utils/activityLabels.ts
index 5550e86d3f..2e7560980f 100644
--- a/client/src/utils/activityLabels.ts
+++ b/client/src/utils/activityLabels.ts
@@ -30,6 +30,10 @@ export type ActivityPhaseSegment =
* the header carries the newest child label as a ticker instead of a
* generated summary. Set only by `synthesizeActivityFolds`. */
synthesized?: boolean;
+ /** A synthesized card over the span the run is still writing: it folds
+ * from the first tool call and keeps the in-flight tail inside, and its
+ * header is resolved at render from the newest activity in `content`. */
+ live?: boolean;
};
function isVisibleContentPart(part: TMessageContentParts | undefined): boolean {
@@ -230,6 +234,27 @@ function claimsActivity(part: TMessageContentParts | undefined): boolean {
return typeof name !== 'string' || !name.startsWith(Constants.LC_TRANSFER_TO_);
}
+/**
+ * A call a live row cannot stand for: a handoff, whose card names the
+ * destination agent and can never join a group, or a legacy Assistants variant
+ * (no top-level `args`), which the live header has no line for. Questions
+ * and subagents also retain their own cards: optimistic answers, child
+ * progress and detached-thread navigation are not carried by the outer part.
+ */
+function endsLiveSpan(part: TMessageContentParts | undefined): boolean {
+ if (part?.type !== ContentTypes.TOOL_CALL) {
+ return false;
+ }
+ const toolCall = part[ContentTypes.TOOL_CALL];
+ return (
+ !claimsActivity(part) ||
+ toolCall == null ||
+ !('args' in toolCall) ||
+ toolCall.name === 'ask_user_question' ||
+ toolCall.name === Constants.SUBAGENT
+ );
+}
+
type FoldRun = {
content: Array<TMessageContentParts | undefined>;
contentIndices: number[];
@@ -320,6 +345,44 @@ function buildSynthesizedPhaseLabel(run: FoldRun): SynthesizedPhaseHeader | unde
};
}
+/**
+ * Builds the header for the span a run is still writing. It needs no filled
+ * label — one claimable tool call is enough — because its purpose is to hold
+ * the block at the single row it will settle into, rather than letting every
+ * call add and remove rows on the way there. The text stays empty: the newest
+ * line needs localization, so the renderer resolves it.
+ */
+function buildLivePhaseLabel(run: FoldRun): SynthesizedPhaseHeader | undefined {
+ let activities = 0;
+ for (const part of run.content) {
+ /** Only an agents-shaped call can be named by the live header; the legacy
+ * Assistants variants carry no top-level `args` and keep their own cards. */
+ const toolCall = part?.type === ContentTypes.TOOL_CALL ? part[ContentTypes.TOOL_CALL] : null;
+ if (toolCall != null && 'args' in toolCall && claimsActivity(part)) {
+ activities += 1;
+ }
+ }
+ if (activities === 0) {
+ return undefined;
+ }
+ const endPosition = run.content.length - 1;
+ const labelIndex = run.contentIndices[endPosition];
+ return {
+ labelIndex,
+ endPosition,
+ labelPart: {
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: '',
+ activity_label_type: 'phase',
+ activity_start_index: run.contentIndices[0],
+ activity_end_index: labelIndex + 1,
+ activity_count: activities,
+ status: 'ok',
+ pending: true,
+ } as ActivityLabelPart,
+ };
+}
+
/**
* Splits one unclaimed content segment at its hard boundaries and folds every
* run that carries enough labeled activity into a phase segment.
@@ -332,6 +395,7 @@ function buildSynthesizedPhaseLabel(run: FoldRun): SynthesizedPhaseHeader | unde
*/
function synthesizeActivityFolds(
segment: Extract<ActivityPhaseSegment, { type: 'content' }>,
+ liveTail = false,
): ActivityPhaseSegment[] {
const segments: ActivityPhaseSegment[] = [];
const pending: FoldRun = { content: [], contentIndices: [] };
@@ -360,11 +424,12 @@ function synthesizeActivityFolds(
pending.contentIndices.push(run.contentIndices[position]);
}
};
- const flushRun = () => {
+ const flushRun = (live = false) => {
if (run.contentIndices.length === 0) {
return;
}
- const header = buildSynthesizedPhaseLabel(run);
+ const liveHeader = live ? buildLivePhaseLabel(run) : undefined;
+ const header = liveHeader ?? buildSynthesizedPhaseLabel(run);
if (header == null) {
carryOver(0);
} else {
@@ -380,6 +445,7 @@ function synthesizeActivityFolds(
labelIndex: header.labelIndex,
hasContent: content.some(isVisibleContentPart),
synthesized: true,
+ ...(liveHeader != null && { live: true }),
});
/** Everything past the newest label is still in flight — the reasoning
* and the tool call the reader is watching right now. It stays outside
@@ -393,7 +459,10 @@ function synthesizeActivityFolds(
for (let position = 0; position < segment.content.length; position += 1) {
const part = segment.content[position];
const index = segment.contentIndices[position];
- if (isFoldBoundaryPart(part)) {
+ /** Folding a call the header cannot stand for would hide its card for the
+ * rest of the run, so while streaming it ends the span the way prose
+ * does, and the calls after it start a live span of their own. */
+ if (isFoldBoundaryPart(part) || (liveTail && endsLiveSpan(part))) {
flushRun();
pending.content.push(part);
pending.contentIndices.push(index);
@@ -402,7 +471,9 @@ function synthesizeActivityFolds(
run.content.push(part);
run.contentIndices.push(index);
}
- flushRun();
+ /** Only a run that reaches the end of the message is still being written; a
+ * boundary after it means the stream has moved on to something else. */
+ flushRun(liveTail);
flushPending();
return folded ? segments : [segment];
}
@@ -415,6 +486,8 @@ function synthesizeActivityFolds(
export function groupActivityPhases(
content: Array<TMessageContentParts | undefined> | undefined,
laneGroups?: ReadonlySet<number>,
+ /** True while this message is the one the run is streaming into. */
+ live = false,
): ActivityPhaseSegment[] | undefined {
if (!content) {
return undefined;
@@ -446,12 +519,15 @@ export function groupActivityPhases(
/** No marker has landed yet — the whole message is one unclaimed span.
* Returning `undefined` when nothing folds keeps the untouched
* fast path for messages that never accumulate labeled activity. */
- const folded = synthesizeActivityFolds({
- type: 'content',
- content: definedIndices.map((index) => content[index]),
- contentIndices: definedIndices,
- startIndex: definedIndices[0] ?? 0,
- });
+ const folded = synthesizeActivityFolds(
+ {
+ type: 'content',
+ content: definedIndices.map((index) => content[index]),
+ contentIndices: definedIndices,
+ startIndex: definedIndices[0] ?? 0,
+ },
+ live,
+ );
return folded.some((segment) => segment.type === 'phase') ? folded : undefined;
}
@@ -607,8 +683,11 @@ export function groupActivityPhases(
if (!foldable) {
return segments;
}
- return segments.flatMap((segment) =>
- segment.type === 'content' ? synthesizeActivityFolds(segment) : segment,
+ const tail = segments.length - 1;
+ return segments.flatMap((segment, position) =>
+ segment.type === 'content'
+ ? synthesizeActivityFolds(segment, live && position === tail)
+ : segment,
);
}
diff --git a/client/src/utils/groupToolCalls.ts b/client/src/utils/groupToolCalls.ts
index ec5d85fb37..26c50bbf41 100644
--- a/client/src/utils/groupToolCalls.ts
+++ b/client/src/utils/groupToolCalls.ts
@@ -34,6 +34,28 @@ export function hasPendingApprovalInPart(part: TMessageContentParts): boolean {
);
}
+/**
+ * True while a standard tool call waits on a sign-in. A step the run already
+ * closed can never be waiting, whatever its progress says: `ToolCall` hides
+ * the sign-in button on a terminal status, so counting it as pending would
+ * show a trust warning with no authentication action behind it.
+ */
+export function hasPendingAuthInPart(part: TMessageContentParts): boolean {
+ if (part.type !== ContentTypes.TOOL_CALL) {
+ return false;
+ }
+ const toolCall = part[ContentTypes.TOOL_CALL];
+ if (!toolCall || !('args' in toolCall) || toolCall.runStepStatus != null) {
+ return false;
+ }
+ const standardToolCall = toolCall as Agents.ToolCall & { progress?: number };
+ return (
+ typeof standardToolCall.auth === 'string' &&
+ standardToolCall.auth.length > 0 &&
+ (standardToolCall.progress ?? 0.1) < 1
+ );
+}
+
function isGroupableToolCall(part: TMessageContentParts): boolean {
if (part.type !== ContentTypes.TOOL_CALL) {
return false;