Skip to content

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

🪭 fix: Settle Parent Phase Cards Without Replaying the Entrance Fold (#15345)

Danny Avila4d5126976a6a
diff --git a/client/src/components/Chat/Messages/Content/ContentParts.tsx b/client/src/components/Chat/Messages/Content/ContentParts.tsx
index 2133d60a7c..4cc420a24c 100644
--- a/client/src/components/Chat/Messages/Content/ContentParts.tsx
+++ b/client/src/components/Chat/Messages/Content/ContentParts.tsx
@@ -14,8 +14,12 @@ import {
filterAttachmentsForPart,
groupSequentialToolCalls,
} from '~/utils';
+import {
+ groupActivityPhases,
+ lastCursorContentIdx,
+ getActivityLabelText,
+} from '~/utils/activityLabels';
import WorkspaceChanges, { partitionWorkspaceChanges } from './Parts/WorkspaceChanges';
-import { groupActivityPhases, lastCursorContentIdx } from '~/utils/activityLabels';
import { ParallelContentRenderer, type PartWithIndex } from './ParallelContent';
import MemoryArtifacts, { hasMemoryArtifacts } from './MemoryArtifacts';
import { MessageContext, SearchContext } from '~/Providers';
@@ -169,6 +173,8 @@ type ContentPartsProps = {
| undefined;
/** Internal recursion guard for nested phase segments. */
nestedActivityPhase?: boolean;
+ /** Internal signal that this segment renders inside a completed phase card. */
+ withinActivityPhase?: boolean;
/** Internal signal that the parent already removed message-level workspace attachments. */
workspaceAttachmentsPartitioned?: boolean;
/** Absolute transcript index represented by `content[0]` in a phase slice. */
@@ -205,6 +211,7 @@ const ContentPartsBody = memo(function ContentPartsBody({
isLatestMessage,
createdAt,
nestedActivityPhase = false,
+ withinActivityPhase = false,
workspaceAttachmentsPartitioned = false,
contentIndexOffset = 0,
contentIndices,
@@ -249,30 +256,72 @@ const ContentPartsBody = memo(function ContentPartsBody({
() => (nestedActivityPhase ? undefined : groupActivityPhases(content)),
[nestedActivityPhase, content],
);
- const completedPhaseIndices = useMemo(() => {
+ const completedPhaseKeys = useMemo(() => {
const indices = new Set<number>();
+ const labels = new Map<string, number>();
+ const ordinals = new Map<number, number>();
for (const segment of phaseSegments ?? []) {
if (segment.type === 'phase') {
+ const text = getActivityLabelText(segment.labelPart);
+ const occurrence = (labels.get(text) ?? 0) + 1;
indices.add(getPartKeyIndex(segment.labelPart, segment.labelIndex));
+ labels.set(text, occurrence);
+ ordinals.set(getPartKeyIndex(segment.labelPart, segment.labelIndex), occurrence);
}
}
- return indices;
+ return { indices, labels, ordinals };
}, [phaseSegments]);
/** A phase label can finish after the root text stream settles, so
* `isSubmitting` is not a reliable entrance signal. Compare committed
* phase markers instead: a marker that appears after this renderer has
* mounted is live; markers present on the first render are history.
*
- * The recorded set is scoped to the message it described. `MultiMessage`
- * renders siblings without a key, so this instance survives a sibling
- * switch with its refs intact — an unscoped set would report the previous
- * sibling's phases and animate the newly selected sibling's history. */
- const previousPhaseRef = useRef<{ messageId: string; indices: Set<number> } | null>(null);
- const previousPhaseIndices =
- previousPhaseRef.current?.messageId === messageId ? previousPhaseRef.current.indices : null;
+ * Both the render key AND the label text identify a known marker. The
+ * final event swaps in the server's compacted content, and when the
+ * streamed-index stamp cannot pair the two arrays every index-derived key
+ * shifts — an index-only guard then reads each already-settled phase as
+ * new and replays its fold over content the reader already watched fold.
+ * The label text survives any re-key, so a re-keyed marker whose text was
+ * already on screen mounts settled instead. The text layer engages ONLY
+ * when a previously rendered key has vanished — the signature of a
+ * re-key. A pure addition keeps key identity authoritative, so a marker
+ * that fills out of order behind an already-rendered twin (concurrent
+ * fills can resolve later-index first, with identical summaries) still
+ * animates. Under a re-key, texts are counted and each marker paired
+ * with a prior occurrence by position: a run may legitimately generate
+ * two phases with identical summaries, and only an occurrence past the
+ * previously rendered count deserves its entrance.
+ *
+ * The recorded sets are scoped to the message they described.
+ * `MultiMessage` renders siblings without a key, so this instance survives
+ * a sibling switch with its refs intact — unscoped sets would report the
+ * previous sibling's phases and animate the newly selected sibling's
+ * history. */
+ const previousPhaseRef = useRef<{
+ messageId: string;
+ indices: Set<number>;
+ labels: Map<string, number>;
+ } | null>(null);
+ const previousPhases =
+ previousPhaseRef.current?.messageId === messageId ? previousPhaseRef.current : null;
+ const hasPhaseRekey = useMemo(() => {
+ if (previousPhases == null) {
+ return false;
+ }
+ for (const key of previousPhases.indices) {
+ if (!completedPhaseKeys.indices.has(key)) {
+ return true;
+ }
+ }
+ return false;
+ }, [previousPhases, completedPhaseKeys]);
useEffect(() => {
- previousPhaseRef.current = { messageId, indices: completedPhaseIndices };
- }, [messageId, completedPhaseIndices]);
+ previousPhaseRef.current = {
+ messageId,
+ indices: completedPhaseKeys.indices,
+ labels: completedPhaseKeys.labels,
+ };
+ }, [messageId, completedPhaseKeys]);
const handleGroupExpansionChange = useCallback(
(groupId: string, state: ToolCallGroupExpansionState) => {
@@ -527,6 +576,7 @@ const ContentPartsBody = memo(function ContentPartsBody({
segmentStartIndex: number,
segmentIndices: ReadonlyArray<number>,
key: string,
+ withinPhase = false,
) => {
return (
<ContentPartsBody
@@ -543,6 +593,7 @@ const ContentPartsBody = memo(function ContentPartsBody({
isSubmitting={isSubmitting}
isLatestMessage={isLatestMessage}
nestedActivityPhase
+ withinActivityPhase={withinPhase}
workspaceAttachmentsPartitioned
contentIndexOffset={segmentStartIndex}
contentIndices={segmentIndices}
@@ -570,6 +621,7 @@ const ContentPartsBody = memo(function ContentPartsBody({
);
}
const phaseKeyIndex = getPartKeyIndex(segment.labelPart, segment.labelIndex);
+ const labelText = getActivityLabelText(segment.labelPart);
return (
<ActivityPhaseGroup
key={`activity-phase-${messageId}-${phaseKeyIndex}`}
@@ -579,7 +631,11 @@ const ContentPartsBody = memo(function ContentPartsBody({
(part) => part != null && hasPendingApprovalInPart(part),
)}
animateEntrance={
- previousPhaseIndices != null && !previousPhaseIndices.has(phaseKeyIndex)
+ previousPhases != null &&
+ !previousPhases.indices.has(phaseKeyIndex) &&
+ (!hasPhaseRekey ||
+ (completedPhaseKeys.ordinals.get(phaseKeyIndex) ?? 1) >
+ (previousPhases.labels.get(labelText) ?? 0))
}
showCursor={
isLast &&
@@ -592,6 +648,7 @@ const ContentPartsBody = memo(function ContentPartsBody({
absoluteIndexAt(segment.startIndex),
segment.contentIndices.map(absoluteIndexAt),
`phase-content-${phaseKeyIndex}`,
+ true,
)}
</ActivityPhaseGroup>
);
@@ -698,6 +755,7 @@ const ContentPartsBody = memo(function ContentPartsBody({
initialExpansionState={expansionState.get(groupId)}
onExpansionChange={(state) => handleGroupExpansionChange(groupId, state)}
labelPart={group.labelPart}
+ withinActivityPhase={withinActivityPhase}
/>,
);
return nodes;
diff --git a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
index 46daffdaef..e40ecddbc4 100644
--- a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
@@ -96,6 +96,14 @@ interface ToolCallGroupProps {
/** Activity-label part terminating this block; when it carries generated
* text the header shows that text instead of the default tool summary. */
labelPart?: PartWithIndex;
+ /** True inside a completed phase card. The phase summary already speaks for
+ * this activity, so the group defaults collapsed and never auto-expands —
+ * a remount into the folding card must not toggle open and shut again
+ * while the parent entrance is playing. A pending approval overrides the
+ * suppression: a phase can resolve while an approval inside it still
+ * blocks the run, and hiding that card behind a second collapsed
+ * disclosure would bury the action the run is waiting on. */
+ withinActivityPhase?: boolean;
}
export type ToolCallGroupExpansionState = {
@@ -113,6 +121,7 @@ export default function ToolCallGroup({
initialExpansionState,
onExpansionChange,
labelPart,
+ withinActivityPhase = false,
}: ToolCallGroupProps) {
const localize = useLocalize();
const mcpIconMap = useMCPIconMap();
@@ -207,9 +216,10 @@ export default function ToolCallGroup({
* even at a single tool call — agent runs are full of one-call batches,
* and leaving those expanded defeats the grouping. */
const autoCollapse = !autoExpand && allCompleted && (count >= 2 || activityLabelText.length > 0);
+ const suppressAutoExpand = withinActivityPhase && !hasPendingApproval;
const initialState = initialExpansionState?.userOverride === true ? initialExpansionState : null;
const [isExpanded, setIsExpanded] = useState(
- initialState?.isExpanded ?? (autoExpand || !autoCollapse),
+ initialState?.isExpanded ?? (autoExpand || (!autoCollapse && !suppressAutoExpand)),
);
const [userOverride, setUserOverride] = useState(initialState != null);
const [shouldRenderBody, setShouldRenderBody] = useState(isExpanded);
@@ -322,11 +332,11 @@ export default function ToolCallGroup({
);
useEffect(() => {
- if (hasActiveToolCall && !userOverride) {
+ if (hasActiveToolCall && !userOverride && !suppressAutoExpand) {
setShouldRenderBody(true);
setIsExpanded(true);
}
- }, [hasActiveToolCall, userOverride]);
+ }, [hasActiveToolCall, userOverride, suppressAutoExpand]);
return (
<div className="mb-2 mt-1" ref={rootRef}>
diff --git a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
index 0958825d8e..4bb8089aba 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ContentParts.test.tsx
@@ -708,7 +708,11 @@ describe('ContentParts — settled content identity across compaction', () => {
expect(phaseNode).toHaveAttribute('data-animate-entrance', 'false');
});
- it('remounts and replays the phase entrance without the stamp (regression control)', () => {
+ /** When the stamp cannot pair the two arrays every index-derived key
+ * shifts and the phase group remounts — but its label text was already on
+ * screen, so the remounted card must mount settled instead of replaying
+ * the fold over content the reader already watched fold. */
+ it('remounts without replaying the phase entrance when the settle re-keys the content', () => {
const { rerender } = renderStreaming();
const phaseNode = screen.getByTestId('activity-phase-group');
@@ -716,6 +720,180 @@ describe('ContentParts — settled content identity across compaction', () => {
const settledPhase = screen.getByTestId('activity-phase-group');
expect(settledPhase).not.toBe(phaseNode);
- expect(settledPhase).toHaveAttribute('data-animate-entrance', 'true');
+ expect(settledPhase).toHaveAttribute('data-animate-entrance', 'false');
+ });
+
+ /** Identical summaries are legitimate across phases of one run. A second
+ * marker with an already-seen text is a grown occurrence count, not a
+ * re-key of the first — only the newcomer animates. */
+ it('animates a second phase that repeats an earlier label text', () => {
+ const repeatedPhase = (index: number, bounds: { start: number; end: number }) =>
+ ({
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: 'Completed the activity phase',
+ activity_label_type: 'phase',
+ activity_start_index: bounds.start,
+ activity_end_index: bounds.end,
+ activity_count: 1,
+ pending: false,
+ streamedIndex: index,
+ }) as unknown as TMessageContentParts;
+ const { rerender } = render(
+ <ContentParts
+ {...baseProps}
+ content={[toolPart, repeatedPhase(1, { start: 0, end: 1 })]}
+ isLast
+ isSubmitting
+ isLatestMessage
+ />,
+ );
+
+ rerender(
+ <ContentParts
+ {...baseProps}
+ content={[
+ toolPart,
+ repeatedPhase(1, { start: 0, end: 1 }),
+ toolPart,
+ repeatedPhase(3, { start: 2, end: 3 }),
+ ]}
+ isLast
+ isSubmitting
+ isLatestMessage
+ />,
+ );
+
+ const phases = screen.getAllByTestId('activity-phase-group');
+ expect(phases).toHaveLength(2);
+ expect(phases[0]).toHaveAttribute('data-animate-entrance', 'false');
+ expect(phases[1]).toHaveAttribute('data-animate-entrance', 'true');
+ });
+
+ /** Concurrent fills can resolve out of order: a later-index marker
+ * renders first, then an earlier reserved marker fills with an identical
+ * summary. No previously rendered key vanished, so key identity stays
+ * authoritative and the newly filled earlier marker still animates. */
+ it('animates an earlier marker that fills out of order behind a same-text twin', () => {
+ const twinPhase = (bounds: { start: number; end: number }) =>
+ ({
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: 'Completed the activity phase',
+ activity_label_type: 'phase',
+ activity_start_index: bounds.start,
+ activity_end_index: bounds.end,
+ activity_count: 1,
+ pending: false,
+ }) as unknown as TMessageContentParts;
+ const pendingReservation = {
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: '',
+ activity_label_type: 'phase',
+ activity_start_index: 0,
+ pending: true,
+ } as unknown as TMessageContentParts;
+ const { rerender } = render(
+ <ContentParts
+ {...baseProps}
+ content={[toolPart, pendingReservation, toolPart, twinPhase({ start: 2, end: 3 })]}
+ isLast
+ isSubmitting
+ isLatestMessage
+ />,
+ );
+
+ rerender(
+ <ContentParts
+ {...baseProps}
+ content={[
+ toolPart,
+ twinPhase({ start: 0, end: 1 }),
+ toolPart,
+ twinPhase({ start: 2, end: 3 }),
+ ]}
+ isLast
+ isSubmitting
+ isLatestMessage
+ />,
+ );
+
+ const phases = screen.getAllByTestId('activity-phase-group');
+ expect(phases).toHaveLength(2);
+ expect(phases[0]).toHaveAttribute('data-animate-entrance', 'true');
+ expect(phases[1]).toHaveAttribute('data-animate-entrance', 'false');
+ });
+
+ /** A settle can re-key every existing marker AND land a new same-text
+ * phase in the same commit. Occurrences pair by position: the re-keyed
+ * first and second stay settled; only the third — past the previously
+ * rendered count — animates. */
+ it('animates only the new occurrence when a re-key lands with a repeated label', () => {
+ const repeatedPhase = (bounds: { start: number; end: number }) =>
+ ({
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: 'Completed the activity phase',
+ activity_label_type: 'phase',
+ activity_start_index: bounds.start,
+ activity_end_index: bounds.end,
+ activity_count: 1,
+ pending: false,
+ }) as unknown as TMessageContentParts;
+ const { rerender } = render(
+ <ContentParts
+ {...baseProps}
+ content={[
+ toolPart,
+ repeatedPhase({ start: 0, end: 1 }),
+ toolPart,
+ repeatedPhase({ start: 2, end: 3 }),
+ ]}
+ isLast
+ isSubmitting
+ isLatestMessage
+ />,
+ );
+
+ rerender(
+ <ContentParts
+ {...baseProps}
+ content={[
+ toolPart,
+ toolPart,
+ repeatedPhase({ start: 0, end: 2 }),
+ toolPart,
+ repeatedPhase({ start: 3, end: 4 }),
+ toolPart,
+ repeatedPhase({ start: 5, end: 6 }),
+ ]}
+ isLast
+ />,
+ );
+
+ const phases = screen.getAllByTestId('activity-phase-group');
+ expect(phases).toHaveLength(3);
+ expect(phases[0]).toHaveAttribute('data-animate-entrance', 'false');
+ expect(phases[1]).toHaveAttribute('data-animate-entrance', 'false');
+ expect(phases[2]).toHaveAttribute('data-animate-entrance', 'true');
+ });
+
+ it('still animates a phase whose label first appears at settle', () => {
+ const { rerender } = renderStreaming();
+
+ const lateLabel = {
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: 'Wrote the final summary',
+ activity_label_type: 'phase',
+ activity_start_index: 0,
+ activity_end_index: 2,
+ activity_count: 1,
+ pending: false,
+ } as unknown as TMessageContentParts;
+ rerender(
+ <ContentParts {...baseProps} content={[toolPart, batchLabel, answer, lateLabel]} isLast />,
+ );
+
+ expect(screen.getByTestId('activity-phase-group')).toHaveAttribute(
+ 'data-animate-entrance',
+ 'true',
+ );
});
});
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 2e916958be..147988a6b2 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
@@ -253,6 +253,65 @@ describe('ToolCallGroup image hoisting', () => {
expect(screen.getByTestId('inner-0')).toBeInTheDocument();
});
+ /** A remount into a completed phase card must not flash open and collapse
+ * again while the parent entrance fold is playing — the phase summary
+ * already speaks for this activity. */
+ it('mounts collapsed inside a completed phase even while a tool is still active', () => {
+ const voidToolParts = [{ part: makePart('t1', '', 'update_settings'), idx: 0 }];
+ const labelPart = {
+ part: {
+ type: ContentTypes.ACTIVITY_LABEL,
+ [ContentTypes.ACTIVITY_LABEL]: '',
+ pending: true,
+ } as unknown as TMessageContentParts,
+ idx: 1,
+ };
+
+ renderGroup({
+ ...baseProps,
+ parts: voidToolParts,
+ lastContentIdx: 1,
+ labelPart,
+ isSubmitting: true,
+ withinActivityPhase: true,
+ });
+
+ expect(screen.queryByTestId('inner-0')).not.toBeInTheDocument();
+ expect(screen.getByRole('button')).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ /** A phase can resolve while an approval inside it still blocks the run
+ * (see ActivityPhaseGroup's pending-approval retention) — the remounted
+ * group must keep the actionable card mounted, not bury it behind a
+ * second collapsed disclosure. */
+ it('keeps a pending approval expanded inside a completed phase', () => {
+ renderGroup({
+ ...baseProps,
+ parts: [
+ { part: makeApprovalPart('t1'), idx: 0 },
+ { part: makeApprovalPart('t2'), idx: 1 },
+ ],
+ isSubmitting: true,
+ withinActivityPhase: true,
+ });
+
+ expect(screen.getByRole('button', { name: 'Used 2 tools' })).toHaveAttribute(
+ 'aria-expanded',
+ 'true',
+ );
+ expect(screen.getByTestId('inner-0')).toBeInTheDocument();
+ expect(screen.getByTestId('inner-1')).toBeInTheDocument();
+ });
+
+ it('still expands on user toggle inside a completed phase', () => {
+ renderGroup({ ...baseProps, withinActivityPhase: true });
+
+ fireEvent.click(screen.getByRole('button', { name: 'Used 2 tools' }));
+
+ expect(screen.getByTestId('inner-0')).toBeInTheDocument();
+ expect(screen.getByTestId('inner-1')).toBeInTheDocument();
+ });
+
it('does not render tool bodies for an initially collapsed large completed group', () => {
const largeParts = Array.from({ length: 59 }, (_, idx) => ({
part: makePart(`t${idx}`),