Skip to content

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

feat: debugger execution lifecycle (#9970)

Dylan Madisetti43e391674927
diff --git a/frontend/src/__mocks__/requests.ts b/frontend/src/__mocks__/requests.ts
index 87596fce8f..eb2bea69da 100644
--- a/frontend/src/__mocks__/requests.ts
+++ b/frontend/src/__mocks__/requests.ts
@@ -45,6 +45,7 @@ export const MockRequestClient = {
openFile: vi.fn().mockResolvedValue({}),
getUsageStats: vi.fn().mockResolvedValue({}),
sendPdb: vi.fn().mockResolvedValue({}),
+ sendSetBreakpoints: vi.fn().mockResolvedValue({}),
sendListFiles: vi.fn().mockResolvedValue({ files: [] }),
sendSearchFiles: vi
.fn()
diff --git a/frontend/src/components/app-config/user-config-form.tsx b/frontend/src/components/app-config/user-config-form.tsx
index 87d46ed344..4bbb887d27 100644
--- a/frontend/src/components/app-config/user-config-form.tsx
+++ b/frontend/src/components/app-config/user-config-form.tsx
@@ -1288,6 +1288,32 @@ export const UserConfigForm: React.FC = () => {
</div>
)}
/>
+ <OverriddenFormField
+ control={form.control}
+ name="experimental.debugger"
+ render={({ field, override }) => (
+ <div className="flex flex-col gap-y-1">
+ <FormItem className={formItemClasses}>
+ <FormLabel className="font-normal">Debugger</FormLabel>
+ <FormControl>
+ <Checkbox
+ data-testid="debugger-checkbox"
+ checked={override.value === true}
+ disabled={override.isOverridden}
+ onCheckedChange={field.onChange}
+ />
+ </FormControl>
+ </FormItem>
+ <IsOverridden override={override} />
+ <FormDescription>
+ Enable the live debugger: a clickable breakpoint gutter,
+ current-line highlighting while a cell runs, and dropping
+ into <Kbd className="inline">pdb</Kbd> at breakpoints. This
+ change requires a page refresh to take effect.
+ </FormDescription>
+ </div>
+ )}
+ />
</SettingGroup>
);
}
diff --git a/frontend/src/components/debugger/debugger-code.tsx b/frontend/src/components/debugger/debugger-code.tsx
index 1f335348c4..4a90864d3d 100644
--- a/frontend/src/components/debugger/debugger-code.tsx
+++ b/frontend/src/components/debugger/debugger-code.tsx
@@ -208,7 +208,7 @@ export const DebuggerControls: React.FC<{
</Button>
</Tooltip>
{onClear && (
- <Tooltip content="Clear">
+ <Tooltip content="Quit and clear">
<Button
variant="text"
size="icon"
@@ -217,7 +217,12 @@ export const DebuggerControls: React.FC<{
buttonClasses,
"text-(--red-11) hover:text-(--red-11) hover:bg-(--red-2) hover:border-(--red-8)",
)}
- onClick={onClear}
+ onClick={() => {
+ // Quit the debugger (`q`) before tearing down the console, so
+ // the stdin response targets the still-present pdb prompt.
+ onSubmit("q");
+ onClear();
+ }}
>
<TrashIcon fontSize={36} className={iconClasses} />
</Button>
diff --git a/frontend/src/components/editor/notebook-cell.tsx b/frontend/src/components/editor/notebook-cell.tsx
index f67850cb7a..4412abb2e9 100644
--- a/frontend/src/components/editor/notebook-cell.tsx
+++ b/frontend/src/components/editor/notebook-cell.tsx
@@ -29,6 +29,7 @@ import { outputIsLoading, outputIsStale } from "@/core/cells/cell";
import { isOutputEmpty } from "@/core/cells/outputs";
import { useIsPendingCut } from "@/core/cells/pending-cut-service";
import { autocompletionKeymap } from "@/core/codemirror/cm";
+import { clearCellBreakpoints } from "@/core/codemirror/cells/debugger-state";
import type { LanguageAdapterType } from "@/core/codemirror/language/types";
import { CSSClasses } from "@/core/constants";
import { canCollapseOutline } from "@/core/dom/outline";
@@ -746,6 +747,9 @@ const EditableCellComponent = ({
onRefactorWithAI={handleRefactorWithAI}
onClear={() => {
actions.clearCellConsoleOutput({ cellId });
+ // The debugger "Clear" (trashcan) also drops this cell's
+ // breakpoints; no-op when none are set.
+ clearCellBreakpoints(cellId);
}}
onSubmitDebugger={(text, index) => {
actions.setStdinResponse({
@@ -1211,6 +1215,9 @@ const SetupCellComponent = ({
onRefactorWithAI={handleRefactorWithAI}
onClear={() => {
actions.clearCellConsoleOutput({ cellId });
+ // The debugger "Clear" (trashcan) also drops this cell's
+ // breakpoints; no-op when none are set.
+ clearCellBreakpoints(cellId);
}}
onSubmitDebugger={(text, index) => {
actions.setStdinResponse({
diff --git a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
index c1ab03ca3c..a63e21cffe 100644
--- a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
+++ b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
@@ -24,8 +24,10 @@ import { Tooltip } from "@/components/ui/tooltip";
import { getCellEditorView } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
import { SCRATCH_CELL_ID } from "@/core/cells/ids";
+import { toggleBreakpoint } from "@/core/codemirror/cells/debugger-state";
import { insertDebuggerAtLine } from "@/core/codemirror/editing/debugging";
import { aiFeaturesEnabledAtom } from "@/core/config/config";
+import { getFeatureFlag } from "@/core/config/feature-flag";
import { getRequestClient } from "@/core/network/requests";
import { isStaticNotebook } from "@/core/static/static-state";
import { isWasm } from "@/core/wasm/utils";
@@ -212,7 +214,14 @@ function lastLine(text: string): string {
export const replaceTracebackFilenames = (domNode: DOMNode) => {
const info = getTracebackInfo(domNode);
if (info?.kind === "cell") {
- const tooltipContent = <InsertBreakpointContent />;
+ // With the live debugger enabled, toggle a real gutter breakpoint
+ // instead of mutating the user's code with a `breakpoint()` statement.
+ const debuggerEnabled = getFeatureFlag("debugger");
+ const tooltipContent = debuggerEnabled ? (
+ <ToggleBreakpointContent />
+ ) : (
+ <InsertBreakpointContent />
+ );
return (
<span className="nb">
<span className="inline-flex items-center">
@@ -228,6 +237,10 @@ export const replaceTracebackFilenames = (domNode: DOMNode) => {
>
<BugPlayIcon
onClick={() => {
+ if (debuggerEnabled && !isStaticNotebook()) {
+ toggleBreakpoint(info.cellId, info.lineNumber);
+ return;
+ }
const view = getCellEditorView(info.cellId);
if (view) {
insertDebuggerAtLine(view, info.lineNumber);
@@ -294,3 +307,7 @@ const InsertBreakpointContent = () => {
</>
);
};
+
+const ToggleBreakpointContent = () => {
+ return <>Toggle a breakpoint at this line</>;
+};
diff --git a/frontend/src/core/cells/__tests__/cell.test.ts b/frontend/src/core/cells/__tests__/cell.test.ts
index 70c3f2958c..cac5a868ed 100644
--- a/frontend/src/core/cells/__tests__/cell.test.ts
+++ b/frontend/src/core/cells/__tests__/cell.test.ts
@@ -218,3 +218,42 @@ describe("transitionCell serialization", () => {
);
});
});
+
+describe("transitionCell stdin resolution", () => {
+ function stdinOutput(): OutputMessage {
+ return {
+ channel: "stdin",
+ mimetype: "text/plain",
+ data: "(Pdb) ",
+ timestamp: Date.now() as Seconds,
+ } as OutputMessage;
+ }
+
+ it("resolves a dangling pdb prompt when the cell goes idle", () => {
+ // A paused-pdb cell shows an unanswered stdin prompt (the debugger box);
+ // once it finishes (e.g. after quitting with `q`), the box is removed.
+ const cell = createCellRuntimeState({
+ status: "running",
+ debuggerActive: true,
+ consoleOutputs: [stdinOutput()],
+ });
+ const next = transitionCell(cell, {
+ cell_id: "cell-1",
+ status: "idle",
+ } as CellMessage);
+ expect(next.debuggerActive).toBe(false);
+ expect(next.consoleOutputs[0].response).toBe("");
+ });
+
+ it("leaves an unanswered prompt interactive while still running", () => {
+ const cell = createCellRuntimeState({
+ status: "running",
+ consoleOutputs: [stdinOutput()],
+ });
+ const next = transitionCell(cell, {
+ cell_id: "cell-1",
+ status: null,
+ } as CellMessage);
+ expect(next.consoleOutputs[0].response).toBeUndefined();
+ });
+});
diff --git a/frontend/src/core/cells/cell.ts b/frontend/src/core/cells/cell.ts
index 083e0f3fe9..209f0305f8 100644
--- a/frontend/src/core/cells/cell.ts
+++ b/frontend/src/core/cells/cell.ts
@@ -118,9 +118,11 @@ export function transitionCell(
// Coalesce console outputs, which are streamed during execution.
let consoleOutputs = cell.consoleOutputs;
- // If interrupted on the incoming message,
- // remove the debugger and resolve all stdin for previous console outputs
- if (didInterruptFromThisMessage) {
+ // When the cell is interrupted or finishes (idle), there is no live
+ // stdin/pdb session, so resolve any dangling stdin prompt. This removes the
+ // debugger box — e.g. after quitting pdb with `q`, which stops the cell
+ // (idle) rather than interrupting it.
+ if (didInterruptFromThisMessage || message.status === "idle") {
nextCell.debuggerActive = false;
consoleOutputs = consoleOutputs.map((output) => {
if (output.channel === "stdin") {
diff --git a/frontend/src/core/codemirror/cells/debugger-decorations.ts b/frontend/src/core/codemirror/cells/debugger-decorations.ts
new file mode 100644
index 0000000000..5b58eb3cc8
--- /dev/null
+++ b/frontend/src/core/codemirror/cells/debugger-decorations.ts
@@ -0,0 +1,188 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import {
+ type EditorState,
+ type Extension,
+ RangeSet,
+ RangeSetBuilder,
+ StateEffect,
+ StateField,
+} from "@codemirror/state";
+import {
+ Decoration,
+ type DecorationSet,
+ EditorView,
+ gutter,
+ GutterMarker,
+ type PluginValue,
+ ViewPlugin,
+ type ViewUpdate,
+} from "@codemirror/view";
+import type { CellId } from "@/core/cells/ids";
+import type { Observable } from "@/core/state/observable";
+import { Logger } from "@/utils/Logger";
+import { toggleBreakpoint } from "./debugger-state";
+
+// --- Current-line highlight -------------------------------------------------
+
+function createLineDecoration(
+ state: EditorState,
+ line: number | null,
+): DecorationSet {
+ if (line == null || line < 1 || line > state.doc.lines) {
+ return Decoration.none;
+ }
+ const builder = new RangeSetBuilder<Decoration>();
+ try {
+ const doc = state.doc.line(line);
+ builder.add(
+ doc.from,
+ doc.from,
+ Decoration.line({ class: "cm-debugger-current-line" }),
+ );
+ } catch (error) {
+ Logger.debug("Invalid debugger line", { error });
+ }
+ return builder.finish();
+}
+
+class CurrentLineHighlighter implements PluginValue {
+ private unsubscribe: () => void;
+ decorations: DecorationSet;
+
+ constructor(view: EditorView, lineObservable: Observable<number | null>) {
+ this.decorations = createLineDecoration(view.state, lineObservable.get());
+ this.unsubscribe = lineObservable.sub((line) => {
+ this.decorations = createLineDecoration(view.state, line);
+ // Force a re-render; the decoration set changed out of band.
+ view.dispatch({ userEvent: "marimo.debugger-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. */
+export function debuggerLineHighlighter(
+ lineObservable: Observable<number | null>,
+): Extension {
+ return [
+ ViewPlugin.define(
+ (view) => new CurrentLineHighlighter(view, lineObservable),
+ { decorations: (plugin) => plugin.decorations },
+ ),
+ EditorView.theme({
+ ".cm-debugger-current-line": {
+ backgroundColor: "color-mix(in srgb, var(--amber-4) 50%, transparent)",
+ },
+ }),
+ ];
+}
+
+// --- Breakpoint gutter ------------------------------------------------------
+
+class BreakpointMarker extends GutterMarker {
+ override toDOM() {
+ const dot = document.createElement("div");
+ dot.className = "cm-breakpoint-marker";
+ return dot;
+ }
+}
+
+const breakpointMarker = new BreakpointMarker();
+
+const setBreakpointLines = StateEffect.define<ReadonlySet<number>>();
+
+const breakpointLinesField = StateField.define<ReadonlySet<number>>({
+ create: () => new Set<number>(),
+ update(value, tr) {
+ for (const effect of tr.effects) {
+ if (effect.is(setBreakpointLines)) {
+ return effect.value;
+ }
+ }
+ return value;
+ },
+});
+
+function buildBreakpointMarkers(state: EditorState): RangeSet<GutterMarker> {
+ const lines = state.field(breakpointLinesField);
+ if (lines.size === 0) {
+ return RangeSet.empty;
+ }
+ const builder = new RangeSetBuilder<GutterMarker>();
+ for (const lineNo of [...lines].toSorted((a, b) => a - b)) {
+ if (lineNo >= 1 && lineNo <= state.doc.lines) {
+ const line = state.doc.line(lineNo);
+ builder.add(line.from, line.from, breakpointMarker);
+ }
+ }
+ return builder.finish();
+}
+
+/** Keep `breakpointLinesField` in sync with the per-cell breakpoints atom. */
+class BreakpointSync implements PluginValue {
+ private unsubscribe: () => void;
+
+ constructor(view: EditorView, observable: Observable<ReadonlySet<number>>) {
+ const apply = (lines: ReadonlySet<number>) => {
+ view.dispatch({ effects: setBreakpointLines.of(lines) });
+ };
+ // Dispatching during view construction is disallowed; defer the initial
+ // sync (e.g. for editors that mount after breakpoints already exist).
+ // Read the value fresh inside the microtask so a `sub` update that lands
+ // first isn't clobbered by a stale snapshot.
+ if (observable.get().size > 0) {
+ queueMicrotask(() => apply(observable.get()));
+ }
+ this.unsubscribe = observable.sub(apply);
+ }
+
+ destroy() {
+ this.unsubscribe();
+ }
+}
+
+/** A clickable gutter for toggling breakpoints on a cell's lines. */
+export function breakpointGutter(
+ cellId: CellId,
+ breakpointsObservable: Observable<ReadonlySet<number>>,
+): Extension {
+ return [
+ breakpointLinesField,
+ ViewPlugin.define(
+ (view) => new BreakpointSync(view, breakpointsObservable),
+ ),
+ gutter({
+ class: "cm-breakpoint-gutter",
+ markers: (view) => buildBreakpointMarkers(view.state),
+ initialSpacer: () => breakpointMarker,
+ domEventHandlers: {
+ mousedown: (view, line) => {
+ const lineNo = view.state.doc.lineAt(line.from).number;
+ toggleBreakpoint(cellId, lineNo);
+ return true;
+ },
+ },
+ }),
+ EditorView.theme({
+ ".cm-breakpoint-gutter": {
+ width: "14px",
+ cursor: "pointer",
+ },
+ ".cm-breakpoint-marker": {
+ width: "8px",
+ height: "8px",
+ borderRadius: "50%",
+ backgroundColor: "var(--red-9)",
+ margin: "4px auto",
+ },
+ }),
+ ];
+}
diff --git a/frontend/src/core/codemirror/cells/debugger-state.ts b/frontend/src/core/codemirror/cells/debugger-state.ts
new file mode 100644
index 0000000000..9609c3b989
--- /dev/null
+++ b/frontend/src/core/codemirror/cells/debugger-state.ts
@@ -0,0 +1,92 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { atom } from "jotai";
+import type { CellId } from "@/core/cells/ids";
+import { getRequestClient } from "@/core/network/requests";
+import { store } from "@/core/state/jotai";
+import { Logger } from "@/utils/Logger";
+
+/**
+ * State for the experimental live debugger.
+ *
+ * - `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.
+ * - `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 {
+ cellId: CellId;
+ line: number;
+}
+
+export const debuggerCurrentLineAtom = atom<DebuggerLine | null>(null);
+
+export const breakpointsAtom = atom<ReadonlyMap<CellId, ReadonlySet<number>>>(
+ new Map<CellId, ReadonlySet<number>>(),
+);
+
+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);
+ return current?.cellId === cellId ? current.line : null;
+ });
+}
+
+/** Per-cell derived atom: the breakpoint lines for `cellId`. */
+export function createCellBreakpointsAtom(cellId: CellId) {
+ return atom((get) => get(breakpointsAtom).get(cellId) ?? EMPTY_LINES);
+}
+
+function sendBreakpoints(map: ReadonlyMap<CellId, ReadonlySet<number>>): void {
+ const breakpoints: Record<string, number[]> = {};
+ for (const [cellId, lines] of map) {
+ if (lines.size > 0) {
+ breakpoints[cellId] = [...lines].toSorted((a, b) => a - b);
+ }
+ }
+ // Fire-and-forget: the request layer rethrows on failure (e.g. static or
+ // wasm mode with no live kernel). Swallow it so toggling a breakpoint never
+ // surfaces as an unhandled promise rejection.
+ getRequestClient()
+ .sendSetBreakpoints({ breakpoints })
+ .catch((error) => {
+ Logger.debug("Failed to sync breakpoints to kernel", { error });
+ });
+}
+
+/** Remove all breakpoints for a cell and sync the full set to the kernel. */
+export function clearCellBreakpoints(cellId: CellId): void {
+ const prev = store.get(breakpointsAtom);
+ if (!prev.has(cellId)) {
+ return;
+ }
+ const next = new Map(prev);
+ next.delete(cellId);
+ store.set(breakpointsAtom, next);
+ sendBreakpoints(next);
+}
+
+/** Toggle a breakpoint at `(cellId, line)` and sync the full set to the kernel. */
+export function toggleBreakpoint(cellId: CellId, line: number): void {
+ const prev = store.get(breakpointsAtom);
+ const next = new Map(prev);
+ const lines = new Set(next.get(cellId) ?? []);
+ if (lines.has(line)) {
+ lines.delete(line);
+ } else {
+ lines.add(line);
+ }
+ if (lines.size > 0) {
+ next.set(cellId, lines);
+ } else {
+ next.delete(cellId);
+ }
+ store.set(breakpointsAtom, next);
+ sendBreakpoints(next);
+}
diff --git a/frontend/src/core/codemirror/cells/extensions.ts b/frontend/src/core/codemirror/cells/extensions.ts
index c1b3acc662..2b8b878840 100644
--- a/frontend/src/core/codemirror/cells/extensions.ts
+++ b/frontend/src/core/codemirror/cells/extensions.ts
@@ -17,6 +17,7 @@ import {
import { loroSyncAnnotation } from "@/core/codemirror/rtc/loro/sync";
import type { KeymapConfig } from "@/core/config/config-schema";
import type { HotkeyProvider } from "@/core/hotkeys/hotkeys";
+import { getFeatureFlag } from "@/core/config/feature-flag";
import { duplicateWithCtrlModifier } from "@/core/hotkeys/shortcuts";
import { store } from "@/core/state/jotai";
import { createObservable } from "@/core/state/observable";
@@ -25,6 +26,14 @@ import { formattingChangeEffect } from "../format";
import { goToDefinitionAtCursorPosition } from "../go-to-definition/utils";
import { getEditorCodeAsPython } from "../language/utils";
import { isAtEndOfEditor, isAtStartOfEditor } from "../utils";
+import {
+ breakpointGutter,
+ debuggerLineHighlighter,
+} from "./debugger-decorations";
+import {
+ createCellBreakpointsAtom,
+ createDebuggerLineAtom,
+} from "./debugger-state";
import {
type CodemirrorCellActions,
cellActionsState,
@@ -428,6 +437,19 @@ 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),
+ ),
+ ]
+ : [],
];
}
diff --git a/frontend/src/core/config/feature-flag.tsx b/frontend/src/core/config/feature-flag.tsx
index 8715a16c1b..29cee5a82c 100644
--- a/frontend/src/core/config/feature-flag.tsx
+++ b/frontend/src/core/config/feature-flag.tsx
@@ -11,6 +11,7 @@ export interface ExperimentalFeatures {
rtc_v2: boolean;
cache_panel: boolean;
external_agents: boolean;
+ debugger: boolean; // Live frame-watching debugger (gutter breakpoints + pdb)
// Add new feature flags here
}
@@ -20,6 +21,7 @@ const defaultValues: ExperimentalFeatures = {
rtc_v2: false,
cache_panel: false,
external_agents: import.meta.env.DEV,
+ debugger: false,
};
export function getFeatureFlag<T extends keyof ExperimentalFeatures>(
diff --git a/frontend/src/core/islands/bootstrap.ts b/frontend/src/core/islands/bootstrap.ts
index 255434141b..339cf0af02 100644
--- a/frontend/src/core/islands/bootstrap.ts
+++ b/frontend/src/core/islands/bootstrap.ts
@@ -174,6 +174,7 @@ function handleMessage(
case "completion-result":
case "reload":
case "focus-cell":
+ case "active-line":
case "variables":
case "variable-values":
case "data-column-preview":
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index 215d4b950e..e3ed684d3f 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -244,6 +244,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
sendListFiles = throwNotImplemented;
sendSearchFiles = throwNotImplemented;
sendPdb = throwNotImplemented;
+ sendSetBreakpoints = throwNotImplemented;
sendCreateFileOrFolder = throwNotImplemented;
sendDeleteFileOrFolder = throwNotImplemented;
sendCopyFileOrFolder = throwNotImplemented;
diff --git a/frontend/src/core/network/requests-lazy.ts b/frontend/src/core/network/requests-lazy.ts
index 9840cb86ff..fe49af0311 100644
--- a/frontend/src/core/network/requests-lazy.ts
+++ b/frontend/src/core/network/requests-lazy.ts
@@ -108,6 +108,7 @@ const ACTIONS: Record<keyof AllRequests, Action> = {
sendStdin: "waitForConnectionOpen",
sendInterrupt: "waitForConnectionOpen",
sendPdb: "waitForConnectionOpen",
+ sendSetBreakpoints: "waitForConnectionOpen",
sendInstallMissingPackages: "waitForConnectionOpen",
readSnippets: "waitForConnectionOpen",
previewDatasetColumn: "waitForConnectionOpen",
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index 6a394a54a7..e0e9b72ba0 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -293,6 +293,14 @@ export function createNetworkRequests(): EditRequests & RunRequests {
})
.then(handleResponseReturnNull);
},
+ sendSetBreakpoints: (request) => {
+ return getClient()
+ .POST("/api/kernel/pdb/breakpoints", {
+ body: request,
+ params: getParams(),
+ })
+ .then(handleResponseReturnNull);
+ },
sendListFiles: async (request) => {
await waitForConnectionOpen();
return getClient()
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index 1b7aaba017..494c283cd1 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -68,6 +68,7 @@ export function createStaticRequests(): EditRequests & RunRequests {
sendListFiles: throwNotInEditMode,
sendSearchFiles: throwNotInEditMode,
sendPdb: throwNotInEditMode,
+ sendSetBreakpoints: throwNotInEditMode,
sendCreateFileOrFolder: throwNotInEditMode,
sendDeleteFileOrFolder: throwNotInEditMode,
sendCopyFileOrFolder: throwNotInEditMode,
diff --git a/frontend/src/core/network/requests-toasting.tsx b/frontend/src/core/network/requests-toasting.tsx
index 12d07564f6..d84bab9056 100644
--- a/frontend/src/core/network/requests-toasting.tsx
+++ b/frontend/src/core/network/requests-toasting.tsx
@@ -49,6 +49,7 @@ export function createErrorToastingRequests(
sendListFiles: "Failed to list files",
sendSearchFiles: "Failed to search files",
sendPdb: "Failed to start debug session",
+ sendSetBreakpoints: "", // No toast
sendCreateFileOrFolder: "Failed to create file or folder",
sendDeleteFileOrFolder: "Failed to delete file or folder",
sendCopyFileOrFolder: "Failed to duplicate file or folder",
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index c1ade525fb..6b8e39c315 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -66,6 +66,7 @@ export type ListDataSourceConnectionRequest =
schemas["ListDataSourceConnectionRequest"];
export type ValidateSQLRequest = schemas["ValidateSQLRequest"];
export type DebugCellRequest = schemas["DebugCellRequest"];
+export type SetBreakpointsRequest = schemas["SetBreakpointsRequest"];
export type ReadCodeResponse = schemas["ReadCodeResponse"];
export type RecentFilesResponse = schemas["RecentFilesResponse"];
export type RenameNotebookRequest = schemas["RenameNotebookRequest"];
@@ -172,6 +173,7 @@ export interface EditRequests {
getUsageStats: () => Promise<UsageResponse>;
// Debugger
sendPdb: (request: DebugCellRequest) => Promise<null>;
+ sendSetBreakpoints: (request: SetBreakpointsRequest) => Promise<null>;
// File explorer requests
sendListFiles: (request: FileListRequest) => Promise<FileListResponse>;
sendSearchFiles: (request: FileSearchRequest) => Promise<FileSearchResponse>;
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index aa76d3b9e9..8ef174b4ed 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -257,6 +257,10 @@ export class PyodideBridge implements RunRequests, EditRequests {
throwNotImplemented();
};
+ sendSetBreakpoints: EditRequests["sendSetBreakpoints"] = async () => {
+ throwNotImplemented();
+ };
+
sendRun: EditRequests["sendRun"] = async (request) => {
await this.rpc.proxy.request.loadPackages(request.codes.join("\n"));
diff --git a/frontend/src/core/websocket/useMarimoKernelConnection.tsx b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
index dcb13f9320..ab62272406 100644
--- a/frontend/src/core/websocket/useMarimoKernelConnection.tsx
+++ b/frontend/src/core/websocket/useMarimoKernelConnection.tsx
@@ -32,6 +32,7 @@ import { cacheInfoAtom } from "../cache/requests";
import { SCRATCH_CELL_ID } from "../cells/ids";
import { useRunsActions } from "../cells/runs";
import { focusAndScrollCellOutputIntoView } from "../cells/scrollCellIntoView";
+import { debuggerCurrentLineAtom } from "../codemirror/cells/debugger-state";
import type { CellData } from "../cells/types";
import { capabilitiesAtom } from "../config/capabilities";
import { useSetAppConfig } from "../config/config";
@@ -196,6 +197,7 @@ export function useMarimoKernelConnection(opts: {
const runtimeManager = useRuntimeManager();
const setCacheInfo = useSetAtom(cacheInfoAtom);
const setKernelStartupError = useSetAtom(kernelStartupErrorAtom);
+ const setDebuggerCurrentLine = useSetAtom(debuggerCurrentLineAtom);
const {
setNamespaces: setStorageNamespaces,
filterFromVariables: filterStorageFromVariables,
@@ -392,6 +394,13 @@ export function useMarimoKernelConnection(opts: {
case "focus-cell":
focusAndScrollCellOutputIntoView(msg.data.cell_id);
return;
+ case "active-line":
+ setDebuggerCurrentLine(
+ msg.data.line == null
+ ? null
+ : { cellId: msg.data.cell_id, line: msg.data.line },
+ );
+ return;
case "notebook-document-transaction":
handleDocumentTransaction(msg.data.transaction);
return;
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index 94db98b5f6..fb577193d5 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -328,6 +328,7 @@ def _generate_server_api_schema() -> dict[str, Any]:
notifications.QueryParamsDeleteNotification,
notifications.QueryParamsClearNotification,
notifications.FocusCellNotification,
+ notifications.ActiveLineNotification,
notifications.ConsumerCapabilitiesNotification,
notifications.NotificationMessage,
# ai
@@ -441,6 +442,7 @@ def _generate_server_api_schema() -> dict[str, Any]:
models.MCPStatusResponse,
models.PreviewDatasetColumnRequest,
models.PreviewSQLTableRequest,
+ models.SetBreakpointsRequest,
models.StorageListEntriesRequest,
models.StorageDownloadRequest,
models.ReadCodeResponse,
diff --git a/marimo/_config/config.py b/marimo/_config/config.py
index 2e8cdcfee7..3696b9cb79 100644
--- a/marimo/_config/config.py
+++ b/marimo/_config/config.py
@@ -600,6 +600,7 @@ class ExperimentalConfig(TypedDict, total=False):
wasm_layouts: bool # Used in playground (community cloud)
rtc_v2: bool
isolate_apps: bool
+ debugger: bool # Live frame-watching debugger (gutter breakpoints + pdb)
# Internal features
cache: CacheConfig
diff --git a/marimo/_ipc/connection.py b/marimo/_ipc/connection.py
index 4ece955ddd..e44a239286 100644
--- a/marimo/_ipc/connection.py
+++ b/marimo/_ipc/connection.py
@@ -16,8 +16,8 @@ from marimo._ipc.types import ConnectionInfo
from marimo._messaging.types import KernelMessage
from marimo._runtime.commands import (
BatchableCommand,
- CodeCompletionCommand,
CommandMessage,
+ OutOfBandCommand,
)
from marimo._session.queue import QueueType
@@ -117,7 +117,7 @@ class Connection:
control: Channel[CommandMessage]
ui_element: Channel[BatchableCommand]
- completion: Channel[CodeCompletionCommand]
+ completion: Channel[OutOfBandCommand]
win32_interrupt: Channel[bool] | None
input: Channel[str]
@@ -196,7 +196,7 @@ class Connection:
context=context,
control=Channel.Pull(context, msg_type=CommandMessage),
ui_element=Channel.Pull(context, msg_type=BatchableCommand),
- completion=Channel.Pull(context, msg_type=CodeCompletionCommand),
+ completion=Channel.Pull(context, msg_type=OutOfBandCommand),
win32_interrupt=Channel.Pull(context, msg_type=bool)
if connection_info.win32_interrupt
else None,
diff --git a/marimo/_ipc/queue_manager.py b/marimo/_ipc/queue_manager.py
index 2c109e43e2..6d11a610bc 100644
--- a/marimo/_ipc/queue_manager.py
+++ b/marimo/_ipc/queue_manager.py
@@ -13,8 +13,8 @@ if typing.TYPE_CHECKING:
from marimo._messaging.types import KernelMessage
from marimo._runtime.commands import (
BatchableCommand,
- CodeCompletionCommand,
CommandMessage,
+ OutOfBandCommand,
)
from marimo._session.queue import QueueType
@@ -48,8 +48,8 @@ class QueueManager:
return self.conn.ui_element.queue
@property
- def completion_queue(self) -> QueueType[CodeCompletionCommand]:
- """Queue for code completion requests."""
+ def completion_queue(self) -> QueueType[OutOfBandCommand]:
+ """Queue for off-main-loop commands (completions + breakpoints)."""
return self.conn.completion.queue
@property
diff --git a/marimo/_messaging/notification.py b/marimo/_messaging/notification.py
index 5af6757643..2b5f578d66 100644
--- a/marimo/_messaging/notification.py
+++ b/marimo/_messaging/notification.py
@@ -827,6 +827,23 @@ class FocusCellNotification(Notification, tag="focus-cell"):
cell_id: CellId_t
+class ActiveLineNotification(Notification, tag="active-line"):
+ """Reports the line a cell's frame watcher is currently executing.
+
+ Emitted on a timed heartbeat while a cell runs (only when the line
+ changed), so the editor can highlight the live line. A `None` line
+ clears the highlight (e.g. when the cell finishes).
+
+ Attributes:
+ cell_id: Cell whose frame is being watched.
+ line: 1-based line within the cell, or `None` to clear.
+ """
+
+ name: ClassVar[str] = "active-line"
+ cell_id: CellId_t
+ line: int | None = None
+
+
class SecretKeysResultNotification(Notification, tag="secret-keys-result"):
"""Available secret keys from secret providers.
@@ -932,6 +949,8 @@ NotificationMessage = (
| CacheInfoNotification
# Kiosk
| FocusCellNotification
+ # Debugger
+ | ActiveLineNotification
# Document
| NotebookDocumentTransactionNotification
# Consumer
diff --git a/marimo/_pyodide/pyodide_session.py b/marimo/_pyodide/pyodide_session.py
index 135fbb5687..336a079c21 100644
--- a/marimo/_pyodide/pyodide_session.py
+++ b/marimo/_pyodide/pyodide_session.py
@@ -28,8 +28,8 @@ from marimo._runtime import commands, handlers, patches
from marimo._runtime.commands import (
AppMetadata,
BatchableCommand,
- CodeCompletionCommand,
CommandMessage,
+ OutOfBandCommand,
UpdateUserConfigCommand,
)
from marimo._runtime.marimo_pdb import MarimoPdb
@@ -91,8 +91,9 @@ class AsyncQueueManager:
# set UI elements duplicated in another queue so they can be batched
self.set_ui_element_queue = asyncio.Queue[BatchableCommand]()
- # Code completion requests are sent through a separate queue
- self.completion_queue = asyncio.Queue[commands.CodeCompletionCommand]()
+ # Off-main-loop commands (completions + breakpoints) go through a
+ # separate queue.
+ self.completion_queue = asyncio.Queue[commands.OutOfBandCommand]()
# Input messages for the user's Python code are sent through the
# input queue
@@ -425,7 +426,7 @@ def _dispose_pyodide_lifecycle_items(ctx: RuntimeContext) -> None:
def _launch_pyodide_kernel(
control_queue: asyncio.Queue[CommandMessage],
set_ui_element_queue: asyncio.Queue[BatchableCommand],
- completion_queue: asyncio.Queue[CodeCompletionCommand],
+ completion_queue: asyncio.Queue[OutOfBandCommand],
input_queue: asyncio.Queue[str],
on_message: Callable[[KernelMessage], None],
session_mode: SessionMode,
@@ -441,8 +442,8 @@ def _launch_pyodide_kernel(
from marimo._runtime.kernel_lifecycle import (
KernelArgs,
asyncio_queue_reader,
+ collapse_out_of_band,
create_kernel,
- drain_stale,
listen_messages,
teardown_kernel,
)
@@ -483,12 +484,11 @@ def _launch_pyodide_kernel(
if is_edit_mode:
signal.signal(signal.SIGINT, handlers.construct_interrupt_handler())
- async def listen_completion() -> None:
+ async def listen_out_of_band() -> None:
while True:
- request = drain_stale(
- completion_queue, latest=await completion_queue.get()
- )
- kernel.code_completion(request, docstrings_limit=5)
+ first = await completion_queue.get()
+ for command in collapse_out_of_band(completion_queue, first=first):
+ kernel.dispatch_out_of_band(command, docstrings_limit=5)
async def listen() -> None:
try:
@@ -499,7 +499,7 @@ def _launch_pyodide_kernel(
set_ui_element_queue,
asyncio_queue_reader,
),
- listen_completion(),
+ listen_out_of_band(),
)
finally:
try:
diff --git a/marimo/_runtime/commands.py b/marimo/_runtime/commands.py
index a162954202..1656ad49c8 100644
--- a/marimo/_runtime/commands.py
+++ b/marimo/_runtime/commands.py
@@ -221,6 +221,27 @@ class DebugCellCommand(Command):
return f"DebugCellCommand(cell={self.cell_id})"
+class SetBreakpointsCommand(Command):
+ """Set the live debugger's breakpoints (session-scoped, not persisted).
+
+ Replaces the full breakpoint set: the frontend always sends the complete
+ map of cell id -> 1-based line numbers. Only meaningful when the
+ `debugger` experimental feature is enabled.
+
+ Attributes:
+ breakpoints: Map of cell id to lines that have a breakpoint.
+ request: HTTP request context if available.
+ """
+
+ breakpoints: dict[CellId_t, list[int]]
+ # incoming request, e.g. from Starlette or FastAPI
+ request: HTTPRequest | None = None
+
+ def __repr__(self) -> str:
+ count = sum(len(lines) for lines in self.breakpoints.values())
+ return f"SetBreakpointsCommand(count={count})"
+
+
class ExecuteCellCommand(Command):
"""Execute a single cell.
@@ -915,6 +936,7 @@ CommandMessage = (
| ExecuteScratchpadCommand
| ExecuteStaleCellsCommand
| DebugCellCommand
+ | SetBreakpointsCommand
| DeleteCellCommand
| SyncGraphCommand
| UpdateCellConfigCommand
@@ -950,3 +972,14 @@ CommandMessage = (
All commands that can be sent to the kernel.
"""
+
+
+OutOfBandCommand = CodeCompletionCommand | SetBreakpointsCommand
+"""Commands processed off the main control loop.
+
+Unlike the rest of `CommandMessage` (which the kernel handles serially, and so
+cannot be delivered while a cell is executing), these are drained by a
+background worker and applied immediately. A command belongs here when it is
+fire-and-forget, cheap to apply, and useful mid-execution. Add a member to this
+union and a branch to `Kernel.dispatch_out_of_band` to introduce a new one.
+"""
diff --git a/marimo/_runtime/executor/__init__.py b/marimo/_runtime/executor/__init__.py
index 37e85877ea..f9fe89a453 100644
--- a/marimo/_runtime/executor/__init__.py
+++ b/marimo/_runtime/executor/__init__.py
@@ -21,10 +21,12 @@ from marimo._runtime.executor.lifecycles import (
ExecutionLifecycle,
Skip,
)
+from marimo._runtime.executor.lifecycles.debugger import DebuggerLifecycle
from marimo._runtime.executor.lifecycles.strict import StrictLifecycle
__all__ = [
"_EXECUTOR_REGISTRY",
+ "DebuggerLifecycle",
"DefaultExecutor",
"Evaluator",
"ExecutionLifecycle",
diff --git a/marimo/_runtime/executor/lifecycles/debugger.py b/marimo/_runtime/executor/lifecycles/debugger.py
new file mode 100644
index 0000000000..bf8ba54bf7
--- /dev/null
+++ b/marimo/_runtime/executor/lifecycles/debugger.py
@@ -0,0 +1,236 @@
+# Copyright 2026 Marimo. All rights reserved.
+"""DebuggerLifecycle frame-watches each cell body for the live debugger."""
+
+from __future__ import annotations
+
+import sys
+import threading
+from typing import TYPE_CHECKING, Any
+
+from marimo._ast.compiler import cell_id_from_filename
+
+if TYPE_CHECKING:
+ from types import FrameType
+
+ from marimo._ast.cell import CellImpl
+ from marimo._messaging.types import Stream
+ from marimo._runtime.executor.lifecycles import Skip
+ from marimo._runtime.marimo_pdb import MarimoPdb
+ from marimo._runtime.runner.result import RunResult
+ from marimo._types.globals import MutableGlobals
+ from marimo._types.ids import CellId_t
+
+
+class FrameWatcher:
+ """Frame watcher for the experimental live debugger.
+
+ Installed around a single cell's execution (via `DebuggerLifecycle`):
+ `install()` registers a `sys.settrace` hook on the executing thread and
+ starts a heartbeat thread; `uninstall()` removes both. While installed it
+ traces only cell frames (identified by the cell id encoded in their
+ `co_filename`, see `cell_id_from_filename`) and:
+
+ - records the current `(cell_id, line)` on every traced line (cheap), which
+ the heartbeat flushes to the frontend as an `ActiveLineNotification`
+ only when it changes — never once per line; and
+ - drops into `MarimoPdb` when a line with a registered breakpoint is hit,
+ handing tracing off to pdb for the rest of the cell.
+
+ `settrace` is per-thread, so only the cell-executing thread is traced. The
+ heartbeat runs on its own thread (it must emit even while a synchronous
+ cell blocks the kernel thread) using a stream copied for cross-thread use.
+ """
+
+ # Lines are flushed to the frontend at most this often.
+ HEARTBEAT_INTERVAL_S = 0.075
+ # Don't block teardown indefinitely waiting on the heartbeat thread.
+ _JOIN_TIMEOUT_S = 1.0
+
+ def __init__(self, debugger: MarimoPdb) -> None:
+ self._debugger = debugger
+ self._installed = False
+ self._prev_trace: Any = None
+ self._stream: Stream | None = None
+ # Most recent (cell_id, line) seen by the trace function, and the last
+ # value flushed to the frontend.
+ self._current: tuple[CellId_t, int] | None = None
+ self._flushed: tuple[CellId_t, int] | None = None
+ self._stop = threading.Event()
+ self._thread: threading.Thread | None = None
+ # Cache co_filename -> cell_id to avoid re-parsing on every line.
+ self._cell_id_cache: dict[str, CellId_t | None] = {}
+ # True once a debug session has started; gates consulting pdb's
+ # `stop_here` so `next`/`step` work (we don't step before the first
+ # breakpoint, when bdb would stop everywhere).
+ self._stepping = False
+
+ def install(self) -> None:
+ if self._installed:
+ return
+ from marimo._runtime.context import get_context
+ from marimo._runtime.context.types import ContextNotInitializedError
+
+ try:
+ stream = get_context().stream
+ self._stream = stream.copy_for_thread()
+ except (ContextNotInitializedError, RuntimeError):
+ # No context (shouldn't happen during a cell run) or a stream that
+ # can't be used off-thread; fall back to no line streaming.
+ self._stream = None
+
+ # 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()
+
+ self._installed = True
+ self._current = None
+ self._flushed = None
+ self._stepping = False
+ self._stop.clear()
+ self._prev_trace = sys.gettrace()
+ if self._stream is not None:
+ self._thread = threading.Thread(
+ target=self._heartbeat,
+ name="marimo-frame-watcher",
+ daemon=True,
+ )
+ self._thread.start()
+ sys.settrace(self._trace)
+
+ def uninstall(self) -> None:
+ if not self._installed:
+ return
+ self._installed = False
+ sys.settrace(self._prev_trace)
+ self._prev_trace = None
+ self._stop.set()
+ if self._thread is not None:
+ self._thread.join(timeout=self._JOIN_TIMEOUT_S)
+ self._thread = None
+ # Clear the current-line highlight on the frontend.
+ if self._current is not None:
+ self._broadcast(self._current[0], None)
+ self._current = None
+ self._flushed = None
+
+ def _cell_id_for(self, filename: str) -> CellId_t | None:
+ if filename not in self._cell_id_cache:
+ self._cell_id_cache[filename] = cell_id_from_filename(filename)
+ return self._cell_id_cache[filename]
+
+ def _trace(self, frame: FrameType, event: str, arg: Any) -> Any:
+ del arg
+ if event == "call":
+ # Only descend into cell frames; everything else (marimo
+ # internals, libraries) is skipped with no per-line overhead.
+ return (
+ self._trace
+ if self._cell_id_for(frame.f_code.co_filename) is not None
+ else None
+ )
+ if event == "line":
+ cell_id = self._cell_id_for(frame.f_code.co_filename)
+ if cell_id is None:
+ return self._trace
+ lineno = frame.f_lineno
+ 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)
+ ):
+ self._enter_debugger(frame)
+ return self._trace
+
+ def _enter_debugger(self, frame: FrameType) -> None:
+ """Run the pdb prompt at `frame`, keeping our watcher in control.
+
+ We drive `interaction()` directly rather than `set_trace()` so that
+ pdb never takes ownership of `sys.settrace`. `continue`/`next`/`step`
+ call `sys.settrace(None)` (no pdb breaks are registered), so we re-arm
+ our trace afterward — that is what lets a breakpoint inside a loop
+ fire again on the next iteration.
+
+ `botframe` is pinned to this frame so bdb's `set_continue` produces a
+ `stop_here` that is `False` (plain resume), while `step`/`next` leave a
+ `stop_here` that fires at the right upcoming line — which our `_trace`
+ consults to implement stepping.
+
+ If the user quits (`q`), we stop the cell cleanly with a
+ `MarimoStopError` (the same path as `mo.stop()`) rather than letting
+ execution run on.
+ """
+ debugger = self._debugger
+ debugger.disable_sigint()
+ debugger.reset()
+ debugger.botframe = frame
+ try:
+ debugger.interaction(frame, None)
+ finally:
+ sys.settrace(self._trace)
+ # `set_continue` clears `f_trace` on every live frame up to the
+ # (unset) bottom frame, which would silence our watcher for the
+ # rest of the current frames. Re-arm the cell frames on the stack
+ # so line events keep firing (e.g. the next loop iteration).
+ f: FrameType | None = frame
+ while f is not None:
+ if self._cell_id_for(f.f_code.co_filename) is not None:
+ f.f_trace = self._trace
+ f = f.f_back
+
+ if getattr(debugger, "quitting", False):
+ from marimo._runtime.control_flow import MarimoStopError
+
+ raise MarimoStopError(None)
+ # The session is live: consult `stop_here` on subsequent lines so a
+ # `step`/`next` lands, while a `continue` simply runs to the next
+ # breakpoint (its `stop_here` is `False`).
+ self._stepping = True
+
+ def _heartbeat(self) -> None:
+ while not self._stop.wait(self.HEARTBEAT_INTERVAL_S):
+ current = self._current
+ if current is not None and current != self._flushed:
+ self._flushed = current
+ self._broadcast(current[0], current[1])
+
+ def _broadcast(self, cell_id: CellId_t, line: int | None) -> None:
+ if self._stream is None:
+ return
+ from marimo._messaging.notification import ActiveLineNotification
+ from marimo._messaging.notification_utils import broadcast_notification
+
+ broadcast_notification(
+ ActiveLineNotification(cell_id=cell_id, line=line),
+ stream=self._stream,
+ )
+
+
+class DebuggerLifecycle:
+ """Install a frame watcher around a cell body for the live debugger.
+
+ `setup` installs the watcher (`sys.settrace` + heartbeat) before the body
+ runs; `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__`).
+ """
+
+ name = "debugger"
+
+ def __init__(self, debugger: MarimoPdb) -> None:
+ self._watcher = FrameWatcher(debugger)
+
+ def setup(self, cell: CellImpl, glbls: MutableGlobals) -> Skip | None:
+ del cell, glbls
+ self._watcher.install()
+ return None
+
+ def teardown(
+ self,
+ cell: CellImpl,
+ glbls: MutableGlobals,
+ run_result: RunResult,
+ ) -> None:
+ del cell, glbls, run_result
+ self._watcher.uninstall()
diff --git a/marimo/_runtime/kernel_lifecycle.py b/marimo/_runtime/kernel_lifecycle.py
index 9adf98399e..d452678dc8 100644
--- a/marimo/_runtime/kernel_lifecycle.py
+++ b/marimo/_runtime/kernel_lifecycle.py
@@ -17,6 +17,7 @@ from marimo import _loggers
from marimo._runtime import patches
from marimo._runtime.commands import (
ModelCommand,
+ OutOfBandCommand,
StopKernelCommand,
UpdateUIElementCommand,
)
@@ -99,6 +100,31 @@ def drain_stale(queue: Any, *, latest: _T) -> _T:
return latest
+def collapse_out_of_band(
+ queue: Any, *, first: OutOfBandCommand
+) -> list[OutOfBandCommand]:
+ """Drain queued out-of-band commands, keeping the latest of each type.
+
+ `first` is the already-dequeued command that unblocked the worker; the
+ rest of the queue is drained non-blockingly. Out-of-band commands are
+ idempotent "latest wins" updates, so older commands of the same type are
+ stale and dropped. Returns one command per type, in first-seen order.
+
+ Works for both `multiprocessing`/`queue.Queue` and `asyncio.Queue` (both
+ expose a synchronous `get_nowait`); `empty()` is avoided because
+ `multiprocessing.Queue.empty()` can lie.
+ """
+ latest: dict[type, OutOfBandCommand] = {}
+ item: OutOfBandCommand | None = first
+ while item is not None:
+ latest[type(item)] = item
+ try:
+ item = queue.get_nowait()
+ except (asyncio.QueueEmpty, _queue.Empty):
+ item = None
+ return list(latest.values())
+
+
def _build_hooks(
is_edit_mode: bool, user_config: MarimoConfig
) -> NotebookCellHooks:
diff --git a/marimo/_runtime/marimo_pdb.py b/marimo/_runtime/marimo_pdb.py
index 7832130090..66db3b593a 100644
--- a/marimo/_runtime/marimo_pdb.py
+++ b/marimo/_runtime/marimo_pdb.py
@@ -77,6 +77,19 @@ class MarimoPdb(Pdb):
self._last_tracebacks: dict[CellId_t, TracebackType] = {}
self._last_traceback: TracebackType | None = None
+ # Live breakpoints, keyed by cell id -> set of 1-based line numbers.
+ # Session-scoped (not persisted to the notebook file); updated by the
+ # `SetBreakpointsCommand` handler and read by the frame watcher.
+ self.breakpoints: dict[CellId_t, set[int]] = {}
+
+ def disable_sigint(self) -> None:
+ """Stop pdb from installing its own SIGINT handler.
+
+ marimo owns interrupt handling; with pdb's handler installed an
+ interrupt becomes a debugger break instead of interrupting the cell.
+ """
+ self.nosigint = True
+
def set_trace(
self, frame: FrameType | None = None, header: str | None = None
) -> None:
diff --git a/marimo/_runtime/runner/cell_runner.py b/marimo/_runtime/runner/cell_runner.py
index b735d4c1f9..472abbaac7 100644
--- a/marimo/_runtime/runner/cell_runner.py
+++ b/marimo/_runtime/runner/cell_runner.py
@@ -29,6 +29,7 @@ from marimo._runtime.exceptions import (
unwrap_user_exception,
)
from marimo._runtime.executor import (
+ DebuggerLifecycle,
Evaluator,
ExecutionLifecycle,
StrictLifecycle,
@@ -175,6 +176,17 @@ 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.
+ experimental = (
+ self.user_config.get("experimental", {})
+ if self.user_config is not None
+ else {}
+ )
+ if self.debugger is not None and bool(
+ experimental.get("debugger", False)
+ ):
+ lifecycles.append(DebuggerLifecycle(self.debugger))
self._evaluator = Evaluator(
executor=resolve_executor(), lifecycles=lifecycles
)
diff --git a/marimo/_runtime/runtime.py b/marimo/_runtime/runtime.py
index 3eb3659e18..c5a9535223 100644
--- a/marimo/_runtime/runtime.py
+++ b/marimo/_runtime/runtime.py
@@ -108,6 +108,8 @@ from marimo._runtime.commands import (
ExecuteCellCommand,
ExecuteStaleCellsCommand,
InvokeFunctionCommand,
+ OutOfBandCommand,
+ SetBreakpointsCommand,
UpdateCellConfigCommand,
UpdateUIElementCommand,
UpdateUserConfigCommand,
@@ -516,7 +518,7 @@ class Kernel:
self._globals_lock = threading.RLock()
self._state_lock = threading.RLock()
- self._completion_worker_started = False
+ self._out_of_band_worker_started = False
self.debugger = debugger_override
if self.debugger is not None:
@@ -673,30 +675,77 @@ class Kernel:
@contextlib.contextmanager
def lock_globals(self) -> Iterator[None]:
- # The only other thread accessing globals is the completion worker. If
- # we haven't started a completion worker, there's no need to lock
- # globals.
- if self._completion_worker_started:
+ # The only other thread accessing globals is the out-of-band worker.
+ # If we haven't started one, there's no need to lock globals.
+ if self._out_of_band_worker_started:
with self._globals_lock:
yield
else:
yield
- def start_completion_worker(
- self, completion_queue: QueueType[CodeCompletionCommand]
+ def start_out_of_band_worker(
+ self, out_of_band_queue: QueueType[OutOfBandCommand]
) -> None:
- """Must be called after context is initialized"""
- from marimo._runtime.kernel_lifecycle import drain_stale
+ """Start the background worker for out-of-band commands.
+
+ Drains the queue on its own thread so these commands apply even while
+ a cell is executing (the control queue is blocked behind the running
+ cell). Must be called after the context is initialized.
+ """
+ from marimo._runtime.kernel_lifecycle import collapse_out_of_band
def _worker() -> None:
while True:
- request = drain_stale(
- completion_queue, latest=completion_queue.get()
+ # Block for the next command, then drain and dispatch whatever
+ # else is queued in one pass (latest of each type wins).
+ commands = collapse_out_of_band(
+ out_of_band_queue, first=out_of_band_queue.get()
+ )
+ # Breakpoint updates are latency-sensitive; apply them before
+ # the (potentially slow, docstring-resolving) completion
+ # command queued in the same drain pass.
+ commands.sort(
+ key=lambda c: (
+ 0 if isinstance(c, SetBreakpointsCommand) else 1
+ )
)
- self.code_completion(request, docstrings_limit=80)
+ for command in commands:
+ self.dispatch_out_of_band(command, docstrings_limit=80)
threading.Thread(target=_worker, daemon=True).start()
- self._completion_worker_started = True
+ self._out_of_band_worker_started = True
+
+ def dispatch_out_of_band(
+ self, command: OutOfBandCommand, *, docstrings_limit: int
+ ) -> None:
+ """Apply a single out-of-band command.
+
+ The one place that maps an `OutOfBandCommand` to its handler; extend
+ with a new branch when adding a member to the union.
+ """
+ from marimo._utils.assert_never import assert_never
+
+ if isinstance(command, SetBreakpointsCommand):
+ self.set_breakpoints(command)
+ elif isinstance(command, CodeCompletionCommand):
+ self.code_completion(command, docstrings_limit=docstrings_limit)
+ else:
+ # Exhaustiveness guard: a new OutOfBandCommand member without a
+ # branch here would otherwise be silently dropped by the worker.
+ assert_never(command)
+
+ def set_breakpoints(self, request: SetBreakpointsCommand) -> None:
+ """Update the live debugger's breakpoints (session-scoped).
+
+ Replaces the full set; read by the frame watcher (`DebuggerLifecycle`).
+ """
+ if self.debugger is None:
+ return
+ self.debugger.breakpoints = {
+ cell_id: set(lines)
+ for cell_id, lines in request.breakpoints.items()
+ if lines
+ }
@kernel_tracer.start_as_current_span("code_completion")
def code_completion(
@@ -2512,7 +2561,7 @@ def _install_subprocess_handlers(
def launch_kernel(
control_queue: QueueType[CommandMessage],
set_ui_element_queue: QueueType[BatchableCommand],
- completion_queue: QueueType[CodeCompletionCommand],
+ completion_queue: QueueType[OutOfBandCommand],
input_queue: QueueType[str],
stream_queue: QueueType[KernelMessage] | None,
socket_addr: tuple[str, int] | None,
@@ -2570,8 +2619,8 @@ def launch_kernel(
)
) as (kernel, ctx):
if is_edit_mode:
- # completions only provided in edit mode
- kernel.start_completion_worker(completion_queue)
+ # out-of-band commands are only processed in edit mode
+ kernel.start_out_of_band_worker(completion_queue)
if is_subprocess:
# Read theme from kernel.user_config — create_kernel may have
diff --git a/marimo/_server/api/endpoints/execution.py b/marimo/_server/api/endpoints/execution.py
index bbe86ee117..0fb3591db4 100644
--- a/marimo/_server/api/endpoints/execution.py
+++ b/marimo/_server/api/endpoints/execution.py
@@ -34,6 +34,7 @@ from marimo._server.models.models import (
InvokeFunctionRequest,
KernelStatusResponse,
ModelRequest,
+ SetBreakpointsRequest,
SuccessResponse,
UpdateUIElementValuesRequest,
)
@@ -453,6 +454,35 @@ async def run_post_mortem(
return await dispatch_control_request(request, DebugCellRequest)
[email protected]("/pdb/breakpoints")
+@requires("edit")
+async def set_breakpoints(
+ *,
+ request: Request,
+) -> BaseResponse:
+ """
+ parameters:
+ - in: header
+ name: Marimo-Session-Id
+ schema:
+ type: string
+ required: true
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/SetBreakpointsRequest"
+ responses:
+ 200:
+ description: Set the live debugger's breakpoints for the session.
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/SuccessResponse"
+ """
+ return await dispatch_control_request(request, SetBreakpointsRequest)
+
+
@router.post("/restart_session")
@requires("edit")
async def restart_session(
diff --git a/marimo/_server/models/models.py b/marimo/_server/models/models.py
index c69fe45557..19d55f536b 100644
--- a/marimo/_server/models/models.py
+++ b/marimo/_server/models/models.py
@@ -25,6 +25,7 @@ from marimo._runtime.commands import (
ModelCommand,
PreviewDatasetColumnCommand,
PreviewSQLTableCommand,
+ SetBreakpointsCommand,
StorageDownloadCommand,
StorageListEntriesCommand,
UpdateCellConfigCommand,
@@ -55,6 +56,13 @@ class DebugCellRequest(DebugCellCommand, tag=False):
return DebugCellCommand(cell_id=self.cell_id, request=self.request)
+class SetBreakpointsRequest(SetBreakpointsCommand, tag=False):
+ def as_command(self) -> SetBreakpointsCommand:
+ return SetBreakpointsCommand(
+ breakpoints=self.breakpoints, request=self.request
+ )
+
+
class ExecuteScratchpadRequest(ExecuteScratchpadCommand, tag=False):
def as_command(self) -> ExecuteScratchpadCommand:
return ExecuteScratchpadCommand(code=self.code, request=self.request)
diff --git a/marimo/_session/managers/app_host.py b/marimo/_session/managers/app_host.py
index 78e85d9f4e..8adf71c150 100644
--- a/marimo/_session/managers/app_host.py
+++ b/marimo/_session/managers/app_host.py
@@ -90,7 +90,7 @@ class AppHostQueueManager(QueueManagerProto):
self.set_ui_element_queue: QueueType[commands.BatchableCommand] = (
_AppHostPushQueue(app_host, session_id, Channel.UI_ELEMENT)
)
- self.completion_queue: QueueType[commands.CodeCompletionCommand] = (
+ self.completion_queue: QueueType[commands.OutOfBandCommand] = (
_AppHostPushQueue(app_host, session_id, Channel.COMPLETION)
)
self.input_queue: QueueType[str] = _AppHostPushQueue(
diff --git a/marimo/_session/managers/ipc.py b/marimo/_session/managers/ipc.py
index e58a0859b4..358809107a 100644
--- a/marimo/_session/managers/ipc.py
+++ b/marimo/_session/managers/ipc.py
@@ -88,7 +88,7 @@ class IPCQueueManagerImpl(QueueManager):
@property
def completion_queue( # type: ignore[override]
self,
- ) -> QueueType[commands.CodeCompletionCommand]:
+ ) -> QueueType[commands.OutOfBandCommand]:
return self._ipc.completion_queue
@property
diff --git a/marimo/_session/managers/queue.py b/marimo/_session/managers/queue.py
index 8b5a306c3e..6e683242a4 100644
--- a/marimo/_session/managers/queue.py
+++ b/marimo/_session/managers/queue.py
@@ -35,10 +35,11 @@ class QueueManagerImpl(QueueManager):
| queue.Queue[commands.BatchableCommand]
) = context.Queue() if context is not None else queue.Queue()
- # Code completion requests are sent through a separate queue
+ # Off-main-loop commands (completions + breakpoints) go through a
+ # separate queue so they apply even while a cell is executing.
self.completion_queue: (
- MPQueue[commands.CodeCompletionCommand]
- | queue.Queue[commands.CodeCompletionCommand]
+ MPQueue[commands.OutOfBandCommand]
+ | queue.Queue[commands.OutOfBandCommand]
) = context.Queue() if context is not None else queue.Queue()
self.win32_interrupt_queue: MPQueue[bool] | queue.Queue[bool] | None
diff --git a/marimo/_session/queue.py b/marimo/_session/queue.py
index b41f954703..e5b7c380de 100644
--- a/marimo/_session/queue.py
+++ b/marimo/_session/queue.py
@@ -1,7 +1,7 @@
# Copyright 2026 Marimo. All rights reserved.
from __future__ import annotations
-from typing import TYPE_CHECKING, Protocol, TypeVar
+from typing import TYPE_CHECKING, Protocol, TypeVar, get_args
if TYPE_CHECKING:
from marimo._runtime import commands
@@ -34,18 +34,19 @@ class QueueType(Protocol[T]):
def route_control_request(
request: commands.CommandMessage,
control_queue: QueueType[commands.CommandMessage],
- completion_queue: QueueType[commands.CodeCompletionCommand],
+ completion_queue: QueueType[commands.OutOfBandCommand],
ui_element_queue: QueueType[commands.BatchableCommand],
) -> None:
"""Route a control request to the appropriate queue(s).
- - CodeCompletionCommand → completion_queue only
+ - OutOfBandCommand members → completion_queue only (drained off the main
+ loop so they apply even while a cell is executing)
- UpdateUIElementCommand / ModelCommand → control_queue + ui_element_queue
- Everything else → control_queue only
"""
from marimo._runtime import commands
- if isinstance(request, commands.CodeCompletionCommand):
+ if isinstance(request, get_args(commands.OutOfBandCommand)):
completion_queue.put(request)
return
diff --git a/marimo/_session/types.py b/marimo/_session/types.py
index 583da58dba..aefb8199e1 100644
--- a/marimo/_session/types.py
+++ b/marimo/_session/types.py
@@ -42,7 +42,7 @@ class QueueManager(Protocol):
control_queue: QueueType[commands.CommandMessage]
set_ui_element_queue: QueueType[commands.BatchableCommand]
- completion_queue: QueueType[commands.CodeCompletionCommand]
+ completion_queue: QueueType[commands.OutOfBandCommand]
input_queue: QueueType[str]
stream_queue: QueueType[KernelMessage | None] | None
win32_interrupt_queue: QueueType[bool] | None
diff --git a/marimo/_smoke_tests/debugger_test.py b/marimo/_smoke_tests/debugger_test.py
new file mode 100644
index 0000000000..a0134e638b
--- /dev/null
+++ b/marimo/_smoke_tests/debugger_test.py
@@ -0,0 +1,95 @@
+# /// script
+# requires-python = ">=3.11"
+# dependencies = []
+#
+# [tool.marimo.experimental]
+# debugger = true
+# ///
+
+import marimo
+
+__generated_with = "0.23.13"
+app = marimo.App()
+
+with app.setup(hide_code=True):
+ # Setup cell: runs first, frame-watched like any other cell.
+ import time
+ import marimo as mo
+
+ HEARTBEAT_DEMO_ITERS = 40
+
+
[email protected](hide_code=True)
+def _():
+ mo.md("""
+ # 🐛 Debugger lifecycle test
+
+ The experimental `debugger` flag is set in this notebook's script
+ metadata (top of the file), so it's on for this notebook only.
+
+ **What to try**
+ - Click in the **leftmost gutter** of any cell to toggle a red
+ breakpoint dot. Run the cell → it drops into `pdb` at that line.
+ - Run the **slow loop** cell below and watch the **amber current-line
+ highlight** move on the heartbeat (it updates on change, ~every
+ 75ms, not every line).
+ - In a cell that raises, the traceback's **bug icon** now toggles a
+ gutter breakpoint instead of inserting `breakpoint()`.
+ """)
+ return
+
+
+def _(fib):
+ # Slow loop: run this and watch the current-line highlight track progress.
+ total = 0
+ for i in range(HEARTBEAT_DEMO_ITERS):
+ total += i
+ time.sleep(0.1) # set a gutter breakpoint here to pause mid-loop
+ time.sleep(0.1) # set a gutter breakpoint here to pause mid-loop
+ fib(i)
+ total
+ return
+
+
+def _():
+ # Step-into target: set a breakpoint inside `fib` and call it.
+ # @mo.cache
+ def fib(n):
+ if n < 2:
+ return n
+ a, b = 0, 1
+ for _ in range(n - 1):
+ a, b = b, a + b # good breakpoint line
+ return b
+
+
+ fib(20)
+ return (fib,)
+
+
+def _():
+ with mo.cache("hi"):
+ print(7)
+ time.sleep(1)
+ breakpoint()
+ return
+
+
+def _():
+ # Cell that raises — use the traceback bug icon to drop a breakpoint,
+ # then re-run to inspect.
+ def boom(x):
+ y = x * 2
+ return y / 0 # ZeroDivisionError
+
+
+ boom(21)
+ return
+
+
+if __name__ == "__main__":
+ app.run()
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 7e264d8830..f4af702f2b 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -1,5 +1,28 @@
components:
schemas:
+ ActiveLineNotification:
+ description: "Reports the line a cell's frame watcher is currently executing.\n\
+ \n Emitted on a timed heartbeat while a cell runs (only when the line\n\
+ \ changed), so the editor can highlight the live line. A `None` line\n\
+ \ clears the highlight (e.g. when the cell finishes).\n\n Attributes:\n\
+ \ cell_id: Cell whose frame is being watched.\n line: 1-based\
+ \ line within the cell, or `None` to clear."
+ properties:
+ cell_id:
+ $ref: '#/components/schemas/CellId'
+ line:
+ anyOf:
+ - type: integer
+ - type: 'null'
+ default: null
+ op:
+ enum:
+ - active-line
+ required:
+ - op
+ - cell_id
+ title: ActiveLineNotification
+ type: object
AddPackageRequest:
description: 'This can be a remove package or a local package.
@@ -2636,6 +2659,7 @@ components:
- $ref: '#/components/schemas/ExecuteScratchpadCommand'
- $ref: '#/components/schemas/ExecuteStaleCellsCommand'
- $ref: '#/components/schemas/DebugCellCommand'
+ - $ref: '#/components/schemas/SetBreakpointsCommand'
- $ref: '#/components/schemas/DeleteCellCommand'
- $ref: '#/components/schemas/SyncGraphCommand'
- $ref: '#/components/schemas/UpdateCellConfigCommand'
@@ -2679,6 +2703,7 @@ components:
preview-sql-table: '#/components/schemas/PreviewSQLTableCommand'
refresh-secrets: '#/components/schemas/RefreshSecretsCommand'
rename-notebook: '#/components/schemas/RenameNotebookCommand'
+ set-breakpoints: '#/components/schemas/SetBreakpointsCommand'
stop-kernel: '#/components/schemas/StopKernelCommand'
storage-download: '#/components/schemas/StorageDownloadCommand'
storage-list-entries: '#/components/schemas/StorageListEntriesCommand'
@@ -2768,10 +2793,12 @@ components:
- $ref: '#/components/schemas/CacheClearedNotification'
- $ref: '#/components/schemas/CacheInfoNotification'
- $ref: '#/components/schemas/FocusCellNotification'
+ - $ref: '#/components/schemas/ActiveLineNotification'
- $ref: '#/components/schemas/NotebookDocumentTransactionNotification'
- $ref: '#/components/schemas/ConsumerCapabilitiesNotification'
discriminator:
mapping:
+ active-line: '#/components/schemas/ActiveLineNotification'
alert: '#/components/schemas/AlertNotification'
banner: '#/components/schemas/BannerNotification'
cache-cleared: '#/components/schemas/CacheClearedNotification'
@@ -4671,6 +4698,50 @@ components:
SessionId:
format: session-id
type: string
+ SetBreakpointsCommand:
+ description: "Set the live debugger's breakpoints (session-scoped, not persisted).\n\
+ \n Replaces the full breakpoint set: the frontend always sends the complete\n\
+ \ map of cell id -> 1-based line numbers. Only meaningful when the\n \
+ \ `debugger` experimental feature is enabled.\n\n Attributes:\n \
+ \ breakpoints: Map of cell id to lines that have a breakpoint.\n request:\
+ \ HTTP request context if available."
+ properties:
+ breakpoints:
+ additionalProperties:
+ items:
+ type: integer
+ type: array
+ type: object
+ request:
+ anyOf:
+ - $ref: '#/components/schemas/HTTPRequest'
+ - type: 'null'
+ default: null
+ type:
+ enum:
+ - set-breakpoints
+ required:
+ - type
+ - breakpoints
+ title: SetBreakpointsCommand
+ type: object
+ SetBreakpointsRequest:
+ properties:
+ breakpoints:
+ additionalProperties:
+ items:
+ type: integer
+ type: array
+ type: object
+ request:
+ anyOf:
+ - $ref: '#/components/schemas/HTTPRequest'
+ - type: 'null'
+ default: null
+ required:
+ - breakpoints
+ title: SetBreakpointsRequest
+ type: object
SetCode:
description: Replace a cell's source code.
properties:
@@ -6667,6 +6738,26 @@ paths:
schema:
$ref: '#/components/schemas/SuccessResponse'
description: Interrupt the kernel's execution
+ /api/kernel/pdb/breakpoints:
+ post:
+ parameters:
+ - in: header
+ name: Marimo-Session-Id
+ required: true
+ schema:
+ type: string
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SetBreakpointsRequest'
+ responses:
+ 200:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SuccessResponse'
+ description: Set the live debugger's breakpoints for the session.
/api/kernel/pdb/pm:
post:
parameters:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index 5176641a4d..b8b0006a7c 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -1989,6 +1989,47 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/kernel/pdb/breakpoints": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ post: {
+ parameters: {
+ query?: never;
+ header: {
+ "Marimo-Session-Id": string;
+ };
+ path?: never;
+ cookie?: never;
+ };
+ requestBody?: {
+ content: {
+ "application/json": components["schemas"]["SetBreakpointsRequest"];
+ };
+ };
+ responses: {
+ /** @description Set the live debugger's breakpoints for the session. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["SuccessResponse"];
+ };
+ };
+ };
+ };
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/kernel/pdb/pm": {
parameters: {
query?: never;
@@ -3375,6 +3416,25 @@ export interface paths {
export type webhooks = Record<string, any>;
export interface components {
schemas: {
+ /**
+ * ActiveLineNotification
+ * @description Reports the line a cell's frame watcher is currently executing.
+ *
+ * Emitted on a timed heartbeat while a cell runs (only when the line
+ * changed), so the editor can highlight the live line. A `None` line
+ * clears the highlight (e.g. when the cell finishes).
+ *
+ * Attributes:
+ * cell_id: Cell whose frame is being watched.
+ * line: 1-based line within the cell, or `None` to clear.
+ */
+ ActiveLineNotification: {
+ cell_id: components["schemas"]["CellId"];
+ /** @default null */
+ line?: number | null;
+ /** @enum {unknown} */
+ op: "active-line";
+ };
/**
* AddPackageRequest
* @description This can be a remove package or a local package.
@@ -5017,6 +5077,7 @@ export interface components {
| components["schemas"]["ExecuteScratchpadCommand"]
| components["schemas"]["ExecuteStaleCellsCommand"]
| components["schemas"]["DebugCellCommand"]
+ | components["schemas"]["SetBreakpointsCommand"]
| components["schemas"]["DeleteCellCommand"]
| components["schemas"]["SyncGraphCommand"]
| components["schemas"]["UpdateCellConfigCommand"]
@@ -5100,6 +5161,7 @@ export interface components {
| components["schemas"]["CacheClearedNotification"]
| components["schemas"]["CacheInfoNotification"]
| components["schemas"]["FocusCellNotification"]
+ | components["schemas"]["ActiveLineNotification"]
| components["schemas"]["NotebookDocumentTransactionNotification"]
| components["schemas"]["ConsumerCapabilitiesNotification"];
};
@@ -6253,6 +6315,35 @@ export interface components {
};
/** Format: session-id */
SessionId: TypedString<"SessionId">;
+ /**
+ * SetBreakpointsCommand
+ * @description Set the live debugger's breakpoints (session-scoped, not persisted).
+ *
+ * Replaces the full breakpoint set: the frontend always sends the complete
+ * map of cell id -> 1-based line numbers. Only meaningful when the
+ * `debugger` experimental feature is enabled.
+ *
+ * Attributes:
+ * breakpoints: Map of cell id to lines that have a breakpoint.
+ * request: HTTP request context if available.
+ */
+ SetBreakpointsCommand: {
+ breakpoints: {
+ [key: string]: number[];
+ };
+ /** @default null */
+ request?: components["schemas"]["HTTPRequest"] | null;
+ /** @enum {unknown} */
+ type: "set-breakpoints";
+ };
+ /** SetBreakpointsRequest */
+ SetBreakpointsRequest: {
+ breakpoints: {
+ [key: string]: number[];
+ };
+ /** @default null */
+ request?: components["schemas"]["HTTPRequest"] | null;
+ };
/**
* SetCode
* @description Replace a cell's source code.
diff --git a/tests/_runtime/runner/test_cell_runner.py b/tests/_runtime/runner/test_cell_runner.py
index b96449f9f8..ebb55af13f 100644
--- a/tests/_runtime/runner/test_cell_runner.py
+++ b/tests/_runtime/runner/test_cell_runner.py
@@ -33,6 +33,41 @@ async def test_cell_output(
assert k.debugger._last_traceback is None
+async def test_debugger_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 runner._evaluator.lifecycles
+
+ def with_flag(value: bool) -> Any:
+ experimental = {**k.user_config.get("experimental", {})}
+ experimental["debugger"] = value
+ return {**k.user_config, "experimental": experimental}
+
+ def has_debugger(items: list[Any]) -> bool:
+ return any(isinstance(item, DebuggerLifecycle) for item in items)
+
+ # On when the flag is set and a debugger is present.
+ assert has_debugger(lifecycles(with_flag(True), k.debugger))
+ # Off when the flag is unset.
+ assert not has_debugger(lifecycles(with_flag(False), k.debugger))
+ # Off when there is no debugger, even with the flag on.
+ assert not has_debugger(lifecycles(with_flag(True), None))
+
+
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.py
new file mode 100644
index 0000000000..38b90f3779
--- /dev/null
+++ b/tests/_runtime/test_executor_debugger.py
@@ -0,0 +1,204 @@
+# Copyright 2026 Marimo. All rights reserved.
+from __future__ import annotations
+
+from typing import Any
+
+import pytest
+
+from tests._messaging.mocks import MockStream
+
+
+class _FakeDebugger:
+ """Minimal stand-in for `MarimoPdb` used by the frame watcher tests.
+
+ Records `interaction()` calls (by line) instead of entering a real pdb
+ session.
+ """
+
+ def __init__(
+ self,
+ *,
+ quit_on_interaction: bool = False,
+ step: bool = False,
+ ) -> None:
+ self.breakpoints: dict[Any, set[int]] = {}
+ self.interaction_lines: list[int] = []
+ self.nosigint = False
+ self.quitting = False
+ self.botframe: Any = None
+ self._quit_on_interaction = quit_on_interaction
+ # `step=True` mimics a `step`/`next` command: pdb wants to stop at
+ # every upcoming line (`stop_here` truthy). Default mimics `continue`.
+ self._step = step
+
+ def disable_sigint(self) -> None:
+ self.nosigint = True
+
+ def reset(self) -> None:
+ self.quitting = False
+
+ def stop_here(self, frame: Any) -> bool:
+ del frame
+ return self._step
+
+ def interaction(self, frame: Any, traceback: Any) -> None:
+ del traceback
+ self.interaction_lines.append(frame.f_lineno)
+ # Mimic pdb's `quit` command setting the bdb quitting flag.
+ if self._quit_on_interaction:
+ self.quitting = True
+
+
+class TestFrameWatcher:
+ @staticmethod
+ def _cell_code(cell_id: str, code: str) -> Any:
+ from marimo._ast.compiler import get_filename
+
+ return compile(code, get_filename(cell_id), "exec")
+
+ @staticmethod
+ def test_records_current_cell_line() -> None:
+ from marimo._runtime.executor.lifecycles.debugger import FrameWatcher
+
+ watcher = FrameWatcher(_FakeDebugger()) # type: ignore[arg-type]
+ 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_ignores_non_cell_frames() -> None:
+ from marimo._runtime.executor.lifecycles.debugger import FrameWatcher
+
+ watcher = FrameWatcher(_FakeDebugger()) # type: ignore[arg-type]
+ # A plain (non-cell) filename must never be traced.
+ code = compile("a = 1\nb = 2\n", "<plain>", "exec")
+ watcher.install()
+ try:
+ exec(code, {})
+ current = watcher._current
+ finally:
+ watcher.uninstall()
+ assert current is None
+
+ @staticmethod
+ def test_breakpoint_drops_into_pdb() -> None:
+ from marimo._runtime.executor.lifecycles.debugger import FrameWatcher
+
+ debugger = _FakeDebugger()
+ debugger.breakpoints = {"abc": {2}}
+ watcher = FrameWatcher(debugger) # type: ignore[arg-type]
+ code = TestFrameWatcher._cell_code("abc", "a = 1\nb = 2\nc = 3\n")
+ watcher.install()
+ try:
+ exec(code, {})
+ finally:
+ watcher.uninstall()
+ # The pdb prompt opens once, at the breakpoint line, and not for
+ # other lines.
+ assert debugger.interaction_lines == [2]
+
+ @staticmethod
+ def test_breakpoint_in_loop_rehits_each_iteration() -> None:
+ from marimo._runtime.executor.lifecycles.debugger import FrameWatcher
+
+ debugger = _FakeDebugger()
+ # Line 2 (the loop body) has a breakpoint; it should fire on every
+ # iteration even though `interaction` (continue) returns each time.
+ debugger.breakpoints = {"abc": {2}}
+ watcher = FrameWatcher(debugger) # type: ignore[arg-type]
+ code = TestFrameWatcher._cell_code(
+ "abc", "for i in range(3):\n x = i\n"
+ )
+ watcher.install()
+ try:
+ exec(code, {})
+ finally:
+ watcher.uninstall()
+ assert debugger.interaction_lines == [2, 2, 2]
+
+ @staticmethod
+ def test_step_stops_at_each_following_line() -> None:
+ from marimo._runtime.executor.lifecycles.debugger import FrameWatcher
+
+ # Breakpoint at line 1; stepping then stops at every subsequent line
+ # (the watcher consults pdb's `stop_here` once a session is underway).
+ debugger = _FakeDebugger(step=True)
+ debugger.breakpoints = {"abc": {1}}
+ watcher = FrameWatcher(debugger) # type: ignore[arg-type]
+ code = TestFrameWatcher._cell_code("abc", "a = 1\nb = 2\nc = 3\n")
+ watcher.install()
+ try:
+ exec(code, {})
+ finally:
+ watcher.uninstall()
+ assert debugger.interaction_lines == [1, 2, 3]
+
+ @staticmethod
+ def test_quit_stops_the_cell() -> None:
+ from marimo._runtime.control_flow import MarimoStopError
+ from marimo._runtime.executor.lifecycles.debugger import FrameWatcher
+
+ debugger = _FakeDebugger(quit_on_interaction=True)
+ debugger.breakpoints = {"abc": {2}}
+ watcher = FrameWatcher(debugger) # type: ignore[arg-type]
+ code = TestFrameWatcher._cell_code("abc", "a = 1\nb = 2\nc = 3\n")
+ watcher.install()
+ try:
+ # Quitting at the breakpoint raises MarimoStopError out of the
+ # cell body (the clean-stop path), so line 3 never runs.
+ with pytest.raises(MarimoStopError):
+ exec(code, {})
+ finally:
+ watcher.uninstall()
+ assert debugger.interaction_lines == [2]
+
+ @staticmethod
+ def test_disables_pdb_sigint_hijack() -> None:
+ from marimo._runtime.executor.lifecycles.debugger import FrameWatcher
+
+ debugger = _FakeDebugger()
+ watcher = FrameWatcher(debugger) # type: ignore[arg-type]
+ watcher.install()
+ try:
+ # marimo owns SIGINT, so pdb must not install its own handler.
+ assert debugger.nosigint is True
+ finally:
+ watcher.uninstall()
+
+ @staticmethod
+ def test_uninstall_restores_previous_trace() -> None:
+ import sys
+
+ from marimo._runtime.executor.lifecycles.debugger import FrameWatcher
+
+ prev = sys.gettrace()
+ watcher = FrameWatcher(_FakeDebugger()) # type: ignore[arg-type]
+ watcher.install()
+ # `_trace` is a bound method (new wrapper each access), so compare the
+ # underlying instance rather than identity.
+ installed = sys.gettrace()
+ assert getattr(installed, "__self__", None) is watcher
+ watcher.uninstall()
+ assert sys.gettrace() is prev
+
+ @staticmethod
+ def test_broadcast_emits_active_line_notification() -> None:
+ from marimo._messaging.notification import ActiveLineNotification
+ from marimo._runtime.executor.lifecycles.debugger import FrameWatcher
+
+ watcher = FrameWatcher(_FakeDebugger()) # type: ignore[arg-type]
+ watcher._stream = MockStream()
+ watcher._broadcast("abc", 5) # type: ignore[arg-type]
+ watcher._broadcast("abc", None) # type: ignore[arg-type]
+
+ ops = watcher._stream.parsed_operations
+ assert len(ops) == 2
+ assert isinstance(ops[0], ActiveLineNotification)
+ assert ops[0].cell_id == "abc"
+ assert ops[0].line == 5
+ assert ops[1].line is None
diff --git a/tests/_runtime/test_kernel_lifecycle.py b/tests/_runtime/test_kernel_lifecycle.py
index 228ce68843..1c11233a6a 100644
--- a/tests/_runtime/test_kernel_lifecycle.py
+++ b/tests/_runtime/test_kernel_lifecycle.py
@@ -9,13 +9,16 @@ from unittest.mock import AsyncMock, MagicMock
import pytest
from marimo._runtime.commands import (
+ CodeCompletionCommand,
ExecuteCellsCommand,
ModelCommand,
+ SetBreakpointsCommand,
StopKernelCommand,
UpdateUIElementCommand,
)
from marimo._runtime.kernel_lifecycle import (
asyncio_queue_reader,
+ collapse_out_of_band,
drain_stale,
listen_messages,
make_control_enqueuer,
@@ -188,6 +191,45 @@ def test_drain_stale_returns_newest_pending(queue_factory: Any) -> None:
assert q.empty()
+ "queue_factory",
+ [asyncio.Queue, _queue.Queue],
+ ids=["asyncio", "threading"],
+)
+def test_collapse_out_of_band_returns_first_when_empty(
+ queue_factory: Any,
+) -> None:
+ q = queue_factory()
+ first = CodeCompletionCommand(id="r1", document="x.", cell_id="c1")
+ assert collapse_out_of_band(q, first=first) == [first]
+
+
+ "queue_factory",
+ [asyncio.Queue, _queue.Queue],
+ ids=["asyncio", "threading"],
+)
+def test_collapse_out_of_band_keeps_latest_per_type(
+ queue_factory: Any,
+) -> None:
+ q = queue_factory()
+ completion_old = CodeCompletionCommand(
+ id="r1", document="x.", cell_id="c1"
+ )
+ breakpoints = SetBreakpointsCommand(breakpoints={"c1": [1]})
+ completion_new = CodeCompletionCommand(
+ id="r2", document="y.", cell_id="c1"
+ )
+ q.put_nowait(breakpoints)
+ q.put_nowait(completion_new)
+
+ result = collapse_out_of_band(q, first=completion_old)
+
+ # One command per type, latest wins, in first-seen order.
+ assert result == [completion_new, breakpoints]
+ assert q.empty()
+
+
def test_make_control_enqueuer_routes_plain_command_to_control_only() -> None:
control: asyncio.Queue[Any] = asyncio.Queue()
ui: asyncio.Queue[Any] = asyncio.Queue()
diff --git a/tests/_runtime/test_request_router.py b/tests/_runtime/test_request_router.py
index 0e53b3492b..359e2f7f26 100644
--- a/tests/_runtime/test_request_router.py
+++ b/tests/_runtime/test_request_router.py
@@ -19,6 +19,7 @@ from marimo._runtime.commands import (
ClearCacheCommand,
CodeCompletionCommand,
CommandMessage,
+ SetBreakpointsCommand,
StopKernelCommand,
)
from marimo._runtime.kernel_request_handlers import KernelRequestHandlers
@@ -40,9 +41,11 @@ ALL_CALLBACKS: list[type] = [
]
# Commands that are part of the CommandMessage dispatch surface but are
-# intentionally not handled by the kernel's RequestRouter. CodeCompletionCommand
-# is delivered on its own queue and processed by start_completion_worker.
-NOT_ROUTED: set[type] = {CodeCompletionCommand}
+# intentionally not handled by the kernel's RequestRouter. These are delivered
+# on the off-main-loop completion queue and processed by
+# start_completion_worker: CodeCompletionCommand (autocomplete) and
+# SetBreakpointsCommand (live-debugger breakpoints, so they apply mid-run).
+NOT_ROUTED: set[type] = {CodeCompletionCommand, SetBreakpointsCommand}
def _all_command_classes() -> set[type]:
diff --git a/tests/_session/test_queue.py b/tests/_session/test_queue.py
index 5a2b921f81..b201acdf7f 100644
--- a/tests/_session/test_queue.py
+++ b/tests/_session/test_queue.py
@@ -7,6 +7,7 @@ from marimo._runtime.commands import (
CodeCompletionCommand,
ModelCommand,
ModelUpdateMessage,
+ SetBreakpointsCommand,
StopKernelCommand,
UpdateUIElementCommand,
)
@@ -27,6 +28,18 @@ class TestRouteControlRequest:
control.put.assert_not_called()
ui_element.put.assert_not_called()
+ def test_breakpoints_go_to_completion_queue_only(self) -> None:
+ # Breakpoints are drained off the main loop so they apply even while a
+ # cell is executing (the control queue is blocked behind it).
+ control, completion, ui_element = self._make_queues()
+ cmd = SetBreakpointsCommand(breakpoints={"c1": [1, 2]})
+
+ route_control_request(cmd, control, completion, ui_element)
+
+ completion.put.assert_called_once_with(cmd)
+ control.put.assert_not_called()
+ ui_element.put.assert_not_called()
+
def test_ui_element_goes_to_both_queues(self) -> None:
control, completion, ui_element = self._make_queues()
cmd = UpdateUIElementCommand(object_ids=["ui1"], values=[42])