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.
Python agentagent-osaiai-agentsai-partnerchatopsclaudeclaude-codecodexdevtoolsdiscord-botlark-botllmlocal-firstlong-term-memoryopencodeslack-botvibe-codingvibeywechat
fix(runtime): read command lines through psutil, so a restart cannot orphan the Web UI (#2487)
Call White999e2ab87e41
diff --git a/tests/test_runtime_process_scan.py b/tests/test_runtime_process_scan.pyindex 1cbf44e30..28152df9e 100644--- a/tests/test_runtime_process_scan.py+++ b/tests/test_runtime_process_scan.py@@ -14,6 +14,7 @@ invisible. On Windows it was a ``powershell`` launch, and that is whyimport osimport secrets+import shleximport subprocessimport sysimport threading@@ -84,30 +85,65 @@ def test_the_service_scan_starts_no_external_process_per_scanned_process(monkeyp)-def test_the_windows_command_lookup_cannot_hang_its_caller(monkeypatch):- """The single-pid diagnostic lookup keeps its shell, but on a leash.+def test_the_command_lookup_reads_a_live_process_without_starting_one(monkeypatch):+ """The single-pid lookup reads the command line in this process.- Dropping it from the scan leaves it right for what it is actually for:- naming one specific process. It still runs on lifecycle paths such as- ``vibe stop``, though, so it must not be able to wait forever on a shell- that never answers.+ It names one process for an identity check or a log line, on lifecycle+ paths such as ``vibe start`` and ``vibe stop``. A ``powershell`` or ``ps``+ child per lookup took seconds on Windows, and could not run at all where a+ setuid ``ps`` is barred, as under a macOS sandbox. A path with a space must+ stay one argument."""- calls = []+ child = subprocess.Popen([sys.executable, "-c", "import time; time.sleep(60)", "/tmp/Vibe Tools/cloudflared"])+ launched = []+ try:+ monkeypatch.setattr(runtime.subprocess, "run", lambda command, **kwargs: launched.append(command))+ command = runtime.get_process_command(child.pid)+ finally:+ child.kill()+ child.wait(timeout=10)++ assert launched == []+ assert command is not None+ if os.name == "nt":+ assert command.endswith(' "/tmp/Vibe Tools/cloudflared"'), command+ else:+ assert shlex.split(command)[-1] == "/tmp/Vibe Tools/cloudflared", command- def record(command, **kwargs):- calls.append(kwargs)- return SimpleNamespace(stdout="", stderr="")- monkeypatch.setattr(runtime.subprocess, "run", record)+def _deny_every_process(monkeypatch):+ def denied(pid):+ raise runtime.psutil.AccessDenied(pid)- runtime._get_process_command_windows(4321)+ monkeypatch.setattr(runtime.psutil, "Process", denied)- assert calls, "the lookup never ran its shell, so this asserts nothing"- assert all(isinstance(call.get("timeout"), (int, float)) and call["timeout"] > 0 for call in calls), (- f"an unbounded external shell on a lifecycle path: {calls}"+[email protected](os.name == "nt", reason="only POSIX has a ps that reads what psutil may not")+def test_another_users_process_is_still_read_through_ps(monkeypatch):+ """On macOS psutil may not read another user's process; the setuid ``ps`` can."""++ _deny_every_process(monkeypatch)+ asked = []+ monkeypatch.setattr(+ runtime.subprocess,+ "run",+ lambda command, **kwargs: asked.append(command) or SimpleNamespace(stdout="/usr/sbin/someone-else --flag\n"),)+ assert runtime.get_process_command(4321) == "/usr/sbin/someone-else --flag"+ assert asked == [["ps", "-p", "4321", "-o", "command="]]++[email protected](os.name != "nt", reason="Windows has no other reader to ask")+def test_on_windows_a_process_psutil_may_not_read_is_unread_without_a_shell(monkeypatch):+ _deny_every_process(monkeypatch)+ asked = []+ monkeypatch.setattr(runtime.subprocess, "run", lambda command, **kwargs: asked.append(command))++ assert runtime.get_process_command(4321) is None+ assert asked == []+@pytest.mark.skipif(os.name != "nt", reason="only a real Windows process table holds enough unreadable processes")def test_the_service_scan_finishes_promptly_on_a_real_windows_process_table():diff --git a/tests/test_ui_server_logs.py b/tests/test_ui_server_logs.pyindex 118714d8f..3099a45d6 100644--- a/tests/test_ui_server_logs.py+++ b/tests/test_ui_server_logs.py@@ -8,6 +8,7 @@ from pathlib import Pathimport main as service_mainfrom config import paths+from tests.fake_pid_helpers import fake_pidfrom tests.ui_server_test_helpers import csrf_headersfrom vibe import runtimefrom vibe.ui_server import app@@ -300,8 +301,11 @@ def test_control_start_reuses_running_service_without_stop(monkeypatch, tmp_pathdef test_control_stop_uses_locked_service_stop(monkeypatch, tmp_path):monkeypatch.setenv("AVIBE_HOME", str(tmp_path))paths.ensure_data_dirs()- runtime.write_status("running", detail="running", service_pid=12345, ui_pid=67890)- paths.get_runtime_pid_path().write_text("12345", encoding="utf-8")+ # The stop reads the recorded service's command line, which a literal pid+ # reads off a real process.+ service_pid = fake_pid()+ runtime.write_status("running", detail="running", service_pid=service_pid, ui_pid=67890)+ paths.get_runtime_pid_path().write_text(str(service_pid), encoding="utf-8")calls = []monkeypatch.setattr(service_main, "shutdown_intent_required", lambda: True)@@ -321,7 +325,7 @@ def test_control_stop_uses_locked_service_stop(monkeypatch, tmp_path):calls.append("service_reaped_ui")return True- monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 12345)+ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == service_pid)monkeypatch.setattr(runtime, "stop_service", stop_service)monkeypatch.setattr(runtime, "stop_process", lambda pid_path: calls.append(("stop_process", pid_path)) or True)diff --git a/tests/test_vibe_cli.py b/tests/test_vibe_cli.pyindex ec6f22b22..612a3fe19 100644--- a/tests/test_vibe_cli.py+++ b/tests/test_vibe_cli.py@@ -986,6 +986,8 @@ def test_stop_process_preserves_pidfile_when_stop_fails(tmp_path, monkeypatch):def test_stop_pid_reports_failure_when_sigkill_does_not_terminate(monkeypatch):+ # stop_pid logs its target's command line, which a literal pid reads off a real process.+ pid = fake_pid()monkeypatch.setattr(runtime.os, "name", "posix", raising=False)monkeypatch.setattr(runtime, "pid_alive", lambda pid: True)monkeypatch.setattr(runtime, "write_shutdown_intent", lambda *args, **kwargs: None)@@ -997,8 +999,8 @@ def test_stop_pid_reports_failure_when_sigkill_does_not_terminate(monkeypatch):monkeypatch.setattr(runtime.os, "kill", _kill)- assert runtime.stop_pid(12345, timeout=0) is False- assert calls == [(12345, signal.SIGTERM), (12345, signal.SIGKILL)]+ assert runtime.stop_pid(pid, timeout=0) is False+ assert calls == [(pid, signal.SIGTERM), (pid, signal.SIGKILL)]def test_cli_stop_process_reuses_runtime_impl(tmp_path, monkeypatch):@@ -1099,13 +1101,6 @@ def test_cli_stop_fallback_stops_tool_commands_with_the_opencode_server(tmp_pathserver.stdout.close()-def test_proc_cmdline_decode_preserves_argv_boundaries():- command = runtime._decode_proc_cmdline(b"/tmp/Vibe Tools/cloudflared\x00tunnel\x00run\x00")-- assert command is not None- assert shlex.split(command)[0] == "/tmp/Vibe Tools/cloudflared"--def test_cmd_restart_schedules_delayed_restart(monkeypatch, capsys):scheduled = {}stop_called = []@@ -4526,6 +4521,8 @@ def test_restart_parser_rejects_non_finite_delay_seconds(raw_value):def test_stop_pid_handles_process_lookup_race(monkeypatch):+ # stop_pid logs its target's command line, which a literal pid reads off a real process.+ pid = fake_pid()monkeypatch.setattr(runtime.os, "name", "posix", raising=False)monkeypatch.setattr(runtime, "pid_alive", lambda pid: True)monkeypatch.setattr(runtime, "write_shutdown_intent", lambda *args, **kwargs: None)@@ -4535,10 +4532,12 @@ def test_stop_pid_handles_process_lookup_race(monkeypatch):monkeypatch.setattr(runtime.os, "kill", _kill)- assert runtime.stop_pid(12345) is False+ assert runtime.stop_pid(pid) is Falsedef test_stop_pid_handles_permission_error(monkeypatch):+ # stop_pid logs its target's command line, which a literal pid reads off a real process.+ pid = fake_pid()monkeypatch.setattr(runtime.os, "name", "posix", raising=False)monkeypatch.setattr(runtime, "pid_alive", lambda pid: True)monkeypatch.setattr(runtime, "write_shutdown_intent", lambda *args, **kwargs: None)@@ -4548,10 +4547,12 @@ def test_stop_pid_handles_permission_error(monkeypatch):monkeypatch.setattr(runtime.os, "kill", _kill)- assert runtime.stop_pid(12345) is False+ assert runtime.stop_pid(pid) is Falsedef test_stop_pid_writes_shutdown_intent_before_sigterm(monkeypatch):+ # stop_pid logs its target's command line, which a literal pid reads off a real process.+ pid = fake_pid()monkeypatch.setattr(runtime.os, "name", "posix", raising=False)alive_results = iter([True, False])monkeypatch.setattr(runtime, "pid_alive", lambda pid: next(alive_results))@@ -4564,11 +4565,11 @@ def test_stop_pid_writes_shutdown_intent_before_sigterm(monkeypatch):monkeypatch.setattr(runtime.time, "sleep", lambda _seconds: None)monkeypatch.setattr(runtime, "write_shutdown_intent", lambda *args, **kwargs: calls.append(("intent", args, kwargs)))- assert runtime.stop_pid(12345) is True+ assert runtime.stop_pid(pid) is Trueassert calls[0][0] == "intent"- assert calls[0][1] == (12345,)+ assert calls[0][1] == (pid,)assert calls[0][2]["signum"] == signal.SIGTERM- assert calls[1] == (12345, signal.SIGTERM)+ assert calls[1] == (pid, signal.SIGTERM)def test_start_ui_reuses_existing_live_pid(tmp_path, monkeypatch):@@ -4601,6 +4602,108 @@ def test_start_ui_reuses_existing_live_pid(tmp_path, monkeypatch):assert runtime.start_ui("127.0.0.1", 5123) == 12345+# A UI server as far as `ui_server_compatible` can tell -- every path answers+# the readiness the real one gives -- whose command line names the real one.+_STUB_UI_SERVER = """# stands in for vibe.ui_server's run_ui_server+import http.server, json+class Handler(http.server.BaseHTTPRequestHandler):+ def do_GET(self):+ body = json.dumps({"schema_version": 1, "product": "avibe", "ready": True}).encode()+ self.send_response(200)+ self.send_header("Content-Type", "application/json")+ self.send_header("Content-Length", str(len(body)))+ self.end_headers()+ self.wfile.write(body)+ def log_message(self, *args):+ pass+server = http.server.HTTPServer(("127.0.0.1", 0), Handler)+print(server.server_address[1], flush=True)+server.serve_forever()+"""+++def test_a_start_identifies_a_serving_ui_without_an_external_lookup_so_a_stop_ends_it(tmp_path, monkeypatch):+ """The UI a hard-killed service left serving is still stopped by the next stop.++ After the service is killed outright the next start finds the recorded UI+ serving. Its command line came from ``ps`` or PowerShell, and where that+ could not run -- a setuid ``ps`` barred by a macOS sandbox, a PowerShell+ lookup that failed or timed out -- the start took the UI for another+ program, dropped its record and started a replacement, which died on the+ port. The old UI kept serving with nothing pointing at it, and ``vibe+ stop`` left it running.+ """++ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")+ runtime.ensure_dirs()+ ui = subprocess.Popen([sys.executable, "-c", _STUB_UI_SERVER], stdout=subprocess.PIPE, text=True)+ try:+ port = int(ui.stdout.readline())+ paths.get_runtime_ui_pid_path().write_text(str(ui.pid), encoding="utf-8")++ def no_external_lookup(command, **kwargs):+ raise OSError(f"no external process can run here: {command[0]}")++ monkeypatch.setattr(runtime.subprocess, "run", no_external_lookup)+ replacements = []++ def die_on_the_port(args, pid_path, *_args, **_kwargs):+ replacements.append(args)+ pid_path.write_text(str(fake_pid()), encoding="utf-8")+ return fake_pid()++ monkeypatch.setattr(runtime, "spawn_background", die_on_the_port)+ info = runtime.ProcessStartInfo()++ started = runtime.start_ui("127.0.0.1", port, wait_for_ready=False, start_info=info)+ runtime.stop_ui(stop_remote_access=False)++ try:+ ui.wait(timeout=15)+ except subprocess.TimeoutExpired:+ pytest.fail("the stop left the recorded UI serving")+ assert replacements == []+ assert started == ui.pid+ assert (info.pid, info.reused) == (ui.pid, True)+ finally:+ if ui.poll() is None:+ ui.kill()+ ui.wait(timeout=10)+ ui.stdout.close()++[email protected]("ui_answers", [False, True])+def test_start_ui_never_adopts_a_recorded_pid_it_cannot_identify(tmp_path, monkeypatch, ui_answers):+ """A UI answering on the port is not shown to be the recorded pid.++ A pid whose command line cannot be read -- one psutil may not read, so not+ a process this user started -- is replaced whether or not some UI answers:+ adopting it would hand the next stop a process that may not be the UI.+ """++ monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")+ runtime.ensure_dirs()+ paths.get_runtime_ui_pid_path().write_text("12345", encoding="utf-8")++ monkeypatch.setattr(runtime, "pid_alive", lambda pid: pid == 12345)+ monkeypatch.setattr(runtime, "ui_server_compatible", lambda host, port: ui_answers)+ monkeypatch.setattr(runtime, "get_process_command", lambda pid: None)+ monkeypatch.setattr(runtime, "wait_for_ui_server", lambda host, port: True)++ def fail_stop(pid, timeout=5):+ raise AssertionError(f"a pid that cannot be identified should not be stopped: {pid}")++ def fake_spawn(args, pid_path, stdout_name, stderr_name, env=None):+ pid_path.write_text("67890", encoding="utf-8")+ return 67890++ monkeypatch.setattr(runtime, "stop_pid", fail_stop)+ monkeypatch.setattr(runtime, "spawn_background", fake_spawn)++ assert runtime.start_ui("127.0.0.1", 5123) == 67890+ assert paths.get_runtime_ui_pid_path().read_text(encoding="utf-8") == "67890"++def test_start_ui_does_not_reuse_unrelated_pid_with_healthy_endpoint(tmp_path, monkeypatch):monkeypatch.setattr(paths, "get_vibe_remote_dir", lambda: tmp_path / ".vibe_remote")runtime.ensure_dirs()diff --git a/vibe/runtime.py b/vibe/runtime.pyindex 73a55fcb0..baf589fa1 100644--- a/vibe/runtime.py+++ b/vibe/runtime.py@@ -664,53 +664,31 @@ def _terminate_process_windows(pid: int, timeout: float = 5) -> bool:return False-# One shell that never answers must not be able to hold a `vibe stop` open.-# This lookup names a single process for a log line or an identity check, so a-# bound that costs it an unanswered question is cheaper than an unbounded wait-# on a lifecycle path. The existing `except Exception: continue` already moves-# on to the next shell, and TimeoutExpired arrives there.-_WINDOWS_COMMAND_LOOKUP_TIMEOUT_SECONDS = 5.0---def _get_process_command_windows(pid: int) -> str | None:- script = f'$p = Get-CimInstance Win32_Process -Filter "ProcessId = {pid}"; if ($p) {{ $p.CommandLine }}'- for shell in ("powershell", "pwsh"):- try:- result = subprocess.run(- [shell, "-NoProfile", "-Command", script],- capture_output=True,- text=True,- check=False,- timeout=_WINDOWS_COMMAND_LOOKUP_TIMEOUT_SECONDS,- )- except Exception:- continue- command = (result.stdout or "").strip()- if command:- return command- return None---def _decode_proc_cmdline(raw: bytes) -> str | None:- argv = [part.decode("utf-8", "replace") for part in raw.split(b"\x00") if part]- return shlex.join(argv) if argv else None--def get_process_command(pid: int) -> str | None:+ """The command line ``pid`` runs, or None when it cannot be read.++ psutil reads it in this process. A ``ps`` or PowerShell child per lookup+ took seconds on Windows, and failed outright where a setuid ``ps`` cannot+ run, as under a macOS sandbox: there a start could not tell the recorded+ UI from another program and replaced it, orphaning the UI still serving.+ Only another user's process, which psutil may not read on macOS, still+ asks ``ps``; on Windows such a process reads as None.+ """+if not isinstance(pid, int) or pid <= 0:return None-- if os.name == "nt":- return _get_process_command_windows(pid)-- proc_cmdline = Path(f"/proc/{pid}/cmdline")try:- command = _decode_proc_cmdline(proc_cmdline.read_bytes())- except Exception:- command = None- if command:- return command+ argv = psutil.Process(pid).cmdline()+ except psutil.AccessDenied:+ return None if os.name == "nt" else _get_process_command_from_ps(pid)+ except psutil.Error:+ return None+ if not argv:+ return None+ return subprocess.list2cmdline(argv) if os.name == "nt" else shlex.join(argv)++def _get_process_command_from_ps(pid: int) -> str | None:try:result = subprocess.run(["ps", "-p", str(pid), "-o", "command="],@@ -862,7 +840,7 @@ def _process_command_from_info(proc) -> str | None:"""Name a scanned process from what psutil already collected, or not at all.This is asked for every process on the machine, so it has to be cheap. It- used to fall back to `get_process_command`, which on Windows launches+ used to fall back to `get_process_command`, which on Windows then launched`powershell -Command Get-CimInstance ...` -- and a second `pwsh` when thefirst says nothing -- once per process. A per-process external shell insidea whole-machine walk is invisible on Linux, where that fallback is a /proc