Compare commits

..
Author SHA1 Message Date
Julius Marminge 3031dfd122 Respect user scroll intent across wheel, pointer, and touch
- track wheel-up, pointer drag, and touch gestures before disabling auto-tail
- avoid false auto-scroll handoff caused by content height changes
- add pointer/touch handlers to message list for consistent scroll behavior
2026-02-19 16:17:58 -08:00
Julius Marminge 0cb4e75728 Preserve chat auto-scroll until user scrolls up
- Track last scroll position and content height to avoid disabling tail mode on new messages
- Stop auto-scroll immediately on upward mouse wheel input
- Keep chat pinned to bottom reliably while streaming
2026-02-19 16:04:42 -08:00
Julius Marminge 01accc005e Defer chat auto-scroll to animation frame
- Queue tail-to-bottom scrolling with `requestAnimationFrame` to avoid redundant scroll calls
- Preserve user scroll position by checking auto-scroll intent before running
- Cancel any pending frame on unmount to prevent stale callbacks
2026-02-19 15:51:14 -08:00
Julius Marminge 0d9c26810f Tighten chat auto-tail to true bottom position
- Replace near-bottom threshold logic with strict bottom epsilon detection
- Rename scroll helper to `isScrollContainerAtBottom` and cover overscroll in tests
- Auto-tail chat/worklog updates only while user remains at bottom
2026-02-19 01:42:40 -08:00
5 changed files with 154 additions and 190 deletions

No files matched your search

+26 -16
View File
@@ -1,11 +1,11 @@
import { describe, expect, it } from "vitest";
import { AUTO_SCROLL_BOTTOM_THRESHOLD_PX, isScrollContainerNearBottom } from "./chat-scroll";
import { AUTO_SCROLL_BOTTOM_EPSILON_PX, isScrollContainerAtBottom } from "./chat-scroll";
describe("isScrollContainerNearBottom", () => {
describe("isScrollContainerAtBottom", () => {
it("returns true when already at bottom", () => {
expect(
isScrollContainerNearBottom({
isScrollContainerAtBottom({
scrollTop: 600,
clientHeight: 400,
scrollHeight: 1_000,
@@ -13,31 +13,31 @@ describe("isScrollContainerNearBottom", () => {
).toBe(true);
});
it("returns true when within the auto-scroll threshold", () => {
it("returns true when within the bottom epsilon", () => {
expect(
isScrollContainerNearBottom({
scrollTop: 540,
isScrollContainerAtBottom({
scrollTop: 599,
clientHeight: 400,
scrollHeight: 1_000,
}),
).toBe(true);
});
it("returns false when the user is meaningfully above the bottom", () => {
it("returns false when the user is above the epsilon", () => {
expect(
isScrollContainerNearBottom({
scrollTop: 520,
isScrollContainerAtBottom({
scrollTop: 597,
clientHeight: 400,
scrollHeight: 1_000,
}),
).toBe(false);
});
it("clamps negative thresholds to zero", () => {
it("clamps negative epsilons to zero", () => {
expect(
isScrollContainerNearBottom(
isScrollContainerAtBottom(
{
scrollTop: 539,
scrollTop: 599,
clientHeight: 400,
scrollHeight: 1_000,
},
@@ -46,17 +46,27 @@ describe("isScrollContainerNearBottom", () => {
).toBe(false);
});
it("falls back to the default threshold for non-finite values", () => {
it("falls back to the default epsilon for non-finite values", () => {
expect(
isScrollContainerNearBottom(
isScrollContainerAtBottom(
{
scrollTop: 540,
scrollTop: 599,
clientHeight: 400,
scrollHeight: 1_000,
},
Number.NaN,
),
).toBe(true);
expect(AUTO_SCROLL_BOTTOM_THRESHOLD_PX).toBe(64);
expect(AUTO_SCROLL_BOTTOM_EPSILON_PX).toBe(2);
});
it("treats overscrolled values as bottom", () => {
expect(
isScrollContainerAtBottom({
scrollTop: 610,
clientHeight: 400,
scrollHeight: 1_000,
}),
).toBe(true);
});
});
+8 -8
View File
@@ -1,4 +1,4 @@
export const AUTO_SCROLL_BOTTOM_THRESHOLD_PX = 64;
export const AUTO_SCROLL_BOTTOM_EPSILON_PX = 2;
interface ScrollPosition {
scrollTop: number;
@@ -6,19 +6,19 @@ interface ScrollPosition {
scrollHeight: number;
}
export function isScrollContainerNearBottom(
export function isScrollContainerAtBottom(
position: ScrollPosition,
thresholdPx = AUTO_SCROLL_BOTTOM_THRESHOLD_PX,
epsilonPx = AUTO_SCROLL_BOTTOM_EPSILON_PX,
): boolean {
const threshold = Number.isFinite(thresholdPx)
? Math.max(0, thresholdPx)
: AUTO_SCROLL_BOTTOM_THRESHOLD_PX;
const epsilon = Number.isFinite(epsilonPx)
? Math.max(0, epsilonPx)
: AUTO_SCROLL_BOTTOM_EPSILON_PX;
const { scrollTop, clientHeight, scrollHeight } = position;
if (![scrollTop, clientHeight, scrollHeight].every(Number.isFinite)) {
return true;
}
const distanceFromBottom = scrollHeight - clientHeight - scrollTop;
return distanceFromBottom <= threshold;
const distanceFromBottom = Math.max(0, scrollHeight - clientHeight - scrollTop);
return distanceFromBottom <= epsilon;
}
+92 -12
View File
@@ -17,6 +17,9 @@ import {
type DragEvent,
type FormEvent,
type KeyboardEvent,
type PointerEvent,
type TouchEvent,
type WheelEvent,
memo,
type RefObject,
useCallback,
@@ -61,7 +64,7 @@ import {
formatElapsed,
formatTimestamp,
} from "../session-logic";
import { isScrollContainerNearBottom } from "../chat-scroll";
import { isScrollContainerAtBottom } from "../chat-scroll";
import { useStore } from "../store";
import { truncateTitle } from "../truncateTitle";
import {
@@ -402,6 +405,11 @@ export default function ChatView({ threadId }: ChatViewProps) {
>(() => readLastInvokedScriptByProjectFromStorage());
const messagesScrollRef = useRef<HTMLDivElement>(null);
const shouldAutoScrollRef = useRef(true);
const lastKnownScrollTopRef = useRef(0);
const isPointerScrollActiveRef = useRef(false);
const lastTouchClientYRef = useRef<number | null>(null);
const pendingUserScrollUpIntentRef = useRef(false);
const pendingAutoScrollFrameRef = useRef<number | null>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
const composerCommandInputRef = useRef<HTMLInputElement>(null);
const composerImagesRef = useRef<ComposerImageAttachment[]>([]);
@@ -1094,33 +1102,97 @@ export default function ChatView({ threadId }: ChatViewProps) {
}
}, [lastInvokedScriptByProjectId]);
// Auto-scroll on new messages
const messageCount = activeThread?.messages.length ?? 0;
// Auto-tail while the user stays at the bottom.
const workLogCount = workLogEntries.length;
const scrollMessagesToBottom = useCallback((behavior: ScrollBehavior = "auto") => {
const scrollContainer = messagesScrollRef.current;
if (!scrollContainer) return;
scrollContainer.scrollTo({ top: scrollContainer.scrollHeight, behavior });
lastKnownScrollTopRef.current = scrollContainer.scrollTop;
shouldAutoScrollRef.current = true;
}, []);
const requestAutoTailToBottom = useCallback(() => {
if (pendingAutoScrollFrameRef.current !== null) return;
pendingAutoScrollFrameRef.current = window.requestAnimationFrame(() => {
pendingAutoScrollFrameRef.current = null;
if (!shouldAutoScrollRef.current) return;
scrollMessagesToBottom();
});
}, [scrollMessagesToBottom]);
const onMessagesScroll = useCallback(() => {
const scrollContainer = messagesScrollRef.current;
if (!scrollContainer) return;
shouldAutoScrollRef.current = isScrollContainerNearBottom(scrollContainer);
const currentScrollTop = scrollContainer.scrollTop;
const atBottom = isScrollContainerAtBottom(scrollContainer);
if (!shouldAutoScrollRef.current && atBottom) {
shouldAutoScrollRef.current = true;
pendingUserScrollUpIntentRef.current = false;
} else if (shouldAutoScrollRef.current && pendingUserScrollUpIntentRef.current) {
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
if (scrolledUp) {
shouldAutoScrollRef.current = false;
}
pendingUserScrollUpIntentRef.current = false;
} else if (shouldAutoScrollRef.current && isPointerScrollActiveRef.current) {
// Pointer-driven upward scroll means user takes control.
const scrolledUp = currentScrollTop < lastKnownScrollTopRef.current - 1;
if (scrolledUp) {
shouldAutoScrollRef.current = false;
}
}
lastKnownScrollTopRef.current = currentScrollTop;
}, []);
const onMessagesWheel = useCallback((event: WheelEvent<HTMLDivElement>) => {
// Wheel-up indicates user intent to move away from bottom.
if (event.deltaY < 0) {
pendingUserScrollUpIntentRef.current = true;
}
}, []);
const onMessagesPointerDown = useCallback((_event: PointerEvent<HTMLDivElement>) => {
isPointerScrollActiveRef.current = true;
}, []);
const onMessagesPointerUp = useCallback((_event: PointerEvent<HTMLDivElement>) => {
isPointerScrollActiveRef.current = false;
}, []);
const onMessagesPointerCancel = useCallback((_event: PointerEvent<HTMLDivElement>) => {
isPointerScrollActiveRef.current = false;
}, []);
const onMessagesTouchStart = useCallback((event: TouchEvent<HTMLDivElement>) => {
const touch = event.touches[0];
if (!touch) return;
lastTouchClientYRef.current = touch.clientY;
}, []);
const onMessagesTouchMove = useCallback((event: TouchEvent<HTMLDivElement>) => {
const touch = event.touches[0];
if (!touch) return;
const previousTouchY = lastTouchClientYRef.current;
if (previousTouchY !== null && touch.clientY > previousTouchY + 1) {
// Finger moved downward => user intends to scroll content upward.
pendingUserScrollUpIntentRef.current = true;
}
lastTouchClientYRef.current = touch.clientY;
}, []);
const onMessagesTouchEnd = useCallback((_event: TouchEvent<HTMLDivElement>) => {
lastTouchClientYRef.current = null;
}, []);
useLayoutEffect(() => {
if (!activeThread?.id) return;
scrollMessagesToBottom();
}, [activeThread?.id, scrollMessagesToBottom]);
useEffect(() => {
useLayoutEffect(() => {
if (!shouldAutoScrollRef.current) return;
scrollMessagesToBottom("smooth");
}, [messageCount, scrollMessagesToBottom]);
useEffect(() => {
if (phase !== "running") return;
if (!shouldAutoScrollRef.current) return;
scrollMessagesToBottom("smooth");
}, [phase, workLogCount, scrollMessagesToBottom]);
requestAutoTailToBottom();
}, [activeThread?.messages, workLogCount, requestAutoTailToBottom]);
useEffect(
() => () => {
if (pendingAutoScrollFrameRef.current === null) return;
window.cancelAnimationFrame(pendingAutoScrollFrameRef.current);
pendingAutoScrollFrameRef.current = null;
},
[],
);
useEffect(() => {
setExpandedWorkGroups({});
@@ -2050,6 +2122,14 @@ export default function ChatView({ threadId }: ChatViewProps) {
ref={messagesScrollRef}
className="min-h-0 flex-1 overflow-y-auto px-5 py-4"
onScroll={onMessagesScroll}
onWheel={onMessagesWheel}
onPointerDown={onMessagesPointerDown}
onPointerUp={onMessagesPointerUp}
onPointerCancel={onMessagesPointerCancel}
onTouchStart={onMessagesTouchStart}
onTouchMove={onMessagesTouchMove}
onTouchEnd={onMessagesTouchEnd}
onTouchCancel={onMessagesTouchEnd}
>
<MessagesTimeline
hasMessages={activeThread.messages.length > 0}
+28 -144
View File
@@ -7,8 +7,8 @@ import {
} from "@pierre/diffs/react";
import { useQuery } from "@tanstack/react-query";
import { useParams } from "@tanstack/react-router";
import { ChevronLeftIcon, ChevronRightIcon, Columns2Icon, Rows3Icon } from "lucide-react";
import { type ReactNode, useCallback, useEffect, useMemo, useRef, useState } from "react";
import { Columns2Icon, Rows3Icon } from "lucide-react";
import { type ReactNode, useEffect, useMemo, useRef, useState } from "react";
import { checkpointDiffQueryOptions } from "~/lib/providerReactQuery";
import { cn } from "~/lib/utils";
import { isElectron } from "../env";
@@ -16,6 +16,7 @@ import { useNativeApi } from "../hooks/useNativeApi";
import { useTheme } from "../hooks/useTheme";
import { buildPatchCacheKey } from "../lib/diffRendering";
import { useTurnDiffSummaries } from "../hooks/useTurnDiffSummaries";
import { formatTimestamp } from "../session-logic";
import { useStore } from "../store";
import { ToggleGroup, Toggle } from "./ui/toggle-group";
@@ -71,21 +72,13 @@ function buildFileDiffRenderKey(fileDiff: FileDiffMetadata): string {
return fileDiff.cacheKey ?? `${fileDiff.prevName ?? "none"}:${fileDiff.name}`;
}
function formatTurnChipTimestamp(isoDate: string): string {
return new Intl.DateTimeFormat(undefined, {
hour: "numeric",
minute: "2-digit",
}).format(new Date(isoDate));
}
interface DiffPanelProps {
mode?: "inline" | "sheet";
}
export function DiffWorkerPoolProvider({ children }: { children?: ReactNode }) {
const workerPoolSize = useMemo(() => {
const cores =
typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
const cores = typeof navigator === "undefined" ? 4 : Math.max(1, navigator.hardwareConcurrency || 4);
return Math.max(2, Math.min(6, Math.floor(cores / 2)));
}, []);
@@ -112,9 +105,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
const { state, dispatch } = useStore();
const [diffRenderMode, setDiffRenderMode] = useState<DiffRenderMode>("stacked");
const patchViewportRef = useRef<HTMLDivElement>(null);
const turnStripRef = useRef<HTMLDivElement>(null);
const [canScrollTurnStripLeft, setCanScrollTurnStripLeft] = useState(false);
const [canScrollTurnStripRight, setCanScrollTurnStripRight] = useState(false);
const params = useParams({ strict: false });
const routeThreadId = typeof params.threadId === "string" ? params.threadId : null;
const activeThreadId = state.diffThreadId ?? routeThreadId;
@@ -241,63 +231,6 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
threadId: activeThread.id,
});
};
const updateTurnStripScrollState = useCallback(() => {
const element = turnStripRef.current;
if (!element) {
setCanScrollTurnStripLeft(false);
setCanScrollTurnStripRight(false);
return;
}
const maxScrollLeft = Math.max(0, element.scrollWidth - element.clientWidth);
setCanScrollTurnStripLeft(element.scrollLeft > 4);
setCanScrollTurnStripRight(element.scrollLeft < maxScrollLeft - 4);
}, []);
const scrollTurnStripBy = useCallback((offset: number) => {
const element = turnStripRef.current;
if (!element) return;
element.scrollBy({ left: offset, behavior: "smooth" });
}, []);
const onTurnStripWheel = useCallback((event: WheelEvent) => {
const element = turnStripRef.current;
if (!element) return;
if (element.scrollWidth <= element.clientWidth + 1) return;
if (Math.abs(event.deltaY) <= Math.abs(event.deltaX)) return;
event.preventDefault();
element.scrollBy({ left: event.deltaY, behavior: "auto" });
}, []);
useEffect(() => {
const element = turnStripRef.current;
if (!element) return;
updateTurnStripScrollState();
const onScroll = () => updateTurnStripScrollState();
element.addEventListener("scroll", onScroll, { passive: true });
element.addEventListener("wheel", onTurnStripWheel, { passive: false });
const resizeObserver = new ResizeObserver(() => updateTurnStripScrollState());
resizeObserver.observe(element);
return () => {
element.removeEventListener("scroll", onScroll);
element.removeEventListener("wheel", onTurnStripWheel);
resizeObserver.disconnect();
};
}, [updateTurnStripScrollState, onTurnStripWheel]);
useEffect(() => {
updateTurnStripScrollState();
}, [turnDiffSummaries, selectedTurnId, updateTurnStripScrollState]);
useEffect(() => {
const element = turnStripRef.current;
if (!element) return;
const selectedChip = element.querySelector<HTMLElement>("[data-turn-chip-selected='true']");
selectedChip?.scrollIntoView({ block: "nearest", inline: "nearest", behavior: "smooth" });
}, [selectedTurn?.turnId, selectedTurnId]);
const shouldUseDragRegion = isElectron && mode === "inline";
@@ -312,98 +245,49 @@ export default function DiffPanel({ mode = "inline" }: DiffPanelProps) {
>
<div
className={cn(
"flex items-center justify-between gap-2 border-b border-border px-4",
"flex items-center justify-between border-b border-border px-4",
shouldUseDragRegion ? "drag-region h-[52px]" : "py-3",
)}
>
<div className="relative min-w-0 flex-1 [-webkit-app-region:no-drag]">
{canScrollTurnStripLeft && (
<div className="pointer-events-none absolute inset-y-0 left-8 z-10 w-7 bg-gradient-to-r from-card to-transparent" />
)}
{canScrollTurnStripRight && (
<div className="pointer-events-none absolute inset-y-0 right-8 z-10 w-7 bg-gradient-to-l from-card to-transparent" />
)}
<button
type="button"
className={cn(
"absolute left-0 top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors",
canScrollTurnStripLeft
? "border-border/70 hover:border-border hover:text-foreground"
: "cursor-not-allowed border-border/40 text-muted-foreground/40",
)}
onClick={() => scrollTurnStripBy(-180)}
disabled={!canScrollTurnStripLeft}
aria-label="Scroll turn list left"
>
<ChevronLeftIcon className="size-3.5" />
<div className="flex gap-1.5 overflow-x-auto pb-0.5">
<button type="button" className="shrink-0 rounded-md" onClick={selectWholeConversation}>
<div
className={cn(
"rounded-md border px-2 py-1 text-left transition-colors",
selectedTurnId === null
? "border-border bg-accent text-accent-foreground"
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
)}
>
<div className="text-[10px] font-medium">All turns</div>
<div className="text-[8px] opacity-70">Conversation</div>
</div>
</button>
<button
type="button"
className={cn(
"absolute right-0 top-1/2 z-20 inline-flex size-6 -translate-y-1/2 items-center justify-center rounded-md border bg-background/90 text-muted-foreground transition-colors",
canScrollTurnStripRight
? "border-border/70 hover:border-border hover:text-foreground"
: "cursor-not-allowed border-border/40 text-muted-foreground/40",
)}
onClick={() => scrollTurnStripBy(180)}
disabled={!canScrollTurnStripRight}
aria-label="Scroll turn list right"
>
<ChevronRightIcon className="size-3.5" />
</button>
<div
ref={turnStripRef}
className="turn-chip-strip flex gap-1 overflow-x-auto px-8 py-0.5"
>
{turnDiffSummaries.map((summary, index) => (
<button
key={summary.turnId}
type="button"
className="shrink-0 rounded-md"
onClick={selectWholeConversation}
data-turn-chip-selected={selectedTurnId === null}
onClick={() => selectTurn(summary.turnId)}
title={summary.turnId}
>
<div
className={cn(
"rounded-md border px-2 py-1 text-left transition-colors",
selectedTurnId === null
summary.turnId === selectedTurn?.turnId
? "border-border bg-accent text-accent-foreground"
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
)}
>
<div className="text-[10px] leading-tight font-medium">All turns</div>
<div className="text-[10px] font-medium">
Turn {turnDiffSummaries.length - index}
</div>
<div className="text-[8px] opacity-70">{formatTimestamp(summary.completedAt)}</div>
</div>
</button>
{turnDiffSummaries.map((summary, index) => (
<button
key={summary.turnId}
type="button"
className="shrink-0 rounded-md"
onClick={() => selectTurn(summary.turnId)}
title={summary.turnId}
data-turn-chip-selected={summary.turnId === selectedTurn?.turnId}
>
<div
className={cn(
"rounded-md border px-2 py-1 text-left transition-colors",
summary.turnId === selectedTurn?.turnId
? "border-border bg-accent text-accent-foreground"
: "border-border/70 bg-background/70 text-muted-foreground/80 hover:border-border hover:text-foreground/80",
)}
>
<div className="flex items-center gap-1">
<span className="text-[10px] leading-tight font-medium">
Turn {turnDiffSummaries.length - index}
</span>
<span className="text-[9px] leading-tight opacity-70">
{formatTurnChipTimestamp(summary.completedAt)}
</span>
</div>
</div>
</button>
))}
</div>
))}
</div>
<ToggleGroup
className="shrink-0 [-webkit-app-region:no-drag]"
variant="outline"
size="xs"
value={[diffRenderMode]}
-10
View File
@@ -190,16 +190,6 @@ input {
background: rgba(255, 255, 255, 0.18);
}
.turn-chip-strip {
scrollbar-width: none;
-ms-overflow-style: none;
overscroll-behavior-x: contain;
}
.turn-chip-strip::-webkit-scrollbar {
display: none;
}
/* Terminal drawer scrollbar parity with chat */
.thread-terminal-drawer .xterm .xterm-scrollable-element > .scrollbar.vertical {
width: 6px !important;