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(agents): terminal run result must be the turn's final text, never a tool label (#923)

Call White37faf44ec1b4
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index fd39817bd..fd93fcbd4 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -68,6 +68,10 @@ class ClaudeAgent(BaseAgent):
self._detached_unsolicited_text: dict[str, str] = {}
self._activity_flush_tasks: dict[str, asyncio.Task] = {}
self._activity_settle_events: dict[str, asyncio.Event] = {}
+ self._foreground_tool_use_ids: dict[str, set[str]] = {}
+ self._turns_with_foreground_tools: set[str] = set()
+ self._detached_foreground_tool_use_ids: dict[str, set[str]] = {}
+ self._detached_foreground_task_ids: dict[str, set[str]] = {}
# Question handler for AskUserQuestion support (disabled)
# NOTE: Uncomment when SDK adds AskUserQuestion support
@@ -407,6 +411,9 @@ class ClaudeAgent(BaseAgent):
self._last_assistant_text.pop(composite_key, None)
self._pending_assistant_message.pop(composite_key, None)
+ self._foreground_tool_use_ids.pop(composite_key, None)
+ self._turns_with_foreground_tools.discard(composite_key)
+ self._clear_detached_foreground_tool_state(composite_key)
self._native_session_ids.pop(composite_key, None)
self._suppressed_synthetic_results.discard(composite_key)
self._suppressed_synthetic_error_text.pop(composite_key, None)
@@ -652,6 +659,14 @@ class ClaudeAgent(BaseAgent):
for block in getattr(message, "content", []) or []:
if isinstance(block, ToolUseBlock):
+ self._track_tool_activity_mode(
+ composite_key,
+ block,
+ detached=(
+ output_mode == "detached"
+ or composite_key in self._detached_activity_outputs
+ ),
+ )
# AskUserQuestion handling disabled - tool is disallowed via ClaudeAgentOptions
# if self.ENABLE_ASK_USER_QUESTION and self._question_handler:
# if self._question_handler.is_ask_user_question(block):
@@ -805,15 +820,23 @@ class ClaudeAgent(BaseAgent):
continue
if message_type == "result":
- result_text = getattr(message, "result", None)
+ raw_result_text = getattr(message, "result", None)
+ result_text = raw_result_text
detached_activities = self._detached_activity_outputs.pop(
composite_key,
None,
)
if detached_activities:
detached_activity = detached_activities[-1]
- if not result_text:
- result_text = self._detached_assistant_text.get(composite_key)
+ detached_text = self._detached_assistant_text.get(
+ composite_key
+ )
+ result_text = self._select_detached_result_text(
+ composite_key,
+ message,
+ raw_result_text,
+ detached_text,
+ )
self._detached_assistant_text.pop(composite_key, None)
try:
await self._emit_activity_result(
@@ -842,10 +865,18 @@ class ClaudeAgent(BaseAgent):
# own backend query and liveness/timeout path.
self._mark_session_idle_if_runtime_free(composite_key)
self._signal_activity_output_settled(composite_key)
+ self._clear_detached_foreground_tool_state(composite_key)
continue
if output_mode == "detached":
- if not result_text:
- result_text = self._detached_unsolicited_text.get(composite_key)
+ detached_text = self._detached_unsolicited_text.get(
+ composite_key
+ )
+ result_text = self._select_detached_result_text(
+ composite_key,
+ message,
+ raw_result_text,
+ detached_text,
+ )
self._detached_unsolicited_text.pop(composite_key, None)
self._detached_unsolicited_outputs.discard(composite_key)
if result_text:
@@ -857,27 +888,33 @@ class ClaudeAgent(BaseAgent):
parse_mode="markdown",
output=self._unsolicited_message_output(message),
)
+ self._clear_detached_foreground_tool_state(composite_key)
continue
self._pending_assistant_message.pop(composite_key, None)
- if self._consume_suppressed_synthetic_result(composite_key, message, result_text):
+ if self._consume_suppressed_synthetic_result(
+ composite_key,
+ message,
+ raw_result_text,
+ ):
self._last_assistant_text.pop(composite_key, None)
+ self._foreground_tool_use_ids.pop(composite_key, None)
+ self._turns_with_foreground_tools.discard(composite_key)
continue
- if not result_text:
- # ResultMessage had no text; use the last assistant
- # text as a fallback so the user still sees output.
- fallback = self._last_assistant_text.get(composite_key)
- if fallback:
- result_text = fallback
failure_disposition = await self._handle_terminal_failure_result(
context,
composite_key,
message,
- result_text,
+ raw_result_text
+ or self._last_assistant_text.get(composite_key),
)
if failure_disposition == "auth":
+ self._foreground_tool_use_ids.pop(composite_key, None)
+ self._turns_with_foreground_tools.discard(composite_key)
return
if failure_disposition:
+ self._foreground_tool_use_ids.pop(composite_key, None)
+ self._turns_with_foreground_tools.discard(composite_key)
continue
# NOTE: The pending assistant message is intentionally
@@ -888,6 +925,10 @@ class ClaudeAgent(BaseAgent):
pending_request = self._pop_pending_request(composite_key)
output_activities = self._request_activities(pending_request)
output_activity = output_activities[-1] if output_activities else None
+ result_text = self._select_terminal_text(
+ composite_key,
+ raw_result_text,
+ )
# The receiver is long-lived and reused across a session's
# turns, so ``context`` still carries the FIRST turn's
@@ -960,6 +1001,8 @@ class ClaudeAgent(BaseAgent):
pending_request,
)
self._last_assistant_text.pop(composite_key, None)
+ self._foreground_tool_use_ids.pop(composite_key, None)
+ self._turns_with_foreground_tools.discard(composite_key)
is_idle = self._mark_session_idle_if_no_pending_requests(composite_key)
try:
session = await self.session_manager.get_or_create_session(
@@ -1081,6 +1124,9 @@ class ClaudeAgent(BaseAgent):
finally:
self._suppressed_synthetic_results.discard(composite_key)
self._suppressed_synthetic_error_text.pop(composite_key, None)
+ self._foreground_tool_use_ids.pop(composite_key, None)
+ self._turns_with_foreground_tools.discard(composite_key)
+ self._clear_detached_foreground_tool_state(composite_key)
detached_activities = self._detached_activity_outputs.pop(composite_key, None)
if detached_activities:
registry = self._activity_registry()
@@ -1317,13 +1363,14 @@ class ClaudeAgent(BaseAgent):
@staticmethod
def _adopt_pending_turn_token(context: MessageContext, pending_request: Optional[AgentRequest]) -> None:
- """Copy the pending turn tokens onto the reused receiver context.
+ """Copy pending Turn identity onto the reused receiver context.
Claude runs one long-lived receiver per runtime session, so the context
captured when it started can carry an older turn's tokens. The web stream
guard uses ``turn_token`` and the shared backend runtime gate uses
``agent_runtime_turn_token``; both must follow the FIFO-matched pending
- request before any assistant/tool/result emit.
+ request before any assistant/tool/result emit. Harness Run attribution is
+ Turn-scoped too, so replace it rather than leaking a prior receiver turn.
"""
if pending_request is None:
return
@@ -1332,7 +1379,12 @@ class ClaudeAgent(BaseAgent):
token = src_payload.get(AGENT_TURN_TOKEN)
runtime_key = src_payload.get(AGENT_RUNTIME_TURN_KEY)
runtime_token = src_payload.get(AGENT_RUNTIME_TURN_TOKEN)
- if not (token or runtime_key or runtime_token):
+ attribution_keys = ("task_trigger_kind", "task_execution_id", "coalesced_queue")
+ current_payload = getattr(context, "platform_specific", None) or {}
+ updates_attribution = any(
+ key in src_payload or key in current_payload for key in attribution_keys
+ )
+ if not (token or runtime_key or runtime_token or updates_attribution):
return
if context.platform_specific is None:
context.platform_specific = {}
@@ -1342,6 +1394,17 @@ class ClaudeAgent(BaseAgent):
context.platform_specific[AGENT_RUNTIME_TURN_KEY] = runtime_key
if runtime_token:
context.platform_specific[AGENT_RUNTIME_TURN_TOKEN] = runtime_token
+ for key in attribution_keys:
+ if key not in src_payload:
+ context.platform_specific.pop(key, None)
+ continue
+ value = src_payload[key]
+ if isinstance(value, dict):
+ value = dict(value)
+ execution_ids = value.get("execution_ids")
+ if isinstance(execution_ids, list):
+ value["execution_ids"] = list(execution_ids)
+ context.platform_specific[key] = value
def _retire_failed_auth_turn(self, composite_key: str, context: MessageContext) -> None:
"""Retire a terminal auth-failure turn from the pending FIFO.
@@ -1530,6 +1593,73 @@ class ClaudeAgent(BaseAgent):
data = getattr(message, "data", None)
return data.get(name, default) if isinstance(data, dict) else default
+ def _track_tool_activity_mode(
+ self,
+ composite_key: str,
+ block: ToolUseBlock,
+ *,
+ detached: bool = False,
+ ) -> None:
+ """Remember which Claude task frames belong to foreground tool steps."""
+
+ tool_use_id = str(getattr(block, "id", "") or "").strip()
+ if not tool_use_id:
+ return
+ tool_input = getattr(block, "input", None)
+ runs_in_background = bool(
+ isinstance(tool_input, dict) and tool_input.get("run_in_background") is True
+ )
+ if runs_in_background:
+ return
+ if detached:
+ self._detached_foreground_tool_use_ids.setdefault(
+ composite_key,
+ set(),
+ ).add(tool_use_id)
+ return
+ self._foreground_tool_use_ids.setdefault(composite_key, set()).add(
+ tool_use_id
+ )
+ self._turns_with_foreground_tools.add(composite_key)
+
+ def _clear_detached_foreground_tool_state(self, composite_key: str) -> None:
+ self._detached_foreground_tool_use_ids.pop(composite_key, None)
+ self._detached_foreground_task_ids.pop(composite_key, None)
+
+ def _select_terminal_text(
+ self,
+ composite_key: str,
+ sdk_result: str | None,
+ ) -> str:
+ """Select terminal content from assistant TextBlocks, never tool labels."""
+
+ assistant_text = str(
+ self._last_assistant_text.get(composite_key) or ""
+ ).strip()
+ if assistant_text:
+ return assistant_text
+ if composite_key in self._turns_with_foreground_tools:
+ return "<silent>Claude turn completed without assistant text.</silent>"
+ return str(sdk_result or "")
+
+ def _select_detached_result_text(
+ self,
+ composite_key: str,
+ message,
+ sdk_result: str | None,
+ assistant_text: str | None,
+ ) -> str | None:
+ """Prefer assistant text unless a detached Result carries a real failure."""
+
+ failure = self._terminal_backend_failure(message, sdk_result)
+ if failure is not None:
+ return sdk_result or assistant_text
+ if assistant_text:
+ return assistant_text
+ if composite_key in self._detached_foreground_tool_use_ids:
+ return "<silent>Claude turn completed without assistant text.</silent>"
+ return sdk_result
+
def _current_turn_id(
self,
composite_key: str,
@@ -1603,6 +1733,18 @@ class ClaudeAgent(BaseAgent):
description = str(self._task_field(message, "description", "") or "").strip() or None
task_type = str(self._task_field(message, "task_type", "") or "").strip()
tool_use_id = str(self._task_field(message, "tool_use_id", "") or "").strip()
+ detached_tool_ids = self._detached_foreground_tool_use_ids.get(composite_key) or set()
+ detached_task_ids = self._detached_foreground_task_ids.get(composite_key) or set()
+ if task_id in detached_task_ids or (tool_use_id and tool_use_id in detached_tool_ids):
+ self._detached_foreground_task_ids.setdefault(composite_key, set()).add(
+ task_id
+ )
+ return True
+ foreground_tool_ids = self._foreground_tool_use_ids.get(composite_key) or set()
+ foreground = bool(
+ (existing_activity is not None and existing_activity.foreground)
+ or (tool_use_id and tool_use_id in foreground_tool_ids)
+ )
metadata = {
key: value
for key, value in {
@@ -1647,6 +1789,7 @@ class ClaudeAgent(BaseAgent):
activity_id=task_id,
kind=task_type or "background_task",
description=description,
+ foreground=foreground,
parent_activity_id=tool_use_id or None,
turn_id=turn_id,
run_id=run_ids[0] if run_ids else None,
@@ -1684,6 +1827,7 @@ class ClaudeAgent(BaseAgent):
activity_id=task_id,
kind=task_type or "background_task",
description=description,
+ foreground=foreground,
parent_activity_id=tool_use_id or None,
turn_id=turn_id,
run_id=run_ids[0] if run_ids else None,
@@ -1695,14 +1839,14 @@ class ClaudeAgent(BaseAgent):
activity_id=task_id,
status=status,
metadata=metadata,
- expects_output=status == "completed",
- retain_terminal_snapshot=status != "completed",
+ expects_output=status == "completed" and not foreground,
+ retain_terminal_snapshot=status != "completed" and not foreground,
)
service = getattr(self.controller, "agent_service", None)
on_terminal = getattr(service, "on_activity_terminal", None)
- if completed is not None and callable(on_terminal):
+ if completed is not None and not foreground and callable(on_terminal):
on_terminal(completed)
- if status != "completed":
+ if status != "completed" or foreground:
self._mark_session_idle_if_runtime_free(composite_key)
self._signal_activity_output_settled(composite_key)
return True
@@ -2304,14 +2448,14 @@ class ClaudeAgent(BaseAgent):
return session_id
return None
- def _extract_text_blocks(self, message, context: MessageContext) -> str:
+ def _extract_text_blocks(self, message, _context: MessageContext) -> str:
"""Extract text-only content blocks for result fallbacks."""
parts = []
for block in getattr(message, "content", []) or []:
if isinstance(block, TextBlock):
text = block.text.strip() if block.text else ""
if text:
- parts.append(self._get_formatter(context).escape_special_chars(text))
+ parts.append(text)
return "\n\n".join(parts).strip()
@staticmethod
diff --git a/tests/test_claude_agent_initiated_turn.py b/tests/test_claude_agent_initiated_turn.py
index 4c2bef896..8ae08c359 100644
--- a/tests/test_claude_agent_initiated_turn.py
+++ b/tests/test_claude_agent_initiated_turn.py
@@ -22,12 +22,16 @@ import sys
import unittest
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock, Mock
+from unittest.mock import ANY, AsyncMock, Mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from modules.agents.claude_agent import ClaudeAgent
from modules.agents.service import AgentService
+from modules.claude_sdk_compat import (
+ TextBlock,
+ ToolUseBlock,
+)
from core.message_output import terminal_output_for
@@ -156,6 +160,78 @@ def _completed_task_notification_then_wait_client(release: asyncio.Event):
return _Client()
+def _foreground_bash_then_delayed_result_client(
+ notification_seen: asyncio.Event,
+ release_result: asyncio.Event,
+):
+ def _content_block(block_type, **values):
+ block = object.__new__(block_type)
+ for name, value in values.items():
+ setattr(block, name, value)
+ return block
+
+ class ResultMessage:
+ subtype = "success"
+ result = "Push branch, confirm repo"
+ duration_ms = 1
+
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ text_message = AssistantMessage()
+ text_message.content = [
+ _content_block(
+ TextBlock,
+ text=(
+ "Two clean commits. Let me run `git push` and "
+ "**confirm** the repo/remote for the PR."
+ ),
+ )
+ ]
+ yield text_message
+
+ tool_message = AssistantMessage()
+ tool_message.content = [
+ _content_block(
+ ToolUseBlock,
+ id="toolu_push",
+ name="Bash",
+ input={
+ "command": "git push",
+ "description": "Push branch, confirm repo",
+ },
+ )
+ ]
+ yield tool_message
+
+ task_started = TaskStartedMessage()
+ task_started.subtype = "task_started"
+ task_started.task_id = "task-push"
+ task_started.description = "Push branch, confirm repo"
+ task_started.tool_use_id = "toolu_push"
+ task_started.task_type = "local_bash"
+ task_started.data = {}
+ yield task_started
+
+ task_completed = TaskNotificationMessage()
+ task_completed.subtype = "task_notification"
+ task_completed.task_id = "task-push"
+ task_completed.status = "completed"
+ task_completed.output_file = "/tmp/task-push.output"
+ task_completed.summary = "Push branch, confirm repo"
+ task_completed.tool_use_id = "toolu_push"
+ task_completed.data = {}
+ yield task_completed
+ yield task_completed
+ notification_seen.set()
+ await release_result.wait()
+ yield ResultMessage()
+
+ return _iterate()
+
+ return _Client()
+
+
def _fallback_client(data):
class ModelRefusalFallbackMessage:
subtype = "model_refusal_fallback"
@@ -826,6 +902,470 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
release.set()
await receiver
+ async def test_foreground_tool_activity_waits_for_result_and_uses_assistant_text(self):
+ agent, service = _build_agent()
+ agent._adopt_pending_turn_token = ClaudeAgent._adopt_pending_turn_token
+ agent.ACTIVITY_OUTPUT_FLUSH_GRACE_SECONDS = 0
+ formatter = SimpleNamespace(
+ escape_special_chars=lambda text: text.replace("`", "\\`").replace(
+ "*", "\\*"
+ ),
+ format_assistant_message=lambda parts: "\n\n".join(parts),
+ format_toolcall=lambda *_args, **_kwargs: "Bash tool call",
+ format_toolcall_label=lambda *_args, **_kwargs: "Push branch, confirm repo",
+ )
+ agent._get_formatter = lambda _context: formatter
+ emitted_provenance = []
+
+ async def _emit_result(context, _text, *, request=None, output=None, **_kwargs):
+ semantics = output or terminal_output_for(request)
+ emitted_provenance.append(semantics.provenance(context))
+ return "message-id"
+
+ agent.emit_result_message = AsyncMock(side_effect=_emit_result)
+ composite_key = "session-foreground-bash:/tmp/work"
+ origin_context = SimpleNamespace(
+ platform_specific={
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-origin",
+ "turn_token": "turn-origin",
+ }
+ )
+ queued_context = SimpleNamespace(
+ platform_specific={
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-followup",
+ "turn_token": "turn-followup",
+ }
+ )
+ origin_request = SimpleNamespace(context=origin_context)
+ queued_request = SimpleNamespace(context=queued_context)
+ agent._pending_requests[composite_key] = [origin_request, queued_request]
+ receiver_context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform="avibe",
+ platform_specific={"agent_session_id": "sess-foreground-bash"},
+ )
+ notification_seen = asyncio.Event()
+ release_result = asyncio.Event()
+ receiver = asyncio.create_task(
+ agent._receive_messages(
+ _foreground_bash_then_delayed_result_client(
+ notification_seen,
+ release_result,
+ ),
+ "session-foreground-bash",
+ "/tmp/work",
+ receiver_context,
+ composite_key=composite_key,
+ )
+ )
+
+ await asyncio.wait_for(notification_seen.wait(), timeout=1)
+ await asyncio.sleep(0.01)
+
+ agent.emit_result_message.assert_not_awaited()
+ self.assertEqual(
+ agent._pending_requests[composite_key],
+ [origin_request, queued_request],
+ )
+ self.assertFalse(
+ service.activities.has_completed_output("claude", composite_key)
+ )
+
+ release_result.set()
+ await asyncio.wait_for(receiver, timeout=1)
+
+ agent.emit_result_message.assert_awaited_once()
+ self.assertEqual(
+ agent.emit_result_message.await_args.args[1],
+ (
+ "Two clean commits. Let me run `git push` and **confirm** the "
+ "repo/remote for the PR."
+ ),
+ )
+ self.assertEqual(agent._pending_requests[composite_key], [queued_request])
+ self.assertEqual(emitted_provenance[0]["run_id"], "run-origin")
+
+ async def test_detached_unsolicited_error_keeps_sdk_failure_text(self):
+ agent, _service = _build_agent()
+ composite_key = "session-detached-unsolicited-error:/tmp/work"
+ context = SimpleNamespace(
+ platform_specific={"agent_session_id": "sess-detached-unsolicited-error"}
+ )
+ agent._detached_unsolicited_outputs.add(composite_key)
+ agent._detached_unsolicited_text[composite_key] = "Earlier assistant text"
+ agent.emit_result_message = AsyncMock(return_value="message-id")
+
+ class ResultMessage:
+ subtype = "error_during_execution"
+ result = "Bash exited with status 1"
+ duration_ms = 1
+
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ yield ResultMessage()
+
+ return _iterate()
+
+ await agent._receive_messages(
+ _Client(),
+ "session-detached-unsolicited-error",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+
+ agent.emit_result_message.assert_awaited_once()
+ self.assertEqual(
+ agent.emit_result_message.await_args.args[1],
+ "Bash exited with status 1",
+ )
+
+ async def test_detached_activity_result_does_not_clear_new_turn_foreground_state(self):
+ agent, service = _build_agent()
+ composite_key = "session-detached-keeps-foreground:/tmp/work"
+ context = SimpleNamespace(
+ platform_specific={"agent_session_id": "sess-detached-keeps-foreground"}
+ )
+ service.activities.start(
+ backend="claude",
+ runtime_key=composite_key,
+ session_id="sess-detached-keeps-foreground",
+ activity_id="task-older-turn",
+ kind="local_agent",
+ turn_id="older-turn",
+ )
+ service.activities.complete(
+ backend="claude",
+ runtime_key=composite_key,
+ activity_id="task-older-turn",
+ status="completed",
+ expects_output=True,
+ )
+ agent._detached_activity_outputs[composite_key] = (
+ service.activities.claim_completed_output_batch("claude", composite_key)
+ )
+ agent._foreground_tool_use_ids[composite_key] = {"toolu_new_turn"}
+ agent._turns_with_foreground_tools.add(composite_key)
+ agent._emit_activity_result = AsyncMock()
+ result_processed = asyncio.Event()
+ release_receiver = asyncio.Event()
+
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ yield ResultMessage()
+ result_processed.set()
+ await release_receiver.wait()
+
+ return _iterate()
+
+ receiver = asyncio.create_task(
+ agent._receive_messages(
+ _Client(),
+ "session-detached-keeps-foreground",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+ )
+ try:
+ await asyncio.wait_for(result_processed.wait(), timeout=1)
+ self.assertEqual(
+ agent._foreground_tool_use_ids[composite_key],
+ {"toolu_new_turn"},
+ )
+ self.assertIn(composite_key, agent._turns_with_foreground_tools)
+ finally:
+ release_receiver.set()
+ await receiver
+
+ async def test_detached_foreground_tool_does_not_poison_next_pending_turn(self):
+ agent, service = _build_agent()
+ agent._adopt_pending_turn_token = ClaudeAgent._adopt_pending_turn_token
+ composite_key = "session-detached-tool-then-user:/tmp/work"
+ context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform="avibe",
+ platform_specific={"agent_session_id": "sess-detached-tool-then-user"},
+ )
+ next_request = SimpleNamespace(
+ context=SimpleNamespace(
+ platform_specific={
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-next",
+ "turn_token": "turn-next",
+ }
+ )
+ )
+ agent._detached_unsolicited_outputs.add(composite_key)
+ agent.emit_result_message = AsyncMock(return_value="message-id")
+
+ def _content_block(block_type, **values):
+ block = object.__new__(block_type)
+ for name, value in values.items():
+ setattr(block, name, value)
+ return block
+
+ class ResultMessage:
+ subtype = "success"
+ duration_ms = 1
+
+ def __init__(self, result):
+ self.result = result
+
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ tool_message = AssistantMessage()
+ tool_message.content = [
+ _content_block(
+ ToolUseBlock,
+ id="toolu_detached",
+ name="Bash",
+ input={
+ "command": "git push",
+ "description": "Push branch, confirm repo",
+ },
+ )
+ ]
+ yield tool_message
+
+ started = TaskStartedMessage()
+ started.task_id = "task-detached-tool"
+ started.tool_use_id = "toolu_detached"
+ started.task_type = "local_bash"
+ started.data = {}
+ yield started
+
+ completed = TaskNotificationMessage()
+ completed.task_id = "task-detached-tool"
+ completed.status = "completed"
+ completed.summary = "Push branch, confirm repo"
+ completed.data = {}
+ yield completed
+
+ yield ResultMessage("Push branch, confirm repo")
+ agent._pending_requests[composite_key] = [next_request]
+ yield ResultMessage("Actual next-turn answer")
+
+ return _iterate()
+
+ await agent._receive_messages(
+ _Client(),
+ "session-detached-tool-then-user",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+
+ self.assertEqual(agent.emit_result_message.await_count, 2)
+ first_text = agent.emit_result_message.await_args_list[0].args[1]
+ second_text = agent.emit_result_message.await_args_list[1].args[1]
+ self.assertIn("<silent>", first_text)
+ self.assertNotIn("Push branch, confirm repo", first_text)
+ self.assertEqual(second_text, "Actual next-turn answer")
+ self.assertFalse(
+ service.activities.has_completed_output("claude", composite_key)
+ )
+
+ async def test_detached_activity_error_keeps_sdk_failure_text(self):
+ agent, service = _build_agent()
+ composite_key = "session-detached-error:/tmp/work"
+ context = SimpleNamespace(
+ platform_specific={"agent_session_id": "sess-detached-error"}
+ )
+ service.activities.start(
+ backend="claude",
+ runtime_key=composite_key,
+ session_id="sess-detached-error",
+ activity_id="task-detached-error",
+ kind="local_agent",
+ turn_id="origin-turn",
+ )
+ service.activities.complete(
+ backend="claude",
+ runtime_key=composite_key,
+ activity_id="task-detached-error",
+ status="completed",
+ expects_output=True,
+ )
+ activities = service.activities.claim_completed_output_batch(
+ "claude",
+ composite_key,
+ )
+ agent._detached_activity_outputs[composite_key] = activities
+ agent._detached_assistant_text[composite_key] = "Earlier assistant text"
+ agent._emit_activity_result = AsyncMock()
+
+ class ResultMessage:
+ subtype = "error_during_execution"
+ result = "Bash exited with status 1"
+ duration_ms = 1
+
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ yield ResultMessage()
+
+ return _iterate()
+
+ await agent._receive_messages(
+ _Client(),
+ "session-detached-error",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+
+ agent._emit_activity_result.assert_awaited_once()
+ self.assertEqual(
+ agent._emit_activity_result.await_args.args[2],
+ "Bash exited with status 1",
+ )
+
+ async def test_foreground_tool_without_text_settles_silently(self):
+ agent, _service = _build_agent()
+ composite_key = "session-textless-tool:/tmp/work"
+ agent._turns_with_foreground_tools.add(composite_key)
+
+ selected = agent._select_terminal_text(
+ composite_key,
+ "Push branch, confirm repo",
+ )
+ self.assertIn("<silent>", selected)
+ self.assertNotIn("Push branch, confirm repo", selected)
+
+ context = SimpleNamespace(platform_specific={})
+ await agent.emit_result_message(context, selected, duration_ms=1000)
+
+ agent.controller.emit_agent_message.assert_awaited_once()
+ self.assertEqual(agent.controller.emit_agent_message.await_args.args[2], "")
+ self.assertNotIn(
+ "result_footer",
+ agent.controller.emit_agent_message.await_args.kwargs,
+ )
+
+ def test_foreground_tool_failure_does_not_settle_owned_run(self):
+ agent, service = _build_agent()
+ composite_key = "session-foreground-failure:/tmp/work"
+ context = SimpleNamespace(
+ platform_specific={
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-foreground-failure",
+ "turn_token": "turn-foreground-failure",
+ }
+ )
+ agent._pending_requests[composite_key] = [SimpleNamespace(context=context)]
+ tool_block = object.__new__(ToolUseBlock)
+ tool_block.id = "toolu_failure"
+ tool_block.name = "Bash"
+ tool_block.input = {
+ "command": "false",
+ "description": "Run failing probe",
+ }
+ agent._track_tool_activity_mode(composite_key, tool_block)
+ on_terminal = Mock()
+ service.on_activity_terminal = on_terminal
+
+ started = TaskStartedMessage()
+ started.task_id = "task-failure"
+ started.description = "Run failing probe"
+ started.tool_use_id = "toolu_failure"
+ started.task_type = "local_bash"
+ started.data = {}
+ self.assertTrue(
+ agent._handle_activity_message(started, composite_key, context)
+ )
+
+ failed = TaskNotificationMessage()
+ failed.task_id = "task-failure"
+ failed.status = "failed"
+ failed.summary = "Run failing probe"
+ failed.tool_use_id = "toolu_failure"
+ failed.data = {}
+ self.assertTrue(
+ agent._handle_activity_message(failed, composite_key, context)
+ )
+
+ on_terminal.assert_not_called()
+ self.assertFalse(service.activities.has_completed_output("claude", composite_key))
+ self.assertEqual(
+ service.activities.active_for_runtime("claude", composite_key),
+ [],
+ )
+
+ async def test_receiver_exit_clears_foreground_tool_state(self):
+ agent, _service = _build_agent()
+ composite_key = "session-dead-receiver:/tmp/work"
+ context = SimpleNamespace(
+ platform_specific={"agent_session_id": "sess-dead-receiver"}
+ )
+ agent._foreground_tool_use_ids[composite_key] = {"toolu_stale"}
+ agent._turns_with_foreground_tools.add(composite_key)
+
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ if False:
+ yield None
+
+ return _iterate()
+
+ await agent._receive_messages(
+ _Client(),
+ "session-dead-receiver",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+
+ self.assertNotIn(composite_key, agent._foreground_tool_use_ids)
+ self.assertNotIn(composite_key, agent._turns_with_foreground_tools)
+
+ async def test_empty_error_result_uses_last_assistant_diagnostic(self):
+ agent, _service = _build_agent()
+ composite_key = "session-empty-error:/tmp/work"
+ context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform_specific={"agent_session_id": "sess-empty-error"},
+ )
+ agent._pending_requests[composite_key] = [SimpleNamespace(context=context)]
+ agent._last_assistant_text[composite_key] = "Detailed provider diagnostic"
+ agent._handle_terminal_failure_result = AsyncMock(return_value=True)
+
+ class ResultMessage:
+ subtype = "error_during_execution"
+ result = None
+ duration_ms = 1
+
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ yield ResultMessage()
+
+ return _iterate()
+
+ await agent._receive_messages(
+ _Client(),
+ "session-empty-error",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+
+ agent._handle_terminal_failure_result.assert_awaited_once_with(
+ context,
+ composite_key,
+ ANY,
+ "Detailed provider diagnostic",
+ )
+
async def test_summaryless_completed_activity_settles_silently(self):
agent, service = _build_agent()
composite_key = "session-silent-activity:/tmp/work"
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index d6ea74fdc..986895dd4 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -638,7 +638,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
next_request = SimpleNamespace(started_at=None)
agent._pending_requests[composite_key] = [queued_request, next_request]
agent._pending_reactions[composite_key] = [("m1", ":eyes:"), ("m2", ":eyes:")]
- agent._last_assistant_text[composite_key] = "last"
+ agent._last_assistant_text[composite_key] = "final assistant text"
controller.session_manager.session.session_active[composite_key] = True
result_message = type(
@@ -659,7 +659,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(mark_idle_calls, [])
agent.emit_result_message.assert_awaited_once_with(
context,
- "done",
+ "final assistant text",
subtype="success",
duration_ms=1,
parse_mode="markdown",
@@ -2646,9 +2646,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
class AdoptPendingTurnTokenTests(unittest.TestCase):
- """``_adopt_pending_turn_token`` realigns the reused receiver's stale token
- with the turn a result belongs to, so the streaming completion guard in
- ``_stream_chunk`` correlates it to the live sink instead of rejecting it."""
+ """Pending Turn identity replaces stale reused-receiver identity."""
def test_adopts_pending_requests_token(self):
# Reused receiver context still carries turn-1's token; the FIFO-matched
@@ -2671,6 +2669,54 @@ class AdoptPendingTurnTokenTests(unittest.TestCase):
ClaudeAgent._adopt_pending_turn_token(ctx, pending)
self.assertEqual(ctx.platform_specific["turn_token"], "T1")
+ def test_adopts_agent_run_attribution(self):
+ ctx = SimpleNamespace(
+ platform_specific={
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-old",
+ }
+ )
+ coalesced = {"execution_ids": ["run-new", "run-child"]}
+ pending = SimpleNamespace(
+ context=SimpleNamespace(
+ platform_specific={
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-new",
+ "coalesced_queue": coalesced,
+ }
+ )
+ )
+
+ ClaudeAgent._adopt_pending_turn_token(ctx, pending)
+
+ self.assertEqual(ctx.platform_specific["task_execution_id"], "run-new")
+ self.assertEqual(ctx.platform_specific["coalesced_queue"], coalesced)
+ self.assertIsNot(ctx.platform_specific["coalesced_queue"], coalesced)
+ self.assertIsNot(
+ ctx.platform_specific["coalesced_queue"]["execution_ids"],
+ coalesced["execution_ids"],
+ )
+
+ def test_clears_stale_agent_run_attribution_for_plain_turn(self):
+ ctx = SimpleNamespace(
+ platform_specific={
+ "turn_token": "T1",
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-old",
+ "coalesced_queue": {"execution_ids": ["run-old"]},
+ }
+ )
+ pending = SimpleNamespace(
+ context=SimpleNamespace(platform_specific={"turn_token": "T2"})
+ )
+
+ ClaudeAgent._adopt_pending_turn_token(ctx, pending)
+
+ self.assertEqual(ctx.platform_specific["turn_token"], "T2")
+ self.assertNotIn("task_trigger_kind", ctx.platform_specific)
+ self.assertNotIn("task_execution_id", ctx.platform_specific)
+ self.assertNotIn("coalesced_queue", ctx.platform_specific)
+
class _FakeBaseAgent(BaseAgent):
"""Minimal concrete BaseAgent so the shared session-binding helpers resolve
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 2bb21c966..c66b435f4 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -2326,6 +2326,67 @@ def test_duplicate_terminal_output_does_not_append_result_text_again(
assert "deferred_terminal_status" not in terminal["result_payload"]
+def test_claude_terminal_output_records_assistant_text_not_tool_description(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ caller_session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id="target-session",
+ message="delegated work",
+ agent_name="claude",
+ callback_session_id=caller_session_id,
+ )
+ assert request_store.claim(request.id) is not None
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+ assistant_text = (
+ "Two clean commits. Let me push the branch and confirm the repo/remote "
+ "for the PR."
+ )
+
+ recorded = sqlite_store.record_run_output(
+ request.id,
+ output_id="terminal",
+ text=assistant_text,
+ provenance={"backend": "claude", "run_id": request.id},
+ terminal_status="succeeded",
+ )
+
+ terminal = request_store.get_run(request.id)
+ assert terminal is not None
+ assert recorded["terminal_transition"] is True
+ assert terminal["result_text"] == assistant_text
+ assert [item["text"] for item in terminal["result_payload"]["outputs"]] == [
+ assistant_text
+ ]
+ assert "Push branch, confirm repo" not in terminal["result_text"]
+
+ service = ScheduledTaskService(
+ controller=_avibe_controller_double(
+ gate=SimpleNamespace(
+ submit_scheduled=lambda *_args, **_kwargs: None,
+ in_flight={},
+ ),
+ handle_scheduled_message=lambda *_args, **_kwargs: None,
+ ),
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+ asyncio.run(service._drain_callbacks())
+ asyncio.run(service._drain_callbacks())
+
+ callback_runs = [
+ run
+ for run in request_store.list_runs()
+ if run.get("source_kind") == "callback"
+ and run.get("parent_run_id") == request.id
+ ]
+ assert [run["message"] for run in callback_runs] == [assistant_text]
+
+
def test_failed_run_records_error_and_enqueues_one_terminal_callback(
tmp_path: Path,
monkeypatch,