Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(opencode): stop tool commands too when vibe stop falls back to the server pid (#2325)

Call White21fb3c3aba33
diff --git a/modules/agents/opencode/server.py b/modules/agents/opencode/server.py
index 7b4ba1be9..85d6f0695 100644
--- a/modules/agents/opencode/server.py
+++ b/modules/agents/opencode/server.py
@@ -1748,6 +1748,12 @@ class OpenCodeServerManager:
groups[process] = os.getpgid(process.pid)
except OSError:
continue
+ # The caller's own group is the one carrying out this stop: ``vibe
+ # stop`` run from an OpenCode tool sits inside the tree. It is never
+ # signalled, nor waited for, so the stop can finish its own work.
+ tree = [process for process in tree if groups.get(process) != own_group]
+ if not tree:
+ return True
# A group is the tree's when a process of the tree founded it. It is
# signalled only while a live process of the tree is still in it,
# proof that its id was not recycled, and the group signal also
diff --git a/tests/test_desktop_runtime_stop.py b/tests/test_desktop_runtime_stop.py
index 5aa726556..b70653198 100644
--- a/tests/test_desktop_runtime_stop.py
+++ b/tests/test_desktop_runtime_stop.py
@@ -158,6 +158,14 @@ def stop_env(monkeypatch):
monkeypatch.setattr(os, "kill", recording_kill)
monkeypatch.setattr(runtime, "stop_pid", lambda pid, timeout=5: effects["stop_pid"].append(pid) or False)
+ # The OpenCode server is stopped with its tool tree; record that stop the same way.
+ from modules.agents.opencode.server import OpenCodeServerManager
+
+ monkeypatch.setattr(
+ OpenCodeServerManager,
+ "_terminate_pid_tree_sync",
+ staticmethod(lambda pid, timeout=5.0: effects["stop_pid"].append(pid) or False),
+ )
monkeypatch.setattr(remote_access, "stop", lambda: effects["remote_access"].append(True) or {"ok": True})
# The full stop reaps the installers of this process's own Runtime id,
# which here would be the host's; the scoped stop reaps those of its id.
diff --git a/tests/test_opencode_server.py b/tests/test_opencode_server.py
index 78597755c..6aa91d0cc 100644
--- a/tests/test_opencode_server.py
+++ b/tests/test_opencode_server.py
@@ -9,6 +9,7 @@ import subprocess
import sys
import tempfile
import threading
+import time
import types
import unittest
from contextlib import suppress
@@ -3293,6 +3294,59 @@ def test_stopping_the_server_stops_tool_commands_in_their_own_session(tmp_path):
server.stdout.close()
+# A server whose tools run in their own sessions, as OpenCode's do: one keeps
+# working, the other stops the server from inside the tree, as `vibe stop` run
+# from an OpenCode shell tool does.
+_SERVER_WITH_STOPPING_TOOL = """
+import os, subprocess, sys
+marker, done = sys.argv[1], sys.argv[2]
+worker = subprocess.Popen(["/bin/sh", "-c", "while :; do sleep 1; done", "tool", marker], start_new_session=True)
+print(worker.pid, flush=True)
+stopper = (
+ "import sys\\n"
+ "from modules.agents.opencode.server import OpenCodeServerManager\\n"
+ "stopped = OpenCodeServerManager._terminate_pid_tree_sync(int(sys.argv[1]), timeout=2.0)\\n"
+ "open(sys.argv[2], 'w').write(str(stopped))\\n"
+)
+subprocess.Popen([sys.executable, "-c", stopper, str(os.getpid()), done, marker], start_new_session=True)
+worker.wait()
+"""
+
+
[email protected](os.name == "nt", reason="POSIX sessions and process groups")
+def test_a_stop_run_from_inside_the_tree_survives_to_finish_it(tmp_path):
+ # Every tree member outside the caller's group was signalled one by one, so
+ # a stop running inside the tree killed itself before it finished.
+ done = tmp_path / "stop-finished"
+ server = subprocess.Popen(
+ [sys.executable, "-c", _SERVER_WITH_STOPPING_TOOL, str(tmp_path / "marker"), str(done)],
+ stdout=subprocess.PIPE,
+ text=True,
+ start_new_session=True,
+ cwd=Path(__file__).resolve().parents[1],
+ )
+ worker_pid = None
+ try:
+ worker_pid = int(server.stdout.readline())
+ worker = psutil.Process(worker_pid)
+ threading.Thread(target=server.wait, daemon=True).start()
+ deadline = time.monotonic() + 20
+ while not done.exists() and time.monotonic() < deadline:
+ time.sleep(0.1)
+
+ assert done.read_text() == "True"
+ assert _exited(worker)
+ assert server.wait(timeout=5) == -signal.SIGTERM
+ finally:
+ if worker_pid is not None:
+ with suppress(ProcessLookupError):
+ os.killpg(worker_pid, signal.SIGKILL)
+ if server.poll() is None:
+ server.kill()
+ server.wait(timeout=5)
+ server.stdout.close()
+
+
def test_mh_runtime_002_matching_overlay_does_not_wait_for_an_unrelated_active_run():
"""MH-RUNTIME-002: unchanged direct mode cannot head-of-line block another Session."""
diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.py
index 67ae1355c..516ff188f 100644
--- a/tests/test_vibe_cli.py
+++ b/tests/test_vibe_cli.py
@@ -1011,12 +1011,72 @@ def test_cli_stop_opencode_server_uses_runtime_helpers(tmp_path, monkeypatch):
monkeypatch.setattr(paths, "get_logs_dir", lambda: tmp_path)
monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 321)
monkeypatch.setattr(runtime, "get_process_command", lambda pid: "C:\\opencode.exe serve --port=4096")
- monkeypatch.setattr(runtime, "stop_pid", lambda pid, timeout=5: pid == 321)
+ from modules.agents.opencode.server import OpenCodeServerManager
+
+ monkeypatch.setattr(OpenCodeServerManager, "_terminate_pid_tree_sync", staticmethod(lambda pid, timeout=5: pid == 321))
assert cli._stop_opencode_server() is True
assert not pid_file.exists()
+# A server that starts its tool the way OpenCode's shell tool does (detached, so
+# setsid): the tool leads its own session, out of reach of a signal to the server.
+# The tool names the test's tmp_path, which keeps the orphan it becomes on master
+# signalable for cleanup under the test signal guard.
+_SERVER_WITH_DETACHED_TOOL = """
+import subprocess, sys
+tool = subprocess.Popen(["/bin/sh", "-c", "while :; do sleep 1; done", "tool", sys.argv[1]], start_new_session=True)
+print(tool.pid, flush=True)
+tool.wait()
+"""
+
+
[email protected](os.name == "nt", reason="POSIX sessions and process groups")
+def test_cli_stop_fallback_stops_tool_commands_with_the_opencode_server(tmp_path, monkeypatch):
+ # `vibe stop` and /api/control fall back to this path when the service's
+ # own teardown did not stop OpenCode. Stopping only the server pid left the
+ # running tool command behind, still executing after the stop.
+ import psutil
+
+ server = subprocess.Popen(
+ [sys.executable, "-c", _SERVER_WITH_DETACHED_TOOL, str(tmp_path)],
+ stdout=subprocess.PIPE,
+ text=True,
+ start_new_session=True,
+ )
+ tool_pid = None
+ try:
+ tool_pid = int(server.stdout.readline())
+ tool = psutil.Process(tool_pid)
+ assert os.getsid(tool_pid) == tool_pid != os.getsid(server.pid)
+ # Reap the server when it exits, as its real parent would.
+ threading.Thread(target=server.wait, daemon=True).start()
+ pid_file = tmp_path / "opencode_server.json"
+ pid_file.write_text(json.dumps({"pid": server.pid}), encoding="utf-8")
+ monkeypatch.setattr(paths, "get_logs_dir", lambda: tmp_path)
+ monkeypatch.setattr(
+ runtime,
+ "get_process_command",
+ lambda pid: "opencode serve --hostname=127.0.0.1 --port=4096" if pid == server.pid else "",
+ )
+
+ assert cli._stop_opencode_server() is True
+
+ assert not pid_file.exists()
+ try:
+ assert not tool.is_running() or tool.status() == psutil.STATUS_ZOMBIE
+ except psutil.NoSuchProcess:
+ pass
+ finally:
+ if tool_pid is not None:
+ with contextlib.suppress(ProcessLookupError):
+ os.killpg(tool_pid, signal.SIGKILL)
+ if server.poll() is None:
+ server.kill()
+ server.wait(timeout=5)
+ server.stdout.close()
+
+
def test_proc_cmdline_decode_preserves_argv_boundaries():
command = runtime._decode_proc_cmdline(b"/tmp/Vibe Tools/cloudflared\x00tunnel\x00run\x00")
diff --git a/vibe/cli.py b/vibe/cli.py
index 9344fd05f..66837f501 100644
--- a/vibe/cli.py
+++ b/vibe/cli.py
@@ -13903,7 +13903,12 @@ def _stop_opencode_server(runtime_ids: frozenset[str] = frozenset()):
logger.warning("Leaving the OpenCode server pid=%s running: %s", pid, refusal)
return False
- if runtime.stop_pid(pid, timeout=5):
+ # OpenCode starts each tool command in its own session, so stopping only
+ # the server pid would leave a running command behind. Stop the whole tree
+ # the way the service's own teardown does.
+ from modules.agents.opencode.server import OpenCodeServerManager
+
+ if OpenCodeServerManager._terminate_pid_tree_sync(pid, timeout=5):
pid_file.unlink(missing_ok=True)
return True
logger.warning("Failed to stop OpenCode server (pid=%s)", pid)