Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
328 changes: 327 additions & 1 deletion frontend/src/components/editor/__tests__/cell-renders.test.tsx
Original file line number Diff line number Diff line change
@@ -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";
Expand All @@ -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();
});

Expand Down Expand Up @@ -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<ReturnType<typeof setup>>["store"], id: string) {
return store.get(notebookAtom).cellHandles[cellId(id)].current?.editorView;
}

function prompt() {
const editor = document.querySelector<HTMLElement>(
".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 () => {
Expand All @@ -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 () => {
Expand Down Expand Up @@ -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<Uint8Array>();
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);
},
);
Loading
Loading