Skip to content

🙌 OpenHands: AI-Driven Development

fix(frontend): scroll chat to bottom when a new prompt is submitted (#831)

Hiep Led7d396df1efc
diff --git a/__tests__/components/chat/chat-interface.test.tsx b/__tests__/components/chat/chat-interface.test.tsx
index 593f15a3b7..60f26228d6 100644
--- a/__tests__/components/chat/chat-interface.test.tsx
+++ b/__tests__/components/chat/chat-interface.test.tsx
@@ -388,7 +388,7 @@ describe("ChatInterface - Scroll-up loads older events", () => {
renderWithQueryClient(<ChatInterface />, queryClient);
const scrollContainer = document.querySelector(
- ".custom-scrollbar-always",
+ "[data-testid='chat-scroll-container']",
) as HTMLElement | null;
expect(scrollContainer).not.toBeNull();
@@ -434,7 +434,7 @@ describe("ChatInterface - Scroll-up loads older events", () => {
renderWithQueryClient(<ChatInterface />, queryClient);
const scrollContainer = document.querySelector(
- ".custom-scrollbar-always",
+ "[data-testid='chat-scroll-container']",
) as HTMLElement | null;
expect(scrollContainer).not.toBeNull();
@@ -518,7 +518,7 @@ describe("ChatInterface - Scroll-up loads older events", () => {
renderWithQueryClient(<ChatInterface />, queryClient);
const scrollContainer = document.querySelector(
- ".custom-scrollbar-always",
+ "[data-testid='chat-scroll-container']",
) as HTMLElement | null;
expect(scrollContainer).not.toBeNull();
@@ -577,7 +577,7 @@ describe("ChatInterface - Scroll-up loads older events", () => {
// The scroll container exists (so the user can scroll up to load older).
const scrollContainer = document.querySelector(
- ".custom-scrollbar-always",
+ "[data-testid='chat-scroll-container']",
) as HTMLElement | null;
expect(scrollContainer).not.toBeNull();
@@ -699,6 +699,107 @@ describe("ChatInterface - Pending message queue", () => {
});
});
+describe("ChatInterface - Auto-scroll on submit (issue #817)", () => {
+ let queryClient: QueryClient;
+
+ beforeEach(() => {
+ mockSend.mockReset();
+ mockSend.mockResolvedValue({ queued: false });
+ queryClient = new QueryClient({
+ defaultOptions: { queries: { retry: false } },
+ });
+ useOptimisticUserMessageStore.setState({ pendingMessages: [] });
+ useErrorMessageStore.setState({ errorMessage: null });
+ (useConfig as unknown as ReturnType<typeof vi.fn>).mockReturnValue({
+ data: {},
+ });
+ (
+ useUnifiedUploadFiles as unknown as ReturnType<typeof vi.fn>
+ ).mockReturnValue({
+ mutateAsync: vi
+ .fn()
+ .mockResolvedValue({ skipped_files: [], uploaded_files: [] }),
+ isLoading: false,
+ });
+ useEventStore.setState({
+ events: [],
+ eventIds: new Set(),
+ uiEvents: [],
+ });
+ });
+
+ afterEach(() => {
+ useOptimisticUserMessageStore.setState({ pendingMessages: [] });
+ });
+
+ it("scrolls to bottom when a new prompt is submitted while the user is scrolled up", async () => {
+ // Arrange: render and grab the chat scroll container.
+ render(
+ <QueryClientProvider client={queryClient}>
+ <MemoryRouter initialEntries={["/test-conversation-id"]}>
+ <Routes>
+ <Route path=":conversationId" element={<ChatInterface />} />
+ </Routes>
+ </MemoryRouter>
+ </QueryClientProvider>,
+ );
+
+ const scrollContainer = document.querySelector(
+ "[data-testid='chat-scroll-container']",
+ ) as HTMLElement | null;
+ expect(scrollContainer).not.toBeNull();
+
+ // Let the mount-time auto-scroll rAF (which re-arms autoScroll=true)
+ // run and settle BEFORE the scroll-up sim. Otherwise that rAF would
+ // fire later and undo the autoScroll=false precondition for the bug.
+ await new Promise((r) => {
+ setTimeout(r, 0);
+ });
+
+ // Capture every scrollTop write so we can detect the rAF inside
+ // scrollDomToBottom landing `dom.scrollTop = dom.scrollHeight`.
+ const scrollWrites: number[] = [];
+ let scrollTopRead = 200;
+ Object.defineProperty(scrollContainer!, "scrollTop", {
+ configurable: true,
+ get: () => scrollTopRead,
+ set: (value: number) => {
+ scrollWrites.push(value);
+ },
+ });
+ Object.defineProperty(scrollContainer!, "scrollHeight", {
+ configurable: true,
+ writable: true,
+ value: 10000,
+ });
+ Object.defineProperty(scrollContainer!, "clientHeight", {
+ configurable: true,
+ writable: true,
+ value: 800,
+ });
+
+ // Simulate the user scrolling up: first event seeds prev=200, the
+ // second event at scrollTop=50 is detected as scrolling up and flips
+ // the hook's `autoScroll` to false (the precondition for the bug).
+ fireEvent.scroll(scrollContainer!);
+ scrollTopRead = 50;
+ fireEvent.scroll(scrollContainer!);
+ scrollWrites.length = 0;
+
+ // Act: submit a new prompt (same path InteractiveChatBox uses).
+ act(() => {
+ useConversationStore.setState({ submittedMessage: "hello" });
+ });
+
+ // Assert: scrollDomToBottom landed scrollHeight onto scrollTop even
+ // though autoScroll was off. Without the fix the auto-scroll effect
+ // would skip the call and `scrollWrites` would stay empty.
+ await waitFor(() => {
+ expect(scrollWrites).toContain(10000);
+ });
+ });
+});
+
describe("ChatInterface - Status Indicator", () => {
it("should render ChatStatusIndicator when agent is not awaiting user input / conversation is NOT ready", () => {
vi.mocked(useAgentState).mockReturnValue({
diff --git a/__tests__/components/features/chat/git-control-bar.test.tsx b/__tests__/components/features/chat/git-control-bar.test.tsx
index 3bcbb29fd4..8123a4630c 100644
--- a/__tests__/components/features/chat/git-control-bar.test.tsx
+++ b/__tests__/components/features/chat/git-control-bar.test.tsx
@@ -13,6 +13,16 @@ import { useHomeStore } from "#/stores/home-store";
import { useOptimisticUserMessageStore } from "#/stores/optimistic-user-message-store";
import { getStoredConversationMetadata } from "#/api/conversation-metadata-store";
import { GitControlBar } from "#/components/features/chat/git-control-bar";
+import { ScrollProvider } from "#/context/scroll-context";
+
+// Holder so the OpenRepositoryModal mock can hand its `onLaunch` prop back
+// to the test — the modal renders null but the parent's launch flow is the
+// only way to drive handleLaunchRepository.
+const mocks = vi.hoisted(() => ({
+ modalLaunchHandler: {
+ current: null as ((repo: unknown, branch: unknown) => void) | null,
+ },
+}));
vi.mock("#/hooks/use-conversation-id", () => ({
useOptionalConversationId: () => ({ conversationId: "test-conversation-id" }),
@@ -55,7 +65,12 @@ vi.mock("#/components/features/chat/git-control-bar-tooltip-wrapper", () => ({
children,
}));
vi.mock("#/components/features/chat/open-repository-modal", () => ({
- OpenRepositoryModal: () => null,
+ OpenRepositoryModal: (props: {
+ onLaunch?: (repo: unknown, branch: unknown) => void;
+ }) => {
+ mocks.modalLaunchHandler.current = props.onLaunch ?? null;
+ return null;
+ },
}));
const makeBackend = (kind: "local" | "cloud") => ({
@@ -178,3 +193,74 @@ describe("GitControlBar repo button visibility", () => {
expect(button).toHaveAttribute("data-disabled", "true");
});
});
+
+describe("GitControlBar - Auto-scroll on clone (issue #817)", () => {
+ beforeEach(() => {
+ mocks.modalLaunchHandler.current = null;
+ vi.mocked(useActiveBackend).mockReturnValue(makeBackend("cloud"));
+ vi.mocked(useActiveConversation).mockReturnValue({
+ data: { id: "test-conversation-id" },
+ } as ReturnType<typeof useActiveConversation>);
+ vi.mocked(useTaskPolling).mockReturnValue({
+ repositoryInfo: null,
+ } as unknown as ReturnType<typeof useTaskPolling>);
+ vi.mocked(useLocalGitInfo).mockReturnValue({
+ data: null,
+ } as unknown as ReturnType<typeof useLocalGitInfo>);
+ vi.mocked(useUnifiedWebSocketStatus).mockReturnValue("OPEN");
+ vi.mocked(useSendMessage).mockReturnValue({
+ send: vi.fn().mockResolvedValue(undefined),
+ } as unknown as ReturnType<typeof useSendMessage>);
+ // updateRepository mocked to invoke onSuccess synchronously so the
+ // post-update branch (where the scroll now lives) runs deterministically.
+ vi.mocked(useUpdateConversationRepository).mockReturnValue({
+ mutate: (_args: unknown, options: { onSuccess?: () => void }) => {
+ options?.onSuccess?.();
+ },
+ } as unknown as ReturnType<typeof useUpdateConversationRepository>);
+ vi.mocked(useHomeStore).mockReturnValue({
+ addRecentRepository: vi.fn(),
+ } as unknown as ReturnType<typeof useHomeStore>);
+ vi.mocked(useOptimisticUserMessageStore).mockImplementation(((
+ selector: (s: unknown) => unknown,
+ ) =>
+ selector({
+ enqueuePendingMessage: vi.fn().mockReturnValue("pending-id"),
+ markPendingMessageError: vi.fn(),
+ })) as unknown as typeof useOptimisticUserMessageStore);
+ vi.mocked(getStoredConversationMetadata).mockReturnValue(null);
+ });
+
+ it("scrolls the chat to bottom after a successful clone is enqueued", () => {
+ // Arrange: provide a spy via ScrollProvider so we can observe the
+ // scroll callback the bar pulls out of useOptionalScrollContext.
+ const scrollDomToBottom = vi.fn();
+ const scrollValue = {
+ scrollRef: { current: null },
+ autoScroll: true,
+ setAutoScroll: vi.fn(),
+ scrollDomToBottom,
+ hitBottom: true,
+ setHitBottom: vi.fn(),
+ onChatBodyScroll: vi.fn(),
+ };
+
+ renderWithProviders(
+ <ScrollProvider value={scrollValue}>
+ <GitControlBar onSuggestionsClick={vi.fn()} />
+ </ScrollProvider>,
+ );
+
+ expect(typeof mocks.modalLaunchHandler.current).toBe("function");
+
+ // Act: drive handleLaunchRepository the same way the modal does.
+ mocks.modalLaunchHandler.current?.(
+ { full_name: "user/repo", git_provider: "github" },
+ { name: "main" },
+ );
+
+ // Assert: the optimistic clone bubble must pull the chat back to the
+ // bottom even if the user had scrolled up.
+ expect(scrollDomToBottom).toHaveBeenCalledTimes(1);
+ });
+});
diff --git a/src/components/features/chat/chat-interface.tsx b/src/components/features/chat/chat-interface.tsx
index 5d56feddbf..e16a0cc4d6 100644
--- a/src/components/features/chat/chat-interface.tsx
+++ b/src/components/features/chat/chat-interface.tsx
@@ -336,6 +336,10 @@ export function ChatInterface() {
fileUrls: uploadedFiles,
timestamp,
});
+ // Submitting a new prompt should always pull the chat back to the
+ // latest message even if the user had scrolled up. This also re-arms
+ // autoScroll so the streamed agent reply auto-follows.
+ scrollDomToBottom();
setMessageToSend("");
try {
@@ -455,6 +459,7 @@ export function ChatInterface() {
<div
ref={scrollRef}
+ data-testid="chat-scroll-container"
onScroll={(e) => {
onChatBodyScroll(e.currentTarget);
maybeLoadOlder(e.currentTarget);
diff --git a/src/components/features/chat/git-control-bar.tsx b/src/components/features/chat/git-control-bar.tsx
index 1d69eab323..c2a706bda1 100644
--- a/src/components/features/chat/git-control-bar.tsx
+++ b/src/components/features/chat/git-control-bar.tsx
@@ -24,6 +24,7 @@ import { useOptimisticUserMessageStore } from "#/stores/optimistic-user-message-
import { getStoredConversationMetadata } from "#/api/conversation-metadata-store";
import { useActiveBackend } from "#/contexts/active-backend-context";
import { useUserProviders } from "#/hooks/use-user-providers";
+import { useOptionalScrollContext } from "#/context/scroll-context";
interface GitControlBarProps {
onSuggestionsClick: (value: string) => void;
@@ -60,6 +61,7 @@ export function GitControlBar({ onSuggestionsClick }: GitControlBarProps) {
useEffect(() => {
sendRef.current = send;
}, [send]);
+ const scrollContext = useOptionalScrollContext();
const { mutate: updateRepository } = useUpdateConversationRepository();
const { mutate: _createConversation, isPending: _isCreatingConversation } =
useCreateConversation();
@@ -169,6 +171,9 @@ export function GitControlBar({ onSuggestionsClick }: GitControlBarProps) {
const pendingId = conversationId
? enqueuePendingMessage({ conversationId, text: clonePrompt })
: null;
+ // Pull chat back to the bottom so the optimistic "Clone …" bubble
+ // is visible even if the user had scrolled up.
+ scrollContext?.scrollDomToBottom();
// `send` returns a Promise; surface a failed send by flipping the
// matching pending entry to "error" so the user gets the retry link
// rather than a perpetual "Sending…" bubble.
diff --git a/src/context/scroll-context.tsx b/src/context/scroll-context.tsx
index 2394bc07f2..7046744a74 100644
--- a/src/context/scroll-context.tsx
+++ b/src/context/scroll-context.tsx
@@ -40,3 +40,11 @@ export function useScrollContext() {
}
return context;
}
+
+// Same as useScrollContext but returns undefined when no provider is mounted.
+// Use this in components that have valid render paths both inside and outside
+// the chat's ScrollProvider (e.g. GitControlBar in production vs. isolated
+// test mounts).
+export function useOptionalScrollContext() {
+ return useContext(ScrollContext);
+}