A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
perf: reduce unnecessary work while editing cells (#11367)
Myles Scolnick6b1754d2fb48
diff --git a/frontend/benchmarks/cell-analysis.bench.ts b/frontend/benchmarks/cell-analysis.bench.tsnew file mode 100644index 0000000000..533c5377f3--- /dev/null+++ b/frontend/benchmarks/cell-analysis.bench.ts@@ -0,0 +1,103 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { python } from "@codemirror/lang-python";+import { ensureSyntaxTree, syntaxTree } from "@codemirror/language";+import { EditorState } from "@codemirror/state";+import { bench, describe, expect } from "vitest";+import { cellId, variableName } from "@/__tests__/branded";+import {+ findCacheSites,+ findDeclarationSites,+} from "@/core/codemirror/code-lens/analyzer";+import { findReactiveVariables } from "@/core/codemirror/reactive-references/analyzer";+import type { Variables } from "@/core/variables/types";++const options = { time: 500, warmupTime: 200, iterations: 100 };+const id = cellId("edited-cell");+const variables: Variables = {};+for (let i = 0; i < 1000; i++) {+ const name = variableName(`source_${i}`);+ variables[name] = { name, declaredBy: [cellId("other-cell")], usedBy: [id] };+}++for (const lines of [20, 200, 2000]) {+ for (const valid of [true, false]) {+ describe(`${lines} lines / ${valid ? "valid" : "unfinished"} Python`, () => {+ const code =+ Array.from(+ { length: lines },+ (_, i) => `value_${i} = source_${i % 1000} + ${i}`,+ ).join("\n") + (valid ? "" : "\nunfinished = (");+ const names = new Set(+ Array.from({ length: lines }, (_, i) => `value_${i}`),+ );+ let state: EditorState;++ const benchmarkOptions = {+ ...options,+ setup() {+ state = EditorState.create({ doc: code, extensions: [python()] });+ // EditorState.create only parses a prefix for large documents. Without+ // this check, a fast benchmark can silently measure incomplete analysis.+ ensureSyntaxTree(state, state.doc.length, 5000);+ // Publish the parser's completed tree into the immutable state field.+ state = state.update({}).state;+ expect(syntaxTree(state).length).toBe(state.doc.length);+ expect(findDeclarationSites({ state, names })).toHaveLength(+ valid ? lines : 0,+ );+ expect(+ findReactiveVariables({ state, cellId: id, variables }),+ ).toHaveLength(valid ? lines : 0);+ },+ };++ bench(+ "one-character transaction (no view)",+ () => {+ // Start from a fixed state to avoid accumulating text/history. Parsing+ // and view work scheduled after the transaction is not included.+ const next = state.update({+ changes: { from: Math.floor(code.length / 2), insert: "x" },+ }).state;+ if (next.doc.length !== code.length + 1) {+ throw new Error("Edit did not apply");+ }+ },+ benchmarkOptions,+ );++ bench(+ "serialize entire document",+ () => {+ state.doc.toString();+ },+ benchmarkOptions,+ );++ bench(+ "reactive references / 1000 variables",+ () => {+ findReactiveVariables({ state, cellId: id, variables });+ },+ benchmarkOptions,+ );++ bench(+ "code lens declarations",+ () => {+ findDeclarationSites({ state, names });+ },+ benchmarkOptions,+ );++ bench(+ "cache scan / no cache sites",+ () => {+ findCacheSites(state);+ },+ benchmarkOptions,+ );+ });+ }+}diff --git a/frontend/benchmarks/cell-editing.bench.ts b/frontend/benchmarks/cell-editing.bench.tsnew file mode 100644index 0000000000..0bf27a10c8--- /dev/null+++ b/frontend/benchmarks/cell-editing.bench.ts@@ -0,0 +1,135 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { type Atom, createStore } from "jotai";+import { bench, describe, expect, vi } from "vitest";+import { MockNotebook } from "@/__mocks__/notebook";+import { cellId } from "@/__tests__/branded";+import {+ cellDataAtom,+ cellErrorsAtom,+ cellHandleAtom,+ cellIdToNamesMap,+ exportedForTesting,+ needsRunAtom,+ notebookAtom,+ notebookIsRunningAtom,+ notebookOutline,+ notebookQueuedOrRunningCountAtom,+ notebookReducer,+} from "@/core/cells/cells";+import type { CellData } from "@/core/cells/types";+import type { CellAction } from "@/core/cells/document-changes";+import { layoutStateAtom } from "@/core/layout/state";+import { lastSavedNotebookAtom, needsSaveAtom } from "@/core/saving/state";++// Keep action-to-document conversion, but exclude the network queue and timers.+// Otherwise a throughput benchmark queues millions of artificial keystrokes.+vi.mock("@/core/cells/document-changes", async (importOriginal) => {+ const actual =+ await importOriginal<typeof import("@/core/cells/document-changes")>();+ return {+ ...actual,+ documentTransactionMiddleware: actual.toDocumentChanges,+ };+});++const options = { time: 500, warmupTime: 200, iterations: 100 };+const code = Array.from({ length: 20 }, (_, i) => `value_${i} = ${i}`).join(+ "\n",+);++for (const count of [10, 25, 100, 1000]) {+ describe(`${count} cells / 20 lines each`, () => {+ for (const mode of [+ "reducer",+ "store",+ "cell subscribers",+ "derived subscribers",+ ] as const) {+ describe(`${mode}`, () => {+ const ids = Array.from({ length: count }, (_, i) =>+ cellId(`bench-${i}`),+ );+ const cellData: Record<string, Partial<CellData>> = {};+ for (const id of ids) {+ cellData[id] = { code, lastCodeRun: code };+ }+ let state = MockNotebook.notebookState({ cellData });+ const store = createStore();+ const unsubscribes: Array<() => void> = [];+ const target = ids[Math.floor(ids.length / 2)];+ let iteration = 0;++ function edit() {+ const action: CellAction = {+ type: "updateCellCode",+ payload: {+ cellId: target,+ code: `${code}\n# ${iteration++ % 2}`,+ formattingChange: false,+ },+ };+ if (mode === "reducer") {+ state = notebookReducer(state, action);+ } else {+ store.set(notebookAtom, (previous) =>+ notebookReducer(previous, action),+ );+ }+ }++ function setup() {+ state = MockNotebook.notebookState({ cellData });+ iteration = 0;+ store.set(notebookAtom, state);+ store.set(lastSavedNotebookAtom, {+ codes: ids.map(() => code),+ names: ids.map((id) => state.cellData[id].name),+ configs: ids.map((id) => state.cellData[id].config),+ layout: store.get(layoutStateAtom),+ });+ const subscribe = (value: Atom<unknown>) => {+ unsubscribes.push(store.sub(value, () => undefined));+ };+ if (mode === "cell subscribers" || mode === "derived subscribers") {+ for (const id of ids) {+ subscribe(cellDataAtom(id));+ subscribe(exportedForTesting.cellRuntimeAtom(id));+ subscribe(cellHandleAtom(id));+ }+ }+ if (mode === "derived subscribers") {+ for (const value of [+ cellErrorsAtom,+ notebookOutline,+ cellIdToNamesMap,+ notebookIsRunningAtom,+ notebookQueuedOrRunningCountAtom,+ needsRunAtom,+ needsSaveAtom,+ ]) {+ subscribe(value);+ }+ }++ // Verify the fixture really edits one cell, preserving unrelated data.+ const previous = state;+ edit();+ const next = mode === "reducer" ? state : store.get(notebookAtom);+ expect(next.cellData[target].code).toBe(`${code}\n# 0`);+ expect(next.cellData[ids[0]]).toBe(previous.cellData[ids[0]]);+ expect(next.cellRuntime).toBe(previous.cellRuntime);+ }++ function teardown() {+ for (const unsubscribe of unsubscribes) {+ unsubscribe();+ }+ unsubscribes.length = 0;+ }++ bench("one edit", edit, { ...options, setup, teardown });+ });+ }+ });+}diff --git a/frontend/benchmarks/cell-editing.browser.ts b/frontend/benchmarks/cell-editing.browser.tsnew file mode 100644index 0000000000..0b61ad4343--- /dev/null+++ b/frontend/benchmarks/cell-editing.browser.ts@@ -0,0 +1,359 @@+/* Copyright 2026 Marimo. All rights reserved. */++// Run against a disposable notebook: this types into its middle cell.+// node benchmarks/cell-editing.browser.ts URL OUTPUT_DIRECTORY+import { mkdir, writeFile } from "node:fs/promises";+import path from "node:path";+import { chromium } from "@playwright/test";+import { installReactCommitRecorder } from "./react-commits.ts";++interface Sample {+ phase: string;+ handler: number;+ input: number;+ frame: number;+}++interface BrowserMetrics {+ phase: string;+ samples: Sample[];+ events: Array<{ phase: string; name: string; duration: number }>;+ longTasks: Array<{ phase: string; duration: number }>;+}++declare global {+ interface Window {+ editingMetrics: BrowserMetrics;+ }+}++const [url, outputDirectory] = process.argv.slice(2);+if (!url || !outputDirectory) {+ throw new Error(+ "Usage: node benchmarks/cell-editing.browser.ts URL OUTPUT_DIRECTORY",+ );+}++const repetitions = Number(process.env.EDITING_BENCH_RUNS ?? 3);+const continuousKeys = Number(process.env.EDITING_BENCH_CONTINUOUS_KEYS ?? 30);+const pausedKeys = 20;+const expectedKeys = continuousKeys + pausedKeys;+const warmup = " warmup";+const expectedHeadings = process.env.EDITING_BENCH_HEADINGS+ ? Number(process.env.EDITING_BENCH_HEADINGS)+ : undefined;+const headingSelector = ".marimo-cell :is(h1, h2, h3, h4, h5, h6)";+const rates = (process.env.EDITING_BENCH_RATES ?? "1,4,6")+ .split(",")+ .map(Number);+if (+ !Number.isInteger(repetitions) ||+ repetitions < 1 ||+ !Number.isInteger(continuousKeys) ||+ continuousKeys < 1 ||+ (expectedHeadings !== undefined &&+ (!Number.isInteger(expectedHeadings) || expectedHeadings < 0)) ||+ rates.some((rate) => !Number.isFinite(rate) || rate < 1)+) {+ throw new Error(+ "Use positive integer repetitions and key counts, nonnegative integer heading counts, and CPU slowdown rates of at least 1",+ );+}++function distribution(values: number[]) {+ const sorted = values.toSorted((a, b) => a - b);+ const quantile = (fraction: number) =>+ sorted[+ Math.min(sorted.length - 1, Math.ceil(sorted.length * fraction) - 1)+ ] ?? null;+ return {+ count: sorted.length,+ p50: quantile(0.5),+ p95: quantile(0.95),+ max: sorted.at(-1) ?? null,+ };+}++await mkdir(outputDirectory, { recursive: true });+const browser = await chromium.launch({ headless: true });+try {+ for (let repetition = 1; repetition <= repetitions; repetition++) {+ // Alternate order to reduce systematic warmup/order effects.+ for (const rate of repetition % 2 ? rates : rates.toReversed()) {+ const context = await browser.newContext({+ viewport: { width: 1280, height: 720 },+ });+ try {+ const page = await context.newPage();+ if (process.env.EDITING_BENCH_REACT === "1") {+ await installReactCommitRecorder(page);+ }+ const errors: string[] = [];+ page.on("pageerror", (error) => errors.push(error.message));+ await page.goto(url);+ await page.locator(".cm-content").first().waitFor();+ const count = await page.locator(".marimo-cell").count();+ await page.waitForFunction(+ (expected) =>+ document.querySelectorAll(".cm-content").length === expected,+ count,+ );+ if (expectedHeadings !== undefined) {+ await page.waitForFunction(+ ({ selector, expected }) =>+ document.querySelectorAll(selector).length === expected,+ { selector: headingSelector, expected: expectedHeadings },+ );+ }+ await page.waitForFunction(+ () =>+ !document.querySelector(+ '[data-status="running"], [data-status="queued"]',+ ),+ );+ const headingCount = await page.locator(headingSelector).count();+ const editor = page.locator(".cm-content").nth(Math.floor(count / 2));+ await editor.focus();+ await editor.press("ControlOrMeta+End");+ const startingText = await editor.textContent();+ await page.keyboard.type(warmup);+ await page.waitForTimeout(2000);+ const originalText = await editor.textContent();++ await page.evaluate(() => {+ const metrics: BrowserMetrics = {+ phase: "continuous",+ samples: [],+ events: [],+ longTasks: [],+ };+ window.editingMetrics = metrics;+ window.editingCommits?.reset();+ const pending = new WeakMap<+ Event,+ { start: number; sample: Sample }+ >();+ let lastSample: Sample | undefined;+ let inputStart = 0;+ document.addEventListener(+ "keydown",+ (event) => {+ if (+ event.key !== "x" ||+ !(event.target instanceof HTMLElement) ||+ !event.target.closest(".cm-content")+ ) {+ return;+ }+ const start = performance.now();+ const sample = {+ phase: metrics.phase,+ handler: -1,+ input: -1,+ frame: -1,+ };+ lastSample = sample;+ metrics.samples.push(sample);+ pending.set(event, { start, sample });+ requestAnimationFrame(() => {+ // This callback precedes paint. Do not label this value INP.+ sample.frame = performance.now() - start;+ });+ },+ { capture: true },+ );+ document.addEventListener("keydown", (event) => {+ const value = pending.get(event);+ if (value) {+ value.sample.handler = performance.now() - value.start;+ }+ });+ document.addEventListener(+ "beforeinput",+ () => {+ inputStart = performance.now();+ },+ { capture: true },+ );+ document.addEventListener("input", () => {+ if (lastSample && inputStart) {+ lastSample.input = performance.now() - inputStart;+ inputStart = 0;+ }+ });+ new PerformanceObserver((list) => {+ for (const entry of list.getEntries()) {+ metrics.longTasks.push({+ phase: metrics.phase,+ duration: entry.duration,+ });+ }+ }).observe({ type: "longtask" });+ new PerformanceObserver((list) => {+ for (const entry of list.getEntries()) {+ metrics.events.push({+ phase: metrics.phase,+ name: entry.name,+ duration: entry.duration,+ });+ }+ }).observe({+ type: "event",+ durationThreshold: 16,+ } as PerformanceObserverInit);+ });+ const cdp = await context.newCDPSession(page);+ await cdp.send("Emulation.setCPUThrottlingRate", { rate });+ await page.waitForTimeout(500);+ const profile = process.env.EDITING_BENCH_PROFILE === "1";+ let traceComplete: Promise<{ stream?: string }> | undefined;+ if (profile) {+ traceComplete = new Promise((resolve) => {+ cdp.once("Tracing.tracingComplete", resolve);+ });+ await cdp.send("Tracing.start", {+ categories: "devtools.timeline,v8,blink.user_timing",+ transferMode: "ReturnAsStream",+ });+ await cdp.send("Profiler.enable");+ await cdp.send("Profiler.start");+ }+ // Real key events preserve CodeMirror's keyboard and DOM input paths.+ await page.keyboard.type("x".repeat(continuousKeys), { delay: 80 });+ await page.waitForTimeout(500);+ await page.evaluate(() => {+ window.editingMetrics.phase = "paused";+ });+ await page.keyboard.type("x".repeat(pausedKeys), { delay: 400 });+ await page.waitForTimeout(1000);+ const metrics = await page.evaluate(() => window.editingMetrics);+ const react = await page.evaluate(() => {+ const recorder = window.editingCommits;+ return recorder+ ? { version: recorder.version, commits: recorder.commits }+ : undefined;+ });+ if (+ react &&+ !react.commits.some((commit) => commit.renderDuration > 0)+ ) {+ throw new Error("Use the profiling build when EDITING_BENCH_REACT=1");+ }+ if (react && react.commits.length >= 1000) {+ throw new Error("React commit buffer filled; use a shorter run");+ }+ if (profile) {+ const result = await cdp.send("Profiler.stop");+ await writeFile(+ path.join(+ outputDirectory,+ `cells-${count}-cpu-${rate}-run-${repetition}.cpuprofile`,+ ),+ JSON.stringify(result.profile),+ );+ await cdp.send("Tracing.end");+ const trace = await traceComplete;+ if (!trace?.stream) {+ throw new Error("Chrome did not return a trace stream");+ }+ const chunks: string[] = [];+ while (true) {+ const chunk = await cdp.send("IO.read", { handle: trace.stream });+ chunks.push(+ chunk.base64Encoded+ ? Buffer.from(chunk.data, "base64").toString()+ : chunk.data,+ );+ if (chunk.eof) {+ break;+ }+ }+ await cdp.send("IO.close", { handle: trace.stream });+ await writeFile(+ path.join(+ outputDirectory,+ `cells-${count}-cpu-${rate}-run-${repetition}.trace.json`,+ ),+ chunks.join(""),+ );+ }+ const finalText = await editor.textContent();+ if (+ metrics.samples.length !== expectedKeys ||+ finalText !== `${originalText}${"x".repeat(expectedKeys)}` ||+ errors.length > 0+ ) {+ throw new Error(+ `Invalid run: ${JSON.stringify({ samples: metrics.samples.length, textMatches: finalText === `${originalText}${"x".repeat(expectedKeys)}`, errors })}`,+ );+ }+ const summary = {+ url,+ browser: browser.version(),+ cellCount: count,+ headingCount,+ rate,+ repetition,+ continuousKeys,+ pausedKeys,+ units: "ms",+ phases: ["continuous", "paused"].map((phase) => {+ const samples = metrics.samples.filter(+ (sample) => sample.phase === phase,+ );+ return {+ phase,+ keydownHandlers: distribution(+ samples+ .filter((sample) => sample.handler >= 0)+ .map((sample) => sample.handler),+ ),+ beforeInputToInputBubble: distribution(+ samples+ .filter((sample) => sample.input >= 0)+ .map((sample) => sample.input),+ ),+ keydownToAnimationFrame: distribution(+ samples.map((sample) => sample.frame),+ ),+ longTasks: distribution(+ metrics.longTasks+ .filter((task) => task.phase === phase)+ .map((task) => task.duration),+ ),+ // Event Timing omits events below its threshold and quantizes duration.+ slowEvents: distribution(+ metrics.events+ .filter((event) => event.phase === phase)+ .map((event) => event.duration),+ ),+ };+ }),+ metrics,+ react,+ };+ const filename = `cells-${count}-cpu-${rate}-run-${repetition}.json`;+ await writeFile(+ path.join(outputDirectory, filename),+ `${JSON.stringify(summary, null, 2)}\n`,+ );+ process.stdout.write(+ `${JSON.stringify({ filename, phases: summary.phases })}\n`,+ );+ // Restore the fixture so later runs have the same document size.+ await cdp.send("Emulation.setCPUThrottlingRate", { rate: 1 });+ for (let i = 0; i < expectedKeys + warmup.length; i++) {+ await page.keyboard.press("Backspace");+ }+ if ((await editor.textContent()) !== startingText) {+ throw new Error("Failed to restore the fixture");+ }+ await page.waitForTimeout(1500);+ } finally {+ await context.close();+ }+ }+ }+} finally {+ await browser.close();+}diff --git a/frontend/benchmarks/cell-editing.md b/frontend/benchmarks/cell-editing.mdnew file mode 100644index 0000000000..7a4a682f44--- /dev/null+++ b/frontend/benchmarks/cell-editing.md@@ -0,0 +1,152 @@+# Cell editing benchmarks++Measure before changing production code. Use 25 and 100 cells for browser measurements. Use 1,000 cells for scaling tests.++## Instructions++Run each revision three times on an idle machine. Keep the fixture, browser, CPU slowdown, and typing length constant.+Save each run to a separate output path.++### Microbenchmarks++From the repository root:++```sh+mkdir -p .context+cd frontend+pnpm exec vitest bench benchmarks/cell-editing.bench.ts benchmarks/cell-analysis.bench.ts \+ --mode test --run --no-file-parallelism \+ --outputJson ../.context/cell-editing-baseline.json+```++For comparisons, add `--compare ../.context/cell-editing-baseline.json` and change the output filename.++- `cell-editing.bench.ts`: reducer, document conversion, and Jotai subscriptions at 10, 25, 100, and 1,000 cells.+- `cell-analysis.bench.ts`: Python transactions and analyzers at 20, 200, and 2,000 lines, with 1,000 known variables.++These benchmarks exclude React, DOM layout, and network work.++### Browser benchmark++From `frontend`, build the production editor and create disposable fixtures:++```sh+pnpm build+cp -R dist/. ../marimo/_static/+node benchmarks/create-editing-fixtures.ts ../.context/browser-fixtures+cd ../.context/browser-fixtures+uv run --no-project --with-editable ../.. marimo edit . \+ --headless --no-token --skip-update-check --port 29871+```++The fixture directory must not exist. Fixtures contain 20 editable lines per cell, excluding the generated return statement.+Copilot and pylsp are disabled. Default fixtures have no outputs.+Add `--outlines` to create `outline-25.py` and `outline-100.py` with 48 and 198 rendered headings.+The harness restores edits after successful runs. Failed or interrupted runs can leave edits behind.++In another terminal, from `frontend`:++```sh+node benchmarks/cell-editing.browser.ts \+ 'http://127.0.0.1:29871/?file=browser-25.py' ../.context/browser-results+node benchmarks/cell-editing.browser.ts \+ 'http://127.0.0.1:29871/?file=browser-100.py' ../.context/browser-results+```++For fixtures generated with `--outlines`, use these commands instead:++```sh+EDITING_BENCH_HEADINGS=48 node benchmarks/cell-editing.browser.ts \+ 'http://127.0.0.1:29871/?file=outline-25.py' ../.context/outline-results+EDITING_BENCH_HEADINGS=198 node benchmarks/cell-editing.browser.ts \+ 'http://127.0.0.1:29871/?file=outline-100.py' ../.context/outline-results+```++| Environment variable | Default | Purpose |+| --- | --- | --- |+| `EDITING_BENCH_RUNS` | `3` | Repetitions |+| `EDITING_BENCH_RATES` | `1,4,6` | CPU slowdown rates |+| `EDITING_BENCH_CONTINUOUS_KEYS` | `30` | Characters at 80 ms intervals, followed by 20 characters at 400 ms intervals |+| `EDITING_BENCH_HEADINGS` | Unset | Wait for this number of rendered headings before typing |+| `EDITING_BENCH_PROFILE` | `0` | Set to `1` for a CPU profile and browser trace |+| `EDITING_BENCH_REACT` | `0` | Set to `1` for React commit records with the profiling build |++Input duration spans `beforeinput` capture through `input` bubbling. Frame duration spans keydown capture through the next animation frame.+Neither includes initial input queuing or measures keyboard-to-paint latency. JSON also includes long tasks and thresholded Event Timing entries.++### Profiling++For React records, check the recorder and build with profiling enabled:++```sh+node benchmarks/check-react-commits.ts+pnpm exec vite build --config vite.editing-profile.mts+cp -R dist/. ../marimo/_static/+EDITING_BENCH_RUNS=1 EDITING_BENCH_RATES=6 EDITING_BENCH_REACT=1 \+ node benchmarks/cell-editing.browser.ts \+ 'http://127.0.0.1:29871/?file=browser-25.py' ../.context/react-results+```++Recheck the recorder after React upgrades because it uses private DevTools interfaces.+For CPU profiles, set `EDITING_BENCH_PROFILE=1` and open the `.cpuprofile` or `.trace.json` in Chrome DevTools.+For source maps, build with `pnpm exec vite build --sourcemap hidden` and copy `dist/.` again.+Use the normal production build for latency comparisons. Profiling adds overhead.++## Benchmarks++### Browser input processing++*Last recorded: 2026-10-20 · Apple M4 Max · Chromium 153.0.8010.12 · 6× CPU slowdown*++Milliseconds, median of three per-run percentiles. Paused typing uses 20 characters after the continuous burst.++| Cells | Continuous characters | Continuous p50 | Continuous p95 | Paused p50 | Paused p95 |+| --- | --- | --- | --- | --- | --- |+| 25 | 30 | 13.0 | 18.6 | 11.4 | 13.6 |+| 25 | 150 | 10.8 | 14.1 | 11.0 | 13.5 |+| 100 | 30 | 17.3 | 19.2 | 16.7 | 19.4 |++### Input processing with rendered headings++*Last recorded: 2026-10-20 · Apple M4 Max · Chromium 153.0.8010.12 · 6× CPU slowdown · background CPU load present*++Milliseconds, median of three per-run p95 values; 30 continuous and 20 paused characters.+Before/after narrowing outline subscriptions to cell order and runtime state.++| Cells | Headings | Continuous before | Continuous after | Paused before | Paused after |+| --- | --- | --- | --- | --- | --- |+| 25 | 48 | 24.5 | 18.0 | 25.7 | 16.0 |+| 100 | 198 | 74.9 | 24.5 | 38.9 | 23.6 |++The 100-cell continuous p95 ranged from 37.2–110.7 ms before and 22.8–24.9 ms after.++### Favicon input processing++*Last recorded: 2026-10-20 · Apple M4 Max · Chromium 153.0.8010.12 · 6× CPU slowdown · background CPU load present*++Milliseconds, median of three per-run p95 values; no outputs, 150 continuous and 20 paused characters.+Before/after narrowing favicon subscriptions and fixing reset cleanup.++| Cells | Continuous before | Continuous after | Paused before | Paused after |+| --- | --- | --- | --- | --- |+| 25 | 12.9 | 13.2 | 12.4 | 12.2 |+| 100 | 19.7 | 19.5 | 20.5 | 20.6 |++For 50 keystrokes at 25 cells, favicon renders and icon lookups each fell from 50 to 0.++### Isolated operations++*Last recorded: 2026-10-19 · Apple M4 Max · Node 24.22.0 · Vitest 4.1.11 · jsdom*++Milliseconds, median of three run means. Store measurements use synthetic subscriptions and development Jotai.++| Operation | Size | Mean, ms |+| --- | --- | --- |+| Reducer and document conversion | 1,000 cells | 0.0011 |+| Store with cell subscribers | 100 cells | 0.283 |+| Store with cell subscribers | 1,000 cells | 3.525 |+| Store with cell and derived subscribers | 1,000 cells | 4.599 |+| Python state transaction | 2,000 lines | 0.630 |+| Reactive-reference analysis | 2,000 lines | 5.739 |+| Code-lens declaration analysis | 2,000 lines | 0.807 |+| Document serialization | 2,000 lines | 0.0166 |diff --git a/frontend/benchmarks/check-react-commits.ts b/frontend/benchmarks/check-react-commits.tsnew file mode 100644index 0000000000..9661231d13--- /dev/null+++ b/frontend/benchmarks/check-react-commits.ts@@ -0,0 +1,124 @@+/* Copyright 2026 Marimo. All rights reserved. */++import assert from "node:assert/strict";+import { createRequire } from "node:module";+import { chromium } from "@playwright/test";+import { build } from "vite";+import { installReactCommitRecorder } from "./react-commits.ts";++declare global {+ interface Window {+ incrementEdited?: () => void;+ incrementParent?: () => void;+ }+}++const require = createRequire(import.meta.url);+const result = await build({+ configFile: false,+ logLevel: "error",+ define: { "process.env.NODE_ENV": JSON.stringify("production") },+ resolve: {+ alias: [+ { find: /^react$/, replacement: require.resolve("react") },+ {+ find: /^react-dom\/client$/,+ replacement: require.resolve("react-dom/profiling"),+ },+ ],+ },+ plugins: [+ {+ name: "react-commit-probe",+ resolveId(id) {+ if (id.endsWith("/react-commit-probe")) {+ return "\0react-commit-probe";+ }+ },+ load(id) {+ if (id !== "\0react-commit-probe") {+ return;+ }+ return `+ import { createElement as h, memo, useState } from "react";+ import { createRoot } from "react-dom/client";+ const Stable = memo(function Stable() {+ return h("span", null, "stable");+ });+ const Edited = memo(function Edited() {+ const [value, setValue] = useState(0);+ window.incrementEdited = () => setValue((n) => n + 1);+ return h("span", null, value);+ });+ function App() {+ const [value, setValue] = useState(0);+ window.incrementParent = () => setValue((n) => n + 1);+ return h("div", { "data-count": value }, h(Edited), h(Stable));+ }+ createRoot(document.body).render(h(App));+ `;+ },+ },+ ],+ build: {+ write: false,+ minify: false,+ lib: { entry: "react-commit-probe", formats: ["iife"], name: "Probe" },+ },+});+const output = Array.isArray(result) ? result[0] : result;+assert("output" in output);+const chunk = output.output.find((entry) => entry.type === "chunk");+assert(chunk);++const browser = await chromium.launch();+try {+ const page = await browser.newPage();+ await installReactCommitRecorder(page);+ await page.route("http://react-commit-probe.test/", (route) =>+ route.fulfill({+ contentType: "text/html",+ body: "<html><body></body></html>",+ }),+ );+ await page.goto("http://react-commit-probe.test/");+ await page.addScriptTag({ content: chunk.code });+ await page.waitForFunction(() => window.incrementEdited);+ await page.evaluate(() => {+ window.editingMetrics = {+ phase: "probe",+ samples: [],+ events: [],+ longTasks: [],+ };+ window.editingCommits?.reset();+ });+ for (let i = 1; i <= 5; i++) {+ await page.evaluate((iteration) => {+ if (iteration <= 3) {+ window.incrementEdited?.();+ } else {+ window.incrementParent?.();+ }+ }, i);+ await page.waitForFunction(+ (expected) => window.editingCommits?.commits.length === expected,+ i,+ );+ }+ const commits = await page.evaluate(() => window.editingCommits?.commits);+ assert(commits);+ assert(commits.every((commit) => Number.isFinite(commit.renderDuration)));+ const counts: Record<string, number> = {};+ for (const commit of commits) {+ for (const component of commit.components) {+ counts[component.name] = (counts[component.name] ?? 0) + 1;+ }+ }+ assert.deepEqual(counts, { Edited: 3, App: 2 });+ process.stdout.write(+ "React recorder: 3 child renders, 2 parent renders, 0 memoized sibling renders.\n",+ );+} finally {+ await browser.close();+}diff --git a/frontend/benchmarks/create-editing-fixtures.ts b/frontend/benchmarks/create-editing-fixtures.tsnew file mode 100644index 0000000000..40fdb9d3f3--- /dev/null+++ b/frontend/benchmarks/create-editing-fixtures.ts@@ -0,0 +1,49 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { mkdir, writeFile } from "node:fs/promises";+import path from "node:path";++const directory = process.argv[2];+const outlines = process.argv.includes("--outlines");+if (!directory) {+ throw new Error(+ "Usage: node benchmarks/create-editing-fixtures.ts NEW_DIRECTORY [--outlines]",+ );+}+// A new directory prevents overwriting notebooks or personal configuration.+await mkdir(directory, { recursive: false });+await writeFile(+ path.join(directory, ".marimo.toml"),+ `+[runtime]+auto_instantiate = true+[completion]+copilot = false+[language_servers.pylsp]+enabled = false+`,+);+// Stop project configuration discovery before reaching the repository config.+await writeFile(path.join(directory, "pyproject.toml"), "[tool.marimo]\n");++for (const count of [25, 100]) {+ let source = "import marimo\napp = marimo.App()\n";+ for (let i = 0; i < count; i++) {+ const imports = outlines && i === 0;+ const output = outlines && i > 0;+ source += `\[email protected]\ndef _(${output ? "mo" : ""}):\n`;+ source += imports ? " import marimo as mo\n" : ` value_${i} = ${i}\n`;+ for (let line = 2; line <= (output ? 18 : 19); line++) {+ source += ` # line ${line}\n`;+ }+ if (output) {+ source += ` mo.md("## Section ${i}\\n\\n### Details ${i}")\n`;+ }+ source += ` # edit here\n return (${imports ? "mo" : `value_${i}`},)\n`;+ }+ source += '\nif __name__ == "__main__":\n app.run()\n';+ await writeFile(+ path.join(directory, `${outlines ? "outline" : "browser"}-${count}.py`),+ source,+ );+}diff --git a/frontend/benchmarks/react-commits.ts b/frontend/benchmarks/react-commits.tsnew file mode 100644index 0000000000..2c8581b159--- /dev/null+++ b/frontend/benchmarks/react-commits.ts@@ -0,0 +1,119 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { Page } from "@playwright/test";++interface RenderedComponent {+ name: string;+ cellId: string | null;+ changedProps: string[];+}++interface Commit {+ phase: string;+ renderDuration: number;+ components: RenderedComponent[];+}++interface CommitRecorder {+ version: string;+ commits: Commit[];+ reset: () => void;+}++declare global {+ interface Window {+ editingCommits?: CommitRecorder;+ }+}++// This diagnostic uses React's private DevTools hook and Fiber fields.+// Revalidate it after React upgrades; it is not an application dependency.+export async function installReactCommitRecorder(page: Page) {+ await page.addInitScript(() => {+ interface ComponentType {+ name?: string;+ displayName?: string;+ render?: ComponentType;+ type?: ComponentType;+ }+ interface Fiber {+ tag: number;+ flags: number;+ type: ComponentType | null;+ memoizedProps: Record<string, unknown> | null;+ alternate: Fiber | null;+ child: Fiber | null;+ sibling: Fiber | null;+ actualDuration: number;+ }++ const recorder: CommitRecorder = {+ version: "",+ commits: [],+ reset() {+ recorder.commits.length = 0;+ },+ };+ window.editingCommits = recorder;+ Object.assign(window, {+ __REACT_DEVTOOLS_GLOBAL_HOOK__: {+ supportsFiber: true,+ inject(renderer: { version: string }) {+ recorder.version = renderer.version;+ return 1;+ },+ onCommitFiberRoot(_renderer: number, root: { current: Fiber }) {+ // Only record the measured window, after mounting and warmup.+ if (!window.editingMetrics || recorder.commits.length >= 1000) {+ return;+ }+ const components: RenderedComponent[] = [];+ function visit(fiber: Fiber, inheritedCellId: string | null) {+ const previous = fiber.alternate;+ const cellId =+ typeof fiber.memoizedProps?.cellId === "string"+ ? fiber.memoizedProps.cellId+ : inheritedCellId;+ // PerformedWork identifies rendered function/class/memo components.+ if (+ [0, 1, 11, 14, 15].includes(fiber.tag) &&+ (fiber.flags & 1) !== 0+ ) {+ const type = fiber.type;+ const name =+ type?.displayName ??+ type?.name ??+ type?.render?.displayName ??+ type?.render?.name ??+ type?.type?.name ??+ "Anonymous";+ const props = fiber.memoizedProps ?? {};+ const previousProps = previous?.memoizedProps ?? {};+ components.push({+ name,+ cellId,+ changedProps: Object.keys({+ ...previousProps,+ ...props,+ }).filter((key) => !Object.is(props[key], previousProps[key])),+ });+ }+ // A bailed-out parent can reuse its entire previous child list.+ // Do not count stale flags in that reused subtree as new renders.+ if (fiber.child !== previous?.child) {+ for (let child = fiber.child; child; child = child.sibling) {+ visit(child, cellId);+ }+ }+ }+ visit(root.current, null);+ recorder.commits.push({+ phase: window.editingMetrics.phase,+ renderDuration: root.current.actualDuration,+ components,+ });+ },+ },+ });+ });+}diff --git a/frontend/src/components/editor/__tests__/dynamic-favicon.test.tsx b/frontend/src/components/editor/__tests__/dynamic-favicon.test.tsxindex 244b02be10..6aa3397dfa 100644--- a/frontend/src/components/editor/__tests__/dynamic-favicon.test.tsx+++ b/frontend/src/components/editor/__tests__/dynamic-favicon.test.tsx@@ -1,17 +1,41 @@/* Copyright 2026 Marimo. All rights reserved. */-import { render, waitFor } from "@testing-library/react";+import {+ act,+ render as renderComponent,+ waitFor,+} from "@testing-library/react";import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { useCellErrors } from "@/core/cells/cells";+import { Provider, createStore } from "jotai";+import type { ReactNode } from "react";+import { MockNotebook } from "@/__mocks__/notebook";+import { cellId } from "@/__tests__/branded";+import { notebookAtom } from "@/core/cells/cells";import { DynamicFavicon } from "../dynamic-favicon";-// Mock useCellErrors hook-vi.mock("@/core/cells/cells", () => ({- useCellErrors: vi.fn(),-}));-describe("DynamicFavicon", () => {let favicon: HTMLLinkElement;+ let store: ReturnType<typeof createStore>;+ const id = cellId("cell");++ function render(ui: ReactNode) {+ return renderComponent(ui, {+ wrapper: ({ children }) => <Provider store={store}>{children}</Provider>,+ });+ }++ function setErrors() {+ store.set(+ notebookAtom,+ MockNotebook.notebookStateWithErrors([+ {+ cellId: id,+ cellName: "cell",+ errorData: [MockNotebook.errors.syntax("Invalid syntax")],+ },+ ]),+ );+ }beforeEach(() => {document@@ -27,15 +51,20 @@ describe("DynamicFavicon", () => {// Mock document.hasFocusvi.spyOn(document, "hasFocus").mockReturnValue(true);- // Mock useCellErrors to return no errors by default- (useCellErrors as ReturnType<typeof vi.fn>).mockReturnValue([]);+ store = createStore();+ store.set(+ notebookAtom,+ MockNotebook.notebookState({+ cellData: { [id]: { code: "x = 1" } },+ }),+ );});afterEach(() => {document.querySelectorAll("link[rel~='icon']").forEach((element) => element.remove());- vi.clearAllMocks();+ vi.restoreAllMocks();vi.useRealTimers();});@@ -67,9 +96,7 @@ describe("DynamicFavicon", () => {});it("should show error favicon when run completes with errors", async () => {- (useCellErrors as ReturnType<typeof vi.fn>).mockReturnValue([- { error: "mock error" },- ]);+ setErrors();const { rerender } = render(<DynamicFavicon isRunning={true} />);@@ -147,6 +174,72 @@ describe("DynamicFavicon", () => {});});+ it("does not look up or rewrite the favicon when code changes", async () => {+ const { rerender } = render(<DynamicFavicon isRunning={true} />);+ await waitFor(() => expect(favicon.href).toContain("circle-play.ico"));+ rerender(<DynamicFavicon isRunning={false} />);+ await waitFor(() => expect(favicon.href).toContain("circle-check.ico"));+ const lookup = vi.spyOn(document, "querySelector");+ const write = vi.spyOn(favicon, "href", "set");++ await act(async () => {+ store.set(notebookAtom, (state) => ({+ ...state,+ cellData: {+ ...state.cellData,+ [id]: { ...state.cellData[id], code: "x = 2" },+ },+ }));+ });++ expect(+ lookup.mock.calls.filter(+ ([selector]) => selector === "link[rel~='icon']",+ ),+ ).toEqual([]);+ expect(write).not.toHaveBeenCalled();+ lookup.mockRestore();+ write.mockRestore();+ });++ it("updates the favicon when the error count changes", async () => {+ const { rerender } = render(<DynamicFavicon isRunning={true} />);+ await waitFor(() => expect(favicon.href).toContain("circle-play.ico"));+ rerender(<DynamicFavicon isRunning={false} />);+ await waitFor(() => expect(favicon.href).toContain("circle-check.ico"));++ act(() => setErrors());+ await waitFor(() => expect(favicon.href).toContain("circle-x.ico"));++ act(() =>+ store.set(+ notebookAtom,+ MockNotebook.notebookState({ cellData: { [id]: {} } }),+ ),+ );+ await waitFor(() => expect(favicon.href).toContain("circle-check.ico"));+ });++ it("keeps the completion icon until its own reset timer expires", async () => {+ vi.useFakeTimers();+ const { rerender } = render(<DynamicFavicon isRunning={true} />);+ await act(() => vi.advanceTimersByTimeAsync(1000));+ rerender(<DynamicFavicon isRunning={false} />);+ await act(() => vi.advanceTimersByTimeAsync(2000));+ expect(favicon.href).toContain("circle-check.ico");+ await act(() => vi.advanceTimersByTimeAsync(1000));+ expect(favicon.href).toContain("favicon.ico");+ });++ it("cancels the reset timer when unmounted", async () => {+ vi.useFakeTimers();+ const { unmount } = render(<DynamicFavicon isRunning={true} />);+ await act(() => vi.advanceTimersByTimeAsync(0));+ expect(vi.getTimerCount()).toBe(1);+ unmount();+ expect(vi.getTimerCount()).toBe(0);+ });+describe("notifications", () => {beforeEach(() => {vi.spyOn(document, "visibilityState", "get").mockReturnValue("hidden");@@ -156,7 +249,7 @@ describe("DynamicFavicon", () => {global.Notification.permission = "granted";});- it("should send success notification when run completes without errors", () => {+ it("should send success notification when run completes without errors", async () => {// @ts-expect-error ok in testsglobal.Notification = vi.fn()@@ -172,12 +265,11 @@ describe("DynamicFavicon", () => {const { rerender } = render(<DynamicFavicon isRunning={true} />);rerender(<DynamicFavicon isRunning={false} />);+ await waitFor(() => expect(Notification).toHaveBeenCalledOnce());});- it("should send error notification when run completes with errors", () => {- (useCellErrors as ReturnType<typeof vi.fn>).mockReturnValue([- { error: "mock error" },- ]);+ it("should send error notification when run completes with errors", async () => {+ setErrors();// @ts-expect-error ok in testsglobal.Notification = vi@@ -194,6 +286,7 @@ describe("DynamicFavicon", () => {const { rerender } = render(<DynamicFavicon isRunning={true} />);rerender(<DynamicFavicon isRunning={false} />);+ await waitFor(() => expect(Notification).toHaveBeenCalledOnce());});it("should not send notification when document is visible", () => {diff --git a/frontend/src/components/editor/controls/__tests__/command-palette.test.tsx b/frontend/src/components/editor/controls/__tests__/command-palette.test.tsxnew file mode 100644index 0000000000..3bbb344ea3--- /dev/null+++ b/frontend/src/components/editor/controls/__tests__/command-palette.test.tsx@@ -0,0 +1,53 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { fireEvent, render, screen, waitFor } from "@testing-library/react";+import { createStore, Provider } from "jotai";+import { expect, it, vi } from "vitest";+import { useNotebookActions } from "../../actions/useNotebookActions";+import CommandPalette from "../command-palette";++vi.mock("../../actions/useNotebookActions", () => ({+ useNotebookActions: vi.fn(),+}));+vi.mock("../../actions/useCellActionButton", () => ({+ useCellActionButtons: () => [],+}));+vi.mock("../../actions/useConfigActions", () => ({+ useConfigActions: () => [],+}));++it("builds current actions only while open and keeps the opening shortcut active", async () => {+ HTMLElement.prototype.scrollIntoView = vi.fn();+ const firstAction = vi.fn();+ const nextAction = vi.fn();+ vi.mocked(useNotebookActions).mockReturnValue([+ { label: "First action", handle: firstAction },+ ]);+ render(+ <Provider store={createStore()}>+ <CommandPalette />+ </Provider>,+ );+ expect(useNotebookActions).not.toHaveBeenCalled();++ fireEvent.keyDown(document, { key: "k", ctrlKey: true });+ await screen.findByPlaceholderText("Type to search...");+ fireEvent.click(screen.getByText("First action"));+ await waitFor(() => expect(firstAction).toHaveBeenCalledOnce());+ await waitFor(() =>+ expect(screen.queryByPlaceholderText("Type to search...")).toBeNull(),+ );++ vi.mocked(useNotebookActions)+ .mockClear()+ .mockReturnValue([{ label: "Updated action", handle: nextAction }]);+ fireEvent.keyDown(document, { key: "x" });+ expect(useNotebookActions).not.toHaveBeenCalled();++ fireEvent.keyDown(document, { key: "k", ctrlKey: true });+ await screen.findByPlaceholderText("Type to search...");+ expect(screen.queryByText("First action")).toBeNull();+ fireEvent.click(screen.getByText("Updated action"));+ await waitFor(() => expect(nextAction).toHaveBeenCalledOnce());+ expect(firstAction).toHaveBeenCalledOnce();+});diff --git a/frontend/src/components/editor/controls/command-palette.tsx b/frontend/src/components/editor/controls/command-palette.tsxindex d68ebcf1bb..4f33ba8f10 100644--- a/frontend/src/components/editor/controls/command-palette.tsx+++ b/frontend/src/components/editor/controls/command-palette.tsx@@ -1,6 +1,6 @@/* Copyright 2026 Marimo. All rights reserved. */-import { useAtom, useAtomValue } from "jotai";+import { useAtom, useAtomValue, useSetAtom } from "jotai";import {CommandDialog,CommandEmpty,@@ -32,6 +32,25 @@ import { commandPaletteAtom } from "./state";const CommandPalette = () => {const [open, setOpen] = useAtom(commandPaletteAtom);+ const hotkeys = useAtomValue(hotkeysAtom);++ useEventListener(document, "keydown", (e) => {+ if (parseShortcut(hotkeys.getHotkey("global.commandPalette").key)(e)) {+ e.preventDefault();+ setOpen((open) => !open);+ }+ });++ return (+ <CommandDialog open={open} onOpenChange={setOpen}>+ <CommandPaletteContent />+ </CommandDialog>+ );+};++// The dialog mounts these subscriptions only while its content is present.+const CommandPaletteContent = () => {+ const setOpen = useSetAtom(commandPaletteAtom);const registeredActions = useRegisteredActions();const lastFocusedCell = useAtomValue(lastFocusedCellAtom);const hotkeys = useAtomValue(hotkeysAtom);@@ -55,13 +74,6 @@ const CommandPalette = () => {const { recentCommands, addRecentCommand } = useRecentCommands();const recentCommandsSet = new Set(recentCommands);- useEventListener(document, "keydown", (e) => {- if (parseShortcut(hotkeys.getHotkey("global.commandPalette").key)(e)) {- e.preventDefault();- setOpen((open) => !open);- }- });-const renderShortcutCommandItem = (shortcut: HotkeyAction,props: {@@ -142,7 +154,7 @@ const CommandPalette = () => {};return (- <CommandDialog open={open} onOpenChange={setOpen}>+ <><CommandInput placeholder="Type to search..." /><CommandList><CommandEmpty>No results found.</CommandEmpty>@@ -211,7 +223,7 @@ const CommandPalette = () => {})}</CommandGroup></CommandList>- </CommandDialog>+ </>);};diff --git a/frontend/src/components/editor/dynamic-favicon.tsx b/frontend/src/components/editor/dynamic-favicon.tsxindex eac30e148e..22a46833a9 100644--- a/frontend/src/components/editor/dynamic-favicon.tsx+++ b/frontend/src/components/editor/dynamic-favicon.tsx@@ -1,8 +1,9 @@/* Copyright 2026 Marimo. All rights reserved. */import { usePrevious } from "@dnd-kit/utilities";+import { useAtomValue } from "jotai";import { useEffect } from "react";-import { useCellErrors } from "@/core/cells/cells";+import { cellErrorCount } from "@/core/cells/cells";import { useEventListener } from "@/hooks/useEventListener";import successFaviconUrl from "../../assets/circle-check.ico";import runningFaviconUrl from "../../assets/circle-play.ico";@@ -15,13 +16,6 @@ const FAVICON_PATHS = {error: errorFaviconUrl,} as const;-// Cache favicon object URLs lazily-type FaviconKey = keyof typeof FAVICON_PATHS;--async function getFaviconUrl(key: FaviconKey): Promise<string> {- return FAVICON_PATHS[key];-}-function getOrCreateFavicon(): HTMLLinkElement {const existingFavicon =document.querySelector<HTMLLinkElement>("link[rel~='icon']");@@ -44,16 +38,16 @@ function maybeSendNotification(numErrors: number) {return;}- const sendNotification = async () => {+ const sendNotification = () => {if (numErrors === 0) {new Notification("Execution completed", {body: "Your notebook run completed successfully.",- icon: await getFaviconUrl("success"),+ icon: FAVICON_PATHS.success,});} else {new Notification("Execution failed", {body: `Your notebook run encountered ${numErrors} error(s).`,- icon: await getFaviconUrl("error"),+ icon: FAVICON_PATHS.error,});}};@@ -75,7 +69,7 @@ function maybeSendNotification(numErrors: number) {export const DynamicFavicon = (props: Props) => {const { isRunning } = props;- const errors = useCellErrors();+ const numErrors = useAtomValue(cellErrorCount);useEffect(() => {const favicon = getOrCreateFavicon();@@ -86,46 +80,33 @@ export const DynamicFavicon = (props: Props) => {return;}- const updateFavicon = async () => {- let key: FaviconKey;- // When notebook is running, display running favicon- if (isRunning) {- key = "running";- } else {- // When run is complete, display success or error favicon- key = errors.length === 0 ? "success" : "error";- }- favicon.href = await getFaviconUrl(key);+ const key = isRunning ? "running" : numErrors === 0 ? "success" : "error";+ favicon.href = FAVICON_PATHS[key];- // If notebook is in focus, reset favicon after 3 seconds- // If not in focus, the focus event listener handles it- if (!document.hasFocus()) {- return;- }-- const timeoutId = setTimeout(async () => {- favicon.href = await getFaviconUrl("idle");- }, 3000);-- return () => clearTimeout(timeoutId);- };+ if (!document.hasFocus()) {+ // The focus listener resets the favicon when the user returns.+ return;+ }- updateFavicon();- }, [isRunning, errors]);+ const timeoutId = setTimeout(() => {+ favicon.href = FAVICON_PATHS.idle;+ }, 3000);+ return () => clearTimeout(timeoutId);+ }, [isRunning, numErrors]);// Send user notification when run has completedconst prevRunning = usePrevious(isRunning) ?? isRunning;useEffect(() => {if (prevRunning && !isRunning) {- maybeSendNotification(errors.length);+ maybeSendNotification(numErrors);}- }, [errors, prevRunning, isRunning]);+ }, [numErrors, prevRunning, isRunning]);// When notebook comes back in focus, reset favicon- useEventListener(window, "focus", async (_) => {+ useEventListener(window, "focus", () => {if (!isRunning) {const favicon = getOrCreateFavicon();- favicon.href = await getFaviconUrl("idle");+ favicon.href = FAVICON_PATHS.idle;}});diff --git a/frontend/src/core/cells/__tests__/notebook-outline.test.ts b/frontend/src/core/cells/__tests__/notebook-outline.test.tsnew file mode 100644index 0000000000..147df01617--- /dev/null+++ b/frontend/src/core/cells/__tests__/notebook-outline.test.ts@@ -0,0 +1,113 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { createStore } from "jotai";+import { afterEach, describe, expect, it, vi } from "vitest";+import { MockNotebook } from "@/__mocks__/notebook";+import { cellId } from "@/__tests__/branded";+import {+ createNotebookActions,+ notebookAtom,+ notebookOutline,+ notebookReducer,+} from "../cells";+import { exportedForTesting } from "../document-changes";+import type { Outline } from "../outline";++const first = cellId("first");+const second = cellId("second");+const firstOutline: Outline = {+ items: [{ name: "First", level: 1, by: { id: "first" } }],+};+const secondOutline: Outline = {+ items: [{ name: "Second", level: 2, by: { id: "second" } }],+};++function setup() {+ const store = createStore();+ store.set(+ notebookAtom,+ MockNotebook.notebookState({+ cellData: { [first]: { code: "x = 1" }, [second]: {} },+ cellRuntime: {+ [first]: { outline: firstOutline },+ [second]: { outline: secondOutline },+ },+ }),+ );+ const actions = createNotebookActions((action) =>+ store.set(notebookAtom, (state) => notebookReducer(state, action)),+ );+ return { store, actions };+}++afterEach(() => {+ exportedForTesting.cancelPendingChanges();+});++describe("notebookOutline", () => {+ it("does not notify outline subscribers when cell code changes", () => {+ const { store, actions } = setup();+ const initial = store.get(notebookOutline);+ const listener = vi.fn();+ const unsubscribe = store.sub(notebookOutline, listener);++ actions.updateCellCode({+ cellId: first,+ code: "x = 2",+ formattingChange: false,+ });++ expect(store.get(notebookOutline)).toBe(initial);+ expect(listener).not.toHaveBeenCalled();+ unsubscribe();+ });++ it("updates headings when runtime outlines change or are removed", () => {+ const { store } = setup();+ const updated: Outline = {+ items: [{ name: "Updated", level: 1, by: { id: "updated" } }],+ };++ for (const outline of [updated, null]) {+ store.set(notebookAtom, (state) => ({+ ...state,+ cellRuntime: {+ ...state.cellRuntime,+ [first]: { ...state.cellRuntime[first], outline },+ },+ }));+ expect(store.get(notebookOutline)).toEqual({+ items: [...(outline?.items ?? []), ...secondOutline.items],+ });+ }+ });++ it("keeps headings in cell order after moving and deleting cells", () => {+ const { store, actions } = setup();+ actions.moveCell({ cellId: second, before: true });+ expect(store.get(notebookOutline)).toEqual({+ items: [...secondOutline.items, ...firstOutline.items],+ });++ actions.deleteCell({ cellId: second });+ expect(store.get(notebookOutline)).toEqual(firstOutline);+ });++ it("notifies subscribers when output is replaced with the same headings", () => {+ const { store } = setup();+ const listener = vi.fn();+ const unsubscribe = store.sub(notebookOutline, listener);++ store.set(notebookAtom, (state) => ({+ ...state,+ cellRuntime: {+ ...state.cellRuntime,+ [first]: { ...state.cellRuntime[first], outline: { ...firstOutline } },+ },+ }));++ // Consumers must reconnect to replacement heading elements in the DOM.+ expect(listener).toHaveBeenCalledOnce();+ unsubscribe();+ });+});diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.tsindex ef4248a31b..51e83dfb93 100644--- a/frontend/src/core/cells/cells.ts+++ b/frontend/src/core/cells/cells.ts@@ -1761,7 +1761,8 @@ export const cellErrorsAtom = atom((get) => {});export const notebookOutline = atom((get) => {- const { cellIds, cellRuntime } = get(notebookAtom);+ const cellIds = get(cellIdsAtom);+ const cellRuntime = get(cellsRuntimeAtom);const outlines = cellIds.inOrderIds.map((cellId) => cellRuntime[cellId].outline,);diff --git a/frontend/tsconfig.json b/frontend/tsconfig.jsonindex 3b821e3ad4..b577b9b32a 100644--- a/frontend/tsconfig.json+++ b/frontend/tsconfig.json@@ -36,5 +36,5 @@"incremental": true,"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo"},- "include": ["src", "scripts", "playwright.config.ts", "e2e-tests"]+ "include": ["src", "scripts", "benchmarks", "playwright.config.ts", "e2e-tests"]}diff --git a/frontend/vite.editing-profile.mts b/frontend/vite.editing-profile.mtsnew file mode 100644index 0000000000..d3a8884fe2--- /dev/null+++ b/frontend/vite.editing-profile.mts@@ -0,0 +1,16 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { defineConfig, mergeConfig } from "vite";+import config from "./vite.config.mts";++// Use only for attribution. Measure latency with the normal production build.+export default defineConfig(+ mergeConfig(config, {+ resolve: {+ alias: [+ { find: /^react-dom\/client$/, replacement: "react-dom/profiling" },+ ],+ },+ build: { minify: false, sourcemap: true },+ }),+);