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(agents): tighten runtime gate edge cases

cyh31070409e7fc
diff --git a/core/controller.py b/core/controller.py
index 53dd1129f..4ffd2151b 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -678,7 +678,7 @@ class Controller:
# Register callbacks with the IM client
self.im_client.register_callbacks(
- on_message=self._dispatch_to_controller_loop_background(_on_im_message),
+ on_message=self._dispatch_im_message_to_controller_loop(_on_im_message),
on_command=command_handlers,
on_callback_query=self._dispatch_to_controller_loop(self.message_handler.handle_callback_query),
on_settings_update=self._dispatch_to_controller_loop(self.settings_handler.handle_settings_update),
@@ -710,12 +710,44 @@ class Controller:
return _wrapped
+ def _dispatch_im_message_to_controller_loop(self, callback):
+ tracked_platforms = {"telegram", "wechat"}
+
+ async def _wrapped(context, *args, **kwargs):
+ platform = str(
+ getattr(context, "platform", None)
+ or (getattr(context, "platform_specific", None) or {}).get("platform")
+ or ""
+ )
+ if platform in tracked_platforms:
+ return await self._run_on_controller_loop(callback, context, *args, **kwargs)
+ self._schedule_controller_callback(callback, context, *args, **kwargs)
+ return None
+
+ return _wrapped
+
def _dispatch_to_controller_loop_background(self, callback):
async def _wrapped(*args, **kwargs):
self._schedule_controller_callback(callback, *args, **kwargs)
return _wrapped
+ async def _run_on_controller_loop(self, callback, *args, **kwargs):
+ loop = self._loop
+ if loop is None:
+ return await callback(*args, **kwargs)
+
+ try:
+ current_loop = asyncio.get_running_loop()
+ except RuntimeError:
+ current_loop = None
+
+ if current_loop is loop:
+ return await callback(*args, **kwargs)
+
+ future = asyncio.run_coroutine_threadsafe(callback(*args, **kwargs), loop)
+ return await asyncio.wrap_future(future)
+
def _schedule_controller_callback(self, callback, *args, **kwargs) -> None:
async def _runner():
await callback(*args, **kwargs)
diff --git a/modules/agents/service.py b/modules/agents/service.py
index f05f0e3d8..6dd4ca877 100644
--- a/modules/agents/service.py
+++ b/modules/agents/service.py
@@ -43,17 +43,18 @@ class AgentService:
await gate.lock.acquire()
gate.token = uuid.uuid4().hex
gate.backend = agent.name
+ gate.running = True
self._stamp_runtime_turn(request, runtime_key, gate.token)
- # INBOUND status chokepoint (one of exactly two — the other is the outbound
- # MessageDispatcher.emit_agent_message). Every turn, every source (chat /
- # scheduled / Show Page), every backend funnels through here, so this is the
- # single place that marks an avibe session "running". The matching idle /
- # failed is written by the outbound terminal result. Non-avibe turns carry
- # no workbench session id and are skipped.
- manager = getattr(self.controller, "session_turns", None)
- if manager is not None:
- manager.on_running(request.context)
try:
+ # INBOUND status chokepoint (one of exactly two — the other is the outbound
+ # MessageDispatcher.emit_agent_message). Every turn, every source (chat /
+ # scheduled / Show Page), every backend funnels through here, so this is the
+ # single place that marks an avibe session "running". The matching idle /
+ # failed is written by the outbound terminal result. Non-avibe turns carry
+ # no workbench session id and are skipped.
+ manager = getattr(self.controller, "session_turns", None)
+ if manager is not None:
+ manager.on_running(request.context)
await agent.handle_message(request)
except asyncio.CancelledError:
self.release_runtime_turn(request.context)
@@ -116,7 +117,13 @@ class AgentService:
if gate is not None and gate.token:
self._stamp_runtime_turn(request, runtime_key, gate.token)
handled = await agent.handle_stop(request)
- if not handled and getattr(request, "stop_failure_reason", None) in STALE_STOP_REASONS:
+ if (
+ not handled
+ and getattr(request, "stop_failure_reason", None) in STALE_STOP_REASONS
+ and gate is not None
+ and gate.token
+ and not gate.running
+ ):
self.release_runtime_turn(request.context)
return handled
@@ -142,6 +149,7 @@ class AgentService:
return
gate.token = ""
gate.backend = ""
+ gate.running = False
if gate.lock.locked():
gate.lock.release()
@@ -218,3 +226,4 @@ class _RuntimeTurnGate:
lock: asyncio.Lock = field(default_factory=asyncio.Lock)
token: str = ""
backend: str = ""
+ running: bool = False
diff --git a/tests/test_agent_service.py b/tests/test_agent_service.py
index a498d1b01..57b0324ca 100644
--- a/tests/test_agent_service.py
+++ b/tests/test_agent_service.py
@@ -79,6 +79,11 @@ class _Controller:
self.session_turns = None
+class _FailingTurnManager:
+ def on_running(self, _context):
+ raise RuntimeError("status failed")
+
+
def _request(message: str, runtime_key: str = "session:/repo"):
return SimpleNamespace(
context=SimpleNamespace(platform_specific={}),
@@ -300,6 +305,7 @@ def test_agent_service_releases_runtime_gate_for_stale_stop() -> None:
await gate.lock.acquire()
gate.token = "stop-token"
gate.backend = "claude"
+ gate.running = False
handled = await service.handle_stop("claude", request)
@@ -310,6 +316,28 @@ def test_agent_service_releases_runtime_gate_for_stale_stop() -> None:
asyncio.run(_run())
+def test_agent_service_keeps_runtime_gate_for_startup_window_stop() -> None:
+ async def _run():
+ service = AgentService(controller=_Controller())
+ agent = _StopRuntimeAgent("not_active")
+ service.register(agent)
+ request = _request("stop")
+ gate = service._get_turn_gate("session:/repo")
+ await gate.lock.acquire()
+ gate.token = "stop-token"
+ gate.backend = "codex"
+ gate.running = True
+
+ handled = await service.handle_stop("claude", request)
+
+ assert handled is False
+ assert gate.lock.locked()
+ assert gate.token == "stop-token"
+ service.release_runtime_turn_key("session:/repo", "stop-token")
+
+ asyncio.run(_run())
+
+
def test_agent_service_keeps_runtime_gate_for_interrupt_failure_stop() -> None:
async def _run():
service = AgentService(controller=_Controller())
@@ -320,6 +348,7 @@ def test_agent_service_keeps_runtime_gate_for_interrupt_failure_stop() -> None:
await gate.lock.acquire()
gate.token = "stop-token"
gate.backend = "claude"
+ gate.running = True
handled = await service.handle_stop("claude", request)
@@ -330,6 +359,31 @@ def test_agent_service_keeps_runtime_gate_for_interrupt_failure_stop() -> None:
asyncio.run(_run())
+def test_agent_service_releases_gate_when_on_running_fails() -> None:
+ async def _run():
+ controller = _Controller()
+ controller.session_turns = _FailingTurnManager()
+ service = AgentService(controller=controller)
+ agent = _RuntimeAgent()
+ service.register(agent)
+ request = _request("hello")
+
+ try:
+ await service.handle_message("claude", request)
+ except RuntimeError as err:
+ assert str(err) == "status failed"
+ else:
+ raise AssertionError("on_running failure should escape")
+
+ gate = service._turn_gates["session:/repo"]
+ assert not gate.lock.locked()
+ assert gate.token == ""
+ assert gate.running is False
+ assert agent.started == []
+
+ asyncio.run(_run())
+
+
def test_agent_service_releases_gate_when_exception_terminal_emit_fails() -> None:
async def _run():
controller = _Controller()
diff --git a/tests/test_controller_dispatch_loop.py b/tests/test_controller_dispatch_loop.py
index a04fe87c2..e905bfd88 100644
--- a/tests/test_controller_dispatch_loop.py
+++ b/tests/test_controller_dispatch_loop.py
@@ -4,6 +4,7 @@ import asyncio
import threading
import sys
from pathlib import Path
+from types import SimpleNamespace
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
@@ -46,7 +47,7 @@ def test_dispatch_to_controller_loop_runs_callback_on_controller_loop():
assert result["value"] == "hello"
-def test_dispatch_to_controller_loop_background_returns_before_callback_finishes():
+def test_dispatch_im_message_to_controller_loop_backgrounds_untracked_platforms():
controller = Controller.__new__(Controller)
loop = asyncio.new_event_loop()
controller._loop = loop
@@ -54,15 +55,17 @@ def test_dispatch_to_controller_loop_background_returns_before_callback_finishes
callback_can_finish = threading.Event()
result: dict[str, object] = {}
- async def callback(value: str) -> None:
+ async def callback(context, value: str) -> None:
result["thread"] = threading.current_thread().name
result["loop"] = asyncio.get_running_loop()
+ result["platform"] = context.platform
result["value"] = value
callback_started.set()
await asyncio.to_thread(callback_can_finish.wait)
result["finished"] = True
- wrapped = Controller._dispatch_to_controller_loop_background(controller, callback)
+ wrapped = Controller._dispatch_im_message_to_controller_loop(controller, callback)
+ context = SimpleNamespace(platform="slack", platform_specific={"platform": "slack"})
def _loop_runner() -> None:
asyncio.set_event_loop(loop)
@@ -72,7 +75,7 @@ def test_dispatch_to_controller_loop_background_returns_before_callback_finishes
loop_thread.start()
async def _invoke() -> None:
- await asyncio.wait_for(wrapped("hello"), timeout=0.2)
+ await asyncio.wait_for(wrapped(context, "hello"), timeout=0.2)
try:
asyncio.run(_invoke())
@@ -90,6 +93,58 @@ def test_dispatch_to_controller_loop_background_returns_before_callback_finishes
assert result["finished"] is True
assert result["thread"] == "controller-loop"
+ assert result["platform"] == "slack"
+ assert result["value"] == "hello"
+
+
+def test_dispatch_im_message_to_controller_loop_waits_for_tracked_platforms():
+ controller = Controller.__new__(Controller)
+ loop = asyncio.new_event_loop()
+ controller._loop = loop
+ callback_started = threading.Event()
+ callback_can_finish = threading.Event()
+ result: dict[str, object] = {}
+
+ async def callback(context, value: str) -> str:
+ result["thread"] = threading.current_thread().name
+ result["loop"] = asyncio.get_running_loop()
+ result["platform"] = context.platform
+ result["value"] = value
+ callback_started.set()
+ await asyncio.to_thread(callback_can_finish.wait)
+ result["finished"] = True
+ return "done"
+
+ wrapped = Controller._dispatch_im_message_to_controller_loop(controller, callback)
+ context = SimpleNamespace(platform="telegram", platform_specific={"platform": "telegram"})
+
+ def _loop_runner() -> None:
+ asyncio.set_event_loop(loop)
+ loop.run_forever()
+
+ loop_thread = threading.Thread(target=_loop_runner, name="controller-loop", daemon=True)
+ loop_thread.start()
+
+ async def _invoke() -> str:
+ task = asyncio.create_task(wrapped(context, "hello"))
+ await asyncio.to_thread(callback_started.wait)
+ await asyncio.sleep(0)
+ assert not task.done()
+ callback_can_finish.set()
+ return await asyncio.wait_for(task, timeout=1)
+
+ try:
+ output = asyncio.run(_invoke())
+ finally:
+ callback_can_finish.set()
+ loop.call_soon_threadsafe(loop.stop)
+ loop_thread.join(timeout=2)
+ loop.close()
+
+ assert output == "done"
+ assert result["finished"] is True
+ assert result["thread"] == "controller-loop"
+ assert result["platform"] == "telegram"
assert result["value"] == "hello"