mirror of
https://github.com/danny-avila/LibreChat.git
synced 2026-11-21 15:33:45 +00:00
💭 refactor: Move the Reasoning, Thinking and Web Search Parts Into @librechat/chat (#18147)
- 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
This commit is contained in:
parent
5473f91036
commit
d603bfff0f
31 changed files with 1638 additions and 812 deletions
7
.github/guard-specs.json
vendored
7
.github/guard-specs.json
vendored
|
|
@ -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/"
|
||||
|
|
|
|||
|
|
@ -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) => <AnimatedText text={text} />,
|
||||
renderImage: (props) => getAppPartRenderers().renderImage(props),
|
||||
renderFilePreview: (props) => getAppPartRenderers().renderFilePreview(props),
|
||||
useSmoothStreaming,
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
||||
|
|
|
|||
|
|
@ -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 }) => (
|
||||
<div data-testid="thinking-label" title={title}>
|
||||
{label}
|
||||
</div>
|
||||
),
|
||||
}));
|
||||
|
||||
describe('ReasoningMarker', () => {
|
||||
it('shows the generated label for reasoning this view cannot show', () => {
|
||||
render(<ReasoningMarker label="Planning the answer" />);
|
||||
|
||||
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(<ReasoningMarker encrypted label="Inspecting an encoded data snapshot" />);
|
||||
|
||||
const marker = screen.getByTestId('thinking-label');
|
||||
expect(marker).toHaveTextContent('com_ui_reasoning_encrypted');
|
||||
expect(marker).toHaveAttribute('title', 'com_ui_reasoning_encrypted_description');
|
||||
});
|
||||
});
|
||||
|
|
@ -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(<ThinkingContent animate>{text}</ThinkingContent>);
|
||||
expect(document.querySelector('[data-lc-fade]')).not.toBeNull();
|
||||
expect(screen.getByText(/Hello/)).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
|
@ -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: () => <button type="button" data-testid="copy-thoughts" />,
|
||||
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(
|
||||
<ThinkingButton
|
||||
isExpanded={false}
|
||||
onClick={() => {}}
|
||||
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(<ThinkingLabel label="Thoughts" />);
|
||||
const label = screen.getByText('Thoughts');
|
||||
expect(label.parentElement).toHaveClass('tool-status-text');
|
||||
expect(label.parentElement).not.toHaveClass('text-xl');
|
||||
expect(label).toHaveClass('font-medium');
|
||||
});
|
||||
});
|
||||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
<div className="flex items-center" aria-hidden="true">
|
||||
{visible.map((source, i) => (
|
||||
<div
|
||||
key={source.link}
|
||||
className={cn(
|
||||
'border-border-medium bg-surface-secondary relative flex items-center justify-center rounded-full border',
|
||||
'h-[1.375rem] w-[1.375rem]',
|
||||
i > 0 && '-ms-2.5',
|
||||
)}
|
||||
style={{ zIndex: MAX_VISIBLE_FAVICONS - i }}
|
||||
>
|
||||
<FaviconImage domain={getCleanDomain(source.link)} className="size-3 rounded-full" />
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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<string, SearchResultData> = {};
|
||||
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 (
|
||||
<ToolCall
|
||||
name={Tools.web_search}
|
||||
args={args ?? ''}
|
||||
output={output}
|
||||
initialProgress={progress}
|
||||
isSubmitting={isSubmitting}
|
||||
isLast={isLast}
|
||||
runStepStatus={runStepStatus}
|
||||
attachments={attachments}
|
||||
hideAttachments={hideAttachments}
|
||||
onExpand={onExpand}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
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 = (
|
||||
<HoverCard openDelay={50} open={showDetails} onOpenChange={setShowDetails}>
|
||||
{/* Composed through `asChild` so the shared Button owns the
|
||||
rounding, hover fill, focus ring and motion (and gives a real
|
||||
<button> instead of Radix's default anchor). Only the
|
||||
hover-card reveal and the icon geometry stay local. */}
|
||||
<HoverCardTrigger asChild>
|
||||
<Button
|
||||
variant="quiet"
|
||||
size="icon"
|
||||
className={cn(
|
||||
'ms-auto size-auto cursor-help rounded-md p-1',
|
||||
/** On the title line it sits beside the always-visible chevron. */
|
||||
!inHeader &&
|
||||
'opacity-0 group-focus-within/websearch:opacity-100 group-hover/websearch:opacity-100 focus-visible:opacity-100',
|
||||
)}
|
||||
onFocus={() => setShowDetails(true)}
|
||||
onBlur={() => setShowDetails(false)}
|
||||
aria-label={localize('com_ui_web_search_details')}
|
||||
>
|
||||
<Info className="size-3.5" aria-hidden="true" />
|
||||
</Button>
|
||||
</HoverCardTrigger>
|
||||
<HoverCardPortal>
|
||||
<HoverCardContent side="top" className="z-[999] w-80">
|
||||
<div className="max-h-[60vh] space-y-2 overflow-y-auto">
|
||||
{query && (
|
||||
<div>
|
||||
<div className="text-text-secondary text-3xs font-medium tracking-wide uppercase">
|
||||
{localize('com_ui_search_query')}
|
||||
</div>
|
||||
<div className="text-text-primary mt-0.5 text-sm">{query}</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="text-text-secondary text-xs">
|
||||
{localize(
|
||||
sourceCount === 1 ? 'com_ui_web_search_source' : 'com_ui_web_search_sources',
|
||||
{ count: sourceCount },
|
||||
)}
|
||||
</div>
|
||||
{answerBox && (answerBox.title || answerText) && (
|
||||
<div className="border-border-inset border-t pt-2">
|
||||
{answerBox.title && (
|
||||
<div className="text-text-primary text-sm font-medium">{answerBox.title}</div>
|
||||
)}
|
||||
{answerText && (
|
||||
<div className="text-text-secondary mt-1 text-xs leading-relaxed">
|
||||
{answerText}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</HoverCardContent>
|
||||
</HoverCardPortal>
|
||||
</HoverCard>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={cn('group/websearch', bare && 'my-1.5')}>
|
||||
<span className="sr-only" aria-live="polite" aria-atomic="true">
|
||||
{completedText}
|
||||
</span>
|
||||
<div className={cn('relative flex items-center gap-1.5', bare ? 'h-0' : 'my-1.5 h-5')}>
|
||||
{!bare && (
|
||||
<Button
|
||||
ref={rowRef}
|
||||
variant="disclosure"
|
||||
className={cn(
|
||||
'tool-status-text group/disclosure text-text-secondary h-5 min-w-0 rounded-full font-normal',
|
||||
/** This row is a status line, not a padded control: the shared
|
||||
* recipe's color transition would turn its hover into a fade,
|
||||
* and the chevron reveal beside it is deliberately instant. */
|
||||
'transition-none',
|
||||
!hasSourceData && 'pointer-events-none disabled:opacity-100',
|
||||
)}
|
||||
disabled={!hasSourceData}
|
||||
onClick={hasSourceData ? handleToggleSources : undefined}
|
||||
aria-expanded={hasSourceData ? showSourceList : undefined}
|
||||
aria-label={
|
||||
hasSourceData
|
||||
? `${completedText} - ${localize(sourceCount === 1 ? 'com_ui_web_search_source' : 'com_ui_web_search_sources', { count: sourceCount })}`
|
||||
: completedText
|
||||
}
|
||||
>
|
||||
<span className={ROW_GLYPH_SLOT} aria-hidden="true">
|
||||
{hasSourceData ? (
|
||||
<SourceFaviconStack sources={allSources} />
|
||||
) : (
|
||||
<Globe className="text-text-secondary size-4 shrink-0" />
|
||||
)}
|
||||
</span>
|
||||
<span className="min-w-0 truncate font-medium">{completedText}</span>
|
||||
{hasSourceData && (
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
disclosureChevronVariants({ expanded: showSourceList }),
|
||||
'ms-auto size-3.5',
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
{hasDetails && !bare && details}
|
||||
{hasDetails && inHeader && headerSlot && createPortal(details, headerSlot)}
|
||||
</div>
|
||||
{hasSourceData && (
|
||||
<div style={sourceExpandStyle} onTransitionEnd={handleTransitionEnd}>
|
||||
<div className="min-h-0 overflow-hidden" ref={sourceExpandRef}>
|
||||
{shouldRenderBody && (
|
||||
<div
|
||||
className={cn(
|
||||
toolPanelSpacingClassName,
|
||||
'border-border-light mt-1.5 max-h-[17.5rem] overflow-y-auto rounded-lg border',
|
||||
)}
|
||||
>
|
||||
{allSources.map((source, i) => {
|
||||
const domain = getCleanDomain(source.link);
|
||||
const snippet = 'snippet' in source ? source.snippet : undefined;
|
||||
return (
|
||||
<a
|
||||
key={source.link}
|
||||
href={source.link}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={cn(
|
||||
'hover:bg-surface-hover flex gap-2.5 px-3 py-2 transition-colors',
|
||||
snippet ? 'items-start' : 'items-center',
|
||||
i > 0 && 'border-border-light border-t',
|
||||
)}
|
||||
>
|
||||
<FaviconImage
|
||||
domain={domain}
|
||||
className={cn('size-4 shrink-0 rounded-sm', snippet && 'mt-0.5')}
|
||||
/>
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="text-text-primary block truncate text-xs font-medium">
|
||||
{source.title || domain}
|
||||
</span>
|
||||
{snippet && (
|
||||
<span className="text-text-secondary text-2xs mt-0.5 line-clamp-2 block leading-relaxed">
|
||||
{snippet}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="shrink-0 text-end">
|
||||
<span className="text-text-secondary text-2xs block">{domain}</span>
|
||||
{source.date && (
|
||||
<span className="text-text-secondary text-3xs block">
|
||||
{source.date}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{!hideAttachments && <SearchVerticals attachments={attachments} />}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="text-text-secondary relative my-1.5 flex h-5 shrink-0 items-center gap-2">
|
||||
<span className="sr-only" aria-live="polite" aria-atomic="true">
|
||||
{genericProgressText}
|
||||
</span>
|
||||
<span className={ROW_GLYPH_SLOT} aria-hidden="true">
|
||||
{showSources && <StackedFavicons sources={streamingSources} start={-5} />}
|
||||
<Globe className="text-text-secondary size-4 shrink-0" />
|
||||
</span>
|
||||
<Shimmer className="tool-status-text min-w-0 truncate font-medium">{progressText}</Shimmer>
|
||||
</div>
|
||||
<WebSearchPart
|
||||
initialProgress={initialProgress}
|
||||
isSubmitting={isSubmitting}
|
||||
isLast={isLast}
|
||||
args={args}
|
||||
output={output}
|
||||
attachments={attachments}
|
||||
hideAttachments={hideAttachments}
|
||||
onExpand={onExpand}
|
||||
runStepStatus={runStepStatus}
|
||||
searchResults={searchResults}
|
||||
headerSlot={headerSlot}
|
||||
renderFavicon={({ domain, className }) => (
|
||||
<FaviconImage domain={domain} className={className ?? ''} />
|
||||
)}
|
||||
renderStackedFavicons={({ sources, start }) => (
|
||||
<StackedFavicons sources={sources} start={start} />
|
||||
)}
|
||||
renderVerticals={(verticalAttachments) => (
|
||||
<SearchVerticals attachments={verticalAttachments} />
|
||||
)}
|
||||
renderFailedCall={(failed) => <ToolCall {...failed} />}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
|
|
|||
|
|
@ -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<string, unknown>) => {
|
||||
const translations: Record<string, string> = {
|
||||
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', () => ({
|
||||
|
|
|
|||
|
|
@ -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<string, SearchResultData>): ValidSource[] {
|
||||
const sourceMap = new Map<string, ValidSource>();
|
||||
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<string>();
|
||||
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<string, SearchResultData> = {};
|
||||
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';
|
||||
|
|
|
|||
|
|
@ -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 (
|
||||
|
|
|
|||
361
e2e/specs/mock/scenarios/part-disclosures.spec.ts
Normal file
361
e2e/specs/mock/scenarios/part-disclosures.spec.ts
Normal file
|
|
@ -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<string, unknown>;
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
|
@ -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
|
||||
|
|
|
|||
|
|
@ -376,6 +376,8 @@ export default [
|
|||
'part-fold',
|
||||
'tool-status-text',
|
||||
'tool-call-expand',
|
||||
'part-expand',
|
||||
'thought-peek',
|
||||
'message-render',
|
||||
'message-timestamp',
|
||||
'popover-animate',
|
||||
|
|
|
|||
1
package-lock.json
generated
1
package-lock.json
generated
|
|
@ -43236,6 +43236,7 @@
|
|||
"name": "@librechat/chat",
|
||||
"version": "0.1.0",
|
||||
"dependencies": {
|
||||
"copy-to-clipboard": "^3.3.3",
|
||||
"sse.js": "^2.8.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
|
|||
|
|
@ -81,6 +81,7 @@
|
|||
"uuid": "^11.1.1"
|
||||
},
|
||||
"dependencies": {
|
||||
"copy-to-clipboard": "^3.3.3",
|
||||
"sse.js": "^2.8.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
|
|
|
|||
|
|
@ -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';
|
||||
|
|
|
|||
|
|
@ -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<HTMLDivElement>(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<HTMLDivElement>(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 (
|
||||
<div
|
||||
aria-hidden="true"
|
||||
className="border-border-light mt-1 overflow-hidden rounded-lg border px-4 py-3"
|
||||
data-testid="streaming-thought-peek"
|
||||
>
|
||||
return (
|
||||
<div
|
||||
ref={ref}
|
||||
className={cn(
|
||||
/** Fixed-height window the text scrolls through. The one-line top pad
|
||||
* keeps the first streaming line below the top fade (a blank line
|
||||
* above it) instead of jammed against the faded edge. */
|
||||
'text-text-primary h-[5.5rem] overflow-hidden pt-6.5 leading-6.5 break-words whitespace-pre-wrap',
|
||||
fontSize,
|
||||
)}
|
||||
style={{ maskImage: PEEK_FADE, WebkitMaskImage: PEEK_FADE }}
|
||||
aria-hidden="true"
|
||||
className="border-border-light mt-1 overflow-hidden rounded-lg border px-4 py-3"
|
||||
data-testid="streaming-thought-peek"
|
||||
>
|
||||
{peek}
|
||||
<div
|
||||
ref={ref}
|
||||
className={classes(
|
||||
/** Fixed-height window the text scrolls through. The one-line top pad
|
||||
* keeps the first streaming line below the top fade (a blank line
|
||||
* above it) instead of jammed against the faded edge. The fade itself
|
||||
* is `.thought-peek` in the shared parts stylesheet: a mask stencil,
|
||||
* not paint, so it is not a theme color. */
|
||||
'thought-peek text-text-primary h-[5.5rem] overflow-hidden pt-6.5 leading-6.5 break-words whitespace-pre-wrap',
|
||||
fontSize,
|
||||
)}
|
||||
>
|
||||
{peek}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
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<ReasoningProps> = 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<HTMLDivElement>(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}
|
||||
>
|
||||
<div
|
||||
className={cn('overflow-hidden', nextType !== ContentTypes.THINK && 'pb-4')}
|
||||
className={classes('overflow-hidden', nextType !== ContentTypes.THINK && 'pb-4')}
|
||||
ref={expandRef}
|
||||
>
|
||||
{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<ReasoningCompactProps> = 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"
|
||||
>
|
||||
<span className={ROW_GLYPH_SLOT} aria-hidden="true">
|
||||
<Lightbulb className="text-text-secondary size-4 shrink-0" />
|
||||
</span>
|
||||
<span className="tool-status-text font-medium">{label}</span>
|
||||
<span className="tool-status-text text-text-secondary font-medium">{label}</span>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
className={classes(
|
||||
disclosureChevronVariants({ expanded: isExpanded }),
|
||||
'ms-auto size-4 translate-y-[1px]',
|
||||
)}
|
||||
|
|
@ -430,7 +418,7 @@ export const ReasoningCompact = memo(
|
|||
copiedLabel={localize('com_ui_copied_to_clipboard')}
|
||||
/** Laid over the row's end, inside the chevron, so the chevron
|
||||
* lines up with every tool row's instead of moving left of it. */
|
||||
className={cn(
|
||||
className={classes(
|
||||
'absolute end-6 shrink-0 opacity-0 transition-opacity',
|
||||
'group-focus-within/reasoning-compact:opacity-100 group-hover/reasoning-compact:opacity-100',
|
||||
'focus-visible:opacity-100',
|
||||
|
|
@ -444,18 +432,21 @@ export const ReasoningCompact = memo(
|
|||
role="group"
|
||||
aria-label={label}
|
||||
aria-hidden={!isExpanded || undefined}
|
||||
style={expandStyle}
|
||||
className="part-expand"
|
||||
data-expanded={isExpanded ? 'true' : 'false'}
|
||||
onTransitionEnd={handleTransitionEnd}
|
||||
>
|
||||
<div className="overflow-hidden" ref={expandRef}>
|
||||
{shouldRenderBody && (
|
||||
<div
|
||||
className={cn(
|
||||
className={classes(
|
||||
toolPanelSpacingClassName,
|
||||
'border-border-light bg-surface-secondary text-text-secondary relative rounded-lg border p-3',
|
||||
)}
|
||||
>
|
||||
<p className={cn('leading-6.5 whitespace-pre-wrap', fontSize)}>{reasoningText}</p>
|
||||
<p className={classes('leading-6.5 whitespace-pre-wrap', fontSize)}>
|
||||
{reasoningText}
|
||||
</p>
|
||||
<FloatingThinkingBar
|
||||
isVisible={isBarVisible && isExpanded && !headerInViewport}
|
||||
isExpanded={isExpanded}
|
||||
|
|
@ -1,22 +1,14 @@
|
|||
import {
|
||||
useState,
|
||||
useMemo,
|
||||
memo,
|
||||
useEffect,
|
||||
useCallback,
|
||||
useRef,
|
||||
useId,
|
||||
type MouseEvent,
|
||||
} from 'react';
|
||||
import { Lightbulb, ChevronDown } from 'lucide-react';
|
||||
import { Button, Shimmer, MorphIcon, TooltipAnchor } from '@librechat/client';
|
||||
import { ChevronUp as ChevronUpNode, ChevronDown as ChevronDownNode } from 'lucide';
|
||||
import { ROW_GLYPH_SLOT, CopyButton, useExpandCollapse } from '@librechat/chat/components';
|
||||
import type { FocusEvent, FC } from 'react';
|
||||
import { useMessagePartsHost } from '~/Providers/MessagePartsHostContext';
|
||||
import { cn, isRectVisible } from '~/utils';
|
||||
import { AnimatedText } from '../animate';
|
||||
import { useLocalize } from '~/hooks';
|
||||
import { memo, useCallback, useEffect, useId, useMemo, useRef, useState } from 'react';
|
||||
import { ChevronDown, Lightbulb } from 'lucide-react';
|
||||
import { ChevronDown as ChevronDownNode, ChevronUp as ChevronUpNode } from 'lucide';
|
||||
import { Button, MorphIcon, Shimmer, TooltipAnchor, useLocalize } from '@librechat/client';
|
||||
import type { FC, FocusEvent, MouseEvent, NamedExoticComponent } from 'react';
|
||||
import { useMessagePartsHost } from '../../react/host';
|
||||
import useExpandCollapse from './useExpandCollapse';
|
||||
import { isRectVisible } from '../../core/viewport';
|
||||
import { ROW_GLYPH_SLOT } from './rows';
|
||||
import CopyButton from './CopyButton';
|
||||
import { classes } from './classes';
|
||||
|
||||
/**
|
||||
* Tracks whether the referenced element is within the viewport. Mirrors the
|
||||
|
|
@ -68,14 +60,16 @@ export const ThinkingContent: FC<{
|
|||
children: React.ReactNode;
|
||||
animate?: boolean;
|
||||
}> = memo(({ children, animate = false }) => {
|
||||
const { useFontSize } = useMessagePartsHost();
|
||||
const { useFontSize, renderStreamingText } = useMessagePartsHost();
|
||||
const fontSize = useFontSize();
|
||||
const content =
|
||||
animate && typeof children === 'string' ? <AnimatedText text={children} /> : children;
|
||||
animate && typeof children === 'string'
|
||||
? (renderStreamingText?.(children) ?? children)
|
||||
: children;
|
||||
|
||||
return (
|
||||
<div className="border-border-light bg-surface-secondary text-text-secondary relative rounded-lg border p-3">
|
||||
<p className={cn('leading-6.5 whitespace-pre-wrap', fontSize)}>{content}</p>
|
||||
<p className={classes('leading-6.5 whitespace-pre-wrap', fontSize)}>{content}</p>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
|
|
@ -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<HTMLButtonElement>) => 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<ThinkingButtonProps> = memo(
|
||||
({
|
||||
isExpanded,
|
||||
onClick,
|
||||
|
|
@ -95,19 +103,7 @@ export const ThinkingButton = memo(
|
|||
showCopyButton = true,
|
||||
animateLabel = false,
|
||||
shimmerLabel = false,
|
||||
}: {
|
||||
isExpanded: boolean;
|
||||
onClick: (e: MouseEvent<HTMLButtonElement>) => 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"
|
||||
>
|
||||
<span className={cn(ROW_GLYPH_SLOT, 'relative me-2')}>
|
||||
<span className={classes(ROW_GLYPH_SLOT, 'relative me-2')}>
|
||||
<Lightbulb
|
||||
className="icon-sm text-text-secondary absolute opacity-100 transition-opacity group-hover/button:opacity-0"
|
||||
aria-hidden="true"
|
||||
/>
|
||||
<ChevronDown
|
||||
className={cn(
|
||||
className={classes(
|
||||
'icon-sm text-text-primary absolute transform-gpu opacity-0 transition-all duration-300 group-hover/button:opacity-100',
|
||||
isExpanded && 'rotate-180',
|
||||
)}
|
||||
|
|
@ -148,7 +144,7 @@ export const ThinkingButton = memo(
|
|||
</span>
|
||||
{/* 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 (
|
||||
<div className="mb-2 pt-2 pb-2">
|
||||
<div className="tool-status-text flex w-full items-center justify-start" title={title}>
|
||||
<span className={cn(ROW_GLYPH_SLOT, 'relative me-2')}>
|
||||
<Lightbulb className="icon-sm text-text-secondary" aria-hidden="true" />
|
||||
</span>
|
||||
<span className="text-text-secondary min-w-0 truncate text-start font-medium">{label}</span>
|
||||
export const ThinkingLabel: NamedExoticComponent<{ label: string; title?: string }> = memo(
|
||||
({ label, title }: { label: string; title?: string }) => {
|
||||
return (
|
||||
<div className="mb-2 pt-2 pb-2">
|
||||
<div className="tool-status-text flex w-full items-center justify-start" title={title}>
|
||||
<span className={classes(ROW_GLYPH_SLOT, 'relative me-2')}>
|
||||
<Lightbulb className="icon-sm text-text-secondary" aria-hidden="true" />
|
||||
</span>
|
||||
<span className="text-text-secondary min-w-0 truncate text-start font-medium">
|
||||
{label}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
/**
|
||||
* 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<HTMLButtonElement>) => void;
|
||||
content?: string;
|
||||
contentId: string;
|
||||
}) => {
|
||||
type FloatingThinkingBarProps = {
|
||||
isVisible: boolean;
|
||||
isExpanded: boolean;
|
||||
onClick: (e: MouseEvent<HTMLButtonElement>) => void;
|
||||
content?: string;
|
||||
contentId: string;
|
||||
};
|
||||
|
||||
export const FloatingThinkingBar: NamedExoticComponent<FloatingThinkingBarProps> = memo(
|
||||
({ isVisible, isExpanded, onClick, content, contentId }: FloatingThinkingBarProps) => {
|
||||
const localize = useLocalize();
|
||||
const [isCopied, setIsCopied] = useState(false);
|
||||
|
||||
|
|
@ -252,7 +248,7 @@ export const FloatingThinkingBar = memo(
|
|||
|
||||
return (
|
||||
<div
|
||||
className={cn(
|
||||
className={classes(
|
||||
/* Laid over the text rather than reserved below it, so the box keeps
|
||||
even padding; the fill keeps the controls legible over a line. */
|
||||
'bg-surface-secondary absolute inset-e-3 bottom-3 flex items-center gap-2 rounded-lg transition-opacity duration-150',
|
||||
|
|
@ -318,7 +314,7 @@ const Thinking: React.ElementType = memo(({ children }: { children: React.ReactN
|
|||
const containerRef = useRef<HTMLDivElement>(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<HTMLButtonElement>) => {
|
||||
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
|
||||
498
packages/chat/src/components/parts/WebSearch.tsx
Normal file
498
packages/chat/src/components/parts/WebSearch.tsx
Normal file
|
|
@ -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<string, unknown>;
|
||||
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 (
|
||||
<div className="flex items-center" aria-hidden="true">
|
||||
{visible.map((source, i) => (
|
||||
<div
|
||||
key={source.link}
|
||||
className={classes(
|
||||
'border-border-medium bg-surface-secondary relative flex items-center justify-center rounded-full border',
|
||||
'h-[1.375rem] w-[1.375rem]',
|
||||
i > 0 && '-ms-2.5',
|
||||
)}
|
||||
style={{ zIndex: MAX_VISIBLE_FAVICONS - i }}
|
||||
>
|
||||
{renderFavicon({ domain: getCleanDomain(source.link), className: 'size-3 rounded-full' })}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
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<string, unknown>;
|
||||
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<string, SearchResultData> = {};
|
||||
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 = (
|
||||
<div
|
||||
className={classes(
|
||||
'ms-auto flex',
|
||||
/** On the title line it sits beside the always-visible chevron. */
|
||||
!inHeader &&
|
||||
'opacity-0 group-focus-within/websearch:opacity-100 group-hover/websearch:opacity-100',
|
||||
)}
|
||||
>
|
||||
<HoverCard openDelay={50} open={showDetails} onOpenChange={setShowDetails}>
|
||||
{/* Composed through `asChild` so the shared Button owns the
|
||||
rounding, hover fill, focus ring and motion (and gives a real
|
||||
<button> instead of Radix's default anchor). The reveal lives on
|
||||
the wrapper so the button itself stays a quiet icon control. */}
|
||||
<HoverCardTrigger asChild>
|
||||
<Button
|
||||
variant="quiet"
|
||||
size="icon-inline"
|
||||
className="cursor-help"
|
||||
onFocus={() => setShowDetails(true)}
|
||||
onBlur={() => setShowDetails(false)}
|
||||
aria-label={localize('com_ui_web_search_details')}
|
||||
>
|
||||
<Info className="size-3.5" aria-hidden="true" />
|
||||
</Button>
|
||||
</HoverCardTrigger>
|
||||
<HoverCardPortal>
|
||||
<HoverCardContent side="top" className="z-[999] w-80">
|
||||
<div className="max-h-[60vh] space-y-2 overflow-y-auto">
|
||||
{query && (
|
||||
<div>
|
||||
<div className="text-text-secondary text-3xs font-medium tracking-wide uppercase">
|
||||
{localize('com_ui_search_query')}
|
||||
</div>
|
||||
<div className="text-text-primary mt-0.5 text-sm">{query}</div>
|
||||
</div>
|
||||
)}
|
||||
<div className="text-text-secondary text-xs">
|
||||
{localize(
|
||||
sourceCount === 1 ? 'com_ui_web_search_source' : 'com_ui_web_search_sources',
|
||||
{ count: sourceCount },
|
||||
)}
|
||||
</div>
|
||||
{answerBox && (answerBox.title || answerText) && (
|
||||
<div className="border-border-inset border-t pt-2">
|
||||
{answerBox.title && (
|
||||
<div className="text-text-primary text-sm font-medium">{answerBox.title}</div>
|
||||
)}
|
||||
{answerText && (
|
||||
<div className="text-text-secondary mt-1 text-xs leading-relaxed">
|
||||
{answerText}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</HoverCardContent>
|
||||
</HoverCardPortal>
|
||||
</HoverCard>
|
||||
</div>
|
||||
);
|
||||
|
||||
return (
|
||||
<div className={classes('group/websearch', bare && 'my-1.5')}>
|
||||
<span className="sr-only" aria-live="polite" aria-atomic="true">
|
||||
{completedText}
|
||||
</span>
|
||||
<div className={classes('relative flex items-center gap-1.5', bare ? 'h-0' : 'my-1.5 h-5')}>
|
||||
{!bare && (
|
||||
<Button
|
||||
ref={rowRef}
|
||||
variant="disclosure-search"
|
||||
className="group/disclosure min-w-0"
|
||||
disabled={!hasSourceData}
|
||||
onClick={hasSourceData ? handleToggleSources : undefined}
|
||||
aria-expanded={hasSourceData ? showSourceList : undefined}
|
||||
aria-label={
|
||||
hasSourceData
|
||||
? `${completedText} - ${localize(sourceCount === 1 ? 'com_ui_web_search_source' : 'com_ui_web_search_sources', { count: sourceCount })}`
|
||||
: completedText
|
||||
}
|
||||
>
|
||||
<span className={ROW_GLYPH_SLOT} aria-hidden="true">
|
||||
{hasSourceData && renderFavicon != null ? (
|
||||
<SourceFaviconStack sources={allSources} renderFavicon={renderFavicon} />
|
||||
) : (
|
||||
<Globe className="text-text-secondary size-4 shrink-0" />
|
||||
)}
|
||||
</span>
|
||||
<span className="min-w-0 truncate font-medium">{completedText}</span>
|
||||
{hasSourceData && (
|
||||
<ChevronDown
|
||||
className={classes(
|
||||
disclosureChevronVariants({ expanded: showSourceList }),
|
||||
'ms-auto size-3.5',
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
{hasDetails && !bare && details}
|
||||
{hasDetails && inHeader && headerSlot && createPortal(details, headerSlot)}
|
||||
</div>
|
||||
{hasSourceData && (
|
||||
<div
|
||||
className="part-expand"
|
||||
data-expanded={showSourceList ? 'true' : 'false'}
|
||||
onTransitionEnd={handleTransitionEnd}
|
||||
>
|
||||
<div className="min-h-0 overflow-hidden" ref={sourceExpandRef}>
|
||||
{shouldRenderBody && (
|
||||
<div
|
||||
className={classes(
|
||||
toolPanelSpacingClassName,
|
||||
'border-border-light mt-1.5 max-h-[17.5rem] overflow-y-auto rounded-lg border',
|
||||
)}
|
||||
>
|
||||
{allSources.map((source, i) => {
|
||||
const domain = getCleanDomain(source.link);
|
||||
const snippet = 'snippet' in source ? source.snippet : undefined;
|
||||
return (
|
||||
<a
|
||||
key={source.link}
|
||||
href={source.link}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className={classes(
|
||||
'hover:bg-surface-hover flex gap-2.5 px-3 py-2 transition-colors',
|
||||
snippet ? 'items-start' : 'items-center',
|
||||
i > 0 && 'border-border-light border-t',
|
||||
)}
|
||||
>
|
||||
{renderFavicon != null ? (
|
||||
renderFavicon({
|
||||
domain,
|
||||
className: classes('size-4 shrink-0 rounded-sm', snippet && 'mt-0.5'),
|
||||
})
|
||||
) : (
|
||||
<Globe
|
||||
className={classes(
|
||||
'text-text-secondary size-4 shrink-0',
|
||||
snippet && 'mt-0.5',
|
||||
)}
|
||||
aria-hidden="true"
|
||||
/>
|
||||
)}
|
||||
<span className="min-w-0 flex-1">
|
||||
<span className="text-text-primary block truncate text-xs font-medium">
|
||||
{source.title || domain}
|
||||
</span>
|
||||
{snippet && (
|
||||
<span className="text-text-secondary text-2xs mt-0.5 line-clamp-2 block leading-relaxed">
|
||||
{snippet}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
<span className="shrink-0 text-end">
|
||||
<span className="text-text-secondary text-2xs block">{domain}</span>
|
||||
{source.date && (
|
||||
<span className="text-text-secondary text-3xs block">
|
||||
{source.date}
|
||||
</span>
|
||||
)}
|
||||
</span>
|
||||
</a>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{!hideAttachments && renderVerticals?.(attachments)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="text-text-secondary relative my-1.5 flex h-5 shrink-0 items-center gap-2">
|
||||
<span className="sr-only" aria-live="polite" aria-atomic="true">
|
||||
{genericProgressText}
|
||||
</span>
|
||||
<span className={ROW_GLYPH_SLOT} aria-hidden="true">
|
||||
{showSources && renderStackedFavicons?.({ sources: streamingSources, start: -5 })}
|
||||
<Globe className="text-text-secondary size-4 shrink-0" />
|
||||
</span>
|
||||
<Shimmer className="tool-status-text min-w-0 truncate font-medium">{progressText}</Shimmer>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -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: () => <button type="button">{'copy'}</button>,
|
||||
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 }) => <div>{children}</div>,
|
||||
ThinkingButton: () => <button type="button">{'thinking'}</button>,
|
||||
FloatingThinkingBar: () => null,
|
||||
useInViewport: () => ({ ref: { current: null }, inViewport: true }),
|
||||
}));
|
||||
|
||||
jest.mock('lucide-react', () => ({
|
||||
Lightbulb: () => <span data-testid="thoughts-icon" />,
|
||||
ChevronDown: ({ className }: { className?: string }) => (
|
||||
|
|
@ -39,9 +22,17 @@ jest.mock('lucide-react', () => ({
|
|||
),
|
||||
}));
|
||||
|
||||
function renderCompact(node: ReactNode) {
|
||||
return render(
|
||||
<MessagePartsHostProvider host={createMessagePartsHost()}>{node}</MessagePartsHostProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
describe('ReasoningCompact', () => {
|
||||
it('always shows its own Thoughts chevron', () => {
|
||||
render(<ReasoningCompact reasoning="A useful thought" label="Thoughts" showThinking={false} />);
|
||||
renderCompact(
|
||||
<ReasoningCompact reasoning="A useful thought" label="Thoughts" showThinking={false} />,
|
||||
);
|
||||
|
||||
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(<ReasoningCompact reasoning="A useful thought" label="Thoughts" showThinking={false} />);
|
||||
renderCompact(
|
||||
<ReasoningCompact reasoning="A useful thought" label="Thoughts" showThinking={false} />,
|
||||
);
|
||||
|
||||
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(<ReasoningCompact reasoning="A useful thought" label="Thoughts" showThinking={false} />);
|
||||
renderCompact(
|
||||
<ReasoningCompact reasoning="A useful thought" label="Thoughts" showThinking={false} />,
|
||||
);
|
||||
|
||||
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(
|
||||
<ReasoningCompact
|
||||
reasoning="A long stream of reasoning"
|
||||
label="Thoughts"
|
||||
|
|
@ -91,12 +77,8 @@ describe('ReasoningCompact', () => {
|
|||
});
|
||||
|
||||
it('opens from the host preference rather than the app store', () => {
|
||||
render(
|
||||
<ReasoningCompact
|
||||
reasoning="A long stream of reasoning"
|
||||
label="Thoughts"
|
||||
showThinking={true}
|
||||
/>,
|
||||
renderCompact(
|
||||
<ReasoningCompact reasoning="A long stream of reasoning" label="Thoughts" showThinking />,
|
||||
);
|
||||
|
||||
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(
|
||||
<ReasoningCompact
|
||||
reasoning={`Checking the manifest.\n${encoded}\nRolling back.`}
|
||||
label="Thoughts"
|
||||
|
|
@ -124,7 +106,7 @@ describe('ReasoningCompact', () => {
|
|||
const prefix = Buffer.from(Array.from({ length: 75 }, (_, i) => (i * 37 + 3) % 256)).toString(
|
||||
'base64',
|
||||
);
|
||||
render(
|
||||
renderCompact(
|
||||
<ReasoningCompact
|
||||
reasoning={`Checking the manifest. ${prefix}`}
|
||||
label="Thinking"
|
||||
|
|
@ -0,0 +1,29 @@
|
|||
/**
|
||||
* @jest-environment jsdom
|
||||
*/
|
||||
import React from 'react';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import '@testing-library/jest-dom';
|
||||
import { ReasoningMarker } from '../Reasoning';
|
||||
|
||||
jest.mock('@librechat/client', () => ({
|
||||
...jest.requireActual('@librechat/client'),
|
||||
useLocalize: () => (key: string) => key,
|
||||
}));
|
||||
|
||||
describe('ReasoningMarker', () => {
|
||||
it('shows the generated label for reasoning this view cannot show', () => {
|
||||
render(<ReasoningMarker label="Planning the answer" />);
|
||||
|
||||
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(<ReasoningMarker encrypted label="Inspecting an encoded data snapshot" />);
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
|
|
@ -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(
|
||||
<ThinkingButton
|
||||
isExpanded={false}
|
||||
onClick={() => 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(<ThinkingLabel label="Thoughts" />);
|
||||
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(
|
||||
<MessagePartsHostProvider host={createMessagePartsHost()}>
|
||||
<ThinkingContent animate>Checking the manifest</ThinkingContent>
|
||||
</MessagePartsHostProvider>,
|
||||
);
|
||||
expect(screen.getByText('Checking the manifest')).toBeInTheDocument();
|
||||
expect(document.querySelector('[data-lc-fade]')).toBeNull();
|
||||
});
|
||||
|
||||
it('hands a streaming string to the host renderer', () => {
|
||||
render(
|
||||
<MessagePartsHostProvider
|
||||
host={createMessagePartsHost({
|
||||
renderStreamingText: (text) => <span data-testid="streamed">{text}</span>,
|
||||
})}
|
||||
>
|
||||
<ThinkingContent animate>Checking the manifest</ThinkingContent>
|
||||
</MessagePartsHostProvider>,
|
||||
);
|
||||
expect(screen.getByTestId('streamed')).toHaveTextContent('Checking the manifest');
|
||||
});
|
||||
|
||||
it('leaves settled text alone', () => {
|
||||
render(
|
||||
<MessagePartsHostProvider
|
||||
host={createMessagePartsHost({
|
||||
renderStreamingText: (text) => <span data-testid="streamed">{text}</span>,
|
||||
})}
|
||||
>
|
||||
<ThinkingContent>Checking the manifest</ThinkingContent>
|
||||
</MessagePartsHostProvider>,
|
||||
);
|
||||
expect(screen.queryByTestId('streamed')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('Checking the manifest')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
129
packages/chat/src/components/parts/__tests__/WebSearch.spec.tsx
Normal file
129
packages/chat/src/components/parts/__tests__/WebSearch.spec.tsx
Normal file
|
|
@ -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(
|
||||
<MessagePartsHostProvider host={createMessagePartsHost()}>{node}</MessagePartsHostProvider>,
|
||||
);
|
||||
}
|
||||
|
||||
jest.mock('@librechat/client', () => ({
|
||||
...jest.requireActual('@librechat/client'),
|
||||
useLocalize: () => (key: string, values?: Record<string, unknown>) => {
|
||||
const translations: Record<string, string> = {
|
||||
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(
|
||||
<WebSearch
|
||||
initialProgress={1}
|
||||
isSubmitting={false}
|
||||
attachments={[attachment(0, [source('https://pi.example.com/1', 'Pi')])]}
|
||||
searchResults={{
|
||||
1: { turn: 1, organic: [source('https://other.example.com/1', 'Other')] },
|
||||
}}
|
||||
renderFavicon={({ domain }) => <span data-testid="favicon">{domain}</span>}
|
||||
/>,
|
||||
);
|
||||
|
||||
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(
|
||||
<WebSearch
|
||||
initialProgress={1}
|
||||
isSubmitting={false}
|
||||
output="Error processing search results"
|
||||
/>,
|
||||
);
|
||||
expect(container).toBeEmptyDOMElement();
|
||||
});
|
||||
|
||||
it('asks the host to render a failed call for schema feedback', () => {
|
||||
const renderFailedCall = jest.fn(() => <div data-testid="failed-call" />);
|
||||
render(
|
||||
<WebSearch
|
||||
initialProgress={1}
|
||||
isSubmitting={false}
|
||||
args={{ query: 'x' }}
|
||||
output={'Error: Invalid search arguments\n Please fix your mistakes.'}
|
||||
runStepStatus="completed"
|
||||
renderFailedCall={renderFailedCall}
|
||||
/>,
|
||||
);
|
||||
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(
|
||||
<WebSearch
|
||||
initialProgress={0.5}
|
||||
isSubmitting
|
||||
isLast
|
||||
attachments={[attachment(0, [source('https://a.com', 'A')])]}
|
||||
renderStackedFavicons={({ sources }) => <span data-testid="stacked">{sources.length}</span>}
|
||||
/>,
|
||||
);
|
||||
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(
|
||||
<GeneratedToolLabelContext.Provider value>
|
||||
<WebSearch
|
||||
initialProgress={1}
|
||||
isSubmitting={false}
|
||||
args={{ query: 'example' }}
|
||||
attachments={[attachment(0, [source('https://example.com', 'Example')])]}
|
||||
headerSlot={slot}
|
||||
/>
|
||||
</GeneratedToolLabelContext.Provider>,
|
||||
);
|
||||
const details = screen.getByRole('button', { name: 'Search details' });
|
||||
expect(slot).toContainElement(details);
|
||||
expect(details).not.toHaveClass('opacity-0');
|
||||
slot.remove();
|
||||
});
|
||||
});
|
||||
11
packages/chat/src/components/parts/classes.ts
Normal file
11
packages/chat/src/components/parts/classes.ts
Normal file
|
|
@ -0,0 +1,11 @@
|
|||
/** Joins class names. Package parts do not call `cn()`, so conditional classes are concatenated. */
|
||||
export function classes(...parts: Array<string | false | null | undefined>): string {
|
||||
let result = '';
|
||||
for (const part of parts) {
|
||||
if (part == null || part === false || part === '') {
|
||||
continue;
|
||||
}
|
||||
result = result === '' ? part : `${result} ${part}`;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
77
packages/chat/src/components/parts/sources.ts
Normal file
77
packages/chat/src/components/parts/sources.ts
Normal file
|
|
@ -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<string, SearchResultData>): ValidSource[] {
|
||||
const sourceMap = new Map<string, ValidSource>();
|
||||
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<string>();
|
||||
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<string, SearchResultData> = {};
|
||||
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));
|
||||
}
|
||||
|
|
@ -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. */
|
||||
|
|
|
|||
|
|
@ -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(
|
||||
<I18nextProvider i18n={i18n}>
|
||||
<MessagePartsHostProvider host={streaming}>
|
||||
<Reasoning reasoning="Checking the manifest. Reading the lockfile." isLast />
|
||||
</MessagePartsHostProvider>
|
||||
</I18nextProvider>,
|
||||
);
|
||||
|
||||
/** 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();
|
||||
});
|
||||
});
|
||||
|
|
|
|||
|
|
@ -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. */
|
||||
{
|
||||
|
|
|
|||
77
packages/client/src/theme/disclosure.spec.ts
Normal file
77
packages/client/src/theme/disclosure.spec.ts
Normal file
|
|
@ -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:/);
|
||||
});
|
||||
});
|
||||
|
|
@ -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
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue