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): preserve .err companions until requester consumes them
cyh356836dc3948
diff --git a/core/runtime_commands.py b/core/runtime_commands.pyindex 060aea060..59ca8e10f 100644--- a/core/runtime_commands.py+++ b/core/runtime_commands.py@@ -18,6 +18,7 @@ from __future__ import annotationsimport asyncioimport loggingimport re+import timefrom pathlib import Pathfrom typing import TYPE_CHECKING, Awaitable, Callable, Optional@@ -36,6 +37,12 @@ _SUPPORTED_BACKENDS = {"opencode", "codex"}_MARKER_PATTERN = re.compile(r"^restart-(?P<backend>[a-z][a-z0-9_-]*)(?:\.(?P<reqid>[A-Za-z0-9_-]+))?\.cmd$")+_ERR_SUFFIX = ".cmd.err"+# .err companions older than this are assumed orphaned (the requester never+# polled — e.g. the UI server was restarted mid-flight) and may be cleaned+# up. The window is generous because ``_wait_for_controller_ack`` waits up+# to ~4s; anything older than five minutes is safely past every caller.+_ERR_STALE_AGE_SECONDS = 300.0_POLL_INTERVAL_SECONDS = 0.5@@ -99,6 +106,14 @@ class RuntimeCommandWatcher:for marker in entries:if not marker.is_file():continue+ # ``.cmd.err`` companions are status output for the requester;+ # leaving them in place is required so ``_wait_for_controller_ack``+ # can read them before the next sweep. Only drop ones that are+ # demonstrably orphaned so the directory does not grow without+ # bound when a requester crashes mid-flight.+ if marker.name.endswith(_ERR_SUFFIX):+ self._maybe_evict_stale_err(marker)+ continuematch = _MARKER_PATTERN.match(marker.name)if not match:logger.debug("Ignoring unknown runtime command marker: %s", marker.name)@@ -111,6 +126,28 @@ class RuntimeCommandWatcher:continueawait self._handle_restart(backend, marker)+ @staticmethod+ def _maybe_evict_stale_err(err_marker: Path) -> None:+ """Delete a ``.err`` companion only if it is clearly orphaned.++ The requester reads ``.err`` files at most a few seconds after the+ controller writes them; anything older is past every caller's+ polling window and can be reclaimed. We deliberately do *not*+ delete fresh ones — that would race against+ ``_wait_for_controller_ack`` and silently demote a real failure to+ a "restart succeeded" toast.+ """+ try:+ age = time.time() - err_marker.stat().st_mtime+ except OSError:+ return+ if age < _ERR_STALE_AGE_SECONDS:+ return+ try:+ err_marker.unlink(missing_ok=True)+ except OSError as exc: # pragma: no cover - best-effort cleanup+ logger.debug("Could not evict stale err marker %s: %s", err_marker, exc)+async def _handle_restart(self, backend: str, marker: Path) -> None:logger.info("Runtime command: refresh backend=%s", backend)handler: Optional[Callable[[str], Awaitable[None]]] = getattr(diff --git a/tests/test_runtime_commands.py b/tests/test_runtime_commands.pyindex 17f0aacc5..829f78341 100644--- a/tests/test_runtime_commands.py+++ b/tests/test_runtime_commands.py@@ -1,7 +1,9 @@from __future__ import annotationsimport asyncio+import osimport sys+import timefrom pathlib import Pathfrom types import SimpleNamespace@@ -9,7 +11,10 @@ import pytestsys.path.insert(0, str(Path(__file__).resolve().parents[1]))-from core.runtime_commands import RuntimeCommandWatcher+from core.runtime_commands import (+ _ERR_STALE_AGE_SECONDS,+ RuntimeCommandWatcher,+)def _make_watcher(tmp_path: Path, handler) -> tuple[RuntimeCommandWatcher, Path]:@@ -78,3 +83,39 @@ def test_handle_restart_err_message_truncated(tmp_path: Path) -> None:err = tmp_path / "restart-opencode.cmd.err"assert err.exists()assert len(err.read_text()) <= 1024+++def test_sweep_preserves_fresh_err_companion(tmp_path: Path) -> None:+ """Regression for P2: sweep must not delete a fresh ``.err`` before the requester reads it.++ Reproduces the race where the controller writes ``<marker>.cmd.err`` to+ signal a failure, then the next sweep tick deletes it because it does+ not match ``_MARKER_PATTERN``. If the UI server's+ ``_wait_for_controller_ack`` polls *after* that sweep, it sees marker+ absent + no ``.err`` and reports success — a false positive.+ """+ controller = SimpleNamespace(agent_auth_service=SimpleNamespace())+ watcher = RuntimeCommandWatcher(controller, directory=tmp_path) # type: ignore[arg-type]+ err_marker = tmp_path / "restart-codex.abc123.cmd.err"+ err_marker.write_text("refresh failed", encoding="utf-8")++ asyncio.run(watcher._sweep_once())++ assert err_marker.exists(), ".err companion deleted by sweep — caller would see false success"+ assert err_marker.read_text(encoding="utf-8") == "refresh failed"+++def test_sweep_evicts_orphaned_err_companion(tmp_path: Path) -> None:+ """An ``.err`` older than the stale window is safely past every caller and may be cleaned up."""+ controller = SimpleNamespace(agent_auth_service=SimpleNamespace())+ watcher = RuntimeCommandWatcher(controller, directory=tmp_path) # type: ignore[arg-type]+ err_marker = tmp_path / "restart-codex.dead.cmd.err"+ err_marker.write_text("ancient", encoding="utf-8")+ # Backdate the mtime well past the eviction window so the sweep treats+ # it as orphaned (the original requester is long gone).+ old = time.time() - _ERR_STALE_AGE_SECONDS - 60+ os.utime(err_marker, (old, old))++ asyncio.run(watcher._sweep_once())++ assert not err_marker.exists()