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(agents): deliver agent-initiated turn output (background-task / ScheduleWakeup) (#687)
Call White9774d24bd18b
diff --git a/docs/plans/agent-initiated-turn-outbox.md b/docs/plans/agent-initiated-turn-outbox.mdnew file mode 100644index 000000000..4e9760ac2--- /dev/null+++ b/docs/plans/agent-initiated-turn-outbox.md@@ -0,0 +1,212 @@+# Agent-initiated turn Outbox capture++## Background++When the Claude Code backend finishes a **background task** (`run_in_background:+true`) or fires a **ScheduleWakeup**, the harness re-invokes the agent loop+**inside the same SDK process**. That produces a fresh assistant/result stream+on Avibe's long-lived `ClaudeAgent._receive_messages` receiver — but Avibe never+sent a query, so it never opened a runtime turn for it.++### Symptom (verified)++A background task completes, the agent writes a user-facing reply, and the user+never receives it. The reply is not persisted to `messages`, not delivered to+IM, not pushed — it exists only in the Claude Code transcript.++Runtime evidence (session `ses6efm3vrtnw`, `~/.avibe/logs/vibe_remote.log`):++```+2026-06-28 02:49:41 - Dropping stale assistant emit for superseded runtime turn in avibe::ses6efm3vrtnw+2026-06-28 02:49:41 - Dropping stale toolcall emit for superseded runtime turn in avibe::ses6efm3vrtnw+2026-06-28 02:50:09 - Dropping stale result emit for superseded runtime turn in avibe::ses6efm3vrtnw+```++The reply WAS produced and DID reach `emit_agent_message`; the outbound+active-turn guard dropped every emit of the turn.++## Root cause++Two outbound chokepoint guards in `core/message_dispatcher.py`+(`emit_agent_message`) drop any emit whose context fails+`_is_current_runtime_turn` →+`AgentService.emit_matches_runtime_turn(context)`:++* result guard (`canonical_type == "result"`)+* assistant/tool/log guard++`emit_matches_runtime_turn` returns `True` only when+`gate.token == context[agent_runtime_turn_token]`. For an agent-initiated turn:++* the previous turn's terminal result already **released** the gate+ (`gate.token == ""`), and+* the receiver's reused context still carries the **previous** turn's token,+* `_pending_requests` is empty, so no fresh token is adopted.++`"" != "<old token>"` → guard fails → output dropped, with no persist, deliver,+stream, or notify. This is precisely the "agent acts on a non-user trigger"+Outbox gap the product vision calls out (Inbox → Processing → Outbox; user+messages are one signal, not the only trigger).++Scope note: this is the receiver-alive case (idle timeout is 600s; the verified+repro completed in ~1.5 min). A background task that runs **longer** than the+idle timeout is a separate, larger problem (the session is evicted and the SDK+client/process torn down before the reply is produced) and is out of scope here.++## Solution++Make an agent-initiated turn a **first-class turn** so its output rides the same+INBOUND (session → running) and OUTBOUND (terminal result → idle + persist ++deliver + notify + gate release) chokepoints as a user turn.++* `AgentService.begin_agent_initiated_turn(agent_name, context, runtime_key)`+ (shared, reusable by any backend): if the runtime gate is **free**, acquire it+ (acquiring a free `asyncio.Lock` never yields → the `locked()`-check + acquire+ is atomic on the loop, so a concurrent user turn can't slip in), mint a fresh+ token, stamp it onto the context, and mark the session running. Returns the+ token, or `None` when a real turn already owns the gate (let it own the+ output).+* `ClaudeAgent._receive_messages`: when an assistant/result message arrives with+ **no pending request**, call a helper that opens an agent-initiated turn and+ synthesizes a pending `AgentRequest`. From there the existing handlers+ (token adoption, FIFO pop on result, EOF/error/cancel settle) treat it exactly+ like a normal turn — the terminal result releases the gate via the dispatcher's+ result `finally`.++No change to the guards themselves: stale stragglers from stopped/superseded+turns (a DIFFERENT non-empty gate token, or a held gate) are still dropped.++## Interaction with idle Claude eviction (and how long a session can wait)++`SessionHandler.evict_idle_sessions` reclaims a Claude SDK client (cancels its+receiver + disconnects/reaps the ~220MB subprocess) once a session is idle past+`claude.idle_timeout_seconds` (default **600s / 10 min**; swept every ~100s). A+session flagged `active` is exempt from this plain idle eviction — only the+stuck-active backstop (`max(idle_timeout * multiplier, floor)`, ~30 min) can+reclaim an active one.++Two interactions, both handled:++1. **The silent wait before the reply (a CEILING, not a conflict).** After the+ turn that started the background task goes idle, the session sits idle with+ `last_activity` frozen at that turn's last streamed message. If the background+ task reports back within ~`idle_timeout` (default 10 min) the receiver is+ still alive and the agent-initiated turn opens normally. If it stays silent+ longer, the idle sweep evicts the session first — the receiver is gone, so the+ eventual reply has nowhere to land (this is "Case B": the reply, and likely+ the task itself as a child of the reaped process, is lost). This bound is+ fundamental: Avibe cannot keep a Claude subprocess alive indefinitely on the+ chance a maybe-never task will report back, and it has no signal that a+ background task is pending inside the SDK process. **Answer to "how long can+ it wait": ~`claude.idle_timeout_seconds` (default 600s) from the prior turn's+ last activity.** Raising the wait = raise that config (at the cost of more+ lingering subprocesses); a smarter pending-work-aware extension would need an+ upstream SDK signal and is a separate follow-up.++2. **Mid-turn eviction parity (closed by this change).** `begin_agent_initiated_turn`+ marks the workbench dot running but does NOT add the session to+ `active_sessions`; a user turn does (in `handle_message`). Left as-is, an+ in-flight agent-initiated turn would be protected only by per-message activity+ touches and could be reclaimed mid-turn if it went quiet > idle_timeout (e.g.+ it started its own long background work), whereas a user turn survives to the+ ~30-min backstop. Fix: the Claude detection marks the session active on open+ (mirroring `handle_message`); the existing terminal-result / EOF / error /+ cancel paths already mark it idle, so it stays balanced and the stuck-active+ backstop still reclaims a wedged turn. This also routes a force-eviction+ through `force_cleanup_stuck_active_session` (settles dot + releases gate)+ rather than a bare `cleanup_session`. No gate/active-flag/dot leak in the+ open-vs-evict race.++Known minor edge (not fixed here): the shared receiver CancelledError path+releases the gate + marks the session idle but does not settle the workbench+`agent_status` dot. So if a plain `cleanup_session` cancels an agent-initiated+turn before its terminal result (i.e. `/clear` or an auth/config refresh fires+in the sub-second window after the dot goes `running`), the dot can stay green+until the next turn settles it (or `reset_stale` on restart). This is+pre-existing behavior of the cancel path for any in-flight turn, narrow, and+self-healing; the idle-eviction trigger specifically is already covered because+marking the turn active routes eviction through `force_cleanup_stuck_active_session`,+which emits a terminal result. Settling the dot in the shared cancel path is a+separate, broader change (it also affects normal turns) left as a follow-up.++## Evidence layers++* unit — `AgentService.begin_agent_initiated_turn` opens on a free gate / no-ops+ on a held gate; `emit_matches_runtime_turn` passes after open.+* receiver integration — `tests/test_claude_agent_initiated_turn.py`: drive+ `_receive_messages` with unsolicited assistant+result, assert a turn is opened,+ the result is NOT dropped (guard passes), and the gate is released.+* residual manual — local Incus regression: start a background bash task in an+ agent session, let it finish, confirm the completion reply reaches the channel.++## Todo++- [x] Root-cause + evidence+- [x] `begin_agent_initiated_turn` in `modules/agents/service.py`+- [x] detection + synthetic request in `modules/agents/claude_agent.py`+- [x] idle-eviction parity: mark session active on open+- [x] regression test+- [x] ruff + focused pytest++## Review fixes (PR #687)++- **Codex P1 — suppressed synthetic result leak.** A malformed-tool-use synthetic+ API error pops the turn's real pending request and arms+ `_suppressed_synthetic_results` for the PAIRED `ResultMessage`, which the result+ branch skips (`continue`) with no terminal emit. That paired result reached the+ new detection hook with an empty FIFO + free gate, so it opened an+ agent-initiated turn that was then skipped — leaking the gate / pending request+ / active flag until EOF and blocking the next user message. This hit **normal+ user turns** too (any turn ending in a malformed tool call), not just+ agent-initiated ones. Fix: `_maybe_begin_agent_initiated_turn` returns early+ when `composite_key in _suppressed_synthetic_results` (the set is cleared by+ `_consume_suppressed_synthetic_result` / cleanup, so real later turns still+ open). Regression test:+ `test_suppressed_synthetic_result_does_not_open_a_turn`.+- **Codex P1 — receiver deadlock on queued gate waiters.** `asyncio.Lock` can be+ momentarily unlocked while it still has queued waiters (a user turn that blocked+ on the gate while the previous turn held it). `locked()` is False in that window,+ so `await gate.lock.acquire()` would SUSPEND the long-lived Claude receiver+ behind the queued user turn — and the receiver is the only reader of that turn's+ terminal result (which releases the gate), so the session deadlocks. Fix:+ `begin_agent_initiated_turn` is now strictly non-blocking — it bails unless the+ gate is free AND has no live waiters (`_lock_has_live_waiters`), so the+ `acquire()` completes synchronously. Regression test:+ `test_does_not_block_when_a_user_turn_is_queued_on_the_gate`.+- **Codex P2 — Stop control for agent-initiated turns (DEFERRED, follow-up).**+ `begin_agent_initiated_turn` writes session status `running` but does not add a+ `Turn` to `SessionTurnManager.in_flight` or publish `turn.start`, so the+ Workbench cancel endpoint returns `not_in_flight` — a long-running+ agent-initiated turn shows running but has no working Stop button. Deferred:+ doing it right is real FSM work (a `Turn` needs a cancelable task; `in_flight`+ must be popped on every agent-initiated terminal/EOF/error/cancel path;+ `turn.start`/`turn.end` published; reset-stale interaction) — a medium change+ with its own review/test surface, not a bugfix-PR add-on. Agent-initiated turns+ are typically short (report a result and end) and still settle themselves on+ their terminal result, so the gap is narrow. Tracked as a follow-up issue.+- **Codex P2 — unsolicited output lost when a user turn is contended (DEFERRED,+ follow-up).** The P1 fix makes the open strictly non-blocking, so when a user+ turn holds/has-just-acquired the gate but hasn't appended its pending request+ yet, an agent-initiated reply buffered behind the previous turn is dropped by+ the outbound guard (it can't open its own turn without risking the deadlock).+ This is an inherent tradeoff of the gate-based, deadlock-safe approach: the PR+ is still a strict improvement (was 100% loss for agent-initiated output → now+ loss only in this contended window), and the loss is now logged instead of+ silent. Fully preserving the reply across a concurrent user turn needs a+ non-gated persist fallback or an output re-queue — part of making+ agent-initiated turns first-class FSM citizens. Tracked with the Stop-control+ follow-up.++## Backend parity (Codex / OpenCode)++The bug needs two co-conditions: (1) the backend re-invokes its own agent loop+while Avibe thinks the session is idle, and (2) a long-lived Avibe-side listener+receives that output. Only Claude has both today (background tasks ++ScheduleWakeup are Claude Code harness features; SDK streaming receiver is+long-lived). Codex has a persistent reader but no self-invocation (every turn is+an Avibe `sendUserTurn`). OpenCode's poll loop is turn-scoped (stops after the+turn) and also has no self-invocation. So neither needs alignment now;+`begin_agent_initiated_turn` is backend-agnostic and ready if either gains a+self-invocation source. NB: Avibe's own `vibe task` / `vibe watch` are NOT+affected on any backend — they dispatch through `handle_message`, which opens+the gate.diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex 29f93aff1..95af2bd23 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -559,6 +559,22 @@ class ClaudeAgent(BaseAgent):message_type = self._detect_message_type(message)formatter = self._get_formatter(context)+ # Unsolicited backend output (a background-task completion or+ # a ScheduleWakeup re-invoked the agent inside this SDK+ # process) reaches this long-lived receiver with no Avibe turn+ # open. Open an agent-initiated turn so the reply is persisted+ # + delivered + notified instead of dropped by the outbound+ # active-turn guard. Content messages only — system/user+ # frames never carry a user-facing reply.+ if message_type in ("assistant", "result"):+ await self._maybe_begin_agent_initiated_turn(+ context,+ composite_key,+ base_session_id,+ working_path,+ session_key,+ )+if message_type == "assistant":toolcalls = []text_parts = []@@ -1069,6 +1085,96 @@ class ClaudeAgent(BaseAgent):def _has_pending_requests(self, composite_key: str) -> bool:return bool(self._pending_requests.get(composite_key))+ async def _maybe_begin_agent_initiated_turn(+ self,+ context: MessageContext,+ composite_key: str,+ base_session_id: str,+ working_path: str,+ session_key: str,+ ) -> None:+ """Open a turn for UNSOLICITED backend output (no Avibe query behind it).++ Claude Code re-invokes the agent loop inside this same SDK process when a+ background task completes or a ScheduleWakeup fires, streaming a fresh+ assistant/result run onto this long-lived receiver. The previous turn's+ terminal result already released the runtime gate and this receiver's+ reused context still carries that turn's (now stale) token, so the+ outbound active-turn guard would drop the whole reply — it would never be+ persisted, delivered, or pushed.++ When output arrives with NO pending request, open an agent-initiated turn+ and synthesize a pending ``AgentRequest`` for it. The existing+ assistant/result handlers then treat it exactly like a normal turn (token+ adoption keeps the gate token live across the assistant→result sequence,+ the result pops the synthetic request and the dispatcher's result+ ``finally`` releases the gate, and an EOF/error/cancel settles it through+ the same paths). No-op when a turn is already in flight for this session+ (a real user turn, or an agent-initiated turn already opened for an+ earlier message of this same run).+ """+ if self._has_pending_requests(composite_key):+ return+ # A malformed-tool-use synthetic API error pops the turn's real pending+ # request and arms ``_suppressed_synthetic_results`` for the PAIRED+ # ResultMessage, which the result branch then skips (``continue``) with NO+ # terminal emit. That paired result reaches this hook with an empty FIFO ++ # free gate, so opening an agent-initiated turn for it would leak the gate /+ # pending request / active flag until EOF — and the NEXT user message for+ # this Claude session would block behind the leaked gate (Codex P1). Skip+ # while a suppressed synthetic result is pending; the set is cleared by+ # ``_consume_suppressed_synthetic_result`` / cleanup, so real later turns+ # open normally.+ if composite_key in self._suppressed_synthetic_results:+ return+ service = getattr(self.controller, "agent_service", None)+ begin = getattr(service, "begin_agent_initiated_turn", None)+ if not callable(begin):+ return+ payload = getattr(context, "platform_specific", None) or {}+ runtime_key = str(payload.get(AGENT_RUNTIME_TURN_KEY) or "").strip() or composite_key+ token = await begin(self.name, context, runtime_key)+ if not token:+ # The gate is CONTENDED — a user turn holds it, or one is queued on it+ # and we must not block the receiver behind that waiter (deadlock; see+ # begin_agent_initiated_turn). If a turn actually holds the gate the+ # output rides that turn's machinery; in the narrow free-but-queued+ # window the outbound guard drops it. Log so that (rare, sub-tick) loss+ # is visible instead of silent — full preservation across a queued user+ # turn is a tracked follow-up.+ logger.info(+ "Agent-initiated output for %s not opened: runtime gate contended "+ "(a user turn holds or is queued on it)",+ composite_key,+ )+ return+ # Mark the session ACTIVE so this in-flight agent-initiated turn gets the+ # SAME idle-eviction exemption a user turn gets in ``handle_message``.+ # Without it the turn is protected only by per-message activity touches and+ # could be reclaimed mid-turn if it goes quiet past the idle timeout (e.g.+ # it kicks off its own long background work). The terminal result / EOF /+ # error / cancel paths all mark the session idle again, so this stays+ # balanced; the stuck-active backstop still reclaims a wedged turn. (The+ # SILENT wait BEFORE this first output is still bounded by the idle timeout+ # — once the session is evicted the receiver is gone and no agent-initiated+ # turn can open. See docs/plans/agent-initiated-turn-outbox.md.)+ mark_active = getattr(self.session_handler, "mark_session_active", None)+ if callable(mark_active):+ mark_active(composite_key)+ request = AgentRequest(+ context=context,+ message="",+ working_path=working_path,+ base_session_id=base_session_id,+ composite_session_id=composite_key,+ session_key=session_key,+ )+ self._pending_requests.setdefault(composite_key, []).append(request)+ logger.info(+ "Opened agent-initiated turn for session %s (unsolicited backend output)",+ composite_key,+ )+def _mark_session_idle_if_no_pending_requests(self, composite_key: str) -> bool:if self._has_pending_requests(composite_key):return Falsediff --git a/modules/agents/service.py b/modules/agents/service.pyindex d7d6753d9..e8d9d576b 100644--- a/modules/agents/service.py+++ b/modules/agents/service.py@@ -253,6 +253,85 @@ class AgentService:gate = self._turn_gates.get(runtime_key)return bool(gate is not None and gate.token == runtime_token and gate.runtime_started)+ @staticmethod+ def _lock_has_live_waiters(lock: asyncio.Lock) -> bool:+ """True when ``lock`` has at least one not-yet-cancelled queued waiter.++ ``asyncio.Lock.locked()`` reports only whether the lock is HELD, not whether+ coroutines are queued waiting for it — but acquiring a lock that is free yet+ has waiters still suspends. ``begin_agent_initiated_turn`` needs this signal+ to stay strictly non-blocking. ``_waiters`` is a CPython asyncio internal (a+ deque or ``None``); guarded with ``getattr`` so a future runtime that drops+ it degrades to "no waiters" instead of raising.+ """+ waiters = getattr(lock, "_waiters", None)+ if not waiters:+ return False+ return any(not w.cancelled() for w in waiters)++ async def begin_agent_initiated_turn(+ self, agent_name: str, context: Any, runtime_key: str+ ) -> Optional[str]:+ """Open a runtime-gate turn for backend output Avibe did NOT initiate.++ Claude Code (and any future backend that re-invokes its agent loop inside+ a persistent process) can start a fresh turn when a background task+ finishes or a ScheduleWakeup fires — WITHOUT Avibe sending a query. That+ output reaches the long-lived receiver with no turn open, so the outbound+ active-turn guard (``emit_matches_runtime_turn``) would drop every+ assistant/tool/result emit as a stale straggler. Open a turn here so the+ reply rides the same INBOUND chokepoint (session → ``running``) and+ OUTBOUND chokepoint (terminal result → idle/failed + persist + deliver ++ notify + gate release) as a user turn.++ Returns the fresh turn token when the gate was free and a turn was opened,+ else ``None`` when the gate is contended (a user turn holds OR is queued on+ it) — let that turn own the output; the agent-initiated emit then adopts its+ token instead.++ STRICTLY NON-BLOCKING: this runs ON the long-lived Claude receiver, which is+ the only reader of the SDK stream. An ``asyncio.Lock`` can be momentarily+ unlocked while it still has QUEUED WAITERS (a user turn that blocked on this+ gate while the previous turn held it, between that turn's release and the+ waiter resuming). In that window ``locked()`` is False, yet+ ``await acquire()`` would SUSPEND the receiver behind the queued user turn —+ and the receiver is what reads that turn's terminal result to release the+ gate, so the session would deadlock. So bail unless the gate is free AND has+ no live waiters; the ``acquire()`` below then completes synchronously+ without yielding, so no concurrent turn can slip in (Codex P1).+ """+ runtime_key = str(runtime_key or "").strip()+ if not runtime_key:+ return None+ gate = self._get_turn_gate(runtime_key)+ if gate.lock.locked() or self._lock_has_live_waiters(gate.lock):+ return None+ await gate.lock.acquire()+ gate.token = uuid.uuid4().hex+ gate.backend = agent_name+ # The backend already produced output, so the turn is unambiguously+ # running — there is no queued-startup window to distinguish (unlike a+ # user turn waiting on the gate), so mark it started immediately.+ gate.runtime_started = True+ if context.platform_specific is None:+ context.platform_specific = {}+ context.platform_specific[AGENT_RUNTIME_TURN_KEY] = runtime_key+ context.platform_specific[AGENT_RUNTIME_TURN_TOKEN] = gate.token+ # Fresh streaming token too: the previous turn's SSE sink is already gone,+ # and a leftover ``turn_token`` would only confuse ``mark_turn_complete``+ # (which no-ops anyway with no live sink for this session).+ context.platform_specific[AGENT_TURN_TOKEN] = gate.token+ # INBOUND status chokepoint (mirrors ``handle_message``): mark the avibe+ # session ``running`` so the sidebar dot reflects the agent-initiated work.+ # Non-avibe contexts resolve to no session id and are skipped.+ manager = getattr(self.controller, "session_turns", None)+ if manager is not None:+ try:+ manager.on_running(context)+ except Exception:+ logger.debug("on_running failed for agent-initiated turn", exc_info=True)+ return gate.token+def release_runtime_turn(self, context: Any) -> None:payload = getattr(context, "platform_specific", None) or {}runtime_key = str(payload.get(AGENT_RUNTIME_TURN_KEY) or "").strip()diff --git a/tests/test_claude_agent_initiated_turn.py b/tests/test_claude_agent_initiated_turn.pynew file mode 100644index 000000000..0ff9264be--- /dev/null+++ b/tests/test_claude_agent_initiated_turn.py@@ -0,0 +1,308 @@+"""Regression: backend output produced WITHOUT an Avibe-initiated turn (a Claude+Code background-task completion or ScheduleWakeup re-invoking the agent loop+inside the same SDK process) must still be delivered to the user.++Before the fix, that output streamed onto ``ClaudeAgent._receive_messages`` after+the previous turn had already released the runtime gate, so the receiver's reused+context carried a stale runtime-turn token and ``_pending_requests`` was empty.+The outbound active-turn guard (``AgentService.emit_matches_runtime_turn``) then+dropped every assistant/tool/result emit as a superseded straggler — the reply+was never persisted, delivered, or pushed (verified in production logs for+session ``ses6efm3vrtnw``).++The fix opens an *agent-initiated* turn when content arrives with no pending+request, so the reply rides the same persist + deliver + notify chokepoints as a+user turn.+"""++from __future__ import annotations++import asyncio+import sys+import unittest+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import AsyncMock++sys.path.insert(0, str(Path(__file__).resolve().parents[1]))++from modules.agents.claude_agent import ClaudeAgent+from modules.agents.service import AgentService+++# Class names mirror the Claude SDK frames so ``_detect_message_type`` (which maps+# on ``__class__.__name__``) classifies them as assistant / result.+class AssistantMessage:+ """Minimal assistant frame (no text/toolcalls) — just enough to be detected+ as the FIRST content message of an agent-initiated run."""++ error = ""+ content: list = []+ usage = None+++class ResultMessage:+ subtype = "success"+ result = "✅ master 回归环境已就绪"+ duration_ms = 1+++def _assistant_then_result_client():+ class _Client:+ def receive_messages(self):+ async def _iterate():+ yield AssistantMessage()+ yield ResultMessage()++ return _iterate()++ return _Client()+++def _one_result_client():+ class _Client:+ def receive_messages(self):+ async def _iterate():+ yield ResultMessage()++ return _iterate()++ return _Client()+++def _build_agent(*, running_calls=None, mark_idle_calls=None, active_calls=None):+ mark_idle_calls = mark_idle_calls if mark_idle_calls is not None else []+ controller = SimpleNamespace(+ config=SimpleNamespace(platform="slack"),+ im_client=SimpleNamespace(formatter=None),+ settings_manager=SimpleNamespace(sessions=None),+ session_manager=SimpleNamespace(+ get_or_create_session=AsyncMock(return_value=SimpleNamespace(session_active={})),+ ),+ receiver_tasks={},+ claude_sessions={},+ claude_client=SimpleNamespace(_is_skip_message=lambda message: False),+ session_handler=SimpleNamespace(+ mark_session_idle=lambda key: mark_idle_calls.append(key),+ mark_session_active=lambda key: (active_calls.append(key) if active_calls is not None else None),+ touch_session_activity=lambda key: None,+ ),+ note_session_tokens=lambda *a, **k: None,+ emit_agent_message=AsyncMock(return_value=None),+ )+ # INBOUND chokepoint recorder for the agent-initiated turn open.+ controller.session_turns = SimpleNamespace(+ on_running=lambda ctx: (running_calls.append(ctx) if running_calls is not None else None)+ )+ controller._get_session_key = lambda context: "session-key"++ service = AgentService(controller)+ agent = ClaudeAgent(controller)+ service.register(agent)+ controller.agent_service = service++ # Stub the external bits the assistant/result branches touch so the test+ # isolates the agent-initiated-turn contract (mirrors the result-settle test).+ agent._maybe_capture_session_id = lambda *a, **k: None+ agent._consume_suppressed_synthetic_result = lambda *a, **k: False+ agent._handle_auth_failure_result = AsyncMock(return_value=False)+ agent._handle_synthetic_api_error_message = AsyncMock(return_value=False)+ agent._reserved_native_session_id = lambda *a, **k: None+ agent._adopt_pending_turn_token = lambda *a, **k: None+ agent._get_formatter = lambda context: None+ agent._handle_receiver_eof = AsyncMock()+ return agent, service+++class BeginAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):+ async def test_opens_turn_on_free_gate_so_guard_passes(self):+ running_calls: list = []+ agent, service = _build_agent(running_calls=running_calls)+ context = SimpleNamespace(+ platform_specific={+ "agent_runtime_turn_key": "S:/w",+ "agent_runtime_turn_token": "OLD",+ "agent_session_id": "sess-1",+ }+ )+ # Precondition: the prior turn released the gate, so the stale token on the+ # context fails the guard — exactly the state that dropped the reply.+ self.assertFalse(service.emit_matches_runtime_turn(context))++ token = await service.begin_agent_initiated_turn("claude", context, "S:/w")++ self.assertTrue(token)+ self.assertNotEqual(token, "OLD")+ gate = service._get_turn_gate("S:/w")+ self.assertTrue(gate.lock.locked())+ self.assertEqual(gate.token, token)+ self.assertTrue(gate.runtime_started)+ self.assertEqual(context.platform_specific["agent_runtime_turn_token"], token)+ # The guard now passes — the reply will NOT be dropped.+ self.assertTrue(service.emit_matches_runtime_turn(context))+ # INBOUND chokepoint fired (session → running).+ self.assertEqual(running_calls, [context])++ async def test_noop_when_a_real_turn_holds_the_gate(self):+ agent, service = _build_agent()+ gate = service._get_turn_gate("S:/w")+ await gate.lock.acquire()+ gate.token = "R1"+ gate.backend = "claude"+ context = SimpleNamespace(platform_specific={"agent_session_id": "sess-1"})++ token = await service.begin_agent_initiated_turn("claude", context, "S:/w")++ self.assertIsNone(token)+ # Untouched: the real turn still owns the gate.+ self.assertEqual(gate.token, "R1")++ async def test_does_not_block_when_a_user_turn_is_queued_on_the_gate(self):+ # Regression (Codex P1): an asyncio.Lock can be momentarily unlocked while+ # it still has QUEUED WAITERS (a user turn that blocked on the gate while+ # the previous turn held it). locked() is False then, but awaiting acquire()+ # would suspend the long-lived receiver behind the queued user turn —+ # deadlocking the session (the receiver is what reads that turn's result to+ # release the gate). begin must be strictly non-blocking when a waiter exists.+ agent, service = _build_agent()+ runtime_key = "S:/w"+ gate = service._get_turn_gate(runtime_key)+ await gate.lock.acquire() # "turn A" holds the gate+ waiter = asyncio.ensure_future(gate.lock.acquire()) # "turn B" queues+ await asyncio.sleep(0) # let B register as a waiter+ try:+ # The deadlock window: A releases → lock unlocked but B still queued.+ gate.lock.release()+ context = SimpleNamespace(platform_specific={"agent_session_id": "s"})+ token = await asyncio.wait_for(+ service.begin_agent_initiated_turn("claude", context, runtime_key),+ timeout=1.0, # wait_for proves it returned without suspending behind B+ )+ self.assertIsNone(token)+ finally:+ await waiter # B acquires+ gate.lock.release()++ async def test_suppressed_synthetic_result_does_not_open_a_turn(self):+ # Regression (Codex P1): a malformed-tool-use synthetic error pops the+ # real pending request and arms _suppressed_synthetic_results for the+ # PAIRED ResultMessage, which is skipped with no terminal emit. Opening an+ # agent-initiated turn for it would leak the gate/pending/active flag and+ # block the next user message. The detection must skip while suppression+ # is pending.+ active_calls: list[str] = []+ agent, service = _build_agent(active_calls=active_calls)+ composite_key = "session-3:/tmp/work"+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform="avibe",+ platform_specific={+ "agent_runtime_turn_key": composite_key,+ "agent_runtime_turn_token": "OLD",+ "agent_session_id": "sess-3",+ },+ )+ agent._suppressed_synthetic_results.add(composite_key)++ await agent._maybe_begin_agent_initiated_turn(+ context, composite_key, "session-3", "/tmp/work", "session-key"+ )++ gate = service._get_turn_gate(composite_key)+ self.assertFalse(gate.lock.locked()) # no turn opened+ self.assertEqual(gate.token, "") # no token minted+ self.assertEqual(active_calls, []) # session not marked active+ self.assertFalse(agent._has_pending_requests(composite_key)) # no synthetic request+++class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):+ async def test_unsolicited_reply_is_delivered_not_dropped(self):+ running_calls: list = []+ mark_idle_calls: list[str] = []+ active_calls: list[str] = []+ agent, service = _build_agent(+ running_calls=running_calls, mark_idle_calls=mark_idle_calls, active_calls=active_calls+ )+ composite_key = "session-1:/tmp/work"+ # Receiver context as it looks AFTER the previous turn completed: a stale+ # runtime-turn token, no pending request, and the gate already released.+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform="avibe",+ platform_specific={+ "agent_runtime_turn_key": composite_key,+ "agent_runtime_turn_token": "OLD",+ "agent_session_id": "sess-1",+ },+ )+ self.assertFalse(service.emit_matches_runtime_turn(context))++ # Capture whether the guard would pass at the moment the result is emitted.+ guard_at_emit: list[bool] = []++ async def _capture_result(ctx, *a, **k):+ guard_at_emit.append(service.emit_matches_runtime_turn(ctx))++ agent.emit_result_message = AsyncMock(side_effect=_capture_result)++ await agent._receive_messages(+ _assistant_then_result_client(),+ "session-1",+ "/tmp/work",+ context,+ composite_key=composite_key,+ )++ # The reply reached emit (was NOT dropped), and the guard passed.+ agent.emit_result_message.assert_awaited_once()+ self.assertEqual(guard_at_emit, [True])+ # A real agent-initiated turn was opened (fresh token, not the stale one).+ gate = service._get_turn_gate(composite_key)+ self.assertNotEqual(gate.token, "OLD")+ self.assertTrue(gate.token)+ # INBOUND chokepoint fired once and the turn settled (synthetic request popped).+ self.assertEqual(len(running_calls), 1)+ # Marked active on open (eviction parity with a user turn) then idle on settle.+ self.assertEqual(active_calls, [composite_key])+ self.assertEqual(mark_idle_calls, [composite_key])+ self.assertFalse(agent._has_pending_requests(composite_key))++ async def test_normal_turn_with_pending_request_does_not_reopen(self):+ agent, service = _build_agent()+ composite_key = "session-2:/tmp/work"+ gate = service._get_turn_gate(composite_key)+ await gate.lock.acquire()+ gate.token = "R1"+ gate.backend = "claude"+ context = SimpleNamespace(+ user_id="U1",+ channel_id="C1",+ platform="avibe",+ platform_specific={+ "agent_runtime_turn_key": composite_key,+ "agent_runtime_turn_token": "R1",+ "agent_session_id": "sess-2",+ },+ )+ # A real turn is in flight: one pending request already enqueued.+ agent._pending_requests[composite_key] = [SimpleNamespace(context=context)]+ agent.emit_result_message = AsyncMock(return_value=None)++ await agent._receive_messages(+ _one_result_client(),+ "session-2",+ "/tmp/work",+ context,+ composite_key=composite_key,+ )++ agent.emit_result_message.assert_awaited_once()+ # The gate token was NOT replaced by a fresh agent-initiated token: the+ # detection correctly no-ops when a real turn already owns the session.+ self.assertEqual(gate.token, "R1")+++if __name__ == "__main__": # pragma: no cover+ unittest.main()