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(stop): hold native abort ownership

cyh49707528e96a
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 5e3a70686..559850863 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -833,19 +833,23 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
except asyncio.CancelledError:
logger.debug(f"OpenCode task cancelled for {request.base_session_id}")
finally:
- if self._active_requests.get(request.base_session_id) is task:
- self._active_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
- # stream waiter: a no-result failure (only a notify was emitted)
- # ends the spinner now instead of waiting out the safety timeout.
- # Token-guarded + no-op for IM/CLI; success already released via the
- # result emit during the poll. Defensive: tolerate controllers
- # without streaming completion support.
- _mark = getattr(self.controller, "mark_turn_complete", None)
- if callable(_mark):
- _mark(request.context)
+ # Stop holds this same lock until the native abort has settled. Keep
+ # the old request's Turn/session ownership until then, so a queued
+ # successor cannot reuse the native session under an in-flight abort.
+ async with lock:
+ if self._active_requests.get(request.base_session_id) is task:
+ self._active_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
+ # stream waiter: a no-result failure (only a notify was emitted)
+ # ends the spinner now instead of waiting out the safety timeout.
+ # Token-guarded + no-op for IM/CLI; success already released via the
+ # result emit during the poll. Defensive: tolerate controllers
+ # without streaming completion support.
+ _mark = getattr(self.controller, "mark_turn_complete", None)
+ if callable(_mark):
+ _mark(request.context)
async def _process_message(self, request: AgentRequest) -> None:
run_registered = False
@@ -1647,71 +1651,76 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
return True
async def handle_stop(self, request: AgentRequest) -> bool:
- task = self._active_requests.get(request.base_session_id)
- if not task or task.done():
- request.stop_failure_reason = "not_active"
- return False
+ lock = self._session_manager.get_session_lock(request.base_session_id)
+ async with lock:
+ # Read the task only after claiming the same ownership boundary used
+ # to start and retire requests. A result that completed while Stop
+ # waited for the lock remains authoritative.
+ task = self._active_requests.get(request.base_session_id)
+ if not task or task.done():
+ request.stop_failure_reason = "not_active"
+ return False
- req_info = self._session_manager.get_request_session(request.base_session_id)
- opencode_session_id = None
- if 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 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 = False
- try:
+ req_info = self._session_manager.get_request_session(request.base_session_id)
+ opencode_session_id = None
+ if 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 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 = False
try:
- 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
+ try:
+ 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
- try:
- await task
- except asyncio.CancelledError:
- pass
- finally:
- # Only reached with the intent still set if something above raised
- # past the handlers; a claimed intent is already gone.
- self._user_stopped_sessions.discard(request.base_session_id)
-
- if opencode_session_id:
- self.sessions.remove_active_poll(opencode_session_id)
-
- # 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 bubble
- # (``level="silent"`` makes that explicit rather than faking it via empty text).
- # ``stop_output_for`` (not the terminal-turn default) keeps this empty body out
- # of the run's terminal state so the stop settles it ``canceled`` instead of
- # ``succeeded`` — see its docstring.
- await self.controller.emit_agent_message(
- request.context,
- "result",
- "",
- level="silent",
- output=stop_output_for(request),
- )
- logger.info(f"OpenCode session {request.base_session_id} terminated via /stop")
- return True
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ finally:
+ # Only reached with the intent still set if something above raised
+ # past the handlers; a claimed intent is already gone.
+ self._user_stopped_sessions.discard(request.base_session_id)
+
+ if opencode_session_id:
+ self.sessions.remove_active_poll(opencode_session_id)
+
+ # 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 bubble
+ # (``level="silent"`` makes that explicit rather than faking it via empty text).
+ # ``stop_output_for`` (not the terminal-turn default) keeps this empty body out
+ # of the run's terminal state so the stop settles it ``canceled`` instead of
+ # ``succeeded`` — see its docstring.
+ await self.controller.emit_agent_message(
+ request.context,
+ "result",
+ "",
+ level="silent",
+ output=stop_output_for(request),
+ )
+ logger.info(f"OpenCode session {request.base_session_id} terminated via /stop")
+ return True
async def clear_sessions(self, session_key: str) -> int:
self.sessions.clear_agent_sessions(session_key, self.name)
diff --git a/modules/im/slack.py b/modules/im/slack.py
index f6dd497aa..b8283b3f0 100644
--- a/modules/im/slack.py
+++ b/modules/im/slack.py
@@ -1409,8 +1409,8 @@ class SlackBot(BaseIMClient):
"🤷": "shrug",
# Terminal receipts. Both forms of each are listed because the
# constants carry U+FE0F and callers may strip it.
- "⏹️": "stop_button",
- "⏹": "stop_button",
+ "⏹️": "black_square_for_stop",
+ "⏹": "black_square_for_stop",
"⚠️": "warning",
"⚠": "warning",
}
diff --git a/tests/test_agent_steering.py b/tests/test_agent_steering.py
index bb04fc803..28ee9f185 100644
--- a/tests/test_agent_steering.py
+++ b/tests/test_agent_steering.py
@@ -110,10 +110,14 @@ class _OpenCodeSessionManager:
def __init__(self, base_session_id: str, native_session_id: str, cwd: str) -> None:
self.base_session_id = base_session_id
self.request_session = (native_session_id, cwd, "session-key")
+ self.session_lock = asyncio.Lock()
def get_request_session(self, base_session_id: str):
return self.request_session if base_session_id == self.base_session_id else None
+ def get_session_lock(self, _base_session_id: str):
+ return self.session_lock
+
class _OpenCodeServer:
def __init__(
diff --git a/tests/test_delivery_ack_reaction.py b/tests/test_delivery_ack_reaction.py
index 2f55a8be7..cb645a938 100644
--- a/tests/test_delivery_ack_reaction.py
+++ b/tests/test_delivery_ack_reaction.py
@@ -489,13 +489,16 @@ class TerminalReceiptEmojiMappingTests(unittest.TestCase):
def test_slack_maps_both_forms_to_short_names(self):
from modules.im.slack import SlackBot
- for emoji in self.receipts:
- for form in (emoji, emoji.replace("️", "")):
- with self.subTest(emoji=form):
- name = SlackBot._slack_reaction_name(form)
- # Unmapped codepoints fall through raw and reactions.add
- # rejects them with ``invalid_name``.
- self.assertTrue(name.isascii(), name)
+ expected = {
+ STOPPED_REACTION_EMOJI: "black_square_for_stop",
+ STOPPED_REACTION_EMOJI.replace("️", ""): "black_square_for_stop",
+ INTERRUPTED_REACTION_EMOJI: "warning",
+ INTERRUPTED_REACTION_EMOJI.replace("️", ""): "warning",
+ }
+ self.assertEqual(
+ {emoji: SlackBot._slack_reaction_name(emoji) for emoji in expected},
+ expected,
+ )
def test_telegram_maps_to_supported_distinct_reactions(self):
from modules.im.telegram import TelegramBot
diff --git a/tests/test_opencode_stop_receipt.py b/tests/test_opencode_stop_receipt.py
index 1af9ff574..47cc9aed3 100644
--- a/tests/test_opencode_stop_receipt.py
+++ b/tests/test_opencode_stop_receipt.py
@@ -32,7 +32,11 @@ def _agent():
agent = object.__new__(OpenCodeAgent)
agent._active_requests = {}
agent._user_stopped_sessions = set()
- agent._session_manager = SimpleNamespace(get_request_session=lambda _base: None)
+ session_lock = asyncio.Lock()
+ agent._session_manager = SimpleNamespace(
+ get_request_session=lambda _base: None,
+ get_session_lock=lambda _base: session_lock,
+ )
async def _abort(_base, task, _request_session, *, cancel_before_abort=False):
if cancel_before_abort and not task.done():
@@ -55,6 +59,44 @@ def _request(session_id="session-1"):
class OpenCodeStopIntentTests(unittest.IsolatedAsyncioTestCase):
+ async def test_native_abort_settles_before_request_releases_turn_ownership(self):
+ agent = _agent()
+ request = _request()
+ request_started = asyncio.Event()
+ abort_started = asyncio.Event()
+ release_abort = asyncio.Event()
+ agent.controller.mark_turn_complete = Mock()
+
+ async def in_flight(_request):
+ request_started.set()
+ await asyncio.Event().wait()
+
+ async def abort(_base, task, _request_session, *, cancel_before_abort=False):
+ self.assertTrue(cancel_before_abort)
+ task.cancel()
+ abort_started.set()
+ await release_abort.wait()
+ return True
+
+ agent._process_message = in_flight
+ agent._abort_active_request = abort
+ agent._session_manager.pop_request_session = Mock()
+
+ message_task = asyncio.create_task(agent.handle_message(request))
+ await request_started.wait()
+ stop_task = asyncio.create_task(agent.handle_stop(request))
+ await abort_started.wait()
+ await asyncio.sleep(0)
+
+ self.assertFalse(message_task.done())
+ agent.controller.mark_turn_complete.assert_not_called()
+
+ release_abort.set()
+ self.assertTrue(await stop_task)
+ await message_task
+
+ agent.controller.mark_turn_complete.assert_called_once_with(request.context)
+
async def test_cancelled_request_sees_the_user_stop_intent(self):
agent = _agent()
observed: list[bool] = []