Skip to content

Dodaios is an open-source agent OS for your desktop: it runs your coding agents, browser and apps by voice or chat, on your own machine. Formerly Personal Jarvis.

fix(chat): every conversation surface follows the same scrolling rule

rubenluetke10-beep8d194fbea083
diff --git a/jarvis/ui/web/frontend/src/components/friends/ChatThread.tsx b/jarvis/ui/web/frontend/src/components/friends/ChatThread.tsx
index c8ebb803da..def94a9abb 100644
--- a/jarvis/ui/web/frontend/src/components/friends/ChatThread.tsx
+++ b/jarvis/ui/web/frontend/src/components/friends/ChatThread.tsx
@@ -1,7 +1,9 @@
-import { useEffect, useRef, useState, type FormEvent } from "react";
+import { useLayoutEffect, useState, type FormEvent } from "react";
import { Loader2, Send } from "lucide-react";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { ScrollToEndButton } from "@/components/ui/scroll-to-end-button";
+import { useStickToBottom } from "@/hooks/useStickToBottom";
import { useT } from "@/i18n";
import {
useFriendMessages,
@@ -26,16 +28,15 @@ export function ChatThread({ friend }: { friend: FriendDetail }) {
const messages = useFriendMessages(friend.id);
const send = useSendFriendMessage();
const [draft, setDraft] = useState("");
- const scrollRef = useRef<HTMLDivElement | null>(null);
const list = messages.data ?? [];
const hasChannel = friend.channels.length > 0;
- useEffect(() => {
- const el = scrollRef.current;
- if (!el) return;
- el.scrollTop = el.scrollHeight;
- }, [list.length]);
+ // This used to set scrollTop on the CONTENT div inside the ScrollArea, which
+ // does not scroll — so the thread never moved at all. The rule now lives in
+ // one place and lands on the actual viewport (hooks/useStickToBottom).
+ const { rootRef, contentRef, atEnd, jumpToEnd, follow } = useStickToBottom();
+ useLayoutEffect(follow, [follow, list.length]);
function handleSubmit(e: FormEvent) {
e.preventDefault();
@@ -65,8 +66,8 @@ export function ChatThread({ friend }: { friend: FriendDetail }) {
{list.length === 0 ? (
<EmptyThread hasChannel={hasChannel} />
) : (
- <ScrollArea className="h-full">
- <div ref={scrollRef} className="space-y-3 px-5 py-4">
+ <ScrollArea ref={rootRef} className="h-full">
+ <div ref={contentRef} className="space-y-3 px-5 py-4">
{list.map((m, idx) => (
<FriendMessageBubble key={`${m.timestamp_ns}-${idx}`} message={m} />
))}
@@ -77,8 +78,9 @@ export function ChatThread({ friend }: { friend: FriendDetail }) {
<form
onSubmit={handleSubmit}
- className="flex items-center gap-2 border-t border-border bg-card/30 px-5 py-3"
+ className="relative flex items-center gap-2 border-t border-border bg-card/30 px-5 py-3"
>
+ {list.length > 0 && !atEnd && <ScrollToEndButton onClick={jumpToEnd} />}
<input
type="text"
value={draft}
diff --git a/jarvis/ui/web/frontend/src/components/home/VoiceStage.test.tsx b/jarvis/ui/web/frontend/src/components/home/VoiceStage.test.tsx
index ffe2104cbc..30532cf82d 100644
--- a/jarvis/ui/web/frontend/src/components/home/VoiceStage.test.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/VoiceStage.test.tsx
@@ -2,7 +2,8 @@ import { act, cleanup, fireEvent, render as rtlRender, screen } from "@testing-l
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import { afterEach, describe, expect, it, vi } from "vitest";
-import { NEAR_END_PX, VoiceStage, hintFor, isNearEnd, waveformPhase } from "@/components/home/VoiceStage";
+import { VoiceStage, hintFor, waveformPhase } from "@/components/home/VoiceStage";
+import { NEAR_END_PX, isNearEnd } from "@/hooks/useStickToBottom";
import { stateKey } from "@/components/home/JarvisBar";
import { greetingKey } from "@/components/home/Greeting";
import { useHomeStore } from "@/store/home";
diff --git a/jarvis/ui/web/frontend/src/components/home/VoiceStage.tsx b/jarvis/ui/web/frontend/src/components/home/VoiceStage.tsx
index 4e5b13ac9c..a42d4d84b0 100644
--- a/jarvis/ui/web/frontend/src/components/home/VoiceStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/VoiceStage.tsx
@@ -1,15 +1,16 @@
-import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
-import { ArrowDown } from "lucide-react";
+import { useLayoutEffect, useMemo } from "react";
import { useEventStore, type VoiceState } from "@/store/events";
import { useHomeStore } from "@/store/home";
import type { WaveformPhase } from "@/components/overlay/VoiceWaveform";
import { useVoiceCall } from "@/components/agentic/useVoiceCall";
import { useVoiceReadiness } from "@/hooks/useVoiceReadiness";
+import { useStickToBottom } from "@/hooks/useStickToBottom";
import { useWakeWord } from "@/hooks/useWakeWord";
import { fill, useT } from "@/i18n";
import { cn } from "@/lib/utils";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { ScrollToEndButton } from "@/components/ui/scroll-to-end-button";
import { Greeting } from "@/components/home/Greeting";
import { JarvisBar } from "@/components/home/JarvisBar";
import { TurnSteps, traceWorthShowing } from "@/components/home/TurnSteps";
@@ -36,10 +37,11 @@ import { traceModel } from "@/lib/thinkingSteps";
* steps render between your words and the answer — live while the turn runs,
* folded afterwards (components/home/TurnSteps).
*
- * Scrolling follows the Claude app. New output pulls the view along ONLY
- * while the view is already at the end; scrolled up to read something, you
- * keep your place while the conversation goes on below, and a button over
- * the bar takes you back to the end. Nothing yanks the page out from under
+ * Scrolling follows the Claude app, through the rule every conversation
+ * surface here shares (hooks/useStickToBottom): new output pulls the view
+ * along ONLY while the view is already at the end; scrolled up to read
+ * something, you keep your place while the conversation goes on below, and a
+ * button over the bar takes you back. Nothing yanks the page out from under
* someone mid-sentence.
*/
export function VoiceStage() {
@@ -75,61 +77,8 @@ export function VoiceStage() {
: "";
const hasLines = lines.length > 0 || Boolean(liveLine) || Boolean(liveAnswer);
- const rootRef = useRef<HTMLDivElement | null>(null);
- const columnRef = useRef<HTMLDivElement | null>(null);
- // Whether new output pulls the view along. A ref, not state: the auto-scroll
- // below runs in a layout effect and must read the CURRENT answer, not the
- // one a re-render would deliver a frame later. `atEnd` mirrors it for the
- // button, which only has to be right by the next paint.
- const stickRef = useRef(true);
- const [atEnd, setAtEnd] = useState(true);
-
- const jumpToEnd = useCallback(() => {
- const viewport = viewportOf(rootRef.current);
- if (!viewport) return;
- stickRef.current = true;
- setAtEnd(true);
- if (!prefersReducedMotion() && typeof viewport.scrollTo === "function") {
- viewport.scrollTo({ top: viewport.scrollHeight, behavior: "smooth" });
- } else {
- viewport.scrollTop = viewport.scrollHeight;
- }
- }, []);
-
- // One listener answers both questions: does new output pull the view along,
- // and is the "back to the end" button needed.
- useEffect(() => {
- const viewport = viewportOf(rootRef.current);
- if (!viewport) return;
- const read = () => {
- const near = isNearEnd(viewport.scrollTop, viewport.scrollHeight, viewport.clientHeight);
- stickRef.current = near;
- setAtEnd(near);
- };
- read();
- viewport.addEventListener("scroll", read, { passive: true });
- return () => viewport.removeEventListener("scroll", read);
- }, [hasLines]);
-
- useLayoutEffect(() => {
- const viewport = viewportOf(rootRef.current);
- if (!viewport || !stickRef.current) return;
- viewport.scrollTop = viewport.scrollHeight;
- }, [lines, liveLine, liveAnswer]);
-
- // An answer and its steps grow WITHOUT a new line arriving, so the effect
- // above never fires for them; the column's own size is the honest signal
- // where the platform has ResizeObserver.
- useEffect(() => {
- const column = columnRef.current;
- const viewport = viewportOf(rootRef.current);
- if (!column || !viewport || typeof ResizeObserver === "undefined") return;
- const ro = new ResizeObserver(() => {
- if (stickRef.current) viewport.scrollTop = viewport.scrollHeight;
- });
- ro.observe(column);
- return () => ro.disconnect();
- }, [hasLines]);
+ const { rootRef, contentRef, atEnd, jumpToEnd, follow } = useStickToBottom();
+ useLayoutEffect(follow, [follow, lines, liveLine, liveAnswer]);
const phase = waveformPhase(voiceState, connected);
const hint = hintFor({ connected, warming, connecting, voiceState, wakePhrase, t });
@@ -157,7 +106,7 @@ export function VoiceStage() {
>
<ScrollArea ref={rootRef} className="min-h-0 w-full flex-1" data-testid="voice-transcript">
<div
- ref={columnRef}
+ ref={contentRef}
className="mx-auto flex w-full max-w-[760px] flex-col gap-3 px-6 pb-4 pt-6"
aria-live="polite"
>
@@ -190,52 +139,13 @@ export function VoiceStage() {
</ScrollArea>
<div className="relative w-full max-w-[760px] px-6 pb-6 pt-2">
- {!atEnd && (
- <button
- type="button"
- onClick={jumpToEnd}
- data-testid="voice-scroll-end"
- aria-label={t("home.transcript_to_end")}
- title={t("home.transcript_to_end")}
- className={cn(
- "absolute -top-3 left-1/2 z-10 flex h-8 w-8 -translate-x-1/2 items-center justify-center",
- "rounded-full border border-border bg-card/95 text-muted-foreground shadow-md backdrop-blur",
- "transition-colors hover:border-primary/40 hover:text-foreground",
- "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
- )}
- >
- <ArrowDown aria-hidden className="h-4 w-4" />
- </button>
- )}
+ {!atEnd && <ScrollToEndButton onClick={jumpToEnd} testId="voice-scroll-end" />}
<JarvisBar phase={phase} hint={hint} />
</div>
</div>
);
}
-/**
- * Within this many pixels of the bottom counts as "at the end", so sub-pixel
- * rounding — or the half line a growing answer adds between two frames —
- * never reads as "they scrolled away".
- */
-export const NEAR_END_PX = 72;
-
-export function isNearEnd(scrollTop: number, scrollHeight: number, clientHeight: number): boolean {
- return scrollHeight - scrollTop - clientHeight <= NEAR_END_PX;
-}
-
-/** Radix renders the scrolling element as the viewport inside our ScrollArea root. */
-function viewportOf(root: HTMLElement | null): HTMLElement | null {
- if (!root) return null;
- return (root.querySelector("[data-radix-scroll-area-viewport]") as HTMLElement | null) ?? root;
-}
-
-function prefersReducedMotion(): boolean {
- return typeof window !== "undefined" && typeof window.matchMedia === "function"
- ? window.matchMedia("(prefers-reduced-motion: reduce)").matches
- : false;
-}
-
/**
* One line of the lane. A LIVE line (words still being said, an answer still
* being produced) is muted and italic with a cursor; the finished line it
diff --git a/jarvis/ui/web/frontend/src/components/home/VoiceThreadStage.tsx b/jarvis/ui/web/frontend/src/components/home/VoiceThreadStage.tsx
index a6c80a43b9..71d487d9d4 100644
--- a/jarvis/ui/web/frontend/src/components/home/VoiceThreadStage.tsx
+++ b/jarvis/ui/web/frontend/src/components/home/VoiceThreadStage.tsx
@@ -1,9 +1,11 @@
-import { useEffect, useMemo, useRef } from "react";
+import { useLayoutEffect, useMemo } from "react";
import { AudioLines, Mic } from "lucide-react";
import { useEventStore, type ChatMessage } from "@/store/events";
import { useHomeStore } from "@/store/home";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { ScrollToEndButton } from "@/components/ui/scroll-to-end-button";
+import { useStickToBottom } from "@/hooks/useStickToBottom";
import { ThoughtTraceDisclosure } from "@/components/ThinkingTrace";
import { transcriptFromMessages } from "@/lib/homeTranscript";
import { fill, useT } from "@/i18n";
@@ -37,11 +39,11 @@ export function VoiceThreadStage() {
[activeThreadId, conversations],
);
- const endRef = useRef<HTMLDivElement | null>(null);
- // A reopened thread lands at its end, where the conversation stopped.
- useEffect(() => {
- endRef.current?.scrollIntoView({ block: "end" });
- }, [activeThreadId, messages.length]);
+ // A reopened thread lands at its end, where the conversation stopped — but
+ // a reader who has scrolled up into it stays there when the rest of a long
+ // thread finishes loading (hooks/useStickToBottom).
+ const { rootRef, contentRef, atEnd, jumpToEnd, follow } = useStickToBottom();
+ useLayoutEffect(follow, [follow, activeThreadId, messages.length]);
const continueByVoice = () => {
seedTranscript(transcriptFromMessages(messages));
@@ -54,8 +56,11 @@ export function VoiceThreadStage() {
data-testid="voice-thread-stage"
data-thread={activeThreadId ?? ""}
>
- <ScrollArea className="min-h-0 w-full flex-1">
- <div className="mx-auto flex w-full max-w-[760px] flex-col gap-4 px-6 pb-6 pt-8">
+ <ScrollArea ref={rootRef} className="min-h-0 w-full flex-1">
+ <div
+ ref={contentRef}
+ className="mx-auto flex w-full max-w-[760px] flex-col gap-4 px-6 pb-6 pt-8"
+ >
<header className="flex items-center gap-2.5 border-b border-border pb-3">
<span className="flex h-7 w-7 shrink-0 items-center justify-center rounded-lg border border-border bg-secondary/50">
<Mic aria-hidden className="h-3.5 w-3.5 text-primary" />
@@ -77,11 +82,11 @@ export function VoiceThreadStage() {
) : (
messages.map((m) => <SpokenTurn key={m.id} message={m} />)
)}
- <div ref={endRef} />
</div>
</ScrollArea>
- <div className="w-full max-w-[760px] px-6 pb-5 pt-2">
+ <div className="relative w-full max-w-[760px] px-6 pb-5 pt-2">
+ {messages.length > 0 && !atEnd && <ScrollToEndButton onClick={jumpToEnd} />}
<div className="flex items-center gap-3 rounded-2xl border border-border bg-card/60 px-4 py-3">
<p className="min-w-0 flex-1 text-xs leading-relaxed text-muted-foreground">
{t("voice_thread.read_only")}
diff --git a/jarvis/ui/web/frontend/src/components/ui/scroll-to-end-button.tsx b/jarvis/ui/web/frontend/src/components/ui/scroll-to-end-button.tsx
new file mode 100644
index 0000000000..3cd7d3a0ed
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/components/ui/scroll-to-end-button.tsx
@@ -0,0 +1,47 @@
+import { ArrowDown } from "lucide-react";
+
+import { useT } from "@/i18n";
+import { cn } from "@/lib/utils";
+
+/**
+ * The way back to the newest message, for a surface that follows the rule in
+ * hooks/useStickToBottom.
+ *
+ * Render it only while `atEnd` is false — a permanent one would be a control
+ * that does nothing most of the time. It floats over whatever sits under the
+ * conversation (a composer, the Jarvis bar), so its parent needs `relative`.
+ *
+ * The label lives under `home.` because that is where the voice stage that
+ * first needed it put it; it says nothing home-specific and every surface
+ * shares the one string rather than translating the same sentence twice.
+ */
+export function ScrollToEndButton({
+ onClick,
+ className,
+ testId = "scroll-to-end",
+}: {
+ onClick: () => void;
+ className?: string;
+ testId?: string;
+}) {
+ const t = useT();
+ const label = t("home.transcript_to_end");
+ return (
+ <button
+ type="button"
+ onClick={onClick}
+ data-testid={testId}
+ aria-label={label}
+ title={label}
+ className={cn(
+ "absolute -top-3 left-1/2 z-10 flex h-8 w-8 -translate-x-1/2 items-center justify-center",
+ "rounded-full border border-border bg-card/95 text-muted-foreground shadow-md backdrop-blur",
+ "transition-colors hover:border-primary/40 hover:text-foreground",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring",
+ className,
+ )}
+ >
+ <ArrowDown aria-hidden className="h-4 w-4" />
+ </button>
+ );
+}
diff --git a/jarvis/ui/web/frontend/src/hooks/useStickToBottom.test.tsx b/jarvis/ui/web/frontend/src/hooks/useStickToBottom.test.tsx
new file mode 100644
index 0000000000..ef10726bb1
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useStickToBottom.test.tsx
@@ -0,0 +1,121 @@
+import { act, cleanup, fireEvent, render, screen } from "@testing-library/react";
+import { afterEach, describe, expect, it } from "vitest";
+import { useLayoutEffect, useState } from "react";
+
+import { NEAR_END_PX, isNearEnd, scrollViewportOf, useStickToBottom } from "@/hooks/useStickToBottom";
+
+afterEach(cleanup);
+
+/** jsdom lays nothing out, so the scroller is told how tall it "is". */
+function measure(el: HTMLElement, scrollTop: number, scrollHeight: number, clientHeight: number) {
+ Object.defineProperty(el, "scrollHeight", { value: scrollHeight, configurable: true });
+ Object.defineProperty(el, "clientHeight", { value: clientHeight, configurable: true });
+ el.scrollTop = scrollTop;
+}
+
+/** A minimal surface that grows, like a chat thread does. */
+function Thread({ initial = 3 }: { initial?: number }) {
+ const [count, setCount] = useState(initial);
+ const { rootRef, contentRef, atEnd, jumpToEnd, follow } = useStickToBottom();
+ useLayoutEffect(follow, [follow, count]);
+ return (
+ <div>
+ <div ref={rootRef} data-testid="scroller" style={{ overflowY: "auto" }}>
+ <div ref={contentRef}>
+ {Array.from({ length: count }, (_, i) => (
+ <p key={i}>message {i}</p>
+ ))}
+ </div>
+ </div>
+ <button type="button" onClick={() => setCount((n) => n + 1)}>
+ add
+ </button>
+ {!atEnd && (
+ <button type="button" data-testid="back" onClick={jumpToEnd}>
+ back
+ </button>
+ )}
+ </div>
+ );
+}
+
+describe("isNearEnd", () => {
+ it("treats the last stretch above the bottom as being at the end", () => {
+ expect(isNearEnd(900, 1000, 100)).toBe(true);
+ expect(isNearEnd(900 - NEAR_END_PX, 1000, 100)).toBe(true);
+ expect(isNearEnd(900 - NEAR_END_PX - 1, 1000, 100)).toBe(false);
+ expect(isNearEnd(0, 1000, 100)).toBe(false);
+ });
+
+ it("calls content shorter than its viewport already at the end", () => {
+ expect(isNearEnd(0, 100, 400)).toBe(true);
+ });
+});
+
+describe("scrollViewportOf", () => {
+ it("finds the Radix viewport inside a root, and falls back to the root itself", () => {
+ const root = document.createElement("div");
+ expect(scrollViewportOf(root)).toBe(root);
+ const viewport = document.createElement("div");
+ viewport.setAttribute("data-radix-scroll-area-viewport", "");
+ root.appendChild(viewport);
+ expect(scrollViewportOf(root)).toBe(viewport);
+ expect(scrollViewportOf(null)).toBeNull();
+ });
+});
+
+describe("useStickToBottom", () => {
+ it("follows new content while the view sits at the end", () => {
+ render(<Thread />);
+ const scroller = screen.getByTestId("scroller");
+ measure(scroller, 950, 1000, 50);
+ act(() => {
+ fireEvent.scroll(scroller);
+ });
+
+ measure(scroller, 950, 2000, 50);
+ act(() => {
+ fireEvent.click(screen.getByText("add"));
+ });
+ expect(scroller.scrollTop).toBe(2000);
+ });
+
+ it("leaves a reader who scrolled up exactly where they are", () => {
+ render(<Thread />);
+ const scroller = screen.getByTestId("scroller");
+ measure(scroller, 100, 1000, 50);
+ act(() => {
+ fireEvent.scroll(scroller);
+ });
+
+ act(() => {
+ fireEvent.click(screen.getByText("add"));
+ });
+ expect(scroller.scrollTop).toBe(100);
+ });
+
+ it("offers the way back only while the reader is away from the end", () => {
+ render(<Thread />);
+ const scroller = screen.getByTestId("scroller");
+ expect(screen.queryByTestId("back")).toBeNull();
+
+ measure(scroller, 100, 1000, 50);
+ act(() => {
+ fireEvent.scroll(scroller);
+ });
+ expect(screen.getByTestId("back")).toBeTruthy();
+
+ // Taking it resumes following, so the button retires itself.
+ act(() => {
+ fireEvent.click(screen.getByTestId("back"));
+ });
+ expect(scroller.scrollTop).toBe(1000);
+ expect(screen.queryByTestId("back")).toBeNull();
+
+ measure(scroller, 1000, 2000, 50);
+ act(() => {
+ fireEvent.click(screen.getByText("add"));
+ });
+ expect(scroller.scrollTop).toBe(2000);
+ });
+});
diff --git a/jarvis/ui/web/frontend/src/hooks/useStickToBottom.ts b/jarvis/ui/web/frontend/src/hooks/useStickToBottom.ts
new file mode 100644
index 0000000000..b393a23d10
--- /dev/null
+++ b/jarvis/ui/web/frontend/src/hooks/useStickToBottom.ts
@@ -0,0 +1,122 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+
+/**
+ * "Follow the newest, unless the reader is reading" — the scrolling rule every
+ * conversation surface owes its reader.
+ *
+ * The wrong version is one line and looks right: scroll to the end whenever
+ * anything arrives. It reads fine while you watch an answer come in and is
+ * unusable the moment you want to look back — a streaming answer fires an
+ * update per token, so each attempt to scroll up is undone before the next
+ * frame. The rule instead: new output pulls the view along ONLY while the view
+ * is already at the end. Scrolled up, the reader keeps their place, and
+ * `atEnd` turns false so the surface can offer a way back.
+ *
+ * Use it for anything that GROWS while being read — chat threads, transcripts,
+ * live logs. A view that only ever lands at its end once (a stored thread
+ * opened for reading) does not need this; a plain scroll on load says that
+ * more honestly.
+ *
+ * const { rootRef, contentRef, atEnd, jumpToEnd } = useStickToBottom();
+ * <ScrollArea ref={rootRef}><div ref={contentRef}>…</div></ScrollArea>
+ * {!atEnd && <button onClick={jumpToEnd}>…</button>}
+ *
+ * `rootRef` goes on the scrolling element or on a Radix ScrollArea root —
+ * either is resolved. `contentRef` goes on the growing child, which is what
+ * makes an answer that grows without a new item still pull the view along;
+ * where the platform has no ResizeObserver, call `follow()` from an effect of
+ * your own instead.
+ */
+export function useStickToBottom() {
+ // A ref AND a state for the same node on purpose: `follow` must read the
+ // current element synchronously inside a layout effect, while the listeners
+ // below have to re-attach when the element appears or is replaced — which
+ // only a state dependency can trigger.
+ const rootElRef = useRef<HTMLElement | null>(null);
+ const [rootEl, setRootEl] = useState<HTMLElement | null>(null);
+ const contentElRef = useRef<HTMLElement | null>(null);
+ const [contentEl, setContentEl] = useState<HTMLElement | null>(null);
+ const stickRef = useRef(true);
+ const [atEnd, setAtEnd] = useState(true);
+
+ const rootRef = useCallback((node: HTMLElement | null) => {
+ rootElRef.current = node;
+ setRootEl(node);
+ }, []);
+ const contentRef = useCallback((node: HTMLElement | null) => {
+ contentElRef.current = node;
+ setContentEl(node);
+ }, []);
+
+ /** Pull the view to the end — but only if it was already there. */
+ const follow = useCallback(() => {
+ const viewport = scrollViewportOf(rootElRef.current);
+ if (!viewport || !stickRef.current) return;
+ viewport.scrollTop = viewport.scrollHeight;
+ }, []);
+
+ /** Take the reader back to the end, and follow again from there. */
+ const jumpToEnd = useCallback(() => {
+ const viewport = scrollViewportOf(rootElRef.current);
+ if (!viewport) return;
+ stickRef.current = true;
+ setAtEnd(true);
+ if (!prefersReducedMotion() && typeof viewport.scrollTo === "function") {
+ viewport.scrollTo({ top: viewport.scrollHeight, behavior: "smooth" });
+ } else {
+ viewport.scrollTop = viewport.scrollHeight;
+ }
+ }, []);
+
+ // One listener answers both questions: does new output pull the view along,
+ // and does the surface need to offer a way back.
+ useEffect(() => {
+ const viewport = scrollViewportOf(rootEl);
+ if (!viewport) return;
+ const read = () => {
+ const near = isNearEnd(viewport.scrollTop, viewport.scrollHeight, viewport.clientHeight);
+ stickRef.current = near;
+ setAtEnd(near);
+ };
+ read();
+ viewport.addEventListener("scroll", read, { passive: true });
+ return () => viewport.removeEventListener("scroll", read);
+ }, [rootEl]);
+
+ // An answer grows WITHOUT a new item arriving, so no render-driven effect
+ // fires for it; the content's own size is the honest signal.
+ useEffect(() => {
+ const viewport = scrollViewportOf(rootEl);
+ if (!viewport || !contentEl || typeof ResizeObserver === "undefined") return;
+ const ro = new ResizeObserver(() => {
+ if (stickRef.current) viewport.scrollTop = viewport.scrollHeight;
+ });
+ ro.observe(contentEl);
+ return () => ro.disconnect();
+ }, [rootEl, contentEl]);
+
+ return { rootRef, contentRef, atEnd, jumpToEnd, follow };
+}
+
+/**
+ * Within this many pixels of the bottom counts as "at the end", so sub-pixel
+ * rounding — or the half line a growing answer adds between two frames —
+ * never reads as "they scrolled away".
+ */
+export const NEAR_END_PX = 72;
+
+export function isNearEnd(scrollTop: number, scrollHeight: number, clientHeight: number): boolean {
+ return scrollHeight - scrollTop - clientHeight <= NEAR_END_PX;
+}
+
+/** Radix renders the scrolling element as a viewport inside the ScrollArea root. */
+export function scrollViewportOf(root: HTMLElement | null): HTMLElement | null {
+ if (!root) return null;
+ return (root.querySelector("[data-radix-scroll-area-viewport]") as HTMLElement | null) ?? root;
+}
+
+function prefersReducedMotion(): boolean {
+ return typeof window !== "undefined" && typeof window.matchMedia === "function"
+ ? window.matchMedia("(prefers-reduced-motion: reduce)").matches
+ : false;
+}
diff --git a/jarvis/ui/web/frontend/src/views/ChatsView.tsx b/jarvis/ui/web/frontend/src/views/ChatsView.tsx
index ce4fcd11fd..024f9f43cd 100644
--- a/jarvis/ui/web/frontend/src/views/ChatsView.tsx
+++ b/jarvis/ui/web/frontend/src/views/ChatsView.tsx
@@ -1,4 +1,4 @@
-import { useCallback, useEffect, useRef, type ReactNode } from "react";
+import { useCallback, useEffect, useLayoutEffect, type ReactNode } from "react";
import { MessageSquare, Mic, Plus, Trash2, AudioLines } from "lucide-react";
import {
useEventStore,
@@ -7,12 +7,14 @@ import {
type ConversationSummary,
} from "@/store/events";
import { ScrollArea } from "@/components/ui/scroll-area";
+import { ScrollToEndButton } from "@/components/ui/scroll-to-end-button";
import { ChatInput } from "@/components/ChatInput";
import { MascotGigi } from "@/components/MascotGigi";
import { ThinkingTrace, ThoughtTraceDisclosure } from "@/components/ThinkingTrace";
import { cn } from "@/lib/utils";
import { useT } from "@/i18n";
import { useResizablePane } from "@/hooks/useResizablePane";
+import { useStickToBottom } from "@/hooks/useStickToBottom";
import { PaneResizer } from "@/components/layout/PaneResizer";
import { useVoiceReadiness } from "@/hooks/useVoiceReadiness";
import {
@@ -46,7 +48,6 @@ export function ChatsView({
const setActiveConversation = useEventStore((s) => s.setActiveConversation);
const setMessages = useEventStore((s) => s.setMessages);
const pushToast = useEventStore((s) => s.pushToast);
- const endRef = useRef<HTMLDivElement | null>(null);
// Drag-resizable history pane. Width persists across reloads (localStorage);
// bounds keep it from collapsing or swallowing the chat column.
@@ -57,9 +58,11 @@ export function ChatsView({
max: 560,
});
- useEffect(() => {
- endRef.current?.scrollIntoView({ behavior: "smooth", block: "end" });
- }, [messages.length, chatThinking]);
+ // Follow the answer, but never drag the reader back: `chatThinking` ticks
+ // through a whole reply, so an unconditional scroll here made it impossible
+ // to look back at anything while the assistant was still writing.
+ const { rootRef, contentRef, atEnd, jumpToEnd, follow } = useStickToBottom();
+ useLayoutEffect(follow, [follow, messages.length, chatThinking]);
const refresh = useCallback(async () => {
try {
@@ -177,19 +180,19 @@ export function ChatsView({
{!hasContent ? (
<EmptyState />
) : (
- <ScrollArea className="h-full">
- <div className="space-y-3 px-6 py-4">
+ <ScrollArea ref={rootRef} className="h-full">
+ <div ref={contentRef} className="space-y-3 px-6 py-4">
{messages.map((m) => (
<MessageBubble key={m.id} message={m} />
))}
{chatThinking && <ThinkingTrace />}
- <div ref={endRef} />
</div>
</ScrollArea>
)}
</div>
- <div className="border-t border-border px-6 py-4">
+ <div className="relative border-t border-border px-6 py-4">
+ {hasContent && !atEnd && <ScrollToEndButton onClick={jumpToEnd} />}
<ChatInput />
</div>
</div>