ui: Add baseline diffing to the tree explorer; use it in HDE

Make flamegraph diffing an opt-in feature of the tree explorer panel,
next to its Call Tree and Functions table views, and make the Heap
Dump Explorer its first user.

Tree explorer:
- TreeExplorerPanelAttrs.baseline opts into comparing the panel's tree
  against a baseline tree, fetched with the same state (metric,
  filters, view). Hosts without a baseline are unaffected. For now,
  only trees of the same trace are supported.
- buildTreeExplorerDiff pairs the nodes of the two trees by name and
  grouping properties under paired parents, pprof-style, and lays out
  their union as one tree. Columns marked profileSpecific (e.g. hashes
  of ids) are ignored when pairing.
- state.comparison chooses what is shown (the diff, or either tree on
  its own), what diff node widths are proportional to (both trees, or
  one of them) and what node colors encode (absolute or relative
  change).
- A Diff switch and a Baseline/Current toggle at the right of the tab
  bar choose between the diff and either tree. A legend and a tune
  menu control how the diff is drawn.
- The flamegraph colors diff nodes from green (shrank) to red (grew).
  Its tooltips, copied stacks and exports show the baseline and current
  values and their change, and only the properties which pair nodes, as
  the others have a value per tree. Host node actions are not offered
  on nodes only the baseline has.
- The Call Tree and Functions tabs show the diff with baseline, change
  and relative change columns, largest growth first.

Heap Dump Explorer:
- A "Compare with:" picker on the Flamegraph tab selects a baseline
  dump of the same trace. It is persisted with the rest of the state.
- Heap dump labels include the dump's time, to tell apart the dumps of
  one process.
- The pprof download holds the dump being shown.

Merging several profiles is not part of this change.
diff --git a/docs/visualization/heap-dump-explorer.md b/docs/visualization/heap-dump-explorer.md
index 58bb2f2..ea2ff63 100644
--- a/docs/visualization/heap-dump-explorer.md
+++ b/docs/visualization/heap-dump-explorer.md
@@ -234,9 +234,10 @@
 heap is disproportionately large.
 
 The same flamegraph appears in the timeline when you click a heap
-dump diamond in an _"ART heap dump"_ track — every feature below works
-identically there. A few extras that only exist in the timeline
-variant are covered at the end under
+dump diamond in an _"ART heap dump"_ track — every feature below but
+[comparing two dumps](#comparing-two-heap-dumps) works identically
+there. A few extras that only exist in the timeline variant are
+covered at the end under
 [the timeline flamegraph](#the-timeline-flamegraph).
 
 ![Timeline on top, heap graph flamegraph in the bottom panel after clicking the heap dump diamond on the process track.](../images/heap_docs/14-flamegraph-bottom-panel.png)
@@ -448,6 +449,63 @@
 anchored as `^name$`), so filtering on `java.lang.String` will not
 accidentally match `java.lang.StringBuilder`.
 
+### Comparing two heap dumps
+
+NOTE: Comparing is only available on the explorer's Flamegraph tab; the
+timeline flamegraph always shows a single dump.
+
+When the trace holds more than one heap dump, the Flamegraph tab can
+show how the heap changed between two of them, e.g. between a dump
+taken before and one taken after repeating a suspected leak a few
+times. Pick the earlier dump in the _Compare with:_ menu next to the
+_Heap dump:_ selector: the flamegraph then shows the tree of the active
+dump diffed against the tree of that _baseline_ dump.
+
+- Nodes are paired across the two dumps by their path of class names
+  (and their Root Type and Heap Type), so the same reference chain
+  lines up in both dumps even though the objects themselves differ.
+- **Red** nodes grew, **green** nodes shrank and grey ones did not
+  change; the legend at the right of the tab bar reads from _Shrank_
+  to _Grew_.
+- A node's width is proportional to the sum of its values in both
+  dumps, so that nodes only one of the dumps has are visible too.
+- Hovering a node shows its Cumulative and Self values in the baseline
+  and in the current dump and how they changed. The `root` row
+  summarizes the change of the whole dump, e.g.
+  `root: 20.10 MiB → 24.50 MiB (+4.40 MiB, +21.89%)`.
+- The diff's tooltips, copied stacks and exports leave out the Self
+  Count, which belongs to a single dump: switch to the _Object Count_
+  metric to compare the numbers of objects instead.
+
+The _Diff_ switch at the right of the tab bar turns the diff off; the
+_Baseline_ / _Current_ toggle then shows either dump on its own, with
+the same metric and filters, to flip between the two. While diffing,
+the tune button next to the legend changes how the diff is drawn:
+
+- **Node width** — _Baseline + current_ (the default) or the values of
+  a single dump, _Current_ or _Baseline_, which sizes nodes like that
+  dump's own flamegraph and hides the nodes only the other dump has.
+- **Node color** — _Absolute change_ (the default) colors nodes by
+  their change relative to the largest change in the tree, so that the
+  biggest movers stand out. _Relative change_ colors them by their
+  change relative to their own baseline value, saturating at ±100%, so
+  that small classes which doubled stand out too.
+
+The _Call Tree_ and _Functions_ tabs show the same diff as tables,
+with baseline, change (`Δ`) and relative change (`Δ %`) columns,
+largest growth first. Exports of the diff hold the baseline and current
+values of each row and their change, in files ending in `_diff` (or in
+`_baseline` when showing the baseline dump). The _Pprof profile_
+download always holds a single dump: the baseline dump when showing it,
+otherwise the active dump.
+
+In the diff, node actions such as _Show objects from this class_ act on
+the active dump, so they are not offered on nodes only the baseline
+has. When showing the baseline dump they act on that dump, and showing
+its objects makes it the active dump. The _View in Flamegraph_ buttons
+of an object tab pivot on a path of the active dump, so they show the
+active dump on its own.
+
 ### The timeline flamegraph
 
 The flamegraph in the timeline's _"ART heap dump"_ details panel has
diff --git a/ui/src/components/tree_explorer_fetcher.ts b/ui/src/components/tree_explorer_fetcher.ts
index 8784c3c..927897c 100644
--- a/ui/src/components/tree_explorer_fetcher.ts
+++ b/ui/src/components/tree_explorer_fetcher.ts
@@ -52,6 +52,12 @@
   // Function that determines whether the property should be displayed for a
   // given node.
   readonly isVisible?: (value: string) => boolean;
+
+  // Whether the values of the column only have meaning within the tree they
+  // were read from (e.g. ids, or hashes of them), so that they never match
+  // between two trees: diffs then pair nodes ignoring the column. Only
+  // meaningful for unaggregatable properties.
+  readonly profileSpecific?: boolean;
 }
 
 export interface AggTreeExplorerQueryColumn extends TreeExplorerQueryColumn {
@@ -394,6 +400,7 @@
           value,
           isVisible: a.isVisible ? a.isVisible(value) : true,
           isAggregatable: false,
+          profileSpecific: a.profileSpecific,
         });
       }
     }
diff --git a/ui/src/components/tree_explorer_panel.ts b/ui/src/components/tree_explorer_panel.ts
index 479798c..fe9913a 100644
--- a/ui/src/components/tree_explorer_panel.ts
+++ b/ui/src/components/tree_explorer_panel.ts
@@ -36,6 +36,14 @@
   buildFlatExportString,
 } from './tree_explorer_table_views';
 import {Tabs} from '../widgets/tabs';
+import {
+  type TreeExplorerBaseline,
+  TreeExplorerPanelDiff,
+  exportDiffSuffix,
+  renderTreeExplorerDiffControls,
+} from './tree_explorer_panel_diff';
+
+export type {TreeExplorerBaseline} from './tree_explorer_panel_diff';
 
 export interface TreeExplorerPanelAttrs {
   // The fetcher supplying the tree, or undefined to show a pending state.
@@ -57,6 +65,11 @@
   // Host-provided downloads shown alongside the built-in exports of the
   // displayed tree, for representations the panel cannot build itself.
   readonly extraDownloadItems?: ReadonlyArray<ExportDownloadItem>;
+
+  // Opts into comparing the tree against a baseline tree: adds controls
+  // choosing (in `state.comparison`) whether the views show the diff of the
+  // two trees (see tree_explorer_diff.ts) or either tree on its own.
+  readonly baseline?: TreeExplorerBaseline;
 }
 
 // The batteries-included tree explorer: a tab bar switching between the
@@ -72,15 +85,18 @@
 // panel.
 export class TreeExplorerPanel implements m.ClassComponent<TreeExplorerPanelAttrs> {
   private highlightPattern = '';
+  private readonly diff = new TreeExplorerPanelDiff();
 
   view({attrs}: m.CVnode<TreeExplorerPanelAttrs>): m.Children {
     const {fetcher, state = createDefaultTreeExplorerState(fetcher.metrics)} =
       attrs;
     const metrics = fetcher?.metrics;
-    const data =
-      fetcher !== undefined && state !== undefined
-        ? fetcher.use({...state, view: effectiveView(state)}).data
-        : undefined;
+    const {data, shown, compareDisabledReason} = this.diff.shownData(
+      fetcher,
+      attrs.baseline,
+      state,
+      effectiveView,
+    );
 
     const shownState = state ?? {
       view: {kind: 'TOP_DOWN' as const},
@@ -127,11 +143,11 @@
                       );
                 },
           exportFileBaseName:
-            displayMode === 'flat'
+            (displayMode === 'flat'
               ? 'functions'
               : displayMode === 'tree'
                 ? 'call_tree'
-                : 'flamegraph',
+                : 'flamegraph') + exportDiffSuffix(shown),
           extraDownloadItems: attrs.extraDownloadItems,
         }),
         children,
@@ -164,6 +180,13 @@
             displayMode: key as TreeExplorerDisplayMode,
           });
         },
+        rightContent: renderTreeExplorerDiffControls(
+          attrs.baseline,
+          shownState,
+          attrs.onStateChange,
+          displayMode,
+          compareDisabledReason,
+        ),
         tabs: [
           {
             key: 'flamegraph',
diff --git a/ui/src/components/tree_explorer_panel_diff.ts b/ui/src/components/tree_explorer_panel_diff.ts
new file mode 100644
index 0000000..d3fd5c2
--- /dev/null
+++ b/ui/src/components/tree_explorer_panel_diff.ts
@@ -0,0 +1,162 @@
+// Copyright (C) 2026 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+import m from 'mithril';
+import {assertUnreachable} from '../base/assert';
+import {
+  type TreeExplorerComparison,
+  type TreeExplorerData,
+  type TreeExplorerDiffWidth,
+  type TreeExplorerDisplayMode,
+  type TreeExplorerMetric,
+  type TreeExplorerState,
+  type TreeExplorerView,
+  getTreeExplorerComparison,
+  metricId,
+} from '../widgets/tree_explorer';
+import {buildTreeExplorerDiff} from '../widgets/tree_explorer_diff';
+import {TreeExplorerDiffControls} from '../widgets/tree_explorer_diff_controls';
+import type {TreeExplorerFetcher} from './tree_explorer_fetcher';
+
+// A tree to compare the panel's tree against. For now, only trees of the
+// same trace are supported, e.g. another heap dump in it.
+export interface TreeExplorerBaseline {
+  // Supplies the baseline tree, fetched with the same state (metric, filters,
+  // view) as the current tree, so its metrics should have the same ids and
+  // properties as the current fetcher's. Owned by the caller, like
+  // TreeExplorerPanelAttrs.fetcher.
+  readonly fetcher: TreeExplorerFetcher;
+
+  // Short human-readable names of the baseline and the current tree, e.g. of
+  // the heap dumps they were read from. Default to 'Baseline' and 'Current'.
+  readonly baselineLabel?: string;
+  readonly currentLabel?: string;
+}
+
+// The panel's diffing state: which tree it shows given a baseline, and the
+// last diff built.
+export class TreeExplorerPanelDiff {
+  private lastDiff?: {
+    readonly current: TreeExplorerData;
+    readonly baseline: TreeExplorerData;
+    readonly width: TreeExplorerDiffWidth;
+    readonly diff: TreeExplorerData;
+  };
+
+  // The tree the views show, or undefined while it is pending: the fetched
+  // tree, or given a baseline, per state.comparison, its diff against the
+  // baseline tree or either tree on its own. Also says why the trees cannot
+  // be compared, if they cannot: the current tree is then shown.
+  shownData(
+    fetcher: TreeExplorerFetcher | undefined,
+    baseline: TreeExplorerBaseline | undefined,
+    state: TreeExplorerState,
+    effectiveView: (state: TreeExplorerState) => TreeExplorerView,
+  ): {
+    readonly data?: TreeExplorerData;
+    readonly shown?: TreeExplorerComparison['show'];
+    readonly compareDisabledReason?: string;
+  } {
+    if (fetcher === undefined) {
+      return {};
+    }
+    const fetchState = {...state, view: effectiveView(state)};
+    const current = fetcher.use(fetchState).data;
+    if (baseline === undefined) {
+      return {data: current};
+    }
+    const selected = (x: TreeExplorerMetric) =>
+      metricId(x) === state.selectedMetricId;
+    if (!baseline.fetcher.metrics.some(selected)) {
+      const name = fetcher.metrics.find(selected)?.name ?? 'such';
+      return {
+        data: current,
+        compareDisabledReason: `The baseline has no ${name} data`,
+      };
+    }
+    // Fetched whatever is shown, so that switching between the trees and
+    // their diff is instant.
+    const base = baseline.fetcher.use(fetchState).data;
+    const {show, width} = getTreeExplorerComparison(state);
+    switch (show) {
+      case 'CURRENT':
+        return {data: current, shown: show};
+      case 'BASELINE':
+        return {data: base, shown: show};
+      case 'DIFF':
+        return {
+          data:
+            current === undefined || base === undefined
+              ? undefined
+              : this.diffOf(current, base, width),
+          shown: show,
+        };
+      default:
+        assertUnreachable(show);
+    }
+  }
+
+  // Builds the diff only when an input changes: the flamegraph resets its
+  // zoom on new data.
+  private diffOf(
+    current: TreeExplorerData,
+    baseline: TreeExplorerData,
+    width: TreeExplorerDiffWidth,
+  ): TreeExplorerData {
+    const last = this.lastDiff;
+    if (
+      last !== undefined &&
+      last.current === current &&
+      last.baseline === baseline &&
+      last.width === width
+    ) {
+      return last.diff;
+    }
+    const diff = buildTreeExplorerDiff(current, baseline, width);
+    this.lastDiff = {current, baseline, width, diff};
+    return diff;
+  }
+}
+
+export function renderTreeExplorerDiffControls(
+  baseline: TreeExplorerBaseline | undefined,
+  state: TreeExplorerState,
+  onStateChange: (state: TreeExplorerState) => void,
+  displayMode: TreeExplorerDisplayMode,
+  disabledReason?: string,
+): m.Children {
+  if (baseline === undefined) {
+    return null;
+  }
+  return m(TreeExplorerDiffControls, {
+    comparison: getTreeExplorerComparison(state),
+    onComparisonChange: (comparison) => onStateChange({...state, comparison}),
+    baselineLabel: baseline.baselineLabel ?? 'Baseline',
+    currentLabel: baseline.currentLabel ?? 'Current',
+    flamegraphOptions: displayMode === 'flamegraph',
+    disabledReason,
+  });
+}
+
+export function exportDiffSuffix(
+  shown?: TreeExplorerComparison['show'],
+): string {
+  if (shown === 'DIFF') {
+    return '_diff';
+  }
+  if (shown === 'BASELINE') {
+    return '_baseline';
+  }
+  return '';
+}
diff --git a/ui/src/components/tree_explorer_table_views.ts b/ui/src/components/tree_explorer_table_views.ts
index 2d822e5..a9948e1 100644
--- a/ui/src/components/tree_explorer_table_views.ts
+++ b/ui/src/components/tree_explorer_table_views.ts
@@ -39,6 +39,13 @@
 } from './widgets/datagrid/data_source';
 import type {IdBasedTree} from './widgets/datagrid/model';
 import type {Row, SqlValue} from '../trace_processor/query_result';
+import {
+  DIFF_FLAT_INITIAL_COLUMNS,
+  DIFF_TREE_INITIAL_COLUMNS,
+  buildFlatDiffExportString,
+  diffColumnSchema,
+  diffColumns,
+} from './tree_explorer_table_views_diff';
 
 const DEFAULT_TREE: IdBasedTree = {
   idField: 'id',
@@ -56,6 +63,9 @@
 // the share of the root total. DataGrid id-based tree mode keeps expansion
 // O(visible rows) and the DOM virtualised. Direction (top-down vs bottom-up)
 // is a property of the fetched tree, not of this widget.
+//
+// Given a diff (see TreeExplorerData.diff), rows show how the values changed
+// from the baseline tree, biggest growth first.
 export class TreeExplorerTreeView implements m.ClassComponent<TreeExplorerTreeViewAttrs> {
   private source?: TreeExplorerTreeDataSource;
   private sourceData?: TreeExplorerData;
@@ -69,42 +79,52 @@
     }
     const fmtValue = (value: SqlValue) =>
       typeof value === 'number' ? displaySize(value, attrs.unit) : '';
-    return m(DataGrid, {
-      className: 'pf-tree-explorer__grid',
-      fillHeight: true,
-      // The tree explorer's own filter bar is the filtering surface;
-      // row-level grid filters have no meaning on a tree walk.
-      disableFilterControls: true,
-      schema: {
-        name: {title: 'Name', columnType: 'text'},
-        total: {
-          title: 'Total',
-          columnType: 'quantitative',
-          cellRenderer: fmtValue,
+    const isDiff = attrs.data.diff !== undefined;
+    // A fragment, so that its key is honoured: the grid only reads its
+    // initial columns when created, so it is recreated when switching
+    // between a single tree and a diff.
+    return [
+      m(DataGrid, {
+        key: isDiff ? 'diff' : 'tree',
+        className: 'pf-tree-explorer__grid',
+        fillHeight: true,
+        // The tree explorer's own filter bar is the filtering surface;
+        // row-level grid filters have no meaning on a tree walk.
+        disableFilterControls: true,
+        schema: {
+          name: {title: 'Name', columnType: 'text'},
+          total: {
+            title: isDiff ? 'Current total' : 'Total',
+            columnType: 'quantitative',
+            cellRenderer: fmtValue,
+          },
+          self: {
+            title: isDiff ? 'Current self' : 'Self',
+            columnType: 'quantitative',
+            cellRenderer: fmtValue,
+          },
+          percent: {
+            title: '% of total',
+            columnType: 'quantitative',
+            cellRenderer: fmtPercent,
+          },
+          ...(isDiff ? diffColumnSchema(attrs.unit) : {}),
         },
-        self: {
-          title: 'Self',
-          columnType: 'quantitative',
-          cellRenderer: fmtValue,
+        data: this.source,
+        initialColumns: isDiff
+          ? DIFF_TREE_INITIAL_COLUMNS
+          : [
+              {id: 'name', field: 'name'},
+              {id: 'total', field: 'total', sort: 'DESC'},
+              {id: 'self', field: 'self'},
+              {id: 'percent', field: 'percent'},
+            ],
+        tree: this.tree ?? DEFAULT_TREE,
+        onTreeChanged: (tree) => {
+          this.tree = tree;
         },
-        percent: {
-          title: '% of total',
-          columnType: 'quantitative',
-          cellRenderer: fmtPercent,
-        },
-      },
-      data: this.source,
-      initialColumns: [
-        {id: 'name', field: 'name'},
-        {id: 'total', field: 'total', sort: 'DESC'},
-        {id: 'self', field: 'self'},
-        {id: 'percent', field: 'percent'},
-      ],
-      tree: this.tree ?? DEFAULT_TREE,
-      onTreeChanged: (tree) => {
-        this.tree = tree;
-      },
-    });
+      }),
+    ];
   }
 }
 
@@ -115,10 +135,12 @@
   private readonly children = new Map<number, TreeExplorerNode[]>();
   private readonly roots: TreeExplorerNode[] = [];
   private readonly total: number;
+  private readonly isDiff: boolean;
 
   constructor(data: TreeExplorerData) {
     super([]);
     this.total = data.allRootsCumulativeValue;
+    this.isDiff = data.diff !== undefined;
     const ids = new Set(data.nodes.map((n) => n.id));
     for (const n of data.nodes) {
       if (ids.has(n.parentId)) {
@@ -155,24 +177,24 @@
       collapsedIds !== undefined
         ? !collapsedIds.has(BigInt(id))
         : (expandedIds?.has(BigInt(id)) ?? false);
-    const cmp = this.comparator(model.sort);
+    // The grid reads cells by column alias, which is not the field for the
+    // columns the user adds.
+    const aliased = model.columns.filter((c) => c.alias !== c.field);
+    const sortField = model.columns.find(
+      (c) => c.alias === model.sort?.alias,
+    )?.field;
+    const cmp = this.comparator(sortField, model.sort?.direction);
     const rows: Row[] = [];
     const visit = (nodes: TreeExplorerNode[], depth: number) => {
-      for (const n of [...nodes].sort(cmp)) {
-        const children = this.children.get(n.id);
-        rows.push({
-          id: n.id,
-          parentId: n.parentId,
-          name: n.name,
-          total: n.cumulativeValue,
-          self: n.selfValue,
-          percent:
-            this.total === 0 ? 0 : (n.cumulativeValue / this.total) * 100,
-          __id: n.id,
-          __depth: depth,
-          __has_children: children === undefined ? 0 : 1,
-        });
-        if (children !== undefined && isExpanded(n.id)) {
+      const siblings = nodes.map((n) => ({node: n, row: this.row(n, depth)}));
+      siblings.sort((a, b) => cmp(a.row, b.row));
+      for (const {node, row} of siblings) {
+        for (const {field, alias} of aliased) {
+          row[alias] = row[field] ?? null;
+        }
+        rows.push(row);
+        const children = this.children.get(node.id);
+        if (children !== undefined && isExpanded(node.id)) {
           visit(children, depth + 1);
         }
       }
@@ -181,18 +203,39 @@
     return rows;
   }
 
+  private row(n: TreeExplorerNode, depth: number): Row {
+    return {
+      id: n.id,
+      parentId: n.parentId,
+      name: n.name,
+      total: n.cumulativeValue,
+      self: n.selfValue,
+      percent: this.total === 0 ? 0 : (n.cumulativeValue / this.total) * 100,
+      ...(this.isDiff
+        ? diffColumns({
+            baselineTotal: n.baselineCumulativeValue ?? 0,
+            total: n.cumulativeValue,
+            baselineSelf: n.baselineSelfValue ?? 0,
+            self: n.selfValue,
+          })
+        : {}),
+      __id: n.id,
+      __depth: depth,
+      __has_children: this.children.has(n.id) ? 1 : 0,
+    };
+  }
+
   private comparator(
-    sort: {alias: string; direction: 'ASC' | 'DESC'} | undefined,
-  ): (a: TreeExplorerNode, b: TreeExplorerNode) => number {
-    const dir = sort?.direction === 'ASC' ? 1 : -1;
-    switch (sort?.alias) {
-      case 'name':
-        return (a, b) => dir * a.name.localeCompare(b.name);
-      case 'self':
-        return (a, b) => dir * (a.selfValue - b.selfValue);
-      default: // 'total', 'percent' and the initial (unsorted) state.
-        return (a, b) => dir * (a.cumulativeValue - b.cumulativeValue);
+    field: string | undefined,
+    direction: 'ASC' | 'DESC' | undefined,
+  ): (a: Row, b: Row) => number {
+    const dir = direction === 'ASC' ? 1 : -1;
+    if (field === 'name') {
+      return (a, b) => dir * String(a.name).localeCompare(String(b.name));
     }
+    // Total when unsorted.
+    const key = field ?? 'total';
+    return (a, b) => dir * (Number(a[key]) - Number(b[key]));
   }
 }
 
@@ -200,6 +243,10 @@
   readonly name: string;
   readonly self: number;
   readonly total: number;
+  // Only set for diffs (see TreeExplorerData.diff): the values in the
+  // baseline tree, while `self` and `total` are the current tree's.
+  readonly baselineSelf?: number;
+  readonly baselineTotal?: number;
 }
 
 // Aggregates the tree per function name, pprof-style: `self` sums a
@@ -207,7 +254,8 @@
 // cumulative value counting only the topmost occurrence on each path, so
 // recursion (A -> B -> A) does not double-count A. Only the callee direction
 // (depth > 0) is aggregated: in PIVOT view the negative-depth caller nodes
-// re-attribute the same samples.
+// re-attribute the same samples. Diffs aggregate the baseline values the same
+// way.
 export function computeFlatFunctions(
   data: TreeExplorerData,
 ): TreeExplorerFlatFunction[] {
@@ -228,7 +276,10 @@
     }
   }
 
-  const functions = new Map<string, {self: number; total: number}>();
+  const functions = new Map<
+    string,
+    {self: number; total: number; baselineSelf: number; baselineTotal: number}
+  >();
   // Number of times each name occurs on the current root-to-node path.
   // Explicit stack with exit markers: call stacks can be deep.
   const onPath = new Map<string, number>();
@@ -245,13 +296,15 @@
       }
       let fn = functions.get(name);
       if (fn === undefined) {
-        fn = {self: 0, total: 0};
+        fn = {self: 0, total: 0, baselineSelf: 0, baselineTotal: 0};
         functions.set(name, fn);
       }
       fn.self += node.selfValue;
+      fn.baselineSelf += node.baselineSelfValue ?? 0;
       const occurrences = onPath.get(name) ?? 0;
       if (occurrences === 0) {
         fn.total += node.cumulativeValue;
+        fn.baselineTotal += node.baselineCumulativeValue ?? 0;
       }
       onPath.set(name, occurrences + 1);
       stack.push({node, exit: true});
@@ -260,7 +313,10 @@
       }
     }
   }
-  return [...functions].map(([name, {self, total}]) => ({name, self, total}));
+  const isDiff = data.diff !== undefined;
+  return [...functions].map(([name, fn]) =>
+    isDiff ? {name, ...fn} : {name, self: fn.self, total: fn.total},
+  );
 }
 
 export interface TreeExplorerFlatViewAttrs {
@@ -269,6 +325,7 @@
 }
 
 // Flat per-function table (pprof "Top"): Name, Self, Self %, Total, Total %.
+// Given a diff, it shows how self values changed, biggest growth first.
 export class TreeExplorerFlatView implements m.ClassComponent<TreeExplorerFlatViewAttrs> {
   private rows?: readonly Row[];
   private rowsData?: TreeExplorerData;
@@ -280,42 +337,50 @@
     }
     const fmtValue = (value: SqlValue) =>
       typeof value === 'number' ? displaySize(value, attrs.unit) : '';
-    return m(DataGrid, {
-      className: 'pf-tree-explorer__grid',
-      fillHeight: true,
-      disableFilterControls: true,
-      schema: {
-        name: {title: 'Name', columnType: 'text'},
-        self: {
-          title: 'Self',
-          columnType: 'quantitative',
-          cellRenderer: fmtValue,
+    const isDiff = attrs.data.diff !== undefined;
+    // A keyed fragment, as in TreeExplorerTreeView.
+    return [
+      m(DataGrid, {
+        key: isDiff ? 'diff' : 'flat',
+        className: 'pf-tree-explorer__grid',
+        fillHeight: true,
+        disableFilterControls: true,
+        schema: {
+          name: {title: 'Name', columnType: 'text'},
+          self: {
+            title: isDiff ? 'Current self' : 'Self',
+            columnType: 'quantitative',
+            cellRenderer: fmtValue,
+          },
+          selfPercent: {
+            title: 'Self %',
+            columnType: 'quantitative',
+            cellRenderer: fmtPercent,
+          },
+          total: {
+            title: isDiff ? 'Current total' : 'Total',
+            columnType: 'quantitative',
+            cellRenderer: fmtValue,
+          },
+          totalPercent: {
+            title: 'Total %',
+            columnType: 'quantitative',
+            cellRenderer: fmtPercent,
+          },
+          ...(isDiff ? diffColumnSchema(attrs.unit) : {}),
         },
-        selfPercent: {
-          title: 'Self %',
-          columnType: 'quantitative',
-          cellRenderer: fmtPercent,
-        },
-        total: {
-          title: 'Total',
-          columnType: 'quantitative',
-          cellRenderer: fmtValue,
-        },
-        totalPercent: {
-          title: 'Total %',
-          columnType: 'quantitative',
-          cellRenderer: fmtPercent,
-        },
-      },
-      data: this.rows,
-      initialColumns: [
-        {id: 'name', field: 'name'},
-        {id: 'self', field: 'self', sort: 'DESC'},
-        {id: 'selfPercent', field: 'selfPercent'},
-        {id: 'total', field: 'total'},
-        {id: 'totalPercent', field: 'totalPercent'},
-      ],
-    });
+        data: this.rows,
+        initialColumns: isDiff
+          ? DIFF_FLAT_INITIAL_COLUMNS
+          : [
+              {id: 'name', field: 'name'},
+              {id: 'self', field: 'self', sort: 'DESC'},
+              {id: 'selfPercent', field: 'selfPercent'},
+              {id: 'total', field: 'total'},
+              {id: 'totalPercent', field: 'totalPercent'},
+            ],
+      }),
+    ];
   }
 }
 
@@ -328,6 +393,14 @@
     selfPercent: pct(fn.self),
     total: fn.total,
     totalPercent: pct(fn.total),
+    ...(data.diff !== undefined
+      ? diffColumns({
+          baselineTotal: fn.baselineTotal ?? 0,
+          total: fn.total,
+          baselineSelf: fn.baselineSelf ?? 0,
+          self: fn.self,
+        })
+      : {}),
   }));
 }
 
@@ -342,6 +415,13 @@
   metric: TreeExplorerMetric,
   format: ExportFormat,
 ): string {
+  if (data.diff !== undefined) {
+    return buildFlatDiffExportString(
+      computeFlatFunctions(data),
+      metric,
+      format,
+    );
+  }
   const unitDisplay = getUnitDisplayName(metric.unit);
   const columns = ['name', 'self', 'selfPercent', 'total', 'totalPercent'];
   const columnNames: Record<string, string> = {
diff --git a/ui/src/components/tree_explorer_table_views_diff.scss b/ui/src/components/tree_explorer_table_views_diff.scss
new file mode 100644
index 0000000..25d9a59
--- /dev/null
+++ b/ui/src/components/tree_explorer_table_views_diff.scss
@@ -0,0 +1,25 @@
+// Copyright (C) 2026 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// The change columns of the table views when diffing against a baseline,
+// colored like the diffed flamegraph.
+.pf-tree-explorer__delta {
+  &--grew {
+    color: var(--pf-color-danger);
+  }
+
+  &--shrank {
+    color: var(--pf-color-success);
+  }
+}
diff --git a/ui/src/components/tree_explorer_table_views_diff.ts b/ui/src/components/tree_explorer_table_views_diff.ts
new file mode 100644
index 0000000..89c00da
--- /dev/null
+++ b/ui/src/components/tree_explorer_table_views_diff.ts
@@ -0,0 +1,228 @@
+// Copyright (C) 2026 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+import './tree_explorer_table_views_diff.scss';
+import m from 'mithril';
+import {assertUnreachable} from '../base/assert';
+import {classNames} from '../base/classnames';
+import {
+  formatAsJSON,
+  formatAsMarkdown,
+  formatAsTSV,
+} from '../base/export_formatters';
+import type {ExportFormat} from '../widgets/export_button';
+import {
+  displaySize,
+  getUnitDisplayName,
+  type TreeExplorerMetric,
+} from '../widgets/tree_explorer';
+import {
+  changePercentage,
+  displaySignedSize,
+} from '../widgets/tree_explorer_diff';
+import type {ColumnDef, ColumnSchema} from './widgets/datagrid/datagrid_schema';
+import type {Column} from './widgets/datagrid/model';
+import type {SqlValue} from '../trace_processor/query_result';
+
+// A row's values in the baseline and current trees of a diff.
+interface DiffValues {
+  readonly baselineTotal: number;
+  readonly total: number;
+  readonly baselineSelf: number;
+  readonly self: number;
+}
+
+interface DiffColumns {
+  readonly baselineTotal: number;
+  readonly totalDelta: number;
+  readonly totalDeltaPercent: number;
+  readonly baselineSelf: number;
+  readonly selfDelta: number;
+  readonly selfDeltaPercent: number;
+}
+
+// The columns (see diffColumnSchema) which diffs add to a row: the baseline
+// values and how the values changed.
+export function diffColumns({
+  baselineTotal,
+  total,
+  baselineSelf,
+  self,
+}: DiffValues): DiffColumns {
+  return {
+    baselineTotal,
+    totalDelta: total - baselineTotal,
+    totalDeltaPercent: relativeChange(baselineTotal, total),
+    baselineSelf,
+    selfDelta: self - baselineSelf,
+    selfDeltaPercent: relativeChange(baselineSelf, self),
+  };
+}
+
+// The change from `baseline` to `current` in percent of `baseline`. New
+// values have no baseline to relate to: they are +Infinity, which sorts them
+// as the largest relative growth.
+function relativeChange(baseline: number, current: number): number {
+  return changePercentage(baseline, current) ?? Infinity;
+}
+
+export function diffColumnSchema(unit: string): ColumnSchema {
+  const value = (title: string): ColumnDef => ({
+    title,
+    columnType: 'quantitative',
+    cellRenderer: (v) => (typeof v === 'number' ? displaySize(v, unit) : ''),
+  });
+  const delta = (title: string): ColumnDef => ({
+    title,
+    columnType: 'quantitative',
+    cellRenderer: (v) => renderDelta(v, (d) => displaySignedSize(d, unit)),
+  });
+  const deltaPercent = (title: string): ColumnDef => ({
+    title,
+    columnType: 'quantitative',
+    cellRenderer: (v) =>
+      renderDelta(v, (d) =>
+        d === Infinity ? 'new' : `${d > 0 ? '+' : ''}${d.toFixed(1)}%`,
+      ),
+  });
+  return {
+    baselineTotal: value('Baseline total'),
+    totalDelta: delta('Total Δ'),
+    totalDeltaPercent: deltaPercent('Total Δ %'),
+    baselineSelf: value('Baseline self'),
+    selfDelta: delta('Self Δ'),
+    selfDeltaPercent: deltaPercent('Self Δ %'),
+  };
+}
+
+// A change, colored by whether the value grew or shrank.
+function renderDelta(
+  value: SqlValue,
+  format: (delta: number) => string,
+): m.Children {
+  if (typeof value !== 'number') {
+    return '';
+  }
+  return m(
+    'span',
+    {
+      className: classNames(
+        value > 0 && 'pf-tree-explorer__delta--grew',
+        value < 0 && 'pf-tree-explorer__delta--shrank',
+      ),
+    },
+    format(value),
+  );
+}
+
+export const DIFF_TREE_INITIAL_COLUMNS: readonly Column[] = [
+  {id: 'name', field: 'name'},
+  {id: 'baselineTotal', field: 'baselineTotal'},
+  {id: 'total', field: 'total'},
+  {id: 'totalDelta', field: 'totalDelta', sort: 'DESC'},
+  {id: 'totalDeltaPercent', field: 'totalDeltaPercent'},
+  {id: 'selfDelta', field: 'selfDelta'},
+];
+
+export const DIFF_FLAT_INITIAL_COLUMNS: readonly Column[] = [
+  {id: 'name', field: 'name'},
+  {id: 'baselineSelf', field: 'baselineSelf'},
+  {id: 'self', field: 'self'},
+  {id: 'selfDelta', field: 'selfDelta', sort: 'DESC'},
+  {id: 'selfDeltaPercent', field: 'selfDeltaPercent'},
+  {id: 'totalDelta', field: 'totalDelta'},
+];
+
+// A function's values in the baseline and current trees of a diff (see
+// computeFlatFunctions).
+export interface DiffFlatFunction {
+  readonly name: string;
+  readonly self: number;
+  readonly total: number;
+  readonly baselineSelf?: number;
+  readonly baselineTotal?: number;
+}
+
+// Exports both trees' values of each function and their changes, biggest
+// self growth first.
+export function buildFlatDiffExportString(
+  flatFunctions: ReadonlyArray<DiffFlatFunction>,
+  metric: TreeExplorerMetric,
+  format: ExportFormat,
+): string {
+  const unitDisplay = getUnitDisplayName(metric.unit);
+  const columns = [
+    'name',
+    'baselineSelf',
+    'self',
+    'selfDelta',
+    'selfDeltaPercent',
+    'baselineTotal',
+    'total',
+    'totalDelta',
+    'totalDeltaPercent',
+  ];
+  const columnNames: Record<string, string> = {
+    name: metric.nameColumnLabel ?? 'Name',
+    baselineSelf: `Baseline Self ${metric.name} (${unitDisplay})`,
+    self: `Current Self ${metric.name} (${unitDisplay})`,
+    selfDelta: `Change Self ${metric.name} (${unitDisplay})`,
+    selfDeltaPercent: 'Change Self %',
+    baselineTotal: `Baseline Total ${metric.name} (${unitDisplay})`,
+    total: `Current Total ${metric.name} (${unitDisplay})`,
+    totalDelta: `Change Total ${metric.name} (${unitDisplay})`,
+    totalDeltaPercent: 'Change Total %',
+  };
+  const percentColumns = new Set(['selfDeltaPercent', 'totalDeltaPercent']);
+  const rows = flatFunctions
+    .map((fn) => ({
+      name: fn.name,
+      self: fn.self,
+      total: fn.total,
+      ...diffColumns({
+        baselineTotal: fn.baselineTotal ?? 0,
+        total: fn.total,
+        baselineSelf: fn.baselineSelf ?? 0,
+        self: fn.self,
+      }),
+    }))
+    .sort((a, b) => b.selfDelta - a.selfDelta)
+    .map((row) => {
+      const values: Record<string, string> = {};
+      for (const column of columns) {
+        const value = row[column as keyof typeof row];
+        if (typeof value !== 'number') {
+          values[column] = String(value ?? '');
+        } else if (!Number.isFinite(value)) {
+          // A relative change without a baseline value to relate to.
+          values[column] = '';
+        } else {
+          values[column] = percentColumns.has(column)
+            ? value.toFixed(2)
+            : value.toString();
+        }
+      }
+      return values;
+    });
+  switch (format) {
+    case 'tsv':
+      return formatAsTSV(columns, columnNames, rows);
+    case 'json':
+      return formatAsJSON(columns, columnNames, rows);
+    case 'markdown':
+      return formatAsMarkdown(columns, columnNames, rows);
+    default:
+      assertUnreachable(format);
+  }
+}
diff --git a/ui/src/components/tree_explorer_table_views_unittest.ts b/ui/src/components/tree_explorer_table_views_unittest.ts
index 459aa70..f84f615 100644
--- a/ui/src/components/tree_explorer_table_views_unittest.ts
+++ b/ui/src/components/tree_explorer_table_views_unittest.ts
@@ -12,7 +12,10 @@
 // See the License for the specific language governing permissions and
 // limitations under the License.
 
-import {computeFlatFunctions} from './tree_explorer_table_views';
+import {
+  buildFlatExportString,
+  computeFlatFunctions,
+} from './tree_explorer_table_views';
 import type {
   TreeExplorerData,
   TreeExplorerNode,
@@ -25,6 +28,8 @@
   readonly name: string;
   readonly selfValue: number;
   readonly cumulativeValue: number;
+  readonly baselineSelfValue?: number;
+  readonly baselineCumulativeValue?: number;
 }
 
 function makeData(nodes: ReadonlyArray<TestNode>): TreeExplorerData {
@@ -45,6 +50,24 @@
   };
 }
 
+// A diff whose nodes carry both trees' values.
+function makeDiffData(nodes: ReadonlyArray<TestNode>): TreeExplorerData {
+  const roots = nodes.filter((n) => n.parentId === -1);
+  const sum = (values: number[]) => values.reduce((a, b) => a + b, 0);
+  return {
+    ...makeData(nodes),
+    allRootsCumulativeValue: sum(roots.map((n) => n.cumulativeValue)),
+    diff: {
+      baselineUnfilteredCumulativeValue: 0,
+      baselineAllRootsCumulativeValue: sum(
+        roots.map((n) => n.baselineCumulativeValue ?? 0),
+      ),
+      layoutWidth: 0,
+      maxAbsDelta: 0,
+    },
+  };
+}
+
 function byName(functions: ReturnType<typeof computeFlatFunctions>) {
   return new Map(functions.map((f) => [f.name, f]));
 }
@@ -203,3 +226,141 @@
   expect(fns.get('Pivot')).toEqual({name: 'Pivot', self: 3, total: 10});
   expect(fns.get('Callee')).toEqual({name: 'Callee', self: 7, total: 7});
 });
+
+// current: A -> B -> A; baseline: A -> {B -> A, C}. C was removed and the
+// recursive A grew.
+const DIFF_NODES: ReadonlyArray<TestNode> = [
+  {
+    id: 1,
+    parentId: -1,
+    depth: 1,
+    name: 'A',
+    selfValue: 1,
+    cumulativeValue: 10,
+    baselineSelfValue: 1,
+    baselineCumulativeValue: 8,
+  },
+  {
+    id: 2,
+    parentId: 1,
+    depth: 2,
+    name: 'B',
+    selfValue: 2,
+    cumulativeValue: 9,
+    baselineSelfValue: 2,
+    baselineCumulativeValue: 5,
+  },
+  {
+    id: 3,
+    parentId: 2,
+    depth: 3,
+    name: 'A',
+    selfValue: 7,
+    cumulativeValue: 7,
+    baselineSelfValue: 3,
+    baselineCumulativeValue: 3,
+  },
+  {
+    id: 4,
+    parentId: 1,
+    depth: 2,
+    name: 'C',
+    selfValue: 0,
+    cumulativeValue: 0,
+    baselineSelfValue: 2,
+    baselineCumulativeValue: 2,
+  },
+];
+
+test('computeFlatFunctions aggregates the baseline values of diffs', () => {
+  const fns = byName(computeFlatFunctions(makeDiffData(DIFF_NODES)));
+  // The recursive A counts once towards the totals of either tree.
+  expect(fns.get('A')).toEqual({
+    name: 'A',
+    self: 8,
+    total: 10,
+    baselineSelf: 4,
+    baselineTotal: 8,
+  });
+  expect(fns.get('B')).toEqual({
+    name: 'B',
+    self: 2,
+    total: 9,
+    baselineSelf: 2,
+    baselineTotal: 5,
+  });
+  expect(fns.get('C')).toEqual({
+    name: 'C',
+    self: 0,
+    total: 0,
+    baselineSelf: 2,
+    baselineTotal: 2,
+  });
+});
+
+test('buildFlatExportString exports both trees of diffs', () => {
+  // X is new: it has no relative change.
+  const data = makeDiffData([
+    ...DIFF_NODES,
+    {
+      id: 5,
+      parentId: -1,
+      depth: 1,
+      name: 'X',
+      selfValue: 5,
+      cumulativeValue: 5,
+    },
+  ]);
+  const lines = buildFlatExportString(
+    data,
+    {name: 'Size', unit: 'B'},
+    'tsv',
+  ).split('\n');
+  expect(lines).toEqual([
+    [
+      'Name',
+      'Baseline Self Size (B)',
+      'Current Self Size (B)',
+      'Change Self Size (B)',
+      'Change Self %',
+      'Baseline Total Size (B)',
+      'Current Total Size (B)',
+      'Change Total Size (B)',
+      'Change Total %',
+    ].join('\t'),
+    // Biggest self growth first.
+    ['X', '0', '5', '5', '', '0', '5', '5', ''].join('\t'),
+    ['A', '4', '8', '4', '100.00', '8', '10', '2', '25.00'].join('\t'),
+    ['B', '2', '2', '0', '0.00', '5', '9', '4', '80.00'].join('\t'),
+    ['C', '2', '0', '-2', '-100.00', '2', '0', '-2', '-100.00'].join('\t'),
+  ]);
+});
+
+test('buildFlatExportString exports single trees unchanged', () => {
+  const lines = buildFlatExportString(
+    makeData([
+      {
+        id: 1,
+        parentId: -1,
+        depth: 1,
+        name: 'A',
+        selfValue: 1,
+        cumulativeValue: 3,
+      },
+      {
+        id: 2,
+        parentId: 1,
+        depth: 2,
+        name: 'B',
+        selfValue: 2,
+        cumulativeValue: 2,
+      },
+    ]),
+    {name: 'Size', unit: 'B'},
+    'tsv',
+  ).split('\n');
+  expect(lines[0]).toBe(
+    ['Name', 'Self Size (B)', 'Self %', 'Total Size (B)', 'Total %'].join('\t'),
+  );
+  expect(lines.slice(1).map((l) => l.split('\t')[0])).toEqual(['B', 'A']);
+});
diff --git a/ui/src/plugins/com.android.HeapDumpExplorer/heap_dump_page.ts b/ui/src/plugins/com.android.HeapDumpExplorer/heap_dump_page.ts
index 454fdfd..c3ff764 100644
--- a/ui/src/plugins/com.android.HeapDumpExplorer/heap_dump_page.ts
+++ b/ui/src/plugins/com.android.HeapDumpExplorer/heap_dump_page.ts
@@ -85,7 +85,8 @@
   state: NavState,
   overview: OverviewData,
 ): {tabs: TabsTab[]; actions: Map<string, TabActions>} {
-  const {engine, trace, navigateWithTabs, clearNavParam} = session;
+  const {engine, trace, navigateWithTabs, clearNavParam, baselineDump} =
+    session;
   const hideExplanationSetting = session.hideDefaultChangedHint;
   const hideHint = hideExplanationSetting.get();
   const actions = new Map<string, TabActions>();
@@ -108,17 +109,14 @@
       title: 'Flamegraph',
       content: m(FlamegraphView, {
         trace,
-        upid: activeDump.upid,
-        ts: activeDump.ts,
+        dump: dumpRef(session, activeDump),
+        baseline:
+          baselineDump === undefined
+            ? undefined
+            : dumpRef(session, baselineDump),
         state: session.flamegraphPanelState,
         onStateChange: session.setFlamegraphPanelState,
-        onShowObjects: (pathHashes, isDominator) =>
-          session.openFlamegraph({
-            pathHashes,
-            isDominator,
-            upid: activeDump.upid,
-            ts: activeDump.ts,
-          }),
+        onShowObjects: (selection) => session.openFlamegraph(selection),
       }),
     },
     {
@@ -266,6 +264,19 @@
     : `pid ${d.pid}`;
 }
 
+// Tells the dumps of a process apart by when they were taken.
+function dumpLabel(
+  session: HeapDumpExplorerSession,
+  d: queries.HeapDump,
+): string {
+  const offset = Time.diff(d.ts, session.trace.traceInfo.start);
+  return `${processLabel(d)} — ${formatDuration(session.trace, offset)}`;
+}
+
+function dumpRef(session: HeapDumpExplorerSession, d: queries.HeapDump) {
+  return {upid: d.upid, ts: d.ts, label: dumpLabel(session, d)};
+}
+
 function renderDumpSelector(session: HeapDumpExplorerSession): m.Children {
   const allDumps = session.dumps;
   const active = session.activeDump;
@@ -279,25 +290,72 @@
       PopupMenu,
       {
         trigger: m(Button, {
-          label: processLabel(active),
+          label: dumpLabel(session, active),
           icon: 'memory',
           rightIcon: 'arrow_drop_down',
           variant: ButtonVariant.Outlined,
           compact: true,
         }),
       },
-      allDumps.map((d) => {
-        const offset = Time.diff(d.ts, session.trace.traceInfo.start);
-        return m(MenuItem, {
-          label: `${processLabel(d)} — ${formatDuration(session.trace, offset)}`,
+      allDumps.map((d) =>
+        m(MenuItem, {
+          label: dumpLabel(session, d),
           active: d === active,
           onclick: () => session.selectDump(d),
-        });
-      }),
+        }),
+      ),
     ),
+    // Only the flamegraph compares dumps.
+    session.nav.view === 'flamegraph' &&
+      renderBaselineSelector(session, active),
   );
 }
 
+// Picks the dump the flamegraph compares the active dump against.
+function renderBaselineSelector(
+  session: HeapDumpExplorerSession,
+  active: queries.HeapDump,
+): m.Children {
+  const baseline = session.baselineDump;
+  return [
+    m(
+      'span',
+      {
+        class:
+          'pf-hde-dump-selector__label pf-hde-dump-selector__label--baseline',
+      },
+      'Compare with:',
+    ),
+    m(
+      PopupMenu,
+      {
+        trigger: m(Button, {
+          label: baseline === undefined ? 'None' : dumpLabel(session, baseline),
+          icon: 'difference',
+          rightIcon: 'arrow_drop_down',
+          variant: ButtonVariant.Outlined,
+          compact: true,
+          title: 'Show how the flamegraph changed from another heap dump',
+        }),
+      },
+      m(MenuItem, {
+        label: 'None',
+        active: baseline === undefined,
+        onclick: () => session.setBaselineDump(undefined),
+      }),
+      session.dumps
+        .filter((d) => d !== active)
+        .map((d) =>
+          m(MenuItem, {
+            label: dumpLabel(session, d),
+            active: d === baseline,
+            onclick: () => session.setBaselineDump(d),
+          }),
+        ),
+    ),
+  ];
+}
+
 export class HeapDumpPage implements m.ClassComponent<HeapDumpPageAttrs> {
   oncreate({attrs}: m.VnodeDOM<HeapDumpPageAttrs>) {
     attrs.session.setNavigateCallback((sub) => {
diff --git a/ui/src/plugins/com.android.HeapDumpExplorer/persisted_state.ts b/ui/src/plugins/com.android.HeapDumpExplorer/persisted_state.ts
index a456fd1..7a959e5 100644
--- a/ui/src/plugins/com.android.HeapDumpExplorer/persisted_state.ts
+++ b/ui/src/plugins/com.android.HeapDumpExplorer/persisted_state.ts
@@ -45,6 +45,8 @@
     // The selected heap dump; identifies which dump the rest of the state
     // belongs to. Restore is skipped if it no longer matches a loaded dump.
     activeDump: DUMP_REF_SCHEMA.optional(),
+    // The dump the Flamegraph tab compares the active dump against, if any.
+    baselineDump: DUMP_REF_SCHEMA.optional(),
     // The active navigation, as a stateToSubpage subpage string.
     nav: z.string().optional(),
     // Open "Flamegraph objects" drill-down tabs. The active one is not stored;
diff --git a/ui/src/plugins/com.android.HeapDumpExplorer/session.ts b/ui/src/plugins/com.android.HeapDumpExplorer/session.ts
index e199be9..2880071 100644
--- a/ui/src/plugins/com.android.HeapDumpExplorer/session.ts
+++ b/ui/src/plugins/com.android.HeapDumpExplorer/session.ts
@@ -31,20 +31,16 @@
   subpageToState,
 } from './nav_state';
 import type {OverviewData} from './types';
-import type {TreeExplorerState} from '../../widgets/tree_explorer';
+import {
+  DEFAULT_TREE_EXPLORER_COMPARISON,
+  type TreeExplorerState,
+} from '../../widgets/tree_explorer';
 import type {HdeState} from './persisted_state';
 import {
+  type FlamegraphObjectsSelection,
   METRIC_DOMINATED_OBJECT_SIZE,
   METRIC_OBJECT_SIZE,
 } from './views/flamegraph_view';
-import type {time} from '../../base/time';
-
-interface FlamegraphSelection {
-  readonly pathHashes: string;
-  readonly isDominator: boolean;
-  readonly upid: number;
-  readonly ts: time;
-}
 
 // A flamegraph drill-down tab: identity plus the title's object count (null
 // until fetched).
@@ -108,6 +104,32 @@
     );
   }
 
+  // The dump the Flamegraph tab compares the active dump against, if any.
+  get baselineDump(): queries.HeapDump | undefined {
+    const ref = this.store.state.baselineDump;
+    if (ref === undefined) return undefined;
+    const dump = this._dumps.find(
+      (d) => d.upid === ref.upid && d.ts === BigInt(ref.ts),
+    );
+    return dump === this.activeDump ? undefined : dump;
+  }
+
+  setBaselineDump(d: queries.HeapDump | undefined): void {
+    const panelState = this.flamegraphPanelState;
+    this.store.edit((s) => {
+      s.baselineDump =
+        d === undefined ? undefined : {upid: d.upid, ts: d.ts.toString()};
+      // Choosing a baseline asks for the diff against it.
+      if (d !== undefined && panelState?.comparison !== undefined) {
+        s.flamegraphPanelState = {
+          ...panelState,
+          comparison: {...panelState.comparison, show: 'DIFF'},
+        };
+      }
+    });
+    m.redraw();
+  }
+
   // Loads the dumps and reconciles them with the stored active dump. Returns
   // true if a valid permalink was restored, otherwise resets to the first dump.
   async loadDumps(): Promise<boolean> {
@@ -127,6 +149,7 @@
           first === undefined
             ? undefined
             : {upid: first.upid, ts: first.ts.toString()};
+        s.baselineDump = undefined;
         s.nav = undefined;
         s.flamegraphTabs = undefined;
         s.instanceTabs = undefined;
@@ -150,8 +173,13 @@
   private switchToDump(d: queries.HeapDump): void {
     this._overview = null;
     this._counts.clear();
+    const keepBaseline = this.baselineDump !== d;
     this.store.edit((s) => {
       s.activeDump = {upid: d.upid, ts: d.ts.toString()};
+      // A dump is not compared against itself.
+      if (!keepBaseline) {
+        s.baselineDump = undefined;
+      }
       s.flamegraphTabs = undefined;
       s.instanceTabs = undefined;
       s.flamegraphPanelState = undefined;
@@ -251,7 +279,7 @@
     };
   }
 
-  openFlamegraph(sel: FlamegraphSelection): void {
+  openFlamegraph(sel: FlamegraphObjectsSelection): void {
     const target = this._dumps.find(
       (d) => d.upid === sel.upid && d.ts === sel.ts,
     );
@@ -407,6 +435,13 @@
         pivot: `/^${pathHash}$/`,
         displayLabel: `${label} (this instance)`,
       },
+      // Path hashes are specific to a dump, so the pivot finds nothing in a
+      // baseline dump: show the active dump alone.
+      comparison: {
+        ...(this.flamegraphPanelState?.comparison ??
+          DEFAULT_TREE_EXPLORER_COMPARISON),
+        show: 'CURRENT',
+      },
     });
     this.navigate('flamegraph');
   };
diff --git a/ui/src/plugins/com.android.HeapDumpExplorer/styles.scss b/ui/src/plugins/com.android.HeapDumpExplorer/styles.scss
index 952b319..8bd0b26 100644
--- a/ui/src/plugins/com.android.HeapDumpExplorer/styles.scss
+++ b/ui/src/plugins/com.android.HeapDumpExplorer/styles.scss
@@ -88,6 +88,11 @@
 
 .pf-hde-dump-selector__label {
   color: var(--pf-color-text-hint);
+
+  // Starts the group picking the flamegraph's baseline dump.
+  &--baseline {
+    margin-left: 1rem;
+  }
 }
 
 .pf-hde-error-text {
diff --git a/ui/src/plugins/com.android.HeapDumpExplorer/views/flamegraph_view.ts b/ui/src/plugins/com.android.HeapDumpExplorer/views/flamegraph_view.ts
index 16a79e1..d12718f 100644
--- a/ui/src/plugins/com.android.HeapDumpExplorer/views/flamegraph_view.ts
+++ b/ui/src/plugins/com.android.HeapDumpExplorer/views/flamegraph_view.ts
@@ -21,9 +21,13 @@
   type TreeExplorerQueryMetric,
 } from '../../../components/tree_explorer_fetcher';
 import {Memo} from '../../../base/memo';
-import {TreeExplorerPanel} from '../../../components/tree_explorer_panel';
+import {
+  type TreeExplorerBaseline,
+  TreeExplorerPanel,
+} from '../../../components/tree_explorer_panel';
 import {
   createDefaultTreeExplorerState,
+  getTreeExplorerComparison,
   type TreeExplorerState,
   type TreeExplorerOptionalAction,
 } from '../../../widgets/tree_explorer';
@@ -44,21 +48,39 @@
 export const METRIC_OBJECT_SIZE = 'Object Size';
 export const METRIC_DOMINATED_OBJECT_SIZE = 'Dominated Object Size';
 
-interface FlamegraphViewAttrs {
-  readonly trace: Trace;
+// A heap dump, as identified in the trace, and a short name for it.
+interface DumpRef {
   readonly upid: number;
   readonly ts: time;
+  readonly label: string;
+}
+
+// The objects of a class node of a dump's tree.
+export interface FlamegraphObjectsSelection {
+  // The node's path_hash_stable (CSV).
+  readonly pathHashes: string;
+  readonly isDominator: boolean;
+  readonly upid: number;
+  readonly ts: time;
+}
+
+interface FlamegraphViewAttrs {
+  readonly trace: Trace;
+  readonly dump: DumpRef;
+  // The dump to compare `dump` against, if any.
+  readonly baseline?: DumpRef;
   readonly state: TreeExplorerState | undefined;
   readonly onStateChange: (state: TreeExplorerState) => void;
-  // Open the flamegraph-objects tab for `pathHashes` (CSV).
-  readonly onShowObjects: (pathHashes: string, isDominator: boolean) => void;
+  // Open the flamegraph-objects tab for a node of either dump's tree.
+  readonly onShowObjects: (selection: FlamegraphObjectsSelection) => void;
 }
 
 // path_hash_stable is exposed unaggregatable (and CAST to TEXT in SQL,
 // since the stdlib emits it as INT64 and the flamegraph reads
 // unaggregatable columns as STR_NULL) so it lands in `matchingColumns`
 // — that's what lets a PIVOT filter target a specific node by its hash.
-// Hidden from the tooltip via `isVisible: false`.
+// Hidden from the tooltip via `isVisible: false`. The hash is seeded with
+// the dump's upid and timestamp, so diffs must not pair nodes by it.
 const UNAGG_PROPS = [
   {name: 'root_type', displayName: 'Root Type'},
   {name: 'heap_type', displayName: 'Heap Type'},
@@ -66,6 +88,7 @@
     name: 'path_hash_stable',
     displayName: 'Path Hash',
     isVisible: () => false,
+    profileSpecific: true,
   },
 ];
 
@@ -154,7 +177,7 @@
 function buildHeapGraphMetrics(
   upid: number,
   ts: time,
-  onShowObjects: (pathHashes: string, isDominator: boolean) => void,
+  onShowObjects: (selection: FlamegraphObjectsSelection) => void,
 ): ReadonlyArray<TreeExplorerQueryMetric> {
   const showObjectsAction = (
     isDominator: boolean,
@@ -166,7 +189,7 @@
     execute: async ({properties}) => {
       const pathHashes = properties.get('path_hash_stable');
       if (pathHashes === undefined) return;
-      onShowObjects(pathHashes, isDominator);
+      onShowObjects({pathHashes, isDominator, upid, ts});
     },
   });
   return METRIC_SPECS.map((s) =>
@@ -183,9 +206,15 @@
 }
 
 export function FlamegraphView(): m.Component<FlamegraphViewAttrs> {
-  // The fetcher is created for the dump it serves and disposed by the memo when
-  // the dump changes or when this view is removed.
+  // The fetchers are created for the dumps they serve and disposed by the
+  // memos when the dumps change or when this view is removed.
   const fetcherMemo = new Memo<TreeExplorerFetcher>();
+  const baselineFetcherMemo = new Memo<TreeExplorerFetcher>();
+  const createFetcher = (attrs: FlamegraphViewAttrs, dump: DumpRef) =>
+    new TreeExplorerFetcher(
+      attrs.trace,
+      buildHeapGraphMetrics(dump.upid, dump.ts, attrs.onShowObjects),
+    );
 
   // Mirrors dev.perfetto.HeapProfile: if the heap graph is incomplete we gate
   // the flamegraph behind a dismissible warning modal. Keyed by dump so it
@@ -198,18 +227,28 @@
 
   return {
     view({attrs}) {
+      const {dump, baseline} = attrs;
       const fetcher = fetcherMemo.use({
-        key: {upid: attrs.upid, ts: attrs.ts},
-        compute: () =>
-          new TreeExplorerFetcher(
-            attrs.trace,
-            buildHeapGraphMetrics(attrs.upid, attrs.ts, attrs.onShowObjects),
-          ),
+        key: {upid: dump.upid, ts: dump.ts},
+        compute: () => createFetcher(attrs, dump),
       });
       const metrics = fetcher.metrics;
+      let panelBaseline: TreeExplorerBaseline | undefined;
+      if (baseline === undefined) {
+        baselineFetcherMemo.invalidate();
+      } else {
+        panelBaseline = {
+          fetcher: baselineFetcherMemo.use({
+            key: {upid: baseline.upid, ts: baseline.ts},
+            compute: () => createFetcher(attrs, baseline),
+          }),
+          baselineLabel: baseline.label,
+          currentLabel: dump.label,
+        };
+      }
 
       const incomplete = incompleteSlot.use({
-        key: {upid: attrs.upid, ts: attrs.ts},
+        key: {upid: dump.upid, ts: dump.ts},
         compute: async () => ({
           isIncomplete: await isHeapGraphIncomplete(attrs.trace),
           dismissed: false,
@@ -225,6 +264,14 @@
         attrs.onStateChange(state);
       }
 
+      // A pprof profile holds a single dump: the one shown, or in a diff the
+      // current one.
+      const pprofDump =
+        baseline !== undefined &&
+        getTreeExplorerComparison(state).show === 'BASELINE'
+          ? baseline
+          : dump;
+
       return [
         incomplete !== undefined &&
           incomplete.isIncomplete &&
@@ -236,17 +283,20 @@
           fetcher,
           state,
           onStateChange: attrs.onStateChange,
+          baseline: panelBaseline,
           extraDownloadItems: [
             {
               label: 'Pprof profile (.pb)',
               icon: 'file_download',
               description:
-                'Whole snapshot, converted from the trace: filters, the ' +
-                'selected measure and the view direction are not applied.',
+                'Whole snapshot' +
+                (baseline === undefined ? '' : ` of ${pprofDump.label}`) +
+                ', converted from the trace: filters, the selected measure ' +
+                'and the view direction are not applied.',
               title:
                 'Download the full profile as pprof, for use with pprof tools',
               onDownload: () =>
-                downloadPprof(attrs.trace, attrs.upid, attrs.ts),
+                downloadPprof(attrs.trace, pprofDump.upid, pprofDump.ts),
             },
           ],
         }),
@@ -254,6 +304,7 @@
     },
     onremove() {
       fetcherMemo.dispose();
+      baselineFetcherMemo.dispose();
     },
   };
 }
diff --git a/ui/src/widgets/flamegraph.ts b/ui/src/widgets/flamegraph.ts
index dc36789..fefa997 100644
--- a/ui/src/widgets/flamegraph.ts
+++ b/ui/src/widgets/flamegraph.ts
@@ -52,9 +52,23 @@
   addFilter,
   displayPercentage,
   displaySize,
+  getTreeExplorerComparison,
   getUnitDisplayName,
   metricId,
 } from './tree_explorer';
+import {
+  isPairingProperty,
+  treeExplorerDiffColor,
+  treeExplorerDiffScore,
+} from './tree_explorer_diff';
+import {
+  buildFlamegraphDiffExportString,
+  filterDiffHostActions,
+  flamegraphDiffRootLabel,
+  formatDiffStackColumns,
+  renderFlamegraphDiffNodeTooltip,
+  renderFlamegraphDiffRootTooltip,
+} from './flamegraph_diff';
 
 const LABEL_FONT_STYLE = '12px Roboto';
 const NODE_HEIGHT = 20;
@@ -423,7 +437,7 @@
           this.attrs.data,
           this.zoomRegion ?? {
             queryXStart: 0,
-            queryXEnd: this.attrs.data.allRootsCumulativeValue,
+            queryXEnd: layoutWidth(this.attrs.data),
             type: 'ROOT',
           },
           size.width,
@@ -447,9 +461,38 @@
     const yStart = canvasRect.top;
     const yEnd = canvasRect.bottom;
 
-    const {allRootsCumulativeValue, unfilteredCumulativeValue, nodes} =
+    const {allRootsCumulativeValue, unfilteredCumulativeValue, nodes, diff} =
       this.attrs.data;
     const unit = ensureExists(this.selectedMetric).unit;
+    const rootLabel =
+      diff === undefined
+        ? `root: ${displaySize(allRootsCumulativeValue, unit)} (${displayPercentage(
+            allRootsCumulativeValue,
+            unfilteredCumulativeValue,
+          )})`
+        : flamegraphDiffRootLabel(
+            diff.baselineAllRootsCumulativeValue,
+            allRootsCumulativeValue,
+            unit,
+          );
+    const diffColor = getTreeExplorerComparison(this.attrs.state).color;
+    // A diff colors nodes by how their value changed instead of by name.
+    const colorSchemeOf = (
+      name: string,
+      greyed: boolean,
+      baseline: number,
+      current: number,
+    ) =>
+      diff === undefined || greyed
+        ? getFlamegraphColorScheme(name, greyed)
+        : getDiffColorScheme(
+            treeExplorerDiffScore(
+              baseline,
+              current,
+              diffColor,
+              diff.maxAbsDelta,
+            ),
+          );
 
     ctx.font = LABEL_FONT_STYLE;
     ctx.textBaseline = 'middle';
@@ -472,22 +515,29 @@
       }
 
       const hover = isIntersecting(this.hoveredX, this.hoveredY, node);
+      const greyed = state === 'PARTIAL';
       let name: string;
       let colorScheme;
       if (source.kind === 'ROOT') {
-        const val = displaySize(allRootsCumulativeValue, unit);
-        const percent = displayPercentage(
+        name = rootLabel;
+        colorScheme = colorSchemeOf(
+          'root',
+          greyed,
+          diff?.baselineAllRootsCumulativeValue ?? 0,
           allRootsCumulativeValue,
-          unfilteredCumulativeValue,
         );
-        name = `root: ${val} (${percent})`;
-        colorScheme = getFlamegraphColorScheme('root', state === 'PARTIAL');
       } else if (source.kind === 'MERGED') {
         name = '(merged)';
-        colorScheme = getFlamegraphColorScheme(name, state === 'PARTIAL');
+        colorScheme = colorSchemeOf(name, greyed, 0, 0);
       } else {
-        name = nodes[source.queryIdx].name;
-        colorScheme = getFlamegraphColorScheme(name, state === 'PARTIAL');
+        const queryNode = nodes[source.queryIdx];
+        name = queryNode.name;
+        colorScheme = colorSchemeOf(
+          name,
+          greyed,
+          queryNode.baselineCumulativeValue ?? 0,
+          queryNode.cumulativeValue,
+        );
       }
       const highlighted =
         source.kind === 'NODE' &&
@@ -574,9 +624,19 @@
       unfilteredCumulativeValue,
       nodeActions,
       rootActions,
+      diff,
     } = ensureExists(this.attrs.data);
     const {unit, nameColumnLabel} = ensureExists(this.selectedMetric);
     if (source.kind === 'ROOT') {
+      const actions = this.renderActionsMenu(rootActions, new Map());
+      if (diff !== undefined) {
+        return renderFlamegraphDiffRootTooltip(
+          unit,
+          diff.baselineAllRootsCumulativeValue,
+          allRootsCumulativeValue,
+          actions,
+        );
+      }
       const val = displaySize(allRootsCumulativeValue, unit);
       const percent = displayPercentage(
         allRootsCumulativeValue,
@@ -589,7 +649,7 @@
           '.tooltip-text-line',
           m('.tooltip-bold-text', 'Cumulative:'),
           m('.tooltip-text', `${val}, ${percent}`),
-          this.renderActionsMenu(rootActions, new Map()),
+          actions,
         ),
       );
     }
@@ -634,24 +694,32 @@
         m('.tooltip-bold-text', `${nameLabel}:`),
         m('.tooltip-text', name),
       ),
-      m(
-        '.tooltip-text-line',
-        m('.tooltip-bold-text', 'Cumulative:'),
-        m(
-          '.tooltip-text',
-          `${displaySize(cumulativeValue, unit)} (${percentText})`,
-        ),
-      ),
-      m(
-        '.tooltip-text-line',
-        m('.tooltip-bold-text', 'Self:'),
-        m(
-          '.tooltip-text',
-          `${displaySize(selfValue, unit)} (${selfPercentText})`,
-        ),
-      ),
+      diff === undefined
+        ? [
+            m(
+              '.tooltip-text-line',
+              m('.tooltip-bold-text', 'Cumulative:'),
+              m(
+                '.tooltip-text',
+                `${displaySize(cumulativeValue, unit)} (${percentText})`,
+              ),
+            ),
+            m(
+              '.tooltip-text-line',
+              m('.tooltip-bold-text', 'Self:'),
+              m(
+                '.tooltip-text',
+                `${displaySize(selfValue, unit)} (${selfPercentText})`,
+              ),
+            ),
+          ]
+        : renderFlamegraphDiffNodeTooltip(unit, nodes[queryIdx]),
       Array.from(properties, ([_, value]) => {
-        if (value.isVisible) {
+        // In a diff, only the pairing properties are those of both trees.
+        if (
+          value.isVisible &&
+          (diff === undefined || isPairingProperty(value))
+        ) {
           return m(
             '.tooltip-text-line',
             m('.tooltip-bold-text', value.displayName + ':'),
@@ -675,11 +743,16 @@
   ) {
     const {properties} = node;
     const builtIn = this.buildNodeActions(source, name, node);
+    const hostActions = filterDiffHostActions(
+      nodeActions,
+      this.attrs.data?.diff !== undefined,
+      node.cumulativeValue,
+    );
 
     const isFlat = (a: TreeExplorerOptionalAction) =>
       a.execute !== undefined &&
       (a.subActions === undefined || a.subActions.length === 0);
-    const embedderFlat: NodeAction[] = nodeActions.filter(isFlat).map((a) => ({
+    const embedderFlat: NodeAction[] = hostActions.filter(isFlat).map((a) => ({
       label: a.name,
       icon: a.icon ?? 'open_in_new',
       description: a.description,
@@ -692,7 +765,7 @@
         this.tooltipPos = undefined;
       },
     }));
-    const embedderComplex = nodeActions
+    const embedderComplex = hostActions
       .filter((a) => !isFlat(a))
       .map((a) => this.renderMenuItem(a, properties, node));
 
@@ -943,7 +1016,9 @@
     node: TreeExplorerNode,
     withDetails: boolean,
   ): string {
-    const {nodes, unfilteredCumulativeValue} = ensureExists(this.attrs.data);
+    const {nodes, unfilteredCumulativeValue, diff} = ensureExists(
+      this.attrs.data,
+    );
     const metric = ensureExists(this.selectedMetric);
     const view = this.attrs.state.view;
 
@@ -968,11 +1043,15 @@
       return stack.map((n) => n.name).join('\n');
     }
 
-    // Collect all unique property keys, separated by aggregatable status
+    // Collect all unique property keys, separated by aggregatable status. In
+    // a diff, only the pairing properties are those of both trees.
     const unaggKeys: string[] = [];
     const aggKeys: string[] = [];
     for (const entry of stack) {
       for (const [key, prop] of entry.properties) {
+        if (diff !== undefined && !isPairingProperty(prop)) {
+          continue;
+        }
         if (prop.isAggregatable) {
           if (!aggKeys.includes(key)) {
             aggKeys.push(key);
@@ -1032,10 +1111,14 @@
       for (const key of unaggKeys) {
         cols.push(entry.properties.get(key)?.value ?? '');
       }
-      cols.push(
-        `${cumulative} (${cumulativePercent})`,
-        `${self} (${selfPercent})`,
-      );
+      if (diff === undefined) {
+        cols.push(
+          `${cumulative} (${cumulativePercent})`,
+          `${self} (${selfPercent})`,
+        );
+      } else {
+        cols.push(...formatDiffStackColumns(entry, metric.unit));
+      }
       for (const key of aggKeys) {
         cols.push(entry.properties.get(key)?.value ?? '');
       }
@@ -1060,6 +1143,9 @@
   metric: TreeExplorerMetric,
   format: ExportFormat,
 ): string {
+  if (data.diff !== undefined) {
+    return buildFlamegraphDiffExportString(data, metric, format);
+  }
   const {nodes} = data;
   const unitDisplay = getUnitDisplayName(metric.unit);
 
@@ -1122,11 +1208,18 @@
   }
 }
 
+// The extent of the x axis the nodes are laid out on.
+function layoutWidth(data: TreeExplorerData): number {
+  return data.diff?.layoutWidth ?? data.allRootsCumulativeValue;
+}
+
 function computeRenderNodes(
-  {nodes, allRootsCumulativeValue, minDepth}: TreeExplorerData,
+  data: TreeExplorerData,
   zoomRegion: ZoomRegion,
   canvasWidth: number,
 ): ReadonlyArray<RenderNode> {
+  const {nodes, minDepth} = data;
+  const rootQueryXEnd = layoutWidth(data);
   const renderNodes: RenderNode[] = [];
 
   const mergedKeyToX = new Map<string, number>();
@@ -1138,12 +1231,11 @@
     source: {
       kind: 'ROOT',
       queryXStart: 0,
-      queryXEnd: allRootsCumulativeValue,
+      queryXEnd: rootQueryXEnd,
       type: 'ROOT',
     },
     state:
-      zoomRegion.queryXStart === 0 &&
-      zoomRegion.queryXEnd === allRootsCumulativeValue
+      zoomRegion.queryXStart === 0 && zoomRegion.queryXEnd === rootQueryXEnd
         ? 'NORMAL'
         : 'PARTIAL',
   });
@@ -1152,6 +1244,11 @@
   for (let i = 0; i < nodes.length; i++) {
     const {id, parentId, depth, xStart: qXStart, xEnd: qXEnd} = nodes[i];
     assertTrue(depth !== 0);
+    // Diff nodes which take no space (the nodes missing from the tree the
+    // widths are taken from) are not drawn.
+    if (data.diff !== undefined && qXEnd <= qXStart) {
+      continue;
+    }
 
     const depthMatchingZoom = isDepthMatchingZoom(depth, zoomRegion);
     if (
@@ -1162,7 +1259,7 @@
     }
     const queryXPerPx = depthMatchingZoom
       ? zoomQueryWidth / canvasWidth
-      : allRootsCumulativeValue / canvasWidth;
+      : rootQueryXEnd / canvasWidth;
     const relativeXStart = depthMatchingZoom
       ? qXStart - zoomRegion.queryXStart
       : qXStart;
@@ -1352,3 +1449,18 @@
   colorSchemeCache.set(name, scheme);
   return scheme;
 }
+
+// Cache for the color schemes of diff nodes, by score in percent.
+const diffColorSchemeCache = new Map<number, ColorScheme>();
+
+// The color scheme of a diff node, by its treeExplorerDiffScore.
+function getDiffColorScheme(score: number): ColorScheme {
+  const percent = Math.round(score * 100);
+  let scheme = diffColorSchemeCache.get(percent);
+  if (scheme === undefined) {
+    const base = treeExplorerDiffColor(percent / 100);
+    scheme = makeColorScheme(base, base.darken(10));
+    diffColorSchemeCache.set(percent, scheme);
+  }
+  return scheme;
+}
diff --git a/ui/src/widgets/flamegraph_diff.scss b/ui/src/widgets/flamegraph_diff.scss
new file mode 100644
index 0000000..188ac45
--- /dev/null
+++ b/ui/src/widgets/flamegraph_diff.scss
@@ -0,0 +1,52 @@
+// Copyright (C) 2026 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Baseline, current and change of a node's values, in the tooltips of diffs.
+.pf-flamegraph-diff-table {
+  margin-top: 4px;
+  border-collapse: collapse;
+  cursor: text;
+
+  th,
+  td {
+    padding: 2px 0 2px 16px;
+    white-space: nowrap;
+
+    &:first-child {
+      padding-left: 0;
+    }
+  }
+
+  th {
+    font-weight: 600;
+    text-align: left;
+  }
+
+  thead th,
+  td {
+    text-align: right;
+  }
+
+  td {
+    font-variant-numeric: tabular-nums;
+  }
+
+  &__change--grew {
+    color: var(--pf-color-danger);
+  }
+
+  &__change--shrank {
+    color: var(--pf-color-success);
+  }
+}
diff --git a/ui/src/widgets/flamegraph_diff.ts b/ui/src/widgets/flamegraph_diff.ts
new file mode 100644
index 0000000..1ce99b7
--- /dev/null
+++ b/ui/src/widgets/flamegraph_diff.ts
@@ -0,0 +1,246 @@
+// Copyright (C) 2026 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+import './flamegraph_diff.scss';
+import m from 'mithril';
+import {assertUnreachable} from '../base/assert';
+import {classNames} from '../base/classnames';
+import type {ExportFormat} from './export_button';
+import {
+  formatAsJSON,
+  formatAsMarkdown,
+  formatAsTSV,
+} from '../base/export_formatters';
+import {
+  type TreeExplorerData,
+  type TreeExplorerMetric,
+  type TreeExplorerNode,
+  type TreeExplorerOptionalAction,
+  displaySize,
+  getUnitDisplayName,
+} from './tree_explorer';
+import {
+  displayChange,
+  displayChangePercentage,
+  displaySignedSize,
+  isPairingProperty,
+} from './tree_explorer_diff';
+
+export function flamegraphDiffRootLabel(
+  baselineCumulative: number,
+  currentCumulative: number,
+  unit: string,
+): string {
+  return `root: ${displayChange(baselineCumulative, currentCumulative, unit)}`;
+}
+
+// The values of a node (or of the root) in the baseline and current trees of
+// a diff, and how they changed.
+function renderDiffTable(
+  unit: string,
+  rows: ReadonlyArray<{
+    readonly label: string;
+    readonly baseline: number;
+    readonly current: number;
+  }>,
+): m.Children {
+  return m(
+    'table.pf-flamegraph-diff-table',
+    m(
+      'thead',
+      m(
+        'tr',
+        m('th'),
+        m('th', 'Baseline'),
+        m('th', 'Current'),
+        m('th', 'Change'),
+      ),
+    ),
+    m(
+      'tbody',
+      rows.map(({label, baseline, current}) => {
+        const delta = current - baseline;
+        return m(
+          'tr',
+          m('th', label),
+          m('td', displaySize(baseline, unit)),
+          m('td', displaySize(current, unit)),
+          m(
+            'td',
+            {
+              className: classNames(
+                delta > 0 && 'pf-flamegraph-diff-table__change--grew',
+                delta < 0 && 'pf-flamegraph-diff-table__change--shrank',
+              ),
+            },
+            `${displaySignedSize(delta, unit)} (${displayChangePercentage(
+              baseline,
+              current,
+            )})`,
+          ),
+        );
+      }),
+    ),
+  );
+}
+
+export function renderFlamegraphDiffRootTooltip(
+  unit: string,
+  baselineAllRootsCumulativeValue: number,
+  allRootsCumulativeValue: number,
+  actionsMenu: m.Children,
+): m.Children {
+  return m(
+    'div',
+    m('.tooltip-text-line', m('.tooltip-bold-text', 'root'), actionsMenu),
+    renderDiffTable(unit, [
+      {
+        label: 'Cumulative',
+        baseline: baselineAllRootsCumulativeValue,
+        current: allRootsCumulativeValue,
+      },
+    ]),
+  );
+}
+
+export function renderFlamegraphDiffNodeTooltip(
+  unit: string,
+  node: TreeExplorerNode,
+): m.Children {
+  return renderDiffTable(unit, [
+    {
+      label: 'Cumulative',
+      baseline: node.baselineCumulativeValue ?? 0,
+      current: node.cumulativeValue,
+    },
+    {
+      label: 'Self',
+      baseline: node.baselineSelfValue ?? 0,
+      current: node.selfValue,
+    },
+  ]);
+}
+
+// The host's actions act on the current tree of a diff, which the nodes
+// only the baseline tree has are missing from.
+export function filterDiffHostActions(
+  nodeActions: ReadonlyArray<TreeExplorerOptionalAction>,
+  isDiff: boolean,
+  cumulativeValue: number,
+): ReadonlyArray<TreeExplorerOptionalAction> {
+  if (isDiff && cumulativeValue === 0) {
+    return [];
+  }
+  return nodeActions;
+}
+
+export function formatDiffStackColumns(
+  node: TreeExplorerNode,
+  unit: string,
+): [string, string] {
+  return [
+    displayChange(
+      node.baselineCumulativeValue ?? 0,
+      node.cumulativeValue,
+      unit,
+    ),
+    displayChange(node.baselineSelfValue ?? 0, node.selfValue, unit),
+  ];
+}
+
+// A diff exports each value in the baseline and current trees and its
+// change, and only the pairing properties, i.e. those of both trees.
+export function buildFlamegraphDiffExportString(
+  data: TreeExplorerData,
+  metric: TreeExplorerMetric,
+  format: ExportFormat,
+): string {
+  const {nodes} = data;
+  const unitDisplay = getUnitDisplayName(metric.unit);
+
+  const unaggKeys: string[] = [];
+  const aggKeys: string[] = [];
+  const propDisplayNames = new Map<string, string>();
+  for (const node of nodes) {
+    for (const [key, prop] of node.properties) {
+      if (!isPairingProperty(prop)) {
+        continue;
+      }
+      const keys = prop.isAggregatable ? aggKeys : unaggKeys;
+      if (!keys.includes(key)) {
+        keys.push(key);
+        propDisplayNames.set(key, prop.displayName);
+      }
+    }
+  }
+
+  const columns = [
+    'id',
+    'parentId',
+    'depth',
+    'name',
+    ...unaggKeys,
+    'baselineCumulativeValue',
+    'cumulativeValue',
+    'cumulativeDelta',
+    'baselineSelfValue',
+    'selfValue',
+    'selfDelta',
+    ...aggKeys,
+  ];
+  const columnNames: Record<string, string> = {
+    ...Object.fromEntries(propDisplayNames),
+    id: 'Id',
+    parentId: 'Parent Id',
+    depth: 'Depth',
+    name: metric.nameColumnLabel ?? 'Name',
+    cumulativeValue: `Current Cumulative ${metric.name} (${unitDisplay})`,
+    selfValue: `Current Self ${metric.name} (${unitDisplay})`,
+    baselineCumulativeValue: `Baseline Cumulative ${metric.name} (${unitDisplay})`,
+    cumulativeDelta: `Change Cumulative ${metric.name} (${unitDisplay})`,
+    baselineSelfValue: `Baseline Self ${metric.name} (${unitDisplay})`,
+    selfDelta: `Change Self ${metric.name} (${unitDisplay})`,
+  };
+  const rows = nodes.map((n) => {
+    const baselineCumulative = n.baselineCumulativeValue ?? 0;
+    const baselineSelf = n.baselineSelfValue ?? 0;
+    const row: Record<string, string> = {
+      id: n.id.toString(),
+      parentId: n.parentId.toString(),
+      depth: n.depth.toString(),
+      name: n.name,
+      baselineCumulativeValue: baselineCumulative.toString(),
+      cumulativeValue: n.cumulativeValue.toString(),
+      cumulativeDelta: (n.cumulativeValue - baselineCumulative).toString(),
+      baselineSelfValue: baselineSelf.toString(),
+      selfValue: n.selfValue.toString(),
+      selfDelta: (n.selfValue - baselineSelf).toString(),
+    };
+    for (const key of [...unaggKeys, ...aggKeys]) {
+      row[key] = n.properties.get(key)?.value ?? '';
+    }
+    return row;
+  });
+
+  switch (format) {
+    case 'tsv':
+      return formatAsTSV(columns, columnNames, rows);
+    case 'json':
+      return formatAsJSON(columns, columnNames, rows);
+    case 'markdown':
+      return formatAsMarkdown(columns, columnNames, rows);
+    default:
+      assertUnreachable(format);
+  }
+}
diff --git a/ui/src/widgets/flamegraph_unittest.ts b/ui/src/widgets/flamegraph_unittest.ts
new file mode 100644
index 0000000..3cf1c0b
--- /dev/null
+++ b/ui/src/widgets/flamegraph_unittest.ts
@@ -0,0 +1,194 @@
+// Copyright (C) 2026 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+import {buildFlamegraphExportString} from './flamegraph';
+import type {
+  TreeExplorerData,
+  TreeExplorerNode,
+  TreeExplorerPropertyDefinition,
+} from './tree_explorer';
+import {buildTreeExplorerDiff} from './tree_explorer_diff';
+
+const METRIC = {name: 'Size', unit: 'B'};
+
+// A single root with one child per entry of `children` (name, self value).
+function makeTree(
+  rootSelf: number,
+  children: ReadonlyArray<[string, number]>,
+): TreeExplorerData {
+  const total = children.reduce((sum, [_, self]) => sum + self, rootSelf);
+  const node = (
+    id: number,
+    parentId: number,
+    depth: number,
+    name: string,
+    self: number,
+    cumulative: number,
+  ): TreeExplorerNode => ({
+    id,
+    parentId,
+    depth,
+    name,
+    selfValue: self,
+    cumulativeValue: cumulative,
+    properties: new Map(),
+    xStart: 0,
+    xEnd: 0,
+  });
+  return {
+    nodes: [
+      node(0, -1, 1, 'A', rootSelf, total),
+      ...children.map(([name, self], i) => node(i + 1, 0, 2, name, self, self)),
+    ],
+    unfilteredCumulativeValue: total,
+    allRootsCumulativeValue: total,
+    minDepth: 0,
+    maxDepth: children.length > 0 ? 2 : 1,
+    nodeActions: [],
+    rootActions: [],
+  };
+}
+
+test('buildFlamegraphExportString exports single trees', () => {
+  const lines = buildFlamegraphExportString(
+    makeTree(1, [['B', 4]]),
+    METRIC,
+    'tsv',
+  ).split('\n');
+  expect(lines).toEqual([
+    'Id\tParent Id\tDepth\tName\tCumulative Size (B)\tSelf Size (B)',
+    '0\t-1\t1\tA\t5\t1',
+    '1\t0\t2\tB\t4\t4',
+  ]);
+});
+
+test('buildFlamegraphExportString exports both trees of diffs', () => {
+  const current = makeTree(1, [
+    ['B', 4],
+    ['C', 5],
+  ]);
+  const baseline = makeTree(1, [
+    ['B', 2],
+    ['D', 3],
+  ]);
+  const lines = buildFlamegraphExportString(
+    buildTreeExplorerDiff(current, baseline, 'COMBINED'),
+    METRIC,
+    'tsv',
+  ).split('\n');
+  expect(lines).toEqual([
+    [
+      'Id',
+      'Parent Id',
+      'Depth',
+      'Name',
+      'Baseline Cumulative Size (B)',
+      'Current Cumulative Size (B)',
+      'Change Cumulative Size (B)',
+      'Baseline Self Size (B)',
+      'Current Self Size (B)',
+      'Change Self Size (B)',
+    ].join('\t'),
+    '0\t-1\t1\tA\t6\t10\t4\t1\t1\t0',
+    '1\t0\t2\tB\t2\t4\t2\t2\t4\t2',
+    '2\t0\t2\tC\t0\t5\t5\t0\t5\t5',
+    // Only in the baseline.
+    '3\t0\t2\tD\t3\t0\t-3\t3\t0\t-3',
+  ]);
+});
+
+// A single node with a grouping, a profile-specific and an aggregatable
+// property.
+function makeNodeWithProperties(
+  value: number,
+  hash: string,
+  count: number,
+): TreeExplorerData {
+  const property = (
+    displayName: string,
+    propertyValue: string,
+    isAggregatable: boolean,
+    profileSpecific?: boolean,
+  ): TreeExplorerPropertyDefinition => ({
+    displayName,
+    value: propertyValue,
+    isVisible: true,
+    isAggregatable,
+    profileSpecific,
+  });
+  return {
+    nodes: [
+      {
+        id: 0,
+        parentId: -1,
+        depth: 1,
+        name: 'A',
+        selfValue: value,
+        cumulativeValue: value,
+        properties: new Map([
+          ['heap', property('Heap', 'app', false)],
+          ['hash', property('Hash', hash, false, true)],
+          ['count', property('Count', `${count}`, true)],
+        ]),
+        xStart: 0,
+        xEnd: value,
+      },
+    ],
+    unfilteredCumulativeValue: value,
+    allRootsCumulativeValue: value,
+    minDepth: 0,
+    maxDepth: 1,
+    nodeActions: [],
+    rootActions: [],
+  };
+}
+
+test('buildFlamegraphExportString exports properties of single trees', () => {
+  const lines = buildFlamegraphExportString(
+    makeNodeWithProperties(30, 'c1', 3),
+    METRIC,
+    'tsv',
+  ).split('\n');
+  expect(lines).toEqual([
+    'Id\tParent Id\tDepth\tName\tHeap\tHash\tCumulative Size (B)\t' +
+      'Self Size (B)\tCount',
+    '0\t-1\t1\tA\tapp\tc1\t30\t30\t3',
+  ]);
+});
+
+test('buildFlamegraphExportString exports only properties of both trees of diffs', () => {
+  const diff = buildTreeExplorerDiff(
+    makeNodeWithProperties(30, 'c1', 3),
+    makeNodeWithProperties(10, 'b1', 1),
+    'COMBINED',
+  );
+  const lines = buildFlamegraphExportString(diff, METRIC, 'tsv').split('\n');
+  // The hash and count differ between the trees, so neither is exported.
+  expect(lines).toEqual([
+    [
+      'Id',
+      'Parent Id',
+      'Depth',
+      'Name',
+      'Heap',
+      'Baseline Cumulative Size (B)',
+      'Current Cumulative Size (B)',
+      'Change Cumulative Size (B)',
+      'Baseline Self Size (B)',
+      'Current Self Size (B)',
+      'Change Self Size (B)',
+    ].join('\t'),
+    '0\t-1\t1\tA\tapp\t10\t30\t20\t10\t30\t20',
+  ]);
+});
diff --git a/ui/src/widgets/tree_explorer.ts b/ui/src/widgets/tree_explorer.ts
index 06e0fe4..4f2cb6f 100644
--- a/ui/src/widgets/tree_explorer.ts
+++ b/ui/src/widgets/tree_explorer.ts
@@ -57,6 +57,10 @@
   value: string;
   isVisible: boolean;
   isAggregatable: boolean;
+  // The value only has meaning within the tree it was read from (e.g. an id,
+  // or a hash of one), so it never matches between two trees: diffs pair
+  // nodes ignoring it.
+  profileSpecific?: boolean;
 };
 
 export interface TreeExplorerNode {
@@ -71,6 +75,11 @@
   readonly marker?: string;
   readonly xStart: number;
   readonly xEnd: number;
+  // Only set in a diff (see TreeExplorerData.diff): the node's values in the
+  // baseline tree, while selfValue/cumulativeValue hold its values in the
+  // current tree. A node missing from one of the trees has 0 values there.
+  readonly baselineSelfValue?: number;
+  readonly baselineCumulativeValue?: number;
 }
 
 export interface TreeExplorerData {
@@ -81,6 +90,23 @@
   readonly maxDepth: number;
   readonly nodeActions: ReadonlyArray<TreeExplorerOptionalAction>;
   readonly rootActions: ReadonlyArray<TreeExplorerOptionalAction>;
+  // Set when the data is the diff of a current tree against a baseline tree
+  // (see tree_explorer_diff.ts). The fields above then describe the current
+  // tree, and every node carries its baseline values too.
+  readonly diff?: TreeExplorerDiffSummary;
+}
+
+export interface TreeExplorerDiffSummary {
+  // The baseline tree's unfilteredCumulativeValue / allRootsCumulativeValue.
+  readonly baselineUnfilteredCumulativeValue: number;
+  readonly baselineAllRootsCumulativeValue: number;
+  // Extent of the x axis the nodes' xStart/xEnd are laid out on. Unlike in a
+  // single tree, node widths need not be the current values (see
+  // TreeExplorerComparison.width).
+  readonly layoutWidth: number;
+  // Largest absolute cumulative change of any node or of the root: the scale
+  // of ABSOLUTE diff coloring.
+  readonly maxAbsDelta: number;
 }
 
 const TREE_EXPLORER_FILTER_SCHEMA = z
@@ -119,6 +145,36 @@
 
 export type TreeExplorerView = z.infer<typeof TREE_EXPLORER_VIEW_SCHEMA>;
 
+// How a tree is compared against a baseline tree. Only has an effect when the
+// host supplies a baseline (see TreeExplorerPanelAttrs.baseline).
+const TREE_EXPLORER_COMPARISON_SCHEMA = z
+  .object({
+    // What the views show: the diff of the current tree against the
+    // baseline, or one of the two trees on its own.
+    show: z.enum(['DIFF', 'CURRENT', 'BASELINE']),
+    // What the widths of diff nodes are proportional to: the sum of both
+    // trees' values, so nodes of either tree are visible, or the values of a
+    // single tree, which hides the nodes only the other tree has.
+    width: z.enum(['COMBINED', 'CURRENT', 'BASELINE']),
+    // What the colors of diff nodes encode: the change relative to the
+    // largest change in the tree (ABSOLUTE), or relative to the node's own
+    // baseline value (RELATIVE).
+    color: z.enum(['ABSOLUTE', 'RELATIVE']),
+  })
+  .readonly();
+
+export type TreeExplorerComparison = z.infer<
+  typeof TREE_EXPLORER_COMPARISON_SCHEMA
+>;
+export type TreeExplorerDiffWidth = TreeExplorerComparison['width'];
+export type TreeExplorerDiffColor = TreeExplorerComparison['color'];
+
+export const DEFAULT_TREE_EXPLORER_COMPARISON: TreeExplorerComparison = {
+  show: 'DIFF',
+  width: 'COMBINED',
+  color: 'ABSOLUTE',
+};
+
 export const TREE_EXPLORER_STATE_SCHEMA = z
   .object({
     selectedMetricId: z.string().readonly(),
@@ -129,12 +185,21 @@
     displayMode: z.enum(['flamegraph', 'tree', 'flat']).default('flamegraph'),
     filters: z.array(TREE_EXPLORER_FILTER_SCHEMA),
     view: TREE_EXPLORER_VIEW_SCHEMA,
+    // Undefined means DEFAULT_TREE_EXPLORER_COMPARISON: read it through
+    // getTreeExplorerComparison().
+    comparison: TREE_EXPLORER_COMPARISON_SCHEMA.optional(),
   })
   .readonly();
 
 export type TreeExplorerState = z.infer<typeof TREE_EXPLORER_STATE_SCHEMA>;
 export type TreeExplorerDisplayMode = TreeExplorerState['displayMode'];
 
+export function getTreeExplorerComparison(
+  state: TreeExplorerState,
+): TreeExplorerComparison {
+  return state.comparison ?? DEFAULT_TREE_EXPLORER_COMPARISON;
+}
+
 export interface TreeExplorerMetric {
   // Stable identity used in persisted state. Defaults to `name`.
   readonly id?: string;
@@ -275,10 +340,7 @@
     return state;
   }
   return {
-    filters: state.filters,
-    view: state.view,
-    addedMetricIds: state.addedMetricIds,
-    displayMode: state.displayMode,
+    ...state,
     selectedMetricId: metricId(metrics[0]),
   };
 }
diff --git a/ui/src/widgets/tree_explorer_diff.ts b/ui/src/widgets/tree_explorer_diff.ts
new file mode 100644
index 0000000..3a89b9b
--- /dev/null
+++ b/ui/src/widgets/tree_explorer_diff.ts
@@ -0,0 +1,381 @@
+// Copyright (C) 2026 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+// Diffing of tree explorer trees: pairs up the nodes of a current and a
+// baseline tree (both fetched with the same metric, filters and view), lays
+// the union out as a single flamegraph, and scores and colors every node by
+// how it changed, pprof-style.
+
+import {assertUnreachable} from '../base/assert';
+import {type Color, HSLColor, rgbToHsl} from '../base/color';
+import {
+  type TreeExplorerData,
+  type TreeExplorerDiffColor,
+  type TreeExplorerDiffWidth,
+  type TreeExplorerNode,
+  type TreeExplorerPropertyDefinition,
+  displaySize,
+} from './tree_explorer';
+
+// A node of the union of the two trees: the node of either tree, or both
+// paired up, at one position in the tree.
+interface PairedNode {
+  // Unique among the paired nodes; keys their children.
+  readonly index: number;
+  readonly parent?: PairedNode;
+  readonly depth: number;
+  readonly children: PairedNode[];
+  // The first node of each tree which landed here (there is at most one
+  // unless a tree has siblings its pairing key cannot tell apart).
+  current?: TreeExplorerNode;
+  baseline?: TreeExplorerNode;
+  currentSelf: number;
+  currentCumulative: number;
+  baselineSelf: number;
+  baselineCumulative: number;
+  width: number;
+  x: number;
+  // Position in the output.
+  id: number;
+}
+
+// Builds the diff of `current` against `baseline`: the union of their nodes,
+// where a node of one tree is paired with the node of the other tree at the
+// same position, i.e. with the same name and grouping (unaggregatable)
+// properties, under paired parents. Profile-specific properties (see
+// TreeExplorerPropertyDefinition) are not compared.
+//
+// Nodes carry the current values in selfValue/cumulativeValue and the
+// baseline ones in baselineSelfValue/baselineCumulativeValue, with 0 for the
+// tree a node is missing from. They are laid out like the flamegraph operator
+// does (widest siblings first, one strip per direction, parents before
+// children) with widths per `width`, so nodes of zero width are laid out but
+// take no space.
+//
+// Both inputs must list parents before children, as TreeExplorerFetcher
+// does. The result takes its totals and actions from `current`.
+export function buildTreeExplorerDiff(
+  current: TreeExplorerData,
+  baseline: TreeExplorerData,
+  width: TreeExplorerDiffWidth,
+): TreeExplorerData {
+  // Paired nodes by parent index and pairing key. Roots are keyed under a
+  // virtual parent per direction: in a PIVOT view both strips have the same
+  // roots.
+  const pairedByKey = new Map<string, PairedNode>();
+  const downwardRoots: PairedNode[] = [];
+  const upwardRoots: PairedNode[] = [];
+
+  const pairInto = (data: TreeExplorerData, isCurrent: boolean) => {
+    const pairedNodes = new Map<number, PairedNode>();
+    for (const node of data.nodes) {
+      const parent =
+        node.parentId === -1 ? undefined : pairedNodes.get(node.parentId);
+      if (node.parentId !== -1 && parent === undefined) {
+        // Only reachable if parents are not listed first.
+        continue;
+      }
+      const parentIndex = parent?.index ?? (node.depth < 0 ? -2 : -1);
+      const key = `${parentIndex}\u0000${pairingKey(node)}`;
+      let paired = pairedByKey.get(key);
+      if (paired === undefined) {
+        paired = {
+          index: pairedByKey.size,
+          parent,
+          depth: node.depth,
+          children: [],
+          currentSelf: 0,
+          currentCumulative: 0,
+          baselineSelf: 0,
+          baselineCumulative: 0,
+          width: 0,
+          x: 0,
+          id: -1,
+        };
+        pairedByKey.set(key, paired);
+        if (parent !== undefined) {
+          parent.children.push(paired);
+        } else if (node.depth < 0) {
+          upwardRoots.push(paired);
+        } else {
+          downwardRoots.push(paired);
+        }
+      }
+      if (isCurrent) {
+        paired.current ??= node;
+        paired.currentSelf += node.selfValue;
+        paired.currentCumulative += node.cumulativeValue;
+      } else {
+        paired.baseline ??= node;
+        paired.baselineSelf += node.selfValue;
+        paired.baselineCumulative += node.cumulativeValue;
+      }
+      pairedNodes.set(node.id, paired);
+    }
+  };
+  pairInto(current, true);
+  pairInto(baseline, false);
+
+  for (const paired of pairedByKey.values()) {
+    paired.width = diffWidth(
+      paired.baselineCumulative,
+      paired.currentCumulative,
+      width,
+    );
+  }
+
+  // Lay out like the operator's ComputeLayout: each strip starts at x = 0,
+  // siblings are packed widest first (ties in pairing order, i.e. the
+  // current tree's order, then the baseline-only nodes) and the breadth-first
+  // walk order, with the strips' roots merged by x, is the output order.
+  const byWidthDesc = (a: PairedNode, b: PairedNode) => b.width - a.width;
+  const layoutStrip = (roots: PairedNode[]) => {
+    roots.sort(byWidthDesc);
+    let x = 0;
+    for (const root of roots) {
+      root.x = x;
+      x += root.width;
+    }
+    return x;
+  };
+  const layoutWidth = Math.max(
+    layoutStrip(downwardRoots),
+    layoutStrip(upwardRoots),
+  );
+  const order: PairedNode[] = [];
+  const emit = (paired: PairedNode) => {
+    paired.id = order.length;
+    order.push(paired);
+  };
+  for (let d = 0, u = 0; d < downwardRoots.length || u < upwardRoots.length;) {
+    if (
+      u >= upwardRoots.length ||
+      (d < downwardRoots.length && downwardRoots[d].x <= upwardRoots[u].x)
+    ) {
+      emit(downwardRoots[d++]);
+    } else {
+      emit(upwardRoots[u++]);
+    }
+  }
+  for (let i = 0; i < order.length; i++) {
+    const paired = order[i];
+    paired.children.sort(byWidthDesc);
+    let x = paired.x;
+    for (const child of paired.children) {
+      child.x = x;
+      x += child.width;
+      emit(child);
+    }
+  }
+
+  let minDepth = 0;
+  let maxDepth = 0;
+  let maxAbsDelta = Math.abs(
+    current.allRootsCumulativeValue - baseline.allRootsCumulativeValue,
+  );
+  const nodes: TreeExplorerNode[] = order.map((paired) => {
+    // Every paired node holds a node of at least one of the trees.
+    const source = (paired.current ?? paired.baseline)!;
+    // Nodes which take no space are not drawn: they add no rows.
+    if (paired.width > 0) {
+      minDepth = Math.min(minDepth, paired.depth);
+      maxDepth = Math.max(maxDepth, paired.depth);
+    }
+    maxAbsDelta = Math.max(
+      maxAbsDelta,
+      Math.abs(paired.currentCumulative - paired.baselineCumulative),
+    );
+    return {
+      id: paired.id,
+      parentId: paired.parent?.id ?? -1,
+      depth: paired.depth,
+      name: source.name,
+      selfValue: paired.currentSelf,
+      cumulativeValue: paired.currentCumulative,
+      parentCumulativeValue: paired.parent?.currentCumulative,
+      // The pairing properties are equal on both sides; the others
+      // (aggregatable and profile-specific) are taken from the current tree
+      // where the node exists there, so that node actions reading them act
+      // on the current tree. The flamegraph shows only the pairing ones, and
+      // offers no host actions on the nodes only the baseline has.
+      properties: source.properties,
+      marker: source.marker,
+      xStart: paired.x,
+      xEnd: paired.x + paired.width,
+      baselineSelfValue: paired.baselineSelf,
+      baselineCumulativeValue: paired.baselineCumulative,
+    };
+  });
+
+  return {
+    nodes,
+    unfilteredCumulativeValue: current.unfilteredCumulativeValue,
+    allRootsCumulativeValue: current.allRootsCumulativeValue,
+    minDepth,
+    maxDepth,
+    nodeActions: current.nodeActions,
+    rootActions: current.rootActions,
+    diff: {
+      baselineUnfilteredCumulativeValue: baseline.unfilteredCumulativeValue,
+      baselineAllRootsCumulativeValue: baseline.allRootsCumulativeValue,
+      layoutWidth,
+      maxAbsDelta,
+    },
+  };
+}
+
+// Whether nodes of the two trees of a diff are only paired up if they have
+// the same value of `property`: the grouping (unaggregatable) properties,
+// which the flamegraph operator also merges siblings by, minus the
+// profile-specific ones. Only these are the same on both sides of a diff
+// node; the others have a value per tree.
+export function isPairingProperty(
+  property: TreeExplorerPropertyDefinition,
+): boolean {
+  return !property.isAggregatable && property.profileSpecific !== true;
+}
+
+// Identifies a node among its siblings across trees: its name and pairing
+// properties, sorted so that property order does not matter.
+function pairingKey(node: TreeExplorerNode): string {
+  const parts: string[] = [];
+  for (const [key, property] of node.properties) {
+    if (isPairingProperty(property)) {
+      parts.push(`${key}\u0001${property.value}`);
+    }
+  }
+  parts.sort();
+  return [node.name, ...parts].join('\u0000');
+}
+
+function diffWidth(
+  baseline: number,
+  current: number,
+  width: TreeExplorerDiffWidth,
+): number {
+  switch (width) {
+    case 'COMBINED':
+      return baseline + current;
+    case 'CURRENT':
+      return current;
+    case 'BASELINE':
+      return baseline;
+    default:
+      assertUnreachable(width);
+  }
+}
+
+// How a value changed from `baseline` to `current`, as a score in [-1, 1]:
+// positive if it grew, negative if it shrank, 0 if unchanged.
+//  - ABSOLUTE: the change relative to `maxAbsDelta`, the largest change in
+//    the tree, so the biggest movers stand out.
+//  - RELATIVE: the change relative to the baseline value, saturating at a
+//    doubling; new values score 1 and removed ones -1.
+export function treeExplorerDiffScore(
+  baseline: number,
+  current: number,
+  color: TreeExplorerDiffColor,
+  maxAbsDelta: number,
+): number {
+  const delta = current - baseline;
+  if (delta === 0) {
+    return 0;
+  }
+  switch (color) {
+    case 'ABSOLUTE':
+      return maxAbsDelta === 0 ? 0 : clampScore(delta / maxAbsDelta);
+    case 'RELATIVE':
+      return baseline === 0 ? 1 : clampScore(delta / baseline);
+    default:
+      assertUnreachable(color);
+  }
+}
+
+// The pprof web UI's diff palette (dotColor in pprof's
+// internal/report/graph.go), tuned for the light fill of flamegraph nodes:
+// green for scores < 0 (shrank), grey for 0, red for > 0 (grew).
+const DIFF_SATURATION = 0.5; // Saturation at |score| = 1.
+const DIFF_VALUE = 0.78; // HSV value of all colors.
+const DIFF_SHIFT = 0.7; // Pushes scores away from grey to use more range.
+
+export function treeExplorerDiffColor(score: number): Color {
+  score = Number.isFinite(score) ? clampScore(score) : 0;
+  // Desaturate near 0, so that small changes read as grey, not yellow.
+  let saturation = DIFF_SATURATION;
+  if (Math.abs(score) < 0.2) {
+    saturation *= Math.abs(score) / 0.2;
+  }
+  const shifted = Math.sign(score) * Math.pow(Math.abs(score), 1 - DIFF_SHIFT);
+  let r = DIFF_VALUE;
+  let g = DIFF_VALUE;
+  if (shifted < 0) {
+    r *= 1 + saturation * shifted;
+  } else {
+    g *= 1 - saturation * shifted;
+  }
+  const b = DIFF_VALUE * (1 - saturation);
+  const to255 = (x: number) => Math.round(x * 255);
+  return new HSLColor(rgbToHsl([to255(r), to255(g), to255(b)]));
+}
+
+function clampScore(score: number): number {
+  return Math.max(-1, Math.min(1, score));
+}
+
+// Formats a signed change in the metric's unit, e.g. "+1.50 MiB" or "-3".
+export function displaySignedSize(delta: number, unit: string): string {
+  if (delta === 0) {
+    return displaySize(0, unit);
+  }
+  return `${delta > 0 ? '+' : '-'}${displaySize(Math.abs(delta), unit)}`;
+}
+
+// The change from `baseline` to `current` relative to `baseline`, in percent,
+// or undefined when there is no baseline value to relate to.
+export function changePercentage(
+  baseline: number,
+  current: number,
+): number | undefined {
+  if (baseline === 0) {
+    return current === 0 ? 0 : undefined;
+  }
+  return ((current - baseline) / baseline) * 100;
+}
+
+// Formats the change from `baseline` to `current` relative to `baseline`,
+// e.g. "+25.00%", or "new" when there is no baseline value to relate to.
+export function displayChangePercentage(
+  baseline: number,
+  current: number,
+): string {
+  const change = changePercentage(baseline, current);
+  if (change === undefined) {
+    return 'new';
+  }
+  return `${change > 0 ? '+' : ''}${change.toFixed(2)}%`;
+}
+
+// Formats a value of a diff, e.g.
+// "1.00 MiB → 1.50 MiB (+512.00 KiB, +50.00%)".
+export function displayChange(
+  baseline: number,
+  current: number,
+  unit: string,
+): string {
+  const from = displaySize(baseline, unit);
+  const to = displaySize(current, unit);
+  const delta = displaySignedSize(current - baseline, unit);
+  const percentage = displayChangePercentage(baseline, current);
+  return `${from} → ${to} (${delta}, ${percentage})`;
+}
diff --git a/ui/src/widgets/tree_explorer_diff_controls.scss b/ui/src/widgets/tree_explorer_diff_controls.scss
new file mode 100644
index 0000000..c3260ba
--- /dev/null
+++ b/ui/src/widgets/tree_explorer_diff_controls.scss
@@ -0,0 +1,38 @@
+// Copyright (C) 2026 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+.pf-tree-explorer-diff-controls {
+  display: flex;
+  align-items: center;
+  align-self: center;
+  gap: 8px;
+  padding-right: 8px;
+
+  &__legend {
+    display: flex;
+    align-items: center;
+    gap: 4px;
+    font-size: var(--pf-font-size-s);
+    color: var(--pf-color-text-muted);
+    user-select: none;
+  }
+
+  // A canvas one pixel high, painted with the diff palette and stretched
+  // into a color scale.
+  &__scale {
+    width: 64px;
+    height: 10px;
+    border-radius: 2px;
+  }
+}
diff --git a/ui/src/widgets/tree_explorer_diff_controls.ts b/ui/src/widgets/tree_explorer_diff_controls.ts
new file mode 100644
index 0000000..71ddaca
--- /dev/null
+++ b/ui/src/widgets/tree_explorer_diff_controls.ts
@@ -0,0 +1,182 @@
+// Copyright (C) 2026 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+import './tree_explorer_diff_controls.scss';
+import m from 'mithril';
+import {Icons} from '../base/semantic_icons';
+import {Button} from './button';
+import {MenuDivider, MenuItem, MenuTitle, PopupMenu} from './menu';
+import {PopupPosition} from './popup';
+import {RadioGroup} from './radio_group';
+import {Switch} from './switch';
+import type {
+  TreeExplorerComparison,
+  TreeExplorerDiffColor,
+  TreeExplorerDiffWidth,
+} from './tree_explorer';
+import {treeExplorerDiffColor} from './tree_explorer_diff';
+
+export interface TreeExplorerDiffControlsAttrs {
+  readonly comparison: TreeExplorerComparison;
+  readonly onComparisonChange: (comparison: TreeExplorerComparison) => void;
+
+  // Short human-readable names of the two trees, e.g. of the heap dumps they
+  // were read from.
+  readonly baselineLabel: string;
+  readonly currentLabel: string;
+
+  // Whether to offer the options which only apply to the flamegraph: node
+  // widths and colors.
+  readonly flamegraphOptions: boolean;
+
+  // Set when the trees cannot be compared (e.g. the baseline lacks the
+  // selected metric): disables the controls, which then show the current
+  // tree, and says why.
+  readonly disabledReason?: string;
+}
+
+const WIDTH_OPTIONS: ReadonlyArray<{
+  readonly value: TreeExplorerDiffWidth;
+  readonly label: string;
+}> = [
+  {value: 'COMBINED', label: 'Baseline + current'},
+  {value: 'CURRENT', label: 'Current'},
+  {value: 'BASELINE', label: 'Baseline'},
+];
+
+const COLOR_OPTIONS: ReadonlyArray<{
+  readonly value: TreeExplorerDiffColor;
+  readonly label: string;
+}> = [
+  {value: 'ABSOLUTE', label: 'Absolute change'},
+  {value: 'RELATIVE', label: 'Relative change'},
+];
+
+const COLOR_DESCRIPTIONS: Record<TreeExplorerDiffColor, string> = {
+  ABSOLUTE: 'Node colors show the change relative to the largest change.',
+  RELATIVE:
+    'Node colors show the change relative to the baseline value, ' +
+    'saturating at -100% and +100%.',
+};
+
+// Chooses what a tree explorer with a baseline tree shows: the diff of the
+// current tree against the baseline (see TreeExplorerComparison), or either
+// tree on its own, and how the diff is drawn. The counterpart of switching
+// between merged and individual profiles.
+export class TreeExplorerDiffControls implements m.ClassComponent<TreeExplorerDiffControlsAttrs> {
+  view({attrs}: m.CVnode<TreeExplorerDiffControlsAttrs>): m.Children {
+    const {comparison, baselineLabel, currentLabel, disabledReason} = attrs;
+    const disabled = disabledReason !== undefined;
+    const isDiff = comparison.show === 'DIFF' && !disabled;
+    const update = (change: Partial<TreeExplorerComparison>) =>
+      attrs.onComparisonChange({...comparison, ...change});
+    return m(
+      '.pf-tree-explorer-diff-controls',
+      m(Switch, {
+        label: 'Diff',
+        checked: isDiff,
+        disabled,
+        title:
+          disabledReason ??
+          `Show how ${currentLabel} changed from ${baselineLabel}`,
+        onchange: () => update({show: isDiff ? 'CURRENT' : 'DIFF'}),
+      }),
+      !isDiff &&
+        m(
+          RadioGroup,
+          {
+            selectedValue: disabled ? 'CURRENT' : comparison.show,
+            disabled,
+            onValueChange: (show) =>
+              update({show: show === 'BASELINE' ? 'BASELINE' : 'CURRENT'}),
+          },
+          m(
+            RadioGroup.Button,
+            {value: 'BASELINE', title: baselineLabel},
+            'Baseline',
+          ),
+          m(
+            RadioGroup.Button,
+            {value: 'CURRENT', title: currentLabel},
+            'Current',
+          ),
+        ),
+      isDiff &&
+        attrs.flamegraphOptions && [
+          m(
+            '.pf-tree-explorer-diff-controls__legend',
+            {title: COLOR_DESCRIPTIONS[comparison.color]},
+            'Shrank',
+            m('canvas.pf-tree-explorer-diff-controls__scale', {
+              width: LEGEND_STEPS,
+              height: 1,
+              oncreate: ({dom}) => paintLegend(dom as HTMLCanvasElement),
+            }),
+            'Grew',
+          ),
+          m(
+            PopupMenu,
+            {
+              trigger: m(Button, {
+                icon: 'tune',
+                compact: true,
+                title: 'Diff options',
+              }),
+              position: PopupPosition.BottomEnd,
+            },
+            m(MenuTitle, {label: 'Node width'}),
+            WIDTH_OPTIONS.map(({value, label}) =>
+              m(MenuItem, {
+                label,
+                icon:
+                  comparison.width === value
+                    ? Icons.RadioChecked
+                    : Icons.RadioUnchecked,
+                onclick: () => update({width: value}),
+              }),
+            ),
+            m(MenuDivider),
+            m(MenuTitle, {label: 'Node color'}),
+            COLOR_OPTIONS.map(({value, label}) =>
+              m(MenuItem, {
+                label,
+                icon:
+                  comparison.color === value
+                    ? Icons.RadioChecked
+                    : Icons.RadioUnchecked,
+                onclick: () => update({color: value}),
+              }),
+            ),
+          ),
+        ],
+    );
+  }
+}
+
+// The legend is the diff palette painted on a canvas (stretched by CSS),
+// from the most shrunk to the most grown, so that it shares its colors with
+// the flamegraph without duplicating them in styles.
+const LEGEND_STEPS = 32;
+
+function paintLegend(canvas: HTMLCanvasElement) {
+  const ctx = canvas.getContext('2d');
+  if (ctx === null) {
+    return;
+  }
+  for (let i = 0; i < LEGEND_STEPS; i++) {
+    const score = (2 * i) / (LEGEND_STEPS - 1) - 1;
+    ctx.fillStyle = treeExplorerDiffColor(score).cssString;
+    ctx.fillRect(i, 0, 1, 1);
+  }
+}
diff --git a/ui/src/widgets/tree_explorer_diff_unittest.ts b/ui/src/widgets/tree_explorer_diff_unittest.ts
new file mode 100644
index 0000000..ccbebdd
--- /dev/null
+++ b/ui/src/widgets/tree_explorer_diff_unittest.ts
@@ -0,0 +1,557 @@
+// Copyright (C) 2026 The Android Open Source Project
+//
+// Licensed under the Apache License, Version 2.0 (the "License");
+// you may not use this file except in compliance with the License.
+// You may obtain a copy of the License at
+//
+//      http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+import type {TreeExplorerData, TreeExplorerNode} from './tree_explorer';
+import {
+  buildTreeExplorerDiff,
+  changePercentage,
+  displayChange,
+  displayChangePercentage,
+  displaySignedSize,
+  isPairingProperty,
+  treeExplorerDiffColor,
+  treeExplorerDiffScore,
+} from './tree_explorer_diff';
+
+interface Spec {
+  readonly name: string;
+  readonly self?: number;
+  readonly props?: Readonly<Record<string, string>>;
+  readonly children?: ReadonlyArray<Spec>;
+}
+
+// The kinds of properties other than regular grouping ones, by key.
+type PropertyKinds = Readonly<
+  Record<string, 'aggregatable' | 'profileSpecific'>
+>;
+
+// Builds tree explorer data the way the operator returns it: breadth-first
+// (parents before children), roots at depth 1 (`roots`) and -1 (`upward`).
+function makeTree(
+  roots: ReadonlyArray<Spec>,
+  upward: ReadonlyArray<Spec> = [],
+  kinds: PropertyKinds = {},
+): TreeExplorerData {
+  const cumulative = (s: Spec): number =>
+    (s.self ?? 0) +
+    (s.children ?? []).reduce((sum, c) => sum + cumulative(c), 0);
+  const queue = [
+    ...roots.map((spec) => ({spec, parentId: -1, depth: 1})),
+    ...upward.map((spec) => ({spec, parentId: -1, depth: -1})),
+  ];
+  const nodes: TreeExplorerNode[] = [];
+  for (let id = 0; id < queue.length; id++) {
+    const {spec, parentId, depth} = queue[id];
+    nodes.push({
+      id,
+      parentId,
+      depth,
+      name: spec.name,
+      selfValue: spec.self ?? 0,
+      cumulativeValue: cumulative(spec),
+      properties: new Map(
+        Object.entries(spec.props ?? {}).map(([key, value]) => [
+          key,
+          {
+            displayName: key,
+            value,
+            isVisible: true,
+            isAggregatable: kinds[key] === 'aggregatable',
+            profileSpecific: kinds[key] === 'profileSpecific',
+          },
+        ]),
+      ),
+      xStart: 0,
+      xEnd: 0,
+    });
+    for (const child of spec.children ?? []) {
+      queue.push({spec: child, parentId: id, depth: depth + Math.sign(depth)});
+    }
+  }
+  // Like the fetcher: bottom-up trees only have upward nodes.
+  const total = (roots.length > 0 ? roots : upward).reduce(
+    (sum, s) => sum + cumulative(s),
+    0,
+  );
+  return {
+    nodes,
+    unfilteredCumulativeValue: total,
+    allRootsCumulativeValue: total,
+    minDepth: Math.min(0, ...nodes.map((n) => n.depth)),
+    maxDepth: Math.max(0, ...nodes.map((n) => n.depth)),
+    nodeActions: [],
+    rootActions: [],
+  };
+}
+
+// Nodes by their path of names from the root, e.g. 'A/B'; paths of upward
+// nodes start with '^'.
+function byPath(data: TreeExplorerData): Map<string, TreeExplorerNode> {
+  const byId = new Map(data.nodes.map((n) => [n.id, n]));
+  const path = (n: TreeExplorerNode): string => {
+    const parent = byId.get(n.parentId);
+    if (parent !== undefined) {
+      return `${path(parent)}/${n.name}`;
+    }
+    return n.depth < 0 ? `^${n.name}` : n.name;
+  };
+  const result = new Map<string, TreeExplorerNode>();
+  for (const n of data.nodes) {
+    const p = path(n);
+    expect(result.has(p)).toBe(false);
+    result.set(p, n);
+  }
+  return result;
+}
+
+function values(n: TreeExplorerNode | undefined) {
+  return {
+    self: n?.selfValue,
+    cumulative: n?.cumulativeValue,
+    baselineSelf: n?.baselineSelfValue,
+    baselineCumulative: n?.baselineCumulativeValue,
+  };
+}
+
+function extent(n: TreeExplorerNode | undefined) {
+  return [n?.xStart, n?.xEnd];
+}
+
+// current: A -> {B, C}; baseline: A -> {B, D}.
+const CURRENT = makeTree([
+  {
+    name: 'A',
+    self: 1,
+    children: [
+      {name: 'B', self: 4},
+      {name: 'C', self: 5},
+    ],
+  },
+]);
+const BASELINE = makeTree([
+  {
+    name: 'A',
+    self: 1,
+    children: [
+      {name: 'B', self: 2},
+      {name: 'D', self: 3},
+    ],
+  },
+]);
+
+describe('buildTreeExplorerDiff', () => {
+  test('pairs nodes by path and keeps added and removed ones', () => {
+    const nodes = byPath(buildTreeExplorerDiff(CURRENT, BASELINE, 'COMBINED'));
+    expect([...nodes.keys()].sort()).toEqual(['A', 'A/B', 'A/C', 'A/D']);
+    expect(values(nodes.get('A'))).toEqual({
+      self: 1,
+      cumulative: 10,
+      baselineSelf: 1,
+      baselineCumulative: 6,
+    });
+    expect(values(nodes.get('A/B'))).toEqual({
+      self: 4,
+      cumulative: 4,
+      baselineSelf: 2,
+      baselineCumulative: 2,
+    });
+    // Only in the current tree.
+    expect(values(nodes.get('A/C'))).toEqual({
+      self: 5,
+      cumulative: 5,
+      baselineSelf: 0,
+      baselineCumulative: 0,
+    });
+    // Only in the baseline tree.
+    expect(values(nodes.get('A/D'))).toEqual({
+      self: 0,
+      cumulative: 0,
+      baselineSelf: 3,
+      baselineCumulative: 3,
+    });
+  });
+
+  test('summarizes both trees', () => {
+    const diff = buildTreeExplorerDiff(CURRENT, BASELINE, 'COMBINED');
+    expect(diff.allRootsCumulativeValue).toBe(10);
+    expect(diff.unfilteredCumulativeValue).toBe(10);
+    expect(diff.diff).toEqual({
+      baselineAllRootsCumulativeValue: 6,
+      baselineUnfilteredCumulativeValue: 6,
+      layoutWidth: 16,
+      // A/C grew by 5: more than the root (+4) or any other node.
+      maxAbsDelta: 5,
+    });
+    expect(diff.minDepth).toBe(0);
+    expect(diff.maxDepth).toBe(2);
+  });
+
+  test('lists parents first with ids matching positions', () => {
+    const {nodes} = buildTreeExplorerDiff(CURRENT, BASELINE, 'COMBINED');
+    nodes.forEach((n, i) => {
+      expect(n.id).toBe(i);
+      expect(n.parentId).toBeLessThan(i);
+    });
+  });
+
+  test('COMBINED widths show both trees, widest siblings first', () => {
+    const nodes = byPath(buildTreeExplorerDiff(CURRENT, BASELINE, 'COMBINED'));
+    expect(extent(nodes.get('A'))).toEqual([0, 16]);
+    expect(extent(nodes.get('A/B'))).toEqual([0, 6]);
+    expect(extent(nodes.get('A/C'))).toEqual([6, 11]);
+    expect(extent(nodes.get('A/D'))).toEqual([11, 14]);
+  });
+
+  test('CURRENT widths hide baseline-only nodes', () => {
+    const diff = buildTreeExplorerDiff(CURRENT, BASELINE, 'CURRENT');
+    const nodes = byPath(diff);
+    expect(diff.diff?.layoutWidth).toBe(10);
+    expect(extent(nodes.get('A'))).toEqual([0, 10]);
+    expect(extent(nodes.get('A/C'))).toEqual([0, 5]);
+    expect(extent(nodes.get('A/B'))).toEqual([5, 9]);
+    expect(extent(nodes.get('A/D'))).toEqual([9, 9]);
+  });
+
+  test('BASELINE widths hide current-only nodes', () => {
+    const diff = buildTreeExplorerDiff(CURRENT, BASELINE, 'BASELINE');
+    const nodes = byPath(diff);
+    expect(diff.diff?.layoutWidth).toBe(6);
+    expect(extent(nodes.get('A/D'))).toEqual([0, 3]);
+    expect(extent(nodes.get('A/B'))).toEqual([3, 5]);
+    expect(extent(nodes.get('A/C'))).toEqual([5, 5]);
+  });
+
+  test('hidden nodes do not extend the depth range', () => {
+    const current = makeTree([{name: 'A', self: 1}]);
+    const baseline = makeTree([
+      {name: 'A', children: [{name: 'B', children: [{name: 'C', self: 1}]}]},
+    ]);
+    expect(buildTreeExplorerDiff(current, baseline, 'COMBINED').maxDepth).toBe(
+      3,
+    );
+    expect(buildTreeExplorerDiff(current, baseline, 'CURRENT').maxDepth).toBe(
+      1,
+    );
+  });
+
+  test('children nest within their parents', () => {
+    const current = makeTree([
+      {
+        name: 'main',
+        children: [
+          {name: 'a', self: 3, children: [{name: 'x', self: 7}]},
+          {name: 'b', self: 1},
+        ],
+      },
+      {name: 'other', self: 2},
+    ]);
+    const baseline = makeTree([
+      {
+        name: 'main',
+        children: [
+          {name: 'a', children: [{name: 'y', self: 4}]},
+          {name: 'c', self: 9},
+        ],
+      },
+    ]);
+    for (const width of ['COMBINED', 'CURRENT', 'BASELINE'] as const) {
+      const {nodes} = buildTreeExplorerDiff(current, baseline, width);
+      for (const n of nodes) {
+        const parent = nodes[n.parentId];
+        if (parent !== undefined) {
+          expect(n.xStart).toBeGreaterThanOrEqual(parent.xStart);
+          expect(n.xEnd).toBeLessThanOrEqual(parent.xEnd);
+        }
+      }
+    }
+  });
+
+  test('does not pair same-named nodes under different parents', () => {
+    const current = makeTree([
+      {name: 'A', children: [{name: 'X', self: 1}]},
+      {name: 'B', children: [{name: 'X', self: 2}]},
+    ]);
+    const baseline = makeTree([{name: 'A', children: [{name: 'X', self: 5}]}]);
+    const nodes = byPath(buildTreeExplorerDiff(current, baseline, 'COMBINED'));
+    expect(values(nodes.get('A/X'))).toMatchObject({
+      cumulative: 1,
+      baselineCumulative: 5,
+    });
+    expect(values(nodes.get('B/X'))).toMatchObject({
+      cumulative: 2,
+      baselineCumulative: 0,
+    });
+  });
+
+  test('pairs by grouping properties, except profile-specific ones', () => {
+    const kinds: PropertyKinds = {hash: 'profileSpecific'};
+    const current = makeTree(
+      [
+        {name: 'Foo', self: 3, props: {heap: 'app', hash: 'c1'}},
+        {name: 'Foo', self: 1, props: {heap: 'zygote', hash: 'c2'}},
+      ],
+      [],
+      kinds,
+    );
+    const baseline = makeTree(
+      [
+        {name: 'Foo', self: 2, props: {heap: 'app', hash: 'b1'}},
+        {name: 'Bar', self: 4, props: {heap: 'app', hash: 'b2'}},
+      ],
+      [],
+      kinds,
+    );
+    const {nodes} = buildTreeExplorerDiff(current, baseline, 'COMBINED');
+    const find = (name: string, heap: string) =>
+      nodes.find(
+        (n) => n.name === name && n.properties.get('heap')?.value === heap,
+      );
+    const fooApp = find('Foo', 'app');
+    expect(values(fooApp)).toMatchObject({
+      cumulative: 3,
+      baselineCumulative: 2,
+    });
+    // Profile-specific values come from the current tree when possible...
+    expect(fooApp?.properties.get('hash')?.value).toBe('c1');
+    expect(values(find('Foo', 'zygote'))).toMatchObject({
+      cumulative: 1,
+      baselineCumulative: 0,
+    });
+    // ...and from the baseline for nodes only it has.
+    const bar = find('Bar', 'app');
+    expect(values(bar)).toMatchObject({cumulative: 0, baselineCumulative: 4});
+    expect(bar?.properties.get('hash')?.value).toBe('b2');
+    expect(nodes.length).toBe(3);
+  });
+
+  test('does not pair nodes differing in a regular grouping property', () => {
+    const current = makeTree([{name: 'Foo', self: 3, props: {hash: 'c1'}}]);
+    const baseline = makeTree([{name: 'Foo', self: 2, props: {hash: 'b1'}}]);
+    const {nodes} = buildTreeExplorerDiff(current, baseline, 'COMBINED');
+    expect(nodes.length).toBe(2);
+  });
+
+  test('pairs nodes differing in aggregatable properties', () => {
+    const kinds: PropertyKinds = {count: 'aggregatable'};
+    const current = makeTree(
+      [{name: 'Foo', self: 3, props: {count: '3'}}],
+      [],
+      kinds,
+    );
+    const baseline = makeTree(
+      [{name: 'Foo', self: 2, props: {count: '2'}}],
+      [],
+      kinds,
+    );
+    const {nodes} = buildTreeExplorerDiff(current, baseline, 'COMBINED');
+    expect(nodes.length).toBe(1);
+    expect(values(nodes[0])).toMatchObject({
+      cumulative: 3,
+      baselineCumulative: 2,
+    });
+  });
+
+  test('sums siblings of a tree which pair up alike', () => {
+    // Differ only in a profile-specific property, so they pair up alike.
+    const kinds: PropertyKinds = {hash: 'profileSpecific'};
+    const current = makeTree(
+      [
+        {name: 'Foo', self: 3, props: {hash: 'c1'}},
+        {name: 'Foo', self: 1, props: {hash: 'c2'}},
+      ],
+      [],
+      kinds,
+    );
+    const baseline = makeTree(
+      [{name: 'Foo', self: 2, props: {hash: 'b1'}}],
+      [],
+      kinds,
+    );
+    const {nodes} = buildTreeExplorerDiff(current, baseline, 'COMBINED');
+    expect(nodes.length).toBe(1);
+    expect(values(nodes[0])).toEqual({
+      self: 4,
+      cumulative: 4,
+      baselineSelf: 2,
+      baselineCumulative: 2,
+    });
+    expect(extent(nodes[0])).toEqual([0, 6]);
+  });
+
+  test('keeps the two directions of a pivot apart', () => {
+    const current = makeTree(
+      [{name: 'P', self: 3}],
+      [{name: 'P', children: [{name: 'Q', self: 3}]}],
+    );
+    const baseline = makeTree(
+      [{name: 'P', self: 1}],
+      [{name: 'P', children: [{name: 'Q', self: 1}]}],
+    );
+    const diff = buildTreeExplorerDiff(current, baseline, 'COMBINED');
+    const nodes = byPath(diff);
+    expect(nodes.get('P')?.depth).toBe(1);
+    expect(nodes.get('^P')?.depth).toBe(-1);
+    expect(nodes.get('^P/Q')?.depth).toBe(-2);
+    expect(values(nodes.get('^P/Q'))).toMatchObject({
+      cumulative: 3,
+      baselineCumulative: 1,
+    });
+    // Both strips start at x = 0.
+    expect(extent(nodes.get('P'))).toEqual([0, 4]);
+    expect(extent(nodes.get('^P'))).toEqual([0, 4]);
+    expect(diff.minDepth).toBe(-2);
+    expect(diff.maxDepth).toBe(1);
+  });
+
+  test('diffs bottom-up trees', () => {
+    const current = makeTree(
+      [],
+      [{name: 'leaf', children: [{name: 'a', self: 3}]}],
+    );
+    const baseline = makeTree(
+      [],
+      [
+        {
+          name: 'leaf',
+          children: [
+            {name: 'a', self: 1},
+            {name: 'b', self: 2},
+          ],
+        },
+      ],
+    );
+    const diff = buildTreeExplorerDiff(current, baseline, 'COMBINED');
+    const nodes = byPath(diff);
+    expect([...nodes.keys()].sort()).toEqual(['^leaf', '^leaf/a', '^leaf/b']);
+    expect(values(nodes.get('^leaf/b'))).toMatchObject({
+      cumulative: 0,
+      baselineCumulative: 2,
+    });
+    expect(extent(nodes.get('^leaf'))).toEqual([0, 6]);
+    expect(extent(nodes.get('^leaf/a'))).toEqual([0, 4]);
+    expect(extent(nodes.get('^leaf/b'))).toEqual([4, 6]);
+    expect(diff.allRootsCumulativeValue).toBe(3);
+    expect(diff.diff).toMatchObject({
+      baselineAllRootsCumulativeValue: 3,
+      layoutWidth: 6,
+    });
+    expect(diff.minDepth).toBe(-2);
+    expect(diff.maxDepth).toBe(0);
+  });
+
+  test('handles empty trees', () => {
+    const empty = makeTree([]);
+    const diff = buildTreeExplorerDiff(CURRENT, empty, 'COMBINED');
+    expect(diff.nodes.length).toBe(3);
+    for (const n of diff.nodes) {
+      expect(n.baselineCumulativeValue).toBe(0);
+    }
+    expect(buildTreeExplorerDiff(empty, empty, 'COMBINED').nodes).toEqual([]);
+  });
+});
+
+test('isPairingProperty', () => {
+  const property = (isAggregatable: boolean, profileSpecific?: boolean) => ({
+    displayName: 'p',
+    value: 'v',
+    isVisible: true,
+    isAggregatable,
+    profileSpecific,
+  });
+  expect(isPairingProperty(property(false))).toBe(true);
+  expect(isPairingProperty(property(false, false))).toBe(true);
+  expect(isPairingProperty(property(false, true))).toBe(false);
+  expect(isPairingProperty(property(true))).toBe(false);
+});
+
+describe('treeExplorerDiffScore', () => {
+  test('ABSOLUTE scores the change against the largest change', () => {
+    expect(treeExplorerDiffScore(6, 10, 'ABSOLUTE', 8)).toBe(0.5);
+    expect(treeExplorerDiffScore(10, 6, 'ABSOLUTE', 8)).toBe(-0.5);
+    expect(treeExplorerDiffScore(5, 5, 'ABSOLUTE', 8)).toBe(0);
+    expect(treeExplorerDiffScore(0, 20, 'ABSOLUTE', 8)).toBe(1);
+    expect(treeExplorerDiffScore(5, 5, 'ABSOLUTE', 0)).toBe(0);
+  });
+
+  test('RELATIVE scores the change against the baseline value', () => {
+    expect(treeExplorerDiffScore(10, 15, 'RELATIVE', 100)).toBe(0.5);
+    expect(treeExplorerDiffScore(10, 5, 'RELATIVE', 100)).toBe(-0.5);
+    expect(treeExplorerDiffScore(10, 40, 'RELATIVE', 100)).toBe(1);
+    expect(treeExplorerDiffScore(0, 5, 'RELATIVE', 100)).toBe(1);
+    expect(treeExplorerDiffScore(5, 0, 'RELATIVE', 100)).toBe(-1);
+    expect(treeExplorerDiffScore(0, 0, 'RELATIVE', 100)).toBe(0);
+  });
+});
+
+describe('treeExplorerDiffColor', () => {
+  // cssString is "rgb(R G B)".
+  const rgb = (score: number): [number, number, number] => {
+    const css = treeExplorerDiffColor(score).cssString;
+    const match = css.match(/rgb\((\d+) (\d+) (\d+)\)/);
+    if (match === null) throw new Error(`Unexpected color: ${css}`);
+    return [Number(match[1]), Number(match[2]), Number(match[3])];
+  };
+
+  test('is grey when unchanged', () => {
+    const [r, g, b] = rgb(0);
+    expect(r).toBe(g);
+    expect(g).toBe(b);
+  });
+
+  test('is red when grown and green when shrunk', () => {
+    const [r1, g1, b1] = rgb(1);
+    expect(r1).toBeGreaterThan(g1);
+    expect(r1).toBeGreaterThan(b1);
+    const [r2, g2, b2] = rgb(-1);
+    expect(g2).toBeGreaterThan(r2);
+    expect(g2).toBeGreaterThan(b2);
+  });
+
+  test('intensifies with the size of the change', () => {
+    expect(rgb(0.9)[1]).toBeLessThan(rgb(0.3)[1]);
+    expect(rgb(-0.9)[0]).toBeLessThan(rgb(-0.3)[0]);
+  });
+
+  test('clamps out of range and non-finite scores', () => {
+    expect(rgb(5)).toEqual(rgb(1));
+    expect(rgb(-5)).toEqual(rgb(-1));
+    expect(rgb(NaN)).toEqual(rgb(0));
+  });
+});
+
+describe('diff formatters', () => {
+  test('displaySignedSize formats zero, positive, and negative deltas', () => {
+    expect(displaySignedSize(0, 'B')).toBe('0 B');
+    expect(displaySignedSize(1024, 'B')).toBe('+1 KiB');
+    expect(displaySignedSize(-2048, 'B')).toBe('-2 KiB');
+    expect(displaySignedSize(1536, 'B')).toBe('+1.50 KiB');
+  });
+
+  test('changePercentage handles zero baseline and normal values', () => {
+    expect(changePercentage(0, 0)).toBe(0);
+    expect(changePercentage(0, 100)).toBeUndefined();
+    expect(changePercentage(100, 150)).toBe(50);
+    expect(changePercentage(100, 50)).toBe(-50);
+  });
+
+  test('displayChangePercentage formats relative change and new values', () => {
+    expect(displayChangePercentage(0, 100)).toBe('new');
+    expect(displayChangePercentage(100, 125)).toBe('+25.00%');
+    expect(displayChangePercentage(100, 75)).toBe('-25.00%');
+  });
+
+  test('displayChange formats full diff change string', () => {
+    expect(displayChange(100, 150, 'count')).toBe('100 → 150 (+50, +50.00%)');
+  });
+});
diff --git a/ui/src/widgets/tree_explorer_filter_bar.ts b/ui/src/widgets/tree_explorer_filter_bar.ts
index cb6b926..44ab42e 100644
--- a/ui/src/widgets/tree_explorer_filter_bar.ts
+++ b/ui/src/widgets/tree_explorer_filter_bar.ts
@@ -325,12 +325,16 @@
   }
 
   private renderHighlightSearch(attrs: TreeExplorerFilterBarAttrs) {
-    const {highlightPattern, highlightRegex} = attrs;
+    const {highlightPattern, highlightRegex, data} = attrs;
     const matchCount =
       highlightRegex === undefined
         ? 0
-        : (attrs.data?.nodes.filter((node) => highlightRegex.test(node.name))
-            .length ?? 0);
+        : (data?.nodes.filter(
+            (node) =>
+              // Diff nodes which take no space are hidden.
+              (data.diff === undefined || node.xEnd > node.xStart) &&
+              highlightRegex.test(node.name),
+          ).length ?? 0);
     return m(
       '.pf-tree-explorer-highlight-search',
       m(TextInput, {