Skip to content

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

Enhance session timeline visualization (#615)

harshil-2096fe6a14b8e23d
diff --git a/.changeset/clean-session-timeline.md b/.changeset/clean-session-timeline.md
new file mode 100644
index 000000000..151137359
--- /dev/null
+++ b/.changeset/clean-session-timeline.md
@@ -0,0 +1,5 @@
+---
+"@truefoundry/trueforge-ui": patch
+---
+
+Improve session timelines with sub-agent wait states, grouped point-event markers, clean linear ticks, and readable summary durations.
diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionEventTimeline.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionEventTimeline.tsx
index f7a00055d..a8013910a 100644
--- a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionEventTimeline.tsx
+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionEventTimeline.tsx
@@ -2,13 +2,14 @@
import { useCallback, useMemo, useState, type ComponentType } from 'react';
-import { useSlot } from '../../theme/SlotsProvider.js';
-import { SESSION_EVENT_TYPES, type SessionEventType } from '../../utils/sessionEventTimeline.js';
+import { useSlot, useThemeMode } from '../../theme/SlotsProvider.js';
+import { getSessionEventColor, SESSION_EVENT_TYPES, type SessionEventType } from '../../utils/sessionEventTimeline.js';
import { cn } from '../lib/cn.js';
import type { AgentSessionEventTimelineProps } from './types.js';
export function AgentSessionEventTimeline({ turns, segments, onSelectTurn }: AgentSessionEventTimelineProps) {
const AgentSessionEventTimelineChart = useSlot('AgentSessionEventTimelineChart');
+ const isDark = useThemeMode() === 'dark';
const [hiddenTypes, setHiddenTypes] = useState<Set<SessionEventType>>(() => new Set());
const availableEventTypes = useMemo(() => {
@@ -48,7 +49,10 @@ export function AgentSessionEventTimeline({ turns, segments, onSelectTurn }: Age
)}
onClick={() => handleToggleType(eventType.id)}
>
- <span className="size-2 rounded-sm" style={{ backgroundColor: eventType.color }} />
+ <span
+ className="size-2 rounded-sm"
+ style={{ backgroundColor: getSessionEventColor(eventType.id, isDark) }}
+ />
{eventType.label}
</button>
);
diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionEventTimelineChart.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionEventTimelineChart.tsx
index 8ddbff9c1..7a355dc33 100644
--- a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionEventTimelineChart.tsx
+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionEventTimelineChart.tsx
@@ -1,20 +1,24 @@
'use client';
import {
+ BarController,
BarElement,
Chart as ChartJS,
LinearScale,
+ PointElement,
+ ScatterController,
Tooltip,
type ChartData,
+ type ChartDataset,
type ChartOptions,
type Plugin,
} from 'chart.js';
import { useCallback, useEffect, useMemo, useRef, useState, type ComponentType, type CSSProperties } from 'react';
-import { Bar } from 'react-chartjs-2';
+import { Chart } from 'react-chartjs-2';
import { useThemeMode } from '../../theme/SlotsProvider.js';
+import { roundDurationMsToSecond } from '../../utils/sessionDisplayFormat.js';
import {
- formatTimelineDuration,
getSessionEventColor,
getSessionEventHoverColor,
getSessionEventLabel,
@@ -23,12 +27,14 @@ import {
} from '../../utils/sessionEventTimeline.js';
import {
buildTimelineAxisTicks,
+ formatTimelineAxisDuration,
getActiveTimelineMs,
getSubAgentHoverGroups,
getSubAgentLanes,
getTimelineHoverTargetId,
getTimelineLayout,
getTimelineRange,
+ groupCoincidentTimelineMarkers,
groupOverlappingToolCalls,
pickLongestNonOverlappingSegments,
TIMELINE_TYPE,
@@ -40,31 +46,35 @@ import { LightTooltip } from '../primitives/Tooltip.js';
import {
hasSessionEventTooltip,
SessionEventTooltip,
+ SessionMarkerGroupTooltip,
SessionSubAgentGroupTooltip,
SessionToolCallGroupTooltip,
SessionTurnTooltip,
} from './AgentSessionTimelineTooltip.js';
import type { AgentSessionEventTimelineChartProps } from './types.js';
-ChartJS.register(LinearScale, BarElement, Tooltip);
+ChartJS.register(BarController, BarElement, LinearScale, PointElement, ScatterController, Tooltip);
const MARKER_PX = 4;
const TURN_GAP_PX = 12;
const END_PAD_PX = 12;
const BAR_RADIUS_PX = 2;
const ROW_GAP_PX = 8;
+const MARKER_EVENT_GAP_PX = 2;
const OVERHEAD_PX = 30;
type BarPoint = { x: [number, number]; y: number };
+type MarkerPoint = { x: number; y: number };
+type TimelineChartType = 'bar' | 'scatter';
-function rowCenters(heights: number[], gap: number): { centers: number[]; band: number } {
+function rowCenters({ heights, gaps }: { heights: number[]; gaps: number[] }): { centers: number[]; band: number } {
const centers: number[] = [];
let offset = 0;
- for (const height of heights) {
+ heights.forEach((height, index) => {
centers.push(offset + height / 2);
- offset += height + gap;
- }
- return { centers, band: Math.max(0, offset - gap) };
+ offset += height + (gaps[index] ?? 0);
+ });
+ return { centers, band: offset };
}
function eventOrder(type: SessionEventTimelineSegment['type']): number {
@@ -90,8 +100,8 @@ export function AgentSessionEventTimelineChart({
const isDark = mode === 'dark';
const axis = isDark ? '#8c8c92' : '#71717a';
const grid = isDark ? '#27272a' : '#e4e4e7';
- const turnFill = isDark ? '#3f3f46' : '#e4e4e7';
- const turnHover = isDark ? '#52525b' : '#d4d4d8';
+ const turnFill = isDark ? '#3f3f46' : '#E0ECFD';
+ const turnHover = isDark ? '#52525b' : '#E0ECFD';
const wrapperRef = useRef<HTMLDivElement>(null);
const [widthPx, setWidthPx] = useState(0);
const [overheadPx, setOverheadPx] = useState(OVERHEAD_PX);
@@ -137,9 +147,14 @@ export function AgentSessionEventTimelineChart({
};
}, [refreshTooltipAnchor, tooltipTarget]);
- const activeTotalMs = Math.max(1, ...segments.map(segment => segment.endMs));
+ const segmentTotalMs = Math.max(0, ...segments.map(segment => segment.endMs));
+ const activeTotalMs = Math.max(1, roundDurationMsToSecond(segmentTotalMs));
const { turnStartsMs, turnOrdinals, turnRanges } = useMemo(() => getTimelineLayout(segments), [segments]);
- const gapCount = Math.max(0, turnStartsMs.length - 1);
+ const activeTurnStartsMs = useMemo(
+ () => turnStartsMs.filter((startMs, index) => index === 0 || startMs <= activeTotalMs),
+ [activeTotalMs, turnStartsMs],
+ );
+ const gapCount = Math.max(0, activeTurnStartsMs.length - 1);
const scaleWidthPx = Math.max(widthPx / 2, widthPx - TURN_GAP_PX * gapCount - END_PAD_PX);
const msPerPx = activeTotalMs / Math.max(1, scaleWidthPx);
const turnGapMs = TURN_GAP_PX * msPerPx;
@@ -147,10 +162,10 @@ export function AgentSessionEventTimelineChart({
const timelineMaxMs = totalMs + END_PAD_PX * msPerPx;
const timelineGaps = useMemo<TimelineGap[]>(
() =>
- turnStartsMs
+ activeTurnStartsMs
.slice(1)
.map((startMs, index) => ({ startMs: startMs + index * turnGapMs, endMs: startMs + (index + 1) * turnGapMs })),
- [turnGapMs, turnStartsMs],
+ [activeTurnStartsMs, turnGapMs],
);
const visibleSegments = useMemo(
@@ -162,6 +177,8 @@ export function AgentSessionEventTimelineChart({
}),
[hiddenTypes, segments, turnGapMs, turnOrdinals],
);
+ const markerGroups = useMemo(() => groupCoincidentTimelineMarkers(visibleSegments), [visibleSegments]);
+ const durationSegments = useMemo(() => visibleSegments.filter(segment => !segment.isMarker), [visibleSegments]);
const turnBars = useMemo<TimelineTurnBar[]>(
() =>
turnRanges.length < 2
@@ -176,8 +193,8 @@ export function AgentSessionEventTimelineChart({
[msPerPx, turnGapMs, turnRanges],
);
const subAgentSegments = useMemo(
- () => visibleSegments.filter(segment => segment.type === 'sub_agent'),
- [visibleSegments],
+ () => durationSegments.filter(segment => segment.type === 'sub_agent'),
+ [durationSegments],
);
const mainSubAgents = useMemo(() => pickLongestNonOverlappingSegments(subAgentSegments), [subAgentSegments]);
const subAgentGroups = useMemo(
@@ -185,15 +202,15 @@ export function AgentSessionEventTimelineChart({
[mainSubAgents, subAgentSegments],
);
const subAgentLanes = useMemo(
- () => getSubAgentLanes({ subAgentSegments, threadSegments: visibleSegments, minWidthMs: MARKER_PX * msPerPx }),
- [msPerPx, subAgentSegments, visibleSegments],
+ () => getSubAgentLanes({ subAgentSegments, threadSegments: durationSegments, minWidthMs: MARKER_PX * msPerPx }),
+ [durationSegments, msPerPx, subAgentSegments],
);
const mainCandidates = useMemo(() => {
const kept = new Set(mainSubAgents.map(segment => segment.id));
- return visibleSegments.filter(
+ return durationSegments.filter(
segment => segment.threadId === MAIN_THREAD_ID || (segment.type === 'sub_agent' && kept.has(segment.id)),
);
- }, [mainSubAgents, visibleSegments]);
+ }, [durationSegments, mainSubAgents]);
const toolCallGroups = useMemo(
() =>
groupOverlappingToolCalls(mainCandidates.filter(segment => segment.type === 'tool_call')).filter(
@@ -211,15 +228,21 @@ export function AgentSessionEventTimelineChart({
);
const laneCount = subAgentLanes.reduce((count, lane) => Math.max(count, lane.lane + 1), 0);
const hasTurnRow = turnBars.length > 0;
- const eventRow = hasTurnRow ? 1 : 0;
- const { centers, band } = useMemo(
- () => rowCenters([...(hasTurnRow ? [16] : []), 28, ...Array.from({ length: laneCount }, () => 12)], ROW_GAP_PX),
- [hasTurnRow, laneCount],
- );
+ const markerRow = hasTurnRow ? 1 : 0;
+ const eventRow = markerRow + 1;
+ const { centers, band } = useMemo(() => {
+ const heights = [...(hasTurnRow ? [16] : []), 10, 28, ...Array.from({ length: laneCount }, () => 12)];
+ const gaps = heights.map((_, index) => {
+ if (index === heights.length - 1) return 0;
+ return index === markerRow ? MARKER_EVENT_GAP_PX : ROW_GAP_PX;
+ });
+ return rowCenters({ heights, gaps });
+ }, [hasTurnRow, laneCount, markerRow]);
const chartTargets = useMemo<Array<TimelineHoverTarget | null>>(
() => [
...turnBars.map((bar): TimelineHoverTarget => ({ type: TIMELINE_TYPE.turn, bar })),
+ ...markerGroups.map((group): TimelineHoverTarget => ({ type: TIMELINE_TYPE.markerGroup, group })),
...subAgentLanes.flatMap(lane =>
lane.segments.map((segment): TimelineHoverTarget => ({ type: TIMELINE_TYPE.event, segment })),
),
@@ -230,7 +253,7 @@ export function AgentSessionEventTimelineChart({
}),
...toolCallGroups.map((group): TimelineHoverTarget => ({ type: TIMELINE_TYPE.toolCallGroup, group })),
],
- [mainEventSegments, subAgentGroups, subAgentLanes, toolCallGroups, turnBars],
+ [mainEventSegments, markerGroups, subAgentGroups, subAgentLanes, toolCallGroups, turnBars],
);
const barDataset = ({
@@ -267,7 +290,7 @@ export function AgentSessionEventTimelineChart({
...(inflateAmount == null ? {} : { inflateAmount }),
});
- const chartData = useMemo<ChartData<'bar', BarPoint[], string>>(
+ const chartData = useMemo<ChartData<TimelineChartType, Array<BarPoint | MarkerPoint>, string>>(
() => ({
datasets: [
...turnBars.map(bar =>
@@ -280,14 +303,31 @@ export function AgentSessionEventTimelineChart({
thickness: 16,
}),
),
+ ...markerGroups.map(group => {
+ const type = group.segments.length === 1 ? group.segments[0]?.type : 'system';
+ const color = getSessionEventColor(type ?? 'system', isDark);
+ return {
+ type: 'scatter' as const,
+ label: group.segments.map(segment => getSessionEventLabel(segment.type)).join(', '),
+ data: [{ x: group.startMs, y: centers[markerRow] ?? 0 }] satisfies MarkerPoint[],
+ pointStyle: 'rectRot' as const,
+ pointRadius: 5,
+ pointHoverRadius: 6,
+ clip: false,
+ backgroundColor: color,
+ hoverBackgroundColor: getSessionEventHoverColor(type ?? 'system', isDark),
+ borderWidth: 0,
+ order: 0,
+ } satisfies ChartDataset<'scatter', MarkerPoint[]>;
+ }),
...subAgentLanes.flatMap(lane =>
lane.segments.map(segment =>
barDataset({
label: `${getSessionEventLabel(segment.type)}: ${segment.title}`,
range: segment,
y: centers[eventRow + 1 + lane.lane] ?? 0,
- color: getSessionEventColor(segment.type),
- hover: getSessionEventHoverColor(segment.type),
+ color: getSessionEventColor(segment.type, isDark),
+ hover: getSessionEventHoverColor(segment.type, isDark),
thickness: 12,
order: eventOrder(segment.type),
inflateAmount: 0.5,
@@ -299,8 +339,8 @@ export function AgentSessionEventTimelineChart({
label: `${getSessionEventLabel(segment.type)}: ${segment.title}`,
range: segment,
y: centers[eventRow] ?? 0,
- color: getSessionEventColor(segment.type),
- hover: getSessionEventHoverColor(segment.type),
+ color: getSessionEventColor(segment.type, isDark),
+ hover: getSessionEventHoverColor(segment.type, isDark),
thickness: 28,
order: eventOrder(segment.type),
inflateAmount: 0.5,
@@ -311,8 +351,8 @@ export function AgentSessionEventTimelineChart({
label: 'Parallel tool calls',
range: group,
y: centers[eventRow] ?? 0,
- color: getSessionEventColor('tool_call'),
- hover: getSessionEventHoverColor('tool_call'),
+ color: getSessionEventColor('tool_call', isDark),
+ hover: getSessionEventHoverColor('tool_call', isDark),
thickness: 28,
order: eventOrder('tool_call'),
inflateAmount: 0.5,
@@ -320,10 +360,22 @@ export function AgentSessionEventTimelineChart({
),
],
}),
- [centers, eventRow, mainEventSegments, subAgentLanes, toolCallGroups, turnBars, turnFill, turnHover],
+ [
+ centers,
+ eventRow,
+ isDark,
+ mainEventSegments,
+ markerGroups,
+ markerRow,
+ subAgentLanes,
+ toolCallGroups,
+ turnBars,
+ turnFill,
+ turnHover,
+ ],
);
- const turnLabelPlugin = useMemo<Plugin<'bar'>>(
+ const turnLabelPlugin = useMemo<Plugin<TimelineChartType>>(
() => ({
id: 'turnLabels',
afterDatasetsDraw(chart) {
@@ -344,7 +396,7 @@ export function AgentSessionEventTimelineChart({
}),
[axis, turnBars],
);
- const overheadPlugin = useMemo<Plugin<'bar'>>(
+ const overheadPlugin = useMemo<Plugin<TimelineChartType>>(
() => ({
id: 'timelineOverhead',
afterLayout(chart) {
@@ -355,7 +407,7 @@ export function AgentSessionEventTimelineChart({
[],
);
- const chartOptions = useMemo<ChartOptions<'bar'>>(
+ const chartOptions = useMemo<ChartOptions<TimelineChartType>>(
() => ({
indexAxis: 'y',
animation: false,
@@ -398,21 +450,18 @@ export function AgentSessionEventTimelineChart({
grid: { color: grid },
border: { color: grid },
afterBuildTicks: scale => {
- scale.ticks = buildTimelineAxisTicks({
- ticks: scale.ticks,
- totalMs,
- timelineMaxMs,
- });
+ scale.ticks = buildTimelineAxisTicks({ activeTotalMs, turnStartsMs: activeTurnStartsMs, turnGapMs });
},
ticks: {
color: axis,
autoSkip: false,
- includeBounds: true,
+ includeBounds: false,
maxTicksLimit: 9,
- stepSize: timelineMaxMs / 8,
callback: value => {
const timelineMs = Number(value);
- return timelineMs <= totalMs ? formatTimelineDuration(getActiveTimelineMs(timelineMs, timelineGaps)) : '';
+ return timelineMs <= totalMs
+ ? formatTimelineAxisDuration(getActiveTimelineMs(timelineMs, timelineGaps))
+ : '';
},
},
},
@@ -427,7 +476,20 @@ export function AgentSessionEventTimelineChart({
},
},
}),
- [axis, band, chartTargets, grid, onSelectTurn, refreshTooltipAnchor, timelineGaps, timelineMaxMs, totalMs],
+ [
+ activeTotalMs,
+ activeTurnStartsMs,
+ axis,
+ band,
+ chartTargets,
+ grid,
+ onSelectTurn,
+ refreshTooltipAnchor,
+ timelineGaps,
+ timelineMaxMs,
+ totalMs,
+ turnGapMs,
+ ],
);
const tooltipTurn = tooltipTarget?.type === TIMELINE_TYPE.turn ? turns[tooltipTarget.bar.turnIndex] : undefined;
@@ -451,6 +513,8 @@ export function AgentSessionEventTimelineChart({
/>
) : tooltipTarget?.type === TIMELINE_TYPE.toolCallGroup ? (
<SessionToolCallGroupTooltip group={tooltipTarget.group} />
+ ) : tooltipTarget?.type === TIMELINE_TYPE.markerGroup ? (
+ <SessionMarkerGroupTooltip group={tooltipTarget.group} />
) : tooltipTarget?.type === TIMELINE_TYPE.subAgentGroup ? (
<SessionSubAgentGroupTooltip group={tooltipTarget.group} />
) : null;
@@ -467,7 +531,12 @@ export function AgentSessionEventTimelineChart({
anchor={tooltipAnchor}
>
<div className="w-full" style={containerStyle} onMouseLeave={clearTooltip}>
- <Bar data={chartData} options={chartOptions} plugins={[turnLabelPlugin, overheadPlugin]} />
+ <Chart<TimelineChartType, Array<BarPoint | MarkerPoint>, string>
+ type="bar"
+ data={chartData}
+ options={chartOptions}
+ plugins={[turnLabelPlugin, overheadPlugin]}
+ />
</div>
</LightTooltip>
</div>
diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionMetricsStrip.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionMetricsStrip.tsx
index 16e3fd246..73db62a74 100644
--- a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionMetricsStrip.tsx
+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionMetricsStrip.tsx
@@ -3,7 +3,7 @@
import type { ComponentType, ReactNode } from 'react';
import { Icon } from '../../icons/Icon.js';
-import { formatCostUsd, formatTokenCount } from '../../utils/sessionDisplayFormat.js';
+import { formatCostUsd, formatReadableDurationMs, formatTokenCount } from '../../utils/sessionDisplayFormat.js';
import { formatTimelineDuration } from '../../utils/sessionEventTimeline.js';
import { LightTooltip } from '../primitives/Tooltip.js';
import {
@@ -53,7 +53,7 @@ export function AgentSessionMetricsStrip({ metrics }: AgentSessionMetricsStripPr
<SessionMetricTile
id="wall-time"
label="Duration"
- value={formatTimelineDuration(metrics.wallTimeMs)}
+ value={formatReadableDurationMs(metrics.wallTimeMs)}
tooltip={
<SessionMetricTooltipContent title="Where the time went">
<StackedProportionBar data={metrics.timeBreakdown} formatValue={formatTimelineDuration} />
diff --git a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionTimelineTooltip.tsx b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionTimelineTooltip.tsx
index de76b086c..ee30e6580 100644
--- a/packages/trueforge-ui/src/atoms/agent-details/AgentSessionTimelineTooltip.tsx
+++ b/packages/trueforge-ui/src/atoms/agent-details/AgentSessionTimelineTooltip.tsx
@@ -1,5 +1,6 @@
'use client';
+import { useThemeMode } from '../../theme/SlotsProvider.js';
import { formatCostUsd, formatDurationMs, formatTokenCount } from '../../utils/sessionDisplayFormat.js';
import {
formatTimelineDuration,
@@ -8,7 +9,11 @@ import {
SESSION_EVENT_TOOLTIP_HIDE_DURATION,
type SessionEventTimelineSegment,
} from '../../utils/sessionEventTimeline.js';
-import type { TimelineSubAgentGroup, TimelineToolCallGroup } from '../../utils/sessionEventTimelineChart.js';
+import type {
+ TimelineMarkerGroup,
+ TimelineSubAgentGroup,
+ TimelineToolCallGroup,
+} from '../../utils/sessionEventTimelineChart.js';
import type { SessionTurnView } from '../../utils/sessionTurnViews.js';
export function hasSessionEventTooltip(segment: SessionEventTimelineSegment): boolean {
@@ -62,6 +67,7 @@ export function SessionTurnTooltip({
durationMs: number;
segments: SessionEventTimelineSegment[];
}) {
+ const isDark = useThemeMode() === 'dark';
return (
<div className="max-h-72 w-72 max-w-full overflow-auto text-xs text-text-primary">
<div className="flex items-center justify-between gap-3">
@@ -80,7 +86,7 @@ export function SessionTurnTooltip({
<div key={segment.id} className="flex min-w-0 items-center gap-1.5">
<span
className="size-1.5 shrink-0 rounded-full"
- style={{ backgroundColor: getSessionEventColor(segment.type) }}
+ style={{ backgroundColor: getSessionEventColor(segment.type, isDark) }}
/>
<span className="min-w-0 flex-1 truncate">{label}</span>
{segment.isMarker ? null : (
@@ -119,6 +125,34 @@ export function SessionToolCallGroupTooltip({ group }: { group: TimelineToolCall
);
}
+export function SessionMarkerGroupTooltip({ group }: { group: TimelineMarkerGroup }) {
+ const isDark = useThemeMode() === 'dark';
+ const singleSegment = group.segments.length === 1 ? group.segments[0] : undefined;
+ if (singleSegment != null) return <SessionEventTooltip segment={singleSegment} />;
+
+ return (
+ <div className="max-h-72 w-80 max-w-full overflow-auto text-xs">
+ <span className="font-medium text-text-secondary">Events</span>
+ <div className="mt-1.5 border-t border-border pt-1.5">
+ {group.segments.map(segment => (
+ <div key={segment.id} className="flex min-w-0 items-start gap-1.5 py-0.5">
+ <span
+ className="mt-1 size-1.5 shrink-0 rounded-full"
+ style={{ backgroundColor: getSessionEventColor(segment.type, isDark) }}
+ />
+ <div className="min-w-0">
+ <div className="font-medium text-text-secondary">{getSessionEventTooltipHeading(segment.type)}</div>
+ <div className="wrap-break-word font-medium text-text-primary">
+ {segment.description.trim() || segment.title}
+ </div>
+ </div>
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
+
export function SessionSubAgentGroupTooltip({ group }: { group: TimelineSubAgentGroup }) {
return (
<div className="max-h-72 w-80 max-w-full overflow-auto text-xs">
@@ -130,11 +164,15 @@ export function SessionSubAgentGroupTooltip({ group }: { group: TimelineSubAgent
{group.segments.map((segment, index) => (
<div key={segment.id} className="flex items-center justify-between gap-2 py-0.5">
<span className="min-w-0 truncate font-medium text-text-primary">
- {`Sub-agent ${index + 1}: ${segment.description || segment.title}`}
- </span>
- <span className="shrink-0 tabular-nums text-text-secondary">
- {formatTimelineDuration(segment.endMs - segment.startMs)}
+ {group.segments.length === 1
+ ? segment.description || segment.title
+ : `Sub-agent ${index + 1}: ${segment.description || segment.title}`}
</span>
+ {group.segments.length === 1 ? null : (
+ <span className="shrink-0 tabular-nums text-text-secondary">
+ {formatTimelineDuration(segment.endMs - segment.startMs)}
+ </span>
+ )}
</div>
))}
</div>
diff --git a/packages/trueforge-ui/src/utils/buildSessionTimelineSegments.ts b/packages/trueforge-ui/src/utils/buildSessionTimelineSegments.ts
index 5dfc04b02..3aed07590 100644
--- a/packages/trueforge-ui/src/utils/buildSessionTimelineSegments.ts
+++ b/packages/trueforge-ui/src/utils/buildSessionTimelineSegments.ts
@@ -46,6 +46,7 @@ export function buildSessionTimelineSegments(turns: SessionTurnView[]): SessionE
const approvalRequiredIdsByTurnId = new Map<string, Set<string>>();
const threadDoneEvents = new Map<string, TimelineEvent>();
const subAgentToolCallIds = new Set<string>();
+ const toolCallRequestsByTurnId = new Map<string, Map<string, { startedAtMs: number; threadId: string }>>();
let latestMs = originMs;
for (const turn of turns) {
@@ -72,6 +73,16 @@ export function buildSessionTimelineSegments(turns: SessionTurnView[]): SessionE
if (toolCallId != null) subAgentToolCallIds.add(toolCallId);
} else if (event.type === 'thread.done') {
threadDoneEvents.set(eventThreadId(event), event);
+ } else if (event.type === 'model.message') {
+ const startedAtMs = parseTimestamp(eventCreatedAt(event));
+ if (startedAtMs == null) continue;
+ const requests = toolCallRequestsByTurnId.get(turn.turnId) ?? new Map();
+ for (const toolCall of toolCallsOf(event)) {
+ if (typeof toolCall.id === 'string') {
+ requests.set(toolCall.id, { startedAtMs, threadId: eventThreadId(event) });
+ }
+ }
+ toolCallRequestsByTurnId.set(turn.turnId, requests);
}
}
}
@@ -121,6 +132,7 @@ export function buildSessionTimelineSegments(turns: SessionTurnView[]): SessionE
toolResponsesByTurnId,
approvalRequiredIdsByTurnId,
subAgentToolCallIds,
+ toolCallRequestsByTurnId,
threadDoneEvents,
segments,
});
@@ -157,6 +169,7 @@ function appendEventSegments({
toolResponsesByTurnId,
approvalRequiredIdsByTurnId,
subAgentToolCallIds,
+ toolCallRequestsByTurnId,
threadDoneEvents,
segments,
}: {
@@ -171,6 +184,7 @@ function appendEventSegments({
toolResponsesByTurnId: Map<string, Map<string, TimelineEvent>>;
approvalRequiredIdsByTurnId: Map<string, Set<string>>;
subAgentToolCallIds: Set<string>;
+ toolCallRequestsByTurnId: Map<string, Map<string, { startedAtMs: number; threadId: string }>>;
threadDoneEvents: Map<string, TimelineEvent>;
segments: SessionEventTimelineSegment[];
}): void {
@@ -224,6 +238,20 @@ function appendEventSegments({
case 'thread.created': {
// The parent call is represented by this track, while child events are
// assigned to the same thread id and rendered on the track's lane.
+ const parentCallId = parentToolCallId(event);
+ const request = parentCallId == null ? undefined : toolCallRequestsByTurnId.get(turn.turnId)?.get(parentCallId);
+ if (request != null && request.startedAtMs < eventMs) {
+ segments.push({
+ id: `${eventId(event)}-waiting`,
+ type: 'system',
+ title: 'system.waiting_for_sub_agent',
+ description: 'System waiting for sub-agent to start executing',
+ startMs: request.startedAtMs - originMs,
+ endMs: eventMs - originMs,
+ turnIndex,
+ threadId: request.threadId,
+ });
+ }
const doneEvent = threadDoneEvents.get(threadId);
const doneMs = doneEvent == null ? null : parseTimestamp(eventCreatedAt(doneEvent));
segments.push({
diff --git a/packages/trueforge-ui/src/utils/sessionDisplayFormat.ts b/packages/trueforge-ui/src/utils/sessionDisplayFormat.ts
index fbd60f728..a00b5b396 100644
--- a/packages/trueforge-ui/src/utils/sessionDisplayFormat.ts
+++ b/packages/trueforge-ui/src/utils/sessionDisplayFormat.ts
@@ -25,6 +25,23 @@ export function formatDurationMs(durationMs: number): string {
return `${(durationMs / 3_600_000).toFixed(2)}h`;
}
+export function roundDurationMsToSecond(durationMs: number): number {
+ return Math.max(0, Math.round(durationMs / 1_000) * 1_000);
+}
+
+/** Whole-unit duration for prominent summary UI (e.g. 3m 8s). */
+export function formatReadableDurationMs(durationMs: number): string {
+ const totalSeconds = roundDurationMsToSecond(durationMs) / 1_000;
+ const hours = Math.floor(totalSeconds / 3_600);
+ const minutes = Math.floor((totalSeconds % 3_600) / 60);
+ const seconds = totalSeconds % 60;
+ return [
+ ...(hours > 0 ? [`${hours}h`] : []),
+ ...(minutes > 0 ? [`${minutes}m`] : []),
+ ...(seconds > 0 || totalSeconds === 0 ? [`${seconds}s`] : []),
+ ].join(' ');
+}
+
export function formatSessionListMetrics(metrics: {
totalTurns: number;
totalCostInUsd?: number;
@@ -33,6 +50,6 @@ export function formatSessionListMetrics(metrics: {
return [
`${metrics.totalTurns} turns`,
...(metrics.totalCostInUsd == null ? [] : [formatCostUsd(metrics.totalCostInUsd)]),
- formatDurationMs(metrics.totalDurationMs),
+ formatReadableDurationMs(metrics.totalDurationMs),
].join(' | ');
}
diff --git a/packages/trueforge-ui/src/utils/sessionEventTimeline.ts b/packages/trueforge-ui/src/utils/sessionEventTimeline.ts
index 2a642f793..169e06505 100644
--- a/packages/trueforge-ui/src/utils/sessionEventTimeline.ts
+++ b/packages/trueforge-ui/src/utils/sessionEventTimeline.ts
@@ -16,6 +16,7 @@ export type SessionEventTypeDefinition = {
id: SessionEventType;
label: string;
color: string;
+ darkColor?: string;
};
/**
@@ -42,10 +43,10 @@ export type SessionEventTimelineSegment = {
export const SESSION_EVENT_TYPES: SessionEventTypeDefinition[] = [
{ id: 'system', label: 'System', color: '#94a3b8' },
{ id: 'user', label: 'User', color: '#34d399' },
- { id: 'model', label: 'Model', color: '#3b82f6' },
+ { id: 'model', label: 'Model', color: '#3b82f6', darkColor: '#6366f1' },
{ id: 'tool_call', label: 'Tool call', color: '#f59e0b' },
{ id: 'approval', label: 'Approval / HITL', color: '#f472b6' },
- { id: 'sub_agent', label: 'Sub-agent', color: '#c084fc' },
+ { id: 'sub_agent', label: 'Sub-agent', color: '#e2e8f0', darkColor: '#3f3f46' },
{ id: 'waiting_on_human', label: 'Waiting on human', color: '#22d3ee' },
{ id: 'error', label: 'Error', color: '#f87171' },
];
@@ -68,13 +69,15 @@ export function formatTimelineDuration(durationMs: number): string {
}
/** Resolve a segment's color from the same registry used to build the legend. */
-export function getSessionEventColor(type: SessionEventType): string {
- return SESSION_EVENT_TYPES.find(eventType => eventType.id === type)?.color ?? '#94a3b8';
+export function getSessionEventColor(type: SessionEventType, isDarkMode = false): string {
+ const eventType = SESSION_EVENT_TYPES.find(eventType => eventType.id === type);
+ return (isDarkMode ? eventType?.darkColor : undefined) ?? eventType?.color ?? '#94a3b8';
}
/** Darken the base color by 10% so hover remains recognizable in either theme. */
-export function getSessionEventHoverColor(type: SessionEventType): string {
- const hex = getSessionEventColor(type).replace('#', '');
+export function getSessionEventHoverColor(type: SessionEventType, isDarkMode = false): string {
+ const color = getSessionEventColor(type, isDarkMode);
+ const hex = color.replace('#', '');
const normalized =
hex.length === 3
? hex
@@ -82,7 +85,7 @@ export function getSessionEventHoverColor(type: SessionEventType): string {
.map(char => `${char}${char}`)
.join('')
: hex;
- if (normalized.length !== 6) return getSessionEventColor(type);
+ if (normalized.length !== 6) return color;
const value = Number.parseInt(normalized, 16);
const channel = (shift: number) =>
Math.max(0, Math.round(((value >> shift) & 255) * 0.9))
diff --git a/packages/trueforge-ui/src/utils/sessionEventTimelineChart.ts b/packages/trueforge-ui/src/utils/sessionEventTimelineChart.ts
index 235c9ef5b..297eaeec9 100644
--- a/packages/trueforge-ui/src/utils/sessionEventTimelineChart.ts
+++ b/packages/trueforge-ui/src/utils/sessionEventTimelineChart.ts
@@ -55,9 +55,15 @@ export type TimelineSubAgentGroup = TimelineGap & {
segments: SessionEventTimelineSegment[];
};
+export type TimelineMarkerGroup = TimelineGap & {
+ id: string;
+ segments: SessionEventTimelineSegment[];
+};
+
export const TIMELINE_TYPE = {
turn: 'turn',
event: 'event',
+ markerGroup: 'markerGroup',
toolCallGroup: 'toolCallGroup',
subAgentGroup: 'subAgentGroup',
} as const;
@@ -65,6 +71,7 @@ export const TIMELINE_TYPE = {
export type TimelineHoverTarget =
| { type: typeof TIMELINE_TYPE.turn; bar: TimelineTurnBar }
| { type: typeof TIMELINE_TYPE.event; segment: SessionEventTimelineSegment }
+ | { type: typeof TIMELINE_TYPE.markerGroup; group: TimelineMarkerGroup }
| { type: typeof TIMELINE_TYPE.toolCallGroup; group: TimelineToolCallGroup }
| { type: typeof TIMELINE_TYPE.subAgentGroup; group: TimelineSubAgentGroup };
@@ -81,6 +88,70 @@ export function getTimelineRange({ startMs, endMs }: TimelineGap): [number, numb
return [startMs, endMs];
}
+/** Collapse point events at an identical chart timestamp into one marker and tooltip. */
+export function groupCoincidentTimelineMarkers(segments: SessionEventTimelineSegment[]): TimelineMarkerGroup[] {
+ const groupsByTimestamp = new Map<number, SessionEventTimelineSegment[]>();
+ for (const segment of segments) {
+ if (!segment.isMarker) continue;
+ const group = groupsByTimestamp.get(segment.startMs);
+ if (group) group.push(segment);
+ else groupsByTimestamp.set(segment.startMs, [segment]);
+ }
+ return Array.from(groupsByTimestamp, ([startMs, group]) => ({
+ id: `marker-group-${group.map(segment => segment.id).join('-')}`,
+ startMs,
+ endMs: startMs,
+ segments: group,
+ })).sort((left, right) => left.startMs - right.startMs);
+}
+
+function timelineAxisUnit(totalMs: number): { divisorMs: number; suffix: string } {
+ if (totalMs < 1_000) return { divisorMs: 1, suffix: 'ms' };
+ if (totalMs < 60_000) return { divisorMs: 1_000, suffix: 's' };
+ if (totalMs < 3_600_000) return { divisorMs: 60_000, suffix: 'm' };
+ return { divisorMs: 3_600_000, suffix: 'h' };
+}
+
+/** Format an axis label as milliseconds, seconds, minutes, or hours by elapsed time. */
+export function formatTimelineAxisDuration(durationMs: number): string {
+ const unit = timelineAxisUnit(durationMs);
+ return `${Number((durationMs / unit.divisorMs).toFixed(2))}${unit.suffix}`;
+}
+
+function getCleanAxisStepMs(totalMs: number): number {
+ const { divisorMs } = timelineAxisUnit(totalMs);
+ const target = totalMs / divisorMs / 8;
+ if (divisorMs >= 60_000 && target < 1) return Math.max(0.25, Math.ceil(target * 4) / 4) * divisorMs;
+ const integerTarget = Math.max(1, target);
+ const magnitude = 10 ** Math.floor(Math.log10(integerTarget));
+ const normalized = integerTarget / magnitude;
+ const multiplier = normalized <= 1 ? 1 : normalized <= 2 ? 2 : normalized <= 5 ? 5 : 10;
+ return multiplier * magnitude * divisorMs;
+}
+
+/** Generate clean active-time ticks, translated around fixed visual turn separators. */
+export function buildTimelineAxisTicks({
+ activeTotalMs,
+ turnStartsMs,
+ turnGapMs,
+}: {
+ activeTotalMs: number;
+ turnStartsMs: number[];
+ turnGapMs: number;
+}): Array<{ value: number }> {
+ const stepMs = getCleanAxisStepMs(activeTotalMs);
+ const activeTicks: number[] = [];
+ for (let activeMs = 0; activeMs < activeTotalMs; activeMs += stepMs) activeTicks.push(activeMs);
+ const lastRegularTick = activeTicks.at(-1);
+ if (lastRegularTick != null && lastRegularTick > 0 && activeTotalMs - lastRegularTick < stepMs / 4) {
+ activeTicks.pop();
+ }
+ if (activeTicks.at(-1) !== activeTotalMs) activeTicks.push(activeTotalMs);
+ return activeTicks.map(activeMs => ({
+ value: activeMs + turnStartsMs.slice(1).filter(turnStartMs => turnStartMs <= activeMs).length * turnGapMs,
+ }));
+}
+
/**
* Derive one background range per turn from all of that turn's segments.
*
@@ -274,10 +345,7 @@ export function compressInterTurnGaps(segments: SessionEventTimelineSegment[]):
});
}
-/**
- * Translate a chart-axis coordinate back to active elapsed time by subtracting
- * the fixed visual gaps inserted between turn bars.
- */
+/** Translate a chart coordinate back to active elapsed time across visual turn separators. */
export function getActiveTimelineMs(valueMs: number, gaps: TimelineGap[]): number {
let activeMs = valueMs;
for (const gap of gaps) {
@@ -285,19 +353,3 @@ export function getActiveTimelineMs(valueMs: number, gaps: TimelineGap[]): numbe
}
return Math.max(0, activeMs);
}
-
-/**
- * Keep generated ticks before the active endpoint, then force endpoint and
- * padding ticks so the final duration label and trailing whitespace are stable.
- */
-export function buildTimelineAxisTicks<T extends { value: number }>({
- ticks,
- totalMs,
- timelineMaxMs,
-}: {
- ticks: readonly T[];
- totalMs: number;
- timelineMaxMs: number;
-}): Array<T | { value: number }> {
- return [...ticks.filter(tick => tick.value < totalMs), { value: totalMs }, { value: timelineMaxMs }];
-}
diff --git a/packages/trueforge-ui/test/atoms/AgentSessionEventTimelineChart.test.tsx b/packages/trueforge-ui/test/atoms/AgentSessionEventTimelineChart.test.tsx
index 9f4e2b235..fc2e4680b 100644
--- a/packages/trueforge-ui/test/atoms/AgentSessionEventTimelineChart.test.tsx
+++ b/packages/trueforge-ui/test/atoms/AgentSessionEventTimelineChart.test.tsx
@@ -3,14 +3,19 @@ import { act, fireEvent, render, screen, waitFor } from '@testing-library/react'
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { AgentSessionEventTimelineChart } from '@/atoms/agent-details/AgentSessionEventTimelineChart.js';
-import { SessionSubAgentGroupTooltip } from '@/atoms/agent-details/AgentSessionTimelineTooltip.js';
+import {
+ SessionMarkerGroupTooltip,
+ SessionSubAgentGroupTooltip,
+} from '@/atoms/agent-details/AgentSessionTimelineTooltip.js';
import type { SessionEventTimelineSegment } from '@/utils/sessionEventTimeline.js';
import type { SessionTurnView } from '@/utils/sessionTurnViews.js';
let capturedOptions: unknown;
+let capturedData: unknown;
vi.mock('react-chartjs-2', () => ({
- Bar: ({ options }: { options: unknown }) => {
+ Chart: ({ data, options }: { data: unknown; options: unknown }) => {
+ capturedData = data;
capturedOptions = options;
return <canvas role="img" aria-label="Timeline chart" />;
},
@@ -60,9 +65,63 @@ const segments: SessionEventTimelineSegment[] = [
describe('AgentSessionEventTimelineChart', () => {
beforeEach(() => {
+ capturedData = undefined;
capturedOptions = undefined;
});
+ it('uses one unclipped diamond close to the event row and no fractional tick step', () => {
+ const coincidentSegments: SessionEventTimelineSegment[] = [
+ segments[0] ??
+ (() => {
+ throw new Error('Expected user segment');
+ })(),
+ {
+ id: 'turn-1-system',
+ type: 'system',
+ title: 'mcp.initialize',
+ description: 'MCP initialized',
+ startMs: 0,
+ endMs: 0,
+ turnIndex: 0,
+ threadId: 'main',
+ isMarker: true,
+ },
+ segments[1] ??
+ (() => {
+ throw new Error('Expected model segment');
+ })(),
+ ];
+
+ render(<AgentSessionEventTimelineChart turns={turns} segments={coincidentSegments} hiddenTypes={new Set()} />);
+
+ const datasets = Reflect.get(capturedData ?? {}, 'datasets');
+ expect(Array.isArray(datasets)).toBe(true);
+ if (!Array.isArray(datasets)) throw new Error('Expected chart datasets');
+ const markerDatasets = datasets.filter(dataset => {
+ if (typeof dataset !== 'object' || dataset == null) return false;
+ return Reflect.get(dataset, 'type') === 'scatter';
+ });
+ expect(markerDatasets).toHaveLength(1);
+ expect(Reflect.get(markerDatasets[0] ?? {}, 'pointStyle')).toBe('rectRot');
+ expect(Reflect.get(markerDatasets[0] ?? {}, 'clip')).toBe(false);
+ const markerData = Reflect.get(markerDatasets[0] ?? {}, 'data');
+ const barDataset = datasets.find(dataset => {
+ if (typeof dataset !== 'object' || dataset == null) return false;
+ return Reflect.get(dataset, 'type') !== 'scatter';
+ });
+ const barData = typeof barDataset === 'object' && barDataset != null ? Reflect.get(barDataset, 'data') : undefined;
+ const markerPoint = Array.isArray(markerData) ? markerData[0] : undefined;
+ const barPoint = Array.isArray(barData) ? barData[0] : undefined;
+ const markerY = typeof markerPoint === 'object' && markerPoint != null ? Reflect.get(markerPoint, 'y') : undefined;
+ const barY = typeof barPoint === 'object' && barPoint != null ? Reflect.get(barPoint, 'y') : undefined;
+ expect(typeof markerY === 'number' && typeof barY === 'number' ? barY - markerY : undefined).toBe(21);
+
+ const scales = Reflect.get(capturedOptions ?? {}, 'scales');
+ const xScale = typeof scales === 'object' && scales != null ? Reflect.get(scales, 'x') : undefined;
+ const ticks = typeof xScale === 'object' && xScale != null ? Reflect.get(xScale, 'ticks') : undefined;
+ expect(typeof ticks === 'object' && ticks != null ? Reflect.has(ticks, 'stepSize') : false).toBe(false);
+ });
+
it('keeps an open tooltip anchored to live chart bounds while scrolling', async () => {
const { container } = render(
<AgentSessionEventTimelineChart turns={turns} segments={segments} hiddenTypes={new Set()} />,
@@ -131,4 +190,101 @@ describe('AgentSessionEventTimelineChart', () => {
expect(screen.getByText('Sub-agent 2: Writer')).toBeInTheDocument();
expect(screen.getAllByText('5s')).not.toHaveLength(0);
});
+
+ it('shows only the name for a single sub-agent bar', () => {
+ render(
+ <SessionSubAgentGroupTooltip
+ group={{
+ id: 'sub-agent-group',
+ barId: 'researcher',
+ startMs: 1_000,
+ endMs: 6_000,
+ segments: [
+ {
+ id: 'researcher',
+ type: 'sub_agent',
+ title: 'thread.created',
+ description: 'Researcher',
+ startMs: 1_000,
+ endMs: 6_000,
+ turnIndex: 0,
+ threadId: 'researcher-thread',
+ },
+ ],
+ }}
+ />,
+ );
+
+ expect(screen.getByText('Researcher')).toBeInTheDocument();
+ expect(screen.queryByText('Sub-agent 1: Researcher')).not.toBeInTheDocument();
+ });
+
+ it('shows the event directly for a single diamond', () => {
+ render(
+ <SessionMarkerGroupTooltip
+ group={{
+ id: 'marker-user',
+ startMs: 0,
+ endMs: 0,
+ segments: [
+ {
+ id: 'user',
+ type: 'user',
+ title: 'user.message',
+ description: 'Hello',
+ startMs: 0,
+ endMs: 0,
+ turnIndex: 0,
+ threadId: 'main',
+ isMarker: true,
+ },
+ ],
+ }}
+ />,
+ );
+
+ expect(screen.getByText('User Message')).toBeInTheDocument();
+ expect(screen.getByText('Hello')).toBeInTheDocument();
+ expect(screen.queryByText('Events')).not.toBeInTheDocument();
+ });
+
+ it('lists every event represented by a shared diamond', () => {
+ render(
+ <SessionMarkerGroupTooltip
+ group={{
+ id: 'marker-1000',
+ startMs: 1_000,
+ endMs: 1_000,
+ segments: [
+ {
+ id: 'approval',
+ type: 'approval',
+ title: 'tool.approval_required',
+ description: 'Approval required',
+ startMs: 1_000,
+ endMs: 1_000,
+ turnIndex: 0,
+ threadId: 'main',
+ isMarker: true,
+ },
+ {
+ id: 'system',
+ type: 'system',
+ title: 'mcp.initialize',
+ description: 'MCP initialized',
+ startMs: 1_000,
+ endMs: 1_000,
+ turnIndex: 0,
+ threadId: 'main',
+ isMarker: true,
+ },
+ ],
+ }}
+ />,
+ );
+
+ expect(screen.getByText('Events')).toBeInTheDocument();
+ expect(screen.getByText('Approval required')).toBeInTheDocument();
+ expect(screen.getByText('MCP initialized')).toBeInTheDocument();
+ });
});
diff --git a/packages/trueforge-ui/test/atoms/AgentSessionMetricsStrip.test.tsx b/packages/trueforge-ui/test/atoms/AgentSessionMetricsStrip.test.tsx
index 844f7ac11..9d67fa5d1 100644
--- a/packages/trueforge-ui/test/atoms/AgentSessionMetricsStrip.test.tsx
+++ b/packages/trueforge-ui/test/atoms/AgentSessionMetricsStrip.test.tsx
@@ -7,7 +7,7 @@ import type { SessionMetrics } from '@/utils/buildSessionMetrics.js';
const metrics: SessionMetrics = {
totalTurns: 7,
- wallTimeMs: 120_000,
+ wallTimeMs: 188_000,
totalCostUsd: 2.6229,
totalTokens: 280_000,
contextTokens: 280_000,
@@ -42,6 +42,7 @@ describe('AgentSessionMetricsStrip', () => {
expect(screen.getByText('Turns')).toBeInTheDocument();
expect(screen.getByText('7')).toBeInTheDocument();
expect(screen.getByText('Duration')).toBeInTheDocument();
+ expect(screen.getByText('3m 8s')).toBeInTheDocument();
expect(screen.getByText('Cost')).toBeInTheDocument();
expect(screen.getByText('$2.6229')).toBeInTheDocument();
expect(screen.getByText('Tokens')).toBeInTheDocument();
diff --git a/packages/trueforge-ui/test/utils/sessionAgentDetails.test.ts b/packages/trueforge-ui/test/utils/sessionAgentDetails.test.ts
index 14fc7b616..691275f9d 100644
--- a/packages/trueforge-ui/test/utils/sessionAgentDetails.test.ts
+++ b/packages/trueforge-ui/test/utils/sessionAgentDetails.test.ts
@@ -75,12 +75,12 @@ describe('sessionDisplayFormat', () => {
it('formats list metrics like the sessions mock', () => {
assert.equal(
formatSessionListMetrics({ totalTurns: 5, totalCostInUsd: 0.1615, totalDurationMs: 41_380 }),
- '5 turns | $0.1615 | 41.38s',
+ '5 turns | $0.1615 | 41s',
);
assert.equal(formatTokenCount(122_000), '122K');
assert.equal(formatCostUsd(1.4872), '$1.4872');
assert.equal(formatDurationMs(76_800), '1.28m');
- assert.equal(formatSessionListMetrics({ totalTurns: 5, totalDurationMs: 41_380 }), '5 turns | 41.38s');
+ assert.equal(formatSessionListMetrics({ totalTurns: 5, totalDurationMs: 42_691 }), '5 turns | 43s');
});
});
diff --git a/packages/trueforge-ui/test/utils/sessionEventTimeline.test.ts b/packages/trueforge-ui/test/utils/sessionEventTimeline.test.ts
index ae8d52551..005d9b6ed 100644
--- a/packages/trueforge-ui/test/utils/sessionEventTimeline.test.ts
+++ b/packages/trueforge-ui/test/utils/sessionEventTimeline.test.ts
@@ -4,18 +4,29 @@ import { describe, it } from 'vitest';
import type { SessionEventItem } from '@/server/types.js';
import { buildSessionMetrics } from '@/utils/buildSessionMetrics.js';
import { buildSessionTimelineSegments } from '@/utils/buildSessionTimelineSegments.js';
-import type { SessionEventTimelineSegment } from '@/utils/sessionEventTimeline.js';
+import { getSessionEventColor, type SessionEventTimelineSegment } from '@/utils/sessionEventTimeline.js';
import {
buildTimelineAxisTicks,
compressInterTurnGaps,
+ formatTimelineAxisDuration,
getActiveTimelineMs,
getSubAgentHoverGroups,
getSubAgentLanes,
+ groupCoincidentTimelineMarkers,
groupOverlappingToolCalls,
pickLongestNonOverlappingSegments,
} from '@/utils/sessionEventTimelineChart.js';
import { buildSessionTurnViews } from '@/utils/sessionTurnViews.js';
+describe('session event colors', () => {
+ it('uses dark overrides when present and otherwise falls back to the base color', () => {
+ assert.equal(getSessionEventColor('model'), '#3b82f6');
+ assert.equal(getSessionEventColor('model', true), '#6366f1');
+ assert.equal(getSessionEventColor('sub_agent', true), '#3f3f46');
+ assert.equal(getSessionEventColor('tool_call', true), '#f59e0b');
+ });
+});
+
function created({
turnId,
createdAt,
@@ -156,6 +167,19 @@ describe('buildSessionTimelineSegments', () => {
segments.some(segment => segment.id.endsWith('call-sub')),
false,
);
+ assert.deepEqual(
+ segments
+ .filter(segment => segment.type === 'system' && segment.title === 'system.waiting_for_sub_agent')
+ .map(({ description, startMs, endMs, threadId }) => ({ description, startMs, endMs, threadId })),
+ [
+ {
+ description: 'System waiting for sub-agent to start executing',
+ startMs: 1_000,
+ endMs: 1_100,
+ threadId: 'main',
+ },
+ ],
+ );
const toolCalls = segments.filter(segment => segment.type === 'tool_call');
assert.equal(toolCalls.length, 2);
const groups = groupOverlappingToolCalls(toolCalls).filter(group => group.segments.length > 1);
@@ -176,6 +200,21 @@ describe('sessionEventTimelineChart helpers', () => {
turnIndex,
threadId: 'main',
}));
+ const marker = (
+ id: string,
+ type: SessionEventTimelineSegment['type'],
+ startMs: number,
+ ): SessionEventTimelineSegment => ({
+ id,
+ type,
+ title: id,
+ description: id,
+ startMs,
+ endMs: startMs,
+ turnIndex: 0,
+ threadId: 'main',
+ isMarker: true,
+ });
it('picks the longest non-overlapping sub-agent bars', () => {
const selected = pickLongestNonOverlappingSegments(
@@ -267,18 +306,54 @@ describe('sessionEventTimelineChart helpers', () => {
assert.equal(lanes.find(lane => lane.threadId === 'c')?.lane, 0);
});
- it('subtracts visual turn-gap bands from axis labels', () => {
- assert.equal(getActiveTimelineMs(150, [{ startMs: 100, endMs: 120 }]), 130);
+ it('groups coincident point events into one marker', () => {
+ assert.deepEqual(
+ groupCoincidentTimelineMarkers([
+ marker('user', 'user', 10),
+ marker('system', 'system', 10),
+ marker('error', 'error', 20),
+ ...bars([[10, 30, 0]]),
+ ]).map(group => ({
+ startMs: group.startMs,
+ ids: group.segments.map(segment => segment.id),
+ })),
+ [
+ { startMs: 10, ids: ['user', 'system'] },
+ { startMs: 20, ids: ['error'] },
+ ],
+ );
+ });
+
+ it('maps clean active-time ticks around fixed turn separators', () => {
+ const gaps = [{ startMs: 42_000, endMs: 43_000 }];
+ const ticks = buildTimelineAxisTicks({
+ activeTotalMs: 96_000,
+ turnStartsMs: [0, 42_000],
+ turnGapMs: 1_000,
+ });
+ assert.deepEqual(
+ ticks.map(tick => getActiveTimelineMs(tick.value, gaps)),
+ [0, 15_000, 30_000, 45_000, 60_000, 75_000, 90_000, 96_000],
+ );
+ assert.deepEqual(
+ ticks.map(tick => formatTimelineAxisDuration(getActiveTimelineMs(tick.value, gaps))),
+ ['0ms', '15s', '30s', '45s', '1m', '1.25m', '1.5m', '1.6m'],
+ );
+ assert.equal(formatTimelineAxisDuration(813_292), '13.55m');
+ });
+
+ it('changes axis units at one second, one minute, and one hour', () => {
+ assert.deepEqual([999, 1_000, 60_000, 3_600_000].map(formatTimelineAxisDuration), ['999ms', '1s', '1m', '1h']);
});
- it('keeps the session end time as the last labeled tick', () => {
+ it('drops a regular tick that would overlap the exact endpoint', () => {
assert.deepEqual(
buildTimelineAxisTicks({
- ticks: [{ value: 0 }, { value: 4000 }, { value: 8000 }, { value: 9000 }],
- totalMs: 7900,
- timelineMaxMs: 9000,
- }),
- [{ value: 0 }, { value: 4000 }, { value: 7900 }, { value: 9000 }],
+ activeTotalMs: 121_000,
+ turnStartsMs: [0],
+ turnGapMs: 0,
+ }).map(tick => tick.value),
+ [0, 30_000, 60_000, 90_000, 121_000],
);
});