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): release steering receipts acknowledged by one coalesced echo (#2347)

Call White898d050b1917
diff --git a/docs/plans/claude-result-provenance.md b/docs/plans/claude-result-provenance.md
index 694ef982a..dbf5e0746 100644
--- a/docs/plans/claude-result-provenance.md
+++ b/docs/plans/claude-result-provenance.md
@@ -139,9 +139,17 @@ facts 4 and 5 are why only the first frame counts. Turns started by a scheduled
wakeup were not measured; the rule assumes that, like notifications, they do not
replay a human-origin input.
-Open follow-ups outside this rule: under fact 5 the answered human request never
-receives a human Result, and under fact 6 exact-text native input receipts miss
-merged inputs. Both predate it and need their own decisions.
+Open follow-up outside this rule: under fact 5 the answered human request never
+receives a human Result. It predates the rule and needs its own decision.
+
+Fact 6 is resolved in the receipt owner (HFR-487). The merged replay is the
+queued inputs joined by newlines, so one echo consumes the matching contiguous
+FIFO run of receipts. Echoes with another explicit origin never consume receipts,
+even when their text matches. A human-origin or origin-less echo that matches no receipt is
+Avibe input in a shape the receipts do not model; it logs a warning and leaves
+the receipts pending. The stream exposes no sound boundary for which receipts
+such an echo covers, so a release heuristic would trade a loud wedge for silent
+early settlement.
## Validation
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 2d02d29f7..95ec28639 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -1530,29 +1530,70 @@ class ClaudeAgent(BaseAgent):
return "\n".join(texts)
return None
+ @staticmethod
+ def _echoed_receipt_run(
+ receipts: list[_ClaudeInputReceipt],
+ text: str,
+ ) -> tuple[int, int] | None:
+ """Return the earliest contiguous receipt run one native echo replays.
+
+ Claude dequeues every input queued behind a running response together
+ and replays them as one top-level user message joined by newlines.
+ """
+ for start in range(len(receipts)):
+ joined = receipts[start].text
+ end = start + 1
+ while True:
+ if joined == text:
+ return start, end
+ if end == len(receipts) or not text.startswith(f"{joined}\n"):
+ break
+ joined = f"{joined}\n{receipts[end].text}"
+ end += 1
+ return None
+
def _observe_native_user_input(
self,
composite_key: str,
message,
- ) -> _ClaudeInputReceipt | None:
+ ) -> list[_ClaudeInputReceipt]:
text = self._native_user_input_text(message)
if text is None:
- return None
+ return []
receipt_map = self._native_input_receipt_map()
receipts = receipt_map.get(composite_key) or []
- for index, receipt in enumerate(receipts):
- if receipt.text != text:
- continue
- receipts.pop(index)
- if not receipts:
- receipt_map.pop(composite_key, None)
+ if not receipts:
+ return []
+ origin = self._result_origin_kind(message)
+ if origin not in {None, "human"}:
+ # Injected turns (task notifications, peers, ...) are never Avibe
+ # input, even when their text happens to equal a receipt.
+ return []
+ run = self._echoed_receipt_run(receipts, text)
+ if run is None:
+ # A human or origin-less replay is Avibe input in a shape the receipts
+ # do not model. The stream gives no sound boundary for which receipts
+ # it covers, so they stay pending; make the drift loud instead of
+ # guessing.
+ logger.warning(
+ "Claude replayed input that matches no pending receipt for %s; "
+ "%d input receipt(s) remain pending",
+ composite_key,
+ len(receipts),
+ )
+ return []
+ start, end = run
+ consumed = receipts[start:end]
+ del receipts[start:end]
+ if not receipts:
+ receipt_map.pop(composite_key, None)
+ for receipt in consumed:
logger.debug(
"Observed Claude %s input receipt for %s",
receipt.kind,
composite_key,
)
- return receipt
- return None
+ return consumed
def _pending_steering_input_state(self, composite_key: str) -> str | None:
for receipt in self._native_input_receipt_map().get(composite_key) or []:
@@ -2125,11 +2166,11 @@ class ClaudeAgent(BaseAgent):
# started, so its owner is unproven.
turn_origin = self._result_origin_kind(message) or ""
async with self._steering_lock(composite_key):
- receipt = self._observe_native_user_input(
+ receipts = self._observe_native_user_input(
composite_key,
message,
)
- if receipt is not None and receipt.kind == "steer":
+ if any(receipt.kind == "steer" for receipt in receipts):
await self._retire_primary_phase_on_steer_receipt(
context,
composite_key,
diff --git a/tests/scenarios/harness_failure_recovery/catalog.yaml b/tests/scenarios/harness_failure_recovery/catalog.yaml
index 0cb96fd01..85e04843e 100644
--- a/tests/scenarios/harness_failure_recovery/catalog.yaml
+++ b/tests/scenarios/harness_failure_recovery/catalog.yaml
@@ -3879,9 +3879,9 @@ scenarios:
backend: claude
# A transport write only queues input, while Claude may merge several inputs
# into one response. Avibe enables the CLI's replay-user-messages protocol so
- # each consumed input produces a native top-level UserMessage echo in FIFO
- # order. A Result before the echo stays nonterminal; a Result after every echo
- # can settle the shared Turn.
+ # consumed input produces a native top-level UserMessage echo in FIFO order;
+ # inputs dequeued together share one echo (HFR-487). A Result before the echo
+ # stays nonterminal; a Result after every echo can settle the shared Turn.
test: tests/test_claude_agent_sessions.py::test_user_echo_allows_one_result_to_own_primary_and_steer
- id: HFR-436
name: Watch waiter health is independent from downstream event processing
@@ -4399,6 +4399,17 @@ scenarios:
test: tests/test_background_command_caller_context.py::test_hfr_486_watch_child_vault_callback_uses_only_current_binding
# Real argv/shell children with clean/contaminated parents, bound/unbound
# targets, isolated Vault expiry, retargeting, and remote snapshot transport.
+ - id: HFR-487
+ name: one coalesced Claude input echo acknowledges every queued steer
+ status: covered
+ kind: recovery
+ layer: contract
+ backend: claude
+ # Claude dequeues every input queued behind a running response together and
+ # replays them as one newline-joined UserMessage. That echo acknowledges the
+ # whole FIFO run. Injected turns such as task notifications never consume
+ # receipts, even when their text matches; an unmatched human echo is logged.
+ test: tests/test_claude_agent_sessions.py::test_coalesced_echo_acknowledges_its_whole_queued_run
- id: HFR-488
name: an injected Claude turn's reply is never replayed as the next turn's narration
status: covered
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index aba01f4f9..c6588fe36 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -1,4 +1,5 @@
import asyncio
+import logging
import sys
import unittest
from datetime import datetime, timezone
@@ -1608,6 +1609,113 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
self.assertNotIn(composite_key, agent._pending_requests)
self.assertNotIn(composite_key, agent._native_input_receipts)
+ async def test_coalesced_echo_acknowledges_its_whole_queued_run(self):
+ """HFR-487: one native echo may acknowledge every queued input."""
+
+ agent_logger = logging.getLogger("modules.agents.claude_agent")
+ queued = ["first steer", "second steer"]
+ # (name, echo, origin, receipts still pending once the echo is observed)
+ cases = (
+ # Claude dequeues inputs queued behind a response together and
+ # replays them as one newline-joined user message.
+ ("coalesced", "first steer\nsecond steer", None, []),
+ # Avibe input in a shape the receipts do not model: nothing is
+ # guessed, and the drift is logged.
+ ("unrecognized human", "first steer, rewritten", {"kind": "human"}, queued),
+ ("unrecognized origin-less", "first steer, rewritten", None, queued),
+ # Same text as the queued run, but an injected turn is not Avibe input.
+ ("injected notification", "first steer\nsecond steer", {"kind": "task-notification"}, queued),
+ )
+ for name, echo, origin, still_pending in cases:
+ settles = not still_pending
+ observed_pending = []
+ with self.subTest(name):
+ controller = _StubController()
+ controller._get_session_key = lambda _context: "session-1"
+ controller.emit_agent_message = AsyncMock()
+ controller.session_handler.mark_session_idle = lambda _key: None
+ controller.session_handler.handle_session_error = AsyncMock()
+ agent = ClaudeAgent(controller)
+ agent.emit_result_message = AsyncMock()
+ agent._get_formatter = lambda _context: SimpleNamespace(
+ format_assistant_message=lambda parts: "\n\n".join(parts),
+ )
+ composite_key = "session-coalesced-steer:/tmp/work"
+ context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform_specific={"turn_token": "T1"},
+ )
+ pending_request = SimpleNamespace(
+ context=context,
+ started_at=None,
+ ack_reaction_message_id=None,
+ ack_reaction_emoji=None,
+ )
+ agent._pending_requests[composite_key] = [pending_request]
+ for text in ("first steer", "second steer"):
+ receipt = agent._register_native_input(
+ composite_key,
+ text,
+ kind="steer",
+ )
+ receipt.state = "accepted"
+ agent._advance_steering_generation(composite_key)
+
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ yield type(
+ "ResultMessage",
+ (),
+ {
+ "subtype": "success",
+ "result": "primary result",
+ "duration_ms": 1,
+ },
+ )()
+ yield UserMessage(echo, origin=origin)
+ observed_pending.append(
+ [r.text for r in agent._native_input_receipts.get(composite_key, [])]
+ )
+ yield type(
+ "ResultMessage",
+ (),
+ {
+ "subtype": "success",
+ "result": "steered result",
+ "duration_ms": 2,
+ },
+ )()
+
+ return _iterate()
+
+ with self.assertLogs("modules.agents.claude_agent", "WARNING") as logs:
+ await agent._receive_messages(
+ _Client(),
+ "session-coalesced-steer",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+ agent_logger.warning("receiver finished")
+ drifted = any("matches no pending receipt" in line for line in logs.output)
+ self.assertEqual(drifted, name.startswith("unrecognized"))
+
+ self.assertEqual(observed_pending, [still_pending])
+ if settles:
+ agent.emit_result_message.assert_awaited_once_with(
+ context,
+ "steered result",
+ subtype="success",
+ duration_ms=2,
+ parse_mode="markdown",
+ request=pending_request,
+ )
+ self.assertNotIn(composite_key, agent._native_input_receipts)
+ else:
+ # Unacknowledged input keeps the Turn open.
+ agent.emit_result_message.assert_not_awaited()
async def test_narration_keeps_claude_markdown_as_written(self):
"""Narration reaches every surface as the Markdown Claude wrote, like the Result."""