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.

support images mimebundling in auto export for ipynb (#7825)

Shahmir Varqha1226783969ab
diff --git a/frontend/src/__mocks__/requests.ts b/frontend/src/__mocks__/requests.ts
index bff13d9afa..25d6629654 100644
--- a/frontend/src/__mocks__/requests.ts
+++ b/frontend/src/__mocks__/requests.ts
@@ -63,6 +63,7 @@ export const MockRequestClient = {
autoExportAsHTML: vi.fn().mockResolvedValue({}),
autoExportAsMarkdown: vi.fn().mockResolvedValue({}),
autoExportAsIPYNB: vi.fn().mockResolvedValue({}),
+ updateCellOutputs: vi.fn().mockResolvedValue({}),
addPackage: vi.fn().mockResolvedValue({}),
removePackage: vi.fn().mockResolvedValue({}),
getPackageList: vi.fn().mockResolvedValue({ packages: [] }),
diff --git a/frontend/src/core/cells/cells.ts b/frontend/src/core/cells/cells.ts
index 39234a5ac3..96b0763540 100644
--- a/frontend/src/core/cells/cells.ts
+++ b/frontend/src/core/cells/cells.ts
@@ -1594,6 +1594,8 @@ const cellDataAtoms = splitAtom(
);
export const useCellDataAtoms = () => useAtom(cellDataAtoms);
+export const cellsRuntimeAtom = atom((get) => get(notebookAtom).cellRuntime);
+
export const notebookIsRunningAtom = atom((get) =>
notebookIsRunning(get(notebookAtom)),
);
diff --git a/frontend/src/core/export/__tests__/hooks.test.ts b/frontend/src/core/export/__tests__/hooks.test.ts
new file mode 100644
index 0000000000..4c65c1d172
--- /dev/null
+++ b/frontend/src/core/export/__tests__/hooks.test.ts
@@ -0,0 +1,504 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { renderHook } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import type { ReactNode } from "react";
+import * as React from "react";
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import type { CellId } from "@/core/cells/ids";
+import { CellOutputId } from "@/core/cells/ids";
+import type { CellRuntimeState } from "@/core/cells/types";
+import { useEnrichCellOutputs } from "../hooks";
+
+// Mock html-to-image
+vi.mock("html-to-image", () => ({
+ toPng: vi.fn(),
+}));
+
+// Mock Logger
+vi.mock("@/utils/Logger", () => ({
+ Logger: {
+ error: vi.fn(),
+ },
+}));
+
+// Mock cellsRuntimeAtom - must be defined inline in the factory function
+vi.mock("@/core/cells/cells", async () => {
+ const { atom } = await import("jotai");
+ return {
+ cellsRuntimeAtom: atom({}),
+ };
+});
+
+import { toPng } from "html-to-image";
+import { cellsRuntimeAtom } from "@/core/cells/cells";
+import { Logger } from "@/utils/Logger";
+
+describe("useEnrichCellOutputs", () => {
+ let store: ReturnType<typeof createStore>;
+
+ beforeEach(() => {
+ vi.clearAllMocks();
+ store = createStore();
+ });
+
+ const wrapper = ({ children }: { children: ReactNode }) =>
+ React.createElement(Provider, { store }, children);
+
+ // Helper to set the mocked atom (cast to any to work around type mismatch)
+ const setCellsRuntime = (value: Record<CellId, CellRuntimeState>) => {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ store.set(cellsRuntimeAtom as any, value);
+ };
+
+ const createMockCellRuntimes = (
+ cells: Record<string, Partial<CellRuntimeState>>,
+ ): Record<CellId, CellRuntimeState> => {
+ return Object.fromEntries(
+ Object.entries(cells).map(([cellId, cell]) => [
+ cellId as CellId,
+ {
+ output: cell.output || null,
+ status: cell.status || "idle",
+ interrupted: false,
+ errored: false,
+ runStartTimestamp: null,
+ runElapsedTimeMs: null,
+ stallTime: null as unknown as number,
+ ...cell,
+ } as CellRuntimeState,
+ ]),
+ ) as Record<CellId, CellRuntimeState>;
+ };
+
+ it("should return empty object when no cells need screenshots", async () => {
+ vi.spyOn(document, "getElementById");
+
+ // Set up cell runtimes with no text/html outputs
+ setCellsRuntime(
+ createMockCellRuntimes({
+ "cell-1": {
+ output: {
+ channel: "output",
+ mimetype: "text/plain",
+ data: "Hello World",
+ timestamp: 0,
+ },
+ },
+ }),
+ );
+
+ const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
+
+ const enrichCellOutputs = result.current;
+ const output = await enrichCellOutputs();
+
+ expect(output).toEqual({});
+ expect(document.getElementById).not.toHaveBeenCalled();
+ expect(toPng).not.toHaveBeenCalled();
+ });
+
+ it("should capture screenshots for cells with text/html output", async () => {
+ const cellId = "cell-1" as CellId;
+ const mockElement = document.createElement("div");
+ const mockDataUrl = "data:image/png;base64,mockImageData";
+
+ // Mock document.getElementById
+ vi.spyOn(document, "getElementById").mockReturnValue(mockElement);
+ vi.mocked(toPng).mockResolvedValue(mockDataUrl);
+
+ setCellsRuntime(
+ createMockCellRuntimes({
+ [cellId]: {
+ output: {
+ channel: "output",
+ mimetype: "text/html",
+ data: "<div>Chart</div>",
+ timestamp: 0,
+ },
+ },
+ }),
+ );
+
+ const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
+
+ const enrichCellOutputs = result.current;
+ const output = await enrichCellOutputs();
+
+ expect(document.getElementById).toHaveBeenCalledWith(
+ CellOutputId.create(cellId),
+ );
+ expect(toPng).toHaveBeenCalledWith(mockElement);
+ expect(output).toEqual({
+ [cellId]: ["image/png", mockDataUrl],
+ });
+ });
+
+ it("should skip cells where output has not changed", async () => {
+ const cellId = "cell-1" as CellId;
+ const mockElement = document.createElement("div");
+ const mockDataUrl = "data:image/png;base64,mockImageData";
+ const htmlData = "<div>Chart</div>";
+
+ vi.spyOn(document, "getElementById").mockReturnValue(mockElement);
+ vi.mocked(toPng).mockResolvedValue(mockDataUrl);
+
+ setCellsRuntime(
+ createMockCellRuntimes({
+ [cellId]: {
+ output: {
+ channel: "output",
+ mimetype: "text/html",
+ data: htmlData,
+ timestamp: 0,
+ },
+ },
+ }),
+ );
+
+ const { result, rerender } = renderHook(() => useEnrichCellOutputs(), {
+ wrapper,
+ });
+
+ // First call - should capture
+ let enrichCellOutputs = result.current;
+ let output = await enrichCellOutputs();
+ expect(output).toEqual({ [cellId]: ["image/png", mockDataUrl] });
+ expect(toPng).toHaveBeenCalledTimes(1);
+
+ // Rerender to get updated atom state
+ rerender();
+
+ // Second call with same output - should not capture again
+ enrichCellOutputs = result.current;
+ output = await enrichCellOutputs();
+ expect(output).toEqual({}); // Empty because output hasn't changed
+ expect(toPng).toHaveBeenCalledTimes(1); // Still only 1 call
+ });
+
+ it("should handle screenshot errors gracefully", async () => {
+ const cellId = "cell-1" as CellId;
+ const mockElement = document.createElement("div");
+ const error = new Error("Screenshot failed");
+
+ vi.spyOn(document, "getElementById").mockReturnValue(mockElement);
+ vi.mocked(toPng).mockRejectedValue(error);
+
+ setCellsRuntime(
+ createMockCellRuntimes({
+ [cellId]: {
+ output: {
+ channel: "output",
+ mimetype: "text/html",
+ data: "<div>Chart</div>",
+ timestamp: 0,
+ },
+ },
+ }),
+ );
+
+ const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
+
+ const enrichCellOutputs = result.current;
+ const output = await enrichCellOutputs();
+
+ expect(output).toEqual({}); // Failed screenshot should be filtered out
+ expect(Logger.error).toHaveBeenCalledWith(
+ `Error screenshotting cell ${cellId}:`,
+ error,
+ );
+ });
+
+ it("should handle missing DOM elements", async () => {
+ const cellId = "cell-1" as CellId;
+
+ vi.spyOn(document, "getElementById").mockReturnValue(null);
+
+ setCellsRuntime(
+ createMockCellRuntimes({
+ [cellId]: {
+ output: {
+ channel: "output",
+ mimetype: "text/html",
+ data: "<div>Chart</div>",
+ timestamp: 0,
+ },
+ },
+ }),
+ );
+
+ const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
+
+ const enrichCellOutputs = result.current;
+ const output = await enrichCellOutputs();
+
+ expect(output).toEqual({});
+ expect(Logger.error).toHaveBeenCalledWith(
+ `Output element not found for cell ${cellId}`,
+ );
+ expect(toPng).not.toHaveBeenCalled();
+ });
+
+ it("should process multiple cells in parallel", async () => {
+ const cell1 = "cell-1" as CellId;
+ const cell2 = "cell-2" as CellId;
+ const mockElement1 = document.createElement("div");
+ const mockElement2 = document.createElement("div");
+ const mockDataUrl1 = "data:image/png;base64,image1";
+ const mockDataUrl2 = "data:image/png;base64,image2";
+
+ vi.spyOn(document, "getElementById")
+ .mockReturnValueOnce(mockElement1)
+ .mockReturnValueOnce(mockElement2);
+
+ vi.mocked(toPng)
+ .mockResolvedValueOnce(mockDataUrl1)
+ .mockResolvedValueOnce(mockDataUrl2);
+
+ setCellsRuntime(
+ createMockCellRuntimes({
+ [cell1]: {
+ output: {
+ channel: "output",
+ mimetype: "text/html",
+ data: "<div>Chart 1</div>",
+ timestamp: 0,
+ },
+ },
+ [cell2]: {
+ output: {
+ channel: "output",
+ mimetype: "text/html",
+ data: "<div>Chart 2</div>",
+ timestamp: 0,
+ },
+ },
+ }),
+ );
+
+ const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
+
+ const enrichCellOutputs = result.current;
+ const output = await enrichCellOutputs();
+
+ expect(output).toEqual({
+ [cell1]: ["image/png", mockDataUrl1],
+ [cell2]: ["image/png", mockDataUrl2],
+ });
+ expect(toPng).toHaveBeenCalledTimes(2);
+ });
+
+ it("should filter out null results from failed screenshots", async () => {
+ // Setup: one successful, one failed screenshot
+ const cell1 = "cell-1" as CellId;
+ const cell2 = "cell-2" as CellId;
+ const mockElement1 = document.createElement("div");
+ const mockDataUrl = "data:image/png;base64,image1";
+
+ vi.spyOn(document, "getElementById")
+ .mockReturnValueOnce(mockElement1)
+ .mockReturnValueOnce(null); // Second cell fails to find element
+
+ vi.mocked(toPng).mockResolvedValue(mockDataUrl);
+
+ setCellsRuntime(
+ createMockCellRuntimes({
+ [cell1]: {
+ output: {
+ channel: "output",
+ mimetype: "text/html",
+ data: "<div>Chart 1</div>",
+ timestamp: 0,
+ },
+ },
+ [cell2]: {
+ output: {
+ channel: "output",
+ mimetype: "text/html",
+ data: "<div>Chart 2</div>",
+ timestamp: 0,
+ },
+ },
+ }),
+ );
+
+ const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
+
+ const enrichCellOutputs = result.current;
+ const output = await enrichCellOutputs();
+
+ // Only the successful screenshot should be in the result
+ expect(output).toEqual({
+ [cell1]: ["image/png", mockDataUrl],
+ });
+ expect(Logger.error).toHaveBeenCalledWith(
+ `Output element not found for cell ${cell2}`,
+ );
+ });
+
+ it("should only capture screenshots for cells with changed output", async () => {
+ const cellId = "cell-1" as CellId;
+ const mockElement = document.createElement("div");
+ const mockDataUrl1 = "data:image/png;base64,image1";
+ const mockDataUrl2 = "data:image/png;base64,image2";
+
+ vi.spyOn(document, "getElementById").mockReturnValue(mockElement);
+ vi.mocked(toPng)
+ .mockResolvedValueOnce(mockDataUrl1)
+ .mockResolvedValueOnce(mockDataUrl2);
+
+ // First call - cell should be captured
+ setCellsRuntime(
+ createMockCellRuntimes({
+ [cellId]: {
+ output: {
+ channel: "output",
+ mimetype: "text/html",
+ data: "<div>Chart v1</div>",
+ timestamp: 0,
+ },
+ },
+ }),
+ );
+
+ const { result, rerender } = renderHook(() => useEnrichCellOutputs(), {
+ wrapper,
+ });
+
+ // First screenshot
+ let enrichCellOutputs = result.current;
+ let output = await enrichCellOutputs();
+ expect(output).toEqual({ [cellId]: ["image/png", mockDataUrl1] });
+
+ // Second call - same output, should not be captured
+ rerender();
+ enrichCellOutputs = result.current;
+ output = await enrichCellOutputs();
+ expect(output).toEqual({});
+
+ // Third call - output changed, should be captured
+ setCellsRuntime(
+ createMockCellRuntimes({
+ [cellId]: {
+ output: {
+ channel: "output",
+ mimetype: "text/html",
+ data: "<div>Chart v2</div>", // Changed!
+ timestamp: 0,
+ },
+ },
+ }),
+ );
+
+ rerender();
+ enrichCellOutputs = result.current;
+ output = await enrichCellOutputs();
+ expect(output).toEqual({ [cellId]: ["image/png", mockDataUrl2] });
+ expect(toPng).toHaveBeenCalledTimes(2);
+ });
+
+ it("should ignore cells with non-text/html mimetype", async () => {
+ vi.spyOn(document, "getElementById");
+
+ setCellsRuntime(
+ createMockCellRuntimes({
+ "cell-1": {
+ output: {
+ channel: "output",
+ mimetype: "application/json",
+ data: '{"key": "value"}',
+ timestamp: 0,
+ },
+ },
+ "cell-2": {
+ output: {
+ channel: "output",
+ mimetype: "text/plain",
+ data: "Plain text",
+ timestamp: 0,
+ },
+ },
+ "cell-3": {
+ output: {
+ channel: "output",
+ mimetype: "image/png",
+ data: "data:image/png;base64,existing",
+ timestamp: 0,
+ },
+ },
+ }),
+ );
+
+ const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
+
+ const enrichCellOutputs = result.current;
+ const output = await enrichCellOutputs();
+
+ // None of these should trigger screenshots
+ expect(output).toEqual({});
+ expect(document.getElementById).not.toHaveBeenCalled();
+ expect(toPng).not.toHaveBeenCalled();
+ });
+
+ it("should ignore cells with null or undefined output", async () => {
+ vi.spyOn(document, "getElementById");
+
+ setCellsRuntime(
+ createMockCellRuntimes({
+ "cell-1": {
+ output: null,
+ },
+ "cell-2": {
+ output: undefined,
+ },
+ }),
+ );
+
+ const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
+
+ const enrichCellOutputs = result.current;
+ const output = await enrichCellOutputs();
+
+ expect(output).toEqual({});
+ expect(document.getElementById).not.toHaveBeenCalled();
+ expect(toPng).not.toHaveBeenCalled();
+ });
+
+ it("should return correctly formatted result with CellId and tuple", async () => {
+ // Expected format: Record<CellId, ["image/png", string]>
+ const cellId = "test-cell" as CellId;
+ const mockElement = document.createElement("div");
+ const mockDataUrl = "data:image/png;base64,testData";
+
+ vi.spyOn(document, "getElementById").mockReturnValue(mockElement);
+ vi.mocked(toPng).mockResolvedValue(mockDataUrl);
+
+ setCellsRuntime(
+ createMockCellRuntimes({
+ [cellId]: {
+ output: {
+ channel: "output",
+ mimetype: "text/html",
+ data: "<div>Content</div>",
+ timestamp: 0,
+ },
+ },
+ }),
+ );
+
+ const { result } = renderHook(() => useEnrichCellOutputs(), { wrapper });
+
+ const enrichCellOutputs = result.current;
+ const output = await enrichCellOutputs();
+
+ // Verify the exact return type structure
+ expect(output).toHaveProperty(cellId);
+ const cellOutput = output[cellId];
+ expect(cellOutput).toBeDefined();
+ expect(Array.isArray(cellOutput)).toBe(true);
+ if (cellOutput) {
+ expect(cellOutput[0]).toBe("image/png");
+ expect(cellOutput[1]).toBe(mockDataUrl);
+ }
+ });
+});
diff --git a/frontend/src/core/export/hooks.ts b/frontend/src/core/export/hooks.ts
index d795a4f3db..b600317499 100644
--- a/frontend/src/core/export/hooks.ts
+++ b/frontend/src/core/export/hooks.ts
@@ -1,7 +1,12 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { useAtomValue } from "jotai";
+import { toPng } from "html-to-image";
+import { atom, useAtom, useAtomValue } from "jotai";
import { appConfigAtom } from "@/core/config/config";
import { useInterval } from "@/hooks/useInterval";
+import { Logger } from "@/utils/Logger";
+import { Objects } from "@/utils/objects";
+import { cellsRuntimeAtom } from "../cells/cells";
+import { type CellId, CellOutputId } from "../cells/ids";
import { connectionAtom } from "../network/connection";
import { useRequestClient } from "../network/requests";
import { VirtualFileTracker } from "../static/virtual-file-tracker";
@@ -21,8 +26,13 @@ export function useAutoExport() {
const markdownDisabled = !markdownEnabled || !isConnected;
const htmlDisabled = !htmlEnabled || !isConnected;
const ipynbDisabled = !ipynbEnabled || !isConnected;
- const { autoExportAsHTML, autoExportAsIPYNB, autoExportAsMarkdown } =
- useRequestClient();
+ const {
+ autoExportAsHTML,
+ autoExportAsIPYNB,
+ autoExportAsMarkdown,
+ updateCellOutputs,
+ } = useRequestClient();
+ const takeScreenshots = useEnrichCellOutputs();
useInterval(
async () => {
@@ -50,12 +60,91 @@ export function useAutoExport() {
useInterval(
async () => {
+ const cellsToOutput = await takeScreenshots();
+ if (Object.keys(cellsToOutput).length > 0) {
+ await updateCellOutputs({
+ cellIdsToOutput: cellsToOutput,
+ });
+ }
await autoExportAsIPYNB({
download: false,
});
},
// Run every 5 seconds, or when the document becomes visible
// Ignore if the document is not visible
- { delayMs: DELAY, whenVisible: true, disabled: ipynbDisabled },
+ // Skip if running to ensure no race conditions between screenshot and export
+ {
+ delayMs: DELAY,
+ whenVisible: true,
+ disabled: ipynbDisabled,
+ skipIfRunning: true,
+ },
);
}
+
+// We track cells that need screenshots, these will be exported to IPYNB
+const richCellsToOutputAtom = atom<Record<CellId, unknown>>({});
+
+/**
+ * Take screenshots of cells with HTML outputs. These images will be sent to the backend to be exported to IPYNB.
+ * @returns A map of cell IDs to their screenshots data.
+ */
+export function useEnrichCellOutputs() {
+ const [richCellsOutput, setRichCellsOutput] = useAtom(richCellsToOutputAtom);
+ const cellRuntimes = useAtomValue(cellsRuntimeAtom);
+
+ return async (): Promise<Record<CellId, ["image/png", string]>> => {
+ const trackedCellsOutput: Record<CellId, unknown> = {};
+
+ const cellsToCaptureScreenshot: [CellId, unknown][] = [];
+ for (const [cellId, runtime] of Objects.entries(cellRuntimes)) {
+ const outputData = runtime.output?.data;
+ const outputHasChanged = richCellsOutput[cellId] !== outputData;
+ // Track latest output for this cell
+ trackedCellsOutput[cellId] = outputData;
+ if (
+ runtime.output?.mimetype === "text/html" &&
+ outputData &&
+ outputHasChanged
+ ) {
+ cellsToCaptureScreenshot.push([cellId, runtime]);
+ }
+ }
+ // Always update tracked outputs, this ensures data is fresh for the next run
+ setRichCellsOutput(trackedCellsOutput);
+
+ if (cellsToCaptureScreenshot.length === 0) {
+ return {};
+ }
+
+ // Capture screenshots
+ const results = await Promise.all(
+ cellsToCaptureScreenshot.map(async ([cellId]) => {
+ const outputElement = document.getElementById(
+ CellOutputId.create(cellId),
+ );
+ if (!outputElement) {
+ Logger.error(`Output element not found for cell ${cellId}`);
+ return null;
+ }
+
+ try {
+ const dataUrl = await toPng(outputElement);
+ return [cellId, ["image/png", dataUrl]] as [
+ CellId,
+ ["image/png", string],
+ ];
+ } catch (error) {
+ Logger.error(`Error screenshotting cell ${cellId}:`, error);
+ return null;
+ }
+ }),
+ );
+
+ return Objects.fromEntries(
+ results.filter(
+ (result): result is [CellId, ["image/png", string]] => result !== null,
+ ),
+ );
+ };
+}
diff --git a/frontend/src/core/islands/bridge.ts b/frontend/src/core/islands/bridge.ts
index 5966155ef6..993e1885a2 100644
--- a/frontend/src/core/islands/bridge.ts
+++ b/frontend/src/core/islands/bridge.ts
@@ -171,6 +171,7 @@ export class IslandsPyodideBridge implements RunRequests, EditRequests {
autoExportAsHTML = throwNotImplemented;
autoExportAsMarkdown = throwNotImplemented;
autoExportAsIPYNB = throwNotImplemented;
+ updateCellOutputs = throwNotImplemented;
addPackage = throwNotImplemented;
removePackage = throwNotImplemented;
getPackageList = throwNotImplemented;
diff --git a/frontend/src/core/network/requests-lazy.ts b/frontend/src/core/network/requests-lazy.ts
index c507fa8164..edca97304d 100644
--- a/frontend/src/core/network/requests-lazy.ts
+++ b/frontend/src/core/network/requests-lazy.ts
@@ -67,6 +67,7 @@ const ACTIONS: Record<keyof AllRequests, Action> = {
autoExportAsHTML: "waitForConnectionOpen",
autoExportAsMarkdown: "waitForConnectionOpen",
autoExportAsIPYNB: "waitForConnectionOpen",
+ updateCellOutputs: "waitForConnectionOpen",
// Sidebar operations that wait for connection
listSecretKeys: "throwError",
diff --git a/frontend/src/core/network/requests-network.ts b/frontend/src/core/network/requests-network.ts
index 458a3d696d..662298d83f 100644
--- a/frontend/src/core/network/requests-network.ts
+++ b/frontend/src/core/network/requests-network.ts
@@ -405,6 +405,14 @@ export function createNetworkRequests(): EditRequests & RunRequests {
})
.then(handleResponseReturnNull);
},
+ updateCellOutputs: async (request) => {
+ return getClient()
+ .POST("/api/export/update_cell_outputs", {
+ body: request,
+ params: getParams(),
+ })
+ .then(handleResponseReturnNull);
+ },
addPackage: (request) => {
return getClient()
.POST("/api/packages/add", {
diff --git a/frontend/src/core/network/requests-static.ts b/frontend/src/core/network/requests-static.ts
index cc0119b972..4311c9ee22 100644
--- a/frontend/src/core/network/requests-static.ts
+++ b/frontend/src/core/network/requests-static.ts
@@ -79,6 +79,7 @@ export function createStaticRequests(): EditRequests & RunRequests {
autoExportAsHTML: throwNotInEditMode,
autoExportAsMarkdown: throwNotInEditMode,
autoExportAsIPYNB: throwNotInEditMode,
+ updateCellOutputs: throwNotInEditMode,
addPackage: throwNotInEditMode,
removePackage: throwNotInEditMode,
getPackageList: throwNotInEditMode,
diff --git a/frontend/src/core/network/requests-toasting.tsx b/frontend/src/core/network/requests-toasting.tsx
index 748126fbd9..a39df411f4 100644
--- a/frontend/src/core/network/requests-toasting.tsx
+++ b/frontend/src/core/network/requests-toasting.tsx
@@ -64,6 +64,7 @@ export function createErrorToastingRequests(
autoExportAsHTML: "", // No toast
autoExportAsMarkdown: "", // No toast
autoExportAsIPYNB: "", // No toast
+ updateCellOutputs: "", // No toast
addPackage: "Failed to add package",
removePackage: "Failed to remove package",
getPackageList: "Failed to get package list",
diff --git a/frontend/src/core/network/types.ts b/frontend/src/core/network/types.ts
index c4a8328670..9b2ee1b8aa 100644
--- a/frontend/src/core/network/types.ts
+++ b/frontend/src/core/network/types.ts
@@ -21,6 +21,7 @@ export type ExportAsHTMLRequest = schemas["ExportAsHTMLRequest"];
export type ExportAsMarkdownRequest = schemas["ExportAsMarkdownRequest"];
export type ExportAsIPYNBRequest = schemas["ExportAsIPYNBRequest"];
export type ExportAsScriptRequest = schemas["ExportAsScriptRequest"];
+export type UpdateCellOutputsRequest = schemas["UpdateCellOutputsRequest"];
export type FileCreateRequest = schemas["FileCreateRequest"];
export type FileCreateResponse = schemas["FileCreateResponse"];
export type FileDeleteRequest = schemas["FileDeleteRequest"];
@@ -175,6 +176,7 @@ export interface EditRequests {
autoExportAsHTML: (request: ExportAsHTMLRequest) => Promise<null>;
autoExportAsMarkdown: (request: ExportAsMarkdownRequest) => Promise<null>;
autoExportAsIPYNB: (request: ExportAsIPYNBRequest) => Promise<null>;
+ updateCellOutputs: (request: UpdateCellOutputsRequest) => Promise<null>;
// Package requests
getPackageList: () => Promise<ListPackagesResponse>;
getDependencyTree: () => Promise<DependencyTreeResponse>;
diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.ts
index a59c695472..6fad95f10a 100644
--- a/frontend/src/core/wasm/bridge.ts
+++ b/frontend/src/core/wasm/bridge.ts
@@ -589,6 +589,7 @@ export class PyodideBridge implements RunRequests, EditRequests {
autoExportAsHTML = throwNotImplemented;
autoExportAsMarkdown = throwNotImplemented;
autoExportAsIPYNB = throwNotImplemented;
+ updateCellOutputs = throwNotImplemented;
writeSecret = throwNotImplemented;
invokeAiTool = throwNotImplemented;
clearCache = throwNotImplemented;
diff --git a/frontend/src/hooks/__tests__/useInterval.test.tsx b/frontend/src/hooks/__tests__/useInterval.test.tsx
index f39fbc6dc8..e6aaa23cde 100644
--- a/frontend/src/hooks/__tests__/useInterval.test.tsx
+++ b/frontend/src/hooks/__tests__/useInterval.test.tsx
@@ -67,4 +67,108 @@ describe("useInterval", () => {
vi.advanceTimersByTime(1000);
expect(callback).not.toHaveBeenCalled();
});
+
+ describe("skipIfRunning", () => {
+ it("should allow overlapping async calls by default", async () => {
+ let concurrentCalls = 0;
+ let maxConcurrentCalls = 0;
+
+ const callback = vi.fn(async () => {
+ concurrentCalls++;
+ maxConcurrentCalls = Math.max(maxConcurrentCalls, concurrentCalls);
+ // Simulate slow async work
+ await new Promise((resolve) => setTimeout(resolve, 2000));
+ concurrentCalls--;
+ });
+
+ renderHook(() =>
+ useInterval(callback, { delayMs: 500, whenVisible: false }),
+ );
+
+ // First call at 500ms
+ vi.advanceTimersByTime(500);
+ expect(callback).toHaveBeenCalledTimes(1);
+
+ // Second call at 1000ms (while first is still running)
+ vi.advanceTimersByTime(500);
+ expect(callback).toHaveBeenCalledTimes(2);
+
+ // Third call at 1500ms
+ vi.advanceTimersByTime(500);
+ expect(callback).toHaveBeenCalledTimes(3);
+
+ // Multiple concurrent calls should have occurred
+ expect(maxConcurrentCalls).toBeGreaterThan(1);
+ });
+
+ it("should skip calls when skipIfRunning is true", async () => {
+ let concurrentCalls = 0;
+ let maxConcurrentCalls = 0;
+
+ const callback = vi.fn(async () => {
+ concurrentCalls++;
+ maxConcurrentCalls = Math.max(maxConcurrentCalls, concurrentCalls);
+ // Simulate slow async work (3 seconds)
+ await new Promise<void>((resolve) => setTimeout(resolve, 3000));
+ concurrentCalls--;
+ });
+
+ renderHook(() =>
+ useInterval(callback, {
+ delayMs: 500,
+ whenVisible: false,
+ skipIfRunning: true,
+ }),
+ );
+
+ // First call at 500ms
+ await vi.advanceTimersByTimeAsync(500);
+ expect(callback).toHaveBeenCalledTimes(1);
+
+ // Second interval tick at 1000ms - should be skipped since first is still running
+ await vi.advanceTimersByTimeAsync(500);
+ expect(callback).toHaveBeenCalledTimes(1); // Still 1, not 2
+
+ // Third interval tick at 1500ms - should still be skipped
+ await vi.advanceTimersByTimeAsync(500);
+ expect(callback).toHaveBeenCalledTimes(1); // Still 1
+
+ // Only one concurrent call should have occurred
+ expect(maxConcurrentCalls).toBe(1);
+
+ // Advance past the 3 second timeout to complete first callback
+ await vi.advanceTimersByTimeAsync(2000);
+
+ // Next interval tick should now be able to run
+ await vi.advanceTimersByTimeAsync(500);
+ expect(callback).toHaveBeenCalledTimes(2);
+ });
+
+ it("should allow next call after previous async call completes with skipIfRunning true", async () => {
+ const callback = vi.fn(async () => {
+ // Quick async operation
+ await Promise.resolve();
+ });
+
+ renderHook(() =>
+ useInterval(callback, {
+ delayMs: 1000,
+ whenVisible: false,
+ skipIfRunning: true,
+ }),
+ );
+
+ // First call
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(callback).toHaveBeenCalledTimes(1);
+
+ // Second call - should proceed since first completed
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(callback).toHaveBeenCalledTimes(2);
+
+ // Third call
+ await vi.advanceTimersByTimeAsync(1000);
+ expect(callback).toHaveBeenCalledTimes(3);
+ });
+ });
});
diff --git a/frontend/src/hooks/useInterval.ts b/frontend/src/hooks/useInterval.ts
index 66b99ef6d1..a5f7cf5e40 100644
--- a/frontend/src/hooks/useInterval.ts
+++ b/frontend/src/hooks/useInterval.ts
@@ -1,9 +1,16 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { useEffect, useRef } from "react";
+import { useCallback, useEffect, useRef } from "react";
import { useEventListener } from "./useEventListener";
/**
* Creates an interval that runs a callback every `delayMs` milliseconds.
+ *
+ * @param callback - The callback to run.
+ * @param opts - The options for the interval.
+ * @param opts.delayMs - The delay in milliseconds between runs.
+ * @param opts.whenVisible - Whether to run the callback when the document is visible.
+ * @param opts.disabled - Whether to disable the interval.
+ * @param opts.skipIfRunning - Whether to skip the callback if it is already running.
*/
export function useInterval(
callback: () => void,
@@ -11,16 +18,35 @@ export function useInterval(
delayMs: number | null;
whenVisible: boolean;
disabled?: boolean;
+ skipIfRunning?: boolean;
},
) {
- const { delayMs, whenVisible, disabled = false } = opts;
- const savedCallback = useRef<() => void>(undefined);
+ const {
+ delayMs,
+ whenVisible,
+ disabled = false,
+ skipIfRunning = false,
+ } = opts;
+ const savedCallback = useRef<() => void | Promise<void>>(undefined);
+ const isRunning = useRef(false);
// Store the callback
useEffect(() => {
savedCallback.current = callback;
}, [callback]);
+ const runCallback = useCallback(async () => {
+ if (isRunning.current && skipIfRunning) {
+ return;
+ }
+ isRunning.current = true;
+ try {
+ await savedCallback.current?.();
+ } finally {
+ isRunning.current = false;
+ }
+ }, [skipIfRunning]);
+
// Run the interval
useEffect(() => {
if (delayMs === null || disabled) {
@@ -32,16 +58,16 @@ export function useInterval(
return;
}
- savedCallback.current?.();
+ runCallback();
}, delayMs);
return () => clearInterval(id);
- }, [delayMs, whenVisible, disabled]);
+ }, [delayMs, whenVisible, disabled, runCallback]);
// When the document becomes visible, run the callback
useEventListener(document, "visibilitychange", () => {
if (document.visibilityState === "visible" && whenVisible && !disabled) {
- savedCallback.current?.();
+ runCallback();
}
});
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index 6305e42b3c..a4a9d989e2 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -155,6 +155,7 @@ def _generate_server_api_schema() -> dict[str, Any]:
export.ExportAsMarkdownRequest,
export.ExportAsScriptRequest,
export.ExportAsIPYNBRequest,
+ export.UpdateCellOutputsRequest,
files.FileCreateRequest,
files.FileCreateResponse,
files.FileDeleteRequest,
diff --git a/marimo/_messaging/mimetypes.py b/marimo/_messaging/mimetypes.py
index a4870aae9e..d067dec236 100644
--- a/marimo/_messaging/mimetypes.py
+++ b/marimo/_messaging/mimetypes.py
@@ -37,7 +37,8 @@ ConsoleMimeType = Literal[
]
MimeBundle = dict[KnownMimeType, Any]
-MimeBundleOrTuple = Union[MimeBundle, tuple[MimeBundle, Any]]
+MimeBundleTuple = tuple[KnownMimeType, Any]
+MimeBundleOrTuple = Union[MimeBundle, MimeBundleTuple]
# Used for metadata in a marimo mimebundle
METADATA_KEY = "__metadata__"
diff --git a/marimo/_server/api/endpoints/export.py b/marimo/_server/api/endpoints/export.py
index a941b759fe..b59bcac8f7 100644
--- a/marimo/_server/api/endpoints/export.py
+++ b/marimo/_server/api/endpoints/export.py
@@ -24,6 +24,7 @@ from marimo._server.models.export import (
ExportAsHTMLRequest,
ExportAsMarkdownRequest,
ExportAsScriptRequest,
+ UpdateCellOutputsRequest,
)
from marimo._server.models.models import SuccessResponse
from marimo._server.router import APIRouter
@@ -416,3 +417,38 @@ async def auto_export_as_ipynb(
content=asdict(SuccessResponse()),
background=BackgroundTask(_background_export),
)
+
+
[email protected]("/update_cell_outputs")
+@requires("edit")
+async def update_cell_outputs(
+ *, request: Request
+) -> JSONResponse | PlainTextResponse:
+ """
+ parameters:
+ - in: header
+ name: Marimo-Session-Id
+ schema:
+ type: string
+ required: true
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/UpdateCellOutputsRequest"
+ responses:
+ 200:
+ description: Update the cell outputs
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/SuccessResponse"
+ 400:
+ description: File must be saved before downloading
+ """
+ app_state = AppState(request)
+ body = await parse_request(request, cls=UpdateCellOutputsRequest)
+ session = app_state.require_current_session()
+ session.session_view.update_cell_outputs(body.cell_ids_to_output)
+
+ return JSONResponse(content=asdict(SuccessResponse()))
diff --git a/marimo/_server/models/export.py b/marimo/_server/models/export.py
index 0ac66e85e1..33d23bb507 100644
--- a/marimo/_server/models/export.py
+++ b/marimo/_server/models/export.py
@@ -5,6 +5,9 @@ from typing import Optional
import msgspec
+from marimo._messaging.mimetypes import MimeBundleTuple
+from marimo._types.ids import CellId_t
+
class ExportAsHTMLRequest(msgspec.Struct, rename="camel"):
download: bool
@@ -23,3 +26,7 @@ class ExportAsIPYNBRequest(msgspec.Struct, rename="camel"):
class ExportAsMarkdownRequest(msgspec.Struct, rename="camel"):
download: bool
+
+
+class UpdateCellOutputsRequest(msgspec.Struct, rename="camel"):
+ cell_ids_to_output: dict[CellId_t, MimeBundleTuple]
diff --git a/marimo/_session/state/session_view.py b/marimo/_session/state/session_view.py
index 6c9eb1f630..084e79284f 100644
--- a/marimo/_session/state/session_view.py
+++ b/marimo/_session/state/session_view.py
@@ -3,10 +3,12 @@ from __future__ import annotations
import time
from dataclasses import dataclass
-from typing import Any, Literal, Optional
+from typing import Any, Literal, Optional, cast
+from marimo import _loggers
from marimo._data.models import DataSourceConnection, DataTable
from marimo._messaging.cell_output import CellChannel, CellOutput
+from marimo._messaging.mimetypes import KnownMimeType, MimeBundleTuple
from marimo._messaging.notification import (
CellNotification,
DatasetsNotification,
@@ -42,7 +44,10 @@ from marimo._sql.engines.duckdb import INTERNAL_DUCKDB_ENGINE
from marimo._types.ids import CellId_t, WidgetModelId
from marimo._utils.lists import as_list
+LOGGER = _loggers.marimo_logger()
+
ExportType = Literal["html", "md", "ipynb", "session"]
+MIMEBUNDLE_TYPE: KnownMimeType = "application/vnd.marimo+mimebundle"
@dataclass
@@ -352,6 +357,54 @@ class SessionView:
outputs[cell_id] = as_list(cell_notif.console)
return outputs
+ def update_cell_outputs(
+ self, cell_id_to_output: dict[CellId_t, MimeBundleTuple]
+ ) -> None:
+ self._touch() # Mark all auto-export states as stale
+
+ for cell_id, output in cell_id_to_output.items():
+ cell_notif = self.cell_notifications.get(cell_id)
+ if cell_notif is None:
+ LOGGER.warning(f"Cell {cell_id} not found in session view")
+ continue
+
+ mimetype, data = output
+ new_mimebundle = {mimetype: data}
+
+ if cell_notif.output is None:
+ cell_notif.output = CellOutput(
+ channel=CellChannel.OUTPUT, mimetype=mimetype, data=data
+ )
+ elif isinstance(cell_notif.output.data, list):
+ LOGGER.debug(
+ "Skipping list of errors output, should not have rich elements"
+ )
+ continue
+ elif cell_notif.output.mimetype == MIMEBUNDLE_TYPE:
+ if not isinstance(cell_notif.output.data, dict):
+ LOGGER.warning(
+ "Existing output is a mimebundle for cell %s, but data is not a dict (type=%s)",
+ cell_id,
+ type(cell_notif.output.data).__name__,
+ )
+ continue
+ cell_notif.output.data = cast(
+ dict[str, Any],
+ {
+ **cell_notif.output.data,
+ **new_mimebundle,
+ },
+ )
+ else:
+ # We form a new mimebundle including the existing output
+ mimebundle = {
+ cell_notif.output.mimetype: cell_notif.output.data
+ }
+ cell_notif.output.mimetype = MIMEBUNDLE_TYPE
+ cell_notif.output.data = cast(
+ dict[str, Any], {**mimebundle, **new_mimebundle}
+ )
+
def save_execution_time(
self, notification: NotificationMessage, event: Literal["start", "end"]
) -> None:
diff --git a/packages/openapi/api.yaml b/packages/openapi/api.yaml
index 8dd9831347..06132789ae 100644
--- a/packages/openapi/api.yaml
+++ b/packages/openapi/api.yaml
@@ -4041,6 +4041,43 @@ components:
- cellIds
title: UpdateCellIdsRequest
type: object
+ UpdateCellOutputsRequest:
+ properties:
+ cellIdsToOutput:
+ additionalProperties:
+ items: false
+ maxItems: 2
+ minItems: 2
+ prefixItems:
+ - enum:
+ - application/json
+ - application/vnd.jupyter.widget-view+json
+ - application/vnd.marimo+error
+ - application/vnd.marimo+mimebundle
+ - application/vnd.marimo+traceback
+ - application/vnd.vega.v5+json
+ - application/vnd.vegalite.v5+json
+ - image/avif
+ - image/bmp
+ - image/gif
+ - image/jpeg
+ - image/png
+ - image/svg+xml
+ - image/tiff
+ - text/csv
+ - text/html
+ - text/latex
+ - text/markdown
+ - text/plain
+ - video/mp4
+ - video/mpeg
+ - {}
+ type: array
+ type: object
+ required:
+ - cellIdsToOutput
+ title: UpdateCellOutputsRequest
+ type: object
UpdateUIElementCommand:
description: "Update UI element values.\n\n Triggered when users interact\
\ with UI elements (sliders, inputs, dropdowns, etc.).\n Updates element\
@@ -4416,7 +4453,7 @@ components:
type: object
info:
title: marimo API
- version: 0.18.4
+ version: 0.19.2
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
@@ -4810,6 +4847,28 @@ paths:
description: Export the notebook as a script
400:
description: File must be saved before downloading
+ /api/export/update_cell_outputs:
+ post:
+ parameters:
+ - in: header
+ name: Marimo-Session-Id
+ required: true
+ schema:
+ type: string
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/UpdateCellOutputsRequest'
+ responses:
+ 200:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/SuccessResponse'
+ description: Update the cell outputs
+ 400:
+ description: File must be saved before downloading
/api/files/create:
post:
requestBody:
diff --git a/packages/openapi/src/api.ts b/packages/openapi/src/api.ts
index ba9c595937..d8fd7f92e4 100644
--- a/packages/openapi/src/api.ts
+++ b/packages/openapi/src/api.ts
@@ -852,6 +852,54 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/export/update_cell_outputs": {
+ 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"]["UpdateCellOutputsRequest"];
+ };
+ };
+ responses: {
+ /** @description Update the cell outputs */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["SuccessResponse"];
+ };
+ };
+ /** @description File must be saved before downloading */
+ 400: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content?: never;
+ };
+ };
+ };
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/files/create": {
parameters: {
query?: never;
@@ -5191,6 +5239,37 @@ export interface components {
UpdateCellIdsRequest: {
cellIds: string[];
};
+ /** UpdateCellOutputsRequest */
+ UpdateCellOutputsRequest: {
+ cellIdsToOutput: {
+ [key: string]: [
+ (
+ | "application/json"
+ | "application/vnd.jupyter.widget-view+json"
+ | "application/vnd.marimo+error"
+ | "application/vnd.marimo+mimebundle"
+ | "application/vnd.marimo+traceback"
+ | "application/vnd.vega.v5+json"
+ | "application/vnd.vegalite.v5+json"
+ | "image/avif"
+ | "image/bmp"
+ | "image/gif"
+ | "image/jpeg"
+ | "image/png"
+ | "image/svg+xml"
+ | "image/tiff"
+ | "text/csv"
+ | "text/html"
+ | "text/latex"
+ | "text/markdown"
+ | "text/plain"
+ | "video/mp4"
+ | "video/mpeg"
+ ),
+ unknown,
+ ];
+ };
+ };
/**
* UpdateUIElementCommand
* @description Update UI element values.
diff --git a/tests/_server/api/endpoints/test_export.py b/tests/_server/api/endpoints/test_export.py
index 371ef7ea78..4142adc79d 100644
--- a/tests/_server/api/endpoints/test_export.py
+++ b/tests/_server/api/endpoints/test_export.py
@@ -621,3 +621,60 @@ def test_export_script_download_edge_case_filenames(
assert response.status_code == 200, f"Failed for filename: {filename}"
assert "Content-Disposition" in response.headers
assert "attachment" in response.headers["Content-Disposition"]
+
+
+@with_session(SESSION_ID)
+def test_update_cell_outputs_new_cell(client: TestClient) -> None:
+ """Test updating cell outputs for a cell with no existing output."""
+ session = get_session_manager(client).get_session(SESSION_ID)
+ assert session
+
+ # Create a cell notification without output
+ cell_id = CellId_t("test_cell")
+ session.session_view.cell_notifications[cell_id] = CellNotification(
+ cell_id=cell_id,
+ output=None,
+ status="idle",
+ )
+
+ response = client.post(
+ "/api/export/update_cell_outputs",
+ headers=HEADERS,
+ json={
+ "cellIdsToOutput": {
+ cell_id: ["image/png", "data:image/png;base64,iVBORw0KGgo="]
+ }
+ },
+ )
+
+ assert response.status_code == 200
+ assert response.json() == {"success": True}
+ assert session.session_view.needs_export("ipynb")
+
+ # Verify output was created
+ cell_notification = session.session_view.cell_notifications[cell_id]
+ assert cell_notification.output is not None
+ assert cell_notification.output == CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="image/png",
+ data="data:image/png;base64,iVBORw0KGgo=",
+ timestamp=cell_notification.output.timestamp,
+ )
+
+
+@with_session(SESSION_ID)
+def test_update_cell_outputs_missing_cell(client: TestClient) -> None:
+ """Test updating cell outputs for non-existent cell logs warning."""
+ response = client.post(
+ "/api/export/update_cell_outputs",
+ headers=HEADERS,
+ json={
+ "cellIdsToOutput": {
+ "nonexistent_cell": ["image/png", "data:image/png;base64,test"]
+ }
+ },
+ )
+
+ # Should succeed but log a warning
+ assert response.status_code == 200
+ assert response.json() == {"success": True}
diff --git a/tests/_session/state/test_session_view.py b/tests/_session/state/test_session_view.py
index 5e4e35e321..b32de6dd55 100644
--- a/tests/_session/state/test_session_view.py
+++ b/tests/_session/state/test_session_view.py
@@ -13,6 +13,7 @@ from marimo._data.models import (
Schema,
)
from marimo._messaging.cell_output import CellChannel, CellOutput
+from marimo._messaging.errors import UnknownError
from marimo._messaging.msgspec_encoder import asdict as serialize
from marimo._messaging.notification import (
CellNotification,
@@ -1522,3 +1523,173 @@ def test_session_view_package_logs_empty_content(
assert "empty_logs" in session_view.package_logs
assert session_view.package_logs["empty_logs"] == ""
+
+
+class TestUpdateCellOutputs:
+ """Tests for SessionView.update_cell_outputs method."""
+
+ def test_creates_new_output_when_none(self) -> None:
+ """When existing output is None, creates a new CellOutput."""
+ session_view = SessionView()
+ cell_id = CellId_t("cell1")
+ session_view.cell_notifications[cell_id] = CellNotification(
+ cell_id=cell_id, output=None, status="idle"
+ )
+
+ session_view.update_cell_outputs(
+ {cell_id: ("image/png", "base64_data")}
+ )
+
+ output = session_view.cell_notifications[cell_id].output
+ assert output is not None
+ assert output.channel == CellChannel.OUTPUT
+ assert output.mimetype == "image/png"
+ assert output.data == "base64_data"
+
+ def test_skips_error_output(self) -> None:
+ """When existing output data is a list (errors), skips update."""
+ session_view = SessionView()
+ cell_id = CellId_t("cell1")
+ error = UnknownError(msg="Something went wrong")
+ error_output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+error",
+ data=[error],
+ )
+ session_view.cell_notifications[cell_id] = CellNotification(
+ cell_id=cell_id, output=error_output, status="idle"
+ )
+
+ session_view.update_cell_outputs(
+ {cell_id: ("image/png", "base64_data")}
+ )
+
+ # Output should be unchanged
+ assert session_view.cell_notifications[cell_id].output == error_output
+
+ def test_merges_into_existing_mimebundle(self) -> None:
+ """When existing output is a mimebundle, merges new data into it."""
+ session_view = SessionView()
+ cell_id = CellId_t("cell1")
+ session_view.cell_notifications[cell_id] = CellNotification(
+ cell_id=cell_id,
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data={"text/html": "<div>Chart</div>"},
+ ),
+ status="idle",
+ )
+
+ session_view.update_cell_outputs(
+ {cell_id: ("image/png", "base64_data")}
+ )
+
+ output = session_view.cell_notifications[cell_id].output
+ assert output is not None
+ assert output.channel == CellChannel.OUTPUT
+ assert output.mimetype == "application/vnd.marimo+mimebundle"
+ assert output.data == {
+ "text/html": "<div>Chart</div>",
+ "image/png": "base64_data",
+ }
+
+ def test_converts_string_output_to_mimebundle(self) -> None:
+ """When existing output is a string, converts to mimebundle."""
+ session_view = SessionView()
+ cell_id = CellId_t("cell1")
+ session_view.cell_notifications[cell_id] = CellNotification(
+ cell_id=cell_id,
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="text/html",
+ data="<div>Original</div>",
+ ),
+ status="idle",
+ )
+
+ session_view.update_cell_outputs(
+ {cell_id: ("image/png", "base64_data")}
+ )
+
+ output = session_view.cell_notifications[cell_id].output
+ assert output is not None
+ assert output.mimetype == "application/vnd.marimo+mimebundle"
+ assert output.data == {
+ "text/html": "<div>Original</div>",
+ "image/png": "base64_data",
+ }
+
+ def test_overwrites_same_mimetype(self) -> None:
+ """When merging same mimetype, new data overwrites old."""
+ session_view = SessionView()
+ cell_id = CellId_t("cell1")
+ session_view.cell_notifications[cell_id] = CellNotification(
+ cell_id=cell_id,
+ output=CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data={"text/html": "<div>HTML</div>", "image/png": "old_data"},
+ ),
+ status="idle",
+ )
+
+ session_view.update_cell_outputs({cell_id: ("image/png", "new_data")})
+
+ output = session_view.cell_notifications[cell_id].output
+ assert output is not None
+ assert output.data == {
+ "text/html": "<div>HTML</div>",
+ "image/png": "new_data",
+ }
+
+ def test_skips_missing_cell(self) -> None:
+ """When cell doesn't exist, logs warning and continues."""
+ session_view = SessionView()
+
+ # Should not raise
+ session_view.update_cell_outputs(
+ {CellId_t("missing"): ("image/png", "data")}
+ )
+
+ def test_marks_exports_stale(self) -> None:
+ """Calling update_cell_outputs marks all exports as stale."""
+ session_view = SessionView()
+ cell_id = CellId_t("cell1")
+ session_view.cell_notifications[cell_id] = CellNotification(
+ cell_id=cell_id, output=None, status="idle"
+ )
+
+ # Mark exports as done
+ session_view.mark_auto_export_html()
+ session_view.mark_auto_export_ipynb()
+ assert not session_view.needs_export("html")
+ assert not session_view.needs_export("ipynb")
+
+ session_view.update_cell_outputs({cell_id: ("image/png", "data")})
+
+ # Should be stale now
+ assert session_view.needs_export("html")
+ assert session_view.needs_export("ipynb")
+
+ def test_skips_malformed_mimebundle(self) -> None:
+ """When mimetype is mimebundle but data is not a dict, skips."""
+ session_view = SessionView()
+ cell_id = CellId_t("cell1")
+ malformed_output = CellOutput(
+ channel=CellChannel.OUTPUT,
+ mimetype="application/vnd.marimo+mimebundle",
+ data="not a dict",
+ )
+ session_view.cell_notifications[cell_id] = CellNotification(
+ cell_id=cell_id, output=malformed_output, status="idle"
+ )
+
+ session_view.update_cell_outputs(
+ {cell_id: ("image/png", "base64_data")}
+ )
+
+ # Output should be unchanged
+ assert (
+ session_view.cell_notifications[cell_id].output == malformed_output
+ )