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.

Improve Copilot Integration (#3484)

devin-ai-integration[bot]9d5c97b181b9
diff --git a/.github/workflows/test_cli.yaml b/.github/workflows/test_cli.yaml
index 0ac2596200..004b55755f 100644
--- a/.github/workflows/test_cli.yaml
+++ b/.github/workflows/test_cli.yaml
@@ -31,7 +31,7 @@ jobs:
if: ${{ needs.changes.outputs.cli == 'true' }}
name: Build marimo wheel
runs-on: ubuntu-latest
- timeout-minutes: 3 # 2024-01-18 avg: 0.8m max: 1.0m
+ timeout-minutes: 8 # 2024-01-18
defaults:
run:
shell: bash
diff --git a/frontend/src/__tests__/setup.ts b/frontend/src/__tests__/setup.ts
index 4b3c5e88b2..83ffae4acd 100644
--- a/frontend/src/__tests__/setup.ts
+++ b/frontend/src/__tests__/setup.ts
@@ -1,4 +1,9 @@
/* Copyright 2024 Marimo. All rights reserved. */
-
-// Required for testing ser/deser of blobs
+import { afterEach } from "vitest";
+import { cleanup } from "@testing-library/react";
import "blob-polyfill";
+
+// Cleanup after each test case (e.g., clearing jsdom)
+afterEach(() => {
+ cleanup();
+});
diff --git a/frontend/src/components/editor/chrome/wrapper/copilot-status.tsx b/frontend/src/components/editor/chrome/wrapper/copilot-status.tsx
index e7ed23deac..279c82bb9d 100644
--- a/frontend/src/components/editor/chrome/wrapper/copilot-status.tsx
+++ b/frontend/src/components/editor/chrome/wrapper/copilot-status.tsx
@@ -5,6 +5,7 @@ import { Spinner } from "@/components/icons/spinner";
import {
isGitHubCopilotSignedInState,
githubCopilotLoadingVersion,
+ copilotSignedInState,
} from "@/core/codemirror/copilot/state";
import { atom, useAtomValue, useSetAtom } from "jotai";
import { aiEnabledAtom, resolvedMarimoConfigAtom } from "@/core/config/config";
@@ -13,7 +14,11 @@ import { SparklesIcon } from "lucide-react";
import { FooterItem } from "./footer-item";
import { activeUserConfigCategoryAtom } from "@/components/app-config/user-config-form";
import { settingDialogAtom } from "@/components/app-config/app-config-button";
-
+import { toast } from "@/components/ui/use-toast";
+import { getCopilotClient } from "@/core/codemirror/copilot/client";
+import { Logger } from "@/utils/Logger";
+import { Button } from "@/components/ui/button";
+import { useOnMount } from "@/hooks/useLifecycle";
export const AIStatusIcon: React.FC = () => {
const ai = useAtomValue(aiAtom);
const aiEnabled = useAtomValue(aiEnabledAtom);
@@ -82,6 +87,61 @@ const GitHubCopilotStatus: React.FC = () => {
const { handleClick } = useOpenAISettings();
const label = isGitHubCopilotSignedIn ? "Ready" : "Not connected";
+ const setCopilotSignedIn = useSetAtom(isGitHubCopilotSignedInState);
+ const setStep = useSetAtom(copilotSignedInState);
+
+ // Check connection on mount
+ useOnMount(() => {
+ const client = getCopilotClient();
+ let mounted = true;
+
+ const checkConnection = async () => {
+ try {
+ // If we fail to initialize, show connection error
+ await client.initializePromise.catch((error) => {
+ Logger.error("Copilot#checkConnection: Failed to initialize", error);
+ client.close();
+ throw error;
+ });
+
+ if (!mounted) {
+ return;
+ }
+
+ const signedIn = await client.signedIn();
+ if (!mounted) {
+ return;
+ }
+
+ setCopilotSignedIn(signedIn);
+ setStep(signedIn ? "signedIn" : "signedOut");
+ } catch (error) {
+ if (!mounted) {
+ return;
+ }
+ Logger.warn("Copilot#checkConnection: Connection failed", error);
+ setCopilotSignedIn(false);
+ setStep("connectionError");
+ toast({
+ title: "GitHub Copilot Connection Error",
+ description:
+ "Failed to connect to GitHub Copilot. Check settings and try again.",
+ variant: "danger",
+ action: (
+ <Button variant="link" onClick={handleClick}>
+ Settings
+ </Button>
+ ),
+ });
+ }
+ };
+
+ checkConnection();
+
+ return () => {
+ mounted = false;
+ };
+ });
return (
<FooterItem
diff --git a/frontend/src/core/codemirror/copilot/client.ts b/frontend/src/core/codemirror/copilot/client.ts
index 5755c0f004..54c2dd4d78 100644
--- a/frontend/src/core/codemirror/copilot/client.ts
+++ b/frontend/src/core/codemirror/copilot/client.ts
@@ -8,6 +8,8 @@ import type { JSONRPCRequestData } from "@open-rpc/client-js/build/Request";
import { waitForEnabledCopilot } from "./state";
import { waitForWs } from "@/utils/waitForWs";
import { resolveToWsUrl } from "@/core/websocket/createWsUrl";
+import { Logger } from "@/utils/Logger";
+import { toast } from "@/components/ui/use-toast";
// Dummy file for the copilot language server
export const COPILOT_FILENAME = "/marimo.py";
@@ -25,35 +27,65 @@ export const createWSTransport = once(() => {
*/
class LazyWebsocketTransport extends Transport {
private delegate: WebSocketTransport | undefined;
+ private readonly WS_URL = resolveToWsUrl("lsp/copilot");
constructor() {
super();
this.delegate = undefined;
}
+ private async tryConnect(retries = 3, delayMs = 1000): Promise<void> {
+ for (let attempt = 1; attempt <= retries; attempt++) {
+ try {
+ // Create delegate, if it doesn't exist
+ if (!this.delegate) {
+ this.delegate = new WebSocketTransport(this.WS_URL);
+ }
+ await this.delegate.connect();
+ Logger.log("Copilot#connect: Connected successfully");
+ return;
+ } catch (error) {
+ Logger.warn(
+ `Copilot#connect: Connection attempt ${attempt}/${retries} failed`,
+ error,
+ );
+ if (attempt === retries) {
+ this.delegate = undefined;
+ // Show error toast on final retry
+ toast({
+ variant: "danger",
+ title: "GitHub Copilot Connection Error",
+ description:
+ "Failed to connect to GitHub Copilot. Please check settings and try again.",
+ });
+ throw error;
+ }
+ await new Promise((resolve) => setTimeout(resolve, delayMs));
+ }
+ }
+ }
+
override async connect() {
// Wait for copilot to be enabled
await waitForEnabledCopilot();
- // Wait for ws to be available
- await waitForWs(createWsUrl(), 3);
-
- // Create delegate, if it doesn't exist
- if (!this.delegate) {
- this.delegate = new WebSocketTransport(createWsUrl());
- }
+ // Wait for ws to be available with retries
+ await waitForWs(this.WS_URL, 3);
- // Connect
- return this.delegate.connect();
+ // Try connecting with retries
+ return this.tryConnect();
}
override close() {
this.delegate?.close();
+ this.delegate = undefined;
}
override async sendData(
data: JSONRPCRequestData,
- timeout?: number | null | undefined,
+ timeout: number | null | undefined,
) {
+ // Clamp timeout to 5 seconds
+ timeout = Math.min(timeout ?? 5000, 5000);
return this.delegate?.sendData(data, timeout);
}
}
@@ -79,7 +111,3 @@ export function copilotServer() {
languageId: LANGUAGE_ID,
});
}
-
-export function createWsUrl(): string {
- return resolveToWsUrl("lsp/copilot");
-}
diff --git a/frontend/src/core/codemirror/copilot/copilot-config.tsx b/frontend/src/core/codemirror/copilot/copilot-config.tsx
index 3494aedb51..13f7c044da 100644
--- a/frontend/src/core/codemirror/copilot/copilot-config.tsx
+++ b/frontend/src/core/codemirror/copilot/copilot-config.tsx
@@ -1,52 +1,25 @@
/* Copyright 2024 Marimo. All rights reserved. */
import { useAtom } from "jotai";
-import { isGitHubCopilotSignedInState } from "./state";
-import { memo, useEffect, useState } from "react";
+import { copilotSignedInState, isGitHubCopilotSignedInState } from "./state";
+import { memo, useState } from "react";
import { getCopilotClient } from "./client";
import { Button, buttonVariants } from "@/components/ui/button";
+import { useOpenAISettings } from "@/components/editor/chrome/wrapper/copilot-status";
import { CheckIcon, CopyIcon, Loader2Icon, XIcon } from "lucide-react";
import { Label } from "@/components/ui/label";
import { toast } from "@/components/ui/use-toast";
import { copyToClipboard } from "@/utils/copy";
-
-type Step =
- | "signedIn"
- | "signingIn"
- | "signInFailed"
- | "signedOut"
- | "connecting"
- | "notConnected";
+import { Logger } from "@/utils/Logger";
export const CopilotConfig = memo(() => {
const [copilotSignedIn, copilotChangeSignIn] = useAtom(
isGitHubCopilotSignedInState,
);
- const [step, setStep] = useState<Step>();
-
+ const [step, setStep] = useAtom(copilotSignedInState);
+ const { handleClick: openSettings } = useOpenAISettings();
const [localData, setLocalData] = useState<{ url: string; code: string }>();
const [loading, setLoading] = useState(false);
- // Check connection on mount
- useEffect(() => {
- const client = getCopilotClient();
- // If we fail to initialize, show not connected
- client.initializePromise.catch(() => {
- copilotChangeSignIn(false);
- setStep("notConnected");
- });
- client
- .signedIn()
- .then((signedIn) => {
- copilotChangeSignIn(signedIn);
- setStep(signedIn ? "signedIn" : "signedOut");
- })
- .catch(() => {
- copilotChangeSignIn(false);
- setStep("notConnected");
- });
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, []);
-
const trySignIn = async (evt: React.MouseEvent) => {
evt.preventDefault();
setLoading(true);
@@ -72,31 +45,96 @@ export const CopilotConfig = memo(() => {
return;
}
const client = getCopilotClient();
+ const MAX_RETRIES = 3;
+ const RETRY_DELAY_MS = 1000;
+
try {
setLoading(true);
+ Logger.log("Copilot#tryFinishSignIn: Attempting to confirm sign-in");
const { status } = await client.signInConfirm({
userCode: localData.code,
});
if (status === "OK" || status === "AlreadySignedIn") {
+ Logger.log("Copilot#tryFinishSignIn: Sign-in confirmed successfully");
copilotChangeSignIn(true);
setStep("signedIn");
} else {
+ Logger.warn(
+ "Copilot#tryFinishSignIn: Sign-in confirmation returned unexpected status",
+ { status },
+ );
setStep("signInFailed");
}
- } catch {
- // If request failed, try seeing if we're already signed in
- // otherwise, show the error
- // We try 3 times, waiting 1 second between each try
- for (let i = 0; i < 3; i++) {
- await new Promise((resolve) => setTimeout(resolve, 1000));
- const signedIn = await client.signedIn();
- if (signedIn) {
- copilotChangeSignIn(true);
- setStep("signedIn");
- return;
+ } catch (error) {
+ Logger.warn(
+ "Copilot#tryFinishSignIn: Initial sign-in confirmation failed, attempting retries",
+ );
+
+ // Check if it's a connection error
+ if (
+ error instanceof Error &&
+ (error.message.includes("ECONNREFUSED") ||
+ error.message.includes("WebSocket") ||
+ error.message.includes("network"))
+ ) {
+ Logger.error(
+ "Copilot#tryFinishSignIn: Connection error during sign-in",
+ error,
+ );
+ setStep("connectionError");
+ toast({
+ title: "GitHub Copilot Connection Error",
+ description: "Lost connection during sign-in. Please try again.",
+ variant: "danger",
+ action: <Button onClick={trySignIn}>Retry</Button>,
+ });
+ return;
+ }
+
+ // If not a connection error, try seeing if we're already signed in
+ // We try multiple times with a delay between attempts
+ for (let i = 0; i < MAX_RETRIES; i++) {
+ try {
+ await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY_MS));
+ const signedIn = await client.signedIn();
+ if (signedIn) {
+ Logger.log(
+ "Copilot#tryFinishSignIn: Successfully signed in after retry",
+ );
+ copilotChangeSignIn(true);
+ setStep("signedIn");
+ return;
+ }
+ } catch (retryError) {
+ Logger.warn("Copilot#tryFinishSignIn: Retry attempt failed", {
+ attempt: i + 1,
+ maxRetries: MAX_RETRIES,
+ });
+ // Check for connection errors during retry
+ if (
+ retryError instanceof Error &&
+ (retryError.message.includes("ECONNREFUSED") ||
+ retryError.message.includes("WebSocket") ||
+ retryError.message.includes("network"))
+ ) {
+ setStep("connectionError");
+ toast({
+ title: "GitHub Copilot Connection Error",
+ description:
+ "Lost connection during sign-in. Please check settings and try again.",
+ variant: "danger",
+ action: (
+ <Button variant="link" onClick={openSettings}>
+ Settings
+ </Button>
+ ),
+ });
+ return;
+ }
}
}
+ Logger.error("Copilot#tryFinishSignIn: All sign-in attempts failed");
setStep("signInFailed");
} finally {
setLoading(false);
@@ -200,6 +238,20 @@ export const CopilotConfig = memo(() => {
</div>
);
+ case "connectionError":
+ return (
+ <div className="flex flex-col gap-1">
+ <Label className="font-normal flex">
+ <XIcon className="h-4 w-4 mr-1" />
+ Connection Error
+ </Label>
+ <div className="text-sm">Unable to connect to GitHub Copilot.</div>
+ <Button onClick={trySignIn} size="xs" variant="link">
+ Retry Connection
+ </Button>
+ </div>
+ );
+
case "notConnected":
return (
<div className="flex flex-col gap-1">
diff --git a/frontend/src/core/codemirror/copilot/language-server.ts b/frontend/src/core/codemirror/copilot/language-server.ts
index de23458d52..c33f98be4a 100644
--- a/frontend/src/core/codemirror/copilot/language-server.ts
+++ b/frontend/src/core/codemirror/copilot/language-server.ts
@@ -50,12 +50,17 @@ export interface LSPRequestMap {
export class CopilotLanguageServerClient extends LanguageServerClient {
private documentVersion = 0;
- private _request<Method extends keyof LSPRequestMap>(
+ private async _request<Method extends keyof LSPRequestMap>(
method: Method,
params: LSPRequestMap[Method][0],
): Promise<LSPRequestMap[Method][1]> {
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- return (this as any).request(method, params);
+ try {
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
+ return await (this as any).request(method, params);
+ } catch (error) {
+ Logger.error("CopilotLanguageServerClient#request: Error", error);
+ throw error;
+ }
}
private isDisabled() {
@@ -108,20 +113,44 @@ export class CopilotLanguageServerClient extends LanguageServerClient {
return this._request("signOut", {});
}
- signInInitiate() {
- return this._request("signInInitiate", {});
+ async signInInitiate() {
+ Logger.log("Copilot#signInInitiate: Starting sign-in flow");
+ try {
+ const result = await this._request("signInInitiate", {});
+ Logger.log("Copilot#signInInitiate: Sign-in flow started successfully");
+ return result;
+ } catch (error) {
+ Logger.warn(
+ "Copilot#signInInitiate: Failed to start sign-in flow",
+ error,
+ );
+ throw error;
+ }
}
- signInConfirm(params: CopilotSignInConfirmParams) {
- return this._request("signInConfirm", params);
+ async signInConfirm(params: CopilotSignInConfirmParams) {
+ Logger.log("Copilot#signInConfirm: Confirming sign-in");
+ try {
+ const result = await this._request("signInConfirm", params);
+ Logger.log("Copilot#signInConfirm: Sign-in confirmed successfully");
+ return result;
+ } catch (error) {
+ Logger.warn("Copilot#signInConfirm: Failed to confirm sign-in", error);
+ throw error;
+ }
}
async signedIn() {
- const { status, user } = await this._request("checkStatus", {});
- Logger.debug("Copilot#signedIn", status, user);
- return (
- status === "SignedIn" || status === "AlreadySignedIn" || status === "OK"
- );
+ try {
+ const { status } = await this._request("checkStatus", {});
+ Logger.log("Copilot#signedIn: Status check completed", { status });
+ return (
+ status === "SignedIn" || status === "AlreadySignedIn" || status === "OK"
+ );
+ } catch (error) {
+ Logger.warn("Copilot#signedIn: Failed to check sign-in status", error);
+ throw error;
+ }
}
// COMPLETIONS
diff --git a/frontend/src/core/codemirror/copilot/state.ts b/frontend/src/core/codemirror/copilot/state.ts
index aa61cfcc68..aa7b224456 100644
--- a/frontend/src/core/codemirror/copilot/state.ts
+++ b/frontend/src/core/codemirror/copilot/state.ts
@@ -18,6 +18,17 @@ export const isGitHubCopilotSignedInState = atomWithStorage<boolean | null>(
},
);
+type Step =
+ | "signedIn"
+ | "signingIn"
+ | "signInFailed"
+ | "signedOut"
+ | "connecting"
+ | "connectionError"
+ | "notConnected";
+
+export const copilotSignedInState = atom<Step | null>(null);
+
export const githubCopilotLoadingVersion = atom<number | null>(null);
/**
diff --git a/frontend/src/plugins/impl/__tests__/NumberPlugin.test.tsx b/frontend/src/plugins/impl/__tests__/NumberPlugin.test.tsx
index a38a893585..e5c23fffeb 100644
--- a/frontend/src/plugins/impl/__tests__/NumberPlugin.test.tsx
+++ b/frontend/src/plugins/impl/__tests__/NumberPlugin.test.tsx
@@ -85,7 +85,7 @@ describe("NumberPlugin", () => {
};
// Initial render - setValue should be called immediately with initial value
- const { getAllByRole, rerender } = render(plugin.render(props));
+ const { getByRole, rerender } = render(plugin.render(props));
// Wait for React-Aria NumberField to initialize
act(() => {
@@ -97,10 +97,9 @@ describe("NumberPlugin", () => {
// Clear the mock to test debounced user input
setValue.mockClear();
- const allInputs = getAllByRole("textbox", {
+ const input = getByRole("textbox", {
name: "Number input",
- });
- const input = allInputs[1];
+ }) as HTMLInputElement;
expect(input).toBeTruthy();
// Simulate user typing and committing the value