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(backends): address P1+P2 review pass on PR #282

cyh622b268a814c
diff --git a/core/runtime_commands.py b/core/runtime_commands.py
index f3a203964..060aea060 100644
--- a/core/runtime_commands.py
+++ b/core/runtime_commands.py
@@ -29,7 +29,13 @@ if TYPE_CHECKING: # pragma: no cover - typing only
logger = logging.getLogger(__name__)
_SUPPORTED_BACKENDS = {"opencode", "codex"}
-_MARKER_PATTERN = re.compile(r"^restart-(?P<backend>[a-z][a-z0-9_-]*)\.cmd$")
+# The optional ``.<reqid>`` suffix lets each restart get its own marker
+# (and ``.err`` companion). The UI server's ``_request_controller_restart``
+# always sends a reqid; we still accept the bare ``restart-<backend>.cmd``
+# form so any leftover marker from an older client doesn't get ignored.
+_MARKER_PATTERN = re.compile(
+ r"^restart-(?P<backend>[a-z][a-z0-9_-]*)(?:\.(?P<reqid>[A-Za-z0-9_-]+))?\.cmd$"
+)
_POLL_INTERVAL_SECONDS = 0.5
diff --git a/tests/test_codex_process_match.py b/tests/test_codex_process_match.py
index 040e0747d..535c8248a 100644
--- a/tests/test_codex_process_match.py
+++ b/tests/test_codex_process_match.py
@@ -93,3 +93,53 @@ def test_requires_app_server_token(tmp_path: Path) -> None:
_, codex_path = _make_paths(tmp_path)
cmdline = [codex_path, "login", "--browser"]
assert api._process_matches_codex_binary(cmdline, codex_path) is False
+
+
+def test_codex_processes_skips_uids_attr_on_windows(monkeypatch, tmp_path: Path) -> None:
+ """``psutil.process_iter`` rejects ``uids`` on Windows; gate the request.
+
+ Regression for the Codex review P1: ``_codex_processes`` previously
+ asked for ``['pid', 'name', 'cmdline', 'uids']`` unconditionally, and
+ on Windows ``process_iter`` raises ``ValueError: invalid attr name
+ 'uids'`` — making the entire backend runtime probe crash with 500.
+ """
+ import sys
+ import types
+
+ # Pretend we're on a platform without ``os.getuid`` (i.e. Windows).
+ if hasattr(os, "getuid"):
+ monkeypatch.delattr(os, "getuid")
+
+ seen_attrs: list[list[str]] = []
+ fake_psutil = types.SimpleNamespace(
+ NoSuchProcess=Exception,
+ AccessDenied=Exception,
+ process_iter=lambda attrs: seen_attrs.append(list(attrs)) or iter(()),
+ )
+ monkeypatch.setitem(sys.modules, "psutil", fake_psutil)
+
+ api._codex_processes(None)
+ assert seen_attrs, "process_iter should have been called once"
+ assert "uids" not in seen_attrs[0]
+ assert seen_attrs[0] == ["pid", "name", "cmdline"]
+
+
+def test_codex_processes_requests_uids_on_posix(monkeypatch) -> None:
+ """On POSIX, ``uids`` is still requested so we can filter by current user."""
+ import sys
+ import types
+
+ if not hasattr(os, "getuid"):
+ # Test only meaningful on POSIX; skip on Windows hosts.
+ return
+ seen_attrs: list[list[str]] = []
+ fake_psutil = types.SimpleNamespace(
+ NoSuchProcess=Exception,
+ AccessDenied=Exception,
+ process_iter=lambda attrs: seen_attrs.append(list(attrs)) or iter(()),
+ )
+ monkeypatch.setitem(sys.modules, "psutil", fake_psutil)
+
+ api._codex_processes(None)
+ assert seen_attrs
+ assert "uids" in seen_attrs[0]
diff --git a/tests/test_controller_ack.py b/tests/test_controller_ack.py
index 1a85c2559..e53a330c3 100644
--- a/tests/test_controller_ack.py
+++ b/tests/test_controller_ack.py
@@ -10,7 +10,7 @@ from vibe import api
def test_ack_success_returns_no_error(tmp_path: Path) -> None:
"""Marker absent + no .err sentinel → handled=True, error=None."""
- marker = tmp_path / "restart-opencode.cmd"
+ marker = tmp_path / "restart-opencode.abc123.cmd"
# marker never existed → already "removed"
handled, error = api._wait_for_controller_ack(marker, timeout=0.05)
assert handled is True
@@ -19,8 +19,8 @@ def test_ack_success_returns_no_error(tmp_path: Path) -> None:
def test_ack_failure_reads_and_consumes_err_sentinel(tmp_path: Path) -> None:
"""Marker absent + .err present → handled=True, error=<message>, sentinel cleaned."""
- marker = tmp_path / "restart-opencode.cmd"
- err_marker = tmp_path / "restart-opencode.cmd.err"
+ marker = tmp_path / "restart-opencode.abc123.cmd"
+ err_marker = tmp_path / "restart-opencode.abc123.cmd.err"
err_marker.write_text("transport teardown failed", encoding="utf-8")
handled, error = api._wait_for_controller_ack(marker, timeout=0.05)
@@ -32,7 +32,7 @@ def test_ack_failure_reads_and_consumes_err_sentinel(tmp_path: Path) -> None:
def test_ack_timeout_leaves_marker(tmp_path: Path) -> None:
"""Marker still present after timeout → handled=False, caller falls back to direct kill."""
- marker = tmp_path / "restart-opencode.cmd"
+ marker = tmp_path / "restart-opencode.abc123.cmd"
marker.write_text("{}", encoding="utf-8")
handled, error = api._wait_for_controller_ack(marker, timeout=0.05)
assert handled is False
@@ -43,11 +43,32 @@ def test_ack_timeout_leaves_marker(tmp_path: Path) -> None:
def test_ack_blank_err_falls_back_to_unknown(tmp_path: Path) -> None:
"""An empty .err shouldn't masquerade as success — surface a generic message."""
- marker = tmp_path / "restart-opencode.cmd"
- err_marker = tmp_path / "restart-opencode.cmd.err"
+ marker = tmp_path / "restart-opencode.abc123.cmd"
+ err_marker = tmp_path / "restart-opencode.abc123.cmd.err"
err_marker.write_text("", encoding="utf-8")
handled, error = api._wait_for_controller_ack(marker, timeout=0.05)
assert handled is True
assert error == "unknown error"
assert not err_marker.exists()
+
+
+def test_ack_ignores_stale_err_from_other_request(tmp_path: Path) -> None:
+ """A stale .err from a *different* reqid must NOT poison our request.
+
+ Regression for the race where a prior restart timed out caller-side,
+ the controller later wrote its ``.err``, and the next restart
+ misread that file as its own failure.
+ """
+ stale = tmp_path / "restart-opencode.aaa111.cmd.err"
+ stale.write_text("ancient failure", encoding="utf-8")
+ # Fresh request uses a different reqid; its marker never existed
+ # (controller-handled immediately).
+ fresh_marker = tmp_path / "restart-opencode.bbb222.cmd"
+ handled, error = api._wait_for_controller_ack(fresh_marker, timeout=0.05)
+ assert handled is True
+ assert error is None
+ # The stale file belongs to a different request — leave it for that
+ # request's caller to clean up (it never will, but it also never
+ # contaminates this one).
+ assert stale.exists()
diff --git a/vibe/api.py b/vibe/api.py
index 34cce72ca..ee8c5219a 100644
--- a/vibe/api.py
+++ b/vibe/api.py
@@ -8,6 +8,7 @@ import subprocess
import sys
import time
import urllib.request
+import uuid
from pathlib import Path
from typing import Dict, List, Optional
@@ -1753,9 +1754,16 @@ def _codex_processes(resolved_binary: str | None) -> list[int]:
except ImportError: # pragma: no cover - psutil is a hard dep elsewhere
return []
+ # ``uids`` is a POSIX-only psutil attribute; requesting it on Windows
+ # makes ``process_iter`` raise ``ValueError: invalid attr name 'uids'``
+ # and the entire probe blows up. Gate it on ``getuid`` availability,
+ # which is the same signal we use to decide whether to filter at all.
current_uid = os.getuid() if hasattr(os, "getuid") else None
+ attrs = ["pid", "name", "cmdline"]
+ if current_uid is not None:
+ attrs.append("uids")
pids: list[int] = []
- for proc in psutil.process_iter(attrs=["pid", "name", "cmdline", "uids"]):
+ for proc in psutil.process_iter(attrs=attrs):
try:
info = proc.info
cmdline = info.get("cmdline") or []
@@ -1878,15 +1886,22 @@ def _request_controller_restart(backend: str, timeout: float = 4.0) -> tuple[boo
direct process kill when the controller is unreachable (e.g. running
detached, not yet started).
+ Each request gets its own marker filename (``restart-<backend>.<reqid>.cmd``)
+ so we can correlate failures back to *this* request. Without the reqid,
+ a stale ``.err`` from a prior request that timed out caller-side — or an
+ overlapping concurrent restart — could be mistaken for *our* failure and
+ surface a phantom error toast.
+
Returns ``(handled, error)`` — see ``_wait_for_controller_ack`` for the
contract. ``handled=True`` does *not* imply success; check ``error`` too
so the UI toast doesn't claim a restart when the controller's refresh
actually raised.
"""
- marker = _runtime_command_dir() / f"restart-{backend}.cmd"
+ reqid = uuid.uuid4().hex[:8]
+ marker = _runtime_command_dir() / f"restart-{backend}.{reqid}.cmd"
try:
marker.write_text(
- json.dumps({"backend": backend, "ts": time.time()}),
+ json.dumps({"backend": backend, "ts": time.time(), "reqid": reqid}),
encoding="utf-8",
)
except OSError as exc:
@@ -1895,12 +1910,17 @@ def _request_controller_restart(backend: str, timeout: float = 4.0) -> tuple[boo
handled, error = _wait_for_controller_ack(marker, timeout)
if handled:
return True, error
- # Marker still present — controller didn't pick it up. Clean up before
- # falling back so we don't leave a stale request lying around.
+ # Marker still present — controller didn't pick it up. Clean up the
+ # request marker *and* any stray ``.err`` so the next attempt starts
+ # from a clean slate.
try:
marker.unlink(missing_ok=True)
except OSError:
pass
+ try:
+ marker.with_name(marker.name + ".err").unlink(missing_ok=True)
+ except OSError:
+ pass
return False, None