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): keep live human phases visible across tasks and steers (#2243)

Call Whitea78be44a1881
diff --git a/core/agent_tool_policy.py b/core/agent_tool_policy.py
index 9612ff4f8..65d515abb 100644
--- a/core/agent_tool_policy.py
+++ b/core/agent_tool_policy.py
@@ -73,9 +73,27 @@ def _advise(advice: str) -> ToolPolicyDecision:
return ToolPolicyDecision(allowed=True, advice=advice)
+def runs_in_background(
+ tool_name: str,
+ tool_input: Optional[Dict[str, Any]] = None,
+) -> bool:
+ """Whether one tool call detaches from the turn that issued it.
+
+ ``Agent`` runs in the background by default, so only an explicit false is
+ synchronous; ``Workflow`` always runs in the background; every other tool
+ is foreground unless the call explicitly asks for background.
+ """
+
+ flag = tool_input.get("run_in_background") if isinstance(tool_input, dict) else None
+ if tool_name == "Workflow":
+ return True
+ if tool_name == "Agent":
+ return flag is not False
+ return flag is True
+
+
def _check_agent(tool_input: Dict[str, Any]) -> ToolPolicyDecision:
- # Background is the tool's default, so only an explicit false is synchronous.
- if tool_input.get("run_in_background") is False:
+ if not runs_in_background("Agent", tool_input):
return ALLOWED
return _deny(
"A background subagent dies with this agent process and its result is "
@@ -129,7 +147,7 @@ def _check_bash(tool_input: Dict[str, Any]) -> ToolPolicyDecision:
# overwhelmingly used for work that finishes inside the turn (a build, a
# push, a test run). Denying all of it would cost more than the occasional
# lost result, so this advises instead of blocking.
- if tool_input.get("run_in_background") is not True:
+ if not runs_in_background("Bash", tool_input):
return ALLOWED
return _advise(
"This background shell is session-only: it dies with the agent process, "
diff --git a/docs/plans/claude-result-provenance.md b/docs/plans/claude-result-provenance.md
index 2331ed2c6..866b500a1 100644
--- a/docs/plans/claude-result-provenance.md
+++ b/docs/plans/claude-result-provenance.md
@@ -136,7 +136,7 @@ and native-input receipts, not a second human terminal state machine.
| External acceptance but failed local settlement without durable Message evidence | Keep the claim and original payload; refine only the record's retry policy to the dispatcher's existing local-settlement-only path. Never resend externally. |
| Durable delivery and local settlement | Retire that record and only its captured synthetic Request/token. An unrelated current synthetic or human owner is untouched. |
| EOF/error/Stop/replacement | Retire exactly the dead client. Frozen records survive; provisional detached records from that generation are conservatively frozen without borrowing replacement provenance. |
-| Activity classification | Update lineage and notify the Run owner without deleting awaiting/claimed output receipts. |
+| Activity classification | Update lineage and notify the Run owner of background terminals without deleting awaiting/claimed output receipts; a foreground terminal only acknowledges its snapshot (2026-09-28). |
| Terminal-snapshot acknowledgement | Delete only an indexed terminal snapshot, after Run-owner acceptance. Force-ended snapshots remain indexed until acknowledgement. |
The existing admission fence is consulted before Result classification/replay,
@@ -161,8 +161,10 @@ have a reachable drain/ack path.
The managed worker rechecks the ledger after awaited delivery: a Result appended
during a retry remains its responsibility even if the initial list was drained.
There is no new generic queue, service, or per-output timer. Missing/unknown
-origin with competing Activity remains conservative; foreground execution mode
-and TaskStarted linkage are still not human-provenance evidence.
+origin with competing Activity remains conservative; while ownership is
+contested, foreground execution mode and TaskStarted linkage are still not
+human-provenance evidence. The uncontested live case is covered in the
+2026-09-28 section.
Consumer coverage includes event-held native streams; old payload plus later
failure and human phases; human and synthetic successor admission; Stop-first
@@ -283,3 +285,65 @@ human input queued behind the Turn indefinitely.
- 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.
+
+## Uncontested live phases and steer boundaries (2026-09-28)
+
+A long foreground command made a human Turn look stuck. Take this stream:
+`Bash(sleep 600)` is emitted live, its `TaskStarted` arrives, and the model
+keeps working. Every `TaskStarted` opened the provenance barrier, so each later
+Assistant and tool frame of that Turn was buffered until the terminal Result.
+The Web UI showed nothing for the rest of the Turn. If a steer receipt arrived
+while frames were buffered, the receipt boundary cleared the buffer and its
+provisional facts without replaying them. Those frames were lost, and the
+pre-steer Activities stayed provisional snapshots that kept competing.
+
+- A live frame is emitted only when nothing competes with the pending human
+ request, so the receiver has already attributed it to that request. A
+ foreground task whose parent tool is such a frame inherits the frame's owner
+ when all of these hold: the tool is still recorded as a live foreground tool,
+ no frame is buffered, no competing Activity or output record exists, and the
+ pending request is a real human request. The Activity starts with that Turn,
+ Run, and delivery identity and `provenance_human`, so it does not compete, and
+ later frames of the phase stay live. If any condition fails, the task is
+ provisional as before.
+- Only foreground tools qualify. A foreground completion has no Activity output
+ that a Result could claim, and its terminal follows the existing
+ non-provisional foreground owner: the Turn's Result settles the Run. A
+ background tool's completion creates queued output, and the Activity flush can
+ complete a Turn from it. Background tools therefore stay provisional until the
+ Result classifies their phase, even when their frame was live. Foreground
+ follows each tool's real default through the shared tool policy
+ (`runs_in_background`): an `Agent` call without `run_in_background` is a
+ background subagent, while a `Bash` call without it is foreground.
+- A foreground task is one step of its Turn, and the agent can recover from a
+ failed step. Its terminal never settles the Run on either path: the Turn's
+ Result owns the Run outcome. Previously a foreground task that stayed
+ provisional behind competing output was handed to the Run owner once the
+ human Result classified it, so a failed, stopped, or killed step made the Run
+ fail or cancel immediately and stickily, even when the Turn then succeeded.
+ The same stream settled differently depending on whether unrelated output
+ happened to compete. Classification now only acknowledges such a foreground
+ terminal snapshot; classified background terminals still notify the Run
+ owner, which `Activity classification` below describes.
+- When a steer receipt arrives while frames are buffered, no Result separates
+ those frames from the steer, so Claude consumed the steer within the same
+ turn. The receiver appends a steer-boundary marker and keeps the frames and
+ their provisional facts for the one terminal Result that classifies both
+ sides. A human Result replays the frames and emits the pre-steer text at the
+ marker as non-terminal primary output, the same shape as a live steer
+ boundary. Foreground-tool evidence is phase-local there too: the marker
+ retires the pre-steer evidence, so a post-steer Result without its own
+ Assistant text keeps its result text instead of the silent tool-only
+ sentinel. A detached Result ignores the marker and keeps the pending request.
+ Without buffered frames, the existing live boundary behavior is unchanged.
+- Replay is ordered. Once a phase has a buffered frame, every later frame of
+ that phase is buffered too, even if the competing output finishes first. A
+ later frame therefore cannot overtake earlier held frames, and replay after
+ the marker re-derives exactly the evidence that belongs after the boundary.
+
+Consumer tests cover the uncontested live task, a competing Activity that
+appears before `TaskStarted`, a default-background `Agent` task, and human or
+detached classification of buffered frames across a steer boundary, including a
+post-steer Result with no Assistant frame and competition that ends after the
+steer. They are hermetic receiver tests, not native SDK or Web/IM end-to-end
+tests.
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 27e5720bc..ed6e5bfbf 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -7,6 +7,7 @@ from dataclasses import dataclass, field, replace
from typing import Any, Callable, Literal, Optional
from core.agent_auth_service import classify_auth_error
+from core.agent_tool_policy import runs_in_background as tool_runs_in_background
from core.backend_failure import backend_failure_notification_output, emit_backend_failure
from core.handlers.session_handler import ClaudeInputNotSentError, ClaudeSessionNotFoundError
from core.message_dispatcher import ActivityOutputDeliveryError
@@ -59,6 +60,11 @@ from modules.im import MessageContext
logger = logging.getLogger(__name__)
+# Position of a native steer receipt inside buffered Assistant frames. The
+# frames on both sides share one terminal Result, which decides whether the
+# boundary closes a human primary phase or is ignored with detached output.
+_STEER_BOUNDARY = object()
+
@dataclass
class _ClaudeInputReceipt:
@@ -2929,6 +2935,8 @@ class ClaudeAgent(BaseAgent):
return None
for message, frame_steering_generation in messages:
+ if message is _STEER_BOUNDARY:
+ continue
try:
text = self._extract_text_blocks(message, context)
except Exception:
@@ -3866,8 +3874,11 @@ class ClaudeAgent(BaseAgent):
service = getattr(self.controller, "agent_service", None)
notify = getattr(service, "on_activity_terminal", None)
- if not callable(notify):
- return
+ ack_terminal = getattr(
+ self._activity_registry(),
+ "ack_recovered_terminal",
+ None,
+ )
for activity in activities:
status = str(getattr(activity, "status", "") or "").strip().lower()
if status not in {
@@ -3880,7 +3891,23 @@ class ClaudeAgent(BaseAgent):
continue
if getattr(activity, "completed_at", None) is None:
continue
- notify(activity)
+ if getattr(activity, "foreground", False):
+ # A foreground task is one step of its Turn, and the agent can
+ # recover from a failed step. As on the live path, the Turn's
+ # Result owns the Run outcome; only the provenance snapshot the
+ # task kept until that Result arrived is retired here.
+ if callable(ack_terminal):
+ try:
+ ack_terminal(activity)
+ except Exception:
+ logger.warning(
+ "Failed to retire classified foreground Activity %s",
+ getattr(activity, "id", ""),
+ exc_info=True,
+ )
+ continue
+ if callable(notify):
+ notify(activity)
def _attach_request_activities(
self,
@@ -4096,15 +4123,12 @@ class ClaudeAgent(BaseAgent):
tool_use_id = str(getattr(block, "id", "") or "").strip()
if not tool_use_id:
return
- tool_input = getattr(block, "input", None)
- # Deliberately not the same test as ``core/agent_tool_policy.py``, which
- # treats an omitted flag on an ``Agent`` call as background because that
- # is the tool's documented default. This helper is generic over every
- # tool, and for the dominant case -- ``Bash`` -- an omitted flag means
- # foreground. Misjudging a frame here only mislabels a task frame, so it
- # stays with the majority reading instead of special-casing per tool.
- runs_in_background = bool(
- isinstance(tool_input, dict) and tool_input.get("run_in_background") is True
+ # Foreground evidence decides live Activity ownership, so it follows
+ # each tool's real default: an ``Agent`` call with no flag runs in the
+ # background even though a ``Bash`` call with no flag does not.
+ runs_in_background = tool_runs_in_background(
+ str(getattr(block, "name", "") or ""),
+ getattr(block, "input", None),
)
if provisional:
self._provisional_tool_use_ids.setdefault(
@@ -4408,6 +4432,11 @@ class ClaudeAgent(BaseAgent):
def _should_buffer_assistant_message(self, composite_key: str) -> bool:
"""Hold an origin-less Assistant frame while Activity ownership is open."""
+ if self._buffered_assistant_messages.get(composite_key):
+ # Replay is ordered: once a phase's frames are held, the rest of
+ # that phase is held with them, even if competing output has since
+ # finished. A later frame must not overtake the earlier ones.
+ return True
records = self._output_records_for_runtime(composite_key)
if records:
pending = self._pending_requests.get(composite_key) or []
@@ -4476,6 +4505,26 @@ class ClaudeAgent(BaseAgent):
)
for message, frame_steering_generation in messages:
try:
+ if message is _STEER_BOUNDARY:
+ if not detached:
+ # Mirror the live steer boundary: the text before it
+ # closes the primary phase without closing the Turn.
+ await self._emit_steered_primary_output(
+ context,
+ composite_key,
+ str(
+ self._last_assistant_text.get(composite_key) or ""
+ ).strip(),
+ )
+ self._last_assistant_text.pop(composite_key, None)
+ self._pending_assistant_message.pop(composite_key, None)
+ # Foreground-tool evidence is phase-local, as on the
+ # live steer path. Every later frame of this phase is
+ # buffered, so replaying them re-derives exactly the
+ # evidence that belongs after the boundary.
+ self._foreground_tool_use_ids.pop(composite_key, None)
+ self._turns_with_foreground_tools.discard(composite_key)
+ continue
assistant_text = self._extract_text_blocks(message, context)
context_tokens = self._extract_context_tokens(message)
if context_tokens:
@@ -4661,19 +4710,42 @@ class ClaudeAgent(BaseAgent):
) -> None:
"""Close all response-local primary state at the native input boundary."""
- if not await self._emit_buffered_primary_phase(context, composite_key):
- pending = self._pending_requests.get(composite_key) or []
- primary_request = pending[0] if pending else None
- primary_text = self._select_terminal_text(composite_key, None)
- if primary_text or self._request_activities(primary_request):
- self._adopt_pending_turn_token(context, primary_request)
- await self._emit_primary_phase_output(
- context,
- primary_request,
- primary_text,
- )
+ emitted_primary = await self._emit_buffered_primary_phase(
+ context,
+ composite_key,
+ )
+ buffered = self._buffered_assistant_messages.get(composite_key)
+ if buffered:
+ # No Result separates these origin-less frames from the steer, so
+ # Claude consumed it inside the same turn: one terminal Result
+ # classifies both sides. Keep the frames and their provisional
+ # facts for it; human replay closes the primary phase here.
+ buffered.append((_STEER_BOUNDARY, None))
+ return
+ if not emitted_primary:
+ await self._emit_steered_primary_output(
+ context,
+ composite_key,
+ self._select_terminal_text(composite_key, None),
+ )
self._clear_result_phase_state(composite_key)
+ async def _emit_steered_primary_output(
+ self,
+ context: MessageContext,
+ composite_key: str,
+ primary_text: str,
+ ) -> None:
+ pending = self._pending_requests.get(composite_key) or []
+ primary_request = pending[0] if pending else None
+ if primary_text or self._request_activities(primary_request):
+ self._adopt_pending_turn_token(context, primary_request)
+ await self._emit_primary_phase_output(
+ context,
+ primary_request,
+ primary_text,
+ )
+
def _select_buffered_terminal_text(self, composite_key: str, buffered) -> str:
"""Render a buffered pre-steer result without using newer assistant text."""
message, assistant_text, had_foreground_tools = self._unpack_buffered_terminal(
@@ -4817,11 +4889,26 @@ class ClaudeAgent(BaseAgent):
)
pending = self._pending_requests.get(composite_key) or []
# A pending human request is not enough to prove that this Activity
- # belongs to it. Keep all newly-created Activities provisional until
- # Result.origin classifies the phase, even when a buffered foreground
- # ToolUseBlock already supplied an operational foreground hint.
+ # belongs to it: an interleaved detached phase may have started it.
+ # Keep newly-created Activities provisional until Result.origin
+ # classifies the phase, even when a buffered foreground ToolUseBlock
+ # already supplied an operational foreground hint. The exception is a
+ # foreground task whose parent tool frame was emitted live for that
+ # human request: that frame was attributed because nothing competed,
+ # and it still does not, so the task inherits the frame's owner. A
+ # foreground completion carries no Activity output for a terminal
+ # Result to claim; background tools stay provisional.
+ live_human_activity = bool(
+ pending
+ and existing_activity is None
+ and tool_use_id
+ and tool_use_id in provisional_foreground_tool_ids
+ and not getattr(pending[0], "_claude_synthetic_owner", False)
+ and not self._buffered_assistant_messages.get(composite_key)
+ and not self._has_competing_activity(composite_key)
+ )
provenance_pending = bool(
- (pending and existing_activity is None)
+ (pending and existing_activity is None and not live_human_activity)
or (
existing_activity is not None
and existing_activity.metadata.get("provenance_pending")
@@ -4910,6 +4997,8 @@ class ClaudeAgent(BaseAgent):
).strip()
if delivery_key:
metadata["delivery_key_external"] = delivery_key
+ if live_human_activity:
+ metadata["provenance_human"] = True
run_ids = self._activity_run_ids(composite_key, context)
turn_id = self._current_turn_id(composite_key, context)
else:
diff --git a/tests/test_claude_result_provenance.py b/tests/test_claude_result_provenance.py
index 043de9611..b1ad03b96 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
+from modules.claude_sdk_compat import TextBlock, ToolUseBlock, UserMessage
from modules.agents.claude_agent import ClaudeAgent
from tests.test_claude_agent_initiated_turn import _build_agent, _dispatcher_owned_emit
@@ -128,6 +128,51 @@ def _failing_client(messages, error):
return _Client()
+class _ToolcallFormatter:
+ @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']}"
+
+
+def _bash(tool_id: str, command: str):
+ return _block(ToolUseBlock, id=tool_id, name="Bash", input={"command": command})
+
+
+def _agent(tool_id: str, command: str):
+ """An ``Agent`` call without ``run_in_background``: background by default."""
+
+ return _block(ToolUseBlock, id=tool_id, name="Agent", input={"command": command})
+
+
+def _visible_emits(agent):
+ 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", "output"}
+ ]
+
+
+def _start_competing_activity(service, key: str) -> None:
+ """Start output that no pending human Turn owns, so its phase is contested."""
+
+ service.activities.start(
+ backend="claude",
+ runtime_key=key,
+ session_id="sess-competing",
+ activity_id="background-task",
+ kind="local_agent",
+ turn_id="background-turn",
+ )
+
+
def _task_pair(task_id: str):
return [
TaskStartedMessage(task_id),
@@ -352,6 +397,267 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(agent.emit_result_message.await_count, 1)
self.assertIs(agent.emit_result_message.await_args.kwargs["request"], request)
+ async def test_live_foreground_task_keeps_its_human_phase_streaming(self):
+ key = "session-live-foreground-task:/tmp/work"
+ agent, service = _build_agent()
+ context = _context(key)
+ request = _pending_request(key)
+ agent._pending_requests[key] = [request]
+ agent._get_formatter = lambda _context: _ToolcallFormatter()
+ agent.emit_result_message = AsyncMock(return_value="message-id")
+ before_result = {}
+
+ class _Client:
+ def receive_messages(self):
+ async def stream():
+ yield AssistantMessage(_bash("live-tool", "sleep 60"))
+ yield TaskStartedMessage("live-task", tool_use_id="live-tool")
+ yield AssistantMessage(
+ _block(TextBlock, text="progress while the task runs"),
+ _bash("next-tool", "pwd"),
+ )
+ before_result["emitted"] = _visible_emits(agent)
+ before_result["buffered"] = list(
+ agent._buffered_assistant_messages.get(key) or ()
+ )
+ before_result["activities"] = (
+ service.activities.active_for_runtime("claude", key)
+ )
+ yield TaskNotificationMessage("live-task", "live task finished")
+ yield ResultMessage("human reply", origin={"kind": "human"})
+
+ return stream()
+
+ await agent._receive_messages(
+ _Client(),
+ "sess-live-foreground-task",
+ "/tmp/work",
+ context,
+ composite_key=key,
+ )
+
+ # The task's parent tool was already emitted live for this human
+ # phase while nothing competed, so later frames stay live too.
+ self.assertEqual(
+ before_result["emitted"],
+ [("toolcall", "Bash(sleep 60)"), ("toolcall", "Bash(pwd)")],
+ )
+ self.assertEqual(before_result["buffered"], [])
+ [activity] = before_result["activities"]
+ self.assertEqual(activity.turn_id, "human-turn")
+ self.assertTrue(activity.metadata.get("provenance_human"))
+ self.assertFalse(activity.metadata.get("provenance_pending"))
+ self.assertNotIn(key, agent._activity_provenance_barriers)
+ self.assertEqual(agent.emit_result_message.await_count, 1)
+ self.assertIs(agent.emit_result_message.await_args.kwargs["request"], request)
+ self.assertFalse(agent._has_pending_requests(key))
+ self.assertFalse(service.activities.has_completed_output("claude", key))
+
+ async def test_live_task_stays_provisional_without_uncontested_foreground_proof(self):
+ cases = {
+ # Output not bound to this Turn appears before the task starts, so
+ # ownership of later frames is contested again.
+ "competing output": (_bash("live-tool", "sleep 60"), True),
+ # An Agent call with no flag is a background subagent, whatever a
+ # Bash call with no flag would mean.
+ "default-background Agent": (_agent("live-tool", "sleep 60"), False),
+ }
+ for index, (label, (tool_block, compete)) in enumerate(cases.items()):
+ with self.subTest(label):
+ key = f"session-live-task-provisional-{index}:/tmp/work"
+ agent, service = _build_agent()
+ context = _context(key)
+ request = _pending_request(key)
+ agent._pending_requests[key] = [request]
+ agent._get_formatter = lambda _context: _ToolcallFormatter()
+ agent.emit_result_message = AsyncMock(return_value="message-id")
+ before_result = {}
+ tool_name = tool_block.name
+
+ class _Client:
+ def receive_messages(self):
+ async def stream():
+ yield AssistantMessage(tool_block)
+ if compete:
+ _start_competing_activity(service, key)
+ yield TaskStartedMessage(
+ "live-task", tool_use_id="live-tool"
+ )
+ yield AssistantMessage(_bash("next-tool", "pwd"))
+ before_result["emitted"] = _visible_emits(agent)
+ before_result["activity"] = next(
+ activity
+ for activity in service.activities.active_for_runtime(
+ "claude", key
+ )
+ if activity.id == "live-task"
+ )
+ yield ResultMessage("human reply", origin={"kind": "human"})
+
+ return stream()
+
+ await agent._receive_messages(
+ _Client(),
+ "sess-live-task-provisional",
+ "/tmp/work",
+ context,
+ composite_key=key,
+ )
+
+ self.assertEqual(
+ before_result["emitted"],
+ [("toolcall", f"{tool_name}(sleep 60)")],
+ )
+ self.assertTrue(
+ before_result["activity"].metadata.get("provenance_pending")
+ )
+ self.assertIsNone(before_result["activity"].turn_id)
+ self.assertIn(("toolcall", "Bash(pwd)"), _visible_emits(agent))
+ self.assertIs(
+ agent.emit_result_message.await_args.kwargs["request"],
+ request,
+ )
+
+ async def test_steer_boundary_keeps_buffered_frames_for_the_human_result(self):
+ post_steer_answer = AssistantMessage(
+ _bash("post-steer-tool", "ls"),
+ _block(TextBlock, text="answer after steer"),
+ )
+ cases = {
+ "post-steer answer frame": (
+ [post_steer_answer],
+ [("toolcall", "Bash(ls)")],
+ ),
+ # The pre-steer foreground tool must not make the post-steer
+ # Result look like a silent tool-only phase.
+ "result without a post-steer frame": ([], []),
+ # Competing output that finishes after the steer does not let a
+ # later frame overtake the ones still held before it.
+ "competition ends after the steer": (
+ ["finish-competition", post_steer_answer],
+ [("toolcall", "Bash(ls)")],
+ ),
+ }
+ for index, (label, (post_steer, post_steer_emits)) in enumerate(cases.items()):
+ with self.subTest(label):
+ key = f"session-buffered-steer-{index}:/tmp/work"
+ agent, service = _build_agent()
+ context = _context(key)
+ request = _pending_request(key)
+ agent._pending_requests[key] = [request]
+ agent._get_formatter = lambda _context: _ToolcallFormatter()
+ agent.emit_result_message = AsyncMock(return_value="message-id")
+ _start_competing_activity(service, key)
+ receipt = agent._register_native_input(
+ key, "steered prompt", kind="steer"
+ )
+ receipt.state = "accepted"
+ agent._advance_steering_generation(key)
+
+ class _Client:
+ def receive_messages(self):
+ async def stream():
+ yield AssistantMessage(
+ _block(TextBlock, text="answer before steer"),
+ _bash("pre-steer-tool", "pwd"),
+ )
+ yield UserMessage("steered prompt")
+ for item in post_steer:
+ if item == "finish-competition":
+ service.activities.complete(
+ backend="claude",
+ runtime_key=key,
+ activity_id="background-task",
+ status="completed",
+ )
+ continue
+ yield item
+ yield ResultMessage(
+ "answer after steer", origin={"kind": "human"}
+ )
+
+ return stream()
+
+ await agent._receive_messages(
+ _Client(),
+ "sess-buffered-steer",
+ "/tmp/work",
+ context,
+ composite_key=key,
+ )
+
+ # Same order and shape the live path emits: the pre-steer text
+ # closes its phase as a non-terminal output at the boundary.
+ self.assertEqual(
+ _visible_emits(agent),
+ [
+ ("toolcall", "Bash(pwd)"),
+ ("output", "answer before steer"),
+ *post_steer_emits,
+ ],
+ )
+ presteer_output = next(
+ call.kwargs["output"]
+ for call in agent.controller.emit_agent_message.await_args_list
+ if call.args[1] == "output"
+ )
+ self.assertFalse(presteer_output.completes_turn)
+ self.assertEqual(agent.emit_result_message.await_count, 1)
+ self.assertEqual(
+ agent.emit_result_message.await_args.args[1],
+ "answer after steer",
+ )
+ self.assertIs(
+ agent.emit_result_message.await_args.kwargs["request"],
+ request,
+ )
+ self.assertFalse(agent._has_pending_requests(key))
+ self.assertEqual(agent._buffered_assistant_messages.get(key), None)
+
+ async def test_steer_boundary_frames_follow_a_detached_result(self):
+ key = "session-buffered-steer-detached:/tmp/work"
+ agent, service = _build_agent()
+ context = _context(key)
+ request = _pending_request(key)
+ agent._pending_requests[key] = [request]
+ agent._get_formatter = lambda _context: _ToolcallFormatter()
+ agent.emit_result_message = AsyncMock(return_value="message-id")
+ _start_competing_activity(service, key)
+ receipt = agent._register_native_input(key, "steered prompt", kind="steer")
+ receipt.state = "accepted"
+ agent._advance_steering_generation(key)
+
+ await agent._receive_messages(
+ _client(
+ [
+ AssistantMessage(
+ _block(TextBlock, text="detached before steer"),
+ _bash("pre-steer-tool", "pwd"),
+ ),
+ UserMessage("steered prompt"),
+ AssistantMessage(_block(TextBlock, text="detached after steer")),
+ ResultMessage(
+ "detached reply",
+ origin={"kind": "task-notification"},
+ ),
+ ]
+ ),
+ "sess-buffered-steer-detached",
+ "/tmp/work",
+ context,
+ composite_key=key,
+ )
+
+ # The boundary marker never turns detached frames into human output.
+ self.assertEqual(_visible_emits(agent), [])
+ self.assertEqual(agent.emit_result_message.await_count, 1)
+ self.assertEqual(
+ agent.emit_result_message.await_args.args[1],
+ "detached after steer",
+ )
+ self.assertIsNone(agent.emit_result_message.await_args.kwargs.get("request"))
+ self.assertIs(agent._pending_requests[key][0], request)
+
async def test_activity_flush_defers_until_buffered_phase_has_terminal_owner(self):
key = "session-provenance-flush-race:/tmp/work"
agent, service = _build_agent()
@@ -620,9 +926,14 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):
async def test_terminal_provisional_activity_statuses_rebind_before_run_settlement(
self,
):
- for status in ("failed", "stopped", "killed", "completed"):
- with self.subTest(status=status):
- key = f"session-terminal-lineage-{status}:/tmp/work"
+ cases = [
+ (mode, status)
+ for mode in ("background", "foreground")
+ for status in ("failed", "stopped", "killed", "completed")
+ ]
+ for mode, status in cases:
+ with self.subTest(mode=mode, status=status):
+ key = f"session-terminal-lineage-{mode}-{status}:/tmp/work"
agent, service = _build_agent()
context = _context(key)
request = _pending_request(key)
@@ -645,12 +956,18 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):
settle_activity_runs=settle_activity,
)
agent.emit_result_message = AsyncMock(return_value="message-id")
+ # Competing output keeps this task provisional until the human
+ # Result classifies its phase.
+ _start_competing_activity(service, key)
+ tool_input = {"command": "fixture"}
+ if mode == "background":
+ tool_input["run_in_background"] = True
tool = _block(
ToolUseBlock,
id=f"tool-{status}",
name="Bash",
- input={"command": "fixture"},
+ input=tool_input,
)
started = TaskStartedMessage(
f"task-{status}",
@@ -671,20 +988,31 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):
ResultMessage("human reply", origin={"kind": "human"}),
]
),
- f"sess-terminal-lineage-{status}",
+ f"sess-terminal-lineage-{mode}-{status}",
"/tmp/work",
context,
composite_key=key,
)
- settle_activity.assert_called_once()
- settled = settle_activity.call_args.args[0]
- self.assertEqual(settled.run_id, "human-run")
- self.assertEqual(settled.turn_id, "human-turn")
- self.assertEqual(
- settled.metadata["delivery_key_external"],
- "human-delivery",
- )
+ # Receiver EOF also disconnects the competing Activity; only
+ # the classified task carries the human lineage.
+ settled = [
+ call.args[0]
+ for call in settle_activity.call_args_list
+ if call.args[0].id == f"task-{status}"
+ ]
+ if mode == "foreground":
+ # A foreground task is a step of the Turn: the agent may
+ # recover from it, so the Result owns the Run outcome.
+ self.assertEqual(settled, [])
+ else:
+ [activity] = settled
+ self.assertEqual(activity.run_id, "human-run")
+ self.assertEqual(activity.turn_id, "human-turn")
+ self.assertEqual(
+ activity.metadata["delivery_key_external"],
+ "human-delivery",
+ )
self.assertFalse(
service.activities.terminal_snapshots_for_runtime(
"claude",
@@ -1697,6 +2025,7 @@ class ClaudeResultProvenanceTests(unittest.IsolatedAsyncioTestCase):
service.activities.classify_provisional_provenance = Mock(
side_effect=RuntimeError("activity store unavailable")
)
+ _start_competing_activity(service, key)
await agent._receive_messages(
_client(