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
TypeScript aianthropicartifactsawsazurechatgptchatgpt-cloneclaudeclonedeepseekgeminigooglegpt-5librechatmcpo1openairesponses-apivisionwebui
✏️ feat: Edit Pasted Text and Clear It on New Chat (#15017)
Marco Beretta124e357cbf87
diff --git a/api/server/routes/files/files.js b/api/server/routes/files/files.jsindex 50b4621fbe..fd1188a37b 100644--- a/api/server/routes/files/files.js+++ b/api/server/routes/files/files.js@@ -7,6 +7,7 @@ const {getApprovalTtlMs,refreshS3FileUrls,handleFilesUsageRequest,+ buildDeleteFilesResponse,shouldUseUploadSse,startUploadSseStream,sendUploadPolicyError,@@ -176,6 +177,9 @@ router.post('/usage', async (req, res) => {router.delete('/', async (req, res) => {try {+ const sendDeleteResult = (result, successMessage) =>+ res.status(200).json(buildDeleteFilesResponse(result, successMessage));+const { files: _files } = req.body;/** @type {MongoFile[]} */@@ -260,14 +264,14 @@ router.delete('/', async (req, res) => {}if (dbFiles.length > 0 && nonOwnedFiles.length === 0) {- await processDeleteRequest({ req, files: ownedFiles });+ const result = await processDeleteRequest({ req, files: ownedFiles });logger.debug(`[/files] Files deleted successfully: ${ownedFiles.filter((f) => f.file_id).map((f) => f.file_id).join(', ')}`,);- res.status(200).json({ message: 'Files deleted successfully' });+ sendDeleteResult(result, 'Files deleted successfully');return;}@@ -290,20 +294,19 @@ router.delete('/', async (req, res) => {const toolResourceFiles = assistant.tool_resources?.[req.body.tool_resource]?.file_ids ?? [];const assistantFiles = files.filter((f) => toolResourceFiles.includes(f.file_id));- await processDeleteRequest({ req, files: assistantFiles });- res.status(200).json({ message: 'File associations removed successfully from assistant' });+ const result = await processDeleteRequest({ req, files: assistantFiles });+ sendDeleteResult(result, 'File associations removed successfully from assistant');return;} else if (req.body.assistant_id &&req.body.files?.[0]?.filepath === EModelEndpoint.azureAssistants) {- await processDeleteRequest({ req, files: req.body.files });- return res- .status(200)- .json({ message: 'File associations removed successfully from Azure Assistant' });+ const result = await processDeleteRequest({ req, files: req.body.files });+ sendDeleteResult(result, 'File associations removed successfully from Azure Assistant');+ return;}- await processDeleteRequest({ req, files: authorizedFiles });+ const result = await processDeleteRequest({ req, files: authorizedFiles });logger.debug(`[/files] Files deleted successfully: ${authorizedFiles@@ -311,7 +314,7 @@ router.delete('/', async (req, res) => {.map((f) => f.file_id).join(', ')}`,);- res.status(200).json({ message: 'Files deleted successfully' });+ sendDeleteResult(result, 'Files deleted successfully');} catch (error) {logger.error('[/files] Error deleting files:', error);res.status(400).json({ message: 'Error in request', error: error.message });diff --git a/client/src/components/Chat/Input/ChatForm.tsx b/client/src/components/Chat/Input/ChatForm.tsxindex 91b56393a2..0bfe3f7416 100644--- a/client/src/components/Chat/Input/ChatForm.tsx+++ b/client/src/components/Chat/Input/ChatForm.tsx@@ -16,17 +16,27 @@ import {useSubmitMessage,useFocusChatEffect,} from '~/hooks';+import {+ cn,+ getModelSpec,+ hasIncompleteFiles,+ removeFocusRings,+ getComposerDraftId,+ getFilesDraftCached,+ isPastedTextFileMarked,+} from '~/utils';import {useChatContext,useChatFormContext,useAddedChatContext,useAssistantsMapContext,} from '~/Providers';-import { cn, getModelSpec, hasIncompleteFiles, removeFocusRings } from '~/utils';import PendingManualSkillsChips from './PendingManualSkillsChips';+import usePastedTextEdit from '~/hooks/Files/usePastedTextEdit';import useAskAnswerMode from '~/hooks/Input/useAskAnswerMode';import AskUserQuestionPopover from './AskUserQuestionPopover';import InterruptSteerButton from './InterruptSteerButton';+import PastedTextDialog from './Files/PastedTextDialog';import DuringRunSendButton from './DuringRunSendButton';import ProjectLandingChip from '../ProjectLandingChip';import { useGetStartupConfig } from '~/data-provider';@@ -197,6 +207,31 @@ const ChatForm = memo(function ChatForm({draftId: answerMode.draftId,});+ const pastedTextEdit = usePastedTextEdit({ index, files, setFiles, textAreaRef });++ /** Provenance, not the filename, decides which chips are pastes: a user can deliberately+ * upload a `pasted-text.txt`. Restored provenance comes from the files draft; marks made+ * this session are read live from the registry, so new pastes need no recompute. */+ const pastedTextFileIds = useMemo(() => {+ const draftId = getComposerDraftId(index, conversationId, isSubmitting);+ const draftIds = getFilesDraftCached(draftId).pastedTextIds ?? [];+ return new Set<string>(draftIds);+ }, [index, conversationId, isSubmitting]);+ const isPastedTextFile = useCallback(+ (file: ExtendedFile) =>+ pastedTextFileIds.has(file.file_id) ||+ (file.temp_file_id != null && pastedTextFileIds.has(file.temp_file_id)) ||+ isPastedTextFileMarked(file.file_id) ||+ isPastedTextFileMarked(file.temp_file_id),+ [pastedTextFileIds],+ );+ /** The chip's actions hide while a replacement upload or inline move is in flight, so the+ * same original cannot be acted on twice. */+ const isPasteActionPending = useCallback(+ (file: ExtendedFile) => pastedTextEdit.isActionPending(file.file_id),+ [pastedTextEdit],+ );+const { submitMessage, submitPrompt } = useSubmitMessage();/** Queued/steered sends carry their FULL submission context: explicit@@ -586,10 +621,20 @@ const ChatForm = memo(function ChatForm({setBadges={setBadges}/><FileFormChat+ index={index}conversation={conversation}files={files}setFiles={setFiles}setFilesLoading={setFilesLoading}+ isPastedTextFile={isPastedTextFile}+ isPasteActionPending={isPasteActionPending}+ onEditPastedText={pastedTextEdit.openEditor}+ onMovePastedTextInline={pastedTextEdit.moveInline}+ />+ <PastedTextDialog+ edit={pastedTextEdit.editing}+ onClose={pastedTextEdit.closeEditor}+ onSave={pastedTextEdit.saveEdit}/>{endpoint && (<div className={cn('flex', isRTL ? 'flex-row-reverse' : 'flex-row')}>diff --git a/client/src/components/Chat/Input/Files/FileContainer.tsx b/client/src/components/Chat/Input/Files/FileContainer.tsxindex c0790c7c72..9dfd53bf2e 100644--- a/client/src/components/Chat/Input/Files/FileContainer.tsx+++ b/client/src/components/Chat/Input/Files/FileContainer.tsx@@ -5,11 +5,19 @@ import { getFileType, cn } from '~/utils';import FilePreview from './FilePreview';import RemoveFile from './RemoveFile';+/** A second action offered in place of the subtitle, revealed when the chip is hovered or holds focus. */+export type SubtitleAction = {+ label: string;+ onClick: () => void;+};+const FileContainer = ({file,overrideType,displayName,subtitle,+ subtitleAction,+ ariaLabel,buttonClassName,containerClassName,onDelete,@@ -32,6 +40,19 @@ const FileContainer = ({* can include icons (spinner, alert) alongside the text.*/subtitle?: ReactNode;+ /**+ * Turns the subtitle line into its own control, so a chip can offer a second action without+ * spending another visible affordance on it. Supplying this drops the chip's own `<button>`+ * wrapper for a full-bleed one sitting behind the content, because a button inside a button+ * is invalid markup and browsers drop the inner one's events.+ */+ subtitleAction?: SubtitleAction;+ /**+ * Overrides the chip's accessible name. Callers that make the chip do something+ * (open an editor, open a preview) pass a label that says so, since the bare+ * filename does not tell a screen reader user that the chip is actionable.+ */+ ariaLabel?: string;buttonClassName?: string;containerClassName?: string;onDelete?: () => void;@@ -39,38 +60,98 @@ const FileContainer = ({}) => {const fileType = getFileType(overrideType ?? file.type);const visibleName = displayName ?? file.filename ?? '';+ const interactive = onClick != null;+ const surfaceClassName = cn(+ 'relative overflow-hidden rounded-2xl border border-border-light bg-surface-hover-alt',+ interactive && 'transition-colors hover:bg-surface-active',+ buttonClassName,+ );+ const focusRing =+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-text-primary focus-visible:ring-offset-1 focus-visible:ring-offset-surface-primary';+ /** The full-bleed target sits inside the surface's `overflow-hidden`, so an offset ring+ * would be clipped away entirely; the inset ring draws within the target's own box and the+ * matching radius keeps it inside the surface's rounded corners. */+ const insetFocusRing =+ 'focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-text-primary';++ const details = (+ <div className="w-56 p-1.5">+ <div className="flex flex-row items-center gap-2">+ <FilePreview file={file} fileType={fileType} className="relative" />+ <div className="overflow-hidden">+ <div className="truncate font-medium" title={visibleName}>+ {visibleName}+ </div>+ {subtitleAction != null ? (+ /** Sits above the full-bleed target so the subtitle keeps its own click. */+ <button+ type="button"+ onClick={subtitleAction.onClick}+ aria-label={subtitleAction.label}+ className={cn(+ /** Reads as the subtitle it replaces, so no colour of its own; the underline is+ * the only thing marking it as clickable, and it lands once the pointer is on+ * the label rather than merely on the chip. The hit area is the label and+ * nothing more: `inline-block` keeps it off the rest of the row, and+ * `leading-4` keeps it inside its 20px line so the chip's own center still+ * opens the editor. */+ 'pointer-events-auto relative z-10 inline-block max-w-full truncate rounded text-left align-middle leading-4 text-text-secondary hover:underline',+ focusRing,+ )}+ >+ <span+ aria-hidden="true"+ className="group-focus-within:hidden group-hover:hidden [@media(hover:none)]:hidden"+ >+ {fileType.title}+ </span>+ <span+ aria-hidden="true"+ className="hidden group-focus-within:inline group-hover:inline [@media(hover:none)]:inline"+ >+ {subtitleAction.label}+ </span>+ </button>+ ) : (+ (subtitle ?? (+ <div className="truncate text-text-secondary" title={fileType.title}>+ {fileType.title}+ </div>+ ))+ )}+ </div>+ </div>+ </div>+ );return (<divclassName={cn('group relative inline-block text-sm text-text-primary', containerClassName)}>- <button- type="button"- onClick={onClick}- aria-label={visibleName}- className={cn(- 'relative overflow-hidden rounded-2xl border border-border-light bg-surface-hover-alt',- buttonClassName,- )}- >- <div className="w-56 p-1.5">- <div className="flex flex-row items-center gap-2">- <FilePreview file={file} fileType={fileType} className="relative" />- <div className="overflow-hidden">- <div className="truncate font-medium" title={visibleName}>- {visibleName}- </div>- {subtitle != null ? (- subtitle- ) : (- <div className="truncate text-text-secondary" title={fileType.title}>- {fileType.title}- </div>- )}- </div>- </div>+ {subtitleAction != null ? (+ <div className={surfaceClassName}>+ <button+ type="button"+ onClick={onClick}+ aria-label={ariaLabel ?? visibleName}+ className={cn(+ 'absolute inset-0 z-0 rounded-2xl',+ interactive && 'cursor-pointer',+ insetFocusRing,+ )}+ />+ <div className="pointer-events-none relative">{details}</div></div>- </button>+ ) : (+ <button+ type="button"+ onClick={onClick}+ aria-label={ariaLabel ?? visibleName}+ className={cn(surfaceClassName, interactive && cn('cursor-pointer', focusRing))}+ >+ {details}+ </button>+ )}{onDelete && <RemoveFile onRemove={onDelete} />}</div>);diff --git a/client/src/components/Chat/Input/Files/FileFormChat.tsx b/client/src/components/Chat/Input/Files/FileFormChat.tsxindex 83ed052988..e93e37131b 100644--- a/client/src/components/Chat/Input/Files/FileFormChat.tsx+++ b/client/src/components/Chat/Input/Files/FileFormChat.tsx@@ -16,15 +16,29 @@ const ChatFileRowWrapper = ({ children }: { children: React.ReactNode }) => ();function FileFormChat({+ index,conversation,files,setFiles,setFilesLoading,+ isPastedTextFile,+ isPasteActionPending,+ onEditPastedText,+ onMovePastedTextInline,}: {+ index: number;conversation: TConversation | null;files: Map<string, ExtendedFile>;setFiles: FileSetter;setFilesLoading: React.Dispatch<React.SetStateAction<boolean>>;+ /** Marks chips the composer generated from a long paste, so only those offer the paste+ * affordances. Filenames cannot carry that decision: users can upload a `pasted-text.txt`. */+ isPastedTextFile?: (file: ExtendedFile) => boolean;+ /** Hides the paste actions while a replacement upload or inline move is in flight for the+ * chip, so the same original cannot be acted on twice. */+ isPasteActionPending?: (file: ExtendedFile) => boolean;+ onEditPastedText?: (file: ExtendedFile) => void;+ onMovePastedTextInline?: (file: ExtendedFile) => void;}) {const chatDirection = useRecoilValue(store.chatDirection).toLowerCase();const { endpoint: _endpoint } = conversation ?? { endpoint: null };@@ -41,11 +55,16 @@ function FileFormChat({<><FileRowfiles={files}+ index={index}setFiles={setFiles}abortUpload={abortUpload}setFilesLoading={setFilesLoading}isRTL={isRTL}Wrapper={ChatFileRowWrapper}+ isPastedTextFile={isPastedTextFile}+ isPasteActionPending={isPasteActionPending}+ onEditPastedText={onEditPastedText}+ onMovePastedTextInline={onMovePastedTextInline}/></>);diff --git a/client/src/components/Chat/Input/Files/FileRow.tsx b/client/src/components/Chat/Input/Files/FileRow.tsxindex 7f94c4b477..3e8d53ad1e 100644--- a/client/src/components/Chat/Input/Files/FileRow.tsx+++ b/client/src/components/Chat/Input/Files/FileRow.tsx@@ -26,9 +26,14 @@ export default function FileRow({assistant_id,agent_id,tool_resource,+ index,fileFilter,isRTL = false,Wrapper,+ isPastedTextFile,+ isPasteActionPending,+ onEditPastedText,+ onMovePastedTextInline,}: {files: Map<string, ExtendedFile> | undefined;abortUpload?: (fileId?: string) => void;@@ -38,8 +43,19 @@ export default function FileRow({assistant_id?: string;agent_id?: string;tool_resource?: EToolResources;+ index?: number;isRTL?: boolean;Wrapper?: React.FC<{ children: React.ReactNode }>;+ /** Marks chips the composer generated from a long paste. Provenance comes from the caller's+ * marker registry rather than the filename, which a deliberate upload can share. */+ isPastedTextFile?: (file: ExtendedFile) => boolean;+ /** Hides the paste actions while a replacement upload or inline move is in flight for the+ * chip, so the same original cannot be acted on twice. */+ isPasteActionPending?: (file: ExtendedFile) => boolean;+ /** Opens the paste editor. Only the composer passes it, so other rows stay inert chips. */+ onEditPastedText?: (file: ExtendedFile) => void;+ /** Returns a paste to the composer, offered from the chip's subtitle line. */+ onMovePastedTextInline?: (file: ExtendedFile) => void;}) {const localize = useLocalize();const { showToast } = useToastContext();@@ -64,7 +80,13 @@ export default function FileRow({},});- const { deleteFile } = useFileDeletion({ mutateAsync, agent_id, assistant_id, tool_resource });+ const { deleteFile } = useFileDeletion({+ mutateAsync,+ agent_id,+ assistant_id,+ tool_resource,+ index,+ });useEffect(() => {if (!setFilesLoading) return;@@ -119,7 +141,7 @@ export default function FileRow({},{ map: new Map(), uniqueFiles: [] as ExtendedFile[] },)- .uniqueFiles.map((file: ExtendedFile, index: number) => {+ .uniqueFiles.map((file: ExtendedFile, fileIndex: number) => {const handleDelete = () => {if (abortUpload && file.progress < 1) {abortUpload(file.file_id);@@ -133,10 +155,19 @@ export default function FileRow({deleteFile({ file, setFiles });};const isImage = file.type?.startsWith('image') ?? false;+ /** An upload still in flight has no stored text to open yet, and without a paste+ * marker the chip is an ordinary attachment however it is named. An action already+ * in flight against the chip hides both affordances until it settles. */+ const isEditablePaste =+ onEditPastedText != null &&+ isPastedTextFile != null &&+ file.progress >= 1 &&+ isPastedTextFile(file) &&+ !isPasteActionPending?.(file);return (<div- key={index}+ key={fileIndex}style={{flexBasis: '70px',flexGrow: 0,@@ -151,7 +182,24 @@ export default function FileRow({source={file.source}/>) : (- <FileContainer file={file} onDelete={handleDelete} />+ <FileContainer+ file={file}+ onDelete={handleDelete}+ onClick={isEditablePaste ? () => onEditPastedText(file) : undefined}+ ariaLabel={+ isEditablePaste+ ? localize('com_ui_pasted_text_edit_chip', { 0: file.filename ?? '' })+ : undefined+ }+ subtitleAction={+ isEditablePaste && onMovePastedTextInline != null+ ? {+ label: localize('com_ui_pasted_text_move_inline'),+ onClick: () => onMovePastedTextInline(file),+ }+ : undefined+ }+ />)}</div>);diff --git a/client/src/components/Chat/Input/Files/PastedTextDialog.tsx b/client/src/components/Chat/Input/Files/PastedTextDialog.tsxnew file mode 100644index 0000000000..6d6c88bd58--- /dev/null+++ b/client/src/components/Chat/Input/Files/PastedTextDialog.tsx@@ -0,0 +1,66 @@+import { useId, useState } from 'react';+import {+ Button,+ OGDialog,+ Textarea,+ OGDialogClose,+ OGDialogTitle,+ OGDialogHeader,+ OGDialogContent,+} from '@librechat/client';+import type { PastedTextEdit } from '~/hooks/Files/usePastedTextEdit';+import { useLocalize } from '~/hooks';++/**+ * Opens the text behind a `pasted-text.txt` chip so it can be corrected before sending. Returning+ * the paste to the composer lives on the chip itself rather than here.+ */+export default function PastedTextDialog({+ edit,+ onClose,+ onSave,+}: {+ /** Null while no chip is open; carries the resolved text so the field starts filled. */+ edit: PastedTextEdit | null;+ onClose: () => void;+ onSave: (text: string) => void;+}) {+ const localize = useLocalize();+ const fieldId = useId();+ const [text, setText] = useState('');+ const [openedFileId, setOpenedFileId] = useState<string | null>(null);++ /** Reset on the render that opens a different chip rather than in an effect. */+ const currentFileId = edit?.file.file_id ?? null;+ if (currentFileId !== openedFileId) {+ setOpenedFileId(currentFileId);+ setText(edit?.text ?? '');+ }++ const isEmpty = text.trim() === '';++ return (+ <OGDialog open={edit != null} onOpenChange={(open) => !open && onClose()}>+ <OGDialogContent className="w-11/12 max-w-4xl" showCloseButton={false}>+ <OGDialogHeader>+ <OGDialogTitle>{localize('com_ui_pasted_text_edit')}</OGDialogTitle>+ </OGDialogHeader>+ <Textarea+ id={fieldId}+ value={text}+ onChange={(e) => setText(e.target.value)}+ aria-label={localize('com_ui_pasted_text_edit')}+ className="h-[65vh] max-h-[70vh] min-h-[20rem] font-mono text-xs"+ />+ <div className="flex justify-end gap-2 pt-4">+ <OGDialogClose asChild>+ <Button variant="outline">{localize('com_ui_cancel')}</Button>+ </OGDialogClose>+ <Button variant="default" disabled={isEmpty} onClick={() => onSave(text)}>+ {localize('com_ui_save')}+ </Button>+ </div>+ </OGDialogContent>+ </OGDialog>+ );+}diff --git a/client/src/components/Chat/Input/Files/__tests__/FileContainer.spec.tsx b/client/src/components/Chat/Input/Files/__tests__/FileContainer.spec.tsxindex 3291eb5b8c..f072042387 100644--- a/client/src/components/Chat/Input/Files/__tests__/FileContainer.spec.tsx+++ b/client/src/components/Chat/Input/Files/__tests__/FileContainer.spec.tsx@@ -1,5 +1,7 @@import React from 'react';+import userEvent from '@testing-library/user-event';import { render, screen } from '@testing-library/react';+import '@testing-library/jest-dom';import type { TFile } from 'librechat-data-provider';import FileContainer from '../FileContainer';@@ -54,3 +56,150 @@ describe('FileContainer chip label', () => {expect(container.querySelector('.font-medium')?.textContent).toBe('');});});++describe('FileContainer subtitle action', () => {+ const subtitleAction = (onClick = jest.fn()) => ({ label: 'Move back into message', onClick });++ it('shows the file type until the chip is hovered', () => {+ render(+ <FileContainer file={baseFile()} onClick={jest.fn()} subtitleAction={subtitleAction()} />,+ );++ /** Both labels are in the DOM; which one shows is a `group-hover` swap CSS owns. */+ expect(screen.getByText('Plain')).toBeInTheDocument();+ expect(screen.getByText('Move back into message')).toBeInTheDocument();+ });++ it('names the subtitle control for screen readers regardless of the visible label', () => {+ render(+ <FileContainer file={baseFile()} onClick={jest.fn()} subtitleAction={subtitleAction()} />,+ );++ const control = screen.getByRole('button', { name: 'Move back into message' });+ expect(control).toBeInTheDocument();+ /** The swapped spans are decorative; the accessible name comes from the label. */+ expect(screen.getByText('Plain')).toHaveAttribute('aria-hidden', 'true');+ });++ it('runs the subtitle action without also opening the chip', async () => {+ const onClick = jest.fn();+ const onSubtitleClick = jest.fn();+ render(+ <FileContainer+ file={baseFile()}+ onClick={onClick}+ ariaLabel="Edit pasted text"+ subtitleAction={subtitleAction(onSubtitleClick)}+ />,+ );++ await userEvent.click(screen.getByRole('button', { name: 'Move back into message' }));++ expect(onSubtitleClick).toHaveBeenCalledTimes(1);+ expect(onClick).not.toHaveBeenCalled();+ });++ it('keeps the chip itself clickable alongside the subtitle control', async () => {+ const onClick = jest.fn();+ render(+ <FileContainer+ file={baseFile()}+ onClick={onClick}+ ariaLabel="Edit pasted text"+ subtitleAction={subtitleAction()}+ />,+ );++ await userEvent.click(screen.getByRole('button', { name: 'Edit pasted text' }));++ expect(onClick).toHaveBeenCalledTimes(1);+ });++ it('never nests the subtitle control inside the chip control', () => {+ const { container } = render(+ <FileContainer file={baseFile()} onClick={jest.fn()} subtitleAction={subtitleAction()} />,+ );++ /** A button inside a button is invalid markup and browsers drop the inner one's events. */+ expect(container.querySelector('button button')).toBeNull();+ });++ it('reveals the action from the whole chip rather than the label alone', () => {+ render(+ <FileContainer file={baseFile()} onClick={jest.fn()} subtitleAction={subtitleAction()} />,+ );++ /** The swap keys off the chip's own `group`, so pointing anywhere on the chip offers it. */+ const resting = screen.getByText('Plain');+ const revealed = screen.getByText('Move back into message');+ expect(resting.className).toContain('group-hover:hidden');+ expect(revealed.className).toContain('group-hover:inline');+ expect(`${resting.className} ${revealed.className}`).not.toContain('group-hover/');+ });++ it('reveals the action for keyboard users too', () => {+ render(+ <FileContainer file={baseFile()} onClick={jest.fn()} subtitleAction={subtitleAction()} />,+ );++ expect(screen.getByText('Plain').className).toContain('group-focus-within:hidden');+ expect(screen.getByText('Move back into message').className).toContain(+ 'group-focus-within:inline',+ );+ });++ it('keeps the action revealed on devices with no hover to reveal it', () => {+ render(+ <FileContainer file={baseFile()} onClick={jest.fn()} subtitleAction={subtitleAction()} />,+ );++ /** Touch has no hover or focus to announce the swap with, so the label itself must show:+ * an inert-looking "Plain Text" subtitle that detaches on tap is a trap, not an affordance. */+ expect(screen.getByText('Plain').className).toContain('[@media(hover:none)]:hidden');+ expect(screen.getByText('Move back into message').className).toContain(+ '[@media(hover:none)]:inline',+ );+ });++ it('keeps the full-chip focus indicator inside the clipped surface', () => {+ render(+ <FileContainer file={baseFile()} onClick={jest.fn()} subtitleAction={subtitleAction()} />,+ );++ /** The surface applies `overflow-hidden`, so an offset ring on the full-bleed button would+ * be clipped away entirely; the treatment draws inside the target instead. */+ const chipControl = screen.getByRole('button', { name: 'report.pdf' });+ expect(chipControl.className).toContain('focus-visible:ring-inset');+ expect(chipControl.className).not.toContain('ring-offset');+ });++ it('styles the action exactly like the subtitle it replaces', () => {+ render(+ <FileContainer file={baseFile()} onClick={jest.fn()} subtitleAction={subtitleAction()} />,+ );++ const control = screen.getByRole('button', { name: 'Move back into message' });+ expect(control.className).toContain('text-text-secondary');+ /** No colour of its own: it should read as the subtitle, not as a link. */+ expect(control.className).not.toContain('hover:text-text-primary');+ });++ it('underlines the action once the pointer is on the label itself', () => {+ render(+ <FileContainer file={baseFile()} onClick={jest.fn()} subtitleAction={subtitleAction()} />,+ );++ /** Keyed to the control's own hover, not the chip's, so the underline only shows up+ * under a pointer that is actually on the label. */+ const control = screen.getByRole('button', { name: 'Move back into message' });+ expect(control.className).toContain('hover:underline');+ expect(control.className).not.toContain('group-hover:underline');+ });++ it('leaves the plain subtitle alone when no action is offered', () => {+ render(<FileContainer file={baseFile()} onClick={jest.fn()} />);++ expect(screen.getByText('Plain')).toBeInTheDocument();+ expect(screen.queryByText('Move back into message')).not.toBeInTheDocument();+ });+});diff --git a/client/src/components/Chat/Input/Files/__tests__/FileRow.spec.tsx b/client/src/components/Chat/Input/Files/__tests__/FileRow.spec.tsxindex ccfa19ffc8..c4cb734091 100644--- a/client/src/components/Chat/Input/Files/__tests__/FileRow.spec.tsx+++ b/client/src/components/Chat/Input/Files/__tests__/FileRow.spec.tsx@@ -1,4 +1,5 @@import React from 'react';+import userEvent from '@testing-library/user-event';import { render, screen } from '@testing-library/react';import '@testing-library/jest-dom';import { FileSources } from 'librechat-data-provider';@@ -37,10 +38,20 @@ jest.mock('../Image', () => {});jest.mock('../FileContainer', () => {- return function MockFileContainer({ file }: any) {+ return function MockFileContainer({ file, onClick, ariaLabel, subtitleAction }: any) {return (<div data-testid="mock-file-container"><span data-testid="file-name">{file.filename}</span>+ {onClick != null && (+ <button type="button" aria-label={ariaLabel} onClick={onClick}>+ {file.filename}+ </button>+ )}+ {subtitleAction != null && (+ <button type="button" aria-label={subtitleAction.label} onClick={subtitleAction.onClick}>+ {subtitleAction.label}+ </button>+ )}</div>);};@@ -95,6 +106,27 @@ describe('FileRow', () => {);};+ it('passes the composer pane index to file deletion', () => {+ const file = createMockFile();+ const filesMap = new Map<string, ExtendedFile>();+ filesMap.set(file.file_id, file);++ render(+ <FileRow+ files={filesMap}+ setFiles={mockSetFiles}+ setFilesLoading={mockSetFilesLoading}+ index={1}+ />,+ );++ expect(mockUseFileDeletion).toHaveBeenCalledWith(+ expect.objectContaining({+ index: 1,+ }),+ );+ });+describe('Image URL Selection Logic', () => {it('should prefer cached preview over filepath when upload is complete', () => {const file = createMockFile({@@ -360,4 +392,150 @@ describe('FileRow', () => {);});});+ describe('Pasted-text editing', () => {+ const pastedFile = (overrides: Partial<ExtendedFile> = {}) =>+ createMockFile({+ file_id: 'pasted-file',+ type: 'text/plain',+ filename: 'pasted-text.txt',+ preview: undefined,+ filepath: '/uploads/user123/pasted-text.txt',+ ...overrides,+ });++ const renderWithEditor = (+ file: ExtendedFile,+ {+ isPaste = true,+ actionPending = false,+ onEditPastedText,+ onMovePastedTextInline,+ }: {+ /** Stands in for the provenance registry the composer passes down. */+ isPaste?: boolean;+ /** Stands in for the in-flight action lock the composer passes down. */+ actionPending?: boolean;+ onEditPastedText?: (f: ExtendedFile) => void;+ onMovePastedTextInline?: (f: ExtendedFile) => void;+ } = {},+ ) => {+ const filesMap = new Map<string, ExtendedFile>();+ filesMap.set(file.file_id, file);+ return render(+ <FileRow+ files={filesMap}+ setFiles={mockSetFiles}+ setFilesLoading={mockSetFilesLoading}+ isPastedTextFile={() => isPaste}+ isPasteActionPending={() => actionPending}+ onEditPastedText={onEditPastedText}+ onMovePastedTextInline={onMovePastedTextInline}+ />,+ );+ };++ it('opens the editor with the chip that was clicked', async () => {+ const onEditPastedText = jest.fn();+ const file = pastedFile();+ renderWithEditor(file, { onEditPastedText });++ await userEvent.click(screen.getByRole('button', { name: 'com_ui_pasted_text_edit_chip' }));++ expect(onEditPastedText).toHaveBeenCalledWith(file);+ });++ it('names the action rather than just the file for screen readers', () => {+ renderWithEditor(pastedFile(), { onEditPastedText: jest.fn() });++ expect(screen.getByRole('button').getAttribute('aria-label')).toBe(+ 'com_ui_pasted_text_edit_chip',+ );+ });++ it('numbered pastes are editable too', () => {+ renderWithEditor(pastedFile({ filename: 'pasted-text-2.txt' }), {+ onEditPastedText: jest.fn(),+ });++ expect(screen.getByRole('button')).toBeInTheDocument();+ });++ it('leaves a deliberate text upload inert', () => {+ renderWithEditor(pastedFile({ filename: 'notes.txt' }), { isPaste: false });++ expect(screen.queryByRole('button')).not.toBeInTheDocument();+ });++ it('leaves a deliberate upload named like a paste inert', () => {+ renderWithEditor(pastedFile(), { isPaste: false });++ expect(screen.queryByRole('button')).not.toBeInTheDocument();+ });++ it('waits for the upload to finish before offering the editor', () => {+ renderWithEditor(pastedFile({ progress: 0.4 }), { onEditPastedText: jest.fn() });++ expect(screen.queryByRole('button')).not.toBeInTheDocument();+ });++ it('stays inert where no editor is wired up', () => {+ renderWithEditor(pastedFile());++ expect(screen.queryByRole('button')).not.toBeInTheDocument();+ });++ it('stays inert where no provenance predicate is wired up', () => {+ const filesMap = new Map<string, ExtendedFile>();+ filesMap.set('pasted-file', pastedFile());+ render(+ <FileRow+ files={filesMap}+ setFiles={mockSetFiles}+ setFilesLoading={mockSetFilesLoading}+ onEditPastedText={jest.fn()}+ />,+ );++ expect(screen.queryByRole('button')).not.toBeInTheDocument();+ });++ it('offers returning the paste to the composer from the chip subtitle', async () => {+ const onMovePastedTextInline = jest.fn();+ const file = pastedFile();+ renderWithEditor(file, { onEditPastedText: jest.fn(), onMovePastedTextInline });++ await userEvent.click(screen.getByRole('button', { name: 'com_ui_pasted_text_move_inline' }));++ expect(onMovePastedTextInline).toHaveBeenCalledWith(file);+ });++ it('offers no subtitle action for a deliberate text upload', () => {+ renderWithEditor(pastedFile({ filename: 'notes.txt' }), {+ isPaste: false,+ onMovePastedTextInline: jest.fn(),+ });++ expect(+ screen.queryByRole('button', { name: 'com_ui_pasted_text_move_inline' }),+ ).not.toBeInTheDocument();+ });++ it('hides the paste actions while an action is in flight for the chip', () => {+ renderWithEditor(pastedFile(), {+ actionPending: true,+ onEditPastedText: jest.fn(),+ onMovePastedTextInline: jest.fn(),+ });++ expect(screen.queryByRole('button')).not.toBeInTheDocument();+ });++ it('offers no subtitle action where no handler is wired up', () => {+ renderWithEditor(pastedFile());++ expect(+ screen.queryByRole('button', { name: 'com_ui_pasted_text_move_inline' }),+ ).not.toBeInTheDocument();+ });+ });});diff --git a/client/src/components/Chat/Input/Files/__tests__/PastedTextDialog.spec.tsx b/client/src/components/Chat/Input/Files/__tests__/PastedTextDialog.spec.tsxnew file mode 100644index 0000000000..e22998ca87--- /dev/null+++ b/client/src/components/Chat/Input/Files/__tests__/PastedTextDialog.spec.tsx@@ -0,0 +1,109 @@+import React from 'react';+import userEvent from '@testing-library/user-event';+import { render, screen } from '@testing-library/react';+import '@testing-library/jest-dom';+import type { PastedTextEdit } from '~/hooks/Files/usePastedTextEdit';+import type { ExtendedFile } from '~/common';+import PastedTextDialog from '../PastedTextDialog';++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++const pastedFile = (file_id: string): ExtendedFile => ({+ file_id,+ filename: 'pasted-text.txt',+ type: 'text/plain',+ progress: 1,+ size: 4000,+});++const edit = (file_id: string, text: string): PastedTextEdit => ({+ file: pastedFile(file_id),+ text,+ conversationId: 'conversation-a',+ draftToken: Symbol('new-conversation-draft'),+});++describe('PastedTextDialog', () => {+ const renderDialog = (over: Partial<React.ComponentProps<typeof PastedTextDialog>> = {}) => {+ const props = {+ edit: edit('pasted-file', 'the original paste'),+ onClose: jest.fn(),+ onSave: jest.fn(),+ ...over,+ };+ return { ...props, ...render(<PastedTextDialog {...props} />) };+ };++ it('stays closed with nothing being edited', () => {+ renderDialog({ edit: null });++ expect(screen.queryByRole('dialog')).not.toBeInTheDocument();+ });++ it('opens with the resolved paste already in the field', () => {+ renderDialog();++ expect(screen.getByRole('textbox')).toHaveValue('the original paste');+ });++ it('saves what the user typed, not what was pasted', async () => {+ const { onSave } = renderDialog();++ const field = screen.getByRole('textbox');+ await userEvent.clear(field);+ await userEvent.type(field, 'corrected');+ await userEvent.click(screen.getByRole('button', { name: 'com_ui_save' }));++ expect(onSave).toHaveBeenCalledWith('corrected');+ });++ it('refuses to write an empty attachment', async () => {+ renderDialog();++ await userEvent.clear(screen.getByRole('textbox'));++ expect(screen.getByRole('button', { name: 'com_ui_save' })).toBeDisabled();+ });++ it('leaves returning the paste to the composer to the chip', () => {+ renderDialog();++ expect(+ screen.queryByRole('button', { name: 'com_ui_pasted_text_move_inline' }),+ ).not.toBeInTheDocument();+ });++ it('discards an abandoned edit when a different chip is opened', async () => {+ const { rerender, onSave } = renderDialog();++ await userEvent.clear(screen.getByRole('textbox'));+ await userEvent.type(screen.getByRole('textbox'), 'abandoned');+ rerender(+ <PastedTextDialog+ edit={edit('second-file', 'the second paste')}+ onClose={jest.fn()}+ onSave={onSave}+ />,+ );++ expect(screen.getByRole('textbox')).toHaveValue('the second paste');+ });++ it('reopening the same chip starts from its stored text again', async () => {+ const { rerender } = renderDialog();++ await userEvent.type(screen.getByRole('textbox'), ' plus more');+ rerender(<PastedTextDialog edit={null} onClose={jest.fn()} onSave={jest.fn()} />);+ rerender(+ <PastedTextDialog+ edit={edit('pasted-file', 'the original paste')}+ onClose={jest.fn()}+ onSave={jest.fn()}+ />,+ );++ expect(screen.getByRole('textbox')).toHaveValue('the original paste');+ });+});diff --git a/client/src/components/Chat/Presentation.tsx b/client/src/components/Chat/Presentation.tsxindex 3a09112463..af383fff73 100644--- a/client/src/components/Chat/Presentation.tsx+++ b/client/src/components/Chat/Presentation.tsx@@ -10,6 +10,7 @@ import { useDeleteFilesMutation } from '~/data-provider';import { SidePanelGroup } from '~/components/SidePanel';import { activeSubagentPanel } from '~/store/subagents';import { useSetFilesToDelete } from '~/hooks';+import { failedFileIdsFrom } from '~/utils';import store from '~/store';const Artifacts = lazy(() => import('~/components/Artifacts/Artifacts'));@@ -45,9 +46,29 @@ export default function Presentation({ children }: { children: React.ReactNode }const setFilesToDelete = useSetFilesToDelete();const { mutateAsync } = useDeleteFilesMutation({- onSuccess: () => {+ onSuccess: (result) => {console.log('Temporary Files deleted');- setFilesToDelete({});+ const failed = new Set(failedFileIdsFrom(result));+ if (failed.size === 0) {+ setFilesToDelete({});+ return;+ }+ try {+ const filesToDelete = localStorage.getItem(LocalStorageKeys.FILES_TO_DELETE);+ const map = JSON.parse(filesToDelete ?? '{}') as Record<string, ExtendedFile>;+ const remaining: Record<string, ExtendedFile> = {};+ for (const [key, file] of Object.entries(map)) {+ if (+ (file.file_id != null && failed.has(file.file_id)) ||+ (file.temp_file_id != null && failed.has(file.temp_file_id))+ ) {+ remaining[key] = file;+ }+ }+ setFilesToDelete(remaining);+ } catch {+ // Keep existing records if reading or parsing fails.+ }},onError: (error) => {console.log('Error deleting temporary files:', error);diff --git a/client/src/components/UnifiedSidebar/mobile/__tests__/BottomBar.spec.tsx b/client/src/components/UnifiedSidebar/mobile/__tests__/BottomBar.spec.tsxindex 7db76f18e3..96e2a0ecfe 100644--- a/client/src/components/UnifiedSidebar/mobile/__tests__/BottomBar.spec.tsx+++ b/client/src/components/UnifiedSidebar/mobile/__tests__/BottomBar.spec.tsx@@ -21,6 +21,8 @@ jest.mock('@librechat/client', () => ({children: React.ReactNode;asChild?: boolean;}) => <div {...props}>{children}</div>,+ /** The real `useNewChat` pulls the file-deletion mutation, which reads the toast context. */+ useToastContext: () => ({ showToast: jest.fn() }),}));jest.mock('~/Providers', () => ({diff --git a/client/src/data-provider/Files/mutations.ts b/client/src/data-provider/Files/mutations.tsindex 097829022a..900cb10629 100644--- a/client/src/data-provider/Files/mutations.ts+++ b/client/src/data-provider/Files/mutations.ts@@ -178,12 +178,12 @@ export const useDeleteFilesMutation = (const queryClient = useQueryClient();const { showToast } = useToastContext();const localize = useLocalize();- const { onSuccess, onError, ...options } = _options || {};+ const { onSuccess, onError, silent = false, ...options } = _options || {};return useMutation([MutationKeys.fileDelete], {mutationFn: (body: t.DeleteFilesBody) => dataService.deleteFiles(body),...options,onError: (error, vars, context) => {- if (error && typeof error === 'object' && 'response' in error) {+ if (!silent && error && typeof error === 'object' && 'response' in error) {const errorWithResponse = error as { response?: { status?: number } };if (errorWithResponse.response?.status === 403) {showToast({@@ -195,21 +195,32 @@ export const useDeleteFilesMutation = (onError?.(error, vars, context);},onSuccess: (data, vars, context) => {+ /** Only a reported failure leaves a record on disk, so everything else the request named+ * is gone. Reading it the other way around would strand a row the server never had: a+ * file another tab already deleted matches no record, and the route answers that with+ * both id lists empty. Failed ids stay cached so the retry can still find them. */+ const failed = new Set(data?.failedFileIds ?? []);queryClient.setQueryData<t.TFile[] | undefined>([QueryKeys.files], (cachefiles) => {const { files: filesDeleted } = vars;-- const fileMap = filesDeleted.reduce((acc, file) => {- acc.set(file.file_id, file);+ const requested = filesDeleted.reduce((acc, file) => {+ acc.add(file.file_id);return acc;- }, new Map<string, t.BatchFile>());+ }, new Set<string>());- return (cachefiles ?? []).filter((file) => !fileMap.has(file.file_id));+ return (cachefiles ?? []).filter(+ (file) => !requested.has(file.file_id) || failed.has(file.file_id),+ );});- showToast({- message: localize('com_ui_delete_success'),- status: 'success',- });+ /** A storage failure still answers 200, so reporting success off the status alone would+ * tell the user a file is gone while it is sitting on disk and back in their list. */+ if (!silent) {+ showToast(+ failed.size > 0+ ? { message: localize('com_ui_delete_partial_failure'), status: 'error' }+ : { message: localize('com_ui_delete_success'), status: 'success' },+ );+ }onSuccess?.(data, vars, context);if (vars.agent_id != null && vars.agent_id) {diff --git a/client/src/hooks/AuthContext.tsx b/client/src/hooks/AuthContext.tsxindex 73a8742007..a44c6aab26 100644--- a/client/src/hooks/AuthContext.tsx+++ b/client/src/hooks/AuthContext.tsx@@ -8,8 +8,8 @@ import {createContext,} from 'react';import { debounce } from 'lodash';-import { useRecoilState, useSetRecoilState } from 'recoil';import { useNavigate } from 'react-router-dom';+import { useRecoilState, useSetRecoilState } from 'recoil';import {apiBaseUrl,SystemRoles,@@ -19,6 +19,14 @@ import {} from 'librechat-data-provider';import type * as t from 'librechat-data-provider';import type { ReactNode } from 'react';+import {+ SESSION_KEY,+ isSafeRedirect,+ getPostLoginRedirect,+ clearComposerDraftStorage,+ clearRetainedFileDeletions,+ openFileDeletionRetention,+} from '~/utils';import {useGetRole,useGetUserQuery,@@ -27,7 +35,6 @@ import {useRefreshTokenMutation,} from '~/data-provider';import { TAuthConfig, TUserContext, TAuthContext, TResError } from '~/common';-import { SESSION_KEY, isSafeRedirect, getPostLoginRedirect } from '~/utils';import useTimeout from './useTimeout';import store from '~/store';@@ -37,6 +44,17 @@ if (import.meta.hot) {import.meta.hot.data.__AuthContext = AuthContext;}+/** Client state belonging to the session that is ending. Drafts go out with the retained+ * deletions rather than being left to the next sign-in: a social sign-in returns through the+ * silent refresh and never passes the login mutation that clears them, and the browser tab keeps+ * its identity across an in-app account switch, so the account on the way out is the only place+ * that reliably sees the transition. Both are cleared together so neither can be added to an exit+ * path the other was wired into. */+const endSessionClientState = (): void => {+ clearRetainedFileDeletions();+ clearComposerDraftStorage();+};+const AuthContextProvider = ({authConfig,children,@@ -77,6 +95,17 @@ const AuthContextProvider = ({setIsAuthenticated(isAuthenticated);if (isAuthenticated) {setQueriesEnabled(true);+ /** The clear on the way out latches retention shut so a DELETE that settles afterwards+ * cannot write the departing account's payload back in. This is the only place that+ * knows a new session exists to reopen it for. */+ openFileDeletionRetention();+ } else {+ /** Cleanup still queued from a failed delete belongs to the account that uploaded+ * those files, and losing the session passes through here every way it can happen: the+ * explicit logout, a silent refresh that comes back empty, and a failed user query.+ * Carrying the queue across would retry it under whoever signs in next, which the+ * ownership check rejects forever instead of cleaning anything up. */+ endSessionClientState();}const searchParams = new URLSearchParams(window.location.search);@@ -127,15 +156,17 @@ const AuthContextProvider = ({const logoutUser = useLogoutUserMutation({onSuccess: (data) => {if (data.redirect) {- /** data.redirect is the IdP's end_session_endpoint URL — an absolute URL generated+ /** data.redirect is the IdP's end_session_endpoint URL: an absolute URL generated* server-side from trusted IdP metadata (not user input), so isSafeRedirect is bypassed.* setUserContext is debounced (50ms) and won't fire before page unload, so clear the- * axios Authorization header synchronously to prevent in-flight requests. */+ * axios Authorization header and deletion state synchronously to prevent in-flight requests. */isExternalRedirectRef.current = true;setTokenHeader(undefined);+ endSessionClientState();window.location.replace(data.redirect);return;}+ endSessionClientState();setUserContext({token: undefined,isAuthenticated: false,@@ -144,6 +175,7 @@ const AuthContextProvider = ({});},onError: (error) => {+ endSessionClientState();doSetError((error as Error).message);setUserContext({token: undefined,@@ -202,6 +234,7 @@ const AuthContextProvider = ({return;}console.log('Token is not present. User is not authenticated.');+ endSessionClientState();if (authConfig?.test === true) {return;}@@ -212,6 +245,7 @@ const AuthContextProvider = ({return;}console.log('refreshToken mutation error:', error);+ endSessionClientState();if (authConfig?.test === true) {return;}@@ -228,6 +262,7 @@ const AuthContextProvider = ({if (userQuery.data) {setUser(userQuery.data);} else if (userQuery.isError) {+ endSessionClientState();doSetError((userQuery.error as Error).message);navigate(buildLoginRedirectUrl(), { replace: true });}@@ -237,6 +272,9 @@ const AuthContextProvider = ({if (token == null || !token || !isAuthenticated) {silentRefresh();}+ /** `doSetError` is `useTimeout`'s inner closure, rebuilt every render, and this effect calls+ * `silentRefresh`: depending on it would re-fire the refresh mutation on every render. */+ // eslint-disable-next-line react-hooks/exhaustive-deps}, [token,isAuthenticated,@@ -283,6 +321,9 @@ const AuthContextProvider = ({isAuthenticated,}),+ /** `login` is a plain function rebuilt every render, so depending on it would rebuild this+ * context value every render and re-render every consumer of auth state. */+ // eslint-disable-next-line react-hooks/exhaustive-deps[user,error,diff --git a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsxindex d395b03b71..e964bb56e9 100644--- a/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx+++ b/client/src/hooks/Chat/__tests__/useChatFunctions.regenerate.spec.tsx@@ -2,6 +2,7 @@ import { renderHook, act } from '@testing-library/react';import { Constants, EModelEndpoint } from 'librechat-data-provider';import type { TConversation, TMessage, TSubmission } from 'librechat-data-provider';import useChatFunctions from '../useChatFunctions';+import { isPasteSubmitted } from '~/utils';const mockNavigate = jest.fn();const mockSetShowStopButton = jest.fn();@@ -342,4 +343,44 @@ describe('useChatFunctions ask attachments', () => {filename: 'quarterly-report.pdf',});});++ it('marks files consumed through overrideFiles as submitted', () => {+ const overrideFiles = [+ {+ file_id: 'queued-override-file',+ temp_file_id: 'queued-override-temp-file',+ filepath: '/uploads/queued-override-file',+ filename: 'queued-override.txt',+ type: 'text/plain',+ },+ ];+ const setMessages = jest.fn();+ const setSubmission = jest.fn();+ const setFiles = jest.fn();++ const { result } = renderHook(() =>+ useChatFunctions({+ isSubmitting: false,+ latestMessage: null,+ conversation: conversation(Constants.NEW_CONVO as string),+ getMessages: () => [],+ setMessages,+ setSubmission,+ files: new Map(),+ setFiles,+ }),+ );++ act(() => {+ result.current.ask(+ { text: 'queued override' },+ {+ overrideFiles,+ },+ );+ });++ expect(isPasteSubmitted('queued-override-file')).toBe(true);+ expect(isPasteSubmitted('queued-override-temp-file')).toBe(true);+ });});diff --git a/client/src/hooks/Chat/__tests__/useNewChat.spec.ts b/client/src/hooks/Chat/__tests__/useNewChat.spec.tsindex 0b74a8cf3e..ce9df1bb36 100644--- a/client/src/hooks/Chat/__tests__/useNewChat.spec.ts+++ b/client/src/hooks/Chat/__tests__/useNewChat.spec.ts@@ -1,17 +1,73 @@import { renderHook, act } from '@testing-library/react';import type { MouseEvent } from 'react';+import type { FilesDraft } from '~/utils';const mockNewConversation = jest.fn();const mockClearMessagesCache = jest.fn();const mockInvalidateQueries = jest.fn();+const mockClearAllDrafts = jest.fn();+const mockDeleteFiles = jest.fn();+const mockScheduleRetainedRetry = jest.fn();++/** A live composer entry: what the ownership check reads off the file map. */+type LiveFile = {+ file_id: string;+ attached?: boolean;+ progress?: number;+ filepath?: string;+ source?: string;+ embedded?: boolean;+};++/** Values the module-level mocks read, so each test can stage its own scenario. */+const mockState = {+ saveDrafts: false,+ isSubmitting: false,+ tabId: 'this-tab',+ filesDraft: { fileIds: [], pendingPastes: {} } as FilesDraft,+ pendingFilesDraft: { fileIds: [], pendingPastes: {} } as FilesDraft,+ files: new Map<string, LiveFile>(),+ retainedDeletions: [] as { file_id: string; filepath: string; source: string }[],+ markedPasteIds: [] as string[],+ submittedPasteIds: [] as string[],+ liveAttachmentIds: [] as string[],+ /** What other live tabs publish and have drafted; the real collectors read these from shared+ * storage, and a discard must treat them as protection while ignoring its own. */+ foreignLiveAttachmentIds: [] as string[],+ foreignDraftedIds: [] as string[],+ retainedPassInFlight: false,+ persistedPendingDiscardIds: [] as string[],+ retainedListener: null as (() => void) | null,+ pendingDiscardListener: null as (() => void) | null,+ fileList: undefined as+ | {+ file_id: string;+ filepath: string;+ source: string;+ embedded?: boolean;+ temp_file_id?: string;+ }[]+ | undefined,+};jest.mock('@tanstack/react-query', () => ({useQueryClient: () => ({ invalidateQueries: mockInvalidateQueries }),}));jest.mock('recoil', () => ({- useRecoilValue: () => 'convo-1',+ useRecoilValue: (key: unknown) => {+ if (typeof key === 'string' && key.startsWith('conversationIdByIndex')) {+ return 'convo-1';+ }+ if (typeof key === 'string' && key.startsWith('files-by-index')) {+ return mockState.files;+ }+ if (typeof key === 'string' && key.startsWith('isSubmitting')) {+ return mockState.isSubmitting;+ }+ return mockState.saveDrafts;+ },}));jest.mock('~/hooks/useNewConvo', () => ({@@ -21,11 +77,137 @@ jest.mock('~/hooks/useNewConvo', () => ({jest.mock('~/utils', () => ({clearMessagesCache: (...args: unknown[]) => mockClearMessagesCache(...args),+ clearAllDrafts: (...args: unknown[]) => mockClearAllDrafts(...args),+ getNewConversationDraftId: (index = 0) => (index === 0 ? 'new' : `new:${index}`),+ getPendingDraftId: (index = 0) => (index === 0 ? 'pending' : `pending:${index}`),+ getComposerDraftId: (index = 0, conversationId?: string | null) => {+ if (conversationId != null && conversationId !== '') {+ return conversationId;+ }+ return index === 0 ? 'new' : `new:${index}`;+ },+ getFilesDraft: (id: string) =>+ id === 'pending' || (typeof id === 'string' && id.startsWith('pending:'))+ ? mockState.pendingFilesDraft+ : mockState.filesDraft,+ isFilesDraftOwnedByThisTab: (draft: { tabId?: string }) =>+ draft.tabId == null || draft.tabId === mockState.tabId,+ loadPendingDiscardIds: () => [...mockState.persistedPendingDiscardIds],+ storePendingDiscardIds: (_index: number, ids: string[]) => {+ mockState.persistedPendingDiscardIds = [...ids];+ },+ subscribePendingDiscardIds: (listener: () => void) => {+ mockState.pendingDiscardListener = listener;+ return () => {+ mockState.pendingDiscardListener = null;+ };+ },+ subscribeRetainedFileDeletions: (listener: () => void) => {+ mockState.retainedListener = listener;+ return () => {+ mockState.retainedListener = null;+ mockState.pendingDiscardListener = null;+ };+ },+ takeRetainedFileDeletions: () => mockState.retainedDeletions,+ clearRetainedFileDeletion: (fileId: string) => {+ mockState.retainedDeletions = mockState.retainedDeletions.filter(+ (record) => record.file_id !== fileId,+ );+ },+ failedFileIdsFrom: (result: { failedFileIds?: string[] } | void) =>+ result != null && Array.isArray(result.failedFileIds) ? result.failedFileIds : [],+ scheduleRetainedFileDeletionRetry: () => mockScheduleRetainedRetry(),+ isPastedTextFileMarked: (fileId: string) => mockState.markedPasteIds.includes(fileId),+ isPasteSubmitted: (fileId: string) => mockState.submittedPasteIds.includes(fileId),+ collectLiveAttachmentIds: ({ excludeOwnPane }: { excludeOwnPane?: number | 'tab' } = {}) =>+ new Set<string>(+ excludeOwnPane === undefined+ ? [...mockState.liveAttachmentIds, ...mockState.foreignLiveAttachmentIds]+ : mockState.foreignLiveAttachmentIds,+ ),+ /** The union every deletion path consults: other tabs' drafts and other tabs' live presence,+ * with the caller's own discarded draft keys left out. */+ collectForeignAttachmentClaims: (excludeDraftIds: string[] = []) => {+ const ids = new Set<string>(mockState.foreignDraftedIds);+ const excluded = new Set(excludeDraftIds);+ const own: [string, FilesDraft][] = [+ ['new', mockState.filesDraft],+ ['pending', mockState.pendingFilesDraft],+ ];+ for (const [draftId, draft] of own) {+ if (excluded.has(draftId)) {+ continue;+ }+ for (const fileId of draft.fileIds) {+ ids.add(fileId);+ }+ for (const pasteId of draft.pastedTextIds ?? []) {+ ids.add(pasteId);+ }+ for (const pendingId of Object.keys(draft.pendingPastes)) {+ ids.add(pendingId);+ }+ }+ for (const id of mockState.foreignLiveAttachmentIds) {+ ids.add(id);+ }+ return ids;+ },+ removeTabAttachmentPresence: (ids: string[]) => {+ const idSet = new Set(ids);+ mockState.liveAttachmentIds = mockState.liveAttachmentIds.filter((id) => !idSet.has(id));+ },+ beginRetainedDeletionPass: () => {+ if (mockState.retainedPassInFlight) {+ return false;+ }+ mockState.retainedPassInFlight = true;+ return true;+ },+ endRetainedDeletionPass: () => {+ mockState.retainedPassInFlight = false;+ },+ /** Stands in for the localStorage sweep: the ids every draft is holding, minus the keys the+ * caller is discarding. Other tabs' drafts are never excludable, which is the point. */+ collectDraftedAttachmentIds: (excludeIds: string[] = []) => {+ const ids = new Set<string>(mockState.foreignDraftedIds);+ const excluded = new Set(excludeIds);+ const own: [string, FilesDraft][] = [+ ['new', mockState.filesDraft],+ ['pending', mockState.pendingFilesDraft],+ ];+ for (const [draftId, draft] of own) {+ if (excluded.has(draftId)) {+ continue;+ }+ for (const fileId of draft.fileIds) {+ ids.add(fileId);+ }+ for (const pasteId of draft.pastedTextIds ?? []) {+ ids.add(pasteId);+ }+ for (const pendingId of Object.keys(draft.pendingPastes)) {+ ids.add(pendingId);+ }+ }+ return ids;+ },+}));++jest.mock('~/data-provider', () => ({+ useGetFiles: () => ({ data: mockState.fileList }),+ useDeleteFilesMutation: () => ({ mutateAsync: mockDeleteFiles }),}));jest.mock('~/store', () => ({__esModule: true,- default: { conversationIdByIndex: (index: number) => `conversationIdByIndex-${index}` },+ default: {+ conversationIdByIndex: (index: number) => `conversationIdByIndex-${index}`,+ filesByIndex: (index: number) => `files-by-index-${index}`,+ isSubmittingFamily: (index: number) => `isSubmitting-${index}`,+ saveDrafts: 'saveDrafts',+ },}));jest.mock('librechat-data-provider', () => ({@@ -47,6 +229,25 @@ const clickEvent = (overrides: Partial<MouseEvent<HTMLElement>> = {}) =>describe('useNewChat', () => {beforeEach(() => {jest.clearAllMocks();+ mockDeleteFiles.mockResolvedValue(undefined);+ mockState.saveDrafts = false;+ mockState.isSubmitting = false;+ mockState.tabId = 'this-tab';+ mockState.filesDraft = { fileIds: [], pendingPastes: {} };+ mockState.pendingFilesDraft = { fileIds: [], pendingPastes: {} };+ mockState.files = new Map();+ mockState.fileList = undefined;+ mockState.retainedDeletions = [];+ mockState.persistedPendingDiscardIds = [];+ mockState.retainedListener = null;+ mockState.pendingDiscardListener = null;+ mockState.markedPasteIds = [];+ mockState.submittedPasteIds = [];+ mockState.liveAttachmentIds = [];+ mockState.foreignLiveAttachmentIds = [];+ mockState.foreignDraftedIds = [];+ mockState.retainedPassInFlight = false;+ mockScheduleRetainedRetry.mockClear();});it('clears the outgoing conversation before resetting', () => {@@ -59,6 +260,839 @@ describe('useNewChat', () => {expect(mockNewConversation).toHaveBeenCalledTimes(1);});+ it('drops the unsaved-chat draft before the reset restores from it', () => {+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockClearAllDrafts).toHaveBeenCalledWith('new');+ expect(mockClearAllDrafts.mock.invocationCallOrder[0]).toBeLessThan(+ mockNewConversation.mock.invocationCallOrder[0],+ );+ });++ it('drops only its own pane unsaved-chat draft', () => {+ const { result } = renderHook(() => useNewChat({ index: 1 }));++ act(() => result.current.startNewChat());++ expect(mockClearAllDrafts).toHaveBeenCalledWith('new:1');+ expect(mockClearAllDrafts).not.toHaveBeenCalledWith('new');+ });++ it('deletes the draft uploads a draft-saving user is discarding with the draft', () => {+ mockState.saveDrafts = true;+ mockState.filesDraft = {+ fileIds: ['stored-file'],+ pendingPastes: { 'in-flight-paste': { text: 'x', selectionStart: 0 } },+ };+ mockState.files = new Map([+ ['stored-file', { file_id: 'stored-file', progress: 1 }],+ ['in-flight-paste', { file_id: 'in-flight-paste', progress: 0.4 }],+ ]);+ mockState.fileList = [+ { file_id: 'stored-file', filepath: '/uploads/stored.txt', source: 'local' },+ { file_id: 'in-flight-paste', filepath: '/uploads/pending.txt', source: 'local' },+ ];+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [+ {+ file_id: 'stored-file',+ embedded: false,+ filepath: '/uploads/stored.txt',+ source: 'local',+ },+ {+ file_id: 'in-flight-paste',+ embedded: false,+ filepath: '/uploads/pending.txt',+ source: 'local',+ },+ ],+ });+ expect(mockDeleteFiles.mock.invocationCallOrder[0]).toBeLessThan(+ mockClearAllDrafts.mock.invocationCallOrder[0],+ );+ });++ it('leaves deletion to the reset path when draft saving is off', () => {+ mockState.saveDrafts = false;+ mockState.filesDraft = {+ fileIds: ['stored-file'],+ pendingPastes: {},+ };+ mockState.fileList = [+ { file_id: 'stored-file', filepath: '/uploads/stored.txt', source: 'local' },+ ];+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).not.toHaveBeenCalled();+ });++ it('discards a live generated paste the draft could not record', () => {+ /** Persisting the draft can fail outright (private mode, quota) while the upload and its+ * chip still succeed, leaving the draft empty and the upload with nothing to clean it up. */+ mockState.saveDrafts = true;+ mockState.filesDraft = { fileIds: [], pendingPastes: {} };+ mockState.markedPasteIds = ['unrecorded-paste'];+ mockState.files = new Map([+ [+ 'unrecorded-paste',+ {+ file_id: 'unrecorded-paste',+ progress: 1,+ filepath: '/uploads/unrecorded.txt',+ source: 'local',+ },+ ],+ ]);+ mockState.fileList = [];+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [expect.objectContaining({ file_id: 'unrecorded-paste' })],+ });+ });++ it('spares a paste a message already took, even after the run ends', () => {+ /** Submitting empties the file map but leaves the draft's provenance behind, and Stop and+ * error paths clear the submitting flag without clearing the draft. */+ mockState.saveDrafts = true;+ mockState.submittedPasteIds = ['sent-paste'];+ mockState.filesDraft = { fileIds: [], pendingPastes: {}, pastedTextIds: ['sent-paste'] };+ mockState.files = new Map();+ mockState.fileList = [+ { file_id: 'sent-paste', filepath: '/uploads/sent.txt', source: 'local' },+ ];+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).not.toHaveBeenCalled();+ });++ it('discards a completed paste marked under its temporary upload id', () => {+ /** The registry holds the client id; the finished entry carries the server one and keeps the+ * original as temp_file_id. */+ mockState.saveDrafts = true;+ mockState.filesDraft = { fileIds: [], pendingPastes: {} };+ mockState.markedPasteIds = ['client-upload-id'];+ mockState.files = new Map([+ [+ 'client-upload-id',+ {+ file_id: 'server-file-id',+ temp_file_id: 'client-upload-id',+ progress: 1,+ filepath: '/uploads/paste.txt',+ source: 'local',+ },+ ],+ ]);+ mockState.fileList = [];+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [expect.objectContaining({ file_id: 'server-file-id' })],+ });+ });++ it('defers an in-flight paste upload even with draft saving off', () => {+ /** It has no filepath yet, so nothing can build a payload for it now; the id has to outlive+ * the reset or the record it becomes is orphaned. */+ mockState.saveDrafts = false;+ mockState.markedPasteIds = ['in-flight-paste'];+ mockState.files = new Map([['in-flight-paste', { file_id: 'in-flight-paste', progress: 0.3 }]]);+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockState.persistedPendingDiscardIds).toContain('in-flight-paste');+ });++ it('spares a marked paste that came back re-attached from the library', () => {+ mockState.saveDrafts = true;+ mockState.filesDraft = { fileIds: [], pendingPastes: {} };+ mockState.markedPasteIds = ['sent-paste'];+ mockState.files = new Map([+ [+ 'sent-paste',+ {+ file_id: 'sent-paste',+ progress: 1,+ attached: true,+ filepath: '/uploads/sent.txt',+ source: 'local',+ },+ ],+ ]);+ mockState.fileList = [];+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).not.toHaveBeenCalled();+ });++ it('deletes embedded owned uploads with the discarded draft', () => {+ mockState.saveDrafts = true;+ mockState.filesDraft = {+ fileIds: ['known', 'embedded', 'missing'],+ pendingPastes: {},+ };+ mockState.files = new Map([+ ['known', { file_id: 'known', progress: 1 }],+ ['embedded', { file_id: 'embedded', progress: 1 }],+ ]);+ mockState.fileList = [+ { file_id: 'known', filepath: '/uploads/known.txt', source: 'local' },+ { file_id: 'embedded', filepath: '/uploads/embedded.txt', source: 'local', embedded: true },+ ];+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [+ { file_id: 'known', embedded: false, filepath: '/uploads/known.txt', source: 'local' },+ {+ file_id: 'embedded',+ embedded: true,+ filepath: '/uploads/embedded.txt',+ source: 'local',+ },+ ],+ });+ });++ it('spares a draft another browser tab still owns', () => {+ mockState.saveDrafts = true;+ mockState.filesDraft = {+ fileIds: ['other-tab-file'],+ pendingPastes: {},+ tabId: 'other-tab',+ };+ mockState.fileList = [+ { file_id: 'other-tab-file', filepath: '/uploads/other.txt', source: 'local' },+ ];+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).not.toHaveBeenCalled();+ expect(mockClearAllDrafts).not.toHaveBeenCalledWith('new');+ expect(mockClearAllDrafts).toHaveBeenCalledWith('pending');+ });++ it('deletes a draft carrying this tab stamp', () => {+ mockState.saveDrafts = true;+ mockState.filesDraft = {+ fileIds: ['own-file'],+ pendingPastes: {},+ tabId: 'this-tab',+ };+ mockState.files = new Map([['own-file', { file_id: 'own-file', progress: 1 }]]);+ mockState.fileList = [{ file_id: 'own-file', filepath: '/uploads/own.txt', source: 'local' }];+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [+ { file_id: 'own-file', embedded: false, filepath: '/uploads/own.txt', source: 'local' },+ ],+ });+ });++ it('spares a discarded paste another live tab is holding', () => {+ /** The retry effect consults other tabs before deleting; this direct path has to as well, or+ * New Chat here deletes the server file out from under the other tab's chip. */+ mockState.saveDrafts = true;+ mockState.filesDraft = {+ fileIds: ['shared-file'],+ pendingPastes: {},+ tabId: 'this-tab',+ };+ mockState.files = new Map([['shared-file', { file_id: 'shared-file', progress: 1 }]]);+ mockState.fileList = [+ { file_id: 'shared-file', filepath: '/uploads/shared.txt', source: 'local' },+ ];+ mockState.foreignLiveAttachmentIds = ['shared-file'];+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).not.toHaveBeenCalled();+ });++ it('spares a discarded paste another tab has drafted elsewhere', () => {+ /** That tab reattached the file to a conversation this pane has never opened, so only its+ * persisted draft records it. This tab's own discarded keys are excluded from that lookup,+ * or every discard would protect itself and nothing would ever be cleaned up. */+ mockState.saveDrafts = true;+ mockState.filesDraft = {+ fileIds: ['shared-file'],+ pendingPastes: {},+ tabId: 'this-tab',+ };+ mockState.files = new Map([['shared-file', { file_id: 'shared-file', progress: 1 }]]);+ mockState.fileList = [+ { file_id: 'shared-file', filepath: '/uploads/shared.txt', source: 'local' },+ ];+ mockState.foreignDraftedIds = ['shared-file'];+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).not.toHaveBeenCalled();+ });++ it('spares library files the draft recorded through a re-attach', () => {+ mockState.saveDrafts = true;+ mockState.filesDraft = {+ fileIds: ['library-file', 'own-file'],+ pendingPastes: {},+ };+ /** `attached: true` is how a re-attached stored file enters the composer: it has other+ * references, so discarding this draft must not delete it. */+ mockState.files = new Map([+ ['library-file', { file_id: 'library-file', attached: true, progress: 1 }],+ ['own-file', { file_id: 'own-file', progress: 1 }],+ ]);+ mockState.fileList = [+ { file_id: 'library-file', filepath: '/uploads/library.txt', source: 'local' },+ { file_id: 'own-file', filepath: '/uploads/own.txt', source: 'local' },+ ];+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [+ { file_id: 'own-file', embedded: false, filepath: '/uploads/own.txt', source: 'local' },+ ],+ });+ });++ it('deletes a draft-owned paste before the composer map is rebuilt after a reload', () => {+ mockState.saveDrafts = true;+ mockState.filesDraft = {+ fileIds: ['late-paste'],+ pendingPastes: {},+ pastedTextIds: ['late-paste'],+ };+ /** The reload just happened: the files query has not restored any chips into the map yet. */+ mockState.fileList = [+ { file_id: 'late-paste', filepath: '/uploads/late.txt', source: 'local' },+ ];+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [+ { file_id: 'late-paste', embedded: false, filepath: '/uploads/late.txt', source: 'local' },+ ],+ });+ });++ it('defers a draft-owned paste whose record has not arrived after a reload', async () => {+ mockState.saveDrafts = true;+ mockState.filesDraft = {+ fileIds: ['late-paste'],+ pendingPastes: {},+ pastedTextIds: ['late-paste'],+ };+ const { result, rerender } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).not.toHaveBeenCalled();++ mockState.filesDraft = { fileIds: [], pendingPastes: {} };+ mockState.fileList = [+ { file_id: 'late-paste', filepath: '/uploads/late.txt', source: 'local' },+ ];+ await act(async () => {+ rerender();+ });++ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [+ { file_id: 'late-paste', embedded: false, filepath: '/uploads/late.txt', source: 'local' },+ ],+ });+ });++ it('drains a deletion another flow retained after a failed request', async () => {+ mockState.saveDrafts = true;+ mockState.filesDraft = {+ fileIds: ['stored-file'],+ pendingPastes: {},+ };+ mockState.files = new Map([['stored-file', { file_id: 'stored-file', progress: 1 }]]);+ mockState.retainedDeletions = [+ { file_id: 'retained-file', filepath: '/uploads/retained.txt', source: 'local' },+ ];+ const { result, rerender } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ /** The retained payload rides along the retry effect's next files-cache tick. */+ mockState.filesDraft = { fileIds: [], pendingPastes: {} };+ mockState.files = new Map();+ mockState.fileList = [+ { file_id: 'stored-file', filepath: '/uploads/stored.txt', source: 'local' },+ ];+ await act(async () => {+ rerender();+ });++ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [+ {+ file_id: 'stored-file',+ embedded: false,+ filepath: '/uploads/stored.txt',+ source: 'local',+ },+ { file_id: 'retained-file', filepath: '/uploads/retained.txt', source: 'local' },+ ],+ });+ expect(mockState.retainedDeletions).toHaveLength(0);+ });++ it('keeps retained deletions when the retried request fails again', async () => {+ mockDeleteFiles.mockRejectedValueOnce(new Error('offline'));+ mockState.retainedDeletions = [+ { file_id: 'retained-file', filepath: '/uploads/retained.txt', source: 'local' },+ ];+ const { result, rerender } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ mockState.fileList = [];+ await act(async () => {+ rerender();+ });++ expect(mockDeleteFiles).toHaveBeenCalledTimes(1);+ expect(mockState.retainedDeletions).toHaveLength(1);+ /** A second failure moves nothing this effect watches, so the payload only gets another+ * attempt if one is scheduled. */+ expect(mockScheduleRetainedRetry).toHaveBeenCalled();+ });++ it('retries a deferred deletion whose request failed', async () => {+ mockDeleteFiles.mockRejectedValueOnce(new Error('offline'));+ mockState.saveDrafts = true;+ mockState.filesDraft = {+ fileIds: ['in-flight'],+ pendingPastes: {},+ };+ mockState.files = new Map([['in-flight', { file_id: 'in-flight', progress: 0.4 }]]);+ const { result, rerender } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ mockState.filesDraft = { fileIds: [], pendingPastes: {} };+ mockState.files = new Map();+ mockState.fileList = [+ { file_id: 'in-flight', filepath: '/uploads/in-flight.txt', source: 'local' },+ ];+ await act(async () => {+ rerender();+ });+ expect(mockDeleteFiles).toHaveBeenCalledTimes(1);++ /** The failed delete kept the id; the next cache update retries it. */+ mockState.fileList = [+ { file_id: 'in-flight', filepath: '/uploads/in-flight.txt', source: 'local' },+ ];+ await act(async () => {+ rerender();+ });++ expect(mockDeleteFiles).toHaveBeenCalledTimes(2);+ });++ it('retains an immediate deletion whose request failed for a retry', async () => {+ mockDeleteFiles.mockRejectedValueOnce(new Error('offline'));+ mockState.saveDrafts = true;+ mockState.filesDraft = {+ fileIds: ['stored-file'],+ pendingPastes: {},+ };+ mockState.files = new Map([['stored-file', { file_id: 'stored-file', progress: 1 }]]);+ mockState.fileList = [+ { file_id: 'stored-file', filepath: '/uploads/stored.txt', source: 'local' },+ ];+ const { result, rerender } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());+ expect(mockDeleteFiles).toHaveBeenCalledTimes(1);++ mockState.filesDraft = { fileIds: [], pendingPastes: {} };+ mockState.files = new Map();+ mockState.fileList = [+ { file_id: 'stored-file', filepath: '/uploads/stored.txt', source: 'local' },+ ];+ await act(async () => {+ rerender();+ });++ expect(mockDeleteFiles).toHaveBeenCalledTimes(2);+ expect(mockDeleteFiles).toHaveBeenLastCalledWith({+ files: [+ {+ file_id: 'stored-file',+ embedded: false,+ filepath: '/uploads/stored.txt',+ source: 'local',+ },+ ],+ });+ });++ it('spares draft ids the composer no longer shows, whose ownership is unknowable', () => {+ mockState.saveDrafts = true;+ mockState.filesDraft = {+ fileIds: ['absent-file'],+ pendingPastes: {},+ };+ mockState.fileList = [+ { file_id: 'absent-file', filepath: '/uploads/absent.txt', source: 'local' },+ ];+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).not.toHaveBeenCalled();+ });++ it('deletes an in-flight upload once its record arrives in the files cache', async () => {+ mockState.saveDrafts = true;+ mockState.filesDraft = {+ fileIds: ['in-flight'],+ pendingPastes: {},+ };+ mockState.files = new Map([['in-flight', { file_id: 'in-flight', progress: 0.4 }]]);+ const { result, rerender } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).not.toHaveBeenCalled();++ /** What the reset itself does: the draft key is dropped and the composer map cleared. */+ mockState.filesDraft = { fileIds: [], pendingPastes: {} };+ mockState.files = new Map();+ mockState.fileList = [+ { file_id: 'in-flight', filepath: '/uploads/in-flight.txt', source: 'local' },+ ];+ await act(async () => {+ rerender();+ });++ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [+ {+ file_id: 'in-flight',+ embedded: false,+ filepath: '/uploads/in-flight.txt',+ source: 'local',+ },+ ],+ });+ });++ it('deletes a deferred upload by its temporary request id once the record arrives', async () => {+ mockState.saveDrafts = true;+ mockState.filesDraft = {+ fileIds: ['request-uuid'],+ pendingPastes: {},+ };+ mockState.files = new Map([['request-uuid', { file_id: 'request-uuid', progress: 0.4 }]]);+ const { result, rerender } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).not.toHaveBeenCalled();++ /** The cache keys the record by the server-assigned id and keeps the request uuid as+ * its temp id; the discard was tracked under the request uuid. */+ mockState.filesDraft = { fileIds: [], pendingPastes: {} };+ mockState.files = new Map();+ mockState.fileList = [+ {+ file_id: 'server-id',+ temp_file_id: 'request-uuid',+ filepath: '/uploads/uploaded.txt',+ source: 'local',+ },+ ];+ await act(async () => {+ rerender();+ });++ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [+ {+ file_id: 'server-id',+ embedded: false,+ filepath: '/uploads/uploaded.txt',+ source: 'local',+ },+ ],+ });+ });++ it('keeps earlier deferred deletions when a second reset defers more', async () => {+ mockState.saveDrafts = true;+ mockState.filesDraft = { fileIds: ['upload-a'], pendingPastes: {} };+ mockState.files = new Map([['upload-a', { file_id: 'upload-a', progress: 0.4 }]]);+ const { result, rerender } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ /** A second new chat before the first upload completed, with a fresh upload of its own.+ * The rerender stands in for the re-render the map change causes in a live composer. */+ mockState.filesDraft = { fileIds: ['upload-b'], pendingPastes: {} };+ mockState.files = new Map([['upload-b', { file_id: 'upload-b', progress: 0.4 }]]);+ act(() => rerender());+ act(() => result.current.startNewChat());++ mockState.filesDraft = { fileIds: [], pendingPastes: {} };+ mockState.files = new Map();+ mockState.fileList = [+ { file_id: 'upload-a', filepath: '/uploads/a.txt', source: 'local' },+ { file_id: 'upload-b', filepath: '/uploads/b.txt', source: 'local' },+ ];+ await act(async () => {+ rerender();+ });++ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [+ { file_id: 'upload-a', embedded: false, filepath: '/uploads/a.txt', source: 'local' },+ { file_id: 'upload-b', embedded: false, filepath: '/uploads/b.txt', source: 'local' },+ ],+ });+ });++ it('clears the pending draft a running response parked this pane under', () => {+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockClearAllDrafts).toHaveBeenCalledWith('pending');+ expect(mockClearAllDrafts).toHaveBeenCalledWith('new');+ });++ it('deletes pending-draft uploads before clearing them', () => {+ mockState.saveDrafts = true;+ mockState.pendingFilesDraft = {+ fileIds: ['queued-file'],+ pendingPastes: {},+ };+ mockState.files = new Map([['queued-file', { file_id: 'queued-file', progress: 1 }]]);+ mockState.fileList = [+ { file_id: 'queued-file', filepath: '/uploads/queued.txt', source: 'local' },+ ];+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [+ {+ file_id: 'queued-file',+ embedded: false,+ filepath: '/uploads/queued.txt',+ source: 'local',+ },+ ],+ });+ expect(mockDeleteFiles.mock.invocationCallOrder[0]).toBeLessThan(+ mockClearAllDrafts.mock.invocationCallOrder[0],+ );+ expect(mockClearAllDrafts).toHaveBeenCalledWith('pending');+ });++ it('spares a pending draft another browser tab still owns', () => {+ mockState.saveDrafts = true;+ mockState.pendingFilesDraft = {+ fileIds: ['other-pending-file'],+ pendingPastes: {},+ tabId: 'other-tab',+ };+ mockState.fileList = [+ { file_id: 'other-pending-file', filepath: '/uploads/other-pending.txt', source: 'local' },+ ];+ const { result } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ expect(mockDeleteFiles).not.toHaveBeenCalled();+ expect(mockClearAllDrafts).not.toHaveBeenCalledWith('pending');+ expect(mockClearAllDrafts).toHaveBeenCalledWith('new');+ });++ it('spares a reattached file from a retained deletion retry', async () => {+ mockState.retainedDeletions = [+ { file_id: 'reattached-file', filepath: '/uploads/reattached.txt', source: 'local' },+ ];+ mockState.files = new Map([['reattached-file', { file_id: 'reattached-file', progress: 1 }]]);+ mockState.fileList = [+ { file_id: 'reattached-file', filepath: '/uploads/reattached.txt', source: 'local' },+ ];+ const { result, rerender } = renderHook(() => useNewChat());++ await act(async () => {+ rerender();+ });++ expect(mockDeleteFiles).not.toHaveBeenCalled();+ expect(mockState.retainedDeletions).toHaveLength(0);+ expect(result.current).toBeDefined();+ });++ it('spares a submitted file from a retained deletion retry', async () => {+ /** The tab that sent the message can be suspended, or have sent it longer ago than presence+ * remembers, so neither its draft nor its published chips are here to speak for the file. The+ * submitted ledger is durable and shared, and it is the only thing left that can. */+ mockState.retainedDeletions = [+ { file_id: 'sent-file', filepath: '/uploads/sent.txt', source: 'local' },+ ];+ mockState.submittedPasteIds = ['sent-file'];+ mockState.fileList = [{ file_id: 'sent-file', filepath: '/uploads/sent.txt', source: 'local' }];+ const { result, rerender } = renderHook(() => useNewChat());++ await act(async () => {+ rerender();+ });++ expect(mockDeleteFiles).not.toHaveBeenCalled();+ expect(result.current).toBeDefined();+ });++ it('spares a discard whose server record a submission consumed under another id', async () => {+ /** The discard is keyed by the temporary upload id while the pane that sent it marked only the+ * server id, so the record has to be resolved before the ledger is consulted. */+ mockState.persistedPendingDiscardIds = ['client-temp-id'];+ mockState.submittedPasteIds = ['server-file-id'];+ mockState.fileList = [+ {+ file_id: 'server-file-id',+ temp_file_id: 'client-temp-id',+ filepath: '/uploads/sent.txt',+ source: 'local',+ },+ ];+ const { result, rerender } = renderHook(() => useNewChat());++ await act(async () => {+ rerender();+ });++ expect(mockDeleteFiles).not.toHaveBeenCalled();+ expect(result.current).toBeDefined();+ });++ it('keeps retained deletions when the API reports a partial failure', async () => {+ mockDeleteFiles.mockResolvedValueOnce({+ message: 'Some files could not be deleted',+ deletedFileIds: [],+ failedFileIds: ['retained-file'],+ });+ mockState.retainedDeletions = [+ { file_id: 'retained-file', filepath: '/uploads/retained.txt', source: 'local' },+ ];+ mockState.fileList = [+ { file_id: 'retained-file', filepath: '/uploads/retained.txt', source: 'local' },+ ];+ const { rerender } = renderHook(() => useNewChat());++ await act(async () => {+ rerender();+ });++ expect(mockDeleteFiles).toHaveBeenCalledTimes(1);+ expect(mockState.retainedDeletions).toHaveLength(1);+ });++ it('retries a retained deletion when the retain store notifies', async () => {+ mockState.fileList = [+ { file_id: 'retained-file', filepath: '/uploads/retained.txt', source: 'local' },+ ];+ renderHook(() => useNewChat());++ mockState.retainedDeletions = [+ { file_id: 'retained-file', filepath: '/uploads/retained.txt', source: 'local' },+ ];+ await act(async () => {+ mockState.retainedListener?.();+ });++ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [{ file_id: 'retained-file', filepath: '/uploads/retained.txt', source: 'local' }],+ });+ });++ it('resumes deferred discards persisted from a previous mount', async () => {+ mockState.persistedPendingDiscardIds = ['late-paste'];+ mockState.fileList = [+ { file_id: 'late-paste', filepath: '/uploads/late.txt', source: 'local' },+ ];+ renderHook(() => useNewChat());++ await act(async () => undefined);++ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [+ {+ file_id: 'late-paste',+ embedded: false,+ filepath: '/uploads/late.txt',+ source: 'local',+ },+ ],+ });+ });++ it('spares a deferred upload that came back attached to the fresh composer', async () => {+ mockState.saveDrafts = true;+ mockState.filesDraft = {+ fileIds: ['in-flight'],+ pendingPastes: {},+ };+ mockState.files = new Map([['in-flight', { file_id: 'in-flight', progress: 0.4 }]]);+ const { result, rerender } = renderHook(() => useNewChat());++ act(() => result.current.startNewChat());++ /** The user immediately re-attached the same file (dedupe lands on the same id). */+ mockState.filesDraft = { fileIds: [], pendingPastes: {} };+ mockState.files = new Map([['in-flight', { file_id: 'in-flight', progress: 1 }]]);+ mockState.fileList = [+ { file_id: 'in-flight', filepath: '/uploads/in-flight.txt', source: 'local' },+ ];+ await act(async () => {+ rerender();+ });++ expect(mockDeleteFiles).not.toHaveBeenCalled();+ });+it('runs the optional callback after the reset', () => {const onNewChat = jest.fn();const { result } = renderHook(() => useNewChat({ onNewChat }));diff --git a/client/src/hooks/Chat/useChatFunctions.ts b/client/src/hooks/Chat/useChatFunctions.tsindex cb2bc929ad..984c06f3c3 100644--- a/client/src/hooks/Chat/useChatFunctions.ts+++ b/client/src/hooks/Chat/useChatFunctions.ts@@ -29,6 +29,7 @@ import type { TAskFunction, ExtendedFile } from '~/common';import {logger,requestChatFocus,+ markPasteSubmitted,hasStreamStartFailed,isSubmittableMessage,createDualMessageContent,@@ -548,9 +549,15 @@ export default function useChatFunctions({if (setFiles && reuseFiles === true) {currentMsg.files = [...submissionFiles];+ /** Queued override files were consumed just like composer files, so mark their identities+ * as submitted before later draft cleanup can classify the restored paste as unsent. */+ submissionFiles.forEach((file) => {+ markPasteSubmitted(file.file_id);+ markPasteSubmitted(file.temp_file_id);+ });// Caller-supplied overrideFiles were consumed elsewhere (queued- // during-run messages take theirs out of the composer at queue time) —- // clearing here would eat attachments staged for the user's NEXT send.+ // during-run messages take theirs out of the composer at queue time,+ // so clearing here would eat attachments staged for the user's NEXT send.if (isRegenerate) {setFiles(new Map());setFilesToDelete({});@@ -567,6 +574,13 @@ export default function useChatFunctions({height: file.height,width: file.width,}));+ /** The draft keeps a paste's provenance after the map is emptied, so discarding later has+ * to be able to tell what this message already took with it. */+ files.forEach((file, key) => {+ markPasteSubmitted(key);+ markPasteSubmitted(file.file_id);+ markPasteSubmitted(file.temp_file_id);+ });setFiles(new Map());setFilesToDelete({});}diff --git a/client/src/hooks/Chat/useNewChat.ts b/client/src/hooks/Chat/useNewChat.tsindex 76e3b4d59a..564a3afe12 100644--- a/client/src/hooks/Chat/useNewChat.ts+++ b/client/src/hooks/Chat/useNewChat.ts@@ -1,12 +1,37 @@-import { useCallback } from 'react';+import { useCallback, useEffect, useState } from 'react';import { useRecoilValue } from 'recoil';import { QueryKeys } from 'librechat-data-provider';import { useQueryClient } from '@tanstack/react-query';-+import type { FileSources, TFile } from 'librechat-data-provider';import type { MouseEvent } from 'react';-+import type { ExtendedFile } from '~/common';+import type { FilesDraft } from '~/utils';+import {+ beginRetainedDeletionPass,+ clearAllDrafts,+ clearMessagesCache,+ clearRetainedFileDeletion,+ failedFileIdsFrom,+ getFilesDraft,+ getNewConversationDraftId,+ collectDraftedAttachmentIds,+ collectForeignAttachmentClaims,+ collectLiveAttachmentIds,+ endRetainedDeletionPass,+ getPendingDraftId,+ isFilesDraftOwnedByThisTab,+ isPastedTextFileMarked,+ isPasteSubmitted,+ loadPendingDiscardIds,+ removeTabAttachmentPresence,+ scheduleRetainedFileDeletionRetry,+ storePendingDiscardIds,+ subscribePendingDiscardIds,+ subscribeRetainedFileDeletions,+ takeRetainedFileDeletions,+} from '~/utils';+import { useGetFiles, useDeleteFilesMutation } from '~/data-provider';import useNewConvo from '~/hooks/useNewConvo';-import { clearMessagesCache } from '~/utils';import store from '~/store';export type UseNewChatParams = {@@ -26,6 +51,60 @@ export type UseNewChatResult = {newConversation: ReturnType<typeof useNewConvo>['newConversation'];};+type DeletableRecord = {+ file_id: string;+ embedded: boolean;+ filepath: string;+ source: FileSources;+};++const toDeletableRecord = (record: TFile): DeletableRecord | null => {+ if (record.filepath == null || record.filepath === '' || !record.source) {+ return null;+ }+ return {+ file_id: record.file_id,+ embedded: record.embedded ?? false,+ filepath: record.filepath,+ source: record.source,+ };+};++/** The live chip's own evidence of what it is, used when no draft record exists to read. */+const toDeletableComposerFile = (file: ExtendedFile): DeletableRecord | null => {+ if (file.filepath == null || file.filepath === '' || file.source == null) {+ return null;+ }+ return {+ file_id: file.file_id,+ embedded: file.embedded ?? false,+ filepath: file.filepath,+ source: file.source,+ };+};++/** Every id the composer currently owns: map keys plus their resolved file ids. Pastes stay+ * owned even when restoration stamped them `attached`, because the draft says they are ours. */+const collectOwnedIds = (files: Map<string, ExtendedFile>, pasteIds: Set<string>): Set<string> => {+ const ownedIds = new Set<string>();+ files.forEach((file, key) => {+ if (file.attached === true && !pasteIds.has(key) && !pasteIds.has(file.file_id)) {+ return;+ }+ ownedIds.add(key);+ if (file.file_id != null) {+ ownedIds.add(file.file_id);+ }+ });+ return ownedIds;+};++/** The draft and the composer map carry a request's own uuid, while the files cache keys the+ * record by the server-assigned file id and remembers the request id as `temp_file_id`, so a+ * discard is matched through either identity. */+const findFilesRecord = (fileList: TFile[] | undefined, fileId: string): TFile | undefined =>+ fileList?.find((entry) => entry.file_id === fileId || entry.temp_file_id === fileId);+/*** Single source of truth for starting a new conversation: drops the cached* messages for the outgoing conversation, invalidates the messages query, then@@ -38,13 +117,358 @@ export default function useNewChat({const queryClient = useQueryClient();const { newConversation } = useNewConvo(index);const conversationId = useRecoilValue(store.conversationIdByIndex(index));+ const files = useRecoilValue(store.filesByIndex(index));+ const saveDrafts = useRecoilValue(store.saveDrafts);+ const { data: fileList } = useGetFiles<TFile[]>();+ const { mutateAsync } = useDeleteFilesMutation();+ /** The cleanup pass runs on a timer nobody asked for, so it reports nothing: a storage failure+ * that keeps failing would otherwise toast on every retry, and success would arrive minutes+ * after the action that caused it. */+ const { mutateAsync: mutateAsyncSilently } = useDeleteFilesMutation({ silent: true });+ /** Draft uploads whose records were not resolvable when the draft was discarded: the files+ * cache was still loading, or the upload was still in flight and completed only after. */+ const [pendingDiscardIds, setPendingDiscardIdsState] = useState<string[]>(() =>+ loadPendingDiscardIds(index),+ );+ const [retainedGeneration, setRetainedGeneration] = useState(0);++ const setPendingDiscardIds = useCallback(+ (updater: string[] | ((current: string[]) => string[])) => {+ setPendingDiscardIdsState((current) => {+ const next = typeof updater === 'function' ? updater(current) : updater;+ /** The header, sidebar, mobile bar and shortcut hooks each mount this hook against one+ * shared session store, so writing this instance's snapshot back would drop ids another+ * instance recorded and never saw. Only the ids this instance actually knows about are+ * resolved; anything else in the store is another instance's and is carried through. */+ const known = new Set(current);+ const merged = Array.from(+ new Set([...next, ...loadPendingDiscardIds(index).filter((id) => !known.has(id))]),+ );+ storePendingDiscardIds(index, merged);+ return merged;+ });+ },+ [index],+ );++ useEffect(() => subscribeRetainedFileDeletions(() => setRetainedGeneration((n) => n + 1)), []);++ /** Another instance may have deferred work and then unmounted, so the store is re-read on every+ * write rather than only at mount. Only a real change is applied, or the write this instance+ * just made would set state straight back and loop. */+ useEffect(+ () =>+ subscribePendingDiscardIds(() =>+ setPendingDiscardIdsState((current) => {+ const stored = loadPendingDiscardIds(index);+ const changed =+ stored.length !== current.length || stored.some((id, at) => id !== current[at]);+ return changed ? stored : current;+ }),+ ),+ [index],+ );++ useEffect(() => {+ const retained = takeRetainedFileDeletions();+ if ((pendingDiscardIds.length === 0 && retained.length === 0) || fileList == null) {+ return;+ }+ /** Another mounted instance is already running this pass. Ask for a later one rather than+ * dropping the work: whatever it does not resolve has to be revisited by someone. */+ if (!beginRetainedDeletionPass()) {+ scheduleRetainedFileDeletionRetry();+ return;+ }+ let cancelled = false;+ const attempt = async () => {+ removeTabAttachmentPresence(+ [...pendingDiscardIds, ...retained.map((record) => record.file_id)],+ index,+ );+ /** An id that came back, as a live chip or inside any draft, is no longer the discarded+ * draft's to delete. Every persisted draft is consulted, not just this pane's keys: after+ * a reload the `files` map is empty until the autosave restore renders, and a second tab+ * can have reattached the file to a conversation this pane has never opened. Drafts live in+ * `localStorage`, so that tab's record is readable from here. */+ const reattached = collectDraftedAttachmentIds();+ /** Drafts are only written when draft saving is on, so live tabs also publish what their+ * composers are holding: without that, a file reattached in another tab with the setting+ * off would be invisible here and deleted underneath it. */+ for (const liveId of collectLiveAttachmentIds()) {+ reattached.add(liveId);+ }+ files.forEach((file, key) => {+ reattached.add(key);+ if (file.file_id != null) {+ reattached.add(file.file_id);+ }+ /** A discard can be pending under the upload's temporary id, and `findFilesRecord`+ * resolves that alias to the same record: without matching it here, reattaching the+ * surviving file would not protect it from its own pending deletion. */+ if (file.temp_file_id != null && file.temp_file_id !== '') {+ reattached.add(file.temp_file_id);+ }+ });+ /** A file a message already consumed is off-limits whatever the draft and presence records+ * say. Those are per-tab and time-bounded; the submitted ledger is durable and shared, so it+ * is the one that can still speak for a send that happened in a tab which has since been+ * suspended, or longer ago than presence remembers.+ *+ * The record is resolved before judging, because the two sides can know the file by+ * different names: a discard is often keyed by the temporary upload id while the pane that+ * sent it marked only the server id. */+ const consumedBySubmission = (fileId: string): boolean => {+ const record = findFilesRecord(fileList, fileId);+ return [fileId, record?.file_id, record?.temp_file_id].some((id) => isPasteSubmitted(id));+ };+ const deletable: DeletableRecord[] = [];+ const stillPending: string[] = [];+ for (const fileId of pendingDiscardIds) {+ if (reattached.has(fileId) || consumedBySubmission(fileId)) {+ continue;+ }+ const record = findFilesRecord(fileList, fileId);+ if (record == null) {+ stillPending.push(fileId);+ continue;+ }+ const deletableRecord = toDeletableRecord(record);+ if (deletableRecord != null) {+ deletable.push(deletableRecord);+ }+ }+ /** Deletions other flows retained after a failed request ride along: their payloads+ * cannot be rebuilt, so they retry here until one succeeds. A file the composer has+ * since reattached, or that a message has since consumed, is no longer ours to retry. */+ const retainedToRetry = retained.filter(+ (record) => !reattached.has(record.file_id) && !consumedBySubmission(record.file_id),+ );+ for (const record of retained) {+ if (reattached.has(record.file_id) || consumedBySubmission(record.file_id)) {+ clearRetainedFileDeletion(record.file_id);+ }+ }+ const batch = [...deletable, ...retainedToRetry];+ if (batch.length > 0) {+ try {+ const result = await mutateAsyncSilently({ files: batch });+ const failed = new Set(failedFileIdsFrom(result));+ for (const record of retainedToRetry) {+ if (!failed.has(record.file_id)) {+ clearRetainedFileDeletion(record.file_id);+ }+ }+ for (const record of deletable) {+ if (failed.has(record.file_id)) {+ stillPending.push(record.file_id);+ }+ }+ /** A reported failure leaves both stores exactly as they were, so this effect has no+ * dependency left to move it: the next attempt has to be asked for, same as a rejection. */+ if (failed.size > 0) {+ scheduleRetainedFileDeletionRetry();+ }+ } catch {+ /** The draft is already gone, so these ids are the only record of what to clean:+ * keep them for the next files-cache update rather than orphaning the uploads. Nothing+ * here moves an effect dependency, so the next attempt has to be asked for. */+ scheduleRetainedFileDeletionRetry();+ return;+ }+ }+ if (!cancelled && stillPending.length !== pendingDiscardIds.length) {+ setPendingDiscardIds(stillPending);+ }+ };+ void attempt().finally(endRetainedDeletionPass);+ return () => {+ cancelled = true;+ };+ }, [+ pendingDiscardIds,+ conversationId,+ fileList,+ files,+ index,+ mutateAsyncSilently,+ retainedGeneration,+ setPendingDiscardIds,+ ]);const startNewChat = useCallback(() => {clearMessagesCache(queryClient, conversationId);queryClient.invalidateQueries([QueryKeys.messages]);+ /** `newConversation` empties the composer, but the unsaved-chat draft key outlives it and+ * `useAutoSave` restores from that key on the way in, so an unsent paste came back on every+ * later new chat. Dropping the key first makes an explicit new chat an actual clean slate,+ * for the text draft and its attachments alike. Per-conversation drafts are untouched.+ *+ * With draft saving on, `newConversation` deliberately leaves the draft's files alive+ * because a draft normally keeps them restorable; discarding the draft removes the only+ * reference to them, so the uploads are deleted here rather than orphaned. Two limits keep+ * that deletion safe: the unsaved-chat key is shared by every tab's default composer, so a+ * record stamped with another tab's id is left alone, and only ids the composer still owns+ * are deleted, because the draft also records library attaches whose files other messages+ * share. Ids the composer no longer shows cannot be told apart from those, so they are left+ * to retention cleanup; ids still uploading are kept until their records arrive. */+ const draftId = getNewConversationDraftId(index);+ const pendingId = getPendingDraftId(index);+ const idleDraft = getFilesDraft(draftId);+ const pendingDraft = getFilesDraft(pendingId);+ const collectDiscardWork = (+ draft: FilesDraft,+ ): { deletable: DeletableRecord[]; deferred: string[] } => {+ if (!isFilesDraftOwnedByThisTab(draft)) {+ return { deletable: [], deferred: [] };+ }+ const pasteIds = new Set(draft.pastedTextIds ?? []);+ const ownedIds = collectOwnedIds(files, pasteIds);+ /** A draft's own paste provenance is ownership in itself: after a reload the composer+ * map may not be rebuilt yet when New Chat is clicked, and the chips those ids are+ * waiting to become would otherwise be skipped rather than discarded with the draft.+ *+ * Not for one a message already took, though. Submitting empties the file map but leaves+ * the draft's provenance behind, and the run ending is no evidence either way: Stop and+ * error paths clear the flag without clearing the draft. Only the submission itself knows,+ * so ids it consumed are excluded by name rather than by whether a run is in flight. */+ for (const pasteId of pasteIds) {+ if (!isPasteSubmitted(pasteId)) {+ ownedIds.add(pasteId);+ }+ }+ const draftFileIds = new Set([...draft.fileIds, ...Object.keys(draft.pendingPastes)]);+ const deletable: DeletableRecord[] = [];+ const deferred: string[] = [];+ for (const fileId of draftFileIds) {+ if (!ownedIds.has(fileId)) {+ continue;+ }+ const record = findFilesRecord(fileList, fileId);+ const deletableRecord = record != null ? toDeletableRecord(record) : null;+ if (deletableRecord != null) {+ deletable.push(deletableRecord);+ } else if (record == null) {+ deferred.push(fileId);+ }+ }+ return { deletable, deferred };+ };+ if (saveDrafts) {+ const idleWork = collectDiscardWork(idleDraft);+ const pendingWork = collectDiscardWork(pendingDraft);+ const seen = new Set<string>();+ const deletable: DeletableRecord[] = [];+ for (const record of [...idleWork.deletable, ...pendingWork.deletable]) {+ if (seen.has(record.file_id)) {+ continue;+ }+ seen.add(record.file_id);+ deletable.push(record);+ }+ /** Persisting a draft can fail outright (private mode, quota) while the upload and its+ * chip still succeed, leaving nothing in the draft to discard from. A generated paste the+ * composer is still showing is its own evidence, so it is collected directly. One that came+ * back `attached` is skipped for the usual reason: the registry also remembers pastes that+ * were already sent and re-attached, and those belong to the message that sent them. */+ files.forEach((file, key) => {+ /** The registry is marked with the client upload id, while a completed entry carries the+ * server one and keeps the original as `temp_file_id`, so the marker is matched through+ * every identity or the finished paste reads as somebody else's file. */+ const isMarkedPaste = [key, file.file_id, file.temp_file_id].some((id) =>+ isPastedTextFileMarked(id),+ );+ if (+ file.attached === true ||+ file.progress < 1 ||+ !isMarkedPaste ||+ seen.has(file.file_id)+ ) {+ return;+ }+ const record = toDeletableComposerFile(file);+ if (record != null) {+ seen.add(record.file_id);+ deletable.push(record);+ }+ });+ const deferred = [...idleWork.deferred, ...pendingWork.deferred];+ /** The retry effect consults every other tab before it deletes; this direct path has to do+ * the same or it races past that guard entirely. A second tab can have reattached one of+ * these pastes and even sent it, in which case its draft or its published presence is the+ * only thing standing between the upload and this request. Its own keys and its own presence+ * are excluded, because those hold exactly what this discard is throwing away. */+ const claimedElsewhere = collectForeignAttachmentClaims([draftId, pendingId], index);+ const discardable = deletable.filter((record) => !claimedElsewhere.has(record.file_id));+ if (discardable.length > 0) {+ mutateAsync({ files: discardable })+ .then((result) => {+ const failedIds = failedFileIdsFrom(result);+ if (failedIds.length > 0) {+ setPendingDiscardIds((current) => Array.from(new Set([...current, ...failedIds])));+ }+ })+ .catch(() => {+ /** A failed deletion is retried on the next files-cache update, exactly like a+ * deferred one, instead of orphaning the uploads. */+ const failedIds = discardable.map((record) => record.file_id);+ setPendingDiscardIds((current) => Array.from(new Set([...current, ...failedIds])));+ });+ }+ /** Merged, not replaced: a second reset while an earlier upload is still in flight+ * must not forget that earlier id, or its eventual record is orphaned. */+ setPendingDiscardIds((current) => Array.from(new Set([...current, ...deferred])));+ }+ /** An upload still in flight has no filepath or source yet, so no discard path can build a+ * payload for it and the reset drops the chip regardless. Its id is deferred so the record is+ * deleted once it finally arrives. With draft saving on the draft supplies these ids; with it+ * off nothing else remembers them at all. */+ const inFlightPasteIds: string[] = [];+ files.forEach((file, key) => {+ const isMarkedPaste = [key, file.file_id, file.temp_file_id].some((id) =>+ isPastedTextFileMarked(id),+ );+ if (file.attached !== true && file.progress < 1 && isMarkedPaste) {+ inFlightPasteIds.push(file.file_id);+ }+ });+ if (inFlightPasteIds.length > 0) {+ setPendingDiscardIds((current) => Array.from(new Set([...current, ...inFlightPasteIds])));+ }+ /** A running response parks this pane's composer under the pending key; the clean slate+ * discards that too, or the queued text and attachments come back with the next run.+ * A record another tab still owns is left in place: clearing it would drop that tab's+ * unsent text and attachment recovery if it reloads before the next autosave. */+ if (isFilesDraftOwnedByThisTab(pendingDraft)) {+ clearAllDrafts(pendingId);+ }+ if (isFilesDraftOwnedByThisTab(idleDraft)) {+ clearAllDrafts(draftId);+ }+ const discardedFileIds = Array.from(+ new Set([+ ...inFlightPasteIds,+ ...Array.from(files.keys()),+ ...Array.from(files.values()).flatMap(+ (f) => [f.file_id, f.temp_file_id].filter(Boolean) as string[],+ ),+ ]),+ );+ removeTabAttachmentPresence(discardedFileIds, index);newConversation();onNewChat?.();- }, [queryClient, conversationId, newConversation, onNewChat]);+ }, [+ queryClient,+ conversationId,+ newConversation,+ onNewChat,+ index,+ saveDrafts,+ fileList,+ mutateAsync,+ files,+ setPendingDiscardIds,+ ]);const handleNewChatClick = useCallback((event: MouseEvent<HTMLElement>) => {diff --git a/client/src/hooks/Files/__tests__/useDeleteFilesFromTable.spec.tsx b/client/src/hooks/Files/__tests__/useDeleteFilesFromTable.spec.tsxnew file mode 100644index 0000000000..5858d26573--- /dev/null+++ b/client/src/hooks/Files/__tests__/useDeleteFilesFromTable.spec.tsx@@ -0,0 +1,74 @@+import { renderHook } from '@testing-library/react';+import { QueryKeys } from 'librechat-data-provider';+import { QueryClient, QueryClientProvider } from '@tanstack/react-query';+import type {+ BatchFile,+ DeleteFilesBody,+ DeleteFilesResponse,+ DeleteMutationOptions,+ TFile,+} from 'librechat-data-provider';+import type { ReactNode } from 'react';++const mockUseDeleteFilesMutation = jest.fn();+const mockDeleteFiles = jest.fn();++jest.mock('~/data-provider', () => ({+ useDeleteFilesMutation: (options: DeleteMutationOptions) => {+ mockUseDeleteFilesMutation(options);+ return { mutateAsync: jest.fn() };+ },+}));++jest.mock('../useFileDeletion', () => ({+ __esModule: true,+ default: () => ({ deleteFiles: mockDeleteFiles }),+}));++import useDeleteFilesFromTable from '../useDeleteFilesFromTable';++const makeFile = (file_id: string): TFile => ({ file_id }) as TFile;+const makeBatchFile = (file_id: string): BatchFile =>+ ({+ file_id,+ filepath: `/uploads/${file_id}`,+ embedded: false,+ source: 'local',+ }) as BatchFile;++const wrapper =+ (queryClient: QueryClient) =>+ ({ children }: { children: ReactNode }) => (+ <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>+ );++describe('useDeleteFilesFromTable', () => {+ beforeEach(() => {+ mockUseDeleteFilesMutation.mockClear();+ mockDeleteFiles.mockClear();+ });++ it('keeps files reported as failed in the cached table list', async () => {+ const queryClient = new QueryClient();+ const failedFile = makeFile('failed-file');+ const deletedFile = makeFile('deleted-file');+ queryClient.setQueryData<TFile[]>([QueryKeys.files], [failedFile, deletedFile]);++ renderHook(() => useDeleteFilesFromTable(), { wrapper: wrapper(queryClient) });++ const options = mockUseDeleteFilesMutation.mock.calls[0][0] as DeleteMutationOptions;+ const variables: DeleteFilesBody = {+ files: [makeBatchFile('failed-file'), makeBatchFile('deleted-file')],+ };+ const context = await options.onMutate?.(variables);+ const result: DeleteFilesResponse = {+ message: 'Some files could not be deleted',+ failedFileIds: ['failed-file'],+ deletedFileIds: ['deleted-file'],+ };++ options.onSuccess?.(result, variables, context);++ expect(queryClient.getQueryData<TFile[]>([QueryKeys.files])).toEqual([failedFile]);+ });+});diff --git a/client/src/hooks/Files/__tests__/useFileDeletion.spec.tsx b/client/src/hooks/Files/__tests__/useFileDeletion.spec.tsxindex b962cf031b..2739ace894 100644--- a/client/src/hooks/Files/__tests__/useFileDeletion.spec.tsx+++ b/client/src/hooks/Files/__tests__/useFileDeletion.spec.tsx@@ -2,6 +2,12 @@ import React, { useState } from 'react';import { FileSources, EToolResources } from 'librechat-data-provider';import { render, screen, act, renderHook } from '@testing-library/react';import type { ExtendedFile } from '~/common';+import {+ clearRetainedFileDeletion,+ collectLiveAttachmentIds,+ publishTabAttachmentIds,+ takeRetainedFileDeletions,+} from '~/utils';import FileRow from '~/components/Chat/Input/Files/FileRow';import useFileDeletion from '../useFileDeletion';@@ -88,7 +94,13 @@ describe('useFileDeletion', () => {beforeEach(() => {jest.useFakeTimers();mockMutateAsync.mockClear();+ /** react-query's `mutateAsync` always hands back a promise, and the hook reads the response+ * to find out what the server could not delete. */+ mockMutateAsync.mockResolvedValue({ message: 'ok', deletedFileIds: [], failedFileIds: [] });mockClearUploadRecovery.mockClear();+ for (const retained of takeRetainedFileDeletions()) {+ clearRetainedFileDeletion(retained.file_id);+ }});afterEach(() => jest.useRealTimers());@@ -125,6 +137,55 @@ describe('useFileDeletion', () => {);});+ it('retains a deletion the request never completed', async () => {+ /** The chip is gone by the time this runs, so nothing else remembers the upload exists. */+ mockMutateAsync.mockRejectedValueOnce(new Error('offline'));+ const { result } = renderHook(() => useFileDeletion({ mutateAsync: mockMutateAsync }));++ act(() => {+ result.current.deleteFile({ file: makeFile('lost-file') });+ });+ act(() => {+ jest.advanceTimersByTime(3000);+ });+ await act(async () => {});++ expect(takeRetainedFileDeletions()).toEqual([+ expect.objectContaining({ file_id: 'lost-file' }),+ ]);+ });++ it('does not queue a failed agent unlink for the generic delete retry', async () => {+ /** The retry sends files alone, so replaying an unlink through it would hit the ordinary+ * delete branch and destroy a record the agent and other references still point at. */+ mockMutateAsync.mockRejectedValueOnce(new Error('offline'));+ render(<ConditionalPanel initial={[makeFile('agent-file')]} />);++ clickDelete('agent-file');+ await act(async () => {});++ expect(takeRetainedFileDeletions()).toEqual([]);+ });++ it('retains only the ids the server reported as failed', async () => {+ mockMutateAsync.mockResolvedValue({+ message: 'Some files could not be deleted',+ deletedFileIds: ['file-a'],+ failedFileIds: ['file-b'],+ });+ const { result } = renderHook(() => useFileDeletion({ mutateAsync: mockMutateAsync }));++ act(() => {+ result.current.deleteFiles({ files: [makeFile('file-a'), makeFile('file-b')] });+ });+ act(() => {+ jest.advanceTimersByTime(3000);+ });+ await act(async () => {});++ expect(takeRetainedFileDeletions()).toEqual([expect.objectContaining({ file_id: 'file-b' })]);+ });+it('does not delete a file that was attached from existing storage', () => {const { result } = renderHook(() => useFileDeletion({ mutateAsync: mockMutateAsync }));@@ -152,4 +213,32 @@ describe('useFileDeletion', () => {expect(mockClearUploadRecovery).toHaveBeenCalledWith('pending-file');expect(mockMutateAsync).not.toHaveBeenCalled();});++ it("keeps a sibling pane's published claim when pane 0 removes its chip", () => {+ publishTabAttachmentIds(0, ['shared-file']);+ publishTabAttachmentIds(1, ['shared-file']);+ const { result } = renderHook(() =>+ useFileDeletion({ mutateAsync: mockMutateAsync, index: 0 }),+ );++ act(() => {+ result.current.deleteFile({ file: makeFile('shared-file') });+ });++ expect(collectLiveAttachmentIds().has('shared-file')).toBe(true);+ });++ it("keeps a sibling pane's published claim when pane 0 removes a batch", () => {+ publishTabAttachmentIds(0, ['batch-shared-file']);+ publishTabAttachmentIds(1, ['batch-shared-file']);+ const { result } = renderHook(() =>+ useFileDeletion({ mutateAsync: mockMutateAsync, index: 0 }),+ );++ act(() => {+ result.current.deleteFiles({ files: [makeFile('batch-shared-file')] });+ });++ expect(collectLiveAttachmentIds().has('batch-shared-file')).toBe(true);+ });});diff --git a/client/src/hooks/Files/__tests__/useFileHandling.test.ts b/client/src/hooks/Files/__tests__/useFileHandling.test.tsindex 0378f58b04..33738f7375 100644--- a/client/src/hooks/Files/__tests__/useFileHandling.test.ts+++ b/client/src/hooks/Files/__tests__/useFileHandling.test.ts@@ -415,6 +415,43 @@ describe('useFileHandling', () => {}});+ it('validates a replacement without counting the source attachment', async () => {+ mockFileConfig = mergeFileConfig({+ endpoints: { default: { fileLimit: 1, totalSizeLimit: 7 } },+ });+ const source = makeSizedFile('original.txt', 'text/plain', 4 * megabyte);+ const replacement = makeSizedFile('replacement.txt', 'text/plain', 4 * megabyte);+ const sharedState = {+ files: new Map([+ [+ 'source-file',+ {+ file_id: 'source-file',+ file: source,+ filename: source.name,+ type: source.type,+ size: source.size,+ progress: 1,+ },+ ],+ ]),+ setFiles: jest.fn(),+ setFilesLoading: mockSetFilesLoading,+ };+ const { useFileHandlingNoChatContext } = await import('../useFileHandling');+ const menu = renderHook(() => useFileHandlingNoChatContext(undefined, sharedState));++ let accepted = false;+ await act(async () => {+ accepted = await menu.result.current.handleFiles([replacement], undefined, {+ replacesFileId: 'source-file',+ });+ });++ expect(accepted).toBe(true);+ expect(mockMutate).toHaveBeenCalledTimes(1);+ });+it('uploads the selected file when the input is reset before processing starts', async () => {const selectedFile = makeSizedFile('notes.txt', 'text/plain', 1024);/** Mirrors the live `FileList` an input clears in place when its value is reset */diff --git a/client/src/hooks/Files/__tests__/usePastedTextEdit.spec.tsx b/client/src/hooks/Files/__tests__/usePastedTextEdit.spec.tsxnew file mode 100644index 0000000000..1f7140e85a--- /dev/null+++ b/client/src/hooks/Files/__tests__/usePastedTextEdit.spec.tsx@@ -0,0 +1,1131 @@+import { renderHook, act } from '@testing-library/react';++/** This jsdom build lacks `Blob.prototype.text`, which browsers have had for years; the+ * paste editor reads chip text through it, so give the test environment the same primitive. */+if (typeof Blob.prototype.text !== 'function') {+ Blob.prototype.text = function (): Promise<string> {+ return new Promise((resolve) => {+ const reader = new FileReader();+ reader.onload = () => resolve(reader.result as string);+ reader.readAsText(this);+ });+ };+}++import { FileSources } from 'librechat-data-provider';+import type { TConversation } from 'librechat-data-provider';+import type { UploadLifecycleCallbacks } from '../useFileHandling';+import type { FilesDraft } from '~/utils';+import type { ExtendedFile } from '~/common';++const mockShowToast = jest.fn();+const mockSetValue = jest.fn();+const mockDeleteFile = jest.fn();+const mockDeleteFiles = jest.fn();+const mockRouteFiles = jest.fn();+const mockFileDownload = jest.fn();+const mockMarkPastedTextFile = jest.fn();+const mockRetainFileDeletion = jest.fn();+const mockRemoveTabAttachmentPresence = jest.fn();+const mockAddPastedTextDraftFile = jest.fn(({ id, fileId }: { id: string; fileId: string }) => {+ const draft = mockState.draftsById[id] ?? {+ fileIds: [],+ pendingPastes: {},+ pastedTextIds: [],+ };+ if (draft.pastedTextIds?.includes(fileId) !== true) {+ mockState.draftsById[id] = {+ ...draft,+ pastedTextIds: [...(draft.pastedTextIds ?? []), fileId],+ };+ }+});+const mockRemovePendingTextAttachmentDraft = jest.fn(+ ({ id, fileId, removeFile = false }: { id: string; fileId: string; removeFile?: boolean }) => {+ const draft = mockState.draftsById[id] ?? {+ fileIds: [],+ pendingPastes: {},+ pastedTextIds: [],+ };+ mockState.draftsById[id] = {+ ...draft,+ fileIds: removeFile+ ? draft.fileIds.filter((draftFileId) => draftFileId !== fileId)+ : draft.fileIds,+ pastedTextIds: removeFile+ ? draft.pastedTextIds?.filter((pasteId) => pasteId !== fileId)+ : draft.pastedTextIds,+ pendingPastes: Object.fromEntries(+ Object.entries(draft.pendingPastes).filter(([pendingId]) => pendingId !== fileId),+ ),+ };+ },+);+const mockCollectForeignAttachmentClaims = jest.fn(+ (excludeDraftIds: string[] = [], _excludeOwnPane: number | 'tab' = 'tab'): Set<string> => {+ const excluded = new Set(excludeDraftIds);+ const claims = new Set<string>();+ for (const [draftId, draft] of Object.entries(mockState.draftsById)) {+ if (excluded.has(draftId)) {+ continue;+ }+ for (const fileId of draft.fileIds) {+ claims.add(fileId);+ }+ for (const pasteId of draft.pastedTextIds ?? []) {+ claims.add(pasteId);+ }+ for (const pendingId of Object.keys(draft.pendingPastes)) {+ claims.add(pendingId);+ }+ }+ return claims;+ },+);++/** Values the module-level mocks read, so each test can stage its own scenario. */+const mockState = {+ conversation: { conversationId: 'conversation-a', endpoint: 'openAI' } as TConversation,+ draftToken: Symbol('new-conversation-draft'),+ saveDrafts: true,+ tabId: 'this-tab',+ fileList: [] as TFile[],+ draftsById: {} as Record<string, FilesDraft>,+ submittedPasteIds: new Set<string>(),+};++type TFile = { file_id: string; text?: string };++jest.mock('~/hooks', () => ({+ useLocalize: () => (key: string) => key,+}));++jest.mock('@librechat/client', () => ({+ useToastContext: () => ({ showToast: mockShowToast }),+}));++jest.mock('recoil', () => ({+ useRecoilValue: () => mockState.saveDrafts,+}));++jest.mock('~/store', () => ({+ __esModule: true,+ default: { saveDrafts: { key: 'saveDrafts' } },+}));++jest.mock('~/hooks/AuthContext', () => ({+ useAuthContext: () => ({ user: { id: 'user-1' } }),+}));++jest.mock('~/Providers', () => ({+ useChatContext: () => ({ conversation: mockState.conversation, isSubmitting: false }),+ useChatFormContext: () => ({+ getValues: () => '',+ setValue: mockSetValue,+ }),+}));++jest.mock('../useFileUploadRouter', () => ({+ __esModule: true,+ default: () => mockRouteFiles,+}));++jest.mock('../useFileDeletion', () => ({+ __esModule: true,+ default: () => ({ deleteFile: mockDeleteFile }),+}));++jest.mock('~/data-provider', () => ({+ useGetFiles: () => ({ data: mockState.fileList }),+ useDeleteFilesMutation: () => ({ mutateAsync: mockDeleteFiles }),+}));++jest.mock('~/utils', () => ({+ collectForeignAttachmentClaims: (+ excludeDraftIds: string[] = [],+ excludeOwnPane: number | 'tab' = 'tab',+ ) => mockCollectForeignAttachmentClaims(excludeDraftIds, excludeOwnPane),+ forceResize: jest.fn(),+ getNewConversationDraftToken: () => mockState.draftToken,+ getComposerDraftId: (index: number, conversationId: string | null, isSubmitting = false) =>+ `${conversationId ?? 'new'}:${index}:${isSubmitting ? 'pending' : 'idle'}`,+ getFilesDraftCached: (id: string) =>+ mockState.draftsById[id] ?? { fileIds: [], pendingPastes: {}, pastedTextIds: [] },+ getBrowserTabId: () => mockState.tabId,+ /** The other tab in these scenarios is open, so a stamp that is not ours is a live claim. */+ isFilesDraftOwnedByThisTab: (draft: { tabId?: string }) =>+ draft.tabId == null || draft.tabId === mockState.tabId,+ isPasteSubmitted: (fileId?: string | null) =>+ fileId != null && mockState.submittedPasteIds.has(fileId),+ markPastedTextFile: (...args: unknown[]) => mockMarkPastedTextFile(...args),+ removeTabAttachmentPresence: (...args: unknown[]) => mockRemoveTabAttachmentPresence(...args),+ retainFileDeletion: (...args: unknown[]) => mockRetainFileDeletion(...args),+ addPastedTextDraftFile: (args: { id: string; fileId: string }) =>+ mockAddPastedTextDraftFile(args),+ removePendingTextAttachmentDraft: (args: { id: string; fileId: string; removeFile?: boolean }) =>+ mockRemovePendingTextAttachmentDraft(args),+ nextPastedTextFilename: jest.requireActual('~/utils/files').nextPastedTextFilename,+ failedFileIdsFrom: jest.requireActual('~/utils/files').failedFileIdsFrom,+}));++jest.mock('librechat-data-provider', () => ({+ ...jest.requireActual('librechat-data-provider'),+ dataService: { getFileDownload: (...args: unknown[]) => mockFileDownload(...args) },+ isAssistantsEndpoint: () => false,+}));++import usePastedTextEdit from '../usePastedTextEdit';++const pastedFile = (overrides: Partial<ExtendedFile> = {}): ExtendedFile => ({+ file_id: 'pasted-file',+ filename: 'pasted-text.txt',+ type: 'text/plain',+ progress: 1,+ size: 4000,+ file: new File(['the original paste'], 'pasted-text.txt', { type: 'text/plain' }),+ ...overrides,+});++describe('usePastedTextEdit', () => {+ let capturedLifecycle: UploadLifecycleCallbacks | undefined;++ beforeEach(() => {+ jest.clearAllMocks();+ mockDeleteFiles.mockResolvedValue(undefined);+ capturedLifecycle = undefined;+ mockState.conversation = {+ conversationId: 'conversation-a',+ endpoint: 'openAI',+ } as TConversation;+ mockState.draftToken = Symbol('new-conversation-draft');+ mockState.saveDrafts = true;+ mockState.tabId = 'this-tab';+ mockState.fileList = [];+ mockState.draftsById = {};+ mockState.submittedPasteIds.clear();+ mockRouteFiles.mockImplementation(+ (_files: unknown, _toolResource: unknown, lifecycle: UploadLifecycleCallbacks) => {+ capturedLifecycle = lifecycle;+ return Promise.resolve(true);+ },+ );+ });++ const renderEditor = (files?: Map<string, ExtendedFile>, index = 0, setFiles = jest.fn()) =>+ renderHook(+ ({ files: composerFiles }) =>+ usePastedTextEdit({+ files: composerFiles,+ index,+ setFiles,+ textAreaRef: { current: null },+ }),+ {+ initialProps: {+ files:+ files ??+ new Map<string, ExtendedFile>([+ ['pasted-file', pastedFile()],+ ['restored-file', pastedFile({ file_id: 'restored-file', file: undefined })],+ ]),+ },+ },+ );++ const openEditor = async () => {+ const editor = renderEditor();+ await act(async () => {+ await editor.result.current.openEditor(pastedFile());+ });+ return editor;+ };++ it('keeps the original attached until the replacement upload succeeds', async () => {+ const editor = await openEditor();++ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });++ expect(mockRouteFiles).toHaveBeenCalledTimes(1);+ expect(mockRouteFiles).toHaveBeenCalledWith(+ expect.any(Array),+ expect.anything(),+ expect.objectContaining({ replacesFileId: 'pasted-file' }),+ );+ expect(mockDeleteFile).not.toHaveBeenCalled();++ await act(async () => {+ capturedLifecycle?.onSuccess?.('replacement-file');+ });++ expect(mockDeleteFile).toHaveBeenCalledWith({+ file: expect.objectContaining({ file_id: 'pasted-file' }),+ setFiles: expect.anything(),+ });+ });+ it('removes a live paste claimed by another tab without scheduling deletion or retry', async () => {+ const live = pastedFile({ file_id: 'claimed-live-file' });+ mockState.draftsById['other-tab-draft'] = {+ fileIds: ['claimed-live-file'],+ pendingPastes: {},+ pastedTextIds: [],+ tabId: 'other-tab',+ };+ let currentFiles = new Map<string, ExtendedFile>([['claimed-live-file', live]]);+ const setFiles = jest.fn(+ (update: (current: Map<string, ExtendedFile>) => Map<string, ExtendedFile>) => {+ currentFiles = update(currentFiles);+ },+ );+ const editor = renderEditor(currentFiles, 2, setFiles);++ await act(async () => {+ await editor.result.current.openEditor(live);+ });+ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });+ await act(async () => {+ capturedLifecycle?.onSuccess?.('replacement-file');+ });++ expect(currentFiles.has('claimed-live-file')).toBe(false);+ expect(mockDeleteFile).not.toHaveBeenCalled();+ expect(mockDeleteFiles).not.toHaveBeenCalled();+ expect(mockRetainFileDeletion).not.toHaveBeenCalled();+ expect(mockCollectForeignAttachmentClaims).toHaveBeenCalledWith(expect.any(Array), 2);+ });++ it('leaves the original attached when the replacement is rejected', async () => {+ mockRouteFiles.mockResolvedValue(false);+ const editor = await openEditor();++ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });++ expect(mockDeleteFile).not.toHaveBeenCalled();+ expect(mockShowToast).toHaveBeenCalledWith(+ expect.objectContaining({ message: 'com_ui_pasted_text_save_error' }),+ );+ });++ it('removes replacement provenance when the replacement upload is rejected', async () => {+ mockRouteFiles.mockResolvedValue(false);+ const draftId = 'conversation-a:0:idle';+ mockState.draftsById[draftId] = {+ fileIds: ['existing-file'],+ pastedTextIds: ['existing-paste'],+ pendingPastes: {+ 'existing-paste': { text: 'existing', selectionStart: 0 },+ },+ };+ const editor = await openEditor();++ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });++ const replacementCall = mockAddPastedTextDraftFile.mock.calls[0]?.[0];+ if (+ replacementCall == null ||+ typeof replacementCall !== 'object' ||+ !('fileId' in replacementCall) ||+ typeof replacementCall.fileId !== 'string'+ ) {+ throw new Error('Expected a replacement draft file id');+ }+ const replacementId = replacementCall.fileId;+ const draft = mockState.draftsById[draftId];+ expect(mockRemovePendingTextAttachmentDraft).toHaveBeenCalledWith({+ id: draftId,+ fileId: replacementId,+ removeFile: true,+ });+ expect(draft.fileIds).not.toContain(replacementId);+ expect(draft.pastedTextIds).not.toContain(replacementId);+ expect(draft.pendingPastes).not.toHaveProperty(replacementId);+ });++ it('queues a failed edit behind a dialog another chip occupies', async () => {+ /** The gate stands in for the upload request: B opens while A's replacement is in flight. */+ let releaseSave: (accepted: boolean) => void = () => undefined;+ mockRouteFiles.mockImplementation(+ () =>+ new Promise<boolean>((resolve) => {+ releaseSave = (accepted) => resolve(accepted);+ }),+ );+ const fileA = pastedFile();+ const fileB = pastedFile({ file_id: 'second-file' });+ const editor = renderEditor(+ new Map<string, ExtendedFile>([+ ['pasted-file', fileA],+ ['second-file', fileB],+ ]),+ );++ await act(async () => {+ await editor.result.current.openEditor(fileA);+ });+ await act(async () => {+ void editor.result.current.saveEdit('fixed A');+ });+ await act(async () => {+ await editor.result.current.openEditor(fileB);+ });+ expect(editor.result.current.editing?.file.file_id).toBe('second-file');++ await act(async () => {+ releaseSave(false);+ });++ /** A's corrections must not be dropped just because B's dialog is open. */+ expect(editor.result.current.editing?.file.file_id).toBe('second-file');+ act(() => {+ editor.result.current.closeEditor();+ });++ expect(editor.result.current.editing?.file.file_id).toBe('pasted-file');+ expect(editor.result.current.editing?.text).toBe('fixed A');+ });++ it('refuses a second action against a chip whose replacement is uploading', async () => {+ /** The upload stays in flight: the gate is never pulled. */+ mockRouteFiles.mockImplementation(() => new Promise<boolean>(() => undefined));+ const editor = await openEditor();+ await act(async () => {+ void editor.result.current.saveEdit('corrected');+ });++ expect(editor.result.current.isActionPending('pasted-file')).toBe(true);+ await act(async () => {+ await editor.result.current.openEditor(pastedFile());+ });++ expect(editor.result.current.editing).toBeNull();+ expect(mockRouteFiles).toHaveBeenCalledTimes(1);+ });++ it('restores the corrections when the replacement is rejected', async () => {+ mockRouteFiles.mockResolvedValue(false);+ const editor = await openEditor();++ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });++ expect(editor.result.current.editing?.text).toBe('corrected');+ expect(editor.result.current.editing?.file.file_id).toBe('pasted-file');+ expect(mockShowToast).toHaveBeenCalledWith(+ expect.objectContaining({ message: 'com_ui_pasted_text_save_error' }),+ );+ });++ it('restores the corrections when the replacement upload fails', async () => {+ const editor = await openEditor();++ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });+ expect(editor.result.current.editing).toBeNull();+ await act(async () => {+ capturedLifecycle?.onError?.('replacement-file');+ });++ expect(editor.result.current.editing?.text).toBe('corrected');+ });++ it('leaves the original attached when the replacement upload fails', async () => {+ const editor = await openEditor();++ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });+ await act(async () => {+ capturedLifecycle?.onError?.('replacement-file');+ });++ expect(mockDeleteFile).not.toHaveBeenCalled();+ });++ it('deletes a restored paste record the normal removal path would keep', async () => {+ mockState.draftsById = {+ 'conversation-a:0:idle': { fileIds: [], pendingPastes: {}, pastedTextIds: ['pasted-file'] },+ };+ const editor = renderEditor();+ const restored = pastedFile({+ attached: true,+ filepath: '/uploads/user123/pasted-text.txt',+ source: FileSources.local,+ });++ await act(async () => {+ await editor.result.current.openEditor(restored);+ });+ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });+ await act(async () => {+ capturedLifecycle?.onSuccess?.('replacement-file');+ });++ /** `attached: true` is what restoration stamps on, and what makes the shared removal+ * path keep the server record; the paste's own upload must not survive the edit. */+ expect(mockDeleteFile).toHaveBeenCalledTimes(1);+ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [+ expect.objectContaining({+ file_id: 'pasted-file',+ filepath: '/uploads/user123/pasted-text.txt',+ }),+ ],+ });+ });+ it('removes a restored paste locally without deleting when another draft claims it', async () => {+ mockState.draftsById = {+ 'conversation-a:0:idle': {+ fileIds: [],+ pendingPastes: {},+ pastedTextIds: ['pasted-file'],+ },+ 'conversation-b:0:idle': {+ fileIds: [],+ pendingPastes: {},+ pastedTextIds: ['pasted-file'],+ },+ };+ const editor = renderEditor();+ const restored = pastedFile({+ attached: true,+ filepath: '/uploads/user123/pasted-text.txt',+ source: FileSources.local,+ });++ await act(async () => {+ await editor.result.current.openEditor(restored);+ });+ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });+ await act(async () => {+ capturedLifecycle?.onSuccess?.('replacement-file');+ });++ expect(mockDeleteFile).not.toHaveBeenCalled();+ expect(mockDeleteFiles).not.toHaveBeenCalled();+ expect(mockRetainFileDeletion).not.toHaveBeenCalled();+ expect(mockCollectForeignAttachmentClaims).toHaveBeenCalledWith(+ ['conversation-a:0:idle', 'conversation-a:0:pending'],+ 0,+ );+ });++ it('spares a restored paste whose draft another tab wrote last', async () => {+ /** Two tabs can restore the same conversation draft; the deleting composer only owns the+ * claim when the draft carries its own tab stamp (or predates stamping). */+ mockState.draftsById = {+ 'conversation-a:0:idle': {+ fileIds: [],+ pendingPastes: {},+ pastedTextIds: ['pasted-file'],+ tabId: 'other-tab',+ },+ };+ const editor = renderEditor();+ const restored = pastedFile({+ attached: true,+ filepath: '/uploads/user123/pasted-text.txt',+ source: FileSources.local,+ });++ await act(async () => {+ await editor.result.current.openEditor(restored);+ });+ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });+ await act(async () => {+ capturedLifecycle?.onSuccess?.('replacement-file');+ });++ expect(mockDeleteFile).toHaveBeenCalledTimes(1);+ expect(mockDeleteFiles).not.toHaveBeenCalled();+ });++ it('follows the draft a finishing response migrated the claim to', async () => {+ /** The edit was captured while submitting, so its key was the pending one; the run then+ * finished and autosave moved the record to the conversation key. The claim must be found+ * under either. */+ mockState.draftsById = {+ 'conversation-a:0:pending': {+ fileIds: [],+ pendingPastes: {},+ pastedTextIds: ['pasted-file'],+ },+ };+ const editor = renderEditor();+ const restored = pastedFile({+ attached: true,+ filepath: '/uploads/user123/pasted-text.txt',+ source: FileSources.local,+ });++ await act(async () => {+ await editor.result.current.openEditor(restored);+ });+ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });+ await act(async () => {+ capturedLifecycle?.onSuccess?.('replacement-file');+ });++ expect(mockDeleteFile).toHaveBeenCalledTimes(1);+ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [expect.objectContaining({ file_id: 'pasted-file' })],+ });+ });++ it('retains a failed restored-paste deletion for retry', async () => {+ mockDeleteFiles.mockRejectedValueOnce(new Error('offline'));+ mockState.draftsById = {+ 'conversation-a:0:idle': { fileIds: [], pendingPastes: {}, pastedTextIds: ['pasted-file'] },+ };+ const editor = renderEditor();+ const restored = pastedFile({+ attached: true,+ filepath: '/uploads/user123/pasted-text.txt',+ source: FileSources.local,+ });++ await act(async () => {+ await editor.result.current.openEditor(restored);+ });+ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });+ await act(async () => {+ capturedLifecycle?.onSuccess?.('replacement-file');+ });++ expect(mockDeleteFiles).toHaveBeenCalledTimes(1);+ expect(mockRetainFileDeletion).toHaveBeenCalledWith({+ file_id: 'pasted-file',+ embedded: false,+ filepath: '/uploads/user123/pasted-text.txt',+ source: FileSources.local,+ });+ });++ it('retains a restored-paste deletion the server reports as failed', async () => {+ /** A storage delete that fails still answers 200, so the resolved payload is the only place+ * the failure shows up. */+ mockDeleteFiles.mockResolvedValueOnce({+ message: 'Some files could not be deleted',+ deletedFileIds: [],+ failedFileIds: ['pasted-file'],+ });+ mockState.draftsById = {+ 'conversation-a:0:idle': { fileIds: [], pendingPastes: {}, pastedTextIds: ['pasted-file'] },+ };+ const editor = renderEditor();+ const restored = pastedFile({+ attached: true,+ filepath: '/uploads/user123/pasted-text.txt',+ source: FileSources.local,+ });++ await act(async () => {+ await editor.result.current.openEditor(restored);+ });+ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });+ await act(async () => {+ capturedLifecycle?.onSuccess?.('replacement-file');+ });++ expect(mockRetainFileDeletion).toHaveBeenCalledWith({+ file_id: 'pasted-file',+ embedded: false,+ filepath: '/uploads/user123/pasted-text.txt',+ source: FileSources.local,+ });+ });++ it('does not retain a restored-paste deletion the server accepted', async () => {+ mockDeleteFiles.mockResolvedValueOnce({+ message: 'Files deleted successfully',+ deletedFileIds: ['pasted-file'],+ failedFileIds: [],+ });+ mockState.draftsById = {+ 'conversation-a:0:idle': { fileIds: [], pendingPastes: {}, pastedTextIds: ['pasted-file'] },+ };+ const editor = renderEditor();+ const restored = pastedFile({+ attached: true,+ filepath: '/uploads/user123/pasted-text.txt',+ source: FileSources.local,+ });++ await act(async () => {+ await editor.result.current.openEditor(restored);+ });+ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });+ await act(async () => {+ capturedLifecycle?.onSuccess?.('replacement-file');+ });++ expect(mockDeleteFiles).toHaveBeenCalledTimes(1);+ expect(mockRetainFileDeletion).not.toHaveBeenCalled();+ });++ it('spares a sent paste re-attached from the library', async () => {+ /** The registry remembers the id even though the draft does not: the paste was sent, and+ * the stored file was re-attached, so its record is shared with the earlier message. */+ const editor = renderEditor();+ const reattached = pastedFile({+ attached: true,+ filepath: '/uploads/user123/pasted-text.txt',+ source: FileSources.local,+ });++ await act(async () => {+ await editor.result.current.openEditor(reattached);+ });+ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });+ await act(async () => {+ capturedLifecycle?.onSuccess?.('replacement-file');+ });++ expect(mockDeleteFile).toHaveBeenCalledTimes(1);+ expect(mockDeleteFiles).not.toHaveBeenCalled();+ });++ it('discards a stale editor resolution that loses to a later click', async () => {+ const gates: Array<(text: string) => void> = [];+ mockFileDownload.mockImplementation(+ () =>+ new Promise((resolve) => {+ gates.push((text: string) => resolve({ data: new Blob([text], { type: 'text/plain' }) }));+ }),+ );+ const slow = pastedFile({ file_id: 'restored-file', file: undefined });+ const fast = pastedFile({ file_id: 'pasted-file' });+ const editor = renderEditor();+ let slowOpen: Promise<void> = Promise.resolve();+ await act(async () => {+ slowOpen = editor.result.current.openEditor(slow);+ });+ await act(async () => {+ await editor.result.current.openEditor(fast);+ });+ expect(editor.result.current.editing?.file.file_id).toBe('pasted-file');++ /** The earlier, slower click resolves last and must not take the dialog back. */+ await act(async () => {+ gates[0]?.('the slow paste');+ await slowOpen;+ });++ expect(editor.result.current.editing?.file.file_id).toBe('pasted-file');+ });++ it('records the replacement as a generated paste', async () => {+ const editor = await openEditor();++ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });++ /** Without provenance the fresh chip renders as an ordinary attachment and immediately+ * loses the Edit and Move back affordances it exists for. */+ expect(mockMarkPastedTextFile).toHaveBeenCalledWith(expect.any(String));+ expect(mockAddPastedTextDraftFile).toHaveBeenCalledWith({+ id: expect.any(String),+ fileId: expect.any(String),+ });+ });++ it('marks replacement provenance in memory when draft saving is off', async () => {+ mockState.saveDrafts = false;+ const editor = await openEditor();++ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });++ expect(mockMarkPastedTextFile).toHaveBeenCalledWith(expect.any(String));+ expect(mockAddPastedTextDraftFile).not.toHaveBeenCalled();+ });++ it('keeps the original when the composer changes while the replacement uploads', async () => {+ const editor = await openEditor();++ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });+ mockState.conversation = {+ conversationId: 'conversation-b',+ endpoint: 'openAI',+ } as TConversation;+ await act(async () => {+ editor.rerender({ files: new Map<string, ExtendedFile>() });+ });++ await act(async () => {+ capturedLifecycle?.onSuccess?.('replacement-file');+ });++ expect(mockDeleteFile).not.toHaveBeenCalled();+ });++ it('keeps the original when a send cleared the composer while the replacement uploads', async () => {+ const editor = await openEditor();++ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });+ await act(async () => {+ editor.rerender({ files: new Map<string, ExtendedFile>() });+ });++ await act(async () => {+ capturedLifecycle?.onSuccess?.('replacement-file');+ });++ expect(mockDeleteFile).not.toHaveBeenCalled();+ });++ it('aborts a move into a composer that was reset while the text resolved', async () => {+ let releaseDownload: (text: string) => void = () => undefined;+ mockFileDownload.mockImplementation(+ () =>+ new Promise((resolve) => {+ releaseDownload = (text: string) =>+ resolve({ data: new Blob([text], { type: 'text/plain' }) });+ }),+ );+ const restored = pastedFile({ file_id: 'restored-file', file: undefined });+ const editor = renderEditor();+ let moved: Promise<void> = Promise.resolve();+ await act(async () => {+ moved = editor.result.current.moveInline(restored);+ });+ /** A second new chat: same conversation id, new unsaved-chat identity. */+ mockState.draftToken = Symbol('new-conversation-draft');+ await act(async () => {+ editor.rerender({+ files: new Map<string, ExtendedFile>([['restored-file', restored]]),+ });+ });++ await act(async () => {+ releaseDownload('recovered from storage');+ await moved;+ });++ expect(mockDeleteFile).not.toHaveBeenCalled();+ expect(mockSetValue).not.toHaveBeenCalled();+ });++ it('aborts a move when the message was sent while the text resolved', async () => {+ let releaseDownload: (text: string) => void = () => undefined;+ mockFileDownload.mockImplementation(+ () =>+ new Promise((resolve) => {+ releaseDownload = (text: string) =>+ resolve({ data: new Blob([text], { type: 'text/plain' }) });+ }),+ );+ const restored = pastedFile({ file_id: 'restored-file', file: undefined });+ const editor = renderEditor();+ let moved: Promise<void> = Promise.resolve();+ await act(async () => {+ moved = editor.result.current.moveInline(restored);+ });+ /** Sending clears the composer's files without changing either conversation identity. */+ await act(async () => {+ editor.rerender({ files: new Map<string, ExtendedFile>() });+ });++ await act(async () => {+ releaseDownload('recovered from storage');+ await moved;+ });++ expect(mockDeleteFile).not.toHaveBeenCalled();+ expect(mockSetValue).not.toHaveBeenCalled();+ });++ it('does not open an editor for an attachment a send already took', async () => {+ let releaseDownload: (text: string) => void = () => undefined;+ mockFileDownload.mockImplementation(+ () =>+ new Promise((resolve) => {+ releaseDownload = (text: string) =>+ resolve({ data: new Blob([text], { type: 'text/plain' }) });+ }),+ );+ const restored = pastedFile({ file_id: 'restored-file', file: undefined });+ const editor = renderEditor();+ let opened: Promise<void> = Promise.resolve();+ await act(async () => {+ opened = editor.result.current.openEditor(restored);+ });+ /** Sending clears the composer's files without changing either conversation identity. */+ await act(async () => {+ editor.rerender({ files: new Map<string, ExtendedFile>() });+ });++ await act(async () => {+ releaseDownload('recovered from storage');+ await opened;+ });++ expect(editor.result.current.editing).toBeNull();+ expect(mockShowToast).not.toHaveBeenCalled();+ });++ it('detaches through a restored entry keyed by its temporary upload id', async () => {+ /** Draft restoration keys the map by the temporary id while the value carries the+ * server-assigned one; membership must match either identity. */+ const restored = pastedFile({ file_id: 'server-id', temp_file_id: 'temp-key' });+ const editor = renderEditor(new Map([['temp-key', restored]]));++ await act(async () => {+ await editor.result.current.openEditor(restored);+ });+ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });+ await act(async () => {+ capturedLifecycle?.onSuccess?.('replacement-file');+ });++ expect(mockDeleteFile).toHaveBeenCalledTimes(1);+ });+ it('does not delete a submitted restored paste when detaching its replacement', async () => {+ const restored = pastedFile({+ file_id: 'server-id',+ temp_file_id: 'submitted-temp-id',+ attached: true,+ });+ mockState.submittedPasteIds.add('submitted-temp-id');+ mockState.draftsById['conversation-a:0:idle'] = {+ fileIds: [],+ pendingPastes: {},+ pastedTextIds: ['server-id'],+ tabId: 'this-tab',+ };+ const editor = renderEditor(new Map([['server-id', restored]]));++ await act(async () => {+ await editor.result.current.openEditor(restored);+ });+ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });+ await act(async () => {+ capturedLifecycle?.onSuccess?.('replacement-file');+ });+ expect(mockDeleteFile).toHaveBeenCalledTimes(1);+ expect(mockDeleteFiles).not.toHaveBeenCalled();+ });++ it('abandons the queued replacement when its composer is gone by commit time', async () => {+ /** The upload queue holds the batch open until this gate is pulled, standing in for the+ * config wait that keeps a real batch queued across a navigation. */+ let commitQueue: (accepted: boolean) => void = () => undefined;+ mockRouteFiles.mockImplementation(+ (_files: unknown, _toolResource: unknown, lifecycle: UploadLifecycleCallbacks) =>+ new Promise<boolean>((resolve) => {+ commitQueue = (accepted) => resolve(accepted && lifecycle.shouldCommit?.() !== false);+ }),+ );+ const editor = await openEditor();++ let save: Promise<void> = Promise.resolve();+ await act(async () => {+ save = editor.result.current.saveEdit('corrected');+ });+ mockState.conversation = {+ conversationId: 'conversation-b',+ endpoint: 'openAI',+ } as TConversation;+ await act(async () => {+ editor.rerender({ files: new Map<string, ExtendedFile>() });+ });++ expect(mockRouteFiles).toHaveBeenCalledTimes(1);+ await act(async () => {+ commitQueue(true);+ await save;+ });++ expect(await mockRouteFiles.mock.results[0].value).toBe(false);+ expect(mockDeleteFile).not.toHaveBeenCalled();+ });++ it('retires the editor when the conversation changes under it', async () => {+ const editor = await openEditor();+ expect(editor.result.current.editing).not.toBeNull();++ mockState.conversation = {+ conversationId: 'conversation-b',+ endpoint: 'openAI',+ } as TConversation;+ await act(async () => {+ editor.rerender({ files: new Map<string, ExtendedFile>() });+ });++ expect(editor.result.current.editing).toBeNull();+ });++ it('retires the editor when a new chat resets the unsaved-chat identity', async () => {+ const editor = await openEditor();+ expect(editor.result.current.editing).not.toBeNull();++ mockState.draftToken = Symbol('new-conversation-draft');+ await act(async () => {+ editor.rerender({ files: new Map<string, ExtendedFile>() });+ });++ expect(editor.result.current.editing).toBeNull();+ });++ it('refuses a save from a different conversation than the one the edit opened in', async () => {+ const editor = await openEditor();++ mockState.conversation = {+ conversationId: 'conversation-b',+ endpoint: 'openAI',+ } as TConversation;+ await act(async () => {+ editor.rerender({ files: new Map<string, ExtendedFile>() });+ });+ await act(async () => {+ await editor.result.current.saveEdit('corrected');+ });++ expect(mockRouteFiles).not.toHaveBeenCalled();+ expect(mockDeleteFile).not.toHaveBeenCalled();+ });++ it('resolves restored text by downloading the stored bytes', async () => {+ mockFileDownload.mockResolvedValue({+ data: new Blob(['recovered from storage'], { type: 'text/plain' }),+ });+ const restored = pastedFile({ file: undefined, file_id: 'restored-file' });++ const editor = renderEditor();+ await act(async () => {+ await editor.result.current.openEditor(restored);+ });++ expect(mockFileDownload).toHaveBeenCalledWith('user-1', 'restored-file');+ expect(editor.result.current.editing?.text).toBe('recovered from storage');+ });++ it('does not toast a stale failed resolve after a later chip opened', async () => {+ const gates: Array<(error: Error) => void> = [];+ mockFileDownload.mockImplementation(+ () =>+ new Promise((_resolve, reject) => {+ gates.push((error: Error) => reject(error));+ }),+ );+ const slow = pastedFile({ file_id: 'restored-file', file: undefined });+ const fast = pastedFile({ file_id: 'pasted-file' });+ const editor = renderEditor();+ let slowOpen: Promise<void> = Promise.resolve();+ await act(async () => {+ slowOpen = editor.result.current.openEditor(slow);+ });+ await act(async () => {+ await editor.result.current.openEditor(fast);+ });+ expect(editor.result.current.editing?.file.file_id).toBe('pasted-file');++ await act(async () => {+ gates[0]?.(new Error('gone'));+ await slowOpen;+ });++ expect(mockShowToast).not.toHaveBeenCalled();+ expect(editor.result.current.editing?.file.file_id).toBe('pasted-file');+ });++ it('abandons a queued replacement after the original is sent', async () => {+ let commitQueue: (accepted: boolean) => void = () => undefined;+ mockRouteFiles.mockImplementation(+ (_files: unknown, _toolResource: unknown, lifecycle: UploadLifecycleCallbacks) =>+ new Promise<boolean>((resolve) => {+ commitQueue = (accepted) => resolve(accepted && lifecycle.shouldCommit?.() !== false);+ }),+ );+ const editor = await openEditor();+ let save: Promise<void> = Promise.resolve();+ await act(async () => {+ save = editor.result.current.saveEdit('corrected');+ });+ await act(async () => {+ editor.rerender({ files: new Map<string, ExtendedFile>() });+ });+ await act(async () => {+ commitQueue(true);+ await save;+ });++ expect(await mockRouteFiles.mock.results[0].value).toBe(false);+ expect(mockDeleteFile).not.toHaveBeenCalled();+ expect(mockShowToast).not.toHaveBeenCalled();+ });++ it('serializes a second move back against the same attachment', async () => {+ let release: (text: string) => void = () => undefined;+ mockFileDownload.mockImplementation(+ () =>+ new Promise((resolve) => {+ release = (text: string) => resolve({ data: new Blob([text], { type: 'text/plain' }) });+ }),+ );+ const file = pastedFile({ file_id: 'restored-file', file: undefined });+ const editor = renderEditor(new Map([['restored-file', file]]));+ let firstMove: Promise<void> = Promise.resolve();++ await act(async () => {+ firstMove = editor.result.current.moveInline(file);+ void editor.result.current.moveInline(file);+ });+ await act(async () => {+ release('the paste');+ await firstMove;+ });++ expect(mockFileDownload).toHaveBeenCalledTimes(1);+ expect(mockSetValue).toHaveBeenCalledTimes(1);+ });++ it('reports the text unavailable when every source comes back empty', async () => {+ mockFileDownload.mockRejectedValue(new Error('gone'));+ const restored = pastedFile({ file: undefined, file_id: 'restored-file' });++ const editor = renderEditor();+ await act(async () => {+ await editor.result.current.openEditor(restored);+ });++ expect(editor.result.current.editing).toBeNull();+ expect(mockShowToast).toHaveBeenCalledWith(+ expect.objectContaining({ message: 'com_ui_pasted_text_unavailable' }),+ );+ });+});diff --git a/client/src/hooks/Files/index.ts b/client/src/hooks/Files/index.tsindex 21654a95e4..93c6d429e4 100644--- a/client/src/hooks/Files/index.ts+++ b/client/src/hooks/Files/index.ts@@ -8,6 +8,7 @@ export { default as useUpdateFiles } from './useUpdateFiles';export { default as useDragHelpers } from './useDragHelpers';export { default as useUploadOptions } from './useUploadOptions';export { default as useFileUploadRouter } from './useFileUploadRouter';+export { default as usePastedTextEdit } from './usePastedTextEdit';export { default as useFileMap } from './useFileMap';export { default as useSharePointPicker } from './useSharePointPicker';export { default as useSharePointDownload } from './useSharePointDownload';diff --git a/client/src/hooks/Files/useDeleteFilesFromTable.tsx b/client/src/hooks/Files/useDeleteFilesFromTable.tsxindex 351199fb00..408b573b5e 100644--- a/client/src/hooks/Files/useDeleteFilesFromTable.tsx+++ b/client/src/hooks/Files/useDeleteFilesFromTable.tsx@@ -1,8 +1,9 @@-import { useQueryClient } from '@tanstack/react-query';import { QueryKeys } from 'librechat-data-provider';+import { useQueryClient } from '@tanstack/react-query';import type { BatchFile, TFile } from 'librechat-data-provider';import { useDeleteFilesMutation } from '~/data-provider';import useFileDeletion from './useFileDeletion';+import { failedFileIdsFrom } from '~/utils';export default function useDeleteFilesFromTable(callback?: () => void) {const queryClient = useQueryClient();@@ -23,11 +24,16 @@ export default function useDeleteFilesFromTable(callback?: () => void) {onSuccess: (data, variables, context) => {console.log('Files deleted');const { filesToDeleteMap } = context as { filesToDeleteMap: Map<string, BatchFile> };+ const failed = new Set(failedFileIdsFrom(data));queryClient.setQueryData([QueryKeys.files], (oldFiles: TFile[] | undefined) => {const { files } = variables;+ /** A resolved request is not proof the records are gone: the route answers a failed+ * storage delete with HTTP 200 and names the id in `failedFileIds`. */return files.length- ? oldFiles?.filter((file) => !filesToDeleteMap.has(file.file_id))+ ? oldFiles?.filter(+ (file) => !filesToDeleteMap.has(file.file_id) || failed.has(file.file_id),+ ): oldFiles;});callback?.();diff --git a/client/src/hooks/Files/useFileDeletion.ts b/client/src/hooks/Files/useFileDeletion.tsindex 19b6fd3eac..8ccab3e7df 100644--- a/client/src/hooks/Files/useFileDeletion.ts+++ b/client/src/hooks/Files/useFileDeletion.ts@@ -4,9 +4,15 @@ import { FileSources, EToolResources, removeNullishValues } from 'librechat-dataimport type { UseMutateAsyncFunction } from '@tanstack/react-query';import type * as t from 'librechat-data-provider';import type { ExtendedFile, GenericSetter } from '~/common';+import {+ deletePreview,+ failedFileIdsFrom,+ removeTabAttachmentPresence,+ retainFileDeletion,+ scheduleRetainedFileDeletionRetry,+} from '~/utils';import useSetFilesToDelete from './useSetFilesToDelete';import { clearUploadRecovery } from './useFileHandling';-import { deletePreview } from '~/utils';type FileMapSetter = GenericSetter<Map<string, ExtendedFile>>;@@ -15,11 +21,13 @@ const useFileDeletion = ({agent_id,assistant_id,tool_resource,+ index,}: {mutateAsync: UseMutateAsyncFunction<t.DeleteFilesResponse, unknown, t.DeleteFilesBody, unknown>;agent_id?: string;assistant_id?: string;tool_resource?: EToolResources;+ index?: number;}) => {const [_batch, setFileDeleteBatch] = useState<t.BatchFile[]>([]);const setFilesToDelete = useSetFilesToDelete();@@ -42,7 +50,37 @@ const useFileDeletion = ({tool_resource,});console.log('Deleting files:', filesToDelete, payload);- mutateAsync({ files: filesToDelete, ...payload });+ /** The chips are already gone by the time this runs, so a lost request leaves nothing that+ * could rebuild the payload: whatever the server did not delete is kept for the retry pass.+ * A resolved request proves nothing on its own, since a failed storage delete is reported+ * as a 200 naming the file in `failedFileIds`. */+ const retainBatch = (files: t.BatchFile[]): void => {+ /** Only a plain deletion belongs in the shared retry queue. An agent or assistant unlink+ * carries context the retry does not replay, and without it the route would take the+ * ordinary delete branch and destroy a record other references still point at. Nothing is+ * orphaned by a failed unlink either: the file and its links are all still there. */+ if (agent_id != null || assistant_id != null || tool_resource != null) {+ return;+ }+ for (const file of files) {+ retainFileDeletion({+ file_id: file.file_id,+ embedded: file.embedded ?? false,+ filepath: file.filepath ?? '',+ source: file.source ?? FileSources.local,+ });+ }+ scheduleRetainedFileDeletionRetry();+ };+ mutateAsync({ files: filesToDelete, ...payload })+ .then((result) => {+ const failed = new Set(failedFileIdsFrom(result));+ if (failed.size === 0) {+ return;+ }+ retainBatch(filesToDelete.filter((file) => failed.has(file.file_id)));+ })+ .catch(() => retainBatch(filesToDelete));setFileDeleteBatch([]);},[mutateAsync],@@ -72,7 +110,7 @@ const useFileDeletion = ({if (temp_file_id) {clearUploadRecovery(temp_file_id);}-+ removeTabAttachmentPresence([file_id, temp_file_id].filter(Boolean), index);const progress = _file['progress'] ?? 1;if (progress < 1) {@@ -116,7 +154,7 @@ const useFileDeletion = ({return newBatch;});},- [debouncedDelete, setFilesToDelete, agent_id, assistant_id, tool_resource],+ [debouncedDelete, setFilesToDelete, agent_id, assistant_id, tool_resource, index],);const deleteFiles = useCallback(@@ -149,6 +187,10 @@ const useFileDeletion = ({deletePreview(temp_file_id);}}+ removeTabAttachmentPresence(+ batchFiles.flatMap((f) => [f.file_id, f.temp_file_id].filter(Boolean) as string[]),+ index,+ );if (setFiles) {setFiles((currentFiles) => {@@ -175,7 +217,7 @@ const useFileDeletion = ({return newBatch;});},- [debouncedDelete, setFilesToDelete, agent_id, assistant_id],+ [debouncedDelete, setFilesToDelete, agent_id, assistant_id, index],);return { deleteFile, deleteFiles };diff --git a/client/src/hooks/Files/useFileHandling.ts b/client/src/hooks/Files/useFileHandling.tsindex 1eac7e627c..3e83419d48 100644--- a/client/src/hooks/Files/useFileHandling.ts+++ b/client/src/hooks/Files/useFileHandling.ts@@ -63,6 +63,9 @@ type ProcessedUpload = {export type UploadLifecycleCallbacks = {/** 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+ * count against this upload's file and total-size limits. */+ replacesFileId?: string;/** Read once the queue and config waits are over, immediately before the batch is written into* 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. */@@ -451,12 +454,32 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: FilfileConfig: currentFileConfig,endpointType,});+ /** The source remains visible until success, so exclude only its matching entry from this+ * upload's validation tallies. All other callers validate against the complete file map. */+ const filesForValidation = (() => {+ const replacesFileId = uploadLifecycle?.replacesFileId;+ if (replacesFileId == null || replacesFileId === '') {+ return existingFiles;+ }+ const withoutSource = new Map(existingFiles);+ for (const [key, existingFile] of existingFiles) {+ if (+ key === replacesFileId ||+ existingFile.file_id === replacesFileId ||+ existingFile.temp_file_id === replacesFileId+ ) {+ withoutSource.delete(key);+ break;+ }+ }+ return withoutSource;+ })();/* Validate files */let filesAreValid: boolean;try {filesAreValid = validateFiles({- files: existingFiles,+ files: filesForValidation,fileList,setError,fileConfig: currentFileConfig,@@ -611,12 +634,12 @@ const useFileHandlingCore = (params: UseFileHandling | undefined, fileState: Filtry {batchIsValid =validateFileDuplicates({- files: existingFiles,+ files: filesForValidation,fileList: processedFileList,setError,}) &&validateFileSizes({- files: existingFiles,+ files: filesForValidation,fileList: processedFileList,setError,endpointFileConfig,diff --git a/client/src/hooks/Files/usePastedTextEdit.ts b/client/src/hooks/Files/usePastedTextEdit.tsnew file mode 100644index 0000000000..1fecf3f5e1--- /dev/null+++ b/client/src/hooks/Files/usePastedTextEdit.ts@@ -0,0 +1,513 @@+import { useState, useCallback, useRef } from 'react';+import { v4 } from 'uuid';+import { useRecoilValue } from 'recoil';+import { useToastContext } from '@librechat/client';+import {+ dataService,+ EToolResources,+ FileSources,+ isAssistantsEndpoint,+} from 'librechat-data-provider';+import type { TFile } from 'librechat-data-provider';+import type { ExtendedFile, FileSetter } from '~/common';+import {+ addPastedTextDraftFile,+ collectForeignAttachmentClaims,+ failedFileIdsFrom,+ forceResize,+ isFilesDraftOwnedByThisTab,+ isPasteSubmitted,+ getComposerDraftId,+ getFilesDraftCached,+ markPastedTextFile,+ nextPastedTextFilename,+ removePendingTextAttachmentDraft,+ removeTabAttachmentPresence,+ retainFileDeletion,+} from '~/utils';+import { useDeleteFilesMutation, useGetFiles } from '~/data-provider';+import { useChatContext, useChatFormContext } from '~/Providers';+import useFileUploadRouter from './useFileUploadRouter';+import { getNewConversationDraftToken } from '~/utils';+import { useAuthContext } from '~/hooks/AuthContext';+import useFileDeletion from './useFileDeletion';+import { useLocalize } from '~/hooks';+import store from '~/store';++/** The attachment being edited, with its text already resolved so the dialog stays controlled. */+export type PastedTextEdit = {+ file: ExtendedFile;+ text: string;+ /** The composer the dialog was opened in; an edit must never apply to a different one. */+ conversationId: string | null;+ /** Distinguishes two successive unsaved chats, which share the `new` conversation id. */+ draftToken: symbol;+};++/**+ * Backs the paste editor: resolves an attached `pasted-text.txt` back to the text it holds, and+ * applies an edit either as a replacement attachment or by returning the text to the composer.+ */+export default function usePastedTextEdit({+ index = 0,+ files,+ setFiles,+ textAreaRef,+}: {+ index?: number;+ files: Map<string, ExtendedFile>;+ setFiles: FileSetter;+ textAreaRef: React.RefObject<HTMLTextAreaElement>;+}) {+ const localize = useLocalize();+ const { showToast } = useToastContext();+ const { user } = useAuthContext();+ const { conversation, isSubmitting } = useChatContext();+ const methods = useChatFormContext();+ const routeFiles = useFileUploadRouter();+ const { data: fileList } = useGetFiles<TFile[]>();+ const saveDrafts = useRecoilValue(store.saveDrafts);+ const [editing, setEditing] = useState<PastedTextEdit | null>(null);+ /** Failed edits that could not reopen their dialog because another chip was open. Their+ * corrections have no other owner, so they wait for the dialog to free up. */+ const [failedEdits, setFailedEdits] = useState<PastedTextEdit[]>([]);+ /** Source attachments with a replacement upload or inline move in flight; a second action+ * against the same original would double-replace or double-insert it. */+ const [pendingActionIds, setPendingActionIds] = useState<Set<string>>(new Set());++ const { mutateAsync } = useDeleteFilesMutation();+ const { deleteFile } = useFileDeletion({ mutateAsync });++ const conversationId = conversation?.conversationId ?? null;+ const conversationIdRef = useRef(conversationId);+ conversationIdRef.current = conversationId;+ /** Async resolves must re-check the composer against its current state, not the render the+ * callback was captured on. */+ const filesRef = useRef(files);+ filesRef.current = files;+ const editingRef = useRef(editing);+ editingRef.current = editing;+ /** Sequence of editor-open requests, so a slow resolve cannot overwrite a later click. */+ const openRequestRef = useRef(0);+ /** Synchronous lock for in-flight edit/move actions. React state lags a render behind, so two+ * clicks in the same turn would both observe an empty set and double-insert the paste. */+ const pendingActionIdsRef = useRef<Set<string>>(new Set());++ /** The dialog belongs to the composer it was opened in. Switching conversation or starting a+ * new chat retires it: saving from the new composer would detach that conversation's file and+ * upload the replacement into it. Reset on the render that observes the change. */+ if (+ editing != null &&+ (editing.conversationId !== conversationId ||+ editing.draftToken !== getNewConversationDraftToken(index))+ ) {+ setEditing(null);+ }+ if (editing == null && failedEdits.length > 0) {+ setEditing(failedEdits[0]);+ setFailedEdits((queue) => queue.slice(1));+ }++ /** The in-memory blob is the only current copy right after an edit; the file record is the+ * only copy left once the composer was rebuilt from a draft. */+ const resolveText = useCallback(+ async (file: ExtendedFile): Promise<string | null> => {+ if (file.file != null) {+ try {+ return await file.file.text();+ } catch {+ // Fall through to the stored copy rather than failing the open.+ }+ }+ const stored = fileList?.find((entry) => entry.file_id === file.file_id)?.text;+ if (stored != null && stored !== '') {+ return stored;+ }+ /** Assistants and agent uploads are persisted without a `text` field, so a paste restored+ * from a draft has no copy in memory or on its record; the stored bytes are the only+ * remaining source. */+ if (user?.id != null && (file.type ?? '').startsWith('text/')) {+ try {+ const response = await dataService.getFileDownload(user.id, file.file_id);+ const downloaded = await response.data.text();+ if (downloaded !== '') {+ return downloaded;+ }+ } catch {+ // Unreadable bytes leave the affordance to report the text as missing.+ }+ }+ return null;+ },+ [fileList, user?.id],+ );++ /** Whether a file is still one of this composer's unsent chips. The map is not always keyed by+ * the file's own id: a restored entry keeps its temporary upload id as the key while the value+ * carries the server-assigned one, so every identity is matched against keys and values. */+ const isAttachedToComposer = useCallback((file: ExtendedFile): boolean => {+ const identities = new Set([file.file_id]);+ if (file.temp_file_id != null && file.temp_file_id !== '') {+ identities.add(file.temp_file_id);+ }+ for (const [key, entry] of filesRef.current) {+ if (identities.has(key)) {+ return true;+ }+ if (+ (entry.file_id != null && identities.has(entry.file_id)) ||+ (entry.temp_file_id != null && identities.has(entry.temp_file_id))+ ) {+ return true;+ }+ }+ return false;+ }, []);++ const isOpenStale = useCallback(+ (+ request: number,+ conversationIdAtOpen: string | null,+ draftTokenAtOpen: symbol,+ file: ExtendedFile,+ ) =>+ openRequestRef.current !== request ||+ conversationIdRef.current !== conversationIdAtOpen ||+ getNewConversationDraftToken(index) !== draftTokenAtOpen ||+ !isAttachedToComposer(file),+ [index, isAttachedToComposer],+ );++ const openEditor = useCallback(+ async (file: ExtendedFile) => {+ /** A replacement for this chip is already in flight; acting on it again would+ * double-replace the same original. */+ if (pendingActionIdsRef.current.has(file.file_id)) {+ return;+ }+ const conversationIdAtOpen = conversationIdRef.current;+ const draftTokenAtOpen = getNewConversationDraftToken(index);+ /** Restored chips resolve asynchronously; a later click on another chip must not be+ * overwritten by an earlier, slower resolution. */+ const request = ++openRequestRef.current;+ const text = await resolveText(file);+ /** Stale checks first: a failed resolve for an earlier click must not toast after a+ * later chip opened, or after the original was sent / the conversation was left. */+ if (isOpenStale(request, conversationIdAtOpen, draftTokenAtOpen, file)) {+ return;+ }+ if (text == null) {+ showToast({ message: localize('com_ui_pasted_text_unavailable'), status: 'error' });+ return;+ }+ setEditing({+ file,+ text,+ conversationId: conversationIdAtOpen,+ draftToken: draftTokenAtOpen,+ });+ },+ [resolveText, showToast, localize, index, isOpenStale],+ );++ const closeEditor = useCallback(() => setEditing(null), []);++ /** Removes the chip locally and schedules the upload's deletion. A paste restored from a+ * draft carries `attached: true`, which makes `deleteFile` keep the server record because a+ * restored file is normally shared. Foreign claims are checked before either path can schedule+ * deletion, because another tab or composer pane may still reference the upload. Both draft keys+ * are read, since a response finishing mid-edit migrates the record between them. */+ const detach = useCallback(+ (file: ExtendedFile) => {+ const restored = file.attached === true;+ const attachmentIds = [file.file_id, file.temp_file_id].filter(+ (id): id is string => id != null && id !== '',+ );+ const draftIds = [+ getComposerDraftId(index, conversationIdRef.current, isSubmitting),+ getComposerDraftId(index, conversationIdRef.current, !isSubmitting),+ ];+ const claimedElsewhere = collectForeignAttachmentClaims(draftIds, index);+ if (attachmentIds.some((id) => claimedElsewhere.has(id))) {+ removeTabAttachmentPresence(attachmentIds, index);+ setFiles((currentFiles) => {+ const updatedFiles = new Map(currentFiles);+ attachmentIds.forEach((id) => updatedFiles.delete(id));+ return updatedFiles;+ });+ return;+ }++ deleteFile({ file, setFiles });+ if (!restored || file.progress < 1) {+ return;+ }+ /** A submitted paste is still referenced by the message that consumed it. Stop and error+ * paths intentionally leave its draft provenance behind, so detaching a restored chip must+ * not mistake that stale claim for ownership and delete the server record. */+ if (attachmentIds.some((id) => isPasteSubmitted(id))) {+ return;+ }+ const draftOwned = [isSubmitting, !isSubmitting].some((submitting) => {+ const draft = getFilesDraftCached(+ getComposerDraftId(index, conversationIdRef.current, submitting),+ );+ if (!isFilesDraftOwnedByThisTab(draft)) {+ return false;+ }+ const claimed = draft.pastedTextIds ?? [];+ return attachmentIds.some((id) => claimed.includes(id));+ });+ if (draftOwned) {+ const deletion = {+ file_id: file.file_id,+ embedded: file.embedded ?? false,+ filepath: file.filepath ?? '',+ source: file.source ?? FileSources.local,+ };+ /** The chip is already gone, so a failed request cannot be rebuilt from the composer;+ * the payload is retained for the discard path's next retry. A resolved request is not+ * proof of deletion either: the route reports a failed storage delete as a 200 carrying+ * the id in `failedFileIds`, and the draft provenance this deletion was derived from is+ * pruned right after, so retention is the last reference to the orphaned upload. */+ mutateAsync({ files: [deletion] })+ .then((result) => {+ if (failedFileIdsFrom(result).includes(deletion.file_id)) {+ retainFileDeletion(deletion);+ }+ })+ .catch(() => {+ retainFileDeletion(deletion);+ });+ }+ },+ [deleteFile, setFiles, mutateAsync, index, isSubmitting],+ );++ /** The composer an edit belongs to: same conversation, same unsaved-chat identity. */+ const isOriginatingComposer = useCallback(+ (editConversationId: string | null, editDraftToken: symbol) =>+ conversationIdRef.current === editConversationId &&+ getNewConversationDraftToken(index) === editDraftToken,+ [index],+ );++ const saveEdit = useCallback(+ async (text: string) => {+ if (editing == null) {+ return;+ }+ const { file, conversationId: editConversationId, draftToken: editDraftToken } = editing;+ /** Refuse a save from a composer the paste did not come from: the detach and the+ * replacement upload would otherwise land in whatever the user switched to. */+ if (!isOriginatingComposer(editConversationId, editDraftToken)) {+ setEditing(null);+ return;+ }+ /** Uploads are deduped on name + size + type, and an edit that preserves length would+ * otherwise collide with the attachment it replaces. A free name cannot. */+ const attachedFilenames = new Set(+ Array.from(files.values()).map(+ (attached) => attached.file?.name ?? attached.filename ?? '',+ ),+ );+ const replacement = new File([text], nextPastedTextFilename(attachedFilenames), {+ type: 'text/plain',+ });+ /** A paste restored from a draft has no `tool_resource`: the server record does not keep+ * one. `embedded` does survive, and it is only ever set for a file that was vectorized,+ * so it is what tells a file-search paste apart from a plain one, and `metadata.codeEnvRef`+ * does the same for one staged into the code sandbox. Falling straight through to `context`+ * would upload the correction where the original was not and then detach the original,+ * quietly dropping the edited paste out of file search or out of the sandbox. */+ const restoredToolResource = ((): EToolResources | undefined => {+ if (file.metadata?.codeEnvRef != null || file.metadata?.codeEnvRefs != null) {+ return EToolResources.execute_code;+ }+ return file.embedded === true ? EToolResources.file_search : undefined;+ })();+ const toolResource =+ (file.tool_resource as EToolResources | undefined) ??+ restoredToolResource ??+ (isAssistantsEndpoint(conversation?.endpoint) ? undefined : EToolResources.context);++ setEditing(null);+ /** The original stays until the replacement is stored, but it stops accepting actions:+ * a second edit or a Move back against the same original would double-replace it. */+ const sourceId = file.file_id;+ pendingActionIdsRef.current.add(sourceId);+ setPendingActionIds(new Set(pendingActionIdsRef.current));+ const settleAction = () => {+ pendingActionIdsRef.current.delete(sourceId);+ setPendingActionIds(new Set(pendingActionIdsRef.current));+ };+ /** The original stays until the replacement is stored. `routeFiles` resolving only means+ * the upload was accepted into the queue, and detaching first would leave neither copy+ * behind when the upload is rejected or fails. */+ const uploadId = v4();+ /** The replacement is itself a generated paste: without recording its provenance the+ * fresh chip immediately loses the Edit and Move back affordances it exists for. */+ markPastedTextFile(uploadId);+ const replacementDraftId = getComposerDraftId(index, conversationIdRef.current, isSubmitting);+ /** Same rule as the original paste: a record another open tab owns is not ours to write to.+ * `setFilesDraft` keeps that tab's stamp, so recording the replacement there would hand it+ * a chip this composer is still holding, which it could then delete through New Chat. */+ if (saveDrafts && isFilesDraftOwnedByThisTab(getFilesDraftCached(replacementDraftId))) {+ addPastedTextDraftFile({+ id: replacementDraftId,+ fileId: uploadId,+ });+ }+ /** The corrections stay recoverable: a rejected or failed upload reopens the editor with+ * what the user typed, because the original attachment alone no longer holds it. When+ * another chip's dialog is open, the failed edit queues for the freed dialog instead of+ * being dropped: the failed upload's callback was its only remaining owner. */+ const restoreEdits = () => {+ if (!isOriginatingComposer(editConversationId, editDraftToken)) {+ return;+ }+ const revived = {+ file,+ text,+ conversationId: editConversationId,+ draftToken: editDraftToken,+ };+ if (editingRef.current == null) {+ setEditing(revived);+ } else {+ setFailedEdits((queue) => [...queue, revived]);+ }+ };+ const accepted = await routeFiles([replacement], toolResource, {+ fileId: uploadId,+ replacesFileId: sourceId,+ shouldCommit: () =>+ isOriginatingComposer(editConversationId, editDraftToken) && isAttachedToComposer(file),+ onSuccess: () => {+ settleAction();+ /** `shouldCommit` only gates the queue, not the request: the composer can change+ * while the upload itself is in flight, and so can the map, when the message this+ * file belongs to was sent in the meantime. Either way the original is no longer+ * this composer's unsent chip to remove. */+ if (+ isOriginatingComposer(editConversationId, editDraftToken) &&+ isAttachedToComposer(file)+ ) {+ detach(file);+ }+ },+ onError: () => {+ settleAction();+ restoreEdits();+ },+ onAbort: () => {+ settleAction();+ restoreEdits();+ },+ });+ if (!accepted) {+ settleAction();+ /** The queue rejected the replacement before it could create a file, so remove the+ * provenance record that was reserved before routing. Recheck ownership because another+ * tab may have claimed the draft while the upload was in flight. */+ if (saveDrafts && isFilesDraftOwnedByThisTab(getFilesDraftCached(replacementDraftId))) {+ removePendingTextAttachmentDraft({+ id: replacementDraftId,+ fileId: uploadId,+ removeFile: true,+ });+ }+ /** A send or navigation already took the original; reopening the editor or toasting a+ * save error would put a replacement into the emptied composer. */+ if (+ isOriginatingComposer(editConversationId, editDraftToken) &&+ isAttachedToComposer(file)+ ) {+ restoreEdits();+ showToast({ message: localize('com_ui_pasted_text_save_error'), status: 'error' });+ }+ }+ },+ [+ editing,+ files,+ conversation?.endpoint,+ isOriginatingComposer,+ isAttachedToComposer,+ detach,+ routeFiles,+ showToast,+ localize,+ index,+ saveDrafts,+ isSubmitting,+ ],+ );++ /**+ * Drops the attachment and appends its text to the composer. The caret the paste came from is+ * long gone by now, so this lands at the end rather than guessing at an offset.+ *+ * The write goes through the form rather than `insertTextAtCursor`: that helper needs the+ * textarea focused for `execCommand`, and the chip that was clicked is being unmounted as this+ * runs, so the insert silently did nothing. The manual `input` event stands in for the one+ * `execCommand` would have fired, which is what tells autosave to write the draft.+ */+ const moveInline = useCallback(+ async (file: ExtendedFile) => {+ /** Same lock as an edit: a replacement already in flight must not race a move, and a+ * second action must not race this move's own resolve. The ref is claimed before any+ * await so two clicks in the same turn cannot both proceed. */+ if (pendingActionIdsRef.current.has(file.file_id)) {+ return;+ }+ pendingActionIdsRef.current.add(file.file_id);+ setPendingActionIds(new Set(pendingActionIdsRef.current));+ try {+ const conversationIdAtClick = conversationIdRef.current;+ const draftTokenAtClick = getNewConversationDraftToken(index);+ const text = await resolveText(file);+ const moveStale =+ conversationIdRef.current !== conversationIdAtClick ||+ getNewConversationDraftToken(index) !== draftTokenAtClick ||+ !isAttachedToComposer(file);+ if (moveStale) {+ return;+ }+ if (text == null) {+ showToast({ message: localize('com_ui_pasted_text_unavailable'), status: 'error' });+ return;+ }++ setEditing((current) => (current?.file.file_id === file.file_id ? null : current));+ detach(file);++ const textArea = textAreaRef.current;+ const current = textArea?.value ?? methods.getValues('text') ?? '';+ const next = current.length > 0 ? `${current}\n${text}` : text;+ methods.setValue('text', next, { shouldDirty: true, shouldValidate: true });++ if (textArea == null) {+ return;+ }+ textArea.dispatchEvent(new Event('input', { bubbles: true }));+ forceResize(textArea);+ textArea.focus();+ textArea.setSelectionRange(next.length, next.length);+ } finally {+ pendingActionIdsRef.current.delete(file.file_id);+ setPendingActionIds(new Set(pendingActionIdsRef.current));+ }+ },+ [resolveText, showToast, localize, detach, textAreaRef, methods, index, isAttachedToComposer],+ );++ /** Whether a replacement upload or inline move is in flight for a source attachment; the+ * chip's actions hide while it is, so the same original cannot be acted on twice. */+ const isActionPending = useCallback(+ (fileId: string) => pendingActionIds.has(fileId),+ [pendingActionIds],+ );++ return { editing, openEditor, closeEditor, saveEdit, moveInline, isActionPending };+}diff --git a/client/src/hooks/Input/useAutoSave.spec.ts b/client/src/hooks/Input/useAutoSave.spec.tsindex 8331f9b54f..09d2d1d608 100644--- a/client/src/hooks/Input/useAutoSave.spec.ts+++ b/client/src/hooks/Input/useAutoSave.spec.ts@@ -42,6 +42,7 @@ import {setDraft,setFilesDraft,} from '~/utils';+import { markPastedTextFile } from '~/utils/files';import store from '~/store';import { useAutoSave } from '~/hooks';@@ -54,6 +55,13 @@ const makeTextAreaRef = (value = '') =>current: { value, addEventListener: jest.fn(), removeEventListener: jest.fn() },}) as unknown as React.RefObject<HTMLTextAreaElement>;+/** The registry `isTabLive` reads. A stamped tab keeps its claim only while it keeps reporting,+ * so a scenario about another tab has to say whether that tab is still open. */+const markTabLive = (tabId: string): void =>+ localStorage.setItem(`librechat-live-tab:${tabId}`, JSON.stringify({ seenAt: Date.now() }));++const markTabGone = (tabId: string): void => localStorage.removeItem(`librechat-live-tab:${tabId}`);+beforeEach(() => {localStorage.clear();(useRecoilValue as jest.Mock).mockImplementation((atom) => {@@ -656,4 +664,292 @@ describe('useAutoSave — file cache updates', () => {progress: 1,});});++ it('prunes paste provenance ids that left the composer', () => {+ setFilesDraft('convo-1', {+ fileIds: ['live-file', 'removed-file'],+ pendingPastes: {},+ pastedTextIds: ['live-file', 'removed-file'],+ });+ const files = new Map([['live-file', { file_id: 'live-file', progress: 1, size: 0 }]]);++ renderHook(() =>+ useAutoSave({+ conversationId: 'convo-1',+ textAreaRef: makeTextAreaRef(),+ files,+ setFiles: jest.fn(),+ }),+ );++ expect(getFilesDraft('convo-1').pastedTextIds).toEqual(['live-file']);+ });++ it('rebuilds paste provenance for a queued upload restored without a draft', () => {+ /** A paste queued during a run has its pending draft taken by `takeComposerDraft`, so Edit+ * message later restores the upload into an otherwise empty composer with nothing recording+ * that it was a generated paste. Unmarked, it reads as a shared attachment: removing it would+ * not delete it and New Chat would skip it, orphaning the unsent upload. */+ markPastedTextFile('queued-paste');+ setFilesDraft('convo-1', { fileIds: ['queued-paste'], pendingPastes: {} });+ const files = new Map([+ ['queued-paste', { file_id: 'queued-paste', progress: 1, size: 0, attached: true }],+ ]);++ renderHook(() =>+ useAutoSave({+ conversationId: 'convo-1',+ textAreaRef: makeTextAreaRef(),+ files,+ setFiles: jest.fn(),+ }),+ );++ expect(getFilesDraft('convo-1').pastedTextIds).toEqual(['queued-paste']);+ });++ it('does not restore a files draft another open tab owns', () => {+ markTabLive('other-tab');+ mockGetDraft.mockImplementation((id: string) => (id === 'convo-2' ? 'other tab text' : ''));+ setFilesDraft('convo-2', {+ fileIds: ['other-tab-file'],+ pendingPastes: {},+ tabId: 'other-tab',+ });+ const setFiles = jest.fn();+ const { rerender } = renderHook(+ ({ conversationId }: { conversationId: string }) =>+ useAutoSave({+ conversationId,+ textAreaRef: makeTextAreaRef(),+ files: new Map(),+ setFiles,+ }),+ { initialProps: { conversationId: 'convo-1' } },+ );++ act(() => {+ rerender({ conversationId: 'convo-2' });+ });++ expect(mockSetValue).not.toHaveBeenCalledWith('text', 'other tab text');+ expect(getFilesDraft('convo-2').tabId).toBe('other-tab');+ });+ it('keeps autosaving to the pending key while the destination is owned by another live tab', () => {+ jest.useFakeTimers();+ markTabLive('other-tab');+ const savedDrafts = new Map<string, string>();+ mockGetDraft.mockImplementation((id: string) => savedDrafts.get(id) ?? '');+ mockSetDraft.mockImplementation(({ id, value }: { id: string; value?: string }) => {+ if (value != null && value.length > 1) {+ savedDrafts.set(id, value);+ }+ });+ const textAreaRef = makeTextAreaRef('queued draft');+ const { rerender, unmount } = renderHook(+ ({ isSubmitting }: { isSubmitting: boolean }) =>+ useAutoSave({+ isSubmitting,+ conversationId: 'convo-2',+ textAreaRef,+ files: new Map(),+ setFiles: jest.fn(),+ }),+ { initialProps: { isSubmitting: true } },+ );++ setFilesDraft(Constants.PENDING_CONVO, {+ fileIds: ['queued-file'],+ pendingPastes: {},+ });+ setFilesDraft('convo-2', {+ fileIds: ['other-tab-file'],+ pendingPastes: {},+ tabId: 'other-tab',+ });++ act(() => {+ rerender({ isSubmitting: false });+ });++ const inputListeners = (textAreaRef.current!.addEventListener as jest.Mock).mock.calls.filter(+ ([event]) => event === 'input',+ );+ const inputListener = inputListeners[inputListeners.length - 1][1] as (event: unknown) => void;+ textAreaRef.current!.value = 'later edit';+ act(() => {+ inputListener({ target: { value: 'later edit' } });+ jest.advanceTimersByTime(50);+ });++ expect(savedDrafts.get(Constants.PENDING_CONVO)).toBe('later edit');++ unmount();+ mockSetValue.mockClear();+ renderHook(() =>+ useAutoSave({+ isSubmitting: false,+ conversationId: 'convo-2',+ textAreaRef: makeTextAreaRef(),+ files: new Map(),+ setFiles: jest.fn(),+ }),+ );+ expect(mockSetValue).toHaveBeenLastCalledWith('text', 'later edit');+ jest.useRealTimers();+ });++ it('leaves an ordinary conversation on its own key when the pending draft is empty', () => {+ /** Mounting straight onto a conversation reports no previous key, and treating that alone as+ * the awaited pending transition ran the migration on every such load: the conversation was+ * put on the pending key and a just-sent attachment came back into the composer. A reload with+ * real queued work still has to be recognised, so the pending record has to hold something. */+ mockGetDraft.mockImplementation((id: string) =>+ id === 'convo-9' ? 'text that belongs to convo-9' : '',+ );++ renderHook(() =>+ useAutoSave({+ isSubmitting: false,+ conversationId: 'convo-9',+ textAreaRef: makeTextAreaRef(),+ files: new Map(),+ setFiles: jest.fn(),+ }),+ );++ expect(mockSetValue).toHaveBeenLastCalledWith('text', 'text that belongs to convo-9');+ });+ it('keeps live attachments when both pending and destination drafts belong to other tabs', () => {+ markTabLive('pending-owner');+ markTabLive('destination-owner');+ setFilesDraft(Constants.PENDING_CONVO, {+ fileIds: ['pending-tab-file'],+ pendingPastes: {},+ tabId: 'pending-owner',+ });+ setFilesDraft('conversation-foreign', {+ fileIds: ['destination-tab-file'],+ pendingPastes: {},+ tabId: 'destination-owner',+ });++ const files = new Map([+ ['queued-file', { file_id: 'queued-file', progress: 1, size: 1, attached: true }],+ ]);+ const setFiles = jest.fn();+ const { rerender } = renderHook(+ ({ isSubmitting }: { isSubmitting: boolean }) =>+ useAutoSave({+ conversationId: 'conversation-foreign',+ isSubmitting,+ textAreaRef: makeTextAreaRef(),+ files,+ setFiles,+ }),+ { initialProps: { isSubmitting: true } },+ );++ act(() => {+ rerender({ isSubmitting: false });+ });++ const updates = setFiles.mock.calls.map(([update]) =>+ typeof update === 'function' ? update(new Map()) : update,+ );+ expect(updates.some((update) => update.has('queued-file'))).toBe(true);+ });++ it('does not migrate blocked pending drafts to an unrelated conversation', () => {+ const pendingTextKey = `${LocalStorageKeys.TEXT_DRAFT}${Constants.PENDING_CONVO}`;+ localStorage.setItem(pendingTextKey, encodeBase64('draft for conversation C'));+ markTabLive('other-tab');+ (hasInFlightUpload as jest.Mock).mockReturnValue(true);+ setFilesDraft(Constants.PENDING_CONVO, {+ fileIds: ['pending-file'],+ pendingPastes: {+ 'pending-file': { text: 'pending paste', selectionStart: 0 },+ },+ });+ setFilesDraft('conversation-c', {+ fileIds: ['other-tab-file'],+ pendingPastes: {},+ tabId: 'other-tab',+ });++ const { rerender } = renderHook(+ ({ conversationId, isSubmitting }: { conversationId: string; isSubmitting: boolean }) =>+ useAutoSave({+ conversationId,+ isSubmitting,+ textAreaRef: makeTextAreaRef(),+ files: new Map(),+ setFiles: jest.fn(),+ }),+ {+ initialProps: {+ conversationId: 'conversation-c',+ isSubmitting: true,+ },+ },+ );++ act(() => {+ rerender({ conversationId: 'conversation-c', isSubmitting: false });+ });+ act(() => {+ rerender({ conversationId: 'conversation-d', isSubmitting: false });+ });++ expect(localStorage.getItem(pendingTextKey)).toBe(encodeBase64('draft for conversation C'));+ expect(localStorage.getItem(`${LocalStorageKeys.TEXT_DRAFT}conversation-d`)).toBeNull();+ expect(getFilesDraft(Constants.PENDING_CONVO).pendingPastes['pending-file']?.text).toBe(+ 'pending paste',+ );+ expect(getFilesDraft('conversation-d')).toEqual({ fileIds: [], pendingPastes: {} });+ markTabGone('other-tab');+ act(() => {+ rerender({ conversationId: 'conversation-c', isSubmitting: false });+ });++ expect(localStorage.getItem(pendingTextKey)).toBeNull();+ expect(localStorage.getItem(`${LocalStorageKeys.TEXT_DRAFT}conversation-c`)).toBe(+ encodeBase64('draft for conversation C'),+ );+ expect(getFilesDraft('conversation-c').pendingPastes['pending-file']?.text).toBe(+ 'pending paste',+ );+ });+ it('restores a files draft whose owning tab has closed', () => {+ /** A closed tab's id can never be presented again, so without reclaiming it the draft and+ * the text saved beside it would stay unreachable for the rest of the profile's life. */+ markTabLive('other-tab');+ setFilesDraft('convo-2', {+ fileIds: ['closed-tab-file'],+ pendingPastes: {},+ tabId: 'other-tab',+ });+ markTabGone('other-tab');+ mockGetDraft.mockImplementation((id: string) => (id === 'convo-2' ? 'closed tab text' : ''));+ (useGetFiles as jest.Mock).mockReturnValue({+ data: [{ ...persistedRecord, file_id: 'closed-tab-file' }],+ });++ const { rerender } = renderHook(+ ({ conversationId }: { conversationId: string }) =>+ useAutoSave({+ conversationId,+ textAreaRef: makeTextAreaRef(),+ files: new Map(),+ setFiles: jest.fn(),+ }),+ { initialProps: { conversationId: 'convo-1' } },+ );++ act(() => {+ rerender({ conversationId: 'convo-2' });+ });++ expect(mockSetValue).toHaveBeenCalledWith('text', 'closed tab text');+ });});diff --git a/client/src/hooks/Input/useAutoSave.ts b/client/src/hooks/Input/useAutoSave.tsindex ee9ce33ca2..31ccc1f54f 100644--- a/client/src/hooks/Input/useAutoSave.ts+++ b/client/src/hooks/Input/useAutoSave.ts@@ -13,12 +13,16 @@ import {getNewConversationDraftId,getPendingDraftId,isAskAnswerDraftId,+ isFilesDraftOwnedByThisTab,isNewConversationDraftId,+ mayWriteComposerText,migrateFilesDraft,migrateTextDraft,+ publishTabAttachmentIds,setDraft,setFilesDraft,} from '~/utils';+import { isPastedTextFileMarked, markPastedTextFile } from '~/utils/files';import { hasInFlightUpload } from '~/hooks/Files/useFileHandling';import { useChatFormContext } from '~/Providers';import { useGetFiles } from '~/data-provider';@@ -61,6 +65,26 @@ export const useAutoSave = ({const filesRef = useRef(files);filesRef.current = files;+ /** Publishes what this composer holds so cleanup running in another tab can see it. Not gated+ * on `saveDrafts`: with draft saving off nothing is persisted at all, which is exactly when a+ * reattached file would otherwise look like nobody's and be deleted by a retry elsewhere. */+ useEffect(() => {+ /** Every identity, not just the map key: a restored upload is keyed by its temporary id while+ * the value carries the server one, and a retained deletion in another tab names whichever of+ * those it recorded. Publishing one alias would leave the chip unprotected under the other. */+ const identities = new Set<string>();+ files.forEach((file, key) => {+ identities.add(key);+ if (file.file_id != null && file.file_id !== '') {+ identities.add(file.file_id);+ }+ if (file.temp_file_id != null && file.temp_file_id !== '') {+ identities.add(file.temp_file_id);+ }+ });+ publishTabAttachmentIds(index, Array.from(identities));+ }, [index, files]);+const restoreFiles = useCallback((id: string): PendingTextAttachmentDraft[] => {const filesDraft = getFilesDraft(id);@@ -70,13 +94,18 @@ export const useAutoSave = ({* the file-cache path runs on every `QueryKeys.files` write (an upload* landing, an SSE attachment during a run), where an empty draft means the* write has not caught up yet, not that the user has no attachments. */- if (filesDraft.fileIds.length === 0 || fileList == null) {+ if (+ !isFilesDraftOwnedByThisTab(filesDraft) ||+ filesDraft.fileIds.length === 0 ||+ fileList == null+ ) {return [];}const activeFileIds = new Set(filesRef.current.keys());const fileIdsToKeep: string[] = [];const pendingPastes = { ...filesDraft.pendingPastes };+ const pastedTextIds = [...(filesDraft.pastedTextIds ?? [])];const pastesToRecover: PendingTextAttachmentDraft[] = [];// Retrieve files stored in localStorage from files in fileList and set them to `setFiles`@@ -93,6 +122,14 @@ export const useAutoSave = ({if (fileToRecover) {fileIdsToKeep.push(fileId);+ if (pendingPastes[fileId] != null && !pastedTextIds.includes(fileId)) {+ /** Consuming the paste record here, so its id moves to the persistent provenance+ * list: the text is no longer kept, but the chip must stay recognizable as a paste. */+ pastedTextIds.push(fileId);+ }+ if (pastedTextIds.includes(fileId)) {+ markPastedTextFile(fileToRecover.file_id);+ }delete pendingPastes[fileId];setFiles((currentFiles) => {const updatedFiles = new Map(currentFiles);@@ -127,7 +164,12 @@ export const useAutoSave = ({fileIdsToKeep.push(fileId);});- setFilesDraft(id, { fileIds: fileIdsToKeep, pendingPastes });+ const keptIdentities = new Set([...fileIdsToKeep, ...Object.keys(pendingPastes)]);+ setFilesDraft(id, {+ fileIds: fileIdsToKeep,+ pastedTextIds: pastedTextIds.filter((pastedId) => keptIdentities.has(pastedId)),+ pendingPastes,+ });return pastesToRecover;},[fileList, setFiles],@@ -159,26 +201,33 @@ export const useAutoSave = ({},[textAreaRef],);-+ /** The key this composer reads and writes right now. It is the conversation, except while the+ * switch effect has parked storage on the pending key because the destination is not writable.+ * `currentConversationId` alone will not do: it lags `conversationId` by a render on every+ * transition, so keying off it restored the previous conversation's draft into the composer,+ * which after a send put the just-sent attachment straight back as a chip. */+ const activeStorageId =+ currentConversationId === pendingDraftId ? pendingDraftId : conversationId;useEffect(() => {// This useEffect is responsible for setting up and cleaning up the auto-save functionality// for the text area input. It saves the text to localStorage with a debounce to prevent// excessive writes.- if (!saveDrafts || conversationId == null || conversationId === '') {+ const draftStorageId = activeStorageId;+ if (!saveDrafts || draftStorageId == null || draftStorageId === '') {return;}/** Saves the composer's value AT FLUSH TIME rather than the value captured- * when the event fired. A during-run steer/queue consumes the text and- * clears the composer programmatically, so a write still in flight would- * otherwise land after the submit and restore the just-sent text. */+ * when the event fired. A during-run steer/queue consumes the text and+ * clears the composer programmatically, so a write still in flight would+ * otherwise land after the submit and restore the just-sent text. */const saveLatest = () =>- setDraft({ id: conversationId, value: textAreaRef?.current?.value ?? '' });+ setDraft({ id: draftStorageId, value: textAreaRef?.current?.value ?? '' });/** Use shorter debounce for saving text (25ms) to capture rapid typing */const handleInputFast = debounce(saveLatest, 25);- /** Use longer debounce for clearing empty values (850ms) to prevent accidental draft loss */+ /** Use longer debounce for clearing empty values (850ms) to prevent accidental clearing */const handleInputSlow = debounce(saveLatest, 850);const eventListener = (e: Event) => {@@ -210,9 +259,10 @@ export const useAutoSave = ({handleInputFast.cancel();handleInputSlow.cancel();};- }, [conversationId, saveDrafts, textAreaRef]);+ }, [activeStorageId, saveDrafts, textAreaRef]);const prevConversationIdRef = useRef<string | null>(null);+ const pendingDestinationRef = useRef<string | null>(null);useEffect(() => {// This useEffect is responsible for saving the current conversation's draft and@@ -233,37 +283,105 @@ export const useAutoSave = ({/** 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. */let filesDraftId = conversationId;+ let textDraftId = conversationId;+ let nextConversationId = conversationId;try {// Check for transition from PENDING_CONVO to a valid conversationId.// An ask-answer key is excluded: it is a temporary overlay, not the- // pending draft's destination — migrating would delete the very draft+ // pending draft's destination. Migrating would delete the very draft// the answer-phase swap-back is supposed to restore.+ /** A reload reports no previous key, so the pending draft has to be able to speak for+ * itself: this is only the awaited transition when this tab actually owns a pending record+ * that still holds something. Treating any first mount as the transition put an ordinary+ * conversation on the pending key, which then restored a just-sent attachment back into the+ * composer. */+ const pendingDraftRecord = getFilesDraft(pendingDraftId);+ const pendingDraftHasContent =+ isFilesDraftOwnedByThisTab(pendingDraftRecord) &&+ (pendingDraftRecord.fileIds.length > 0 ||+ Object.keys(pendingDraftRecord.pendingPastes).length > 0 ||+ (getDraft(pendingDraftId) ?? '') !== '');+ const pendingDestination = pendingDestinationRef.current;+ const pendingStorageActive =+ (prevConversationIdRef.current === pendingDraftId ||+ currentConversationId === pendingDraftId ||+ (currentConversationId == null && pendingDraftHasContent) ||+ pendingDestination === conversationId) &&+ (pendingDestination == null || pendingDestination === conversationId);if (- prevConversationIdRef.current === pendingDraftId &&+ pendingStorageActive &&conversationId !== pendingDraftId &&!isAskAnswerDraftId(conversationId) &&!isNewConversationDraftId(conversationId) &&conversationId.length > 3) {- // Move the pending text draft to the new conversationId, falling back to the current- // text area value when there was no pending draft to carry over- if (!migrateTextDraft(pendingDraftId, conversationId) && textAreaRef?.current?.value) {- setDraft({ id: conversationId, value: textAreaRef.current.value });+ /** Two tabs running at once share the default pending key, so the record here may be+ * another tab's: migrating first and checking ownership afterwards moved that tab's text+ * and attachments under this conversation and left it nothing to carry over when its own+ * run finished. This composer's text moves to the conversation only when that key is+ * writable; otherwise the pending key remains the active storage location. */+ /** The destination has to be writable too: another tab viewing this same conversation can+ * own its draft with attachments still on screen, and migrating over it would delete that+ * record and restamp the owner. */+ const pendingOwned = isFilesDraftOwnedByThisTab(getFilesDraft(pendingDraftId));+ const destinationOwned = isFilesDraftOwnedByThisTab(getFilesDraft(conversationId));+ const destinationWritable = destinationOwned && mayWriteComposerText(conversationId);+ if (pendingOwned && !destinationWritable) {+ /** Ours to move but nowhere to move it to. Keep both the draft and the active storage key+ * on the pending id until the destination can be written without clobbering its owner. */+ pendingDestinationRef.current = conversationId;+ filesDraftId = pendingDraftId;+ textDraftId = pendingDraftId;+ nextConversationId = pendingDraftId;+ } else if (pendingOwned) {+ pendingDestinationRef.current = null;+ // Move the pending text draft to the new conversationId, falling back to the current+ // text area value when there was no pending draft to carry over+ if (!migrateTextDraft(pendingDraftId, conversationId) && textAreaRef?.current?.value) {+ setDraft({ id: conversationId, value: textAreaRef.current.value });+ }+ filesDraftId = migrateFilesDraft(pendingDraftId, conversationId);+ } else {+ if (textAreaRef?.current?.value) {+ setDraft({ id: conversationId, value: textAreaRef.current.value });+ }+ /** Nothing is taken from the record, but this tab's own queued attachments still have+ * to survive the switch. The map is cleared at the top of this effect, so persist them+ * under the destination when it is writable and restore the live map otherwise. */+ const liveFileIds = Array.from(filesRef.current.keys());+ if (liveFileIds.length > 0 && destinationOwned) {+ /** Provenance travels with them, or the restored chips stop being recognised as+ * pastes and lose both editing and New Chat cleanup. It is rebuilt from the session+ * registry rather than the foreign record, which is not ours to read. The unsent+ * paste text cannot come along: this tab was refused the pending key all run, so it+ * was never written anywhere to carry. */+ setFilesDraft(conversationId, {+ fileIds: liveFileIds,+ pendingPastes: {},+ pastedTextIds: liveFileIds.filter((fileId) => isPastedTextFileMarked(fileId)),+ });+ } else if (liveFileIds.length > 0) {+ /** Neither shared key is writable by this tab. The live map is the only copy of these+ * queued attachments, so restore it after the unconditional switch clear rather than+ * dropping it. */+ setFiles(filesRef.current);+ }}- filesDraftId = migrateFilesDraft(pendingDraftId, conversationId);} else if (currentConversationId != null && currentConversationId) {saveText(currentConversationId);}- const pendingPastes = restoreFiles(filesDraftId);- restoreText(conversationId, pendingPastes);+ if (isFilesDraftOwnedByThisTab(getFilesDraft(filesDraftId))) {+ const pendingPastes = restoreFiles(filesDraftId);+ restoreText(textDraftId, pendingPastes);+ }} catch (e) {console.error(e);}- prevConversationIdRef.current = conversationId;- setCurrentConversationId(conversationId);+ prevConversationIdRef.current = nextConversationId;+ setCurrentConversationId(nextConversationId);}, [currentConversationId,conversationId,@@ -277,46 +395,65 @@ export const useAutoSave = ({]);useEffect(() => {- if (- !saveDrafts ||- conversationId == null ||- conversationId === '' ||- currentConversationId !== conversationId ||- fileList == null- ) {+ const draftStorageId = activeStorageId;+ if (!saveDrafts || draftStorageId == null || draftStorageId === '' || fileList == null) {return;}- const pendingPastes = restoreFiles(conversationId);+ const pendingPastes = restoreFiles(draftStorageId);if (pendingPastes.length > 0) {- restoreText(conversationId, pendingPastes);+ restoreText(draftStorageId, pendingPastes);}- }, [conversationId, currentConversationId, fileList, restoreFiles, restoreText, saveDrafts]);+ }, [activeStorageId, fileList, restoreFiles, restoreText, saveDrafts]);useEffect(() => {// This useEffect is responsible for saving or removing the current conversation's file drafts// in localStorage whenever the file attachments change.// 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 (- !saveDrafts ||- conversationId == null ||- conversationId === '' ||- currentConversationId !== conversationId- ) {+ if (!saveDrafts || draftStorageId == null || draftStorageId === '') {return;}- const existingDraft = getFilesDraft(conversationId);+ const existingDraft = getFilesDraft(draftStorageId);+ if (!isFilesDraftOwnedByThisTab(existingDraft)) {+ return;+ }const pendingFileIds = Object.keys(existingDraft.pendingPastes);const draftFileIds = [...fileIds,...pendingFileIds.filter((fileId) => !fileIds.includes(fileId)),];- setFilesDraft(conversationId, {+ const liveIds = new Set(draftFileIds);+ files.forEach((file, key) => {+ liveIds.add(key);+ if (file.file_id != null) {+ liveIds.add(file.file_id);+ }+ if (file.temp_file_id != null && file.temp_file_id !== '') {+ liveIds.add(file.temp_file_id);+ }+ });+ /** Provenance is rebuilt, not just filtered. A paste queued during a run has its pending+ * draft taken by `takeComposerDraft`, so choosing Edit message later restores the upload into+ * an otherwise empty composer with nothing recording that it was ever a generated paste.+ * Filtering alone left it unmarked, and an unmarked restored chip is treated as a shared+ * attachment: removing it would not delete it and New Chat would skip it, so the unsent upload+ * was orphaned. The session registry still knows, so it is asked. */+ const pastedTextIds = (existingDraft.pastedTextIds ?? []).filter((id) => liveIds.has(id));+ const claimed = new Set(pastedTextIds);+ for (const id of liveIds) {+ if (!claimed.has(id) && isPastedTextFileMarked(id)) {+ pastedTextIds.push(id);+ claimed.add(id);+ }+ }+ setFilesDraft(draftStorageId, {fileIds: draftFileIds,+ pastedTextIds,pendingPastes: existingDraft.pendingPastes,});- }, [conversationId, saveDrafts, currentConversationId, fileIds]);+ }, [conversationId, saveDrafts, currentConversationId, fileIds, files]);};diff --git a/client/src/hooks/Input/useTextarea.spec.tsx b/client/src/hooks/Input/useTextarea.spec.tsxindex 98f97fcd41..9b3e1f7551 100644--- a/client/src/hooks/Input/useTextarea.spec.tsx+++ b/client/src/hooks/Input/useTextarea.spec.tsx@@ -32,6 +32,7 @@ let mockConversation: { endpoint: string; conversationId?: string } = {jest.mock('~/utils', () => ({...jest.requireActual('~/utils/drafts'),+ ...jest.requireActual('~/utils/files'),forceResize: mockForceResize,insertTextAtCursor: mockInsertTextAtCursor,resolvePastedTextFile: mockResolvePastedTextFile,@@ -275,7 +276,9 @@ describe('useTextarea long-paste fallback', () => {expect(mockInsertTextAtCursor).toHaveBeenCalledWith(textArea, pastedText);expect(mockForceResize).toHaveBeenCalledWith(textArea);- expect(getFilesDraft('convo-1')).toEqual({ fileIds: [], pendingPastes: {} });+ expect(getFilesDraft('convo-1')).toEqual(+ expect.objectContaining({ fileIds: [], pendingPastes: {} }),+ );});it('skips upload-failure recovery when the conversation changed', async () => {@@ -356,6 +359,44 @@ describe('useTextarea long-paste fallback', () => {expect(getFilesDraft('convo-1').pendingPastes['file-1']?.text).toBe(pastedText);});+ it('reinserts a failed paste at its anchor when another tab owns the draft', async () => {+ /** The ownership guard skips the only durable copy of the paste, so this callback is all that+ * is left holding it: refusing because the composer moved on would lose the text outright. */+ localStorage.setItem('librechat-live-tab:other-tab', JSON.stringify({ seenAt: Date.now() }));+ localStorage.setItem(+ 'filesDraft_convo-1',+ JSON.stringify({ fileIds: ['other-tab-file'], pendingPastes: {}, tabId: 'other-tab' }),+ );+ let insertOffset = -1;+ mockInsertTextAtCursor.mockImplementationOnce((element: HTMLTextAreaElement) => {+ insertOffset = element.selectionStart;+ });+ let uploadLifecycle: UploadLifecycleCallbacks | undefined;+ mockRouteFiles.mockImplementationOnce(+ (_files: File[], _toolResource: EToolResources, lifecycle?: UploadLifecycleCallbacks) => {+ uploadLifecycle = lifecycle;+ return Promise.resolve(true);+ },+ );+ const { result, textArea } = renderTextareaHook();+ textArea.value = 'draft at paste time';+ textArea.setSelectionRange('draft at paste time'.length, 'draft at paste time'.length);+ const event = createPasteEvent();++ act(() =>+ result.current.handlePaste(event as unknown as React.ClipboardEvent<HTMLTextAreaElement>),+ );++ await waitFor(() => expect(uploadLifecycle).toBeDefined());+ expect(getFilesDraft('convo-1').pendingPastes).toEqual({});+ textArea.value = 'draft at paste time and more';++ act(() => uploadLifecycle?.onError?.('file-1'));++ expect(mockInsertTextAtCursor).toHaveBeenCalledWith(textArea, pastedText);+ expect(insertOffset).toBe('draft at paste time'.length);+ });+it('forwards upload recovery through the assistants route', async () => {mockConversation = { endpoint: 'assistants' };let uploadLifecycle: UploadLifecycleCallbacks | undefined;@@ -436,7 +477,9 @@ describe('useTextarea long-paste fallback', () => {expect(mockInsertTextAtCursor).toHaveBeenCalledWith(textArea, pastedText);expect(mockForceResize).toHaveBeenCalledWith(textArea);- expect(getFilesDraft('convo-1')).toEqual({ fileIds: [], pendingPastes: {} });+ expect(getFilesDraft('convo-1')).toEqual(+ expect.objectContaining({ fileIds: [], pendingPastes: {} }),+ );});it('stores a pending paste under the submitting pane draft key', async () => {@@ -462,7 +505,9 @@ describe('useTextarea long-paste fallback', () => {pastedText,),);- expect(getFilesDraft(Constants.PENDING_CONVO)).toEqual({ fileIds: [], pendingPastes: {} });+ expect(getFilesDraft(Constants.PENDING_CONVO)).toEqual(+ expect.objectContaining({ fileIds: [], pendingPastes: {} }),+ );expect(uploadLifecycle).toBeDefined();});@@ -489,7 +534,9 @@ describe('useTextarea long-paste fallback', () => {getFilesDraft(getNewConversationDraftId(1)).pendingPastes['pane-1-new-file']?.text,).toBe(pastedText),);- expect(getFilesDraft(Constants.NEW_CONVO)).toEqual({ fileIds: [], pendingPastes: {} });+ expect(getFilesDraft(Constants.NEW_CONVO)).toEqual(+ expect.objectContaining({ fileIds: [], pendingPastes: {} }),+ );expect(uploadLifecycle).toBeDefined();});@@ -677,10 +724,12 @@ describe('useTextarea long-paste fallback', () => {);act(() => uploadLifecycle?.onSuccess?.('successful-file'));- expect(getFilesDraft('convo-1')).toEqual({- fileIds: ['successful-file'],- pendingPastes: {},- });+ expect(getFilesDraft('convo-1')).toEqual(+ expect.objectContaining({+ fileIds: ['successful-file'],+ pendingPastes: {},+ }),+ );});it('does not treat a successful upload as failed when draft storage reads throw', async () => {diff --git a/client/src/hooks/Input/useTextarea.ts b/client/src/hooks/Input/useTextarea.tsindex ec1dc3423c..a317b82eff 100644--- a/client/src/hooks/Input/useTextarea.ts+++ b/client/src/hooks/Input/useTextarea.ts@@ -15,7 +15,12 @@ import {getComposerDraftId,setPendingTextAttachmentDraft,removePendingTextAttachmentDraft,+ resolvePendingPasteInsertStart,+ addPastedTextDraftFile,+ isFilesDraftOwnedByThisTab,+ getFilesDraft,setDraft,+ markPastedTextFile,getEntityName,getEntity,checkIfScrollable,@@ -400,7 +405,13 @@ export default function useTextarea({}const composerValue = textArea.value;const pendingFileId = v4();- if (saveDrafts) {+ markPastedTextFile(pendingFileId);+ /** Another open tab can hold this shared key against files it still has attached, and+ * `setFilesDraft` keeps that owner rather than rejecting the write: recording this paste+ * there would hand it to a composer that never made it, which could then restore the+ * upload and delete it through New Chat while this tab still shows the chip. */+ if (saveDrafts && isFilesDraftOwnedByThisTab(getFilesDraft(draftId))) {+ addPastedTextDraftFile({ id: draftId, fileId: pendingFileId });try {setDraft({ id: draftId, value: composerValue, persistExact: true });setPendingTextAttachmentDraft({@@ -418,8 +429,8 @@ export default function useTextarea({// Persistence must not prevent the generated attachment from uploading.}}- const restorePaste = (target: HTMLTextAreaElement) => {- target.setSelectionRange(selectionStart, selectionStart);+ const restorePaste = (target: HTMLTextAreaElement, insertStart: number) => {+ target.setSelectionRange(insertStart, insertStart);insertTextAtCursor(target, pastedText);forceResize(target);};@@ -427,18 +438,43 @@ export default function useTextarea({const isOriginatingComposer = (): boolean =>conversationIdRef.current === conversationId &&getNewConversationDraftToken(index) === draftToken;- const restorePasteAfterUploadFailure = (): boolean => {+ /** Whether a durable copy of this paste exists. When one does, a composer the user has+ * since typed into is deliberately left alone: the record recovers at an anchored offset on+ * the next restore, and inserting here as well would fight that. */+ const hasPersistedPasteRecovery = (fileId: string): boolean => {+ if (!saveDrafts) {+ return false;+ }+ const { pendingPastes } = getFilesDraft(draftId);+ return pendingPastes[fileId] != null || pendingPastes[pendingFileId] != null;+ };+ const restorePasteAfterUploadFailure = (fileId: string): boolean => {const currentTextArea = textAreaRef.current;- if (- !currentTextArea ||- answerModeActiveRef.current ||- !isOriginatingComposer() ||- currentTextArea.value !== composerValue- ) {+ if (!currentTextArea || answerModeActiveRef.current || !isOriginatingComposer()) {return false;}-- restorePaste(currentTextArea);+ const composerUnchanged = currentTextArea.value === composerValue;+ if (!composerUnchanged && hasPersistedPasteRecovery(fileId)) {+ return false;+ }+ /** Nothing durable to fall back on: the shared draft key belongs to another tab, or drafts+ * are off, so this callback holds the only copy of the paste left. Dropping it because the+ * composer moved on would lose it outright, so it goes back in at the offset its anchors+ * resolve to, which is where a restore from a record would have put it. */+ restorePaste(+ currentTextArea,+ composerUnchanged+ ? selectionStart+ : resolvePendingPasteInsertStart(currentTextArea.value, {+ text: pastedText,+ selectionStart,+ selectionEnd,+ replacedText,+ replacedApplied: true,+ anchorBefore: composerValue.slice(0, selectionStart),+ anchorAfter: composerValue.slice(selectionStart),+ }),+ );if (saveDrafts) {setDraft({id: getComposerDraftId(index, conversationIdRef.current, isSubmittingRef.current),@@ -465,10 +501,16 @@ export default function useTextarea({fileId: pendingFileId,shouldCommit: isOriginatingComposer,onStart: (fileId) => {- if (!saveDrafts || fileId === pendingFileId) {+ markPastedTextFile(fileId);+ if (+ !saveDrafts ||+ fileId === pendingFileId ||+ !isFilesDraftOwnedByThisTab(getFilesDraft(draftId))+ ) {return;}try {+ addPastedTextDraftFile({ id: draftId, fileId });removePendingTextAttachmentDraft({id: draftId,fileId: pendingFileId,@@ -493,7 +535,7 @@ export default function useTextarea({clearPendingPasteDraft(fileId);},onError: (fileId) => {- const restored = restorePasteAfterUploadFailure();+ const restored = restorePasteAfterUploadFailure(fileId);if (restored || getNewConversationDraftToken(index) !== draftToken) {clearPendingPasteDraft(fileId, true);}@@ -507,7 +549,7 @@ export default function useTextarea({/** The name is either attached now or was never taken, so stop reserving it. */reservedPasteFilenames.current.delete(pastedFilename);if (!accepted) {- const restored = restorePasteAfterUploadFailure();+ const restored = restorePasteAfterUploadFailure(pendingFileId);if (restored || getNewConversationDraftToken(index) !== draftToken) {clearPendingPasteDraft(pendingFileId, true);}diff --git a/client/src/hooks/__tests__/useNewConvo.spec.ts b/client/src/hooks/__tests__/useNewConvo.spec.tsnew file mode 100644index 0000000000..7c2c8313ae--- /dev/null+++ b/client/src/hooks/__tests__/useNewConvo.spec.ts@@ -0,0 +1,183 @@+import { renderHook, act } from '@testing-library/react';++const mockDeleteFiles = jest.fn();+const mockSetFiles = jest.fn();+const mockRemoveTabAttachmentPresence = jest.fn();+const mockCollectForeignAttachmentClaims = jest.fn(+ (_excludeDraftIds: string[], _excludeOwnPane?: number | 'tab') => new Set(mockForeignClaims),+);+const mockForeignClaims = new Set<string>();+const mockMarkedPasteIds = new Set<string>();+const mockPendingDiscardIds = new Set<string>();+const mockStorePendingDiscardIds = jest.fn((_index: number, ids: string[]) => {+ mockPendingDiscardIds.clear();+ ids.forEach((id) => mockPendingDiscardIds.add(id));+});+const mockFiles = new Map<+ string,+ {+ file_id: string;+ temp_file_id?: string;+ filepath?: string;+ source?: string;+ embedded?: boolean;+ attached?: boolean;+ progress?: number;+ }+>();++jest.mock('react-router-dom', () => ({+ useNavigate: () => jest.fn(),+ useSearchParams: () => [new URLSearchParams()],+}));++jest.mock('recoil', () => ({+ useRecoilState: () => [mockFiles, mockSetFiles],+ useRecoilValue: (key: string) => {+ if (key === 'saveDrafts') {+ return false;+ }+ if (key === 'saveBadgesState') {+ return true;+ }+ return null;+ },+ useSetRecoilState: () => jest.fn(),+ useRecoilCallback: () => jest.fn(),+}));+jest.mock('librechat-data-provider/react-query', () => ({+ useGetModelsQuery: () => ({ data: {} }),+}));++jest.mock('librechat-data-provider', () => ({+ ...jest.requireActual('librechat-data-provider'),+}));++jest.mock('~/utils', () => ({+ updateLastSelectedModel: jest.fn(),+ getLocalStorageItems: () => ({}),+ getDefaultModelSpec: () => ({}),+ getDefaultEndpoint: () => undefined,+ getModelSpecPreset: jest.fn(),+ hasModelSelection: () => false,+ isPastedTextFileMarked: (fileId?: string | null) =>+ fileId != null && mockMarkedPasteIds.has(fileId),+ collectForeignAttachmentClaims: (excludeDraftIds: string[], excludeOwnPane?: number | 'tab') =>+ mockCollectForeignAttachmentClaims(excludeDraftIds, excludeOwnPane),+ getNewConversationDraftId: (index = 0) => (index === 0 ? 'new' : `new:${index}`),+ getPendingDraftId: (index = 0) => (index === 0 ? 'pending' : `pending:${index}`),+ renewNewConversationDraftToken: jest.fn(),+ removeTabAttachmentPresence: (...args: unknown[]) => mockRemoveTabAttachmentPresence(...args),+ loadPendingDiscardIds: () => [...mockPendingDiscardIds],+ storePendingDiscardIds: (index: number, ids: string[]) => mockStorePendingDiscardIds(index, ids),+ scheduleRetainedFileDeletionRetry: jest.fn(),+ retainFileDeletion: jest.fn(),+ failedFileIdsFrom: () => [],+ logger: { log: jest.fn() },+}));++jest.mock('~/data-provider', () => ({+ useDeleteFilesMutation: () => ({ mutateAsync: mockDeleteFiles }),+ useGetEndpointsQuery: () => ({ data: {} }),+ useGetStartupConfig: () => ({ data: {} }),+}));++jest.mock('../Conversations/useNavigateToConvo', () => ({+ __esModule: true,+ supersedeNavigation: jest.fn(),+}));+jest.mock('../Conversations/useGetConversation', () => ({+ __esModule: true,+ default: () => () => null,+}));+jest.mock('../Assistants/useAssistantListMap', () => ({+ __esModule: true,+ default: () => ({}),+}));+jest.mock('../Files/useFileHandling', () => ({ clearUploadRecovery: jest.fn() }));+jest.mock('../useChatBadges', () => ({ useResetChatBadges: () => jest.fn() }));+jest.mock('../Agents', () => ({ useApplyModelSpecEffects: () => jest.fn() }));+jest.mock('../Audio', () => ({ usePauseGlobalAudio: () => ({ pauseGlobalAudio: jest.fn() }) }));+jest.mock('~/Providers', () => ({ useAgentsMapContext: () => ({}) }));+jest.mock('~/hooks', () => ({ useHasAccess: () => true }));+jest.mock('~/store', () => ({+ __esModule: true,+ default: {+ defaultPreset: 'defaultPreset',+ saveBadgesState: 'saveBadgesState',+ saveDrafts: 'saveDrafts',+ filesByIndex: () => 'filesByIndex',+ submissionByIndex: () => 'submissionByIndex',+ useClearConvoState: () => jest.fn(),+ useSetConversationAtom: () => ({ setConversation: jest.fn() }),+ },+}));++import useNewConvo from '../useNewConvo';++describe('useNewConvo reset cleanup', () => {+ beforeEach(() => {+ jest.clearAllMocks();+ mockDeleteFiles.mockResolvedValue({});+ mockForeignClaims.clear();+ mockMarkedPasteIds.clear();+ mockPendingDiscardIds.clear();+ mockFiles.clear();+ mockFiles.set('claimed-file', {+ file_id: 'claimed-file',+ temp_file_id: 'client-claimed-file',+ filepath: '/uploads/claimed-file.txt',+ source: 'local',+ });+ mockFiles.set('own-file', {+ file_id: 'own-file',+ temp_file_id: 'client-own-file',+ filepath: '/uploads/own-file.txt',+ source: 'local',+ });+ });++ it('does not delete a file claimed by another tab but deletes an unclaimed file', () => {+ mockForeignClaims.add('claimed-file');+ const { result } = renderHook(() => useNewConvo(2));++ act(() => {+ result.current.newConversation();+ });++ expect(mockCollectForeignAttachmentClaims).toHaveBeenCalledWith(['new:2', 'pending:2'], 2);+ expect(mockRemoveTabAttachmentPresence).toHaveBeenCalledWith(expect.any(Array), 2);++ expect(mockDeleteFiles).toHaveBeenCalledWith({+ files: [+ {+ file_id: 'own-file',+ embedded: false,+ filepath: '/uploads/own-file.txt',+ source: 'local',+ },+ ],+ });+ });++ it('defers an in-flight generated paste when drafts are disabled', () => {+ /** Direct `newConversation()` callers never pass through useNewChat, so this reset is the only+ * thing that can remember an upload with no filepath yet: nothing else would be left to delete+ * the server record once the request finally lands. */+ mockFiles.clear();+ mockFiles.set('inflight-paste', {+ file_id: 'inflight-paste',+ attached: false,+ progress: 0,+ });+ mockMarkedPasteIds.add('inflight-paste');+ const { result } = renderHook(() => useNewConvo());++ act(() => {+ result.current.newConversation();+ });++ expect(mockStorePendingDiscardIds).toHaveBeenCalledWith(0, ['inflight-paste']);+ expect(mockPendingDiscardIds).toEqual(new Set(['inflight-paste']));+ });+});diff --git a/client/src/hooks/useNewConvo.ts b/client/src/hooks/useNewConvo.tsindex 37669b2bcc..32f1ee71b4 100644--- a/client/src/hooks/useNewConvo.ts+++ b/client/src/hooks/useNewConvo.ts@@ -34,6 +34,16 @@ import {buildDefaultConvo,requestChatFocus,renewNewConversationDraftToken,+ getNewConversationDraftId,+ getPendingDraftId,+ isPastedTextFileMarked,+ loadPendingDiscardIds,+ storePendingDiscardIds,+ removeTabAttachmentPresence,+ collectForeignAttachmentClaims,+ scheduleRetainedFileDeletionRetry,+ retainFileDeletion,+ failedFileIdsFrom,logger,} from '~/utils';import { useDeleteFilesMutation, useGetEndpointsQuery, useGetStartupConfig } from '~/data-provider';@@ -382,12 +392,19 @@ const useNewConvo = (index = 0) => {clearUploadRecovery(file.temp_file_id);}+ /** A generated paste is this composer's own upload and goes with it, even when that+ * upload was vectorized for file search: skipping every embedded record left an unsent+ * embedded paste with its metadata, storage and vectors all still on the server.+ * Anything else embedded is left alone, since those are shared. */+ const ownedPaste =+ [fileId, file.file_id, file.temp_file_id].some((id) => isPastedTextFileMarked(id)) &&+ file.attached !== true;if (file.filepath == null ||file.filepath === '' ||!file.source ||- (file.embedded ?? false) ||- !file.temp_file_id+ ((file.embedded ?? false) && !ownedPaste) ||+ (!file.temp_file_id && !ownedPaste)) {return [];}@@ -395,25 +412,84 @@ const useNewConvo = (index = 0) => {return [{file_id: file.file_id,- embedded: false,+ embedded: ownedPaste ? (file.embedded ?? false) : false,filepath: file.filepath,source: file.source as FileSources,},];});+ if (!saveDrafts) {+ /** An upload still in flight has no filepath or source yet, so filesToDelete cannot build a+ * deletion payload for it. Direct newConversation callers need to persist its id before+ * clearing the composer map. Merge with the existing store because useNewChat may already+ * have recorded the same id. */+ const inFlightPasteIds: string[] = [];+ files.forEach((file, key) => {+ const isMarkedPaste = [key, file.file_id, file.temp_file_id].some((id) =>+ isPastedTextFileMarked(id),+ );+ if (file.attached !== true && file.progress < 1 && isMarkedPaste) {+ inFlightPasteIds.push(file.file_id);+ }+ });+ if (inFlightPasteIds.length > 0) {+ const pendingDiscardIds = new Set(loadPendingDiscardIds(index));+ inFlightPasteIds.forEach((fileId) => pendingDiscardIds.add(fileId));+ storePendingDiscardIds(index, Array.from(pendingDiscardIds));+ }+ }+ const discardedFileIds = Array.from(+ new Set([+ ...filesToDelete.map((f) => f.file_id),+ ...Array.from(files.keys()),+ ...Array.from(files.values()).flatMap(+ (f) => [f.file_id, f.temp_file_id].filter(Boolean) as string[],+ ),+ ]),+ );+ removeTabAttachmentPresence(discardedFileIds, index);setFiles(new Map());localStorage.setItem(LocalStorageKeys.FILES_TO_DELETE, JSON.stringify({}));-if (!saveDrafts && filesToDelete.length > 0) {- mutateAsync({ files: filesToDelete });+ /** Another tab's draft or live presence wins over this reset's cleanup: its chip or sent+ * message may still reference the same server upload. The discarded draft keys are+ * excluded so this pane's own claims do not block its cleanup, and skipped records are+ * not retained for retry because they are not this pane's to delete. */+ const claimedElsewhere = collectForeignAttachmentClaims(+ [getNewConversationDraftId(index), getPendingDraftId(index)],+ index,+ );+ const deletableFiles = filesToDelete.filter(+ (record) => !claimedElsewhere.has(record.file_id),+ );+ if (deletableFiles.length > 0) {+ /** The map is already cleared above, so a lost request leaves nothing that could+ * rebuild these payloads. Whatever the server did not delete is retained for the+ * cleanup pass, since a failed storage delete comes back as a 200 naming the file in+ * `failedFileIds` rather than as a rejection. */+ const retainAll = (records: typeof filesToDelete) => {+ for (const record of records) {+ retainFileDeletion(record);+ }+ scheduleRetainedFileDeletionRetry();+ };+ mutateAsync({ files: deletableFiles })+ .then((result) => {+ const failed = new Set(failedFileIdsFrom(result));+ if (failed.size === 0) {+ return;+ }+ retainAll(deletableFiles.filter((record) => failed.has(record.file_id)));+ })+ .catch(() => retainAll(deletableFiles));+ }}}/** A first visit to another conversation may still be waiting on its- * record. Starting a new chat keeps the pathname, so nothing the route- * check sees changes — without this, that record lands and pulls the user- * into the conversation they just abandoned.+ * record. Starting a new chat keeps the pathname, so the route check sees no change. That+ * record could then land and pull the user into the conversation they just abandoned.** `keepComposerState` marks a call that re-renders a composer an earlier* call already opened, such as agent metadata arriving late. The user diddiff --git a/client/src/locales/en/translation.json b/client/src/locales/en/translation.jsonindex 65737a336c..d905e52f27 100644--- a/client/src/locales/en/translation.json+++ b/client/src/locales/en/translation.json@@ -1168,6 +1168,7 @@"com_ui_delete_selected_items": "Delete selected items","com_ui_delete_shared_link": "Delete shared link?","com_ui_delete_shared_link_heading": "Delete Shared Link",+ "com_ui_delete_partial_failure": "Some files could not be deleted","com_ui_delete_success": "Successfully deleted","com_ui_delete_tool": "Delete Tool","com_ui_delete_tool_confirm": "Are you sure you want to delete this tool?",@@ -1689,6 +1690,11 @@"com_ui_output": "Output","com_ui_page": "Page","com_ui_parameters": "Parameters",+ "com_ui_pasted_text_edit": "Edit pasted text",+ "com_ui_pasted_text_edit_chip": "Edit pasted text, {{0}}",+ "com_ui_pasted_text_move_inline": "Move back into message",+ "com_ui_pasted_text_save_error": "Could not save the edited text",+ "com_ui_pasted_text_unavailable": "This pasted text is no longer available to edit","com_ui_path": "Path","com_ui_people": "people","com_ui_people_picker": "People Picker",diff --git a/client/src/utils/__tests__/localStorage.test.ts b/client/src/utils/__tests__/localStorage.test.tsindex 18918ce187..0d9974d650 100644--- a/client/src/utils/__tests__/localStorage.test.ts+++ b/client/src/utils/__tests__/localStorage.test.ts@@ -1,5 +1,5 @@import { LocalStorageKeys } from 'librechat-data-provider';-import { clearAllConversationStorage } from '../localStorage';+import { clearAllConversationStorage, clearLocalStorage } from '../localStorage';describe('clearAllConversationStorage', () => {beforeEach(() => {@@ -27,3 +27,37 @@ describe('clearAllConversationStorage', () => {expect(localStorage.getItem('unrelated-key')).toBe('keep-me');});});++describe('clearLocalStorage', () => {+ beforeEach(() => {+ localStorage.clear();+ });++ it('drops composer drafts so an account change cannot restore the last user text', () => {+ /** A files draft carries the whole text of a paste held as a file, and the browser tab keeps+ * its identity across an in-app account switch, so leaving these behind let the next account+ * be handed the previous one's writing by the ordinary draft restore. */+ localStorage.setItem(+ `${LocalStorageKeys.FILES_DRAFT}new`,+ JSON.stringify({ fileIds: [], pendingPastes: { 'paste-1': { encodedText: 'c2VjcmV0' } } }),+ );+ localStorage.setItem(`${LocalStorageKeys.TEXT_DRAFT}new`, 'half-written message');+ localStorage.setItem('unrelated-key', 'keep-me');++ clearLocalStorage();++ expect(localStorage.getItem(`${LocalStorageKeys.FILES_DRAFT}new`)).toBeNull();+ expect(localStorage.getItem(`${LocalStorageKeys.TEXT_DRAFT}new`)).toBeNull();+ expect(localStorage.getItem('unrelated-key')).toBe('keep-me');+ });++ it('drops them even for the pane skipFirst would otherwise spare', () => {+ localStorage.setItem(`${LocalStorageKeys.FILES_DRAFT}new:0`, JSON.stringify({ fileIds: [] }));+ localStorage.setItem(`${LocalStorageKeys.TEXT_DRAFT}new:0`, 'first pane text');++ clearLocalStorage(true);++ expect(localStorage.getItem(`${LocalStorageKeys.FILES_DRAFT}new:0`)).toBeNull();+ expect(localStorage.getItem(`${LocalStorageKeys.TEXT_DRAFT}new:0`)).toBeNull();+ });+});diff --git a/client/src/utils/__tests__/resolvePastedTextFile.spec.ts b/client/src/utils/__tests__/resolvePastedTextFile.spec.tsindex aa614974b0..77921eed8e 100644--- a/client/src/utils/__tests__/resolvePastedTextFile.spec.ts+++ b/client/src/utils/__tests__/resolvePastedTextFile.spec.ts@@ -3,6 +3,8 @@ import type { FileConfig } from 'librechat-data-provider';import {getViableUploadOptions,resolvePastedTextFile,+ isPastedTextFilename,+ nextPastedTextFilename,PASTE_AS_FILE_MIN_LENGTH,PASTED_TEXT_FILENAME,type UploadOptionContext,@@ -200,3 +202,42 @@ describe('resolvePastedTextFile', () => {expect(getOptions).not.toHaveBeenCalled();});});++describe('isPastedTextFilename', () => {+ it('accepts every name the paste flow generates', () => {+ const attachedFilenames = new Set<string>();+ const generated = Array.from({ length: 4 }, () => {+ const name = nextPastedTextFilename(attachedFilenames);+ attachedFilenames.add(name);+ return name;+ });++ expect(generated).toEqual([+ PASTED_TEXT_FILENAME,+ 'pasted-text-2.txt',+ 'pasted-text-3.txt',+ 'pasted-text-4.txt',+ ]);+ expect(generated.every(isPastedTextFilename)).toBe(true);+ /** The counter has no ceiling: a busy composer reaches double digits. */+ expect(isPastedTextFilename('pasted-text-10.txt')).toBe(true);+ });++ it.each([+ ['a deliberate upload that merely mentions pasting', 'my-pasted-text.txt'],+ ['a different extension', 'pasted-text.md'],+ ['a suffix that is not a paste number', 'pasted-text-final.txt'],+ ['a name with the marker in the middle', 'notes-pasted-text.txt'],+ ['a counter the generator never produces', 'pasted-text-1.txt'],+ ['a zero counter the generator never produces', 'pasted-text-0.txt'],+ ['a zero-padded counter the generator never produces', 'pasted-text-02.txt'],+ ['an empty name', ''],+ ])('rejects %s', (_label, filename) => {+ expect(isPastedTextFilename(filename)).toBe(false);+ });++ it('rejects a missing name rather than throwing', () => {+ expect(isPastedTextFilename(undefined)).toBe(false);+ expect(isPastedTextFilename(null)).toBe(false);+ });+});diff --git a/client/src/utils/__tests__/retainedFileDeletions.spec.ts b/client/src/utils/__tests__/retainedFileDeletions.spec.tsnew file mode 100644index 0000000000..6602367323--- /dev/null+++ b/client/src/utils/__tests__/retainedFileDeletions.spec.ts@@ -0,0 +1,155 @@+import { FileSources } from 'librechat-data-provider';++const RETAINED_KEY = 'librechat-retained-file-deletions';++const record = {+ file_id: 'orphan-file',+ embedded: false,+ filepath: '/uploads/user-1/orphan.txt',+ source: FileSources.local,+};++describe('retained file deletions', () => {+ beforeEach(() => {+ jest.resetModules();+ sessionStorage.clear();+ });++ it('persists a retained deletion so a reload can still clean it up', async () => {+ const { retainFileDeletion } = await import('../files');+ retainFileDeletion(record);++ expect(JSON.parse(sessionStorage.getItem(RETAINED_KEY) ?? '[]')).toEqual([record]);+ });++ it('recovers a retained deletion written before the page reloaded', async () => {+ sessionStorage.setItem(RETAINED_KEY, JSON.stringify([record]));++ /** A fresh import stands in for the reload: the module-level map starts empty, so the stored+ * copy is the only thing that still knows the upload needs deleting. */+ const { takeRetainedFileDeletions } = await import('../files');++ expect(takeRetainedFileDeletions()).toEqual([record]);+ });++ it('stops persisting a deletion once it succeeds', async () => {+ const { retainFileDeletion, clearRetainedFileDeletion, takeRetainedFileDeletions } =+ await import('../files');+ retainFileDeletion(record);++ clearRetainedFileDeletion(record.file_id);++ expect(takeRetainedFileDeletions()).toEqual([]);+ expect(sessionStorage.getItem(RETAINED_KEY)).toBeNull();+ });++ it('wakes the retry listeners again after a failed attempt', async () => {+ jest.useFakeTimers();+ try {+ const {+ retainFileDeletion,+ subscribeRetainedFileDeletions,+ scheduleRetainedFileDeletionRetry,+ } = await import('../files');+ retainFileDeletion(record);+ const listener = jest.fn();+ subscribeRetainedFileDeletions(listener);++ scheduleRetainedFileDeletionRetry();+ expect(listener).not.toHaveBeenCalled();++ jest.advanceTimersByTime(5_000);++ expect(listener).toHaveBeenCalledTimes(1);+ } finally {+ jest.useRealTimers();+ }+ });++ it('lets one worker claim the pass and turns the others away', async () => {+ const { beginRetainedDeletionPass, endRetainedDeletionPass } = await import('../files');++ expect(beginRetainedDeletionPass()).toBe(true);+ expect(beginRetainedDeletionPass()).toBe(false);++ endRetainedDeletionPass();++ expect(beginRetainedDeletionPass()).toBe(true);+ });++ it('drops the queue on sign-out so it is never retried as another user', async () => {+ const { retainFileDeletion, clearRetainedFileDeletions, takeRetainedFileDeletions } =+ await import('../files');+ retainFileDeletion(record);++ clearRetainedFileDeletions();++ expect(takeRetainedFileDeletions()).toEqual([]);+ expect(sessionStorage.getItem(RETAINED_KEY)).toBeNull();+ });++ it('ignores a corrupt stored payload rather than failing to load', async () => {+ sessionStorage.setItem(RETAINED_KEY, 'not json');++ const { takeRetainedFileDeletions } = await import('../files');++ expect(takeRetainedFileDeletions()).toEqual([]);+ });++ it('persists submitted paste IDs across reloads', async () => {+ const { markPasteSubmitted, isPasteSubmitted } = await import('../files');+ markPasteSubmitted('submitted-file-id');+ expect(isPasteSubmitted('submitted-file-id')).toBe(true);++ // Simulate reload with a fresh import+ jest.resetModules();+ const reloaded = await import('../files');+ expect(reloaded.isPasteSubmitted('submitted-file-id')).toBe(true);+ expect(reloaded.isPasteSubmitted('other-file-id')).toBe(false);+ });++ it('makes submitted paste IDs readable by another tab', async () => {+ /** The tab that retries a retained deletion is rarely the tab that sent the message. Keeping+ * this evidence in `sessionStorage` left published tab presence as the only cross-tab record,+ * and that ages out on a fixed window, so a retry resuming after it deleted a sent file. */+ const { markPasteSubmitted } = await import('../files');+ markPasteSubmitted('sent-in-another-tab');++ /** A second tab shares `localStorage` and nothing else, so dropping this tab's session is what+ * standing in another tab looks like here. */+ sessionStorage.clear();+ jest.resetModules();+ const otherTab = await import('../files');++ expect(otherTab.isPasteSubmitted('sent-in-another-tab')).toBe(true);+ });++ it('keeps submitted paste IDs however long the deletion work takes', async () => {+ /** The work this evidence has to outlast is a retained deletion, and those carry no expiry of+ * their own, so any interval chosen here could be outlived by a suspended tab still holding+ * cleanup work. It is bounded by count instead of by time. */+ const { markPasteSubmitted, isPasteSubmitted } = await import('../files');+ markPasteSubmitted('long-ago');+ const stored = JSON.parse(+ localStorage.getItem('librechat-submitted-paste-file-ids') ?? '{}',+ ) as Record<string, number>;+ localStorage.setItem(+ 'librechat-submitted-paste-file-ids',+ JSON.stringify({ ...stored, 'long-ago': Date.now() - 2_592_000_000 }),+ );++ expect(isPasteSubmitted('long-ago')).toBe(true);+ });++ it('persists marked pasted text IDs across reloads', async () => {+ const { markPastedTextFile, isPastedTextFileMarked } = await import('../files');+ markPastedTextFile('paste-upload-id');+ expect(isPastedTextFileMarked('paste-upload-id')).toBe(true);++ // Simulate reload with a fresh import+ jest.resetModules();+ const reloaded = await import('../files');+ expect(reloaded.isPastedTextFileMarked('paste-upload-id')).toBe(true);+ expect(reloaded.isPastedTextFileMarked('other-paste-id')).toBe(false);+ });+});diff --git a/client/src/utils/drafts.spec.ts b/client/src/utils/drafts.spec.tsindex a78a9723d2..b951eaaaa3 100644--- a/client/src/utils/drafts.spec.ts+++ b/client/src/utils/drafts.spec.ts@@ -2,24 +2,33 @@ import { Constants, LocalStorageKeys } from 'librechat-data-provider';import {applyPendingPasteToDraft,applyPendingPastesToDraft,+ clearAllDrafts,clearComposerDrafts,decodeBase64,encodeBase64,resolvePendingPasteInsertStart,getComposerDraftId,+ getBrowserTabId,getDraft,getFilesDraft,getNewConversationDraftId,getNewConversationDraftToken,getPendingDraftId,+ isFilesDraftOwnedByThisTab,isNewConversationDraftId,+ isTabLive,+ publishTabAttachmentIds,+ collectLiveAttachmentIds,+ removeTabAttachmentPresence,migrateFilesDraft,migrateTextDraft,renewNewConversationDraftToken,setDraft,setFilesDraft,+ removePendingTextAttachmentDraft,setPendingTextAttachmentDraft,} from './drafts';+import { markPasteSubmitted } from './files';describe('new-conversation draft tokens', () => {it('keeps tokens independent across composer indexes', () => {@@ -271,6 +280,522 @@ describe('pending paste encoding', () => {});});+/** One presence record per tab, matching the store the liveness check reads. */+const markTabLive = (tabId: string, seenAt = Date.now()): void =>+ localStorage.setItem(`librechat-live-tab:${tabId}`, JSON.stringify({ seenAt }));++describe('browser tab ownership of unsaved-chat drafts', () => {+ beforeEach(() => {+ localStorage.clear();+ sessionStorage.clear();+ });++ it('returns a stable id per tab session', () => {+ const first = getBrowserTabId();+ expect(first).toBe(getBrowserTabId());+ });++ it('still attributes a tab when session storage is unusable', () => {+ /** Session storage can be blocked or quota-exhausted while localStorage still works. Returning+ * an empty id left the document unattributed, and every ownership and liveness guard reads+ * that as "no owner", so tabs would destructively clear each other's attachment-backed drafts.+ * An id that lasts only for this document still tells the open tabs apart. */+ const getItem = jest.spyOn(Storage.prototype, 'getItem').mockImplementation((key: string) => {+ if (key === 'librechat-tab-session') {+ throw new Error('session storage blocked');+ }+ return null;+ });++ try {+ expect(getBrowserTabId()).not.toBe('');+ } finally {+ getItem.mockRestore();+ }+ });++ /** jsdom's performance object has no navigation-timing entries at all, so the stub installs+ * the method rather than spying on it. */+ const withNavigationType = (type: string, run: () => void): void => {+ const performanceStub = performance as unknown as {+ getEntriesByType?: (type: string) => PerformanceEntry[];+ };+ const original = performanceStub.getEntriesByType;+ performanceStub.getEntriesByType = () => [{ type } as unknown as PerformanceEntry];+ try {+ run();+ } finally {+ if (original != null) {+ performanceStub.getEntriesByType = original;+ } else {+ delete performanceStub.getEntriesByType;+ }+ }+ };++ it('adopts the stored id when the same tab reloaded', () => {+ sessionStorage.setItem('librechat-tab-session', 'kept-through-reload');+ withNavigationType('reload', () => {+ expect(getBrowserTabId()).toBe('kept-through-reload');+ });+ });++ it('adopts the stored id on back-forward restoration', () => {+ sessionStorage.setItem('librechat-tab-session', 'kept-through-history');+ withNavigationType('back_forward', () => {+ expect(getBrowserTabId()).toBe('kept-through-history');+ });+ });++ it('still mints an id when the browser has no randomUUID', () => {+ /** Insecure origins and older webviews have none, and an empty id would leave every draft+ * unowned and every guard reading another tab's record as its own. */+ const original = crypto.randomUUID;++ (crypto as any).randomUUID = undefined;+ try {+ withNavigationType('navigate', () => {+ const minted = getBrowserTabId();+ expect(minted).not.toBe('');+ expect(minted).toBe(sessionStorage.getItem('librechat-tab-session'));+ });+ } finally {+ (crypto as any).randomUUID = original;+ }+ });++ it('mints a fresh id when storage was inherited by a cloned tab', () => {+ sessionStorage.setItem('librechat-tab-session', 'inherited-from-original');+ withNavigationType('navigate', () => {+ const minted = getBrowserTabId();+ expect(minted).not.toBe('inherited-from-original');+ expect(minted).toBe(sessionStorage.getItem('librechat-tab-session'));+ });+ });++ it('stamps the writing tab on unsaved-chat drafts', () => {+ setFilesDraft(Constants.NEW_CONVO, { fileIds: ['file-1'], pendingPastes: {} });++ expect(getFilesDraft(Constants.NEW_CONVO).tabId).toBe(getBrowserTabId());+ });++ it('stamps conversation drafts too: their key is shared by every tab viewing the chat', () => {+ setFilesDraft('convo-1', { fileIds: ['file-1'], pendingPastes: {} });++ expect(getFilesDraft('convo-1').tabId).toBe(getBrowserTabId());+ });++ it('treats a record owned by an open tab as another tab’s', () => {+ markTabLive('other-tab');++ expect(isFilesDraftOwnedByThisTab({ fileIds: [], pendingPastes: {}, tabId: 'other-tab' })).toBe(+ false,+ );+ });++ it('leaves no attachment claim behind when a rejected upload is removed', () => {+ /** Validation can reject a paste before it ever reaches composer state, and the failure path+ * removes it with `removeFile`. Keeping the id in `pastedTextIds` made the leftover record read+ * as a real attachment claim, and with the file map unchanged nothing would prune it, so the+ * stub locked every other tab out of the shared composer key with no chip behind it. */+ setPendingTextAttachmentDraft({+ id: Constants.NEW_CONVO as string,+ fileId: 'rejected-paste',+ text: 'a'.repeat(30),+ selectionStart: 0,+ });+ setFilesDraft(Constants.NEW_CONVO, {+ ...getFilesDraft(Constants.NEW_CONVO),+ pastedTextIds: ['rejected-paste'],+ });++ removePendingTextAttachmentDraft({+ id: Constants.NEW_CONVO as string,+ fileId: 'rejected-paste',+ removeFile: true,+ });++ const draft = getFilesDraft(Constants.NEW_CONVO);+ expect(draft.fileIds).toEqual([]);+ expect(draft.pastedTextIds ?? []).toEqual([]);+ expect(Object.keys(draft.pendingPastes)).toEqual([]);+ });++ it('reclaims a record whose owning tab has closed', () => {+ /** The tab that stamped it can never present that id again, so holding the claim open would+ * leave the draft unreachable to every tab, for good. */+ expect(+ isFilesDraftOwnedByThisTab({ fileIds: [], pendingPastes: {}, tabId: 'closed-tab' }),+ ).toBe(true);+ });++ it('keeps its claim when the page only enters the back-forward cache', () => {+ /** A bfcached document can come back with those attachments still on screen, so handing the+ * claim over now would let another tab delete the files out from under it. */+ const tabId = getBrowserTabId();+ window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: true }));++ expect(isTabLive(tabId)).toBe(true);+ });++ it('holds a bfcached claim past the ordinary liveness window', () => {+ /** A frozen heartbeat must not read as a dead tab: the document can still come back with+ * those attachments on screen. */+ const tabId = getBrowserTabId();+ window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: true }));+ const parked = JSON.parse(localStorage.getItem(`librechat-live-tab:${tabId}`) ?? '{}');+ localStorage.setItem(+ `librechat-live-tab:${tabId}`,+ JSON.stringify({ ...parked, seenAt: Date.now() - 600_000 }),+ );++ expect(isTabLive(tabId)).toBe(true);+ });++ it('lets a bfcached claim go once even a restorable document would be gone', () => {+ const tabId = 'parked-tab';+ localStorage.setItem(+ `librechat-live-tab:${tabId}`,+ JSON.stringify({ seenAt: Date.now() - 3_600_000, suspended: true }),+ );++ expect(isTabLive(tabId)).toBe(false);+ });++ it('stays live through an ordinary reload rather than releasing mid-bootstrap', () => {+ /** `pagehide` cannot tell a reload from a close, and the id survives a reload on purpose, so+ * releasing here would hand this tab's own draft away while the document was restarting. */+ const tabId = getBrowserTabId();+ window.dispatchEvent(new PageTransitionEvent('pagehide', { persisted: false }));++ expect(isTabLive(tabId)).toBe(true);+ });++ it('lets a closed tab expire through the ordinary window', () => {+ markTabLive('closed-tab', Date.now() - 600_000);++ expect(isTabLive('closed-tab')).toBe(false);+ });++ it('keeps protecting an id after the composer that held it was emptied', () => {+ /** Sending clears the map and the draft, so without a memory of what this tab just held,+ * another tab's backed-off retry would delete a file the sent message now references. */+ publishTabAttachmentIds(0, ['sent-file']);+ publishTabAttachmentIds(0, []);++ expect(collectLiveAttachmentIds().has('sent-file')).toBe(true);+ });++ it('stops protecting an id when it is explicitly removed from presence', () => {+ publishTabAttachmentIds(0, ['discarded-file']);+ expect(collectLiveAttachmentIds().has('discarded-file')).toBe(true);++ removeTabAttachmentPresence(['discarded-file']);+ expect(collectLiveAttachmentIds().has('discarded-file')).toBe(false);+ });++ it("keeps another tab's recent record when withdrawing its own", () => {+ /** Once that tab reattached the file and sent it, its composer and its draft are both empty,+ * so this record is the only thing left protecting the upload. Erasing it here would hand the+ * next retry a file it reads as abandoned and let it delete the upload out of the message that+ * now references it. */+ localStorage.setItem(+ 'librechat-live-tab:other-tab',+ JSON.stringify({ seenAt: Date.now(), recent: { 'shared-file': Date.now() } }),+ );+ publishTabAttachmentIds(0, ['shared-file']);++ removeTabAttachmentPresence(['shared-file']);++ expect(collectLiveAttachmentIds().has('shared-file')).toBe(true);+ expect(collectLiveAttachmentIds({ excludeOwnPane: 'tab' }).has('shared-file')).toBe(true);+ });++ it('keeps a submitted id protected when a later chip of it is removed', () => {+ /** The same file can be sent on one message and reattached afterwards. Removing that later+ * chip is not evidence the file is unused, and once the composer and draft have cleared this+ * entry is the only cross-tab record that a message still references it. */+ markPasteSubmitted('sent-then-reattached');+ publishTabAttachmentIds(0, ['sent-then-reattached']);++ removeTabAttachmentPresence(['sent-then-reattached']);++ expect(collectLiveAttachmentIds().has('sent-then-reattached')).toBe(true);+ });++ it("keeps a sibling pane's chip protected when one pane withdraws", () => {+ /** One tab holds several composers, and the hook that wins the global deletion pass only knows+ * its own pane's file map. Sweeping every pane's entry erased the evidence of a chip the other+ * pane still has on screen, and with draft saving off nothing else recorded it. */+ publishTabAttachmentIds(0, ['shared-across-panes']);+ publishTabAttachmentIds(1, ['shared-across-panes']);++ removeTabAttachmentPresence(['shared-across-panes'], 0);++ expect(collectLiveAttachmentIds().has('shared-across-panes')).toBe(true);+ });++ it("keeps a sibling pane's chip live when withdrawal resumes after liveness expires", () => {+ /** A resumed withdrawal proves the tab is running, just like publishing does. If it rewrites+ * its expired timestamp unchanged, the collection sweep removes the whole record and erases a+ * sibling pane's only claim before cleanup checks what remains on screen. */+ const tabId = getBrowserTabId();+ publishTabAttachmentIds(0, ['resumed-withdrawal']);+ publishTabAttachmentIds(1, ['resumed-withdrawal']);+ const presence = JSON.parse(localStorage.getItem(`librechat-live-tab:${tabId}`) ?? '{}');+ localStorage.setItem(+ `librechat-live-tab:${tabId}`,+ JSON.stringify({ ...presence, seenAt: Date.now() - 600_000 }),+ );++ removeTabAttachmentPresence(['resumed-withdrawal'], 0);++ expect(collectLiveAttachmentIds({ excludeOwnPane: 0 }).has('resumed-withdrawal')).toBe(true);+ });++ it("reports a sibling pane's chip as claimed elsewhere", () => {+ /** Excluding the whole tab hid the other composer, so the pane doing the discarding deleted a+ * file the sibling still had on screen. Side-by-side panes are as independent here as separate+ * tabs; only the discarding pane's own entry is left out. */+ publishTabAttachmentIds(0, ['pane-0-file']);+ publishTabAttachmentIds(1, ['pane-1-file']);++ const claimed = collectLiveAttachmentIds({ excludeOwnPane: 0 });++ expect(claimed.has('pane-1-file')).toBe(true);+ expect(claimed.has('pane-0-file')).toBe(false);+ });++ it('refreshes liveness when a resumed tab publishes an attachment', () => {+ /** Publishing is a user-visible act, so it proves the tab is running. Rewriting the record+ * with its expired seenAt left a resumed tab looking dead until its next interval tick, long+ * enough for another tab's cleanup to delete the file under the chip just added. */+ const tabId = getBrowserTabId();+ publishTabAttachmentIds(0, ['first-file']);+ const presence = JSON.parse(localStorage.getItem(`librechat-live-tab:${tabId}`) ?? '{}');+ localStorage.setItem(+ `librechat-live-tab:${tabId}`,+ JSON.stringify({ ...presence, seenAt: Date.now() - 600_000 }),+ );++ publishTabAttachmentIds(0, ['first-file', 'just-added']);++ expect(isTabLive(tabId)).toBe(true);+ expect(collectLiveAttachmentIds().has('just-added')).toBe(true);+ });++ it('keeps its own published ids through a heartbeat that resumes past the window', () => {+ /** Timers pause while the machine sleeps, so a live tab can beat again with its own record+ * already stale. Sweeping before reading it published an empty presence, and nothing would+ * republish it because the file map had not changed. */+ const tabId = getBrowserTabId();+ publishTabAttachmentIds(0, ['on-screen-file']);+ const presence = JSON.parse(localStorage.getItem(`librechat-live-tab:${tabId}`) ?? '{}');+ localStorage.setItem(+ `librechat-live-tab:${tabId}`,+ JSON.stringify({ ...presence, seenAt: Date.now() - 600_000 }),+ );++ window.dispatchEvent(new PageTransitionEvent('pageshow', { persisted: false }));++ expect(collectLiveAttachmentIds().has('on-screen-file')).toBe(true);+ });++ it('forgets a held id once the window has passed', () => {+ const tabId = getBrowserTabId();+ publishTabAttachmentIds(0, ['old-file']);+ const presence = JSON.parse(localStorage.getItem(`librechat-live-tab:${tabId}`) ?? '{}');+ localStorage.setItem(+ `librechat-live-tab:${tabId}`,+ JSON.stringify({+ ...presence,+ attachments: {},+ recent: { 'old-file': Date.now() - 900_000 },+ }),+ );++ expect(collectLiveAttachmentIds().has('old-file')).toBe(false);+ });++ it('does not drop another tab when both record a heartbeat', () => {+ /** One shared map meant two tabs could read the same snapshot and write back rival copies,+ * and the loser vanished until its next beat: long enough to look abandoned. */+ markTabLive('other-tab');+ const ownId = getBrowserTabId();++ expect(isTabLive('other-tab')).toBe(true);+ expect(isTabLive(ownId)).toBe(true);+ });++ it('reclaims a record whose owning tab stopped reporting long ago', () => {+ markTabLive('crashed-tab', Date.now() - 600_000);++ expect(+ isFilesDraftOwnedByThisTab({ fileIds: [], pendingPastes: {}, tabId: 'crashed-tab' }),+ ).toBe(true);+ });++ it('restamps a written record when the tab that claimed it is gone', () => {+ setFilesDraft(Constants.NEW_CONVO, {+ fileIds: ['file-1'],+ pendingPastes: {},+ tabId: 'closed-tab',+ });++ expect(getFilesDraft(Constants.NEW_CONVO).tabId).toBe(getBrowserTabId());+ });++ it('leaves the claim alone when the tab that made it is still open', () => {+ markTabLive('other-tab');+ setFilesDraft(Constants.NEW_CONVO, {+ fileIds: ['file-1'],+ pendingPastes: {},+ tabId: 'other-tab',+ });++ expect(getFilesDraft(Constants.NEW_CONVO).tabId).toBe('other-tab');+ });++ it('claims a shared composer key from a text draft with no attachment', () => {+ /** Ownership rides on the files record, which is only written once something is attached, so+ * a typed-but-unattached draft used to read as nobody's and be cleared by another tab. */+ setDraft({ id: getNewConversationDraftId(), value: 'queued follow-up' });++ expect(getFilesDraft(getNewConversationDraftId()).tabId).toBe(getBrowserTabId());+ });++ it('gives the shared key back when the text is cleared and nothing is attached', () => {+ /** Otherwise the empty claim outlives the draft and locks the key to a tab that has nothing+ * in it, leaving the next tab unable to restore its own text. */+ setDraft({ id: getNewConversationDraftId(), value: 'queued follow-up' });++ setDraft({ id: getNewConversationDraftId(), value: '' });++ expect(getFilesDraft(getNewConversationDraftId()).tabId).toBeUndefined();+ });++ it('keeps saving the owner’s own text once its draft has an attachment', () => {+ /** The refusal is about other tabs. Applying it to the owner would silently stop the+ * composer saving anything typed after the first file was attached. */+ setFilesDraft(getNewConversationDraftId(), { fileIds: ['my-file'], pendingPastes: {} });++ setDraft({ id: getNewConversationDraftId(), value: 'typed after attaching' });++ expect(getDraft(getNewConversationDraftId())).toBe('typed after attaching');+ });++ it('keeps the claim when clearing the text leaves an attachment behind', () => {+ setFilesDraft(getNewConversationDraftId(), { fileIds: ['file-1'], pendingPastes: {} });+ setDraft({ id: getNewConversationDraftId(), value: 'queued follow-up' });++ setDraft({ id: getNewConversationDraftId(), value: '' });++ expect(getFilesDraft(getNewConversationDraftId()).tabId).toBe(getBrowserTabId());+ });++ it('takes a text-only claim from another tab, whose text it is overwriting anyway', () => {+ /** The shared text record has no per-tab copy: once this tab writes, its text is the only+ * text there is, so a stamp left with the other tab would stop it restoring its own draft. */+ markTabLive('other-tab');+ localStorage.setItem(+ `${LocalStorageKeys.FILES_DRAFT}${getNewConversationDraftId()}`,+ JSON.stringify({ fileIds: [], tabId: 'other-tab' }),+ );++ setDraft({ id: getNewConversationDraftId(), value: 'text from this tab' });++ expect(getFilesDraft(getNewConversationDraftId()).tabId).toBe(getBrowserTabId());+ });++ it('leaves a claim backed by an attachment with the tab that still has it', () => {+ markTabLive('other-tab');+ setFilesDraft(getNewConversationDraftId(), {+ fileIds: ['other-tab-file'],+ pendingPastes: {},+ tabId: 'other-tab',+ });++ setDraft({ id: getNewConversationDraftId(), value: 'text from this tab' });++ expect(getFilesDraft(getNewConversationDraftId()).tabId).toBe('other-tab');+ });++ it('does not overwrite the text of a tab whose attachment claim it could not take', () => {+ /** This tab could not restore what it wrote anyway, so writing would destroy the other+ * tab's text for nothing. */+ markTabLive('other-tab');+ setFilesDraft(getNewConversationDraftId(), {+ fileIds: ['other-tab-file'],+ pendingPastes: {},+ tabId: 'other-tab',+ });+ localStorage.setItem(+ `${LocalStorageKeys.TEXT_DRAFT}${getNewConversationDraftId()}`,+ encodeBase64('text the other tab is still writing'),+ );++ setDraft({ id: getNewConversationDraftId(), value: 'text from this tab' });++ expect(getDraft(getNewConversationDraftId())).toBe('text the other tab is still writing');+ });++ it('refuses to overwrite a conversation draft another tab holds with attachments', () => {+ /** A conversation key is reachable from every tab viewing that chat and is stamped the same+ * way, so the text guard cannot be limited to the shared composer keys. */+ markTabLive('other-tab');+ setFilesDraft('convo-1', {+ fileIds: ['other-tab-file'],+ pendingPastes: {},+ tabId: 'other-tab',+ });+ localStorage.setItem(+ `${LocalStorageKeys.TEXT_DRAFT}convo-1`,+ encodeBase64('text the other tab is still writing'),+ );++ setDraft({ id: 'convo-1', value: 'text from this tab' });++ expect(getDraft('convo-1')).toBe('text the other tab is still writing');+ });++ it('does not claim a conversation key, which tabs are meant to share', () => {+ setDraft({ id: 'convo-1', value: 'shared conversation text' });++ expect(getFilesDraft('convo-1').tabId).toBeUndefined();+ });++ it('refuses to clear a shared key another live tab holds with text alone', () => {+ /** `claimComposerDraftTab` stamps a key that holds nothing but text, and the attachment-backed+ * guard ignored that: tab A finishing a run that began as an unsaved chat cleared the shared+ * new-chat key and took tab B's half-written message with it. Overwriting that text is still a+ * normal race between panes; destroying the record is not. Written the way that claim is,+ * since `setFilesDraft` drops a record with nothing attached rather than leaving a stub. */+ markTabLive('other-tab');+ localStorage.setItem(+ `${LocalStorageKeys.FILES_DRAFT}${Constants.NEW_CONVO}`,+ JSON.stringify({ fileIds: [], tabId: 'other-tab' }),+ );+ localStorage.setItem(+ `${LocalStorageKeys.TEXT_DRAFT}${Constants.NEW_CONVO}`,+ encodeBase64('text the other tab is still writing'),+ );++ clearAllDrafts(Constants.NEW_CONVO);++ expect(getDraft(Constants.NEW_CONVO)).toBe('text the other tab is still writing');+ });++ it('keeps the original tab owner when another tab rewrites the same record', () => {+ setFilesDraft(Constants.NEW_CONVO, { fileIds: ['file-1'], pendingPastes: {} });+ const stamped = getFilesDraft(Constants.NEW_CONVO).tabId;++ sessionStorage.clear();+ setFilesDraft(Constants.NEW_CONVO, { fileIds: ['file-1'], pendingPastes: {} });++ expect(getFilesDraft(Constants.NEW_CONVO).tabId).toBe(stamped);+ });+});+describe('migrateFilesDraft', () => {beforeEach(() => {localStorage.clear();diff --git a/client/src/utils/drafts.ts b/client/src/utils/drafts.tsindex a0eb063b2a..2191c15d03 100644--- a/client/src/utils/drafts.ts+++ b/client/src/utils/drafts.ts@@ -1,5 +1,6 @@import debounce from 'lodash/debounce';import { Constants, LocalStorageKeys } from 'librechat-data-provider';+import { isPasteSubmitted } from './files';export type PendingTextAttachmentDraft = {text: string;@@ -16,6 +17,15 @@ export type PendingTextAttachmentDraft = {export type FilesDraft = {fileIds: string[];pendingPastes: Record<string, PendingTextAttachmentDraft>;+ /** Paste-generated attachment ids, kept after `pendingPastes` is consumed so provenance+ * survives reloads without holding the (much larger) paste text indefinitely. */+ pastedTextIds?: string[];+ /** The browser tab that first wrote the draft. Every draft key is reachable from more than+ * one tab (the unsaved-chat key by every default composer, a conversation key by every tab+ * viewing it), so destructive actions read this to leave other tabs' composers alone.+ * Later rewrites, including another tab restoring the same record, keep this owner rather+ * than restamping. Undefined on records older than the stamp. */+ tabId?: string;};type StoredPendingTextAttachmentDraft = {@@ -32,6 +42,8 @@ type StoredPendingTextAttachmentDraft = {type StoredFilesDraft = {fileIds: string[];pendingPastes: Record<string, StoredPendingTextAttachmentDraft>;+ pastedTextIds?: string[];+ tabId?: string;};const newConversationDraftTokens = new Map<number, symbol>();@@ -63,6 +75,15 @@ export const isNewConversationDraftId = (id?: string | null): boolean =>typeof id === 'string' &&(id === Constants.NEW_CONVO || id.startsWith(`${Constants.NEW_CONVO}:`));+export const isPendingDraftId = (id?: string | null): boolean =>+ typeof id === 'string' &&+ (id === Constants.PENDING_CONVO || id.startsWith(`${Constants.PENDING_CONVO}:`));++/** Keys every tab's default composer reaches, rather than one conversation's own draft. These are+ * the records a destructive action has to check an owner for. */+export const isSharedComposerDraftId = (id?: string | null): boolean =>+ isNewConversationDraftId(id) || isPendingDraftId(id);+export const getConversationDraftId = (index = 0, conversationId?: string | null): string =>conversationId == null || conversationId === '' || conversationId === Constants.NEW_CONVO? getNewConversationDraftId(index)@@ -268,12 +289,22 @@ const removeLocalStorageItem = (key: string): void => {};export const clearDraft = debounce((id?: string | null) => {- removeLocalStorageItem(`${LocalStorageKeys.TEXT_DRAFT}${id ?? ''}`);+ const key = id ?? '';+ if (!mayClearComposerDrafts(key)) {+ return;+ }+ removeLocalStorageItem(`${LocalStorageKeys.TEXT_DRAFT}${key}`);}, 2500);-/** Synchronously removes both text and file drafts for a conversation (or NEW_CONVO fallback) */+/** Synchronously removes both text and file drafts for a conversation (or NEW_CONVO fallback).+ * A record another live tab owns is left alone, attachment or not: every key here is reachable+ * from more than one tab, and clearing one would take that tab's unsent text and its attachment+ * recovery with it. */export const clearAllDrafts = (conversationId?: string | null) => {const key = conversationId || Constants.NEW_CONVO;+ if (!mayClearComposerDrafts(key)) {+ return;+ }removeLocalStorageItem(`${LocalStorageKeys.TEXT_DRAFT}${key}`);removeLocalStorageItem(`${LocalStorageKeys.FILES_DRAFT}${key}`);};@@ -376,22 +407,507 @@ export const getFilesDraft = (id: string): FilesDraft => {return {fileIds: Array.isArray(storedDraft.fileIds) ? storedDraft.fileIds : [],pendingPastes,+ pastedTextIds: Array.isArray(storedDraft.pastedTextIds) ? storedDraft.pastedTextIds : [],+ tabId: typeof storedDraft.tabId === 'string' ? storedDraft.tabId : undefined,};} catch {return { fileIds: [], pendingPastes: {} };}};+const TAB_SESSION_STORAGE_KEY = 'librechat-tab-session';++let documentTabId: string | null = null;++/** Identifies this browser tab for the session. `sessionStorage` is per-tab and survives that+ * tab's reloads, which is exactly the ownership an unsaved-chat draft needs: the draft key is+ * shared through `localStorage` by every tab's default composer, while the composer that owns+ * the record stays identifiable.+ *+ * One caveat decides the shape below: duplicated and opener-created tabs start with a COPY of+ * the original's `sessionStorage`, so a stored id on its own proves nothing. Reload of the same+ * document legitimately keeps it, and so does Back/Forward after the document was evicted from+ * the back-forward cache (Navigation Timing reports `back_forward`, not `reload`). Every other+ * entry into a document mints a fresh id, because an inherited one would attribute another+ * tab's live drafts to this composer. */+/** `crypto.randomUUID` is missing on insecure origins and in older webviews, and letting that+ * throw would leave the tab with no identity at all: every draft would be written unowned and+ * every guard here would read another tab's record as its own. The id only has to tell tabs+ * apart, never resist guessing, so any unique-enough value serves. */+const mintTabId = (): string => {+ if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {+ try {+ return crypto.randomUUID();+ } catch {+ // Fall through to the local mint.+ }+ }+ if (typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function') {+ const bytes = crypto.getRandomValues(new Uint8Array(16));+ return Array.from(bytes, (byte) => byte.toString(16).padStart(2, '0')).join('');+ }+ return `tab-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 12)}`;+};++const resolveBrowserTabId = (): string => {+ try {+ const stored = sessionStorage.getItem(TAB_SESSION_STORAGE_KEY);+ if (documentTabId != null && stored === documentTabId) {+ return documentTabId;+ }+ const navigationType =+ typeof performance.getEntriesByType === 'function'+ ? performance.getEntriesByType('navigation')[0]?.type+ : undefined;+ if (+ stored != null &&+ stored !== '' &&+ (navigationType === 'reload' || navigationType === 'back_forward')+ ) {+ documentTabId = stored;+ return stored;+ }+ documentTabId = mintTabId();+ sessionStorage.setItem(TAB_SESSION_STORAGE_KEY, documentTabId);+ return documentTabId;+ } catch {+ /** Session storage can be blocked or full while `localStorage` still works. Returning '' here+ * gave the document no identity at all, and every ownership and liveness guard reads '' as+ * unattributed, so tabs would overwrite and destructively clear each other's attachment-backed+ * drafts. An id that lives only for this document still tells the open tabs apart; all that is+ * lost is recognising itself after a reload. */+ documentTabId = documentTabId ?? mintTabId();+ return documentTabId;+ }+};++/** `suspended` marks a document sitting in the back-forward cache: frozen rather than gone.+ * `attachments` is what that tab's composers currently hold, per pane, so cleanup running in one+ * tab can see what another has on screen even when nothing was written to a draft. */+type TabPresence = {+ seenAt: number;+ suspended?: boolean;+ attachments?: Record<string, string[]>;+ /** Ids this tab held recently, kept for a while after they leave the composer. Sending a+ * message empties the map and clears the draft, so without this a file reattached here and+ * then sent would go unprotected between another tab's retries and be deleted out of the+ * message that now references it. A retry that sees one cancels its record for good, so the+ * window only has to outlast that tab's backoff. */+ recent?: Record<string, number>;+};+type StoredTabPresence = {+ seenAt?: number;+ suspended?: boolean;+ attachments?: unknown;+ recent?: unknown;+};++const RECENT_ATTACHMENT_WINDOW_MS = 600_000;++/** One key per tab, never a shared map. Two tabs beating at the same time would otherwise read+ * the same registry and write back rival snapshots, and the loser of that race disappears until+ * its next beat, long enough for another tab to treat its live draft as abandoned. */+const TAB_PRESENCE_KEY_PREFIX = 'librechat-live-tab:';+const TAB_HEARTBEAT_MS = 10_000;+/** A hidden tab has its timers throttled to roughly one tick a minute, so the gap between two+ * heartbeats of a perfectly healthy background composer is far wider than the interval asks for.+ * The window has to clear that comfortably, or a backgrounded tab would have its own draft taken+ * away from it. Losing a closed tab's claim a couple of minutes late costs nothing; taking a live+ * tab's draft costs the text it was still writing. */+const TAB_LIVENESS_WINDOW_MS = 150_000;+/** A bfcached document's heartbeat is frozen, so the ordinary window would expire a tab that can+ * still be restored with those attachments on screen, and another tab could delete the files+ * underneath it. It gets a far longer grace, comfortably past the point where browsers evict a+ * bfcache entry, but still a bounded one: a claim that never expired is exactly what left drafts+ * stranded under owners that no longer existed. */+const TAB_SUSPENDED_WINDOW_MS = 1_800_000;++const isPresenceLive = (presence: TabPresence, now: number): boolean =>+ now - presence.seenAt <=+ (presence.suspended === true ? TAB_SUSPENDED_WINDOW_MS : TAB_LIVENESS_WINDOW_MS);++const toAttachments = (value: unknown): Record<string, string[]> | undefined => {+ if (value == null || typeof value !== 'object' || Array.isArray(value)) {+ return undefined;+ }+ const attachments: Record<string, string[]> = {};+ for (const [pane, ids] of Object.entries(value as Record<string, unknown>)) {+ if (Array.isArray(ids)) {+ attachments[pane] = ids.filter((id): id is string => typeof id === 'string');+ }+ }+ return attachments;+};++const toRecent = (value: unknown): Record<string, number> | undefined => {+ if (value == null || typeof value !== 'object' || Array.isArray(value)) {+ return undefined;+ }+ const recent: Record<string, number> = {};+ for (const [id, seenAt] of Object.entries(value as Record<string, unknown>)) {+ if (typeof seenAt === 'number') {+ recent[id] = seenAt;+ }+ }+ return recent;+};++const readTabPresence = (tabId: string): TabPresence | null => {+ try {+ const raw = localStorage.getItem(`${TAB_PRESENCE_KEY_PREFIX}${tabId}`);+ if (raw == null || raw === '') {+ return null;+ }+ const parsed = JSON.parse(raw) as StoredTabPresence | null;+ if (parsed == null || typeof parsed.seenAt !== 'number') {+ return null;+ }+ return {+ seenAt: parsed.seenAt,+ suspended: parsed.suspended === true,+ attachments: toAttachments(parsed.attachments),+ recent: toRecent(parsed.recent),+ };+ } catch {+ return null;+ }+};++const writeTabPresence = (tabId: string, presence: TabPresence): void => {+ try {+ localStorage.setItem(`${TAB_PRESENCE_KEY_PREFIX}${tabId}`, JSON.stringify(presence));+ } catch {+ // A tab that cannot record a heartbeat reads as gone, which only ever releases its claims.+ }+};++/** Every tab still reporting, dropping the records of those that stopped so the store cannot grow+ * an entry for every tab the browser has ever opened. */+const readLiveTabs = (): Map<string, TabPresence> => {+ const live = new Map<string, TabPresence>();+ try {+ const now = Date.now();+ const expired: string[] = [];+ for (let i = 0; i < localStorage.length; i++) {+ const key = localStorage.key(i);+ if (key == null || !key.startsWith(TAB_PRESENCE_KEY_PREFIX)) {+ continue;+ }+ const tabId = key.slice(TAB_PRESENCE_KEY_PREFIX.length);+ const presence = readTabPresence(tabId);+ if (presence == null || !isPresenceLive(presence, now)) {+ expired.push(key);+ continue;+ }+ live.set(tabId, presence);+ }+ for (const key of expired) {+ localStorage.removeItem(key);+ }+ } catch {+ // An unreadable store just means no other tab can be proven live.+ }+ return live;+};++/** Marks this tab as present. Only ever writes this tab's own key, so concurrent beats cannot+ * overwrite one another. */+const recordTabPresence = (tabId: string, suspended = false): void => {+ /** Read before sweeping, never after. Timers pause while the machine sleeps, so a perfectly+ * live tab can come back with its own record already past the liveness window; letting the+ * sweep reap it first and then rewriting from nothing published an empty presence, and because+ * the file map had not changed there was nothing to make `useAutoSave` republish it. Another+ * tab's retry would then see no claim on chips this one still has on screen. */+ const existing = readTabPresence(tabId);+ /** The beat is the only thing guaranteed to run, so it is where the sweep belongs. Hanging it+ * off cleanup meant a profile that never had a failed deletion accumulated a record for every+ * tab it had ever opened, until the origin quota ran out and draft writes began failing. */+ readLiveTabs();+ writeTabPresence(tabId, {+ seenAt: Date.now(),+ ...(suspended ? { suspended: true } : {}),+ ...(existing?.attachments != null ? { attachments: existing.attachments } : {}),+ ...(existing?.recent != null ? { recent: existing.recent } : {}),+ });+};++/** Publishes what a composer is holding right now, so cleanup in another tab can see attachments+ * that never reached a draft: with draft saving off nothing is written at all, and a reattached+ * file would otherwise look like nobody's. */+export const publishTabAttachmentIds = (index: number, ids: string[]): void => {+ const tabId = getBrowserTabId();+ if (tabId === '') {+ return;+ }+ const now = Date.now();+ const existing = readTabPresence(tabId);+ const attachments = { ...(existing?.attachments ?? {}) };+ if (ids.length === 0) {+ delete attachments[index];+ } else {+ attachments[index] = ids;+ }+ const recent: Record<string, number> = {};+ for (const [id, seenAt] of Object.entries(existing?.recent ?? {})) {+ if (now - seenAt <= RECENT_ATTACHMENT_WINDOW_MS) {+ recent[id] = seenAt;+ }+ }+ for (const id of ids) {+ recent[id] = now;+ }+ /** Publishing is a user-visible act, so it is proof this tab is running right now. Carrying the+ * old `seenAt` over meant a tab whose timers had been paused past the liveness window published+ * a chip and stayed expired until its next interval tick, long enough for another tab's cleanup+ * to sweep the record and delete the file under the chip that had just appeared. A document+ * publishing attachments is also plainly not frozen in the back-forward cache. */+ writeTabPresence(tabId, {+ seenAt: now,+ ...(Object.keys(attachments).length > 0 ? { attachments } : {}),+ ...(Object.keys(recent).length > 0 ? { recent } : {}),+ });+};++/** Withdraws attachment ids from this tab's own presence, so a chip that left a composer stops+ * reading as live. A discarded or deleted file otherwise keeps its `recent` entry for the whole+ * window, and the retry sweep reads that as evidence the file was reattached: it cancels its own+ * cleanup and leaves the failed upload orphaned on the server.+ *+ * Strictly this tab's record, never another's. A second tab that reattached the same file and then+ * sent it has an empty composer and an empty draft, so its `recent` entry is the only thing left+ * protecting the file; erasing that here would hand the next retry a file it reads as abandoned+ * and let it delete the upload out of the message that now references it. The withdrawing tab is+ * always the one that published what it is withdrawing, so its own record is all it needs.+ *+ * `index` narrows that further to the one pane doing the withdrawing. One tab holds several+ * composers, and the hook that wins the global deletion pass only knows its own `files` map, so+ * sweeping every pane's entry would erase the evidence of a chip a sibling pane still has on+ * screen. Omitted only by callers that speak for the whole tab. */+export const removeTabAttachmentPresence = (ids: string[], index?: number): void => {+ if (ids.length === 0) {+ return;+ }+ const tabId = getBrowserTabId();+ if (tabId === '') {+ return;+ }+ const presence = readTabPresence(tabId);+ if (presence == null) {+ return;+ }+ const idSet = new Set(ids);+ let modified = false;+ const attachments = { ...presence.attachments };+ for (const [pane, paneIds] of Object.entries(attachments)) {+ if (index != null && pane !== `${index}`) {+ continue;+ }+ const kept = paneIds.filter((id) => !idSet.has(id));+ if (kept.length === paneIds.length) {+ continue;+ }+ if (kept.length === 0) {+ delete attachments[pane];+ } else {+ attachments[pane] = kept;+ }+ modified = true;+ }+ /** Whatever any pane of this tab still shows stays protected: `recent` is one flat map for the+ * whole tab, so withdrawing an id a sibling pane is still holding would drop the only record of+ * it when draft saving is off. */+ const heldElsewhere = new Set(Object.values(attachments).flat());+ const recent = { ...presence.recent };+ for (const id of idSet) {+ if (recent[id] == null || heldElsewhere.has(id)) {+ continue;+ }+ /** A chip leaving is not evidence the file is unused: this tab may have sent the same file on+ * an earlier message and only now be removing a later reattachment of it. The `recent` entry+ * is the only cross-tab record of that submitted use once the composer and draft have cleared,+ * so an id a submission already consumed keeps its entry and ages out on the ordinary window+ * instead of being withdrawn here. */+ if (isPasteSubmitted(id)) {+ continue;+ }+ delete recent[id];+ modified = true;+ }+ if (!modified) {+ return;+ }+ /** Withdrawing is a user-visible act, so it proves this tab is running right now. A suspended+ * document is not withdrawing anything. Carrying the old `seenAt` over would let the collection+ * sweep remove this record immediately, including claims from sibling panes still on screen. */+ writeTabPresence(tabId, {+ seenAt: Date.now(),+ ...(Object.keys(attachments).length > 0 ? { attachments } : {}),+ ...(Object.keys(recent).length > 0 ? { recent } : {}),+ });+};++/** Every attachment id a live tab's composers are currently showing, or held recently enough to+ * still count.+ *+ * `excludeOwnPane` is how a discard asks what everyone *else* is holding. It cannot count its own+ * pane, because that pane's chips are precisely what it is discarding, and it cannot count this+ * tab's `recent` either, since that map is flat and cannot say which pane an id came from. Every+ * other pane of this tab does count: side-by-side composers are as independent as separate tabs+ * here, and excluding the whole tab deleted files out from under a sibling pane's live chip.+ * Pass `'tab'` when the caller speaks for the tab as a whole rather than one pane. */+export const collectLiveAttachmentIds = ({+ excludeOwnPane,+}: { excludeOwnPane?: number | 'tab' } = {}): Set<string> => {+ const ids = new Set<string>();+ const now = Date.now();+ const ownTabId = excludeOwnPane === undefined ? '' : getBrowserTabId();+ for (const [tabId, presence] of readLiveTabs()) {+ const isOwnTab = ownTabId !== '' && tabId === ownTabId;+ if (isOwnTab && excludeOwnPane === 'tab') {+ continue;+ }+ for (const [pane, paneIds] of Object.entries(presence.attachments ?? {})) {+ if (isOwnTab && pane === `${excludeOwnPane}`) {+ continue;+ }+ for (const id of paneIds) {+ ids.add(id);+ }+ }+ if (isOwnTab) {+ continue;+ }+ for (const [id, seenAt] of Object.entries(presence.recent ?? {})) {+ if (now - seenAt <= RECENT_ATTACHMENT_WINDOW_MS) {+ ids.add(id);+ }+ }+ }+ return ids;+};++let heartbeatTimer: ReturnType<typeof setInterval> | null = null;+let heartbeatTabId: string | null = null;++const startTabHeartbeat = (tabId: string): void => {+ if (heartbeatTabId === tabId || typeof window === 'undefined') {+ return;+ }+ heartbeatTabId = tabId;+ recordTabPresence(tabId);+ if (heartbeatTimer != null) {+ return;+ }+ const beat = (): void => {+ if (heartbeatTabId != null) {+ recordTabPresence(heartbeatTabId);+ }+ };+ heartbeatTimer = setInterval(beat, TAB_HEARTBEAT_MS);+ /** `pagehide` cannot tell a close from a reload, and the id deliberately survives a reload, so+ * releasing the claim here would hand this tab's own draft to another one while the document+ * was still bootstrapping. A closed tab is left to the ordinary window instead, which is what+ * the window is for. `persisted` is the one case worth marking: the document is going into the+ * back-forward cache with a frozen heartbeat, so it is parked for the longer grace and beats+ * normally again on `pageshow`. */+ window.addEventListener('pagehide', (event) => {+ if (heartbeatTabId != null && event.persisted) {+ recordTabPresence(heartbeatTabId, true);+ }+ });+ window.addEventListener('pageshow', beat);+};++export const getBrowserTabId = (): string => {+ const tabId = resolveBrowserTabId();+ if (tabId !== '') {+ startTabHeartbeat(tabId);+ }+ return tabId;+};++/** Whether the tab a claim names is still around to act on it. A closed tab's `sessionStorage`+ * goes with it, so its id can never be presented again: without a liveness view its drafts would+ * stay stamped to an owner that no longer exists, and no tab could restore, update, or clean them+ * up again. */+export const isTabLive = (tabId?: string | null): boolean => {+ if (tabId == null || tabId === '') {+ return false;+ }+ if (tabId === documentTabId) {+ return true;+ }+ const presence = readTabPresence(tabId);+ return presence != null && isPresenceLive(presence, Date.now());+};++/** Destructive readers skip a record another tab still owns. Untagged legacy drafts are treated+ * as owned so pre-stamp recovery still deletes and clears, and so is a record whose owning tab+ * has since gone away, which is the only way its draft becomes reachable again. */+export const isFilesDraftOwnedByThisTab = (draft: FilesDraft): boolean =>+ draft.tabId == null || draft.tabId === getBrowserTabId() || !isTabLive(draft.tabId);++let filesDraftCache: { id: string; raw: string | null; draft: FilesDraft } | null = null;++/** Reads a files draft without re-parsing storage when the record has not changed. Paste text can+ * dominate the draft's size, and consumers re-read per file-map change, not per write. */+export const getFilesDraftCached = (id: string): FilesDraft => {+ const raw = getLocalStorageItem(`${LocalStorageKeys.FILES_DRAFT}${id}`);+ if (filesDraftCache != null && filesDraftCache.id === id && filesDraftCache.raw === raw) {+ return filesDraftCache.draft;+ }+ const draft = getFilesDraft(id);+ filesDraftCache = { id, raw, draft };+ return draft;+};++/** Adds a paste-generated file id to a draft's persistent provenance record. */+export const addPastedTextDraftFile = ({ id, fileId }: { id: string; fileId: string }): void => {+ const draft = getFilesDraft(id);+ if (draft.pastedTextIds?.includes(fileId) === true) {+ return;+ }+ setFilesDraft(id, {+ ...draft,+ pastedTextIds: [...(draft.pastedTextIds ?? []), fileId],+ });+};+export const setFilesDraft = (id: string, draft: FilesDraft): void => {const key = `${LocalStorageKeys.FILES_DRAFT}${id}`;const pendingPasteEntries = Object.entries(draft.pendingPastes);- if (draft.fileIds.length === 0 && pendingPasteEntries.length === 0) {+ /** Stamp only the first writer, and only for as long as that writer is still open. A later+ * restore or autosave from another live tab must not steal ownership: that stamp is what keeps+ * Edit / Move back / New Chat from deleting a file the original tab still has attached. Once+ * the owner is gone the claim is worth nothing, so the tab writing now takes it over rather+ * than leaving the record stranded under an id that can never come back. */+ const claimed = draft.tabId ?? getFilesDraft(id).tabId;+ const tabId = (claimed != null && isTabLive(claimed) ? claimed : getBrowserTabId()) || undefined;+ filesDraftCache = null;+ if (+ draft.fileIds.length === 0 &&+ pendingPasteEntries.length === 0 &&+ (draft.pastedTextIds?.length ?? 0) === 0+ ) {removeLocalStorageItem(key);return;}if (pendingPasteEntries.length === 0) {- setLocalStorageItem(key, JSON.stringify(draft.fileIds));+ /** Keep the bare array shape when there is nothing to add, so older readers are unaffected. */+ const bareFileIds = !draft.pastedTextIds?.length && !tabId;+ setLocalStorageItem(+ key,+ JSON.stringify(+ bareFileIds+ ? draft.fileIds+ : {+ fileIds: draft.fileIds,+ ...(draft.pastedTextIds?.length ? { pastedTextIds: draft.pastedTextIds } : {}),+ ...(tabId ? { tabId } : {}),+ },+ ),+ );return;}@@ -424,10 +940,158 @@ export const setFilesDraft = (id: string, draft: FilesDraft): void => {setLocalStorageItem(key,- JSON.stringify({ fileIds: draft.fileIds, pendingPastes } satisfies StoredFilesDraft),+ JSON.stringify({+ fileIds: draft.fileIds,+ pendingPastes,+ ...(draft.pastedTextIds?.length ? { pastedTextIds: draft.pastedTextIds } : {}),+ ...(tabId ? { tabId } : {}),+ } satisfies StoredFilesDraft),);};+/** Every attachment id any persisted composer draft is holding, across every key and therefore+ * every tab: `localStorage` is shared, so a draft another tab wrote for a conversation this one+ * has never opened is still readable here. Cleanup that only consulted this pane's own keys would+ * delete a file a second tab had reattached somewhere else.+ *+ * `excludeIds` leaves out the keys the caller is itself discarding. Those drafts are the reason+ * the deletion exists, so counting them as protection would cancel every discard; every other+ * key, including this tab's own conversation drafts, still counts. */+export const collectDraftedAttachmentIds = (excludeIds: string[] = []): Set<string> => {+ const ids = new Set<string>();+ const excluded = new Set(excludeIds);+ try {+ for (let i = 0; i < localStorage.length; i++) {+ const key = localStorage.key(i);+ if (key == null || !key.startsWith(LocalStorageKeys.FILES_DRAFT)) {+ continue;+ }+ const draftId = key.slice(LocalStorageKeys.FILES_DRAFT.length);+ if (excluded.has(draftId)) {+ continue;+ }+ const draft = getFilesDraft(draftId);+ for (const fileId of draft.fileIds) {+ ids.add(fileId);+ }+ for (const pasteId of draft.pastedTextIds ?? []) {+ ids.add(pasteId);+ }+ for (const pendingId of Object.keys(draft.pendingPastes)) {+ ids.add(pendingId);+ }+ }+ } catch {+ // An unreadable store just means no drafted ids to protect beyond the caller's own.+ }+ return ids;+};++/** Every attachment id something other than the caller still claims: any persisted draft outside+ * the keys it is acting on, plus what every other live tab publishes. Every path that deletes an+ * upload has to consult this first, because a second tab or pane can have reattached the same+ * library file, or sent it, and its claim is the only thing standing between that file and the+ * request. One helper rather than a union rebuilt at each deletion site: the guard was missed at+ * three of them precisely because each site assembled it by hand. */+export const collectForeignAttachmentClaims = (+ excludeDraftIds: string[] = [],+ excludeOwnPane: number | 'tab' = 'tab',+): Set<string> => {+ const ids = collectDraftedAttachmentIds(excludeDraftIds);+ for (const liveId of collectLiveAttachmentIds({ excludeOwnPane })) {+ ids.add(liveId);+ }+ return ids;+};++const hasDraftAttachments = (draft: FilesDraft): boolean =>+ draft.fileIds.length > 0 ||+ Object.keys(draft.pendingPastes).length > 0 ||+ (draft.pastedTextIds?.length ?? 0) > 0;++/** A record another open tab is holding against files it still has on screen. Writing over its+ * text, or clearing it, would destroy a draft this tab could never have restored anyway. */+const isForeignAttachmentClaim = (draft: FilesDraft, tabId: string): boolean =>+ draft.tabId != null &&+ draft.tabId !== tabId &&+ hasDraftAttachments(draft) &&+ isTabLive(draft.tabId);++/** Whether this tab may write the text record behind a draft key. Conversation keys are reachable+ * from every tab viewing that chat and are stamped just like the shared composer ones, so the+ * guard is not limited to those. Only an attachment-backed claim refuses a write: last writer wins+ * for text is deliberate, or the tab that typed last could not restore what it typed. */+export const mayWriteComposerText = (id: string): boolean => {+ const tabId = getBrowserTabId();+ return tabId === '' || !isForeignAttachmentClaim(getFilesDraftCached(id), tabId);+};++/** Any live tab other than this one has the key stamped, whether or not anything is attached. */+const isForeignLiveClaim = (draft: FilesDraft, tabId: string): boolean =>+ draft.tabId != null && draft.tabId !== tabId && isTabLive(draft.tabId);++/** Whether this tab may destroy what is behind a draft key. Stricter than the write guard on+ * purpose: `claimComposerDraftTab` stamps a key that holds nothing but text, and overwriting that+ * text is a normal race between panes, but deleting another live tab's record is not. Tab A+ * finishing a run that began as an unsaved chat would otherwise clear the shared new-chat key and+ * take tab B's half-written message with it, with no attachment anywhere to refuse it. */+export const mayClearComposerDrafts = (id: string): boolean => {+ const tabId = getBrowserTabId();+ return tabId === '' || !isForeignLiveClaim(getFilesDraftCached(id), tabId);+};++/** Records which tab a shared composer key belongs to when text is all it holds. The files draft+ * doubles as the ownership record, but it is only written once there is an attachment, so a typed+ * but unattached draft read as unowned and another tab's New Chat cleared it. */+export const claimComposerDraftTab = (id: string): boolean => {+ /** Reached from every debounced keystroke, so it reads through the cache rather than+ * re-parsing the record each time. */+ const existing = getFilesDraftCached(id);+ const tabId = getBrowserTabId();+ /** Already ours, or storage cannot attribute a tab at all: there is nothing to claim and the+ * write goes ahead. This has to come first, or the owner of an attachment-backed draft would+ * be refused its own key and stop saving what it types. */+ if (existing.tabId === tabId || tabId === '') {+ return true;+ }+ /** A claim with nothing behind it speaks only for text, and the caller is about to overwrite+ * that text on a key every tab writes to: the stamp follows whoever's text is actually stored,+ * or the tab that typed last could not restore what it typed. A claim backed by an attachment+ * stays with its owner while that tab is open, because taking it would let this tab delete+ * files the other one still has on screen. */+ if (isForeignAttachmentClaim(existing, tabId)) {+ return false;+ }+ if (hasDraftAttachments(existing)) {+ setFilesDraft(id, { ...existing, tabId });+ return true;+ }+ /** Nothing but the claim to store. `setFilesDraft` drops an empty record rather than leaving+ * a stub behind, which is right for attachments and wrong for this. */+ filesDraftCache = null;+ setLocalStorageItem(+ `${LocalStorageKeys.FILES_DRAFT}${id}`,+ JSON.stringify({ fileIds: [], tabId }),+ );+ return true;+};++/** Drops a claim with nothing behind it. Once the text is cleared and nothing is attached, the+ * record is pure residue, and leaving it would lock the shared key to a tab that no longer has a+ * draft there: the next tab to type could neither restore its own text nor take the key back. */+export const releaseComposerDraftTab = (id: string): void => {+ const existing = getFilesDraftCached(id);+ if (+ existing.tabId == null ||+ existing.tabId !== getBrowserTabId() ||+ hasDraftAttachments(existing)+ ) {+ return;+ }+ filesDraftCache = null;+ removeLocalStorageItem(`${LocalStorageKeys.FILES_DRAFT}${id}`);+};+/** Moves a text draft between keys, reporting whether there was one to move. */export const migrateTextDraft = (fromId: string, toId: string): boolean => {const key = `${LocalStorageKeys.TEXT_DRAFT}${fromId}`;@@ -494,6 +1158,7 @@ export const setPendingTextAttachmentDraft = ({Math.max(0, ...Object.values(draft.pendingPastes).map((paste) => paste.sequence ?? 0)) + 1;setFilesDraft(id, {fileIds: draft.fileIds.includes(fileId) ? draft.fileIds : [...draft.fileIds, fileId],+ pastedTextIds: draft.pastedTextIds,pendingPastes: {...draft.pendingPastes,[fileId]: {@@ -522,10 +1187,18 @@ export const removePendingTextAttachmentDraft = ({const draft = getFilesDraft(id);const pendingPastes = { ...draft.pendingPastes };delete pendingPastes[fileId];+ /** `removeFile` means the upload never landed or is gone, so its provenance goes with it.+ * Leaving the id in `pastedTextIds` was enough for `hasDraftAttachments` to read the record as a+ * real attachment claim, and since the file map never changed there was no later render to prune+ * it: the stub then locked every other tab out of the shared composer key with no chip behind+ * it. */setFilesDraft(id, {fileIds: removeFile? draft.fileIds.filter((draftFileId) => draftFileId !== fileId): draft.fileIds,+ pastedTextIds: removeFile+ ? draft.pastedTextIds?.filter((pasteId) => pasteId !== fileId)+ : draft.pastedTextIds,pendingPastes,});};@@ -543,10 +1216,31 @@ export const setDraft = ({? value != null && value.length > 0: value && value.length > 1;if (shouldPersist) {+ /** A refused key belongs to another open tab holding it against attachments it still has.+ * This tab could not restore what it wrote there anyway, so the write would only destroy that+ * tab's text for nothing. */+ if (!mayWriteComposerText(id)) {+ return;+ }+ /** Claim before writing, but only where ownership would not otherwise exist: the shared text+ * record has no per-tab copy, so once the write lands this tab's text is the only text there+ * is and the stamp has to agree. A conversation key is left unstamped unless something is+ * actually attached to it, since tabs are meant to share those. */+ if (isSharedComposerDraftId(id)) {+ claimComposerDraftTab(id);+ }setLocalStorageItem(`${LocalStorageKeys.TEXT_DRAFT}${id}`, encodeBase64(value ?? ''));return;}+ /** Stricter than the write path: an empty composer in this tab must not erase text another open+ * tab is still holding, and a tab that has only typed still holds it. */+ if (!mayClearComposerDrafts(id)) {+ return;+ }removeLocalStorageItem(`${LocalStorageKeys.TEXT_DRAFT}${id}`);+ if (isSharedComposerDraftId(id)) {+ releaseComposerDraftTab(id);+ }};export const getDraft = (id?: string): string | null =>diff --git a/client/src/utils/files.ts b/client/src/utils/files.tsindex ba446a6331..462b0145e5 100644--- a/client/src/utils/files.ts+++ b/client/src/utils/files.ts@@ -21,7 +21,14 @@ import {isDocumentSupportedProvider,fileConfig as defaultFileConfig,} from 'librechat-data-provider';-import type { TFile, EndpointFileConfig, FileConfig, RegexLike } from 'librechat-data-provider';+import type {+ TFile,+ DeleteFilesResponse,+ EndpointFileConfig,+ FileConfig,+ FileSources,+ RegexLike,+} from 'librechat-data-provider';import type { QueryClient } from '@tanstack/react-query';import type { ExtendedFile } from '~/common';@@ -494,6 +501,360 @@ export const PASTE_AS_FILE_MIN_LENGTH = 2500;export const PASTED_TEXT_FILENAME = 'pasted-text.txt';+/** Matches every name `nextPastedTextFilename` can produce, and nothing else: the counter+ * starts at the bare name and jumps to 2, so `-0`, `-1`, and zero-padded variants are never+ * generated and must not read as generated. The alternation is "any integer of 2 or more":+ * a single digit 2-9, or two or more digits. */+const PASTED_TEXT_FILENAME_PATTERN = /^pasted-text(-([2-9]|[1-9]\d+))?\.txt$/;++/**+ * Whether a filename is one `nextPastedTextFilename` can produce. Name alone cannot prove an+ * attachment is a paste, though: a user can deliberately upload a file with one of these names.+ * Provenance comes from the paste registry and the files draft, not the name.+ */+export const isPastedTextFilename = (filename?: string | null): boolean =>+ filename != null && PASTED_TEXT_FILENAME_PATTERN.test(filename);++/** Paste provenance is genuinely per-tab: it decides which chips offer the paste affordances, and+ * `sessionStorage` is exactly that scope, surviving this tab's reloads without reaching another.+ * It has to survive a reload or an already-sent paste would be reclassified as unsent, because the+ * files draft it gets restored from does survive. */+const PASTED_TEXT_STORAGE_KEY = 'librechat-pasted-text-file-ids';++const readStoredPasteIds = (key: string): string[] => {+ try {+ const parsed = JSON.parse(sessionStorage.getItem(key) ?? 'null') as unknown;+ return Array.isArray(parsed) ? parsed.filter((id): id is string => typeof id === 'string') : [];+ } catch {+ return [];+ }+};++const persistPasteIds = (key: string, ids: Set<string>): void => {+ try {+ if (ids.size === 0) {+ sessionStorage.removeItem(key);+ return;+ }+ sessionStorage.setItem(key, JSON.stringify(Array.from(ids)));+ } catch {+ // The in-memory copy still drives this session.+ }+};++const pastedTextFileIds = new Set<string>(readStoredPasteIds(PASTED_TEXT_STORAGE_KEY));++/** Records that a file id belongs to a paste the composer generated, so its chip can offer the+ * paste affordances. Persisted per tab, so a reload does not strip those affordances off a chip+ * the autosaved draft restores. */+export const markPastedTextFile = (fileId: string): void => {+ pastedTextFileIds.add(fileId);+ persistPasteIds(PASTED_TEXT_STORAGE_KEY, pastedTextFileIds);+};++export const isPastedTextFileMarked = (fileId?: string | null): boolean =>+ fileId != null && pastedTextFileIds.has(fileId);++/** Submitted-use evidence, unlike paste provenance, has to be readable by every tab and outlive+ * any of them, so it lives in `localStorage` rather than this tab's session.+ *+ * The tab that deletes is rarely the tab that sent. A retained deletion is retried by whichever+ * tab is holding it, possibly long after being frozen and resumed, while the message referencing+ * the file was sent somewhere else entirely. Published tab presence used to be the only cross-tab+ * evidence and it ages out on a ten-minute window, so a retry resuming after that classified a+ * sent file as abandoned and deleted it out of its message.+ *+ * Deliberately not expired on a timer. The work this evidence has to outlast is a retained+ * deletion, and those carry no expiry of their own: any interval chosen here can be outlived by a+ * suspended tab still holding cleanup work, which is the same bug again with a longer fuse. The+ * ledger is bounded by count instead, evicting the oldest entries only when it would otherwise+ * grow without limit, since running out of origin quota would break draft writes for everyone. */+const SUBMITTED_PASTES_STORAGE_KEY = 'librechat-submitted-paste-file-ids';+const SUBMITTED_PASTE_LIMIT = 5000;++type SubmittedPastes = Record<string, number>;++let submittedPastesCache: { raw: string | null; ids: SubmittedPastes } | null = null;++/** Read through a raw-string cache: another tab's write changes the string, so this stays current+ * without re-parsing on every lookup, and lookups happen per file per cleanup pass. */+const readSubmittedPastes = (): SubmittedPastes => {+ let raw: string | null = null;+ try {+ raw = localStorage.getItem(SUBMITTED_PASTES_STORAGE_KEY);+ } catch {+ return submittedPastesCache?.ids ?? {};+ }+ if (submittedPastesCache != null && submittedPastesCache.raw === raw) {+ return submittedPastesCache.ids;+ }+ const ids: SubmittedPastes = {};+ try {+ const parsed = JSON.parse(raw ?? 'null') as unknown;+ if (parsed != null && typeof parsed === 'object' && !Array.isArray(parsed)) {+ for (const [id, seenAt] of Object.entries(parsed as Record<string, unknown>)) {+ if (typeof seenAt === 'number') {+ ids[id] = seenAt;+ }+ }+ }+ } catch {+ // An unreadable record protects nothing, which is the same as having none.+ }+ submittedPastesCache = { raw, ids };+ return ids;+};++/** Records that a paste left the composer on a message. Submitting empties the file map but the+ * draft keeps its provenance, and the run ending (including by Stop or an error) is not evidence+ * the paste is unsent: only this is. Without it, discarding afterwards would delete a file the+ * sent turn already references. */+export const markPasteSubmitted = (fileId?: string | null): void => {+ if (fileId == null || fileId === '') {+ return;+ }+ const ids: SubmittedPastes = { ...readSubmittedPastes(), [fileId]: Date.now() };+ let entries = Object.entries(ids);+ if (entries.length > SUBMITTED_PASTE_LIMIT) {+ entries = entries.sort((a, b) => b[1] - a[1]).slice(0, SUBMITTED_PASTE_LIMIT);+ }+ const bounded = Object.fromEntries(entries);+ try {+ localStorage.setItem(SUBMITTED_PASTES_STORAGE_KEY, JSON.stringify(bounded));+ submittedPastesCache = null;+ } catch {+ /** The write is the protection, so a failure has to be remembered in memory at least: this+ * tab's own cleanup must not turn around and delete what it just sent. */+ submittedPastesCache = { raw: submittedPastesCache?.raw ?? null, ids: bounded };+ }+};++export const isPasteSubmitted = (fileId?: string | null): boolean =>+ fileId != null && fileId !== '' && readSubmittedPastes()[fileId] != null;++/** A file deletion whose request failed, kept with everything needed to retry it: the chip it+ * came from is already gone, so the payload cannot be rebuilt from the composer. */+export type PendingFileDeletion = {+ file_id: string;+ embedded: boolean;+ filepath: string;+ source: FileSources;+};++/** A resolved delete request is not proof the records are gone: the route answers 200 with+ * `failedFileIds` when a storage delete fails, so every caller that cleans up after itself has to+ * read the result rather than only catching a rejection. */+export const failedFileIdsFrom = (result: DeleteFilesResponse | void): string[] =>+ result != null && Array.isArray(result.failedFileIds) ? result.failedFileIds : [];++const RETAINED_DELETION_STORAGE_KEY = 'librechat-retained-file-deletions';+const RETAINED_RETRY_BASE_DELAY_MS = 5_000;+const RETAINED_RETRY_MAX_DELAY_MS = 60_000;++const readStoredRetainedDeletions = (): PendingFileDeletion[] => {+ try {+ const raw = sessionStorage.getItem(RETAINED_DELETION_STORAGE_KEY);+ if (raw == null || raw === '') {+ return [];+ }+ const parsed = JSON.parse(raw) as PendingFileDeletion[] | null;+ return Array.isArray(parsed) ? parsed : [];+ } catch {+ return [];+ }+};++/** Survives a reload: the chip these came from is gone, so once the tab forgets the payload the+ * upload on the server has no reference left at all. */+const retainedFileDeletions = new Map<string, PendingFileDeletion>(+ readStoredRetainedDeletions().map((record) => [record.file_id, record]),+);+const retainedFileDeletionListeners = new Set<() => void>();++const persistRetainedFileDeletions = (): void => {+ try {+ if (retainedFileDeletions.size === 0) {+ sessionStorage.removeItem(RETAINED_DELETION_STORAGE_KEY);+ return;+ }+ sessionStorage.setItem(+ RETAINED_DELETION_STORAGE_KEY,+ JSON.stringify(Array.from(retainedFileDeletions.values())),+ );+ } catch {+ // The in-memory copy still drives this session's retries.+ }+};++const notifyRetainedFileDeletions = (): void => {+ retainedFileDeletionListeners.forEach((listener) => listener());+};++let retainedRetryTimer: ReturnType<typeof setTimeout> | null = null;+let retainedRetryDelayMs = RETAINED_RETRY_BASE_DELAY_MS;+let onlineRetryBound = false;++const bindOnlineRetainedRetry = (): void => {+ if (onlineRetryBound || typeof window === 'undefined') {+ return;+ }+ onlineRetryBound = true;+ window.addEventListener('online', () => {+ retainedRetryDelayMs = RETAINED_RETRY_BASE_DELAY_MS;+ notifyRetainedFileDeletions();+ });+};++/** A retry that fails again changes nothing the cleanup effect depends on, and the files query+ * does not refetch on reconnect, so without an explicit wake-up the payload would sit untouched+ * until some unrelated cache update happened to arrive. Backs off to a slow poll rather than+ * giving up, because giving up is what orphans the upload. */+export const scheduleRetainedFileDeletionRetry = (): void => {+ if (retainedRetryTimer != null) {+ return;+ }+ bindOnlineRetainedRetry();+ retainedRetryTimer = setTimeout(() => {+ retainedRetryTimer = null;+ retainedRetryDelayMs = Math.min(retainedRetryDelayMs * 2, RETAINED_RETRY_MAX_DELAY_MS);+ notifyRetainedFileDeletions();+ }, retainedRetryDelayMs);+};++let retainedPassInFlight = false;++/** The header, sidebar, mobile bar and shortcut hooks each mount the cleanup effect, and the+ * store they read is shared, so without a claim every one of them would issue the same DELETE and+ * toast about it. Only the instance that takes this runs the pass. */+export const beginRetainedDeletionPass = (): boolean => {+ if (retainedPassInFlight) {+ return false;+ }+ retainedPassInFlight = true;+ return true;+};++export const endRetainedDeletionPass = (): void => {+ retainedPassInFlight = false;+};++/** Whether this session may still record deletions. A DELETE that was already in flight when the+ * session ended settles after the queue was dropped, and its handler is the last reference to+ * that payload, so it writes the previous account's records straight back in. The latch is what+ * makes the clear stick: retention reopens only when a session is established again. */+let retentionOpen = true;++/** Drops the queue outright and refuses further records until the next sign-in. The payloads+ * belong to the account that uploaded them, so carrying them across a sign-out would retry+ * another user's credentials against files they do not own, failing the ownership check forever+ * instead of cleaning anything up. */+export const clearRetainedFileDeletions = (): void => {+ retentionOpen = false;+ retainedFileDeletions.clear();+ persistRetainedFileDeletions();+ retainedRetryDelayMs = RETAINED_RETRY_BASE_DELAY_MS;+ if (retainedRetryTimer != null) {+ clearTimeout(retainedRetryTimer);+ retainedRetryTimer = null;+ }+};++/** Reopens retention for a newly established session. Records already in the store are this+ * account's own, carried across a reload by `sessionStorage`, so the queue is left alone. */+export const openFileDeletionRetention = (): void => {+ retentionOpen = true;+};++export const retainFileDeletion = (record: PendingFileDeletion): void => {+ if (!retentionOpen) {+ return;+ }+ retainedFileDeletions.set(record.file_id, record);+ persistRetainedFileDeletions();+ retainedRetryDelayMs = RETAINED_RETRY_BASE_DELAY_MS;+ notifyRetainedFileDeletions();+};++export const clearRetainedFileDeletion = (fileId: string): void => {+ if (!retainedFileDeletions.delete(fileId)) {+ return;+ }+ persistRetainedFileDeletions();+ retainedRetryDelayMs = RETAINED_RETRY_BASE_DELAY_MS;+};++/** The deletions waiting for a retry; ownership stays with the store until one succeeds. */+export const takeRetainedFileDeletions = (): PendingFileDeletion[] =>+ Array.from(retainedFileDeletions.values());++/** Subscribe to a retained deletion being recorded so a retry effect can run without waiting+ * for an unrelated files-cache update. */+export const subscribeRetainedFileDeletions = (listener: () => void): (() => void) => {+ retainedFileDeletionListeners.add(listener);+ return () => {+ retainedFileDeletionListeners.delete(listener);+ };+};++const PENDING_DISCARD_STORAGE_KEY = 'librechat-pending-file-discards';++type PendingDiscardStore = Record<string, string[]>;++const readPendingDiscardStore = (): PendingDiscardStore => {+ try {+ const raw = sessionStorage.getItem(PENDING_DISCARD_STORAGE_KEY);+ if (raw == null || raw === '') {+ return {};+ }+ const parsed: unknown = JSON.parse(raw);+ return parsed != null && typeof parsed === 'object' && !Array.isArray(parsed)+ ? (parsed as PendingDiscardStore)+ : {};+ } catch {+ return {};+ }+};++/** Draft uploads whose records were not yet resolvable when New Chat discarded them. Stored+ * per composer index so a reload or remount can still delete them once the files cache+ * exposes the record. */+export const loadPendingDiscardIds = (index = 0): string[] => {+ const stored = readPendingDiscardStore()[String(index)];+ return Array.isArray(stored) ? stored.filter((id) => typeof id === 'string') : [];+};++const pendingDiscardListeners = new Set<() => void>();++/** Several hooks mount this state against one session store, and an instance that unmounts takes+ * its snapshot with it. Without a notification the remaining ones keep stale lists and the work+ * it deferred is never picked up again. */+export const subscribePendingDiscardIds = (listener: () => void): (() => void) => {+ pendingDiscardListeners.add(listener);+ return () => {+ pendingDiscardListeners.delete(listener);+ };+};++export const storePendingDiscardIds = (index: number, ids: string[]): void => {+ try {+ const store = readPendingDiscardStore();+ if (ids.length === 0) {+ delete store[String(index)];+ } else {+ store[String(index)] = ids;+ }+ if (Object.keys(store).length === 0) {+ sessionStorage.removeItem(PENDING_DISCARD_STORAGE_KEY);+ pendingDiscardListeners.forEach((listener) => listener());+ return;+ }+ sessionStorage.setItem(PENDING_DISCARD_STORAGE_KEY, JSON.stringify(store));+ pendingDiscardListeners.forEach((listener) => listener());+ } catch {+ // Privacy-blocked storage cannot persist deferred discards across reloads.+ }+};+export type PasteAsFileContext = {/** The user's `pasteLongTextAsFile` preference. */enabled: boolean;@@ -511,7 +872,7 @@ export type PasteAsFileContext = {* alone for pastes and reject a second, different paste that merely matched the first one's* length. Numbering keeps every paste attachable while staying readable in the UI.*/-const nextPastedTextFilename = (taken: Set<string>): string => {+export const nextPastedTextFilename = (taken: Set<string>): string => {let candidate = PASTED_TEXT_FILENAME;let suffix = 1;while (taken.has(candidate)) {diff --git a/client/src/utils/localStorage.ts b/client/src/utils/localStorage.tsindex a43838bd3b..1790068921 100644--- a/client/src/utils/localStorage.ts+++ b/client/src/utils/localStorage.ts@@ -24,7 +24,27 @@ export function getLocalStorageItems() {};}+/** Drops every composer draft. These hold whatever the user typed, and a paste held as a file+ * keeps its entire text in the files draft, so they outlive a sign-out and the browser tab keeps+ * its identity across an in-app account switch: the ordinary draft restore could otherwise hand+ * the next account the previous one's writing. Called on the way out of a session rather than only+ * 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() {+ Object.keys(localStorage).forEach((key) => {+ if (+ key.startsWith(LocalStorageKeys.FILES_DRAFT) ||+ key.startsWith(LocalStorageKeys.TEXT_DRAFT)+ ) {+ localStorage.removeItem(key);+ }+ });+}+export function clearLocalStorage(skipFirst?: boolean) {+ /** Ahead of `skipFirst`: that exception exists to preserve the first pane's settings, and a+ * shared browser is no place to make an exception for someone else's writing. */+ clearComposerDraftStorage();const keys = Object.keys(localStorage);keys.forEach((key) => {if (skipFirst === true && key.endsWith('0')) {diff --git a/packages/api/src/files/deletion.spec.ts b/packages/api/src/files/deletion.spec.tsnew file mode 100644index 0000000000..409c1d2f82--- /dev/null+++ b/packages/api/src/files/deletion.spec.ts@@ -0,0 +1,34 @@+import { buildDeleteFilesResponse, PARTIAL_FILE_DELETION_MESSAGE } from './deletion';++describe('delete files response', () => {+ it('reports the caller’s success message when nothing failed', () => {+ expect(+ buildDeleteFilesResponse({ deletedFileIds: ['file-1'], failedFileIds: [] }, 'All gone'),+ ).toEqual({+ message: 'All gone',+ deletedFileIds: ['file-1'],+ failedFileIds: [],+ });+ });++ it('names the partial failure so a 200 is not read as a clean delete', () => {+ expect(+ buildDeleteFilesResponse(+ { deletedFileIds: ['file-1'], failedFileIds: ['file-2'] },+ 'All gone',+ ),+ ).toEqual({+ message: PARTIAL_FILE_DELETION_MESSAGE,+ deletedFileIds: ['file-1'],+ failedFileIds: ['file-2'],+ });+ });++ it('answers with empty lists when there was nothing to delete', () => {+ expect(buildDeleteFilesResponse(undefined, 'All gone')).toEqual({+ message: 'All gone',+ deletedFileIds: [],+ failedFileIds: [],+ });+ });+});diff --git a/packages/api/src/files/deletion.ts b/packages/api/src/files/deletion.tsnew file mode 100644index 0000000000..92f176a23f--- /dev/null+++ b/packages/api/src/files/deletion.ts@@ -0,0 +1,27 @@+import type { DeleteFilesResponse } from 'librechat-data-provider';++/** What a delete pass reports back about the records it was given. */+export type FileDeletionOutcome = {+ deletedFileIds?: string[];+ failedFileIds?: string[];+};++export const PARTIAL_FILE_DELETION_MESSAGE = 'Some files could not be deleted';++/**+ * Shapes the body of a delete response. A record whose storage delete failed is not an error for+ * the request as a whole, so the outcome travels in the body rather than the status: clients read+ * `failedFileIds` to know what is still on disk, and treat everything else they asked for as gone.+ */+export const buildDeleteFilesResponse = (+ result: FileDeletionOutcome | null | undefined,+ successMessage: string,+): DeleteFilesResponse => {+ const deletedFileIds = result?.deletedFileIds ?? [];+ const failedFileIds = result?.failedFileIds ?? [];+ return {+ message: failedFileIds.length > 0 ? PARTIAL_FILE_DELETION_MESSAGE : successMessage,+ deletedFileIds,+ failedFileIds,+ };+};diff --git a/packages/api/src/files/index.ts b/packages/api/src/files/index.tsindex 73bf09e27a..8844750cd6 100644--- a/packages/api/src/files/index.ts+++ b/packages/api/src/files/index.ts@@ -2,6 +2,7 @@ export * from './agents';export * from './audio';export * from './code';export * from './context';+export * from './deletion';export * from './extract';export * from './documents/crud';export * from './encode';diff --git a/packages/data-provider/src/types/files.ts b/packages/data-provider/src/types/files.tsindex 653b504e7f..845a4964cf 100644--- a/packages/data-provider/src/types/files.ts+++ b/packages/data-provider/src/types/files.ts@@ -256,7 +256,9 @@ export type TFilesUsageResponse = {export type DeleteFilesResponse = {message: string;- result: Record<string, unknown>;+ result?: Record<string, unknown>;+ deletedFileIds?: string[];+ failedFileIds?: string[];};export type BatchFile = {@@ -280,4 +282,7 @@ export type DeleteMutationOptions = {onSuccess?: (data: DeleteFilesResponse, variables: DeleteFilesBody, context?: unknown) => void;onMutate?: (variables: DeleteFilesBody) => void | Promise<unknown>;onError?: (error: unknown, variables: DeleteFilesBody, context?: unknown) => void;+ /** Suppresses the result toasts. Background cleanup runs on a timer the user never asked for,+ * and a storage failure that keeps failing would otherwise announce itself on every retry. */+ silent?: boolean;};