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: () => ,
- useExpandCollapse: () => ({ style: {}, ref: { current: null } }),
-}));
-
-jest.mock('~/store/fontSize', () => ({
- fontSizeAtom: { toString: () => 'fontSizeAtom' },
-}));
-
-jest.mock('jotai', () => ({
- ...jest.requireActual('jotai'),
- useAtomValue: () => 'text-xl',
-}));
-
-/** Every activity row — a tool call, a grouped thought, a phase summary — is
- * set at `tool-status-text`. A reasoning header sized to the reader's body
- * text instead was the one row that grew with that setting, so the same
- * thought read at two sizes depending on which surface held it. */
-describe('reasoning header rows', () => {
- it('sets the thinking disclosure at the shared row scale, not the body size', () => {
- render(
- {}}
- label="Reframing the analysis"
- contentId="thoughts"
- />,
- );
- const button = screen.getByRole('button', { name: 'Reframing the analysis' });
- expect(button).toHaveClass('tool-status-text');
- expect(button).not.toHaveClass('text-xl');
- expect(screen.getByText('Reframing the analysis')).toHaveClass('font-medium');
- });
-
- it('sets the non-interactive marker the same way', () => {
- render( );
- const label = screen.getByText('Thoughts');
- expect(label.parentElement).toHaveClass('tool-status-text');
- expect(label.parentElement).not.toHaveClass('text-xl');
- expect(label).toHaveClass('font-medium');
- });
-});
diff --git a/client/src/components/Chat/Messages/Content/Parts/index.ts b/client/src/components/Chat/Messages/Content/Parts/index.ts
index be649bcccc..bf6e51ad39 100644
--- a/client/src/components/Chat/Messages/Content/Parts/index.ts
+++ b/client/src/components/Chat/Messages/Content/Parts/index.ts
@@ -12,11 +12,11 @@ export {
CollapsibleText,
} from '@librechat/chat/components';
export {
- default as Reasoning,
- ReasoningMarker,
+ Reasoning,
ReasoningCompact,
+ ReasoningMarker,
StreamingThoughtPeek,
-} from './Reasoning';
+} from '@librechat/chat/components';
export { default as LogContent } from './LogContent';
export { default as ExecuteCode } from './ExecuteCode';
export { default as SkillCall } from './SkillCall';
diff --git a/client/src/components/Chat/Messages/Content/WebSearch.tsx b/client/src/components/Chat/Messages/Content/WebSearch.tsx
index b9afe92452..a989b33693 100644
--- a/client/src/components/Chat/Messages/Content/WebSearch.tsx
+++ b/client/src/components/Chat/Messages/Content/WebSearch.tsx
@@ -1,83 +1,21 @@
-import { useMemo, useState, useContext } from 'react';
-import { createPortal } from 'react-dom';
-import { Tools } from 'librechat-data-provider';
-import { parseJsonField } from '@librechat/chat';
-import { ToolCall } from '@librechat/chat/components';
-import { Globe, ChevronDown, Info } from 'lucide-react';
-import { ROW_GLYPH_SLOT, useToolPreparation, useExpandCollapse } from '@librechat/chat/components';
-import {
- Button,
- Shimmer,
- HoverCard,
- HoverCardTrigger,
- HoverCardPortal,
- HoverCardContent,
- disclosureChevronVariants,
-} from '@librechat/client';
-import {
- useRowHandoff,
- GeneratedToolLabelContext,
- useToolExpansion,
- useToolContentRequest,
- toolPanelSpacingClassName,
- useToolCallIntent,
- useLazyCollapseBody,
-} from '@librechat/chat/react';
-import type {
- TAttachment,
- ValidSource,
- SearchResultData,
- PartMetadata,
- AnswerBoxResult,
-} from 'librechat-data-provider';
-import { FaviconImage, getCleanDomain } from '~/components/Web/SourceHovercard';
-import { collectSources, getUniqueDomainSources } from './sources';
+import { useContext } from 'react';
+import { ToolCall, WebSearch as WebSearchPart } from '@librechat/chat/components';
+import type { PartMetadata, TAttachment } from 'librechat-data-provider';
+import { FaviconImage } from '~/components/Web/SourceHovercard';
import { StackedFavicons } from '~/components/Web/Sources';
-import { isError } from './ToolOutput/OutputRenderer';
import { HeaderActionSlotContext } from './slot';
import { useSearchContext } from '~/Providers';
import SearchVerticals from './verticals';
-import { useLocalize } from '~/hooks';
-import cn from '~/utils/cn';
import './toolCallSlots';
-type ProgressKeys =
- | 'com_ui_web_searching'
- | 'com_ui_web_searching_again'
- | 'com_ui_web_search_processing'
- | 'com_ui_web_search_reading';
-
-const MAX_VISIBLE_FAVICONS = 3;
-
-function SourceFaviconStack({ sources }: { sources: ValidSource[] }) {
- const visible = getUniqueDomainSources(sources, MAX_VISIBLE_FAVICONS);
- return (
-
- {visible.map((source, i) => (
-
0 && '-ms-2.5',
- )}
- style={{ zIndex: MAX_VISIBLE_FAVICONS - i }}
- >
-
-
- ))}
-
- );
-}
-
export default function WebSearch({
- initialProgress: progress = 0.1,
- isSubmitting,
isLast,
+ isSubmitting,
args,
output,
+ initialProgress,
attachments,
- hideAttachments = false,
+ hideAttachments,
onExpand,
runStepStatus,
}: {
@@ -91,354 +29,31 @@ export default function WebSearch({
onExpand?: () => void;
runStepStatus?: PartMetadata['runStepStatus'];
}) {
- const localize = useLocalize();
- /** Model-authored live label (web_search carries `intent` natively);
- * persists as the settled label like the other tool cards. */
- const intent = useToolCallIntent(args);
- const preparationText = useToolPreparation();
const { searchResults } = useSearchContext();
- const error = (typeof output === 'string' && isError(output)) || runStepStatus === 'failed';
- const legacyError =
- !error && typeof output === 'string' && output.toLowerCase().includes('error processing');
- const isClosed = runStepStatus != null;
-
- // Server tool calls (srvtoolu_) never receive ON_RUN_STEP_COMPLETED, so progress
- // stays at the default 0.1. Treat the search as complete if attachments have results.
- const hasResults = useMemo(
- () =>
- attachments?.some((att) => att.type === Tools.web_search && att[Tools.web_search]) ?? false,
- [attachments],
- );
- const effectiveProgress = isClosed || (hasResults && !isSubmitting) ? 1 : progress;
- /** Older search errors with only the loose "error processing" text were
- * hidden, not counted as failures. Preserve that legacy behavior rather
- * than labeling them completed; recognized failures get a real disclosure
- * below so the group pill can reach their error. */
- const cancelled = isClosed
- ? runStepStatus === 'cancelled' || legacyError
- : (!isSubmitting && effectiveProgress < 1) || legacyError;
-
- const finalizing = !isClosed && isSubmitting && isLast && effectiveProgress === 1;
- /** A search that is the message's FINAL part stays "finalizing" only while
- * the submission is live — afterwards it must settle like any other call,
- * or the completed label (and its settled intent announcement) never
- * renders and the card shimmers forever. A closed step settles immediately
- * on its own status instead of waiting for the submission to end. */
- const complete = isClosed
- ? !cancelled
- : effectiveProgress === 1 && !finalizing && (!isLast || !isSubmitting);
-
- const ownTurn = useMemo((): string => {
- if (!attachments) {
- return '0';
- }
- for (const att of attachments) {
- if (att.type === Tools.web_search && att[Tools.web_search]) {
- const turn = att[Tools.web_search].turn;
- return typeof turn === 'number' ? String(turn) : '0';
- }
- }
- return '0';
- }, [attachments]);
-
- const allSources = useMemo((): ValidSource[] => {
- if (attachments != null) {
- const turnMap: Record = {};
- for (const att of attachments) {
- if (att.type === Tools.web_search && att[Tools.web_search]) {
- const data = att[Tools.web_search];
- const key = typeof data.turn === 'number' ? String(data.turn) : '0';
- turnMap[key] = data;
- }
- }
- return collectSources(turnMap);
- }
- if (searchResults?.[ownTurn]) {
- return collectSources({ [ownTurn]: searchResults[ownTurn] });
- }
- return [];
- }, [searchResults, attachments, ownTurn]);
-
- /** Direct-answer card shown at the top of the source list. Attachment-only:
- * answer boxes are provider extras (Serper) that never carry citations, so
- * the streaming path does not need them. */
- const answerBox = useMemo((): AnswerBoxResult | undefined => {
- if (!attachments) {
- return undefined;
- }
- for (const att of attachments) {
- const answer = att.type === Tools.web_search ? att[Tools.web_search]?.answerBox : undefined;
- if (answer) {
- return answer;
- }
- }
- return undefined;
- }, [attachments]);
- /** `snippet` and `snippetHighlighted` are independently optional, and
- * `hasDetails` opens the card for ANY answer box, so a provider result
- * carrying only highlights rendered a heading with an empty body. */
- const answerText = useMemo(
- () => answerBox?.snippet || answerBox?.snippetHighlighted?.join(' ') || undefined,
- [answerBox],
- );
-
- // Show favicons from the raw SERP results immediately rather than waiting for
- // each source to flip to `processed`; the agents scrape barrier would otherwise
- // freeze the stack on "Searching the web" for the slowest scrape's duration.
- const streamingSources = useMemo(() => {
- if (complete && !finalizing) {
- return [];
- }
- return allSources;
- }, [allSources, complete, finalizing]);
-
- const showSources = streamingSources.length > 0;
- /** Stable phase text: the live region must not re-announce the growing
- * intent on every delta, so it always gets this value while streaming;
- * the settled intent is announced once via the completed branch. */
- const genericProgressText = useMemo(() => {
- if (preparationText != null) {
- return preparationText;
- }
- let text: ProgressKeys =
- ownTurn !== '0' ? 'com_ui_web_searching_again' : 'com_ui_web_searching';
- if (showSources) {
- text = 'com_ui_web_search_processing';
- }
- if (finalizing) {
- text = 'com_ui_web_search_reading';
- }
- return localize(text);
- }, [ownTurn, localize, showSources, finalizing, preparationText]);
- const progressText = preparationText ?? intent ?? genericProgressText;
-
- const generatedLabel = useContext(GeneratedToolLabelContext);
const headerSlot = useContext(HeaderActionSlotContext);
- const bare = generatedLabel && complete && !error && !cancelled && allSources.length > 0;
- const rowRef = useRowHandoff(bare);
- const sourceCount = allSources.length;
- const [showDetails, setShowDetails] = useState(false);
- useToolContentRequest(showDetails);
- const [expandedSources, setShowSourceList] = useToolExpansion(sourceCount > 0);
- const showSourceList = bare || expandedSources;
- useToolContentRequest(bare);
- const { style: sourceExpandStyle, ref: sourceExpandRef } = useExpandCollapse(showSourceList);
- const { shouldRenderBody, mountBody, handleTransitionEnd } = useLazyCollapseBody(showSourceList);
-
- const handleToggleSources = () => {
- mountBody();
- setShowSourceList(!showSourceList);
- if (!showSourceList) {
- onExpand?.();
- }
- };
-
- if (error && runStepStatus !== 'cancelled') {
- return (
-
- );
- }
-
- if (cancelled) {
- return null;
- }
-
- if (complete) {
- const hasSourceData = sourceCount > 0;
- const completedText = intent ?? localize('com_ui_web_searched');
- const query = parseJsonField(args, 'query');
- const hasDetails = !!query || !!answerBox;
-
- /** A generated title replaced the row, so its action moves to the title line. */
- const inHeader = bare && headerSlot != null;
- const details = (
-
- {/* Composed through `asChild` so the shared Button owns the
- rounding, hover fill, focus ring and motion (and gives a real
- instead of Radix's default anchor). Only the
- hover-card reveal and the icon geometry stay local. */}
-
- setShowDetails(true)}
- onBlur={() => setShowDetails(false)}
- aria-label={localize('com_ui_web_search_details')}
- >
-
-
-
-
-
-
- {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 && (
-
-
- {hasSourceData ? (
-
- ) : (
-
- )}
-
- {completedText}
- {hasSourceData && (
-
- )}
-
- )}
- {hasDetails && !bare && details}
- {hasDetails && inHeader && headerSlot && createPortal(details, headerSlot)}
-
- {hasSourceData && (
-
-
- {shouldRenderBody && (
-
- )}
-
-
- )}
- {!hideAttachments &&
}
-
- );
- }
-
return (
-
-
- {genericProgressText}
-
-
- {showSources && }
-
-
- {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 (
);
});
@@ -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"
>
-
+
{/* The sweep rides the label row itself. That row is a flex item, so
`.shimmer`'s `inline-block` is blockified away and the text sits
- exactly where the un-shimmered label sits — which matters, because
+ exactly where the un-shimmered label sits, which matters, because
an `inline-block` carrying `truncate` takes its baseline from its
bottom margin edge, growing the line box and lifting the label off
the icon's axis.
@@ -185,7 +181,7 @@ export const ThinkingButton = memo(
onClick={handleCopy}
label={localize('com_ui_copy_thoughts_to_clipboard')}
copiedLabel={localize('com_ui_copied_to_clipboard')}
- className={cn(
+ className={classes(
'absolute inset-e-0 top-1/2 -translate-y-1/2 opacity-0 transition-opacity',
'group-focus-within/thinking-container:opacity-100 group-hover/thinking-container:opacity-100',
'focus-visible:opacity-100',
@@ -203,38 +199,38 @@ export const ThinkingButton = memo(
* (detached subagent projections retain only a marker). Keeps the reasoning
* presentation identical across surfaces without offering an empty disclosure.
*/
-export const ThinkingLabel = memo(({ label, title }: { label: string; title?: string }) => {
- return (
-
-
-
-
-
-
{label}
+export const ThinkingLabel: NamedExoticComponent<{ label: string; title?: string }> = memo(
+ ({ label, title }: { label: string; title?: string }) => {
+ return (
+
-
- );
-});
+ );
+ },
+);
/**
* FloatingThinkingBar - Floating bar with expand/collapse and copy buttons
* Shows on hover/focus, positioned at bottom right of thinking content
* Inspired by CodeBlock's FloatingCodeBar pattern
*/
-export const FloatingThinkingBar = memo(
- ({
- isVisible,
- isExpanded,
- onClick,
- content,
- contentId,
- }: {
- isVisible: boolean;
- isExpanded: boolean;
- onClick: (e: MouseEvent
) => void;
- content?: string;
- contentId: string;
- }) => {
+type FloatingThinkingBarProps = {
+ isVisible: boolean;
+ isExpanded: boolean;
+ onClick: (e: MouseEvent) => void;
+ content?: string;
+ contentId: string;
+};
+
+export const FloatingThinkingBar: NamedExoticComponent = memo(
+ ({ isVisible, isExpanded, onClick, content, contentId }: FloatingThinkingBarProps) => {
const localize = useLocalize();
const [isCopied, setIsCopied] = useState(false);
@@ -252,7 +248,7 @@ export const FloatingThinkingBar = memo(
return (
(null);
const { ref: headerRef, inViewport: headerInViewport, recheck: recheckHeader } = useInViewport();
const contentId = useId();
- const { style: expandStyle, ref: expandRef } = useExpandCollapse(isExpanded);
+ const { ref: expandRef } = useExpandCollapse(isExpanded);
const handleClick = useCallback((e: MouseEvent
) => {
e.preventDefault();
@@ -384,7 +380,8 @@ const Thinking: React.ElementType = memo(({ children }: { children: React.ReactN
role="group"
aria-label={label}
aria-hidden={!isExpanded || undefined}
- style={expandStyle}
+ className="part-expand"
+ data-expanded={isExpanded ? 'true' : 'false'}
>
{/** Trailing gap lives inside the animated grid track (padding), not as
* an expand-only margin on the grid container, so it grows with the
diff --git a/packages/chat/src/components/parts/WebSearch.tsx b/packages/chat/src/components/parts/WebSearch.tsx
new file mode 100644
index 0000000000..4ac83e582b
--- /dev/null
+++ b/packages/chat/src/components/parts/WebSearch.tsx
@@ -0,0 +1,498 @@
+import { useContext, useMemo, useState } from 'react';
+import { createPortal } from 'react-dom';
+import { Tools } from 'librechat-data-provider';
+import { ChevronDown, Globe, Info } from 'lucide-react';
+import {
+ Button,
+ HoverCard,
+ HoverCardContent,
+ HoverCardPortal,
+ HoverCardTrigger,
+ Shimmer,
+ disclosureChevronVariants,
+ useLocalize,
+} from '@librechat/client';
+import type {
+ AnswerBoxResult,
+ PartMetadata,
+ SearchResultData,
+ TAttachment,
+ ValidSource,
+} from 'librechat-data-provider';
+import type { ReactNode } from 'react';
+import {
+ GeneratedToolLabelContext,
+ toolPanelSpacingClassName,
+ useToolContentRequest,
+ useToolExpansion,
+} from '../../react/parts/disclosure';
+import { collectSources, getCleanDomain, getUniqueDomainSources } from './sources';
+import useLazyCollapseBody from '../../react/parts/useLazyCollapseBody';
+import { parseJsonField } from '../../core/parts/parseJsonField';
+import { useToolCallIntent } from '../../react/parts/intent';
+import useRowHandoff from '../../react/parts/handoff';
+import useExpandCollapse from './useExpandCollapse';
+import { useToolPreparation } from './preparation';
+import { isError } from '../../core/parts/output';
+import { ROW_GLYPH_SLOT } from './rows';
+import { classes } from './classes';
+
+/** What the app's tool card renders when a search fails. */
+export type WebSearchFailedCall = {
+ name: string;
+ args: string | Record;
+ output?: string | null;
+ initialProgress: number;
+ isSubmitting: boolean;
+ isLast?: boolean;
+ runStepStatus?: PartMetadata['runStepStatus'];
+ attachments?: TAttachment[];
+ hideAttachments?: boolean;
+ onExpand?: () => void;
+};
+
+export type WebSearchFaviconProps = {
+ domain: string;
+ className?: string;
+};
+
+export type WebSearchStackProps = {
+ sources: ValidSource[];
+ start?: number;
+};
+
+type ProgressKeys =
+ | 'com_ui_web_searching'
+ | 'com_ui_web_searching_again'
+ | 'com_ui_web_search_processing'
+ | 'com_ui_web_search_reading';
+
+const MAX_VISIBLE_FAVICONS = 3;
+
+function SourceFaviconStack({
+ sources,
+ renderFavicon,
+}: {
+ sources: ValidSource[];
+ renderFavicon: (props: WebSearchFaviconProps) => ReactNode;
+}) {
+ const visible = getUniqueDomainSources(sources, MAX_VISIBLE_FAVICONS);
+ return (
+
+ {visible.map((source, i) => (
+
0 && '-ms-2.5',
+ )}
+ style={{ zIndex: MAX_VISIBLE_FAVICONS - i }}
+ >
+ {renderFavicon({ domain: getCleanDomain(source.link), className: 'size-3 rounded-full' })}
+
+ ))}
+
+ );
+}
+
+export default function WebSearch({
+ initialProgress: progress = 0.1,
+ isSubmitting,
+ isLast,
+ args,
+ output,
+ attachments,
+ hideAttachments = false,
+ onExpand,
+ runStepStatus,
+ searchResults,
+ headerSlot = null,
+ renderFavicon,
+ renderStackedFavicons,
+ renderVerticals,
+ renderFailedCall,
+}: {
+ isLast?: boolean;
+ isSubmitting: boolean;
+ args?: string | Record;
+ output?: string | null;
+ initialProgress: number;
+ attachments?: TAttachment[];
+ hideAttachments?: boolean;
+ onExpand?: () => void;
+ runStepStatus?: PartMetadata['runStepStatus'];
+ /** Streaming results for this message, used until attachments carry the turn. */
+ searchResults?: { [key: string]: SearchResultData };
+ /** The fold header's action slot, when a generated title replaced this row. */
+ headerSlot?: HTMLElement | null;
+ /** One site's icon. Absent, a finished row with sources keeps the globe. */
+ renderFavicon?: (props: WebSearchFaviconProps) => ReactNode;
+ /** Overlapping icons while results are still arriving. */
+ renderStackedFavicons?: (props: WebSearchStackProps) => ReactNode;
+ /** Image, shopping and place strips under a finished search. */
+ renderVerticals?: (attachments?: TAttachment[]) => ReactNode;
+ /** The app's tool card for a failed search. Absent, a failure renders nothing. */
+ renderFailedCall?: (props: WebSearchFailedCall) => ReactNode;
+}): ReactNode {
+ const localize = useLocalize();
+ /** Model-authored live label (web_search carries `intent` natively);
+ * persists as the settled label like the other tool cards. */
+ const intent = useToolCallIntent(args);
+ const preparationText = useToolPreparation();
+ const error = (typeof output === 'string' && isError(output)) || runStepStatus === 'failed';
+ const legacyError =
+ !error && typeof output === 'string' && output.toLowerCase().includes('error processing');
+ const isClosed = runStepStatus != null;
+
+ // Server tool calls (srvtoolu_) never receive ON_RUN_STEP_COMPLETED, so progress
+ // stays at the default 0.1. Treat the search as complete if attachments have results.
+ const hasResults = useMemo(
+ () =>
+ attachments?.some((att) => att.type === Tools.web_search && att[Tools.web_search]) ?? false,
+ [attachments],
+ );
+ const effectiveProgress = isClosed || (hasResults && !isSubmitting) ? 1 : progress;
+ /** Older search errors with only the loose "error processing" text were
+ * hidden, not counted as failures. Preserve that legacy behavior rather
+ * than labeling them completed; recognized failures get a real disclosure
+ * below so the group pill can reach their error. */
+ const cancelled = isClosed
+ ? runStepStatus === 'cancelled' || legacyError
+ : (!isSubmitting && effectiveProgress < 1) || legacyError;
+
+ const finalizing = !isClosed && isSubmitting && isLast && effectiveProgress === 1;
+ /** A search that is the message's FINAL part stays "finalizing" only while
+ * the submission is live. Afterwards it must settle like any other call,
+ * or the completed label (and its settled intent announcement) never
+ * renders and the card shimmers forever. A closed step settles immediately
+ * on its own status instead of waiting for the submission to end. */
+ const complete = isClosed
+ ? !cancelled
+ : effectiveProgress === 1 && !finalizing && (!isLast || !isSubmitting);
+
+ const ownTurn = useMemo((): string => {
+ if (!attachments) {
+ return '0';
+ }
+ for (const att of attachments) {
+ if (att.type === Tools.web_search && att[Tools.web_search]) {
+ const turn = att[Tools.web_search].turn;
+ return typeof turn === 'number' ? String(turn) : '0';
+ }
+ }
+ return '0';
+ }, [attachments]);
+
+ const allSources = useMemo((): ValidSource[] => {
+ if (attachments != null) {
+ const turnMap: Record = {};
+ for (const att of attachments) {
+ if (att.type === Tools.web_search && att[Tools.web_search]) {
+ const data = att[Tools.web_search];
+ const key = typeof data.turn === 'number' ? String(data.turn) : '0';
+ turnMap[key] = data;
+ }
+ }
+ return collectSources(turnMap);
+ }
+ const turnResults = searchResults?.[ownTurn];
+ if (turnResults) {
+ return collectSources({ [ownTurn]: turnResults });
+ }
+ return [];
+ }, [searchResults, attachments, ownTurn]);
+
+ /** Direct-answer card shown at the top of the source list. Attachment-only:
+ * answer boxes are provider extras (Serper) that never carry citations, so
+ * the streaming path does not need them. */
+ const answerBox = useMemo((): AnswerBoxResult | undefined => {
+ if (!attachments) {
+ return undefined;
+ }
+ for (const att of attachments) {
+ const answer = att.type === Tools.web_search ? att[Tools.web_search]?.answerBox : undefined;
+ if (answer) {
+ return answer;
+ }
+ }
+ return undefined;
+ }, [attachments]);
+ /** `snippet` and `snippetHighlighted` are independently optional, and
+ * `hasDetails` opens the card for ANY answer box, so a provider result
+ * carrying only highlights rendered a heading with an empty body. */
+ const answerText = useMemo(
+ () => answerBox?.snippet || answerBox?.snippetHighlighted?.join(' ') || undefined,
+ [answerBox],
+ );
+
+ // Show favicons from the raw SERP results immediately rather than waiting for
+ // each source to flip to `processed`; the agents scrape barrier would otherwise
+ // freeze the stack on "Searching the web" for the slowest scrape's duration.
+ const streamingSources = useMemo(() => {
+ if (complete && !finalizing) {
+ return [];
+ }
+ return allSources;
+ }, [allSources, complete, finalizing]);
+
+ const showSources = streamingSources.length > 0;
+ /** Stable phase text: the live region must not re-announce the growing
+ * intent on every delta, so it always gets this value while streaming;
+ * the settled intent is announced once via the completed branch. */
+ const genericProgressText = useMemo(() => {
+ if (preparationText != null) {
+ return preparationText;
+ }
+ let text: ProgressKeys =
+ ownTurn !== '0' ? 'com_ui_web_searching_again' : 'com_ui_web_searching';
+ if (showSources) {
+ text = 'com_ui_web_search_processing';
+ }
+ if (finalizing) {
+ text = 'com_ui_web_search_reading';
+ }
+ return localize(text);
+ }, [ownTurn, localize, showSources, finalizing, preparationText]);
+ const progressText = preparationText ?? intent ?? genericProgressText;
+
+ const generatedLabel = useContext(GeneratedToolLabelContext);
+ const bare = generatedLabel && complete && !error && !cancelled && allSources.length > 0;
+ const rowRef = useRowHandoff(bare);
+ const sourceCount = allSources.length;
+ const [showDetails, setShowDetails] = useState(false);
+ useToolContentRequest(showDetails);
+ const [expandedSources, setShowSourceList] = useToolExpansion(sourceCount > 0);
+ const showSourceList = bare || expandedSources;
+ useToolContentRequest(bare);
+ const { ref: sourceExpandRef } = useExpandCollapse(showSourceList);
+ const { shouldRenderBody, mountBody, handleTransitionEnd } = useLazyCollapseBody(showSourceList);
+
+ const handleToggleSources = () => {
+ mountBody();
+ setShowSourceList(!showSourceList);
+ if (!showSourceList) {
+ onExpand?.();
+ }
+ };
+
+ if (error && runStepStatus !== 'cancelled') {
+ return (
+ renderFailedCall?.({
+ name: Tools.web_search,
+ args: args ?? '',
+ output,
+ initialProgress: progress,
+ isSubmitting,
+ isLast,
+ runStepStatus,
+ attachments,
+ hideAttachments,
+ onExpand,
+ }) ?? null
+ );
+ }
+
+ if (cancelled) {
+ return null;
+ }
+
+ if (complete) {
+ const hasSourceData = sourceCount > 0;
+ const completedText = intent ?? localize('com_ui_web_searched');
+ const query = parseJsonField(args, 'query');
+ const hasDetails = !!query || !!answerBox;
+
+ /** A generated title replaced the row, so its action moves to the title line. */
+ const inHeader = bare && headerSlot != null;
+ const details = (
+
+
+ {/* Composed through `asChild` so the shared Button owns the
+ rounding, hover fill, focus ring and motion (and gives a real
+ instead of Radix's default anchor). The reveal lives on
+ the wrapper so the button itself stays a quiet icon control. */}
+
+ setShowDetails(true)}
+ onBlur={() => setShowDetails(false)}
+ aria-label={localize('com_ui_web_search_details')}
+ >
+
+
+
+
+
+
+ {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 && (
+
+
+ {hasSourceData && renderFavicon != null ? (
+
+ ) : (
+
+ )}
+
+ {completedText}
+ {hasSourceData && (
+
+ )}
+
+ )}
+ {hasDetails && !bare && details}
+ {hasDetails && inHeader && headerSlot && createPortal(details, headerSlot)}
+
+ {hasSourceData && (
+
+
+ {shouldRenderBody && (
+
+ )}
+
+
+ )}
+ {!hideAttachments && renderVerticals?.(attachments)}
+
+ );
+ }
+
+ return (
+
+
+ {genericProgressText}
+
+
+ {showSources && renderStackedFavicons?.({ sources: streamingSources, start: -5 })}
+
+
+ {progressText}
+
+ );
+}
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/ReasoningCompact.test.tsx b/packages/chat/src/components/parts/__tests__/ReasoningCompact.spec.tsx
similarity index 60%
rename from client/src/components/Chat/Messages/Content/Parts/__tests__/ReasoningCompact.test.tsx
rename to packages/chat/src/components/parts/__tests__/ReasoningCompact.spec.tsx
index ab816eae3d..ae451cfd63 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/ReasoningCompact.test.tsx
+++ b/packages/chat/src/components/parts/__tests__/ReasoningCompact.spec.tsx
@@ -1,37 +1,20 @@
+/**
+ * @jest-environment jsdom
+ */
import React from 'react';
import { render, screen } from '@testing-library/react';
-import { ROW_GLYPH_SLOT } from '@librechat/chat/components';
+import '@testing-library/jest-dom';
+import type { ReactNode } from 'react';
+import { createMessagePartsHost } from '../../../__fixtures__/partsHost';
+import { MessagePartsHostProvider } from '../../../react/host';
import { ReasoningCompact } from '../Reasoning';
+import { ROW_GLYPH_SLOT } from '../rows';
-jest.mock('~/hooks', () => ({
+jest.mock('@librechat/client', () => ({
+ ...jest.requireActual('@librechat/client'),
useLocalize: () => (key: string) => key,
}));
-jest.mock('@librechat/chat/components', () => ({
- ...jest.requireActual('@librechat/chat/components'),
- CopyButton: () => {'copy'} ,
- useExpandCollapse: (isExpanded: boolean) => ({
- style: { display: 'grid', gridTemplateRows: isExpanded ? '1fr' : '0fr' },
- ref: { current: null },
- }),
-}));
-
-jest.mock('@librechat/chat/react', () => ({
- ...jest.requireActual('@librechat/chat/react'),
- useLazyCollapseBody: (isExpanded: boolean) => ({
- shouldRenderBody: isExpanded,
- mountBody: jest.fn(),
- handleTransitionEnd: jest.fn(),
- }),
-}));
-
-jest.mock('../Thinking', () => ({
- ThinkingContent: ({ children }: { children?: React.ReactNode }) => {children}
,
- ThinkingButton: () => {'thinking'} ,
- FloatingThinkingBar: () => null,
- useInViewport: () => ({ ref: { current: null }, inViewport: true }),
-}));
-
jest.mock('lucide-react', () => ({
Lightbulb: () => ,
ChevronDown: ({ className }: { className?: string }) => (
@@ -39,9 +22,17 @@ jest.mock('lucide-react', () => ({
),
}));
+function renderCompact(node: ReactNode) {
+ return render(
+ {node} ,
+ );
+}
+
describe('ReasoningCompact', () => {
it('always shows its own Thoughts chevron', () => {
- render( );
+ renderCompact(
+ ,
+ );
const button = screen.getByRole('button', { name: 'Thoughts' });
const chevron = screen.getByTestId('thoughts-chevron');
@@ -52,33 +43,28 @@ describe('ReasoningCompact', () => {
});
it('takes the shared glyph slot so it lands on the row rail', () => {
- /** Every other row under a message header centers its glyph in the 24px
- * slot, including the `ThinkingLabel` marker that stands in for this
- * exact row when a projection has no text. Bare, the bulb sat on the
- * pre-rail axis and the label 8px left of its neighbours. */
- render( );
+ renderCompact(
+ ,
+ );
const slot = screen.getByTestId('thoughts-icon').parentElement;
for (const token of ROW_GLYPH_SLOT.split(' ')) {
expect(slot).toHaveClass(token);
}
- /** 24px slot plus the row's 8px gap is what puts the label where the
- * header's name starts. */
expect(screen.getByRole('button', { name: 'Thoughts' })).toHaveClass('gap-2');
});
it('spaces its header like a tool row', () => {
- render( );
+ renderCompact(
+ ,
+ );
const header = screen.getByRole('button', { name: 'Thoughts' }).parentElement;
expect(header).toHaveClass('my-1.5', 'h-5');
});
it('leaves the full reasoning text unmounted while collapsed', () => {
- /** Collapsed is the default whenever thoughts are hidden, and a streaming
- * THINK part re-renders on every delta, so keeping the whole text mounted
- * behind the invisible panel cost layout work for nothing. */
- render(
+ renderCompact(
{
});
it('opens from the host preference rather than the app store', () => {
- render(
- ,
+ renderCompact(
+ ,
);
expect(screen.getByText('A long stream of reasoning')).toBeInTheDocument();
@@ -106,7 +88,7 @@ describe('ReasoningCompact', () => {
const encoded = Buffer.from(Array.from({ length: 900 }, (_, i) => (i * 37 + 3) % 256)).toString(
'base64',
);
- render(
+ renderCompact(
{
const prefix = Buffer.from(Array.from({ length: 75 }, (_, i) => (i * 37 + 3) % 256)).toString(
'base64',
);
- render(
+ renderCompact(
({
+ ...jest.requireActual('@librechat/client'),
+ useLocalize: () => (key: string) => key,
+}));
+
+describe('ReasoningMarker', () => {
+ it('shows the generated label for reasoning this view cannot show', () => {
+ render( );
+
+ const label = screen.getByText('Planning the answer');
+ expect(label.parentElement).toHaveAttribute('title', 'com_ui_thoughts_unavailable');
+ });
+
+ it('shows a neutral encrypted state and ignores any label', () => {
+ render( );
+
+ const label = screen.getByText('com_ui_reasoning_encrypted');
+ expect(label.parentElement).toHaveAttribute('title', 'com_ui_reasoning_encrypted_description');
+ expect(screen.queryByText('Inspecting an encoded data snapshot')).not.toBeInTheDocument();
+ });
+});
diff --git a/packages/chat/src/components/parts/__tests__/Thinking.spec.tsx b/packages/chat/src/components/parts/__tests__/Thinking.spec.tsx
new file mode 100644
index 0000000000..6010edece5
--- /dev/null
+++ b/packages/chat/src/components/parts/__tests__/Thinking.spec.tsx
@@ -0,0 +1,80 @@
+/**
+ * @jest-environment jsdom
+ */
+import React from 'react';
+import { render, screen } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import { ThinkingButton, ThinkingContent, ThinkingLabel } from '../Thinking';
+import { createMessagePartsHost } from '../../../__fixtures__/partsHost';
+import { MessagePartsHostProvider } from '../../../react/host';
+
+jest.mock('@librechat/client', () => ({
+ ...jest.requireActual('@librechat/client'),
+ useLocalize: () => (key: string) => key,
+}));
+
+/** Every activity row is set at `tool-status-text`. A reasoning header sized to the reader's
+ * body text was the one row that grew with that setting. */
+describe('reasoning header rows', () => {
+ it('sets the thinking disclosure at the shared row scale, not the body size', () => {
+ render(
+ undefined}
+ label="Reframing the analysis"
+ contentId="thoughts"
+ />,
+ );
+ const button = screen.getByRole('button', { name: 'Reframing the analysis' });
+ expect(button).toHaveClass('tool-status-text');
+ expect(button).not.toHaveClass('text-xl');
+ expect(screen.getByText('Reframing the analysis')).toHaveClass('font-medium');
+ });
+
+ it('sets the non-interactive marker the same way', () => {
+ render( );
+ const label = screen.getByText('Thoughts');
+ expect(label.parentElement).toHaveClass('tool-status-text');
+ expect(label.parentElement).not.toHaveClass('text-xl');
+ expect(label).toHaveClass('font-medium');
+ });
+});
+
+describe('ThinkingContent', () => {
+ it('shows plain text when the host does not animate a stream', () => {
+ render(
+
+ Checking the manifest
+ ,
+ );
+ expect(screen.getByText('Checking the manifest')).toBeInTheDocument();
+ expect(document.querySelector('[data-lc-fade]')).toBeNull();
+ });
+
+ it('hands a streaming string to the host renderer', () => {
+ render(
+ {text} ,
+ })}
+ >
+ Checking the manifest
+ ,
+ );
+ expect(screen.getByTestId('streamed')).toHaveTextContent('Checking the manifest');
+ });
+
+ it('leaves settled text alone', () => {
+ render(
+ {text} ,
+ })}
+ >
+ Checking the manifest
+ ,
+ );
+ expect(screen.queryByTestId('streamed')).not.toBeInTheDocument();
+ expect(screen.getByText('Checking the manifest')).toBeInTheDocument();
+ });
+});
diff --git a/packages/chat/src/components/parts/__tests__/WebSearch.spec.tsx b/packages/chat/src/components/parts/__tests__/WebSearch.spec.tsx
new file mode 100644
index 0000000000..80f04b7335
--- /dev/null
+++ b/packages/chat/src/components/parts/__tests__/WebSearch.spec.tsx
@@ -0,0 +1,129 @@
+/**
+ * @jest-environment jsdom
+ */
+import React from 'react';
+import { Tools } from 'librechat-data-provider';
+import { fireEvent, render as renderBare, screen } from '@testing-library/react';
+import '@testing-library/jest-dom';
+import type { SearchResultData, TAttachment, ValidSource } from 'librechat-data-provider';
+import type { ReactElement } from 'react';
+import { GeneratedToolLabelContext } from '../../../react/parts/disclosure';
+import { createMessagePartsHost } from '../../../__fixtures__/partsHost';
+import { MessagePartsHostProvider } from '../../../react/host';
+import WebSearch from '../WebSearch';
+
+function render(node: ReactElement) {
+ return renderBare(
+ {node} ,
+ );
+}
+
+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_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',
+ };
+ return translations[key] ?? key;
+ },
+}));
+
+function source(link: string, title: string): ValidSource {
+ return { link, title } as ValidSource;
+}
+
+function attachment(turn: number, organic: ValidSource[]): TAttachment {
+ return {
+ type: Tools.web_search,
+ [Tools.web_search]: { turn, organic } as SearchResultData,
+ } as unknown as TAttachment;
+}
+
+describe('WebSearch', () => {
+ it('shows only the turn its attachments own', () => {
+ render(
+ {domain} }
+ />,
+ );
+
+ fireEvent.click(screen.getByRole('button', { name: /Searched the web/ }));
+ expect(screen.getByRole('link')).toHaveAttribute('href', 'https://pi.example.com/1');
+ expect(screen.queryByRole('link', { name: /Other/ })).not.toBeInTheDocument();
+ });
+
+ it('renders nothing for a legacy search error when no failure card is supplied', () => {
+ const { container } = render(
+ ,
+ );
+ expect(container).toBeEmptyDOMElement();
+ });
+
+ it('asks the host to render a failed call for schema feedback', () => {
+ const renderFailedCall = jest.fn(() =>
);
+ render(
+ ,
+ );
+ expect(renderFailedCall).toHaveBeenCalledWith(
+ expect.objectContaining({
+ name: Tools.web_search,
+ output: expect.stringContaining('Error:'),
+ }),
+ );
+ expect(screen.getByTestId('failed-call')).toBeInTheDocument();
+ });
+
+ it('draws streaming icons through the host and keeps the globe', () => {
+ render(
+ {sources.length} }
+ />,
+ );
+ expect(screen.getByTestId('stacked')).toHaveTextContent('1');
+ });
+
+ it('moves details into the header slot a generated title provides', () => {
+ const slot = document.createElement('span');
+ document.body.appendChild(slot);
+ render(
+
+
+ ,
+ );
+ const details = screen.getByRole('button', { name: 'Search details' });
+ expect(slot).toContainElement(details);
+ expect(details).not.toHaveClass('opacity-0');
+ slot.remove();
+ });
+});
diff --git a/packages/chat/src/components/parts/classes.ts b/packages/chat/src/components/parts/classes.ts
new file mode 100644
index 0000000000..f63b3d8916
--- /dev/null
+++ b/packages/chat/src/components/parts/classes.ts
@@ -0,0 +1,11 @@
+/** Joins class names. Package parts do not call `cn()`, so conditional classes are concatenated. */
+export function classes(...parts: Array): string {
+ let result = '';
+ for (const part of parts) {
+ if (part == null || part === false || part === '') {
+ continue;
+ }
+ result = result === '' ? part : `${result} ${part}`;
+ }
+ return result;
+}
diff --git a/packages/chat/src/components/parts/sources.ts b/packages/chat/src/components/parts/sources.ts
new file mode 100644
index 0000000000..0ff284c1ad
--- /dev/null
+++ b/packages/chat/src/components/parts/sources.ts
@@ -0,0 +1,77 @@
+import { Tools } from 'librechat-data-provider';
+import type { SearchResultData, TAttachment, ValidSource } from 'librechat-data-provider';
+
+/** Host of a result link, without the scheme or a leading `www.`. */
+export function getCleanDomain(url: string): string {
+ const domain = url.replace(/(^\w+:|^)\/\//, '').split('/')[0];
+ return domain.startsWith('www.') ? domain.substring(4) : domain;
+}
+
+/** 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((source) => {
+ if (source.link) {
+ sourceMap.set(source.link, source);
+ }
+ });
+ result.topStories?.forEach((source) => {
+ if (source.link) {
+ sourceMap.set(source.link, source);
+ }
+ });
+ }
+ 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, that is 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 and 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));
+}
diff --git a/packages/chat/src/react/host.tsx b/packages/chat/src/react/host.tsx
index e15409f522..aa8efe039e 100644
--- a/packages/chat/src/react/host.tsx
+++ b/packages/chat/src/react/host.tsx
@@ -204,6 +204,11 @@ export interface MessagePartsHost {
useMessage: () => MessagePartMessage;
/** Renders markdown with the app's renderer. */
renderMarkdown: (props: MessagePartsMarkdownProps) => ReactNode;
+ /**
+ * Renders plain text while it is still streaming, so a reasoning stream can fade its words in.
+ * Absent, the part shows the text as it is.
+ */
+ renderStreamingText?: (text: string) => ReactNode;
/** Renders an attached image with the app's image viewer. */
renderImage: (props: MessagePartsImageProps) => ReactNode;
/** Renders the app's preview dialog for an attached file. */
diff --git a/packages/chat/test/consumer.spec.tsx b/packages/chat/test/consumer.spec.tsx
index c9a0d67fdb..e64d43bebb 100644
--- a/packages/chat/test/consumer.spec.tsx
+++ b/packages/chat/test/consumer.spec.tsx
@@ -10,6 +10,7 @@ import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import {
Part,
Text,
+ Reasoning,
MessageRow,
MentionPopover,
ChatScreen,
@@ -761,4 +762,31 @@ describe('a consumer styled by the published stylesheet alone', () => {
expect(iconRule).toContain('width: 1rem');
expect(iconRule).toContain('height: 1rem');
});
+
+ it('opens and fades a streaming thought from the shipped rules, as plain text', () => {
+ const streaming: MessagePartsHost = {
+ ...host,
+ useMessage: () => ({ messageId: 'reply-1', isSubmitting: true, isLatestMessage: true }),
+ useSmoothStreaming: () => true,
+ };
+ render(
+
+
+
+
+ ,
+ );
+
+ /** The peek's edge fade and the panel's grid-rows motion are the package's, not the app's. */
+ const peek = screen.getByTestId('streaming-thought-peek');
+ expect(declaredFor(peek.firstElementChild as Element)).toMatch(/mask-image/);
+ const panel = document.querySelector('.part-expand') as Element;
+ expect(declaredFor(panel)).toMatch(/grid-template-rows:\s*0fr/);
+ expect(declaredFor(panel)).toMatch(/transition:[^;]*\.01ms/);
+
+ /** This host supplies no streaming renderer, so the opened thought is the text as it is. */
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_thinking' }));
+ expect(screen.getByText('Checking the manifest. Reading the lockfile.')).toBeInTheDocument();
+ expect(document.querySelector('[data-lc-fade]')).toBeNull();
+ });
});
diff --git a/packages/client/src/components/Button.tsx b/packages/client/src/components/Button.tsx
index 38644bf59c..d433eb16b1 100644
--- a/packages/client/src/components/Button.tsx
+++ b/packages/client/src/components/Button.tsx
@@ -45,6 +45,7 @@ type ButtonVariantOptions =
| 'disclosure'
| 'disclosure-line'
| 'disclosure-panel'
+ | 'disclosure-search'
| 'option'
| 'text-action'
| 'hint'
@@ -62,6 +63,7 @@ type ButtonVariantOptions =
| 'dense'
| 'compact'
| 'icon'
+ | 'icon-inline'
| 'icon-sm'
| 'icon-xs'
| 'icon-theme'
@@ -274,6 +276,12 @@ const buttonVariantRecipe = cva(
'w-full justify-start text-start text-text-secondary hover:bg-surface-hover hover:active:bg-surface-pressed hover:text-text-primary focus-visible:ring-focus-control focus-visible:ring-inset focus-visible:ring-offset-0',
'disclosure-line':
'w-full justify-start gap-0 font-normal leading-4.5 focus-visible:ring-focus-subtle focus-visible:ring-offset-0 disabled:opacity-100',
+ /**
+ * A finished web search row: the same quiet disclosure as a tool header, at the status
+ * line's type size, with no color fade so the chevron beside it appears at once.
+ */
+ 'disclosure-search':
+ 'tool-status-text w-full justify-start font-normal text-text-secondary transition-none focus-visible:ring-focus-subtle focus-visible:ring-offset-0 disabled:opacity-100 theme-disabled:border-transparent theme-disabled:bg-transparent theme-disabled:text-text-secondary theme-disabled:hover:bg-transparent theme-disabled:hover:text-text-secondary theme-disabled:[&_*]:text-text-secondary',
/**
* A full-width answer row in an option list, such as the choices of an
* `ask_user_question`. The fill follows the pointer instantly rather than
@@ -352,6 +360,8 @@ const buttonVariantRecipe = cva(
* such as a clipped text's Show more. */
'bare-xs': 'h-auto gap-1 p-0 text-xs',
icon: 'size-theme-button',
+ /** A small icon that sits in a text row, such as a search row's details button. */
+ 'icon-inline': 'size-auto rounded-md p-1',
'icon-sm': 'size-theme-icon-button-sm p-0',
'icon-xs': 'size-theme-button-xs',
/**
@@ -423,6 +433,12 @@ const buttonVariantRecipe = cva(
size: 'default',
class: 'h-auto rounded-none p-0',
},
+ /* Sized by its glyph slot and status line, and pill-shaped so its focus ring hugs the row. */
+ {
+ variant: 'disclosure-search',
+ size: 'default',
+ class: 'h-auto rounded-full p-0',
+ },
/* Sized by the text it stands for, like `section-header`, so the default
* size recipe must not pad it away from the content it lines up with. */
{
diff --git a/packages/client/src/theme/disclosure.spec.ts b/packages/client/src/theme/disclosure.spec.ts
new file mode 100644
index 0000000000..d1b51443b3
--- /dev/null
+++ b/packages/client/src/theme/disclosure.spec.ts
@@ -0,0 +1,77 @@
+import fs from 'fs';
+import path from 'path';
+
+/**
+ * A host that loads only `@librechat/client` gets the package styles through its ThemeProvider and
+ * nothing from the app's `style.css`. The reasoning, thinking and web search parts open and close
+ * their bodies with `.part-expand` and fade the live peek with `.thought-peek`, so those rules, and
+ * every other class the parts draw with, have to ship with the package or that host sees a panel
+ * that never animates and a peek with hard edges.
+ */
+const root = path.resolve(__dirname, '../../../..');
+const partsDir = path.join(root, 'packages/chat/src/components/parts');
+const parts = fs.readFileSync(path.join(__dirname, 'parts.css'), 'utf8');
+const appStyles = fs.readFileSync(path.join(root, 'client/src/style.css'), 'utf8');
+
+const stylesheets = (dir: string): string[] =>
+ fs.readdirSync(dir, { withFileTypes: true }).flatMap((entry) => {
+ const file = path.join(dir, entry.name);
+ if (entry.isDirectory()) {
+ return stylesheets(file);
+ }
+ return entry.name.endsWith('.css') ? [fs.readFileSync(file, 'utf8')] : [];
+ });
+const packageStyles = stylesheets(path.join(root, 'packages/client/src')).join('\n');
+
+const defines = (css: string, name: string): boolean =>
+ new RegExp(`^\\s*\\.${name}(?![\\w-])`, 'm').test(css);
+
+const sources = ['Reasoning.tsx', 'Thinking.tsx', 'WebSearch.tsx'].map((file) =>
+ fs.readFileSync(path.join(partsDir, file), 'utf8'),
+);
+
+/** Tailwind's own marker class, and the `role` value that shares its name. */
+const TAILWIND = new Set(['group']);
+
+/** Every plain class name in a string literal of the three parts. */
+const classNames = Array.from(
+ new Set(
+ sources
+ .flatMap((source) => source.match(/(['"`])(?:(?!\1)[^\\\n])*\1/g) ?? [])
+ .flatMap((literal) => literal.slice(1, -1).split(/\s+/))
+ .filter((token) => /^[a-z][a-z0-9]*(?:-[a-z0-9]+)*$/.test(token) && !TAILWIND.has(token)),
+ ),
+);
+
+const reducedMotion = parts.split('@media (prefers-reduced-motion: reduce)').slice(1).join('\n');
+
+describe('reasoning, thinking and web search part styles', () => {
+ it('finds the classes the parts draw with', () => {
+ expect(classNames).toEqual(
+ expect.arrayContaining(['part-expand', 'thought-peek', 'tool-status-text']),
+ );
+ });
+
+ it('draws with no class that only the app stylesheet defines', () => {
+ const appOnly = classNames.filter(
+ (name) => defines(appStyles, name) && !defines(packageStyles, name),
+ );
+ expect(appOnly).toEqual([]);
+ });
+
+ it.each(['part-expand', 'thought-peek'])('ships .%s with the client package', (name) => {
+ expect(defines(parts, name)).toBe(true);
+ expect(defines(appStyles, name)).toBe(false);
+ });
+
+ it('keeps a transition under reduced motion so a closed body still unmounts', () => {
+ expect(reducedMotion).toMatch(/\.part-expand[\s,{]/);
+ expect(reducedMotion).toMatch(/grid-template-rows 0\.01ms/);
+ });
+
+ it('masks the peek with both the standard and the prefixed property', () => {
+ const peek = parts.slice(parts.indexOf('.thought-peek'));
+ expect(peek).toMatch(/\bmask-image:/);
+ expect(peek).toMatch(/-webkit-mask-image:/);
+ });
+});
diff --git a/packages/client/src/theme/parts.css b/packages/client/src/theme/parts.css
index 2108ddddd9..ba84ba9dbe 100644
--- a/packages/client/src/theme/parts.css
+++ b/packages/client/src/theme/parts.css
@@ -360,3 +360,52 @@
opacity: var(--expand-opacity, 1);
transition: var(--expand-transition);
}
+
+/**
+ * Disclosure body that opens and closes on grid rows. `data-expanded="true"`
+ * opens it. Reduced motion keeps a 0.01ms transition so `transitionend` still
+ * fires and a collapsed body can unmount.
+ */
+.part-expand {
+ display: grid;
+ grid-template-rows: 0fr;
+ opacity: 0;
+ transition:
+ grid-template-rows 0.3s cubic-bezier(0.16, 1, 0.3, 1),
+ opacity 0.3s cubic-bezier(0.16, 1, 0.3, 1);
+}
+
+.part-expand[data-expanded='true'] {
+ grid-template-rows: 1fr;
+ opacity: 1;
+}
+
+@media (prefers-reduced-motion: reduce) {
+ .part-expand {
+ transition:
+ grid-template-rows 0.01ms linear,
+ opacity 0.01ms linear;
+ }
+}
+
+/**
+ * Edge fade for a live reasoning peek. A mask stencil, not paint: only the
+ * alpha channel is read. Opaque black means "keep this pixel" and
+ * `transparent` means "hide it". The hue never reaches the screen.
+ */
+.thought-peek {
+ mask-image: linear-gradient(
+ to bottom,
+ transparent,
+ rgb(var(--black) / 1) 1.25rem,
+ rgb(var(--black) / 1) calc(100% - 1.25rem),
+ transparent
+ );
+ -webkit-mask-image: linear-gradient(
+ to bottom,
+ transparent,
+ rgb(var(--black) / 1) 1.25rem,
+ rgb(var(--black) / 1) calc(100% - 1.25rem),
+ transparent
+ );
+}