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
feat: experimental line_timing — green active-line highlight + per-line timer (#10126)
Myles Scolnickf8be7db3e8e3
diff --git a/frontend/src/__tests__/CellStatus.test.tsx b/frontend/src/__tests__/CellStatus.test.tsxindex 6cc9391b7a..bdf8e8b8e7 100644--- a/frontend/src/__tests__/CellStatus.test.tsx+++ b/frontend/src/__tests__/CellStatus.test.tsx@@ -3,11 +3,10 @@import { render } from "@testing-library/react";import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";import { TooltipProvider } from "@/components/ui/tooltip";-import type { Seconds } from "@/utils/time";+import { formatElapsedTime, type Seconds } from "@/utils/time";import {CellStatusComponent,ElapsedTime,- formatElapsedTime,} from "../components/editor/cell/CellStatus";// Mock date-fns to have consistent date formatting in testsdiff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsxindex 4bbb887d27..ebc8db2e87 100644--- a/frontend/src/components/app-config/user-config-form.tsx+++ b/frontend/src/components/app-config/user-config-form.tsx@@ -1314,6 +1314,32 @@ export const UserConfigForm: React.FC = () => {</div>)}/>+ <OverriddenFormField+ control={form.control}+ name="experimental.line_timing"+ render={({ field, override }) => (+ <div className="flex flex-col gap-y-1">+ <FormItem className={formItemClasses}>+ <FormLabel className="font-normal">Line Timing</FormLabel>+ <FormControl>+ <Checkbox+ data-testid="line-timing-checkbox"+ checked={override.value === true}+ disabled={override.isOverridden}+ onCheckedChange={field.onChange}+ />+ </FormControl>+ </FormItem>+ <IsOverridden override={override} />+ <FormDescription>+ Highlight the line a cell is currently executing in green,+ with an elapsed timer next to long-running lines. Adds+ tracing overhead to every run while enabled. This change+ requires a page refresh to take effect.+ </FormDescription>+ </div>+ )}+ /></SettingGroup>);}diff --git a/frontend/src/components/editor/cell/CellStatus.tsx b/frontend/src/components/editor/cell/CellStatus.tsxindex 7ce5c032fa..5313f36554 100644--- a/frontend/src/components/editor/cell/CellStatus.tsx+++ b/frontend/src/components/editor/cell/CellStatus.tsx@@ -14,7 +14,7 @@ import { Tooltip } from "../../ui/tooltip";import "./cell-status.css";import { formatDistanceToNow } from "date-fns";-import { Time } from "@/utils/time";+import { formatElapsedTime, Time } from "@/utils/time";export interface CellStatusComponentProps extends Pick<CellRuntimeState,@@ -348,25 +348,6 @@ const LastRanTime = (props: { lastRanTime: number }) => {);};-export function formatElapsedTime(elapsedTime: number | null) {- if (elapsedTime === null) {- return "";- }-- const milliseconds = elapsedTime;- const seconds = milliseconds / 1000;-- if (seconds >= 60) {- const minutes = Math.floor(seconds / 60);- const remainingSeconds = Math.floor(seconds % 60);- return `${minutes}m${remainingSeconds}s`;- }- if (seconds >= 1) {- return `${seconds.toFixed(2).toString()}s`;- }- return `${milliseconds.toFixed(0).toString()}ms`;-}-const CellTimer = (props: { startTime: Time }) => {const time = useElapsedTime(props.startTime.toMilliseconds());return <span>{formatElapsedTime(time)}</span>;diff --git a/frontend/src/components/editor/cell/PendingDeleteConfirmation.tsx b/frontend/src/components/editor/cell/PendingDeleteConfirmation.tsxindex c6c447bca1..393cfac046 100644--- a/frontend/src/components/editor/cell/PendingDeleteConfirmation.tsx+++ b/frontend/src/components/editor/cell/PendingDeleteConfirmation.tsx@@ -3,12 +3,12 @@import { AlertTriangleIcon } from "lucide-react";import React from "react";import { FocusScope } from "react-aria";-import { formatElapsedTime } from "@/components/editor/cell/CellStatus";import { CellLink } from "@/components/editor/links/cell-link";import { Button } from "@/components/ui/button";import type { CellId } from "@/core/cells/ids";import { usePendingDelete } from "@/core/cells/pending-delete-service";import { cn } from "@/utils/cn";+import { formatElapsedTime } from "@/utils/time";export const PendingDeleteConfirmation: React.FC<{ cellId: CellId }> = ({cellId,diff --git a/frontend/src/components/tracing/tracing.tsx b/frontend/src/components/tracing/tracing.tsxindex f742c847c6..6acd100a2e 100644--- a/frontend/src/components/tracing/tracing.tsx+++ b/frontend/src/components/tracing/tracing.tsx@@ -28,9 +28,10 @@ import {} from "@/core/cells/runs";import { type ResolvedTheme, useTheme } from "@/theme/useTheme";import { cn } from "@/utils/cn";+import { formatElapsedTime } from "@/utils/time";import { ClearButton } from "../buttons/clear-button";import type { SignalListener } from "../charts/types";-import { ElapsedTime, formatElapsedTime } from "../editor/cell/CellStatus";+import { ElapsedTime } from "../editor/cell/CellStatus";import { PanelEmptyState } from "../editor/chrome/panels/empty-state";import { usePanelSection } from "../editor/chrome/panels/panel-context";import { CellLink } from "../editor/links/cell-link";diff --git a/frontend/src/core/codemirror/cells/__tests__/debugger-state.test.ts b/frontend/src/core/codemirror/cells/__tests__/debugger-state.test.tsindex 415a0c62cd..0ae4eb8df2 100644--- a/frontend/src/core/codemirror/cells/__tests__/debugger-state.test.ts+++ b/frontend/src/core/codemirror/cells/__tests__/debugger-state.test.ts@@ -1,16 +1,18 @@/* Copyright 2026 Marimo. All rights reserved. */-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { MockRequestClient } from "@/__mocks__/requests";import { cellId } from "@/__tests__/branded";import { store } from "@/core/state/jotai";import {+ activeLineAtom,breakpointsAtom,clearCellBreakpoints,+ createActiveLineInfoAtom,createCellBreakpointsAtom,createDebuggerLineAtom,- debuggerCurrentLineAtom,resyncBreakpoints,+ setActiveLine,toggleBreakpoint,} from "../debugger-state";@@ -25,7 +27,7 @@ const cell2 = cellId("cell2");describe("debugger-state", () => {beforeEach(() => {store.set(breakpointsAtom, new Map());- store.set(debuggerCurrentLineAtom, null);+ store.set(activeLineAtom, null);vi.clearAllMocks();});@@ -130,10 +132,93 @@ describe("debugger-state", () => {});it("returns the line only for the matching cell", () => {- store.set(debuggerCurrentLineAtom, { cellId: cell1, line: 10 });+ store.set(activeLineAtom, { cellId: cell1, line: 10, startedAtMs: 0 });expect(store.get(createDebuggerLineAtom(cell1))).toBe(10);expect(store.get(createDebuggerLineAtom(cell2))).toBeNull();});});++ describe("setActiveLine", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("stamps startedAtMs when the line is first set", () => {+ vi.setSystemTime(1000);+ setActiveLine({ cellId: cell1, line: 3 });++ expect(store.get(activeLineAtom)).toEqual({+ cellId: cell1,+ line: 3,+ startedAtMs: 1000,+ });+ });++ it("preserves startedAtMs when the same line is set again", () => {+ vi.setSystemTime(1000);+ setActiveLine({ cellId: cell1, line: 3 });+ vi.setSystemTime(2000);+ setActiveLine({ cellId: cell1, line: 3 });++ expect(store.get(activeLineAtom)).toEqual({+ cellId: cell1,+ line: 3,+ startedAtMs: 1000,+ });+ });++ it("resets startedAtMs when the line changes", () => {+ vi.setSystemTime(1000);+ setActiveLine({ cellId: cell1, line: 3 });+ vi.setSystemTime(2000);+ setActiveLine({ cellId: cell1, line: 4 });++ expect(store.get(activeLineAtom)).toEqual({+ cellId: cell1,+ line: 4,+ startedAtMs: 2000,+ });+ });++ it("resets startedAtMs when the cell changes", () => {+ vi.setSystemTime(1000);+ setActiveLine({ cellId: cell1, line: 3 });+ vi.setSystemTime(2000);+ setActiveLine({ cellId: cell2, line: 3 });++ expect(store.get(activeLineAtom)).toEqual({+ cellId: cell2,+ line: 3,+ startedAtMs: 2000,+ });+ });++ it("clears the active line on null", () => {+ setActiveLine({ cellId: cell1, line: 3 });+ setActiveLine(null);++ expect(store.get(activeLineAtom)).toBeNull();+ });+ });++ describe("createActiveLineInfoAtom", () => {+ it("returns null when no line is set", () => {+ expect(store.get(createActiveLineInfoAtom(cell1))).toBeNull();+ });++ it("returns line info only for the matching cell", () => {+ store.set(activeLineAtom, { cellId: cell1, line: 10, startedAtMs: 42 });++ expect(store.get(createActiveLineInfoAtom(cell1))).toEqual({+ line: 10,+ startedAtMs: 42,+ });+ expect(store.get(createActiveLineInfoAtom(cell2))).toBeNull();+ });+ });});diff --git a/frontend/src/core/codemirror/cells/__tests__/line-timing-decorations.test.ts b/frontend/src/core/codemirror/cells/__tests__/line-timing-decorations.test.tsnew file mode 100644index 0000000000..366c37fb06--- /dev/null+++ b/frontend/src/core/codemirror/cells/__tests__/line-timing-decorations.test.ts@@ -0,0 +1,126 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { python } from "@codemirror/lang-python";+import { EditorState } from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { createMockObservable } from "@/core/state/__mocks__/mocks";+import type { Observable } from "@/core/state/observable";+import {+ type ActiveLineInfo,+ activeLineTimer,+} from "../line-timing-decorations";++type MockObservable = Observable<ActiveLineInfo | null> & {+ set: (value: ActiveLineInfo | null) => void;+};++function createEditor(+ content: string,+ infoObservable: Observable<ActiveLineInfo | null>,+) {+ const state = EditorState.create({+ doc: content,+ extensions: [python(), activeLineTimer(infoObservable)],+ });++ return new EditorView({+ state,+ parent: document.body,+ });+}++const CODE = `a = 1+b = 2+c = 3`;++describe("line-timing-decorations", () => {+ let view: EditorView | null = null;+ let observable: MockObservable;++ beforeEach(() => {+ vi.useFakeTimers();+ vi.setSystemTime(10_000);+ observable = createMockObservable<ActiveLineInfo | null>(null);+ });++ afterEach(() => {+ if (view) {+ view.destroy();+ view = null;+ }+ document.body.innerHTML = "";+ vi.useRealTimers();+ });++ it("highlights the active line and no other", () => {+ view = createEditor(CODE, observable);++ expect(view.dom.querySelector(".cm-timing-current-line")).toBeNull();++ observable.set({ line: 2, startedAtMs: Date.now() });++ const highlighted = view.dom.querySelectorAll(".cm-timing-current-line");+ expect(highlighted).toHaveLength(1);+ expect(highlighted[0].textContent).toContain("b = 2");+ });++ it("keeps the timer empty before the threshold and formats after", () => {+ view = createEditor(CODE, observable);+ observable.set({ line: 1, startedAtMs: Date.now() });++ const timer = view.dom.querySelector(".cm-line-timer");+ expect(timer).not.toBeNull();+ expect(timer?.textContent).toBe("");++ // Still below the 500ms threshold.+ vi.advanceTimersByTime(250);+ expect(timer?.textContent).toBe("");++ // Past the threshold: shows the elapsed time and keeps ticking.+ vi.advanceTimersByTime(500);+ expect(timer?.textContent).toBe("750ms");++ vi.advanceTimersByTime(1000);+ expect(timer?.textContent).toBe("1.75s");+ });++ it("reuses the widget DOM node when startedAtMs is unchanged", () => {+ view = createEditor(CODE, observable);+ observable.set({ line: 1, startedAtMs: Date.now() });++ const before = view.dom.querySelector(".cm-line-timer");+ expect(before).not.toBeNull();++ // A fresh info object for the same line and start time (e.g. a duplicate+ // notification) must not recreate the widget.+ observable.set({ line: 1, startedAtMs: 10_000 });++ expect(view.dom.querySelector(".cm-line-timer")).toBe(before);+ });++ it("clears the timer interval when the widget is destroyed", () => {+ const setIntervalSpy = vi.spyOn(window, "setInterval");+ const clearIntervalSpy = vi.spyOn(window, "clearInterval");+ view = createEditor(CODE, observable);+ observable.set({ line: 1, startedAtMs: Date.now() });++ expect(view.dom.querySelector(".cm-line-timer")).not.toBeNull();+ expect(setIntervalSpy).toHaveBeenCalledTimes(1);+ const intervalId = setIntervalSpy.mock.results[0].value;++ observable.set(null);++ expect(view.dom.querySelector(".cm-line-timer")).toBeNull();+ expect(clearIntervalSpy).toHaveBeenCalledWith(intervalId);+ });++ it("renders nothing for an out-of-range line", () => {+ view = createEditor(CODE, observable);++ observable.set({ line: 100, startedAtMs: Date.now() });++ expect(view.dom.querySelector(".cm-timing-current-line")).toBeNull();+ expect(view.dom.querySelector(".cm-line-timer")).toBeNull();+ });+});diff --git a/frontend/src/core/codemirror/cells/debugger-state.ts b/frontend/src/core/codemirror/cells/debugger-state.tsindex af18890ccd..0aeb0c8316 100644--- a/frontend/src/core/codemirror/cells/debugger-state.ts+++ b/frontend/src/core/codemirror/cells/debugger-state.ts@@ -2,27 +2,50 @@import { atom } from "jotai";import type { CellId } from "@/core/cells/ids";+import type { ActiveLineInfo } from "@/core/codemirror/cells/line-timing-decorations";import { getRequestClient } from "@/core/network/requests";import { store } from "@/core/state/jotai";import { Logger } from "@/utils/Logger";/**- * State for the experimental live debugger.+ * State for the experimental live debugger and line-timing highlight.*- * - `debuggerCurrentLineAtom` holds the cell + line the kernel's frame watcher- * is currently executing (driven by `active-line` notifications). Only one- * cell runs at a time, so a single global value suffices.+ * - `activeLineAtom` holds the cell + line the kernel's frame watcher is+ * currently executing (driven by `active-line` notifications), plus when+ * the frontend first saw execution on that line. Only one cell runs at a+ * time, so a single global value suffices.* - `breakpointsAtom` holds the user's gutter breakpoints, session-only. It is* the source of truth; mutations are mirrored to the kernel via* `sendSetBreakpoints`.*/-export interface DebuggerLine {+export interface ActiveLine {cellId: CellId;line: number;+ /** When the frontend first saw execution on this (cellId, line). */+ startedAtMs: number;}-export const debuggerCurrentLineAtom = atom<DebuggerLine | null>(null);+export const activeLineAtom = atom<ActiveLine | null>(null);++/**+ * Update the active line, stamping `startedAtMs` only when the (cellId, line)+ * actually changes, so duplicate notifications (e.g. reconnects) never reset+ * the elapsed-time baseline.+ */+export function setActiveLine(+ next: { cellId: CellId; line: number } | null,+): void {+ const prev = store.get(activeLineAtom);+ if (next === null) {+ store.set(activeLineAtom, null);+ return;+ }+ if (prev?.cellId === next.cellId && prev.line === next.line) {+ return;+ }+ store.set(activeLineAtom, { ...next, startedAtMs: Date.now() });+}export const breakpointsAtom = atom<ReadonlyMap<CellId, ReadonlySet<number>>>(new Map<CellId, ReadonlySet<number>>(),@@ -33,11 +56,21 @@ const EMPTY_LINES: ReadonlySet<number> = new Set();/** Per-cell derived atom: the current debug line for `cellId`, or `null`. */export function createDebuggerLineAtom(cellId: CellId) {return atom((get) => {- const current = get(debuggerCurrentLineAtom);+ const current = get(activeLineAtom);return current?.cellId === cellId ? current.line : null;});}+/** Per-cell derived atom: the active line + start time for `cellId`, or `null`. */+export function createActiveLineInfoAtom(cellId: CellId) {+ return atom((get): ActiveLineInfo | null => {+ const current = get(activeLineAtom);+ return current?.cellId === cellId+ ? { line: current.line, startedAtMs: current.startedAtMs }+ : null;+ });+}+/** Per-cell derived atom: the breakpoint lines for `cellId`. */export function createCellBreakpointsAtom(cellId: CellId) {return atom((get) => get(breakpointsAtom).get(cellId) ?? EMPTY_LINES);diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.tsindex 2b8b878840..e6e77f3262 100644--- a/frontend/src/core/codemirror/cells/extensions.ts+++ b/frontend/src/core/codemirror/cells/extensions.ts@@ -31,9 +31,11 @@ import {debuggerLineHighlighter,} from "./debugger-decorations";import {+ createActiveLineInfoAtom,createCellBreakpointsAtom,createDebuggerLineAtom,} from "./debugger-state";+import { activeLineTimer } from "./line-timing-decorations";import {type CodemirrorCellActions,cellActionsState,@@ -429,6 +431,8 @@ export function cellBundle({cellActions: CodemirrorCellActions;keymapConfig: KeymapConfig;}): Extension[] {+ const debuggerOn = getFeatureFlag("debugger");+ const lineTimingOn = getFeatureFlag("line_timing");return [cellActionsState.of(cellActions),cellIdState.of(cellId),@@ -437,19 +441,24 @@ export function cellBundle({errorLineHighlighter(createObservable(createTracebackInfoAtom(cellId), store),),- // Experimental live debugger: clickable breakpoint gutter + current-line- // highlight. Gated so there is no gutter/overhead when disabled.- getFeatureFlag("debugger")- ? [- breakpointGutter(- cellId,- createObservable(createCellBreakpointsAtom(cellId), store),- ),- debuggerLineHighlighter(- createObservable(createDebuggerLineAtom(cellId), store),- ),- ]+ // Experimental live debugger and line-timing highlight. Gated so there is+ // no gutter/overhead when disabled. Both track the same active line; when+ // both flags are on, the green timing highlight replaces the amber one.+ debuggerOn+ ? breakpointGutter(+ cellId,+ createObservable(createCellBreakpointsAtom(cellId), store),+ ): [],+ lineTimingOn+ ? activeLineTimer(+ createObservable(createActiveLineInfoAtom(cellId), store),+ )+ : debuggerOn+ ? debuggerLineHighlighter(+ createObservable(createDebuggerLineAtom(cellId), store),+ )+ : [],];}diff --git a/frontend/src/core/codemirror/cells/line-timing-decorations.ts b/frontend/src/core/codemirror/cells/line-timing-decorations.tsnew file mode 100644index 0000000000..b4300a94d1--- /dev/null+++ b/frontend/src/core/codemirror/cells/line-timing-decorations.ts@@ -0,0 +1,165 @@+/* Copyright 2026 Marimo. All rights reserved. */++import {+ type EditorState,+ type Extension,+ RangeSetBuilder,+} from "@codemirror/state";+import {+ Decoration,+ type DecorationSet,+ EditorView,+ type PluginValue,+ ViewPlugin,+ type ViewUpdate,+ WidgetType,+} from "@codemirror/view";+import type { Observable } from "@/core/state/observable";+import { Logger } from "@/utils/Logger";+import { formatElapsedTime } from "@/utils/time";++/** The line a cell is currently executing and when execution first hit it. */+export interface ActiveLineInfo {+ line: number;+ startedAtMs: number;+}++// Only show the timer once a line has been busy this long, so short-lived+// lines never flash a pill.+const SHOW_TIMER_AFTER_MS = 500;+const TICK_INTERVAL_MS = 250;++/**+ * End-of-line elapsed-time pill for the currently executing line.+ *+ * Ticking is pure DOM mutation on the widget's own interval; no editor+ * transactions are dispatched while the timer counts.+ */+class LineTimerWidget extends WidgetType {+ // Track intervals per DOM node: CodeMirror may reuse the node across+ // decoration remaps (`eq` below), and `destroy` only receives the node.+ private static readonly intervals = new WeakMap<HTMLElement, number>();++ private readonly startedAtMs: number;++ constructor(startedAtMs: number) {+ super();+ this.startedAtMs = startedAtMs;+ }++ override eq(other: LineTimerWidget): boolean {+ return other.startedAtMs === this.startedAtMs;+ }++ override toDOM(): HTMLElement {+ const el = document.createElement("span");+ el.className = "cm-line-timer";+ el.setAttribute("aria-hidden", "true");+ const tick = () => {+ const elapsed = Date.now() - this.startedAtMs;+ el.textContent =+ elapsed >= SHOW_TIMER_AFTER_MS ? formatElapsedTime(elapsed) : "";+ };+ tick();+ LineTimerWidget.intervals.set(+ el,+ window.setInterval(tick, TICK_INTERVAL_MS),+ );+ return el;+ }++ override destroy(dom: HTMLElement): void {+ const interval = LineTimerWidget.intervals.get(dom);+ if (interval !== undefined) {+ window.clearInterval(interval);+ LineTimerWidget.intervals.delete(dom);+ }+ }++ override ignoreEvent(): boolean {+ return true;+ }+}++function createTimingDecorations(+ state: EditorState,+ info: ActiveLineInfo | null,+): DecorationSet {+ if (info === null || info.line < 1 || info.line > state.doc.lines) {+ return Decoration.none;+ }+ const builder = new RangeSetBuilder<Decoration>();+ try {+ const line = state.doc.line(info.line);+ builder.add(+ line.from,+ line.from,+ Decoration.line({ class: "cm-timing-current-line" }),+ );+ builder.add(+ line.to,+ line.to,+ Decoration.widget({+ widget: new LineTimerWidget(info.startedAtMs),+ side: 1,+ }),+ );+ } catch (error) {+ Logger.debug("Invalid timing line", { error });+ }+ return builder.finish();+}++class ActiveLineTimer implements PluginValue {+ private unsubscribe: () => void;+ decorations: DecorationSet;++ constructor(+ view: EditorView,+ infoObservable: Observable<ActiveLineInfo | null>,+ ) {+ this.decorations = createTimingDecorations(+ view.state,+ infoObservable.get(),+ );+ this.unsubscribe = infoObservable.sub((info) => {+ this.decorations = createTimingDecorations(view.state, info);+ // Force a re-render; the decoration set changed out of band.+ view.dispatch({ userEvent: "marimo.timing-line-update" });+ });+ }++ update(update: ViewUpdate) {+ this.decorations = this.decorations.map(update.changes);+ }++ destroy() {+ this.unsubscribe();+ }+}++/**+ * Highlight the line a cell's frame watcher is currently executing in green,+ * with a dim elapsed-time pill at the end of the line once it has been busy+ * for a while.+ */+export function activeLineTimer(+ infoObservable: Observable<ActiveLineInfo | null>,+): Extension {+ return [+ ViewPlugin.define((view) => new ActiveLineTimer(view, infoObservable), {+ decorations: (plugin) => plugin.decorations,+ }),+ EditorView.theme({+ ".cm-timing-current-line": {+ backgroundColor: "color-mix(in srgb, var(--grass-4) 50%, transparent)",+ },+ ".cm-line-timer": {+ color: "var(--grass-11)",+ fontSize: "0.85em",+ marginLeft: "1.5ch",+ pointerEvents: "none",+ },+ }),+ ];+}diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsxindex 29cee5a82c..695f691ecf 100644--- a/frontend/src/core/config/feature-flag.tsx+++ b/frontend/src/core/config/feature-flag.tsx@@ -12,6 +12,7 @@ export interface ExperimentalFeatures {cache_panel: boolean;external_agents: boolean;debugger: boolean; // Live frame-watching debugger (gutter breakpoints + pdb)+ line_timing: boolean; // Green active-line highlight + per-line elapsed timer// Add new feature flags here}@@ -22,6 +23,7 @@ const defaultValues: ExperimentalFeatures = {cache_panel: false,external_agents: import.meta.env.DEV,debugger: false,+ line_timing: false,};export function getFeatureFlag<T extends keyof ExperimentalFeatures>(diff --git a/frontend/src/core/websocket/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useMarimoKernelConnection.tsxindex 023338c1d3..6bde5e3206 100644--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx+++ b/frontend/src/core/websocket/useMarimoKernelConnection.tsx@@ -33,8 +33,8 @@ import { SCRATCH_CELL_ID } from "../cells/ids";import { useRunsActions } from "../cells/runs";import { focusAndScrollCellOutputIntoView } from "../cells/scrollCellIntoView";import {- debuggerCurrentLineAtom,resyncBreakpoints,+ setActiveLine,} from "../codemirror/cells/debugger-state";import type { CellData } from "../cells/types";import { capabilitiesAtom } from "../config/capabilities";@@ -226,7 +226,6 @@ export function useMarimoKernelConnection(opts: {const transportType = useAtomValue(connectionTransportTypeAtom);const setCacheInfo = useSetAtom(cacheInfoAtom);const setKernelStartupError = useSetAtom(kernelStartupErrorAtom);- const setDebuggerCurrentLine = useSetAtom(debuggerCurrentLineAtom);const {setNamespaces: setStorageNamespaces,filterFromVariables: filterStorageFromVariables,@@ -255,7 +254,7 @@ export function useMarimoKernelConnection(opts: {// A freshly started kernel has no breakpoints of its own; re-push// the client's set so they still apply, and clear the stale// highlighted line from the previous kernel instance.- setDebuggerCurrentLine(null);+ setActiveLine(null);resyncBreakpoints();return;}@@ -429,7 +428,7 @@ export function useMarimoKernelConnection(opts: {focusAndScrollCellOutputIntoView(msg.data.cell_id);return;case "active-line":- setDebuggerCurrentLine(+ setActiveLine(msg.data.line == null? null: { cellId: msg.data.cell_id, line: msg.data.line },diff --git a/frontend/src/utils/time.ts b/frontend/src/utils/time.tsindex 589e91d551..160de66e9e 100644--- a/frontend/src/utils/time.ts+++ b/frontend/src/utils/time.ts@@ -43,3 +43,23 @@ export class Time {return (this.ms / 1000) as Seconds;}}++/** Format a duration in milliseconds, e.g. `500ms`, `1.50s`, `1m30s`. */+export function formatElapsedTime(elapsedTime: number | null): string {+ if (elapsedTime === null) {+ return "";+ }++ const milliseconds = elapsedTime;+ const seconds = milliseconds / 1000;++ if (seconds >= 60) {+ const minutes = Math.floor(seconds / 60);+ const remainingSeconds = Math.floor(seconds % 60);+ return `${minutes}m${remainingSeconds}s`;+ }+ if (seconds >= 1) {+ return `${seconds.toFixed(2).toString()}s`;+ }+ return `${milliseconds.toFixed(0).toString()}ms`;+}diff --git a/marimo/_config/config.py b/marimo/_config/config.pyindex b795f27b9c..df0414a334 100644--- a/marimo/_config/config.py+++ b/marimo/_config/config.py@@ -610,6 +610,7 @@ class ExperimentalConfig(TypedDict, total=False):rtc_v2: boolisolate_apps: booldebugger: bool # Live frame-watching debugger (gutter breakpoints + pdb)+ line_timing: bool # Active-line highlight + per-line timer (sys.settrace)# Internal featurescache: CacheConfigdiff --git a/marimo/_runtime/executor/lifecycles/debugger.py b/marimo/_runtime/executor/lifecycles/debugger.pyindex bf8ba54bf7..a664936f31 100644--- a/marimo/_runtime/executor/lifecycles/debugger.py+++ b/marimo/_runtime/executor/lifecycles/debugger.py@@ -1,5 +1,8 @@# Copyright 2026 Marimo. All rights reserved.-"""DebuggerLifecycle frame-watches each cell body for the live debugger."""+"""DebuggerLifecycle frame-watches each cell body.++Powers the experimental live debugger and line-timing highlight.+"""from __future__ import annotations@@ -22,7 +25,7 @@ if TYPE_CHECKING:class FrameWatcher:- """Frame watcher for the experimental live debugger.+ """Frame watcher powering the live debugger and line-timing highlight.Installed around a single cell's execution (via `DebuggerLifecycle`):`install()` registers a `sys.settrace` hook on the executing thread and@@ -36,6 +39,10 @@ class FrameWatcher:- drops into `MarimoPdb` when a line with a registered breakpoint is hit,handing tracing off to pdb for the rest of the cell.+ The debugger is optional: with `debugger=None` (the `line_timing` flag+ without the `debugger` flag) the watcher only streams the active line and+ never enters pdb.+`settrace` is per-thread, so only the cell-executing thread is traced. Theheartbeat runs on its own thread (it must emit even while a synchronouscell blocks the kernel thread) using a stream copied for cross-thread use.@@ -46,7 +53,7 @@ class FrameWatcher:# Don't block teardown indefinitely waiting on the heartbeat thread._JOIN_TIMEOUT_S = 1.0- def __init__(self, debugger: MarimoPdb) -> None:+ def __init__(self, debugger: MarimoPdb | None) -> None:self._debugger = debuggerself._installed = Falseself._prev_trace: Any = None@@ -81,7 +88,8 @@ class FrameWatcher:# marimo owns interrupt handling. Stop pdb from installing its own# SIGINT handler (which would turn an interrupt into a debugger break# instead of actually interrupting the cell).- self._debugger.disable_sigint()+ if self._debugger is not None:+ self._debugger.disable_sigint()self._installed = Trueself._current = None@@ -137,8 +145,9 @@ class FrameWatcher:self._current = (cell_id, lineno)# Stop on a gutter breakpoint, or — once a session is underway —# wherever pdb's step/next bookkeeping wants to (`stop_here`).- if lineno in self._debugger.breakpoints.get(cell_id, ()) or (- self._stepping and self._debugger.stop_here(frame)+ if self._debugger is not None and (+ lineno in self._debugger.breakpoints.get(cell_id, ())+ or (self._stepping and self._debugger.stop_here(frame))):self._enter_debugger(frame)return self._trace@@ -161,6 +170,7 @@ class FrameWatcher:`MarimoStopError` (the same path as `mo.stop()`) rather than lettingexecution run on."""+ assert self._debugger is not Nonedebugger = self._debuggerdebugger.disable_sigint()debugger.reset()@@ -208,17 +218,17 @@ class FrameWatcher:class DebuggerLifecycle:- """Install a frame watcher around a cell body for the live debugger.+ """Install a frame watcher around a cell body.`setup` installs the watcher (`sys.settrace` + heartbeat) before the bodyruns; `teardown` removes it. The lifecycle only toggles the watcher per- cell so debug mode can be turned on and off. Gated by the `debugger`- experimental flag (see `Runner.__init__`).+ cell so debug mode can be turned on and off. Gated by the `debugger` and+ `line_timing` experimental flags (see `Runner.__init__`)."""name = "debugger"- def __init__(self, debugger: MarimoPdb) -> None:+ def __init__(self, debugger: MarimoPdb | None) -> None:self._watcher = FrameWatcher(debugger)def setup(self, cell: CellImpl, glbls: MutableGlobals) -> Skip | None:diff --git a/marimo/_runtime/runner/cell_runner.py b/marimo/_runtime/runner/cell_runner.pyindex 472abbaac7..66c33daaf7 100644--- a/marimo/_runtime/runner/cell_runner.py+++ b/marimo/_runtime/runner/cell_runner.py@@ -176,17 +176,22 @@ class Runner:),))- # Live debugger: frame-watch each cell body when the experimental flag- # is on. Gated here so there is zero tracing overhead when disabled.+ # Live debugger and line-timing highlight share one frame-watching+ # lifecycle (a single `sys.settrace` hook). Gated here so there is+ # zero tracing overhead when disabled.experimental = (self.user_config.get("experimental", {})if self.user_config is not Noneelse {})- if self.debugger is not None and bool(+ debugger_on = self.debugger is not None and bool(experimental.get("debugger", False)- ):- lifecycles.append(DebuggerLifecycle(self.debugger))+ )+ line_timing_on = bool(experimental.get("line_timing", False))+ if debugger_on or line_timing_on:+ lifecycles.append(+ DebuggerLifecycle(self.debugger if debugger_on else None)+ )self._evaluator = Evaluator(executor=resolve_executor(), lifecycles=lifecycles)diff --git a/marimo/_smoke_tests/line_timing_test.py b/marimo/_smoke_tests/line_timing_test.pynew file mode 100644index 0000000000..0d4785aa52--- /dev/null+++ b/marimo/_smoke_tests/line_timing_test.py@@ -0,0 +1,79 @@+# /// script+# requires-python = ">=3.11"+# dependencies = []+#+# [tool.marimo.experimental]+# line_timing = true+# ///++import marimo++__generated_with = "0.23.13"+app = marimo.App()++with app.setup(hide_code=True):+ import time+ import marimo as mo++[email protected](hide_code=True)+def _():+ mo.md("""+ # ⏱️ Line timing test++ The experimental `line_timing` flag is set in this notebook's script+ metadata (top of the file), so it's on for this notebook only.++ **What to watch for**+ - While a cell runs, the currently executing line is highlighted+ **green**.+ - Once a line has been busy for ~500ms, a small dim **elapsed-time+ pill** appears at the end of the line and ticks until execution+ moves on.+ - Fast lines never show a timer — the highlight just steps through.+ - Everything clears when the cell finishes.+ """)+ return+++def _():+ # Staged pipeline: the highlight steps through; the timer appears+ # only on the slow steps.+ time.sleep(0.2) # fast: no timer+ time.sleep(0.8) # timer appears at ~500ms+ time.sleep(2) # counts to ~2s+ time.sleep(5) # counts to ~5s+ return+++def _():+ # Fast loop: the highlight bounces between lines, but no line stays+ # busy for 500ms, so the timer never flickers in.+ total = 0+ for i in range(100):+ total += i+ time.sleep(0.02)+ total+ return+++def _():+ time.sleep(8) # one long line: the timer ticks the whole way+ return++[email protected](hide_code=True)+def _():+ mo.md("""+ Tip: also set `debugger = true` in the script metadata to verify that+ the green timing highlight wins over the amber debugger highlight and+ that the breakpoint gutter still works.+ """)+ return+++if __name__ == "__main__":+ app.run()diff --git a/tests/_runtime/runner/test_cell_runner.py b/tests/_runtime/runner/test_cell_runner.pyindex ebb55af13f..9973b8a63c 100644--- a/tests/_runtime/runner/test_cell_runner.py+++ b/tests/_runtime/runner/test_cell_runner.py@@ -68,6 +68,54 @@ async def test_debugger_lifecycle_gated_by_flag(assert not has_debugger(lifecycles(with_flag(True), None))+async def test_line_timing_lifecycle_gated_by_flag(+ execution_kernel: Kernel, exec_req: ExecReqProvider+) -> None:+ from marimo._runtime.executor import DebuggerLifecycle++ k = execution_kernel+ await k.run([exec_req.get("1")])++ def lifecycles(user_config: Any, debugger: Any) -> list[Any]:+ runner = Runner(+ roots=set(k.graph.cells.keys()),+ graph=k.graph,+ glbls=k.globals,+ debugger=debugger,+ hooks=NotebookCellHooks(),+ user_config=user_config,+ )+ return [+ item+ for item in runner._evaluator.lifecycles+ if isinstance(item, DebuggerLifecycle)+ ]++ def with_flags(**flags: bool) -> Any:+ experimental = {**k.user_config.get("experimental", {}), **flags}+ return {**k.user_config, "experimental": experimental}++ # line_timing alone: one lifecycle, watching without a debugger — even+ # when a debugger instance is available.+ for debugger in (None, k.debugger):+ items = lifecycles(+ with_flags(debugger=False, line_timing=True), debugger+ )+ assert len(items) == 1+ assert items[0]._watcher._debugger is None++ # Both flags: exactly one lifecycle (a single settrace hook), holding the+ # debugger.+ items = lifecycles(with_flags(debugger=True, line_timing=True), k.debugger)+ assert len(items) == 1+ assert items[0]._watcher._debugger is k.debugger++ # Both off: absent.+ assert not lifecycles(+ with_flags(debugger=False, line_timing=False), k.debugger+ )++async def test_traceback_includes_lineno(execution_kernel: Kernel, exec_req: ExecReqProvider) -> None:diff --git a/tests/_runtime/test_executor_debugger.py b/tests/_runtime/test_executor_debugger.pyindex 38b90f3779..d998b004d1 100644--- a/tests/_runtime/test_executor_debugger.py+++ b/tests/_runtime/test_executor_debugger.py@@ -202,3 +202,101 @@ class TestFrameWatcher:assert ops[0].cell_id == "abc"assert ops[0].line == 5assert ops[1].line is None+++class TestFrameWatcherWithoutDebugger:+ """The watcher with `debugger=None` (the `line_timing` flag) only streams+ the active line; there is no pdb to enter."""++ @staticmethod+ def test_records_current_cell_line() -> None:+ from marimo._runtime.executor.lifecycles.debugger import FrameWatcher++ watcher = FrameWatcher(None)+ code = TestFrameWatcher._cell_code("abc", "a = 1\nb = 2\nc = 3\n")+ watcher.install()+ try:+ exec(code, {})+ current = watcher._current+ finally:+ watcher.uninstall()+ assert current == ("abc", 3)++ @staticmethod+ def test_install_uninstall_restores_previous_trace() -> None:+ import sys++ from marimo._runtime.executor.lifecycles.debugger import FrameWatcher++ prev = sys.gettrace()+ watcher = FrameWatcher(None)+ watcher.install()+ installed = sys.gettrace()+ assert getattr(installed, "__self__", None) is watcher+ watcher.uninstall()+ assert sys.gettrace() is prev++ @staticmethod+ def test_runs_to_completion_without_entering_pdb() -> None:+ from marimo._runtime.executor.lifecycles.debugger import FrameWatcher++ watcher = FrameWatcher(None)+ code = TestFrameWatcher._cell_code(+ "abc", "total = 0\nfor i in range(3):\n total += i\n"+ )+ glbls: dict[str, Any] = {}+ watcher.install()+ try:+ exec(code, glbls)+ finally:+ watcher.uninstall()+ assert glbls["total"] == 3++ @staticmethod+ def test_heartbeat_flushes_active_line() -> None:+ import threading+ import time++ from marimo._messaging.notification import ActiveLineNotification+ from marimo._runtime.executor.lifecycles.debugger import FrameWatcher++ watcher = FrameWatcher(None)+ stream = MockStream()+ watcher._stream = stream+ watcher._current = ("abc", 5) # type: ignore[assignment]+ watcher._stop.clear()+ thread = threading.Thread(target=watcher._heartbeat, daemon=True)+ thread.start()+ try:+ for _ in range(100):+ if stream.parsed_operations:+ break+ time.sleep(0.01)+ finally:+ watcher._stop.set()+ thread.join(timeout=1.0)++ ops = stream.parsed_operations+ assert ops, "heartbeat never flushed the active line"+ assert isinstance(ops[0], ActiveLineNotification)+ assert (ops[0].cell_id, ops[0].line) == ("abc", 5)+ assert watcher._flushed == ("abc", 5)++ @staticmethod+ def test_uninstall_broadcasts_line_clear() -> None:+ from marimo._runtime.executor.lifecycles.debugger import FrameWatcher++ watcher = FrameWatcher(None)+ code = TestFrameWatcher._cell_code("abc", "a = 1\n")+ watcher.install()+ # No runtime context in tests, so install() found no stream; give the+ # watcher one to observe the clear broadcast on uninstall.+ stream = MockStream()+ watcher._stream = stream+ try:+ exec(code, {})+ finally:+ watcher.uninstall()++ assert stream.parsed_operations+ assert stream.parsed_operations[-1].line is None