Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
🧘 fix: Keep Prose Mounted While Activity Labels Update (#16531)
lia-by-librechat[bot]5f4d96c49b0a
diff --git a/client/src/components/Chat/Messages/Content/ContentParts.tsx b/client/src/components/Chat/Messages/Content/ContentParts.tsxindex 74da5a3885..a944fbf037 100644--- a/client/src/components/Chat/Messages/Content/ContentParts.tsx+++ b/client/src/components/Chat/Messages/Content/ContentParts.tsx@@ -710,38 +710,39 @@ const ContentPartsBody = memo(function ContentPartsBody({return occurrences;}, [toolGroupOccurrenceByIndex, sequentialParts, fallbackScope]);- const groupedParts = useMemo(() => {- return groupSequentialToolCalls(sequentialParts).map((group) => {- if (group.type === 'single') {- return group;- }- const baseGroupId = getToolGroupId(group.parts, fallbackScope);- 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>();- for (const { part } of group.parts) {- for (const attachment of attachmentsForPart(part) ?? []) {- seenAttachments.add(attachment);+ const groupParts = useCallback(+ (parts: PartWithIndex[]) => {+ return groupSequentialToolCalls(parts).map((group) => {+ if (group.type === 'single') {+ return group;}- }- const groupAttachments = hideAttachments ? undefined : Array.from(seenAttachments);- return {- ...group,- groupId,- groupAttachments,- sourceAttachments: Array.from(seenAttachments),- };- });- }, [- sequentialParts,- attachmentsForPart,- fallbackScope,- hideAttachments,- resolvedToolGroupOccurrences,- ]);+ const baseGroupId = getToolGroupId(group.parts, fallbackScope);+ 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>();+ 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,+ sourceAttachments: Array.from(seenAttachments),+ };+ });+ },+ [attachmentsForPart, fallbackScope, hideAttachments, resolvedToolGroupOccurrences],+ );+ const groupedParts = useMemo(+ () => (phaseSegments == null ? groupParts(sequentialParts) : []),+ [phaseSegments, groupParts, sequentialParts],+ );/** The re-attribution node for a part resuming after a steer block, shared* by the sequential path and the parallel renderer's sequential stretches. */@@ -786,10 +787,72 @@ const ContentPartsBody = memo(function ContentPartsBody({);}+ const safeContent = content ?? [];+ /** A solitary seeded empty TEXT part (useChatFunctions' assistant-side+ * placeholder) is the same waiting state as no content at all — route it+ * through EmptyText instead of Markdown's flush initializing dot so both+ * flows share the gated header-axis nudge. Never solitary mid-stream, so+ * empty TEXT after real parts keeps its flush in-flow cursor. */+ const solitaryEmptyText = safeContent.length === 1 && isEmptyTextPart(safeContent[0]);+ const showEmptyCursor =+ (safeContent.length === 0 || solitaryEmptyText) &&+ effectiveIsSubmitting &&+ !cursorOwnedElsewhere;+ /** Skips trailing blank label reservations and empty provider placeholders,+ * keeping the cursor attached to the last visible output. */+ const relativeLastContentIdx = lastCursorContentIdx(safeContent);+ const lastContentIdx = relativeLastContentIdx < 0 ? -1 : absoluteIndexAt(relativeLastContentIdx);++ const renderGroups = (groups: ReturnType<typeof groupParts>, lastContentIdx: number) =>+ groups.flatMap((group) => {+ const first = group.type === 'single' ? group.part : group.parts[0];+ const firstIdx = first?.idx ?? -1;+ const nodes: ReactElement[] = [];+ const attribution = renderResumeAttribution(+ firstIdx,+ first ? getPartKeyIndex(first.part, first.idx) : firstIdx,+ );+ if (attribution != null) {+ nodes.push(attribution);+ }+ if (group.type === 'single') {+ const { part, idx } = group.part;+ nodes.push(renderPart(part, idx, idx === lastContentIdx));+ return nodes;+ }+ const { groupId } = group;+ nodes.push(+ <ToolCallGroup+ key={`tool-group-${groupId}`}+ parts={group.parts}+ isSubmitting={effectiveIsSubmitting}+ /** The label part is CONSUMED into the header, not listed in+ * `parts` — a filled label at the content tail must still+ * mark its group as last or nothing holds the streaming+ * cursor until the next delta. */+ isLast={+ isLast &&+ (group.parts.some((p) => p.idx === lastContentIdx) ||+ group.labelPart?.idx === lastContentIdx)+ }+ renderPart={renderGroupedPart}+ lastContentIdx={lastContentIdx}+ groupAttachments={group.groupAttachments}+ sourceAttachments={group.sourceAttachments}+ initialExpansionState={expansionState.get(groupId)}+ showThinking={showThinking}+ onExpansionChange={(state) => handleGroupExpansionChange(groupId, state)}+ labelPart={group.labelPart}+ withinActivityPhase={withinActivityPhase}+ parentPhaseOwnsFailurePill={parentPhaseOwnsFailurePill}+ />,+ );+ return nodes;+ });++ const hasParallelContent = hasParallelLanes(content, messageLaneGroups);+ let phaseContent: ReactElement[] | undefined;if (phaseSegments != null) {- const relativeGlobalLastContentIdx = lastCursorContentIdx(content ?? []);- const globalLastContentIdx =- relativeGlobalLastContentIdx < 0 ? -1 : absoluteIndexAt(relativeGlobalLastContentIdx);/** Segment keys anchor to their first defined part's stable index, never* to the segment's ordinal: hole-only slots form phantom segments while* a run streams and vanish from the compacted final content, so ordinal@@ -863,8 +926,8 @@ const ContentPartsBody = memo(function ContentPartsBody({return false;}return segment.synthesized === true- ? segment.contentIndices.map(absoluteIndexAt).includes(globalLastContentIdx)- : absoluteIndexAt(segment.labelIndex) === globalLastContentIdx;+ ? segment.contentIndices.map(absoluteIndexAt).includes(lastContentIdx)+ : absoluteIndexAt(segment.labelIndex) === lastContentIdx;});const renderSegment = (segmentContent: Array<TMessageContentParts | undefined>,@@ -887,7 +950,7 @@ const ContentPartsBody = memo(function ContentPartsBody({attachments={inlineAttachments}searchResults={searchResults}isCreatedByUser={isCreatedByUser}- isLast={!ownsCursor && isLast && segmentIndices.includes(globalLastContentIdx)}+ isLast={!ownsCursor && isLast && segmentIndices.includes(lastContentIdx)}isSubmitting={isSubmitting}isLatestMessage={isLatestMessage}nestedActivityPhase@@ -907,197 +970,171 @@ const ContentPartsBody = memo(function ContentPartsBody({/>);};- const hasParallelContent = hasParallelLanes(content, messageLaneGroups);- return (- <ApprovalProvider>- <SearchContext.Provider value={{ searchResults }}>- <MemoryArtifacts attachments={attachments} />- {hasParallelContent && (- <Sources messageId={messageId} conversationId={conversationId || undefined} />- )}- {renderPendingSkills()}- {phaseSegments.map((segment) => {- if (segment.type !== 'phase') {- return renderSegment(- segment.content,- absoluteIndexAt(segment.startIndex),- segment.contentIndices.map(absoluteIndexAt),- `phase-adjacent-${segmentKeyIndex(segment)}`,- );- }- 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- * header ticks with the newest child label, so keying on it would- * remount the card on every tick — and when the summary finally- * lands, a card keyed the same way as the fold it replaces is- * RECONCILED rather than remounted, so a reader who opened the- * ticker keeps it open with no state to hand over. A phase with no- * children has no span to anchor to and keeps its marker key.- *- * The first tool call carries it — its provider id paired with- * its own position. No message identity goes into it, and none- * can: `MultiMessage` reuses this instance across siblings, but- * `messageId` moves at settle (batched with- * `setIsSubmitting(false)`, so that commit is indistinguishable- * from a sibling switch) and the positional `siblingIdx` moves- * under background churn that deliberately PRESERVES the viewed- * response. Both halves survive those: the position is- * content-derived, and the provider id is what separates two- * siblings whose cards start at the same index. Pairing them also- * keeps repeated provider ids in one message apart, the way- * `getToolGroupId` uses an occurrence counter. */- const cardKey = stableCardKey(segment);- const labelText = getActivityLabelText(segment.labelPart);- const segmentIndices = segment.contentIndices.map(absoluteIndexAt);- /** While a run streams, the cursor sits INSIDE a synthesized span.- * A collapsed card would swallow it, so the card carries it below- * the header and the nested body stands down. */- const ownsCursor =- synthesized &&- isLast &&- effectiveIsSubmitting &&- segmentIndices.includes(globalLastContentIdx);- const hasPendingApproval = segment.content.some(- (part) => part != null && hasPendingApprovalInPart(part),- );- /** The span's files, lifted out of the fold into their own row- * under the header.- *- * This is why a span carrying attachments no longer has to skip- * folding. `ToolCallGroup` hoists `groupAttachments` outside its- * own panel so generated output survives collapsing the group,- * and folding that group into a card used to put the hoist back- * inside a disclosure — so a synthesized span with any output- * rendered unfolded rather than swallow it. Hoisting one level- * further makes the card safe for exactly that content, and- * agent runs that produce files are the ones with the longest- * lists to fold. */- const phaseAttachments = collectPhaseAttachments(segment.content);- /** A fold summarizes work that is DONE. An unresolved approval is- * the run asking the reader for something and blocking until it- * gets it — never put that behind a disclosure they have to find.- * A server marker cannot hit this (it is emitted after the batch- * resolves), but a subagent nested in an already-labeled group- * 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. */- /** "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),- segmentIndices,- `phase-awaiting-${cardKey}`,- );- }- return (- <ActivityPhaseGroup- key={`activity-phase-${cardKey}`}- labelPart={segment.labelPart}- hasContent={segment.hasContent}- attachments={phaseAttachments}- hasPendingApproval={hasPendingApproval}- onExpansionChange={- live &&- reasoningDisclosures != null &&- !segment.content.some((part) => part?.type === ContentTypes.TOOL_CALL)- ? (expanded) => {- segment.content.forEach((part, position) => {- if (part?.type !== ContentTypes.THINK) {- return;- }- const index = getPartKeyIndex(part, segmentIndices[position]);- disclosureStore.set(- reasoningDisclosure(reasoningDisclosures, index),- expanded,- );- });- }- : undefined- }- 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- * mid-run — the key carries `messageId`, which changes when- * the placeholder hydrates to the server id, and a reconnect- * mounts straight onto existing labeled content. Either- * would flash the whole fold back open. Fold GROWTH is- * already unanimated, so formation matching it is the- * consistent behavior, not a downgrade. */- !synthesized &&- previousPhases != null &&- !previousPhases.indices.has(phaseKeyIndex) &&- (!hasPhaseRekey ||- (completedPhaseKeys.ordinals.get(phaseKeyIndex) ?? 1) >- (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 && !live- : isLast &&- effectiveIsSubmitting &&- absoluteIndexAt(segment.labelIndex) === globalLastContentIdx+ phaseContent = phaseSegments.flatMap((segment) => {+ if (segment.type !== 'phase') {+ if (hasParallelContent) {+ return renderSegment(+ segment.content,+ absoluteIndexAt(segment.startIndex),+ segment.contentIndices.map(absoluteIndexAt),+ `phase-adjacent-${segmentKeyIndex(segment)}`,+ );+ }+ /** Unclaimed prose keeps its original parent and part key. A+ * nested body here would remount it whenever a fold appears or+ * disappears, replaying the markdown word fade. */+ const parts: PartWithIndex[] = [];+ segment.content.forEach((part, position) => {+ if (part != null) {+ parts.push({ part, idx: absoluteIndexAt(segment.contentIndices[position]) });+ }+ });+ return renderGroups(groupParts(parts), lastContentIdx);+ }+ 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+ * header ticks with the newest child label, so keying on it would+ * remount the card on every tick — and when the summary finally+ * lands, a card keyed the same way as the fold it replaces is+ * RECONCILED rather than remounted, so a reader who opened the+ * ticker keeps it open with no state to hand over. A phase with no+ * children has no span to anchor to and keeps its marker key.+ *+ * The first tool call carries it — its provider id paired with+ * its own position. No message identity goes into it, and none+ * can: `MultiMessage` reuses this instance across siblings, but+ * `messageId` moves at settle (batched with+ * `setIsSubmitting(false)`, so that commit is indistinguishable+ * from a sibling switch) and the positional `siblingIdx` moves+ * under background churn that deliberately PRESERVES the viewed+ * response. Both halves survive those: the position is+ * content-derived, and the provider id is what separates two+ * siblings whose cards start at the same index. Pairing them also+ * keeps repeated provider ids in one message apart, the way+ * `getToolGroupId` uses an occurrence counter. */+ const cardKey = stableCardKey(segment);+ const labelText = getActivityLabelText(segment.labelPart);+ const segmentIndices = segment.contentIndices.map(absoluteIndexAt);+ /** While a run streams, the cursor sits INSIDE a synthesized span.+ * A collapsed card would swallow it, so the card carries it below+ * the header and the nested body stands down. */+ const ownsCursor =+ synthesized && isLast && effectiveIsSubmitting && segmentIndices.includes(lastContentIdx);+ const hasPendingApproval = segment.content.some(+ (part) => part != null && hasPendingApprovalInPart(part),+ );+ /** The span's files, lifted out of the fold into their own row+ * under the header.+ *+ * This is why a span carrying attachments no longer has to skip+ * folding. `ToolCallGroup` hoists `groupAttachments` outside its+ * own panel so generated output survives collapsing the group,+ * and folding that group into a card used to put the hoist back+ * inside a disclosure — so a synthesized span with any output+ * rendered unfolded rather than swallow it. Hoisting one level+ * further makes the card safe for exactly that content, and+ * agent runs that produce files are the ones with the longest+ * lists to fold. */+ const phaseAttachments = collectPhaseAttachments(segment.content);+ /** A fold summarizes work that is DONE. An unresolved approval is+ * the run asking the reader for something and blocking until it+ * gets it — never put that behind a disclosure they have to find.+ * A server marker cannot hit this (it is emitted after the batch+ * resolves), but a subagent nested in an already-labeled group+ * 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. */+ /** "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),+ segmentIndices,+ `phase-awaiting-${cardKey}`,+ );+ }+ return (+ <ActivityPhaseGroup+ key={`activity-phase-${cardKey}`}+ labelPart={segment.labelPart}+ hasContent={segment.hasContent}+ attachments={phaseAttachments}+ hasPendingApproval={hasPendingApproval}+ onExpansionChange={+ live &&+ reasoningDisclosures != null &&+ !segment.content.some((part) => part?.type === ContentTypes.TOOL_CALL)+ ? (expanded) => {+ segment.content.forEach((part, position) => {+ if (part?.type !== ContentTypes.THINK) {+ return;+ }+ const index = getPartKeyIndex(part, segmentIndices[position]);+ disclosureStore.set(reasoningDisclosure(reasoningDisclosures, index), expanded);+ });}- >- {renderSegment(- segment.content,- absoluteIndexAt(segment.startIndex),- segmentIndices,- `phase-content-${cardKey}`,- /** 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,- true,- )}- </ActivityPhaseGroup>- );- })}- <WorkspaceChanges attachments={workspaceChanges} />- </SearchContext.Provider>- </ApprovalProvider>- );+ : undefined+ }+ 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+ * mid-run — the key carries `messageId`, which changes when+ * the placeholder hydrates to the server id, and a reconnect+ * mounts straight onto existing labeled content. Either+ * would flash the whole fold back open. Fold GROWTH is+ * already unanimated, so formation matching it is the+ * consistent behavior, not a downgrade. */+ !synthesized &&+ previousPhases != null &&+ !previousPhases.indices.has(phaseKeyIndex) &&+ (!hasPhaseRekey ||+ (completedPhaseKeys.ordinals.get(phaseKeyIndex) ?? 1) >+ (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 && !live+ : isLast &&+ effectiveIsSubmitting &&+ absoluteIndexAt(segment.labelIndex) === lastContentIdx+ }+ >+ {renderSegment(+ segment.content,+ absoluteIndexAt(segment.startIndex),+ segmentIndices,+ `phase-content-${cardKey}`,+ /** 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,+ true,+ )}+ </ActivityPhaseGroup>+ );+ });}- const safeContent = content ?? [];- /** A solitary seeded empty TEXT part (useChatFunctions' assistant-side- * placeholder) is the same waiting state as no content at all — route it- * through EmptyText instead of Markdown's flush initializing dot so both- * flows share the gated header-axis nudge. Never solitary mid-stream, so- * empty TEXT after real parts keeps its flush in-flow cursor. */- const solitaryEmptyText = safeContent.length === 1 && isEmptyTextPart(safeContent[0]);- const showEmptyCursor =- (safeContent.length === 0 || solitaryEmptyText) &&- effectiveIsSubmitting &&- !cursorOwnedElsewhere;- /** Skips trailing blank label reservations and empty provider placeholders,- * keeping the cursor attached to the last visible output. */- const relativeLastContentIdx = lastCursorContentIdx(safeContent);- const lastContentIdx = relativeLastContentIdx < 0 ? -1 : absoluteIndexAt(relativeLastContentIdx);-/** Columns only when at least two agents share a group — a lone group* renders here, where tool grouping and activity labels apply. */- const hasParallelContent = hasParallelLanes(safeContent, messageLaneGroups);- if (hasParallelContent) {+ if (hasParallelContent && phaseContent == null) {const parallelContent = (<>{renderPendingSkills()}@@ -1130,6 +1167,9 @@ const ContentPartsBody = memo(function ContentPartsBody({const sequentialContent = (<SearchContext.Provider value={{ searchResults }}>{!nestedActivityPhase && <MemoryArtifacts attachments={attachments} />}+ {phaseContent != null && hasParallelContent && (+ <Sources messageId={messageId} conversationId={conversationId || undefined} />+ )}{!nestedActivityPhase && renderPendingSkills()}{showEmptyCursor && (<Container>@@ -1142,52 +1182,7 @@ const ContentPartsBody = memo(function ContentPartsBody({/></Container>)}- {!showEmptyCursor &&- groupedParts.flatMap((group) => {- const first = group.type === 'single' ? group.part : group.parts[0];- const firstIdx = first?.idx ?? -1;- const nodes: ReactElement[] = [];- const attribution = renderResumeAttribution(- firstIdx,- first ? getPartKeyIndex(first.part, first.idx) : firstIdx,- );- if (attribution != null) {- nodes.push(attribution);- }- if (group.type === 'single') {- const { part, idx } = group.part;- nodes.push(renderPart(part, idx, idx === lastContentIdx));- return nodes;- }- const { groupId } = group;- nodes.push(- <ToolCallGroup- key={`tool-group-${groupId}`}- parts={group.parts}- isSubmitting={effectiveIsSubmitting}- /** The label part is CONSUMED into the header, not listed in- * `parts` — a filled label at the content tail must still- * mark its group as last or nothing holds the streaming- * cursor until the next delta. */- isLast={- isLast &&- (group.parts.some((p) => p.idx === lastContentIdx) ||- group.labelPart?.idx === lastContentIdx)- }- renderPart={renderGroupedPart}- lastContentIdx={lastContentIdx}- groupAttachments={group.groupAttachments}- sourceAttachments={group.sourceAttachments}- initialExpansionState={expansionState.get(groupId)}- showThinking={showThinking}- onExpansionChange={(state) => handleGroupExpansionChange(groupId, state)}- labelPart={group.labelPart}- withinActivityPhase={withinActivityPhase}- parentPhaseOwnsFailurePill={parentPhaseOwnsFailurePill}- />,- );- return nodes;- })}+ {!showEmptyCursor && (phaseContent ?? renderGroups(groupedParts, lastContentIdx))}{!nestedActivityPhase && <WorkspaceChanges attachments={workspaceChanges} />}</SearchContext.Provider>);diff --git a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.integration.test.tsxindex 921b749a47..09352da57a 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@@ -4,6 +4,7 @@ import { ContentTypes, Tools } from 'librechat-data-provider';import { act, fireEvent, render, screen, within } from '@testing-library/react';import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';import ContentParts from '../ContentParts';+import { Text } from '../Parts';jest.mock('~/hooks', () => ({useLocalize: () => (key: string, values?: Record<string | number, string>) => {@@ -102,7 +103,7 @@ jest.mock('../Parts', () => ({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>,+ Text: jest.fn(({ text }: { text?: string }) => <div data-testid="text">{text}</div>),MemoryCall: ({ attachments }: { attachments?: TAttachment[] }) => (<div data-testid="memory-call" data-count={attachments?.length ?? 0} />),@@ -241,6 +242,75 @@ const renderContentParts = (props: React.ComponentProps<typeof ContentParts>) =></RecoilRoot>,);+describe('ContentParts integration: adjacent prose identity', () => {+ afterEach(() => {+ jest.useRealTimers();+ });++ it.each([true, false])(+ 'keeps prose mounted through activity transitions with live folding %s',+ (foldLiveActivity) => {+ jest.useFakeTimers();+ const introText = "Let me establish today's date and gather independent signals.";+ const answerText = 'Two things stand out immediately. Let me dig into both.';+ const intro = makeTextPart(introText);+ const answer = makeTextPart(answerText);+ const call = makeMcpToolCall('date', false);+ const completed = makeMcpToolCall('date');+ const reservation: TMessageContentParts = {+ type: ContentTypes.ACTIVITY_LABEL,+ [ContentTypes.ACTIVITY_LABEL]: '',+ tool_call_ids: ['date'],+ pending: true,+ };+ const label = { ...reservation, activity_label: 'Established current date', pending: false };+ const frame = (content: TMessageContentParts[]) => (+ <RecoilRoot>+ <ContentParts+ messageId="msg1"+ content={content}+ isCreatedByUser={false}+ isLast+ isSubmitting+ isLatestMessage+ showThinking={false}+ foldLiveActivity={foldLiveActivity}+ />+ </RecoilRoot>+ );+ const { rerender } = render(frame([intro]));+ const row = screen.getByText(introText);++ rerender(frame([intro, call]));+ expect(screen.getByText(introText)).toBe(row);++ rerender(frame([intro, completed, reservation]));+ const renders = jest.mocked(Text).mock.calls.length;+ rerender(frame([intro, completed, label]));+ expect(screen.getByText(introText)).toBe(row);+ expect(jest.mocked(Text).mock.calls).toHaveLength(renders);+ act(() => {+ jest.advanceTimersByTime(1000);+ });+ expect(screen.getByRole('button', { name: /Established current date/ })).toBeInTheDocument();++ rerender(frame([intro, completed, label, answer]));+ expect(screen.getByText(introText)).toBe(row);+ const answerRow = screen.getByText(answerText);++ const nextCall = makeMcpToolCall('incidents', false);+ rerender(frame([intro, completed, label, answer, nextCall]));+ expect(screen.getByText(introText)).toBe(row);+ expect(screen.getByText(answerText)).toBe(answerRow);++ const phase = makePhasePart(1, 3, 'Confirmed date');+ rerender(frame([intro, completed, label, answer, nextCall, phase]));+ expect(screen.getByText(introText)).toBe(row);+ expect(screen.getByText(answerText)).toBe(answerRow);+ },+ );+});+describe('ContentParts integration: MCP image hoist and grouping', () => {const baseProps = {messageId: 'msg1',diff --git a/e2e/setup/fake-model.js b/e2e/setup/fake-model.jsindex 30043194c5..9ac45cc30f 100644--- a/e2e/setup/fake-model.js+++ b/e2e/setup/fake-model.js@@ -54,6 +54,7 @@ const STEER_LATE_REPLY_MARKER = 'E2E_STEER_LATE_REPLY:';const ACTIVITY_REPLY_MARKER = 'E2E_ACTIVITY_REPLY:';const ACTIVITY_PHASE_REPLY_MARKER = 'E2E_ACTIVITY_PHASE_REPLY:';const ACTIVITY_FAILED_REPLY_MARKER = 'E2E_ACTIVITY_FAILED_REPLY:';+const ACTIVITY_PROSE_REPLY_MARKER = 'E2E_ACTIVITY_PROSE_REPLY:';const ASK_USER_QUESTION_MARKER = 'E2E_ASK_USER_QUESTION:';const RESUME_ICON_REPLY_MARKER = 'E2E_RESUME_ICON_REPLY:';const FORCED_ERROR_MARKER = 'E2E_FORCED_ERROR:';@@ -743,7 +744,13 @@ class UsageEmittingFakeChatModel extends FakeChatModel {this.streamSleep = sleep ?? CHUNK_DELAY_MS;}- async *streamScriptedResponseChunks({ response, toolCalls, textDeltaBlocks, runManager }) {+ async *streamScriptedResponseChunks({+ response,+ toolCalls,+ textDeltaBlocks,+ beforeToolsDelayMs,+ runManager,+ }) {if (this.emitCustomEvent) {await runManager?.handleCustomEvent('some_test_event', {someval: true,@@ -766,7 +773,7 @@ class UsageEmittingFakeChatModel extends FakeChatModel {}if (toolCalls?.length) {- await new Promise((resolve) => setTimeout(resolve, this.streamSleep));+ await new Promise((resolve) => setTimeout(resolve, beforeToolsDelayMs ?? this.streamSleep));if (!toolCalls.some((toolCall) => toolCall.streamArgs)) {const toolCallChunks = toolCalls.map((toolCall, index) => ({name: toolCall.name,@@ -838,6 +845,7 @@ class UsageEmittingFakeChatModel extends FakeChatModel {response: scriptedResponse.response ?? '',toolCalls: scriptedResponse.toolCalls,textDeltaBlocks: scriptedResponse.textDeltaBlocks === true,+ beforeToolsDelayMs: scriptedResponse.beforeToolsDelayMs,runManager,});} else if (dynamicResponse) {@@ -1501,6 +1509,43 @@ function activityPhaseReplyResponses(label, toolNames) {};}+/** Short prose remains visible while the real tool/label pipeline forms and+ * dissolves folds. The pause before calls lets the browser finish the initial+ * word fade and install its identity/animation observer before that transition. */+function activityProseReplyResponses(label, toolNames) {+ const toolName = Array.from(toolNames).find((name) => name.startsWith(STEER_TOOL_NAME_PREFIX));+ if (!toolName) {+ throw new Error('Activity prose fixture requires the memory MCP tool');+ }+ const prose = [+ "Let me establish today's date and gather independent signals in parallel.",+ 'Today is **2026-09-29 23:20 UTC**. Two things stand out immediately: a config-structure PR landed yesterday, and an image bump went in today. Let me dig into both.',+ "Important finding: PR #4079 ships the config **disabled by default**. Let me check today's actual runtime state and the image bump.",+ ];+ let invocation = 0;+ return {+ responses: [''],+ resolveInvocation: async () => {+ const batch = invocation++;+ if (batch < prose.length) {+ return {+ response: prose[batch],+ beforeToolsDelayMs: 2000,+ toolCalls: [+ {+ id: `call_e2e_activity_prose_${label}_${batch}`,+ name: toolName,+ args: { fact: `activity prose ${label} ${batch}` },+ type: 'tool_call',+ },+ ],+ };+ }+ return { response: `E2E activity prose complete ${label}` };+ },+ };+}+/*** A phase whose middle batch holds a failed call beside a slow one: `slow_echo`* called without its required `text` fails schema validation before the tool@@ -3089,6 +3134,11 @@ function resolveResponses({ graph, messages, text, toolNames }) {return activityPhaseReplyResponses(activityPhaseLabel, toolNames);}+ const activityProseLabel = getMarkerValue(text, ACTIVITY_PROSE_REPLY_MARKER);+ if (activityProseLabel) {+ return activityProseReplyResponses(activityProseLabel, toolNames);+ }+const activityFailedLabel = getMarkerValue(text, ACTIVITY_FAILED_REPLY_MARKER);if (activityFailedLabel) {return activityFailedReplyResponses(activityFailedLabel, toolNames);diff --git a/e2e/specs/mock/activity-prose.spec.ts b/e2e/specs/mock/activity-prose.spec.tsnew file mode 100644index 0000000000..dde5cc6a32--- /dev/null+++ b/e2e/specs/mock/activity-prose.spec.ts@@ -0,0 +1,157 @@+import { expect, test } from '@playwright/test';+import { NEW_CHAT_PATH, messagesView, selectMockEndpoint, sendMessage } from './helpers';++const INTRO = "Let me establish today's date and gather independent signals in parallel.";+const LABELS = [+ 'Established current date, found active incidents and recent chart updates',+ 'Checked chart version and loaded the logs schema',+ 'Confirmed deployed image and checked runtime configuration',+];+const LABEL_SERVER = `http://127.0.0.1:${process.env.E2E_LABEL_PORT || '8889'}`;++type ProseProbe = {+ fadeStarts: number;+ lowestOpacity: number;+ disconnected: boolean;+ spans: Element[];+};+type ObservedParagraph = HTMLElement & { proseProbe?: ProseProbe };++/** Do not let an OS motion preference silently bypass the regression. */+test.use({ contextOptions: { reducedMotion: 'no-preference' } });++for (const autoExpandTools of [false, true]) {+ test(`keeps introductory Markdown mounted without replaying its fade as activity labels arrive (tools expanded: ${autoExpandTools})`, async ({+ page,+ request,+ }, testInfo) => {+ test.setTimeout(90_000);+ await page.addInitScript((expanded) => {+ localStorage.setItem('smoothStreaming', 'true');+ localStorage.setItem('autoExpandTools', String(expanded));+ localStorage.setItem('color-theme', 'dark');+ }, autoExpandTools);+ const label = `prose-${Date.now()}`;+ expect((await request.post(`${LABEL_SERVER}/__e2e/reset`)).ok()).toBeTruthy();+ expect(+ (+ await request.post(`${LABEL_SERVER}/__e2e/behavior`, {+ data: {+ delayMs: 700,+ phaseLabel: 'Verified runtime configuration and deployment',+ labelsByPrompt: Object.fromEntries(+ LABELS.map((text, batch) => [`activity prose ${label} ${batch}`, text]),+ ),+ },+ })+ ).ok(),+ ).toBeTruthy();++ await page.goto(NEW_CHAT_PATH);+ await selectMockEndpoint(page, { label: 'Mock Provider F', model: 'mock-model-f' });+ await page.getByRole('button', { name: 'MCP Servers', exact: true }).click();+ const server = page.getByRole('menuitemcheckbox', { name: /E2E Memory/ });+ await server.click();+ await expect(server).toHaveAttribute('aria-checked', 'true');+ await page.keyboard.press('Escape');+ expect((await sendMessage(page, `E2E_ACTIVITY_PROSE_REPLY:${label}`)).ok()).toBeTruthy();++ const intro = messagesView(page).locator('.message-content p').filter({ hasText: INTRO });+ await expect(intro).toHaveText(INTRO);+ /** Prove this is the real animated Markdown path, not a text stub or a+ * reduced-motion run that could pass without ever exercising the fade. */+ await expect(intro.locator('[data-lc-fade]').first()).toHaveCSS('animation-name', 'lc-fade-in');+ await expect+ .poll(() =>+ intro.evaluate((element) =>+ element+ .getAnimations({ subtree: true })+ .every((animation) => animation.playState === 'finished'),+ ),+ )+ .toBe(true);+ const original = await intro.elementHandle();+ if (!original) {+ throw new Error('Introductory Markdown paragraph was not mounted');+ }+ await original.evaluate((element: ObservedParagraph) => {+ const probe: ProseProbe = {+ fadeStarts: 0,+ lowestOpacity: 1,+ disconnected: false,+ spans: Array.from(element.querySelectorAll('[data-lc-fade]')),+ };+ element.proseProbe = probe;+ document.addEventListener(+ 'animationstart',+ (event) => {+ const target = event.target;+ if (+ event.animationName === 'lc-fade-in' &&+ target instanceof Element &&+ target.closest('p')?.textContent === element.textContent+ ) {+ probe.fadeStarts += 1;+ probe.lowestOpacity = Math.min(+ probe.lowestOpacity,+ Number(getComputedStyle(target).opacity),+ );+ }+ },+ true,+ );+ const observer = new MutationObserver(() => {+ if (!element.isConnected) {+ probe.disconnected = true;+ observer.disconnect();+ }+ });+ observer.observe(document.body, { childList: true, subtree: true });+ });++ const snapshots = [];+ for (const text of LABELS.slice(0, 2)) {+ await expect(+ messagesView(page)+ .getByRole('button', { name: new RegExp(text) })+ .first(),+ ).toBeVisible({ timeout: 30_000 });+ /** Sample on a painted frame so queued animationstart events are included. */+ await page.evaluate(+ () => new Promise<void>((resolve) => requestAnimationFrame(() => resolve())),+ );+ const snapshot = await original.evaluate((element: ObservedParagraph) => {+ const probe = element.proseProbe;+ if (!probe) {+ throw new Error('Markdown observer was lost');+ }+ return {+ connected: element.isConnected,+ disconnected: probe.disconnected,+ originalFadeSpansConnected: probe.spans.every((span) => span.isConnected),+ fadeStarts: probe.fadeStarts,+ lowestOpacity: probe.lowestOpacity,+ };+ });+ snapshots.push({ label: text, ...snapshot });+ expect+ .soft(snapshot.connected, 'An activity update must retain the original paragraph')+ .toBe(true);+ expect+ .soft(snapshot.originalFadeSpansConnected, 'Existing word spans must not be replaced')+ .toBe(true);+ expect+ .soft(snapshot.fadeStarts, 'Already-visible prose must not restart its word fade')+ .toBe(0);+ }+ await testInfo.attach('markdown-identity-and-fade', {+ body: JSON.stringify(snapshots, null, 2),+ contentType: 'application/json',+ });+ await expect(messagesView(page).getByText(`E2E activity prose complete ${label}`)).toBeVisible({+ timeout: 30_000,+ });+ await expect(page.getByRole('button', { name: 'Stop generating' })).toBeHidden();+ await expect(intro).toHaveText(INTRO);+ });+}