🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.
TypeScript analyticsautogenevaluationlangchainlarge-language-modelsllama-indexllmllm-evaluationllm-observabilityllmopsmonitoringobservabilityopen-sourceopenaiplaygroundprompt-engineeringprompt-managementself-hostedycombinator
fix(sessions): Smooth scroll + highlight scrolled to item (#18526)
Ben Bachem2e614d092da4
diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/ConnectedModernSessionBodyTimeline.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/ConnectedModernSessionBodyTimeline.tsxindex 3393ed1034..c70f7eb9ee 100644--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/ConnectedModernSessionBodyTimeline.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/ConnectedModernSessionBodyTimeline.tsx@@ -207,6 +207,7 @@ export function ConnectedModernSessionBodyTimeline({index: number,observationId?: string,rowId?: string,+ toolGroupId?: string,) => {const entry = entries[index];const traceId = entry@@ -222,7 +223,7 @@ export function ConnectedModernSessionBodyTimeline({requestId: scrollRequestIdRef.current,});}- timelineController.onSelect(index, observationId, rowId);+ timelineController.onSelect(index, observationId, rowId, toolGroupId);};return (diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.stories.tsxindex e0efabeae5..851c0caedc 100644--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.stories.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/SessionConversationalView.stories.tsx@@ -2299,7 +2299,7 @@ function SessionConversationalViewStory({return next;})}- onSelect={(index, observationId, rowId) => {+ onSelect={(index, observationId, rowId, toolGroupId) => {const entry = entries[index];const traceId = entry? displayedTraces[entry.traceIndex]?.trace.id@@ -2313,7 +2313,7 @@ function SessionConversationalViewStory({requestId: ++requestId.current,});}- controller.onSelect(index, observationId, rowId);+ controller.onSelect(index, observationId, rowId, toolGroupId);}}onVisibleTraceIdsChange={fn()}isLoadingTranscripts={isSearchPending}@@ -2796,6 +2796,20 @@ export const ExactMessageNavigation = meta.story({await userEvent.click(card.getByRole("button", { name: "Tool: lookup · save" }),);+ const toolGroup = await waitFor(async () => {+ const group = canvas+ .getByLabelText("Session conversation timeline")+ .querySelector<HTMLElement>(+ '[data-session-item-id="scroll-turn-2:0"] [data-session-tool-group-id="0:3"]',+ );+ await expect(group).toHaveAttribute("data-session-navigation-highlight");+ if (!group) throw new Error("Target tool group is not mounted");+ await expect(+ group.querySelectorAll("[data-session-tool-row]"),+ ).toHaveLength(2);+ await expect(group.getAnimations()).toHaveLength(1);+ return group;+ });await expectNavigation(canvasElement,/^2\.1 Navigation turn 2/,@@ -2816,6 +2830,96 @@ export const ExactMessageNavigation = meta.story({await expect(within(entry).getByRole("button", { name: "Expand save" }),).toBeVisible();+ await userEvent.type(search, "save");+ const filteredHeader = await sidebar.findByRole("button", {+ name: /^2\.1 Navigation turn 2/,+ });+ await userEvent.click(+ within(filteredHeader.parentElement!.parentElement!).getByRole("button", {+ name: "tool: save",+ }),+ );+ await waitFor(async () => {+ await expect(toolGroup).not.toHaveAttribute(+ "data-session-navigation-highlight",+ );+ await expect(+ toolGroup.querySelector('[data-session-transcript-row-id="0:4"]'),+ ).toHaveAttribute("data-session-navigation-highlight");+ await expect(+ toolGroup.querySelector('[data-session-transcript-row-id="0:3"]'),+ ).not.toHaveAttribute("data-session-navigation-highlight");+ });+ },+});++export const RepeatNavigationHighlight = meta.story({+ name: "(Test) Repeat Navigation Highlight",+ args: { transcriptTraces: navigationTraces, viewportHeight: 480 },+ play: async ({ canvasElement }) => {+ const canvas = within(canvasElement);+ const sidebar = within(canvas.getByRole("complementary"));+ const feed = canvas.getByLabelText("Session conversation timeline");+ await userEvent.type(sidebar.getByRole("textbox"), "Turn 1 thread 3");+ const button = sidebar.getByRole("button", { name: "User message" });+ await userEvent.click(button);+ const target = await waitFor(async () => {+ const row = feed.querySelector<HTMLElement>(+ '[data-session-item-id="scroll-turn-1:2"] [data-session-transcript-row-id="2:1"]',+ );+ await expect(row).toHaveAttribute("data-session-navigation-highlight");+ if (!row) throw new Error("Target message is not mounted");+ return row;+ });+ const bubble = target.querySelector<HTMLElement>(+ "[data-session-message-bubble]",+ );+ if (!bubble) throw new Error("Target message bubble is not mounted");+ await expect(target.getAnimations()).toHaveLength(0);+ await expect(getComputedStyle(target).backgroundColor).toBe(+ "rgba(0, 0, 0, 0)",+ );+ const originalAnimation = bubble.getAnimations()[0]!;+ await waitFor(+ async () => {+ await expect(originalAnimation.currentTime).toBeGreaterThanOrEqual(900);+ await expect(originalAnimation.playState).toBe("running");+ },+ { timeout: 2_000 },+ );+ const fadedBackground = getComputedStyle(bubble).backgroundColor;++ await userEvent.click(button);+ const restartedAnimation = await waitFor(async () => {+ const animation = bubble.getAnimations()[0];+ await expect(animation).toBeDefined();+ await expect(animation).not.toBe(originalAnimation);+ await expect(animation?.currentTime).toBeLessThan(300);+ await expect(getComputedStyle(bubble).backgroundColor).not.toBe(+ fadedBackground,+ );+ return animation!;+ });+ await waitFor(+ async () => {+ await expect(target).not.toHaveAttribute(+ "data-session-navigation-highlight",+ );+ },+ { timeout: 2_000 },+ );+ const idleBackground = getComputedStyle(bubble).backgroundColor;++ await userEvent.click(button);+ await waitFor(async () => {+ const animation = bubble.getAnimations()[0];+ await expect(animation).toBeDefined();+ await expect(animation).not.toBe(restartedAnimation);+ await expect(animation?.currentTime).toBeLessThan(300);+ await expect(getComputedStyle(bubble).backgroundColor).not.toBe(+ idleBackground,+ );+ });},});diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.stories.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.stories.tsxindex 1d238d22e5..1ac36cbfb6 100644--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.stories.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.stories.tsx@@ -271,7 +271,12 @@ export const GroupedTools = meta.story({canvas.queryByRole("button", { name: "tool: apply_patch" }),).not.toBeInTheDocument();await userEvent.click(group);- await expect(args.onSelect).toHaveBeenCalledWith(0, "generation-1", "0:0");+ await expect(args.onSelect).toHaveBeenCalledWith(+ 0,+ "generation-1",+ "0:0",+ "0:0",+ );await userEvent.type(canvas.getByRole("textbox"), "tool");await expect(canvas.queryByRole("button", { name: /^Tool:.*read_file.*apply_patch/ }),diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.tsxindex d194aa4d59..15bcb82854 100644--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationSidebar/SessionConversationSidebar.tsx@@ -60,6 +60,7 @@ export function SessionConversationSidebar(index: number,observationId?: string,rowId?: string,+ toolGroupId?: string,) => void;onVisibleTraceIdsChange: (traceIds: string[]) => void;isLoadingTranscripts: boolean;@@ -499,6 +500,7 @@ export function SessionConversationSidebar(targetIndex,firstTool.observationId,firstTool.id,+ firstTool.id,)}className="ph-no-capture text-muted-foreground hover:bg-foreground/10 -mr-2 -ml-1 flex min-w-0 items-center gap-2 rounded-sm px-1 py-1 text-left text-[13px] transition-colors duration-150"diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.module.css b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.module.cssnew file mode 100644index 0000000000..8ced2b24aa--- /dev/null+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.module.css@@ -0,0 +1,57 @@+.timeline {+ --session-navigation-highlight: hsl(var(--muted));+}++.timeline [data-session-message-bubble] {+ --session-navigation-highlight: color-mix(+ in srgb,+ hsl(var(--muted-foreground)) 20%,+ hsl(var(--muted))+ );+}++.timeline [data-session-message-role="user"] {+ --session-navigation-highlight: color-mix(+ in srgb,+ var(--color-blue-400) 20%,+ hsl(var(--muted))+ );+}++.timeline [data-session-navigation-highlight]:not([data-session-message-row]) {+ border-radius: 0.5rem;+ animation: navigation-highlight 1.5s ease-out;+}++.timeline+ [data-session-navigation-highlight][data-session-message-row]+ [data-session-message-bubble] {+ animation: message-highlight 1.5s ease-out;+}++@keyframes message-highlight {+ 0%,+ 20% {+ background-color: var(--session-navigation-highlight);+ }+}++@keyframes navigation-highlight {+ 0%,+ 20% {+ background-color: var(--session-navigation-highlight);+ }+ 100% {+ background-color: transparent;+ }+}++@media (prefers-reduced-motion: reduce) {+ .timeline [data-session-navigation-highlight]:not([data-session-message-row]),+ .timeline+ [data-session-navigation-highlight][data-session-message-row]+ [data-session-message-bubble] {+ animation: none;+ background-color: var(--session-navigation-highlight);+ }+}diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.tsxindex 7779c20c81..9e52003a67 100644--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/SessionConversationTimeline.tsx@@ -1,6 +1,7 @@import { type ComponentProps } from "react";import { SessionConversationTimelineTrace } from "@/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/SessionConversationTimelineTrace";import { type SessionConversationTimelineController } from "@/src/features/sessions/hooks/useSessionConversationTimelineController";+import styles from "./SessionConversationTimeline.module.css";export function SessionConversationTimeline({traces,@@ -15,7 +16,7 @@ export function SessionConversationTimeline({<divref={feedRef}aria-label="Session conversation timeline"- className="h-full min-h-0 overflow-y-auto [overflow-anchor:none]"+ className={`${styles.timeline} h-full min-h-0 overflow-y-auto [overflow-anchor:none]`}><divstyle={{diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/SessionTranscriptContent.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/SessionTranscriptContent.tsxindex ff4f3cdc2d..5fc91a69b7 100644--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/SessionTranscriptContent.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/SessionTranscriptContent.tsx@@ -81,7 +81,7 @@ function SessionTranscriptThread({} | null;}) {const groups = groupConsecutiveTools(rows, {- minGroupSize: 4,+ minGroupSize: 2,isTool: ({ row }) => row.type === "tool",getBoundary: ({ threadIndex }) => threadIndex,getToolName: ({ row }) =>@@ -105,6 +105,9 @@ function SessionTranscriptThread({<divkey={group.type === "tools" ? group.rows[0]!.id : group.row.id}data-session-compact-row={isCompact ? "" : undefined}+ data-session-tool-group-id={+ group.type === "tools" ? group.rows[0]!.id : undefined+ }className={cn(index > 0 &&(() => {@@ -184,6 +187,7 @@ function SessionTranscriptRow({className="group space-y-1"data-session-tool-row={isTool ? "" : undefined}data-session-system-row={isSystem ? "" : undefined}+ data-session-message-row={!isTool && !isSystem ? "" : undefined}data-session-observation-id={row.message.observationId ?? undefined}data-session-transcript-row-id={id}data-scroll-request-id={scrollRequestId}@@ -223,6 +227,15 @@ function SessionTranscriptToolGroup({const isOpen =expansion.isExpanded ||(containsTarget && props.scrollTarget?.requestId !== expansion.requestId);+ if (rows.length < 4) {+ return (+ <div className="space-y-1">+ {rows.map((item) => (+ <SessionTranscriptRow key={item.id} {...props} item={item} />+ ))}+ </div>+ );+ }return (<SessionTimelineCollapsibleRowlabel={summary}diff --git a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsx b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsxindex 76a70d7a89..8f2c4c23b9 100644--- a/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsx+++ b/web/src/features/sessions/components/ConnectedModernSessionBodyTimeline/components/ConnectedSessionConversationTimeline/components/SessionConversationalView/components/SessionConversationTimeline/components/SessionConversationTimelineTrace/components/SessionTranscriptContent/components/SessionTimelineContentMessage/SessionTimelineContentMessage.tsx@@ -96,6 +96,8 @@ export function SessionTimelineContentMessage({<divkey={`reasoning-${groupIndex}`}className="flex w-full flex-col gap-1"+ data-session-message-bubble=""+ data-session-message-role={role}>{group.parts.map((part, partIndex) => (<SessionTimelinePart@@ -132,6 +134,8 @@ export function SessionTimelineContentMessage({className={cn("flex w-full", presentation.wrapper)}><article+ data-session-message-bubble=""+ data-session-message-role={role}className={cn("group/bubble min-w-0 overflow-hidden",presentation.container,diff --git a/web/src/features/sessions/hooks/useSessionConversationTimelineController.clienttest.tsx b/web/src/features/sessions/hooks/useSessionConversationTimelineController.clienttest.tsxindex e244310049..dc964bb2e5 100644--- a/web/src/features/sessions/hooks/useSessionConversationTimelineController.clienttest.tsx+++ b/web/src/features/sessions/hooks/useSessionConversationTimelineController.clienttest.tsx@@ -1,5 +1,5 @@import { act, fireEvent, renderHook, waitFor } from "@testing-library/react";-import { afterEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { useSessionConversationTimelineController } from "./useSessionConversationTimelineController";import { type EventSessionTrace } from "@/src/features/sessions/sessionDetailPageTypes";import { getScrollSpyAnchor } from "@/src/hooks/useVirtualizedScrollSpy";@@ -41,10 +41,27 @@ const trace = {scores: [],} satisfies EventSessionTrace;+beforeEach(() => {+ vi.stubGlobal(+ "matchMedia",+ vi.fn().mockReturnValue({+ matches: true,+ media: "(prefers-reduced-motion: reduce)",+ onchange: null,+ addListener: vi.fn(),+ removeListener: vi.fn(),+ addEventListener: vi.fn(),+ removeEventListener: vi.fn(),+ dispatchEvent: vi.fn(),+ }),+ );+});+afterEach(() => {feedRef.current = null;virtualizer.scrollOffset = 0;vi.restoreAllMocks();+ vi.unstubAllGlobals();vi.useRealTimers();vi.clearAllMocks();});@@ -84,25 +101,159 @@ function appendMeasuredRow(}describe("useSessionConversationTimelineController", () => {- it.each([300, 500, 800])(- "aligns with 20%% of the actual %spx scroll viewport rather than the bounding box or window",- (height) => {- const feed = createMeasuredFeed();- Object.defineProperty(feed, "clientHeight", {- value: height,- configurable: true,+ it("highlights the whole tool group for group selection, but only the row for individual selection", () => {+ const feed = createMeasuredFeed();+ const row = appendMeasuredRow(feed, "trace:0", "0:0", 700);+ const entry = row.parentElement!;+ const group = document.createElement("div");+ group.dataset.sessionToolGroupId = "0:0";+ group.getBoundingClientRect = () =>+ new DOMRect(0, 200 + 700 - feed.scrollTop, 100, 200);+ const secondRow = document.createElement("div");+ secondRow.dataset.sessionTranscriptRowId = "0:1";+ group.append(row, secondRow);+ entry.append(group);+ const { result } = renderHook(() =>+ useSessionConversationTimelineController([{ trace, itemId: "trace:0" }]),+ );+ act(() => result.current.onSelect(0, undefined, "0:0", "0:0"));+ expect(feed.scrollTop).toBe(600);+ expect(group).toHaveAttribute("data-session-navigation-highlight");+ expect(row).not.toHaveAttribute("data-session-navigation-highlight");+ expect(secondRow).not.toHaveAttribute("data-session-navigation-highlight");+ act(() => result.current.onSelect(0, undefined, "0:0"));+ expect(group).not.toHaveAttribute("data-session-navigation-highlight");+ expect(row).toHaveAttribute("data-session-navigation-highlight");+ expect(secondRow).not.toHaveAttribute("data-session-navigation-highlight");+ });++ it.each(["message", "tool", "thread"] as const)(+ "highlights the %s as it enters the viewport, restarts on repeat selection, and clears on expiry or unmount",+ async (targetType) => {+ vi.useFakeTimers({+ toFake: [+ "setTimeout",+ "clearTimeout",+ "requestAnimationFrame",+ "cancelAnimationFrame",+ "performance",+ ],});- appendMeasuredRow(feed, "trace:0", "0:0", 700);- const { result } = renderHook(() =>+ vi.mocked(window.matchMedia).mockReturnValue({+ ...window.matchMedia("(prefers-reduced-motion: reduce)"),+ matches: false,+ });+ const feed = createMeasuredFeed();+ const row = appendMeasuredRow(feed, "trace:0", "0:0", 700);+ row.dataset.sessionObservationId = "tool";+ const target = targetType === "thread" ? row.parentElement! : row;+ row.parentElement!.getBoundingClientRect = () =>+ new DOMRect(0, 200 - feed.scrollTop, 100, 800);+ const { result, unmount } = renderHook(() =>useSessionConversationTimelineController([{ trace, itemId: "trace:0" },]),);- act(() => result.current.onSelect(0, undefined, "0:0"));- expect(feed.scrollTop).toBe(700 - height * 0.2);+ const observationId = targetType === "tool" ? "tool" : undefined;+ const rowId = targetType === "message" ? "0:0" : undefined;+ act(() => result.current.onSelect(0, observationId, rowId));+ if (targetType !== "thread") {+ expect(target).not.toHaveAttribute("data-session-navigation-highlight");+ }+ await act(async () => await vi.advanceTimersByTimeAsync(96));+ expect(feed.querySelector("[data-session-navigation-highlight]")).toBe(+ target,+ );+ if (targetType !== "thread") {+ expect(feed.scrollTop).toBeLessThan(600);+ }+ act(() => result.current.onSelect(0, observationId, rowId));+ await act(async () => await vi.advanceTimersByTimeAsync(900));+ expect(target).toHaveAttribute("data-session-navigation-highlight");+ await act(async () => await vi.advanceTimersByTimeAsync(650));+ expect(target).not.toHaveAttribute("data-session-navigation-highlight");+ act(() => result.current.onSelect(0, observationId, rowId));+ expect(target).toHaveAttribute("data-session-navigation-highlight");+ unmount();+ expect(target).not.toHaveAttribute("data-session-navigation-highlight");},);+ it.each([+ { initialTop: 0, frameMs: 16 },+ { initialTop: 9_500, frameMs: 16 },+ { initialTop: 0, frameMs: 600 },+ ])(+ "smoothly approaches a distant unmounted entry from $initialTop px with $frameMs ms frames and integer scroll positions",+ async ({ initialTop, frameMs }) => {+ vi.useFakeTimers({+ toFake: [+ "setTimeout",+ "clearTimeout",+ "requestAnimationFrame",+ "cancelAnimationFrame",+ "performance",+ ],+ });+ if (frameMs > 16) {+ vi.spyOn(window, "requestAnimationFrame").mockImplementation(+ (callback) =>+ window.setTimeout(() => callback(performance.now()), frameMs),+ );+ vi.spyOn(window, "cancelAnimationFrame").mockImplementation((frame) =>+ window.clearTimeout(frame),+ );+ }+ vi.mocked(window.matchMedia).mockReturnValue({+ ...window.matchMedia("(prefers-reduced-motion: reduce)"),+ matches: false,+ });+ const feed = createMeasuredFeed();+ feed.scrollTop = initialTop;+ feed.scrollTo = vi.fn((options?: ScrollToOptions | number) => {+ if (typeof options !== "object") return;+ feed.scrollTop = Math.round(options.top ?? 0);+ virtualizer.scrollOffset = feed.scrollTop;+ });+ const traces = Array.from({ length: 80 }, (_, index) => ({+ trace,+ itemId: `trace:${index}`,+ }));+ const { result, rerender } = renderHook(() =>+ useSessionConversationTimelineController(traces),+ );+ act(() => result.current.onSelect(79, undefined, "79:0"));+ expect(feed.scrollTop).toBe(initialTop);+ await act(+ async () => await vi.advanceTimersByTimeAsync(Math.max(64, frameMs)),+ );+ expect(feed.scrollTop).toBeGreaterThan(Math.min(initialTop, 7_800));+ expect(feed.scrollTop).toBeLessThan(Math.max(initialTop, 7_800));+ expect(result.current.activeItemId).toBe("trace:79");++ const row = appendMeasuredRow(feed, "trace:79", "79:0", 8_500);+ await act(async () => await vi.advanceTimersByTimeAsync(64));+ row.getBoundingClientRect = () =>+ new DOMRect(0, 200 + 8_800 - feed.scrollTop, 100, 100);+ await act(async () => await vi.advanceTimersByTimeAsync(3_500));+ expect(feed.scrollTop).toBe(8_700);+ virtualizer.scrollOffset = 0;+ rerender();+ expect(result.current.activeItemId).toBe("trace:1");+ },+ );++ it("aligns rows with 20% of the scroll viewport in offset containers with reduced motion", () => {+ const feed = createMeasuredFeed();+ feed.scrollTop = 100;+ appendMeasuredRow(feed, "trace:0", "0:0", 700);+ const { result } = renderHook(() =>+ useSessionConversationTimelineController([{ trace, itemId: "trace:0" }]),+ );+ act(() => result.current.onSelect(0, undefined, "0:0"));+ expect(feed.scrollTop).toBe(600);+ });+it("corrects navigation and recomputes the scroll-spy anchor when the viewport resizes", async () => {const feed = createMeasuredFeed();appendMeasuredRow(feed, "trace:2", "2:0", 140);@@ -113,6 +264,7 @@ describe("useSessionConversationTimelineController", () => {]),);act(() => result.current.onSelect(1, undefined, "2:0"));+ expect(result.current.activeItemId).toBe("trace:2");expect(feed.scrollTop).toBe(40);Object.defineProperty(feed, "clientHeight", { value: 300 });rerender();@@ -126,7 +278,7 @@ describe("useSessionConversationTimelineController", () => {expect(result.current.activeItemId).toBe("trace:0");});- it("bounds the fallback for a short entry before the earliest reachable anchor and releases it on resize", async () => {+ it("keeps an unreachable boundary entry selected until scrolling past the buffer and releases it on resize", async () => {const feed = createMeasuredFeed();Object.defineProperty(feed, "clientHeight", {value: 800,@@ -144,6 +296,20 @@ describe("useSessionConversationTimelineController", () => {async () =>await new Promise((resolve) => window.setTimeout(resolve, 300)),);+ fireEvent.wheel(feed);+ expect(result.current.activeItemId).toBe("trace:0");+ feed.scrollTop = 80;+ fireEvent.scroll(feed);+ expect(result.current.activeItemId).toBe("trace:0");+ feed.scrollTop = 81;+ fireEvent.scroll(feed);+ expect(result.current.activeItemId).toBe("trace:2");+ feed.scrollTop = 0;+ act(() => result.current.onSelect(0));+ await act(+ async () =>+ await new Promise((resolve) => window.setTimeout(resolve, 300)),+ );expect(result.current.activeItemId).toBe("trace:0");Object.defineProperty(feed, "clientHeight", { value: 300 });feed.scrollTop = 100;@@ -152,39 +318,6 @@ describe("useSessionConversationTimelineController", () => {expect(result.current.activeItemId).toBe("trace:2");});- it.each(["wheel", "touchstart", "pointerdown", "keydown"])(- "keeps fallback selection after %s until scrolling past the buffer",- async (eventType) => {- const feed = createMeasuredFeed();- Object.defineProperty(feed, "clientHeight", { value: 800 });- appendMeasuredRow(feed, "trace:0", "0:0", 0);- const { result } = renderHook(() =>- useSessionConversationTimelineController([- { trace, itemId: "trace:0" },- { trace, itemId: "trace:2" },- ]),- );- act(() => result.current.onSelect(0));- await act(- async () =>- await new Promise((resolve) => window.setTimeout(resolve, 300)),- );- fireEvent(- feed,- eventType === "keydown"- ? new KeyboardEvent(eventType, { key: "ArrowDown" })- : new Event(eventType),- );- expect(result.current.activeItemId).toBe("trace:0");- feed.scrollTop = 80;- fireEvent.scroll(feed);- expect(result.current.activeItemId).toBe("trace:0");- feed.scrollTop = 81;- fireEvent.scroll(feed);- expect(result.current.activeItemId).toBe("trace:2");- },- );-it("uses content starts rather than clamped scroll offsets at the natural bottom", () => {const feed = createMeasuredFeed();appendMeasuredRow(feed, "trace:2", "2:0", 9_750);@@ -212,28 +345,6 @@ describe("useSessionConversationTimelineController", () => {).toBeCloseTo(9_700);});- it("navigates to rows without an observation and releases selection to the scroll spy", async () => {- const feed = createMeasuredFeed();- appendMeasuredRow(feed, "trace:2", "2:0", 140);- const { result, rerender } = renderHook(() =>- useSessionConversationTimelineController([- { trace, itemId: "trace:0" },- { trace, itemId: "trace:2" },- { trace, itemId: "trace:4" },- ]),- );- act(() => result.current.onSelect(1, undefined, "2:0"));- expect(result.current.activeItemId).toBe("trace:2");- expect(feed.scrollTop).toBe(40);- await act(- async () =>- await new Promise((resolve) => window.setTimeout(resolve, 300)),- );- virtualizer.scrollOffset = 200;- rerender();- expect(result.current.activeItemId).toBe("trace:4");- });-it("lets the latest click win when an earlier row mounts later", async () => {const feed = createMeasuredFeed();const { result } = renderHook(() =>@@ -292,57 +403,50 @@ describe("useSessionConversationTimelineController", () => {expect(feed.scrollTop).toBe(0);});- it("aligns rows with the scroll-spy anchor in offset containers rather than centering", () => {- const feed = document.createElement("div");- feedRef.current = feed;- Object.defineProperty(feed, "clientHeight", { value: 500 });- feed.scrollTop = 100;- feed.getBoundingClientRect = () => new DOMRect(0, 200, 100, 500);- feed.scrollTo = vi.fn();- const item = document.createElement("div");- item.dataset.sessionTraceId = trace.id;- const row = document.createElement("div");- row.dataset.sessionObservationId = "generation";- row.dataset.sessionTranscriptRowId = "0:1";- row.getBoundingClientRect = () => new DOMRect(0, 450, 100, 100);- item.append(row);- feed.append(item);- const { result } = renderHook(() =>- useSessionConversationTimelineController([{ trace }]),- );- act(() => result.current.onSelect(0, "generation", "0:1"));- expect(feed.scrollTo).toHaveBeenCalledWith({- top: 250,- behavior: "auto",- });- });-it.each(["wheel", "touchstart", "pointerdown", "keydown"])(- "cancels delayed row navigation on %s intent",+ "cancels animation and delayed row navigation on %s intent",async (eventType) => {- const feed = document.createElement("div");- feedRef.current = feed;- feed.scrollTo = vi.fn();+ vi.useFakeTimers({+ toFake: [+ "setTimeout",+ "clearTimeout",+ "requestAnimationFrame",+ "cancelAnimationFrame",+ "performance",+ ],+ });+ vi.mocked(window.matchMedia).mockReturnValue({+ ...window.matchMedia("(prefers-reduced-motion: reduce)"),+ matches: false,+ });+ const feed = createMeasuredFeed();const { result } = renderHook(() =>- useSessionConversationTimelineController([{ trace }]),+ useSessionConversationTimelineController(+ Array.from({ length: 21 }, (_, index) => ({+ trace,+ itemId: `trace:${index}`,+ })),+ ),);- act(() => result.current.onSelect(0, "generation", "0:1"));+ act(() => result.current.onSelect(20, undefined, "20:1"));+ await act(async () => await vi.advanceTimersByTimeAsync(64));+ expect(feed.scrollTop).toBeGreaterThan(0);+ expect(feed.scrollTop).toBeLessThan(1_900);fireEvent(feed,eventType === "keydown"? new KeyboardEvent("keydown", { key: "PageUp" }): new Event(eventType),);+ const stoppedTop = feed.scrollTop;vi.mocked(feed.scrollTo).mockClear();- const item = document.createElement("div");- item.dataset.sessionTraceId = trace.id;- const row = document.createElement("div");- row.dataset.sessionObservationId = "generation";- row.dataset.sessionTranscriptRowId = "0:1";- item.append(row);- feed.append(item);- await act(async () => await Promise.resolve());+ appendMeasuredRow(feed, "trace:20", "20:1", 2_500);+ await act(async () => await vi.advanceTimersByTimeAsync(500));+ expect(feed.scrollTop).toBe(stoppedTop);expect(feed.scrollTo).not.toHaveBeenCalled();+ expect(+ feed.querySelector("[data-session-navigation-highlight]"),+ ).toBeNull();},);@@ -389,17 +493,15 @@ describe("useSessionConversationTimelineController", () => {});it("selects the exact thread item when observations repeat", () => {- const feed = document.createElement("div");- Object.defineProperty(feed, "clientHeight", { value: 500 });- feedRef.current = feed;- feed.scrollTo = vi.fn();+ const feed = createMeasuredFeed();for (const [index, itemId] of ["trace:0", "trace:2"].entries()) {const item = document.createElement("div");item.dataset.sessionTraceId = trace.id;item.dataset.sessionItemId = itemId;const row = document.createElement("div");row.dataset.sessionObservationId = "generation";- row.getBoundingClientRect = () => new DOMRect(0, index * 100, 100, 0);+ row.getBoundingClientRect = () =>+ new DOMRect(0, 200 + 400 + index * 300 - feed.scrollTop, 100, 100);item.append(row);feed.append(item);}@@ -411,10 +513,7 @@ describe("useSessionConversationTimelineController", () => {);act(() => result.current.onSelect(1, "generation"));expect(result.current.activeItemId).toBe("trace:2");- expect(feed.scrollTo).toHaveBeenCalledWith({- top: 0,- behavior: "auto",- });+ expect(feed.scrollTop).toBe(600);});it("scrolls to the exact row when multiple rows share an observation", () => {const feed = document.createElement("div");@@ -439,29 +538,7 @@ describe("useSessionConversationTimelineController", () => {expect(result.current.activeItemId).toBe("trace");expect(feed.scrollTo).toHaveBeenCalledWith({top: 100,- behavior: "auto",+ behavior: "instant",});});-- it("waits for a virtualized row to mount before scrolling", async () => {- const feed = document.createElement("div");- feedRef.current = feed;- feed.scrollTo = vi.fn();- const { result } = renderHook(() =>- useSessionConversationTimelineController([{ trace }]),- );- act(() => result.current.onSelect(0, "generation", "0:1"));- expect(feed.scrollTo).toHaveBeenCalledWith({ top: 0, behavior: "auto" });- vi.mocked(feed.scrollTo).mockClear();-- const traceElement = document.createElement("div");- traceElement.dataset.sessionTraceId = trace.id;- const row = document.createElement("div");- row.dataset.sessionObservationId = "generation";- row.dataset.sessionTranscriptRowId = "0:1";- row.getBoundingClientRect = () => new DOMRect(0, 200, 100, 0);- traceElement.append(row);- feed.append(traceElement);- await waitFor(() => expect(feed.scrollTo).toHaveBeenCalledOnce());- });});diff --git a/web/src/features/sessions/hooks/useSessionConversationTimelineController.ts b/web/src/features/sessions/hooks/useSessionConversationTimelineController.tsindex aa18b0ad40..c9cf23d7bf 100644--- a/web/src/features/sessions/hooks/useSessionConversationTimelineController.ts+++ b/web/src/features/sessions/hooks/useSessionConversationTimelineController.ts@@ -12,6 +12,8 @@ import {const SESSION_TIMELINE_OVERSCAN = 5;const SESSION_TIMELINE_ANCHOR_RATIO = 0.2;+const SESSION_TIMELINE_SCROLL_TIME_CONSTANT_MS = 80;+const SESSION_TIMELINE_HIGHLIGHT_MS = 1_500;export type SessionConversationTimelineScrollTarget = {itemId?: string;traceId: string;@@ -63,11 +65,18 @@ export function useSessionConversationTimelineController(fallbackOffset?: number;} | null>(null);const navigationCleanupRef = useRef<(() => void) | null>(null);+ const highlightCleanupRef = useRef<(() => void) | null>(null);const latestTracesRef = useRef(traces);useLayoutEffect(() => {latestTracesRef.current = traces;}, [traces]);- useEffect(() => () => navigationCleanupRef.current?.(), []);+ useEffect(+ () => () => {+ navigationCleanupRef.current?.();+ highlightCleanupRef.current?.();+ },+ [],+ );useEffect(() => {const feed = feedRef.current;@@ -87,7 +96,14 @@ export function useSessionConversationTimelineController(return () => feed.removeEventListener("scroll", clearFallback);}, [feedRef, selection]);- const onSelect = (index: number, observationId?: string, rowId?: string) => {+ const onSelect = (+ index: number,+ observationId?: string,+ rowId?: string,+ toolGroupId?: string,+ ) => {+ highlightCleanupRef.current?.();+ highlightCleanupRef.current = null;navigationCleanupRef.current?.();navigationCleanupRef.current = null;setSelection(null);@@ -103,6 +119,11 @@ export function useSessionConversationTimelineController(let previousTarget: number | undefined;let stableSince = performance.now();let previousScrollTop = feed.scrollTop;+ let previousFrameTime = performance.now();+ let highlightedTarget: HTMLElement | null = null;+ const reduceMotion = window.matchMedia(+ "(prefers-reduced-motion: reduce)",+ ).matches;let stopped = false;const cleanup = () => {stopped = true;@@ -115,6 +136,7 @@ export function useSessionConversationTimelineController(};const cancel = () => {cleanup();+ highlightCleanupRef.current?.();navigationCleanupRef.current = null;feed.scrollTo({ top: feed.scrollTop, behavior: "instant" });setSelection(null);@@ -158,6 +180,7 @@ export function useSessionConversationTimelineController(}if (currentIndex === -1) {cleanup();+ highlightCleanupRef.current?.();navigationCleanupRef.current = null;setSelection(null);return;@@ -184,6 +207,15 @@ export function useSessionConversationTimelineController(): undefined;const mountedTarget = rowId || observationId ? row : entry;+ const highlightTarget = toolGroupId+ ? Array.from(+ entry?.querySelectorAll<HTMLElement>(+ "[data-session-tool-group-id]",+ ) ?? [],+ ).find(+ (element) => element.dataset.sessionToolGroupId === toolGroupId,+ )+ : mountedTarget;const measurements = virtualizer.measurementsCache;const itemOffset = measurements[currentIndex]?.start;if (itemOffset === undefined) {@@ -205,10 +237,57 @@ export function useSessionConversationTimelineController(endTransitionRatio: 0.2,viewportInset: viewportHeight * SESSION_TIMELINE_ANCHOR_RATIO,});- if (previousTarget === undefined || Math.abs(previousTarget - top) > 1) {+ const targetChanged =+ previousTarget === undefined || Math.abs(previousTarget - top) > 1;+ if (targetChanged) {previousTarget = top;stableSince = performance.now();- feed.scrollTo({ top, behavior: "auto" });+ }+ const now = performance.now();+ const elapsed = Math.max(0, now - previousFrameTime);+ previousFrameTime = now;+ // Retarget each frame as virtual rows mount and resize, without restarting+ // a browser smooth-scroll animation or relying on estimated row heights.+ const distance = top - feed.scrollTop;+ // Integer scroll positions would otherwise stall on subpixel steps.+ const step = Math.min(+ Math.abs(distance),+ Math.max(+ elapsed > 0 ? 1 : 0,+ Math.abs(distance) *+ (1 - Math.exp(-elapsed / SESSION_TIMELINE_SCROLL_TIME_CONSTANT_MS)),+ ),+ );+ const nextTop =+ reduceMotion || Math.abs(distance) <= 1+ ? top+ : feed.scrollTop + Math.sign(distance) * step;+ if (reduceMotion ? targetChanged : nextTop !== feed.scrollTop) {+ feed.scrollTo({ top: nextTop, behavior: "instant" });+ }+ if (highlightTarget && highlightTarget !== highlightedTarget) {+ const targetBounds = highlightTarget.getBoundingClientRect();+ const viewportTop = feed.getBoundingClientRect().top + feed.clientTop;+ if (+ targetBounds.bottom > viewportTop &&+ targetBounds.top < viewportTop + feed.clientHeight+ ) {+ highlightCleanupRef.current?.();+ highlightedTarget = highlightTarget;+ highlightTarget.dataset.sessionNavigationHighlight = "";+ const clearHighlight = () => {+ highlightTarget.removeAttribute(+ "data-session-navigation-highlight",+ );+ window.clearTimeout(highlightTimeout);+ highlightCleanupRef.current = null;+ };+ const highlightTimeout = window.setTimeout(+ clearHighlight,+ SESSION_TIMELINE_HIGHLIGHT_MS,+ );+ highlightCleanupRef.current = clearHighlight;+ }}if (virtualizer.isScrolling ||