Skip to content

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

feat(ai): add "Fix with AI assistant" option for errors (#10024)

Shahmir Varqhaeb778e30d77b
diff --git a/frontend/src/components/chat/acp/agent-panel.tsx b/frontend/src/components/chat/acp/agent-panel.tsx
index 1794a6e13f..7b018e7674 100644
--- a/frontend/src/components/chat/acp/agent-panel.tsx
+++ b/frontend/src/components/chat/acp/agent-panel.tsx
@@ -49,6 +49,7 @@ import {
addContextCompletion,
CONTEXT_TRIGGER,
} from "@/components/editor/ai/completion-utils";
+import { pendingAiPromptAtom } from "@/core/ai/state";
import {
Select,
SelectContent,
@@ -72,6 +73,7 @@ import {
SendButton,
} from "../chat-components";
import { useFileState } from "../chat-utils";
+import { focusInputAndMoveToEnd } from "@/core/codemirror/utils";
import { ReadyToChatBlock } from "./blocks";
import {
convertFilesToResourceLinks,
@@ -305,6 +307,7 @@ interface PromptAreaProps {
onModeChange?: (mode: string) => void;
sessionModels?: SessionModelState | null;
onModelChange?: (modelId: string) => void;
+ inputRef: React.RefObject<ReactCodeMirrorRef | null>;
}
const PromptArea = memo<PromptAreaProps>(
@@ -322,8 +325,8 @@ const PromptArea = memo<PromptAreaProps>(
onModeChange,
sessionModels,
onModelChange,
+ inputRef,
}) => {
- const inputRef = useRef<ReactCodeMirrorRef | null>(null);
const promptCompletions: AdditionalCompletions | undefined = useMemo(() => {
if (!commands) {
return undefined;
@@ -660,6 +663,8 @@ const AgentPanel: React.FC = () => {
const [isLoading, setIsLoading] = useState(false);
const [error, setError] = useState<Error | string | null>(null);
const [promptValue, setPromptValue] = useState("");
+ const promptInputRef = useRef<ReactCodeMirrorRef | null>(null);
+ const [pendingPrompt, setPendingPrompt] = useAtom(pendingAiPromptAtom);
const { files, addFiles, clearFiles, removeFile } = useFileState();
const [sessionModels, setSessionModels] = useState<SessionModelState | null>(
null,
@@ -973,6 +978,34 @@ const AgentPanel: React.FC = () => {
},
);
+ // Consume a prompt queued by another part of the app (e.g. error auto-fix).
+ useEffect(() => {
+ if (
+ !activeSessionId ||
+ !agent ||
+ isLoading ||
+ connectionState.status !== "connected" ||
+ !pendingPrompt
+ ) {
+ return;
+ }
+ setPendingPrompt(null);
+ if (pendingPrompt.submit) {
+ void handlePromptSubmit(undefined, pendingPrompt.prompt);
+ } else {
+ setPromptValue(pendingPrompt.prompt);
+ focusInputAndMoveToEnd(promptInputRef);
+ }
+ }, [
+ activeSessionId,
+ agent,
+ isLoading,
+ connectionState.status,
+ pendingPrompt,
+ setPendingPrompt,
+ handlePromptSubmit,
+ ]);
+
// Handler for stopping the current operation
const handleStop = useEvent(async () => {
if (!activeSessionId || !agent) {
@@ -1187,6 +1220,7 @@ const AgentPanel: React.FC = () => {
onModeChange={handleModeChange}
sessionModels={sessionModels}
onModelChange={handleModelChange}
+ inputRef={promptInputRef}
/>
</>
);
diff --git a/frontend/src/components/chat/chat-panel.tsx b/frontend/src/components/chat/chat-panel.tsx
index 6167b2465f..f46c33a335 100644
--- a/frontend/src/components/chat/chat-panel.tsx
+++ b/frontend/src/components/chat/chat-panel.tsx
@@ -45,6 +45,7 @@ import {
type Chat,
type ChatId,
chatStateAtom,
+ pendingAiPromptAtom,
} from "@/core/ai/state";
import type { ToolNotebookContext } from "@/core/ai/tools/base";
import {
@@ -94,6 +95,7 @@ import {
useFileState,
} from "./chat-utils";
import { getCodes } from "@/core/codemirror/copilot/getCodes";
+import { focusInputAndMoveToEnd } from "@/core/codemirror/utils";
// Default mode for the AI
const DEFAULT_MODE = "manual";
@@ -407,6 +409,7 @@ const ChatInput: React.FC<ChatInputProps> = memo(
<div className="relative shrink-0 min-h-[80px] flex flex-col border-t">
<div className={cn("px-2 py-3 flex-1", inputClassName)}>
<PromptInput
+ className="max-h-[400px]"
inputRef={inputRef}
value={input}
onChange={setInput}
@@ -481,6 +484,7 @@ const ChatPanel = () => {
const ChatPanelBody = () => {
const setChatState = useSetAtom(chatStateAtom);
const [activeChat, setActiveChat] = useAtom(activeChatAtom);
+ const [pendingPrompt, setPendingPrompt] = useAtom(pendingAiPromptAtom);
const [input, setInput] = useState("");
const [newThreadInput, setNewThreadInput] = useState("");
const { files, addFiles, clearFiles, removeFile } = useFileState();
@@ -600,10 +604,7 @@ const ChatPanelBody = () => {
requestAnimationFrame(scrollToBottom);
}, [activeChatId]);
- const createNewThread = async (
- initialMessage: string,
- initialAttachments?: File[],
- ) => {
+ const startNewChatState = useEvent((initialMessage: string) => {
const now = Date.now();
const newChat: Chat = {
id: chatId as ChatId,
@@ -613,41 +614,41 @@ const ChatPanelBody = () => {
updatedAt: now,
};
- // Create new chat and set as active
setChatState((prev) => {
const newChats = new Map(prev.chats);
newChats.set(newChat.id, newChat);
- const newState = {
+ return {
...prev,
chats: newChats,
activeChatId: newChat.id,
};
- return newState;
});
+ });
- const fileParts =
- initialAttachments && initialAttachments.length > 0
- ? await convertToFileUIPart(initialAttachments)
- : undefined;
- const { contextPart, attachments } =
- await resolveChatContext(initialMessage);
+ const createNewThread = useEvent(
+ async (initialMessage: string, initialAttachments?: File[]) => {
+ startNewChatState(initialMessage);
- // Trigger AI conversation with append
- sendMessage({
- role: "user",
- parts: [
- {
- type: "text" as const,
- text: initialMessage,
- },
- ...(contextPart ? [contextPart] : []),
- ...(fileParts ?? []),
- ...attachments,
- ],
- });
- clearFiles();
- setInput("");
- };
+ const fileParts =
+ initialAttachments && initialAttachments.length > 0
+ ? await convertToFileUIPart(initialAttachments)
+ : undefined;
+ const { contextPart, attachments } =
+ await resolveChatContext(initialMessage);
+
+ sendMessage({
+ role: "user",
+ parts: [
+ { type: "text" as const, text: initialMessage },
+ ...(contextPart ? [contextPart] : []),
+ ...(fileParts ?? []),
+ ...attachments,
+ ],
+ });
+ clearFiles();
+ setInput("");
+ },
+ );
const handleNewChat = useEvent(() => {
setActiveChat(null);
@@ -728,7 +729,45 @@ const ChatPanelBody = () => {
const handleOnCloseThread = () => newThreadInputRef.current?.editor?.blur();
+ const submitPendingPrompt = useEvent(async (prompt: string) => {
+ if (activeChatId == null) {
+ startNewChatState(prompt);
+ // Starting a chat swaps the new-thread input for the regular input;
+ // carry over any draft the user had typed so it isn't lost.
+ setInput(newThreadInput);
+ }
+ const { contextPart, attachments } = await resolveChatContext(prompt);
+ sendMessage({
+ role: "user",
+ parts: [
+ { type: "text", text: prompt },
+ ...(contextPart ? [contextPart] : []),
+ ...attachments,
+ ],
+ });
+ });
+
const isNewThread = messages.length === 0;
+
+ // Deliver a prompt queued elsewhere (e.g. error auto-fix) to the chat,
+ // appending to the active thread or starting one if none exists.
+ useEffect(() => {
+ if (!pendingPrompt) {
+ return;
+ }
+ setPendingPrompt(null);
+ const { prompt, submit } = pendingPrompt;
+ if (submit) {
+ void submitPendingPrompt(prompt);
+ } else if (isNewThread) {
+ setNewThreadInput(prompt);
+ focusInputAndMoveToEnd(newThreadInputRef);
+ } else {
+ setInput(prompt);
+ focusInputAndMoveToEnd(newMessageInputRef);
+ }
+ }, [pendingPrompt, setPendingPrompt, isNewThread, submitPendingPrompt]);
+
const chatInput = isNewThread ? (
<ChatInput
key="new-thread-input"
diff --git a/frontend/src/components/editor/chrome/wrapper/__tests__/useOpenAiAssistant.test.ts b/frontend/src/components/editor/chrome/wrapper/__tests__/useOpenAiAssistant.test.ts
new file mode 100644
index 0000000000..ab282cc56a
--- /dev/null
+++ b/frontend/src/components/editor/chrome/wrapper/__tests__/useOpenAiAssistant.test.ts
@@ -0,0 +1,36 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+
+const getFeatureFlag = vi.fn<(flag: string) => boolean>();
+
+vi.mock("@/core/config/feature-flag", () => ({
+ getFeatureFlag: (flag: string) => getFeatureFlag(flag),
+}));
+
+const { resolveAiPanelTab } = await import("../useOpenAiAssistant");
+
+describe("resolveAiPanelTab", () => {
+ beforeEach(() => {
+ getFeatureFlag.mockReset();
+ });
+
+ it("honors an explicit panel regardless of the feature flag", () => {
+ getFeatureFlag.mockReturnValue(false);
+ expect(resolveAiPanelTab("agents", "chat")).toBe("agents");
+ expect(resolveAiPanelTab("chat", "agents")).toBe("chat");
+ });
+
+ it("uses the stored tab when external agents are enabled", () => {
+ getFeatureFlag.mockReturnValue(true);
+ expect(resolveAiPanelTab(undefined, "agents")).toBe("agents");
+ expect(resolveAiPanelTab(undefined, "chat")).toBe("chat");
+ });
+
+ it("falls back to chat when external agents are disabled", () => {
+ getFeatureFlag.mockReturnValue(false);
+ // A stale "agents" preference must not strand the prompt.
+ expect(resolveAiPanelTab(undefined, "agents")).toBe("chat");
+ expect(resolveAiPanelTab(undefined, "chat")).toBe("chat");
+ });
+});
diff --git a/frontend/src/components/editor/chrome/wrapper/useAiPanel.ts b/frontend/src/components/editor/chrome/wrapper/useAiPanel.ts
index 5b73584417..7469d1a8bb 100644
--- a/frontend/src/components/editor/chrome/wrapper/useAiPanel.ts
+++ b/frontend/src/components/editor/chrome/wrapper/useAiPanel.ts
@@ -6,7 +6,9 @@ import { jotaiJsonStorage } from "@/utils/storage/jotai";
const AI_PANEL_TAB_KEY = "marimo:chrome:ai-panel-tab";
-const aiPanelTabAtom = atomWithStorage<"chat" | "agents">(
+export type AiPanelTab = "chat" | "agents";
+
+export const aiPanelTabAtom = atomWithStorage<AiPanelTab>(
AI_PANEL_TAB_KEY,
"chat",
jotaiJsonStorage,
diff --git a/frontend/src/components/editor/chrome/wrapper/useOpenAiAssistant.ts b/frontend/src/components/editor/chrome/wrapper/useOpenAiAssistant.ts
new file mode 100644
index 0000000000..2cd2332365
--- /dev/null
+++ b/frontend/src/components/editor/chrome/wrapper/useOpenAiAssistant.ts
@@ -0,0 +1,88 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { useSetAtom, useStore } from "jotai";
+import useEvent from "react-use-event-hook";
+import { agentSessionStateAtom } from "@/components/chat/acp/state";
+import { toast } from "@/components/ui/use-toast";
+import { useModelChange } from "@/core/ai/config";
+import { pendingAiPromptAtom } from "@/core/ai/state";
+import type { CopilotMode } from "@/core/ai/tools/registry";
+import { aiModelConfiguredAtom } from "@/core/config/config";
+import { getFeatureFlag } from "@/core/config/feature-flag";
+import { Logger } from "@/utils/Logger";
+import { useChromeActions } from "../state";
+import { type AiPanelTab, aiPanelTabAtom, useAiPanelTab } from "./useAiPanel";
+
+// Error fixes work best with kernel access, so we default the chat panel to
+// code mode. The agents panel manages its own mode, so this is chat-only.
+const FIX_CHAT_MODE: CopilotMode = "code_mode";
+
+export interface OpenAiAssistantOptions {
+ prompt: string;
+ submit?: boolean;
+ /** Override the user's AI sidebar tab. When omitted, the stored tab is used. */
+ panel?: AiPanelTab;
+}
+
+// Resolve which AI panel to open.
+export function resolveAiPanelTab(
+ panel: AiPanelTab | undefined,
+ storedTab: AiPanelTab,
+): AiPanelTab {
+ if (panel) {
+ return panel;
+ }
+ return getFeatureFlag("external_agents") ? storedTab : "chat";
+}
+
+/**
+ * Opens the AI assistant sidebar panel and delivers a prompt to it.
+ *
+ * If no `panel` is given, the user's configured tab is respected.
+ */
+export function useOpenAiAssistant() {
+ const { openApplication } = useChromeActions();
+ const { setAiPanelTab } = useAiPanelTab();
+ const { saveModeChange } = useModelChange();
+ const setPendingPrompt = useSetAtom(pendingAiPromptAtom);
+ const store = useStore();
+
+ return useEvent(async (opts: OpenAiAssistantOptions) => {
+ const tab = resolveAiPanelTab(opts.panel, store.get(aiPanelTabAtom));
+
+ const chatPanelReady = store.get(aiModelConfiguredAtom);
+ const agentsPanelReady =
+ getFeatureFlag("external_agents") &&
+ store.get(agentSessionStateAtom).sessions.length > 0;
+ const isReady = tab === "agents" ? agentsPanelReady : chatPanelReady;
+
+ if (!isReady) {
+ toast({
+ title: tab === "agents" ? "No agent session" : "AI not configured",
+ description:
+ tab === "agents"
+ ? "Start an agent session or switch to the chat panel."
+ : "Configure an AI provider and chat model to fix with AI.",
+ variant: "danger",
+ });
+ return;
+ }
+
+ if (opts.panel) {
+ setAiPanelTab(opts.panel);
+ }
+
+ if (tab === "chat") {
+ await saveModeChange(FIX_CHAT_MODE).catch(() =>
+ Logger.error("Failed to save mode change"),
+ );
+ }
+
+ setPendingPrompt({
+ prompt: opts.prompt,
+ submit: opts.submit ?? false,
+ });
+
+ openApplication("ai");
+ });
+}
diff --git a/frontend/src/components/editor/errors/__tests__/auto-fix.test.ts b/frontend/src/components/editor/errors/__tests__/auto-fix.test.ts
new file mode 100644
index 0000000000..f2010dc729
--- /dev/null
+++ b/frontend/src/components/editor/errors/__tests__/auto-fix.test.ts
@@ -0,0 +1,119 @@
+/* Copyright 2026 Marimo. All rights reserved. */
+
+import { beforeEach, describe, expect, it, vi } from "vitest";
+import { cellId } from "@/__tests__/branded";
+import type { MarimoError } from "@/core/kernel/messages";
+
+const getDatasourceContext = vi.fn<(id: unknown) => string | null>(() => null);
+
+vi.mock("@/core/ai/context/providers/datasource", () => ({
+ getDatasourceContext: (id: unknown) => getDatasourceContext(id),
+}));
+
+const { buildFixPrompt, buildFixPromptFromText } = await import("../auto-fix");
+
+describe("buildFixPromptFromText", () => {
+ beforeEach(() => {
+ getDatasourceContext.mockReset();
+ getDatasourceContext.mockReturnValue(null);
+ });
+
+ it("includes the cell id in the header when provided", () => {
+ const prompt = buildFixPromptFromText("boom", cellId("cell-1"));
+ expect(prompt).toBe(
+ "My cell (id: cell-1) produced the following error. Please fix it:\n\nboom",
+ );
+ });
+
+ it("uses a generic header when no cell id is provided", () => {
+ const prompt = buildFixPromptFromText("boom");
+ expect(prompt).toBe(
+ "My code gives the following error. Please fix it:\n\nboom",
+ );
+ });
+
+ it("appends datasource context when explicitly requested for the cell", () => {
+ getDatasourceContext.mockReturnValue("@datasource://my_db");
+ const prompt = buildFixPromptFromText("boom", cellId("cell-1"), {
+ includeDatasourceContext: true,
+ });
+ expect(prompt).toBe(
+ "My cell (id: cell-1) produced the following error. Please fix it:\n\nboom\n\nDatabase schema: @datasource://my_db",
+ );
+ });
+
+ it("does not append datasource context by default", () => {
+ getDatasourceContext.mockReturnValue("@datasource://my_db");
+ const prompt = buildFixPromptFromText("boom", cellId("cell-1"));
+ expect(prompt).toBe(
+ "My cell (id: cell-1) produced the following error. Please fix it:\n\nboom",
+ );
+ expect(getDatasourceContext).not.toHaveBeenCalled();
+ });
+
+ it("does not look up datasource context without a cell id", () => {
+ buildFixPromptFromText("boom", undefined, {
+ includeDatasourceContext: true,
+ });
+ expect(getDatasourceContext).not.toHaveBeenCalled();
+ });
+});
+
+describe("buildFixPrompt", () => {
+ beforeEach(() => {
+ getDatasourceContext.mockReset();
+ getDatasourceContext.mockReturnValue(null);
+ });
+
+ it("uses the error message when present", () => {
+ const errors: MarimoError[] = [
+ { type: "sql-error", msg: "syntax error", sql_statement: "SELECT" },
+ ];
+ expect(buildFixPrompt(errors, cellId("cell-1"))).toBe(
+ "My cell (id: cell-1) produced the following error. Please fix it:\n\nsyntax error",
+ );
+ });
+
+ it("joins multiple errors with newlines", () => {
+ const errors: MarimoError[] = [
+ { type: "syntax", msg: "bad syntax" },
+ {
+ type: "exception",
+ exception_type: "ValueError",
+ msg: "bad value",
+ raising_cell: null,
+ },
+ ];
+ expect(buildFixPrompt(errors, cellId("cell-1"))).toBe(
+ "My cell (id: cell-1) produced the following error. Please fix it:\n\nbad syntax\nbad value",
+ );
+ });
+
+ it("falls back to the error type when there is no message", () => {
+ const errors: MarimoError[] = [
+ { type: "multiple-defs", name: "foo", cells: [cellId("foo")] },
+ ];
+ expect(buildFixPrompt(errors, cellId("cell-1"))).toBe(
+ "My cell (id: cell-1) produced the following error. Please fix it:\n\nmultiple-defs",
+ );
+ });
+
+ it("appends datasource context for SQL errors", () => {
+ getDatasourceContext.mockReturnValue("@datasource://my_db");
+ const errors: MarimoError[] = [
+ { type: "sql-error", msg: "syntax error", sql_statement: "SELECT" },
+ ];
+ expect(buildFixPrompt(errors, cellId("cell-1"))).toBe(
+ "My cell (id: cell-1) produced the following error. Please fix it:\n\nsyntax error\n\nDatabase schema: @datasource://my_db",
+ );
+ });
+
+ it("does not append datasource context for non-SQL errors", () => {
+ getDatasourceContext.mockReturnValue("@datasource://my_db");
+ const errors: MarimoError[] = [{ type: "syntax", msg: "bad syntax" }];
+ expect(buildFixPrompt(errors, cellId("cell-1"))).toBe(
+ "My cell (id: cell-1) produced the following error. Please fix it:\n\nbad syntax",
+ );
+ expect(getDatasourceContext).not.toHaveBeenCalled();
+ });
+});
diff --git a/frontend/src/components/editor/errors/auto-fix.tsx b/frontend/src/components/editor/errors/auto-fix.tsx
index 4dc7387afb..6f8cf30955 100644
--- a/frontend/src/components/editor/errors/auto-fix.tsx
+++ b/frontend/src/components/editor/errors/auto-fix.tsx
@@ -1,7 +1,14 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { useAtomValue, useSetAtom, useStore } from "jotai";
-import { ChevronDownIcon, SparklesIcon, WrenchIcon } from "lucide-react";
+import {
+ CheckIcon,
+ ChevronDownIcon,
+ HatGlasses,
+ type LucideIcon,
+ SparklesIcon,
+ WrenchIcon,
+} from "lucide-react";
import { Button } from "@/components/ui/button";
import {
DropdownMenu,
@@ -14,11 +21,46 @@ import { aiCompletionCellAtom } from "@/core/ai/state";
import { notebookAtom, useCellActions } from "@/core/cells/cells";
import type { CellId } from "@/core/cells/ids";
import { aiFeaturesEnabledAtom } from "@/core/config/config";
+import { getDatasourceContext } from "@/core/ai/context/providers/datasource";
import { getAutoFixes } from "@/core/errors/errors";
import type { MarimoError } from "@/core/kernel/messages";
import { cn } from "@/utils/cn";
+import { useOpenAiAssistant } from "../chrome/wrapper/useOpenAiAssistant";
import { type FixMode, useFixMode } from "./fix-mode";
+export function buildFixPromptFromText(
+ errorText: string,
+ cellId?: CellId,
+ {
+ includeDatasourceContext = false,
+ }: { includeDatasourceContext?: boolean } = {},
+): string {
+ const header =
+ cellId != null
+ ? `My cell (id: ${cellId}) produced the following error. Please fix it:`
+ : "My code gives the following error. Please fix it:";
+ let prompt = `${header}\n\n${errorText}`;
+ if (cellId != null && includeDatasourceContext) {
+ const datasourceContext = getDatasourceContext(cellId);
+ if (datasourceContext) {
+ prompt += `\n\nDatabase schema: ${datasourceContext}`;
+ }
+ }
+ return prompt;
+}
+
+export function buildFixPrompt(errors: MarimoError[], cellId: CellId): string {
+ const errorText = errors
+ .map((error) => ("msg" in error && error.msg ? error.msg : error.type))
+ .join("\n");
+ const includeDatasourceContext = errors.some(
+ (error) => error.type === "sql-error",
+ );
+ return buildFixPromptFromText(errorText, cellId, {
+ includeDatasourceContext,
+ });
+}
+
export const AutoFixButton = ({
errors,
cellId,
@@ -35,6 +77,7 @@ export const AutoFixButton = ({
getAutoFixes(error, { aiEnabled: aiFeaturesEnabled }),
);
const setAiCompletionCell = useSetAtom(aiCompletionCellAtom);
+ const openAiAssistant = useOpenAiAssistant();
if (autoFixes.length === 0) {
return null;
@@ -67,6 +110,12 @@ export const AutoFixButton = ({
editorView?.focus();
};
+ const openAISidebar = () => {
+ openAiAssistant({
+ prompt: buildFixPrompt(errors, cellId),
+ });
+ };
+
return (
<div className={cn("my-2", className)}>
{firstFix.fixType === "ai" ? (
@@ -74,6 +123,7 @@ export const AutoFixButton = ({
tooltip={firstFix.description}
openPrompt={() => handleFix(false)}
applyAutofix={() => handleFix(true)}
+ openChat={openAISidebar}
/>
) : (
<Tooltip content={firstFix.description} align="start">
@@ -92,23 +142,53 @@ export const AutoFixButton = ({
);
};
-const PromptIcon = SparklesIcon;
-const AutofixIcon = WrenchIcon;
+interface FixModeConfig {
+ Icon: LucideIcon;
+ title: string;
+ description: string;
+}
-const PromptTitle = "Suggest a prompt";
-const AutofixTitle = "Fix with AI";
+const MODE_CONFIG: Record<FixMode, FixModeConfig> = {
+ autofix: {
+ Icon: WrenchIcon,
+ title: "Inline AI Fix",
+ description: "Apply AI fixes inline in the cell",
+ },
+ chat: {
+ Icon: HatGlasses,
+ title: "Fix with AI assistant",
+ description: "Open the AI sidebar to fix",
+ },
+ prompt: {
+ Icon: SparklesIcon,
+ title: "Suggest a prompt",
+ description: "Edit the prompt before applying",
+ },
+};
+
+const FIX_MODES: FixMode[] = ["autofix", "prompt", "chat"];
export const AIFixButton = ({
tooltip,
openPrompt,
applyAutofix,
+ openChat,
}: {
tooltip: string;
openPrompt: () => void;
applyAutofix: () => void;
+ openChat: () => void;
}) => {
const { fixMode, setFixMode } = useFixMode();
+ let onAction = openPrompt;
+ if (fixMode === "chat") {
+ onAction = openChat;
+ } else if (fixMode === "autofix") {
+ onAction = applyAutofix;
+ }
+ const { Icon, title } = MODE_CONFIG[fixMode];
+
return (
<div className="flex">
<Tooltip content={tooltip} align="start">
@@ -116,14 +196,10 @@ export const AIFixButton = ({
size="xs"
variant="outline"
className="font-normal rounded-r-none border-r-0"
- onClick={fixMode === "prompt" ? openPrompt : applyAutofix}
+ onClick={onAction}
>
- {fixMode === "prompt" ? (
- <PromptIcon className="h-3 w-3 mr-2 mb-0.5" />
- ) : (
- <AutofixIcon className="h-3 w-3 mr-2 mb-0.5" />
- )}
- {fixMode === "prompt" ? PromptTitle : AutofixTitle}
+ <Icon className="h-3 w-3 mr-2 mb-0.5" />
+ {title}
</Button>
</Tooltip>
<DropdownMenu>
@@ -138,40 +214,38 @@ export const AIFixButton = ({
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end" className="w-56">
- <DropdownMenuItem
- className="flex items-center gap-2"
- onClick={() => {
- setFixMode(fixMode === "prompt" ? "autofix" : "prompt");
- }}
- >
- <AiModeItem mode={fixMode === "prompt" ? "autofix" : "prompt"} />
- </DropdownMenuItem>
+ {FIX_MODES.map((mode) => (
+ <DropdownMenuItem
+ key={mode}
+ className="flex items-center gap-2"
+ onClick={() => setFixMode(mode)}
+ >
+ <AiModeItem mode={mode} selected={mode === fixMode} />
+ </DropdownMenuItem>
+ ))}
</DropdownMenuContent>
</DropdownMenu>
</div>
);
};
-const AiModeItem = ({ mode }: { mode: FixMode }) => {
- const icon =
- mode === "prompt" ? (
- <PromptIcon className="h-4 w-4" />
- ) : (
- <AutofixIcon className="h-4 w-4" />
- );
- const title = mode === "prompt" ? PromptTitle : AutofixTitle;
- const description =
- mode === "prompt"
- ? "Edit the prompt before applying"
- : "Apply AI fixes automatically";
+const AiModeItem = ({
+ mode,
+ selected,
+}: {
+ mode: FixMode;
+ selected: boolean;
+}) => {
+ const { Icon, title, description } = MODE_CONFIG[mode];
return (
- <div className="flex items-center gap-2">
- {icon}
+ <div className="flex items-center gap-2 w-full">
+ <Icon className="h-4 w-4 shrink-0" />
<div className="flex flex-col">
<span className="font-medium">{title}</span>
<span className="text-xs text-muted-foreground">{description}</span>
</div>
+ {selected && <CheckIcon className="h-4 w-4 ml-auto shrink-0" />}
</div>
);
};
diff --git a/frontend/src/components/editor/errors/fix-mode.ts b/frontend/src/components/editor/errors/fix-mode.ts
index 6f4fbdd9ee..9a94e402e4 100644
--- a/frontend/src/components/editor/errors/fix-mode.ts
+++ b/frontend/src/components/editor/errors/fix-mode.ts
@@ -4,7 +4,7 @@ import { useAtom } from "jotai";
import { atomWithStorage } from "jotai/utils";
import { jotaiJsonStorage } from "@/utils/storage/jotai";
-export type FixMode = "prompt" | "autofix";
+export type FixMode = "prompt" | "autofix" | "chat";
const BASE_KEY = "marimo:ai-autofix-mode";
diff --git a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
index d5ba1e7df0..9b32a8175e 100644
--- a/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
+++ b/frontend/src/components/editor/output/MarimoTracebackOutput.tsx
@@ -41,7 +41,8 @@ import {
extractAllTracebackInfo,
getTracebackInfo,
} from "@/utils/traceback";
-import { AIFixButton } from "../errors/auto-fix";
+import { useOpenAiAssistant } from "../chrome/wrapper/useOpenAiAssistant";
+import { AIFixButton, buildFixPromptFromText } from "../errors/auto-fix";
import { MangledSegments } from "../errors/mangled-local-chip";
import { CellLinkTraceback } from "../links/cell-link";
import type { OnRefactorWithAI } from "../Output";
@@ -71,6 +72,7 @@ export const MarimoTracebackOutput = ({
const lastTracebackLine = lastLine(traceback);
const aiFeaturesEnabled = useAtomValue(aiFeaturesEnabledAtom);
+ const openAiAssistant = useOpenAiAssistant();
// Get last traceback info
const tracebackInfo = extractAllTracebackInfo(traceback)?.at(0);
@@ -97,6 +99,12 @@ export const MarimoTracebackOutput = ({
});
};
+ const openAISidebar = () => {
+ openAiAssistant({
+ prompt: buildFixPromptFromText(lastTracebackLine, cellId),
+ });
+ };
+
return (
<div className="flex flex-col gap-2 min-w-full w-fit">
<button
@@ -126,6 +134,7 @@ export const MarimoTracebackOutput = ({
tooltip="Fix with AI"
openPrompt={() => handleRefactorWithAI(false)}
applyAutofix={() => handleRefactorWithAI(true)}
+ openChat={openAISidebar}
/>
)}
{showDebugger && (
diff --git a/frontend/src/components/editor/output/__tests__/traceback.test.tsx b/frontend/src/components/editor/output/__tests__/traceback.test.tsx
index b38d597a4c..64b70194ff 100644
--- a/frontend/src/components/editor/output/__tests__/traceback.test.tsx
+++ b/frontend/src/components/editor/output/__tests__/traceback.test.tsx
@@ -1,11 +1,14 @@
/* Copyright 2026 Marimo. All rights reserved. */
import { render } from "@testing-library/react";
+import { Provider } from "jotai";
import { beforeAll, beforeEach, describe, expect, test, vi } from "vitest";
+import { MockRequestClient } from "@/__mocks__/requests";
import { Tracebacks } from "@/__mocks__/tracebacks";
import { cellId } from "@/__tests__/branded";
import { TooltipProvider } from "@/components/ui/tooltip";
import { initialModeAtom } from "@/core/mode";
+import { requestClientAtom } from "@/core/network/requests";
import { store } from "@/core/state/jotai";
import { renderHTML } from "@/plugins/core/RenderHTML";
import {
@@ -20,13 +23,16 @@ describe("traceback component", () => {
beforeEach(() => {
vi.resetAllMocks();
store.set(initialModeAtom, "edit");
+ store.set(requestClientAtom, MockRequestClient.create());
});
test("extracts cell-link", () => {
const traceback = (
- <TooltipProvider>
- <MarimoTracebackOutput traceback={Tracebacks.raw} cellId={cid} />
- </TooltipProvider>
+ <Provider store={store}>
+ <TooltipProvider>
+ <MarimoTracebackOutput traceback={Tracebacks.raw} cellId={cid} />
+ </TooltipProvider>
+ </Provider>
);
const { unmount, getAllByRole } = render(traceback);
@@ -44,9 +50,11 @@ describe("traceback component", () => {
test("renames File to Cell for relevant lines", () => {
const traceback = (
- <TooltipProvider>
- <MarimoTracebackOutput traceback={Tracebacks.raw} cellId={cid} />
- </TooltipProvider>
+ <Provider store={store}>
+ <TooltipProvider>
+ <MarimoTracebackOutput traceback={Tracebacks.raw} cellId={cid} />
+ </TooltipProvider>
+ </Provider>
);
const { unmount, container } = render(traceback);
diff --git a/frontend/src/core/ai/config.ts b/frontend/src/core/ai/config.ts
index 426fc995e3..3747e650be 100644
--- a/frontend/src/core/ai/config.ts
+++ b/frontend/src/core/ai/config.ts
@@ -60,7 +60,7 @@ export const useModelChange = () => {
},
};
- saveConfig(newConfig);
+ await saveConfig(newConfig);
};
const saveModeChange = async (newMode: CopilotMode) => {
@@ -71,7 +71,7 @@ export const useModelChange = () => {
},
};
- saveConfig(newConfig);
+ await saveConfig(newConfig);
};
return { saveModelChange, saveModeChange };
diff --git a/frontend/src/core/ai/state.ts b/frontend/src/core/ai/state.ts
index 7aef97b0d3..b4a46c77fd 100644
--- a/frontend/src/core/ai/state.ts
+++ b/frontend/src/core/ai/state.ts
@@ -21,6 +21,17 @@ export interface AiCompletionCell {
export const aiCompletionCellAtom = atom<AiCompletionCell | null>(null);
+/**
+ * A prompt queued to be delivered to the AI assistant panel.
+ * The active panel consumes this on mount/when ready, then clears it.
+ */
+export interface PendingAiPrompt {
+ prompt: string;
+ submit: boolean;
+}
+
+export const pendingAiPromptAtom = atom<PendingAiPrompt | null>(null);
+
const INCLUDE_OTHER_CELLS_KEY = "marimo:ai:includeOtherCells";
export const includeOtherCellsAtom = atomWithStorage<boolean>(
INCLUDE_OTHER_CELLS_KEY,
diff --git a/frontend/src/core/codemirror/utils.ts b/frontend/src/core/codemirror/utils.ts
index 8f6ce3eb4c..5818b23332 100644
--- a/frontend/src/core/codemirror/utils.ts
+++ b/frontend/src/core/codemirror/utils.ts
@@ -2,6 +2,7 @@
import type { EditorState, Transaction } from "@codemirror/state";
import type { EditorView, ViewUpdate } from "@codemirror/view";
import { getCM } from "@replit/codemirror-vim";
+import type { ReactCodeMirrorRef } from "@uiw/react-codemirror";
export function isAtStartOfEditor(ev: { state: EditorState }) {
const main = ev.state.selection.main;
@@ -37,6 +38,20 @@ export function moveToEndOfEditor(ev: EditorView | undefined) {
});
}
+/** We delay the focus and move to end of the editor until React has rendered the prefilled value. */
+export function focusInputAndMoveToEnd(
+ ref: React.RefObject<ReactCodeMirrorRef | null>,
+) {
+ requestAnimationFrame(() => {
+ const view = ref.current?.view;
+ if (!view) {
+ return;
+ }
+ view.focus();
+ moveToEndOfEditor(view);
+ });
+}
+
export function isInVimMode(ev: EditorView): boolean {
return getCM(ev)?.state.vim != null;
}