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(claude): end agent-initiated turn when its detached reply is delivered (#2224)

Call White589f87d23b50
diff --git a/docs/plans/claude-result-provenance.md b/docs/plans/claude-result-provenance.md
index ed05f5782..2331ed2c6 100644
--- a/docs/plans/claude-result-provenance.md
+++ b/docs/plans/claude-result-provenance.md
@@ -250,3 +250,36 @@ Web/IM end-to-end tests. The ledger remains process-local; restart coverage
concerns the existing durable Activity receipt store, not a new unsolicited
output outbox. Fresh automatic exact-head review and CI remain required after
the single push; local tests do not establish acceptance.
+
+## Agent-initiated Turn settlement on retirement (2026-09-27)
+
+A task-notification Result is detached output, so its delivery never completes
+a Turn. When that output belonged to a synthetic agent-initiated owner, the
+retirement in transition 9 released only the runtime gate. The agent-initiated
+Turn's waiter was never signalled. The Session therefore stayed in flight
+("delivering"), Stop waited for a terminal that could not arrive, and later
+human input queued behind the Turn indefinitely.
+
+- Retiring a synthetic owner is that owner's terminal boundary. It ends the
+ agent-initiated Turn through the canonical empty terminal result
+ (`completes_turn=True`, `completes_run=False`) before the gate is released,
+ matching the forced-cancel settle path. The Run, if any, stays with the
+ detached output that already settled it. The output record is already gone,
+ so nothing retries this settle: if it fails or is cancelled, the Turn waiter
+ is still released (cancellation then propagates), so the Session cannot wedge.
+ That fallback first latches an error outcome through the same
+ `on_terminal_result` chokepoint. Otherwise a failed error settle would
+ terminalize the Turn as completed.
+- The settle carries the outcome frozen on the record when it is classified.
+ That outcome uses `_terminal_backend_failure`, the predicate that already
+ selects detached result text. A Result that fails only through `is_error`,
+ `error`, `errors`, `api_error_status`, or a `failed` subtype therefore ends
+ its Turn as failed, not completed.
+- The settle awaits delivery while the owner is already retired but the gate
+ is still held. Output reaching the receiver in that window belongs to the
+ next Turn. It waits for the settlement, then opens that Turn normally.
+ Classifying the output against the held gate would instead make it a
+ detached record that is delivered outside any Turn.
+- A silent-only detached reply settles its Activity claim without creating a
+ Message. A missing receipt for such a reply is success, not a delivery
+ failure, so it no longer retries forever ahead of every later record.
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index bccaedb8d..27e5720bc 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -22,6 +22,7 @@ from core.native_dispatch_phase import mark_backend_dispatch_attempted, mark_pre
from core.processing_indicator import STOPPED_REACTION_EMOJI
from core.reply_enhancer import strip_silent_blocks
from core.resource_governance import pids_failure_labels
+from core.run_settlement import SETTLED_BY_TURN_ONLY_RESULT
from core.runtime_activation import RuntimeActivationIdentity, RuntimeActivationRegistry
from core.runtime_work import RuntimeWorkLane
from core.services.agent_steering import (
@@ -88,6 +89,7 @@ class _ClaudeOutputRecoveryRecord:
request: AgentRequest | None = None
context: MessageContext | None = None
subtype: str = "success"
+ is_error: bool = False
duration_ms: int = 0
delivering: bool = False
provenance: str | None = None
@@ -162,6 +164,7 @@ class ClaudeAgent(BaseAgent):
self._detached_foreground_tool_use_ids: dict[str, set[str]] = {}
self._detached_foreground_task_ids: dict[str, set[str]] = {}
self._synthetic_pending_owners: dict[str, AgentRequest] = {}
+ self._synthetic_owner_settlements: dict[str, asyncio.Event] = {}
self._provenance_recovery_evidence: dict[str, dict[str, object]] = {}
# Question handler for AskUserQuestion support (disabled)
@@ -317,6 +320,10 @@ class ClaudeAgent(BaseAgent):
record.context = self._snapshot_output_context(context)
record.provenance = self._result_origin_kind(message)
record.subtype = str(getattr(message, "subtype", "success") or "")
+ record.is_error = (
+ self._terminal_backend_failure(message, getattr(message, "result", None))
+ is not None
+ )
record.duration_ms = getattr(message, "duration_ms", 0)
if record.output is None:
record.output = self._unsolicited_message_output(message, phase_id=record.phase_id)
@@ -3747,14 +3754,21 @@ class ClaudeAgent(BaseAgent):
return []
return list(getattr(request, "output_activities", None) or [])
- def _retire_synthetic_pending_owner(
+ async def _retire_synthetic_pending_owner(
self,
composite_key: str,
context: MessageContext,
*,
owner: AgentRequest | None,
+ is_error: bool = False,
) -> bool:
- """Release this output's captured owner, never the current runtime owner."""
+ """Release this output's captured owner, never the current runtime owner.
+
+ Detached output never completes a Turn, so retirement is the synthetic
+ owner's terminal boundary: it ends the agent-initiated Turn through the
+ canonical silent result before the gate opens for the next Turn. The
+ Run, if any, stays with the detached output that already settled it.
+ """
synthetic = owner
if (
@@ -3779,9 +3793,44 @@ class ClaudeAgent(BaseAgent):
self._pop_pending_request(composite_key)
self._clear_request_activities(synthetic)
self._mark_session_idle_if_no_pending_requests(composite_key)
- self._release_service_runtime_turn(
- getattr(synthetic, "context", None) or context
- )
+ owner_context = getattr(synthetic, "context", None) or context
+ # Output arriving while this Turn settles belongs to the next Turn. The
+ # receiver waits here rather than classifying it against a gate that
+ # this settling Turn still holds.
+ settled = asyncio.Event()
+ self._synthetic_owner_settlements[composite_key] = settled
+ try:
+ await self.controller.emit_agent_message(
+ owner_context,
+ "result",
+ "",
+ is_error=is_error,
+ output=MessageOutput(completes_turn=True, completes_run=False),
+ )
+ except BaseException as exc:
+ # No backend result will ever arrive for this Turn again and its
+ # record is already gone, so a failed or cancelled settle must still
+ # latch its outcome and release its waiter rather than wedge the
+ # Session.
+ if isinstance(exc, Exception):
+ logger.warning(
+ "Agent-initiated turn settle failed for %s", composite_key, exc_info=True,
+ )
+ latch = getattr(
+ getattr(self.controller, "session_turns", None), "on_terminal_result", None,
+ )
+ if is_error and callable(latch):
+ latch(owner_context, is_error=True, settled_by=SETTLED_BY_TURN_ONLY_RESULT)
+ mark = getattr(self.controller, "mark_turn_complete", None)
+ if callable(mark):
+ mark(owner_context, settled_by=SETTLED_BY_TURN_ONLY_RESULT)
+ if not isinstance(exc, Exception):
+ raise
+ finally:
+ self._release_service_runtime_turn(owner_context)
+ if self._synthetic_owner_settlements.get(composite_key) is settled:
+ self._synthetic_owner_settlements.pop(composite_key, None)
+ settled.set()
return True
def _has_synthetic_delivery_pending(self, composite_key: str) -> bool:
@@ -5225,7 +5274,9 @@ class ClaudeAgent(BaseAgent):
subtype=record.subtype, duration_ms=record.duration_ms,
parse_mode="markdown", output=record.output,
)
- if message_id is None:
+ # A silent-only reply settles without a Message, so it has no
+ # receipt; retrying it would block every later record.
+ if message_id is None and strip_silent_blocks(record.text).strip():
raise ActivityOutputDeliveryError(
"Claude detached output was not accepted", delivered=False,
)
@@ -5255,7 +5306,12 @@ class ClaudeAgent(BaseAgent):
finally:
record.delivering = False
self._remove_output_record(record)
- self._retire_synthetic_pending_owner(composite_key, context, owner=record.request)
+ await self._retire_synthetic_pending_owner(
+ composite_key,
+ context,
+ owner=record.request,
+ is_error=record.is_error,
+ )
self._mark_session_idle_if_runtime_free(composite_key)
self._signal_activity_output_settled(composite_key)
# Another Result can append a record while this batch is in flight.
@@ -5602,6 +5658,9 @@ class ClaudeAgent(BaseAgent):
agent-initiated Turn and synthesize a pending ``AgentRequest`` so the
existing result path retains its normal lifecycle behavior.
"""
+ settling = self._synthetic_owner_settlements.get(composite_key)
+ if settling is not None:
+ await settling.wait()
registry = self._activity_registry()
pending = self._pending_requests.get(composite_key) or []
defer_activity_claim = message_type == "result" and (
diff --git a/modules/agents/service.py b/modules/agents/service.py
index 46a45ce06..ad4f8c14c 100644
--- a/modules/agents/service.py
+++ b/modules/agents/service.py
@@ -964,7 +964,7 @@ class AgentService:
try:
register(context)
except Exception:
- logger.debug("register_agent_initiated_turn failed", exc_info=True)
+ logger.warning("register_agent_initiated_turn failed", exc_info=True)
self._record_runtime_turn_start(
gate,
runtime_key=runtime_key,
diff --git a/tests/test_claude_agent_initiated_turn.py b/tests/test_claude_agent_initiated_turn.py
index ed642afcc..677e8cca4 100644
--- a/tests/test_claude_agent_initiated_turn.py
+++ b/tests/test_claude_agent_initiated_turn.py
@@ -21,7 +21,7 @@ import asyncio
import sys
import unittest
from pathlib import Path
-from types import SimpleNamespace
+from types import MethodType, SimpleNamespace
from unittest.mock import ANY, AsyncMock, Mock, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
@@ -32,12 +32,16 @@ from modules.claude_sdk_compat import (
TextBlock,
ToolUseBlock,
)
+from core.controller import Controller
+from core.message_context import resolve_turn_sink_key
from core.message_output import MessageOutput, terminal_output_for
from core.message_dispatcher import (
ActivityOutputDeliveryError,
ConsolidatedMessageDispatcher,
)
from core.session_activities import SessionActivityRegistry, TERMINAL_SNAPSHOT_PHASE
+from core.run_settlement import SETTLED_BY_TURN_ONLY_RESULT
+from core.session_turns import SessionTurnManager
from core.runtime_activation import RuntimeActivationRegistry
from modules.im import MessageContext
@@ -870,10 +874,123 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
)
self.assertFalse(agent.emit_result_message.await_count)
- agent._retire_synthetic_pending_owner(composite_key, context, owner=synthetic)
+ await agent._retire_synthetic_pending_owner(composite_key, context, owner=synthetic)
self.assertFalse(agent._has_pending_requests(composite_key))
self.assertFalse(service._get_turn_gate(composite_key).lock.locked())
+ async def test_interrupted_synthetic_turn_settle_still_releases_its_waiter(self):
+ # Retirement runs after the output record is gone, so nothing retries an
+ # interrupted settle; the waiter must be released on failure and on
+ # cancellation alike, cancellation must still propagate, and an error
+ # outcome must still reach the Turn instead of settling as completed.
+ for error, propagates, is_error in (
+ (RuntimeError("dispatcher unavailable"), False, False),
+ (asyncio.CancelledError(), True, False),
+ (RuntimeError("settings unavailable"), False, True),
+ ):
+ with self.subTest(error=type(error).__name__, is_error=is_error):
+ agent, service = _build_agent()
+ composite_key = "session-synthetic-settle-interrupted:/tmp/work"
+ context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform="avibe",
+ platform_specific={
+ "agent_runtime_turn_key": composite_key,
+ "agent_session_id": "sess-synthetic-settle-interrupted",
+ },
+ )
+ await agent._maybe_begin_agent_initiated_turn(
+ context,
+ composite_key,
+ "sess-synthetic-settle-interrupted",
+ "/tmp/work",
+ "session-key",
+ message_type="assistant",
+ )
+ synthetic = agent._synthetic_pending_owners[composite_key]
+ settled: list[str] = []
+ latched: list[tuple[bool, str]] = []
+ agent.controller.emit_agent_message = AsyncMock(side_effect=error)
+ agent.controller.mark_turn_complete = (
+ lambda _ctx, *, settled_by: settled.append(settled_by)
+ )
+ agent.controller.session_turns.on_terminal_result = (
+ lambda _ctx, *, is_error, settled_by: latched.append((is_error, settled_by))
+ )
+
+ if propagates:
+ with self.assertRaises(type(error)):
+ await agent._retire_synthetic_pending_owner(
+ composite_key, context, owner=synthetic, is_error=is_error,
+ )
+ else:
+ self.assertTrue(
+ await agent._retire_synthetic_pending_owner(
+ composite_key, context, owner=synthetic, is_error=is_error,
+ )
+ )
+
+ self.assertEqual(settled, [SETTLED_BY_TURN_ONLY_RESULT])
+ if is_error:
+ self.assertEqual(latched, [(True, SETTLED_BY_TURN_ONLY_RESULT)])
+ self.assertFalse(agent._has_pending_requests(composite_key))
+ self.assertFalse(service.runtime_turn_active(composite_key))
+
+ async def test_output_during_synthetic_turn_settle_opens_the_next_turn(self):
+ # The settling Turn still holds the gate. Output classified against it
+ # would be a detached record that the release then delivers outside any
+ # Turn, concurrently with whatever Turn is admitted next.
+ agent, service = _build_agent()
+ composite_key = "session-synthetic-settle-window:/tmp/work"
+ context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform="avibe",
+ platform_specific={
+ "agent_runtime_turn_key": composite_key,
+ "agent_session_id": "sess-synthetic-settle-window",
+ },
+ )
+ begin_args = (
+ context,
+ composite_key,
+ "sess-synthetic-settle-window",
+ "/tmp/work",
+ "session-key",
+ )
+ await agent._maybe_begin_agent_initiated_turn(*begin_args, message_type="assistant")
+ settling_owner = agent._synthetic_pending_owners[composite_key]
+ settle_entered = asyncio.Event()
+ finish_settle = asyncio.Event()
+
+ async def slow_settle(*_args, **_kwargs):
+ settle_entered.set()
+ await finish_settle.wait()
+
+ agent.controller.emit_agent_message = AsyncMock(side_effect=slow_settle)
+ retirement = asyncio.create_task(
+ agent._retire_synthetic_pending_owner(
+ composite_key, context, owner=settling_owner,
+ )
+ )
+ await asyncio.wait_for(settle_entered.wait(), timeout=1)
+ next_output = asyncio.create_task(
+ agent._maybe_begin_agent_initiated_turn(*begin_args, message_type="assistant")
+ )
+ for _ in range(5):
+ await asyncio.sleep(0)
+ self.assertFalse(next_output.done())
+
+ finish_settle.set()
+ self.assertTrue(await asyncio.wait_for(retirement, timeout=1))
+ self.assertIsNone(await asyncio.wait_for(next_output, timeout=1))
+
+ next_owner = agent._synthetic_pending_owners[composite_key]
+ self.assertIsNot(next_owner, settling_owner)
+ self.assertEqual(agent._output_records_for_runtime(composite_key), [])
+ self.assertTrue(service.runtime_turn_active(composite_key))
+
async def test_synthetic_owner_transfers_claimed_activity_batch_to_detached_result(self):
agent, service = _build_agent()
composite_key = "session-synthetic-claimed-batch:/tmp/work"
@@ -1857,6 +1974,114 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
release_receiver.set()
await asyncio.wait_for(receiver, timeout=1)
+ async def test_delivered_detached_reply_ends_its_agent_initiated_turn(self):
+ # A task-notification reply is detached output, so it cannot complete the
+ # synthetic agent-initiated Turn itself. Unless retiring its owner ends
+ # that Turn, the Session stays "delivering" and never admits the next one.
+ # The Turn ends with the reply's own outcome, including a failure the
+ # Result reports only through its structured error flag.
+ for reply, result_is_error, expected_sent, expected_status in (
+ (
+ "Background verification finished",
+ False,
+ ["Background verification finished"],
+ "idle",
+ ),
+ ("<silent>nothing new</silent>", False, [], "idle"),
+ (
+ "Background verification crashed",
+ True,
+ ["Background verification crashed"],
+ "failed",
+ ),
+ ):
+ with self.subTest(reply=reply):
+ agent, service = _build_agent()
+ client = _ActivityDeliveryClient()
+ _install_activity_dispatcher(agent, client)
+ controller = agent.controller
+ controller.message_dispatcher = ConsolidatedMessageDispatcher(controller)
+ controller.emit_agent_message = MethodType(Controller.emit_agent_message, controller)
+ controller.mark_turn_complete = MethodType(Controller.mark_turn_complete, controller)
+ controller.get_turn_sink = MethodType(Controller.get_turn_sink, controller)
+ controller._session_id_from_context = lambda ctx: (
+ (ctx.platform_specific or {}).get("agent_session_id")
+ )
+ statuses: list[str] = []
+ controller.set_agent_status = lambda _session_id, status: statuses.append(status)
+ manager = SessionTurnManager(controller=controller)
+ manager.flush_queue = AsyncMock(return_value=False)
+ controller.session_turns = manager
+ composite_key = "session-detached-turn-end:/tmp/work"
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="avibe",
+ platform_specific={
+ "agent_runtime_turn_key": composite_key,
+ "agent_session_id": "sess-detached-turn-end",
+ },
+ )
+ release_receiver = asyncio.Event()
+
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ assistant = AssistantMessage()
+ assistant.content = [TextBlock(text=reply)]
+ yield assistant
+ detached_result = ResultMessage()
+ detached_result.result = reply
+ detached_result.is_error = result_is_error
+ detached_result.origin = {"kind": "task-notification"}
+ yield detached_result
+ await release_receiver.wait()
+
+ return _iterate()
+
+ events: list[tuple[str, str]] = []
+ with (
+ patch(
+ "core.inbox_events.bus.publish",
+ side_effect=lambda topic, payload: events.append(
+ (topic, (payload or {}).get("session_id"))
+ ),
+ ),
+ patch(
+ "core.message_dispatcher.persist_agent_message",
+ return_value={"id": "message-row"},
+ ),
+ patch("core.message_dispatcher.agent_message_exists", return_value=False),
+ ):
+ receiver = asyncio.create_task(
+ agent._receive_messages(
+ _Client(),
+ "sess-detached-turn-end",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+ )
+ await asyncio.wait_for(
+ _wait_until(lambda: ("turn.end", "sess-detached-turn-end") in events),
+ timeout=1,
+ )
+
+ self.assertFalse(receiver.done())
+ self.assertIn(("turn.start", "sess-detached-turn-end"), events)
+ self.assertNotIn("sess-detached-turn-end", manager.in_flight)
+ self.assertEqual(client.sent, expected_sent)
+ self.assertEqual(statuses[-1:], [expected_status])
+ self.assertIsNone(
+ manager.get_turn_sink(resolve_turn_sink_key(controller, context))
+ )
+ self.assertEqual(agent._output_records_for_runtime(composite_key), [])
+ self.assertFalse(agent._has_pending_requests(composite_key))
+ self.assertFalse(service.runtime_turn_active(composite_key))
+
+ release_receiver.set()
+ await asyncio.wait_for(receiver, timeout=1)
+
async def test_detached_activity_retry_keeps_terminal_text_and_owner_while_stream_is_open(
self,
):
diff --git a/tests/test_claude_output_recovery_ledger.py b/tests/test_claude_output_recovery_ledger.py
index bcb0a3f1f..3d766cb63 100644
--- a/tests/test_claude_output_recovery_ledger.py
+++ b/tests/test_claude_output_recovery_ledger.py
@@ -419,8 +419,12 @@ async def test_unowned_terminal_text_survives_claim_failure(
payloads = []
async def accepted(ctx, kind, text, **kwargs):
- payloads.append((text, kwargs["output"]))
output = kwargs["output"]
+ if output.completes_turn and not output.detached:
+ # The retired synthetic owner's Turn settle carries no Message.
+ service.release_runtime_turn(ctx)
+ return None
+ payloads.append((text, output))
assert registry.settle_completed_output_batch(output, accepted_message_exists=True)
if output.completes_turn:
service.release_runtime_turn(ctx)