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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 28 additions & 15 deletions nodejs/src/client.ts
Original file line number Diff line number Diff line change
Expand Up @@ -232,6 +232,8 @@ export class CopilotClient {
* Parse CLI URL into host and port
* Supports formats: "host:port", "http://host:port", "https://host:port", or just "port"
*/
private startPromise: Promise<void> | null = null;

private parseCliUrl(url: string): { host: string; port: number } {
// Remove protocol if present
let cleanUrl = url.replace(/^https?:\/\//, "");
Expand Down Expand Up @@ -282,25 +284,34 @@ export class CopilotClient {
return;
}

this.state = "connecting";
if (this.startPromise) {
return this.startPromise;
}
Comment on lines 284 to +289
Copy link

Copilot AI Mar 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

start() now returns a Promise in some branches but returns nothing in the early-return path shown here. If start() is no longer declared async, callers doing await client.start() may not reliably await anything. Consider ensuring start() is declared async (so return; becomes Promise<void>), or return a resolved promise in the early-return path (e.g., return this.startPromise ?? Promise.resolve();) to keep the return type consistent.

Copilot uses AI. Check for mistakes.

try {
// Only start CLI server process if not connecting to external server
if (!this.isExternalServer) {
await this.startCLIServer();
}
this.startPromise = (async () => {
this.state = "connecting";

try {
Comment on lines +291 to +294
Copy link

Copilot AI Mar 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

startPromise is cleared on error and on explicit stop/cleanup, but it is never cleared on a successful start. Keeping a resolved promise around works, but it can become a stale gate if any other code path later transitions the client back to "disconnected" without also clearing startPromise. Consider limiting startPromise to only represent an in-flight start (e.g., set it back to null in a finally after the connection attempt completes successfully), relying on this.state === "connected" for the fast-path afterward.

Copilot uses AI. Check for mistakes.
// Only start CLI server process if not connecting to external server
if (!this.isExternalServer) {
await this.startCLIServer();
}

// Connect to the server
await this.connectToServer();
// Connect to the server
await this.connectToServer();

// Verify protocol version compatibility
await this.verifyProtocolVersion();
// Verify protocol version compatibility
await this.verifyProtocolVersion();

this.state = "connected";
} catch (error) {
this.state = "error";
throw error;
}
this.state = "connected";
} catch (error) {
this.state = "error";
this.startPromise = null;
throw error;
}
})();

return this.startPromise;
Comment on lines +306 to +314
Copy link

Copilot AI Mar 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

startPromise is cleared on error and on explicit stop/cleanup, but it is never cleared on a successful start. Keeping a resolved promise around works, but it can become a stale gate if any other code path later transitions the client back to "disconnected" without also clearing startPromise. Consider limiting startPromise to only represent an in-flight start (e.g., set it back to null in a finally after the connection attempt completes successfully), relying on this.state === "connected" for the fast-path afterward.

Copilot uses AI. Check for mistakes.
}

/**
Expand Down Expand Up @@ -403,6 +414,7 @@ export class CopilotClient {
}

this.state = "disconnected";
this.startPromise = null;
this.actualPort = null;
this.stderrBuffer = "";
this.processExitPromise = null;
Expand Down Expand Up @@ -475,6 +487,7 @@ export class CopilotClient {
}

this.state = "disconnected";
this.startPromise = null;
this.actualPort = null;
this.stderrBuffer = "";
this.processExitPromise = null;
Expand Down
6 changes: 1 addition & 5 deletions nodejs/test/e2e/session.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,11 +130,7 @@ describe("Sessions", async () => {
expect(functionNames).not.toContain("view");
});

// TODO: This test shows there's a race condition inside client.ts. If createSession is called
// concurrently and autoStart is on, it may start multiple child processes. This needs to be fixed.
// Right now it manifests as being unable to delete the temp directories during afterAll even though
// we stopped all the clients (one or more child processes were left orphaned).
it.skip("should handle multiple concurrent sessions", async () => {
it("should handle multiple concurrent sessions", async () => {
const [s1, s2, s3] = await Promise.all([
client.createSession({ onPermissionRequest: approveAll }),
client.createSession({ onPermissionRequest: approveAll }),
Expand Down
64 changes: 33 additions & 31 deletions python/copilot/client.py
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ def __init__(self, options: CopilotClientOptions | None = None):
self._process: subprocess.Popen | None = None
self._client: JsonRpcClient | None = None
self._state: ConnectionState = "disconnected"
self._start_lock = asyncio.Lock()
self._sessions: dict[str, CopilotSession] = {}
self._sessions_lock = threading.Lock()
self._models_cache: list[ModelInfo] | None = None
Expand Down Expand Up @@ -281,39 +282,40 @@ async def start(self) -> None:
>>> await client.start()
>>> # Now ready to create sessions
"""
if self._state == "connected":
return
async with self._start_lock:
Comment on lines 284 to +285
Copy link

Copilot AI Mar 5, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This acquires/awaits the lock even when already connected (the common steady-state). A small optimization is to add a fast-path check before entering the lock, and keep the check inside the lock as well (double-checked locking pattern) to preserve correctness while avoiding unnecessary lock contention/awaits.

Suggested change
"""
if self._state == "connected":
return
async with self._start_lock:
"""
# Fast-path: avoid acquiring the start lock if we're already connected.
if self._state == "connected":
return
async with self._start_lock:
# Double-check under the lock to ensure correctness with concurrent callers.

Copilot uses AI. Check for mistakes.
if self._state == "connected":
return

self._state = "connecting"
self._state = "connecting"

try:
# Only start CLI server process if not connecting to external server
if not self._is_external_server:
await self._start_cli_server()

# Connect to the server
await self._connect_to_server()

# Verify protocol version compatibility
await self._verify_protocol_version()

self._state = "connected"
except ProcessExitedError as e:
# Process exited with error - reraise as RuntimeError with stderr
self._state = "error"
raise RuntimeError(str(e)) from None
except Exception as e:
self._state = "error"
# Check if process exited and capture any remaining stderr
if self._process and hasattr(self._process, "poll"):
return_code = self._process.poll()
if return_code is not None and self._client:
stderr_output = self._client.get_stderr_output()
if stderr_output:
raise RuntimeError(
f"CLI process exited with code {return_code}\nstderr: {stderr_output}"
) from e
raise
try:
# Only start CLI server process if not connecting to external server
if not self._is_external_server:
await self._start_cli_server()

# Connect to the server
await self._connect_to_server()

# Verify protocol version compatibility
await self._verify_protocol_version()

self._state = "connected"
except ProcessExitedError as e:
# Process exited with error - reraise as RuntimeError with stderr
self._state = "error"
raise RuntimeError(str(e)) from None
except Exception as e:
self._state = "error"
# Check if process exited and capture any remaining stderr
if self._process and hasattr(self._process, "poll"):
return_code = self._process.poll()
if return_code is not None and self._client:
stderr_output = self._client.get_stderr_output()
if stderr_output:
raise RuntimeError(
f"CLI process exited with code {return_code}\nstderr: {stderr_output}"
) from e
raise

async def stop(self) -> None:
"""
Expand Down
5 changes: 0 additions & 5 deletions python/e2e/test_session.py
Original file line number Diff line number Diff line change
Expand Up @@ -123,11 +123,6 @@ async def test_should_create_a_session_with_excludedTools(self, ctx: E2ETestCont
assert "grep" in tool_names
assert "view" not in tool_names

# TODO: This test shows there's a race condition inside client.ts. If createSession
# is called concurrently and autoStart is on, it may start multiple child processes.
# This needs to be fixed. Right now it manifests as being unable to delete the temp
# directories during afterAll even though we stopped all the clients.
@pytest.mark.skip(reason="Known race condition - see TypeScript test")
async def test_should_handle_multiple_concurrent_sessions(self, ctx: E2ETestContext):
import asyncio

Expand Down
Loading