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(backends): surface failed backend refresh instead of acking success
cyh1853cb7b2cdb
diff --git a/core/runtime_commands.py b/core/runtime_commands.pyindex 73ec9ddca..f3a203964 100644--- a/core/runtime_commands.py+++ b/core/runtime_commands.py@@ -112,16 +112,36 @@ class RuntimeCommandWatcher:)if handler is None:logger.warning("AgentAuthService missing _refresh_backend_runtime; dropping marker")- marker.unlink(missing_ok=True)+ self._fail_marker(marker, "refresh handler unavailable")returntry:await handler(backend)except Exception as exc:logger.error("Backend refresh failed for %s: %s", backend, exc, exc_info=True)- finally:- # Always delete the marker so the UI server stops waiting; a- # failed refresh is still observable via the next runtime probe.- try:- marker.unlink(missing_ok=True)- except OSError as exc: # pragma: no cover - best-effort cleanup- logger.debug("Could not remove marker %s: %s", marker, exc)+ self._fail_marker(marker, str(exc) or exc.__class__.__name__)+ return+ # Success path: silently drop the marker so the UI server reads the+ # absence-of-``.err`` as a clean ack.+ try:+ marker.unlink(missing_ok=True)+ except OSError as exc: # pragma: no cover - best-effort cleanup+ logger.debug("Could not remove marker %s: %s", marker, exc)++ @staticmethod+ def _fail_marker(marker: Path, error: str) -> None:+ """Surface a refresh failure to the UI server via a companion ``.err``.++ The caller (``vibe.api._wait_for_controller_ack``) treats marker+ deletion as the ack and looks for ``marker.name + ".err"`` to decide+ whether the refresh actually succeeded — otherwise the UI would+ toast ``ok: true`` while the runtime is still stale.+ """+ err_marker = marker.with_name(marker.name + ".err")+ try:+ err_marker.write_text(error[:1024], encoding="utf-8")+ except OSError as exc: # pragma: no cover - best-effort surface+ logger.debug("Could not write error marker %s: %s", err_marker, exc)+ try:+ marker.unlink(missing_ok=True)+ except OSError as exc: # pragma: no cover - best-effort cleanup+ logger.debug("Could not remove marker %s: %s", marker, exc)diff --git a/tests/test_controller_ack.py b/tests/test_controller_ack.pynew file mode 100644index 000000000..1a85c2559--- /dev/null+++ b/tests/test_controller_ack.py@@ -0,0 +1,53 @@+from __future__ import annotations++import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++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 never existed → already "removed"+ handled, error = api._wait_for_controller_ack(marker, timeout=0.05)+ assert handled is True+ assert error is 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"+ err_marker.write_text("transport teardown failed", encoding="utf-8")++ handled, error = api._wait_for_controller_ack(marker, timeout=0.05)+ assert handled is True+ assert error == "transport teardown failed"+ # Sentinel must be consumed so the next restart starts clean.+ assert not err_marker.exists()+++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.write_text("{}", encoding="utf-8")+ handled, error = api._wait_for_controller_ack(marker, timeout=0.05)+ assert handled is False+ assert error is None+ # The watcher would normally delete this; the caller does its own cleanup.+ assert marker.exists()+++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"+ 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()diff --git a/tests/test_runtime_commands.py b/tests/test_runtime_commands.pynew file mode 100644index 000000000..17f0aacc5--- /dev/null+++ b/tests/test_runtime_commands.py@@ -0,0 +1,80 @@+from __future__ import annotations++import asyncio+import sys+from pathlib import Path+from types import SimpleNamespace++import pytest++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from core.runtime_commands import RuntimeCommandWatcher+++def _make_watcher(tmp_path: Path, handler) -> tuple[RuntimeCommandWatcher, Path]:+ """Build a watcher whose controller's auth service exposes ``handler``."""+ auth_service = SimpleNamespace(_refresh_backend_runtime=handler)+ controller = SimpleNamespace(agent_auth_service=auth_service)+ watcher = RuntimeCommandWatcher(controller, directory=tmp_path) # type: ignore[arg-type]+ marker = tmp_path / "restart-opencode.cmd"+ marker.write_text('{"backend":"opencode"}', encoding="utf-8")+ return watcher, marker+++def test_handle_restart_success_deletes_marker_no_err(tmp_path: Path) -> None:+ """Happy path: marker deleted, no ``.err`` companion."""++ async def handler(name: str) -> None:+ assert name == "opencode"++ watcher, marker = _make_watcher(tmp_path, handler)+ asyncio.run(watcher._handle_restart("opencode", marker))++ assert not marker.exists()+ assert not (tmp_path / "restart-opencode.cmd.err").exists()+++def test_handle_restart_failure_writes_err_sentinel(tmp_path: Path) -> None:+ """Handler raises → marker deleted AND ``.err`` companion written."""++ async def handler(name: str) -> None:+ raise RuntimeError("transport teardown failed mid-way")++ watcher, marker = _make_watcher(tmp_path, handler)+ asyncio.run(watcher._handle_restart("opencode", marker))++ assert not marker.exists()+ err = tmp_path / "restart-opencode.cmd.err"+ assert err.exists()+ assert "transport teardown failed mid-way" in err.read_text()+++def test_handle_restart_missing_handler_writes_err_sentinel(tmp_path: Path) -> None:+ """No ``_refresh_backend_runtime`` on the service → also surface failure."""+ auth_service = SimpleNamespace() # no handler attribute+ controller = SimpleNamespace(agent_auth_service=auth_service)+ watcher = RuntimeCommandWatcher(controller, directory=tmp_path) # type: ignore[arg-type]+ marker = tmp_path / "restart-codex.cmd"+ marker.write_text("{}", encoding="utf-8")++ asyncio.run(watcher._handle_restart("codex", marker))++ assert not marker.exists()+ err = tmp_path / "restart-codex.cmd.err"+ assert err.exists()+ assert "refresh handler unavailable" in err.read_text()+++def test_handle_restart_err_message_truncated(tmp_path: Path) -> None:+ """Pathological multi-MB exception messages must not blow up the disk."""++ async def handler(name: str) -> None:+ raise RuntimeError("x" * 5000)++ watcher, marker = _make_watcher(tmp_path, handler)+ asyncio.run(watcher._handle_restart("opencode", marker))++ err = tmp_path / "restart-opencode.cmd.err"+ assert err.exists()+ assert len(err.read_text()) <= 1024diff --git a/vibe/api.py b/vibe/api.pyindex 6795edde0..34cce72ca 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -1831,17 +1831,42 @@ def _runtime_command_dir() -> Path:return base-def _wait_for_controller_ack(marker: Path, timeout: float) -> bool:- """Poll for ``marker`` removal as a signal that the controller ran it."""+def _wait_for_controller_ack(marker: Path, timeout: float) -> tuple[bool, str | None]:+ """Poll for ``marker`` removal as a signal that the controller ran it.++ Returns ``(handled, error)``:++ - ``handled=True, error=None`` — controller picked up the marker and the+ handler returned cleanly.+ - ``handled=True, error="..."`` — controller picked up the marker but+ the handler raised; the controller wrote the message to a companion+ ``<marker>.err`` file before deleting the request marker.+ - ``handled=False, error=None`` — timed out; the controller never+ consumed the marker. Caller should fall back to a direct kill.++ The companion ``.err`` file is consumed (unlinked) before returning so+ later requests start clean.+ """+ err_marker = marker.with_name(marker.name + ".err")deadline = time.monotonic() + timeoutwhile time.monotonic() < deadline:if not marker.exists():- return True+ error: str | None = None+ if err_marker.exists():+ try:+ error = err_marker.read_text(encoding="utf-8").strip() or "unknown error"+ except OSError:+ error = "unknown error"+ try:+ err_marker.unlink(missing_ok=True)+ except OSError: # pragma: no cover - best-effort cleanup+ pass+ return True, errortime.sleep(0.1)- return False+ return False, None-def _request_controller_restart(backend: str, timeout: float = 4.0) -> bool:+def _request_controller_restart(backend: str, timeout: float = 4.0) -> tuple[bool, str | None]:"""Ask the controller to refresh a backend via the runtime-command marker.The controller's ``RuntimeCommandWatcher`` (see ``core/runtime_commands.py``)@@ -1852,6 +1877,11 @@ def _request_controller_restart(backend: str, timeout: float = 4.0) -> bool:wait briefly for the controller to delete it; the caller falls back to adirect process kill when the controller is unreachable (e.g. runningdetached, not yet started).++ 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"try:@@ -1861,16 +1891,17 @@ def _request_controller_restart(backend: str, timeout: float = 4.0) -> bool:)except OSError as exc:logger.debug("Failed to write controller restart marker for %s: %s", backend, exc)- return False- if _wait_for_controller_ack(marker, timeout):- return True+ return False, None+ 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.try:marker.unlink(missing_ok=True)except OSError:pass- return False+ return False, Nonedef restart_backend(name: str) -> dict:@@ -1888,10 +1919,19 @@ def restart_backend(name: str) -> dict:if name not in _BACKENDS_WITH_RESTART:return {"ok": False, "message": f"Restart is not supported for backend: {name}"}- controller_handled = _request_controller_restart(name)+ controller_handled, controller_error = _request_controller_restart(name)_invalidate_version_cache(name)if controller_handled:+ if controller_error:+ # Controller saw the request and ran the handler, but the handler+ # raised. Don't lie to the user — surface the failure so they can+ # retry or look at logs. (The next runtime probe will also reflect+ # the stale state, but the toast must already say so.)+ return {+ "ok": False,+ "message": f"Backend refresh failed: {controller_error}",+ }if name == "opencode":return {"ok": True, "message": "OpenCode server refreshed; it will respawn on next request."}return {"ok": True, "message": "Codex runtime refreshed; transports will respawn on next request."}