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: Stop the Live Activity Row From Flashing Open on Code Calls and Thoughts (#16145)

Danny Aviladdd8d78d1d76
diff --git a/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx b/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx
index dfae90a0c1..341d6c151f 100644
--- a/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx
+++ b/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx
@@ -1,7 +1,8 @@
import { memo, useId, useCallback, useEffect, useMemo, useRef, useState } from 'react';
+import { useAtomValue } from 'jotai';
import { Button } from '@librechat/client';
import { ContentTypes } from 'librechat-data-provider';
-import { Check, ChevronDown, TriangleAlert } from 'lucide-react';
+import { Check, Lightbulb, ChevronDown, TriangleAlert } from 'lucide-react';
import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';
import type { CSSProperties, ReactNode } from 'react';
import {
@@ -18,6 +19,7 @@ import { useMCPIconMap, useMCPServerNames } from '~/hooks/MCP';
import { getActivityLabelText } from '~/utils/activityLabels';
import { getOutcomeStatus, summarizeSpan } from './outcome';
import { ROW_GLYPH_SLOT, TOOL_ROW_CLASSES } from './rows';
+import { sandboxStartingByToolCallId } from '~/store';
import { StackedToolIcons } from './ToolOutput';
import { getSourceDomains } from './sources';
import { mapAttachments } from '~/utils/map';
@@ -266,7 +268,17 @@ function LivePhaseHeader({
() => getLiveActivity(parts, localize, mcpServerNames, attachmentsById),
[parts, localize, mcpServerNames, attachmentsById],
);
- const { text, source } = activity;
+ /** A code card names its sandbox startup from events outside the content
+ * array. The row reads the same signal for its newest call, so the span
+ * never has to unfold for the card to say it. */
+ const sandboxStarting = useAtomValue(
+ sandboxStartingByToolCallId(activity.pendingToolCallId ?? ''),
+ );
+ const text =
+ sandboxStarting && activity.pendingToolCallId != null
+ ? localize('com_ui_sandbox_starting')
+ : activity.text;
+ const { source } = activity;
const line = useMemo(() => ({ text, source }), [text, source]);
const painted = useThrottledValue(line, LIVE_ACTIVITY_THROTTLE_MS);
const iconKey = activity.iconNames.join('|');
@@ -313,16 +325,28 @@ function LivePhaseHeader({
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>
+ {iconNames.length === 0 ? (
+ /** A span that is only reasoning so far has no tool to show; it takes
+ * the glyph the reasoning row itself uses. */
+ <span
+ className={cn(ROW_GLYPH_SLOT, 'animate-pulse text-text-primary')}
+ aria-hidden="true"
+ data-testid="live-phase-thinking"
+ >
+ <Lightbulb size={14} />
+ </span>
+ ) : (
+ <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}
@@ -354,6 +378,7 @@ export default function ActivityPhaseGroup({
hasPendingApproval = false,
liveParts,
spanParts,
+ onExpansionChange,
}: {
labelPart: ActivityPhasePart;
children: ReactNode;
@@ -374,6 +399,7 @@ export default function ActivityPhaseGroup({
liveParts?: ReadonlyArray<TMessageContentParts | undefined>;
/** The span's parts once settled, for the header's icon stack. */
spanParts?: ReadonlyArray<TMessageContentParts | undefined>;
+ onExpansionChange?: (expanded: boolean) => void;
}) {
const isLive = liveParts != null;
const label = getActivityLabelText(labelPart);
@@ -470,8 +496,9 @@ export default function ActivityPhaseGroup({
cancelEntranceRef.current = null;
mountBody();
setIsSettled(true);
- setIsExpanded((expanded) => !expanded);
- }, [mountBody]);
+ onExpansionChange?.(!isExpanded);
+ setIsExpanded(!isExpanded);
+ }, [mountBody, isExpanded, onExpansionChange]);
/** Only the folding entrance drives the header off its natural height.
* History and reduced-motion render the plain, unstyled row. */
diff --git a/client/src/components/Chat/Messages/Content/ContentParts.tsx b/client/src/components/Chat/Messages/Content/ContentParts.tsx
index 8a72411bbe..cf7a27bbb4 100644
--- a/client/src/components/Chat/Messages/Content/ContentParts.tsx
+++ b/client/src/components/Chat/Messages/Content/ContentParts.tsx
@@ -1,4 +1,5 @@
-import { memo, useRef, useMemo, useEffect, useCallback, Fragment } from 'react';
+import { memo, useRef, useMemo, useEffect, useCallback, useContext, Fragment } from 'react';
+import { useStore } from 'jotai';
import { ContentTypes } from 'librechat-data-provider';
import type {
TMessageContentParts,
@@ -9,6 +10,7 @@ import type {
import type { ReactNode, ReactElement } from 'react';
import type { ToolCallGroupExpansionState } from './ToolCallGroup';
import type { ActivityPhaseSegment } from '~/utils/activityLabels';
+import type { ReasoningDisclosures } from './disclosure';
import {
mapAttachments,
getPartKeyIndex,
@@ -24,6 +26,7 @@ import {
} from '~/utils/activityLabels';
import WorkspaceChanges, { partitionWorkspaceChanges } from './Parts/WorkspaceChanges';
import { ParallelContentRenderer, type PartWithIndex } from './ParallelContent';
+import { ReasoningDisclosureContext, reasoningDisclosure } from './disclosure';
import { MediaContext, MessageContext, SearchContext } from '~/Providers';
import MemoryArtifacts, { hasMemoryArtifacts } from './MemoryArtifacts';
import { hasParallelLanes, parallelLaneGroups } from '~/utils/lanes';
@@ -338,15 +341,29 @@ const ContentPartsBody = memo(function ContentPartsBody({
),
[attachmentMap, resolvedToolCallStepOwners],
);
+ const disclosureStore = useStore();
+ const reasoningDisclosures = useContext(ReasoningDisclosureContext);
const effectiveIsSubmitting = isLatestMessage ? isSubmitting : false;
const localToolGroupExpansionRef = useRef(new Map<string, ToolCallGroupExpansionState>());
const expansionState = toolGroupExpansionState ?? localToolGroupExpansionRef.current;
const fallbackScopeRef = useRef({ messageId, scope: 0 });
+ /** Keys a phase card has already rendered under, by its computed key and by
+ * where its span starts. See `stableCardKey`. */
+ const cardKeyAliasesRef = useRef(new Map<string, string>());
+ const cardScopeRef = useRef(0);
if (fallbackScopeRef.current.messageId !== messageId) {
if (!effectiveIsSubmitting) {
fallbackScopeRef.current.scope += 1;
expansionState.clear();
}
+ cardScopeRef.current += 1;
+ /** Positions belong to one response, even when the next sibling is live.
+ * Tool-backed aliases still bridge placeholder hydration and finalization. */
+ for (const alias of cardKeyAliasesRef.current.keys()) {
+ if (alias.startsWith('start:') || alias.startsWith('key:fallback:')) {
+ cardKeyAliasesRef.current.delete(alias);
+ }
+ }
fallbackScopeRef.current.messageId = messageId;
}
const fallbackScope = fallbackScopeRef.current.scope;
@@ -796,7 +813,24 @@ const ContentPartsBody = memo(function ContentPartsBody({
const position = segment.hasContent
? segmentKeyIndex(segment)
: getPartKeyIndex(segment.labelPart, segment.labelIndex);
- return `fallback:${fallbackScope}:${position}`;
+ return `fallback:${cardScopeRef.current}:${position}`;
+ };
+ /** A live card can exist before its first tool call — a span that is only
+ * a thought so far has no provider id, so `phaseCardKey` gives it the
+ * positional fallback, and would hand it a different, tool-anchored key
+ * the moment a call is appended. That is a remount mid-thought: the row
+ * blinks and a reader who opened it is shut out. The first key a span
+ * renders under is therefore kept, and remembered both by where the span
+ * starts and by the key it would otherwise move to, so the summary that
+ * later claims the same calls from a different start still lands on it. */
+ const stableCardKey = (segment: Extract<ActivityPhaseSegment, { type: 'phase' }>): string => {
+ const computed = phaseCardKey(segment);
+ const start = absoluteIndexAt(segment.contentIndices[0] ?? segment.startIndex);
+ const aliases = cardKeyAliasesRef.current;
+ const key = aliases.get(`key:${computed}`) ?? aliases.get(`start:${start}`) ?? computed;
+ aliases.set(`key:${computed}`, key);
+ aliases.set(`start:${start}`, key);
+ return key;
};
/** Exactly one thing may hold the streaming cursor. A card carries it
* below its own header whenever the tail of the run sits inside its
@@ -893,7 +927,7 @@ const ContentPartsBody = memo(function ContentPartsBody({
* 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 = phaseCardKey(segment);
+ 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.
@@ -954,6 +988,24 @@ const ContentPartsBody = memo(function ContentPartsBody({
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={
@@ -1122,7 +1174,14 @@ const ContentPartsBody = memo(function ContentPartsBody({
});
const ContentParts = memo(function ContentParts(props: ContentPartsProps) {
- const { attachments } = props;
+ const { attachments, messageId } = props;
+ const reasoningState = useRef<{ messageId: string; disclosures: ReasoningDisclosures } | null>(
+ null,
+ );
+ if (reasoningState.current?.messageId !== messageId) {
+ reasoningState.current = { messageId, disclosures: new Map() };
+ }
+ const reasoningDisclosures = reasoningState.current.disclosures;
/** Published once for the whole message so every markdown block below —
* including the ones nested inside phase cards — resolves a bare
* `![DTI](5_dti.png)` against the files this turn actually produced.
@@ -1140,7 +1199,9 @@ const ContentParts = memo(function ContentParts(props: ContentPartsProps) {
const media = useMemo(() => ({ attachmentsByName }), [attachmentsByName]);
return (
<MediaContext.Provider value={media}>
- <ContentPartsBody {...props} />
+ <ReasoningDisclosureContext.Provider value={reasoningDisclosures}>
+ <ContentPartsBody {...props} />
+ </ReasoningDisclosureContext.Provider>
</MediaContext.Provider>
);
});
diff --git a/client/src/components/Chat/Messages/Content/Part.tsx b/client/src/components/Chat/Messages/Content/Part.tsx
index 9cf2bf13cb..5948a1a992 100644
--- a/client/src/components/Chat/Messages/Content/Part.tsx
+++ b/client/src/components/Chat/Messages/Content/Part.tsx
@@ -25,10 +25,16 @@ import {
SubagentCall,
SteerPart,
} from './Parts';
-import { getCachedPreview, getActivityLabelPart, getActivityLabelText } from '~/utils';
+import {
+ getCachedPreview,
+ getActivityLabelPart,
+ getActivityLabelText,
+ getPartKeyIndex,
+} from '~/utils';
import { getAskUserQuestionPart } from '~/utils/approval';
import AskUserQuestionCall from './AskUserQuestionCall';
import { isBashProgrammaticToolCall } from './routing';
+import { useMessageContext } from '~/Providers';
import { ErrorMessage } from './MessageContent';
import AskUserQuestion from './AskUserQuestion';
import RetrievalCall from './RetrievalCall';
@@ -61,6 +67,7 @@ const Part = memo(function Part({
hideAttachments,
onToolExpand,
}: PartProps) {
+ const { partIndex } = useMessageContext();
if (!part) {
return null;
}
@@ -153,6 +160,7 @@ const Part = memo(function Part({
}
return (
<Reasoning
+ partKeyIndex={getPartKeyIndex(part, partIndex ?? 0)}
reasoning={reasoning}
isLast={isLast ?? false}
reasoningLabel={part.reasoning_label}
diff --git a/client/src/components/Chat/Messages/Content/Parts/BashCall.tsx b/client/src/components/Chat/Messages/Content/Parts/BashCall.tsx
index 47312563d0..a253576a2e 100644
--- a/client/src/components/Chat/Messages/Content/Parts/BashCall.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/BashCall.tsx
@@ -1,6 +1,6 @@
import { useMemo, useRef, useState, useCallback, useEffect } from 'react';
import copy from 'copy-to-clipboard';
-import { useRecoilValue } from 'recoil';
+import { useAtomValue } from 'jotai';
import type { TAttachment, PartMetadata } from 'librechat-data-provider';
import { parseBackgroundHandle, splitBackgroundAttachments } from './handle';
import ProgressText from '~/components/Chat/Messages/Content/ProgressText';
@@ -52,7 +52,7 @@ export default function BashCall({
const localize = useLocalize();
const command = useMemo(() => parseJsonField(args, commandField), [args, commandField]);
const isWritingCommand = !command || !areToolCallArgsComplete(args);
- const sandboxStarting = useRecoilValue(sandboxStartingByToolCallId(toolCallId ?? ''));
+ const sandboxStarting = useAtomValue(sandboxStartingByToolCallId(toolCallId ?? ''));
const outputHasError = useMemo(() => ERROR_PATTERNS.test(output), [output]);
/** A backgrounded call's persisted output stays the dispatch handle until
diff --git a/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx b/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx
index 52090262c3..e6fbcd37b6 100644
--- a/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/ExecuteCode.tsx
@@ -1,5 +1,5 @@
import { useMemo } from 'react';
-import { useRecoilValue } from 'recoil';
+import { useAtomValue } from 'jotai';
import { SquareTerminal } from 'lucide-react';
import type { TAttachment, PartMetadata } from 'librechat-data-provider';
import { parseBackgroundHandle, splitBackgroundAttachments } from './handle';
@@ -90,7 +90,7 @@ export default function ExecuteCode({
/** Model-authored live label, streamed as the first args key; persists as
* the settled label (completion is a UI state, not a tense change). */
const intent = useToolCallIntent(args);
- const sandboxStarting = useRecoilValue(sandboxStartingByToolCallId(toolCallId ?? ''));
+ const sandboxStarting = useAtomValue(sandboxStartingByToolCallId(toolCallId ?? ''));
const outputHasError = useMemo(() => ERROR_PATTERNS.test(output), [output]);
/** A backgrounded call's persisted output stays the dispatch handle until
diff --git a/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx b/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx
index 41162fe41a..8565ea28a0 100644
--- a/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx
@@ -1,6 +1,6 @@
import { memo, useMemo, useState, useEffect, useCallback, useRef, useId } from 'react';
import copy from 'copy-to-clipboard';
-import { useAtomValue } from 'jotai';
+import { useAtom, useAtomValue } from 'jotai';
import { Lightbulb, ChevronDown } from 'lucide-react';
import { ContentTypes } from 'librechat-data-provider';
import { Button, disclosureChevronVariants } from '@librechat/client';
@@ -16,6 +16,7 @@ import { useLocalize, useExpandCollapse, useLazyCollapseBody } from '~/hooks';
import useSmoothStreaming from '~/hooks/Messages/useSmoothStreaming';
import CopyButton from '~/components/Messages/Content/CopyButton';
import { showThinkingAtom } from '~/store/showThinking';
+import { useReasoningDisclosure } from '../disclosure';
import { fontSizeAtom } from '~/store/fontSize';
import { useMessageContext } from '~/Providers';
import { ROW_GLYPH_SLOT } from '../rows';
@@ -108,6 +109,7 @@ const StreamingThoughtPeek = memo(({ text }: { text: string }) => {
StreamingThoughtPeek.displayName = 'StreamingThoughtPeek';
type ReasoningProps = {
+ partKeyIndex?: number;
reasoning: string;
isLast: boolean;
reasoningLabel?: string;
@@ -147,12 +149,14 @@ export const ReasoningMarker = memo(({ label }: { label?: string }) => {
ReasoningMarker.displayName = 'ReasoningMarker';
const Reasoning = memo((props: ReasoningProps) => {
- const { reasoning, isLast, reasoningLabel } = props;
+ const { reasoning, isLast, reasoningLabel, partKeyIndex = 0 } = props;
const contentId = useId();
const localize = useLocalize();
const showThinking = useAtomValue(showThinkingAtom);
const smoothStreaming = useSmoothStreaming();
- const [isExpanded, setIsExpanded] = useState(showThinking);
+ const [expansionOverride, setIsExpanded] = useAtom(useReasoningDisclosure(partKeyIndex));
+ const [defaultExpanded] = useState(showThinking);
+ const isExpanded = expansionOverride ?? defaultExpanded;
const [isBarVisible, setIsBarVisible] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
const { ref: headerRef, inViewport: headerInViewport } = useInViewport();
@@ -167,9 +171,9 @@ const Reasoning = memo((props: ReasoningProps) => {
(e: MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
mountBody();
- setIsExpanded((prev) => !prev);
+ setIsExpanded(!isExpanded);
},
- [mountBody],
+ [mountBody, isExpanded, setIsExpanded],
);
const handleFocus = useCallback(() => {
@@ -272,6 +276,7 @@ const Reasoning = memo((props: ReasoningProps) => {
Reasoning.displayName = 'Reasoning';
type ReasoningCompactProps = {
+ partKeyIndex?: number;
reasoning: string;
label: string;
/** The host's thoughts-visible preference, supplied by the group rather
@@ -298,11 +303,14 @@ export const ReasoningCompact = memo(
showThinking,
isAfterTool = false,
isStreaming = false,
+ partKeyIndex = 0,
}: ReasoningCompactProps) => {
const contentId = useId();
const localize = useLocalize();
const fontSize = useAtomValue(fontSizeAtom);
- const [isExpanded, setIsExpanded] = useState(showThinking);
+ const [expansionOverride, setIsExpanded] = useAtom(useReasoningDisclosure(partKeyIndex));
+ const [defaultExpanded] = useState(showThinking);
+ const isExpanded = expansionOverride ?? defaultExpanded;
const [isBarVisible, setIsBarVisible] = useState(false);
const [isCopied, setIsCopied] = useState(false);
const containerRef = useRef<HTMLDivElement>(null);
@@ -320,9 +328,9 @@ export const ReasoningCompact = memo(
(e: MouseEvent<HTMLButtonElement>) => {
e.preventDefault();
mountBody();
- setIsExpanded((prev) => !prev);
+ setIsExpanded(!isExpanded);
},
- [mountBody],
+ [mountBody, isExpanded, setIsExpanded],
);
const handleCopy = useCallback(() => {
diff --git a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
index 573a8f4e45..e247a03c1e 100644
--- a/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
+++ b/client/src/components/Chat/Messages/Content/ToolCallGroup.tsx
@@ -9,6 +9,7 @@ import type { ToolMeta } from './outcome';
import {
cn,
getToolDisplayLabel,
+ getPartKeyIndex,
hasPendingAuthInPart,
hasPendingApprovalInPart,
getBatchActivityLabelPart,
@@ -565,6 +566,7 @@ export default function ToolCallGroup({
return (
<ReasoningCompact
key={`reasoning-${idx}`}
+ partKeyIndex={getPartKeyIndex(part, idx)}
reasoning={reasoning}
label={label}
showThinking={showThinking}
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 25358086f2..e983feb192 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
@@ -1289,9 +1289,88 @@ describe('ContentParts — live activity fold', () => {
expect(screen.getByTestId('compact-reasoning')).toBeInTheDocument();
});
- it('leaves reasoning that has not reached a tool call on its own row', () => {
+ it('holds the block at one row from a thought through the calls that follow it', () => {
+ /** A reasoning model thinks, then calls. Rendering the thought as its own
+ * row gave it a multi-line peek that the first call then snapped shut — a
+ * jump up and back down on every step. The row count must not move. */
+ const thought = {
+ type: ContentTypes.THINK,
+ think: 'Planning the lookup.',
+ } as unknown as TMessageContentParts;
+ const { rerender } = renderContentParts({ ...liveProps, content: [thought] });
+ expect(screen.getAllByRole('button')).toHaveLength(1);
+ expect(liveHeader()).toHaveTextContent('Planning the lookup.');
+ expect(screen.queryByTestId('reasoning')).toBeNull();
+ expect(screen.getByTestId('live-phase-thinking')).toBeInTheDocument();
+
+ rerender(
+ <RecoilRoot>
+ <ContentParts {...liveProps} content={[thought, intentCall('t1', 'Reading the file')]} />
+ </RecoilRoot>,
+ );
+ expect(screen.getAllByRole('button')).toHaveLength(1);
+ expect(screen.queryByTestId('reasoning')).toBeNull();
+ });
+
+ it('keeps a row the reader opened on a thought open when the first tool call arrives', () => {
+ /** Reasoning-only, the card has no provider id to key on; gaining one must
+ * not remount it. */
+ const thought = {
+ type: ContentTypes.THINK,
+ think: 'Planning the lookup.',
+ } as unknown as TMessageContentParts;
+ const { rerender } = renderContentParts({ ...liveProps, content: [thought] });
+ const card = screen.getByTestId('activity-phase-card');
+ fireEvent.click(liveHeader());
+ expect(liveHeader()).toHaveAttribute('aria-expanded', 'true');
+
+ rerender(
+ <RecoilRoot>
+ <ContentParts {...liveProps} content={[thought, intentCall('t1', 'Reading the file')]} />
+ </RecoilRoot>,
+ );
+
+ expect(screen.getByTestId('activity-phase-card')).toBe(card);
+ expect(liveHeader()).toHaveAttribute('aria-expanded', 'true');
+ });
+
+ it('keeps a reasoning-led card open through the summary and the response finalizing', () => {
+ const thought = {
+ type: ContentTypes.THINK,
+ think: 'Planning the lookup.',
+ } as unknown as TMessageContentParts;
+ const calls = [makeMcpToolCall('t1'), makeMcpToolCall('t2')];
+ const frame = (props: {
+ content: TMessageContentParts[];
+ messageId?: string;
+ isSubmitting?: boolean;
+ }) => (
+ <RecoilRoot>
+ <ContentParts {...liveProps} {...props} />
+ </RecoilRoot>
+ );
+ const { rerender } = render(frame({ content: [thought] }));
+ rerender(frame({ content: [thought, ...calls] }));
+ fireEvent.click(liveHeader());
+ const card = screen.getByTestId('activity-phase-card');
+
+ const settled = [thought, ...calls, makePhasePart(0, 3, 'Fetched two images')];
+ rerender(frame({ content: settled }));
+ expect(screen.getByTestId('activity-phase-card')).toBe(card);
+
+ /** The message takes its server id in the same commit the run ends. */
+ rerender(frame({ content: settled, messageId: 'server-id', isSubmitting: false }));
+ expect(screen.getByTestId('activity-phase-card')).toBe(card);
+ expect(screen.getByRole('button', { name: 'Fetched two images' })).toHaveAttribute(
+ 'aria-expanded',
+ 'true',
+ );
+ });
+
+ it('keeps a thought on its own open row for a reader who opens thinking by default', () => {
renderContentParts({
...liveProps,
+ showThinking: true,
content: [
{ type: ContentTypes.THINK, think: 'Planning.' } as unknown as TMessageContentParts,
],
diff --git a/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx
index 453b46ec19..394e7acb66 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx
@@ -1,5 +1,6 @@
import React from 'react';
-import { RecoilRoot, useSetRecoilState } from 'recoil';
+import { RecoilRoot } from 'recoil';
+import { Provider, useSetAtom } from 'jotai';
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';
@@ -623,23 +624,25 @@ describe('live activity hardening transitions', () => {
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}
- />
+ <Provider>
+ {extra}
+ <ContentParts
+ content={content}
+ messageId="m1"
+ conversationId="c1"
+ isCreatedByUser={false}
+ isLast
+ isLatestMessage
+ isSubmitting
+ showThinking={false}
+ />
+ </Provider>
</RecoilRoot>
</QueryClientProvider>
);
function SandboxEvent() {
- const setStarting = useSetRecoilState(sandboxStartingByToolCallId('sandbox-call'));
+ const setStarting = useSetAtom(sandboxStartingByToolCallId('sandbox-call'));
return <button onClick={() => setStarting(true)}>{'Start sandbox'}</button>;
}
@@ -648,17 +651,48 @@ describe('live activity hardening transitions', () => {
[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) => {
+ ])('names %s sandbox startup on the row without unfolding the span', (name, args) => {
+ /** Unfolding here to let the card say "Starting sandbox" opened the WHOLE
+ * span for as long as the call ran and shut it when output landed — on
+ * every call of a run whose model did not put `intent` first. The row
+ * reads the same sandbox signal instead, and stays one card throughout. */
jest.useFakeTimers();
const call = { name, args, output: '' };
const view = render(frame([toPart(call, 'sandbox-call')], <SandboxEvent />));
- expect(screen.queryByTestId('activity-phase-card')).toBeNull();
+ const card = screen.getByTestId('activity-phase-card');
+ expect(screen.queryByTestId('tool-call')).toBeNull();
+
fireEvent.click(screen.getByRole('button', { name: 'Start sandbox' }));
- expect(view.container).toHaveTextContent('Starting sandbox');
+ act(() => {
+ jest.advanceTimersByTime(500);
+ });
+ expect(card).toHaveTextContent('Starting sandbox');
+
view.rerender(
frame([toPart({ ...call, output: 'ok', runStepStatus: 'completed' }, 'sandbox-call')]),
);
- expect(screen.getByTestId('activity-phase-card')).toBeInTheDocument();
+ expect(screen.getByTestId('activity-phase-card')).toBe(card);
+ });
+
+ it('holds one card across a run of code calls whose intent is not the first key', () => {
+ /** The shape of the run that flashed: `{"command":…,"intent":…}`, which the
+ * anchored intent reader rejects, so each call was "a code call with no
+ * intent" from the moment its args completed until its output landed. */
+ const args = '{"command":"gh run view 1","intent":"Viewing the failing run"}';
+ const writing = toPart({ name: Tools.bash_tool, args: '{"command":"gh run', output: '' }, 'b1');
+ const dispatched = toPart({ name: Tools.bash_tool, args, output: '' }, 'b1');
+ const finished = toPart({ name: Tools.bash_tool, args, output: 'ok' }, 'b1');
+ const view = render(frame([writing]));
+ const card = screen.getByTestId('activity-phase-card');
+ for (const content of [
+ [dispatched],
+ [finished],
+ [finished, toPart({ name: Tools.bash_tool, args, output: '' }, 'b2')],
+ ]) {
+ view.rerender(frame(content));
+ expect(screen.getByTestId('activity-phase-card')).toBe(card);
+ expect(screen.queryByTestId('tool-call')).toBeNull();
+ }
});
it('folds an early code delta and keeps folding once its intent arrives', () => {
@@ -848,3 +882,128 @@ describe('live activity hardening transitions', () => {
expect(announcer).toHaveTextContent('Completed lookup');
});
});
+
+describe('live disclosure ownership', () => {
+ const thought: TMessageContentParts = { type: ContentTypes.THINK, think: 'Planning the lookup.' };
+ const queryClient = new QueryClient();
+ const frame = (content: TMessageContentParts[], messageId = 'm1', isSubmitting = true) => (
+ <QueryClientProvider client={queryClient}>
+ <RecoilRoot>
+ <ContentParts
+ content={content}
+ messageId={messageId}
+ conversationId="c1"
+ isCreatedByUser={false}
+ isLast
+ isLatestMessage
+ isSubmitting={isSubmitting}
+ showThinking={false}
+ foldLiveActivity
+ />
+ </RecoilRoot>
+ </QueryClientProvider>
+ );
+
+ const originalObserver = global.IntersectionObserver;
+ afterEach(() => {
+ global.IntersectionObserver = originalObserver;
+ });
+ beforeEach(() => {
+ const observer: IntersectionObserver = {
+ root: null,
+ rootMargin: '',
+ thresholds: [],
+ observe: jest.fn(),
+ unobserve: jest.fn(),
+ disconnect: jest.fn(),
+ takeRecords: () => [],
+ };
+ global.IntersectionObserver = jest.fn(() => observer);
+ });
+
+ it.each(['answer', 'stop'] as const)(
+ 'keeps opened reasoning visible when the run reaches %s without tools',
+ (transition) => {
+ const view = render(frame([thought]));
+ fireEvent.click(within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0]);
+ expect(
+ view.container.querySelector('.group\\/reasoning button[aria-expanded]'),
+ ).toHaveAttribute('aria-expanded', 'true');
+
+ const content: TMessageContentParts[] =
+ transition === 'answer'
+ ? [thought, { type: ContentTypes.TEXT, text: 'Here is the answer.' }]
+ : [thought];
+ view.rerender(frame(content, 'm1', transition === 'answer'));
+ expect(screen.getByRole('button', { name: /^Thoughts$/i })).toHaveAttribute(
+ 'aria-expanded',
+ 'true',
+ );
+ },
+ );
+
+ it('preserves an explicitly closed thought when the answer starts', () => {
+ const view = render(frame([thought]));
+ fireEvent.click(within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0]);
+ const reasoningHeader = view.container.querySelector(
+ '.group\\/reasoning button[aria-expanded]',
+ );
+ expect(reasoningHeader).not.toBeNull();
+ fireEvent.click(reasoningHeader!);
+ view.rerender(frame([thought, { type: ContentTypes.TEXT, text: 'Here is the answer.' }]));
+ expect(screen.getByRole('button', { name: /^Thoughts$/i })).toHaveAttribute(
+ 'aria-expanded',
+ 'false',
+ );
+ });
+
+ it.each(['tool', 'thought'] as const)(
+ 'isolates a new streaming sibling beginning with a %s',
+ (kind) => {
+ const phase: TMessageContentParts = {
+ type: ContentTypes.ACTIVITY_LABEL,
+ activity_label: 'Looked up results',
+ activity_label_type: 'phase',
+ activity_start_index: 0,
+ activity_end_index: 1,
+ };
+ const view = render(
+ frame(
+ [toPart({ name: 'lookup', output: 'done' }, 'old-tool'), phase],
+ 'old-message',
+ false,
+ ),
+ );
+ fireEvent.click(within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0]);
+ view.rerender(
+ frame(
+ [kind === 'tool' ? toPart({ name: 'lookup', output: '' }, 'new-tool') : thought],
+ 'new-message',
+ ),
+ );
+ expect(
+ within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0],
+ ).toHaveAttribute('aria-expanded', 'false');
+ },
+ );
+
+ it('isolates two reasoning-only streaming siblings at the same position', () => {
+ const view = render(frame([thought], 'old-message'));
+ fireEvent.click(within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0]);
+ view.rerender(frame([thought], 'new-message'));
+ expect(
+ within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0],
+ ).toHaveAttribute('aria-expanded', 'false');
+ });
+
+ it('keeps a reasoning-led card open when its tool-backed message hydrates mid-stream', () => {
+ const view = render(frame([thought]));
+ fireEvent.click(within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0]);
+ const content = [thought, toPart({ name: 'lookup', output: '' }, 'tool')];
+ view.rerender(frame(content));
+ const card = screen.getByTestId('activity-phase-card');
+ view.rerender(frame(content, 'server-id'));
+ expect(screen.getByTestId('activity-phase-card')).toBe(card);
+ expect(within(card).getAllByRole('button')[0]).toHaveAttribute('aria-expanded', 'true');
+ });
+});
diff --git a/client/src/components/Chat/Messages/Content/__tests__/Part.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/Part.test.tsx
index ecac2322e0..7ad9f1b729 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/Part.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/Part.test.tsx
@@ -68,6 +68,7 @@ jest.mock('../Image', () => ({
}));
jest.mock('~/utils', () => ({
+ getPartKeyIndex: jest.requireActual('~/utils').getPartKeyIndex,
getCachedPreview: jest.fn(),
}));
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 c8dce56f0c..726f047700 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/ToolCallGroup.test.tsx
@@ -121,6 +121,7 @@ jest.mock('~/utils/approval', () => ({
}));
jest.mock('~/utils', () => ({
+ getPartKeyIndex: jest.requireActual('~/utils').getPartKeyIndex,
cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),
getToolDisplayLabel: (name: string, _localize: unknown, knownServerNames?: readonly string[]) => {
const configuredServer = knownServerNames?.find((server) => name.endsWith(`_mcp_${server}`));
diff --git a/client/src/components/Chat/Messages/Content/disclosure.ts b/client/src/components/Chat/Messages/Content/disclosure.ts
index 517a7ab4c0..e4a546cc32 100644
--- a/client/src/components/Chat/Messages/Content/disclosure.ts
+++ b/client/src/components/Chat/Messages/Content/disclosure.ts
@@ -1,3 +1,32 @@
+import { createContext, useContext, useMemo } from 'react';
+import { atom } from 'jotai';
+import type { PrimitiveAtom } from 'jotai';
+
+export type ReasoningDisclosures = Map<number, PrimitiveAtom<boolean | undefined>>;
+
+/** Owned by one message, above the layouts that can move its reasoning. */
+export const ReasoningDisclosureContext = createContext<ReasoningDisclosures | null>(null);
+
+export function reasoningDisclosure(disclosures: ReasoningDisclosures, index: number) {
+ let disclosure = disclosures.get(index);
+ if (disclosure == null) {
+ disclosure = atom<boolean | undefined>(undefined);
+ disclosures.set(index, disclosure);
+ }
+ return disclosure;
+}
+
+export function useReasoningDisclosure(index: number) {
+ const disclosures = useContext(ReasoningDisclosureContext);
+ return useMemo(
+ () =>
+ disclosures == null
+ ? atom<boolean | undefined>(undefined)
+ : reasoningDisclosure(disclosures, index),
+ [disclosures, index],
+ );
+}
+
/** Panel spacing is genuine feature layout, so it stays here. The chevron
* appearance lives in `@librechat/client` as `disclosureChevronVariants`. */
export const toolPanelSpacingClassName = 'mb-2 mt-0';
diff --git a/client/src/components/Chat/Messages/Content/live.ts b/client/src/components/Chat/Messages/Content/live.ts
index 886b6d70e6..4ed1917626 100644
--- a/client/src/components/Chat/Messages/Content/live.ts
+++ b/client/src/components/Chat/Messages/Content/live.ts
@@ -12,7 +12,6 @@ import { getBatchActivityLabelPart, getActivityLabelText } from '~/utils/activit
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';
@@ -30,6 +29,11 @@ export type LiveActivity = {
* transition for a genuinely different line. */
source: string;
iconNames: string[];
+ /** Set while the newest line is a call still running with no intent of its
+ * own. Code cards name their startup from sandbox events that live outside
+ * the content array; the header reads the same signal for this call rather
+ * than unfolding the span to let the card say it. */
+ pendingToolCallId?: string;
/** Failed and stopped calls anywhere in the span, not just the newest line. */
outcome: SpanOutcome;
};
@@ -170,26 +174,7 @@ 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)
- );
+ return needsReader(part) || isLiveSubagent(part);
}
/** Icons the header stack can show. */
@@ -226,12 +211,31 @@ export function getSpanIconNames(parts: ReadonlyArray<TMessageContentParts | und
return Array.from(icons).reverse();
}
+/** A call still running whose line is only the generic one: no intent, no
+ * verdict, no background state. */
+function isAwaitingStartup(
+ part: TMessageContentParts,
+ toolCall: LiveToolCall,
+ span: SpanSummary,
+): boolean {
+ const meta = span.metaOf(part);
+ return (
+ toolCall.id != null &&
+ meta != null &&
+ !meta.hasOutput &&
+ !meta.failed &&
+ !meta.cancelled &&
+ meta.background == null &&
+ getToolCallIntent(toolCall.args) == null
+ );
+}
+
function newestLine(
parts: ReadonlyArray<TMessageContentParts | undefined>,
localize: Localize,
serverNames: readonly string[],
span: SpanSummary,
-): Pick<LiveActivity, 'text' | 'source'> {
+): Pick<LiveActivity, 'text' | 'source' | 'pendingToolCallId'> {
for (let position = parts.length - 1; position >= 0; position -= 1) {
const part = parts[position];
if (part == null) {
@@ -276,6 +280,7 @@ function newestLine(
* identity: a second call reusing an id is a new line, not the first
* one still growing. */
source: `tool:${toolCall.id ?? ''}:${position}`,
+ ...(isAwaitingStartup(part, toolCall, span) && { pendingToolCallId: toolCall.id }),
};
}
}
diff --git a/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts b/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
index 19bae33e92..7e0df6cdaf 100644
--- a/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useStepHandler.spec.ts
@@ -1,5 +1,5 @@
import React from 'react';
-import { useStore } from 'jotai';
+import { useStore, useAtomValue } from 'jotai';
import { RecoilRoot, useRecoilCallback } from 'recoil';
import { renderHook, act } from '@testing-library/react';
import {
@@ -27,6 +27,7 @@ import {
} from '~/components/Chat/Subagents/state';
import { ptcTraceByToolCallId, ptcTraceKey, PTC_TRACE_MAX_ENTRIES } from '~/store/ptc';
import { resolveAskUserQuestionPart } from '~/utils/approval';
+import { sandboxStartingByToolCallId } from '~/store/sandbox';
import useStepHandler from '~/hooks/SSE/useStepHandler';
import { IsolatedAtomStore } from 'test/harness';
@@ -1878,6 +1879,64 @@ describe('useStepHandler', () => {
});
});
+ describe('sandbox startup state', () => {
+ const wrapper = ({ children }: React.PropsWithChildren) =>
+ React.createElement(RecoilRoot, null, React.createElement(IsolatedAtomStore, null, children));
+
+ it.each(['completed', 'cleanup'] as const)(
+ 'clears the Jotai startup signal on %s',
+ (terminal) => {
+ mockGetMessages.mockReturnValue([createResponseMessage()]);
+ const { result } = renderHook(
+ () => ({
+ ...useStepHandler(createHookParams()),
+ starting: useAtomValue(sandboxStartingByToolCallId('tool-call-1')),
+ }),
+ { wrapper },
+ );
+ const submission = createSubmission();
+ expect(result.current.starting).toBe(false);
+ act(() => {
+ result.current.stepHandler(
+ { event: StepEvents.ON_RUN_STEP, data: createToolCallRunStep() },
+ submission,
+ );
+ result.current.stepHandler(
+ { event: StepEvents.ON_SANDBOX_STARTING, data: { tool_call_id: 'tool-call-1' } },
+ submission,
+ );
+ });
+ expect(result.current.starting).toBe(true);
+ act(() => {
+ if (terminal === 'cleanup') {
+ result.current.clearStepMaps();
+ return;
+ }
+ result.current.stepHandler(
+ {
+ event: StepEvents.ON_RUN_STEP_COMPLETED,
+ data: {
+ result: {
+ id: 'step-tool-1',
+ index: 0,
+ tool_call: {
+ id: 'tool-call-1',
+ name: 'test_tool',
+ args: '{}',
+ output: 'done',
+ type: ToolCallTypes.TOOL_CALL,
+ },
+ } as Agents.ToolEndEvent,
+ },
+ },
+ submission,
+ );
+ });
+ expect(result.current.starting).toBe(false);
+ },
+ );
+ });
+
describe('on_run_step_completed event', () => {
it('should finalize tool call with output', () => {
const responseMessage = createResponseMessage();
diff --git a/client/src/hooks/SSE/useStepHandler.ts b/client/src/hooks/SSE/useStepHandler.ts
index 78f6894e09..7e70de8572 100644
--- a/client/src/hooks/SSE/useStepHandler.ts
+++ b/client/src/hooks/SSE/useStepHandler.ts
@@ -318,37 +318,32 @@ export default function useStepHandler({
/** Tool-call ids whose sandbox-starting atom is set, so completion can clear them. */
const knownSandboxAtomKeys = useRef(new Set<string>());
- const setSandboxStarting = useRecoilCallback(
- ({ set }) =>
- (toolCallId: string): void => {
- knownSandboxAtomKeys.current.add(toolCallId);
- set(sandboxStartingByToolCallId(toolCallId), true);
- },
- [],
+ const sandboxStore = useStore();
+ const setSandboxStarting = useCallback(
+ (toolCallId: string): void => {
+ knownSandboxAtomKeys.current.add(toolCallId);
+ sandboxStore.set(sandboxStartingByToolCallId(toolCallId), true);
+ },
+ [sandboxStore],
);
- const clearSandboxStarting = useRecoilCallback(
- ({ reset }) =>
- (toolCallId?: string | null): void => {
- if (!toolCallId || !knownSandboxAtomKeys.current.has(toolCallId)) {
- return;
- }
- knownSandboxAtomKeys.current.delete(toolCallId);
- reset(sandboxStartingByToolCallId(toolCallId));
- },
- [],
+ const clearSandboxStarting = useCallback(
+ (toolCallId?: string | null): void => {
+ if (!toolCallId || !knownSandboxAtomKeys.current.has(toolCallId)) {
+ return;
+ }
+ knownSandboxAtomKeys.current.delete(toolCallId);
+ sandboxStore.set(sandboxStartingByToolCallId(toolCallId), false);
+ },
+ [sandboxStore],
);
- const resetSandboxAtoms = useRecoilCallback(
- ({ reset }) =>
- (): void => {
- for (const toolCallId of knownSandboxAtomKeys.current) {
- reset(sandboxStartingByToolCallId(toolCallId));
- }
- knownSandboxAtomKeys.current.clear();
- },
- [],
- );
+ const resetSandboxAtoms = useCallback((): void => {
+ for (const toolCallId of knownSandboxAtomKeys.current) {
+ sandboxStore.set(sandboxStartingByToolCallId(toolCallId), false);
+ }
+ knownSandboxAtomKeys.current.clear();
+ }, [sandboxStore]);
/** PTC tool call ids with a live trace, so the atoms can be released. */
const knownPtcAtomKeys = useRef(new Set<string>());
diff --git a/client/src/store/sandbox.ts b/client/src/store/sandbox.ts
index 54232d90b3..30e7d8ad2a 100644
--- a/client/src/store/sandbox.ts
+++ b/client/src/store/sandbox.ts
@@ -1,4 +1,5 @@
-import { atomFamily } from 'recoil';
+import { atom } from 'jotai';
+import { atomFamily } from 'jotai/utils';
/**
* True while the backend reported the stateful code sandbox is cold-booting
@@ -7,7 +8,4 @@ import { atomFamily } from 'recoil';
* "starting sandbox" message while set. Cleared when the tool call's run
* step completes.
*/
-export const sandboxStartingByToolCallId = atomFamily<boolean, string>({
- key: 'sandboxStartingByToolCallId',
- default: false,
-});
+export const sandboxStartingByToolCallId = atomFamily((_toolCallId: string) => atom(false));
diff --git a/client/src/utils/__tests__/activityLabels.spec.ts b/client/src/utils/__tests__/activityLabels.spec.ts
index 207ba61571..d8f0929414 100644
--- a/client/src/utils/__tests__/activityLabels.spec.ts
+++ b/client/src/utils/__tests__/activityLabels.spec.ts
@@ -886,8 +886,18 @@ describe('groupActivityPhases — live tail', () => {
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('folds a streaming thought before any tool call, so its peek never opens and snaps shut', () => {
+ const segments = groupActivityPhases([think], undefined, true);
+ expect(segments?.[0]).toMatchObject({ type: 'phase', live: true, contentIndices: [0] });
+ });
+
+ it('does not fold a thought that has no text yet', () => {
+ const empty = { type: ContentTypes.THINK, think: ' ' } as unknown as TMessageContentParts;
+ expect(groupActivityPhases([empty], undefined, true)).toBeUndefined();
+ });
+
+ it('leaves a settled thought on its own row', () => {
+ expect(groupActivityPhases([think])).toBeUndefined();
});
it('does not fold a span the stream has already moved past', () => {
diff --git a/client/src/utils/activityLabels.ts b/client/src/utils/activityLabels.ts
index 2e7560980f..bc5cf42ca9 100644
--- a/client/src/utils/activityLabels.ts
+++ b/client/src/utils/activityLabels.ts
@@ -354,7 +354,17 @@ function buildSynthesizedPhaseLabel(run: FoldRun): SynthesizedPhaseHeader | unde
*/
function buildLivePhaseLabel(run: FoldRun): SynthesizedPhaseHeader | undefined {
let activities = 0;
+ let reasons = false;
for (const part of run.content) {
+ /** A thought counts from its first character. Left outside until a tool
+ * call arrived, it rendered as its own row with a multi-line peek that
+ * the first call then snapped shut — a grow-and-shrink on every step of a
+ * reasoning model that talks between calls. */
+ if (part?.type === ContentTypes.THINK) {
+ const thought = typeof part.think === 'string' ? part.think : (part.think?.value ?? '');
+ reasons ||= thought.trim().length > 0;
+ continue;
+ }
/** 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;
@@ -362,7 +372,7 @@ function buildLivePhaseLabel(run: FoldRun): SynthesizedPhaseHeader | undefined {
activities += 1;
}
}
- if (activities === 0) {
+ if (activities === 0 && !reasons) {
return undefined;
}
const endPosition = run.content.length - 1;