From ebc30b9f4c5ae51ef8a7385b2542431cb68df825 Mon Sep 17 00:00:00 2001 From: Kiran Gadhave Date: Tue, 1 Dec 2026 10:24:43 -0800 Subject: [PATCH 1/5] perf: defer per-cell AI completion work Opening the AI prompt in one cell caused every cell editor to commit, and idle cells each retained a chat client. Subscribe by cell and create the client only when a prompt is submitted. Keep requests independent of the visible prompt so switching cells preserves in-flight proposals. Keep the original editor mounted during comparisons to preserve its selection and restore focus. --- .../editor/__tests__/cell-renders.test.tsx | 210 +++++- .../editor/ai/ai-completion-editor.tsx | 627 ++++++++++-------- .../editor/cell/code/cell-editor.tsx | 28 +- frontend/src/core/ai/state.ts | 6 + 4 files changed, 566 insertions(+), 305 deletions(-) diff --git a/frontend/src/components/editor/__tests__/cell-renders.test.tsx b/frontend/src/components/editor/__tests__/cell-renders.test.tsx index 5b7e28c9003..c2543fa39bb 100644 --- a/frontend/src/components/editor/__tests__/cell-renders.test.tsx +++ b/frontend/src/components/editor/__tests__/cell-renders.test.tsx @@ -1,5 +1,7 @@ /* Copyright 2026 Marimo. All rights reserved. */ -import { act, render } from "@testing-library/react"; +import { Chat, useChat } from "@ai-sdk/react"; +import { EditorView } from "@codemirror/view"; +import { act, fireEvent, render, screen } from "@testing-library/react"; import { Profiler } from "react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { DocumentWrapper } from "@/__mocks__/document"; @@ -9,6 +11,8 @@ import { createRenderTracker } from "@/__tests__/render-tracker"; import { cell } from "@/core/notebook/document/__tests__/fixtures"; import { cellId } from "@/__tests__/branded"; import { TooltipProvider } from "@/components/ui/tooltip"; +import { stagedAICellsAtom } from "@/core/ai/staged-cells"; +import { aiCompletionCellAtom } from "@/core/ai/state"; import { notebookAtom } from "@/core/cells/cells"; import { editorMountScheduler } from "@/core/codemirror/editor-mount-scheduler"; import { setupNotebook } from "@/core/cells/__tests__/harness"; @@ -17,10 +21,13 @@ import { requestClientAtom } from "@/core/network/requests"; import { invariant } from "@/utils/invariant"; import { Cell } from "../notebook-cell"; +vi.mock("@ai-sdk/react", { spy: true }); + const stops: Array<() => void> = []; beforeEach(() => vi.useFakeTimers()); afterEach(() => { act(() => stops.splice(0).forEach((stop) => stop())); + vi.restoreAllMocks(); vi.useRealTimers(); }); @@ -63,10 +70,69 @@ async function setup(count: number) { }); expect(Object.keys(renders.counts())).toEqual(ids); renders.reset(); - return { ...notebook, replica, renders }; + return { ...notebook, replica, renders, container: mounted.container }; +} + +function editor(store: Awaited>["store"], id: string) { + return store.get(notebookAtom).cellHandles[cellId(id)].current?.editorView; +} + +function prompt() { + const editor = document.querySelector( + ".mo-ai-prompt .cm-editor", + ); + invariant(editor, "The AI prompt must be mounted"); + const view = EditorView.findFromDOM(editor); + invariant(view, "The AI prompt must have an editor view"); + return view; } describe.each([2, 25])("cell render isolation with %i cells", (count) => { + it("opens, switches, and closes AI completion without work in unrelated cells", async () => { + const { store, renders } = await setup(count); + const a = cellId("c1"); + const b = cellId("c2"); + expect(editor(store, a)).toBeNull(); + expect(editor(store, b)).toBeNull(); + + await act(async () => store.set(aiCompletionCellAtom, { cellId: a })); + expect(Object.keys(renders.counts())).toEqual([a]); + const viewA = editor(store, a); + invariant(viewA, "Opening AI completion must promote a dormant editor"); + const parent = viewA.dom.parentElement; + const initialPrompt = "Rename this variable"; + + renders.reset(); + await act(async () => + store.set(aiCompletionCellAtom, { cellId: b, initialPrompt }), + ); + expect(Object.keys(renders.counts()).toSorted()).toEqual([a, b]); + expect(editor(store, a)).toBe(viewA); + expect(viewA.dom.parentElement).toBe(parent); + const viewB = editor(store, b); + invariant(viewB, "Switching AI completion must promote the new editor"); + await act(async () => vi.advanceTimersByTimeAsync(100)); + const promptView = prompt(); + expect(promptView.hasFocus).toBe(true); + expect( + promptView.state.sliceDoc( + promptView.state.selection.main.from, + promptView.state.selection.main.to, + ), + ).toBe(initialPrompt); + expect(Object.keys(renders.counts()).toSorted()).toEqual([a, b]); + + renders.reset(); + fireEvent.click( + screen.getByRole("button", { name: "Discard AI completion" }), + ); + expect(Object.keys(renders.counts())).toEqual([b]); + expect(store.get(aiCompletionCellAtom)).toBeNull(); + expect(viewB.hasFocus).toBe(true); + expect(useChat).not.toHaveBeenCalled(); + expect(Chat).not.toHaveBeenCalled(); + }); + it("does not re-render other cells on a keystroke", async () => { const { store, model, renders } = await setup(count); await act(async () => { @@ -114,3 +180,143 @@ describe.each([2, 25])("cell render isolation with %i cells", (count) => { } }); }); + +it("preserves a streaming proposal across target switches and applies changes to the same editor", async () => { + const { store, container } = await setup(2); + const a = cellId("c1"); + const b = cellId("c2"); + const first = new TransformStream(); + const writer = first.writable.getWriter(); + const encoder = new TextEncoder(); + const chunk = (value: object) => `data: ${JSON.stringify(value)}\n\n`; + const data = (code: string) => + chunk({ type: "data-cell-completion", data: { code } }); + const finish = `${chunk({ type: "finish", finishReason: "stop" })}data: [DONE]\n\n`; + const headers = { "Content-Type": "text/event-stream" }; + const fetch = vi + .spyOn(globalThis, "fetch") + .mockResolvedValueOnce(new Response(first.readable, { headers })) + .mockResolvedValueOnce(new Response(data("x = 100") + finish, { headers })); + const suggestion = () => + container.querySelector(".cm-mergeView .cm-merge-b .cm-content"); + + await act(async () => { + store.set(aiCompletionCellAtom, { + cellId: a, + initialPrompt: "Fix", + triggerImmediately: true, + }); + }); + await act(async () => vi.advanceTimersByTimeAsync(100)); + expect(fetch).toHaveBeenCalledTimes(1); + expect(fetch.mock.calls[0][1]?.body).toEqual( + expect.stringContaining('"code":"x = 1"'), + ); + expect(Chat).toHaveBeenCalledTimes(1); + + const view = editor(store, a); + invariant(view, "AI completion must promote the editor"); + act(() => view.dispatch({ selection: { anchor: 0, head: 1 } })); + const parent = view.dom.parentElement; + const selection = view.state.selection; + await act(async () => writer.write(encoder.encode(data("x = 9")))); + expect(suggestion()).toHaveTextContent("x = 9"); + expect(view.dom).not.toBeVisible(); + expect(view.dom.parentElement).toBe(parent); + + await act(async () => store.set(aiCompletionCellAtom, { cellId: b })); + expect(suggestion()).toBeNull(); + expect(view.dom).toBeVisible(); + await act(async () => { + await writer.write(encoder.encode(data("x = 99") + finish)); + await writer.close(); + }); + expect(suggestion()).toBeNull(); + await act(async () => store.set(aiCompletionCellAtom, { cellId: a })); + expect(suggestion()).toHaveTextContent("x = 99"); + fireEvent.click(screen.getByRole("button", { name: /Revert change/ })); + expect(suggestion()).toBeNull(); + expect(view.state.doc.toString()).toBe("x = 1"); + expect(view.state.selection.eq(selection)).toBe(true); + expect(prompt().hasFocus).toBe(true); + + const input = prompt(); + act(() => input.dispatch({ changes: { from: 0, insert: "Try again" } })); + await act(async () => fireEvent.keyDown(input.contentDOM, { key: "Enter" })); + expect(suggestion()).toHaveTextContent("x = 100"); + expect(useChat).not.toHaveBeenCalled(); + expect(Chat).toHaveBeenCalledTimes(2); + fireEvent.click(screen.getByRole("button", { name: /^Keep change/ })); + expect(store.get(aiCompletionCellAtom)).toBeNull(); + expect(view.state.doc.toString()).toBe("x = 100"); + expect(view.dom.parentElement).toBe(parent); + expect(view.hasFocus).toBe(true); +}); + +it("shows staged edits without allocating a chat", async () => { + const { store, container } = await setup(2); + const a = cellId("c1"); + act(() => editorMountScheduler.promote(a)); + const view = editor(store, a); + invariant(view, "The cell editor must be mounted"); + const parent = view.dom.parentElement; + + act(() => + store.set( + stagedAICellsAtom, + new Map([[a, { type: "update_cell", previousCode: "" }]]), + ), + ); + const diff = container.querySelector(".cm-mergeView"); + expect(diff).toBeVisible(); + expect(view.dom).not.toBeVisible(); + + await act(async () => + store.set(aiCompletionCellAtom, { cellId: cellId("c2") }), + ); + expect(container.querySelector(".cm-mergeView")).toBe(diff); + act(() => store.set(stagedAICellsAtom, new Map())); + expect(view.dom).toBeVisible(); + expect(view.dom.parentElement).toBe(parent); + expect(useChat).not.toHaveBeenCalled(); + expect(Chat).not.toHaveBeenCalled(); +}); + +it("aborts a stopped request and can submit again", async () => { + const { store } = await setup(2); + const fetch = vi + .spyOn(globalThis, "fetch") + .mockImplementationOnce((_url, options) => { + const signal = options?.signal; + invariant(signal, "A completion request must be abortable"); + return new Promise((_resolve, reject) => { + signal.addEventListener("abort", () => reject(signal.reason), { + once: true, + }); + }); + }) + .mockResolvedValueOnce( + new Response( + 'data: {"type":"data-cell-completion","data":{"code":"x = 42"}}\n\n' + + 'data: {"type":"finish","finishReason":"stop"}\n\n' + + "data: [DONE]\n\n", + { headers: { "Content-Type": "text/event-stream" } }, + ), + ); + await act(async () => + store.set(aiCompletionCellAtom, { + cellId: cellId("c1"), + initialPrompt: "Update the value", + }), + ); + + const submit = () => screen.getByRole("button", { name: "Submit" }); + await act(async () => fireEvent.click(submit())); + const signal = fetch.mock.calls[0][1]?.signal; + expect(signal?.aborted).toBe(false); + fireEvent.click(screen.getByRole("button", { name: "Stop" })); + expect(signal?.aborted).toBe(true); + await act(async () => fireEvent.click(submit())); + expect(fetch).toHaveBeenCalledTimes(2); + expect(screen.getByRole("button", { name: /^Keep change/ })).toBeEnabled(); +}); diff --git a/frontend/src/components/editor/ai/ai-completion-editor.tsx b/frontend/src/components/editor/ai/ai-completion-editor.tsx index 240c327d4b7..eded6faff52 100644 --- a/frontend/src/components/editor/ai/ai-completion-editor.tsx +++ b/frontend/src/components/editor/ai/ai-completion-editor.tsx @@ -1,6 +1,6 @@ /* Copyright 2026 Marimo. All rights reserved. */ -import { useChat } from "@ai-sdk/react"; +import { Chat } from "@ai-sdk/react"; import { EditorView } from "@codemirror/view"; import { CircleCheckIcon, @@ -8,7 +8,14 @@ import { SparklesIcon, XIcon, } from "lucide-react"; -import React, { useCallback, useEffect, useId, useState } from "react"; +import React, { + useEffect, + useId, + useLayoutEffect, + useRef, + useState, +} from "react"; +import useEvent from "react-use-event-hook"; import CodeMirrorMerge from "react-codemirror-merge"; import { DefaultChatTransport } from "ai"; import { Button } from "@/components/ui/button"; @@ -33,18 +40,17 @@ import { cellCompletionSchema, type CompletionUIMessage, } from "@/core/ai/completion-output"; -import { AI_SDK_UI_THROTTLE_MS } from "@/core/ai/constants"; import { type AiCompletionCell, includeOtherCellsAtom } from "@/core/ai/state"; import type { CellId } from "@/core/cells/ids"; import { getCodes } from "@/core/codemirror/copilot/getCodes"; import type { LanguageAdapterType } from "@/core/codemirror/language/types"; import { selectAllText } from "@/core/codemirror/utils"; import { useRuntimeManager } from "@/core/runtime/config"; +import type { RuntimeManager } from "@/core/runtime/runtime"; import type { AiCompletionRequest } from "@/core/network/types"; import { useTheme } from "@/theme/useTheme"; import { cn } from "@/utils/cn"; import { prettyError } from "@/utils/errors"; -import { retryWithTimeout } from "@/utils/timeout"; import { PromptInput } from "./prompt-input"; import { AcceptCompletionButton, @@ -61,112 +67,58 @@ const Modified = CodeMirrorMerge.Modified; interface Props { cellId: CellId; aiCompletionCell: AiCompletionCell | null; - className?: string; currentCode: string; currentLanguageAdapter: LanguageAdapterType | undefined; onChange: (code: string) => void; - declineChange: () => void; - acceptChange: (rightHandCode: string) => void; + close: () => void; + focusEditor: () => void; runCell: () => void; outputArea?: "above" | "below"; - /** - * Children shown when there is no completion - */ children: React.ReactNode; } const baseExtensions = [customPythonLanguageSupport(), EditorView.lineWrapping]; -/** - * Editor for AI completions that goes above a cell to modify it. - * - * This shows a left/right split with the original and modified code. - */ export const AiCompletionEditor: React.FC = ({ cellId, aiCompletionCell, - className, - onChange, - currentLanguageAdapter, currentCode, - declineChange, - acceptChange, + currentLanguageAdapter, + onChange, + close, + focusEditor, runCell, - outputArea, + outputArea = "below", children, }) => { - const [showInputPrompt, setShowInputPrompt] = useState(false); - - const [includeOtherCells, setIncludeOtherCells] = useAtom( - includeOtherCellsAtom, - ); - const includeOtherCellsCheckboxId = useId(); - - const runtimeManager = useRuntimeManager(); - - const { - initialPrompt, - triggerImmediately, - cellId: aiCellId, - } = aiCompletionCell ?? {}; - const enabled = aiCellId === cellId; - - const updatedCell = useStagedAICell(cellId); - let previousCellCode: string | undefined; - if (updatedCell?.type === "update_cell") { - previousCellCode = updatedCell.previousCode; - } + const stagedCell = useStagedAICell(cellId); + const previousCode = + stagedCell?.type === "update_cell" ? stagedCell.previousCode : undefined; const [completion, setCompletion] = useState(""); - const [input, setInput] = useState(initialPrompt ?? ""); - const transport = React.useMemo( - () => - new DefaultChatTransport({ - api: runtimeManager.getAiURL("completion").toString(), - headers: () => runtimeManager.headers(), - prepareSendMessagesRequest: ({ body, id }) => ({ - body: { ...body, id }, - }), - }), - [runtimeManager], - ); - const { - sendMessage, - stop: stopChat, - status, - } = useChat({ - throttle: AI_SDK_UI_THROTTLE_MS, - transport, - onData: (part) => { - if (part.type === CELL_COMPLETION_DATA_TYPE) { - const completion = cellCompletionSchema.parse(part.data); - setCompletion(completion.code.trimEnd()); - } - }, - onError: (error) => { - setCompletion(""); - toast({ - title: "Completion failed", - description: prettyError(error), - }); - }, - onFinish: ({ isAbort, isDisconnect, isError, finishReason }) => { - if (isAbort || isDisconnect || isError || finishReason !== "stop") { - setCompletion(""); - } - }, - }); - const isLoading = status === "submitted" || status === "streaming"; - - const stop = useCallback(() => { - setCompletion(""); - void stopChat(); - }, [stopChat]); + const [isLoading, setIsLoading] = useState(false); + const [showInputPrompt, setShowInputPrompt] = useState(false); + const request = useRef | null>(null); + const chatId = useRef(undefined); + const restoreFocus = useRef(false); - const complete = useCallback( - async (prompt: string) => { - await stopChat(); - setCompletion(""); + useEffect(() => { + return () => { + const chat = request.current; + request.current = null; + void chat?.stop(); + }; + }, []); + + const complete = useEvent( + async ( + prompt: string, + includeOtherCells: boolean, + runtime: RuntimeManager, + ) => { + if (request.current) { + return; + } const body = { ...getAICompletionBody({ input: prompt }), @@ -176,128 +128,253 @@ export const AiCompletionEditor: React.FC = ({ language: currentLanguageAdapter ?? "python", } satisfies AiCompletionRequest; - await sendMessage({ text: prompt }, { body }); + // A request can finish while another cell owns the prompt. + const chat = new Chat({ + id: chatId.current, + transport: new DefaultChatTransport({ + api: runtime.getAiURL("completion").toString(), + headers: () => runtime.headers(), + prepareSendMessagesRequest: ({ body, id }) => ({ + body: { ...body, id }, + }), + }), + onData: (part) => { + if ( + request.current === chat && + part.type === CELL_COMPLETION_DATA_TYPE + ) { + const completion = cellCompletionSchema.parse(part.data); + setCompletion(completion.code.trimEnd()); + } + }, + onError: (error) => { + if (request.current === chat) { + setCompletion(""); + toast({ + title: "Completion failed", + description: prettyError(error), + }); + } + }, + onFinish: ({ isAbort, isDisconnect, isError, finishReason }) => { + if ( + request.current === chat && + (isAbort || isDisconnect || isError || finishReason !== "stop") + ) { + setCompletion(""); + } + }, + }); + chatId.current = chat.id; + request.current = chat; + setCompletion(""); + setIsLoading(true); + + try { + await chat.sendMessage({ text: prompt }, { body }); + } finally { + if (request.current === chat) { + request.current = null; + setIsLoading(false); + } + } }, - [ - currentCode, - currentLanguageAdapter, - includeOtherCells, - sendMessage, - stopChat, - ], ); - const handleSubmit = useCallback(() => { - void complete(input); - }, [complete, input]); - - const inputRef = React.useRef(null); - - const initialSubmit = useCallback(() => { - if (triggerImmediately && !isLoading && initialPrompt) { - // Use complete to pass the prompt directly, else input might be empty - void complete(initialPrompt); - } - // oxlint-disable-next-line react-hooks/exhaustive-deps - }, [triggerImmediately]); - - // Focus the input - useEffect(() => { - if (enabled) { - retryWithTimeout( - () => { - const input = inputRef.current; - if (input?.view) { - input.view.focus(); - initialSubmit(); - return true; - } - return false; - }, - { retries: 3, delay: 100, initialDelay: 100 }, - ); // Wait for animation to complete + const stop = () => { + const chat = request.current; + request.current = null; + setCompletion(""); + setIsLoading(false); + void chat?.stop(); + }; - selectAllText(inputRef.current?.view); - } - }, [enabled, initialSubmit]); + const closeAndFocusEditor = () => { + restoreFocus.current = true; + close(); + }; - // Reset the input when the prompt changes - useEffect(() => { - if (enabled) { - setInput(initialPrompt || ""); + // The editor is visible again after the comparison leaves the DOM. + useLayoutEffect(() => { + if (!aiCompletionCell && restoreFocus.current) { + restoreFocus.current = false; + focusEditor(); } - }, [enabled, initialPrompt, setInput]); - - const { theme } = useTheme(); + }, [aiCompletionCell, focusEditor]); - const handleAcceptCompletion = () => { - acceptChange(completion); + const handleAccept = () => { + onChange(completion); setCompletion(""); + closeAndFocusEditor(); }; - // Reject discards the suggestion but keeps the prompt open for refinement. - const handleDeclineCompletion = () => { + const handleReject = () => { stop(); setShowInputPrompt(true); - inputRef.current?.view?.focus(); }; - const showCompletionBanner = - enabled && triggerImmediately && (completion || isLoading); - // Set default output area to below if not specified - outputArea = outputArea ?? "below"; - - const showInput = enabled && (!triggerImmediately || showInputPrompt); + const showInput = Boolean( + aiCompletionCell && + (!aiCompletionCell.triggerImmediately || showInputPrompt), + ); + const showCompletion = Boolean(aiCompletionCell && completion); + const showComparison = showCompletion || previousCode !== undefined; - const completionBanner = ( + const showBanner = showCompletion || isLoading; + const completionBanner = aiCompletionCell?.triggerImmediately && (
- + {showBanner && ( + + )}
); - const renderMergeEditor = (originalCode: string, modifiedCode: string) => { - return ( - - + {aiCompletionCell && ( + { + stop(); + closeAndFocusEditor(); + }} + runCell={runCell} /> - - - ); - }; + )} + + {outputArea === "below" && completionBanner} + + ); +}; + +function CompletionComparison({ + originalCode, + modifiedCode, + onChange, +}: { + originalCode: string; + modifiedCode: string; + onChange: (code: string) => void; +}) { + const { theme } = useTheme(); + return ( + + + + + ); +} + +function AiCompletionPrompt({ + target, + showInput, + complete, + completion, + isLoading, + stop, + onAccept: handleAcceptCompletion, + onReject, + onClose, + runCell, +}: { + target: AiCompletionCell; + showInput: boolean; + complete: ( + prompt: string, + includeOtherCells: boolean, + runtime: RuntimeManager, + ) => Promise; + completion: string; + isLoading: boolean; + stop: () => void; + onAccept: () => void; + onReject: () => void; + onClose: () => void; + runCell: () => void; +}) { + const [includeOtherCells, setIncludeOtherCells] = useAtom( + includeOtherCellsAtom, + ); + const includeOtherCellsCheckboxId = useId(); + const runtime = useRuntimeManager(); + const inputRef = useRef(null); + const [input, setInput] = useState(target.initialPrompt ?? ""); + const submit = useEvent((prompt: string) => { + void complete(prompt, includeOtherCells, runtime); + }); + + useEffect(() => { + setInput(target.initialPrompt ?? ""); + const { initialPrompt, triggerImmediately } = target; + if (triggerImmediately && initialPrompt) { + const timer = setTimeout(() => submit(initialPrompt), 100); + return () => clearTimeout(timer); + } + }, [target, submit]); - const renderCompletionEditor = () => { - if (completion && enabled) { - return renderMergeEditor(currentCode, completion); + useEffect(() => { + if (!showInput) { + return; } - // If there is no completion and there is previous cell code, it means there is an AI change to the cell. - // And we want to render the previous cell code as the original - if (!completion && previousCellCode) { - return renderMergeEditor(previousCellCode, currentCode); + const timer = setTimeout(() => { + const view = inputRef.current?.view; + view?.focus(); + selectAllText(view); + }, 100); + return () => clearTimeout(timer); + }, [target, showInput]); + + const handleDeclineCompletion = () => { + onReject(); + if (showInput) { + inputRef.current?.view?.focus(); } }; + const handleSubmit = () => submit(input); const completionButtons = ( <> @@ -322,115 +399,95 @@ export const AiCompletionEditor: React.FC = ({ return (
-
- {enabled && ( - <> - - { - stop(); - declineChange(); - }} - value={input} - onChange={setInput} - onSubmit={() => { - if (!isLoading) { - if (inputRef.current?.view) { - storePrompt(inputRef.current.view); - } - handleSubmit(); - } - }} - onKeyDown={createAiCompletionOnKeydown({ - handleAcceptCompletion, - handleDeclineCompletion, - isLoading, - hasCompletion: completion.trim().length > 0, - })} - /> - -
-
- - addContextCompletion(inputRef)} - isLoading={isLoading} - /> - -
- {completion && ( -
- {completionButtons} -
- )} -
- -
- -
- - setIncludeOtherCells(Boolean(checked)) - } - /> - -
-
- - + + { + if (!isLoading) { + if (inputRef.current?.view) { + storePrompt(inputRef.current.view); + } + handleSubmit(); + } + }} + onKeyDown={createAiCompletionOnKeydown({ + handleAcceptCompletion, + handleDeclineCompletion, + isLoading, + hasCompletion: completion.trim().length > 0, + })} + /> + +
+
+ + addContextCompletion(inputRef)} + isLoading={isLoading} + /> + +
+ {completion && ( +
+ {completionButtons} +
)}
- {outputArea === "above" && completionBanner} - {renderCompletionEditor()} - {(!completion || !enabled) && !previousCellCode && children} - {/* By default, show the completion banner below the code */} - {outputArea === "below" && completionBanner} + +
+ +
+ + setIncludeOtherCells(Boolean(checked)) + } + /> + +
+
+
); -}; +} interface CompletionBannerProps { status: "loading" | "generated"; diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx index f86db7c11e7..80617840d63 100644 --- a/frontend/src/components/editor/cell/code/cell-editor.tsx +++ b/frontend/src/components/editor/cell/code/cell-editor.tsx @@ -2,10 +2,10 @@ import { historyField } from "@codemirror/commands"; import { EditorState, type Extension, StateEffect } from "@codemirror/state"; import { EditorView, ViewPlugin } from "@codemirror/view"; -import { useAtom, useAtomValue, useSetAtom } from "jotai"; +import { useAtomValue, useSetAtom } from "jotai"; import React, { memo, useEffect, useMemo, useRef } from "react"; import useEvent from "react-use-event-hook"; -import { aiCompletionCellAtom } from "@/core/ai/state"; +import { aiCompletionCellAtom, useAiCompletionCell } from "@/core/ai/state"; import { maybeAddMarimoImport } from "@/core/cells/add-missing-import"; import { useCellActions } from "@/core/cells/actions"; import { @@ -119,7 +119,8 @@ const CellEditorInternal = ({ tooltipParentSelector, extensions: extraExtensions, }: CellEditorProps) => { - const [aiCompletionCell, setAiCompletionCell] = useAtom(aiCompletionCellAtom); + const aiCompletionCell = useAiCompletionCell(cellId); + const setAiCompletionCell = useSetAtom(aiCompletionCellAtom); const serializedEditorState = useRestoredEditorState(cellId); const takeRestoredEditorState = useSetAtom(takeRestoredEditorStateAtom); const showHiddenCodeNow = useSetAtom(showHiddenCodeAtom); @@ -378,7 +379,7 @@ const CellEditorInternal = ({ }, [handleReconfigureEditor, extensions, editorViewRef]); // An AI edit applies to the editor, which a dormant cell does not have yet. - const isAiCompletionTarget = aiCompletionCell?.cellId === cellId; + const isAiCompletionTarget = aiCompletionCell !== null; useEffect(() => { if (isAiCompletionTarget) { promote(); @@ -403,10 +404,12 @@ const CellEditorInternal = ({ aiCompletionCell={aiCompletionCell} currentCode={mountedEditorView?.state.doc.toString() ?? code} currentLanguageAdapter={languageAdapter} - declineChange={useEvent(() => { - setAiCompletionCell(null); - editorViewRef.current?.focus(); + close={useEvent(() => { + setAiCompletionCell((target) => + target?.cellId === cellId ? null : target, + ); })} + focusEditor={useEvent(() => editorViewRef.current?.focus())} onChange={useEvent((newCode) => { editorViewRef.current?.dispatch({ changes: { @@ -416,17 +419,6 @@ const CellEditorInternal = ({ }, }); })} - acceptChange={useEvent((newCode) => { - editorViewRef.current?.dispatch({ - changes: { - from: 0, - to: editorViewRef.current.state.doc.length, - insert: newCode, - }, - }); - editorViewRef.current?.focus(); - setAiCompletionCell(null); - })} runCell={handleRunCell} outputArea={outputArea} > diff --git a/frontend/src/core/ai/state.ts b/frontend/src/core/ai/state.ts index 0ae249b844e..813ab09ebcf 100644 --- a/frontend/src/core/ai/state.ts +++ b/frontend/src/core/ai/state.ts @@ -5,6 +5,7 @@ import type { FileUIPart } from "ai"; import { atom } from "jotai"; import { atomWithStorage } from "jotai/utils"; import { toast } from "@/components/ui/use-toast"; +import { createKeyedSelectorHook } from "@/core/state/create-keyed-selector-hook"; import { uniqueBy } from "@/utils/arrays"; import { Logger } from "@/utils/Logger"; import { adaptForLocalStorage, jotaiJsonStorage } from "@/utils/storage/jotai"; @@ -24,6 +25,11 @@ export interface AiCompletionCell { export const aiCompletionCellAtom = atom(null); +export const useAiCompletionCell = createKeyedSelectorHook( + aiCompletionCellAtom, + (target, cellId: CellId) => (target?.cellId === cellId ? target : null), +); + /** * A prompt queued to be delivered to the AI assistant panel. * The active panel consumes this on mount/when ready, then clears it. From 0dfe52760bf0831949108562d4a5bb55caf000aa Mon Sep 17 00:00:00 2001 From: Kiran Gadhave Date: Wed, 2 Dec 2026 10:41:25 -0800 Subject: [PATCH 2/5] fix: preserve cell completion edits and prompt focus --- .../editor/__tests__/cell-renders.test.tsx | 137 +++++++++++++++--- .../ai/__tests__/completion-utils.test.ts | 32 ++-- .../editor/ai/ai-completion-editor.tsx | 83 ++++++----- .../components/editor/ai/completion-utils.ts | 16 +- .../editor/cell/code/cell-editor.tsx | 12 +- 5 files changed, 195 insertions(+), 85 deletions(-) diff --git a/frontend/src/components/editor/__tests__/cell-renders.test.tsx b/frontend/src/components/editor/__tests__/cell-renders.test.tsx index c2543fa39bb..b539f09f879 100644 --- a/frontend/src/components/editor/__tests__/cell-renders.test.tsx +++ b/frontend/src/components/editor/__tests__/cell-renders.test.tsx @@ -14,9 +14,12 @@ import { TooltipProvider } from "@/components/ui/tooltip"; import { stagedAICellsAtom } from "@/core/ai/staged-cells"; import { aiCompletionCellAtom } from "@/core/ai/state"; import { notebookAtom } from "@/core/cells/cells"; +import { HTMLCellId } from "@/core/cells/ids"; +import * as notebookCode from "@/core/codemirror/copilot/getCodes"; import { editorMountScheduler } from "@/core/codemirror/editor-mount-scheduler"; import { setupNotebook } from "@/core/cells/__tests__/harness"; import { defaultUserConfig } from "@/core/config/config-schema"; +import { isPlatformMac } from "@/core/hotkeys/shortcuts"; import { requestClientAtom } from "@/core/network/requests"; import { invariant } from "@/utils/invariant"; import { Cell } from "../notebook-cell"; @@ -87,6 +90,18 @@ function prompt() { return view; } +const streamChunk = (value: object) => `data: ${JSON.stringify(value)}\n\n`; +const completionChunk = (code: string) => + streamChunk({ type: "data-cell-completion", data: { code } }); +const finishStream = `${streamChunk({ type: "finish", finishReason: "stop" })}data: [DONE]\n\n`; +const streamHeaders = { "Content-Type": "text/event-stream" }; + +function completionResponse(code: string) { + return new Response(completionChunk(code) + finishStream, { + headers: streamHeaders, + }); +} + describe.each([2, 25])("cell render isolation with %i cells", (count) => { it("opens, switches, and closes AI completion without work in unrelated cells", async () => { const { store, renders } = await setup(count); @@ -188,15 +203,12 @@ it("preserves a streaming proposal across target switches and applies changes to const first = new TransformStream(); const writer = first.writable.getWriter(); const encoder = new TextEncoder(); - const chunk = (value: object) => `data: ${JSON.stringify(value)}\n\n`; - const data = (code: string) => - chunk({ type: "data-cell-completion", data: { code } }); - const finish = `${chunk({ type: "finish", finishReason: "stop" })}data: [DONE]\n\n`; - const headers = { "Content-Type": "text/event-stream" }; const fetch = vi .spyOn(globalThis, "fetch") - .mockResolvedValueOnce(new Response(first.readable, { headers })) - .mockResolvedValueOnce(new Response(data("x = 100") + finish, { headers })); + .mockResolvedValueOnce( + new Response(first.readable, { headers: streamHeaders }), + ) + .mockResolvedValueOnce(completionResponse("x = 100")); const suggestion = () => container.querySelector(".cm-mergeView .cm-merge-b .cm-content"); @@ -219,7 +231,7 @@ it("preserves a streaming proposal across target switches and applies changes to act(() => view.dispatch({ selection: { anchor: 0, head: 1 } })); const parent = view.dom.parentElement; const selection = view.state.selection; - await act(async () => writer.write(encoder.encode(data("x = 9")))); + await act(async () => writer.write(encoder.encode(completionChunk("x = 9")))); expect(suggestion()).toHaveTextContent("x = 9"); expect(view.dom).not.toBeVisible(); expect(view.dom.parentElement).toBe(parent); @@ -228,7 +240,9 @@ it("preserves a streaming proposal across target switches and applies changes to expect(suggestion()).toBeNull(); expect(view.dom).toBeVisible(); await act(async () => { - await writer.write(encoder.encode(data("x = 99") + finish)); + await writer.write( + encoder.encode(completionChunk("x = 99") + finishStream), + ); await writer.close(); }); expect(suggestion()).toBeNull(); @@ -269,12 +283,21 @@ it("shows staged edits without allocating a chat", async () => { ); const diff = container.querySelector(".cm-mergeView"); expect(diff).toBeVisible(); + expect(diff?.querySelector(".cm-merge-a .cm-content")).toHaveAttribute( + "contenteditable", + "false", + ); expect(view.dom).not.toBeVisible(); await act(async () => store.set(aiCompletionCellAtom, { cellId: cellId("c2") }), ); expect(container.querySelector(".cm-mergeView")).toBe(diff); + await act(async () => store.set(aiCompletionCellAtom, { cellId: a })); + fireEvent.click( + screen.getByRole("button", { name: "Discard AI completion" }), + ); + expect(document.getElementById(HTMLCellId.create(a))).toHaveFocus(); act(() => store.set(stagedAICellsAtom, new Map())); expect(view.dom).toBeVisible(); expect(view.dom.parentElement).toBe(parent); @@ -284,6 +307,7 @@ it("shows staged edits without allocating a chat", async () => { it("aborts a stopped request and can submit again", async () => { const { store } = await setup(2); + const getCodes = vi.spyOn(notebookCode, "getCodes").mockReturnValue("y = 2"); const fetch = vi .spyOn(globalThis, "fetch") .mockImplementationOnce((_url, options) => { @@ -295,14 +319,7 @@ it("aborts a stopped request and can submit again", async () => { }); }); }) - .mockResolvedValueOnce( - new Response( - 'data: {"type":"data-cell-completion","data":{"code":"x = 42"}}\n\n' + - 'data: {"type":"finish","finishReason":"stop"}\n\n' + - "data: [DONE]\n\n", - { headers: { "Content-Type": "text/event-stream" } }, - ), - ); + .mockResolvedValueOnce(completionResponse("x = 42")); await act(async () => store.set(aiCompletionCellAtom, { cellId: cellId("c1"), @@ -311,12 +328,98 @@ it("aborts a stopped request and can submit again", async () => { ); const submit = () => screen.getByRole("button", { name: "Submit" }); + const allCode = screen.getByRole("checkbox", { name: "All code" }); + expect(allCode).toBeChecked(); + fireEvent.click(allCode); await act(async () => fireEvent.click(submit())); + expect(getCodes).not.toHaveBeenCalled(); + expect(fetch.mock.calls[0][1]?.body).toEqual( + expect.stringContaining('"includeOtherCode":""'), + ); const signal = fetch.mock.calls[0][1]?.signal; expect(signal?.aborted).toBe(false); fireEvent.click(screen.getByRole("button", { name: "Stop" })); expect(signal?.aborted).toBe(true); + fireEvent.click(allCode); await act(async () => fireEvent.click(submit())); expect(fetch).toHaveBeenCalledTimes(2); + expect(getCodes).toHaveBeenCalledExactlyOnceWith("x = 1"); + expect(fetch.mock.calls[1][1]?.body).toEqual( + expect.stringContaining('"includeOtherCode":"y = 2"'), + ); expect(screen.getByRole("button", { name: /^Keep change/ })).toBeEnabled(); }); + +it("preserves the cursor when the user types before the prompt focus timer fires", async () => { + const { store } = await setup(1); + await act(async () => + store.set(aiCompletionCellAtom, { cellId: cellId("c1") }), + ); + const input = prompt(); + act(() => { + input.focus(); + input.dispatch({ + changes: { from: 0, insert: "Fix" }, + selection: { anchor: 3 }, + }); + }); + const selection = input.state.selection; + await act(async () => vi.advanceTimersByTimeAsync(100)); + expect(input.state.selection.eq(selection)).toBe(true); +}); + +it("focuses the visible prompt after a banner rejection", async () => { + const { store } = await setup(1); + vi.spyOn(globalThis, "fetch").mockResolvedValueOnce( + completionResponse("x = 2"), + ); + await act(async () => + store.set(aiCompletionCellAtom, { + cellId: cellId("c1"), + initialPrompt: "Fix", + triggerImmediately: true, + }), + ); + await act(async () => vi.advanceTimersByTimeAsync(100)); + fireEvent.click(screen.getByRole("switch")); + await act(async () => vi.advanceTimersByTimeAsync(100)); + const reject = screen.getByRole("button", { name: "Revert change" }); + act(() => reject.focus()); + fireEvent.click(reject); + expect(prompt().hasFocus).toBe(true); +}); + +it.each([ + { proposal: "", cursor: 0 }, + { proposal: "x = 1", cursor: 2 }, +])( + "can keep a proposal of '$proposal' without disturbing the cursor", + async ({ proposal, cursor }) => { + const { store, container } = await setup(1); + const a = cellId("c1"); + vi.spyOn(globalThis, "fetch").mockResolvedValueOnce( + completionResponse(proposal), + ); + await act(async () => + store.set(aiCompletionCellAtom, { + cellId: a, + initialPrompt: "Edit this cell", + }), + ); + const view = editor(store, a); + invariant(view, "Opening the prompt must promote the editor"); + act(() => view.dispatch({ selection: { anchor: 2 } })); + await act(async () => + fireEvent.click(screen.getByRole("button", { name: "Submit" })), + ); + expect(container.querySelector(".cm-mergeView")).toBeVisible(); + expect(screen.getByRole("button", { name: /^Keep change/ })).toBeEnabled(); + fireEvent.keyDown(prompt().contentDOM, { + key: "Enter", + [isPlatformMac() ? "metaKey" : "ctrlKey"]: true, + }); + expect(store.get(aiCompletionCellAtom)).toBeNull(); + expect(view.state.doc.toString()).toBe(proposal); + expect(view.state.selection.main.head).toBe(cursor); + }, +); diff --git a/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts b/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts index 56bb6935f18..29c59ce8bc8 100644 --- a/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts +++ b/frontend/src/components/editor/ai/__tests__/completion-utils.test.ts @@ -1,18 +1,9 @@ /* Copyright 2026 Marimo. All rights reserved. */ import type { Variable } from "@marimo-team/client/protocol"; import type { FileUIPart, UIMessage } from "ai"; -import { - afterEach, - beforeEach, - describe, - expect, - it, - type Mock, - vi, -} from "vitest"; +import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; import { MockExecutions } from "@/__mocks__/executions"; import * as aiContext from "@/core/ai/context/context"; -import { getCodes } from "@/core/codemirror/copilot/getCodes"; import { dataSourceConnectionsAtom } from "@/core/datasets/data-source-connections"; import { DUCKDB_ENGINE } from "@/core/datasets/engines"; import { datasetsAtom } from "@/core/datasets/state"; @@ -43,6 +34,8 @@ function setBindings(bindings: Pick[]) { } describe("getAICompletionBody", () => { + const includeOtherCode = "// Some other code"; + beforeEach(() => { // Reset the Jotai store before each test store.set(datasetsAtom, { @@ -53,7 +46,6 @@ describe("getAICompletionBody", () => { connectionsMap: new Map(), }); store.set(activeNotebookReplicaAtom, null); - (getCodes as Mock).mockReturnValue("// Some other code"); }); it("should return the correct completion body with mentioned datasets", () => { @@ -77,7 +69,7 @@ describe("getAICompletionBody", () => { store.set(datasetsAtom, { tables: testDatasets } as DatasetsState); const input = "Use @data://dataset1 and @data://dataset2 for analysis"; - const result = getAICompletionBody({ input }); + const result = getAICompletionBody({ input, includeOtherCode }); expect(result).toMatchInlineSnapshot(` { @@ -99,7 +91,7 @@ describe("getAICompletionBody", () => { it("should handle input with no mentioned datasets", () => { const input = "Perform some analysis without mentioning @data://datasets"; - const result = getAICompletionBody({ input }); + const result = getAICompletionBody({ input, includeOtherCode }); expect(result).toMatchInlineSnapshot(` { @@ -128,7 +120,7 @@ describe("getAICompletionBody", () => { const input = "Use @data://existingDataset and @data://nonExistentDataset for analysis"; - const result = getAICompletionBody({ input }); + const result = getAICompletionBody({ input, includeOtherCode }); expect(result).toMatchInlineSnapshot(` { @@ -163,7 +155,7 @@ describe("getAICompletionBody", () => { const input = "Use @data://dataset.with.dots and @data://regular_dataset for analysis"; - const result = getAICompletionBody({ input }); + const result = getAICompletionBody({ input, includeOtherCode }); expect(result).toMatchInlineSnapshot(` { @@ -215,7 +207,7 @@ describe("getAICompletionBody", () => { }); const input = "Use @data://table1 for analysis"; - const result = getAICompletionBody({ input }); + const result = getAICompletionBody({ input, includeOtherCode }); expect(result).toMatchInlineSnapshot(` { @@ -238,7 +230,7 @@ describe("getAICompletionBody", () => { ]); const input = "Use @variable://var1 and @variable://var2 for analysis"; - const result = getAICompletionBody({ input }); + const result = getAICompletionBody({ input, includeOtherCode }); expect(result).toMatchInlineSnapshot(` { @@ -270,7 +262,7 @@ describe("getAICompletionBody", () => { setBindings([{ name: "var1", type: "string", preview: "string value" }]); const input = "Use @data://dataset1 and @variable://var1 for analysis"; - const result = getAICompletionBody({ input }); + const result = getAICompletionBody({ input, includeOtherCode }); expect(result).toMatchInlineSnapshot(` { @@ -296,7 +288,7 @@ describe("getAICompletionBody", () => { const input = "Use @variable://existingVar and @variable://nonExistentVar for analysis"; - const result = getAICompletionBody({ input }); + const result = getAICompletionBody({ input, includeOtherCode }); expect(result).toMatchInlineSnapshot(` { @@ -325,7 +317,7 @@ describe("getAICompletionBody", () => { ]); const input = "Use @data://conflict for analysis"; - const result = getAICompletionBody({ input }); + const result = getAICompletionBody({ input, includeOtherCode }); expect(result).toMatchInlineSnapshot(` { diff --git a/frontend/src/components/editor/ai/ai-completion-editor.tsx b/frontend/src/components/editor/ai/ai-completion-editor.tsx index eded6faff52..57f42e574b7 100644 --- a/frontend/src/components/editor/ai/ai-completion-editor.tsx +++ b/frontend/src/components/editor/ai/ai-completion-editor.tsx @@ -51,6 +51,7 @@ import type { AiCompletionRequest } from "@/core/network/types"; import { useTheme } from "@/theme/useTheme"; import { cn } from "@/utils/cn"; import { prettyError } from "@/utils/errors"; +import { focusCell } from "../navigation/focus-utils"; import { PromptInput } from "./prompt-input"; import { AcceptCompletionButton, @@ -95,12 +96,14 @@ export const AiCompletionEditor: React.FC = ({ const previousCode = stagedCell?.type === "update_cell" ? stagedCell.previousCode : undefined; - const [completion, setCompletion] = useState(""); + const [completion, setCompletion] = useState(null); + const hasCompletion = completion !== null; const [isLoading, setIsLoading] = useState(false); const [showInputPrompt, setShowInputPrompt] = useState(false); const request = useRef | null>(null); const chatId = useRef(undefined); const restoreFocus = useRef(false); + const inputRef = useRef(null); useEffect(() => { return () => { @@ -121,9 +124,11 @@ export const AiCompletionEditor: React.FC = ({ } const body = { - ...getAICompletionBody({ input: prompt }), + ...getAICompletionBody({ + input: prompt, + includeOtherCode: includeOtherCells ? getCodes(currentCode) : "", + }), prompt, - includeOtherCode: includeOtherCells ? getCodes(currentCode) : "", code: currentCode, language: currentLanguageAdapter ?? "python", } satisfies AiCompletionRequest; @@ -149,7 +154,7 @@ export const AiCompletionEditor: React.FC = ({ }, onError: (error) => { if (request.current === chat) { - setCompletion(""); + setCompletion(null); toast({ title: "Completion failed", description: prettyError(error), @@ -161,13 +166,13 @@ export const AiCompletionEditor: React.FC = ({ request.current === chat && (isAbort || isDisconnect || isError || finishReason !== "stop") ) { - setCompletion(""); + setCompletion(null); } }, }); chatId.current = chat.id; request.current = chat; - setCompletion(""); + setCompletion(null); setIsLoading(true); try { @@ -184,7 +189,7 @@ export const AiCompletionEditor: React.FC = ({ const stop = () => { const chat = request.current; request.current = null; - setCompletion(""); + setCompletion(null); setIsLoading(false); void chat?.stop(); }; @@ -194,30 +199,40 @@ export const AiCompletionEditor: React.FC = ({ close(); }; - // The editor is visible again after the comparison leaves the DOM. + // Wait until the prompt leaves the DOM to restore focus. useLayoutEffect(() => { if (!aiCompletionCell && restoreFocus.current) { restoreFocus.current = false; - focusEditor(); + if (previousCode !== undefined) { + focusCell(cellId); + } else { + focusEditor(); + } } - }, [aiCompletionCell, focusEditor]); + }, [aiCompletionCell, cellId, focusEditor, previousCode]); const handleAccept = () => { + if (!hasCompletion) { + return; + } onChange(completion); - setCompletion(""); + setCompletion(null); closeAndFocusEditor(); }; + const showInput = Boolean( + aiCompletionCell && + (!aiCompletionCell.triggerImmediately || showInputPrompt), + ); const handleReject = () => { stop(); setShowInputPrompt(true); + if (showInput) { + inputRef.current?.view?.focus(); + } }; - const showInput = Boolean( - aiCompletionCell && - (!aiCompletionCell.triggerImmediately || showInputPrompt), - ); - const showCompletion = Boolean(aiCompletionCell && completion); + const showCompletion = aiCompletionCell !== null && hasCompletion; const showComparison = showCompletion || previousCode !== undefined; const showBanner = showCompletion || isLoading; @@ -252,9 +267,10 @@ export const AiCompletionEditor: React.FC = ({ {aiCompletionCell && ( = ({ showCompletion ? currentCode : (previousCode ?? currentCode) } modifiedCode={showCompletion ? completion : currentCode} - onChange={onChange} + onChange={showCompletion ? onChange : undefined} /> )} @@ -289,13 +305,15 @@ function CompletionComparison({ }: { originalCode: string; modifiedCode: string; - onChange: (code: string) => void; + onChange?: (code: string) => void; }) { const { theme } = useTheme(); return ( @@ -311,24 +329,26 @@ function CompletionComparison({ function AiCompletionPrompt({ target, + inputRef, showInput, complete, - completion, + hasCompletion, isLoading, stop, onAccept: handleAcceptCompletion, - onReject, + onReject: handleDeclineCompletion, onClose, runCell, }: { target: AiCompletionCell; + inputRef: React.RefObject; showInput: boolean; complete: ( prompt: string, includeOtherCells: boolean, runtime: RuntimeManager, ) => Promise; - completion: string; + hasCompletion: boolean; isLoading: boolean; stop: () => void; onAccept: () => void; @@ -341,7 +361,6 @@ function AiCompletionPrompt({ ); const includeOtherCellsCheckboxId = useId(); const runtime = useRuntimeManager(); - const inputRef = useRef(null); const [input, setInput] = useState(target.initialPrompt ?? ""); const submit = useEvent((prompt: string) => { void complete(prompt, includeOtherCells, runtime); @@ -362,18 +381,14 @@ function AiCompletionPrompt({ } const timer = setTimeout(() => { const view = inputRef.current?.view; - view?.focus(); - selectAllText(view); + if (view && !view.hasFocus) { + view.focus(); + selectAllText(view); + } }, 100); return () => clearTimeout(timer); - }, [target, showInput]); + }, [target, showInput, inputRef]); - const handleDeclineCompletion = () => { - onReject(); - if (showInput) { - inputRef.current?.view?.focus(); - } - }; const handleSubmit = () => submit(input); const completionButtons = ( @@ -424,7 +439,7 @@ function AiCompletionPrompt({ handleAcceptCompletion, handleDeclineCompletion, isLoading, - hasCompletion: completion.trim().length > 0, + hasCompletion, })} /> @@ -449,7 +464,7 @@ function AiCompletionPrompt({ placeholder="Edit model" />
- {completion && ( + {hasCompletion && (
{completionButtons}
diff --git a/frontend/src/components/editor/ai/completion-utils.ts b/frontend/src/components/editor/ai/completion-utils.ts index 547801e99a0..76093e23271 100644 --- a/frontend/src/components/editor/ai/completion-utils.ts +++ b/frontend/src/components/editor/ai/completion-utils.ts @@ -17,10 +17,6 @@ import { Logger } from "@/utils/Logger"; export const CONTEXT_TRIGGER = "@"; -interface Opts { - input: string; -} - interface AICompletionBodyWithAttachments { body: Omit; attachments: FileUIPart[]; @@ -31,7 +27,11 @@ interface AICompletionBodyWithAttachments { */ export function getAICompletionBody({ input, -}: Opts): Omit { + includeOtherCode, +}: { + input: string; + includeOtherCode: string; +}): Omit { let contextString = ""; // Skip if no '@' in the input @@ -41,7 +41,7 @@ export function getAICompletionBody({ } return { - includeOtherCode: getCodes(""), + includeOtherCode, context: { plainText: contextString, schema: [], @@ -175,7 +175,9 @@ export async function resolveChatContext( */ export async function getAICompletionBodyWithAttachments({ input, -}: Opts): Promise { +}: { + input: string; +}): Promise { const { plainText, attachments } = await resolveContextAttachments(input); return { diff --git a/frontend/src/components/editor/cell/code/cell-editor.tsx b/frontend/src/components/editor/cell/code/cell-editor.tsx index 80617840d63..82efe78b356 100644 --- a/frontend/src/components/editor/cell/code/cell-editor.tsx +++ b/frontend/src/components/editor/cell/code/cell-editor.tsx @@ -22,6 +22,7 @@ import type { CellData } from "@/core/cells/types"; import type { CellRunStatus } from "@/core/executions"; import { setupCodeMirror } from "@/core/codemirror/cm"; import { acceptCompletionOnEnterAtom } from "@/core/codemirror/completion/accept-on-enter-atom"; +import { replaceEditorContent } from "@/core/codemirror/replace-editor-content"; import { useLazyEditorMount } from "@/core/codemirror/use-lazy-editor-mount"; import { getInitialLanguageAdapter, @@ -411,13 +412,10 @@ const CellEditorInternal = ({ })} focusEditor={useEvent(() => editorViewRef.current?.focus())} onChange={useEvent((newCode) => { - editorViewRef.current?.dispatch({ - changes: { - from: 0, - to: editorViewRef.current.state.doc.length, - insert: newCode, - }, - }); + const view = editorViewRef.current; + if (view) { + replaceEditorContent(view, newCode); + } })} runCell={handleRunCell} outputArea={outputArea} From cb59a7b2be7a297590e07d122a9023936066ef12 Mon Sep 17 00:00:00 2001 From: Kiran Gadhave Date: Wed, 2 Dec 2026 10:54:22 -0800 Subject: [PATCH 3/5] fix: scope prompt drafts to their completion target --- .../editor/__tests__/cell-renders.test.tsx | 14 ++++++++++++++ .../components/editor/ai/ai-completion-editor.tsx | 15 +++++++++------ 2 files changed, 23 insertions(+), 6 deletions(-) diff --git a/frontend/src/components/editor/__tests__/cell-renders.test.tsx b/frontend/src/components/editor/__tests__/cell-renders.test.tsx index b539f09f879..75bc35e6911 100644 --- a/frontend/src/components/editor/__tests__/cell-renders.test.tsx +++ b/frontend/src/components/editor/__tests__/cell-renders.test.tsx @@ -368,6 +368,20 @@ it("preserves the cursor when the user types before the prompt focus timer fires expect(input.state.selection.eq(selection)).toBe(true); }); +it("resets a draft when the same cell receives a fresh prompt", async () => { + const { store } = await setup(1); + const target = { cellId: cellId("c1") }; + await act(async () => store.set(aiCompletionCellAtom, target)); + const input = prompt(); + const submit = screen.getByRole("button", { name: "Submit" }); + act(() => input.dispatch({ changes: { from: 0, insert: "Fix this line" } })); + expect(submit).toBeEnabled(); + + await act(async () => store.set(aiCompletionCellAtom, { ...target })); + expect(prompt()).toBe(input); + expect(submit).toBeDisabled(); +}); + it("focuses the visible prompt after a banner rejection", async () => { const { store } = await setup(1); vi.spyOn(globalThis, "fetch").mockResolvedValueOnce( diff --git a/frontend/src/components/editor/ai/ai-completion-editor.tsx b/frontend/src/components/editor/ai/ai-completion-editor.tsx index 57f42e574b7..6c11ce29f6c 100644 --- a/frontend/src/components/editor/ai/ai-completion-editor.tsx +++ b/frontend/src/components/editor/ai/ai-completion-editor.tsx @@ -175,14 +175,12 @@ export const AiCompletionEditor: React.FC = ({ setCompletion(null); setIsLoading(true); - try { - await chat.sendMessage({ text: prompt }, { body }); - } finally { + await chat.sendMessage({ text: prompt }, { body }).finally(() => { if (request.current === chat) { request.current = null; setIsLoading(false); } - } + }); }, ); @@ -361,13 +359,18 @@ function AiCompletionPrompt({ ); const includeOtherCellsCheckboxId = useId(); const runtime = useRuntimeManager(); - const [input, setInput] = useState(target.initialPrompt ?? ""); + const [draft, setDraft] = useState<{ + target: AiCompletionCell; + text: string; + }>(); + const input = + draft?.target === target ? draft.text : (target.initialPrompt ?? ""); + const setInput = useEvent((text: string) => setDraft({ target, text })); const submit = useEvent((prompt: string) => { void complete(prompt, includeOtherCells, runtime); }); useEffect(() => { - setInput(target.initialPrompt ?? ""); const { initialPrompt, triggerImmediately } = target; if (triggerImmediately && initialPrompt) { const timer = setTimeout(() => submit(initialPrompt), 100); From 9ce18dd04e197cb99cd4d6f88a558ebab8d4e239 Mon Sep 17 00:00:00 2001 From: Kiran Gadhave Date: Wed, 2 Dec 2026 12:41:52 -0800 Subject: [PATCH 4/5] fix: cancel prompt autofocus after user interaction --- .../components/editor/__tests__/cell-renders.test.tsx | 5 ++++- .../src/components/editor/ai/ai-completion-editor.tsx | 10 ++++++++-- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/frontend/src/components/editor/__tests__/cell-renders.test.tsx b/frontend/src/components/editor/__tests__/cell-renders.test.tsx index 75bc35e6911..edd32fdef26 100644 --- a/frontend/src/components/editor/__tests__/cell-renders.test.tsx +++ b/frontend/src/components/editor/__tests__/cell-renders.test.tsx @@ -350,7 +350,7 @@ it("aborts a stopped request and can submit again", async () => { expect(screen.getByRole("button", { name: /^Keep change/ })).toBeEnabled(); }); -it("preserves the cursor when the user types before the prompt focus timer fires", async () => { +it("preserves focus and selection when the user types and leaves the prompt before autofocus", async () => { const { store } = await setup(1); await act(async () => store.set(aiCompletionCellAtom, { cellId: cellId("c1") }), @@ -364,7 +364,10 @@ it("preserves the cursor when the user types before the prompt focus timer fires }); }); const selection = input.state.selection; + const submit = screen.getByRole("button", { name: "Submit" }); + act(() => submit.focus()); await act(async () => vi.advanceTimersByTimeAsync(100)); + expect(submit).toHaveFocus(); expect(input.state.selection.eq(selection)).toBe(true); }); diff --git a/frontend/src/components/editor/ai/ai-completion-editor.tsx b/frontend/src/components/editor/ai/ai-completion-editor.tsx index 6c11ce29f6c..4a75f132915 100644 --- a/frontend/src/components/editor/ai/ai-completion-editor.tsx +++ b/frontend/src/components/editor/ai/ai-completion-editor.tsx @@ -379,7 +379,8 @@ function AiCompletionPrompt({ }, [target, submit]); useEffect(() => { - if (!showInput) { + const prompt = inputRef.current; + if (!showInput || prompt?.view?.hasFocus) { return; } const timer = setTimeout(() => { @@ -389,7 +390,12 @@ function AiCompletionPrompt({ selectAllText(view); } }, 100); - return () => clearTimeout(timer); + const cancel = () => clearTimeout(timer); + prompt?.editor?.addEventListener("focusin", cancel, { once: true }); + return () => { + cancel(); + prompt?.editor?.removeEventListener("focusin", cancel); + }; }, [target, showInput, inputRef]); const handleSubmit = () => submit(input); From ed6ba6880b75bdacdb9d5a8dd081beb9b0a39473 Mon Sep 17 00:00:00 2001 From: Kiran Gadhave Date: Wed, 2 Dec 2026 12:48:52 -0800 Subject: [PATCH 5/5] refactor: isolate cell completion comparison rendering --- .../editor/ai/ai-completion-editor.tsx | 49 +++++++++++++------ 1 file changed, 35 insertions(+), 14 deletions(-) diff --git a/frontend/src/components/editor/ai/ai-completion-editor.tsx b/frontend/src/components/editor/ai/ai-completion-editor.tsx index 4a75f132915..7e552d491d5 100644 --- a/frontend/src/components/editor/ai/ai-completion-editor.tsx +++ b/frontend/src/components/editor/ai/ai-completion-editor.tsx @@ -230,10 +230,13 @@ export const AiCompletionEditor: React.FC = ({ } }; - const showCompletion = aiCompletionCell !== null && hasCompletion; - const showComparison = showCompletion || previousCode !== undefined; - - const showBanner = showCompletion || isLoading; + const comparison = renderCompletionComparison( + currentCode, + aiCompletionCell ? completion : null, + previousCode, + onChange, + ); + const showBanner = hasCompletion || isLoading; const completionBanner = aiCompletionCell?.triggerImmediately && (
= ({ /> )} {outputArea === "above" && completionBanner} - {showComparison && ( - - )} - + {comparison} + {outputArea === "below" && completionBanner}
); }; +function renderCompletionComparison( + currentCode: string, + proposal: string | null, + previousCode: string | undefined, + onChange: (code: string) => void, +) { + if (proposal !== null) { + return ( + + ); + } + if (previousCode !== undefined) { + return ( + + ); + } + return null; +} + function CompletionComparison({ originalCode, modifiedCode,