Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
104 changes: 104 additions & 0 deletions apps/web/src/components/chat/MessagesTimeline.browser.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -469,6 +469,110 @@ describe("MessagesTimeline messages", () => {
await expectHeadingInView("Last turn", "Turn 118:");
});

it("disables the minimap's next turn button at the bottom of the thread", async () => {
setup();
const props = baseProps();
const entries = Array.from({ length: 16 }, (_, index) => [
message(`Question ${index}`, {}, `user-${index}`),
message(`Answer ${index}`, { role: "assistant" }, `assistant-${index}`),
]).flat();
await using screen = await renderTimeline(entries, props);
const viewport = props.listRef.current!.getScrollableNode()!;
const strips = () => [
...screen.container.querySelectorAll<HTMLElement>("[data-minimap-strip]"),
];
// Several final turns share the last screen, so the current turn is not the last one.
await vi.waitFor(() => {
expect(viewport.scrollTop).toBeGreaterThan(0);
expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeLessThan(2);
expect(strips()[0]?.dataset.inView).toBe("false");
expect(
strips()
.slice(-2)
.map((strip) => strip.dataset.inView),
).toEqual(["true", "true"]);
expect(screen.button("Previous turn")).not.toBeDisabled();
});

expect(screen.button("Next turn")).toBeDisabled();

viewport.scrollTop -= 30;
await vi.waitFor(() => expect(screen.button("Next turn")).not.toBeDisabled());

// Shrinking a detached viewport moves the bottom away without a scroll event.
await screen.rerender(
<MessagesTimeline {...props} timelineEntries={entries} liveFollowEnabled={false} />,
);
viewport.scrollTop = viewport.scrollHeight;
await vi.waitFor(() => expect(screen.button("Next turn")).toBeDisabled());
screen.container.style.height = "600px";
await vi.waitFor(() => {
expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeGreaterThan(
500,
);
expect(screen.button("Next turn")).not.toBeDisabled();
});

// So does a footer that grows below a detached bottom.
viewport.scrollTop = viewport.scrollHeight;
await vi.waitFor(() => expect(screen.button("Next turn")).toBeDisabled());
await screen.rerender(
<MessagesTimeline
{...props}
timelineEntries={entries}
liveFollowEnabled={false}
footer={<div style={{ height: 400 }} />}
/>,
);
await vi.waitFor(() => {
expect(viewport.scrollHeight - viewport.clientHeight - viewport.scrollTop).toBeGreaterThan(
300,
);
expect(screen.button("Next turn")).not.toBeDisabled();
});
});

it("enables the minimap's next turn button on a thread restored above its bottom", async () => {
setup();
const base = baseProps();
const turns = (prefix: string) =>
Array.from({ length: 16 }, (_, index) => [
message(`${prefix} question ${index}`, {}, `${prefix}-user-${index}`),
message(`${prefix} answer ${index}`, { role: "assistant" }, `${prefix}-assistant-${index}`),
]).flat();
const other = "environment-local:thread-minimap-restored";
rememberTimelinePosition(
other,
{ rowId: "entry-b-user-4", offsetWithinRow: 0, scrollOffset: 0, atEnd: false },
false,
);
await using screen = await renderElement(
<MessagesTimeline {...base} timelineEntries={turns("a")} />,
);
const viewport = base.listRef.current!.getScrollableNode()!;
await vi.waitFor(() => {
expect(viewport.scrollTop).toBeGreaterThan(0);
expect(screen.button("Next turn")).toBeDisabled();
});

await screen.rerender(
<MessagesTimeline
{...base}
routeThreadKey={other}
timelineEntries={turns("b")}
liveFollowEnabled={false}
/>,
);
await vi.waitFor(() => {
const row = screen.container.querySelector('[data-timeline-row-id="entry-b-user-4"]');
expect(row).not.toBeNull();
expect(
Math.abs(row!.getBoundingClientRect().top - viewport.getBoundingClientRect().top),
).toBeLessThanOrEqual(2);
expect(screen.button("Next turn")).not.toBeDisabled();
});
});

it("keeps rows in item order after a reload or thread switch, before any timer runs", async () => {
setup();
// NVDA's browse mode keeps the first DOM order it reads, so a timer that sorts rows later is too late.
Expand Down
24 changes: 19 additions & 5 deletions apps/web/src/components/chat/MessagesTimeline.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -794,6 +794,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
};
const [minimapHitStripWidth, setMinimapHitStripWidth] = useState(0);
const [minimapCurrentIndex, setMinimapCurrentIndex] = useState<number | null>(null);
const [minimapAtEnd, setMinimapAtEnd] = useState(false);
const handleAnchorReady = (info: { anchorIndex: number | undefined }) => {
if (anchorMessageId !== null && info.anchorIndex !== undefined) {
onAnchorReady(anchorMessageId, info.anchorIndex);
Expand Down Expand Up @@ -864,17 +865,27 @@ const ConversationTimeline = memo(function ConversationTimeline({
setMinimapCurrentIndex((current) =>
current === nextCurrentIndex ? current : nextCurrentIndex,
);
// The exact bottom, not the follow re-arm zone: Next can still scroll inside that zone.
setMinimapAtEnd(
viewport !== undefined &&
viewport.scrollHeight - viewport.scrollTop - viewport.clientHeight <= 1,
);
});

const minimapRefreshFrameRef = useRef<number | null>(null);
const scheduleMinimapRefresh = () => {
const scheduleMinimapRefresh = useStableCallback(() => {
if (minimapRefreshFrameRef.current !== null) return;
// LegendList recycles row containers before React commits their positions.
minimapRefreshFrameRef.current = requestAnimationFrame(() => {
minimapRefreshFrameRef.current = null;
refreshMinimap();
});
};
});

// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- the minimap skips refreshes until the restore commits, and the restore can land without a scroll event
useLayoutEffect(() => {
if (!restoringThreadPosition) scheduleMinimapRefresh();
}, [restoringThreadPosition, scheduleMinimapRefresh]);

// The measurement the last remember wrote, so a follow release can rewrite
// it without reading render state from a listener.
Expand Down Expand Up @@ -970,9 +981,10 @@ const ConversationTimeline = memo(function ConversationTimeline({
const attachTimelineViewportElement = (viewportElement: HTMLDivElement | null) => {
setTimelineViewportElement(viewportElement);
if (!viewportElement) return;
const stopObserving = observeResize(viewportElement, () =>
measureTimelineGutter(viewportElement),
);
const stopObserving = observeResize(viewportElement, () => {
measureTimelineGutter(viewportElement);
scheduleMinimapRefresh();
});
return () => {
stopObserving();
setTimelineViewportElement(null);
Expand Down Expand Up @@ -1323,6 +1335,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
maintainScrollAtEndThreshold={1}
onScroll={handleScroll}
onItemSizeChanged={scheduleMinimapRefresh}
onMetricsChange={scheduleMinimapRefresh}
className={cn(
"messages-timeline-scroll scrollbar-gutter-both h-full min-h-0 overflow-x-hidden overscroll-y-contain [overflow-anchor:none]",
topFadeEnabled && "topbar-scroll-fade",
Expand All @@ -1335,6 +1348,7 @@ const ConversationTimeline = memo(function ConversationTimeline({
hasPersistentGutter={minimapHasPersistentGutter}
hitStripWidth={minimapHitStripWidth}
currentIndex={minimapCurrentIndex}
atEnd={minimapAtEnd}
stripMap={minimapStripMap}
onWheel={forwardMinimapWheel}
onSelect={(item) => {
Expand Down
5 changes: 4 additions & 1 deletion apps/web/src/components/chat/TimelineMinimap.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,6 +38,7 @@ export function TimelineMinimap({
hasPersistentGutter,
hitStripWidth,
currentIndex,
atEnd,
items,
stripMap,
onWheel,
Expand All @@ -46,6 +47,7 @@ export function TimelineMinimap({
hasPersistentGutter: boolean;
hitStripWidth: number;
currentIndex: number | null;
atEnd: boolean;
items: ReadonlyArray<TimelineMinimapItem>;
stripMap: Map<string, HTMLSpanElement>;
onWheel: (event: WheelEvent) => void;
Expand Down Expand Up @@ -84,7 +86,8 @@ export function TimelineMinimap({
currentIndex !== null && currentIndex >= 0 && currentIndex < items.length ? currentIndex : null;
const previousItem =
resolvedCurrentIndex === null ? null : (items[resolvedCurrentIndex - 1] ?? null);
const nextItem = resolvedCurrentIndex === null ? null : (items[resolvedCurrentIndex + 1] ?? null);
const nextItem =
resolvedCurrentIndex === null || atEnd ? null : (items[resolvedCurrentIndex + 1] ?? null);

const resolveActiveIndexFromPointer = (event: MouseEvent<HTMLElement>) => {
const rect = event.currentTarget.getBoundingClientRect();
Expand Down
Loading