πͺ’ 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(trace): let the compact timeline's tooltip leave the timeline (#16314)
Nikita Kabardin18b181ca67e6
diff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsxindex 46b28268c8..afca6982a5 100644--- a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.stories.tsx@@ -509,8 +509,10 @@ export const TooltipShowsCostAndTokens = meta.story({}),);+ // `document`, not `canvasElement`: the tooltip renders in the tooltip layer,+ // which is a body-level sibling of the app root.const tooltip = () =>- canvasElement.querySelector<HTMLElement>(+ document.querySelector<HTMLElement>('[data-testid="timeline-dense-tooltip"]',);await waitFor(() => expect(tooltip()).not.toBeNull());@@ -1102,7 +1104,7 @@ export const TooltipFollowsTheContent = meta.story({);if (!surface) throw new Error("dense surface not found");const tooltip = () =>- canvasElement.querySelector<HTMLElement>(+ document.querySelector<HTMLElement>('[data-testid="timeline-dense-tooltip"]',)?.textContent ?? "";@@ -1428,9 +1430,10 @@ export const HoverOpensATooltip = meta.story({);// Hover names what you are on β this layout spends no row pixels on text.+ // In the tooltip layer, so `document` rather than the story canvas.await waitFor(() =>expect(- canvasElement.querySelector('[data-testid="timeline-dense-tooltip"]'),+ document.querySelector('[data-testid="timeline-dense-tooltip"]'),).not.toBeNull(),);// And hovering must not move anything: no reflow, no new scroll.@@ -1604,3 +1607,73 @@ export const ADoubleTapSelectsOnce = meta.story({await expect(onSelect.mock.calls.length).toBe(1);},});++/**+ * The tooltip is the one thing in this renderer that belongs OUTSIDE the box.+ * Kept inside, it had to be clamped to the room left β and the clamp measured its+ * height with a guess (one row, when it grew to two), so hovering a row near the+ * bottom of a short panel cut the metrics line clean off.+ */+export const TheTooltipEscapesTheSurface = meta.story({+ name: "(Test) The Tooltip Escapes The Surface",+ args: {+ roots: manySpans(40),+ box: PEEK,+ gutter: "auto",+ pointer: "fine",+ barColor: "type",+ compress: false,+ showReadout: true,+ selectedId: null,+ onSelect: fn(),+ onHover: fn(),+ factsOf: () => ["$0.006425", "2,100 β 380 (β 2,480)"],+ },+ play: async ({ canvasElement }) => {+ const surface = canvasElement.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-surface"]',+ );+ if (!surface) throw new Error("dense surface not found");+ const rect = surface.getBoundingClientRect();+ // The LAST row, hard against the bottom edge β the case in the report.+ surface.dispatchEvent(+ new PointerEvent("pointermove", {+ bubbles: true,+ pointerType: "mouse",+ clientX: rect.left + rect.width * 0.7,+ clientY: rect.bottom - 3,+ }),+ );++ const tooltip = await waitFor(() => {+ const el = document.querySelector<HTMLElement>(+ '[data-testid="timeline-dense-tooltip"]',+ );+ if (!el) throw new Error("no tooltip");+ return el;+ });++ // Not inside the box that clips it. Everything else here follows from that.+ await expect(surface.contains(tooltip)).toBe(false);++ // Both rows drawn, and nothing of it cut: an element clipped by an ancestor+ // still reports its full box, so the thing to check is that its own content+ // fits and that the box is on screen.+ await expect(tooltip.scrollHeight).toBeLessThanOrEqual(+ tooltip.clientHeight,+ );+ await expect(tooltip.innerText).toContain("$0.006425");+ const box = tooltip.getBoundingClientRect();+ await expect(box.height).toBeGreaterThan(20);+ await expect(box.bottom).toBeLessThanOrEqual(window.innerHeight + 0.5);+ await expect(box.right).toBeLessThanOrEqual(window.innerWidth + 0.5);+ await expect(box.top).toBeGreaterThanOrEqual(-0.5);+ await expect(box.left).toBeGreaterThanOrEqual(-0.5);++ // And the surface still has nothing to scroll β it never held the tooltip.+ await expect(surface.scrollWidth).toBeLessThanOrEqual(surface.clientWidth);+ await expect(surface.scrollHeight).toBeLessThanOrEqual(+ surface.clientHeight,+ );+ },+});diff --git a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsxindex 5befcf8f50..76d499d4dd 100644--- a/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx+++ b/web/src/features/traces/components/TraceTimelineDense/TimelineDense.tsx@@ -47,6 +47,7 @@* and absolutely-positioned rows are the wrong substrate. That is the next spike.*/+import { type CSSProperties } from "react";import { useTheme } from "next-themes";import {useCallback,@@ -64,6 +65,11 @@ import {Plus,} from "lucide-react";import { ItemBadge, type LangfuseItemType } from "@/src/components/ItemBadge";+import {+ tooltipPlacement,+ type TooltipPlacement,+} from "../../fns/timeline/tooltipPlacement";+import { Layer } from "@/src/components/ui/layer";import { cn } from "@/src/utils/tailwind";import { type Density, type PointerModality } from "../../fns/timeline/density";import {@@ -306,9 +312,13 @@ export function TimelineDense({factsOf,}: TimelineDenseProps) {const [viewport, setViewport] = useState<Viewport | null>(null);- const [pointerPos, setPointerPos] = useState<{ x: number; y: number } | null>(- null,- );+ const [pointerPos, setPointerPos] = useState<{+ x: number;+ y: number;+ /** The same point in VIEWPORT coordinates, for the tooltip's own layer. */+ clientX: number;+ clientY: number;+ } | null>(null);const [dragging, setDragging] = useState(false);/*** Shift-drag box, in surface coordinates, while it is being drawn. The REF is@@ -488,7 +498,9 @@ export function TimelineDense({*/const notifyHover = (viewport: Viewport,- at = pointerPosRef.current,+ // Only the surface-local point matters here; the viewport coordinates the+ // tooltip needs are not this function's business.+ at: { x: number; y: number } | null = pointerPosRef.current,): void => {if (!at || !onHover) return;const live = layoutRef.current;@@ -1032,7 +1044,12 @@ export function TimelineDense({}notifyHover(current, { x: offsetX, y: offsetY });- setPointerPos({ x: offsetX, y: offsetY });+ setPointerPos({+ x: offsetX,+ y: offsetY,+ clientX: event.clientX,+ clientY: event.clientY,+ });};/** Release of a shift-drag: fly to the box, if it is big enough to mean one. */@@ -1588,64 +1605,58 @@ export function TimelineDense({</div>) : null}- {/* The tooltip is what names a row when the gutter cannot. */}+ {/* The tooltip is what names a row when the gutter cannot β and it is the+ one thing here that belongs OUTSIDE the box. Kept inside, it had to be+ clamped to the space left, which on the bottom rows of a short panel+ meant clamping it against a guess at its own height and cutting the+ metrics line off. In the tooltip layer nothing clips it, and the+ surface still has nothing to scroll because it is not in the surface.++ It anchors to whichever side of the pointer has room rather than+ measuring itself: the side with room is known from the pointer alone,+ a size is not, and a tooltip that has to be measured before it can be+ placed is a tooltip that renders once in the wrong place. */}{focused && pointerPos && !dragging && pointerPos.x > gutterWidth ? (- <div- className="border-border bg-background text-foreground pointer-events-none absolute z-10 flex flex-col gap-0.5 overflow-hidden rounded border px-1.5 py-1 shadow-md"- style={{- left:- pointerPos.x > contentWidth * 0.55- ? undefined- : `${Math.round(pointerPos.x + 12)}px`,- right:- pointerPos.x > contentWidth * 0.55- ? `${Math.round(Math.max(contentWidth - pointerPos.x + 12, 4))}px`- : undefined,- // Clamped to the space left, not a percentage guess: an unclamped- // tooltip poked past the surface and put 5px of scrollWidth on a- // box whose whole claim is that nothing scrolls.- maxWidth: `${Math.max(- pointerPos.x > contentWidth * 0.55- ? pointerPos.x - 16- : contentWidth - pointerPos.x - 16,- 80,- )}px`,- top: `${Math.round(- Math.min(- Math.max(pointerPos.y + 12, 2),- Math.max(surfaceHeight - 26, 2),- ),- )}px`,- fontSize: "10px",- }}- data-testid="timeline-dense-tooltip"- >- {/* Two rows, like a tree row: identity, then the metrics. One row- made the NAME the only flexible item, so adding cost and tokens- truncated it away β and the name is the thing you hovered for. */}- <span className="flex items-center gap-1">- <span- className={cn(- "h-2 w-2 shrink-0 rounded-[1px]",- TYPE_COLOR[focused.type] ?? FALLBACK_COLOR,- )}- />- <span className="truncate" title={focused.name}>- {focused.name}+ <Layer name="tooltip">+ <div+ className="border-border bg-background text-foreground pointer-events-none fixed flex flex-col gap-0.5 rounded border px-1.5 py-1 shadow-md"+ style={tooltipStyle(+ tooltipPlacement({+ clientX: pointerPos.clientX,+ clientY: pointerPos.clientY,+ viewportWidth: window.innerWidth,+ viewportHeight: window.innerHeight,+ }),+ )}+ data-testid="timeline-dense-tooltip"+ >+ {/* Two rows, like a tree row: identity, then the metrics. One row+ made the NAME the only flexible item, so adding cost and tokens+ truncated it away β and the name is the thing you hovered for. */}+ <span className="flex items-center gap-1">+ <span+ className={cn(+ "h-2 w-2 shrink-0 rounded-[1px]",+ TYPE_COLOR[focused.type] ?? FALLBACK_COLOR,+ )}+ />+ <span className="truncate" title={focused.name}>+ {focused.name}+ </span></span>- </span>- <span className="text-muted-foreground flex flex-wrap items-center gap-x-1.5 gap-y-0.5">- <span>- {focused.durationMs == null- ? "β"- : formatDurationMs(focused.durationMs)}+ <span className="text-muted-foreground flex flex-wrap items-center gap-x-1.5 gap-y-0.5">+ <span>+ {focused.durationMs == null+ ? "β"+ : formatDurationMs(focused.durationMs)}+ </span>+ <span>@{formatDurationMs(focused.startMs)}</span>+ {factsOf?.(focused.id).map((fact) => (+ <span key={fact}>{fact}</span>+ ))}</span>- <span>@{formatDurationMs(focused.startMs)}</span>- {factsOf?.(focused.id).map((fact) => (- <span key={fact}>{fact}</span>- ))}- </span>- </div>+ </div>+ </Layer>) : null}</div>@@ -1680,6 +1691,17 @@ export function TimelineDense({* its name, indented by depth. Shared by the in-flow rail and the peek overlay so* the two cannot drift apart.*/+/** The placement as inline style. Split out so the geometry stays pure. */+function tooltipStyle(placement: TooltipPlacement): CSSProperties {+ return {+ left: `${Math.round(placement.left)}px`,+ top: `${Math.round(placement.top)}px`,+ transform: placement.transform,+ maxWidth: `${Math.round(placement.maxWidth)}px`,+ fontSize: "10px",+ };+}+function GutterContent({node,width,diff --git a/web/src/features/traces/fns/timeline/layout.clienttest.ts b/web/src/features/traces/fns/timeline/layout.clienttest.tsindex c3ff64d28c..23e6445932 100644--- a/web/src/features/traces/fns/timeline/layout.clienttest.ts+++ b/web/src/features/traces/fns/timeline/layout.clienttest.ts@@ -9,6 +9,7 @@ import {type TimelineLayout,} from "./layout";import { PX_PER_LETTER, createTextMeasurerFrom } from "./textMeasurer";+import { tooltipPlacement } from "./tooltipPlacement";import {MAX_ZOOM_PRECISION_MS,clampView,@@ -321,6 +322,85 @@ describe("textMeasurer", () => {});});+describe("tooltipPlacement", () => {+ /** The box the placement implies, given a content size it never asks about. */+ const boxOf = (+ placement: ReturnType<typeof tooltipPlacement>,+ height: number,+ ) => {+ const width = placement.maxWidth;+ const flipX = placement.transform.includes("-100%,");+ const flipY = placement.transform.endsWith("-100%)");+ return {+ left: flipX ? placement.left - width : placement.left,+ right: flipX ? placement.left : placement.left + width,+ top: flipY ? placement.top - height : placement.top,+ bottom: flipY ? placement.top : placement.top + height,+ };+ };++ it("never leaves the viewport, at any window size or pointer position", () => {+ // Phone through desktop, including the widths where a fixed 320px cap and a+ // fixed flip threshold disagree β that combination ran the box off the right+ // edge for any pointer just short of the threshold.+ for (const viewportWidth of [320, 480, 700, 800, 830, 1024, 1280, 1920]) {+ for (const viewportHeight of [300, 568, 658, 900]) {+ for (const fraction of [0, 0.1, 0.49, 0.5, 0.51, 0.59, 0.6, 0.61, 1]) {+ const clientX = Math.round(viewportWidth * fraction);+ const clientY = Math.round(viewportHeight * fraction);+ const placement = tooltipPlacement({+ clientX,+ clientY,+ viewportWidth,+ viewportHeight,+ });+ // Two text lines, and then some, since the metrics line can wrap.+ const box = boxOf(placement, 80);+ const at = `${viewportWidth}x${viewportHeight} @${fraction}`;+ expect(box.left, `left ${at}`).toBeGreaterThanOrEqual(0);+ expect(box.right, `right ${at}`).toBeLessThanOrEqual(viewportWidth);+ expect(box.top, `top ${at}`).toBeGreaterThanOrEqual(0);+ expect(box.bottom, `bottom ${at}`).toBeLessThanOrEqual(+ viewportHeight,+ );+ }+ }+ }+ });++ it("takes the roomier side of the pointer", () => {+ const viewport = { viewportWidth: 1000, viewportHeight: 800 };+ // Left of centre: grow right and down, anchored at the pointer.+ expect(+ tooltipPlacement({ clientX: 100, clientY: 100, ...viewport }).transform,+ ).toBe("translate(0, 0)");+ // Right of centre: grow left and up, anchored by its own far edge.+ expect(+ tooltipPlacement({ clientX: 900, clientY: 700, ...viewport }).transform,+ ).toBe("translate(-100%, -100%)");+ });++ it("spends the room it has, and never more", () => {+ const viewport = { viewportWidth: 1000, viewportHeight: 800 };+ // Middle of a wide window: the full width is affordable.+ expect(+ tooltipPlacement({ clientX: 300, clientY: 400, ...viewport }).maxWidth,+ ).toBe(320);+ // 200px from the left edge leaves 200 minus the offset and the margin.+ expect(+ tooltipPlacement({ clientX: 200, clientY: 400, ...viewport }).maxWidth,+ ).toBe(320);+ expect(+ tooltipPlacement({+ clientX: 120,+ clientY: 400,+ viewportWidth: 260,+ viewportHeight: 800,+ }).maxWidth,+ ).toBe(260 - 120 - 16);+ });+});+describe("formatDurationMs", () => {it("keeps labels short at every magnitude", () => {expect(formatDurationMs(0)).toBe("0ms");diff --git a/web/src/features/traces/fns/timeline/tooltipPlacement.ts b/web/src/features/traces/fns/timeline/tooltipPlacement.tsnew file mode 100644index 0000000000..3b68ff9031--- /dev/null+++ b/web/src/features/traces/fns/timeline/tooltipPlacement.ts@@ -0,0 +1,63 @@+/**+ * Where a pointer-anchored tooltip goes, in viewport coordinates.+ *+ * Pure because the interesting part is the edges, and the edges are a function of+ * two viewport sizes and a point β none of which a story can vary, since a play+ * function cannot resize the window it runs in. Here they can all be swept.+ *+ * The rule: anchor to whichever side of the pointer has MORE room, and cap the+ * width at the room that side actually has. Both halves are load-bearing.+ * Choosing a side by a fixed threshold and capping the width at a fixed number+ * are independently reasonable and jointly wrong β on a window narrower than+ * ~830px a pointer just short of the threshold anchored left and then ran a+ * 320px box off the right edge, which is the clipping this replaced, one axis+ * over.+ *+ * Nothing here measures the tooltip. A size is not knowable before the thing is+ * rendered, and something that must be measured before it can be placed is+ * placed wrongly once, visibly, every time it appears.+ */++/** How far off the pointer the tooltip sits, so the cursor never covers it. */+const OFFSET_PX = 12;+/** Widest it ever gets, room permitting. */+const MAX_WIDTH_PX = 320;+/** Kept off the viewport edge itself. */+const EDGE_PX = 4;+/**+ * Never priced below this: a window narrow enough to force it is narrower than+ * any real one, and a zero-width tooltip is worse than one hanging over an edge.+ */+const MIN_WIDTH_PX = 60;++export type TooltipPlacement = {+ left: number;+ top: number;+ /** `translate(β¦)` β the flip, which is what keeps this measurement-free. */+ transform: string;+ maxWidth: number;+};++export function tooltipPlacement(input: {+ clientX: number;+ clientY: number;+ viewportWidth: number;+ viewportHeight: number;+}): TooltipPlacement {+ const { clientX, clientY, viewportWidth, viewportHeight } = input;+ // The roomier side, not a fixed fraction: at the halfway point the two are+ // equal, so this is the only split that cannot pick the cramped one.+ const flipX = clientX > viewportWidth / 2;+ const flipY = clientY > viewportHeight / 2;++ const roomX = flipX+ ? clientX - OFFSET_PX - EDGE_PX+ : viewportWidth - clientX - OFFSET_PX - EDGE_PX;++ return {+ left: clientX + (flipX ? -OFFSET_PX : OFFSET_PX),+ top: clientY + (flipY ? -OFFSET_PX : OFFSET_PX),+ transform: `translate(${flipX ? "-100%" : "0"}, ${flipY ? "-100%" : "0"})`,+ maxWidth: Math.max(Math.min(MAX_WIDTH_PX, roomX), MIN_WIDTH_PX),+ };+}