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(claude): surface stale session resume errors
cyhe323f6168b04
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.pyindex fd6e0fd14..494006163 100644--- a/core/handlers/session_handler.py+++ b/core/handlers/session_handler.py@@ -3,6 +3,7 @@import asyncioimport loggingimport os+import reimport timefrom typing import Optional, Dict, Any, Tuplefrom uuid import uuid4@@ -14,6 +15,20 @@ from .base import BaseHandlerlogger = logging.getLogger(__name__)+CLAUDE_NO_CONVERSATION_RE = re.compile(r"No conversation found with session ID:\s*([0-9a-fA-F-]+)")+++class ClaudeSessionNotFoundError(RuntimeError):+ """Claude Code could not resume a persisted session in the current cwd."""++ def __init__(self, session_id: str, working_path: str, stderr: str = ""):+ self.session_id = session_id+ self.working_path = working_path+ self.stderr = stderr+ super().__init__(+ f"Claude Code session not found in current working directory: {session_id} ({working_path})"+ )+class SessionHandler(BaseHandler):"""Handles all session-related operations"""@@ -507,6 +522,16 @@ class SessionHandler(BaseHandler):if effective_model:extra_args["model"] = effective_model+ claude_stderr_lines: list[str] = []++ def _capture_claude_stderr(line: str) -> None:+ text = (line or "").strip()+ if not text:+ return+ claude_stderr_lines.append(text)+ if len(claude_stderr_lines) > 40:+ del claude_stderr_lines[:-40]+# Collect Anthropic-related environment variables to pass to Claudeclaude_env = {}for key in os.environ:@@ -527,6 +552,7 @@ class SessionHandler(BaseHandler):# See: https://github.com/anthropics/claude-code/issues/10168"disallowed_tools": ["AskUserQuestion"],"env": claude_env, # Pass Anthropic/Claude env vars+ "stderr": _capture_claude_stderr,}cli_path_override = self._get_claude_cli_path_override()if cli_path_override:@@ -573,7 +599,18 @@ class SessionHandler(BaseHandler):logger.info(f" - subagent: {subagent_name}")# Connect the client- await client.connect()+ try:+ await client.connect()+ except Exception as exc:+ stderr_text = "\n".join(claude_stderr_lines)+ match = CLAUDE_NO_CONVERSATION_RE.search(stderr_text) or CLAUDE_NO_CONVERSATION_RE.search(str(exc))+ if match:+ raise ClaudeSessionNotFoundError(+ session_id=match.group(1),+ working_path=str(working_path),+ stderr=stderr_text,+ ) from exc+ raiseself.claude_sessions[composite_key] = clientself.bind_claude_runtime_session(client, base_session_id, composite_key)@@ -825,7 +862,23 @@ class SessionHandler(BaseHandler):error_msg = str(error)# Check for specific error types- if "read() called while another coroutine" in error_msg:+ if isinstance(error, ClaudeSessionNotFoundError):+ logger.warning(+ "Claude session %s not found for current working directory %s; keeping persisted mapping unchanged",+ error.session_id,+ error.working_path,+ )+ await self._get_im_client(context).send_message(+ context,+ self._get_formatter(context).format_error(+ self._t(+ "error.claudeSessionNotFound",+ sessionId=error.session_id,+ path=error.working_path,+ )+ ),+ )+ elif "read() called while another coroutine" in error_msg:logger.error(f"Session {composite_key} has concurrent read error - cleaning up")await self.cleanup_session(composite_key)diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.pyindex 7e2b9b318..0cdb4da74 100644--- a/tests/test_claude_cli_path.py+++ b/tests/test_claude_cli_path.py@@ -6,6 +6,8 @@ from pathlib import Pathimport sysfrom typing import Any+import pytest+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))import core.handlers.session_handler as session_handler_module@@ -209,6 +211,46 @@ def test_session_handler_expands_tilde_in_claude_cli_path(monkeypatch, tmp_path:assert captured["options"].cli_path == str(Path("~/bin/claude").expanduser())+def test_session_handler_surfaces_claude_missing_resume_session(monkeypatch, tmp_path: Path) -> None:+ stale_session_id = "11111111-1111-1111-1111-111111111111"+ captured: dict[str, Any] = {}++ class _StaleSessions:+ @staticmethod+ def get_claude_session_id(settings_key, base_session_id):+ assert settings_key == "test::C123"+ assert base_session_id == "slack_C123"+ return stale_session_id++ @staticmethod+ def get_agent_session_id(settings_key, base_session_id, agent_name):+ return None++ class _StubClaudeSDKClient:+ def __init__(self, options):+ captured["options"] = options++ async def connect(self) -> None:+ captured["options"].stderr(f"No conversation found with session ID: {stale_session_id}")+ raise RuntimeError("Command failed with exit code 1")++ monkeypatch.setattr(session_handler_module, "ClaudeAgentOptions", _StubClaudeAgentOptions)+ monkeypatch.setattr(session_handler_module, "ClaudeSDKClient", _StubClaudeSDKClient)++ controller = _Controller(tmp_path)+ controller.settings_manager.sessions = _StaleSessions()+ handler = SessionHandler(controller)+ context = MessageContext(user_id="U123", channel_id="C123")++ with pytest.raises(session_handler_module.ClaudeSessionNotFoundError) as exc_info:+ _run_session(handler, context)++ assert exc_info.value.session_id == stale_session_id+ assert exc_info.value.working_path == str(tmp_path)+ assert stale_session_id in exc_info.value.stderr+ assert captured["options"].resume == stale_session_id++def test_session_handler_uses_scheduled_turn_source_for_dm_anchor(monkeypatch, tmp_path: Path) -> None:captured: dict[str, Any] = {}diff --git a/tests/test_session_handler_base_id.py b/tests/test_session_handler_base_id.pyindex 93d7dea63..62080b378 100644--- a/tests/test_session_handler_base_id.py+++ b/tests/test_session_handler_base_id.py@@ -1,12 +1,13 @@from __future__ import annotations+import asynciofrom dataclasses import dataclassimport sysfrom pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parents[1]))-from core.handlers.session_handler import SessionHandler+from core.handlers.session_handler import ClaudeSessionNotFoundError, SessionHandlerfrom modules.im import MessageContext@@ -89,6 +90,33 @@ class _Controller:return self.im_client+class _FakeFormatter:+ @staticmethod+ def format_error(text: str) -> str:+ return f"ERR:{text}"+++class _FakeIM:+ def __init__(self) -> None:+ self.formatter = _FakeFormatter()+ self.sent_messages = []++ @staticmethod+ def should_use_thread_for_dm_session() -> bool:+ return False++ @staticmethod+ def should_use_message_id_for_channel_session(context=None) -> bool:+ return True++ @staticmethod+ def should_use_thread_for_reply() -> bool:+ return True++ async def send_message(self, context: MessageContext, message: str) -> None:+ self.sent_messages.append((context, message))++def test_dm_session_base_id_uses_stable_channel_id() -> None:handler = SessionHandler(_Controller(platform="discord", dm_threads=False))context = MessageContext(@@ -286,3 +314,34 @@ def test_alias_session_base_clears_source_even_when_alias_already_exists() -> Noassert changed is Trueassert controller.sessions.alias_calls == [("slack::C123", "slack_scheduled-abc", "slack_171717.123")]assert controller.sessions.clear_calls == [("slack::C123", "slack_scheduled-abc")]+++def test_claude_session_not_found_error_is_reported_without_cleanup() -> None:+ controller = _Controller(platform="slack", dm_threads=False)+ controller.im_client = _FakeIM()+ handler = SessionHandler(controller)+ cleanup_calls = []++ async def _cleanup_session(composite_key: str) -> None:+ cleanup_calls.append(composite_key)++ handler.cleanup_session = _cleanup_session+ context = MessageContext(user_id="U123", channel_id="C123", platform="slack")++ asyncio.run(+ handler.handle_session_error(+ "slack_C123:/tmp/other",+ context,+ ClaudeSessionNotFoundError(+ session_id="11111111-1111-1111-1111-111111111111",+ working_path="/tmp/other",+ ),+ )+ )++ assert cleanup_calls == []+ assert len(controller.im_client.sent_messages) == 1+ _, message = controller.im_client.sent_messages[0]+ assert message.startswith("ERR:Claude Code could not find the historical session")+ assert "11111111-1111-1111-1111-111111111111" in message+ assert "/tmp/other" in messagediff --git a/vibe/i18n/en.json b/vibe/i18n/en.jsonindex 3f888e1b6..8bb6b14de 100644--- a/vibe/i18n/en.json+++ b/vibe/i18n/en.json@@ -45,6 +45,7 @@"opencodeQuestionUnsupportedWechat": "OpenCode interactive questions are temporarily disabled on WeChat. Please send a follow-up message instead.","sessionReset": "Session error detected. Session has been reset. Please try your message again.","sessionConnectionLost": "Connection to Claude was lost. Please try your message again.",+ "claudeSessionNotFound": "Claude Code could not find the historical session `{sessionId}` in the current working directory:\n`{path}`\n\nClaude Code sessions are scoped to a working directory. This usually means the conversation was resumed after switching workdirs, or the local Claude Code session data changed. Switch back to the original working directory to continue that session, or start a new Claude Code session from the current directory.","sessionGeneric": "An error occurred: {error}","resultAttachmentUploadFailed": "Failed to upload attachment. Want me to split the result into multiple messages?","resultDeliveryFailed": "⚠️ Message delivery failed. The content may be too long or incompatible. Ask me to resend it."diff --git a/vibe/i18n/zh.json b/vibe/i18n/zh.jsonindex 3d260d0a2..c946dc7e9 100644--- a/vibe/i18n/zh.json+++ b/vibe/i18n/zh.json@@ -45,6 +45,7 @@"opencodeQuestionUnsupportedWechat": "微信平台暂时不支持 OpenCode 的交互式提问。请直接再发一条消息继续。","sessionReset": "检测到会话错误。会话已重置,请重试。","sessionConnectionLost": "与 Claude 的连接已断开,请重试。",+ "claudeSessionNotFound": "Claude Code 在当前工作目录下找不到历史会话 `{sessionId}`:\n`{path}`\n\nClaude Code 的会话和工作目录相关。通常是恢复会话后切换了工作目录,或本地 Claude Code 会话数据发生变化。请切回原来的工作目录继续该会话,或在当前目录开始一个新的 Claude Code 会话。","sessionGeneric": "发生错误:{error}","resultAttachmentUploadFailed": "附件上传失败。要我改成拆分成多条消息发送吗?","resultDeliveryFailed": "⚠️ 消息投递失败,内容可能过长或格式不兼容。你可以让我重新发送一次。"