Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

feat(trace): graph view mode switcher — aggregated vs expanded as-it-ran DAG (LFE-10676) (#14934)

Nikita Kabardin33950d9493e5
diff --git a/web/src/__tests__/buildExpandedGraph.clienttest.ts b/web/src/__tests__/buildExpandedGraph.clienttest.ts
new file mode 100644
index 0000000000..0706cc8898
--- /dev/null
+++ b/web/src/__tests__/buildExpandedGraph.clienttest.ts
@@ -0,0 +1,388 @@
+import {
+ buildExpandedGraph,
+ MAX_EXPANDED_EDGES,
+} from "@/src/features/trace-graph-view/buildExpandedGraph";
+import {
+ type AgentGraphDataResponse,
+ LANGFUSE_START_NODE_NAME,
+ LANGFUSE_END_NODE_NAME,
+} from "@/src/features/trace-graph-view/types";
+
+describe("buildExpandedGraph", () => {
+ const obs = (
+ overrides: Partial<AgentGraphDataResponse> = {},
+ ): AgentGraphDataResponse => ({
+ id: "mock-id",
+ name: "mock-name",
+ node: null,
+ step: null,
+ parentObservationId: null,
+ startTime: "2026-01-01T00:00:00.000Z",
+ endTime: "2026-01-01T00:00:01.000Z",
+ observationType: "AGENT",
+ ...overrides,
+ });
+
+ const t = (seconds: number) =>
+ new Date(Date.UTC(2026, 0, 1, 0, 0, seconds)).toISOString();
+
+ const edgeSet = (result: ReturnType<typeof buildExpandedGraph>) =>
+ new Set(result.graph.edges.map((e) => `${e.from}->${e.to}`));
+
+ describe("nodes", () => {
+ it("creates one node per observation — repeated names stay distinct", () => {
+ const data = [
+ obs({ id: "a1", name: "agent", startTime: t(0), endTime: t(10) }),
+ obs({ id: "l1", name: "llm", startTime: t(1), endTime: t(2), step: 2 }),
+ obs({ id: "l2", name: "llm", startTime: t(3), endTime: t(4), step: 3 }),
+ obs({ id: "l3", name: "llm", startTime: t(5), endTime: t(6), step: 4 }),
+ ];
+
+ const result = buildExpandedGraph(data);
+ const llmNodes = result.graph.nodes.filter((n) => n.label === "llm");
+
+ expect(llmNodes.map((n) => n.id)).toEqual(["l1", "l2", "l3"]);
+ });
+
+ it("dedupes duplicate observation ids", () => {
+ const data = [
+ obs({ id: "a1", name: "agent" }),
+ obs({ id: "a1", name: "agent" }),
+ ];
+
+ const result = buildExpandedGraph(data);
+ const agentNodes = result.graph.nodes.filter((n) => n.id === "a1");
+
+ expect(agentNodes).toHaveLength(1);
+ });
+
+ it("replaces incoming system rows with derived start/end anchors", () => {
+ const data = [
+ obs({
+ id: LANGFUSE_START_NODE_NAME,
+ name: LANGFUSE_START_NODE_NAME,
+ step: 0,
+ }),
+ obs({ id: "a1", name: "agent", step: 1 }),
+ obs({
+ id: LANGFUSE_END_NODE_NAME,
+ name: LANGFUSE_END_NODE_NAME,
+ step: 2,
+ }),
+ ];
+
+ const result = buildExpandedGraph(data);
+
+ expect(result.graph.nodes.map((n) => n.id)).toEqual([
+ LANGFUSE_START_NODE_NAME,
+ "a1",
+ LANGFUSE_END_NODE_NAME,
+ ]);
+ expect(edgeSet(result)).toEqual(
+ new Set([
+ `${LANGFUSE_START_NODE_NAME}->a1`,
+ `a1->${LANGFUSE_END_NODE_NAME}`,
+ ]),
+ );
+ // system nodes are not click-selectable observations
+ expect(result.nodeToObservationsMap).toEqual({ a1: ["a1"] });
+ });
+ });
+
+ describe("edges", () => {
+ it("chains sequential siblings and descends from the parent", () => {
+ const data = [
+ obs({ id: "root", name: "root", startTime: t(0), endTime: t(10) }),
+ obs({
+ id: "l1",
+ name: "llm",
+ parentObservationId: "root",
+ startTime: t(1),
+ endTime: t(2),
+ }),
+ obs({
+ id: "l2",
+ name: "llm",
+ parentObservationId: "root",
+ startTime: t(3),
+ endTime: t(4),
+ }),
+ ];
+
+ const result = buildExpandedGraph(data);
+
+ expect(edgeSet(result)).toEqual(
+ new Set([
+ `${LANGFUSE_START_NODE_NAME}->root`,
+ "root->l1",
+ "l1->l2",
+ // __end__ hangs off the end of the ROOT-level run, not nested leaves
+ `root->${LANGFUSE_END_NODE_NAME}`,
+ ]),
+ );
+ });
+
+ it("forks parallel siblings and joins them into the next step", () => {
+ const data = [
+ obs({ id: "plan", name: "plan", startTime: t(0), endTime: t(1) }),
+ obs({ id: "s1", name: "search-a", startTime: t(2), endTime: t(5) }),
+ obs({ id: "s2", name: "search-b", startTime: t(2), endTime: t(6) }),
+ obs({ id: "sum", name: "summarize", startTime: t(7), endTime: t(8) }),
+ ];
+
+ const result = buildExpandedGraph(data);
+
+ expect(edgeSet(result)).toEqual(
+ new Set([
+ `${LANGFUSE_START_NODE_NAME}->plan`,
+ "plan->s1",
+ "plan->s2",
+ "s1->sum",
+ "s2->sum",
+ `sum->${LANGFUSE_END_NODE_NAME}`,
+ ]),
+ );
+ });
+
+ it("keeps only direct predecessors (transitive reduction)", () => {
+ // a finishes, then b, then c starts: c connects from b only — the
+ // a-before-c ordering is implied through b.
+ const data = [
+ obs({ id: "a", name: "a", startTime: t(0), endTime: t(1) }),
+ obs({ id: "b", name: "b", startTime: t(2), endTime: t(3) }),
+ obs({ id: "c", name: "c", startTime: t(4), endTime: t(5) }),
+ ];
+
+ const result = buildExpandedGraph(data);
+
+ expect(edgeSet(result).has("a->c")).toBe(false);
+ expect(edgeSet(result).has("a->b")).toBe(true);
+ expect(edgeSet(result).has("b->c")).toBe(true);
+ });
+
+ it("walks parent chains through observations missing from the graph", () => {
+ // The middle span is not part of the graph data (e.g. filtered out);
+ // its child should resolve to the grandparent via the ancestry list.
+ const graphData = [
+ obs({ id: "root", name: "root", startTime: t(0), endTime: t(10) }),
+ obs({
+ id: "leaf",
+ name: "leaf",
+ parentObservationId: "hidden",
+ startTime: t(1),
+ endTime: t(2),
+ }),
+ ];
+ const ancestry = [
+ ...graphData,
+ obs({
+ id: "hidden",
+ name: "hidden",
+ parentObservationId: "root",
+ startTime: t(1),
+ endTime: t(3),
+ }),
+ ];
+
+ const result = buildExpandedGraph(graphData, ancestry);
+
+ expect(edgeSet(result).has("root->leaf")).toBe(true);
+ });
+
+ it("chains through an instant (zero-duration) predecessor instead of orphaning", () => {
+ // c1 is instant: the strict happened-before reduction has no "still
+ // running at the latest start" predecessor for c2 — the fallback must
+ // keep the chain (root→c1→c2), never wire c2 to __start__.
+ const data = [
+ obs({ id: "root", name: "root", startTime: t(0), endTime: t(10) }),
+ obs({
+ id: "c1",
+ name: "instant",
+ parentObservationId: "root",
+ startTime: t(1),
+ endTime: t(1),
+ }),
+ obs({
+ id: "c2",
+ name: "next",
+ parentObservationId: "root",
+ startTime: t(2),
+ endTime: t(3),
+ }),
+ ];
+
+ const result = buildExpandedGraph(data);
+
+ expect(edgeSet(result).has("c1->c2")).toBe(true);
+ expect(edgeSet(result).has(`${LANGFUSE_START_NODE_NAME}->c2`)).toBe(
+ false,
+ );
+ });
+
+ it("chains through a still-running predecessor (no endTime)", () => {
+ const data = [
+ obs({
+ id: "a",
+ name: "a",
+ startTime: t(0),
+ endTime: undefined,
+ }),
+ obs({ id: "b", name: "b", startTime: t(2), endTime: t(3) }),
+ ];
+
+ const result = buildExpandedGraph(data);
+
+ expect(edgeSet(result).has("a->b")).toBe(true);
+ expect(edgeSet(result).has(`${LANGFUSE_START_NODE_NAME}->b`)).toBe(false);
+ });
+
+ it("keeps the edge of an instant that ran alongside a longer sibling", () => {
+ // The instant's own start is the latest start among the predecessors —
+ // the reduction must compare each predecessor against the OTHERS'
+ // starts, or the instant's edge is dropped and it dangles as a false
+ // sink while the successor loses a real ordering edge.
+ const data = [
+ obs({ id: "a", name: "long", startTime: t(0), endTime: t(5) }),
+ obs({ id: "i", name: "instant", startTime: t(3), endTime: t(3) }),
+ obs({ id: "c", name: "next", startTime: t(6), endTime: t(7) }),
+ ];
+
+ const result = buildExpandedGraph(data);
+
+ // both predecessors are direct (neither fits entirely after the other)
+ expect(edgeSet(result).has("a->c")).toBe(true);
+ expect(edgeSet(result).has("i->c")).toBe(true);
+ expect(edgeSet(result).has(`i->${LANGFUSE_END_NODE_NAME}`)).toBe(false);
+ });
+
+ it("chains a same-start instant through its longer sibling instead of orphaning it", () => {
+ // b (instant) shares a's start and ends before a's start — the
+ // happened-before b→a must be emitted (end tiebreak in the run-order
+ // sort), so the reduction may legitimately drop b→c as implied via
+ // b→a→c. Without the tiebreak b sorted after a, b→a was never
+ // considered, and b dangled as a disconnected __start__→b→__end__.
+ const data = [
+ obs({ id: "a", name: "long", startTime: t(0), endTime: t(5) }),
+ obs({ id: "b", name: "instant", startTime: t(0), endTime: t(0) }),
+ obs({ id: "c", name: "next", startTime: t(10), endTime: t(15) }),
+ ];
+
+ const result = buildExpandedGraph(data);
+
+ expect(edgeSet(result)).toEqual(
+ new Set([
+ `${LANGFUSE_START_NODE_NAME}->b`,
+ "b->a",
+ "a->c",
+ `c->${LANGFUSE_END_NODE_NAME}`,
+ ]),
+ );
+ });
+
+ it("chains same-timestamp instants singly instead of quadratically", () => {
+ const data = ["s1", "s2", "s3"].map((id) =>
+ obs({ id, name: id, startTime: t(1), endTime: t(1) }),
+ );
+
+ const result = buildExpandedGraph(data);
+
+ expect(edgeSet(result).has("s1->s2")).toBe(true);
+ expect(edgeSet(result).has("s2->s3")).toBe(true);
+ expect(edgeSet(result).has("s1->s3")).toBe(false);
+ });
+
+ it("treats unresolvable parents as root-level", () => {
+ // LangGraph shape: node observations whose parent (the trace root span)
+ // is filtered out of the graph entirely → they chain at root level.
+ const data = [
+ obs({
+ id: "n1",
+ name: "planner",
+ parentObservationId: "gone",
+ startTime: t(0),
+ endTime: t(1),
+ }),
+ obs({
+ id: "n2",
+ name: "retriever",
+ parentObservationId: "gone",
+ startTime: t(2),
+ endTime: t(3),
+ }),
+ ];
+
+ const result = buildExpandedGraph(data);
+
+ expect(edgeSet(result)).toEqual(
+ new Set([
+ `${LANGFUSE_START_NODE_NAME}->n1`,
+ "n1->n2",
+ `n2->${LANGFUSE_END_NODE_NAME}`,
+ ]),
+ );
+ });
+ });
+
+ it("bails with limitExceeded when parallel batches explode the edge count", () => {
+ // A join of 110 parallel siblings into 110 parallel successors is
+ // all-to-all (12100 edges), past the budget: the builder must bail
+ // instead of freezing ELK.
+ const data = [
+ ...Array.from({ length: 110 }, (_, i) =>
+ obs({ id: `a${i}`, name: `a${i}`, startTime: t(0), endTime: t(100) }),
+ ),
+ ...Array.from({ length: 110 }, (_, i) =>
+ obs({
+ id: `b${i}`,
+ name: `b${i}`,
+ startTime: t(200),
+ endTime: t(300),
+ }),
+ ),
+ ];
+
+ const result = buildExpandedGraph(data);
+
+ expect(110 * 110).toBeGreaterThan(MAX_EXPANDED_EDGES);
+ expect(result.limitExceeded).toBe(true);
+ expect(result.graph.nodes).toEqual([]);
+ expect(result.graph.edges).toEqual([]);
+ });
+
+ it("keeps a maximal linear chain under the edge budget", () => {
+ // 5000 sequential calls (the panel's observation cap) are ~5000 linear
+ // edges — a legitimate shape that must render, not bail.
+ const n = 5000;
+ const data = Array.from({ length: n }, (_, i) =>
+ obs({
+ id: `o${i}`,
+ name: "call",
+ startTime: t(i * 2),
+ endTime: t(i * 2 + 1),
+ }),
+ );
+
+ const result = buildExpandedGraph(data);
+
+ expect(result.limitExceeded).toBeUndefined();
+ expect(result.graph.nodes).toHaveLength(n + 2);
+ });
+
+ it("returns an identity observation map", () => {
+ const data = [
+ obs({ id: "a", name: "a", step: 1 }),
+ obs({ id: "b", name: "b", step: 2 }),
+ ];
+
+ const result = buildExpandedGraph(data);
+
+ expect(result.nodeToObservationsMap).toEqual({ a: ["a"], b: ["b"] });
+ });
+
+ it("returns an empty graph for empty input", () => {
+ expect(buildExpandedGraph([])).toEqual({
+ graph: { nodes: [], edges: [] },
+ nodeToObservationsMap: {},
+ });
+ });
+});
diff --git a/web/src/components/trace/components/TraceGraphView/TraceGraphView.tsx b/web/src/components/trace/components/TraceGraphView/TraceGraphView.tsx
index b388f86dbb..c1a71c00af 100644
--- a/web/src/components/trace/components/TraceGraphView/TraceGraphView.tsx
+++ b/web/src/components/trace/components/TraceGraphView/TraceGraphView.tsx
@@ -8,10 +8,12 @@
import { TraceGraphView as TraceGraphViewComponent } from "@/src/features/trace-graph-view/components/TraceGraphView";
import { useTraceGraphData } from "../../contexts/TraceGraphDataContext";
import { useActiveObservationIds } from "../../contexts/PlayheadContext";
+import { useViewPreferences } from "../../contexts/ViewPreferencesContext";
export function TraceGraphView() {
const { agentGraphData, isLoading } = useTraceGraphData();
const activeObservationIds = useActiveObservationIds();
+ const { graphViewMode, setGraphViewMode } = useViewPreferences();
if (isLoading) {
return (
@@ -29,6 +31,8 @@ export function TraceGraphView() {
<TraceGraphViewComponent
agentGraphData={agentGraphData}
activeObservationIds={activeObservationIds}
+ viewMode={graphViewMode}
+ onViewModeChange={setGraphViewMode}
/>
);
}
diff --git a/web/src/components/trace/components/_layout/TracePanelNavigationLayoutDesktop.tsx b/web/src/components/trace/components/_layout/TracePanelNavigationLayoutDesktop.tsx
index 26d0ad951c..7c344d21c5 100644
--- a/web/src/components/trace/components/_layout/TracePanelNavigationLayoutDesktop.tsx
+++ b/web/src/components/trace/components/_layout/TracePanelNavigationLayoutDesktop.tsx
@@ -17,18 +17,21 @@
* - useTraceGraphData() - for the collapsed-by-default heuristic
*/
-import { useLayoutEffect, type ReactNode } from "react";
+import { useLayoutEffect, useRef, type ReactNode } from "react";
import { ChevronDown, ChevronUp } from "lucide-react";
+import { useGroupRef } from "react-resizable-panels";
import {
ResizablePanel,
ResizablePanelGroup,
ResizableHandle,
usePanelRef,
+ useDefaultLayout,
} from "@/src/components/ui/resizable";
import useLocalStorage from "@/src/components/useLocalStorage";
import { useDesktopLayoutContext } from "./TraceLayoutDesktop";
import { useTraceData } from "../../contexts/TraceDataContext";
import { useTraceGraphData } from "../../contexts/TraceGraphDataContext";
+import { useViewPreferences } from "../../contexts/ViewPreferencesContext";
import { TracePanelNavigationHeader } from "./TracePanelNavigationHeader";
import { TracePanelNavigationHiddenNotice } from "./TracePanelNavigationHiddenNotice";
@@ -36,6 +39,23 @@ import { TracePanelNavigationHiddenNotice } from "./TracePanelNavigationHiddenNo
// h-7 so a collapsed panel shows exactly the bar and nothing else.
const GRAPH_BAR_PX = 28;
+// The tree/graph split persists in localStorage like the outer nav/detail
+// split (LFE-10601/LFE-10729 model): peek and full-page each keep their own
+// group so a ratio dragged in the short peek panel doesn't leak into the tall
+// full-page view and vice versa. The graph panel's collapse state persists
+// separately (per-project, below) — the saved layout is always the OPEN ratio.
+const GRAPH_SPLIT_GROUP_ID = "trace-nav-graph-split-v1";
+const PEEK_GRAPH_SPLIT_GROUP_ID = "trace-nav-graph-split-peek-v1";
+const GRAPH_SPLIT_TREE_PANEL_ID = "trace-nav-graph-split-tree";
+const GRAPH_SPLIT_GRAPH_PANEL_ID = "trace-nav-graph-split-graph";
+
+// No-op storage so `useDefaultLayout` never touches a real Storage during
+// SSR / DOM-less tests (mirrors TraceLayoutDesktop).
+const NOOP_LAYOUT_STORAGE = {
+ getItem: () => null,
+ setItem: () => {},
+};
+
/**
* Slim header strip of the graph panel — its collapsed form, and the
* click-to-toggle affordance while expanded (mirrors the mobile layout's bar).
@@ -76,6 +96,7 @@ export function TracePanelNavigationLayoutDesktop({
useDesktopLayoutContext();
const { trace } = useTraceData();
const { isAgentGraph } = useTraceGraphData();
+ const { isPeekMode } = useViewPreferences();
// Per-project persisted collapse. Tri-state: null = no user choice yet, so
// the default stays reactive (agent graphs expand, >1-node-only graphs stay
@@ -86,15 +107,57 @@ export function TracePanelNavigationLayoutDesktop({
const graphCollapsed = storedGraphCollapsed ?? !isAgentGraph;
const graphPanelRef = usePanelRef();
+ const graphGroupRef = useGroupRef();
+
+ // Persisted tree/graph ratio (see the group-id comment above).
+ const { defaultLayout, onLayoutChanged } = useDefaultLayout({
+ id: isPeekMode ? PEEK_GRAPH_SPLIT_GROUP_ID : GRAPH_SPLIT_GROUP_ID,
+ panelIds: [GRAPH_SPLIT_TREE_PANEL_ID, GRAPH_SPLIT_GRAPH_PANEL_ID],
+ storage:
+ typeof window === "undefined" ? NOOP_LAYOUT_STORAGE : window.localStorage,
+ });
+
+ // Save only the OPEN ratio: while the graph panel sits on its 28px rail the
+ // layout is the collapse state (persisted separately) — letting it through
+ // would overwrite the user's preferred split with the rail share. The ref
+ // tracks the freshest saved share for the expand-restore below (the hook's
+ // `defaultLayout` is the mount-time snapshot).
+ const lastOpenGraphSharePct = useRef<number | null>(
+ defaultLayout?.[GRAPH_SPLIT_GRAPH_PANEL_ID] ?? null,
+ );
+ const handleLayoutChanged = (layout: Record<string, number>) => {
+ if (graphPanelRef.current?.isCollapsed()) return;
+ lastOpenGraphSharePct.current =
+ layout[GRAPH_SPLIT_GRAPH_PANEL_ID] ?? lastOpenGraphSharePct.current;
+ onLayoutChanged(layout);
+ };
// State → panel: keep the imperative panel in sync (mount, storage default,
// bar toggle). Pre-paint so an initially-collapsed panel never flashes open.
useLayoutEffect(() => {
const panel = graphPanelRef.current;
if (!panel) return;
- if (graphCollapsed && !panel.isCollapsed()) panel.collapse();
- else if (!graphCollapsed && panel.isCollapsed()) panel.expand();
- }, [graphCollapsed, graphPanelRef, secondaryContent]);
+ if (graphCollapsed && !panel.isCollapsed()) {
+ panel.collapse();
+ } else if (!graphCollapsed && panel.isCollapsed()) {
+ // A panel that mounted collapsed has no in-session pre-collapse size —
+ // a bare expand() falls back to its minSize. Reopen at the persisted
+ // open ratio instead, atomically via the GROUP (chained per-panel
+ // expand()+resize() validates against a stale store and no-ops — the
+ // TraceLayoutDesktop lesson). Bounded by the panels' 20% mins so a
+ // corrupt value can't strand the layout.
+ const share = lastOpenGraphSharePct.current;
+ const group = graphGroupRef.current;
+ if (group && share !== null && share >= 20 && share <= 80) {
+ group.setLayout({
+ [GRAPH_SPLIT_TREE_PANEL_ID]: 100 - share,
+ [GRAPH_SPLIT_GRAPH_PANEL_ID]: share,
+ });
+ } else {
+ panel.expand();
+ }
+ }
+ }, [graphCollapsed, graphPanelRef, graphGroupRef, secondaryContent]);
return (
<div className="flex h-full flex-col border-r">
@@ -110,12 +173,21 @@ export function TracePanelNavigationLayoutDesktop({
<ResizablePanelGroup
orientation="vertical"
className="flex-1 overflow-hidden"
+ id={isPeekMode ? PEEK_GRAPH_SPLIT_GROUP_ID : GRAPH_SPLIT_GROUP_ID}
+ groupRef={graphGroupRef}
+ defaultLayout={defaultLayout}
+ onLayoutChanged={handleLayoutChanged}
>
- <ResizablePanel defaultSize="60%" minSize="20%">
+ <ResizablePanel
+ id={GRAPH_SPLIT_TREE_PANEL_ID}
+ defaultSize="60%"
+ minSize="20%"
+ >
<div className="h-full overflow-hidden">{children}</div>
</ResizablePanel>
<ResizableHandle className="bg-border h-px" />
<ResizablePanel
+ id={GRAPH_SPLIT_GRAPH_PANEL_ID}
defaultSize="40%"
minSize="20%"
collapsible
diff --git a/web/src/components/trace/contexts/ViewPreferencesContext.tsx b/web/src/components/trace/contexts/ViewPreferencesContext.tsx
index 368fbad4d8..70548e5446 100644
--- a/web/src/components/trace/contexts/ViewPreferencesContext.tsx
+++ b/web/src/components/trace/contexts/ViewPreferencesContext.tsx
@@ -14,6 +14,10 @@
import { createContext, useContext, useMemo, type ReactNode } from "react";
import { type ObservationLevelType, ObservationLevel } from "@langfuse/shared";
import useLocalStorage from "@/src/components/useLocalStorage";
+import {
+ GRAPH_VIEW_MODES,
+ type GraphViewMode,
+} from "@/src/features/trace-graph-view/types";
/** Log view ordering mode */
export type LogViewMode = "chronological" | "tree-order";
@@ -37,6 +41,9 @@ interface ViewPreferencesContextValue {
setShowComments: (value: boolean) => void;
showGraph: boolean;
setShowGraph: (value: boolean) => void;
+ /** Graph panel build mode (aggregated vs expanded "as it ran") */
+ graphViewMode: GraphViewMode;
+ setGraphViewMode: (value: GraphViewMode) => void;
minObservationLevel: ObservationLevelType;
setMinObservationLevel: (value: ObservationLevelType) => void;
/** Whether trace is rendered in peek mode (e.g., table peek views) */
@@ -100,6 +107,13 @@ export function ViewPreferencesProvider({
);
const [showComments, setShowComments] = useLocalStorage("showComments", true);
const [showGraph, setShowGraph] = useLocalStorage("showGraph", true);
+ const [storedGraphViewMode, setGraphViewMode] =
+ useLocalStorage<GraphViewMode>("graphViewMode", "aggregated");
+ // Sanitize persisted values: the mode enum may evolve and a stale
+ // localStorage entry must degrade to the default, not break the graph.
+ const graphViewMode = GRAPH_VIEW_MODES.includes(storedGraphViewMode)
+ ? storedGraphViewMode
+ : "aggregated";
const [minObservationLevel, setMinObservationLevel] =
useLocalStorage<ObservationLevelType>(
"minObservationLevel",
@@ -135,6 +149,8 @@ export function ViewPreferencesProvider({
setShowComments,
showGraph,
setShowGraph,
+ graphViewMode,
+ setGraphViewMode,
minObservationLevel,
setMinObservationLevel,
isPeekMode,
@@ -161,6 +177,8 @@ export function ViewPreferencesProvider({
setShowComments,
showGraph,
setShowGraph,
+ graphViewMode,
+ setGraphViewMode,
minObservationLevel,
setMinObservationLevel,
isPeekMode,
diff --git a/web/src/features/trace-graph-view/README.md b/web/src/features/trace-graph-view/README.md
index 576830a53d..45bfa08f8c 100644
--- a/web/src/features/trace-graph-view/README.md
+++ b/web/src/features/trace-graph-view/README.md
@@ -11,13 +11,23 @@ custom renderer keeps it virtualization-ready.
agentGraphData (tRPC getAgentGraphData)
→ buildStepData timing-based step inference (cycle-guarded)
/ transformLanggraphToGeneralized when langgraph metadata exists
- → buildGraphCanvasData nodes/edges + node→observations cycling map
+ → one builder per GraphViewMode (the mode switch overlaid on the canvas):
+ buildGraphCanvasData "aggregated": repeats collapse by name (+ cycling
+ map); langgraph traces show framework nodes only
+ buildExpandedGraph "expanded": one node per observation (EVERY call,
+ minus EVENTs — framework metadata is ignored);
+ edges from the instrumented hierarchy +
+ happened-before sibling ordering (fork/join)
→ layout/elkLayout.computeGraphLayout async ELK (lazy import);
layout/measureNode estimates node boxes (labels, counter reserve)
→ components/ElkGraphRenderer draws + gestures
components/GraphNode view-only node (memo)
```
+Both builders return the same `{graph, nodeToObservationsMap}` pair — everything
+downstream is mode-agnostic. The selected mode is a trace view preference
+(`ViewPreferencesContext.graphViewMode`, localStorage), passed in as a prop.
+
## Ownership
- **Viewport**: deterministic and data-derived — the rendered transform is
diff --git a/web/src/features/trace-graph-view/buildExpandedGraph.ts b/web/src/features/trace-graph-view/buildExpandedGraph.ts
new file mode 100644
index 0000000000..7c59eb3b17
--- /dev/null
+++ b/web/src/features/trace-graph-view/buildExpandedGraph.ts
@@ -0,0 +1,272 @@
+import {
+ type AgentGraphDataResponse,
+ type GraphNodeData,
+ LANGFUSE_START_NODE_NAME,
+ LANGFUSE_END_NODE_NAME,
+ LANGGRAPH_START_NODE_NAME,
+ LANGGRAPH_END_NODE_NAME,
+} from "./types";
+import { type GraphParseResult } from "./buildGraphCanvasData";
+
+/**
+ * Expanded ("as it ran") graph builder: one node per observation `id` —
+ * repeated calls become distinct nodes instead of collapsing into a single
+ * `name (3/3)` vertex, so loops unroll into an acyclic DAG (which call is
+ * which reads off the run order of the layout).
+ *
+ * The instrumented hierarchy is the source of truth: a child hangs off its
+ * parent (descent into a subtree) or off the sibling(s) that actually
+ * finished before it started (fork/join derived from timing, only ever
+ * within one parent's scope). No step inference, no framework metadata.
+ */
+const SYSTEM_NODE_IDS = new Set<string>([
+ LANGFUSE_START_NODE_NAME,
+ LANGFUSE_END_NODE_NAME,
+ LANGGRAPH_START_NODE_NAME,
+ LANGGRAPH_END_NODE_NAME,
+]);
+
+/**
+ * Edge budget for expanded graphs. Consecutive parallel batches connect
+ * all-to-all (N×M edges), so a wide trace can explode combinatorially —
+ * ELK's layout cost grows super-linearly with edges and would freeze the
+ * tab long before the 5000-observation panel cap kicks in. Builders bail
+ * past the budget and the view shows a "too complex" notice instead. The
+ * bound clears every linear shape under the panel's observation cap (a
+ * 5000-call chain is ~5000 edges) and cuts off the quadratic ones.
+ */
+export const MAX_EXPANDED_EDGES = 10_000;
+
+export interface ExpandedGraphResult extends GraphParseResult {
+ /** True when the trace exceeded MAX_EXPANDED_EDGES — the graph is empty. */
+ limitExceeded?: boolean;
+}
+
+type Edge = { from: string; to: string };
+
+const EDGE_LIMIT_RESULT: ExpandedGraphResult = {
+ graph: { nodes: [], edges: [] },
+ nodeToObservationsMap: {},
+ limitExceeded: true,
+};
+
+function startMs(obs: AgentGraphDataResponse): number {
+ return new Date(obs.startTime).getTime();
+}
+
+/** Effective end: missing endTime counts as instant; inverted ranges clamp. */
+function endMs(obs: AgentGraphDataResponse): number {
+ const start = startMs(obs);
+ const end = obs.endTime ? new Date(obs.endTime).getTime() : start;
+ return Math.max(start, end);
+}
+
+/**
+ * Run order for the sibling scan. The happened-before pass only looks
+ * BACKWARDS (j < i), so it needs: x happened-before y (x.end ≤ y.start) ⇒
+ * x sorts before y. Start alone doesn't guarantee that — a same-start
+ * instant ends before its longer sibling STARTS, yet an id tiebreak could
+ * sort it after, and the reduction would then drop edges citing a chain
+ * that was never emitted. Tie-breaking by END fixes it: a same-start pair
+ * can only be ordered (one an instant at the shared start), and the instant
+ * has the smaller end. Same-instant ties (id tiebreak) are symmetric and
+ * covered by the fallback chain.
+ */
+function byRunOrder(
+ a: AgentGraphDataResponse,
+ b: AgentGraphDataResponse,
+): number {
+ return (
+ startMs(a) - startMs(b) || endMs(a) - endMs(b) || a.id.localeCompare(b.id)
+ );
+}
+
+/**
+ * Structural flow edges. Observations are grouped under their nearest included
+ * ancestor (`ancestry` supplies parent links for observations filtered out of
+ * the graph, e.g. EVENTs; unresolvable parents land in the root group). Within
+ * a group, an observation connects from the sibling(s) that actually finished
+ * before it started — reduced to the direct predecessors, so sequential work
+ * chains, parallel work forks, and a later step joins the branches back. A
+ * child no sibling precedes hangs off its parent (descent into the subtree).
+ *
+ * Also returns the root group's sinks (members with no outgoing SIBLING edge —
+ * descent edges into children don't count) so the caller wires __end__ to the
+ * end of the top-level run only, not to every nested leaf.
+ */
+function buildFlowEdges(
+ observations: AgentGraphDataResponse[],
+ ancestry: AgentGraphDataResponse[],
+): { edges: Edge[]; sinkIds: Set<string> } | null {
+ const included = new Set(observations.map((obs) => obs.id));
+ const ancestryById = new Map(ancestry.map((obs) => [obs.id, obs]));
+
+ const resolveParent = (obs: AgentGraphDataResponse): string | null => {
+ const seen = new Set<string>();
+ let parentId = obs.parentObservationId;
+ while (parentId && !seen.has(parentId)) {
+ if (included.has(parentId)) return parentId;
+ seen.add(parentId);
+ parentId = ancestryById.get(parentId)?.parentObservationId ?? null;
+ }
+ return null;
+ };
+
+ const groups = new Map<string | null, AgentGraphDataResponse[]>();
+ for (const obs of observations) {
+ const parent = resolveParent(obs);
+ const group = groups.get(parent);
+ if (group) group.push(obs);
+ else groups.set(parent, [obs]);
+ }
+
+ const edges: Edge[] = [];
+ const rootSiblingFroms = new Set<string>();
+ for (const [parentId, group] of groups) {
+ const ordered = [...group].sort(byRunOrder);
+ // Precomputed times + index loops: the scan is O(n²) in the group size
+ // and must stay allocation-free to be instant at the 5000-observation
+ // panel cap (a naive slice/filter per element takes seconds there).
+ const starts = ordered.map(startMs);
+ const ends = ordered.map(endMs);
+ for (let i = 0; i < ordered.length; i++) {
+ if (edges.length > MAX_EXPANDED_EDGES) return null;
+ const current = ordered[i];
+ // Stats over the siblings that finished before this one started
+ // ("happened before"): the latest end (fallback anchor) and the two
+ // largest starts. Two, not one: the reduction predicate for a
+ // predecessor p must range over the OTHER predecessors' starts — using
+ // a single max would compare an instant against its own start and
+ // wrongly drop its edge (p.end === p.start === max).
+ let finishedCount = 0;
+ let maxEnd = -Infinity;
+ let latestFallback = -1;
+ let maxStart = -Infinity;
+ let maxStartIdx = -1;
+ let secondMaxStart = -Infinity;
+ for (let j = 0; j < i; j++) {
+ if (ends[j] > starts[i]) continue;
+ finishedCount++;
+ if (ends[j] >= maxEnd) {
+ maxEnd = ends[j];
+ latestFallback = j;
+ }
+ if (starts[j] > maxStart) {
+ secondMaxStart = maxStart;
+ maxStart = starts[j];
+ maxStartIdx = j;
+ } else if (starts[j] > secondMaxStart) {
+ secondMaxStart = starts[j];
+ }
+ }
+ if (finishedCount === 0) {
+ // Nothing precedes it in this scope: descend from the parent. Root
+ // group sources get no edge — __start__ wiring covers them.
+ if (parentId !== null) edges.push({ from: parentId, to: current.id });
+ continue;
+ }
+ // Direct predecessors only (transitive reduction of the interval
+ // order): keep p iff no OTHER predecessor fits entirely after it,
+ // i.e. p.end > max(start of the others). When same-millisecond
+ // instants tie for the latest start, every candidate fails the strict
+ // check (nothing ends after the tied start) — fall back to one edge
+ // from the latest-ending predecessor so a chain of instants stays a
+ // chain instead of orphaning every successor onto __start__.
+ let emitted = false;
+ for (let j = 0; j < i; j++) {
+ if (ends[j] > starts[i]) continue;
+ const othersMaxStart = j === maxStartIdx ? secondMaxStart : maxStart;
+ if (ends[j] > othersMaxStart) {
+ edges.push({ from: ordered[j].id, to: current.id });
+ if (parentId === null) rootSiblingFroms.add(ordered[j].id);
+ emitted = true;
+ }
+ }
+ if (!emitted) {
+ edges.push({ from: ordered[latestFallback].id, to: current.id });
+ if (parentId === null) {
+ rootSiblingFroms.add(ordered[latestFallback].id);
+ }
+ }
+ }
+ }
+
+ const sinkIds = new Set(
+ (groups.get(null) ?? [])
+ .filter((obs) => !rootSiblingFroms.has(obs.id))
+ .map((obs) => obs.id),
+ );
+ return { edges, sinkIds };
+}
+
+/**
+ * Build the expanded graph. `data` is the normalized observation list (the
+ * same input the aggregated builder receives); `ancestry` optionally supplies
+ * the unfiltered observations so parent chains can be walked through
+ * observations that aren't part of the graph.
+ */
+export function buildExpandedGraph(
+ data: AgentGraphDataResponse[],
+ ancestry: AgentGraphDataResponse[] = data,
+): ExpandedGraphResult {
+ // Dedupe by id (re-seeded/duplicated ingestion can repeat ids) and drop the
+ // synthetic system rows — start/end are re-derived from the edges below.
+ const byId = new Map<string, AgentGraphDataResponse>();
+ for (const obs of data) {
+ if (!SYSTEM_NODE_IDS.has(obs.id) && !byId.has(obs.id)) {
+ byId.set(obs.id, obs);
+ }
+ }
+ const observations = [...byId.values()].sort(byRunOrder);
+
+ if (observations.length === 0) {
+ return { graph: { nodes: [], edges: [] }, nodeToObservationsMap: {} };
+ }
+
+ const nodes: GraphNodeData[] = observations.map((obs) => ({
+ id: obs.id,
+ label: obs.name,
+ type: obs.observationType,
+ }));
+
+ const built = buildFlowEdges(observations, ancestry);
+ if (built === null) return EDGE_LIMIT_RESULT;
+ const { edges, sinkIds } = built;
+
+ // Synthetic entry/exit anchors, derived from the built edges: __start__
+ // feeds every source; sinks feed __end__. Nested leaves always have an
+ // incoming parent/sibling edge, so sources are naturally the root-level
+ // heads, and buildFlowEdges caps sinks to the end of the root-level run so
+ // a bushy tree's every leaf doesn't converge on __end__.
+ const hasIncoming = new Set(edges.map((edge) => edge.to));
+ const sources = observations.filter((obs) => !hasIncoming.has(obs.id));
+ const sinks = observations.filter((obs) => sinkIds.has(obs.id));
+
+ nodes.unshift({
+ id: LANGFUSE_START_NODE_NAME,
+ label: LANGFUSE_START_NODE_NAME,
+ type: "LANGGRAPH_SYSTEM",
+ });
+ nodes.push({
+ id: LANGFUSE_END_NODE_NAME,
+ label: LANGFUSE_END_NODE_NAME,
+ type: "LANGGRAPH_SYSTEM",
+ });
+ for (const source of sources) {
+ edges.push({ from: LANGFUSE_START_NODE_NAME, to: source.id });
+ }
+ for (const sink of sinks) {
+ edges.push({ from: sink.id, to: LANGFUSE_END_NODE_NAME });
+ }
+ // Anchor wiring counts against the budget too (a degenerate trace of
+ // isolated observations gets two anchor edges apiece).
+ if (edges.length > MAX_EXPANDED_EDGES) return EDGE_LIMIT_RESULT;
+
+ // One observation per node — clicking a node selects exactly that call.
+ const nodeToObservationsMap: Record<string, string[]> = {};
+ for (const obs of observations) {
+ nodeToObservationsMap[obs.id] = [obs.id];
+ }
+
+ return { graph: { nodes, edges }, nodeToObservationsMap };
+}
diff --git a/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx b/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx
index 5a6e62ea68..87daa7e072 100644
--- a/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx
+++ b/web/src/features/trace-graph-view/components/ElkGraphRenderer.tsx
@@ -17,7 +17,11 @@ import { ZoomIn, ZoomOut, Maximize } from "lucide-react";
import { Button } from "@/src/components/ui/button";
import { type GraphCanvasData, type GraphNodeData } from "../types";
-import { computeGraphLayout, type GraphLayout } from "../layout/elkLayout";
+import {
+ computeGraphLayout,
+ type GraphLayout,
+ type GraphLayoutDirection,
+} from "../layout/elkLayout";
import { GraphNode } from "./GraphNode";
type ElkGraphRendererProps = {
@@ -32,6 +36,8 @@ type ElkGraphRendererProps = {
* (resting state stays fully visible — no dimming).
*/
activeNodeNames?: ReadonlySet<string> | null;
+ /** Layer direction: DOWN (default) or RIGHT (long expanded chains). */
+ layoutDirection?: GraphLayoutDirection;
};
type Transform = { x: number; y: number; k: number };
@@ -78,6 +84,7 @@ export const ElkGraphRenderer: React.FC<ElkGraphRendererProps> = ({
nodeToObservationsMap = {},
currentObservationIndices = {},
activeNodeNames = null,
+ layoutDirection = "DOWN",
}) => {
const containerRef = useRef<HTMLDivElement>(null);
const worldRef = useRef<HTMLDivElement>(null);
@@ -144,7 +151,7 @@ export const ElkGraphRenderer: React.FC<ElkGraphRendererProps> = ({
// A new graph gets a fresh fit; stale hover highlighting drops too.
overrideRef.current = null;
setHoveredId(null);
- computeGraphLayout(graph, nodeToObservationsMap)
+ computeGraphLayout(graph, nodeToObservationsMap, layoutDirection)
.then((result) => {
if (!cancelled) setLayout(result);
})
@@ -156,7 +163,7 @@ export const ElkGraphRenderer: React.FC<ElkGraphRendererProps> = ({
return () => {
cancelled = true;
};
- }, [graph, nodeToObservationsMap, layoutAttempt]);
+ }, [graph, nodeToObservationsMap, layoutDirection, layoutAttempt]);
// Track container size.
useEffect(() => {
diff --git a/web/src/features/trace-graph-view/components/GraphViewModeSwitch.tsx b/web/src/features/trace-graph-view/components/GraphViewModeSwitch.tsx
new file mode 100644
index 0000000000..bba1a3b89f
--- /dev/null
+++ b/web/src/features/trace-graph-view/components/GraphViewModeSwitch.tsx
@@ -0,0 +1,64 @@
+import React from "react";
+import { Combine, Route, type LucideIcon } from "lucide-react";
+
+import { cn } from "@/src/utils/tailwind";
+import { type GraphViewMode } from "../types";
+
+/**
+ * Segmented mode switch overlaid on the graph canvas. Mirrors the Tree/Timeline
+ * ViewModeSwitch styling (TracePanelNavigationHeader) so the trace view's mode
+ * switches read as one family.
+ */
+const MODES: {
+ mode: GraphViewMode;
+ icon: LucideIcon;
+ label: string;
+ title: string;
+}[] = [
+ {
+ mode: "aggregated",
+ icon: Combine,
+ label: "Aggregated",
+ title: "Repeated steps grouped into one node — the overall shape",
+ },
+ {
+ mode: "expanded",
+ icon: Route,
+ label: "Expanded",
+ title: "Every call as its own node, in the order it ran",
+ },
+];
+
+export function GraphViewModeSwitch({
+ value,
+ onChange,
+}: {
+ value: GraphViewMode;
+ onChange: (mode: GraphViewMode) => void;
+}) {
+ return (
+ <div className="bg-background/80 inline-flex h-7 items-center rounded-md border p-0.5 backdrop-blur">
+ {MODES.map(({ mode, icon: Icon, label, title }) => (
+ <button
+ key={mode}
+ type="button"
+ onClick={() => onChange(mode)}
+ aria-pressed={value === mode}
+ aria-label={label}
+ title={title}
+ className={cn(
+ "flex h-6 items-center gap-1.5 rounded-md px-2 text-xs font-medium transition-colors",
+ value === mode
+ ? "bg-primary text-primary-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ >
+ <Icon className="h-3.5 w-3.5 shrink-0" />
+ {/* Collapse to icons on narrow canvases (mirrors the nav header's
+ switch) so the pill never collides with the zoom stack. */}
+ <span className="@max-[340px]/graphcanvas:hidden">{label}</span>
+ </button>
+ ))}
+ </div>
+ );
+}
diff --git a/web/src/features/trace-graph-view/components/TraceGraphView.tsx b/web/src/features/trace-graph-view/components/TraceGraphView.tsx
index 45f82dc402..c646300d2d 100644
--- a/web/src/features/trace-graph-view/components/TraceGraphView.tsx
+++ b/web/src/features/trace-graph-view/components/TraceGraphView.tsx
@@ -6,14 +6,17 @@ import React, {
useRef,
} from "react";
import { StringParam, useQueryParam } from "use-query-params";
+import { ObservationType } from "@langfuse/shared";
import { ElkGraphRenderer } from "./ElkGraphRenderer";
-import { type AgentGraphDataResponse } from "../types";
+import { GraphViewModeSwitch } from "./GraphViewModeSwitch";
+import { type AgentGraphDataResponse, type GraphViewMode } from "../types";
import { buildStepData } from "../buildStepData";
import {
buildGraphFromStepData,
transformLanggraphToGeneralized,
} from "../buildGraphCanvasData";
+import { buildExpandedGraph } from "../buildExpandedGraph";
import {
LANGFUSE_START_NODE_NAME,
LANGFUSE_END_NODE_NAME,
@@ -28,11 +31,17 @@ type TraceGraphViewProps = {
* Mapped to their node names here so the graph glows in sync with the timeline.
*/
activeObservationIds?: ReadonlySet<string>;
+ /** How the graph is built (aggregated vs expanded) — see GraphViewMode. */
+ viewMode?: GraphViewMode;
+ /** When provided, the mode switch is rendered over the canvas. */
+ onViewModeChange?: (mode: GraphViewMode) => void;
};
export const TraceGraphView: React.FC<TraceGraphViewProps> = ({
agentGraphData,
activeObservationIds,
+ viewMode = "aggregated",
+ onViewModeChange,
}) => {
const [selectedNodeName, setSelectedNodeName] = useState<string | null>(null);
const [currentObservationId, setCurrentObservationId] = useQueryParam(
@@ -72,9 +81,31 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({
return agentGraphData; // Already normalized
}, [agentGraphData]);
- const { graph, nodeToObservationsMap } = useMemo(() => {
- return buildGraphFromStepData(normalizedData);
- }, [normalizedData]);
+ // In expanded mode node ids are observation ids (one node per call); in
+ // aggregated mode they are step names (repeats collapse into one node).
+ const isExpanded = viewMode === "expanded";
+
+ const { graph, nodeToObservationsMap, limitExceeded } = useMemo(() => {
+ if (isExpanded) {
+ // Expanded ignores framework metadata: the instrumented hierarchy is
+ // the source of truth, so EVERY call becomes a node — including e.g.
+ // the LLM/tool calls inside LangGraph nodes, which the aggregated
+ // path's normalization filters out. Only EVENTs stay excluded
+ // (matching buildStepData's policy for the graph views).
+ return buildExpandedGraph(
+ agentGraphData.filter(
+ (o) => o.observationType !== ObservationType.EVENT,
+ ),
+ agentGraphData,
+ );
+ }
+ return { ...buildGraphFromStepData(normalizedData), limitExceeded: false };
+ }, [normalizedData, isExpanded, agentGraphData]);
+
+ const graphNodeIds = useMemo(
+ () => new Set(graph.nodes.map((node) => node.id)),
+ [graph.nodes],
+ );
// Unfiltered observation lookup for the parent-walk fallback below (child
// observations without a langgraph node are absent from normalizedData).
@@ -83,16 +114,24 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({
[agentGraphData],
);
- // observation id → its node name, so the playhead's active-observation set can
- // be projected onto graph nodes (nodeToObservationsMap only holds the top-most
- // of a same-name chain, so build the reverse map from the full data instead).
+ // observation id → its node id, so the playhead's active-observation set can
+ // be projected onto graph nodes. Aggregated: id → node NAME from the full
+ // data (nodeToObservationsMap only holds the top-most of a same-name chain).
+ // Expanded: node ids ARE observation ids — the projection is identity over
+ // the unfiltered data (ids that aren't graph nodes simply never match).
const observationToNodeName = useMemo(() => {
const map = new Map<string, string>();
- for (const o of normalizedData) {
- if (o.id && o.node) map.set(o.id, o.node);
+ if (isExpanded) {
+ for (const o of agentGraphData) {
+ if (o.id) map.set(o.id, o.id);
+ }
+ } else {
+ for (const o of normalizedData) {
+ if (o.id && o.node) map.set(o.id, o.node);
+ }
}
return map;
- }, [normalizedData]);
+ }, [normalizedData, agentGraphData, isExpanded]);
const activeNodeNames = useMemo(() => {
if (!activeObservationIds || activeObservationIds.size === 0) return null;
@@ -109,6 +148,14 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({
setCurrentObservationIndices({});
}, [normalizedData]);
+ // A mode switch rebuilds the graph in a different node-id space, so the
+ // selection must re-resolve. Clear any stale click-echo entry first (runs
+ // before the sync effect below — declaration order) or it would swallow
+ // that re-sync and silently drop the highlight.
+ useEffect(() => {
+ clickWroteObservationIdRef.current = undefined;
+ }, [viewMode]);
+
useEffect(() => {
// Skip genuine echoes of an in-canvas click (the click already selected the
// node); a stale entry from a no-op write is cleared and IGNORED when a
@@ -136,37 +183,52 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({
}
}
- // Fallback for observations not in the cycling map: nested/repeated
- // same-name observations (only the top-most of a same-name chain is
- // registered) map to their own node; descendants WITHOUT a node of their
- // own (e.g. LangGraph child spans, which are filtered out of
- // normalizedData) resolve by walking UP the parent chain in the unfiltered
- // data until an ancestor carries one — so selecting any descendant keeps
- // its enclosing node focused instead of clearing the selection.
+ // Fallback for observations not in the cycling map. Expanded modes: node
+ // ids are observation ids, so walk UP the parent chain to the nearest
+ // ancestor that has a node in the graph (covers observations filtered out
+ // of the graph, e.g. EVENTs and LangGraph child spans). Aggregated:
+ // nested/repeated same-name observations (only the top-most of a
+ // same-name chain is registered) map to their own node; descendants
+ // WITHOUT a node of their own resolve by walking UP the parent chain in
+ // the unfiltered data until an ancestor carries one — so selecting any
+ // descendant keeps its enclosing node focused instead of clearing the
+ // selection.
if (!foundNodeName && currentObservationId) {
- const own = normalizedData.find((o) => o.id === currentObservationId);
- if (own?.node) {
- foundNodeName = own.node;
- } else {
+ if (isExpanded) {
const seen = new Set<string>();
let cursor = agentGraphById.get(currentObservationId);
while (cursor && !seen.has(cursor.id)) {
seen.add(cursor.id);
- if (cursor.node) {
- foundNodeName = cursor.node;
+ if (graphNodeIds.has(cursor.id)) {
+ foundNodeName = cursor.id;
break;
}
cursor = cursor.parentObservationId
? agentGraphById.get(cursor.parentObservationId)
: undefined;
}
+ } else {
+ const own = normalizedData.find((o) => o.id === currentObservationId);
+ if (own?.node) {
+ foundNodeName = own.node;
+ } else {
+ const seen = new Set<string>();
+ let cursor = agentGraphById.get(currentObservationId);
+ while (cursor && !seen.has(cursor.id)) {
+ seen.add(cursor.id);
+ if (cursor.node) {
+ foundNodeName = cursor.node;
+ break;
+ }
+ cursor = cursor.parentObservationId
+ ? agentGraphById.get(cursor.parentObservationId)
+ : undefined;
+ }
+ }
}
}
- if (
- foundNodeName &&
- graph.nodes.some((node) => node.id === foundNodeName)
- ) {
+ if (foundNodeName && graphNodeIds.has(foundNodeName)) {
setSelectedNodeName(foundNodeName);
// Only sync the cycling index when the id was actually found in the
// cycling map — fallback-resolved observations must not rewind the
@@ -187,7 +249,8 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({
}, [
currentObservationId,
agentGraphById,
- graph.nodes,
+ graphNodeIds,
+ isExpanded,
nodeToObservationsMap,
normalizedData,
]);
@@ -248,15 +311,32 @@ export const TraceGraphView: React.FC<TraceGraphViewProps> = ({
);
return (
- <div className="h-full w-full">
- <ElkGraphRenderer
- graph={graph}
- selectedNodeName={selectedNodeName}
- onCanvasNodeNameChange={onCanvasNodeNameChange}
- nodeToObservationsMap={nodeToObservationsMap}
- currentObservationIndices={currentObservationIndices}
- activeNodeNames={activeNodeNames}
- />
+ <div className="@container/graphcanvas relative h-full w-full">
+ {limitExceeded ? (
+ <div className="text-muted-foreground flex h-full items-center justify-center px-4 text-center text-sm">
+ This trace branches too widely for the expanded graph — use the
+ aggregated view.
+ </div>
+ ) : (
+ <ElkGraphRenderer
+ graph={graph}
+ selectedNodeName={selectedNodeName}
+ onCanvasNodeNameChange={onCanvasNodeNameChange}
+ nodeToObservationsMap={nodeToObservationsMap}
+ currentObservationIndices={currentObservationIndices}
+ activeNodeNames={activeNodeNames}
+ // Expanded runs are long chains — left→right reads like a
+ // timeline and fits the wide graph panel far better than top-down.
+ layoutDirection={isExpanded ? "RIGHT" : "DOWN"}
+ />
+ )}
+ {onViewModeChange && (
+ // Overlaid sibling of the canvas (top-left, opposite the zoom stack)
+ // so canvas clicks/gestures underneath are untouched.
+ <div className="absolute top-2 left-2 z-10">
+ <GraphViewModeSwitch value={viewMode} onChange={onViewModeChange} />
+ </div>
+ )}
</div>
);
};
diff --git a/web/src/features/trace-graph-view/layout/elkLayout.ts b/web/src/features/trace-graph-view/layout/elkLayout.ts
index 13d89f1de3..3c237a4f18 100644
--- a/web/src/features/trace-graph-view/layout/elkLayout.ts
+++ b/web/src/features/trace-graph-view/layout/elkLayout.ts
@@ -1,6 +1,12 @@
import type { ELK, ElkNode } from "elkjs";
-import { type GraphCanvasData } from "../types";
+import {
+ type GraphCanvasData,
+ LANGFUSE_START_NODE_NAME,
+ LANGFUSE_END_NODE_NAME,
+ LANGGRAPH_START_NODE_NAME,
+ LANGGRAPH_END_NODE_NAME,
+} from "../types";
import { measureNode } from "./measureNode";
export interface PositionedNode {
@@ -27,14 +33,17 @@ export interface GraphLayout {
height: number;
}
+export type GraphLayoutDirection = "DOWN" | "RIGHT";
+
/**
- * ELK "layered" options for a top-down, deterministic DAG. Orthogonal routing +
- * merged edges keep dense traces from turning into a hairball.
+ * ELK "layered" options for a deterministic DAG. Orthogonal routing + merged
+ * edges keep dense traces from turning into a hairball. Direction is
+ * per-mode: aggregated graphs read top-down; expanded "as it ran" chains are
+ * long and thin, so they lay out left→right like a timeline.
* @see https://eclipse.dev/elk/reference/algorithms/org-eclipse-elk-layered.html
*/
const LAYOUT_OPTIONS: Record<string, string> = {
"elk.algorithm": "org.eclipse.elk.layered",
- "elk.direction": "DOWN",
"elk.edgeRouting": "ORTHOGONAL",
"elk.layered.mergeEdges": "true",
"elk.layered.spacing.nodeNodeBetweenLayers": "52",
@@ -44,17 +53,51 @@ const LAYOUT_OPTIONS: Record<string, string> = {
"elk.layered.cycleBreaking.strategy": "DEPTH_FIRST",
};
+/**
+ * MULTI_EDGE wrapping recurses per layer inside elkjs and a fully sequential
+ * expanded trace makes one layer per observation: measured, the recursion
+ * stack-overflows around ~1200 layers on small-stack browsers (Firefox) and
+ * costs tens of seconds well before that. Above this bound the graph keeps
+ * the RIGHT direction but skips wrapping (a plain ribbon lays out in
+ * milliseconds at any size).
+ */
+const MAX_WRAP_NODES = 300;
+
/** Map our {nodes, edges} into an ELK graph, deduping edges and dropping self-loops. */
function buildElkGraph(
graph: GraphCanvasData,
counterReserve: Map<string, number>,
+ direction: GraphLayoutDirection,
): ElkNode {
const children = graph.nodes.map((node) => {
const { width, height } = measureNode(
node,
counterReserve.get(node.id) ?? 0,
);
- return { id: node.id, width, height };
+ // The synthetic anchors mean "the run starts/ends here" — pin them to
+ // the first/last layer so edge shape can't strand them mid-graph (e.g.
+ // a root span's `root→__end__` edge would otherwise place __end__ in
+ // the second column while the run continues to the right of it).
+ const constraint =
+ node.id === LANGFUSE_START_NODE_NAME ||
+ node.id === LANGGRAPH_START_NODE_NAME
+ ? "FIRST"
+ : node.id === LANGFUSE_END_NODE_NAME ||
+ node.id === LANGGRAPH_END_NODE_NAME
+ ? "LAST"
+ : null;
+ return {
+ id: node.id,
+ width,
+ height,
+ ...(constraint
+ ? {
+ layoutOptions: {
+ "elk.layered.layering.layerConstraint": constraint,
+ },
+ }
+ : {}),
+ };
});
const seen = new Set<string>();
@@ -76,7 +119,20 @@ function buildElkGraph(
return {
id: "root",
- layoutOptions: LAYOUT_OPTIONS,
+ layoutOptions: {
+ ...LAYOUT_OPTIONS,
+ "elk.direction": direction,
+ // Long expanded chains: let ELK wrap the layer sequence into multiple
+ // rows near the panel's aspect ratio, so fit-zoom stays readable
+ // instead of shrinking a 1×N ribbon to nothing (bounded — see
+ // MAX_WRAP_NODES).
+ ...(direction === "RIGHT" && graph.nodes.length <= MAX_WRAP_NODES
+ ? {
+ "elk.layered.wrapping.strategy": "MULTI_EDGE",
+ "elk.aspectRatio": "1.6",
+ }
+ : {}),
+ },
children,
edges,
};
@@ -127,6 +183,7 @@ function buildCounterReserve(
export async function computeGraphLayout(
graph: GraphCanvasData,
nodeToObservationsMap: Record<string, string[]> = {},
+ direction: GraphLayoutDirection = "DOWN",
): Promise<GraphLayout> {
if (graph.nodes.length === 0) {
return { nodes: [], edges: [], width: 0, height: 0 };
@@ -134,7 +191,9 @@ export async function computeGraphLayout(
const elk = await getElk();
const counterReserve = buildCounterReserve(nodeToObservationsMap);
- const result = await elk.layout(buildElkGraph(graph, counterReserve));
+ const result = await elk.layout(
+ buildElkGraph(graph, counterReserve, direction),
+ );
const nodes: PositionedNode[] = (result.children ?? []).map((child) => ({
id: child.id,
diff --git a/web/src/features/trace-graph-view/types.ts b/web/src/features/trace-graph-view/types.ts
index 8f1cb3d5d0..b170b90371 100644
--- a/web/src/features/trace-graph-view/types.ts
+++ b/web/src/features/trace-graph-view/types.ts
@@ -6,6 +6,18 @@ export type GraphNodeData = {
type: string;
};
+/**
+ * How the graph is built from the trace's observations:
+ * - "aggregated": repeated step names collapse into one node (loops render as
+ * cycles) — the original view, good for overall shape.
+ * - "expanded": one node per observation — the run "as it ran". Edges come
+ * from the instrumented hierarchy (parent → first child) plus
+ * happened-before ordering between siblings (fork/join from actual
+ * timing), so loops unroll into an acyclic DAG.
+ */
+export const GRAPH_VIEW_MODES = ["aggregated", "expanded"] as const;
+export type GraphViewMode = (typeof GRAPH_VIEW_MODES)[number];
+
export type GraphCanvasData = {
nodes: GraphNodeData[];
edges: { from: string; to: string }[];