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.

feat: terminal panel (#1786)

Myles Scolnick63a254854e66
diff --git a/frontend/package.json b/frontend/package.json
index 6621c6ffdc..acc3fb9bd4 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -78,6 +78,9 @@
"@uiw/codemirror-extensions-langs": "^4.22.2",
"@uiw/react-codemirror": "^4.22.2",
"@valtown/codemirror-codeium": "^1.0.2",
+ "@xterm/addon-attach": "^0.11.0",
+ "@xterm/addon-fit": "^0.10.0",
+ "@xterm/xterm": "^5.5.0",
"ai": "^3.2.16",
"ansi_up": "^6.0.2",
"class-variance-authority": "^0.7.0",
diff --git a/frontend/pnpm-lock.yaml b/frontend/pnpm-lock.yaml
index bb734f6932..d40c905915 100644
--- a/frontend/pnpm-lock.yaml
+++ b/frontend/pnpm-lock.yaml
@@ -200,6 +200,15 @@ dependencies:
'@valtown/codemirror-codeium':
specifier: ^1.0.2
version: 1.0.2(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])
+ '@xterm/addon-attach':
+ specifier: ^0.11.0
+ version: 0.11.0(@xterm/[email protected])
+ '@xterm/addon-fit':
+ specifier: ^0.10.0
+ version: 0.10.0(@xterm/[email protected])
+ '@xterm/xterm':
+ specifier: ^5.5.0
+ version: 5.5.0
ai:
specifier: ^3.2.16
@@ -9435,6 +9444,26 @@ packages:
'@xtuc/long': 4.2.2
dev: false
+ resolution: {integrity: sha512-JboCN0QAY6ZLY/SSB/Zl2cQ5zW1Eh4X3fH7BnuR1NB7xGRhzbqU2Npmpiw/3zFlxDaU88vtKzok44JKi2L2V2Q==}
+ peerDependencies:
+ '@xterm/xterm': ^5.0.0
+ dependencies:
+ '@xterm/xterm': 5.5.0
+ dev: false
+
+ resolution: {integrity: sha512-UFYkDm4HUahf2lnEyHvio51TNGiLK66mqP2JoATy7hRZeXaGMRDr00JiSF7m63vR5WKATF605yEggJKsw0JpMQ==}
+ peerDependencies:
+ '@xterm/xterm': ^5.0.0
+ dependencies:
+ '@xterm/xterm': 5.5.0
+ dev: false
+
+ resolution: {integrity: sha512-hqJHYaQb5OptNunnyAnkHyM8aCjZ1MEIDTQu1iIbbTD/xops91NB5yq1ZK/dC2JDbVWtF23zUtl9JE2NqwT87A==}
+ dev: false
+
resolution: {integrity: sha512-DX8nKgqcGwsc0eJSqYt5lwP4DH5FlHnmuWWBRy7X0NcaGR0ZtuyeESgMwTYVEtxmsNGY+qit4QYT/MIYTOTPeA==}
dev: false
diff --git a/frontend/src/components/editor/boundary/ErrorBoundary.tsx b/frontend/src/components/editor/boundary/ErrorBoundary.tsx
index 4a6eccbd6a..01d8fef69c 100644
--- a/frontend/src/components/editor/boundary/ErrorBoundary.tsx
+++ b/frontend/src/components/editor/boundary/ErrorBoundary.tsx
@@ -1,8 +1,8 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { PropsWithChildren } from "react";
+import type { PropsWithChildren } from "react";
import {
ErrorBoundary as ReactErrorBoundary,
- FallbackProps,
+ type FallbackProps,
} from "react-error-boundary";
import { Button } from "../../ui/button";
import { Constants } from "@/core/constants";
diff --git a/frontend/src/components/editor/chrome/state.ts b/frontend/src/components/editor/chrome/state.ts
index d367809e34..73904efa81 100644
--- a/frontend/src/components/editor/chrome/state.ts
+++ b/frontend/src/components/editor/chrome/state.ts
@@ -1,14 +1,14 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { createReducerAndAtoms } from "@/utils/createReducer";
import { useAtomValue } from "jotai";
-import { PanelType } from "./types";
+import type { PanelType } from "./types";
import { ZodLocalStorage } from "@/utils/localStorage";
import { z } from "zod";
export interface ChromeState {
selectedPanel: PanelType | undefined;
- isOpen: boolean;
- panelLocation: "left" | "bottom";
+ isSidebarOpen: boolean;
+ isTerminalOpen: boolean;
}
const storage = new ZodLocalStorage<ChromeState>(
@@ -18,8 +18,8 @@ const storage = new ZodLocalStorage<ChromeState>(
.string()
.optional()
.transform((v) => v as PanelType),
- isOpen: z.boolean(),
- panelLocation: z.union([z.literal("left"), z.literal("bottom")]),
+ isSidebarOpen: z.boolean(),
+ isTerminalOpen: z.boolean(),
}),
initialState,
);
@@ -27,8 +27,8 @@ const storage = new ZodLocalStorage<ChromeState>(
function initialState(): ChromeState {
return {
selectedPanel: "variables", // initial panel
- isOpen: false,
- panelLocation: "left",
+ isSidebarOpen: false,
+ isTerminalOpen: false,
};
}
@@ -45,15 +45,25 @@ const {
selectedPanel,
// If it was closed, open it
// If it was open, keep it open unless it was the same application
- isOpen: state.isOpen ? state.selectedPanel !== selectedPanel : true,
+ isSidebarOpen: state.isSidebarOpen
+ ? state.selectedPanel !== selectedPanel
+ : true,
}),
- openPanel: (state) => ({ ...state, isOpen: true }),
- closePanel: (state) => ({ ...state, isOpen: false }),
- togglePanel: (state) => ({ ...state, isOpen: !state.isOpen }),
- setIsOpen: (state, isOpen: boolean) => ({ ...state, isOpen }),
- changePanelLocation: (state, panelLocation: "left" | "bottom") => ({
+ toggleSidebarPanel: (state) => ({
...state,
- panelLocation,
+ isSidebarOpen: !state.isSidebarOpen,
+ }),
+ setIsSidebarOpen: (state, isOpen: boolean) => ({
+ ...state,
+ isSidebarOpen: isOpen,
+ }),
+ toggleTerminal: (state) => ({
+ ...state,
+ isTerminalOpen: !state.isTerminalOpen,
+ }),
+ setIsTerminalOpen: (state, isOpen: boolean) => ({
+ ...state,
+ isTerminalOpen: isOpen,
}),
},
[(_prevState, newState) => storage.set(newState)],
@@ -61,7 +71,7 @@ const {
export const useChromeState = () => {
const state = useAtomValue(chromeAtom);
- if (state.isOpen) {
+ if (state.isSidebarOpen) {
return state;
}
return {
diff --git a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
index 01c515d43a..899bf201b5 100644
--- a/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/app-chrome.tsx
@@ -24,15 +24,17 @@ import { FileExplorerPanel } from "../panels/file-explorer-panel";
import { SnippetsPanel } from "../panels/snippets-panel";
import { ErrorBoundary } from "../../boundary/ErrorBoundary";
import { DataSourcesPanel } from "../panels/datasources-panel";
+import { LazyMount } from "@/components/utils/lazy-mount";
import { ScratchpadPanel } from "../panels/scratchpad-panel";
+import { IfCapability } from "@/core/config/if-capability";
+
+const LazyTerminal = React.lazy(() => import("@/components/terminal/terminal"));
export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
- const { isOpen, selectedPanel } = useChromeState();
- const { setIsOpen } = useChromeActions();
+ const { isSidebarOpen, isTerminalOpen, selectedPanel } = useChromeState();
+ const { setIsSidebarOpen, setIsTerminalOpen } = useChromeActions();
const sidebarRef = React.useRef<ImperativePanelHandle>(null);
- // We only support 'left' for now
- // We may add support for a bottom bar, but currently it forces the app to remount
- const panelLocation = "left";
+ const terminalRef = React.useRef<ImperativePanelHandle>(null);
// sync sidebar
useEffect(() => {
@@ -41,10 +43,10 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
}
const isCurrentlyCollapsed = sidebarRef.current.isCollapsed();
- if (isOpen && isCurrentlyCollapsed) {
+ if (isSidebarOpen && isCurrentlyCollapsed) {
sidebarRef.current.expand();
}
- if (!isOpen && !isCurrentlyCollapsed) {
+ if (!isSidebarOpen && !isCurrentlyCollapsed) {
sidebarRef.current.collapse();
}
@@ -56,26 +58,63 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
window.dispatchEvent(new Event("resize"));
});
});
- }, [isOpen]);
+ }, [isSidebarOpen]);
+
+ // sync terminal
+ useEffect(() => {
+ if (!terminalRef.current) {
+ return;
+ }
+
+ const isCurrentlyCollapsed = terminalRef.current.isCollapsed();
+ if (isTerminalOpen && isCurrentlyCollapsed) {
+ terminalRef.current.expand();
+ }
+ if (!isTerminalOpen && !isCurrentlyCollapsed) {
+ terminalRef.current.collapse();
+ }
- const appBody = (
- <Panel id="app" key={`app-${panelLocation}`} className="relative h-full">
+ // Dispatch a resize event so widgets know to resize
+ requestAnimationFrame(() => {
+ // HACK: Unfortunately, we have to do this twice to make sure it the
+ // panel is fully expanded before we dispatch the resize event
+ requestAnimationFrame(() => {
+ window.dispatchEvent(new Event("resize"));
+ });
+ });
+ }, [isTerminalOpen]);
+
+ const appBodyPanel = (
+ <Panel id="app" key="app" className="relative h-full">
<Suspense>{children}</Suspense>
</Panel>
);
- const resizeHandle = (
+ const handleDragging = (isDragging: boolean) => {
+ if (!isDragging) {
+ // Once the user is done dragging, dispatch a resize event
+ window.dispatchEvent(new Event("resize"));
+ }
+ };
+
+ const helperResizeHandle = (
<PanelResizeHandle
- onDragging={(isDragging) => {
- if (!isDragging) {
- // Once the user is done dragging, dispatch a resize event
- window.dispatchEvent(new Event("resize"));
- }
- }}
+ onDragging={handleDragging}
className={cn(
"border-border no-print z-10",
- isOpen ? "resize-handle" : "resize-handle-collapsed",
- panelLocation === "left" ? "vertical" : "horizontal",
+ isSidebarOpen ? "resize-handle" : "resize-handle-collapsed",
+ "vertical",
+ )}
+ />
+ );
+
+ const terminalResizeHandle = (
+ <PanelResizeHandle
+ onDragging={handleDragging}
+ className={cn(
+ "border-border no-print z-20",
+ isTerminalOpen ? "resize-handle" : "resize-handle-collapsed",
+ "horizontal",
)}
/>
);
@@ -93,7 +132,7 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
className="m-0"
size="xs"
variant="text"
- onClick={() => setIsOpen(false)}
+ onClick={() => setIsSidebarOpen(false)}
>
<XIcon className="w-4 h-4" />
</Button>
@@ -113,16 +152,16 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
</ErrorBoundary>
);
- const helperPane = (
+ const helperPanel = (
<Panel
ref={sidebarRef}
id="helper"
- key={`helper-${panelLocation}`}
+ key={"helper"}
collapsedSize={0}
collapsible={true}
className={cn(
"dark:bg-[var(--slate-1)] no-print",
- isOpen && "border-r border-l border-[var(--slate-7)]",
+ isSidebarOpen && "border-r border-l border-[var(--slate-7)]",
)}
minSize={10}
// We can't make the default size greater than 0, otherwise it will start open
@@ -134,34 +173,61 @@ export const AppChrome: React.FC<PropsWithChildren> = ({ children }) => {
sidebarRef.current?.resize(30);
}
}}
- onCollapse={() => setIsOpen(false)}
- onExpand={() => setIsOpen(true)}
+ onCollapse={() => setIsSidebarOpen(false)}
+ onExpand={() => setIsSidebarOpen(true)}
>
- {panelLocation === "left" ? (
- <span className="flex flex-row h-full">
- {helpPaneBody} {resizeHandle}
- </span>
- ) : (
- <span>
- {resizeHandle} {helpPaneBody}
- </span>
+ <span className="flex flex-row h-full">
+ {helpPaneBody} {helperResizeHandle}
+ </span>
+ </Panel>
+ );
+
+ const terminalPanel = (
+ <Panel
+ ref={terminalRef}
+ id="terminal"
+ key={"terminal"}
+ collapsedSize={0}
+ collapsible={true}
+ className={cn(
+ "dark:bg-[var(--slate-1)] no-print",
+ isTerminalOpen && "border-[var(--slate-7)]",
)}
+ minSize={10}
+ // We can't make the default size greater than 0, otherwise it will start open
+ defaultSize={0}
+ maxSize={75}
+ onResize={(size, prevSize) => {
+ // This means it started closed and is opening for the first time
+ if (prevSize === 0 && size === 10) {
+ terminalRef.current?.resize(30);
+ }
+ }}
+ onCollapse={() => setIsTerminalOpen(false)}
+ onExpand={() => setIsTerminalOpen(true)}
+ >
+ {terminalResizeHandle}
+ <LazyMount isOpen={isTerminalOpen}>
+ <LazyTerminal />
+ </LazyMount>
</Panel>
);
- // If we ever support panelLocation !== left, this layout needs to be
- // updated.
return (
<div className="flex flex-col flex-1 overflow-hidden absolute inset-0">
<PanelGroup
- key={panelLocation}
- autoSaveId={`marimo:chrome`}
- direction={panelLocation === "left" ? "horizontal" : "vertical"}
- storage={createStorage(panelLocation)}
+ autoSaveId="marimo:chrome:v1:l2"
+ direction={"horizontal"}
+ storage={createStorage("left")}
>
<Sidebar />
- {helperPane}
- {appBody}
+ {helperPanel}
+ <Panel>
+ <PanelGroup autoSaveId="marimo:chrome:v1:l1" direction="vertical">
+ {appBodyPanel}
+ <IfCapability capability="terminal">{terminalPanel}</IfCapability>
+ </PanelGroup>
+ </Panel>
</PanelGroup>
<ErrorBoundary>
<Footer />
diff --git a/frontend/src/components/editor/chrome/wrapper/footer.tsx b/frontend/src/components/editor/chrome/wrapper/footer.tsx
index fed266dc23..4b5347e681 100644
--- a/frontend/src/components/editor/chrome/wrapper/footer.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/footer.tsx
@@ -9,15 +9,16 @@ import { cellErrorCount } from "@/core/cells/cells";
import { type PanelDescriptor, PANELS } from "../types";
import { MachineStats } from "./machine-stats";
import { useUserConfig } from "@/core/config/config";
-import { ZapIcon, ZapOffIcon } from "lucide-react";
+import { TerminalSquareIcon, ZapIcon, ZapOffIcon } from "lucide-react";
import { saveUserConfig } from "@/core/network/requests";
import type { UserConfig } from "@/core/config/config-schema";
import { ShowInKioskMode } from "../../kiosk-mode";
import { invariant } from "@/utils/invariant";
+import { IfCapability } from "@/core/config/if-capability";
export const Footer: React.FC = () => {
- const { selectedPanel } = useChromeState();
- const { openApplication } = useChromeActions();
+ const { selectedPanel, isTerminalOpen } = useChromeState();
+ const { openApplication, toggleTerminal } = useChromeActions();
const [config, setConfig] = useUserConfig();
const errorCount = useAtomValue(cellErrorCount);
@@ -39,6 +40,16 @@ export const Footer: React.FC = () => {
<span className="ml-1 font-mono mt-[0.125rem]">{errorCount}</span>
</FooterItem>
+ <IfCapability capability="terminal">
+ <FooterItem
+ tooltip="Open terminal"
+ selected={isTerminalOpen}
+ onClick={() => toggleTerminal()}
+ >
+ <TerminalSquareIcon className="h-5 w-5" />
+ </FooterItem>
+ </IfCapability>
+
<FooterItem
tooltip={
config.runtime.auto_instantiate
diff --git a/frontend/src/components/editor/chrome/wrapper/storage.ts b/frontend/src/components/editor/chrome/wrapper/storage.ts
index 2c48835e00..4375aa83f2 100644
--- a/frontend/src/components/editor/chrome/wrapper/storage.ts
+++ b/frontend/src/components/editor/chrome/wrapper/storage.ts
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { PanelGroupStorage } from "react-resizable-panels";
+import type { PanelGroupStorage } from "react-resizable-panels";
import { z } from "zod";
import { Objects } from "@/utils/objects";
diff --git a/frontend/src/components/editor/renderers/CellArray.tsx b/frontend/src/components/editor/renderers/CellArray.tsx
index 5958a2bcf7..d5269f42cc 100644
--- a/frontend/src/components/editor/renderers/CellArray.tsx
+++ b/frontend/src/components/editor/renderers/CellArray.tsx
@@ -60,14 +60,14 @@ export const CellArray: React.FC<CellArrayProps> = ({
}) => {
const actions = useCellActions();
const { theme } = useTheme();
- const { togglePanel } = useChromeActions();
+ const { toggleSidebarPanel } = useChromeActions();
const { invisible } = useDelayVisibility(notebook.cellIds.length, mode);
// HOTKEYS
useHotkey("global.focusTop", actions.focusTopCell);
useHotkey("global.focusBottom", actions.focusBottomCell);
- useHotkey("global.toggleSidebar", togglePanel);
+ useHotkey("global.toggleSidebar", toggleSidebarPanel);
useHotkey("global.foldCode", actions.foldAll);
useHotkey("global.unfoldCode", actions.unfoldAll);
useHotkey("global.formatAll", () => {
diff --git a/frontend/src/components/terminal/terminal.tsx b/frontend/src/components/terminal/terminal.tsx
new file mode 100644
index 0000000000..30cf39a880
--- /dev/null
+++ b/frontend/src/components/terminal/terminal.tsx
@@ -0,0 +1,64 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { Strings } from "@/utils/strings";
+import React, { useEffect, useRef } 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 terminalRef = useRef<HTMLDivElement>(null);
+ const terminal = useRef<Terminal | null>(null);
+
+ useEffect(() => {
+ if (!terminalRef.current || terminal.current) {
+ 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);
+
+ // 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);
+ };
+ }, []);
+
+ return (
+ <div className="relative w-full h-[calc(100%-4px)] dark bg-[var(--slate-1)]">
+ <div className="w-full h-full" ref={terminalRef} />
+ </div>
+ );
+};
+
+export function createWsUrl(): string {
+ const baseURI = document.baseURI;
+
+ const url = new URL(baseURI);
+ const protocol = url.protocol === "https:" ? "wss" : "ws";
+ url.protocol = protocol;
+ url.pathname = `${Strings.withoutTrailingSlash(url.pathname)}/terminal/ws`;
+
+ return url.toString();
+}
+
+export default React.memo(TerminalComponent);
diff --git a/frontend/src/components/terminal/xterm.css b/frontend/src/components/terminal/xterm.css
new file mode 100644
index 0000000000..de1a06ff7c
--- /dev/null
+++ b/frontend/src/components/terminal/xterm.css
@@ -0,0 +1,3 @@
+.xterm {
+ padding: .5rem;
+}
diff --git a/frontend/src/components/utils/lazy-mount.tsx b/frontend/src/components/utils/lazy-mount.tsx
new file mode 100644
index 0000000000..0c351ec3ce
--- /dev/null
+++ b/frontend/src/components/utils/lazy-mount.tsx
@@ -0,0 +1,24 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React, { type PropsWithChildren } from "react";
+
+interface Props {
+ isOpen: boolean;
+}
+
+/**
+ * Lazy-mount until it is open for the first time
+ */
+export const LazyMount: React.FC<PropsWithChildren<Props>> = ({
+ isOpen,
+ children,
+}) => {
+ const [isMounted, setIsMounted] = React.useState(false);
+
+ React.useEffect(() => {
+ if (isOpen && !isMounted) {
+ setIsMounted(true);
+ }
+ }, [isOpen, isMounted]);
+
+ return isMounted ? children : null;
+};
diff --git a/frontend/src/core/codemirror/language/__tests__/extension.test.ts b/frontend/src/core/codemirror/language/__tests__/extension.test.ts
index 8ccc26747f..8163a827ef 100644
--- a/frontend/src/core/codemirror/language/__tests__/extension.test.ts
+++ b/frontend/src/core/codemirror/language/__tests__/extension.test.ts
@@ -34,6 +34,7 @@ describe("getInitialLanguageAdapter", () => {
beforeAll(() => {
store.set(capabilitiesAtom, {
sql: true,
+ terminal: true,
});
});
diff --git a/frontend/src/core/codemirror/language/__tests__/sql.test.ts b/frontend/src/core/codemirror/language/__tests__/sql.test.ts
index 8387d5be23..223668b703 100644
--- a/frontend/src/core/codemirror/language/__tests__/sql.test.ts
+++ b/frontend/src/core/codemirror/language/__tests__/sql.test.ts
@@ -10,6 +10,7 @@ describe("SQLLanguageAdapter", () => {
beforeAll(() => {
store.set(capabilitiesAtom, {
sql: true,
+ terminal: true,
});
});
diff --git a/frontend/src/core/config/capabilities.ts b/frontend/src/core/config/capabilities.ts
index d9e6b41e47..3806c040c5 100644
--- a/frontend/src/core/config/capabilities.ts
+++ b/frontend/src/core/config/capabilities.ts
@@ -4,4 +4,5 @@ import { Capabilities } from "../kernel/messages";
export const capabilitiesAtom = atom<Capabilities>({
sql: false,
+ terminal: false,
});
diff --git a/frontend/src/core/config/if-capability.tsx b/frontend/src/core/config/if-capability.tsx
new file mode 100644
index 0000000000..38e57cd012
--- /dev/null
+++ b/frontend/src/core/config/if-capability.tsx
@@ -0,0 +1,18 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import React from "react";
+import { Capabilities } from "../kernel/messages";
+import { useAtomValue } from "jotai";
+import { capabilitiesAtom } from "./capabilities";
+
+interface Props {
+ capability: keyof Capabilities;
+ children: React.ReactNode;
+}
+
+export const IfCapability: React.FC<Props> = (props) => {
+ const value = useAtomValue(capabilitiesAtom)[props.capability];
+ if (value) {
+ return props.children;
+ }
+ return null;
+};
diff --git a/frontend/src/utils/strings.ts b/frontend/src/utils/strings.ts
index a15a4fcdfc..5e90b509c9 100644
--- a/frontend/src/utils/strings.ts
+++ b/frontend/src/utils/strings.ts
@@ -36,4 +36,8 @@ export const Strings = {
.replaceAll("'", "&#039;")
.replaceAll("\n", " ");
},
+
+ withoutTrailingSlash(url: string): string {
+ return url.endsWith("/") ? url.slice(0, -1) : url;
+ },
};
diff --git a/frontend/vite.config.mts b/frontend/vite.config.mts
index 630efe3301..858694aae2 100644
--- a/frontend/vite.config.mts
+++ b/frontend/vite.config.mts
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import { defineConfig, Plugin } from "vite";
+import { defineConfig, type Plugin } from "vite";
import react from "@vitejs/plugin-react-swc";
import tsconfigPaths from "vite-tsconfig-paths";
import { JSDOM } from "jsdom";
@@ -133,6 +133,14 @@ export default defineConfig({
origin: TARGET,
},
},
+ "/terminal/ws": {
+ target: `ws://${HOST}:${SERVER_PORT}`,
+ ws: true,
+ changeOrigin: true,
+ headers: {
+ origin: TARGET,
+ },
+ },
},
headers: isPyodide
? {
diff --git a/marimo/_cli/cli.py b/marimo/_cli/cli.py
index d11f2717b9..6fb4fa231f 100644
--- a/marimo/_cli/cli.py
+++ b/marimo/_cli/cli.py
@@ -285,7 +285,13 @@ def edit(
try:
with open(name, "w"):
pass
- except OSError:
+ except OSError as e:
+ if isinstance(e, FileNotFoundError):
+ # This means that the parent directory does not exist
+ parent_dir = os.path.dirname(name)
+ raise click.ClickException(
+ f"Parent directory does not exist: {parent_dir}"
+ ) from e
raise
else:
name = os.getcwd()
diff --git a/marimo/_cli/development/commands.py b/marimo/_cli/development/commands.py
index f732cd6be6..b8f906c508 100644
--- a/marimo/_cli/development/commands.py
+++ b/marimo/_cli/development/commands.py
@@ -1,7 +1,7 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
-from typing import Any, Dict
+from typing import TYPE_CHECKING, Any, Dict
import click
from starlette.schemas import SchemaGenerator
@@ -18,6 +18,7 @@ import marimo._server.models.models as models
import marimo._snippets.snippets as snippets
from marimo import __version__
from marimo._ast.cell import CellConfig, CellStatusType
+from marimo._cli.print import orange
from marimo._config.config import MarimoConfig
from marimo._messaging.cell_output import CellChannel, CellOutput
from marimo._messaging.mimetypes import KnownMimeType
@@ -28,6 +29,9 @@ from marimo._utils.dataclass_to_openapi import (
PythonTypeToOpenAPI,
)
+if TYPE_CHECKING:
+ import psutil
+
def _generate_schema() -> dict[str, Any]:
# dataclass components used in websocket messages
@@ -243,4 +247,77 @@ def openapi() -> None:
print(yaml.dump(_generate_schema(), default_flow_style=False))
[email protected](help="Various commands for the marimo processes", hidden=True)
+def ps() -> None:
+ pass
+
+
+def get_marimo_processes() -> list["psutil.Process"]:
+ import psutil
+
+ def is_marimo_process(proc: psutil.Process) -> bool:
+ if proc.name() == "marimo":
+ return True
+
+ if proc.name().lower() == "python":
+ try:
+ cmds = proc.cmdline()
+ except psutil.AccessDenied:
+ return False
+ except psutil.ZombieProcess:
+ return False
+ # any endswith marimo
+ has_marimo = any(x.endswith("marimo") for x in cmds)
+ # any command equals "tutorial", "edit", or "run"
+ has_running_command = any(
+ x in {"run", "tutorial", "edit"} for x in cmds
+ )
+ return has_marimo and has_running_command
+
+ return False
+
+ result: list[psutil.Process] = []
+
+ for proc in psutil.process_iter():
+ if is_marimo_process(proc):
+ result.append(proc)
+
+ return result
+
+
[email protected](help="List the marimo processes", name="list")
+def list_processes() -> None:
+ """
+ Example usage:
+
+ marimo development ps list
+ """
+ # pretty print processes
+ result = get_marimo_processes()
+ for proc in result:
+ cmds = proc.cmdline()
+ cmd = " ".join(cmds[1:])
+ print(f"PID: {orange(str(proc.pid))} | {cmd}")
+
+
[email protected](help="Kill the marimo processes")
+def killall() -> None:
+ """
+ Example usage:
+
+ marimo development ps killall
+ """
+ import os
+
+ for proc in get_marimo_processes():
+ # Ignore self
+ if proc.pid == os.getpid():
+ continue
+ proc.kill()
+ print(f"Killed process {proc.pid}")
+
+ print("Killed all marimo processes")
+
+
development.add_command(openapi)
+development.add_command(ps)
diff --git a/marimo/_messaging/ops.py b/marimo/_messaging/ops.py
index 0b3fcaa341..dcc677ac24 100644
--- a/marimo/_messaging/ops.py
+++ b/marimo/_messaging/ops.py
@@ -41,6 +41,7 @@ from marimo._plugins.core.web_component import JSONType
from marimo._plugins.ui._core.ui_element import UIElement
from marimo._runtime.context import get_context
from marimo._runtime.layout.layout import LayoutConfig
+from marimo._utils.platform import is_pyodide, is_windows
LOGGER = loggers.marimo_logger()
@@ -335,9 +336,12 @@ class CompletedRun(Op):
@dataclass
class KernelCapabilities:
sql: bool = False
+ terminal: bool = False
def __post_init__(self) -> None:
self.sql = DependencyManager.has_duckdb()
+ # Only available in mac/linux
+ self.terminal = not is_windows() and not is_pyodide()
@dataclass
diff --git a/marimo/_server/api/endpoints/terminal.py b/marimo/_server/api/endpoints/terminal.py
new file mode 100644
index 0000000000..a9667631d0
--- /dev/null
+++ b/marimo/_server/api/endpoints/terminal.py
@@ -0,0 +1,95 @@
+from __future__ import annotations
+
+import asyncio
+import os
+import select
+import signal
+import subprocess
+
+from starlette.websockets import WebSocket, WebSocketDisconnect
+
+from marimo import _loggers
+from marimo._server.api.deps import AppState
+from marimo._server.model import SessionMode
+from marimo._server.router import APIRouter
+
+LOGGER = _loggers.marimo_logger()
+
+router = APIRouter()
+
+
+async def _read_from_pty(master: int, websocket: WebSocket) -> None:
+ loop = asyncio.get_running_loop()
+ try:
+ # TODO: loop.add_reader would likely be better in this case
+ # but when the program is closed from the terminal, it hangs
+ # for an additional second before the process is killed.
+ with os.fdopen(master, "rb", buffering=0) as master_file:
+ while True:
+ try:
+ r, _, _ = await loop.run_in_executor(
+ None, select.select, [master_file], [], [], 0.1
+ )
+ if not r:
+ await asyncio.sleep(0.1) # Prevent busy-waiting
+ continue
+ data = os.read(master, 1024)
+ if not data:
+ break
+ await websocket.send_text(data.decode())
+ except (asyncio.CancelledError, WebSocketDisconnect):
+ break
+ except OSError as e:
+ if e.errno == 9: # Bad file descriptor
+ LOGGER.debug("File descriptor closed, stopping read loop")
+ return
+ raise # Re-raise other OSErrors
+
+
+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
+
+
+async def websocket_endpoint(websocket: WebSocket) -> None:
+ app_state = AppState(websocket)
+ if app_state.mode != SessionMode.EDIT:
+ await websocket.close()
+ return
+
+ await websocket.accept()
+ LOGGER.debug("Terminal websocket accepted")
+ import pty
+
+ child_pid, fd = pty.fork()
+ if child_pid == 0:
+ default_shell = os.environ.get("SHELL", "/bin/bash")
+ subprocess.run([default_shell], shell=True) ## noqa: ASYNC221
+ return
+
+ reader_task = asyncio.create_task(_read_from_pty(fd, websocket))
+ writer_task = asyncio.create_task(_write_to_pty(fd, websocket))
+
+ try:
+ await asyncio.gather(reader_task, writer_task)
+ except WebSocketDisconnect:
+ pass
+ except Exception as e:
+ await websocket.close()
+ LOGGER.exception(e)
+ finally:
+ if reader_task and not reader_task.done():
+ reader_task.cancel()
+ if writer_task and not writer_task.done():
+ writer_task.cancel()
+ os.kill(child_pid, signal.SIGKILL)
+ os.waitpid(child_pid, 0) ## noqa: ASYNC222
+ LOGGER.debug("Terminal websocket closed")
diff --git a/marimo/_server/api/router.py b/marimo/_server/api/router.py
index d0ad966aa1..6256e5f40c 100644
--- a/marimo/_server/api/router.py
+++ b/marimo/_server/api/router.py
@@ -22,6 +22,7 @@ from marimo._server.api.endpoints.files import router as files_router
from marimo._server.api.endpoints.health import router as health_router
from marimo._server.api.endpoints.home import router as home_router
from marimo._server.api.endpoints.login import router as login_router
+from marimo._server.api.endpoints.terminal import router as terminal_router
from marimo._server.api.endpoints.ws import router as ws_router
from marimo._server.router import APIRouter
@@ -57,6 +58,9 @@ def build_routes(base_url: str = "") -> List[BaseRoute]:
app_router.include_router(
export_router, prefix="/api/export", name="export"
)
+ app_router.include_router(
+ terminal_router, prefix="/terminal", name="terminal"
+ )
app_router.include_router(health_router, name="health")
app_router.include_router(ws_router, name="ws")
app_router.include_router(assets_router, name="assets")
diff --git a/openapi/api.yaml b/openapi/api.yaml
index d7356f719e..b6d1d2218a 100644
--- a/openapi/api.yaml
+++ b/openapi/api.yaml
@@ -844,8 +844,11 @@ components:
properties:
sql:
type: boolean
+ terminal:
+ type: boolean
required:
- sql
+ - terminal
type: object
cell_ids:
items:
@@ -1758,7 +1761,7 @@ components:
type: object
info:
title: marimo API
- version: 0.7.8
+ version: 0.7.9
openapi: 3.1.0
paths:
/@file/{filename_and_length}:
diff --git a/openapi/src/api.ts b/openapi/src/api.ts
index 51968ee016..96559c35c4 100644
--- a/openapi/src/api.ts
+++ b/openapi/src/api.ts
@@ -1090,6 +1090,7 @@ export interface components {
};
capabilities: {
sql: boolean;
+ terminal: boolean;
};
cell_ids: string[];
codes: string[];
diff --git a/tests/_server/api/endpoints/test_kiosk.py b/tests/_server/api/endpoints/test_kiosk.py
index 5a98878c1c..5830f560d2 100644
--- a/tests/_server/api/endpoints/test_kiosk.py
+++ b/tests/_server/api/endpoints/test_kiosk.py
@@ -1,10 +1,10 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+from dataclasses import asdict
from typing import TYPE_CHECKING, Any, Optional
-from marimo._dependencies.dependencies import DependencyManager
-from marimo._messaging.ops import KernelReady
+from marimo._messaging.ops import KernelCapabilities, KernelReady
from marimo._utils.parse_dataclass import parse_raw
from tests._server.mocks import token_header
@@ -27,9 +27,7 @@ def create_response(
"kiosk": False,
"configs": [{"disabled": False, "hide_code": False}],
"app_config": {"width": "full"},
- "capabilities": {
- "sql": DependencyManager.has_duckdb(),
- },
+ "capabilities": asdict(KernelCapabilities()),
}
response.update(partial_response)
return response
diff --git a/tests/_server/api/endpoints/test_resume_session.py b/tests/_server/api/endpoints/test_resume_session.py
index 673b81f61e..8da7d0a368 100644
--- a/tests/_server/api/endpoints/test_resume_session.py
+++ b/tests/_server/api/endpoints/test_resume_session.py
@@ -2,10 +2,10 @@
from __future__ import annotations
import time
+from dataclasses import asdict
from typing import TYPE_CHECKING, Any, Optional
-from marimo._dependencies.dependencies import DependencyManager
-from marimo._messaging.ops import CellOp, KernelReady
+from marimo._messaging.ops import CellOp, KernelCapabilities, KernelReady
from marimo._server.sessions import Session
from marimo._utils.parse_dataclass import parse_raw
from tests._server.conftest import get_session_manager
@@ -30,9 +30,7 @@ def create_response(
"kiosk": False,
"configs": [{"disabled": False, "hide_code": False}],
"app_config": {"width": "full"},
- "capabilities": {
- "sql": DependencyManager.has_duckdb(),
- },
+ "capabilities": asdict(KernelCapabilities()),
}
response.update(partial_response)
return response
diff --git a/tests/_server/api/endpoints/test_terminal.py b/tests/_server/api/endpoints/test_terminal.py
new file mode 100644
index 0000000000..cfe26de14d
--- /dev/null
+++ b/tests/_server/api/endpoints/test_terminal.py
@@ -0,0 +1,35 @@
+# Copyright 2024 Marimo. All rights reserved.
+from __future__ import annotations
+
+import sys
+from typing import TYPE_CHECKING
+
+import pytest
+from starlette.websockets import WebSocketDisconnect
+
+from marimo._server.model import SessionMode
+from marimo._server.sessions import SessionManager
+from tests._server.conftest import get_session_manager
+
+if TYPE_CHECKING:
+ from starlette.testclient import TestClient
+
+is_windows = sys.platform == "win32"
+
+
[email protected](is_windows, reason="Skip on Windows")
+def test_terminal_ws(client: TestClient) -> None:
+ with client.websocket_connect("/terminal/ws") as websocket:
+ # Send echo message
+ websocket.send_text("echo hello")
+ data = websocket.receive_text()
+ assert "echo hello" in data
+
+
+def test_terminal_ws_not_allowed_in_run(client: TestClient) -> None:
+ session_manager: SessionManager = get_session_manager(client)
+ session_manager.mode = SessionMode.RUN
+ with pytest.raises(WebSocketDisconnect):
+ with client.websocket_connect("/terminal/ws") as websocket:
+ websocket.send_text("echo hello")
+ session_manager.mode = SessionMode.EDIT
diff --git a/tests/_server/api/endpoints/test_ws.py b/tests/_server/api/endpoints/test_ws.py
index 847e9a2d11..e84ba1e5c0 100644
--- a/tests/_server/api/endpoints/test_ws.py
+++ b/tests/_server/api/endpoints/test_ws.py
@@ -1,14 +1,14 @@
# Copyright 2024 Marimo. All rights reserved.
from __future__ import annotations
+from dataclasses import asdict
from pathlib import Path
from typing import TYPE_CHECKING, Any, Optional
import pytest
from starlette.websockets import WebSocketDisconnect
-from marimo._dependencies.dependencies import DependencyManager
-from marimo._messaging.ops import KernelReady
+from marimo._messaging.ops import KernelCapabilities, KernelReady
from marimo._server.api.endpoints.ws import WebSocketCodes
from marimo._server.model import SessionMode
from marimo._server.sessions import SessionManager
@@ -35,9 +35,7 @@ def create_response(
"kiosk": False,
"configs": [{"disabled": False, "hide_code": False}],
"app_config": {"width": "full"},
- "capabilities": {
- "sql": DependencyManager.has_duckdb(),
- },
+ "capabilities": asdict(KernelCapabilities()),
}
response.update(partial_response)
return response