Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

improvement(frontend): condensed dependency graph representation (#10766)

Dylan Madisetti94221e41e905
diff --git a/frontend/src/components/dependency-graph/__tests__/elements.test.ts b/frontend/src/components/dependency-graph/__tests__/elements.test.ts
new file mode 100644
index 0000000000..75f6e14383
--- /dev/null
+++ b/frontend/src/components/dependency-graph/__tests__/elements.test.ts
@@ -0,0 +1,151 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { describe, expect, it } from "vitest";
+import type { CellId } from "@/core/cells/ids";
+import type { Variable, VariableName, Variables } from "@/core/variables/types";
+import { createCellRuntimeState } from "@/core/cells/types";
+import {
+ collapsedNodeWidth,
+ computeDefsByCell,
+ isStateFlowVariable,
+ reusableCellIds,
+ wrapDefs,
+} from "../elements";
+
+const names = (list: string[]) => list as VariableName[];
+
+function variable(
+ partial: Omit<Partial<Variable>, "name"> & { name: string },
+): Variable {
+ return {
+ declaredBy: [],
+ usedBy: [],
+ ...partial,
+ name: partial.name as VariableName,
+ };
+}
+
+describe("collapsedNodeWidth", () => {
+ it("clamps short labels to the minimum width", () => {
+ expect(collapsedNodeWidth("")).toBe(90);
+ expect(collapsedNodeWidth("x")).toBe(90);
+ });
+
+ it("clamps long labels to the maximum width", () => {
+ expect(collapsedNodeWidth("a".repeat(100))).toBe(240);
+ });
+
+ it("scales with label length between the bounds", () => {
+ const width = collapsedNodeWidth("df, summary");
+ expect(width).toBeGreaterThan(90);
+ expect(width).toBeLessThan(240);
+ });
+});
+
+describe("isStateFlowVariable", () => {
+ it("flags State and SetFunctor (from mo.state)", () => {
+ expect(
+ isStateFlowVariable(variable({ name: "g", dataType: "State" })),
+ ).toBe(true);
+ expect(
+ isStateFlowVariable(variable({ name: "s", dataType: "SetFunctor" })),
+ ).toBe(true);
+ });
+
+ it("does not flag UI elements or plain values", () => {
+ // UIElement is frontend-driven / immutable during a run — not a state flow.
+ expect(
+ isStateFlowVariable(variable({ name: "sl", dataType: "slider" })),
+ ).toBe(false);
+ expect(isStateFlowVariable(variable({ name: "n", dataType: "int" }))).toBe(
+ false,
+ );
+ expect(isStateFlowVariable(variable({ name: "u", dataType: null }))).toBe(
+ false,
+ );
+ expect(isStateFlowVariable(variable({ name: "u2" }))).toBe(false);
+ });
+});
+
+describe("wrapDefs", () => {
+ it("packs short names to the 12-char minimum budget", () => {
+ expect(
+ wrapDefs(names(["np", "math", "time", "io", "numpy", "pandas"])),
+ ).toEqual(["np, math", "time, io", "numpy", "pandas"]);
+ });
+
+ it("gives a long name its own line, then packs the rest to its width", () => {
+ expect(
+ wrapDefs(
+ names([
+ "very_very_very_long_variable_name",
+ "short_var",
+ "shr_v",
+ "io",
+ "numpy",
+ "wev",
+ ]),
+ ),
+ ).toEqual([
+ "very_very_very_long_variable_name",
+ "short_var, shr_v, io, numpy, wev",
+ ]);
+ });
+
+ it("returns an empty list for no defs", () => {
+ expect(wrapDefs(names([]))).toEqual([]);
+ });
+
+ it("caps the budget so packed lines fit the max node width", () => {
+ // One name far beyond the width cap must not widen every other line.
+ const huge = "x".repeat(60);
+ const lines = wrapDefs(
+ names([huge, "aaaaaaaaaa", "bbbbbbbbbb", "cccccccccc"]),
+ );
+ expect(lines[0]).toBe(huge);
+ for (const line of lines.slice(1)) {
+ expect(line.length).toBeLessThanOrEqual(33);
+ }
+ });
+});
+
+describe("computeDefsByCell", () => {
+ it("maps each cell to the variables it declares", () => {
+ const c1 = "c1" as CellId;
+ const c2 = "c2" as CellId;
+ const a = "a" as VariableName;
+ const b = "b" as VariableName;
+ const c = "c" as VariableName;
+ const variables: Variables = {
+ [a]: variable({ name: a, declaredBy: [c1], usedBy: [c2] }),
+ [b]: variable({ name: b, declaredBy: [c1] }),
+ [c]: variable({ name: c, declaredBy: [c2] }),
+ };
+ const defs = computeDefsByCell(variables);
+ expect(defs.get(c1)).toEqual([a, b]);
+ expect(defs.get(c2)).toEqual([c]);
+ });
+
+ it("returns an empty map when there are no variables", () => {
+ expect(computeDefsByCell({}).size).toBe(0);
+ });
+});
+
+describe("reusableCellIds", () => {
+ const c1 = "c1" as CellId;
+ const c2 = "c2" as CellId;
+ const c3 = "c3" as CellId;
+
+ it("collects cells whose serialization hint is valid, case-insensitively", () => {
+ const runtime = {
+ [c1]: createCellRuntimeState({ serialization: "Valid" }),
+ [c2]: createCellRuntimeState({ serialization: "Unparsable" }),
+ [c3]: createCellRuntimeState(),
+ };
+ expect(reusableCellIds([c1, c2, c3], runtime)).toEqual(new Set([c1]));
+ });
+
+ it("ignores cells with no runtime entry", () => {
+ expect(reusableCellIds([c1], {})).toEqual(new Set());
+ });
+});
diff --git a/frontend/src/components/dependency-graph/custom-edge.tsx b/frontend/src/components/dependency-graph/custom-edge.tsx
new file mode 100644
index 0000000000..ca67ffe583
--- /dev/null
+++ b/frontend/src/components/dependency-graph/custom-edge.tsx
@@ -0,0 +1,68 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { memo } from "react";
+import { BaseEdge, type EdgeProps, getBezierPath } from "reactflow";
+import {
+ DEFAULT_EDGE_COLOR,
+ type DependencyEdgeData,
+ STATE_FLOW_EDGE_COLOR,
+} from "./elements";
+
+// Gentle curvature keeps edges reading as clean directional splines
+// (TensorBoard-style) rather than hard right-angle elbows.
+const EDGE_CURVATURE = 0.35;
+
+/**
+ * A dependency edge, drawn as a smooth curved spline that flows out of the
+ * source handle and into the target — the TensorBoard graph aesthetic. Mutable
+ * `State`/setter flows get a distinct dashed accent style.
+ */
+export const DependencyEdge = memo((props: EdgeProps<DependencyEdgeData>) => {
+ const {
+ sourceX,
+ sourceY,
+ targetX,
+ targetY,
+ sourcePosition,
+ targetPosition,
+ markerEnd,
+ data,
+ selected,
+ } = props;
+
+ const [path] = getBezierPath({
+ sourceX,
+ sourceY,
+ targetX,
+ targetY,
+ sourcePosition,
+ targetPosition,
+ curvature: EDGE_CURVATURE,
+ });
+
+ const isStateFlow = data?.isStateFlow ?? false;
+ // The inline stroke replaces React Flow's stylesheet-driven edge colors, so
+ // the selected state must be restyled here too or it becomes invisible.
+ const stroke = selected
+ ? "var(--primary)"
+ : isStateFlow
+ ? STATE_FLOW_EDGE_COLOR
+ : DEFAULT_EDGE_COLOR;
+
+ return (
+ <BaseEdge
+ path={path}
+ markerEnd={markerEnd}
+ style={{
+ strokeWidth: selected ? 2.5 : isStateFlow ? 2 : 1.5,
+ stroke,
+ strokeDasharray: isStateFlow ? "5 3" : undefined,
+ }}
+ />
+ );
+});
+DependencyEdge.displayName = "DependencyEdge";
+
+export const edgeTypes = {
+ dependency: DependencyEdge,
+};
diff --git a/frontend/src/components/dependency-graph/custom-node.tsx b/frontend/src/components/dependency-graph/custom-node.tsx
index 399a174b79..9359df80c3 100644
--- a/frontend/src/components/dependency-graph/custom-node.tsx
+++ b/frontend/src/components/dependency-graph/custom-node.tsx
@@ -2,25 +2,20 @@
import { useAtomValue } from "jotai";
import React, { memo, use } from "react";
-import { Handle, Position, useStore } from "reactflow";
+import { Handle, Position } from "reactflow";
import { TinyCode } from "@/components/editor/cell/TinyCode";
import { useCellIds } from "@/core/cells/cells";
-import { displayCellName } from "@/core/cells/names";
+import { displayCellName, isInternalCellName } from "@/core/cells/names";
import { cn } from "@/utils/cn";
import {
type CustomNodeProps,
- getNodeHeight,
INPUTS_HANDLE_ID,
+ nodeBodyLines,
+ nodeDimensions,
OUTPUTS_HANDLE_ID,
} from "./elements";
import type { LayoutDirection } from "./types";
-
-function getWidth(canvasWidth: number) {
- const minWidth = 100;
- const maxWidth = 400;
- const padding = 50;
- return Math.min(Math.max(canvasWidth - padding * 2, minWidth), maxWidth);
-}
+import { extractCellPreview } from "./utils/cell-preview";
export const EdgeMarkerContext = React.createContext<LayoutDirection>("LR");
@@ -36,13 +31,19 @@ export const CustomNode = memo((props: CustomNodeProps) => {
const { data, selected } = props; // must match the equality check
const cell = useAtomValue(data.atom);
const cellIndex = useCellIds().inOrderIds.indexOf(cell.id);
- const nonSelectedColor = "var(--gray-3)";
- const selectedColor = "var(--gray-9)";
- const color = selected ? selectedColor : nonSelectedColor;
- const reactFlowWidth = useStore(({ width }) => width);
+ const handleColor = selected ? "var(--gray-9)" : "var(--gray-3)";
const edgeMarkers = use(EdgeMarkerContext);
- const linesOfCode = cell.code.split("\n").length;
+ const { width, height } = nodeDimensions(data);
+ const isNamed = !isInternalCellName(cell.name);
+ const name = displayCellName(cell.name, cellIndex);
+ // Only collapsed nodes without defs render the preview; skip the parse
+ // otherwise, since it scales with notebook size.
+ const preview =
+ !data.expanded && data.defs.length === 0
+ ? extractCellPreview(cell.code).text
+ : undefined;
+
return (
<div>
<Handle
@@ -50,43 +51,70 @@ export const CustomNode = memo((props: CustomNodeProps) => {
id={INPUTS_HANDLE_ID}
data-testid="input-one"
position={edgeMarkers === "LR" ? Position.Left : Position.Top}
- style={{ background: color }}
+ style={{ background: handleColor }}
/>
<Handle
type="source"
id={INPUTS_HANDLE_ID}
data-testid="input-two"
position={edgeMarkers === "LR" ? Position.Left : Position.Top}
- style={{ background: color }}
+ style={{ background: handleColor }}
/>
<div
className={cn(
"flex flex-col bg-card border border-input/50 rounded-md mx-[2px] overflow-hidden",
selected && "border-primary",
)}
- style={{
- height: getNodeHeight(linesOfCode),
- width: data.forceWidth || getWidth(reactFlowWidth),
- }}
+ style={{ height, width }}
>
- <div className="text-muted-foreground font-semibold text-xs py-1 px-2 bg-muted border-b">
- {displayCellName(cell.name, cellIndex)}
+ <div className="text-xs py-0.5 px-2 bg-muted border-b flex items-center justify-between gap-2 shrink-0">
+ <span
+ className={cn(
+ "truncate",
+ isNamed
+ ? "font-semibold text-foreground"
+ : "text-muted-foreground/70",
+ )}
+ >
+ {name}
+ </span>
</div>
- <TinyCode code={cell.code} />
+ {data.expanded ? (
+ <TinyCode code={cell.code} />
+ ) : (
+ <div className="flex-1 min-h-0 flex flex-col justify-center px-2 py-1 font-mono text-xs leading-4">
+ {data.defs.length > 0 ? (
+ // Defs wrapped into comma-separated lines — taller, not wider.
+ nodeBodyLines(data).map((line) => (
+ <span
+ key={line}
+ className="text-foreground truncate"
+ title={line}
+ >
+ {line}
+ </span>
+ ))
+ ) : (
+ <span className="truncate italic text-muted-foreground/60">
+ {preview ?? "empty"}
+ </span>
+ )}
+ </div>
+ )}
</div>
<Handle
type="source"
id={OUTPUTS_HANDLE_ID}
data-testid="output-one"
position={edgeMarkers === "LR" ? Position.Right : Position.Bottom}
- style={{ background: color }}
+ style={{ background: handleColor }}
/>
<Handle
type="target"
id={OUTPUTS_HANDLE_ID}
data-testid="output-two"
position={edgeMarkers === "LR" ? Position.Right : Position.Bottom}
- style={{ background: color }}
+ style={{ background: handleColor }}
/>
</div>
);
diff --git a/frontend/src/components/dependency-graph/dependency-graph-tree.tsx b/frontend/src/components/dependency-graph/dependency-graph-tree.tsx
index 8e930817a4..eaa313723f 100644
--- a/frontend/src/components/dependency-graph/dependency-graph-tree.tsx
+++ b/frontend/src/components/dependency-graph/dependency-graph-tree.tsx
@@ -1,8 +1,13 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import type { Atom } from "jotai";
+import { type Atom, atom, useAtomValue } from "jotai";
import { MapPinIcon } from "lucide-react";
-import React, { type PropsWithChildren, useEffect, useState } from "react";
+import React, {
+ type PropsWithChildren,
+ useEffect,
+ useMemo,
+ useState,
+} from "react";
import useEvent from "react-use-event-hook";
import ReactFlow, {
Background,
@@ -15,6 +20,7 @@ import ReactFlow, {
useNodesState,
useReactFlow,
} from "reactflow";
+import { edgeTypes } from "@/components/dependency-graph/custom-edge";
import {
EdgeMarkerContext,
nodeTypes,
@@ -25,11 +31,16 @@ import type { CellData } from "@/core/cells/types";
import { store } from "@/core/state/jotai";
import type { Variables } from "@/core/variables/types";
import { Events } from "@/utils/events";
-import { scrollAndHighlightCell } from "../editor/links/cell-link";
import { Tooltip } from "../ui/tooltip";
-import { type NodeData, TreeElementsBuilder } from "./elements";
+import {
+ computeDefsByCell,
+ type NodeData,
+ nodeDimensions,
+ TreeElementsBuilder,
+} from "./elements";
import { GraphSelectionPanel } from "./panels";
import type { GraphSelection, GraphSettings, LayoutDirection } from "./types";
+import { extractCellPreview } from "./utils/cell-preview";
import { layoutElements } from "./utils/layout";
import { useFitToViewOnDimensionChange } from "./utils/useFitToViewOnDimensionChange";
@@ -43,6 +54,24 @@ interface Props {
const elementsBuilder = new TreeElementsBuilder();
+/**
+ * Apply the current expand/collapse selection to freshly-built nodes, resizing
+ * each so the layout engine and the DOM agree on node dimensions.
+ */
+function withExpansion(
+ nodes: Node<NodeData>[],
+ expandedIds: Set<CellId>,
+): Node<NodeData>[] {
+ return nodes.map((node) => {
+ const data: NodeData = {
+ ...node.data,
+ expanded: expandedIds.has(node.id as CellId),
+ };
+ const { width, height } = nodeDimensions(data);
+ return { ...node, data, width, height };
+ });
+}
+
export const DependencyGraphTree: React.FC<PropsWithChildren<Props>> = ({
cellIds,
variables,
@@ -51,22 +80,23 @@ export const DependencyGraphTree: React.FC<PropsWithChildren<Props>> = ({
layoutDirection,
settings,
}) => {
+ // Cells whose node is expanded to show its full code (toggled by double-click).
+ const [expandedIds, setExpandedIds] = useState<Set<CellId>>(() => new Set());
+
// oxlint-disable-next-line react/hook-use-state
const [initial] = useState(() => {
- let elements = elementsBuilder.createElements(
+ const elements = elementsBuilder.createElements(
cellIds,
cellAtoms,
variables,
settings.hidePureMarkdown,
settings.hideReusableFunctions,
);
- elements = layoutElements({
- nodes: elements.nodes,
+ return layoutElements({
+ nodes: withExpansion(elements.nodes, expandedIds),
edges: elements.edges,
direction: layoutDirection,
});
-
- return elements;
// Only run once
});
@@ -82,22 +112,68 @@ export const DependencyGraphTree: React.FC<PropsWithChildren<Props>> = ({
edges: elements.edges,
direction: layoutDirection,
});
- setNodes(result.nodes);
- setEdges(result.edges);
+ // Rebuilt elements are fresh objects; carry selection over so a
+ // re-layout (e.g. toggling expansion) doesn't silently clear it while
+ // the selection panel still targets the element.
+ setNodes((prev) => {
+ const selected = new Set(
+ prev.filter((node) => node.selected).map((node) => node.id),
+ );
+ return result.nodes.map((node) =>
+ selected.has(node.id) ? { ...node, selected: true } : node,
+ );
+ });
+ setEdges((prev) => {
+ const selected = new Set(
+ prev.filter((edge) => edge.selected).map((edge) => edge.id),
+ );
+ return result.edges.map((edge) =>
+ selected.has(edge.id) ? { ...edge, selected: true } : edge,
+ );
+ });
},
);
- // If the cellIds change, update the nodes.
+ // Node sizes depend on live cell code: the line count when expanded, or the
+ // preview when a cell defines nothing. The cell atoms keep their identity
+ // across edits, so the rebuild effect below can't see code changes through
+ // its deps — subscribe to the size-relevant inputs explicitly.
+ const defsByCell = useMemo(() => computeDefsByCell(variables), [variables]);
+ const sizeSignature = useAtomValue(
+ useMemo(
+ () =>
+ atom((get) =>
+ cellIds
+ .map((cellId, index) => {
+ const code = get(cellAtoms[index]).code;
+ if (expandedIds.has(cellId)) {
+ return `e${code.trim().split("\n").length}`;
+ }
+ if ((defsByCell.get(cellId) ?? []).length > 0) {
+ // Collapsed nodes with defs size off the defs, not the code.
+ return "d";
+ }
+ return `p${extractCellPreview(code).text?.length ?? 0}`;
+ })
+ .join(),
+ ),
+ [cellIds, cellAtoms, expandedIds, defsByCell],
+ ),
+ );
+
+ // Rebuild + re-layout when the graph inputs or the expand/collapse set change.
useEffect(() => {
- syncChanges(
- elementsBuilder.createElements(
- cellIds,
- cellAtoms,
- variables,
- settings.hidePureMarkdown,
- settings.hideReusableFunctions,
- ),
+ const elements = elementsBuilder.createElements(
+ cellIds,
+ cellAtoms,
+ variables,
+ settings.hidePureMarkdown,
+ settings.hideReusableFunctions,
);
+ syncChanges({
+ nodes: withExpansion(elements.nodes, expandedIds),
+ edges: elements.edges,
+ });
}, [
cellIds,
variables,
@@ -105,6 +181,8 @@ export const DependencyGraphTree: React.FC<PropsWithChildren<Props>> = ({
syncChanges,
settings.hidePureMarkdown,
settings.hideReusableFunctions,
+ expandedIds,
+ sizeSignature,
]);
const [selection, setSelection] = useState<GraphSelection>();
@@ -120,6 +198,7 @@ export const DependencyGraphTree: React.FC<PropsWithChildren<Props>> = ({
nodes={nodes}
edges={edges}
nodeTypes={nodeTypes}
+ edgeTypes={edgeTypes}
minZoom={0.2}
fitViewOptions={{
minZoom: 0.5,
@@ -137,7 +216,17 @@ export const DependencyGraphTree: React.FC<PropsWithChildren<Props>> = ({
});
}}
onNodeDoubleClick={(_event, node) => {
- scrollAndHighlightCell(node.id as CellId, "focus");
+ // Expand/collapse the node to reveal its full code in place.
+ const id = node.id as CellId;
+ setExpandedIds((prev) => {
+ const next = new Set(prev);
+ if (next.has(id)) {
+ next.delete(id);
+ } else {
+ next.add(id);
+ }
+ return next;
+ });
}}
fitView={true}
onNodesChange={onNodesChange}
diff --git a/frontend/src/components/dependency-graph/elements.ts b/frontend/src/components/dependency-graph/elements.ts
index bd8e10cf1f..fda8261f9e 100644
--- a/frontend/src/components/dependency-graph/elements.ts
+++ b/frontend/src/components/dependency-graph/elements.ts
@@ -4,26 +4,177 @@ import type { Atom } from "jotai";
import { type Edge, MarkerType, type Node, type NodeProps } from "reactflow";
import { getNotebook } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
-import type { CellData } from "@/core/cells/types";
+import type { CellData, CellRuntimeState } from "@/core/cells/types";
import { store } from "@/core/state/jotai";
-import type { Variables } from "@/core/variables/types";
+import type { Variable, VariableName, Variables } from "@/core/variables/types";
import { Arrays } from "@/utils/arrays";
+import { extractCellPreview } from "./utils/cell-preview";
+
+/** The edge type registered for dependency edges (see `custom-edge.tsx`). */
+export const DEPENDENCY_EDGE_TYPE = "dependency";
+
+// Stroke/marker colors shared by the dependency edge and its arrow marker.
+export const STATE_FLOW_EDGE_COLOR = "var(--amber-10)";
+export const DEFAULT_EDGE_COLOR = "var(--gray-8)";
+
+export interface DependencyEdgeData {
+ /** Variables carried across this edge. */
+ variables: VariableName[];
+ /** True when any carried variable is a mutable `State`/`SetFunctor` flow. */
+ isStateFlow: boolean;
+}
+
+// A `State`/`SetFunctor` (from `mo.state`) is mutable mid-run, so it is drawn
+// distinctly. `UIElement` is intentionally excluded: it is frontend-driven and
+// immutable during a run.
+const STATE_DATATYPES = new Set(["State", "SetFunctor"]);
+
+export function isStateFlowVariable(variable: Variable): boolean {
+ return variable.dataType != null && STATE_DATATYPES.has(variable.dataType);
+}
export interface NodeData {
atom: Atom<CellData>;
- forceWidth?: number;
+ /** Variables this cell defines — the node's primary identity when collapsed. */
+ defs: VariableName[];
+ /** When true the node renders its full code instead of the compact ref list. */
+ expanded?: boolean;
}
export type CustomNodeProps = NodeProps<NodeData>;
+const LINE_HEIGHT = 11; // matches TinyCode.css
+
export function getNodeHeight(linesOfCode: number) {
- const LINE_HEIGHT = 11; // matches TinyCode.css
return Math.min(linesOfCode * LINE_HEIGHT + 35, 200);
}
+// Compact-node sizing. A collapsed node wraps its defined variables into
+// comma-separated lines at a character budget, so it grows taller rather than
+// wider; the same budget drives the estimated width so dagre and the DOM agree.
+export const NODE_HEADER_HEIGHT = 22;
+const DEF_LINE_HEIGHT = 16;
+const BODY_V_PADDING = 10;
+const EXPANDED_NODE_WIDTH = 300;
+const CHAR_WIDTH = 6.5; // text-xs monospace-ish
+const NODE_H_PADDING = 22;
+const MIN_NODE_WIDTH = 90;
+const MAX_NODE_WIDTH = 240;
+// Wrap defs to the longest single name, but never narrower than this — short
+// names pack several per line, a long one gets a line to itself.
+const WRAP_MIN_CHARS = 12;
+// ... and never wider than fits MAX_NODE_WIDTH, or packed lines would be
+// clipped by the width clamp. A single name over this budget still gets its
+// own line; the renderer truncates it with an ellipsis and a title.
+const WRAP_MAX_CHARS = Math.floor(
+ (MAX_NODE_WIDTH - NODE_H_PADDING) / CHAR_WIDTH,
+);
+
+export function collapsedNodeWidth(label: string): number {
+ const raw = label.length * CHAR_WIDTH + NODE_H_PADDING;
+ return Math.min(Math.max(raw, MIN_NODE_WIDTH), MAX_NODE_WIDTH);
+}
+
+/** The per-line character budget used to wrap a node's defs. */
+function defsWrapBudget(defs: VariableName[]): number {
+ const longest = defs.reduce(
+ (max, def) => Math.max(max, def.length),
+ WRAP_MIN_CHARS,
+ );
+ return Math.min(longest, WRAP_MAX_CHARS);
+}
+
+/**
+ * Greedily pack `defs` into comma-separated lines, each no wider than the
+ * budget (the longest name, or `WRAP_MIN_CHARS`). No trailing commas.
+ */
+export function wrapDefs(defs: VariableName[]): string[] {
+ const budget = defsWrapBudget(defs);
+ const lines: string[] = [];
+ let current = "";
+ for (const def of defs) {
+ if (current === "") {
+ current = def;
+ } else if (current.length + 2 + def.length <= budget) {
+ current = `${current}, ${def}`;
+ } else {
+ lines.push(current);
+ current = def;
+ }
+ }
+ if (current !== "") {
+ lines.push(current);
+ }
+ return lines;
+}
+
+/**
+ * The lines shown in a collapsed node's body: its defs wrapped to a budget, or
+ * a single code-preview line when the cell defines nothing.
+ */
+export function nodeBodyLines(data: NodeData): string[] {
+ if (data.defs.length > 0) {
+ return wrapDefs(data.defs);
+ }
+ const preview = extractCellPreview(store.get(data.atom).code).text;
+ return preview ? [preview] : [];
+}
+
+export function nodeDimensions(data: NodeData): {
+ width: number;
+ height: number;
+} {
+ if (data.expanded) {
+ const lines = store.get(data.atom).code.trim().split("\n").length;
+ return { width: EXPANDED_NODE_WIDTH, height: getNodeHeight(lines) };
+ }
+ const lines = nodeBodyLines(data);
+ const widthChars =
+ data.defs.length > 0
+ ? defsWrapBudget(data.defs)
+ : lines.reduce((max, line) => Math.max(max, line.length), 0);
+ const bodyLines = Math.max(lines.length, 1);
+ return {
+ width: collapsedNodeWidth("x".repeat(widthChars)),
+ height: NODE_HEADER_HEIGHT + bodyLines * DEF_LINE_HEIGHT + BODY_V_PADDING,
+ };
+}
+
// The nodes must have the same handle IDs to ensure edges connect correctly
export const OUTPUTS_HANDLE_ID = "outputs";
export const INPUTS_HANDLE_ID = "inputs";
+/**
+ * Cells hidden by the reusable-functions filter: those the kernel marked as
+ * valid top-level definitions (serialization hint `Valid`).
+ */
+export function reusableCellIds(
+ cellIds: CellId[],
+ cellRuntime: Record<CellId, CellRuntimeState>,
+): Set<CellId> {
+ const reusable = new Set<CellId>();
+ for (const cellId of cellIds) {
+ if (cellRuntime[cellId]?.serialization?.toLowerCase() === "valid") {
+ reusable.add(cellId);
+ }
+ }
+ return reusable;
+}
+
+/** Map each cell to the names of the variables it declares. */
+export function computeDefsByCell(
+ variables: Variables,
+): Map<CellId, VariableName[]> {
+ const defsByCell = new Map<CellId, VariableName[]>();
+ for (const variable of Object.values(variables)) {
+ for (const cellId of variable.declaredBy) {
+ const defs = defsByCell.get(cellId) ?? [];
+ defs.push(variable.name);
+ defsByCell.set(cellId, defs);
+ }
+ }
+ return defsByCell;
+}
+
interface ElementsBuilder {
createElements: (
cellIds: CellId[],
@@ -59,16 +210,17 @@ export class VerticalElementsBuilder implements ElementsBuilder {
private createNode(
id: string,
atom: Atom<CellData>,
+ defs: VariableName[],
prevY: number,
): Node<NodeData> {
- const linesOfCode = store.get(atom).code.trim().split("\n").length;
- const height = getNodeHeight(linesOfCode);
+ const data: NodeData = { atom, defs };
+ const { width, height } = nodeDimensions(data);
return {
id: id,
- data: { atom },
- width: 250,
+ data,
+ width,
type: "custom",
- height: height,
+ height,
position: { x: 0, y: prevY + 20 },
};
}
@@ -83,8 +235,14 @@ export class VerticalElementsBuilder implements ElementsBuilder {
let prevY = 0;
const nodes: Node<NodeData>[] = [];
const edges: Edge[] = [];
+ const defsByCell = computeDefsByCell(variables);
for (const [cellId, cellAtom] of Arrays.zip(cellIds, cellAtoms)) {
- const node = this.createNode(cellId, cellAtom, prevY);
+ const node = this.createNode(
+ cellId,
+ cellAtom,
+ defsByCell.get(cellId) ?? [],
+ prevY,
+ );
nodes.push(node);
prevY = node.position.y + (node.height || 0);
}
@@ -110,16 +268,24 @@ export class VerticalElementsBuilder implements ElementsBuilder {
}
}
+interface AggregatedEdge {
+ source: CellId;
+ target: CellId;
+ variables: VariableName[];
+ isStateFlow: boolean;
+}
+
export class TreeElementsBuilder implements ElementsBuilder {
- private createEdge(source: CellId, target: CellId): Edge {
+ private createEdge(edge: AggregatedEdge): Edge<DependencyEdgeData> {
+ const { source, target, variables, isStateFlow } = edge;
return {
- animated: true,
+ type: DEPENDENCY_EDGE_TYPE,
markerEnd: {
type: MarkerType.ArrowClosed,
+ color: isStateFlow ? STATE_FLOW_EDGE_COLOR : DEFAULT_EDGE_COLOR,
},
id: `${source}-${target}`,
- // Make thicker
- style: { strokeWidth: 2 },
+ data: { variables, isStateFlow },
source: source,
// Use the same handle ids as the custom node
sourceHandle: OUTPUTS_HANDLE_ID,
@@ -128,15 +294,19 @@ export class TreeElementsBuilder implements ElementsBuilder {
};
}
- private createNode(id: string, atom: Atom<CellData>): Node<NodeData> {
- const linesOfCode = store.get(atom).code.trim().split("\n").length;
- const height = getNodeHeight(linesOfCode);
+ private createNode(
+ id: string,
+ atom: Atom<CellData>,
+ defs: VariableName[],
+ ): Node<NodeData> {
+ const data: NodeData = { atom, defs };
+ const { width, height } = nodeDimensions(data);
return {
id: id,
- data: { atom, forceWidth: 300 },
- width: 300,
+ data,
+ width,
type: "custom",
- height: height,
+ height,
position: { x: 0, y: 0 },
};
}
@@ -149,10 +319,19 @@ export class TreeElementsBuilder implements ElementsBuilder {
hideReusableFunctions: boolean,
) {
const nodes: Node<NodeData>[] = [];
- const edges: Edge[] = [];
+
+ const cellRuntime = getNotebook().cellRuntime;
+ // Hidden reusable cells are dropped along with their edges — a reusable
+ // function is nearly always referenced somewhere, so gating on "no edges"
+ // would make the filter a no-op.
+ const hiddenReusable = hideReusableFunctions
+ ? reusableCellIds(cellIds, cellRuntime)
+ : new Set<CellId>();
const nodesWithEdges = new Set<CellId>();
- const visited = new Set<string>();
+ // Dedupe cell→cell edges, aggregating every variable that crosses them so a
+ // single edge can carry multiple refs and flag whether any is a state flow.
+ const edgesByPair = new Map<string, AggregatedEdge>();
for (const variable of Object.values(variables)) {
// Skip marimo, since likely every cell uses it
@@ -160,40 +339,55 @@ export class TreeElementsBuilder implements ElementsBuilder {
continue;
}
+ const isState = isStateFlowVariable(variable);
const { declaredBy, usedBy } = variable;
for (const fromId of declaredBy) {
for (const toId of usedBy) {
- const key = `${fromId}-${toId}`;
- if (visited.has(key)) {
+ if (hiddenReusable.has(fromId) || hiddenReusable.has(toId)) {
continue;
}
- visited.add(key);
+ const key = `${fromId}-${toId}`;
+ const existing = edgesByPair.get(key);
+ if (existing) {
+ existing.variables.push(variable.name);
+ existing.isStateFlow ||= isState;
+ } else {
+ edgesByPair.set(key, {
+ source: fromId,
+ target: toId,
+ variables: [variable.name],
+ isStateFlow: isState,
+ });
+ }
nodesWithEdges.add(fromId);
nodesWithEdges.add(toId);
- edges.push(this.createEdge(fromId, toId));
}
}
}
- const cellRuntime = getNotebook().cellRuntime;
+ const edges = [...edgesByPair.values()].map((edge) =>
+ this.createEdge(edge),
+ );
+
+ const defsByCell = computeDefsByCell(variables);
for (const [cellId, cellAtom] of Arrays.zip(cellIds, cellAtoms)) {
const code = store.get(cellAtom).code.trim();
const hasEdge = nodesWithEdges.has(cellId);
const isMarkdown = code.startsWith("mo.md");
- const runtime = cellRuntime[cellId];
- const isReusable = runtime?.serialization?.toLowerCase() === "valid";
// Apply filters
if (hidePureMarkdown && isMarkdown && !hasEdge) {
continue;
}
- if (hideReusableFunctions && isReusable && !hasEdge) {
+ if (hiddenReusable.has(cellId)) {
continue;
}
// Show every cell that wasn't filtered out
- nodes.push(this.createNode(cellId, cellAtom));
+ nodes.push(
+ this.createNode(cellId, cellAtom, defsByCell.get(cellId) ?? []),
+ );
}
return { nodes, edges };
diff --git a/frontend/src/components/dependency-graph/panels.tsx b/frontend/src/components/dependency-graph/panels.tsx
index 6cca2c1c83..fca2295fb7 100644
--- a/frontend/src/components/dependency-graph/panels.tsx
+++ b/frontend/src/components/dependency-graph/panels.tsx
@@ -4,6 +4,7 @@ import {
ArrowRightFromLineIcon,
ArrowRightIcon,
ArrowRightToLineIcon,
+ ExternalLinkIcon,
MoreVerticalIcon,
NetworkIcon,
SettingsIcon,
@@ -13,17 +14,18 @@ import {
} from "lucide-react";
import React, { memo, useId } from "react";
import { type Edge, Panel } from "reactflow";
-import { getCellEditorView } from "@/core/cells/cells";
+import { getCellEditorView, useCellActions } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
import { goToVariableDefinition } from "@/core/codemirror/go-to-definition/commands";
import type { Variable, Variables } from "@/core/variables/types";
import { ConnectionCellActionsDropdown } from "../editor/cell/cell-actions";
-import { CellLink } from "../editor/links/cell-link";
+import { CellLink, scrollAndHighlightCell } from "../editor/links/cell-link";
import { CellLinkList } from "../editor/links/cell-link-list";
import { Button } from "../ui/button";
import { Checkbox } from "../ui/checkbox";
import { Label } from "../ui/label";
import { Popover, PopoverContent, PopoverTrigger } from "../ui/popover";
+import { Tooltip } from "../ui/tooltip";
import { VariableName } from "../variables/common";
import type { GraphSelection, GraphSettings, LayoutDirection } from "./types";
@@ -122,6 +124,8 @@ export const GraphSelectionPanel: React.FC<{
edges: Edge[];
variables: Variables;
}> = memo(({ selection, variables, onClearSelection }) => {
+ const { showCellIfHidden } = useCellActions();
+
if (!selection) {
return null;
}
@@ -194,6 +198,23 @@ export const GraphSelectionPanel: React.FC<{
<SquareFunction className="w-5 h-5" />
<CellLink cellId={selection.id} />
<div className="flex-1" />
+ <Tooltip content="Open cell in editor" delayDuration={200}>
+ <Button
+ aria-label="Open cell in editor"
+ variant="text"
+ size="icon"
+ onClick={() => {
+ // The cell may sit in a collapsed section; reveal it first
+ // or the scroll target won't be in the DOM.
+ showCellIfHidden({ cellId: selection.id });
+ requestAnimationFrame(() => {
+ scrollAndHighlightCell(selection.id, "focus");
+ });
+ }}
+ >
+ <ExternalLinkIcon className="w-4 h-4" />
+ </Button>
+ </Tooltip>
<ConnectionCellActionsDropdown cellId={selection.id}>
<Button variant="ghost" size="icon">
<MoreVerticalIcon className="w-4 h-4" />
diff --git a/frontend/src/components/dependency-graph/utils/__tests__/layout.test.ts b/frontend/src/components/dependency-graph/utils/__tests__/layout.test.ts
new file mode 100644
index 0000000000..e4733b568d
--- /dev/null
+++ b/frontend/src/components/dependency-graph/utils/__tests__/layout.test.ts
@@ -0,0 +1,78 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import type { Node } from "reactflow";
+import { describe, expect, it } from "vitest";
+import type { NodeData } from "../../elements";
+import { boundingBox, placeIslands } from "../layout";
+
+function node(
+ id: string,
+ x: number,
+ y: number,
+ width: number,
+ height: number,
+): Node<NodeData> {
+ return {
+ id,
+ position: { x, y },
+ width,
+ height,
+ data: { atom: {} as NodeData["atom"], defs: [] },
+ };
+}
+
+describe("boundingBox", () => {
+ it("is all-zero for an empty set", () => {
+ expect(boundingBox([])).toEqual({ minX: 0, minY: 0, maxX: 0, maxY: 0 });
+ });
+
+ it("spans position + size across nodes", () => {
+ const box = boundingBox([
+ node("a", 0, 0, 50, 50),
+ node("b", 10, 20, 100, 40),
+ ]);
+ expect(box).toEqual({ minX: 0, minY: 0, maxX: 110, maxY: 60 });
+ });
+
+ it("reads size from style.width/height when width/height are absent", () => {
+ const groupNode: Node = {
+ id: "g",
+ position: { x: 5, y: 5 },
+ data: {},
+ style: { width: 200, height: 100 },
+ };
+ expect(boundingBox([groupNode])).toEqual({
+ minX: 5,
+ minY: 5,
+ maxX: 205,
+ maxY: 105,
+ });
+ });
+});
+
+describe("placeIslands", () => {
+ it("returns nothing when there are no islands", () => {
+ expect(placeIslands([], [node("a", 0, 0, 100, 100)])).toEqual([]);
+ });
+
+ it("stacks islands in a column to the right of the placed graph", () => {
+ const placed = [node("main", 0, 0, 200, 300)];
+ const islands = [node("i0", 0, 0, 90, 40), node("i1", 0, 0, 90, 40)];
+ const result = placeIslands(islands, placed);
+ // startX = maxX(200) + margin(40) = 240; startY = minY(0).
+ expect(result[0].position).toEqual({ x: 240, y: 0 });
+ // Second island stacked below the first (height 40 + gap 20).
+ expect(result[1].position).toEqual({ x: 240, y: 60 });
+ });
+
+ it("wraps into a new column when the column gets too tall", () => {
+ const placed = [node("main", 0, 0, 200, 300)];
+ const islands = Array.from({ length: 10 }, (_, i) =>
+ node(`i${i}`, 0, 0, 90, 40),
+ );
+ const result = placeIslands(islands, placed);
+ const firstColumnX = result[0].position.x;
+ const wrapped = result.find((n) => n.position.x > firstColumnX);
+ expect(wrapped).toBeDefined();
+ });
+});
diff --git a/frontend/src/components/dependency-graph/utils/layout.ts b/frontend/src/components/dependency-graph/utils/layout.ts
index 5d4c57d6f7..c046f3e397 100644
--- a/frontend/src/components/dependency-graph/utils/layout.ts
+++ b/frontend/src/components/dependency-graph/utils/layout.ts
@@ -1,45 +1,135 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { graphlib, layout } from "@dagrejs/dagre";
import type { Edge, Node } from "reactflow";
+import type { NodeData } from "../elements";
import type { LayoutDirection } from "../types";
-const g = new graphlib.Graph().setDefaultEdgeLabel(() => ({}));
+// Disconnected cells are stacked in a compact column to the side of the main
+// graph, like TensorBoard's extracted/auxiliary nodes (extractXOffset 15,
+// extractYOffset 20).
+const ISLAND_GAP = 20;
+const ISLAND_MARGIN = 40;
+const ISLAND_MIN_COLUMN_HEIGHT = 320;
+/**
+ * Lay out cell nodes with dagre. Disconnected cells are pulled out of the
+ * dagre flow and stacked in a compact column to the side of the main graph.
+ */
export const layoutElements = ({
nodes,
edges,
direction,
}: {
- nodes: Node[];
+ nodes: Node<NodeData>[];
edges: Edge[];
direction: LayoutDirection;
-}) => {
+}): { nodes: Node<NodeData>[]; edges: Edge[] } => {
+ const g = new graphlib.Graph().setDefaultEdgeLabel(() => ({}));
g.setGraph({
rankdir: direction,
- nodesep: 150,
- ranksep: 200,
- // So far, longest-path seems to give the best results as trees are
- // generally quite wide.
- ranker: "longest-path",
+ // Tight spacing mirroring TensorBoard's graph (nodesep 5, ranksep 25,
+ // edgesep 5), nudged up a little since our nodes are wider ref boxes than
+ // TensorBoard's op ellipses. The dagre default ranker (network-simplex)
+ // gives cleaner layered routing with fewer crossings than longest-path.
+ nodesep: 20,
+ ranksep: 30,
+ edgesep: 10,
});
+ // Disconnected cells are pulled out of the dagre flow and stacked to the
+ // side, so they don't stretch the main graph's layout.
+ const connectedIds = new Set<string>();
+ for (const edge of edges) {
+ connectedIds.add(edge.source);
+ connectedIds.add(edge.target);
+ }
+ const isIsland = (node: Node<NodeData>) => !connectedIds.has(node.id);
+ const flowNodes = nodes.filter((node) => !isIsland(node));
+ const islands = nodes.filter(isIsland);
+
edges.forEach((edge) => g.setEdge(edge.source, edge.target));
- nodes.forEach((node) =>
+ flowNodes.forEach((node) => {
g.setNode(node.id, {
...node,
width: node.width ?? 0,
height: node.height ?? 0,
- }),
- );
+ });
+ });
layout(g);
- return {
- nodes: nodes.map((node) => {
- const { x, y } = g.node(node.id);
-
- return { ...node, position: { x, y } };
- }),
- edges,
+ // dagre reports node coords as centers; ReactFlow wants top-left.
+ const topLeft = (id: string) => {
+ const { x, y, width, height } = g.node(id);
+ return { x: x - width / 2, y: y - height / 2 };
};
+
+ const cellNodes = flowNodes.map((node) => ({
+ ...node,
+ position: topLeft(node.id),
+ }));
+
+ const islandNodes = placeIslands(islands, cellNodes);
+ return { nodes: [...cellNodes, ...islandNodes], edges };
};
+
+/** Bounding box of already-positioned nodes (top-left position + size). */
+export function boundingBox(nodes: Node[]): {
+ minX: number;
+ minY: number;
+ maxX: number;
+ maxY: number;
+} {
+ if (nodes.length === 0) {
+ return { minX: 0, minY: 0, maxX: 0, maxY: 0 };
+ }
+ let minX = Infinity;
+ let minY = Infinity;
+ let maxX = -Infinity;
+ let maxY = -Infinity;
+ for (const node of nodes) {
+ const styleW = node.style?.width;
+ const styleH = node.style?.height;
+ const w = node.width ?? (typeof styleW === "number" ? styleW : 0);
+ const h = node.height ?? (typeof styleH === "number" ? styleH : 0);
+ minX = Math.min(minX, node.position.x);
+ minY = Math.min(minY, node.position.y);
+ maxX = Math.max(maxX, node.position.x + w);
+ maxY = Math.max(maxY, node.position.y + h);
+ }
+ return { minX, minY, maxX, maxY };
+}
+
+/**
+ * Stack disconnected nodes in a compact column (wrapping into more columns when
+ * tall) just to the right of the main graph.
+ */
+export function placeIslands(
+ islands: Node<NodeData>[],
+ placed: Node[],
+): Node<NodeData>[] {
+ if (islands.length === 0) {
+ return [];
+ }
+ const box = boundingBox(placed);
+ const startX = (placed.length === 0 ? 0 : box.maxX) + ISLAND_MARGIN;
+ const startY = placed.length === 0 ? 0 : box.minY;
+ const columnHeight = Math.max(box.maxY - box.minY, ISLAND_MIN_COLUMN_HEIGHT);
+
+ let x = startX;
+ let y = startY;
+ let columnWidth = 0;
+ return islands.map((node) => {
+ const h = node.height ?? 0;
+ if (y > startY && y + h > startY + columnHeight) {
+ // Wrap to the next column.
+ x += columnWidth + ISLAND_MARGIN;
+ y = startY;
+ columnWidth = 0;
+ }
+ const position = { x, y };
+ y += h + ISLAND_GAP;
+ columnWidth = Math.max(columnWidth, node.width ?? 0);
+ return { ...node, position };
+ });
+}