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
feat(wechat): add text-based resume recovery
cyh7d63c27be04f
diff --git a/core/controller.py b/core/controller.pyindex 2d8a99138..312493d10 100644--- a/core/controller.py+++ b/core/controller.py@@ -300,6 +300,7 @@ class Controller:"new": self._dispatch_to_controller_loop(self.command_handler.handle_new),"cwd": self._dispatch_to_controller_loop(self.command_handler.handle_cwd),"set_cwd": self._dispatch_to_controller_loop(self.command_handler.handle_set_cwd),+ "resume": self._dispatch_to_controller_loop(self.command_handler.handle_resume),"settings": self._dispatch_to_controller_loop(self.settings_handler.handle_settings),"stop": self._dispatch_to_controller_loop(self.command_handler.handle_stop),"bind": self._dispatch_to_controller_loop(self.command_handler.handle_bind),diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.pyindex 3e6dc6eb0..836d1e4e1 100644--- a/core/handlers/command_handlers.py+++ b/core/handlers/command_handlers.py@@ -1,9 +1,11 @@"""Command handlers for bot commands like /start, /new, /cwd, etc."""-import osimport logging-from typing import Optional+import os+import time+from typing import Any, Optionalfrom modules.agents import get_agent_display_name+from modules.agents.native_sessions import NativeResumeSessionfrom modules.agents.base import AgentRequestfrom modules.im import MessageContext, InlineKeyboard, InlineButton@@ -19,6 +21,9 @@ class CommandHandlers(BaseHandler):"""Initialize with reference to main controller"""super().__init__(controller)self.session_manager = controller.session_manager+ self._resume_snapshots: dict[str, dict[str, Any]] = {}+ self._resume_snapshot_ttl_seconds = 600.0+ self._wechat_resume_page_size = 5def _get_channel_context(self, context: MessageContext) -> MessageContext:"""Get context for channel messages (no thread)"""@@ -61,6 +66,7 @@ class CommandHandlers(BaseHandler):self._t("command.start.commandStart"),self._t("command.start.commandCwd"),self._t("command.start.commandSetCwd"),+ self._t("command.start.commandResume"),self._t("command.start.commandStop", agent=agent_display_name),]if not supports_threads:@@ -68,6 +74,279 @@ class CommandHandlers(BaseHandler):lines.extend(commands)return "\n".join(line for line in lines if line)+ def _normalize_resume_agent(self, value: str) -> Optional[str]:+ normalized = (value or "").strip().lower()+ aliases = {+ "oc": "opencode",+ "opencode": "opencode",+ "open-code": "opencode",+ "cc": "claude",+ "claude": "claude",+ "claudecode": "claude",+ "claude-code": "claude",+ "cx": "codex",+ "codex": "codex",+ }+ return aliases.get(normalized)++ def _get_resume_snapshot_key(self, context: MessageContext) -> str:+ platform = context.platform or (context.platform_specific or {}).get("platform") or self.config.platform+ return f"{platform}::{self._get_settings_key(context)}"++ def _store_resume_snapshot(+ self,+ context: MessageContext,+ *,+ items: list[NativeResumeSession],+ page: int,+ total: int,+ working_path: str,+ ) -> None:+ self._resume_snapshots[self._get_resume_snapshot_key(context)] = {+ "stored_at": time.time(),+ "items": list(items),+ "page": page,+ "total": total,+ "working_path": working_path,+ }++ def _get_resume_snapshot(self, context: MessageContext) -> Optional[dict[str, Any]]:+ snapshot = self._resume_snapshots.get(self._get_resume_snapshot_key(context))+ if not snapshot:+ return None+ if time.time() - float(snapshot.get("stored_at", 0.0)) > self._resume_snapshot_ttl_seconds:+ self._resume_snapshots.pop(self._get_resume_snapshot_key(context), None)+ return None+ if snapshot.get("working_path") != self.controller.get_cwd(context):+ self._resume_snapshots.pop(self._get_resume_snapshot_key(context), None)+ return None+ return snapshot++ def _list_recent_native_sessions(+ self,+ context: MessageContext,+ *,+ limit: int = 100,+ ) -> tuple[str, list[NativeResumeSession]]:+ working_path = self.controller.get_cwd(context)+ native_session_service = getattr(self.controller, "native_session_service", None)+ if native_session_service is None:+ return working_path, []+ return working_path, native_session_service.list_recent_sessions(working_path, limit=limit)++ @staticmethod+ def _format_resume_time(item: NativeResumeSession) -> str:+ dt = item.updated_at or item.created_at+ if dt is None:+ return "--"+ return dt.strftime("%m-%d %H:%M")++ @staticmethod+ def _format_resume_tail(item: NativeResumeSession) -> str:+ preview = (item.last_agent_tail or item.last_agent_message or "").strip()+ if preview:+ return preview+ suffix = item.native_session_id[-15:] if len(item.native_session_id) > 15 else item.native_session_id+ return f"...{suffix}"++ async def _send_wechat_resume_usage(self, context: MessageContext, *, include_snapshot_expired: bool = False) -> None:+ channel_context = self._get_channel_context(context)+ lines = []+ if include_snapshot_expired:+ lines.append(f"⏮️ {self._t('command.resume.snapshotExpired')}")+ lines.append("")+ lines.extend(+ [+ self._t("command.resume.usageTitle"),+ self._t("command.resume.usageList"),+ self._t("command.resume.usagePick"),+ self._t("command.resume.usageMore"),+ self._t("command.resume.usageLatest"),+ self._t("command.resume.usageManual"),+ ]+ )+ await self._get_im_client(channel_context).send_message(channel_context, "\n".join(lines))++ async def _send_wechat_resume_page(self, context: MessageContext, *, page: int) -> None:+ page_size = self._wechat_resume_page_size+ working_path, sessions = self._list_recent_native_sessions(context, limit=100)+ channel_context = self._get_channel_context(context)+ if not sessions:+ await self._get_im_client(channel_context).send_message(+ channel_context,+ "\n".join(+ [+ f"⏮️ {self._t('command.resume.noStoredSessions')}",+ "",+ self._t("command.resume.usageManual"),+ ]+ ),+ )+ return++ total = len(sessions)+ page_count = max(1, (total + page_size - 1) // page_size)+ if page < 1:+ page = 1+ if page > page_count:+ await self._get_im_client(channel_context).send_message(+ channel_context,+ f"⏮️ {self._t('command.resume.noMorePages')}",+ )+ return++ start = (page - 1) * page_size+ page_items = sessions[start : start + page_size]+ self._store_resume_snapshot(context, items=page_items, page=page, total=total, working_path=working_path)++ lines = [+ f"⏮️ {self._t('command.resume.listTitle')}",+ self._t("command.resume.listPage", page=page, total=page_count),+ "",+ ]+ for idx, item in enumerate(page_items, start=1):+ lines.append(+ self._t(+ "command.resume.listItemTitle",+ index=idx,+ prefix=item.agent_prefix,+ preview=self._format_resume_tail(item),+ )+ )+ lines.append(self._t("command.resume.listItemTime", time=self._format_resume_time(item)))+ lines.append("")++ if lines and not lines[-1]:+ lines.pop()++ lines.extend(+ [+ "",+ self._t("command.resume.usagePick"),+ self._t("command.resume.usageMore"),+ self._t("command.resume.usageLatest"),+ self._t("command.resume.usageManual"),+ ]+ )++ await self._get_im_client(channel_context).send_message(channel_context, "\n".join(lines))++ async def _handle_wechat_resume_selection(self, context: MessageContext, *, selection: int) -> None:+ snapshot = self._get_resume_snapshot(context)+ if not snapshot:+ await self._send_wechat_resume_usage(context, include_snapshot_expired=True)+ return++ items = snapshot.get("items") or []+ if not isinstance(items, list) or selection < 1 or selection > len(items):+ channel_context = self._get_channel_context(context)+ await self._get_im_client(channel_context).send_message(+ channel_context,+ f"⏮️ {self._t('command.resume.invalidSelection')}",+ )+ return++ item = items[selection - 1]+ if not isinstance(item, NativeResumeSession):+ await self._send_wechat_resume_usage(context, include_snapshot_expired=True)+ return++ await self.controller.session_handler.handle_resume_session_submission(+ user_id=context.user_id,+ channel_id=context.channel_id,+ thread_id=context.thread_id,+ agent=item.agent,+ session_id=item.native_session_id,+ host_message_ts=context.message_id,+ is_dm=bool((context.platform_specific or {}).get("is_dm", False)),+ platform=context.platform or (context.platform_specific or {}).get("platform") or self.config.platform,+ )++ async def _handle_wechat_resume_latest(self, context: MessageContext, *, agent: Optional[str] = None) -> None:+ _, sessions = self._list_recent_native_sessions(context, limit=100)+ if agent:+ sessions = [item for item in sessions if item.agent == agent]+ if not sessions:+ channel_context = self._get_channel_context(context)+ key = "command.resume.noStoredSessionsForBackend" if agent else "command.resume.noStoredSessions"+ kwargs = {"backend": agent} if agent else {}+ await self._get_im_client(channel_context).send_message(+ channel_context,+ f"⏮️ {self._t(key, **kwargs)}",+ )+ return++ item = sessions[0]+ await self.controller.session_handler.handle_resume_session_submission(+ user_id=context.user_id,+ channel_id=context.channel_id,+ thread_id=context.thread_id,+ agent=item.agent,+ session_id=item.native_session_id,+ host_message_ts=context.message_id,+ is_dm=bool((context.platform_specific or {}).get("is_dm", False)),+ platform=context.platform or (context.platform_specific or {}).get("platform") or self.config.platform,+ )++ async def _handle_wechat_resume(self, context: MessageContext, args: str) -> None:+ stripped_args = args.strip()+ if not stripped_args:+ await self._send_wechat_resume_page(context, page=1)+ return++ parts = stripped_args.split()+ head = parts[0].lower()++ if head.isdigit():+ await self._handle_wechat_resume_selection(context, selection=int(head))+ return++ if head == "more":+ snapshot = self._get_resume_snapshot(context)+ if not snapshot:+ await self._send_wechat_resume_usage(context, include_snapshot_expired=True)+ return+ page = int(snapshot.get("page", 1)) + 1+ await self._send_wechat_resume_page(context, page=page)+ return++ if head == "latest":+ agent = self._normalize_resume_agent(parts[1]) if len(parts) > 1 else None+ if len(parts) > 1 and not agent:+ channel_context = self._get_channel_context(context)+ await self._get_im_client(channel_context).send_message(+ channel_context,+ f"⏮️ {self._t('command.resume.unknownBackend')}",+ )+ return+ await self._handle_wechat_resume_latest(context, agent=agent)+ return++ agent = self._normalize_resume_agent(head)+ if agent:+ session_id = stripped_args[len(parts[0]) :].strip()+ if not session_id:+ await self._send_wechat_resume_usage(context)+ return+ await self.controller.session_handler.handle_resume_session_submission(+ user_id=context.user_id,+ channel_id=context.channel_id,+ thread_id=context.thread_id,+ agent=agent,+ session_id=session_id,+ host_message_ts=context.message_id,+ is_dm=bool((context.platform_specific or {}).get("is_dm", False)),+ platform=context.platform or (context.platform_specific or {}).get("platform") or self.config.platform,+ )+ return++ channel_context = self._get_channel_context(context)+ await self._get_im_client(channel_context).send_message(+ channel_context,+ f"⏮️ {self._t('command.resume.unknownCommand')}",+ )+ await self._send_wechat_resume_usage(context)+async def handle_start(self, context: MessageContext, args: str = ""):"""Handle /start command with interactive buttons"""im_client = self._get_im_client(context)@@ -379,14 +658,15 @@ class CommandHandlers(BaseHandler):f"📂 {self._t('command.cwd.clickButton')}",)- async def handle_resume(self, context: MessageContext):+ async def handle_resume(self, context: MessageContext, args: str = ""):"""Open resume-session modal (Slack) or explain availability."""platform = context.platform or (context.platform_specific or {}).get("platform") or self.config.platformim_client = self._get_im_client(context)- working_path = self.controller.get_cwd(context)- native_session_service = getattr(self.controller, "native_session_service", None)- limit = 25 if platform == "discord" else 100- sessions = native_session_service.list_recent_sessions(working_path, limit=limit) if native_session_service else []+ if platform == "wechat":+ await self._handle_wechat_resume(context, args)+ return++ working_path, sessions = self._list_recent_native_sessions(context, limit=25 if platform == "discord" else 100)if platform == "discord":interaction = context.platform_specific.get("interaction") if context.platform_specific else Noneif interaction and hasattr(im_client, "open_resume_session_modal"):diff --git a/tests/test_command_handler_user_names.py b/tests/test_command_handler_user_names.pyindex 9010c9301..f27990c74 100644--- a/tests/test_command_handler_user_names.py+++ b/tests/test_command_handler_user_names.py@@ -13,11 +13,15 @@ sys.path.insert(0, str(ROOT))def _load_command_handlers_class():agents_module = types.ModuleType("modules.agents")+ agents_module.__path__ = [str(ROOT / "modules" / "agents")]setattr(agents_module, "AgentRequest", type("AgentRequest", (), {}))setattr(agents_module, "get_agent_display_name", lambda agent_name, fallback=None: agent_name or fallback or "Unknown")sys.modules["modules.agents"] = agents_module+ agents_base_module = types.ModuleType("modules.agents.base")+ setattr(agents_base_module, "AgentRequest", type("AgentRequest", (), {}))+ sys.modules["modules.agents.base"] = agents_base_modulecore_pkg = types.ModuleType("core")core_pkg.__path__ = [str(ROOT / "core")]@@ -129,6 +133,7 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):self.assertIn("你好 小王!", message)self.assertIn("/start - 显示欢迎消息", message)self.assertIn("/setcwd <路径> - 设置工作目录", message)+ self.assertIn("/resume - 恢复当前目录下最近的会话", message)self.assertIn("/new - 开启一个全新的会话", message)self.assertNotIn("User ID", message)self.assertNotIn("How it works", message)diff --git a/tests/test_resume_session.py b/tests/test_resume_session.pyindex c0ae9dfb3..75cd2e860 100644--- a/tests/test_resume_session.py+++ b/tests/test_resume_session.py@@ -1,4 +1,6 @@import unittest+from datetime import datetime+from unittest.mock import AsyncMockfrom core.controller import Controllerfrom core.handlers.command_handlers import CommandHandlers@@ -280,6 +282,137 @@ class ResumeSessionTests(unittest.IsolatedAsyncioTestCase):self.assertEqual([item.native_session_id for item in sessions], ["thread_123"])self.assertEqual(ctrl.native_session_service.calls, [("/Users/cyh/vibe-remote", 100)])+ async def test_command_handlers_handle_resume_wechat_lists_recent_sessions(self):+ settings = _StubSettingsManager()+ im_client = _StubIMClient()+ ctrl = _StubController()+ ctrl.init_minimal(im_client, settings, _StubConfig(platform="wechat"))+ ctrl.config.language = "zh"+ ctrl.native_session_service = _StubNativeSessionService(+ [+ NativeResumeSession(+ agent="claude",+ agent_prefix="cc",+ native_session_id="claude-1",+ working_path="/Users/cyh/vibe-remote",+ created_at=None,+ updated_at=datetime(2026, 3, 27, 14, 32),+ sort_ts=10.0,+ last_agent_message="",+ last_agent_tail="...修好了 Claude fallback 列表",+ ),+ NativeResumeSession(+ agent="codex",+ agent_prefix="cx",+ native_session_id="codex-1",+ working_path="/Users/cyh/vibe-remote",+ created_at=None,+ updated_at=datetime(2026, 3, 27, 14, 10),+ sort_ts=9.0,+ last_agent_message="",+ last_agent_tail="...继续在子区里回复这条消息",+ ),+ ]+ )++ ctx = MessageContext(+ user_id="wx-user",+ channel_id="wx-chat",+ platform="wechat",+ platform_specific={"is_dm": True, "platform": "wechat"},+ )++ await ctrl.command_handler.handle_resume(ctx)++ self.assertEqual(len(im_client.messages), 1)+ text = im_client.messages[0][2]+ self.assertIn("当前工作目录下最近的 Agent 会话", text)+ self.assertIn("1. cc ...修好了 Claude fallback 列表", text)+ self.assertIn("2. cx ...继续在子区里回复这条消息", text)+ self.assertIn("/resume 1 - 恢复当前列表中的第 1 条", text)+ self.assertIn("/resume more - 查看下一页", text)++ async def test_command_handlers_handle_resume_wechat_numeric_selection_uses_snapshot(self):+ settings = _StubSettingsManager()+ im_client = _StubIMClient()+ ctrl = _StubController()+ ctrl.init_minimal(im_client, settings, _StubConfig(platform="wechat"))+ ctrl.native_session_service = _StubNativeSessionService(+ [+ NativeResumeSession(+ agent="opencode",+ agent_prefix="oc",+ native_session_id="oc-1",+ working_path="/Users/cyh/vibe-remote",+ created_at=None,+ updated_at=None,+ sort_ts=10.0,+ last_agent_message="",+ last_agent_tail="...第一条",+ ),+ NativeResumeSession(+ agent="claude",+ agent_prefix="cc",+ native_session_id="cc-2",+ working_path="/Users/cyh/vibe-remote",+ created_at=None,+ updated_at=None,+ sort_ts=9.0,+ last_agent_message="",+ last_agent_tail="...第二条",+ ),+ ]+ )+ ctrl.session_handler.handle_resume_session_submission = AsyncMock()+ ctx = MessageContext(+ user_id="wx-user",+ channel_id="wx-chat",+ platform="wechat",+ message_id="MSG1",+ platform_specific={"is_dm": True, "platform": "wechat"},+ )++ await ctrl.command_handler.handle_resume(ctx)+ await ctrl.command_handler.handle_resume(ctx, "2")++ ctrl.session_handler.handle_resume_session_submission.assert_awaited_once_with(+ user_id="wx-user",+ channel_id="wx-chat",+ thread_id=None,+ agent="claude",+ session_id="cc-2",+ host_message_ts="MSG1",+ is_dm=True,+ platform="wechat",+ )++ async def test_command_handlers_handle_resume_wechat_manual_backend_session_id(self):+ settings = _StubSettingsManager()+ im_client = _StubIMClient()+ ctrl = _StubController()+ ctrl.init_minimal(im_client, settings, _StubConfig(platform="wechat"))+ ctrl.session_handler.handle_resume_session_submission = AsyncMock()+ ctx = MessageContext(+ user_id="wx-user",+ channel_id="wx-chat",+ platform="wechat",+ message_id="MSG1",+ platform_specific={"is_dm": True, "platform": "wechat"},+ )++ await ctrl.command_handler.handle_resume(ctx, "cc 59adbb74-ce14-418f-b176-28210e21b6ae")++ ctrl.session_handler.handle_resume_session_submission.assert_awaited_once_with(+ user_id="wx-user",+ channel_id="wx-chat",+ thread_id=None,+ agent="claude",+ session_id="59adbb74-ce14-418f-b176-28210e21b6ae",+ host_message_ts="MSG1",+ is_dm=True,+ platform="wechat",+ )+async def test_resume_modal_manual_session_uses_manual_agent(self):if SlackBot is None:self.skipTest("Slack dependencies not installed in this environment")diff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex ee1db06c0..cdd1d9cb7 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -184,6 +184,7 @@"commandStart": "/start - Show this welcome message","commandCwd": "/cwd - Show current working directory","commandSetCwd": "/setcwd <path> - Set working directory",+ "commandResume": "/resume - Restore a recent session for this working directory","commandStop": "/stop - Interrupt {agent} execution","commandNew": "/new - Start a fresh session","quickActions": "Quick Actions:",@@ -210,7 +211,23 @@"resume": {"slackOnly": "Resume is currently available only on Slack. Continue in the same thread to auto-resume.","clickButton": "Please click the Resume button inside Slack to open the picker.",- "noStoredSessions": "No recent agent sessions found for this working directory. You can still paste a session ID manually in the resume modal."+ "noStoredSessions": "No recent agent sessions found for this working directory.",+ "noStoredSessionsForBackend": "No recent {backend} sessions found for this working directory.",+ "listTitle": "Recent agent sessions for the current working directory",+ "listPage": "Page {page} / {total}",+ "listItemTitle": "{index}. {prefix} {preview}",+ "listItemTime": " {time}",+ "usageTitle": "Usage:",+ "usageList": "/resume - Show recent sessions",+ "usagePick": "/resume 1 - Restore item 1 from the current list",+ "usageMore": "/resume more - Show the next page",+ "usageLatest": "/resume latest [oc|cc|cx] - Restore the latest session",+ "usageManual": "/resume <oc|cc|cx> <session_id> - Restore a session manually",+ "snapshotExpired": "The last shown session list expired. Please run /resume again first.",+ "invalidSelection": "Choose a valid number from the current list.",+ "unknownBackend": "Unknown backend. Use oc, cc, cx, or a full backend name.",+ "unknownCommand": "Unknown resume command.",+ "noMorePages": "There are no more sessions to show."},"stop": {"noActiveSession": "No active session to stop for this channel."diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex e1f894f81..bc5065336 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -184,6 +184,7 @@"commandStart": "/start - 显示欢迎消息","commandCwd": "/cwd - 显示当前工作目录","commandSetCwd": "/setcwd <路径> - 设置工作目录",+ "commandResume": "/resume - 恢复当前目录下最近的会话","commandStop": "/stop - 中断 {agent} 当前执行","commandNew": "/new - 开启一个全新的会话","quickActions": "快捷操作:",@@ -210,7 +211,23 @@"resume": {"slackOnly": "恢复功能目前仅在 Slack 上可用。在同一线程中继续可自动恢复。","clickButton": "请在 Slack 中点击“恢复”按钮打开选择器。",- "noStoredSessions": "当前工作目录下未找到最近的 Agent 会话。您仍可以在恢复对话框中手动粘贴会话 ID。"+ "noStoredSessions": "当前工作目录下未找到最近的 Agent 会话。",+ "noStoredSessionsForBackend": "当前工作目录下未找到最近的 {backend} 会话。",+ "listTitle": "当前工作目录下最近的 Agent 会话",+ "listPage": "第 {page} / {total} 页",+ "listItemTitle": "{index}. {prefix} {preview}",+ "listItemTime": " {time}",+ "usageTitle": "使用方式:",+ "usageList": "/resume - 查看最近会话",+ "usagePick": "/resume 1 - 恢复当前列表中的第 1 条",+ "usageMore": "/resume more - 查看下一页",+ "usageLatest": "/resume latest [oc|cc|cx] - 恢复最近一条会话",+ "usageManual": "/resume <oc|cc|cx> <session_id> - 手动恢复指定会话",+ "snapshotExpired": "上一次显示的会话列表已过期,请先重新执行 /resume。",+ "invalidSelection": "请选择当前列表中的有效编号。",+ "unknownBackend": "后端不合法,请使用 oc、cc、cx 或完整后端名。",+ "unknownCommand": "未识别的恢复命令。",+ "noMorePages": "已经没有更多会话了。"},"stop": {"noActiveSession": "此频道没有要停止的活动会话。"