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: Show a Thought on the Live Header Only as Finished Sentences (#16392)

Danny Avila269e6b34f89e
diff --git a/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx b/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx
index 0ca2a73cfe..d73ded46b6 100644
--- a/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx
+++ b/client/src/components/Chat/Messages/Content/ActivityPhaseGroup.tsx
@@ -1,19 +1,10 @@
-import {
- memo,
- useId,
- useCallback,
- useEffect,
- useMemo,
- useRef,
- useState,
- useLayoutEffect,
-} from 'react';
+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, Lightbulb, ChevronDown, TriangleAlert } from 'lucide-react';
import type { TAttachment, TMessageContentParts } from 'librechat-data-provider';
-import type { CSSProperties, ReactNode, RefObject } from 'react';
+import type { CSSProperties, ReactNode } from 'react';
import {
useLocalize,
useExpandCollapse,
@@ -26,6 +17,7 @@ import {
getLiveActivity,
getSpanIconNames,
LIVE_ACTIVITY_THROTTLE_MS,
+ LIVE_REASONING_HOLD_MS,
} from './live';
import { FailedRevealContext, FailedRevealPill, useFailedRevealTrigger } from './reveal';
import { FOLD_RAIL_CLASSES, ROW_GLYPH_SLOT, TOOL_ROW_CLASSES } from './rows';
@@ -115,12 +107,8 @@ function PhaseGlyph({ failed }: { failed: boolean }) {
* from adding descender space, which made a live row 2px taller than the
* settled row it becomes.
*/
-function LiveLine({ text, previewRef }: { text: string; previewRef?: RefObject<HTMLSpanElement> }) {
- return (
- <span ref={previewRef} className="shimmer max-w-full truncate align-top">
- {text}
- </span>
- );
+function LiveLine({ text }: { text: string }) {
+ return <span className="shimmer max-w-full truncate align-top">{text}</span>;
}
const PhaseLabel = memo(function PhaseLabel({
@@ -131,7 +119,6 @@ const PhaseLabel = memo(function PhaseLabel({
live = false,
grow = true,
lineId,
- previewRef,
}: {
text: string;
animate: boolean;
@@ -147,7 +134,6 @@ const PhaseLabel = memo(function PhaseLabel({
grow?: boolean;
/** Id for the current line, so a live disclosure can be named by it alone. */
lineId?: string;
- previewRef?: RefObject<HTMLSpanElement>;
}) {
const [lines, setLines] = useState<{
current: string;
@@ -216,7 +202,7 @@ const PhaseLabel = memo(function PhaseLabel({
failed && 'text-text-warning',
)}
>
- {live ? <LiveLine text={lines.current} previewRef={previewRef} /> : lines.current}
+ {live ? <LiveLine text={lines.current} /> : lines.current}
</span>
</span>
);
@@ -271,8 +257,8 @@ function SpanGlyph({
*
* Its own component so only a live card pays for it — the localization and MCP
* lookups, and the throttle. `liveParts` is rebuilt on every streamed delta;
- * full reasoning lines and tool activity repaint at most twice a second.
- * Short reasoning sentences stream freely until they fill the available row.
+ * tool activity repaints at most twice a second and a finished reasoning
+ * sentence holds the line for at least a second.
*/
function LivePhaseHeader({
parts,
@@ -312,36 +298,12 @@ function LivePhaseHeader({
const comboCount = showSandboxStartup ? 1 : activity.comboCount;
const { source } = activity;
const line = useMemo(() => ({ text, source, comboCount }), [text, source, comboCount]);
- const previewRef = useRef<HTMLSpanElement>(null);
- /** The full width the line may occupy, which is the flex track rather than
- * the label box: the box shrinks to its text whenever the multiplier rides
- * beside it, and measuring that would call every line full. */
- const lineRowRef = useRef<HTMLSpanElement>(null);
- const [isPreviewFull, setIsPreviewFull] = useState(false);
+ /** A thought's line is a finished sentence and holds for a beat; everything
+ * else repaints at the ordinary cadence. */
const painted = useThrottledValue(
line,
- source.startsWith('think:') && !isPreviewFull ? 0 : LIVE_ACTIVITY_THROTTLE_MS,
+ source.startsWith('think:') ? LIVE_REASONING_HOLD_MS : LIVE_ACTIVITY_THROTTLE_MS,
);
- const measurePreview = useCallback(() => {
- const preview = previewRef.current;
- const width = lineRowRef.current?.clientWidth ?? 0;
- setIsPreviewFull(width > 0 && (preview?.scrollWidth ?? 0) >= width);
- }, []);
-
- /** Measure the painted sentence, not the accumulated reasoning or the next
- * queued line: a newly displayed short sentence must fill before it waits. */
- useLayoutEffect(measurePreview, [measurePreview, painted.text, painted.source]);
- useLayoutEffect(() => {
- const preview = previewRef.current;
- const row = lineRowRef.current;
- if (!preview || !row || typeof ResizeObserver === 'undefined') {
- return;
- }
- const observer = new ResizeObserver(measurePreview);
- observer.observe(row);
- observer.observe(preview);
- return () => observer.disconnect();
- }, [measurePreview, painted.source]);
const iconKey = activity.iconNames.join('|');
const iconNames = useMemo(() => (iconKey ? iconKey.split('|') : []), [iconKey]);
const sourceDomains = useMemo(() => getSourceDomains(attachments, SPAN_SITES), [attachments]);
@@ -411,7 +373,7 @@ function LivePhaseHeader({
* separate element rather than part of the line's text so the
* disclosure's name keeps a space before it and the ticker still
* animates one sentence at a time. */}
- <span className="flex min-w-0 flex-1 items-center gap-1.5" ref={lineRowRef}>
+ <span className="flex min-w-0 flex-1 items-center gap-1.5">
<PhaseLabel
text={painted.text}
source={painted.source}
@@ -420,7 +382,6 @@ function LivePhaseHeader({
live
grow={combo === ''}
lineId={lineId}
- previewRef={previewRef}
/>
{combo !== '' && (
<span
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 4e38738b86..ae71dbef38 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
@@ -1261,14 +1261,19 @@ describe('ContentParts — live activity fold', () => {
expect(liveHeader()).toHaveTextContent('Both refs share a commit.');
expect(screen.queryByTestId('reasoning')).toBeNull();
+ /** The next sentence is not shown while it is still being written. */
rerender(frame('Both refs share a commit. That leaves the ordering'));
act(() => {
- jest.advanceTimersByTime(500);
+ jest.advanceTimersByTime(1000);
+ });
+ expect(liveHeader()).toHaveTextContent('Both refs share a commit.');
+ expect(liveHeader()).not.toHaveTextContent('That leaves the ordering');
+ rerender(frame('Both refs share a commit. That leaves the ordering.'));
+ act(() => {
+ jest.advanceTimersByTime(1000);
});
- expect(liveHeader()).toHaveTextContent('That leaves the ordering');
- /** The previous sentence is the `aria-hidden` line sliding out, which is
- * the tick itself; the row's current line is the new sentence alone. */
- expect(within(liveHeader()).getByTitle('That leaves the ordering')).toBeInTheDocument();
+ expect(liveHeader()).toHaveTextContent('That leaves the ordering.');
+ expect(within(liveHeader()).getByTitle('That leaves the ordering.')).toBeInTheDocument();
expect(screen.getAllByRole('button')).toHaveLength(1);
});
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 8fad9144f9..0eae37dc85 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/LiveParity.test.tsx
@@ -535,8 +535,9 @@ describe('live fold parity with the cards it hides', () => {
mount([toPart({ name: 'lookup', output: 'rows' }), think], undefined, true);
const button = within(screen.getByTestId('activity-phase-card')).getAllByRole('button')[0];
- expect(button).toHaveTextContent('接下来检查顺序约定');
- expect(button).not.toHaveTextContent('两个引用');
+ /** Only the finished sentence; the one still being written stays out. */
+ expect(button).toHaveTextContent('两个引用共享一个提交。');
+ expect(button).not.toHaveTextContent('接下来');
});
it('keeps a CJK sentence that ends exactly at the tail instead of reverting to the call', () => {
@@ -908,79 +909,47 @@ describe('live activity hardening transitions', () => {
</QueryClientProvider>
);
- it.each([160, 640])('streams each short sentence freely until it fills a %ipx row', (width) => {
+ it('shows a thought only as finished sentences, each held for a second', () => {
jest.useFakeTimers();
- jest.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockReturnValue(width);
- jest.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockImplementation(function (
- this: HTMLElement,
- ) {
- return (this.textContent?.length ?? 0) * 8;
- });
const content = (think: string): TMessageContentParts[] => [
{ type: ContentTypes.THINK, think },
];
const view = render(frame(content('Let me')));
const header = screen.getByRole('button');
- view.rerender(frame(content('Let me check')));
- expect(header).toHaveAccessibleName('Let me check');
-
- const full = 'Checking the available evidence '.repeat(Math.ceil(width / 240)).trim();
- view.rerender(frame(content(full)));
- expect(header).toHaveAccessibleName(full);
- view.rerender(frame(content(full + ' carefully')));
- expect(header).toHaveAccessibleName(full);
- act(() => jest.advanceTimersByTime(500));
- expect(header).toHaveAccessibleName(full + ' carefully');
-
- view.rerender(frame(content(full + ' carefully. Now I')));
- act(() => jest.advanceTimersByTime(500));
- expect(header).toHaveAccessibleName('Now I');
- view.rerender(frame(content(full + ' carefully. Now I can check')));
- expect(header).toHaveAccessibleName('Now I can check');
+ /** Nothing finished yet: the generic line, not a fragment. */
+ expect(header).toHaveAccessibleName('Thinking...');
+ view.rerender(frame(content('Let me check the evidence')));
+ act(() => jest.advanceTimersByTime(1000));
+ expect(header).toHaveAccessibleName('Thinking...');
+
+ /** A sentence finishing a second after the last paint shows at once. */
+ view.rerender(frame(content('Let me check the evidence.')));
+ expect(header).toHaveAccessibleName('Let me check the evidence.');
+
+ /** The next sentence is written behind the finished one. */
+ view.rerender(frame(content('Let me check the evidence. Now I can')));
+ act(() => jest.advanceTimersByTime(200));
+ expect(header).toHaveAccessibleName('Let me check the evidence.');
+
+ /** Finished 200ms after the last paint: the line holds its sentence for
+ * the rest of the second before the next one takes it. */
+ view.rerender(frame(content('Let me check the evidence. Now I can decide.')));
+ act(() => jest.advanceTimersByTime(200));
+ expect(header).toHaveAccessibleName('Let me check the evidence.');
+ act(() => jest.advanceTimersByTime(600));
+ expect(header).toHaveAccessibleName('Now I can decide.');
expect(screen.getByTestId('activity-phase-announcer')).toBeEmptyDOMElement();
- jest.restoreAllMocks();
});
- it('releases a queued reasoning preview when resizing gives the line more room', () => {
+ it('keeps decimals and versions inside one sentence', () => {
jest.useFakeTimers();
- let width = 160;
- const callbacks = new Set<ResizeObserverCallback>();
- const disconnect = jest.fn();
- jest.spyOn(global, 'ResizeObserver').mockImplementation((callback) => {
- callbacks.add(callback);
- return {
- observe: jest.fn(),
- unobserve: jest.fn(),
- disconnect: () => {
- callbacks.delete(callback);
- disconnect();
- },
- };
- });
- jest.spyOn(HTMLElement.prototype, 'clientWidth', 'get').mockImplementation(() => width);
- jest.spyOn(HTMLElement.prototype, 'scrollWidth', 'get').mockImplementation(function (
- this: HTMLElement,
- ) {
- return (this.textContent?.length ?? 0) * 8;
- });
const content = (think: string): TMessageContentParts[] => [
{ type: ContentTypes.THINK, think },
];
- const initial = 'Checking the available evidence';
- const view = render(frame(content(initial)));
- view.rerender(frame(content(initial + ' carefully')));
- expect(screen.getByRole('button')).toHaveAccessibleName(initial);
-
- width = 640;
- act(() => {
- for (const callback of callbacks) {
- callback([], { observe: () => {}, unobserve: () => {}, disconnect: () => {} });
- }
- });
- expect(screen.getByRole('button')).toHaveAccessibleName(initial + ' carefully');
- view.unmount();
- expect(disconnect).toHaveBeenCalled();
- jest.restoreAllMocks();
+ render(frame(content('The gain was 3.5 points on v2.1 today. Next up')));
+ expect(screen.getByRole('button')).toHaveAccessibleName(
+ 'The gain was 3.5 points on v2.1 today.',
+ );
});
function SandboxEvent() {
@@ -1186,7 +1155,9 @@ describe('live activity hardening transitions', () => {
});
}
expect(screen.getByTestId('activity-phase-announcer')).toBeEmptyDOMElement();
- expect(screen.getByRole('button')).toHaveAccessibleName('Next sentence');
+ /** The finished sentence is the long run itself, clamped to one line;
+ * the sentence after it is still being written. */
+ expect(screen.getByRole('button')).toHaveAccessibleName(`${'x'.repeat(255)}…`);
},
);
diff --git a/client/src/components/Chat/Messages/Content/live.ts b/client/src/components/Chat/Messages/Content/live.ts
index fcfe0b7bdf..1f55ba14a7 100644
--- a/client/src/components/Chat/Messages/Content/live.ts
+++ b/client/src/components/Chat/Messages/Content/live.ts
@@ -148,8 +148,20 @@ function toolCallLine(
/** Bounds the sentence scan on long reasoning, like the streaming peek. */
const REASONING_TAIL_CHARS = 1200;
+/** How long a completed reasoning sentence holds the line before the next
+ * one may replace it. Sentences can close a few hundred milliseconds apart;
+ * a line that swaps that often cannot be read, and the header is there to be
+ * read, not to keep pace with the stream. */
+export const LIVE_REASONING_HOLD_MS = 1000;
+
/**
- * A bounded preview of the sentence the thought is currently writing.
+ * The last COMPLETE sentence of a thought: the one that ends at the newest
+ * sentence mark, never the one still being written. A line that grew word by
+ * word read as disjointed fragments ("This is a simple greeting, not") and
+ * was gone before it made sense; a finished sentence says one thing and stays
+ * until the next is finished. Undefined until the first mark lands, so the
+ * header keeps its generic line rather than showing a fragment.
+ *
* Preview offsets are not activity identities: a sliding window, whitespace
* or a resumed snapshot can move them without starting a new thought.
*/
@@ -162,18 +174,17 @@ function lastReasoningSentence(reasoning: string): string | undefined {
if (!tail) {
return undefined;
}
+ /** A Latin mark closes a sentence only when followed by space or the end
+ * of the text, so "3.5" and "v2.1" stay whole; CJK marks need no space. */
+ const boundary = /[.!?](?:\s+|$)|[。!?]\s*/g;
let start = 0;
- /** CJK sentences end in full-width marks with no space after them. */
- const boundary = /[.!?]\s+|[。!?]\s*/g;
+ let complete: string | undefined;
for (let match = boundary.exec(tail); match != null; match = boundary.exec(tail)) {
- const end = match.index + match[0].length;
- /** A mark that closes the tail ends the CURRENT sentence; it does not
- * start an empty one. The finished sentence stays until the next begins. */
- if (end < tail.length) {
- start = end;
- }
+ /** The mark itself is one code unit in both scripts. */
+ complete = tail.slice(start, match.index + 1);
+ start = match.index + match[0].length;
}
- return boundIntentLabel(tail.slice(start));
+ return complete == null ? undefined : boundIntentLabel(complete);
}
/**