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
improvement: add open in terminal to agent sidebar (#6405)
Myles Scolnick5c1ae843baa4
diff --git a/frontend/src/components/chat/acp/agent-docs.tsx b/frontend/src/components/chat/acp/agent-docs.tsxindex 566879bf91..58ecef12c3 100644--- a/frontend/src/components/chat/acp/agent-docs.tsx+++ b/frontend/src/components/chat/acp/agent-docs.tsx@@ -1,9 +1,14 @@/* Copyright 2024 Marimo. All rights reserved. */-import { TerminalIcon } from "lucide-react";+import { useAtomValue } from "jotai";+import { TerminalIcon, TerminalSquareIcon } from "lucide-react";import { memo } from "react";import { AiProviderIcon } from "@/components/ai/ai-provider-icon";import { CopyClipboardIcon } from "@/components/icons/copy-icon";+import { useTerminalCommands } from "@/components/terminal/hooks";+import { Button } from "@/components/ui/button";+import { Tooltip } from "@/components/ui/tooltip";+import { capabilitiesAtom } from "@/core/config/capabilities";import { cn } from "@/utils/cn";import {type ExternalAgentId,@@ -22,6 +27,12 @@ const AgentDocItem = memo<AgentDocItemProps>(({ agentId, showCopy = true, className }) => {const command = getAgentConnectionCommand(agentId);const displayName = getAgentDisplayName(agentId);+ const capabilities = useAtomValue(capabilitiesAtom);+ const { sendCommand } = useTerminalCommands();++ const handleSendToTerminal = () => {+ sendCommand(command);+ };return (<div className={cn("space-y-2", className)}>@@ -35,9 +46,25 @@ const AgentDocItem = memo<AgentDocItemProps>(<code className="text-xs font-mono break-words flex-1 whitespace-pre-wrap">{command}</code>- {showCopy && (- <CopyClipboardIcon value={command} className="h-3 w-3" />- )}+ <div className="flex items-center gap-1 flex-shrink-0">+ {showCopy && (+ <Button size="xs" variant="outline" className="border">+ <CopyClipboardIcon value={command} className="h-3 w-3" />+ </Button>+ )}+ {capabilities.terminal && (+ <Tooltip content="Run in terminal" delayDuration={100}>+ <Button+ onClick={handleSendToTerminal}+ title="Send to terminal"+ size="xs"+ variant="outline"+ >+ <TerminalSquareIcon className="h-3 w-3" />+ </Button>+ </Tooltip>+ )}+ </div></div></div></div>diff --git a/frontend/src/components/terminal/__tests__/state.test.ts b/frontend/src/components/terminal/__tests__/state.test.tsnew file mode 100644index 0000000000..7a7c95380c--- /dev/null+++ b/frontend/src/components/terminal/__tests__/state.test.ts@@ -0,0 +1,207 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { describe, expect, it } from "vitest";+import { exportedForTesting } from "../state";++const { reducer, initialState } = exportedForTesting;++describe("terminal state", () => {+ describe("initialState", () => {+ it("should return initial state with empty pendingCommands and isReady false", () => {+ const state = initialState();+ expect(state).toEqual({+ pendingCommands: [],+ isReady: false,+ });+ });+ });++ describe("reducer", () => {+ it("should add a command to pendingCommands", () => {+ const state = initialState();+ const text = "ls -la";++ const newState = reducer(state, { type: "addCommand", payload: text });++ expect(newState.pendingCommands).toHaveLength(1);+ expect(newState.pendingCommands[0]).toMatchObject({+ text: "ls -la",+ timestamp: expect.any(Number),+ });+ expect(newState.pendingCommands[0].id).toBeDefined();+ expect(newState.isReady).toBe(false);+ });++ it("should add multiple commands to pendingCommands", () => {+ const state = initialState();++ let newState = reducer(state, { type: "addCommand", payload: "ls -la" });+ newState = reducer(newState, { type: "addCommand", payload: "cd /home" });+ newState = reducer(newState, { type: "addCommand", payload: "pwd" });++ expect(newState.pendingCommands).toHaveLength(3);+ expect(newState.pendingCommands[0].text).toBe("ls -la");+ expect(newState.pendingCommands[1].text).toBe("cd /home");+ expect(newState.pendingCommands[2].text).toBe("pwd");+ });++ it("should remove a command by id", () => {+ const state = initialState();++ let newState = reducer(state, { type: "addCommand", payload: "ls -la" });+ newState = reducer(newState, { type: "addCommand", payload: "cd /home" });+ newState = reducer(newState, { type: "addCommand", payload: "pwd" });++ const commandToRemove = newState.pendingCommands[1];+ newState = reducer(newState, {+ type: "removeCommand",+ payload: commandToRemove.id,+ });++ expect(newState.pendingCommands).toHaveLength(2);+ expect(newState.pendingCommands[0].text).toBe("ls -la");+ expect(newState.pendingCommands[1].text).toBe("pwd");+ });++ it("should not remove anything if command id does not exist", () => {+ const state = initialState();++ let newState = reducer(state, { type: "addCommand", payload: "ls -la" });+ newState = reducer(newState, { type: "addCommand", payload: "cd /home" });++ const originalLength = newState.pendingCommands.length;+ newState = reducer(newState, {+ type: "removeCommand",+ payload: "non-existent-id",+ });++ expect(newState.pendingCommands).toHaveLength(originalLength);+ });++ it("should set isReady to true", () => {+ const state = initialState();++ const newState = reducer(state, { type: "setReady", payload: true });++ expect(newState.isReady).toBe(true);+ expect(newState.pendingCommands).toEqual([]);+ });++ it("should set isReady to false", () => {+ const state = { ...initialState(), isReady: true };++ const newState = reducer(state, { type: "setReady", payload: false });++ expect(newState.isReady).toBe(false);+ });++ it("should clear all pending commands", () => {+ const state = initialState();++ let newState = reducer(state, { type: "addCommand", payload: "ls -la" });+ newState = reducer(newState, { type: "addCommand", payload: "cd /home" });+ newState = reducer(newState, { type: "addCommand", payload: "pwd" });++ expect(newState.pendingCommands).toHaveLength(3);++ newState = reducer(newState, {+ type: "clearCommands",+ payload: undefined,+ });++ expect(newState.pendingCommands).toHaveLength(0);+ expect(newState.isReady).toBe(false);+ });++ it("should preserve other state when adding commands", () => {+ const state = { ...initialState(), isReady: true };++ const newState = reducer(state, {+ type: "addCommand",+ payload: "ls -la",+ });++ expect(newState.isReady).toBe(true);+ expect(newState.pendingCommands).toHaveLength(1);+ });++ it("should preserve other state when removing commands", () => {+ const state = { ...initialState(), isReady: true };++ let newState = reducer(state, { type: "addCommand", payload: "ls -la" });+ newState = reducer(newState, {+ type: "removeCommand",+ payload: newState.pendingCommands[0].id,+ });++ expect(newState.isReady).toBe(true);+ expect(newState.pendingCommands).toHaveLength(0);+ });++ it("should preserve other state when setting ready", () => {+ const state = initialState();++ let newState = reducer(state, { type: "addCommand", payload: "ls -la" });+ newState = reducer(newState, { type: "addCommand", payload: "cd /home" });+ newState = reducer(newState, { type: "setReady", payload: true });++ expect(newState.isReady).toBe(true);+ expect(newState.pendingCommands).toHaveLength(2);+ });++ it("should preserve other state when clearing commands", () => {+ const state = { ...initialState(), isReady: true };++ let newState = reducer(state, { type: "addCommand", payload: "ls -la" });+ newState = reducer(newState, {+ type: "clearCommands",+ payload: undefined,+ });++ expect(newState.isReady).toBe(true);+ expect(newState.pendingCommands).toHaveLength(0);+ });+ });++ describe("command properties", () => {+ it("should generate unique ids for commands", () => {+ const state = initialState();++ let newState = reducer(state, {+ type: "addCommand",+ payload: "command1",+ });+ newState = reducer(newState, { type: "addCommand", payload: "command2" });++ const ids = newState.pendingCommands.map((cmd) => cmd.id);+ expect(ids[0]).not.toBe(ids[1]);+ expect(ids[0]).toBeDefined();+ expect(ids[1]).toBeDefined();+ });++ it("should set timestamp when adding commands", () => {+ const state = initialState();+ const beforeTime = Date.now();++ const newState = reducer(state, {+ type: "addCommand",+ payload: "ls -la",+ });++ const afterTime = Date.now();+ const command = newState.pendingCommands[0];++ expect(command.timestamp).toBeGreaterThanOrEqual(beforeTime);+ expect(command.timestamp).toBeLessThanOrEqual(afterTime);+ });++ it("should preserve text when adding commands", () => {+ const state = initialState();+ const text = "echo 'Hello World'";++ const newState = reducer(state, { type: "addCommand", payload: text });++ expect(newState.pendingCommands[0].text).toBe(text);+ });+ });+});diff --git a/frontend/src/components/terminal/hooks.ts b/frontend/src/components/terminal/hooks.tsnew file mode 100644index 0000000000..5158aeb33b--- /dev/null+++ b/frontend/src/components/terminal/hooks.ts@@ -0,0 +1,41 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { useChromeActions } from "../editor/chrome/state";+import { useTerminalActions } from "./state";++/**+ * Hook for sending commands to the terminal programmatically.+ * This will:+ * 1. Open the terminal if it's not already open+ * 2. Wait for the terminal to be connected+ * 3. Send the command text to the terminal+ *+ * @example+ * ```tsx+ * function CopyButton({ command }: { command: string }) {+ * const { sendCommand } = useTerminalCommands();+ *+ * return (+ * <button onClick={() => sendCommand(command)}>+ * Copy to Terminal+ * </button>+ * );+ * }+ * ```+ */+export function useTerminalCommands() {+ const { addCommand } = useTerminalActions();+ const { setIsTerminalOpen } = useChromeActions();++ const sendCommand = (text: string) => {+ // First, ensure the terminal is open+ setIsTerminalOpen(true);++ // Add the command to the queue+ addCommand(text);+ };++ return {+ sendCommand,+ };+}diff --git a/frontend/src/components/terminal/state.ts b/frontend/src/components/terminal/state.tsnew file mode 100644index 0000000000..e65ed5c8ac--- /dev/null+++ b/frontend/src/components/terminal/state.ts@@ -0,0 +1,75 @@+/* Copyright 2024 Marimo. All rights reserved. */++import { useAtomValue } from "jotai";+import { createReducerAndAtoms } from "@/utils/createReducer";+import { generateUUID } from "@/utils/uuid";++export interface TerminalCommand {+ id: string;+ text: string;+ timestamp: number;+}++export interface TerminalState {+ pendingCommands: TerminalCommand[];+ isReady: boolean;+}++function initialState(): TerminalState {+ return {+ pendingCommands: [],+ isReady: false,+ };+}++const {+ reducer,+ createActions,+ valueAtom: terminalStateAtom,+ useActions,+} = createReducerAndAtoms(initialState, {+ addCommand: (state, text: string) => {+ const command: TerminalCommand = {+ id: generateUUID(),+ text,+ timestamp: Date.now(),+ };++ return {+ ...state,+ pendingCommands: [...state.pendingCommands, command],+ };+ },+ removeCommand: (state, commandId: string) => ({+ ...state,+ pendingCommands: state.pendingCommands.filter(+ (cmd) => cmd.id !== commandId,+ ),+ }),+ setReady: (state, isReady: boolean) => ({+ ...state,+ isReady,+ }),+ clearCommands: (state) => ({+ ...state,+ pendingCommands: [],+ }),+});++/**+ * React hook to get the terminal state.+ */+export const useTerminalState = () => useAtomValue(terminalStateAtom);++/**+ * React hook to get the terminal actions.+ */+export function useTerminalActions() {+ return useActions();+}++export const exportedForTesting = {+ reducer,+ createActions,+ initialState,+};diff --git a/frontend/src/components/terminal/terminal.tsx b/frontend/src/components/terminal/terminal.tsxindex b2b845ff28..5eedbf7aa1 100644--- a/frontend/src/components/terminal/terminal.tsx+++ b/frontend/src/components/terminal/terminal.tsx@@ -24,6 +24,7 @@ import { cn } from "@/utils/cn";import { copyToClipboard } from "@/utils/copy";import { Logger } from "@/utils/Logger";import { MinimalHotkeys } from "../shortcuts/renderShortcut";+import { useTerminalActions, useTerminalState } from "./state";import { createTerminalTheme } from "./theme";interface TerminalButtonProps {@@ -182,6 +183,10 @@ const TerminalComponent: React.FC<TerminalComponentProps> = ({const [contextMenu, setContextMenu] = useState<Position | null>(null);const runtimeManager = useRuntimeManager();+ // Terminal command state management+ const terminalState = useTerminalState();+ const { removeCommand, setReady } = useTerminalActions();+// Keyboard shortcuts handlerconst handleKeyDown = useEvent(createKeyboardHandler(terminal, searchAddon));@@ -254,6 +259,19 @@ const TerminalComponent: React.FC<TerminalComponentProps> = ({terminal.loadAddon(attachAddon);wsRef.current = socket;+ // Terminal is ready when the websocket is open+ const updateReadyState = () => {+ setReady(socket.readyState === WebSocket.OPEN);+ };++ const handleError = () => {+ updateReadyState();+ };++ const handleOpen = () => {+ updateReadyState();+ };+const handleDisconnect = () => {onClose();// Reset@@ -261,9 +279,15 @@ const TerminalComponent: React.FC<TerminalComponentProps> = ({wsRef.current = null;terminal.clear();setInitialized(false);+ setReady(false);};+ socket.addEventListener("open", handleOpen);socket.addEventListener("close", handleDisconnect);+ socket.addEventListener("error", handleError);++ // Set initial ready state+ updateReadyState();setInitialized(true);} catch (error) {Logger.error("Runtime health check failed for terminal", error);@@ -279,6 +303,30 @@ const TerminalComponent: React.FC<TerminalComponentProps> = ({// eslint-disable-next-line react-hooks/exhaustive-deps}, [initialized]);+ // Process pending commands when terminal is ready+ useEffect(() => {+ if (!terminalState.isReady || terminalState.pendingCommands.length === 0) {+ return;+ }++ // Process all pending commands+ for (const command of terminalState.pendingCommands) {+ if (terminal && wsRef.current?.readyState === WebSocket.OPEN) {+ Logger.debug("Sending programmatic command to terminal", {+ command: command.text,+ });+ terminal.input(command.text);+ terminal.focus();+ removeCommand(command.id);+ }+ }+ }, [+ terminal,+ terminalState.isReady,+ terminalState.pendingCommands,+ removeCommand,+ ]);+// When visibleuseEffect(() => {if (visible) {diff --git a/marimo/_server/ai/mcp.py b/marimo/_server/ai/mcp.pyindex 262920aa3f..db12f974aa 100644--- a/marimo/_server/ai/mcp.py+++ b/marimo/_server/ai/mcp.py@@ -946,11 +946,9 @@ def get_mcp_client(config: Optional[MCPConfig] = None) -> MCPClient:"""Get the global MCP client instance, initializing it if needed."""global _MCP_CLIENTif _MCP_CLIENT is None:- try:- DependencyManager.mcp.require(why="for MCP server connections")- except ModuleNotFoundError as e:- LOGGER.info(f"MCP SDK not available: {str(e)}")- raise+ if not DependencyManager.mcp.has():+ LOGGER.info("MCP SDK not available")+ raise ModuleNotFoundError("MCP SDK not available")_MCP_CLIENT = MCPClient(config or _get_default_config())LOGGER.info("MCP client initialized")