diff --git a/frontend/src/__mocks__/executions.ts b/frontend/src/__mocks__/executions.ts
index 4446715d58d..94bdfd92d69 100644
--- a/frontend/src/__mocks__/executions.ts
+++ b/frontend/src/__mocks__/executions.ts
@@ -323,7 +323,7 @@ export const MockExecutions = {
} satisfies NotebookReplica;
store.set(activeNotebookReplicaAtom, replica);
// Selector tests share current inputs; frame scheduling is tested separately.
- store.set(activeNotebookFrameAtom, replica);
+ store.set(activeNotebookFrameAtom, { ...replica, flush: () => undefined });
return replica;
},
};
diff --git a/frontend/src/components/editor/Output.tsx b/frontend/src/components/editor/Output.tsx
index ed6750391fb..baf817a777b 100644
--- a/frontend/src/components/editor/Output.tsx
+++ b/frontend/src/components/editor/Output.tsx
@@ -1,5 +1,5 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import React, { memo, Suspense, useMemo, useRef } from "react";
+import React, { memo, useMemo, useRef } from "react";
import { type CellId, CellOutputId } from "@/core/cells/ids";
import type { CellOutput } from "@/core/executions";
import type { OutputMessage } from "@/core/kernel/messages";
@@ -21,7 +21,6 @@ import {
ExpandIcon,
ShrinkIcon,
} from "lucide-react";
-import { tooltipHandler } from "@/components/charts/tooltip";
import { useExpandedOutput } from "@/core/cells/outputs";
import { viewStateAtom } from "@/core/mode";
import { useEventListener } from "@/hooks/useEventListener";
@@ -30,15 +29,12 @@ import { useOverflowDetection } from "@/hooks/useOverflowDetection";
import { renderHTML } from "@/plugins/core/RenderHTML";
import { Banner } from "@/plugins/impl/common/error-banner";
import type { TopLevelFacetedUnitSpec } from "@/plugins/impl/data-explorer/queries/types";
-import { getContainerWidth } from "@/plugins/impl/vega/utils";
-import { useTheme } from "@/theme/useTheme";
import { Events } from "@/utils/events";
import { invariant } from "@/utils/invariant";
import { Logger } from "@/utils/Logger";
import { processMimeBundle } from "@/utils/mime-types";
import { Objects } from "@/utils/objects";
-import { LazyVegaEmbed } from "../charts/lazy";
-import { ChartLoadingState } from "../data-table/charts/components/chart-states";
+import { VegaOutput } from "./output/VegaOutput";
import { Button } from "../ui/button";
import { useIsFullScreen } from "../ui/fullscreen";
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
@@ -85,7 +81,6 @@ export const OutputRenderer: React.FC<{
metadata,
renderFallback,
} = props;
- const { theme } = useTheme();
// Memoize parsing the json data
const parsedJsonData = useMemo(() => {
@@ -214,20 +209,7 @@ export const OutputRenderer: React.FC<{
case "application/vnd.vega.v5+json":
case "application/vnd.vegalite.v6+json":
case "application/vnd.vega.v6+json":
- return (
- }>
-
-
- );
+ return ;
case "application/vnd.marimo+mimebundle":
return (
();
+ return (
+ }>
+ setRendered(embed)}
+ data-marimo-vega-ready={rendered === embed || undefined}
+ data-container-width={getContainerWidth(spec)}
+ />
+
+ );
+}
diff --git a/frontend/src/core/executions/__tests__/atoms.test.ts b/frontend/src/core/executions/__tests__/atoms.test.ts
index b457953fb7b..fdb953dcb7a 100644
--- a/frontend/src/core/executions/__tests__/atoms.test.ts
+++ b/frontend/src/core/executions/__tests__/atoms.test.ts
@@ -19,7 +19,6 @@ import {
cellExecutionInputsAtom,
cellExecutionAtom,
cellOutputAtom,
- cellOutputsAtom,
scratchOutputAtom,
cellOutputInputsAtom,
cellOutlineAtom,
@@ -264,7 +263,6 @@ it.each([25, 500])(
}
onTestFinished(() => releaseCellOutputAtoms(id));
}
- onTestFinished(store.sub(cellOutputsAtom, () => undefined));
onTestFinished(store.sub(scratchOutputAtom, () => undefined));
scratchView.mockClear();
executionView.mockClear();
diff --git a/frontend/src/core/executions/atoms.ts b/frontend/src/core/executions/atoms.ts
index 8e1e6ca9ac5..03a586bb4ef 100644
--- a/frontend/src/core/executions/atoms.ts
+++ b/frontend/src/core/executions/atoms.ts
@@ -13,11 +13,10 @@ import {
ConnectionState,
type Executions,
type NotebookReplica,
- type ReplicaFrame,
+ type FrameSource,
type Results,
} from "@/core/notebook/replica";
import { atomWithSelectedInputs } from "@/core/state/atom-with-selected-inputs";
-import { arrayShallowEquals } from "@/utils/arrays";
import {
activeNotebookReplicaAtom,
activeNotebookFrameAtom,
@@ -26,7 +25,7 @@ import { type CellFreshnessInputs, freshnessOf } from "./freshness";
import {
type CellOutputInputs,
type ClearedOutput,
- type CellOutput,
+ cellOutputsView,
resultOutput,
shownCellExecution,
shownExecution,
@@ -112,7 +111,7 @@ function current(marks: Marks, shown: ShownNotebook | null, empty: T): T {
: empty;
}
-type ReplicaSource = Atom;
+type ReplicaSource = Atom;
function createShownNotebookAtom(source: ReplicaSource) {
return atom((get): ShownNotebook | null => {
@@ -250,41 +249,39 @@ const displayedNotebookAtom = atom((get): ShownNotebook | null => {
};
});
-/** What every cell's output derives from. Pair with `cellOutputView`. */
-export const cellOutputInputsAtom = atom((get): CellOutputInputs => {
- const frame = get(activeNotebookFrameAtom);
- return {
- executions: frame === null ? NO_EXECUTIONS : get(frame.executionsAtom),
- results: frame === null ? NO_RESULTS : get(frame.resultsAtom),
- cleared: current(
- get(clearedOutputsAtom),
- get(displayedNotebookAtom),
- NO_CLEARED,
- ),
- cells:
- frame === null ? NO_CELLS : (get(frame.documentAtom)?.cells ?? NO_CELLS),
- };
-});
+function createOutputInputsAtom(
+ source: ReplicaSource,
+ notebookAtom: Atom,
+) {
+ return atom((get): CellOutputInputs => {
+ const state = get(source);
+ return {
+ executions: state === null ? NO_EXECUTIONS : get(state.executionsAtom),
+ results: state === null ? NO_RESULTS : get(state.resultsAtom),
+ cleared: current(get(clearedOutputsAtom), get(notebookAtom), NO_CLEARED),
+ cells:
+ state === null
+ ? NO_CELLS
+ : (get(state.documentAtom)?.cells ?? NO_CELLS),
+ };
+ });
+}
-/** What every cell shows, by cell id. Pair with `cellOutputAtom` for one cell. */
-const outputCellIdsAtom = selectAtom(
- cellOutputInputsAtom,
- (inputs) => [
- ...new Set([...inputs.results.keys(), ...inputs.executions.latest.keys()]),
- ],
- arrayShallowEquals,
+/** What each cell shows in the last published frame. */
+export const cellOutputInputsAtom = createOutputInputsAtom(
+ activeNotebookFrameAtom,
+ displayedNotebookAtom,
);
-export const cellOutputsAtom = atom((get) => {
- const outputs = new Map();
- for (const id of get(outputCellIdsAtom)) {
- const output = get(cellOutputAtom(id));
- if (output !== null) {
- outputs.set(id, output);
- }
- }
- return outputs;
-});
+const immediateOutputInputsAtom = createOutputInputsAtom(
+ activeNotebookReplicaAtom,
+ shownNotebookAtom,
+);
+
+/** Read at export time, including output received since the last display frame. */
+export const cellOutputsAtom = atom((get) =>
+ cellOutputsView(get(immediateOutputInputsAtom)),
+);
function latestFor(executions: Executions, id: Protocol.CellId) {
const latest = executions.latest.get(id);
diff --git a/frontend/src/core/export/__tests__/output-snapshot.test.tsx b/frontend/src/core/export/__tests__/output-snapshot.test.tsx
new file mode 100644
index 00000000000..bc2199a2b6e
--- /dev/null
+++ b/frontend/src/core/export/__tests__/output-snapshot.test.tsx
@@ -0,0 +1,240 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { act, fireEvent, renderHook, waitFor } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import type { ComponentType, ReactNode } from "react";
+import { describe, expect, it, onTestFinished, vi } from "vitest";
+import { mockAnimationFrames } from "@/__mocks__/animation-frames";
+import { MockModules } from "@/__mocks__/common";
+import { MockExecutions } from "@/__mocks__/executions";
+import { MockRequestClient } from "@/__mocks__/requests";
+import { cellId } from "@/__tests__/branded";
+import {
+ DEFAULT_EXPORT_OPTIONS,
+ exportOptionsAtom,
+} from "@/components/editor/actions/export-dialog/state";
+import { useExportDialog } from "@/components/editor/actions/export-dialog/use-export-dialog";
+import { OutputRenderer } from "@/components/editor/Output";
+import { CellOutputId } from "@/core/cells/ids";
+import { releaseCellOutputAtoms, useCellOutput } from "@/core/executions";
+import { connectionAtom } from "@/core/network/connection";
+import { requestClientAtom } from "@/core/network/requests";
+import { document as notebookDocument } from "@/core/notebook/document/__tests__/fixtures";
+import { createReplicaFrame } from "@/core/notebook/replica";
+import { executions } from "@/core/notebook/replica/resources/executions";
+import { filenameAtom } from "@/core/saving/file-state";
+import { activeNotebookFrameAtom } from "@/core/session/active-notebook";
+import { ConnectionState } from "@/core/session/types";
+import { Deferred } from "@/utils/Deferred";
+import { ProgressState } from "@/utils/progress";
+import { toPng } from "@/utils/html-to-image";
+import { captureTracker, useAutoExport, useEnrichCellOutputs } from "../hooks";
+
+interface ChartProps {
+ onEmbed: () => void;
+ "data-marimo-vega-ready"?: boolean;
+}
+const chartModule = new Deferred<{ default: ComponentType }>();
+vi.mock("@/components/charts/lazy", async () => {
+ const { lazy } = await import("react");
+ return { LazyVegaEmbed: lazy(() => chartModule.promise) };
+});
+
+vi.mock(
+ "@/components/ui/use-toast",
+ () => MockModules.toastWithControls().mock,
+);
+
+vi.mock("@/utils/html-to-image", () => ({
+ toPng: vi.fn(),
+}));
+
+vi.mock("@/utils/download", async (importOriginal) => ({
+ ...(await importOriginal()),
+ downloadExportedFile: vi.fn(),
+}));
+
+const CELL_ID = cellId("c1");
+const OUTPUT_ID = CellOutputId.create(CELL_ID);
+const OLD_OUTPUT = "previous output";
+const NEW_OUTPUT = "latest output";
+
+function png(text: string) {
+ return `data:image/png;base64,${btoa(text)}`;
+}
+
+function Output() {
+ const output = useCellOutput(CELL_ID);
+ return (
+
+ {output && }
+
+ );
+}
+
+interface ExportTrigger {
+ isAvailable: boolean;
+ start: () => void;
+}
+
+function useManualExport(): ExportTrigger {
+ const dialog = useExportDialog({ initialFormat: "ipynb", onClose: vi.fn() });
+ return {
+ isAvailable: dialog.selected.status.available,
+ start: dialog.submit,
+ };
+}
+
+function useAutomaticExport(): ExportTrigger {
+ useAutoExport();
+ return {
+ isAvailable: true,
+ start: () => fireEvent(document, new Event("visibilitychange")),
+ };
+}
+
+describe("IPYNB output snapshots", () => {
+ it("retries the same chart after its module and view finish loading", async () => {
+ const store = createStore();
+ const chart = vi.fn((props: ChartProps) => (
+
+ rendered chart
+
+ ));
+ captureTracker.reset();
+ onTestFinished(() => {
+ releaseCellOutputAtoms(CELL_ID);
+ captureTracker.reset();
+ });
+ const showChart = (mark: string) =>
+ MockExecutions.seed(store, [
+ MockExecutions.shown(CELL_ID, {
+ mimetype: "application/vnd.vegalite.v5+json",
+ data: JSON.stringify({ mark }),
+ }),
+ ]);
+ showChart("point");
+ vi.mocked(toPng)
+ .mockClear()
+ .mockImplementation(async (node) => png(node.textContent ?? ""));
+ const { result } = renderHook(useEnrichCellOutputs, {
+ wrapper: ({ children }: { children: ReactNode }) => (
+
+
+ {children}
+
+ ),
+ });
+ const capture = () =>
+ result.current({ progress: ProgressState.indeterminate() });
+ expect(document.getElementById(OUTPUT_ID)).toHaveTextContent(
+ "Loading chart",
+ );
+ expect(await capture()).toEqual({});
+ await act(async () => chartModule.resolve({ default: chart }));
+ expect(await capture()).toEqual({});
+ expect(toPng).not.toHaveBeenCalled();
+ act(() => chart.mock.lastCall![0].onEmbed());
+ expect(await capture()).toEqual({
+ [CELL_ID]: ["image/png", png("rendered chart")],
+ });
+ expect(await capture()).toEqual({});
+ expect(toPng).toHaveBeenCalledOnce();
+
+ act(() => {
+ showChart("bar");
+ });
+ expect(await capture()).toEqual({});
+ expect(toPng).toHaveBeenCalledOnce();
+ });
+
+ it.each([
+ { mode: "manual", useExport: useManualExport, request: "exportAsIPYNB" },
+ {
+ mode: "automatic",
+ useExport: useAutomaticExport,
+ request: "autoExportAsIPYNB",
+ },
+ ] as const)(
+ "uploads the latest browser output before $mode export while a display frame is pending",
+ async ({ useExport, request }) => {
+ captureTracker.reset();
+ const advanceFrame = mockAnimationFrames();
+ const lifetime = new AbortController();
+ onTestFinished(() => {
+ lifetime.abort();
+ releaseCellOutputAtoms(CELL_ID);
+ captureTracker.reset();
+ });
+ const store = createStore();
+ const notebook = notebookDocument();
+ notebook.revision.app_config = { auto_download: ["ipynb"] };
+ const running = MockExecutions.running(CELL_ID);
+ const previous = MockExecutions.output(running, {
+ mimetype: "text/plain",
+ data: OLD_OUTPUT,
+ });
+ const replica = MockExecutions.seed(
+ store,
+ [running, previous],
+ null,
+ notebook,
+ );
+ store.set(
+ activeNotebookFrameAtom,
+ createReplicaFrame(store, replica, { signal: lifetime.signal }),
+ );
+ store.set(connectionAtom, { state: ConnectionState.OPEN });
+ store.set(filenameAtom, "notebook.py");
+ store.set(exportOptionsAtom, {
+ ...DEFAULT_EXPORT_OPTIONS,
+ ipynb: { ...DEFAULT_EXPORT_OPTIONS.ipynb, includeOutputs: true },
+ });
+ const requests = MockRequestClient.create();
+ store.set(requestClientAtom, requests);
+ const uploaded = new Deferred();
+ requests.updateCellOutputs.mockReturnValueOnce(uploaded.promise);
+ vi.mocked(toPng).mockImplementation(async (node) =>
+ png(node.textContent ?? ""),
+ );
+
+ const { result } = renderHook(useExport, {
+ wrapper: ({ children }: { children: ReactNode }) => (
+
+
+ {children}
+
+ ),
+ });
+ await waitFor(() => expect(result.current.isAvailable).toBe(true));
+
+ const output = MockExecutions.output(running, {
+ mimetype: "text/html",
+ data: `${NEW_OUTPUT}`,
+ });
+ act(() => {
+ store.set(replica.executionsAtom, (state) =>
+ executions.on.output!(
+ state,
+ { event: "output", id: "2", data: { output } },
+ { phase: "live" },
+ ),
+ );
+ });
+ expect(document.getElementById(OUTPUT_ID)).toHaveTextContent(OLD_OUTPUT);
+
+ await act(async () => {
+ result.current.start();
+ });
+ expect(requests.updateCellOutputs).toHaveBeenCalledExactlyOnceWith({
+ cellIdsToOutput: { [CELL_ID]: ["image/png", png(NEW_OUTPUT)] },
+ });
+ expect(requests[request]).not.toHaveBeenCalled();
+
+ await act(async () => uploaded.resolve(null));
+ expect(requests[request]).toHaveBeenCalledOnce();
+ act(advanceFrame);
+ expect(document.getElementById(OUTPUT_ID)).toHaveTextContent(NEW_OUTPUT);
+ },
+ );
+});
diff --git a/frontend/src/core/export/__tests__/output-subscription.test.tsx b/frontend/src/core/export/__tests__/output-subscription.test.tsx
new file mode 100644
index 00000000000..c4506dac42f
--- /dev/null
+++ b/frontend/src/core/export/__tests__/output-subscription.test.tsx
@@ -0,0 +1,79 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { act, render } from "@testing-library/react";
+import { createStore, Provider } from "jotai";
+import { Profiler } from "react";
+import { describe, expect, it, onTestFinished, vi } from "vitest";
+import { MockExecutions } from "@/__mocks__/executions";
+import { MockRequestClient } from "@/__mocks__/requests";
+import { cellId } from "@/__tests__/branded";
+import { createRenderTracker } from "@/__tests__/render-tracker";
+import { pageAppConfigAtom } from "@/core/config/config";
+import { cellOutputsAtom, releaseCellOutputAtoms } from "@/core/executions";
+import { connectionAtom } from "@/core/network/connection";
+import { requestClientAtom } from "@/core/network/requests";
+import { ConnectionState } from "@/core/session/types";
+import { invariant } from "@/utils/invariant";
+import { useAutoExport } from "../hooks";
+
+function AutoExportOwner() {
+ useAutoExport();
+ return null;
+}
+
+describe.each([2, 250])("auto-export with %i cells", (size) => {
+ it("does no export work when a plain-text output changes", () => {
+ const store = createStore();
+ const ids = Array.from({ length: size }, (_, i) => cellId(`cell-${i}`));
+ const replica = MockExecutions.seed(
+ store,
+ ids.map((id) =>
+ MockExecutions.shown(id, { mimetype: "text/plain", data: id }),
+ ),
+ );
+ store.set(requestClientAtom, MockRequestClient.create());
+ store.set(connectionAtom, { state: ConnectionState.OPEN });
+ store.set(pageAppConfigAtom, { auto_download: [] });
+
+ const readOutputs = vi.spyOn(cellOutputsAtom, "read");
+ const renders = createRenderTracker();
+ const { unmount } = render(
+
+
+
+
+ ,
+ );
+ onTestFinished(() => {
+ unmount();
+ readOutputs.mockRestore();
+ ids.forEach(releaseCellOutputAtoms);
+ });
+
+ expect(renders.counts()["auto-export"]).toBeGreaterThan(0);
+ expect.soft(readOutputs).toHaveBeenCalledTimes(0);
+ readOutputs.mockClear();
+ renders.reset();
+
+ const [changedCell] = ids;
+ act(() => {
+ store.set(replica.resultsAtom, (results) => {
+ const before = results.get(changedCell);
+ invariant(before, "The changed cell has a result");
+ return new Map(results).set(changedCell, {
+ ...before,
+ output: MockExecutions.output(before.record, {
+ mimetype: "text/plain",
+ data: "updated",
+ }),
+ outputVersion: before.outputVersion + 1,
+ });
+ });
+ });
+
+ expect({
+ aggregateReads: readOutputs.mock.calls.length,
+ commits: renders.counts(),
+ }).toEqual({ aggregateReads: 0, commits: {} });
+ });
+});
diff --git a/frontend/src/core/export/hooks.ts b/frontend/src/core/export/hooks.ts
index 300852008a3..38ddc4f5bcb 100644
--- a/frontend/src/core/export/hooks.ts
+++ b/frontend/src/core/export/hooks.ts
@@ -1,5 +1,8 @@
/* Copyright 2026 Marimo. All rights reserved. */
-import { useAtomValue } from "jotai";
+import { useAtomValue, useStore } from "jotai";
+// Screenshot capture reads the DOM immediately after publishing a pending frame.
+// react-doctor-disable-next-line react-doctor/no-flush-sync
+import { flushSync } from "react-dom";
import type { MimeType } from "@/components/editor/Output";
import { toast } from "@/components/ui/use-toast";
import { appConfigAtom } from "@/core/config/config";
@@ -9,14 +12,15 @@ import { getImageDataUrlForCell } from "@/utils/download";
import { Logger } from "@/utils/Logger";
import { Objects } from "@/utils/objects";
import { ProgressState } from "@/utils/progress";
-import type { CellId } from "../cells/ids";
-import { cellOutputsAtom } from "../executions";
+import { type CellId, CellOutputId } from "../cells/ids";
+import { type CellOutput, cellOutputsAtom } from "../executions";
import { getExportLayout } from "./layout";
import { connectionAtom } from "../network/connection";
import { useRequestClient } from "../network/requests";
import type { UpdateCellOutputsRequest } from "../network/types";
import { VirtualFileTracker } from "../static/virtual-file-tracker";
import { ConnectionState } from "../session/types";
+import { activeNotebookFrameAtom } from "../session/active-notebook";
const DELAY = 5000; // 5 seconds;
@@ -91,9 +95,7 @@ export function useAutoExport() {
);
}
-// MIME types to capture screenshots for
-const MIME_TYPES_TO_CAPTURE_SCREENSHOTS = new Set([
- "text/html",
+const VEGA_MIME_TYPES = new Set([
"application/vnd.vegalite.v5+json",
"application/vnd.vega.v5+json",
"application/vnd.vegalite.v6+json",
@@ -122,17 +124,18 @@ interface UseEnrichCellOutputsOptions {
export function useEnrichCellOutputs(): (
opts: UseEnrichCellOutputsOptions,
) => Promise {
- const outputs = useAtomValue(cellOutputsAtom);
+ const store = useStore();
return async (
opts: UseEnrichCellOutputsOptions,
): Promise => {
const { progress } = opts;
+ const outputs = store.get(cellOutputsAtom);
// Prune tracked state for cells that no longer show anything
captureTracker.prune(new Set(outputs.keys()));
- const cellsToCaptureScreenshot: [CellId, unknown][] = [];
+ const cellsToCaptureScreenshot: [CellId, CellOutput][] = [];
const inFlightWaiters: {
cellId: CellId;
promise: Promise;
@@ -141,11 +144,12 @@ export function useEnrichCellOutputs(): (
for (const [cellId, output] of outputs) {
const outputData = output.data;
if (
- MIME_TYPES_TO_CAPTURE_SCREENSHOTS.has(output.mimetype) &&
+ (output.mimetype === "text/html" ||
+ VEGA_MIME_TYPES.has(output.mimetype)) &&
outputData
) {
if (captureTracker.needsCapture(cellId, outputData)) {
- cellsToCaptureScreenshot.push([cellId, outputData]);
+ cellsToCaptureScreenshot.push([cellId, output]);
} else {
// If already in-flight with the same value, await its result
const promise = captureTracker.waitForInFlight(cellId, outputData);
@@ -160,17 +164,29 @@ export function useEnrichCellOutputs(): (
return {};
}
- // Start the progress bar for new captures only
if (cellsToCaptureScreenshot.length > 0) {
+ const frame = store.get(activeNotebookFrameAtom);
+ if (frame) {
+ flushSync(frame.flush);
+ }
progress.addTotal(cellsToCaptureScreenshot.length);
}
// Capture screenshots — each key gets its own AbortSignal so
// aborting one cell does not affect the others.
const results: ScreenshotResults = {};
- for (const [cellId, outputData] of cellsToCaptureScreenshot) {
- const handle = captureTracker.startCapture(cellId, outputData);
+ for (const [cellId, output] of cellsToCaptureScreenshot) {
+ const handle = captureTracker.startCapture(cellId, output.data);
try {
+ if (
+ VEGA_MIME_TYPES.has(output.mimetype) &&
+ !document
+ .getElementById(CellOutputId.create(cellId))
+ ?.querySelector("[data-marimo-vega-ready]")
+ ) {
+ handle.markFailed();
+ continue;
+ }
const dataUrl = await getImageDataUrlForCell(cellId);
if (handle.signal.aborted) {
continue;
diff --git a/frontend/src/core/notebook/replica/frame.ts b/frontend/src/core/notebook/replica/frame.ts
index 6e617bfd07d..b2a8ac38c09 100644
--- a/frontend/src/core/notebook/replica/frame.ts
+++ b/frontend/src/core/notebook/replica/frame.ts
@@ -4,7 +4,7 @@ import { atom, type createStore } from "jotai/vanilla";
import type { NotebookReplica } from "./replica";
import { oncePerFrame } from "./once-per-frame";
-export type ReplicaFrame = Pick<
+export type FrameSource = Pick<
NotebookReplica,
| "notebookAtom"
| "generationAtom"
@@ -16,10 +16,15 @@ export type ReplicaFrame = Pick<
| "runtimeAtom"
>;
+export interface ReplicaFrame extends FrameSource {
+ /** Publish pending state before an operation reads the rendered notebook. */
+ flush(): void;
+}
+
/** The replica's display atoms, republished together once per frame. */
export function createReplicaFrame(
store: ReturnType,
- replica: ReplicaFrame,
+ replica: FrameSource,
{ signal }: { signal: AbortSignal },
): ReplicaFrame {
const currentAtom = atom((get) => ({
@@ -42,6 +47,7 @@ export function createReplicaFrame(
signal.addEventListener("abort", unsubscribe, { once: true });
}
return {
+ flush: publish.flush,
notebookAtom: atom((get) => get(frameAtom).notebook),
generationAtom: atom((get) => get(frameAtom).generation),
documentAtom: atom((get) => get(frameAtom).document),
diff --git a/frontend/src/core/notebook/replica/index.ts b/frontend/src/core/notebook/replica/index.ts
index 15a55a16018..00ce5005a0f 100644
--- a/frontend/src/core/notebook/replica/index.ts
+++ b/frontend/src/core/notebook/replica/index.ts
@@ -3,7 +3,11 @@
/** Backend-confirmed notebook state, independent of React and transports. */
export type { NotebookBackend } from "./backend";
-export { createReplicaFrame, type ReplicaFrame } from "./frame";
+export {
+ createReplicaFrame,
+ type FrameSource,
+ type ReplicaFrame,
+} from "./frame";
export {
type CloseDecision,
ConnectionClosedReason,
diff --git a/frontend/src/core/notebook/replica/once-per-frame.ts b/frontend/src/core/notebook/replica/once-per-frame.ts
index d0549171c91..9f68e5189bd 100644
--- a/frontend/src/core/notebook/replica/once-per-frame.ts
+++ b/frontend/src/core/notebook/replica/once-per-frame.ts
@@ -4,7 +4,7 @@
export function oncePerFrame(
publish: () => void,
{ signal }: { signal: AbortSignal },
-): () => void {
+) {
let generation = 0;
let cancelScheduled: (() => void) | undefined;
@@ -36,7 +36,7 @@ export function oncePerFrame(
);
}
- return () => {
+ function schedule() {
if (signal.aborted || cancelScheduled) {
return;
}
@@ -56,5 +56,6 @@ export function oncePerFrame(
const frame = requestAnimationFrame(callback);
cancelScheduled = () => cancelAnimationFrame(frame);
}
- };
+ }
+ return Object.assign(schedule, { flush: run });
}