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.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
feat(frontend): introduce progressive loading for wasm (#10044)
Myles Scolnick72bda05d539f
diff --git a/frontend/src/components/editor/chrome/wrapper/footer-items/pyodide-status.tsx b/frontend/src/components/editor/chrome/wrapper/footer-items/pyodide-status.tsxindex c6cb9b1c31..1f6933e174 100644--- a/frontend/src/components/editor/chrome/wrapper/footer-items/pyodide-status.tsx+++ b/frontend/src/components/editor/chrome/wrapper/footer-items/pyodide-status.tsx@@ -1,47 +1,17 @@/* Copyright 2026 Marimo. All rights reserved. */-import { useAtomValue } from "jotai";-import { AlertCircleIcon } from "lucide-react";import type React from "react";-import { Spinner } from "@/components/icons/spinner";-import { Tooltip } from "@/components/ui/tooltip";-import { wasmInitializationAtom, wasmInitStatusAtom } from "@/core/wasm/state";+import { RuntimeStatusBadge } from "@/components/lifecycle/RuntimeStatusBadge";import { isWasm } from "@/core/wasm/utils";/**- * Footer indicator that surfaces Pyodide initialization progress. Mirrors- * the "Kernel" indicator but tracks the WASM runtime instead of the server- * connection. Hides itself once Pyodide is ready.+ * Footer indicator that surfaces Pyodide initialization progress. Thin+ * wrapper around `<RuntimeStatusBadge>` so the rest of the footer chrome+ * doesn't need to know about adapters.*/export const PyodideStatus: React.FC = () => {- const status = useAtomValue(wasmInitStatusAtom);- const message = useAtomValue(wasmInitializationAtom);-- if (!isWasm() || status === "ready") {+ if (!isWasm()) {return null;}-- const icon =- status === "error" ? (- <AlertCircleIcon className="w-4 h-4 text-destructive" />- ) : (- <Spinner size="small" />- );-- const tooltip = status === "error" ? "Pyodide failed to initialize" : message;-- return (- <Tooltip- content={<div className="text-sm whitespace-pre-line">{tooltip}</div>}- data-testid="footer-pyodide-status"- >- <div- className="p-1 hover:bg-accent rounded flex items-center gap-1.5 text-xs text-muted-foreground"- data-testid="pyodide-status"- >- {icon}- <span>Pyodide</span>- </div>- </Tooltip>- );+ return <RuntimeStatusBadge />;};diff --git a/frontend/src/components/lifecycle/ProgressiveBoundary.tsx b/frontend/src/components/lifecycle/ProgressiveBoundary.tsxnew file mode 100644index 0000000000..c29a7272b3--- /dev/null+++ b/frontend/src/components/lifecycle/ProgressiveBoundary.tsx@@ -0,0 +1,42 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { type Atom, useAtomValue } from "jotai";+import type React from "react";+import type { PropsWithChildren } from "react";+import { useDelayElapsed } from "@/hooks/useDelayElapsed";++interface Props {+ /** Children render once this atom resolves true. */+ requires: Atom<boolean>;+ fallback?: React.ReactNode;+ /** Suppress the fallback for this many ms; avoids spinner flashes. */+ delay?: number;+}++/**+ * ```tsx+ * <ProgressiveBoundary requires={canPaintAtom} delay={2000} fallback={<Spinner />}>+ * <Editor />+ * </ProgressiveBoundary>+ * ```+ */+export const ProgressiveBoundary: React.FC<PropsWithChildren<Props>> = ({+ requires,+ fallback = null,+ delay = 0,+ children,+}) => {+ const ready = useAtomValue(requires);+ // Key the delay off `ready` so the suppression window re-arms whenever the+ // gate closes again — otherwise a `true → false` flip would show the+ // fallback immediately and reintroduce the flash `delay` is meant to avoid.+ const delayElapsed = useDelayElapsed(ready ? 0 : delay);++ if (ready) {+ return children;+ }+ if (!delayElapsed) {+ return null;+ }+ return fallback;+};diff --git a/frontend/src/components/lifecycle/RuntimeStatusBadge.tsx b/frontend/src/components/lifecycle/RuntimeStatusBadge.tsxnew file mode 100644index 0000000000..7587cdccbb--- /dev/null+++ b/frontend/src/components/lifecycle/RuntimeStatusBadge.tsx@@ -0,0 +1,59 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { useAtomValue } from "jotai";+import { AlertCircleIcon } from "lucide-react";+import type React from "react";+import { Spinner } from "@/components/icons/spinner";+import { Tooltip } from "@/components/ui/tooltip";+import { type AdapterState, runtimeAdapterAtom } from "@/core/runtime/adapter";++/**+ * Footer pill that surfaces the active runtime's connection/initialization+ * status via its adapter. Hides itself once the runtime is ready.+ */+export const RuntimeStatusBadge: React.FC = () => {+ const adapter = useAtomValue(runtimeAdapterAtom);+ const state = useAtomValue(adapter.state);++ if (state.kind === "ready") {+ return null;+ }++ const icon =+ state.kind === "failed" ? (+ <AlertCircleIcon className="w-4 h-4 text-destructive" />+ ) : (+ <Spinner size="small" />+ );++ return (+ <Tooltip+ content={+ <div className="text-sm whitespace-pre-line">+ {tooltipFor(state, adapter.label)}+ </div>+ }+ data-testid="footer-runtime-status"+ >+ <button+ type="button"+ className="p-1 hover:bg-accent rounded flex items-center gap-1.5 text-xs text-muted-foreground"+ data-testid="runtime-status-footer"+ >+ {icon}+ <span>{adapter.label}</span>+ </button>+ </Tooltip>+ );+};++function tooltipFor(state: AdapterState, label: string): string {+ switch (state.kind) {+ case "failed":+ return state.error.message;+ case "connecting":+ return state.progress?.label ?? `${label} starting…`;+ case "ready":+ return `${label} ready`;+ }+}diff --git a/frontend/src/components/lifecycle/__tests__/ProgressiveBoundary.test.tsx b/frontend/src/components/lifecycle/__tests__/ProgressiveBoundary.test.tsxnew file mode 100644index 0000000000..7e9a9bdc61--- /dev/null+++ b/frontend/src/components/lifecycle/__tests__/ProgressiveBoundary.test.tsx@@ -0,0 +1,147 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { act, render, screen } from "@testing-library/react";+import { atom, createStore, Provider } from "jotai";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { ProgressiveBoundary } from "../ProgressiveBoundary";++describe("ProgressiveBoundary", () => {+ let store: ReturnType<typeof createStore>;++ const wrapper = ({ children }: { children: ReactNode }) => (+ <Provider store={store}>{children}</Provider>+ );++ beforeEach(() => {+ vi.useFakeTimers();+ store = createStore();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("renders children once the capability resolves true", () => {+ const capability = atom(true);+ render(+ <ProgressiveBoundary requires={capability}>+ <span>content</span>+ </ProgressiveBoundary>,+ { wrapper },+ );+ expect(screen.getByText("content")).toBeInTheDocument();+ });++ it("blocks children with no fallback when capability is false", () => {+ const capability = atom(false);+ const { container } = render(+ <ProgressiveBoundary requires={capability}>+ <span>content</span>+ </ProgressiveBoundary>,+ { wrapper },+ );+ expect(container).toBeEmptyDOMElement();+ });++ it("renders the fallback when capability is false", () => {+ const capability = atom(false);+ render(+ <ProgressiveBoundary requires={capability} fallback={<span>wait</span>}>+ <span>content</span>+ </ProgressiveBoundary>,+ { wrapper },+ );+ expect(screen.getByText("wait")).toBeInTheDocument();+ expect(screen.queryByText("content")).not.toBeInTheDocument();+ });++ it("renders children once a previously-false capability flips true", () => {+ const capability = atom(false);+ render(+ <ProgressiveBoundary requires={capability} fallback={<span>wait</span>}>+ <span>content</span>+ </ProgressiveBoundary>,+ { wrapper },+ );+ expect(screen.getByText("wait")).toBeInTheDocument();++ act(() => store.set(capability, true));+ expect(screen.getByText("content")).toBeInTheDocument();+ });++ it("reopens the gate when a capability flips back to false", () => {+ const capability = atom(true);+ render(+ <ProgressiveBoundary requires={capability} fallback={<span>wait</span>}>+ <span>content</span>+ </ProgressiveBoundary>,+ { wrapper },+ );+ expect(screen.getByText("content")).toBeInTheDocument();++ act(() => store.set(capability, false));+ expect(screen.queryByText("content")).not.toBeInTheDocument();+ expect(screen.getByText("wait")).toBeInTheDocument();+ });++ it("delays the fallback by `delay` ms", () => {+ const capability = atom(false);+ render(+ <ProgressiveBoundary+ requires={capability}+ delay={2000}+ fallback={<span>wait</span>}+ >+ <span>content</span>+ </ProgressiveBoundary>,+ { wrapper },+ );+ // Before the delay elapses, no fallback.+ expect(screen.queryByText("wait")).not.toBeInTheDocument();++ act(() => vi.advanceTimersByTime(2000));+ expect(screen.getByText("wait")).toBeInTheDocument();+ });++ it("re-arms the delay when the gate closes again", () => {+ const capability = atom(true);+ render(+ <ProgressiveBoundary+ requires={capability}+ delay={2000}+ fallback={<span>wait</span>}+ >+ <span>content</span>+ </ProgressiveBoundary>,+ { wrapper },+ );+ expect(screen.getByText("content")).toBeInTheDocument();++ // Gate closes: fallback should stay suppressed until the delay re-elapses.+ act(() => store.set(capability, false));+ expect(screen.queryByText("wait")).not.toBeInTheDocument();+ expect(screen.queryByText("content")).not.toBeInTheDocument();++ act(() => vi.advanceTimersByTime(2000));+ expect(screen.getByText("wait")).toBeInTheDocument();+ });++ it("skips the fallback entirely if the gate opens before the delay", () => {+ const capability = atom(false);+ render(+ <ProgressiveBoundary+ requires={capability}+ delay={5000}+ fallback={<span>wait</span>}+ >+ <span>content</span>+ </ProgressiveBoundary>,+ { wrapper },+ );+ expect(screen.queryByText("wait")).not.toBeInTheDocument();++ act(() => store.set(capability, true));+ expect(screen.getByText("content")).toBeInTheDocument();+ });+});diff --git a/frontend/src/components/lifecycle/__tests__/RuntimeStatusBadge.test.tsx b/frontend/src/components/lifecycle/__tests__/RuntimeStatusBadge.test.tsxnew file mode 100644index 0000000000..8a223c4fab--- /dev/null+++ b/frontend/src/components/lifecycle/__tests__/RuntimeStatusBadge.test.tsx@@ -0,0 +1,72 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { render, screen } from "@testing-library/react";+import { atom, createStore, Provider } from "jotai";+import type { ReactNode } from "react";+import { beforeEach, describe, expect, it } from "vitest";+import { TooltipProvider } from "@/components/ui/tooltip";+import {+ type AdapterState,+ type RuntimeAdapter,+ runtimeAdapterAtom,+} from "@/core/runtime/adapter";+import { RuntimeStatusBadge } from "../RuntimeStatusBadge";++function makeAdapter(initial: AdapterState): RuntimeAdapter {+ return {+ kind: "remote",+ label: "Kernel",+ capabilities: {+ canHealthCheck: true,+ canShutdown: true,+ canRestart: true,+ supportsLsp: true,+ },+ state: atom<AdapterState>(initial),+ };+}++let store: ReturnType<typeof createStore>;++const wrapper = ({ children }: { children: ReactNode }) => (+ <Provider store={store}>+ <TooltipProvider>{children}</TooltipProvider>+ </Provider>+);++beforeEach(() => {+ store = createStore();+});++describe("RuntimeStatusBadge", () => {+ it("hides itself when the runtime is ready", () => {+ store.set(runtimeAdapterAtom, makeAdapter({ kind: "ready" }));+ const { container } = render(<RuntimeStatusBadge />, { wrapper });+ expect(container).toBeEmptyDOMElement();+ });++ it("shows a labeled spinner pill while connecting", () => {+ store.set(+ runtimeAdapterAtom,+ makeAdapter({+ kind: "connecting",+ progress: { label: "Loading Pyodide…" },+ }),+ );+ render(<RuntimeStatusBadge />, { wrapper });+ expect(screen.getByTestId("runtime-status-footer")).toBeInTheDocument();+ expect(screen.getByText("Kernel")).toBeInTheDocument();+ });++ it("shows the failure icon when the runtime fails", () => {+ store.set(+ runtimeAdapterAtom,+ makeAdapter({+ kind: "failed",+ error: { message: "Boom", errorKind: "init" },+ }),+ );+ render(<RuntimeStatusBadge />, { wrapper });+ expect(screen.getByTestId("runtime-status-footer")).toBeInTheDocument();+ });+});diff --git a/frontend/src/core/edit-app.tsx b/frontend/src/core/edit-app.tsxindex b983d91e06..fab57aca47 100644--- a/frontend/src/core/edit-app.tsx+++ b/frontend/src/core/edit-app.tsx@@ -13,6 +13,7 @@ import { AppHeader } from "@/components/editor/header/app-header";import { FilenameForm } from "@/components/editor/header/filename-form";import { MultiCellActionToolbar } from "@/components/editor/navigation/multi-cell-action-toolbar";import { ViewerBanner } from "@/components/editor/viewer-banner";+import { ProgressiveBoundary } from "@/components/lifecycle/ProgressiveBoundary";import { cn } from "@/utils/cn";import { Paths } from "@/utils/paths";import { AppContainer } from "../components/editor/app-container";@@ -64,7 +65,6 @@ export const EditApp: React.FC<AppProps> = ({useCellActions();const viewState = useAtomValue(viewStateAtom);const numColumns = useAtomValue(numColumnsAtom);- const hasCells = useAtomValue(hasCellsAtom);const filename = useFilename();const setLastSavedNotebook = useSetAtom(lastSavedNotebookAtom);const { sendComponentValues, sendInterrupt } = useRequestClient();@@ -181,13 +181,16 @@ export const EditApp: React.FC<AppProps> = ({<ViewerBanner />- {/* Don't render until we have a single cell */}- {hasCells && (+ {/* Don't render until we have a single cell. NotStartedConnectionAlert+ still covers the "no remote runtime started" prompt. */}+ <ProgressiveBoundary+ requires={hasCellsAtom}+ fallback={<NotStartedConnectionAlert />}+ ><CellsRenderer appConfig={appConfig} mode={viewState.mode}>{editableCellsArray}</CellsRenderer>- )}- {!hasCells && <NotStartedConnectionAlert />}+ </ProgressiveBoundary></AppContainer><MultiCellActionToolbar />{!hideControls && (diff --git a/frontend/src/core/lifecycle/__tests__/render-policy.test.ts b/frontend/src/core/lifecycle/__tests__/render-policy.test.tsnew file mode 100644index 0000000000..712b3a2104--- /dev/null+++ b/frontend/src/core/lifecycle/__tests__/render-policy.test.ts@@ -0,0 +1,247 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { visibleForTesting } from "../render-policy";++const { computeRenderPolicy } = visibleForTesting;++const originalHref = window.location.href;+function setSearch(search: string) {+ window.history.replaceState(null, "", `/${search}`);+}++describe("computeRenderPolicy", () => {+ it("shows code in edit mode", () => {+ const policy = computeRenderPolicy({+ mode: "edit",+ showAppCode: false, // ignored in edit mode+ hasCells: true,+ hasCachedOutputs: false,+ allCellsIdle: false,+ });+ expect(policy.showCode).toBe(true);+ });++ it("hides code in present mode regardless of config", () => {+ const policy = computeRenderPolicy({+ mode: "present",+ showAppCode: true,+ hasCells: true,+ hasCachedOutputs: true,+ allCellsIdle: false,+ });+ expect(policy.showCode).toBe(false);+ });++ it("respects showAppCode in read mode", () => {+ expect(+ computeRenderPolicy({+ mode: "read",+ showAppCode: true,+ hasCells: true,+ hasCachedOutputs: false,+ allCellsIdle: false,+ }).showCode,+ ).toBe(true);++ expect(+ computeRenderPolicy({+ mode: "read",+ showAppCode: false,+ hasCells: true,+ hasCachedOutputs: false,+ allCellsIdle: false,+ }).showCode,+ ).toBe(false);+ });++ it("reports showCachedOutputs when cells and cached outputs are present", () => {+ expect(+ computeRenderPolicy({+ mode: "read",+ showAppCode: false,+ hasCells: true,+ hasCachedOutputs: true,+ allCellsIdle: false,+ }).showCachedOutputs,+ ).toBe(true);+ });++ it("does not report showCachedOutputs when there are no cells", () => {+ expect(+ computeRenderPolicy({+ mode: "read",+ showAppCode: false,+ hasCells: false,+ hasCachedOutputs: true,+ allCellsIdle: false,+ }).showCachedOutputs,+ ).toBe(false);+ });++ it("only reports showCachedOutputs for real outputs, not an idle notebook", () => {+ // Regression guard: `showCachedOutputs` must stay honest even when the+ // notebook is settled with no outputs (that only affects `canPaint`).+ expect(+ computeRenderPolicy({+ mode: "read",+ showAppCode: false,+ hasCells: true,+ hasCachedOutputs: false,+ allCellsIdle: true,+ }).showCachedOutputs,+ ).toBe(false);+ });+});++describe("computeRenderPolicy — read-mode code visibility", () => {+ beforeEach(() => {+ setSearch("");+ });++ afterEach(() => {+ window.history.replaceState(null, "", originalHref);+ });++ it("hides code when the server stripped sources (?include-code=false)", () => {+ setSearch("?include-code=false");+ const policy = computeRenderPolicy({+ mode: "read",+ showAppCode: true, // config would show code, but sources are stripped+ hasCells: true,+ hasCachedOutputs: false,+ allCellsIdle: false,+ });+ expect(policy.showCode).toBe(false);+ // With no code, no outputs, and still running, there is nothing to paint.+ expect(policy.canPaint).toBe(false);+ });++ it("include-code=false still paints when cached outputs exist", () => {+ setSearch("?include-code=false");+ expect(+ computeRenderPolicy({+ mode: "read",+ showAppCode: true,+ hasCells: true,+ hasCachedOutputs: true,+ allCellsIdle: false,+ }).canPaint,+ ).toBe(true);+ });+});++describe("computeRenderPolicy.canPaint", () => {+ it("is false when no cells exist, even if all (zero) cells are vacuously idle", () => {+ expect(+ computeRenderPolicy({+ mode: "read",+ showAppCode: true,+ hasCells: false,+ hasCachedOutputs: false,+ allCellsIdle: true,+ }).canPaint,+ ).toBe(false);+ });++ it("is true in edit mode whenever cells exist", () => {+ expect(+ computeRenderPolicy({+ mode: "edit",+ showAppCode: false,+ hasCells: true,+ hasCachedOutputs: false,+ allCellsIdle: false,+ }).canPaint,+ ).toBe(true);+ });++ it("is true in read mode when code is visible", () => {+ expect(+ computeRenderPolicy({+ mode: "read",+ showAppCode: true,+ hasCells: true,+ hasCachedOutputs: false,+ allCellsIdle: false,+ }).canPaint,+ ).toBe(true);+ });++ it("is false in headless read mode while the notebook is still running with no outputs", () => {+ expect(+ computeRenderPolicy({+ mode: "read",+ showAppCode: false,+ hasCells: true,+ hasCachedOutputs: false,+ allCellsIdle: false,+ }).canPaint,+ ).toBe(false);+ });++ it("is true in headless read mode with cached outputs", () => {+ expect(+ computeRenderPolicy({+ mode: "read",+ showAppCode: false,+ hasCells: true,+ hasCachedOutputs: true,+ allCellsIdle: false,+ }).canPaint,+ ).toBe(true);+ });++ it("is true in headless read mode for a settled notebook with no outputs", () => {+ // A notebook that ran to completion producing no outputs must still paint+ // (empty) rather than sit on a spinner — parity with the pre-framework+ // `hasAnyOutputAtom` idle fallback.+ expect(+ computeRenderPolicy({+ mode: "read",+ showAppCode: false,+ hasCells: true,+ hasCachedOutputs: false,+ allCellsIdle: true,+ }).canPaint,+ ).toBe(true);+ });++ // In present mode `showCode` is always false, so `canPaint` rides entirely+ // on cached outputs / a settled notebook.+ it("is true in present mode with cached outputs", () => {+ expect(+ computeRenderPolicy({+ mode: "present",+ showAppCode: true,+ hasCells: true,+ hasCachedOutputs: true,+ allCellsIdle: false,+ }).canPaint,+ ).toBe(true);+ });++ it("is false in present mode while still running with no outputs", () => {+ expect(+ computeRenderPolicy({+ mode: "present",+ showAppCode: true,+ hasCells: true,+ hasCachedOutputs: false,+ allCellsIdle: false,+ }).canPaint,+ ).toBe(false);+ });++ it("is true in present mode for a settled notebook with no outputs", () => {+ expect(+ computeRenderPolicy({+ mode: "present",+ showAppCode: true,+ hasCells: true,+ hasCachedOutputs: false,+ allCellsIdle: true,+ }).canPaint,+ ).toBe(true);+ });+});diff --git a/frontend/src/core/lifecycle/render-policy.ts b/frontend/src/core/lifecycle/render-policy.tsnew file mode 100644index 0000000000..a697c07c0a--- /dev/null+++ b/frontend/src/core/lifecycle/render-policy.ts@@ -0,0 +1,125 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { atom } from "jotai";+import { hasCellsAtom, notebookAtom } from "../cells/cells";+import { isOutputEmpty } from "../cells/outputs";+import { KnownQueryParams } from "../constants";+import { showCodeInRunModeAtom } from "../meta/state";+import { type AppMode, initialModeAtom } from "../mode";+import { hasQueryParam } from "@/utils/urls";++export interface RenderPolicy {+ /** False in `present` mode, and in `read` mode when the user has opted to hide code. */+ showCode: boolean;+ /** True only when there are real, non-empty cached outputs to display. */+ showCachedOutputs: boolean;+ /**+ * Whether the current view has anything to paint without waiting on the+ * runtime:+ * - In edit/home/gallery mode, this is `hasCells` — the editor renders the+ * cell skeleton even when output is empty.+ * - In read/present mode with code visible, the cell source is enough.+ * - In headless read mode (code hidden), we need either cached outputs or a+ * settled notebook (all cells idle) — a completed but output-less notebook+ * is still "done" and shouldn't strand on an infinite spinner.+ */+ canPaint: boolean;+}++function readCodeVisibility(+ mode: AppMode | undefined,+ showAppCode: boolean,+): boolean {+ if (mode === "edit" || mode === "home" || mode === "gallery") {+ return true;+ }+ if (mode === "present") {+ return false;+ }+ // read mode (or undefined). If `marimo run` stripped the sources+ // (`--include-code` off), there is no code to show regardless of any other+ // signal — mirror `core/meta/code-visibility.ts` so the two don't drift.+ if (hasQueryParam(KnownQueryParams.includeCode, "false")) {+ return false;+ }+ // Otherwise the URL `show-code` param wins, then the view config.+ if (hasQueryParam(KnownQueryParams.showCode, "false")) {+ return false;+ }+ if (hasQueryParam(KnownQueryParams.showCode, "true")) {+ return true;+ }+ return showAppCode;+}++function computeRenderPolicy(input: {+ mode: AppMode | undefined;+ showAppCode: boolean;+ hasCells: boolean;+ hasCachedOutputs: boolean;+ /**+ * True when every cell is idle. A settled notebook is paintable even with no+ * visible outputs — otherwise a completed but output-less notebook viewed in+ * headless read mode would strand on an infinite spinner. Mirrors the+ * pre-framework `hasAnyOutputAtom` idle fallback.+ */+ allCellsIdle: boolean;+}): RenderPolicy {+ const showCode = readCodeVisibility(input.mode, input.showAppCode);+ const showCachedOutputs = input.hasCells && input.hasCachedOutputs;+ const canPaint =+ input.hasCells && (showCode || showCachedOutputs || input.allCellsIdle);++ return { showCode, showCachedOutputs, canPaint };+}++/**+ * Both cell-runtime facts the render policy needs, computed in a single pass+ * over `cellRuntime`:+ * - `hasCachedOutputs`: any cell has a non-empty output.+ * - `allCellsIdle`: every cell's status is idle — nothing queued or running.+ * Vacuously true for an empty notebook, so `canPaint` still gates on+ * `hasCells`.+ *+ * Fan out to two boolean selector atoms below so `renderPolicyAtom` only+ * recomputes when one of the booleans actually flips, not on every notebook+ * update.+ */+const cellRuntimeSummaryAtom = atom((get) => {+ let hasCachedOutputs = false;+ let allCellsIdle = true;+ for (const runtime of Object.values(get(notebookAtom).cellRuntime)) {+ if (!isOutputEmpty(runtime.output)) {+ hasCachedOutputs = true;+ }+ if (runtime.status !== "idle") {+ allCellsIdle = false;+ }+ }+ return { hasCachedOutputs, allCellsIdle };+});++const hasCachedOutputsAtom = atom(+ (get) => get(cellRuntimeSummaryAtom).hasCachedOutputs,+);++const allCellsIdleAtom = atom(+ (get) => get(cellRuntimeSummaryAtom).allCellsIdle,+);++export const renderPolicyAtom = atom<RenderPolicy>((get) =>+ computeRenderPolicy({+ mode: get(initialModeAtom),+ showAppCode: get(showCodeInRunModeAtom),+ hasCells: get(hasCellsAtom),+ hasCachedOutputs: get(hasCachedOutputsAtom),+ allCellsIdle: get(allCellsIdleAtom),+ }),+);++/** Sugar over `renderPolicyAtom.canPaint`. */+export const canPaintAtom = atom((get) => get(renderPolicyAtom).canPaint);++export const visibleForTesting = {+ computeRenderPolicy,+};diff --git a/frontend/src/core/run-app.tsx b/frontend/src/core/run-app.tsxindex 30a53e4abf..f2a9f8a429 100644--- a/frontend/src/core/run-app.tsx+++ b/frontend/src/core/run-app.tsx@@ -1,13 +1,13 @@/* Copyright 2026 Marimo. All rights reserved. */-import { useAtomValue } from "jotai";+import { atom, useAtomValue } from "jotai";import { ArrowLeftIcon } from "lucide-react";import { useEffect } from "react";import { AppContainer } from "@/components/editor/app-container";import { AppHeader } from "@/components/editor/header/app-header";+import { ProgressiveBoundary } from "@/components/lifecycle/ProgressiveBoundary";import { Spinner } from "@/components/icons/spinner";import { buttonVariants } from "@/components/ui/button";-import { DelayMount } from "@/components/utils/delay-mount";import { cn } from "@/utils/cn";import { CellsRenderer } from "../components/editor/renderers/cells-renderer";import {@@ -18,6 +18,7 @@ import {import type { AppConfig } from "./config/config-schema";import { RuntimeState } from "./kernel/RuntimeState";import { getSessionId } from "./kernel/session";+import { connectionAtom } from "./network/connection";import { useRequestClient } from "./network/requests";import { isAppConnecting } from "./websocket/connection-utils";import { useMarimoKernelConnection } from "./websocket/useMarimoKernelConnection";@@ -26,6 +27,16 @@ interface AppProps {appConfig: AppConfig;}+/**+ * Paint the (possibly empty) app once we have cells, or as soon as we are no+ * longer actively connecting. Without the connection check, a connected or+ * disconnected notebook with no cells would sit on a misleading "Connecting…"+ * spinner instead of rendering the empty app.+ */+const canPaintRunAppAtom = atom(+ (get) => get(hasCellsAtom) || !isAppConnecting(get(connectionAtom).state),+);+export const RunApp: React.FC<AppProps> = ({ appConfig }) => {const { setCells } = useCellActions();const { sendComponentValues } = useRequestClient();@@ -45,26 +56,6 @@ export const RunApp: React.FC<AppProps> = ({ appConfig }) => {});const isRunning = useAtomValue(notebookIsRunningAtom);- const isConnecting = isAppConnecting(connection.state);- // Skip the "Connecting..." gate when we already have cells to show — from- // an embedded snapshot or a prior connection.- const hasExistingCells = useAtomValue(hasCellsAtom);-- const renderCells = () => {- // If we are connecting for more than 2 seconds, show a spinner- if (isConnecting && !hasExistingCells) {- return (- <DelayMount milliseconds={2000} fallback={null}>- <Spinner className="mx-auto" />- <p className="text-center text-sm text-muted-foreground mt-2">- Connecting...- </p>- </DelayMount>- );- }-- return <CellsRenderer appConfig={appConfig} mode="read" />;- };const galleryHref = (() => {if (typeof window === "undefined") {@@ -103,7 +94,20 @@ export const RunApp: React.FC<AppProps> = ({ appConfig }) => {</div>)}</AppHeader>- {renderCells()}+ <ProgressiveBoundary+ requires={canPaintRunAppAtom}+ delay={2000}+ fallback={+ <>+ <Spinner className="mx-auto" />+ <p className="text-center text-sm text-muted-foreground mt-2">+ Connecting...+ </p>+ </>+ }+ >+ <CellsRenderer appConfig={appConfig} mode="read" />+ </ProgressiveBoundary></AppContainer>);};diff --git a/frontend/src/core/runtime/__tests__/adapter.test.ts b/frontend/src/core/runtime/__tests__/adapter.test.tsnew file mode 100644index 0000000000..0b7b83ea27--- /dev/null+++ b/frontend/src/core/runtime/__tests__/adapter.test.ts@@ -0,0 +1,160 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { createStore } from "jotai";+import { describe, expect, it } from "vitest";+import { islandsInitializedAtom } from "../../islands/state";+import { kernelStateAtom } from "../../kernel/state";+import { connectionAtom } from "../../network/connection";+import { wasmInitStateAtom } from "../../wasm/state";+import { WebSocketState } from "../../websocket/types";+import {+ canRunCellsAtom,+ islandsAdapter,+ remoteAdapter,+ runtimeAdapterAtom,+ staticAdapter,+ wasmAdapter,+} from "../adapter";++describe("wasmAdapter", () => {+ it("reports connecting with the progress label while loading", () => {+ const store = createStore();+ store.set(wasmInitStateAtom, {+ kind: "loading",+ message: "Loading Pyodide…",+ });+ expect(store.get(wasmAdapter.state)).toEqual({+ kind: "connecting",+ progress: { label: "Loading Pyodide…" },+ });+ });++ it("reports ready when initialized", () => {+ const store = createStore();+ store.set(wasmInitStateAtom, { kind: "ready" });+ expect(store.get(wasmAdapter.state)).toEqual({ kind: "ready" });+ });++ it("exposes the real error message on failure", () => {+ const store = createStore();+ store.set(wasmInitStateAtom, {+ kind: "error",+ message: "ImportError: numpy",+ });+ expect(store.get(wasmAdapter.state)).toEqual({+ kind: "failed",+ error: { message: "ImportError: numpy", errorKind: "init" },+ });+ });+});++describe("remoteAdapter", () => {+ it.each([+ [{ state: WebSocketState.OPEN }, { kind: "ready" }],+ [+ { state: WebSocketState.CONNECTING },+ { kind: "connecting", progress: { label: "Connecting…" } },+ ],+ [+ { state: WebSocketState.NOT_STARTED },+ { kind: "connecting", progress: { label: "Not connected" } },+ ],+ ] as const)("maps %j to %j", (conn, expected) => {+ const store = createStore();+ store.set(connectionAtom, conn as never);+ expect(store.get(remoteAdapter.state)).toEqual(expected);+ });++ it("surfaces the close reason when closed", () => {+ const store = createStore();+ store.set(connectionAtom, {+ state: WebSocketState.CLOSED,+ code: "KERNEL_DISCONNECTED",+ reason: "Kernel went away",+ });+ expect(store.get(remoteAdapter.state)).toEqual({+ kind: "failed",+ error: { message: "Kernel went away", errorKind: "runtime" },+ });+ });+});++describe("staticAdapter", () => {+ it("is always ready", () => {+ const store = createStore();+ expect(store.get(staticAdapter.state)).toEqual({ kind: "ready" });+ });++ it("advertises no capabilities", () => {+ expect(staticAdapter.capabilities).toEqual({+ canHealthCheck: false,+ canShutdown: false,+ canRestart: false,+ supportsLsp: false,+ });+ });+});++describe("islandsAdapter", () => {+ it("is connecting before islands report initialization", () => {+ const store = createStore();+ store.set(islandsInitializedAtom, false);+ expect(store.get(islandsAdapter.state)).toEqual({+ kind: "connecting",+ progress: { label: "Initializing islands…" },+ });+ });++ it("is ready once islands initialize", () => {+ const store = createStore();+ store.set(islandsInitializedAtom, true);+ expect(store.get(islandsAdapter.state)).toEqual({ kind: "ready" });+ });++ it("surfaces the error string when islands fail", () => {+ const store = createStore();+ store.set(islandsInitializedAtom, "wheel download failed");+ expect(store.get(islandsAdapter.state)).toEqual({+ kind: "failed",+ error: { message: "wheel download failed", errorKind: "init" },+ });+ });+});++describe("canRunCellsAtom", () => {+ it("is false on a remote adapter until kernel acks", () => {+ const store = createStore();+ // Default adapter in test env is remote.+ store.set(connectionAtom, { state: WebSocketState.OPEN });+ expect(store.get(canRunCellsAtom)).toBe(false);++ store.set(kernelStateAtom, { isInstantiated: true, error: null });+ expect(store.get(canRunCellsAtom)).toBe(true);+ });++ it("is true on WASM as soon as the adapter is ready (no separate kernel ack)", () => {+ const store = createStore();+ store.set(runtimeAdapterAtom, wasmAdapter);+ store.set(wasmInitStateAtom, { kind: "loading", message: "…" });+ expect(store.get(canRunCellsAtom)).toBe(false);++ store.set(wasmInitStateAtom, { kind: "ready" });+ expect(store.get(canRunCellsAtom)).toBe(true);+ });++ it("is always false on a static notebook", () => {+ const store = createStore();+ store.set(runtimeAdapterAtom, staticAdapter);+ expect(store.get(canRunCellsAtom)).toBe(false);+ });++ it("is true on islands once initialized", () => {+ const store = createStore();+ store.set(runtimeAdapterAtom, islandsAdapter);+ store.set(islandsInitializedAtom, false);+ expect(store.get(canRunCellsAtom)).toBe(false);++ store.set(islandsInitializedAtom, true);+ expect(store.get(canRunCellsAtom)).toBe(true);+ });+});diff --git a/frontend/src/core/runtime/adapter.ts b/frontend/src/core/runtime/adapter.tsnew file mode 100644index 0000000000..759ed42906--- /dev/null+++ b/frontend/src/core/runtime/adapter.ts@@ -0,0 +1,182 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { type Atom, atom } from "jotai";+import { kernelStateAtom } from "../kernel/state";+import { islandsInitializedAtom } from "../islands/state";+import { isIslands } from "../islands/utils";+import { connectionAtom } from "../network/connection";+import { isStaticNotebook } from "../static/static-state";+import { wasmInitStateAtom } from "../wasm/state";+import { isWasm } from "../wasm/utils";+import { WebSocketState } from "../websocket/types";++export type RuntimeKind = "wasm" | "remote" | "static" | "islands";++export type AdapterState =+ | { kind: "connecting"; progress?: { label: string; percent?: number } }+ | { kind: "ready" }+ | {+ kind: "failed";+ error: { message: string; errorKind: "init" | "runtime" };+ };++export interface RuntimeCapabilities {+ canHealthCheck: boolean;+ canShutdown: boolean;+ canRestart: boolean;+ supportsLsp: boolean;+}++/** Runtimes with no server-side kernel to manage (wasm, static, islands). */+const NO_CAPABILITIES: RuntimeCapabilities = {+ canHealthCheck: false,+ canShutdown: false,+ canRestart: false,+ supportsLsp: false,+};++/**+ * One adapter per runtime so consumers don't branch on `isWasm()` /+ * `isStaticNotebook()` / `isIslands()` at the call site.+ */+export interface RuntimeAdapter {+ readonly kind: RuntimeKind;+ /** Short label suitable for status pills, e.g. "Kernel", "Pyodide". */+ readonly label: string;+ readonly capabilities: RuntimeCapabilities;+ state: Atom<AdapterState>;+}++// --- WASM ------------------------------------------------------------------++const wasmStateAtom = atom<AdapterState>((get) => {+ const s = get(wasmInitStateAtom);+ switch (s.kind) {+ case "loading":+ return { kind: "connecting", progress: { label: s.message } };+ case "ready":+ return { kind: "ready" };+ case "error":+ return {+ kind: "failed",+ error: { message: s.message, errorKind: "init" },+ };+ }+});++export const wasmAdapter: RuntimeAdapter = {+ kind: "wasm",+ label: "Pyodide",+ capabilities: NO_CAPABILITIES,+ state: wasmStateAtom,+};++// --- Remote ----------------------------------------------------------------++const remoteStateAtom = atom<AdapterState>((get) => {+ const conn = get(connectionAtom);+ switch (conn.state) {+ case WebSocketState.OPEN:+ return { kind: "ready" };+ case WebSocketState.CONNECTING:+ return { kind: "connecting", progress: { label: "Connecting…" } };+ case WebSocketState.NOT_STARTED:+ return { kind: "connecting", progress: { label: "Not connected" } };+ case WebSocketState.CLOSING:+ case WebSocketState.CLOSED:+ return {+ kind: "failed",+ error: {+ message:+ conn.state === WebSocketState.CLOSED+ ? conn.reason+ : "Disconnecting",+ errorKind: "runtime",+ },+ };+ }+});++export const remoteAdapter: RuntimeAdapter = {+ kind: "remote",+ label: "Kernel",+ capabilities: {+ canHealthCheck: true,+ canShutdown: true,+ canRestart: true,+ supportsLsp: true,+ },+ state: remoteStateAtom,+};++// --- Static ----------------------------------------------------------------++const staticStateAtom = atom<AdapterState>({ kind: "ready" });++export const staticAdapter: RuntimeAdapter = {+ kind: "static",+ label: "Static",+ capabilities: NO_CAPABILITIES,+ state: staticStateAtom,+};++// --- Islands ---------------------------------------------------------------++const islandsStateAtom = atom<AdapterState>((get) => {+ const status = get(islandsInitializedAtom);+ if (status === true) {+ return { kind: "ready" };+ }+ if (typeof status === "string") {+ return {+ kind: "failed",+ error: { message: status, errorKind: "init" },+ };+ }+ return {+ kind: "connecting",+ progress: { label: "Initializing islands…" },+ };+});++export const islandsAdapter: RuntimeAdapter = {+ kind: "islands",+ label: "Islands",+ capabilities: NO_CAPABILITIES,+ state: islandsStateAtom,+};++function selectAdapter(): RuntimeAdapter {+ if (isStaticNotebook()) {+ return staticAdapter;+ }+ if (isIslands()) {+ return islandsAdapter;+ }+ if (isWasm()) {+ return wasmAdapter;+ }+ return remoteAdapter;+}++/** Picked once at module load; the choice doesn't change after page load. */+export const runtimeAdapterAtom = atom<RuntimeAdapter>(selectAdapter());++/**+ * Remote runtimes require both the WS to be open *and* the kernel to have+ * ack'd instantiation. WASM/islands have no separate kernel handshake.+ * Static notebooks never run cells.+ */+export const canRunCellsAtom = atom<boolean>((get) => {+ const adapter = get(runtimeAdapterAtom);+ if (get(adapter.state).kind !== "ready") {+ return false;+ }+ if (adapter.kind === "static") {+ return false;+ }+ if (adapter.kind === "remote") {+ return get(kernelStateAtom).isInstantiated;+ }+ return true;+});diff --git a/frontend/src/core/wasm/PyodideLoader.tsx b/frontend/src/core/wasm/PyodideLoader.tsxindex d4283cfe00..37239a6a0d 100644--- a/frontend/src/core/wasm/PyodideLoader.tsx+++ b/frontend/src/core/wasm/PyodideLoader.tsx@@ -5,54 +5,41 @@ import type React from "react";import type { PropsWithChildren } from "react";import { useEffect, useRef } from "react";import { LargeSpinner } from "@/components/icons/large-spinner";+import { ProgressiveBoundary } from "@/components/lifecycle/ProgressiveBoundary";import { toast } from "@/components/ui/use-toast";-import { hasCellsAtom } from "@/core/cells/cells";-import { showCodeInRunModeAtom } from "@/core/meta/state";-import { store } from "@/core/state/jotai";+import { canPaintAtom } from "@/core/lifecycle/render-policy";+import { wasmInitStateAtom } from "@/core/wasm/state";import { useAsyncData } from "@/hooks/useAsyncData";import { prettyError } from "@/utils/errors";import { Logger } from "@/utils/Logger";-import { hasQueryParam } from "@/utils/urls";-import { KnownQueryParams } from "../constants";-import { type AppMode, getInitialAppMode } from "../mode";import { PyodideBridge } from "./bridge";-import { hasAnyOutputAtom, wasmInitializationAtom } from "./state";import { isWasm } from "./utils";/**- * HOC to load Pyodide before rendering children, if necessary.+ * Paints the snapshot (or hydrated cells) immediately and lets Pyodide+ * finish downloading in the background. UI elements aren't interactive+ * until Pyodide is ready.*/export const PyodideLoader: React.FC<PropsWithChildren> = ({ children }) => {if (!isWasm()) {return children;}-return <PyodideLoaderInner>{children}</PyodideLoaderInner>;};const PyodideLoaderInner: React.FC<PropsWithChildren> = ({ children }) => {- // Don't block render on Pyodide: a hydrated snapshot can paint immediately- // while Pyodide downloads in the background.const { error } = useAsyncData(async () => {await PyodideBridge.INSTANCE.initialized.promise;return true;}, []);- const hasCells = useAtomValue(hasCellsAtom);- const hasOutput = useAtomValue(hasAnyOutputAtom);- const nothingToShow = shouldShowSpinner({- hasCells,- hasOutput,- mode: getInitialAppMode(),- codeHidden: isCodeHidden(),- });+ const canPaint = useAtomValue(canPaintAtom);+ // If the snapshot is already on screen, toast instead of throwing so we+ // don't tear it down. With nothing painted, throw to surface the error UI.const didToastErrorRef = useRef(false);useEffect(() => {- // With snapshot content on-screen, toast instead of throwing so the- // snapshot stays readable. The ref ensures we only toast once even if- // nothingToShow toggles later.- if (error && !nothingToShow && !didToastErrorRef.current) {+ if (error && canPaint && !didToastErrorRef.current) {didToastErrorRef.current = true;Logger.error("Pyodide failed to initialize", error);toast({@@ -61,50 +48,21 @@ const PyodideLoaderInner: React.FC<PropsWithChildren> = ({ children }) => {variant: "danger",});}- }, [error, nothingToShow]);+ }, [error, canPaint]);- if (error && nothingToShow) {+ if (error && !canPaint) {throw error;}- if (nothingToShow) {- return <WasmSpinner />;- }-- return children;-};--function isCodeHidden() {- // Code is hidden if ANY are true:- // - the query param is set to false- // - the view.showAppCode is falsereturn (- hasQueryParam(KnownQueryParams.showCode, "false") ||- !store.get(showCodeInRunModeAtom)+ <ProgressiveBoundary requires={canPaintAtom} fallback={<WasmSpinner />}>+ {children}+ </ProgressiveBoundary>);-}--/**- * Pure predicate: should the WASM loader render a spinner instead of its- * children? We block render only when nothing user-visible would appear:- * - no cells have been hydrated (Pyodide hasn't parsed the notebook), or- * - we are in headless run mode (code hidden) with no outputs to display.- */-export function shouldShowSpinner(input: {- hasCells: boolean;- hasOutput: boolean;- mode: AppMode;- codeHidden: boolean;-}): boolean {- const { hasCells, hasOutput, mode, codeHidden } = input;- if (!hasCells) {- return true;- }- return !hasOutput && mode === "read" && codeHidden;-}--export const WasmSpinner: React.FC<PropsWithChildren> = ({ children }) => {- const wasmInitialization = useAtomValue(wasmInitializationAtom);+};- return <LargeSpinner title={wasmInitialization} />;+const WasmSpinner: React.FC = () => {+ const state = useAtomValue(wasmInitStateAtom);+ const title = state.kind === "loading" ? state.message : "Loading…";+ return <LargeSpinner title={title} />;};diff --git a/frontend/src/core/wasm/__tests__/PyodideLoader.test.ts b/frontend/src/core/wasm/__tests__/PyodideLoader.test.tsdeleted file mode 100644index ed8aa16498..0000000000--- a/frontend/src/core/wasm/__tests__/PyodideLoader.test.ts+++ /dev/null@@ -1,72 +0,0 @@-/* Copyright 2026 Marimo. All rights reserved. */--import { describe, expect, it } from "vitest";-import { shouldShowSpinner } from "../PyodideLoader";--describe("shouldShowSpinner", () => {- it("shows the spinner when there are no cells yet (Pyodide hasn't parsed)", () => {- expect(- shouldShowSpinner({- hasCells: false,- hasOutput: false,- mode: "read",- codeHidden: false,- }),- ).toBe(true);-- expect(- shouldShowSpinner({- hasCells: false,- hasOutput: true,- mode: "edit",- codeHidden: false,- }),- ).toBe(true);- });-- it("renders children once cells exist with code visible", () => {- // run mode, code visible, no outputs yet — the user can read the code- expect(- shouldShowSpinner({- hasCells: true,- hasOutput: false,- mode: "read",- codeHidden: false,- }),- ).toBe(false);- });-- it("renders children once cells exist with cached outputs (snapshot case)", () => {- expect(- shouldShowSpinner({- hasCells: true,- hasOutput: true,- mode: "read",- codeHidden: true,- }),- ).toBe(false);- });-- it("keeps the spinner up in headless run mode with no outputs", () => {- // read mode + code hidden + no outputs = nothing visible to render- expect(- shouldShowSpinner({- hasCells: true,- hasOutput: false,- mode: "read",- codeHidden: true,- }),- ).toBe(true);- });-- it("never blocks edit mode once cells exist", () => {- expect(- shouldShowSpinner({- hasCells: true,- hasOutput: false,- mode: "edit",- codeHidden: true,- }),- ).toBe(false);- });-});diff --git a/frontend/src/core/wasm/__tests__/state.test.ts b/frontend/src/core/wasm/__tests__/state.test.tsdeleted file mode 100644index 3cb0f0919f..0000000000--- a/frontend/src/core/wasm/__tests__/state.test.ts+++ /dev/null@@ -1,124 +0,0 @@-/* Copyright 2026 Marimo. All rights reserved. */--import { createRef } from "react";-import { describe, expect, it } from "vitest";-import { cellId } from "@/__tests__/branded";-import type { NotebookState } from "@/core/cells/cells";-import { initialNotebookState, notebookAtom } from "@/core/cells/cells";-import { createCell, createCellRuntimeState } from "@/core/cells/types";-import type { OutputMessage } from "@/core/kernel/messages";-import { store } from "@/core/state/jotai";-import { CollapsibleTree, MultiColumn } from "@/utils/id-tree";-import { hasAnyOutputAtom } from "../state";--describe("hasAnyOutputAtom", () => {- const createNotebookState = (- outputs: (OutputMessage | null)[],- ): NotebookState => ({- ...initialNotebookState(),- cellIds: new MultiColumn([- CollapsibleTree.from(outputs.map((_, i) => cellId(`${i}`))),- ]),- cellData: Object.fromEntries(- outputs.map((_, i) => [- cellId(`${i}`),- createCell({ id: cellId(`${i}`) }),- ]),- ),- cellRuntime: Object.fromEntries(- outputs.map((output, i) => [- `${i}`,- createCellRuntimeState({- output,- status: "queued",- outline: { items: [] },- }),- ]),- ),- cellHandles: Object.fromEntries(- outputs.map((_, i) => [cellId(`${i}`), createRef()]),- ),- });-- it("should return false when there are no outputs", () => {- store.set(notebookAtom, createNotebookState([null, null]));- expect(store.get(hasAnyOutputAtom)).toBe(false);- });-- it("should return false when all outputs are empty", () => {- store.set(- notebookAtom,- createNotebookState([- { channel: "output", mimetype: "text/plain", data: "", timestamp: 0 },- { channel: "output", mimetype: "text/plain", data: "", timestamp: 0 },- ]),- );- expect(store.get(hasAnyOutputAtom)).toBe(false);- });-- it("should return true when there is at least one non-empty output", () => {- store.set(- notebookAtom,- createNotebookState([- { channel: "output", mimetype: "text/plain", data: "", timestamp: 0 },- {- channel: "output",- mimetype: "text/plain",- data: "hello",- timestamp: 0,- },- ]),- );- expect(store.get(hasAnyOutputAtom)).toBe(true);- });-- it("should handle various output types", () => {- store.set(- notebookAtom,- createNotebookState([- {- channel: "output",- mimetype: "application/json",- data: { foo: "bar" },- timestamp: 0,- },- { channel: "output", mimetype: "text/plain", data: "", timestamp: 0 },- ]),- );- expect(store.get(hasAnyOutputAtom)).toBe(true);- });-- it("should return true when all outputs are idle", () => {- const notebookState = createNotebookState([null, null]);- const cellId0 = cellId("0");- const cellId1 = cellId("1");- // Some idle cell, so returns false- store.set(notebookAtom, {- ...notebookState,- cellRuntime: {- ...notebookState.cellRuntime,- [cellId0]: {- ...notebookState.cellRuntime[cellId0],- status: "idle",- },- },- });- expect(store.get(hasAnyOutputAtom)).toBe(false);-- // All cells are idle, so returns true- store.set(notebookAtom, {- ...notebookState,- cellRuntime: {- [cellId0]: {- ...notebookState.cellRuntime[cellId0],- status: "idle",- },- [cellId1]: {- ...notebookState.cellRuntime[cellId1],- status: "idle",- },- },- });- expect(store.get(hasAnyOutputAtom)).toBe(true);- });-});diff --git a/frontend/src/core/wasm/bridge.ts b/frontend/src/core/wasm/bridge.tsindex 5cc30aa5b6..aa76d3b9e9 100644--- a/frontend/src/core/wasm/bridge.ts+++ b/frontend/src/core/wasm/bridge.ts@@ -38,7 +38,7 @@ import type { IConnectionTransport } from "../websocket/transports/transport";import { PyodideRouter } from "./router";import { getWorkerRPC } from "./rpc";import { createShareableLink } from "./share";-import { wasmInitializationAtom, wasmInitStatusAtom } from "./state";+import { wasmInitStateAtom } from "./state";import { fallbackFileStore, notebookFileStore } from "./store";import { isWasm } from "./utils";import type { SaveWorkerSchema } from "./worker/save-worker";@@ -120,11 +120,16 @@ export class PyodideBridge implements RunRequests, EditRequests {// By initializing after, we get hits on cached network requeststhis.saveRpc = this.getSaveWorker();this.setInterruptBuffer();- store.set(wasmInitStatusAtom, "ready");+ store.set(wasmInitStateAtom, { kind: "ready" });this.initialized.resolve();});this.rpc.addMessageListener("initializingMessage", ({ message }) => {- store.set(wasmInitializationAtom, message);+ // Only bump the progress label while still loading — if we've already+ // reached "ready" or "error", a late message shouldn't roll us back.+ const current = store.get(wasmInitStateAtom);+ if (current.kind === "loading") {+ store.set(wasmInitStateAtom, { kind: "loading", message });+ }});this.rpc.addMessageListener("initializedError", ({ error }) => {// If already initialized, surface as a toast and leave the deferred /@@ -138,7 +143,7 @@ export class PyodideBridge implements RunRequests, EditRequests {});return;}- store.set(wasmInitStatusAtom, "error");+ store.set(wasmInitStateAtom, { kind: "error", message: error });this.initialized.reject(new Error(error));});this.rpc.addMessageListener("kernelMessage", ({ message }) => {diff --git a/frontend/src/core/wasm/state.ts b/frontend/src/core/wasm/state.tsindex b77f325387..17898eb7fd 100644--- a/frontend/src/core/wasm/state.ts+++ b/frontend/src/core/wasm/state.ts@@ -1,24 +1,13 @@/* Copyright 2026 Marimo. All rights reserved. */import { atom } from "jotai";-import { notebookAtom } from "../cells/cells";-import { isOutputEmpty } from "../cells/outputs";-export const wasmInitializationAtom = atom<string>("Initializing...");+/** Tagged so the progress label and error message can't drift apart. */+export type WasmInitState =+ | { kind: "loading"; message: string }+ | { kind: "ready" }+ | { kind: "error"; message: string };-export type WasmInitStatus = "loading" | "ready" | "error";-export const wasmInitStatusAtom = atom<WasmInitStatus>("loading");--export const hasAnyOutputAtom = atom<boolean>((get) => {- const notebook = get(notebookAtom);- const runtimeStates = Object.values(notebook.cellRuntime);- // First check if there is any output- const hasOutput = runtimeStates.some(- (runtime) => !isOutputEmpty(runtime.output),- );- if (hasOutput) {- return true;- }- // If there is no output, check if they have all run to completion- // in case this notebook doesn't contain outputs- return runtimeStates.every((runtime) => runtime.status === "idle");+export const wasmInitStateAtom = atom<WasmInitState>({+ kind: "loading",+ message: "Initializing...",});diff --git a/frontend/src/hooks/__tests__/useDelayElapsed.test.tsx b/frontend/src/hooks/__tests__/useDelayElapsed.test.tsxnew file mode 100644index 0000000000..86d8645da4--- /dev/null+++ b/frontend/src/hooks/__tests__/useDelayElapsed.test.tsx@@ -0,0 +1,55 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { act, renderHook } from "@testing-library/react";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { useDelayElapsed } from "../useDelayElapsed";++describe("useDelayElapsed", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });++ afterEach(() => {+ vi.useRealTimers();+ });++ it("resolves true immediately when delay <= 0", () => {+ const { result } = renderHook(() => useDelayElapsed(0));+ expect(result.current).toBe(true);+ });++ it("stays false until the delay elapses, then flips true", () => {+ const { result } = renderHook(() => useDelayElapsed(2000));+ expect(result.current).toBe(false);++ act(() => vi.advanceTimersByTime(1999));+ expect(result.current).toBe(false);++ act(() => vi.advanceTimersByTime(1));+ expect(result.current).toBe(true);+ });++ it("restarts the timer when the delay changes", () => {+ const { result, rerender } = renderHook(+ ({ delay }) => useDelayElapsed(delay),+ { initialProps: { delay: 1000 } },+ );++ act(() => vi.advanceTimersByTime(1000));+ expect(result.current).toBe(true);++ rerender({ delay: 500 });+ expect(result.current).toBe(false);++ act(() => vi.advanceTimersByTime(500));+ expect(result.current).toBe(true);+ });++ it("clears the timer on unmount", () => {+ const { unmount } = renderHook(() => useDelayElapsed(1000));+ expect(vi.getTimerCount()).toBe(1);+ unmount();+ // The pending timeout must be cleared, not left dangling.+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/frontend/src/hooks/useDelayElapsed.ts b/frontend/src/hooks/useDelayElapsed.tsnew file mode 100644index 0000000000..0af0a7e4cd--- /dev/null+++ b/frontend/src/hooks/useDelayElapsed.ts@@ -0,0 +1,27 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { useLayoutEffect, useState } from "react";++/**+ * Returns `false` until `delayMs` has elapsed since mount (or since `delayMs`+ * last changed), then `true`. Resolves to `true` immediately when+ * `delayMs <= 0`. Useful for suppressing spinner/fallback flashes.+ */+export function useDelayElapsed(delayMs: number): boolean {+ const [elapsed, setElapsed] = useState(delayMs <= 0);++ // Layout effect (not a plain effect) so that when `delayMs` flips from `<= 0`+ // to `> 0` — e.g. a gate re-closing — we reset `elapsed` to `false` before+ // the browser paints, rather than briefly flashing the fallback for a frame.+ useLayoutEffect(() => {+ if (delayMs <= 0) {+ setElapsed(true);+ return;+ }+ setElapsed(false);+ const timeout = setTimeout(() => setElapsed(true), delayMs);+ return () => clearTimeout(timeout);+ }, [delayMs]);++ return elapsed;+}