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(review): stop losing lost-turn reports and /stop receipts

qiqib6f19dc66d2d
diff --git a/core/session_turns.py b/core/session_turns.py
index 8a16e6b8b..687641fdd 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -5420,12 +5420,12 @@ class SessionTurnManager:
has to announce itself.
Recovery runs from ``_on_runtime_ready``, which fires BEFORE an external
- transport has necessarily connected, and the notify dispatcher turns a
- send failure into a ``None`` this method cannot distinguish from success.
- A turn is terminal once reported, so a lost report is lost for good —
- hence the report is held until ``notify_transport_ready`` says that
- platform can actually deliver. ``avibe`` is ready as soon as the runtime
- is, so Workbench sessions still report inline.
+ transport has necessarily connected. A turn is terminal once reported, so
+ a lost report is lost for good — hence the report is held until
+ ``notify_transport_ready`` says that platform can actually deliver, and a
+ send that still fails goes back on the queue rather than being dropped.
+ ``avibe`` is ready as soon as the runtime is, so Workbench sessions
+ report inline.
"""
if self.controller is None:
@@ -5440,17 +5440,18 @@ class SessionTurnManager:
)
return
platform = str(getattr(context, "platform", "") or "")
- if not self._transport_can_deliver(platform):
- self._pending_lost_turn_reports.setdefault(platform, []).append(
- (session_id, str(origin_native_message_id or ""))
- )
- logger.info(
- "lost turn report deferred until %s transport is ready (session=%s)",
- platform,
- session_id,
- )
+ if self._transport_can_deliver(platform) and await self._emit_lost_turn_report(
+ context, session_id, origin_native_message_id
+ ):
return
- await self._emit_lost_turn_report(context, session_id, origin_native_message_id)
+ self._pending_lost_turn_reports.setdefault(platform, []).append(
+ (session_id, str(origin_native_message_id or ""))
+ )
+ logger.info(
+ "lost turn report held until %s transport can deliver (session=%s)",
+ platform,
+ session_id,
+ )
def _transport_can_deliver(self, platform: str) -> bool:
"""Whether ``platform`` can deliver right now.
@@ -5482,6 +5483,7 @@ class SessionTurnManager:
if not pending or self.controller is None:
return 0
reported = 0
+ unsent: list[tuple[str, str]] = []
for session_id, origin_native_message_id in pending:
try:
context = self._delivery_context(session_id)
@@ -5496,6 +5498,20 @@ class SessionTurnManager:
context, session_id, origin_native_message_id
):
reported += 1
+ else:
+ # "Ready" is the transport's claim, not a delivered message: a
+ # transient API error still loses the notice. Popping happened
+ # first, so an unsent report has to be put BACK or the only
+ # record of the interruption is gone for the process's lifetime.
+ unsent.append((session_id, str(origin_native_message_id or "")))
+ if unsent:
+ self._pending_lost_turn_reports.setdefault(platform, []).extend(unsent)
+ logger.info(
+ "%d lost turn report(s) on %s still undelivered; retained for the "
+ "next transport-ready",
+ len(unsent),
+ platform,
+ )
return reported
async def _emit_lost_turn_report(
@@ -5504,8 +5520,17 @@ class SessionTurnManager:
session_id: str,
origin_native_message_id: str,
) -> bool:
+ """Emit one interruption notice. ``False`` means it did NOT reach the user.
+
+ The dispatcher returns the delivered message id, and ``None`` when every
+ send failed — so a falsy return is real evidence of loss, not merely an
+ absent receipt. Treating it as success would stamp a ⚠️ next to a notice
+ nobody got, on a turn that is already terminal and will never be retried
+ by anything else.
+ """
+
try:
- await self.controller.emit_agent_message(
+ delivered = await self.controller.emit_agent_message(
context,
"notify",
i18n_t("turn.interrupted.serviceRestart", self._controller_language()),
@@ -5517,6 +5542,12 @@ class SessionTurnManager:
exc_info=True,
)
return False
+ if not delivered:
+ logger.warning(
+ "lost turn report: notify produced no delivery for session=%s",
+ session_id,
+ )
+ return False
# The dead process could not clear its own 👀. Retire it here so the
# triggering message stops claiming the turn is still running.
native_message_id = str(origin_native_message_id or "")
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 67757bf92..54255984c 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -1264,7 +1264,15 @@ class ClaudeAgent(BaseAgent):
self._adopt_pending_turn_token(request.context, stopped_request)
if stopped_request is not None:
try:
- await self._remove_specific_pending_reaction(composite_key, request.context, stopped_request)
+ # Registry only: ``finish()`` below owns removing the 👀 and
+ # putting ⏹️ in its place, and it can only do that if the
+ # reaction is still on the message when it runs.
+ await self._remove_specific_pending_reaction(
+ composite_key,
+ request.context,
+ stopped_request,
+ clear_on_platform=False,
+ )
await self._remove_ack_reaction(
stopped_request,
terminal_emoji=STOPPED_REACTION_EMOJI,
@@ -3835,11 +3843,23 @@ class ClaudeAgent(BaseAgent):
self._pending_requests.pop(composite_key, None)
async def _remove_specific_pending_reaction(
- self, composite_key: str, context: MessageContext, request: AgentRequest
+ self,
+ composite_key: str,
+ context: MessageContext,
+ request: AgentRequest,
+ *,
+ clear_on_platform: bool = True,
) -> None:
"""Remove a specific reaction from the queue by matching message_id.
Used on error paths to remove the current request's reaction instead of FIFO.
+
+ ``clear_on_platform=False`` forgets the REGISTRY entry only. The registry
+ and the processing indicator both point at the same platform reaction, so
+ a caller that then calls ``_remove_ack_reaction`` would otherwise remove
+ it twice — and the second removal reports failure (the reaction is
+ already gone), which is exactly what suppresses a terminal receipt. A
+ stop hands both platform operations to ``finish()`` instead.
"""
target_id = getattr(request, "ack_reaction_message_id", None)
target_emoji = getattr(request, "ack_reaction_emoji", None)
@@ -3854,6 +3874,8 @@ class ClaudeAgent(BaseAgent):
reactions.pop(i)
if not reactions:
self._pending_reactions.pop(composite_key, None)
+ if not clear_on_platform:
+ return
try:
await self.im_client.remove_reaction(context, msg_id, emoji)
except Exception as err:
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index 5e6d7b2ec..597789da2 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -152,6 +152,11 @@ class CodexAgent(BaseAgent):
self._thread_caller_env_configs: Dict[str, tuple[str, dict[str, str]]] = {}
# base_session_id → (thread_id, effective Git PATH, PATH override persisted)
self._thread_git_path_configs: Dict[str, tuple[str, str, bool]] = {}
+ # Turn ids the USER stopped. ``turn/interrupt`` and the ``turn/completed``
+ # notification it provokes race each other, and whichever arrives first
+ # clears the 👀 — so the stop intent has to outlive both and be consumed
+ # by the winner. See ``consume_user_stop_intent``.
+ self._user_stopped_turn_ids: set[str] = set()
self._fork_correction_pending_base_sessions: set[str] = set()
self._connection_probes: Dict[str, _CodexConnectionProbeState] = {}
self._connection_probe_turns: Dict[str, str] = {}
@@ -629,13 +634,20 @@ class CodexAgent(BaseAgent):
request.stop_failure_reason = "runtime_unavailable"
return False
+ # Recorded BEFORE the RPC. Codex answers an interrupt with a
+ # ``turn/completed`` notification the event worker may process while this
+ # call is still awaiting its response; that handler pops the turn and
+ # clears its reaction, after which ``clear_pending`` here returns None.
+ # Whichever side gets there first consumes the intent and owes the
+ # receipt, so the race can no longer swallow it.
+ self._user_stopped_turn_ids.add(turn_id)
try:
await transport.send_request(
"turn/interrupt",
{"threadId": thread_id, "turnId": turn_id},
)
interrupted_request = self._event_handler.clear_pending(turn_id)
- if interrupted_request:
+ if interrupted_request and self.consume_user_stop_intent(turn_id):
await self._remove_ack_reaction(
interrupted_request,
terminal_emoji=STOPPED_REACTION_EMOJI,
@@ -661,8 +673,24 @@ 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
+ def consume_user_stop_intent(self, turn_id: str) -> bool:
+ """Claim the /stop intent for ``turn_id``; True for the first claimer only.
+
+ Both the interrupt RPC and the ``turn/completed`` notification it causes
+ want to retire the same reaction, and either may run first. Claiming the
+ intent makes the receipt exactly-once instead of dependent on that order.
+ """
+
+ if not turn_id or turn_id not in self._user_stopped_turn_ids:
+ return False
+ self._user_stopped_turn_ids.discard(turn_id)
+ return True
+
async def clear_sessions(self, session_key: str) -> int:
"""Clear sessions scoped to a specific session_key."""
self.sessions.clear_agent_sessions(session_key, self.name)
diff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.py
index 82186f049..f3209ab5e 100644
--- a/modules/agents/codex/event_handler.py
+++ b/modules/agents/codex/event_handler.py
@@ -10,6 +10,7 @@ from typing import TYPE_CHECKING, Any
from vibe.i18n import t as i18n_t
from core.backend_failure import emit_backend_failure
+from core.processing_indicator import STOPPED_REACTION_EMOJI
from core.reply_enhancer import strip_silent_blocks
if TYPE_CHECKING:
@@ -142,7 +143,16 @@ class CodexEventHandler:
return
self._clear_generated_image_snapshot(params)
self._agent._turn_registry.pop_turn(turn_id)
- await self._agent._remove_ack_reaction(tracked_request)
+ # A turn is interrupted for two very different reasons: the user
+ # stopped it, or a newer turn superseded it. Only the first is owed a
+ # ⏹️, and only the first claimer of the intent stamps it — this may
+ # be running concurrently with the ``turn/interrupt`` RPC that caused
+ # the completion.
+ stopped_by_user = self._agent.consume_user_stop_intent(turn_id)
+ await self._agent._remove_ack_reaction(
+ tracked_request,
+ terminal_emoji=STOPPED_REACTION_EMOJI if stopped_by_user else None,
+ )
# Turn ended without a result — release any web-Chat stream waiter
# (token-guarded, so a superseded turn won't close a newer stream).
self._release_stream_turn(tracked_request.context)
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 983440f63..c0691c400 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -20,6 +20,7 @@ import aiohttp
from core.avibe_cloud import avibe_cloud_url_available
from core.backend_failure import emit_backend_failure
from core.message_output import stop_output_for, terminal_output_for
+from core.processing_indicator import STOPPED_REACTION_EMOJI
from core.native_dispatch_phase import mark_backend_dispatch_attempted
from core.resource_governance import governor_from_controller
from core.runtime_activation import RuntimeActivationIdentity
@@ -533,6 +534,10 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
self._poll_loop = OpenCodePollLoop(self)
self._active_requests: Dict[str, asyncio.Task] = {}
+ # 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``.
+ self._user_stopped_sessions: set[str] = set()
self._session_last_activity: Dict[str, float] = {}
self._steering_states: Dict[str, _OpenCodeSteerState] = {}
self._restored_poll_servers: Dict[asyncio.Task, _SteeringAwareOpenCodeServer] = {}
@@ -1231,7 +1236,18 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
except asyncio.CancelledError:
logger.info(f"OpenCode request cancelled for {request.base_session_id}")
- await self._remove_ack_reaction(request)
+ # A /stop is silent by design, so the ⏹️ replacing the 👀 is the only
+ # thing that tells the user this turn ended on their command. Every
+ # other cancellation (shutdown, clear_sessions, supersede) leaves the
+ # plain removal, because none of those are the user's doing.
+ await self._remove_ack_reaction(
+ request,
+ terminal_emoji=(
+ STOPPED_REACTION_EMOJI
+ if request.base_session_id in self._user_stopped_sessions
+ else None
+ ),
+ )
if session_id:
self.sessions.remove_active_poll(session_id)
raise
@@ -1628,16 +1644,23 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
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 can trade it for
+ # the ⏹️ receipt. Without this it cannot tell a /stop from a shutdown.
+ self._user_stopped_sessions.add(request.base_session_id)
try:
- await self._abort_active_request(request.base_session_id, task, req_info)
- except Exception as e:
- logger.warning(f"Failed to abort OpenCode session: {e}")
+ try:
+ await self._abort_active_request(request.base_session_id, task, req_info)
+ except Exception as e:
+ logger.warning(f"Failed to abort OpenCode session: {e}")
- task.cancel()
- try:
- await task
- except asyncio.CancelledError:
- pass
+ task.cancel()
+ try:
+ await task
+ except asyncio.CancelledError:
+ pass
+ finally:
+ self._user_stopped_sessions.discard(request.base_session_id)
if opencode_session_id:
self.sessions.remove_active_poll(opencode_session_id)
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index 1e63bccde..7478f3d9d 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -603,6 +603,7 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
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()
transport = SimpleNamespace(is_alive=True, send_request=AsyncMock(side_effect=RuntimeError("boom")))
agent._transports = {"/tmp": transport}
agent._event_handler = SimpleNamespace(clear_pending=Mock(return_value=SimpleNamespace()))
@@ -616,12 +617,15 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
self.assertFalse(result)
agent._event_handler.clear_pending.assert_not_called()
agent._remove_ack_reaction.assert_not_awaited()
+ # Nothing was stopped, so no later ending may inherit a stopped receipt.
+ self.assertEqual(agent._user_stopped_turn_ids, set())
async def test_handle_stop_hides_turn_after_interrupt_succeeds(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()
events = []
diff --git a/tests/test_codex_event_handler.py b/tests/test_codex_event_handler.py
index 40a98e253..839798298 100644
--- a/tests/test_codex_event_handler.py
+++ b/tests/test_codex_event_handler.py
@@ -15,6 +15,7 @@ assert _SPEC is not None and _SPEC.loader is not None
_MODULE = importlib.util.module_from_spec(_SPEC)
_SPEC.loader.exec_module(_MODULE)
CodexEventHandler = _MODULE.CodexEventHandler
+STOPPED_REACTION_EMOJI = _MODULE.STOPPED_REACTION_EMOJI
class _TurnState:
@@ -94,6 +95,13 @@ class _StubAgent:
self.emit_result_message = AsyncMock()
self._remove_ack_reaction = AsyncMock()
self._maybe_backfill_session_title = Mock()
+ self._user_stopped_turn_ids: set[str] = set()
+
+ def consume_user_stop_intent(self, turn_id):
+ if turn_id not in self._user_stopped_turn_ids:
+ return False
+ self._user_stopped_turn_ids.discard(turn_id)
+ return True
def bind_agent_session_id(self, request, native_session_id):
payload = dict(request.context.platform_specific or {})
@@ -356,6 +364,30 @@ class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):
agent.emit_result_message.assert_not_awaited()
release_runtime_turn.assert_called_once_with(context)
+ # Superseded by a newer turn, not stopped by the user: no receipt.
+ agent._remove_ack_reaction.assert_awaited_once_with(request, terminal_emoji=None)
+
+ async def test_user_stopped_completion_stamps_the_receipt(self):
+ # The completion notification can beat handle_stop's own RPC back. When
+ # it does, it inherits the duty to trade the 👀 for a ⏹️ — otherwise the
+ # silent stop leaves the message showing nothing at all.
+ agent = _StubAgent()
+ agent.controller.agent_service = SimpleNamespace(release_runtime_turn=Mock())
+ handler = CodexEventHandler(agent)
+ context = SimpleNamespace(platform_specific={})
+ request = SimpleNamespace(base_session_id="session-1", context=context, started_at=0)
+ agent._turn_registry.register_turn("turn-1", request)
+ agent._user_stopped_turn_ids.add("turn-1")
+
+ await handler._on_turn_completed(
+ {"turn": {"id": "turn-1", "status": "interrupted"}}, request
+ )
+
+ agent._remove_ack_reaction.assert_awaited_once_with(
+ request, terminal_emoji=STOPPED_REACTION_EMOJI
+ )
+ # Consumed: handle_stop must not stamp a second one behind it.
+ self.assertEqual(agent._user_stopped_turn_ids, set())
async def test_auth_recovery_message_suppresses_plain_notify(self):
agent = _StubAgent()
diff --git a/tests/test_controller_im_ready.py b/tests/test_controller_im_ready.py
index 7b2e9d773..86544a4be 100644
--- a/tests/test_controller_im_ready.py
+++ b/tests/test_controller_im_ready.py
@@ -64,6 +64,9 @@ def test_transport_ready_restores_only_its_state() -> None:
start=Mock(),
)
controller.scheduled_task_service = SimpleNamespace(start=Mock(), notify_transport_ready=Mock())
+ controller.session_turns = SimpleNamespace(
+ notify_transport_ready=AsyncMock(return_value=0)
+ )
controller.watch_service = SimpleNamespace(start=Mock())
controller.runtime_command_watcher = SimpleNamespace(start=AsyncMock())
controller.runtime_work_supervisor = SimpleNamespace(notify=Mock())
@@ -74,6 +77,8 @@ def test_transport_ready_restores_only_its_state() -> None:
opencode_agent.restore_active_polls.assert_awaited_once_with({"discord", ""})
controller.scheduled_task_service.notify_transport_ready.assert_called_once_with("discord")
+ # Interruption reports held during recovery are owed to this transport.
+ controller.session_turns.notify_transport_ready.assert_awaited_once_with("discord")
controller.update_checker.notify_transport_ready.assert_called_once_with("discord")
controller.update_checker.check_and_send_post_update_notification.assert_awaited_once_with(
ready_platform="discord"
@@ -110,12 +115,16 @@ def test_transport_ready_registers_polls_before_owner_recovery() -> None:
controller.scheduled_task_service = SimpleNamespace(
notify_transport_ready=Mock()
)
+ controller.session_turns = SimpleNamespace(
+ notify_transport_ready=AsyncMock(return_value=0)
+ )
controller._delivery_recovery_complete = asyncio.Event()
ready = asyncio.create_task(controller._on_im_ready(platform="slack"))
await restore_entered.wait()
assert not ready.done()
+ controller.session_turns.notify_transport_ready.assert_not_awaited()
controller.scheduled_task_service.notify_transport_ready.assert_not_called()
controller.update_checker.notify_transport_ready.assert_not_called()
controller.update_checker.check_and_send_post_update_notification.assert_not_awaited()
@@ -126,6 +135,7 @@ def test_transport_ready_registers_polls_before_owner_recovery() -> None:
controller.scheduled_task_service.notify_transport_ready.assert_called_once_with(
"slack"
)
+ controller.session_turns.notify_transport_ready.assert_awaited_once_with("slack")
controller.update_checker.notify_transport_ready.assert_called_once_with("slack")
asyncio.run(exercise())
diff --git a/tests/test_opencode_stop_receipt.py b/tests/test_opencode_stop_receipt.py
new file mode 100644
index 000000000..0e549c8c4
--- /dev/null
+++ b/tests/test_opencode_stop_receipt.py
@@ -0,0 +1,119 @@
+"""OpenCode's /stop must leave a ⏹️ receipt like the other two backends.
+
+OpenCode has no interrupt RPC: a stop cancels the in-flight request task, and
+the cancellation lands inside the request coroutine, which is what owns the 👀.
+That coroutine cannot tell a user stop from a shutdown or a ``clear_sessions``
+sweep on its own, so ``handle_stop`` publishes the intent for the duration of
+the cancellation. Without it, an OpenCode stop clears the reaction and emits a
+silent result — a turn that ends with no trace at all.
+"""
+
+from __future__ import annotations
+
+import asyncio
+import inspect
+import sys
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
+
+from core.processing_indicator import STOPPED_REACTION_EMOJI
+from modules.agents.opencode.agent import OpenCodeAgent
+
+
+def _agent():
+ agent = object.__new__(OpenCodeAgent)
+ agent._active_requests = {}
+ agent._user_stopped_sessions = set()
+ agent._session_manager = SimpleNamespace(get_request_session=lambda _base: None)
+ agent._abort_active_request = AsyncMock()
+ agent.sessions = SimpleNamespace(remove_active_poll=Mock())
+ agent.controller = SimpleNamespace(emit_agent_message=AsyncMock())
+ return agent
+
+
+def _request(session_id="session-1"):
+ return SimpleNamespace(
+ base_session_id=session_id,
+ working_path="/tmp",
+ context=SimpleNamespace(platform_specific={}),
+ output=None,
+ )
+
+
+class OpenCodeStopIntentTests(unittest.IsolatedAsyncioTestCase):
+ async def test_cancelled_request_sees_the_user_stop_intent(self):
+ agent = _agent()
+ observed: list[bool] = []
+ entered = asyncio.Event()
+
+ async def in_flight():
+ try:
+ entered.set()
+ await asyncio.sleep(3600)
+ except asyncio.CancelledError:
+ # This is the branch that decides between a plain removal and
+ # the receipt; it must be able to see the intent from here.
+ observed.append("session-1" in agent._user_stopped_sessions)
+ raise
+
+ task = asyncio.create_task(in_flight())
+ agent._active_requests["session-1"] = task
+ await entered.wait()
+
+ result = await agent.handle_stop(_request())
+
+ self.assertTrue(result)
+ self.assertEqual(observed, [True])
+ # Cleared afterwards: a later shutdown of the same session is not a stop.
+ self.assertEqual(agent._user_stopped_sessions, set())
+
+ 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)
+
+ task = asyncio.create_task(in_flight())
+ agent._active_requests["session-1"] = task
+ await asyncio.sleep(0)
+
+ result = await agent.handle_stop(_request())
+
+ self.assertTrue(result)
+ self.assertEqual(agent._user_stopped_sessions, set())
+
+ async def test_stop_of_an_idle_session_publishes_no_intent(self):
+ agent = _agent()
+
+ result = await agent.handle_stop(_request())
+
+ self.assertFalse(result)
+ self.assertEqual(agent._user_stopped_sessions, set())
+
+
+class OpenCodeStopReceiptTests(unittest.TestCase):
+ """The intent is only useful if the cancellation branch actually spends it.
+
+ ``_process_message`` is a several-hundred-line coroutine whose cancellation
+ branch sits behind server startup, session creation and the poll loop, so
+ driving it here would mostly be a test of the stubs. Pin the coupling
+ instead: the branch must read the intent set and ask for the receipt.
+ """
+
+ def test_cancellation_branch_reads_the_intent(self):
+ source = inspect.getsource(OpenCodeAgent._process_message)
+ _, _, after = source.partition("except asyncio.CancelledError:")
+ branch = after.partition("raise")[0]
+
+ self.assertTrue(branch, "_process_message no longer handles cancellation")
+ self.assertIn("_user_stopped_sessions", branch)
+ self.assertIn("STOPPED_REACTION_EMOJI", branch)
+
+
+if __name__ == "__main__":
+ unittest.main()
diff --git a/tests/test_session_delivery_fsm.py b/tests/test_session_delivery_fsm.py
index d06ad633a..a641b1537 100644
--- a/tests/test_session_delivery_fsm.py
+++ b/tests/test_session_delivery_fsm.py
@@ -3191,6 +3191,9 @@ def _capture_lost_turn_report(manager: SessionTurnManager) -> tuple[list, list]:
async def _emit(_context, kind, text, **_kwargs):
emitted.append((kind, text))
+ # The dispatcher answers with the delivered message id; a falsy answer
+ # means the send failed, which the report path must not read as success.
+ return f"msg-{len(emitted)}"
async def _stamp(_context, message_id, emoji):
stamped.append((message_id, emoji))
@@ -3297,6 +3300,59 @@ def test_lost_im_turn_report_waits_for_its_transport(managers) -> None:
assert len(emitted) == 1
+def test_lost_im_turn_report_survives_a_failed_send(managers) -> None:
+ # "Transport ready" is the transport's claim, not a delivered message. The
+ # dispatcher swallows a send failure and answers None, and the turn is
+ # already terminal, so treating that as done would discard the only account
+ # of the interruption the user will ever get.
+ first, restarted, _engine, _engine_b, _starts = managers
+ context = _context()
+ admitted = asyncio.run(
+ first.deliver(
+ DeliveryRequest(
+ session_id="ses_fsm",
+ priority="p3",
+ content="im turn killed by restart",
+ native_message_id="m-origin",
+ ),
+ context=context,
+ )
+ )
+ turn_id = str(admitted.turn_id)
+ context.platform_specific["turn_token"] = turn_id
+ context.platform_specific["agent_runtime_turn_token"] = f"runtime-{turn_id}"
+ first._active_identity = lambda _backend, _session_id, logical_id: (
+ logical_id,
+ f"native-{logical_id}",
+ )
+ first.on_native_start(
+ context,
+ backend="codex",
+ runtime_key=f"runtime-key-{turn_id}",
+ runtime_turn_id=f"runtime-{turn_id}",
+ )
+ emitted, stamped = _capture_lost_turn_report(restarted)
+ restarted._active_identity = lambda *_args: None
+ delivers = False
+
+ async def _emit(_context, kind, text, **_kwargs):
+ emitted.append((kind, text))
+ return "msg-1" if delivers else None
+
+ restarted.controller.emit_agent_message = _emit
+
+ asyncio.run(restarted.recover_durable_delivery_state("ses_fsm", service_restart=True))
+
+ # It was attempted and it failed: no ⚠️ next to a notice nobody received.
+ assert [kind for kind, _text in emitted] == ["notify"]
+ assert stamped == []
+
+ delivers = True
+ assert asyncio.run(restarted.notify_transport_ready("avibe")) == 1
+ assert len(emitted) == 2
+ assert stamped == [("m-origin", INTERRUPTED_REACTION_EMOJI)]
+
+
def test_lost_turn_owning_a_run_leaves_the_notice_to_the_harness_lane(managers) -> None:
# A Harness turn already gets harness.run.interrupted.* stamped on its Run.
# Reporting again here would double-notify the same interruption.