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

* refactor: Move Composer Attachment Components Into @librechat/chat

* test: Cover the Pasted Text Editor From Paste to Saved Edit

* test: Keep the Real Data Provider Enums in the ChatView Subagent Spec

* refactor: Build the Source Badge Styles at Render Time

* test: Reopen the Pasted Text Correction From Its Replacement Chip

* chore: Re-record the Attachment Design Suppressions on Dev

* test: Merge the SteerPart Package Mocks Into One Factory
This commit is contained in:
Marco Beretta 2026-10-29 20:38:24 +01:00 • committed by GitHub
parent 7f597b4787
commit 59557a46eb
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
51 changed files with 500 additions and 281 deletions

View file

@ -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",

View file

@ -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 />

View file

@ -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';

View file

@ -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';

View file

@ -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';

View file

@ -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';

View file

@ -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'),
),
];

View file

@ -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';

View file

@ -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

View file

@ -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',

View file

@ -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;

View file

@ -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');

View file

@ -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';

View file

@ -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';

View file

@ -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';

View file

@ -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';

View file

@ -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', () => ({

View file

@ -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', () => ({

View file

@ -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: ({

View file

@ -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' }),

View file

@ -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',
() =>

View file

@ -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,
}));

View file

@ -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';

View file

@ -1,4 +1,4 @@
import ProgressCircle from '~/components/Chat/Input/Files/ProgressCircle';
import { ProgressCircle } from '@librechat/chat/components';
export function NoImage() {
return (

View file

@ -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;

View file

@ -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.

View file

@ -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

View file

@ -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();
});
});

View file

@ -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

2
package-lock.json generated
View file

@ -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": "*",

View file

@ -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",

View file

@ -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';

View file

@ -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 (
<>

View file

@ -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;

View file

@ -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">

View file

@ -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;

View file

@ -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

View file

@ -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);

View file

@ -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('');

View file

@ -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">

View file

@ -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

View file

@ -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>
);
}

View file

@ -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', () => ({

View file

@ -1,3 +1,6 @@
/**
* @jest-environment jsdom
*/
import React from 'react';
import '@testing-library/jest-dom';
import { render, screen, fireEvent } from '@testing-library/react';

View file

@ -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,
}));

View file

@ -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();
});
});

View file

@ -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();
});
});

View file

@ -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);
});
});

View file

@ -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;
};

View file

@ -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';

View file

@ -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);
}