Skip to content

The open-source agent harness - the runtime layer that turns an LLM into a working agent.

chore: update cost breakdown tooltip ui and fixed tooltip hover state (#948)

harshil-209601b27f035187
diff --git a/.changeset/cost-per-turn-tooltip-interactive.md b/.changeset/cost-per-turn-tooltip-interactive.md
new file mode 100644
index 000000000..1c94ed457
--- /dev/null
+++ b/.changeset/cost-per-turn-tooltip-interactive.md
@@ -0,0 +1,5 @@
+---
+'@truefoundry/trueforge-ui': patch
+---
+
+Show cost-per-turn breakdown rows in the session metrics strip tooltip, and make tooltips interactive by default so rich popups stay open while hovering their content. Keep the timeline chart tooltip non-interactive so cursor-anchored hover is not stolen from the canvas.
diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionEventTimelineChart.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionEventTimelineChart.tsx
index 3b870cf56..a8b314b7f 100644
--- a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionEventTimelineChart.tsx
+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionEventTimelineChart.tsx
@@ -578,6 +578,7 @@ export function AgentSessionEventTimelineChart({
side="bottom"
triggerClassName="block w-full"
followCursor
+ interactive={false}
open={tooltipTarget != null && tooltipContent != null}
className="max-w-[min(25rem,calc(100vw-1rem))] whitespace-normal"
anchor={tooltipAnchor}
diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionMetricCharts.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionMetricCharts.tsx
index 3704b8e54..dd369ea11 100644
--- a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionMetricCharts.tsx
+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionMetricCharts.tsx
@@ -3,9 +3,27 @@
import type { ReactNode } from 'react';
import type { SessionMetricBarDatum } from '../../utils/buildSessionMetrics.js';
-import { LightTooltip } from '../primitives/Tooltip.js';
+import { formatCostUsd } from '../../utils/sessionDisplayFormat.js';
-const MIN_VERTICAL_BAR_HEIGHT_PERCENT = 6;
+export function CostBreakdownRows({ data }: { data: SessionMetricBarDatum[] }) {
+ const maxValue = Math.max(0, ...data.map(item => item.value)) || 1;
+ return (
+ <div className="grid grid-cols-[max-content_minmax(0,1fr)_max-content] items-center gap-x-2 gap-y-2">
+ {data.map(item => (
+ <div key={item.label} className="contents">
+ <span className="max-w-28 truncate text-text-secondary">{item.label}</span>
+ <div className="h-1.5 min-w-0 overflow-hidden rounded-full bg-secondary-bg">
+ <div
+ className="h-full rounded-full"
+ style={{ width: `${(item.value / maxValue) * 100}%`, backgroundColor: item.color }}
+ />
+ </div>
+ <span className="text-right font-semibold text-text-primary">{formatCostUsd(item.value)}</span>
+ </div>
+ ))}
+ </div>
+ );
+}
export function SessionMetricTooltipContent({
title,
@@ -88,35 +106,3 @@ export function HorizontalBarRows({
</div>
);
}
-
-export function VerticalBarColumns({
- data,
- formatValue,
-}: {
- data: SessionMetricBarDatum[];
- formatValue: (value: number) => string;
-}) {
- const maxValue = Math.max(0, ...data.map(item => item.value)) || 1;
- return (
- <div className="h-24 overflow-x-auto">
- <div className="mx-auto flex h-full w-fit items-end">
- {data.map(item => (
- <LightTooltip key={item.label} title={formatValue(item.value)} side="top">
- <div className="flex h-full w-10 shrink-0 flex-col items-center justify-end gap-1">
- <div className="flex h-[4.5rem] items-end">
- <div
- className="w-6 rounded-t-sm"
- style={{
- height: `${Math.max(MIN_VERTICAL_BAR_HEIGHT_PERCENT, (item.value / maxValue) * 100)}%`,
- backgroundColor: item.color,
- }}
- />
- </div>
- <span className="text-[0.625rem] leading-4 text-text-secondary">{item.label}</span>
- </div>
- </LightTooltip>
- ))}
- </div>
- </div>
- );
-}
diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionMetricsStrip.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionMetricsStrip.tsx
index f2fbf268f..f1f06fcc7 100644
--- a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionMetricsStrip.tsx
+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionMetricsStrip.tsx
@@ -8,10 +8,10 @@ import { formatTimelineDuration } from '../../utils/sessionEventTimeline.js';
import { cn } from '../lib/cn.js';
import { LightTooltip } from '../primitives/Tooltip.js';
import {
+ CostBreakdownRows,
HorizontalBarRows,
SessionMetricTooltipContent,
StackedProportionBar,
- VerticalBarColumns,
} from './AgentSessionMetricCharts.js';
import type { AgentSessionMetricsStripProps } from './types.js';
@@ -73,8 +73,8 @@ export function AgentSessionMetricsStrip({ metrics }: AgentSessionMetricsStripPr
value={formatCostUsd(metrics.totalCostUsd)}
tooltip={
metrics.costPerTurn.length > 1 && metrics.totalCostUsd > 0 ? (
- <SessionMetricTooltipContent title="Cost per turn" fitWidth>
- <VerticalBarColumns data={metrics.costPerTurn} formatValue={formatCostUsd} />
+ <SessionMetricTooltipContent title="Cost per turn">
+ <CostBreakdownRows data={metrics.costPerTurn} />
</SessionMetricTooltipContent>
) : null
}
diff --git a/packages/trueforge-ui/src/atoms/primitives/Tooltip.tsx b/packages/trueforge-ui/src/atoms/primitives/Tooltip.tsx
index a81a91658..25b56464f 100644
--- a/packages/trueforge-ui/src/atoms/primitives/Tooltip.tsx
+++ b/packages/trueforge-ui/src/atoms/primitives/Tooltip.tsx
@@ -1,6 +1,6 @@
'use client';
-import React, { cloneElement, isValidElement, useLayoutEffect, useRef, useState } from 'react';
+import React, { cloneElement, isValidElement, useEffect, useLayoutEffect, useRef, useState } from 'react';
import { createPortal } from 'react-dom';
import { cn } from '../lib/cn.js';
@@ -8,6 +8,32 @@ import { themePortalRoot } from '../lib/themePortalRoot.js';
const TOOLTIP_VIEWPORT_PAD = 8;
const TOOLTIP_GAP = 6;
+/** Grace period to cross the gap between trigger and portaled popup. */
+const INTERACTIVE_CLOSE_DELAY_MS = 100;
+
+/** Only one uncontrolled hover tooltip may stay open — avoids stacked/adjacent popups. */
+let exclusiveHoverOwner: object | null = null;
+let exclusiveHoverClose: (() => void) | null = null;
+
+function claimExclusiveHover(owner: object, close: () => void) {
+ if (exclusiveHoverOwner != null && exclusiveHoverOwner !== owner) exclusiveHoverClose?.();
+ exclusiveHoverOwner = owner;
+ exclusiveHoverClose = close;
+}
+
+function releaseExclusiveHover(owner: object) {
+ if (exclusiveHoverOwner === owner) {
+ exclusiveHoverOwner = null;
+ exclusiveHoverClose = null;
+ }
+}
+
+function interactiveBridgeStyle(side: TooltipSide): React.CSSProperties {
+ if (side === 'bottom') return { left: 0, right: 0, top: -TOOLTIP_GAP, height: TOOLTIP_GAP };
+ if (side === 'top') return { left: 0, right: 0, bottom: -TOOLTIP_GAP, height: TOOLTIP_GAP };
+ if (side === 'right') return { top: 0, bottom: 0, left: -TOOLTIP_GAP, width: TOOLTIP_GAP };
+ return { top: 0, bottom: 0, right: -TOOLTIP_GAP, width: TOOLTIP_GAP };
+}
export type TooltipSide = 'top' | 'bottom' | 'left' | 'right';
@@ -120,6 +146,8 @@ export type TooltipProps = {
anchor?: TooltipAnchor | null;
/** Controls visibility when provided; otherwise hover/focus owns it. */
open?: boolean;
+ /** When true (default) the tooltip stays open while the cursor is inside the popup. */
+ interactive?: boolean;
};
export function Tooltip({
@@ -132,17 +160,62 @@ export function Tooltip({
followCursor = false,
anchor = null,
open,
+ interactive = true,
}: TooltipProps) {
const [uncontrolledVisible, setUncontrolledVisible] = useState(false);
const visible = open ?? uncontrolledVisible;
+ const controlled = open !== undefined;
const setVisible = (next: boolean) => {
- if (open === undefined) setUncontrolledVisible(next);
+ if (!controlled) setUncontrolledVisible(next);
};
const [pos, setPos] = useState<{ top: number; left: number } | null>(null);
const triggerWrapRef = useRef<HTMLSpanElement>(null);
const tooltipRef = useRef<HTMLSpanElement>(null);
const cursorXRef = useRef<number | null>(null);
const placeRef = useRef<() => void>(() => {});
+ // Tracks how many hover regions (trigger + tooltip) are currently entered.
+ // The tooltip hides only when this drops to zero after the debounce delay.
+ const hoverCountRef = useRef(0);
+ const leaveTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const ownerRef = useRef({});
+ const dismissRef = useRef(() => {});
+
+ const cancelHide = () => {
+ if (leaveTimerRef.current != null) {
+ clearTimeout(leaveTimerRef.current);
+ leaveTimerRef.current = null;
+ }
+ };
+
+ const hide = () => {
+ cancelHide();
+ hoverCountRef.current = 0;
+ releaseExclusiveHover(ownerRef.current);
+ setVisible(false);
+ };
+
+ dismissRef.current = hide;
+
+ const scheduleHide = () => {
+ cancelHide();
+ leaveTimerRef.current = setTimeout(() => {
+ leaveTimerRef.current = null;
+ if (hoverCountRef.current <= 0) hide();
+ }, INTERACTIVE_CLOSE_DELAY_MS);
+ };
+
+ const show = () => {
+ if (!controlled) claimExclusiveHover(ownerRef.current, () => dismissRef.current());
+ setVisible(true);
+ };
+
+ useEffect(
+ () => () => {
+ cancelHide();
+ releaseExclusiveHover(ownerRef.current);
+ },
+ [],
+ );
placeRef.current = () => {
const trigger = triggerWrapRef.current;
@@ -203,7 +276,11 @@ export function Tooltip({
const child = cloneElement(children as React.ReactElement<AnyProps>, {
onMouseEnter(e: React.MouseEvent<Element>) {
if (followCursor) cursorXRef.current = e.clientX;
- setVisible(true);
+ if (interactive) {
+ cancelHide();
+ hoverCountRef.current += 1;
+ }
+ show();
(p.onMouseEnter as ((e: React.MouseEvent<Element>) => void) | undefined)?.(e);
},
onMouseMove(e: React.MouseEvent<Element>) {
@@ -215,19 +292,24 @@ export function Tooltip({
},
onMouseLeave(e: React.MouseEvent<Element>) {
cursorXRef.current = null;
- setVisible(false);
+ if (interactive) {
+ hoverCountRef.current = Math.max(0, hoverCountRef.current - 1);
+ scheduleHide();
+ } else {
+ hide();
+ }
(p.onMouseLeave as ((e: React.MouseEvent<Element>) => void) | undefined)?.(e);
},
onFocus(e: React.FocusEvent<Element>) {
- setVisible(true);
+ show();
(p.onFocus as ((e: React.FocusEvent<Element>) => void) | undefined)?.(e);
},
onBlur(e: React.FocusEvent<Element>) {
- setVisible(false);
+ hide();
(p.onBlur as ((e: React.FocusEvent<Element>) => void) | undefined)?.(e);
},
onClick(e: React.MouseEvent<Element>) {
- if (dismissOnClick) setVisible(false);
+ if (dismissOnClick) hide();
(p.onClick as ((e: React.MouseEvent<Element>) => void) | undefined)?.(e);
},
});
@@ -245,11 +327,31 @@ export function Tooltip({
visibility: pos == null ? 'hidden' : undefined,
}}
className={cn(
- 'pointer-events-none fixed z-[200] max-w-[calc(100vw-1rem)]',
+ interactive ? 'pointer-events-auto' : 'pointer-events-none',
+ 'fixed z-[200] max-w-[calc(100vw-1rem)]',
'whitespace-nowrap rounded bg-card-bg px-2 py-1 text-xs text-text-primary shadow-md',
className,
)}
+ onMouseEnter={
+ interactive
+ ? () => {
+ cancelHide();
+ hoverCountRef.current += 1;
+ }
+ : undefined
+ }
+ onMouseLeave={
+ interactive
+ ? () => {
+ hoverCountRef.current = Math.max(0, hoverCountRef.current - 1);
+ scheduleHide();
+ }
+ : undefined
+ }
>
+ {interactive ? (
+ <span aria-hidden className="pointer-events-auto absolute" style={interactiveBridgeStyle(side)} />
+ ) : null}
{content}
</span>,
themePortalRoot(triggerWrapRef.current),
@@ -275,6 +377,8 @@ export type LightTooltipProps = {
followCursor?: boolean;
anchor?: TooltipAnchor | null;
open?: boolean;
+ /** When true (default) the tooltip stays open while the cursor is inside the popup. */
+ interactive?: boolean;
};
export function LightTooltip({
@@ -288,6 +392,7 @@ export function LightTooltip({
followCursor,
anchor,
open,
+ interactive,
}: LightTooltipProps) {
return (
<Tooltip
@@ -299,6 +404,7 @@ export function LightTooltip({
followCursor={followCursor}
anchor={anchor}
open={open}
+ interactive={interactive}
>
{children}
</Tooltip>
diff --git a/packages/trueforge-ui/test/atoms/AgentSessionMetricsStrip.test.tsx b/packages/trueforge-ui/test/atoms/AgentSessionMetricsStrip.test.tsx
index f3e0448c6..653e42893 100644
--- a/packages/trueforge-ui/test/atoms/AgentSessionMetricsStrip.test.tsx
+++ b/packages/trueforge-ui/test/atoms/AgentSessionMetricsStrip.test.tsx
@@ -1,7 +1,8 @@
// @vitest-environment jsdom
-import { render, screen } from '@testing-library/react';
+import { fireEvent, render, screen } from '@testing-library/react';
import { describe, expect, it } from 'vitest';
+import { CostBreakdownRows } from '@/atoms/agent-details/AgentSessionMetricCharts.js';
import { AgentSessionMetricsStrip } from '@/atoms/agent-details/AgentSessionMetricsStrip.js';
import type { SessionMetrics } from '@/utils/buildSessionMetrics.js';
@@ -69,4 +70,40 @@ describe('AgentSessionMetricsStrip', () => {
'@min-[48rem]:grid-cols-7',
);
});
+
+ it.each(['wall-time', 'cost', 'tokens', 'context', 'tool-calls'] as const)(
+ 'renders the %s tooltip with interactive pointer-events when hovered',
+ tileId => {
+ render(<AgentSessionMetricsStrip metrics={metrics} />);
+ const tile = document.querySelector(`[data-slot="session-metric-${tileId}"]`);
+ expect(tile).not.toBeNull();
+ fireEvent.mouseEnter(tile!);
+ const tooltip = document.querySelector('[role="tooltip"]');
+ expect(tooltip).not.toBeNull();
+ expect(tooltip!.className).toMatch(/pointer-events-auto/);
+ },
+ );
+});
+
+describe('CostBreakdownRows', () => {
+ it('renders a row for each datum with label and formatted cost', () => {
+ render(
+ <CostBreakdownRows
+ data={[
+ { label: 'T1', value: 2, color: '#f59e0b' },
+ { label: 'T2', value: 0.6, color: '#f59e0b' },
+ ]}
+ />,
+ );
+
+ expect(screen.getByText('T1')).toBeInTheDocument();
+ expect(screen.getByText('T2')).toBeInTheDocument();
+ expect(screen.getByText('$2.0000')).toBeInTheDocument();
+ expect(screen.getByText('$0.6000')).toBeInTheDocument();
+ });
+
+ it('renders nothing for an empty dataset', () => {
+ const { container } = render(<CostBreakdownRows data={[]} />);
+ expect(container.firstChild).toBeEmptyDOMElement();
+ });
});
diff --git a/packages/trueforge-ui/test/atoms/primitives/Tooltip.test.tsx b/packages/trueforge-ui/test/atoms/primitives/Tooltip.test.tsx
index 50a104afa..e1e78903e 100644
--- a/packages/trueforge-ui/test/atoms/primitives/Tooltip.test.tsx
+++ b/packages/trueforge-ui/test/atoms/primitives/Tooltip.test.tsx
@@ -9,7 +9,7 @@ describe('Tooltip', () => {
const onMouseLeave = vi.fn();
render(
- <Tooltip content="Copy message" className="host-tooltip">
+ <Tooltip content="Copy message" className="host-tooltip" interactive={false}>
<button onMouseEnter={onMouseEnter} onMouseLeave={onMouseLeave}>
Copy
</button>
@@ -271,3 +271,111 @@ describe('LightTooltip', () => {
expect(tooltip).toHaveClass('host-light-tooltip');
});
});
+
+describe('Tooltip interactive mode', () => {
+ it('keeps the tooltip open when the cursor moves from the trigger into the popup', () => {
+ vi.useFakeTimers();
+ render(
+ <Tooltip content="Rich content" interactive>
+ <button>Trigger</button>
+ </Tooltip>,
+ );
+
+ const trigger = screen.getByRole('button', { name: 'Trigger' });
+ fireEvent.mouseEnter(trigger);
+ expect(screen.getByRole('tooltip')).toBeInTheDocument();
+
+ fireEvent.mouseLeave(trigger);
+ expect(screen.getByRole('tooltip')).toBeInTheDocument();
+
+ fireEvent.mouseEnter(screen.getByRole('tooltip'));
+ act(() => {
+ vi.advanceTimersByTime(250);
+ });
+ expect(screen.getByRole('tooltip')).toBeInTheDocument();
+ vi.useRealTimers();
+ });
+
+ it('hides only after the close delay when the cursor leaves without entering the popup', () => {
+ vi.useFakeTimers();
+ render(
+ <Tooltip content="Rich content" interactive>
+ <button>Trigger</button>
+ </Tooltip>,
+ );
+
+ const trigger = screen.getByRole('button', { name: 'Trigger' });
+ fireEvent.mouseEnter(trigger);
+ fireEvent.mouseLeave(trigger);
+ expect(screen.getByRole('tooltip')).toBeInTheDocument();
+
+ act(() => {
+ vi.advanceTimersByTime(99);
+ });
+ expect(screen.getByRole('tooltip')).toBeInTheDocument();
+
+ act(() => {
+ vi.advanceTimersByTime(1);
+ });
+ expect(screen.queryByRole('tooltip')).not.toBeInTheDocument();
+ vi.useRealTimers();
+ });
+
+ it('gives the tooltip element pointer-events-auto when interactive', () => {
+ render(
+ <Tooltip content="Rich content" interactive>
+ <button>Trigger</button>
+ </Tooltip>,
+ );
+
+ fireEvent.mouseEnter(screen.getByRole('button', { name: 'Trigger' }));
+ const tooltip = screen.getByRole('tooltip');
+ expect(tooltip.className).toMatch(/pointer-events-auto/);
+ expect(tooltip.className).not.toMatch(/pointer-events-none/);
+ });
+
+ it('is interactive by default', () => {
+ render(
+ <Tooltip content="Simple tip">
+ <button>Trigger</button>
+ </Tooltip>,
+ );
+
+ fireEvent.mouseEnter(screen.getByRole('button', { name: 'Trigger' }));
+ const tooltip = screen.getByRole('tooltip');
+ expect(tooltip.className).toMatch(/pointer-events-auto/);
+ expect(tooltip.className).not.toMatch(/pointer-events-none/);
+ });
+
+ it('uses pointer-events-none when interactive is false', () => {
+ render(
+ <Tooltip content="Simple tip" interactive={false}>
+ <button>Trigger</button>
+ </Tooltip>,
+ );
+
+ fireEvent.mouseEnter(screen.getByRole('button', { name: 'Trigger' }));
+ const tooltip = screen.getByRole('tooltip');
+ expect(tooltip.className).toMatch(/pointer-events-none/);
+ });
+
+ it('closes the previous tooltip immediately when another opens', () => {
+ render(
+ <>
+ <Tooltip content="Duration detail">
+ <button>Duration</button>
+ </Tooltip>
+ <Tooltip content="Tokens detail">
+ <button>Tokens</button>
+ </Tooltip>
+ </>,
+ );
+
+ fireEvent.mouseEnter(screen.getByRole('button', { name: 'Duration' }));
+ expect(screen.getByRole('tooltip')).toHaveTextContent('Duration detail');
+
+ fireEvent.mouseEnter(screen.getByRole('button', { name: 'Tokens' }));
+ expect(screen.getByRole('tooltip')).toHaveTextContent('Tokens detail');
+ expect(screen.queryByText('Duration detail')).not.toBeInTheDocument();
+ });
+});