diff --git a/webui/src/hooks/useComposerMentionInput.ts b/webui/src/hooks/useComposerMentionInput.ts index ba8ba6fb9..0f09c496c 100644 --- a/webui/src/hooks/useComposerMentionInput.ts +++ b/webui/src/hooks/useComposerMentionInput.ts @@ -44,7 +44,10 @@ export function useComposerMentionInput({ }, [inputRef]); const selectRaw = useCallback((start: number, end = start) => { - inputRef.current?.setSelectionRange( + const el = inputRef.current; + // Focus first: removing a queued prompt's edit button can reset a blurred selection. + el?.focus(); + el?.setSelectionRange( mentionTextOffset(textRef.current, start, "toDisplay", "start"), mentionTextOffset(textRef.current, end, "toDisplay", "end"), ); diff --git a/webui/src/tests/thread-composer.test.tsx b/webui/src/tests/thread-composer.test.tsx index 5b22b5804..3be941eda 100644 --- a/webui/src/tests/thread-composer.test.tsx +++ b/webui/src/tests/thread-composer.test.tsx @@ -2981,10 +2981,19 @@ describe("ThreadComposer", () => { fireEvent.keyDown(input, { key: "Enter" }); const editButton = screen.getByRole("button", { name: "Edit guidance" }); - fireEvent.click(editButton); + const textarea = input as HTMLTextAreaElement; + const setSelection = textarea.setSelectionRange.bind(textarea); + const focusedSelections: boolean[] = []; + vi.spyOn(textarea, "setSelectionRange").mockImplementation((start, end, direction) => { + focusedSelections.push(document.activeElement === textarea); + setSelection(start, end, direction); + }); + await userEvent.click(editButton); await waitFor(() => { expect(input).toHaveFocus(); }); + expect(focusedSelections).toEqual([true]); + expect(textarea.selectionStart).toBe("rough follow-up".length); expect(input).toHaveValue("rough follow-up"); expect(screen.queryByRole("group", { name: "Queued guidance" })).not.toBeInTheDocument(); fireEvent.change(input, { target: { value: "polished follow-up" } });