🚚 feat: Route Attachments and Provision Tools Lazily (#15763)

This commit is contained in:
Danny Avila 2026-09-08 23:28:52 -04:00 • committed by GitHub
parent e6376f6df4
commit ec15075dc8
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
112 changed files with 12570 additions and 478 deletions

View file

@ -4,14 +4,15 @@ import {
supportsFiles,
mergeFileConfig,
isAgentsEndpoint,
resolveEndpointType,
isEphemeralAgentId,
isAssistantsEndpoint,
getEndpointFileConfig,
} from 'librechat-data-provider';
import type { TConversation } from 'librechat-data-provider';
import type { ExtendedFile, FileSetter } from '~/common';
import { useGetFileConfig, useGetEndpointsQuery, useGetAgentByIdQuery } from '~/data-provider';
import { useAgentsMapContext } from '~/Providers';
import useAgentUploadTarget from '~/hooks/Agents/useAgentUploadTarget';
import { useGetFileConfig } from '~/data-provider';
import { isUnifiedUploadMode } from '~/utils';
import AttachFileMenu from './AttachFileMenu';
import AttachFile from './AttachFile';
@ -33,48 +34,14 @@ function AttachFileChat({
const isAgents = useMemo(() => isAgentsEndpoint(endpoint), [endpoint]);
const isAssistants = useMemo(() => isAssistantsEndpoint(endpoint), [endpoint]);
const agentsMap = useAgentsMapContext();
const { agentProvider, endpointType, useResponsesApi } = useAgentUploadTarget(conversation);
const needsAgentFetch = useMemo(() => {
if (!isAgents || !conversation?.agent_id) {
return false;
}
const agent = agentsMap?.[conversation.agent_id];
return !agent?.model_parameters;
}, [isAgents, conversation?.agent_id, agentsMap]);
const { data: agentData } = useGetAgentByIdQuery(conversation?.agent_id, {
enabled: needsAgentFetch,
});
const useResponsesApi = useMemo(() => {
if (!isAgents || !conversation?.agent_id || conversation?.useResponsesApi !== undefined) {
return conversation?.useResponsesApi;
}
return (
agentData?.model_parameters?.useResponsesApi ??
agentsMap?.[conversation.agent_id]?.model_parameters?.useResponsesApi
);
}, [isAgents, conversation?.agent_id, conversation?.useResponsesApi, agentData, agentsMap]);
const { data: fileConfig = null } = useGetFileConfig({
/* Success, not merely settled: a failed or paused fetch leaves the built-in defaults in
* place, where the absent opt-out reads as unified. */
const { data: fileConfig = null, isSuccess: isFileConfigLoaded } = useGetFileConfig({
select: (data) => mergeFileConfig(data),
});
const { data: endpointsConfig } = useGetEndpointsQuery();
const agentProvider = useMemo(() => {
if (!isAgents || !conversation?.agent_id) {
return undefined;
}
return agentData?.provider ?? agentsMap?.[conversation.agent_id]?.provider;
}, [isAgents, conversation?.agent_id, agentData, agentsMap]);
const endpointType = useMemo(
() => resolveEndpointType(endpointsConfig, endpoint, agentProvider),
[endpointsConfig, endpoint, agentProvider],
);
const fileConfigEndpoint = useMemo(
() => (isAgents && agentProvider ? agentProvider : endpoint),
[isAgents, agentProvider, endpoint],
@ -96,6 +63,19 @@ function AttachFileChat({
() => (disableInputs || endpointFileConfig?.disabled) ?? false,
[disableInputs, endpointFileConfig?.disabled],
);
/* A saved agent's policy lives under its provider, so nothing is resolved for it until
* that provider is known; until then endpointFileConfig is the generic agents entry.
* An ephemeral agent has no record to fetch, so waiting on one never ends. */
const isSavedAgent =
isAgents && conversation?.agent_id != null && !isEphemeralAgentId(conversation.agent_id);
const isPolicyResolved = isFileConfigLoaded && (!isSavedAgent || agentProvider != null);
/* Resolved here rather than in the menu: an unresolved config reads as unified, which
* would show the wrong uploader on a legacy deployment. */
const isUnifiedMode = useMemo(
() => isUnifiedUploadMode(endpointFileConfig, isPolicyResolved),
[endpointFileConfig, isPolicyResolved],
);
if (isAssistants && endpointSupportsFiles && !isUploadDisabled) {
return (
@ -111,11 +91,15 @@ function AttachFileChat({
return (
<AttachFileMenu
endpoint={endpoint}
disabled={disableInputs}
/* Inert until the config resolves: the menu is an action, not just a display, and
* offering the chooser here submits an explicit destination a unified deployment
* would have inferred. The drag and paste paths hold for the same reason. */
disabled={disableInputs || !isPolicyResolved}
endpointType={endpointType}
conversationId={conversationId}
agentId={conversation?.agent_id}
endpointFileConfig={endpointFileConfig}
isUnifiedMode={isUnifiedMode}
useResponsesApi={useResponsesApi}
files={files}
setFiles={setFiles}

View file

@ -9,6 +9,7 @@ import {
TerminalSquareIcon,
} from 'lucide-react';
import {
IconButton,
FileUpload,
TooltipAnchor,
DropdownPopup,
@ -76,6 +77,8 @@ interface AttachFileMenuProps {
conversationId: string;
endpointType?: EModelEndpoint | string;
endpointFileConfig?: EndpointFileConfig;
/** Resolved by the parent, which knows whether the file config has landed. */
isUnifiedMode: boolean;
useResponsesApi?: boolean;
files: Map<string, ExtendedFile>;
setFiles: FileSetter;
@ -90,6 +93,7 @@ const AttachFileMenu = ({
endpointType,
conversationId,
endpointFileConfig,
isUnifiedMode,
useResponsesApi,
files,
setFiles,
@ -164,11 +168,38 @@ const AttachFileMenu = ({
inputRef.current.accept = '';
}
inputRef.current.click();
inputRef.current.accept = '';
},
[endpointFileConfig?.supportedMimeTypes],
);
/** Unified mode: single click triggers file upload with no tool_resource */
const handleUnifiedUpload = useCallback(() => {
toolResourceRef.current = undefined;
handleUploadClick();
}, [handleUploadClick]);
/** Unified mode removed the destination chooser, not the source chooser. SharePoint has
* no trigger of its own, so without this the picker becomes unreachable whenever the
* composer is in unified mode. Destination stays implicit on both sources. */
const unifiedSourceItems = useMemo<MenuItemProps[]>(
() => [
{
label: localize('com_files_upload_local_machine'),
onClick: handleUnifiedUpload,
icon: <FileImageIcon className="icon-md" />,
},
{
label: localize('com_files_upload_sharepoint'),
onClick: () => {
toolResourceRef.current = undefined;
setIsSharePointDialogOpen(true);
},
icon: <SharePointIcon className="icon-md" />,
},
],
[localize, handleUnifiedUpload, setIsSharePointDialogOpen],
);
const dropdownItems = useMemo(() => {
const setToolResource = (value: EToolResources | undefined) => {
toolResourceRef.current = value;
@ -330,6 +361,63 @@ const AttachFileMenu = ({
}
};
if (isUnifiedMode) {
return (
<>
<FileUpload
ref={inputRef}
handleFileChange={(e) => {
handleFileChange(e, toolResourceRef.current);
}}
>
{sharePointEnabled === true ? (
<DropdownPopup
menuId="attach-file-menu"
className="overflow-visible"
isOpen={isPopoverActive}
setIsOpen={setIsPopoverActive}
modal={false}
portal={true}
unmountOnHide={true}
trigger={menuTrigger}
items={unifiedSourceItems}
iconClassName="mr-0"
/>
) : (
<TooltipAnchor
render={
<IconButton
type="button"
size="theme"
shape="theme"
disabled={isUploadDisabled}
id="attach-file-button"
label={localize('com_sidepanel_attach_files')}
onClick={handleUnifiedUpload}
aria-keyshortcuts={uploadFileAriaKey}
className="p-1 hover:bg-surface-composer-hover"
>
<AttachmentIcon />
</IconButton>
}
id="attach-file-button"
description={uploadFileTooltip}
disabled={isUploadDisabled}
/>
)}
</FileUpload>
<SharePointPickerDialog
isOpen={isSharePointDialogOpen}
onOpenChange={setIsSharePointDialogOpen}
onFilesSelected={handleSharePointFilesSelected}
isDownloading={isProcessing}
downloadProgress={downloadProgress}
maxSelectionCount={endpointFileConfig?.fileLimit}
/>
</>
);
}
return (
<>
<FileUpload

View file

@ -25,11 +25,13 @@ let mockFileConfig = defaultFileConfig;
let mockAgentsMap: Record<string, Partial<Agent>> = {};
let mockAgentQueryData: Partial<Agent> | undefined;
let mockFileConfigLoaded = true;
jest.mock('~/data-provider', () => ({
useGetEndpointsQuery: () => ({ data: mockEndpointsConfig }),
useGetFileConfig: ({ select }: { select?: (data: unknown) => unknown }) => ({
data: select != null ? select(mockFileConfig) : mockFileConfig,
isSuccess: mockFileConfigLoaded,
}),
useGetAgentByIdQuery: () => ({ data: mockAgentQueryData }),
}));
@ -38,6 +40,12 @@ jest.mock('~/Providers', () => ({
useAgentsMapContext: () => mockAgentsMap,
}));
/* The shared upload-target hook reads the module directly rather than the barrel, so
* the barrel mock alone leaves it with no agents map. */
jest.mock('~/Providers/AgentsMapContext', () => ({
useAgentsMapContext: () => mockAgentsMap,
}));
/** Capture the props passed to AttachFileMenu */
let mockAttachFileMenuProps: Record<string, unknown> = {};
jest.mock('../AttachFileMenu', () => {
@ -77,6 +85,7 @@ describe('AttachFileChat', () => {
mockAgentsMap = {};
mockAgentQueryData = undefined;
mockAttachFileMenuProps = {};
mockFileConfigLoaded = true;
});
describe('rendering decisions', () => {
@ -161,7 +170,9 @@ describe('AttachFileChat', () => {
expect(mockAttachFileMenuProps.useResponsesApi).toBe(true);
});
it('preserves an explicit conversation useResponsesApi false override', () => {
it('lets the saved agent decide over the conversation', () => {
/* Execution reads the agent's own model parameters, so the attach menu must offer
* what the turn will actually do rather than what the conversation says. */
mockAgentQueryData = {
provider: EModelEndpoint.azureOpenAI,
model_parameters: { useResponsesApi: true },
@ -171,7 +182,20 @@ describe('AttachFileChat', () => {
agent_id: 'agent-1',
useResponsesApi: false,
});
expect(mockAttachFileMenuProps.useResponsesApi).toBe(false);
expect(mockAttachFileMenuProps.useResponsesApi).toBe(true);
});
it('keeps the conversation setting when the agent states none', () => {
mockAgentQueryData = {
provider: EModelEndpoint.azureOpenAI,
model_parameters: {},
} as Partial<Agent>;
renderComponent({
endpoint: EModelEndpoint.agents,
agent_id: 'agent-1',
useResponsesApi: true,
});
expect(mockAttachFileMenuProps.useResponsesApi).toBe(true);
});
});
@ -282,3 +306,64 @@ describe('AttachFileChat', () => {
});
});
});
describe('AttachFileChat upload config gating', () => {
beforeEach(() => {
mockFileConfig = defaultFileConfig;
mockAgentsMap = {};
mockAgentQueryData = undefined;
mockAttachFileMenuProps = {};
});
it('leaves the attach menu inert until the file config resolves', () => {
/* The menu is an action, not just a display: offering the chooser here submits an
* explicit destination a unified deployment would have inferred, and after a failed
* fetch it would keep offering it. */
mockFileConfigLoaded = false;
renderComponent({ endpoint: EModelEndpoint.agents });
expect(mockAttachFileMenuProps.disabled).toBe(true);
});
it('enables it once the config lands', () => {
mockFileConfigLoaded = true;
renderComponent({ endpoint: EModelEndpoint.agents });
expect(mockAttachFileMenuProps.disabled).toBe(false);
});
it('keeps it inert while a saved agent provider is still being fetched', () => {
/* The config can succeed before the agent does, and until then endpointFileConfig is
* the generic agents entry rather than the provider's. */
mockFileConfigLoaded = true;
mockAgentsMap = {};
mockAgentQueryData = undefined;
renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'agent_saved01' });
expect(mockAttachFileMenuProps.disabled).toBe(true);
});
it('does not wait on a provider an ephemeral agent will never have', () => {
/* There is no record to fetch for one, so gating on its provider never lifts and the
* attach control stays disabled for the whole conversation. */
mockFileConfigLoaded = true;
mockAgentsMap = {};
mockAgentQueryData = undefined;
renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'ephemeral-convo-1' });
expect(mockAttachFileMenuProps.disabled).toBe(false);
});
it('enables it once that provider resolves', () => {
mockFileConfigLoaded = true;
mockAgentQueryData = { provider: 'openAI' } as Partial<Agent>;
renderComponent({ endpoint: EModelEndpoint.agents, agent_id: 'agent_saved01' });
expect(mockAttachFileMenuProps.disabled).toBe(false);
});
});

View file

@ -46,6 +46,12 @@ jest.mock('@librechat/client', () => {
),
),
TooltipAnchor: (props) => props.render,
/* Mirrors the real primitive closely enough for these assertions: it applies
* `label` as the accessible name, which is how the trigger is queried. */
IconButton: R.forwardRef((props, ref) => {
const { label, size: _size, shape: _shape, variant: _variant, children, ...rest } = props;
return R.createElement('button', { ref, 'aria-label': label, ...rest }, children);
}),
DropdownPopup: (props) =>
R.createElement(
'div',
@ -99,6 +105,7 @@ const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false
function setupMocks(overrides: { provider?: string } = {}) {
const translations: Record<string, string> = {
com_files_upload_local_machine: 'From Local Computer',
com_files_upload_sharepoint: 'Upload from SharePoint',
com_sidepanel_attach_files: 'Attach Files',
com_ui_upload_code_environment: 'Upload to Code Environment',
@ -141,6 +148,7 @@ function renderMenu(props: Record<string, unknown> = {}) {
setFiles={() => {}}
setFilesLoading={() => {}}
conversation={null}
isUnifiedMode={false}
{...props}
/>
</RecoilRoot>
@ -155,6 +163,51 @@ function openMenu() {
describe('AttachFileMenu', () => {
beforeEach(jest.clearAllMocks);
describe('unified mode upload sources', () => {
it('uses a single upload button when SharePoint is disabled', () => {
setupMocks();
renderMenu({ isUnifiedMode: true });
expect(screen.getByRole('button', { name: /attach files/i })).toBeInTheDocument();
expect(
screen.queryByRole('button', { name: /attach file options/i }),
).not.toBeInTheDocument();
});
it('offers SharePoint alongside local upload when SharePoint is enabled', () => {
setupMocks();
mockUseGetStartupConfig.mockReturnValue({ data: { sharePointFilePickerEnabled: true } });
renderMenu({ isUnifiedMode: true });
openMenu();
expect(screen.getByText('From Local Computer')).toBeInTheDocument();
expect(screen.getByText('Upload from SharePoint')).toBeInTheDocument();
});
it('does not offer a destination choice on either source', () => {
setupMocks();
mockUseAgentCapabilities.mockReturnValue({
contextEnabled: true,
fileSearchEnabled: true,
codeEnabled: true,
});
mockUseAgentToolPermissions.mockReturnValue({
fileSearchAllowedByAgent: true,
codeAllowedByAgent: true,
provider: undefined,
});
mockUseGetStartupConfig.mockReturnValue({ data: { sharePointFilePickerEnabled: true } });
renderMenu({ isUnifiedMode: true });
openMenu();
expect(screen.queryByText('Upload to Code Environment')).not.toBeInTheDocument();
expect(screen.queryByText('Upload for File Search')).not.toBeInTheDocument();
expect(screen.queryByText('Upload as Text')).not.toBeInTheDocument();
});
});
describe('Upload to Provider vs Upload Image', () => {
it('shows "Upload to Provider" when endpointType is custom (resolved from agent provider)', () => {
setupMocks({ provider: 'Moonshot' });
@ -273,6 +326,15 @@ describe('AttachFileMenu', () => {
expect(screen.getByTestId('dropdown-popup')).toHaveAttribute('data-modal', 'false');
expect(screen.getByTestId('dropdown-popup')).toHaveAttribute('data-portal', 'true');
});
it('renders the unified upload button when legacyFileUploadUX is not true', () => {
setupMocks();
renderMenu({ isUnifiedMode: true });
expect(screen.getByRole('button', { name: /attach files/i })).toBeInTheDocument();
expect(
screen.queryByRole('button', { name: /attach file options/i }),
).not.toBeInTheDocument();
});
});
describe('Agent Capabilities', () => {

View file

@ -167,7 +167,7 @@ const ToolsDropdown = ({ disabled }: ToolsDropdownProps) => {
onClick: handleFileSearchToggle,
hideOnClick: false,
render: (props) => (
<div {...props}>
<div {...props} data-testid="tools-menu-file-search">
<div className="flex items-center gap-2">
<VectorIcon className="icon-md" />
<span>{localize('com_assistants_file_search')}</span>
@ -317,7 +317,7 @@ const ToolsDropdown = ({ disabled }: ToolsDropdownProps) => {
onClick: handleCodeInterpreterToggle,
hideOnClick: false,
render: (props) => (
<div {...props}>
<div {...props} data-testid="tools-menu-run-code">
<div className="flex items-center gap-2">
<TerminalSquareIcon className="icon-md" aria-hidden="true" />
<span>{localize('com_ui_run_code')}</span>

View file

@ -124,7 +124,12 @@ function renderComposer({
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
});
queryClient.setQueryData([QueryKeys.fileConfig], {});
/* These interaction tests exercise the destination menu. Unified-mode control
* behavior has its own focused coverage, so opt this harness into the legacy menu
* instead of depending on the product default. */
queryClient.setQueryData([QueryKeys.fileConfig], {
endpoints: { default: { legacyFileUploadUX: true } },
});
queryClient.setQueryData<TFile[]>([QueryKeys.files], []);
queryClient.setQueryData([QueryKeys.endpoints], { [EModelEndpoint.openAI]: { order: 0 } });

View file

@ -115,11 +115,14 @@ function Harness() {
);
}
function renderComposer() {
function renderComposer({ legacyUploadUX = false }: { legacyUploadUX?: boolean } = {}) {
const queryClient = new QueryClient({
defaultOptions: { queries: { retry: false }, mutations: { retry: false } },
});
queryClient.setQueryData([QueryKeys.fileConfig], {});
queryClient.setQueryData(
[QueryKeys.fileConfig],
legacyUploadUX ? { legacyFileUploadUX: true } : {},
);
queryClient.setQueryData<TFile[]>([QueryKeys.files], []);
queryClient.setQueryData([QueryKeys.endpoints], { [EModelEndpoint.openAI]: { order: 0 } });
@ -157,6 +160,10 @@ const pasteImage = (textarea: HTMLElement) => {
* trigger to return focus to when it closes and used to leave focus on
* `document.body` — which reads to the user as "the send button is enabled but
* Enter does nothing", since Enter-to-send is a textarea key handler.
*
* The dialog only exists on a `legacyFileUploadUX` endpoint. Unified upload routes
* a pasted file straight to its destination, so these render in legacy mode and the
* unified path is covered separately below.
*/
describe('composer focus after a pasted upload', () => {
beforeEach(() => {
@ -172,7 +179,7 @@ describe('composer focus after a pasted upload', () => {
});
test('returns focus to the composer when the upload dialog closes', async () => {
renderComposer();
renderComposer({ legacyUploadUX: true });
const textarea = await screen.findByTestId('text-input');
await userEvent.click(textarea);
@ -189,7 +196,7 @@ describe('composer focus after a pasted upload', () => {
}, 20000);
test('Enter still sends after a pasted upload, with no further typing', async () => {
renderComposer();
renderComposer({ legacyUploadUX: true });
const textarea = await screen.findByTestId('text-input');
await userEvent.click(textarea);
@ -210,3 +217,56 @@ describe('composer focus after a pasted upload', () => {
expect(mockAsk.mock.calls[0][0]).toEqual(expect.objectContaining({ text: 'hi' }));
}, 20000);
});
/**
* Unified upload routes a pasted file to its destination without raising the chooser,
* so the dialog that used to steal focus never opens. The user-facing contract is the
* same either way: the composer keeps focus and Enter still sends.
*/
describe('composer focus after a pasted upload in unified mode', () => {
beforeEach(() => {
localStorage.clear();
global.URL.createObjectURL = jest.fn(() => 'blob:preview');
global.URL.revokeObjectURL = jest.fn();
(global as unknown as { Image: unknown }).Image = StubImage;
mockUpload.mockReset();
mockAsk.mockReset();
mockUpload.mockImplementation((body: FormData) =>
Promise.resolve({ ...uploadResponse, temp_file_id: body.get('file_id') as string }),
);
});
test('uploads without a destination dialog and leaves focus in the composer', async () => {
renderComposer();
const textarea = await screen.findByTestId('text-input');
await userEvent.click(textarea);
await userEvent.type(textarea, 'hi');
expect(textarea).toHaveFocus();
pasteImage(textarea);
await waitFor(() => expect(mockUpload).toHaveBeenCalled());
expect(screen.queryAllByRole('button', { name: /upload/i })).toHaveLength(0);
expect(textarea).toHaveFocus();
}, 20000);
test('Enter still sends after a pasted upload, with no further typing', async () => {
renderComposer();
const textarea = await screen.findByTestId('text-input');
await userEvent.click(textarea);
await userEvent.type(textarea, 'hi');
pasteImage(textarea);
await waitFor(() => expect(mockUpload).toHaveBeenCalled());
await waitFor(() => expect(screen.getByTestId('send-button')).toBeEnabled());
/** Straight to the keyboard, as above: any click or keystroke first would restore
* focus on its own and hide a regression. */
fireEvent.keyDown(document.activeElement as Element, { key: 'Enter', code: 'Enter' });
await waitFor(() => expect(mockAsk).toHaveBeenCalled());
expect(mockAsk.mock.calls[0][0]).toEqual(expect.objectContaining({ text: 'hi' }));
}, 20000);
});