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
Remove run-stale-cells from Suggest edits (#11612)
Trevor Manz02877cd4ae29
diff --git a/docs/guides/editor_features/tools.md b/docs/guides/editor_features/tools.mdindex e2604b5422..73ae5112c7 100644--- a/docs/guides/editor_features/tools.md+++ b/docs/guides/editor_features/tools.md@@ -65,7 +65,6 @@ reference tools through the [marimo MCP server](mcp.md#mcp-server).| Tool | Description ||------|-------------|| **edit_notebook** | Propose adding, removing, or updating cells. Changes appear in the notebook for the user to keep or discard. This tool does not run cells. |-| **run_stale_cells** | Run cells that are stale (outdated due to upstream changes). Triggers execution of affected cells to update the notebook state. |## Web search and fetchdiff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsxindex 072ee6fd48..2c89379029 100644--- a/frontend/src/components/chat/chat-panel.tsx+++ b/frontend/src/components/chat/chat-panel.tsx@@ -493,7 +493,7 @@ const ChatPanelBody = () => {setAbortNotice(null);});const runtimeManager = useRuntimeManager();- const { invokeAiTool, sendRun } = useRequestClient();+ const { invokeAiTool } = useRequestClient();const { openModal, closeModal } = useImperativeModal();const activeChatId = activeChat?.id;@@ -502,12 +502,10 @@ const ChatPanelBody = () => {const store = useStore();const { addStagedCell } = useStagedAICellsActions();- const { prepareForRun, createCell } = useCellActions();+ const { createCell } = useCellActions();const toolContext: ToolNotebookContext = {addStagedCell,createCell,- prepareForRun,- sendRun,store,};diff --git a/frontend/src/core/ai/tools/__tests__/edit-notebook-tool.test.ts b/frontend/src/core/ai/tools/__tests__/edit-notebook-tool.test.tsindex e186e0d7b6..81e9e43448 100644--- a/frontend/src/core/ai/tools/__tests__/edit-notebook-tool.test.ts+++ b/frontend/src/core/ai/tools/__tests__/edit-notebook-tool.test.ts@@ -65,8 +65,6 @@ describe("EditNotebookTool", () => {let toolContext: {addStagedCell: ReturnType<typeof vi.fn>;createCell: ReturnType<typeof vi.fn>;- prepareForRun: ReturnType<typeof vi.fn>;- sendRun: ReturnType<typeof vi.fn>;store: ReturnType<typeof getDefaultStore>;};@@ -82,8 +80,6 @@ describe("EditNotebookTool", () => {store.set(stagedAICellsAtom, new Map(current).set(cellId, edit));}),createCell: vi.fn(),- prepareForRun: vi.fn(),- sendRun: vi.fn().mockResolvedValue(null),store,};tool = new EditNotebookTool();diff --git a/frontend/src/core/ai/tools/__tests__/registry.test.ts b/frontend/src/core/ai/tools/__tests__/registry.test.tsindex 2747c5d9e7..6a2ba73e25 100644--- a/frontend/src/core/ai/tools/__tests__/registry.test.ts+++ b/frontend/src/core/ai/tools/__tests__/registry.test.ts@@ -10,6 +10,23 @@ import { TestFrontendTool } from "../sample-tool";const INVALID_KEYS_IN_SCHEMA_PARAMS = new Set(["anyOf", "oneOf"]);describe("FrontendToolRegistry", () => {+ it("only offers cell proposals with Suggest edits access", () => {+ expect(+ Object.fromEntries(+ COPILOT_MODES.map((mode) => [+ mode,+ FRONTEND_TOOL_REGISTRY.getToolSchemas(mode).map((tool) => tool.name),+ ]),+ ),+ ).toEqual({+ manual: [],+ ask: [],+ agent: ["edit_notebook_tool"],+ code_mode: [],+ });+ expect(FRONTEND_TOOL_REGISTRY.has("run_stale_cells_tool")).toBe(false);+ });+it("registers tools via constructor and supports has()", () => {const registry = new FrontendToolRegistry([new TestFrontendTool()]);expect(registry.has("test_frontend_tool")).toBe(true);diff --git a/frontend/src/core/ai/tools/__tests__/run-cells-tool.test.ts b/frontend/src/core/ai/tools/__tests__/run-cells-tool.test.tsdeleted file mode 100644index ebc78f4dcc..0000000000--- a/frontend/src/core/ai/tools/__tests__/run-cells-tool.test.ts+++ /dev/null@@ -1,656 +0,0 @@-/* Copyright 2026 Marimo. All rights reserved. */--import { getDefaultStore } from "jotai";-import { beforeEach, describe, expect, it, vi } from "vitest";-import { MockNotebook } from "@/__mocks__/notebook";-import { cellId } from "@/__tests__/branded";-import { notebookAtom } from "@/core/cells/cells";-import type { CellId } from "@/core/cells/ids";-import { RunStaleCellsTool } from "../run-cells-tool";--// Mock runCells-vi.mock("@/components/editor/cell/useRunCells", () => ({- runCells: vi.fn(),-}));--// Mock getCellContextData-vi.mock("../../context/providers/cell-output", () => ({- getCellContextData: vi.fn(),-}));--import { runCells } from "@/components/editor/cell/useRunCells";-import { getCellContextData } from "../../context/providers/cell-output";--describe("RunStaleCellsTool", () => {- let store: ReturnType<typeof getDefaultStore>;- let tool: RunStaleCellsTool;- let cellId1: CellId;- let cellId2: CellId;- let cellId3: CellId;- let toolContext: {- addStagedCell: ReturnType<typeof vi.fn>;- createCell: ReturnType<typeof vi.fn>;- prepareForRun: ReturnType<typeof vi.fn>;- sendRun: ReturnType<typeof vi.fn>;- store: ReturnType<typeof getDefaultStore>;- };-- beforeEach(() => {- store = getDefaultStore();- toolContext = {- addStagedCell: vi.fn(),- createCell: vi.fn(),- prepareForRun: vi.fn(),- sendRun: vi.fn().mockResolvedValue(null),- store,- };-- tool = new RunStaleCellsTool({ postExecutionDelay: 0 });-- cellId1 = cellId("cell-1");- cellId2 = cellId("cell-2");- cellId3 = cellId("cell-3");-- // Reset mocks- vi.clearAllMocks();- });-- describe("no stale cells", () => {- it("should return success message when no stale cells exist", async () => {- const notebook = MockNotebook.notebookState({- cellData: {- [cellId1]: {- code: "x = 1",- edited: false,- lastCodeRun: "x = 1",- lastExecutionTime: 100,- },- },- });- // Make sure cell is not stale by setting runtime state- notebook.cellRuntime[cellId1] = {- ...notebook.cellRuntime[cellId1],- runElapsedTimeMs: 100 as never,- status: "idle",- };- store.set(notebookAtom, notebook);-- const result = await tool.handler({}, toolContext as never);-- expect(result.status).toBe("success");- expect(result.message).toBe("No stale cells found.");- expect(result.cellsToOutput).toBeUndefined();- expect(vi.mocked(runCells)).not.toHaveBeenCalled();- });- });-- describe("running stale cells", () => {- it("should run stale cells and return their outputs", async () => {- const notebook = MockNotebook.notebookState({- cellData: {- [cellId1]: {- code: "x = 1",- edited: true,- lastCodeRun: null,- },- [cellId2]: {- code: "y = 2",- edited: false,- lastCodeRun: "y = 2",- lastExecutionTime: 100,- },- [cellId3]: {- code: "z = 3",- edited: true,- lastCodeRun: "z = 2",- },- },- });- // Make cellId2 not stale- notebook.cellRuntime[cellId2] = {- ...notebook.cellRuntime[cellId2],- runElapsedTimeMs: 100 as never,- status: "idle",- };- store.set(notebookAtom, notebook);-- // Mock runCells to update cell runtime status- vi.mocked(runCells).mockImplementation(async () => {- const updatedNotebook = store.get(notebookAtom);- updatedNotebook.cellRuntime[cellId1] = {- ...updatedNotebook.cellRuntime[cellId1],- status: "idle",- };- updatedNotebook.cellRuntime[cellId3] = {- ...updatedNotebook.cellRuntime[cellId3],- status: "idle",- };- store.set(notebookAtom, updatedNotebook);- });-- // Mock getCellContextData to return outputs- vi.mocked(getCellContextData).mockImplementation((cellId) => {- if (cellId === cellId1) {- return {- cellOutput: {- outputType: "text",- processedContent: "1",- imageUrl: null,- output: {},- },- consoleOutputs: null,- cellName: "cell1",- } as never;- }- if (cellId === cellId3) {- return {- cellOutput: {- outputType: "text",- processedContent: "3",- imageUrl: null,- output: {},- },- consoleOutputs: null,- cellName: "cell3",- } as never;- }- return {} as never;- });-- const result = await tool.handler({}, toolContext as never);-- expect(result.status).toBe("success");- expect(result.cellsToOutput).toBeDefined();- expect(result.cellsToOutput).toHaveProperty(cellId1);- expect(result.cellsToOutput).toHaveProperty(cellId3);- expect(result.cellsToOutput).not.toHaveProperty(cellId2);-- // Verify runCells was called with correct parameters- expect(vi.mocked(runCells)).toHaveBeenCalledWith({- cellIds: [cellId1, cellId3],- sendRun: toolContext.sendRun,- prepareForRun: toolContext.prepareForRun,- notebook,- });- });-- it("should handle cells with no output", async () => {- const notebook = MockNotebook.notebookState({- cellData: {- [cellId1]: { code: "x = 1", edited: true },- },- });- store.set(notebookAtom, notebook);-- // Mock runCells- vi.mocked(runCells).mockImplementation(async () => {- const updatedNotebook = store.get(notebookAtom);- updatedNotebook.cellRuntime[cellId1] = {- ...updatedNotebook.cellRuntime[cellId1],- status: "idle",- };- store.set(notebookAtom, updatedNotebook);- });-- // Mock getCellContextData to return no outputs- vi.mocked(getCellContextData).mockReturnValue({- cellOutput: null,- consoleOutputs: null,- cellName: "cell1",- } as never);-- const result = await tool.handler({}, toolContext as never);-- expect(result.status).toBe("success");- expect(result.cellsToOutput).toBeDefined();- expect(result.cellsToOutput?.[cellId1]).toBeNull();- });-- it("should handle cells with console output", async () => {- const notebook = MockNotebook.notebookState({- cellData: {- [cellId1]: { code: 'print("hello")', edited: true },- },- });- store.set(notebookAtom, notebook);-- // Mock runCells- vi.mocked(runCells).mockImplementation(async () => {- const updatedNotebook = store.get(notebookAtom);- updatedNotebook.cellRuntime[cellId1] = {- ...updatedNotebook.cellRuntime[cellId1],- status: "idle",- };- store.set(notebookAtom, updatedNotebook);- });-- // Mock getCellContextData to return console output- vi.mocked(getCellContextData).mockReturnValue({- cellOutput: null,- consoleOutputs: [- {- outputType: "text",- processedContent: "hello",- imageUrl: null,- output: {},- },- ],- cellName: "cell1",- } as never);-- const result = await tool.handler({}, toolContext as never);-- expect(result.status).toBe("success");- expect(result.cellsToOutput).toBeDefined();- expect(result.cellsToOutput?.[cellId1]?.consoleOutput).toContain("hello");- expect(result.message).toContain("Console output");- });-- it("should handle cells with media output", async () => {- const notebook = MockNotebook.notebookState({- cellData: {- [cellId1]: { code: "plt.plot()", edited: true },- },- });- store.set(notebookAtom, notebook);-- // Mock runCells- vi.mocked(runCells).mockImplementation(async () => {- const updatedNotebook = store.get(notebookAtom);- updatedNotebook.cellRuntime[cellId1] = {- ...updatedNotebook.cellRuntime[cellId1],- status: "idle",- };- store.set(notebookAtom, updatedNotebook);- });-- // Mock getCellContextData to return media output- vi.mocked(getCellContextData).mockReturnValue({- cellOutput: {- outputType: "media",- processedContent: null,- imageUrl: "https://example.com/image.png",- output: { mimetype: "image/png" },- },- consoleOutputs: null,- cellName: "cell1",- } as never);-- const result = await tool.handler({}, toolContext as never);-- expect(result.status).toBe("success");- expect(result.cellsToOutput).toBeDefined();- expect(result.cellsToOutput?.[cellId1]?.cellOutput).toContain(- "image/png",- );- expect(result.cellsToOutput?.[cellId1]?.cellOutput).toContain(- "https://example.com/image.png",- );- });-- it("should handle both cell output and console output", async () => {- const notebook = MockNotebook.notebookState({- cellData: {- [cellId1]: { code: 'x = 1; print("debug")', edited: true },- },- });- store.set(notebookAtom, notebook);-- // Mock runCells- vi.mocked(runCells).mockImplementation(async () => {- const updatedNotebook = store.get(notebookAtom);- updatedNotebook.cellRuntime[cellId1] = {- ...updatedNotebook.cellRuntime[cellId1],- status: "idle",- };- store.set(notebookAtom, updatedNotebook);- });-- // Mock getCellContextData to return both outputs- vi.mocked(getCellContextData).mockReturnValue({- cellOutput: {- outputType: "text",- processedContent: "1",- imageUrl: null,- output: {},- },- consoleOutputs: [- {- outputType: "text",- processedContent: "debug",- imageUrl: null,- output: {},- },- ],- cellName: "cell1",- } as never);-- const result = await tool.handler({}, toolContext as never);-- expect(result.status).toBe("success");- expect(result.cellsToOutput).toBeDefined();- expect(result.cellsToOutput?.[cellId1]?.cellOutput).toContain("1");- expect(result.cellsToOutput?.[cellId1]?.consoleOutput).toContain("debug");- });-- it("should handle cell output with object output", async () => {- const notebook = MockNotebook.notebookState({- cellData: {- [cellId1]: { code: "x = {'a': 1, 'b': 2}", edited: true },- },- });- store.set(notebookAtom, notebook);-- // Mock runCells- vi.mocked(runCells).mockImplementation(async () => {- const updatedNotebook = store.get(notebookAtom);- updatedNotebook.cellRuntime[cellId1] = {- ...updatedNotebook.cellRuntime[cellId1],- status: "idle",- };- store.set(notebookAtom, updatedNotebook);- });-- // Mock getCellContextData to return object output- vi.mocked(getCellContextData).mockReturnValue({- cellOutput: {- outputType: "text",- processedContent: null,- imageUrl: null,- output: { data: JSON.stringify({ a: 1, b: 2 }) },- },- consoleOutputs: null,- cellName: "cell1",- } as never);-- const result = await tool.handler({}, toolContext as never);-- expect(result.status).toBe("success");- expect(result.cellsToOutput).toBeDefined();- expect(result.cellsToOutput?.[cellId1]?.cellOutput).toEqual(- 'Output:\n{"a":1,"b":2}',- );- });-- it("should return success when all stale cells have no output", async () => {- const notebook = MockNotebook.notebookState({- cellData: {- [cellId1]: { code: "x = 1", edited: true },- [cellId2]: { code: "y = 2", edited: true },- },- });- store.set(notebookAtom, notebook);-- // Mock runCells- vi.mocked(runCells).mockImplementation(async () => {- const updatedNotebook = store.get(notebookAtom);- updatedNotebook.cellRuntime[cellId1] = {- ...updatedNotebook.cellRuntime[cellId1],- status: "idle",- };- updatedNotebook.cellRuntime[cellId2] = {- ...updatedNotebook.cellRuntime[cellId2],- status: "idle",- };- store.set(notebookAtom, updatedNotebook);- });-- // Mock getCellContextData to return no outputs for both cells- vi.mocked(getCellContextData).mockReturnValue({- cellOutput: null,- consoleOutputs: null,- cellName: "cell1",- } as never);-- const result = await tool.handler({}, toolContext as never);-- expect(result.status).toBe("success");- expect(result.cellsToOutput).toBeDefined();- // Both cells should be in the output as null- expect(result.cellsToOutput?.[cellId1]).toBeNull();- expect(result.cellsToOutput?.[cellId2]).toBeNull();- });- });-- describe("output truncation", () => {- it("should summarize text/html output instead of dumping raw content", async () => {- const notebook = MockNotebook.notebookState({- cellData: {- [cellId1]: { code: "fig.show()", edited: true },- },- });- store.set(notebookAtom, notebook);-- vi.mocked(runCells).mockImplementation(async () => {- const updatedNotebook = store.get(notebookAtom);- updatedNotebook.cellRuntime[cellId1] = {- ...updatedNotebook.cellRuntime[cellId1],- status: "idle",- };- store.set(notebookAtom, updatedNotebook);- });-- const largeHtml = `<div>${"x".repeat(2_000_000)}</div>`;- vi.mocked(getCellContextData).mockReturnValue({- cellOutput: {- outputType: "text",- processedContent: null,- imageUrl: null,- output: { mimetype: "text/html", data: largeHtml },- },- consoleOutputs: null,- cellName: "cell1",- } as never);-- const result = await tool.handler({}, toolContext as never);-- expect(result.status).toBe("success");- const output = result.cellsToOutput?.[cellId1]?.cellOutput ?? "";- expect(output).toContain("HTML Output:");- expect(output).toContain("text/html");- expect(output.length).toBeLessThan(200);- expect(output).not.toContain(largeHtml);- });-- it("should truncate large text output to MAX_TEXT_OUTPUT_CHARS", async () => {- const notebook = MockNotebook.notebookState({- cellData: {- [cellId1]: { code: "print(big_string)", edited: true },- },- });- store.set(notebookAtom, notebook);-- vi.mocked(runCells).mockImplementation(async () => {- const updatedNotebook = store.get(notebookAtom);- updatedNotebook.cellRuntime[cellId1] = {- ...updatedNotebook.cellRuntime[cellId1],- status: "idle",- };- store.set(notebookAtom, updatedNotebook);- });-- const largeText = "a".repeat(10_000);- vi.mocked(getCellContextData).mockReturnValue({- cellOutput: {- outputType: "text",- processedContent: largeText,- imageUrl: null,- output: { mimetype: "text/plain", data: largeText },- },- consoleOutputs: null,- cellName: "cell1",- } as never);-- const result = await tool.handler({}, toolContext as never);-- const output = result.cellsToOutput?.[cellId1]?.cellOutput ?? "";- expect(output).toContain("[TRUNCATED:");- expect(output).toContain("Full output visible in the notebook UI.");- // Output should be capped (2000 chars content + "Output:\n" prefix + truncation message)- expect(output.length).toBeLessThan(2200);- });-- it("should omit output for cells that exceed total output budget", async () => {- const cellIds = Array.from({ length: 25 }, (_, i) =>- cellId(`budget-cell-${i}`),- );- const cellData: Record<string, { code: string; edited: boolean }> = {};- for (const id of cellIds) {- cellData[id] = { code: "x = 1", edited: true };- }-- const notebook = MockNotebook.notebookState({ cellData });- store.set(notebookAtom, notebook);-- vi.mocked(runCells).mockImplementation(async () => {- const updatedNotebook = store.get(notebookAtom);- for (const id of cellIds) {- updatedNotebook.cellRuntime[id] = {- ...updatedNotebook.cellRuntime[id],- status: "idle",- };- }- store.set(notebookAtom, updatedNotebook);- });-- // Each cell produces ~2008 chars of formatted output ("Output:\n" + 2000 chars).- // After 20 cells the running total exceeds MAX_TOOL_OUTPUT_CHARS (40,000).- const content = "a".repeat(2000);- vi.mocked(getCellContextData).mockReturnValue({- cellOutput: {- outputType: "text",- processedContent: content,- imageUrl: null,- output: { mimetype: "text/plain", data: content },- },- consoleOutputs: null,- cellName: "cell",- } as never);-- const result = await tool.handler({}, toolContext as never);-- expect(result.cellsToOutput?.[cellIds[0]]?.cellOutput).toContain(- "Output:",- );- expect(result.cellsToOutput?.[cellIds[24]]?.cellOutput).toBe(- "Cell executed (output omitted due to context limits).",- );- });-- it("should use higher truncation limit for error outputs", async () => {- const notebook = MockNotebook.notebookState({- cellData: {- [cellId1]: { code: "raise Exception()", edited: true },- },- });- store.set(notebookAtom, notebook);-- vi.mocked(runCells).mockImplementation(async () => {- const updatedNotebook = store.get(notebookAtom);- updatedNotebook.cellRuntime[cellId1] = {- ...updatedNotebook.cellRuntime[cellId1],- status: "idle",- };- store.set(notebookAtom, updatedNotebook);- });-- // 2500 chars sits between MAX_TEXT_OUTPUT_CHARS (2000) and MAX_ERROR_OUTPUT_CHARS (3000)- const errorContent = "E".repeat(2500);- vi.mocked(getCellContextData).mockReturnValue({- cellOutput: {- outputType: "text",- processedContent: errorContent,- imageUrl: null,- output: {- mimetype: "application/vnd.marimo+error",- data: errorContent,- },- },- consoleOutputs: null,- cellName: "cell1",- } as never);-- const result = await tool.handler({}, toolContext as never);-- const output = result.cellsToOutput?.[cellId1]?.cellOutput ?? "";- expect(output).not.toContain("[TRUNCATED:");- expect(output).toContain(errorContent);- });-- it("should truncate large console output", async () => {- const notebook = MockNotebook.notebookState({- cellData: {- [cellId1]: { code: 'print("x" * 10000)', edited: true },- },- });- store.set(notebookAtom, notebook);-- vi.mocked(runCells).mockImplementation(async () => {- const updatedNotebook = store.get(notebookAtom);- updatedNotebook.cellRuntime[cellId1] = {- ...updatedNotebook.cellRuntime[cellId1],- status: "idle",- };- store.set(notebookAtom, updatedNotebook);- });-- const largeConsoleText = "x".repeat(10_000);- vi.mocked(getCellContextData).mockReturnValue({- cellOutput: null,- consoleOutputs: [- {- outputType: "text",- processedContent: largeConsoleText,- imageUrl: null,- output: { mimetype: "text/plain", data: largeConsoleText },- },- ],- cellName: "cell1",- } as never);-- const result = await tool.handler({}, toolContext as never);-- const consoleOutput =- result.cellsToOutput?.[cellId1]?.consoleOutput ?? "";- expect(consoleOutput).toContain("[TRUNCATED:");- expect(consoleOutput.length).toBeLessThan(2200);- });- });-- describe("cell execution completion", () => {- it("should complete immediately if cells are already idle", async () => {- const notebook = MockNotebook.notebookState({- cellData: {- [cellId1]: { code: "x = 1", edited: true },- },- });-- // Set cell runtime to already be idle- notebook.cellRuntime[cellId1] = {- ...notebook.cellRuntime[cellId1],- status: "idle",- };- store.set(notebookAtom, notebook);-- // Mock runCells to do nothing (cells already idle)- vi.mocked(runCells).mockResolvedValue();-- // Mock getCellContextData- vi.mocked(getCellContextData).mockReturnValue({- cellOutput: {- outputType: "text",- processedContent: "1",- imageUrl: null,- output: {},- },- consoleOutputs: null,- cellName: "cell1",- } as never);-- const result = await tool.handler({}, toolContext as never);-- expect(result.status).toBe("success");- expect(result.cellsToOutput).toBeDefined();- });- });-});diff --git a/frontend/src/core/ai/tools/base.ts b/frontend/src/core/ai/tools/base.tsindex 37e1c7fbea..9ed0b59a45 100644--- a/frontend/src/core/ai/tools/base.ts+++ b/frontend/src/core/ai/tools/base.ts@@ -3,7 +3,6 @@import { z } from "zod";import type { CreateCell } from "@/core/cells/actions";import type { CellId } from "@/core/cells/ids";-import type { ExecuteCellsRequest } from "@/core/network/types";import type { JotaiStore } from "@/core/state/jotai";import type { Edit } from "../staged-cells";import type { CopilotMode } from "./registry";@@ -67,9 +66,6 @@ export class ToolExecutionError extends Error {}}-// Can be any input-export type EmptyToolInput = unknown;-/*** Base interface for tool output responses.* Mirrors the SuccessResult dataclass from marimo/_ai/_tools/types.py@@ -114,8 +110,6 @@ export interface ToolNotebookContext {store: JotaiStore;addStagedCell: (payload: { cellId: CellId; edit: Edit }) => void;createCell: CreateCell;- prepareForRun: (payload: { cellId: CellId }) => void;- sendRun: (request: ExecuteCellsRequest) => Promise<null>;}export interface AiTool<TIn, TOut> {diff --git a/frontend/src/core/ai/tools/edit-notebook-tool.ts b/frontend/src/core/ai/tools/edit-notebook-tool.tsindex c7539bea9e..6beb2f7b8b 100644--- a/frontend/src/core/ai/tools/edit-notebook-tool.ts+++ b/frontend/src/core/ai/tools/edit-notebook-tool.ts@@ -254,7 +254,6 @@ export class EditNotebookTool implements AiTool<next_steps: ["If you need to perform more edits, call this tool again.","You should use the lint notebook tool to check for errors and lint issues. Fix them by editing the notebook.",- "You should use the run stale cells tool to run the cells that have been edited or newly added. This allows you to see the output of the cells and fix any errors.",],};};diff --git a/frontend/src/core/ai/tools/registry.ts b/frontend/src/core/ai/tools/registry.tsindex d856cdf64f..81f703a6d4 100644--- a/frontend/src/core/ai/tools/registry.ts+++ b/frontend/src/core/ai/tools/registry.ts@@ -9,7 +9,6 @@ import {type ToolNotebookContext,} from "./base";import { EditNotebookTool } from "./edit-notebook-tool";-import { RunStaleCellsTool } from "./run-cells-tool";import { formatToolDescription } from "./utils";export type AnyZodObject = ZodObject<z.ZodRawShape>;@@ -148,5 +147,4 @@ export class FrontendToolRegistry {export const FRONTEND_TOOL_REGISTRY = new FrontendToolRegistry([new EditNotebookTool(),- new RunStaleCellsTool(),]);diff --git a/frontend/src/core/ai/tools/run-cells-tool.ts b/frontend/src/core/ai/tools/run-cells-tool.tsdeleted file mode 100644index e4ae77c8a9..0000000000--- a/frontend/src/core/ai/tools/run-cells-tool.ts+++ /dev/null@@ -1,303 +0,0 @@-/* Copyright 2026 Marimo. All rights reserved. */--import type { FileUIPart } from "ai";-import { z } from "zod";-import { runCells } from "@/components/editor/cell/useRunCells";-import { notebookAtom } from "@/core/cells/cells";-import type { CellId } from "@/core/cells/ids";-import { staleCellIds } from "@/core/cells/utils";-import { type JotaiStore, waitFor } from "@/core/state/jotai";-import {- type BaseOutput,- getCellContextData,-} from "../context/providers/cell-output";-import {- type AiTool,- type EmptyToolInput,- type ToolDescription,- type ToolNotebookContext,- type ToolOutputBase,- toolOutputBaseSchema,-} from "./base";-import type { CopilotMode } from "./registry";--const POST_EXECUTION_DELAY = 200;-const WAIT_FOR_CELLS_TIMEOUT = 30_000;--// Output size limits to prevent exceeding LLM token limits.-const MAX_TEXT_OUTPUT_CHARS = 2000;-const MAX_ERROR_OUTPUT_CHARS = 3000;-const MAX_TOOL_OUTPUT_CHARS = 40_000;--interface CellOutput {- consoleOutput?: string;- cellOutput?: string;-}--// Must use Record instead of Map because Map serializes to JSON as {}-interface RunStaleCellsOutput extends ToolOutputBase {- cellsToOutput?: Record<CellId, CellOutput | null>;-}--const description: ToolDescription = {- baseDescription:- "Run cells in the current notebook that are stale. Stale cells are cells that have been edited or newly added. You can run this tool after editing the notebook or when requested. The output of the ran cells will be returned alongside metadata.",-};--const filePartSchema = z.object({- type: z.literal("file"),- url: z.string(),- mediaType: z.string(),-}) satisfies z.ZodType<FileUIPart>;--export class RunStaleCellsTool implements AiTool<- EmptyToolInput,- RunStaleCellsOutput-> {- public readonly name = "run_stale_cells_tool";- public readonly description = description;- public readonly schema = z.object({});- public readonly outputSchema = toolOutputBaseSchema.extend({- cellsToOutput: z- .record(- z.string(),- z- .object({- consoleOutput: z.string().optional(),- cellOutput: z.string().optional(),- consoleAttachments: z.array(filePartSchema).optional(),- cellAttachments: z.array(filePartSchema).optional(),- })- .nullable(),- )- .optional(),- }) satisfies z.ZodType<RunStaleCellsOutput>;- public readonly mode: CopilotMode[] = ["agent"];-- private readonly postExecutionDelay: number;-- public constructor(opts?: { postExecutionDelay?: number }) {- this.postExecutionDelay = opts?.postExecutionDelay ?? POST_EXECUTION_DELAY;- }-- public handler = async (- _args: EmptyToolInput,- toolContext: ToolNotebookContext,- ): Promise<RunStaleCellsOutput> => {- const { prepareForRun, sendRun, store } = toolContext;-- const notebook = store.get(notebookAtom);- const staleCells = staleCellIds(notebook);-- if (staleCells.length === 0) {- return {- status: "success",- message: "No stale cells found.",- };- }-- await runCells({- cellIds: staleCells,- sendRun,- prepareForRun,- notebook,- });-- // Wait for all cells to finish executing- const allCellsFinished = await this.waitForCellsToFinish(- store,- staleCells,- WAIT_FOR_CELLS_TIMEOUT,- this.postExecutionDelay,- );- if (!allCellsFinished) {- return {- status: "success",- message:- "No output was returned because some cells have not finished executing",- };- }-- // Get notebook state after cells have finished- const updatedNotebook = store.get(notebookAtom);-- const cellsToOutput = new Map<CellId, CellOutput | null>();- let outputHasErrors = false;- let hasAnyConsoleOutput = false;- let totalOutputChars = 0;-- for (const cellId of staleCells) {- const cellContextData = getCellContextData(cellId, updatedNotebook, {- includeConsoleOutput: true,- });-- const cellOutput = cellContextData.cellOutput;- const consoleOutputs = cellContextData.consoleOutputs;- const hasConsoleOutput = consoleOutputs && consoleOutputs.length > 0;-- // Track errors regardless of budget- if (- (cellOutput && this.outputHasErrors(cellOutput)) ||- (hasConsoleOutput &&- consoleOutputs.some((output) => this.outputHasErrors(output)))- ) {- outputHasErrors = true;- }-- if (!cellOutput && !hasConsoleOutput) {- cellsToOutput.set(cellId, null);- continue;- }-- // If total budget exceeded, summarize remaining cells- if (totalOutputChars >= MAX_TOOL_OUTPUT_CHARS) {- cellsToOutput.set(cellId, {- cellOutput: "Cell executed (output omitted due to context limits).",- });- continue;- }-- let cellOutputString: string | undefined;- let consoleOutputString: string | undefined;-- if (cellOutput) {- cellOutputString = this.formatOutputString(cellOutput);- totalOutputChars += cellOutputString.length;- }-- if (hasConsoleOutput) {- hasAnyConsoleOutput = true;- consoleOutputString = consoleOutputs- .map((output) => this.formatOutputString(output))- .join("\n");- consoleOutputString = this.truncateString(- consoleOutputString,- MAX_TEXT_OUTPUT_CHARS,- );- totalOutputChars += consoleOutputString.length;- }-- cellsToOutput.set(cellId, {- cellOutput: cellOutputString,- consoleOutput: consoleOutputString,- });- }-- if (cellsToOutput.size === 0) {- return {- status: "success",- message: "Stale cells have been run. No output was returned.",- };- }-- const nextSteps = [- "Review the output of the cells. The CellId is the key of the result object.",- outputHasErrors- ? "There are errors in the cells. Please fix them by using the edit notebook tool and the given CellIds."- : "You may edit the notebook further with the given CellIds.",- ];-- return {- status: "success",- cellsToOutput: Object.fromEntries(cellsToOutput),- message: hasAnyConsoleOutput- ? "Console output represents the stdout or stderr of the cell (eg. print statements)."- : undefined,- next_steps: nextSteps,- };- };-- private outputHasErrors(cellOutput: BaseOutput): boolean {- return (- cellOutput.output.mimetype === "application/vnd.marimo+error" ||- cellOutput.output.mimetype === "application/vnd.marimo+traceback"- );- }-- private formatOutputString(cellOutput: BaseOutput): string {- const { outputType, processedContent, imageUrl, output } = cellOutput;-- if (outputType === "media") {- const base = `Media Output: Contains ${output.mimetype} content`;- return imageUrl ? `${base}\nImage URL: ${imageUrl}` : base;- }-- if (output.mimetype === "text/html") {- // text/html (e.g. plotly figures, rich dataframes) can be millions of- // chars and is not interpretable by LLMs — summarize instead- const dataLength =- typeof output.data === "string"- ? output.data.length- : JSON.stringify(output.data).length;- return `HTML Output: text/html content (${dataLength.toLocaleString()} chars). Full output visible in notebook UI.`;- }-- const maxChars = this.outputHasErrors(cellOutput)- ? MAX_ERROR_OUTPUT_CHARS- : MAX_TEXT_OUTPUT_CHARS;-- let content = processedContent;- if (!content) {- content =- typeof output.data === "string"- ? output.data- : JSON.stringify(output.data);- }- return `Output:\n${this.truncateString(content, maxChars)}`;- }-- private truncateString(str: string, maxLength: number): string {- if (str.length <= maxLength) {- return str;- }- return `${str.slice(0, maxLength)}\n\n[TRUNCATED: ${str.length.toLocaleString()} → ${maxLength.toLocaleString()} chars. Full output visible in the notebook UI.]`;- }- /**- * Wait for cells to finish executing (status becomes "idle")- * Returns true if all cells finished executing, false if the timeout was reached- */- private async waitForCellsToFinish(- store: JotaiStore,- cellIds: CellId[],- timeout: number,- postExecutionDelay: number,- ): Promise<boolean> {- const checkAllFinished = (- notebook: ReturnType<typeof notebookAtom.read>,- ) => {- return cellIds.every((cellId) => {- const cellRuntime = notebook.cellRuntime[cellId];- return (- cellRuntime?.status !== "running" && cellRuntime?.status !== "queued"- );- });- };-- // Add a small delay after cells finish to allow console outputs to arrive- // Console outputs are streamed and might still be in-flight- const delayForConsoleOutputs = async () => {- if (postExecutionDelay > 0) {- await new Promise((resolve) => setTimeout(resolve, postExecutionDelay));- }- return true;- };-- // Return immediately if all cells are finished- if (checkAllFinished(store.get(notebookAtom))) {- return await delayForConsoleOutputs();- }-- // Wait for notebook state changes with timeout- try {- await Promise.race([- waitFor(notebookAtom, checkAllFinished),- new Promise<never>((_, reject) =>- setTimeout(() => reject(new Error("timeout")), timeout),- ),- ]);- return await delayForConsoleOutputs();- } catch {- return false;- }- }-}diff --git a/marimo/_server/ai/prompts.py b/marimo/_server/ai/prompts.pyindex cde6b5c293..d58b9bf3a9 100644--- a/marimo/_server/ai/prompts.py+++ b/marimo/_server/ai/prompts.py@@ -236,18 +236,18 @@ def _get_mode_intro_message(mode: CopilotMode) -> str:elif mode == "agent":return (f"{base_intro}"- "You have Suggest edits access - you have autonomy to resolve the user's query by using the tools provided. Please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved.\n"+ "You can inspect the notebook and propose cell changes for the user to review.\n""\n\n## Suggest edits\n"- "- You are encouraged to edit existing cells in the notebook or add new cells.\n"+ "- Use the notebook editing tool to propose changes to existing cells or add new cells for review.\n""- You should do the following things after editing the notebook:\n""\t 1. Use the lint notebook tool to check for errors and lint issues\n"- "\t 2. Run stale cells tool to run the code\n"- "\t 3. If there are errors in cells you have added, edit the existing cell. Don't add new cells to correct errors.\n"+ "\t 2. If there are errors in cells you have added, edit the existing cell. Don't add new cells to correct errors.\n""- If you say you're about to do something, actually do it in the same turn (run the tool call right after).\n""- Group code into logical cells, eg. functions should be in separate cells and all the calls will be in one cell. When asked for explanations or summaries, use markdown cells with proper formatting.\n\n""## Capabilities\n"- "- You can use a set of read and write tools to gather additional context from the notebook or environment (e.g., searching code, summarizing data, or reading documentation) and to modify the notebook (e.g., adding cells, editing cells, deleting cells).\n"+ "- You can use a set of read and write tools to gather additional context from the notebook or environment (e.g., searching code, summarizing data, or reading documentation) and to propose notebook changes (e.g., adding cells, editing cells, deleting cells).\n""## Limitations\n"+ "- Leave execution to the user. Do not run notebook cells or Python code.\n""- You must always explain to the user why you are using a tool before invoking it.\n")elif mode == "code_mode":diff --git a/tests/_server/ai/snapshots/chat_system_prompts.txt b/tests/_server/ai/snapshots/chat_system_prompts.txtindex 8e2145d676..6d7231b188 100644--- a/tests/_server/ai/snapshots/chat_system_prompts.txt+++ b/tests/_server/ai/snapshots/chat_system_prompts.txt@@ -460,21 +460,21 @@ import numpy as npYou are Marimo Copilot, an AI assistant integrated into the marimo notebook code editor.Your primary function is to help users create, analyze, and improve data science notebooks using marimo's reactive programming model.-You have Suggest edits access - you have autonomy to resolve the user's query by using the tools provided. Please keep going until the user's query is completely resolved, before ending your turn and yielding back to the user. Only terminate your turn when you are sure that the problem is solved.+You can inspect the notebook and propose cell changes for the user to review.## Suggest edits-- You are encouraged to edit existing cells in the notebook or add new cells.+- Use the notebook editing tool to propose changes to existing cells or add new cells for review.- You should do the following things after editing the notebook:1. Use the lint notebook tool to check for errors and lint issues- 2. Run stale cells tool to run the code- 3. If there are errors in cells you have added, edit the existing cell. Don't add new cells to correct errors.+ 2. If there are errors in cells you have added, edit the existing cell. Don't add new cells to correct errors.- If you say you're about to do something, actually do it in the same turn (run the tool call right after).- Group code into logical cells, eg. functions should be in separate cells and all the calls will be in one cell. When asked for explanations or summaries, use markdown cells with proper formatting.## Capabilities-- You can use a set of read and write tools to gather additional context from the notebook or environment (e.g., searching code, summarizing data, or reading documentation) and to modify the notebook (e.g., adding cells, editing cells, deleting cells).+- You can use a set of read and write tools to gather additional context from the notebook or environment (e.g., searching code, summarizing data, or reading documentation) and to propose notebook changes (e.g., adding cells, editing cells, deleting cells).## Limitations+- Leave execution to the user. Do not run notebook cells or Python code.- You must always explain to the user why you are using a tool before invoking it.Current notebook session ID: s_test. Use this session_id with tools that require it.