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
add editable code in slide view (#9389)
Shahmir Varqha7a83d3fef513
diff --git a/frontend/islands/vite.config.mts b/frontend/islands/vite.config.mtsindex 3a8f8a6bb7..60ee5f9a3c 100644--- a/frontend/islands/vite.config.mts+++ b/frontend/islands/vite.config.mts@@ -3,6 +3,7 @@import { execFile, execFileSync } from "node:child_process";import fs from "node:fs";import path from "node:path";+import { fileURLToPath } from "node:url";import { promisify } from "node:util";import react from "@vitejs/plugin-react";import { defineConfig, type Plugin } from "vite";@@ -12,10 +13,12 @@ import packageJson from "../package.json";const execFileAsync = promisify(execFile);+const dirname = path.dirname(fileURLToPath(import.meta.url));+const htmlDevPlugin = (): Plugin => {const generateHtml = async (): Promise<string> => {// Auto-regenerate HTML in dev mode by running the Python script- const scriptPath = path.resolve(__dirname, "generate.py");+ const scriptPath = path.resolve(dirname, "generate.py");try {const { stdout } = await execFileAsync("uv", ["run", scriptPath], {env: { ...process.env, MODE: "dev" },@@ -25,7 +28,7 @@ const htmlDevPlugin = (): Plugin => {console.error("Failed to generate demo HTML:", error);// Fallback to existing file if generation failsconst indexHtml = await fs.promises.readFile(- path.resolve(__dirname, "__demo__", "index.html"),+ path.resolve(dirname, "__demo__", "index.html"),"utf-8",);const preamble = `<!DOCTYPE html>\n@@ -48,7 +51,7 @@ window.$RefreshSig$ = () => (type) => type;</script>},// Watch the generate.py file and trigger HMR on changesconfigureServer(server) {- const scriptPath = path.resolve(__dirname, "generate.py");+ const scriptPath = path.resolve(dirname, "generate.py");server.watcher.add(scriptPath);server.watcher.on("change", (file) => {if (file === scriptPath) {@@ -80,6 +83,20 @@ export default defineConfig({resolve: {tsconfigPaths: true,dedupe: ["react", "react-dom", "@emotion/react", "@emotion/cache"],+ alias: [+ // Islands run read-only and never render the slide code editor, so+ // swap `SlideCellView` for a no-op stub. This keeps CodeMirror, the+ // Codeium adapter, and `@bufbuild/protobuf` out of the islands bundle+ // (the latter contains a `process.env.BUF_BIGINT_DISABLE` literal+ // that `islands/validate.sh` otherwise flags).+ {+ find: "@/components/slides/slide-cell-view",+ replacement: path.resolve(+ dirname,+ "../src/core/islands/stubs/slide-cell-view.tsx",+ ),+ },+ ],},experimental: {enableNativePlugin: true,@@ -121,7 +138,7 @@ export default defineConfig({build: {emptyOutDir: true,lib: {- entry: path.resolve(__dirname, "../src/core/islands/main.ts"),+ entry: path.resolve(dirname, "../src/core/islands/main.ts"),formats: ["es"],},rolldownOptions: {diff --git a/frontend/src/components/editor/notebook-cell.tsx b/frontend/src/components/editor/notebook-cell.tsxindex d4c4231c16..7767275e17 100644--- a/frontend/src/components/editor/notebook-cell.tsx+++ b/frontend/src/components/editor/notebook-cell.tsx@@ -48,7 +48,11 @@ import {useCellRuntime,} from "../../core/cells/cells";import { type CellId, SETUP_CELL_ID } from "../../core/cells/ids";-import { isUninstantiated } from "../../core/cells/utils";+import {+ cellNeedsRun,+ cellStatusClasses,+ isUninstantiated,+} from "../../core/cells/utils";import type { UserConfig } from "../../core/config/config-schema";import { isAppInteractionDisabled } from "../../core/websocket/connection-utils";import { useCellRenderCount } from "../../hooks/useCellRenderCount";@@ -390,9 +394,6 @@ const EditableCellComponent = ({const [languageAdapter, setLanguageAdapter] = useState<LanguageAdapterType>();- const disabledOrAncestorDisabled =- cellData.config.disabled || cellRuntime.status === "disabled-transitively";-const uninstantiated = isUninstantiated({executionTime: cellRuntime.runElapsedTimeMs ?? cellData.lastExecutionTime,status: cellRuntime.status,@@ -401,10 +402,13 @@ const EditableCellComponent = ({stopped: cellRuntime.stopped,});- const needsRun =- cellData.edited ||- cellRuntime.interrupted ||- (cellRuntime.staleInputs && !disabledOrAncestorDisabled);+ const needsRun = cellNeedsRun({+ edited: cellData.edited,+ interrupted: cellRuntime.interrupted,+ staleInputs: cellRuntime.staleInputs,+ disabled: cellData.config.disabled,+ status: cellRuntime.status,+ });const loading = outputIsLoading(cellRuntime.status);@@ -532,11 +536,13 @@ const EditableCellComponent = ({const className = clsx("marimo-cell", "hover-actions-parent z-10", {interactive: true,- "needs-run": needsRun,- "has-error": cellRuntime.errored,- stopped: cellRuntime.stopped,- disabled: cellData.config.disabled,- stale: cellRuntime.status === "disabled-transitively",+ ...cellStatusClasses({+ needsRun,+ errored: cellRuntime.errored,+ stopped: cellRuntime.stopped,+ disabled: cellData.config.disabled,+ status: cellRuntime.status,+ }),borderless:isMarkdownCodeHidden && hasOutput && !navigationProps["data-selected"],});@@ -979,9 +985,6 @@ const SetupCellComponent = ({const setAiCompletionCell = useSetAtom(aiCompletionCellAtom);const runCell = useRunCell(cellId);- const disabledOrAncestorDisabled =- cellData.config.disabled || cellRuntime.status === "disabled-transitively";-const uninstantiated = isUninstantiated({executionTime: cellRuntime.runElapsedTimeMs ?? cellData.lastExecutionTime,status: cellRuntime.status,@@ -990,10 +993,13 @@ const SetupCellComponent = ({stopped: cellRuntime.stopped,});- const needsRun =- cellData.edited ||- cellRuntime.interrupted ||- (cellRuntime.staleInputs && !disabledOrAncestorDisabled);+ const needsRun = cellNeedsRun({+ edited: cellData.edited,+ interrupted: cellRuntime.interrupted,+ staleInputs: cellRuntime.staleInputs,+ disabled: cellData.config.disabled,+ status: cellRuntime.status,+ });const loading =cellRuntime.status === "running" || cellRuntime.status === "queued";@@ -1034,9 +1040,13 @@ const SetupCellComponent = ({const className = clsx("marimo-cell", "hover-actions-parent z-10", {interactive: true,- "needs-run": needsRun,- "has-error": cellRuntime.errored,- stopped: cellRuntime.stopped,+ ...cellStatusClasses({+ needsRun,+ errored: cellRuntime.errored,+ stopped: cellRuntime.stopped,+ disabled: cellData.config.disabled,+ status: cellRuntime.status,+ }),});const handleRefactorWithAI: OnRefactorWithAI = useEvent(diff --git a/frontend/src/components/editor/renderers/slides-layout/slides-layout.tsx b/frontend/src/components/editor/renderers/slides-layout/slides-layout.tsxindex 1f0f8faf12..6f152c1df6 100644--- a/frontend/src/components/editor/renderers/slides-layout/slides-layout.tsx+++ b/frontend/src/components/editor/renderers/slides-layout/slides-layout.tsx@@ -1,5 +1,5 @@/* Copyright 2026 Marimo. All rights reserved. */-import React, { useMemo, useRef, useState } from "react";+import React, { useMemo, useState } from "react";import { useAtomValue } from "jotai";import { numColumnsAtom } from "@/core/cells/cells";import type { CellId } from "@/core/cells/ids";@@ -8,7 +8,6 @@ import type { SlidesLayout } from "./types";import { computeSlideCellsInfo } from "./compute-slide-cells";import { SlidesMinimap } from "@/components/slides/minimap";import useEvent from "react-use-event-hook";-import type { RevealApi } from "reveal.js";type Props = ICellRendererProps<SlidesLayout>;@@ -26,7 +25,6 @@ export const SlidesLayoutRenderer: React.FC<Props> = ({const numColumns = useAtomValue(numColumnsAtom);const isMultiColumn = numColumns > 1;const [activeCellId, setActiveCellId] = useState<CellId | null>(null);- const deckRef = useRef<RevealApi | null>(null);const { cellsWithOutput, skippedIds, slideTypes, startCellIndex } = useMemo(() => computeSlideCellsInfo(cells, layout),@@ -53,9 +51,9 @@ export const SlidesLayoutRenderer: React.FC<Props> = ({setLayout={setLayout}activeIndex={resolvedIndex}onSlideChange={handleSlideChange}- deckRef={deckRef}- configWidth={250}+ configWidth={300}mode={mode}+ isEditable={mode !== "read"}/>);diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsxindex 10e380ad88..b52e10b690 100644--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx@@ -34,6 +34,7 @@ import { useResolvedMarimoConfig } from "@/core/config/config";import { CSSClasses, KnownQueryParams } from "@/core/constants";import type { MarimoError, OutputMessage } from "@/core/kernel/messages";import { kernelStateAtom } from "@/core/kernel/state";+import { useNotebookCodeAvailable } from "@/core/meta/code-visibility";import { showCodeInRunModeAtom } from "@/core/meta/state";import { isErrorMime } from "@/core/mime";import { type AppMode, kioskModeAtom } from "@/core/mode";@@ -83,23 +84,7 @@ const VerticalLayoutRenderer: React.FC<VerticalLayoutProps> = ({: showCodeByQueryParam === "true";});- const evaluateCanShowCode = () => {- const cellsHaveCode = cells.some((cell) => Boolean(cell.code));-- if (kioskMode) {- return true;- }-- // Only show code if in read mode and there is at least one cell with code-- // If it is a static-notebook or wasm-read-only-notebook, code is always included,- // but it can be turned it off via a query parameter (include-code=false)-- const includeCode = urlParams.get(KnownQueryParams.includeCode);- return mode === "read" && includeCode !== "false" && cellsHaveCode;- };-- const canShowCode = evaluateCanShowCode();+ const canShowCode = useNotebookCodeAvailable(cells);const renderCell = (cell: CellRuntimeState & CellData) => {return (diff --git a/frontend/src/components/slides/reveal-component.tsx b/frontend/src/components/slides/reveal-component.tsxindex e035aafb7b..9d6c5a3db9 100644--- a/frontend/src/components/slides/reveal-component.tsx+++ b/frontend/src/components/slides/reveal-component.tsx@@ -1,6 +1,7 @@/* Copyright 2026 Marimo. All rights reserved. */import {+ startTransition,useEffect,useMemo,useRef,@@ -8,7 +9,7 @@ import {Fragment as ReactFragment,} from "react";import useEvent from "react-use-event-hook";-import { ExpandIcon, EyeOffIcon } from "lucide-react";+import { CodeIcon, ExpandIcon, EyeOffIcon } from "lucide-react";import { Deck, Fragment, Slide, Stack } from "@revealjs/react";import { Slide as CellOutputSlide } from "@/components/slides/slide";import { Button } from "@/components/ui/button";@@ -34,6 +35,13 @@ import {DEFAULT_SLIDE_TYPE,SlideSidebar,} from "./slide-form";+import {+ SlideCellReadOnlyView,+ SlideCellView,+} from "@/components/slides/slide-cell-view";+import { cn } from "@/utils/cn";+import { isIslands } from "@/core/islands/utils";+import { useNotebookCodeAvailable } from "@/core/meta/code-visibility";import type { AppMode } from "@/core/mode";const ASPECT_RATIO = 16 / 9;@@ -118,21 +126,41 @@ function triggerResize(deck: RevealApi | null) {const SubslideView = ({subslide,+ showCode,+ isEditable,}: {subslide: ComposedSubslide<RuntimeCell>;+ showCode: boolean;+ isEditable: boolean;}) => (<Slide><div className="h-full w-full overflow-auto flex">- <div className="mo-slide-content" style={{ margin: "auto 20px" }}>+ <div+ className={+ showCode ? "mo-slide-content flex flex-col gap-3" : "mo-slide-content"+ }+ style={{+ margin: "auto 20px",+ }}+ >{subslide.blocks.map((block, i) => {- const rendered = block.cells.map((cell) => (- <CellOutputSlide- key={cell.id}- cellId={cell.id}- status={cell.status}- output={cell.output}- />- ));+ const rendered = block.cells.map((cell) => {+ if (!showCode) {+ return (+ <CellOutputSlide+ key={cell.id}+ cellId={cell.id}+ status={cell.status}+ output={cell.output}+ />+ );+ }+ return isEditable ? (+ <SlideCellView key={cell.id} cell={cell} />+ ) : (+ <SlideCellReadOnlyView key={cell.id} cell={cell} />+ );+ });if (block.isFragment) {return (<Fragment key={i} as="div">@@ -147,27 +175,37 @@ const SubslideView = ({</Slide>);+// There is an upstream react bug in dev mode (https://github.com/facebook/react/issues/34840)+// Uncaught SecurityError: Failed to read a named property '$$typeof' from 'Window'+// Happens with cells containing iframes / external contentconst RevealSlidesComponent = ({cellsWithOutput,layout,setLayout,activeIndex,onSlideChange,- deckRef,mode,configWidth = 300, // px+ isEditable = false,}: {cellsWithOutput: RuntimeCell[];layout: SlidesLayout;setLayout: (layout: SlidesLayout) => void;activeIndex?: number;onSlideChange?: (index: number) => void;- deckRef: React.RefObject<RevealApi | null>;mode: AppMode;configWidth?: number;+ isEditable?: boolean;}) => {const containerRef = useRef<HTMLDivElement>(null);+ const deckRef = useRef<RevealApi | null>(null);const { width, height } = useSlideDimensions(containerRef);++ const [showCode, setShowCode] = useState(false);+ const codeAvailable = useNotebookCodeAvailable(cellsWithOutput);+ const codeToggleEnabled = !isIslands() && codeAvailable;+ const codeShown = codeToggleEnabled && showCode;+const activeCell =activeIndex != null ? cellsWithOutput[activeIndex] : undefined;// Fall back to the first cell while the deck settles on an initial slide.@@ -217,11 +255,7 @@ const RevealSlidesComponent = ({[width, height, deckTransition],);- useEffect(() => {- const deck = deckRef.current;- if (deck == null) {- return;- }+ const navigateDeckToActiveCell = useEvent((deck: RevealApi) => {const target = resolveDeckNavigationTarget({activeIndex,cells: cellsWithOutput,@@ -234,7 +268,43 @@ const RevealSlidesComponent = ({}deck.slide(next.h, next.v, next.f);clearPreviousVerticalIndices(deck);- }, [activeIndex, cellToTarget, cellsWithOutput, deckRef]);+ });++ useEffect(() => {+ const deck = deckRef.current;+ if (deck == null) {+ return;+ }+ navigateDeckToActiveCell(deck);+ }, [activeIndex, cellToTarget, cellsWithOutput, navigateDeckToActiveCell]);++ // Toggling code (re)mounts a CodeMirror editor on the active slide. Defer+ // the state update so the button/keypress paints first and the heavier mount+ // can be interrupted by higher-priority work.+ const toggleShowCode = useEvent(() => {+ startTransition(() => setShowCode((value) => !value));+ });++ const handleDeckReady = useEvent((deck: RevealApi) => {+ navigateDeckToActiveCell(deck);+ if (codeToggleEnabled) {+ deck.addKeyBinding(+ { keyCode: 67, key: "C", description: "Toggle code editor" },+ toggleShowCode,+ );+ }+ });++ const activeSubslide = useMemo(() => {+ if (!activeCell) {+ return null;+ }+ const target = cellToTarget.get(activeCell.id);+ if (!target) {+ return null;+ }+ return { h: target.h, v: target.v };+ }, [activeCell, cellToTarget]);// Forward the deck's current cell to the parent, except while a skipped// preview is parked: every reveal.js event during that window is an echo@@ -266,6 +336,7 @@ const RevealSlidesComponent = ({if (Events.fromInput(event)) {return;}+const direction = classifyNavKey(event);if (direction === 0) {return;@@ -279,6 +350,11 @@ const RevealSlidesComponent = ({onSlideChange?.(nextIndex);});+ const handleSlideChange = useEvent(() => {+ reportCurrentCell();+ triggerResize(deckRef.current);+ });+useEventListener(document, "keydown", handleParkedNavKey, { capture: true });return (@@ -292,23 +368,38 @@ const RevealSlidesComponent = ({deckRef={deckRef}className="aspect-video w-full overflow-hidden border rounded bg-background mo-slides-theme prose-slides"config={revealConfig}- onSlideChange={() => {- reportCurrentCell();- const deck = deckRef.current;- triggerResize(deck);- }}+ onReady={handleDeckReady}+ onSlideChange={handleSlideChange}onFragmentShown={reportCurrentCell}onFragmentHidden={reportCurrentCell}>- {composition.stacks.map((stack, i) => {+ {composition.stacks.map((stack, h) => {if (stack.subslides.length === 1) {- return <SubslideView key={i} subslide={stack.subslides[0]} />;+ const isActive =+ activeSubslide?.h === h && activeSubslide?.v === 0;+ return (+ <SubslideView+ key={h}+ subslide={stack.subslides[0]}+ showCode={codeShown && isActive}+ isEditable={isEditable}+ />+ );}return (- <Stack key={i}>- {stack.subslides.map((sub, j) => (- <SubslideView key={j} subslide={sub} />- ))}+ <Stack key={h}>+ {stack.subslides.map((sub, v) => {+ const isActive =+ activeSubslide?.h === h && activeSubslide?.v === v;+ return (+ <SubslideView+ key={v}+ subslide={sub}+ showCode={codeShown && isActive}+ isEditable={isEditable}+ />+ );+ })}</Stack>);})}@@ -336,24 +427,45 @@ const RevealSlidesComponent = ({</div></div>)}- <Tooltip content="Fullscreen (F)">- <Button- data-testid="marimo-plugin-slides-fullscreen"- variant="ghost"- size="icon"- className="absolute top-2 right-2 z-20 opacity-0 group-hover:opacity-70 text-muted-foreground transition-opacity h-7 w-7"- onClick={() => {- deckRef.current- ?.getViewportElement()- ?.requestFullscreen()- .catch((error) => {- Logger.error("Failed to request fullscreen", error);- });- }}- >- <ExpandIcon className="h-4 w-4" />- </Button>- </Tooltip>+ <div className="absolute top-2 right-2 z-20 opacity-0 group-hover:opacity-70 text-muted-foreground transition-opacity">+ {codeToggleEnabled && (+ <Tooltip content={codeShown ? "Hide code (C)" : "Show code (C)"}>+ <Button+ data-testid="marimo-plugin-slides-toggle-code"+ variant="ghost"+ size="icon"+ className={cn(+ "text-muted-foreground h-7 w-7",+ codeShown && "text-foreground bg-muted",+ )}+ aria-pressed={codeShown}+ aria-label={codeShown ? "Hide code" : "Show code"}+ onClick={toggleShowCode}+ >+ <CodeIcon className="h-4 w-4" />+ </Button>+ </Tooltip>+ )}+ <Tooltip content="Fullscreen (F)">+ <Button+ data-testid="marimo-plugin-slides-fullscreen"+ variant="ghost"+ size="icon"+ className="text-muted-foreground h-7 w-7"+ aria-label="Enter fullscreen"+ onClick={() => {+ deckRef.current+ ?.getViewportElement()+ ?.requestFullscreen()+ .catch((error) => {+ Logger.error("Failed to request fullscreen", error);+ });+ }}+ >+ <ExpandIcon className="h-4 w-4" />+ </Button>+ </Tooltip>+ </div></div></div>diff --git a/frontend/src/components/slides/reveal-slides.css b/frontend/src/components/slides/reveal-slides.cssindex a1e47c7966..92e2547f93 100644--- a/frontend/src/components/slides/reveal-slides.css+++ b/frontend/src/components/slides/reveal-slides.css@@ -72,3 +72,11 @@.reveal .mo-slide-content .output {margin: 0;}++.reveal .marimo-cell .cm-editor {+ border-radius: 8px;+ padding-right: 10px;+}+.reveal .marimo-cell .cm-panels {+ margin-right: 0;+}diff --git a/frontend/src/components/slides/slide-cell-view.tsx b/frontend/src/components/slides/slide-cell-view.tsxnew file mode 100644index 0000000000..b444fdce14--- /dev/null+++ b/frontend/src/components/slides/slide-cell-view.tsx@@ -0,0 +1,182 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { useMemo, useRef, useState } from "react";+import type { EditorView } from "@codemirror/view";+import { useAtomValue } from "jotai";+import { CellEditor } from "@/components/editor/cell/code/cell-editor";+import { CellStatusComponent } from "@/components/editor/cell/CellStatus";+import { RunButton } from "@/components/editor/cell/RunButton";+import { StopButton } from "@/components/editor/cell/StopButton";+import { useRunCell } from "@/components/editor/cell/useRunCells";+import { Slide as CellOutputSlide } from "@/components/slides/slide";+import { useUserConfig } from "@/core/config/config";+import {+ cellNeedsRun,+ cellStatusClasses,+ isUninstantiated,+} from "@/core/cells/utils";+import type { CellData, CellRuntimeState } from "@/core/cells/types";+import type { LanguageAdapterType } from "@/core/codemirror/language/types";+import { connectionAtom } from "@/core/network/connection";+import { useTheme } from "@/theme/useTheme";+import { cn } from "@/utils/cn";+import { ReadonlyCode } from "../editor/code/readonly-python-code";+import { languageAdapterFromCode } from "@/core/codemirror/language/extension";++type RuntimeCell = CellRuntimeState & CellData;++/**+ * Renders a single cell in the slides view as an editable CodeMirror editor+ * stacked with its output, mirroring the notebook layout. Editing and+ * Ctrl/Cmd+Enter run the cell against the live kernel so presenters can iterate+ * without leaving the slide deck.+ */+export const SlideCellView = ({ cell }: { cell: RuntimeCell }) => {+ const [userConfig] = useUserConfig();+ const { theme } = useTheme();+ const runCell = useRunCell(cell.id);+ const connection = useAtomValue(connectionAtom);+ const editorViewRef = useRef<EditorView | null>(null);+ const editorViewParentRef = useRef<HTMLDivElement | null>(null);+ const [languageAdapter, setLanguageAdapter] = useState<+ LanguageAdapterType | undefined+ >();++ const cellOutputPosition = userConfig.display.cell_output;+ const hasOutput = cell.output != null;++ const uninstantiated = isUninstantiated({+ executionTime: cell.runElapsedTimeMs ?? cell.lastExecutionTime,+ status: cell.status,+ errored: cell.errored,+ interrupted: cell.interrupted,+ stopped: cell.stopped,+ });++ const needsRun = cellNeedsRun({+ edited: cell.edited,+ interrupted: cell.interrupted,+ staleInputs: cell.staleInputs,+ disabled: cell.config.disabled,+ status: cell.status,+ });++ const editorWrapperClassName = cn(+ "marimo-cell",+ "hover-actions-parent",+ "interactive",+ cellStatusClasses({+ needsRun,+ errored: cell.errored,+ stopped: cell.stopped,+ disabled: cell.config.disabled,+ status: cell.status,+ }),+ );++ const output = (+ <CellOutputSlide+ cellId={cell.id}+ status={cell.status}+ output={cell.output}+ />+ );++ const toolbar = (+ <div className="absolute top-1 right-2 z-10 flex items-center gap-1.5">+ <CellStatusComponent+ editing={true}+ status={cell.status}+ disabled={cell.config.disabled ?? false}+ staleInputs={cell.staleInputs}+ edited={cell.edited}+ interrupted={cell.interrupted}+ elapsedTime={cell.runElapsedTimeMs ?? cell.lastExecutionTime}+ runStartTimestamp={cell.runStartTimestamp}+ lastRunStartTimestamp={cell.lastRunStartTimestamp}+ uninstantiated={uninstantiated}+ />+ <div className="flex items-center shadow-none gap-1">+ <RunButton+ edited={cell.edited}+ status={cell.status}+ needsRun={needsRun}+ connectionState={connection.state}+ config={cell.config}+ onClick={runCell}+ />+ <StopButton status={cell.status} connectionState={connection.state} />+ </div>+ </div>+ );++ const editor = (+ <div className={editorWrapperClassName}>+ <CellEditor+ theme={theme}+ showPlaceholder={false}+ id={cell.id}+ code={cell.code}+ config={cell.config}+ status={cell.status}+ serializedEditorState={cell.serializedEditorState}+ runCell={runCell}+ setEditorView={(ev) => {+ editorViewRef.current = ev;+ }}+ userConfig={userConfig}+ editorViewRef={editorViewRef}+ editorViewParentRef={editorViewParentRef}+ hasOutput={hasOutput}+ // hide_code is intentionally overridden in the slide view; the editor+ // is unmounted entirely when the user toggles code off.+ showHiddenCode={() => undefined}+ languageAdapter={languageAdapter}+ setLanguageAdapter={setLanguageAdapter}+ showLanguageToggles={false}+ outputArea={cellOutputPosition}+ />+ {toolbar}+ </div>+ );++ return (+ <>+ {cellOutputPosition === "above" && output}+ {editor}+ {cellOutputPosition === "below" && output}+ </>+ );+};++export const SlideCellReadOnlyView = ({ cell }: { cell: RuntimeCell }) => {+ const [userConfig] = useUserConfig();+ const cellOutputPosition = userConfig.display.cell_output;++ const language = useMemo(() => {+ const adapter = languageAdapterFromCode(cell.code.trim());+ return adapter.type === "sql" ? "sql" : "python";+ }, [cell.code]);++ const output = (+ <CellOutputSlide+ cellId={cell.id}+ status={cell.status}+ output={cell.output}+ />+ );++ const editor = (+ <div className="marimo-cell">+ <ReadonlyCode code={cell.code} language={language} showHideCode={false} />+ </div>+ );++ return (+ <>+ {cellOutputPosition === "above" && output}+ {editor}+ {cellOutputPosition === "below" && output}+ </>+ );+};diff --git a/frontend/src/components/slides/slide-form.tsx b/frontend/src/components/slides/slide-form.tsxindex fa0c3f8227..90028dab36 100644--- a/frontend/src/components/slides/slide-form.tsx+++ b/frontend/src/components/slides/slide-form.tsx@@ -288,6 +288,8 @@ export const SlideSidebar = ({width: isConfigOpen ? configWidth : COLLAPSED_CONFIG_WIDTH,}}aria-label="Slide configuration"+ // Prevent keys from bubbling up to reveal.js's document-level keydown listener and moving the deck.+ onKeyDown={(e) => e.stopPropagation()}><headerclassName={cn(diff --git a/frontend/src/core/cells/utils.ts b/frontend/src/core/cells/utils.tsindex b2eaad1961..699ca5f855 100644--- a/frontend/src/core/cells/utils.ts+++ b/frontend/src/core/cells/utils.ts@@ -140,3 +140,48 @@ export function isUninstantiated({!(errored || interrupted || stopped));}++/**+ * Whether a cell needs to be run given its edited / interrupted / stale+ * inputs, while accounting for ancestor-disabled cells (which should not be+ * flagged as needing a run until re-enabled).+ */+export function cellNeedsRun({+ edited,+ interrupted,+ staleInputs,+ disabled,+ status,+}: {+ edited: boolean;+ interrupted: boolean;+ staleInputs: boolean;+ disabled: boolean | undefined;+ status: RuntimeState;+}): boolean {+ const disabledOrAncestorDisabled =+ disabled || status === "disabled-transitively";+ return edited || interrupted || (staleInputs && !disabledOrAncestorDisabled);+}++export function cellStatusClasses({+ needsRun,+ errored,+ stopped,+ disabled,+ status,+}: {+ needsRun: boolean;+ errored: boolean;+ stopped: boolean;+ disabled: boolean | undefined;+ status: RuntimeState;+}) {+ return {+ "needs-run": needsRun,+ "has-error": errored,+ stopped,+ disabled: disabled ?? false,+ stale: status === "disabled-transitively",+ };+}diff --git a/frontend/src/core/islands/stubs/slide-cell-view.tsx b/frontend/src/core/islands/stubs/slide-cell-view.tsxnew file mode 100644index 0000000000..b6c02a16e1--- /dev/null+++ b/frontend/src/core/islands/stubs/slide-cell-view.tsx@@ -0,0 +1,30 @@+/* Copyright 2026 Marimo. All rights reserved. */++import type { RuntimeCell } from "@/core/cells/types";+import { Logger } from "@/utils/Logger";++/**+ * Build-time stub for `@/components/slides/slide-cell-view`, wired up via+ * `resolve.alias` in `frontend/islands/vite.config.mts`. Islands embeds gate+ * off the slides "show code" toggle entirely (see `useNotebookCodeAvailable`+ * + `isIslands()`), so neither view is reachable at runtime there.+ *+ * Replacing the module at build time keeps the entire CodeMirror /+ * Codeium / `@bufbuild/protobuf` import subtree out of the islands bundle,+ * which both shrinks the bundle and lets `islands/validate.sh` pass — the+ * upstream protobuf code contains a `process.env.BUF_BIGINT_DISABLE`+ * runtime check that the validator otherwise flags.+ */+export const SlideCellView = (_props: { cell: RuntimeCell }) => {+ Logger.warn(+ "SlideCellView islands stub rendered; this should never happen in a read-only embed.",+ );+ return null;+};++export const SlideCellReadOnlyView = (_props: { cell: RuntimeCell }) => {+ Logger.warn(+ "SlideCellReadOnlyView islands stub rendered; this should never happen in a read-only embed.",+ );+ return null;+};diff --git a/frontend/src/core/meta/__tests__/code-visibility.test.tsx b/frontend/src/core/meta/__tests__/code-visibility.test.tsxnew file mode 100644index 0000000000..f4632fbf7e--- /dev/null+++ b/frontend/src/core/meta/__tests__/code-visibility.test.tsx@@ -0,0 +1,141 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { renderHook } from "@testing-library/react";+import { createStore, Provider } from "jotai";+import type { ReactNode } from "react";+import { afterEach, beforeEach, describe, expect, it } from "vitest";+import { showCodeInRunModeAtom } from "@/core/meta/state";+import { type AppMode, kioskModeAtom, viewStateAtom } from "@/core/mode";+import { useNotebookCodeAvailable } from "../code-visibility";++interface StoreOpts {+ mode?: AppMode;+ kiosk?: boolean;+ showInRunMode?: boolean;+}++function makeStore({+ mode = "read",+ kiosk = false,+ showInRunMode = true,+}: StoreOpts = {}) {+ const store = createStore();+ store.set(viewStateAtom, { mode, cellAnchor: null });+ store.set(kioskModeAtom, kiosk);+ store.set(showCodeInRunModeAtom, showInRunMode);+ return store;+}++function wrap(store: ReturnType<typeof createStore>) {+ return ({ children }: { children: ReactNode }) => (+ <Provider store={store}>{children}</Provider>+ );+}++const cellsWithCode = [{ code: "x = 1" }, { code: "" }];+const cellsWithoutCode = [{ code: "" }, { code: "" }];++const originalHref = window.location.href;++function setSearch(search: string) {+ window.history.replaceState(null, "", `/${search}`);+}++describe("useNotebookCodeAvailable", () => {+ beforeEach(() => {+ setSearch("");+ });++ afterEach(() => {+ window.history.replaceState(null, "", originalHref);+ });++ it("returns true in edit mode regardless of cells", () => {+ const store = makeStore({ mode: "edit" });+ const { result } = renderHook(+ () => useNotebookCodeAvailable(cellsWithoutCode),+ { wrapper: wrap(store) },+ );+ expect(result.current).toBe(true);+ });++ it("returns true in present mode (only reachable from edit)", () => {+ const store = makeStore({ mode: "present" });+ const { result } = renderHook(+ () => useNotebookCodeAvailable(cellsWithoutCode),+ { wrapper: wrap(store) },+ );+ expect(result.current).toBe(true);+ });++ it("returns true in kiosk mode even when read mode and no code", () => {+ const store = makeStore({+ mode: "read",+ kiosk: true,+ showInRunMode: false,+ });+ const { result } = renderHook(+ () => useNotebookCodeAvailable(cellsWithoutCode),+ { wrapper: wrap(store) },+ );+ expect(result.current).toBe(true);+ });++ it("returns true in read mode when at least one cell has code", () => {+ const store = makeStore({ mode: "read" });+ const { result } = renderHook(+ () => useNotebookCodeAvailable(cellsWithCode),+ { wrapper: wrap(store) },+ );+ expect(result.current).toBe(true);+ });++ it("returns false in read mode when every cell.code is empty (server stripped)", () => {+ const store = makeStore({ mode: "read" });+ const { result } = renderHook(+ () => useNotebookCodeAvailable(cellsWithoutCode),+ { wrapper: wrap(store) },+ );+ expect(result.current).toBe(false);+ });++ it("returns false in read mode when host opts out via showAppCode", () => {+ const store = makeStore({ mode: "read", showInRunMode: false });+ const { result } = renderHook(+ () => useNotebookCodeAvailable(cellsWithCode),+ { wrapper: wrap(store) },+ );+ expect(result.current).toBe(false);+ });++ it("returns false in read mode when ?include-code=false", () => {+ setSearch("?include-code=false");+ const store = makeStore({ mode: "read" });+ const { result } = renderHook(+ () => useNotebookCodeAvailable(cellsWithCode),+ { wrapper: wrap(store) },+ );+ expect(result.current).toBe(false);+ });++ it("ignores ?include-code=false in kiosk mode", () => {+ setSearch("?include-code=false");+ const store = makeStore({ mode: "read", kiosk: true });+ const { result } = renderHook(+ () => useNotebookCodeAvailable(cellsWithoutCode),+ { wrapper: wrap(store) },+ );+ expect(result.current).toBe(true);+ });++ it("returns false for non-edit/non-read modes (home, gallery)", () => {+ for (const mode of ["home", "gallery"] as const) {+ const store = makeStore({ mode });+ const { result } = renderHook(+ () => useNotebookCodeAvailable(cellsWithCode),+ { wrapper: wrap(store) },+ );+ expect(result.current).toBe(false);+ }+ });+});diff --git a/frontend/src/core/meta/code-visibility.ts b/frontend/src/core/meta/code-visibility.tsnew file mode 100644index 0000000000..a5aaef8589--- /dev/null+++ b/frontend/src/core/meta/code-visibility.ts@@ -0,0 +1,48 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { useAtomValue } from "jotai";+import { KnownQueryParams } from "@/core/constants";+import { showCodeInRunModeAtom } from "@/core/meta/state";+import { kioskModeAtom, viewStateAtom } from "@/core/mode";+import { logNever } from "@/utils/assertNever";++/**+ * Whether the notebook source code reached the frontend and can be rendered.+ *+ * In `marimo run` the server omits cell sources unless `--include-code` is+ * set (every `cell.code` arrives as `""`). Use this to gate any "show code"+ * / "copy code" / "download .py" affordance.+ */+export function useNotebookCodeAvailable(+ cells: ReadonlyArray<{ code: string }>,+): boolean {+ const kioskMode = useAtomValue(kioskModeAtom);+ const { mode } = useAtomValue(viewStateAtom);+ const showInRunMode = useAtomValue(showCodeInRunModeAtom);++ if (kioskMode) {+ return true;+ }++ switch (mode) {+ case "edit":+ case "present":+ return true;+ case "home":+ case "gallery":+ return false;+ case "read": {+ if (!showInRunMode) {+ return false;+ }+ const params = new URLSearchParams(window.location.search);+ if (params.get(KnownQueryParams.includeCode) === "false") {+ return false;+ }+ return cells.some((cell) => Boolean(cell.code));+ }+ default:+ logNever(mode);+ return false;+ }+}diff --git a/marimo/_smoke_tests/slides_examples/kitchen_sink.py b/marimo/_smoke_tests/slides_examples/kitchen_sink.pyindex 8661018edc..90c67bbbf1 100644--- a/marimo/_smoke_tests/slides_examples/kitchen_sink.py+++ b/marimo/_smoke_tests/slides_examples/kitchen_sink.py@@ -1,6 +1,6 @@import marimo-__generated_with = "0.23.1"+__generated_with = "0.23.2"app = marimo.App(width="medium",layout_file="layouts/kitchen_sink.slides.json",@@ -95,7 +95,7 @@ def _(mo):@app.cell(hide_code=True)def _(mo):- mo.md("## " + "A really long H2 heading that keeps on going and going " * 6)+ mo.md("## " + "A really long H2 heading that keeps on going and going " * 7)return@@ -118,7 +118,7 @@ def _(mo):def _(mo):mo.md("""# H1 Heading- ## H2 Subheading+ ## H2 Subheadings""").left()return@@ -255,6 +255,12 @@ def _(mo):return+def _(mo):+ mo.Html('<iframe src="https://www.youtube.com/embed/dQw4w9WgXcQ"></iframe>')+ return++@app.cell(hide_code=True)def _(mo):mo.image("https://picsum.photos/seed/marimo/400/300")diff --git a/marimo/_smoke_tests/slides_examples/layouts/nested_slides.slides.json b/marimo/_smoke_tests/slides_examples/layouts/nested_slides.slides.jsonindex a0397ec713..a85dc17544 100644--- a/marimo/_smoke_tests/slides_examples/layouts/nested_slides.slides.json+++ b/marimo/_smoke_tests/slides_examples/layouts/nested_slides.slides.json@@ -63,6 +63,18 @@{"type": "fragment"},+ {+ "type": "sub-slide"+ },+ {+ "type": "fragment"+ },+ {+ "type": "fragment"+ },+ {+ "type": "fragment"+ },{"type": "slide"}diff --git a/marimo/_smoke_tests/slides_examples/nested_slides.py b/marimo/_smoke_tests/slides_examples/nested_slides.pyindex f35e58283b..c1d694c1ce 100644--- a/marimo/_smoke_tests/slides_examples/nested_slides.py+++ b/marimo/_smoke_tests/slides_examples/nested_slides.py@@ -1,6 +1,6 @@import marimo-__generated_with = "0.23.2"+__generated_with = "0.23.3"app = marimo.App(width="medium",layout_file="layouts/nested_slides.slides.json",@@ -43,8 +43,7 @@ def _(mo):@app.cell(hide_code=True)def _(mo):- # Cell 4 (fragment) — second reveal on the title slide.- mo.md("""+ mo.md(r"""- Composed from flat marimo cells""")return@@ -227,6 +226,255 @@ def _(mo, secret):return+def _(mo):+ _bios_df = {+ "first_name": ["Jane", "Alex", "Doe", "Maria", "Li", "Omar"],+ "last_name": ["Smith", "Johnson", "Brown", "Garcia", "Wei", "Ali"],+ "age": [29, 35, 42, 28, 31, 45],+ "occupation": [+ "Data Scientist",+ "Product Manager",+ "Software Engineer",+ "UX Designer",+ "Researcher",+ "Entrepreneur",+ ],+ "location": [+ "San Francisco, CA",+ "New York, NY",+ "Austin, TX",+ "Boston, MA",+ "Seattle, WA",+ "Dubai, UAE",+ ],+ "email": [+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ ],+ "bio": [+ "Data scientist focused on applied ML and visualization.",+ "Product manager with a background in UX and analytics.",+ "Backend engineer specializing in scalable systems.",+ "UX designer crafting human-centered digital experiences.",+ "Researcher working on human-computer interaction.",+ "Founder and operator of several tech startups.",+ ],+ "interests": [+ "hiking, photography, cooking",+ "reading, strategy games, travel",+ "open-source, biking, woodworking",+ "illustration, prototyping, user research",+ "machine learning, teaching, chess",+ "investing, mentoring, sailing",+ ],+ "joined_date": [+ "2019-06-12",+ "2017-09-03",+ "2015-02-18",+ "2020-11-01",+ "2018-04-22",+ "2010-08-30",+ ],+ "followers": [1240, 5400, 2870, 920, 1500, 10300],+ "active": [True, True, True, True, True, False],+ }++ tbl = mo.ui.table(_bios_df)+ tbl+ return+++def _(mo):+ _bios_df = {+ "first_name": ["Jane", "Alex", "Doe", "Maria", "Li", "Omar"],+ "last_name": ["Smith", "Johnson", "Brown", "Garcia", "Wei", "Ali"],+ "age": [29, 35, 42, 28, 31, 45],+ "occupation": [+ "Data Scientist",+ "Product Manager",+ "Software Engineer",+ "UX Designer",+ "Researcher",+ "Entrepreneur",+ ],+ "location": [+ "San Francisco, CA",+ "New York, NY",+ "Austin, TX",+ "Boston, MA",+ "Seattle, WA",+ "Dubai, UAE",+ ],+ "email": [+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ ],+ "bio": [+ "Data scientist focused on applied ML and visualization.",+ "Product manager with a background in UX and analytics.",+ "Backend engineer specializing in scalable systems.",+ "UX designer crafting human-centered digital experiences.",+ "Researcher working on human-computer interaction.",+ "Founder and operator of several tech startups.",+ ],+ "interests": [+ "hiking, photography, cooking",+ "reading, strategy games, travel",+ "open-source, biking, woodworking",+ "illustration, prototyping, user research",+ "machine learning, teaching, chess",+ "investing, mentoring, sailing",+ ],+ "joined_date": [+ "2019-06-12",+ "2017-09-03",+ "2015-02-18",+ "2020-11-01",+ "2018-04-22",+ "2010-08-30",+ ],+ "followers": [1240, 5400, 2870, 920, 1500, 10300],+ "active": [True, True, True, True, True, False],+ }++ mo.ui.table(_bios_df)+ return+++def _(mo):+ _bios_df = {+ "first_name": ["Jane", "Alex", "Doe", "Maria", "Li", "Omar"],+ "last_name": ["Smith", "Johnson", "Brown", "Garcia", "Wei", "Ali"],+ "age": [29, 35, 42, 28, 31, 45],+ "occupation": [+ "Data Scientist",+ "Product Manager",+ "Software Engineer",+ "UX Designer",+ "Researcher",+ "Entrepreneur",+ ],+ "location": [+ "San Francisco, CA",+ "New York, NY",+ "Austin, TX",+ "Boston, MA",+ "Seattle, WA",+ "Dubai, UAE",+ ],+ "email": [+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ ],+ "bio": [+ "Data scientist focused on applied ML and visualization.",+ "Product manager with a background in UX and analytics.",+ "Backend engineer specializing in scalable systems.",+ "UX designer crafting human-centered digital experiences.",+ "Researcher working on human-computer interaction.",+ "Founder and operator of several tech startups.",+ ],+ "interests": [+ "hiking, photography, cooking",+ "reading, strategy games, travel",+ "open-source, biking, woodworking",+ "illustration, prototyping, user research",+ "machine learning, teaching, chess",+ "investing, mentoring, sailing",+ ],+ "joined_date": [+ "2019-06-12",+ "2017-09-03",+ "2015-02-18",+ "2020-11-01",+ "2018-04-22",+ "2010-08-30",+ ],+ "followers": [1240, 5400, 2870, 920, 1500, 10300],+ "active": [True, True, True, True, True, False],+ }++ mo.ui.table(_bios_df)+ return+++def _(mo):+ _bios_df = {+ "first_name": ["Jane", "Alex", "Doe", "Maria", "Li", "Omar"],+ "last_name": ["Smith", "Johnson", "Brown", "Garcia", "Wei", "Ali"],+ "age": [29, 35, 42, 28, 31, 45],+ "occupation": [+ "Data Scientist",+ "Product Manager",+ "Software Engineer",+ "UX Designer",+ "Researcher",+ "Entrepreneur",+ ],+ "location": [+ "San Francisco, CA",+ "New York, NY",+ "Austin, TX",+ "Boston, MA",+ "Seattle, WA",+ "Dubai, UAE",+ ],+ "email": [+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ "[email protected]",+ ],+ "bio": [+ "Data scientist focused on applied ML and visualization.",+ "Product manager with a background in UX and analytics.",+ "Backend engineer specializing in scalable systems.",+ "UX designer crafting human-centered digital experiences.",+ "Researcher working on human-computer interaction.",+ "Founder and operator of several tech startups.",+ ],+ "interests": [+ "hiking, photography, cooking",+ "reading, strategy games, travel",+ "open-source, biking, woodworking",+ "illustration, prototyping, user research",+ "machine learning, teaching, chess",+ "investing, mentoring, sailing",+ ],+ "joined_date": [+ "2019-06-12",+ "2017-09-03",+ "2015-02-18",+ "2020-11-01",+ "2018-04-22",+ "2010-08-30",+ ],+ "followers": [1240, 5400, 2870, 920, 1500, 10300],+ "active": [True, True, True, True, True, False],+ }++ mo.ui.table(_bios_df)+ return++@app.cell(hide_code=True)def _(mo):# Cell 22 (slide) — closing slide.