Skip to content

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

fix: trim copilot prefix and suffix based on the response position and existing code (#2239)

Myles Scolnickdea52ac0d47e
diff --git a/frontend/src/core/codemirror/copilot/__tests__/copilot.test.ts b/frontend/src/core/codemirror/copilot/__tests__/copilot.test.ts
new file mode 100644
index 0000000000..523977bad0
--- /dev/null
+++ b/frontend/src/core/codemirror/copilot/__tests__/copilot.test.ts
@@ -0,0 +1,261 @@
+/* Copyright 2024 Marimo. All rights reserved. */
+import { describe, it, expect } from "vitest";
+import { exportedForTesting } from "../extension";
+import { EditorView } from "@codemirror/view";
+import type { CopilotGetCompletionsResult } from "../types";
+
+const { getCopilotRequest, getSuggestion } = exportedForTesting;
+
+const OTHER_CODE = "import numpy as np\nimport pandas as pd";
+
+describe("getCopilotRequest", () => {
+ it("empty document", () => {
+ const view = new EditorView({
+ doc: "",
+ extensions: [],
+ });
+ const state = view.state;
+ const allCode = state.doc.toString();
+ const result = getCopilotRequest(state, allCode);
+
+ expect(result.doc.source).toMatchInlineSnapshot(`""`);
+ expect(result.doc.position).toMatchInlineSnapshot(`
+ {
+ "character": 0,
+ "line": 0,
+ }
+ `);
+ });
+
+ it("should create a correct request object - with no code other code, at the beginning", () => {
+ const view = new EditorView({
+ doc: "x = 1\ny =",
+ extensions: [],
+ });
+ const state = view.state;
+ const allCode = state.doc.toString();
+ const result = getCopilotRequest(state, allCode);
+
+ expect(result.doc.source).toMatchInlineSnapshot(`
+ "x = 1
+ y ="
+ `);
+ expect(result.doc.position).toMatchInlineSnapshot(`
+ {
+ "character": 0,
+ "line": 0,
+ }
+ `);
+ });
+
+ it("should create a correct request object - with no code other code, at the end", () => {
+ const view = new EditorView({
+ doc: "x = 1\ny =",
+ extensions: [],
+ });
+ // Move cursor to the end of the document
+ view.dispatch({
+ selection: { anchor: view.state.doc.length },
+ });
+ const state = view.state;
+ const allCode = state.doc.toString();
+ const result = getCopilotRequest(state, allCode);
+
+ expect(result.doc.source).toMatchInlineSnapshot(`
+ "x = 1
+ y ="
+ `);
+ expect(result.doc.position).toMatchInlineSnapshot(`
+ {
+ "character": 3,
+ "line": 1,
+ }
+ `);
+ });
+
+ it("should create a correct request object - when other code, at the beginning", () => {
+ const view = new EditorView({
+ doc: "x = 1\ny =",
+ extensions: [],
+ });
+ const state = view.state;
+ const allCode = `${OTHER_CODE}\n${state.doc.toString()}`;
+ const result = getCopilotRequest(state, allCode);
+
+ expect(result.doc.source).toMatchInlineSnapshot(`
+ "import numpy as np
+ import pandas as pd
+ x = 1
+ y ="
+ `);
+ expect(result.doc.position).toMatchInlineSnapshot(`
+ {
+ "character": 0,
+ "line": 2,
+ }
+ `);
+ });
+
+ it("should create a correct request object - when other code, at the end", () => {
+ const view = new EditorView({
+ doc: "x = 1\ny =",
+ extensions: [],
+ });
+ // Move cursor to the end of the document
+ view.dispatch({
+ selection: { anchor: view.state.doc.length },
+ });
+ const state = view.state;
+ const allCode = `${OTHER_CODE}\n${state.doc.toString()}`;
+ const result = getCopilotRequest(state, allCode);
+
+ expect(result.doc.source).toMatchInlineSnapshot(`
+ "import numpy as np
+ import pandas as pd
+ x = 1
+ y ="
+ `);
+ expect(result.doc.position).toMatchInlineSnapshot(`
+ {
+ "character": 3,
+ "line": 3,
+ }
+ `);
+ });
+});
+
+describe("getSuggestion", () => {
+ it("should return an empty string for empty completions", () => {
+ const view = new EditorView({
+ doc: "mo",
+ extensions: [],
+ });
+ const response = { completions: [] };
+ const position = { line: 0, character: 0 };
+
+ const result = getSuggestion(response, position, view.state);
+
+ expect(result).toBe("");
+ });
+
+ it("should not trim when startOffset is zero - at the beginning of the line", () => {
+ const view = new EditorView({
+ doc: "mo",
+ extensions: [],
+ });
+ const response = {
+ completions: [
+ {
+ displayText: "mo.ui.table(",
+ position: { line: 0, character: 0 },
+ },
+ ],
+ } as CopilotGetCompletionsResult;
+
+ // We are 2 characters into the line
+ const position = { line: 0, character: 0 };
+ const result = getSuggestion(response, position, view.state);
+
+ expect(result).toBe("mo.ui.table(");
+ });
+
+ it("should not trim when startOffset is zero - in the middle", () => {
+ const view = new EditorView({
+ doc: "mo",
+ extensions: [],
+ });
+ const response = {
+ completions: [
+ {
+ displayText: ".ui.table(",
+ position: { line: 0, character: 2 },
+ },
+ ],
+ } as CopilotGetCompletionsResult;
+
+ // We are 2 characters into the line
+ const position = { line: 0, character: 2 };
+ const result = getSuggestion(response, position, view.state);
+
+ expect(result).toBe(".ui.table(");
+ });
+
+ it("should trim the beginning of displayText when startOffset is negative", () => {
+ const view = new EditorView({
+ doc: "mo",
+ extensions: [],
+ });
+ const response = {
+ completions: [
+ {
+ displayText: "mo.ui.table(",
+ position: { line: 0, character: 0 },
+ },
+ ],
+ } as CopilotGetCompletionsResult;
+
+ // We are 2 characters into the line
+ const position = { line: 0, character: 2 };
+ const result = getSuggestion(response, position, view.state);
+
+ expect(result).toBe(".ui.table(");
+ });
+
+ it("should trim end of displayText when it matches the next characters - on the same line", () => {
+ const view = new EditorView({
+ doc: "print('hello') # comment",
+ // Cursor ------- ^
+ extensions: [],
+ });
+ // Set the cursor to just after the print('hello
+ view.dispatch({
+ selection: { anchor: 12 },
+ });
+ const response = {
+ completions: [
+ {
+ displayText: " world')",
+ position: { line: 0, character: 12 },
+ },
+ ],
+ } as CopilotGetCompletionsResult;
+
+ // We are 2 characters into the line
+ const position = { line: 0, character: 12 };
+ const result = getSuggestion(response, position, view.state);
+
+ // If should just be ` world` since we already have a trailing `')`
+ expect(result).toBe(" world");
+ });
+
+ it("should trim end of displayText when it matches the next characters - on the next line", () => {
+ const view = new EditorView({
+ doc: `mo.md("""\nhello\n""")`,
+ // Cursor ----------- ^
+ extensions: [],
+ });
+
+ // Set the cursor to just after the `hello`
+ view.dispatch({
+ selection: { anchor: 15 },
+ });
+ const textUpToCursor = view.state.doc.sliceString(0, 15);
+ expect(textUpToCursor).toBe(`mo.md("""\nhello`);
+
+ const response = {
+ completions: [
+ {
+ displayText: `hello world\n""")`,
+ position: { line: 1, character: 0 },
+ },
+ ],
+ } as CopilotGetCompletionsResult;
+
+ // We are 5 characters into the line (past the hello)
+ const position = { line: 1, character: 5 };
+ const result = getSuggestion(response, position, view.state);
+
+ // If should just be `world` since we already have a trailing `""")`
+ expect(result).toBe(" world");
+ });
+});
diff --git a/frontend/src/core/codemirror/copilot/extension.ts b/frontend/src/core/codemirror/copilot/extension.ts
index fa448c062c..c6443ed3ea 100644
--- a/frontend/src/core/codemirror/copilot/extension.ts
+++ b/frontend/src/core/codemirror/copilot/extension.ts
@@ -1,5 +1,5 @@
/* Copyright 2024 Marimo. All rights reserved. */
-import type { Extension, Text } from "@codemirror/state";
+import type { EditorState, Extension, Text } from "@codemirror/state";
import {
COPILOT_FILENAME,
LANGUAGE_ID,
@@ -15,6 +15,10 @@ import {
import { isCopilotEnabled } from "./state";
import { getCodes } from "./getCodes";
import type { CompletionConfig } from "@/core/config/config-schema";
+import type {
+ CopilotGetCompletionsParams,
+ CopilotGetCompletionsResult,
+} from "./types";
import { Logger } from "@/utils/Logger";
export const copilotBundle = (config: CompletionConfig): Extension => {
@@ -48,47 +52,31 @@ export const copilotBundle = (config: CompletionConfig): Extension => {
extensions.push(
inlineSuggestion({
delay: 200, // default is 500ms
- fetchFn: async (view) => {
+ fetchFn: async (state) => {
if (!isCopilotEnabled()) {
return "";
}
// If no text, don't fetch
- if (view.doc.length === 0) {
+ if (state.doc.length === 0) {
return "";
}
- // wait 10ms so that the view is updated first
- await new Promise((resolve) => setTimeout(resolve, 10));
+ // wait 20ms so that the view is updated first
+ await new Promise((resolve) => setTimeout(resolve, 20));
- // We need to update the position of the cursor because added newlines
- // from appending the other code
- const currentCode = view.doc.toString();
+ const currentCode = state.doc.toString();
const allCode = getCodes(currentCode);
- const numberOfNewLines =
- allCode.split("\n").length - currentCode.split("\n").length;
-
- const position = offsetToPos(view.doc, view.selection.main.head);
- position.line += numberOfNewLines;
-
- Logger.debug(`Copilot: ${position.line} ${position.character}`);
- const response = await getCopilotClient().getCompletion({
- doc: {
- source: allCode,
- tabSize: view.tabSize,
- indentSize: 1,
- insertSpaces: true,
- path: COPILOT_FILENAME,
- version: 0,
- uri: `file://${COPILOT_FILENAME}`,
- relativePath: COPILOT_FILENAME,
- languageId: LANGUAGE_ID,
- position: position,
- },
- });
- Logger.debug(`Copilot: ${JSON.stringify(response)}`);
+ const request = getCopilotRequest(state, allCode);
+ const response = await getCopilotClient().getCompletion(request);
- return response.completions.map((c) => c.displayText)[0] ?? "";
+ const suggestion = getSuggestion(
+ response,
+ request.doc.position,
+ state,
+ );
+ Logger.debug("Copilot suggestion:", suggestion);
+ return suggestion;
},
}),
);
@@ -101,6 +89,92 @@ export const copilotBundle = (config: CompletionConfig): Extension => {
];
};
+function getCopilotRequest(
+ state: EditorState,
+ allCode: string,
+): CopilotGetCompletionsParams {
+ // We need to update the position of the cursor because added newlines
+ // from appending the other code
+ const currentCode = state.doc.toString();
+ const numberOfNewLines =
+ allCode.split("\n").length - currentCode.split("\n").length;
+
+ const position = offsetToPos(state.doc, state.selection.main.head);
+ position.line += numberOfNewLines;
+
+ return {
+ doc: {
+ source: allCode,
+ tabSize: state.tabSize,
+ indentSize: 1,
+ insertSpaces: true,
+ path: COPILOT_FILENAME,
+ version: 0,
+ uri: `file://${COPILOT_FILENAME}`,
+ relativePath: COPILOT_FILENAME,
+ languageId: LANGUAGE_ID,
+ position: position,
+ },
+ };
+}
+
+function getSuggestion(
+ response: CopilotGetCompletionsResult,
+ userPosition: CopilotGetCompletionsParams["doc"]["position"],
+ state: EditorState,
+): string {
+ // Empty (can happen if it is a stale request)
+ if (response.completions.length === 0) {
+ return "";
+ }
+
+ const { displayText, position: completionPosition } = response.completions[0];
+
+ // Calculate the start of the suggestion relative to the current position
+ const startOffset = completionPosition.character - userPosition.character;
+
+ // If startOffset is negative, we need to trim the beginning of displayText
+ const trimmedDisplayText =
+ startOffset < 0 ? displayText.slice(-startOffset) : displayText;
+
+ // If startOffset is positive, we need to prepend spaces
+ const resultText =
+ startOffset > 0
+ ? " ".repeat(startOffset) + trimmedDisplayText
+ : trimmedDisplayText;
+
+ // If the end of the suggestion already exists next in the document, we should trim it,
+ // for example closing quotes, brackets, etc.
+ // e.g
+ // current content: print("hello|")
+ // position ^
+ // suggestion: world")
+ // we need to remove the closing ") since we already have it
+ //
+ // See https://github.com/marimo-team/marimo/issues/830
+
+ // Loop through from the whole word to the end of the suggestion
+ // if we find a match, we trim it off the end of the suggestion
+ const remainingText = state.doc.sliceString(
+ state.selection.main.head,
+ state.doc.length,
+ );
+
+ for (let i = 0; i < resultText.length; i++) {
+ const remainingResultText = resultText.slice(i);
+ if (remainingText.startsWith(remainingResultText)) {
+ return resultText.slice(0, i);
+ }
+ }
+
+ return resultText;
+}
+
+export const exportedForTesting = {
+ getCopilotRequest,
+ getSuggestion,
+};
+
function offsetToPos(doc: Text, offset: number) {
const line = doc.lineAt(offset);
return {
diff --git a/frontend/src/core/codemirror/copilot/language-server.ts b/frontend/src/core/codemirror/copilot/language-server.ts
index f3bddb07d1..b61f759eca 100644
--- a/frontend/src/core/codemirror/copilot/language-server.ts
+++ b/frontend/src/core/codemirror/copilot/language-server.ts
@@ -135,11 +135,18 @@ export class CopilotLanguageServerClient extends LanguageServerClient {
const version = this.documentVersion;
- return this._request("getCompletions", {
+ const response = await this._request("getCompletions", {
doc: {
...params.doc,
version: version,
},
});
+
+ // If the document version has changed since the request was made, return an empty response
+ if (version !== this.documentVersion) {
+ return { completions: [] };
+ }
+
+ return response;
}
}