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
fix: stdin handling for empty submissions (#9556)
Shahmir Varqha9d7a8fe3bbdc
diff --git a/frontend/src/components/editor/notebook-cell.tsx b/frontend/src/components/editor/notebook-cell.tsxindex 0c556798bf..376f204394 100644--- a/frontend/src/components/editor/notebook-cell.tsx+++ b/frontend/src/components/editor/notebook-cell.tsx@@ -740,6 +740,7 @@ const EditableCellComponent = ({<ConsoleOutputconsoleOutputs={cellRuntime.consoleOutputs}stale={consoleOutputStale}+ interrupted={cellRuntime.interrupted}// Empty name if serialization triggeredcellName={cellRuntime.serialization ? "_" : cellData.name}onRefactorWithAI={handleRefactorWithAI}@@ -1204,6 +1205,7 @@ const SetupCellComponent = ({<ConsoleOutputconsoleOutputs={cellRuntime.consoleOutputs}stale={consoleOutputStale}+ interrupted={cellRuntime.interrupted}// Don't show namecellName={"_"}onRefactorWithAI={handleRefactorWithAI}diff --git a/frontend/src/components/editor/output/console/ConsoleOutput.tsx b/frontend/src/components/editor/output/console/ConsoleOutput.tsxindex 7c2bb25679..6e6cb0ac0f 100644--- a/frontend/src/components/editor/output/console/ConsoleOutput.tsx+++ b/frontend/src/components/editor/output/console/ConsoleOutput.tsx@@ -85,6 +85,7 @@ interface Props {className?: string;consoleOutputs: WithResponse<OutputMessage>[];stale: boolean;+ interrupted: boolean;debuggerActive: boolean;onRefactorWithAI?: OnRefactorWithAI;onClear?: () => void;@@ -111,6 +112,7 @@ const ConsoleOutputInternal = (props: Props): React.ReactNode => {const {consoleOutputs: rawConsoleOutputs,stale,+ interrupted,cellName,cellId,onSubmitDebugger,@@ -280,6 +282,7 @@ const ConsoleOutputInternal = (props: Props): React.ReactNode => {output={output.data}response={output.response}isPassword={isPassword}+ interrupted={interrupted}/>);}@@ -359,9 +362,9 @@ const StdInput = (props: {if (e.key === "Enter" && !e.shiftKey) {if (value) {addToHistory(value);- onSubmit(value);- setValue("");}+ onSubmit(value);+ setValue("");e.preventDefault();e.stopPropagation();}@@ -382,12 +385,27 @@ const StdInputWithResponse = (props: {output: string;response?: string;isPassword?: boolean;+ interrupted?: boolean;}) => {+ const { output, response, isPassword, interrupted } = props;+ const hasResponse = response != null && response !== "";+ const wasInterruptedWithoutResponse = interrupted && !hasResponse;+return (<div className="flex gap-2 items-center">- {renderText(props.output)}- {!props.isPassword && (- <span className="text-(--sky-11)">{props.response}</span>+ {renderText(output)}+ {!isPassword && !wasInterruptedWithoutResponse && (+ <span+ className="inline-flex items-center gap-1 text-(--sky-11)"+ aria-label="stdin response"+ >+ <ChevronRightIcon className="w-4 h-4 shrink-0 opacity-70" />+ {hasResponse ? (+ response+ ) : (+ <span className="italic opacity-70">(empty)</span>+ )}+ </span>)}</div>);diff --git a/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx b/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsxindex 7ed85f951a..f58fa08ba4 100644--- a/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx+++ b/frontend/src/components/editor/output/console/__tests__/ConsoleOutput.test.tsx@@ -28,6 +28,7 @@ describe("ConsoleOutput integration", () => {cellName: "test_cell",consoleOutputs: [] as WithResponse<OutputMessage>[],stale: false,+ interrupted: false,debuggerActive: false,onSubmitDebugger: () => {// noop@@ -59,6 +60,7 @@ describe("ConsoleOutput pdb history", () => {cellName: "test_cell",consoleOutputs: [] as WithResponse<OutputMessage>[],stale: false,+ interrupted: false,debuggerActive: false,onSubmitDebugger: vi.fn(),};@@ -118,6 +120,82 @@ describe("ConsoleOutput pdb history", () => {expect(newInput).toHaveValue("next");});+ it("should submit an empty string when Enter is pressed with no input", () => {+ // Many CLIs prompt "Press Enter to continue" and expect "" back.+ const onSubmitDebugger = vi.fn();+ const outputs: WithResponse<OutputMessage>[] = [+ stdinPrompt("Press Enter to continue: "),+ ];++ renderWithProvider(+ <ConsoleOutput+ {...defaultProps}+ consoleOutputs={outputs}+ onSubmitDebugger={onSubmitDebugger}+ />,+ );++ const input = screen.getByTestId("console-input");+ fireEvent.keyDown(input, { key: "Enter" });++ expect(onSubmitDebugger).toHaveBeenCalledWith("", 0);+ });++ it("should not record empty submissions in input history", () => {+ const onSubmitDebugger = vi.fn();+ const outputs1: WithResponse<OutputMessage>[] = [stdinPrompt("(Pdb) ")];++ const { rerender } = renderWithProvider(+ <ConsoleOutput+ {...defaultProps}+ consoleOutputs={outputs1}+ onSubmitDebugger={onSubmitDebugger}+ />,+ );++ let input = screen.getByTestId("console-input");+ fireEvent.change(input, { target: { value: "step" } });+ fireEvent.keyDown(input, { key: "Enter" });++ const outputs2: WithResponse<OutputMessage>[] = [+ stdinPrompt("(Pdb) ", "step"),+ stdinPrompt("(Pdb) "),+ ];+ rerender(+ <TooltipProvider>+ <ConsoleOutput+ {...defaultProps}+ consoleOutputs={outputs2}+ onSubmitDebugger={onSubmitDebugger}+ />+ </TooltipProvider>,+ );++ // Submit an empty value; this should NOT enter the history stack.+ input = screen.getByTestId("console-input");+ fireEvent.keyDown(input, { key: "Enter" });++ const outputs3: WithResponse<OutputMessage>[] = [+ stdinPrompt("(Pdb) ", "step"),+ stdinPrompt("(Pdb) ", ""),+ stdinPrompt("(Pdb) "),+ ];+ rerender(+ <TooltipProvider>+ <ConsoleOutput+ {...defaultProps}+ consoleOutputs={outputs3}+ onSubmitDebugger={onSubmitDebugger}+ />+ </TooltipProvider>,+ );++ // ArrowUp should jump back to "step", skipping the empty submission.+ input = screen.getByTestId("console-input");+ fireEvent.keyDown(input, { key: "ArrowUp" });+ expect(input).toHaveValue("step");+ });+it("should navigate through multiple history entries across remounts", () => {const onSubmitDebugger = vi.fn();@@ -192,6 +270,41 @@ describe("ConsoleOutput pdb history", () => {fireEvent.keyDown(input, { key: "ArrowDown" });expect(input).toHaveValue("");});++ it("should distinguish an interrupted prompt from a bare-Enter submission", () => {+ // After interrupt, cell.ts coerces pending stdin prompts to response: "".+ // We must render that case differently from a real bare-Enter response,+ // so the user isn't told they "submitted" a blank value.+ const interruptedOutputs: WithResponse<OutputMessage>[] = [+ stdinPrompt("Press Enter to continue: ", ""),+ ];++ const { rerender } = renderWithProvider(+ <ConsoleOutput+ {...defaultProps}+ consoleOutputs={interruptedOutputs}+ interrupted={true}+ />,+ );++ // No response chunk should be rendered for an interrupted pending prompt.+ expect(screen.queryByLabelText("stdin response")).not.toBeInTheDocument();++ // Same outputs, but the cell isn't interrupted -- this is a real+ // bare-Enter submission, so we should render the (empty) placeholder.+ rerender(+ <TooltipProvider>+ <ConsoleOutput+ {...defaultProps}+ consoleOutputs={interruptedOutputs}+ interrupted={false}+ />+ </TooltipProvider>,+ );++ expect(screen.getByLabelText("stdin response")).toBeInTheDocument();+ expect(screen.getByText("(empty)")).toBeInTheDocument();+ });});describe("ConsoleOutput debounced clearing", () => {@@ -219,6 +332,7 @@ describe("ConsoleOutput debounced clearing", () => {cellName: "test_cell",consoleOutputs: [] as WithResponse<OutputMessage>[],stale: false,+ interrupted: false,debuggerActive: false,onSubmitDebugger: vi.fn(),};diff --git a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsxindex b52e10b690..6b244c873d 100644--- a/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx+++ b/frontend/src/components/editor/renderers/vertical-layout/vertical-layout.tsx@@ -405,6 +405,7 @@ const VerticalCell = memo(<ConsoleOutputconsoleOutputs={consoleOutputs}stale={outputStale}+ interrupted={interrupted}cellName={name}onSubmitDebugger={() => null}cellId={cellId}diff --git a/frontend/src/components/scratchpad/scratchpad.tsx b/frontend/src/components/scratchpad/scratchpad.tsxindex 25bb59ce80..e9ab5ddf58 100644--- a/frontend/src/components/scratchpad/scratchpad.tsx+++ b/frontend/src/components/scratchpad/scratchpad.tsx@@ -289,6 +289,7 @@ export const ScratchPad: React.FC = () => {consoleOutputs={consoleOutputs}className="overflow-auto"stale={false}+ interrupted={false}cellName={DEFAULT_CELL_NAME}onSubmitDebugger={Functions.NOOP}cellId={cellId}diff --git a/marimo/_messaging/streams.py b/marimo/_messaging/streams.pyindex dac6b69f75..8a1d5f0d2f 100644--- a/marimo/_messaging/streams.py+++ b/marimo/_messaging/streams.py@@ -466,20 +466,6 @@ class ThreadSafeStdin(Stdin):return self._stream.input_queue.get()- def readline(self, size: int | None = -1) -> str: # type: ignore[override]- # size only included for compatibility with sys.stdin.readline API;- # we don't support it.- del size- return self._readline_with_prompt(prompt="")-- def readlines(self, hint: int | None = -1) -> list[str]: # type: ignore[override]- # Just an alias for readline.- #- # hint only included for compatibility with sys.stdin.readlines API;- # we don't support it.- del hint- return self._readline_with_prompt(prompt="").split("\n")-@contextlib.contextmanagerdef redirect(standard_stream: Stdout | Stderr) -> Iterator[None]:diff --git a/marimo/_messaging/types.py b/marimo/_messaging/types.pyindex 65c72634e8..319b5cc313 100644--- a/marimo/_messaging/types.py+++ b/marimo/_messaging/types.py@@ -63,7 +63,7 @@ def _ensure_plain_str(s: str) -> str:# These streams are not stoppable by users (we don't implement stop).-class Stdout(io.TextIOBase):+class Stdout(io.TextIOBase, abc.ABC):name = "stdout"@abc.abstractmethod@@ -81,7 +81,7 @@ class Stdout(io.TextIOBase):"""Tear down resources, if any."""-class Stderr(io.TextIOBase):+class Stderr(io.TextIOBase, abc.ABC):name = "stderr"@abc.abstractmethod@@ -99,9 +99,32 @@ class Stderr(io.TextIOBase):"""Tear down resources, if any."""-class Stdin(io.TextIOBase):+class Stdin(io.TextIOBase, abc.ABC):name = "stdin"+ @abc.abstractmethod+ def _readline_with_prompt(+ self, prompt: str = "", password: bool = False+ ) -> str:+ """Send a prompt to the frontend and return the user's bare response.++ Subclasses implement the transport. Returns the user-typed text+ without a trailing newline (matches Python's input() contract).+ """++ # `size` and `hint` are accepted for sys.stdin API compatibility but+ # ignored: marimo's stdin is a single-prompt pseudofile.++ def readline(self, size: int | None = -1) -> str: # type: ignore[override]+ del size+ # Trailing "\n" is required so a blank submission doesn't look like+ # EOF to builtin input() (used by rich, click, getpass, pdb, etc.).+ return self._readline_with_prompt(prompt="") + "\n"++ def readlines(self, hint: int | None = -1) -> list[str]: # type: ignore[override]+ del hint+ return [self.readline()]+def _stop(self) -> None:"""Tear down resources, if any."""diff --git a/marimo/_pyodide/streams.py b/marimo/_pyodide/streams.pyindex cb902fbf00..266d72c56b 100644--- a/marimo/_pyodide/streams.py+++ b/marimo/_pyodide/streams.py@@ -179,17 +179,3 @@ class PyodideStdin(Stdin):def _get_response(self) -> str:loop = asyncio.get_event_loop()return loop.run_until_complete(self.stream.input_queue.get())-- def readline(self, size: int | None = -1) -> str: # type: ignore[override]- # size only included for compatibility with sys.stdin.readline API;- # we don't support it.- del size- return self._readline_with_prompt(prompt="")-- def readlines(self, hint: int | None = -1) -> list[str]: # type: ignore[override]- # Just an alias for readline.- #- # hint only included for compatibility with sys.stdin.readlines API;- # we don't support it.- del hint- return self._readline_with_prompt(prompt="").split("\n")diff --git a/tests/_messaging/test_streams.py b/tests/_messaging/test_streams.pyindex 52198bac84..6a4e16e29c 100644--- a/tests/_messaging/test_streams.py+++ b/tests/_messaging/test_streams.py@@ -25,7 +25,7 @@ class TestStdin:await k.run([exec_req.get("import sys; output = sys.stdin.readline()")])- assert k.globals["output"] == ""+ assert k.globals["output"] == "\n"@staticmethodasync def test_readlines_installed(@@ -34,7 +34,19 @@ class TestStdin:await k.run([exec_req.get("import sys; output = sys.stdin.readlines()")])- assert k.globals["output"] == [""]+ assert k.globals["output"] == ["\n"]++ @staticmethod+ async def test_builtin_input_with_empty_response(+ k: Kernel, exec_req: ExecReqProvider+ ) -> None:+ # Bypasses the cell-scoped input override, exercising the same+ # readline()-based path that rich/click/getpass/pdb hit. Must not+ # raise EOFError on an empty submission.+ await k.run(+ [exec_req.get("import builtins; output = builtins.input()")]+ )+ assert k.globals["output"] == ""@staticmethodasync def test_getpass_installed(diff --git a/tests/_messaging/test_types.py b/tests/_messaging/test_types.pyindex 1bf372429f..cfee7b8dc4 100644--- a/tests/_messaging/test_types.py+++ b/tests/_messaging/test_types.py@@ -146,12 +146,19 @@ class TestStdoutStderr:class TestStdin:+ class MockStdin(Stdin):+ def _readline_with_prompt(+ self, prompt: str = "", password: bool = False+ ) -> str:+ del prompt, password+ return ""+def test_stdin_name(self) -> None:- stdin = Stdin()+ stdin = self.MockStdin()assert stdin.name == "stdin"def test_not_stoppable(self) -> None:- stdin = Stdin()+ stdin = self.MockStdin()assert not hasattr(stdin, "stop")diff --git a/tests/_pyodide/test_pyodide_streams.py b/tests/_pyodide/test_pyodide_streams.pyindex 779690f08a..731898358a 100644--- a/tests/_pyodide/test_pyodide_streams.py+++ b/tests/_pyodide/test_pyodide_streams.py@@ -45,8 +45,9 @@ def pyodide_stderr(pyodide_: PyodideStream) -> PyodideStderr:@pytest.fixturedef pyodide_stdin(pyodide_: PyodideStream) -> PyodideStdin:+ # bridge.ts -> put_input sends raw user text; readline() adds the "\n".stdin = PyodideStdin(pyodide_)- stdin._get_response = lambda: "test input\n"+ stdin._get_response = lambda: "test input"return stdin@@ -132,12 +133,9 @@ class TestPyodideStdin:pyodide_pipe: Mock,pyodide_input_queue: asyncio.Queue[str],) -> None:- # Queue up a response- await pyodide_input_queue.put("test input\n")- # Read the line+ await pyodide_input_queue.put("test input")result = pyodide_stdin.readline()assert result == "test input\n"- # Verify prompt was sentassert pyodide_pipe.call_count == 1msg_bytes = pyodide_pipe.call_args[0][0]msg = json.loads(msg_bytes)@@ -152,12 +150,11 @@ class TestPyodideStdin:pyodide_pipe: Mock,pyodide_input_queue: asyncio.Queue[str],) -> None:- # Queue up a response- await pyodide_input_queue.put("test input\n")- # Read the line with prompt+ await pyodide_input_queue.put("test input")+ # The _readline_with_prompt primitive returns bare text; the "\n"+ # is only added by readline() for file-protocol consumers.result = pyodide_stdin._readline_with_prompt("Enter: ")- assert result == "test input\n"- # Verify prompt was sent+ assert result == "test input"assert pyodide_pipe.call_count == 1msg_bytes = pyodide_pipe.call_args[0][0]msg = json.loads(msg_bytes)@@ -172,16 +169,11 @@ class TestPyodideStdin:pyodide_pipe: Mock,pyodide_input_queue: asyncio.Queue[str],) -> None:- pyodide_stdin._get_response = Mock(- return_value="line1\nline2\nline3\n"- )+ pyodide_stdin._get_response = Mock(return_value="hello")- # Queue up a response- await pyodide_input_queue.put("line1\nline2\nline3\n")- # Read the lines+ await pyodide_input_queue.put("hello")result = pyodide_stdin.readlines()- assert result == ["line1", "line2", "line3", ""]- # Verify prompt was sent+ assert result == ["hello\n"]assert pyodide_pipe.call_count == 1msg_bytes = pyodide_pipe.call_args[0][0]msg = json.loads(msg_bytes)@@ -189,3 +181,13 @@ class TestPyodideStdin:assert msg["cell_id"] == pyodide_stdin.stream.cell_idassert msg["console"]["mimetype"] == "text/plain"assert msg["console"]["data"] == ""++ async def test_readline_empty_submission(+ self,+ pyodide_stdin: PyodideStdin,+ pyodide_input_queue: asyncio.Queue[str],+ ) -> None:+ # Empty submission must be a blank line ("\n"), not "" (= EOF).+ pyodide_stdin._get_response = lambda: ""+ await pyodide_input_queue.put("")+ assert pyodide_stdin.readline() == "\n"