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(wechat): defer bind menu hint until first message
cyh0de33dde3573
diff --git a/config/v2_settings.py b/config/v2_settings.pyindex 1256273b8..7f2ecbfc8 100644--- a/config/v2_settings.py+++ b/config/v2_settings.py@@ -118,6 +118,7 @@ class UserSettings:custom_cwd: Optional[str] = Nonerouting: RoutingSettings = field(default_factory=RoutingSettings)dm_chat_id: str = ""+ pending_bind_menu_hint: bool = False@dataclass@@ -242,6 +243,7 @@ def parse_settings_payload(payload: dict) -> tuple[SettingsState, bool]:custom_cwd=up.get("custom_cwd"),routing=_parse_routing(up.get("routing") or {}),dm_chat_id=up.get("dm_chat_id", ""),+ pending_bind_menu_hint=bool(up.get("pending_bind_menu_hint", False)),)else:raw_channels = payload.get("channels") or {}@@ -278,6 +280,7 @@ def parse_settings_payload(payload: dict) -> tuple[SettingsState, bool]:custom_cwd=up.get("custom_cwd"),routing=_parse_routing(up.get("routing") or {}),dm_chat_id=up.get("dm_chat_id", ""),+ pending_bind_menu_hint=bool(up.get("pending_bind_menu_hint", False)),)raw_codes = payload.get("bind_codes") or []diff --git a/modules/im/wechat.py b/modules/im/wechat.pyindex 6facc8122..4ac1f4c93 100644--- a/modules/im/wechat.py+++ b/modules/im/wechat.py@@ -1214,6 +1214,36 @@ class WeChatBot(BaseIMClient):except Exception:logger.exception("WeChat message callback task failed")+ def _consume_pending_bind_menu_hint(self, user_id: str) -> bool:+ manager = self.settings_manager+ if manager is None:+ return False+ store_getter = getattr(manager, "get_store", None)+ if not callable(store_getter):+ return False+ try:+ store = store_getter()+ user = store.get_user(user_id, platform="wechat")+ if user is None or not user.pending_bind_menu_hint:+ return False+ user.pending_bind_menu_hint = False+ store.update_user(user_id, user, platform="wechat")+ manager_reload = getattr(manager, "_reload_if_changed", None)+ if callable(manager_reload):+ manager_reload()+ return True+ except Exception as exc:+ logger.warning("Failed to consume WeChat bind menu hint for %s: %s", user_id, exc)+ return False++ async def _send_bind_menu_hint_if_pending(self, context: MessageContext) -> None:+ if not self._consume_pending_bind_menu_hint(context.user_id):+ return+ try:+ await self.send_message(context, self._t("bind.menuHintStart", context.channel_id))+ except Exception as exc:+ logger.warning("Failed to send WeChat bind menu hint to %s: %s", context.user_id, exc)+async def _process_inbound_message(self, msg: dict) -> None:"""Convert an iLink message to MessageContext and dispatch."""message_id = str(msg.get("message_id", ""))@@ -1285,6 +1315,8 @@ class WeChatBot(BaseIMClient):logger.error("Failed to send auth denial: %s", exc)return+ await self._send_bind_menu_hint_if_pending(context)+# Try slash command dispatch firstallow_plain_bind = self.should_allow_plain_bind(user_id=from_user,diff --git a/storage/settings_service.py b/storage/settings_service.pyindex f3fa90437..ec58abf90 100644--- a/storage/settings_service.py+++ b/storage/settings_service.py@@ -143,6 +143,7 @@ class SQLiteSettingsService:{"bound_at": item.bound_at or "","dm_chat_id": item.dm_chat_id or "",+ "pending_bind_menu_hint": bool(item.pending_bind_menu_hint),"show_message_types": item.show_message_types,"routing": routing,}@@ -220,6 +221,7 @@ class SQLiteSettingsService:custom_cwd=row["workdir"],routing=_routing_from_row(row, payload),dm_chat_id=str(payload.get("dm_chat_id") or ""),+ pending_bind_menu_hint=bool(payload.get("pending_bind_menu_hint", False)),)return resultdiff --git a/tests/test_sqlite_settings_store.py b/tests/test_sqlite_settings_store.pyindex 2d7fe2baf..14a38eb41 100644--- a/tests/test_sqlite_settings_store.py+++ b/tests/test_sqlite_settings_store.py@@ -66,6 +66,30 @@ def test_settings_store_reloads_external_sqlite_writes(tmp_path: Path) -> None:store.close()+def test_settings_store_preserves_user_pending_bind_menu_hint(tmp_path: Path) -> None:+ db_path = tmp_path / "vibe.sqlite"+ run_migrations(db_path)+ service = SQLiteSettingsService(db_path)+ try:+ service.save_state(+ SettingsState(+ users={+ "wechat::wx-user": UserSettings(+ display_name="WeChat User",+ pending_bind_menu_hint=True,+ ),+ }+ )+ )++ state = service.load_state()+ finally:+ service.close()++ user = state.users["wechat::wx-user"]+ assert user.pending_bind_menu_hint is True++def test_settings_save_preserves_observed_scope_metadata(tmp_path: Path) -> None:db_path = tmp_path / "vibe.sqlite"run_migrations(db_path)diff --git a/tests/test_ui_server_fastapi.py b/tests/test_ui_server_fastapi.pyindex 6083dc586..a9beb962d 100644--- a/tests/test_ui_server_fastapi.py+++ b/tests/test_ui_server_fastapi.py@@ -1,5 +1,4 @@import pytest-from unittest.mock import Mockfrom vibe.ui_compat import CompatApp, normalize_response, route_path_to_fastapi, run_maybe_async, requestfrom starlette.websockets import WebSocketDisconnect@@ -91,7 +90,9 @@ def test_run_maybe_async_offloads_sync_handlers_without_losing_context():assert tick == "tick"-def test_wechat_qr_poll_schedules_bind_hint_without_awaiting_send(monkeypatch):+def test_wechat_qr_poll_marks_bind_hint_without_scheduling_send(monkeypatch):+ from vibe import runtime+class _Auth:async def poll_status(self, session_key):assert session_key == "qr-session"@@ -102,17 +103,14 @@ def test_wechat_qr_poll_schedules_bind_hint_without_awaiting_send(monkeypatch):"user_id": "wx-user",}- scheduled = []+ bound_users = []+ runtime.ensure_config()monkeypatch.setattr(ui_server, "_get_wechat_auth", lambda: _Auth())- monkeypatch.setattr(- ui_server,- "_schedule_wechat_bind_success_hint",- lambda **kwargs: scheduled.append(kwargs),- )monkeypatch.setattr("vibe.api.auto_bind_wechat_user",- lambda user_id: {"ok": True, "already_bound": False, "is_admin": True},+ lambda user_id: bound_users.append(user_id)+ or {"ok": True, "already_bound": False, "is_admin": True, "pending_bind_menu_hint": True},)client = app.test_client()@@ -124,39 +122,4 @@ def test_wechat_qr_poll_schedules_bind_hint_without_awaiting_send(monkeypatch):assert response.status_code == 200assert response.get_json()["status"] == "confirmed"- assert scheduled == [- {- "user_id": "wx-user",- "bot_token": "wechat-token",- "base_url": "https://wechat.example.com",- "already_bound": False,- "is_admin": True,- }- ]---def test_wechat_bind_hint_scheduler_uses_persistent_loop(monkeypatch):- scheduled_coroutines = []- fake_loop = object()- fake_future = Mock()-- monkeypatch.setattr(ui_server, "_ensure_wechat_hint_loop", lambda: fake_loop)- monkeypatch.setattr(- ui_server.asyncio,- "run_coroutine_threadsafe",- lambda coro, loop: scheduled_coroutines.append((coro, loop)) or fake_future,- )-- ui_server._schedule_wechat_bind_success_hint(- user_id="wx-user",- bot_token="wechat-token",- base_url="https://wechat.example.com",- already_bound=False,- is_admin=False,- )-- assert len(scheduled_coroutines) == 1- assert scheduled_coroutines[0][1] is fake_loop- assert scheduled_coroutines[0][0].cr_code.co_name == "_send_hint"- fake_future.add_done_callback.assert_called_once()- scheduled_coroutines[0][0].close()+ assert bound_users == ["wx-user"]diff --git a/tests/test_wechat_auth.py b/tests/test_wechat_auth.pyindex 1328a5ed6..15d70f4da 100644--- a/tests/test_wechat_auth.py+++ b/tests/test_wechat_auth.py@@ -1,11 +1,11 @@import sysimport unittest-from types import SimpleNamespacefrom pathlib import Pathfrom unittest.mock import AsyncMock, patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from config.v2_settings import SettingsStorefrom modules.im.wechat_auth import WeChatAuthManagerfrom vibe import api as vibe_api@@ -53,85 +53,29 @@ class WeChatAuthManagerTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(result["status"], "expired")self.assertIn("start a new login", result["message"].lower())- async def test_send_wechat_bind_success_hint_uses_start_instruction(self):- sent = {}-- async def fake_send_message(base_url, token, to_user_id, context_token, item_list):- sent.update(- {- "base_url": base_url,- "token": token,- "to_user_id": to_user_id,- "context_token": context_token,- "item_list": item_list,- }- )- return {}-- config = SimpleNamespace(language="zh")-- with patch("vibe.api.load_config", return_value=config), patch(- "modules.im.wechat_api.send_message",- new=AsyncMock(side_effect=fake_send_message),- ):- result = await vibe_api.send_wechat_bind_success_hint(- user_id="wx-user",- bot_token="token",- base_url="https://wechat.example.com",- is_admin=True,- )-- self.assertTrue(result)- self.assertEqual(sent["to_user_id"], "wx-user")- self.assertIn("绑定成功", sent["item_list"][0]["text_item"]["text"])- self.assertIn("第一个用户", sent["item_list"][0]["text_item"]["text"])- self.assertIn("/start", sent["item_list"][0]["text_item"]["text"])-- async def test_send_wechat_bind_success_hint_uses_neutral_success_for_non_admin(self):- sent = {}-- async def fake_send_message(base_url, token, to_user_id, context_token, item_list):- sent["text"] = item_list[0]["text_item"]["text"]- return {}-- config = SimpleNamespace(language="zh")-- with patch("vibe.api.load_config", return_value=config), patch(- "modules.im.wechat_api.send_message",- new=AsyncMock(side_effect=fake_send_message),- ):- result = await vibe_api.send_wechat_bind_success_hint(- user_id="wx-user",- bot_token="token",- base_url="https://wechat.example.com",- is_admin=False,- )-- self.assertTrue(result)- self.assertIn("绑定成功", sent["text"])- self.assertNotIn("第一个用户", sent["text"])- self.assertIn("/start", sent["text"])-- async def test_send_wechat_bind_success_hint_handles_existing_binding(self):- sent = {}-- async def fake_send_message(base_url, token, to_user_id, context_token, item_list):- sent["text"] = item_list[0]["text_item"]["text"]- return {}-- config = SimpleNamespace(language="zh")-- with patch("vibe.api.load_config", return_value=config), patch(- "modules.im.wechat_api.send_message",- new=AsyncMock(side_effect=fake_send_message),- ):- result = await vibe_api.send_wechat_bind_success_hint(- user_id="wx-user",- bot_token="token",- base_url="https://wechat.example.com",- already_bound=True,- )-- self.assertTrue(result)- self.assertIn("已经绑定过了", sent["text"])- self.assertIn("/start", sent["text"])+ async def test_auto_bind_wechat_user_marks_one_time_menu_hint_pending(self):+ SettingsStore.reset_instance()++ with patch("vibe.api.load_config") as load_config:+ load_config.return_value.runtime.default_cwd = "/tmp/vibe"+ load_config.return_value.agents.default_backend = "opencode"+ result = vibe_api.auto_bind_wechat_user("wx-user")++ self.assertTrue(result["ok"])+ self.assertFalse(result["already_bound"])+ self.assertTrue(result["pending_bind_menu_hint"])++ user = SettingsStore.get_instance().get_user("wx-user", platform="wechat")+ self.assertIsNotNone(user)+ self.assertTrue(user.pending_bind_menu_hint) # type: ignore[union-attr]++ async def test_auto_bind_wechat_user_does_not_rearm_existing_user_hint(self):+ SettingsStore.reset_instance()+ store = SettingsStore.get_instance()+ store.add_user("wx-user", "WeChat User", platform="wechat")++ result = vibe_api.auto_bind_wechat_user("wx-user")++ self.assertTrue(result["ok"])+ self.assertTrue(result["already_bound"])+ self.assertFalse(result["pending_bind_menu_hint"])diff --git a/tests/test_wechat_bot.py b/tests/test_wechat_bot.pyindex d14b761ec..ab2414b31 100644--- a/tests/test_wechat_bot.py+++ b/tests/test_wechat_bot.py@@ -10,10 +10,12 @@ from unittest.mock import patchsys.path.insert(0, str(Path(__file__).resolve().parents[1]))+from config.v2_settings import SettingsStore, UserSettingsfrom core.auth import AuthResultfrom modules.im import MessageContextfrom modules.im.wechat import WeChatBot, WeChatConfig, _get_updates_error_codefrom modules.im import wechat_api as wechat_api_module+from modules.settings_manager import SettingsManagerclass WeChatBotTests(unittest.IsolatedAsyncioTestCase):@@ -262,6 +264,100 @@ class WeChatBotTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(args[0].user_id, "user-1")self.assertEqual(args[1], "hi")+ async def test_process_inbound_message_sends_pending_bind_menu_hint_once(self):+ SettingsStore.reset_instance()+ store = SettingsStore.get_instance()+ store.set_users_for_platform(+ "wechat",+ {+ "user-1": UserSettings(+ display_name="WeChat User",+ enabled=True,+ pending_bind_menu_hint=True,+ )+ },+ )+ store.save()++ bot = self._make_bot()+ bot.set_settings_manager(SettingsManager(platform="wechat"))+ bot.check_authorization = lambda **kwargs: AuthResult(allowed=True, is_dm=True)+ bot.dispatch_text_command = AsyncMock(return_value=False)+ bot._process_media_items = AsyncMock(return_value=None)+ bot.on_message_callback = AsyncMock()+ bot.send_message = AsyncMock(return_value="wc-hint")++ msg = {+ "message_id": "mid-hint-1",+ "from_user_id": "user-1",+ "context_token": "ctx-1",+ "item_list": [{"type": 1, "text_item": {"text": "hi"}}],+ }++ await bot._process_inbound_message(msg)+ await asyncio.gather(*tuple(bot._message_callback_tasks))++ bot.send_message.assert_awaited_once()+ self.assertIn("/start", bot.send_message.await_args.args[1]) # type: ignore[union-attr]+ bot.on_message_callback.assert_awaited_once()+ self.assertEqual(bot.on_message_callback.await_args.args[1], "hi") # type: ignore[union-attr]+ user = SettingsStore.get_instance().get_user("user-1", platform="wechat")+ self.assertIsNotNone(user)+ self.assertFalse(user.pending_bind_menu_hint) # type: ignore[union-attr]++ bot.send_message.reset_mock()+ bot.on_message_callback.reset_mock()+ second_msg = {+ "message_id": "mid-hint-2",+ "from_user_id": "user-1",+ "context_token": "ctx-2",+ "item_list": [{"type": 1, "text_item": {"text": "again"}}],+ }++ await bot._process_inbound_message(second_msg)+ await asyncio.gather(*tuple(bot._message_callback_tasks))++ bot.send_message.assert_not_awaited()+ bot.on_message_callback.assert_awaited_once()+ self.assertEqual(bot.on_message_callback.await_args.args[1], "again") # type: ignore[union-attr]++ async def test_process_inbound_message_sends_pending_bind_menu_hint_before_command(self):+ SettingsStore.reset_instance()+ store = SettingsStore.get_instance()+ store.set_users_for_platform(+ "wechat",+ {+ "user-1": UserSettings(+ display_name="WeChat User",+ enabled=True,+ pending_bind_menu_hint=True,+ )+ },+ )+ store.save()++ bot = self._make_bot()+ bot.set_settings_manager(SettingsManager(platform="wechat"))+ bot.check_authorization = lambda **kwargs: AuthResult(allowed=True, is_dm=True)+ bot._process_media_items = AsyncMock(return_value=None)+ bot.send_message = AsyncMock(return_value="wc-hint")+ bot.dispatch_text_command = AsyncMock(return_value=True)+ bot.on_message_callback = AsyncMock()++ msg = {+ "message_id": "mid-hint-command",+ "from_user_id": "user-1",+ "context_token": "ctx-1",+ "item_list": [{"type": 1, "text_item": {"text": "/start"}}],+ }++ await bot._process_inbound_message(msg)++ bot.send_message.assert_awaited_once()+ self.assertIn("/start", bot.send_message.await_args.args[1]) # type: ignore[union-attr]+ bot.dispatch_text_command.assert_awaited_once()+ bot.on_message_callback.assert_not_called()+async def test_process_inbound_message_persists_context_token(self):with tempfile.TemporaryDirectory() as tmpdir:with patch.dict("os.environ", {"VIBE_REMOTE_HOME": tmpdir}):diff --git a/vibe/api.py b/vibe/api.pyindex ee6a1b94c..0a5c152c9 100644--- a/vibe/api.py+++ b/vibe/api.py@@ -4355,6 +4355,7 @@ def save_users(payload: dict) -> dict:custom_cwd=up.get("custom_cwd"),routing=_parse_routing(_normalize_routing_payload(up.get("routing") or {})),dm_chat_id=existing.dm_chat_id if existing else "",+ pending_bind_menu_hint=existing.pending_bind_menu_hint if existing else False,)# Merge instead of replace: update existing users and add new ones,@@ -4452,7 +4453,7 @@ def auto_bind_wechat_user(user_id: str) -> dict:WeChat is 1:1 DM only — no channels, no bind codes needed.The QR scan itself is the authentication, so we auto-bind the user- as admin with default settings.+ and mark the one-time menu hint to be sent on the user's next message."""from config.v2_settings import _now_iso@@ -4463,7 +4464,12 @@ def auto_bind_wechat_user(user_id: str) -> dict:if store.is_bound_user(user_id, platform=platform):logger.info("WeChat user %s already bound, skipping auto-bind", user_id)existing = store.get_user(user_id, platform=platform)- return {"ok": True, "already_bound": True, "is_admin": bool(getattr(existing, "is_admin", False))}+ return {+ "ok": True,+ "already_bound": True,+ "is_admin": bool(getattr(existing, "is_admin", False)),+ "pending_bind_menu_hint": bool(getattr(existing, "pending_bind_menu_hint", False)),+ }config = load_config()is_admin = not store.has_any_admin(platform=platform)@@ -4474,6 +4480,7 @@ def auto_bind_wechat_user(user_id: str) -> dict:enabled=True,custom_cwd=config.runtime.default_cwd or None,routing=RoutingSettings(agent_backend=config.agents.default_backend or None),+ pending_bind_menu_hint=True,)current_users = store.get_users_for_platform(platform)@@ -4482,58 +4489,7 @@ def auto_bind_wechat_user(user_id: str) -> dict:store.save()logger.info("Auto-bound WeChat user %s (admin=%s)", user_id, is_admin)- return {"ok": True, "already_bound": False, "is_admin": is_admin}---async def send_wechat_bind_success_hint(- *,- user_id: str,- bot_token: str,- base_url: str,- context_token: str = "",- already_bound: bool = False,- is_admin: bool = False,-) -> bool:- """Best-effort post-bind hint for WeChat QR login.-- QR login is WeChat's bind flow, so users do not send a bind code. Send the- same menu-discovery hint immediately when the upstream API accepts it.- """- if not user_id or not bot_token:- return False-- from modules.im import wechat_api- from modules.im.wechat import WeChatConfig, WeChatBot- from vibe.i18n import t as i18n_t-- config = load_config()- lang = getattr(config, "language", "en")- status_line = (- i18n_t("bind.alreadyBound", lang)- if already_bound- else i18n_t("bind.successAdmin" if is_admin else "bind.success", lang, name=user_id)- )- message = "\n\n".join(- [- status_line,- i18n_t("bind.menuHintStart", lang),- ]- )- text = WeChatBot(WeChatConfig(bot_token=bot_token, base_url=base_url)).format_markdown(message)- item_list = [{"type": 1, "text_item": {"text": text}}]-- try:- await wechat_api.send_message(- base_url,- bot_token,- user_id,- context_token,- item_list,- )- return True- except Exception as exc:- logger.warning("Failed to send WeChat bind success hint to %s: %s", user_id, exc)- return False+ return {"ok": True, "already_bound": False, "is_admin": is_admin, "pending_bind_menu_hint": True}# ---------------------------------------------------------------------------diff --git a/vibe/ui_server.py b/vibe/ui_server.pyindex 979fdc82c..d90bf133d 100644--- a/vibe/ui_server.py+++ b/vibe/ui_server.py@@ -1,4 +1,3 @@-import asyncioimport base64import hashlibimport hmac@@ -12,8 +11,8 @@ import secretsimport shutilimport socketimport subprocess-import timeimport threading+import timefrom datetime import datetimefrom pathlib import Pathfrom typing import Any, Callable@@ -36,9 +35,6 @@ app = CompatApp(title="Vibe Remote UI", docs_url=None, redoc_url=None, openapi_u# Global server instance for graceful shutdown on reload_server = None-_wechat_hint_loop: asyncio.AbstractEventLoop | None = None-_wechat_hint_loop_thread: threading.Thread | None = None-_wechat_hint_loop_lock = threading.Lock()STRUCTURED_LOG_PATTERN = re.compile(r"^(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2},\d{3})\s+-\s+([\w.]+)\s+-\s+(\w+)\s+-\s+(.*)$")LEVEL_HINT_PATTERN = re.compile(r"\b(DEBUG|INFO|WARNING|ERROR|CRITICAL)\b")@@ -784,60 +780,6 @@ def _is_remote_access_request(config: V2Config) -> bool:return _normalized_host(request.host) == public_host-def _ensure_wechat_hint_loop() -> asyncio.AbstractEventLoop:- global _wechat_hint_loop, _wechat_hint_loop_thread- with _wechat_hint_loop_lock:- if _wechat_hint_loop is not None and not _wechat_hint_loop.is_closed():- return _wechat_hint_loop-- loop = asyncio.new_event_loop()-- def _runner() -> None:- asyncio.set_event_loop(loop)- loop.run_forever()-- _wechat_hint_loop = loop- _wechat_hint_loop_thread = threading.Thread(target=_runner, daemon=True, name="wechat-bind-hints")- _wechat_hint_loop_thread.start()- return loop---def _schedule_wechat_bind_success_hint(- *,- user_id: str,- bot_token: str,- base_url: str,- already_bound: bool,- is_admin: bool,-) -> None:- if not user_id or not bot_token:- return-- async def _send_hint() -> None:- try:- from vibe import api as vibe_api-- await vibe_api.send_wechat_bind_success_hint(- user_id=user_id,- bot_token=bot_token,- base_url=base_url,- already_bound=already_bound,- is_admin=is_admin,- )- except Exception as exc:- logger.warning("Failed to send WeChat bind success hint in background: %s", exc)-- future = asyncio.run_coroutine_threadsafe(_send_hint(), _ensure_wechat_hint_loop())-- def _log_failure(done_future) -> None:- try:- done_future.result()- except Exception as exc:- logger.warning("WeChat bind success hint task failed: %s", exc)-- future.add_done_callback(_log_failure)--def _remote_access_public_host(config: V2Config) -> str | None:public_url = (config.remote_access.vibe_cloud.public_url or "").strip()if not public_url:@@ -1727,14 +1669,7 @@ async def wechat_qr_login_poll():try:from vibe import api as vibe_api- bind_result = vibe_api.auto_bind_wechat_user(user_id)- _schedule_wechat_bind_success_hint(- user_id=user_id,- bot_token=result.get("bot_token", ""),- base_url=result.get("base_url") or payload.get("base_url", "https://ilinkai.weixin.qq.com"),- already_bound=bool(bind_result.get("already_bound")),- is_admin=bool(bind_result.get("is_admin")),- )+ vibe_api.auto_bind_wechat_user(user_id)except Exception as e:logger.warning("Failed to auto-bind WeChat user: %s", e)