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

🪏 fix: Restore Explicit File Search Uploads (#17226)

lia-by-librechat[bot]1871d3140151
diff --git a/api/server/services/Files/process.spec.js b/api/server/services/Files/process.spec.js
index cd685fab1a..1454ac5dbb 100644
--- a/api/server/services/Files/process.spec.js
+++ b/api/server/services/Files/process.spec.js
@@ -1847,7 +1847,68 @@ describe('processAgentFileUpload', () => {
});
});
- describe('explicit legacy tool delivery path', () => {
+ describe('explicit tool delivery path', () => {
+ test.each([undefined, 'agent_saved01'])(
+ 'embeds a unified chat upload only when File Search was chosen (agent=%s)',
+ async (agent_id) => {
+ const storageUpload = setupStoredFileUpload({ embedded: false });
+ mergeFileConfig.mockReturnValue({
+ ...makeFileConfig(),
+ endpoints: { openAI: { legacyFileUploadUX: false } },
+ });
+ const req = makeReq({ body: { endpoint: EModelEndpoint.openAI } });
+ const metadata = {
+ endpoint: EModelEndpoint.openAI,
+ effectiveEndpoint: EModelEndpoint.openAI,
+ agent_id,
+ agentTools: [EToolResources.file_search],
+ message_file: 'true',
+ file_id: 'f-explicit-search',
+ tool_resource: EToolResources.file_search,
+ };
+
+ await processAgentFileUpload({ req, res: mockRes, metadata });
+
+ expect(uploadVectors).toHaveBeenCalledTimes(1);
+ expect(uploadVectors).toHaveBeenCalledWith({
+ req,
+ file: req.file,
+ file_id: metadata.file_id,
+ entity_id: undefined,
+ });
+ expect(storageUpload).toHaveBeenCalledTimes(1);
+ expect(db.createFile).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ file_id: metadata.file_id,
+ embedded: true,
+ llmDeliveryPath: 'none',
+ metadata: expect.objectContaining({ destinationChosen: true }),
+ }),
+ true,
+ );
+ expect(db.addAgentResourceFile).not.toHaveBeenCalled();
+ expect(mockRes.status).toHaveBeenCalledWith(200);
+
+ jest.clearAllMocks();
+ await processAgentFileUpload({
+ req,
+ res: mockRes,
+ metadata: { ...metadata, file_id: 'f-normal-upload', tool_resource: undefined },
+ });
+
+ expect(uploadVectors).not.toHaveBeenCalled();
+ expect(db.createFile).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ file_id: 'f-normal-upload',
+ embedded: false,
+ llmDeliveryPath: 'provider',
+ metadata: expect.objectContaining({ destinationChosen: false }),
+ }),
+ true,
+ );
+ },
+ );
+
test('persists llmDeliveryPath none for explicit file_search uploads', async () => {
const { createFile } = require('~/models');
const storageUpload = jest.fn().mockResolvedValue({
diff --git a/client/src/Providers/__tests__/BadgeRowContext.spec.tsx b/client/src/Providers/__tests__/BadgeRowContext.spec.tsx
index 9d0cf5e3fa..696201ab98 100644
--- a/client/src/Providers/__tests__/BadgeRowContext.spec.tsx
+++ b/client/src/Providers/__tests__/BadgeRowContext.spec.tsx
@@ -1,8 +1,17 @@
-import React from 'react';
+import React, { useState } from 'react';
import { RecoilRoot } from 'recoil';
-import { render } from '@testing-library/react';
+import { useForm } from 'react-hook-form';
+import { render, act } from '@testing-library/react';
+import { LocalStorageKeys } from 'librechat-data-provider';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import type { ExtendedFile, ChatFormValues } from '~/common';
+import { getFilesDraft, getComposerDraftId, getAskAnswerDraftId } from '~/utils/drafts';
+import { beginFileSearchUpload, completeFileSearchUpload } from '~/hooks/Files/search';
+import { getFileSearchChoice, clearFileSearchChoices } from '~/utils/choices';
import BadgeRowProvider, { useBadgeRowContext } from '../BadgeRowContext';
+import { ChatFormProvider } from '~/Providers/ChatFormContext';
+import { useAutoSave } from '~/hooks/Input/useAutoSave';
+import { ephemeralAgentByConvoId } from '~/store';
/**
* `BadgeRowProvider` is an inline child of `ChatForm`, which re-renders on every
@@ -28,6 +37,7 @@ jest.mock('@librechat/client', () => ({
would look unstable for a reason that does not exist outside the tests. */
const mockTranslate = (key: string) => key;
const mockToolAuth = { authenticated: false };
+let mockCachedFiles: object[] = [];
jest.mock('react-i18next', () => ({
...jest.requireActual('react-i18next'),
useTranslation: () => ({ t: mockTranslate, i18n: { changeLanguage: jest.fn() } }),
@@ -42,9 +52,12 @@ jest.mock('~/data-provider', () => ({
useGetStartupConfig: () => ({ data: undefined }),
useMCPServersQuery: () => ({ data: undefined, isLoading: false }),
useVerifyAgentToolAuth: () => ({ data: mockToolAuth }),
+ useGetFiles: () => ({ data: mockCachedFiles }),
}));
-function renderProvider() {
+type DraftScope = { index?: number; isSubmitting?: boolean; draftId?: string };
+
+function renderProvider(initialId = 'convo-badge-row', restoreDraft = false, initiallyOff = false) {
const client = new QueryClient({
defaultOptions: { queries: { retry: false, cacheTime: 0 } },
});
@@ -53,25 +66,218 @@ function renderProvider() {
value = useBadgeRowContext();
return null;
};
- const Tree = ({ marker }: { marker: number }) => (
+ let scope: DraftScope = {};
+ let stage: (file: ExtendedFile) => void = () => undefined;
+ let restoredFiles = new Map<string, ExtendedFile>();
+ function DraftOwner({ id }: { id: string }) {
+ const [files, setFiles] = useState(new Map<string, ExtendedFile>());
+ stage = (file) => setFiles(new Map([[file.file_id, file]]));
+ restoredFiles = files;
+ useAutoSave({ conversationId: id, files, setFiles, ...scope });
+ return null;
+ }
+ function Form({ id }: { id: string }) {
+ const methods = useForm<ChatFormValues>({ defaultValues: { text: '' } });
+ return (
+ <ChatFormProvider {...methods}>
+ <DraftOwner id={id} />
+ </ChatFormProvider>
+ );
+ }
+ const Tree = ({ marker, id }: { marker: number; id: string }) => (
<QueryClientProvider client={client}>
- <RecoilRoot>
- <BadgeRowProvider conversationId="convo-badge-row">
+ <RecoilRoot
+ initializeState={({ set }) => {
+ if (initiallyOff) set(ephemeralAgentByConvoId(initialId), { file_search: false });
+ }}
+ >
+ <BadgeRowProvider conversationId={id}>
{/* Re-rendered along with the provider, the way `Bar` is. */}
<span>{marker}</span>
<Consumer />
+ {restoreDraft && <Form id={id} />}
</BadgeRowProvider>
</RecoilRoot>
</QueryClientProvider>
);
- const { rerender } = render(<Tree marker={0} />);
+ let id = initialId;
+ const { rerender, unmount } = render(<Tree marker={0} id={id} />);
return {
getValue: () => value,
- retype: (marker: number) => rerender(<Tree marker={marker} />),
+ unmount,
+ retype: (marker: number) => rerender(<Tree marker={marker} id={id} />),
+ navigate: (next: string, nextScope: DraftScope = {}) => {
+ id = next;
+ scope = nextScope;
+ rerender(<Tree marker={0} id={id} />);
+ },
+ stage: (file: ExtendedFile) => stage(file),
+ files: () => restoredFiles,
};
}
+describe('File Search deferred upload effects', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ clearFileSearchChoices();
+ mockCachedFiles = [];
+ });
+
+ const file = (): ExtendedFile => ({
+ file_id: 'pending-search',
+ type: 'text/plain',
+ progress: 0.2,
+ size: 5,
+ tool_resource: 'file_search',
+ });
+ const persisted = {
+ file_id: 'server-search',
+ temp_file_id: 'pending-search',
+ filename: 'search.txt',
+ filepath: '/files/search.txt',
+ type: 'text/plain',
+ bytes: 5,
+ embedded: true,
+ llmDeliveryPath: 'none',
+ };
+
+ it.each([
+ ['passive', true, false],
+ ['disable', false, true],
+ ['disable-then-enable', true, true],
+ ] as const)(
+ 'preserves explicit ordering through real navigation effects (%s)',
+ async (action, enabled, sameMs) => {
+ const clock = jest.spyOn(Date, 'now').mockReturnValue(1000);
+ const view = renderProvider('origin', true, true);
+ act(() => view.stage(file()));
+ const toggle = view.getValue()?.fileSearch;
+ if (!toggle) throw new Error('Missing real File Search toggle');
+ const intent = beginFileSearchUpload('pending-search', 'origin');
+ let resolveMutation: () => void = () => undefined;
+ let activated = false;
+ const mutation = new Promise<void>((resolve) => {
+ resolveMutation = resolve;
+ });
+ const completion = mutation.then(() => {
+ activated = completeFileSearchUpload(
+ 'pending-search',
+ 'origin',
+ intent.persisted ? undefined : intent.choiceRevision,
+ );
+ if (activated) toggle.setEphemeralAgent((previous) => ({ ...previous, file_search: true }));
+ });
+ if (!sameMs) clock.mockReturnValue(2000);
+ act(() => view.navigate('new'));
+ if (!sameMs) clock.mockReturnValue(3000);
+ act(() => view.navigate('origin'));
+ expect(localStorage.getItem(`${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}origin`)).toBe(
+ 'false',
+ );
+ expect(getFileSearchChoice('origin')).toBeNull();
+ if (action !== 'passive')
+ act(() => view.getValue()?.fileSearch.handleChange({ value: false }));
+ if (action === 'disable-then-enable')
+ act(() => view.getValue()?.fileSearch.handleChange({ value: true }));
+ await act(async () => {
+ resolveMutation();
+ await completion;
+ });
+ expect(activated).toBe(enabled);
+ expect(view.getValue()?.fileSearch.isToolEnabled).toBe(enabled);
+ mockCachedFiles = [persisted];
+ act(() => view.retype(1));
+ expect(view.files().get('pending-search')?.file_id).toBe('server-search');
+ act(() => view.navigate('new'));
+ act(() => view.navigate('origin'));
+ expect(view.getValue()?.fileSearch.isToolEnabled).toBe(enabled);
+ view.unmount();
+ const reloaded = renderProvider('origin', true);
+ expect(reloaded.getValue()?.fileSearch.isToolEnabled).toBe(enabled);
+ reloaded.unmount();
+ clock.mockRestore();
+ },
+ );
+
+ it.each<{ owner: string; scope: DraftScope }>([
+ { owner: 'origin', scope: {} },
+ { owner: 'origin', scope: { isSubmitting: true } },
+ { owner: 'new', scope: { index: 1 } },
+ { owner: 'origin', scope: { draftId: getAskAnswerDraftId('question') } },
+ ])('keeps draft ownership across repeated navigation (%j)', ({ owner, scope }) => {
+ const view = renderProvider(owner, true, true);
+ act(() => view.navigate(owner, scope));
+ const draftId =
+ scope.draftId ?? getComposerDraftId(scope.index ?? 0, owner, scope.isSubmitting ?? false);
+ act(() => view.stage(file()));
+ beginFileSearchUpload('pending-search', owner);
+ for (let visit = 0; visit < 3; visit++) {
+ act(() => view.navigate('away'));
+ expect(getFilesDraft(draftId).fileIds).toContain('pending-search');
+ expect(getFilesDraft('away').fileIds).not.toContain('pending-search');
+ act(() => view.navigate(owner, scope));
+ expect(getFilesDraft(draftId).fileIds).toContain('pending-search');
+ }
+ mockCachedFiles = [persisted];
+ act(() => view.retype(1));
+ expect(view.files().get('pending-search')?.file_id).toBe('server-search');
+ expect(view.getValue()?.fileSearch.isToolEnabled).toBe(true);
+ view.unmount();
+ });
+
+ it('honors an explicit disable when intent storage is unavailable', () => {
+ const view = renderProvider('origin', false, true);
+ const write = Storage.prototype.setItem;
+ const unavailable = jest.spyOn(Storage.prototype, 'setItem').mockImplementation(function (
+ this: Storage,
+ key: string,
+ value: string,
+ ) {
+ if (key.startsWith('file-search-upload:') || key.startsWith('file-search-choice:')) {
+ throw new Error('Storage unavailable');
+ }
+ write.call(this, key, value);
+ });
+ const intent = beginFileSearchUpload('pending-search', 'origin');
+ expect(intent.persisted).toBe(false);
+ act(() => view.getValue()?.fileSearch.handleChange({ value: false }));
+ expect(completeFileSearchUpload('pending-search', 'origin', intent.choiceRevision)).toBe(false);
+ unavailable.mockRestore();
+ view.unmount();
+ });
+
+ it('restores a pending explicit intent after reload without a surviving mutation callback', () => {
+ const clock = jest.spyOn(Date, 'now').mockReturnValue(1000);
+ const first = renderProvider('origin', true, true);
+ act(() => first.stage(file()));
+ beginFileSearchUpload('pending-search', 'origin');
+ act(() => first.navigate('new'));
+ first.unmount();
+ clock.mockReturnValue(2000);
+ mockCachedFiles = [persisted];
+ const reloaded = renderProvider('origin', true);
+ expect(reloaded.files().get('pending-search')?.file_id).toBe('server-search');
+ expect(reloaded.getValue()?.fileSearch.isToolEnabled).toBe(true);
+ reloaded.unmount();
+ clock.mockRestore();
+ });
+});
+
describe('BadgeRowProvider', () => {
+ it('recovers completed explicit uploads on reload without overriding a later disable', () => {
+ localStorage.clear();
+ beginFileSearchUpload('upload-id', 'convo-badge-row');
+ expect(completeFileSearchUpload('upload-id', 'convo-badge-row')).toBe(true);
+ const first = renderProvider();
+ expect(first.getValue()?.fileSearch.isToolEnabled).toBe(true);
+ act(() => first.getValue()?.fileSearch.setToggleState(false));
+ first.unmount();
+ const reloaded = renderProvider();
+ expect(reloaded.getValue()?.fileSearch.isToolEnabled).toBe(false);
+ reloaded.unmount();
+ localStorage.clear();
+ });
+
it('hands consumers the same value across a parent re-render', () => {
const { getValue, retype } = renderProvider();
const first = getValue();
diff --git a/client/src/components/Chat/Input/Composer/Palette.tsx b/client/src/components/Chat/Input/Composer/Palette.tsx
index b0964b7614..ed6bbac80d 100644
--- a/client/src/components/Chat/Input/Composer/Palette.tsx
+++ b/client/src/components/Chat/Input/Composer/Palette.tsx
@@ -411,6 +411,7 @@ function Palette({
);
const isUnifiedMode = isUnifiedUploadMode(endpointFileConfig, canAttach);
const attach = useAttachItems({
+ index,
agentId,
endpoint,
endpointType,
diff --git a/client/src/components/Chat/Input/Composer/Tray.tsx b/client/src/components/Chat/Input/Composer/Tray.tsx
index caa16c7511..c39ba79184 100644
--- a/client/src/components/Chat/Input/Composer/Tray.tsx
+++ b/client/src/components/Chat/Input/Composer/Tray.tsx
@@ -114,6 +114,7 @@ function Tray({
[items, focusComposer],
);
const { abortUpload } = useFileHandlingNoChatContext(undefined, {
+ index,
files,
setFiles,
setFilesLoading,
diff --git a/client/src/components/Chat/__tests__/ProjectLandingChip.ownership.spec.tsx b/client/src/components/Chat/__tests__/ProjectLandingChip.ownership.spec.tsx
new file mode 100644
index 0000000000..e72c651386
--- /dev/null
+++ b/client/src/components/Chat/__tests__/ProjectLandingChip.ownership.spec.tsx
@@ -0,0 +1,153 @@
+import React, { useState } from 'react';
+import { BrowserRouter, useLocation } from 'react-router-dom';
+import { act, fireEvent, render, screen } from '@testing-library/react';
+import type { TConversation } from 'librechat-data-provider';
+import type { ExtendedFile } from '~/common';
+import {
+ captureComposerDraft,
+ bindComposerLaunch,
+ adoptComposerConversation,
+} from '~/utils/drafts';
+import { useAutoSave } from '~/hooks/Input/useAutoSave';
+import ProjectLandingChip from '../ProjectLandingChip';
+
+const mockChatContext = React.createContext<{
+ conversation: TConversation;
+ setConversation: React.Dispatch<React.SetStateAction<TConversation>>;
+} | null>(null);
+const mockSetValue = jest.fn();
+const mockProjects = [
+ { _id: 'project-a', name: 'Project A' },
+ { _id: 'project-b', name: 'Project B' },
+];
+
+jest.mock('recoil', () => ({
+ ...jest.requireActual('recoil'),
+ useSetRecoilState: () => jest.fn(),
+}));
+jest.mock('~/store', () => ({ ephemeralAgentByConvoId: (id: string) => id }));
+jest.mock('~/Providers', () => ({
+ useChatContext: () => jest.requireActual('react').useContext(mockChatContext),
+ useChatFormContext: () => ({ setValue: mockSetValue }),
+}));
+jest.mock('~/hooks/Files/useFileHandling', () => ({ hasInFlightUpload: () => false }));
+jest.mock('~/utils', () => jest.requireActual('~/utils/drafts'));
+jest.mock('~/Providers/ChatSettingsContext', () => ({
+ useChatSettings: () => ({ saveDrafts: false }),
+}));
+jest.mock('~/data-provider', () => ({
+ useGetFiles: () => ({ data: [] }),
+ useProjectsInfiniteQuery: () => ({ data: { pages: [{ projects: mockProjects }] } }),
+}));
+jest.mock('~/hooks', () => ({ useLocalize: () => (key: string) => key }));
+jest.mock('@librechat/client', () => {
+ const React = jest.requireActual<typeof import('react')>('react');
+ return {
+ ControlCombobox: ({
+ selectedValue,
+ setValue,
+ ariaLabel,
+ items,
+ }: {
+ selectedValue: string;
+ setValue: (value: string) => void;
+ ariaLabel: string;
+ items: Array<{ value: string; label: string }>;
+ }) =>
+ React.createElement(
+ 'select',
+ {
+ 'aria-label': ariaLabel,
+ value: selectedValue,
+ onChange: (event: React.ChangeEvent<HTMLSelectElement>) => setValue(event.target.value),
+ },
+ items.map((item) =>
+ React.createElement('option', { key: item.value, value: item.value }, item.label),
+ ),
+ ),
+ TooltipAnchor: ({ render: control }: { render: React.ReactNode }) => control,
+ };
+});
+
+function mountProjectComposer() {
+ const api: { setSubmitting: (value: boolean) => void } = { setSubmitting: () => undefined };
+ function Harness() {
+ const location = useLocation();
+ const [conversation, setConversation] = useState<TConversation>({
+ conversationId: 'new',
+ chatProjectId: 'project-a',
+ title: 'New Chat',
+ } as TConversation);
+ const [isSubmitting, setSubmitting] = useState(false);
+ const [files, setFiles] = useState<Map<string, ExtendedFile>>(new Map());
+ api.setSubmitting = setSubmitting;
+ useAutoSave({ index: 3, conversationId: 'new', isSubmitting, files, setFiles });
+ const project = mockProjects.find(({ _id }) => _id === conversation.chatProjectId);
+ return (
+ <mockChatContext.Provider value={{ conversation, setConversation }}>
+ <output aria-label="Current route">{location.pathname + location.search}</output>
+ {project && (
+ <ProjectLandingChip
+ project={project as Parameters<typeof ProjectLandingChip>[0]['project']}
+ />
+ )}
+ </mockChatContext.Provider>
+ );
+ }
+ return {
+ ...render(
+ <BrowserRouter>
+ <Harness />
+ </BrowserRouter>,
+ ),
+ api,
+ };
+}
+
+beforeEach(() => {
+ localStorage.clear();
+ window.history.replaceState({}, '', '/c/new?projectId=project-a');
+});
+
+afterEach(() => window.history.replaceState({}, '', '/'));
+
+it.each(['remove', 'replace'])(
+ 'starts a fresh scope after the project chip changes the route (%s)',
+ (action) => {
+ const view = mountProjectComposer();
+ const previous = captureComposerDraft(3, 'new');
+ const previousLaunch = { conversationId: 'new' };
+ bindComposerLaunch(previousLaunch, 3);
+ if (action === 'remove') {
+ fireEvent.click(screen.getByRole('button', { name: 'com_ui_remove_from_project' }));
+ } else {
+ fireEvent.change(screen.getByRole('combobox', { name: 'com_ui_change_project' }), {
+ target: { value: 'project-b' },
+ });
+ }
+ expect(screen.getByLabelText('Current route').textContent).toBe(
+ action === 'remove' ? '/c/new' : '/c/new?projectId=project-b',
+ );
+ expect(previous()).toBe(false);
+ const current = captureComposerDraft(3, 'new');
+ expect(current()).toBe(true);
+ expect(adoptComposerConversation(previousLaunch, 'stale-project-chat', 3)).toBe(false);
+ const launch = { conversationId: 'new' };
+ bindComposerLaunch(launch, 3);
+ act(() => view.api.setSubmitting(true));
+ expect(current()).toBe(true);
+ expect(adoptComposerConversation(launch, 'current-project-chat', 3)).toBe(true);
+ expect(current.conversationId()).toBe('current-project-chat');
+ view.unmount();
+ },
+);
+
+it('keeps ownership when the project selection does not change the route', () => {
+ const view = mountProjectComposer();
+ const captured = captureComposerDraft(3, 'new');
+ fireEvent.change(screen.getByRole('combobox', { name: 'com_ui_change_project' }), {
+ target: { value: 'project-a' },
+ });
+ expect(captured()).toBe(true);
+ view.unmount();
+});
diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.ts
index 168badea82..9731c4b7a2 100644
--- a/client/src/hooks/Chat/useChatFunctions.ts
+++ b/client/src/hooks/Chat/useChatFunctions.ts
@@ -30,11 +30,17 @@ import type {
} from 'librechat-data-provider';
import type { SetterOrUpdater } from 'recoil';
import type { TAskFunction, ExtendedFile } from '~/common';
+import {
+ logger,
+ requestChatFocus,
+ markPasteSubmitted,
+ isSubmittableMessage,
+ bindComposerLaunch,
+} from '~/utils';
import {
withSubmittedCodeDecision,
resolveSubmittedCodeApprovalMode,
} from '~/hooks/Agents/codeDecision';
-import { logger, requestChatFocus, markPasteSubmitted, isSubmittableMessage } from '~/utils';
import { activeUsageResponseIdFamily } from '~/components/Chat/Input/TokenUsage/store';
import useFocusRegeneratedResponse from '~/hooks/Chat/useFocusRegeneratedResponse';
import useGetConversation from '~/hooks/Conversations/useGetConversation';
@@ -460,6 +466,7 @@ export default function useChatFunctions({
* completion synchronously, which is the whole window it has to cover. */
askInFlightRef.current = true;
setSubmissionStart(Date.now());
+ bindComposerLaunch(submission.conversation, index);
setSubmission(submission);
logger.dir('message_stream', {
conversationId,
diff --git a/client/src/hooks/Files/__tests__/useFileHandling.test.ts b/client/src/hooks/Files/__tests__/useFileHandling.test.ts
index a49b0956d8..efee967391 100644
--- a/client/src/hooks/Files/__tests__/useFileHandling.test.ts
+++ b/client/src/hooks/Files/__tests__/useFileHandling.test.ts
@@ -1,11 +1,15 @@
+import React from 'react';
import { renderHook, act, waitFor } from '@testing-library/react';
import {
megabyte,
Constants,
+ EToolResources,
mergeFileConfig,
EModelEndpoint,
getEndpointFileConfig,
} from 'librechat-data-provider';
+import type { ExtendedFile } from '~/common';
+import { setFileSearchChoice, clearFileSearchChoices } from '~/utils/choices';
type MockUploadMutationOptions = {
onSuccess?: (
@@ -51,6 +55,15 @@ let mockHeicModuleError: Error | undefined;
const mockShowToast = jest.fn();
const mockSetFilesLoading = jest.fn();
const mockMutate = jest.fn();
+let mockEphemeralAgent: { file_search?: boolean; execute_code?: boolean } = {};
+const mockSetEphemeralAgent = jest.fn(
+ (update: (previous: typeof mockEphemeralAgent) => typeof mockEphemeralAgent, _key?: string) => {
+ mockEphemeralAgent = update(mockEphemeralAgent);
+ },
+);
+let mockDownloadedFiles: File[] = [];
+let mockDownloadError: Error | undefined;
+let mockDownloadGate: Promise<void> | undefined;
const mockProcessFileForUpload = jest.fn(
async (_file: File, _quality?: number, _onProgress?: (progress: number) => void) => _file,
);
@@ -94,7 +107,15 @@ jest.mock('@librechat/client', () => ({
jest.mock('recoil', () => ({
...jest.requireActual('recoil'),
- useSetRecoilState: jest.fn(() => jest.fn()),
+ useRecoilCallback: jest.fn((callback) =>
+ callback({ set: (atom, update) => mockSetEphemeralAgent(update, atom.key) }),
+ ),
+ useSetRecoilState: jest.fn(
+ (atom: { key: string }) =>
+ (update: (previous: typeof mockEphemeralAgent) => typeof mockEphemeralAgent) => {
+ mockSetEphemeralAgent(update, atom.key);
+ },
+ ),
}));
jest.mock('~/Providers/ChatSettingsContext', () => ({
@@ -103,7 +124,7 @@ jest.mock('~/Providers/ChatSettingsContext', () => ({
jest.mock('~/store', () => ({
__esModule: true,
- ephemeralAgentByConvoId: jest.fn(() => ({ key: 'mock' })),
+ ephemeralAgentByConvoId: jest.fn((key: string) => ({ key })),
}));
jest.mock('@tanstack/react-query', () => ({
@@ -131,6 +152,23 @@ jest.mock('~/hooks/useLocalize', () => {
return { __esModule: true, default: fn, TranslationKeys: {} };
});
+jest.mock('../useSharePointDownload', () => ({
+ __esModule: true,
+ default: (options: { onFilesDownloaded?: (files: File[]) => void | Promise<void> }) => ({
+ downloadSharePointFiles: async () => {
+ await mockDownloadGate;
+ if (mockDownloadError) {
+ throw mockDownloadError;
+ }
+ await options.onFilesDownloaded?.(mockDownloadedFiles);
+ return mockDownloadedFiles;
+ },
+ isDownloading: false,
+ downloadProgress: null,
+ error: null,
+ }),
+}));
+
jest.mock('../useDelayedUploadToast', () => ({
useDelayedUploadToast: jest.fn(() => ({
startUploadTimer: jest.fn(),
@@ -199,6 +237,7 @@ describe('useFileHandling', () => {
});
beforeEach(() => {
jest.clearAllMocks();
+ localStorage.clear();
mockValidateFiles.mockImplementation(() => true);
mockPartitionUploads.mockImplementation(jest.requireActual('~/utils/files').partitionUploads);
mockValidateFileSizes.mockImplementation(jest.requireActual('~/utils/files').validateFileSizes);
@@ -218,6 +257,11 @@ describe('useFileHandling', () => {
mockIsTemporary = false;
mockImageDecodes = true;
mockUploadOptions = {};
+ mockEphemeralAgent = {};
+ mockDownloadedFiles = [];
+ mockDownloadError = undefined;
+ mockDownloadGate = undefined;
+ clearFileSearchChoices();
});
const loadHook = async () => (await import('../useFileHandling')).default;
@@ -261,7 +305,7 @@ describe('useFileHandling', () => {
body,
),
);
- expect(mockDeleteFileById).toHaveBeenCalledWith(fileId);
+ expect(mockDeleteFileById).toHaveBeenCalledWith(fileId, expect.any(Function));
await waitFor(() =>
expect(mockLocalize).toHaveBeenCalledWith('com_error_files_provider_audio_format'),
);
@@ -1514,6 +1558,482 @@ describe('useFileHandling', () => {
});
});
+ describe('explicit File Search activation', () => {
+ beforeEach(() => jest.useFakeTimers());
+ afterEach(() => {
+ act(() => jest.runOnlyPendingTimers());
+ jest.useRealTimers();
+ mockAddFile.mockReset();
+ mockReplaceFile.mockReset();
+ mockDeleteFileById.mockReset();
+ });
+
+ const document = () => new File(['hello'], 'search.txt', { type: 'text/plain' });
+ const succeed = (body: FormData) => {
+ mockUploadOptions.onSuccess?.(
+ {
+ temp_file_id: body.get('file_id') as string,
+ file_id: 'persisted-search-file',
+ filepath: '/files/search.txt',
+ type: 'text/plain',
+ filename: 'search.txt',
+ source: 'local',
+ embedded: true,
+ },
+ body,
+ );
+ };
+
+ it.each([false, true])(
+ 'cancels a visible staged document through a separate tray instance (preenabled: %s)',
+ async (preenabled) => {
+ mockEphemeralAgent = { file_search: preenabled };
+ let release: () => void = () => undefined;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ mockResizeImageIfNeeded.mockImplementationOnce(async (file: File) => {
+ await gate;
+ return { file, resized: false };
+ });
+ const { useFileHandlingNoChatContext, clearUploadRecovery, hasInFlightUpload } =
+ await import('../useFileHandling');
+ const { result } = renderHook(() => {
+ const [files, setFiles] = React.useState(new Map<string, ExtendedFile>());
+ mockAddFile.mockImplementation((file) =>
+ setFiles((previous) => new Map(previous).set(file.file_id, file)),
+ );
+ mockReplaceFile.mockImplementation((file) =>
+ setFiles((previous) => new Map(previous).set(file.file_id, file)),
+ );
+ mockDeleteFileById.mockImplementation((id) =>
+ setFiles((previous) => {
+ const next = new Map(previous);
+ next.delete(id);
+ return next;
+ }),
+ );
+ const state = { files, setFiles, conversation: null };
+ return {
+ owner: useFileHandlingNoChatContext(undefined, state),
+ tray: useFileHandlingNoChatContext(undefined, state),
+ files,
+ };
+ });
+ let pending: Promise<boolean> = Promise.resolve(false);
+ act(() => {
+ pending = result.current.owner.handleFiles(
+ [document(), new File(['image'], 'surviving.png', { type: 'image/png' })],
+ EToolResources.file_search,
+ );
+ });
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ const canceledId = mockAddFile.mock.calls[0][0].file_id;
+ expect(result.current.files.has(canceledId)).toBe(true);
+ expect(hasInFlightUpload(canceledId)).toBe(true);
+ act(() => result.current.tray.abortUpload(canceledId));
+ expect(hasInFlightUpload(canceledId)).toBe(false);
+ expect(result.current.files.has(canceledId)).toBe(false);
+ act(() => clearUploadRecovery(canceledId, true));
+ await act(async () => {
+ release();
+ await pending;
+ jest.runAllTicks();
+ });
+ expect(result.current.files.has(canceledId)).toBe(false);
+ expect(mockMutate.mock.calls.some(([body]) => body.get('file_id') === canceledId)).toBe(
+ false,
+ );
+ expect(mockMutate).toHaveBeenCalledTimes(1);
+ expect(mockEphemeralAgent.file_search).toBe(preenabled);
+ act(() => succeed(mockMutate.mock.calls[0][0]));
+ expect(mockEphemeralAgent.file_search).toBe(true);
+ },
+ );
+
+ it('ignores late canceled responses without deleting a replacement or disabling Code', async () => {
+ mockEphemeralAgent = { execute_code: true };
+ const {
+ default: useFileHandling,
+ clearUploadRecovery,
+ hasInFlightUpload,
+ } = await import('../useFileHandling');
+ const { result } = renderHook(() => useFileHandling());
+ await act(async () => {
+ await result.current.handleFiles([document()], EToolResources.execute_code, {
+ fileId: 'reused-upload',
+ });
+ });
+ const oldBody = mockMutate.mock.calls[0][0] as FormData;
+ const oldOptions = mockUploadOptions;
+ act(() => clearUploadRecovery('reused-upload'));
+ await act(async () => {
+ await result.current.handleFiles([document()], EToolResources.file_search, {
+ fileId: 'reused-upload',
+ });
+ });
+ const deletes = mockDeleteFileById.mock.calls.length;
+ act(() => {
+ oldOptions.onError?.({ code: 'ERR_CANCELED' }, oldBody);
+ oldOptions.onSuccess?.(
+ {
+ temp_file_id: 'reused-upload',
+ file_id: 'old-server-file',
+ filepath: '',
+ type: 'text/plain',
+ filename: 'old.txt',
+ source: 'local',
+ embedded: true,
+ },
+ oldBody,
+ );
+ });
+ expect(hasInFlightUpload('reused-upload')).toBe(true);
+ expect(mockDeleteFileById).toHaveBeenCalledTimes(deletes);
+ expect(mockEphemeralAgent.execute_code).toBe(true);
+ expect(mockEphemeralAgent.file_search).not.toBe(true);
+ act(() => succeed(mockMutate.mock.calls[1][0]));
+ expect(mockEphemeralAgent.file_search).toBe(true);
+ expect(hasInFlightUpload('reused-upload')).toBe(false);
+ });
+
+ it('releases an assigned ID rejected before staging', async () => {
+ const { default: useFileHandling, hasInFlightUpload } = await import('../useFileHandling');
+ mockValidateFiles.mockReturnValueOnce(false);
+ const { result } = renderHook(() => useFileHandling());
+ await act(async () => {
+ expect(
+ await result.current.handleFiles([document()], EToolResources.file_search, {
+ fileId: 'rejected-upload',
+ }),
+ ).toBe(false);
+ });
+ expect(hasInFlightUpload('rejected-upload')).toBe(false);
+ expect(mockMutate).not.toHaveBeenCalled();
+ });
+
+ it('does not consume a replacement assigned ID when its canceled queued predecessor finishes', async () => {
+ let release: () => void = () => undefined;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ mockIsConfigPending = true;
+ mockWaitForConfig.mockImplementation(() => gate);
+ const { default: useFileHandling, hasInFlightUpload } = await import('../useFileHandling');
+ const { result } = renderHook(() => useFileHandling());
+ let first: Promise<boolean> = Promise.resolve(false);
+ let second: Promise<boolean> = Promise.resolve(false);
+ act(() => {
+ first = result.current.handleFiles([document()], EToolResources.file_search, {
+ fileId: 'queued-replacement',
+ });
+ second = result.current.handleFiles([document()], EToolResources.file_search, {
+ fileId: 'queued-replacement',
+ });
+ });
+ await act(async () => {
+ release();
+ expect(await first).toBe(false);
+ expect(await second).toBe(true);
+ });
+ expect(mockMutate).toHaveBeenCalledTimes(1);
+ expect(hasInFlightUpload('queued-replacement')).toBe(true);
+ act(() => succeed(mockMutate.mock.calls[0][0]));
+ expect(mockEphemeralAgent.file_search).toBe(true);
+ });
+
+ it.each(['config', 'resize', 'queue'])(
+ 'preserves a disable made after initiation but before %s finishes',
+ async (boundary) => {
+ const conversationId = Constants.NEW_CONVO as string;
+ setFileSearchChoice(conversationId, true);
+ mockEphemeralAgent = { file_search: true };
+ let release: () => void = () => undefined;
+ const gate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ if (boundary !== 'resize') {
+ mockIsConfigPending = true;
+ mockWaitForConfig.mockImplementation(() => gate);
+ } else {
+ mockImageDecodes = false;
+ mockResizeImageIfNeeded.mockImplementationOnce(async (file: File) => {
+ await gate;
+ return { file, resized: false };
+ });
+ }
+ const useFileHandling = await loadHook();
+ const { result } = renderHook(() => useFileHandling());
+ let first: Promise<boolean> | undefined;
+ let pending: Promise<boolean> = Promise.resolve(false);
+ act(() => {
+ if (boundary === 'queue') {
+ first = result.current.handleFiles([
+ new File(['one'], 'first.txt', { type: 'text/plain' }),
+ ]);
+ }
+ pending = result.current.handleFiles(
+ boundary === 'resize'
+ ? [document(), new File(['image'], 'companion.png', { type: 'image/png' })]
+ : [document()],
+ EToolResources.file_search,
+ );
+ });
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ expect(mockMutate).not.toHaveBeenCalled();
+ setFileSearchChoice(conversationId, false);
+ mockEphemeralAgent = { file_search: false };
+ await act(async () => {
+ release();
+ await first;
+ await pending;
+ jest.runAllTicks();
+ });
+ const body = mockMutate.mock.calls.find(
+ ([form]) => form.get('tool_resource') === EToolResources.file_search,
+ )?.[0] as FormData;
+ expect(body).toBeDefined();
+ act(() => succeed(body));
+ expect(mockEphemeralAgent.file_search).toBe(false);
+ if (boundary === 'resize') expect(mockDeleteFileById).toHaveBeenCalled();
+ },
+ );
+
+ it.each(['context', 'no-context'])(
+ 'captures ordering before the SharePoint download await (%s)',
+ async (variant) => {
+ const conversationId = Constants.NEW_CONVO as string;
+ setFileSearchChoice(conversationId, true);
+ mockEphemeralAgent = { file_search: true };
+ mockDownloadedFiles = [document()];
+ let release: () => void = () => undefined;
+ mockDownloadGate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ const sharePoint = await import('../useSharePointFileHandling');
+ const props = { toolResource: EToolResources.file_search };
+ const state = { files: new Map(), setFiles: jest.fn(), conversation: null };
+ const useSharePoint =
+ variant === 'context'
+ ? () => sharePoint.default(props)
+ : () => sharePoint.useSharePointFileHandlingNoChatContext(props, state);
+ const { result } = renderHook(() => useSharePoint());
+ let pending: Promise<void> = Promise.resolve();
+ act(() => {
+ pending = result.current.handleSharePointFiles([]);
+ });
+ expect(mockMutate).not.toHaveBeenCalled();
+ setFileSearchChoice(conversationId, false);
+ mockEphemeralAgent = { file_search: false };
+ await act(async () => {
+ release();
+ await pending;
+ });
+ expect(mockMutate).toHaveBeenCalledTimes(1);
+ act(() => succeed(mockMutate.mock.calls[0][0]));
+ expect(mockEphemeralAgent.file_search).toBe(false);
+ },
+ );
+
+ it('activates after persistence and before the attachment is submit-ready', async () => {
+ const useFileHandling = await loadHook();
+ const { result } = renderHook(() => useFileHandling());
+ const onSuccess = jest.fn(() => expect(mockEphemeralAgent.file_search).toBe(true));
+ await act(async () => {
+ await result.current.handleFiles([document()], EToolResources.file_search, { onSuccess });
+ });
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ act(() => succeed(mockMutate.mock.calls[0][0]));
+ expect(mockEphemeralAgent.file_search).toBe(true);
+ expect(onSuccess).toHaveBeenCalledTimes(1);
+ expect(mockUpdateFileById).not.toHaveBeenCalledWith(
+ expect.anything(),
+ expect.objectContaining({ progress: 1 }),
+ expect.anything(),
+ );
+ });
+
+ it.each(['empty', 'rejected', 'invalid', 'oversized'])(
+ 'does not activate for an %s batch',
+ async (mode) => {
+ const error = jest.spyOn(console, 'error').mockImplementation(() => undefined);
+ if (mode === 'rejected') mockValidateFiles.mockReturnValueOnce(false);
+ if (mode === 'invalid') {
+ mockValidateFiles.mockImplementationOnce(() => {
+ throw new Error('invalid config');
+ });
+ }
+ mockFileConfig = mergeFileConfig({ endpoints: { default: { fileSizeLimit: 1 } } });
+ const useFileHandling = await loadHook();
+ const { result } = renderHook(() => useFileHandling());
+ const files =
+ mode === 'empty'
+ ? []
+ : [
+ mode === 'oversized'
+ ? makeSizedFile('large.txt', 'text/plain', 2 * megabyte)
+ : document(),
+ ];
+ await act(async () => {
+ expect(await result.current.handleFiles(files, EToolResources.file_search)).toBe(false);
+ });
+ expect(mockMutate).not.toHaveBeenCalled();
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ error.mockRestore();
+ },
+ );
+
+ it.each([false, true])('preserves preenabled=%s on cancel/error', async (enabled) => {
+ const log = jest.spyOn(console, 'log').mockImplementation(() => undefined);
+ mockEphemeralAgent = { file_search: enabled };
+ const useFileHandling = await loadHook();
+ const { result } = renderHook(() => useFileHandling());
+ await act(async () => {
+ await result.current.handleFiles([document()], EToolResources.file_search);
+ });
+ const body = mockMutate.mock.calls[0][0] as FormData;
+ act(() => result.current.abortUpload(body.get('file_id') as string));
+ act(() => succeed(body));
+ expect(mockEphemeralAgent.file_search).toBe(enabled);
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ act(() => mockUploadOptions.onError?.(new Error('upload failed'), body));
+ expect(mockEphemeralAgent.file_search).toBe(enabled);
+ log.mockRestore();
+ });
+
+ it('does not activate on upload failure without cancellation', async () => {
+ const log = jest.spyOn(console, 'log').mockImplementation(() => undefined);
+ const useFileHandling = await loadHook();
+ const { result } = renderHook(() => useFileHandling());
+ await act(async () => {
+ await result.current.handleFiles([document()], EToolResources.file_search);
+ });
+ act(() => {
+ mockUploadOptions.onError?.(new Error('upload failed'), mockMutate.mock.calls[0][0]);
+ });
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ log.mockRestore();
+ });
+
+ it('activates when a surviving file in a partially rejected batch succeeds', async () => {
+ mockFileConfig = mergeFileConfig({ endpoints: { default: { fileSizeLimit: 1 } } });
+ const useFileHandling = await loadHook();
+ const { result } = renderHook(() => useFileHandling());
+ await act(async () => {
+ expect(
+ await result.current.handleFiles(
+ [document(), makeSizedFile('large.txt', 'text/plain', 2 * megabyte)],
+ EToolResources.file_search,
+ ),
+ ).toBe(true);
+ });
+ expect(mockMutate).toHaveBeenCalledTimes(1);
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ act(() => succeed(mockMutate.mock.calls[0][0]));
+ expect(mockEphemeralAgent.file_search).toBe(true);
+ });
+
+ it('retains only activation when New Chat keeps the upload as a draft', async () => {
+ const { clearUploadRecovery } = await import('../useFileHandling');
+ const onSuccess = jest.fn();
+ const onAbort = jest.fn();
+ const useFileHandling = await loadHook();
+ const { result } = renderHook(() => useFileHandling());
+ await act(async () => {
+ await result.current.handleFiles([document()], EToolResources.file_search, {
+ onSuccess,
+ onAbort,
+ });
+ });
+ const body = mockMutate.mock.calls[0][0] as FormData;
+ act(() => clearUploadRecovery(body.get('file_id') as string, true));
+ expect(onAbort).toHaveBeenCalledTimes(1);
+ act(() => succeed(body));
+ expect(mockEphemeralAgent.file_search).toBe(true);
+ expect(onSuccess).not.toHaveBeenCalled();
+ });
+
+ it('activates only the originating conversation after navigation', async () => {
+ mockConversation = { conversationId: 'origin', endpoint: 'openAI' };
+ const useFileHandling = await loadHook();
+ const { result, rerender } = renderHook(() => useFileHandling());
+ await act(async () => {
+ await result.current.handleFiles([document()], EToolResources.file_search);
+ });
+ mockConversation = { conversationId: 'destination', endpoint: 'openAI' };
+ rerender();
+ act(() => succeed(mockMutate.mock.calls[0][0]));
+ expect(mockSetEphemeralAgent).toHaveBeenCalledWith(expect.any(Function), 'origin');
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalledWith(expect.anything(), 'destination');
+ });
+
+ it.each([undefined, EToolResources.context])(
+ 'leaves implicit/context uploads unchanged (%s)',
+ async (resource) => {
+ const useFileHandling = await loadHook();
+ const { result } = renderHook(() => useFileHandling());
+ await act(async () => {
+ await result.current.handleFiles([document()], resource);
+ });
+ act(() => succeed(mockMutate.mock.calls[0][0]));
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ },
+ );
+
+ it('does not change saved-agent tool configuration', async () => {
+ mockConversation = { agent_id: 'agent_saved', endpoint: 'agents' };
+ const useFileHandling = await loadHook();
+ const { result } = renderHook(() => useFileHandling());
+ await act(async () => {
+ await result.current.handleFiles([document()], EToolResources.file_search);
+ });
+ act(() => succeed(mockMutate.mock.calls[0][0]));
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ });
+
+ it.each(['empty', 'rejected', 'success', 'download failure'])(
+ 'uses the same persistence boundary for SharePoint (%s)',
+ async (mode) => {
+ const log = jest.spyOn(console, 'error').mockImplementation(() => undefined);
+ mockDownloadedFiles = mode === 'empty' ? [] : [document()];
+ if (mode === 'rejected') mockValidateFiles.mockReturnValueOnce(false);
+ if (mode === 'download failure') mockDownloadError = new Error('download failed');
+ const { useSharePointFileHandlingNoChatContext } = await import(
+ '../useSharePointFileHandling'
+ );
+ const { result } = renderHook(() =>
+ useSharePointFileHandlingNoChatContext(
+ { toolResource: EToolResources.file_search },
+ { files: new Map(), setFiles: jest.fn(), conversation: null },
+ ),
+ );
+ await act(async () => {
+ const promise = result.current.handleSharePointFiles([]);
+ if (mode === 'download failure') {
+ await expect(promise).rejects.toThrow('download failed');
+ } else {
+ await promise;
+ }
+ });
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ if (mode === 'success') {
+ expect(mockMutate).toHaveBeenCalledTimes(1);
+ act(() => succeed(mockMutate.mock.calls[0][0]));
+ expect(mockEphemeralAgent.file_search).toBe(true);
+ } else {
+ expect(mockMutate).not.toHaveBeenCalled();
+ }
+ log.mockRestore();
+ },
+ );
+ });
+
/** Callers gate success messaging on this result, so a rejected upload must not report true */
describe('acceptance result', () => {
it('resolves false when validation rejects the files', async () => {
@@ -1785,6 +2305,112 @@ describe('useFileHandling', () => {
consoleLog.mockRestore();
});
});
+ it('finishes a persisted replacement after its success callback consumes the source', async () => {
+ jest.useFakeTimers();
+ try {
+ let eligible = true;
+ const useFileHandling = await loadHook();
+ const { result } = renderHook(() => useFileHandling());
+ await act(async () => {
+ await result.current.handleFiles(
+ [new File(['text'], 'replacement.txt', { type: 'text/plain' })],
+ undefined,
+ {
+ shouldCommit: () => eligible,
+ onSuccess: () => {
+ eligible = false;
+ },
+ },
+ );
+ });
+ const body = mockMutate.mock.calls[0][0] as FormData;
+ act(() => {
+ mockUploadOptions.onSuccess?.(
+ {
+ temp_file_id: body.get('file_id') as string,
+ file_id: 'saved',
+ filepath: '/files/saved',
+ type: 'text/plain',
+ filename: 'replacement.txt',
+ source: 'local',
+ embedded: false,
+ },
+ body,
+ );
+ jest.runAllTimers();
+ });
+ expect(eligible).toBe(false);
+ expect(mockUpdateFileById).toHaveBeenLastCalledWith(
+ expect.any(String),
+ expect.objectContaining({ progress: 1 }),
+ false,
+ expect.any(Function),
+ );
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
+ it('rechecks upload ownership when queued file-map updaters execute', () => {
+ const useUpdateFiles = jest.requireActual('../useUpdateFiles').default;
+ const updates: React.SetStateAction<Map<string, ExtendedFile>>[] = [];
+ const setFiles = (update: React.SetStateAction<Map<string, ExtendedFile>>) =>
+ updates.push(update);
+ const { result } = renderHook(() => useUpdateFiles(setFiles));
+ let ownsComposer = true;
+ const isCurrent = () => ownsComposer;
+ const file = { file_id: 'existing', progress: 0.2, size: 1 } as ExtendedFile;
+ act(() => {
+ result.current.addFile(file, isCurrent);
+ result.current.replaceFile(file, isCurrent);
+ result.current.updateFileById(file.file_id, { progress: 1 }, false, isCurrent);
+ result.current.deleteFileById(file.file_id, isCurrent);
+ });
+ ownsComposer = false;
+ const destination = new Map([[file.file_id, file]]);
+ for (const update of updates) {
+ expect(typeof update === 'function' ? update(destination) : update).toBe(destination);
+ }
+ });
+
+ it('rechecks the upload entry identity when deferred disposal executes', () => {
+ const useUpdateFiles =
+ jest.requireActual<typeof import('../useUpdateFiles')>('../useUpdateFiles').default;
+ const updates: React.SetStateAction<Map<string, ExtendedFile>>[] = [];
+ const { result } = renderHook(() => useUpdateFiles((update) => updates.push(update)));
+ const original = new File(['old'], 'old.txt', { type: 'text/plain' });
+ const replacement = new File(['fresh'], 'fresh.txt', { type: 'text/plain' });
+ const file = { file_id: 'retired-id', file: original, progress: 0.2, size: 3 };
+ act(() =>
+ result.current.deleteFileById('retired-id', (files) => {
+ const entry = files.get('retired-id');
+ return entry?.file === original && entry.progress < 1;
+ }),
+ );
+ const update = updates[0];
+ expect(typeof update).toBe('function');
+ if (typeof update !== 'function') throw new Error('Expected a deferred update');
+ const retained = { file_id: 'kept', progress: 1, size: 1 };
+ const retired = new Map<string, ExtendedFile>([
+ ['retired-id', file],
+ ['kept', retained],
+ ]);
+ expect(update(retired).has('retired-id')).toBe(false);
+ expect(update(retired).get('kept')).toBe(retained);
+ for (const entry of [
+ { ...file, file: replacement },
+ { ...file, progress: 1 },
+ ]) {
+ const current = new Map<string, ExtendedFile>([
+ ['retired-id', entry],
+ ['kept', retained],
+ ]);
+ expect(update(current)).toBe(current);
+ }
+ const current = new Map([['kept', retained]]);
+ expect(update(current)).toBe(current);
+ });
+
describe('stalled attachments', () => {
/**
* The upload only starts once the browser has decoded the image, so a decode
@@ -1808,7 +2434,7 @@ describe('useFileHandling', () => {
const addedFile = mockAddFile.mock.calls[0][0] as { file_id: string };
expect(mockMutate).not.toHaveBeenCalled();
- expect(mockDeleteFileById).toHaveBeenCalledWith(addedFile.file_id);
+ expect(mockDeleteFileById).toHaveBeenCalledWith(addedFile.file_id, expect.any(Function));
});
it('reports the failure through the upload lifecycle when a decode fails', async () => {
diff --git a/client/src/hooks/Files/search.ts b/client/src/hooks/Files/search.ts
new file mode 100644
index 0000000000..aadf3f7c76
--- /dev/null
+++ b/client/src/hooks/Files/search.ts
@@ -0,0 +1,237 @@
+import { Constants, LocalStorageKeys } from 'librechat-data-provider';
+import type { TEphemeralAgent } from 'librechat-data-provider';
+import type { CapturedComposerDraft } from '~/utils/drafts';
+import {
+ getFileSearchChoice,
+ transferFileSearchChoice,
+ acceptFileSearchChoice,
+} from '~/utils/choices';
+import { getTimestampedValue, isTimestampExpired, setTimestamp } from '~/utils/timestamps';
+import { getNewConversationDraftRevision } from '~/utils/drafts';
+import { FILE_SEARCH_UPLOAD_PREFIX } from '~/utils/localStorage';
+
+const keyFor = (fileId: string) => `${FILE_SEARCH_UPLOAD_PREFIX}${fileId}`;
+
+export type FileSearchUploadContext = Readonly<{
+ conversationId: string;
+ choiceRevision: string | null;
+ createdAt: number;
+ projectId?: string | null;
+ newChatGeneration?: Readonly<{ index: number; revision: string }>;
+}>;
+type Intent = FileSearchUploadContext;
+const owners = new WeakMap<FileSearchUploadContext, CapturedComposerDraft>();
+const assignments = new Map<string, { owner: CapturedComposerDraft; dispose: () => void }>();
+
+export function transferFileSearchPreference(
+ sourceId: string,
+ targetId: string,
+): boolean | undefined {
+ let enabled = transferFileSearchChoice(sourceId, targetId);
+ const targetKey = `${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}${targetId}`;
+ try {
+ const preference =
+ getTimestampedValue(targetKey) ??
+ getTimestampedValue(`${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}${sourceId}`);
+ if (enabled == null && (preference === 'true' || preference === 'false')) {
+ enabled = preference === 'true';
+ }
+ if (enabled != null) {
+ localStorage.setItem(targetKey, JSON.stringify(enabled));
+ setTimestamp(targetKey);
+ }
+ } catch {
+ // A blocked store must not prevent the acknowledged identity handoff.
+ }
+ return enabled;
+}
+
+export function getFileSearchPreference(conversationId: string): boolean | undefined {
+ const choice = getFileSearchChoice(conversationId);
+ if (choice) return choice.enabled;
+ try {
+ const preference = getTimestampedValue(
+ `${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}${conversationId}`,
+ );
+ if (preference === 'true' || preference === 'false') return preference === 'true';
+ } catch {
+ // Unavailable storage leaves the live template as the fallback.
+ }
+ return undefined;
+}
+
+/** Acknowledgements cannot replay a tool snapshot over accepted uploads or later toggles. */
+export function withFileSearchPreference(
+ conversationId: string,
+ agent: TEphemeralAgent | null | undefined,
+): TEphemeralAgent | null | undefined {
+ const enabled = getFileSearchPreference(conversationId);
+ return enabled == null || enabled === agent?.file_search
+ ? agent
+ : { ...agent, file_search: enabled };
+}
+
+export function captureFileSearchUpload(
+ conversationId: string,
+ owner?: CapturedComposerDraft,
+): FileSearchUploadContext {
+ const context = {
+ get conversationId() {
+ return owner?.conversationId() ?? conversationId;
+ },
+ choiceRevision: getFileSearchChoice(conversationId)?.revision ?? null,
+ createdAt: Date.now(),
+ projectId: new URLSearchParams(window.location.search).get('projectId'),
+ newChatGeneration:
+ conversationId === Constants.NEW_CONVO
+ ? (owner?.newChatGeneration ?? { index: 0, revision: getNewConversationDraftRevision(0) })
+ : undefined,
+ };
+ if (owner) owners.set(context, owner);
+ return context;
+}
+
+export function beginFileSearchUpload(
+ fileId: string,
+ operation: string | FileSearchUploadContext,
+): { choiceRevision: string | null; persisted: boolean } {
+ const context = typeof operation === 'string' ? captureFileSearchUpload(operation) : operation;
+ const { choiceRevision } = context;
+ assignments.get(fileId)?.dispose();
+ const owner = owners.get(context);
+ if (owner?.registered) {
+ assignments.set(fileId, {
+ owner,
+ dispose: owner.onAssignment((sourceId, targetId) => {
+ transferFileSearchPreference(sourceId, targetId);
+ try {
+ localStorage.setItem(keyFor(fileId), JSON.stringify(context));
+ } catch {
+ /* Live recovery owns completion. */
+ }
+ }),
+ });
+ }
+ try {
+ localStorage.setItem(keyFor(fileId), JSON.stringify(context));
+ return { choiceRevision, persisted: true };
+ } catch {
+ // The live recovery callback still owns activation when storage is unavailable.
+ }
+ return { choiceRevision, persisted: false };
+}
+
+export function cancelFileSearchUpload(fileId: string): void {
+ assignments.get(fileId)?.dispose();
+ assignments.delete(fileId);
+ try {
+ localStorage.removeItem(keyFor(fileId));
+ } catch {
+ // Best-effort storage cleanup.
+ }
+}
+
+function readIntent(fileId: string): Intent | null {
+ let intent: Intent | null = null;
+ try {
+ const value = JSON.parse(localStorage.getItem(keyFor(fileId)) ?? 'null') as Intent | null;
+ if (
+ value &&
+ typeof value.conversationId === 'string' &&
+ (value.choiceRevision === null || typeof value.choiceRevision === 'string') &&
+ Number.isFinite(value.createdAt) &&
+ !isTimestampExpired(value.createdAt)
+ ) {
+ intent = value;
+ }
+ } catch {
+ // A live callback can recover without a stored record.
+ }
+ return intent;
+}
+
+/** Unknown attachments remain restorable; explicit uploads must still own their destination. */
+export function canRestoreFileSearchUpload(
+ fileId: string,
+ conversationId: string,
+ context?: FileSearchUploadContext,
+): boolean {
+ const intent = context ?? readIntent(fileId);
+ const owner = assignments.get(fileId)?.owner ?? (context ? owners.get(context) : undefined);
+ if (
+ owner &&
+ (owner.conversationId() !== conversationId || (!owner() && !owner.retainsFile(fileId)))
+ ) {
+ return false;
+ }
+ if (!intent) return true;
+ if (intent.conversationId !== conversationId) return owner == null;
+ if (conversationId !== Constants.NEW_CONVO) return true;
+ const generation = intent.newChatGeneration;
+ return (
+ generation != null &&
+ Number.isInteger(generation.index) &&
+ generation.index >= 0 &&
+ generation.revision === getNewConversationDraftRevision(generation.index) &&
+ (intent.projectId === undefined ||
+ intent.projectId === new URLSearchParams(window.location.search).get('projectId'))
+ );
+}
+
+export function hasPendingFileSearchUpload(fileId: string, conversationId: string): boolean {
+ const intent = readIntent(fileId);
+ return (
+ intent?.conversationId === conversationId &&
+ canRestoreFileSearchUpload(fileId, conversationId, intent)
+ );
+}
+
+/** Completes only an explicit upload intent, never an arbitrary embedded attachment. */
+export function completeFileSearchUpload(
+ fileId: string,
+ conversationId: string,
+ choiceRevision?: string | null,
+): boolean {
+ const owner = assignments.get(fileId)?.owner;
+ let intent = readIntent(fileId);
+ intent ??=
+ choiceRevision === undefined
+ ? null
+ : {
+ conversationId,
+ choiceRevision,
+ createdAt: Date.now(),
+ newChatGeneration:
+ conversationId === Constants.NEW_CONVO
+ ? (owner?.newChatGeneration ?? {
+ index: 0,
+ revision: getNewConversationDraftRevision(0),
+ })
+ : undefined,
+ };
+ if (!intent) {
+ if (owner && !owner() && !owner.retainsFile(fileId)) {
+ owner.discardFile(fileId);
+ cancelFileSearchUpload(fileId);
+ } else if (!owner) cancelFileSearchUpload(fileId);
+ return false;
+ }
+ if (intent.conversationId !== conversationId) {
+ return false;
+ }
+ if (!canRestoreFileSearchUpload(fileId, conversationId, intent)) {
+ owner?.discardFile(fileId);
+ cancelFileSearchUpload(fileId);
+ return false;
+ }
+ cancelFileSearchUpload(fileId);
+ if (!acceptFileSearchChoice(conversationId, intent.choiceRevision)) return false;
+ const preferenceKey = `${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}${conversationId}`;
+ try {
+ localStorage.setItem(preferenceKey, 'true');
+ setTimestamp(preferenceKey);
+ } catch {
+ // Persistence is best-effort; the accepted live upload must remain usable.
+ }
+ return true;
+}
diff --git a/client/src/hooks/Files/useFileHandling.ts b/client/src/hooks/Files/useFileHandling.ts
index 08bb3c44ed..3253f4b095 100644
--- a/client/src/hooks/Files/useFileHandling.ts
+++ b/client/src/hooks/Files/useFileHandling.ts
@@ -1,9 +1,9 @@
import React, { useCallback, useEffect, useRef, useMemo, useState } from 'react';
import { v4 } from 'uuid';
import debounce from 'lodash/debounce';
-import { useSetRecoilState } from 'recoil';
import { useToastContext } from '@librechat/client';
import { useQueryClient } from '@tanstack/react-query';
+import { useSetRecoilState, useRecoilCallback } from 'recoil';
import {
megabyte,
QueryKeys,
@@ -11,6 +11,7 @@ import {
EToolResources,
mergeFileConfig,
isAssistantsEndpoint,
+ isEphemeralAgentId,
getEndpointFileConfig,
defaultAssistantsVersion,
} from 'librechat-data-provider';
@@ -23,6 +24,7 @@ import type {
import type { TConversation } from 'librechat-data-provider';
import type { SkippedUpload, UploadPartition } from '~/utils';
import type { ExtendedFile, FileSetter } from '~/common';
+import type { FileSearchUploadContext } from './search';
import {
logger,
validateFiles,
@@ -34,6 +36,13 @@ import {
removePreviewEntry,
validateFileDuplicates,
} from '~/utils';
+import {
+ beginFileSearchUpload,
+ captureFileSearchUpload,
+ canRestoreFileSearchUpload,
+ cancelFileSearchUpload,
+ completeFileSearchUpload,
+} from './search';
import { useGetFileConfig, useUploadFileMutation } from '~/data-provider';
import useAgentUploadTarget from '~/hooks/Agents/useAgentUploadTarget';
import useLocalize, { TranslationKeys } from '~/hooks/useLocalize';
@@ -41,6 +50,7 @@ import { useChatSettings } from '~/Providers/ChatSettingsContext';
import { useDelayedUploadToast } from './useDelayedUploadToast';
import { useChatContext } from '~/Providers/ChatContext';
import { importWithRecovery } from '~/lib/assets/lazy';
+import { captureComposerDraft } from '~/utils/drafts';
import { ephemeralAgentByConvoId } from '~/store';
import useClientResize from './useClientResize';
import useUpdateFiles from './useUpdateFiles';
@@ -56,6 +66,7 @@ type UseFileHandling = {
};
export type FileHandlingState = {
+ index?: number;
files: Map<string, ExtendedFile>;
setFiles: FileSetter;
setFilesLoading?: React.Dispatch<React.SetStateAction<boolean>>;
@@ -65,6 +76,7 @@ export type FileHandlingState = {
type ProcessedUpload = {
extendedFile: ExtendedFile;
preview: string;
+ recovery: UploadRecovery;
resizeDetails?: {
originalSize: number;
newSize: number;
@@ -73,6 +85,8 @@ type ProcessedUpload = {
};
export type UploadLifecycleCallbacks = {
+ /** Immutable operation intent, captured before queue/config/preparation/download waits. */
+ fileSearch?: Readonly<{ context: FileSearchUploadContext; activate: () => void }>;
/** Preassigned id so callers can persist recovery before the shared upload queue waits. */
fileId?: string;
/** An attachment being replaced remains in state until the replacement succeeds, but should not
@@ -82,6 +96,8 @@ export type UploadLifecycleCallbacks = {
* the shared file state. A `false` return abandons the batch so a delayed upload cannot land in
* a composer the user has since navigated away from. */
shouldCommit?: () => boolean;
+ /** UI ownership remains independent of a replacement's pre-staging eligibility. */
+ isCurrent?: () => boolean;
onStart?: (fileId: string) => void;
onSuccess?: (fileId: string) => void;
onError?: (fileId: string) => void;
@@ -89,19 +105,56 @@ export type UploadLifecycleCallbacks = {
};
const noop = () => {};
-const uploadErrorCallbacks = new Map<string, UploadLifecycleCallbacks>();
+type UploadRecovery = UploadLifecycleCallbacks & {
+ status: 'staged' | 'uploading' | 'settled' | 'canceled';
+ dispose?: () => void;
+ body?: FormData;
+ onFileSearchSuccess?: () => void;
+};
+const uploadErrorCallbacks = new Map<string, UploadRecovery>();
-const takeUploadRecovery = (fileId: string): UploadLifecycleCallbacks | undefined => {
+const takeUploadRecovery = (fileId: string, body?: FormData): UploadRecovery | undefined => {
const callbacks = uploadErrorCallbacks.get(fileId);
+ if (body && callbacks?.body !== body) {
+ return undefined;
+ }
uploadErrorCallbacks.delete(fileId);
+ if (callbacks) {
+ callbacks.status = 'settled';
+ }
return callbacks;
};
-export const clearUploadRecovery = (fileId: string) => {
- takeUploadRecovery(fileId)?.onAbort?.(fileId);
+export const clearUploadRecovery = (fileId: string, retainFileSearch = false) => {
+ const recovery = uploadErrorCallbacks.get(fileId);
+ const onAbort = recovery?.onAbort;
+ if (retainFileSearch && recovery?.fileSearch && recovery.status !== 'canceled') {
+ recovery.onStart = undefined;
+ recovery.onSuccess = undefined;
+ recovery.onError = undefined;
+ recovery.onAbort = undefined;
+ } else {
+ uploadErrorCallbacks.delete(fileId);
+ if (recovery) {
+ recovery.status = 'canceled';
+ recovery.dispose?.();
+ }
+ }
+ if (!retainFileSearch) {
+ cancelFileSearchUpload(fileId);
+ }
+ onAbort?.(fileId);
};
-export const hasInFlightUpload = (fileId: string): boolean => uploadErrorCallbacks.has(fileId);
+export const hasInFlightUpload = (fileId: string, conversationId?: string): boolean => {
+ const recovery = uploadErrorCallbacks.get(fileId);
+ return (
+ recovery != null &&
+ (conversationId == null ||
+ (recovery.fileSearch?.context.conversationId === conversationId &&
+ canRestoreFileSearchUpload(fileId, conversationId, recovery.fileSearch.context)))
+ );
+};
type UploadScope = {
queue: Promise<void>;
@@ -150,7 +203,21 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
const [errors, setErrors] = useState<string[]>([]);
const abortControllerRef = useRef<AbortController | null>(null);
const { startUploadTimer, clearUploadTimer } = useDelayedUploadToast();
- const { files, setFiles, conversation } = fileState;
+ const { files, setFiles, conversation, index = 0 } = fileState;
+ const owner = useMemo(
+ () => ({ index, fileSetter: params?.fileSetter }),
+ [index, params?.fileSetter],
+ );
+ const currentConversationRef = useRef(conversation?.conversationId ?? Constants.NEW_CONVO);
+ currentConversationRef.current = conversation?.conversationId ?? Constants.NEW_CONVO;
+ const ownerRef = useRef<typeof owner | null>(owner);
+ ownerRef.current = owner;
+ useEffect(() => {
+ ownerRef.current = owner;
+ return () => {
+ ownerRef.current = null;
+ };
+ }, [owner]);
const filesRef = useRef(files);
filesRef.current = files;
const fileSetter = params?.fileSetter ?? setFiles;
@@ -164,10 +231,28 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
}
}
}
+ const composerRoute = window.location.pathname + window.location.search;
+ useEffect(() => {
+ if (!tracksReservations) return;
+ for (const fileId of files.keys()) {
+ const recovery = uploadErrorCallbacks.get(fileId);
+ if (recovery?.isCurrent?.() === false) recovery.dispose?.();
+ }
+ }, [files, conversation?.conversationId, composerRoute, tracksReservations]);
+
const setFilesLoading = fileState.setFilesLoading ?? noop;
const setEphemeralAgent = useSetRecoilState(
ephemeralAgentByConvoId(conversation?.conversationId ?? Constants.NEW_CONVO),
);
+ const activateFileSearch = useRecoilCallback(
+ ({ set }) =>
+ (conversationId: string) =>
+ set(ephemeralAgentByConvoId(conversationId), (previous) => ({
+ ...previous,
+ [EToolResources.file_search]: true,
+ })),
+ [],
+ );
const { isTemporary } = useChatSettings();
const setError = (error: string) => setErrors((prevErrors) => [...prevErrors, error]);
@@ -274,12 +359,21 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
* the attachment stays below `progress: 1` and the send button never
* re-enables. Reconcile against the id we own. */
const fileId = (body.get('file_id') as string | null) ?? data.temp_file_id;
- takeUploadRecovery(fileId)?.onSuccess?.(fileId);
+ const recovery = takeUploadRecovery(fileId, body);
+ if (!recovery) {
+ return;
+ }
+ recovery.onFileSearchSuccess?.();
+ recovery?.onSuccess?.(fileId);
clearUploadTimer(fileId);
if (agent_id) {
queryClient.refetchQueries([QueryKeys.agent, agent_id]);
return;
}
+ if (recovery.isCurrent?.() === false) {
+ recovery.dispose?.();
+ return;
+ }
updateFileById(
fileId,
{
@@ -287,9 +381,14 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
filepath: data.filepath,
},
assistant_id ? true : false,
+ recovery.isCurrent,
);
setTimeout(() => {
+ if (recovery.isCurrent?.() === false) {
+ recovery.dispose?.();
+ return;
+ }
const cachedBlob = getCachedPreview(fileId);
if (cachedBlob && data.file_id !== fileId) {
cachePreview(data.file_id, cachedBlob);
@@ -316,23 +415,31 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
llmDeliveryPath: data.llmDeliveryPath,
},
assistant_id ? true : false,
+ recovery.isCurrent,
);
}, 300);
},
onError: (_error, body) => {
const error = _error as TError | undefined;
- console.log('upload error', error);
const file_id = body.get('file_id') as string;
- const uploadLifecycle = takeUploadRecovery(file_id);
+ const uploadLifecycle = takeUploadRecovery(file_id, body);
+ if (!uploadLifecycle) {
+ return;
+ }
+ console.log('upload error', error);
+ uploadLifecycle.dispose?.();
+ cancelFileSearchUpload(file_id);
const tool_resource = body.get('tool_resource');
- if (tool_resource === EToolResources.execute_code) {
+ if (
+ tool_resource === EToolResources.execute_code &&
+ uploadLifecycle.isCurrent?.() !== false
+ ) {
setEphemeralAgent((prev) => ({
...prev,
[EToolResources.execute_code]: false,
}));
}
clearUploadTimer(file_id);
- deleteFileById(file_id);
let errorMessage = 'com_error_files_upload';
@@ -348,22 +455,103 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
abortControllerRef.current?.signal,
);
+ const captureUploadLifecycle = (
+ toolResource?: string,
+ lifecycle?: UploadLifecycleCallbacks,
+ ): UploadLifecycleCallbacks | undefined => {
+ const ownsDraft = captureComposerDraft(
+ index,
+ conversation?.conversationId ?? Constants.NEW_CONVO,
+ );
+ if (isConversationUpload) {
+ const originId = conversation?.conversationId ?? Constants.NEW_CONVO;
+ const shouldCommit = lifecycle?.shouldCommit;
+ const previousOwner = lifecycle?.isCurrent;
+ const usesComposerOwner = ownsDraft.registered && params?.fileSetter == null;
+ const isCurrent = () =>
+ (usesComposerOwner || ownerRef.current === owner) &&
+ ownsDraft() &&
+ (usesComposerOwner ||
+ currentConversationRef.current === originId ||
+ currentConversationRef.current === ownsDraft.conversationId()) &&
+ previousOwner?.() !== false;
+ lifecycle = {
+ ...lifecycle,
+ isCurrent,
+ shouldCommit: () => isCurrent() && shouldCommit?.() !== false,
+ };
+ }
+ if (
+ lifecycle?.fileSearch ||
+ !isConversationUpload ||
+ isAssistantsEndpoint(endpointType ?? endpoint) ||
+ toolResource !== EToolResources.file_search ||
+ !isEphemeralAgentId(conversation?.agent_id)
+ ) {
+ return lifecycle;
+ }
+ return {
+ ...lifecycle,
+ fileSearch: {
+ context: captureFileSearchUpload(
+ conversation?.conversationId ?? Constants.NEW_CONVO,
+ ownsDraft,
+ ),
+ activate: () => activateFileSearch(ownsDraft.conversationId()),
+ },
+ };
+ };
+
+ const canStageUpload = (fileId: string, recovery: UploadRecovery): boolean => {
+ if (recovery.status !== 'staged') return false;
+ if (recovery.shouldCommit?.() !== false) return true;
+ if (uploadErrorCallbacks.get(fileId) === recovery) clearUploadRecovery(fileId);
+ return false;
+ };
+
const uploadWithRecovery = (
formData: FormData,
file_id: string,
- uploadLifecycle?: UploadLifecycleCallbacks,
+ uploadLifecycle: UploadRecovery,
) => {
- if (uploadLifecycle) {
- uploadErrorCallbacks.set(file_id, uploadLifecycle);
- uploadLifecycle.onStart?.(file_id);
+ /* Capture the originating conversation's setter, not the mutation observer's
+ * current conversation. Removal clears this callback before any late success. */
+ if (!canStageUpload(file_id, uploadLifecycle)) {
+ return;
+ }
+ const callbacks = uploadLifecycle;
+ callbacks.status = 'uploading';
+ callbacks.body = formData;
+ const operation = uploadLifecycle?.fileSearch;
+ if (operation && formData.get('tool_resource') === EToolResources.file_search) {
+ const intent = beginFileSearchUpload(file_id, operation.context);
+ callbacks.onFileSearchSuccess = () => {
+ if (
+ completeFileSearchUpload(
+ file_id,
+ operation.context.conversationId,
+ intent.persisted ? undefined : intent.choiceRevision,
+ )
+ ) {
+ operation.activate();
+ }
+ };
+ }
+ uploadErrorCallbacks.set(file_id, callbacks);
+ callbacks.onStart?.(file_id);
+ if (callbacks.shouldCommit?.() === false) {
+ clearUploadRecovery(file_id);
+ return;
+ }
+ if (callbacks.status === 'uploading') {
+ uploadFile.mutate(formData);
}
- uploadFile.mutate(formData);
};
- const startUpload = async (
- extendedFile: ExtendedFile,
- uploadLifecycle?: UploadLifecycleCallbacks,
- ) => {
+ const startUpload = async (extendedFile: ExtendedFile, uploadLifecycle: UploadRecovery) => {
+ if (!canStageUpload(extendedFile.file_id, uploadLifecycle)) {
+ return;
+ }
const filename = extendedFile.file?.name ?? 'File';
startUploadTimer(extendedFile.file_id, filename, extendedFile.size);
@@ -456,17 +644,20 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
const loadImage = (
extendedFile: ExtendedFile,
preview: string,
- uploadLifecycle?: UploadLifecycleCallbacks,
+ uploadLifecycle: UploadRecovery,
) => {
const img = new Image();
img.onload = async () => {
+ if (!canStageUpload(extendedFile.file_id, uploadLifecycle)) {
+ return;
+ }
const measuredFile: ExtendedFile = {
...extendedFile,
width: img.width,
height: img.height,
progress: 0.6,
};
- replaceFile(measuredFile);
+ replaceFile(measuredFile, uploadLifecycle.isCurrent);
await startUpload(measuredFile, uploadLifecycle);
};
@@ -477,17 +668,12 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
* session, with nothing to click and no error to explain it. Drop the file and
* say so instead. */
img.onerror = () => {
- clearUploadTimer(extendedFile.file_id);
- takeUploadRecovery(extendedFile.file_id)?.onError?.(extendedFile.file_id);
- deleteFileById(extendedFile.file_id);
- /** Reservations are released by the render that observes the file in the
- * shared state, which a decode failing before that render never reaches —
- * and once the file is gone no later render can either. A leaked one is
- * merged into every subsequent batch's validation, so re-picking the same
- * file reads as a duplicate and its size keeps counting against the limit. */
- uploadScope.recent.delete(extendedFile.file_id);
- removePreviewEntry(extendedFile.file_id);
- URL.revokeObjectURL(preview);
+ if (!canStageUpload(extendedFile.file_id, uploadLifecycle)) {
+ return;
+ }
+ const recovery = takeUploadRecovery(extendedFile.file_id);
+ recovery?.dispose?.();
+ recovery?.onError?.(extendedFile.file_id);
setError('com_error_files_process');
};
img.src = preview;
@@ -495,10 +681,17 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
/** Resolves to whether the files passed validation and were accepted for upload. */
const processFiles = async (
- fileList: File[],
+ originalFileList: File[],
_toolResource?: string,
uploadLifecycle?: UploadLifecycleCallbacks,
+ assignedRecovery?: UploadRecovery,
): Promise<boolean> => {
+ const fileList =
+ assignedRecovery?.status === 'canceled' ? originalFileList.slice(1) : originalFileList;
+ if (assignedRecovery?.status === 'canceled' && fileList.length === 0) {
+ setFilesLoading(false);
+ return false;
+ }
abortControllerRef.current = new AbortController();
const existingFiles = tracksReservations
@@ -572,16 +765,58 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
return false;
}
+ const includesAssignedFile =
+ assignedRecovery?.status === 'staged' &&
+ (selection.keptIndices.length === 0 || selection.keptIndices[0] === 0);
+ if (assignedRecovery && !includesAssignedFile) {
+ if (uploadErrorCallbacks.get(uploadLifecycle?.fileId ?? '') === assignedRecovery) {
+ takeUploadRecovery(uploadLifecycle?.fileId ?? '');
+ }
+ }
+
/* Process files */
const processedUploads: ProcessedUpload[] = [];
for (const [fileIndex, originalFile] of acceptedFileList.entries()) {
- const file_id =
- fileIndex === 0 && uploadLifecycle?.fileId != null && uploadLifecycle.fileId !== ''
- ? uploadLifecycle.fileId
- : v4();
+ if (uploadLifecycle?.shouldCommit?.() === false) break;
+ const usesAssignedId = fileIndex === 0 && includesAssignedFile;
+ const file_id = usesAssignedId && uploadLifecycle?.fileId ? uploadLifecycle.fileId : v4();
+ const recovery: UploadRecovery =
+ usesAssignedId && assignedRecovery
+ ? assignedRecovery
+ : { ...uploadLifecycle, status: 'staged' };
+ uploadErrorCallbacks.set(file_id, recovery);
+ let currentPreview: string | undefined;
+ let ownedFile = originalFile;
+ recovery.dispose = () => {
+ recovery.dispose = undefined;
+ const ownsEntry = (currentFiles: Map<string, ExtendedFile>) => {
+ const owner = uploadErrorCallbacks.get(file_id);
+ const entry = currentFiles.get(file_id);
+ return (
+ (owner == null || owner === recovery) &&
+ entry != null &&
+ entry.progress < 1 &&
+ (entry.file === originalFile || entry.file === ownedFile)
+ );
+ };
+ const owner = uploadErrorCallbacks.get(file_id);
+ if (owner == null || owner === recovery) {
+ deleteFileById(file_id, ownsEntry);
+ removePreviewEntry(file_id);
+ uploadScope.recent.delete(file_id);
+ if (ownsEntry(filesRef.current)) {
+ const remaining = new Map(filesRef.current);
+ remaining.delete(file_id);
+ filesRef.current = remaining;
+ }
+ }
+ clearUploadTimer(file_id);
+ if (currentPreview) URL.revokeObjectURL(currentPreview);
+ };
try {
// Create initial preview with original file
const initialPreview = URL.createObjectURL(originalFile);
+ currentPreview = initialPreview;
cachePreview(file_id, initialPreview);
// Create initial ExtendedFile to show immediately
@@ -599,7 +834,7 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
}
// Add file immediately to show in UI
- addFile(initialExtendedFile);
+ addFile(initialExtendedFile, recovery.isCurrent);
const originalFileName = originalFile.name.toLowerCase();
@@ -621,15 +856,20 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
? await importWithRecovery(() => import('~/utils/heicConverter')).then(
({ processFileForUpload }) =>
processFileForUpload(originalFile, 0.9, (conversionProgress) => {
+ if (!canStageUpload(file_id, recovery)) return;
const adjustedProgress = 0.1 + conversionProgress * 0.4;
- replaceFile({
- ...initialExtendedFile,
- progress: adjustedProgress,
- });
+ replaceFile(
+ {
+ ...initialExtendedFile,
+ progress: adjustedProgress,
+ },
+ recovery.isCurrent,
+ );
}),
)
: originalFile;
+ if (!canStageUpload(file_id, recovery)) continue;
let finalProcessedFile = heicProcessedFile;
let resizeDetails: ProcessedUpload['resizeDetails'];
@@ -644,17 +884,21 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
resizeDetails = { originalSize, newSize, compressionRatio };
}
} catch (resizeError) {
+ if (!canStageUpload(file_id, recovery)) continue;
console.warn('Image resize failed, using original:', resizeError);
// Continue with HEIC processed file if resizing fails
}
}
+ if (!canStageUpload(file_id, recovery)) continue;
// If file was processed (HEIC converted or resized), update with new file and preview
if (finalProcessedFile !== originalFile) {
URL.revokeObjectURL(initialPreview); // Clean up original preview
const newPreview = URL.createObjectURL(finalProcessedFile);
+ currentPreview = newPreview;
cachePreview(file_id, newPreview);
+ ownedFile = finalProcessedFile;
const updatedExtendedFile: ExtendedFile = {
...initialExtendedFile,
file: finalProcessedFile,
@@ -664,9 +908,10 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
size: finalProcessedFile.size,
};
- replaceFile(updatedExtendedFile);
+ replaceFile(updatedExtendedFile, recovery.isCurrent);
processedUploads.push({
extendedFile: updatedExtendedFile,
+ recovery,
preview: newPreview,
resizeDetails,
});
@@ -676,15 +921,17 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
...initialExtendedFile,
progress: 0.2,
};
- replaceFile(readyExtendedFile);
+ replaceFile(readyExtendedFile, recovery.isCurrent);
processedUploads.push({
extendedFile: readyExtendedFile,
+ recovery,
preview: initialPreview,
resizeDetails,
});
}
} catch (error) {
- deleteFileById(file_id);
+ if (recovery.status === 'canceled') continue;
+ takeUploadRecovery(file_id)?.dispose?.();
console.log('file handling error', error);
if (error instanceof Error && error.message.includes('HEIC')) {
setError('com_error_heic_conversion');
@@ -694,20 +941,23 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
}
}
- const discardProcessedUpload = ({ extendedFile, preview }: ProcessedUpload) => {
- deleteFileById(extendedFile.file_id);
- removePreviewEntry(extendedFile.file_id);
- URL.revokeObjectURL(preview);
+ const discardProcessedUpload = ({ extendedFile, recovery }: ProcessedUpload) => {
+ if (uploadErrorCallbacks.get(extendedFile.file_id) === recovery) {
+ takeUploadRecovery(extendedFile.file_id);
+ }
+ recovery.dispose?.();
};
const discardProcessedUploads = () => {
for (const upload of processedUploads) {
discardProcessedUpload(upload);
}
- filesRef.current = existingFiles;
};
- const processedFileList = processedUploads.map(({ extendedFile }) => extendedFile.file as File);
+ const eligibleUploads = processedUploads.filter(({ extendedFile, recovery }) =>
+ canStageUpload(extendedFile.file_id, recovery),
+ );
+ const processedFileList = eligibleUploads.map(({ extendedFile }) => extendedFile.file as File);
let batch: UploadPartition;
let acceptedUploads: ProcessedUpload[];
@@ -717,7 +967,7 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
fileList: processedFileList,
endpointFileConfig,
});
- acceptedUploads = batch.keptIndices.map((index) => processedUploads[index]);
+ acceptedUploads = batch.keptIndices.map((index) => eligibleUploads[index]);
const acceptedFiles = acceptedUploads.map(({ extendedFile }) => extendedFile.file as File);
/** `fileLimit` and `totalSizeLimit` describe the batch rather than any one file, so both are
* applied to whatever survived the per-file partition above. */
@@ -766,7 +1016,7 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
}
for (const { index } of batch.skipped) {
- discardProcessedUpload(processedUploads[index]);
+ discardProcessedUpload(eligibleUploads[index]);
}
/** Held until the batch is known to be uploading: a selection that is rejected in full reports
* itself through the batch-level errors alone, never alongside a partial-success notice. */
@@ -781,7 +1031,7 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
}
filesRef.current = filesWithProcessedUploads;
- for (const { extendedFile, preview, resizeDetails } of acceptedUploads) {
+ for (const { extendedFile, preview, resizeDetails, recovery } of acceptedUploads) {
if (resizeDetails) {
const { originalSize, newSize, compressionRatio } = resizeDetails;
showToast({
@@ -796,11 +1046,11 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
}
if (extendedFile.file?.type.startsWith('image/') === true) {
- loadImage(extendedFile, preview, uploadLifecycle);
+ loadImage(extendedFile, preview, recovery);
continue;
}
- await startUpload(extendedFile, uploadLifecycle);
+ await startUpload(extendedFile, recovery);
}
return acceptedUploads.length > 0;
@@ -811,12 +1061,23 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
_toolResource?: string,
uploadLifecycle?: UploadLifecycleCallbacks,
): Promise<boolean> => {
+ const lifecycle = captureUploadLifecycle(_toolResource, uploadLifecycle);
/** `FileList` is live: copy it before yielding, as callers reset the input synchronously */
const fileList = Array.from(_files);
- const assignedFileId = uploadLifecycle?.fileId;
- if (assignedFileId) {
- uploadErrorCallbacks.set(assignedFileId, uploadLifecycle);
+ const assignedFileId = lifecycle?.fileId;
+ const assignedRecovery: UploadRecovery | undefined =
+ assignedFileId && lifecycle ? { ...lifecycle, status: 'staged' } : undefined;
+ if (assignedFileId && assignedRecovery) {
+ if (uploadErrorCallbacks.has(assignedFileId)) {
+ clearUploadRecovery(assignedFileId);
+ }
+ uploadErrorCallbacks.set(assignedFileId, assignedRecovery);
}
+ const releaseAssignedRecovery = () => {
+ if (assignedFileId && uploadErrorCallbacks.get(assignedFileId) === assignedRecovery) {
+ takeUploadRecovery(assignedFileId)?.dispose?.();
+ }
+ };
/** Started before queueing so every waiting batch shares one bounded config window */
const configReady = isConfigPending ? waitForConfig() : undefined;
const previousProcessing = uploadScope.queue;
@@ -828,22 +1089,18 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
try {
await previousProcessing;
await configReady;
- if (uploadLifecycle?.shouldCommit?.() === false) {
- if (assignedFileId) {
- takeUploadRecovery(assignedFileId);
- }
+ if (lifecycle?.shouldCommit?.() === false) {
+ releaseAssignedRecovery();
setFilesLoading(false);
return false;
}
- const accepted = await processFiles(fileList, _toolResource, uploadLifecycle);
- if (!accepted && assignedFileId) {
- takeUploadRecovery(assignedFileId);
+ const accepted = await processFiles(fileList, _toolResource, lifecycle, assignedRecovery);
+ if (!accepted) {
+ releaseAssignedRecovery();
}
return accepted;
} catch (error) {
- if (assignedFileId) {
- takeUploadRecovery(assignedFileId);
- }
+ releaseAssignedRecovery();
throw error;
} finally {
releaseProcessing();
@@ -878,6 +1135,7 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Fil
return {
handleFileChange,
handleFiles,
+ captureUploadLifecycle,
abortUpload,
setFiles,
files,
@@ -890,9 +1148,10 @@ export const useFileHandlingNoChatContext = (
) => useFileHandlingCore(params, fileState);
const useFileHandling = (params?: UseFileHandling) => {
- const { files, setFiles, setFilesLoading, conversation } = useChatContext();
+ const { files, setFiles, setFilesLoading, conversation, index } = useChatContext();
return useFileHandlingCore(params, {
+ index,
files,
setFiles,
conversation,
diff --git a/client/src/hooks/Files/useSharePointFileHandling.ts b/client/src/hooks/Files/useSharePointFileHandling.ts
index a04ef0104b..e90ac15ec1 100644
--- a/client/src/hooks/Files/useSharePointFileHandling.ts
+++ b/client/src/hooks/Files/useSharePointFileHandling.ts
@@ -24,13 +24,9 @@ interface UseSharePointFileHandlingReturn {
export default function useSharePointFileHandling(
props?: UseSharePointFileHandlingProps,
): UseSharePointFileHandlingReturn {
- const { handleFiles } = useFileHandling(props);
+ const { handleFiles, captureUploadLifecycle } = useFileHandling(props);
const { downloadSharePointFiles, isDownloading, downloadProgress, error } = useSharePointDownload(
{
- onFilesDownloaded: async (downloadedFiles: File[]) => {
- const fileArray = Array.from(downloadedFiles);
- await handleFiles(fileArray, props?.toolResource);
- },
onError: (error) => {
console.error('SharePoint download failed:', error);
},
@@ -39,14 +35,17 @@ export default function useSharePointFileHandling(
const handleSharePointFiles = useCallback(
async (sharePointFiles: SharePointFile[]) => {
+ const toolResource = props?.toolResource;
+ const lifecycle = captureUploadLifecycle(toolResource);
try {
- await downloadSharePointFiles(sharePointFiles);
+ const downloadedFiles = await downloadSharePointFiles(sharePointFiles);
+ await handleFiles(downloadedFiles, toolResource, lifecycle);
} catch (error) {
console.error('SharePoint file handling error:', error);
throw error;
}
},
- [downloadSharePointFiles],
+ [downloadSharePointFiles, handleFiles, captureUploadLifecycle, props?.toolResource],
);
return {
@@ -61,14 +60,10 @@ export function useSharePointFileHandlingNoChatContext(
props: UseSharePointFileHandlingProps | undefined,
fileState: FileHandlingState,
): UseSharePointFileHandlingReturn {
- const { handleFiles } = useFileHandlingNoChatContext(props, fileState);
+ const { handleFiles, captureUploadLifecycle } = useFileHandlingNoChatContext(props, fileState);
const { downloadSharePointFiles, isDownloading, downloadProgress, error } = useSharePointDownload(
{
- onFilesDownloaded: async (downloadedFiles: File[]) => {
- const fileArray = Array.from(downloadedFiles);
- await handleFiles(fileArray, props?.toolResource);
- },
onError: (error) => {
console.error('SharePoint download failed:', error);
},
@@ -77,14 +72,17 @@ export function useSharePointFileHandlingNoChatContext(
const handleSharePointFiles = useCallback(
async (sharePointFiles: SharePointFile[]) => {
+ const toolResource = props?.toolResource;
+ const lifecycle = captureUploadLifecycle(toolResource);
try {
- await downloadSharePointFiles(sharePointFiles);
+ const downloadedFiles = await downloadSharePointFiles(sharePointFiles);
+ await handleFiles(downloadedFiles, toolResource, lifecycle);
} catch (error) {
console.error('SharePoint file handling error:', error);
throw error;
}
},
- [downloadSharePointFiles],
+ [downloadSharePointFiles, handleFiles, captureUploadLifecycle, props?.toolResource],
);
return {
diff --git a/client/src/hooks/Files/useUpdateFiles.ts b/client/src/hooks/Files/useUpdateFiles.ts
index d33ad527a1..df271935fd 100644
--- a/client/src/hooks/Files/useUpdateFiles.ts
+++ b/client/src/hooks/Files/useUpdateFiles.ts
@@ -11,9 +11,11 @@ export default function useUpdateFiles(setFiles: FileSetter) {
* outranks any earlier consumption of the same id: re-attaching a library
* file reuses its server id, so the mark is dropped rather than obeyed.
*/
- const addFile = (newFile: ExtendedFile) => {
+ const addFile = (newFile: ExtendedFile, shouldCommit?: () => boolean) => {
+ if (shouldCommit?.() === false) return;
releaseComposerFile(newFile.file_id);
setFiles((currentFiles) => {
+ if (shouldCommit?.() === false) return currentFiles;
const updatedFiles = new Map(currentFiles);
updatedFiles.set(newFile.file_id, newFile);
return updatedFiles;
@@ -27,19 +29,26 @@ export default function useUpdateFiles(setFiles: FileSetter) {
* it back would resurrect a file the message already owns, so a consumed id
* is dropped here instead of re-entering the composer.
*/
- const replaceFile = (newFile: ExtendedFile) => {
+ const replaceFile = (newFile: ExtendedFile, shouldCommit?: () => boolean) => {
if (isComposerFileTaken(newFile.file_id)) {
return;
}
setFiles((currentFiles) => {
+ if (shouldCommit?.() === false) return currentFiles;
const updatedFiles = new Map(currentFiles);
updatedFiles.set(newFile.file_id, newFile);
return updatedFiles;
});
};
- const updateFileById = (fileId: string, updates: Partial<ExtendedFile>, isEntityFile = false) => {
+ const updateFileById = (
+ fileId: string,
+ updates: Partial<ExtendedFile>,
+ isEntityFile = false,
+ shouldCommit?: () => boolean,
+ ) => {
setFiles((currentFiles) => {
+ if (shouldCommit?.() === false) return currentFiles;
if (!currentFiles.has(fileId)) {
console.warn(`File with id ${fileId} not found.`);
return currentFiles;
@@ -62,8 +71,12 @@ export default function useUpdateFiles(setFiles: FileSetter) {
});
};
- const deleteFileById = (fileId: string) => {
+ const deleteFileById = (
+ fileId: string,
+ shouldCommit?: (currentFiles: Map<string, ExtendedFile>) => boolean,
+ ) => {
setFiles((currentFiles) => {
+ if (shouldCommit?.(currentFiles) === false) return currentFiles;
const updatedFiles = new Map(currentFiles);
if (updatedFiles.has(fileId)) {
updatedFiles.delete(fileId);
diff --git a/client/src/hooks/Input/__tests__/useAttachItems.spec.tsx b/client/src/hooks/Input/__tests__/useAttachItems.spec.tsx
index 7b22b6877b..ae43125efb 100644
--- a/client/src/hooks/Input/__tests__/useAttachItems.spec.tsx
+++ b/client/src/hooks/Input/__tests__/useAttachItems.spec.tsx
@@ -1,8 +1,18 @@
import React from 'react';
-import { RecoilRoot } from 'recoil';
+import { RecoilRoot, useRecoilValue } from 'recoil';
import { act, renderHook } from '@testing-library/react';
-import { Tools, EToolResources, EModelEndpoint } from 'librechat-data-provider';
+import {
+ Tools,
+ Permissions,
+ roleDefaults,
+ PermissionTypes,
+ EToolResources,
+ EModelEndpoint,
+} from 'librechat-data-provider';
import type { TConversation, EndpointFileConfig } from 'librechat-data-provider';
+import type { TAuthContext } from '~/common';
+import { AuthContext } from '~/hooks/AuthContext';
+import { ephemeralAgentByConvoId } from '~/store';
import useAttachItems from '../useAttachItems';
/**
@@ -13,11 +23,17 @@ import useAttachItems from '../useAttachItems';
*/
jest.mock('~/hooks', () => ({
+ useHasAccess: jest.fn(jest.requireActual('~/hooks/Roles/useHasAccess').default),
useAgentToolPermissions: jest.fn(),
useAgentCapabilities: jest.fn(),
useGetAgentsConfig: jest.fn(),
}));
+jest.mock('~/hooks/AuthContext', () => {
+ const { createContext } = jest.requireActual('react');
+ return { AuthContext: createContext(undefined) };
+});
+
jest.mock('~/hooks/useLocalize', () => ({
__esModule: true,
default: () => (key: string) => key,
@@ -31,11 +47,11 @@ jest.mock('~/hooks/Files', () => ({
jest.mock('~/hooks/Files/useSharePointFileHandling', () => ({
__esModule: true,
default: jest.fn(),
- useSharePointFileHandlingNoChatContext: () => ({
- handleSharePointFiles: jest.fn(),
+ useSharePointFileHandlingNoChatContext: jest.fn(() => ({
+ handleSharePointFiles: jest.fn().mockResolvedValue(undefined),
isProcessing: false,
downloadProgress: undefined,
- }),
+ })),
}));
jest.mock('~/data-provider', () => ({
@@ -62,8 +78,51 @@ interface Options {
fileSearchEnabled?: boolean;
codeEnabled?: boolean;
sharePointEnabled?: boolean;
+ codeEnvironmentId?: string;
+ statefulCodeSessionsAllowedByAgent?: boolean;
+ authContext?: TAuthContext;
+ initialFileSearch?: boolean;
+}
+
+function accessContext(canUseFileSearch?: boolean): TAuthContext {
+ return {
+ user: {
+ id: 'user-1',
+ username: 'reader',
+ email: '[email protected]',
+ name: 'Reader',
+ avatar: '',
+ role: 'reader',
+ provider: 'local',
+ createdAt: '2026-10-18T00:00:00Z',
+ updatedAt: '2026-10-18T00:00:00Z',
+ },
+ roles:
+ canUseFileSearch === undefined
+ ? undefined
+ : {
+ reader: {
+ ...roleDefaults.USER,
+ name: 'reader',
+ permissions: {
+ ...roleDefaults.USER.permissions,
+ [PermissionTypes.FILE_SEARCH]: { [Permissions.USE]: canUseFileSearch },
+ },
+ },
+ },
+ token: undefined,
+ isAuthenticated: true,
+ isAuthReady: true,
+ error: undefined,
+ login: jest.fn(),
+ logout: jest.fn(),
+ completeAuthentication: jest.fn(),
+ setError: jest.fn(),
+ };
}
+const allowedAccess = accessContext(true);
+
/** Row ids, which are what the palette keys and folds on. */
function renderEntries(options: Options = {}): string[] {
const {
@@ -104,7 +163,11 @@ function renderEntries(options: Options = {}): string[] {
setFilesLoading: jest.fn(),
}),
{
- wrapper: ({ children }: { children: React.ReactNode }) => <RecoilRoot>{children}</RecoilRoot>,
+ wrapper: ({ children }: { children: React.ReactNode }) => (
+ <AuthContext.Provider value={options.authContext ?? allowedAccess}>
+ <RecoilRoot>{children}</RecoilRoot>
+ </AuthContext.Provider>
+ ),
},
);
@@ -115,18 +178,25 @@ const allCapabilities = { contextEnabled: true, fileSearchEnabled: true, codeEna
/** The hook, not just its entry labels, so a destination can be chosen. */
function renderAttach(options: Options = {}) {
- mockUseAgentToolPermissions.mockReturnValue({ tools: options.tools, provider: options.provider });
+ mockUseAgentToolPermissions.mockReturnValue({
+ tools: options.tools,
+ provider: options.provider,
+ codeEnvironmentId: options.codeEnvironmentId,
+ statefulCodeSessionsAllowedByAgent: options.statefulCodeSessionsAllowedByAgent,
+ });
mockUseAgentCapabilities.mockReturnValue({
contextEnabled: options.contextEnabled ?? true,
fileSearchEnabled: options.fileSearchEnabled ?? true,
codeEnabled: options.codeEnabled ?? true,
});
mockUseGetAgentsConfig.mockReturnValue({ agentsConfig: { capabilities: [] } });
- mockUseGetStartupConfig.mockReturnValue({ data: { sharePointFilePickerEnabled: false } });
+ mockUseGetStartupConfig.mockReturnValue({
+ data: { sharePointFilePickerEnabled: options.sharePointEnabled ?? false },
+ });
return renderHook(
- () =>
- useAttachItems({
+ () => {
+ const attach = useAttachItems({
agentId: options.agentId ?? null,
endpoint: options.endpoint ?? null,
endpointType: options.endpointType,
@@ -138,9 +208,24 @@ function renderAttach(options: Options = {}) {
files: new Map(),
setFiles: jest.fn(),
setFilesLoading: jest.fn(),
- }),
+ });
+ const ephemeralAgent = useRecoilValue(ephemeralAgentByConvoId('convo-1'));
+ return { ...attach, ephemeralAgent };
+ },
{
- wrapper: ({ children }: { children: React.ReactNode }) => <RecoilRoot>{children}</RecoilRoot>,
+ wrapper: ({ children }: { children: React.ReactNode }) => (
+ <AuthContext.Provider value={options.authContext ?? allowedAccess}>
+ <RecoilRoot
+ initializeState={({ set }) => {
+ if (options.initialFileSearch) {
+ set(ephemeralAgentByConvoId('convo-1'), { file_search: true });
+ }
+ }}
+ >
+ {children}
+ </RecoilRoot>
+ </AuthContext.Provider>
+ ),
},
);
}
@@ -213,7 +298,7 @@ describe('useAttachItems', () => {
it('reads a provider whatever its casing, which OpenRouter arrives in', () => {
expect(renderEntries({ provider: 'OpenRouter' })).toContain('local:provider');
});
- it('offers local and SharePoint sources without destination choices in unified mode', () => {
+ it('keeps implicit upload first and restores only explicit File Search in unified mode', () => {
expect(
renderEntries({
isUnifiedMode: true,
@@ -222,8 +307,197 @@ describe('useAttachItems', () => {
fileSearchEnabled: true,
codeEnabled: true,
}),
+ ).toEqual([
+ 'local:unified',
+ 'local:file_search',
+ 'sharepoint:unified',
+ 'sharepoint:file_search',
+ ]);
+ });
+ });
+
+ describe.each([false, true])('File Search role access (unified=%s)', (isUnifiedMode) => {
+ it.each([null, SAVED_AGENT])(
+ 'fails closed while roles load and respects permission changes (agent=%s)',
+ (agentId) => {
+ const options: Options = {
+ ...allCapabilities,
+ isUnifiedMode,
+ agentId,
+ tools: [Tools.file_search, Tools.execute_code],
+ sharePointEnabled: true,
+ authContext: accessContext(),
+ };
+ const { result, rerender } = renderAttach(options);
+ const ids = () => result.current.entries.map((entry) => entry.id);
+ const fileSearchIds = ['local:file_search', 'sharepoint:file_search'];
+
+ for (const id of fileSearchIds) {
+ expect(ids()).not.toContain(id);
+ }
+
+ options.authContext = accessContext(true);
+ rerender();
+ expect(ids()).toEqual(expect.arrayContaining(fileSearchIds));
+
+ options.authContext = accessContext(false);
+ rerender();
+ for (const id of fileSearchIds) {
+ expect(ids()).not.toContain(id);
+ }
+ expect(ids()).toEqual(
+ expect.arrayContaining([
+ `local:${isUnifiedMode ? 'unified' : 'image'}`,
+ `sharepoint:${isUnifiedMode ? 'unified' : 'image'}`,
+ ]),
+ );
+ expect(ids().includes('local:execute_code')).toBe(!isUnifiedMode);
+ expect(ids().includes('sharepoint:execute_code')).toBe(!isUnifiedMode);
+ },
+ );
+ });
+
+ describe.each([false, true])('cancelled File Search selection (preenabled=%s)', (enabled) => {
+ it.each(['local', 'sharepoint'])('preserves the prior tool state for %s', (source) => {
+ const { result } = renderAttach({
+ isUnifiedMode: true,
+ sharePointEnabled: true,
+ initialFileSearch: enabled,
+ });
+ act(() => {
+ result.current.entries.find((entry) => entry.id === `${source}:file_search`)?.onSelect();
+ });
+ if (source === 'sharepoint') {
+ act(() => result.current.setIsSharePointDialogOpen(false));
+ }
+ expect(result.current.ephemeralAgent?.file_search ?? false).toBe(enabled);
+ expect(mockHandleFileChange).not.toHaveBeenCalled();
+ });
+ });
+
+ describe('unified destinations', () => {
+ it('keeps both sources implicit when File Search is disabled, even with code enabled', () => {
+ expect(
+ renderEntries({ isUnifiedMode: true, sharePointEnabled: true, codeEnabled: true }),
).toEqual(['local:unified', 'sharepoint:unified']);
});
+
+ it('offers File Search only when a saved agent allows it', () => {
+ expect(
+ renderEntries({
+ ...allCapabilities,
+ isUnifiedMode: true,
+ agentId: SAVED_AGENT,
+ tools: [Tools.file_search],
+ }),
+ ).toEqual(['local:unified', 'local:file_search']);
+ });
+
+ it('does not offer explicit destinations for an agent with only code enabled', () => {
+ expect(
+ renderEntries({
+ ...allCapabilities,
+ isUnifiedMode: true,
+ sharePointEnabled: true,
+ agentId: SAVED_AGENT,
+ tools: [Tools.execute_code],
+ }),
+ ).toEqual(['local:unified', 'sharepoint:unified']);
+ });
+
+ it('keeps both sources implicit for the selected stateful code environment', () => {
+ const { result } = renderAttach({
+ isUnifiedMode: true,
+ sharePointEnabled: true,
+ agentId: SAVED_AGENT,
+ tools: [Tools.file_search, Tools.execute_code],
+ codeEnvironmentId: 'stateful-only',
+ statefulCodeSessionsAllowedByAgent: true,
+ });
+ expect(result.current.entries.map((entry) => entry.id)).toEqual([
+ 'local:unified',
+ 'local:file_search',
+ 'sharepoint:unified',
+ 'sharepoint:file_search',
+ ]);
+ const input = document.createElement('input');
+ Object.defineProperty(result.current.inputRef, 'current', { value: input, writable: true });
+
+ act(() => {
+ result.current.entries.find((entry) => entry.id === 'local:unified')?.onSelect();
+ });
+ act(() => pickFile(input, result.current.onFileChange));
+ expect(mockHandleFileChange).toHaveBeenLastCalledWith(expect.anything(), undefined);
+
+ act(() => {
+ result.current.entries.find((entry) => entry.id === 'sharepoint:unified')?.onSelect();
+ });
+ const sharePoint = jest.requireMock('~/hooks/Files/useSharePointFileHandling');
+ expect(result.current.isSharePointDialogOpen).toBe(true);
+ expect(sharePoint.useSharePointFileHandlingNoChatContext).toHaveBeenLastCalledWith(
+ { toolResource: undefined },
+ expect.anything(),
+ );
+ });
+
+ it.each([EModelEndpoint.assistants, EModelEndpoint.azureAssistants])(
+ 'keeps unified %s uploads on their existing source rows',
+ (endpoint) => {
+ expect(
+ renderEntries({
+ ...allCapabilities,
+ isUnifiedMode: true,
+ sharePointEnabled: true,
+ endpoint,
+ }),
+ ).toEqual(['local:unified', 'sharepoint:unified']);
+ },
+ );
+
+ it('labels and folds SharePoint tool destinations separately from local uploads', () => {
+ const { result } = renderAttach({ isUnifiedMode: true, sharePointEnabled: true });
+ expect(
+ result.current.entries.filter((entry) => entry.primary).map((entry) => entry.id),
+ ).toEqual(['local:unified', 'sharepoint:unified']);
+ expect(
+ result.current.entries.find((entry) => entry.id === 'sharepoint:file_search'),
+ ).toMatchObject({ label: 'com_ui_upload_file_search (com_files_upload_sharepoint)' });
+ });
+
+ it('carries File Search through the picker without enabling it and resets the next upload', () => {
+ const { result } = renderAttach({ isUnifiedMode: true });
+ const input = document.createElement('input');
+ Object.defineProperty(result.current.inputRef, 'current', { value: input, writable: true });
+
+ act(() => {
+ result.current.entries.find((entry) => entry.id === 'local:file_search')?.onSelect();
+ });
+ act(() => pickFile(input, result.current.onFileChange));
+ expect(mockHandleFileChange).toHaveBeenLastCalledWith(
+ expect.anything(),
+ EToolResources.file_search,
+ );
+ expect(result.current.ephemeralAgent?.[EToolResources.file_search]).not.toBe(true);
+
+ act(() => {
+ result.current.entries.find((entry) => entry.id === 'local:unified')?.onSelect();
+ });
+ act(() => pickFile(input, result.current.onFileChange));
+ expect(mockHandleFileChange).toHaveBeenLastCalledWith(expect.anything(), undefined);
+ });
+
+ it('passes a SharePoint File Search choice to its upload handler', () => {
+ const { result } = renderAttach({ isUnifiedMode: true, sharePointEnabled: true });
+ const sharePoint = jest.requireMock('~/hooks/Files/useSharePointFileHandling');
+ act(() => {
+ result.current.entries.find((entry) => entry.id === 'sharepoint:file_search')?.onSelect();
+ });
+ expect(result.current.isSharePointDialogOpen).toBe(true);
+ expect(sharePoint.useSharePointFileHandlingNoChatContext).toHaveBeenLastCalledWith(
+ { toolResource: EToolResources.file_search },
+ expect.anything(),
+ );
+ });
});
describe('destinations behind an agent capability', () => {
@@ -286,6 +560,49 @@ describe('useAttachItems', () => {
});
});
+ describe('legacy code destinations', () => {
+ it('keeps explicit local and SharePoint code uploads in nonunified mode', () => {
+ const { result } = renderAttach({ isUnifiedMode: false, sharePointEnabled: true });
+ expect(result.current.entries.map((entry) => entry.id)).toEqual(
+ expect.arrayContaining(['local:execute_code', 'sharepoint:execute_code']),
+ );
+ const input = document.createElement('input');
+ Object.defineProperty(result.current.inputRef, 'current', { value: input, writable: true });
+
+ act(() => {
+ result.current.entries.find((entry) => entry.id === 'local:execute_code')?.onSelect();
+ });
+ act(() => pickFile(input, result.current.onFileChange));
+ expect(mockHandleFileChange).toHaveBeenLastCalledWith(
+ expect.anything(),
+ EToolResources.execute_code,
+ );
+
+ act(() => {
+ result.current.entries.find((entry) => entry.id === 'sharepoint:execute_code')?.onSelect();
+ });
+ const sharePoint = jest.requireMock('~/hooks/Files/useSharePointFileHandling');
+ expect(sharePoint.useSharePointFileHandlingNoChatContext).toHaveBeenLastCalledWith(
+ { toolResource: EToolResources.execute_code },
+ expect.anything(),
+ );
+ });
+
+ it.each([
+ { codeEnabled: false, tools: [Tools.execute_code] },
+ { codeEnabled: true, tools: [Tools.file_search] },
+ ])('keeps legacy code capability and agent gates (%j)', (options) => {
+ const ids = renderEntries({
+ ...options,
+ isUnifiedMode: false,
+ sharePointEnabled: true,
+ agentId: SAVED_AGENT,
+ });
+ expect(ids).not.toContain('local:execute_code');
+ expect(ids).not.toContain('sharepoint:execute_code');
+ });
+ });
+
describe('SharePoint', () => {
it('mirrors every local destination when it is enabled', () => {
expect(renderEntries({ ...allCapabilities, sharePointEnabled: true })).toEqual([
@@ -330,7 +647,9 @@ describe('useAttachItems', () => {
}),
{
wrapper: ({ children }: { children: React.ReactNode }) => (
- <RecoilRoot>{children}</RecoilRoot>
+ <AuthContext.Provider value={allowedAccess}>
+ <RecoilRoot>{children}</RecoilRoot>
+ </AuthContext.Provider>
),
},
);
diff --git a/client/src/hooks/Input/useAttachItems.tsx b/client/src/hooks/Input/useAttachItems.tsx
index 860ba6b6da..6b2ce45401 100644
--- a/client/src/hooks/Input/useAttachItems.tsx
+++ b/client/src/hooks/Input/useAttachItems.tsx
@@ -10,6 +10,8 @@ import {
} from 'lucide-react';
import {
Providers,
+ Permissions,
+ PermissionTypes,
EToolResources,
EModelEndpoint,
getConfiguredMimeAccept,
@@ -27,8 +29,13 @@ import type {
} from 'librechat-data-provider';
import type { SharePointFile } from '~/data-provider/Files/sharepoint';
import type { ExtendedFile, FileSetter } from '~/common';
+import {
+ useHasAccess,
+ useAgentToolPermissions,
+ useAgentCapabilities,
+ useGetAgentsConfig,
+} from '~/hooks';
import { useSharePointFileHandlingNoChatContext } from '~/hooks/Files/useSharePointFileHandling';
-import { useAgentToolPermissions, useAgentCapabilities, useGetAgentsConfig } from '~/hooks';
import { useFileHandlingNoChatContext } from '~/hooks/Files';
import { useGetStartupConfig } from '~/data-provider';
import { getUploadToolAllowances } from '~/utils';
@@ -88,11 +95,12 @@ export interface UseAttachItems {
}
interface UseAttachItemsParams {
+ index?: number;
agentId?: string | null;
endpoint?: string | null;
endpointType?: EModelEndpoint | string;
endpointFileConfig?: EndpointFileConfig;
- /** Resolved unified mode hides tool destinations behind the implicit uploader. */
+ /** Unified mode keeps implicit upload first, alongside explicit tool destinations. */
isUnifiedMode?: boolean;
useResponsesApi?: boolean;
conversationId: string;
@@ -112,6 +120,7 @@ interface UseAttachItemsParams {
* popover so selecting a file does not race the popover unmounting.
*/
export default function useAttachItems({
+ index = 0,
agentId,
endpoint,
endpointType,
@@ -136,6 +145,7 @@ export default function useAttachItems({
const [, setEphemeralAgent] = useRecoilState(ephemeralAgentByConvoId(conversationId));
const { handleFileChange } = useFileHandlingNoChatContext(undefined, {
+ index,
files,
setFiles,
setFilesLoading,
@@ -144,7 +154,7 @@ export default function useAttachItems({
const { handleSharePointFiles, isProcessing, downloadProgress } =
useSharePointFileHandlingNoChatContext(
{ toolResource: sharePointResource },
- { files, setFiles, setFilesLoading, conversation },
+ { index, files, setFiles, setFilesLoading, conversation },
);
const ephemeralAgent = useRecoilValue(ephemeralAgentByConvoId(conversationId));
@@ -162,6 +172,10 @@ export default function useAttachItems({
const { contextEnabled, fileSearchEnabled, codeEnabled } = useAgentCapabilities(
agentsConfig?.capabilities ?? defaultAgentCapabilities,
);
+ const canUseFileSearch = useHasAccess({
+ permissionType: PermissionTypes.FILE_SEARCH,
+ permission: Permissions.USE,
+ });
const { tools, provider } = useAgentToolPermissions(agentId, ephemeralAgent);
/* The same allowances the drag-and-drop router resolves, so a file reaches
the same destinations whether it is dropped on the composer or picked
@@ -211,9 +225,8 @@ export default function useAttachItems({
const build = (onAction: (fileType?: FileUploadType) => void, prefix: string) => {
const items: AttachEntry[] = [];
- /* Unified mode keeps the destination implicit and exposes only the
- available sources, so the palette never routes a source through a
- legacy tool resource. */
+ /* Keep implicit attachment as the default; tool destinations below are
+ deliberate opt-ins, not a reason to embed every upload. */
if (isUnifiedMode) {
items.push({
id: `${prefix}:unified`,
@@ -237,106 +250,112 @@ export default function useAttachItems({
}
},
});
- return items;
- }
- /* Assistants own their own file handling: whatever the assistant is
- configured to accept goes up unfiltered, and none of the tool
- destinations below apply. Scoping this to the image capability, as the
- provider check would, silently dropped PDF support. */
- if (isAssistantsEndpoint(endpoint)) {
- items.push({
- id: `${prefix}:assistants`,
- label: localize('com_sidepanel_attach_files'),
- primary: true,
- icon: <FileImageIcon className="icon-md" aria-hidden="true" />,
- onSelect: () => {
- setToolResource(undefined);
- onAction();
- },
- });
- return items;
- }
+ if (isAssistantsEndpoint(endpoint)) {
+ return items;
+ }
+ } else {
+ /* Assistants own their own file handling: whatever the assistant is
+ configured to accept goes up unfiltered, and none of the tool
+ destinations below apply. Scoping this to the image capability, as the
+ provider check would, silently dropped PDF support. */
+ if (isAssistantsEndpoint(endpoint)) {
+ items.push({
+ id: `${prefix}:assistants`,
+ label: localize('com_sidepanel_attach_files'),
+ primary: true,
+ icon: <FileImageIcon className="icon-md" aria-hidden="true" />,
+ onSelect: () => {
+ setToolResource(undefined);
+ onAction();
+ },
+ });
+ return items;
+ }
- let currentProvider = provider || endpoint;
+ let currentProvider = provider || endpoint;
- // This will be removed in a future PR to formally normalize Providers comparisons to be case insensitive
- if (currentProvider?.toLowerCase() === Providers.OPENROUTER) {
- currentProvider = Providers.OPENROUTER;
- }
+ // This will be removed in a future PR to formally normalize Providers comparisons to be case insensitive
+ if (currentProvider?.toLowerCase() === Providers.OPENROUTER) {
+ currentProvider = Providers.OPENROUTER;
+ }
- const isAzureWithResponsesApi =
- (currentProvider === EModelEndpoint.azureOpenAI ||
- endpointType === EModelEndpoint.azureOpenAI) &&
- useResponsesApi === true;
+ const isAzureWithResponsesApi =
+ (currentProvider === EModelEndpoint.azureOpenAI ||
+ endpointType === EModelEndpoint.azureOpenAI) &&
+ useResponsesApi === true;
- if (
- isDocumentSupportedProvider(endpointType) ||
- isDocumentSupportedProvider(currentProvider) ||
- isAzureWithResponsesApi
- ) {
- items.push({
- id: `${prefix}:provider`,
- label: localize('com_ui_upload_provider'),
- primary: true,
- icon: <FileImageIcon className="icon-md" aria-hidden="true" />,
- onSelect: () => {
- setToolResource(undefined);
- let fileType: Exclude<FileUploadType, 'image' | 'document'> = 'image_document';
- if (currentProvider === Providers.GOOGLE || currentProvider === Providers.OPENROUTER) {
- fileType = 'image_document_video_audio';
- } else if (
- currentProvider === Providers.BEDROCK ||
- endpointType === EModelEndpoint.bedrock
- ) {
- fileType = 'image_document_extended';
- } else if (
- endpointType === EModelEndpoint.custom &&
- isExplicitMimeConfig(endpointFileConfig?.supportedMimeTypes)
- ) {
- fileType = 'image_document_video_audio_configured';
- }
- onAction(fileType);
- },
- });
- } else {
- items.push({
- id: `${prefix}:image`,
- label: localize('com_ui_upload_image_input'),
- primary: true,
- icon: <ImageUpIcon className="icon-md" aria-hidden="true" />,
- onSelect: () => {
- setToolResource(undefined);
- onAction('image');
- },
- });
- }
+ if (
+ isDocumentSupportedProvider(endpointType) ||
+ isDocumentSupportedProvider(currentProvider) ||
+ isAzureWithResponsesApi
+ ) {
+ items.push({
+ id: `${prefix}:provider`,
+ label: localize('com_ui_upload_provider'),
+ primary: true,
+ icon: <FileImageIcon className="icon-md" aria-hidden="true" />,
+ onSelect: () => {
+ setToolResource(undefined);
+ let fileType: Exclude<FileUploadType, 'image' | 'document'> = 'image_document';
+ if (
+ currentProvider === Providers.GOOGLE ||
+ currentProvider === Providers.OPENROUTER
+ ) {
+ fileType = 'image_document_video_audio';
+ } else if (
+ currentProvider === Providers.BEDROCK ||
+ endpointType === EModelEndpoint.bedrock
+ ) {
+ fileType = 'image_document_extended';
+ } else if (
+ endpointType === EModelEndpoint.custom &&
+ isExplicitMimeConfig(endpointFileConfig?.supportedMimeTypes)
+ ) {
+ fileType = 'image_document_video_audio_configured';
+ }
+ onAction(fileType);
+ },
+ });
+ } else {
+ items.push({
+ id: `${prefix}:image`,
+ label: localize('com_ui_upload_image_input'),
+ primary: true,
+ icon: <ImageUpIcon className="icon-md" aria-hidden="true" />,
+ onSelect: () => {
+ setToolResource(undefined);
+ onAction('image');
+ },
+ });
+ }
- if (contextEnabled) {
- items.push({
- id: `${prefix}:context`,
- label: localize('com_ui_upload_ocr_text'),
- icon: <FileType2Icon className="icon-md" aria-hidden="true" />,
- onSelect: () => {
- setToolResource(EToolResources.context);
- onAction();
- },
- });
+ if (contextEnabled) {
+ items.push({
+ id: `${prefix}:context`,
+ label: localize('com_ui_upload_ocr_text'),
+ icon: <FileType2Icon className="icon-md" aria-hidden="true" />,
+ onSelect: () => {
+ setToolResource(EToolResources.context);
+ onAction();
+ },
+ });
+ }
}
- if (fileSearchEnabled && fileSearchAllowedByAgent) {
+ if (fileSearchEnabled && canUseFileSearch && fileSearchAllowedByAgent) {
items.push({
id: `${prefix}:file_search`,
label: localize('com_ui_upload_file_search'),
icon: <FileSearch className="icon-md" aria-hidden="true" />,
onSelect: () => {
setToolResource(EToolResources.file_search);
- setEphemeralAgent((prev) => ({ ...prev, [EToolResources.file_search]: true }));
onAction();
},
});
}
- if (codeEnabled && codeAllowedByAgent) {
+ /* Unified code uploads defer provisioning to the environment selected for the turn. */
+ if (!isUnifiedMode && codeEnabled && codeAllowedByAgent) {
items.push({
id: `${prefix}:execute_code`,
label: localize('com_ui_upload_code_environment'),
@@ -364,9 +383,10 @@ export default function useAttachItems({
/* Legacy mode folds SharePoint behind the local destination; unified
mode keeps both source rows visible in the palette. */
primary: isUnifiedMode ? item.primary : false,
- label: isUnifiedMode
- ? item.label
- : `${item.label} (${localize('com_files_upload_sharepoint')})`,
+ label:
+ isUnifiedMode && item.primary === true
+ ? item.label
+ : `${item.label} (${localize('com_files_upload_sharepoint')})`,
icon: <SharePointIcon className="icon-md" aria-hidden="true" />,
});
}
@@ -383,6 +403,7 @@ export default function useAttachItems({
codeEnabled,
contextEnabled,
fileSearchEnabled,
+ canUseFileSearch,
useResponsesApi,
isUnifiedMode,
handleUploadClick,
diff --git a/client/src/hooks/Input/useAutoSave.spec.ts b/client/src/hooks/Input/useAutoSave.spec.ts
index d878185489..a904ab3038 100644
--- a/client/src/hooks/Input/useAutoSave.spec.ts
+++ b/client/src/hooks/Input/useAutoSave.spec.ts
@@ -1,9 +1,12 @@
+const mockSetDraftEphemeralAgent = jest.fn();
+
jest.mock('recoil', () => ({
...jest.requireActual('recoil'),
useRecoilValue: jest.fn(),
+ useSetRecoilState: () => mockSetDraftEphemeralAgent,
}));
-jest.mock('~/store', () => ({}));
+jest.mock('~/store', () => ({ ephemeralAgentByConvoId: (id: string) => id }));
jest.mock('~/Providers/ChatSettingsContext', () => ({
useChatSettings: () => ({ saveDrafts: true }),
@@ -36,6 +39,7 @@ import { Constants, LocalStorageKeys } from 'librechat-data-provider';
import { useChatFormContext } from '~/Providers';
import { useGetFiles } from '~/data-provider';
import { hasInFlightUpload } from '~/hooks/Files/useFileHandling';
+import { beginFileSearchUpload, captureFileSearchUpload } from '~/hooks/Files/search';
import {
encodeBase64,
clearDraft,
@@ -43,11 +47,20 @@ import {
getAskAnswerDraftId,
getDraft,
getFilesDraft,
+ getPendingDraftId,
setDraft,
setFilesDraft,
+ renewNewConversationDraftToken,
} from '~/utils';
+import {
+ bindComposerLaunch,
+ adoptComposerConversation,
+ registerComposerDraft,
+ captureComposerDraft,
+} from '~/utils/drafts';
import { markPastedTextFile } from '~/utils/files';
import { useAutoSave } from '~/hooks';
+import type { ExtendedFile } from '~/common';
const mockSetValue = jest.fn();
const mockGetDraft = getDraft as jest.Mock;
@@ -75,6 +88,48 @@ beforeEach(() => {
});
describe('useAutoSave — conversation switching', () => {
+ it('recovers blocked pending drafts when this document sweeps an expired foreign lease', async () => {
+ jest.useFakeTimers({ doNotFake: ['queueMicrotask'] });
+ try {
+ markTabLive('expired-owner');
+ const textAreaRef = makeTextAreaRef('');
+ (useGetFiles as jest.Mock).mockReturnValue({ data: [{ file_id: 'lease-file', bytes: 3 }] });
+ const { result, rerender, unmount } = renderHook(
+ ({ isSubmitting }: { isSubmitting: boolean }) => {
+ const [files, setFiles] = React.useState<Map<string, ExtendedFile>>(new Map());
+ useAutoSave({
+ conversationId: 'lease-destination',
+ isSubmitting,
+ textAreaRef,
+ files,
+ setFiles,
+ });
+ return files;
+ },
+ { initialProps: { isSubmitting: true } },
+ );
+ setFilesDraft(Constants.PENDING_CONVO, { fileIds: ['lease-file'], pendingPastes: {} });
+ setFilesDraft('lease-destination', {
+ fileIds: ['foreign-file'],
+ pendingPastes: {},
+ tabId: 'expired-owner',
+ });
+ act(() => rerender({ isSubmitting: false }));
+ expect(getFilesDraft('lease-destination').tabId).toBe('expired-owner');
+ await act(async () => {
+ jest.advanceTimersByTime(160_000);
+ await Promise.resolve();
+ });
+ expect(localStorage.getItem('librechat-live-tab:expired-owner')).toBeNull();
+ expect(getFilesDraft(Constants.PENDING_CONVO).fileIds).toEqual([]);
+ expect(getFilesDraft('lease-destination').fileIds).toEqual(['lease-file']);
+ expect(result.current.has('lease-file')).toBe(true);
+ unmount();
+ } finally {
+ jest.useRealTimers();
+ }
+ });
+
it('clears the textarea when switching to a conversation with no draft', () => {
const { rerender } = renderHook(
({ conversationId }: { conversationId: string }) =>
@@ -740,6 +795,71 @@ describe('useAutoSave — side-by-side pending drafts', () => {
const pane0PendingId = Constants.PENDING_CONVO;
const pane1PendingId = `${Constants.PENDING_CONVO}:1`;
+ it.each([0, 1].flatMap((index) => [false, true].map((explicit) => ({ index, explicit }))))(
+ 'keeps post-acknowledgement uploads through run end (pane $index, explicit $explicit)',
+ ({ index, explicit }) => {
+ window.history.replaceState({}, '', '/c/new');
+ const file = {
+ file_id: 'after-ack-file',
+ progress: 1,
+ size: 6,
+ type: 'text/plain',
+ ...(explicit ? { embedded: true, tool_resource: 'file_search' } : {}),
+ };
+ (useGetFiles as jest.Mock).mockReturnValue({ data: [{ ...file, bytes: 6 }] });
+ const { result, rerender, unmount } = renderHook(
+ ({ conversationId, isSubmitting }) => {
+ const [files, setFiles] = React.useState<Map<string, ExtendedFile>>(new Map());
+ useAutoSave({ index, conversationId, isSubmitting, files, setFiles });
+ return { files, setFiles };
+ },
+ { initialProps: { conversationId: 'new', isSubmitting: true } },
+ );
+ const launch = { conversationId: 'new' };
+ bindComposerLaunch(launch, index);
+ expect(adoptComposerConversation(launch, 'saved-after-ack', index)).toBe(true);
+ act(() => {
+ window.history.replaceState({}, '', '/c/saved-after-ack');
+ rerender({ conversationId: 'saved-after-ack', isSubmitting: true });
+ });
+ act(() => result.current.setFiles(new Map([['after-ack-file', file]])));
+ const pendingId = getPendingDraftId(index);
+ expect(getFilesDraft(pendingId).fileIds).toContain('after-ack-file');
+ act(() => rerender({ conversationId: 'saved-after-ack', isSubmitting: false }));
+ expect(result.current.files.get('after-ack-file')?.progress).toBe(1);
+ expect(getFilesDraft('saved-after-ack').fileIds).toContain('after-ack-file');
+ unmount();
+ window.history.replaceState({}, '', '/');
+ },
+ );
+
+ it('does not reattribute a pending draft to an unacknowledged destination', () => {
+ window.history.replaceState({}, '', '/c/new');
+ const { rerender, unmount } = renderHook(
+ ({ conversationId, files }) =>
+ useAutoSave({
+ index: 40,
+ conversationId,
+ isSubmitting: true,
+ files,
+ setFiles: jest.fn(),
+ }),
+ { initialProps: { conversationId: 'new', files: new Map<string, ExtendedFile>() } },
+ );
+ const pendingId = getPendingDraftId(40);
+ setFilesDraft(pendingId, { fileIds: ['original-pending-file'], pendingPastes: {} });
+ act(() => {
+ window.history.replaceState({}, '', '/c/unrelated-destination');
+ rerender({
+ conversationId: 'unrelated-destination',
+ files: new Map([['unrelated-file', { file_id: 'unrelated-file', progress: 1, size: 1 }]]),
+ });
+ });
+ expect(getFilesDraft(pendingId).fileIds).toEqual(['original-pending-file']);
+ unmount();
+ window.history.replaceState({}, '', '/');
+ });
+
it('migrates only this pane pending file draft when a run finishes', () => {
const { rerender } = renderHook(
({ isSubmitting }: { isSubmitting: boolean }) =>
@@ -960,6 +1080,64 @@ describe('useAutoSave — file cache updates', () => {
expect(restored?.file).toBeInstanceOf(File);
});
+ it('rejects a restored file-map updater after its new-chat generation retires', () => {
+ const setFiles = jest.fn();
+ setFilesDraft('new:38', { fileIds: ['client-temp-id'], pendingPastes: {} });
+ const host = renderHook(() => {
+ (useGetFiles as jest.Mock).mockReturnValue({ data: [persistedRecord] });
+ return useAutoSave({ index: 38, conversationId: 'new', files: new Map(), setFiles });
+ });
+ expect(applySetFiles(setFiles, new Map()).get('client-temp-id')?.progress).toBe(1);
+ renewNewConversationDraftToken(38);
+ expect(applySetFiles(setFiles, new Map()).size).toBe(0);
+ host.unmount();
+ });
+
+ it('prunes a retired new-chat intent before cache recovery without live callbacks', () => {
+ beginFileSearchUpload('client-temp-id', 'new');
+ setFilesDraft('new', { fileIds: ['client-temp-id'], pendingPastes: {} });
+ renewNewConversationDraftToken();
+ const setFiles = jest.fn();
+ const host = renderHook(() => {
+ (useGetFiles as jest.Mock).mockReturnValue({
+ data: [{ ...persistedRecord, embedded: true }],
+ });
+ return useAutoSave({ conversationId: 'new', files: new Map(), setFiles });
+ });
+ expect(applySetFiles(setFiles, new Map()).size).toBe(0);
+ expect(getFilesDraft('new').fileIds).toEqual([]);
+ expect(mockSetDraftEphemeralAgent).not.toHaveBeenCalled();
+ host.unmount();
+ });
+
+ it('restores an inactive upload after its owned pending draft migrates home', async () => {
+ const conversationId = 'migrated-saved-owner';
+ const index = 41;
+ window.history.replaceState({}, '', `/c/${conversationId}`);
+ const pendingId = getPendingDraftId(index);
+ const release = registerComposerDraft(index, conversationId, pendingId, {});
+ const owner = captureComposerDraft(index, conversationId);
+ setFilesDraft(pendingId, { fileIds: ['client-temp-id'], pendingPastes: {} });
+ beginFileSearchUpload('client-temp-id', captureFileSearchUpload(conversationId, owner));
+ release();
+ await Promise.resolve();
+ const host = renderHook(() => {
+ const [files, setFiles] = React.useState<Map<string, ExtendedFile>>(new Map());
+ (useGetFiles as jest.Mock).mockReturnValue({
+ data: [{ ...persistedRecord, embedded: true }],
+ });
+ useAutoSave({ index, conversationId, files, setFiles });
+ return files;
+ });
+ expect(owner()).toBe(false);
+ expect(host.result.current.get('client-temp-id')?.progress).toBe(1);
+ expect(getFilesDraft(conversationId).fileIds).toContain('client-temp-id');
+ expect(getFilesDraft(pendingId).fileIds).toEqual([]);
+ expect(mockSetDraftEphemeralAgent).toHaveBeenCalledWith(expect.any(Function));
+ host.unmount();
+ window.history.replaceState({}, '', '/');
+ });
+
it('marks a file restored from a draft alone as attached', () => {
const setFiles = jest.fn();
setFilesDraft('convo-1', { fileIds: ['client-temp-id'], pendingPastes: {} });
@@ -1085,6 +1263,71 @@ describe('useAutoSave — file cache updates', () => {
(clearAllDrafts as jest.Mock).mockReset();
});
+ it.each([false, true])(
+ 'bounds blocked destination renders and recovers after ownership release (unstable setter: %s)',
+ (unstable) => {
+ markTabLive('blocking-owner');
+ const textAreaRef = makeTextAreaRef('');
+ const cachedFile = { file_id: 'queued-file', bytes: 3, filename: 'queued.txt' };
+ (useGetFiles as jest.Mock).mockReturnValue({ data: [cachedFile] });
+ let renders = 0;
+ let writes = 0;
+ const { result, rerender, unmount } = renderHook(
+ ({ isSubmitting }: { isSubmitting: boolean }) => {
+ if (++renders > 40) throw new Error('unbounded draft recovery');
+ const [files, updateFiles] = React.useState<Map<string, ExtendedFile>>(new Map());
+ const stableSetter = React.useCallback(
+ (update: React.SetStateAction<Map<string, ExtendedFile>>) => {
+ writes++;
+ updateFiles(update);
+ },
+ [],
+ );
+ const setFiles = unstable
+ ? (update: React.SetStateAction<Map<string, ExtendedFile>>) => stableSetter(update)
+ : stableSetter;
+ useAutoSave({
+ conversationId: 'blocked-destination',
+ isSubmitting,
+ textAreaRef,
+ files,
+ setFiles,
+ });
+ return files;
+ },
+ { initialProps: { isSubmitting: true } },
+ );
+ setFilesDraft(Constants.PENDING_CONVO, { fileIds: ['queued-file'], pendingPastes: {} });
+ setFilesDraft('blocked-destination', {
+ fileIds: ['foreign-file'],
+ pendingPastes: {},
+ tabId: 'blocking-owner',
+ });
+ const foreign = getFilesDraft('blocked-destination');
+ act(() => rerender({ isSubmitting: false }));
+ expect(result.current.has('queued-file')).toBe(true);
+ const writesAfterBlock = writes;
+ for (let i = 0; i < 3; i++) act(() => rerender({ isSubmitting: false }));
+ expect(writes - writesAfterBlock).toBeLessThan(8);
+ expect(getFilesDraft('blocked-destination')).toEqual(foreign);
+ expect(getFilesDraft(Constants.PENDING_CONVO).fileIds).toEqual(['queued-file']);
+ markTabGone('blocking-owner');
+ act(() =>
+ window.dispatchEvent(
+ new StorageEvent('storage', { key: 'librechat-live-tab:blocking-owner' }),
+ ),
+ );
+ expect(getFilesDraft(Constants.PENDING_CONVO).fileIds).toEqual([]);
+ expect(getFilesDraft('blocked-destination').fileIds).toEqual(['queued-file']);
+ const writesAfterMigration = writes;
+ (useGetFiles as jest.Mock).mockReturnValue({ data: [{ ...cachedFile }] });
+ act(() => rerender({ isSubmitting: false }));
+ expect(writes - writesAfterMigration).toBeLessThan(5);
+ expect(renders).toBeLessThan(35);
+ unmount();
+ },
+ );
+
it('keeps autosaving to the pending key while the destination is owned by another live tab', () => {
jest.useFakeTimers();
markTabLive('other-tab');
diff --git a/client/src/hooks/Input/useAutoSave.ts b/client/src/hooks/Input/useAutoSave.ts
index cba8b39529..73aaf99f40 100644
--- a/client/src/hooks/Input/useAutoSave.ts
+++ b/client/src/hooks/Input/useAutoSave.ts
@@ -1,12 +1,14 @@
import { useState, useEffect, useMemo, useCallback, useRef } from 'react';
import debounce from 'lodash/debounce';
-import { SetterOrUpdater } from 'recoil';
+import { useSetRecoilState } from 'recoil';
import { Constants } from 'librechat-data-provider';
import type { TFile } from 'librechat-data-provider';
+import type { SetterOrUpdater } from 'recoil';
import type { PendingTextAttachmentDraft } from '~/utils';
import type { ExtendedFile } from '~/common';
import {
applyPendingPastesToDraft,
+ captureComposerDraft,
clearDraft,
clearAllDrafts,
getDraft,
@@ -16,16 +18,26 @@ import {
isAskAnswerDraftId,
isFilesDraftOwnedByThisTab,
isNewConversationDraftId,
+ isPendingDraftId,
mayWriteComposerText,
migrateFilesDraft,
migrateTextDraft,
publishTabAttachmentIds,
+ registerComposerDraft,
+ subscribeDraftOwnership,
setDraft,
setFilesDraft,
} from '~/utils';
+import {
+ completeFileSearchUpload,
+ hasPendingFileSearchUpload,
+ canRestoreFileSearchUpload,
+ cancelFileSearchUpload,
+} from '~/hooks/Files/search';
import { isPastedTextFileMarked, markPastedTextFile } from '~/utils/files';
import { hasInFlightUpload } from '~/hooks/Files/useFileHandling';
import { useChatSettings } from '~/Providers/ChatSettingsContext';
+import { ephemeralAgentByConvoId } from '~/store';
import { useChatFormContext } from '~/Providers';
import { useGetFiles } from '~/data-provider';
@@ -55,12 +67,19 @@ export const useAutoSave = ({
// setting for auto-save
const { setValue } = useChatFormContext();
const { saveDrafts } = useChatSettings();
+ const setEphemeralAgent = useSetRecoilState(
+ ephemeralAgentByConvoId(_conversationId ?? Constants.NEW_CONVO),
+ );
const pendingDraftId = getPendingDraftId(index);
const conversationDraftId =
_conversationId === Constants.NEW_CONVO ? getNewConversationDraftId(index) : _conversationId;
const conversationId = draftId ?? (isSubmitting ? pendingDraftId : conversationDraftId);
- const [currentConversationId, setCurrentConversationId] = useState<string | null>(null);
+ const [currentDraft, setCurrentDraft] = useState<{
+ id: string;
+ conversationId: string;
+ } | null>(null);
+ const currentConversationId = currentDraft?.id ?? null;
const fileIds = useMemo(() => Array.from(files.keys()), [files]);
const { data: fileList } = useGetFiles<TFile[]>();
const filesRef = useRef(files);
@@ -111,7 +130,10 @@ export const useAutoSave = ({
return [];
}
+ const ownsDraft = captureComposerDraft(index, _conversationId ?? Constants.NEW_CONVO);
+ const ownerId = ownsDraft.conversationId();
const activeFileIds = new Set(filesRef.current.keys());
+ const rejectedFileIds: string[] = [];
const fileIdsToKeep: string[] = [];
const pendingPastes = { ...filesDraft.pendingPastes };
const pastedTextIds = [...(filesDraft.pastedTextIds ?? [])];
@@ -130,6 +152,11 @@ export const useAutoSave = ({
}
}
filesDraft.fileIds.forEach((fileId) => {
+ if (!canRestoreFileSearchUpload(fileId, ownerId)) {
+ rejectedFileIds.push(fileId);
+ delete pendingPastes[fileId];
+ return;
+ }
const fileData = filesById.get(fileId);
const tempFileData = filesByTempId.get(fileId);
const { fileToRecover, fileIdToRecover } = fileData
@@ -140,6 +167,15 @@ export const useAutoSave = ({
};
if (fileToRecover) {
+ if (
+ fileToRecover.embedded === true &&
+ completeFileSearchUpload(
+ fileToRecover.temp_file_id || fileIdToRecover,
+ _conversationId ?? Constants.NEW_CONVO,
+ )
+ ) {
+ setEphemeralAgent((previous) => ({ ...previous, file_search: true }));
+ }
fileIdsToKeep.push(fileId);
if (pendingPastes[fileId] != null && !pastedTextIds.includes(fileId)) {
/** Consuming the paste record here, so its id moves to the persistent provenance
@@ -151,7 +187,7 @@ export const useAutoSave = ({
}
delete pendingPastes[fileId];
setFiles((currentFiles) => {
- const updatedFiles = new Map(currentFiles);
+ if (!ownsDraft()) return currentFiles;
/** The same entry may still be live in the composer — this path also
* runs when the upload that created it writes the file cache. Layer
* the persisted record over it instead of replacing it: the local
@@ -159,15 +195,29 @@ export const useAutoSave = ({
* resource the upload was staged under exist nowhere on the server
* record, and `attached` decides whether removing the chip also
* deletes the file, which a composer-owned upload still needs. */
- const live = updatedFiles.get(fileIdToRecover);
- updatedFiles.set(fileIdToRecover, {
+ const live = currentFiles.get(fileIdToRecover);
+ const restored = {
...live,
...fileToRecover,
preview: live?.preview ?? fileToRecover.preview,
progress: 1,
attached: live ? (live.attached ?? false) : true,
size: fileToRecover.bytes,
- });
+ };
+ let unchanged = live != null;
+ if (live) {
+ for (const key in restored) {
+ if (!Object.is(Reflect.get(live, key), Reflect.get(restored, key))) {
+ unchanged = false;
+ break;
+ }
+ }
+ }
+ if (unchanged) {
+ return currentFiles;
+ }
+ const updatedFiles = new Map(currentFiles);
+ updatedFiles.set(fileIdToRecover, restored);
return updatedFiles;
});
return;
@@ -189,9 +239,10 @@ export const useAutoSave = ({
pastedTextIds: pastedTextIds.filter((pastedId) => keptIdentities.has(pastedId)),
pendingPastes,
});
+ rejectedFileIds.forEach(cancelFileSearchUpload);
return pastesToRecover;
},
- [fileList, setFiles],
+ [index, fileList, setFiles, _conversationId, setEphemeralAgent],
);
const restoreText = useCallback(
@@ -227,6 +278,18 @@ export const useAutoSave = ({
* which after a send put the just-sent attachment straight back as a chip. */
const activeStorageId =
currentConversationId === pendingDraftId ? pendingDraftId : conversationId;
+ const composerHostRef = useRef({});
+ const composerRoute = window.location.pathname + window.location.search;
+ useEffect(() => {
+ if (!activeStorageId) return;
+ return registerComposerDraft(
+ index,
+ _conversationId ?? Constants.NEW_CONVO,
+ activeStorageId,
+ composerHostRef.current,
+ );
+ }, [index, _conversationId, activeStorageId, composerRoute]);
+
/** Snapshot before a URL prompt replaces text; user input resumes normal persistence. */
const preserveText = useCallback(() => {
if (!saveDrafts || !activeStorageId || !textAreaRef?.current) {
@@ -331,6 +394,9 @@ export const useAutoSave = ({
const prevConversationIdRef = useRef<string | null>(null);
const pendingDestinationRef = useRef<string | null>(null);
+ // Pending provenance outlives the displayed draft during unrelated visits.
+ const pendingOwnerRef = useRef<string | null>(null);
+ const [ownershipVersion, setOwnershipVersion] = useState(0);
useEffect(() => {
// This useEffect is responsible for saving the current conversation's draft and
@@ -341,12 +407,43 @@ export const useAutoSave = ({
if (!saveDrafts || conversationId == null || conversationId === '') {
return;
}
+ if (
+ conversationId === pendingDraftId &&
+ currentConversationId !== pendingDraftId &&
+ pendingDestinationRef.current == null
+ ) {
+ pendingOwnerRef.current = _conversationId ?? Constants.NEW_CONVO;
+ }
if (conversationId === currentConversationId) {
+ const ownerId = _conversationId ?? Constants.NEW_CONVO;
+ if (currentDraft && currentDraft.conversationId !== ownerId) {
+ const owner = captureComposerDraft(index, currentDraft.conversationId);
+ if (owner() && owner.conversationId() === ownerId) {
+ if (pendingOwnerRef.current === currentDraft.conversationId) {
+ pendingOwnerRef.current = ownerId;
+ }
+ setCurrentDraft((previous) =>
+ previous === currentDraft && owner()
+ ? { ...previous, conversationId: ownerId }
+ : previous,
+ );
+ }
+ }
+ return;
+ }
+
+ const awaitingDestination = pendingDestinationRef.current;
+ if (
+ currentConversationId === pendingDraftId &&
+ awaitingDestination === conversationId &&
+ (!isFilesDraftOwnedByThisTab(getFilesDraft(conversationId)) ||
+ !mayWriteComposerText(conversationId))
+ ) {
return;
}
// clear attachment files when switching conversation
- setFiles(new Map());
+ setFiles((current) => (current.size === 0 ? current : new Map()));
/** The key the attachments live under once the pending draft has been moved. A move that
* storage refuses leaves them behind, and recovery has to read them where they still are. */
@@ -371,14 +468,21 @@ export const useAutoSave = ({
Object.keys(pendingDraftRecord.pendingPastes).length > 0 ||
(getDraft(pendingDraftId) ?? '') !== '');
const pendingDestination = pendingDestinationRef.current;
+ const pendingOwner = pendingOwnerRef.current ?? currentDraft?.conversationId;
const pendingStorageActive =
(prevConversationIdRef.current === pendingDraftId ||
currentConversationId === pendingDraftId ||
(currentConversationId == null && pendingDraftHasContent) ||
+ (pendingOwner === (_conversationId ?? Constants.NEW_CONVO) && pendingDraftHasContent) ||
pendingDestination === conversationId) &&
(pendingDestination == null || pendingDestination === conversationId);
if (
pendingStorageActive &&
+ (pendingDestination === conversationId ||
+ pendingOwner == null ||
+ isNewConversationDraftId(pendingOwner) ||
+ isPendingDraftId(pendingOwner) ||
+ pendingOwner === (_conversationId ?? Constants.NEW_CONVO)) &&
conversationId !== pendingDraftId &&
!isAskAnswerDraftId(conversationId) &&
!isNewConversationDraftId(conversationId) &&
@@ -404,6 +508,7 @@ export const useAutoSave = ({
nextConversationId = pendingDraftId;
} else if (pendingOwned) {
pendingDestinationRef.current = null;
+ pendingOwnerRef.current = null;
/** Move the pending text draft to the new conversationId, then let the composer correct
* it. Both describe the same composer and the record is a debounced copy of it, so when
* they disagree the record is simply older, and restoring it would roll the user's last
@@ -457,10 +562,19 @@ export const useAutoSave = ({
}
prevConversationIdRef.current = nextConversationId;
- setCurrentConversationId(nextConversationId);
+ const owner = _conversationId ?? Constants.NEW_CONVO;
+ setCurrentDraft((previous) =>
+ previous?.id === nextConversationId && previous.conversationId === owner
+ ? previous
+ : { id: nextConversationId, conversationId: owner },
+ );
}, [
+ index,
+ ownershipVersion,
+ currentDraft,
currentConversationId,
conversationId,
+ _conversationId,
pendingDraftId,
restoreFiles,
textAreaRef,
@@ -470,6 +584,23 @@ export const useAutoSave = ({
setFiles,
]);
+ useEffect(() => {
+ const destination = pendingDestinationRef.current;
+ if (!saveDrafts || !destination || destination !== conversationId) {
+ return;
+ }
+ const retry = () => {
+ if (
+ pendingDestinationRef.current === destination &&
+ isFilesDraftOwnedByThisTab(getFilesDraft(destination)) &&
+ mayWriteComposerText(destination)
+ ) {
+ setOwnershipVersion((version) => version + 1);
+ }
+ };
+ return subscribeDraftOwnership(destination, retry);
+ }, [conversationId, currentDraft, saveDrafts]);
+
useEffect(() => {
const draftStorageId = activeStorageId;
if (!saveDrafts || draftStorageId == null || draftStorageId === '' || fileList == null) {
@@ -488,6 +619,9 @@ export const useAutoSave = ({
// It ensures that the file drafts are kept up-to-date and can be restored
// when the conversation is revisited.
const draftStorageId = currentConversationId ?? conversationId;
+ if (currentDraft && currentDraft.conversationId !== (_conversationId ?? Constants.NEW_CONVO)) {
+ return;
+ }
if (!saveDrafts || draftStorageId == null || draftStorageId === '') {
return;
@@ -501,6 +635,19 @@ export const useAutoSave = ({
const draftFileIds = [
...fileIds,
...pendingFileIds.filter((fileId) => !fileIds.includes(fileId)),
+ ...existingDraft.fileIds.filter(
+ (fileId) =>
+ !fileIds.includes(fileId) &&
+ !pendingFileIds.includes(fileId) &&
+ (hasPendingFileSearchUpload(
+ fileId,
+ currentDraft?.conversationId ?? _conversationId ?? Constants.NEW_CONVO,
+ ) ||
+ hasInFlightUpload(
+ fileId,
+ currentDraft?.conversationId ?? _conversationId ?? Constants.NEW_CONVO,
+ )),
+ ),
];
const liveIds = new Set(draftFileIds);
files.forEach((file, key) => {
@@ -531,7 +678,15 @@ export const useAutoSave = ({
pastedTextIds,
pendingPastes: existingDraft.pendingPastes,
});
- }, [conversationId, saveDrafts, currentConversationId, fileIds, files]);
+ }, [
+ conversationId,
+ saveDrafts,
+ currentDraft,
+ currentConversationId,
+ fileIds,
+ files,
+ _conversationId,
+ ]);
return { consumeDraft, preserveText, settleText };
};
diff --git a/client/src/hooks/Input/useQueryParams.ownership.spec.ts b/client/src/hooks/Input/useQueryParams.ownership.spec.ts
new file mode 100644
index 0000000000..1bc6d66dc1
--- /dev/null
+++ b/client/src/hooks/Input/useQueryParams.ownership.spec.ts
@@ -0,0 +1,135 @@
+import React from 'react';
+import { useRecoilValue } from 'recoil';
+import { act, renderHook } from '@testing-library/react';
+import { EModelEndpoint } from 'librechat-data-provider';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import {
+ registerComposerDraft,
+ captureComposerDraft,
+ bindComposerLaunch,
+ adoptComposerConversation,
+} from '~/utils/drafts';
+import {
+ beginFileSearchUpload,
+ captureFileSearchUpload,
+ completeFileSearchUpload,
+} from '~/hooks/Files/search';
+import useQueryParams from './useQueryParams';
+
+const mockSubmit = jest.fn();
+const mockNewConversation = jest.fn();
+const mockContext = {
+ index: 2,
+ conversation: { conversationId: 'new', endpoint: EModelEndpoint.openAI },
+ newConversation: mockNewConversation,
+};
+let mockText = '';
+const mockMethods = {
+ setValue: (_name: string, text: string) => {
+ mockText = text;
+ },
+ getValues: () => mockText,
+ handleSubmit: (accepted: (data: { text: string }) => void) => () => accepted({ text: mockText }),
+};
+
+jest.mock('react-router-dom', () => ({
+ useLocation: () => ({
+ pathname: globalThis.window.location.pathname,
+ search: globalThis.window.location.search,
+ }),
+ useSearchParams: () => [
+ new URLSearchParams(globalThis.window.location.search),
+ (params: URLSearchParams) => {
+ const query = params.toString();
+ globalThis.window.history.replaceState(
+ {},
+ '',
+ globalThis.window.location.pathname + (query ? `?${query}` : ''),
+ );
+ },
+ ],
+}));
+jest.mock('recoil', () => ({
+ ...jest.requireActual('recoil'),
+ useRecoilValue: jest.fn(),
+}));
+jest.mock('~/hooks', () => ({
+ useAuthContext: () => ({ isAuthenticated: true }),
+ useAgentsMap: () => ({}),
+ useDefaultConvo: () => () => ({}),
+ useSubmitMessage: () => ({ submitMessage: mockSubmit }),
+}));
+jest.mock('~/Providers', () => ({
+ useChatContext: () => mockContext,
+ useChatFormContext: () => mockMethods,
+}));
+jest.mock('~/data-provider', () => ({
+ startupConfigKey: () => ['startupConfig'],
+ useGetAgentByIdQuery: () => ({ data: null }),
+}));
+jest.mock('~/hooks/Chat/ask/guards', () => ({ isHistoryRevalidating: () => false }));
+jest.mock('~/store', () => ({
+ __esModule: true,
+ default: { modularChat: 'modularChat', availableTools: 'availableTools' },
+}));
+jest.mock('~/utils', () => ({
+ ...jest.requireActual('~/utils/drafts'),
+ processValidSettings: (settings: Record<string, string>) => settings,
+ logger: { log: jest.fn() },
+}));
+
+describe('consumed prompt URL ownership', () => {
+ beforeEach(() => {
+ jest.useFakeTimers();
+ localStorage.clear();
+ mockSubmit.mockReset();
+ mockNewConversation.mockReset();
+ mockText = '';
+ (useRecoilValue as jest.Mock).mockImplementation((key) =>
+ key === 'availableTools' ? [] : false,
+ );
+ });
+
+ afterEach(() => {
+ jest.useRealTimers();
+ window.history.replaceState({}, '', '/');
+ });
+
+ it.each([false, true])(
+ 'preserves the real query cleanup before first-ID acknowledgement (auto-submit: %s)',
+ (autoSubmit) => {
+ window.history.replaceState(
+ {},
+ '',
+ `/c/new?prompt=hello&projectId=project-1${autoSubmit ? '&submit=true' : ''}`,
+ );
+ const release = registerComposerDraft(2, 'new', 'new:2', {});
+ const captured = captureComposerDraft(2, 'new');
+ const launch = { conversationId: 'new' };
+ mockSubmit.mockImplementation(() => bindComposerLaunch(launch, 2));
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, cacheTime: Infinity } },
+ });
+ client.setQueryData(['startupConfig'], { modelSpecs: { list: [] } });
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(QueryClientProvider, { client }, children);
+ const textAreaRef = { current: document.createElement('textarea') };
+ const { unmount } = renderHook(() => useQueryParams({ textAreaRef }), { wrapper });
+ act(() => jest.advanceTimersByTime(100));
+ expect(mockText).toBe('hello');
+ expect(window.location.search).toBe('?projectId=project-1');
+ expect(captured()).toBe(true);
+ expect(mockSubmit).toHaveBeenCalledTimes(autoSubmit ? 1 : 0);
+ if (!autoSubmit) bindComposerLaunch(launch, 2);
+ beginFileSearchUpload('url-search', captureFileSearchUpload('new', captured));
+ expect(adoptComposerConversation(launch, 'saved-query', 2)).toBe(true);
+ expect(captured.conversationId()).toBe('saved-query');
+ expect(completeFileSearchUpload('url-search', 'saved-query')).toBe(true);
+ window.history.replaceState({}, '', '/c/unrelated');
+ expect(captured()).toBe(false);
+ release();
+ unmount();
+ client.clear();
+ },
+ );
+});
diff --git a/client/src/hooks/Input/useQueryParams.ts b/client/src/hooks/Input/useQueryParams.ts
index f62b465099..5ef6e21df1 100644
--- a/client/src/hooks/Input/useQueryParams.ts
+++ b/client/src/hooks/Input/useQueryParams.ts
@@ -35,6 +35,7 @@ import { useAuthContext, useAgentsMap, useDefaultConvo, useSubmitMessage } from
import { startupConfigKey, useGetAgentByIdQuery } from '~/data-provider';
import { useChatContext, useChatFormContext } from '~/Providers';
import { isHistoryRevalidating } from '~/hooks/Chat/ask/guards';
+import { consumeComposerQuery } from '~/utils/drafts';
import store from '~/store';
const PROJECT_ID_SEARCH_PARAM = 'projectId';
@@ -127,7 +128,7 @@ export default function useQueryParams({
submitMessageRef.current = submitMessage;
const queryClient = useQueryClient();
- const { conversation, newConversation } = useChatContext();
+ const { conversation, newConversation, index = 0 } = useChatContext();
const urlAgentId = searchParams.get('agent_id') || '';
const { data: urlAgent } = useGetAgentByIdQuery(urlAgentId);
@@ -144,6 +145,18 @@ export default function useQueryParams({
const conversationRef = useRef(conversation);
conversationRef.current = conversation;
+ const clearConsumedSearchParams = useCallback(() => {
+ const params = getPreservedSearchParams();
+ consumeComposerQuery(
+ index,
+ conversationRef.current?.conversationId ?? Constants.NEW_CONVO,
+ routeRef.current.pathname,
+ routeRef.current.search,
+ params.toString(),
+ );
+ setSearchParamsRef.current(params, { replace: true });
+ }, [index, getPreservedSearchParams]);
+
const ownsComposer = useCallback(() => {
const currentId = conversationRef.current?.conversationId;
const current = routeRef.current;
@@ -473,7 +486,7 @@ export default function useQueryParams({
}
validatingRef.current = false;
if (ownsRequest(requestId)) {
- setSearchParamsRef.current(getPreservedSearchParams(), { replace: true });
+ clearConsumedSearchParams();
}
};
methods.handleSubmit(
@@ -508,7 +521,7 @@ export default function useQueryParams({
ownsRequest,
isHistoryPending,
areSettingsApplied,
- getPreservedSearchParams,
+ clearConsumedSearchParams,
restoreUrlPrompt,
settlePrompt,
]);
@@ -616,7 +629,7 @@ export default function useQueryParams({
// Defer URL cleanup until after submission completes (processSubmission handles it)
if ((!willAutoSubmit || !decodedPrompt.trim()) && ownsRequest()) {
settlePrompt();
- setSearchParamsRef.current(getPreservedSearchParams(), { replace: true });
+ clearConsumedSearchParams();
}
};
@@ -648,7 +661,7 @@ export default function useQueryParams({
setSubmissionStatus('failed');
logger.log('conversation', 'Settings application timeout, retaining prompt');
settlePrompt();
- setSearchParamsRef.current(getPreservedSearchParams(), { replace: true });
+ clearConsumedSearchParams();
}
}, MAX_SETTINGS_WAIT_MS);
}
@@ -673,7 +686,7 @@ export default function useQueryParams({
newQueryConvo,
newConversation,
submitMessage,
- getPreservedSearchParams,
+ clearConsumedSearchParams,
queryClient,
processSubmission,
areSettingsApplied,
diff --git a/client/src/hooks/Plugins/useToolToggle.ts b/client/src/hooks/Plugins/useToolToggle.ts
index 2b90675513..f696dcece6 100644
--- a/client/src/hooks/Plugins/useToolToggle.ts
+++ b/client/src/hooks/Plugins/useToolToggle.ts
@@ -6,6 +6,7 @@ import type { VerifyToolAuthResponse } from 'librechat-data-provider';
import type { UseQueryOptions } from '@tanstack/react-query';
import { useVerifyAgentToolAuth, useGetStartupConfig } from '~/data-provider';
import useLocalStorage from '~/hooks/useLocalStorageAlt';
+import { setFileSearchChoice } from '~/utils/choices';
import { setTimestamp } from '~/utils/timestamps';
import { ephemeralAgentByConvoId } from '~/store';
@@ -68,14 +69,15 @@ export function useToolToggle({
return toolValue === true;
}, [toolValue]);
- // Sync to localStorage with timestamps when ephemeralAgent changes
+ // Timestamp changes to this tool, not unrelated fields on the agent.
+ const storedToolValue = ephemeralAgent?.[toolKey];
useEffect(() => {
- const value = ephemeralAgent?.[toolKey];
+ const value = storedToolValue;
if (value !== undefined) {
localStorage.setItem(storageKey, JSON.stringify(value));
setTimestamp(storageKey);
}
- }, [ephemeralAgent, toolKey, storageKey]);
+ }, [storedToolValue, storageKey]);
/** Admin-configured default: pin this tool when its key is listed in `defaultPinnedTools`.
* Only seeds the initial state — a user's stored pin preference always takes precedence. */
@@ -134,6 +136,9 @@ export function useToolToggle({
return;
}
+ if (localStorageKey === LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_) {
+ setFileSearchChoice(key, typeof value === 'string' ? value.length > 0 : value);
+ }
// Update ephemeralAgent (localStorage will sync automatically via effect)
setEphemeralAgent((prev) => ({
...(prev || {}),
@@ -154,6 +159,7 @@ export function useToolToggle({
toolKey,
storageContextKey,
localStorageKey,
+ key,
],
);
diff --git a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
index 6ccfe49f9b..4a649965f3 100644
--- a/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
+++ b/client/src/hooks/SSE/__tests__/useResumableSSE.spec.ts
@@ -21,6 +21,7 @@ import {
pendingUsageFamily,
removeUsageAtoms,
} from '~/components/Chat/Input/TokenUsage/store';
+import { registerComposerDraft, captureComposerDraft, bindComposerLaunch } from '~/utils/drafts';
import { pendingApprovalActionFamily } from '~/components/Chat/approval/state';
type SSEEventListener = (e: Partial<MessageEvent> & { responseCode?: number }) => void;
@@ -504,6 +505,27 @@ describe('useResumableSSE', () => {
return { sse, unmount, chatHelpers };
};
+ it('adopts the acknowledged composer before hydrating a resumable submission', async () => {
+ window.history.replaceState({}, '', '/c/new?prompt=hello');
+ const release = registerComposerDraft(0, Constants.NEW_CONVO, Constants.PENDING_CONVO, {});
+ const submission = buildSubmission({
+ conversation: { conversationId: String(Constants.NEW_CONVO) },
+ });
+ bindComposerLaunch(submission.conversation, 0);
+ const captured = captureComposerDraft(0, Constants.NEW_CONVO);
+ const helpers = buildChatHelpers();
+ const { unmount } = renderHook(() => useResumableSSE(submission, helpers));
+ await flushMicrotasks();
+ expect(captured.conversationId()).toBe('stream-123');
+ expect(window.location.pathname).toBe('/c/stream-123');
+ expect(window.location.search).toBe('?prompt=hello');
+ expect(captured()).toBe(true);
+ getLastSSE().readyState = MOCK_SSE_CLOSED;
+ unmount();
+ release();
+ window.history.replaceState({}, '', '/');
+ });
+
it.each([useSSE, useResumableSSE])(
'%p binds a created response before any output or usage',
async (useTransport) => {
diff --git a/client/src/hooks/SSE/__tests__/workspace.spec.tsx b/client/src/hooks/SSE/__tests__/workspace.spec.tsx
index 5d6c175e17..51fd3dfca1 100644
--- a/client/src/hooks/SSE/__tests__/workspace.spec.tsx
+++ b/client/src/hooks/SSE/__tests__/workspace.spec.tsx
@@ -4,14 +4,29 @@ import { RecoilRoot } from 'recoil';
import { MemoryRouter } from 'react-router-dom';
import { act, renderHook } from '@testing-library/react';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
-import { Constants, EModelEndpoint, QueryKeys } from 'librechat-data-provider';
-import type { ChatCreatedFrame, EventSubmission, TConversation } from 'librechat-data-provider';
+import { Constants, EModelEndpoint, QueryKeys, LocalStorageKeys } from 'librechat-data-provider';
+import type {
+ ChatCreatedFrame,
+ EventSubmission,
+ TConversation,
+ TMessage,
+} from 'librechat-data-provider';
+import {
+ registerComposerDraft,
+ adoptComposerConversation,
+ bindComposerLaunch,
+ captureComposerDraft,
+ getActiveComposerDraftId,
+} from '~/utils/drafts';
+import { setFileSearchChoice, getFileSearchChoice, clearFileSearchChoices } from '~/utils/choices';
+import { beginFileSearchUpload, completeFileSearchUpload } from '~/hooks/Files/search';
import useCodeWorkspace from '~/hooks/Agents/useCodeWorkspace';
import useEventHandlers from '../useEventHandlers';
const mockStatus = jest.fn();
const mockStartupConfig = jest.fn();
const mockApplyAgentTemplate = jest.fn();
+const mockQueueTitleGeneration = jest.fn();
const mockAnnounce = jest.fn();
const mockReset = jest.fn();
@@ -52,6 +67,7 @@ jest.mock('~/data-provider', () => ({
/** The barrel can be partially initialized through the hook imports above. Keep these
* real hooks rather than snapshotting missing exports or replacing recovery with a stub. */
...jest.requireActual('~/data-provider/CodeEnvironments'),
+ queueTitleGeneration: (conversationId: string) => mockQueueTitleGeneration(conversationId),
useCodeEnvironmentStatusQueries: () => mockStatus(),
useGetStartupConfig: () => ({ data: mockStartupConfig() }),
}));
@@ -64,7 +80,11 @@ const initialConversation = {
title: 'New Chat',
} as TConversation;
-function setup(current = initialConversation, isAddedRequest = false) {
+function setup(
+ current = initialConversation,
+ isAddedRequest = false,
+ currentMessages: TMessage[] = [],
+) {
const queryClient = new QueryClient({ defaultOptions: { queries: { retry: false } } });
queryClient.setQueryData([QueryKeys.allConversations], { pages: [], pageParams: [] });
const wrapper = ({ children }: { children: React.ReactNode }) => (
@@ -83,7 +103,7 @@ function setup(current = initialConversation, isAddedRequest = false) {
isAddedRequest,
setConversation,
setMessages: jest.fn(),
- getMessages: () => [],
+ getMessages: () => currentMessages,
setCompleted: jest.fn(),
setIsSubmitting: jest.fn(),
setShowStopButton: jest.fn(),
@@ -130,6 +150,213 @@ function setup(current = initialConversation, isAddedRequest = false) {
return { ...hook, submission, createdData, queryClient };
}
+describe('created composer identity', () => {
+ beforeEach(() => {
+ localStorage.clear();
+ clearFileSearchChoices();
+ mockApplyAgentTemplate.mockClear();
+ mockQueueTitleGeneration.mockClear();
+ mockStatus.mockReturnValue([]);
+ mockStartupConfig.mockReturnValue({ codeEnvironmentDecisionVersion: 1 });
+ });
+
+ it.each([true, false])(
+ 'preserves current File Search preference across acknowledgement (%s)',
+ (enabled) => {
+ const { result, submission, unmount, queryClient } = setup();
+ const release = registerComposerDraft(0, Constants.NEW_CONVO, 'pending', {});
+ bindComposerLaunch(submission.conversation, 0);
+ localStorage.setItem(`${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}new`, 'true');
+ if (!enabled) setFileSearchChoice('saved-chat', false);
+ act(() =>
+ result.current.createdHandler(
+ { created: true, message: submission.userMessage },
+ {
+ ...submission,
+ ephemeralAgent: { file_search: false },
+ },
+ ),
+ );
+ expect(mockApplyAgentTemplate).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ targetId: 'saved-chat',
+ ephemeralAgent: expect.objectContaining({ file_search: enabled }),
+ }),
+ );
+ expect(localStorage.getItem(`${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}saved-chat`)).toBe(
+ JSON.stringify(enabled),
+ );
+ release();
+ unmount();
+ queryClient.clear();
+ },
+ );
+
+ it.each([false, true])(
+ 'keeps a saved-chat upload preference on later acknowledgements (disabled later: %s)',
+ (disabledLater) => {
+ const { result, submission, createdData, unmount, queryClient } = setup();
+ window.history.replaceState({}, '', '/c/new');
+ const host = {};
+ const release = registerComposerDraft(0, Constants.NEW_CONVO, 'pending', host);
+ bindComposerLaunch(submission.conversation, 0);
+ localStorage.setItem(`${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}new`, 'false');
+ act(() => result.current.createdHandler(createdData, submission));
+ window.history.replaceState({}, '', '/c/saved-chat');
+ release();
+ const releaseSaved = registerComposerDraft(0, 'saved-chat', 'saved-chat', host);
+ setFileSearchChoice('saved-chat', false);
+ beginFileSearchUpload('saved-explicit-upload', 'saved-chat');
+ const revision = getFileSearchChoice('saved-chat')?.revision;
+ if (disabledLater) setFileSearchChoice('saved-chat', false);
+ expect(completeFileSearchUpload('saved-explicit-upload', 'saved-chat')).toBe(!disabledLater);
+ if (disabledLater)
+ localStorage.setItem(`${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}saved-chat`, 'false');
+ const next = {
+ ...submission,
+ conversation: result.current.conversation!,
+ ephemeralAgent: { file_search: !disabledLater },
+ };
+ bindComposerLaunch(next.conversation, 0);
+ act(() => result.current.createdHandler(createdData, next));
+ expect(mockApplyAgentTemplate).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ ephemeralAgent: expect.objectContaining({ file_search: !disabledLater }),
+ }),
+ );
+ expect(localStorage.getItem(`${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}saved-chat`)).toBe(
+ JSON.stringify(!disabledLater),
+ );
+ if (!disabledLater) expect(getFileSearchChoice('saved-chat')?.revision).toBe(revision);
+ releaseSaved();
+ unmount();
+ queryClient.clear();
+ window.history.replaceState({}, '', '/');
+ },
+ );
+
+ it.each(
+ ['created', 'final'].flatMap((event) =>
+ ['saved', 'resumable'].flatMap((origin) =>
+ [
+ 'accepted',
+ 'disabled-before',
+ 'disabled-after',
+ 'blocked-storage',
+ 'accepted-unset',
+ 'blocked-unset',
+ ].map((completion) => ({
+ event,
+ origin,
+ completion,
+ })),
+ ),
+ ),
+ )(
+ 'keeps the current File Search value over a stale template ($event, $origin, $completion)',
+ ({ event, origin, completion }) => {
+ const currentMessages: TMessage[] = [];
+ const saved = { ...initialConversation, conversationId: 'saved-chat' };
+ const { result, submission, createdData, unmount, queryClient } = setup(
+ origin === 'saved' ? saved : initialConversation,
+ false,
+ currentMessages,
+ );
+ window.history.replaceState({}, '', origin === 'saved' ? '/c/saved-chat' : '/c/new');
+ const host = {};
+ let release = registerComposerDraft(
+ 0,
+ submission.conversation!.conversationId!,
+ 'pending',
+ host,
+ );
+ bindComposerLaunch(submission.conversation, 0);
+ if (origin === 'resumable') {
+ expect(adoptComposerConversation(submission.conversation, 'saved-chat', 0)).toBe(true);
+ window.history.replaceState({}, '', '/c/saved-chat');
+ release();
+ release = registerComposerDraft(0, 'saved-chat', 'pending', host);
+ }
+ if (!completion.endsWith('unset')) setFileSearchChoice('saved-chat', false);
+ localStorage.setItem(`${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}saved-chat`, 'false');
+ const previousRevision = getFileSearchChoice('saved-chat')?.revision ?? null;
+ const stale = { ...submission, ephemeralAgent: { file_search: false, web_search: true } };
+ currentMessages.push(stale.userMessage, stale.initialResponse);
+ beginFileSearchUpload('late-accepted-upload', 'saved-chat');
+ const writer = Storage.prototype.setItem;
+ const storage = completion.startsWith('blocked')
+ ? jest.spyOn(Storage.prototype, 'setItem').mockImplementation(function (
+ this: Storage,
+ key: string,
+ value: string,
+ ) {
+ if (
+ key.startsWith('file-search-choice:') ||
+ key.startsWith(`${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}saved-chat`)
+ )
+ throw new Error('Preference storage unavailable');
+ writer.call(this, key, value);
+ })
+ : undefined;
+ try {
+ if (completion === 'disabled-before') setFileSearchChoice('saved-chat', false);
+ expect(completeFileSearchUpload('late-accepted-upload', 'saved-chat')).toBe(
+ completion !== 'disabled-before',
+ );
+ if (completion === 'disabled-after') setFileSearchChoice('saved-chat', false);
+ const enabled = !completion.startsWith('disabled');
+ if (!enabled) stale.ephemeralAgent.file_search = true;
+ act(() => {
+ for (let replay = 0; replay < 2; replay++) {
+ if (event === 'created') result.current.createdHandler(createdData, stale);
+ else {
+ result.current.finalHandler(
+ {
+ conversation: saved,
+ requestMessage: stale.userMessage,
+ responseMessage: { ...stale.initialResponse, text: 'Finished reply' },
+ },
+ stale,
+ );
+ }
+ }
+ });
+ expect(mockApplyAgentTemplate).toHaveBeenLastCalledWith(
+ expect.objectContaining({
+ ephemeralAgent: expect.objectContaining({ file_search: enabled, web_search: true }),
+ }),
+ );
+ if (enabled) expect(getFileSearchChoice('saved-chat')?.revision).toBe(previousRevision);
+ if (event === 'final' && origin === 'resumable') {
+ expect(mockQueueTitleGeneration).toHaveBeenCalledWith('saved-chat');
+ } else {
+ expect(mockQueueTitleGeneration).not.toHaveBeenCalled();
+ }
+ } finally {
+ storage?.mockRestore();
+ release();
+ unmount();
+ queryClient.clear();
+ window.history.replaceState({}, '', '/');
+ }
+ },
+ );
+
+ it('adopts only the composer bound to the acknowledged launch', () => {
+ const { result, submission, unmount } = setup();
+ const release = registerComposerDraft(0, Constants.NEW_CONVO, 'pending', {});
+ bindComposerLaunch(submission.conversation, 0);
+ const captured = captureComposerDraft(0, Constants.NEW_CONVO);
+ act(() =>
+ result.current.createdHandler({ created: true, message: submission.userMessage }, submission),
+ );
+ expect(captured.conversationId()).toBe('saved-chat');
+ expect(getActiveComposerDraftId(0, 'saved-chat')).toBe('pending');
+ release();
+ unmount();
+ });
+});
+
describe('workspace decision at stream acknowledgement', () => {
beforeEach(() => {
mockStartupConfig.mockReturnValue({ codeEnvironmentDecisionVersion: 1 });
diff --git a/client/src/hooks/SSE/cache.ts b/client/src/hooks/SSE/cache.ts
index c8bd965f81..d6fd920c72 100644
--- a/client/src/hooks/SSE/cache.ts
+++ b/client/src/hooks/SSE/cache.ts
@@ -11,6 +11,8 @@ import type { TMessage, TSubmission, TConversation } from 'librechat-data-provid
import type { ResumableCache } from '@librechat/chat';
import type { ActiveJobsResponse } from '~/data-provider';
import {
+ adoptComposerConversation,
+ bindComposerLaunch,
upsertConvoInAllQueries,
removeConvoFromAllQueries,
invalidateConversationLists,
@@ -20,11 +22,13 @@ import {
streamStatusQueryKey,
fetchConversationMessages,
} from '~/data-provider';
+import { transferFileSearchPreference } from '~/hooks/Files/search';
import { fetchConvoSnapshot } from '~/utils/convos';
/** The app's query cache, as a resumable run reads and refreshes it. */
export default function useResumableCache(
getMessages: () => TMessage[] | undefined,
+ runIndex = 0,
): ResumableCache {
const queryClient = useQueryClient();
@@ -81,9 +85,20 @@ export default function useResumableCache(
);
upsertConvoInAllQueries(queryClient, optimisticConversation);
- return hydrateSubmissionMessages(currentSubmission, conversationId);
+ const hydrated = hydrateSubmissionMessages(currentSubmission, conversationId);
+ if (
+ adoptComposerConversation(
+ currentSubmission.conversation,
+ conversationId,
+ runIndex,
+ transferFileSearchPreference,
+ )
+ ) {
+ bindComposerLaunch(hydrated.conversation, runIndex);
+ }
+ return hydrated;
},
- [getMessages, queryClient],
+ [getMessages, queryClient, runIndex],
);
return useMemo<ResumableCache>(
diff --git a/client/src/hooks/SSE/final.ts b/client/src/hooks/SSE/final.ts
index 59c52e8eb2..e4426eebf2 100644
--- a/client/src/hooks/SSE/final.ts
+++ b/client/src/hooks/SSE/final.ts
@@ -27,6 +27,7 @@ import {
preserveStreamedContentIdentity,
} from '~/utils';
import { startupConfigKey, queueTitleGeneration } from '~/data-provider';
+import { withFileSearchPreference } from '~/hooks/Files/search';
import { getConvoTitle } from './turns';
/** Settles a finished turn: the final messages, the conversation it belongs to, and an early abort that restores the draft. */
@@ -317,7 +318,10 @@ export default function useFinalHandler(ctx: EventHandlerContext) {
applyAgentTemplate({
targetId: conversation.conversationId,
sourceId: submissionConvo.conversationId,
- ephemeralAgent: submission.ephemeralAgent,
+ ephemeralAgent: withFileSearchPreference(
+ conversation.conversationId,
+ submission.ephemeralAgent,
+ ),
specName: submission.conversation?.spec,
startupConfig: queryClient.getQueryData<TStartupConfig>(startupConfigKey(true)),
});
diff --git a/client/src/hooks/SSE/opening.ts b/client/src/hooks/SSE/opening.ts
index 63b49595ef..46a5d4075e 100644
--- a/client/src/hooks/SSE/opening.ts
+++ b/client/src/hooks/SSE/opening.ts
@@ -11,12 +11,14 @@ import type {
import type { EventHandlerContext } from './handlers';
import {
scrollToEnd,
+ adoptComposerConversation,
hasRealTitle,
withoutListFlags,
setDocumentTitle,
upsertConvoInAllQueries,
updateConvoInAllQueries,
} from '~/utils';
+import { transferFileSearchPreference, withFileSearchPreference } from '~/hooks/Files/search';
import { startupConfigKey, markTitleGenerationProcessed } from '~/data-provider';
import { MESSAGE_UPDATE_INTERVAL } from '~/common';
import { getConvoTitle } from './turns';
@@ -65,6 +67,7 @@ export default function useTurnHandlers(ctx: EventHandlerContext) {
setShowStopButton,
setConversation,
isAddedRequest,
+ runIndex,
announcePolite,
lastAnnouncementTimeRef,
setAbortScroll,
@@ -111,6 +114,7 @@ export default function useTurnHandlers(ctx: EventHandlerContext) {
(data: TSyncData, submission: EventSubmission) => {
const { conversationId, thread_id, responseMessage, requestMessage } = data;
const { initialResponse, messages: _messages, userMessage, isTemporary = false } = submission;
+ adoptComposerConversation(submission.conversation, conversationId, runIndex);
/** Swap the optimistic user row for the server-stamped one IN PLACE.
* Filtering it out and re-appending at the tail would order any of its
* already-present children (abandoned responses from preempted
@@ -182,7 +186,15 @@ export default function useTurnHandlers(ctx: EventHandlerContext) {
setShowStopButton(true);
},
- [queryClient, setMessages, isAddedRequest, announcePolite, setConversation, setShowStopButton],
+ [
+ queryClient,
+ setMessages,
+ isAddedRequest,
+ announcePolite,
+ setConversation,
+ setShowStopButton,
+ runIndex,
+ ],
);
const createdHandler = useCallback(
@@ -211,6 +223,14 @@ export default function useTurnHandlers(ctx: EventHandlerContext) {
}
const { conversationId, parentMessageId } = userMessage;
+ if (conversationId) {
+ adoptComposerConversation(
+ submission.conversation,
+ conversationId,
+ runIndex,
+ transferFileSearchPreference,
+ );
+ }
lastAnnouncementTimeRef.current = Date.now();
announcePolite({
message: 'start',
@@ -263,7 +283,7 @@ export default function useTurnHandlers(ctx: EventHandlerContext) {
applyAgentTemplate({
targetId: conversationId,
sourceId: submission.conversation?.conversationId,
- ephemeralAgent: submission.ephemeralAgent,
+ ephemeralAgent: withFileSearchPreference(conversationId, submission.ephemeralAgent),
specName: submission.conversation?.spec,
startupConfig: queryClient.getQueryData<TStartupConfig>(startupConfigKey(true)),
});
@@ -281,6 +301,7 @@ export default function useTurnHandlers(ctx: EventHandlerContext) {
applyAgentTemplate,
focusRegeneratedResponse,
lastAnnouncementTimeRef,
+ runIndex,
],
);
diff --git a/client/src/hooks/SSE/useResumableSSE.ts b/client/src/hooks/SSE/useResumableSSE.ts
index 87623fd82d..b49c1bedc8 100644
--- a/client/src/hooks/SSE/useResumableSSE.ts
+++ b/client/src/hooks/SSE/useResumableSSE.ts
@@ -79,7 +79,7 @@ export default function useResumableSSE(
balanceEnabled && balanceQuery.refetch();
}, [balanceEnabled, balanceQuery]);
- const cache = useResumableCache(getMessages);
+ const cache = useResumableCache(getMessages, runIndex);
const steerState = useSteerState();
const steers = useResumableSteers(steerState);
const { events, usage } = useResumableEvents({ run, runIndex, isAddedRequest, chatHelpers });
diff --git a/client/src/hooks/__tests__/useNewConvo.spec.ts b/client/src/hooks/__tests__/useNewConvo.spec.ts
index d1bf07e272..1b9fd91e6f 100644
--- a/client/src/hooks/__tests__/useNewConvo.spec.ts
+++ b/client/src/hooks/__tests__/useNewConvo.spec.ts
@@ -1,11 +1,46 @@
-import { getDefaultStore } from 'jotai';
+import React from 'react';
+import { getDefaultStore, useAtom } from 'jotai';
import { filesFamily } from '@librechat/chat/react';
import { renderHook, act } from '@testing-library/react';
-import { Constants, EModelEndpoint } from 'librechat-data-provider';
-import type { TConversation } from 'librechat-data-provider';
+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
+import { Constants, LocalStorageKeys, EModelEndpoint } from 'librechat-data-provider';
+import type { EventSubmission, TConversation } from 'librechat-data-provider';
import type { ExtendedFile } from '~/common';
+import {
+ setFilesDraft,
+ getFilesDraft,
+ registerComposerDraft,
+ getAskAnswerDraftId,
+ bindComposerLaunch,
+ captureComposerDraft,
+ adoptComposerConversation,
+} from '~/utils/drafts';
+import {
+ beginFileSearchUpload,
+ captureFileSearchUpload,
+ completeFileSearchUpload,
+ transferFileSearchPreference,
+} from '~/hooks/Files/search';
+import { setFileSearchChoice, transferFileSearchChoice } from '~/utils/choices';
+import { clearUploadRecovery } from '~/hooks/Files/useFileHandling';
+import { useAutoSave } from '~/hooks/Input/useAutoSave';
+import useTurnHandlers from '~/hooks/SSE/opening';
const mockDeleteFiles = jest.fn();
+const mockUploadFile = jest.fn();
+let mockUploadOptions: { onSuccess?: (data: object, body: FormData) => void } = {};
+let mockPreparationGate: Promise<void> | undefined;
+let mockConfigPending = false;
+let mockDownloadedFiles: File[] = [];
+const mockResizeFile = jest.fn(async (file: File) => ({ file, resized: false }));
+const mockConvertFile = jest.fn(
+ async (file: File, _quality?: number, _onProgress?: (progress: number) => void) => file,
+);
+
+let mockSaveDrafts = false;
+let mockPreviousConversation: { conversationId: string; endpoint: EModelEndpoint } | null = null;
+let mockFileList: object[] = [];
+const mockSetEphemeralAgent = jest.fn();
const mockRemoveTabAttachmentPresence = jest.fn();
const mockCollectForeignAttachmentClaims = jest.fn(
(_excludeDraftIds: string[], _excludeOwnPane?: number | 'tab') => new Set(mockForeignClaims),
@@ -36,7 +71,7 @@ jest.mock('react-router-dom', () => ({
}));
jest.mock('~/Providers/ChatSettingsContext', () => ({
- useChatSettings: () => ({ saveDrafts: false }),
+ useChatSettings: () => ({ saveDrafts: mockSaveDrafts }),
}));
jest.mock('recoil', () => ({
@@ -46,8 +81,11 @@ jest.mock('recoil', () => ({
}
return null;
},
- useSetRecoilState: () => jest.fn(),
- useRecoilCallback: () => jest.fn(),
+ useSetRecoilState: (key: string) => (update: unknown) => mockSetEphemeralAgent(key, update),
+ useRecoilCallback: (callback) =>
+ callback.length === 0
+ ? jest.fn()
+ : callback({ set: (key, update) => mockSetEphemeralAgent(key, update) }),
}));
jest.mock('librechat-data-provider/react-query', () => ({
useGetModelsQuery: () => ({ data: {} }),
@@ -58,6 +96,9 @@ jest.mock('librechat-data-provider', () => ({
}));
jest.mock('~/utils', () => ({
+ ...jest.requireActual('~/utils/drafts'),
+ ...jest.requireActual('~/utils/files'),
+ ...jest.requireActual('~/utils/previewCache'),
updateLastSelectedModel: jest.fn(),
getLocalStorageItems: () => ({}),
getDefaultModelSpec: () => ({}),
@@ -70,7 +111,9 @@ jest.mock('~/utils', () => ({
mockCollectForeignAttachmentClaims(excludeDraftIds, excludeOwnPane),
getNewConversationDraftId: (index = 0) => (index === 0 ? 'new' : `new:${index}`),
getPendingDraftId: (index = 0) => (index === 0 ? 'pending' : `pending:${index}`),
- renewNewConversationDraftToken: jest.fn(),
+ renewNewConversationDraftToken: jest.fn(
+ jest.requireActual('~/utils/drafts').renewNewConversationDraftToken,
+ ),
removeTabAttachmentPresence: (...args: unknown[]) => mockRemoveTabAttachmentPresence(...args),
loadPendingDiscardIds: () => [...mockPendingDiscardIds],
storePendingDiscardIds: (index: number, ids: string[]) => mockStorePendingDiscardIds(index, ids),
@@ -84,6 +127,45 @@ jest.mock('~/data-provider', () => ({
useDeleteFilesMutation: () => ({ mutateAsync: mockDeleteFiles }),
useGetEndpointsQuery: () => ({ data: {} }),
useGetStartupConfig: () => ({ data: {} }),
+ useGetFiles: () => ({ data: mockFileList }),
+ useGetFileConfig: () => ({ data: null }),
+ useGetAgentByIdQuery: () => ({ data: undefined }),
+ useUploadFileMutation: (options) => {
+ mockUploadOptions = options;
+ return { mutate: mockUploadFile };
+ },
+}));
+
+jest.mock('@librechat/client', () => ({
+ ...jest.requireActual('@librechat/client'),
+ useToastContext: () => ({ showToast: jest.fn() }),
+}));
+jest.mock('~/Providers/AgentsMapContext', () => ({ useAgentsMapContext: () => ({}) }));
+jest.mock('../Files/useDelayedUploadToast', () => ({
+ useDelayedUploadToast: () => ({ startUploadTimer: jest.fn(), clearUploadTimer: jest.fn() }),
+}));
+jest.mock('../Files/useClientResize', () => ({
+ __esModule: true,
+ default: () => ({
+ isConfigPending: mockConfigPending,
+ waitForConfig: () => mockPreparationGate,
+ resizeImageIfNeeded: mockResizeFile,
+ }),
+}));
+jest.mock('~/utils/heicConverter', () => ({
+ processFileForUpload: (...args: [File]) => mockConvertFile(...args),
+}));
+jest.mock('../Files/useSharePointDownload', () => ({
+ __esModule: true,
+ default: () => ({
+ downloadSharePointFiles: async () => {
+ await mockPreparationGate;
+ return mockDownloadedFiles;
+ },
+ isDownloading: false,
+ downloadProgress: null,
+ error: null,
+ }),
}));
jest.mock('../Conversations/useNavigateToConvo', () => ({
@@ -92,19 +174,26 @@ jest.mock('../Conversations/useNavigateToConvo', () => ({
}));
jest.mock('../Conversations/useGetConversation', () => ({
__esModule: true,
- default: () => () => null,
+ default: () => () => mockPreviousConversation,
}));
jest.mock('../Assistants/useAssistantListMap', () => ({
__esModule: true,
default: () => ({}),
}));
-jest.mock('../Files/useFileHandling', () => ({ clearUploadRecovery: jest.fn() }));
+jest.mock('../Files/useFileHandling', () => {
+ const actual = jest.requireActual('../Files/useFileHandling');
+ return { __esModule: true, ...actual, clearUploadRecovery: jest.fn(actual.clearUploadRecovery) };
+});
jest.mock('../Agents', () => ({ useApplyModelSpecEffects: () => jest.fn() }));
jest.mock('../Audio', () => ({ usePauseGlobalAudio: () => ({ pauseGlobalAudio: jest.fn() }) }));
-jest.mock('~/Providers', () => ({ useAgentsMapContext: () => ({}) }));
+jest.mock('~/Providers', () => ({
+ useAgentsMapContext: () => ({}),
+ useChatFormContext: () => ({ setValue: jest.fn() }),
+}));
jest.mock('~/hooks', () => ({ useHasAccess: () => true }));
jest.mock('~/store', () => ({
__esModule: true,
+ ephemeralAgentByConvoId: (id: string) => id,
default: {
defaultPreset: 'defaultPreset',
saveBadgesState: 'saveBadgesState',
@@ -164,6 +253,10 @@ describe('clearInheritedAgentWorkspace', () => {
describe('useNewConvo reset cleanup', () => {
beforeEach(() => {
jest.clearAllMocks();
+ localStorage.clear();
+ mockSaveDrafts = false;
+ mockPreviousConversation = null;
+ mockFileList = [];
mockDeleteFiles.mockResolvedValue({});
mockForeignClaims.clear();
mockMarkedPasteIds.clear();
@@ -187,6 +280,1468 @@ describe('useNewConvo reset cleanup', () => {
}
});
+ it.each(['before-ack', 'after-ack', 'later-disable'])(
+ 'keeps the accepted upload preference when completion is %s',
+ (order) => {
+ const sourceKey = `${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}new`;
+ const targetKey = `${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}assigned-preference`;
+ setFileSearchChoice('new', false);
+ localStorage.setItem(sourceKey, order === 'before-ack' ? 'true' : 'false');
+ transferFileSearchPreference('new', 'assigned-preference');
+ if (order === 'after-ack') localStorage.setItem(targetKey, 'true');
+ if (order === 'later-disable') setFileSearchChoice('assigned-preference', false);
+ expect(transferFileSearchPreference('new', 'assigned-preference')).toBe(
+ order !== 'later-disable',
+ );
+ expect(localStorage.getItem(targetKey)).toBe(JSON.stringify(order !== 'later-disable'));
+ },
+ );
+
+ it.each(
+ ['remove', 'replace'].flatMap((change) =>
+ [undefined, 'file_search'].map((resource) => ({ change, resource })),
+ ),
+ )('accepts a fresh $resource upload after project $change', async ({ change, resource }) => {
+ const { useFileHandlingNoChatContext } = await import('../Files/useFileHandling');
+ mockSaveDrafts = false;
+ mockFiles.clear();
+ mockConfigPending = false;
+ mockPreparationGate = undefined;
+ window.history.replaceState({}, '', '/c/new?projectId=project-a');
+ global.URL.createObjectURL = jest.fn(() => 'blob:project-change');
+ global.URL.revokeObjectURL = jest.fn();
+ const client = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, cacheTime: Infinity },
+ mutations: { retry: false },
+ },
+ });
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(QueryClientProvider, { client }, children);
+ const { result, rerender, unmount } = renderHook(
+ ({ projectId }: { projectId: string | null }) => {
+ const [files, setFiles] = useAtom(filesFamily(2));
+ useAutoSave({ index: 2, conversationId: 'new', files, setFiles });
+ return {
+ files,
+ handler: useFileHandlingNoChatContext(undefined, {
+ index: 2,
+ files,
+ setFiles,
+ conversation: {
+ conversationId: 'new',
+ endpoint: EModelEndpoint.openAI,
+ chatProjectId: projectId,
+ } as TConversation,
+ }),
+ };
+ },
+ { wrapper, initialProps: { projectId: 'project-a' as string | null } },
+ );
+ const previousOwner = captureComposerDraft(2, 'new');
+ const previousLaunch = { conversationId: 'new' };
+ bindComposerLaunch(previousLaunch, 2);
+ act(() => {
+ const projectId = change === 'replace' ? 'project-b' : null;
+ window.history.replaceState({}, '', projectId ? `/c/new?projectId=${projectId}` : '/c/new');
+ rerender({ projectId });
+ });
+ expect(previousOwner()).toBe(false);
+ const currentOwner = captureComposerDraft(2, 'new');
+ expect(currentOwner()).toBe(true);
+ await act(async () => {
+ expect(
+ await result.current.handler.handleFiles(
+ [new File(['project'], 'project.txt', { type: 'text/plain' })],
+ resource,
+ ),
+ ).toBe(true);
+ });
+ const body = mockUploadFile.mock.calls[0][0] as FormData;
+ expect(body.get('tool_resource')).toBe(resource ?? null);
+ await act(async () => {
+ mockUploadOptions.onSuccess?.(
+ {
+ file_id: 'persisted-project-upload',
+ temp_file_id: body.get('file_id'),
+ filename: 'project.txt',
+ filepath: '/files/project.txt',
+ type: 'text/plain',
+ embedded: resource === 'file_search',
+ },
+ body,
+ );
+ await new Promise((resolve) => setTimeout(resolve, 320));
+ });
+ expect(result.current.files.get(body.get('file_id') as string)?.progress).toBe(1);
+ expect(mockSetEphemeralAgent.mock.calls.length > 0).toBe(resource === 'file_search');
+ expect(adoptComposerConversation(previousLaunch, 'stale-project', 2)).toBe(false);
+ const launch = { conversationId: 'new' };
+ bindComposerLaunch(launch, 2);
+ expect(adoptComposerConversation(launch, 'fresh-project', 2)).toBe(true);
+ unmount();
+ client.clear();
+ window.history.replaceState({}, '', '/');
+ });
+
+ it.each(
+ [false, true].flatMap((saveDrafts) =>
+ [undefined, 'file_search'].map((resource) => ({ saveDrafts, resource })),
+ ),
+ )(
+ 'keeps acknowledged $resource completion before props catch up (saveDrafts: $saveDrafts)',
+ async ({ saveDrafts, resource }) => {
+ const { useFileHandlingNoChatContext } = await import('../Files/useFileHandling');
+ mockSaveDrafts = saveDrafts;
+ mockFiles.clear();
+ mockConfigPending = false;
+ mockPreparationGate = undefined;
+ window.history.replaceState({}, '', '/c/new');
+ global.URL.createObjectURL = jest.fn(() => 'blob:acknowledged-gap');
+ global.URL.revokeObjectURL = jest.fn();
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, cacheTime: Infinity } },
+ });
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(QueryClientProvider, { client }, children);
+ const { result, rerender, unmount } = renderHook(
+ ({ conversationId, tick }) => {
+ const [files, setFiles] = useAtom(filesFamily(2));
+ useAutoSave({ index: 2, conversationId, isSubmitting: true, files, setFiles });
+ return {
+ files,
+ tick,
+ handler: useFileHandlingNoChatContext(undefined, {
+ index: 2,
+ files,
+ setFiles,
+ conversation: { conversationId, endpoint: EModelEndpoint.openAI } as TConversation,
+ }),
+ };
+ },
+ { wrapper, initialProps: { conversationId: 'new', tick: 0 } },
+ );
+ const launch = { conversationId: 'new' };
+ bindComposerLaunch(launch, 2);
+ const captured = captureComposerDraft(2, 'new');
+ await act(async () => {
+ await result.current.handler.handleFiles(
+ [new File(['search'], 'ack.txt', { type: 'text/plain' })],
+ resource,
+ );
+ });
+ const body = mockUploadFile.mock.calls[0][0] as FormData;
+ const options = mockUploadOptions;
+ expect(adoptComposerConversation(launch, 'acknowledged-chat', 2)).toBe(true);
+ act(() => {
+ window.history.replaceState({}, '', '/c/acknowledged-chat');
+ rerender({ conversationId: 'new', tick: 1 });
+ });
+ expect(captured()).toBe(true);
+ expect(captured.conversationId()).toBe('acknowledged-chat');
+ expect(adoptComposerConversation(launch, 'acknowledged-chat', 2)).toBe(true);
+ act(() => rerender({ conversationId: 'acknowledged-chat', tick: 2 }));
+ mockSetEphemeralAgent.mockClear();
+ await act(async () => {
+ const persisted = {
+ file_id: 'persisted-ack',
+ temp_file_id: body.get('file_id'),
+ filepath: '/files/ack.txt',
+ filename: 'ack.txt',
+ type: 'text/plain',
+ bytes: 6,
+ embedded: resource === 'file_search',
+ };
+ mockFileList = [persisted];
+ options.onSuccess?.(persisted, body);
+ rerender({ conversationId: 'acknowledged-chat', tick: 3 });
+ await new Promise((resolve) => setTimeout(resolve, 320));
+ });
+ expect(result.current.files.get(body.get('file_id') as string)?.progress).toBe(1);
+ if (resource === 'file_search') {
+ expect(mockSetEphemeralAgent).toHaveBeenCalledWith(
+ 'acknowledged-chat',
+ expect.any(Function),
+ );
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalledWith('new', expect.anything());
+ } else expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ unmount();
+ client.clear();
+ window.history.replaceState({}, '', '/');
+ },
+ );
+
+ it.each(
+ [EModelEndpoint.assistants, EModelEndpoint.azureAssistants].flatMap((endpoint) =>
+ [false, true].map((reset) => ({ endpoint, reset })),
+ ),
+ )(
+ 'keeps only the bound upload through Assistants sync ($endpoint, reset: $reset)',
+ async ({ endpoint, reset }) => {
+ const { useFileHandlingNoChatContext } = await import('../Files/useFileHandling');
+ mockSaveDrafts = false;
+ mockFiles.clear();
+ mockConfigPending = false;
+ mockPreparationGate = undefined;
+ window.history.replaceState({}, '', '/c/new');
+ global.URL.createObjectURL = jest.fn(() => 'blob:assistants-sync');
+ global.URL.revokeObjectURL = jest.fn();
+ const client = new QueryClient({ defaultOptions: { queries: { retry: false } } });
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(QueryClientProvider, { client }, children);
+ const { result, rerender, unmount } = renderHook(
+ ({ conversationId }) => {
+ const [files, setFiles] = useAtom(filesFamily(2));
+ useAutoSave({ index: 2, conversationId, isSubmitting: true, files, setFiles });
+ const handlers = useTurnHandlers({
+ queryClient: client,
+ runIndex: 2,
+ isAddedRequest: false,
+ setMessages: jest.fn(),
+ getMessages: () => [],
+ setCompleted: jest.fn(),
+ setIsSubmitting: jest.fn(),
+ setShowStopButton: jest.fn(),
+ setAbortScroll: jest.fn(),
+ setSubmissionStart: jest.fn(),
+ announcePolite: jest.fn(),
+ lastAnnouncementTimeRef: { current: 0 },
+ applyAgentTemplate: jest.fn(),
+ focusRegeneratedResponse: jest.fn(),
+ location: {
+ pathname: window.location.pathname,
+ search: '',
+ hash: '',
+ state: null,
+ key: 'sync',
+ },
+ navigate: jest.fn(),
+ restorePendingContext: jest.fn(),
+ reconcileFailedCodeDecision: jest.fn(),
+ recoverConversation: jest.fn(),
+ attachmentHandler: jest.fn(),
+ preserveSubagentAtomsForNewConvoIdRef: { current: null },
+ });
+ return {
+ files,
+ handlers,
+ upload: useFileHandlingNoChatContext(undefined, {
+ index: 2,
+ files,
+ setFiles,
+ conversation: {
+ conversationId,
+ endpoint,
+ assistant_id: 'assistant-sync',
+ model: 'gpt-4o',
+ } as TConversation,
+ }),
+ };
+ },
+ { wrapper, initialProps: { conversationId: 'new' } },
+ );
+ const launch = { conversationId: 'new', endpoint };
+ bindComposerLaunch(launch, 2);
+ const owner = captureComposerDraft(2, 'new');
+ await act(async () => {
+ await result.current.upload.handleFiles([
+ new File(['sync'], 'sync.txt', { type: 'text/plain' }),
+ ]);
+ });
+ const body = mockUploadFile.mock.calls[0][0] as FormData;
+ expect(body.get('assistant_id')).toBe('assistant-sync');
+ const options = mockUploadOptions;
+ const next = renderHook(() => useNewConvo(2), { wrapper });
+ if (reset) act(() => next.result.current.newConversation());
+ const submission: EventSubmission = {
+ isTemporary: false,
+ endpointOption: { endpoint },
+ conversation: launch,
+ messages: [],
+ userMessage: {
+ messageId: 'sync-user',
+ conversationId: 'saved-sync',
+ parentMessageId: String(Constants.NO_PARENT),
+ title: 'New Chat',
+ text: 'Hello',
+ isCreatedByUser: true,
+ createdAt: '',
+ updatedAt: '',
+ },
+ initialResponse: {
+ messageId: 'sync-response',
+ conversationId: 'saved-sync',
+ parentMessageId: 'sync-user',
+ title: 'New Chat',
+ text: '',
+ isCreatedByUser: false,
+ createdAt: '',
+ updatedAt: '',
+ },
+ };
+ act(() => {
+ result.current.handlers.syncHandler(
+ {
+ sync: true,
+ conversationId: 'saved-sync',
+ thread_id: 'thread-sync',
+ requestMessage: submission.userMessage,
+ responseMessage: submission.initialResponse,
+ },
+ submission,
+ );
+ window.history.replaceState({}, '', '/c/saved-sync');
+ rerender({ conversationId: 'saved-sync' });
+ });
+ expect(owner()).toBe(!reset);
+ await act(async () => {
+ options.onSuccess?.({ file_id: 'persisted-sync', filepath: '/files/sync.txt' }, body);
+ await new Promise((resolve) => setTimeout(resolve, 320));
+ });
+ if (reset) expect(result.current.files.size).toBe(0);
+ else expect(result.current.files.get(body.get('file_id') as string)?.progress).toBe(1);
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ next.unmount();
+ unmount();
+ client.clear();
+ window.history.replaceState({}, '', '/');
+ },
+ );
+
+ it.each(
+ [false, true].flatMap((saveDrafts) =>
+ ['remove', 'replace'].flatMap((change) =>
+ [undefined, 'file_search'].map((resource) => ({ saveDrafts, change, resource })),
+ ),
+ ),
+ )(
+ 'discards only the retired $resource project upload after $change (saveDrafts: $saveDrafts)',
+ async ({ saveDrafts, change, resource }) => {
+ const { useFileHandlingNoChatContext } = await import('../Files/useFileHandling');
+ mockSaveDrafts = saveDrafts;
+ mockFiles.clear();
+ mockConfigPending = false;
+ mockPreparationGate = undefined;
+ window.history.replaceState({}, '', '/c/new?projectId=project-a');
+ global.URL.createObjectURL = jest.fn(() => 'blob:retired-project');
+ global.URL.revokeObjectURL = jest.fn();
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, cacheTime: Infinity } },
+ });
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(QueryClientProvider, { client }, children);
+ const { result, rerender, unmount } = renderHook(
+ ({ projectId, tick }) => {
+ const [files, setFiles] = useAtom(filesFamily(2));
+ useAutoSave({ index: 2, conversationId: 'new', files, setFiles });
+ return {
+ files,
+ tick,
+ handler: useFileHandlingNoChatContext(undefined, {
+ index: 2,
+ files,
+ setFiles,
+ conversation: {
+ conversationId: 'new',
+ endpoint: EModelEndpoint.openAI,
+ chatProjectId: projectId,
+ } as TConversation,
+ }),
+ };
+ },
+ { wrapper, initialProps: { projectId: 'project-a' as string | null, tick: 0 } },
+ );
+ const owner = captureComposerDraft(2, 'new');
+ const completed = { file_id: 'kept-completed', progress: 1, size: 1, attached: true };
+ act(() => {
+ getDefaultStore().set(filesFamily(2), new Map([['kept-completed', completed]]));
+ });
+ await act(async () => {
+ await result.current.handler.handleFiles(
+ [new File(['search'], 'retired.txt', { type: 'text/plain' })],
+ resource,
+ );
+ });
+ const body = mockUploadFile.mock.calls[0][0] as FormData;
+ const options = mockUploadOptions;
+ const projectId = change === 'replace' ? 'project-b' : null;
+ act(() => {
+ window.history.replaceState({}, '', projectId ? `/c/new?projectId=${projectId}` : '/c/new');
+ rerender({ projectId, tick: 1 });
+ });
+ expect(owner()).toBe(false);
+ const retiredId = body.get('file_id') as string;
+ expect(result.current.files.has(retiredId)).toBe(false);
+ expect(result.current.files.get('kept-completed')).toEqual(completed);
+ await act(async () => {
+ await result.current.handler.handleFiles(
+ [new File(['fresh'], 'fresh.txt', { type: 'text/plain' })],
+ resource,
+ );
+ });
+ const freshBody = mockUploadFile.mock.calls[1][0] as FormData;
+ const freshId = freshBody.get('file_id') as string;
+ const fresh = result.current.files.get(freshId);
+ expect(fresh).toBeDefined();
+ mockSetEphemeralAgent.mockClear();
+ const persisted = {
+ file_id: 'persisted-retired',
+ temp_file_id: body.get('file_id'),
+ filepath: '/files/retired.txt',
+ filename: 'retired.txt',
+ type: 'text/plain',
+ bytes: 6,
+ embedded: resource === 'file_search',
+ llmDeliveryPath: 'none',
+ };
+ // The real mutation caches the response before invoking its success callback.
+ await act(async () => {
+ mockFileList = [persisted];
+ rerender({ projectId, tick: 2 });
+ });
+ await act(async () => {
+ options.onSuccess?.(persisted, body);
+ await new Promise((resolve) => setTimeout(resolve, 320));
+ });
+ expect(result.current.files.has(retiredId)).toBe(false);
+ expect(result.current.files.get('kept-completed')).toEqual(completed);
+ expect(result.current.files.get(freshId)).toBe(fresh);
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ expect(localStorage.getItem(`${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}new`)).not.toBe(
+ 'true',
+ );
+ unmount();
+ client.clear();
+ window.history.replaceState({}, '', '/');
+ },
+ );
+
+ it.each([false, true])(
+ 'activates after navigation only when the owning saved draft retains the upload (%s)',
+ async (retained) => {
+ const { useFileHandlingNoChatContext } = await import('../Files/useFileHandling');
+ mockSaveDrafts = retained;
+ mockFiles.clear();
+ mockConfigPending = false;
+ window.history.replaceState({}, '', '/c/retained-origin');
+ global.URL.createObjectURL = jest.fn(() => 'blob:retained-origin');
+ global.URL.revokeObjectURL = jest.fn();
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, cacheTime: Infinity } },
+ });
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(QueryClientProvider, { client }, children);
+ const { result, rerender, unmount } = renderHook(
+ ({ conversationId, tick }) => {
+ const [files, setFiles] = useAtom(filesFamily(2));
+ useAutoSave({ index: 2, conversationId, files, setFiles });
+ return {
+ files,
+ tick,
+ handler: useFileHandlingNoChatContext(undefined, {
+ index: 2,
+ files,
+ setFiles,
+ conversation: { conversationId, endpoint: EModelEndpoint.openAI } as TConversation,
+ }),
+ };
+ },
+ { wrapper, initialProps: { conversationId: 'retained-origin', tick: 0 } },
+ );
+ await act(async () => {
+ await result.current.handler.handleFiles(
+ [new File(['search'], 'retained.txt', { type: 'text/plain' })],
+ 'file_search',
+ );
+ });
+ const body = mockUploadFile.mock.calls[0][0] as FormData;
+ const options = mockUploadOptions;
+ act(() => {
+ window.history.pushState({}, '', '/c/destination');
+ rerender({ conversationId: 'destination', tick: 1 });
+ });
+ mockSetEphemeralAgent.mockClear();
+ await act(async () => {
+ const persisted = {
+ file_id: 'persisted-retained',
+ temp_file_id: body.get('file_id'),
+ filepath: '/files/retained.txt',
+ filename: 'retained.txt',
+ type: 'text/plain',
+ bytes: 6,
+ embedded: true,
+ };
+ mockFileList = [persisted];
+ rerender({ conversationId: 'destination', tick: 2 });
+ options.onSuccess?.(persisted, body);
+ await new Promise((resolve) => setTimeout(resolve, 320));
+ });
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalledWith('destination', expect.anything());
+ if (retained)
+ expect(mockSetEphemeralAgent).toHaveBeenCalledWith('retained-origin', expect.any(Function));
+ else expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ unmount();
+ client.clear();
+ window.history.replaceState({}, '', '/');
+ },
+ );
+
+ it.each([false, true])(
+ 'keeps the live completion fence when intent storage is blocked (retire: %s)',
+ (retire) => {
+ window.history.replaceState({}, '', '/c/new?projectId=source-project');
+ const release = registerComposerDraft(28, 'new', 'new:28', {});
+ const owner = captureComposerDraft(28, 'new');
+ const write = Storage.prototype.setItem;
+ const unavailable = jest.spyOn(Storage.prototype, 'setItem').mockImplementation(function (
+ this: Storage,
+ key: string,
+ value: string,
+ ) {
+ if (key.startsWith('file-search-upload:')) throw new Error('Intent storage unavailable');
+ write.call(this, key, value);
+ });
+ const intent = beginFileSearchUpload('blocked-owner', captureFileSearchUpload('new', owner));
+ expect(intent.persisted).toBe(false);
+ // Cache restoration lacks a fallback revision; it cannot consume the mutation's live fence.
+ expect(completeFileSearchUpload('blocked-owner', 'new')).toBe(false);
+ let releaseReplacement: (() => void) | undefined;
+ if (retire) {
+ window.history.replaceState({}, '', '/c/new?projectId=replacement');
+ release();
+ releaseReplacement = registerComposerDraft(28, 'new', 'new:28', {});
+ }
+ expect(completeFileSearchUpload('blocked-owner', 'new', intent.choiceRevision)).toBe(!retire);
+ unavailable.mockRestore();
+ releaseReplacement?.();
+ release();
+ window.history.replaceState({}, '', '/');
+ },
+ );
+
+ it.each([false, true])(
+ 'restores persisted intent only in its original new-chat project (%s)',
+ (sameProject) => {
+ window.history.replaceState({}, '', '/c/new?projectId=original-project');
+ beginFileSearchUpload('persisted-project-intent', 'new');
+ if (!sameProject) window.history.replaceState({}, '', '/c/new?projectId=other-project');
+ expect(completeFileSearchUpload('persisted-project-intent', 'new')).toBe(sameProject);
+ window.history.replaceState({}, '', '/');
+ },
+ );
+
+ it('rejects a late upload after browser history returns to its acknowledged source URL', async () => {
+ const { useFileHandlingNoChatContext } = await import('../Files/useFileHandling');
+ mockSaveDrafts = false;
+ mockFiles.clear();
+ mockConfigPending = false;
+ window.history.replaceState({}, '', '/c/new');
+ global.URL.createObjectURL = jest.fn(() => 'blob:history-source');
+ global.URL.revokeObjectURL = jest.fn();
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, cacheTime: Infinity } },
+ });
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(QueryClientProvider, { client }, children);
+ const { result, rerender, unmount } = renderHook(
+ ({ conversationId }) => {
+ const [files, setFiles] = useAtom(filesFamily(2));
+ useAutoSave({ index: 2, conversationId, files, setFiles });
+ return {
+ files,
+ handler: useFileHandlingNoChatContext(undefined, {
+ index: 2,
+ files,
+ setFiles,
+ conversation: { conversationId, endpoint: EModelEndpoint.openAI } as TConversation,
+ }),
+ };
+ },
+ { wrapper, initialProps: { conversationId: 'new' } },
+ );
+ const launch = { conversationId: 'new' };
+ bindComposerLaunch(launch, 2);
+ const owner = captureComposerDraft(2, 'new');
+ await act(async () => {
+ await result.current.handler.handleFiles(
+ [new File(['search'], 'history.txt', { type: 'text/plain' })],
+ 'file_search',
+ );
+ });
+ const body = mockUploadFile.mock.calls[0][0] as FormData;
+ const options = mockUploadOptions;
+ expect(adoptComposerConversation(launch, 'saved-history', 2)).toBe(true);
+ act(() => {
+ window.history.replaceState({}, '', '/c/saved-history');
+ rerender({ conversationId: 'saved-history' });
+ });
+ expect(owner()).toBe(true);
+ // Browser history changes before React reconciles the old conversation prop.
+ window.history.pushState({}, '', '/c/new');
+ expect(owner()).toBe(false);
+ expect(owner.retainsFile(body.get('file_id') as string)).toBe(false);
+ expect(adoptComposerConversation(launch, 'saved-history', 2)).toBe(false);
+ mockSetEphemeralAgent.mockClear();
+ await act(async () => {
+ options.onSuccess?.(
+ {
+ file_id: 'history-persisted',
+ temp_file_id: body.get('file_id'),
+ filepath: '/files/history',
+ embedded: true,
+ },
+ body,
+ );
+ await new Promise((resolve) => setTimeout(resolve, 320));
+ });
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ expect(result.current.files.has(body.get('file_id') as string)).toBe(false);
+ unmount();
+ client.clear();
+ window.history.replaceState({}, '', '/');
+ });
+
+ it.each(
+ ['reset', 'live', 'saved'].flatMap((origin) =>
+ ['cache-first', 'success-first', 'batched'].map((order) => ({ origin, order })),
+ ),
+ )(
+ 'restores only owned uploads after composer replacement ($origin, $order)',
+ async ({ origin, order }) => {
+ const { useFileHandlingNoChatContext } = await import('../Files/useFileHandling');
+ mockSaveDrafts = true;
+ mockFiles.clear();
+ mockConfigPending = false;
+ const conversationId = origin === 'saved' ? 'saved-cache-origin' : 'new';
+ mockPreviousConversation = { conversationId, endpoint: EModelEndpoint.openAI };
+ window.history.replaceState({}, '', `/c/${conversationId}`);
+ global.URL.createObjectURL = jest.fn(() => 'blob:reset-cache');
+ global.URL.revokeObjectURL = jest.fn();
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, cacheTime: Infinity } },
+ });
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(QueryClientProvider, { client }, children);
+ const composer = renderHook(
+ ({ conversationId, tick }) => {
+ const [files, setFiles] = useAtom(filesFamily(2));
+ useAutoSave({ index: 2, conversationId, files, setFiles });
+ return {
+ files,
+ tick,
+ handler: useFileHandlingNoChatContext(undefined, {
+ index: 2,
+ files,
+ setFiles,
+ conversation: { conversationId, endpoint: EModelEndpoint.openAI } as TConversation,
+ }),
+ };
+ },
+ { wrapper, initialProps: { conversationId, tick: 0 } },
+ );
+ await act(async () => {
+ await composer.result.current.handler.handleFiles(
+ [new File(['search'], 'reset-cache.txt', { type: 'text/plain' })],
+ 'file_search',
+ );
+ });
+ const body = mockUploadFile.mock.calls[0][0] as FormData;
+ const fileId = body.get('file_id') as string;
+ const options = mockUploadOptions;
+ expect(getFilesDraft(origin === 'saved' ? conversationId : 'new:2').fileIds).toContain(
+ fileId,
+ );
+ const persisted = {
+ file_id: 'reset-cache-persisted',
+ temp_file_id: fileId,
+ filepath: '/files/reset-cache',
+ filename: 'reset-cache.txt',
+ type: 'text/plain',
+ bytes: 6,
+ embedded: true,
+ llmDeliveryPath: 'none',
+ };
+ const next = renderHook(() => useNewConvo(2), { wrapper });
+ const reset = () => {
+ if (origin === 'live') return;
+ window.history.replaceState({}, '', '/c/new');
+ next.result.current.newConversation({ preset: { endpoint: EModelEndpoint.openAI } });
+ composer.rerender({ conversationId: 'new', tick: 1 });
+ };
+ const cache = () => {
+ mockFileList = [persisted];
+ composer.rerender({ conversationId: 'new', tick: 2 });
+ };
+ if (order === 'batched') {
+ await act(async () => {
+ reset();
+ options.onSuccess?.(persisted, body);
+ cache();
+ });
+ } else {
+ act(reset);
+ if (order === 'cache-first') {
+ act(cache);
+ act(() => options.onSuccess?.(persisted, body));
+ } else {
+ act(() => options.onSuccess?.(persisted, body));
+ act(cache);
+ }
+ }
+ await act(async () => {
+ await new Promise((resolve) => setTimeout(resolve, 320));
+ });
+ if (origin === 'live') {
+ expect(composer.result.current.files.get(fileId)?.progress).toBe(1);
+ expect(mockSetEphemeralAgent).toHaveBeenCalledWith('new', expect.any(Function));
+ } else {
+ expect(composer.result.current.files.size).toBe(0);
+ expect(getFilesDraft('new:2').fileIds).not.toContain(fileId);
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalledWith('new', expect.anything());
+ }
+ if (origin === 'saved') {
+ composer.unmount();
+ window.history.replaceState({}, '', `/c/${conversationId}`);
+ const restored = renderHook(
+ () => {
+ const [files, setFiles] = React.useState<Map<string, ExtendedFile>>(new Map());
+ useAutoSave({ index: 2, conversationId, files, setFiles });
+ return files;
+ },
+ { wrapper },
+ );
+ expect(restored.result.current.get(fileId)?.progress).toBe(1);
+ expect(mockSetEphemeralAgent).toHaveBeenCalledWith(conversationId, expect.any(Function));
+ restored.unmount();
+ }
+ next.unmount();
+ composer.unmount();
+ client.clear();
+ window.history.replaceState({}, '', '/');
+ },
+ );
+
+ it.each(['bootstrap', 'metadata', 'reset'])(
+ 'preserves logical composer ownership only for passive initialization (%s)',
+ (action) => {
+ mockFiles.clear();
+ window.history.replaceState({}, '', '/c/new?projectId=bootstrap-project');
+ const release = registerComposerDraft(2, 'new', 'new:2', {});
+ const owner = captureComposerDraft(2, 'new');
+ beginFileSearchUpload('bootstrap-file', captureFileSearchUpload('new', owner));
+ const client = new QueryClient();
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(QueryClientProvider, { client }, children);
+ const initialized = renderHook(() => useNewConvo(2), { wrapper });
+ const options = {
+ template: { chatProjectId: 'bootstrap-project' },
+ ...(action === 'bootstrap' ? { modelsData: {} } : {}),
+ ...(action === 'metadata' ? { keepComposerState: true } : {}),
+ };
+ act(() => {
+ initialized.result.current.newConversation(options);
+ initialized.result.current.newConversation(options);
+ });
+ expect(owner()).toBe(action !== 'reset');
+ expect(completeFileSearchUpload('bootstrap-file', 'new')).toBe(action !== 'reset');
+ initialized.unmount();
+ release();
+ client.clear();
+ window.history.replaceState({}, '', '/');
+ },
+ );
+
+ it.each(['project', 'answer', 'teardown', 'saved'])(
+ 'keeps logical ownership retirement across reload (%s)',
+ async (boundary) => {
+ const saved = boundary === 'saved';
+ const conversationId = saved ? 'saved-reload-owner' : 'new';
+ window.history.replaceState({}, '', '/c/new?projectId=original');
+ const host = {};
+ const release = registerComposerDraft(
+ 34,
+ conversationId,
+ saved ? conversationId : 'new:34',
+ host,
+ );
+ const owner = captureComposerDraft(34, conversationId);
+ beginFileSearchUpload('reload-logical-owner', captureFileSearchUpload(conversationId, owner));
+ release();
+ let releaseReplacement: (() => void) | undefined;
+ if (boundary === 'project') {
+ window.history.replaceState({}, '', '/c/new?projectId=replacement');
+ releaseReplacement = registerComposerDraft(34, 'new', 'new:34', host);
+ } else if (boundary === 'answer') {
+ releaseReplacement = registerComposerDraft(
+ 34,
+ 'new',
+ getAskAnswerDraftId('reload-answer'),
+ host,
+ );
+ }
+ await Promise.resolve();
+ window.history.replaceState({}, '', '/c/new?projectId=original');
+ const navigation = Object.getOwnPropertyDescriptor(performance, 'getEntriesByType');
+ Object.defineProperty(performance, 'getEntriesByType', {
+ configurable: true,
+ value: () => [{ type: 'reload' }],
+ });
+ try {
+ jest.isolateModules(() => {
+ const reloaded = jest.requireActual<typeof import('../Files/search')>('../Files/search');
+ expect(reloaded.completeFileSearchUpload('reload-logical-owner', conversationId)).toBe(
+ saved,
+ );
+ });
+ } finally {
+ if (navigation) Object.defineProperty(performance, 'getEntriesByType', navigation);
+ else Reflect.deleteProperty(performance, 'getEntriesByType');
+ releaseReplacement?.();
+ window.history.replaceState({}, '', '/');
+ }
+ },
+ );
+
+ it.each(
+ [false, true].flatMap((reset) => [false, true].map((bootstrap) => ({ reset, bootstrap }))),
+ )(
+ 'keeps new-chat intent ownership after reload (reset: $reset, bootstrap: $bootstrap)',
+ async ({ reset, bootstrap }) => {
+ const { useFileHandlingNoChatContext } = await import('../Files/useFileHandling');
+ mockSaveDrafts = true;
+ mockFiles.clear();
+ mockConfigPending = false;
+ mockPreviousConversation = { conversationId: 'new', endpoint: EModelEndpoint.openAI };
+ window.history.replaceState({}, '', '/c/new?projectId=reload-project');
+ global.URL.createObjectURL = jest.fn(() => 'blob:reset-reload');
+ global.URL.revokeObjectURL = jest.fn();
+ const client = new QueryClient({
+ defaultOptions: { queries: { retry: false, cacheTime: Infinity } },
+ });
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(QueryClientProvider, { client }, children);
+ const composer = renderHook(
+ () => {
+ const [files, setFiles] = useAtom(filesFamily(2));
+ useAutoSave({ index: 2, conversationId: 'new', files, setFiles });
+ return {
+ files,
+ handler: useFileHandlingNoChatContext(undefined, {
+ index: 2,
+ files,
+ setFiles,
+ conversation: {
+ conversationId: 'new',
+ endpoint: EModelEndpoint.openAI,
+ chatProjectId: 'reload-project',
+ } as TConversation,
+ }),
+ };
+ },
+ { wrapper },
+ );
+ await act(async () => {
+ await composer.result.current.handler.handleFiles(
+ [new File(['search'], 'reload.txt', { type: 'text/plain' })],
+ 'file_search',
+ );
+ });
+ const body = mockUploadFile.mock.calls[0][0] as FormData;
+ const fileId = body.get('file_id') as string;
+ if (reset) {
+ const next = renderHook(() => useNewConvo(2), { wrapper });
+ act(() =>
+ next.result.current.newConversation({ template: { chatProjectId: 'reload-project' } }),
+ );
+ next.unmount();
+ }
+ composer.unmount();
+ if (bootstrap) {
+ const initialized = renderHook(() => useNewConvo(2), { wrapper });
+ act(() =>
+ initialized.result.current.newConversation({
+ modelsData: {},
+ template: { chatProjectId: 'reload-project' },
+ }),
+ );
+ initialized.unmount();
+ }
+ // Re-execute the real intent module with no live assignments map, preserving browser storage.
+ const navigationDescriptor = Object.getOwnPropertyDescriptor(performance, 'getEntriesByType');
+ Object.defineProperty(performance, 'getEntriesByType', {
+ configurable: true,
+ value: () => [{ type: 'reload' }],
+ });
+ try {
+ jest.isolateModules(() => {
+ const reloaded = jest.requireActual<typeof import('../Files/search')>('../Files/search');
+ expect(reloaded.completeFileSearchUpload(fileId, 'new')).toBe(!reset);
+ });
+ } finally {
+ if (navigationDescriptor)
+ Object.defineProperty(performance, 'getEntriesByType', navigationDescriptor);
+ else Reflect.deleteProperty(performance, 'getEntriesByType');
+ }
+ expect(
+ localStorage.getItem(`${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}new`) === 'true',
+ ).toBe(!reset);
+ client.clear();
+ window.history.replaceState({}, '', '/');
+ },
+ );
+
+ it.each([false, true])(
+ 'completes the next first-ID upload after a same-route reset (saveDrafts: %s)',
+ async (saveDrafts) => {
+ const { useFileHandlingNoChatContext } = await import('../Files/useFileHandling');
+ mockSaveDrafts = saveDrafts;
+ mockFiles.clear();
+ mockPreviousConversation = {
+ conversationId: 'new',
+ endpoint: EModelEndpoint.openAI,
+ };
+ window.history.replaceState({}, '', '/c/new');
+ global.URL.createObjectURL = jest.fn(() => 'blob:reset-generation');
+ global.URL.revokeObjectURL = jest.fn();
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, cacheTime: Infinity },
+ mutations: { retry: false },
+ },
+ });
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(QueryClientProvider, { client: queryClient }, children);
+ const { result, rerender, unmount } = renderHook(
+ ({ conversationId, isSubmitting }) => {
+ const [files, setFiles] = useAtom(filesFamily(2));
+ useAutoSave({ index: 2, conversationId, isSubmitting, files, setFiles });
+ return {
+ files,
+ handler: useFileHandlingNoChatContext(undefined, {
+ index: 2,
+ files,
+ setFiles,
+ conversation: { conversationId, endpoint: EModelEndpoint.openAI } as TConversation,
+ }),
+ };
+ },
+ { wrapper, initialProps: { conversationId: 'new', isSubmitting: false } },
+ );
+ const oldLaunch = { conversationId: 'new' };
+ bindComposerLaunch(oldLaunch, 2);
+ const next = renderHook(() => useNewConvo(2), { wrapper });
+ const launch = { conversationId: 'new' };
+ act(() => {
+ next.result.current.newConversation();
+ bindComposerLaunch(launch, 2);
+ });
+ expect(adoptComposerConversation(oldLaunch, 'stale-generation', 2)).toBe(false);
+ act(() => rerender({ conversationId: 'new', isSubmitting: true }));
+ await act(async () => {
+ expect(
+ await result.current.handler.handleFiles(
+ [new File(['search'], 'reset.txt', { type: 'text/plain' })],
+ 'file_search',
+ ),
+ ).toBe(true);
+ });
+ const body = mockUploadFile.mock.calls[0][0] as FormData;
+ const options = mockUploadOptions;
+ expect(adoptComposerConversation(launch, 'saved-after-reset', 2)).toBe(true);
+ act(() => rerender({ conversationId: 'saved-after-reset', isSubmitting: false }));
+ mockSetEphemeralAgent.mockClear();
+ await act(async () => {
+ const persisted = {
+ temp_file_id: body.get('file_id'),
+ file_id: 'persisted-after-reset',
+ filename: 'reset.txt',
+ filepath: '/files/reset.txt',
+ type: 'text/plain',
+ bytes: 6,
+ embedded: true,
+ };
+ mockFileList = [persisted];
+ options.onSuccess?.(persisted, body);
+ rerender({ conversationId: 'saved-after-reset', isSubmitting: false });
+ await new Promise((resolve) => setTimeout(resolve, 320));
+ });
+ expect(result.current.files.get(body.get('file_id') as string)?.progress).toBe(1);
+ expect(mockSetEphemeralAgent).toHaveBeenCalledWith('saved-after-reset', expect.any(Function));
+ expect(localStorage.getItem(`${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}new`)).not.toBe(
+ 'true',
+ );
+ expect(
+ localStorage.getItem(`${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}saved-after-reset`),
+ ).toBe('true');
+ next.unmount();
+ unmount();
+ queryClient.clear();
+ window.history.replaceState({}, '', '/');
+ },
+ );
+
+ it.each(['upload', 'composer'])(
+ 'keeps acknowledged first-ID completion when the %s host remounts',
+ async (remount) => {
+ const { useFileHandlingNoChatContext } = await import('../Files/useFileHandling');
+ mockSaveDrafts = false;
+ mockFiles.clear();
+ mockConfigPending = false;
+ global.URL.createObjectURL = jest.fn(() => 'blob:remount');
+ global.URL.revokeObjectURL = jest.fn();
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, cacheTime: Infinity },
+ mutations: { retry: false },
+ },
+ });
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(QueryClientProvider, { client: queryClient }, children);
+ const useDraft = ({ conversationId }: { conversationId: string }) => {
+ const [files, setFiles] = useAtom(filesFamily(2));
+ useAutoSave({ index: 2, conversationId, files, setFiles });
+ return { files, setFiles };
+ };
+ let draft = renderHook(useDraft, { wrapper, initialProps: { conversationId: 'new' } });
+ const upload = renderHook(
+ () =>
+ useFileHandlingNoChatContext(undefined, {
+ index: 2,
+ ...draft.result.current,
+ conversation: {
+ conversationId: 'new',
+ endpoint: EModelEndpoint.openAI,
+ } as TConversation,
+ }),
+ { wrapper },
+ );
+ const launch = { conversationId: 'new' };
+ bindComposerLaunch(launch, 2);
+ await act(async () => {
+ await upload.result.current.handleFiles(
+ [new File(['file'], 'remount.txt', { type: 'text/plain' })],
+ 'file_search',
+ );
+ });
+ const body = mockUploadFile.mock.calls[0][0] as FormData;
+ const options = mockUploadOptions;
+ expect(adoptComposerConversation(launch, 'saved-remount', 2)).toBe(true);
+ act(() => draft.rerender({ conversationId: 'saved-remount' }));
+ upload.unmount();
+ if (remount === 'composer') {
+ draft.unmount();
+ draft = renderHook(useDraft, {
+ wrapper,
+ initialProps: { conversationId: 'saved-remount' },
+ });
+ }
+ const replacement = renderHook(
+ () =>
+ useFileHandlingNoChatContext(undefined, {
+ index: 2,
+ ...draft.result.current,
+ conversation: {
+ conversationId: 'saved-remount',
+ endpoint: EModelEndpoint.openAI,
+ } as TConversation,
+ }),
+ { wrapper },
+ );
+ await act(async () => {
+ options.onSuccess?.(
+ {
+ temp_file_id: body.get('file_id'),
+ file_id: 'persisted-remount',
+ filename: 'remount.txt',
+ filepath: '/files/remount',
+ type: 'text/plain',
+ embedded: true,
+ },
+ body,
+ );
+ await new Promise((resolve) => setTimeout(resolve, 320));
+ });
+ expect(draft.result.current.files.get(body.get('file_id') as string)?.progress).toBe(1);
+ replacement.unmount();
+ draft.unmount();
+ queryClient.clear();
+ },
+ );
+
+ it.each([
+ 'pending-no-drafts',
+ 'assigned',
+ 'assigned-disable',
+ 'source-disable',
+ 'unrelated-navigation',
+ ])('keeps logical upload ownership through %s', async (mode) => {
+ const { useFileHandlingNoChatContext } = await import('../Files/useFileHandling');
+ mockConfigPending = false;
+ mockPreparationGate = undefined;
+ mockFiles.clear();
+ mockSaveDrafts = mode !== 'pending-no-drafts';
+ const sourceId = mode === 'pending-no-drafts' ? 'existing-chat' : 'new';
+ const sourceConversation = { conversationId: sourceId };
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, cacheTime: Infinity },
+ mutations: { retry: false },
+ },
+ });
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(QueryClientProvider, { client: queryClient }, children);
+ global.URL.createObjectURL = jest.fn(() => 'blob:logical');
+ global.URL.revokeObjectURL = jest.fn();
+ const { result, rerender, unmount } = renderHook(
+ ({ conversationId, isSubmitting }) => {
+ const [files, setFiles] = useAtom(filesFamily(2));
+ useAutoSave({ index: 2, conversationId, isSubmitting, files, setFiles });
+ return {
+ files,
+ handler: useFileHandlingNoChatContext(undefined, {
+ index: 2,
+ files,
+ setFiles,
+ conversation: { conversationId, endpoint: EModelEndpoint.openAI } as TConversation,
+ }),
+ };
+ },
+ { wrapper, initialProps: { conversationId: sourceId, isSubmitting: true } },
+ );
+ if (mode !== 'pending-no-drafts') bindComposerLaunch(sourceConversation, 2);
+ await act(async () => {
+ expect(
+ await result.current.handler.handleFiles(
+ [new File(['text'], 'logical.txt', { type: 'text/plain' })],
+ 'file_search',
+ ),
+ ).toBe(true);
+ });
+ const body = mockUploadFile.mock.calls[0][0] as FormData;
+ const options = mockUploadOptions;
+ const targetId = mode === 'pending-no-drafts' ? sourceId : 'saved-chat';
+ if (mode !== 'pending-no-drafts' && mode !== 'unrelated-navigation') {
+ expect(adoptComposerConversation(sourceConversation, targetId, 2)).toBe(true);
+ transferFileSearchChoice('new', targetId);
+ }
+ act(() => rerender({ conversationId: targetId, isSubmitting: false }));
+ if (mode === 'assigned-disable') setFileSearchChoice(targetId, false);
+ if (mode === 'source-disable') setFileSearchChoice('new', false);
+ mockSetEphemeralAgent.mockClear();
+ await act(async () => {
+ const persisted = {
+ temp_file_id: body.get('file_id'),
+ file_id: 'server-file',
+ filepath: '/files/logical',
+ filename: 'logical.txt',
+ type: 'text/plain',
+ bytes: 4,
+ embedded: true,
+ };
+ mockFileList = [persisted];
+ options.onSuccess?.(persisted, body);
+ rerender({ conversationId: targetId, isSubmitting: false });
+ await new Promise((resolve) => setTimeout(resolve, 320));
+ });
+ if (mode === 'pending-no-drafts' || mode === 'assigned') {
+ expect(result.current.files.get(body.get('file_id') as string)?.progress).toBe(1);
+ expect(mockSetEphemeralAgent).toHaveBeenCalledWith(targetId, expect.any(Function));
+ expect(localStorage.getItem(`${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}${targetId}`)).toBe(
+ 'true',
+ );
+ } else if (mode !== 'unrelated-navigation')
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ if (mode !== 'pending-no-drafts' && mode !== 'unrelated-navigation')
+ expect(localStorage.getItem(`${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}new`)).not.toBe(
+ 'true',
+ );
+ unmount();
+ queryClient.clear();
+ });
+
+ it.each(
+ [
+ 'config',
+ 'queue',
+ 'sharepoint',
+ 'sharepoint-no-context',
+ 'heic',
+ 'decode',
+ 'route',
+ 'answer',
+ 'unmount',
+ ].flatMap((boundary) => ['new', 'origin'].map((origin) => ({ boundary, origin }))),
+ )(
+ 'abandons $boundary upload after $origin composer resets before staging',
+ async ({ boundary, origin }) => {
+ const { useFileHandlingNoChatContext } = await import('../Files/useFileHandling');
+ const { default: useSharePoint, useSharePointFileHandlingNoChatContext } = await import(
+ '../Files/useSharePointFileHandling'
+ );
+ const { ChatContext } = await import('~/Providers/ChatContext');
+ let release: () => void = () => undefined;
+ mockPreparationGate = new Promise<void>((resolve) => {
+ release = resolve;
+ });
+ mockConfigPending = ['config', 'queue', 'route', 'answer', 'unmount'].includes(boundary);
+ mockSaveDrafts = true;
+ mockPreviousConversation = { conversationId: origin, endpoint: EModelEndpoint.openAI };
+ mockFiles.clear();
+ global.URL.createObjectURL = jest.fn(() => 'blob:deferred');
+ global.URL.revokeObjectURL = jest.fn();
+ mockDownloadedFiles = [new File(['search'], 'search.txt', { type: 'text/plain' })];
+ mockConvertFile.mockImplementation(async (file, _quality, onProgress) => {
+ await mockPreparationGate;
+ onProgress?.(0.8);
+ return file;
+ });
+ const imageCallbacks: (() => void)[] = [];
+ const originalImage = global.Image;
+ if (boundary === 'decode') {
+ Object.defineProperty(global, 'Image', {
+ configurable: true,
+ writable: true,
+ value: class {
+ width = 640;
+ height = 480;
+ onload: (() => void) | null = null;
+ set src(_value: string) {
+ imageCallbacks.push(() => this.onload?.());
+ }
+ },
+ });
+ }
+ const queryClient = new QueryClient({
+ defaultOptions: {
+ queries: { retry: false, cacheTime: Infinity },
+ mutations: { retry: false },
+ },
+ });
+ const wrapper = ({ children }: { children: React.ReactNode }) =>
+ React.createElement(QueryClientProvider, { client: queryClient }, children);
+ const { result, rerender, unmount } = renderHook(
+ ({ conversationId, draftId }) => {
+ const [files, setFiles] = useAtom(filesFamily(2));
+ const state = {
+ index: 2,
+ files,
+ setFiles,
+ conversation: { conversationId, endpoint: EModelEndpoint.openAI } as TConversation,
+ };
+ useAutoSave({ ...state, index: 2, conversationId, draftId });
+ const handler = useFileHandlingNoChatContext(undefined, state);
+ const sharepoint = useSharePointFileHandlingNoChatContext(
+ { toolResource: 'file_search' },
+ state,
+ );
+ return { handler, sharepoint, files, state };
+ },
+ { wrapper, initialProps: { conversationId: origin, draftId: null as string | null } },
+ );
+ const contextState = result.current.state;
+ const contextSharePoint = renderHook(() => useSharePoint({ toolResource: 'file_search' }), {
+ wrapper: ({ children }) =>
+ React.createElement(
+ QueryClientProvider,
+ { client: queryClient },
+ React.createElement(
+ ChatContext.Provider,
+ {
+ value: contextState as ReturnType<
+ typeof import('~/Providers/ChatContext').useChatContext
+ >,
+ },
+ children,
+ ),
+ ),
+ });
+ const next = renderHook(() => useNewConvo(2), { wrapper });
+ let first: Promise<boolean> | undefined;
+ let pending: Promise<boolean | void> = Promise.resolve();
+ act(() => {
+ if (boundary === 'queue')
+ first = result.current.handler.handleFiles(mockDownloadedFiles, 'file_search');
+ if (boundary === 'sharepoint') {
+ pending = contextSharePoint.result.current.handleSharePointFiles([]);
+ } else if (boundary === 'sharepoint-no-context') {
+ pending = result.current.sharepoint.handleSharePointFiles([]);
+ } else {
+ let selectedFiles = mockDownloadedFiles;
+ if (boundary === 'heic')
+ selectedFiles = [new File(['heic'], 'search.heic', { type: 'image/heic' })];
+ else if (boundary === 'decode')
+ selectedFiles = [new File(['image'], 'search.png', { type: 'image/png' })];
+ pending = result.current.handler.handleFiles(selectedFiles, 'file_search');
+ }
+ });
+ await act(async () => {
+ await Promise.resolve();
+ await Promise.resolve();
+ });
+ act(() => {
+ if (boundary === 'unmount') unmount();
+ else if (boundary === 'route') {
+ window.history.pushState({}, '', '/c/destination');
+ rerender({ conversationId: 'destination', draftId: null });
+ } else if (boundary === 'answer') {
+ rerender({ conversationId: origin, draftId: getAskAnswerDraftId('next-question') });
+ } else {
+ next.result.current.newConversation();
+ rerender({ conversationId: 'new', draftId: null });
+ }
+ });
+ await act(async () => {
+ release();
+ await first;
+ const accepted = await pending;
+ if (!boundary.startsWith('sharepoint') && boundary !== 'decode')
+ expect(accepted).toBe(false);
+ imageCallbacks.forEach((decode) => decode());
+ });
+ expect(mockUploadFile).not.toHaveBeenCalled();
+ if (boundary !== 'unmount') expect(result.current.files.size).toBe(0);
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ contextSharePoint.unmount();
+ next.unmount();
+ unmount();
+ mockConfigPending = false;
+ mockPreparationGate = undefined;
+ window.history.replaceState({}, '', '/');
+ global.Image = originalImage;
+ queryClient.clear();
+ },
+ );
+
+ it.each(['retained', 'discarded', 'disabled', 'unrelated', 'other-conversation'])(
+ 'restores File Search only for a retained explicit upload (%s)',
+ (mode) => {
+ mockSaveDrafts = mode !== 'discarded';
+ mockPreviousConversation = {
+ conversationId: 'origin-conversation',
+ endpoint: EModelEndpoint.openAI,
+ };
+ mockFiles.clear();
+ mockFiles.set('pending-search', {
+ file_id: 'pending-search',
+ attached: false,
+ progress: 0.2,
+ });
+ setFilesDraft('origin-conversation', { fileIds: ['pending-search'], pendingPastes: {} });
+ if (mode !== 'unrelated') {
+ beginFileSearchUpload(
+ 'pending-search',
+ mode === 'other-conversation' ? 'other-conversation' : 'origin-conversation',
+ );
+ if (mode === 'disabled') {
+ setFileSearchChoice('origin-conversation', false);
+ }
+ }
+ const next = renderHook(() => useNewConvo());
+ act(() => next.result.current.newConversation());
+ expect(clearUploadRecovery).toHaveBeenCalledWith('pending-search', mockSaveDrafts);
+ expect(getDefaultStore().get(filesFamily(0)).size).toBe(0);
+ next.unmount();
+
+ // Persistence finishes after leaving; restoration reads the real saved draft and file cache.
+ mockSaveDrafts = true;
+ mockFileList = [
+ {
+ file_id: 'persisted-search',
+ temp_file_id: 'pending-search',
+ filepath: '/files/search.txt',
+ filename: 'search.txt',
+ bytes: 5,
+ type: 'text/plain',
+ embedded: true,
+ llmDeliveryPath: 'none',
+ },
+ ];
+ const setFiles = jest.fn();
+ const restored = renderHook(() =>
+ useAutoSave({
+ conversationId: 'origin-conversation',
+ files: new Map(),
+ setFiles,
+ }),
+ );
+ const files = setFiles.mock.calls.reduce(
+ (current, [update]) => (typeof update === 'function' ? update(current) : update),
+ new Map(),
+ );
+ expect(files.get('pending-search')).toMatchObject({
+ file_id: 'persisted-search',
+ progress: 1,
+ llmDeliveryPath: 'none',
+ });
+ if (mode === 'retained') {
+ expect(mockSetEphemeralAgent).toHaveBeenCalledWith(
+ 'origin-conversation',
+ expect.any(Function),
+ );
+ const update = mockSetEphemeralAgent.mock.calls.at(-1)?.[1];
+ expect(update({ web_search: true })).toEqual({ web_search: true, file_search: true });
+ expect(
+ localStorage.getItem(`${LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_}origin-conversation`),
+ ).toBe('true');
+ } else {
+ expect(mockSetEphemeralAgent).not.toHaveBeenCalled();
+ }
+ restored.unmount();
+ },
+ );
+
+ it.each(['active', 'other-question', 'other-conversation', 'other-pane'])(
+ 'retains only the owning active answer draft on New Chat (%s)',
+ (mode) => {
+ mockSaveDrafts = true;
+ mockPreviousConversation = {
+ conversationId: 'answer-origin',
+ endpoint: EModelEndpoint.openAI,
+ };
+ mockFiles.clear();
+ mockFiles.set('answer-upload', { file_id: 'answer-upload', attached: false, progress: 0.2 });
+ const draftId = getAskAnswerDraftId('active-question');
+ const source = renderHook(() =>
+ useAutoSave({
+ index: mode === 'other-pane' ? 0 : 2,
+ conversationId: mode === 'other-conversation' ? 'unrelated-origin' : 'answer-origin',
+ draftId,
+ files: mockFiles as Map<string, ExtendedFile>,
+ setFiles: jest.fn(),
+ }),
+ );
+ if (mode === 'other-question') {
+ setFilesDraft(draftId, { fileIds: [], pendingPastes: {} });
+ setFilesDraft(getAskAnswerDraftId('other-question'), {
+ fileIds: ['answer-upload'],
+ pendingPastes: {},
+ });
+ }
+ beginFileSearchUpload('answer-upload', 'answer-origin');
+ const next = renderHook(() => useNewConvo(2));
+ act(() => next.result.current.newConversation());
+ expect(clearUploadRecovery).toHaveBeenCalledWith('answer-upload', mode === 'active');
+ next.unmount();
+ source.unmount();
+ mockFileList = [
+ { file_id: 'saved-answer', temp_file_id: 'answer-upload', bytes: 3, embedded: true },
+ ];
+ setFilesDraft(draftId, { fileIds: ['answer-upload'], pendingPastes: {} });
+ mockSetEphemeralAgent.mockClear();
+ const restored = renderHook(() =>
+ useAutoSave({
+ index: 2,
+ conversationId: 'answer-origin',
+ draftId,
+ files: new Map(),
+ setFiles: jest.fn(),
+ }),
+ );
+ expect(mockSetEphemeralAgent.mock.calls.length > 0).toBe(mode === 'active');
+ restored.unmount();
+ },
+ );
+
it('does not delete a file claimed by another tab but deletes an unclaimed file', () => {
mockForeignClaims.add('claimed-file');
const { result } = renderHook(() => useNewConvo(2));
diff --git a/client/src/hooks/useNewConvo.ts b/client/src/hooks/useNewConvo.ts
index 244c217e5c..ec71bc00d4 100644
--- a/client/src/hooks/useNewConvo.ts
+++ b/client/src/hooks/useNewConvo.ts
@@ -39,6 +39,8 @@ import {
renewNewConversationDraftToken,
getNewConversationDraftId,
getPendingDraftId,
+ getActiveComposerDraftId,
+ getFilesDraft,
isPastedTextFileMarked,
loadPendingDiscardIds,
storePendingDiscardIds,
@@ -332,6 +334,7 @@ const useNewConvo = (index = 0) => {
}: NewConversationOptions = {}) {
const nextConversationId = _template.conversationId ?? '';
const keepsExistingDraft =
+ modelsData != null ||
keepComposerState ||
(nextConversationId !== '' &&
nextConversationId !== Constants.NEW_CONVO &&
@@ -388,10 +391,31 @@ const useNewConvo = (index = 0) => {
!modelsData &&
!keepComposerState
) {
+ const sourceDraftId =
+ !prevConversation?.conversationId ||
+ prevConversation.conversationId === Constants.NEW_CONVO
+ ? getNewConversationDraftId(index)
+ : prevConversation.conversationId;
+ const activeDraftId = getActiveComposerDraftId(
+ index,
+ prevConversation?.conversationId ?? Constants.NEW_CONVO,
+ );
+ const retainedUploadIds = new Set(
+ saveDrafts
+ ? [
+ ...getFilesDraft(sourceDraftId).fileIds,
+ ...getFilesDraft(getPendingDraftId(index)).fileIds,
+ ...(activeDraftId ? getFilesDraft(activeDraftId).fileIds : []),
+ ]
+ : [],
+ );
const filesToDelete = Array.from(files.entries()).flatMap(([fileId, file]) => {
- clearUploadRecovery(fileId);
+ const retainFileSearch = [fileId, file.file_id, file.temp_file_id].some(
+ (id) => id != null && retainedUploadIds.has(id),
+ );
+ clearUploadRecovery(fileId, retainFileSearch);
if (file.temp_file_id && file.temp_file_id !== fileId) {
- clearUploadRecovery(file.temp_file_id);
+ clearUploadRecovery(file.temp_file_id, retainFileSearch);
}
/** A generated paste is this composer's own upload and goes with it, even when that
diff --git a/client/src/utils/choices.ts b/client/src/utils/choices.ts
new file mode 100644
index 0000000000..ce1d81bd2a
--- /dev/null
+++ b/client/src/utils/choices.ts
@@ -0,0 +1,70 @@
+import { v4 } from 'uuid';
+import { resolveComposerConversationId } from './drafts';
+
+export const FILE_SEARCH_CHOICE_PREFIX = 'file-search-choice:';
+type FileSearchChoice = { revision: string | null; enabled: boolean };
+const unavailableStorage = new Map<string, FileSearchChoice>();
+
+function readFileSearchChoice(conversationId: string): FileSearchChoice | null {
+ const fallback = unavailableStorage.get(conversationId);
+ if (fallback) {
+ return fallback;
+ }
+ try {
+ const choice = JSON.parse(
+ localStorage.getItem(`${FILE_SEARCH_CHOICE_PREFIX}${conversationId}`) ?? 'null',
+ ) as FileSearchChoice | null;
+ return choice &&
+ (choice.revision === null || typeof choice.revision === 'string') &&
+ typeof choice.enabled === 'boolean'
+ ? choice
+ : null;
+ } catch {
+ return null;
+ }
+}
+
+export function getFileSearchChoice(conversationId: string): FileSearchChoice | null {
+ return readFileSearchChoice(resolveComposerConversationId(conversationId));
+}
+
+export function transferFileSearchChoice(sourceId: string, targetId: string): boolean | undefined {
+ const source = readFileSearchChoice(sourceId);
+ const target = readFileSearchChoice(targetId);
+ if (!target && source) {
+ try {
+ localStorage.setItem(`${FILE_SEARCH_CHOICE_PREFIX}${targetId}`, JSON.stringify(source));
+ } catch {
+ unavailableStorage.set(targetId, source);
+ }
+ }
+ return target && target.revision !== source?.revision ? target.enabled : undefined;
+}
+
+function writeFileSearchChoice(conversationId: string, choice: FileSearchChoice): void {
+ try {
+ localStorage.setItem(`${FILE_SEARCH_CHOICE_PREFIX}${conversationId}`, JSON.stringify(choice));
+ unavailableStorage.delete(conversationId);
+ } catch {
+ unavailableStorage.set(conversationId, choice);
+ }
+}
+
+/** Only explicit toggles advance the revision; accepted uploads retain it. */
+export function setFileSearchChoice(conversationId: string, enabled: boolean): void {
+ writeFileSearchChoice(resolveComposerConversationId(conversationId), { revision: v4(), enabled });
+}
+
+export function acceptFileSearchChoice(conversationId: string, revision: string | null): boolean {
+ conversationId = resolveComposerConversationId(conversationId);
+ const choice = readFileSearchChoice(conversationId);
+ if (choice && choice.revision !== revision && !choice.enabled) return false;
+ if (!choice?.enabled) {
+ writeFileSearchChoice(conversationId, { revision: choice?.revision ?? null, enabled: true });
+ }
+ return true;
+}
+
+export function clearFileSearchChoices(): void {
+ unavailableStorage.clear();
+}
diff --git a/client/src/utils/drafts.spec.ts b/client/src/utils/drafts.spec.ts
index 287d42f7da..b3853e2926 100644
--- a/client/src/utils/drafts.spec.ts
+++ b/client/src/utils/drafts.spec.ts
@@ -14,6 +14,7 @@ import {
getFilesDraft,
getNewConversationDraftId,
getNewConversationDraftToken,
+ getNewConversationDraftRevision,
getPendingDraftId,
isFilesDraftOwnedByThisTab,
isNewConversationDraftId,
@@ -26,6 +27,14 @@ import {
renewNewConversationDraftToken,
setDraft,
setFilesDraft,
+ subscribeDraftOwnership,
+ registerComposerDraft,
+ captureComposerDraft,
+ bindComposerLaunch,
+ consumeComposerQuery,
+ adoptComposerConversation,
+ resolveComposerConversationId,
+ getActiveComposerDraftId,
removePendingTextAttachmentDraft,
setPendingTextAttachmentDraft,
} from './drafts';
@@ -1135,3 +1144,534 @@ describe('clearDraft navigation ordering', () => {
expect(getDraft('chat-b')).toBe('');
});
});
+
+describe('composer draft ownership', () => {
+ it('releases only the registered pane scope and rejects another conversation', () => {
+ const releaseOld = registerComposerDraft(4, 'origin', 'ask-answer:old');
+ const releaseNew = registerComposerDraft(4, 'origin', 'ask-answer:new');
+ releaseOld();
+ expect(getActiveComposerDraftId(4, 'origin')).toBe('ask-answer:new');
+ expect(getActiveComposerDraftId(4, 'other')).toBeNull();
+ expect(getActiveComposerDraftId(5, 'origin')).toBeNull();
+ releaseNew();
+ expect(getActiveComposerDraftId(4, 'origin')).toBeNull();
+ });
+
+ it('coalesces actual local changes and stops notifying after unsubscription', async () => {
+ localStorage.clear();
+ await Promise.resolve();
+ const changed = jest.fn();
+ const unsubscribe = subscribeDraftOwnership('observed', changed);
+ const draft = { fileIds: ['file'], pendingPastes: {} };
+ setFilesDraft('unrelated', draft);
+ setFilesDraft('observed', draft);
+ setFilesDraft('observed', draft);
+ await Promise.resolve();
+ expect(changed).toHaveBeenCalledTimes(1);
+ setFilesDraft('observed', draft);
+ await Promise.resolve();
+ expect(changed).toHaveBeenCalledTimes(1);
+ unsubscribe();
+ clearFilesDraft('observed');
+ await Promise.resolve();
+ expect(changed).toHaveBeenCalledTimes(1);
+ });
+});
+
+describe('logical composer lifetime', () => {
+ it('preserves pending storage migration but rejects a new host and answer scope', () => {
+ const host = {};
+ const leavePending = registerComposerDraft(7, 'chat', 'pending:7', host);
+ const captured = captureComposerDraft(7, 'chat');
+ leavePending();
+ const leaveIdle = registerComposerDraft(7, 'chat', 'chat', host);
+ expect(captured()).toBe(true);
+ leaveIdle();
+ const leaveAnswer = registerComposerDraft(7, 'chat', 'ask-answer:question', host);
+ expect(captured()).toBe(false);
+ leaveAnswer();
+ });
+ it('hands an acknowledged scope to a replacement host without accepting stale cleanup', () => {
+ const releaseFirst = registerComposerDraft(9, Constants.NEW_CONVO, 'pending:9', {});
+ const launch = { conversationId: Constants.NEW_CONVO };
+ bindComposerLaunch(launch, 9);
+ const captured = captureComposerDraft(9, Constants.NEW_CONVO);
+ expect(adoptComposerConversation(launch, 'assigned-chat', 9)).toBe(true);
+ releaseFirst();
+ const releaseReplacement = registerComposerDraft(9, 'assigned-chat', 'assigned-chat', {});
+ releaseFirst();
+ expect(captured()).toBe(true);
+ expect(captured.conversationId()).toBe('assigned-chat');
+ releaseReplacement();
+ expect(captured()).toBe(false);
+ });
+
+ it('does not revive an acknowledged scope after genuine teardown', async () => {
+ const release = registerComposerDraft(10, Constants.NEW_CONVO, 'pending:10', {});
+ const launch = { conversationId: Constants.NEW_CONVO };
+ bindComposerLaunch(launch, 10);
+ const captured = captureComposerDraft(10, Constants.NEW_CONVO);
+ expect(adoptComposerConversation(launch, 'closed-chat', 10)).toBe(true);
+ release();
+ await Promise.resolve();
+ const closeNewHost = registerComposerDraft(10, 'closed-chat', 'closed-chat', {});
+ expect(captured()).toBe(false);
+ closeNewHost();
+ });
+
+ it('does not treat a remount without acknowledgement as the same composer', () => {
+ const release = registerComposerDraft(11, 'existing-chat', 'existing-chat', {});
+ const captured = captureComposerDraft(11, 'existing-chat');
+ release();
+ const closeReplacement = registerComposerDraft(11, 'existing-chat', 'existing-chat', {});
+ expect(captured()).toBe(false);
+ closeReplacement();
+ });
+
+ it('keeps side-by-side new-chat choices from targeting an assigned pane', () => {
+ const releaseAssigned = registerComposerDraft(12, Constants.NEW_CONVO, 'pending:12', {});
+ const launch = { conversationId: Constants.NEW_CONVO };
+ bindComposerLaunch(launch, 12);
+ const captured = captureComposerDraft(12, Constants.NEW_CONVO);
+ expect(adoptComposerConversation(launch, 'assigned-pane', 12)).toBe(true);
+ const releaseNew = registerComposerDraft(13, Constants.NEW_CONVO, 'new:13', {});
+ expect(resolveComposerConversationId(Constants.NEW_CONVO)).toBe(Constants.NEW_CONVO);
+ expect(captured()).toBe(true);
+ expect(captured.conversationId()).toBe('assigned-pane');
+ releaseNew();
+ releaseAssigned();
+ });
+
+ it('rejects a stale acknowledgement after navigation before React commits', () => {
+ window.history.replaceState({}, '', '/c/new?prompt=hello');
+ const release = registerComposerDraft(14, Constants.NEW_CONVO, 'pending:14', {});
+ const launch = { conversationId: Constants.NEW_CONVO };
+ bindComposerLaunch(launch, 14);
+ window.history.pushState({}, '', '/c/unrelated');
+ expect(adoptComposerConversation(launch, 'stale-id', 14)).toBe(false);
+ release();
+ window.history.replaceState({}, '', '/');
+ });
+
+ it('preserves the query when the server replaces the new-chat URL', () => {
+ window.history.replaceState({}, '', '/c/new?prompt=hello');
+ const release = registerComposerDraft(15, Constants.NEW_CONVO, 'pending:15', {});
+ const launch = { conversationId: Constants.NEW_CONVO };
+ bindComposerLaunch(launch, 15);
+ const captured = captureComposerDraft(15, Constants.NEW_CONVO);
+ expect(adoptComposerConversation(launch, 'assigned-id', 15)).toBe(true);
+ window.history.replaceState({}, '', '/c/assigned-id?prompt=hello');
+ expect(captured()).toBe(true);
+ release();
+ window.history.replaceState({}, '', '/');
+ });
+
+ it('binds a new launch immediately after a same-route reset without reviving the old one', () => {
+ const host = {};
+ const release = registerComposerDraft(16, Constants.NEW_CONVO, 'new:16', host);
+ const oldLaunch = { conversationId: Constants.NEW_CONVO };
+ bindComposerLaunch(oldLaunch, 16);
+ const oldOwner = captureComposerDraft(16, Constants.NEW_CONVO);
+ renewNewConversationDraftToken(16);
+ const launch = { conversationId: Constants.NEW_CONVO };
+ bindComposerLaunch(launch, 16);
+ const owner = captureComposerDraft(16, Constants.NEW_CONVO);
+ expect(oldOwner()).toBe(false);
+ expect(adoptComposerConversation(oldLaunch, 'old-reset-chat', 16)).toBe(false);
+ release();
+ const releasePending = registerComposerDraft(16, Constants.NEW_CONVO, 'pending:16', host);
+ expect(owner()).toBe(true);
+ expect(adoptComposerConversation(launch, 'new-reset-chat', 16)).toBe(true);
+ expect(owner.conversationId()).toBe('new-reset-chat');
+ releasePending();
+ });
+
+ it('retires the refreshed registration on unmount and keeps sibling panes unchanged', async () => {
+ const release = registerComposerDraft(17, Constants.NEW_CONVO, 'new:17', {});
+ const releaseSibling = registerComposerDraft(18, Constants.NEW_CONVO, 'new:18', {});
+ const sibling = captureComposerDraft(18, Constants.NEW_CONVO);
+ renewNewConversationDraftToken(17);
+ const owner = captureComposerDraft(17, Constants.NEW_CONVO);
+ expect(owner()).toBe(true);
+ expect(sibling()).toBe(true);
+ release();
+ expect(owner()).toBe(false);
+ await Promise.resolve();
+ expect(getActiveComposerDraftId(17, Constants.NEW_CONVO)).toBeNull();
+ expect(sibling()).toBe(true);
+ releaseSibling();
+ });
+
+ it('keeps captured upload ownership across consumed prompt parameters and acknowledgement', () => {
+ window.history.replaceState({}, '', '/c/new?prompt=hello&submit=true&projectId=project');
+ const release = registerComposerDraft(20, Constants.NEW_CONVO, 'pending:20', {});
+ const captured = captureComposerDraft(20, Constants.NEW_CONVO);
+ const launch = { conversationId: Constants.NEW_CONVO };
+ bindComposerLaunch(launch, 20);
+ consumeComposerQuery(
+ 20,
+ Constants.NEW_CONVO,
+ '/c/new',
+ 'submit=true&projectId=project&prompt=hello',
+ 'projectId=project',
+ );
+ window.history.replaceState({}, '', '/c/new?projectId=project');
+ expect(captured()).toBe(true);
+ expect(adoptComposerConversation(launch, 'cleaned-chat', 20)).toBe(true);
+ window.history.replaceState({}, '', '/c/cleaned-chat?projectId=project');
+ expect(captured()).toBe(true);
+ window.history.pushState({}, '', '/c/another-chat?projectId=project');
+ expect(captured()).toBe(false);
+ release();
+ window.history.replaceState({}, '', '/');
+ });
+
+ it('preserves an acknowledged route when its consumed parameters are cleaned afterwards', () => {
+ window.history.replaceState({}, '', '/c/new?prompt=hello');
+ const release = registerComposerDraft(21, Constants.NEW_CONVO, 'pending:21', {});
+ const launch = { conversationId: Constants.NEW_CONVO };
+ bindComposerLaunch(launch, 21);
+ const captured = captureComposerDraft(21, Constants.NEW_CONVO);
+ expect(adoptComposerConversation(launch, 'assigned-cleanup', 21)).toBe(true);
+ window.history.replaceState({}, '', '/c/assigned-cleanup?prompt=hello');
+ consumeComposerQuery(21, 'assigned-cleanup', '/c/assigned-cleanup', 'prompt=hello', '');
+ window.history.replaceState({}, '', '/c/assigned-cleanup');
+ expect(captured()).toBe(true);
+ expect(adoptComposerConversation(launch, 'assigned-cleanup', 21)).toBe(true);
+ release();
+ window.history.replaceState({}, '', '/');
+ });
+
+ it.each([
+ { owner: 'new', path: '/c/new', from: 'prompt=hello&projectId=project', to: '' },
+ { owner: 'new', path: '/c/new', from: 'prompt=hello&projectId=project', to: 'projectId=other' },
+ {
+ owner: 'other',
+ path: '/c/new',
+ from: 'prompt=hello&projectId=project',
+ to: 'projectId=project',
+ },
+ {
+ owner: 'new',
+ path: '/c/new',
+ from: 'prompt=hello&projectId=project',
+ to: 'prompt=another&projectId=project',
+ },
+ {
+ owner: 'new',
+ path: '/c/unrelated',
+ from: 'prompt=hello&projectId=project',
+ to: 'projectId=project',
+ },
+ ])('does not treat a project, owner, prompt, or path change as consumption (%j)', (change) => {
+ window.history.replaceState({}, '', '/c/new?prompt=hello&projectId=project');
+ const release = registerComposerDraft(22, Constants.NEW_CONVO, 'pending:22', {});
+ const captured = captureComposerDraft(22, Constants.NEW_CONVO);
+ consumeComposerQuery(22, change.owner, change.path, change.from, change.to);
+ window.history.replaceState({}, '', change.path + (change.to ? `?${change.to}` : ''));
+ expect(captured()).toBe(false);
+ release();
+ window.history.replaceState({}, '', '/');
+ });
+
+ it('retires the old scope when the same host is registered on a changed project route', () => {
+ window.history.replaceState({}, '', '/c/new?projectId=project-a');
+ const host = {};
+ const releaseOld = registerComposerDraft(23, Constants.NEW_CONVO, 'new:23', host);
+ const oldOwner = captureComposerDraft(23, Constants.NEW_CONVO);
+ const oldLaunch = { conversationId: Constants.NEW_CONVO };
+ bindComposerLaunch(oldLaunch, 23);
+ window.history.replaceState({}, '', '/c/new?projectId=project-b');
+ releaseOld();
+ const releaseNew = registerComposerDraft(23, Constants.NEW_CONVO, 'new:23', host);
+ const owner = captureComposerDraft(23, Constants.NEW_CONVO);
+ expect(oldOwner()).toBe(false);
+ expect(owner()).toBe(true);
+ expect(adoptComposerConversation(oldLaunch, 'wrong-project', 23)).toBe(false);
+ releaseNew();
+ window.history.replaceState({}, '', '/');
+ });
+
+ it('reuses registered ownership after passive query cleanup and acknowledged route adoption', () => {
+ window.history.replaceState({}, '', '/c/new?prompt=hello&projectId=project');
+ const host = {};
+ const release = registerComposerDraft(24, Constants.NEW_CONVO, 'new:24', host);
+ const owner = captureComposerDraft(24, Constants.NEW_CONVO);
+ consumeComposerQuery(
+ 24,
+ Constants.NEW_CONVO,
+ '/c/new',
+ 'prompt=hello&projectId=project',
+ 'projectId=project',
+ );
+ window.history.replaceState({}, '', '/c/new?projectId=project');
+ release();
+ const releaseCleaned = registerComposerDraft(24, Constants.NEW_CONVO, 'pending:24', host);
+ expect(owner()).toBe(true);
+ const launch = { conversationId: Constants.NEW_CONVO };
+ bindComposerLaunch(launch, 24);
+ expect(adoptComposerConversation(launch, 'assigned-project', 24)).toBe(true);
+ window.history.replaceState({}, '', '/c/assigned-project?projectId=project');
+ releaseCleaned();
+ const releaseAssigned = registerComposerDraft(24, 'assigned-project', 'assigned-project', host);
+ expect(owner()).toBe(true);
+ expect(owner.conversationId()).toBe('assigned-project');
+ releaseAssigned();
+ window.history.replaceState({}, '', '/');
+ });
+
+ it('keeps the acknowledged owner while its source prop catches up after the URL', () => {
+ window.history.replaceState({}, '', '/c/new?projectId=project');
+ const host = {};
+ const releaseSource = registerComposerDraft(25, Constants.NEW_CONVO, 'pending:25', host);
+ const captured = captureComposerDraft(25, Constants.NEW_CONVO);
+ const launch = { conversationId: Constants.NEW_CONVO };
+ bindComposerLaunch(launch, 25);
+ expect(adoptComposerConversation(launch, 'acknowledged-url', 25)).toBe(true);
+ window.history.replaceState({}, '', '/c/acknowledged-url?projectId=project');
+ releaseSource();
+ const releaseLagging = registerComposerDraft(25, Constants.NEW_CONVO, 'pending:25', host);
+ expect(captured()).toBe(true);
+ expect(captured.conversationId()).toBe('acknowledged-url');
+ expect(adoptComposerConversation(launch, 'acknowledged-url', 25)).toBe(true);
+ releaseLagging();
+ const releaseSaved = registerComposerDraft(25, 'acknowledged-url', 'acknowledged-url', host);
+ expect(captured()).toBe(true);
+ window.history.replaceState({}, '', '/c/acknowledged-url?projectId=other');
+ releaseSaved();
+ const releaseOther = registerComposerDraft(25, 'acknowledged-url', 'acknowledged-url', host);
+ expect(captured()).toBe(false);
+ releaseOther();
+ window.history.replaceState({}, '', '/');
+ });
+
+ it('does not reuse the source alias after the saved conversation prop has arrived', () => {
+ window.history.replaceState({}, '', '/c/new');
+ const host = {};
+ const releaseSource = registerComposerDraft(29, Constants.NEW_CONVO, 'pending:29', host);
+ const owner = captureComposerDraft(29, Constants.NEW_CONVO);
+ const launch = { conversationId: Constants.NEW_CONVO };
+ bindComposerLaunch(launch, 29);
+ expect(adoptComposerConversation(launch, 'saved-before-back', 29)).toBe(true);
+ window.history.replaceState({}, '', '/c/saved-before-back');
+ releaseSource();
+ const releaseSaved = registerComposerDraft(29, 'saved-before-back', 'saved-before-back', host);
+ expect(owner()).toBe(true);
+ window.history.pushState({}, '', '/c/new');
+ releaseSaved();
+ const releaseReturned = registerComposerDraft(29, Constants.NEW_CONVO, 'new:29', host);
+ expect(owner()).toBe(false);
+ expect(captureComposerDraft(29, Constants.NEW_CONVO)()).toBe(true);
+ expect(adoptComposerConversation(launch, 'saved-before-back', 29)).toBe(false);
+ releaseReturned();
+ window.history.replaceState({}, '', '/');
+ });
+
+ it('permits origin recovery only when an owned saved draft still references the file', () => {
+ const release = registerComposerDraft(26, 'saved-owner', 'saved-owner', {});
+ const captured = captureComposerDraft(26, 'saved-owner');
+ setFilesDraft('saved-owner', { fileIds: ['kept-file'], pendingPastes: {} });
+ release();
+ expect(captured()).toBe(false);
+ expect(captured.retainsFile('kept-file')).toBe(true);
+ expect(captured.retainsFile('absent-file')).toBe(false);
+ clearFilesDraft('saved-owner');
+ expect(captured.retainsFile('kept-file')).toBe(false);
+ });
+
+ it.each(['owned', 'blocked', 'unrelated', 'foreign', 'unsubscribed'])(
+ 'follows a retained pending upload only through its owned migration (%s)',
+ async (mode) => {
+ const conversationId = 'retained-migration';
+ const pendingId = getPendingDraftId(42);
+ const release = registerComposerDraft(42, conversationId, pendingId, {});
+ const captured = captureComposerDraft(42, conversationId);
+ const unsubscribe = captured.onAssignment(jest.fn());
+ if (mode === 'foreign') markTabLive('foreign-migration-owner');
+ setFilesDraft(pendingId, {
+ fileIds: ['migrating-upload'],
+ pendingPastes: {},
+ ...(mode === 'foreign' ? { tabId: 'foreign-migration-owner' } : {}),
+ });
+ release();
+ await Promise.resolve();
+ if (mode === 'unsubscribed') unsubscribe();
+ const setItem = Storage.prototype.setItem;
+ const blocked =
+ mode === 'blocked'
+ ? jest.spyOn(Storage.prototype, 'setItem').mockImplementation(function (
+ this: Storage,
+ key: string,
+ value: string,
+ ) {
+ if (key === `${LocalStorageKeys.FILES_DRAFT}${conversationId}`) {
+ throw new Error('Migration destination unavailable');
+ }
+ setItem.call(this, key, value);
+ })
+ : undefined;
+ try {
+ const destination = mode === 'unrelated' ? 'unrelated-migration' : conversationId;
+ expect(migrateFilesDraft(pendingId, destination)).toBe(
+ mode === 'blocked' ? pendingId : destination,
+ );
+ expect(captured()).toBe(false);
+ expect(captured.retainsFile('migrating-upload')).toBe(
+ mode === 'owned' || mode === 'blocked',
+ );
+ if (mode === 'owned') {
+ captured.discardFile('migrating-upload');
+ expect(getFilesDraft(conversationId).fileIds).toEqual([]);
+ }
+ } finally {
+ blocked?.mockRestore();
+ unsubscribe();
+ }
+ },
+ );
+
+ it('never treats a shared new-chat draft as a retained retired project', () => {
+ const release = registerComposerDraft(27, Constants.NEW_CONVO, 'new:27', {});
+ const captured = captureComposerDraft(27, Constants.NEW_CONVO);
+ setFilesDraft('new:27', { fileIds: ['old-project-file'], pendingPastes: {} });
+ release();
+ expect(captured()).toBe(false);
+ expect(captured.retainsFile('old-project-file')).toBe(false);
+ clearFilesDraft('new:27');
+ });
+
+ it.each(['url-first', 'props-first'])(
+ 'retires the source URL after both parts of the handoff arrive (%s)',
+ (order) => {
+ window.history.replaceState({}, '', '/c/new?projectId=history-project');
+ const host = {};
+ const release = registerComposerDraft(30, Constants.NEW_CONVO, 'pending:30', host);
+ const owner = captureComposerDraft(30, Constants.NEW_CONVO);
+ const launch = { conversationId: Constants.NEW_CONVO };
+ bindComposerLaunch(launch, 30);
+ expect(adoptComposerConversation(launch, 'saved-terminal-route', 30)).toBe(true);
+ if (order === 'url-first') {
+ window.history.replaceState({}, '', '/c/saved-terminal-route?projectId=history-project');
+ expect(owner()).toBe(true);
+ }
+ release();
+ const releaseSaved = registerComposerDraft(
+ 30,
+ 'saved-terminal-route',
+ 'saved-terminal-route',
+ host,
+ );
+ expect(owner()).toBe(true);
+ window.history.replaceState({}, '', '/c/saved-terminal-route?projectId=history-project');
+ expect(owner()).toBe(true);
+ window.history.pushState({}, '', '/c/new?projectId=history-project');
+ expect(owner()).toBe(false);
+ expect(adoptComposerConversation(launch, 'saved-terminal-route', 30)).toBe(false);
+ releaseSaved();
+ window.history.replaceState({}, '', '/');
+ },
+ );
+
+ it('discards a retired upload only from its pane and leaves fresh attachments intact', () => {
+ const release = registerComposerDraft(35, Constants.NEW_CONVO, 'pending:35', {});
+ const owner = captureComposerDraft(35, Constants.NEW_CONVO);
+ for (const id of ['new:35', 'pending:35', 'new:36', 'saved-unrelated']) {
+ setFilesDraft(id, { fileIds: ['retired-upload', 'fresh-file'], pendingPastes: {} });
+ }
+ renewNewConversationDraftToken(35);
+ owner.discardFile('retired-upload');
+ expect(getFilesDraft('new:35').fileIds).toEqual(['fresh-file']);
+ expect(getFilesDraft('pending:35').fileIds).toEqual(['fresh-file']);
+ expect(getFilesDraft('new:36').fileIds).toEqual(['retired-upload', 'fresh-file']);
+ expect(getFilesDraft('saved-unrelated').fileIds).toEqual(['retired-upload', 'fresh-file']);
+ release();
+ });
+
+ it("never prunes a retired upload from another live tab's draft", () => {
+ const release = registerComposerDraft(37, Constants.NEW_CONVO, 'new:37', {});
+ const owner = captureComposerDraft(37, Constants.NEW_CONVO);
+ markTabLive('foreign-retained-upload');
+ setFilesDraft('new:37', {
+ fileIds: ['foreign-file'],
+ pendingPastes: {},
+ tabId: 'foreign-retained-upload',
+ });
+ renewNewConversationDraftToken(37);
+ owner.discardFile('foreign-file');
+ expect(getFilesDraft('new:37').fileIds).toEqual(['foreign-file']);
+ expect(getFilesDraft('new:37').tabId).toBe('foreign-retained-upload');
+ release();
+ });
+
+ it('notifies the identity assignment once while validating replays and later launches', () => {
+ window.history.replaceState({}, '', '/c/new');
+ const host = {};
+ const release = registerComposerDraft(39, Constants.NEW_CONVO, 'new:39', host);
+ const launch = { conversationId: Constants.NEW_CONVO };
+ bindComposerLaunch(launch, 39);
+ const assigned = jest.fn();
+ expect(adoptComposerConversation(launch, 'once-assigned', 39, assigned)).toBe(true);
+ expect(assigned).toHaveBeenCalledWith(Constants.NEW_CONVO, 'once-assigned');
+ expect(adoptComposerConversation(launch, 'once-assigned', 39, assigned)).toBe(true);
+ window.history.replaceState({}, '', '/c/once-assigned');
+ release();
+ const releaseSaved = registerComposerDraft(39, 'once-assigned', 'once-assigned', host);
+ const nextLaunch = { conversationId: 'once-assigned' };
+ bindComposerLaunch(nextLaunch, 39);
+ expect(adoptComposerConversation(nextLaunch, 'once-assigned', 39, assigned)).toBe(true);
+ expect(assigned).toHaveBeenCalledTimes(1);
+ window.history.replaceState({}, '', '/c/unrelated');
+ expect(adoptComposerConversation(nextLaunch, 'once-assigned', 39, assigned)).toBe(false);
+ expect(assigned).toHaveBeenCalledTimes(1);
+ releaseSaved();
+ window.history.replaceState({}, '', '/');
+ });
+
+ it('keeps reset revisions pane-local and stable until an explicit reset', () => {
+ const first = getNewConversationDraftRevision(31);
+ expect(getNewConversationDraftRevision(31)).toBe(first);
+ const sibling = getNewConversationDraftRevision(32);
+ renewNewConversationDraftToken(31);
+ expect(getNewConversationDraftRevision(31)).not.toBe(first);
+ expect(getNewConversationDraftRevision(32)).toBe(sibling);
+ });
+
+ it('does not trust an old reset revision when session storage is read-only on reload', () => {
+ const revision = getNewConversationDraftRevision(33);
+ const setItem = Storage.prototype.setItem;
+ const blocked = jest.spyOn(Storage.prototype, 'setItem').mockImplementation(function (
+ this: Storage,
+ key: string,
+ value: string,
+ ) {
+ if (key === 'librechat-new-composer:33') throw new Error('Session revision unavailable');
+ setItem.call(this, key, value);
+ });
+ const navigation = Object.getOwnPropertyDescriptor(performance, 'getEntriesByType');
+ Object.defineProperty(performance, 'getEntriesByType', {
+ configurable: true,
+ value: () => [{ type: 'reload' }],
+ });
+ try {
+ renewNewConversationDraftToken(33);
+ expect(getNewConversationDraftRevision(33)).not.toBe(revision);
+ jest.isolateModules(() => {
+ const reloaded = jest.requireActual<typeof import('./drafts')>('./drafts');
+ expect(reloaded.getNewConversationDraftRevision(33)).not.toBe(revision);
+ });
+ } finally {
+ blocked.mockRestore();
+ if (navigation) Object.defineProperty(performance, 'getEntriesByType', navigation);
+ else Reflect.deleteProperty(performance, 'getEntriesByType');
+ }
+ });
+
+ it('rejects an acknowledgement from a launch superseded by New Chat', () => {
+ const release = registerComposerDraft(8, Constants.NEW_CONVO, 'pending:8', {});
+ const submissionConversation = { conversationId: Constants.NEW_CONVO };
+ bindComposerLaunch(submissionConversation, 8);
+ renewNewConversationDraftToken(8);
+ expect(adoptComposerConversation(submissionConversation, 'server-id', 8)).toBe(false);
+ release();
+ });
+});
diff --git a/client/src/utils/drafts.ts b/client/src/utils/drafts.ts
index 037db909a9..85c53ab291 100644
--- a/client/src/utils/drafts.ts
+++ b/client/src/utils/drafts.ts
@@ -46,6 +46,25 @@ type StoredFilesDraft = {
};
const newConversationDraftTokens = new Map<number, symbol>();
+const newConversationDraftRevisions = new Map<number, string>();
+const newConversationRevisionKey = (index: number): string => `librechat-new-composer:${index}`;
+
+/** Reload preserves the revision; an explicit reset replaces it before any new work starts. */
+export const getNewConversationDraftRevision = (index = 0): string => {
+ const current = newConversationDraftRevisions.get(index);
+ if (current) return current;
+ let revision: string;
+ try {
+ revision = sessionStorage.getItem(newConversationRevisionKey(index)) || mintTabId();
+ // Verify persistence is writable; a blocked reload must not trust an old reset revision.
+ sessionStorage.setItem(newConversationRevisionKey(index), revision);
+ } catch {
+ revision = mintTabId();
+ }
+ const scopedRevision = `${getBrowserTabId()}:${revision}`;
+ newConversationDraftRevisions.set(index, scopedRevision);
+ return scopedRevision;
+};
/** Per-composer identity so a side-by-side new-chat reset cannot discard another pane's paste recovery. */
export const getNewConversationDraftToken = (index = 0): symbol => {
@@ -59,7 +78,27 @@ export const getNewConversationDraftToken = (index = 0): symbol => {
};
export const renewNewConversationDraftToken = (index = 0): void => {
- newConversationDraftTokens.set(index, Symbol('new-conversation-draft'));
+ const generation = Symbol('new-conversation-draft');
+ newConversationDraftTokens.set(index, generation);
+ const revision = mintTabId();
+ newConversationDraftRevisions.set(index, `${getBrowserTabId()}:${revision}`);
+ try {
+ sessionStorage.setItem(newConversationRevisionKey(index), revision);
+ } catch {
+ // The live revision still fences this document; blocked reloads start a fresh revision.
+ }
+ const scope = composerDraftScopes.get(index);
+ if (scope?.active && scope.conversationId === Constants.NEW_CONVO) {
+ composerDraftScopes.set(index, {
+ ...scope,
+ generation,
+ route: composerRoute(),
+ sourceId: undefined,
+ sourcePropPending: false,
+ assignedRoute: undefined,
+ assignments: new Set(),
+ });
+ }
};
/** Draft key used while a run is in flight. Extra panes get a suffix so one run cannot migrate another pane's attachments. */
@@ -266,9 +305,315 @@ const getLocalStorageItem = (key: string): string | null => {
}
};
+const ownershipChanges = new Set<string>();
+const ownershipListeners = new Set<(keys: ReadonlySet<string>) => void>();
+let ownershipNotificationPending = false;
+
+const notifyOwnershipChange = (key: string): void => {
+ ownershipChanges.add(key);
+ if (ownershipNotificationPending) return;
+ ownershipNotificationPending = true;
+ void Promise.resolve().then(() => {
+ ownershipNotificationPending = false;
+ const keys = new Set(ownershipChanges);
+ ownershipChanges.clear();
+ ownershipListeners.forEach((listener) => listener(keys));
+ });
+};
+
+export const subscribeDraftOwnership = (id: string, onChange: () => void): (() => void) => {
+ const draftKey = `${LocalStorageKeys.FILES_DRAFT}${id}`;
+ const relevant = (key: string): boolean =>
+ key === draftKey || key.startsWith(TAB_PRESENCE_KEY_PREFIX);
+ const local = (keys: ReadonlySet<string>) => {
+ for (const key of keys) {
+ if (!relevant(key)) continue;
+ onChange();
+ return;
+ }
+ };
+ const external = (event: StorageEvent) => {
+ if (event.key == null || relevant(event.key)) onChange();
+ };
+ ownershipListeners.add(local);
+ window.addEventListener('storage', external);
+ return () => {
+ ownershipListeners.delete(local);
+ window.removeEventListener('storage', external);
+ };
+};
+
+type ComposerDraftScope = {
+ conversationId: string;
+ draftId: string;
+ host?: object;
+ registration: object;
+ active: boolean;
+ generation: symbol;
+ answerId: string | null;
+ route: string;
+ assignedRoute?: string;
+ sourceId?: string;
+ sourcePropPending?: boolean;
+ assignments: Set<(sourceId: string, targetId: string) => void>;
+};
+const composerDraftMigrations = new Set<(fromId: string, toId: string) => void>();
+const composerDraftScopes = new Map<number, ComposerDraftScope>();
+const composerLaunches = new WeakMap<object, { index: number; scope: ComposerDraftScope }>();
+const composerRoute = () => window.location.pathname + window.location.search;
+
+const matchesComposerRoute = (scope: ComposerDraftScope): boolean => {
+ const route = composerRoute();
+ if (!scope.sourcePropPending && scope.assignedRoute === route) {
+ scope.route = route;
+ }
+ return route === scope.route || route === scope.assignedRoute;
+};
+
+export const registerComposerDraft = (
+ index: number,
+ conversationId: string,
+ draftId: string,
+ host?: object,
+): (() => void) => {
+ const previous = composerDraftScopes.get(index);
+ const generation = getNewConversationDraftToken(index);
+ const answerId = isAskAnswerDraftId(draftId) ? draftId : null;
+ const route = composerRoute();
+ const scope: ComposerDraftScope =
+ host &&
+ previous != null &&
+ (previous.host === host || (!previous.active && previous.sourceId != null)) &&
+ previous.generation === generation &&
+ (previous.conversationId === conversationId ||
+ (previous.sourcePropPending && previous.sourceId === conversationId)) &&
+ previous.answerId === answerId &&
+ (previous.route === route || previous.assignedRoute === route)
+ ? previous
+ : {
+ conversationId,
+ draftId,
+ host,
+ registration: {},
+ generation,
+ answerId,
+ active: true,
+ route,
+ assignments: new Set<(sourceId: string, targetId: string) => void>(),
+ };
+ if (previous && scope !== previous && conversationId === Constants.NEW_CONVO) {
+ renewNewConversationDraftToken(index);
+ scope.generation = getNewConversationDraftToken(index);
+ }
+ const registration = {};
+ scope.registration = registration;
+ scope.host = host;
+ scope.active = true;
+ scope.draftId = draftId;
+ if (scope.conversationId === conversationId) {
+ scope.sourcePropPending = false;
+ if (scope.assignedRoute === route) scope.route = route;
+ }
+ composerDraftScopes.set(index, scope);
+ return () => {
+ const current = composerDraftScopes.get(index);
+ if (current?.registration !== registration) return;
+ current.active = false;
+ void Promise.resolve().then(() => {
+ if (composerDraftScopes.get(index) === current && !current.active) {
+ if (current.conversationId === Constants.NEW_CONVO) {
+ renewNewConversationDraftToken(index);
+ }
+ composerDraftScopes.delete(index);
+ }
+ });
+ };
+};
+
+export const getActiveComposerDraftId = (index: number, conversationId: string): string | null => {
+ const scope = composerDraftScopes.get(index);
+ return scope?.active && scope.conversationId === conversationId ? scope.draftId : null;
+};
+
+const normalizedComposerSearch = (search: string): string => {
+ const params = new URLSearchParams(search);
+ params.sort();
+ return params.toString();
+};
+
+/** Only consumed parameters change here; project and navigation changes keep their fence. */
+export const consumeComposerQuery = (
+ index: number,
+ conversationId: string,
+ pathname: string,
+ previousSearch: string,
+ nextSearch: string,
+): void => {
+ const scope = composerDraftScopes.get(index);
+ if (
+ !scope?.active ||
+ scope.generation !== getNewConversationDraftToken(index) ||
+ (scope.conversationId !== conversationId && scope.sourceId !== conversationId)
+ ) {
+ return;
+ }
+ const previous = new URLSearchParams(previousSearch);
+ const next = new URLSearchParams(nextSearch);
+ if (
+ (previous.get('projectId') || null) !== (next.get('projectId') || null) ||
+ Array.from(next.keys()).some((key) => key !== 'projectId')
+ ) {
+ return;
+ }
+ const expectedSearch = normalizedComposerSearch(previousSearch);
+ const cleanedSearch = next.toString();
+ for (const field of ['route', 'assignedRoute'] as const) {
+ const value = scope[field];
+ if (value == null) continue;
+ const route = new URL(value, window.location.origin);
+ if (route.pathname !== pathname || normalizedComposerSearch(route.search) !== expectedSearch) {
+ continue;
+ }
+ scope[field] = pathname + (cleanedSearch ? `?${cleanedSearch}` : '');
+ }
+};
+
+export const bindComposerLaunch = (
+ conversation: object | null | undefined,
+ index: number,
+): void => {
+ const scope = composerDraftScopes.get(index);
+ if (conversation && scope?.active) composerLaunches.set(conversation, { index, scope });
+};
+
+/** Only an acknowledged submission may rename a composer; assignment effects run once. */
+export const adoptComposerConversation = (
+ conversation: object | null | undefined,
+ targetId: string,
+ index: number,
+ onAssignment?: (sourceId: string, targetId: string) => void,
+): boolean => {
+ const launch = conversation ? composerLaunches.get(conversation) : undefined;
+ const scope = launch?.scope;
+ if (
+ !scope ||
+ launch?.index !== index ||
+ !scope.active ||
+ composerDraftScopes.get(index) !== scope ||
+ scope.generation !== getNewConversationDraftToken(index) ||
+ !targetId ||
+ targetId === Constants.NEW_CONVO
+ )
+ return false;
+ if (scope.sourceId === Constants.NEW_CONVO && scope.conversationId === targetId) {
+ return matchesComposerRoute(scope);
+ }
+ if (scope.conversationId !== Constants.NEW_CONVO || composerRoute() !== scope.route) return false;
+ const sourceId = scope.conversationId;
+ scope.sourceId = sourceId;
+ scope.sourcePropPending = true;
+ scope.conversationId = targetId;
+ const assignedRoute = new URL(scope.route, window.location.origin);
+ assignedRoute.pathname = assignedRoute.pathname.replace(
+ /\/new$/,
+ `/${encodeURIComponent(targetId)}`,
+ );
+ scope.assignedRoute = assignedRoute.pathname + assignedRoute.search;
+ scope.assignments.forEach((listener) => listener(sourceId, targetId));
+ onAssignment?.(sourceId, targetId);
+ return true;
+};
+
+export const resolveComposerConversationId = (conversationId: string): string => {
+ let assignedId: string | undefined;
+ for (const [index, scope] of composerDraftScopes) {
+ if (!scope.active || scope.generation !== getNewConversationDraftToken(index)) continue;
+ if (scope.conversationId === conversationId) return conversationId;
+ if (scope.sourceId !== conversationId) continue;
+ if (assignedId != null) return conversationId;
+ assignedId = scope.conversationId;
+ }
+ return assignedId ?? conversationId;
+};
+
+export type CapturedComposerDraft = (() => boolean) & {
+ registered: boolean;
+ newChatGeneration?: Readonly<{ index: number; revision: string }>;
+ conversationId: () => string;
+ retainsFile: (fileId: string) => boolean;
+ discardFile: (fileId: string) => void;
+ onAssignment: (listener: (sourceId: string, targetId: string) => void) => () => void;
+};
+
+export const captureComposerDraft = (
+ index: number,
+ conversationId: string,
+): CapturedComposerDraft => {
+ const scope = composerDraftScopes.get(index);
+ const generation = getNewConversationDraftToken(index);
+ const route = composerRoute();
+ return Object.assign(
+ () =>
+ (!scope ||
+ (scope.active &&
+ (scope.conversationId === conversationId || scope.sourceId === conversationId))) &&
+ composerDraftScopes.get(index) === scope &&
+ getNewConversationDraftToken(index) === generation &&
+ (scope ? matchesComposerRoute(scope) : composerRoute() === route),
+ {
+ registered: scope != null,
+ newChatGeneration:
+ conversationId === Constants.NEW_CONVO
+ ? { index, revision: getNewConversationDraftRevision(index) }
+ : undefined,
+ conversationId: () => scope?.conversationId ?? conversationId,
+ retainsFile: (fileId: string) => {
+ if (!scope || scope.conversationId === Constants.NEW_CONVO) return false;
+ const draft = getFilesDraft(scope.draftId);
+ return isFilesDraftOwnedByThisTab(draft) && draft.fileIds.includes(fileId);
+ },
+ discardFile: (fileId: string) => {
+ const draftIds = new Set([scope?.draftId ?? getConversationDraftId(index, conversationId)]);
+ if (conversationId === Constants.NEW_CONVO) {
+ draftIds.add(getNewConversationDraftId(index));
+ draftIds.add(getPendingDraftId(index));
+ }
+ for (const id of draftIds) {
+ const draft = getFilesDraft(id);
+ if (isFilesDraftOwnedByThisTab(draft) && draft.fileIds.includes(fileId)) {
+ removePendingTextAttachmentDraft({ id, fileId, removeFile: true });
+ }
+ }
+ },
+ onAssignment: (listener: (sourceId: string, targetId: string) => void) => {
+ const migrate = (fromId: string, toId: string) => {
+ if (
+ scope != null &&
+ scope.draftId === fromId &&
+ isPendingDraftId(fromId) &&
+ scope.conversationId === toId &&
+ toId !== Constants.NEW_CONVO
+ ) {
+ scope.draftId = toId;
+ }
+ };
+ scope?.assignments.add(listener);
+ composerDraftMigrations.add(migrate);
+ return () => {
+ scope?.assignments.delete(listener);
+ composerDraftMigrations.delete(migrate);
+ };
+ },
+ },
+ );
+};
+
const setLocalStorageItem = (key: string, value: string): void => {
try {
+ const changed =
+ key.startsWith(LocalStorageKeys.FILES_DRAFT) && localStorage.getItem(key) !== value;
localStorage.setItem(key, value);
+ if (changed) notifyOwnershipChange(key);
} catch {
// Quota or disabled storage must not abort paste/upload recovery.
}
@@ -276,7 +621,10 @@ const setLocalStorageItem = (key: string, value: string): void => {
const removeLocalStorageItem = (key: string): void => {
try {
+ const changed =
+ key.startsWith(LocalStorageKeys.FILES_DRAFT) && localStorage.getItem(key) != null;
localStorage.removeItem(key);
+ if (changed) notifyOwnershipChange(key);
} catch {
// Ignore storage failures on cleanup.
}
@@ -598,6 +946,7 @@ const readLiveTabs = (): Map<string, TabPresence> => {
}
for (const key of expired) {
localStorage.removeItem(key);
+ if (key !== `${TAB_PRESENCE_KEY_PREFIX}${documentTabId}`) notifyOwnershipChange(key);
}
} catch {
// An unreadable store just means no other tab can be proven live.
@@ -1126,7 +1475,13 @@ export const migrateFilesDraft = (fromId: string, toId: string): string => {
removeLocalStorageItem(key);
try {
- localStorage.setItem(`${LocalStorageKeys.FILES_DRAFT}${toId}`, record);
+ const destinationKey = `${LocalStorageKeys.FILES_DRAFT}${toId}`;
+ const changed = getLocalStorageItem(destinationKey) !== record;
+ localStorage.setItem(destinationKey, record);
+ if (isFilesDraftOwnedByThisTab(getFilesDraft(toId))) {
+ composerDraftMigrations.forEach((listener) => listener(fromId, toId));
+ }
+ if (changed) notifyOwnershipChange(destinationKey);
return toId;
} catch {
/** Storage cannot hold the record even with the source freed, so put it back rather than
diff --git a/client/src/utils/localStorage.ts b/client/src/utils/localStorage.ts
index 11e4aa8062..9e47992e77 100644
--- a/client/src/utils/localStorage.ts
+++ b/client/src/utils/localStorage.ts
@@ -1,4 +1,8 @@
-import { LocalStorageKeys, TConversation } from 'librechat-data-provider';
+import { LocalStorageKeys } from 'librechat-data-provider';
+import type { TConversation } from 'librechat-data-provider';
+import { FILE_SEARCH_CHOICE_PREFIX, clearFileSearchChoices } from './choices';
+
+export const FILE_SEARCH_UPLOAD_PREFIX = 'file-search-upload:';
export function getLocalStorageItems() {
const items = {
@@ -31,10 +35,13 @@ export function getLocalStorageItems() {
* on the way in, because a social sign-in returns through the silent refresh and never passes the
* login mutation at all. */
export function clearComposerDraftStorage() {
+ clearFileSearchChoices();
Object.keys(localStorage).forEach((key) => {
if (
key.startsWith(LocalStorageKeys.FILES_DRAFT) ||
- key.startsWith(LocalStorageKeys.TEXT_DRAFT)
+ key.startsWith(LocalStorageKeys.TEXT_DRAFT) ||
+ key.startsWith(FILE_SEARCH_UPLOAD_PREFIX) ||
+ key.startsWith(FILE_SEARCH_CHOICE_PREFIX)
) {
localStorage.removeItem(key);
}
diff --git a/client/src/utils/timestamps.ts b/client/src/utils/timestamps.ts
index 4d9e0eb025..4db75e8295 100644
--- a/client/src/utils/timestamps.ts
+++ b/client/src/utils/timestamps.ts
@@ -1,4 +1,6 @@
import { LocalStorageKeys } from 'librechat-data-provider';
+import { FILE_SEARCH_UPLOAD_PREFIX } from './localStorage';
+import { FILE_SEARCH_CHOICE_PREFIX } from './choices';
/** Suffix for timestamp entries */
const TIMESTAMP_SUFFIX = '_TIMESTAMP';
@@ -23,10 +25,20 @@ const TIMESTAMPED_KEYS = [
/**
* Set only a timestamp for a key (when the value is handled elsewhere)
*/
+export function isTimestampExpired(timestamp: number): boolean {
+ return Date.now() - timestamp > CLEANUP_THRESHOLD;
+}
+
export function setTimestamp(key: string): void {
localStorage.setItem(`${key}${TIMESTAMP_SUFFIX}`, Date.now().toString());
}
+export function getTimestamp(key: string): number | null {
+ const raw = localStorage.getItem(`${key}${TIMESTAMP_SUFFIX}`);
+ const timestamp = raw == null ? NaN : Number(raw);
+ return Number.isFinite(timestamp) ? timestamp : null;
+}
+
/**
* Get a value from localStorage, checking if it has a valid timestamp
* Returns null if the value is too old or has no timestamp
@@ -67,6 +79,24 @@ export function cleanupTimestampedStorage(): void {
if (key === LocalStorageKeys.PIN_MCP_) {
continue;
}
+ if (key.startsWith(FILE_SEARCH_UPLOAD_PREFIX)) {
+ try {
+ const intent = JSON.parse(localStorage.getItem(key) ?? 'null') as {
+ createdAt?: number;
+ } | null;
+ if (
+ !intent ||
+ typeof intent.createdAt !== 'number' ||
+ !Number.isFinite(intent.createdAt) ||
+ isTimestampExpired(intent.createdAt)
+ ) {
+ keysToRemove.push(key);
+ }
+ } catch {
+ keysToRemove.push(key);
+ }
+ continue;
+ }
// Check if this key should be timestamped
const isTimestampedKey = TIMESTAMPED_KEYS.some(
@@ -92,7 +122,16 @@ export function cleanupTimestampedStorage(): void {
}
}
- keysToRemove.forEach((key) => localStorage.removeItem(key));
+ keysToRemove.forEach((key) => {
+ localStorage.removeItem(key);
+ if (
+ key.startsWith(LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_) &&
+ !key.endsWith(TIMESTAMP_SUFFIX)
+ ) {
+ const conversationId = key.slice(LocalStorageKeys.LAST_FILE_SEARCH_TOGGLE_.length);
+ localStorage.removeItem(`${FILE_SEARCH_CHOICE_PREFIX}${conversationId}`);
+ }
+ });
} catch (error) {
console.error('Error during cleanup of timestamped storage:', error);
}
diff --git a/packages/chat/src/core/__tests__/mount.spec.ts b/packages/chat/src/core/__tests__/mount.spec.ts
index 4d879611ab..8290adb811 100644
--- a/packages/chat/src/core/__tests__/mount.spec.ts
+++ b/packages/chat/src/core/__tests__/mount.spec.ts
@@ -55,6 +55,9 @@ describe('mountSubmission', () => {
expect(host.cache.queueTitleGeneration).toHaveBeenCalledWith('c-9');
expect(host.pane.replaceNewConversationUrl).toHaveBeenCalledWith('c-9');
expect(host.cache.addOptimisticConversation).toHaveBeenCalledWith('c-9', newChat);
+ expect(
+ (host.cache.addOptimisticConversation as jest.Mock).mock.invocationCallOrder[0],
+ ).toBeLessThan((host.pane.replaceNewConversationUrl as jest.Mock).mock.invocationCallOrder[0]);
expect(run.optimisticStreamIds.has('c-9')).toBe(true);
expect(host.stream.reconnectToStream).toHaveBeenCalledTimes(1);
});
diff --git a/packages/chat/src/core/resumable/mount.ts b/packages/chat/src/core/resumable/mount.ts
index 76a5f60ea6..06b4f5736a 100644
--- a/packages/chat/src/core/resumable/mount.ts
+++ b/packages/chat/src/core/resumable/mount.ts
@@ -49,11 +49,12 @@ function attachStartedStream(
if (isNewConvo && !submission.isTemporary) {
host.cache.queueTitleGeneration(newStreamId);
}
- if (isInitialNewConversation(submission)) {
+ // The host adopts the composer before the address bar leaves its source route.
+ const streamSubmission = host.cache.addOptimisticConversation(newStreamId, submission);
+ if (isNewConvo) {
run.optimisticStreamIds.add(newStreamId);
host.pane.replaceNewConversationUrl(newStreamId);
}
- const streamSubmission = host.cache.addOptimisticConversation(newStreamId, submission);
run.submission = streamSubmission;
// A deduped retry (status: 'resumed') attaches to an already-running stream, so
// subscribe with resume=true to replay its state instead of only live events.