A reactive notebook for Python — run reproducible experiments, query with SQL, execute as a script, deploy as an app, and version with git. Stored as pure Python. All in a modern, AI-native editor.
Python artificial-intelligencedagdata-sciencedata-visualizationdataflowdeveloper-toolsmachine-learningnotebookspipelinepythonreactivesqlweb-app
fix: improve inline completion responsiveness (#11288)
Myles Scolnickf240019517f8
diff --git a/frontend/package.json b/frontend/package.jsonindex f16f24efd1..0eb993db2b 100644--- a/frontend/package.json+++ b/frontend/package.json@@ -52,8 +52,8 @@"@lezer/lr": "^1.4.10","@lezer/markdown": "^1.7.2","@lezer/python": "^1.1.19",- "@marimo-team/codemirror-ai": "^0.3.9",- "@marimo-team/codemirror-languageserver": "^2.0.0",+ "@marimo-team/codemirror-ai": "^0.3.10",+ "@marimo-team/codemirror-languageserver": "^2.0.1","@marimo-team/codemirror-mcp": "^0.1.7","@marimo-team/codemirror-sql": "^0.3.0","@marimo-team/llm-info": "workspace:*",diff --git a/frontend/src/core/codemirror/copilot/__tests__/completion-integration.test.ts b/frontend/src/core/codemirror/copilot/__tests__/completion-integration.test.tsnew file mode 100644index 0000000000..5c790f081e--- /dev/null+++ b/frontend/src/core/codemirror/copilot/__tests__/completion-integration.test.ts@@ -0,0 +1,447 @@+/* Copyright 2026 Marimo. All rights reserved. */++import { EditorView } from "@codemirror/view";+import {+ languageServerWithClient,+ type JSONRPCMessage,+ type JSONRPCRequest,+ type Transport,+} from "@marimo-team/codemirror-languageserver";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { API } from "@/core/network/api";+import { languageAdapterState } from "../../language/extension";+import { copilotBundle } from "../extension";+import { getCodes } from "../getCodes";+import { CopilotLanguageServerClient } from "../language-server";++const fixture: { client?: CopilotLanguageServerClient } = vi.hoisted(+ () => ({}),+);++vi.mock("../client", () => ({+ COPILOT_FILENAME: "/__marimo_copilot__.py",+ getCopilotClient: () => fixture.client,+ copilotServer: () =>+ languageServerWithClient({+ client: fixture.client!,+ documentUri: "file:///__marimo_copilot__.py",+ languageId: "python",+ sendIncrementalChanges: false,+ hoverEnabled: false,+ completionEnabled: false,+ diagnosticsEnabled: false,+ signatureHelpEnabled: false,+ }),+}));+vi.mock("../state", async (importOriginal) => ({+ ...(await importOriginal<typeof import("../state")>()),+ isCopilotEnabled: () => true,+}));+vi.mock("../getCodes", () => ({+ getCodes: vi.fn((code: string) => `import math\n\n${code}`),+}));++describe("Copilot editor integration", () => {+ let view: EditorView;+ let client: CopilotLanguageServerClient;+ let emit: (message: JSONRPCMessage) => void;+ let sent: JSONRPCMessage[];++ function requests() {+ return sent.filter(+ (message): message is JSONRPCRequest =>+ "id" in message &&+ "method" in message &&+ message.method === "textDocument/inlineCompletion",+ );+ }+ function type(text: string) {+ const from = view.state.selection.main.head;+ view.dispatch({+ changes: { from, insert: text },+ selection: { anchor: from + text.length },+ });+ }+ function respond(text: string) {+ emit({+ jsonrpc: "2.0",+ id: requests().at(-1)!.id,+ result: [{ insertText: text }],+ });+ }++ function useCustomEditor() {+ view.destroy();+ view = new EditorView({+ parent: document.body,+ doc: "pri",+ selection: { anchor: 3 },+ extensions: [+ languageAdapterState,+ copilotBundle({+ copilot: "custom",+ activate_on_typing: true,+ signature_hint_on_typing: false,+ }),+ ],+ });+ vi.spyOn(view, "hasFocus", "get").mockReturnValue(true);+ }++ beforeEach(async () => {+ vi.useFakeTimers();+ // copilotBundle intentionally disables itself in ordinary unit tests.+ vi.stubEnv("NODE_ENV", "development");+ sent = [];+ const transport: Transport = {+ connect: vi.fn().mockResolvedValue(undefined),+ close: vi.fn(),+ onMessage: (handler) => {+ emit = handler;+ return vi.fn();+ },+ send: (message) => {+ sent.push(message);+ if (+ "id" in message &&+ "method" in message &&+ ["initialize", "shutdown"].includes(message.method)+ ) {+ emit({+ jsonrpc: "2.0",+ id: message.id,+ result:+ message.method === "initialize"+ ? { capabilities: { textDocumentSync: 1 } }+ : null,+ });+ }+ },+ };+ client = new CopilotLanguageServerClient({+ rootUri: "file:///",+ workspaceFolders: null,+ transport,+ });+ fixture.client = client;+ await client.initializePromise;+ view = new EditorView({+ parent: document.body,+ doc: "pri",+ selection: { anchor: 3 },+ extensions: copilotBundle({+ copilot: "github",+ activate_on_typing: true,+ signature_hint_on_typing: false,+ }),+ });+ vi.spyOn(view, "hasFocus", "get").mockReturnValue(true);+ await vi.advanceTimersByTimeAsync(0);+ sent.length = 0;+ vi.mocked(getCodes).mockClear();+ });++ afterEach(() => {+ view.destroy();+ client.close();+ fixture.client = undefined;+ vi.useRealTimers();+ vi.unstubAllEnvs();+ vi.restoreAllMocks();+ });++ it("uploads once and requests the matching version/position at 150ms without an extra sleep", async () => {+ type("n");+ type("t");+ await vi.advanceTimersByTimeAsync(149);+ expect(sent).toEqual([]);+ expect(getCodes).not.toHaveBeenCalled();+ await vi.advanceTimersByTimeAsync(1);+ expect(getCodes).toHaveBeenCalledExactlyOnceWith("print");+ expect(sent).toEqual([+ {+ jsonrpc: "2.0",+ method: "textDocument/didChange",+ params: {+ textDocument: { uri: "file:///__marimo_copilot__.py", version: 2 },+ contentChanges: [{ text: "import math\n\nprint" }],+ },+ },+ {+ jsonrpc: "2.0",+ id: expect.any(Number),+ method: "textDocument/inlineCompletion",+ params: {+ textDocument: { uri: "file:///__marimo_copilot__.py", version: 2 },+ position: { line: 2, character: 5 },+ context: { triggerKind: 2 },+ formattingOptions: { tabSize: 4, insertSpaces: true },+ },+ },+ ]);+ respond("(value)");+ await vi.advanceTimersByTimeAsync(0);+ expect(view.dom.querySelector(".cm-inline-suggestion")).toHaveTextContent(+ "(value)",+ );+ type("(");+ expect(view.dom.querySelector(".cm-inline-suggestion")).toHaveTextContent(+ "value)",+ );+ await vi.advanceTimersByTimeAsync(500);+ expect(requests()).toHaveLength(1);+ expect(getCodes).toHaveBeenCalledTimes(1);+ type("x");+ await vi.advanceTimersByTimeAsync(150);+ expect(getCodes).toHaveBeenLastCalledWith("print(x");+ expect(requests()).toHaveLength(2);+ respond(")");+ await vi.advanceTimersByTimeAsync(0);+ expect(view.dom.querySelector(".cm-inline-suggestion")).toHaveTextContent(+ ")",+ );+ });++ it("never uploads a superseded snapshot when typing restarts the debounce", async () => {+ const flush = vi.spyOn(client, "flushDocumentChanges");+ type("n");+ await vi.advanceTimersByTimeAsync(149);+ type("t");+ await vi.advanceTimersByTimeAsync(149);+ expect(flush).not.toHaveBeenCalled();+ expect(getCodes).not.toHaveBeenCalled();+ expect(sent).toEqual([]);+ await vi.advanceTimersByTimeAsync(1);+ expect(flush.mock.calls.filter(([code]) => code !== undefined)).toEqual([+ ["print"],+ ]);+ expect(getCodes).toHaveBeenCalledExactlyOnceWith("print");+ expect(+ sent.filter(+ (message) =>+ "method" in message && message.method === "textDocument/didChange",+ ),+ ).toEqual([+ {+ jsonrpc: "2.0",+ method: "textDocument/didChange",+ params: {+ textDocument: { uri: "file:///__marimo_copilot__.py", version: 2 },+ contentChanges: [{ text: "import math\n\nprint" }],+ },+ },+ ]);+ expect(requests()).toHaveLength(1);+ respond("(latest)");+ await vi.advanceTimersByTimeAsync(0);+ expect(view.dom.querySelector(".cm-inline-suggestion")).toHaveTextContent(+ "(latest)",+ );+ });++ it("does not flush a cancelled callback after moving away and back before its deadline", async () => {+ const flush = vi.spyOn(client, "flushDocumentChanges");+ type("n");+ await vi.advanceTimersByTimeAsync(149);+ view.dispatch({ selection: { anchor: 0 } });+ view.dispatch({ selection: { anchor: 4 } });+ await vi.advanceTimersByTimeAsync(1000);+ expect(flush).not.toHaveBeenCalled();+ expect(getCodes).not.toHaveBeenCalled();+ expect(sent).toEqual([]);+ expect(view.dom.querySelector(".cm-inline-suggestion")).toBeNull();+ });++ it("cancels on cursor movement and never shows an old reply", async () => {+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ view.dispatch({ selection: { anchor: 0 } });+ await vi.advanceTimersByTimeAsync(0);+ expect(sent.at(-1)).toEqual({+ jsonrpc: "2.0",+ method: "$/cancelRequest",+ params: { id: requests()[0].id },+ });+ respond("stale");+ await vi.advanceTimersByTimeAsync(0);+ expect(view.dom.querySelector(".cm-inline-suggestion")).toBeNull();+ });++ it("cancels an in-flight suggestion on typing before requesting the next version", async () => {+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ type("t");+ await vi.advanceTimersByTimeAsync(0);+ expect(sent.at(-1)).toEqual({+ jsonrpc: "2.0",+ method: "$/cancelRequest",+ params: { id: requests()[0].id },+ });+ await vi.advanceTimersByTimeAsync(150);+ respond("(new)");+ await vi.advanceTimersByTimeAsync(0);+ emit({+ jsonrpc: "2.0",+ id: requests()[0].id,+ result: [{ insertText: "stale" }],+ });+ await vi.advanceTimersByTimeAsync(0);+ expect(view.dom.querySelector(".cm-inline-suggestion")).toHaveTextContent(+ "(new)",+ );+ });+ it("does not display a response after focus is lost", async () => {+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ vi.spyOn(view, "hasFocus", "get").mockReturnValue(false);+ respond("stale");+ await vi.advanceTimersByTimeAsync(0);+ expect(view.dom.querySelector(".cm-inline-suggestion")).toBeNull();+ });++ it("passes cancellation through to custom provider HTTP requests", async () => {+ const result = Promise.withResolvers<string>();+ const post = vi.spyOn(API, "post").mockReturnValue(result.promise);+ useCustomEditor();+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ expect(post).toHaveBeenCalledExactlyOnceWith(+ "/ai/inline_completion",+ { prefix: "prin", suffix: "", language: "python" },+ { signal: expect.objectContaining({ aborted: false }) },+ );+ const signal = post.mock.calls[0][2]?.signal;+ type("t");+ expect(signal?.aborted).toBe(true);+ result.resolve("stale");+ await vi.advanceTimersByTimeAsync(0);+ expect(view.dom.querySelector(".cm-inline-suggestion")).toBeNull();+ });+ it.each(["HTTP failure", "AbortError"])(+ "recovers on the next edit after custom provider %s",+ async (failure) => {+ useCustomEditor();+ const error = vi+ .spyOn(console, "error")+ .mockImplementation(() => undefined);+ const post = vi+ .spyOn(API, "post")+ .mockRejectedValueOnce(+ failure === "AbortError"+ ? new DOMException("aborted", "AbortError")+ : new Error("HTTP 503"),+ )+ .mockResolvedValueOnce("(recovered)");+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ expect(post).toHaveBeenCalledTimes(1);+ expect(view.dom.querySelector(".cm-inline-suggestion")).toBeNull();+ expect(error).toHaveBeenCalledTimes(failure === "AbortError" ? 0 : 1);+ type("t");+ await vi.advanceTimersByTimeAsync(150);+ expect(post).toHaveBeenCalledTimes(2);+ expect(view.dom.querySelector(".cm-inline-suggestion")).toHaveTextContent(+ "(recovered)",+ );+ },+ );++ it.each(["empty document", "empty prefix"])(+ "does not call the custom provider for an %s",+ async (input) => {+ useCustomEditor();+ const post = vi.spyOn(API, "post").mockResolvedValue("unexpected");+ view.dispatch({+ changes: {+ from: 0,+ to: view.state.doc.length,+ insert: input === "empty document" ? "" : "suffix",+ },+ selection: { anchor: 0 },+ });+ await vi.advanceTimersByTimeAsync(150);+ expect(post).not.toHaveBeenCalled();+ expect(view.dom.querySelector(".cm-inline-suggestion")).toBeNull();+ },+ );++ it("aborts custom provider HTTP work when its editor is destroyed", async () => {+ useCustomEditor();+ const result = Promise.withResolvers<string>();+ const post = vi.spyOn(API, "post").mockReturnValue(result.promise);+ const error = vi+ .spyOn(console, "error")+ .mockImplementation(() => undefined);+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ expect(post).toHaveBeenCalledTimes(1);+ const signal = post.mock.calls[0][2]?.signal;+ expect(signal?.aborted).toBe(false);+ view.destroy();+ expect(signal?.aborted).toBe(true);+ result.reject(new Error("connection closed after destruction"));+ await vi.advanceTimersByTimeAsync(150);+ expect(post).toHaveBeenCalledTimes(1);+ expect(error).not.toHaveBeenCalled();+ });++ it.each(["server error", "timeout"])(+ "recovers on the next edit after a Copilot %s",+ async (failure) => {+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ expect(requests()).toHaveLength(1);+ const id = requests()[0].id;+ if (failure === "timeout") {+ await vi.advanceTimersByTimeAsync(10_000);+ } else {+ emit({+ jsonrpc: "2.0",+ id,+ error: { code: -32603, message: "unavailable" },+ });+ await vi.advanceTimersByTimeAsync(0);+ }+ expect(+ sent.filter(+ (message) =>+ "method" in message && message.method === "$/cancelRequest",+ ),+ ).toEqual(+ failure === "timeout"+ ? [{ jsonrpc: "2.0", method: "$/cancelRequest", params: { id } }]+ : [],+ );+ expect(view.dom.querySelector(".cm-inline-suggestion")).toBeNull();+ type("t");+ await vi.advanceTimersByTimeAsync(150);+ expect(requests()).toHaveLength(2);+ respond("(recovered)");+ await vi.advanceTimersByTimeAsync(0);+ emit({ jsonrpc: "2.0", id, result: [{ insertText: "stale" }] });+ await vi.advanceTimersByTimeAsync(0);+ expect(view.dom.querySelector(".cm-inline-suggestion")).toHaveTextContent(+ "(recovered)",+ );+ },+ );++ it("keeps the focused cell last when another cell changes during the debounce", async () => {+ type("n");+ await client.textDocumentDidChange({+ textDocument: { uri: "file:///__marimo_copilot__.py", version: 1 },+ contentChanges: [{ text: "other_cell = 42" }],+ });+ await vi.advanceTimersByTimeAsync(150);+ expect(getCodes).toHaveBeenCalledExactlyOnceWith("prin");+ expect(requests()[0].params).toMatchObject({+ textDocument: { version: 3 },+ position: { line: 2, character: 4 },+ });+ respond("t()");+ await vi.advanceTimersByTimeAsync(0);+ expect(view.dom.querySelector(".cm-inline-suggestion")).toHaveTextContent(+ "t()",+ );+ });+});diff --git a/frontend/src/core/codemirror/copilot/__tests__/inline-completion.test.ts b/frontend/src/core/codemirror/copilot/__tests__/inline-completion.test.tsnew file mode 100644index 0000000000..260ce03a02--- /dev/null+++ b/frontend/src/core/codemirror/copilot/__tests__/inline-completion.test.ts@@ -0,0 +1,395 @@+/* Copyright 2026 Marimo. All rights reserved. */++import {+ EditorSelection,+ EditorState,+ type TransactionSpec,+} from "@codemirror/state";+import { EditorView } from "@codemirror/view";+import {+ acceptInlineCompletion,+ inlineCompletion,+ rejectInlineCompletion,+} from "@marimo-team/codemirror-ai";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++// Exercise the installed dependency to catch regressions in upstream releases.+describe("inline completion lifecycle", () => {+ let view: EditorView;+ const fetchFn =+ vi.fn<+ (+ state: EditorState,+ signal: AbortSignal,+ view: EditorView,+ ) => Promise<string>+ >();++ function create(+ options: Partial<Parameters<typeof inlineCompletion>[0]> = {},+ ) {+ view = new EditorView({+ parent: document.body,+ state: EditorState.create({+ doc: "pri",+ selection: { anchor: 3 },+ extensions: [+ EditorState.allowMultipleSelections.of(true),+ inlineCompletion({ delay: 150, fetchFn, ...options }),+ ],+ }),+ });+ }++ function type(text: string) {+ view.dispatch({+ ...view.state.replaceSelection(text),+ userEvent: "input.type",+ });+ }++ function suggestion() {+ return view.dom.querySelector(".cm-inline-suggestion")?.textContent ?? null;+ }++ async function show(text = 't("hello")') {+ fetchFn.mockResolvedValue(text);+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ expect(suggestion()).toBe(text);+ }++ beforeEach(() => {+ vi.useFakeTimers();+ fetchFn.mockReset().mockResolvedValue('t("hello")');+ });++ afterEach(() => {+ view?.destroy();+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it("debounces bursts and fetches only the latest document at 150ms", async () => {+ create();+ type("n");+ await vi.advanceTimersByTimeAsync(149);+ expect(fetchFn).not.toHaveBeenCalled();+ type("t");+ await vi.advanceTimersByTimeAsync(149);+ expect(fetchFn).not.toHaveBeenCalled();+ const state = view.state;+ await vi.advanceTimersByTimeAsync(1);+ expect(fetchFn).toHaveBeenCalledExactlyOnceWith(+ state,+ expect.objectContaining({ aborted: false }),+ view,+ );+ });++ it.each(["t", 't("', 't("hello'])(+ "retains the suffix immediately after matching input %j",+ async (text) => {+ create();+ await show();+ type(text);+ expect(suggestion()).toBe('t("hello")'.slice(text.length));+ await vi.advanceTimersByTimeAsync(1000);+ expect(fetchFn).toHaveBeenCalledTimes(1);+ expect(acceptInlineCompletion(view)).toBe(true);+ expect(view.state.doc.toString()).toBe('print("hello")');+ },+ );++ it("preserves multiline and UTF-16 suggestions", async () => {+ create();+ await show("😀\nnext()");+ type("😀\n");+ expect(suggestion()).toBe("next()");+ expect(fetchFn).toHaveBeenCalledTimes(1);+ });++ it("fetches a continuation when the suggestion is fully typed", async () => {+ create();+ await show("t");+ fetchFn.mockResolvedValue("(value)");+ type("t");+ expect(suggestion()).toBeNull();+ await vi.advanceTimersByTimeAsync(150);+ expect(suggestion()).toBe("(value)");+ expect(fetchFn).toHaveBeenCalledTimes(2);+ });++ it.each<[string, TransactionSpec]>([+ [+ "mismatch",+ { changes: { from: 4, insert: "x" }, selection: { anchor: 5 } },+ ],+ ["deletion", { changes: { from: 3, to: 4 }, selection: { anchor: 3 } }],+ [+ "replacement",+ { changes: { from: 3, to: 4, insert: "t" }, selection: { anchor: 4 } },+ ],+ [+ "edit away from cursor",+ { changes: { from: 0, insert: "t" }, selection: { anchor: 5 } },+ ],+ [+ "multiple edits",+ {+ changes: [+ { from: 0, insert: "x" },+ { from: 4, insert: "t" },+ ],+ selection: { anchor: 6 },+ },+ ],+ [+ "cursor moved after insertion",+ { changes: { from: 4, insert: "t" }, selection: { anchor: 0 } },+ ],+ ])("discards a suggestion after %s", async (_label, transaction) => {+ create();+ await show();+ view.dispatch(transaction);+ expect(suggestion()).toBeNull();+ await vi.advanceTimersByTimeAsync(150);+ expect(fetchFn).toHaveBeenCalledTimes(2);+ });++ it("does not reuse suggestions or fetch for multiple cursors", async () => {+ create();+ await show();+ view.dispatch({+ selection: EditorSelection.create(+ [EditorSelection.cursor(0), EditorSelection.cursor(4)],+ 1,+ ),+ });+ type("t");+ expect(view.state.doc.toString()).toBe("tprint");+ expect(view.state.selection.toJSON()).toEqual(+ EditorSelection.create(+ [EditorSelection.cursor(1), EditorSelection.cursor(6)],+ 1,+ ).toJSON(),+ );+ await vi.advanceTimersByTimeAsync(150);+ expect(suggestion()).toBeNull();+ expect(fetchFn).toHaveBeenCalledTimes(1);+ });++ it("does not fetch when an edit leaves a nonempty selection", async () => {+ create();+ view.dispatch({+ changes: { from: 3, insert: "n" },+ selection: { anchor: 0, head: 4 },+ });+ await vi.advanceTimersByTimeAsync(150);+ expect(fetchFn).not.toHaveBeenCalled();+ expect(suggestion()).toBeNull();+ });++ it("cancels a deferred cache hit before it can display at a new cursor", async () => {+ create();+ await show();+ view.dispatch({ changes: { from: 3, to: 4 }, selection: { anchor: 3 } });+ type("n");+ view.dispatch({ selection: { anchor: 0 } });+ await vi.advanceTimersByTimeAsync(150);+ expect(fetchFn).toHaveBeenCalledTimes(1);+ expect(suggestion()).toBeNull();+ });++ it("ignores a late failure from a cancelled request without hiding its replacement", async () => {+ create();+ const error = vi+ .spyOn(console, "error")+ .mockImplementation(() => undefined);+ const old = Promise.withResolvers<string>();+ fetchFn.mockReturnValueOnce(old.promise).mockResolvedValueOnce("(new)");+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ type("t");+ await vi.advanceTimersByTimeAsync(150);+ expect(suggestion()).toBe("(new)");+ old.reject(new Error("old connection failed"));+ await vi.advanceTimersByTimeAsync(0);+ expect(suggestion()).toBe("(new)");+ expect(error).not.toHaveBeenCalled();+ });++ it("cancels scheduled work when the cursor moves", async () => {+ create();+ type("n");+ view.dispatch({ selection: { anchor: 0 } });+ await vi.advanceTimersByTimeAsync(150);+ expect(fetchFn).not.toHaveBeenCalled();+ });++ it("aborts superseded work and ignores an out-of-order response", async () => {+ create();+ const old = Promise.withResolvers<string>();+ const latest = Promise.withResolvers<string>();+ fetchFn+ .mockReturnValueOnce(old.promise)+ .mockReturnValueOnce(latest.promise);+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ const oldSignal = fetchFn.mock.calls[0][1];+ type("t");+ expect(oldSignal.aborted).toBe(true);+ await vi.advanceTimersByTimeAsync(150);+ latest.resolve("(new)");+ await vi.advanceTimersByTimeAsync(0);+ old.resolve("stale");+ await vi.advanceTimersByTimeAsync(0);+ expect(suggestion()).toBe("(new)");+ });++ it("ignores a response after moving away and back to the same cursor", async () => {+ create();+ const result = Promise.withResolvers<string>();+ fetchFn.mockReturnValue(result.promise);+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ view.dispatch({ selection: { anchor: 0 } });+ view.dispatch({ selection: { anchor: 4 } });+ result.resolve("stale");+ await vi.advanceTimersByTimeAsync(0);+ expect(suggestion()).toBeNull();+ expect(fetchFn.mock.calls[0][1].aborted).toBe(true);+ });++ it.each([false, true])(+ "cancels on destruction (already fetching: %s)",+ async (started) => {+ create();+ const result = Promise.withResolvers<string>();+ fetchFn.mockReturnValue(result.promise);+ type("n");+ if (started) {+ await vi.advanceTimersByTimeAsync(150);+ }+ view.destroy();+ result.resolve("stale");+ await vi.advanceTimersByTimeAsync(200);+ expect(fetchFn).toHaveBeenCalledTimes(started ? 1 : 0);+ expect(fetchFn.mock.calls[0]?.[1].aborted).toBe(+ started ? true : undefined,+ );+ },+ );++ it("recovers after a failed request", async () => {+ create();+ const error = vi+ .spyOn(console, "error")+ .mockImplementation(() => undefined);+ fetchFn.mockRejectedValueOnce(new Error("offline"));+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ expect(suggestion()).toBeNull();+ expect(error).toHaveBeenCalledTimes(1);+ type("t");+ await vi.advanceTimersByTimeAsync(150);+ expect(suggestion()).toBe('t("hello")');+ });++ it("does not log an expected abort rejection", async () => {+ create();+ const error = vi+ .spyOn(console, "error")+ .mockImplementation(() => undefined);+ fetchFn.mockRejectedValueOnce(new DOMException("aborted", "AbortError"));+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ expect(error).not.toHaveBeenCalled();+ expect(suggestion()).toBeNull();+ });++ it("respects fetch/display gates and Escape rejection", async () => {+ const before = vi.fn(() => false);+ const display = vi.fn(() => false);+ create({+ events: { beforeSuggestionFetch: before, shouldShowSuggestion: display },+ });+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ expect(fetchFn).not.toHaveBeenCalled();+ before.mockReturnValue(true);+ type("t");+ await vi.advanceTimersByTimeAsync(150);+ expect(suggestion()).toBeNull();+ display.mockReturnValue(true);+ type("(");+ await vi.advanceTimersByTimeAsync(150);+ expect(rejectInlineCompletion(view)).toBe(true);+ expect(suggestion()).toBeNull();+ expect(acceptInlineCompletion(view)).toBe(false);+ });++ it("reuses a cached result without dispatching during a view update", async () => {+ create();+ await show();+ view.dispatch({ changes: { from: 3, to: 4 }, selection: { anchor: 3 } });+ type("n");+ expect(() => view.dispatch({})).not.toThrow();+ await vi.advanceTimersByTimeAsync(0);+ expect(suggestion()).toBe('t("hello")');+ expect(fetchFn).toHaveBeenCalledTimes(1);+ });++ it("does not reuse the same document's cached suggestion at a different cursor", async () => {+ create();+ await show();+ view.dispatch({ changes: { from: 3, to: 4 }, selection: { anchor: 3 } });+ view.dispatch({+ changes: { from: 3, insert: "n" },+ selection: { anchor: 0 },+ });+ await vi.advanceTimersByTimeAsync(150);+ expect(fetchFn).toHaveBeenCalledTimes(2);+ expect(fetchFn.mock.calls[1][0].selection.main.head).toBe(0);+ });++ it("expires cached results", async () => {+ create({ cacheTimeout: 100 });+ await show();+ await vi.advanceTimersByTimeAsync(101);+ view.dispatch({ changes: { from: 3, to: 4 }, selection: { anchor: 3 } });+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ expect(fetchFn).toHaveBeenCalledTimes(2);+ });+ it("bounds the cache instead of retaining every document ever typed", async () => {+ create({ delay: 0, cacheTimeout: 1_000_000 });+ await show();+ for (let i = 0; i < 21; i++) {+ const text = `entry${i}`;+ view.dispatch({+ changes: { from: 0, to: view.state.doc.length, insert: text },+ selection: { anchor: text.length },+ });+ await vi.advanceTimersByTimeAsync(0);+ }+ view.dispatch({+ changes: { from: 0, to: view.state.doc.length, insert: "prin" },+ selection: { anchor: 4 },+ });+ await vi.advanceTimersByTimeAsync(0);+ expect(fetchFn).toHaveBeenCalledTimes(23);+ });++ it("does not cache empty results", async () => {+ create();+ fetchFn.mockResolvedValueOnce("");+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ view.dispatch({ changes: { from: 3, to: 4 }, selection: { anchor: 3 } });+ type("n");+ await vi.advanceTimersByTimeAsync(150);+ expect(fetchFn).toHaveBeenCalledTimes(2);+ expect(suggestion()).toBe('t("hello")');+ });+});diff --git a/frontend/src/core/codemirror/copilot/__tests__/language-server.test.ts b/frontend/src/core/codemirror/copilot/__tests__/language-server.test.tsindex ce148bfdab..dbb5488bd6 100644--- a/frontend/src/core/codemirror/copilot/__tests__/language-server.test.ts+++ b/frontend/src/core/codemirror/copilot/__tests__/language-server.test.ts@@ -5,10 +5,12 @@ import type {JSONRPCRequest,Transport,} from "@marimo-team/codemirror-languageserver";-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import type { InlineCompletionParams } from "vscode-languageserver-protocol";import { store } from "@/core/state/jotai";+import * as notebookCodes from "../getCodes";import { CopilotLanguageServerClient } from "../language-server";-import { copilotStatusState } from "../state";+import { copilotStatusState, githubCopilotLoadingVersion } from "../state";const copilotState = vi.hoisted(() => ({ isEnabled: true }));@@ -382,6 +384,7 @@ describe("CopilotLanguageServerClient", () => {contentChanges: [{ text: "value = 2" }],});+ await client.flushDocumentChanges();expect(notifications(mockTransport, "textDocument/didChange")).toEqual([{jsonrpc: "2.0",@@ -503,3 +506,509 @@ describe("CopilotLanguageServerClient", () => {});});});++describe("Copilot completion requests", () => {+ let transport: MockTransport;+ let client: CopilotLanguageServerClient;+ const params: InlineCompletionParams = {+ textDocument: { uri: "file:///test.py" },+ position: { line: 0, character: 1 },+ context: { triggerKind: 2 },+ };+ const suggestion = [{ insertText: "result" }];++ function requests() {+ return transport.sent.filter(+ (message): message is JSONRPCRequest =>+ isRequest(message) &&+ message.method === "textDocument/inlineCompletion",+ );+ }++ async function change(text: string) {+ await client.textDocumentDidChange({+ textDocument: { uri: params.textDocument.uri, version: 1 },+ contentChanges: [{ text }],+ });+ }++ async function tick() {+ await vi.advanceTimersByTimeAsync(0);+ }++ beforeEach(async () => {+ vi.useFakeTimers();+ copilotState.isEnabled = true;+ store.set(githubCopilotLoadingVersion, null);+ transport = new MockTransport();+ client = new CopilotLanguageServerClient({+ rootUri: "file:///test",+ workspaceFolders: null,+ transport,+ });+ await client.initializePromise;+ await client.textDocumentDidOpen({+ textDocument: {+ uri: params.textDocument.uri,+ languageId: "python",+ version: 1,+ text: "x",+ },+ });+ transport.sent.length = 0;+ });++ afterEach(() => {+ client.close();+ const shutdown = transport.sent.find(+ (message) => isRequest(message) && message.method === "shutdown",+ );+ if (shutdown && isRequest(shutdown)) {+ transport.emit({ jsonrpc: "2.0", id: shutdown.id, result: null });+ }+ vi.useRealTimers();+ vi.restoreAllMocks();+ });++ it("coalesces edits and sends the latest document before the completion", async () => {+ for (const text of ["p", "pr", "pri", "prin", "print"]) {+ await change(text);+ }+ expect(notifications(transport, "textDocument/didChange")).toEqual([]);+ const response = client.getCompletion(params);+ await tick();+ expect(transport.sent).toEqual([+ {+ jsonrpc: "2.0",+ method: "textDocument/didChange",+ params: {+ textDocument: { uri: params.textDocument.uri, version: 6 },+ contentChanges: [{ text: "print" }],+ },+ },+ {+ jsonrpc: "2.0",+ id: expect.any(Number),+ method: "textDocument/inlineCompletion",+ params: {+ ...params,+ textDocument: { uri: params.textDocument.uri, version: 6 },+ },+ },+ ]);+ transport.emit({+ jsonrpc: "2.0",+ id: requests()[0].id,+ result: suggestion,+ });+ await expect(response).resolves.toEqual(suggestion);+ expect(store.get(githubCopilotLoadingVersion)).toBeNull();+ expect(await client.flushDocumentChanges()).toBe("print");+ expect(notifications(transport, "textDocument/didChange")).toHaveLength(1);+ });++ it.each(["x", ""])(+ "does not upload an unchanged focused cell %j again",+ async (text) => {+ const assemble = vi.spyOn(notebookCodes, "getCodes");+ await change(text);+ expect(await client.flushDocumentChanges(text)).toBe(text);+ expect(await client.flushDocumentChanges(text)).toBe(text);+ expect(await client.flushDocumentChanges(text)).toBe(text);+ expect(assemble).toHaveBeenCalledTimes(3);+ expect(notifications(transport, "textDocument/didChange")).toEqual([+ {+ jsonrpc: "2.0",+ method: "textDocument/didChange",+ params: {+ textDocument: { uri: params.textDocument.uri, version: 2 },+ contentChanges: [{ text }],+ },+ },+ ]);++ await change("next");+ await client.flushDocumentChanges("next");+ expect(+ notifications(transport, "textDocument/didChange")[1].params,+ ).toEqual({+ textDocument: { uri: params.textDocument.uri, version: 3 },+ contentChanges: [{ text: "next" }],+ });+ },+ );++ it("does not upload a document that already matches didOpen", async () => {+ expect(await client.flushDocumentChanges("x")).toBe("x");+ expect(notifications(transport, "textDocument/didChange")).toEqual([]);+ });++ it("compares the assembled notebook and uploads changes in another cell", async () => {+ let otherCell = "import math";+ const assemble = vi+ .spyOn(notebookCodes, "getCodes")+ .mockImplementation((code) => `${otherCell}\n${code}`);+ await change("x");+ expect(await client.flushDocumentChanges("x")).toBe("import math\nx");+ expect(await client.flushDocumentChanges("x")).toBe("import math\nx");+ otherCell = "import random";+ expect(await client.flushDocumentChanges("x")).toBe("import random\nx");+ expect(await client.flushDocumentChanges("x")).toBe("import random\nx");+ expect(assemble).toHaveBeenCalledTimes(4);+ expect(notifications(transport, "textDocument/didChange")).toEqual([+ {+ jsonrpc: "2.0",+ method: "textDocument/didChange",+ params: {+ textDocument: { uri: params.textDocument.uri, version: 2 },+ contentChanges: [{ text: "import math\nx" }],+ },+ },+ {+ jsonrpc: "2.0",+ method: "textDocument/didChange",+ params: {+ textDocument: { uri: params.textDocument.uri, version: 3 },+ contentChanges: [{ text: "import random\nx" }],+ },+ },+ ]);+ });++ it("assembles once with the focused cell last when another cell has a pending edit", async () => {+ const assemble = vi+ .spyOn(notebookCodes, "getCodes")+ .mockImplementation((code) => `other\n${code}`);+ await change("other");+ expect(await client.flushDocumentChanges("x")).toBe("other\nx");+ expect(assemble).toHaveBeenCalledExactlyOnceWith("x");+ expect(notifications(transport, "textDocument/didChange")).toEqual([+ {+ jsonrpc: "2.0",+ method: "textDocument/didChange",+ params: {+ textDocument: { uri: params.textDocument.uri, version: 3 },+ contentChanges: [{ text: "other\nx" }],+ },+ },+ ]);+ });++ it("retries a failed upload even when its text matches the last attempted document", async () => {+ const assemble = vi.spyOn(notebookCodes, "getCodes");+ transport.send.mockImplementationOnce(() => {+ throw new Error("socket closed");+ });+ await expect(client.flushDocumentChanges("latest")).rejects.toThrow(+ "socket closed",+ );+ expect(await client.flushDocumentChanges("latest")).toBe("latest");+ expect(await client.flushDocumentChanges("latest")).toBe("latest");+ expect(assemble).toHaveBeenCalledTimes(3);+ expect(notifications(transport, "textDocument/didChange")).toEqual([+ {+ jsonrpc: "2.0",+ method: "textDocument/didChange",+ params: {+ textDocument: { uri: params.textDocument.uri, version: 2 },+ contentChanges: [{ text: "latest" }],+ },+ },+ ]);+ });++ it("cancels a rapid request instead of giving the next caller its promise", async () => {+ const first = client.getCompletion(params);+ await tick();+ const second = client.getCompletion({+ ...params,+ position: { line: 0, character: 0 },+ });+ await tick();+ expect(requests()).toHaveLength(2);+ expect(notifications(transport, "$/cancelRequest")).toEqual([+ {+ jsonrpc: "2.0",+ method: "$/cancelRequest",+ params: { id: requests()[0].id },+ },+ ]);+ await expect(first).resolves.toBeNull();+ // Both requests use the same version; old cleanup must not hide the new spinner.+ expect(store.get(githubCopilotLoadingVersion)).toBe(1);+ transport.emit({+ jsonrpc: "2.0",+ id: requests()[1].id,+ result: suggestion,+ });+ await expect(second).resolves.toEqual(suggestion);+ transport.emit({+ jsonrpc: "2.0",+ id: requests()[0].id,+ result: [{ insertText: "stale" }],+ });+ expect(store.get(githubCopilotLoadingVersion)).toBeNull();+ });++ it("suppresses a request superseded before it reaches the wire", async () => {+ const first = client.getCompletion(params);+ const second = client.getCompletion(params);+ await tick();+ expect(requests()).toHaveLength(1);+ await expect(first).resolves.toBeNull();+ transport.emit({+ jsonrpc: "2.0",+ id: requests()[0].id,+ result: suggestion,+ });+ await expect(second).resolves.toEqual(suggestion);+ });++ it("aborts on an edit before any replacement completion is requested", async () => {+ const response = client.getCompletion(params);+ await tick();+ await change("changed");+ await expect(response).resolves.toBeNull();+ expect(notifications(transport, "$/cancelRequest")).toHaveLength(1);+ expect(notifications(transport, "textDocument/didChange")).toEqual([]);+ expect(store.get(githubCopilotLoadingVersion)).toBeNull();+ });++ it.each([false, true])(+ "handles external cancellation (already sent: %s)",+ async (sent) => {+ const controller = new AbortController();+ if (!sent) {+ controller.abort();+ }+ const response = client.getCompletion(params, controller.signal);+ if (sent) {+ await tick();+ controller.abort();+ }+ await expect(response).resolves.toBeNull();+ expect(requests()).toHaveLength(sent ? 1 : 0);+ expect(notifications(transport, "$/cancelRequest")).toHaveLength(+ sent ? 1 : 0,+ );+ expect(store.get(githubCopilotLoadingVersion)).toBeNull();+ },+ );++ it.each([null, [], { items: [] }])(+ "handles empty response %j",+ async (result) => {+ const response = client.getCompletion(params);+ await tick();+ transport.emit({ jsonrpc: "2.0", id: requests()[0].id, result });+ await expect(response).resolves.toEqual(result);+ expect(store.get(githubCopilotLoadingVersion)).toBeNull();+ },+ );++ it("fails quietly on a server error and allows a subsequent request", async () => {+ const response = client.getCompletion(params);+ await tick();+ transport.emit({+ jsonrpc: "2.0",+ id: requests()[0].id,+ error: { code: -32603, message: "unavailable" },+ });+ await expect(response).resolves.toBeNull();+ const retry = client.getCompletion(params);+ await tick();+ transport.emit({+ jsonrpc: "2.0",+ id: requests()[1].id,+ result: suggestion,+ });+ await expect(retry).resolves.toEqual(suggestion);+ });++ it("cancels a timed-out request and clears its loading state", async () => {+ const response = client.getCompletion(params);+ await vi.advanceTimersByTimeAsync(10_000);+ await expect(response).resolves.toBeNull();+ expect(notifications(transport, "$/cancelRequest")).toHaveLength(1);+ expect(store.get(githubCopilotLoadingVersion)).toBeNull();+ });++ it("does not send requests while disabled or display a response after disabling", async () => {+ copilotState.isEnabled = false;+ await expect(client.getCompletion(params)).resolves.toBeNull();+ expect(requests()).toEqual([]);+ copilotState.isEnabled = true;+ const response = client.getCompletion(params);+ await tick();+ copilotState.isEnabled = false;+ transport.emit({+ jsonrpc: "2.0",+ id: requests()[0].id,+ result: suggestion,+ });+ await expect(response).resolves.toBeNull();+ });++ it("preserves pending edits after a failed document upload and retries them", async () => {+ await change("latest");+ transport.send.mockImplementationOnce(() => {+ throw new Error("socket closed");+ });+ await expect(client.getCompletion(params)).resolves.toBeNull();+ expect(requests()).toEqual([]);+ const response = client.getCompletion(params);+ await tick();+ expect(notifications(transport, "textDocument/didChange")).toEqual([+ {+ jsonrpc: "2.0",+ method: "textDocument/didChange",+ params: {+ textDocument: { uri: params.textDocument.uri, version: 2 },+ contentChanges: [{ text: "latest" }],+ },+ },+ ]);+ transport.emit({+ jsonrpc: "2.0",+ id: requests()[0].id,+ result: suggestion,+ });+ await expect(response).resolves.toEqual(suggestion);+ });++ it.each(["success", "failure"])(+ "cancels a request during a stalled reconnect before handshake %s",+ async (outcome) => {+ transport.send.mockImplementationOnce((message) => {+ transport.sent.push(message);+ });+ const reconnect = client.reInitialize().then(+ () => "ready",+ (error: unknown) => error,+ );+ const initialize = transport.sent.find(+ (message) => isRequest(message) && message.method === "initialize",+ );+ if (!initialize || !isRequest(initialize)) {+ throw new Error("Expected initialize request");+ }+ const controller = new AbortController();+ const remove = vi.spyOn(controller.signal, "removeEventListener");+ const settled = vi.fn();+ const response = client+ .getCompletion(params, controller.signal)+ .then(settled);+ await tick();+ expect(settled).not.toHaveBeenCalled();+ expect(requests()).toEqual([]);+ expect(store.get(githubCopilotLoadingVersion)).toBe(1);+ controller.abort();+ await tick();+ // Assert before answering initialize so the handshake cannot hide a stuck abort.+ expect(settled).toHaveBeenCalledExactlyOnceWith(null);+ expect(remove).toHaveBeenCalledExactlyOnceWith(+ "abort",+ expect.any(Function),+ );+ expect(store.get(githubCopilotLoadingVersion)).toBeNull();+ expect(notifications(transport, "$/cancelRequest")).toEqual([]);+ transport.emit(+ outcome === "success"+ ? {+ jsonrpc: "2.0",+ id: initialize.id,+ result: { capabilities: {} },+ }+ : {+ jsonrpc: "2.0",+ id: initialize.id,+ error: { code: -32603, message: "handshake failed" },+ },+ );+ const handshakeError = expect.objectContaining({+ message: "handshake failed",+ });+ await expect(reconnect).resolves.toEqual(+ outcome === "success" ? "ready" : handshakeError,+ );+ expect(requests()).toEqual([]);+ let retryResult: unknown;+ if (outcome === "success") {+ const retry = client.getCompletion(params);+ await tick();+ transport.emit({+ jsonrpc: "2.0",+ id: requests()[0].id,+ result: suggestion,+ });+ retryResult = await retry;+ }+ expect(requests()).toHaveLength(outcome === "success" ? 1 : 0);+ expect(retryResult).toEqual(+ outcome === "success" ? suggestion : undefined,+ );+ await response;+ expect(settled).toHaveBeenCalledTimes(1);+ },+ );++ it("replays the most recent unsent edit on reconnect", async () => {+ await change("first");+ await change("latest");+ await client.reInitialize();+ expect(notifications(transport, "textDocument/didOpen")).toEqual([+ {+ jsonrpc: "2.0",+ method: "textDocument/didOpen",+ params: {+ textDocument: {+ uri: params.textDocument.uri,+ languageId: "python",+ version: 3,+ text: "latest",+ },+ },+ },+ ]);+ expect(notifications(transport, "textDocument/didChange")).toEqual([]);+ });++ it("cancels requests and drops pending changes when the final editor closes", async () => {+ const response = client.getCompletion(params);+ await tick();+ await client.textDocumentDidClose({ textDocument: params.textDocument });+ await expect(response).resolves.toBeNull();+ await change("unsent");+ await client.textDocumentDidClose({ textDocument: params.textDocument });+ await client.flushDocumentChanges();+ expect(notifications(transport, "textDocument/didChange")).toEqual([]);+ });+ it("does not request completions for a closed document", async () => {+ await client.textDocumentDidClose({ textDocument: params.textDocument });+ await expect(client.getCompletion(params)).resolves.toBeNull();+ expect(requests()).toEqual([]);+ expect(store.get(githubCopilotLoadingVersion)).toBeNull();+ });++ it("keeps a newer edit when an earlier upload fails", async () => {+ await change("old");+ transport.send.mockImplementationOnce(() => {+ void change("new");+ throw new Error("send failed");+ });+ await expect(client.flushDocumentChanges("old")).rejects.toThrow(+ "send failed",+ );+ expect(await client.flushDocumentChanges("new")).toBe("new");+ expect(notifications(transport, "textDocument/didChange")).toEqual([+ {+ jsonrpc: "2.0",+ method: "textDocument/didChange",+ params: {+ textDocument: { uri: params.textDocument.uri, version: 3 },+ contentChanges: [{ text: "new" }],+ },+ },+ ]);+ });+});diff --git a/frontend/src/core/codemirror/copilot/__tests__/rpc-cancellation.test.ts b/frontend/src/core/codemirror/copilot/__tests__/rpc-cancellation.test.tsnew file mode 100644index 0000000000..a5e8ef8daf--- /dev/null+++ b/frontend/src/core/codemirror/copilot/__tests__/rpc-cancellation.test.ts@@ -0,0 +1,201 @@+/* Copyright 2026 Marimo. All rights reserved. */++import {+ JSONRPCClient,+ type JSONRPCMessage,+ type Transport,+} from "@marimo-team/codemirror-languageserver";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";++describe("LSP request cancellation", () => {+ let client: JSONRPCClient;+ let emit: (message: JSONRPCMessage) => void;+ let disconnect: (error: Error) => void;+ let connected: ReturnType<typeof Promise.withResolvers<undefined>>;+ let transport: Transport & {+ send: ReturnType<typeof vi.fn<(message: JSONRPCMessage) => void>>;+ };++ beforeEach(() => {+ vi.useFakeTimers();+ connected = Promise.withResolvers<undefined>();+ transport = {+ connect: () => connected.promise,+ close: vi.fn(),+ send: vi.fn<(message: JSONRPCMessage) => void>(),+ onMessage: (handler) => {+ emit = handler;+ return vi.fn();+ },+ onClose: (handler) => {+ disconnect = handler;+ return vi.fn();+ },+ };+ client = new JSONRPCClient(transport);+ });++ afterEach(() => {+ client.close();+ vi.useRealTimers();+ });++ async function connect() {+ connected.resolve(undefined);+ await vi.advanceTimersByTimeAsync(0);+ }++ it("does not send an already-aborted request", async () => {+ await connect();+ const controller = new AbortController();+ controller.abort();+ await expect(+ client.request("complete", {}, 1000, controller.signal),+ ).rejects.toMatchObject({ name: "AbortError" });+ expect(transport.send).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ });++ it("cancels while connecting without sending either request or cancellation", async () => {+ const controller = new AbortController();+ const response = client.request("complete", {}, 1000, controller.signal);+ controller.abort();+ await expect(response).rejects.toMatchObject({ name: "AbortError" });+ await connect();+ expect(transport.send).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ });++ it("rejects a failed connection and removes the waiting request's abort listener", async () => {+ const controller = new AbortController();+ const remove = vi.spyOn(controller.signal, "removeEventListener");+ const response = client.request("complete", {}, 1000, controller.signal);+ const settled = response.catch((error: unknown) => error);+ connected.reject(new Error("connection refused"));+ await expect(settled).resolves.toMatchObject({+ message: "connection refused",+ });+ expect(remove).toHaveBeenCalledExactlyOnceWith(+ "abort",+ expect.any(Function),+ );+ controller.abort();+ expect(transport.send).not.toHaveBeenCalled();+ expect(vi.getTimerCount()).toBe(0);+ });++ it("cancels exactly the matching request, ignores late replies, and leaves others active", async () => {+ await connect();+ const controller = new AbortController();+ const first = client.request(+ "complete",+ { position: 1 },+ 1000,+ controller.signal,+ );+ const second = client.request("complete", { position: 2 }, 1000);+ controller.abort();+ controller.abort();+ await expect(first).rejects.toMatchObject({ name: "AbortError" });+ emit({ jsonrpc: "2.0", id: 0, result: "stale" });+ emit({ jsonrpc: "2.0", id: 1, result: "latest" });+ await expect(second).resolves.toBe("latest");+ expect(transport.send.mock.calls).toEqual([+ [{ jsonrpc: "2.0", id: 0, method: "complete", params: { position: 1 } }],+ [{ jsonrpc: "2.0", id: 1, method: "complete", params: { position: 2 } }],+ [{ jsonrpc: "2.0", method: "$/cancelRequest", params: { id: 0 } }],+ ]);+ expect(vi.getTimerCount()).toBe(0);+ });++ it.each([+ "success",+ "error",+ "timeout",+ "disconnect",+ "close",+ "send failure",+ ])("removes the abort listener and timer after %s", async (outcome) => {+ await connect();+ const controller = new AbortController();+ const remove = vi.spyOn(controller.signal, "removeEventListener");+ if (outcome === "send failure") {+ transport.send.mockImplementationOnce(() => {+ throw new Error("send failed");+ });+ }+ const response = client.request("complete", {}, 1000, controller.signal);+ // Attach the rejection handler before advancing timers or dropping the connection.+ const settled = response.then(+ (value) => ({ status: "fulfilled", value }),+ (error: unknown) => ({ status: "rejected", error }),+ );+ if (outcome === "success") {+ emit({ jsonrpc: "2.0", id: 0, result: "ok" });+ }+ if (outcome === "error") {+ emit({+ jsonrpc: "2.0",+ id: 0,+ error: { code: -32603, message: "failed" },+ });+ }+ if (outcome === "timeout") {+ await vi.advanceTimersByTimeAsync(1000);+ }+ if (outcome === "disconnect") {+ disconnect(new Error("disconnected"));+ }+ if (outcome === "close") {+ client.close();+ }+ const expectedError = expect.any(Error);+ expect(await settled).toEqual(+ outcome === "success"+ ? { status: "fulfilled", value: "ok" }+ : { status: "rejected", error: expectedError },+ );+ expect(remove).toHaveBeenCalledExactlyOnceWith(+ "abort",+ expect.any(Function),+ );+ expect(vi.getTimerCount()).toBe(0);+ const calls = transport.send.mock.calls.length;+ controller.abort();+ expect(transport.send).toHaveBeenCalledTimes(calls);+ });++ it("sends exactly one cancellation at the timeout boundary and ignores a late reply", async () => {+ await connect();+ const controller = new AbortController();+ const settled = client+ .request("complete", {}, 1000, controller.signal)+ .catch((error: unknown) => error);+ await vi.advanceTimersByTimeAsync(999);+ expect(transport.send.mock.calls).toEqual([+ [{ jsonrpc: "2.0", id: 0, method: "complete", params: {} }],+ ]);+ await vi.advanceTimersByTimeAsync(1);+ expect(transport.send.mock.calls).toEqual([+ [{ jsonrpc: "2.0", id: 0, method: "complete", params: {} }],+ [{ jsonrpc: "2.0", method: "$/cancelRequest", params: { id: 0 } }],+ ]);+ emit({ jsonrpc: "2.0", id: 0, result: "late" });+ controller.abort();+ await expect(settled).resolves.toMatchObject({ code: -32001 });+ expect(transport.send).toHaveBeenCalledTimes(2);+ expect(vi.getTimerCount()).toBe(0);+ });++ it("settles cancellation even if sending the cancellation notification fails", async () => {+ await connect();+ const controller = new AbortController();+ const response = client.request("complete", {}, 1000, controller.signal);+ transport.send.mockImplementationOnce(() => {+ throw new Error("connection gone");+ });+ controller.abort();+ await expect(response).rejects.toMatchObject({ name: "AbortError" });+ expect(vi.getTimerCount()).toBe(0);+ });+});diff --git a/frontend/src/core/codemirror/copilot/extension.ts b/frontend/src/core/codemirror/copilot/extension.tsindex 658218bc54..90cde91be4 100644--- a/frontend/src/core/codemirror/copilot/extension.ts+++ b/frontend/src/core/codemirror/copilot/extension.ts@@ -39,7 +39,7 @@ const copilotCompartment = new Compartment();const logger = Logger.get("@github/copilot-language-server");const commonInlineCompletionConfig = {- delay: 300, // default is 500ms+ delay: 150,includeKeymap: true,events: {// Only show suggestions when the editor is focused@@ -79,7 +79,7 @@ export const copilotBundle = (config: CompletionConfig): Extension => {extensions.push(inlineCompletion({...commonInlineCompletionConfig,- fetchFn: async (state, _abortSignal, view) => {+ fetchFn: async (state, signal, view) => {const currentPosition = state.selection.main.head;if (!isCopilotEnabled()) {return "";@@ -94,16 +94,22 @@ export const copilotBundle = (config: CompletionConfig): Extension => {return "";}- // wait 20ms so that the view is updated first- await new Promise((resolve) => setTimeout(resolve, 20));-- const currentCode = state.doc.toString();- const allCode = getCodes(currentCode);+ const client = getCopilotClient();+ const allCode = await client.flushDocumentChanges(+ state.doc.toString(),+ );+ if (signal.aborted || state.doc !== view.state.doc) {+ return "";+ }const request = getCopilotRequest(state, allCode);- const response = await getCopilotClient().getCompletion(request);+ const response = await client.getCompletion(request, signal);// If we are at a new position, ignore the response- if (currentPosition !== view.state.selection.main.head) {+ if (+ signal.aborted ||+ state.doc !== view.state.doc ||+ currentPosition !== view.state.selection.main.head+ ) {Logger.debug("ignoring response because of new position");return "";}@@ -119,7 +125,7 @@ export const copilotBundle = (config: CompletionConfig): Extension => {extensions.push(inlineCompletion({...commonInlineCompletionConfig,- fetchFn: async (state, _abortSignal, view) => {+ fetchFn: async (state, signal, view) => {const currentPosition = state.selection.main.head;if (state.doc.length === 0) {@@ -146,10 +152,15 @@ export const copilotBundle = (config: CompletionConfig): Extension => {let res = await API.post<AiInlineCompletionRequest, string>("/ai/inline_completion",{ prefix, suffix, language },+ { signal },);// If we are at a new position, ignore the response- if (currentPosition !== view.state.selection.main.head) {+ if (+ signal.aborted ||+ state.doc !== view.state.doc ||+ currentPosition !== view.state.selection.main.head+ ) {Logger.debug("ignoring response because of new position");return "";}diff --git a/frontend/src/core/codemirror/copilot/language-server.ts b/frontend/src/core/codemirror/copilot/language-server.tsindex 11e80c36cd..5c47c3e32d 100644--- a/frontend/src/core/codemirror/copilot/language-server.ts+++ b/frontend/src/core/codemirror/copilot/language-server.ts@@ -1,7 +1,6 @@/* Copyright 2026 Marimo. All rights reserved. */import { LanguageServerClient } from "@marimo-team/codemirror-languageserver";-import { throttle } from "lodash-es";import type {CompletionItem,CompletionList,@@ -58,6 +57,7 @@ interface UntypedLanguageServerMethods {method: string,params: unknown,timeout: number,+ signal?: AbortSignal,) => Promise<unknown>;notify: (method: string, params: unknown) => Promise<void>;}@@ -113,6 +113,8 @@ function isLogMessageParams(*/export class CopilotLanguageServerClient extends LanguageServerClient {private documentVersion = 0;+ private pendingChange: DidChangeTextDocumentParams | undefined;+ private completionController: AbortController | undefined;private openDocumentCount = 0;private lastOpenedDocument: DidOpenTextDocumentParams | undefined;private copilotSettings: Record<string, unknown> = {};@@ -142,9 +144,11 @@ export class CopilotLanguageServerClient extends LanguageServerClient {*/public async reInitialize(): Promise<void> {logger.log("#reInitialize: Re-initializing LSP connection");+ this.completionController?.abort();this.initializePromise = this.initialize();await this.initializePromise;await this.sendConfiguration();+ this.applyPendingChange();if (this.openDocumentCount > 0 && this.lastOpenedDocument) {await this.sendNotification("textDocument/didOpen",@@ -168,12 +172,14 @@ export class CopilotLanguageServerClient extends LanguageServerClient {private async _request<Method extends keyof LSPRequestMap>(method: Method,params: LSPRequestMap[Method][0],+ signal?: AbortSignal,): Promise<LSPRequestMap[Method][1]> {assertHasLanguageServerRpc(this);return (await this.request(method,params,REQUEST_TIMEOUT_MS,+ signal,)) as LSPRequestMap[Method][1];}@@ -230,6 +236,10 @@ export class CopilotLanguageServerClient extends LanguageServerClient {return;}this.openDocumentCount--;+ if (this.openDocumentCount === 0) {+ this.pendingChange = undefined;+ this.completionController?.abort();+ }return super.textDocumentDidClose(params);}@@ -281,27 +291,72 @@ export class CopilotLanguageServerClient extends LanguageServerClient {);}- const text = getCodes(change.text);- const version = ++this.documentVersion;- // `reInitialize` replays this as a didOpen, so keep the original languageId+ this.completionController?.abort();+ this.pendingChange = {+ ...params,+ textDocument: VersionedTextDocumentIdentifier.create(+ params.textDocument.uri,+ ++this.documentVersion,+ ),+ };+ }++ private applyPendingChange(+ assembledText?: string,+ ): DidChangeTextDocumentParams | undefined {+ const pending = this.pendingChange;+ if (!pending) {+ return;+ }+ this.pendingChange = undefined;+ const text = assembledText ?? getCodes(pending.contentChanges[0].text);this.lastOpenedDocument = {textDocument: {- uri: params.textDocument.uri,+ ...pending.textDocument,languageId:this.lastOpenedDocument?.textDocument.languageId ??DEFAULT_LANGUAGE_ID,- version,text,},};- return super.textDocumentDidChange({- ...params,- contentChanges: [{ text: text }],- textDocument: VersionedTextDocumentIdentifier.create(- params.textDocument.uri,- version,- ),- });+ return { ...pending, contentChanges: [{ text }] };+ }++ /** Assemble and send the latest notebook once, just before requesting a suggestion. */+ public async flushDocumentChanges(currentCode?: string): Promise<string> {+ // Another cell may have changed since the focused editor last typed.+ // The focused cell must be last in the shared document for cursor mapping.+ const assembledText =+ currentCode !== undefined && this.lastOpenedDocument+ ? getCodes(currentCode)+ : undefined;+ if (+ currentCode !== undefined &&+ this.lastOpenedDocument &&+ (this.pendingChange+ ? this.pendingChange.contentChanges[0].text !== currentCode+ : assembledText !== this.lastOpenedDocument.textDocument.text)+ ) {+ this.pendingChange = {+ textDocument: VersionedTextDocumentIdentifier.create(+ this.lastOpenedDocument.textDocument.uri,+ ++this.documentVersion,+ ),+ contentChanges: [{ text: currentCode }],+ };+ }+ const pending = this.pendingChange;+ const change = this.applyPendingChange(assembledText);+ if (change) {+ try {+ await super.textDocumentDidChange(change);+ } catch (error) {+ // Preserve newer edits if the send failed while another change arrived.+ this.pendingChange ??= pending;+ throw error;+ }+ }+ return this.lastOpenedDocument?.textDocument.text ?? "";}public override textDocumentHover(params: HoverParams): Promise<Hover> {@@ -351,49 +406,32 @@ export class CopilotLanguageServerClient extends LanguageServerClient {}}- private getCompletionInternal = async (- params: InlineCompletionParams,- version: number,- ): Promise<InlineCompletionList | InlineCompletionItem[] | null> => {- return await this._request("textDocument/inlineCompletion", {- ...params,- textDocument: {- ...VersionedTextDocumentIdentifier.create(- params.textDocument.uri,- version,- ),- },- });- };-- // Even though the copilot extension has a debounce,- // there are multiple requests sent at the same time- // when multiple Codemirror instances are mounted at the same time.- // So we throttle it to ignore multiple requests at the same time.- private throttledGetCompletionInternal = throttle(- this.getCompletionInternal,- 200,- );-public async getCompletion(params: InlineCompletionParams,+ signal?: AbortSignal,): Promise<InlineCompletionList | InlineCompletionItem[] | null> {- if (this.isDisabled()) {+ if (this.isDisabled() || signal?.aborted || this.openDocumentCount === 0) {return null;}+ this.completionController?.abort();+ const controller = new AbortController();+ this.completionController = controller;+ const abort = () => controller.abort();+ signal?.addEventListener("abort", abort, { once: true });const requestVersion = this.documentVersion;-- // If version is 0, it means the document hasn't been opened yet- if (requestVersion === 0) {- return null;- }-- // Start a loading indicatorsetGitHubCopilotLoadingVersion(requestVersion);- let response: InlineCompletionList | InlineCompletionItem[] | null;try {- response = await this.throttledGetCompletionInternal(+ await this.flushDocumentChanges();+ if (+ controller.signal.aborted ||+ this.isDisabled() ||+ requestVersion === 0+ ) {+ return null;+ }+ const response = await this._request(+ "textDocument/inlineCompletion",{...params,textDocument: VersionedTextDocumentIdentifier.create(@@ -401,24 +439,35 @@ export class CopilotLanguageServerClient extends LanguageServerClient {requestVersion,),},- requestVersion,+ controller.signal,);+ if (+ controller.signal.aborted ||+ this.isDisabled() ||+ requestVersion !== this.documentVersion+ ) {+ return null;+ }+ return response;} catch (error) {- // A suggestion that times out should fail quietly rather than surface as- // an unhandled rejection out of the inline-completion fetcher.- logger.warn("#getCompletion: Failed to fetch completions", error);+ if (!controller.signal.aborted) {+ logger.warn("#getCompletion: Failed to fetch completions", error);+ }return null;} finally {- // Stop the loading indicator (only if the version hasn't changed)- clearGitHubCopilotLoadingVersion(requestVersion);- }-- // If the document version has changed since the request was made, return an empty response- if (requestVersion !== this.documentVersion) {- return null;+ signal?.removeEventListener("abort", abort);+ // A superseded request can have the same document version as its successor.+ if (this.completionController === controller) {+ this.completionController = undefined;+ clearGitHubCopilotLoadingVersion(requestVersion);+ }}+ }- return response ?? null;+ public override close(): void {+ this.pendingChange = undefined;+ this.completionController?.abort();+ super.close();}/**diff --git a/frontend/src/core/network/__tests__/api.test.ts b/frontend/src/core/network/__tests__/api.test.tsindex 011e4d8268..c0d4ad8c30 100644--- a/frontend/src/core/network/__tests__/api.test.ts+++ b/frontend/src/core/network/__tests__/api.test.ts@@ -1,7 +1,8 @@/* Copyright 2026 Marimo. All rights reserved. */-import { beforeEach, describe, expect, it, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import { HTTPError } from "@/utils/errors";+import { Logger } from "@/utils/Logger";import { API } from "../api";// Mock fetch globally@@ -25,6 +26,118 @@ describe("API", () => {baseUrl = "http://localhost:8000";});+ afterEach(() => {+ vi.restoreAllMocks();+ });++ it.each(["before fetch", "during fetch"])(+ "API.post propagates cancellation %s without logging it",+ async (timing) => {+ const log = vi.spyOn(Logger, "error").mockReturnValue(undefined);+ const controller = new AbortController();+ mockFetch.mockImplementation(+ (_url: string, { signal }: RequestInit) =>+ new Promise<Response>((_resolve, reject) => {+ if (signal?.aborted) {+ reject(signal.reason);+ } else {+ signal?.addEventListener("abort", () => reject(signal.reason), {+ once: true,+ });+ }+ }),+ );+ if (timing === "before fetch") {+ controller.abort();+ }++ const response = API.post("/foo", {}, { signal: controller.signal });+ controller.abort();++ await expect(response).rejects.toBe(controller.signal.reason);+ expect(mockFetch).toHaveBeenCalledWith(+ "http://localhost:8000/api/foo",+ expect.objectContaining({ signal: controller.signal }),+ );+ expect(log).not.toHaveBeenCalled();+ },+ );++ it.each(["application/json", "text/plain"])(+ "API.post propagates an abort while reading %s without logging it",+ async (contentType) => {+ const log = vi.spyOn(Logger, "error").mockReturnValue(undefined);+ const error = new DOMException("Body read aborted", "AbortError");+ const readBody = vi.fn().mockRejectedValue(error);+ mockFetch.mockResolvedValue({+ ok: true,+ headers: new Headers({ "Content-Type": contentType }),+ json: readBody,+ text: readBody,+ });++ await expect(API.post("/foo", {})).rejects.toBe(error);+ expect(readBody).toHaveBeenCalledExactlyOnceWith();+ expect(log).not.toHaveBeenCalled();+ },+ );++ it.each([new TypeError("Failed to fetch"), null, "Request failed"])(+ "API.post logs and preserves non-abort fetch failures: %s",+ async (error) => {+ const log = vi.spyOn(Logger, "error").mockReturnValue(undefined);+ const controller = new AbortController();+ controller.abort();+ mockFetch.mockRejectedValue(error);++ await expect(+ API.post("/foo", {}, { signal: controller.signal }),+ ).rejects.toBe(error);+ expect(log).toHaveBeenCalledExactlyOnceWith(+ "Error requesting http://localhost:8000/api/foo",+ error,+ );+ },+ );++ it("API.post logs HTTP failures and preserves their status and body", async () => {+ const log = vi.spyOn(Logger, "error").mockReturnValue(undefined);+ const body = { detail: "Service unavailable" };+ mockFetch.mockResolvedValue(+ new Response(JSON.stringify(body), {+ status: 503,+ statusText: "Service Unavailable",+ headers: { "Content-Type": "application/json" },+ }),+ );++ await expect(API.post("/foo", {})).rejects.toMatchObject({+ name: "HTTPError",+ status: 503,+ message: "Service Unavailable",+ cause: body,+ });+ expect(log).toHaveBeenCalledExactlyOnceWith(+ "Error requesting http://localhost:8000/api/foo",+ expect.any(HTTPError),+ );+ });++ it("API.post logs malformed JSON responses", async () => {+ const log = vi.spyOn(Logger, "error").mockReturnValue(undefined);+ mockFetch.mockResolvedValue(+ new Response("invalid json", {+ headers: { "Content-Type": "application/json" },+ }),+ );++ await expect(API.post("/foo", {})).rejects.toBeInstanceOf(SyntaxError);+ expect(log).toHaveBeenCalledExactlyOnceWith(+ "Error requesting http://localhost:8000/api/foo",+ expect.any(SyntaxError),+ );+ });+it("API.post calls fetch with POST and correct URL", async () => {mockFetch.mockResolvedValue({ok: true,diff --git a/frontend/src/core/network/api.ts b/frontend/src/core/network/api.tsindex 2ae6fc0054..828599e181 100644--- a/frontend/src/core/network/api.ts+++ b/frontend/src/core/network/api.ts@@ -101,8 +101,9 @@ export const API = {return response.text() as unknown as RESP;}).catch((error) => {- // Catch and rethrow- Logger.error(`Error requesting ${fullUrl}`, error);+ if (error?.name !== "AbortError") {+ Logger.error(`Error requesting ${fullUrl}`, error);+ }throw error;});},diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex b466977f3c..9366fd7174 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -132,11 +132,11 @@ importers:specifier: ^1.1.19version: 1.1.19'@marimo-team/codemirror-ai':- specifier: ^0.3.9- version: 0.3.9(@codemirror/[email protected])(@codemirror/[email protected])+ specifier: ^0.3.10+ version: 0.3.10(@codemirror/[email protected])(@codemirror/[email protected])'@marimo-team/codemirror-languageserver':- specifier: ^2.0.0- version: 2.0.0(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])+ specifier: ^2.0.1+ version: 2.0.1(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])'@marimo-team/codemirror-mcp':specifier: ^0.1.7version: 0.1.7(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@modelcontextprotocol/[email protected])@@ -1609,14 +1609,14 @@ packages:'@marijn/[email protected]':resolution: {integrity: sha512-FY+MKLBoTsLNJF/eLWaOsXGdz6uh3Iu1axjPf6TUq92IYumcTcXWHoS747JARLkcdlJ/Waiaxc5wQfFO8jC6NA==}- '@marimo-team/[email protected]':- resolution: {integrity: sha512-XfEzR1jhA1eznCmFyaslvGpENcZ7EJjsxx+PZyHTn8l9FNER+S/jldpmv+dDMOT232L9kgGP2MZEdi5iiNfAsA==}+ '@marimo-team/[email protected]':+ resolution: {integrity: sha512-icDL6oROFp3MaK6/oE5UrDxcq1jWrU8Vji0GgLjZGwO4p1a9s/8kayiUmI4A9Tiepo5X+teZHPCWG7q0nNQgOA==}peerDependencies:'@codemirror/state': ^6'@codemirror/view': ^6- '@marimo-team/[email protected]':- resolution: {integrity: sha512-ch/jeSnyfufQsycttZk/wmqQ5MSz1Ofe9iP1Lye4eJMSd0zUcDthqHnUWxPqyV4HMK3ns6bIS8pKQYQ7VkiauA==}+ '@marimo-team/[email protected]':+ resolution: {integrity: sha512-MwT+AyUSHs2ChUBTIgtqc8lM2oKvt+S+kgGRFsN+KhnboPEi2fgpoF+3taBnzf7EjjlmizKZ9CjUFs9dV5zA4A==}peerDependencies:'@codemirror/autocomplete': ^6'@codemirror/lint': ^6@@ -10392,13 +10392,13 @@ snapshots:'@marijn/[email protected]': {}dependencies:'@codemirror/state': 6.7.6'@codemirror/view': 6.43.13diff: 8.0.2- '@marimo-team/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':+ '@marimo-team/[email protected](@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])(@codemirror/[email protected])':dependencies:'@codemirror/autocomplete': 6.20.3'@codemirror/lint': 6.9.7