Skip to content

The fastest, cheapest, most efficient open-source agent harness. Run more than 500 agents on a $10 VPS.

feat(chat): focus the composer when a conversation is opened

M3gA-Mind660f554b1e72
diff --git a/app/src/components/assistant-ui/lib/useComposerFocusOnThreadOpen.ts b/app/src/components/assistant-ui/lib/useComposerFocusOnThreadOpen.ts
new file mode 100644
index 0000000000..de9aa742f2
--- /dev/null
+++ b/app/src/components/assistant-ui/lib/useComposerFocusOnThreadOpen.ts
@@ -0,0 +1,67 @@
+import { useAui } from '@assistant-ui/react';
+import debugFactory from 'debug';
+import { type RefObject, useEffect } from 'react';
+
+const debug = debugFactory('openhuman:assistant-composer');
+
+const MODAL_SELECTOR = '[role="dialog"], [role="alertdialog"], dialog, [aria-modal="true"]';
+
+function isEditable(el: Element): boolean {
+ if (el instanceof HTMLInputElement || el instanceof HTMLTextAreaElement) return true;
+ if (el instanceof HTMLSelectElement) return true;
+ // `isContentEditable` is unimplemented in jsdom; the attribute is what Lexical sets.
+ return el.closest('[contenteditable="true"]') !== null;
+}
+
+/**
+ * Puts the caret at the end of the composer when a conversation opens: once when
+ * the composer mounts (a thread was opened) and once per `threads.selectionChanged`
+ * (a switch, including New chat landing on another thread). Every open path —
+ * thread list, route, New chat — converges on one of those two, and nothing else
+ * (messages, re-renders) triggers it.
+ *
+ * The plain `ComposerPrimitive.Input` does this natively; `LexicalComposerInput`
+ * only focuses on `thread.runStart`, hence this hook.
+ *
+ * It never steals focus: it stands down while a modal is open, while focus is
+ * already in another input, and while the composer is disabled.
+ */
+export function useComposerFocusOnThreadOpen(inputWrapperRef: RefObject<HTMLElement | null>) {
+ const aui = useAui();
+
+ useEffect(() => {
+ const focus = (reason: 'open' | 'switch') => {
+ // The same condition `LexicalComposerInput` makes the editor read-only on.
+ const disabled =
+ aui.thread.getState().isDisabled || aui.composer.getState().dictation?.inputDisabled;
+ const textbox = inputWrapperRef.current?.querySelector<HTMLElement>(
+ '[contenteditable="true"]'
+ );
+ if (disabled || !textbox) {
+ debug('focus on %s: skipped, composer disabled or not mounted', reason);
+ return;
+ }
+ const active = document.activeElement;
+ const elsewhere = active && active !== textbox && active !== document.body;
+ if (
+ (elsewhere && (isEditable(active) || active.closest(MODAL_SELECTOR))) ||
+ document.querySelector('[aria-modal="true"]')
+ ) {
+ debug('focus on %s: skipped, a modal or another input holds focus', reason);
+ return;
+ }
+
+ textbox.focus({ preventScroll: true });
+ // Caret after any restored draft, not before it.
+ const selection = window.getSelection();
+ if (selection) {
+ selection.selectAllChildren(textbox);
+ selection.collapseToEnd();
+ }
+ debug('focus on %s: composer focused', reason);
+ };
+
+ focus('open');
+ return aui.on('threads.selectionChanged', () => focus('switch'));
+ }, [aui, inputWrapperRef]);
+}
diff --git a/app/src/components/assistant-ui/thread.composerFocus.test.tsx b/app/src/components/assistant-ui/thread.composerFocus.test.tsx
new file mode 100644
index 0000000000..30a1c96f2b
--- /dev/null
+++ b/app/src/components/assistant-ui/thread.composerFocus.test.tsx
@@ -0,0 +1,209 @@
+/** The composer takes the caret once per conversation open, and never steals it. */
+import { AssistantUiRuntimeProvider } from '@/providers/AssistantUiRuntimeProvider';
+import chatRuntimeReducer from '@/store/chatRuntimeSlice';
+import threadReducer, { loadThreadMessages } from '@/store/threadSlice';
+import type { ThreadMessage } from '@/types/thread';
+import {
+ AssistantRuntimeProvider,
+ type ThreadMessageLike,
+ useExternalStoreRuntime,
+} from '@assistant-ui/react';
+import { configureStore } from '@reduxjs/toolkit';
+import { render, screen, waitFor } from '@testing-library/react';
+import { act, type ReactNode } from 'react';
+import { Provider } from 'react-redux';
+import { afterEach, beforeEach, describe, expect, it, type MockInstance, vi } from 'vitest';
+
+import { Thread } from './thread';
+
+vi.mock('@/services/api/threadApi', () => ({
+ threadApi: { getDerivedTranscript: vi.fn().mockResolvedValue({ items: [], nextCursor: null }) },
+}));
+
+function msg(id: string, sender: 'user' | 'agent', content: string): ThreadMessage {
+ return {
+ id,
+ content,
+ type: 'text',
+ extraMetadata: {},
+ sender,
+ createdAt: `2026-10-14T00:00:${id.padStart(2, '0')}Z`,
+ };
+}
+
+function makeStore() {
+ return configureStore({ reducer: { thread: threadReducer, chatRuntime: chatRuntimeReducer } });
+}
+
+type Store = ReturnType<typeof makeStore>;
+
+function cacheThread(store: Store, threadId: string, messages: ThreadMessage[]) {
+ act(() => {
+ store.dispatch({ type: loadThreadMessages.fulfilled.type, payload: { threadId, messages } });
+ });
+}
+
+/** The thread under test, plus whatever the page around it holds (a modal, a search box). */
+function ui(store: Store, threadId: string, around?: ReactNode) {
+ return (
+ <Provider store={store}>
+ {around}
+ <AssistantUiRuntimeProvider threadId={threadId}>
+ <Thread />
+ </AssistantUiRuntimeProvider>
+ </Provider>
+ );
+}
+
+function composer() {
+ return screen.getByTestId('chat-message-input');
+}
+
+function blurAll() {
+ act(() => (document.activeElement as HTMLElement | null)?.blur());
+ expect(document.activeElement).toBe(document.body);
+}
+
+let scrollToSpy: MockInstance;
+let scrollIntoViewSpy: MockInstance;
+let focusSpy: MockInstance;
+
+beforeEach(() => {
+ scrollToSpy = vi.spyOn(HTMLElement.prototype, 'scrollTo').mockImplementation(() => {});
+ scrollIntoViewSpy = vi.spyOn(Element.prototype, 'scrollIntoView').mockImplementation(() => {});
+ focusSpy = vi.spyOn(HTMLElement.prototype, 'focus');
+});
+
+afterEach(() => {
+ scrollToSpy.mockRestore();
+ scrollIntoViewSpy.mockRestore();
+ focusSpy.mockRestore();
+});
+
+describe('composer focus on conversation open', () => {
+ it('focuses the composer when a conversation is opened, without scrolling to it', async () => {
+ const store = makeStore();
+ cacheThread(store, 't-open', [msg('1', 'user', 'q'), msg('2', 'agent', 'a')]);
+
+ render(ui(store, 't-open'));
+
+ await waitFor(() => expect(composer()).toHaveFocus());
+ const call = focusSpy.mock.calls.find((_, i) => focusSpy.mock.contexts[i] === composer());
+ expect(call?.[0]).toEqual({ preventScroll: true });
+ });
+
+ it('focuses the composer again when switching conversations', async () => {
+ const store = makeStore();
+ cacheThread(store, 't-a', [msg('1', 'user', 'first')]);
+ cacheThread(store, 't-b', [msg('2', 'user', 'hi'), msg('3', 'agent', 'second')]);
+
+ const { rerender } = render(ui(store, 't-a'));
+ await waitFor(() => expect(composer()).toHaveFocus());
+ // Clicking a row in the thread list moves focus off the composer first.
+ blurAll();
+
+ rerender(ui(store, 't-b'));
+
+ await waitFor(() => expect(composer()).toHaveFocus());
+ });
+
+ it('focuses the composer when New chat lands on an empty conversation', async () => {
+ const store = makeStore();
+ cacheThread(store, 't-old', [msg('1', 'user', 'old'), msg('2', 'agent', 'reply')]);
+ cacheThread(store, 't-new', []);
+
+ const { rerender } = render(ui(store, 't-old'));
+ await waitFor(() => expect(composer()).toHaveFocus());
+ blurAll();
+
+ rerender(ui(store, 't-new'));
+
+ await waitFor(() => expect(composer()).toHaveFocus());
+ });
+
+ it('does not take focus from another input on the page', async () => {
+ const store = makeStore();
+ cacheThread(store, 't-a', [msg('1', 'user', 'first')]);
+ cacheThread(store, 't-b', [msg('2', 'user', 'second')]);
+ const search = <input aria-label="Search conversations" />;
+
+ const { rerender } = render(ui(store, 't-a', search));
+ await waitFor(() => expect(composer()).toHaveFocus());
+ const box = screen.getByLabelText('Search conversations');
+ act(() => box.focus());
+
+ rerender(ui(store, 't-b', search));
+
+ // Let the switch's event and effects run before asserting nothing moved.
+ await act(async () => {});
+ expect(box).toHaveFocus();
+ });
+
+ it('does not take focus from an open modal', async () => {
+ const store = makeStore();
+ cacheThread(store, 't-a', [msg('1', 'user', 'first')]);
+ cacheThread(store, 't-b', [msg('2', 'user', 'second')]);
+ const modal = (
+ <div role="dialog" aria-modal="true">
+ <button type="button">Confirm</button>
+ </div>
+ );
+
+ const { rerender } = render(ui(store, 't-a'));
+ await waitFor(() => expect(composer()).toHaveFocus());
+
+ rerender(ui(store, 't-a', modal));
+ const confirm = screen.getByRole('button', { name: 'Confirm' });
+ act(() => confirm.focus());
+
+ rerender(ui(store, 't-b', modal));
+
+ await act(async () => {});
+ expect(confirm).toHaveFocus();
+ });
+
+ it('does not re-focus on new messages or re-renders of the same conversation', async () => {
+ const store = makeStore();
+ cacheThread(store, 't-same', [msg('1', 'user', 'q'), msg('2', 'agent', 'a')]);
+
+ const { rerender } = render(ui(store, 't-same'));
+ await waitFor(() => expect(composer()).toHaveFocus());
+ blurAll();
+
+ cacheThread(store, 't-same', [
+ msg('1', 'user', 'q'),
+ msg('2', 'agent', 'a'),
+ msg('4', 'user', 'follow-up'),
+ ]);
+ rerender(ui(store, 't-same'));
+
+ await act(async () => {});
+ expect(document.activeElement).toBe(document.body);
+ });
+});
+
+describe('composer focus while disabled', () => {
+ function Disabled() {
+ const messages: ThreadMessageLike[] = [
+ { role: 'user', content: [{ type: 'text', text: 'hello' }], createdAt: new Date() },
+ ];
+ const runtime = useExternalStoreRuntime({
+ messages,
+ isDisabled: true,
+ convertMessage: (m: ThreadMessageLike) => m,
+ onNew: async () => {},
+ });
+ return (
+ <AssistantRuntimeProvider runtime={runtime}>
+ <Thread />
+ </AssistantRuntimeProvider>
+ );
+ }
+
+ it('leaves a disabled composer unfocused', async () => {
+ render(<Disabled />);
+
+ await act(async () => {});
+ expect(document.activeElement).toBe(document.body);
+ });
+});
diff --git a/app/src/components/assistant-ui/thread.tsx b/app/src/components/assistant-ui/thread.tsx
index 64f1279e0e..5e1d272cb9 100644
--- a/app/src/components/assistant-ui/thread.tsx
+++ b/app/src/components/assistant-ui/thread.tsx
@@ -16,6 +16,7 @@ import { StoppedRun } from '@/components/assistant-ui/elements/stopped-run';
import { ToolFallback } from '@/components/assistant-ui/elements/tool-fallback';
import { File } from '@/components/assistant-ui/file';
import { ThreadFollowupSuggestions } from '@/components/assistant-ui/follow-up-suggestions';
+import { useComposerFocusOnThreadOpen } from '@/components/assistant-ui/lib/useComposerFocusOnThreadOpen';
import { cn } from '@/components/assistant-ui/lib/utils';
import { MarkdownText } from '@/components/assistant-ui/markdown-text';
import { ComposerQuotePreview, SelectionToolbar } from '@/components/assistant-ui/quote';
@@ -673,6 +674,7 @@ const Composer: FC<{
textbox?.removeAttribute('data-testid');
};
}, [messageInputLabel]);
+ useComposerFocusOnThreadOpen(inputWrapperRef);
// Set for as long as an IME composition is open. The gate is a ref rather
// than state because it is read from a microtask, not from a render.
diff --git a/app/test/e2e/specs/chat-live-history-parity.spec.ts b/app/test/e2e/specs/chat-live-history-parity.spec.ts
index c34b13b9f4..be79d95551 100644
--- a/app/test/e2e/specs/chat-live-history-parity.spec.ts
+++ b/app/test/e2e/specs/chat-live-history-parity.spec.ts
@@ -359,4 +359,24 @@ describe('Chat live/history parity', () => {
expect(reopened).toEqual(settled);
console.log(`${LOG_PREFIX} P3: ${reopened.length} blocks identical live and reopened`);
});
+
+ it('P4 — New thread and reopening a conversation put the caret in the composer', async () => {
+ const composerHasFocus = () =>
+ browser.execute(
+ () => document.activeElement?.getAttribute('data-testid') === 'chat-message-input'
+ );
+
+ expect(await clickByTitle('New thread', 8_000)).toBe(true);
+ await browser.waitUntil(
+ async () => (await getSelectedThreadId()) !== threadId && (await composerHasFocus()),
+ { timeout: 10_000, timeoutMsg: 'New thread did not focus the composer' }
+ );
+
+ await clickTestIdOrText(`thread-row-${threadId}`, PROMPT, 10_000);
+ await browser.waitUntil(
+ async () => (await getSelectedThreadId()) === threadId && (await composerHasFocus()),
+ { timeout: 10_000, timeoutMsg: 'reopening the conversation did not focus the composer' }
+ );
+ console.log(`${LOG_PREFIX} P4: composer focused after New thread and reopen`);
+ });
});