From d603bfff0f895f58ef94bdaeaf29cf65a3e2a000 Mon Sep 17 00:00:00 2001 From: Marco Beretta <81851188+berry-13@users.noreply.github.com> Date: Sat, 14 Nov 2026 20:28:41 +0100 Subject: [PATCH] =?UTF-8?q?=F0=9F=92=AD=20refactor:=20Move=20the=20Reasoni?= =?UTF-8?q?ng,=20Thinking=20and=20Web=20Search=20Parts=20Into=20@librechat?= =?UTF-8?q?/chat=20(#18147)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - refactor: Move Reasoning Parts into the Chat Package - fix: Lay Out the Web Search Details Button as a Flex Item - test: Cover Part Disclosures and the Styles They Ship With - test: Cover a Consumer Opening a Thought With the Package Styles - fix: Size the Web Search Row Button by Its Content - test: Hold the Part Motion and Peek Fade to Their Old Inline Styles --- .github/guard-specs.json | 7 + .../src/Providers/MessagePartsHostContext.tsx | 2 + .../Chat/Messages/Content/MessageContent.tsx | 2 +- .../Parts/__tests__/ReasoningMarker.test.tsx | 33 -- .../Parts/__tests__/Thinking.stream.spec.tsx | 13 + .../Content/Parts/__tests__/Thinking.test.tsx | 51 -- .../Chat/Messages/Content/Parts/index.ts | 6 +- .../Chat/Messages/Content/WebSearch.tsx | 445 ++-------------- .../Content/__tests__/WebSearch.test.tsx | 31 +- .../Chat/Messages/Content/sources.ts | 78 +-- client/src/components/Web/SourceHovercard.tsx | 6 +- .../mock/scenarios/part-disclosures.spec.ts | 361 +++++++++++++ eslint-suppressions.json | 21 - eslint.config.mjs | 2 + package-lock.json | 1 + packages/chat/package.json | 1 + packages/chat/src/components.ts | 27 + .../chat/src/components/parts}/Reasoning.tsx | 153 +++--- .../chat/src/components/parts}/Thinking.tsx | 133 +++-- .../chat/src/components/parts/WebSearch.tsx | 498 ++++++++++++++++++ .../parts/__tests__/ReasoningCompact.spec.tsx | 78 ++- .../parts/__tests__/ReasoningMarker.spec.tsx | 29 + .../parts/__tests__/Thinking.spec.tsx | 80 +++ .../parts/__tests__/WebSearch.spec.tsx | 129 +++++ packages/chat/src/components/parts/classes.ts | 11 + packages/chat/src/components/parts/sources.ts | 77 +++ packages/chat/src/react/host.tsx | 5 + packages/chat/test/consumer.spec.tsx | 28 + packages/client/src/components/Button.tsx | 16 + packages/client/src/theme/disclosure.spec.ts | 77 +++ packages/client/src/theme/parts.css | 49 ++ 31 files changed, 1638 insertions(+), 812 deletions(-) delete mode 100644 client/src/components/Chat/Messages/Content/Parts/__tests__/ReasoningMarker.test.tsx create mode 100644 client/src/components/Chat/Messages/Content/Parts/__tests__/Thinking.stream.spec.tsx delete mode 100644 client/src/components/Chat/Messages/Content/Parts/__tests__/Thinking.test.tsx create mode 100644 e2e/specs/mock/scenarios/part-disclosures.spec.ts rename {client/src/components/Chat/Messages/Content/Parts => packages/chat/src/components/parts}/Reasoning.tsx (79%) rename {client/src/components/Chat/Messages/Content/Parts => packages/chat/src/components/parts}/Thinking.tsx (80%) create mode 100644 packages/chat/src/components/parts/WebSearch.tsx rename client/src/components/Chat/Messages/Content/Parts/__tests__/ReasoningCompact.test.tsx => packages/chat/src/components/parts/__tests__/ReasoningCompact.spec.tsx (60%) create mode 100644 packages/chat/src/components/parts/__tests__/ReasoningMarker.spec.tsx create mode 100644 packages/chat/src/components/parts/__tests__/Thinking.spec.tsx create mode 100644 packages/chat/src/components/parts/__tests__/WebSearch.spec.tsx create mode 100644 packages/chat/src/components/parts/classes.ts create mode 100644 packages/chat/src/components/parts/sources.ts create mode 100644 packages/client/src/theme/disclosure.spec.ts diff --git a/.github/guard-specs.json b/.github/guard-specs.json index f13cbb56a0..4428be6540 100644 --- a/.github/guard-specs.json +++ b/.github/guard-specs.json @@ -94,6 +94,13 @@ "packages/client/src/theme/parts.css", "packages/chat/src/components/composer/Palette.tsx" ], + "packages/client/src/theme/disclosure.spec.ts": [ + "client/src/style.css", + "packages/client/src/", + "packages/chat/src/components/parts/Reasoning.tsx", + "packages/chat/src/components/parts/Thinking.tsx", + "packages/chat/src/components/parts/WebSearch.tsx" + ], "packages/client/src/theme/primitives.spec.ts": [ "eslint-suppressions.json", "packages/client/src/components/" diff --git a/client/src/Providers/MessagePartsHostContext.tsx b/client/src/Providers/MessagePartsHostContext.tsx index 5b68510ab6..311ff42713 100644 --- a/client/src/Providers/MessagePartsHostContext.tsx +++ b/client/src/Providers/MessagePartsHostContext.tsx @@ -44,6 +44,7 @@ import ToolIcon, { getToolIconType } from '~/components/Chat/Messages/Content/To import { getToolCallAttachments } from '~/components/Chat/Messages/Content/toolCallAttachment'; import ProgressText from '~/components/Chat/Messages/Content/ProgressText'; import ToolCallInfo from '~/components/Chat/Messages/Content/ToolCallInfo'; +import { AnimatedText } from '~/components/Chat/Messages/Content/animate'; import useSmoothStreaming from '~/hooks/Messages/useSmoothStreaming'; import { ptcTraceByToolCallId, ptcTraceKey } from '~/hooks/SSE/ptc'; import { sandboxStartingByToolCallId } from '~/hooks/SSE/sandbox'; @@ -176,6 +177,7 @@ function useAppToolCallChrome(): ToolCallChrome { export const appMessagePartsHost: MessagePartsHost = { useMessage: useAppMessage, renderMarkdown: (props) => getAppPartRenderers().renderMarkdown(props), + renderStreamingText: (text) => , renderImage: (props) => getAppPartRenderers().renderImage(props), renderFilePreview: (props) => getAppPartRenderers().renderFilePreview(props), useSmoothStreaming, diff --git a/client/src/components/Chat/Messages/Content/MessageContent.tsx b/client/src/components/Chat/Messages/Content/MessageContent.tsx index 01b11764a5..e624418af5 100644 --- a/client/src/components/Chat/Messages/Content/MessageContent.tsx +++ b/client/src/components/Chat/Messages/Content/MessageContent.tsx @@ -1,4 +1,5 @@ import { memo, Suspense, useMemo } from 'react'; +import { Thinking } from '@librechat/chat/components'; import { Alert, DelayedRender } from '@librechat/client'; import { Constants, parseThinkingContent } from 'librechat-data-provider'; import { @@ -16,7 +17,6 @@ import Error from '~/components/Messages/Content/Error'; import { useLocalize, useOnline } from '~/hooks'; import MarkdownLite from './MarkdownLite'; import EditMessage from './EditMessage'; -import Thinking from './Parts/Thinking'; import Markdown from './Markdown'; import { cn } from '~/utils'; diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/ReasoningMarker.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/ReasoningMarker.test.tsx deleted file mode 100644 index bc1009c001..0000000000 --- a/client/src/components/Chat/Messages/Content/Parts/__tests__/ReasoningMarker.test.tsx +++ /dev/null @@ -1,33 +0,0 @@ -import React from 'react'; -import { render, screen } from '@testing-library/react'; -import { ReasoningMarker } from '../Reasoning'; - -jest.mock('~/hooks', () => ({ - useLocalize: () => (key: string) => key, -})); - -jest.mock('../Thinking', () => ({ - ThinkingLabel: ({ label, title }: { label: string; title?: string }) => ( -
- {label} -
- ), -})); - -describe('ReasoningMarker', () => { - it('shows the generated label for reasoning this view cannot show', () => { - render(); - - const marker = screen.getByTestId('thinking-label'); - expect(marker).toHaveTextContent('Planning the answer'); - expect(marker).toHaveAttribute('title', 'com_ui_thoughts_unavailable'); - }); - - it('shows a neutral encrypted state and ignores any label', () => { - render(); - - const marker = screen.getByTestId('thinking-label'); - expect(marker).toHaveTextContent('com_ui_reasoning_encrypted'); - expect(marker).toHaveAttribute('title', 'com_ui_reasoning_encrypted_description'); - }); -}); diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/Thinking.stream.spec.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/Thinking.stream.spec.tsx new file mode 100644 index 0000000000..93def997ac --- /dev/null +++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/Thinking.stream.spec.tsx @@ -0,0 +1,13 @@ +import { render, screen } from '@testing-library/react'; +import { ThinkingContent } from '@librechat/chat/components'; +import '~/Providers/MessagePartsHostContext'; + +/** The app host, registered by importing it, is what fades a live reasoning stream. */ +describe('app reasoning stream', () => { + it('fades streaming reasoning through the registered host', () => { + const text = 'Hello there'; + render({text}); + expect(document.querySelector('[data-lc-fade]')).not.toBeNull(); + expect(screen.getByText(/Hello/)).toBeInTheDocument(); + }); +}); diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/Thinking.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/Thinking.test.tsx deleted file mode 100644 index 5791ed056f..0000000000 --- a/client/src/components/Chat/Messages/Content/Parts/__tests__/Thinking.test.tsx +++ /dev/null @@ -1,51 +0,0 @@ -import React from 'react'; -import { render, screen } from '@testing-library/react'; -import { ThinkingButton, ThinkingLabel } from '../Thinking'; - -jest.mock('~/hooks', () => ({ - useLocalize: () => (key: string) => key, -})); - -jest.mock('@librechat/chat/components', () => ({ - ...jest.requireActual('@librechat/chat/components'), - CopyButton: () => - - - -
- {query && ( -
-
- {localize('com_ui_search_query')} -
-
{query}
-
- )} -
- {localize( - sourceCount === 1 ? 'com_ui_web_search_source' : 'com_ui_web_search_sources', - { count: sourceCount }, - )} -
- {answerBox && (answerBox.title || answerText) && ( -
- {answerBox.title && ( -
{answerBox.title}
- )} - {answerText && ( -
- {answerText} -
- )} -
- )} -
-
-
- - ); - - return ( -
- - {completedText} - -
- {!bare && ( - - )} - {hasDetails && !bare && details} - {hasDetails && inHeader && headerSlot && createPortal(details, headerSlot)} -
- {hasSourceData && ( -
-
- {shouldRenderBody && ( -
- {allSources.map((source, i) => { - const domain = getCleanDomain(source.link); - const snippet = 'snippet' in source ? source.snippet : undefined; - return ( - 0 && 'border-border-light border-t', - )} - > - - - - {source.title || domain} - - {snippet && ( - - {snippet} - - )} - - - {domain} - {source.date && ( - - {source.date} - - )} - - - ); - })} -
- )} -
-
- )} - {!hideAttachments && } -
- ); - } - return ( -
- - {genericProgressText} - - - {progressText} -
+ ( + + )} + renderStackedFavicons={({ sources, start }) => ( + + )} + renderVerticals={(verticalAttachments) => ( + + )} + renderFailedCall={(failed) => } + /> ); } diff --git a/client/src/components/Chat/Messages/Content/__tests__/WebSearch.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/WebSearch.test.tsx index e49949fb59..299a9a8158 100644 --- a/client/src/components/Chat/Messages/Content/__tests__/WebSearch.test.tsx +++ b/client/src/components/Chat/Messages/Content/__tests__/WebSearch.test.tsx @@ -33,21 +33,22 @@ jest.mock('~/hooks', () => ({ }, })); -jest.mock('@librechat/chat/components', () => ({ - ...jest.requireActual('@librechat/chat/components'), - useExpandCollapse: (isExpanded: boolean) => ({ - style: { - display: 'grid', - gridTemplateRows: isExpanded ? '1fr' : '0fr', - opacity: isExpanded ? 1 : 0, - }, - ref: { current: null }, - }), -})); - -jest.mock('@librechat/chat/react', () => ({ - ...jest.requireActual('@librechat/chat/react'), - useProgress: (progress: number) => progress, +jest.mock('@librechat/client', () => ({ + ...jest.requireActual('@librechat/client'), + useLocalize: () => (key: string, values?: Record) => { + const translations: Record = { + com_ui_web_searching: 'Searching the web', + com_ui_web_searching_again: 'Searching again', + com_ui_web_search_processing: 'Processing results', + com_ui_web_search_reading: 'Reading sources', + com_ui_web_searched: 'Searched the web', + com_ui_web_search_source: `${values?.count ?? 1} source`, + com_ui_web_search_sources: `${values?.count ?? 0} sources`, + com_ui_web_search_details: 'Search details', + com_ui_search_query: 'Query', + }; + return translations[key] || key; + }, })); jest.mock('~/hooks/MCP', () => ({ diff --git a/client/src/components/Chat/Messages/Content/sources.ts b/client/src/components/Chat/Messages/Content/sources.ts index a4f9627b5f..bd81b70aac 100644 --- a/client/src/components/Chat/Messages/Content/sources.ts +++ b/client/src/components/Chat/Messages/Content/sources.ts @@ -1,72 +1,6 @@ -import { Tools } from 'librechat-data-provider'; -import type { TAttachment, ValidSource, SearchResultData } from 'librechat-data-provider'; -import { getCleanDomain } from '~/components/Web/SourceHovercard'; - -/** Every distinct source across the given search turns, last write wins per link. */ -export function collectSources(results: Record): ValidSource[] { - const sourceMap = new Map(); - for (const result of Object.values(results)) { - if (!result) { - continue; - } - result.organic?.forEach((s) => { - if (s.link) { - sourceMap.set(s.link, s); - } - }); - result.topStories?.forEach((s) => { - if (s.link) { - sourceMap.set(s.link, s); - } - }); - } - return Array.from(sourceMap.values()); -} - -/** The first `max` sources with distinct domains, in result order. */ -export function getUniqueDomainSources(sources: ValidSource[], max: number): ValidSource[] { - const seen = new Set(); - const result: ValidSource[] = []; - for (const source of sources) { - const domain = getCleanDomain(source.link); - if (seen.has(domain)) { - continue; - } - seen.add(domain); - result.push(source); - if (result.length >= max) { - break; - } - } - return result; -} - -const NO_DOMAINS: string[] = []; - -/** - * The domains a collapsed header can show in place of the generic search - * glyph. A header stands for rows it hides, so it should carry the most - * specific glyph those rows show — for a web search, the sites it read. - * Only ownership-filtered attachments qualify, including live SSE snapshots. - * Message-wide search context is derived from those same attachments but loses - * call/agent/step ownership. Repeated turn numbers are local to each owner. - * Returns a shared empty array when there are none, so a memoized consumer - * does not see a new value on every attachment churn. - */ -export function getSourceDomains(attachments: TAttachment[] | undefined, max: number): string[] { - const turns: Record = {}; - for (const attachment of attachments ?? []) { - const data = attachment.type === Tools.web_search ? attachment[Tools.web_search] : undefined; - if (data != null) { - const owner = JSON.stringify([ - attachment.toolCallId, - attachment.agentId, - attachment.stepId, - data.turn ?? 0, - ]); - turns[owner] = data; - } - } - const sources = getUniqueDomainSources(collectSources(turns), max); - return sources.length === 0 ? NO_DOMAINS : sources.map((source) => getCleanDomain(source.link)); -} +export { + collectSources, + getCleanDomain, + getSourceDomains, + getUniqueDomainSources, +} from '@librechat/chat/components'; diff --git a/client/src/components/Web/SourceHovercard.tsx b/client/src/components/Web/SourceHovercard.tsx index 756d5b99d5..9fb4016af2 100644 --- a/client/src/components/Web/SourceHovercard.tsx +++ b/client/src/components/Web/SourceHovercard.tsx @@ -3,6 +3,7 @@ import * as Ariakit from '@ariakit/react'; import { Button } from '@librechat/client'; import { VisuallyHidden } from '@ariakit/react'; import { ChevronDown, FileText } from 'lucide-react'; +import { getCleanDomain } from '@librechat/chat/components'; import { useLocalize } from '~/hooks'; import { cn } from '~/utils'; @@ -30,10 +31,7 @@ function getFaviconUrl(domain: string) { return `https://www.google.com/s2/favicons?domain=${domain}&sz=32`; } -export function getCleanDomain(url: string) { - const domain = url.replace(/(^\w+:|^)\/\//, '').split('/')[0]; - return domain.startsWith('www.') ? domain.substring(4) : domain; -} +export { getCleanDomain }; export function FaviconImage({ domain, className = '' }: { domain: string; className?: string }) { return ( diff --git a/e2e/specs/mock/scenarios/part-disclosures.spec.ts b/e2e/specs/mock/scenarios/part-disclosures.spec.ts new file mode 100644 index 0000000000..4fe39809d2 --- /dev/null +++ b/e2e/specs/mock/scenarios/part-disclosures.spec.ts @@ -0,0 +1,361 @@ +import { expect, test } from '@playwright/test'; +import type { Locator, Page, Route } from '@playwright/test'; +import { + MOCK_ENDPOINTS, + NEW_CHAT_PATH, + messagesView, + selectMockEndpoint, + sendMessageAndWaitForCompletion, + thinkPrompt, + thinkText, +} from '../helpers'; + +/** + * The thought and web search disclosures open and close on a shared grid-rows transition. These + * scenarios cover what a reader does with them: fold a thought with motion reduced, open a + * finished search's sources and details, and see the panel motion and the live peek's edge fade + * the way they were drawn before they moved into the shared stylesheet. Search and grouped-thought + * conversations are routed fixtures. + */ +test.describe.configure({ timeout: 120_000 }); + +type Part = Record; + +const NO_PARENT = '00000000-0000-0000-0000-000000000000'; +const DONE = 'Part disclosures fixture done.'; +const QUERY = 'css view transitions support'; +const unique = (prefix: string) => `${prefix}-${Date.now()}-${Math.floor(Math.random() * 1e6)}`; +const escapeRe = (value: string) => value.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); + +/** Serves a one-reply conversation made of `content`, and opens it. */ +async function openConversation(page: Page, content: Part[], attachments: Part[] = []) { + const conversationId = unique('e2e-part-disclosures'); + const now = new Date(0).toISOString(); + const messageId = `${conversationId}-msg`; + const message = { + messageId, + conversationId, + parentMessageId: NO_PARENT, + isCreatedByUser: false, + sender: 'Assistant', + endpoint: 'Mock Provider A', + model: 'mock-model-a', + text: '', + content: [...content, { type: 'text', text: DONE }], + attachments: attachments.map((attachment) => ({ ...attachment, messageId })), + createdAt: now, + updatedAt: now, + }; + const conversation = { + conversationId, + title: 'Part disclosures', + endpoint: 'Mock Provider A', + endpointType: 'custom', + model: 'mock-model-a', + createdAt: now, + updatedAt: now, + }; + const convoIdRe = escapeRe(conversationId); + await page.route(new RegExp(`/api/convos/${convoIdRe}(?:\\?.*)?$`), (route: Route) => + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify(conversation), + }), + ); + await page.route(new RegExp(`/api/messages/${convoIdRe}(?:\\?.*)?$`), (route: Route) => + route.fulfill({ + status: 200, + contentType: 'application/json', + body: JSON.stringify([message]), + }), + ); + await page.goto(`/c/${conversationId}`, { timeout: 30000 }); + await expect(messagesView(page).getByText(DONE)).toBeVisible({ timeout: 20000 }); +} + +const finishedSearch: Part[] = [ + { + type: 'tool_call', + tool_call: { + id: 's1', + name: 'web_search', + args: JSON.stringify({ query: QUERY }), + output: 'results', + progress: 1, + type: 'tool_call', + runStepStatus: 'completed', + }, + }, +]; + +const searchSources: Part[] = [ + { + type: 'web_search', + toolCallId: 's1', + web_search: { + turn: 0, + organic: [{ link: 'https://developer.mozilla.org/', title: 'MDN on view transitions' }], + topStories: [], + }, + }, +]; + +/** A command and a thought under one generated title, so the thought is a row in the group. */ +const groupedThought: Part[] = [ + { + type: 'tool_call', + tool_call: { + id: 'g1', + name: 'bash_tool', + args: '{"command":"echo hi"}', + output: 'hi', + progress: 1, + type: 'tool_call', + runStepStatus: 'completed', + }, + }, + { type: 'activity_label', activity_label: 'Checked the command', pending: false }, + { type: 'think', think: 'Checking whether the output matches' }, +]; + +const EXPAND = + 'grid-template-rows 0.3s cubic-bezier(0.16, 1, 0.3, 1), opacity 0.3s cubic-bezier(0.16, 1, 0.3, 1)'; +const REDUCED = 'grid-template-rows 0.01ms linear, opacity 0.01ms linear'; +const PANEL_PROPS = [ + 'display', + 'grid-template-rows', + 'height', + 'opacity', + 'transition-property', + 'transition-duration', + 'transition-timing-function', + 'transition-delay', +]; + +/** The inline style a disclosure panel carried before its motion moved into the shared stylesheet. */ +const inlinePanel = (open: boolean, reduced = false) => + `display: grid; grid-template-rows: ${open ? '1fr' : '0fr'}; opacity: ${open ? 1 : 0}; ` + + `transition: ${reduced ? REDUCED : EXPAND}`; + +const FADE = + 'linear-gradient(to bottom, transparent, black 1.25rem, black calc(100% - 1.25rem), transparent)'; +const PEEK_PROPS = ['mask-image', '-webkit-mask-image']; + +/** The inline style the live peek carried before its edge fade moved into the shared stylesheet. */ +const inlinePeek = `mask-image: ${FADE}; -webkit-mask-image: ${FADE}`; + +/** + * The element's computed values for `props`, the values its own subtree gets when `inline` styles + * it in place of the stylesheet class in `retired`, and the stylesheet rules that match the element + * and set one of them: what the app's stylesheet would have to be changing, if the two differ. + */ +function againstInline(locator: Locator, inline: string, props: string[], retired: string[]) { + return locator.evaluate( + (node, { inline: style, props: names, retired: classNames }) => { + const read = (element: Element) => + Object.fromEntries( + names.map((name) => [name, getComputedStyle(element).getPropertyValue(name)]), + ); + const probe = node.cloneNode(true) as HTMLElement; + probe.classList.remove(...classNames); + probe.removeAttribute('data-expanded'); + probe.style.cssText = style; + node.parentElement?.appendChild(probe); + const expected = read(probe); + probe.remove(); + + const rules: string[] = []; + const walk = (list: CSSRuleList) => { + for (const rule of Array.from(list)) { + if (rule instanceof CSSStyleRule) { + try { + if ( + /\b(display|opacity|transition|grid-template|mask)/.test(rule.style.cssText) && + node.matches(rule.selectorText) + ) { + rules.push(`${rule.selectorText} { ${rule.style.cssText} }`); + } + } catch { + /* a selector this engine cannot match against an element */ + } + } else if ( + 'cssRules' in rule && + (!(rule instanceof CSSMediaRule) || window.matchMedia(rule.conditionText).matches) + ) { + walk((rule as CSSGroupingRule).cssRules); + } + } + }; + for (const sheet of Array.from(document.styleSheets)) { + try { + walk(sheet.cssRules); + } catch { + /* a sheet from another origin cannot be read */ + } + } + return { actual: read(node), expected, rules }; + }, + { inline, props, retired }, + ); +} + +/** Waits out the panel's own transition, then holds it to the old inline style, rows and all. */ +async function expectPanelAsBefore(panel: Locator, open: boolean, reduced = false) { + const compare = () => + againstInline(panel, inlinePanel(open, reduced), PANEL_PROPS, ['part-expand']); + let last = await compare(); + try { + await expect + .poll( + async () => { + last = await compare(); + return JSON.stringify(last.actual) === JSON.stringify(last.expected); + }, + { timeout: 5_000 }, + ) + .toBe(true); + } catch (error) { + expect(last.actual, `rules that match the panel:\n${last.rules.join('\n')}`).toEqual( + last.expected, + ); + throw error; + } + expect(last.actual.opacity).toBe(open ? '1' : '0'); +} + +test.describe('part disclosures', () => { + test('a reader who prefers reduced motion folds a thought and its text leaves the page @scenario:reduced-motion-fold-removes-thought-text', async ({ + page, + }) => { + const label = unique('reduced-fold'); + await page.emulateMedia({ reducedMotion: 'reduce' }); + await page.addInitScript(() => { + window.localStorage.setItem('showThinking', 'true'); + }); + await page.goto(NEW_CHAT_PATH, { timeout: 10_000 }); + await selectMockEndpoint(page, MOCK_ENDPOINTS[0]); + await sendMessageAndWaitForCompletion(page, thinkPrompt(label)); + + const message = messagesView(page).locator('.message-render').last(); + const header = message.getByRole('button', { name: /Thoughts/ }).first(); + const thought = message.getByText(thinkText(label)); + await expect(header).toHaveAttribute('aria-expanded', 'true', { timeout: 15_000 }); + await expect(thought).toBeVisible(); + + await header.click(); + await expect(header).toHaveAttribute('aria-expanded', 'false'); + await expect(thought).toHaveCount(0); + + await header.click(); + await expect(header).toHaveAttribute('aria-expanded', 'true'); + await expect(thought).toBeVisible(); + }); + + test('a finished web search opens its sources, and its details show on focus @scenario:finished-web-search-opens-sources-and-shows-details-on-focus', async ({ + page, + }) => { + await openConversation(page, finishedSearch, searchSources); + const view = messagesView(page); + const row = view.getByRole('button', { name: /Searched the web/ }).first(); + const source = view.getByRole('link', { name: /MDN on view transitions/ }); + await expect(row).toBeVisible(); + if ((await row.getAttribute('aria-expanded')) === 'true') { + await row.click(); + await expect(source).toHaveCount(0); + } + + await row.click(); + await expect(row).toHaveAttribute('aria-expanded', 'true'); + await expect(source).toBeVisible(); + await expect(source).toHaveAttribute('href', 'https://developer.mozilla.org/'); + + await row.press('Enter'); + await expect(row).toHaveAttribute('aria-expanded', 'false'); + await expect(source).toHaveCount(0); + + const details = view.getByRole('button', { name: 'Search details' }); + const reveal = details.locator('xpath=..'); + /** The row still holds focus from the keyboard toggle, and focus anywhere in the row reveals it. */ + await row.evaluate((node) => node.blur()); + await page.mouse.move(0, 0); + await expect(reveal).toHaveCSS('opacity', '0'); + await details.focus(); + await expect(reveal).toHaveCSS('opacity', '1'); + await expect(page.getByText(QUERY)).toBeVisible(); + }); + + test('the thought panel keeps its motion and the live peek its edge fade under the app stylesheet @scenario:part-styles-survive-the-app-stylesheet', async ({ + page, + }) => { + test.setTimeout(180_000); + const label = unique('cascade'); + await page.addInitScript(() => { + window.localStorage.setItem('showThinking', 'false'); + }); + await page.goto(NEW_CHAT_PATH, { timeout: 10_000 }); + await selectMockEndpoint(page, MOCK_ENDPOINTS[0]); + await sendMessageAndWaitForCompletion(page, thinkPrompt(label)); + + const view = messagesView(page); + const message = view.locator('.message-render').last(); + const header = message.getByRole('button', { name: /Thoughts/ }).first(); + const panel = message.locator('.part-expand').first(); + await expect(header).toHaveAttribute('aria-expanded', 'false'); + await expectPanelAsBefore(panel, false); + + /** + * The live peek draws only while a folded thought streams, and the app folds a streaming + * tail into its own activity card instead. A stand-in with the peek's class goes where the + * peek would sit, among the same ancestors, so the app's stylesheet gets to act on it. + */ + await panel.evaluate((node) => { + const standIn = document.createElement('div'); + standIn.setAttribute('data-testid', 'peek-stand-in'); + standIn.className = 'thought-peek'; + standIn.textContent = 'A thought that fades at its edges'; + node.parentElement?.insertBefore(standIn, node); + }); + const peek = await againstInline(message.getByTestId('peek-stand-in'), inlinePeek, PEEK_PROPS, [ + 'thought-peek', + ]); + expect(peek.actual, `rules that match the peek:\n${peek.rules.join('\n')}`).toEqual( + peek.expected, + ); + expect(peek.actual['mask-image']).toContain('linear-gradient'); + + await header.click(); + await expect(header).toHaveAttribute('aria-expanded', 'true'); + await expectPanelAsBefore(panel, true); + + await page.emulateMedia({ reducedMotion: 'reduce' }); + await expectPanelAsBefore(panel, true, true); + await page.emulateMedia({ reducedMotion: 'no-preference' }); + + /** The same panel inside a search row, and as a row of a tool group, with other ancestors. */ + await openConversation(page, finishedSearch, searchSources); + const row = messagesView(page) + .getByRole('button', { name: /Searched the web/ }) + .first(); + if ((await row.getAttribute('aria-expanded')) !== 'true') { + await row.click(); + } + await expect(row).toHaveAttribute('aria-expanded', 'true'); + await expectPanelAsBefore(messagesView(page).locator('.part-expand').first(), true); + + await openConversation(page, groupedThought); + const group = messagesView(page) + .getByRole('button', { name: /Checked the command/ }) + .first(); + await group.click(); + const thoughts = messagesView(page) + .getByRole('button', { name: /Thoughts/ }) + .last(); + await expect(thoughts).toBeVisible(); + const compact = messagesView(page).locator('.part-expand').last(); + await expectPanelAsBefore(compact, false); + await thoughts.click(); + await expect(thoughts).toHaveAttribute('aria-expanded', 'true'); + await expectPanelAsBefore(compact, true); + }); +}); diff --git a/eslint-suppressions.json b/eslint-suppressions.json index de15eee56b..e28f7132f9 100644 --- a/eslint-suppressions.json +++ b/eslint-suppressions.json @@ -206,14 +206,6 @@ "count": 1 } }, - "client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx": { - "shadcn/no-inline-styles": { - "count": 4 - }, - "shadcn/no-restyle": { - "count": 2 - } - }, "client/src/components/Chat/Messages/Content/Parts/SkillCall.tsx": { "shadcn/no-inline-styles": { "count": 1 @@ -224,11 +216,6 @@ "count": 1 } }, - "client/src/components/Chat/Messages/Content/Parts/Thinking.tsx": { - "shadcn/no-inline-styles": { - "count": 1 - } - }, "client/src/components/Chat/Messages/Content/Parts/WorkspaceChanges.tsx": { "shadcn/no-inline-styles": { "count": 1 @@ -286,14 +273,6 @@ "count": 1 } }, - "client/src/components/Chat/Messages/Content/WebSearch.tsx": { - "shadcn/no-inline-styles": { - "count": 1 - }, - "shadcn/no-restyle": { - "count": 12 - } - }, "client/src/components/Chat/Messages/Content/animate.tsx": { "shadcn/no-inline-styles": { "count": 1 diff --git a/eslint.config.mjs b/eslint.config.mjs index 0aa95a2e03..466cee55b2 100644 --- a/eslint.config.mjs +++ b/eslint.config.mjs @@ -376,6 +376,8 @@ export default [ 'part-fold', 'tool-status-text', 'tool-call-expand', + 'part-expand', + 'thought-peek', 'message-render', 'message-timestamp', 'popover-animate', diff --git a/package-lock.json b/package-lock.json index 7d5a4b99b2..d855afa22b 100644 --- a/package-lock.json +++ b/package-lock.json @@ -43236,6 +43236,7 @@ "name": "@librechat/chat", "version": "0.1.0", "dependencies": { + "copy-to-clipboard": "^3.3.3", "sse.js": "^2.8.0" }, "devDependencies": { diff --git a/packages/chat/package.json b/packages/chat/package.json index 3f493d281c..b3a0910d2e 100644 --- a/packages/chat/package.json +++ b/packages/chat/package.json @@ -81,6 +81,7 @@ "uuid": "^11.1.1" }, "dependencies": { + "copy-to-clipboard": "^3.3.3", "sse.js": "^2.8.0" }, "devDependencies": { diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts index 45f47c8a0e..2955bb7448 100644 --- a/packages/chat/src/components.ts +++ b/packages/chat/src/components.ts @@ -327,3 +327,30 @@ export type { PendingToolApprovalButtonProps, PendingToolApprovalPanelProps, } from './components/approval/Review'; + +/** Reasoning, thinking and web search parts, with the source and viewport helpers they share. */ +export { + default as Thinking, + FloatingThinkingBar, + ThinkingButton, + ThinkingContent, + ThinkingLabel, +} from './components/parts/Thinking'; +export { + default as Reasoning, + ReasoningCompact, + ReasoningMarker, + StreamingThoughtPeek, +} from './components/parts/Reasoning'; +export { default as WebSearch } from './components/parts/WebSearch'; +export type { + WebSearchFailedCall, + WebSearchFaviconProps, + WebSearchStackProps, +} from './components/parts/WebSearch'; +export { + collectSources, + getCleanDomain, + getSourceDomains, + getUniqueDomainSources, +} from './components/parts/sources'; diff --git a/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx b/packages/chat/src/components/parts/Reasoning.tsx similarity index 79% rename from client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx rename to packages/chat/src/components/parts/Reasoning.tsx index b559276dd0..ea5a09f77a 100644 --- a/client/src/components/Chat/Messages/Content/Parts/Reasoning.tsx +++ b/packages/chat/src/components/parts/Reasoning.tsx @@ -1,26 +1,24 @@ -import { memo, useMemo, useState, useEffect, useCallback, useRef, useId } from 'react'; +import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react'; import { useAtom } from 'jotai'; import copy from 'copy-to-clipboard'; -import { Lightbulb, ChevronDown } from 'lucide-react'; -import { Button, disclosureChevronVariants } from '@librechat/client'; +import { ChevronDown, Lightbulb } from 'lucide-react'; import { ContentTypes, readableReasoning } from 'librechat-data-provider'; -import { ROW_GLYPH_SLOT, useExpandCollapse, CopyButton } from '@librechat/chat/components'; +import { Button, disclosureChevronVariants, useLocalize } from '@librechat/client'; +import type { FocusEvent, MouseEvent, NamedExoticComponent } from 'react'; import { - toolPanelSpacingClassName, - useReasoningDisclosure, - useLazyCollapseBody, -} from '@librechat/chat/react'; -import type { MouseEvent, FocusEvent } from 'react'; -import { - ThinkingContent, - ThinkingButton, - ThinkingLabel, FloatingThinkingBar, + ThinkingButton, + ThinkingContent, + ThinkingLabel, useInViewport, } from './Thinking'; -import { useMessagePartsHost } from '~/Providers/MessagePartsHostContext'; -import { useLocalize } from '~/hooks'; -import { cn } from '~/utils'; +import { toolPanelSpacingClassName, useReasoningDisclosure } from '../../react/parts/disclosure'; +import useLazyCollapseBody from '../../react/parts/useLazyCollapseBody'; +import { useMessagePartsHost } from '../../react/host'; +import useExpandCollapse from './useExpandCollapse'; +import { ROW_GLYPH_SLOT } from './rows'; +import CopyButton from './CopyButton'; +import { classes } from './classes'; const stripThinkTags = (reasoning: string): string => reasoning @@ -50,20 +48,6 @@ const lastSentences = (text: string): string => { return sentences.slice(-PEEK_SENTENCES).join(' ').trim(); }; -/** Symmetric top + bottom edge fade so streaming text dissolves in at the - * bottom and out at the top, framed by the same rounded outline the expanded - * panel uses. - * - * Custom-CSS exception, narrowly scoped: this is a `mask-image` stencil, not - * paint. Only the alpha channel is read, so `black` means "keep this pixel" - * and `transparent` means "hide it". The hue never reaches the screen and no - * theme could meaningfully restyle it. Routing it through a theme role would - * invite a token with alpha, which would silently wash out the text the mask - * is supposed to keep. Tailwind has no mask-image utility that expresses a - * four-stop gradient with `calc()` offsets, hence the inline style. */ -const PEEK_FADE = - 'linear-gradient(to bottom, transparent, black 1.25rem, black calc(100% - 1.25rem), transparent)'; - /** * Collapsed live preview of streaming reasoning. Mirrors the expanded thought * panel. It uses the same rounded outline and text treatment, but with a border instead @@ -73,48 +57,51 @@ const PEEK_FADE = * out loud" treatment popularized by Grok). Decorative only (aria-hidden); the * toggle button above it provides the accessible control. */ -export const StreamingThoughtPeek = memo(({ text }: { text: string }) => { - const ref = useRef(null); - const { useFontSize } = useMessagePartsHost(); - const fontSize = useFontSize(); - const peek = useMemo(() => lastSentences(text), [text]); +export const StreamingThoughtPeek: NamedExoticComponent<{ text: string }> = memo( + ({ text }: { text: string }) => { + const ref = useRef(null); + const { useFontSize } = useMessagePartsHost(); + const fontSize = useFontSize(); + const peek = useMemo(() => lastSentences(text), [text]); - /** Pin to the newest content as tokens arrive. `overflow-hidden` elements - * are still scrollable programmatically, so the tail stays in view without - * exposing a scrollbar. */ - useEffect(() => { - const el = ref.current; - if (el) { - el.scrollTop = el.scrollHeight; + /** Pin to the newest content as tokens arrive. `overflow-hidden` elements + * are still scrollable programmatically, so the tail stays in view without + * exposing a scrollbar. */ + useEffect(() => { + const el = ref.current; + if (el) { + el.scrollTop = el.scrollHeight; + } + }, [peek]); + + if (!peek) { + return null; } - }, [peek]); - if (!peek) { - return null; - } - - return ( - - ); -}); + ); + }, +); StreamingThoughtPeek.displayName = 'StreamingThoughtPeek'; @@ -147,10 +134,10 @@ type ReasoningProps = { * * For legacy text-based messages, see Thinking.tsx component. */ -/** Reasoning that happened but whose text this view cannot show — detached +/** Reasoning that happened but whose text this view cannot show: detached * subagent projections keep only a marker, and providers can return reasoning * encrypted. Renders the shared reasoning header row without a disclosure. */ -export const ReasoningMarker = memo( +export const ReasoningMarker: NamedExoticComponent<{ label?: string; encrypted?: boolean }> = memo( ({ label, encrypted = false }: { label?: string; encrypted?: boolean }) => { const localize = useLocalize(); if (encrypted) { @@ -168,7 +155,7 @@ export const ReasoningMarker = memo( ReasoningMarker.displayName = 'ReasoningMarker'; -const Reasoning = memo((props: ReasoningProps) => { +const Reasoning: NamedExoticComponent = memo((props: ReasoningProps) => { const { reasoning, isLast, reasoningLabel, partKeyIndex = 0 } = props; const contentId = useId(); const localize = useLocalize(); @@ -181,7 +168,7 @@ const Reasoning = memo((props: ReasoningProps) => { const [isBarVisible, setIsBarVisible] = useState(false); const containerRef = useRef(null); const { ref: headerRef, inViewport: headerInViewport, recheck: recheckHeader } = useInViewport(); - const { style: expandStyle, ref: expandRef } = useExpandCollapse(isExpanded); + const { ref: expandRef } = useExpandCollapse(isExpanded); const { shouldRenderBody, mountBody, handleTransitionEnd } = useLazyCollapseBody(isExpanded); const { isSubmitting, isLatestMessage, nextType } = useMessage(); const effectiveIsSubmitting = isLatestMessage ? isSubmitting : false; @@ -268,11 +255,12 @@ const Reasoning = memo((props: ReasoningProps) => { role="group" aria-label={label} aria-hidden={!isExpanded || undefined} - style={expandStyle} + className="part-expand" + data-expanded={isExpanded ? 'true' : 'false'} onTransitionEnd={handleTransitionEnd} >
{shouldRenderBody && ( @@ -320,7 +308,7 @@ type ReasoningCompactProps = { * {@link Reasoning} affordances: a hover-revealed copy button on the header and * a floating collapse + copy bar inside the rounded content panel. */ -export const ReasoningCompact = memo( +export const ReasoningCompact: NamedExoticComponent = memo( ({ reasoning, label, @@ -343,7 +331,7 @@ export const ReasoningCompact = memo( inViewport: headerInViewport, recheck: recheckHeader, } = useInViewport(); - const { style: expandStyle, ref: expandRef } = useExpandCollapse(isExpanded); + const { ref: expandRef } = useExpandCollapse(isExpanded); /** Collapsed is the default whenever thoughts are hidden, and a streaming * THINK part re-renders on every delta. Keeping the full text mounted * behind the invisible panel made long reasoning streams progressively @@ -406,14 +394,14 @@ export const ReasoningCompact = memo( onClick={handleToggle} aria-expanded={isExpanded} aria-controls={contentId} - className="group/disclosure text-text-secondary min-w-0 flex-1 font-normal" + className="group/disclosure min-w-0 flex-1" > - {label} + {label}
{shouldRenderBody && (
-

{reasoningText}

+

+ {reasoningText} +

= memo(({ children, animate = false }) => { - const { useFontSize } = useMessagePartsHost(); + const { useFontSize, renderStreamingText } = useMessagePartsHost(); const fontSize = useFontSize(); const content = - animate && typeof children === 'string' ? : children; + animate && typeof children === 'string' + ? (renderStreamingText?.(children) ?? children) + : children; return (
-

{content}

+

{content}

); }); @@ -85,7 +79,21 @@ export const ThinkingContent: FC<{ * Shows lightbulb icon by default, chevron on hover * Shared between legacy Thinking component and modern ContentParts */ -export const ThinkingButton = memo( +type ThinkingButtonProps = { + isExpanded: boolean; + onClick: (e: MouseEvent) => void; + label: string; + content?: string; + contentId: string; + showCopyButton?: boolean; + animateLabel?: boolean; + /** Reasoning is still being generated: carry the same shimmer a running + * tool call's label carries, so "thinking" reads as in-flight rather + * than as a settled disclosure. Off for finished thoughts. */ + shimmerLabel?: boolean; +}; + +export const ThinkingButton: NamedExoticComponent = memo( ({ isExpanded, onClick, @@ -95,19 +103,7 @@ export const ThinkingButton = memo( showCopyButton = true, animateLabel = false, shimmerLabel = false, - }: { - isExpanded: boolean; - onClick: (e: MouseEvent) => void; - label: string; - content?: string; - contentId: string; - showCopyButton?: boolean; - animateLabel?: boolean; - /** Reasoning is still being generated: carry the same shimmer a running - * tool call's label carries, so "thinking" reads as in-flight rather - * than as a settled disclosure. Off for finished thoughts. */ - shimmerLabel?: boolean; - }) => { + }: ThinkingButtonProps) => { const localize = useLocalize(); const [isCopied, setIsCopied] = useState(false); @@ -133,13 +129,13 @@ export const ThinkingButton = memo( * second, larger kind of row beside them. */ className="group/button tool-status-text flex flex-1 items-center justify-start rounded-lg pe-10" > - +