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

📎 refactor: Move Composer Attachment Components Into the Chat Package (#17533)

Marco Beretta59557a46eb29
diff --git a/bun.lock b/bun.lock
index 4b77fe18f8..162a43f8b9 100644
--- a/bun.lock
+++ b/bun.lock
@@ -448,6 +448,7 @@
"@babel/preset-react": "^7.22.15",
"@babel/preset-typescript": "^7.21.0",
"@librechat/client": "*",
+ "@radix-ui/react-dialog": "^1.1.23",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^14.0.0",
"@types/jest": "^29.5.2",
@@ -470,6 +471,7 @@
},
"peerDependencies": {
"@librechat/client": "*",
+ "@radix-ui/react-dialog": "^1.1.23",
"jotai": "^2.12.5",
"librechat-data-provider": "*",
"lucide": "^0.528.0",
diff --git a/client/src/App.jsx b/client/src/App.jsx
index a6a0c9f0db..19318aae21 100644
--- a/client/src/App.jsx
+++ b/client/src/App.jsx
@@ -5,6 +5,7 @@ import { RouterProvider } from 'react-router-dom';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { Toast, ToastViewport, ToastProvider, useInputModality } from '@librechat/client';
import { QueryClient, QueryClientProvider, QueryCache, MutationCache } from '@tanstack/react-query';
+import { FilesHostProvider, appFilesHost } from '~/Providers/FilesHostContext';
import Direction, { ToastSwipeProvider } from '~/Providers/Direction';
import { ScreenshotProvider, useApiErrorBoundary } from './hooks';
import WakeLockManager from '~/components/System/WakeLockManager';
@@ -81,7 +82,9 @@ const App = () => {
transition-safe reads are gated behind
`_TRANSITION_SUPPORT_UNSTABLE` hooks this app does not use.
Worth revisiting once that state has moved to Jotai. */}
- <RouterProvider router={router} useTransitions={false} />
+ <FilesHostProvider host={appFilesHost}>
+ <RouterProvider router={router} useTransitions={false} />
+ </FilesHostProvider>
<WakeLockManager />
<QueryDevtoolsGate />
<Toast />
diff --git a/client/src/Providers/FilesHostContext.tsx b/client/src/Providers/FilesHostContext.tsx
new file mode 100644
index 0000000000..88a7fd4f43
--- /dev/null
+++ b/client/src/Providers/FilesHostContext.tsx
@@ -0,0 +1,11 @@
+import type { FilesHost } from '@librechat/chat/react';
+import { MinimalIcon } from '~/components/Endpoints';
+
+/** The app's capabilities for the attachment components in `@librechat/chat`. */
+export const appFilesHost: FilesHost = {
+ renderEndpointIcon: (endpoint) => (
+ <MinimalIcon endpoint={endpoint} size={14} isCreatedByUser={false} iconClassName="h-3 w-3" />
+ ),
+};
+
+export { FilesHostProvider, useFilesHost } from '@librechat/chat/react';
diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsx
index 0555e73e9d..f845f3d7a4 100644
--- a/client/src/components/Chat/Input/ChatForm.tsx
+++ b/client/src/components/Chat/Input/ChatForm.tsx
@@ -4,6 +4,7 @@ import { useWatch } from 'react-hook-form';
import { useAtom, useAtomValue } from 'jotai';
import { useNavigate } from 'react-router-dom';
import { useDirection } from '@radix-ui/react-direction';
+import { PastedTextDialog } from '@librechat/chat/components';
import { useSteering, showStopButtonByIndex, useComposerRestoreHost } from '@librechat/chat/react';
import {
submitFromComposer,
@@ -70,7 +71,6 @@ import useComposerItems from '~/hooks/Input/useComposerItems';
import useAttachTarget from '~/hooks/Input/useAttachTarget';
import { chatDirectionAtom } from '~/store/chatDirection';
import Hints, { composerHintId } from './Composer/Hints';
-import PastedTextDialog from './Files/PastedTextDialog';
import DuringRunSendButton from './DuringRunSendButton';
import ProjectLandingChip from '../ProjectLandingChip';
import useHasAccess from '~/hooks/Roles/useHasAccess';
diff --git a/client/src/components/Chat/Input/Composer/Files.tsx b/client/src/components/Chat/Input/Composer/Files.tsx
index e9893fabe3..59ebc74ab3 100644
--- a/client/src/components/Chat/Input/Composer/Files.tsx
+++ b/client/src/components/Chat/Input/Composer/Files.tsx
@@ -1,6 +1,7 @@
import { memo, useRef, useMemo, useState, useEffect } from 'react';
import { Eye, Search } from 'lucide-react';
import { apiBaseUrl } from 'librechat-data-provider';
+import { FilePreview, getFileType } from '@librechat/chat/components';
import { Button, IconButton, Spinner, useToastContext } from '@librechat/client';
import type { TFile } from 'librechat-data-provider';
import type { TranslationKeys } from '~/hooks';
@@ -9,10 +10,9 @@ import FilePreviewDialog, {
getDisplayType,
} from '~/components/Chat/Messages/Content/FilePreviewDialog';
import { getPreviewKind } from '~/components/Chat/Messages/Content/preview';
-import { getFileType, toAbsoluteFilePath, triggerDownload } from '~/utils';
import DialogImage from '~/components/Chat/Messages/Content/DialogImage';
-import FilePreview from '~/components/Chat/Input/Files/FilePreview';
import { useGetFiles, useFilePreviewBlob } from '~/data-provider';
+import { toAbsoluteFilePath, triggerDownload } from '~/utils';
import { useLocalize, useAuthContext } from '~/hooks';
export type FileView = 'all' | 'images' | 'documents';
diff --git a/client/src/components/Chat/Input/Composer/Palette.tsx b/client/src/components/Chat/Input/Composer/Palette.tsx
index 30a0e47ed5..ea3792d262 100644
--- a/client/src/components/Chat/Input/Composer/Palette.tsx
+++ b/client/src/components/Chat/Input/Composer/Palette.tsx
@@ -12,6 +12,7 @@ import * as Ariakit from '@ariakit/react';
import { AutoSizer, List } from 'react-virtualized';
import { composerLiftFamily } from '@librechat/chat/react';
import { Star, Plus, Search, ChevronDown } from 'lucide-react';
+import { FilePreview, getFileType } from '@librechat/chat/components';
import { Button, FileUpload, IconButton, TooltipAnchor, useMediaQuery } from '@librechat/client';
import type {
TFile,
@@ -24,15 +25,14 @@ import type { AttachEntry } from '~/hooks/Input/useAttachItems';
import type { ExtendedFile, FileSetter } from '~/common';
import type { CatalogSection } from './Catalog';
import type { TranslationKeys } from '~/hooks';
-import FilePreview from '~/components/Chat/Input/Files/FilePreview';
import { SharePointPickerDialog } from '~/components/SharePoint';
import useReducedMotion from '~/hooks/Generic/useReducedMotion';
-import { getFileType, isUnifiedUploadMode, cn } from '~/utils';
import useToolFavorites from '~/hooks/Input/useToolFavorites';
import useElementSize from '~/hooks/Generic/useElementSize';
import useRecentFiles from '~/hooks/Input/useRecentFiles';
import useAttachItems from '~/hooks/Input/useAttachItems';
import { useMCPRefresh } from '~/hooks/MCP/useMCPRefresh';
+import { isUnifiedUploadMode, cn } from '~/utils';
import { isMacPlatform } from '~/utils/shortcuts';
import { useBadgeRowContext } from '~/Providers';
import { useLocalize } from '~/hooks';
diff --git a/client/src/components/Chat/Input/Composer/__tests__/semanticTokens.spec.ts b/client/src/components/Chat/Input/Composer/__tests__/semanticTokens.spec.ts
index f4274c0e24..f55c880bdb 100644
--- a/client/src/components/Chat/Input/Composer/__tests__/semanticTokens.spec.ts
+++ b/client/src/components/Chat/Input/Composer/__tests__/semanticTokens.spec.ts
@@ -17,7 +17,7 @@ const collectSourceModules = (directory: string): string[] =>
const composerModules = [
...collectSourceModules(composerRoot),
...collectSourceModules(
- join(__dirname, '../../../../../../../packages/chat/src/components/composer'),
+ join(__dirname, '../../../../../../../packages/chat/src/components/composer/bar'),
),
];
diff --git a/client/src/components/Chat/Input/Files/DragDropWrapper.tsx b/client/src/components/Chat/Input/Files/DragDropWrapper.tsx
index 2538315554..f5a4b6ebd4 100644
--- a/client/src/components/Chat/Input/Files/DragDropWrapper.tsx
+++ b/client/src/components/Chat/Input/Files/DragDropWrapper.tsx
@@ -1,4 +1,4 @@
-import DragDropOverlay from '~/components/Chat/Input/Files/DragDropOverlay';
+import { DragDropOverlay } from '@librechat/chat/components';
import DragDropModal from '~/components/Chat/Input/Files/DragDropModal';
import { DragDropProvider, UploadModalProvider } from '~/Providers';
import { useDragHelpers } from '~/hooks';
diff --git a/client/src/components/Chat/Input/Files/FileRow.tsx b/client/src/components/Chat/Input/Files/FileRow.tsx
index bee3166100..7a46bbc810 100644
--- a/client/src/components/Chat/Input/Files/FileRow.tsx
+++ b/client/src/components/Chat/Input/Files/FileRow.tsx
@@ -1,13 +1,12 @@
import { useEffect } from 'react';
import { useToastContext } from '@librechat/client';
import { EToolResources } from 'librechat-data-provider';
+import { FileContainer, AttachmentImage as Image } from '@librechat/chat/components';
import type { ExtendedFile } from '~/common';
import { useDeleteFilesMutation } from '~/data-provider';
import { logger, getCachedPreview } from '~/utils';
import { useFileDeletion } from '~/hooks/Files';
-import FileContainer from './FileContainer';
import { useLocalize } from '~/hooks';
-import Image from './Image';
/**
* Shared wrapper with a stable module-scope identity. Passing an inline arrow as
diff --git a/client/src/components/Chat/Input/Files/Table/Columns.tsx b/client/src/components/Chat/Input/Files/Table/Columns.tsx
index 2f8b6c7543..ec50fb8089 100644
--- a/client/src/components/Chat/Input/Files/Table/Columns.tsx
+++ b/client/src/components/Chat/Input/Files/Table/Columns.tsx
@@ -1,6 +1,7 @@
/* eslint-disable react-hooks/rules-of-hooks */
import { FileSources, FileContext } from 'librechat-data-provider';
import { ArrowUpDown, ArrowUp, ArrowDown, Database } from 'lucide-react';
+import { ImagePreview, FilePreview, getFileType } from '@librechat/chat/components';
import {
Button,
Checkbox,
@@ -11,11 +12,9 @@ import {
} from '@librechat/client';
import type { ColumnDef } from '@tanstack/react-table';
import type { TFile } from 'librechat-data-provider';
-import ImagePreview from '~/components/Chat/Input/Files/ImagePreview';
-import FilePreview from '~/components/Chat/Input/Files/FilePreview';
import { TranslationKeys, useLocalize } from '~/hooks';
import { SortFilterHeader } from './SortFilterHeader';
-import { formatDate, getFileType } from '~/utils';
+import { formatDate } from '~/utils';
const contextMap: Record<any, TranslationKeys> = {
[FileContext.avatar]: 'com_ui_avatar',
diff --git a/client/src/components/Chat/Input/Files/__tests__/FileRow.spec.tsx b/client/src/components/Chat/Input/Files/__tests__/FileRow.spec.tsx
index c4cb734091..8ed712495d 100644
--- a/client/src/components/Chat/Input/Files/__tests__/FileRow.spec.tsx
+++ b/client/src/components/Chat/Input/Files/__tests__/FileRow.spec.tsx
@@ -25,8 +25,9 @@ jest.mock('~/utils', () => ({
getCachedPreview: jest.fn(() => undefined),
}));
-jest.mock('../Image', () => {
- return function MockImage({ url, progress, source }: any) {
+jest.mock('@librechat/chat/components', () => ({
+ ...jest.requireActual('@librechat/chat/components'),
+ AttachmentImage: function MockImage({ url, progress, source }: any) {
return (
<div data-testid="mock-image">
<span data-testid="image-url">{url}</span>
@@ -34,11 +35,8 @@ jest.mock('../Image', () => {
<span data-testid="image-source">{source}</span>
</div>
);
- };
-});
-
-jest.mock('../FileContainer', () => {
- return function MockFileContainer({ file, onClick, ariaLabel, subtitleAction }: any) {
+ },
+ FileContainer: function MockFileContainer({ file, onClick, ariaLabel, subtitleAction }: any) {
return (
<div data-testid="mock-file-container">
<span data-testid="file-name">{file.filename}</span>
@@ -54,8 +52,8 @@ jest.mock('../FileContainer', () => {
)}
</div>
);
- };
-});
+ },
+}));
const mockUseLocalize = jest.requireMock('~/hooks').useLocalize;
const mockUseDeleteFilesMutation = jest.requireMock('~/data-provider').useDeleteFilesMutation;
diff --git a/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx b/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx
index 4cb40b37c6..f2ec40ef18 100644
--- a/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx
+++ b/client/src/components/Chat/Input/__tests__/ChatForm.attachments.spec.tsx
@@ -8,6 +8,7 @@ import { RecoilRoot, useRecoilState } from 'recoil';
import userEvent from '@testing-library/user-event';
import { HTML5Backend } from 'react-dnd-html5-backend';
import { BrowserRouter as Router } from 'react-router-dom';
+import { FileContainer } from '@librechat/chat/components';
import { pendingQuotesByConvoId } from '@librechat/chat/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { QueryKeys, FileSources, EModelEndpoint } from 'librechat-data-provider';
@@ -18,7 +19,6 @@ import type { TranslationKeys } from '~/hooks/useLocalize';
import { getDraft, getPendingDraftId, setDraft } from '~/utils';
import { ChatContext, ChatFormProvider } from '~/Providers';
import { AuthContextProvider } from '~/hooks/AuthContext';
-import * as FileContainer from '../Files/FileContainer';
import { SteerHostTestProvider } from 'test/steerHost';
import ChatForm from '../ChatForm';
import store from '~/store';
@@ -27,6 +27,11 @@ const mockUpload = jest.fn();
const mockAsk = jest.fn();
// Production keeps `t` stable between language changes; the global test double does not.
+jest.mock('@librechat/chat/components', () => {
+ const actual = jest.requireActual('@librechat/chat/components');
+ return { ...actual, FileContainer: jest.fn(actual.FileContainer) };
+});
+
jest.mock('react-i18next', () => {
const actual = jest.requireActual<typeof import('react-i18next')>('react-i18next');
const t = (key: TranslationKeys, options?: import('i18next').TOptions) =>
@@ -473,7 +478,8 @@ describe('ChatForm attachments', () => {
expect(await screen.findByRole('button', { name: 'report.pdf' })).toBeVisible();
const textarea = screen.getByTestId('text-input');
await userEvent.click(textarea);
- const preview = jest.spyOn(FileContainer, 'default');
+ const preview = jest.mocked(FileContainer);
+ preview.mockClear();
await userEvent.type(textarea, 'read this document');
diff --git a/client/src/components/Chat/Messages/Content/EditFiles.tsx b/client/src/components/Chat/Messages/Content/EditFiles.tsx
index 5077d8e191..3d6e186aa2 100644
--- a/client/src/components/Chat/Messages/Content/EditFiles.tsx
+++ b/client/src/components/Chat/Messages/Content/EditFiles.tsx
@@ -1,7 +1,6 @@
import { useEffect, useRef } from 'react';
+import { FileContainer, AttachmentImage as Image } from '@librechat/chat/components';
import type { TFile } from 'librechat-data-provider';
-import FileContainer from '~/components/Chat/Input/Files/FileContainer';
-import Image from '~/components/Chat/Input/Files/Image';
import { getCachedPreview } from '~/utils';
import { useLocalize } from '~/hooks';
diff --git a/client/src/components/Chat/Messages/Content/Files.tsx b/client/src/components/Chat/Messages/Content/Files.tsx
index 097acb007b..cfa2a4e84b 100644
--- a/client/src/components/Chat/Messages/Content/Files.tsx
+++ b/client/src/components/Chat/Messages/Content/Files.tsx
@@ -1,7 +1,7 @@
import { useMemo, useState, useCallback, memo } from 'react';
+import { FileContainer } from '@librechat/chat/components';
import type { TFile, TMessage } from 'librechat-data-provider';
import { useMessagePartsHost } from '~/Providers/MessagePartsHostContext';
-import FileContainer from '~/components/Chat/Input/Files/FileContainer';
import { usesImagePreview, hydrateFileDeliveryMetadata } from '~/utils';
import FilePreviewDialog from './FilePreviewDialog';
import { useShareContext } from '~/Providers';
diff --git a/client/src/components/Chat/Messages/Content/Parts/Attachment.tsx b/client/src/components/Chat/Messages/Content/Parts/Attachment.tsx
index de94a205d5..2fcc84cdbe 100644
--- a/client/src/components/Chat/Messages/Content/Parts/Attachment.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/Attachment.tsx
@@ -1,6 +1,7 @@
import { memo, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from 'react';
import { Tools } from 'librechat-data-provider';
import { Button, useRemScale } from '@librechat/client';
+import { FileContainer } from '@librechat/chat/components';
import { Loader2, AlertCircle, Download, ChevronDown, Files as FilesIcon } from 'lucide-react';
import {
ARTIFACT_ROW_NAV_SPACING,
@@ -20,7 +21,6 @@ import {
renderAttachmentKey,
} from './attachmentTypes';
import { useLocalize, useAttachmentPreviewSync, useExpandCollapse } from '~/hooks';
-import FileContainer from '~/components/Chat/Input/Files/FileContainer';
import { fileToArtifact, TOOL_ARTIFACT_TYPES } from '~/utils/artifacts';
import Image from '~/components/Chat/Messages/Content/Image';
import ToolMermaidArtifact from './ToolMermaidArtifact';
diff --git a/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx b/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx
index 57b6d86925..ccb24ff3cd 100644
--- a/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/SteerPart.tsx
@@ -1,5 +1,10 @@
import { memo, useMemo, useState, useEffect, useCallback } from 'react';
-import { SteerReceipt, CollapsibleText, MessageTimestamp } from '@librechat/chat/components';
+import {
+ SteerReceipt,
+ FileContainer,
+ CollapsibleText,
+ MessageTimestamp,
+} from '@librechat/chat/components';
import type { SteerReceiptState } from '@librechat/chat/components';
import type { TFile, TMessage } from 'librechat-data-provider';
import FilePreviewDialog from '~/components/Chat/Messages/Content/FilePreviewDialog';
@@ -7,7 +12,6 @@ import MessageQuotes from '~/components/Chat/Messages/Content/MessageQuotes';
import { cn, hydrateFileDeliveryMetadata, usesImagePreview } from '~/utils';
import MarkdownLite from '~/components/Chat/Messages/Content/MarkdownLite';
import { useMessagePartsHost } from '~/Providers/MessagePartsHostContext';
-import FileContainer from '~/components/Chat/Input/Files/FileContainer';
import Image from '~/components/Chat/Messages/Content/Image';
import { useShareContext } from '~/Providers';
import { useLocalize } from '~/hooks';
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/ArtifactRouting.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/ArtifactRouting.test.tsx
index a4f9b52aae..6aeb918c58 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/ArtifactRouting.test.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/ArtifactRouting.test.tsx
@@ -29,16 +29,12 @@ jest.mock('../LogLink', () => ({
useAttachmentLink: () => ({ handleDownload: jest.fn() }),
}));
-jest.mock('~/components/Chat/Input/Files/FileContainer', () => ({
- __esModule: true,
- default: ({ file, displayName }: { file: { filename?: string }; displayName?: string }) => (
+jest.mock('@librechat/chat/components', () => ({
+ ...jest.requireActual('@librechat/chat/components'),
+ FileContainer: ({ file, displayName }: { file: { filename?: string }; displayName?: string }) => (
<div data-testid="file-container">{displayName ?? file.filename ?? ''}</div>
),
-}));
-
-jest.mock('~/components/Chat/Input/Files/FilePreview', () => ({
- __esModule: true,
- default: () => <div data-testid="file-preview" />,
+ FilePreview: () => <div data-testid="file-preview" />,
}));
jest.mock('~/components/Chat/Messages/Content/Image', () => ({
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/LogContent.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/LogContent.test.tsx
index f98b4e4eb3..ce5e78455e 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/LogContent.test.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/LogContent.test.tsx
@@ -32,9 +32,9 @@ jest.mock('../LogLink', () => ({
useAttachmentLink: () => ({ handleDownload: jest.fn() }),
}));
-jest.mock('~/components/Chat/Input/Files/FilePreview', () => ({
- __esModule: true,
- default: () => <div data-testid="file-preview" />,
+jest.mock('@librechat/chat/components', () => ({
+ ...jest.requireActual('@librechat/chat/components'),
+ FilePreview: () => <div data-testid="file-preview" />,
}));
jest.mock('~/components/Chat/Messages/Content/Image', () => ({
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx
index 319901739a..71d93c2c03 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/SteerPart.test.tsx
@@ -30,6 +30,11 @@ jest.mock('~/Providers', () => ({
jest.mock('@librechat/chat/components', () => ({
...jest.requireActual('@librechat/chat/components'),
MessageTimestamp: () => <time data-testid="steer-timestamp" />,
+ FileContainer: ({ file, onClick }: { file: { filename?: string }; onClick?: () => void }) => (
+ <button type="button" data-testid="steer-file" onClick={onClick}>
+ {file.filename}
+ </button>
+ ),
}));
jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({
@@ -37,15 +42,6 @@ jest.mock('~/components/Chat/Messages/Content/MarkdownLite', () => ({
default: ({ content }: { content: string }) => <span>{content}</span>,
}));
-jest.mock('~/components/Chat/Input/Files/FileContainer', () => ({
- __esModule: true,
- default: ({ file, onClick }: { file: { filename?: string }; onClick?: () => void }) => (
- <button type="button" data-testid="steer-file" onClick={onClick}>
- {file.filename}
- </button>
- ),
-}));
-
jest.mock('~/components/Chat/Messages/Content/FilePreviewDialog', () => ({
__esModule: true,
default: ({
diff --git a/client/src/components/Chat/Messages/Content/Parts/__tests__/TextAttachment.test.tsx b/client/src/components/Chat/Messages/Content/Parts/__tests__/TextAttachment.test.tsx
index f33704e8a1..db005a8adf 100644
--- a/client/src/components/Chat/Messages/Content/Parts/__tests__/TextAttachment.test.tsx
+++ b/client/src/components/Chat/Messages/Content/Parts/__tests__/TextAttachment.test.tsx
@@ -33,13 +33,14 @@ jest.mock('../LogLink', () => ({
useAttachmentLink: () => ({ handleDownload: mockHandleDownload }),
}));
-jest.mock('~/components/Chat/Input/Files/FileContainer', () => ({
- __esModule: true,
- default: ({ file, onClick }: { file: { filename?: string }; onClick?: () => void }) => (
+jest.mock('@librechat/chat/components', () => ({
+ ...jest.requireActual('@librechat/chat/components'),
+ FileContainer: ({ file, onClick }: { file: { filename?: string }; onClick?: () => void }) => (
<button type="button" data-testid="file-container" onClick={onClick}>
{file.filename ?? ''}
</button>
),
+ FilePreview: () => <div data-testid="file-preview" />,
}));
jest.mock('~/components/Chat/Messages/Content/Image', () => ({
@@ -54,11 +55,6 @@ jest.mock('~/components/Messages/Content/Mermaid/Mermaid', () => ({
),
}));
-jest.mock('~/components/Chat/Input/Files/FilePreview', () => ({
- __esModule: true,
- default: () => <div data-testid="file-preview" />,
-}));
-
jest.mock('~/utils', () => ({
cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),
getFileType: () => ({ paths: [], color: '', title: 'Artifact' }),
diff --git a/client/src/components/Chat/Messages/Content/__tests__/Files.test.tsx b/client/src/components/Chat/Messages/Content/__tests__/Files.test.tsx
index 802f3e9f52..01780b0dbe 100644
--- a/client/src/components/Chat/Messages/Content/__tests__/Files.test.tsx
+++ b/client/src/components/Chat/Messages/Content/__tests__/Files.test.tsx
@@ -8,15 +8,21 @@ jest.mock('~/Providers', () => ({
useFileMapContext: () => ({}),
useShareContext: () => ({}),
}));
-jest.mock(
- '~/components/Chat/Input/Files/FileContainer',
- () =>
- ({ onClick, buttonClassName }: { onClick: () => void; buttonClassName?: string }) => (
- <button className={buttonClassName} onClick={onClick}>
- file action
- </button>
- ),
-);
+jest.mock('@librechat/chat/components', () => ({
+ ...jest.requireActual('@librechat/chat/components'),
+ FileContainer: ({
+ onClick,
+ buttonClassName,
+ }: {
+ onClick: () => void;
+ buttonClassName?: string;
+ }) => (
+ <button className={buttonClassName} onClick={onClick}>
+ file action
+ </button>
+ ),
+}));
+
jest.mock(
'../Image',
() =>
diff --git a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx
index e1fdf19c7a..5ec6da0e12 100644
--- a/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx
+++ b/client/src/components/Chat/__tests__/ChatView.subagent.spec.tsx
@@ -23,6 +23,7 @@ jest.mock('@librechat/client', () => ({
}));
jest.mock('librechat-data-provider', () => ({
+ ...jest.requireActual('librechat-data-provider'),
Constants: { NEW_CONVO: 'new', SEARCH: 'search' },
buildTree: ({ messages }: { messages: unknown[] }) => messages,
}));
diff --git a/client/src/components/Input/SetKeyDialog/GoogleConfig.tsx b/client/src/components/Input/SetKeyDialog/GoogleConfig.tsx
index 7131960c25..f6aec59018 100644
--- a/client/src/components/Input/SetKeyDialog/GoogleConfig.tsx
+++ b/client/src/components/Input/SetKeyDialog/GoogleConfig.tsx
@@ -2,8 +2,8 @@ import React from 'react';
import { object, string } from 'zod';
import { Label } from '@librechat/client';
import { AuthKeys } from 'librechat-data-provider';
+import { FileUpload } from '@librechat/chat/components';
import type { TConfigProps } from '~/common';
-import FileUpload from '~/components/Chat/Input/Files/FileUpload';
import { useLocalize, useMultipleKeys } from '~/hooks';
import InputWithLabel from './InputWithLabel';
diff --git a/client/src/components/SidePanel/Builder/Images.tsx b/client/src/components/SidePanel/Builder/Images.tsx
index a1ae7711fa..9a9eab89ba 100644
--- a/client/src/components/SidePanel/Builder/Images.tsx
+++ b/client/src/components/SidePanel/Builder/Images.tsx
@@ -1,4 +1,4 @@
-import ProgressCircle from '~/components/Chat/Input/Files/ProgressCircle';
+import { ProgressCircle } from '@librechat/chat/components';
export function NoImage() {
return (
diff --git a/client/src/hooks/Files/__tests__/useFileDeletion.spec.tsx b/client/src/hooks/Files/__tests__/useFileDeletion.spec.tsx
index 2739ace894..5fbf1b37e2 100644
--- a/client/src/hooks/Files/__tests__/useFileDeletion.spec.tsx
+++ b/client/src/hooks/Files/__tests__/useFileDeletion.spec.tsx
@@ -41,8 +41,9 @@ jest.mock('../useSetFilesToDelete', () => ({
default: () => jest.fn(),
}));
-jest.mock('~/components/Chat/Input/Files/FileContainer', () => {
- return function MockFileContainer({
+jest.mock('@librechat/chat/components', () => ({
+ ...jest.requireActual('@librechat/chat/components'),
+ FileContainer: function MockFileContainer({
file,
onDelete,
}: {
@@ -50,14 +51,11 @@ jest.mock('~/components/Chat/Input/Files/FileContainer', () => {
onDelete: () => void;
}) {
return <button data-testid={`del-${file.file_id}`} onClick={onDelete} />;
- };
-});
-
-jest.mock('~/components/Chat/Input/Files/Image', () => {
- return function MockImage() {
+ },
+ AttachmentImage: function MockImage() {
return null;
- };
-});
+ },
+}));
const mockClearUploadRecovery = jest.requireMock('../useFileHandling').clearUploadRecovery;
diff --git a/client/src/hooks/Files/usePastedTextEdit.ts b/client/src/hooks/Files/usePastedTextEdit.ts
index 786ce1e299..f1c3c44662 100644
--- a/client/src/hooks/Files/usePastedTextEdit.ts
+++ b/client/src/hooks/Files/usePastedTextEdit.ts
@@ -7,6 +7,7 @@ import {
FileSources,
isAssistantsEndpoint,
} from 'librechat-data-provider';
+import type { PastedTextEdit } from '@librechat/chat/components';
import type { TFile } from 'librechat-data-provider';
import type { ExtendedFile, FileSetter } from '~/common';
import {
@@ -33,16 +34,6 @@ import { useAuthContext } from '~/hooks/AuthContext';
import useFileDeletion from './useFileDeletion';
import { useLocalize } from '~/hooks';
-/** The attachment being edited, with its text already resolved so the dialog stays controlled. */
-export type PastedTextEdit = {
- file: ExtendedFile;
- text: string;
- /** The composer the dialog was opened in; an edit must never apply to a different one. */
- conversationId: string | null;
- /** Distinguishes two successive unsaved chats, which share the `new` conversation id. */
- draftToken: symbol;
-};
-
/**
* Backs the paste editor: resolves an attached `pasted-text.txt` back to the text it holds, and
* applies an edit either as a replacement attachment or by returning the text to the composer.
diff --git a/client/src/utils/files.ts b/client/src/utils/files.ts
index b846996b09..491f496212 100644
--- a/client/src/utils/files.ts
+++ b/client/src/utils/files.ts
@@ -1,18 +1,9 @@
-import {
- TextPaths,
- FilePaths,
- CodePaths,
- AudioPaths,
- VideoPaths,
- SheetPaths,
-} from '@librechat/client';
import {
Tools,
megabyte,
Providers,
QueryKeys,
inferMimeType,
- excelMimeTypes,
EToolResources,
EModelEndpoint,
retrievalMimeTypes,
@@ -34,8 +25,6 @@ import type {
import type { QueryClient } from '@tanstack/react-query';
import type { ExtendedFile } from '~/common';
-export const partialTypes = ['text/x-'];
-
/** Text-routed images use the file action so their extracted preview is reachable. */
export function usesImagePreview(file: Partial<Pick<TFile, 'type' | 'llmDeliveryPath'>>): boolean {
return file.type?.startsWith('image/') === true && file.llmDeliveryPath !== 'text';
@@ -53,102 +42,6 @@ export function hasIncompleteFiles(files: Map<string, ExtendedFile>): boolean {
return false;
}
-const textDocument = {
- paths: TextPaths,
- fillClassName: 'fill-file-document',
- title: 'Document',
-};
-
-const spreadsheet = {
- paths: SheetPaths,
- fillClassName: 'fill-file-sheet',
- title: 'Spreadsheet',
-};
-
-const codeFile = {
- paths: CodePaths,
- fillClassName: 'fill-file-code',
- // TODO: make this dynamic to the language
- title: 'Code',
-};
-
-const artifact = {
- paths: CodePaths,
- fillClassName: 'fill-file-artifact',
- title: 'Code',
-};
-
-const audioFile = {
- paths: AudioPaths,
- fillClassName: 'fill-file-audio',
- title: 'Audio',
-};
-
-const videoFile = {
- paths: VideoPaths,
- fillClassName: 'fill-file-video',
- title: 'Video',
-};
-
-export const fileTypes = {
- /* Category matches */
- file: {
- paths: FilePaths,
- fillClassName: 'fill-file-generic',
- title: 'File',
- },
- text: textDocument,
- txt: textDocument,
- audio: audioFile,
- video: videoFile,
- // application:,
-
- /* Partial matches */
- csv: spreadsheet,
- 'application/pdf': textDocument,
- pdf: textDocument,
- 'text/x-': codeFile,
- artifact: artifact,
-
- /* Exact matches */
- // 'application/json':,
- // 'text/html':,
- // 'text/css':,
- // image,
-};
-
-export const getFileType = (
- type = '',
-): {
- paths: React.FC;
- fillClassName: string;
- title: string;
-} => {
- // Direct match check
- if (fileTypes[type]) {
- return fileTypes[type];
- }
-
- if (excelMimeTypes.test(type)) {
- return spreadsheet;
- }
-
- // Partial match check
- const partialMatch = partialTypes.find((partial) => type.includes(partial));
- if (partialMatch && fileTypes[partialMatch]) {
- return fileTypes[partialMatch];
- }
-
- // Category check
- const category = type.split('/')[0] || 'text';
- if (fileTypes[category]) {
- return fileTypes[category];
- }
-
- // Default file type
- return fileTypes.file;
-};
-
/**
* Format a date string to a human readable format
* @example
diff --git a/e2e/specs/mock/scenarios/composer-attachments.spec.ts b/e2e/specs/mock/scenarios/composer-attachments.spec.ts
new file mode 100644
index 0000000000..311ea2a3d1
--- /dev/null
+++ b/e2e/specs/mock/scenarios/composer-attachments.spec.ts
@@ -0,0 +1,65 @@
+import { expect, test } from '@playwright/test';
+import { MOCK_ENDPOINTS, NEW_CHAT_PATH, selectMockEndpoint } from '../helpers';
+
+/** Past the composer's paste-as-file threshold, so the paste lands as a chip. */
+const LONG_PASTE = Array.from(
+ { length: 60 },
+ (_, index) => `pasted line ${index + 1}: enough prose to cross the attach-as-file threshold`,
+).join('\n');
+
+test.describe('composer attachments', () => {
+ test('a long paste becomes a chip whose editor saves the corrected text @scenario:a-long-paste-becomes-an-editable-chip-whose-edit-is-saved', async ({
+ page,
+ }) => {
+ test.setTimeout(90000);
+ await page.goto(NEW_CHAT_PATH, { timeout: 10000 });
+ await selectMockEndpoint(page, MOCK_ENDPOINTS[0]);
+
+ const textarea = page.getByTestId('text-input');
+ await textarea.click();
+ const firstUpload = page.waitForResponse(
+ (response) =>
+ new URL(response.url()).pathname === '/api/files' && response.request().method() === 'POST',
+ { timeout: 30000 },
+ );
+ await textarea.evaluate((element, text) => {
+ const data = new DataTransfer();
+ data.setData('text/plain', text);
+ element.dispatchEvent(
+ new ClipboardEvent('paste', { clipboardData: data, bubbles: true, cancelable: true }),
+ );
+ }, LONG_PASTE);
+ expect((await firstUpload).ok()).toBe(true);
+
+ await expect(textarea).toHaveValue('');
+ const chip = page.getByRole('button', { name: 'Edit pasted text, pasted-text.txt' });
+ await expect(chip).toBeVisible();
+
+ await chip.click();
+ const dialog = page.getByRole('dialog', { name: 'Edit pasted text' });
+ const editor = dialog.getByRole('textbox', { name: 'Edit pasted text' });
+ await expect(editor).toHaveValue(LONG_PASTE);
+
+ const corrected = `${LONG_PASTE}\ncorrected closing line`;
+ await editor.fill(corrected);
+ const savedUpload = page.waitForResponse(
+ (response) =>
+ new URL(response.url()).pathname === '/api/files' && response.request().method() === 'POST',
+ { timeout: 30000 },
+ );
+ await dialog.getByRole('button', { name: 'Save' }).click();
+ expect((await savedUpload).ok()).toBe(true);
+ await expect(dialog).toBeHidden();
+
+ /** The correction uploads under a free name, so the edited text lives on its own chip. */
+ const replacement = page.getByRole('button', {
+ name: 'Edit pasted text, pasted-text-2.txt',
+ });
+ await expect(replacement).toBeVisible({ timeout: 15000 });
+ await replacement.click();
+ const reopened = page.getByRole('dialog', { name: 'Edit pasted text' });
+ await expect(reopened.getByRole('textbox')).toHaveValue(corrected);
+ await page.keyboard.press('Escape');
+ await expect(reopened).toBeHidden();
+ });
+});
diff --git a/eslint-suppressions.json b/eslint-suppressions.json
index 1531db7d48..7bc6d95c9d 100644
--- a/eslint-suppressions.json
+++ b/eslint-suppressions.json
@@ -109,47 +109,11 @@
"count": 1
}
},
- "client/src/components/Chat/Input/Files/DragDropOverlay.tsx": {
- "shadcn/no-inline-styles": {
- "count": 3
- }
- },
- "client/src/components/Chat/Input/Files/FileUpload.tsx": {
- "shadcn/no-restyle": {
- "count": 11
- },
- "shadcn/require-static-classes": {
- "count": 2
- }
- },
- "client/src/components/Chat/Input/Files/ImagePreview.tsx": {
- "shadcn/no-inline-styles": {
- "count": 3
- }
- },
"client/src/components/Chat/Input/Files/MyFilesModal.tsx": {
"shadcn/no-restyle": {
"count": 2
}
},
- "client/src/components/Chat/Input/Files/PastedTextDialog.tsx": {
- "shadcn/no-restyle": {
- "count": 2
- }
- },
- "client/src/components/Chat/Input/Files/ProgressCircle.tsx": {
- "shadcn/no-arbitrary-values": {
- "count": 1
- },
- "shadcn/no-inline-styles": {
- "count": 1
- }
- },
- "client/src/components/Chat/Input/Files/SourceIcon.tsx": {
- "shadcn/no-arbitrary-values": {
- "count": 1
- }
- },
"client/src/components/Chat/Input/Files/Table/ColumnVisibilityDropdown.tsx": {
"design/disabled-recipe": {
"count": 1
@@ -1414,6 +1378,42 @@
"count": 1
}
},
+ "packages/chat/src/components/composer/files/DragDropOverlay.tsx": {
+ "shadcn/no-inline-styles": {
+ "count": 3
+ }
+ },
+ "packages/chat/src/components/composer/files/FileUpload.tsx": {
+ "shadcn/no-restyle": {
+ "count": 11
+ },
+ "shadcn/require-static-classes": {
+ "count": 2
+ }
+ },
+ "packages/chat/src/components/composer/files/ImagePreview.tsx": {
+ "shadcn/no-inline-styles": {
+ "count": 3
+ }
+ },
+ "packages/chat/src/components/composer/files/PastedTextDialog.tsx": {
+ "shadcn/no-restyle": {
+ "count": 2
+ }
+ },
+ "packages/chat/src/components/composer/files/ProgressCircle.tsx": {
+ "shadcn/no-arbitrary-values": {
+ "count": 1
+ },
+ "shadcn/no-inline-styles": {
+ "count": 1
+ }
+ },
+ "packages/chat/src/components/composer/files/SourceIcon.tsx": {
+ "shadcn/no-arbitrary-values": {
+ "count": 1
+ }
+ },
"packages/chat/src/components/messages/HeaderLabel.tsx": {
"shadcn/no-arbitrary-values": {
"count": 5
diff --git a/package-lock.json b/package-lock.json
index e1a544fdd6..251b0a0171 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -41452,6 +41452,7 @@
"@babel/preset-react": "^7.22.15",
"@babel/preset-typescript": "^7.21.0",
"@librechat/client": "*",
+ "@radix-ui/react-dialog": "^1.1.23",
"@tanstack/react-query": "^4.28.0",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^14.0.0",
@@ -41475,6 +41476,7 @@
},
"peerDependencies": {
"@librechat/client": "*",
+ "@radix-ui/react-dialog": "^1.1.23",
"@tanstack/react-query": "^4.28.0",
"jotai": "^2.12.5",
"librechat-data-provider": "*",
diff --git a/packages/chat/package.json b/packages/chat/package.json
index f689509692..5f7c8eabb3 100644
--- a/packages/chat/package.json
+++ b/packages/chat/package.json
@@ -59,6 +59,7 @@
},
"peerDependencies": {
"@librechat/client": "*",
+ "@radix-ui/react-dialog": "^1.1.23",
"@tanstack/react-query": "^4.28.0",
"jotai": "^2.12.5",
"librechat-data-provider": "*",
@@ -75,6 +76,7 @@
"@babel/preset-react": "^7.22.15",
"@babel/preset-typescript": "^7.21.0",
"@librechat/client": "*",
+ "@radix-ui/react-dialog": "^1.1.23",
"@tanstack/react-query": "^4.28.0",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^14.0.0",
diff --git a/packages/chat/src/components.ts b/packages/chat/src/components.ts
index d0918b90c4..309e1dc183 100644
--- a/packages/chat/src/components.ts
+++ b/packages/chat/src/components.ts
@@ -33,6 +33,18 @@ export type { ComposerSubmitRoute } from './components/composer/submit';
export type { MentionItemProps } from './components/composer/MentionItem';
export type { ChipProps as ComposerChipProps } from './components/composer/bar/Chip';
export type { SteerReceiptState } from './components/composer/steering/Receipt';
+export { default as FileUpload } from './components/composer/files/FileUpload';
+export { default as RemoveFile } from './components/composer/files/RemoveFile';
+export { default as SourceIcon } from './components/composer/files/SourceIcon';
+export { default as FilePreview } from './components/composer/files/FilePreview';
+export { default as ProgressCircle } from './components/composer/files/ProgressCircle';
+export { default as FileContainer } from './components/composer/files/FileContainer';
+export { default as DragDropOverlay } from './components/composer/files/DragDropOverlay';
+export { default as PastedTextDialog } from './components/composer/files/PastedTextDialog';
+export { getFileType } from './components/composer/files/kinds';
+export type { FileKind } from './components/composer/files/kinds';
+export type { SubtitleAction } from './components/composer/files/FileContainer';
+export type { PastedTextEdit } from './components/composer/files/PastedTextDialog';
/** Message list building blocks: rows, headers, sibling navigation and the streaming timer. */
export { default as SubRow } from './components/messages/SubRow';
@@ -74,3 +86,5 @@ export {
FOLD_GLYPH_SELECTOR,
ARTIFACT_ROW_NAV_SPACING,
} from './components/parts/rows';
+export { default as AttachmentImage } from './components/composer/files/Image';
+export { default as ImagePreview } from './components/composer/files/ImagePreview';
diff --git a/client/src/components/Chat/Input/Files/DragDropOverlay.tsx b/packages/chat/src/components/composer/files/DragDropOverlay.tsx
similarity index 96%
rename from client/src/components/Chat/Input/Files/DragDropOverlay.tsx
rename to packages/chat/src/components/composer/files/DragDropOverlay.tsx
index a04b8772d7..db0ac20dd5 100644
--- a/client/src/components/Chat/Input/Files/DragDropOverlay.tsx
+++ b/packages/chat/src/components/composer/files/DragDropOverlay.tsx
@@ -1,11 +1,12 @@
import { memo } from 'react';
-import { useLocalize } from '~/hooks';
+import { useLocalize } from '@librechat/client';
+import type { NamedExoticComponent } from 'react';
interface DragDropOverlayProps {
isActive: boolean;
}
-const DragDropOverlay = memo(({ isActive }: DragDropOverlayProps) => {
+const DragDropOverlay: NamedExoticComponent<DragDropOverlayProps> = memo(({ isActive }) => {
const localize = useLocalize();
return (
<>
diff --git a/client/src/components/Chat/Input/Files/FileContainer.tsx b/packages/chat/src/components/composer/files/FileContainer.tsx
similarity index 97%
rename from client/src/components/Chat/Input/Files/FileContainer.tsx
rename to packages/chat/src/components/composer/files/FileContainer.tsx
index 221cfabfd7..08550ae7ea 100644
--- a/client/src/components/Chat/Input/Files/FileContainer.tsx
+++ b/packages/chat/src/components/composer/files/FileContainer.tsx
@@ -1,8 +1,9 @@
+import { cn } from '@librechat/client';
import type { TFile } from 'librechat-data-provider';
import type { ReactNode } from 'react';
-import type { ExtendedFile } from '~/common';
-import { getFileType, cn } from '~/utils';
+import type { ExtendedFile } from '../../../core/files';
import FilePreview from './FilePreview';
+import { getFileType } from './kinds';
import RemoveFile from './RemoveFile';
/** A second action offered in place of the subtitle, stated on the chip rather than revealed on hover. */
@@ -62,7 +63,7 @@ const FileContainer = ({
removeLabel?: string;
removeDisabled?: boolean;
onClick?: React.MouseEventHandler<HTMLButtonElement>;
-}) => {
+}): React.JSX.Element => {
const fileType = getFileType(overrideType ?? file.type);
const visibleName = displayName ?? file.filename ?? '';
const interactive = onClick != null;
diff --git a/client/src/components/Chat/Input/Files/FilePreview.tsx b/packages/chat/src/components/composer/files/FilePreview.tsx
similarity index 76%
rename from client/src/components/Chat/Input/Files/FilePreview.tsx
rename to packages/chat/src/components/composer/files/FilePreview.tsx
index b33a8415b9..c0075dbc5c 100644
--- a/client/src/components/Chat/Input/Files/FilePreview.tsx
+++ b/packages/chat/src/components/composer/files/FilePreview.tsx
@@ -1,8 +1,7 @@
-import { Spinner, FileIcon } from '@librechat/client';
+import { cn, Spinner, FileIcon } from '@librechat/client';
import type { TFile } from 'librechat-data-provider';
-import type { ExtendedFile } from '~/common';
+import type { ExtendedFile } from '../../../core/files';
import SourceIcon from './SourceIcon';
-import { cn } from '~/utils';
const FilePreview = ({
file,
@@ -16,12 +15,13 @@ const FilePreview = ({
title: string;
};
className?: string;
-}) => {
+}): React.JSX.Element => {
+ const progress = file != null && 'progress' in file ? file.progress : undefined;
return (
<div className={cn('relative size-10 shrink-0 overflow-hidden rounded-xl', className)}>
<FileIcon file={file} fileType={fileType} />
<SourceIcon source={file?.source} isCodeFile={!!file?.['metadata']?.fileIdentifier} />
- {typeof file?.['progress'] === 'number' && file?.['progress'] < 1 && (
+ {typeof progress === 'number' && progress < 1 && (
/* The spinner strokes in currentColor, so it takes the glyph's ink: white on the stock
* tiles, black on the light high-contrast dark tiles. */
<span className="text-file-ink absolute inset-0 m-2.5 flex items-center justify-center">
diff --git a/client/src/components/Chat/Input/Files/FileUpload.tsx b/packages/chat/src/components/composer/files/FileUpload.tsx
similarity index 96%
rename from client/src/components/Chat/Input/Files/FileUpload.tsx
rename to packages/chat/src/components/composer/files/FileUpload.tsx
index aa80f8f97e..7c3e803160 100644
--- a/client/src/components/Chat/Input/Files/FileUpload.tsx
+++ b/packages/chat/src/components/composer/files/FileUpload.tsx
@@ -1,8 +1,6 @@
import React, { useState } from 'react';
import { FileUp } from 'lucide-react';
-import { Button } from '@librechat/client';
-import { useLocalize } from '~/hooks';
-import { cn } from '~/utils/';
+import { cn, Button, useLocalize } from '@librechat/client';
type FileUploadProps = {
onFileSelected: (jsonData: Record<string, unknown>) => void;
diff --git a/client/src/components/Chat/Input/Files/Image.tsx b/packages/chat/src/components/composer/files/Image.tsx
similarity index 97%
rename from client/src/components/Chat/Input/Files/Image.tsx
rename to packages/chat/src/components/composer/files/Image.tsx
index 443a9df219..0720faae58 100644
--- a/client/src/components/Chat/Input/Files/Image.tsx
+++ b/packages/chat/src/components/composer/files/Image.tsx
@@ -18,7 +18,7 @@ const Image = ({
source?: FileSources;
removeLabel?: string;
removeDisabled?: boolean;
-}) => {
+}): React.JSX.Element => {
return (
<div className="group text-text-secondary relative inline-block text-sm">
{/* `flex`, so the button inside is not laid out on a text baseline: the
diff --git a/client/src/components/Chat/Input/Files/ImagePreview.tsx b/packages/chat/src/components/composer/files/ImagePreview.tsx
similarity index 98%
rename from client/src/components/Chat/Input/Files/ImagePreview.tsx
rename to packages/chat/src/components/composer/files/ImagePreview.tsx
index 05088d9cf9..3ba6e175a8 100644
--- a/client/src/components/Chat/Input/Files/ImagePreview.tsx
+++ b/packages/chat/src/components/composer/files/ImagePreview.tsx
@@ -1,12 +1,10 @@
import { useState, useEffect, useCallback, useRef } from 'react';
-import { Button } from '@librechat/client';
import { Maximize2, X } from 'lucide-react';
import { FileSources } from 'librechat-data-provider';
import * as DialogPrimitive from '@radix-ui/react-dialog';
+import { cn, Button, useLocalize } from '@librechat/client';
import ProgressCircle from './ProgressCircle';
import SourceIcon from './SourceIcon';
-import { useLocalize } from '~/hooks';
-import { cn } from '~/utils';
type styleProps = {
backgroundImage?: string;
@@ -29,7 +27,7 @@ const ImagePreview = ({
className?: string;
source?: FileSources;
alt?: string;
-}) => {
+}): React.JSX.Element | null => {
const localize = useLocalize();
const [isModalOpen, setIsModalOpen] = useState(false);
const [isHovered, setIsHovered] = useState(false);
diff --git a/client/src/components/Chat/Input/Files/PastedTextDialog.tsx b/packages/chat/src/components/composer/files/PastedTextDialog.tsx
similarity index 80%
rename from client/src/components/Chat/Input/Files/PastedTextDialog.tsx
rename to packages/chat/src/components/composer/files/PastedTextDialog.tsx
index 6d6c88bd58..5fbc04aa73 100644
--- a/client/src/components/Chat/Input/Files/PastedTextDialog.tsx
+++ b/packages/chat/src/components/composer/files/PastedTextDialog.tsx
@@ -2,14 +2,24 @@ import { useId, useState } from 'react';
import {
Button,
OGDialog,
+ useLocalize,
Textarea,
OGDialogClose,
OGDialogTitle,
OGDialogHeader,
OGDialogContent,
} from '@librechat/client';
-import type { PastedTextEdit } from '~/hooks/Files/usePastedTextEdit';
-import { useLocalize } from '~/hooks';
+import type { ExtendedFile } from '../../../core/files';
+
+/** The attachment being edited, with its text already resolved so the dialog stays controlled. */
+export type PastedTextEdit = {
+ file: ExtendedFile;
+ text: string;
+ /** The composer the dialog was opened in; an edit must never apply to a different one. */
+ conversationId: string | null;
+ /** Distinguishes two successive unsaved chats, which share the `new` conversation id. */
+ draftToken: symbol;
+};
/**
* Opens the text behind a `pasted-text.txt` chip so it can be corrected before sending. Returning
@@ -24,7 +34,7 @@ export default function PastedTextDialog({
edit: PastedTextEdit | null;
onClose: () => void;
onSave: (text: string) => void;
-}) {
+}): React.JSX.Element {
const localize = useLocalize();
const fieldId = useId();
const [text, setText] = useState('');
diff --git a/client/src/components/Chat/Input/Files/ProgressCircle.tsx b/packages/chat/src/components/composer/files/ProgressCircle.tsx
similarity index 97%
rename from client/src/components/Chat/Input/Files/ProgressCircle.tsx
rename to packages/chat/src/components/composer/files/ProgressCircle.tsx
index ac7e70e0e8..d55ab195e0 100644
--- a/client/src/components/Chat/Input/Files/ProgressCircle.tsx
+++ b/packages/chat/src/components/composer/files/ProgressCircle.tsx
@@ -6,7 +6,7 @@ export default function ProgressCircle({
circumference: number;
offset: number;
circleCSSProperties: React.CSSProperties;
-}) {
+}): React.JSX.Element {
return (
<div className="bg-surface-media-overlay/5 text-text-on-media absolute inset-0 flex items-center justify-center">
<svg width="120" height="120" viewBox="0 0 120 120" className="h-6 w-6">
diff --git a/client/src/components/Chat/Input/Files/RemoveFile.tsx b/packages/chat/src/components/composer/files/RemoveFile.tsx
similarity index 94%
rename from client/src/components/Chat/Input/Files/RemoveFile.tsx
rename to packages/chat/src/components/composer/files/RemoveFile.tsx
index 32cccc8bf2..c689397581 100644
--- a/client/src/components/Chat/Input/Files/RemoveFile.tsx
+++ b/packages/chat/src/components/composer/files/RemoveFile.tsx
@@ -1,4 +1,4 @@
-import { useLocalize } from '~/hooks';
+import { useLocalize } from '@librechat/client';
export default function RemoveFile({
onRemove,
@@ -9,7 +9,7 @@ export default function RemoveFile({
disabled?: boolean;
/** Names the file, where several chips sit side by side and "Remove file" would not say which. */
label?: string;
-}) {
+}): React.JSX.Element {
const localize = useLocalize();
return (
<button
diff --git a/client/src/components/Chat/Input/Files/SourceIcon.tsx b/packages/chat/src/components/composer/files/SourceIcon.tsx
similarity index 65%
rename from client/src/components/Chat/Input/Files/SourceIcon.tsx
rename to packages/chat/src/components/composer/files/SourceIcon.tsx
index ffc7317e89..d1760315ad 100644
--- a/client/src/components/Chat/Input/Files/SourceIcon.tsx
+++ b/packages/chat/src/components/composer/files/SourceIcon.tsx
@@ -1,14 +1,16 @@
+import { cn } from '@librechat/client';
import { Terminal, Type, Database } from 'lucide-react';
import { EModelEndpoint, FileSources } from 'librechat-data-provider';
-import { MinimalIcon } from '~/components/Endpoints';
-import { cn } from '~/utils';
+import { useFilesHost } from '../../../react/files';
-const sourceToEndpoint = {
+/** Built per render rather than at import, so loading the components entry reads no
+ * `librechat-data-provider` enums; specs that replace that module can still import it. */
+const sourceToEndpoint = (): Partial<Record<string, EModelEndpoint>> => ({
[FileSources.openai]: EModelEndpoint.openAI,
[FileSources.azure]: EModelEndpoint.azureOpenAI,
-};
+});
-const sourceToClassname = {
+const sourceToClassname = (): Partial<Record<string, string>> => ({
[FileSources.openai]: 'bg-white/75 dark:bg-black/65',
[FileSources.azure]: 'azure-bg-color',
[FileSources.azure_blob]: 'azure-bg-color',
@@ -18,7 +20,7 @@ const sourceToClassname = {
* composited the fill back into the preview the badge sits on. */
[FileSources.text]: 'bg-series-1 text-text-on-status',
[FileSources.vectordb]: 'bg-series-4 text-text-on-status',
-};
+});
const defaultClassName =
'absolute inset-e-0 bottom-0 rounded-full p-[0.15rem] text-text-secondary transition-colors';
@@ -31,10 +33,11 @@ export default function SourceIcon({
source?: FileSources;
isCodeFile?: boolean;
className?: string;
-}) {
+}): React.JSX.Element | null {
+ const { renderEndpointIcon } = useFilesHost();
if (isCodeFile === true) {
return (
- <div className={cn(className, sourceToClassname[FileSources.execute_code] ?? '')}>
+ <div className={cn(className, sourceToClassname()[FileSources.execute_code] ?? '')}>
<span className="flex items-center justify-center">
<Terminal className="h-3 w-3" aria-hidden="true" />
</span>
@@ -44,7 +47,7 @@ export default function SourceIcon({
if (source === FileSources.text) {
return (
- <div className={cn(className, sourceToClassname[source] ?? '')}>
+ <div className={cn(className, sourceToClassname()[source] ?? '')}>
<span className="flex items-center justify-center">
<Type className="h-3 w-3" aria-hidden="true" />
</span>
@@ -54,7 +57,7 @@ export default function SourceIcon({
if (source === FileSources.vectordb) {
return (
- <div className={cn(className, sourceToClassname[source] ?? '')}>
+ <div className={cn(className, sourceToClassname()[source] ?? '')}>
<span className="flex items-center justify-center">
<Database className="h-3 w-3" aria-hidden="true" />
</span>
@@ -62,21 +65,14 @@ export default function SourceIcon({
);
}
- const endpoint = sourceToEndpoint[source ?? ''];
+ const endpoint = sourceToEndpoint()[source ?? ''];
if (!endpoint) {
return null;
}
return (
- <div className={cn(className, sourceToClassname[source ?? ''] ?? '')}>
- <span className="flex items-center justify-center">
- <MinimalIcon
- endpoint={endpoint}
- size={14}
- isCreatedByUser={false}
- iconClassName="h-3 w-3"
- />
- </span>
+ <div className={cn(className, sourceToClassname()[source ?? ''] ?? '')}>
+ <span className="flex items-center justify-center">{renderEndpointIcon(endpoint)}</span>
</div>
);
}
diff --git a/client/src/components/Chat/Input/Files/__tests__/FileContainer.spec.tsx b/packages/chat/src/components/composer/files/__tests__/FileContainer.spec.tsx
similarity index 97%
rename from client/src/components/Chat/Input/Files/__tests__/FileContainer.spec.tsx
rename to packages/chat/src/components/composer/files/__tests__/FileContainer.spec.tsx
index 65e64f3f50..b8a21cac8d 100644
--- a/client/src/components/Chat/Input/Files/__tests__/FileContainer.spec.tsx
+++ b/packages/chat/src/components/composer/files/__tests__/FileContainer.spec.tsx
@@ -1,3 +1,6 @@
+/**
+ * @jest-environment jsdom
+ */
import React from 'react';
import userEvent from '@testing-library/user-event';
import { render, screen } from '@testing-library/react';
@@ -5,9 +8,8 @@ import '@testing-library/jest-dom';
import type { TFile } from 'librechat-data-provider';
import FileContainer from '../FileContainer';
-jest.mock('~/utils', () => ({
- cn: (...classes: Array<string | false | null | undefined>) => classes.filter(Boolean).join(' '),
- getFileType: () => ({ paths: [], color: '', title: 'Plain' }),
+jest.mock('../kinds', () => ({
+ getFileType: () => ({ paths: () => null, fillClassName: '', title: 'Plain' }),
}));
jest.mock('../FilePreview', () => ({
diff --git a/client/src/components/Chat/Input/Files/__tests__/ImagePreview.spec.tsx b/packages/chat/src/components/composer/files/__tests__/ImagePreview.spec.tsx
similarity index 98%
rename from client/src/components/Chat/Input/Files/__tests__/ImagePreview.spec.tsx
rename to packages/chat/src/components/composer/files/__tests__/ImagePreview.spec.tsx
index f408b11e37..bfe672729b 100644
--- a/client/src/components/Chat/Input/Files/__tests__/ImagePreview.spec.tsx
+++ b/packages/chat/src/components/composer/files/__tests__/ImagePreview.spec.tsx
@@ -1,3 +1,6 @@
+/**
+ * @jest-environment jsdom
+ */
import React from 'react';
import '@testing-library/jest-dom';
import { render, screen, fireEvent } from '@testing-library/react';
diff --git a/client/src/components/Chat/Input/Files/__tests__/PastedTextDialog.spec.tsx b/packages/chat/src/components/composer/files/__tests__/PastedTextDialog.spec.tsx
similarity index 92%
rename from client/src/components/Chat/Input/Files/__tests__/PastedTextDialog.spec.tsx
rename to packages/chat/src/components/composer/files/__tests__/PastedTextDialog.spec.tsx
index e22998ca87..fc849d4d58 100644
--- a/client/src/components/Chat/Input/Files/__tests__/PastedTextDialog.spec.tsx
+++ b/packages/chat/src/components/composer/files/__tests__/PastedTextDialog.spec.tsx
@@ -1,12 +1,16 @@
+/**
+ * @jest-environment jsdom
+ */
import React from 'react';
import userEvent from '@testing-library/user-event';
import { render, screen } from '@testing-library/react';
import '@testing-library/jest-dom';
-import type { PastedTextEdit } from '~/hooks/Files/usePastedTextEdit';
-import type { ExtendedFile } from '~/common';
+import type { ExtendedFile } from '../../../../core/files';
+import type { PastedTextEdit } from '../PastedTextDialog';
import PastedTextDialog from '../PastedTextDialog';
-jest.mock('~/hooks', () => ({
+jest.mock('@librechat/client', () => ({
+ ...jest.requireActual('@librechat/client'),
useLocalize: () => (key: string) => key,
}));
diff --git a/packages/chat/src/components/composer/files/__tests__/RemoveFile.spec.tsx b/packages/chat/src/components/composer/files/__tests__/RemoveFile.spec.tsx
new file mode 100644
index 0000000000..a2b49230f4
--- /dev/null
+++ b/packages/chat/src/components/composer/files/__tests__/RemoveFile.spec.tsx
@@ -0,0 +1,24 @@
+/**
+ * @jest-environment jsdom
+ */
+import React from 'react';
+import { fireEvent, render, screen } from '@testing-library/react';
+import RemoveFile from '../RemoveFile';
+
+jest.mock('@librechat/client', () => ({
+ ...jest.requireActual('@librechat/client'),
+ useLocalize: () => (key: string) => key,
+}));
+
+describe('RemoveFile', () => {
+ it('names the file it removes, or falls back to the generic label', () => {
+ const onRemove = jest.fn();
+ const { rerender } = render(<RemoveFile onRemove={onRemove} label="Remove report.pdf" />);
+
+ fireEvent.click(screen.getByRole('button', { name: 'Remove report.pdf' }));
+ expect(onRemove).toHaveBeenCalledTimes(1);
+
+ rerender(<RemoveFile onRemove={onRemove} disabled />);
+ expect(screen.getByRole('button', { name: 'com_ui_attach_remove' })).toBeDisabled();
+ });
+});
diff --git a/packages/chat/src/components/composer/files/__tests__/SourceIcon.spec.tsx b/packages/chat/src/components/composer/files/__tests__/SourceIcon.spec.tsx
new file mode 100644
index 0000000000..3294b35097
--- /dev/null
+++ b/packages/chat/src/components/composer/files/__tests__/SourceIcon.spec.tsx
@@ -0,0 +1,41 @@
+/**
+ * @jest-environment jsdom
+ */
+import React from 'react';
+import { render, screen } from '@testing-library/react';
+import { EModelEndpoint, FileSources } from 'librechat-data-provider';
+import type { FilesHost } from '../../../../react/files';
+import { FilesHostProvider } from '../../../../react/files';
+import SourceIcon from '../SourceIcon';
+
+const host: FilesHost = {
+ renderEndpointIcon: (endpoint) => <span data-testid="endpoint-icon">{endpoint}</span>,
+};
+
+describe('SourceIcon', () => {
+ it('draws the host mark for a provider-stored file', () => {
+ render(
+ <FilesHostProvider host={host}>
+ <SourceIcon source={FileSources.azure} />
+ </FilesHostProvider>,
+ );
+ expect(screen.getByTestId('endpoint-icon')).toHaveTextContent(EModelEndpoint.azureOpenAI);
+ });
+
+ it('keeps the badge without a mark when no host is mounted', () => {
+ const { container } = render(<SourceIcon source={FileSources.openai} />);
+ expect(container.firstElementChild).not.toBeNull();
+ expect(screen.queryByTestId('endpoint-icon')).toBeNull();
+ });
+
+ it('draws its own glyph for code, text and vector sources and nothing for local files', () => {
+ const { container, rerender } = render(<SourceIcon isCodeFile />);
+ expect(container.querySelector('svg')).not.toBeNull();
+
+ rerender(<SourceIcon source={FileSources.vectordb} />);
+ expect(container.firstElementChild).toHaveClass('bg-series-4');
+
+ rerender(<SourceIcon source={FileSources.local} />);
+ expect(container).toBeEmptyDOMElement();
+ });
+});
diff --git a/packages/chat/src/components/composer/files/__tests__/kinds.spec.ts b/packages/chat/src/components/composer/files/__tests__/kinds.spec.ts
new file mode 100644
index 0000000000..228dcdda50
--- /dev/null
+++ b/packages/chat/src/components/composer/files/__tests__/kinds.spec.ts
@@ -0,0 +1,17 @@
+import { fileTypes, getFileType } from '../kinds';
+
+describe('getFileType', () => {
+ it('matches exact, partial, spreadsheet and category types', () => {
+ expect(getFileType('application/pdf').title).toBe('Document');
+ expect(getFileType('text/x-python').title).toBe('Code');
+ expect(
+ getFileType('application/vnd.openxmlformats-officedocument.spreadsheetml.sheet').title,
+ ).toBe('Spreadsheet');
+ expect(getFileType('audio/mpeg').fillClassName).toBe('fill-file-audio');
+ });
+
+ it('falls back to a generic file', () => {
+ expect(getFileType('application/octet-stream')).toBe(fileTypes.file);
+ expect(getFileType()).toBe(fileTypes.text);
+ });
+});
diff --git a/packages/chat/src/components/composer/files/kinds.ts b/packages/chat/src/components/composer/files/kinds.ts
new file mode 100644
index 0000000000..9b9ae26f01
--- /dev/null
+++ b/packages/chat/src/components/composer/files/kinds.ts
@@ -0,0 +1,109 @@
+import { excelMimeTypes } from 'librechat-data-provider';
+import {
+ TextPaths,
+ FilePaths,
+ CodePaths,
+ AudioPaths,
+ VideoPaths,
+ SheetPaths,
+} from '@librechat/client';
+import type { FC } from 'react';
+
+/** How a file renders in an attachment card: the glyph, its fill role, and its kind's name. */
+export type FileKind = {
+ paths: FC;
+ fillClassName: string;
+ title: string;
+};
+
+export const partialTypes: string[] = ['text/x-'];
+
+const textDocument = {
+ paths: TextPaths,
+ fillClassName: 'fill-file-document',
+ title: 'Document',
+};
+
+const spreadsheet = {
+ paths: SheetPaths,
+ fillClassName: 'fill-file-sheet',
+ title: 'Spreadsheet',
+};
+
+const codeFile = {
+ paths: CodePaths,
+ fillClassName: 'fill-file-code',
+ // TODO: make this dynamic to the language
+ title: 'Code',
+};
+
+const artifact = {
+ paths: CodePaths,
+ fillClassName: 'fill-file-artifact',
+ title: 'Code',
+};
+
+const audioFile = {
+ paths: AudioPaths,
+ fillClassName: 'fill-file-audio',
+ title: 'Audio',
+};
+
+const videoFile = {
+ paths: VideoPaths,
+ fillClassName: 'fill-file-video',
+ title: 'Video',
+};
+
+export const fileTypes: Record<string, FileKind> = {
+ /* Category matches */
+ file: {
+ paths: FilePaths,
+ fillClassName: 'fill-file-generic',
+ title: 'File',
+ },
+ text: textDocument,
+ txt: textDocument,
+ audio: audioFile,
+ video: videoFile,
+ // application:,
+
+ /* Partial matches */
+ csv: spreadsheet,
+ 'application/pdf': textDocument,
+ pdf: textDocument,
+ 'text/x-': codeFile,
+ artifact: artifact,
+
+ /* Exact matches */
+ // 'application/json':,
+ // 'text/html':,
+ // 'text/css':,
+ // image,
+};
+
+export const getFileType = (type = ''): FileKind => {
+ // Direct match check
+ if (fileTypes[type]) {
+ return fileTypes[type];
+ }
+
+ if (excelMimeTypes.test(type)) {
+ return spreadsheet;
+ }
+
+ // Partial match check
+ const partialMatch = partialTypes.find((partial) => type.includes(partial));
+ if (partialMatch && fileTypes[partialMatch]) {
+ return fileTypes[partialMatch];
+ }
+
+ // Category check
+ const category = type.split('/')[0] || 'text';
+ if (fileTypes[category]) {
+ return fileTypes[category];
+ }
+
+ // Default file type
+ return fileTypes.file;
+};
diff --git a/packages/chat/src/react.ts b/packages/chat/src/react.ts
index fa69a17ec3..1c72201cdc 100644
--- a/packages/chat/src/react.ts
+++ b/packages/chat/src/react.ts
@@ -151,3 +151,5 @@ export type {
export { boundIntentLabel, getToolCallIntent, useToolCallIntent } from './react/parts/intent';
export { default as useFollowScroll } from './react/parts/useFollowScroll';
export { default as useRowHandoff } from './react/parts/handoff';
+export { useFilesHost, FilesHostProvider } from './react/files';
+export type { FilesHost } from './react/files';
diff --git a/packages/chat/src/react/files.tsx b/packages/chat/src/react/files.tsx
new file mode 100644
index 0000000000..e80a244da2
--- /dev/null
+++ b/packages/chat/src/react/files.tsx
@@ -0,0 +1,32 @@
+import { createContext, useContext } from 'react';
+import type { EModelEndpoint } from 'librechat-data-provider';
+import type { ReactNode } from 'react';
+
+/** App capabilities the attachment components read. */
+export interface FilesHost {
+ /** The provider mark drawn on a file a provider stores (OpenAI, Azure OpenAI). */
+ renderEndpointIcon: (endpoint: EModelEndpoint) => ReactNode;
+}
+
+/** Without a host, attachments still render; a provider-stored file just carries no mark. */
+const fallbackHost: FilesHost = {
+ renderEndpointIcon: () => null,
+};
+
+const FilesHostContext = createContext<FilesHost>(fallbackHost);
+
+/** Supplies the host the attachment components read from. */
+export function FilesHostProvider({
+ host,
+ children,
+}: {
+ host: FilesHost;
+ children: ReactNode;
+}): ReactNode {
+ return <FilesHostContext.Provider value={host}>{children}</FilesHostContext.Provider>;
+}
+
+/** The host of the nearest provider, or one that draws no provider marks. */
+export function useFilesHost(): FilesHost {
+ return useContext(FilesHostContext);
+}