Skip to content

A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.

fix: handle exit code in terminal, auto-close terminal (#1873)

Myles Scolnick32a44d265161
diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
index 899bf201b5..35ad3d9a61 100644
--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
@@ -208,7 +208,10 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
>
{terminalResizeHandle}
<LazyMount isOpen={isTerminalOpen}>
- <LazyTerminal />
+ <LazyTerminal
+ visible={isTerminalOpen}
+ onClose={() => setIsTerminalOpen(false)}
+ />
</LazyMount>
</Panel>
);
diff --git a/frontend/src/components/terminal/terminal.tsx b/frontend/src/components/terminal/terminal.tsx
index 30cf39a880..4a25023519 100644
--- a/frontend/src/components/terminal/terminal.tsx
+++ b/frontend/src/components/terminal/terminal.tsx
@@ -1,46 +1,84 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { Strings } from "@/utils/strings";
-import React, { useEffect, useRef } from "react";
+import React, { useEffect, useRef, useState } from "react";
import { Terminal } from "@xterm/xterm";
import { AttachAddon } from "@xterm/addon-attach";
import { FitAddon } from "@xterm/addon-fit";
import "@xterm/xterm/css/xterm.css";
import "./xterm.css";
-const TerminalComponent = () => {
+const TerminalComponent: React.FC<{
+ visible: boolean;
+ onClose: () => void;
+}> = ({ visible, onClose }) => {
const terminalRef = useRef<HTMLDivElement>(null);
- const terminal = useRef<Terminal | null>(null);
+ // eslint-disable-next-line react/hook-use-state
+ const [{ terminal, fitAddon }] = useState(() => {
+ // Create a new terminal instance
+ const term = new Terminal({});
+ const fitAddon = new FitAddon();
+ term.loadAddon(fitAddon);
+ return { terminal: term, fitAddon };
+ });
+ const [initialized, setInitialized] = React.useState(false);
+ // Websocket Connection
useEffect(() => {
- if (!terminalRef.current || terminal.current) {
+ if (initialized) {
return;
}
- // Create a new terminal instance
- const term = new Terminal({});
- terminal.current = term;
- // Add extra addons
const socket = new WebSocket(createWsUrl());
const attachAddon = new AttachAddon(socket);
- const fitAddon = new FitAddon();
- terminal.current.loadAddon(fitAddon);
- terminal.current.loadAddon(attachAddon);
+ terminal.loadAddon(attachAddon);
+
+ const handleDisconnect = () => {
+ onClose();
+ // Reset
+ attachAddon.dispose();
+ terminal.clear();
+ setInitialized(false);
+ };
+
+ socket.addEventListener("close", handleDisconnect);
+ setInitialized(true);
+
+ return () => {
+ // noop
+ };
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [initialized]);
+ // When visible
+ useEffect(() => {
+ if (visible) {
+ fitAddon.fit();
+ terminal.focus();
+ }
+
+ return;
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [visible]);
+
+ // On mount
+ useEffect(() => {
+ if (!terminalRef.current) {
+ return;
+ }
+
+ terminal.open(terminalRef.current);
+ fitAddon.fit();
+ terminal.focus();
// Handle resize
const handleResize = () => {
fitAddon.fit();
};
window.addEventListener("resize", handleResize);
- // Open terminal
- term.open(terminalRef.current);
- fitAddon.fit();
- term.focus();
-
return () => {
- terminal.current?.dispose();
window.removeEventListener("resize", handleResize);
};
+ // eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
return (
diff --git a/marimo/_server/api/endpoints/terminal.py b/marimo/_server/api/endpoints/terminal.py
index 1477490449..91ed3a173d 100644
--- a/marimo/_server/api/endpoints/terminal.py
+++ b/marimo/_server/api/endpoints/terminal.py
@@ -7,7 +7,7 @@ import select
import signal
import subprocess
-from starlette.websockets import WebSocket, WebSocketDisconnect
+from starlette.websockets import WebSocket, WebSocketDisconnect, WebSocketState
from marimo import _loggers
from marimo._server.api.deps import AppState
@@ -48,15 +48,33 @@ async def _read_from_pty(master: int, websocket: WebSocket) -> None:
async def _write_to_pty(master: int, websocket: WebSocket) -> None:
- with os.fdopen(master, "wb", buffering=0) as master_file:
- while True:
- try:
- data = await websocket.receive_text()
- LOGGER.debug("Received: %s", data)
- master_file.write(data.encode())
- master_file.flush()
- except (asyncio.CancelledError, WebSocketDisconnect):
- break
+ try:
+ buffer = ""
+ with os.fdopen(master, "wb", buffering=0) as master_file:
+ while True:
+ try:
+ data = await websocket.receive_text()
+ LOGGER.debug("Received: %s", data)
+
+ buffer += data
+ if data in ["\r", "\n"]: # Check for line ending
+ if buffer.strip().lower() == "exit":
+ LOGGER.debug(
+ "Exit command received, closing connection"
+ )
+ # End the connection
+ return
+ buffer = "" # Reset buffer after processing a command
+
+ master_file.write(data.encode())
+ master_file.flush()
+ except (asyncio.CancelledError, WebSocketDisconnect):
+ break
+ except OSError as e:
+ if e.errno == 9: # Bad file descriptor
+ LOGGER.debug("File descriptor closed, stopping write loop")
+ return
+ raise
@router.websocket("/ws")
@@ -80,13 +98,21 @@ async def websocket_endpoint(websocket: WebSocket) -> None:
writer_task = asyncio.create_task(_write_to_pty(fd, websocket))
try:
- await asyncio.gather(reader_task, writer_task)
+ _done, pending = await asyncio.wait(
+ [reader_task, writer_task], return_when=asyncio.FIRST_COMPLETED
+ )
+ for task in pending:
+ task.cancel()
except WebSocketDisconnect:
pass
except Exception as e:
- await websocket.close()
LOGGER.exception(e)
finally:
+ try:
+ if websocket.application_state != WebSocketState.DISCONNECTED:
+ await websocket.close()
+ except RuntimeError:
+ pass
if reader_task and not reader_task.done():
reader_task.cancel()
if writer_task and not writer_task.done():