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(im): close hot reconcile runtime gaps

cyh430053e0c893
diff --git a/core/controller.py b/core/controller.py
index 9b5348715..a8e5674cb 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -520,6 +520,7 @@ class Controller:
"allowed_chat_ids",
"allowed_user_ids",
"disable_link_unfurl",
+ "forum_auto_topic",
)
for platform, client in self.im_clients.items():
im_cfg = getattr(client, "config", None)
diff --git a/modules/im/multi.py b/modules/im/multi.py
index 6c2b0cf08..e27e3f25d 100644
--- a/modules/im/multi.py
+++ b/modules/im/multi.py
@@ -33,6 +33,7 @@ class MultiIMClient(BaseIMClient):
# loop (IM worker thread) and runtime add/remove_client calls (the
# reconcile path, on the asyncio loop) can't see a half-updated map.
self._clients_lock = threading.RLock()
+ self._removing_platforms: set[str] = set()
self._stop_requested = threading.Event()
self._ready_lock = threading.Lock()
self._ready_platforms: set[str] = set()
@@ -42,10 +43,22 @@ class MultiIMClient(BaseIMClient):
super().__init__(clients[primary_platform].config)
self.formatter = clients[primary_platform].formatter
else:
- from config.v2_config import AvibeConfig
+ config, formatter = self._workbench_fallback_runtime()
+ super().__init__(config)
+ self.formatter = formatter
- super().__init__(AvibeConfig())
- self.formatter = None
+ @staticmethod
+ def _workbench_fallback_runtime() -> tuple[Any, Any]:
+ from .avibe import AvibeConfig
+ from .formatters.avibe_formatter import AvibeFormatter
+
+ return AvibeConfig(), AvibeFormatter()
+
+ def _use_workbench_fallback_runtime(self) -> None:
+ config, formatter = self._workbench_fallback_runtime()
+ self.primary_platform = "avibe"
+ self.config = config
+ self.formatter = formatter
def _client_snapshot(self) -> Dict[str, BaseIMClient]:
with self._clients_lock:
@@ -69,6 +82,8 @@ class MultiIMClient(BaseIMClient):
if client is not None:
self.config = client.config
self.formatter = client.formatter
+ elif not self.clients:
+ self._use_workbench_fallback_runtime()
def _resolve_platform(self, context: Optional[MessageContext] = None) -> str:
if context is not None:
@@ -399,9 +414,17 @@ class MultiIMClient(BaseIMClient):
for platform, thread in list(self._threads.items()):
if thread.is_alive():
continue
+ if platform in self._removing_platforms:
+ continue
logger.warning("IM runtime for %s exited", platform)
self._threads.pop(platform, None)
- if self.clients and not self._threads:
+ active_platforms = [platform for platform in self.clients if platform not in self._removing_platforms]
+ live_active_threads = [
+ platform
+ for platform in active_platforms
+ if (thread := self._threads.get(platform)) is not None and thread.is_alive()
+ ]
+ if active_platforms and not live_active_threads:
logger.error("All enabled IM runtime threads exited")
break
time.sleep(0.5)
@@ -429,6 +452,7 @@ class MultiIMClient(BaseIMClient):
if platform in self.clients:
logger.warning("add_client: platform %s already present; skipping", platform)
return
+ self._removing_platforms.discard(platform)
self._register_client_callbacks(platform, client)
self.clients[platform] = client
if self.primary_platform not in self.clients:
@@ -452,32 +476,43 @@ class MultiIMClient(BaseIMClient):
"""
with self._clients_lock:
client = self.clients.get(platform)
+ if client is not None:
+ self._removing_platforms.add(platform)
thread = self._threads.get(platform)
if client is None:
return None
- stop_attr = getattr(client, "stop", None)
- if callable(stop_attr) and not inspect.iscoroutinefunction(stop_attr):
- try:
- stop_attr()
- except Exception:
- logger.exception("Failed to stop IM client for %s", platform)
- if thread is not None:
- thread.join(timeout=5.0)
- if thread.is_alive():
- message = f"IM thread for {platform} did not stop within timeout"
- logger.error("%s; hot-remove failed", message)
- raise IMClientRemovalError(message)
-
- ready_callback = None
- with self._clients_lock:
- self.clients.pop(platform, None)
- self._threads.pop(platform, None)
- if platform == self.primary_platform and self.clients:
- next_platform, next_client = next(iter(self.clients.items()))
- self.primary_platform = next_platform
- self.config = next_client.config
- self.formatter = next_client.formatter
+ try:
+ stop_attr = getattr(client, "stop", None)
+ if callable(stop_attr) and not inspect.iscoroutinefunction(stop_attr):
+ try:
+ stop_attr()
+ except Exception:
+ logger.exception("Failed to stop IM client for %s", platform)
+ if thread is not None:
+ thread.join(timeout=5.0)
+ if thread.is_alive():
+ message = f"IM thread for {platform} did not stop within timeout"
+ logger.error("%s; hot-remove failed", message)
+ raise IMClientRemovalError(message)
+
+ ready_callback = None
+ with self._clients_lock:
+ self.clients.pop(platform, None)
+ self._threads.pop(platform, None)
+ self._removing_platforms.discard(platform)
+ if self.clients:
+ if self.primary_platform not in self.clients:
+ next_platform, next_client = next(iter(self.clients.items()))
+ self.primary_platform = next_platform
+ self.config = next_client.config
+ self.formatter = next_client.formatter
+ else:
+ self._use_workbench_fallback_runtime()
+ except Exception:
+ with self._clients_lock:
+ self._removing_platforms.discard(platform)
+ raise
with self._ready_lock:
self._ready_platforms.discard(platform)
if self._mark_ready_if_complete():
diff --git a/modules/im/telegram.py b/modules/im/telegram.py
index fea84ad49..5ce357757 100644
--- a/modules/im/telegram.py
+++ b/modules/im/telegram.py
@@ -106,6 +106,7 @@ class TelegramBot(BaseIMClient):
self._bot_user: Optional[dict[str, Any]] = None
self._on_ready: Optional[Callable] = None
self._loop: Optional[asyncio.AbstractEventLoop] = None
+ self._poll_task: Optional[asyncio.Task[Any]] = None
self._update_tasks: set[asyncio.Task[Any]] = set()
self._message_callback_tasks: set[asyncio.Task[Any]] = set()
self._update_scope_gates: dict[str, _TelegramUpdateScopeGate] = {}
@@ -166,9 +167,13 @@ class TelegramBot(BaseIMClient):
def stop(self):
self._stop_event.set()
+ loop = self._loop
+ poll_task = self._poll_task
+ if loop is not None and loop.is_running() and poll_task is not None and not poll_task.done():
+ loop.call_soon_threadsafe(poll_task.cancel)
async def shutdown(self) -> None:
- self._stop_event.set()
+ self.stop()
async def _run(self) -> None:
self._loop = asyncio.get_running_loop()
@@ -180,19 +185,30 @@ class TelegramBot(BaseIMClient):
while not self._stop_event.is_set():
try:
- updates = await telegram_api.get_updates(
+ self._poll_task = asyncio.create_task(telegram_api.get_updates(
self.config.bot_token,
self._offset,
proxy_url=self._proxy_url,
- )
+ ))
+ try:
+ updates = await self._poll_task
+ except asyncio.CancelledError:
+ if self._stop_event.is_set():
+ break
+ raise
+ finally:
+ self._poll_task = None
for update in updates.get("result", []):
await self._wait_for_update_capacity()
self._offset = int(update["update_id"]) + 1
self._spawn_update_task(update)
except Exception as err:
+ if self._stop_event.is_set():
+ break
logger.warning("Telegram poll loop error: %s", err, exc_info=True)
await asyncio.sleep(2)
finally:
+ self._poll_task = None
await self._drain_background_tasks()
def _spawn_update_task(self, update: dict[str, Any]) -> None:
diff --git a/tests/test_controller_config_reload.py b/tests/test_controller_config_reload.py
index 3b5d2e9d7..94ace8fea 100644
--- a/tests/test_controller_config_reload.py
+++ b/tests/test_controller_config_reload.py
@@ -1,16 +1,18 @@
from types import SimpleNamespace
-from config.v2_config import DiscordConfig, V2Config
+from config.v2_config import DiscordConfig, TelegramConfig, V2Config
from core.controller import Controller
-def _config_payload(discord_payload: dict) -> dict:
+def _config_payload(discord_payload: dict | None = None, telegram_payload: dict | None = None) -> dict:
+ platform = "telegram" if telegram_payload is not None else "discord"
return {
- "platform": "discord",
- "platforms": {"enabled": ["discord"], "primary": "discord"},
+ "platform": platform,
+ "platforms": {"enabled": [platform], "primary": platform},
"mode": "self_host",
"version": "v2",
- "discord": discord_payload,
+ "discord": discord_payload or {},
+ "telegram": telegram_payload or {},
"runtime": {"default_cwd": "_tmp", "log_level": "INFO"},
"agents": {
"default_backend": "opencode",
@@ -28,7 +30,7 @@ def test_refresh_config_updates_platform_message_settings(tmp_path, monkeypatch)
controller = Controller.__new__(Controller)
controller.config = V2Config.from_payload(
_config_payload(
- {
+ discord_payload={
"bot_token": "discord-token",
"require_mention": stale_discord_config.require_mention,
}
@@ -39,7 +41,7 @@ def test_refresh_config_updates_platform_message_settings(tmp_path, monkeypatch)
latest_config = V2Config.from_payload(
_config_payload(
- {
+ discord_payload={
"bot_token": "discord-token",
"require_mention": False,
}
@@ -52,6 +54,44 @@ def test_refresh_config_updates_platform_message_settings(tmp_path, monkeypatch)
assert stale_discord_config.require_mention is False
+def test_refresh_config_updates_telegram_option_only_settings(tmp_path, monkeypatch) -> None:
+ monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
+
+ stale_telegram_config = TelegramConfig(
+ bot_token="123456:test-token",
+ require_mention=True,
+ forum_auto_topic=True,
+ )
+ controller = Controller.__new__(Controller)
+ controller.config = V2Config.from_payload(
+ _config_payload(
+ telegram_payload={
+ "bot_token": "123456:test-token",
+ "require_mention": stale_telegram_config.require_mention,
+ "forum_auto_topic": stale_telegram_config.forum_auto_topic,
+ }
+ )
+ )
+ controller.im_clients = {"telegram": SimpleNamespace(config=stale_telegram_config)}
+ controller._config_mtime = None
+
+ latest_config = V2Config.from_payload(
+ _config_payload(
+ telegram_payload={
+ "bot_token": "123456:test-token",
+ "require_mention": False,
+ "forum_auto_topic": False,
+ }
+ )
+ )
+ latest_config.save()
+
+ controller._refresh_config_from_disk()
+
+ assert stale_telegram_config.require_mention is False
+ assert stale_telegram_config.forum_auto_topic is False
+
+
def test_refresh_config_updates_remote_access_for_audio_asr(tmp_path, monkeypatch) -> None:
monkeypatch.setenv("VIBE_REMOTE_HOME", str(tmp_path))
diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.py
index 921ff3fce..df73287ed 100644
--- a/tests/test_multi_platform_runtime.py
+++ b/tests/test_multi_platform_runtime.py
@@ -106,6 +106,19 @@ class _StubClient(BaseIMClient):
return text
+class _SlowStopClient(_StubClient):
+ def __init__(self, name: str):
+ super().__init__(name, run_until_stopped=True)
+ self.stop_entered = threading.Event()
+ self.finish_stop = threading.Event()
+
+ def stop(self):
+ self.stopped = True
+ self.stop_entered.set()
+ self._stop_event.set()
+ self.finish_stop.wait(timeout=5)
+
+
def test_multi_settings_manager_routes_scoped_keys(tmp_path):
manager = MultiSettingsManager(
["slack", "wechat"], settings_file=str(tmp_path / "settings.json"), primary_platform="slack"
@@ -161,6 +174,19 @@ def test_multi_im_client_remove_client_stops_and_drops_platform():
assert client.primary_platform == "wechat"
+def test_multi_im_client_remove_last_client_restores_workbench_formatter():
+ slack = _StubClient("slack")
+ client = MultiIMClient({"slack": slack}, primary_platform="slack")
+
+ removed = client.remove_client("slack")
+
+ assert removed is slack
+ assert client.clients == {}
+ assert client.primary_platform == "avibe"
+ assert client.formatter is not None
+ assert "Warning" in client.formatter.format_warning("heads up")
+
+
def test_multi_im_client_remove_pending_platform_completes_ready():
slack = _StubClient("slack")
discord = _StubClient("discord")
@@ -222,10 +248,68 @@ def test_multi_im_client_remove_client_keeps_maps_when_thread_will_not_stop():
thread.join(timeout=2)
+def test_multi_im_client_hot_remove_last_client_does_not_return_runtime():
+ slow = _SlowStopClient("slack")
+ client = MultiIMClient({"slack": slow}, primary_platform="slack")
+ returned: list[bool] = []
+ removal_errors: list[BaseException] = []
+
+ def _run() -> None:
+ client.run()
+ returned.append(True)
+
+ runtime_thread = threading.Thread(target=_run, daemon=True)
+ runtime_thread.start()
+ assert client._run_started.wait(timeout=2)
+ assert slow.started.wait(timeout=2)
+
+ def _remove() -> None:
+ try:
+ client.remove_client("slack")
+ except BaseException as exc:
+ removal_errors.append(exc)
+
+ remover = threading.Thread(target=_remove, daemon=True)
+ remover.start()
+ assert slow.stop_entered.wait(timeout=2)
+
+ deadline = time.monotonic() + 2
+ dead_platform_thread = False
+ while time.monotonic() < deadline:
+ with client._clients_lock:
+ platform_thread = client._threads.get("slack")
+ if platform_thread is not None and not platform_thread.is_alive():
+ dead_platform_thread = True
+ break
+ time.sleep(0.01)
+ assert dead_platform_thread is True
+
+ time.sleep(0.7)
+ assert runtime_thread.is_alive() is True
+ assert returned == []
+
+ slow.finish_stop.set()
+ remover.join(timeout=2)
+ assert remover.is_alive() is False
+ assert removal_errors == []
+ assert client.clients == {}
+ assert client.primary_platform == "avibe"
+ assert runtime_thread.is_alive() is True
+ assert returned == []
+
+ client.stop()
+ runtime_thread.join(timeout=2)
+ assert runtime_thread.is_alive() is False
+ assert returned == [True]
+
+
def test_multi_im_client_empty_runtime_stays_alive_until_stop():
client = MultiIMClient({}, primary_platform="avibe")
returned: list[bool] = []
+ assert client.formatter is not None
+ assert "Error" in client.formatter.format_error("boom")
+
def _run() -> None:
client.run()
returned.append(True)
diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.py
index 73d3e6114..44ce5934c 100644
--- a/tests/test_telegram_bot.py
+++ b/tests/test_telegram_bot.py
@@ -2,6 +2,8 @@ from __future__ import annotations
import asyncio
import sys
+import threading
+import time
from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, patch
@@ -14,6 +16,7 @@ from config import paths
from core import chat_discovery
from modules.agents.native_sessions import NativeResumeSession
from modules.im import MessageContext
+from modules.im.multi import MultiIMClient
from modules.im.telegram import TelegramBot
from config.v2_config import TelegramConfig
@@ -1008,3 +1011,39 @@ def test_handle_callback_query_denies_unauthorized_protected_action() -> None:
answer_mock.assert_awaited_once_with("cb-1", "Admin only", show_alert=True)
bot.on_callback_query_callback.assert_not_awaited()
+
+
+def test_remove_client_cancels_telegram_long_poll_promptly(monkeypatch) -> None:
+ poll_started = threading.Event()
+ poll_cancelled = threading.Event()
+
+ async def _get_me(*args, **kwargs):
+ return {"result": {"id": 1, "username": "vibe_remote_bot"}}
+
+ async def _get_updates(*args, **kwargs):
+ poll_started.set()
+ try:
+ await asyncio.Event().wait()
+ except asyncio.CancelledError:
+ poll_cancelled.set()
+ raise
+
+ monkeypatch.setattr("modules.im.telegram.telegram_api.get_me", _get_me)
+ monkeypatch.setattr("modules.im.telegram.telegram_api.get_updates", _get_updates)
+
+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))
+ client = MultiIMClient({"telegram": bot}, primary_platform="telegram")
+ runtime_thread = threading.Thread(target=bot.run, daemon=True)
+ runtime_thread.start()
+ client._threads["telegram"] = runtime_thread
+
+ assert poll_started.wait(timeout=2)
+
+ started = time.monotonic()
+ removed = client.remove_client("telegram")
+ elapsed = time.monotonic() - started
+
+ assert removed is bot
+ assert elapsed < 2
+ assert runtime_thread.is_alive() is False
+ assert poll_cancelled.is_set()