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(claude): stream a replay-proven human turn past lingering Activities (#2248)
Call White7dd8956ab9be
diff --git a/docs/plans/claude-result-provenance.md b/docs/plans/claude-result-provenance.mdindex 866b500a1..694ef982a 100644--- a/docs/plans/claude-result-provenance.md+++ b/docs/plans/claude-result-provenance.md@@ -4,8 +4,9 @@Claude Code keeps one streaming SDK connection per runtime. A detached backgroundActivity can produce Assistant and Result frames while a newer Avibe human Turn is-waiting to write. The SDK's terminal `ResultMessage.origin` is the only reliable+waiting to write. The SDK's terminal `ResultMessage.origin` is the reliableowner signal in this interleaved stream; Assistant frames do not carry that field.+The only earlier signal is the replayed input that starts a human turn.## Contract@@ -19,6 +20,20 @@ owner signal in this interleaved stream; Assistant frames do not carry that fielreplay them only after the terminal Result identifies the phase. Grace-periodActivity flushes defer while that phase is buffered, and replay failures do notprevent terminal settlement.+- Stream a turn whose first content frame is a replayed human input+ (`UserMessage.origin.kind == "human"`) without waiting for its Result, even+ while an Activity competes. Such a turn ends with a human Result (see Measured+ turn shape), so its frames take the human replay path early: they attach to+ the pending human request and never claim Activity output. Any other first+ frame, a human input drained into a running turn, held frames, and detached+ or claimed Activity output that is not yet delivered keep the Result-owned+ path; a later frame never overtakes earlier held output. A generic receiver+ error keeps the client, so the receiver that the next input starts may join a+ running turn whose start it never sees; that receiver streams early only from+ the turn after its first Result. Completed Activity output that is still+ queued follows the human Result on both paths, because the Activity flush+ defers while a human request is pending; streaming earlier does not change+ that order.- Treat a missing or unknown origin as foreground only when no competing Activityevidence exists; otherwise preserve it as detached output and leave the pendinghuman request untouched.@@ -98,6 +113,36 @@ for metadata eligibility, Turn constraints, retries, and persisted local-onlyoutput batches. A metadata predicate can select a candidate, but it cannotcreate a second batching path or absorb a previously bound receipt.+## Measured turn shape (Claude CLI 2.1.280, 2026-09-28)++A hermetic probe (Claude Agent SDK 0.2.158 and its bundled CLI, with+`--replay-user-messages`, against a scripted local Messages mock) established:++1. Turns are serialized. Each turn is `system init`, an optional replayed input,+ its frames, and one Result; turns never interleave.+2. A human turn's first content frame is its replayed input (`isReplay`,+ `origin: human`), always before any Assistant frame. A task-notification turn+ has no replay: it starts with Assistant output, and its Result carries+ `origin: task-notification`.+3. A human input sent while a notification turn runs without a tool becomes its+ own human turn after that Result. A notification and a human input both+ queued behind a turn run as separate FIFO turns.+4. A notification drained into a running human turn appears mid-turn as a+ replayed input with `origin: task-notification`; the Result stays human.+5. A human input sent while a notification turn runs a tool is drained into that+ turn: its replay appears mid-turn, the model answers it inside the+ notification turn, and no human Result follows.+6. Human inputs queued before a turn starts are merged into one replayed input.++Facts 1 and 2 make a turn's first content frame the earliest proof of its owner;+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.+## ValidationConsumer tests cover both terminal result orders, notification-before-human-result,@@ -105,9 +150,13 @@ multiple Activity completion aggregation, Assistant buffering, flush-vs-Resultraces, retained Activity text during a long-lived receiver retry, receivererror recovery ownership, failed/stopped/killed/completed provisional terminallineage, buffered replay failure, unknown origin, client replacement and Stop-races, exactly-once output, and durable unsent-input recovery. A hermetic Claude-Agent SDK 0.2.158 plus bundled CLI probe verifies the outgoing origin shape and-real Result provenance against the local mock upstream.+races, exactly-once output, durable unsent-input recovery, and a replay-proven+human turn streaming past a lingering Activity, including one that finishes+mid-turn, without claiming its output, while notification-started turns, human+inputs drained after Assistant output, and turns the receiver joined after their+start, including a replacement receiver that first sees a task event, stay held.+A hermetic Claude Agent SDK 0.2.158 plus bundled CLI probe verifies the outgoing+origin shape and real Result provenance against the local mock upstream.The current implementation scope is the Claude receiver and existing Activity,dispatcher, receipt, steering, and generation owners only. It does not add adiff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.pyindex ed6e5bfbf..3b143dd8f 100644--- a/modules/agents/claude_agent.py+++ b/modules/agents/claude_agent.py@@ -1989,6 +1989,17 @@ class ClaudeAgent(BaseAgent):)message_stream = client.receive_messages().__aiter__()+ # Claude runs one turn at a time and replays the input that starts+ # a human turn before any Assistant frame of it. The first content+ # frame after a Result therefore names what started the turn: an+ # input origin kind, or "" when anything else comes first, such as+ # Assistant output from a task notification. ``None`` means unseen.+ # A client's first receiver starts before its first turn. A later+ # receiver may start inside a turn it cannot see the start of, so+ # no frame before its first Result proves an owner.+ joined_running_client = getattr(client, "_vibe_receiver_attached", False)+ setattr(client, "_vibe_receiver_attached", True)+ turn_origin: str | None = "" if joined_running_client else Nonewhile True:settling_ambiguous_primary = Falsesettling_ambiguous_assistant_text = None@@ -2089,7 +2100,16 @@ class ClaudeAgent(BaseAgent):message_type = self._detect_message_type(message)if message_type not in {"assistant", "result", "system"}:terminal_steering_generation = None+ if message_type == "result":+ turn_origin = None+ elif message_type == "assistant" and turn_origin is None:+ turn_origin = ""if message_type == "user":+ if turn_origin is None:+ # A frame without origin, such as a tool result,+ # means this receiver joined the turn after it+ # 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(composite_key,@@ -2146,10 +2166,18 @@ class ClaudeAgent(BaseAgent):owner=result_owner,terminal_message=message,)- if (+ buffer_assistant = (message_type == "assistant"and self._should_buffer_assistant_message(composite_key)- ):+ )+ # A proven human turn takes the path its human Result would+ # replay it on, only earlier: attributed to the pending+ # request and never claiming Activity output.+ proven_human_frame = (+ buffer_assistant+ and self._turn_answers_pending_human(composite_key, turn_origin)+ )+ if buffer_assistant and not proven_human_frame:# TaskStarted can legally arrive before the terminal# Result. Record foreground tool ownership now, while# the visible assistant/toolcall output remains buffered@@ -2172,7 +2200,10 @@ class ClaudeAgent(BaseAgent):composite_key,)continue- if message_type in ("assistant", "result") or model_refusal_fallback_notice is not None:+ if (+ message_type in ("assistant", "result")+ or model_refusal_fallback_notice is not None+ ) and not proven_human_frame:output_mode = await self._maybe_begin_agent_initiated_turn(context,composite_key,@@ -4447,6 +4478,32 @@ class ClaudeAgent(BaseAgent):or self._has_competing_activity(composite_key))+ def _turn_answers_pending_human(+ self,+ composite_key: str,+ turn_origin: str | None,+ ) -> bool:+ """Whether Claude's replay proved this turn answers the pending human.++ A turn that starts with a replayed human input ends with a human+ Result, so its frames need not wait for that Result. Held frames and+ detached or claimed Activity output that is not yet delivered are+ earlier, so they are never overtaken. Queued completed Activity output+ follows the human Result either way: the Activity flush defers while a+ human request is pending.+ """++ if turn_origin != "human":+ return False+ if self._buffered_assistant_messages.get(composite_key):+ return False+ if self._output_records_for_runtime(composite_key):+ return False+ pending = self._pending_requests.get(composite_key) or []+ return bool(+ pending and not getattr(pending[0], "_claude_synthetic_owner", False)+ )+def _result_owner(self, composite_key: str, message) -> str:"""Classify a terminal frame before it can claim shared state."""diff --git a/tests/test_claude_result_provenance.py b/tests/test_claude_result_provenance.pyindex b1ad03b96..86f29f762 100644--- a/tests/test_claude_result_provenance.py+++ b/tests/test_claude_result_provenance.py@@ -16,7 +16,7 @@ from core.native_dispatch_phase import (prewrite_failure_evidence,set_dispatch_phase,)-from modules.claude_sdk_compat import TextBlock, ToolUseBlock, UserMessage+from modules.claude_sdk_compat import TextBlock, ToolResultBlock, ToolUseBlock, UserMessagefrom modules.agents.claude_agent import ClaudeAgentfrom tests.test_claude_agent_initiated_turn import _build_agent, _dispatcher_owned_emit@@ -349,6 +349,177 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):self.assertIs(agent.emit_result_message.await_args.kwargs["request"], request)self.assertFalse(service.activities.has_completed_output("claude", key))+ async def test_replayed_human_input_proves_turn_owner_before_result(self):+ # A task an earlier Turn started (a dev server) keeps running, so it+ # competes with every later human Turn. Claude runs one turn at a time+ # and replays the input that starts a human turn before any Assistant+ # frame of it; only that first frame proves who the turn answers.+ human = {"kind": "human"}+ notification = {"kind": "task-notification"}+ progress = [("assistant", "progress"), ("toolcall", "Bash(pwd)")]+ cases = [+ (+ "human replay starts the turn",+ [UserMessage(content="check the build", origin=human)],+ progress,+ False,+ ),+ (+ "lingering task finishes inside the human turn",+ [+ UserMessage(content="check the build", origin=human),+ TaskNotificationMessage("dev-server", "dev server exited"),+ UserMessage(content="<task-notification>", origin=notification),+ ],+ progress,+ False,+ ),+ (+ "injected input starts the turn",+ [UserMessage(content="<task-notification>", origin=notification)],+ [],+ False,+ ),+ (+ "human input drained after Assistant output",+ [+ AssistantMessage(_block(TextBlock, text="notification reply")),+ UserMessage(content="check the build", origin=human),+ ],+ [],+ False,+ ),+ (+ "receiver joins a turn after it started",+ [+ UserMessage(+ content=[+ _block(+ ToolResultBlock,+ tool_use_id="tool-earlier",+ content="ok",+ is_error=False,+ )+ ]+ ),+ UserMessage(content="check the build", origin=human),+ ],+ [],+ False,+ ),+ (+ "replacement receiver joins a running turn",+ [+ TaskStartedMessage("notification-tool"),+ UserMessage(content="check the build", origin=human),+ ],+ [],+ True,+ ),+ ]++ class _Formatter:+ @staticmethod+ def format_assistant_message(parts):+ return "\n".join(parts)++ @staticmethod+ def format_toolcall(name, input_data, **_kwargs):+ return f"{name}({input_data['command']})"++ @staticmethod+ def format_toolcall_label(name, input_data, **_kwargs):+ return f"{name}: {input_data['command']}"++ for label, turn_start, live_before_result, replaces_receiver in cases:+ with self.subTest(label):+ key = "session-proven-human-turn:/tmp/work"+ agent, service = _build_agent()+ context = _context(key)+ agent.emit_result_message = AsyncMock(return_value="message-id")+ agent._get_formatter = lambda _context: _Formatter()++ def visible():+ return [+ (call.args[1], call.args[2])+ for call in agent.controller.emit_agent_message.await_args_list+ if len(call.args) > 2 and call.args[1] in {"assistant", "toolcall"}+ ]++ before_result = []++ class _Client:+ receivers = 0++ def receive_messages(self):+ self.receivers += 1++ async def failed():+ raise RuntimeError("receiver failed")+ yield++ async def stream():+ for message in turn_start:+ yield message+ yield AssistantMessage(_block(TextBlock, text="progress"))+ yield AssistantMessage(+ _block(+ ToolUseBlock,+ id="tool-pwd",+ name="Bash",+ input={"command": "pwd"},+ ),+ _block(TextBlock, text="final"),+ )+ before_result.extend(visible())+ yield ResultMessage("final", origin=human)++ return failed() if replaces_receiver and self.receivers == 1 else stream()++ client = _Client()+++ async def receive():+ await agent._receive_messages(+ client,+ "sess-proven-human-turn",+ "/tmp/work",+ context,+ composite_key=key,+ )++ if replaces_receiver:+ # A generic receiver error keeps the client, so the receiver+ # that the next human input starts may join a running turn.+ agent.record_model_hub_native_failure = AsyncMock()+ agent.controller.agent_auth_service = SimpleNamespace(+ maybe_emit_auth_recovery_message=AsyncMock(return_value=False),+ )+ agent.session_handler.handle_session_error = AsyncMock(return_value=False)+ await receive()+ request = _pending_request(key)+ agent._pending_requests[key] = [request]+ service.activities.start(+ backend="claude",+ runtime_key=key,+ session_id="sess-proven-human-turn",+ activity_id="dev-server",+ kind="local_bash",+ turn_id="earlier-turn",+ )+ await receive()+ for task in list(agent._activity_flush_tasks.values()):+ task.cancel()++ self.assertEqual(before_result, live_before_result)+ # Held or live, the human Result shows each frame exactly once.+ self.assertEqual(visible()[-2:], progress)+ self.assertEqual(visible().count(progress[0]), 1)+ self.assertEqual(agent.emit_result_message.await_count, 1)+ self.assertIs(agent.emit_result_message.await_args.kwargs["request"], request)+ # The task's own output is never merged into the human reply.+ self.assertEqual(request.output_activities, [])+async def test_buffered_foreground_tool_is_owned_before_task_started(self):key = "session-buffered-foreground-tool:/tmp/work"agent, service = _build_agent()