diff --git a/frontend/src/core/cells/__tests__/cell-errors.test.tsx b/frontend/src/core/cells/__tests__/cell-errors.test.tsx new file mode 100644 index 00000000000..608daf45caa --- /dev/null +++ b/frontend/src/core/cells/__tests__/cell-errors.test.tsx @@ -0,0 +1,179 @@ +/* Copyright 2026 Marimo. All rights reserved. */ + +import { act, render, screen } from "@testing-library/react"; +import { createStore, Provider } from "jotai"; +import { Profiler } from "react"; +import { describe, expect, it, onTestFinished, vi } from "vitest"; +import { mockAnimationFrames } from "@/__mocks__/animation-frames"; +import { type ExecutionEntries, MockExecutions } from "@/__mocks__/executions"; +import { MockNotebook } from "@/__mocks__/notebook"; +import { cellId } from "@/__tests__/branded"; +import { createRenderTracker } from "@/__tests__/render-tracker"; +import { cellOutputAtom, clearCellOutputs } from "@/core/executions"; +import { + cell, + document as documentOf, + withCells, +} from "@/core/notebook/document/__tests__/fixtures"; +import { createReplicaFrame } from "@/core/notebook/replica"; +import { activeNotebookFrameAtom } from "@/core/session/active-notebook"; +import { + cellErrorCount, + cellErrorsAtom, + getNotebookActionsForStore, + useCellErrors, +} from "../cells"; + +const first = cellId("c1"); +const second = cellId("c2"); +const third = cellId("c3"); +const firstError = MockExecutions.failed(first); +const secondError = MockExecutions.failed(second); +const ancestorError = MockExecutions.completed(second, { + kind: "skipped", + reason: "upstream-stopped", + message: "The upstream cell stopped", + related: [{ cell_id: first, range: null, message: "Stopped here" }], +}); + +function setup(size: number, ...entries: ExecutionEntries) { + const store = createStore(); + const actions = getNotebookActionsForStore(store); + const order = Array.from({ length: size }, (_, i) => cellId(`c${i + 1}`)); + const confirmed = withCells( + documentOf(), + Object.fromEntries(order.map((id) => [id, cell(id, "pass", { name: id })])), + ); + const cells = new Map(confirmed.cells); + actions.reconcileDocument({ order, cells }); + const replica = MockExecutions.seed(store, entries, null, confirmed); + const receive = (records: ExecutionEntries) => { + const next = MockExecutions.inputs(records); + store.set(replica.executionsAtom, next.executions); + store.set(replica.resultsAtom, next.results); + }; + return { store, actions, order, cells, replica, receive }; +} + +function ErrorNames() { + const names = useCellErrors().map((error) => error.cellName); + return {names.join(", ")}; +} + +describe("cellErrorsAtom", () => { + it.each([5, 500])("skips unrelated updates with %i cells", (size) => { + const { store, actions, order, cells, replica, receive } = setup( + size, + firstError, + ); + const advanceFrame = mockAnimationFrames(); + const lifetime = new AbortController(); + onTestFinished(() => lifetime.abort()); + store.set( + activeNotebookFrameAtom, + createReplicaFrame(store, replica, { signal: lifetime.signal }), + ); + const read = vi.spyOn(cellErrorsAtom, "read"); + onTestFinished(() => read.mockRestore()); + const renders = createRenderTracker(); + render( + + + + + , + ); + const before = store.get(cellErrorsAtom); + renders.reset(); + read.mockClear(); + + act(() => { + actions.startCellConsole({ cellId: second }); + cells.set(first, cell(first, "fixed()", { name: first })); + cells.set(second, cell(second, "pass", { name: "renamed" })); + actions.reconcileDocument({ order, cells }); + }); + act(() => { + receive([ + firstError, + MockExecutions.shown(second, { mimetype: "text/plain", data: "42" }), + ]); + advanceFrame(); + }); + expect(store.get(cellOutputAtom(second))?.data).toBe("42"); + act(() => { + receive([firstError, ancestorError]); + advanceFrame(); + }); + expect(store.get(cellOutputAtom(second))?.data).toEqual([ + expect.objectContaining({ type: "ancestor-stopped" }), + ]); + expect(read).not.toHaveBeenCalled(); + expect(renders.counts()).toEqual({}); + expect(store.get(cellErrorsAtom)).toBe(before); + + act(() => { + receive([firstError, secondError]); + advanceFrame(); + }); + expect(read).toHaveBeenCalledOnce(); + expect(renders.counts()).toEqual({ errors: 1 }); + expect(screen.getByRole("status").textContent).toBe("c1, renamed"); + }); + + it("tracks order, names, clear, and cell lifetime within each store", () => { + const { store, actions, cells, order } = setup(3, firstError, secondError); + const other = setup(2, firstError).store; + const otherErrors = other.get(cellErrorsAtom); + const names = () => + store.get(cellErrorsAtom).map((error) => error.cellName); + expect(names()).toEqual([first, second]); + + cells.set(first, cell(first, "pass", { name: "renamed" })); + actions.reconcileDocument({ order, cells }); + expect(names()).toEqual(["renamed", second]); + const before = store.get(cellErrorsAtom); + actions.reconcileDocument({ order: [third, first, second], cells }); + expect(store.get(cellErrorsAtom)).toBe(before); + actions.reconcileDocument({ order: [third, second, first], cells }); + expect(names()).toEqual([second, "renamed"]); + clearCellOutputs(store, [second]); + expect(store.get(cellErrorCount)).toBe(1); + cells.delete(first); + actions.reconcileDocument({ order: [third, second], cells }); + expect(names()).toEqual([]); + + cells.set(first, cell(first, "pass", { name: "restored" })); + actions.reconcileDocument({ order, cells }); + expect(names()).toEqual(["restored"]); + expect(other.get(cellErrorsAtom)).toBe(otherErrors); + expect(otherErrors.map((error) => error.cellName)).toEqual([first]); + }); + + it("keeps actionable errors in a mixed output", () => { + const { store } = setup(2); + const actionable = [ + MockNotebook.errors.exception("Division by zero"), + MockNotebook.errors.syntax("Invalid syntax"), + ]; + const output = { + channel: "marimo-error", + mimetype: "application/vnd.marimo+error", + timestamp: 1, + data: [ + ...actionable, + { + type: "ancestor-stopped", + raising_cell: second, + msg: "Upstream stop", + }, + ], + } as const; + const read = vi + .spyOn(cellOutputAtom(first), "read") + .mockReturnValue(output); + onTestFinished(() => read.mockRestore()); + expect(store.get(cellErrorsAtom)[0]?.output.data).toEqual(actionable); + expect(store.get(cellErrorCount)).toBe(1); + }); +}); diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts index 44a4d2e2fa3..3ea1a2bac95 100644 --- a/frontend/src/core/cells/cells.ts +++ b/frontend/src/core/cells/cells.ts @@ -18,6 +18,7 @@ import { releaseCellOutputAtoms, } from "@/core/executions"; import type { CellColumnId } from "./layout"; +import { arrayShallowEquals } from "@/utils/arrays"; import { Functions } from "@/utils/functions"; import { invariant } from "@/utils/invariant"; import { Logger } from "@/utils/Logger"; @@ -446,36 +447,31 @@ export const runReasonAtom = atom((get) => export const needsRunAtom = atom((get) => get(runReasonAtom) !== null); -export const cellErrorsAtom = atom((get) => { - const { cellIds, cellData } = get(notebookAtom); - const errors = cellIds - .map((cellId) => { - const output = get(cellOutputAtom(cellId)); - const { name } = cellData[cellId]; - if (output !== null && isErrorMime(output.mimetype)) { - // Filter out ancestor-stopped errors - // These are errors that are caused by a cell that was stopped, - // but nothing the user can take action on. - invariant(Array.isArray(output.data), "Expected array data"); - const nonAncestorErrors = output.data.filter( - (error) => !error.type.includes("ancestor"), - ); - - if (nonAncestorErrors.length > 0) { - return { - output: { ...output, data: nonAncestorErrors }, - cellId: cellId, - cellName: name, - }; - } - } - +const cellErrorAtom = atomFamily((cellId: CellId) => { + const errorOutputAtom = atom((get) => { + const output = get(cellOutputAtom(cellId)); + if (output === null || !isErrorMime(output.mimetype)) { return null; - }) - .filter(Boolean); - return errors; + } + invariant(Array.isArray(output.data), "Expected array data"); + const data = output.data.filter( + (error) => !error.type.includes("ancestor"), + ); + return data.length > 0 ? { ...output, data } : null; + }); + const nameAtom = atom((get) => get(cellDataAtom(cellId))?.name); + return atom((get) => { + const output = get(errorOutputAtom); + return output && { output, cellId, cellName: get(nameAtom) }; + }); }); +export const cellErrorsAtom = selectAtom( + atom((get) => get(cellIdsAtom).map((id) => get(cellErrorAtom(id)))), + (entries) => entries.filter(Boolean), + arrayShallowEquals, +); + // Layout needs lookup by cell ID. Navigation needs the same headings in document order. const orderedCellOutlines = selectAtom( atom((get) => { @@ -616,6 +612,7 @@ export const cellHandleAtom = atomFamily((cellId: CellId) => * @see https://jotai.org/docs/utilities/family#caveat-memory-leaks */ export function releaseCellAtoms(cellId: CellId) { + cellErrorAtom.remove(cellId); cellDataAtom.remove(cellId); cellRuntimeAtom.remove(cellId); cellHandleAtom.remove(cellId);