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: better ACP commands, edit the notebook without --watch, slash-commands (#6360)
Myles Scolnickd390a0c181a7
diff --git a/frontend/package.json b/frontend/package.jsonindex e5060e809a..7f028efc23 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -102,7 +102,7 @@"@xterm/addon-attach": "^0.11.0","@xterm/addon-fit": "^0.10.0","@xterm/xterm": "^5.5.0",- "@zed-industries/agent-client-protocol": "^0.1.2",+ "@zed-industries/agent-client-protocol": "^0.3.1","ai": "^5.0.30","ansi_up": "^6.0.6","class-variance-authority": "^0.7.1",@@ -159,7 +159,7 @@"thememirror": "^2.0.1","timestring": "^7.0.0","typescript-memoize": "^1.1.1",- "use-acp": "^0.1.5",+ "use-acp": "^0.2.3","use-resize-observer": "^9.1.0","vega-lite": "^5.23.0","vega-loader": "^4.5.3",diff --git a/frontend/src/components/chat/acp/__tests__/__snapshots__/prompt.test.ts.snap b/frontend/src/components/chat/acp/__tests__/__snapshots__/prompt.test.ts.snapindex 46afd2e3ed..b41a12f3df 100644--- a/frontend/src/components/chat/acp/__tests__/__snapshots__/prompt.test.ts.snap+++ b/frontend/src/components/chat/acp/__tests__/__snapshots__/prompt.test.ts.snap@@ -3,7 +3,7 @@exports[`getAgentPrompt > should generate complete agent prompt with default filename 1`] = `"I am currently editing a marimo notebook.- You can read or write to the notebook at @test-notebook.py+ You can read or write to the notebook at test-notebook.pyIf you make edits to the notebook, only edit the contents inside the function decorator with @app.cell.marimo will automatically handle adding the parameters and return statement of the function. For example,@@ -11,7 +11,7 @@ exports[`getAgentPrompt > should generate complete agent prompt with default fil\`\`\`@app.cell- def __():+ def _():<your code here>return\`\`\`@@ -37,6 +37,7 @@ exports[`getAgentPrompt > should generate complete agent prompt with default fil7. The last expression in a cell is automatically displayed, just like in Jupyter notebooks.8. Don't include comments in markdown cells9. Don't include comments in SQL cells+ 10. Never define anything using \`global\`.## Reactivity@@ -115,34 +116,50 @@ exports[`getAgentPrompt > should generate complete agent prompt with default fil- \`mo.md(text)\` - display markdown- \`mo.stop(predicate, output=None)\` - stop execution conditionally+ - \`mo.output.append(value)\` - append to the output when it is not the last expression+ - \`mo.output.replace(value)\` - replace the output when it is not the last expression- \`mo.Html(html)\` - display HTML- \`mo.image(image)\` - display an image- \`mo.hstack(elements)\` - stack elements horizontally- \`mo.vstack(elements)\` - stack elements vertically- \`mo.tabs(elements)\` - create a tabbed interface++## Examples+ <example title="Markdown ccell">++ @app.cell+ def _():+ mo.md("""+ # Hello world+ This is a _markdown_ **cell**.+ """)+ return++ </example>+<example title="Basic UI with reactivity">@app.cell- def __():+ def _():import marimo as moimport matplotlib.pyplot as pltimport numpy as npreturn@app.cell- def __():+ def _():n_points = mo.ui.slider(10, 100, value=50, label="Number of points")n_pointsreturn@app.cell- def __():+ def _():x = np.random.rand(n_points.value)y = np.random.rand(n_points.value)-+plt.figure(figsize=(8, 6))plt.scatter(x, y, alpha=0.7)plt.title(f"Scatter plot with {n_points.value} points")@@ -156,14 +173,14 @@ exports[`getAgentPrompt > should generate complete agent prompt with default fil<example title="Data explorer">@app.cell- def __():+ def _():import marimo as moimport pandas as pdfrom vega_datasets import datareturn@app.cell- def __():+ def _():cars_df = data.cars()mo.ui.data_explorer(cars_df)return@@ -173,7 +190,7 @@ exports[`getAgentPrompt > should generate complete agent prompt with default fil<example title="Multiple UI elements">@app.cell- def __():+ def _():import marimo as moimport pandas as pdimport matplotlib.pyplot as plt@@ -181,12 +198,12 @@ exports[`getAgentPrompt > should generate complete agent prompt with default filreturn@app.cell- def __():+ def _():iris = sns.load_dataset('iris')return@app.cell- def __():+ def _():species_selector = mo.ui.dropdown(options=["All"] + iris["species"].unique().tolist(),value="All",@@ -206,9 +223,9 @@ exports[`getAgentPrompt > should generate complete agent prompt with default filreturn@app.cell- def __():+ def _():filtered_data = iris if species_selector.value == "All" else iris[iris["species"] == species_selector.value]-+plt.figure(figsize=(10, 6))sns.scatterplot(data=filtered_data,@@ -222,17 +239,31 @@ exports[`getAgentPrompt > should generate complete agent prompt with default fil</example>+ <example title="Conditional Outputs">++ @app.cell+ def _():+ mo.stop(not data.value, mo.md("No data to display"))++ if mode.value == "scatter":+ mo.output.replace(render_scatter(data.value))+ else:+ mo.output.replace(render_bar_chart(data.value))+ return++ </example>+<example title="Interactive chart with Altair">@app.cell- def __():+ def _():import marimo as moimport altair as altimport pandas as pdreturn@app.cell- def __():+ def _():# Load datasetcars_df = pd.read_csv('<https://raw.githubusercontent.com/vega/vega-datasets/master/data/cars.json>')_chart = alt.Chart(cars_df).mark_point().encode(@@ -243,13 +274,13 @@ exports[`getAgentPrompt > should generate complete agent prompt with default filreturn@app.cell- def __():+ def _():chart = mo.ui.altair_chart(_chart)chartreturn@app.cell- def __():+ def _():# Display the selectionchart.valuereturn@@ -259,19 +290,19 @@ exports[`getAgentPrompt > should generate complete agent prompt with default fil<example title="Run Button Example">@app.cell- def __():+ def _():import marimo as moreturn@app.cell- def __():+ def _():first_button = mo.ui.run_button(label="Option 1")second_button = mo.ui.run_button(label="Option 2")[first_button, second_button]return@app.cell- def __():+ def _():if first_button.value:print("You chose option 1!")elif second_button.value:@@ -285,18 +316,18 @@ exports[`getAgentPrompt > should generate complete agent prompt with default fil<example title="SQL with duckdb">@app.cell- def __():+ def _():import marimo as moimport pandas as pdreturn@app.cell- def __():+ def _():cars_df = pd.read_csv('<https://raw.githubusercontent.com/vega/vega-datasets/master/data/cars.json>')return@app.cell- def __():+ def _():_df = mo.sql("SELECT * from cars_df WHERE Miles_per_Gallon > 20")returndiff --git a/frontend/src/components/chat/acp/__tests__/prompt.test.ts b/frontend/src/components/chat/acp/__tests__/prompt.test.tsindex c7174df280..366702acc3 100644--- a/frontend/src/components/chat/acp/__tests__/prompt.test.ts+++ b/frontend/src/components/chat/acp/__tests__/prompt.test.ts@@ -1,4 +1,4 @@-/* Copyright 2025 Marimo. All rights reserved. */+/* Copyright 2024 Marimo. All rights reserved. */import { describe, expect, it } from "vitest";import { getAgentPrompt } from "../prompt";diff --git a/frontend/src/components/chat/acp/__tests__/state.test.ts b/frontend/src/components/chat/acp/__tests__/state.test.tsindex 03bfb16cdb..f9c236f46e 100644--- a/frontend/src/components/chat/acp/__tests__/state.test.ts+++ b/frontend/src/components/chat/acp/__tests__/state.test.ts@@ -604,17 +604,13 @@ describe("state utility functions", () => {describe("getAgentConnectionCommand", () => {it("should return correct command for claude", () => {expect(getAgentConnectionCommand("claude")).toMatchInlineSnapshot(`- "npx supergateway --stdio\\- "npx @zed-industries/claude-code-acp" \\- --outputTransport ws --port 3017 "+ "npx stdio-to-ws "npx @zed-industries/claude-code-acp" --port 3017"`);});it("should return correct command for gemini", () => {expect(getAgentConnectionCommand("gemini")).toMatchInlineSnapshot(`- "npx supergateway --stdio\\- "npx @google/gemini-cli --experimental-acp" \\- --outputTransport ws --port 3019 "+ "npx stdio-to-ws "npx @google/gemini-cli --experimental-acp" --port 3019"`);});});diff --git a/frontend/src/components/chat/acp/agent-docs.tsx b/frontend/src/components/chat/acp/agent-docs.tsxindex 35cf75619c..566879bf91 100644--- a/frontend/src/components/chat/acp/agent-docs.tsx+++ b/frontend/src/components/chat/acp/agent-docs.tsx@@ -32,7 +32,7 @@ const AgentDocItem = memo<AgentDocItemProps>(<div className="bg-muted/50 rounded-md p-2 border"><div className="flex items-start gap-2 text-xs"><TerminalIcon className="h-4 w-4 mt-0.5 text-muted-foreground flex-shrink-0" />- <code className="text-xs font-mono break-all flex-1 whitespace-pre-wrap">+ <code className="text-xs font-mono break-words flex-1 whitespace-pre-wrap">{command}</code>{showCopy && (@@ -48,7 +48,7 @@ AgentDocItem.displayName = "AgentDocItem";interface AgentDocsProps {title?: string;- description?: string;+ description?: React.ReactNode;agents?: ExternalAgentId[];showCopy?: boolean;className?: string;diff --git a/frontend/src/components/chat/acp/agent-panel.tsx b/frontend/src/components/chat/acp/agent-panel.tsxindex 3c760df363..5ec2417aa4 100644--- a/frontend/src/components/chat/acp/agent-panel.tsx+++ b/frontend/src/components/chat/acp/agent-panel.tsx@@ -1,20 +1,23 @@/* Copyright 2024 Marimo. All rights reserved. */-import { useAtom } from "jotai";+import { useAtom, useAtomValue } from "jotai";import { capitalize } from "lodash-es";import {BotMessageSquareIcon,RefreshCwIcon,StopCircleIcon,} from "lucide-react";-import React, { memo, useEffect, useRef, useState } from "react";+import React, { memo, useEffect, useMemo, useRef, useState } from "react";import useEvent from "react-use-event-hook";import { useAcpClient } from "use-acp";import {ConnectionStatus,PermissionRequest,} from "@/components/chat/acp/common";-import { PromptInput } from "@/components/editor/ai/add-cell-with-ai";+import {+ type AdditionalCompletions,+ PromptInput,+} from "@/components/editor/ai/add-cell-with-ai";import { PanelEmptyState } from "@/components/editor/chrome/panels/empty-state";import { Spinner } from "@/components/icons/spinner";import { Button } from "@/components/ui/button";@@ -34,11 +37,19 @@ import {} from "./state";import { AgentThread } from "./thread";import "./agent-panel.css";+import type { Completion } from "@codemirror/autocomplete";import type {- ReadTextFileResponse,+ ContentBlock,RequestPermissionResponse,- WriteTextFileResponse,} from "@zed-industries/agent-client-protocol";+import {+ Select,+ SelectContent,+ SelectGroup,+ SelectItem,+ SelectLabel,+ SelectTrigger,+} from "@/components/ui/select";import { toast } from "@/components/ui/use-toast";import { useRequestClient } from "@/core/network/requests";import { filenameAtom } from "@/core/saving/file-state";@@ -49,8 +60,10 @@ import { getAgentPrompt } from "./prompt";import type {AgentConnectionState,AgentPendingPermission,+ AvailableCommands,ExternalAgentSessionId,NotificationEvent,+ SessionMode,} from "./types";const logger = Logger.get("agents");@@ -171,35 +184,45 @@ interface EmptyStateProps {}const EmptyState = memo<EmptyStateProps>(- ({ currentAgentId, connectionState, onConnect, onDisconnect }) => (- <div className="flex flex-col h-full">- <AgentPanelHeader- connectionState={connectionState}- currentAgentId={currentAgentId}- onConnect={onConnect}- onDisconnect={onDisconnect}- hasActiveSession={false}- />- <SessionTabs />- <div className="flex-1 flex items-center justify-center p-6">- <div className="max-w-md w-full space-y-6">- <PanelEmptyState- title="No Agent Sessions"- description="Create a new session to start a conversation"- action={<AgentSelector className="border-y-1 rounded" />}- icon={<BotMessageSquareIcon />}- />- {connectionState.status === "disconnected" && (- <AgentDocs- className="border-t pt-6"- title="Connect to an agent"- description="Start agents by running these commands in your terminal:"+ ({ currentAgentId, connectionState, onConnect, onDisconnect }) => {+ const filename = useAtomValue(filenameAtom);+ return (+ <div className="flex flex-col h-full">+ <AgentPanelHeader+ connectionState={connectionState}+ currentAgentId={currentAgentId}+ onConnect={onConnect}+ onDisconnect={onDisconnect}+ hasActiveSession={false}+ />+ <SessionTabs />+ <div className="flex-1 flex items-center justify-center p-6">+ <div className="max-w-md w-full space-y-6">+ <PanelEmptyState+ title="No Agent Sessions"+ description="Create a new session to start a conversation"+ action={<AgentSelector className="border-y-1 rounded" />}+ icon={<BotMessageSquareIcon />}/>- )}+ {connectionState.status === "disconnected" && (+ <AgentDocs+ className="border-t pt-6"+ title="Connect to an agent"+ description={+ <>+ Start agents by running these commands in your terminal:+ <br />+ Note: This must be in the directory{" "}+ {Paths.dirname(filename ?? "")}+ </>+ }+ />+ )}+ </div></div></div>- </div>- ),+ );+ },);EmptyState.displayName = "EmptyState";@@ -248,6 +271,7 @@ interface PromptAreaProps {isLoading: boolean;activeSessionId: ExternalAgentSessionId | null;promptValue: string;+ commands: AvailableCommands | undefined;onPromptValueChange: (value: string) => void;onPromptSubmit: (e: KeyboardEvent | undefined, prompt: string) => void;}@@ -257,36 +281,108 @@ const PromptArea = memo<PromptAreaProps>(isLoading,activeSessionId,promptValue,+ commands,onPromptValueChange,onPromptSubmit,- }) => (- <div- className={cn(- "px-3 py-2 border-t bg-background flex-shrink-0 min-h-[80px]",- (isLoading || !activeSessionId) && "opacity-50 pointer-events-none",- )}- >- <PromptInput- value={promptValue}- onChange={isLoading ? Functions.NOOP : onPromptValueChange}- onSubmit={onPromptSubmit}- onClose={Functions.NOOP}- placeholder={isLoading ? "Processing..." : "Ask your AI agent..."}- className={isLoading ? "opacity-50 pointer-events-none" : ""}- maxHeight="120px"- />- </div>- ),+ }) => {+ const promptCompletions: AdditionalCompletions | undefined = useMemo(() => {+ if (!commands) {+ return undefined;+ }+ // sentence has to begin with '/' to trigger autocomplete+ return {+ triggerCompletionRegex: /^\/(\w+)?/,+ completions: commands.map(+ (prompt): Completion => ({+ label: `/${prompt.name}`,+ info: prompt.description,+ }),+ ),+ };+ }, [commands]);++ return (+ <div+ className={cn(+ "px-3 py-2 border-t bg-background flex-shrink-0 min-h-[80px]",+ (isLoading || !activeSessionId) && "opacity-50 pointer-events-none",+ )}+ >+ <PromptInput+ value={promptValue}+ onChange={isLoading ? Functions.NOOP : onPromptValueChange}+ onSubmit={onPromptSubmit}+ additionalCompletions={promptCompletions}+ onClose={Functions.NOOP}+ placeholder={isLoading ? "Processing..." : "Ask your AI agent..."}+ className={isLoading ? "opacity-50 pointer-events-none" : ""}+ maxHeight="120px"+ />+ </div>+ );+ },);PromptArea.displayName = "PromptArea";+interface ModeSelectorProps {+ sessionMode: SessionMode;+ onModeChange: (mode: string) => void;+}++const ModeSelector = memo<ModeSelectorProps>(+ ({ sessionMode, onModeChange }) => {+ const availableModes = sessionMode?.availableModes || [];+ const currentModeId = sessionMode?.currentModeId;+ if (availableModes.length === 0) {+ return null;+ }++ const modeOptions = availableModes.map((mode) => ({+ value: mode.id,+ label: mode.name,+ subtitle: mode.description ?? "",+ }));+ const currentMode = modeOptions.find((opt) => opt.value === currentModeId);++ return (+ <Select value={currentModeId} onValueChange={onModeChange}>+ <SelectTrigger className="h-6 text-xs border-border shadow-none! ring-0! bg-muted hover:bg-muted/30 py-0 px-2 gap-1 capitalize">+ {currentMode?.label ?? currentModeId}+ </SelectTrigger>+ <SelectContent>+ <SelectGroup>+ <SelectLabel>Agent Mode</SelectLabel>+ {modeOptions.map((option) => (+ <SelectItem+ key={option.value}+ value={option.value}+ className="text-xs"+ >+ <div className="flex flex-col">+ {option.label}+ {option.subtitle && (+ <div className="text-muted-foreground text-xs pt-1 block">+ {option.subtitle}+ </div>+ )}+ </div>+ </SelectItem>+ ))}+ </SelectGroup>+ </SelectContent>+ </Select>+ );+ },+);+ModeSelector.displayName = "ModeSelector";+interface ChatContentProps {hasNotifications: boolean;connectionState: AgentConnectionState;sessionId: ExternalAgentSessionId | null;notifications: NotificationEvent[];pendingPermission: AgentPendingPermission;- onResolvePermission: (option: unknown) => void;+ onResolvePermission: (option: RequestPermissionResponse) => void;onRetryConnection?: () => void;onRetryLastAction?: () => void;onDismissError?: (errorId: string) => void;@@ -421,7 +517,7 @@ const AgentPanel: React.FC = () => {const acpClient = useAcpClient({wsUrl,clientOptions: {- readTextFile: (request): Promise<ReadTextFileResponse> => {+ readTextFile: (request) => {logger.debug("Agent requesting file read", {path: request.path,});@@ -429,7 +525,7 @@ const AgentPanel: React.FC = () => {content: response.contents || "",}));},- writeTextFile: (request): Promise<WriteTextFileResponse> => {+ writeTextFile: (request) => {logger.debug("Agent requesting file write", {path: request.path,contentLength: request.content.length,@@ -437,7 +533,7 @@ const AgentPanel: React.FC = () => {return sendUpdateFile({path: request.path,contents: request.content,- }).then(() => null);+ }).then(() => ({}));},},autoConnect: false, // We'll manage connection manually based on active session@@ -449,11 +545,25 @@ const AgentPanel: React.FC = () => {connectionState,notifications,pendingPermission,+ availableCommands,resolvePermission,+ sessionMode,activeSessionId,agent,} = acpClient;+ useEffect(() => {+ agent?.initialize({+ protocolVersion: 1,+ clientCapabilities: {+ fs: {+ readTextFile: true,+ writeTextFile: true,+ },+ },+ });+ }, [agent]);+// Auto-connect to agent when we have an active session, but only once per sessionuseEffect(() => {if (wsUrl === NO_WS_SET) {@@ -597,26 +707,35 @@ const AgentPanel: React.FC = () => {return;}+ const promptBlocks: ContentBlock[] = [{ type: "text", text: prompt }];+ const hasGivenRules = notifications.some(+ (notification) =>+ notification.type === "session_notification" &&+ notification.data.update.sessionUpdate === "user_message_chunk",+ );+ if (!hasGivenRules) {+ promptBlocks.push(+ {+ type: "resource_link",+ uri: filename,+ mimeType: "text/x-python",+ name: filename,+ },+ {+ type: "resource",+ resource: {+ uri: "marimo_rules.md",+ mimeType: "text/markdown",+ text: getAgentPrompt(filename),+ },+ },+ );+ }+try {await agent.prompt({sessionId: activeSessionId,- prompt: [- { type: "text", text: prompt },- {- type: "resource_link",- uri: filename,- mimeType: "text/x-python",- name: filename,- },- {- type: "resource",- resource: {- uri: "marimo_rules.md",- mimeType: "text/markdown",- text: getAgentPrompt(filename),- },- },- ],+ prompt: promptBlocks,});} catch (error) {logger.error("Failed to send prompt", { error });@@ -652,6 +771,33 @@ const AgentPanel: React.FC = () => {disconnect();});+ const handleModeChange = useEvent((mode: string) => {+ logger.debug("Mode change requested", {+ sessionId: activeSessionId,+ mode,+ });+ if (!agent) {+ toast({+ title: "Agent not connected",+ description: "Please connect to an agent to change the mode",+ variant: "danger",+ });+ return;+ }+ if (!agent.setSessionMode) {+ toast({+ title: "Mode change not supported",+ description: "The agent does not support mode changes",+ variant: "danger",+ });+ return;+ }+ void agent.setSessionMode?.({+ sessionId: activeSessionId as string,+ modeId: mode,+ });+ });+const hasNotifications = notifications.length > 0;const hasActiveSessions = sessionState.sessions.length > 0;@@ -690,7 +836,7 @@ const AgentPanel: React.FC = () => {sessionId: activeSessionId,option,});- resolvePermission(option as RequestPermissionResponse);+ resolvePermission(option);}}onRetryConnection={handleManualConnect}/>@@ -707,7 +853,17 @@ const AgentPanel: React.FC = () => {promptValue={promptValue}onPromptValueChange={setPromptValue}onPromptSubmit={handlePromptSubmit}+ commands={availableCommands}/>++ {sessionMode && (+ <div className="px-3 py-2 border-t flex-shrink-0 h-10">+ <ModeSelector+ sessionMode={sessionMode}+ onModeChange={handleModeChange}+ />+ </div>+ )}</div>);};diff --git a/frontend/src/components/chat/acp/agent-selector.tsx b/frontend/src/components/chat/acp/agent-selector.tsxindex 96ba6b9bbf..2f2330cdfa 100644--- a/frontend/src/components/chat/acp/agent-selector.tsx+++ b/frontend/src/components/chat/acp/agent-selector.tsx@@ -13,7 +13,9 @@ import {DropdownMenuSeparator,DropdownMenuTrigger,} from "@/components/ui/dropdown-menu";+import { useFilename } from "@/core/saving/filename";import { cn } from "@/utils/cn";+import { Paths } from "@/utils/paths";import { AgentDocs } from "./agent-docs";import {type AgentSession,@@ -79,6 +81,7 @@ AgentMenuItem.displayName = "AgentMenuItem";export const AgentSelector: React.FC<AgentSelectorProps> = memo(({ onSessionCreated, className }) => {+ const filename = useFilename();const [sessionState, setSessionState] = useAtom(agentSessionStateAtom);const setActiveTab = useSetAtom(selectedTabAtom);const [isOpen, setIsOpen] = useState(false);@@ -123,7 +126,10 @@ export const AgentSelector: React.FC<AgentSelectorProps> = memo(<div className="px-2 py-2"><div className="text-xs font-medium text-muted-foreground mb-3">To start an external agent, run the following command in your- terminal:+ terminal.+ <br />+ Note: This must be in the directory{" "}+ {Paths.dirname(filename ?? "")}</div><AgentDocsagents={AVAILABLE_AGENTS.map((agent) => agent.id)}diff --git a/frontend/src/components/chat/acp/blocks.tsx b/frontend/src/components/chat/acp/blocks.tsxindex a7d6a88909..4d85e0cd41 100644--- a/frontend/src/components/chat/acp/blocks.tsx+++ b/frontend/src/components/chat/acp/blocks.tsx@@ -39,6 +39,7 @@ import type {AgentThoughtNotificationEvent,ConnectionChangeNotificationEvent,ContentBlockOf,+ CurrentModeUpdateNotificationEvent,ErrorNotificationEvent,PlanNotificationEvent,SessionNotificationEventData,@@ -495,6 +496,18 @@ export const SessionNotificationsBlock = <return <PlansBlock data={items} />;}+ if (kind === "available_commands_update") {+ return null; // nothing to show+ }+ if (kind === "current_mode_update") {+ const lastItem = items.at(-1);+ if (lastItem?.sessionUpdate !== "current_mode_update") {+ return null;+ } else {+ return <CurrentModeBlock data={lastItem} />;+ }+ }+return (<SimpleAccordion title={items[0].sessionUpdate}><JsonOutput data={items} format="tree" className="max-h-64" />@@ -509,6 +522,13 @@ export const SessionNotificationsBlock = <);};+export const CurrentModeBlock = (props: {+ data: CurrentModeUpdateNotificationEvent;+}) => {+ const { currentModeId } = props.data;+ return <div>Mode: {currentModeId}</div>;+};+export const ToolNotificationsBlock = (props: {data: Array<ToolCallNotificationEvent | ToolCallUpdateNotificationEvent>;}) => {diff --git a/frontend/src/components/chat/acp/common.tsx b/frontend/src/components/chat/acp/common.tsxindex 0724525b93..11bee411c9 100644--- a/frontend/src/components/chat/acp/common.tsx+++ b/frontend/src/components/chat/acp/common.tsx@@ -1,5 +1,6 @@/* Copyright 2024 Marimo. All rights reserved. */+import type { RequestPermissionResponse } from "@zed-industries/agent-client-protocol";import {CheckCircleIcon,Loader2,@@ -151,7 +152,7 @@ ConnectionStatus.displayName = "ConnectionStatus";interface PermissionRequestProps {permission: NonNullable<AgentPendingPermission>;- onResolve: (option: unknown) => void;+ onResolve: (option: RequestPermissionResponse) => void;}export const PermissionRequest: React.FC<PermissionRequestProps> = memo(@@ -179,7 +180,14 @@ export const PermissionRequest: React.FC<PermissionRequestProps> = memo(? "text-[var(--blue-10)]": "text-[var(--red-10)]"}- onClick={() => onResolve(option)}+ onClick={() =>+ onResolve({+ outcome: {+ outcome: "selected",+ optionId: option.optionId,+ },+ })+ }>{option.kind.startsWith("allow") && (<CheckCircleIcon className="h-3 w-3 mr-1" />diff --git a/frontend/src/components/chat/acp/prompt.ts b/frontend/src/components/chat/acp/prompt.tsindex d63f53e2b0..f9c4718f94 100644--- a/frontend/src/components/chat/acp/prompt.ts+++ b/frontend/src/components/chat/acp/prompt.ts@@ -3,7 +3,7 @@export function getAgentPrompt(filename: string) {return `I am currently editing a marimo notebook.- You can read or write to the notebook at @${filename}+ You can read or write to the notebook at ${filename}If you make edits to the notebook, only edit the contents inside the function decorator with @app.cell.marimo will automatically handle adding the parameters and return statement of the function. For example,@@ -11,7 +11,7 @@ export function getAgentPrompt(filename: string) {\`\`\`@app.cell- def __():+ def _():<your code here>return\`\`\`@@ -37,6 +37,7 @@ export function getAgentPrompt(filename: string) {7. The last expression in a cell is automatically displayed, just like in Jupyter notebooks.8. Don't include comments in markdown cells9. Don't include comments in SQL cells+ 10. Never define anything using \`global\`.## Reactivity@@ -115,14 +116,29 @@ export function getAgentPrompt(filename: string) {- \`mo.md(text)\` - display markdown- \`mo.stop(predicate, output=None)\` - stop execution conditionally+ - \`mo.output.append(value)\` - append to the output when it is not the last expression+ - \`mo.output.replace(value)\` - replace the output when it is not the last expression- \`mo.Html(html)\` - display HTML- \`mo.image(image)\` - display an image- \`mo.hstack(elements)\` - stack elements horizontally- \`mo.vstack(elements)\` - stack elements vertically- \`mo.tabs(elements)\` - create a tabbed interface++## Examples+ <example title="Markdown ccell">+ ${formatCells([+ `+ mo.md("""+ # Hello world+ This is a _markdown_ **cell**.+ """)+ `,+ ])}+ </example>+<example title="Basic UI with reactivity">${formatCells([`@@ -207,6 +223,19 @@ export function getAgentPrompt(filename: string) {])}</example>+ <example title="Conditional Outputs">+ ${formatCells([+ `+ mo.stop(not data.value, mo.md("No data to display"))++ if mode.value == "scatter":+ mo.output.replace(render_scatter(data.value))+ else:+ mo.output.replace(render_bar_chart(data.value))+ `,+ ])}+ </example>+<example title="Interactive chart with Altair">${formatCells([`@@ -256,25 +285,19 @@ export function getAgentPrompt(filename: string) {}function formatCells(cells: string[]) {- // Option 1:- // return cells.map((cell) => {- // return `# Cell ${cell}`;- // });-const indent = " ";const indentCode = (code: string) => {return code.trim().split("\n")- .map((line) => indent + line)+ .map((line) => (indent + line).trimEnd()).join("\n");};- // Option 2:const formatCell = (cell: string) => {return `@app.cell- def __():+ def _():${indentCode(cell)}return`;diff --git a/frontend/src/components/chat/acp/state.ts b/frontend/src/components/chat/acp/state.tsindex 9e16328d32..9d07a8c5c4 100644--- a/frontend/src/components/chat/acp/state.ts+++ b/frontend/src/components/chat/acp/state.ts@@ -259,5 +259,5 @@ export function getAgentSessionSupport(export function getAgentConnectionCommand(agentId: ExternalAgentId): string {const port = AGENT_CONFIG[agentId].port;const command = AGENT_CONFIG[agentId].command;- return `npx supergateway --stdio\\\n "${command}" \\\n --outputTransport ws --port ${port} `;+ return `npx stdio-to-ws "${command}" --port ${port}`;}diff --git a/frontend/src/components/chat/acp/types.ts b/frontend/src/components/chat/acp/types.tsindex 9bfdfa0340..fe8b023968 100644--- a/frontend/src/components/chat/acp/types.ts+++ b/frontend/src/components/chat/acp/types.ts@@ -2,10 +2,16 @@import type { ContentBlock } from "@zed-industries/agent-client-protocol";import type { groupNotifications, useAcpClient } from "use-acp";+export type SessionMode = ReturnType<typeof useAcpClient>["sessionMode"];+export type NotificationEvent = Awaited<ReturnType<typeof groupNotifications>>[number][number];+export type AvailableCommands = ReturnType<+ typeof useAcpClient+>["availableCommands"];+export type AgentConnectionState = ReturnType<typeof useAcpClient>["connectionState"];@@ -49,6 +55,8 @@ export type ToolCallNotificationEvent = NotificationDataOf<"tool_call">;export type ToolCallUpdateNotificationEvent =NotificationDataOf<"tool_call_update">;export type PlanNotificationEvent = NotificationDataOf<"plan">;+export type CurrentModeUpdateNotificationEvent =+ NotificationDataOf<"current_mode_update">;export type ContentBlockType = ContentBlock["type"];export type ContentBlockOf<T extends ContentBlockType> = Extract<diff --git a/frontend/src/core/codemirror/lsp/federated-lsp.ts b/frontend/src/core/codemirror/lsp/federated-lsp.tsindex 2473b5df60..87d882e3e6 100644--- a/frontend/src/core/codemirror/lsp/federated-lsp.ts+++ b/frontend/src/core/codemirror/lsp/federated-lsp.ts@@ -4,7 +4,7 @@ import type { LanguageServerPlugin } from "@marimo-team/codemirror-languageserveimport type * as LSP from "vscode-languageserver-protocol";import { Objects } from "@/utils/objects";import type { ILanguageServerClient } from "./types";-import { getLSPDocument } from "./utils.ts";+import { getLSPDocument } from "./utils";function removeFalseyValues<T extends object>(obj: T): T {return Objects.filter(obj, (value) => value !== false && value !== null) as T;diff --git a/frontend/src/stories/cell.stories.tsx b/frontend/src/stories/cell.stories.tsxindex a9f6bd28ce..05f918e338 100644--- a/frontend/src/stories/cell.stories.tsx+++ b/frontend/src/stories/cell.stories.tsx@@ -11,7 +11,7 @@ import {import { defaultUserConfig } from "@/core/config/config-schema";import { connectionAtom } from "@/core/network/connection";import { requestClientAtom } from "@/core/network/requests";-import { resolveRequestClient } from "@/core/network/resolve.ts";+import { resolveRequestClient } from "@/core/network/resolve";import type { CellConfig } from "@/core/network/types";import { WebSocketState } from "@/core/websocket/types";import { MultiColumn } from "@/utils/id-tree";diff --git a/frontend/src/stories/layout/vertical/one-column.stories.tsx b/frontend/src/stories/layout/vertical/one-column.stories.tsxindex 9f5a299ae7..c6a9a4b8b8 100644--- a/frontend/src/stories/layout/vertical/one-column.stories.tsx+++ b/frontend/src/stories/layout/vertical/one-column.stories.tsx@@ -9,7 +9,7 @@ import { defaultUserConfig, parseAppConfig } from "@/core/config/config-schema";import { showCodeInRunModeAtom } from "@/core/meta/state";import { connectionAtom } from "@/core/network/connection";import { requestClientAtom } from "@/core/network/requests";-import { resolveRequestClient } from "@/core/network/resolve.ts";+import { resolveRequestClient } from "@/core/network/resolve";import { WebSocketState } from "@/core/websocket/types";import { MultiColumn } from "@/utils/id-tree";import type { Milliseconds, Seconds } from "@/utils/time";diff --git a/marimo/_server/api/endpoints/file_explorer.py b/marimo/_server/api/endpoints/file_explorer.pyindex 208f91898c..bdd0fea3e4 100644--- a/marimo/_server/api/endpoints/file_explorer.py+++ b/marimo/_server/api/endpoints/file_explorer.py@@ -7,6 +7,7 @@ from typing import TYPE_CHECKINGfrom starlette.authentication import requiresfrom marimo import _loggers+from marimo._server.api.deps import AppStatefrom marimo._server.api.utils import parse_requestfrom marimo._server.files.os_file_system import OSFileSystemfrom marimo._server.models.files import (@@ -213,10 +214,16 @@ async def update_file(schema:$ref: "#/components/schemas/FileUpdateResponse""""+ app_state = AppState(request)body = await parse_request(request, cls=FileUpdateRequest)try:file_system.get_details(body.path)info = file_system.update_file(body.path, body.contents)++ # Handle marimo notebook reload if there's an active session+ session_manager = app_state.session_manager+ await session_manager.handle_file_change(body.path)+return FileUpdateResponse(success=True, info=info)except Exception as e:LOGGER.error(f"Error updating file or directory: {e}")diff --git a/marimo/_server/sessions.py b/marimo/_server/sessions.pyindex 6ed87434e9..0525e16e3b 100644--- a/marimo/_server/sessions.py+++ b/marimo/_server/sessions.py@@ -783,6 +783,9 @@ class SessionManager:self.include_code = include_codeself.ttl_seconds = ttl_secondsself.lsp_server = lsp_server+ self.file_change_handler = SessionFileChangeHandler(+ self, config_manager+ )self.watcher_manager = FileWatcherManager()self.watch = watchself.recents = RecentFilesManager()@@ -886,71 +889,15 @@ class SessionManager:returnasync def on_file_changed(path: Path) -> None:- LOGGER.debug(f"{path} was modified")# Skip if the session does not relate to the fileif session.app_file_manager.path != os.path.abspath(path):return- # Reload the file manager to get the latest code- try:- changed_cell_ids = session.app_file_manager.reload()- except Exception as e:- # If there are syntax errors, we just skip- # and don't send the changes- LOGGER.error(f"Error loading file: {e}")- return- # In run, we just call Reload()- if self.mode == SessionMode.RUN:- session.write_operation(Reload(), from_consumer_id=None)- return-- # Get the latest codes- codes = list(session.app_file_manager.app.cell_manager.codes())- cell_ids = list(- session.app_file_manager.app.cell_manager.cell_ids()- )- # Send the updated cell ids and codes to the frontend- session.write_operation(- UpdateCellIdsRequest(cell_ids=cell_ids),- from_consumer_id=None,+ # Use the centralized file change handler+ await self.file_change_handler.handle_file_change(+ str(path), [session])- # Check if we should auto-run cells based on config- should_autorun = (- self._config_manager.get_config()["runtime"]["watcher_on_save"]- == "autorun"- )-- # Auto-run cells if configured- if should_autorun:- changed_cell_ids_list = list(changed_cell_ids)- cell_ids_to_idx = {- cell_id: idx for idx, cell_id in enumerate(cell_ids)- }- changed_codes = [- codes[cell_ids_to_idx[cell_id]]- for cell_id in changed_cell_ids_list- ]-- # This runs the request and also runs UpdateCellCodes- session.put_control_request(- ExecuteMultipleRequest(- cell_ids=changed_cell_ids_list,- codes=changed_codes,- request=None,- ),- from_consumer_id=None,- )- else:- session.write_operation(- UpdateCellCodes(- cell_ids=cell_ids,- codes=codes,- code_is_stale=True,- ),- from_consumer_id=None,- )-session._unsubscribe_file_watcher_ = on_file_changed # type: ignoreself.watcher_manager.add_callback(@@ -1000,6 +947,12 @@ class SessionManager:self._start_file_watcher_for_session(session)return False, str(e)+ async def handle_file_change(self, path: str) -> None:+ """Handle a file change."""+ await self.file_change_handler.handle_file_change(+ path, list(self.sessions.values())+ )+def get_session(self, session_id: SessionId) -> Optional[Session]:session = self.sessions.get(session_id)if session:@@ -1168,6 +1121,119 @@ class SessionManager:)+class SessionFileChangeHandler:+ def __init__(+ self,+ session_manager: SessionManager,+ config_manager: MarimoConfigManager,+ ) -> None:+ self.session_manager = session_manager+ self.config_manager = config_manager+ # Track ongoing file change operations to prevent duplicates+ self._file_change_locks: dict[str, asyncio.Lock] = {}++ async def handle_file_change(+ self, file_path: str, sessions: list[Session]+ ) -> None:+ """Handle file changes for marimo notebooks.++ This method reloads the notebook and sends appropriate operations+ to the frontend when a marimo file is modified.+ """+ abs_file_path = os.path.abspath(file_path)++ # Use a lock to prevent concurrent processing of the same file+ if abs_file_path not in self._file_change_locks:+ self._file_change_locks[abs_file_path] = asyncio.Lock()++ async with self._file_change_locks[abs_file_path]:+ # Find all sessions associated with this file+ sessions_for_file: list[Session] = []+ for s in sessions:+ if s.app_file_manager.path == abs_file_path:+ sessions_for_file.append(s)++ if not sessions_for_file:+ # No active session for this file+ return++ if len(sessions_for_file) > 1:+ LOGGER.error(+ f"Only one session should exist for a file: {abs_file_path}"+ )++ self._handle_file_change(+ abs_file_path,+ sessions_for_file[0],+ )++ def _handle_file_change(+ self,+ file_path: str,+ session: Session,+ ) -> None:+ LOGGER.debug(f"{file_path} was modified, handling {session}")++ # Reload the file manager to get the latest code+ try:+ changed_cell_ids = session.app_file_manager.reload()+ except Exception as e:+ # If there are syntax errors, we just skip+ # and don't send the changes+ LOGGER.error(f"Error loading file: {e}")+ return++ # In run mode, we just call Reload()+ if self.session_manager.mode == SessionMode.RUN:+ session.write_operation(Reload(), from_consumer_id=None)+ return++ # Get the latest codes+ codes = list(session.app_file_manager.app.cell_manager.codes())+ cell_ids = list(session.app_file_manager.app.cell_manager.cell_ids())+ # Send the updated cell ids and codes to the frontend+ session.write_operation(+ UpdateCellIdsRequest(cell_ids=cell_ids),+ from_consumer_id=None,+ )++ # Check if we should auto-run cells based on config+ watcher_on_save = self.config_manager.get_config()["runtime"][+ "watcher_on_save"+ ]+ should_autorun = watcher_on_save == "autorun"++ # Auto-run cells if configured+ if should_autorun:+ changed_cell_ids_list = list(changed_cell_ids)+ cell_ids_to_idx = {+ cell_id: idx for idx, cell_id in enumerate(cell_ids)+ }+ changed_codes = [+ codes[cell_ids_to_idx[cell_id]]+ for cell_id in changed_cell_ids_list+ ]++ # This runs the request and also runs UpdateCellCodes+ session.put_control_request(+ ExecuteMultipleRequest(+ cell_ids=changed_cell_ids_list,+ codes=changed_codes,+ request=None,+ ),+ from_consumer_id=None,+ )+ else:+ session.write_operation(+ UpdateCellCodes(+ cell_ids=cell_ids,+ codes=codes,+ code_is_stale=True,+ ),+ from_consumer_id=None,+ )++def send_message_to_consumer(session: Session,operation: MessageOperation,diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b1160153ae..4ef5fe8678 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -287,8 +287,8 @@ importers:specifier: ^5.5.0version: 5.5.0'@zed-industries/agent-client-protocol':- specifier: ^0.1.2- version: 0.1.2+ specifier: ^0.3.1+ version: 0.3.1ai:specifier: ^5.0.30version: 5.0.30([email protected])@@ -458,8 +458,8 @@ importers:specifier: ^1.1.1version: 1.1.1use-acp:- specifier: ^0.1.5- version: 0.1.5(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]([email protected]))+ specifier: ^0.2.3+ version: 0.2.3(@types/[email protected])([email protected]([email protected]))([email protected])([email protected]([email protected]))use-resize-observer:specifier: ^9.1.0@@ -4234,8 +4234,8 @@ packages:'@xtuc/[email protected]':resolution: {integrity: sha512-NuHqBY1PB/D8xU6s/thBgOAiAP7HOYDQ32+BFZILJ8ivkUkAHQnWfn6WhL79Owj1qmUnoN/YPhktdIoucipkAQ==}- '@zed-industries/[email protected]':- resolution: {integrity: sha512-A1RCN7Uf09vngbhBVLiZENenKYOYD2OGiILLGXPaSBloDbem8xmLaDmrKQuYl0kjLJ1DcWmVaHUv97n1l5vJ6w==}+ '@zed-industries/[email protected]':+ resolution: {integrity: sha512-G3gGwNZ18vuuo6rDCo8eoGs/V/P2stIMV7srlaTNXf3u8qAoUNm91p2qhMurR/bCebq8J8yWCKuBZXdC/E162w==}resolution: {integrity: sha512-d8XPSGjfyzlXC3Xx891DJRyZfqk5JU0BJrDQcsWomFIV1/BIzPW5HDH5iDdWpqWaav0YVIEzT1RHTwWr0FFshA==}@@ -9297,8 +9297,8 @@ packages:resolution: {integrity: sha512-WypcfiRhfeUP9vvF0j6rw0J3hrWrw6iZv3+22h6iRMJ/8z1Tj6XfLP4DsUix5MhMPnXpiHDoKyoZ/bdCkwBCiQ==}- resolution: {integrity: sha512-PmsjtVOLtMeuCYp/8zt9CiQ7kuS8p4Umq2cANXvAMcLFuVxxD8Z3FyMKhjuUS49s9a/gDtvXtrpPs/E+VrYyuQ==}+ resolution: {integrity: sha512-bcnKK82iJctyk+gp/8AgGnbd7WoteU2fVa+GDAJSZuOoze6zN3CiqCYBCTUnpyJKmfzQrSL3okUblt0FITArBw==}peerDependencies:react: ^19react-dom: ^19@@ -14455,7 +14455,7 @@ snapshots:'@xtuc/[email protected]': {}- '@zed-industries/[email protected]':+ '@zed-industries/[email protected]':dependencies:zod: 3.25.76@@ -20572,9 +20572,9 @@ snapshots:querystringify: 2.2.0requires-port: 1.0.0- [email protected](@types/[email protected])([email protected]([email protected]))([email protected])([email protected]([email protected])):+ [email protected](@types/[email protected])([email protected]([email protected]))([email protected])([email protected]([email protected])):dependencies:- '@zed-industries/agent-client-protocol': 0.1.2+ '@zed-industries/agent-client-protocol': 0.3.1react: 19.1.1react-dom: 19.1.1([email protected])diff --git a/pyproject.toml b/pyproject.tomlindex cddac2e4fc..755278277b 100644--- a/pyproject.toml+++ b/pyproject.toml@@ -175,6 +175,7 @@ dependencies = ["leafmap~=0.39.2","panel~=1.5.3","polars~=1.9.0",+ "duckdb==1.3.0",# Types in 2.2.0 don't work great with mypy"narwhals>=1.34.1, <2.2.0","matplotlib>=3.8.0",diff --git a/tests/_server/api/endpoints/test_file_explorer.py b/tests/_server/api/endpoints/test_file_explorer.pyindex fcc9586c2b..c740724126 100644--- a/tests/_server/api/endpoints/test_file_explorer.py+++ b/tests/_server/api/endpoints/test_file_explorer.py@@ -6,7 +6,7 @@ from pathlib import Pathfrom tempfile import TemporaryDirectoryfrom typing import TYPE_CHECKING-from tests._server.mocks import token_header+from tests._server.mocks import get_session_manager, token_headerif TYPE_CHECKING:from starlette.testclient import TestClient@@ -91,6 +91,29 @@ def test_update_file(client: TestClient) -> None:f.write(test_content)+def test_update_file_with_session(client: TestClient) -> None:+ sm = get_session_manager(client)+ file_path = sm.file_router.get_unique_file_key()+ assert file_path+ file_path = Path(file_path)+ assert file_path.exists()+ response = client.post(+ "/api/files/update",+ headers=HEADERS,+ json={+ "path": str(file_path),+ "contents": "@app.cell\ndef _(): x=10; x\n",+ },+ )+ assert response.status_code == 200, response.text+ assert response.headers["content-type"] == "application/json"+ assert response.json()["success"] is True+ file_contents = file_path.read_text()+ assert "@app.cell" in file_contents+ assert "x=10; x" in file_contents+ assert len(sm.file_change_handler._file_change_locks) == 1++def test_move_file_or_directory(client: TestClient) -> None:response = client.post("/api/files/move",diff --git a/tests/_server/test_sessions.py b/tests/_server/test_sessions.pyindex 2f0811f6ac..1da8296618 100644--- a/tests/_server/test_sessions.py+++ b/tests/_server/test_sessions.py@@ -443,24 +443,24 @@ def test_session_with_kiosk_consumers() -> None:reason="This test is flaky on Python 3.9",)@save_and_restore_main-async def test_session_manager_file_watching() -> None:+async def test_session_manager_file_watching(tmp_path: Path) -> None:# Create a temporary file- with NamedTemporaryFile(delete=False, suffix=".py") as tmp_file:- tmp_path = Path(tmp_file.name)- # Write initial notebook content- tmp_file.write(- b"""import marimo+ tmp_file = tmp_path / "test.py"+ # Write initial notebook content+ tmp_file.write_text(+ """import marimoapp = marimo.App()@app.celldef __():1"""- )+ )+ file_key = str(tmp_file)try:# Create a session manager with file watching enabled- file_router = AppFileRouter.from_filename(MarimoPath(str(tmp_path)))+ file_router = AppFileRouter.from_filename(MarimoPath(tmp_file))session_manager = SessionManager(file_router=file_router,mode=SessionMode.EDIT,@@ -498,10 +498,10 @@ def __():session_id=session_id,session_consumer=session_consumer,query_params={},- file_key=str(tmp_path),+ file_key=file_key,)- tmp_path.write_text(+ tmp_file.write_text("""import marimoapp = marimo.App()@@ -537,13 +537,13 @@ def __():session_id=SessionId("test2"),session_consumer=session_consumer2,query_params={},- file_key=str(tmp_path),+ file_key=file_key,)# Modify the file againoperations.clear()operations2.clear()- tmp_path.write_text(+ tmp_file.write_text("""import marimoapp = marimo.App()@@ -576,7 +576,7 @@ def __():operations.clear()operations2.clear()- tmp_path.write_text(+ tmp_file.write_text("""import marimoapp = marimo.App()@@ -601,7 +601,6 @@ def __():finally:# Cleanupsession_manager.shutdown()- os.remove(tmp_path)@save_and_restore_main@@ -788,6 +787,7 @@ def __():})session_manager._config_manager = config_reader_lazy+ session_manager.file_change_handler.config_manager = config_reader_lazy# Reset the mocksession_consumer.put_control_request.reset_mock()