mirror of
https://github.com/danny-avila/LibreChat.git
synced 2025-12-19 18:00:15 +01:00
🔎 feat: Native Web Search with Citation References (#7516)
* WIP: search tool integration * WIP: Add web search capabilities and API key management to agent actions * WIP: web search capability to agent configuration and selection * WIP: Add web search capability to backend agent configuration * WIP: add web search option to default agent form values * WIP: add attachments for web search * feat: add plugin for processing web search citations * WIP: first pass, Citation UI * chore: remove console.log * feat: Add AnimatedTabs component for tabbed UI functionality * refactor: AnimatedTabs component with CSS animations and stable ID generation * WIP example content * feat: SearchContext for managing search results apart from MessageContext * feat: Enhance AnimatedTabs with underline animation and state management * WIP: first pass, Implement dynamic tab functionality in Sources component with search results integration * fix: Update class names for improved styling in Sources and AnimatedTabs components * feat: Improve styling and layout in Sources component with enhanced button and item designs * feat: Refactor Sources component to integrate OGDialog for source display and improve layout * style: Update background color in SourceItem and SourcesGroup components for improved visibility * refactor: Sources component to enhance SourceItem structure and improve favicon handling * style: Adjust font size of domain text in SourceItem for better readability * feat: Add localization for citation source and details in CompositeCitation component * style: add theming to Citation components * feat: Enhance SourceItem component with dialog support and improved hovercard functionality * feat: Add localization for sources tab and image alt text in Sources component * style: Replace divs with spans for better semantic structure in CompositeCitation and Citation components * refactor: Sources component to use useMemo for tab generation and improve performance * chore: bump @librechat/agents to v2.4.318 * chore: update search result types * fix: search results retrieval in ContentParts component, re-render attachments when expected * feat: update sources style/types to use latest search result structure * style: enhance Dialog (expanded) SourceItem component with link wrapping and improved styling * style: update ImageItem component styling for improved title visibility * refactor: remove SourceItemBase component and adjust SourceItem layout for improved styling * chore: linting twcss order * fix: prevent FileAttachment from rendering search attachments * fix: append underscore to responseMessageId for unique identification to prevent mapping of previous latest message's attachments * chore: remove unused parameter 'useSpecs' from loadTools function * chore: twcss order * WIP: WebSearch Tool UI * refactor: add limit parameter to StackedFavicons for customizable source display * refactor: optimize search results memoization by making more granular and separate conerns * refactor: integrated StackedFavicons to WebSearch mid-run * chore: bump @librechat/agents to expose handleToolCallChunks * chore: use typedefs from dedicated file instead of defining them in AgentClient module * WIP: first pass, search progress results * refactor: move createOnSearchResults function to a dedicated search module * chore: bump @librechat/agents to v2.4.320 * WIP: first pass, search results processed UX * refactor: consolidate context variables in createOnSearchResults function * chore: bump @librechat/agents to v2.4.321 * feat: add guidelines for web search tool response formatting in loadTools function * feat: add isLast prop to Part component and update WebSearch logic for improved state handling * style: update Hovercard styles for improved UI consistency * feat: export FaviconImage component for improved accessibility in other modules * refactor: export getCleanDomain function and use FaviconImage in Citation component for improved source representation * refactor: implement SourceHovercard component for consistency and DRY compliance * fix: replace <p> with <span> for snippet and title in SourceItem and SourceHovercard for consistency * style: `not-prose` * style: remove 'not-prose' class for consistency in SourceItem, Citation, and SourceHovercard components, adjust style classes * refactor: `imageUrl` on hover and prevent duplicate sources * refactor: enhance SourcesGroup dialog layout and improve source item presentation * refactor: reorganize Web Components, save in same directory * feat: add 'news' refType to refTypeMap for citation sources * style: adjust Hovercard width for improved layout * refactor: update tool usage guidelines for improved clarity and execution * chore: linting * feat: add Web Search badge with initial permissions and local storage logic * feat: add webSearch support to interface and permissions schemas * feat: implement Web Search API key management and localization updates * feat: refactor Web Search API key handling and integrate new search API key form * fix: remove unnecessary visibility state from FileAttachment component * feat: update WebSearch component to use Globe icon and localized search label * feat: enhance ApiKeyDialog with dropdown for reranker selection and update translations * feat: implement dropdown menus for engine, scraper, and reranker selection in ApiKeyDialog * chore: linting and add unknown instead of `any` type * feat: refactor ApiKeyDialog and useAuthSearchTool for improved API key management * refactor: update ocrSchema to use template literals for default apiKey and baseURL * feat: add web search configuration and utility functions for environment variable extraction * fix: ensure filepath is defined before checking its prefix in useAttachmentHandler * feat: enhance web search functionality with improved configuration and environment variable extraction for authFields * fix: update auth type in TPluginAction and TUpdateUserPlugins to use Partial<Record<string, string>> * feat: implement web search authentication verification and enhance webSearchAuth structure * feat: enhance ephemeral agent handling with new web search capability and type definition * feat: enhance isEphemeralAgent function to include web search selection * feat: refactor verifyWebSearchAuth to improve key handling and authentication checks * feat: implement loadWebSearchAuth function for improved web search authentication handling * feat: enhance web search authentication with new configuration options and refactor related types * refactor: rename search engine to search provider and update related localization keys * feat: update verifyWebSearchAuth to handle multiple authentication types and improve error handling * feat: update ApiKeyDialog to accept authTypes prop and remove isUserProvided check * feat: add tests for extractWebSearchEnvVars and loadWebSearchAuth functions * feat: enhance loadWebSearchAuth to support specific service checks for providers, scrapers, and rerankers * fix: update web search configuration key and adjust auth result handling in loadTools function * feat: add new progress key for repeated web searching and update localization * chore: bump @librechat/agents to 2.4.322 * feat: enhance loadTools function to include ISO time and improve search tool logging * feat: update StackedFavicons to handle negative start index and improve citation attribution styling and text * chore: update .gitignore to categorize AI-related files * fix: mobile responsiveness of sources/citations hovercards * feat: enhance source display with improved line clamping for better readability * chore: bump @librechat/agents to v2.4.33 * feat: add handling for image sources in references mapping * chore: bump librechat-data-provider version to 0.7.84 * chore: bump @librechat/agents version to 2.4.34 * fix: update auth handling to support multiple auth types in tools and allow key configuration in agent panel * chore: remove redundant agent attribution text from search form * fix: web search auth uninstall * refactor: convert CheckboxButton to a forwardRef component and update setValue callback signature * feat: add triggerRef prop to ApiKeyDialog components for improved dialog control * feat: integrate triggerRef in CodeInterpreter and WebSearch components for enhanced dialog management * feat: enhance ApiKeyDialog with additional links for Firecrawl and Jina API key guidance * feat: implement web search configuration handling in ApiKeyDialog and add tests for dropdown visibility * fix: update webSearchConfig reference in config route for correct payload assignment * feat: update ApiKeyDialog to conditionally render sections based on authTypes and modify loadWebSearchAuth to correctly categorize authentication types * feat: refactor ApiKeyDialog and related tests to use SearchCategories and RerankerTypes enums and remove nested ternaries * refactor: move ThinkingButton rendering to improve layout consistency in ContentParts * feat: integrate search context into Markdown component to conditionally include unicodeCitation plugin * chore: bump @librechat/agents to v2.4.35 * chore: remove unused 18n key * ci: add WEB_SEARCH permission testing and update AppService tests for new webSearch configuration * ci: add more comprehensive tests for loadWebSearchAuth to validate authentication handling and authTypes structure * chore: remove debugging console log from web.spec.ts to clean up test output
This commit is contained in:
parent
bf80cf30b3
commit
0dbbf7de04
73 changed files with 6366 additions and 2003 deletions
9
client/src/Providers/SearchContext.tsx
Normal file
9
client/src/Providers/SearchContext.tsx
Normal file
|
|
@ -0,0 +1,9 @@
|
|||
import { createContext, useContext } from 'react';
|
||||
import type { SearchResultData } from 'librechat-data-provider';
|
||||
|
||||
type SearchContext = {
|
||||
searchResults?: { [key: string]: SearchResultData };
|
||||
};
|
||||
|
||||
export const SearchContext = createContext<SearchContext>({} as SearchContext);
|
||||
export const useSearchContext = () => useContext(SearchContext);
|
||||
|
|
@ -20,3 +20,4 @@ export * from './ArtifactContext';
|
|||
export * from './CodeBlockContext';
|
||||
export * from './ToolCallsMapContext';
|
||||
export * from './SetConvoContext';
|
||||
export * from './SearchContext';
|
||||
|
|
|
|||
|
|
@ -10,6 +10,7 @@ export type TAgentOption = OptionWithIcon &
|
|||
};
|
||||
|
||||
export type TAgentCapabilities = {
|
||||
[AgentCapabilities.web_search]: boolean;
|
||||
[AgentCapabilities.file_search]: boolean;
|
||||
[AgentCapabilities.execute_code]: boolean;
|
||||
[AgentCapabilities.end_after_tools]?: boolean;
|
||||
|
|
|
|||
|
|
@ -15,6 +15,7 @@ import type { BadgeItem } from '~/common';
|
|||
import { useChatBadges } from '~/hooks';
|
||||
import { Badge } from '~/components/ui';
|
||||
import MCPSelect from './MCPSelect';
|
||||
import WebSearch from './WebSearch';
|
||||
import store from '~/store';
|
||||
|
||||
interface BadgeRowProps {
|
||||
|
|
@ -354,6 +355,7 @@ function BadgeRow({
|
|||
)}
|
||||
{showEphemeralBadges === true && (
|
||||
<>
|
||||
<WebSearch conversationId={conversationId} />
|
||||
<CodeInterpreter conversationId={conversationId} />
|
||||
<MCPSelect conversationId={conversationId} />
|
||||
</>
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import debounce from 'lodash/debounce';
|
||||
import React, { memo, useMemo, useCallback } from 'react';
|
||||
import React, { memo, useMemo, useCallback, useRef } from 'react';
|
||||
import { useRecoilState } from 'recoil';
|
||||
import { TerminalSquareIcon } from 'lucide-react';
|
||||
import {
|
||||
|
|
@ -32,6 +32,7 @@ const storageCondition = (value: unknown, rawCurrentValue?: string | null) => {
|
|||
};
|
||||
|
||||
function CodeInterpreter({ conversationId }: { conversationId?: string | null }) {
|
||||
const triggerRef = useRef<HTMLInputElement>(null);
|
||||
const localize = useLocalize();
|
||||
const key = conversationId ?? Constants.NEW_CONVO;
|
||||
|
||||
|
|
@ -73,9 +74,10 @@ function CodeInterpreter({ conversationId }: { conversationId?: string | null })
|
|||
);
|
||||
|
||||
const handleChange = useCallback(
|
||||
(isChecked: boolean) => {
|
||||
(e: React.ChangeEvent<HTMLInputElement>, isChecked: boolean) => {
|
||||
if (!isAuthenticated) {
|
||||
setIsDialogOpen(true);
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
setRunCode(isChecked);
|
||||
|
|
@ -95,6 +97,7 @@ function CodeInterpreter({ conversationId }: { conversationId?: string | null })
|
|||
return (
|
||||
<>
|
||||
<CheckboxButton
|
||||
ref={triggerRef}
|
||||
className="max-w-fit"
|
||||
defaultChecked={runCode}
|
||||
setValue={debouncedChange}
|
||||
|
|
@ -105,6 +108,7 @@ function CodeInterpreter({ conversationId }: { conversationId?: string | null })
|
|||
<ApiKeyDialog
|
||||
onSubmit={onSubmit}
|
||||
isOpen={isDialogOpen}
|
||||
triggerRef={triggerRef}
|
||||
register={methods.register}
|
||||
onRevoke={handleRevokeApiKey}
|
||||
onOpenChange={setIsDialogOpen}
|
||||
|
|
|
|||
123
client/src/components/Chat/Input/WebSearch.tsx
Normal file
123
client/src/components/Chat/Input/WebSearch.tsx
Normal file
|
|
@ -0,0 +1,123 @@
|
|||
import React, { memo, useRef, useMemo, useCallback } from 'react';
|
||||
import { Globe } from 'lucide-react';
|
||||
import debounce from 'lodash/debounce';
|
||||
import { useRecoilState } from 'recoil';
|
||||
import {
|
||||
Tools,
|
||||
AuthType,
|
||||
Constants,
|
||||
Permissions,
|
||||
PermissionTypes,
|
||||
LocalStorageKeys,
|
||||
} from 'librechat-data-provider';
|
||||
import ApiKeyDialog from '~/components/SidePanel/Agents/Search/ApiKeyDialog';
|
||||
import { useLocalize, useHasAccess, useSearchApiKeyForm } from '~/hooks';
|
||||
import CheckboxButton from '~/components/ui/CheckboxButton';
|
||||
import useLocalStorage from '~/hooks/useLocalStorageAlt';
|
||||
import { useVerifyAgentToolAuth } from '~/data-provider';
|
||||
import { ephemeralAgentByConvoId } from '~/store';
|
||||
|
||||
const storageCondition = (value: unknown, rawCurrentValue?: string | null) => {
|
||||
if (rawCurrentValue) {
|
||||
try {
|
||||
const currentValue = rawCurrentValue?.trim() ?? '';
|
||||
if (currentValue === 'true' && value === false) {
|
||||
return true;
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
return value !== undefined && value !== null && value !== '' && value !== false;
|
||||
};
|
||||
|
||||
function WebSearch({ conversationId }: { conversationId?: string | null }) {
|
||||
const triggerRef = useRef<HTMLInputElement>(null);
|
||||
const localize = useLocalize();
|
||||
const key = conversationId ?? Constants.NEW_CONVO;
|
||||
|
||||
const canUseWebSearch = useHasAccess({
|
||||
permissionType: PermissionTypes.WEB_SEARCH,
|
||||
permission: Permissions.USE,
|
||||
});
|
||||
const [ephemeralAgent, setEphemeralAgent] = useRecoilState(ephemeralAgentByConvoId(key));
|
||||
const isWebSearchToggleEnabled = useMemo(() => {
|
||||
return ephemeralAgent?.web_search ?? false;
|
||||
}, [ephemeralAgent?.web_search]);
|
||||
|
||||
const { data } = useVerifyAgentToolAuth(
|
||||
{ toolId: Tools.web_search },
|
||||
{
|
||||
retry: 1,
|
||||
},
|
||||
);
|
||||
const authTypes = useMemo(() => data?.authTypes ?? [], [data?.authTypes]);
|
||||
const isAuthenticated = useMemo(() => data?.authenticated ?? false, [data?.authenticated]);
|
||||
const { methods, onSubmit, isDialogOpen, setIsDialogOpen, handleRevokeApiKey } =
|
||||
useSearchApiKeyForm({});
|
||||
|
||||
const setValue = useCallback(
|
||||
(isChecked: boolean) => {
|
||||
setEphemeralAgent((prev) => ({
|
||||
...prev,
|
||||
web_search: isChecked,
|
||||
}));
|
||||
},
|
||||
[setEphemeralAgent],
|
||||
);
|
||||
|
||||
const [webSearch, setWebSearch] = useLocalStorage<boolean>(
|
||||
`${LocalStorageKeys.LAST_WEB_SEARCH_TOGGLE_}${key}`,
|
||||
isWebSearchToggleEnabled,
|
||||
setValue,
|
||||
storageCondition,
|
||||
);
|
||||
|
||||
const handleChange = useCallback(
|
||||
(e: React.ChangeEvent<HTMLInputElement>, isChecked: boolean) => {
|
||||
if (!isAuthenticated) {
|
||||
setIsDialogOpen(true);
|
||||
e.preventDefault();
|
||||
return;
|
||||
}
|
||||
setWebSearch(isChecked);
|
||||
},
|
||||
[setWebSearch, setIsDialogOpen, isAuthenticated],
|
||||
);
|
||||
|
||||
const debouncedChange = useMemo(
|
||||
() => debounce(handleChange, 50, { leading: true }),
|
||||
[handleChange],
|
||||
);
|
||||
|
||||
if (!canUseWebSearch) {
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<>
|
||||
<CheckboxButton
|
||||
ref={triggerRef}
|
||||
className="max-w-fit"
|
||||
defaultChecked={webSearch}
|
||||
setValue={debouncedChange}
|
||||
label={localize('com_ui_search')}
|
||||
isCheckedClassName="border-blue-600/40 bg-blue-500/10 hover:bg-blue-700/10"
|
||||
icon={<Globe className="icon-md" />}
|
||||
/>
|
||||
<ApiKeyDialog
|
||||
onSubmit={onSubmit}
|
||||
authTypes={authTypes}
|
||||
isOpen={isDialogOpen}
|
||||
triggerRef={triggerRef}
|
||||
register={methods.register}
|
||||
onRevoke={handleRevokeApiKey}
|
||||
onOpenChange={setIsDialogOpen}
|
||||
handleSubmit={methods.handleSubmit}
|
||||
isToolAuthenticated={isAuthenticated}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export default memo(WebSearch);
|
||||
|
|
@ -2,10 +2,12 @@ import { memo, useMemo, useState } from 'react';
|
|||
import { useRecoilValue, useRecoilState } from 'recoil';
|
||||
import { ContentTypes } from 'librechat-data-provider';
|
||||
import type { TMessageContentParts, TAttachment, Agents } from 'librechat-data-provider';
|
||||
import { useSearchResultsByTurn } from '~/hooks/Messages/useSearchResultsByTurn';
|
||||
import { ThinkingButton } from '~/components/Artifacts/Thinking';
|
||||
import useLocalize from '~/hooks/useLocalize';
|
||||
import { mapAttachments } from '~/utils/map';
|
||||
import { MessageContext } from '~/Providers';
|
||||
import { MessageContext, SearchContext } from '~/Providers';
|
||||
import Sources from '~/components/Web/Sources';
|
||||
import { EditTextPart } from './Parts';
|
||||
import store from '~/store';
|
||||
import Part from './Part';
|
||||
|
|
@ -42,13 +44,15 @@ const ContentParts = memo(
|
|||
setSiblingIdx,
|
||||
}: ContentPartsProps) => {
|
||||
const localize = useLocalize();
|
||||
const messageAttachmentsMap = useRecoilValue(store.messageAttachmentsMap);
|
||||
const [showThinking, setShowThinking] = useRecoilState<boolean>(store.showThinking);
|
||||
const [isExpanded, setIsExpanded] = useState(showThinking);
|
||||
const messageAttachmentsMap = useRecoilValue(store.messageAttachmentsMap);
|
||||
const attachmentMap = useMemo(
|
||||
() => mapAttachments(attachments ?? messageAttachmentsMap[messageId] ?? []),
|
||||
const messageAttachments = useMemo(
|
||||
() => attachments ?? messageAttachmentsMap[messageId] ?? [],
|
||||
[attachments, messageAttachmentsMap, messageId],
|
||||
);
|
||||
const searchResults = useSearchResultsByTurn(messageAttachments);
|
||||
const attachmentMap = useMemo(() => mapAttachments(messageAttachments), [messageAttachments]);
|
||||
|
||||
const hasReasoningParts = useMemo(() => {
|
||||
const hasThinkPart = content?.some((part) => part?.type === ContentTypes.THINK) ?? false;
|
||||
|
|
@ -98,53 +102,56 @@ const ContentParts = memo(
|
|||
|
||||
return (
|
||||
<>
|
||||
{hasReasoningParts && (
|
||||
<div className="mb-5">
|
||||
<ThinkingButton
|
||||
isExpanded={isExpanded}
|
||||
onClick={() =>
|
||||
setIsExpanded((prev) => {
|
||||
const val = !prev;
|
||||
setShowThinking(val);
|
||||
return val;
|
||||
})
|
||||
}
|
||||
label={
|
||||
isSubmitting && isLast ? localize('com_ui_thinking') : localize('com_ui_thoughts')
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{content
|
||||
.filter((part) => part)
|
||||
.map((part, idx) => {
|
||||
const toolCallId =
|
||||
(part?.[ContentTypes.TOOL_CALL] as Agents.ToolCall | undefined)?.id ?? '';
|
||||
const attachments = attachmentMap[toolCallId];
|
||||
<SearchContext.Provider value={{ searchResults }}>
|
||||
<Sources />
|
||||
{hasReasoningParts && (
|
||||
<div className="mb-5">
|
||||
<ThinkingButton
|
||||
isExpanded={isExpanded}
|
||||
onClick={() =>
|
||||
setIsExpanded((prev) => {
|
||||
const val = !prev;
|
||||
setShowThinking(val);
|
||||
return val;
|
||||
})
|
||||
}
|
||||
label={
|
||||
isSubmitting && isLast ? localize('com_ui_thinking') : localize('com_ui_thoughts')
|
||||
}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
{content
|
||||
.filter((part) => part)
|
||||
.map((part, idx) => {
|
||||
const toolCallId =
|
||||
(part?.[ContentTypes.TOOL_CALL] as Agents.ToolCall | undefined)?.id ?? '';
|
||||
const attachments = attachmentMap[toolCallId];
|
||||
|
||||
return (
|
||||
<MessageContext.Provider
|
||||
key={`provider-${messageId}-${idx}`}
|
||||
value={{
|
||||
messageId,
|
||||
conversationId,
|
||||
partIndex: idx,
|
||||
isExpanded,
|
||||
nextType: content[idx + 1]?.type,
|
||||
}}
|
||||
>
|
||||
<Part
|
||||
part={part}
|
||||
attachments={attachments}
|
||||
isSubmitting={isSubmitting}
|
||||
key={`part-${messageId}-${idx}`}
|
||||
isCreatedByUser={isCreatedByUser}
|
||||
isLast={idx === content.length - 1}
|
||||
showCursor={idx === content.length - 1 && isLast}
|
||||
/>
|
||||
</MessageContext.Provider>
|
||||
);
|
||||
})}
|
||||
return (
|
||||
<MessageContext.Provider
|
||||
key={`provider-${messageId}-${idx}`}
|
||||
value={{
|
||||
messageId,
|
||||
isExpanded,
|
||||
conversationId,
|
||||
partIndex: idx,
|
||||
nextType: content[idx + 1]?.type,
|
||||
}}
|
||||
>
|
||||
<Part
|
||||
part={part}
|
||||
attachments={attachments}
|
||||
isSubmitting={isSubmitting}
|
||||
key={`part-${messageId}-${idx}`}
|
||||
isCreatedByUser={isCreatedByUser}
|
||||
isLast={idx === content.length - 1}
|
||||
showCursor={idx === content.length - 1 && isLast}
|
||||
/>
|
||||
</MessageContext.Provider>
|
||||
);
|
||||
})}
|
||||
</SearchContext.Provider>
|
||||
</>
|
||||
);
|
||||
},
|
||||
|
|
|
|||
|
|
@ -12,13 +12,16 @@ import type { Pluggable } from 'unified';
|
|||
import {
|
||||
useToastContext,
|
||||
ArtifactProvider,
|
||||
useSearchContext,
|
||||
CodeBlockProvider,
|
||||
useCodeBlockContext,
|
||||
} from '~/Providers';
|
||||
import { Citation, CompositeCitation, HighlightedText } from '~/components/Web/Citation';
|
||||
import { Artifact, artifactPlugin } from '~/components/Artifacts/Artifact';
|
||||
import { langSubset, preprocessLaTeX, handleDoubleClick } from '~/utils';
|
||||
import CodeBlock from '~/components/Messages/Content/CodeBlock';
|
||||
import useHasAccess from '~/hooks/Roles/useHasAccess';
|
||||
import { unicodeCitation } from '~/components/Web';
|
||||
import { useFileDownload } from '~/data-provider';
|
||||
import useLocalize from '~/hooks/useLocalize';
|
||||
import store from '~/store';
|
||||
|
|
@ -172,6 +175,7 @@ type TContentProps = {
|
|||
};
|
||||
|
||||
const Markdown = memo(({ content = '', isLatestMessage }: TContentProps) => {
|
||||
const { searchResults } = useSearchContext();
|
||||
const LaTeXParsing = useRecoilValue<boolean>(store.LaTeXParsing);
|
||||
const isInitializing = content === '';
|
||||
|
||||
|
|
@ -197,16 +201,22 @@ const Markdown = memo(({ content = '', isLatestMessage }: TContentProps) => {
|
|||
[],
|
||||
);
|
||||
|
||||
const remarkPlugins: Pluggable[] = useMemo(
|
||||
() => [
|
||||
const searchTurns = useMemo(() => Object.keys(searchResults ?? {}).length, [searchResults]);
|
||||
const remarkPlugins: Pluggable[] = useMemo(() => {
|
||||
const plugins: Pluggable[] = [
|
||||
supersub,
|
||||
remarkGfm,
|
||||
remarkDirective,
|
||||
artifactPlugin,
|
||||
[remarkMath, { singleDollarTextMath: true }],
|
||||
],
|
||||
[],
|
||||
);
|
||||
];
|
||||
|
||||
if (searchTurns > 0) {
|
||||
plugins.push(unicodeCitation);
|
||||
}
|
||||
|
||||
return plugins;
|
||||
}, [searchTurns]);
|
||||
|
||||
if (isInitializing) {
|
||||
return (
|
||||
|
|
@ -232,6 +242,9 @@ const Markdown = memo(({ content = '', isLatestMessage }: TContentProps) => {
|
|||
a,
|
||||
p,
|
||||
artifact: Artifact,
|
||||
citation: Citation,
|
||||
'highlighted-text': HighlightedText,
|
||||
'composite-citation': CompositeCitation,
|
||||
} as {
|
||||
[nodeType: string]: React.ElementType;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import { ErrorMessage } from './MessageContent';
|
|||
import RetrievalCall from './RetrievalCall';
|
||||
import CodeAnalyze from './CodeAnalyze';
|
||||
import Container from './Container';
|
||||
import WebSearch from './WebSearch';
|
||||
import ToolCall from './ToolCall';
|
||||
import ImageGen from './ImageGen';
|
||||
import Image from './Image';
|
||||
|
|
@ -107,6 +108,16 @@ const Part = memo(
|
|||
attachments={attachments}
|
||||
/>
|
||||
);
|
||||
} else if (isToolCall && toolCall.name === Tools.web_search) {
|
||||
return (
|
||||
<WebSearch
|
||||
output={toolCall.output ?? ''}
|
||||
initialProgress={toolCall.progress ?? 0.1}
|
||||
isSubmitting={isSubmitting}
|
||||
attachments={attachments}
|
||||
isLast={isLast}
|
||||
/>
|
||||
);
|
||||
} else if (isToolCall) {
|
||||
return (
|
||||
<ToolCall
|
||||
|
|
|
|||
|
|
@ -1,5 +1,5 @@
|
|||
import { memo, useState, useEffect } from 'react';
|
||||
import { imageExtRegex } from 'librechat-data-provider';
|
||||
import { imageExtRegex, Tools } from 'librechat-data-provider';
|
||||
import type { TAttachment, TFile, TAttachmentMetadata } from 'librechat-data-provider';
|
||||
import FileContainer from '~/components/Chat/Input/Files/FileContainer';
|
||||
import Image from '~/components/Chat/Messages/Content/Image';
|
||||
|
|
@ -7,12 +7,12 @@ import { useAttachmentLink } from './LogLink';
|
|||
import { cn } from '~/utils';
|
||||
|
||||
const FileAttachment = memo(({ attachment }: { attachment: Partial<TAttachment> }) => {
|
||||
const [isVisible, setIsVisible] = useState(false);
|
||||
const { handleDownload } = useAttachmentLink({
|
||||
href: attachment.filepath ?? '',
|
||||
filename: attachment.filename ?? '',
|
||||
});
|
||||
const extension = attachment.filename?.split('.').pop();
|
||||
const [isVisible, setIsVisible] = useState(false);
|
||||
|
||||
useEffect(() => {
|
||||
const timer = setTimeout(() => setIsVisible(true), 50);
|
||||
|
|
@ -84,6 +84,9 @@ export default function Attachment({ attachment }: { attachment?: TAttachment })
|
|||
if (!attachment) {
|
||||
return null;
|
||||
}
|
||||
if (attachment.type === Tools.web_search) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const { width, height, filepath = null } = attachment as TFile & TAttachmentMetadata;
|
||||
const isImage =
|
||||
|
|
@ -115,7 +118,7 @@ export function AttachmentGroup({ attachments }: { attachments?: TAttachment[] }
|
|||
|
||||
if (isImage) {
|
||||
imageAttachments.push(attachment);
|
||||
} else {
|
||||
} else if (attachment.type !== Tools.web_search) {
|
||||
fileAttachments.push(attachment);
|
||||
}
|
||||
});
|
||||
|
|
|
|||
91
client/src/components/Chat/Messages/Content/WebSearch.tsx
Normal file
91
client/src/components/Chat/Messages/Content/WebSearch.tsx
Normal file
|
|
@ -0,0 +1,91 @@
|
|||
import { useMemo } from 'react';
|
||||
import type { TAttachment } from 'librechat-data-provider';
|
||||
import { StackedFavicons } from '~/components/Web/Sources';
|
||||
import { useSearchContext } from '~/Providers';
|
||||
import ProgressText from './ProgressText';
|
||||
import { useLocalize } from '~/hooks';
|
||||
|
||||
type ProgressKeys =
|
||||
| 'com_ui_web_searching'
|
||||
| 'com_ui_web_searching_again'
|
||||
| 'com_ui_web_search_processing'
|
||||
| 'com_ui_web_search_reading';
|
||||
|
||||
export default function WebSearch({
|
||||
initialProgress: progress = 0.1,
|
||||
isSubmitting,
|
||||
isLast,
|
||||
output,
|
||||
}: {
|
||||
isLast?: boolean;
|
||||
isSubmitting: boolean;
|
||||
output?: string | null;
|
||||
initialProgress: number;
|
||||
attachments?: TAttachment[];
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
const { searchResults } = useSearchContext();
|
||||
const error = typeof output === 'string' && output.toLowerCase().includes('error processing');
|
||||
const cancelled = (!isSubmitting && progress < 1) || error === true;
|
||||
|
||||
const complete = !isLast && progress === 1;
|
||||
const finalizing = isSubmitting && isLast && progress === 1;
|
||||
const processedSources = useMemo(() => {
|
||||
if (complete && !finalizing) {
|
||||
return [];
|
||||
}
|
||||
if (!searchResults) return [];
|
||||
const values = Object.values(searchResults);
|
||||
const result = values[values.length - 1];
|
||||
if (!result) return [];
|
||||
if (finalizing) {
|
||||
return [...(result.organic || []), ...(result.topStories || [])];
|
||||
}
|
||||
return [...(result.organic || []), ...(result.topStories || [])].filter(
|
||||
(source) => source.processed === true,
|
||||
);
|
||||
}, [searchResults, complete, finalizing]);
|
||||
const turns = useMemo(() => {
|
||||
if (!searchResults) return 0;
|
||||
return Object.values(searchResults).length;
|
||||
}, [searchResults]);
|
||||
|
||||
const clampedProgress = useMemo(() => {
|
||||
return Math.min(progress, 0.99);
|
||||
}, [progress]);
|
||||
|
||||
const showSources = processedSources.length > 0;
|
||||
const progressText = useMemo(() => {
|
||||
let text: ProgressKeys = turns > 1 ? '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);
|
||||
}, [turns, localize, showSources, finalizing]);
|
||||
|
||||
if (complete || cancelled) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<>
|
||||
<div className="relative my-2.5 flex size-5 shrink-0 items-center gap-2.5">
|
||||
{showSources && (
|
||||
<div className="mr-2">
|
||||
<StackedFavicons sources={processedSources} start={-5} />
|
||||
</div>
|
||||
)}
|
||||
<ProgressText
|
||||
finishedText=""
|
||||
hasInput={false}
|
||||
error={cancelled}
|
||||
isExpanded={false}
|
||||
progress={clampedProgress}
|
||||
inProgressText={progressText}
|
||||
/>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -13,6 +13,7 @@ import { processAgentOption } from '~/utils';
|
|||
import Instructions from './Instructions';
|
||||
import AgentAvatar from './AgentAvatar';
|
||||
import FileContext from './FileContext';
|
||||
import SearchForm from './Search/Form';
|
||||
import { useLocalize } from '~/hooks';
|
||||
import FileSearch from './FileSearch';
|
||||
import Artifacts from './Artifacts';
|
||||
|
|
@ -73,6 +74,10 @@ export default function AgentConfig({
|
|||
() => agentsConfig?.capabilities?.includes(AgentCapabilities.file_search) ?? false,
|
||||
[agentsConfig],
|
||||
);
|
||||
const webSearchEnabled = useMemo(
|
||||
() => agentsConfig?.capabilities?.includes(AgentCapabilities.web_search) ?? false,
|
||||
[agentsConfig],
|
||||
);
|
||||
const codeEnabled = useMemo(
|
||||
() => agentsConfig?.capabilities?.includes(AgentCapabilities.execute_code) ?? false,
|
||||
[agentsConfig],
|
||||
|
|
@ -257,13 +262,19 @@ export default function AgentConfig({
|
|||
</div>
|
||||
</button>
|
||||
</div>
|
||||
{(codeEnabled || fileSearchEnabled || artifactsEnabled || ocrEnabled) && (
|
||||
{(codeEnabled ||
|
||||
fileSearchEnabled ||
|
||||
artifactsEnabled ||
|
||||
ocrEnabled ||
|
||||
webSearchEnabled) && (
|
||||
<div className="mb-4 flex w-full flex-col items-start gap-3">
|
||||
<label className="text-token-text-primary block font-medium">
|
||||
{localize('com_assistants_capabilities')}
|
||||
</label>
|
||||
{/* Code Execution */}
|
||||
{codeEnabled && <CodeForm agent_id={agent_id} files={code_files} />}
|
||||
{/* Web Search */}
|
||||
{webSearchEnabled && <SearchForm />}
|
||||
{/* File Context (OCR) */}
|
||||
{ocrEnabled && <FileContext agent_id={agent_id} files={context_files} />}
|
||||
{/* Artifacts */}
|
||||
|
|
|
|||
|
|
@ -162,6 +162,9 @@ export default function AgentPanel({
|
|||
if (data.file_search === true) {
|
||||
tools.push(Tools.file_search);
|
||||
}
|
||||
if (data.web_search === true) {
|
||||
tools.push(Tools.web_search);
|
||||
}
|
||||
|
||||
const {
|
||||
name,
|
||||
|
|
|
|||
|
|
@ -52,6 +52,7 @@ export default function AgentSelect({
|
|||
};
|
||||
|
||||
const capabilities: TAgentCapabilities = {
|
||||
[AgentCapabilities.web_search]: false,
|
||||
[AgentCapabilities.file_search]: false,
|
||||
[AgentCapabilities.execute_code]: false,
|
||||
[AgentCapabilities.end_after_tools]: false,
|
||||
|
|
|
|||
|
|
@ -3,6 +3,7 @@ import type { ApiKeyFormData } from '~/common';
|
|||
import OGDialogTemplate from '~/components/ui/OGDialogTemplate';
|
||||
import { Input, Button, OGDialog } from '~/components/ui';
|
||||
import { useLocalize } from '~/hooks';
|
||||
import type { RefObject } from 'react';
|
||||
|
||||
export default function ApiKeyDialog({
|
||||
isOpen,
|
||||
|
|
@ -13,6 +14,7 @@ export default function ApiKeyDialog({
|
|||
isToolAuthenticated,
|
||||
register,
|
||||
handleSubmit,
|
||||
triggerRef,
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
|
|
@ -22,6 +24,7 @@ export default function ApiKeyDialog({
|
|||
isToolAuthenticated: boolean;
|
||||
register: UseFormRegister<ApiKeyFormData>;
|
||||
handleSubmit: UseFormHandleSubmit<ApiKeyFormData>;
|
||||
triggerRef?: RefObject<HTMLInputElement>;
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
const languageIcons = [
|
||||
|
|
@ -38,7 +41,7 @@ export default function ApiKeyDialog({
|
|||
];
|
||||
|
||||
return (
|
||||
<OGDialog open={isOpen} onOpenChange={onOpenChange}>
|
||||
<OGDialog open={isOpen} onOpenChange={onOpenChange} triggerRef={triggerRef}>
|
||||
<OGDialogTemplate
|
||||
className="w-11/12 sm:w-[450px]"
|
||||
title=""
|
||||
|
|
|
|||
121
client/src/components/SidePanel/Agents/Search/Action.tsx
Normal file
121
client/src/components/SidePanel/Agents/Search/Action.tsx
Normal file
|
|
@ -0,0 +1,121 @@
|
|||
import { KeyRoundIcon } from 'lucide-react';
|
||||
import { AuthType, AgentCapabilities } from 'librechat-data-provider';
|
||||
import { useFormContext, Controller, useWatch } from 'react-hook-form';
|
||||
import type { AgentForm } from '~/common';
|
||||
import {
|
||||
Checkbox,
|
||||
HoverCard,
|
||||
HoverCardContent,
|
||||
HoverCardPortal,
|
||||
HoverCardTrigger,
|
||||
} from '~/components/ui';
|
||||
import { useLocalize, useSearchApiKeyForm } from '~/hooks';
|
||||
import { CircleHelpIcon } from '~/components/svg';
|
||||
import ApiKeyDialog from './ApiKeyDialog';
|
||||
import { ESide } from '~/common';
|
||||
|
||||
export default function Action({
|
||||
authTypes = [],
|
||||
isToolAuthenticated = false,
|
||||
}: {
|
||||
authTypes?: [string, AuthType][];
|
||||
isToolAuthenticated?: boolean;
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
const methods = useFormContext<AgentForm>();
|
||||
const { control, setValue, getValues } = methods;
|
||||
const {
|
||||
onSubmit,
|
||||
isDialogOpen,
|
||||
setIsDialogOpen,
|
||||
handleRevokeApiKey,
|
||||
methods: keyFormMethods,
|
||||
} = useSearchApiKeyForm({
|
||||
onSubmit: () => {
|
||||
setValue(AgentCapabilities.web_search, true, { shouldDirty: true });
|
||||
},
|
||||
onRevoke: () => {
|
||||
setValue(AgentCapabilities.web_search, false, { shouldDirty: true });
|
||||
},
|
||||
});
|
||||
|
||||
const webSearchIsEnabled = useWatch({ control, name: AgentCapabilities.web_search });
|
||||
const isUserProvided = authTypes?.some(([, authType]) => authType === AuthType.USER_PROVIDED);
|
||||
|
||||
const handleCheckboxChange = (checked: boolean) => {
|
||||
if (isToolAuthenticated) {
|
||||
setValue(AgentCapabilities.web_search, checked, { shouldDirty: true });
|
||||
} else if (webSearchIsEnabled) {
|
||||
setValue(AgentCapabilities.web_search, false, { shouldDirty: true });
|
||||
} else {
|
||||
setIsDialogOpen(true);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
<HoverCard openDelay={50}>
|
||||
<div className="flex items-center">
|
||||
<Controller
|
||||
name={AgentCapabilities.web_search}
|
||||
control={control}
|
||||
render={({ field }) => (
|
||||
<Checkbox
|
||||
{...field}
|
||||
checked={
|
||||
webSearchIsEnabled ? webSearchIsEnabled : isToolAuthenticated && field.value
|
||||
}
|
||||
onCheckedChange={handleCheckboxChange}
|
||||
className="relative float-left mr-2 inline-flex h-4 w-4 cursor-pointer"
|
||||
value={field.value.toString()}
|
||||
disabled={webSearchIsEnabled ? false : !isToolAuthenticated}
|
||||
/>
|
||||
)}
|
||||
/>
|
||||
<button
|
||||
type="button"
|
||||
className="flex items-center space-x-2"
|
||||
onClick={() => {
|
||||
const value = !getValues(AgentCapabilities.web_search);
|
||||
handleCheckboxChange(value);
|
||||
}}
|
||||
>
|
||||
<label
|
||||
className="form-check-label text-token-text-primary w-full cursor-pointer"
|
||||
htmlFor={AgentCapabilities.web_search}
|
||||
>
|
||||
{localize('com_ui_web_search')}
|
||||
</label>
|
||||
</button>
|
||||
<div className="ml-2 flex gap-2">
|
||||
{isUserProvided && (isToolAuthenticated || webSearchIsEnabled) && (
|
||||
<button type="button" onClick={() => setIsDialogOpen(true)}>
|
||||
<KeyRoundIcon className="h-5 w-5 text-text-primary" />
|
||||
</button>
|
||||
)}
|
||||
<HoverCardTrigger>
|
||||
<CircleHelpIcon className="h-4 w-4 text-text-tertiary" />
|
||||
</HoverCardTrigger>
|
||||
</div>
|
||||
<HoverCardPortal>
|
||||
<HoverCardContent side={ESide.Top} className="w-80">
|
||||
<div className="space-y-2">
|
||||
<p className="text-sm text-text-secondary">{localize('com_agents_search_info')}</p>
|
||||
</div>
|
||||
</HoverCardContent>
|
||||
</HoverCardPortal>
|
||||
</div>
|
||||
</HoverCard>
|
||||
<ApiKeyDialog
|
||||
onSubmit={onSubmit}
|
||||
authTypes={authTypes}
|
||||
isOpen={isDialogOpen}
|
||||
onRevoke={handleRevokeApiKey}
|
||||
onOpenChange={setIsDialogOpen}
|
||||
register={keyFormMethods.register}
|
||||
isToolAuthenticated={isToolAuthenticated}
|
||||
handleSubmit={keyFormMethods.handleSubmit}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
|
@ -0,0 +1,148 @@
|
|||
import React from 'react';
|
||||
import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import ApiKeyDialog from './ApiKeyDialog';
|
||||
import { AuthType, SearchCategories, RerankerTypes } from 'librechat-data-provider';
|
||||
import { useGetStartupConfig } from '~/data-provider';
|
||||
|
||||
// Mock useLocalize to just return the key
|
||||
jest.mock('~/hooks', () => ({
|
||||
useLocalize: () => (key: string) => key,
|
||||
}));
|
||||
|
||||
jest.mock('~/data-provider', () => ({
|
||||
useGetStartupConfig: jest.fn(),
|
||||
}));
|
||||
|
||||
const mockRegister = (name: string) => ({
|
||||
onChange: jest.fn(),
|
||||
onBlur: jest.fn(),
|
||||
ref: jest.fn(),
|
||||
name,
|
||||
});
|
||||
|
||||
const defaultProps = {
|
||||
isOpen: true,
|
||||
onOpenChange: jest.fn(),
|
||||
onSubmit: jest.fn(),
|
||||
onRevoke: jest.fn(),
|
||||
authTypes: [
|
||||
[SearchCategories.PROVIDERS, AuthType.USER_PROVIDED] as [string, AuthType],
|
||||
[SearchCategories.SCRAPERS, AuthType.USER_PROVIDED] as [string, AuthType],
|
||||
[SearchCategories.RERANKERS, AuthType.USER_PROVIDED] as [string, AuthType],
|
||||
],
|
||||
isToolAuthenticated: false,
|
||||
register: mockRegister as any,
|
||||
handleSubmit: (fn: any) => (e: any) => fn(e),
|
||||
};
|
||||
|
||||
describe('ApiKeyDialog', () => {
|
||||
const mockUseGetStartupConfig = useGetStartupConfig as jest.Mock;
|
||||
|
||||
afterEach(() => jest.clearAllMocks());
|
||||
|
||||
it('shows all dropdowns and both reranker fields when no config is set', () => {
|
||||
mockUseGetStartupConfig.mockReturnValue({ data: {} });
|
||||
render(<ApiKeyDialog {...defaultProps} />);
|
||||
// Provider dropdown button
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'com_ui_web_search_provider_serper' }),
|
||||
).toBeInTheDocument();
|
||||
// Scraper dropdown button
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'com_ui_web_search_scraper_firecrawl' }),
|
||||
).toBeInTheDocument();
|
||||
// Reranker dropdown button
|
||||
expect(
|
||||
screen.getByRole('button', { name: 'com_ui_web_search_reranker_jina' }),
|
||||
).toBeInTheDocument();
|
||||
// Reranker fields (default is Jina)
|
||||
expect(screen.getByPlaceholderText('com_ui_web_search_jina_key')).toBeInTheDocument();
|
||||
// Switch to Cohere
|
||||
fireEvent.click(screen.getByText('com_ui_web_search_reranker_cohere'));
|
||||
expect(screen.getByPlaceholderText('com_ui_web_search_cohere_key')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows static text for provider and only provider input if provider is set', () => {
|
||||
mockUseGetStartupConfig.mockReturnValue({ data: { webSearch: { searchProvider: 'serper' } } });
|
||||
render(<ApiKeyDialog {...defaultProps} />);
|
||||
expect(screen.getByText('com_ui_web_search_provider_serper')).toBeInTheDocument();
|
||||
// Should not find a dropdown button for provider
|
||||
expect(screen.queryByRole('button', { name: /provider/i })).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows only Jina reranker field if rerankerType is set to jina', () => {
|
||||
mockUseGetStartupConfig.mockReturnValue({
|
||||
data: { webSearch: { rerankerType: RerankerTypes.JINA } },
|
||||
});
|
||||
render(<ApiKeyDialog {...defaultProps} />);
|
||||
expect(screen.getByPlaceholderText('com_ui_web_search_jina_key')).toBeInTheDocument();
|
||||
expect(screen.queryByPlaceholderText('com_ui_web_search_cohere_key')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows only Cohere reranker field if rerankerType is set to cohere', () => {
|
||||
mockUseGetStartupConfig.mockReturnValue({
|
||||
data: { webSearch: { rerankerType: RerankerTypes.COHERE } },
|
||||
});
|
||||
render(<ApiKeyDialog {...defaultProps} />);
|
||||
expect(screen.getByPlaceholderText('com_ui_web_search_cohere_key')).toBeInTheDocument();
|
||||
expect(screen.queryByPlaceholderText('com_ui_web_search_jina_key')).not.toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows documentation link for the visible reranker', () => {
|
||||
mockUseGetStartupConfig.mockReturnValue({ data: {} });
|
||||
render(<ApiKeyDialog {...defaultProps} />);
|
||||
// Default is Jina
|
||||
expect(screen.getByText('com_ui_web_search_reranker_jina_key')).toBeInTheDocument();
|
||||
// Switch to Cohere
|
||||
fireEvent.click(screen.getByText('com_ui_web_search_reranker_cohere'));
|
||||
expect(screen.getByText('com_ui_web_search_reranker_cohere_key')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render provider section if SYSTEM_DEFINED', () => {
|
||||
mockUseGetStartupConfig.mockReturnValue({ data: {} });
|
||||
const props = {
|
||||
...defaultProps,
|
||||
authTypes: [
|
||||
[SearchCategories.PROVIDERS, AuthType.SYSTEM_DEFINED],
|
||||
[SearchCategories.SCRAPERS, AuthType.USER_PROVIDED],
|
||||
[SearchCategories.RERANKERS, AuthType.USER_PROVIDED],
|
||||
] as [string, AuthType][],
|
||||
};
|
||||
render(<ApiKeyDialog {...props} />);
|
||||
expect(screen.queryByText('com_ui_web_search_provider')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('com_ui_web_search_scraper')).toBeInTheDocument();
|
||||
expect(screen.getByText('com_ui_web_search_reranker')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render scraper section if SYSTEM_DEFINED', () => {
|
||||
mockUseGetStartupConfig.mockReturnValue({ data: {} });
|
||||
const props = {
|
||||
...defaultProps,
|
||||
authTypes: [
|
||||
[SearchCategories.PROVIDERS, AuthType.USER_PROVIDED],
|
||||
[SearchCategories.SCRAPERS, AuthType.SYSTEM_DEFINED],
|
||||
[SearchCategories.RERANKERS, AuthType.USER_PROVIDED],
|
||||
] as [string, AuthType][],
|
||||
};
|
||||
render(<ApiKeyDialog {...props} />);
|
||||
expect(screen.getByText('com_ui_web_search_provider')).toBeInTheDocument();
|
||||
expect(screen.queryByText('com_ui_web_search_scraper')).not.toBeInTheDocument();
|
||||
expect(screen.getByText('com_ui_web_search_reranker')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render reranker section if SYSTEM_DEFINED', () => {
|
||||
mockUseGetStartupConfig.mockReturnValue({ data: {} });
|
||||
const props = {
|
||||
...defaultProps,
|
||||
authTypes: [
|
||||
[SearchCategories.PROVIDERS, AuthType.USER_PROVIDED],
|
||||
[SearchCategories.SCRAPERS, AuthType.USER_PROVIDED],
|
||||
[SearchCategories.RERANKERS, AuthType.SYSTEM_DEFINED],
|
||||
] as [string, AuthType][],
|
||||
};
|
||||
render(<ApiKeyDialog {...props} />);
|
||||
expect(screen.getByText('com_ui_web_search_provider')).toBeInTheDocument();
|
||||
expect(screen.getByText('com_ui_web_search_scraper')).toBeInTheDocument();
|
||||
expect(screen.queryByText('com_ui_web_search_reranker')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
361
client/src/components/SidePanel/Agents/Search/ApiKeyDialog.tsx
Normal file
361
client/src/components/SidePanel/Agents/Search/ApiKeyDialog.tsx
Normal file
|
|
@ -0,0 +1,361 @@
|
|||
import { useState } from 'react';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
import * as Menu from '@ariakit/react/menu';
|
||||
import { AuthType, SearchCategories, RerankerTypes } from 'librechat-data-provider';
|
||||
import type { UseFormRegister, UseFormHandleSubmit } from 'react-hook-form';
|
||||
import type { SearchApiKeyFormData } from '~/hooks/Plugins/useAuthSearchTool';
|
||||
import type { MenuItemProps } from '~/common';
|
||||
import { Input, Button, OGDialog, Label } from '~/components/ui';
|
||||
import OGDialogTemplate from '~/components/ui/OGDialogTemplate';
|
||||
import DropdownPopup from '~/components/ui/DropdownPopup';
|
||||
import { useGetStartupConfig } from '~/data-provider';
|
||||
import { useLocalize } from '~/hooks';
|
||||
|
||||
export default function ApiKeyDialog({
|
||||
isOpen,
|
||||
onSubmit,
|
||||
onRevoke,
|
||||
onOpenChange,
|
||||
authTypes,
|
||||
isToolAuthenticated,
|
||||
register,
|
||||
handleSubmit,
|
||||
triggerRef,
|
||||
}: {
|
||||
isOpen: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onSubmit: (data: SearchApiKeyFormData) => void;
|
||||
onRevoke: () => void;
|
||||
authTypes: [string, AuthType][];
|
||||
isToolAuthenticated: boolean;
|
||||
register: UseFormRegister<SearchApiKeyFormData>;
|
||||
handleSubmit: UseFormHandleSubmit<SearchApiKeyFormData>;
|
||||
triggerRef?: React.RefObject<HTMLInputElement>;
|
||||
}) {
|
||||
const localize = useLocalize();
|
||||
const { data: config } = useGetStartupConfig();
|
||||
const [selectedReranker, setSelectedReranker] = useState<
|
||||
RerankerTypes.JINA | RerankerTypes.COHERE
|
||||
>(
|
||||
config?.webSearch?.rerankerType === RerankerTypes.COHERE
|
||||
? RerankerTypes.COHERE
|
||||
: RerankerTypes.JINA,
|
||||
);
|
||||
|
||||
const [providerDropdownOpen, setProviderDropdownOpen] = useState(false);
|
||||
const [scraperDropdownOpen, setScraperDropdownOpen] = useState(false);
|
||||
const [rerankerDropdownOpen, setRerankerDropdownOpen] = useState(false);
|
||||
|
||||
const providerItems: MenuItemProps[] = [
|
||||
{
|
||||
label: localize('com_ui_web_search_provider_serper'),
|
||||
onClick: () => {},
|
||||
},
|
||||
];
|
||||
|
||||
const scraperItems: MenuItemProps[] = [
|
||||
{
|
||||
label: localize('com_ui_web_search_scraper_firecrawl'),
|
||||
onClick: () => {},
|
||||
},
|
||||
];
|
||||
|
||||
const rerankerItems: MenuItemProps[] = [
|
||||
{
|
||||
label: localize('com_ui_web_search_reranker_jina'),
|
||||
onClick: () => setSelectedReranker(RerankerTypes.JINA),
|
||||
},
|
||||
{
|
||||
label: localize('com_ui_web_search_reranker_cohere'),
|
||||
onClick: () => setSelectedReranker(RerankerTypes.COHERE),
|
||||
},
|
||||
];
|
||||
|
||||
const showProviderDropdown = !config?.webSearch?.searchProvider;
|
||||
const showScraperDropdown = !config?.webSearch?.scraperType;
|
||||
const showRerankerDropdown = !config?.webSearch?.rerankerType;
|
||||
|
||||
// Determine which categories are SYSTEM_DEFINED
|
||||
const providerAuthType = authTypes.find(([cat]) => cat === SearchCategories.PROVIDERS)?.[1];
|
||||
const scraperAuthType = authTypes.find(([cat]) => cat === SearchCategories.SCRAPERS)?.[1];
|
||||
const rerankerAuthType = authTypes.find(([cat]) => cat === SearchCategories.RERANKERS)?.[1];
|
||||
|
||||
function renderRerankerInput() {
|
||||
if (config?.webSearch?.rerankerType === RerankerTypes.JINA) {
|
||||
return (
|
||||
<>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder={localize('com_ui_web_search_jina_key')}
|
||||
autoComplete="one-time-code"
|
||||
readOnly={true}
|
||||
onFocus={(e) => (e.target.readOnly = false)}
|
||||
{...register('jinaApiKey')}
|
||||
/>
|
||||
<div className="mt-1 text-xs text-text-secondary">
|
||||
<a
|
||||
href="https://jina.ai/api-dashboard/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
|
||||
>
|
||||
{localize('com_ui_web_search_reranker_jina_key')}
|
||||
</a>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (config?.webSearch?.rerankerType === RerankerTypes.COHERE) {
|
||||
return (
|
||||
<>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder={localize('com_ui_web_search_cohere_key')}
|
||||
autoComplete="one-time-code"
|
||||
readOnly={true}
|
||||
onFocus={(e) => (e.target.readOnly = false)}
|
||||
{...register('cohereApiKey')}
|
||||
/>
|
||||
<div className="mt-1 text-xs text-text-secondary">
|
||||
<a
|
||||
href="https://dashboard.cohere.com/welcome/login"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
|
||||
>
|
||||
{localize('com_ui_web_search_reranker_cohere_key')}
|
||||
</a>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (!config?.webSearch?.rerankerType && selectedReranker === RerankerTypes.JINA) {
|
||||
return (
|
||||
<>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder={localize('com_ui_web_search_jina_key')}
|
||||
autoComplete="one-time-code"
|
||||
readOnly={true}
|
||||
onFocus={(e) => (e.target.readOnly = false)}
|
||||
{...register('jinaApiKey')}
|
||||
/>
|
||||
<div className="mt-1 text-xs text-text-secondary">
|
||||
<a
|
||||
href="https://jina.ai/api-dashboard/"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
|
||||
>
|
||||
{localize('com_ui_web_search_reranker_jina_key')}
|
||||
</a>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
if (!config?.webSearch?.rerankerType && selectedReranker === RerankerTypes.COHERE) {
|
||||
return (
|
||||
<>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder={localize('com_ui_web_search_cohere_key')}
|
||||
autoComplete="one-time-code"
|
||||
readOnly={true}
|
||||
onFocus={(e) => (e.target.readOnly = false)}
|
||||
{...register('cohereApiKey')}
|
||||
/>
|
||||
<div className="mt-1 text-xs text-text-secondary">
|
||||
<a
|
||||
href="https://dashboard.cohere.com/welcome/login"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
|
||||
>
|
||||
{localize('com_ui_web_search_reranker_cohere_key')}
|
||||
</a>
|
||||
</div>
|
||||
</>
|
||||
);
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
return (
|
||||
<OGDialog open={isOpen} onOpenChange={onOpenChange} triggerRef={triggerRef}>
|
||||
<OGDialogTemplate
|
||||
className="w-11/12 sm:w-[500px]"
|
||||
title=""
|
||||
main={
|
||||
<>
|
||||
<div className="mb-4 text-center font-medium">{localize('com_ui_web_search')}</div>
|
||||
<div className="mb-4 text-center text-sm">
|
||||
{localize('com_ui_web_search_api_subtitle')}
|
||||
</div>
|
||||
<form onSubmit={handleSubmit(onSubmit)}>
|
||||
{/* Search Provider Section */}
|
||||
{providerAuthType !== AuthType.SYSTEM_DEFINED && (
|
||||
<div className="mb-6">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<Label className="text-md w-fit font-medium">
|
||||
{localize('com_ui_web_search_provider')}
|
||||
</Label>
|
||||
{showProviderDropdown ? (
|
||||
<DropdownPopup
|
||||
menuId="search-provider-dropdown"
|
||||
items={providerItems}
|
||||
isOpen={providerDropdownOpen}
|
||||
setIsOpen={setProviderDropdownOpen}
|
||||
trigger={
|
||||
<Menu.MenuButton
|
||||
onClick={() => setProviderDropdownOpen(!providerDropdownOpen)}
|
||||
className="flex items-center rounded-md border border-border-light px-3 py-1 text-sm text-text-secondary"
|
||||
>
|
||||
{localize('com_ui_web_search_provider_serper')}
|
||||
<ChevronDown className="ml-1 h-4 w-4" />
|
||||
</Menu.MenuButton>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<div className="text-sm text-text-secondary">
|
||||
{localize('com_ui_web_search_provider_serper')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder={`${localize('com_ui_enter_api_key')}`}
|
||||
autoComplete="one-time-code"
|
||||
readOnly={true}
|
||||
onFocus={(e) => (e.target.readOnly = false)}
|
||||
{...register('serperApiKey', { required: true })}
|
||||
/>
|
||||
<div className="mt-1 text-xs text-text-secondary">
|
||||
<a
|
||||
href="https://serper.dev/api-key"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
|
||||
>
|
||||
{localize('com_ui_web_search_provider_serper_key')}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Scraper Section */}
|
||||
{scraperAuthType !== AuthType.SYSTEM_DEFINED && (
|
||||
<div className="mb-6">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<Label className="text-md w-fit font-medium">
|
||||
{localize('com_ui_web_search_scraper')}
|
||||
</Label>
|
||||
{showScraperDropdown ? (
|
||||
<DropdownPopup
|
||||
menuId="scraper-dropdown"
|
||||
items={scraperItems}
|
||||
isOpen={scraperDropdownOpen}
|
||||
setIsOpen={setScraperDropdownOpen}
|
||||
trigger={
|
||||
<Menu.MenuButton
|
||||
onClick={() => setScraperDropdownOpen(!scraperDropdownOpen)}
|
||||
className="flex items-center rounded-md border border-border-light px-3 py-1 text-sm text-text-secondary"
|
||||
>
|
||||
{localize('com_ui_web_search_scraper_firecrawl')}
|
||||
<ChevronDown className="ml-1 h-4 w-4" />
|
||||
</Menu.MenuButton>
|
||||
}
|
||||
/>
|
||||
) : (
|
||||
<div className="text-sm text-text-secondary">
|
||||
{localize('com_ui_web_search_scraper_firecrawl')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<Input
|
||||
type="password"
|
||||
placeholder={`${localize('com_ui_enter_api_key')}`}
|
||||
autoComplete="one-time-code"
|
||||
readOnly={true}
|
||||
onFocus={(e) => (e.target.readOnly = false)}
|
||||
className="mb-2"
|
||||
{...register('firecrawlApiKey')}
|
||||
/>
|
||||
<Input
|
||||
type="text"
|
||||
placeholder={localize('com_ui_web_search_firecrawl_url')}
|
||||
className="mb-1"
|
||||
{...register('firecrawlApiUrl')}
|
||||
/>
|
||||
<div className="mt-1 text-xs text-text-secondary">
|
||||
<a
|
||||
href="https://docs.firecrawl.dev/introduction#api-key"
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-blue-500 hover:text-blue-600 dark:text-blue-400 dark:hover:text-blue-300"
|
||||
>
|
||||
{localize('com_ui_web_search_scraper_firecrawl_key')}
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Reranker Section */}
|
||||
{rerankerAuthType !== AuthType.SYSTEM_DEFINED && (
|
||||
<div className="mb-6">
|
||||
<div className="mb-2 flex items-center justify-between">
|
||||
<Label className="text-md w-fit font-medium">
|
||||
{localize('com_ui_web_search_reranker')}
|
||||
</Label>
|
||||
{showRerankerDropdown && (
|
||||
<DropdownPopup
|
||||
menuId="reranker-dropdown"
|
||||
isOpen={rerankerDropdownOpen}
|
||||
setIsOpen={setRerankerDropdownOpen}
|
||||
items={rerankerItems}
|
||||
trigger={
|
||||
<Menu.MenuButton
|
||||
onClick={() => setRerankerDropdownOpen(!rerankerDropdownOpen)}
|
||||
className="flex items-center rounded-md border border-border-light px-3 py-1 text-sm text-text-secondary"
|
||||
>
|
||||
{selectedReranker === RerankerTypes.JINA
|
||||
? localize('com_ui_web_search_reranker_jina')
|
||||
: localize('com_ui_web_search_reranker_cohere')}
|
||||
<ChevronDown className="ml-1 h-4 w-4" />
|
||||
</Menu.MenuButton>
|
||||
}
|
||||
/>
|
||||
)}
|
||||
{!showRerankerDropdown && (
|
||||
<div className="text-sm text-text-secondary">
|
||||
{config?.webSearch?.rerankerType === RerankerTypes.COHERE
|
||||
? localize('com_ui_web_search_reranker_cohere')
|
||||
: localize('com_ui_web_search_reranker_jina')}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
{renderRerankerInput()}
|
||||
</div>
|
||||
)}
|
||||
</form>
|
||||
</>
|
||||
}
|
||||
selection={{
|
||||
selectHandler: handleSubmit(onSubmit),
|
||||
selectClasses: 'bg-green-500 hover:bg-green-600 text-white',
|
||||
selectText: localize('com_ui_save'),
|
||||
}}
|
||||
buttons={
|
||||
isToolAuthenticated && (
|
||||
<Button
|
||||
onClick={onRevoke}
|
||||
className="bg-destructive text-white transition-all duration-200 hover:bg-destructive/80"
|
||||
>
|
||||
{localize('com_ui_revoke')}
|
||||
</Button>
|
||||
)
|
||||
}
|
||||
showCancelButton={true}
|
||||
/>
|
||||
</OGDialog>
|
||||
);
|
||||
}
|
||||
31
client/src/components/SidePanel/Agents/Search/Form.tsx
Normal file
31
client/src/components/SidePanel/Agents/Search/Form.tsx
Normal file
|
|
@ -0,0 +1,31 @@
|
|||
import { Tools } from 'librechat-data-provider';
|
||||
import { useVerifyAgentToolAuth } from '~/data-provider';
|
||||
import { useLocalize } from '~/hooks';
|
||||
import Action from './Action';
|
||||
|
||||
export default function SearchForm() {
|
||||
const localize = useLocalize();
|
||||
const { data } = useVerifyAgentToolAuth(
|
||||
{ toolId: Tools.web_search },
|
||||
{
|
||||
retry: 1,
|
||||
},
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="w-full">
|
||||
<div className="mb-1.5 flex items-center gap-2">
|
||||
<div className="flex flex-row items-center gap-1">
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="text-token-text-primary block font-medium">
|
||||
{localize('com_ui_web_search')}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col items-start gap-2">
|
||||
<Action authTypes={data?.authTypes} isToolAuthenticated={data?.authenticated} />
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
168
client/src/components/Web/Citation.tsx
Normal file
168
client/src/components/Web/Citation.tsx
Normal file
|
|
@ -0,0 +1,168 @@
|
|||
import { memo, useState, useContext } from 'react';
|
||||
import type { CitationProps } from './types';
|
||||
import { SourceHovercard, FaviconImage, getCleanDomain } from '~/components/Web/SourceHovercard';
|
||||
import { CitationContext, useCitation, useCompositeCitations } from './Context';
|
||||
import { useLocalize } from '~/hooks';
|
||||
|
||||
interface CompositeCitationProps {
|
||||
citationId?: string;
|
||||
node?: {
|
||||
properties?: CitationProps;
|
||||
};
|
||||
}
|
||||
|
||||
export function CompositeCitation(props: CompositeCitationProps) {
|
||||
const localize = useLocalize();
|
||||
const { citations, citationId } = props.node?.properties ?? ({} as CitationProps);
|
||||
const { setHoveredCitationId } = useContext(CitationContext);
|
||||
const [currentPage, setCurrentPage] = useState(0);
|
||||
const sources = useCompositeCitations(citations || []);
|
||||
|
||||
if (!sources || sources.length === 0) return null;
|
||||
const totalPages = sources.length;
|
||||
|
||||
const getCitationLabel = () => {
|
||||
if (!sources || sources.length === 0) return localize('com_citation_source');
|
||||
|
||||
const firstSource = sources[0];
|
||||
const remainingCount = sources.length - 1;
|
||||
const attribution =
|
||||
firstSource.attribution ||
|
||||
firstSource.title ||
|
||||
getCleanDomain(firstSource.link || '') ||
|
||||
localize('com_citation_source');
|
||||
|
||||
return remainingCount > 0 ? `${attribution} +${remainingCount}` : attribution;
|
||||
};
|
||||
|
||||
const handlePrevPage = (e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (currentPage > 0) {
|
||||
setCurrentPage(currentPage - 1);
|
||||
}
|
||||
};
|
||||
|
||||
const handleNextPage = (e: React.MouseEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
if (currentPage < totalPages - 1) {
|
||||
setCurrentPage(currentPage + 1);
|
||||
}
|
||||
};
|
||||
|
||||
const currentSource = sources?.[currentPage];
|
||||
|
||||
return (
|
||||
<SourceHovercard
|
||||
source={currentSource}
|
||||
label={getCitationLabel()}
|
||||
onMouseEnter={() => setHoveredCitationId(citationId || null)}
|
||||
onMouseLeave={() => setHoveredCitationId(null)}
|
||||
>
|
||||
{totalPages > 1 && (
|
||||
<span className="mb-2 flex items-center justify-between border-b border-border-heavy pb-2">
|
||||
<span className="flex gap-2">
|
||||
<button
|
||||
onClick={handlePrevPage}
|
||||
disabled={currentPage === 0}
|
||||
style={{ opacity: currentPage === 0 ? 0.5 : 1 }}
|
||||
className="flex cursor-pointer items-center justify-center border-none bg-transparent p-0 text-base"
|
||||
>
|
||||
←
|
||||
</button>
|
||||
<button
|
||||
onClick={handleNextPage}
|
||||
disabled={currentPage === totalPages - 1}
|
||||
style={{ opacity: currentPage === totalPages - 1 ? 0.5 : 1 }}
|
||||
className="flex cursor-pointer items-center justify-center border-none bg-transparent p-0 text-base"
|
||||
>
|
||||
→
|
||||
</button>
|
||||
</span>
|
||||
<span className="text-xs text-text-tertiary">
|
||||
{currentPage + 1}/{totalPages}
|
||||
</span>
|
||||
</span>
|
||||
)}
|
||||
<span className="mb-2 flex items-center">
|
||||
<FaviconImage domain={getCleanDomain(currentSource.link || '')} className="mr-2" />
|
||||
<a
|
||||
href={currentSource.link}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="line-clamp-2 cursor-pointer overflow-hidden text-sm font-bold text-[#0066cc] hover:underline dark:text-blue-400 md:line-clamp-3"
|
||||
>
|
||||
{currentSource.attribution}
|
||||
</a>
|
||||
</span>
|
||||
<h4 className="mb-1.5 mt-0 text-xs text-text-primary md:text-sm">{currentSource.title}</h4>
|
||||
<p className="my-2 text-ellipsis break-all text-xs text-text-secondary md:text-sm">
|
||||
{currentSource.snippet}
|
||||
</p>
|
||||
</SourceHovercard>
|
||||
);
|
||||
}
|
||||
|
||||
interface CitationComponentProps {
|
||||
citationId: string;
|
||||
citationType: 'span' | 'standalone' | 'composite' | 'group' | 'navlist';
|
||||
node?: {
|
||||
properties?: CitationProps;
|
||||
};
|
||||
}
|
||||
|
||||
export function Citation(props: CitationComponentProps) {
|
||||
const localize = useLocalize();
|
||||
const { citation, citationId } = props.node?.properties ?? {};
|
||||
const { setHoveredCitationId } = useContext(CitationContext);
|
||||
const refData = useCitation({
|
||||
turn: citation?.turn || 0,
|
||||
refType: citation?.refType,
|
||||
index: citation?.index || 0,
|
||||
});
|
||||
if (!refData) return null;
|
||||
|
||||
const getCitationLabel = () => {
|
||||
return (
|
||||
refData.attribution ||
|
||||
refData.title ||
|
||||
getCleanDomain(refData.link || '') ||
|
||||
localize('com_citation_source')
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<SourceHovercard
|
||||
source={refData}
|
||||
label={getCitationLabel()}
|
||||
onMouseEnter={() => setHoveredCitationId(citationId || null)}
|
||||
onMouseLeave={() => setHoveredCitationId(null)}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
export interface HighlightedTextProps {
|
||||
children: React.ReactNode;
|
||||
citationId?: string;
|
||||
}
|
||||
|
||||
export function useHighlightState(citationId: string | undefined) {
|
||||
const { hoveredCitationId } = useContext(CitationContext);
|
||||
return citationId && hoveredCitationId === citationId;
|
||||
}
|
||||
|
||||
export const HighlightedText = memo(function HighlightedText({
|
||||
children,
|
||||
citationId,
|
||||
}: HighlightedTextProps) {
|
||||
const isHighlighted = useHighlightState(citationId);
|
||||
|
||||
return (
|
||||
<span
|
||||
className={`rounded px-0 py-0.5 transition-colors ${isHighlighted ? 'bg-amber-300/20' : ''}`}
|
||||
>
|
||||
{children}
|
||||
</span>
|
||||
);
|
||||
});
|
||||
105
client/src/components/Web/Context.tsx
Normal file
105
client/src/components/Web/Context.tsx
Normal file
|
|
@ -0,0 +1,105 @@
|
|||
import { createContext, useContext } from 'react';
|
||||
import type { SearchRefType, ValidSource, ResultReference } from 'librechat-data-provider';
|
||||
import type * as t from './types';
|
||||
import { useSearchContext } from '~/Providers';
|
||||
|
||||
export interface CitationContextType {
|
||||
hoveredCitationId: string | null;
|
||||
setHoveredCitationId: (id: string | null) => void;
|
||||
}
|
||||
|
||||
export const CitationContext = createContext<CitationContextType>({
|
||||
hoveredCitationId: null,
|
||||
setHoveredCitationId: () => {},
|
||||
});
|
||||
|
||||
export function useHighlightState(citationId: string | undefined) {
|
||||
const { hoveredCitationId } = useContext(CitationContext);
|
||||
return citationId && hoveredCitationId === citationId;
|
||||
}
|
||||
|
||||
export type CitationSource = (ValidSource | ResultReference) & {
|
||||
turn: number;
|
||||
refType: string | SearchRefType;
|
||||
index: number;
|
||||
};
|
||||
|
||||
const refTypeMap: Record<string | SearchRefType, string> = {
|
||||
search: 'organic',
|
||||
ref: 'references',
|
||||
news: 'topStories',
|
||||
};
|
||||
|
||||
export function useCitation({
|
||||
turn,
|
||||
index,
|
||||
refType: _refType,
|
||||
}: {
|
||||
turn: number;
|
||||
index: number;
|
||||
refType?: SearchRefType | string;
|
||||
}): (t.Citation & t.Reference) | undefined {
|
||||
const { searchResults } = useSearchContext();
|
||||
if (!_refType) {
|
||||
return undefined;
|
||||
}
|
||||
const refType = refTypeMap[_refType.toLowerCase()]
|
||||
? refTypeMap[_refType.toLowerCase()]
|
||||
: _refType;
|
||||
|
||||
if (!searchResults || !searchResults[turn] || !searchResults[turn][refType]) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const source: CitationSource = searchResults[turn][refType][index];
|
||||
|
||||
if (!source) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
return {
|
||||
...source,
|
||||
turn,
|
||||
refType: _refType.toLowerCase(),
|
||||
index,
|
||||
link: source.link ?? '',
|
||||
title: source.title ?? '',
|
||||
snippet: source['snippet'] ?? '',
|
||||
attribution: source.attribution ?? '',
|
||||
};
|
||||
}
|
||||
|
||||
export function useCompositeCitations(
|
||||
citations: Array<{ turn: number; refType: SearchRefType | string; index: number }>,
|
||||
): Array<t.Citation & t.Reference> {
|
||||
const { searchResults } = useSearchContext();
|
||||
|
||||
const result: Array<t.Citation & t.Reference> = [];
|
||||
|
||||
for (const { turn, refType: _refType, index } of citations) {
|
||||
const refType = refTypeMap[_refType.toLowerCase()]
|
||||
? refTypeMap[_refType.toLowerCase()]
|
||||
: _refType;
|
||||
|
||||
if (!searchResults || !searchResults[turn] || !searchResults[turn][refType]) {
|
||||
continue;
|
||||
}
|
||||
const source: CitationSource = searchResults[turn][refType][index];
|
||||
if (!source) {
|
||||
continue;
|
||||
}
|
||||
|
||||
result.push({
|
||||
...source,
|
||||
turn,
|
||||
refType: _refType.toLowerCase(),
|
||||
index,
|
||||
link: source.link ?? '',
|
||||
title: source.title ?? '',
|
||||
snippet: source['snippet'] ?? '',
|
||||
attribution: source.attribution ?? '',
|
||||
});
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
113
client/src/components/Web/SourceHovercard.tsx
Normal file
113
client/src/components/Web/SourceHovercard.tsx
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
import React, { ReactNode } from 'react';
|
||||
import * as Ariakit from '@ariakit/react';
|
||||
import { ChevronDown } from 'lucide-react';
|
||||
import { VisuallyHidden } from '@ariakit/react';
|
||||
import { useLocalize } from '~/hooks';
|
||||
import { cn } from '~/utils';
|
||||
|
||||
export interface SourceData {
|
||||
link: string;
|
||||
title?: string;
|
||||
attribution?: string;
|
||||
snippet?: string;
|
||||
}
|
||||
|
||||
interface SourceHovercardProps {
|
||||
source: SourceData;
|
||||
label: string;
|
||||
onMouseEnter?: () => void;
|
||||
onMouseLeave?: () => void;
|
||||
children?: ReactNode;
|
||||
}
|
||||
|
||||
/** Helper to get domain favicon */
|
||||
function getFaviconUrl(domain: string) {
|
||||
return `https://www.google.com/s2/favicons?domain=${domain}&sz=32`;
|
||||
}
|
||||
|
||||
/** Helper to get clean domain name */
|
||||
export function getCleanDomain(url: string) {
|
||||
const domain = url.replace(/(^\w+:|^)\/\//, '').split('/')[0];
|
||||
return domain.startsWith('www.') ? domain.substring(4) : domain;
|
||||
}
|
||||
|
||||
export function FaviconImage({ domain, className = '' }: { domain: string; className?: string }) {
|
||||
return (
|
||||
<div className={cn('relative size-4 flex-shrink-0 overflow-hidden rounded-full', className)}>
|
||||
<div className="absolute inset-0 rounded-full bg-white" />
|
||||
<img src={getFaviconUrl(domain)} alt={domain} className="relative size-full" />
|
||||
<div className="border-border-light/10 absolute inset-0 rounded-full border dark:border-transparent"></div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function SourceHovercard({
|
||||
source,
|
||||
label,
|
||||
onMouseEnter,
|
||||
onMouseLeave,
|
||||
children,
|
||||
}: SourceHovercardProps) {
|
||||
const localize = useLocalize();
|
||||
const domain = getCleanDomain(source.link || '');
|
||||
|
||||
return (
|
||||
<span className="relative ml-0.5 inline-block">
|
||||
<Ariakit.HovercardProvider showTimeout={150} hideTimeout={150}>
|
||||
<span className="flex items-center">
|
||||
<Ariakit.HovercardAnchor
|
||||
render={
|
||||
<a
|
||||
href={source.link}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="ml-1 inline-block h-5 max-w-36 cursor-pointer items-center overflow-hidden text-ellipsis whitespace-nowrap rounded-xl border border-border-heavy bg-surface-secondary px-2 text-xs font-medium no-underline transition-colors hover:bg-surface-hover dark:border-border-medium dark:hover:bg-surface-tertiary"
|
||||
onMouseEnter={onMouseEnter}
|
||||
onMouseLeave={onMouseLeave}
|
||||
>
|
||||
{label}
|
||||
</a>
|
||||
}
|
||||
/>
|
||||
<Ariakit.HovercardDisclosure className="ml-0.5 rounded-full text-text-primary focus:outline-none focus:ring-2 focus:ring-ring">
|
||||
<VisuallyHidden>{localize('com_citation_more_details', { label })}</VisuallyHidden>
|
||||
<ChevronDown className="icon-sm" />
|
||||
</Ariakit.HovercardDisclosure>
|
||||
|
||||
<Ariakit.Hovercard
|
||||
gutter={16}
|
||||
className="dark:shadow-lg-dark z-[999] w-[300px] max-w-[calc(100vw-2rem)] rounded-xl border border-border-medium bg-surface-secondary p-3 text-text-primary shadow-lg"
|
||||
portal={true}
|
||||
unmountOnHide={true}
|
||||
>
|
||||
{children}
|
||||
{!children && (
|
||||
<>
|
||||
<span className="mb-2 flex items-center">
|
||||
<FaviconImage domain={domain} className="mr-2" />
|
||||
<a
|
||||
href={source.link}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="line-clamp-2 cursor-pointer overflow-hidden text-sm font-bold text-[#0066cc] hover:underline dark:text-blue-400 md:line-clamp-3"
|
||||
>
|
||||
{source.attribution || domain}
|
||||
</a>
|
||||
</span>
|
||||
|
||||
<h4 className="mb-1.5 mt-0 text-xs text-text-primary md:text-sm">
|
||||
{source.title || source.link}
|
||||
</h4>
|
||||
{source.snippet && (
|
||||
<span className="my-2 text-ellipsis break-all text-xs text-text-secondary md:text-sm">
|
||||
{source.snippet}
|
||||
</span>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</Ariakit.Hovercard>
|
||||
</span>
|
||||
</Ariakit.HovercardProvider>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
409
client/src/components/Web/Sources.tsx
Normal file
409
client/src/components/Web/Sources.tsx
Normal file
|
|
@ -0,0 +1,409 @@
|
|||
import React, { useMemo } from 'react';
|
||||
import * as Ariakit from '@ariakit/react';
|
||||
import { VisuallyHidden } from '@ariakit/react';
|
||||
import { Globe, Newspaper, Image, ChevronDown } from 'lucide-react';
|
||||
import type { ValidSource, ImageResult } from 'librechat-data-provider';
|
||||
import { FaviconImage, getCleanDomain } from '~/components/Web/SourceHovercard';
|
||||
import { useSearchContext } from '~/Providers';
|
||||
import { AnimatedTabs } from '~/components/ui';
|
||||
import { useLocalize } from '~/hooks';
|
||||
import {
|
||||
OGDialog,
|
||||
OGDialogTitle,
|
||||
OGDialogContent,
|
||||
OGDialogTrigger,
|
||||
} from '~/components/ui/OriginalDialog';
|
||||
|
||||
interface SourceItemProps {
|
||||
source: ValidSource;
|
||||
isNews?: boolean;
|
||||
expanded?: boolean;
|
||||
}
|
||||
|
||||
function SourceItem({ source, isNews, expanded = false }: SourceItemProps) {
|
||||
const localize = useLocalize();
|
||||
const domain = getCleanDomain(source.link);
|
||||
|
||||
if (expanded) {
|
||||
return (
|
||||
<a
|
||||
href={source.link}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex w-full flex-col rounded-lg bg-surface-primary-contrast px-3 py-2 text-sm transition-all duration-300 hover:bg-surface-tertiary"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<FaviconImage domain={domain} />
|
||||
<span className="truncate text-xs font-medium text-text-secondary">{domain}</span>
|
||||
</div>
|
||||
<div className="mt-1">
|
||||
<span className="line-clamp-2 text-sm font-medium text-text-primary md:line-clamp-3">
|
||||
{source.title || source.link}
|
||||
</span>
|
||||
{'snippet' in source && source.snippet && (
|
||||
<span className="mt-1 line-clamp-2 text-xs text-text-secondary md:line-clamp-3">
|
||||
{source.snippet}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="not-prose relative inline-block h-full w-full">
|
||||
<Ariakit.HovercardProvider showTimeout={150} hideTimeout={150}>
|
||||
<div className="flex h-full items-center">
|
||||
<Ariakit.HovercardAnchor
|
||||
render={
|
||||
<a
|
||||
href={source.link}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex h-full w-full flex-col rounded-lg bg-surface-primary-contrast px-3 py-2 text-sm transition-all duration-300 hover:bg-surface-tertiary"
|
||||
>
|
||||
<div className="flex items-center gap-2">
|
||||
<FaviconImage domain={domain} />
|
||||
<span className="truncate text-xs font-medium text-text-secondary">{domain}</span>
|
||||
</div>
|
||||
<div className="mt-1">
|
||||
<span className="line-clamp-2 text-sm font-medium text-text-primary md:line-clamp-3">
|
||||
{source.title || source.link}
|
||||
</span>
|
||||
{/* {'snippet' in source && source.snippet && (
|
||||
<span className="mt-1 line-clamp-2 md:line-clamp-3 text-xs text-text-secondary">
|
||||
{source.snippet}
|
||||
</span>
|
||||
)} */}
|
||||
</div>
|
||||
</a>
|
||||
}
|
||||
/>
|
||||
<Ariakit.HovercardDisclosure className="absolute right-2 rounded-full text-text-primary focus:outline-none focus:ring-2 focus:ring-ring">
|
||||
<VisuallyHidden>
|
||||
{localize('com_citation_more_details', { label: domain })}
|
||||
</VisuallyHidden>
|
||||
<ChevronDown className="icon-sm" />
|
||||
</Ariakit.HovercardDisclosure>
|
||||
|
||||
<Ariakit.Hovercard
|
||||
gutter={16}
|
||||
className="dark:shadow-lg-dark z-[999] w-[300px] max-w-[calc(100vw-2rem)] rounded-xl border border-border-medium bg-surface-secondary p-3 text-text-primary shadow-lg"
|
||||
portal={true}
|
||||
unmountOnHide={true}
|
||||
>
|
||||
<div className="flex gap-3">
|
||||
<div className="flex-1">
|
||||
<div className="mb-2 flex items-center">
|
||||
<FaviconImage domain={domain} className="mr-2" />
|
||||
<a
|
||||
href={source.link}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="line-clamp-2 cursor-pointer overflow-hidden text-sm font-bold text-[#0066cc] hover:underline dark:text-blue-400 md:line-clamp-3"
|
||||
>
|
||||
{source.attribution || domain}
|
||||
</a>
|
||||
</div>
|
||||
<h4 className="mb-1.5 mt-0 text-xs text-text-primary md:text-sm">
|
||||
{source.title || source.link}
|
||||
</h4>
|
||||
{'snippet' in source && source.snippet && (
|
||||
<span className="my-2 text-ellipsis break-all text-xs text-text-secondary md:text-sm">
|
||||
{source.snippet}
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
{'imageUrl' in source && source.imageUrl && (
|
||||
<div className="h-24 w-24 flex-shrink-0 overflow-hidden rounded-md">
|
||||
<img
|
||||
src={source.imageUrl}
|
||||
alt={source.title || localize('com_sources_image_alt')}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</Ariakit.Hovercard>
|
||||
</div>
|
||||
</Ariakit.HovercardProvider>
|
||||
</span>
|
||||
);
|
||||
}
|
||||
|
||||
function ImageItem({ image }: { image: ImageResult }) {
|
||||
const localize = useLocalize();
|
||||
return (
|
||||
<a
|
||||
href={image.imageUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="group overflow-hidden rounded-lg bg-surface-secondary transition-all duration-300 hover:bg-surface-tertiary"
|
||||
>
|
||||
{image.imageUrl && (
|
||||
<div className="relative aspect-square w-full overflow-hidden">
|
||||
<img
|
||||
src={image.imageUrl}
|
||||
alt={image.title || localize('com_sources_image_alt')}
|
||||
className="size-full object-cover"
|
||||
/>
|
||||
{image.title && (
|
||||
<div className="absolute bottom-0 left-0 right-0 w-full border-none bg-gray-900/80 p-1 text-xs font-medium text-white backdrop-blur-sm">
|
||||
<span className="truncate">{image.title}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</a>
|
||||
);
|
||||
}
|
||||
|
||||
export function StackedFavicons({
|
||||
sources,
|
||||
start = 0,
|
||||
end = 3,
|
||||
}: {
|
||||
sources: ValidSource[];
|
||||
start?: number;
|
||||
end?: number;
|
||||
}) {
|
||||
let slice = [start, end];
|
||||
if (start < 0) {
|
||||
slice = [start];
|
||||
}
|
||||
return (
|
||||
<div className="relative flex">
|
||||
{sources.slice(...slice).map((source, i) => (
|
||||
<FaviconImage
|
||||
key={`icon-${i}`}
|
||||
domain={getCleanDomain(source.link)}
|
||||
className={i > 0 ? 'ml-[-6px]' : ''}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SourcesGroup({ sources, limit = 3 }: { sources: ValidSource[]; limit?: number }) {
|
||||
const localize = useLocalize();
|
||||
const visibleSources = sources.slice(0, limit);
|
||||
const remainingSources = sources.slice(limit);
|
||||
const hasMoreSources = remainingSources.length > 0;
|
||||
|
||||
/** Calculate grid columns based on number of items (including the +X sources button if present) */
|
||||
const totalItems = hasMoreSources ? visibleSources.length + 1 : visibleSources.length;
|
||||
const gridCols = `grid-cols-${Math.min(totalItems, 4)}`;
|
||||
|
||||
return (
|
||||
<div className={`grid ${gridCols} scrollbar-none w-full gap-2 overflow-x-auto`}>
|
||||
<OGDialog>
|
||||
{visibleSources.map((source, i) => (
|
||||
<div key={`source-${i}`} className="w-full min-w-[120px]">
|
||||
<SourceItem source={source} />
|
||||
</div>
|
||||
))}
|
||||
{hasMoreSources && (
|
||||
<OGDialogTrigger className="flex flex-col rounded-lg bg-surface-primary-contrast px-3 py-2 text-sm transition-all duration-300 hover:bg-surface-tertiary">
|
||||
<div className="flex items-center gap-2">
|
||||
<StackedFavicons sources={remainingSources} />
|
||||
<span className="truncate text-xs font-medium text-text-secondary">
|
||||
{localize('com_sources_more_sources', { count: remainingSources.length })}
|
||||
</span>
|
||||
</div>
|
||||
</OGDialogTrigger>
|
||||
)}
|
||||
<OGDialogContent className="flex max-h-[80vh] max-w-full flex-col overflow-hidden rounded-lg bg-surface-primary p-0 md:max-w-[600px]">
|
||||
<div className="sticky top-0 z-10 flex items-center justify-between border-b border-border-light bg-surface-primary px-3 py-2">
|
||||
<OGDialogTitle className="text-base font-medium">
|
||||
{localize('com_sources_title')}
|
||||
</OGDialogTitle>
|
||||
<button
|
||||
className="rounded-full p-1 text-text-secondary hover:bg-surface-tertiary hover:text-text-primary"
|
||||
aria-label={localize('com_ui_close')}
|
||||
>
|
||||
<svg
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
width="20"
|
||||
height="20"
|
||||
viewBox="0 0 24 24"
|
||||
fill="none"
|
||||
stroke="currentColor"
|
||||
strokeWidth="2"
|
||||
strokeLinecap="round"
|
||||
strokeLinejoin="round"
|
||||
>
|
||||
<line x1="18" y1="6" x2="6" y2="18"></line>
|
||||
<line x1="6" y1="6" x2="18" y2="18"></line>
|
||||
</svg>
|
||||
</button>
|
||||
</div>
|
||||
<div className="flex-1 overflow-y-auto px-3 py-2">
|
||||
<div className="flex flex-col gap-2">
|
||||
{[...visibleSources, ...remainingSources].map((source, i) => (
|
||||
<a
|
||||
key={`more-source-${i}`}
|
||||
href={source.link}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="flex gap-2 rounded-lg px-2 py-2 transition-colors hover:bg-surface-tertiary"
|
||||
>
|
||||
<FaviconImage
|
||||
domain={getCleanDomain(source.link)}
|
||||
className="h-5 w-5 flex-shrink-0"
|
||||
/>
|
||||
<div className="min-w-0 flex-1">
|
||||
<h3 className="mb-0.5 truncate text-sm font-medium text-text-primary">
|
||||
{source.title || source.link}
|
||||
</h3>
|
||||
{'snippet' in source && source.snippet && (
|
||||
<p className="mb-1 line-clamp-2 text-xs text-text-secondary md:line-clamp-3">
|
||||
{source.snippet}
|
||||
</p>
|
||||
)}
|
||||
<span className="text-xs text-text-secondary-alt">
|
||||
{getCleanDomain(source.link)}
|
||||
</span>
|
||||
</div>
|
||||
{'imageUrl' in source && source.imageUrl && (
|
||||
<div className="hidden h-12 w-12 flex-shrink-0 overflow-hidden rounded-md sm:block">
|
||||
<img
|
||||
src={source.imageUrl}
|
||||
alt={source.title || localize('com_sources_image_alt')}
|
||||
className="h-full w-full object-cover"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</a>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</OGDialogContent>
|
||||
</OGDialog>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function TabWithIcon({ label, icon }: { label: string; icon: React.ReactNode }) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 rounded-md px-3 py-1 text-sm transition-colors hover:bg-surface-tertiary hover:text-text-primary">
|
||||
{React.cloneElement(icon as React.ReactElement, { size: 14 })}
|
||||
<span>{label}</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default function Sources() {
|
||||
const localize = useLocalize();
|
||||
const { searchResults } = useSearchContext();
|
||||
|
||||
const { organicSources, topStories, images, hasAnswerBox } = useMemo(() => {
|
||||
if (!searchResults) {
|
||||
return {
|
||||
organicSources: [],
|
||||
topStories: [],
|
||||
images: [],
|
||||
hasAnswerBox: false,
|
||||
};
|
||||
}
|
||||
|
||||
const organicSourcesMap = new Map<string, ValidSource>();
|
||||
const topStoriesMap = new Map<string, ValidSource>();
|
||||
const imagesMap = new Map<string, ImageResult>();
|
||||
let hasAnswerBox = false;
|
||||
|
||||
Object.values(searchResults).forEach((result) => {
|
||||
if (!result) return;
|
||||
|
||||
if (result.organic?.length) {
|
||||
result.organic.forEach((source) => {
|
||||
if (source.link) {
|
||||
organicSourcesMap.set(source.link, source);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (result.references?.length) {
|
||||
result.references.forEach((source) => {
|
||||
if (source.type === 'image') {
|
||||
imagesMap.set(source.link, {
|
||||
...source,
|
||||
imageUrl: source.link,
|
||||
});
|
||||
return;
|
||||
}
|
||||
if (source.link) {
|
||||
organicSourcesMap.set(source.link, source);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (result.topStories?.length) {
|
||||
result.topStories.forEach((source) => {
|
||||
if (source.link) {
|
||||
topStoriesMap.set(source.link, source);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (result.images?.length) {
|
||||
result.images.forEach((image) => {
|
||||
if (image.imageUrl) {
|
||||
imagesMap.set(image.imageUrl, image);
|
||||
}
|
||||
});
|
||||
}
|
||||
if (result.answerBox) {
|
||||
hasAnswerBox = true;
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
organicSources: Array.from(organicSourcesMap.values()),
|
||||
topStories: Array.from(topStoriesMap.values()),
|
||||
images: Array.from(imagesMap.values()),
|
||||
hasAnswerBox,
|
||||
};
|
||||
}, [searchResults]);
|
||||
|
||||
const tabs = useMemo(() => {
|
||||
const availableTabs: Array<{ label: React.ReactNode; content: React.ReactNode }> = [];
|
||||
|
||||
if (organicSources.length || topStories.length || hasAnswerBox) {
|
||||
availableTabs.push({
|
||||
label: <TabWithIcon label={localize('com_sources_tab_all')} icon={<Globe />} />,
|
||||
content: <SourcesGroup sources={[...organicSources, ...topStories]} />,
|
||||
});
|
||||
}
|
||||
|
||||
if (topStories.length) {
|
||||
availableTabs.push({
|
||||
label: <TabWithIcon label={localize('com_sources_tab_news')} icon={<Newspaper />} />,
|
||||
content: <SourcesGroup sources={topStories} limit={3} />,
|
||||
});
|
||||
}
|
||||
|
||||
if (images.length) {
|
||||
availableTabs.push({
|
||||
label: <TabWithIcon label={localize('com_sources_tab_images')} icon={<Image />} />,
|
||||
content: (
|
||||
<div className="grid grid-cols-2 gap-2 sm:grid-cols-3 md:grid-cols-4 lg:grid-cols-5">
|
||||
{images.map((item, i) => (
|
||||
<ImageItem key={`image-${i}`} image={item} />
|
||||
))}
|
||||
</div>
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
return availableTabs;
|
||||
}, [organicSources, topStories, images, hasAnswerBox, localize]);
|
||||
|
||||
if (!tabs.length) return null;
|
||||
|
||||
return (
|
||||
<AnimatedTabs
|
||||
tabs={tabs}
|
||||
containerClassName="flex min-w-full mb-4"
|
||||
tabListClassName="flex items-center mb-2 border-b border-border-light overflow-x-auto"
|
||||
tabPanelClassName="w-full overflow-x-auto scrollbar-none md:mx-0 md:px-0"
|
||||
tabClassName="flex items-center whitespace-nowrap text-xs font-medium text-token-text-secondary px-1 pt-2 pb-1 border-b-2 border-transparent data-[state=active]:text-text-primary outline-none"
|
||||
/>
|
||||
);
|
||||
}
|
||||
2
client/src/components/Web/index.ts
Normal file
2
client/src/components/Web/index.ts
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
export * from './plugin';
|
||||
export type * from './types';
|
||||
250
client/src/components/Web/plugin.ts
Normal file
250
client/src/components/Web/plugin.ts
Normal file
|
|
@ -0,0 +1,250 @@
|
|||
import { visit } from 'unist-util-visit';
|
||||
import type { Node } from 'unist';
|
||||
import type { Citation, CitationNode } from './types';
|
||||
|
||||
const SPAN_REGEX = /(\\ue203.*?\\ue204)/g;
|
||||
const COMPOSITE_REGEX = /(\\ue200.*?\\ue201)/g;
|
||||
const STANDALONE_PATTERN = /\\ue202turn(\d+)(search|image|news|video|ref)(\d+)/g;
|
||||
const CLEANUP_REGEX = /\\ue200|\\ue201|\\ue202|\\ue203|\\ue204|\\ue206/g;
|
||||
|
||||
/**
|
||||
* Checks if a standalone marker is truly standalone (not inside a composite block)
|
||||
*/
|
||||
function isStandaloneMarker(text: string, position: number): boolean {
|
||||
const beforeText = text.substring(0, position);
|
||||
const lastUe200 = beforeText.lastIndexOf('\\ue200');
|
||||
const lastUe201 = beforeText.lastIndexOf('\\ue201');
|
||||
|
||||
return lastUe200 === -1 || (lastUe201 !== -1 && lastUe201 > lastUe200);
|
||||
}
|
||||
|
||||
/**
|
||||
* Find the next pattern match from the current position
|
||||
*/
|
||||
function findNextMatch(
|
||||
text: string,
|
||||
position: number,
|
||||
): { type: string; match: RegExpExecArray | null; index: number } | null {
|
||||
// Reset regex lastIndex to start from current position
|
||||
SPAN_REGEX.lastIndex = position;
|
||||
COMPOSITE_REGEX.lastIndex = position;
|
||||
STANDALONE_PATTERN.lastIndex = position;
|
||||
|
||||
// Find next occurrence of each pattern
|
||||
const spanMatch = SPAN_REGEX.exec(text);
|
||||
const compositeMatch = COMPOSITE_REGEX.exec(text);
|
||||
|
||||
// For standalone, we need to check each match
|
||||
let standaloneMatch: RegExpExecArray | null = null;
|
||||
STANDALONE_PATTERN.lastIndex = position;
|
||||
|
||||
// Find the first standalone match that's not inside a composite block
|
||||
let match: RegExpExecArray | null;
|
||||
while (!standaloneMatch && (match = STANDALONE_PATTERN.exec(text)) !== null) {
|
||||
if (isStandaloneMarker(text, match.index)) {
|
||||
standaloneMatch = match;
|
||||
}
|
||||
}
|
||||
|
||||
// Find closest match
|
||||
let nextMatch: RegExpExecArray | null = null;
|
||||
let matchType = '';
|
||||
let matchIndex = -1;
|
||||
let typeIndex = -1;
|
||||
|
||||
if (spanMatch && (!nextMatch || spanMatch.index < matchIndex || matchIndex === -1)) {
|
||||
nextMatch = spanMatch;
|
||||
matchType = 'span';
|
||||
matchIndex = spanMatch.index;
|
||||
// We can use a counter for typeIndex if needed
|
||||
typeIndex = 0;
|
||||
}
|
||||
|
||||
if (compositeMatch && (!nextMatch || compositeMatch.index < matchIndex || matchIndex === -1)) {
|
||||
nextMatch = compositeMatch;
|
||||
matchType = 'composite';
|
||||
matchIndex = compositeMatch.index;
|
||||
typeIndex = 0;
|
||||
}
|
||||
|
||||
if (standaloneMatch && (!nextMatch || standaloneMatch.index < matchIndex || matchIndex === -1)) {
|
||||
nextMatch = standaloneMatch;
|
||||
matchType = 'standalone';
|
||||
matchIndex = standaloneMatch.index;
|
||||
typeIndex = 0;
|
||||
}
|
||||
|
||||
if (!nextMatch) return null;
|
||||
|
||||
return { type: matchType, match: nextMatch, index: typeIndex };
|
||||
}
|
||||
|
||||
function processTree(tree: Node) {
|
||||
visit(tree, 'text', (node, index, parent) => {
|
||||
const textNode = node as CitationNode;
|
||||
const parentNode = parent as CitationNode;
|
||||
|
||||
if (typeof textNode.value !== 'string') return;
|
||||
|
||||
const originalValue = textNode.value;
|
||||
const segments: Array<CitationNode> = [];
|
||||
|
||||
// Single-pass processing through the string
|
||||
let currentPosition = 0;
|
||||
|
||||
// Important change: Create a map to track citation IDs by their position
|
||||
// This ensures consistent IDs across multiple segments
|
||||
const citationIds = new Map<number, string>();
|
||||
const typeCounts = { span: 0, composite: 0, standalone: 0 };
|
||||
|
||||
while (currentPosition < originalValue.length) {
|
||||
const nextMatchInfo = findNextMatch(originalValue, currentPosition);
|
||||
|
||||
if (!nextMatchInfo) {
|
||||
// No more matches, add remaining content with cleanup
|
||||
const remainingText = originalValue.substring(currentPosition).replace(CLEANUP_REGEX, '');
|
||||
if (remainingText) {
|
||||
segments.push({ type: 'text', value: remainingText });
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
const { type, match } = nextMatchInfo;
|
||||
const matchIndex = match!.index;
|
||||
const matchText = match![0];
|
||||
|
||||
// Add cleaned text before this match
|
||||
if (matchIndex > currentPosition) {
|
||||
const textBeforeMatch = originalValue
|
||||
.substring(currentPosition, matchIndex)
|
||||
.replace(CLEANUP_REGEX, '');
|
||||
|
||||
if (textBeforeMatch) {
|
||||
segments.push({ type: 'text', value: textBeforeMatch });
|
||||
}
|
||||
}
|
||||
|
||||
// Generate a unique ID for this citation based on its position in the text
|
||||
const citationId = `${type}-${typeCounts[type as keyof typeof typeCounts]}-${matchIndex}`;
|
||||
citationIds.set(matchIndex, citationId);
|
||||
|
||||
// Process based on match type
|
||||
switch (type) {
|
||||
case 'span': {
|
||||
const spanText = matchText;
|
||||
const cleanText = spanText.replace(/\\ue203|\\ue204/g, '');
|
||||
|
||||
// Look ahead for associated citation
|
||||
let associatedCitationId: string | null = null;
|
||||
const endOfSpan = matchIndex + matchText.length;
|
||||
|
||||
// Check if there's a citation right after this span
|
||||
const nextCitation = findNextMatch(originalValue, endOfSpan);
|
||||
if (
|
||||
nextCitation &&
|
||||
(nextCitation.type === 'standalone' || nextCitation.type === 'composite') &&
|
||||
nextCitation.match!.index - endOfSpan < 5
|
||||
) {
|
||||
// Use the ID that will be generated for the next citation
|
||||
const nextIndex = nextCitation.match!.index;
|
||||
const nextType = nextCitation.type;
|
||||
associatedCitationId = `${nextType}-${typeCounts[nextType as keyof typeof typeCounts]}-${nextIndex}`;
|
||||
}
|
||||
|
||||
segments.push({
|
||||
type: 'highlighted-text',
|
||||
data: {
|
||||
hName: 'highlighted-text',
|
||||
hProperties: { citationId: associatedCitationId },
|
||||
},
|
||||
children: [{ type: 'text', value: cleanText }],
|
||||
});
|
||||
|
||||
typeCounts.span++;
|
||||
break;
|
||||
}
|
||||
|
||||
case 'composite': {
|
||||
const compositeText = matchText;
|
||||
|
||||
// Use a regular expression to extract reference indices
|
||||
const compositeRefRegex = new RegExp(STANDALONE_PATTERN.source, 'g');
|
||||
let refMatch: RegExpExecArray | null;
|
||||
const citations: Array<Citation> = [];
|
||||
|
||||
while ((refMatch = compositeRefRegex.exec(compositeText)) !== null) {
|
||||
const turn = Number(refMatch[1]);
|
||||
const refType = refMatch[2];
|
||||
const refIndex = Number(refMatch[3]);
|
||||
|
||||
citations.push({
|
||||
turn,
|
||||
refType,
|
||||
index: refIndex,
|
||||
});
|
||||
}
|
||||
|
||||
if (citations.length > 0) {
|
||||
segments.push({
|
||||
type: 'composite-citation',
|
||||
data: {
|
||||
hName: 'composite-citation',
|
||||
hProperties: {
|
||||
citations,
|
||||
citationId: citationId,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
typeCounts.composite++;
|
||||
break;
|
||||
}
|
||||
|
||||
case 'standalone': {
|
||||
// Extract reference info
|
||||
const turn = Number(match![1]);
|
||||
const refType = match![2];
|
||||
const refIndex = Number(match![3]);
|
||||
|
||||
segments.push({
|
||||
type: 'citation',
|
||||
data: {
|
||||
hName: 'citation',
|
||||
hProperties: {
|
||||
citation: {
|
||||
turn,
|
||||
refType,
|
||||
index: refIndex,
|
||||
},
|
||||
citationType: 'standalone',
|
||||
citationId: citationId,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
typeCounts.standalone++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Move position forward
|
||||
currentPosition = matchIndex + matchText.length;
|
||||
}
|
||||
|
||||
// Replace the original node with our segments or clean up the original
|
||||
if (segments.length > 0 && index !== undefined) {
|
||||
parentNode.children?.splice(index, 1, ...segments);
|
||||
return index + segments.length;
|
||||
} else if (textNode.value !== textNode.value.replace(CLEANUP_REGEX, '')) {
|
||||
// If we didn't create segments but there are markers to clean up
|
||||
textNode.value = textNode.value.replace(CLEANUP_REGEX, '');
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function unicodeCitation() {
|
||||
return (tree: Node) => {
|
||||
processTree(tree);
|
||||
};
|
||||
}
|
||||
32
client/src/components/Web/types.ts
Normal file
32
client/src/components/Web/types.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
import type { SearchRefType } from 'librechat-data-provider';
|
||||
export type Citation = { turn: number; refType: SearchRefType | string; index: number };
|
||||
|
||||
export type CitationProps = {
|
||||
citationId?: string | null;
|
||||
citationType?: string;
|
||||
citations?: Array<Citation>;
|
||||
citation?: Citation;
|
||||
};
|
||||
|
||||
export type CitationNode = {
|
||||
type?: string;
|
||||
value?: string;
|
||||
data?: {
|
||||
hName?: string;
|
||||
hProperties?: CitationProps;
|
||||
};
|
||||
children?: Array<CitationNode>;
|
||||
};
|
||||
|
||||
export interface Sitelink {
|
||||
title: string;
|
||||
link: string;
|
||||
}
|
||||
|
||||
export interface Reference {
|
||||
title: string;
|
||||
link: string;
|
||||
snippet: string;
|
||||
sitelinks?: Sitelink[];
|
||||
attribution: string;
|
||||
}
|
||||
57
client/src/components/ui/AnimatedTabs.css
Normal file
57
client/src/components/ui/AnimatedTabs.css
Normal file
|
|
@ -0,0 +1,57 @@
|
|||
/* AnimatedTabs.css */
|
||||
.animated-tab-panel {
|
||||
transition-property: opacity, translate;
|
||||
transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1);
|
||||
transition-duration: 300ms;
|
||||
animation-duration: 300ms;
|
||||
}
|
||||
|
||||
/* Sliding underline animation for tabs */
|
||||
.animated-tab-list {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.animated-tab-list::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
height: 2px;
|
||||
background-color: currentColor; /* Inherit color from active tab */
|
||||
transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
|
||||
left: var(--tab-left, 0);
|
||||
width: var(--tab-width, 0);
|
||||
}
|
||||
|
||||
.animated-tab {
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.animated-tab[data-state="active"] {
|
||||
border-bottom-color: transparent !important;
|
||||
}
|
||||
|
||||
.animated-tab-panel[data-enter] {
|
||||
opacity: 1 !important;
|
||||
translate: 0 !important;
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.animated-tab-panel {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
|
||||
.animated-tab-panel:not([data-open]) {
|
||||
position: absolute;
|
||||
top: 0px;
|
||||
}
|
||||
|
||||
.animated-panels:has(> [data-was-open]) > .animated-tab-panel {
|
||||
opacity: 0;
|
||||
translate: -100%;
|
||||
}
|
||||
|
||||
.animated-panels [data-was-open] ~ .animated-tab-panel,
|
||||
.animated-panels [data-open] ~ .animated-tab-panel {
|
||||
translate: 100%;
|
||||
}
|
||||
160
client/src/components/ui/AnimatedTabs.tsx
Normal file
160
client/src/components/ui/AnimatedTabs.tsx
Normal file
|
|
@ -0,0 +1,160 @@
|
|||
import * as Ariakit from '@ariakit/react';
|
||||
import { ReactNode, forwardRef, useEffect, useRef } from 'react';
|
||||
import type { ElementRef } from 'react';
|
||||
import { cn } from '~/utils';
|
||||
import './AnimatedTabs.css';
|
||||
|
||||
export interface TabItem {
|
||||
id?: string;
|
||||
label: ReactNode;
|
||||
content: ReactNode;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
export interface AnimatedTabsProps {
|
||||
tabs: TabItem[];
|
||||
className?: string;
|
||||
tabListClassName?: string;
|
||||
tabClassName?: string;
|
||||
tabPanelClassName?: string;
|
||||
tabListProps?: Ariakit.TabListProps;
|
||||
containerClassName?: string;
|
||||
defaultSelectedId?: string;
|
||||
}
|
||||
|
||||
function usePrevious<T>(value: T) {
|
||||
const ref = useRef<T>();
|
||||
useEffect(() => {
|
||||
ref.current = value;
|
||||
}, [value]);
|
||||
return ref.current;
|
||||
}
|
||||
|
||||
const Tab = forwardRef<ElementRef<typeof Ariakit.Tab>, Ariakit.TabProps>(function Tab(props, ref) {
|
||||
const tabRef = useRef<HTMLButtonElement | null>(null);
|
||||
useEffect(() => {
|
||||
const tabElement = tabRef.current;
|
||||
if (!tabElement) return;
|
||||
|
||||
const updateState = () => {
|
||||
const isSelected = tabElement.getAttribute('aria-selected') === 'true';
|
||||
tabElement.setAttribute('data-state', isSelected ? 'active' : 'inactive');
|
||||
};
|
||||
|
||||
updateState();
|
||||
|
||||
const observer = new MutationObserver(updateState);
|
||||
observer.observe(tabElement, { attributes: true, attributeFilter: ['aria-selected'] });
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, []);
|
||||
|
||||
return (
|
||||
<Ariakit.Tab
|
||||
ref={(node) => {
|
||||
// Forward the ref to both our local ref and the provided ref
|
||||
tabRef.current = node;
|
||||
if (typeof ref === 'function') ref(node);
|
||||
else if (ref) ref.current = node;
|
||||
}}
|
||||
{...props}
|
||||
className={`animated-tab aria-selected:text-token-text-primary flex select-none items-center justify-center gap-2 whitespace-nowrap border-none text-sm font-medium outline-none transition-colors aria-disabled:opacity-50 ${props.className || ''}`}
|
||||
/>
|
||||
);
|
||||
});
|
||||
|
||||
const TabPanel = forwardRef<ElementRef<typeof Ariakit.TabPanel>, Ariakit.TabPanelProps>(
|
||||
function TabPanel(props, ref) {
|
||||
const tab = Ariakit.useTabContext();
|
||||
const previousTabId = usePrevious(Ariakit.useStoreState(tab, 'selectedId'));
|
||||
const wasOpen = props.tabId && previousTabId === props.tabId;
|
||||
|
||||
return (
|
||||
<Ariakit.TabPanel
|
||||
ref={ref}
|
||||
{...props}
|
||||
data-was-open={wasOpen || undefined}
|
||||
className={`animated-tab-panel max-w-full ${props.className || ''}`}
|
||||
/>
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
export function AnimatedTabs({
|
||||
tabs,
|
||||
className = '',
|
||||
tabListClassName = '',
|
||||
tabClassName = '',
|
||||
tabPanelClassName = '',
|
||||
containerClassName = '',
|
||||
tabListProps = {},
|
||||
defaultSelectedId,
|
||||
}: AnimatedTabsProps) {
|
||||
const tabIds = tabs.map((tab, index) => tab.id || `tab-${index}`);
|
||||
const firstTabId = defaultSelectedId || tabIds[0];
|
||||
const tabListRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const tabList = tabListRef.current;
|
||||
if (!tabList) return;
|
||||
|
||||
// Function to update the underline position
|
||||
const updateUnderline = () => {
|
||||
const activeTab = tabList.querySelector('[data-state="active"]') as HTMLElement;
|
||||
if (!activeTab) return;
|
||||
|
||||
tabList.style.setProperty('--tab-left', `${activeTab.offsetLeft}px`);
|
||||
tabList.style.setProperty('--tab-width', `${activeTab.offsetWidth}px`);
|
||||
};
|
||||
|
||||
updateUnderline();
|
||||
|
||||
const observer = new MutationObserver(updateUnderline);
|
||||
observer.observe(tabList, { attributes: true, subtree: true, attributeFilter: ['data-state'] });
|
||||
|
||||
return () => observer.disconnect();
|
||||
}, [tabs]);
|
||||
|
||||
return (
|
||||
<div className={`w-full ${className}`}>
|
||||
<Ariakit.TabProvider defaultSelectedId={firstTabId}>
|
||||
<Ariakit.TabList
|
||||
ref={tabListRef}
|
||||
aria-label="Tabs"
|
||||
className={`animated-tab-list flex py-1 ${tabListClassName}`}
|
||||
{...tabListProps}
|
||||
>
|
||||
{tabs.map((tab, index) => (
|
||||
<Tab
|
||||
key={tabIds[index]}
|
||||
id={tabIds[index]}
|
||||
disabled={tab.disabled}
|
||||
className={tabClassName}
|
||||
data-state={tabIds[index] === firstTabId ? 'active' : 'inactive'}
|
||||
>
|
||||
{tab.label}
|
||||
</Tab>
|
||||
))}
|
||||
</Ariakit.TabList>
|
||||
|
||||
<div
|
||||
className={cn(
|
||||
'animated-panels relative flex w-full flex-col items-center overflow-hidden p-0',
|
||||
containerClassName,
|
||||
)}
|
||||
>
|
||||
{tabs.map((tab, index) => (
|
||||
<TabPanel
|
||||
key={`panel-${tabIds[index]}`}
|
||||
id={`panel-${tabIds[index]}`}
|
||||
tabId={tabIds[index]}
|
||||
className={tabPanelClassName}
|
||||
>
|
||||
{tab.content}
|
||||
</TabPanel>
|
||||
))}
|
||||
</div>
|
||||
</Ariakit.TabProvider>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -1,22 +1,19 @@
|
|||
import { useEffect } from 'react';
|
||||
import { Checkbox, useStoreState, useCheckboxStore } from '@ariakit/react';
|
||||
import { cn } from '~/utils';
|
||||
import * as React from 'react';
|
||||
|
||||
export default function CheckboxButton({
|
||||
label,
|
||||
icon,
|
||||
setValue,
|
||||
className,
|
||||
defaultChecked,
|
||||
isCheckedClassName,
|
||||
}: {
|
||||
label: string;
|
||||
className?: string;
|
||||
icon?: React.ReactNode;
|
||||
defaultChecked?: boolean;
|
||||
isCheckedClassName?: string;
|
||||
setValue?: (isChecked: boolean) => void;
|
||||
}) {
|
||||
const CheckboxButton = React.forwardRef<
|
||||
HTMLInputElement,
|
||||
{
|
||||
icon?: React.ReactNode;
|
||||
label: string;
|
||||
className?: string;
|
||||
defaultChecked?: boolean;
|
||||
isCheckedClassName?: string;
|
||||
setValue?: (e: React.ChangeEvent<HTMLInputElement>, isChecked: boolean) => void;
|
||||
}
|
||||
>(({ icon, label, setValue, className, defaultChecked, isCheckedClassName }, ref) => {
|
||||
const checkbox = useCheckboxStore();
|
||||
const isChecked = useStoreState(checkbox, (state) => state?.value);
|
||||
const onChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
|
|
@ -24,7 +21,7 @@ export default function CheckboxButton({
|
|||
if (typeof isChecked !== 'boolean') {
|
||||
return;
|
||||
}
|
||||
setValue?.(!isChecked);
|
||||
setValue?.(e, !isChecked);
|
||||
};
|
||||
useEffect(() => {
|
||||
if (defaultChecked) {
|
||||
|
|
@ -34,6 +31,7 @@ export default function CheckboxButton({
|
|||
|
||||
return (
|
||||
<Checkbox
|
||||
ref={ref}
|
||||
store={checkbox}
|
||||
onChange={onChange}
|
||||
defaultChecked={defaultChecked}
|
||||
|
|
@ -59,4 +57,8 @@ export default function CheckboxButton({
|
|||
<span className="hidden truncate md:block">{label}</span>
|
||||
</Checkbox>
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
CheckboxButton.displayName = 'CheckboxButton';
|
||||
|
||||
export default CheckboxButton;
|
||||
|
|
|
|||
|
|
@ -4,7 +4,7 @@ import { X } from 'lucide-react';
|
|||
import { cn } from '~/utils';
|
||||
|
||||
interface OGDialogProps extends DialogPrimitive.DialogProps {
|
||||
triggerRef?: React.RefObject<HTMLButtonElement>;
|
||||
triggerRef?: React.RefObject<HTMLButtonElement | HTMLInputElement>;
|
||||
}
|
||||
|
||||
const Dialog = React.forwardRef<HTMLDivElement, OGDialogProps>(
|
||||
|
|
|
|||
|
|
@ -1,3 +1,4 @@
|
|||
export * from './AnimatedTabs';
|
||||
export * from './AlertDialog';
|
||||
export * from './Breadcrumb';
|
||||
export * from './Button';
|
||||
|
|
|
|||
|
|
@ -245,7 +245,7 @@ export default function useChatFunctions({
|
|||
const generation = editedText ?? latestMessage?.text ?? '';
|
||||
const responseText = isEditOrContinue ? generation : '';
|
||||
|
||||
const responseMessageId = editedMessageId ?? latestMessage?.messageId ?? null;
|
||||
const responseMessageId = editedMessageId ?? latestMessage?.messageId + '_' ?? null;
|
||||
const initialResponse: TMessage = {
|
||||
sender: responseSender,
|
||||
text: responseText,
|
||||
|
|
|
|||
26
client/src/hooks/Messages/useSearchResultsByTurn.ts
Normal file
26
client/src/hooks/Messages/useSearchResultsByTurn.ts
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
import { useMemo } from 'react';
|
||||
import { TAttachment, Tools, SearchResultData } from 'librechat-data-provider';
|
||||
|
||||
/**
|
||||
* Hook that creates a map of turn numbers to SearchResultData from web search attachments
|
||||
* @param attachments Array of attachment metadata
|
||||
* @returns A map of turn numbers to their corresponding search result data
|
||||
*/
|
||||
export function useSearchResultsByTurn(attachments?: TAttachment[]) {
|
||||
const searchResultsByTurn = useMemo(() => {
|
||||
const turnMap: { [key: string]: SearchResultData } = {};
|
||||
|
||||
attachments?.forEach((attachment) => {
|
||||
if (attachment.type === Tools.web_search && attachment[Tools.web_search]) {
|
||||
const searchData = attachment[Tools.web_search];
|
||||
if (searchData && typeof searchData.turn === 'number') {
|
||||
turnMap[searchData.turn.toString()] = searchData;
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return turnMap;
|
||||
}, [attachments]);
|
||||
|
||||
return searchResultsByTurn;
|
||||
}
|
||||
|
|
@ -1,4 +1,5 @@
|
|||
export { default as useAuthCodeTool } from './useAuthCodeTool';
|
||||
export { default as usePluginInstall } from './usePluginInstall';
|
||||
export { default as useCodeApiKeyForm } from './useCodeApiKeyForm';
|
||||
export { default as useSearchApiKeyForm } from './useSearchApiKeyForm';
|
||||
export { default as usePluginDialogHelpers } from './usePluginDialogHelpers';
|
||||
|
|
|
|||
84
client/src/hooks/Plugins/useAuthSearchTool.ts
Normal file
84
client/src/hooks/Plugins/useAuthSearchTool.ts
Normal file
|
|
@ -0,0 +1,84 @@
|
|||
import { useCallback } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { AuthType, Tools, QueryKeys } from 'librechat-data-provider';
|
||||
import { useUpdateUserPluginsMutation } from 'librechat-data-provider/react-query';
|
||||
|
||||
export type SearchApiKeyFormData = {
|
||||
serperApiKey: string;
|
||||
firecrawlApiKey: string;
|
||||
firecrawlApiUrl: string;
|
||||
jinaApiKey: string;
|
||||
cohereApiKey: string;
|
||||
};
|
||||
|
||||
const useAuthSearchTool = (options?: { isEntityTool: boolean }) => {
|
||||
const queryClient = useQueryClient();
|
||||
const isEntityTool = options?.isEntityTool ?? true;
|
||||
const updateUserPlugins = useUpdateUserPluginsMutation({
|
||||
onMutate: (vars) => {
|
||||
queryClient.setQueryData([QueryKeys.toolAuth, Tools.web_search], () => {
|
||||
return {
|
||||
authenticated: vars.action === 'install',
|
||||
authTypes:
|
||||
vars.action === 'install'
|
||||
? [
|
||||
['providers', AuthType.USER_PROVIDED],
|
||||
['scrapers', AuthType.USER_PROVIDED],
|
||||
['rerankers', AuthType.USER_PROVIDED],
|
||||
]
|
||||
: [],
|
||||
};
|
||||
});
|
||||
},
|
||||
onSuccess: () => {
|
||||
queryClient.invalidateQueries([QueryKeys.toolAuth, Tools.web_search]);
|
||||
},
|
||||
onError: () => {
|
||||
queryClient.invalidateQueries([QueryKeys.toolAuth, Tools.web_search]);
|
||||
},
|
||||
});
|
||||
|
||||
const installTool = useCallback(
|
||||
(data: SearchApiKeyFormData) => {
|
||||
const auth = Object.entries({
|
||||
serperApiKey: data.serperApiKey,
|
||||
firecrawlApiKey: data.firecrawlApiKey,
|
||||
firecrawlApiUrl: data.firecrawlApiUrl,
|
||||
jinaApiKey: data.jinaApiKey,
|
||||
cohereApiKey: data.cohereApiKey,
|
||||
}).reduce(
|
||||
(acc, [key, value]) => {
|
||||
if (value) {
|
||||
acc[key] = value;
|
||||
}
|
||||
return acc;
|
||||
},
|
||||
{} as Record<string, string>,
|
||||
);
|
||||
|
||||
updateUserPlugins.mutate({
|
||||
pluginKey: Tools.web_search,
|
||||
action: 'install',
|
||||
auth,
|
||||
isEntityTool,
|
||||
});
|
||||
},
|
||||
[updateUserPlugins, isEntityTool],
|
||||
);
|
||||
|
||||
const removeTool = useCallback(() => {
|
||||
updateUserPlugins.mutate({
|
||||
pluginKey: Tools.web_search,
|
||||
action: 'uninstall',
|
||||
auth: {},
|
||||
isEntityTool,
|
||||
});
|
||||
}, [updateUserPlugins, isEntityTool]);
|
||||
|
||||
return {
|
||||
removeTool,
|
||||
installTool,
|
||||
};
|
||||
};
|
||||
|
||||
export default useAuthSearchTool;
|
||||
42
client/src/hooks/Plugins/useSearchApiKeyForm.ts
Normal file
42
client/src/hooks/Plugins/useSearchApiKeyForm.ts
Normal file
|
|
@ -0,0 +1,42 @@
|
|||
import { useState, useCallback } from 'react';
|
||||
import { useForm } from 'react-hook-form';
|
||||
import useAuthSearchTool from '~/hooks/Plugins/useAuthSearchTool';
|
||||
import type { SearchApiKeyFormData } from '~/hooks/Plugins/useAuthSearchTool';
|
||||
|
||||
export default function useSearchApiKeyForm({
|
||||
onSubmit,
|
||||
onRevoke,
|
||||
}: {
|
||||
onSubmit?: () => void;
|
||||
onRevoke?: () => void;
|
||||
}) {
|
||||
const methods = useForm<SearchApiKeyFormData>();
|
||||
const [isDialogOpen, setIsDialogOpen] = useState(false);
|
||||
const { installTool, removeTool } = useAuthSearchTool({ isEntityTool: true });
|
||||
const { reset } = methods;
|
||||
|
||||
const onSubmitHandler = useCallback(
|
||||
(data: SearchApiKeyFormData) => {
|
||||
reset();
|
||||
installTool(data);
|
||||
setIsDialogOpen(false);
|
||||
onSubmit?.();
|
||||
},
|
||||
[onSubmit, reset, installTool],
|
||||
);
|
||||
|
||||
const handleRevokeApiKey = useCallback(() => {
|
||||
reset();
|
||||
removeTool();
|
||||
setIsDialogOpen(false);
|
||||
onRevoke?.();
|
||||
}, [reset, onRevoke, removeTool]);
|
||||
|
||||
return {
|
||||
methods,
|
||||
isDialogOpen,
|
||||
setIsDialogOpen,
|
||||
handleRevokeApiKey,
|
||||
onSubmit: onSubmitHandler,
|
||||
};
|
||||
}
|
||||
|
|
@ -10,7 +10,7 @@ export default function useAttachmentHandler(queryClient?: QueryClient) {
|
|||
return ({ data }: { data: TAttachment; submission: EventSubmission }) => {
|
||||
const { messageId } = data;
|
||||
|
||||
if (queryClient && !data?.filepath?.startsWith('/api/files')) {
|
||||
if (queryClient && data?.filepath && !data.filepath.startsWith('/api/files')) {
|
||||
queryClient.setQueryData([QueryKeys.files], (oldData: TAttachment[] | undefined) => {
|
||||
return [data, ...(oldData || [])];
|
||||
});
|
||||
|
|
|
|||
|
|
@ -21,6 +21,7 @@
|
|||
"com_agents_name_placeholder": "Optional: The name of the agent",
|
||||
"com_agents_no_access": "You don't have access to edit this agent.",
|
||||
"com_agents_not_available": "Agent Not Available",
|
||||
"com_agents_search_info": "When enabled, allows your agent to search the web for up-to-date information. Requires a valid API key.",
|
||||
"com_agents_search_name": "Search agents by name",
|
||||
"com_agents_update_error": "There was an error updating your agent.",
|
||||
"com_assistants_action_attempt": "Assistant wants to talk to {{0}}",
|
||||
|
|
@ -724,6 +725,20 @@
|
|||
"com_ui_librechat_code_api_key": "Get your LibreChat Code Interpreter API key",
|
||||
"com_ui_librechat_code_api_subtitle": "Secure. Multi-language. Input/Output Files.",
|
||||
"com_ui_librechat_code_api_title": "Run AI Code",
|
||||
"com_ui_web_search_api_subtitle": "Search the web for up-to-date information",
|
||||
"com_ui_web_search_provider": "Search Provider",
|
||||
"com_ui_web_search_provider_serper": "Serper API",
|
||||
"com_ui_web_search_provider_serper_key": "Get your Serper API key",
|
||||
"com_ui_web_search_scraper": "Scraper",
|
||||
"com_ui_web_search_scraper_firecrawl": "Firecrawl API",
|
||||
"com_ui_web_search_scraper_firecrawl_key": "Get your Firecrawl API key",
|
||||
"com_ui_web_search_reranker": "Reranker",
|
||||
"com_ui_web_search_reranker_jina": "Jina AI",
|
||||
"com_ui_web_search_reranker_cohere": "Cohere",
|
||||
"com_ui_web_search_reranker_cohere_key": "Get your Cohere API key",
|
||||
"com_ui_web_search_firecrawl_url": "Firecrawl API URL (optional)",
|
||||
"com_ui_web_search_jina_key": "Enter Jina API Key",
|
||||
"com_ui_web_search_cohere_key": "Enter Cohere API Key",
|
||||
"com_ui_loading": "Loading...",
|
||||
"com_ui_locked": "Locked",
|
||||
"com_ui_logo": "{{0}} Logo",
|
||||
|
|
@ -800,6 +815,11 @@
|
|||
"com_ui_roleplay": "Roleplay",
|
||||
"com_ui_run_code": "Run Code",
|
||||
"com_ui_run_code_error": "There was an error running the code",
|
||||
"com_ui_web_search": "Web Search",
|
||||
"com_ui_web_search_processing": "Processing results",
|
||||
"com_ui_web_search_reading": "Reading results",
|
||||
"com_ui_web_searching": "Searching the web",
|
||||
"com_ui_web_searching_again": "Searching the web again",
|
||||
"com_ui_save": "Save",
|
||||
"com_ui_save_badge_changes": "Save badge changes?",
|
||||
"com_ui_save_submit": "Save & Submit",
|
||||
|
|
@ -895,5 +915,14 @@
|
|||
"com_ui_yes": "Yes",
|
||||
"com_ui_zoom": "Zoom",
|
||||
"com_user_message": "You",
|
||||
"com_warning_resubmit_unsupported": "Resubmitting the AI message is not supported for this endpoint."
|
||||
"com_warning_resubmit_unsupported": "Resubmitting the AI message is not supported for this endpoint.",
|
||||
"com_citation_source": "Source",
|
||||
"com_citation_more_details": "More details about {{label}}",
|
||||
"com_sources_tab_all": "All",
|
||||
"com_sources_tab_news": "News",
|
||||
"com_sources_tab_images": "Images",
|
||||
"com_sources_more_sources": "+{{count}} sources",
|
||||
"com_sources_title": "Sources",
|
||||
"com_sources_image_alt": "Search result image",
|
||||
"com_ui_web_search_reranker_jina_key": "Get your Jina API key"
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1039,7 +1039,7 @@ pre {
|
|||
--tw-prose-body: #374151;
|
||||
--tw-prose-headings: #111827;
|
||||
--tw-prose-lead: #4b5563;
|
||||
--tw-prose-links: #111827;
|
||||
--tw-prose-links: #0066cc;
|
||||
--tw-prose-bold: #111827;
|
||||
--tw-prose-counters: #6b7280;
|
||||
--tw-prose-bullets: #d1d5db;
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue