📴 fix: Stop Hidden Code Spinners (#15846)

* fix: keep quote selection updates outside React renders

* fix: stop animating hidden code execution spinners

* test: guard idle transcripts against continuous animations

* test: Assert accepted paste behavior independently of placeholder resize
This commit is contained in:
Danny Avila 2026-09-11 21:37:49 -04:00 • committed by GitHub
parent 1bea7e4c9e
commit 767ee591d0
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
7 changed files with 419 additions and 58 deletions

View file

@ -1,4 +1,4 @@
import { memo, useRef, useState, useEffect, useCallback, useLayoutEffect } from 'react';
import { memo, useRef, useEffect, useCallback, useLayoutEffect } from 'react';
import { createPortal } from 'react-dom';
import { TextQuote } from 'lucide-react';
import { useSetRecoilState } from 'recoil';
@ -244,7 +244,7 @@ const resolveTop = (anchor: Anchor, height: number, preferBelow: boolean): numbe
*/
function QuoteButton({ conversationId }: { conversationId: string }) {
const localize = useLocalize();
const [selection, setSelection] = useState<SelectionState | null>(null);
const selectionRef = useRef<SelectionState | null>(null);
const buttonRef = useRef<HTMLButtonElement>(null);
const rangeRef = useRef<Range | null>(null);
const clippersRef = useRef<HTMLElement[]>([]);
@ -255,6 +255,32 @@ function QuoteButton({ conversationId }: { conversationId: string }) {
const hideRef = useRef<() => void>(() => undefined);
const setQuotes = useSetRecoilState(store.pendingQuotesByConvoId(conversationId));
/** Selection and scroll events must not enter React's commit/selection-restoration
* path. Keep the portal mounted and update only its transient presentation. */
const presentSelection = useCallback((next: SelectionState | null) => {
selectionRef.current = next;
const button = buttonRef.current;
if (!button) {
return;
}
if (!next) {
button.style.display = 'none';
return;
}
const touch = String(next.viaTouch);
if (button.dataset.touch !== touch) {
button.dataset.touch = touch;
}
if (button.style.display === 'none') {
button.style.display = 'inline-flex';
}
const { width, height } = button.getBoundingClientRect();
const maxLeft = Math.max(EDGE_MARGIN, window.innerWidth - width - EDGE_MARGIN);
const left = Math.min(Math.max(anchorCenterX(next.anchor) - width / 2, EDGE_MARGIN), maxLeft);
button.style.top = `${resolveTop(next.anchor, height, next.viaTouch)}px`;
button.style.left = `${left}px`;
}, []);
useEffect(() => {
let settleTimer: ReturnType<typeof setTimeout> | undefined;
let frame = 0;
@ -279,7 +305,7 @@ function QuoteButton({ conversationId }: { conversationId: string }) {
}
rangeRef.current = null;
clippersRef.current = [];
setSelection(null);
presentSelection(null);
};
const hide = () => {
@ -299,18 +325,18 @@ function QuoteButton({ conversationId }: { conversationId: string }) {
hide();
return;
}
rangeRef.current = reading.range;
/** Native handle drags can mutate the Selection's Range in place. */
rangeRef.current = reading.range.cloneRange();
clippersRef.current = reading.clippers;
/** Reuse the previous state object when nothing moved so a redundant
* settle pass costs no render. */
setSelection((prev) =>
prev &&
prev.text === reading.text &&
prev.viaTouch === touch &&
sameAnchor(prev.anchor, reading.anchor)
? prev
: { text: reading.text, anchor: reading.anchor, viaTouch: touch },
);
const previous = selectionRef.current;
if (
!previous ||
previous.text !== reading.text ||
previous.viaTouch !== touch ||
!sameAnchor(previous.anchor, reading.anchor)
) {
presentSelection({ text: reading.text, anchor: reading.anchor, viaTouch: touch });
}
};
const handlePointerDown = (event: PointerEvent) => {
@ -382,9 +408,10 @@ function QuoteButton({ conversationId }: { conversationId: string }) {
hide();
return;
}
setSelection((prev) =>
prev && !sameAnchor(prev.anchor, anchor) ? { ...prev, anchor } : prev,
);
const previous = selectionRef.current;
if (previous && !sameAnchor(previous.anchor, anchor)) {
presentSelection({ ...previous, anchor });
}
};
const scheduleReanchor = () => {
@ -422,29 +449,17 @@ function QuoteButton({ conversationId }: { conversationId: string }) {
document.removeEventListener('scroll', scheduleReanchor, true);
window.removeEventListener('resize', scheduleReanchor);
};
}, []);
}, [presentSelection]);
/** Clamp using the button's real size so it never lands off-screen. Apply the
* measured layout directly before paint: feeding it back through state adds
* a synchronous render to every selection update and can exhaust React's
* nested-update limit while the browser is still changing the selection. */
/** A parent render (for example a locale change) can change the button size. */
useLayoutEffect(() => {
const button = buttonRef.current;
if (!selection || !button) {
return;
}
const { width, height } = button.getBoundingClientRect();
const maxLeft = Math.max(EDGE_MARGIN, window.innerWidth - width - EDGE_MARGIN);
const left = Math.min(
Math.max(anchorCenterX(selection.anchor) - width / 2, EDGE_MARGIN),
maxLeft,
);
const top = resolveTop(selection.anchor, height, selection.viaTouch);
presentSelection(selectionRef.current);
});
button.style.top = `${top}px`;
button.style.left = `${left}px`;
button.style.visibility = 'visible';
}, [selection]);
useLayoutEffect(() => {
pressedTextRef.current = null;
hideRef.current();
}, [conversationId]);
const commitQuote = useCallback(
(text: string) => {
@ -454,18 +469,19 @@ function QuoteButton({ conversationId }: { conversationId: string }) {
rangeRef.current = null;
clippersRef.current = [];
pressedTextRef.current = null;
setSelection(null);
presentSelection(null);
window.getSelection()?.removeAllRanges();
document.getElementById(mainTextareaId)?.focus();
},
[setQuotes],
[setQuotes, presentSelection],
);
const addQuote = useCallback(() => {
const selection = selectionRef.current;
if (selection) {
commitQuote(selection.text);
}
}, [selection, commitQuote]);
}, [commitQuote]);
/**
* End a touch press that did not commit. While a press is in flight the
@ -482,16 +498,12 @@ function QuoteButton({ conversationId }: { conversationId: string }) {
}
}, []);
if (!selection) {
return null;
}
return createPortal(
<button
ref={buttonRef}
type="button"
/** A tap is also the gesture that dismisses a selection, so `click` can
* never be relied on here: the button is already unmounted by the time it
* never be relied on here: the button can be hidden by the time it
* would fire. The excerpt is captured on the press and committed on the
* release instead, which keeps a button's normal escape hatches — drag
* off the button, or have the gesture stolen by a scroll, and nothing is
@ -501,7 +513,7 @@ function QuoteButton({ conversationId }: { conversationId: string }) {
return;
}
event.preventDefault();
pressedTextRef.current = selection.text;
pressedTextRef.current = selectionRef.current?.text ?? null;
try {
event.currentTarget.setPointerCapture(event.pointerId);
} catch {
@ -539,13 +551,12 @@ function QuoteButton({ conversationId }: { conversationId: string }) {
style={{
top: 0,
left: 0,
/** Hidden until measured so it never flashes at an unclamped position. */
visibility: 'hidden',
display: 'none',
}}
className={cn(
'fixed z-50 inline-flex items-center gap-1.5 rounded-full border border-border-light bg-surface-secondary text-sm font-medium text-text-primary shadow-lg transition-colors hover:bg-surface-tertiary',
/** Comfortable tap target when the selection came from a finger. */
selection.viaTouch ? 'min-h-11 px-4 py-2.5' : 'px-3 py-1.5',
'px-3 py-1.5 data-[touch=true]:min-h-11 data-[touch=true]:px-4 data-[touch=true]:py-2.5',
)}
>
<TextQuote className="h-4 w-4" aria-hidden="true" />

View file

@ -1,12 +1,14 @@
import React, { Profiler } from 'react';
import { RecoilRoot } from 'recoil';
import { render, screen, fireEvent } from '@testing-library/react';
import { RecoilRoot, useRecoilValue } from 'recoil';
import { act, render, screen, fireEvent } from '@testing-library/react';
jest.mock('~/hooks', () => ({
useLocalize: () => (key: string) => key,
}));
import QuoteButton from '../QuoteButton';
import store from '~/store';
import { mainTextareaId } from '~/common';
const CONVO_ID = 'convo-1';
const SELECTED_TEXT = 'Selected assistant text';
@ -34,13 +36,25 @@ const rect = ({
toJSON: () => ({}),
}) as DOMRect;
function Quotes() {
const quotes = useRecoilValue(store.pendingQuotesByConvoId(CONVO_ID));
return <output data-testid="quotes">{JSON.stringify(quotes)}</output>;
}
function pointer(target: Document | HTMLElement, type: string) {
const event = new MouseEvent(type, { bubbles: true, clientX: 50, clientY: 15 });
Object.defineProperty(event, 'pointerType', { value: 'touch' });
fireEvent(target, event);
}
describe('QuoteButton', () => {
afterEach(() => {
window.getSelection()?.removeAllRanges();
});
it('positions a new selection without scheduling a layout-state render', () => {
const rangeRect = rect({ top: 100, bottom: 120, left: 200, right: 260 });
it('shows, moves, and dismisses selections without React commits, then commits a touch quote', () => {
jest.useFakeTimers();
let rangeRect = rect({ top: 100, bottom: 120, left: 200, right: 260 });
const buttonRect = rect({ top: 0, bottom: 30, left: 0, right: 100 });
const originalRangeRect = Range.prototype.getBoundingClientRect;
const elementRect = jest
@ -60,6 +74,8 @@ describe('QuoteButton', () => {
render(
<RecoilRoot>
<div className="message-render">{SELECTED_TEXT}</div>
<textarea id={mainTextareaId} />
<Quotes />
<Profiler id="quote-button" onRender={onRender}>
<QuoteButton conversationId={CONVO_ID} />
</Profiler>
@ -82,10 +98,47 @@ describe('QuoteButton', () => {
expect(screen.getByTestId('add-to-chat-button')).toHaveStyle({
top: '62px',
left: '180px',
visibility: 'visible',
});
expect(onRender).toHaveBeenCalledTimes(1);
const button = screen.getByTestId('add-to-chat-button');
expect(button).toBeVisible();
expect(onRender).not.toHaveBeenCalled();
rangeRect = rect({ top: 200, bottom: 220, left: 200, right: 260 });
fireEvent.scroll(document);
act(() => jest.advanceTimersByTime(20));
expect(button).toHaveStyle({ top: '162px' });
expect(onRender).not.toHaveBeenCalled();
window.getSelection()?.removeAllRanges();
fireEvent(document, new Event('selectionchange'));
expect(button).not.toBeVisible();
expect(onRender).not.toHaveBeenCalled();
pointer(document, 'pointerdown');
window.getSelection()?.addRange(range);
fireEvent(document, new Event('selectionchange'));
act(() => jest.advanceTimersByTime(300));
expect(button).toBeVisible();
expect(button).toHaveAttribute('data-touch', 'true');
expect(button).toHaveStyle({ top: '228px' });
range.setEnd(textNode, 8);
fireEvent(document, new Event('selectionchange'));
expect(button).not.toBeVisible();
act(() => jest.advanceTimersByTime(300));
expect(button).toBeVisible();
expect(onRender).not.toHaveBeenCalled();
pointer(button, 'pointerdown');
window.getSelection()?.removeAllRanges();
fireEvent(document, new Event('selectionchange'));
expect(button).toBeVisible();
pointer(button, 'pointerup');
expect(button).not.toBeVisible();
expect(screen.getByTestId('quotes')).toHaveTextContent('["Selected"]');
expect(screen.getByRole('textbox')).toHaveFocus();
} finally {
jest.useRealTimers();
elementRect.mockRestore();
if (originalRangeRect) {
Object.defineProperty(Range.prototype, 'getBoundingClientRect', {
@ -98,3 +151,95 @@ describe('QuoteButton', () => {
}
});
});
describe('QuoteButton lifecycle', () => {
const originalRangeRect = Range.prototype.getBoundingClientRect;
beforeEach(() => {
jest.useFakeTimers();
Object.defineProperty(Range.prototype, 'getBoundingClientRect', {
configurable: true,
value: () => rect({ top: 100, bottom: 120, left: 200, right: 260 }),
});
});
afterEach(() => {
window.getSelection()?.removeAllRanges();
jest.useRealTimers();
if (originalRangeRect) {
Object.defineProperty(Range.prototype, 'getBoundingClientRect', {
configurable: true,
value: originalRangeRect,
});
} else {
delete (Range.prototype as Partial<Range>).getBoundingClientRect;
}
});
function setup() {
const content = (conversationId: string) => (
<RecoilRoot>
<div className="message-render">{SELECTED_TEXT}</div>
<textarea id={mainTextareaId} />
<Quotes />
<QuoteButton conversationId={conversationId} />
</RecoilRoot>
);
const view = render(content(CONVO_ID));
const range = document.createRange();
range.selectNodeContents(screen.getByText(SELECTED_TEXT));
window.getSelection()?.removeAllRanges();
window.getSelection()?.addRange(range);
return {
...view,
button: screen.getByTestId('add-to-chat-button'),
navigate: () => view.rerender(content('convo-2')),
};
}
it('supports keyboard selection and activation', () => {
const { button } = setup();
fireEvent.keyDown(document, { key: 'Shift' });
fireEvent.keyUp(document, { key: 'Shift' });
expect(button).toBeVisible();
expect(button).toHaveAttribute('data-touch', 'false');
fireEvent.click(button, { detail: 0 });
expect(screen.getByTestId('quotes')).toHaveTextContent(JSON.stringify([SELECTED_TEXT]));
expect(screen.getByRole('textbox')).toHaveFocus();
expect(button).not.toBeVisible();
});
it('dismisses a canceled touch press without adding a quote', () => {
const { button } = setup();
fireEvent.mouseUp(document);
pointer(button, 'pointerdown');
window.getSelection()?.removeAllRanges();
fireEvent(document, new Event('selectionchange'));
pointer(button, 'pointercancel');
expect(button).not.toBeVisible();
expect(screen.getByTestId('quotes')).toHaveTextContent('[]');
});
it('clears visible and pending selections when the conversation changes', () => {
const { button, navigate } = setup();
fireEvent.mouseUp(document);
expect(button).toBeVisible();
fireEvent(document, new Event('selectionchange'));
navigate();
expect(button).not.toBeVisible();
act(() => jest.advanceTimersByTime(500));
expect(button).not.toBeVisible();
expect(screen.getByTestId('quotes')).toHaveTextContent('[]');
});
it('cancels pending selection work and removes the portal on unmount', () => {
const { unmount } = setup();
fireEvent(document, new Event('selectionchange'));
const readSelection = jest.spyOn(window, 'getSelection');
unmount();
readSelection.mockClear();
act(() => jest.advanceTimersByTime(500));
expect(readSelection).not.toHaveBeenCalled();
expect(screen.queryByTestId('add-to-chat-button')).not.toBeInTheDocument();
});
});

View file

@ -143,7 +143,7 @@ const RunCode: React.FC<CodeBarProps & { iconOnly?: boolean }> = React.memo(
isLoading ? 'opacity-100' : 'opacity-0',
)}
>
<Spinner className="animate-spin" size={18} />
{isLoading && <Spinner size={18} />}
</span>
</span>
{!iconOnly && (

View file

@ -0,0 +1,87 @@
import React from 'react';
import { RecoilRoot } from 'recoil';
import { ToastProvider } from '@librechat/client';
import { dataService } from 'librechat-data-provider';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { act, render, screen, fireEvent, waitFor } from '@testing-library/react';
import type { ToolCallResponse } from 'librechat-data-provider';
import { MessageContext } from '~/Providers/MessageContext';
import RunCode from '../RunCode';
jest.mock('librechat-data-provider', () => {
const actual = jest.requireActual('librechat-data-provider');
return { ...actual, dataService: { ...actual.dataService, callTool: jest.fn() } };
});
jest.mock('~/hooks', () => ({ useLocalize: () => (key: string) => key }));
jest.mock('~/Providers', () => jest.requireActual('~/Providers/MessageContext'));
jest.mock('~/data-provider', () => jest.requireActual('~/data-provider/Tools/mutations'));
describe('RunCode animation lifecycle', () => {
beforeEach(() => jest.useFakeTimers());
afterEach(() => jest.useRealTimers());
it.each(['success', 'error'] as const)(
'only animates during execution, including %s and retry',
async (outcome) => {
let settle: (value: ToolCallResponse) => void = () => undefined;
let reject: (reason: Error) => void = () => undefined;
const callTool = jest.mocked(dataService.callTool).mockImplementation(
() =>
new Promise<ToolCallResponse>((resolve, fail) => {
settle = resolve;
reject = fail;
}),
);
const queryClient = new QueryClient({
defaultOptions: { mutations: { retry: false } },
logger: { log: console.log, warn: console.warn, error: () => undefined },
});
const code = document.createElement('code');
code.textContent = 'print(1)';
const { container, unmount } = render(
<QueryClientProvider client={queryClient}>
<RecoilRoot>
<ToastProvider>
<MessageContext.Provider
value={{ messageId: 'message', conversationId: 'conversation', isExpanded: false }}
>
<RunCode lang="python" codeRef={{ current: code }} blockIndex={0} />
</MessageContext.Provider>
</ToastProvider>
</RecoilRoot>
</QueryClientProvider>,
);
const button = screen.getByRole('button', { name: 'com_ui_run_code' });
expect(container.querySelector('.spinner')).not.toBeInTheDocument();
await act(async () => {
fireEvent.click(button);
await jest.advanceTimersByTimeAsync(0);
});
await waitFor(() => expect(callTool).toHaveBeenCalledTimes(1));
await waitFor(() => expect(button).toBeDisabled());
expect(container.querySelector('.spinner')).toBeInTheDocument();
await act(async () => {
if (outcome === 'success') settle({ result: '1', attachments: [] });
else reject(new Error('Execution failed'));
});
await waitFor(() => expect(button).toBeEnabled());
expect(container.querySelector('.spinner')).not.toBeInTheDocument();
await act(async () => {
jest.advanceTimersByTime(1100);
});
await act(async () => {
fireEvent.click(button);
await jest.advanceTimersByTimeAsync(0);
});
await waitFor(() => expect(callTool).toHaveBeenCalledTimes(2));
await waitFor(() => expect(button).toBeDisabled());
expect(container.querySelector('.spinner')).toBeInTheDocument();
await act(async () => settle({ result: '1', attachments: [] }));
await waitFor(() => expect(button).toBeEnabled());
expect(container.querySelector('.spinner')).not.toBeInTheDocument();
unmount();
queryClient.clear();
},
);
});

View file

@ -281,7 +281,7 @@ describe('useTextarea long-paste fallback', () => {
it('does not restore the paste when the attachment is accepted', async () => {
mockRouteFiles.mockResolvedValueOnce(true);
const { result } = renderTextareaHook();
const { result, textArea } = renderTextareaHook();
const event = createPasteEvent();
act(() =>
@ -296,7 +296,7 @@ describe('useTextarea long-paste fallback', () => {
}),
);
expect(mockInsertTextAtCursor).not.toHaveBeenCalled();
expect(mockForceResize).not.toHaveBeenCalled();
expect(textArea.value).toBe('');
});
it('replaces selected draft text when the attachment is accepted', async () => {

View file

@ -41,3 +41,32 @@ REACT_SCAN_PATH=/tmp/librechat-react-scan/package/dist/auto.global.js \
JSON snapshots are attached to the Playwright results under
`e2e/benchmarks/.test-results/mobile-chat`.
## Deterministic regression guards
The normal mock E2E suite includes `idle-animations.spec.ts`. It renders six settled
messages, including three code blocks, in desktop and narrow layouts and asserts
that the transcript has **no running infinite animations**. The check uses the
browser's animation API, so it catches opacity-hidden spinners and other perpetual
CSS animations. It explicitly enables motion, waits for every code control to
mount, permits finite entrance transitions, and reports the offending animation
and element when it fails. It needs neither a large transcript nor a CPU/time
threshold to catch work that would multiply across a long chat.
After preparing the production client, run it with:
```bash
npx playwright test --config=e2e/playwright.config.mock.ts idle-animations.spec.ts
```
The component tests cover the complementary invariants: `RunCode.test.tsx`
checks that the spinner exists only during execution, including success, failure,
and retry, with fake timers and controlled HTTP completion. `QuoteButton.test.tsx`
uses a React Profiler to assert zero commits for selection and positioning events.
Keep the browser timing measurements above as diagnostic evidence rather than a
single-run merge gate. When a benchmark identifies a regression, add a focused
invariant test at the cause—such as no idle animations, no unrelated renders, or
bounded request counts—where possible. Timing and memory totals vary with the
runner, garbage collection, and browser version; these structural checks do not
require those numbers to stay below an arbitrary threshold.

View file

@ -0,0 +1,89 @@
import { randomUUID } from 'node:crypto';
import { expect, test } from '@playwright/test';
import {
seedConversations,
seedMessages,
deleteConversations,
deleteMessagesByConversation,
} from './db';
import { getE2EUser } from '../../setup/user';
/** Exercise real animation CSS even on hosts whose OS prefers reduced motion. */
test.use({ reducedMotion: 'no-preference' });
for (const viewport of [
{ width: 1280, height: 720 },
{ width: 390, height: 664 },
]) {
test(`settled code messages have no continuously running animations (${viewport.width}px)`, async ({
page,
}) => {
await page.setViewportSize(viewport);
const conversationId = randomUUID();
const userEmail = getE2EUser().email;
const messages = [];
let parentMessageId = '00000000-0000-0000-0000-000000000000';
for (let index = 0; index < 6; index++) {
const messageId = `${conversationId}-${index}`;
const isCreatedByUser = index % 2 === 0;
messages.push({
messageId,
parentMessageId,
isCreatedByUser,
sender: isCreatedByUser ? 'User' : 'Assistant',
text: isCreatedByUser
? `Show example ${index}`
: `Settled example ${index}\n\n\`\`\`python\nprint(${index})\n\`\`\``,
});
parentMessageId = messageId;
}
try {
await seedConversations(userEmail, [
{ conversationId, title: 'Idle animations', updatedAt: new Date() },
]);
await seedMessages(userEmail, conversationId, messages);
await page.goto(`/c/${conversationId}`);
const rows = page.locator('.message-render');
await expect(rows).toHaveCount(messages.length);
for (let index = 1; index < messages.length; index += 2) {
await expect(
rows.nth(index).getByRole('button', { name: 'Run Code', exact: true }).first(),
).toBeAttached();
}
/** Finite entrance transitions are allowed; opacity-hidden infinite loops are not. */
await expect
.poll(
() =>
rows.evaluateAll((elements) =>
elements.flatMap((element) =>
element
.getAnimations({ subtree: true })
.filter(
(animation) =>
animation.playState === 'running' &&
animation.effect?.getTiming().iterations === Infinity,
)
.map((animation) => ({
animation:
animation instanceof CSSAnimation ? animation.animationName : animation.id,
target: (animation.effect as KeyframeEffect | null)?.target?.outerHTML.slice(
0,
250,
),
})),
),
),
{
message:
'Idle transcript must not continuously animate, including invisible descendants',
},
)
.toEqual([]);
} finally {
await deleteMessagesByConversation([conversationId]);
await deleteConversations([conversationId]);
}
});
}