Skip to content

Enhanced ChatGPT Clone: Features Agents, MCP, Skills, DeepSeek, Anthropic, AWS, OpenAI, Responses API, Azure, Groq, o1, GPT-5, Mistral, OpenRouter, Vertex AI, Gemini, Artifacts, AI model switching, message search, Code Interpreter, langchain, DALL-E-3, OpenAPI Actions, Functions, Secure Multi-User Auth, Presets, open-source for self-hosting. Active

📓 fix: Keep Typed Text When Starting a New Chat (#15985)

lia-by-librechat[bot]52293e1298f1
diff --git a/client/src/hooks/Chat/__tests__/useNewChat.spec.ts b/client/src/hooks/Chat/__tests__/useNewChat.spec.ts
index ce9df1bb36..82ad2f879d 100644
--- a/client/src/hooks/Chat/__tests__/useNewChat.spec.ts
+++ b/client/src/hooks/Chat/__tests__/useNewChat.spec.ts
@@ -7,6 +7,7 @@ const mockNewConversation = jest.fn();
const mockClearMessagesCache = jest.fn();
const mockInvalidateQueries = jest.fn();
const mockClearAllDrafts = jest.fn();
+const mockClearFilesDraft = jest.fn();
const mockDeleteFiles = jest.fn();
const mockScheduleRetainedRetry = jest.fn();
@@ -78,6 +79,7 @@ jest.mock('~/hooks/useNewConvo', () => ({
jest.mock('~/utils', () => ({
clearMessagesCache: (...args: unknown[]) => mockClearMessagesCache(...args),
clearAllDrafts: (...args: unknown[]) => mockClearAllDrafts(...args),
+ clearFilesDraft: (...args: unknown[]) => mockClearFilesDraft(...args),
getNewConversationDraftId: (index = 0) => (index === 0 ? 'new' : `new:${index}`),
getPendingDraftId: (index = 0) => (index === 0 ? 'pending' : `pending:${index}`),
getComposerDraftId: (index = 0, conversationId?: string | null) => {
@@ -260,26 +262,36 @@ describe('useNewChat', () => {
expect(mockNewConversation).toHaveBeenCalledTimes(1);
});
- it('drops the unsaved-chat draft before the reset restores from it', () => {
+ it('drops the unsaved-chat attachments before the reset restores from them', () => {
const { result } = renderHook(() => useNewChat());
act(() => result.current.startNewChat());
- expect(mockClearAllDrafts).toHaveBeenCalledWith('new');
- expect(mockClearAllDrafts.mock.invocationCallOrder[0]).toBeLessThan(
+ expect(mockClearFilesDraft).toHaveBeenCalledWith('new');
+ expect(mockClearFilesDraft.mock.invocationCallOrder[0]).toBeLessThan(
mockNewConversation.mock.invocationCallOrder[0],
);
});
- it('drops only its own pane unsaved-chat draft', () => {
- const { result } = renderHook(() => useNewChat({ index: 1 }));
+ /** The reset is also how a user gets back to an unsaved chat they typed in and left, and the
+ * restore that puts an unwanted paste back is the same one that puts the message back. */
+ it('keeps what was typed in the unsaved chat', () => {
+ const { result } = renderHook(() => useNewChat());
act(() => result.current.startNewChat());
- expect(mockClearAllDrafts).toHaveBeenCalledWith('new:1');
expect(mockClearAllDrafts).not.toHaveBeenCalledWith('new');
});
+ it('drops only its own pane unsaved-chat attachments', () => {
+ const { result } = renderHook(() => useNewChat({ index: 1 }));
+
+ act(() => result.current.startNewChat());
+
+ expect(mockClearFilesDraft).toHaveBeenCalledWith('new:1');
+ expect(mockClearFilesDraft).not.toHaveBeenCalledWith('new');
+ });
+
it('deletes the draft uploads a draft-saving user is discarding with the draft', () => {
mockState.saveDrafts = true;
mockState.filesDraft = {
@@ -315,7 +327,7 @@ describe('useNewChat', () => {
],
});
expect(mockDeleteFiles.mock.invocationCallOrder[0]).toBeLessThan(
- mockClearAllDrafts.mock.invocationCallOrder[0],
+ mockClearFilesDraft.mock.invocationCallOrder[0],
);
});
@@ -490,7 +502,7 @@ describe('useNewChat', () => {
act(() => result.current.startNewChat());
expect(mockDeleteFiles).not.toHaveBeenCalled();
- expect(mockClearAllDrafts).not.toHaveBeenCalledWith('new');
+ expect(mockClearFilesDraft).not.toHaveBeenCalledWith('new');
expect(mockClearAllDrafts).toHaveBeenCalledWith('pending');
});
@@ -895,7 +907,7 @@ describe('useNewChat', () => {
act(() => result.current.startNewChat());
expect(mockClearAllDrafts).toHaveBeenCalledWith('pending');
- expect(mockClearAllDrafts).toHaveBeenCalledWith('new');
+ expect(mockClearFilesDraft).toHaveBeenCalledWith('new');
});
it('deletes pending-draft uploads before clearing them', () => {
@@ -944,7 +956,7 @@ describe('useNewChat', () => {
expect(mockDeleteFiles).not.toHaveBeenCalled();
expect(mockClearAllDrafts).not.toHaveBeenCalledWith('pending');
- expect(mockClearAllDrafts).toHaveBeenCalledWith('new');
+ expect(mockClearFilesDraft).toHaveBeenCalledWith('new');
});
it('spares a reattached file from a retained deletion retry', async () => {
diff --git a/client/src/hooks/Chat/useNewChat.ts b/client/src/hooks/Chat/useNewChat.ts
index 564a3afe12..4f109400de 100644
--- a/client/src/hooks/Chat/useNewChat.ts
+++ b/client/src/hooks/Chat/useNewChat.ts
@@ -9,6 +9,7 @@ import type { FilesDraft } from '~/utils';
import {
beginRetainedDeletionPass,
clearAllDrafts,
+ clearFilesDraft,
clearMessagesCache,
clearRetainedFileDeletion,
failedFileIdsFrom,
@@ -299,10 +300,13 @@ export default function useNewChat({
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.
+ /** The unsaved-chat draft key outlives the reset and `useAutoSave` restores from it on the way
+ * in, so an unsent paste came back on every later new chat. Its attachments are dropped here to
+ * make an explicit new chat a clean slate; its text is deliberately kept, because the restore
+ * is also what puts a draft back when the user simply leaves the unsaved chat and returns, and
+ * clearing it made that the one composer that forgot what had been typed in it. Nothing else is
+ * gained by clearing it: unlike an attachment there is no upload behind it to leave dangling.
+ * Per-conversation drafts are untouched either way.
*
* 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
@@ -442,8 +446,11 @@ export default function useNewChat({
if (isFilesDraftOwnedByThisTab(pendingDraft)) {
clearAllDrafts(pendingId);
}
+ /** Attachments only: the uploads behind them have just been deleted, so restoring the chips
+ * would reference files that are gone, while the typed message is what the user expects to
+ * find again on the way back into the unsaved chat. */
if (isFilesDraftOwnedByThisTab(idleDraft)) {
- clearAllDrafts(draftId);
+ clearFilesDraft(draftId);
}
const discardedFileIds = Array.from(
new Set([
diff --git a/client/src/utils/drafts.spec.ts b/client/src/utils/drafts.spec.ts
index b951eaaaa3..1cc6e6ae86 100644
--- a/client/src/utils/drafts.spec.ts
+++ b/client/src/utils/drafts.spec.ts
@@ -4,6 +4,7 @@ import {
applyPendingPastesToDraft,
clearAllDrafts,
clearComposerDrafts,
+ clearFilesDraft,
decodeBase64,
encodeBase64,
resolvePendingPasteInsertStart,
@@ -796,6 +797,73 @@ describe('browser tab ownership of unsaved-chat drafts', () => {
});
});
+describe('clearFilesDraft', () => {
+ const newChatKey = getNewConversationDraftId();
+
+ beforeEach(() => {
+ localStorage.clear();
+ sessionStorage.clear();
+ });
+
+ it('discards the attachments and keeps the text', () => {
+ setDraft({ id: newChatKey, value: 'half-written message' });
+ setFilesDraft(newChatKey, { fileIds: ['file-1'], pendingPastes: {} });
+
+ clearFilesDraft(newChatKey);
+
+ expect(getFilesDraft(newChatKey).fileIds).toEqual([]);
+ expect(getDraft(newChatKey)).toBe('half-written message');
+ });
+
+ it('keeps this tab claim on the text it left behind', () => {
+ /** `setFilesDraft` drops the whole record once nothing is attached, and that record is the
+ * only ownership stamp the shared text draft has: without it another tab's New Chat would be
+ * free to clear text this tab is still holding. */
+ setDraft({ id: newChatKey, value: 'half-written message' });
+ setFilesDraft(newChatKey, { fileIds: ['file-1'], pendingPastes: {} });
+
+ clearFilesDraft(newChatKey);
+
+ expect(getFilesDraft(newChatKey).tabId).toBe(getBrowserTabId());
+ });
+
+ /** The reset empties the file map, and `useAutoSave`'s attachment effect then writes the draft
+ * with nothing in it. That write used to delete the record this helper had just re-stamped, so
+ * the preserved text sat unowned until the next keystroke and another live tab finishing a
+ * new-chat run could clear it as though nobody were holding it. */
+ it('keeps the claim through the empty-map write the reset triggers', () => {
+ setDraft({ id: newChatKey, value: 'half-written message' });
+ setFilesDraft(newChatKey, { fileIds: ['file-1'], pendingPastes: {} });
+
+ clearFilesDraft(newChatKey);
+ /** What the attachment effect writes once the composer's file map is empty. */
+ setFilesDraft(newChatKey, { fileIds: [], pastedTextIds: [], pendingPastes: {} });
+
+ expect(getFilesDraft(newChatKey).tabId).toBe(getBrowserTabId());
+ expect(getDraft(newChatKey)).toBe('half-written message');
+ });
+
+ it('leaves no claim behind when there was no text to hold', () => {
+ setFilesDraft(newChatKey, { fileIds: ['file-1'], pendingPastes: {} });
+
+ clearFilesDraft(newChatKey);
+
+ expect(localStorage.getItem(`${LocalStorageKeys.FILES_DRAFT}${newChatKey}`)).toBeNull();
+ });
+
+ it('refuses a record another live tab owns', () => {
+ markTabLive('other-tab');
+ localStorage.setItem(
+ `${LocalStorageKeys.FILES_DRAFT}${newChatKey}`,
+ JSON.stringify({ fileIds: ['other-tab-file'], tabId: 'other-tab' }),
+ );
+
+ clearFilesDraft(newChatKey);
+
+ expect(getFilesDraft(newChatKey).fileIds).toEqual(['other-tab-file']);
+ });
+});
+
describe('migrateFilesDraft', () => {
beforeEach(() => {
localStorage.clear();
diff --git a/client/src/utils/drafts.ts b/client/src/utils/drafts.ts
index 2191c15d03..facd6ec107 100644
--- a/client/src/utils/drafts.ts
+++ b/client/src/utils/drafts.ts
@@ -889,6 +889,17 @@ export const setFilesDraft = (id: string, draft: FilesDraft): void => {
pendingPasteEntries.length === 0 &&
(draft.pastedTextIds?.length ?? 0) === 0
) {
+ /** Nothing attached, but on a shared key this record is also the only thing saying whose text
+ * is stored there, and dropping it leaves that text unowned for another tab to clear.
+ * `useAutoSave` rewrites the draft with an empty file map on every reset and every composer
+ * mount, so a claim that did not survive this branch barely survived at all. The text itself
+ * is the condition, exactly as in `releaseComposerDraftTab`: with none, the claim is residue
+ * and the record still goes. */
+ const holdsText = (getLocalStorageItem(`${LocalStorageKeys.TEXT_DRAFT}${id}`) ?? '') !== '';
+ if (tabId != null && holdsText && isSharedComposerDraftId(id)) {
+ setLocalStorageItem(key, JSON.stringify({ fileIds: [], tabId }));
+ return;
+ }
removeLocalStorageItem(key);
return;
}
@@ -1246,6 +1257,21 @@ export const setDraft = ({
export const getDraft = (id?: string): string | null =>
decodeBase64((getLocalStorageItem(`${LocalStorageKeys.TEXT_DRAFT}${id ?? ''}`) ?? '') || '');
+/** Discards a key's attachments while leaving its text where it is. New Chat deletes the uploads
+ * the draft was holding, so restoring those chips would put back a file the server no longer has;
+ * a typed message has no such resource behind it, and losing it is what made an unsaved chat the
+ * one composer whose draft did not survive leaving and coming back.
+ *
+ * Written as an empty draft rather than a direct delete so the claim rule lives in one place:
+ * `setFilesDraft` keeps a shared key's stamp while text is stored under it and drops the record
+ * otherwise, which is also what the autosave write that follows this one has to do. */
+export const clearFilesDraft = (id: string): void => {
+ if (!mayClearComposerDrafts(id)) {
+ return;
+ }
+ setFilesDraft(id, { fileIds: [], pendingPastes: {} });
+};
+
/**
* Draft-key prefix for a live `ask_user_question` answer phase. While the
* composer doubles as the free-form answer box, its autosave switches to a key