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.

6.4 KB
Raw Blame
/* Copyright 2026 Marimo. All rights reserved. */

import type { EditorView } from "@codemirror/view";
import { Objects } from "@/utils/objects";
import type { MarimoError, OutputMessage } from "../kernel/messages";
import { isErrorMime } from "../mime";
import type { RuntimeState } from "../network/types";
import type { NotebookState } from "./cells";
import type { CellId } from "./ids";

export function notebookIsRunning(state: NotebookState) {
  return Object.values(state.cellRuntime).some(
    (cell) => cell.status === "running",
  );
}

export function notebookQueueOrRunningCount(state: NotebookState) {
  return Object.values(state.cellRuntime).filter(
    (cell) => cell.status === "running" || cell.status === "queued",
  ).length;
}

export function notebookNeedsRun(state: NotebookState) {
  return staleCellIds(state).length > 0;
}

export function notebookCells(state: NotebookState) {
  return state.cellIds.map((cellId) => state.cellData[cellId]);
}

export function notebookCellEditorViews({ cellHandles }: NotebookState) {
  const views: Record<CellId, EditorView> = {};
  for (const [cell, ref] of Objects.entries(cellHandles)) {
    if (!ref.current?.editorView) {
      continue;
    }
    views[cell] = ref.current.editorView;
  }
  return views;
}

export function disabledCellIds(state: NotebookState) {
  const { cellIds, cellData } = state;
  const disabledCells: CellId[] = [];
  for (const cellId of cellIds) {
    const cell = cellData[cellId];
    if (cell.config.disabled) {
      disabledCells.push(cellId);
    }
  }
  return disabledCells;
}

export function enabledCellIds(state: NotebookState) {
  const { cellIds, cellData } = state;
  const enabledCells: CellId[] = [];
  for (const cellId of cellIds) {
    const cell = cellData[cellId];
    if (!cell.config.disabled) {
      enabledCells.push(cellId);
    }
  }
  return enabledCells;
}

export function canUndoDeletes(state: NotebookState) {
  return state.history.length > 0;
}

/**
 * Label for the undo action based on the last history entry type.
 */
export function getUndoLabel(state: NotebookState): string {
  const last = state.history[state.history.length - 1];
  if (!last) {
    return "Undo cell deletion";
  }
  return last.type === "move" ? "Undo move" : "Undo cell deletion";
}

/**
 * Summarize the run state of the given descendants, whether any is stale,
 * errored, or running.
 */
export function getDescendantsStatus(
  state: NotebookState,
  descendants: readonly CellId[],
) {
  const stale = descendants.some(
    (id) => state.cellRuntime[id]?.staleInputs || state.cellData[id]?.edited,
  );
  const errored = descendants.some((id) => state.cellRuntime[id]?.errored);
  const runningOrQueued = descendants.some(
    (id) =>
      state.cellRuntime[id]?.status === "running" ||
      state.cellRuntime[id]?.status === "queued",
  );

  return {
    stale,
    errored,
    runningOrQueued,
  };
}

/**
 * Cells that are stale and can be run.
 */
export function staleCellIds(state: NotebookState) {
  const { cellIds, cellData, cellRuntime } = state;
  return cellIds.filter(
    (cellId) =>
      isUninstantiated({
        // runElapstedTimeMs is what we've seen in this session
        executionTime:
          cellRuntime[cellId].runElapsedTimeMs ??
          // lastExecutionTime is what was seen on session start/resume
          cellData[cellId].lastExecutionTime,
        status: cellRuntime[cellId].status,
        errored: cellRuntime[cellId].errored,
        interrupted: cellRuntime[cellId].interrupted,
        stopped: cellRuntime[cellId].stopped,
      }) ||
      cellData[cellId].edited ||
      cellRuntime[cellId].interrupted ||
      (cellRuntime[cellId].staleInputs &&
        // if a cell is disabled, it can't be run ...
        !(
          cellRuntime[cellId].status === "disabled-transitively" ||
          cellData[cellId].config.disabled
        )),
  );
}

export function isUninstantiated({
  executionTime,
  status,
  errored,
  interrupted,
  stopped,
}: {
  executionTime: number | null;
  status: RuntimeState;
  errored: boolean;
  interrupted: boolean;
  stopped: boolean;
}) {
  return (
    // hasn't run ...
    executionTime === null &&
    // isn't currently queued/running &&
    status !== "queued" &&
    status !== "running" &&
    // and isn't in an error state.
    !(errored || interrupted || stopped)
  );
}

/**
 * Whether a cell needs to be run given its edited / interrupted / stale
 * inputs, while accounting for ancestor-disabled cells (which should not be
 * flagged as needing a run until re-enabled).
 */
export function cellNeedsRun({
  edited,
  interrupted,
  staleInputs,
  disabled,
  status,
}: {
  edited: boolean;
  interrupted: boolean;
  staleInputs: boolean;
  disabled: boolean | undefined;
  status: RuntimeState;
}): boolean {
  const disabledOrAncestorDisabled =
    disabled || status === "disabled-transitively";
  return edited || interrupted || (staleInputs && !disabledOrAncestorDisabled);
}

export function cellStatusClasses({
  needsRun,
  errored,
  stopped,
  disabled,
  status,
}: {
  needsRun: boolean;
  errored: boolean;
  stopped: boolean;
  disabled: boolean | undefined;
  status: RuntimeState;
}) {
  return {
    "needs-run": needsRun,
    "has-error": errored,
    stopped,
    disabled: disabled ?? false,
    stale: status === "disabled-transitively",
  };
}

/**
 * Status classes for a published cell (read or present mode, output only).
 */
export function publishedCellClasses({
  errored,
  stopped,
}: {
  errored: boolean;
  stopped: boolean;
}) {
  return {
    published: true,
    "has-error": errored,
    stopped: stopped,
  };
}

/**
 * Whether a published cell (read or present mode) should be hidden.
 *
 * Errored, interrupted, and stopped cells (and error outputs) are hidden in
 * published views, unless `show_tracebacks` is enabled and the output carries
 * an exception traceback to display inline.
 */
export function shouldHidePublishedCell({
  errored,
  interrupted,
  stopped,
  output,
  showErrorTracebacks,
}: {
  errored: boolean;
  interrupted: boolean;
  stopped: boolean;
  output: OutputMessage | null;
  showErrorTracebacks: boolean;
}): boolean {
  const outputIsError = isErrorMime(output?.mimetype);
  const hasTraceback =
    showErrorTracebacks &&
    outputIsError &&
    Array.isArray(output?.data) &&
    output.data.some(
      (e: MarimoError) =>
        e.type === "exception" && "traceback" in e && e.traceback,
    );
  return (errored || interrupted || stopped || outputIsError) && !hasTraceback;
}