The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(acp): give each CopilotACPClient session its own process slot
Devin5983dfe72d08
diff --git a/agent/copilot_acp_client.py b/agent/copilot_acp_client.pyindex 4c6641b7755..39e4e197e64 100644--- a/agent/copilot_acp_client.py+++ b/agent/copilot_acp_client.py@@ -288,21 +288,40 @@ class CopilotACPClient:self._acp_args = list(acp_args or args or _resolve_args())self._acp_cwd = str(Path(acp_cwd or os.getcwd()).resolve())self.chat = SimpleNamespace(completions=SimpleNamespace(create=self._create_chat_completion))- self.is_closed, self._active_process = False, None+ self.is_closed = False+ # Clients are cached and shared across concurrent callers (auxiliary tasks, async+ # dispatch), so several ACP sessions can be live on one instance. Track every live+ # child — a single slot would let one session's teardown kill a sibling's process+ # while its own leaked.+ self._active_processes: set[subprocess.Popen[str]] = set()self._active_process_lock = threading.Lock()- def close(self) -> None:- with self._active_process_lock:- proc, self._active_process = self._active_process, None- self.is_closed = True+ @staticmethod+ def _terminate_process(proc: subprocess.Popen[str]) -> None:try:- if proc is not None:- proc.terminate()- proc.wait(timeout=2)+ proc.terminate()+ proc.wait(timeout=2)except Exception:with contextlib.suppress(Exception):proc.kill()+ def _release_process(self, proc: subprocess.Popen[str]) -> None:+ """Reap one session's own child. ``is_closed`` flips only when the last live+ session drains — marking it while siblings still run would tell lifecycle code+ to rebuild a client that is mid-request."""+ with self._active_process_lock:+ self._active_processes.discard(proc)+ if not self._active_processes:+ self.is_closed = True+ self._terminate_process(proc)++ def close(self) -> None:+ with self._active_process_lock:+ procs, self._active_processes = tuple(self._active_processes), set()+ self.is_closed = True+ for proc in procs:+ self._terminate_process(proc)+def _create_chat_completion(self, *, model: str | None = None, messages: list[dict[str, Any]] | None = None, timeout: float | None = None,tools: list[dict[str, Any]] | None = None, tool_choice: Any = None, stream: bool = False, **_: Any,@@ -348,9 +367,9 @@ class CopilotACPClient:if proc.stdin is None or proc.stdout is None:proc.kill()raise RuntimeError("Copilot ACP process did not expose stdin/stdout pipes.")- self.is_closed = Falsewith self._active_process_lock:- self._active_process = proc+ self._active_processes.add(proc)+ self.is_closed = Falsereturn proc@contextlib.contextmanager@@ -413,7 +432,7 @@ class CopilotACPClient:raise RuntimeError("Copilot ACP did not return a sessionId.")yield session, _requestfinally:- self.close()+ self._release_process(proc)def list_models(self, *, timeout_seconds: float = 15.0) -> list[str]:"""Return the enabled models advertised by a short-lived authenticated ACP session."""diff --git a/tests/agent/test_copilot_acp_client.py b/tests/agent/test_copilot_acp_client.pyindex 4220d143310..1831494f3fd 100644--- a/tests/agent/test_copilot_acp_client.py+++ b/tests/agent/test_copilot_acp_client.py@@ -491,3 +491,121 @@ print(json.dumps({{"jsonrpc": "2.0", "id": session["id"], "result": {{"sessionId)assert client.list_models(timeout_seconds=30) == ["gpt-5.6-sol"]+++# --- concurrent sessions on a shared client ---------------------------------+#+# Aux clients are cached per provider config and served to every concurrent+# caller, so one CopilotACPClient can run several ACP sessions at once. Each+# session must reap ITS OWN child on exit: reaping whatever most recently+# claimed shared state kills a sibling's live process and leaks the session's+# own.+++_FAKE_ACP_SERVER = """import json+import sys+import time++for line in sys.stdin:+ request = json.loads(line)+ method = request.get("method")+ if method == "initialize":+ result = {"protocolVersion": 1}+ elif method == "session/new":+ result = {"sessionId": "s1"}+ elif method == "session/prompt":+ time.sleep(0.4)+ print(json.dumps({"jsonrpc": "2.0", "method": "session/update", "params": {+ "update": {"sessionUpdate": "agent_message_chunk", "content": {"text": "done"}},+ }}), flush=True)+ result = {"stopReason": "end_turn"}+ else:+ result = {}+ print(json.dumps({"jsonrpc": "2.0", "id": request["id"], "result": result}), flush=True)+"""+++def _recording_client(tmp_path, spawned):+ server = tmp_path / "fake_copilot_acp.py"+ server.write_text(_FAKE_ACP_SERVER, encoding="utf-8")+ client = CopilotACPClient(command=sys.executable, args=[str(server)], acp_cwd=str(tmp_path))+ real_spawn = client._spawn++ def record_spawn():+ proc = real_spawn()+ spawned.append(proc)+ return proc++ client._spawn = record_spawn+ return client+++def test_overlapping_sessions_reap_their_own_process(tmp_path):+ spawned = []+ client = _recording_client(tmp_path, spawned)++ session_a = client._session(30)+ session_b = client._session(30)+ session_a.__enter__()+ session_b.__enter__()++ proc_a, proc_b = spawned+ session_a.__exit__(None, None, None)++ leaked = proc_a.poll() is None+ killed = proc_b.poll() is not None+ assert not leaked and not killed, (+ f"session A teardown: own child leaked={leaked}, sibling process killed={killed}"+ )++ session_b.__exit__(None, None, None)+ assert proc_b.poll() is not None+++def test_close_terminates_every_live_session_process(tmp_path):+ spawned = []+ client = _recording_client(tmp_path, spawned)++ session_a = client._session(30)+ session_b = client._session(30)+ session_a.__enter__()+ session_b.__enter__()++ client.close()++ assert all(proc.poll() is not None for proc in spawned)+++def test_concurrent_completions_both_succeed_and_reap(tmp_path):+ import threading++ spawned = []+ client = _recording_client(tmp_path, spawned)+ gate = threading.Barrier(2)+ record_spawn = client._spawn++ def gated_spawn():+ proc = record_spawn()+ gate.wait(timeout=10)+ return proc++ client._spawn = gated_spawn+ errors = []++ def call():+ try:+ client._create_chat_completion(+ model="copilot-acp", messages=[{"role": "user", "content": "hi"}]+ )+ except Exception as exc:+ errors.append(exc)++ threads = [threading.Thread(target=call) for _ in range(2)]+ for thread in threads:+ thread.start()+ for thread in threads:+ thread.join(timeout=30)++ assert not errors+ assert len(spawned) == 2+ assert all(proc.poll() is not None for proc in spawned), "spawned child leaked"