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: Preserve Preset Prompt Insertion Behavior (#15672)

Danny Aviladd51b9daf42e
diff --git a/client/src/hooks/Input/useTextarea.spec.tsx b/client/src/hooks/Input/useTextarea.spec.tsx
index 4a5e174136..37204fee6e 100644
--- a/client/src/hooks/Input/useTextarea.spec.tsx
+++ b/client/src/hooks/Input/useTextarea.spec.tsx
@@ -21,6 +21,8 @@ const mockOpenModal = jest.fn();
const mockLocalize = jest.fn((key: string) => key);
const mockSetActivePrompt = jest.fn();
const mockSetPendingComposerText = jest.fn();
+const mockSetValue = jest.fn();
+let mockActivePrompt: string | undefined;
let mockPendingComposerText: string | undefined;
let useTextarea: typeof import('./useTextarea').default;
@@ -48,7 +50,7 @@ jest.mock('recoil', () => ({
useRecoilState: jest.fn((atom: { key?: string }) =>
atom?.key === 'pendingComposerText'
? [mockPendingComposerText, mockSetPendingComposerText]
- : [undefined, mockSetActivePrompt],
+ : [mockActivePrompt, mockSetActivePrompt],
),
}));
@@ -118,6 +120,7 @@ jest.mock('~/Providers/ChatContext', () => ({
}));
jest.mock('~/Providers', () => ({
+ useChatFormContext: jest.fn(() => ({ setValue: mockSetValue })),
useUploadModalContext: jest.fn(() => ({ openModal: mockOpenModal })),
}));
@@ -170,18 +173,74 @@ describe('useTextarea long-paste fallback', () => {
beforeEach(() => {
jest.clearAllMocks();
localStorage.clear();
+ mockActivePrompt = undefined;
mockPendingComposerText = undefined;
mockIndex = 0;
mockIsSubmitting = false;
mockIsUploadConfigPending = false;
mockConversation = { endpoint: 'openAI', conversationId: 'convo-1' };
mockGetUploadOptions.mockReturnValue([EToolResources.context]);
+ mockSetValue.mockReset();
mockResolvePastedTextFile.mockImplementation((text: string) => ({
file: new File([text], 'pasted-text.txt', { type: 'text/plain' }),
toolResource: EToolResources.context,
}));
});
+ it('inserts a preset prompt when the textarea refuses focus', () => {
+ mockActivePrompt = 'selected prompt';
+ const textArea = document.createElement('textarea');
+ textArea.value = 'draft text';
+ textArea.setSelectionRange(6, 10);
+ const focus = jest.spyOn(textArea, 'focus').mockImplementation();
+ mockSetValue.mockImplementation((_name: string, value: string) => {
+ textArea.value = value;
+ });
+
+ renderHook(() =>
+ useTextarea({
+ textAreaRef: { current: textArea },
+ submitButtonRef: { current: null },
+ setIsScrollable: jest.fn(),
+ }),
+ );
+
+ expect(mockSetValue).toHaveBeenCalledWith('text', 'draft selected prompt', {
+ shouldDirty: true,
+ shouldValidate: true,
+ });
+ expect(focus).toHaveBeenCalledTimes(1);
+ expect(document.activeElement).not.toBe(textArea);
+ expect(textArea.selectionStart).toBe(21);
+ expect(textArea.selectionEnd).toBe(21);
+ expect(mockSetActivePrompt).toHaveBeenCalledWith(undefined);
+ });
+
+ it('dispatches an input event when handing text to the composer', () => {
+ mockPendingComposerText = 'continued text';
+ const textArea = document.createElement('textarea');
+ const inputListener = jest.fn();
+ textArea.addEventListener('input', inputListener);
+ mockSetValue.mockImplementation((_name: string, value: string) => {
+ textArea.value = value;
+ });
+
+ renderHook(() =>
+ useTextarea({
+ textAreaRef: { current: textArea },
+ submitButtonRef: { current: null },
+ setIsScrollable: jest.fn(),
+ }),
+ );
+
+ expect(mockSetValue).toHaveBeenCalledWith('text', 'continued text', {
+ shouldDirty: true,
+ shouldValidate: true,
+ });
+ expect(inputListener).toHaveBeenCalledTimes(1);
+ expect(mockSetPendingComposerText).toHaveBeenCalledWith(undefined);
+ });
+
it('keeps long pasted text inline while the composer is the answer box', () => {
const { result } = renderTextareaHook(true);
const event = createPasteEvent();
@@ -961,6 +1020,8 @@ describe('useTextarea long-paste fallback', () => {
describe('useTextarea composer handoff', () => {
beforeEach(() => {
jest.clearAllMocks();
+ mockSetValue.mockReset();
+ mockActivePrompt = undefined;
mockPendingComposerText = undefined;
mockConversation = { endpoint: 'openAI', conversationId: 'convo-1' };
});
@@ -970,9 +1031,16 @@ describe('useTextarea composer handoff', () => {
* delivered whatever the Save Drafts preference is. */
it('drains text handed to this conversation into the composer exactly once', () => {
mockPendingComposerText = 'Take this further.';
+ mockSetValue.mockImplementation((_name: string, value: string) => {
+ expect(value).toBe('Take this further.');
+ });
const { textArea } = renderTextareaHook();
- expect(mockInsertTextAtCursor).toHaveBeenCalledWith(textArea, 'Take this further.');
+ expect(mockSetValue).toHaveBeenCalledWith('text', 'Take this further.', {
+ shouldDirty: true,
+ shouldValidate: true,
+ });
+ expect(mockInsertTextAtCursor).not.toHaveBeenCalled();
expect(mockForceResize).toHaveBeenCalledWith(textArea);
expect(mockSetPendingComposerText).toHaveBeenCalledWith(undefined);
expect(getDraft('convo-1')).toBe('');
diff --git a/client/src/hooks/Input/useTextarea.ts b/client/src/hooks/Input/useTextarea.ts
index c6e86cadf2..ae16a34216 100644
--- a/client/src/hooks/Input/useTextarea.ts
+++ b/client/src/hooks/Input/useTextarea.ts
@@ -27,6 +27,7 @@ import {
} from '~/utils';
import { useAssistantsMapContext } from '~/Providers/AssistantsMapContext';
import { useLatestMessageMeta } from '~/hooks/Messages/useLatestMessage';
+import { useChatFormContext, useUploadModalContext } from '~/Providers';
import useComposerBindings from '~/hooks/Input/useComposerBindings';
import useFileUploadRouter from '~/hooks/Files/useFileUploadRouter';
import { useAgentsMapContext } from '~/Providers/AgentsMapContext';
@@ -35,7 +36,6 @@ import useUploadOptions from '~/hooks/Files/useUploadOptions';
import { useInteractionHealthCheck } from '~/data-provider';
import { resolveComposerKeyDown } from '~/utils/shortcuts';
import { useChatContext } from '~/Providers/ChatContext';
-import { useUploadModalContext } from '~/Providers';
import { globalAudioId } from '~/common';
import { useLocalize } from '~/hooks';
import store from '~/store';
@@ -67,6 +67,7 @@ export default function useTextarea({
}) {
const localize = useLocalize();
const getSender = useGetSender();
+ const { setValue } = useChatFormContext();
const isComposing = useRef(false);
const agentsMap = useAgentsMapContext();
const { showToast } = useToastContext();
@@ -114,14 +115,36 @@ export default function useTextarea({
latestMessage?.error === true && latestMessage.isCreatedByUser === true && !isAssistant;
// && (conversationId?.length ?? 0) > 6; // also ensures that we don't show the wrong placeholder
+ const insertComposerText = useCallback(
+ (text: string) => {
+ const textarea = textAreaRef.current;
+ if (!textarea) {
+ return false;
+ }
+
+ const { value, selectionStart, selectionEnd } = textarea;
+ const nextCursor = selectionStart + text.length;
+ setValue('text', `${value.slice(0, selectionStart)}${text}${value.slice(selectionEnd)}`, {
+ shouldDirty: true,
+ shouldValidate: true,
+ });
+ textarea.dispatchEvent(new Event('input', { bubbles: true }));
+ forceResize(textarea);
+ textarea.focus();
+ textarea.setSelectionRange(nextCursor, nextCursor);
+ return true;
+ },
+ [setValue, textAreaRef],
+ );
+
useEffect(() => {
const prompt = activePrompt ?? '';
- if (prompt && textAreaRef.current) {
- insertTextAtCursor(textAreaRef.current, prompt);
- forceResize(textAreaRef.current);
- setActivePrompt(undefined);
+ if (!prompt || !insertComposerText(prompt)) {
+ return;
}
- }, [activePrompt, setActivePrompt, textAreaRef]);
+
+ setActivePrompt(undefined);
+ }, [activePrompt, insertComposerText, setActivePrompt]);
/** Text a surface the user was leaving handed to THIS conversation (see
* `pendingComposerTextByConvoId`). It is drained once, on the first render
@@ -129,11 +152,12 @@ export default function useTextarea({
* navigation that resolves its record before moving the route. */
useEffect(() => {
const text = pendingComposerText ?? '';
- if (text === '' || textAreaRef.current == null) return;
- insertTextAtCursor(textAreaRef.current, text);
- forceResize(textAreaRef.current);
+ if (text === '' || !insertComposerText(text)) {
+ return;
+ }
+
setPendingComposerText(undefined);
- }, [pendingComposerText, setPendingComposerText, textAreaRef]);
+ }, [insertComposerText, pendingComposerText, setPendingComposerText]);
useEffect(() => {
const currentValue = textAreaRef.current?.value ?? '';