Skip to content

Soul-driven AI agent with permission-hardened tools, token budgets, and multi-channel access. Runs 24/7 from CLI, Telegram or More.

fix(desktop): scroll up while Mercury is still answering

Salman Qureshiab7b465725c0
diff --git a/apps/desktop/src/views/chat/Conversation.tsx b/apps/desktop/src/views/chat/Conversation.tsx
index 645d26f3..be6f8e0e 100644
--- a/apps/desktop/src/views/chat/Conversation.tsx
+++ b/apps/desktop/src/views/chat/Conversation.tsx
@@ -1,5 +1,7 @@
+import { ArrowDown } from "lucide-react";
import { useEffect, useLayoutEffect, useRef, useState, type ReactNode } from "react";
import { PlanCard } from "./PlanCard";
+import { jumpLabel, useFollowBottom } from "./follow";
import { cx } from "~/lib/cx";
import { useConversation, useConversationStore } from "~/app/conversation";
import { answerPrompt } from "~/app/events";
@@ -29,11 +31,26 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
const live = useConversation((s) => s.live);
const stopping = useConversation((s) => s.stopping);
const scroller = useRef<HTMLDivElement>(null);
- const stickToBottom = useRef(true);
+ const content = useRef<HTMLDivElement>(null);
const [visible, setVisible] = useState(PAGE);
const prepend = useRef<{ height: number; top: number } | null>(null);
+ const follow = useFollowBottom(scroller, content, activeId);
+ const busy = !!streaming || stopping || agent === "thinking" || agent === "working" || agent === "streaming";
- useEffect(() => { setVisible(PAGE); stickToBottom.current = true; }, [activeId]);
+ // While the reader is up the page: count what arrived, and notice the reply ending.
+ const [away, setAway] = useState<{ since: number; wasBusy: boolean } | null>(null);
+ useEffect(() => {
+ setAway(follow.following ? null : (a) => a ?? { since: messages.length, wasBusy: busy });
+ }, [follow.following]); // eslint-disable-line react-hooks/exhaustive-deps
+ const unseen = away ? messages.slice(away.since).filter((m) => m.role !== "user").length : 0;
+ const finished = !!away?.wasBusy && !busy;
+
+ // Sending a message follows again: you want to see the answer.
+ const lastId = messages[messages.length - 1]?.id;
+ const lastRole = messages[messages.length - 1]?.role;
+ useEffect(() => { if (lastRole === "user") follow.jump(false); }, [lastId]); // eslint-disable-line react-hooks/exhaustive-deps
+
+ useEffect(() => { setVisible(PAGE); }, [activeId]);
const shown = messages.length > visible ? messages.slice(messages.length - visible) : messages;
// Only your last message can be undone.
const lastYours = [...messages].reverse().find((m) => m.role === "user")?.id;
@@ -51,12 +68,6 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
prepend.current = { height: el.scrollHeight, top: el.scrollTop };
setVisible((v) => v + PAGE);
}
- useEffect(() => {
- const el = scroller.current;
- if (!el || !stickToBottom.current) return;
- el.scrollTop = el.scrollHeight;
- }, [messages, streaming, prompts.length, loading, live]);
-
const isEmpty = !activeId && messages.length === 0 && !streaming;
return (
@@ -66,20 +77,22 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
<StateLabel state={agent} detail={step?.tool ? `${step.tool}${step.total ? ` ${step.current}/${step.total}` : ""}` : undefined} />
</header>
+ <div className="relative flex min-h-0 flex-1 flex-col">
<div
ref={scroller}
+ tabIndex={-1}
onScroll={(e) => {
const el = e.currentTarget;
- stickToBottom.current = el.scrollHeight - el.scrollTop - el.clientHeight < 80;
+ follow.onScroll();
if (el.scrollTop < 160 && hiddenCount > 0 && !prepend.current) loadEarlier();
}}
- className={cx("min-h-0 flex-1 overflow-y-auto overflow-x-hidden", isEmpty && "flex flex-col")}
+ className={cx("min-h-0 flex-1 overflow-y-auto overflow-x-hidden outline-none", isEmpty && "flex flex-col")}
>
{/* Centred with auto margins, not justify-center: when the start screen
is taller than the window, justify-center pushes its top under the
header where it can't be scrolled to. Auto margins collapse instead. */}
{isEmpty ? <div className="m-auto flex w-full justify-center py-8">{empty}</div> : (
- <div className="mx-auto flex w-full min-w-0 max-w-[780px] flex-col gap-7 px-8 py-8 [&>*]:min-w-0">
+ <div ref={content} className="mx-auto flex w-full min-w-0 max-w-[780px] flex-col gap-7 px-8 py-8 [&>*]:min-w-0">
{loading && messages.length === 0 && <ThinkingDots label="Loading" />}
{hiddenCount > 0 && (
<button onClick={loadEarlier} className="self-center rounded-full border border-line px-3 py-1 text-xs text-ink3 hover:text-ink">
@@ -101,6 +114,19 @@ export function Conversation({ header, empty, composer }: { header: ReactNode; e
</div>
)}
</div>
+ {!follow.following && !isEmpty && (
+ <button
+ onClick={() => follow.jump()}
+ className="absolute bottom-4 left-1/2 flex h-8 -translate-x-1/2 items-center gap-2 rounded-full border border-line bg-surface px-3.5 text-xs font-medium text-ink2 shadow-md transition-colors hover:border-line-strong hover:text-ink"
+ aria-label="Jump to the latest message"
+ >
+ {busy && unseen === 0 ? <span className="h-1.5 w-1.5 animate-dot-pulse rounded-full bg-accent" aria-hidden="true" /> : null}
+ {unseen > 0 && <span className="h-1.5 w-1.5 rounded-full bg-blue" aria-hidden="true" />}
+ {jumpLabel({ busy, unseen, finished })}
+ <ArrowDown size={13} aria-hidden="true" />
+ </button>
+ )}
+ </div>
<PlanCard surface={composer.surface} />
<Composer {...composer} />
diff --git a/apps/desktop/src/views/chat/follow.test.ts b/apps/desktop/src/views/chat/follow.test.ts
new file mode 100644
index 00000000..08b1c269
--- /dev/null
+++ b/apps/desktop/src/views/chat/follow.test.ts
@@ -0,0 +1,12 @@
+import { describe, expect, it } from "vitest";
+import { jumpLabel } from "./follow";
+
+describe("jumpLabel", () => {
+ it("says what happened below while you read further up", () => {
+ expect(jumpLabel({ busy: true, unseen: 0, finished: false })).toBe("Mercury is writing");
+ expect(jumpLabel({ busy: false, unseen: 1, finished: true })).toBe("1 new message");
+ expect(jumpLabel({ busy: true, unseen: 3, finished: false })).toBe("3 new messages");
+ expect(jumpLabel({ busy: false, unseen: 0, finished: true })).toBe("Reply finished");
+ expect(jumpLabel({ busy: false, unseen: 0, finished: false })).toBe("Jump to latest");
+ });
+});
diff --git a/apps/desktop/src/views/chat/follow.ts b/apps/desktop/src/views/chat/follow.ts
new file mode 100644
index 00000000..19882bbb
--- /dev/null
+++ b/apps/desktop/src/views/chat/follow.ts
@@ -0,0 +1,117 @@
+import { useCallback, useEffect, useRef, useState, type RefObject } from "react";
+
+/**
+ * Follow the bottom of a streaming conversation, and stop the moment the
+ * reader scrolls up (wheel, trackpad, keys, scrollbar), the way ChatGPT and
+ * Codex do. Following again: back at the bottom, Jump, or sending a message.
+ *
+ * Decided by what the reader does, not by where the view is: a token every
+ * few milliseconds would otherwise pull a small scroll back down before it
+ * counted.
+ */
+
+/** Close enough to the bottom to count as "at the bottom". */
+const AT_BOTTOM_PX = 24;
+
+export interface Follow {
+ following: boolean;
+ /** Scroll to the newest and follow again. */
+ jump: (smooth?: boolean) => void;
+ onScroll: () => void;
+}
+
+export function useFollowBottom(scroller: RefObject<HTMLDivElement | null>, content: RefObject<HTMLDivElement | null>, resetKey: unknown): Follow {
+ const [following, setFollowing] = useState(true);
+ const followingRef = useRef(true);
+ /** Where we last put scrollTop ourselves, so our own scrolls aren't read as the reader's. */
+ const ours = useRef<number | null>(null);
+ /** A smooth jump is on its way down: its scrolls aren't the reader's. */
+ const jumping = useRef(false);
+
+ const set = useCallback((v: boolean) => {
+ if (followingRef.current === v) return;
+ followingRef.current = v;
+ setFollowing(v);
+ }, []);
+
+ const pin = useCallback(() => {
+ const el = scroller.current;
+ if (!el) return;
+ const top = el.scrollHeight - el.clientHeight;
+ if (Math.abs(el.scrollTop - top) < 1) return;
+ ours.current = top;
+ el.scrollTop = top;
+ }, [scroller]);
+
+ const jump = useCallback((smooth = true) => {
+ const el = scroller.current;
+ set(true);
+ if (!el) return;
+ if (smooth) {
+ ours.current = null;
+ jumping.current = true;
+ el.scrollTo({ top: el.scrollHeight, behavior: "smooth" });
+ } else pin();
+ }, [scroller, set, pin]);
+
+ // A new conversation opens at its newest message.
+ useEffect(() => { set(true); requestAnimationFrame(pin); }, [resetKey, set, pin]);
+
+ // Anything that grows the conversation (tokens, tool output, images
+ // loading, an approval) keeps it pinned while following.
+ useEffect(() => {
+ const el = content.current;
+ if (!el || typeof ResizeObserver === "undefined") return;
+ const ro = new ResizeObserver(() => { if (followingRef.current) pin(); });
+ ro.observe(el);
+ return () => ro.disconnect();
+ }, [content, pin, resetKey]);
+
+ // The reader moving up lets go at once.
+ useEffect(() => {
+ const el = scroller.current;
+ if (!el) return;
+ const up = () => { jumping.current = false; if (el.scrollHeight > el.clientHeight) set(false); };
+ const onWheel = (e: WheelEvent) => { if (e.deltaY < 0) up(); };
+ let touchY: number | null = null;
+ const onTouchStart = (e: TouchEvent) => { touchY = e.touches[0]?.clientY ?? null; };
+ const onTouchMove = (e: TouchEvent) => { const y = e.touches[0]?.clientY; if (touchY !== null && y !== undefined && y > touchY + 4) up(); };
+ const onKey = (e: KeyboardEvent) => {
+ // Only keys aimed at the conversation, not at the composer.
+ const t = e.target as HTMLElement | null;
+ if (t && (t.isContentEditable || /^(INPUT|TEXTAREA|SELECT)$/.test(t.tagName))) return;
+ if (["ArrowUp", "PageUp", "Home"].includes(e.key) || (e.key === " " && e.shiftKey)) up();
+ };
+ el.addEventListener("wheel", onWheel, { passive: true });
+ el.addEventListener("touchstart", onTouchStart, { passive: true });
+ el.addEventListener("touchmove", onTouchMove, { passive: true });
+ el.addEventListener("keydown", onKey);
+ return () => {
+ el.removeEventListener("wheel", onWheel);
+ el.removeEventListener("touchstart", onTouchStart);
+ el.removeEventListener("touchmove", onTouchMove);
+ el.removeEventListener("keydown", onKey);
+ };
+ }, [scroller, set]);
+
+ const onScroll = useCallback(() => {
+ const el = scroller.current;
+ if (!el) return;
+ const fromBottom = el.scrollHeight - el.scrollTop - el.clientHeight;
+ if (ours.current !== null && Math.abs(el.scrollTop - ours.current) < 2) { ours.current = null; return; }
+ if (fromBottom <= AT_BOTTOM_PX) { jumping.current = false; set(true); return; }
+ if (jumping.current) return;
+ // Dragging the scrollbar sends no wheel or key: any other scroll away from the bottom is the reader's.
+ if (fromBottom > AT_BOTTOM_PX * 4) set(false);
+ }, [scroller, set]);
+
+ return { following, jump, onScroll };
+}
+
+/** What the jump pill says while the reader is up the page. */
+export function jumpLabel({ busy, unseen, finished }: { busy: boolean; unseen: number; finished: boolean }): string {
+ if (unseen > 0) return `${unseen} new message${unseen === 1 ? "" : "s"}`;
+ if (busy) return "Mercury is writing";
+ if (finished) return "Reply finished";
+ return "Jump to latest";
+}