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: preserve sessions after cwd changes (#580)

Xisheng Parker Zhao57f3a9555b96
diff --git a/core/handlers/base.py b/core/handlers/base.py
index 2c9991555..d4bea6341 100644
--- a/core/handlers/base.py
+++ b/core/handlers/base.py
@@ -1,8 +1,12 @@
"""Shared handler foundation for controller-owned handlers."""
+import logging
+
from modules.im import MessageContext
from vibe.i18n import t as i18n_t
+logger = logging.getLogger(__name__)
+
class BaseHandler:
"""Provide shared controller references and common helper methods."""
@@ -54,6 +58,47 @@ class BaseHandler:
def _t(self, key: str, **kwargs) -> str:
return i18n_t(key, self._get_lang(), **kwargs)
+ def _context_can_start_fresh_session_without_reset(self, context: MessageContext) -> bool:
+ im_client = self._get_im_client(context)
+ is_dm = bool((context.platform_specific or {}).get("is_dm", False))
+ if is_dm:
+ return bool(getattr(im_client, "should_use_thread_for_dm_session", lambda: False)())
+ uses_threads = bool(getattr(im_client, "should_use_thread_for_reply", lambda: False)())
+ uses_message_sessions = bool(
+ getattr(im_client, "should_use_message_id_for_channel_session", lambda _context=None: True)(context)
+ )
+ return uses_threads and uses_message_sessions
+
+ def _session_anchor_for_context(self, context: MessageContext, *, log_context: str = "session hint") -> str:
+ session_handler = getattr(self.controller, "session_handler", None)
+ getter = getattr(session_handler, "get_base_session_id", None)
+ if callable(getter):
+ try:
+ return getter(context)
+ except Exception:
+ logger.debug("Failed to resolve session anchor for %s", log_context, exc_info=True)
+ platform = context.platform or (context.platform_specific or {}).get("platform") or self.config.platform
+ payload = context.platform_specific or {}
+ base_id = (context.channel_id or context.user_id) if payload.get("is_dm", False) else context.channel_id
+ return f"{platform}_{base_id or context.user_id}"
+
+ def _current_flat_scope_session_row_for_hint(self, context: MessageContext, *, log_context: str = "session hint"):
+ if self._context_can_start_fresh_session_without_reset(context):
+ return None
+ finder = getattr(self.sessions, "find_session_for_anchor", None)
+ if not callable(finder):
+ return None
+ session_key = self._get_session_key(context)
+ session_anchor = self._session_anchor_for_context(context, log_context=log_context)
+ try:
+ return finder(session_key, session_anchor)
+ except Exception:
+ logger.debug("Failed to inspect current session for %s", log_context, exc_info=True)
+ return None
+
+ def _flat_scope_needs_new_session_hint(self, context: MessageContext, *, log_context: str = "session hint") -> bool:
+ return bool(self._current_flat_scope_session_row_for_hint(context, log_context=log_context))
+
@staticmethod
def _resolve_user_display_name(user_info: dict, fallback: str) -> str:
return (
diff --git a/core/handlers/command_handlers.py b/core/handlers/command_handlers.py
index 73aaa3122..00b3ed404 100644
--- a/core/handlers/command_handlers.py
+++ b/core/handlers/command_handlers.py
@@ -630,6 +630,8 @@ class CommandHandlers(BaseHandler):
formatter = self._get_formatter(context)
response_text = f"✅ {self._t('success.cwdChanged', path=formatter.format_code_inline(absolute_path))}"
+ if self._flat_scope_needs_new_session_hint(context, log_context="cwd update hint"):
+ response_text = f"{response_text}\n\n{self._t('success.routingUpdateNeedsNewSession')}"
channel_context = self._get_channel_context(context)
await im_client.send_message(channel_context, response_text)
diff --git a/core/handlers/settings_handler.py b/core/handlers/settings_handler.py
index acfc090c7..495c3c50a 100644
--- a/core/handlers/settings_handler.py
+++ b/core/handlers/settings_handler.py
@@ -508,30 +508,6 @@ class SettingsHandler(BaseHandler):
return False
return bool(getattr(backend_config, "enabled", True))
- def _context_can_start_fresh_session_without_reset(self, context: MessageContext) -> bool:
- im_client = self._get_im_client(context)
- is_dm = bool((context.platform_specific or {}).get("is_dm", False))
- if is_dm:
- return bool(getattr(im_client, "should_use_thread_for_dm_session", lambda: False)())
- uses_threads = bool(getattr(im_client, "should_use_thread_for_reply", lambda: False)())
- uses_message_sessions = bool(
- getattr(im_client, "should_use_message_id_for_channel_session", lambda _context=None: True)(context)
- )
- return uses_threads and uses_message_sessions
-
- def _session_anchor_for_context(self, context: MessageContext) -> str:
- session_handler = getattr(self.controller, "session_handler", None)
- getter = getattr(session_handler, "get_base_session_id", None)
- if callable(getter):
- try:
- return getter(context)
- except Exception:
- logger.debug("Failed to resolve session anchor for routing update hint", exc_info=True)
- platform = context.platform or (context.platform_specific or {}).get("platform") or self.config.platform
- payload = context.platform_specific or {}
- base_id = context.channel_id or context.user_id if payload.get("is_dm", False) else context.channel_id
- return f"{platform}_{base_id or context.user_id}"
-
def _resolve_route_backend(self, agent_name: Optional[str]) -> Optional[str]:
if not agent_name:
return None
@@ -584,27 +560,14 @@ class SettingsHandler(BaseHandler):
)
def _routing_update_needs_new_session_hint(self, context: MessageContext, routing) -> bool:
- if self._context_can_start_fresh_session_without_reset(context):
- return False
- finder = getattr(self.sessions, "find_session_for_anchor", None)
- if not callable(finder):
- return False
- session_key = self._get_session_key(context)
- session_anchor = self._session_anchor_for_context(context)
- try:
- row = finder(session_key, session_anchor)
- except Exception:
- logger.debug("Failed to inspect current session for routing update hint", exc_info=True)
- return False
+ row = self._current_flat_scope_session_row_for_hint(context, log_context="routing update hint")
if not row:
return False
current_target = self._routing_target_from_row(row)
next_target = self._routing_target_from_settings(routing)
- if not any(current_target):
- return True
- if current_target[1] and next_target[1] and current_target[1] != next_target[1]:
- return True
- return current_target != next_target
+ current_backend = current_target[1]
+ next_backend = next_target[1]
+ return bool(current_backend and next_backend and current_backend != next_backend)
async def _handle_routing_slack(self, context: MessageContext):
"""Handle routing for Slack using modal dialog"""
diff --git a/tests/test_command_handler_user_names.py b/tests/test_command_handler_user_names.py
index 43f73fcff..1fbb30d91 100644
--- a/tests/test_command_handler_user_names.py
+++ b/tests/test_command_handler_user_names.py
@@ -56,6 +56,12 @@ def _load_command_handlers_class():
CommandHandlers = _load_command_handlers_class()
+class _StubFormatter:
+ @staticmethod
+ def format_code_inline(text):
+ return f"`{text}`"
+
+
class _StubIMClient:
def __init__(self, user_info):
self.user_info = user_info
@@ -63,7 +69,7 @@ class _StubIMClient:
self.sent_contexts = []
self.sent_button_messages = []
self.channel_info_calls = []
- self.formatter = None
+ self.formatter = _StubFormatter()
self.started_topic_context = None
async def get_user_info(self, user_id):
@@ -89,6 +95,9 @@ class _StubIMClient:
class _StubSettingsManager:
def __init__(self):
self.bind_calls = []
+ self.custom_cwd_calls = []
+ self.session_row = None
+ self.session_lookup_calls = []
def is_bound_user(self, user_id, platform=None):
return False
@@ -97,6 +106,13 @@ class _StubSettingsManager:
self.bind_calls.append((user_id, display_name, code, dm_chat_id, platform))
return True, False
+ def set_custom_cwd(self, settings_key, cwd):
+ self.custom_cwd_calls.append((settings_key, cwd))
+
+ def find_session_for_anchor(self, session_key, session_anchor):
+ self.session_lookup_calls.append((session_key, session_anchor))
+ return self.session_row
+
class _StubController:
def __init__(self, user_info):
@@ -104,10 +120,24 @@ class _StubController:
self.im_client = _StubIMClient(user_info)
self.settings_manager = _StubSettingsManager()
self.sessions = self.settings_manager
- self.session_handler = None
+ self.session_handler = type(
+ "SessionHandler",
+ (),
+ {"get_base_session_id": staticmethod(lambda context: f"{context.platform}_{context.channel_id}")},
+ )()
self.session_manager = object()
self.receiver_tasks = {}
- self.agent_service = type("AgentService", (), {"default_agent": "codex"})()
+ self.cleared_sessions = []
+
+ async def _clear_sessions(session_key):
+ self.cleared_sessions.append(session_key)
+ return {"claude": 1}
+
+ self.agent_service = type(
+ "AgentService",
+ (),
+ {"default_agent": "codex", "clear_sessions": staticmethod(_clear_sessions)},
+ )()
def _get_settings_key(self, context: MessageContext) -> str:
return context.user_id if context.channel_id.startswith("D") else context.channel_id
@@ -212,6 +242,36 @@ class CommandHandlerUserNameTests(unittest.IsolatedAsyncioTestCase):
[("wx-chat", "🆕 已开启新的会话。你下一条消息会从全新对话开始。")],
)
+ async def test_setcwd_keeps_existing_scope_session_and_shows_new_hint(self):
+ controller = _StubController({"display_name": "小王"})
+ controller.settings_manager.session_row = {"agent_backend": "claude"}
+ handler = CommandHandlers(controller)
+ context = MessageContext(user_id="wx-user", channel_id="wx-chat", platform="wechat")
+
+ await handler.handle_set_cwd(context, ".")
+
+ self.assertEqual(controller.settings_manager.custom_cwd_calls, [("wx-chat", str(ROOT))])
+ self.assertEqual(controller.cleared_sessions, [])
+ self.assertEqual(controller.settings_manager.session_lookup_calls, [("wechat::wx-chat", "wechat_wx-chat")])
+ self.assertEqual(len(controller.im_client.sent_messages), 1)
+ text = controller.im_client.sent_messages[0][1]
+ self.assertIn("✅", text)
+ self.assertIn(str(ROOT), text)
+ self.assertIn("请使用 /new 命令创建新会话,以使设置变更生效。新会话创建后将覆盖当前会话。", text)
+
+ async def test_setcwd_does_not_show_new_hint_without_existing_scope_session(self):
+ controller = _StubController({"display_name": "小王"})
+ handler = CommandHandlers(controller)
+ context = MessageContext(user_id="wx-user", channel_id="wx-chat", platform="wechat")
+
+ await handler.handle_set_cwd(context, ".")
+
+ self.assertEqual(controller.cleared_sessions, [])
+ self.assertEqual(controller.settings_manager.session_lookup_calls, [("wechat::wx-chat", "wechat_wx-chat")])
+ text = controller.im_client.sent_messages[0][1]
+ self.assertIn(str(ROOT), text)
+ self.assertNotIn("请使用 /new 命令创建新会话", text)
+
async def test_telegram_dm_new_command_clears_user_and_legacy_channel_scopes(self):
controller = _StubController({"display_name": "Alex"})
setattr(controller.config, "platform", "telegram")
diff --git a/tests/test_settings_handler.py b/tests/test_settings_handler.py
index 716644e66..3e5c601d3 100644
--- a/tests/test_settings_handler.py
+++ b/tests/test_settings_handler.py
@@ -236,7 +236,7 @@ def test_handle_routing_update_warns_wechat_flat_scope_with_existing_backend_ses
assert sessions.calls == [("wechat::user::58181121", "wechat_58181121")]
-def test_handle_routing_update_warns_flat_scope_same_backend_model_change() -> None:
+def test_handle_routing_update_does_not_warn_flat_scope_same_backend_model_change() -> None:
handler, send_message, sessions = _make_flat_scope_handler(
row={
"agent_name": "claude",
@@ -262,7 +262,38 @@ def test_handle_routing_update_warns_flat_scope_same_backend_model_change() -> N
)
text = send_message.await_args.args[1]
- assert "请使用 /new 命令创建新会话,以使设置变更生效。新会话创建后将覆盖当前会话。" in text
+ assert "请使用 /new 命令创建新会话" not in text
+ assert sessions.calls == [("telegram::user::58181121", "telegram_58181121")]
+
+
+def test_handle_routing_update_does_not_warn_flat_scope_same_backend_reasoning_change() -> None:
+ handler, send_message, sessions = _make_flat_scope_handler(
+ row={
+ "agent_name": "claude",
+ "agent_backend": "claude",
+ "agent_variant": "claude",
+ "model": "claude-sonnet-4-5",
+ "reasoning_effort": "low",
+ }
+ )
+
+ asyncio.run(
+ handler.handle_routing_update(
+ user_id="58181121",
+ channel_id="58181121",
+ backend="claude",
+ opencode_agent=None,
+ opencode_model=None,
+ claude_agent=None,
+ claude_model="claude-sonnet-4-5",
+ claude_reasoning_effort="high",
+ platform="telegram",
+ is_dm=True,
+ )
+ )
+
+ text = send_message.await_args.args[1]
+ assert "请使用 /new 命令创建新会话" not in text
assert sessions.calls == [("telegram::user::58181121", "telegram_58181121")]