Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

🎨 feat: UI Refresh for Enhanced UX (#6346)

Marco Beretta7f29f2f676ac
diff --git a/api/app/clients/BaseClient.js b/api/app/clients/BaseClient.js
index 44ccc926db..fd1a051832 100644
--- a/api/app/clients/BaseClient.js
+++ b/api/app/clients/BaseClient.js
@@ -879,13 +879,14 @@ class BaseClient {
: await getConvo(this.options.req?.user?.id, message.conversationId);
const unsetFields = {};
+ const exceptions = new Set(['spec', 'iconURL']);
if (existingConvo != null) {
this.fetchedConvo = true;
for (const key in existingConvo) {
if (!key) {
continue;
}
- if (excludedKeys.has(key)) {
+ if (excludedKeys.has(key) && !exceptions.has(key)) {
continue;
}
diff --git a/bun.lockb b/bun.lockb
index e85113bbce..61118178fd 100755
Binary files a/bun.lockb and b/bun.lockb differ
diff --git a/client/package.json b/client/package.json
index 96b402e747..d4cd010a0a 100644
--- a/client/package.json
+++ b/client/package.json
@@ -52,6 +52,7 @@
"@radix-ui/react-switch": "^1.0.3",
"@radix-ui/react-tabs": "^1.0.3",
"@radix-ui/react-toast": "^1.1.5",
+ "@react-spring/web": "^9.7.5",
"@tanstack/react-query": "^4.28.0",
"@tanstack/react-table": "^8.11.7",
"class-variance-authority": "^0.6.0",
@@ -141,8 +142,8 @@
"ts-jest": "^29.2.5",
"typescript": "^5.3.3",
"vite": "^6.1.0",
- "vite-plugin-node-polyfills": "^0.17.0",
"vite-plugin-compression": "^0.5.1",
+ "vite-plugin-node-polyfills": "^0.17.0",
"vite-plugin-pwa": "^0.21.1"
}
}
diff --git a/client/src/common/index.ts b/client/src/common/index.ts
index 3452818fce..e1a3ab0a05 100644
--- a/client/src/common/index.ts
+++ b/client/src/common/index.ts
@@ -3,5 +3,6 @@ export * from './artifacts';
export * from './types';
export * from './menus';
export * from './tools';
+export * from './selector';
export * from './assistants-types';
export * from './agents-types';
diff --git a/client/src/common/selector.ts b/client/src/common/selector.ts
new file mode 100644
index 0000000000..a6380552c7
--- /dev/null
+++ b/client/src/common/selector.ts
@@ -0,0 +1,24 @@
+import React from 'react';
+import { TModelSpec, TInterfaceConfig } from 'librechat-data-provider';
+
+export interface Endpoint {
+ value: string;
+ label: string;
+ hasModels: boolean;
+ models?: string[];
+ icon: React.ReactNode;
+ agentNames?: Record<string, string>;
+ assistantNames?: Record<string, string>;
+ modelIcons?: Record<string, string | undefined>;
+}
+
+export interface SelectedValues {
+ endpoint: string | null;
+ model: string | null;
+ modelSpec: string | null;
+}
+
+export interface ModelSelectorProps {
+ interfaceConfig: TInterfaceConfig;
+ modelSpecs: TModelSpec[];
+}
diff --git a/client/src/common/types.ts b/client/src/common/types.ts
index 118cefce16..71e2e7a0c9 100644
--- a/client/src/common/types.ts
+++ b/client/src/common/types.ts
@@ -1,10 +1,10 @@
import { RefObject } from 'react';
-import { FileSources } from 'librechat-data-provider';
+import { FileSources, EModelEndpoint } from 'librechat-data-provider';
+import type { UseMutationResult } from '@tanstack/react-query';
import type * as InputNumberPrimitive from 'rc-input-number';
+import type { SetterOrUpdater, RecoilState } from 'recoil';
import type { ColumnDef } from '@tanstack/react-table';
-import type { SetterOrUpdater } from 'recoil';
import type * as t from 'librechat-data-provider';
-import type { UseMutationResult } from '@tanstack/react-query';
import type { LucideIcon } from 'lucide-react';
import type { TranslationKeys } from '~/hooks';
@@ -48,6 +48,14 @@ export type AudioChunk = {
};
};
+export type BadgeItem = {
+ id: string;
+ icon: React.ComponentType<any>;
+ label: string;
+ atom: RecoilState<boolean>;
+ isAvailable: boolean;
+};
+
export type AssistantListItem = {
id: string;
name: string;
@@ -488,6 +496,27 @@ export interface ExtendedFile {
metadata?: t.TFile['metadata'];
}
+export interface ExtendedEndpoint {
+ value: EModelEndpoint;
+ label: string;
+ hasModels: boolean;
+ icon: JSX.Element | null;
+ models?: string[];
+ agentNames?: Record<string, string>;
+ assistantNames?: Record<string, string>;
+ modelIcons?: Record<string, string | undefined>;
+}
+
+export interface ModelItemProps {
+ modelName: string;
+ endpoint: EModelEndpoint;
+ isSelected: boolean;
+ onSelect: () => void;
+ onNavigateBack: () => void;
+ icon?: JSX.Element;
+ className?: string;
+}
+
export type ContextType = { navVisible: boolean; setNavVisible: (visible: boolean) => void };
export interface SwitcherProps {
diff --git a/client/src/components/Chat/AddMultiConvo.tsx b/client/src/components/Chat/AddMultiConvo.tsx
index 6cfeb04b9c..24c1d7cb16 100644
--- a/client/src/components/Chat/AddMultiConvo.tsx
+++ b/client/src/components/Chat/AddMultiConvo.tsx
@@ -12,7 +12,7 @@ function AddMultiConvo() {
const localize = useLocalize();
const clickHandler = () => {
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
+
const { title: _t, ...convo } = conversation ?? ({} as TConversation);
setAddedConvo({
...convo,
@@ -42,7 +42,7 @@ function AddMultiConvo() {
role="button"
onClick={clickHandler}
data-testid="parameters-button"
- className="inline-flex size-10 items-center justify-center rounded-lg border border-border-light bg-transparent text-text-primary transition-all ease-in-out hover:bg-surface-tertiary disabled:pointer-events-none disabled:opacity-50 radix-state-open:bg-surface-tertiary"
+ className="inline-flex size-10 flex-shrink-0 items-center justify-center rounded-lg border border-border-light bg-transparent text-text-primary transition-all ease-in-out hover:bg-surface-tertiary disabled:pointer-events-none disabled:opacity-50 radix-state-open:bg-surface-tertiary"
>
<PlusCircle size={16} aria-label="Plus Icon" />
</TooltipAnchor>
diff --git a/client/src/components/Chat/ChatView.tsx b/client/src/components/Chat/ChatView.tsx
index dbf39ee845..1fbfdef736 100644
--- a/client/src/components/Chat/ChatView.tsx
+++ b/client/src/components/Chat/ChatView.tsx
@@ -7,6 +7,7 @@ import type { TMessage } from 'librechat-data-provider';
import type { ChatFormValues } from '~/common';
import { ChatContext, AddedChatContext, useFileMapContext, ChatFormProvider } from '~/Providers';
import { useChatHelpers, useAddedResponse, useSSE } from '~/hooks';
+import ConversationStarters from './Input/ConversationStarters';
import MessagesView from './Messages/MessagesView';
import { Spinner } from '~/components/svg';
import Presentation from './Presentation';
@@ -21,6 +22,7 @@ function ChatView({ index = 0 }: { index?: number }) {
const { conversationId } = useParams();
const rootSubmission = useRecoilValue(store.submissionByIndex(index));
const addedSubmission = useRecoilValue(store.submissionByIndex(index + 1));
+ const centerFormOnLanding = useRecoilValue(store.centerFormOnLanding);
const fileMap = useFileMapContext();
@@ -46,16 +48,18 @@ function ChatView({ index = 0 }: { index?: number }) {
});
let content: JSX.Element | null | undefined;
+ const isLandingPage = !messagesTree || messagesTree.length === 0;
+
if (isLoading && conversationId !== 'new') {
content = (
<div className="flex h-screen items-center justify-center">
- <Spinner className="opacity-0" />
+ <Spinner className="text-text-primary" />
</div>
);
- } else if (messagesTree && messagesTree.length !== 0) {
- content = <MessagesView messagesTree={messagesTree} Header={<Header />} />;
+ } else if (!isLandingPage) {
+ content = <MessagesView messagesTree={messagesTree} />;
} else {
- content = <Landing Header={<Header />} />;
+ content = <Landing centerFormOnLanding={centerFormOnLanding} />;
}
return (
@@ -63,10 +67,27 @@ function ChatView({ index = 0 }: { index?: number }) {
<ChatContext.Provider value={chatHelpers}>
<AddedChatContext.Provider value={addedChatHelpers}>
<Presentation>
- {content}
- <div className="w-full border-t-0 pl-0 pt-2 dark:border-white/20 md:w-[calc(100%-.5rem)] md:border-t-0 md:border-transparent md:pl-0 md:pt-0 md:dark:border-transparent">
- <ChatForm index={index} />
- <Footer />
+ <div className="flex h-full w-full flex-col">
+ {!isLoading && <Header />}
+
+ {isLandingPage ? (
+ <div className="flex flex-1 flex-col items-center justify-end sm:justify-center">
+ {content}
+ <div className="w-full max-w-3xl transition-all duration-200 xl:max-w-4xl">
+ <ChatForm index={index} />
+ <ConversationStarters />
+ <Footer />
+ </div>
+ </div>
+ ) : (
+ <div className="flex h-full flex-col overflow-y-auto">
+ {content}
+ <div className="w-full">
+ <ChatForm index={index} />
+ <Footer />
+ </div>
+ </div>
+ )}
</div>
</Presentation>
</AddedChatContext.Provider>
diff --git a/client/src/components/Chat/ConvoStarter.tsx b/client/src/components/Chat/ConvoStarter.tsx
deleted file mode 100644
index e7dbadbc20..0000000000
--- a/client/src/components/Chat/ConvoStarter.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-interface ConvoStarterProps {
- text: string;
- onClick: () => void;
-}
-
-export default function ConvoStarter({ text, onClick }: ConvoStarterProps) {
- return (
- <button
- onClick={onClick}
- className="relative flex w-40 cursor-pointer flex-col gap-2 rounded-2xl border border-border-medium px-3 pb-4 pt-3 text-start align-top text-[15px] shadow-[0_0_2px_0_rgba(0,0,0,0.05),0_4px_6px_0_rgba(0,0,0,0.02)] transition-colors duration-300 ease-in-out fade-in hover:bg-surface-tertiary"
- >
- <p className="break-word line-clamp-3 overflow-hidden text-balance break-all text-text-secondary">
- {text}
- </p>
- </button>
- );
-}
diff --git a/client/src/components/Chat/Footer.tsx b/client/src/components/Chat/Footer.tsx
index 75470f7e73..8bdebfb474 100644
--- a/client/src/components/Chat/Footer.tsx
+++ b/client/src/components/Chat/Footer.tsx
@@ -56,7 +56,7 @@ export default function Footer({ className }: { className?: string }) {
<React.Fragment key={`main-content-part-${index}`}>
<ReactMarkdown
components={{
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
+
a: ({ node: _n, href, children, ...otherProps }) => {
return (
<a
@@ -70,7 +70,7 @@ export default function Footer({ className }: { className?: string }) {
</a>
);
},
- // eslint-disable-next-line @typescript-eslint/no-unused-vars
+
p: ({ node: _n, ...props }) => <span {...props} />,
}}
>
@@ -87,7 +87,7 @@ export default function Footer({ className }: { className?: string }) {
<div
className={
className ??
- 'relative flex items-center justify-center gap-2 px-2 py-2 text-center text-xs text-text-primary md:px-[60px]'
+ 'relative hidden items-center justify-center gap-2 px-2 py-2 text-center text-xs text-text-primary sm:flex md:px-[60px]'
}
role="contentinfo"
>
diff --git a/client/src/components/Chat/Header.tsx b/client/src/components/Chat/Header.tsx
index 8a40a04d2e..d8a499128f 100644
--- a/client/src/components/Chat/Header.tsx
+++ b/client/src/components/Chat/Header.tsx
@@ -2,11 +2,11 @@ import { useMemo } from 'react';
import { useOutletContext } from 'react-router-dom';
import { getConfigDefaults, PermissionTypes, Permissions } from 'librechat-data-provider';
import type { ContextType } from '~/common';
-import { EndpointsMenu, ModelSpecsMenu, PresetsMenu, HeaderNewChat } from './Menus';
+import ModelSelector from './Menus/Endpoints/ModelSelector';
+import { PresetsMenu, HeaderNewChat } from './Menus';
import { useGetStartupConfig } from '~/data-provider';
import ExportAndShareMenu from './ExportAndShareMenu';
import { useMediaQuery, useHasAccess } from '~/hooks';
-import HeaderOptions from './Input/HeaderOptions';
import BookmarkMenu from './Menus/BookmarkMenu';
import AddMultiConvo from './AddMultiConvo';
@@ -34,14 +34,12 @@ export default function Header() {
const isSmallScreen = useMediaQuery('(max-width: 768px)');
return (
- <div className="sticky top-0 z-10 flex h-14 w-full items-center justify-between bg-white p-2 font-semibold dark:bg-gray-800 dark:text-white">
+ <div className="sticky top-0 z-10 flex h-14 w-full items-center justify-between bg-white p-2 font-semibold text-text-primary dark:bg-gray-800">
<div className="hide-scrollbar flex w-full items-center justify-between gap-2 overflow-x-auto">
- <div className="flex items-center gap-2">
+ <div className="mx-2 flex items-center gap-2">
{!navVisible && <HeaderNewChat />}
- {interfaceConfig.endpointsMenu === true && <EndpointsMenu />}
- {modelSpecs.length > 0 && <ModelSpecsMenu modelSpecs={modelSpecs} />}
- {<HeaderOptions interfaceConfig={interfaceConfig} />}
- {interfaceConfig.presets === true && <PresetsMenu />}
+ {<ModelSelector interfaceConfig={interfaceConfig} modelSpecs={modelSpecs} />}
+ {interfaceConfig.presets === true && interfaceConfig.modelSelect && <PresetsMenu />}
{hasAccessToBookmarks === true && <BookmarkMenu />}
{hasAccessToMultiConvo === true && <AddMultiConvo />}
{isSmallScreen && (
diff --git a/client/src/components/Chat/Input/AudioRecorder.tsx b/client/src/components/Chat/Input/AudioRecorder.tsx
index 512c9c9d9c..eae7c266cf 100644
--- a/client/src/components/Chat/Input/AudioRecorder.tsx
+++ b/client/src/components/Chat/Input/AudioRecorder.tsx
@@ -7,14 +7,12 @@ import { globalAudioId } from '~/common';
import { cn } from '~/utils';
export default function AudioRecorder({
- isRTL,
disabled,
ask,
methods,
textAreaRef,
isSubmitting,
}: {
- isRTL: boolean;
disabled: boolean;
ask: (data: { text: string }) => void;
methods: ReturnType<typeof useChatFormContext>;
@@ -90,9 +88,7 @@ export default function AudioRecorder({
onClick={isListening === true ? handleStopRecording : handleStartRecording}
disabled={disabled}
className={cn(
- 'absolute flex size-[35px] items-center justify-center rounded-full p-1 transition-colors hover:bg-surface-hover',
- isRTL ? 'bottom-2 left-2' : 'bottom-2 right-2',
- disabled ? 'cursor-not-allowed opacity-50' : 'cursor-pointer',
+ 'flex size-9 items-center justify-center rounded-full p-1 transition-colors hover:bg-surface-hover',
)}
title={localize('com_ui_use_micrphone')}
aria-pressed={isListening}
diff --git a/client/src/components/Chat/Input/BadgeRow.tsx b/client/src/components/Chat/Input/BadgeRow.tsx
new file mode 100644
index 0000000000..c217d749ae
--- /dev/null
+++ b/client/src/components/Chat/Input/BadgeRow.tsx
@@ -0,0 +1,357 @@
+import React, {
+ useState,
+ useRef,
+ useEffect,
+ useCallback,
+ useMemo,
+ forwardRef,
+ useReducer,
+} from 'react';
+import { useRecoilValue, useRecoilCallback } from 'recoil';
+import type { LucideIcon } from 'lucide-react';
+import { useChatBadges } from '~/hooks';
+import { Badge } from '~/components/ui';
+import { BadgeItem } from '~/common';
+import store from '~/store';
+
+interface BadgeRowProps {
+ onChange: (badges: Pick<BadgeItem, 'id'>[]) => void;
+ onToggle?: (badgeId: string, currentActive: boolean) => void;
+}
+
+interface BadgeWrapperProps {
+ badge: BadgeItem;
+ isEditing: boolean;
+ onToggle: (badge: BadgeItem) => void;
+ onDelete: (id: string) => void;
+ onMouseDown: (e: React.MouseEvent, badge: BadgeItem, isActive: boolean) => void;
+ badgeRefs: React.MutableRefObject<Record<string, HTMLDivElement>>;
+}
+
+const BadgeWrapper = React.memo(
+ forwardRef<HTMLDivElement, BadgeWrapperProps>(
+ ({ badge, isEditing, onToggle, onDelete, onMouseDown, badgeRefs }, ref) => {
+ const isActive = badge.atom ? useRecoilValue(badge.atom) : false;
+
+ return (
+ <div
+ ref={(el) => {
+ if (el) {
+ badgeRefs.current[badge.id] = el;
+ }
+ if (typeof ref === 'function') {
+ ref(el);
+ } else if (ref) {
+ ref.current = el;
+ }
+ }}
+ onMouseDown={(e) => onMouseDown(e, badge, isActive)}
+ className={isEditing ? 'ios-wiggle badge-icon h-full' : 'badge-icon h-full'}
+ >
+ <Badge
+ icon={badge.icon as LucideIcon}
+ label={badge.label}
+ isActive={isActive}
+ isEditing={isEditing}
+ isAvailable={badge.isAvailable}
+ onToggle={() => onToggle(badge)}
+ onBadgeAction={() => onDelete(badge.id)}
+ />
+ </div>
+ );
+ },
+ ),
+ (prevProps, nextProps) =>
+ prevProps.badge.id === nextProps.badge.id &&
+ prevProps.isEditing === nextProps.isEditing &&
+ prevProps.onToggle === nextProps.onToggle &&
+ prevProps.onDelete === nextProps.onDelete &&
+ prevProps.onMouseDown === nextProps.onMouseDown &&
+ prevProps.badgeRefs === nextProps.badgeRefs,
+);
+
+BadgeWrapper.displayName = 'BadgeWrapper';
+
+interface DragState {
+ draggedBadge: BadgeItem | null;
+ mouseX: number;
+ offsetX: number;
+ insertIndex: number | null;
+ draggedBadgeActive: boolean;
+}
+
+type DragAction =
+ | {
+ type: 'START_DRAG';
+ badge: BadgeItem;
+ mouseX: number;
+ offsetX: number;
+ insertIndex: number;
+ isActive: boolean;
+ }
+ | { type: 'UPDATE_POSITION'; mouseX: number; insertIndex: number }
+ | { type: 'END_DRAG' };
+
+const dragReducer = (state: DragState, action: DragAction): DragState => {
+ switch (action.type) {
+ case 'START_DRAG':
+ return {
+ draggedBadge: action.badge,
+ mouseX: action.mouseX,
+ offsetX: action.offsetX,
+ insertIndex: action.insertIndex,
+ draggedBadgeActive: action.isActive,
+ };
+ case 'UPDATE_POSITION':
+ return {
+ ...state,
+ mouseX: action.mouseX,
+ insertIndex: action.insertIndex,
+ };
+ case 'END_DRAG':
+ return {
+ draggedBadge: null,
+ mouseX: 0,
+ offsetX: 0,
+ insertIndex: null,
+ draggedBadgeActive: false,
+ };
+ default:
+ return state;
+ }
+};
+
+export function BadgeRow({ onChange, onToggle }: BadgeRowProps) {
+ const [orderedBadges, setOrderedBadges] = useState<BadgeItem[]>([]);
+ const [dragState, dispatch] = useReducer(dragReducer, {
+ draggedBadge: null,
+ mouseX: 0,
+ offsetX: 0,
+ insertIndex: null,
+ draggedBadgeActive: false,
+ });
+
+ const badgeRefs = useRef<Record<string, HTMLDivElement>>({});
+ const containerRef = useRef<HTMLDivElement>(null);
+ const animationFrame = useRef<number | null>(null);
+ const containerRectRef = useRef<DOMRect | null>(null);
+
+ const allBadges = useChatBadges() || [];
+ const isEditing = useRecoilValue(store.isEditingBadges);
+
+ const badges = useMemo(
+ () => allBadges.filter((badge) => badge.isAvailable !== false),
+ [allBadges],
+ );
+
+ const toggleBadge = useRecoilCallback(
+ ({ snapshot, set }) =>
+ async (badgeAtom: any) => {
+ const current = await snapshot.getPromise(badgeAtom);
+ set(badgeAtom, !current);
+ },
+ [],
+ );
+
+ useEffect(() => {
+ setOrderedBadges((prev) => {
+ const currentIds = new Set(prev.map((b) => b.id));
+ const newBadges = badges.filter((b) => !currentIds.has(b.id));
+ return newBadges.length > 0 ? [...prev, ...newBadges] : prev;
+ });
+ }, [badges]);
+
+ const tempBadges = dragState.draggedBadge
+ ? orderedBadges.filter((b) => b.id !== dragState.draggedBadge?.id)
+ : orderedBadges;
+ const ghostBadge = dragState.draggedBadge || null;
+
+ const calculateInsertIndex = useCallback(
+ (currentMouseX: number): number => {
+ if (!dragState.draggedBadge || !containerRef.current || !containerRectRef.current) {
+ return 0;
+ }
+ const relativeMouseX = currentMouseX - containerRectRef.current.left;
+ const refs = tempBadges.map((b) => badgeRefs.current[b.id]).filter(Boolean);
+ if (refs.length === 0) {
+ return 0;
+ }
+ let idx = 0;
+ for (let i = 0; i < refs.length; i++) {
+ const rect = refs[i].getBoundingClientRect();
+ const relativeLeft = rect.left - containerRectRef.current.left;
+ const relativeCenter = relativeLeft + rect.width / 2;
+ if (relativeMouseX < relativeCenter) {
+ break;
+ }
+ idx = i + 1;
+ }
+ return idx;
+ },
+ [dragState.draggedBadge, tempBadges],
+ );
+
+ const handleMouseDown = useCallback(
+ (e: React.MouseEvent, badge: BadgeItem, isActive: boolean) => {
+ if (!isEditing || !containerRef.current) {
+ return;
+ }
+ const el = badgeRefs.current[badge.id];
+ if (!el) {
+ return;
+ }
+ const rect = el.getBoundingClientRect();
+ const offsetX = e.clientX - rect.left;
+ const mouseX = e.clientX;
+ const initialIndex = orderedBadges.findIndex((b) => b.id === badge.id);
+ containerRectRef.current = containerRef.current.getBoundingClientRect();
+ dispatch({
+ type: 'START_DRAG',
+ badge,
+ mouseX,
+ offsetX,
+ insertIndex: initialIndex,
+ isActive,
+ });
+ },
+ [isEditing, orderedBadges],
+ );
+
+ const handleMouseMove = useCallback(
+ (e: MouseEvent) => {
+ if (!dragState.draggedBadge) {
+ return;
+ }
+ if (animationFrame.current) {
+ cancelAnimationFrame(animationFrame.current);
+ }
+ animationFrame.current = requestAnimationFrame(() => {
+ const newMouseX = e.clientX;
+ const newInsertIndex = calculateInsertIndex(newMouseX);
+ if (newInsertIndex !== dragState.insertIndex) {
+ dispatch({ type: 'UPDATE_POSITION', mouseX: newMouseX, insertIndex: newInsertIndex });
+ } else {
+ dispatch({
+ type: 'UPDATE_POSITION',
+ mouseX: newMouseX,
+ insertIndex: dragState.insertIndex,
+ });
+ }
+ });
+ },
+ [dragState.draggedBadge, dragState.insertIndex, calculateInsertIndex],
+ );
+
+ const handleMouseUp = useCallback(() => {
+ if (dragState.draggedBadge && dragState.insertIndex !== null) {
+ const otherBadges = orderedBadges.filter((b) => b.id !== dragState.draggedBadge?.id);
+ const newBadges = [
+ ...otherBadges.slice(0, dragState.insertIndex),
+ dragState.draggedBadge,
+ ...otherBadges.slice(dragState.insertIndex),
+ ];
+ setOrderedBadges(newBadges);
+ onChange(newBadges.map((badge) => ({ id: badge.id })));
+ }
+ dispatch({ type: 'END_DRAG' });
+ containerRectRef.current = null;
+ }, [dragState.draggedBadge, dragState.insertIndex, orderedBadges, onChange]);
+
+ const handleDelete = useCallback(
+ (badgeId: string) => {
+ const newBadges = orderedBadges.filter((b) => b.id !== badgeId);
+ setOrderedBadges(newBadges);
+ onChange(newBadges.map((badge) => ({ id: badge.id })));
+ },
+ [orderedBadges, onChange],
+ );
+
+ const handleBadgeToggle = useCallback(
+ (badge: BadgeItem) => {
+ if (badge.atom) {
+ toggleBadge(badge.atom);
+ }
+ if (onToggle) {
+ onToggle(badge.id, !!badge.atom);
+ }
+ },
+ [toggleBadge, onToggle],
+ );
+
+ useEffect(() => {
+ if (!dragState.draggedBadge) {
+ return;
+ }
+ document.addEventListener('mousemove', handleMouseMove);
+ document.addEventListener('mouseup', handleMouseUp);
+ return () => {
+ document.removeEventListener('mousemove', handleMouseMove);
+ document.removeEventListener('mouseup', handleMouseUp);
+ if (animationFrame.current) {
+ cancelAnimationFrame(animationFrame.current);
+ animationFrame.current = null;
+ }
+ };
+ }, [dragState.draggedBadge, handleMouseMove, handleMouseUp]);
+
+ return (
+ <div ref={containerRef} className="relative flex flex-wrap items-center gap-2">
+ {tempBadges.map((badge, index) => (
+ <React.Fragment key={badge.id}>
+ {dragState.draggedBadge && dragState.insertIndex === index && ghostBadge && (
+ <div className="badge-icon h-full">
+ <Badge
+ icon={ghostBadge.icon as LucideIcon}
+ label={ghostBadge.label}
+ isActive={dragState.draggedBadgeActive}
+ isEditing={isEditing}
+ isAvailable={ghostBadge.isAvailable}
+ />
+ </div>
+ )}
+ <BadgeWrapper
+ badge={badge}
+ isEditing={isEditing}
+ onToggle={handleBadgeToggle}
+ onDelete={handleDelete}
+ onMouseDown={handleMouseDown}
+ badgeRefs={badgeRefs}
+ />
+ </React.Fragment>
+ ))}
+ {dragState.draggedBadge && dragState.insertIndex === tempBadges.length && ghostBadge && (
+ <div className="badge-icon h-full">
+ <Badge
+ icon={ghostBadge.icon as LucideIcon}
+ label={ghostBadge.label}
+ isActive={dragState.draggedBadgeActive}
+ isEditing={isEditing}
+ isAvailable={ghostBadge.isAvailable}
+ />
+ </div>
+ )}
+ {ghostBadge && (
+ <div
+ className="ghost-badge h-full"
+ style={{
+ position: 'absolute',
+ top: 0,
+ left: 0,
+ transform: `translateX(${dragState.mouseX - dragState.offsetX - (containerRectRef.current?.left || 0)}px)`,
+ zIndex: 10,
+ pointerEvents: 'none',
+ }}
+ >
+ <Badge
+ icon={ghostBadge.icon as LucideIcon}
+ label={ghostBadge.label}
+ isActive={dragState.draggedBadgeActive}
+ isAvailable={ghostBadge.isAvailable}
+ isEditing
+ isDragging
+ />
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx
index 29592abeaa..3bdbde785e 100644
--- a/client/src/components/Chat/Input/ChatForm.tsx
+++ b/client/src/components/Chat/Input/ChatForm.tsx
@@ -1,11 +1,7 @@
-import { memo, useRef, useMemo, useEffect, useState } from 'react';
+import { memo, useRef, useMemo, useEffect, useState, useCallback } from 'react';
+import { useWatch } from 'react-hook-form';
import { useRecoilState, useRecoilValue } from 'recoil';
-import {
- supportsFiles,
- mergeFileConfig,
- isAssistantsEndpoint,
- fileConfig as defaultFileConfig,
-} from 'librechat-data-provider';
+import { isAssistantsEndpoint } from 'librechat-data-provider';
import {
useChatContext,
useChatFormContext,
@@ -20,60 +16,50 @@ import {
useQueryParams,
useSubmitMessage,
} from '~/hooks';
-import { cn, removeFocusRings, checkIfScrollable } from '~/utils';
-import FileFormWrapper from './Files/FileFormWrapper';
-import { TextareaAutosize } from '~/components/ui';
-import { useGetFileConfig } from '~/data-provider';
-import { TemporaryChat } from './TemporaryChat';
+import { mainTextareaId, BadgeItem } from '~/common';
+import AttachFileChat from './Files/AttachFileChat';
+import FileFormChat from './Files/FileFormChat';
+import { TextareaAutosize } from '~/components';
+import { cn, removeFocusRings } from '~/utils';
import TextareaHeader from './TextareaHeader';
import PromptsCommand from './PromptsCommand';
import AudioRecorder from './AudioRecorder';
-import { mainTextareaId } from '~/common';
import CollapseChat from './CollapseChat';
import StreamAudio from './StreamAudio';
import StopButton from './StopButton';
import SendButton from './SendButton';
+import { BadgeRow } from './BadgeRow';
+import EditBadges from './EditBadges';
import Mention from './Mention';
import store from '~/store';
-const ChatForm = ({ index = 0 }) => {
+const ChatForm = memo(({ index = 0 }: { index?: number }) => {
const submitButtonRef = useRef<HTMLButtonElement>(null);
- const textAreaRef = useRef<HTMLTextAreaElement | null>(null);
- useQueryParams({ textAreaRef });
+ const textAreaRef = useRef<HTMLTextAreaElement>(null);
const [isCollapsed, setIsCollapsed] = useState(false);
- const [isScrollable, setIsScrollable] = useState(false);
+ const [, setIsScrollable] = useState(false);
+ const [visualRowCount, setVisualRowCount] = useState(1);
+ const [isTextAreaFocused, setIsTextAreaFocused] = useState(false);
+ const [backupBadges, setBackupBadges] = useState<Pick<BadgeItem, 'id'>[]>([]);
const SpeechToText = useRecoilValue(store.speechToText);
const TextToSpeech = useRecoilValue(store.textToSpeech);
const automaticPlayback = useRecoilValue(store.automaticPlayback);
const maximizeChatSpace = useRecoilValue(store.maximizeChatSpace);
- const [isTemporaryChat, setIsTemporaryChat] = useRecoilState<boolean>(store.isTemporary);
-
+ const chatDirection = useRecoilValue(store.chatDirection);
const isSearching = useRecoilValue(store.isSearching);
+
+ const [badges, setBadges] = useRecoilState(store.chatBadges);
+ const [isEditingBadges, setIsEditingBadges] = useRecoilState(store.isEditingBadges);
const [showStopButton, setShowStopButton] = useRecoilState(store.showStopButtonByIndex(index));
const [showPlusPopover, setShowPlusPopover] = useRecoilState(store.showPlusPopoverFamily(index));
const [showMentionPopover, setShowMentionPopover] = useRecoilState(
store.showMentionPopoverFamily(index),
);
- const chatDirection = useRecoilValue(store.chatDirection).toLowerCase();
- const isRTL = chatDirection === 'rtl';
-
const { requiresKey } = useRequiresKey();
- const handleKeyUp = useHandleKeyUp({
- index,
- textAreaRef,
- setShowPlusPopover,
- setShowMentionPopover,
- });
- const { handlePaste, handleKeyDown, handleCompositionStart, handleCompositionEnd } = useTextarea({
- textAreaRef,
- submitButtonRef,
- setIsScrollable,
- disabled: !!(requiresKey ?? false),
- });
-
+ const methods = useChatFormContext();
const {
files,
setFiles,
@@ -83,7 +69,6 @@ const ChatForm = ({ index = 0 }) => {
newConversation,
handleStopGenerating,
} = useChatContext();
- const methods = useChatFormContext();
const {
addedIndex,
generateConversation,
@@ -91,45 +76,71 @@ const ChatForm = ({ index = 0 }) => {
setConversation: setAddedConvo,
isSubmitting: isSubmittingAdded,
} = useAddedChatContext();
+ const assistantMap = useAssistantsMapContext();
const showStopAdded = useRecoilValue(store.showStopButtonByIndex(addedIndex));
+ const endpoint = useMemo(
+ () => conversation?.endpointType ?? conversation?.endpoint,
+ [conversation?.endpointType, conversation?.endpoint],
+ );
+
+ const isRTL = useMemo(() => chatDirection === 'rtl', [chatDirection.toLowerCase()]);
+ const invalidAssistant = useMemo(
+ () =>
+ isAssistantsEndpoint(endpoint) &&
+ (!(conversation?.assistant_id ?? '') ||
+ !assistantMap?.[endpoint ?? '']?.[conversation?.assistant_id ?? '']),
+ [conversation?.assistant_id, endpoint, assistantMap],
+ );
+ const disableInputs = useMemo(
+ () => requiresKey || invalidAssistant,
+ [requiresKey, invalidAssistant],
+ );
+
+ const handleContainerClick = useCallback(() => {
+ textAreaRef.current?.focus();
+ }, []);
+
+ const handleFocusOrClick = useCallback(() => {
+ if (isCollapsed) {
+ setIsCollapsed(false);
+ }
+ }, [isCollapsed]);
+
useAutoSave({
- conversationId: useMemo(() => conversation?.conversationId, [conversation]),
+ conversationId: conversation?.conversationId,
textAreaRef,
files,
setFiles,
});
- const assistantMap = useAssistantsMapContext();
const { submitMessage, submitPrompt } = useSubmitMessage();
-
- const { endpoint: _endpoint, endpointType } = conversation ?? { endpoint: null };
- const endpoint = endpointType ?? _endpoint;
-
- const { data: fileConfig = defaultFileConfig } = useGetFileConfig({
- select: (data) => mergeFileConfig(data),
+ const handleKeyUp = useHandleKeyUp({
+ index,
+ textAreaRef,
+ setShowPlusPopover,
+ setShowMentionPopover,
+ });
+ const { handlePaste, handleKeyDown, handleCompositionStart, handleCompositionEnd } = useTextarea({
+ textAreaRef,
+ submitButtonRef,
+ setIsScrollable,
+ disabled: disableInputs,
});
- const endpointFileConfig = fileConfig.endpoints[endpoint ?? ''];
- const invalidAssistant = useMemo(
- () =>
- isAssistantsEndpoint(conversation?.endpoint) &&
- (!(conversation?.assistant_id ?? '') ||
- !assistantMap?.[conversation?.endpoint ?? ''][conversation?.assistant_id ?? '']),
- [conversation?.assistant_id, conversation?.endpoint, assistantMap],
- );
- const disableInputs = useMemo(
- () => !!((requiresKey ?? false) || invalidAssistant),
- [requiresKey, invalidAssistant],
- );
+ useQueryParams({ textAreaRef });
const { ref, ...registerProps } = methods.register('text', {
required: true,
- onChange: (e) => {
- methods.setValue('text', e.target.value, { shouldValidate: true });
- },
+ onChange: useCallback(
+ (e: React.ChangeEvent<HTMLTextAreaElement>) =>
+ methods.setValue('text', e.target.value, { shouldValidate: true }),
+ [methods],
+ ),
});
+ const textValue = useWatch({ control: methods.control, name: 'text' });
+
useEffect(() => {
if (!isSearching && textAreaRef.current && !disableInputs) {
textAreaRef.current.focus();
@@ -138,33 +149,53 @@ const ChatForm = ({ index = 0 }) => {
useEffect(() => {
if (textAreaRef.current) {
- checkIfScrollable(textAreaRef.current);
+ const style = window.getComputedStyle(textAreaRef.current);
+ const lineHeight = parseFloat(style.lineHeight);
+ setVisualRowCount(Math.floor(textAreaRef.current.scrollHeight / lineHeight));
+ }
+ }, [textValue]);
+
+ useEffect(() => {
+ if (isEditingBadges && backupBadges.length === 0) {
+ setBackupBadges([...badges]);
}
+ }, [isEditingBadges, badges, backupBadges.length]);
+
+ const handleSaveBadges = useCallback(() => {
+ setIsEditingBadges(false);
+ setBackupBadges([]);
}, []);
- const endpointSupportsFiles: boolean = supportsFiles[endpointType ?? endpoint ?? ''] ?? false;
- const isUploadDisabled: boolean = endpointFileConfig?.disabled ?? false;
+ const handleCancelBadges = useCallback(() => {
+ if (backupBadges.length > 0) {
+ setBadges([...backupBadges]);
+ }
+ setIsEditingBadges(false);
+ setBackupBadges([]);
+ }, [backupBadges, setBadges]);
- const baseClasses = cn(
- 'md:py-3.5 m-0 w-full resize-none py-[13px] bg-surface-tertiary placeholder-black/50 dark:placeholder-white/50 [&:has(textarea:focus)]:shadow-[0_2px_6px_rgba(0,0,0,.05)]',
- isCollapsed ? 'max-h-[52px]' : 'max-h-[65vh] md:max-h-[75vh]',
- );
+ const isMoreThanThreeRows = visualRowCount > 3;
- const uploadActive = endpointSupportsFiles && !isUploadDisabled;
- const speechClass = isRTL
- ? `pr-${uploadActive ? '12' : '4'} pl-12`
- : `pl-${uploadActive ? '12' : '4'} pr-12`;
+ const baseClasses = useMemo(
+ () =>
+ cn(
+ 'md:py-3.5 m-0 w-full resize-none py-[13px] bg-surface-chat placeholder-black/50 dark:placeholder-white/50 [&:has(textarea:focus)]:shadow-[0_2px_6px_rgba(0,0,0,.05)]',
+ isCollapsed ? 'max-h-[52px]' : 'max-h-[45vh] md:max-h-[55vh]',
+ isMoreThanThreeRows ? 'pl-5' : 'px-5',
+ ),
+ [isCollapsed, isMoreThanThreeRows],
+ );
return (
<form
- onSubmit={methods.handleSubmit((data) => submitMessage(data))}
+ onSubmit={methods.handleSubmit(submitMessage)}
className={cn(
- 'mx-auto flex flex-row gap-3 pl-2 transition-all duration-200 last:mb-2',
- maximizeChatSpace ? 'w-full max-w-full' : 'md:max-w-2xl xl:max-w-3xl',
+ 'mx-auto flex flex-row gap-3 transition-all duration-200 sm:mb-2 sm:px-2',
+ maximizeChatSpace ? 'w-full max-w-full' : 'md:max-w-3xl xl:max-w-4xl',
)}
>
<div className="relative flex h-full flex-1 items-stretch md:flex-col">
- <div className="flex w-full items-center">
+ <div className={cn('flex w-full items-center', isRTL && 'flex-row-reverse')}>
{showPlusPopover && !isAssistantsEndpoint(endpoint) && (
<Mention
setShowMentionPopover={setShowPlusPopover}
@@ -183,90 +214,101 @@ const ChatForm = ({ index = 0 }) => {
/>
)}
<PromptsCommand index={index} textAreaRef={textAreaRef} submitPrompt={submitPrompt} />
- <div className="transitional-all relative flex w-full flex-grow flex-col overflow-hidden rounded-3xl bg-surface-tertiary text-text-primary duration-200">
- <TemporaryChat
- isTemporaryChat={isTemporaryChat}
- setIsTemporaryChat={setIsTemporaryChat}
- />
+ <div
+ onClick={handleContainerClick}
+ className={cn(
+ 'relative flex w-full flex-grow flex-col overflow-hidden rounded-t-3xl border border-border-light bg-surface-chat text-text-primary transition-all duration-200 sm:rounded-3xl',
+ isTextAreaFocused ? 'shadow-lg' : 'shadow-md',
+ )}
+ >
<TextareaHeader addedConvo={addedConvo} setAddedConvo={setAddedConvo} />
- <FileFormWrapper disableInputs={disableInputs}>
- {endpoint && (
- <>
+ <EditBadges
+ isEditingChatBadges={isEditingBadges}
+ handleCancelBadges={handleCancelBadges}
+ handleSaveBadges={handleSaveBadges}
+ setBadges={setBadges}
+ />
+ <FileFormChat disableInputs={disableInputs} />
+ {endpoint && (
+ <div className={cn('flex', isRTL ? 'flex-row-reverse' : 'flex-row')}>
+ <TextareaAutosize
+ {...registerProps}
+ ref={(e) => {
+ ref(e);
+ (textAreaRef as React.MutableRefObject<HTMLTextAreaElement | null>).current = e;
+ }}
+ disabled={disableInputs}
+ onPaste={handlePaste}
+ onKeyDown={handleKeyDown}
+ onKeyUp={handleKeyUp}
+ onCompositionStart={handleCompositionStart}
+ onCompositionEnd={handleCompositionEnd}
+ id={mainTextareaId}
+ tabIndex={0}
+ data-testid="text-input"
+ rows={1}
+ onFocus={() => {
+ handleFocusOrClick();
+ setIsTextAreaFocused(true);
+ }}
+ onBlur={setIsTextAreaFocused.bind(null, false)}
+ onClick={handleFocusOrClick}
+ style={{ height: 44, overflowY: 'auto' }}
+ className={cn(
+ baseClasses,
+ removeFocusRings,
+ 'transition-[max-height] duration-200',
+ )}
+ />
+ <div className="flex flex-col items-start justify-start pt-1.5">
<CollapseChat
isCollapsed={isCollapsed}
- isScrollable={isScrollable}
+ isScrollable={isMoreThanThreeRows}
setIsCollapsed={setIsCollapsed}
/>
- <TextareaAutosize
- {...registerProps}
- ref={(e) => {
- ref(e);
- textAreaRef.current = e;
- }}
- disabled={disableInputs}
- onPaste={handlePaste}
- onKeyDown={handleKeyDown}
- onKeyUp={handleKeyUp}
- onHeightChange={() => {
- if (textAreaRef.current) {
- const scrollable = checkIfScrollable(textAreaRef.current);
- setIsScrollable(scrollable);
- }
- }}
- onCompositionStart={handleCompositionStart}
- onCompositionEnd={handleCompositionEnd}
- id={mainTextareaId}
- tabIndex={0}
- data-testid="text-input"
- rows={1}
- onFocus={() => isCollapsed && setIsCollapsed(false)}
- onClick={() => isCollapsed && setIsCollapsed(false)}
- style={{ height: 44, overflowY: 'auto' }}
- className={cn(
- baseClasses,
- speechClass,
- removeFocusRings,
- 'transition-[max-height] duration-200',
- )}
- />
- </>
- )}
- </FileFormWrapper>
- {SpeechToText && (
- <AudioRecorder
- isRTL={isRTL}
- methods={methods}
- ask={submitMessage}
- textAreaRef={textAreaRef}
- disabled={!!disableInputs}
- isSubmitting={isSubmitting}
- />
+ </div>
+ </div>
)}
- {TextToSpeech && automaticPlayback && <StreamAudio index={index} />}
- </div>
- <div
- className={cn(
- 'mb-[5px] ml-[8px] flex flex-col items-end justify-end',
- isRTL && 'order-first mr-[8px]',
- )}
- style={{ alignSelf: 'flex-end' }}
- >
- {(isSubmitting || isSubmittingAdded) && (showStopButton || showStopAdded) ? (
- <StopButton stop={handleStopGenerating} setShowStopButton={setShowStopButton} />
- ) : (
- endpoint && (
- <SendButton
- ref={submitButtonRef}
- control={methods.control}
- disabled={!!(filesLoading || isSubmitting || disableInputs)}
+ <div
+ className={cn(
+ 'items-between flex gap-2 pb-2',
+ isRTL ? 'flex-row-reverse' : 'flex-row',
+ )}
+ >
+ <div className={`${isRTL ? 'mr-2' : 'ml-2'}`}>
+ <AttachFileChat disableInputs={disableInputs} />
+ </div>
+ <BadgeRow onChange={(newBadges) => setBadges(newBadges)} />
+ <div className="mx-auto flex" />
+ {SpeechToText && (
+ <AudioRecorder
+ methods={methods}
+ ask={submitMessage}
+ textAreaRef={textAreaRef}
+ disabled={disableInputs}
+ isSubmitting={isSubmitting}
/>
- )
- )}
+ )}
+ <div className={`${isRTL ? 'ml-2' : 'mr-2'}`}>
+ {(isSubmitting || isSubmittingAdded) && (showStopButton || showStopAdded) ? (
+ <StopButton stop={handleStopGenerating} setShowStopButton={setShowStopButton} />
+ ) : (
+ endpoint && (
+ <SendButton
+ ref={submitButtonRef}
+ control={methods.control}
+ disabled={filesLoading || isSubmitting || disableInputs}
+ />
+ )
+ )}
+ </div>
+ </div>
+ {TextToSpeech && automaticPlayback && <StreamAudio index={index} />}
</div>
</div>
</div>
</form>
);
-};
+});
-export default memo(ChatForm);
+export default ChatForm;
diff --git a/client/src/components/Chat/Input/CollapseChat.tsx b/client/src/components/Chat/Input/CollapseChat.tsx
index ce6fdbf807..715724c29d 100644
--- a/client/src/components/Chat/Input/CollapseChat.tsx
+++ b/client/src/components/Chat/Input/CollapseChat.tsx
@@ -1,5 +1,5 @@
import React from 'react';
-import { Minimize2 } from 'lucide-react';
+import { ChevronDown, ChevronUp } from 'lucide-react';
import { TooltipAnchor } from '~/components/ui';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
@@ -18,23 +18,37 @@ const CollapseChat = ({
return null;
}
- if (isCollapsed) {
- return null;
- }
+ const description = isCollapsed
+ ? localize('com_ui_expand_chat')
+ : localize('com_ui_collapse_chat');
return (
- <TooltipAnchor
- role="button"
- description={localize('com_ui_collapse_chat')}
- aria-label={localize('com_ui_collapse_chat')}
- onClick={() => setIsCollapsed(true)}
- className={cn(
- 'absolute right-2 top-2 z-10 size-[35px] rounded-full p-2 transition-colors',
- 'hover:bg-surface-hover focus:outline-none focus:ring-2 focus:ring-primary focus:ring-opacity-50',
- )}
- >
- <Minimize2 className="h-full w-full" />
- </TooltipAnchor>
+ <div className="relative ml-auto items-end justify-end">
+ <TooltipAnchor
+ description={description}
+ render={
+ <button
+ aria-label={description}
+ onClick={(event) => {
+ event.preventDefault();
+ event.stopPropagation();
+ setIsCollapsed((prev) => !prev);
+ }}
+ className={cn(
+ // 'absolute right-1.5 top-1.5',
+ 'z-10 size-5 rounded-full transition-colors',
+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-primary focus-visible:ring-opacity-50',
+ )}
+ >
+ {isCollapsed ? (
+ <ChevronDown className="h-full w-full" />
+ ) : (
+ <ChevronUp className="h-full w-full" />
+ )}
+ </button>
+ }
+ />
+ </div>
);
};
diff --git a/client/src/components/Chat/Input/ConversationStarters.tsx b/client/src/components/Chat/Input/ConversationStarters.tsx
new file mode 100644
index 0000000000..12408b55a6
--- /dev/null
+++ b/client/src/components/Chat/Input/ConversationStarters.tsx
@@ -0,0 +1,85 @@
+import { useMemo, useCallback } from 'react';
+import { EModelEndpoint, Constants } from 'librechat-data-provider';
+import { useChatContext, useAgentsMapContext, useAssistantsMapContext } from '~/Providers';
+import { useGetAssistantDocsQuery, useGetEndpointsQuery } from '~/data-provider';
+import { getIconEndpoint, getEntity } from '~/utils';
+import { useSubmitMessage } from '~/hooks';
+
+const ConversationStarters = () => {
+ const { conversation } = useChatContext();
+ const agentsMap = useAgentsMapContext();
+ const assistantMap = useAssistantsMapContext();
+ const { data: endpointsConfig } = useGetEndpointsQuery();
+
+ const endpointType = useMemo(() => {
+ let ep = conversation?.endpoint ?? '';
+ if (
+ [
+ EModelEndpoint.chatGPTBrowser,
+ EModelEndpoint.azureOpenAI,
+ EModelEndpoint.gptPlugins,
+ ].includes(ep as EModelEndpoint)
+ ) {
+ ep = EModelEndpoint.openAI;
+ }
+ return getIconEndpoint({
+ endpointsConfig,
+ iconURL: conversation?.iconURL,
+ endpoint: ep,
+ });
+ }, [conversation?.endpoint, conversation?.iconURL, endpointsConfig]);
+
+ const { data: documentsMap = new Map() } = useGetAssistantDocsQuery(endpointType, {
+ select: (data) => new Map(data.map((dbA) => [dbA.assistant_id, dbA])),
+ });
+
+ const { entity, isAgent } = getEntity({
+ endpoint: endpointType,
+ agentsMap,
+ assistantMap,
+ agent_id: conversation?.agent_id,
+ assistant_id: conversation?.assistant_id,
+ });
+
+ const conversation_starters = useMemo(() => {
+ if (entity?.conversation_starters?.length) {
+ return entity.conversation_starters;
+ }
+
+ if (isAgent) {
+ return [];
+ }
+
+ return documentsMap.get(entity?.id ?? '')?.conversation_starters ?? [];
+ }, [documentsMap, isAgent, entity]);
+
+ const { submitMessage } = useSubmitMessage();
+ const sendConversationStarter = useCallback(
+ (text: string) => submitMessage({ text }),
+ [submitMessage],
+ );
+
+ if (!conversation_starters.length) {
+ return null;
+ }
+
+ return (
+ <div className="mt-8 flex flex-wrap justify-center gap-3 px-4">
+ {conversation_starters
+ .slice(0, Constants.MAX_CONVO_STARTERS)
+ .map((text: string, index: number) => (
+ <button
+ key={index}
+ onClick={() => sendConversationStarter(text)}
+ className="relative flex w-40 cursor-pointer flex-col gap-2 rounded-2xl border border-border-medium px-3 pb-4 pt-3 text-start align-top text-[15px] shadow-[0_0_2px_0_rgba(0,0,0,0.05),0_4px_6px_0_rgba(0,0,0,0.02)] transition-colors duration-300 ease-in-out fade-in hover:bg-surface-tertiary"
+ >
+ <p className="break-word line-clamp-3 overflow-hidden text-balance break-all text-text-secondary">
+ {text}
+ </p>
+ </button>
+ ))}
+ </div>
+ );
+};
+
+export default ConversationStarters;
diff --git a/client/src/components/Chat/Input/EditBadges.tsx b/client/src/components/Chat/Input/EditBadges.tsx
new file mode 100644
index 0000000000..0c9c0b5b22
--- /dev/null
+++ b/client/src/components/Chat/Input/EditBadges.tsx
@@ -0,0 +1,87 @@
+import React, { useCallback } from 'react';
+import { Edit3, Check, X } from 'lucide-react';
+import type { LucideIcon } from 'lucide-react';
+import type { BadgeItem } from '~/common';
+import { useChatBadges, useLocalize } from '~/hooks';
+import { Button, Badge } from '~/components/ui';
+
+interface EditBadgesProps {
+ isEditingChatBadges: boolean;
+ handleCancelBadges: () => void;
+ handleSaveBadges: () => void;
+ setBadges: React.Dispatch<React.SetStateAction<Pick<BadgeItem, 'id'>[]>>;
+}
+
+const EditBadgesComponent = ({
+ isEditingChatBadges,
+ handleCancelBadges,
+ handleSaveBadges,
+ setBadges,
+}: EditBadgesProps) => {
+ const localize = useLocalize();
+ const allBadges = useChatBadges() || [];
+ const unavailableBadges = allBadges.filter((badge) => !badge.isAvailable);
+
+ const handleRestoreBadge = useCallback(
+ (badgeId: string) => {
+ setBadges((prev: Pick<BadgeItem, 'id'>[]) => [...prev, { id: badgeId }]);
+ },
+ [setBadges],
+ );
+
+ if (!isEditingChatBadges) {
+ return null;
+ }
+
+ return (
+ <div className="m-1.5 flex flex-col overflow-hidden rounded-b-lg rounded-t-2xl bg-surface-secondary-alt">
+ <div className="flex items-center gap-4 py-2 pl-3 pr-1.5 text-sm">
+ <span className="mt-0 flex size-6 flex-shrink-0 items-center justify-center">
+ <div className="icon-md">
+ <Edit3 className="icon-md" aria-hidden="true" />
+ </div>
+ </span>
+ <span className="text-token-text-secondary line-clamp-3 flex-1 py-0.5 font-semibold">
+ {localize('com_ui_save_badge_changes')}
+ </span>
+ <div className="flex h-8 gap-2">
+ <Button
+ size="sm"
+ variant="destructive"
+ aria-label="Cancel"
+ onClick={handleCancelBadges}
+ className="h-8"
+ >
+ <X className="icon-md" aria-hidden="true" />
+ </Button>
+ <Button
+ size="sm"
+ variant="submit"
+ aria-label="Save changes"
+ onClick={handleSaveBadges}
+ className="h-8 rounded-b-lg rounded-tr-xl"
+ >
+ <Check className="icon-md" aria-hidden="true" />
+ </Button>
+ </div>
+ </div>
+ {unavailableBadges && unavailableBadges.length > 0 && (
+ <div className="flex flex-wrap items-center gap-2 p-2">
+ {unavailableBadges.map((badge) => (
+ <div key={badge.id} className="badge-icon">
+ <Badge
+ icon={badge.icon as unknown as LucideIcon}
+ label={badge.label}
+ isAvailable={false}
+ isEditing={true}
+ onBadgeAction={() => handleRestoreBadge(badge.id)}
+ />
+ </div>
+ ))}
+ </div>
+ )}
+ </div>
+ );
+};
+
+export default React.memo(EditBadgesComponent);
diff --git a/client/src/components/Chat/Input/Files/AttachFile.tsx b/client/src/components/Chat/Input/Files/AttachFile.tsx
index 6bdccba11f..8d83c01dcc 100644
--- a/client/src/components/Chat/Input/Files/AttachFile.tsx
+++ b/client/src/components/Chat/Input/Files/AttachFile.tsx
@@ -1,55 +1,51 @@
import React, { useRef } from 'react';
-import { FileUpload, TooltipAnchor } from '~/components/ui';
-import { AttachmentIcon } from '~/components/svg';
-import { useLocalize } from '~/hooks';
+import { FileUpload, TooltipAnchor, AttachmentIcon } from '~/components';
+import { useLocalize, useFileHandling } from '~/hooks';
import { cn } from '~/utils';
-const AttachFile = ({
- isRTL,
- disabled,
- handleFileChange,
-}: {
- isRTL: boolean;
- disabled?: boolean | null;
- handleFileChange: (event: React.ChangeEvent<HTMLInputElement>) => void;
-}) => {
+const AttachFile = ({ disabled }: { disabled?: boolean | null }) => {
const localize = useLocalize();
const inputRef = useRef<HTMLInputElement>(null);
const isUploadDisabled = disabled ?? false;
+ const { handleFileChange } = useFileHandling();
+
return (
<FileUpload ref={inputRef} handleFileChange={handleFileChange}>
<TooltipAnchor
- role="button"
+ description={localize('com_sidepanel_attach_files')}
id="attach-file"
- aria-label={localize('com_sidepanel_attach_files')}
disabled={isUploadDisabled}
- className={cn(
- 'absolute flex size-[35px] items-center justify-center rounded-full p-1 transition-colors hover:bg-surface-hover focus:outline-none focus:ring-2 focus:ring-primary focus:ring-opacity-50',
- isRTL ? 'bottom-2 right-2' : 'bottom-2 left-2',
- )}
- description={localize('com_sidepanel_attach_files')}
- onKeyDownCapture={(e) => {
- if (!inputRef.current) {
- return;
- }
- if (e.key === 'Enter' || e.key === ' ') {
- inputRef.current.value = '';
- inputRef.current.click();
- }
- }}
- onClick={() => {
- if (!inputRef.current) {
- return;
- }
- inputRef.current.value = '';
- inputRef.current.click();
- }}
- >
- <div className="flex w-full items-center justify-center gap-2">
- <AttachmentIcon />
- </div>
- </TooltipAnchor>
+ render={
+ <button
+ aria-label={localize('com_sidepanel_attach_files')}
+ disabled={isUploadDisabled}
+ className={cn(
+ 'flex size-9 items-center justify-center rounded-full p-1 transition-colors hover:bg-surface-hover focus:outline-none focus:ring-2 focus:ring-primary focus:ring-opacity-50',
+ )}
+ onKeyDownCapture={(e) => {
+ if (!inputRef.current) {
+ return;
+ }
+ if (e.key === 'Enter' || e.key === ' ') {
+ inputRef.current.value = '';
+ inputRef.current.click();
+ }
+ }}
+ onClick={() => {
+ if (!inputRef.current) {
+ return;
+ }
+ inputRef.current.value = '';
+ inputRef.current.click();
+ }}
+ >
+ <div className="flex w-full items-center justify-center gap-2">
+ <AttachmentIcon />
+ </div>
+ </button>
+ }
+ />
</FileUpload>
);
};
diff --git a/client/src/components/Chat/Input/Files/AttachFileChat.tsx b/client/src/components/Chat/Input/Files/AttachFileChat.tsx
new file mode 100644
index 0000000000..b4b0de1a63
--- /dev/null
+++ b/client/src/components/Chat/Input/Files/AttachFileChat.tsx
@@ -0,0 +1,44 @@
+import { memo, useMemo } from 'react';
+import { useRecoilValue } from 'recoil';
+import {
+ supportsFiles,
+ mergeFileConfig,
+ isAgentsEndpoint,
+ EndpointFileConfig,
+ fileConfig as defaultFileConfig,
+} from 'librechat-data-provider';
+import { useChatContext } from '~/Providers';
+import { useGetFileConfig } from '~/data-provider';
+import AttachFileMenu from './AttachFileMenu';
+import AttachFile from './AttachFile';
+import store from '~/store';
+
+function AttachFileChat({ disableInputs }: { disableInputs: boolean }) {
+ const { conversation } = useChatContext();
+
+ const { endpoint: _endpoint, endpointType } = conversation ?? { endpoint: null };
+
+ const isAgents = useMemo(() => isAgentsEndpoint(_endpoint), [_endpoint]);
+
+ const { data: fileConfig = defaultFileConfig } = useGetFileConfig({
+ select: (data) => mergeFileConfig(data),
+ });
+
+ const endpointFileConfig = fileConfig.endpoints[_endpoint ?? ''] as
+ | EndpointFileConfig
+ | undefined;
+
+ const endpointSupportsFiles: boolean = supportsFiles[endpointType ?? _endpoint ?? ''] ?? false;
+ const isUploadDisabled = (disableInputs || endpointFileConfig?.disabled) ?? false;
+
+ if (isAgents) {
+ return <AttachFileMenu disabled={disableInputs} />;
+ }
+ if (endpointSupportsFiles && !isUploadDisabled) {
+ return <AttachFile disabled={disableInputs} />;
+ }
+
+ return null;
+}
+
+export default memo(AttachFileChat);
diff --git a/client/src/components/Chat/Input/Files/AttachFileMenu.tsx b/client/src/components/Chat/Input/Files/AttachFileMenu.tsx
index 8841a0ae51..0f5f8e05a7 100644
--- a/client/src/components/Chat/Input/Files/AttachFileMenu.tsx
+++ b/client/src/components/Chat/Input/Files/AttachFileMenu.tsx
@@ -2,25 +2,23 @@ import * as Ariakit from '@ariakit/react';
import React, { useRef, useState, useMemo } from 'react';
import { EToolResources, EModelEndpoint } from 'librechat-data-provider';
import { FileSearch, ImageUpIcon, TerminalSquareIcon, FileType2Icon } from 'lucide-react';
-import { FileUpload, TooltipAnchor, DropdownPopup } from '~/components/ui';
+import { FileUpload, TooltipAnchor, DropdownPopup, AttachmentIcon } from '~/components';
import { useGetEndpointsQuery } from '~/data-provider';
-import { AttachmentIcon } from '~/components/svg';
-import { useLocalize } from '~/hooks';
+import { useLocalize, useFileHandling } from '~/hooks';
import { cn } from '~/utils';
interface AttachFileProps {
- isRTL: boolean;
disabled?: boolean | null;
- handleFileChange: (event: React.ChangeEvent<HTMLInputElement>, toolResource?: string) => void;
}
-const AttachFile = ({ isRTL, disabled, handleFileChange }: AttachFileProps) => {
+const AttachFile = ({ disabled }: AttachFileProps) => {
const localize = useLocalize();
const isUploadDisabled = disabled ?? false;
const inputRef = useRef<HTMLInputElement>(null);
const [isPopoverActive, setIsPopoverActive] = useState(false);
const [toolResource, setToolResource] = useState<EToolResources | undefined>();
const { data: endpointsConfig } = useGetEndpointsQuery();
+ const { handleFileChange } = useFileHandling();
const capabilities = useMemo(
() => endpointsConfig?.[EModelEndpoint.agents]?.capabilities ?? [],
@@ -93,8 +91,7 @@ const AttachFile = ({ isRTL, disabled, handleFileChange }: AttachFileProps) => {
id="attach-file-menu-button"
aria-label="Attach File Options"
className={cn(
- 'absolute flex size-[35px] items-center justify-center rounded-full p-1 transition-colors hover:bg-surface-hover focus:outline-none focus:ring-2 focus:ring-primary focus:ring-opacity-50',
- isRTL ? 'bottom-2 right-2' : 'bottom-2 left-1 md:left-2',
+ 'flex size-9 items-center justify-center rounded-full p-1 transition-colors hover:bg-surface-hover focus:outline-none focus:ring-2 focus:ring-primary focus:ring-opacity-50',
)}
>
<div className="flex w-full items-center justify-center gap-2">
@@ -115,17 +112,15 @@ const AttachFile = ({ isRTL, disabled, handleFileChange }: AttachFileProps) => {
handleFileChange(e, toolResource);
}}
>
- <div className="relative select-none">
- <DropdownPopup
- menuId="attach-file-menu"
- isOpen={isPopoverActive}
- setIsOpen={setIsPopoverActive}
- modal={true}
- trigger={menuTrigger}
- items={dropdownItems}
- iconClassName="mr-0"
- />
- </div>
+ <DropdownPopup
+ menuId="attach-file-menu"
+ isOpen={isPopoverActive}
+ setIsOpen={setIsPopoverActive}
+ modal={true}
+ trigger={menuTrigger}
+ items={dropdownItems}
+ iconClassName="mr-0"
+ />
</FileUpload>
);
};
diff --git a/client/src/components/Chat/Input/Files/FileFormChat.tsx b/client/src/components/Chat/Input/Files/FileFormChat.tsx
new file mode 100644
index 0000000000..0dc8618e91
--- /dev/null
+++ b/client/src/components/Chat/Input/Files/FileFormChat.tsx
@@ -0,0 +1,30 @@
+import { memo } from 'react';
+import { useRecoilValue } from 'recoil';
+import { useChatContext } from '~/Providers';
+import { useFileHandling } from '~/hooks';
+import FileRow from './FileRow';
+import store from '~/store';
+
+function FileFormChat({ disableInputs }: { disableInputs: boolean }) {
+ const chatDirection = useRecoilValue(store.chatDirection).toLowerCase();
+ const { files, setFiles, conversation, setFilesLoading } = useChatContext();
+ const { endpoint: _endpoint } = conversation ?? { endpoint: null };
+ const { abortUpload } = useFileHandling();
+
+ const isRTL = chatDirection === 'rtl';
+
+ return (
+ <>
+ <FileRow
+ files={files}
+ setFiles={setFiles}
+ abortUpload={abortUpload}
+ setFilesLoading={setFilesLoading}
+ isRTL={isRTL}
+ Wrapper={({ children }) => <div className="mx-2 mt-2 flex flex-wrap gap-2">{children}</div>}
+ />
+ </>
+ );
+}
+
+export default memo(FileFormChat);
diff --git a/client/src/components/Chat/Input/Files/FileFormWrapper.tsx b/client/src/components/Chat/Input/Files/FileFormWrapper.tsx
deleted file mode 100644
index 73c3b0c096..0000000000
--- a/client/src/components/Chat/Input/Files/FileFormWrapper.tsx
+++ /dev/null
@@ -1,80 +0,0 @@
-import { memo, useMemo } from 'react';
-import { useRecoilValue } from 'recoil';
-import {
- supportsFiles,
- mergeFileConfig,
- isAgentsEndpoint,
- EndpointFileConfig,
- fileConfig as defaultFileConfig,
-} from 'librechat-data-provider';
-import { useGetFileConfig } from '~/data-provider';
-import AttachFileMenu from './AttachFileMenu';
-import { useChatContext } from '~/Providers';
-import { useFileHandling } from '~/hooks';
-import AttachFile from './AttachFile';
-import FileRow from './FileRow';
-import store from '~/store';
-
-function FileFormWrapper({
- children,
- disableInputs,
-}: {
- disableInputs: boolean;
- children?: React.ReactNode;
-}) {
- const chatDirection = useRecoilValue(store.chatDirection).toLowerCase();
- const { files, setFiles, conversation, setFilesLoading } = useChatContext();
- const { endpoint: _endpoint, endpointType } = conversation ?? { endpoint: null };
- const isAgents = useMemo(() => isAgentsEndpoint(_endpoint), [_endpoint]);
-
- const { handleFileChange, abortUpload } = useFileHandling();
-
- const { data: fileConfig = defaultFileConfig } = useGetFileConfig({
- select: (data) => mergeFileConfig(data),
- });
-
- const isRTL = chatDirection === 'rtl';
-
- const endpointFileConfig = fileConfig.endpoints[_endpoint ?? ''] as
- | EndpointFileConfig
- | undefined;
-
- const endpointSupportsFiles: boolean = supportsFiles[endpointType ?? _endpoint ?? ''] ?? false;
- const isUploadDisabled = (disableInputs || endpointFileConfig?.disabled) ?? false;
-
- const renderAttachFile = () => {
- if (isAgents) {
- return (
- <AttachFileMenu
- isRTL={isRTL}
- disabled={disableInputs}
- handleFileChange={handleFileChange}
- />
- );
- }
- if (endpointSupportsFiles && !isUploadDisabled) {
- return (
- <AttachFile isRTL={isRTL} disabled={disableInputs} handleFileChange={handleFileChange} />
- );
- }
-
- return null;
- };
-
- return (
- <>
- <FileRow
- files={files}
- setFiles={setFiles}
- abortUpload={abortUpload}
- setFilesLoading={setFilesLoading}
- isRTL={isRTL}
- Wrapper={({ children }) => <div className="mx-2 mt-2 flex flex-wrap gap-2">{children}</div>}
- />
- {children}
- {renderAttachFile()}
- </>
- );
-}
-
-export default memo(FileFormWrapper);
diff --git a/client/src/components/Chat/Input/Files/RemoveFile.tsx b/client/src/components/Chat/Input/Files/RemoveFile.tsx
index 8eb5507c6f..a3c76a910f 100644
--- a/client/src/components/Chat/Input/Files/RemoveFile.tsx
+++ b/client/src/components/Chat/Input/Files/RemoveFile.tsx
@@ -2,7 +2,7 @@ export default function RemoveFile({ onRemove }: { onRemove: () => void }) {
return (
<button
type="button"
- className="absolute right-1 top-1 -translate-y-1/2 translate-x-1/2 rounded-full bg-surface-secondary p-0.5 transition-colors duration-200 hover:bg-surface-primary z-50"
+ className="absolute right-1 top-1 -translate-y-1/2 translate-x-1/2 rounded-full bg-surface-secondary p-0.5 transition-colors duration-200 hover:bg-surface-primary"
onClick={onRemove}
>
<span>
diff --git a/client/src/components/Chat/Input/HeaderOptions.tsx b/client/src/components/Chat/Input/HeaderOptions.tsx
index 5313f43b8d..2dcca3c1f2 100644
--- a/client/src/components/Chat/Input/HeaderOptions.tsx
+++ b/client/src/components/Chat/Input/HeaderOptions.tsx
@@ -2,17 +2,12 @@ import { useRecoilState } from 'recoil';
import { Settings2 } from 'lucide-react';
import { useState, useEffect, useMemo } from 'react';
import { Root, Anchor } from '@radix-ui/react-popover';
-import {
- EModelEndpoint,
- isParamEndpoint,
- isAgentsEndpoint,
- tConvoUpdateSchema,
-} from 'librechat-data-provider';
+import { EModelEndpoint, isParamEndpoint, tConvoUpdateSchema } from 'librechat-data-provider';
+import { useUserKeyQuery } from 'librechat-data-provider/react-query';
import type { TPreset, TInterfaceConfig } from 'librechat-data-provider';
import { EndpointSettings, SaveAsPresetDialog, AlternativeSettings } from '~/components/Endpoints';
+import { useSetIndexOptions, useMediaQuery, useLocalize } from '~/hooks';
import { PluginStoreDialog, TooltipAnchor } from '~/components';
-import { ModelSelect } from '~/components/Input/ModelSelect';
-import { useSetIndexOptions, useLocalize } from '~/hooks';
import { useGetEndpointsQuery } from '~/data-provider';
import OptionsPopover from './OptionsPopover';
import PopoverButtons from './PopoverButtons';
@@ -26,6 +21,7 @@ export default function HeaderOptions({
interfaceConfig?: Partial<TInterfaceConfig>;
}) {
const { data: endpointsConfig } = useGetEndpointsQuery();
+
const [saveAsDialogShow, setSaveAsDialogShow] = useState<boolean>(false);
const [showPluginStoreDialog, setShowPluginStoreDialog] = useRecoilState(
store.showPluginStoreDialog,
@@ -35,6 +31,15 @@ export default function HeaderOptions({
const { showPopover, conversation, setShowPopover } = useChatContext();
const { setOption } = useSetIndexOptions();
const { endpoint, conversationId } = conversation ?? {};
+ const { data: keyExpiry = { expiresAt: undefined } } = useUserKeyQuery(endpoint ?? '');
+ const userProvidesKey = useMemo(
+ () => !!(endpointsConfig?.[endpoint ?? '']?.userProvide ?? false),
+ [endpointsConfig, endpoint],
+ );
+ const keyProvided = useMemo(
+ () => (userProvidesKey ? !!(keyExpiry.expiresAt ?? '') : true),
+ [keyExpiry.expiresAt, userProvidesKey],
+ );
const noSettings = useMemo<{ [key: string]: boolean }>(
() => ({
@@ -71,14 +76,6 @@ export default function HeaderOptions({
<div className="my-auto lg:max-w-2xl xl:max-w-3xl">
<span className="flex w-full flex-col items-center justify-center gap-0 md:order-none md:m-auto md:gap-2">
<div className="z-[61] flex w-full items-center justify-center gap-2">
- {interfaceConfig?.modelSelect === true && !isAgentsEndpoint(endpoint) && (
- <ModelSelect
- conversation={conversation}
- setOption={setOption}
- showAbove={false}
- popover={true}
- />
- )}
{!noSettings[endpoint] &&
interfaceConfig?.parameters === true &&
paramEndpoint === false && (
diff --git a/client/src/components/Chat/Input/Mention.tsx b/client/src/components/Chat/Input/Mention.tsx
index de36cda09b..067383711e 100644
--- a/client/src/components/Chat/Input/Mention.tsx
+++ b/client/src/components/Chat/Input/Mention.tsx
@@ -28,7 +28,7 @@ export default function Mention({
includeAssistants?: boolean;
}) {
const localize = useLocalize();
- const assistantMap = useAssistantsMapContext();
+ const assistantsMap = useAssistantsMapContext();
const {
options,
presets,
@@ -37,11 +37,11 @@ export default function Mention({
modelsConfig,
endpointsConfig,
assistantListMap,
- } = useMentions({ assistantMap: assistantMap || {}, includeAssistants });
+ } = useMentions({ assistantMap: assistantsMap || {}, includeAssistants });
const { onSelectMention } = useSelectMention({
presets,
modelSpecs,
- assistantMap,
+ assistantsMap,
endpointsConfig,
newConversation,
});
@@ -65,7 +65,7 @@ export default function Mention({
setSearchValue('');
setOpen(false);
setShowMentionPopover(false);
- onSelectMention(mention);
+ onSelectMention?.(mention);
if (textAreaRef.current) {
removeCharIfLast(textAreaRef.current, commandChar);
@@ -158,11 +158,11 @@ export default function Mention({
};
return (
- <div className="absolute bottom-14 z-10 w-full space-y-2">
+ <div className="absolute bottom-28 z-10 w-full space-y-2">
<div className="popover border-token-border-light rounded-2xl border bg-white p-2 shadow-lg dark:bg-gray-700">
<input
// The user expects focus to transition to the input field when the popover is opened
-
+ // eslint-disable-next-line jsx-a11y/no-autofocus
autoFocus
ref={inputRef}
placeholder={localize(placeholder)}
diff --git a/client/src/components/Chat/Input/PromptsCommand.tsx b/client/src/components/Chat/Input/PromptsCommand.tsx
index 4763143600..c34ffc0708 100644
--- a/client/src/components/Chat/Input/PromptsCommand.tsx
+++ b/client/src/components/Chat/Input/PromptsCommand.tsx
@@ -69,7 +69,9 @@ function PromptsCommand({
label: `${group.command != null && group.command ? `/${group.command} - ` : ''}${
group.name
}: ${
- (group.oneliner?.length ?? 0) > 0 ? group.oneliner : group.productionPrompt?.prompt ?? ''
+ (group.oneliner?.length ?? 0) > 0
+ ? group.oneliner
+ : (group.productionPrompt?.prompt ?? '')
}`,
icon: <CategoryIcon category={group.category ?? ''} className="h-5 w-5" />,
}));
@@ -195,11 +197,11 @@ function PromptsCommand({
variableGroup={variableGroup}
setVariableDialogOpen={setVariableDialogOpen}
>
- <div className="absolute bottom-14 z-10 w-full space-y-2">
+ <div className="absolute bottom-28 z-10 w-full space-y-2">
<div className="popover border-token-border-light rounded-2xl border bg-surface-tertiary-alt p-2 shadow-lg">
<input
// The user expects focus to transition to the input field when the popover is opened
- // eslint-disable-next-line jsx-a11y/no-autofocus
+
autoFocus
ref={inputRef}
placeholder={localize('com_ui_command_usage_placeholder')}
diff --git a/client/src/components/Chat/Input/SendButton.tsx b/client/src/components/Chat/Input/SendButton.tsx
index 870d62d312..52a2b4bed4 100644
--- a/client/src/components/Chat/Input/SendButton.tsx
+++ b/client/src/components/Chat/Input/SendButton.tsx
@@ -24,7 +24,7 @@ const SubmitButton = React.memo(
id="send-button"
disabled={props.disabled}
className={cn(
- 'rounded-full bg-text-primary p-2 text-text-primary outline-offset-4 transition-all duration-200 disabled:cursor-not-allowed disabled:text-text-secondary disabled:opacity-10',
+ 'rounded-full bg-text-primary p-1.5 text-text-primary outline-offset-4 transition-all duration-200 disabled:cursor-not-allowed disabled:text-text-secondary disabled:opacity-10',
)}
data-testid="send-button"
type="submit"
@@ -34,7 +34,7 @@ const SubmitButton = React.memo(
</span>
</button>
}
- ></TooltipAnchor>
+ />
);
}),
);
diff --git a/client/src/components/Chat/Input/StopButton.tsx b/client/src/components/Chat/Input/StopButton.tsx
index 36cf471c9a..6c785811cd 100644
--- a/client/src/components/Chat/Input/StopButton.tsx
+++ b/client/src/components/Chat/Input/StopButton.tsx
@@ -12,7 +12,7 @@ export default function StopButton({ stop, setShowStopButton }) {
<button
type="button"
className={cn(
- 'rounded-full bg-text-primary p-2 text-text-primary outline-offset-4 transition-all duration-200 disabled:cursor-not-allowed disabled:text-text-secondary disabled:opacity-10',
+ 'rounded-full bg-text-primary p-1.5 text-text-primary outline-offset-4 transition-all duration-200 disabled:cursor-not-allowed disabled:text-text-secondary disabled:opacity-10',
)}
aria-label={localize('com_nav_stop_generating')}
onClick={(e) => {
diff --git a/client/src/components/Chat/Input/TemporaryChat.tsx b/client/src/components/Chat/Input/TemporaryChat.tsx
deleted file mode 100644
index c1f571ba47..0000000000
--- a/client/src/components/Chat/Input/TemporaryChat.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-import { MessageCircleDashed, X } from 'lucide-react';
-import { useLocalize } from '~/hooks';
-
-interface TemporaryChatProps {
- isTemporaryChat: boolean;
- setIsTemporaryChat: (value: boolean) => void;
-}
-
-export const TemporaryChat = ({ isTemporaryChat, setIsTemporaryChat }: TemporaryChatProps) => {
- const localize = useLocalize();
-
- if (!isTemporaryChat) {
- return null;
- }
-
- return (
- <div className="divide-token-border-light m-1.5 flex flex-col divide-y overflow-hidden rounded-b-lg rounded-t-2xl bg-surface-secondary-alt">
- <div className="flex items-start gap-4 py-2.5 pl-3 pr-1.5 text-sm">
- <span className="mt-0 flex h-6 w-6 flex-shrink-0 items-center justify-center">
- <div className="icon-md">
- <MessageCircleDashed className="icon-md" aria-hidden="true" />
- </div>
- </span>
- <span className="text-token-text-secondary line-clamp-3 flex-1 py-0.5 font-semibold">
- {localize('com_ui_temporary_chat')}
- </span>
- <button
- className="text-token-text-secondary flex-shrink-0"
- type="button"
- aria-label="Close temporary chat"
- onClick={() => setIsTemporaryChat(false)}
- >
- <X className="pr-1" />
- </button>
- </div>
- </div>
- );
-};
diff --git a/client/src/components/Chat/Input/TextareaHeader.tsx b/client/src/components/Chat/Input/TextareaHeader.tsx
index d4aa3f0cc7..9e67252efe 100644
--- a/client/src/components/Chat/Input/TextareaHeader.tsx
+++ b/client/src/components/Chat/Input/TextareaHeader.tsx
@@ -13,7 +13,7 @@ export default function TextareaHeader({
return null;
}
return (
- <div className="divide-token-border-light m-1.5 flex flex-col divide-y overflow-hidden rounded-b-lg rounded-t-2xl bg-surface-secondary-alt">
+ <div className="m-1.5 flex flex-col divide-y overflow-hidden rounded-b-lg rounded-t-2xl bg-surface-secondary-alt">
<AddedConvo addedConvo={addedConvo} setAddedConvo={setAddedConvo} />
</div>
);
diff --git a/client/src/components/Chat/Landing.tsx b/client/src/components/Chat/Landing.tsx
index 5e3ac9de35..e5d2781882 100644
--- a/client/src/components/Chat/Landing.tsx
+++ b/client/src/components/Chat/Landing.tsx
@@ -1,47 +1,45 @@
-import { useMemo } from 'react';
-import { EModelEndpoint, Constants } from 'librechat-data-provider';
+import { useMemo, useCallback, useState, useEffect } from 'react';
+import { EModelEndpoint } from 'librechat-data-provider';
import type * as t from 'librechat-data-provider';
-import type { ReactNode } from 'react';
import { useChatContext, useAgentsMapContext, useAssistantsMapContext } from '~/Providers';
-import {
- useGetAssistantDocsQuery,
- useGetEndpointsQuery,
- useGetStartupConfig,
-} from '~/data-provider';
+import { useGetEndpointsQuery, useGetStartupConfig } from '~/data-provider';
+import { BirthdayIcon, TooltipAnchor, SplitText } from '~/components';
import ConvoIcon from '~/components/Endpoints/ConvoIcon';
-import { getIconEndpoint, getEntity, cn } from '~/utils';
-import { useLocalize, useSubmitMessage } from '~/hooks';
-import { TooltipAnchor } from '~/components/ui';
-import { BirthdayIcon } from '~/components/svg';
-import ConvoStarter from './ConvoStarter';
+import { useLocalize, useAuthContext } from '~/hooks';
+import { getIconEndpoint, getEntity } from '~/utils';
-export default function Landing({ Header }: { Header?: ReactNode }) {
+const containerClassName =
+ 'shadow-stroke relative flex h-full items-center justify-center rounded-full bg-white text-black';
+
+export default function Landing({ centerFormOnLanding }: { centerFormOnLanding: boolean }) {
const { conversation } = useChatContext();
const agentsMap = useAgentsMapContext();
const assistantMap = useAssistantsMapContext();
const { data: startupConfig } = useGetStartupConfig();
const { data: endpointsConfig } = useGetEndpointsQuery();
-
+ const { user } = useAuthContext();
const localize = useLocalize();
- let { endpoint = '' } = conversation ?? {};
-
- if (
- endpoint === EModelEndpoint.chatGPTBrowser ||
- endpoint === EModelEndpoint.azureOpenAI ||
- endpoint === EModelEndpoint.gptPlugins
- ) {
- endpoint = EModelEndpoint.openAI;
- }
-
- const iconURL = conversation?.iconURL;
- endpoint = getIconEndpoint({ endpointsConfig, iconURL, endpoint });
- const { data: documentsMap = new Map() } = useGetAssistantDocsQuery(endpoint, {
- select: (data) => new Map(data.map((dbA) => [dbA.assistant_id, dbA])),
- });
+ const endpointType = useMemo(() => {
+ let ep = conversation?.endpoint ?? '';
+ if (
+ [
+ EModelEndpoint.chatGPTBrowser,
+ EModelEndpoint.azureOpenAI,
+ EModelEndpoint.gptPlugins,
+ ].includes(ep as EModelEndpoint)
+ ) {
+ ep = EModelEndpoint.openAI;
+ }
+ return getIconEndpoint({
+ endpointsConfig,
+ iconURL: conversation?.iconURL,
+ endpoint: ep,
+ });
+ }, [conversation?.endpoint, conversation?.iconURL, endpointsConfig]);
const { entity, isAgent, isAssistant } = getEntity({
- endpoint,
+ endpoint: endpointType,
agentsMap,
assistantMap,
agent_id: conversation?.agent_id,
@@ -50,102 +48,106 @@ export default function Landing({ Header }: { Header?: ReactNode }) {
const name = entity?.name ?? '';
const description = entity?.description ?? '';
- const avatar = isAgent
- ? (entity as t.Agent | undefined)?.avatar?.filepath ?? ''
- : ((entity as t.Assistant | undefined)?.metadata?.avatar as string | undefined) ?? '';
- const conversation_starters = useMemo(() => {
- /* The user made updates, use client-side cache, or they exist in an Agent */
- if (entity && (entity.conversation_starters?.length ?? 0) > 0) {
- return entity.conversation_starters;
- }
- if (isAgent) {
- return entity?.conversation_starters ?? [];
- }
- /* If none in cache, we use the latest assistant docs */
- const entityDocs = documentsMap.get(entity?.id ?? '');
- return entityDocs?.conversation_starters ?? [];
- }, [documentsMap, isAgent, entity]);
+ const getGreeting = useCallback(() => {
+ if (typeof startupConfig?.interface?.customWelcome === 'string') {
+ return startupConfig.interface.customWelcome;
+ }
- const containerClassName =
- 'shadow-stroke relative flex h-full items-center justify-center rounded-full bg-white text-black';
+ const now = new Date();
+ const hours = now.getHours();
- const { submitMessage } = useSubmitMessage();
- const sendConversationStarter = (text: string) => submitMessage({ text });
+ const dayOfWeek = now.getDay();
+ const isWeekend = dayOfWeek === 0 || dayOfWeek === 6;
- const getWelcomeMessage = () => {
- const greeting = conversation?.greeting ?? '';
- if (greeting) {
- return greeting;
+ // Early morning (midnight to 4:59 AM)
+ if (hours >= 0 && hours < 5) {
+ return localize('com_ui_late_night');
}
-
- if (isAssistant) {
- return localize('com_nav_welcome_assistant');
+ // Morning (6 AM to 11:59 AM)
+ else if (hours < 12) {
+ if (isWeekend) {
+ return localize('com_ui_weekend_morning');
+ }
+ return localize('com_ui_good_morning');
}
-
- if (isAgent) {
- return localize('com_nav_welcome_agent');
+ // Afternoon (12 PM to 4:59 PM)
+ else if (hours < 17) {
+ return localize('com_ui_good_afternoon');
}
-
- return typeof startupConfig?.interface?.customWelcome === 'string'
- ? startupConfig?.interface?.customWelcome
- : localize('com_nav_welcome_message');
- };
+ // Evening (5 PM to 8:59 PM)
+ else {
+ return localize('com_ui_good_evening');
+ }
+ }, [localize, startupConfig?.interface?.customWelcome]);
return (
- <div className="relative h-full">
- <div className="absolute left-0 right-0">{Header != null ? Header : null}</div>
- <div className="flex h-full flex-col items-center justify-center">
- <div className={cn('relative h-12 w-12', name && avatar ? 'mb-0' : 'mb-3')}>
- <ConvoIcon
- agentsMap={agentsMap}
- assistantMap={assistantMap}
- conversation={conversation}
- endpointsConfig={endpointsConfig}
- containerClassName={containerClassName}
- context="landing"
- className="h-2/3 w-2/3"
- size={41}
- />
- {startupConfig?.showBirthdayIcon === true ? (
- <TooltipAnchor
- className="absolute bottom-8 right-2.5"
- description={localize('com_ui_happy_birthday')}
- >
- <BirthdayIcon />
- </TooltipAnchor>
- ) : null}
- </div>
- {name ? (
- <div className="flex flex-col items-center gap-0 p-2">
- <div className="text-center text-2xl font-medium dark:text-white">{name}</div>
- <div className="max-w-md text-center text-sm font-normal text-text-primary ">
- {description ||
- (typeof startupConfig?.interface?.customWelcome === 'string'
- ? startupConfig?.interface?.customWelcome
- : localize('com_nav_welcome_message'))}
+ <div
+ className={`flex h-full transform-gpu flex-col items-center justify-center pb-16 transition-all duration-200 ${centerFormOnLanding ? 'max-h-full sm:max-h-0' : 'max-h-full'}`}
+ >
+ <div className="flex flex-col items-center gap-0 p-2">
+ <div className="flex flex-col items-center justify-center gap-4 md:flex-row">
+ <div className="relative size-10 justify-center">
+ <ConvoIcon
+ agentsMap={agentsMap}
+ assistantMap={assistantMap}
+ conversation={conversation}
+ endpointsConfig={endpointsConfig}
+ containerClassName={containerClassName}
+ context="landing"
+ className="h-2/3 w-2/3"
+ size={41}
+ />
+ {startupConfig?.showBirthdayIcon && (
+ <TooltipAnchor
+ className="absolute bottom-[27px] right-2"
+ description={localize('com_ui_happy_birthday')}
+ >
+ <BirthdayIcon />
+ </TooltipAnchor>
+ )}
+ </div>
+ {((isAgent || isAssistant) && name) || name ? (
+ <div className="flex flex-col items-center gap-0 p-2">
+ <SplitText
+ key={`split-text-${name}`}
+ text={name}
+ className="text-4xl font-medium text-text-primary"
+ delay={50}
+ textAlign="center"
+ animationFrom={{ opacity: 0, transform: 'translate3d(0,50px,0)' }}
+ animationTo={{ opacity: 1, transform: 'translate3d(0,0,0)' }}
+ easing="easeOutCubic"
+ threshold={0}
+ rootMargin="0px"
+ />
</div>
- {/* <div className="mt-1 flex items-center gap-1 text-token-text-tertiary">
- <div className="text-sm text-token-text-tertiary">By Daniel Avila</div>
- </div> */}
+ ) : (
+ <SplitText
+ key={`split-text-${getGreeting()}${user?.username || ''}`}
+ text={getGreeting() + (user?.username ? ', ' + user.username : '')}
+ className="text-4xl font-medium text-text-primary"
+ delay={50}
+ textAlign="center"
+ animationFrom={{ opacity: 0, transform: 'translate3d(0,50px,0)' }}
+ animationTo={{ opacity: 1, transform: 'translate3d(0,0,0)' }}
+ easing="easeOutCubic"
+ threshold={0}
+ rootMargin="0px"
+ />
+ )}
+ </div>
+ {(isAgent || isAssistant) && description ? (
+ <div className="animate-fadeIn mt-2 max-w-md text-center text-sm font-normal text-text-primary">
+ {description}
</div>
) : (
- <h2 className="mb-5 max-w-[75vh] px-12 text-center text-lg font-medium dark:text-white md:px-0 md:text-2xl">
- {getWelcomeMessage()}
- </h2>
+ typeof startupConfig?.interface?.customWelcome === 'string' && (
+ <div className="animate-fadeIn mt-2 max-w-md text-center text-sm font-normal text-text-primary">
+ {startupConfig?.interface?.customWelcome}
+ </div>
+ )
)}
- <div className="mt-8 flex flex-wrap justify-center gap-3 px-4">
- {conversation_starters.length > 0 &&
- conversation_starters
- .slice(0, Constants.MAX_CONVO_STARTERS)
- .map((text: string, index: number) => (
- <ConvoStarter
- key={index}
- text={text}
- onClick={() => sendConversationStarter(text)}
- />
- ))}
- </div>
</div>
</div>
);
diff --git a/client/src/components/Chat/Menus/BookmarkMenu.tsx b/client/src/components/Chat/Menus/BookmarkMenu.tsx
index 6616ba46c0..326d1dcd4a 100644
--- a/client/src/components/Chat/Menus/BookmarkMenu.tsx
+++ b/client/src/components/Chat/Menus/BookmarkMenu.tsx
@@ -170,7 +170,7 @@ const BookmarkMenu: FC = () => {
id="bookmark-menu-button"
aria-label={localize('com_ui_bookmarks_add')}
className={cn(
- 'mt-text-sm flex size-10 items-center justify-center gap-2 rounded-lg border border-border-light text-sm transition-colors duration-200 hover:bg-surface-hover',
+ 'mt-text-sm flex size-10 flex-shrink-0 items-center justify-center gap-2 rounded-lg border border-border-light text-sm transition-colors duration-200 hover:bg-surface-hover',
isMenuOpen ? 'bg-surface-hover' : '',
)}
data-testid="bookmark-menu"
diff --git a/client/src/components/Chat/Menus/Endpoints/CustomMenu.tsx b/client/src/components/Chat/Menus/Endpoints/CustomMenu.tsx
new file mode 100644
index 0000000000..24eb0559d6
--- /dev/null
+++ b/client/src/components/Chat/Menus/Endpoints/CustomMenu.tsx
@@ -0,0 +1,246 @@
+import * as React from 'react';
+import * as Ariakit from '@ariakit/react';
+import { cn } from '~/utils';
+
+export interface CustomMenuProps extends Ariakit.MenuButtonProps<'div'> {
+ label?: React.ReactNode;
+ values?: Record<string, any>;
+ onValuesChange?: (values: Record<string, any>) => void;
+ searchValue?: string;
+ onSearch?: (value: string) => void;
+ combobox?: Ariakit.ComboboxProps['render'];
+ trigger?: Ariakit.MenuButtonProps['render'];
+ defaultOpen?: boolean;
+}
+
+export const CustomMenu = React.forwardRef<HTMLDivElement, CustomMenuProps>(function CustomMenu(
+ {
+ label,
+ children,
+ values,
+ onValuesChange,
+ searchValue,
+ onSearch,
+ combobox,
+ trigger,
+ defaultOpen,
+ ...props
+ },
+ ref,
+) {
+ const parent = Ariakit.useMenuContext();
+ const searchable = searchValue != null || !!onSearch || !!combobox;
+
+ const menuStore = Ariakit.useMenuStore({
+ showTimeout: 100,
+ placement: parent ? 'right' : 'left',
+ defaultOpen: defaultOpen,
+ });
+
+ const element = (
+ <Ariakit.MenuProvider store={menuStore} values={values} setValues={onValuesChange}>
+ <Ariakit.MenuButton
+ ref={ref}
+ {...props}
+ className={cn(
+ !parent &&
+ 'flex h-10 w-full items-center justify-center gap-2 rounded-xl border border-border-light px-3 py-2 text-sm text-text-primary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white',
+ menuStore.useState('open')
+ ? 'bg-surface-tertiary hover:bg-surface-tertiary'
+ : 'bg-surface-secondary hover:bg-surface-tertiary',
+ props.className,
+ )}
+ render={parent ? <CustomMenuItem render={trigger} /> : trigger}
+ >
+ <span className="flex-1">{label}</span>
+ <Ariakit.MenuButtonArrow className="stroke-1 text-base opacity-75" />
+ </Ariakit.MenuButton>
+ <Ariakit.Menu
+ open={menuStore.useState('open')}
+ portal
+ overlap
+ unmountOnHide
+ gutter={parent ? -4 : 4}
+ className={cn(
+ `${parent ? 'animate-popover-left ml-3' : 'animate-popover'} outline-none! z-50 flex max-h-[min(450px,var(--popover-available-height))] w-full`,
+ 'w-[var(--menu-width,auto)] min-w-[300px] flex-col overflow-auto rounded-xl border border-border-light',
+ 'bg-surface-secondary px-3 py-2 text-sm text-text-primary shadow-lg',
+ 'max-w-[calc(100vw-4rem)] sm:max-h-[calc(65vh)] sm:max-w-[400px]',
+ searchable && 'p-0',
+ )}
+ >
+ <SearchableContext.Provider value={searchable}>
+ {searchable ? (
+ <>
+ <div className="sticky top-0 z-10 bg-inherit p-1">
+ <Ariakit.Combobox
+ autoSelect
+ render={combobox}
+ className={cn(
+ 'h-10 w-full rounded border-none bg-transparent px-2 text-base',
+ 'sm:h-8 sm:text-sm',
+ )}
+ />
+ </div>
+ <Ariakit.ComboboxList className="p-0.5 pt-0">{children}</Ariakit.ComboboxList>
+ </>
+ ) : (
+ children
+ )}
+ </SearchableContext.Provider>
+ </Ariakit.Menu>
+ </Ariakit.MenuProvider>
+ );
+
+ if (searchable) {
+ return (
+ <Ariakit.ComboboxProvider
+ resetValueOnHide
+ includesBaseElement={false}
+ value={searchValue}
+ setValue={onSearch}
+ >
+ {element}
+ </Ariakit.ComboboxProvider>
+ );
+ }
+
+ return element;
+});
+
+export const CustomMenuSeparator = React.forwardRef<HTMLHRElement, Ariakit.MenuSeparatorProps>(
+ function CustomMenuSeparator(props, ref) {
+ return (
+ <Ariakit.MenuSeparator
+ ref={ref}
+ {...props}
+ className={cn(
+ 'my-0.5 h-0 w-full border-t border-slate-200 dark:border-slate-700',
+ props.className,
+ )}
+ />
+ );
+ },
+);
+
+export interface CustomMenuGroupProps extends Ariakit.MenuGroupProps {
+ label?: React.ReactNode;
+}
+
+export const CustomMenuGroup = React.forwardRef<HTMLDivElement, CustomMenuGroupProps>(
+ function CustomMenuGroup({ label, ...props }, ref) {
+ return (
+ <Ariakit.MenuGroup ref={ref} {...props} className={cn('', props.className)}>
+ {label && (
+ <Ariakit.MenuGroupLabel className="cursor-default p-2 text-sm font-medium opacity-60 sm:py-1 sm:text-xs">
+ {label}
+ </Ariakit.MenuGroupLabel>
+ )}
+ {props.children}
+ </Ariakit.MenuGroup>
+ );
+ },
+);
+
+const SearchableContext = React.createContext(false);
+
+export interface CustomMenuItemProps extends Omit<Ariakit.ComboboxItemProps, 'store'> {
+ name?: string;
+}
+
+export const CustomMenuItem = React.forwardRef<HTMLDivElement, CustomMenuItemProps>(
+ function CustomMenuItem({ name, value, ...props }, ref) {
+ const menu = Ariakit.useMenuContext();
+ const searchable = React.useContext(SearchableContext);
+ const defaultProps: CustomMenuItemProps = {
+ ref,
+ focusOnHover: true,
+ blurOnHoverEnd: false,
+ ...props,
+ className: cn(
+ 'flex cursor-default items-center gap-2 rounded-lg p-2 outline-none! scroll-m-1 scroll-mt-[calc(var(--combobox-height,0px)+var(--label-height,4px))] aria-disabled:opacity-25 data-[active-item]:bg-black/[0.075] data-[active-item]:text-black dark:data-[active-item]:bg-white/10 dark:data-[active-item]:text-white sm:py-1 sm:text-sm min-w-0 w-full',
+ props.className,
+ ),
+ };
+
+ const checkable = Ariakit.useStoreState(menu, (state) => {
+ if (!name) {
+ return false;
+ }
+ if (value == null) {
+ return false;
+ }
+ return state?.values[name] != null;
+ });
+
+ const checked = Ariakit.useStoreState(menu, (state) => {
+ if (!name) {
+ return false;
+ }
+ return state?.values[name] === value;
+ });
+
+ // If the item is checkable, we render a checkmark icon next to the label.
+ if (checkable) {
+ defaultProps.children = (
+ <React.Fragment>
+ <span className="flex-1">{defaultProps.children}</span>
+ <Ariakit.MenuItemCheck checked={checked} />
+ {searchable && (
+ // When an item is displayed in a search menu as a role=option
+ // element instead of a role=menuitemradio, we can't depend on the
+ // aria-checked attribute. Although NVDA and JAWS announce it
+ // accurately, VoiceOver doesn't. TalkBack does announce the checked
+ // state, but misleadingly implies that a double tap will change the
+ // state, which isn't the case. Therefore, we use a visually hidden
+ // element to indicate whether the item is checked or not, ensuring
+ // cross-browser/AT compatibility.
+ <Ariakit.VisuallyHidden>{checked ? 'checked' : 'not checked'}</Ariakit.VisuallyHidden>
+ )}
+ </React.Fragment>
+ );
+ }
+
+ // If the item is not rendered in a search menu (listbox), we can render it
+ // as a MenuItem/MenuItemRadio.
+ if (!searchable) {
+ if (name != null && value != null) {
+ const radioProps = { ...defaultProps, name, value, hideOnClick: true };
+ return <Ariakit.MenuItemRadio {...radioProps} />;
+ }
+ return <Ariakit.MenuItem {...defaultProps} />;
+ }
+
+ return (
+ <Ariakit.ComboboxItem
+ {...defaultProps}
+ setValueOnClick={false}
+ value={checkable ? value : undefined}
+ selectValueOnClick={() => {
+ if (name == null || value == null) {
+ return false;
+ }
+ // By default, clicking on a ComboboxItem will update the
+ // selectedValue state of the combobox. However, since we're sharing
+ // state between combobox and menu, we also need to update the menu's
+ // values state.
+ menu?.setValue(name, value);
+ return true;
+ }}
+ hideOnClick={(event) => {
+ // Make sure that clicking on a combobox item that opens a nested
+ // menu/dialog does not close the menu.
+ const expandable = event.currentTarget.hasAttribute('aria-expanded');
+ if (expandable) {
+ return false;
+ }
+ // By default, clicking on a ComboboxItem only closes its own popover.
+ // However, since we're in a menu context, we also close all parent
+ // menus.
+ menu?.hideAll();
+ return true;
+ }}
+ />
+ );
+ },
+);
diff --git a/client/src/components/Chat/Menus/Endpoints/DialogManager.tsx b/client/src/components/Chat/Menus/Endpoints/DialogManager.tsx
new file mode 100644
index 0000000000..fc6278c20a
--- /dev/null
+++ b/client/src/components/Chat/Menus/Endpoints/DialogManager.tsx
@@ -0,0 +1,34 @@
+import React from 'react';
+import { EModelEndpoint } from 'librechat-data-provider';
+import { SetKeyDialog } from '~/components/Input/SetKeyDialog';
+import { getEndpointField } from '~/utils';
+
+interface DialogManagerProps {
+ keyDialogOpen: boolean;
+ keyDialogEndpoint?: EModelEndpoint;
+ onOpenChange: (open: boolean) => void;
+ endpointsConfig: Record<string, any>;
+}
+
+const DialogManager = ({
+ keyDialogOpen,
+ keyDialogEndpoint,
+ onOpenChange,
+ endpointsConfig,
+}: DialogManagerProps) => {
+ return (
+ <>
+ {keyDialogEndpoint && (
+ <SetKeyDialog
+ open={keyDialogOpen}
+ endpoint={keyDialogEndpoint}
+ endpointType={getEndpointField(endpointsConfig, keyDialogEndpoint, 'type')}
+ onOpenChange={onOpenChange}
+ userProvideURL={getEndpointField(endpointsConfig, keyDialogEndpoint, 'userProvideURL')}
+ />
+ )}
+ </>
+ );
+};
+
+export default DialogManager;
diff --git a/client/src/components/Chat/Menus/Endpoints/MenuItem.tsx b/client/src/components/Chat/Menus/Endpoints/MenuItem.tsx
deleted file mode 100644
index 671abd0d21..0000000000
--- a/client/src/components/Chat/Menus/Endpoints/MenuItem.tsx
+++ /dev/null
@@ -1,221 +0,0 @@
-import { useState } from 'react';
-import { Settings } from 'lucide-react';
-import { useRecoilValue } from 'recoil';
-import { EModelEndpoint } from 'librechat-data-provider';
-import type { TConversation } from 'librechat-data-provider';
-import type { FC } from 'react';
-import { cn, getConvoSwitchLogic, getEndpointField, getIconKey } from '~/utils';
-import { useLocalize, useUserKey, useDefaultConvo } from '~/hooks';
-import { SetKeyDialog } from '~/components/Input/SetKeyDialog';
-import { useGetEndpointsQuery } from '~/data-provider';
-import { useChatContext } from '~/Providers';
-import { icons } from './Icons';
-import store from '~/store';
-
-type MenuItemProps = {
- title: string;
- value: EModelEndpoint;
- selected: boolean;
- description?: string;
- userProvidesKey: boolean;
- // iconPath: string;
- // hoverContent?: string;
-};
-
-const MenuItem: FC<MenuItemProps> = ({
- title,
- value: endpoint,
- description,
- selected,
- userProvidesKey,
- ...rest
-}) => {
- const modularChat = useRecoilValue(store.modularChat);
- const [isDialogOpen, setDialogOpen] = useState(false);
- const { data: endpointsConfig } = useGetEndpointsQuery();
- const { conversation, newConversation } = useChatContext();
- const getDefaultConversation = useDefaultConvo();
-
- const { getExpiry } = useUserKey(endpoint);
- const localize = useLocalize();
- const expiryTime = getExpiry() ?? '';
-
- const onSelectEndpoint = (newEndpoint?: EModelEndpoint) => {
- if (!newEndpoint) {
- return;
- }
-
- if (!expiryTime) {
- setDialogOpen(true);
- }
-
- const {
- template,
- shouldSwitch,
- isNewModular,
- newEndpointType,
- isCurrentModular,
- isExistingConversation,
- } = getConvoSwitchLogic({
- newEndpoint,
- modularChat,
- conversation,
- endpointsConfig,
- });
-
- const isModular = isCurrentModular && isNewModular && shouldSwitch;
- if (isExistingConversation && isModular) {
- template.endpointType = newEndpointType;
-
- const currentConvo = getDefaultConversation({
- /* target endpointType is necessary to avoid endpoint mixing */
- conversation: { ...(conversation ?? {}), endpointType: template.endpointType },
- preset: template,
- });
-
- /* We don't reset the latest message, only when changing settings mid-converstion */
- newConversation({
- template: currentConvo,
- preset: currentConvo,
- keepLatestMessage: true,
- keepAddedConvos: true,
- });
- return;
- }
- newConversation({
- template: { ...(template as Partial<TConversation>) },
- keepAddedConvos: isModular,
- });
- };
-
- const endpointType = getEndpointField(endpointsConfig, endpoint, 'type');
- const iconKey = getIconKey({ endpoint, endpointsConfig, endpointType });
- const Icon = icons[iconKey];
-
- return (
- <>
- <div
- role="option"
- aria-selected={selected}
- className={cn(
- 'group m-1.5 flex max-h-[40px] cursor-pointer gap-2 rounded px-5 py-2.5 !pr-3 text-sm !opacity-100 hover:bg-surface-hover',
- 'radix-disabled:pointer-events-none radix-disabled:opacity-50',
- )}
- tabIndex={0}
- {...rest}
- onClick={() => onSelectEndpoint(endpoint)}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- onSelectEndpoint(endpoint);
- }
- }}
- >
- <div className="flex grow items-center justify-between gap-2">
- <div>
- <div className="flex items-center gap-2">
- {Icon != null && (
- <Icon
- size={18}
- endpoint={endpoint}
- context={'menu-item'}
- className="icon-md shrink-0 dark:text-white"
- iconURL={getEndpointField(endpointsConfig, endpoint, 'iconURL')}
- />
- )}
- <div>
- {title}
- <div className="text-token-text-tertiary">{description}</div>
- </div>
- </div>
- </div>
- <div className="flex items-center gap-2">
- {userProvidesKey ? (
- <div className="text-token-text-primary" key={`set-key-${endpoint}`}>
- <button
- tabIndex={0}
- aria-label={`${localize('com_endpoint_config_key')} for ${title}`}
- className={cn(
- 'invisible flex gap-x-1 group-focus-within:visible group-hover:visible',
- selected ? 'visible' : '',
- expiryTime ? 'text-token-text-primary w-full rounded-lg p-2' : '',
- )}
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDialogOpen(true);
- }}
- onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- e.stopPropagation();
- setDialogOpen(true);
- }
- }}
- >
- <div
- className={cn(
- 'invisible group-focus-within:visible group-hover:visible',
- expiryTime ? 'text-xs' : '',
- )}
- >
- {localize('com_endpoint_config_key')}
- </div>
- <Settings className={cn(expiryTime ? 'icon-sm' : 'icon-md stroke-1')} />
- </button>
- </div>
- ) : null}
- {selected && (
- <svg
- width="24"
- height="24"
- viewBox="0 0 24 24"
- fill="none"
- xmlns="http://www.w3.org/2000/svg"
- className="icon-md block group-hover:hidden"
- >
- <path
- fillRule="evenodd"
- clipRule="evenodd"
- d="M2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12ZM16.0755 7.93219C16.5272 8.25003 16.6356 8.87383 16.3178 9.32549L11.5678 16.0755C11.3931 16.3237 11.1152 16.4792 10.8123 16.4981C10.5093 16.517 10.2142 16.3973 10.0101 16.1727L7.51006 13.4227C7.13855 13.014 7.16867 12.3816 7.57733 12.0101C7.98598 11.6386 8.61843 11.6687 8.98994 12.0773L10.6504 13.9039L14.6822 8.17451C15 7.72284 15.6238 7.61436 16.0755 7.93219Z"
- fill="currentColor"
- />
- </svg>
- )}
- {(!userProvidesKey || expiryTime) && (
- <div className="text-token-text-primary hidden gap-x-1 group-hover:flex ">
- {!userProvidesKey && <div className="">{localize('com_ui_new_chat')}</div>}
- <svg
- width="24"
- height="24"
- viewBox="0 0 24 24"
- fill="none"
- xmlns="http://www.w3.org/2000/svg"
- className="icon-md"
- >
- <path
- fillRule="evenodd"
- clipRule="evenodd"
- d="M16.7929 2.79289C18.0118 1.57394 19.9882 1.57394 21.2071 2.79289C22.4261 4.01184 22.4261 5.98815 21.2071 7.20711L12.7071 15.7071C12.5196 15.8946 12.2652 16 12 16H9C8.44772 16 8 15.5523 8 15V12C8 11.7348 8.10536 11.4804 8.29289 11.2929L16.7929 2.79289ZM19.7929 4.20711C19.355 3.7692 18.645 3.7692 18.2071 4.2071L10 12.4142V14H11.5858L19.7929 5.79289C20.2308 5.35499 20.2308 4.64501 19.7929 4.20711ZM6 5C5.44772 5 5 5.44771 5 6V18C5 18.5523 5.44772 19 6 19H18C18.5523 19 19 18.5523 19 18V14C19 13.4477 19.4477 13 20 13C20.5523 13 21 13.4477 21 14V18C21 19.6569 19.6569 21 18 21H6C4.34315 21 3 19.6569 3 18V6C3 4.34314 4.34315 3 6 3H10C10.5523 3 11 3.44771 11 4C11 4.55228 10.5523 5 10 5H6Z"
- fill="currentColor"
- />
- </svg>
- </div>
- )}
- </div>
- </div>
- </div>
- {userProvidesKey && (
- <SetKeyDialog
- open={isDialogOpen}
- endpoint={endpoint}
- endpointType={endpointType}
- onOpenChange={setDialogOpen}
- userProvideURL={getEndpointField(endpointsConfig, endpoint, 'userProvideURL')}
- />
- )}
- </>
- );
-};
-
-export default MenuItem;
diff --git a/client/src/components/Chat/Menus/Endpoints/MenuItems.tsx b/client/src/components/Chat/Menus/Endpoints/MenuItems.tsx
deleted file mode 100644
index 28fb167f18..0000000000
--- a/client/src/components/Chat/Menus/Endpoints/MenuItems.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-import type { FC } from 'react';
-import { Close } from '@radix-ui/react-popover';
-import {
- EModelEndpoint,
- alternateName,
- PermissionTypes,
- Permissions,
-} from 'librechat-data-provider';
-import { useGetEndpointsQuery } from '~/data-provider';
-import MenuSeparator from '../UI/MenuSeparator';
-import { getEndpointField } from '~/utils';
-import { useHasAccess } from '~/hooks';
-import MenuItem from './MenuItem';
-
-const EndpointItems: FC<{
- endpoints: Array<EModelEndpoint | undefined>;
- selected: EModelEndpoint | '';
-}> = ({ endpoints = [], selected }) => {
- const hasAccessToAgents = useHasAccess({
- permissionType: PermissionTypes.AGENTS,
- permission: Permissions.USE,
- });
- const { data: endpointsConfig } = useGetEndpointsQuery();
- return (
- <>
- {endpoints.map((endpoint, i) => {
- if (!endpoint) {
- return null;
- } else if (!endpointsConfig?.[endpoint]) {
- return null;
- }
-
- if (endpoint === EModelEndpoint.agents && !hasAccessToAgents) {
- return null;
- }
- const userProvidesKey: boolean | null | undefined =
- getEndpointField(endpointsConfig, endpoint, 'userProvide') ?? false;
- return (
- <Close asChild key={`endpoint-${endpoint}`}>
- <div key={`endpoint-${endpoint}`}>
- <MenuItem
- key={`endpoint-item-${endpoint}`}
- title={alternateName[endpoint] || endpoint}
- value={endpoint}
- selected={selected === endpoint}
- data-testid={`endpoint-item-${endpoint}`}
- userProvidesKey={!!userProvidesKey}
- // description="With DALL·E, browsing and analysis"
- />
- {i !== endpoints.length - 1 && <MenuSeparator />}
- </div>
- </Close>
- );
- })}
- </>
- );
-};
-
-export default EndpointItems;
diff --git a/client/src/components/Chat/Menus/Endpoints/ModelSelector.tsx b/client/src/components/Chat/Menus/Endpoints/ModelSelector.tsx
new file mode 100644
index 0000000000..7d94aea83a
--- /dev/null
+++ b/client/src/components/Chat/Menus/Endpoints/ModelSelector.tsx
@@ -0,0 +1,95 @@
+import React from 'react';
+import type { ModelSelectorProps } from '~/common';
+import { ModelSelectorProvider, useModelSelectorContext } from './ModelSelectorContext';
+import { renderModelSpecs, renderEndpoints, renderSearchResults } from './components';
+import { CustomMenu as Menu } from './CustomMenu';
+import DialogManager from './DialogManager';
+import { getSelectedIcon } from './utils';
+import { useLocalize } from '~/hooks';
+
+function ModelSelectorContent() {
+ const localize = useLocalize();
+
+ const {
+ // LibreChat
+ modelSpecs,
+ mappedEndpoints,
+ endpointsConfig,
+ // State
+ searchValue,
+ searchResults,
+ selectedValues,
+
+ // Functions
+ setSearchValue,
+ getDisplayValue,
+ setSelectedValues,
+ // Dialog
+ keyDialogOpen,
+ onOpenChange,
+ keyDialogEndpoint,
+ } = useModelSelectorContext();
+
+ const selectedIcon = getSelectedIcon({
+ mappedEndpoints: mappedEndpoints ?? [],
+ selectedValues,
+ modelSpecs,
+ endpointsConfig,
+ });
+ const selectedDisplayValue = getDisplayValue();
+
+ const trigger = (
+ <button
+ className="my-1 flex h-10 w-full max-w-[70vw] items-center justify-center gap-2 rounded-xl border border-border-light bg-surface-secondary px-3 py-2 text-sm text-text-primary hover:bg-surface-tertiary focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-white"
+ aria-label={localize('com_endpoint_select_model')}
+ >
+ {selectedIcon && React.isValidElement(selectedIcon) && (
+ <div className="flex flex-shrink-0 items-center justify-center overflow-hidden">
+ {selectedIcon}
+ </div>
+ )}
+ <span className="flex-grow truncate text-left">{selectedDisplayValue}</span>
+ </button>
+ );
+
+ return (
+ <div className="relative flex w-full max-w-md flex-col items-center gap-2">
+ <Menu
+ values={selectedValues}
+ onValuesChange={(values: Record<string, any>) => {
+ setSelectedValues({
+ endpoint: values.endpoint || '',
+ model: values.model || '',
+ modelSpec: values.modelSpec || '',
+ });
+ }}
+ onSearch={(value) => setSearchValue(value)}
+ combobox={<input placeholder={localize('com_endpoint_search_models')} />}
+ trigger={trigger}
+ >
+ {searchResults ? (
+ renderSearchResults(searchResults, localize, searchValue)
+ ) : (
+ <>
+ {renderModelSpecs(modelSpecs, selectedValues.modelSpec || '')}
+ {renderEndpoints(mappedEndpoints ?? [])}
+ </>
+ )}
+ </Menu>
+ <DialogManager
+ keyDialogOpen={keyDialogOpen}
+ onOpenChange={onOpenChange}
+ endpointsConfig={endpointsConfig || {}}
+ keyDialogEndpoint={keyDialogEndpoint || undefined}
+ />
+ </div>
+ );
+}
+
+export default function ModelSelector({ interfaceConfig, modelSpecs }: ModelSelectorProps) {
+ return (
+ <ModelSelectorProvider modelSpecs={modelSpecs} interfaceConfig={interfaceConfig}>
+ <ModelSelectorContent />
+ </ModelSelectorProvider>
+ );
+}
diff --git a/client/src/components/Chat/Menus/Endpoints/ModelSelectorContext.tsx b/client/src/components/Chat/Menus/Endpoints/ModelSelectorContext.tsx
new file mode 100644
index 0000000000..3306e2f407
--- /dev/null
+++ b/client/src/components/Chat/Menus/Endpoints/ModelSelectorContext.tsx
@@ -0,0 +1,224 @@
+import React, { startTransition, createContext, useContext, useState, useMemo } from 'react';
+import { EModelEndpoint, isAgentsEndpoint, isAssistantsEndpoint } from 'librechat-data-provider';
+import type * as t from 'librechat-data-provider';
+import type { Endpoint, SelectedValues } from '~/common';
+import { useAgentsMapContext, useAssistantsMapContext, useChatContext } from '~/Providers';
+import { useEndpoints, useSelectorEffects, useKeyDialog, useLocalize } from '~/hooks';
+import useSelectMention from '~/hooks/Input/useSelectMention';
+import { useGetEndpointsQuery } from '~/data-provider';
+import { filterItems } from './utils';
+
+type ModelSelectorContextType = {
+ // State
+ searchValue: string;
+ selectedValues: SelectedValues;
+ endpointSearchValues: Record<string, string>;
+ searchResults: (t.TModelSpec | Endpoint)[] | null;
+ // LibreChat
+ modelSpecs: t.TModelSpec[];
+ mappedEndpoints: Endpoint[];
+ agentsMap: t.TAgentsMap | undefined;
+ assistantsMap: t.TAssistantsMap | undefined;
+ endpointsConfig: t.TEndpointsConfig;
+
+ // Functions
+ getDisplayValue: () => string;
+ endpointRequiresUserKey: (endpoint: string) => boolean;
+ setSelectedValues: React.Dispatch<React.SetStateAction<SelectedValues>>;
+ setSearchValue: (value: string) => void;
+ setEndpointSearchValue: (endpoint: string, value: string) => void;
+ handleSelectSpec: (spec: t.TModelSpec) => void;
+ handleSelectEndpoint: (endpoint: Endpoint) => void;
+ handleSelectModel: (endpoint: Endpoint, model: string) => void;
+} & ReturnType<typeof useKeyDialog>;
+
+const ModelSelectorContext = createContext<ModelSelectorContextType | undefined>(undefined);
+
+export function useModelSelectorContext() {
+ const context = useContext(ModelSelectorContext);
+ if (context === undefined) {
+ throw new Error('useModelSelectorContext must be used within a ModelSelectorProvider');
+ }
+ return context;
+}
+
+interface ModelSelectorProviderProps {
+ children: React.ReactNode;
+ modelSpecs: t.TModelSpec[];
+ interfaceConfig: t.TInterfaceConfig;
+}
+
+export function ModelSelectorProvider({
+ children,
+ modelSpecs,
+ interfaceConfig,
+}: ModelSelectorProviderProps) {
+ const localize = useLocalize();
+ const agentsMap = useAgentsMapContext();
+ const assistantsMap = useAssistantsMapContext();
+ const { data: endpointsConfig } = useGetEndpointsQuery();
+ const { conversation, newConversation } = useChatContext();
+ const { mappedEndpoints, endpointRequiresUserKey } = useEndpoints({
+ agentsMap,
+ assistantsMap,
+ endpointsConfig,
+ interfaceConfig,
+ });
+ const { onSelectEndpoint, onSelectSpec } = useSelectMention({
+ // presets,
+ modelSpecs,
+ assistantsMap,
+ endpointsConfig,
+ newConversation,
+ returnHandlers: true,
+ });
+
+ // State
+ const [selectedValues, setSelectedValues] = useState<SelectedValues>({
+ endpoint: conversation?.endpoint || '',
+ model: conversation?.model || '',
+ modelSpec: conversation?.spec || '',
+ });
+ useSelectorEffects({
+ agentsMap,
+ conversation,
+ assistantsMap,
+ setSelectedValues,
+ });
+
+ const [searchValue, setSearchValueState] = useState('');
+ const [endpointSearchValues, setEndpointSearchValues] = useState<Record<string, string>>({});
+
+ const keyProps = useKeyDialog();
+
+ // Memoized search results
+ const searchResults = useMemo(() => {
+ if (!searchValue) {
+ return null;
+ }
+ const allItems = [...modelSpecs, ...mappedEndpoints];
+ return filterItems(allItems, searchValue, agentsMap, assistantsMap || {});
+ }, [searchValue, modelSpecs, mappedEndpoints, agentsMap, assistantsMap]);
+
+ // Functions
+ const setSearchValue = (value: string) => {
+ startTransition(() => setSearchValueState(value));
+ };
+
+ const setEndpointSearchValue = (endpoint: string, value: string) => {
+ setEndpointSearchValues((prev) => ({
+ ...prev,
+ [endpoint]: value,
+ }));
+ };
+
+ const handleSelectSpec = (spec: t.TModelSpec) => {
+ onSelectSpec?.(spec);
+ setSelectedValues({
+ endpoint: spec.preset.endpoint,
+ model: spec.preset.model ?? null,
+ modelSpec: spec.name,
+ });
+ };
+
+ const handleSelectEndpoint = (endpoint: Endpoint) => {
+ if (!endpoint.hasModels) {
+ if (endpoint.value) {
+ onSelectEndpoint?.(endpoint.value);
+ }
+ setSelectedValues({
+ endpoint: endpoint.value,
+ model: '',
+ modelSpec: '',
+ });
+ }
+ };
+
+ const handleSelectModel = (endpoint: Endpoint, model: string) => {
+ if (isAgentsEndpoint(endpoint.value)) {
+ onSelectEndpoint?.(endpoint.value, {
+ agent_id: model,
+ });
+ } else if (isAssistantsEndpoint(endpoint.value)) {
+ onSelectEndpoint?.(endpoint.value, {
+ assistant_id: model,
+ model: assistantsMap?.[endpoint.value]?.[model]?.model ?? '',
+ });
+ } else if (endpoint.value) {
+ onSelectEndpoint?.(endpoint.value, { model });
+ }
+ setSelectedValues({
+ endpoint: endpoint.value,
+ model: model,
+ modelSpec: '',
+ });
+ };
+
+ const getDisplayValue = () => {
+ if (selectedValues.modelSpec) {
+ const spec = modelSpecs.find((s) => s.name === selectedValues.modelSpec);
+ return spec?.label || localize('com_endpoint_select_model');
+ }
+
+ if (selectedValues.model && selectedValues.endpoint) {
+ const endpoint = mappedEndpoints.find((e) => e.value === selectedValues.endpoint);
+ if (!endpoint) {
+ return localize('com_endpoint_select_model');
+ }
+
+ if (
+ endpoint.value === EModelEndpoint.agents &&
+ endpoint.agentNames &&
+ endpoint.agentNames[selectedValues.model]
+ ) {
+ return endpoint.agentNames[selectedValues.model];
+ }
+
+ if (
+ (endpoint.value === EModelEndpoint.assistants ||
+ endpoint.value === EModelEndpoint.azureAssistants) &&
+ endpoint.assistantNames &&
+ endpoint.assistantNames[selectedValues.model]
+ ) {
+ return endpoint.assistantNames[selectedValues.model];
+ }
+
+ return selectedValues.model;
+ }
+
+ if (selectedValues.endpoint) {
+ const endpoint = mappedEndpoints.find((e) => e.value === selectedValues.endpoint);
+ return endpoint?.label || localize('com_endpoint_select_model');
+ }
+
+ return localize('com_endpoint_select_model');
+ };
+
+ const value = {
+ // State
+ searchValue,
+ searchResults,
+ selectedValues,
+ endpointSearchValues,
+ // LibreChat
+ agentsMap,
+ modelSpecs,
+ assistantsMap,
+ mappedEndpoints,
+ endpointsConfig,
+
+ // Functions
+ setSearchValue,
+ getDisplayValue,
+ handleSelectSpec,
+ handleSelectModel,
+ setSelectedValues,
+ handleSelectEndpoint,
+ setEndpointSearchValue,
+ endpointRequiresUserKey,
+ // Dialog
+ ...keyProps,
+ };
+
+ return <ModelSelectorContext.Provider value={value}>{children}</ModelSelectorContext.Provider>;
+}
diff --git a/client/src/components/Chat/Menus/Endpoints/components/EndpointItem.tsx b/client/src/components/Chat/Menus/Endpoints/components/EndpointItem.tsx
new file mode 100644
index 0000000000..a064ec52b5
--- /dev/null
+++ b/client/src/components/Chat/Menus/Endpoints/components/EndpointItem.tsx
@@ -0,0 +1,174 @@
+import { useMemo } from 'react';
+import { SettingsIcon } from 'lucide-react';
+import { Spinner } from '~/components';
+import { EModelEndpoint, isAgentsEndpoint, isAssistantsEndpoint } from 'librechat-data-provider';
+import type { Endpoint } from '~/common';
+import { CustomMenu as Menu, CustomMenuItem as MenuItem } from '../CustomMenu';
+import { useModelSelectorContext } from '../ModelSelectorContext';
+import { renderEndpointModels } from './EndpointModelItem';
+import { filterModels } from '../utils';
+import { useLocalize } from '~/hooks';
+import { cn } from '~/utils';
+
+interface EndpointItemProps {
+ endpoint: Endpoint;
+}
+
+const SettingsButton = ({
+ endpoint,
+ className,
+ handleOpenKeyDialog,
+}: {
+ endpoint: Endpoint;
+ className?: string;
+ handleOpenKeyDialog: (endpoint: EModelEndpoint, e: React.MouseEvent) => void;
+}) => {
+ const localize = useLocalize();
+ const text = localize('com_endpoint_config_key');
+ return (
+ <button
+ id={`endpoint-${endpoint.value}-settings`}
+ onClick={(e) => {
+ if (!endpoint.value) {
+ return;
+ }
+ e.stopPropagation();
+ handleOpenKeyDialog(endpoint.value as EModelEndpoint, e);
+ }}
+ className={cn(
+ 'flex items-center overflow-visible text-text-primary transition-all duration-300 ease-in-out',
+ 'group/button rounded-md px-1 hover:bg-surface-secondary focus:bg-surface-secondary',
+ className,
+ )}
+ aria-label={`${text} ${endpoint.label}`}
+ >
+ <div className="flex w-[28px] items-center gap-1 whitespace-nowrap transition-all duration-300 ease-in-out group-hover:w-auto group-focus/button:w-auto">
+ <SettingsIcon className="h-4 w-4 flex-shrink-0" />
+ <span className="max-w-0 overflow-hidden whitespace-nowrap opacity-0 transition-all duration-300 ease-in-out group-hover:max-w-[100px] group-hover:opacity-100 group-focus/button:max-w-[100px] group-focus/button:opacity-100">
+ {text}
+ </span>
+ </div>
+ </button>
+ );
+};
+
+export function EndpointItem({ endpoint }: EndpointItemProps) {
+ const localize = useLocalize();
+ const {
+ agentsMap,
+ assistantsMap,
+ selectedValues,
+ handleOpenKeyDialog,
+ handleSelectEndpoint,
+ endpointSearchValues,
+ setEndpointSearchValue,
+ endpointRequiresUserKey,
+ } = useModelSelectorContext();
+ const { model: selectedModel, endpoint: selectedEndpoint } = selectedValues;
+
+ const searchValue = endpointSearchValues[endpoint.value] || '';
+ const isUserProvided = useMemo(() => endpointRequiresUserKey(endpoint.value), [endpoint.value]);
+
+ const renderIconLabel = () => (
+ <div className="flex items-center gap-2">
+ {endpoint.icon && (
+ <div className="flex flex-shrink-0 items-center justify-center overflow-hidden">
+ {endpoint.icon}
+ </div>
+ )}
+ <span
+ className={cn(
+ 'truncate text-left',
+ isUserProvided ? 'group-hover:w-24 group-focus:w-24' : '',
+ )}
+ >
+ {endpoint.label}
+ </span>
+ </div>
+ );
+
+ if (endpoint.hasModels) {
+ const filteredModels = searchValue
+ ? filterModels(endpoint, endpoint.models || [], searchValue, agentsMap, assistantsMap)
+ : null;
+ const placeholder =
+ isAgentsEndpoint(endpoint.value) || isAssistantsEndpoint(endpoint.value)
+ ? localize('com_endpoint_search_var', { 0: endpoint.label })
+ : localize('com_endpoint_search_endpoint_models', { 0: endpoint.label });
+ return (
+ <Menu
+ id={`endpoint-${endpoint.value}-menu`}
+ key={`endpoint-${endpoint.value}-item`}
+ className="transition-opacity duration-200 ease-in-out"
+ defaultOpen={endpoint.value === selectedEndpoint}
+ searchValue={searchValue}
+ onSearch={(value) => setEndpointSearchValue(endpoint.value, value)}
+ combobox={<input placeholder={placeholder} />}
+ label={
+ <div
+ onClick={() => handleSelectEndpoint(endpoint)}
+ className="group flex w-full flex-shrink cursor-pointer items-center justify-between rounded-xl px-1 py-1 text-sm"
+ >
+ {renderIconLabel()}
+ {isUserProvided && (
+ <SettingsButton endpoint={endpoint} handleOpenKeyDialog={handleOpenKeyDialog} />
+ )}
+ </div>
+ }
+ >
+ {(endpoint.value === EModelEndpoint.assistants ||
+ endpoint.value === EModelEndpoint.azureAssistants) &&
+ endpoint.models === undefined ? (
+ <div className="flex items-center justify-center p-2">
+ <Spinner />
+ </div>
+ ) : filteredModels ? (
+ renderEndpointModels(endpoint, endpoint.models || [], selectedModel, filteredModels)
+ ) : (
+ endpoint.models && renderEndpointModels(endpoint, endpoint.models, selectedModel)
+ )}
+ </Menu>
+ );
+ } else {
+ return (
+ <MenuItem
+ id={`endpoint-${endpoint.value}-menu`}
+ key={`endpoint-${endpoint.value}-item`}
+ onClick={() => handleSelectEndpoint(endpoint)}
+ className="flex h-8 w-full cursor-pointer items-center justify-between rounded-xl px-3 py-2 text-sm"
+ >
+ <div className="group flex w-full min-w-0 items-center justify-between">
+ {renderIconLabel()}
+ <div className="flex items-center gap-2">
+ {endpointRequiresUserKey(endpoint.value) && (
+ <SettingsButton endpoint={endpoint} handleOpenKeyDialog={handleOpenKeyDialog} />
+ )}
+ {selectedEndpoint === endpoint.value && (
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ className="block"
+ >
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12ZM16.0755 7.93219C16.5272 8.25003 16.6356 8.87383 16.3178 9.32549L11.5678 16.0755C11.3931 16.3237 11.1152 16.4792 10.8123 16.4981C10.5093 16.517 10.2142 16.3973 10.0101 16.1727L7.51006 13.4227C7.13855 13.014 7.16867 12.3816 7.57733 12.0101C7.98598 11.6386 8.61843 11.6687 8.98994 12.0773L10.6504 13.9039L14.6822 8.17451C15 7.72284 15.6238 7.61436 16.0755 7.93219Z"
+ fill="currentColor"
+ />
+ </svg>
+ )}
+ </div>
+ </div>
+ </MenuItem>
+ );
+ }
+}
+
+export function renderEndpoints(mappedEndpoints: Endpoint[]) {
+ return mappedEndpoints.map((endpoint) => (
+ <EndpointItem endpoint={endpoint} key={`endpoint-${endpoint.value}-item`} />
+ ));
+}
diff --git a/client/src/components/Chat/Menus/Endpoints/components/EndpointModelItem.tsx b/client/src/components/Chat/Menus/Endpoints/components/EndpointModelItem.tsx
new file mode 100644
index 0000000000..cd7c66bb01
--- /dev/null
+++ b/client/src/components/Chat/Menus/Endpoints/components/EndpointModelItem.tsx
@@ -0,0 +1,97 @@
+import React from 'react';
+import { EModelEndpoint } from 'librechat-data-provider';
+import type { Endpoint } from '~/common';
+import { useModelSelectorContext } from '../ModelSelectorContext';
+import { CustomMenuItem as MenuItem } from '../CustomMenu';
+
+interface EndpointModelItemProps {
+ modelId: string | null;
+ endpoint: Endpoint;
+ isSelected: boolean;
+}
+
+export function EndpointModelItem({ modelId, endpoint, isSelected }: EndpointModelItemProps) {
+ const { handleSelectModel } = useModelSelectorContext();
+ let modelName = modelId;
+ const avatarUrl = endpoint?.modelIcons?.[modelId ?? ''] || null;
+
+ // Use custom names if available
+ if (
+ endpoint &&
+ modelId &&
+ endpoint.value === EModelEndpoint.agents &&
+ endpoint.agentNames?.[modelId]
+ ) {
+ modelName = endpoint.agentNames[modelId];
+ } else if (
+ endpoint &&
+ modelId &&
+ (endpoint.value === EModelEndpoint.assistants ||
+ endpoint.value === EModelEndpoint.azureAssistants) &&
+ endpoint.assistantNames?.[modelId]
+ ) {
+ modelName = endpoint.assistantNames[modelId];
+ }
+
+ return (
+ <MenuItem
+ key={modelId}
+ onClick={() => handleSelectModel(endpoint, modelId ?? '')}
+ className="flex h-8 w-full cursor-pointer items-center justify-start rounded-lg px-3 py-2 text-sm"
+ >
+ <div className="flex items-center gap-2">
+ {avatarUrl ? (
+ <div className="flex h-5 w-5 items-center justify-center overflow-hidden rounded-full">
+ <img src={avatarUrl} alt={modelName ?? ''} className="h-full w-full object-cover" />
+ </div>
+ ) : (endpoint.value === EModelEndpoint.agents ||
+ endpoint.value === EModelEndpoint.assistants ||
+ endpoint.value === EModelEndpoint.azureAssistants) &&
+ endpoint.icon ? (
+ <div className="flex h-5 w-5 items-center justify-center overflow-hidden rounded-full">
+ {endpoint.icon}
+ </div>
+ ) : null}
+ <span>{modelName}</span>
+ </div>
+ {isSelected && (
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ className="ml-auto block"
+ >
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12ZM16.0755 7.93219C16.5272 8.25003 16.6356 8.87383 16.3178 9.32549L11.5678 16.0755C11.3931 16.3237 11.1152 16.4792 10.8123 16.4981C10.5093 16.517 10.2142 16.3973 10.0101 16.1727L7.51006 13.4227C7.13855 13.014 7.16867 12.3816 7.57733 12.0101C7.98598 11.6386 8.61843 11.6687 8.98994 12.0773L10.6504 13.9039L14.6822 8.17451C15 7.72284 15.6238 7.61436 16.0755 7.93219Z"
+ fill="currentColor"
+ />
+ </svg>
+ )}
+ </MenuItem>
+ );
+}
+
+export function renderEndpointModels(
+ endpoint: Endpoint | null,
+ models: string[],
+ selectedModel: string | null,
+ filteredModels?: string[],
+) {
+ const modelsToRender = filteredModels || models;
+
+ return modelsToRender.map(
+ (modelId) =>
+ endpoint && (
+ <EndpointModelItem
+ key={modelId}
+ modelId={modelId}
+ endpoint={endpoint}
+ isSelected={selectedModel === modelId}
+ />
+ ),
+ );
+}
diff --git a/client/src/components/Chat/Menus/Endpoints/components/ModelSpecItem.tsx b/client/src/components/Chat/Menus/Endpoints/components/ModelSpecItem.tsx
new file mode 100644
index 0000000000..ea2e26b54c
--- /dev/null
+++ b/client/src/components/Chat/Menus/Endpoints/components/ModelSpecItem.tsx
@@ -0,0 +1,74 @@
+import React from 'react';
+import type { TModelSpec } from 'librechat-data-provider';
+import { CustomMenuItem as MenuItem } from '../CustomMenu';
+import { useModelSelectorContext } from '../ModelSelectorContext';
+import SpecIcon from './SpecIcon';
+import { cn } from '~/utils';
+
+interface ModelSpecItemProps {
+ spec: TModelSpec;
+ isSelected: boolean;
+}
+
+export function ModelSpecItem({ spec, isSelected }: ModelSpecItemProps) {
+ const { handleSelectSpec, endpointsConfig } = useModelSelectorContext();
+ const { showIconInMenu = true } = spec;
+ return (
+ <MenuItem
+ key={spec.name}
+ onClick={() => handleSelectSpec(spec)}
+ className={cn(
+ 'flex w-full cursor-pointer justify-between rounded-lg px-2 text-sm',
+ spec.description ? 'items-start' : 'items-center',
+ )}
+ >
+ <div
+ className={cn(
+ 'flex w-full min-w-0 gap-2 px-1 py-1',
+ spec.description ? 'items-start' : 'items-center',
+ )}
+ >
+ {showIconInMenu && (
+ <div className="flex-shrink-0">
+ <SpecIcon currentSpec={spec} endpointsConfig={endpointsConfig} />
+ </div>
+ )}
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="truncate text-left">{spec.label}</span>
+ {spec.description && (
+ <span className="break-words text-xs font-normal">{spec.description}</span>
+ )}
+ </div>
+ </div>
+ {isSelected && (
+ <div className={cn('flex-shrink-0', spec.description ? 'pt-1' : '')}>
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ className="block"
+ >
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12ZM16.0755 7.93219C16.5272 8.25003 16.6356 8.87383 16.3178 9.32549L11.5678 16.0755C11.3931 16.3237 11.1152 16.4792 10.8123 16.4981C10.5093 16.517 10.2142 16.3973 10.0101 16.1727L7.51006 13.4227C7.13855 13.014 7.16867 12.3816 7.57733 12.0101C7.98598 11.6386 8.61843 11.6687 8.98994 12.0773L10.6504 13.9039L14.6822 8.17451C15 7.72284 15.6238 7.61436 16.0755 7.93219Z"
+ fill="currentColor"
+ />
+ </svg>
+ </div>
+ )}
+ </MenuItem>
+ );
+}
+
+export function renderModelSpecs(specs: TModelSpec[], selectedSpec: string) {
+ if (!specs || specs.length === 0) {
+ return null;
+ }
+
+ return specs.map((spec) => (
+ <ModelSpecItem key={spec.name} spec={spec} isSelected={selectedSpec === spec.name} />
+ ));
+}
diff --git a/client/src/components/Chat/Menus/Endpoints/components/SearchResults.tsx b/client/src/components/Chat/Menus/Endpoints/components/SearchResults.tsx
new file mode 100644
index 0000000000..185073b007
--- /dev/null
+++ b/client/src/components/Chat/Menus/Endpoints/components/SearchResults.tsx
@@ -0,0 +1,253 @@
+import React, { Fragment } from 'react';
+import { EModelEndpoint } from 'librechat-data-provider';
+import type { TModelSpec } from 'librechat-data-provider';
+import type { Endpoint } from '~/common';
+import { useModelSelectorContext } from '../ModelSelectorContext';
+import { CustomMenuItem as MenuItem } from '../CustomMenu';
+import SpecIcon from './SpecIcon';
+import { cn } from '~/utils';
+
+interface SearchResultsProps {
+ results: (TModelSpec | Endpoint)[] | null;
+ localize: (phraseKey: any, options?: any) => string;
+ searchValue: string;
+}
+
+export function SearchResults({ results, localize, searchValue }: SearchResultsProps) {
+ const {
+ selectedValues,
+ handleSelectSpec,
+ handleSelectModel,
+ handleSelectEndpoint,
+ endpointsConfig,
+ agentsMap,
+ assistantsMap,
+ } = useModelSelectorContext();
+
+ const {
+ modelSpec: selectedSpec,
+ endpoint: selectedEndpoint,
+ model: selectedModel,
+ } = selectedValues;
+
+ if (!results) {
+ return null;
+ }
+ if (!results.length) {
+ return (
+ <div className="cursor-default p-2 sm:py-1 sm:text-sm">
+ {localize('com_files_no_results')}
+ </div>
+ );
+ }
+
+ return (
+ <>
+ {results.map((item, i) => {
+ if ('name' in item && 'label' in item) {
+ // Render model spec
+ const spec = item as TModelSpec;
+ return (
+ <MenuItem
+ key={spec.name}
+ onClick={() => handleSelectSpec(spec)}
+ className={cn(
+ 'flex w-full cursor-pointer justify-between rounded-lg px-2 text-sm',
+ spec.description ? 'items-start' : 'items-center',
+ )}
+ >
+ <div
+ className={cn(
+ 'flex w-full min-w-0 gap-2 px-1 py-1',
+ spec.description ? 'items-start' : 'items-center',
+ )}
+ >
+ {(spec.showIconInMenu ?? true) && (
+ <div className="flex-shrink-0">
+ <SpecIcon currentSpec={spec} endpointsConfig={endpointsConfig} />
+ </div>
+ )}
+ <div className="flex min-w-0 flex-col gap-1">
+ <span className="truncate text-left">{spec.label}</span>
+ {spec.description && (
+ <span className="break-words text-xs font-normal">{spec.description}</span>
+ )}
+ </div>
+ </div>
+ {selectedSpec === spec.name && (
+ <div className={cn('flex-shrink-0', spec.description ? 'pt-1' : '')}>
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ className="block"
+ >
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12ZM16.0755 7.93219C16.5272 8.25003 16.6356 8.87383 16.3178 9.32549L11.5678 16.0755C11.3931 16.3237 11.1152 16.4792 10.8123 16.4981C10.5093 16.517 10.2142 16.3973 10.0101 16.1727L7.51006 13.4227C7.13855 13.014 7.16867 12.3816 7.57733 12.0101C7.98598 11.6386 8.61843 11.6687 8.98994 12.0773L10.6504 13.9039L14.6822 8.17451C15 7.72284 15.6238 7.61436 16.0755 7.93219Z"
+ fill="currentColor"
+ />
+ </svg>
+ </div>
+ )}
+ </MenuItem>
+ );
+ } else {
+ // For an endpoint item
+ const endpoint = item as Endpoint;
+ if (endpoint.hasModels && endpoint.models && endpoint.models.length > 0) {
+ const lowerQuery = searchValue.toLowerCase();
+ const filteredModels = endpoint.label.toLowerCase().includes(lowerQuery)
+ ? endpoint.models
+ : endpoint.models.filter((modelId) => {
+ let modelName = modelId;
+ if (
+ endpoint.value === EModelEndpoint.agents &&
+ endpoint.agentNames &&
+ endpoint.agentNames[modelId]
+ ) {
+ modelName = endpoint.agentNames[modelId];
+ } else if (
+ (endpoint.value === EModelEndpoint.assistants ||
+ endpoint.value === EModelEndpoint.azureAssistants) &&
+ endpoint.assistantNames &&
+ endpoint.assistantNames[modelId]
+ ) {
+ modelName = endpoint.assistantNames[modelId];
+ }
+ return modelName.toLowerCase().includes(lowerQuery);
+ });
+
+ if (!filteredModels.length) {
+ return null; // skip if no models match
+ }
+
+ return (
+ <Fragment key={`endpoint-${endpoint.value}-search-${i}`}>
+ <div className="flex items-center gap-2 px-3 py-1 text-sm font-medium">
+ {endpoint.icon && (
+ <div className="flex items-center justify-center overflow-hidden rounded-full p-1">
+ {endpoint.icon}
+ </div>
+ )}
+ {endpoint.label}
+ </div>
+ {filteredModels.map((modelId) => {
+ let modelName = modelId;
+ if (
+ endpoint.value === EModelEndpoint.agents &&
+ endpoint.agentNames &&
+ endpoint.agentNames[modelId]
+ ) {
+ modelName = endpoint.agentNames[modelId];
+ } else if (
+ (endpoint.value === EModelEndpoint.assistants ||
+ endpoint.value === EModelEndpoint.azureAssistants) &&
+ endpoint.assistantNames &&
+ endpoint.assistantNames[modelId]
+ ) {
+ modelName = endpoint.assistantNames[modelId];
+ }
+
+ return (
+ <MenuItem
+ key={`${endpoint.value}-${modelId}-search-${i}`}
+ onClick={() => handleSelectModel(endpoint, modelId)}
+ className="flex w-full cursor-pointer items-center justify-start rounded-lg px-3 py-2 pl-6 text-sm"
+ >
+ <div className="flex items-center gap-2">
+ {endpoint.modelIcons?.[modelId] && (
+ <div className="flex h-5 w-5 items-center justify-center overflow-hidden rounded-full">
+ <img
+ src={endpoint.modelIcons[modelId]}
+ alt={modelName}
+ className="h-full w-full object-cover"
+ />
+ </div>
+ )}
+ <span>{modelName}</span>
+ </div>
+ {selectedEndpoint === endpoint.value && selectedModel === modelId && (
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ className="ml-auto block"
+ >
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12ZM16.0755 7.93219C16.5272 8.25003 16.6356 8.87383 16.3178 9.32549L11.5678 16.0755C11.3931 16.3237 11.1152 16.4792 10.8123 16.4981C10.5093 16.517 10.2142 16.3973 10.0101 16.1727L7.51006 13.4227C7.13855 13.014 7.16867 12.3816 7.57733 12.0101C7.98598 11.6386 8.61843 11.6687 8.98994 12.0773L10.6504 13.9039L14.6822 8.17451C15 7.72284 15.6238 7.61436 16.0755 7.93219Z"
+ fill="currentColor"
+ />
+ </svg>
+ )}
+ </MenuItem>
+ );
+ })}
+ </Fragment>
+ );
+ } else {
+ // Endpoints with no models
+ return (
+ <MenuItem
+ key={`endpoint-${endpoint.value}-search-item`}
+ onClick={() => handleSelectEndpoint(endpoint)}
+ className="flex w-full cursor-pointer items-center justify-between rounded-xl px-3 py-2 text-sm"
+ >
+ <div className="flex items-center gap-2">
+ {endpoint.icon && (
+ <div
+ className="flex items-center justify-center overflow-hidden rounded-full border border-gray-200 p-1 dark:border-gray-700"
+ style={{ borderRadius: '50%' }}
+ >
+ {endpoint.icon}
+ </div>
+ )}
+ <span>{endpoint.label}</span>
+ </div>
+ {selectedEndpoint === endpoint.value && (
+ <svg
+ width="16"
+ height="16"
+ viewBox="0 0 24 24"
+ fill="none"
+ xmlns="http://www.w3.org/2000/svg"
+ className="block"
+ >
+ <path
+ fillRule="evenodd"
+ clipRule="evenodd"
+ d="M2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12ZM16.0755 7.93219C16.5272 8.25003 16.6356 8.87383 16.3178 9.32549L11.5678 16.0755C11.3931 16.3237 11.1152 16.4792 10.8123 16.4981C10.5093 16.517 10.2142 16.3973 10.0101 16.1727L7.51006 13.4227C7.13855 13.014 7.16867 12.3816 7.57733 12.0101C7.98598 11.6386 8.61843 11.6687 8.98994 12.0773L10.6504 13.9039L14.6822 8.17451C15 7.72284 15.6238 7.61436 16.0755 7.93219Z"
+ fill="currentColor"
+ />
+ </svg>
+ )}
+ </MenuItem>
+ );
+ }
+ }
+ })}
+ </>
+ );
+}
+
+export function renderSearchResults(
+ results: (TModelSpec | Endpoint)[] | null,
+ localize: (phraseKey: any, options?: any) => string,
+ searchValue: string,
+) {
+ return (
+ <SearchResults
+ key={`search-results-${searchValue}`}
+ results={results}
+ localize={localize}
+ searchValue={searchValue}
+ />
+ );
+}
diff --git a/client/src/components/Chat/Menus/Models/SpecIcon.tsx b/client/src/components/Chat/Menus/Endpoints/components/SpecIcon.tsx
similarity index 77%
rename from client/src/components/Chat/Menus/Models/SpecIcon.tsx
rename to client/src/components/Chat/Menus/Endpoints/components/SpecIcon.tsx
index 9d1cb09e8e..420af69d71 100644
--- a/client/src/components/Chat/Menus/Models/SpecIcon.tsx
+++ b/client/src/components/Chat/Menus/Endpoints/components/SpecIcon.tsx
@@ -2,27 +2,29 @@ import React, { memo } from 'react';
import type { TModelSpec, TEndpointsConfig } from 'librechat-data-provider';
import type { IconMapProps } from '~/common';
import { getModelSpecIconURL, getIconKey, getEndpointField } from '~/utils';
-import { icons } from '~/components/Chat/Menus/Endpoints/Icons';
import { URLIcon } from '~/components/Endpoints/URLIcon';
+import { icons } from '~/hooks/Endpoint/Icons';
interface SpecIconProps {
currentSpec: TModelSpec;
endpointsConfig: TEndpointsConfig;
}
+type IconType = (props: IconMapProps) => React.JSX.Element;
+
const SpecIcon: React.FC<SpecIconProps> = ({ currentSpec, endpointsConfig }) => {
const iconURL = getModelSpecIconURL(currentSpec);
const { endpoint } = currentSpec.preset;
const endpointIconURL = getEndpointField(endpointsConfig, endpoint, 'iconURL');
const iconKey = getIconKey({ endpoint, endpointsConfig, endpointIconURL });
- let Icon: (props: IconMapProps) => React.JSX.Element;
+ let Icon: IconType;
if (!iconURL.includes('http')) {
- Icon = icons[iconKey] ?? icons.unknown;
+ Icon = (icons[iconKey] ?? icons.unknown) as IconType;
} else if (iconURL) {
return <URLIcon iconURL={iconURL} altName={currentSpec.name} />;
} else {
- Icon = icons[endpoint ?? ''] ?? icons.unknown;
+ Icon = (icons[endpoint ?? ''] ?? icons.unknown) as IconType;
}
return (
@@ -31,7 +33,7 @@ const SpecIcon: React.FC<SpecIconProps> = ({ currentSpec, endpointsConfig }) =>
endpoint={endpoint}
context="menu-item"
iconURL={endpointIconURL}
- className="icon-lg mr-1 shrink-0 text-text-primary"
+ className="icon-md shrink-0 text-text-primary"
/>
);
};
diff --git a/client/src/components/Chat/Menus/Endpoints/components/index.ts b/client/src/components/Chat/Menus/Endpoints/components/index.ts
new file mode 100644
index 0000000000..d39ad4276f
--- /dev/null
+++ b/client/src/components/Chat/Menus/Endpoints/components/index.ts
@@ -0,0 +1,4 @@
+export * from './ModelSpecItem';
+export * from './EndpointModelItem';
+export * from './EndpointItem';
+export * from './SearchResults';
diff --git a/client/src/components/Chat/Menus/Endpoints/utils.ts b/client/src/components/Chat/Menus/Endpoints/utils.ts
new file mode 100644
index 0000000000..6a42d30121
--- /dev/null
+++ b/client/src/components/Chat/Menus/Endpoints/utils.ts
@@ -0,0 +1,162 @@
+import React from 'react';
+import { Bot } from 'lucide-react';
+import { EModelEndpoint } from 'librechat-data-provider';
+import type {
+ TAgentsMap,
+ TAssistantsMap,
+ TEndpointsConfig,
+ TModelSpec,
+} from 'librechat-data-provider';
+import SpecIcon from '~/components/Chat/Menus/Endpoints/components/SpecIcon';
+import { Endpoint, SelectedValues } from '~/common';
+
+export function filterItems<
+ T extends { label: string; name?: string; value?: string; models?: string[] },
+>(
+ items: T[],
+ searchValue: string,
+ agentsMap: TAgentsMap | undefined,
+ assistantsMap: TAssistantsMap | undefined,
+): T[] | null {
+ const searchTermLower = searchValue.trim().toLowerCase();
+ if (!searchTermLower) {
+ return null;
+ }
+
+ return items.filter((item) => {
+ const itemMatches =
+ item.label.toLowerCase().includes(searchTermLower) ||
+ (item.name && item.name.toLowerCase().includes(searchTermLower)) ||
+ (item.value && item.value.toLowerCase().includes(searchTermLower));
+
+ if (itemMatches) {
+ return true;
+ }
+
+ if (item.models && item.models.length > 0) {
+ return item.models.some((modelId) => {
+ if (modelId.toLowerCase().includes(searchTermLower)) {
+ return true;
+ }
+
+ if (item.value === EModelEndpoint.agents && agentsMap && modelId in agentsMap) {
+ const agentName = agentsMap[modelId]?.name;
+ return typeof agentName === 'string' && agentName.toLowerCase().includes(searchTermLower);
+ }
+
+ if (
+ (item.value === EModelEndpoint.assistants ||
+ item.value === EModelEndpoint.azureAssistants) &&
+ assistantsMap
+ ) {
+ const endpoint = item.value;
+ const assistant = assistantsMap[endpoint][modelId];
+ if (assistant && typeof assistant.name === 'string') {
+ return assistant.name.toLowerCase().includes(searchTermLower);
+ }
+ return false;
+ }
+
+ return false;
+ });
+ }
+
+ return false;
+ });
+}
+
+export function filterModels(
+ endpoint: Endpoint,
+ models: string[],
+ searchValue: string,
+ agentsMap: TAgentsMap | undefined,
+ assistantsMap: TAssistantsMap | undefined,
+): string[] {
+ const searchTermLower = searchValue.trim().toLowerCase();
+ if (!searchTermLower) {
+ return models;
+ }
+
+ return models.filter((modelId) => {
+ let modelName = modelId;
+
+ if (endpoint.value === EModelEndpoint.agents && agentsMap && agentsMap[modelId]) {
+ modelName = agentsMap[modelId].name || modelId;
+ } else if (
+ (endpoint.value === EModelEndpoint.assistants ||
+ endpoint.value === EModelEndpoint.azureAssistants) &&
+ assistantsMap &&
+ assistantsMap[endpoint.value]
+ ) {
+ const assistant = assistantsMap[endpoint.value][modelId];
+ modelName =
+ typeof assistant.name === 'string' && assistant.name ? (assistant.name as string) : modelId;
+ }
+
+ return modelName.toLowerCase().includes(searchTermLower);
+ });
+}
+
+export function getSelectedIcon({
+ mappedEndpoints,
+ selectedValues,
+ modelSpecs,
+ endpointsConfig,
+}: {
+ mappedEndpoints: Endpoint[];
+ selectedValues: SelectedValues;
+ modelSpecs: TModelSpec[];
+ endpointsConfig: TEndpointsConfig;
+}): React.ReactNode | null {
+ const { endpoint, model, modelSpec } = selectedValues;
+
+ if (modelSpec) {
+ const spec = modelSpecs.find((s) => s.name === modelSpec);
+ if (!spec) {
+ return null;
+ }
+ const { showIconInHeader = true } = spec;
+ if (!showIconInHeader) {
+ return null;
+ }
+ return React.createElement(SpecIcon, {
+ currentSpec: spec,
+ endpointsConfig,
+ });
+ }
+
+ if (endpoint && model) {
+ const selectedEndpoint = mappedEndpoints.find((e) => e.value === endpoint);
+ if (!selectedEndpoint) {
+ return null;
+ }
+
+ if (selectedEndpoint.modelIcons?.[model]) {
+ const iconUrl = selectedEndpoint.modelIcons[model];
+ return React.createElement(
+ 'div',
+ { className: 'h-5 w-5 overflow-hidden rounded-full' },
+ React.createElement('img', {
+ src: iconUrl,
+ alt: model,
+ className: 'h-full w-full object-cover',
+ }),
+ );
+ }
+
+ return (
+ selectedEndpoint.icon ||
+ React.createElement(Bot, {
+ size: 20,
+ className: 'icon-md shrink-0 text-text-primary',
+ })
+ );
+ }
+
+ if (endpoint) {
+ const selectedEndpoint = mappedEndpoints.find((e) => e.value === endpoint);
+ return selectedEndpoint?.icon || null;
+ }
+
+ return null;
+}
diff --git a/client/src/components/Chat/Menus/EndpointsMenu.tsx b/client/src/components/Chat/Menus/EndpointsMenu.tsx
deleted file mode 100644
index ee90ddeded..0000000000
--- a/client/src/components/Chat/Menus/EndpointsMenu.tsx
+++ /dev/null
@@ -1,105 +0,0 @@
-import { useCallback, useRef } from 'react';
-import { alternateName } from 'librechat-data-provider';
-import { Content, Portal, Root } from '@radix-ui/react-popover';
-import type { FC, KeyboardEvent } from 'react';
-import { useChatContext, useAgentsMapContext, useAssistantsMapContext } from '~/Providers';
-import { useGetEndpointsQuery } from '~/data-provider';
-import { mapEndpoints, getEntity } from '~/utils';
-import EndpointItems from './Endpoints/MenuItems';
-import useLocalize from '~/hooks/useLocalize';
-import TitleButton from './UI/TitleButton';
-
-const EndpointsMenu: FC = () => {
- const { data: endpoints = [] } = useGetEndpointsQuery({
- select: mapEndpoints,
- });
-
- const localize = useLocalize();
- const agentsMap = useAgentsMapContext();
- const assistantMap = useAssistantsMapContext();
- const { conversation } = useChatContext();
- const { endpoint = '' } = conversation ?? {};
-
- const menuRef = useRef<HTMLDivElement>(null);
-
- const handleKeyDown = useCallback((event: KeyboardEvent) => {
- const menuItems = menuRef.current?.querySelectorAll('[role="option"]');
- if (!menuItems) {
- return;
- }
- if (!menuItems.length) {
- return;
- }
-
- const currentIndex = Array.from(menuItems).findIndex((item) => item === document.activeElement);
-
- switch (event.key) {
- case 'ArrowDown':
- event.preventDefault();
- if (currentIndex < menuItems.length - 1) {
- (menuItems[currentIndex + 1] as HTMLElement).focus();
- } else {
- (menuItems[0] as HTMLElement).focus();
- }
- break;
- case 'ArrowUp':
- event.preventDefault();
- if (currentIndex > 0) {
- (menuItems[currentIndex - 1] as HTMLElement).focus();
- } else {
- (menuItems[menuItems.length - 1] as HTMLElement).focus();
- }
- break;
- }
- }, []);
-
- if (!endpoint) {
- console.warn('No endpoint selected');
- return null;
- }
-
- const { entity } = getEntity({
- endpoint,
- agentsMap,
- assistantMap,
- agent_id: conversation?.agent_id,
- assistant_id: conversation?.assistant_id,
- });
-
- const primaryText = entity
- ? entity.name
- : (alternateName[endpoint] as string | undefined) ?? endpoint;
-
- return (
- <Root>
- <TitleButton primaryText={primaryText + ' '} />
- <Portal>
- <div
- style={{
- position: 'fixed',
- left: '0px',
- top: '0px',
- transform: 'translate3d(268px, 50px, 0px)',
- minWidth: 'max-content',
- zIndex: 'auto',
- }}
- >
- <Content
- side="bottom"
- align="start"
- role="listbox"
- id="llm-endpoint-menu"
- ref={menuRef}
- onKeyDown={handleKeyDown}
- aria-label={localize('com_ui_endpoints_available')}
- className="mt-2 max-h-[65vh] min-w-[340px] overflow-y-auto rounded-lg border border-border-light bg-header-primary text-text-primary shadow-lg lg:max-h-[75vh]"
- >
- <EndpointItems endpoints={endpoints} selected={endpoint} />
- </Content>
- </div>
- </Portal>
- </Root>
- );
-};
-
-export default EndpointsMenu;
diff --git a/client/src/components/Chat/Menus/HeaderNewChat.tsx b/client/src/components/Chat/Menus/HeaderNewChat.tsx
index 3e29190e7c..f59f570ec8 100644
--- a/client/src/components/Chat/Menus/HeaderNewChat.tsx
+++ b/client/src/components/Chat/Menus/HeaderNewChat.tsx
@@ -2,7 +2,7 @@ import { useQueryClient } from '@tanstack/react-query';
import { QueryKeys, Constants } from 'librechat-data-provider';
import type { TMessage } from 'librechat-data-provider';
import { useMediaQuery, useLocalize } from '~/hooks';
-import { NewChatIcon } from '~/components/svg';
+import { Button, NewChatIcon } from '~/components';
import { useChatContext } from '~/Providers';
export default function HeaderNewChat() {
@@ -10,15 +10,18 @@ export default function HeaderNewChat() {
const { conversation, newConversation } = useChatContext();
const isSmallScreen = useMediaQuery('(max-width: 768px)');
const localize = useLocalize();
+
if (isSmallScreen) {
return null;
}
+
return (
- <button
+ <Button
+ size="icon"
+ variant="outline"
data-testid="wide-header-new-chat-button"
aria-label={localize('com_ui_new_chat')}
- type="button"
- className="btn btn-neutral btn-small border-token-border-medium focus:border-black-500 dark:focus:border-white-500 relative ml-2 flex h-9 w-9 items-center justify-center whitespace-nowrap rounded-lg border md:flex"
+ className="rounded-xl border border-border-light bg-surface-secondary p-2 hover:bg-surface-hover"
onClick={() => {
queryClient.setQueryData<TMessage[]>(
[QueryKeys.messages, conversation?.conversationId ?? Constants.NEW_CONVO],
@@ -27,9 +30,7 @@ export default function HeaderNewChat() {
newConversation();
}}
>
- <div className="flex w-full items-center justify-center gap-2">
- <NewChatIcon />
- </div>
- </button>
+ <NewChatIcon />
+ </Button>
);
}
diff --git a/client/src/components/Chat/Menus/Models/MenuButton.tsx b/client/src/components/Chat/Menus/Models/MenuButton.tsx
deleted file mode 100644
index 30c714128d..0000000000
--- a/client/src/components/Chat/Menus/Models/MenuButton.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import { useState } from 'react';
-import { Trigger } from '@radix-ui/react-popover';
-import type { TModelSpec, TEndpointsConfig } from 'librechat-data-provider';
-import { useLocalize } from '~/hooks';
-import SpecIcon from './SpecIcon';
-import { cn } from '~/utils';
-
-export default function MenuButton({
- selected,
- className = '',
- textClassName = '',
- primaryText = '',
- secondaryText = '',
- endpointsConfig,
-}: {
- selected?: TModelSpec;
- className?: string;
- textClassName?: string;
- primaryText?: string;
- secondaryText?: string;
- endpointsConfig: TEndpointsConfig;
-}) {
- const localize = useLocalize();
- const [isExpanded, setIsExpanded] = useState(false);
-
- return (
- <Trigger asChild>
- <button
- className={cn(
- 'group flex cursor-pointer items-center gap-1 rounded-xl px-3 py-2 text-lg font-medium hover:bg-gray-50 radix-state-open:bg-gray-50 dark:hover:bg-gray-700 dark:radix-state-open:bg-gray-700',
- className,
- )}
- type="button"
- aria-label={localize('com_ui_llm_menu')}
- role="combobox"
- aria-haspopup="listbox"
- aria-expanded={isExpanded}
- aria-controls="llm-menu"
- onClick={() => setIsExpanded(!isExpanded)}
- >
- {selected && selected.showIconInHeader === true && (
- <SpecIcon currentSpec={selected} endpointsConfig={endpointsConfig} />
- )}
- <div className={textClassName}>
- {!selected ? localize('com_ui_none_selected') : primaryText}{' '}
- {!!secondaryText && <span className="text-token-text-secondary">{secondaryText}</span>}
- </div>
- <svg
- width="16"
- height="17"
- viewBox="0 0 16 17"
- fill="none"
- className="text-token-text-tertiary"
- >
- <path
- d="M11.3346 7.83203L8.00131 11.1654L4.66797 7.83203"
- stroke="currentColor"
- strokeWidth="2"
- strokeLinecap="round"
- strokeLinejoin="round"
- />
- </svg>
- </button>
- </Trigger>
- );
-}
diff --git a/client/src/components/Chat/Menus/Models/ModelSpec.tsx b/client/src/components/Chat/Menus/Models/ModelSpec.tsx
deleted file mode 100644
index 617680946a..0000000000
--- a/client/src/components/Chat/Menus/Models/ModelSpec.tsx
+++ /dev/null
@@ -1,153 +0,0 @@
-import { useState, useMemo } from 'react';
-import { Settings } from 'lucide-react';
-import type { FC } from 'react';
-import type { TModelSpec, TEndpointsConfig } from 'librechat-data-provider';
-import { SetKeyDialog } from '~/components/Input/SetKeyDialog';
-import { useLocalize, useUserKey } from '~/hooks';
-import { cn, getEndpointField } from '~/utils';
-import SpecIcon from './SpecIcon';
-
-type MenuItemProps = {
- title: string;
- spec: TModelSpec;
- selected: boolean;
- description?: string;
- userProvidesKey: boolean;
- endpointsConfig: TEndpointsConfig;
- onClick?: () => void;
- // iconPath: string;
- // hoverContent?: string;
-};
-
-const MenuItem: FC<MenuItemProps> = ({
- title,
- spec,
- selected,
- description,
- userProvidesKey,
- endpointsConfig,
- onClick,
- ...rest
-}) => {
- const { endpoint } = spec.preset;
- const [isDialogOpen, setDialogOpen] = useState(false);
- const { getExpiry } = useUserKey(endpoint ?? '');
- const localize = useLocalize();
- const expiryTime = getExpiry() ?? '';
-
- const clickHandler = () => {
- if (expiryTime) {
- setDialogOpen(true);
- }
- if (onClick) {
- onClick();
- }
- };
-
- const endpointType = useMemo(
- () => spec.preset.endpointType ?? getEndpointField(endpointsConfig, endpoint, 'type'),
- [spec, endpointsConfig, endpoint],
- );
-
- const { showIconInMenu = true } = spec;
-
- return (
- <>
- <div
- id={selected ? 'selected-llm' : undefined}
- role="option"
- aria-selected={selected}
- className="group m-1.5 flex cursor-pointer gap-2 rounded px-1 py-2.5 !pr-3 text-sm !opacity-100 hover:bg-black/5 focus:ring-0 radix-disabled:pointer-events-none radix-disabled:opacity-50 dark:hover:bg-white/5"
- tabIndex={0}
- {...rest}
- onClick={clickHandler}
- aria-label={title}
- onKeyDown={(e) => {
- if (e.key === 'Enter') {
- e.preventDefault();
- clickHandler();
- }
- }}
- >
- <div className="flex grow items-center justify-between gap-2">
- <div>
- <div className="flex items-center gap-2">
- {showIconInMenu && <SpecIcon currentSpec={spec} endpointsConfig={endpointsConfig} />}
- <div>
- {title}
- <div className="text-text-secondary">{description}</div>
- </div>
- </div>
- </div>
- <div className="flex items-center gap-2">
- {userProvidesKey ? (
- <div className="text-token-text-primary" key={`set-key-${endpoint}`}>
- <button
- tabIndex={0}
- aria-label={`${localize('com_endpoint_config_key')} for ${title}`}
- className={cn(
- 'invisible flex gap-x-1 group-focus-within:visible group-hover:visible',
- selected ? 'visible' : '',
- expiryTime
- ? 'w-full rounded-lg p-2 hover:bg-gray-200 dark:hover:bg-gray-900'
- : '',
- )}
- onClick={(e) => {
- e.preventDefault();
- e.stopPropagation();
- setDialogOpen(true);
- }}
- onKeyDown={(e) => {
- if (e.key === 'Enter' || e.key === ' ') {
- e.preventDefault();
- e.stopPropagation();
- setDialogOpen(true);
- }
- }}
- >
- <div
- className={cn(
- 'invisible group-focus-within:visible group-hover:visible',
- expiryTime ? 'text-xs' : '',
- )}
- >
- {localize('com_endpoint_config_key')}
- </div>
- <Settings className={cn(expiryTime ? 'icon-sm' : 'icon-md stroke-1')} />
- </button>
- </div>
- ) : null}
- {selected && (
- <svg
- width="24"
- height="24"
- viewBox="0 0 24 24"
- fill="none"
- xmlns="http://www.w3.org/2000/svg"
- className="icon-md block"
- // className="icon-md block group-hover:hidden"
- >
- <path
- fillRule="evenodd"
- clipRule="evenodd"
- d="M2 12C2 6.47715 6.47715 2 12 2C17.5228 2 22 6.47715 22 12C22 17.5228 17.5228 22 12 22C6.47715 22 2 17.5228 2 12ZM16.0755 7.93219C16.5272 8.25003 16.6356 8.87383 16.3178 9.32549L11.5678 16.0755C11.3931 16.3237 11.1152 16.4792 10.8123 16.4981C10.5093 16.517 10.2142 16.3973 10.0101 16.1727L7.51006 13.4227C7.13855 13.014 7.16867 12.3816 7.57733 12.0101C7.98598 11.6386 8.61843 11.6687 8.98994 12.0773L10.6504 13.9039L14.6822 8.17451C15 7.72284 15.6238 7.61436 16.0755 7.93219Z"
- fill="currentColor"
- />
- </svg>
- )}
- </div>
- </div>
- </div>
- {userProvidesKey && (
- <SetKeyDialog
- open={isDialogOpen}
- onOpenChange={setDialogOpen}
- endpoint={endpoint ?? ''}
- endpointType={endpointType}
- />
- )}
- </>
- );
-};
-
-export default MenuItem;
diff --git a/client/src/components/Chat/Menus/Models/ModelSpecs.tsx b/client/src/components/Chat/Menus/Models/ModelSpecs.tsx
deleted file mode 100644
index 95aafe397e..0000000000
--- a/client/src/components/Chat/Menus/Models/ModelSpecs.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-import type { FC } from 'react';
-import { Close } from '@radix-ui/react-popover';
-import { AuthType } from 'librechat-data-provider';
-import type { TModelSpec, TEndpointsConfig } from 'librechat-data-provider';
-import MenuSeparator from '~/components/Chat/Menus/UI/MenuSeparator';
-import ModelSpec from './ModelSpec';
-
-const ModelSpecs: FC<{
- specs?: Array<TModelSpec | undefined>;
- selected?: TModelSpec;
- setSelected?: (spec: TModelSpec) => void;
- endpointsConfig: TEndpointsConfig;
-}> = ({ specs = [], selected, setSelected = () => ({}), endpointsConfig }) => {
- return (
- <>
- {specs.length &&
- specs.map((spec, i) => {
- if (!spec) {
- return null;
- }
- return (
- <Close asChild key={`spec-${spec.name}`}>
- <div key={`spec-${spec.name}`}>
- <ModelSpec
- spec={spec}
- title={spec.label}
- key={`spec-item-${spec.name}`}
- description={spec.description}
- onClick={() => setSelected(spec)}
- data-testid={`spec-item-${spec.name}`}
- selected={selected?.name === spec.name}
- userProvidesKey={spec.authType === AuthType.USER_PROVIDED}
- endpointsConfig={endpointsConfig}
- />
- {i !== specs.length - 1 && <MenuSeparator />}
- </div>
- </Close>
- );
- })}
- </>
- );
-};
-
-export default ModelSpecs;
diff --git a/client/src/components/Chat/Menus/Models/ModelSpecsMenu.tsx b/client/src/components/Chat/Menus/Models/ModelSpecsMenu.tsx
deleted file mode 100644
index 400a514dd4..0000000000
--- a/client/src/components/Chat/Menus/Models/ModelSpecsMenu.tsx
+++ /dev/null
@@ -1,168 +0,0 @@
-import { useRecoilValue } from 'recoil';
-import { useMemo, useCallback, useRef } from 'react';
-import { Content, Portal, Root } from '@radix-ui/react-popover';
-import { EModelEndpoint, isAssistantsEndpoint } from 'librechat-data-provider';
-import type { TModelSpec, TConversation, TEndpointsConfig } from 'librechat-data-provider';
-import type { KeyboardEvent } from 'react';
-import { useChatContext, useAssistantsMapContext } from '~/Providers';
-import { useDefaultConvo, useNewConvo, useLocalize } from '~/hooks';
-import { getConvoSwitchLogic, getModelSpecIconURL } from '~/utils';
-import { useGetEndpointsQuery } from '~/data-provider';
-import MenuButton from './MenuButton';
-import ModelSpecs from './ModelSpecs';
-import store from '~/store';
-
-export default function ModelSpecsMenu({ modelSpecs }: { modelSpecs?: TModelSpec[] }) {
- const { conversation } = useChatContext();
- const { newConversation } = useNewConvo();
-
- const localize = useLocalize();
- const { data: endpointsConfig = {} as TEndpointsConfig } = useGetEndpointsQuery();
- const modularChat = useRecoilValue(store.modularChat);
- const getDefaultConversation = useDefaultConvo();
- const assistantMap = useAssistantsMapContext();
-
- const onSelectSpec = (spec: TModelSpec) => {
- const { preset } = spec;
- preset.iconURL = getModelSpecIconURL(spec);
- preset.spec = spec.name;
- const { endpoint } = preset;
- const newEndpoint = endpoint ?? '';
- if (!newEndpoint) {
- return;
- }
-
- const {
- template,
- shouldSwitch,
- isNewModular,
- newEndpointType,
- isCurrentModular,
- isExistingConversation,
- } = getConvoSwitchLogic({
- newEndpoint,
- modularChat,
- conversation,
- endpointsConfig,
- });
-
- if (newEndpointType) {
- preset.endpointType = newEndpointType;
- }
-
- if (isAssistantsEndpoint(newEndpoint) && preset.assistant_id != null && !(preset.model ?? '')) {
- preset.model = assistantMap?.[newEndpoint]?.[preset.assistant_id]?.model;
- }
-
- const isModular = isCurrentModular && isNewModular && shouldSwitch;
- if (isExistingConversation && isModular) {
- template.endpointType = newEndpointType as EModelEndpoint | undefined;
-
- const currentConvo = getDefaultConversation({
- /* target endpointType is necessary to avoid endpoint mixing */
- conversation: { ...(conversation ?? {}), endpointType: template.endpointType },
- preset: template,
- });
-
- /* We don't reset the latest message, only when changing settings mid-converstion */
- newConversation({
- template: currentConvo,
- preset,
- keepLatestMessage: true,
- keepAddedConvos: true,
- });
- return;
- }
-
- newConversation({
- template: { ...(template as Partial<TConversation>) },
- preset,
- keepAddedConvos: isModular,
- });
- };
-
- const selected = useMemo(() => {
- const spec = modelSpecs?.find((spec) => spec.name === conversation?.spec);
- if (!spec) {
- return undefined;
- }
- return spec;
- }, [modelSpecs, conversation?.spec]);
-
- const menuRef = useRef<HTMLDivElement>(null);
-
- const handleKeyDown = useCallback((event: KeyboardEvent) => {
- const menuItems = menuRef.current?.querySelectorAll('[role="option"]');
- if (!menuItems) {
- return;
- }
- if (!menuItems.length) {
- return;
- }
-
- const currentIndex = Array.from(menuItems).findIndex((item) => item === document.activeElement);
-
- switch (event.key) {
- case 'ArrowDown':
- event.preventDefault();
- if (currentIndex < menuItems.length - 1) {
- (menuItems[currentIndex + 1] as HTMLElement).focus();
- } else {
- (menuItems[0] as HTMLElement).focus();
- }
- break;
- case 'ArrowUp':
- event.preventDefault();
- if (currentIndex > 0) {
- (menuItems[currentIndex - 1] as HTMLElement).focus();
- } else {
- (menuItems[menuItems.length - 1] as HTMLElement).focus();
- }
- break;
- }
- }, []);
-
- return (
- <Root>
- <MenuButton
- selected={selected}
- className="min-h-11"
- textClassName="block items-center justify-start text-xs md:text-base whitespace-nowrap max-w-64 overflow-hidden shrink-0 text-ellipsis"
- primaryText={selected?.label ?? ''}
- endpointsConfig={endpointsConfig}
- />
- <Portal>
- {modelSpecs && modelSpecs.length && (
- <div
- style={{
- position: 'fixed',
- left: '0px',
- top: '0px',
- transform: 'translate3d(268px, 50px, 0px)',
- minWidth: 'max-content',
- zIndex: 'auto',
- }}
- >
- <Content
- side="bottom"
- align="start"
- id="llm-menu"
- role="listbox"
- ref={menuRef}
- onKeyDown={handleKeyDown}
- aria-label={localize('com_ui_llms_available')}
- className="models-scrollbar mt-2 max-h-[65vh] min-w-[340px] max-w-xs overflow-y-auto rounded-lg border border-gray-100 bg-white shadow-lg dark:border-gray-700 dark:bg-gray-700 dark:text-white lg:max-h-[75vh]"
- >
- <ModelSpecs
- specs={modelSpecs}
- selected={selected}
- setSelected={onSelectSpec}
- endpointsConfig={endpointsConfig}
- />
- </Content>
- </div>
- )}
- </Portal>
- </Root>
- );
-}
diff --git a/client/src/components/Chat/Menus/Presets/PresetItems.tsx b/client/src/components/Chat/Menus/Presets/PresetItems.tsx
index 552b8b5407..f1e8e738a1 100644
--- a/client/src/components/Chat/Menus/Presets/PresetItems.tsx
+++ b/client/src/components/Chat/Menus/Presets/PresetItems.tsx
@@ -10,7 +10,7 @@ import { Dialog, DialogTrigger, Label } from '~/components/ui';
import DialogTemplate from '~/components/ui/DialogTemplate';
import { useGetEndpointsQuery } from '~/data-provider';
import { MenuSeparator, MenuItem } from '../UI';
-import { icons } from '../Endpoints/Icons';
+import { icons } from '~/hooks/Endpoint/Icons';
import { useLocalize } from '~/hooks';
import { cn } from '~/utils';
import store from '~/store';
@@ -39,7 +39,7 @@ const PresetItems: FC<{
<>
<div
role="menuitem"
- className="pointer-none group m-1.5 flex h-8 min-w-[170px] gap-2 rounded px-5 py-2.5 !pr-3 text-sm !opacity-100 focus:ring-0 radix-disabled:pointer-events-none radix-disabled:opacity-50 md:min-w-[240px]"
+ className="pointer-none group m-1.5 flex h-8 min-w-[170px] gap-2 rounded px-5 py-2.5 !pr-3 text-sm !opacity-100 focus:ring-0 radix-disabled:pointer-events-none radix-disabled:opacity-50 md:min-w-[240px]"
tabIndex={-1}
>
<div className="flex h-full grow items-center justify-end gap-2">
diff --git a/client/src/components/Chat/Menus/PresetsMenu.tsx b/client/src/components/Chat/Menus/PresetsMenu.tsx
index 76fc13dab7..224a006d59 100644
--- a/client/src/components/Chat/Menus/PresetsMenu.tsx
+++ b/client/src/components/Chat/Menus/PresetsMenu.tsx
@@ -30,7 +30,7 @@ const PresetsMenu: FC = () => {
tabIndex={0}
role="button"
data-testid="presets-button"
- className="inline-flex size-10 items-center justify-center rounded-lg border border-border-light bg-transparent text-text-primary transition-all ease-in-out hover:bg-surface-tertiary disabled:pointer-events-none disabled:opacity-50 radix-state-open:bg-surface-tertiary"
+ className="inline-flex size-10 flex-shrink-0 items-center justify-center rounded-lg border border-border-light bg-transparent text-text-primary transition-all ease-in-out hover:bg-surface-tertiary disabled:pointer-events-none disabled:opacity-50 radix-state-open:bg-surface-tertiary"
>
<BookCopy size={16} aria-label="Preset Icon" />
</TooltipAnchor>
diff --git a/client/src/components/Chat/Menus/index.ts b/client/src/components/Chat/Menus/index.ts
index f77208fe55..33b7e7d498 100644
--- a/client/src/components/Chat/Menus/index.ts
+++ b/client/src/components/Chat/Menus/index.ts
@@ -1,4 +1,2 @@
export { default as PresetsMenu } from './PresetsMenu';
-export { default as EndpointsMenu } from './EndpointsMenu';
export { default as HeaderNewChat } from './HeaderNewChat';
-export { default as ModelSpecsMenu } from './Models/ModelSpecsMenu';
diff --git a/client/src/components/Chat/Messages/Content/Part.tsx b/client/src/components/Chat/Messages/Content/Part.tsx
index 1351efd59c..8e6e5e09fa 100644
--- a/client/src/components/Chat/Messages/Content/Part.tsx
+++ b/client/src/components/Chat/Messages/Content/Part.tsx
@@ -38,7 +38,13 @@ const Part = memo(
if (part.type === ContentTypes.ERROR) {
return (
<ErrorMessage
- text={part[ContentTypes.ERROR] ?? part[ContentTypes.TEXT]?.value}
+ text={
+ part[ContentTypes.ERROR] ??
+ (typeof part[ContentTypes.TEXT] === 'string'
+ ? part[ContentTypes.TEXT]
+ : part.text?.value) ??
+ ''
+ }
className="my-2"
/>
);
diff --git a/client/src/components/Chat/Messages/MessageParts.tsx b/client/src/components/Chat/Messages/MessageParts.tsx
index 7104528566..1ce0c19e9d 100644
--- a/client/src/components/Chat/Messages/MessageParts.tsx
+++ b/client/src/components/Chat/Messages/MessageParts.tsx
@@ -6,7 +6,7 @@ import MessageIcon from '~/components/Chat/Messages/MessageIcon';
import { useMessageHelpers, useLocalize } from '~/hooks';
import ContentParts from './Content/ContentParts';
import SiblingSwitch from './SiblingSwitch';
-// eslint-disable-next-line import/no-cycle
+
import MultiMessage from './MultiMessage';
import HoverButtons from './HoverButtons';
import SubRow from './SubRow';
@@ -33,8 +33,11 @@ export default function Message(props: TMessageProps) {
copyToClipboard,
regenerateMessage,
} = useMessageHelpers(props);
+
const fontSize = useRecoilValue(store.fontSize);
+ const maximizeChatSpace = useRecoilValue(store.maximizeChatSpace);
const { children, messageId = null, isCreatedByUser } = message ?? {};
+
const name = useMemo(() => {
let result = '';
if (isCreatedByUser === true) {
@@ -67,71 +70,86 @@ export default function Message(props: TMessageProps) {
message?.isCreatedByUser,
],
);
+
if (!message) {
return null;
}
+ const baseClasses = {
+ common: 'group mx-auto flex flex-1 gap-3 transition-all duration-300 transform-gpu',
+ chat: maximizeChatSpace
+ ? 'w-full max-w-full md:px-5 lg:px-1 xl:px-5'
+ : 'md:max-w-[47rem] xl:max-w-[55rem]',
+ };
+
return (
<>
<div
- className="text-token-text-primary w-full border-0 bg-transparent dark:border-0 dark:bg-transparent"
+ className="w-full border-0 bg-transparent dark:border-0 dark:bg-transparent"
onWheel={handleScroll}
onTouchMove={handleScroll}
>
- <div className="m-auto justify-center p-4 py-2 md:gap-6 ">
- <div className="group mx-auto flex flex-1 gap-3 md:max-w-3xl md:px-5 lg:max-w-[40rem] lg:px-1 xl:max-w-[48rem] xl:px-5">
- <div className="relative flex flex-shrink-0 flex-col items-end">
- <div>
- <div className="pt-0.5">
- <div className="shadow-stroke flex h-6 w-6 items-center justify-center overflow-hidden rounded-full">
- <MessageIcon iconData={iconData} assistant={assistant} agent={agent} />
- </div>
- </div>
+ <div className="m-auto justify-center p-4 py-2 md:gap-6">
+ <div
+ id={messageId}
+ aria-label={`message-${message.depth}-${messageId}`}
+ className={cn(baseClasses.common, baseClasses.chat, 'message-render')}
+ >
+ <div className="relative flex flex-shrink-0 flex-col items-center">
+ <div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full pt-0.5">
+ <MessageIcon iconData={iconData} assistant={assistant} agent={agent} />
</div>
</div>
<div
className={cn(
- 'relative flex w-full flex-col',
- isCreatedByUser === true ? '' : 'agent-turn',
+ 'relative flex w-11/12 flex-col',
+ isCreatedByUser ? 'user-turn' : 'agent-turn',
)}
>
- <div className={cn('select-none font-semibold', fontSize)}>{name}</div>
- <div className="flex-col gap-1 md:gap-3">
+ <h2 className={cn('select-none font-semibold text-text-primary', fontSize)}>
+ {name}
+ </h2>
+ <div className="flex flex-col gap-1 md:gap-3">
<div className="flex max-w-full flex-grow flex-col gap-0">
<ContentParts
+ edit={edit}
isLast={isLast}
- isSubmitting={isSubmitting}
+ enterEdit={enterEdit}
+ siblingIdx={siblingIdx}
messageId={message.messageId}
+ isSubmitting={isSubmitting}
+ setSiblingIdx={setSiblingIdx}
+ attachments={message.attachments}
isCreatedByUser={message.isCreatedByUser}
conversationId={conversation?.conversationId}
content={message.content as Array<TMessageContentParts | undefined>}
/>
</div>
+ {isLast && isSubmitting ? (
+ <div className="mt-1 h-[27px] bg-transparent" />
+ ) : (
+ <SubRow classes="text-xs">
+ <SiblingSwitch
+ siblingIdx={siblingIdx}
+ siblingCount={siblingCount}
+ setSiblingIdx={setSiblingIdx}
+ />
+ <HoverButtons
+ index={index}
+ isEditing={edit}
+ message={message}
+ enterEdit={enterEdit}
+ isSubmitting={isSubmitting}
+ conversation={conversation ?? null}
+ regenerate={() => regenerateMessage()}
+ copyToClipboard={copyToClipboard}
+ handleContinue={handleContinue}
+ latestMessage={latestMessage}
+ isLast={isLast}
+ />
+ </SubRow>
+ )}
</div>
- {isLast && isSubmitting ? (
- <div className="mt-1 h-[27px] bg-transparent" />
- ) : (
- <SubRow classes="text-xs">
- <SiblingSwitch
- siblingIdx={siblingIdx}
- siblingCount={siblingCount}
- setSiblingIdx={setSiblingIdx}
- />
- <HoverButtons
- index={index}
- isEditing={edit}
- message={message}
- enterEdit={enterEdit}
- isSubmitting={isSubmitting}
- conversation={conversation ?? null}
- regenerate={() => regenerateMessage()}
- copyToClipboard={copyToClipboard}
- handleContinue={handleContinue}
- latestMessage={latestMessage}
- isLast={isLast}
- />
- </SubRow>
- )}
</div>
</div>
</div>
diff --git a/client/src/components/Chat/Messages/MessagesView.tsx b/client/src/components/Chat/Messages/MessagesView.tsx
index 5097ddb497..bf0016c63a 100644
--- a/client/src/components/Chat/Messages/MessagesView.tsx
+++ b/client/src/components/Chat/Messages/MessagesView.tsx
@@ -1,7 +1,6 @@
import { useState } from 'react';
import { useRecoilValue } from 'recoil';
import { CSSTransition } from 'react-transition-group';
-import type { ReactNode } from 'react';
import type { TMessage } from 'librechat-data-provider';
import { useScreenshot, useMessageScrolling, useLocalize } from '~/hooks';
import ScrollToBottom from '~/components/Messages/ScrollToBottom';
@@ -11,13 +10,12 @@ import store from '~/store';
export default function MessagesView({
messagesTree: _messagesTree,
- Header,
}: {
messagesTree?: TMessage[] | null;
- Header?: ReactNode;
}) {
const localize = useLocalize();
const scrollButtonPreference = useRecoilValue(store.showScrollButton);
+ const maximizeChatSpace = useRecoilValue(store.maximizeChatSpace);
const fontSize = useRecoilValue(store.fontSize);
const { screenshotTargetRef } = useScreenshot();
const [currentEditId, setCurrentEditId] = useState<number | string | null>(-1);
@@ -34,62 +32,64 @@ export default function MessagesView({
const { conversationId } = conversation ?? {};
return (
- <div className="flex-1 overflow-hidden overflow-y-auto">
- <div className="relative h-full">
- <div
- className="scrollbar-gutter-stable"
- onScroll={debouncedHandleScroll}
- ref={scrollableRef}
- style={{
- height: '100%',
- overflowY: 'auto',
- width: '100%',
- }}
- >
- <div className="flex flex-col pb-9 dark:bg-transparent">
- {(_messagesTree && _messagesTree.length == 0) || _messagesTree === null ? (
- <div
- className={cn(
- 'flex w-full items-center justify-center p-3 text-text-secondary',
- fontSize,
- )}
- >
- {localize('com_ui_nothing_found')}
- </div>
- ) : (
- <>
- {Header != null && Header}
- <div ref={screenshotTargetRef}>
- <MultiMessage
- key={conversationId} // avoid internal state mixture
- messagesTree={_messagesTree}
- messageId={conversationId ?? null}
- setCurrentEditId={setCurrentEditId}
- currentEditId={currentEditId ?? null}
- />
+ <>
+ <div className="relative flex-1 overflow-hidden overflow-y-auto">
+ <div className="relative h-full">
+ <div
+ className="scrollbar-gutter-stable"
+ onScroll={debouncedHandleScroll}
+ ref={scrollableRef}
+ style={{
+ height: '100%',
+ overflowY: 'auto',
+ width: '100%',
+ }}
+ >
+ <div className="flex flex-col pb-9 dark:bg-transparent">
+ {(_messagesTree && _messagesTree.length == 0) || _messagesTree === null ? (
+ <div
+ className={cn(
+ 'flex w-full items-center justify-center p-3 text-text-secondary',
+ fontSize,
+ )}
+ >
+ {localize('com_ui_nothing_found')}
</div>
- </>
- )}
- <div
- id="messages-end"
- className="group h-0 w-full flex-shrink-0"
- ref={messagesEndRef}
- />
+ ) : (
+ <>
+ <div ref={screenshotTargetRef}>
+ <MultiMessage
+ key={conversationId}
+ messagesTree={_messagesTree}
+ messageId={conversationId ?? null}
+ setCurrentEditId={setCurrentEditId}
+ currentEditId={currentEditId ?? null}
+ />
+ </div>
+ </>
+ )}
+ <div
+ id="messages-end"
+ className="group h-0 w-full flex-shrink-0"
+ ref={messagesEndRef}
+ />
+ </div>
</div>
+
+ <CSSTransition
+ in={showScrollButton && scrollButtonPreference}
+ timeout={{
+ enter: 550,
+ exit: 700,
+ }}
+ classNames="scroll-animation"
+ unmountOnExit={true}
+ appear={true}
+ >
+ <ScrollToBottom scrollHandler={handleSmoothToRef} />
+ </CSSTransition>
</div>
- <CSSTransition
- in={showScrollButton}
- timeout={400}
- classNames="scroll-down"
- unmountOnExit={false}
- // appear
- >
- {() =>
- showScrollButton &&
- scrollButtonPreference && <ScrollToBottom scrollHandler={handleSmoothToRef} />
- }
- </CSSTransition>
</div>
- </div>
+ </>
);
}
diff --git a/client/src/components/Chat/Messages/MultiMessage.tsx b/client/src/components/Chat/Messages/MultiMessage.tsx
index eb2d2e9257..3cca4ff135 100644
--- a/client/src/components/Chat/Messages/MultiMessage.tsx
+++ b/client/src/components/Chat/Messages/MultiMessage.tsx
@@ -30,7 +30,6 @@ export default function MultiMessage({
useEffect(() => {
// reset siblingIdx when the tree changes, mostly when a new message is submitting.
setSiblingIdx(0);
- // eslint-disable-next-line react-hooks/exhaustive-deps
}, [messagesTree?.length]);
useEffect(() => {
@@ -62,6 +61,7 @@ export default function MultiMessage({
/>
);
} else if (message.content) {
+ console.log('message.id with content', message.messageId);
return (
<MessageContent
key={message.messageId}
diff --git a/client/src/components/Chat/Messages/ui/MessageRender.tsx b/client/src/components/Chat/Messages/ui/MessageRender.tsx
index dbbee5869f..0cbc0f142b 100644
--- a/client/src/components/Chat/Messages/ui/MessageRender.tsx
+++ b/client/src/components/Chat/Messages/ui/MessageRender.tsx
@@ -26,20 +26,21 @@ type MessageRenderProps = {
const MessageRender = memo(
({
- isCard,
+ message: msg,
+ isCard = false,
siblingIdx,
siblingCount,
- message: msg,
setSiblingIdx,
currentEditId,
- isMultiMessage,
+ isMultiMessage = false,
setCurrentEditId,
- isSubmittingFamily,
+ isSubmittingFamily = false,
}: MessageRenderProps) => {
const {
ask,
edit,
index,
+ agent,
assistant,
enterEdit,
conversation,
@@ -56,28 +57,31 @@ const MessageRender = memo(
isMultiMessage,
setCurrentEditId,
});
- const fontSize = useRecoilValue(store.fontSize);
+
const maximizeChatSpace = useRecoilValue(store.maximizeChatSpace);
+ const fontSize = useRecoilValue(store.fontSize);
+
const handleRegenerateMessage = useCallback(() => regenerateMessage(), [regenerateMessage]);
- const { isCreatedByUser, error, unfinished } = msg ?? {};
const hasNoChildren = !(msg?.children?.length ?? 0);
const isLast = useMemo(
() => hasNoChildren && (msg?.depth === latestMessage?.depth || msg?.depth === -1),
[hasNoChildren, msg?.depth, latestMessage?.depth],
);
+ const isLatestMessage = msg?.messageId === latestMessage?.messageId;
+ const showCardRender = isLast && !isSubmittingFamily && isCard;
+ const isLatestCard = isCard && !isSubmittingFamily && isLatestMessage;
const iconData: TMessageIcon = useMemo(
() => ({
endpoint: msg?.endpoint ?? conversation?.endpoint,
model: msg?.model ?? conversation?.model,
- iconURL: msg?.iconURL ?? conversation?.iconURL,
+ iconURL: msg?.iconURL,
modelLabel: messageLabel,
isCreatedByUser: msg?.isCreatedByUser,
}),
[
messageLabel,
conversation?.endpoint,
- conversation?.iconURL,
conversation?.model,
msg?.model,
msg?.iconURL,
@@ -86,49 +90,47 @@ const MessageRender = memo(
],
);
+ const clickHandler = useMemo(
+ () =>
+ showCardRender && !isLatestMessage
+ ? () => {
+ logger.log(`Message Card click: Setting ${msg?.messageId} as latest message`);
+ logger.dir(msg);
+ setLatestMessage(msg!);
+ }
+ : undefined,
+ [showCardRender, isLatestMessage, msg, setLatestMessage],
+ );
+
if (!msg) {
return null;
}
- const isLatestMessage = msg.messageId === latestMessage?.messageId;
- const showCardRender = isLast && !(isSubmittingFamily === true) && isCard === true;
- const isLatestCard = isCard === true && !(isSubmittingFamily === true) && isLatestMessage;
- const clickHandler =
- showCardRender && !isLatestMessage
- ? () => {
- logger.log(`Message Card click: Setting ${msg.messageId} as latest message`);
- logger.dir(msg);
- setLatestMessage(msg);
- }
- : undefined;
-
- // Style classes
- const baseClasses =
- 'final-completion group mx-auto flex flex-1 gap-3 transition-all duration-300 transform-gpu';
- let layoutClasses = '';
-
- if (isCard ?? false) {
- layoutClasses =
- 'relative w-full gap-1 rounded-lg border border-border-medium bg-surface-primary-alt p-2 md:w-1/2 md:gap-3 md:p-4';
- } else if (maximizeChatSpace) {
- layoutClasses = 'md:max-w-full md:px-5';
- } else {
- layoutClasses = 'md:max-w-3xl md:px-5 lg:max-w-[40rem] lg:px-1 xl:max-w-[48rem] xl:px-5';
- }
+ const baseClasses = {
+ common: 'group mx-auto flex flex-1 gap-3 transition-all duration-300 transform-gpu ',
+ card: 'relative w-full gap-1 rounded-lg border border-border-medium bg-surface-primary-alt p-2 md:w-1/2 md:gap-3 md:p-4',
+ chat: maximizeChatSpace
+ ? 'w-full max-w-full md:px-5 lg:px-1 xl:px-5'
+ : 'md:max-w-[47rem] xl:max-w-[55rem]',
+ };
- const latestCardClasses = isLatestCard ? 'bg-surface-secondary' : '';
- const showRenderClasses = showCardRender ? 'cursor-pointer transition-colors duration-300' : '';
+ const conditionalClasses = {
+ latestCard: isLatestCard ? 'bg-surface-secondary' : '',
+ cardRender: showCardRender ? 'cursor-pointer transition-colors duration-300' : '',
+ focus: 'focus:outline-none focus:ring-2 focus:ring-border-xheavy',
+ };
return (
<div
id={msg.messageId}
aria-label={`message-${msg.depth}-${msg.messageId}`}
className={cn(
- baseClasses,
- layoutClasses,
- latestCardClasses,
- showRenderClasses,
- 'message-render focus:outline-none focus:ring-2 focus:ring-border-xheavy',
+ baseClasses.common,
+ isCard ? baseClasses.card : baseClasses.chat,
+ conditionalClasses.latestCard,
+ conditionalClasses.cardRender,
+ conditionalClasses.focus,
+ 'message-render',
)}
onClick={clickHandler}
onKeyDown={(e) => {
@@ -139,31 +141,31 @@ const MessageRender = memo(
role={showCardRender ? 'button' : undefined}
tabIndex={showCardRender ? 0 : undefined}
>
- {isLatestCard === true && (
- <div className="absolute right-0 top-0 m-2 h-3 w-3 rounded-full bg-text-primary"></div>
+ {isLatestCard && (
+ <div className="absolute right-0 top-0 m-2 h-3 w-3 rounded-full bg-text-primary" />
)}
- <div className="relative flex flex-shrink-0 flex-col items-end">
- <div>
- <div className="pt-0.5">
- <div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full">
- <MessageIcon iconData={iconData} assistant={assistant} />
- </div>
- </div>
+
+ <div className="relative flex flex-shrink-0 flex-col items-center">
+ <div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full">
+ <MessageIcon iconData={iconData} assistant={assistant} agent={agent} />
</div>
</div>
+
<div
className={cn(
'relative flex w-11/12 flex-col',
- msg.isCreatedByUser === true ? '' : 'agent-turn',
+ msg.isCreatedByUser ? 'user-turn' : 'agent-turn',
)}
>
<h2 className={cn('select-none font-semibold', fontSize)}>{messageLabel}</h2>
- <div className="flex-col gap-1 md:gap-3">
+
+ <div className="flex flex-col gap-1 md:gap-3">
<div className="flex max-w-full flex-grow flex-col gap-0">
<MessageContext.Provider
value={{
messageId: msg.messageId,
conversationId: conversation?.conversationId,
+ isExpanded: false,
}}
>
{msg.plugin && <Plugin plugin={msg.plugin} />}
@@ -174,40 +176,41 @@ const MessageRender = memo(
text={msg.text || ''}
message={msg}
enterEdit={enterEdit}
- error={!!(error ?? false)}
+ error={!!(msg.error ?? false)}
isSubmitting={isSubmitting}
- unfinished={unfinished ?? false}
- isCreatedByUser={isCreatedByUser ?? true}
+ unfinished={msg.unfinished ?? false}
+ isCreatedByUser={msg.isCreatedByUser ?? true}
siblingIdx={siblingIdx ?? 0}
setSiblingIdx={setSiblingIdx ?? (() => ({}))}
/>
</MessageContext.Provider>
</div>
+
+ {hasNoChildren && (isSubmittingFamily === true || isSubmitting) ? (
+ <PlaceholderRow isCard={isCard} />
+ ) : (
+ <SubRow classes="text-xs">
+ <SiblingSwitch
+ siblingIdx={siblingIdx}
+ siblingCount={siblingCount}
+ setSiblingIdx={setSiblingIdx}
+ />
+ <HoverButtons
+ index={index}
+ isEditing={edit}
+ message={msg}
+ enterEdit={enterEdit}
+ isSubmitting={isSubmitting}
+ conversation={conversation ?? null}
+ regenerate={handleRegenerateMessage}
+ copyToClipboard={copyToClipboard}
+ handleContinue={handleContinue}
+ latestMessage={latestMessage}
+ isLast={isLast}
+ />
+ </SubRow>
+ )}
</div>
- {hasNoChildren && (isSubmittingFamily === true || isSubmitting) ? (
- <PlaceholderRow isCard={isCard} />
- ) : (
- <SubRow classes="text-xs">
- <SiblingSwitch
- siblingIdx={siblingIdx}
- siblingCount={siblingCount}
- setSiblingIdx={setSiblingIdx}
- />
- <HoverButtons
- index={index}
- isEditing={edit}
- message={msg}
- enterEdit={enterEdit}
- isSubmitting={isSubmitting}
- conversation={conversation ?? null}
- regenerate={handleRegenerateMessage}
- copyToClipboard={copyToClipboard}
- handleContinue={handleContinue}
- latestMessage={latestMessage}
- isLast={isLast}
- />
- </SubRow>
- )}
</div>
</div>
);
diff --git a/client/src/components/Chat/Presentation.tsx b/client/src/components/Chat/Presentation.tsx
index 9228fd880c..1c596c6250 100644
--- a/client/src/components/Chat/Presentation.tsx
+++ b/client/src/components/Chat/Presentation.tsx
@@ -57,14 +57,6 @@ export default function Presentation({ children }: { children: React.ReactNode }
}, []);
const fullCollapse = useMemo(() => localStorage.getItem('fullPanelCollapse') === 'true', []);
- const layout = () => (
- <div className="transition-width relative flex h-full w-full flex-1 flex-col items-stretch overflow-hidden bg-presentation pt-0">
- <div className="flex h-full flex-col" role="presentation">
- {children}
- </div>
- </div>
- );
-
return (
<DragDropWrapper className="relative flex w-full grow overflow-hidden bg-presentation">
<SidePanelGroup
diff --git a/client/src/components/Endpoints/ConvoIcon.tsx b/client/src/components/Endpoints/ConvoIcon.tsx
index 9ecd7be39e..faed70a9b9 100644
--- a/client/src/components/Endpoints/ConvoIcon.tsx
+++ b/client/src/components/Endpoints/ConvoIcon.tsx
@@ -1,8 +1,8 @@
import React, { useMemo } from 'react';
import type * as t from 'librechat-data-provider';
import { getEndpointField, getIconKey, getEntity, getIconEndpoint } from '~/utils';
-import { icons } from '~/components/Chat/Menus/Endpoints/Icons';
import ConvoIconURL from '~/components/Endpoints/ConvoIconURL';
+import { icons } from '~/hooks/Endpoint/Icons';
export default function ConvoIcon({
conversation,
diff --git a/client/src/components/Endpoints/ConvoIconURL.tsx b/client/src/components/Endpoints/ConvoIconURL.tsx
index 3966755998..6ce0b87602 100644
--- a/client/src/components/Endpoints/ConvoIconURL.tsx
+++ b/client/src/components/Endpoints/ConvoIconURL.tsx
@@ -1,7 +1,7 @@
import { memo, useMemo } from 'react';
import type { IconMapProps } from '~/common';
-import { icons } from '~/components/Chat/Menus/Endpoints/Icons';
import { URLIcon } from '~/components/Endpoints/URLIcon';
+import { icons } from '~/hooks/Endpoint/Icons';
interface ConvoIconURLProps {
iconURL?: string;
@@ -39,12 +39,7 @@ const ConvoIconURL: React.FC<ConvoIconURLProps> = ({
agentName,
context,
}) => {
- const Icon: (
- props: IconMapProps & {
- context?: string;
- iconURL?: string;
- },
- ) => React.JSX.Element = useMemo(() => icons[iconURL] ?? icons.unknown, [iconURL]);
+ const Icon = useMemo(() => icons[iconURL] ?? icons.unknown, [iconURL]);
const isURL = useMemo(
() => !!(iconURL && (iconURL.includes('http') || iconURL.startsWith('/images/'))),
[iconURL],
@@ -63,15 +58,17 @@ const ConvoIconURL: React.FC<ConvoIconURLProps> = ({
return (
<div className="shadow-stroke relative flex h-full items-center justify-center rounded-full bg-white text-black">
- <Icon
- size={41}
- context={context}
- className="h-2/3 w-2/3"
- agentName={agentName}
- iconURL={endpointIconURL}
- assistantName={assistantName}
- avatar={assistantAvatar ?? agentAvatar}
- />
+ {Icon && (
+ <Icon
+ size={41}
+ context={context}
+ className="h-2/3 w-2/3"
+ agentName={agentName}
+ iconURL={endpointIconURL}
+ assistantName={assistantName}
+ avatar={assistantAvatar ?? agentAvatar}
+ />
+ )}
</div>
);
};
diff --git a/client/src/components/Endpoints/Icon.tsx b/client/src/components/Endpoints/Icon.tsx
index 9b9d56101a..aa9f4d16c3 100644
--- a/client/src/components/Endpoints/Icon.tsx
+++ b/client/src/components/Endpoints/Icon.tsx
@@ -1,4 +1,4 @@
-import React, { memo } from 'react';
+import React, { memo, useState } from 'react';
import type { TUser } from 'librechat-data-provider';
import type { IconProps } from '~/common';
import MessageEndpointIcon from './MessageEndpointIcon';
@@ -16,32 +16,50 @@ type UserAvatarProps = {
className?: string;
};
-const UserAvatar = memo(({ size, user, avatarSrc, username, className }: UserAvatarProps) => (
- <div
- title={username}
- style={{
- width: size,
- height: size,
- }}
- className={cn('relative flex items-center justify-center', className ?? '')}
- >
- {!(user?.avatar ?? '') && (!(user?.username ?? '') || user?.username.trim() === '') ? (
- <div
- style={{
- backgroundColor: 'rgb(121, 137, 255)',
- width: '20px',
- height: '20px',
- boxShadow: 'rgba(240, 246, 252, 0.1) 0px 0px 0px 1px',
- }}
- className="relative flex h-9 w-9 items-center justify-center rounded-sm p-1 text-white"
- >
- <UserIcon />
- </div>
- ) : (
- <img className="rounded-full" src={(user?.avatar ?? '') || avatarSrc} alt="avatar" />
- )}
- </div>
-));
+const UserAvatar = memo(({ size, user, avatarSrc, username, className }: UserAvatarProps) => {
+ const [imageError, setImageError] = useState(false);
+
+ const handleImageError = () => {
+ setImageError(true);
+ };
+
+ const renderDefaultAvatar = () => (
+ <div
+ style={{
+ backgroundColor: 'rgb(121, 137, 255)',
+ width: '20px',
+ height: '20px',
+ boxShadow: 'rgba(240, 246, 252, 0.1) 0px 0px 0px 1px',
+ }}
+ className="relative flex h-9 w-9 items-center justify-center rounded-sm p-1 text-white"
+ >
+ <UserIcon />
+ </div>
+ );
+
+ return (
+ <div
+ title={username}
+ style={{
+ width: size,
+ height: size,
+ }}
+ className={cn('relative flex items-center justify-center', className ?? '')}
+ >
+ {(!(user?.avatar ?? '') && (!(user?.username ?? '') || user?.username.trim() === '')) ||
+ imageError ? (
+ renderDefaultAvatar()
+ ) : (
+ <img
+ className="rounded-full"
+ src={(user?.avatar ?? '') || avatarSrc}
+ alt="avatar"
+ onError={handleImageError}
+ />
+ )}
+ </div>
+ );
+});
UserAvatar.displayName = 'UserAvatar';
diff --git a/client/src/components/Endpoints/MessageEndpointIcon.tsx b/client/src/components/Endpoints/MessageEndpointIcon.tsx
index 6652aa0007..be30ccc67d 100644
--- a/client/src/components/Endpoints/MessageEndpointIcon.tsx
+++ b/client/src/components/Endpoints/MessageEndpointIcon.tsx
@@ -13,7 +13,7 @@ import {
AzureMinimalIcon,
CustomMinimalIcon,
} from '~/components/svg';
-import UnknownIcon from '~/components/Chat/Menus/Endpoints/UnknownIcon';
+import UnknownIcon from '~/hooks/Endpoint/UnknownIcon';
import { IconProps } from '~/common';
import { cn } from '~/utils';
@@ -186,7 +186,7 @@ const MessageEndpointIcon: React.FC<IconProps> = (props) => {
let { icon, bg, name } =
endpoint != null && endpoint && endpointIcons[endpoint]
- ? endpointIcons[endpoint] ?? {}
+ ? (endpointIcons[endpoint] ?? {})
: (endpointIcons.default as EndpointIcon);
if (iconURL && endpointIcons[iconURL]) {
diff --git a/client/src/components/Endpoints/MinimalIcon.tsx b/client/src/components/Endpoints/MinimalIcon.tsx
index 0c7989755e..953859c43a 100644
--- a/client/src/components/Endpoints/MinimalIcon.tsx
+++ b/client/src/components/Endpoints/MinimalIcon.tsx
@@ -11,7 +11,7 @@ import {
BedrockIcon,
Sparkles,
} from '~/components/svg';
-import UnknownIcon from '~/components/Chat/Menus/Endpoints/UnknownIcon';
+import UnknownIcon from '~/hooks/Endpoint/UnknownIcon';
import { IconProps } from '~/common';
import { cn } from '~/utils';
diff --git a/client/src/components/Endpoints/URLIcon.tsx b/client/src/components/Endpoints/URLIcon.tsx
index ad7081d74e..520bf4679e 100644
--- a/client/src/components/Endpoints/URLIcon.tsx
+++ b/client/src/components/Endpoints/URLIcon.tsx
@@ -1,4 +1,6 @@
-import React, { memo } from 'react';
+import React, { memo, useState } from 'react';
+import { icons } from '~/hooks/Endpoint/Icons';
+import { AlertCircle } from 'lucide-react'; // Assuming you have lucide-react for icons
export const URLIcon = memo(
({
@@ -7,15 +9,53 @@ export const URLIcon = memo(
containerStyle = { width: '20', height: '20' },
imageStyle = { width: '100%', height: '100%' },
className = 'icon-xl mr-1 shrink-0 overflow-hidden rounded-full',
+ endpoint,
}: {
iconURL: string;
altName?: string | null;
className?: string;
containerStyle?: React.CSSProperties;
imageStyle?: React.CSSProperties;
- }) => (
- <div className={className} style={containerStyle}>
- <img src={iconURL} alt={altName ?? ''} style={imageStyle} className="object-cover" />
- </div>
- ),
+ endpoint?: string;
+ }) => {
+ const [imageError, setImageError] = useState(false);
+
+ const handleImageError = () => {
+ setImageError(true);
+ };
+
+ const DefaultIcon: React.ElementType =
+ endpoint && icons[endpoint] ? icons[endpoint]! : icons.unknown!;
+ if (imageError || !iconURL) {
+ return (
+ <div className="relative" style={{ ...containerStyle, margin: '2px' }}>
+ <div className={className}>
+ <DefaultIcon endpoint={endpoint} context="menu-item" />
+ </div>
+ {imageError && iconURL && (
+ <div
+ className="absolute flex items-center justify-center rounded-full bg-red-500"
+ style={{ width: '14px', height: '14px', top: 0, right: 0 }}
+ >
+ <AlertCircle size={10} className="text-white" />
+ </div>
+ )}
+ </div>
+ );
+ }
+
+ return (
+ <div className={className} style={containerStyle}>
+ <img
+ src={iconURL}
+ alt={altName ?? ''}
+ style={imageStyle}
+ className="object-cover"
+ onError={handleImageError}
+ />
+ </div>
+ );
+ },
);
+
+URLIcon.displayName = 'URLIcon';
diff --git a/client/src/components/Input/ModelSelect/Anthropic.tsx b/client/src/components/Input/ModelSelect/Anthropic.tsx
index 41678ac594..bbe634478b 100644
--- a/client/src/components/Input/ModelSelect/Anthropic.tsx
+++ b/client/src/components/Input/ModelSelect/Anthropic.tsx
@@ -1,7 +1,6 @@
import { SelectDropDown, SelectDropDownPop } from '~/components/ui';
import type { TModelSelectProps } from '~/common';
import { cn, cardStyle } from '~/utils/';
-import { TemporaryChat } from './TemporaryChat';
export default function Anthropic({
conversation,
@@ -22,7 +21,6 @@ export default function Anthropic({
cardStyle,
'z-50 flex h-[40px] w-48 min-w-48 flex-none items-center justify-center px-4 ring-0 hover:cursor-pointer',
)}
- footer={<TemporaryChat />}
/>
);
}
diff --git a/client/src/components/Input/ModelSelect/ChatGPT.tsx b/client/src/components/Input/ModelSelect/ChatGPT.tsx
index 3a088cd0f5..89c884429e 100644
--- a/client/src/components/Input/ModelSelect/ChatGPT.tsx
+++ b/client/src/components/Input/ModelSelect/ChatGPT.tsx
@@ -1,6 +1,5 @@
import { SelectDropDown, SelectDropDownPop } from '~/components/ui';
import type { TModelSelectProps } from '~/common';
-import { TemporaryChat } from './TemporaryChat';
import { cn, cardStyle } from '~/utils/';
export default function ChatGPT({
@@ -29,7 +28,6 @@ export default function ChatGPT({
cardStyle,
'z-50 flex h-[40px] w-60 min-w-48 flex-none items-center justify-center px-4 ring-0 hover:cursor-pointer',
)}
- footer={<TemporaryChat />}
/>
);
}
diff --git a/client/src/components/Input/ModelSelect/Google.tsx b/client/src/components/Input/ModelSelect/Google.tsx
index d9ab45f77b..eab7f95393 100644
--- a/client/src/components/Input/ModelSelect/Google.tsx
+++ b/client/src/components/Input/ModelSelect/Google.tsx
@@ -1,6 +1,5 @@
import { SelectDropDown, SelectDropDownPop } from '~/components/ui';
import type { TModelSelectProps } from '~/common';
-import { TemporaryChat } from './TemporaryChat';
import { cn, cardStyle } from '~/utils/';
export default function Google({
@@ -22,7 +21,6 @@ export default function Google({
cardStyle,
'z-50 flex h-[40px] w-48 min-w-48 flex-none items-center justify-center px-4 ring-0 hover:cursor-pointer',
)}
- footer={<TemporaryChat />}
/>
);
}
diff --git a/client/src/components/Input/ModelSelect/OpenAI.tsx b/client/src/components/Input/ModelSelect/OpenAI.tsx
index c95e5b3cdf..5b68cb440c 100644
--- a/client/src/components/Input/ModelSelect/OpenAI.tsx
+++ b/client/src/components/Input/ModelSelect/OpenAI.tsx
@@ -1,6 +1,5 @@
import { SelectDropDown, SelectDropDownPop } from '~/components/ui';
import type { TModelSelectProps } from '~/common';
-import { TemporaryChat } from './TemporaryChat';
import { cn, cardStyle } from '~/utils/';
export default function OpenAI({
@@ -22,7 +21,6 @@ export default function OpenAI({
cardStyle,
'z-50 flex h-[40px] w-48 min-w-48 flex-none items-center justify-center px-4 hover:cursor-pointer',
)}
- footer={<TemporaryChat />}
/>
);
}
diff --git a/client/src/components/Input/ModelSelect/TemporaryChat.tsx b/client/src/components/Input/ModelSelect/TemporaryChat.tsx
deleted file mode 100644
index 3b0cae4912..0000000000
--- a/client/src/components/Input/ModelSelect/TemporaryChat.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-import { useMemo } from 'react';
-
-import { MessageCircleDashed } from 'lucide-react';
-import { useRecoilState, useRecoilValue } from 'recoil';
-import { Constants, getConfigDefaults } from 'librechat-data-provider';
-import { useGetStartupConfig } from '~/data-provider';
-import { Switch } from '~/components/ui';
-import { useLocalize } from '~/hooks';
-import { cn } from '~/utils';
-import store from '~/store';
-
-export const TemporaryChat = () => {
- const localize = useLocalize();
- const { data: startupConfig } = useGetStartupConfig();
- const defaultInterface = getConfigDefaults().interface;
- const [isTemporary, setIsTemporary] = useRecoilState(store.isTemporary);
- const conversation = useRecoilValue(store.conversationByIndex(0)) || undefined;
- const conversationId = conversation?.conversationId ?? '';
- const interfaceConfig = useMemo(
- () => startupConfig?.interface ?? defaultInterface,
- [startupConfig],
- );
-
- if (interfaceConfig.temporaryChat === false) {
- return null;
- }
-
- const isActiveConvo = Boolean(
- conversation &&
- conversationId &&
- conversationId !== Constants.NEW_CONVO &&
- conversationId !== 'search',
- );
-
- const onClick = () => {
- if (isActiveConvo) {
- return;
- }
- setIsTemporary(!isTemporary);
- };
-
- return (
- <div className="sticky bottom-0 mt-auto w-full border-none bg-surface-tertiary px-6 py-4">
- <div className="flex items-center justify-between">
- <div className={cn('flex items-center gap-2', isActiveConvo && 'opacity-40')}>
- <MessageCircleDashed className="icon-sm" aria-hidden="true" />
- <span className="truncate text-sm text-text-primary">
- {localize('com_ui_temporary_chat')}
- </span>
- </div>
- <div className="flex flex-shrink-0 items-center">
- <Switch
- id="temporary-chat-switch"
- checked={isTemporary}
- onCheckedChange={onClick}
- disabled={isActiveConvo}
- className="ml-4"
- aria-label="Toggle temporary chat"
- data-testid="temporary-chat-switch"
- />
- </div>
- </div>
- </div>
- );
-};
diff --git a/client/src/components/Messages/Content/CodeBlock.tsx b/client/src/components/Messages/Content/CodeBlock.tsx
index df80c90ecb..978f95eb02 100644
--- a/client/src/components/Messages/Content/CodeBlock.tsx
+++ b/client/src/components/Messages/Content/CodeBlock.tsx
@@ -119,7 +119,7 @@ const CodeBlock: React.FC<CodeBlockProps> = ({
const language = isNonCode ? 'json' : lang;
return (
- <div className="w-full rounded-md bg-gray-900 text-xs text-white/80">
+ <div className="w-full rounded-md bg-surface-primary text-xs text-white/80">
<CodeBar
lang={lang}
error={error}
diff --git a/client/src/components/Messages/ContentRender.tsx b/client/src/components/Messages/ContentRender.tsx
index b06819aaaa..6c141790e2 100644
--- a/client/src/components/Messages/ContentRender.tsx
+++ b/client/src/components/Messages/ContentRender.tsx
@@ -24,18 +24,17 @@ type ContentRenderProps = {
const ContentRender = memo(
({
- isCard,
+ message: msg,
+ isCard = false,
siblingIdx,
siblingCount,
- message: msg,
setSiblingIdx,
currentEditId,
- isMultiMessage,
+ isMultiMessage = false,
setCurrentEditId,
- isSubmittingFamily,
+ isSubmittingFamily = false,
}: ContentRenderProps) => {
const {
- // ask,
edit,
index,
agent,
@@ -58,26 +57,28 @@ const ContentRender = memo(
const maximizeChatSpace = useRecoilValue(store.maximizeChatSpace);
const fontSize = useRecoilValue(store.fontSize);
+
const handleRegenerateMessage = useCallback(() => regenerateMessage(), [regenerateMessage]);
- // const { isCreatedByUser, error, unfinished } = msg ?? {};
const isLast = useMemo(
() =>
!(msg?.children?.length ?? 0) && (msg?.depth === latestMessage?.depth || msg?.depth === -1),
[msg?.children, msg?.depth, latestMessage?.depth],
);
+ const isLatestMessage = msg?.messageId === latestMessage?.messageId;
+ const showCardRender = isLast && !isSubmittingFamily && isCard;
+ const isLatestCard = isCard && !isSubmittingFamily && isLatestMessage;
const iconData: TMessageIcon = useMemo(
() => ({
endpoint: msg?.endpoint ?? conversation?.endpoint,
model: msg?.model ?? conversation?.model,
- iconURL: msg?.iconURL ?? conversation?.iconURL,
+ iconURL: msg?.iconURL,
modelLabel: messageLabel,
isCreatedByUser: msg?.isCreatedByUser,
}),
[
messageLabel,
conversation?.endpoint,
- conversation?.iconURL,
conversation?.model,
msg?.model,
msg?.iconURL,
@@ -86,31 +87,29 @@ const ContentRender = memo(
],
);
+ const clickHandler = useMemo(
+ () =>
+ showCardRender && !isLatestMessage
+ ? () => {
+ logger.log(`Message Card click: Setting ${msg?.messageId} as latest message`);
+ logger.dir(msg);
+ setLatestMessage(msg!);
+ }
+ : undefined,
+ [showCardRender, isLatestMessage, msg, setLatestMessage],
+ );
+
if (!msg) {
return null;
}
- const isLatestMessage = msg.messageId === latestMessage?.messageId;
- const showCardRender = isLast && !(isSubmittingFamily === true) && isCard === true;
- const isLatestCard = isCard === true && !(isSubmittingFamily === true) && isLatestMessage;
- const clickHandler =
- showCardRender && !isLatestMessage
- ? () => {
- logger.log(`Message Card click: Setting ${msg.messageId} as latest message`);
- logger.dir(msg);
- setLatestMessage(msg);
- }
- : undefined;
-
- const baseClasses =
- 'final-completion group mx-auto flex flex-1 gap-3 transition-all duration-300 transform-gpu';
-
- const cardClasses =
- 'relative w-full gap-1 rounded-lg border border-border-medium bg-surface-primary-alt p-2 md:w-1/2 md:gap-3 md:p-4';
-
- const chatSpaceClasses = maximizeChatSpace
- ? 'w-full max-w-full md:px-5 lg:px-1 xl:px-5'
- : 'md:max-w-3xl md:px-5 lg:max-w-[40rem] lg:px-1 xl:max-w-[48rem] xl:px-5';
+ const baseClasses = {
+ common: 'group mx-auto flex flex-1 gap-3 transition-all duration-300 transform-gpu ',
+ card: 'relative w-full gap-1 rounded-lg border border-border-medium bg-surface-primary-alt p-2 md:w-1/2 md:gap-3 md:p-4',
+ chat: maximizeChatSpace
+ ? 'w-full max-w-full md:px-5 lg:px-1 xl:px-5'
+ : 'md:max-w-[47rem] xl:max-w-[55rem]',
+ };
const conditionalClasses = {
latestCard: isLatestCard ? 'bg-surface-secondary' : '',
@@ -123,8 +122,8 @@ const ContentRender = memo(
id={msg.messageId}
aria-label={`message-${msg.depth}-${msg.messageId}`}
className={cn(
- baseClasses,
- isCard === true ? cardClasses : chatSpaceClasses,
+ baseClasses.common,
+ isCard ? baseClasses.card : baseClasses.chat,
conditionalClasses.latestCard,
conditionalClasses.cardRender,
conditionalClasses.focus,
@@ -139,26 +138,25 @@ const ContentRender = memo(
role={showCardRender ? 'button' : undefined}
tabIndex={showCardRender ? 0 : undefined}
>
- {isLatestCard === true && (
+ {isLatestCard && (
<div className="absolute right-0 top-0 m-2 h-3 w-3 rounded-full bg-text-primary" />
)}
- <div className="relative flex flex-shrink-0 flex-col items-end">
- <div>
- <div className="pt-0.5">
- <div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full">
- <MessageIcon iconData={iconData} assistant={assistant} agent={agent} />
- </div>
- </div>
+
+ <div className="relative flex flex-shrink-0 flex-col items-center">
+ <div className="flex h-6 w-6 items-center justify-center overflow-hidden rounded-full">
+ <MessageIcon iconData={iconData} assistant={assistant} agent={agent} />
</div>
</div>
+
<div
className={cn(
'relative flex w-11/12 flex-col',
- msg.isCreatedByUser === true ? '' : 'agent-turn',
+ msg.isCreatedByUser ? 'user-turn' : 'agent-turn',
)}
>
<h2 className={cn('select-none font-semibold', fontSize)}>{messageLabel}</h2>
- <div className="flex-col gap-1 md:gap-3">
+
+ <div className="flex flex-col gap-1 md:gap-3">
<div className="flex max-w-full flex-grow flex-col gap-0">
<ContentParts
edit={edit}
@@ -174,31 +172,32 @@ const ContentRender = memo(
content={msg.content as Array<TMessageContentParts | undefined>}
/>
</div>
+
+ {(isSubmittingFamily || isSubmitting) && !(msg.children?.length ?? 0) ? (
+ <PlaceholderRow isCard={isCard} />
+ ) : (
+ <SubRow classes="text-xs">
+ <SiblingSwitch
+ siblingIdx={siblingIdx}
+ siblingCount={siblingCount}
+ setSiblingIdx={setSiblingIdx}
+ />
+ <HoverButtons
+ index={index}
+ isEditing={edit}
+ message={msg}
+ enterEdit={enterEdit}
+ isSubmitting={isSubmitting}
+ conversation={conversation ?? null}
+ regenerate={handleRegenerateMessage}
+ copyToClipboard={copyToClipboard}
+ handleContinue={handleContinue}
+ latestMessage={latestMessage}
+ isLast={isLast}
+ />
+ </SubRow>
+ )}
</div>
- {!(msg.children?.length ?? 0) && (isSubmittingFamily === true || isSubmitting) ? (
- <PlaceholderRow isCard={isCard} />
- ) : (
- <SubRow classes="text-xs">
- <SiblingSwitch
- siblingIdx={siblingIdx}
- siblingCount={siblingCount}
- setSiblingIdx={setSiblingIdx}
- />
- <HoverButtons
- index={index}
- isEditing={edit}
- message={msg}
- enterEdit={enterEdit}
- isSubmitting={isSubmitting}
- conversation={conversation ?? null}
- regenerate={handleRegenerateMessage}
- copyToClipboard={copyToClipboard}
- handleContinue={handleContinue}
- latestMessage={latestMessage}
- isLast={isLast}
- />
- </SubRow>
- )}
</div>
</div>
);
diff --git a/client/src/components/Messages/ScrollToBottom.tsx b/client/src/components/Messages/ScrollToBottom.tsx
index 58c014c1e1..bb67cfe3df 100644
--- a/client/src/components/Messages/ScrollToBottom.tsx
+++ b/client/src/components/Messages/ScrollToBottom.tsx
@@ -8,16 +8,10 @@ export default function ScrollToBottom({ scrollHandler }: Props) {
return (
<button
onClick={scrollHandler}
- className="absolute bottom-5 right-1/2 cursor-pointer rounded-full border border-gray-200 bg-white bg-clip-padding text-gray-600 dark:border-white/10 dark:bg-gray-850/90 dark:text-gray-200"
+ className="premium-scroll-button absolute bottom-5 right-1/2 cursor-pointer border border-border-light bg-surface-secondary"
aria-label="Scroll to bottom"
>
- <svg
- width="24"
- height="24"
- viewBox="0 0 24 24"
- fill="none"
- className="m-1 text-black dark:text-white"
- >
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" className="text-text-secondary">
<path
d="M17 13L12 18L7 13M12 6L12 17"
stroke="currentColor"
diff --git a/client/src/components/Nav/NewChat.tsx b/client/src/components/Nav/NewChat.tsx
index d691fa7bdf..c31a19b679 100644
--- a/client/src/components/Nav/NewChat.tsx
+++ b/client/src/components/Nav/NewChat.tsx
@@ -5,10 +5,10 @@ import { useQueryClient } from '@tanstack/react-query';
import { QueryKeys, Constants } from 'librechat-data-provider';
import type { TConversation, TMessage } from 'librechat-data-provider';
import { getEndpointField, getIconEndpoint, getIconKey } from '~/utils';
-import { icons } from '~/components/Chat/Menus/Endpoints/Icons';
import ConvoIconURL from '~/components/Endpoints/ConvoIconURL';
import { useGetEndpointsQuery } from '~/data-provider';
import { useLocalize, useNewConvo } from '~/hooks';
+import { icons } from '~/hooks/Endpoint/Icons';
import { NewChatIcon } from '~/components/svg';
import { cn } from '~/utils';
import store from '~/store';
diff --git a/client/src/components/Nav/SettingsTabs/Beta/Beta.tsx b/client/src/components/Nav/SettingsTabs/Beta/Beta.tsx
index 268bba2323..8aeaf554cd 100644
--- a/client/src/components/Nav/SettingsTabs/Beta/Beta.tsx
+++ b/client/src/components/Nav/SettingsTabs/Beta/Beta.tsx
@@ -1,5 +1,6 @@
import { memo } from 'react';
import CodeArtifacts from './CodeArtifacts';
+import ChatBadges from './ChatBadges';
function Beta() {
return (
@@ -7,6 +8,9 @@ function Beta() {
<div className="pb-3">
<CodeArtifacts />
</div>
+ {/* <div className="pb-3">
+ <ChatBadges />
+ </div> */}
</div>
);
}
diff --git a/client/src/components/Nav/SettingsTabs/Beta/ChatBadges.tsx b/client/src/components/Nav/SettingsTabs/Beta/ChatBadges.tsx
new file mode 100644
index 0000000000..8e5eddb138
--- /dev/null
+++ b/client/src/components/Nav/SettingsTabs/Beta/ChatBadges.tsx
@@ -0,0 +1,22 @@
+import { useSetRecoilState } from 'recoil';
+import { Button } from '~/components/ui';
+import { useLocalize } from '~/hooks';
+import store from '~/store';
+
+export default function ChatBadges() {
+ const setIsEditing = useSetRecoilState<boolean>(store.isEditingBadges);
+ const localize = useLocalize();
+
+ const handleEditChatBadges = () => {
+ setIsEditing(true);
+ };
+
+ return (
+ <div className="flex items-center justify-between">
+ <div>{localize('com_nav_edit_chat_badges')}</div>
+ <Button variant="outline" onClick={handleEditChatBadges}>
+ {localize('com_ui_edit')}
+ </Button>
+ </div>
+ );
+}
diff --git a/client/src/components/Nav/SettingsTabs/Chat/CenterChatInput.tsx b/client/src/components/Nav/SettingsTabs/Chat/CenterChatInput.tsx
new file mode 100644
index 0000000000..dc1477e51a
--- /dev/null
+++ b/client/src/components/Nav/SettingsTabs/Chat/CenterChatInput.tsx
@@ -0,0 +1,34 @@
+import { useRecoilState } from 'recoil';
+import HoverCardSettings from '../HoverCardSettings';
+import { Switch } from '~/components/ui/Switch';
+import useLocalize from '~/hooks/useLocalize';
+import store from '~/store';
+
+export default function CenterChatInput({
+ onCheckedChange,
+}: {
+ onCheckedChange?: (value: boolean) => void;
+}) {
+ const [centerFormOnLanding, setcenterFormOnLanding] = useRecoilState(store.centerFormOnLanding);
+ const localize = useLocalize();
+
+ const handleCheckedChange = (value: boolean) => {
+ setcenterFormOnLanding(value);
+ if (onCheckedChange) {
+ onCheckedChange(value);
+ }
+ };
+
+ return (
+ <div className="flex items-center justify-between">
+ <div>{localize('com_nav_center_chat_input')}</div>
+ <Switch
+ id="centerFormOnLanding"
+ checked={centerFormOnLanding}
+ onCheckedChange={handleCheckedChange}
+ className="ml-4"
+ data-testid="centerFormOnLanding"
+ />
+ </div>
+ );
+}
diff --git a/client/src/components/Nav/SettingsTabs/Chat/Chat.tsx b/client/src/components/Nav/SettingsTabs/Chat/Chat.tsx
index 1fd2e5c7bd..7e5b19ed46 100644
--- a/client/src/components/Nav/SettingsTabs/Chat/Chat.tsx
+++ b/client/src/components/Nav/SettingsTabs/Chat/Chat.tsx
@@ -2,6 +2,7 @@ import { memo } from 'react';
import MaximizeChatSpace from './MaximizeChatSpace';
import FontSizeSelector from './FontSizeSelector';
import SendMessageKeyEnter from './EnterToSend';
+import CenterChatInput from './CenterChatInput';
import ShowCodeSwitch from './ShowCodeSwitch';
import { ForkSettings } from './ForkSettings';
import ChatDirection from './ChatDirection';
@@ -20,6 +21,9 @@ function Chat() {
<div className="pb-3">
<ChatDirection />
</div>
+ <div className="pb-3">
+ <CenterChatInput />
+ </div>
<div className="pb-3">
<SendMessageKeyEnter />
</div>
diff --git a/client/src/components/SidePanel/AgentSwitcher.tsx b/client/src/components/SidePanel/AgentSwitcher.tsx
deleted file mode 100644
index b3b73e2672..0000000000
--- a/client/src/components/SidePanel/AgentSwitcher.tsx
+++ /dev/null
@@ -1,88 +0,0 @@
-import { useEffect, useMemo } from 'react';
-import { EModelEndpoint, isAgentsEndpoint, LocalStorageKeys } from 'librechat-data-provider';
-import type { Agent } from 'librechat-data-provider';
-import type { SwitcherProps, OptionWithIcon } from '~/common';
-import { useSetIndexOptions, useSelectAgent, useLocalize } from '~/hooks';
-import { useChatContext, useAgentsMapContext } from '~/Providers';
-import ControlCombobox from '~/components/ui/ControlCombobox';
-import Icon from '~/components/Endpoints/Icon';
-
-export default function AgentSwitcher({ isCollapsed }: SwitcherProps) {
- const localize = useLocalize();
- const { setOption } = useSetIndexOptions();
- const { index, conversation } = useChatContext();
- const { agent_id: selectedAgentId = null, endpoint } = conversation ?? {};
-
- const agentsMapResult = useAgentsMapContext();
-
- const agentsMap = useMemo(() => {
- return agentsMapResult ?? {};
- }, [agentsMapResult]);
-
- const { onSelect } = useSelectAgent();
-
- const agents: Agent[] = useMemo(() => {
- return Object.values(agentsMap) as Agent[];
- }, [agentsMap]);
-
- useEffect(() => {
- if (selectedAgentId == null && agents.length > 0) {
- let agent_id = localStorage.getItem(`${LocalStorageKeys.AGENT_ID_PREFIX}${index}`);
- if (agent_id == null) {
- agent_id = agents[0].id;
- }
- const agent = agentsMap[agent_id];
-
- if (agent !== undefined && isAgentsEndpoint(endpoint as string) === true) {
- setOption('model')('');
- setOption('agent_id')(agent_id);
- }
- }
- }, [index, agents, selectedAgentId, agentsMap, endpoint, setOption]);
-
- const currentAgent = agentsMap[selectedAgentId ?? ''];
-
- const agentOptions: OptionWithIcon[] = useMemo(
- () =>
- agents.map((agent: Agent) => {
- return {
- label: agent.name ?? '',
- value: agent.id,
- icon: (
- <Icon
- isCreatedByUser={false}
- endpoint={EModelEndpoint.agents}
- agentName={agent.name ?? ''}
- iconURL={agent.avatar?.filepath}
- />
- ),
- };
- }),
- [agents],
- );
-
- return (
- <ControlCombobox
- selectedValue={currentAgent?.id ?? ''}
- displayValue={
- agents.find((agent: Agent) => agent.id === selectedAgentId)?.name ??
- localize('com_sidepanel_select_agent')
- }
- selectPlaceholder={localize('com_sidepanel_select_agent')}
- searchPlaceholder={localize('com_agents_search_name')}
- isCollapsed={isCollapsed}
- ariaLabel={'agent'}
- setValue={onSelect}
- items={agentOptions}
- iconClassName="assistant-item"
- SelectIcon={
- <Icon
- isCreatedByUser={false}
- endpoint={endpoint}
- agentName={currentAgent?.name ?? ''}
- iconURL={currentAgent?.avatar?.filepath ?? ''}
- />
- }
- />
- );
-}
diff --git a/client/src/components/SidePanel/Agents/AgentConfig.tsx b/client/src/components/SidePanel/Agents/AgentConfig.tsx
index 864ecd8173..f914a14288 100644
--- a/client/src/components/SidePanel/Agents/AgentConfig.tsx
+++ b/client/src/components/SidePanel/Agents/AgentConfig.tsx
@@ -6,9 +6,9 @@ import type { TPlugin } from 'librechat-data-provider';
import type { AgentForm, AgentPanelProps, IconComponentTypes } from '~/common';
import { cn, defaultTextProps, removeFocusOutlines, getEndpointField, getIconKey } from '~/utils';
import { useToastContext, useFileMapContext } from '~/Providers';
-import { icons } from '~/components/Chat/Menus/Endpoints/Icons';
import Action from '~/components/SidePanel/Builder/Action';
import { ToolSelectDialog } from '~/components/Tools';
+import { icons } from '~/hooks/Endpoint/Icons';
import { processAgentOption } from '~/utils';
import AgentAvatar from './AgentAvatar';
import FileContext from './FileContext';
diff --git a/client/src/components/SidePanel/AssistantSwitcher.tsx b/client/src/components/SidePanel/AssistantSwitcher.tsx
deleted file mode 100644
index 56ed80bb84..0000000000
--- a/client/src/components/SidePanel/AssistantSwitcher.tsx
+++ /dev/null
@@ -1,92 +0,0 @@
-import { useEffect, useMemo } from 'react';
-import { isAssistantsEndpoint, LocalStorageKeys } from 'librechat-data-provider';
-import type { AssistantsEndpoint } from 'librechat-data-provider';
-import type { SwitcherProps, AssistantListItem } from '~/common';
-import { useSetIndexOptions, useSelectAssistant, useLocalize, useAssistantListMap } from '~/hooks';
-import { useChatContext, useAssistantsMapContext } from '~/Providers';
-import ControlCombobox from '~/components/ui/ControlCombobox';
-import Icon from '~/components/Endpoints/Icon';
-
-export default function AssistantSwitcher({ isCollapsed }: SwitcherProps) {
- const localize = useLocalize();
- const { setOption } = useSetIndexOptions();
- const { index, conversation } = useChatContext();
-
- /* `selectedAssistant` must be defined with `null` to cause re-render on update */
- const { assistant_id: selectedAssistant = null, endpoint } = conversation ?? {};
-
- const assistantListMap = useAssistantListMap((res) =>
- res.data.map(({ id, name, metadata }) => ({ id, name, metadata })),
- );
- const assistants: Omit<AssistantListItem, 'model'>[] = useMemo(
- () => assistantListMap[endpoint ?? ''] ?? [],
- [endpoint, assistantListMap],
- );
- const assistantMap = useAssistantsMapContext();
- const { onSelect } = useSelectAssistant(endpoint as AssistantsEndpoint);
-
- useEffect(() => {
- if (!selectedAssistant && assistants && assistants.length && assistantMap) {
- const assistant_id =
- localStorage.getItem(`${LocalStorageKeys.ASST_ID_PREFIX}${index}${endpoint}`) ??
- assistants[0]?.id ??
- '';
- const assistant = assistantMap[endpoint ?? ''][assistant_id];
-
- if (!assistant) {
- return;
- }
-
- if (!isAssistantsEndpoint(endpoint)) {
- return;
- }
-
- setOption('model')(assistant.model);
- setOption('assistant_id')(assistant_id);
- }
- }, [index, assistants, selectedAssistant, assistantMap, endpoint, setOption]);
-
- const currentAssistant = assistantMap?.[endpoint ?? '']?.[selectedAssistant ?? ''];
-
- const assistantOptions = useMemo(() => {
- return assistants.map((assistant) => {
- return {
- label: (assistant.name as string | null) ?? '',
- value: assistant.id,
- icon: (
- <Icon
- isCreatedByUser={false}
- endpoint={endpoint}
- assistantName={(assistant.name as string | null) ?? ''}
- iconURL={assistant.metadata?.avatar ?? ''}
- />
- ),
- };
- });
- }, [assistants, endpoint]);
-
- return (
- <ControlCombobox
- selectedValue={currentAssistant?.id ?? ''}
- displayValue={
- assistants.find((assistant) => assistant.id === selectedAssistant)?.name ??
- localize('com_sidepanel_select_assistant')
- }
- selectPlaceholder={localize('com_sidepanel_select_assistant')}
- searchPlaceholder={localize('com_assistants_search_name')}
- isCollapsed={isCollapsed}
- ariaLabel={'assistant'}
- setValue={onSelect}
- items={assistantOptions}
- iconClassName="assistant-item"
- SelectIcon={
- <Icon
- isCreatedByUser={false}
- endpoint={endpoint}
- assistantName={currentAssistant?.name ?? ''}
- iconURL={currentAssistant?.metadata?.avatar ?? ''}
- />
- }
- />
- );
-}
diff --git a/client/src/components/SidePanel/ModelSwitcher.tsx b/client/src/components/SidePanel/ModelSwitcher.tsx
deleted file mode 100644
index 6c8d79a38e..0000000000
--- a/client/src/components/SidePanel/ModelSwitcher.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-import { useMemo, useRef, useCallback } from 'react';
-import { useGetModelsQuery } from 'librechat-data-provider/react-query';
-import type { SwitcherProps } from '~/common';
-import ControlCombobox from '~/components/ui/ControlCombobox';
-import MinimalIcon from '~/components/Endpoints/MinimalIcon';
-import { useSetIndexOptions, useLocalize } from '~/hooks';
-import { useChatContext } from '~/Providers';
-import { mainTextareaId } from '~/common';
-
-export default function ModelSwitcher({ isCollapsed }: SwitcherProps) {
- const localize = useLocalize();
- const modelsQuery = useGetModelsQuery();
- const { conversation } = useChatContext();
- const { setOption } = useSetIndexOptions();
- const timeoutIdRef = useRef<NodeJS.Timeout>();
-
- const { endpoint, model = null } = conversation ?? {};
- const models = useMemo(() => {
- return (modelsQuery.data?.[endpoint ?? ''] ?? []).map((model) => ({
- label: model,
- value: model,
- }));
- }, [modelsQuery, endpoint]);
-
- const setModel = useCallback(
- (model: string) => {
- setOption('model')(model);
- clearTimeout(timeoutIdRef.current);
- timeoutIdRef.current = setTimeout(() => {
- const textarea = document.getElementById(mainTextareaId);
- if (textarea) {
- textarea.focus();
- }
- }, 150);
- },
- [setOption],
- );
-
- return (
- <ControlCombobox
- displayValue={model ?? ''}
- selectPlaceholder={localize('com_ui_select_model')}
- searchPlaceholder={localize('com_ui_select_search_model')}
- isCollapsed={isCollapsed}
- ariaLabel={'model'}
- selectedValue={model ?? ''}
- setValue={setModel}
- items={models}
- SelectIcon={
- <MinimalIcon
- isCreatedByUser={false}
- endpoint={endpoint}
- // iconURL={} // for future preset icons
- />
- }
- />
- );
-}
diff --git a/client/src/components/SidePanel/Parameters/settings.ts b/client/src/components/SidePanel/Parameters/settings.ts
index b3f1b0c391..4e905ee98b 100644
--- a/client/src/components/SidePanel/Parameters/settings.ts
+++ b/client/src/components/SidePanel/Parameters/settings.ts
@@ -479,7 +479,7 @@ const googleCol2: SettingsConfiguration = [
];
const openAI: SettingsConfiguration = [
- openAIParams.chatGptLabel,
+ librechat.modelLabel,
librechat.promptPrefix,
librechat.maxContextTokens,
openAIParams.max_tokens,
@@ -495,7 +495,7 @@ const openAI: SettingsConfiguration = [
const openAICol1: SettingsConfiguration = [
baseDefinitions.model as SettingDefinition,
- openAIParams.chatGptLabel,
+ librechat.modelLabel,
librechat.promptPrefix,
];
diff --git a/client/src/components/SidePanel/SidePanel.tsx b/client/src/components/SidePanel/SidePanel.tsx
index a3498ba0c1..b01a971330 100644
--- a/client/src/components/SidePanel/SidePanel.tsx
+++ b/client/src/components/SidePanel/SidePanel.tsx
@@ -9,7 +9,7 @@ import { useGetEndpointsQuery } from '~/data-provider';
import NavToggle from '~/components/Nav/NavToggle';
import { cn, getEndpointField } from '~/utils';
import { useChatContext } from '~/Providers';
-import Switcher from './Switcher';
+
import Nav from './Nav';
const defaultMinSize = 20;
@@ -163,27 +163,13 @@ const SidePanel = ({
localStorage.setItem('react-resizable-panels:collapsed', 'true');
}}
className={cn(
- 'sidenav hide-scrollbar border-l border-border-light bg-background transition-opacity',
+ 'sidenav hide-scrollbar border-l border-border-light bg-background py-1 transition-opacity',
isCollapsed ? 'min-w-[50px]' : 'min-w-[340px] sm:min-w-[352px]',
(isSmallScreen && isCollapsed && (minSize === 0 || collapsedSize === 0)) || fullCollapse
? 'hidden min-w-0'
: 'opacity-100',
)}
>
- {interfaceConfig.modelSelect === true && (
- <div
- className={cn(
- 'sticky left-0 right-0 top-0 z-[100] flex h-[52px] flex-wrap items-center justify-center bg-background',
- isCollapsed ? 'h-[52px]' : 'px-2',
- )}
- >
- <Switcher
- isCollapsed={isCollapsed}
- endpointKeyProvided={keyProvided}
- endpoint={endpoint}
- />
- </div>
- )}
<Nav
resize={panelRef.current?.resize}
isCollapsed={isCollapsed}
diff --git a/client/src/components/SidePanel/Switcher.tsx b/client/src/components/SidePanel/Switcher.tsx
deleted file mode 100644
index b3d23108a3..0000000000
--- a/client/src/components/SidePanel/Switcher.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import { isAssistantsEndpoint, isAgentsEndpoint } from 'librechat-data-provider';
-import type { SwitcherProps } from '~/common';
-import AssistantSwitcher from './AssistantSwitcher';
-import AgentSwitcher from './AgentSwitcher';
-import ModelSwitcher from './ModelSwitcher';
-
-export default function Switcher(props: SwitcherProps) {
- if (isAssistantsEndpoint(props.endpoint) && props.endpointKeyProvided) {
- return <AssistantSwitcher {...props} />;
- } else if (isAgentsEndpoint(props.endpoint) && props.endpointKeyProvided) {
- return <AgentSwitcher {...props} />;
- } else if (isAssistantsEndpoint(props.endpoint)) {
- return null;
- }
-
- return <ModelSwitcher {...props} />;
-}
diff --git a/client/src/components/svg/BirthdayIcon.tsx b/client/src/components/svg/BirthdayIcon.tsx
index fb7ab029b8..979751bd05 100644
--- a/client/src/components/svg/BirthdayIcon.tsx
+++ b/client/src/components/svg/BirthdayIcon.tsx
@@ -8,7 +8,7 @@ export default function BirthdayIcon({ className = '' }) {
viewBox="0 0 233.33 290"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
- className={cn('h-11 w-11', className)}
+ className={cn('h-9 w-9', className)}
>
<defs>
<linearGradient
diff --git a/client/src/components/ui/Badge.tsx b/client/src/components/ui/Badge.tsx
new file mode 100644
index 0000000000..b29a953d29
--- /dev/null
+++ b/client/src/components/ui/Badge.tsx
@@ -0,0 +1,83 @@
+import { X, Plus } from 'lucide-react';
+import { motion } from 'framer-motion';
+import type { ButtonHTMLAttributes } from 'react';
+import type { LucideIcon } from 'lucide-react';
+import { cn } from '~/utils';
+
+interface BadgeProps extends ButtonHTMLAttributes<HTMLButtonElement> {
+ icon?: LucideIcon;
+ label: string;
+ isActive?: boolean;
+ isEditing?: boolean;
+ isDragging?: boolean;
+ isAvailable: boolean;
+ onBadgeAction?: () => void;
+ onToggle?: () => void;
+}
+
+export default function Badge({
+ icon: Icon,
+ label,
+ isActive = false,
+ isEditing = false,
+ isDragging = false,
+ isAvailable = true,
+ onBadgeAction,
+ onToggle,
+ className,
+ ...props
+}: BadgeProps) {
+ const isMoveable = isEditing && isAvailable;
+
+ const handleClick: React.MouseEventHandler<HTMLButtonElement> = (e) => {
+ if (!isEditing && onToggle) {
+ if (typeof window !== 'undefined' && window.innerWidth >= 768) {
+ e.preventDefault();
+ }
+ e.stopPropagation();
+ onToggle();
+ }
+ };
+
+ return (
+ <motion.button
+ onClick={handleClick}
+ className={cn(
+ 'group relative inline-flex items-center gap-1.5 rounded-full px-4 py-1.5',
+ 'border border-border-medium text-sm font-medium transition-shadow',
+ isActive
+ ? 'bg-surface-active shadow-md'
+ : 'bg-surface-chat shadow-sm hover:bg-surface-hover hover:shadow-md',
+ isMoveable && 'cursor-move',
+ className,
+ )}
+ animate={{
+ scale: isDragging ? 1.1 : 1,
+ boxShadow: isDragging ? '0 10px 25px rgba(0,0,0,0.1)' : undefined,
+ }}
+ whileTap={{ scale: isDragging ? 1.1 : 0.97 }}
+ transition={{ type: 'tween', duration: 0.1, ease: 'easeOut' }}
+ {...props}
+ >
+ {Icon && <Icon className="relative h-4 w-4" />}
+ <span className="relative hidden md:inline">{label}</span>
+
+ {isEditing && !isDragging && (
+ <motion.button
+ className="absolute -right-1 -top-1 flex h-5 w-5 items-center justify-center rounded-full bg-surface-secondary-alt text-text-primary"
+ initial={{ opacity: 0, scale: 0.8 }}
+ animate={{ opacity: 1, scale: 1 }}
+ exit={{ opacity: 0, scale: 0.8 }}
+ whileTap={{ scale: 0.9 }}
+ onMouseDown={(e) => e.stopPropagation()}
+ onClick={(e) => {
+ e.stopPropagation();
+ onBadgeAction?.();
+ }}
+ >
+ {isAvailable ? <X className="h-3 w-3" /> : <Plus className="h-3 w-3" />}
+ </motion.button>
+ )}
+ </motion.button>
+ );
+}
diff --git a/client/src/components/ui/ControlCombobox.tsx b/client/src/components/ui/ControlCombobox.tsx
index 005df7b3e1..c3d00b0d2d 100644
--- a/client/src/components/ui/ControlCombobox.tsx
+++ b/client/src/components/ui/ControlCombobox.tsx
@@ -107,7 +107,7 @@ function ControlCombobox({
'flex items-center justify-center gap-2 rounded-full bg-surface-secondary',
'text-text-primary hover:bg-surface-tertiary',
'border border-border-light',
- isCollapsed ? 'h-10 w-10' : 'h-10 w-full rounded-md px-3 py-2 text-sm',
+ isCollapsed ? 'h-10 w-10' : 'h-10 w-full rounded-xl px-3 py-2 text-sm',
className,
)}
>
@@ -132,17 +132,19 @@ function ControlCombobox({
store={select}
gutter={4}
portal
- className="z-50 overflow-hidden rounded-md border border-border-light bg-surface-secondary shadow-lg"
+ className={cn(
+ 'animate-popover z-50 overflow-hidden rounded-xl border border-border-light bg-surface-secondary shadow-lg',
+ )}
style={{ width: isCollapsed ? '300px' : (buttonWidth ?? '300px') }}
>
- <div className="p-2">
+ <div className="py-1.5">
<div className="relative">
<Search className="absolute left-3 top-1/2 h-4 w-4 -translate-y-1/2 text-text-primary" />
<Ariakit.Combobox
store={combobox}
autoSelect
placeholder={searchPlaceholder}
- className="w-full rounded-md border border-border-light bg-surface-tertiary py-2 pl-9 pr-3 text-sm text-text-primary focus:outline-none"
+ className="w-full rounded-md bg-surface-secondary py-2 pl-9 pr-3 text-sm text-text-primary focus:outline-none"
/>
</div>
</div>
diff --git a/client/src/components/ui/Select.tsx b/client/src/components/ui/Select.tsx
index f05e40bb09..671bae4438 100644
--- a/client/src/components/ui/Select.tsx
+++ b/client/src/components/ui/Select.tsx
@@ -1,5 +1,3 @@
-'use client';
-
import * as React from 'react';
import * as SelectPrimitive from '@radix-ui/react-select';
import { CaretSortIcon, CheckIcon, ChevronDownIcon, ChevronUpIcon } from '@radix-ui/react-icons';
@@ -19,7 +17,7 @@ const SelectTrigger = React.forwardRef<
<SelectPrimitive.Trigger
ref={ref}
className={cn(
- 'border-input ring-offset-background placeholder:text-muted-foreground flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-gray-200 bg-transparent px-3 py-2 text-sm shadow-sm focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 [&>span]:line-clamp-1',
+ 'flex h-9 w-full items-center justify-between whitespace-nowrap rounded-md border border-gray-200 border-input bg-transparent px-3 py-2 text-sm shadow-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50 dark:border-gray-600 [&>span]:line-clamp-1',
'rounded-lg hover:bg-gray-100/50 dark:hover:bg-gray-700',
className,
)}
@@ -120,7 +118,7 @@ const SelectItem = React.forwardRef<
<SelectPrimitive.Item
ref={ref}
className={cn(
- 'focus:bg-accent focus:text-accent-foreground relative flex w-full cursor-pointer select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
+ 'relative flex w-full cursor-pointer select-none items-center rounded-sm py-1.5 pl-2 pr-8 text-sm outline-none focus:bg-accent focus:text-accent-foreground data-[disabled]:pointer-events-none data-[disabled]:opacity-50',
'rounded-lg hover:bg-gray-100/50 dark:hover:bg-gray-700',
className,
)}
@@ -142,7 +140,7 @@ const SelectSeparator = React.forwardRef<
>(({ className = '', ...props }, ref) => (
<SelectPrimitive.Separator
ref={ref}
- className={cn('bg-muted -mx-1 my-1 h-px', className)}
+ className={cn('-mx-1 my-1 h-px bg-muted', className)}
{...props}
/>
));
diff --git a/client/src/components/ui/SplitText.tsx b/client/src/components/ui/SplitText.tsx
new file mode 100644
index 0000000000..9c77871d5c
--- /dev/null
+++ b/client/src/components/ui/SplitText.tsx
@@ -0,0 +1,102 @@
+import { useSprings, animated, SpringConfig } from '@react-spring/web';
+import { useEffect, useRef, useState } from 'react';
+
+interface SplitTextProps {
+ text?: string;
+ className?: string;
+ delay?: number;
+ animationFrom?: { opacity: number; transform: string };
+ animationTo?: { opacity: number; transform: string };
+ easing?: SpringConfig['easing'];
+ threshold?: number;
+ rootMargin?: string;
+ textAlign?: 'left' | 'right' | 'center' | 'justify' | 'start' | 'end';
+ onLetterAnimationComplete?: () => void;
+}
+
+const SplitText: React.FC<SplitTextProps> = ({
+ text = '',
+ className = '',
+ delay = 100,
+ animationFrom = { opacity: 0, transform: 'translate3d(0,40px,0)' },
+ animationTo = { opacity: 1, transform: 'translate3d(0,0,0)' },
+ easing = (t: number) => t,
+ threshold = 0.1,
+ rootMargin = '-100px',
+ textAlign = 'center',
+ onLetterAnimationComplete,
+}) => {
+ const words = text.split(' ').map((word) => word.split(''));
+ const letters = words.flat();
+ const [inView, setInView] = useState(false);
+ const ref = useRef<HTMLParagraphElement>(null);
+ const animatedCount = useRef(0);
+
+ useEffect(() => {
+ const observer = new IntersectionObserver(
+ ([entry]) => {
+ if (entry.isIntersecting) {
+ setInView(true);
+ if (ref.current) {
+ observer.unobserve(ref.current);
+ }
+ }
+ },
+ { threshold, rootMargin },
+ );
+
+ if (ref.current) {
+ observer.observe(ref.current);
+ }
+
+ return () => observer.disconnect();
+ }, [threshold, rootMargin]);
+
+ const springs = useSprings(
+ letters.length,
+ letters.map((_, i) => ({
+ from: animationFrom,
+ to: inView
+ ? async (next: (props: any) => Promise<void>) => {
+ await next(animationTo);
+ animatedCount.current += 1;
+ if (animatedCount.current === letters.length && onLetterAnimationComplete) {
+ onLetterAnimationComplete();
+ }
+ }
+ : animationFrom,
+ delay: i * delay,
+ config: { easing },
+ })),
+ );
+
+ return (
+ <p
+ ref={ref}
+ className={`split-parent inline overflow-hidden ${className}`}
+ style={{ textAlign, whiteSpace: 'normal', wordWrap: 'break-word' }}
+ >
+ {words.map((word, wordIndex) => (
+ <span key={wordIndex} style={{ display: 'inline-block', whiteSpace: 'nowrap' }}>
+ {word.map((letter, letterIndex) => {
+ const index =
+ words.slice(0, wordIndex).reduce((acc, w) => acc + w.length, 0) + letterIndex;
+
+ return (
+ <animated.span
+ key={index}
+ style={springs[index] as unknown as React.CSSProperties}
+ className="inline-block transform transition-opacity will-change-transform"
+ >
+ {letter}
+ </animated.span>
+ );
+ })}
+ <span style={{ display: 'inline-block', width: '0.3em' }}>&nbsp;</span>
+ </span>
+ ))}
+ </p>
+ );
+};
+
+export default SplitText;
diff --git a/client/src/components/ui/index.ts b/client/src/components/ui/index.ts
index 1f23d51eab..0e9ee85c5d 100644
--- a/client/src/components/ui/index.ts
+++ b/client/src/components/ui/index.ts
@@ -26,8 +26,10 @@ export * from './Tooltip';
export * from './Pagination';
export * from './Progress';
export * from './InputOTP';
+export { default as Badge } from './Badge';
export { default as Combobox } from './Combobox';
export { default as Dropdown } from './Dropdown';
+export { default as SplitText } from './SplitText';
export { default as FileUpload } from './FileUpload';
export { default as FormInput } from './FormInput';
export { default as DropdownPopup } from './DropdownPopup';
diff --git a/client/src/data-provider/Agents/queries.ts b/client/src/data-provider/Agents/queries.ts
index 838984ff10..d1fe5c3e9f 100644
--- a/client/src/data-provider/Agents/queries.ts
+++ b/client/src/data-provider/Agents/queries.ts
@@ -42,6 +42,7 @@ export const useListAgentsQuery = <TData = t.AgentListResponse>(
// select: (res) => {
// return res.data.sort((a, b) => a.created_at - b.created_at);
// },
+ staleTime: 1000 * 5,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
diff --git a/client/src/data-provider/Endpoints/queries.ts b/client/src/data-provider/Endpoints/queries.ts
index 2ef26a5bd9..3f9c468fcf 100644
--- a/client/src/data-provider/Endpoints/queries.ts
+++ b/client/src/data-provider/Endpoints/queries.ts
@@ -31,6 +31,7 @@ export const useGetStartupConfig = (
[QueryKeys.startupConfig],
() => dataService.getStartupConfig(),
{
+ staleTime: Infinity,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
diff --git a/client/src/data-provider/queries.ts b/client/src/data-provider/queries.ts
index 631a3b0f0d..b88d0797e9 100644
--- a/client/src/data-provider/queries.ts
+++ b/client/src/data-provider/queries.ts
@@ -35,6 +35,7 @@ export const useGetPresetsQuery = (
config?: UseQueryOptions<TPreset[]>,
): QueryObserverResult<TPreset[], unknown> => {
return useQuery<TPreset[]>([QueryKeys.presets], () => dataService.getPresets(), {
+ staleTime: 1000 * 10,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
@@ -236,6 +237,7 @@ export const useListAssistantsQuery = <TData = AssistantListResponse>(
// select: (res) => {
// return res.data.sort((a, b) => a.created_at - b.created_at);
// },
+ staleTime: 1000 * 5,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
refetchOnMount: false,
diff --git a/client/src/hooks/Conversations/useDefaultConvo.ts b/client/src/hooks/Conversations/useDefaultConvo.ts
index 777e2c4b74..bfca39d3e0 100644
--- a/client/src/hooks/Conversations/useDefaultConvo.ts
+++ b/client/src/hooks/Conversations/useDefaultConvo.ts
@@ -1,3 +1,4 @@
+import { excludedKeys } from 'librechat-data-provider';
import { useGetModelsQuery } from 'librechat-data-provider/react-query';
import type {
TEndpointsConfig,
@@ -8,26 +9,66 @@ import type {
import { getDefaultEndpoint, buildDefaultConvo } from '~/utils';
import { useGetEndpointsQuery } from '~/data-provider';
-type TDefaultConvo = { conversation: Partial<TConversation>; preset?: Partial<TPreset> | null };
+type TDefaultConvo = {
+ conversation: Partial<TConversation>;
+ preset?: Partial<TPreset> | null;
+ cleanInput?: boolean;
+ cleanOutput?: boolean;
+};
+
+const exceptions = new Set(['spec', 'iconURL']);
const useDefaultConvo = () => {
const { data: endpointsConfig = {} as TEndpointsConfig } = useGetEndpointsQuery();
const { data: modelsConfig = {} as TModelsConfig } = useGetModelsQuery();
- const getDefaultConversation = ({ conversation, preset }: TDefaultConvo) => {
+ const getDefaultConversation = ({
+ conversation: _convo,
+ preset,
+ cleanInput,
+ cleanOutput,
+ }: TDefaultConvo) => {
const endpoint = getDefaultEndpoint({
convoSetup: preset as TPreset,
endpointsConfig,
});
- const models = modelsConfig[endpoint] || [];
+ const models = modelsConfig[endpoint ?? ''] || [];
+ const conversation = { ..._convo };
+ if (cleanInput === true) {
+ for (const key in conversation) {
+ if (excludedKeys.has(key) && !exceptions.has(key)) {
+ continue;
+ }
+ if (conversation[key] == null) {
+ continue;
+ }
+ conversation[key] = undefined;
+ }
+ }
- return buildDefaultConvo({
+ const defaultConvo = buildDefaultConvo({
conversation: conversation as TConversation,
endpoint,
lastConversationSetup: preset as TConversation,
models,
});
+
+ if (!cleanOutput) {
+ return defaultConvo;
+ }
+
+ for (const key in defaultConvo) {
+ if (excludedKeys.has(key) && !exceptions.has(key)) {
+ continue;
+ }
+ if (defaultConvo[key] == null) {
+ continue;
+ }
+ defaultConvo[key] = undefined;
+ }
+
+ return defaultConvo;
};
return getDefaultConversation;
diff --git a/client/src/hooks/Conversations/usePresets.ts b/client/src/hooks/Conversations/usePresets.ts
index 8e8e5436d8..3c30cb6d65 100644
--- a/client/src/hooks/Conversations/usePresets.ts
+++ b/client/src/hooks/Conversations/usePresets.ts
@@ -62,7 +62,6 @@ export default function usePresets() {
}
hasLoaded.current = true;
// dependencies are stable and only needed once
- // eslint-disable-next-line react-hooks/exhaustive-deps
}, [presetsQuery.data, user, modelsData]);
const setPresets = useCallback(
@@ -182,12 +181,22 @@ export default function usePresets() {
endpointsConfig,
});
+ newPreset.spec = null;
+ newPreset.iconURL = newPreset.iconURL ?? null;
+ newPreset.modelLabel = newPreset.modelLabel ?? null;
const isModular = isCurrentModular && isNewModular && shouldSwitch;
if (isExistingConversation && isModular) {
const currentConvo = getDefaultConversation({
/* target endpointType is necessary to avoid endpoint mixing */
- conversation: { ...(conversation ?? {}), endpointType: newEndpointType },
+ conversation: {
+ ...(conversation ?? {}),
+ spec: null,
+ iconURL: null,
+ modelLabel: null,
+ endpointType: newEndpointType,
+ },
preset: { ...newPreset, endpointType: newEndpointType },
+ cleanInput: true,
});
/* We don't reset the latest message, only when changing settings mid-converstion */
diff --git a/client/src/hooks/Conversations/useSetIndexOptions.ts b/client/src/hooks/Conversations/useSetIndexOptions.ts
index 11d60371bf..8e3f3e6363 100644
--- a/client/src/hooks/Conversations/useSetIndexOptions.ts
+++ b/client/src/hooks/Conversations/useSetIndexOptions.ts
@@ -42,7 +42,7 @@ const useSetIndexOptions: TUseSetOptions = (preset = false) => {
const setExample: TSetExample = (i, type, newValue = null) => {
const update = {};
const current = conversation?.examples?.slice() || [];
- const currentExample = { ...current[i] } || {};
+ const currentExample = { ...current[i] };
currentExample[type] = { content: newValue };
current[i] = currentExample;
update['examples'] = current;
diff --git a/client/src/components/Chat/Menus/Endpoints/Icons.tsx b/client/src/hooks/Endpoint/Icons.tsx
similarity index 100%
rename from client/src/components/Chat/Menus/Endpoints/Icons.tsx
rename to client/src/hooks/Endpoint/Icons.tsx
diff --git a/client/src/components/Chat/Menus/Endpoints/UnknownIcon.tsx b/client/src/hooks/Endpoint/UnknownIcon.tsx
similarity index 100%
rename from client/src/components/Chat/Menus/Endpoints/UnknownIcon.tsx
rename to client/src/hooks/Endpoint/UnknownIcon.tsx
diff --git a/client/src/hooks/Endpoint/index.ts b/client/src/hooks/Endpoint/index.ts
new file mode 100644
index 0000000000..1a6a35ef2a
--- /dev/null
+++ b/client/src/hooks/Endpoint/index.ts
@@ -0,0 +1,4 @@
+export { default as useKeyDialog } from './useKeyDialog';
+export { default as useModelSelection } from './useModels';
+export { default as useEndpoints } from './useEndpoints';
+export { default as useSelectorEffects } from './useSelectorEffects';
diff --git a/client/src/hooks/Endpoint/useEndpoints.ts b/client/src/hooks/Endpoint/useEndpoints.ts
new file mode 100644
index 0000000000..ae56d1d0b5
--- /dev/null
+++ b/client/src/hooks/Endpoint/useEndpoints.ts
@@ -0,0 +1,182 @@
+import React, { useMemo, useCallback } from 'react';
+import { useGetModelsQuery } from 'librechat-data-provider/react-query';
+import {
+ EModelEndpoint,
+ PermissionTypes,
+ Permissions,
+ alternateName,
+} from 'librechat-data-provider';
+import type {
+ Agent,
+ Assistant,
+ TEndpointsConfig,
+ TAgentsMap,
+ TInterfaceConfig,
+ TAssistantsMap,
+} from 'librechat-data-provider';
+import type { ExtendedEndpoint } from '~/common';
+import { mapEndpoints, getIconKey, getEndpointField } from '~/utils';
+import { useGetEndpointsQuery } from '~/data-provider';
+import { useChatContext } from '~/Providers';
+import { useHasAccess } from '~/hooks';
+import { icons } from './Icons';
+
+export const useEndpoints = ({
+ agentsMap,
+ assistantsMap,
+ endpointsConfig,
+ interfaceConfig,
+}: {
+ agentsMap?: TAgentsMap;
+ assistantsMap?: TAssistantsMap;
+ endpointsConfig: TEndpointsConfig;
+ interfaceConfig: TInterfaceConfig;
+}) => {
+ const modelsQuery = useGetModelsQuery();
+ const { conversation } = useChatContext();
+ const { data: endpoints = [] } = useGetEndpointsQuery({ select: mapEndpoints });
+
+ const { endpoint } = conversation ?? {};
+
+ const hasAgentAccess = useHasAccess({
+ permissionType: PermissionTypes.AGENTS,
+ permission: Permissions.USE,
+ });
+
+ const agents = useMemo(
+ () =>
+ Object.values(agentsMap ?? {}).filter(
+ (agent): agent is Agent & { name: string } =>
+ agent !== undefined && 'id' in agent && 'name' in agent && agent.name !== null,
+ ),
+ [agentsMap],
+ );
+
+ const assistants: Assistant[] = useMemo(
+ () => Object.values(assistantsMap?.[EModelEndpoint.assistants] ?? {}),
+ [endpoint, assistantsMap],
+ );
+
+ const azureAssistants: Assistant[] = useMemo(
+ () => Object.values(assistantsMap?.[EModelEndpoint.azureAssistants] ?? {}),
+ [endpoint, assistantsMap],
+ );
+
+ const filteredEndpoints = useMemo(() => {
+ if (!interfaceConfig.modelSelect) {
+ return [];
+ }
+ const result: EModelEndpoint[] = [];
+ for (let i = 0; i < endpoints.length; i++) {
+ if (endpoints[i] === EModelEndpoint.agents && !hasAgentAccess) {
+ continue;
+ }
+ result.push(endpoints[i]);
+ }
+
+ return result;
+ }, [endpoints, hasAgentAccess]);
+
+ const endpointRequiresUserKey = useCallback(
+ (ep: string) => {
+ return !!getEndpointField(endpointsConfig, ep, 'userProvide');
+ },
+ [endpointsConfig],
+ );
+
+ const mappedEndpoints: ExtendedEndpoint[] = useMemo(() => {
+ return filteredEndpoints.map((ep) => {
+ const endpointType = getEndpointField(endpointsConfig, ep, 'type');
+ const iconKey = getIconKey({ endpoint: ep, endpointsConfig, endpointType });
+ const Icon = icons[iconKey];
+ const endpointIconURL = getEndpointField(endpointsConfig, ep, 'iconURL');
+ const hasModels =
+ (ep === EModelEndpoint.agents && agents?.length > 0) ||
+ (ep === EModelEndpoint.assistants && assistants?.length > 0) ||
+ (ep !== EModelEndpoint.assistants &&
+ ep !== EModelEndpoint.agents &&
+ (modelsQuery.data?.[ep]?.length ?? 0) > 0);
+
+ // Base result object with formatted default icon
+ const result: ExtendedEndpoint = {
+ value: ep,
+ label: alternateName[ep] || ep,
+ hasModels,
+ icon: Icon
+ ? React.createElement(Icon, {
+ size: 20,
+ className: 'text-text-primary shrink-0 icon-md',
+ iconURL: endpointIconURL,
+ endpoint: ep,
+ })
+ : null,
+ };
+
+ // Handle agents case
+ if (ep === EModelEndpoint.agents && agents.length > 0) {
+ result.models = agents.map((agent) => agent.id);
+ result.agentNames = agents.reduce((acc, agent) => {
+ acc[agent.id] = agent.name || '';
+ return acc;
+ }, {});
+ result.modelIcons = agents.reduce((acc, agent) => {
+ acc[agent.id] = agent?.avatar?.filepath;
+ return acc;
+ }, {});
+ }
+
+ // Handle assistants case
+ else if (ep === EModelEndpoint.assistants && assistants.length > 0) {
+ result.models = assistants.map((assistant: { id: string }) => assistant.id);
+ result.assistantNames = assistants.reduce(
+ (acc: Record<string, string>, assistant: Assistant) => {
+ acc[assistant.id] = assistant.name || '';
+ return acc;
+ },
+ {},
+ );
+ result.modelIcons = assistants.reduce(
+ (acc: Record<string, string | undefined>, assistant: Assistant) => {
+ acc[assistant.id] = assistant.metadata?.avatar;
+ return acc;
+ },
+ {},
+ );
+ } else if (ep === EModelEndpoint.azureAssistants && azureAssistants.length > 0) {
+ result.models = azureAssistants.map((assistant: { id: string }) => assistant.id);
+ result.assistantNames = azureAssistants.reduce(
+ (acc: Record<string, string>, assistant: Assistant) => {
+ acc[assistant.id] = assistant.name || '';
+ return acc;
+ },
+ {},
+ );
+ result.modelIcons = azureAssistants.reduce(
+ (acc: Record<string, string | undefined>, assistant: Assistant) => {
+ acc[assistant.id] = assistant.metadata?.avatar;
+ return acc;
+ },
+ {},
+ );
+ }
+
+ // For other endpoints with models from the modelsQuery
+ else if (
+ ep !== EModelEndpoint.agents &&
+ ep !== EModelEndpoint.assistants &&
+ (modelsQuery.data?.[ep]?.length ?? 0) > 0
+ ) {
+ result.models = modelsQuery.data?.[ep];
+ }
+
+ return result;
+ });
+ }, [filteredEndpoints, endpointsConfig, modelsQuery.data, agents, assistants]);
+
+ return {
+ mappedEndpoints,
+ endpointRequiresUserKey,
+ };
+};
+
+export default useEndpoints;
diff --git a/client/src/hooks/Endpoint/useKeyDialog.ts b/client/src/hooks/Endpoint/useKeyDialog.ts
new file mode 100644
index 0000000000..d783320fd6
--- /dev/null
+++ b/client/src/hooks/Endpoint/useKeyDialog.ts
@@ -0,0 +1,38 @@
+import { useState, useCallback } from 'react';
+import { EModelEndpoint } from 'librechat-data-provider';
+
+export const useKeyDialog = () => {
+ const [keyDialogOpen, setKeyDialogOpen] = useState(false);
+ const [keyDialogEndpoint, setKeyDialogEndpoint] = useState<EModelEndpoint | null>(null);
+
+ const handleOpenKeyDialog = useCallback(
+ (ep: EModelEndpoint, e: React.MouseEvent | React.KeyboardEvent) => {
+ e.preventDefault();
+ e.stopPropagation();
+ setKeyDialogEndpoint(ep);
+ setKeyDialogOpen(true);
+ },
+ [],
+ );
+
+ const onOpenChange = (open: boolean) => {
+ if (!open && keyDialogEndpoint) {
+ const button = document.getElementById(`endpoint-${keyDialogEndpoint}-settings`);
+ if (button) {
+ setTimeout(() => {
+ button.focus();
+ }, 5);
+ }
+ }
+ setKeyDialogOpen(open);
+ };
+
+ return {
+ keyDialogOpen,
+ keyDialogEndpoint,
+ onOpenChange,
+ handleOpenKeyDialog,
+ };
+};
+
+export default useKeyDialog;
diff --git a/client/src/hooks/Endpoint/useModels.ts b/client/src/hooks/Endpoint/useModels.ts
new file mode 100644
index 0000000000..6ce4540c3c
--- /dev/null
+++ b/client/src/hooks/Endpoint/useModels.ts
@@ -0,0 +1,277 @@
+import { useCallback, useRef, useContext, useMemo } from 'react';
+import { EModelEndpoint, LocalStorageKeys } from 'librechat-data-provider';
+import { getConvoSwitchLogic } from '~/utils';
+import { mainTextareaId } from '~/common';
+import { useRecoilState, useRecoilValue } from 'recoil';
+import { useSetIndexOptions, useDefaultConvo } from '~/hooks';
+import { useChatContext, useAssistantsMapContext } from '~/Providers';
+import { useGetEndpointsQuery } from '~/data-provider';
+import store from '~/store';
+
+export const useModelSelection = () => {
+ const { setOption } = useSetIndexOptions();
+ const getDefaultConversation = useDefaultConvo();
+ const { conversation, newConversation, index } = useChatContext();
+ const { data: endpointsConfig = {} } = useGetEndpointsQuery();
+ const modularChat = useRecoilValue(store.modularChat);
+ const assistantsMapResult = useAssistantsMapContext();
+ const assistantsMap = useMemo(() => assistantsMapResult ?? {}, [assistantsMapResult]);
+
+ const timeoutIdRef = useRef<NodeJS.Timeout | undefined>(undefined);
+
+ const setAgentId = useCallback(
+ (agentId: string) => {
+ setOption('agent_id')(agentId);
+ localStorage.setItem(`${LocalStorageKeys.AGENT_ID_PREFIX}${index}`, agentId);
+ clearTimeout(timeoutIdRef.current);
+ timeoutIdRef.current = setTimeout(() => {
+ const textarea = document.getElementById(mainTextareaId);
+ if (textarea) {
+ textarea.focus();
+ }
+ }, 150);
+ },
+ [setOption, index, timeoutIdRef],
+ );
+
+ const setAssistantId = useCallback(
+ (endpoint: string, assistantId: string) => {
+ const assistant = assistantsMap[endpoint]?.[assistantId];
+ if (assistant) {
+ setOption('model')(assistant.model);
+ setOption('assistant_id')(assistantId);
+ localStorage.setItem(`${LocalStorageKeys.ASST_ID_PREFIX}${index}${endpoint}`, assistantId);
+ }
+ clearTimeout(timeoutIdRef.current);
+ timeoutIdRef.current = setTimeout(() => {
+ const textarea = document.getElementById(mainTextareaId);
+ if (textarea) {
+ textarea.focus();
+ }
+ }, 150);
+ },
+ [setOption, index, assistantsMap, timeoutIdRef],
+ );
+
+ const setModel = useCallback(
+ (model: string) => {
+ setOption('model')(model);
+ clearTimeout(timeoutIdRef.current);
+ timeoutIdRef.current = setTimeout(() => {
+ const textarea = document.getElementById(mainTextareaId);
+ if (textarea) {
+ textarea.focus();
+ }
+ }, 150);
+ },
+ [setOption, timeoutIdRef],
+ );
+
+ const handleModelSelect = useCallback(
+ (ep: EModelEndpoint, selectedModel: string) => {
+ if (ep === EModelEndpoint.assistants) {
+ if (conversation?.endpoint === ep) {
+ setAssistantId(ep, selectedModel);
+ return;
+ }
+
+ const { template } = getConvoSwitchLogic({
+ newEndpoint: ep,
+ modularChat: false,
+ conversation,
+ endpointsConfig,
+ });
+
+ const assistant = assistantsMap[ep]?.[selectedModel];
+
+ const currentConvo = getDefaultConversation({
+ conversation: {
+ ...conversation,
+ endpoint: ep,
+ assistant_id: selectedModel,
+ model: assistant?.model || '',
+ },
+ preset: {
+ ...template,
+ endpoint: ep,
+ assistant_id: selectedModel,
+ model: assistant?.model || '',
+ },
+ });
+
+ newConversation({
+ template: currentConvo,
+ preset: currentConvo,
+ keepLatestMessage: true,
+ });
+ return;
+ }
+
+ if (ep === EModelEndpoint.agents) {
+ if (conversation?.endpoint === ep) {
+ setAgentId(selectedModel);
+ return;
+ }
+
+ const { template } = getConvoSwitchLogic({
+ newEndpoint: ep,
+ modularChat: false,
+ conversation,
+ endpointsConfig,
+ });
+
+ const currentConvo = getDefaultConversation({
+ conversation: { ...conversation, endpoint: ep, agent_id: selectedModel },
+ preset: { ...template, endpoint: ep, agent_id: selectedModel },
+ });
+
+ newConversation({
+ template: currentConvo,
+ preset: currentConvo,
+ keepLatestMessage: true,
+ });
+ return;
+ }
+
+ const {
+ template,
+ shouldSwitch,
+ isNewModular,
+ newEndpointType,
+ isCurrentModular,
+ isExistingConversation,
+ } = getConvoSwitchLogic({
+ newEndpoint: ep,
+ modularChat,
+ conversation,
+ endpointsConfig,
+ });
+
+ const isModular = isCurrentModular && isNewModular && shouldSwitch;
+
+ if (isExistingConversation && isModular) {
+ template.endpointType = newEndpointType;
+
+ const currentConvo = getDefaultConversation({
+ conversation: { ...(conversation ?? {}), endpointType: template.endpointType },
+ preset: template,
+ });
+
+ newConversation({
+ template: currentConvo,
+ preset: currentConvo,
+ keepLatestMessage: true,
+ keepAddedConvos: true,
+ });
+ return;
+ }
+ newConversation({
+ template: { ...(template as any) },
+ keepAddedConvos: isModular,
+ });
+
+ setModel(selectedModel);
+ },
+ [
+ conversation,
+ endpointsConfig,
+ modularChat,
+ newConversation,
+ getDefaultConversation,
+ setModel,
+ setAgentId,
+ setAssistantId,
+ assistantsMap,
+ ],
+ );
+
+ const handleEndpointSelect = useCallback(
+ (ep: string, hasModels: boolean, agents: any[], assistants: any[], modelsData: any) => {
+ if (hasModels) {
+ if (conversation?.endpoint !== ep) {
+ const newEndpoint = ep as EModelEndpoint;
+ const { template } = getConvoSwitchLogic({
+ newEndpoint,
+ modularChat: false,
+ conversation,
+ endpointsConfig,
+ });
+
+ let initialModel = '';
+ let initialAgentId = '';
+ let initialAssistantId = '';
+
+ if (newEndpoint === EModelEndpoint.agents && agents.length > 0) {
+ initialAgentId = agents[0].id;
+ } else if (newEndpoint === EModelEndpoint.assistants && assistants.length > 0) {
+ initialAssistantId = assistants[0].id;
+ initialModel = assistantsMap[newEndpoint]?.[initialAssistantId]?.model || '';
+ } else if (modelsData && modelsData[newEndpoint] && modelsData[newEndpoint].length > 0) {
+ initialModel = modelsData[newEndpoint][0];
+ }
+
+ const currentConvo = getDefaultConversation({
+ conversation: {
+ ...conversation,
+ endpoint: newEndpoint,
+ model: initialModel,
+ agent_id: initialAgentId,
+ assistant_id: initialAssistantId,
+ },
+ preset: {
+ ...template,
+ endpoint: newEndpoint,
+ model: initialModel,
+ agent_id: initialAgentId,
+ assistant_id: initialAssistantId,
+ },
+ });
+
+ newConversation({
+ template: currentConvo,
+ preset: currentConvo,
+ keepLatestMessage: true,
+ });
+ }
+ return;
+ }
+
+ if (!hasModels) {
+ const newEndpoint = ep as EModelEndpoint;
+ const { template } = getConvoSwitchLogic({
+ newEndpoint,
+ modularChat: false,
+ conversation,
+ endpointsConfig,
+ });
+ const currentConvo = getDefaultConversation({
+ conversation: { ...conversation, endpoint: newEndpoint },
+ preset: { ...template, endpoint: newEndpoint },
+ });
+ newConversation({
+ template: currentConvo,
+ preset: currentConvo,
+ keepLatestMessage: true,
+ });
+ }
+ },
+ [
+ conversation,
+ endpointsConfig,
+ newConversation,
+ getDefaultConversation,
+ assistantsMap,
+ modularChat,
+ ],
+ );
+
+ return {
+ handleModelSelect,
+ handleEndpointSelect,
+ setAgentId,
+ setAssistantId,
+ setModel,
+ };
+};
+
+export default useModelSelection;
diff --git a/client/src/hooks/Endpoint/useSelectorEffects.ts b/client/src/hooks/Endpoint/useSelectorEffects.ts
new file mode 100644
index 0000000000..c9b075dc7d
--- /dev/null
+++ b/client/src/hooks/Endpoint/useSelectorEffects.ts
@@ -0,0 +1,96 @@
+import React, { useMemo, useEffect, useRef } from 'react';
+import { isAgentsEndpoint, isAssistantsEndpoint, LocalStorageKeys } from 'librechat-data-provider';
+import type * as t from 'librechat-data-provider';
+import type { SelectedValues } from '~/common';
+import useSetIndexOptions from '~/hooks/Conversations/useSetIndexOptions';
+
+export default function useSelectorEffects({
+ index = 0,
+ agentsMap,
+ conversation,
+ assistantsMap,
+ setSelectedValues,
+}: {
+ index?: number;
+ agentsMap: t.TAgentsMap | undefined;
+ assistantsMap: t.TAssistantsMap | undefined;
+ conversation: t.TConversation | null;
+ setSelectedValues: React.Dispatch<React.SetStateAction<SelectedValues>>;
+}) {
+ const { setOption } = useSetIndexOptions();
+ const agents: t.Agent[] = useMemo(() => {
+ return Object.values(agentsMap ?? {}) as t.Agent[];
+ }, [agentsMap]);
+ const { agent_id: selectedAgentId = null, endpoint } = conversation ?? {};
+
+ useEffect(() => {
+ if (selectedAgentId == null && agents.length > 0) {
+ let agent_id = localStorage.getItem(`${LocalStorageKeys.AGENT_ID_PREFIX}${index}`);
+ if (agent_id == null) {
+ agent_id = agents[0].id;
+ }
+ const agent = agentsMap?.[agent_id];
+
+ if (agent !== undefined && isAgentsEndpoint(endpoint as string) === true) {
+ setOption('model')('');
+ setOption('agent_id')(agent_id);
+ }
+ }
+ }, [index, agents, selectedAgentId, agentsMap, endpoint, setOption]);
+
+ const debounceTimeoutRef = useRef<NodeJS.Timeout | null>(null);
+
+ const debouncedSetSelectedValues = (values: SelectedValues) => {
+ if (debounceTimeoutRef.current) {
+ clearTimeout(debounceTimeoutRef.current);
+ }
+
+ debounceTimeoutRef.current = setTimeout(() => {
+ setSelectedValues(values);
+ }, 150);
+ };
+
+ useEffect(() => {
+ if (!conversation?.endpoint) {
+ return;
+ }
+ if (
+ conversation?.assistant_id ||
+ conversation?.agent_id ||
+ conversation?.model ||
+ conversation?.spec
+ ) {
+ if (isAgentsEndpoint(conversation?.endpoint)) {
+ debouncedSetSelectedValues({
+ endpoint: conversation.endpoint || '',
+ model: conversation.agent_id ?? '',
+ modelSpec: '',
+ });
+ return;
+ } else if (isAssistantsEndpoint(conversation?.endpoint)) {
+ debouncedSetSelectedValues({
+ endpoint: conversation.endpoint || '',
+ model: conversation.assistant_id || '',
+ modelSpec: conversation.spec || '',
+ });
+ return;
+ }
+ debouncedSetSelectedValues({
+ endpoint: conversation.endpoint || '',
+ model: conversation.model || '',
+ modelSpec: conversation.spec || '',
+ });
+ }
+ return () => {
+ if (debounceTimeoutRef.current) {
+ clearTimeout(debounceTimeoutRef.current);
+ }
+ };
+ }, [
+ conversation?.spec,
+ conversation?.model,
+ conversation?.endpoint,
+ conversation?.agent_id,
+ conversation?.assistant_id,
+ ]);
+}
diff --git a/client/src/hooks/Input/useMentions.ts b/client/src/hooks/Input/useMentions.ts
index cb5c3a5b29..3fafd7a2de 100644
--- a/client/src/hooks/Input/useMentions.ts
+++ b/client/src/hooks/Input/useMentions.ts
@@ -1,8 +1,10 @@
import { useMemo } from 'react';
import { useGetModelsQuery } from 'librechat-data-provider/react-query';
import {
+ Permissions,
alternateName,
EModelEndpoint,
+ PermissionTypes,
isAgentsEndpoint,
getConfigDefaults,
isAssistantsEndpoint,
@@ -18,6 +20,7 @@ import {
import useAssistantListMap from '~/hooks/Assistants/useAssistantListMap';
import { mapEndpoints, getPresetTitle } from '~/utils';
import { EndpointIcon } from '~/components/Endpoints';
+import useHasAccess from '~/hooks/Roles/useHasAccess';
const defaultInterface = getConfigDefaults().interface;
@@ -53,6 +56,11 @@ export default function useMentions({
assistantMap: TAssistantsMap;
includeAssistants: boolean;
}) {
+ const hasAgentAccess = useHasAccess({
+ permissionType: PermissionTypes.AGENTS,
+ permission: Permissions.USE,
+ });
+
const { data: presets } = useGetPresetsQuery();
const { data: modelsConfig } = useGetModelsQuery();
const { data: startupConfig } = useGetStartupConfig();
@@ -67,7 +75,12 @@ export default function useMentions({
description,
})),
);
+ const interfaceConfig = useMemo(
+ () => startupConfig?.interface ?? defaultInterface,
+ [startupConfig?.interface],
+ );
const { data: agentsList = null } = useListAgentsQuery(undefined, {
+ enabled: hasAgentAccess && interfaceConfig.modelSelect === true,
select: (res) => {
const { data } = res;
return data.map(({ id, name, avatar }) => ({
@@ -113,10 +126,6 @@ export default function useMentions({
);
const modelSpecs = useMemo(() => startupConfig?.modelSpecs?.list ?? [], [startupConfig]);
- const interfaceConfig = useMemo(
- () => startupConfig?.interface ?? defaultInterface,
- [startupConfig],
- );
const options: MentionOption[] = useMemo(() => {
let validEndpoints = endpoints;
@@ -129,6 +138,10 @@ export default function useMentions({
return [];
}
+ if (interfaceConfig.modelSelect !== true) {
+ return [];
+ }
+
const models = (modelsConfig?.[endpoint] ?? []).map((model) => ({
value: endpoint,
label: model,
@@ -159,7 +172,7 @@ export default function useMentions({
}),
type: 'modelSpec' as const,
})),
- ...(interfaceConfig.endpointsMenu === true ? validEndpoints : []).map((endpoint) => ({
+ ...(interfaceConfig.modelSelect === true ? validEndpoints : []).map((endpoint) => ({
value: endpoint,
label: alternateName[endpoint as string] ?? endpoint ?? '',
type: 'endpoint' as const,
@@ -170,14 +183,21 @@ export default function useMentions({
size: 20,
}),
})),
- ...(agentsList ?? []),
- ...(endpointsConfig?.[EModelEndpoint.assistants] && includeAssistants
+ ...(interfaceConfig.modelSelect === true ? (agentsList ?? []) : []),
+ ...(endpointsConfig?.[EModelEndpoint.assistants] &&
+ includeAssistants &&
+ interfaceConfig.modelSelect === true
? assistantListMap[EModelEndpoint.assistants] || []
: []),
- ...(endpointsConfig?.[EModelEndpoint.azureAssistants] && includeAssistants
+ ...(endpointsConfig?.[EModelEndpoint.azureAssistants] &&
+ includeAssistants &&
+ interfaceConfig.modelSelect === true
? assistantListMap[EModelEndpoint.azureAssistants] || []
: []),
- ...((interfaceConfig.presets === true ? presets : [])?.map((preset, index) => ({
+ ...((interfaceConfig.modelSelect === true && interfaceConfig.presets === true
+ ? presets
+ : []
+ )?.map((preset, index) => ({
value: preset.presetId ?? `preset-${index}`,
label: preset.title ?? preset.modelLabel ?? preset.chatGptLabel ?? '',
description: getPresetTitle(preset, true),
diff --git a/client/src/hooks/Input/useQueryParams.ts b/client/src/hooks/Input/useQueryParams.ts
index 94c036500d..d6bb90b210 100644
--- a/client/src/hooks/Input/useQueryParams.ts
+++ b/client/src/hooks/Input/useQueryParams.ts
@@ -9,9 +9,9 @@ import {
tQueryParamsSchema,
isAssistantsEndpoint,
} from 'librechat-data-provider';
-import type { TPreset, TEndpointsConfig } from 'librechat-data-provider';
+import type { TPreset, TEndpointsConfig, TStartupConfig } from 'librechat-data-provider';
import type { ZodAny } from 'zod';
-import { getConvoSwitchLogic, removeUnavailableTools } from '~/utils';
+import { getConvoSwitchLogic, getModelSpecIconURL, removeUnavailableTools } from '~/utils';
import useDefaultConvo from '~/hooks/Conversations/useDefaultConvo';
import { useChatContext, useChatFormContext } from '~/Providers';
import useSubmitMessage from '~/hooks/Messages/useSubmitMessage';
@@ -87,8 +87,20 @@ export default function useQueryParams({
if (!_newPreset) {
return;
}
+ let newPreset = removeUnavailableTools(_newPreset, availableTools);
+ if (newPreset.spec != null && newPreset.spec !== '') {
+ const startupConfig = queryClient.getQueryData<TStartupConfig>([QueryKeys.startupConfig]);
+ const modelSpecs = startupConfig?.modelSpecs?.list ?? [];
+ const spec = modelSpecs.find((s) => s.name === newPreset.spec);
+ if (!spec) {
+ return;
+ }
+ const { preset } = spec;
+ preset.iconURL = getModelSpecIconURL(spec);
+ preset.spec = spec.name;
+ newPreset = preset;
+ }
- const newPreset = removeUnavailableTools(_newPreset, availableTools);
let newEndpoint = newPreset.endpoint ?? '';
const endpointsConfig = queryClient.getQueryData<TEndpointsConfig>([QueryKeys.endpoints]);
@@ -122,14 +134,28 @@ export default function useQueryParams({
endpointsConfig,
});
+ let resetParams = {};
+ if (newPreset.spec == null) {
+ template.spec = null;
+ template.iconURL = null;
+ template.modelLabel = null;
+ resetParams = { spec: null, iconURL: null, modelLabel: null };
+ newPreset = { ...newPreset, ...resetParams };
+ }
+
const isModular = isCurrentModular && isNewModular && shouldSwitch;
if (isExistingConversation && isModular) {
template.endpointType = newEndpointType as EModelEndpoint | undefined;
const currentConvo = getDefaultConversation({
/* target endpointType is necessary to avoid endpoint mixing */
- conversation: { ...(conversation ?? {}), endpointType: template.endpointType },
+ conversation: {
+ ...(conversation ?? {}),
+ endpointType: template.endpointType,
+ ...resetParams,
+ },
preset: template,
+ cleanOutput: newPreset.spec != null && newPreset.spec !== '',
});
/* We don't reset the latest message, only when changing settings mid-converstion */
@@ -161,9 +187,11 @@ export default function useQueryParams({
queryParams[key] = value;
});
- const decodedPrompt = queryParams.prompt || '';
+ // Support both 'prompt' and 'q' as query parameters, with 'prompt' taking precedence
+ const decodedPrompt = queryParams.prompt || queryParams.q || '';
const shouldAutoSubmit = queryParams.submit?.toLowerCase() === 'true';
delete queryParams.prompt;
+ delete queryParams.q;
delete queryParams.submit;
const validSettings = processValidSettings(queryParams);
@@ -184,6 +212,10 @@ export default function useQueryParams({
if (!textAreaRef.current) {
return;
}
+ const startupConfig = queryClient.getQueryData<TStartupConfig>([QueryKeys.startupConfig]);
+ if (!startupConfig) {
+ return;
+ }
const { decodedPrompt, validSettings, shouldAutoSubmit } = processQueryParams();
const currentText = methods.getValues('text');
diff --git a/client/src/hooks/Input/useSelectMention.ts b/client/src/hooks/Input/useSelectMention.ts
index b4748a1cbc..8ba53966b0 100644
--- a/client/src/hooks/Input/useSelectMention.ts
+++ b/client/src/hooks/Input/useSelectMention.ts
@@ -17,15 +17,17 @@ import store from '~/store';
export default function useSelectMention({
presets,
modelSpecs,
- assistantMap,
+ assistantsMap,
endpointsConfig,
newConversation,
+ returnHandlers,
}: {
presets?: TPreset[];
modelSpecs: TModelSpec[];
- assistantMap?: TAssistantsMap;
+ assistantsMap?: TAssistantsMap;
newConversation: ConvoGenerator;
endpointsConfig: TEndpointsConfig;
+ returnHandlers?: boolean;
}) {
const { conversation } = useChatContext();
const getDefaultConversation = useDefaultConvo();
@@ -69,7 +71,7 @@ export default function useSelectMention({
preset.assistant_id != null &&
!(preset.model ?? '')
) {
- preset.model = assistantMap?.[newEndpoint]?.[preset.assistant_id]?.model;
+ preset.model = assistantsMap?.[newEndpoint]?.[preset.assistant_id]?.model;
}
const isModular = isCurrentModular && isNewModular && shouldSwitch;
@@ -80,6 +82,7 @@ export default function useSelectMention({
/* target endpointType is necessary to avoid endpoint mixing */
conversation: { ...(conversation ?? {}), endpointType: template.endpointType },
preset: template,
+ cleanOutput: true,
});
/* We don't reset the latest message, only when changing settings mid-converstion */
@@ -104,7 +107,7 @@ export default function useSelectMention({
modularChat,
newConversation,
endpointsConfig,
- assistantMap,
+ assistantsMap,
],
);
@@ -112,6 +115,7 @@ export default function useSelectMention({
model?: string;
agent_id?: string;
assistant_id?: string;
+ spec?: string | null;
};
const onSelectEndpoint = useCallback(
@@ -149,12 +153,21 @@ export default function useSelectMention({
template.agent_id = agent_id;
}
+ template.spec = null;
+ template.iconURL = null;
+ template.modelLabel = null;
if (isExistingConversation && isCurrentModular && isNewModular && shouldSwitch) {
template.endpointType = newEndpointType;
const currentConvo = getDefaultConversation({
/* target endpointType is necessary to avoid endpoint mixing */
- conversation: { ...(conversation ?? {}), endpointType: template.endpointType },
+ conversation: {
+ ...(conversation ?? {}),
+ spec: null,
+ iconURL: null,
+ modelLabel: null,
+ endpointType: template.endpointType,
+ },
preset: template,
});
@@ -165,7 +178,7 @@ export default function useSelectMention({
newConversation({
template: { ...(template as Partial<TConversation>) },
- preset: { ...kwargs, endpoint: newEndpoint },
+ preset: { ...kwargs, spec: null, iconURL: null, modelLabel: null, endpoint: newEndpoint },
});
},
[conversation, getDefaultConversation, modularChat, newConversation, endpointsConfig],
@@ -194,14 +207,20 @@ export default function useSelectMention({
endpointsConfig,
});
+ newPreset.spec = null;
+ newPreset.iconURL = newPreset.iconURL ?? null;
+ newPreset.modelLabel = newPreset.modelLabel ?? null;
const isModular = isCurrentModular && isNewModular && shouldSwitch;
if (isExistingConversation && isModular) {
template.endpointType = newEndpointType as EModelEndpoint | undefined;
-
+ template.spec = null;
+ template.iconURL = null;
+ template.modelLabel = null;
const currentConvo = getDefaultConversation({
/* target endpointType is necessary to avoid endpoint mixing */
conversation: { ...(conversation ?? {}), endpointType: template.endpointType },
preset: template,
+ cleanInput: true,
});
/* We don't reset the latest message, only when changing settings mid-converstion */
@@ -242,7 +261,7 @@ export default function useSelectMention({
} else if (isAssistantsEndpoint(option.type)) {
onSelectEndpoint(option.type, {
assistant_id: key,
- model: assistantMap?.[option.type]?.[key]?.model ?? '',
+ model: assistantsMap?.[option.type]?.[key]?.model ?? '',
});
} else if (isAgentsEndpoint(option.type)) {
onSelectEndpoint(option.type, {
@@ -250,9 +269,16 @@ export default function useSelectMention({
});
}
},
- [modelSpecs, onSelectEndpoint, onSelectPreset, onSelectSpec, presets, assistantMap],
+ [modelSpecs, onSelectEndpoint, onSelectPreset, onSelectSpec, presets, assistantsMap],
);
+ if (returnHandlers) {
+ return {
+ onSelectSpec,
+ onSelectEndpoint,
+ };
+ }
+
return {
onSelectMention,
};
diff --git a/client/src/hooks/SSE/useEventHandlers.ts b/client/src/hooks/SSE/useEventHandlers.ts
index 0de3d16166..e1cd08f37f 100644
--- a/client/src/hooks/SSE/useEventHandlers.ts
+++ b/client/src/hooks/SSE/useEventHandlers.ts
@@ -10,6 +10,7 @@ import {
tPresetSchema,
tMessageSchema,
tConvoUpdateSchema,
+ ContentTypes,
} from 'librechat-data-provider';
import type {
TMessage,
@@ -58,6 +59,74 @@ export type EventHandlerParams = {
resetLatestMessage?: Resetter;
};
+const createErrorMessage = ({
+ errorMetadata,
+ getMessages,
+ submission,
+ error,
+}: {
+ getMessages: () => TMessage[] | undefined;
+ errorMetadata?: Partial<TMessage>;
+ submission: EventSubmission;
+ error?: Error | unknown;
+}) => {
+ const currentMessages = getMessages();
+ const latestMessage = currentMessages?.[currentMessages.length - 1];
+ let errorMessage: TMessage;
+ const text = submission.initialResponse.text.length > 45 ? submission.initialResponse.text : '';
+ const errorText =
+ (errorMetadata?.text || text || (error as Error | undefined)?.message) ??
+ 'Error cancelling request';
+ const latestContent = latestMessage?.content ?? [];
+ let isValidContentPart = false;
+ if (latestContent.length > 0) {
+ const latestContentPart = latestContent[latestContent.length - 1];
+ const latestPartValue = latestContentPart?.[latestContentPart.type ?? ''];
+ isValidContentPart =
+ latestContentPart.type !== ContentTypes.TEXT ||
+ (latestContentPart.type === ContentTypes.TEXT && typeof latestPartValue === 'string')
+ ? true
+ : latestPartValue?.value !== '';
+ }
+ if (
+ latestMessage?.conversationId &&
+ latestMessage?.messageId &&
+ latestContent &&
+ isValidContentPart
+ ) {
+ const content = [...latestContent];
+ content.push({
+ type: ContentTypes.ERROR,
+ error: errorText,
+ });
+ errorMessage = {
+ ...latestMessage,
+ ...errorMetadata,
+ error: undefined,
+ text: '',
+ content,
+ };
+ if (
+ submission.userMessage.messageId &&
+ submission.userMessage.messageId !== errorMessage.parentMessageId
+ ) {
+ errorMessage.parentMessageId = submission.userMessage.messageId;
+ }
+ return errorMessage;
+ } else if (errorMetadata) {
+ return errorMetadata as TMessage;
+ } else {
+ errorMessage = {
+ ...submission,
+ ...submission.initialResponse,
+ text: errorText,
+ unfinished: !!text.length,
+ error: true,
+ };
+ }
+ return tMessageSchema.parse(errorMessage);
+};
+
export default function useEventHandlers({
genTitle,
setMessages,
@@ -479,11 +548,16 @@ export default function useEventHandlers({
if (!data) {
const convoId = conversationId || v4();
- const errorResponse = parseErrorResponse({
+ const errorMetadata = parseErrorResponse({
text: 'Error connecting to server, try refreshing the page.',
...submission,
conversationId: convoId,
});
+ const errorResponse = createErrorMessage({
+ errorMetadata,
+ getMessages,
+ submission,
+ });
setMessages([...messages, userMessage, errorResponse]);
if (newConversation) {
newConversation({
@@ -593,21 +667,15 @@ export default function useEventHandlers({
} catch (error) {
console.error('Error cancelling request');
console.error(error);
- const convoId = conversationId || v4();
- const text =
- submission.initialResponse.text.length > 45 ? submission.initialResponse.text : '';
- const errorMessage = {
- ...submission,
- ...submission.initialResponse,
- text: (text || (error as Error | undefined)?.message) ?? 'Error cancelling request',
- unfinished: !!text.length,
- error: true,
- };
- const errorResponse = tMessageSchema.parse(errorMessage);
+ const errorResponse = createErrorMessage({
+ getMessages,
+ submission,
+ error,
+ });
setMessages([...submission.messages, submission.userMessage, errorResponse]);
if (newConversation) {
newConversation({
- template: { conversationId: convoId },
+ template: { conversationId: conversationId || errorResponse.conversationId || v4() },
preset: tPresetSchema.parse(submission.conversation),
});
}
diff --git a/client/src/hooks/index.ts b/client/src/hooks/index.ts
index ee2de2d671..83cdb7fbc4 100644
--- a/client/src/hooks/index.ts
+++ b/client/src/hooks/index.ts
@@ -13,22 +13,25 @@ export * from './Plugins';
export * from './Prompts';
export * from './Roles';
export * from './SSE';
-
export * from './AuthContext';
export * from './ThemeContext';
export * from './ScreenshotContext';
export * from './ApiErrorBoundaryContext';
+export * from './Endpoint';
+
+export type { TranslationKeys } from './useLocalize';
+
export { default as useToast } from './useToast';
export { default as useTimeout } from './useTimeout';
export { default as useNewConvo } from './useNewConvo';
export { default as useLocalize } from './useLocalize';
-export type { TranslationKeys } from './useLocalize';
export { default as useMediaQuery } from './useMediaQuery';
+export { default as useChatBadges } from './useChatBadges';
export { default as useScrollToRef } from './useScrollToRef';
export { default as useLocalStorage } from './useLocalStorage';
+export { default as useDocumentTitle } from './useDocumentTitle';
export { default as useDelayedRender } from './useDelayedRender';
export { default as useOnClickOutside } from './useOnClickOutside';
export { default as useSpeechToText } from './Input/useSpeechToText';
export { default as useTextToSpeech } from './Input/useTextToSpeech';
export { default as useGenerationsByLatest } from './useGenerationsByLatest';
-export { default as useDocumentTitle } from './useDocumentTitle';
diff --git a/client/src/hooks/useChatBadges.ts b/client/src/hooks/useChatBadges.ts
new file mode 100644
index 0000000000..ab22d5f13d
--- /dev/null
+++ b/client/src/hooks/useChatBadges.ts
@@ -0,0 +1,35 @@
+import { useRecoilValue } from 'recoil';
+import { MessageCircleDashed, Box } from 'lucide-react';
+import type { BadgeItem } from '~/common';
+import { useLocalize } from '~/hooks';
+import store from '~/store';
+
+const badgeConfig = [
+ {
+ id: '1',
+ icon: MessageCircleDashed,
+ label: 'com_ui_temporary',
+ atom: store.isTemporary,
+ },
+ // {
+ // id: '2',
+ // icon: Box,
+ // label: 'com_ui_artifacts',
+ // atom: store.codeArtifacts,
+ // },
+ // TODO: add more badges here (missing store atoms)
+] as const;
+
+export default function useChatBadges(): BadgeItem[] {
+ const localize = useLocalize();
+ const activeBadges = useRecoilValue(store.chatBadges) as Array<{ id: string }>;
+ const activeBadgeIds = new Set(activeBadges.map((badge) => badge.id));
+
+ return badgeConfig.map((cfg) => ({
+ id: cfg.id,
+ label: localize(cfg.label),
+ icon: cfg.icon,
+ atom: cfg.atom,
+ isAvailable: activeBadgeIds.has(cfg.id),
+ }));
+}
diff --git a/client/src/hooks/useNewConvo.ts b/client/src/hooks/useNewConvo.ts
index 500206b181..16ec363402 100644
--- a/client/src/hooks/useNewConvo.ts
+++ b/client/src/hooks/useNewConvo.ts
@@ -219,11 +219,12 @@ const useNewConvo = (index = 0) => {
};
let preset = _preset;
- const defaultModelSpec = getDefaultModelSpec(startupConfig?.modelSpecs?.list);
+ const defaultModelSpec = getDefaultModelSpec(startupConfig);
if (
!preset &&
startupConfig &&
- startupConfig.modelSpecs?.prioritize === true &&
+ (startupConfig.modelSpecs?.prioritize === true ||
+ (startupConfig.interface?.modelSelect ?? true) !== true) &&
defaultModelSpec
) {
preset = {
diff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.json
index 6e5730050f..46df23e995 100644
--- a/client/src/locales/en/translation.json
+++ b/client/src/locales/en/translation.json
@@ -246,6 +246,10 @@
"com_endpoint_reasoning_effort": "Reasoning Effort",
"com_endpoint_save_as_preset": "Save As Preset",
"com_endpoint_search": "Search endpoint by name",
+ "com_endpoint_search_var": "Search {{0}}...",
+ "com_endpoint_search_models": "Search models...",
+ "com_endpoint_search_endpoint_models": "Search {{0}} models...",
+ "com_endpoint_select_model": "Select a model",
"com_endpoint_set_custom_name": "Set a custom name, in case you can find this preset",
"com_endpoint_skip_hover": "Enable skipping the completion step, which reviews the final answer and generated steps",
"com_endpoint_stop": "Stop Sequences",
@@ -270,7 +274,7 @@
"com_error_no_base_url": "No base URL found. Please provide one and try again.",
"com_error_no_user_key": "No key found. Please provide a key and try again.",
"com_files_filter": "Filter files...",
- "com_files_no_results": "No results.",
+ "com_files_no_results": "No results",
"com_files_number_selected": "{{0}} of {{1}} items(s) selected",
"com_files_table": "something needs to go here. was empty",
"com_generated_files": "Generated files:",
@@ -322,6 +326,7 @@
"com_nav_enabled": "Enabled",
"com_nav_engine": "Engine",
"com_nav_enter_to_send": "Press Enter to send messages",
+ "com_nav_center_chat_input": "Center Chat Input on Welcome Screen",
"com_nav_export": "Export",
"com_nav_export_all_message_branches": "Export all message branches",
"com_nav_export_conversation": "Export conversation",
@@ -432,9 +437,7 @@
"com_nav_user_name_display": "Display username in messages",
"com_nav_voice_select": "Voice",
"com_nav_voices_fetch_error": "Could not retrieve voice options. Please check your internet connection.",
- "com_nav_welcome_agent": "Please Select an Agent",
- "com_nav_welcome_assistant": "Please Select an Assistant",
- "com_nav_welcome_message": "How can I help you today?",
+ "com_nav_edit_chat_badges": "Edit Chat Badges",
"com_show_agent_settings": "Show Agent Settings",
"com_show_completion_settings": "Show Completion Settings",
"com_show_examples": "Show Examples",
@@ -445,8 +448,6 @@
"com_sidepanel_hide_panel": "Hide Panel",
"com_sidepanel_manage_files": "Manage Files",
"com_sidepanel_parameters": "Parameters",
- "com_sidepanel_select_agent": "Select an Agent",
- "com_sidepanel_select_assistant": "Select an Assistant",
"com_ui_2fa_account_security": "Two-factor authentication adds an extra layer of security to your account",
"com_ui_2fa_disable": "Disable 2FA",
"com_ui_2fa_disable_error": "There was an error disabling two-factor authentication",
@@ -550,6 +551,7 @@
"com_ui_close": "Close",
"com_ui_close_menu": "Close Menu",
"com_ui_code": "Code",
+ "com_ui_expand_chat": "Expand Chat",
"com_ui_collapse_chat": "Collapse Chat",
"com_ui_command_placeholder": "Optional: Enter a command for the prompt or name will be used",
"com_ui_command_usage_placeholder": "Select a Prompt by command or name",
@@ -624,7 +626,6 @@
"com_ui_empty_category": "-",
"com_ui_endpoint": "Endpoint",
"com_ui_endpoint_menu": "LLM Endpoint Menu",
- "com_ui_endpoints_available": "Available Endpoints",
"com_ui_enter": "Enter",
"com_ui_enter_api_key": "Enter API Key",
"com_ui_enter_openapi_schema": "Enter your OpenAPI schema here",
@@ -666,7 +667,7 @@
"com_ui_global_group": "something needs to go here. was empty",
"com_ui_go_back": "Go back",
"com_ui_go_to_conversation": "Go to conversation",
- "com_ui_happy_birthday": "It's my 1st birthday!",
+ "com_ui_happy_birthday": "It's my 2nd birthday!",
"com_ui_hide_qr": "Hide QR Code",
"com_ui_host": "Host",
"com_ui_idea": "Ideas",
@@ -686,8 +687,6 @@
"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_llm_menu": "LLM Menu",
- "com_ui_llms_available": "Available LLMs",
"com_ui_loading": "Loading...",
"com_ui_locked": "Locked",
"com_ui_logo": "{{0}} Logo",
@@ -713,7 +712,6 @@
"com_ui_no_terms_content": "No terms and conditions content to display",
"com_ui_no_valid_items": "something needs to go here. was empty",
"com_ui_none": "None",
- "com_ui_none_selected": "None selected",
"com_ui_not_used": "Not Used",
"com_ui_nothing_found": "Nothing found",
"com_ui_oauth": "OAuth",
@@ -805,7 +803,7 @@
"com_ui_storage": "Storage",
"com_ui_submit": "Submit",
"com_ui_teach_or_explain": "Learning",
- "com_ui_temporary_chat": "Temporary Chat",
+ "com_ui_temporary": "Temporary",
"com_ui_terms_and_conditions": "Terms and Conditions",
"com_ui_terms_of_service": "Terms of service",
"com_ui_thinking": "Thinking...",
@@ -846,6 +844,12 @@
"com_ui_write": "Writing",
"com_ui_yes": "Yes",
"com_ui_zoom": "Zoom",
+ "com_ui_save_badge_changes": "Save badge changes?",
+ "com_ui_late_night": "Happy late night",
+ "com_ui_weekend_morning": "Happy weekend",
+ "com_ui_good_morning": "Good morning",
+ "com_ui_good_afternoon": "Good afternoon",
+ "com_ui_good_evening": "Good evening",
"com_user_message": "You",
"com_warning_resubmit_unsupported": "Resubmitting the AI message is not supported for this endpoint."
}
\ No newline at end of file
diff --git a/client/src/routes/ChatRoute.tsx b/client/src/routes/ChatRoute.tsx
index 2356e43966..729c90e467 100644
--- a/client/src/routes/ChatRoute.tsx
+++ b/client/src/routes/ChatRoute.tsx
@@ -57,7 +57,7 @@ export default function ChatRoute() {
}
if (conversationId === Constants.NEW_CONVO && endpointsQuery.data && modelsQuery.data) {
- const spec = getDefaultModelSpec(startupConfig?.modelSpecs?.list);
+ const spec = getDefaultModelSpec(startupConfig);
newConversation({
modelsData: modelsQuery.data,
@@ -88,7 +88,7 @@ export default function ChatRoute() {
assistantListMap[EModelEndpoint.assistants] &&
assistantListMap[EModelEndpoint.azureAssistants]
) {
- const spec = getDefaultModelSpec(startupConfig?.modelSpecs?.list);
+ const spec = getDefaultModelSpec(startupConfig);
newConversation({
modelsData: modelsQuery.data,
template: conversation ? conversation : undefined,
@@ -116,7 +116,6 @@ export default function ChatRoute() {
hasSetConversation.current = true;
}
/* Creates infinite render if all dependencies included due to newConversation invocations exceeding call stack before hasSetConversation.current becomes truthy */
- // eslint-disable-next-line react-hooks/exhaustive-deps
}, [
startupConfig,
initialConvoQuery.data,
@@ -127,8 +126,8 @@ export default function ChatRoute() {
if (endpointsQuery.isLoading || modelsQuery.isLoading) {
return (
- <div aria-live="polite" role="status">
- <Spinner className="m-auto text-black dark:text-white" />
+ <div className="flex h-screen items-center justify-center" aria-live="polite" role="status">
+ <Spinner className="text-text-primary" />
</div>
);
}
diff --git a/client/src/store/index.ts b/client/src/store/index.ts
index 59f12ae0fd..af326ae890 100644
--- a/client/src/store/index.ts
+++ b/client/src/store/index.ts
@@ -12,6 +12,7 @@ import lang from './language';
import settings from './settings';
import misc from './misc';
import isTemporary from './temporary';
+
export default {
...artifacts,
...families,
diff --git a/client/src/store/misc.ts b/client/src/store/misc.ts
index 11fd7915e5..284382403e 100644
--- a/client/src/store/misc.ts
+++ b/client/src/store/misc.ts
@@ -1,6 +1,7 @@
import { atom } from 'recoil';
import { TAttachment } from 'librechat-data-provider';
import { atomWithLocalStorage } from './utils';
+import { BadgeItem } from '~/common';
const hideBannerHint = atomWithLocalStorage('hideBannerHint', [] as string[]);
@@ -14,4 +15,22 @@ const queriesEnabled = atom<boolean>({
default: true,
});
-export default { hideBannerHint, messageAttachmentsMap, queriesEnabled };
+const isEditingBadges = atom<boolean>({
+ key: 'isEditingBadges',
+ default: false,
+});
+
+const chatBadges = atomWithLocalStorage<Pick<BadgeItem, 'id'>[]>('chatBadges', [
+ // When adding new badges, make sure to add them to useChatBadges.ts as well and add them as last item
+ // DO NOT CHANGE THE ORDER OF THE BADGES ALREADY IN THE ARRAY
+ { id: '1' },
+ // { id: '2' },
+]);
+
+export default {
+ hideBannerHint,
+ messageAttachmentsMap,
+ queriesEnabled,
+ isEditingBadges,
+ chatBadges,
+};
diff --git a/client/src/store/settings.ts b/client/src/store/settings.ts
index 901c48c2c4..3fc49dc378 100644
--- a/client/src/store/settings.ts
+++ b/client/src/store/settings.ts
@@ -45,6 +45,8 @@ const localStorageAtoms = {
codeArtifacts: atomWithLocalStorage('codeArtifacts', false),
includeShadcnui: atomWithLocalStorage('includeShadcnui', false),
customPromptMode: atomWithLocalStorage('customPromptMode', false),
+ centerFormOnLanding: atomWithLocalStorage('centerFormOnLanding', true),
+ showFooter: atomWithLocalStorage('showFooter', true),
// Commands settings
atCommand: atomWithLocalStorage('atCommand', true),
diff --git a/client/src/style.css b/client/src/style.css
index d1b7790030..201ada00d7 100644
--- a/client/src/style.css
+++ b/client/src/style.css
@@ -67,7 +67,7 @@ html {
--surface-primary-alt: var(--gray-50);
--surface-primary-contrast: var(--gray-100);
--surface-secondary: var(--gray-50);
- --surface-secondary-alt: var(--gray-300);
+ --surface-secondary-alt: var(--gray-200);
--surface-tertiary: var(--gray-100);
--surface-tertiary-alt: var(--white);
--surface-dialog: var(--white);
@@ -75,6 +75,7 @@ html {
--surface-submit-hover: var(--green-800);
--surface-destructive: var(--red-700);
--surface-destructive-hover: var(--red-800);
+ --surface-chat: var(--white);
--border-light: var(--gray-200);
--border-medium-alt: var(--gray-300);
--border-medium: var(--gray-300);
@@ -132,6 +133,7 @@ html {
--surface-submit-hover: var(--green-800);
--surface-destructive: var(--red-800);
--surface-destructive-hover: var(--red-900);
+ --surface-chat: var(--gray-700);
--border-light: var(--gray-700);
--border-medium-alt: var(--gray-600);
--border-medium: var(--gray-600);
@@ -624,25 +626,127 @@ pre {
margin: 0;
}
-.scroll-down-enter {
+.scroll-animation-enter {
opacity: 0;
+ transform: translateY(20px) scale(0.7) rotate(-5deg);
+ pointer-events: none;
}
-/* .scroll-down-appear {
- opacity: 0;
-} */
-.scroll-down-enter-active {
+.scroll-animation-enter-done {
opacity: 1;
- transition: opacity 400ms;
+ transform: translateY(0) scale(1);
}
-.scroll-down-exit {
- opacity: 1;
+.scroll-animation-exit-done {
+ display: none;
}
-.scroll-down-exit-active {
- opacity: 0;
- transition: opacity 400ms;
+@keyframes twist-entrance {
+ 0% {
+ transform: translateY(20px) scale(0.7) rotate(-5deg);
+ opacity: 0;
+ }
+ 60% {
+ transform: translateY(2px) scale(0.95) rotate(2deg);
+ opacity: 0.9;
+ }
+ 100% {
+ transform: translateY(0) scale(1) rotate(0deg);
+ opacity: 1;
+ }
+}
+
+.scroll-animation-enter-active {
+ animation: twist-entrance 0.5s cubic-bezier(0.25, 0.46, 0.45, 0.94) forwards;
+ transition-delay: 50ms;
+}
+
+@keyframes twist-exit {
+ 0% {
+ transform: translateY(0) scale(1) rotate(0deg);
+ opacity: 1;
+ }
+ 40% {
+ transform: translateY(5px) scale(0.95) rotate(2deg);
+ opacity: 0.7;
+ }
+ 100% {
+ transform: translateY(20px) scale(0.7) rotate(-5deg);
+ opacity: 0;
+ }
+}
+
+.scroll-animation-exit-active {
+ animation: twist-exit 0.4s cubic-bezier(0.55, 0.085, 0.68, 0.53) forwards;
+ pointer-events: none;
+}
+
+.premium-scroll-button {
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ width: 34px;
+ height: 34px;
+ padding: 0;
+ border-radius: 50%;
+ box-shadow:
+ 0 2px 8px rgba(0, 0, 0, 0.05),
+ 0 4px 12px rgba(0, 0, 0, 0.08),
+ 0 0 0 1px rgba(255, 255, 255, 0.08);
+ background-color: rgba(255, 255, 255, 0.9);
+ z-index: 10;
+ transition:
+ transform 500ms cubic-bezier(0.25, 0.1, 0.25, 1),
+ box-shadow 500ms cubic-bezier(0.25, 0.1, 0.25, 1);
+ overflow: hidden;
+}
+
+.dark .premium-scroll-button {
+ box-shadow:
+ 0 2px 8px rgba(0, 0, 0, 0.2),
+ 0 4px 12px rgba(0, 0, 0, 0.25),
+ 0 0 0 1px rgba(255, 255, 255, 0.06);
+ background-color: rgba(35, 35, 40, 0.9);
+}
+
+.scroll-animation-enter-active .premium-scroll-button {
+ pointer-events: none !important;
+}
+
+.premium-scroll-button:hover:not(:active) {
+ transform: translateY(-1.5px) scale(1.02);
+ box-shadow:
+ 0 5px 10px rgba(0, 0, 0, 0.07),
+ 0 7px 14px rgba(0, 0, 0, 0.1),
+ 0 0 0 1px rgba(255, 255, 255, 0.1);
+}
+
+.premium-scroll-button:active {
+ transform: translateY(1px) scale(0.98);
+ transition: all 150ms cubic-bezier(0.2, 0, 0.2, 1);
+ box-shadow:
+ 0 1px 4px rgba(0, 0, 0, 0.1),
+ 0 2px 8px rgba(0, 0, 0, 0.08),
+ 0 0 0 1px rgba(255, 255, 255, 0.08);
+}
+
+@keyframes float {
+ 0%,
+ 100% {
+ transform: translateY(0);
+ }
+ 50% {
+ transform: translateY(-1px);
+ }
+}
+
+.scroll-animation-enter-done .premium-scroll-button {
+ animation: float 2s ease-in-out infinite;
+}
+
+.premium-scroll-button:hover,
+.premium-scroll-button:active {
+ animation: none;
}
.blink {
@@ -749,7 +853,7 @@ pre {
margin-bottom: 1.6em;
margin-top: 1.6em;
padding-left: 1em;
- quotes: '\201C''\201D''\2018''\2019';
+ quotes: '\201C' '\201D' '\2018' '\2019';
}
.prose :where(blockquote p:first-of-type):not(:where([class~='not-prose'] *)):before {
content: open-quote;
@@ -1099,7 +1203,13 @@ pre {
code,
pre {
- font-family: Consolas, Söhne Mono, Monaco, Andale Mono, Ubuntu Mono, monospace !important;
+ font-family:
+ Consolas,
+ Söhne Mono,
+ Monaco,
+ Andale Mono,
+ Ubuntu Mono,
+ monospace !important;
}
code[class='language-plaintext'] {
white-space: pre-line;
@@ -1225,8 +1335,12 @@ button {
--tw-ring-shadow: var(--tw-ring-inset) 0 0 0 calc(2px + var(--tw-ring-offset-width))
var(--tw-ring-color);
--tw-ring-offset-width: 2px;
- box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), 0 0 transparent;
- box-shadow: var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 transparent);
+ box-shadow:
+ var(--tw-ring-offset-shadow),
+ var(--tw-ring-shadow),
+ 0 0 transparent;
+ box-shadow:
+ var(--tw-ring-offset-shadow), var(--tw-ring-shadow), var(--tw-shadow, 0 0 transparent);
}
.btn-primary.focus-visible {
--tw-ring-opacity: 1;
@@ -1693,9 +1807,7 @@ html {
.tooltip-label:before {
content: attr(data-content);
}
-button.scroll-convo {
- display: none;
-}
+
@-webkit-keyframes blink {
to {
visibility: hidden;
@@ -1741,7 +1853,9 @@ button.scroll-convo {
animation: toast-close 0.12s cubic-bezier(0.4, 0, 1, 1) both;
}
.toast-root .alert-root {
- box-shadow: 0 0 1px rgba(67, 90, 111, 0.3), 0 5px 8px -4px rgba(67, 90, 111, 0.3);
+ box-shadow:
+ 0 0 1px rgba(67, 90, 111, 0.3),
+ 0 5px 8px -4px rgba(67, 90, 111, 0.3);
flex-shrink: 0;
pointer-events: all;
}
@@ -1846,8 +1960,12 @@ button.scroll-convo {
}
.dark .shadow-stroke:after,
.shadow-stroke:after {
- box-shadow: 0 0 transparent, 0 0 transparent, var(--tw-shadow);
- box-shadow: var(--tw-ring-offset-shadow, 0 0 transparent), var(--tw-ring-shadow, 0 0 transparent),
+ box-shadow:
+ 0 0 transparent,
+ 0 0 transparent,
+ var(--tw-shadow);
+ box-shadow:
+ var(--tw-ring-offset-shadow, 0 0 transparent), var(--tw-ring-shadow, 0 0 transparent),
var(--tw-shadow);
}
.dark .shadow-stroke:after {
@@ -1869,8 +1987,12 @@ button.scroll-convo {
position: absolute;
right: 0;
top: 0;
- box-shadow: 0 0 transparent, 0 0 transparent, var(--tw-shadow);
- box-shadow: var(--tw-ring-offset-shadow, 0 0 transparent), var(--tw-ring-shadow, 0 0 transparent),
+ box-shadow:
+ 0 0 transparent,
+ 0 0 transparent,
+ var(--tw-shadow);
+ box-shadow:
+ var(--tw-ring-offset-shadow, 0 0 transparent), var(--tw-ring-shadow, 0 0 transparent),
var(--tw-shadow);
}
@@ -1885,8 +2007,17 @@ button.scroll-convo {
content: '⬤';
width: 12px;
height: 12px;
- font-family: system-ui, Inter, Söhne Circle, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell,
- Noto Sans, sans-serif;
+ font-family:
+ system-ui,
+ Inter,
+ Söhne Circle,
+ -apple-system,
+ Segoe UI,
+ Roboto,
+ Ubuntu,
+ Cantarell,
+ Noto Sans,
+ sans-serif;
line-height: normal;
margin-left: 0.25rem;
vertical-align: middle;
@@ -1896,8 +2027,17 @@ button.scroll-convo {
@supports (selector(:has(*))) {
.result-streaming > :is(ul, ol):last-child > li:last-child:not(:has(> :is(ul, ol, pre))):after {
content: '⬤';
- font-family: system-ui, Inter, Söhne Circle, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell,
- Noto Sans, sans-serif;
+ font-family:
+ system-ui,
+ Inter,
+ Söhne Circle,
+ -apple-system,
+ Segoe UI,
+ Roboto,
+ Ubuntu,
+ Cantarell,
+ Noto Sans,
+ sans-serif;
line-height: normal;
margin-left: 0.25rem;
vertical-align: middle;
@@ -1912,8 +2052,17 @@ button.scroll-convo {
.result-streaming > ol:last-child > li:last-child:after,
.result-streaming > ul:last-child > li:last-child:after {
content: '⬤';
- font-family: system-ui, Inter, Söhne Circle, -apple-system, Segoe UI, Roboto, Ubuntu, Cantarell,
- Noto Sans, sans-serif;
+ font-family:
+ system-ui,
+ Inter,
+ Söhne Circle,
+ -apple-system,
+ Segoe UI,
+ Roboto,
+ Ubuntu,
+ Cantarell,
+ Noto Sans,
+ sans-serif;
line-height: normal;
margin-left: 0.25rem;
vertical-align: middle;
@@ -2373,7 +2522,9 @@ button.scroll-convo {
background-color: hsl(var(--background));
padding: 0.5rem;
color: var(--text-primary);
- box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1);
+ box-shadow:
+ 0 10px 15px -3px rgb(0 0 0 / 0.1),
+ 0 4px 6px -4px rgb(0 0 0 / 0.1);
transform-origin: top;
opacity: 0;
transition-property: opacity, scale, translate;
@@ -2394,7 +2545,9 @@ button.scroll-convo {
.popover-ui:where(.dark, .dark *) {
background-color: hsl(var(--secondary));
color: var(--text-secondary);
- box-shadow: 0 10px 15px -3px rgb(0 0 0 / 0.25), 0 4px 6px -4px rgb(0 0 0 / 0.1);
+ box-shadow:
+ 0 10px 15px -3px rgb(0 0 0 / 0.25),
+ 0 4px 6px -4px rgb(0 0 0 / 0.1);
}
.select-item {
@@ -2423,6 +2576,30 @@ button.scroll-convo {
translate: 0;
}
+.animate-popover {
+ transform-origin: top;
+ opacity: 0;
+ transition: opacity 150ms cubic-bezier(0.4, 0, 0.2, 1), transform 150ms cubic-bezier(0.4, 0, 0.2, 1);
+ transform: scale(0.95) translateY(-0.5rem);
+}
+
+.animate-popover[data-enter] {
+ opacity: 1;
+ transform: scale(1) translateY(0);
+}
+
+.animate-popover-left {
+ transform-origin: left;
+ opacity: 0;
+ transition: opacity 150ms cubic-bezier(0.4, 0, 0.2, 1), transform 150ms cubic-bezier(0.4, 0, 0.2, 1);
+ transform: scale(0.95) translateX(-0.5rem);
+}
+
+.animate-popover-left[data-enter] {
+ opacity: 1;
+ transform: scale(1) translateX(0);
+}
+
/** Note: ensure KaTeX can spread across visible space */
.message-content pre:has(> span.katex) {
overflow: visible !important;
@@ -2474,3 +2651,31 @@ button.scroll-convo {
.scale-98 {
transform: scale(0.98);
}
+
+/* Chat Badges Animation */
+
+@keyframes ios-wiggle {
+ 0% {
+ transform: rotate(-1deg);
+ }
+ 50% {
+ transform: rotate(1deg);
+ }
+ 100% {
+ transform: rotate(-1deg);
+ }
+}
+
+.ios-wiggle {
+ animation: ios-wiggle 0.2s ease-in-out infinite;
+}
+
+.ghost-badge {
+ transition:
+ left 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94),
+ top 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
+}
+
+.badge-icon {
+ transition: transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
+}
diff --git a/client/src/utils/endpointFilter.ts b/client/src/utils/endpointFilter.ts
new file mode 100644
index 0000000000..672caf72f8
--- /dev/null
+++ b/client/src/utils/endpointFilter.ts
@@ -0,0 +1,73 @@
+import { EModelEndpoint } from 'librechat-data-provider';
+import { ExtendedEndpoint } from '~/common';
+
+export const filterMenuItems = (
+ searchTerm: string,
+ mappedEndpoints: ExtendedEndpoint[],
+ agents: any[],
+ assistants: any[],
+ modelsData: any,
+): ExtendedEndpoint[] => {
+ if (!searchTerm.trim()) {
+ return mappedEndpoints;
+ }
+
+ const lowercaseSearchTerm = searchTerm.toLowerCase();
+
+ return mappedEndpoints
+ .map((ep) => {
+ if (ep.hasModels) {
+ if (ep.value === EModelEndpoint.agents) {
+ const filteredAgents = agents.filter((agent) =>
+ agent.name?.toLowerCase().includes(lowercaseSearchTerm),
+ );
+ if (ep.label.toLowerCase().includes(lowercaseSearchTerm) || filteredAgents.length > 0) {
+ return {
+ ...ep,
+ models: filteredAgents.map((agent) => agent.id),
+ agentNames: filteredAgents.reduce((acc: Record<string, string>, agent) => {
+ acc[agent.id] = agent.name || '';
+ return acc;
+ }, {}),
+ };
+ }
+ return null;
+ } else if (ep.value === EModelEndpoint.assistants) {
+ const filteredAssistants = assistants.filter((assistant) =>
+ assistant.name?.toLowerCase().includes(lowercaseSearchTerm),
+ );
+ if (
+ ep.label.toLowerCase().includes(lowercaseSearchTerm) ||
+ filteredAssistants.length > 0
+ ) {
+ return {
+ ...ep,
+ models: filteredAssistants.map((assistant) => assistant.id),
+ assistantNames: filteredAssistants.reduce(
+ (acc: Record<string, string>, assistant) => {
+ acc[assistant.id] = assistant.name || '';
+ return acc;
+ },
+ {},
+ ),
+ };
+ }
+ return null;
+ } else {
+ const allModels = modelsData?.[ep.value] ?? [];
+ const filteredModels = allModels.filter((model: string) =>
+ model.toLowerCase().includes(lowercaseSearchTerm),
+ );
+ if (ep.label.toLowerCase().includes(lowercaseSearchTerm) || filteredModels.length > 0) {
+ return { ...ep, models: filteredModels };
+ }
+ return null;
+ }
+ } else {
+ return ep.label.toLowerCase().includes(lowercaseSearchTerm) ? { ...ep, models: [] } : null;
+ }
+ })
+ .filter(Boolean) as ExtendedEndpoint[];
+};
+
+export default filterMenuItems;
diff --git a/client/src/utils/endpoints.ts b/client/src/utils/endpoints.ts
index 0df88a0fa1..f86f81682e 100644
--- a/client/src/utils/endpoints.ts
+++ b/client/src/utils/endpoints.ts
@@ -180,11 +180,27 @@ export function getConvoSwitchLogic(params: ConversationInitParams): InitiatedTe
*
* First, the admin defined default, then last selected spec, followed by first spec
*/
-export function getDefaultModelSpec(modelSpecs?: t.TModelSpec[]) {
- const defaultSpec = modelSpecs?.find((spec) => spec.default);
- const lastSelectedSpecName = localStorage.getItem(LocalStorageKeys.LAST_SPEC);
- const lastSelectedSpec = modelSpecs?.find((spec) => spec.name === lastSelectedSpecName);
- return defaultSpec || lastSelectedSpec || modelSpecs?.[0];
+export function getDefaultModelSpec(startupConfig?: t.TStartupConfig) {
+ const { modelSpecs, interface: interfaceConfig } = startupConfig ?? {};
+ const { list, prioritize } = modelSpecs ?? {};
+ if (!list) {
+ return;
+ }
+ const defaultSpec = list?.find((spec) => spec.default);
+ if (prioritize === true || !interfaceConfig?.modelSelect) {
+ const lastSelectedSpecName = localStorage.getItem(LocalStorageKeys.LAST_SPEC);
+ const lastSelectedSpec = list?.find((spec) => spec.name === lastSelectedSpecName);
+ return defaultSpec || lastSelectedSpec || list?.[0];
+ } else if (defaultSpec) {
+ return defaultSpec;
+ }
+ const lastConversationSetup = JSON.parse(
+ localStorage.getItem(LocalStorageKeys.LAST_CONVO_SETUP + '_0') ?? '{}',
+ );
+ if (!lastConversationSetup.spec) {
+ return;
+ }
+ return list?.find((spec) => spec.name === lastConversationSetup.spec);
}
/** Gets the default spec iconURL by order or definition.
@@ -208,7 +224,7 @@ export function getIconEndpoint({
iconURL?: string | null;
endpoint?: string | null;
}) {
- return (endpointsConfig?.[iconURL ?? ''] ? iconURL ?? endpoint : endpoint) ?? '';
+ return (endpointsConfig?.[iconURL ?? ''] ? (iconURL ?? endpoint) : endpoint) ?? '';
}
/** Gets the key to use for the default endpoint iconURL, as defined by the custom config */
@@ -228,7 +244,7 @@ export function getIconKey({
if (endpointIconURL && EModelEndpoint[endpointIconURL] != null) {
return endpointIconURL;
}
- return endpointType ? 'unknown' : endpoint ?? 'unknown';
+ return endpointType ? 'unknown' : (endpoint ?? 'unknown');
}
export const getEntity = ({
diff --git a/client/src/utils/index.ts b/client/src/utils/index.ts
index 1a295837f4..7c51ab6361 100644
--- a/client/src/utils/index.ts
+++ b/client/src/utils/index.ts
@@ -20,6 +20,7 @@ export { default as logger } from './logger';
export { default as buildTree } from './buildTree';
export { default as getLoginError } from './getLoginError';
export { default as cleanupPreset } from './cleanupPreset';
+export { default as filterMenuItems } from './endpointFilter';
export { default as buildDefaultConvo } from './buildDefaultConvo';
export { default as getDefaultEndpoint } from './getDefaultEndpoint';
diff --git a/client/tailwind.config.cjs b/client/tailwind.config.cjs
index 45f6533fb5..fba7df05c2 100644
--- a/client/tailwind.config.cjs
+++ b/client/tailwind.config.cjs
@@ -87,6 +87,7 @@ module.exports = {
'surface-submit-hover': 'var(--surface-submit-hover)',
'surface-destructive': 'var(--surface-destructive)',
'surface-destructive-hover': 'var(--surface-destructive-hover)',
+ 'surface-chat': 'var(--surface-chat)',
'border-light': 'var(--border-light)',
'border-medium': 'var(--border-medium)',
'border-medium-alt': 'var(--border-medium-alt)',
diff --git a/package-lock.json b/package-lock.json
index c29b53cd21..3841486001 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1094,6 +1094,7 @@
"@radix-ui/react-switch": "^1.0.3",
"@radix-ui/react-tabs": "^1.0.3",
"@radix-ui/react-toast": "^1.1.5",
+ "@react-spring/web": "^9.7.5",
"@tanstack/react-query": "^4.28.0",
"@tanstack/react-table": "^8.11.7",
"class-variance-authority": "^0.6.0",
@@ -21129,6 +21130,78 @@
"react": ">=16.8"
}
},
+ "node_modules/@react-spring/animated": {
+ "version": "9.7.5",
+ "resolved": "https://registry.npmjs.org/@react-spring/animated/-/animated-9.7.5.tgz",
+ "integrity": "sha512-Tqrwz7pIlsSDITzxoLS3n/v/YCUHQdOIKtOJf4yL6kYVSDTSmVK1LI1Q3M/uu2Sx4X3pIWF3xLUhlsA6SPNTNg==",
+ "license": "MIT",
+ "dependencies": {
+ "@react-spring/shared": "~9.7.5",
+ "@react-spring/types": "~9.7.5"
+ },
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0"
+ }
+ },
+ "node_modules/@react-spring/core": {
+ "version": "9.7.5",
+ "resolved": "https://registry.npmjs.org/@react-spring/core/-/core-9.7.5.tgz",
+ "integrity": "sha512-rmEqcxRcu7dWh7MnCcMXLvrf6/SDlSokLaLTxiPlAYi11nN3B5oiCUAblO72o+9z/87j2uzxa2Inm8UbLjXA+w==",
+ "license": "MIT",
+ "dependencies": {
+ "@react-spring/animated": "~9.7.5",
+ "@react-spring/shared": "~9.7.5",
+ "@react-spring/types": "~9.7.5"
+ },
+ "funding": {
+ "type": "opencollective",
+ "url": "https://opencollective.com/react-spring/donate"
+ },
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0"
+ }
+ },
+ "node_modules/@react-spring/rafz": {
+ "version": "9.7.5",
+ "resolved": "https://registry.npmjs.org/@react-spring/rafz/-/rafz-9.7.5.tgz",
+ "integrity": "sha512-5ZenDQMC48wjUzPAm1EtwQ5Ot3bLIAwwqP2w2owG5KoNdNHpEJV263nGhCeKKmuA3vG2zLLOdu3or6kuDjA6Aw==",
+ "license": "MIT"
+ },
+ "node_modules/@react-spring/shared": {
+ "version": "9.7.5",
+ "resolved": "https://registry.npmjs.org/@react-spring/shared/-/shared-9.7.5.tgz",
+ "integrity": "sha512-wdtoJrhUeeyD/PP/zo+np2s1Z820Ohr/BbuVYv+3dVLW7WctoiN7std8rISoYoHpUXtbkpesSKuPIw/6U1w1Pw==",
+ "license": "MIT",
+ "dependencies": {
+ "@react-spring/rafz": "~9.7.5",
+ "@react-spring/types": "~9.7.5"
+ },
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0"
+ }
+ },
+ "node_modules/@react-spring/types": {
+ "version": "9.7.5",
+ "resolved": "https://registry.npmjs.org/@react-spring/types/-/types-9.7.5.tgz",
+ "integrity": "sha512-HVj7LrZ4ReHWBimBvu2SKND3cDVUPWKLqRTmWe/fNY6o1owGOX0cAHbdPDTMelgBlVbrTKrre6lFkhqGZErK/g==",
+ "license": "MIT"
+ },
+ "node_modules/@react-spring/web": {
+ "version": "9.7.5",
+ "resolved": "https://registry.npmjs.org/@react-spring/web/-/web-9.7.5.tgz",
+ "integrity": "sha512-lmvqGwpe+CSttsWNZVr+Dg62adtKhauGwLyGE/RRyZ8AAMLgb9x3NDMA5RMElXo+IMyTkPp7nxTB8ZQlmhb6JQ==",
+ "license": "MIT",
+ "dependencies": {
+ "@react-spring/animated": "~9.7.5",
+ "@react-spring/core": "~9.7.5",
+ "@react-spring/shared": "~9.7.5",
+ "@react-spring/types": "~9.7.5"
+ },
+ "peerDependencies": {
+ "react": "^16.8.0 || ^17.0.0 || ^18.0.0",
+ "react-dom": "^16.8.0 || ^17.0.0 || ^18.0.0"
+ }
+ },
"node_modules/@react-stately/utils": {
"version": "3.10.1",
"resolved": "https://registry.npmjs.org/@react-stately/utils/-/utils-3.10.1.tgz",
@@ -44027,7 +44100,7 @@
},
"packages/data-provider": {
"name": "librechat-data-provider",
- "version": "0.7.74",
+ "version": "0.7.75",
"license": "ISC",
"dependencies": {
"axios": "^1.8.2",
diff --git a/packages/data-provider/package.json b/packages/data-provider/package.json
index ff7d4cb93c..22e733784c 100644
--- a/packages/data-provider/package.json
+++ b/packages/data-provider/package.json
@@ -1,6 +1,6 @@
{
"name": "librechat-data-provider",
- "version": "0.7.74",
+ "version": "0.7.75",
"description": "data services for librechat apps",
"main": "dist/index.js",
"module": "dist/index.es.js",
diff --git a/packages/data-provider/src/config.ts b/packages/data-provider/src/config.ts
index eb4fb89fe8..235c946d75 100644
--- a/packages/data-provider/src/config.ts
+++ b/packages/data-provider/src/config.ts
@@ -51,6 +51,7 @@ export const excludedKeys = new Set([
'tools',
'model',
'files',
+ 'spec',
]);
export enum SettingsViews {
diff --git a/packages/data-provider/src/schemas.ts b/packages/data-provider/src/schemas.ts
index 9c4c30ef01..e033970d29 100644
--- a/packages/data-provider/src/schemas.ts
+++ b/packages/data-provider/src/schemas.ts
@@ -645,6 +645,8 @@ export const tConvoUpdateSchema = tConversationSchema.merge(
export const tQueryParamsSchema = tConversationSchema
.pick({
// librechat settings
+ /** The model spec to be used */
+ spec: true,
/** The AI context window, overrides the system-defined window as determined by `model` value */
maxContextTokens: true,
/**
diff --git a/packages/data-provider/src/types/assistants.ts b/packages/data-provider/src/types/assistants.ts
index 0ecf751961..c25d76ba63 100644
--- a/packages/data-provider/src/types/assistants.ts
+++ b/packages/data-provider/src/types/assistants.ts
@@ -448,7 +448,7 @@ export type ContentPart = (
PartMetadata;
export type TMessageContentParts =
- | { type: ContentTypes.ERROR; text: Text & PartMetadata }
+ | { type: ContentTypes.ERROR; text?: string | (Text & PartMetadata); error?: string }
| { type: ContentTypes.THINK; think: string | (Text & PartMetadata) }
| { type: ContentTypes.TEXT; text: string | (Text & PartMetadata); tool_call_ids?: string[] }
| {