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(telegram): refine scope gate lifecycle
cyh0158c661d2f2
diff --git a/modules/im/telegram.py b/modules/im/telegram.pyindex d643f839a..5c3932cb5 100644--- a/modules/im/telegram.py+++ b/modules/im/telegram.py@@ -80,6 +80,12 @@ class _TelegramSettingsState:is_dm: bool+@dataclass+class _TelegramUpdateScopeGate:+ lock: asyncio.Lock+ waiters: int = 0++class TelegramBot(BaseIMClient):"""Telegram adapter using Bot API long polling."""@@ -100,7 +106,7 @@ class TelegramBot(BaseIMClient):self._loop: Optional[asyncio.AbstractEventLoop] = Noneself._update_tasks: set[asyncio.Task[Any]] = set()self._message_callback_tasks: set[asyncio.Task[Any]] = set()- self._update_scope_locks: dict[str, asyncio.Lock] = {}+ self._update_scope_gates: dict[str, _TelegramUpdateScopeGate] = {}self._cwd_prompts: dict[str, _TelegramCwdPrompt] = {}self._resume_states: dict[str, _TelegramResumeSessionState] = {}self._routing_states: dict[str, _TelegramRoutingState] = {}@@ -189,12 +195,18 @@ class TelegramBot(BaseIMClient):task.add_done_callback(self._handle_update_task_done)async def _handle_scoped_update(self, update: dict[str, Any], scope_key: str) -> None:- lock = self._update_scope_locks.get(scope_key)- if lock is None:- lock = asyncio.Lock()- self._update_scope_locks[scope_key] = lock- async with lock:- await self._handle_update(update)+ gate = self._update_scope_gates.get(scope_key)+ if gate is None:+ gate = _TelegramUpdateScopeGate(lock=asyncio.Lock())+ self._update_scope_gates[scope_key] = gate+ gate.waiters += 1+ try:+ async with gate.lock:+ await self._handle_update(update)+ finally:+ gate.waiters -= 1+ if gate.waiters == 0 and self._update_scope_gates.get(scope_key) is gate:+ self._update_scope_gates.pop(scope_key, None)def _handle_update_task_done(self, task: asyncio.Task[Any]) -> None:self._update_tasks.discard(task)@@ -213,10 +225,10 @@ class TelegramBot(BaseIMClient):await asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)async def _wait_for_message_callback_capacity(self) -> None:- if len(self._message_callback_tasks) < self._MAX_IN_FLIGHT_MESSAGE_CALLBACK_TASKS:- return- pending = tuple(self._message_callback_tasks)- if pending:+ while len(self._message_callback_tasks) >= self._MAX_IN_FLIGHT_MESSAGE_CALLBACK_TASKS:+ pending = tuple(self._message_callback_tasks)+ if not pending:+ returnawait asyncio.wait(pending, return_when=asyncio.FIRST_COMPLETED)async def _drain_task_set(self, tasks: set[asyncio.Task[Any]]) -> None:diff --git a/tests/test_telegram_bot.py b/tests/test_telegram_bot.pyindex 2146e5001..023d39c7b 100644--- a/tests/test_telegram_bot.py+++ b/tests/test_telegram_bot.py@@ -343,6 +343,28 @@ def test_spawn_update_task_keeps_same_scope_updates_ordered() -> None:assert started == [1, 2]+def test_scoped_update_gate_is_evicted_once_scope_turns_idle() -> None:+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))++ async def scenario() -> None:+ with patch.object(bot, "_handle_update", new=AsyncMock()) as handle_mock:+ await bot._handle_scoped_update(+ {+ "update_id": 1,+ "message": {+ "chat": {"id": -100123, "type": "supergroup"},+ "from": {"id": 42},+ },+ },+ "-100123:42",+ )+ handle_mock.assert_awaited_once()++ asyncio.run(asyncio.wait_for(scenario(), timeout=0.2))++ assert bot._update_scope_gates == {}++def test_wait_for_update_capacity_blocks_until_inflight_task_finishes() -> None:bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))bot._MAX_IN_FLIGHT_UPDATE_TASKS = 1@@ -416,6 +438,51 @@ def test_spawn_message_callback_task_waits_for_capacity() -> None:asyncio.run(asyncio.wait_for(scenario(), timeout=0.2))+def test_spawn_message_callback_task_rechecks_capacity_after_wakeup() -> None:+ bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))+ bot._MAX_IN_FLIGHT_MESSAGE_CALLBACK_TASKS = 1+ first_release = asyncio.Event()+ second_release = asyncio.Event()+ first_started = asyncio.Event()+ second_started = asyncio.Event()+ order: list[str] = []++ async def running_callback(_context, text: str) -> None:+ order.append(text)+ if text == "first":+ first_started.set()+ await first_release.wait()+ elif text == "second":+ second_started.set()+ await second_release.wait()++ async def scenario() -> None:+ bot.on_message_callback = running_callback+ context = MessageContext(user_id="42", channel_id="-100123", platform="telegram")+ await bot._spawn_message_callback_task(context, "first")+ await first_started.wait()++ second_waiter = asyncio.create_task(bot._spawn_message_callback_task(context, "second"))+ third_waiter = asyncio.create_task(bot._spawn_message_callback_task(context, "third"))+ await asyncio.sleep(0)+ assert not second_waiter.done()+ assert not third_waiter.done()++ first_release.set()+ await second_started.wait()+ await asyncio.sleep(0)+ assert second_waiter.done()+ assert not third_waiter.done()++ second_release.set()+ await third_waiter+ await bot._drain_background_tasks()++ asyncio.run(asyncio.wait_for(scenario(), timeout=0.2))++ assert order == ["first", "second", "third"]++def test_pending_cwd_prompt_consumes_next_plain_message() -> None:bot = TelegramBot(TelegramConfig(bot_token="123456:test-token"))context = MessageContext(