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): serialize runtime session turns
cyh8d03be1c7a34
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 24a4b845f..f55cdc320 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -37,8 +37,16 @@ class ClaudeAgent(BaseAgent):self._pending_assistant_message: dict[str, str] = {}self._native_session_ids: dict[str, str] = {}self._suppressed_synthetic_results: set[str] = set()- # Store reaction info per session as a queue (FIFO) for cleanup after result- # Each entry is (reaction_message_id, emoji)+ # A Claude SDK client is a single streaming transport. It does not attach+ # a turn id to ResultMessage events, so Avibe must not write a second+ # prompt into the same runtime session until the first prompt reaches a+ # terminal result. Web Chat has its own gate, but IM/scheduled callers can+ # reach this adapter directly; keep the invariant at the backend boundary.+ self._runtime_turn_locks: dict[str, asyncio.Lock] = {}+ self._runtime_turn_lock_keys: dict[str, tuple[str, ...]] = {}+ # Store reaction info per runtime session for cleanup after terminal+ # result. Under the runtime turn gate there is normally one active entry;+ # the list shape remains for defensive cleanup of older queued state.self._pending_reactions: dict[str, list[tuple[str, str]]] = {}self._pending_requests: dict[str, list[AgentRequest]] = {}@@ -68,6 +76,10 @@ class ClaudeAgent(BaseAgent):context = request.contextruntime_base_session_id = request.base_session_idruntime_session_key = request.composite_session_id+ expected_runtime_key = self._expected_runtime_session_key(request)+ held_expected_key: str | None = None+ active_runtime_key: str | None = None+ turn_registered = False# Question callback handling (disabled - SDK doesn't support AskUserQuestion response)# if self.ENABLE_ASK_USER_QUESTION and request.message.startswith("claude_question:"):@@ -75,6 +87,8 @@ class ClaudeAgent(BaseAgent):# returntry:+ await self._acquire_runtime_turn_lock(expected_runtime_key)+ held_expected_key = expected_runtime_keyclient = await self.session_handler.get_or_create_claude_session(context,subagent_name=request.subagent_name,@@ -87,6 +101,13 @@ class ClaudeAgent(BaseAgent):)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)+ if runtime_session_key != expected_runtime_key:+ await self._acquire_runtime_turn_lock(runtime_session_key)+ active_runtime_key = runtime_session_key+ self._runtime_turn_lock_keys[runtime_session_key] = tuple(+ dict.fromkeys((expected_runtime_key, runtime_session_key))+ )+ held_expected_key = Nonemark_session_active = getattr(self.session_handler, "mark_session_active", None)if callable(mark_session_active):mark_session_active(runtime_session_key)@@ -105,10 +126,6 @@ class ClaudeAgent(BaseAgent):message = self._prepare_message_with_files(request)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 (runtime_session_key not in self.receiver_tasksor self.receiver_tasks[runtime_session_key].done()@@ -122,8 +139,27 @@ class ClaudeAgent(BaseAgent):composite_key=runtime_session_key,))+ turn_registered = True+ logger.info(f"Sent message to Claude for session {runtime_session_key}")++ await self._delete_ack(context, request)+ except asyncio.CancelledError:+ if not turn_registered:+ await self._remove_specific_pending_reaction(runtime_session_key, context, request)+ self._remove_pending_request(runtime_session_key, request)+ self._mark_session_idle_if_no_pending_requests(runtime_session_key)+ await self._delete_ack(context, request)+ if active_runtime_key:+ self._release_runtime_turn(active_runtime_key)+ elif held_expected_key:+ self._release_runtime_turn_lock(held_expected_key)+ raiseexcept Exception as e:logger.error(f"Error processing Claude message: {e}", exc_info=True)+ if not turn_registered and active_runtime_key:+ self._release_runtime_turn(active_runtime_key or runtime_session_key)+ elif not turn_registered and held_expected_key:+ self._release_runtime_turn_lock(held_expected_key)# Clean up the specific reaction for this request (not FIFO)await self._remove_specific_pending_reaction(runtime_session_key, context, request)self._remove_pending_request(runtime_session_key, request)@@ -158,6 +194,33 @@ class ClaudeAgent(BaseAgent):finally:await self._delete_ack(context, request)+ async def _acquire_runtime_turn_lock(self, composite_key: str) -> None:+ if not composite_key:+ return+ lock = self._runtime_turn_locks.get(composite_key)+ if lock is None:+ lock = asyncio.Lock()+ self._runtime_turn_locks[composite_key] = lock+ await lock.acquire()++ def _release_runtime_turn(self, composite_key: str) -> None:+ if not composite_key:+ return+ lock_keys = self._runtime_turn_lock_keys.pop(composite_key, None) or (composite_key,)+ for lock_key in reversed(lock_keys):+ self._release_runtime_turn_lock(lock_key)++ def _release_runtime_turn_lock(self, composite_key: str) -> None:+ lock = self._runtime_turn_locks.get(composite_key)+ if lock is not None and lock.locked():+ lock.release()++ @staticmethod+ def _expected_runtime_session_key(request: AgentRequest) -> str:+ payload = getattr(request.context, "platform_specific", None) or {}+ backend_key = str(payload.get("backend_composite_session_id") or "").strip()+ return backend_key or request.composite_session_id+async def _handle_question_callback(self, request: AgentRequest) -> None:"""Handle question-related callbacks (button clicks, modal submissions).@@ -309,6 +372,7 @@ class ClaudeAgent(BaseAgent):if not preserve_pending_request_state:self._pending_reactions.pop(composite_key, None)self._pending_requests.pop(composite_key, None)+ self._release_runtime_turn(composite_key)cleanup = getattr(self.session_handler, "cleanup_session", None)if callable(cleanup):await cleanup(composite_key, current_receiver_task=current_receiver_task)@@ -339,6 +403,8 @@ class ClaudeAgent(BaseAgent):try:if hasattr(client, "interrupt"):await client.interrupt()+ stopped_request = self._pop_pending_request(composite_key)+ self._adopt_pending_turn_token(request.context, stopped_request)# A user-initiated stop is terminal but intentional, so it carries# NO user-facing message: a single SILENT result settles the dot to# idle + releases the SSE waiter through the outbound chokepoint@@ -348,6 +414,8 @@ class ClaudeAgent(BaseAgent):await self.controller.emit_agent_message(request.context, "result", "", level="silent")+ self._mark_session_idle_if_no_pending_requests(composite_key)+ await self._cleanup_runtime_session(composite_key)return Trueelse:request.stop_failure_reason = "unsupported"@@ -455,6 +523,7 @@ class ClaudeAgent(BaseAgent):if callable(mark_session_idle):mark_session_idle(composite_key)await self._clear_pending_reactions(composite_key, context)+ self._release_runtime_turn(composite_key)self._last_assistant_text.pop(composite_key, None)self._pending_assistant_message.pop(composite_key, None)return@@ -538,6 +607,7 @@ class ClaudeAgent(BaseAgent):if callable(mark_session_idle):mark_session_idle(composite_key)await self._clear_pending_reactions(composite_key, context)+ self._release_runtime_turn(composite_key)returncontinue@@ -565,6 +635,7 @@ class ClaudeAgent(BaseAgent):if callable(mark_session_idle):mark_session_idle(composite_key)await self._clear_pending_reactions(composite_key, context)+ self._release_runtime_turn(composite_key)self._last_assistant_text.pop(composite_key, None)self._pending_assistant_message.pop(composite_key, None)return@@ -610,6 +681,7 @@ class ClaudeAgent(BaseAgent):session = await self.session_manager.get_or_create_session(context.user_id, context.channel_id)if session and is_idle:session.session_active[composite_key] = False+ self._release_runtime_turn(composite_key)continue# Ignore UserMessage/tool results; toolcalls are emitted from ToolUseBlock.@@ -627,6 +699,7 @@ class ClaudeAgent(BaseAgent):mark_session_idle(composite_key)logger.info("Claude receiver cancelled for session %s", composite_key)await self._clear_pending_reactions(composite_key, context)+ self._release_runtime_turn(composite_key)raiseexcept Exception as e:composite_key = composite_key or f"{base_session_id}:{working_path}"@@ -675,6 +748,7 @@ class ClaudeAgent(BaseAgent):# the 600s stream timeout and then settle idle. No-op off-workbench# (Codex P2).await self.controller.emit_agent_message(context, "result", "", is_error=True)+ self._release_runtime_turn(composite_key)# NOTE: no `finally` cleanup of pending reactions here.# When the receiver ends normally (stream exhausted after a result),# new messages may have already queued their reactions via@@ -713,6 +787,7 @@ class ClaudeAgent(BaseAgent):self._suppressed_synthetic_results.add(composite_key)self._discard_pending_reaction(composite_key)self._mark_session_idle_if_no_pending_requests(composite_key)+ self._release_runtime_turn(composite_key)return Truedef _consume_suppressed_synthetic_result(self, composite_key: str, message, text: Optional[str]) -> bool:@@ -748,7 +823,8 @@ class ClaudeAgent(BaseAgent):async def _remove_pending_reaction(self, composite_key: str, context: MessageContext) -> None:"""Remove the oldest stored reaction for a session after result is sent.- Uses FIFO queue to handle multiple messages in the same session.+ The backend turn gate normally leaves at most one pending reaction, but+ keep FIFO cleanup for defensive compatibility with older queued state."""reactions = self._pending_reactions.get(composite_key)if reactions:@@ -783,14 +859,13 @@ class ClaudeAgent(BaseAgent):def _adopt_pending_turn_token(context: MessageContext, pending_request: Optional[AgentRequest]) -> None:"""Copy the pending turn's ``turn_token`` onto the reused receiver context.- Claude runs one long-lived receiver per session, so the context captured- when it started carries the FIRST turn's ``turn_token``. The streaming- completion guard in ``core.message_dispatcher._stream_chunk`` correlates a- ``result`` emit to the live turn sink by that token; without this the- current turn's result would carry a stale token and be rejected, hanging- the SSE stream until the safety timeout. Pulling the token from the- FIFO-matched pending request realigns it. No-op when there's no pending- request or it carries no token (fail-open: completion stays ungated)."""+ Claude runs one long-lived receiver per runtime session, so the context+ captured when it started can carry an older turn's ``turn_token``. The+ streaming completion guard in ``core.message_dispatcher._stream_chunk``+ correlates a ``result`` emit to the live turn sink by that token; without+ this, later turns could be rejected as stale. Pulling the token from the+ current pending request realigns it. No-op when there's no pending request+ or it carries no token (fail-open: completion stays ungated)."""if pending_request is None:returnsrc = getattr(pending_request, "context", None)@@ -805,13 +880,11 @@ class ClaudeAgent(BaseAgent):"""Retire a terminal auth-failure turn from the pending FIFO.The auth error IS this turn's (failed) result, so pop its pending request:- leaving the failed entry desyncs request↔result pairing, so the NEXT- successful turn would FIFO-pop this stale request and adopt its old+ leaving the failed entry would make the next result adopt the old``turn_token`` — then ``_stream_chunk`` rejects the live turn's completionand Stop sticks until the safety timeout. Adopt the failed turn's own token- and release its Chat stream now. Called from every auth-failure terminal- path (result / system / assistant); the dot was already settled and the- recovery notify persisted by ``maybe_emit_auth_recovery_message``."""+ and release its Chat stream now. Called from auth-failure terminal paths+ after the recovery notify has been persisted."""failed_request = self._pop_pending_request(composite_key)self._adopt_pending_turn_token(context, failed_request)_mark = getattr(self.controller, "mark_turn_complete", None)diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.pyindex c7bc37622..5d9dff40d 100644--- a/tests/test_claude_agent_sessions.py+++ b/tests/test_claude_agent_sessions.py@@ -99,6 +99,207 @@ class _StubController:class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):+ async def test_handle_message_serializes_queries_for_same_runtime_session(self):+ controller = _StubController()+ runtime_key = "wechat_o9:/tmp/work"+ first_query_started = asyncio.Event()+ release_result = asyncio.Event()+ queries: list[tuple[str, str]] = []++ class ResultMessage:+ subtype = "success"+ result = "done"+ duration_ms = 1++ class _Client:+ _vibe_runtime_base_session_id = "wechat_o9"+ _vibe_runtime_session_key = runtime_key++ async def query(self, message, *, session_id):+ queries.append((message, session_id))+ if len(queries) == 1:+ first_query_started.set()++ def receive_messages(self):+ async def _iterate():+ await release_result.wait()+ yield ResultMessage()++ return _iterate()++ client = _Client()+ controller._get_session_key = lambda _context: "wechat-user"+ controller.emit_agent_message = AsyncMock()+ controller.session_handler = SimpleNamespace(+ get_or_create_claude_session=AsyncMock(return_value=client),+ mark_session_active=lambda _key: None,+ mark_session_idle=lambda _key: None,+ handle_session_error=AsyncMock(),+ capture_session_id=lambda *_args, **_kwargs: None,+ )++ agent = ClaudeAgent(controller)+ agent._prepare_message_with_files = lambda request: request.message+ agent._delete_ack = AsyncMock()+ agent.emit_result_message = AsyncMock()++ def _request(message: str):+ return SimpleNamespace(+ context=SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform_specific={"turn_token": message},+ ),+ message=message,+ working_path="/tmp/work",+ base_session_id="wechat_o9",+ composite_session_id=runtime_key,+ session_key="wechat-user",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ ack_message_id=None,+ ack_reaction_message_id=None,+ ack_reaction_emoji=None,+ files=None,+ )++ first = asyncio.create_task(agent.handle_message(_request("first")))+ await asyncio.wait_for(first_query_started.wait(), timeout=3)+ await asyncio.sleep(0)+ second = asyncio.create_task(agent.handle_message(_request("second")))+ await asyncio.sleep(0.05)++ self.assertEqual(+ queries,+ [("first", runtime_key)],+ "the second prompt must not be written into the same Claude runtime before the first result",+ )++ release_result.set()+ await asyncio.wait_for(first, timeout=3)+ await asyncio.wait_for(second, timeout=3)++ self.assertEqual(queries, [("first", runtime_key), ("second", runtime_key)])++ async def test_cancelled_waiter_does_not_leak_runtime_session_lock(self):+ controller = _StubController()+ runtime_key = "wechat_o9:/tmp/work"+ first_query_started = asyncio.Event()+ release_result = asyncio.Event()+ queries: list[tuple[str, str]] = []++ class ResultMessage:+ subtype = "success"+ result = "done"+ duration_ms = 1++ class _Client:+ _vibe_runtime_base_session_id = "wechat_o9"+ _vibe_runtime_session_key = runtime_key++ async def query(self, message, *, session_id):+ queries.append((message, session_id))+ if len(queries) == 1:+ first_query_started.set()++ def receive_messages(self):+ async def _iterate():+ await release_result.wait()+ yield ResultMessage()++ return _iterate()++ client = _Client()+ controller._get_session_key = lambda _context: "wechat-user"+ controller.emit_agent_message = AsyncMock()+ controller.session_handler = SimpleNamespace(+ get_or_create_claude_session=AsyncMock(return_value=client),+ mark_session_active=lambda _key: None,+ mark_session_idle=lambda _key: None,+ handle_session_error=AsyncMock(),+ capture_session_id=lambda *_args, **_kwargs: None,+ )++ agent = ClaudeAgent(controller)+ agent._prepare_message_with_files = lambda request: request.message+ agent._delete_ack = AsyncMock()+ agent.emit_result_message = AsyncMock()++ def _request(message: str):+ return SimpleNamespace(+ context=SimpleNamespace(user_id="U1", channel_id="C1", platform_specific={}),+ message=message,+ working_path="/tmp/work",+ base_session_id="wechat_o9",+ composite_session_id=runtime_key,+ session_key="wechat-user",+ subagent_name=None,+ subagent_model=None,+ subagent_reasoning_effort=None,+ ack_message_id=None,+ ack_reaction_message_id=None,+ ack_reaction_emoji=None,+ files=None,+ )++ first = asyncio.create_task(agent.handle_message(_request("first")))+ await asyncio.wait_for(first_query_started.wait(), timeout=3)+ blocked = asyncio.create_task(agent.handle_message(_request("cancelled")))+ await asyncio.sleep(0.05)+ blocked.cancel()+ with self.assertRaises(asyncio.CancelledError):+ await blocked++ release_result.set()+ await asyncio.wait_for(first, timeout=3)++ third = asyncio.create_task(agent.handle_message(_request("third")))+ await asyncio.wait_for(third, timeout=3)++ self.assertEqual(queries, [("first", runtime_key), ("third", runtime_key)])+ self.assertNotIn(runtime_key, agent._pending_requests)++ async def test_handle_stop_releases_runtime_turn_gate(self):+ controller = _StubController()+ controller.emit_agent_message = AsyncMock()+ runtime_key = "wechat_o9:/tmp/work"+ interrupted = False++ class _Client:+ async def interrupt(self):+ nonlocal interrupted+ interrupted = True++ async def disconnect(self):+ return None++ agent = ClaudeAgent(controller)+ pending_request = SimpleNamespace(context=SimpleNamespace(platform_specific={"turn_token": "T1"}))+ agent._pending_requests[runtime_key] = [pending_request]+ await agent._acquire_runtime_turn_lock(runtime_key)+ agent._runtime_turn_lock_keys[runtime_key] = (runtime_key,)+ controller.claude_sessions[runtime_key] = _Client()++ request = SimpleNamespace(+ context=SimpleNamespace(platform_specific={}),+ composite_session_id=runtime_key,+ stop_failure_reason=None,+ )++ handled = await agent.handle_stop(request)++ self.assertTrue(handled)+ self.assertTrue(interrupted)+ self.assertNotIn(runtime_key, agent._pending_requests)+ self.assertNotIn(runtime_key, controller.claude_sessions)+ controller.session_handler.cleanup_session.assert_awaited_once_with(+ runtime_key,+ current_receiver_task=None,+ )+ self.assertFalse(agent._runtime_turn_locks[runtime_key].locked())+ self.assertEqual(request.context.platform_specific["turn_token"], "T1")+async def test_result_keeps_claude_session_active_when_requests_are_queued(self):controller = _StubController()mark_idle_calls = []