🪢 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): Sidebar scroll snapping (#19030)
Ben Bachemc329fa08e5ac
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 cdd067e5d8..de606a4826 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@@ -12,6 +12,7 @@ import {} from "@/src/features/sessions/hooks/useSessionConversationTimelineController";import { getSessionConversationEntries } from "../../fns/getSessionConversationEntries";import { type Observation } from "@langfuse/shared";+import { useDebounce } from "@/src/hooks/useDebounce";type TraceProps = ComponentProps<typeof SessionConversationalView@@ -2306,6 +2307,7 @@ function SessionConversationalViewStory({viewportWidth,pageOffset = 0,delayedLoad = false,+ delayedSearch = false,}: {workflowTraces?: WorkflowFixture[];transcriptTraces?: TraceProps[];@@ -2317,9 +2319,12 @@ function SessionConversationalViewStory({viewportWidth?: number;pageOffset?: number;delayedLoad?: boolean;+ delayedSearch?: boolean;}) {const [transcriptsLoaded, setTranscriptsLoaded] = useState(!delayedLoad);const [search, setSearch] = useState("");+ const [appliedSearch, setAppliedSearch] = useState("");+ const applySearch = useDebounce(setAppliedSearch, 500, false);const [collapsedTraceIds, setCollapsedTraceIds] = useState<Set<string>>(new Set(),);@@ -2429,6 +2434,8 @@ function SessionConversationalViewStory({}return (<div+ role="group"+ aria-label="Session workspace"className="@container/session-workspace relative flex h-screen min-w-[320px]"style={{height:@@ -2451,13 +2458,18 @@ function SessionConversationalViewStory({<SessionConversationalViewstate="loaded"search={search}- searchQuery={searchQueryOverride ?? search.trim()}+ searchQuery={+ searchQueryOverride ?? (delayedSearch ? appliedSearch : search.trim())+ }isSearchPending={isSearchPending ||(searchQueryOverride !== undefined &&search.trim() !== searchQueryOverride)}- onSearchChange={setSearch}+ onSearchChange={(value) => {+ setSearch(value);+ if (delayedSearch) applySearch(value.trim());+ }}expandedTraceIds={new Set(entries@@ -3190,7 +3202,11 @@ export const VirtualizedNavigation = meta.story({export const SearchThreadNavigation = meta.story({name: "(Test) Filtered Thread Indices And Individual Tools",- args: { transcriptTraces: navigationTraces, viewportHeight: 480 },+ args: {+ transcriptTraces: navigationTraces,+ viewportHeight: 480,+ delayedSearch: true,+ },play: async ({ canvasElement }) => {const canvas = within(canvasElement);const sidebar = within(canvas.getByRole("complementary"));@@ -3200,7 +3216,7 @@ export const SearchThreadNavigation = meta.story({sidebar.queryByRole("button", { name: /^9\.1/ }),).not.toBeInTheDocument();await userEvent.click(- sidebar.getByRole("button", { name: "Assistant message" }),+ await sidebar.findByRole("button", { name: "Assistant message" }),);await expectNavigation(canvasElement,@@ -3210,6 +3226,11 @@ export const SearchThreadNavigation = meta.story({);await userEvent.clear(search);await userEvent.type(search, "save");+ await waitFor(() =>+ expect(+ sidebar.queryByRole("button", { name: "Assistant message" }),+ ).not.toBeInTheDocument(),+ );const header = await sidebar.findByRole("button", {name: /^9\.2 Navigation turn 9/,});@@ -3222,6 +3243,7 @@ export const SearchThreadNavigation = meta.story({"2:4",);await userEvent.clear(search);+ await new Promise((resolve) => window.setTimeout(resolve, 700));await waitFor(() =>expect(@@ -3229,6 +3251,25 @@ export const SearchThreadNavigation = meta.story({).toHaveAttribute("aria-current", "true"),{ timeout: 3_000 },);+ await userEvent.type(search, "no matching transcript");+ await sidebar.findByText("No matching turns");+ await userEvent.clear(search);+ await waitFor(+ () => {+ const active = sidebar.getByRole("button", {+ name: /^9\.2 Navigation turn 9/,+ });+ const list = canvas.getByRole("region", { name: "Session turns" });+ expect(active).toHaveAttribute("aria-current", "true");+ expect(active.getBoundingClientRect().top).toBeGreaterThanOrEqual(+ list.getBoundingClientRect().top,+ );+ expect(active.getBoundingClientRect().bottom).toBeLessThanOrEqual(+ list.getBoundingClientRect().bottom,+ );+ },+ { timeout: 3_000 },+ );},});@@ -3284,40 +3325,49 @@ export const DelayedTranscriptNavigation = meta.story({},});-export const SidebarFollowResume = meta.story({- name: "(Test) Sidebar Follow Resumes After User Idle",- args: { transcriptTraces: navigationTraces, viewportHeight: 480 },+export const SidebarManualScroll = meta.story({+ name: "(Test) Sidebar Scrolling And Selection",+ args: {+ transcriptTraces: navigationTraces,+ viewportHeight: 480,+ viewportWidth: 1200,+ },play: async ({ canvasElement }) => {const canvas = within(canvasElement);- const feed = canvas.getByLabelText("Session conversation timeline");const list = canvas.getByRole("region", { name: "Session turns" });- const sidebar = within(canvas.getByRole("complementary"));+ const feed = canvas.getByLabelText("Session conversation timeline");+ const initialFeedScroll = feed.scrollTop;+list.dispatchEvent(new WheelEvent("wheel", { deltaY: 100, bubbles: true }));- await waitFor(- () => {- // Newly mounted rows replace estimates, moving the end of the timeline.- feed.scrollTo({ top: feed.scrollHeight, behavior: "instant" });- expect(- sidebar.getByRole("button", { name: /^32\.2 Navigation turn 32/ }),- ).toHaveAttribute("aria-current", "true");- },- { timeout: 3_000 },- );- await waitFor(- () => {- const active = sidebar.getByRole("button", {- name: /^32\.2 Navigation turn 32/,- });- expect(active).toHaveAttribute("aria-current", "true");- const activeRect = active.getBoundingClientRect();+ list.scrollTo({ top: 1500, behavior: "instant" });+ await waitFor(() => expect(list.scrollTop).toBeGreaterThan(1000));+ // Wait beyond the former idle timeout, including virtualized row measurements.+ await new Promise((resolve) => window.setTimeout(resolve, 1000));+ await expect(list.scrollTop).toBeGreaterThan(1000);+ await expect(feed.scrollTop).toBe(initialFeedScroll);++ const sidebar = within(canvas.getByRole("complementary"));+ const visibleTurn = sidebar+ .getAllByRole("button", {+ name: /^\d+\.\d+ Navigation turn/,+ })+ .find((button) => {+ const rect = button.getBoundingClientRect();const listRect = list.getBoundingClientRect();- expect(activeRect.top).toBeGreaterThanOrEqual(listRect.top);- expect(activeRect.bottom).toBeLessThanOrEqual(listRect.bottom);- },- { timeout: 3_000 },+ return rect.top >= listRect.top && rect.bottom <= listRect.bottom;+ });+ if (!visibleTurn)+ throw new Error("No visible turn available for selection");+ await userEvent.click(visibleTurn);+ await waitFor(() =>+ expect(visibleTurn).toHaveAttribute("aria-current", "true"),+ );+ await waitFor(() =>+ expect(feed.scrollTop).toBeGreaterThan(initialFeedScroll),);},});+export const NestedThreadsHidden = meta.story({name: "(Test) Nested Threads Hidden",args: {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 8fd4103c2a..7fc70a9681 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@@ -48,7 +48,6 @@ export type SessionConversationSidebarTrace = {};const EMPTY_TRACES: SessionConversationSidebarTrace[] = [];-const SIDEBAR_AUTO_FOLLOW_IDLE_MS = 750;const SIDEBAR_SCROLL_PADDING = 16;export function SessionConversationSidebar(@@ -59,6 +58,7 @@ export function SessionConversationSidebar(traces: SessionConversationSidebarTrace[];activeTraceId: string | undefined;search: string;+ searchQuery?: string;onSearchChange: (search: string) => void;expandedTraceIds: ReadonlySet<string>;onToggleTraceExpanded: (traceId: string) => void;@@ -77,7 +77,8 @@ export function SessionConversationSidebar(const traces = props.state === "loaded" ? props.traces : EMPTY_TRACES;const activeTraceId =props.state === "loaded" ? props.activeTraceId : undefined;- const sidebarSearch = props.state === "loaded" ? props.search : "";+ const appliedSearch =+ props.state === "loaded" ? (props.searchQuery ?? props.search) : "";const listRef = useRef<HTMLDivElement>(null);const textContextRef = useRef<CanvasRenderingContext2D | null>(null);const [toolGroupMeasurement, setToolGroupMeasurement] = useState<{@@ -140,10 +141,12 @@ export function SessionConversationSidebar(document.fonts?.removeEventListener("loadingdone", measureToolGroupLabel);};}, [measureToolGroupLabel, props.state]);- const isSidebarPointerDownRef = useRef(false);- const autoFollowPausedUntilRef = useRef(0);- const autoFollowTimerRef = useRef<number | undefined>(undefined);- const resumeAutoFollowRef = useRef<(() => void) | null>(null);+ const followedSelectionRef = useRef<{+ traceId: string;+ index: number;+ search: string;+ awaitingMeasurement: boolean;+ } | null>(null);const [isListScrolled, setIsListScrolled] = useState(false);const handleListScroll = (event: UIEvent<HTMLDivElement>) =>setIsListScrolled(event.currentTarget.scrollTop > 0);@@ -180,48 +183,48 @@ export function SessionConversationSidebar(.getVirtualItems().find((item) => item.index === activeTraceIndex)?.size;const sidebarHeight = virtualizer.scrollRect?.height;- const setListElement = useCallback(- (element: HTMLDivElement | null) => {- listRef.current = element;- if (- !element ||- activeTraceIndex === -1 ||- isSidebarPointerDownRef.current ||- Date.now() < autoFollowPausedUntilRef.current- )- return;- const availableHeight =- (sidebarHeight ?? element.clientHeight) - SIDEBAR_SCROLL_PADDING * 2;- virtualizer.scrollToIndex(activeTraceIndex, {- align:- activeTraceSize !== undefined && activeTraceSize > availableHeight- ? "start"- : "auto",- });- },- [activeTraceIndex, activeTraceSize, sidebarHeight, virtualizer],- );useLayoutEffect(() => {- resumeAutoFollowRef.current = () => {- setListElement(listRef.current);+ const element = listRef.current;+ const height = sidebarHeight ?? element?.clientHeight ?? 0;+ if (!activeTraceId || activeTraceIndex === -1 || height === 0) {+ followedSelectionRef.current = null;+ return;+ }+ if (!element) return;+ const previous = followedSelectionRef.current;+ const isSameSelection =+ previous?.traceId === activeTraceId &&+ previous.index === activeTraceIndex &&+ previous.search === appliedSearch;+ if (isSameSelection && !previous.awaitingMeasurement) return;+ if (isSameSelection && activeTraceSize === undefined) return;++ // Measurements and rerenders must not pull the user back after manual scrolling.+ followedSelectionRef.current = {+ traceId: activeTraceId,+ index: activeTraceIndex,+ search: appliedSearch,+ awaitingMeasurement: activeTraceSize === undefined,};- setListElement(listRef.current);- }, [setListElement, sidebarSearch]);- useLayoutEffect(- () => () => window.clearTimeout(autoFollowTimerRef.current),- [],- );- const pauseAutoFollow = () => {- autoFollowPausedUntilRef.current = Date.now() + SIDEBAR_AUTO_FOLLOW_IDLE_MS;- window.clearTimeout(autoFollowTimerRef.current);- autoFollowTimerRef.current = window.setTimeout(- () => resumeAutoFollowRef.current?.(),- SIDEBAR_AUTO_FOLLOW_IDLE_MS,- );- };- const handlePointerEnd = () => {- isSidebarPointerDownRef.current = false;- pauseAutoFollow();+ const availableHeight = height - SIDEBAR_SCROLL_PADDING * 2;+ virtualizer.scrollToIndex(activeTraceIndex, {+ align:+ activeTraceSize !== undefined && activeTraceSize > availableHeight+ ? "start"+ : "auto",+ });+ }, [+ activeTraceId,+ activeTraceIndex,+ activeTraceSize,+ appliedSearch,+ sidebarHeight,+ virtualizer,+ ]);+ const cancelPendingFollow = () => {+ if (followedSelectionRef.current) {+ followedSelectionRef.current.awaitingMeasurement = false;+ }};if (props.state === "loading") {@@ -313,13 +316,14 @@ export function SessionConversationSidebar() : null}</div><div- ref={setListElement}+ ref={listRef}role="region"aria-label="Session turns"className="min-h-0 flex-1 overflow-y-auto [overflow-anchor:none]"onScroll={handleListScroll}- onWheel={pauseAutoFollow}- onTouchMove={pauseAutoFollow}+ onWheel={cancelPendingFollow}+ onTouchMove={cancelPendingFollow}+ onPointerDown={cancelPendingFollow}onKeyDown={(event) => {if ([@@ -332,15 +336,9 @@ export function SessionConversationSidebar(" ",].includes(event.key)) {- pauseAutoFollow();+ cancelPendingFollow();}}}- onPointerDown={() => {- isSidebarPointerDownRef.current = true;- }}- onPointerUp={handlePointerEnd}- onPointerCancel={handlePointerEnd}- onPointerLeave={handlePointerEnd}>{traces.length === 0 ? (<div className="text-muted-foreground px-3 py-6 text-center text-xs">