diff --git a/frontend/src/components/editor/__tests__/cell-renders.test.tsx b/frontend/src/components/editor/__tests__/cell-renders.test.tsx index bbf5d7f6223..9a6b6a40145 100644 --- a/frontend/src/components/editor/__tests__/cell-renders.test.tsx +++ b/frontend/src/components/editor/__tests__/cell-renders.test.tsx @@ -1,4 +1,6 @@ /* Copyright 2026 Marimo. All rights reserved. */ +import { Chat, useChat } from "@ai-sdk/react"; +import { EditorView } from "@codemirror/view"; import { act, fireEvent, render, screen, within } from "@testing-library/react"; import { Profiler } from "react"; import { afterEach, beforeEach, describe, expect, it, vi } from "vitest"; @@ -9,18 +11,26 @@ 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 { 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"; +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,7 +73,33 @@ 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; +} + +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, + }); } it("shares the tooltip hover delay across cells", async () => { @@ -83,6 +119,51 @@ it("shares the tooltip hover delay across cells", async () => { }); 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 () => { @@ -130,3 +211,248 @@ 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 fetch = vi + .spyOn(globalThis, "fetch") + .mockResolvedValueOnce( + new Response(first.readable, { headers: streamHeaders }), + ) + .mockResolvedValueOnce(completionResponse("x = 100")); + 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(completionChunk("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(completionChunk("x = 99") + finishStream), + ); + 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(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); + expect(useChat).not.toHaveBeenCalled(); + expect(Chat).not.toHaveBeenCalled(); +}); + +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) => { + 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(completionResponse("x = 42")); + await act(async () => + store.set(aiCompletionCellAtom, { + cellId: cellId("c1"), + initialPrompt: "Update the value", + }), + ); + + 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 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") }), + ); + const input = prompt(); + act(() => { + input.focus(); + input.dispatch({ + changes: { from: 0, insert: "Fix" }, + selection: { anchor: 3 }, + }); + }); + 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); +}); + +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( + 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 240c327d4b7..7e552d491d5 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,18 @@ 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 { focusCell } from "../navigation/focus-utils"; import { PromptInput } from "./prompt-input"; import { AcceptCompletionButton, @@ -61,243 +68,358 @@ 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 stagedCell = useStagedAICell(cellId); + const previousCode = + stagedCell?.type === "update_cell" ? stagedCell.previousCode : undefined; - 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 [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); - 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(""); + 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 isLoading = status === "submitted" || status === "streaming"; - - const stop = useCallback(() => { - setCompletion(""); - void stopChat(); - }, [stopChat]); - - const complete = useCallback( - async (prompt: string) => { - await stopChat(); - setCompletion(""); const body = { - ...getAICompletionBody({ input: prompt }), + ...getAICompletionBody({ + input: prompt, + includeOtherCode: includeOtherCells ? getCodes(currentCode) : "", + }), prompt, - includeOtherCode: includeOtherCells ? getCodes(currentCode) : "", code: currentCode, 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(null); + toast({ + title: "Completion failed", + description: prettyError(error), + }); + } + }, + onFinish: ({ isAbort, isDisconnect, isError, finishReason }) => { + if ( + request.current === chat && + (isAbort || isDisconnect || isError || finishReason !== "stop") + ) { + setCompletion(null); + } + }, + }); + chatId.current = chat.id; + request.current = chat; + setCompletion(null); + setIsLoading(true); + + 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]); + const stop = () => { + const chat = request.current; + request.current = null; + setCompletion(null); + setIsLoading(false); + void chat?.stop(); + }; - // 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 closeAndFocusEditor = () => { + restoreFocus.current = true; + close(); + }; - selectAllText(inputRef.current?.view); + // Wait until the prompt leaves the DOM to restore focus. + useLayoutEffect(() => { + if (!aiCompletionCell && restoreFocus.current) { + restoreFocus.current = false; + if (previousCode !== undefined) { + focusCell(cellId); + } else { + focusEditor(); + } } - }, [enabled, initialSubmit]); + }, [aiCompletionCell, cellId, focusEditor, previousCode]); - // Reset the input when the prompt changes - useEffect(() => { - if (enabled) { - setInput(initialPrompt || ""); + const handleAccept = () => { + if (!hasCompletion) { + return; } - }, [enabled, initialPrompt, setInput]); - - const { theme } = useTheme(); - - const handleAcceptCompletion = () => { - acceptChange(completion); - setCompletion(""); + onChange(completion); + setCompletion(null); + closeAndFocusEditor(); }; - // Reject discards the suggestion but keeps the prompt open for refinement. - const handleDeclineCompletion = () => { + const showInput = Boolean( + aiCompletionCell && + (!aiCompletionCell.triggerImmediately || showInputPrompt), + ); + const handleReject = () => { stop(); setShowInputPrompt(true); - inputRef.current?.view?.focus(); + if (showInput) { + 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 completionBanner = ( + const comparison = renderCompletionComparison( + currentCode, + aiCompletionCell ? completion : null, + previousCode, + onChange, + ); + const showBanner = hasCompletion || isLoading; + const completionBanner = aiCompletionCell?.triggerImmediately && (
- + {showBanner && ( + + )}
); - const renderMergeEditor = (originalCode: string, modifiedCode: string) => { - return ( - - - + {aiCompletionCell && ( + { + stop(); + closeAndFocusEditor(); + }} + runCell={runCell} /> - + )} + {outputArea === "above" && completionBanner} + {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, + onChange, +}: { + originalCode: string; + modifiedCode: string; + onChange?: (code: string) => void; +}) { + const { theme } = useTheme(); + return ( + + + + + ); +} - const renderCompletionEditor = () => { - if (completion && enabled) { - return renderMergeEditor(currentCode, completion); +function AiCompletionPrompt({ + target, + inputRef, + showInput, + complete, + hasCompletion, + isLoading, + stop, + onAccept: handleAcceptCompletion, + onReject: handleDeclineCompletion, + onClose, + runCell, +}: { + target: AiCompletionCell; + inputRef: React.RefObject; + showInput: boolean; + complete: ( + prompt: string, + includeOtherCells: boolean, + runtime: RuntimeManager, + ) => Promise; + hasCompletion: boolean; + isLoading: boolean; + stop: () => void; + onAccept: () => void; + onReject: () => void; + onClose: () => void; + runCell: () => void; +}) { + const [includeOtherCells, setIncludeOtherCells] = useAtom( + includeOtherCellsAtom, + ); + const includeOtherCellsCheckboxId = useId(); + const runtime = useRuntimeManager(); + 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(() => { + const { initialPrompt, triggerImmediately } = target; + if (triggerImmediately && initialPrompt) { + const timer = setTimeout(() => submit(initialPrompt), 100); + return () => clearTimeout(timer); } - // 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); + }, [target, submit]); + + useEffect(() => { + const prompt = inputRef.current; + if (!showInput || prompt?.view?.hasFocus) { + return; } - }; + const timer = setTimeout(() => { + const view = inputRef.current?.view; + if (view && !view.hasFocus) { + view.focus(); + selectAllText(view); + } + }, 100); + 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); const completionButtons = ( <> @@ -322,115 +444,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, + })} + /> + +
+
+ + addContextCompletion(inputRef)} + isLoading={isLoading} + /> + +
+ {hasCompletion && ( +
+ {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/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 95125b12527..23291ab4720 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 { @@ -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, @@ -120,7 +121,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); @@ -379,7 +381,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(); @@ -404,29 +406,17 @@ 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: { - from: 0, - to: editorViewRef.current.state.doc.length, - insert: newCode, - }, - }); - })} - acceptChange={useEvent((newCode) => { - editorViewRef.current?.dispatch({ - changes: { - from: 0, - to: editorViewRef.current.state.doc.length, - insert: newCode, - }, - }); - editorViewRef.current?.focus(); - setAiCompletionCell(null); + const view = editorViewRef.current; + if (view) { + replaceEditorContent(view, newCode); + } })} 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.