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(claude): track runtime session keys

cyha2dbd5153b84
diff --git a/core/handlers/session_handler.py b/core/handlers/session_handler.py
index 8b2e94296..853771c14 100644
--- a/core/handlers/session_handler.py
+++ b/core/handlers/session_handler.py
@@ -52,6 +52,11 @@ class SessionHandler(BaseHandler):
self.active_sessions.discard(composite_key)
self.session_last_activity.pop(composite_key, None)
+ def bind_claude_runtime_session(self, client: ClaudeSDKClient, base_session_id: str, composite_key: str) -> None:
+ """Attach the resolved Claude runtime keys to the connected client."""
+ setattr(client, "_vibe_runtime_base_session_id", base_session_id)
+ setattr(client, "_vibe_runtime_session_key", composite_key)
+
def get_base_session_id(self, context: MessageContext, source: str = "human") -> str:
"""Get base session ID based on platform and context (without path)"""
platform = self._get_context_platform(context)
@@ -381,6 +386,7 @@ class SessionHandler(BaseHandler):
logger.info(
f"Using existing Claude SDK client for {base_session_id} at {working_path} (model={current_model})"
)
+ self.bind_claude_runtime_session(client, base_session_id, composite_key)
self.touch_session_activity(composite_key)
return client
@@ -409,6 +415,7 @@ class SessionHandler(BaseHandler):
working_path,
explicit_model,
)
+ self.bind_claude_runtime_session(client, cached_base, cached_key)
self.touch_session_activity(cached_key)
return client
# Always use agent-specific key when effective_agent is set
@@ -561,6 +568,7 @@ class SessionHandler(BaseHandler):
await client.connect()
self.claude_sessions[composite_key] = client
+ self.bind_claude_runtime_session(client, base_session_id, composite_key)
self.touch_session_activity(composite_key)
logger.info(f"Created new Claude SDK client for {base_session_id} at {working_path}")
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 66ec00f32..ab3a1f233 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -52,6 +52,8 @@ class ClaudeAgent(BaseAgent):
async def handle_message(self, request: AgentRequest) -> None:
context = request.context
+ runtime_base_session_id = request.base_session_id
+ runtime_session_key = request.composite_session_id
# Question callback handling (disabled - SDK doesn't support AskUserQuestion response)
# if self.ENABLE_ASK_USER_QUESTION and request.message.startswith("claude_question:"):
@@ -65,43 +67,51 @@ class ClaudeAgent(BaseAgent):
subagent_model=request.subagent_model,
subagent_reasoning_effort=request.subagent_reasoning_effort,
)
+ runtime_base_session_id = getattr(client, "_vibe_runtime_base_session_id", runtime_base_session_id)
+ runtime_session_key = getattr(client, "_vibe_runtime_session_key", runtime_session_key)
mark_session_active = getattr(self.session_handler, "mark_session_active", None)
if callable(mark_session_active):
- mark_session_active(request.composite_session_id)
+ mark_session_active(runtime_session_key)
# Queue reaction BEFORE sending query to avoid race condition where
# a fast result arrives before the reaction is queued
if request.ack_reaction_message_id and request.ack_reaction_emoji:
- if request.composite_session_id not in self._pending_reactions:
- self._pending_reactions[request.composite_session_id] = []
- self._pending_reactions[request.composite_session_id].append(
+ if runtime_session_key not in self._pending_reactions:
+ self._pending_reactions[runtime_session_key] = []
+ self._pending_reactions[runtime_session_key].append(
(request.ack_reaction_message_id, request.ack_reaction_emoji)
)
- self._pending_requests.setdefault(request.composite_session_id, []).append(request)
+ self._pending_requests.setdefault(runtime_session_key, []).append(request)
# Prepare message with file attachment info if present
message = self._prepare_message_with_files(request)
- await client.query(message, session_id=request.composite_session_id)
- logger.info(f"Sent message to Claude for session {request.composite_session_id}")
+ await client.query(message, session_id=runtime_session_key)
+ logger.info(f"Sent message to Claude for session {runtime_session_key}")
await self._delete_ack(context, request)
if (
- request.composite_session_id not in self.receiver_tasks
- or self.receiver_tasks[request.composite_session_id].done()
+ runtime_session_key not in self.receiver_tasks
+ or self.receiver_tasks[runtime_session_key].done()
):
- self.receiver_tasks[request.composite_session_id] = asyncio.create_task(
- self._receive_messages(client, request.base_session_id, request.working_path, context)
+ self.receiver_tasks[runtime_session_key] = asyncio.create_task(
+ self._receive_messages(
+ client,
+ runtime_base_session_id,
+ request.working_path,
+ context,
+ composite_key=runtime_session_key,
+ )
)
except Exception as e:
logger.error(f"Error processing Claude message: {e}", exc_info=True)
mark_session_idle = getattr(self.session_handler, "mark_session_idle", None)
if callable(mark_session_idle):
- mark_session_idle(request.composite_session_id)
+ mark_session_idle(runtime_session_key)
# Clean up the specific reaction for this request (not FIFO)
- await self._remove_specific_pending_reaction(request.composite_session_id, context, request)
- self._remove_pending_request(request.composite_session_id, request)
+ await self._remove_specific_pending_reaction(runtime_session_key, context, request)
+ self._remove_pending_request(runtime_session_key, request)
await self._remove_ack_reaction(request)
handled = await self.controller.agent_auth_service.maybe_emit_auth_recovery_message(
context,
@@ -109,7 +119,7 @@ class ClaudeAgent(BaseAgent):
f"❌ Claude error: {e}",
)
if not handled:
- await self.session_handler.handle_session_error(request.composite_session_id, context, e)
+ await self.session_handler.handle_session_error(runtime_session_key, context, e)
finally:
await self._delete_ack(context, request)
@@ -282,11 +292,13 @@ class ClaudeAgent(BaseAgent):
base_session_id: str,
working_path: str,
context: MessageContext,
+ *,
+ composite_key: str | None = None,
):
"""Receive messages from Claude SDK client."""
try:
session_key = self.controller._get_session_key(context)
- composite_key = f"{base_session_id}:{working_path}"
+ composite_key = composite_key or f"{base_session_id}:{working_path}"
# Build a request object for question handler
request = AgentRequest(
@@ -479,7 +491,7 @@ class ClaudeAgent(BaseAgent):
mark_session_idle(composite_key)
session = await self.session_manager.get_or_create_session(context.user_id, context.channel_id)
if session:
- session.session_active[f"{base_session_id}:{working_path}"] = False
+ session.session_active[composite_key] = False
continue
# Ignore UserMessage/tool results; toolcalls are emitted from ToolUseBlock.
@@ -491,7 +503,7 @@ class ClaudeAgent(BaseAgent):
# Receiver task was explicitly cancelled (e.g. /stop, /clear,
# or a new message replacing the session). Clean up reactions
# because this receiver will never process another result.
- composite_key = f"{base_session_id}:{working_path}"
+ composite_key = composite_key or f"{base_session_id}:{working_path}"
mark_session_idle = getattr(self.session_handler, "mark_session_idle", None)
if callable(mark_session_idle):
mark_session_idle(composite_key)
@@ -499,7 +511,7 @@ class ClaudeAgent(BaseAgent):
await self._clear_pending_reactions(composite_key, context)
raise
except Exception as e:
- composite_key = f"{base_session_id}:{working_path}"
+ composite_key = composite_key or f"{base_session_id}:{working_path}"
mark_session_idle = getattr(self.session_handler, "mark_session_idle", None)
if callable(mark_session_idle):
mark_session_idle(composite_key)
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index f0501e008..89ff68662 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -60,6 +60,64 @@ class _StubController:
class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
+ async def test_handle_message_uses_runtime_session_key_for_claude_tracking(self):
+ controller = _StubController()
+ controller.emit_agent_message = AsyncMock()
+ runtime_key = "wechat_o9:reviewer:/tmp/work"
+ client = SimpleNamespace(
+ query=AsyncMock(),
+ _vibe_runtime_base_session_id="wechat_o9:reviewer",
+ _vibe_runtime_session_key=runtime_key,
+ )
+ controller.session_handler = SimpleNamespace(
+ get_or_create_claude_session=AsyncMock(return_value=client),
+ mark_session_active=SimpleNamespace(),
+ handle_session_error=AsyncMock(),
+ capture_session_id=lambda *_: None,
+ )
+ mark_active_calls = []
+ controller.session_handler.mark_session_active = lambda composite_key: mark_active_calls.append(composite_key)
+
+ agent = ClaudeAgent(controller)
+ agent._prepare_message_with_files = lambda request: request.message
+ agent._delete_ack = AsyncMock()
+ agent._receive_messages = AsyncMock()
+
+ request = SimpleNamespace(
+ context=SimpleNamespace(),
+ message="hello",
+ working_path="/tmp/work",
+ base_session_id="wechat_o9",
+ composite_session_id="wechat_o9:/tmp/work",
+ session_key="wechat-user",
+ subagent_name=None,
+ subagent_model=None,
+ subagent_reasoning_effort=None,
+ ack_message_id=None,
+ ack_reaction_message_id="m1",
+ ack_reaction_emoji=":eyes:",
+ files=None,
+ )
+
+ await agent.handle_message(request)
+ await asyncio.sleep(0)
+
+ controller.session_handler.get_or_create_claude_session.assert_awaited_once()
+ self.assertEqual(mark_active_calls, [runtime_key])
+ client.query.assert_awaited_once_with("hello", session_id=runtime_key)
+ self.assertIn(runtime_key, agent._pending_requests)
+ self.assertIn(runtime_key, agent._pending_reactions)
+ self.assertNotIn(request.composite_session_id, agent._pending_requests)
+ self.assertNotIn(request.composite_session_id, agent._pending_reactions)
+ self.assertIn(runtime_key, controller.receiver_tasks)
+ agent._receive_messages.assert_awaited_once_with(
+ client,
+ "wechat_o9:reviewer",
+ "/tmp/work",
+ request.context,
+ composite_key=runtime_key,
+ )
+
async def test_clear_sessions_cancels_receiver_tasks_for_cleared_session(self):
controller = _StubController()
agent = ClaudeAgent(controller)
diff --git a/tests/test_claude_cli_path.py b/tests/test_claude_cli_path.py
index 1fbf8888b..e10a3cec0 100644
--- a/tests/test_claude_cli_path.py
+++ b/tests/test_claude_cli_path.py
@@ -133,6 +133,8 @@ def test_session_handler_passes_configured_claude_cli_path(monkeypatch, tmp_path
assert captured["connected"] is True
assert captured["options"].cli_path == "/usr/local/bin/claude-proxy"
assert controller.claude_sessions[f"slack_C123:{tmp_path}"] is client
+ assert getattr(client, "_vibe_runtime_base_session_id") == "slack_C123"
+ assert getattr(client, "_vibe_runtime_session_key") == f"slack_C123:{tmp_path}"
def test_session_handler_keeps_sdk_default_for_default_claude_binary(monkeypatch, tmp_path: Path) -> None: