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(stop): serialize terminal ownership
cyh9f63edab352e
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.pyindex 597789da2..49ba1b239 100644--- a/modules/agents/codex/agent.py+++ b/modules/agents/codex/agent.py@@ -647,11 +647,18 @@ class CodexAgent(BaseAgent):{"threadId": thread_id, "turnId": turn_id},)interrupted_request = self._event_handler.clear_pending(turn_id)- if interrupted_request and self.consume_user_stop_intent(turn_id):+ stopped_by_user = self.consume_user_stop_intent(turn_id)+ if interrupted_request and stopped_by_user:await self._remove_ack_reaction(interrupted_request,terminal_emoji=STOPPED_REACTION_EMOJI,)+ elif interrupted_request is None and stopped_by_user:+ # A normal/failed completion won the race and popped the turn+ # without consuming the stop intent. Its own terminal output is+ # authoritative, so do not overwrite it with a silent cancel.+ logger.info("Codex turn %s completed before /stop claimed it", turn_id)+ return True# 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 without a@@ -673,10 +680,12 @@ class CodexAgent(BaseAgent):except Exception as e:request.stop_failure_reason = "interrupt_failed"logger.error("Failed to interrupt Codex turn: %s", e)- # The turn was not stopped, so nothing is owed a stopped receipt;- # leaving the intent behind would mis-stamp a later ending.- self._user_stopped_turn_ids.discard(turn_id)return False+ finally:+ # A normal/failed completion does not consume stop intent, and the+ # caller itself may be cancelled while the RPC is in flight. Never+ # let either path leave a stale turn id in this long-lived agent.+ self._user_stopped_turn_ids.discard(turn_id)def consume_user_stop_intent(self, turn_id: str) -> bool:"""Claim the /stop intent for ``turn_id``; True for the first claimer only.diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.pyindex 3837e4cd0..5e3a70686 100644--- a/modules/agents/opencode/agent.py+++ b/modules/agents/opencode/agent.py@@ -60,7 +60,6 @@ from .message_processor import OpenCodeMessageProcessorMixinfrom .poll_loop import (OpenCodePollLoop,restored_platform_from_poll_info,- restored_request_from_poll_info,restored_session_key_from_poll_info,)from .server import (@@ -539,15 +538,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):self._poll_loop = OpenCodePollLoop(self)self._active_requests: Dict[str, asyncio.Task] = {}- # The AgentRequest each active task is serving, keyed exactly like- # ``_active_requests``. ``handle_stop`` receives a *freshly built*- # request describing the ``/stop`` message itself, so it is not a usable- # indicator target: the 👀 sits on the message that opened the turn.- # Only paths that end a turn from OUTSIDE its coroutine need this.- # Restored polls reconstruct and register the same request shape before- # becoming stoppable, so their cancellation can stamp the original turn's- # message instead of the fresh /stop request.- self._active_ack_requests: Dict[str, AgentRequest] = {}# Sessions whose in-flight task is being cancelled BY THE USER. The# cancellation lands in the request coroutine, which cannot otherwise# tell a /stop from any other teardown; see ``handle_stop``.@@ -834,7 +824,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):task = asyncio.create_task(self._process_message(request))self._active_requests[request.base_session_id] = task- self._active_ack_requests[request.base_session_id] = requestif not task:return@@ -846,7 +835,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):finally:if self._active_requests.get(request.base_session_id) is task:self._active_requests.pop(request.base_session_id, None)- self._active_ack_requests.pop(request.base_session_id, None)self._session_manager.pop_request_session(request.base_session_id)# The poll loop ran to completion above (handle_message awaits the# task), so the turn is fully settled here. Release any web-Chat@@ -1651,12 +1639,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):)def consume_user_stop_intent(self, base_session_id: str) -> bool:- """Claim the /stop intent for ``base_session_id``; True for the first claimer.-- Two paths can end a stopped turn — the request coroutine's cancellation- handler, and ``handle_stop`` itself when the coroutine settled during the- abort — and exactly one of them owes the ⏹️. Claiming decides which.- """+ """Let the cancelled request coroutine claim its /stop receipt once."""if not base_session_id or base_session_id not in self._user_stopped_sessions:return False@@ -1669,54 +1652,42 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):request.stop_failure_reason = "not_active"return False- # Read alongside ``task``, not after the abort. Aborting can make the- # task settle normally, which lets ``handle_message``'s ``finally`` run- # and pop this entry while we are still awaiting — by the time the- # receipt branch below looks, the request it needs would be gone.- stopped_request = self._active_ack_requests.get(request.base_session_id)-req_info = self._session_manager.get_request_session(request.base_session_id)opencode_session_id = Noneif req_info:opencode_session_id = req_info[0]# Claimed BEFORE the abort: the request coroutine is what owns the 👀,- # and its cancellation handler is the only place that can trade it for- # the ⏹️ receipt. Without this it cannot tell a /stop from a shutdown.+ # and its cancellation handler is the only place that trades it for the+ # ⏹️ receipt. The helper waits for any already-started steering write,+ # then cancels under that same lock before awaiting the native abort.self._user_stopped_sessions.add(request.base_session_id)+ cancellation_claimed = Falsetry:try:- await self._abort_active_request(request.base_session_id, task, req_info)+ cancellation_claimed = await self._abort_active_request(+ request.base_session_id,+ task,+ req_info,+ cancel_before_abort=True,+ )except Exception as e:logger.warning(f"Failed to abort OpenCode session: {e}")+ cancellation_claimed = task.cancelling() > 0 or task.cancelled()++ if not cancellation_claimed:+ # The runner completed while Stop was waiting for a steering+ # write. Its result/error is authoritative; do not append a+ # stopped receipt or a silent cancellation settlement.+ logger.info(+ "OpenCode session %s completed before /stop claimed it",+ request.base_session_id,+ )+ return True- task.cancel()try:await taskexcept asyncio.CancelledError:pass-- if self.consume_user_stop_intent(request.base_session_id):- # Nobody claimed the intent, so the cancellation handler never- # ran: the abort made the poll loop settle on its own while we- # were awaiting it, and ``task.cancel()`` hit an already-finished- # task. The receipt is still owed — this stop is about to emit a- # silent result, so without it the turn ends with no trace.- #- # Stamped on the turn's OWN request, never on ``request``: that- # one describes the ``/stop`` message, so finishing it would put- # the ⏹️ on the command instead of on the message that started- # the turn (and leave the real 👀 behind). Codex does the same- # with the request it recovers from ``clear_pending``.- if stopped_request is not None:- await self._remove_ack_reaction(- stopped_request,- terminal_emoji=STOPPED_REACTION_EMOJI,- )- else:- logger.debug(- "OpenCode stop of %s has no retained request; skipping the receipt",- request.base_session_id,- )finally:# Only reached with the intent still set if something above raised# past the handlers; a claimed intent is already gone.@@ -1768,18 +1739,29 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):base_session_id: str,task: asyncio.Task,request_session: tuple[str, str, str] | None,- ) -> None:+ *,+ cancel_before_abort: bool = False,+ ) -> bool:state = self._steering_states.get(base_session_id)if state is not None and state.task is task:async with state.lock:state.closing = True+ if cancel_before_abort:+ if task.done():+ return False+ task.cancel()if request_session:server = await self._get_server()await server.abort_session(request_session[0], request_session[1])- return+ return True+ if cancel_before_abort:+ if task.done():+ return False+ task.cancel()if request_session:server = await self._get_server()await server.abort_session(request_session[0], request_session[1])+ return Truedef runtime_turn_keys_for_session_key(self, session_key: str) -> set[str]:return {@@ -1981,7 +1963,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):restoration_ready = asyncio.get_running_loop().create_future()restoration_published = asyncio.Event()- restored_request = restored_request_from_poll_info(self, poll_info)task = asyncio.create_task(self._run_restored_poll_loop_with_tracking(poll_info,@@ -1995,7 +1976,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):(restoration_ready, restoration_published, poll_info))self._active_requests[poll_info.base_session_id] = task- self._active_ack_requests[poll_info.base_session_id] = restored_requestself._session_manager.set_request_session(poll_info.base_session_id,poll_info.opencode_session_id,@@ -2198,7 +2178,6 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):)if self._active_requests.get(poll_info.base_session_id) is current_task:self._active_requests.pop(poll_info.base_session_id, None)- self._active_ack_requests.pop(poll_info.base_session_id, None)self._session_manager.pop_request_session(poll_info.base_session_id)if restoration_ready is not None and not restoration_ready.done():restoration_ready.set_result(False)diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.pyindex e7eef7185..9fb417c0b 100644--- a/modules/agents/opencode/poll_loop.py+++ b/modules/agents/opencode/poll_loop.py@@ -519,10 +519,7 @@ class OpenCodePollLoop:"""Continue a poll loop that was interrupted by restart."""session_id = poll_info.opencode_session_id- active_ack_requests = getattr(self._agent, "_active_ack_requests", {})- restored_request = active_ack_requests.get(- poll_info.base_session_id- ) or self._build_restored_ack_request(poll_info)+ restored_request = self._build_restored_ack_request(poll_info)context = restored_request.contextprocessing_snapshot = (poll_info.processing_indicator if isinstance(poll_info.processing_indicator, dict) else {}diff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.pyindex a3e6f4dfe..bb04fc803 100644--- a/tests/test_agent_steering.py+++ b/tests/test_agent_steering.py@@ -603,7 +603,6 @@ def _opencode_agent(primary: AgentRequest, task: asyncio.Task, server: _OpenCode)agent._client_manager = SimpleNamespace(_server_manager=server)agent._user_stopped_sessions = set()- agent._active_ack_requests = {}agent._steering_states = {primary.base_session_id: _OpenCodeSteerState(task=task,diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.pyindex 7478f3d9d..ad424b291 100644--- a/tests/test_codex_agent.py+++ b/tests/test_codex_agent.py@@ -654,6 +654,29 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):# The stop is silent, so the ⏹️ receipt replacing the running 👀 is the# only thing that tells the user the turn ended on their command.self.assertEqual(events[2], ("ack", STOPPED_REACTION_EMOJI))+ self.assertEqual(agent._user_stopped_turn_ids, set())++ async def test_handle_stop_does_not_cancel_a_turn_that_completed_during_rpc(self):+ agent = object.__new__(CodexAgent)+ agent._session_mgr = SimpleNamespace(get_thread_id=lambda base_session_id: "thread-1")+ agent._turn_registry = _StubTurnRegistry()+ agent._turn_registry._active_turns["session-1"] = "turn-1"+ agent._user_stopped_turn_ids = set()+ agent._transports = {"/tmp": SimpleNamespace(is_alive=True, send_request=AsyncMock(return_value={}))}+ # None with the intent still present means a normal/failed completion+ # popped the turn; an interrupted completion would consume the intent.+ agent._event_handler = SimpleNamespace(clear_pending=Mock(return_value=None))+ agent._remove_ack_reaction = AsyncMock()+ agent.controller = SimpleNamespace(emit_agent_message=AsyncMock())++ request = SimpleNamespace(base_session_id="session-1", working_path="/tmp", context=object())++ result = await agent.handle_stop(request)++ self.assertTrue(result)+ agent._remove_ack_reaction.assert_not_awaited()+ agent.controller.emit_agent_message.assert_not_awaited()+ self.assertEqual(agent._user_stopped_turn_ids, set())async def test_refresh_auth_state_stops_transports_and_invalidates_threads(self):agent = object.__new__(CodexAgent)diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.pyindex 871acd082..cff08c643 100644--- a/tests/test_multi_platform_runtime.py+++ b/tests/test_multi_platform_runtime.py@@ -1244,7 +1244,6 @@ def test_opencode_normal_text_matching_legacy_question_prefix_is_processed():agent.settings_manager = agent.controller.settings_manageragent._session_manager = _SessionManager()agent._active_requests = {}- agent._active_ack_requests = {}async def _process_message(request):processed.append(request.message)diff --git a/tests/test_opencode_restore_polls.py b/tests/test_opencode_restore_polls.pyindex f2091be2f..0a7f6e424 100644--- a/tests/test_opencode_restore_polls.py+++ b/tests/test_opencode_restore_polls.py@@ -131,7 +131,6 @@ def _build_agent(active_polls: dict[str, ActivePollInfo], *, language: str = "enagent._poll_loop = _PollLoop()agent._session_manager = _SessionManager()agent._active_requests = {}- agent._active_ack_requests = {}agent._user_stopped_sessions = set()agent._steering_states = {}agent._restored_poll_servers = {}@@ -228,11 +227,8 @@ def test_restore_im_registration_failure_retries_before_releasing_poll() -> Noneawait asyncio.wait_for(poll_started.wait(), timeout=1)task = agent._active_requests[poll.base_session_id]assert not task.done()- restored_request = agent._active_ack_requests[poll.base_session_id]- assert restored_request.base_session_id == poll.base_session_idrelease_poll.set()await task- assert agent._active_ack_requests == {}return restoredassert asyncio.run(_run()) == 1diff --git a/tests/test_opencode_stop_receipt.py b/tests/test_opencode_stop_receipt.pyindex 3b0c42992..1af9ff574 100644--- a/tests/test_opencode_stop_receipt.py+++ b/tests/test_opencode_stop_receipt.py@@ -25,16 +25,21 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1]))from config.v2_sessions import ActivePollInfofrom core.processing_indicator import STOPPED_REACTION_EMOJI, ProcessingIndicatorServicefrom modules.agents.opencode.agent import OpenCodeAgent-from modules.agents.opencode.poll_loop import OpenCodePollLoop, restored_request_from_poll_info+from modules.agents.opencode.poll_loop import OpenCodePollLoopdef _agent():agent = object.__new__(OpenCodeAgent)agent._active_requests = {}- agent._active_ack_requests = {}agent._user_stopped_sessions = set()agent._session_manager = SimpleNamespace(get_request_session=lambda _base: None)- agent._abort_active_request = AsyncMock()++ async def _abort(_base, task, _request_session, *, cancel_before_abort=False):+ if cancel_before_abort and not task.done():+ task.cancel()+ return True++ agent._abort_active_request = AsyncMock(side_effect=_abort)agent.sessions = SimpleNamespace(remove_active_poll=Mock())agent.controller = SimpleNamespace(emit_agent_message=AsyncMock())return agent@@ -78,7 +83,6 @@ class OpenCodeStopIntentTests(unittest.IsolatedAsyncioTestCase):async def test_intent_is_released_even_when_the_abort_fails(self):agent = _agent()- agent._abort_active_request = AsyncMock(side_effect=RuntimeError("server gone"))async def in_flight():await asyncio.sleep(3600)@@ -87,131 +91,85 @@ class OpenCodeStopIntentTests(unittest.IsolatedAsyncioTestCase):agent._active_requests["session-1"] = taskawait asyncio.sleep(0)+ async def abort_then_fail(*_args, cancel_before_abort=False, **_kwargs):+ self.assertTrue(cancel_before_abort)+ task.cancel()+ raise RuntimeError("server gone")++ agent._abort_active_request = AsyncMock(side_effect=abort_then_fail)+result = await agent.handle_stop(_request())self.assertTrue(result)self.assertEqual(agent._user_stopped_sessions, set())- async def test_task_that_settles_during_the_abort_still_gets_the_receipt(self):- """The abort can end the poll loop before ``task.cancel()`` is reached.+ async def test_stop_cancels_before_native_abort_can_release_normal_completion(self):+ """Once stop accepts an active task, normal completion cannot win."""- Then the cancellation handler — the only other receipt-stamping path —- never runs, ``cancel()`` is a no-op on a finished task, and the silent- stop result that follows would leave the turn with no trace at all.- """agent = _agent()- receipts: list[tuple[object, object]] = []- agent._remove_ack_reaction = AsyncMock(- side_effect=lambda request, *, terminal_emoji=None: receipts.append(- (request, terminal_emoji)- )- )+ release_normal_completion = asyncio.Event()+ outcomes: list[str] = []+ abort_observed_cancelling: list[bool] = []async def in_flight():- await asyncio.sleep(3600)-- task = asyncio.create_task(in_flight())- agent._active_requests["session-1"] = task- turn_request = _request()- agent._active_ack_requests["session-1"] = turn_request- await asyncio.sleep(0)-- async def abort(*_args, **_kwargs):- # Whatever the abort does upstream, the effect here is a task that is- # already finished by the time control comes back.- task.cancel()try:- await task+ await release_normal_completion.wait()+ outcomes.append("result")except asyncio.CancelledError:- pass-- agent._abort_active_request = abort-- stop_request = _request()- self.assertTrue(await agent.handle_stop(stop_request))-- # The receipt belongs on the TURN's request. ``stop_request`` describes- # the /stop message, so stamping that one would put the ⏹️ on the command- # and leave the real 👀 in place.- self.assertEqual(receipts, [(turn_request, STOPPED_REACTION_EMOJI)])- self.assertIsNot(receipts[0][0], stop_request)- self.assertEqual(agent._user_stopped_sessions, set())-- async def test_receipt_survives_handle_messages_cleanup_racing_the_abort(self):- """The waiter that owns the turn can finish its ``finally`` mid-abort.-- ``handle_message`` is blocked on ``await task``; a task settled by the- abort wakes it, and it pops both registries before ``handle_stop``- resumes. Looking the request up after the abort finds nothing, so the- receipt has to be captured up front.- """- agent = _agent()- receipts: list[tuple[object, object]] = []- agent._remove_ack_reaction = AsyncMock(- side_effect=lambda request, *, terminal_emoji=None: receipts.append(- (request, terminal_emoji)- )- )-- async def in_flight():- await asyncio.sleep(3600)+ outcomes.append("stopped")+ self.assertTrue(agent.consume_user_stop_intent("session-1"))+ raisetask = asyncio.create_task(in_flight())agent._active_requests["session-1"] = task- turn_request = _request()- agent._active_ack_requests["session-1"] = turn_requestawait asyncio.sleep(0)- async def abort(*_args, **_kwargs):+ async def abort(*_args, cancel_before_abort=False, **_kwargs):+ self.assertTrue(cancel_before_abort)task.cancel()- try:- await task- except asyncio.CancelledError:- pass- # Exactly what handle_message's finally does once its await returns.- if agent._active_requests.get("session-1") is task:- agent._active_requests.pop("session-1", None)- agent._active_ack_requests.pop("session-1", None)+ abort_observed_cancelling.append(task.cancelling() > 0)+ release_normal_completion.set()+ await asyncio.sleep(0)+ return Trueagent._abort_active_request = abortself.assertTrue(await agent.handle_stop(_request()))- self.assertEqual(receipts, [(turn_request, STOPPED_REACTION_EMOJI)])- self.assertEqual(agent._active_ack_requests, {})+ self.assertEqual(abort_observed_cancelling, [True])+ self.assertEqual(outcomes, ["stopped"])+ self.assertEqual(agent._user_stopped_sessions, set())- async def test_no_receipt_when_the_turns_request_was_not_retained(self):- # Better no receipt than one stamped on the wrong message: a turn with- # nothing retained (restored poll already cleaned up) just ends silently.+ async def test_result_that_wins_while_stop_waits_for_steering_is_authoritative(self):agent = _agent()- receipts: list[object] = []- agent._remove_ack_reaction = AsyncMock(- side_effect=lambda request, *, terminal_emoji=None: receipts.append(terminal_emoji)- )+ release_result = asyncio.Event()+ outcomes: list[str] = []async def in_flight():- await asyncio.sleep(3600)+ await release_result.wait()+ outcomes.append("result")task = asyncio.create_task(in_flight())agent._active_requests["session-1"] = taskawait asyncio.sleep(0)- async def abort(*_args, **_kwargs):- task.cancel()- try:- await task- except asyncio.CancelledError:- pass+ async def abort(*_args, cancel_before_abort=False, **_kwargs):+ self.assertTrue(cancel_before_abort)+ release_result.set()+ await task+ return Falseagent._abort_active_request = abortself.assertTrue(await agent.handle_stop(_request()))- self.assertEqual(receipts, [])+ self.assertEqual(outcomes, ["result"])+ agent.controller.emit_agent_message.assert_not_awaited()+ self.assertEqual(agent._user_stopped_sessions, set())async def test_the_intent_is_claimed_once(self):- # Both paths call consume; the second must see nothing, or a turn whose- # coroutine already stamped would get a second ⏹️ from handle_stop.+ # The request coroutine may encounter nested cancellation cleanup, but+ # only its first claim may stamp the terminal receipt.agent = _agent()agent._user_stopped_sessions.add("session-1")@@ -252,7 +210,6 @@ class OpenCodeStopIntentTests(unittest.IsolatedAsyncioTestCase):controller=_Controller(),opencode_config=SimpleNamespace(active_turn_timeout_seconds=60),sessions=SimpleNamespace(remove_active_poll=Mock()),- _active_ack_requests={},_user_stopped_sessions={"session-1"},)@@ -282,16 +239,16 @@ class OpenCodeStopIntentTests(unittest.IsolatedAsyncioTestCase):"message_id": "m1",},)- restored_request = restored_request_from_poll_info(agent, poll)- agent._active_ack_requests[poll.base_session_id] = restored_request-task = asyncio.create_task(OpenCodePollLoop(agent).run_restored_poll_loop(poll))await entered.wait()task.cancel()with pytest.raises(asyncio.CancelledError):await task- self.assertEqual(cleanups, [(restored_request, STOPPED_REACTION_EMOJI)])+ self.assertEqual(len(cleanups), 1)+ self.assertEqual(cleanups[0][0].base_session_id, poll.base_session_id)+ self.assertEqual(cleanups[0][0].terminal_reaction_message_id, "m1")+ self.assertEqual(cleanups[0][1], STOPPED_REACTION_EMOJI)self.assertEqual(agent._user_stopped_sessions, set())