(null);
+ /// Whether the view should follow new content.
+ ///
+ /// Starts true so opening a conversation lands on the newest message, and
+ /// stays true until the reader scrolls up — following unconditionally would
+ /// yank someone out of the history they were reading.
+ const followTail = useRef(true);
const speechRecognition = useRef<{
start: () => void;
stop: () => void;
@@ -164,6 +171,38 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
setSlotError((current) => ({ ...current, [slot]: message }));
};
+ /// Distance from the bottom that still counts as "reading the newest".
+ const TAIL_THRESHOLD_PX = 80;
+
+ const scrollToTail = useCallback((behavior: ScrollBehavior) => {
+ const list = messageListRef.current;
+ if (!list) return;
+ // `scrollTo` carries the smooth behaviour, but it is not universally
+ // available — jsdom has no implementation at all — so fall back to the
+ // property, which every engine supports.
+ if (typeof list.scrollTo === "function") {
+ list.scrollTo({ top: list.scrollHeight, behavior });
+ } else {
+ list.scrollTop = list.scrollHeight;
+ }
+ }, []);
+
+ // Follow the tail whenever the rendered messages change: a sent message, a
+ // streamed delta, or a freshly loaded history. The list had no scroll code at
+ // all, so every send left the new message below the fold.
+ useEffect(() => {
+ if (!followTail.current) return;
+ scrollToTail("smooth");
+ }, [visibleMessages, scrollToTail]);
+
+ // Opening a conversation, or switching slot or session, starts at the newest
+ // message rather than at the top.
+ useEffect(() => {
+ followTail.current = true;
+ const frame = window.requestAnimationFrame(() => scrollToTail("auto"));
+ return () => window.cancelAnimationFrame(frame);
+ }, [selectedSlot, historySessionId, scrollToTail]);
+
useEffect(() => {
// `listen()` resolves after the effect may already have been cleaned up.
// Assigning the unregister function unconditionally dropped it in that
@@ -761,6 +800,13 @@ export function ChatPanel({ fixedSlot }: ChatPanelProps) {
{
+ const list = event.currentTarget;
+ const distanceFromTail =
+ list.scrollHeight - list.scrollTop - list.clientHeight;
+ followTail.current = distanceFromTail <= TAIL_THRESHOLD_PX;
+ }}
role="tabpanel"
aria-label={`${selectedSlot} messages`}
aria-busy={sending[selectedSlot]}