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.

feat(core): support full-duplex Session outputs (#864)

Call Whitedb290d844363
diff --git a/core/controller.py b/core/controller.py
index f39c1b146..7dd3bbf9c 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -26,6 +26,7 @@ from core.agent_auth_service import AgentAuthService
from core.audio_asr import AudioAsrService
from core.message_context import build_context_session_key
from core.message_dispatcher import ConsolidatedMessageDispatcher
+from core.message_output import MessageOutput
from core.processing_indicator import ProcessingIndicatorService
from core.runtime_commands import RuntimeCommandWatcher
from core.scheduled_tasks import ScheduledTaskService
@@ -1263,6 +1264,7 @@ class Controller:
level: str = "normal",
status_label: Optional[str] = None,
result_footer: Optional[str] = None,
+ output: MessageOutput | None = None,
):
"""Backward-compatible entrypoint; delegated to message dispatcher."""
return await self.message_dispatcher.emit_agent_message(
@@ -1274,6 +1276,7 @@ class Controller:
level=level,
status_label=status_label,
result_footer=result_footer,
+ output=output,
)
def note_session_tokens(self, context: MessageContext, *, total: int) -> None:
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index 8394229a7..e3e21d5f7 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -6,8 +6,9 @@ embedded in ``Controller.emit_agent_message``.
from __future__ import annotations
-import logging
import asyncio
+import hashlib
+import logging
import time
from datetime import datetime, timezone
from pathlib import Path
@@ -18,7 +19,8 @@ from config.platform_registry import get_platform_descriptor
from config.v2_config import DEFAULT_AGENT_PROGRESS_STYLE
from modules.im import MessageContext
from modules.im.formatters.base_formatter import to_status_label
-from core.message_mirror import persist_agent_message
+from core.message_mirror import agent_message_exists, persist_agent_message
+from core.message_output import MessageOutput, output_for_message
from core.reply_enhancer import process_reply, strip_file_links, strip_silent_blocks
from core.session_turns import emit_matches_active_turn
from storage.background import SQLiteBackgroundTaskStore
@@ -49,7 +51,15 @@ def _run_is_cancelled(run: Any) -> bool:
return status in {"canceled", "cancelled"}
-async def _stream_chunk(controller, context, *, text: str, message_id: Optional[str], kind: str) -> None:
+async def _stream_chunk(
+ controller,
+ context,
+ *,
+ text: str,
+ message_id: Optional[str],
+ kind: str,
+ completes_turn: bool | None = None,
+) -> None:
"""Forward one durable agent message to the live streaming turn sink.
A web Chat caller registers a per-session sink in
@@ -58,8 +68,9 @@ async def _stream_chunk(controller, context, *, text: str, message_id: Optional[
even though the agent's receiver runs on a background task carrying a
stale per-turn context. We resolve the sink by *session key* (stable
across a session's turns) rather than off the context, so reused agent
- sessions stream correctly too. A ``result`` emit also marks the turn
- complete so ``dispatch_turn`` can close the stream right after it. No
+ sessions stream correctly too. A terminal ``result`` emit also marks the
+ turn complete so ``dispatch_turn`` can close the stream right after it;
+ multi-output callers explicitly pass ``completes_turn=False``. No
sink (IM / CLI turns) => no-op, byte-identical to master.
"""
@@ -85,7 +96,9 @@ async def _stream_chunk(controller, context, *, text: str, message_id: Optional[
# A misbehaving SSE consumer must not block the underlying agent
# reply. Log + swallow, same posture as ``mirror_outbound``.
logger.exception("turn on_chunk raised; dropping chunk kind=%s", kind)
- if kind == "result":
+ if completes_turn is None:
+ completes_turn = kind == "result"
+ if completes_turn:
# The result is the turn's final answer — release the streaming dispatch
# so it can close the SSE stream right after this chunk. Unlike chunk
# forwarding above, the COMPLETION signal IS turn-token-gated (mirrors
@@ -970,17 +983,69 @@ class ConsolidatedMessageDispatcher:
text: str,
message_id: str | None,
terminal_status: str | None,
+ output_semantics: MessageOutput,
+ provenance: dict[str, Any],
) -> None:
for run_id in run_ids:
get_run = getattr(store, "get_run", None)
if callable(get_run) and _run_is_cancelled(get_run(run_id)):
continue
- store.record_run_message(
- run_id,
- text=text,
- message_id=message_id,
- terminal_status=terminal_status,
- )
+ run_terminal_status = terminal_status
+ if run_terminal_status and self._run_has_blocking_activity(run_id):
+ defer_terminal = getattr(store, "defer_run_terminal", None)
+ if callable(defer_terminal):
+ defer_terminal(run_id, terminal_status=run_terminal_status)
+ run_terminal_status = None
+ record_output = getattr(store, "record_run_output", None)
+ if callable(record_output):
+ output_id = str(output_semantics.idempotency_key or "").strip()
+ if not output_id and output_semantics.sequence is not None:
+ output_id = f"sequence:{output_semantics.sequence}"
+ if not output_id and run_terminal_status:
+ output_id = "terminal"
+ if not output_id:
+ digest = hashlib.sha256(text.encode("utf-8")).hexdigest()[:20]
+ output_id = f"content:{digest}"
+ record_output(
+ run_id,
+ output_id=output_id,
+ text=text,
+ message_id=message_id,
+ sequence=output_semantics.sequence,
+ provenance=provenance,
+ terminal_status=run_terminal_status,
+ )
+ else:
+ # Compatibility for isolated stores and older persisted-state
+ # adapters while the shared SQLite path owns the output ledger.
+ store.record_run_message(
+ run_id,
+ text=text,
+ message_id=message_id,
+ terminal_status=run_terminal_status,
+ )
+
+ def _run_has_blocking_activity(self, run_id: str) -> bool:
+ service = getattr(self.controller, "agent_service", None)
+ registry = getattr(service, "activities", None)
+ has_blocker = getattr(registry, "has_blocking_run_activity", None)
+ if not callable(has_blocker):
+ return False
+ try:
+ return bool(has_blocker(run_id))
+ except Exception:
+ logger.warning("Failed to inspect owned Activities for Run %s", run_id, exc_info=True)
+ return True
+
+ def _forward_agent_run_outputs(self, run_ids: list[str]) -> None:
+ service = getattr(self.controller, "scheduled_task_service", None)
+ forward = getattr(service, "forward_run_outputs", None)
+ if not callable(forward):
+ return
+ try:
+ forward(run_ids)
+ except Exception:
+ logger.warning("Failed to forward Agent Run outputs for %s", ",".join(run_ids), exc_info=True)
def _record_agent_run_terminal_result(
self,
@@ -989,14 +1054,28 @@ class ConsolidatedMessageDispatcher:
message_id: str | None,
*,
is_error: bool,
+ output_semantics: MessageOutput | None = None,
log_label: str = "agent run terminal result",
) -> None:
payload = context.platform_specific or {}
- if payload.get("task_trigger_kind") != "agent_run":
- return
- run_ids = _coalesced_task_execution_ids(payload)
+ semantics = output_semantics or MessageOutput(completes_turn=True)
+ run_ids: list[str] = []
+ explicit_run_id = str(semantics.run_id or "").strip()
+ if explicit_run_id:
+ run_ids.append(explicit_run_id)
+ explicit_run_ids = semantics.metadata.get("run_ids")
+ if isinstance(explicit_run_ids, list):
+ for value in explicit_run_ids:
+ run_id = str(value or "").strip()
+ if run_id and run_id not in run_ids:
+ run_ids.append(run_id)
+ if not run_ids and payload.get("task_trigger_kind") == "agent_run":
+ run_ids = _coalesced_task_execution_ids(payload)
if not run_ids:
return
+ terminal_status = None
+ if semantics.settles_run:
+ terminal_status = "failed" if is_error else "succeeded"
store = None
try:
store = SQLiteBackgroundTaskStore()
@@ -1005,13 +1084,16 @@ class ConsolidatedMessageDispatcher:
run_ids=run_ids,
text=text,
message_id=message_id,
- terminal_status="failed" if is_error else "succeeded",
+ terminal_status=terminal_status,
+ output_semantics=semantics,
+ provenance=semantics.provenance(context),
)
except Exception as err:
logger.warning("Failed to record %s for %s: %s", log_label, ",".join(run_ids), err)
finally:
if store is not None:
store.close()
+ self._forward_agent_run_outputs(run_ids)
def _record_suppressed_agent_run_terminal_result(
self,
@@ -1020,12 +1102,14 @@ class ConsolidatedMessageDispatcher:
message_id: str | None,
*,
is_error: bool,
+ output_semantics: MessageOutput | None = None,
) -> None:
self._record_agent_run_terminal_result(
context,
text,
message_id,
is_error=is_error,
+ output_semantics=output_semantics,
log_label="suppressed agent run terminal result",
)
@@ -1215,6 +1299,7 @@ class ConsolidatedMessageDispatcher:
level: str = "normal",
status_label: Optional[str] = None,
result_footer: Optional[str] = None,
+ output: MessageOutput | None = None,
) -> Optional[str]:
"""Centralized dispatch for agent messages.
@@ -1251,12 +1336,25 @@ class ConsolidatedMessageDispatcher:
terminal ``result`` (the show_duration duration + token usage). It rides
as the platform subtext footer and, in concise mode, supersedes the status
bubble's own terminal footer so the outcome line stays consistent.
+
+ ``output`` separates Message delivery from lifecycle authority. The
+ compatibility default remains one terminal result. Explicit nonterminal
+ outputs remain in the current Turn, while detached outputs are delivered
+ to the Session/IM surface without touching a newer Turn or its stream.
"""
settings_manager = self.controller.get_settings_manager_for_context(context)
im_client = self._get_im_client(context)
canonical_type = settings_manager._canonicalize_message_type(message_type or "")
settings_key = self._get_settings_key(context)
+ output_semantics = output_for_message(canonical_type, output)
+ current_runtime_turn = self._is_current_runtime_turn(context)
+ mutates_turn_lifecycle = (
+ canonical_type == "result"
+ and output_semantics.completes_turn
+ and not output_semantics.detached
+ and current_runtime_turn
+ )
# Terminal status-bubble reason word for the done/orphan footer:
# a clean turn is "done" (✅); a failure is "stopped" (⏹) when it was an
@@ -1272,16 +1370,17 @@ class ConsolidatedMessageDispatcher:
# ``getattr`` keeps it a no-op for controllers without the hook (mirrors
# ``_signal_turn_complete``).
if canonical_type == "result":
- if not self._is_current_runtime_turn(context):
+ if not current_runtime_turn and not output_semantics.detached:
logger.info("Dropping stale result emit for superseded runtime turn in %s", self._get_session_key(context))
return None
# Settle the avibe dot for the ACTIVE turn's terminal result (idle, or
# failed on is_error) via the turn owner, which applies the active-turn
# guard + skips non-avibe contexts. Runtime gate release happens after
# the result path clears/persists/streams its own state.
- manager = getattr(self.controller, "session_turns", None)
- if manager is not None:
- manager.on_terminal_result(context, is_error=is_error)
+ if mutates_turn_lifecycle:
+ manager = getattr(self.controller, "session_turns", None)
+ if manager is not None:
+ manager.on_terminal_result(context, is_error=is_error)
text = strip_silent_blocks(text)
# ``level="silent"`` is the explicit visibility control (orthogonal to type):
# the message already settled the dot above (for a terminal result), so here
@@ -1290,7 +1389,18 @@ class ConsolidatedMessageDispatcher:
# body (e.g. a ``<silent>`` directive reduced to nothing) is silent too.
if level == "silent" or not text or not text.strip():
try:
- if canonical_type == "result":
+ if canonical_type == "result" and output_semantics.settles_run:
+ # Run completion is independent from visible Message and Turn
+ # completion cardinality. A detached/empty final output may
+ # settle its origin Run without touching the current Turn.
+ self._record_agent_run_terminal_result(
+ context,
+ text,
+ None,
+ is_error=is_error,
+ output_semantics=output_semantics,
+ )
+ if mutates_turn_lifecycle:
# A terminal result — even silent/empty — still means the turn
# finished: release the streaming SSE waiter so it closes now
# instead of hanging until the safety timeout, with no visible chunk.
@@ -1298,16 +1408,10 @@ class ConsolidatedMessageDispatcher:
# doesn't stay stuck (missing agent / exception / user stop).
await self._collapse_status_bubble(context, im_client, reason=terminal_reason)
await self._clear_consolidated_state(context)
- self._record_agent_run_terminal_result(
- context,
- text,
- None,
- is_error=is_error,
- )
self._signal_turn_complete(context)
return None
finally:
- if canonical_type == "result":
+ if mutates_turn_lifecycle:
await self._finish_processing_indicator_turn(context)
self._release_runtime_turn(context)
@@ -1317,6 +1421,8 @@ class ConsolidatedMessageDispatcher:
# cross-platform history) — persist_agent_message attributes IM rows to
# this target's scope.
target_context = self._get_target_context(context)
+ output_metadata = output_semantics.provenance(context) if output is not None else None
+ native_output_id = output_semantics.native_message_id(target_context) if output is not None else None
# For a result, persist the SAME cleaned text the user receives:
# process_reply() strips file:// markdown links + the trailing
@@ -1330,6 +1436,31 @@ class ConsolidatedMessageDispatcher:
enhanced = process_reply(text, include_quick_replies=quick_replies_on)
persist_text = enhanced.text if enhanced.text.strip() else text
+ if native_output_id and agent_message_exists(target_context, native_output_id):
+ logger.info("Skipping duplicate agent output %s", native_output_id)
+ try:
+ if canonical_type == "result" and output_semantics.settles_run:
+ duplicate_result_text = self._fold_footer(
+ persist_text,
+ result_footer if mutates_turn_lifecycle else None,
+ )
+ self._record_agent_run_terminal_result(
+ context,
+ duplicate_result_text,
+ None,
+ is_error=is_error,
+ output_semantics=output_semantics,
+ )
+ if mutates_turn_lifecycle:
+ await self._collapse_status_bubble(context, im_client, reason=terminal_reason)
+ await self._clear_consolidated_state(context)
+ self._signal_turn_complete(context)
+ return None
+ finally:
+ if mutates_turn_lifecycle:
+ await self._finish_processing_indicator_turn(context)
+ self._release_runtime_turn(context)
+
# Persistence is decided per delivery path below, not here, so that:
# * suppressed scheduled runs (intentionally private) never leak into
# the cross-platform messages history,
@@ -1359,6 +1490,7 @@ class ConsolidatedMessageDispatcher:
recorded_text,
message_id,
is_error=is_error,
+ output_semantics=output_semantics,
)
elif canonical_type == "result" or (context.platform_specific or {}).get("task_trigger_kind") != "agent_run":
self._record_suppressed_run_message(
@@ -1367,7 +1499,7 @@ class ConsolidatedMessageDispatcher:
message_id,
terminal_status=terminal_status,
)
- if canonical_type == "result":
+ if mutates_turn_lifecycle:
# A suppressed result still ends the turn; collapse any concise
# status bubble posted to a real channel so it doesn't stay stuck.
await self._collapse_status_bubble(context, im_client, reason=terminal_reason)
@@ -1375,7 +1507,7 @@ class ConsolidatedMessageDispatcher:
self._signal_turn_complete(context)
return message_id
finally:
- if canonical_type == "result":
+ if mutates_turn_lifecycle:
await self._finish_processing_indicator_turn(context)
self._release_runtime_turn(context)
@@ -1404,7 +1536,7 @@ class ConsolidatedMessageDispatcher:
# an edit of the bubble) so the IM fires a push notification; the
# transient bubble is then deleted (or collapsed to a marker when the
# platform can't delete) by ``_retire_status_bubble`` below.
- status_bubble_id = self._concise_status_bubble_id(context)
+ status_bubble_id = self._concise_status_bubble_id(context) if mutates_turn_lifecycle else None
status_consolidated_key = self._get_consolidated_message_key(context) if status_bubble_id else None
# S3: stop the heartbeat + finalize the key BEFORE delivery so a late
# heartbeat tick / in-flight process emit can't resurrect the bubble
@@ -1440,8 +1572,8 @@ class ConsolidatedMessageDispatcher:
# a reloaded transcript / inbox / agent-run record keeps the
# duration/token info (it used to live in the result body). It is
# set for BOTH platform kinds; only the DELIVERY form differs.
- folded_footer: Optional[str] = result_footer or None
- if result_footer:
+ folded_footer: Optional[str] = result_footer if mutates_turn_lifecycle else None
+ if folded_footer:
# Gate on the DELIVERY TARGET's capabilities, not the source
# context: a delivery_override can redirect a Slack/Discord/Lark
# turn to a non-subtext target (or vice versa), and the footer
@@ -1449,10 +1581,10 @@ class ConsolidatedMessageDispatcher:
if self._capabilities(target_context).supports_status_bubble:
# Subtext-capable: deliver as the grey subtext footer (body
# stays clean); persistence still folds it in below.
- done_footer = result_footer
+ done_footer = folded_footer
else:
# No subtext rendering: fold onto the delivered body too.
- display_text = self._fold_footer(display_text, result_footer)
+ display_text = self._fold_footer(display_text, folded_footer)
# Pass subtext to RAW send_message calls only when set, so an adapter
# whose send_message predates the subtext kwarg is never handed it
# (the helper paths apply the same guard internally).
@@ -1587,7 +1719,7 @@ class ConsolidatedMessageDispatcher:
if enhanced and enhanced.files:
await self._upload_file_links(im_client, target_context, enhanced.files)
- if scheduled_anchor_message_id:
+ if scheduled_anchor_message_id and mutates_turn_lifecycle:
try:
self.controller.session_handler.finalize_scheduled_delivery(context, scheduled_anchor_message_id)
except Exception as err:
@@ -1612,10 +1744,11 @@ class ConsolidatedMessageDispatcher:
# a fresh log message instead of appending to the previous one.
# Use the key captured at the top of this branch when present so
# teardown can't drift onto a recomputed key (C5).
- if status_consolidated_key:
- await self._drop_status_keys(status_consolidated_key)
- else:
- await self._clear_consolidated_state(context)
+ if mutates_turn_lifecycle:
+ if status_consolidated_key:
+ await self._drop_status_keys(status_consolidated_key)
+ else:
+ await self._clear_consolidated_state(context)
# The stored text keeps the footnote for BOTH platform kinds:
# ``display_text`` already carries it on non-subtext platforms (folded
@@ -1630,6 +1763,7 @@ class ConsolidatedMessageDispatcher:
persisted_result_text,
primary_message_id,
is_error=is_error,
+ output_semantics=output_semantics,
)
# Persist the delivered result (cleaned text == what was shown).
@@ -1658,18 +1792,29 @@ class ConsolidatedMessageDispatcher:
result_type,
avibe_text,
quick_replies=[b.text for b in avibe_enhanced.buttons] or None,
+ metadata=output_metadata,
+ native_message_id=native_output_id,
)
else:
persist_agent_message(
- target_context, result_type, persisted_result_text
+ target_context,
+ result_type,
+ persisted_result_text,
+ metadata=output_metadata,
+ native_message_id=native_output_id,
)
- if primary_message_id and display_text:
+ if primary_message_id and display_text and not output_semantics.detached:
# Stream the delivered result to live consumers (avibe SSE).
await _stream_chunk(
- self.controller, context, text=display_text, message_id=primary_message_id, kind="result"
+ self.controller,
+ context,
+ text=display_text,
+ message_id=primary_message_id,
+ kind="result",
+ completes_turn=mutates_turn_lifecycle,
)
- else:
+ elif mutates_turn_lifecycle:
# A terminal result still completes the turn even if every IM
# delivery path failed and therefore produced no durable message id.
# Without this release, direct agent_run and avibe turn waiters keep
@@ -1678,8 +1823,9 @@ class ConsolidatedMessageDispatcher:
return primary_message_id
finally:
- await self._finish_processing_indicator_turn(context)
- self._release_runtime_turn(context)
+ if mutates_turn_lifecycle:
+ await self._finish_processing_indicator_turn(context)
+ self._release_runtime_turn(context)
if canonical_type not in {"system", "assistant", "toolcall"}:
canonical_type = "assistant"
diff --git a/core/message_mirror.py b/core/message_mirror.py
index c4e55f410..2d075256f 100644
--- a/core/message_mirror.py
+++ b/core/message_mirror.py
@@ -24,7 +24,7 @@ from __future__ import annotations
import logging
from datetime import datetime, timezone
-from typing import Optional
+from typing import Any, Optional
from sqlalchemy.exc import IntegrityError
@@ -175,7 +175,9 @@ def persist_agent_message(
text: str,
*,
quick_replies: Optional[list[str]] = None,
-) -> None:
+ metadata: Optional[dict[str, Any]] = None,
+ native_message_id: Optional[str] = None,
+) -> Optional[dict]:
"""Persist one agent output into the workbench ``messages`` store.
Unified across **all** platforms (including avibe, which has no IM mirror)
@@ -283,6 +285,8 @@ def persist_agent_message(
author_name=agent_name,
message_type=message_type,
text=text,
+ metadata=metadata,
+ native_message_id=native_message_id,
parent_native_message_id=context.thread_id,
content=content,
)
@@ -311,8 +315,35 @@ def persist_agent_message(
maybe_notify_inbox_message(appended_row, inbox_row)
except Exception:
logger.debug("web push notification scheduling failed", exc_info=True)
+ return appended_row
except Exception:
logger.exception("persist_agent_message: failure on platform=%s", context.platform)
+ return None
+
+
+def agent_message_exists(context: MessageContext, native_message_id: str | None) -> bool:
+ """Check a stable output identity before external delivery.
+
+ The database unique constraint remains the final race guard. This early
+ check prevents ordinary callback or backend retries from posting the same
+ durable output to an IM surface twice.
+ """
+
+ platform = str(context.platform or "").strip()
+ identity = str(native_message_id or "").strip()
+ if not platform or not identity:
+ return False
+ try:
+ engine = get_cached_sqlite_engine()
+ with engine.begin() as conn:
+ return messages_service.native_message_exists(
+ conn,
+ platform=platform,
+ native_message_id=identity,
+ )
+ except Exception:
+ logger.debug("agent_message_exists: lookup failed open", exc_info=True)
+ return False
def mirror_harness_inbound(context: MessageContext, text: str) -> None:
diff --git a/core/message_output.py b/core/message_output.py
new file mode 100644
index 000000000..ace7fc0d6
--- /dev/null
+++ b/core/message_output.py
@@ -0,0 +1,80 @@
+"""Message-output semantics shared by every agent backend.
+
+The visible Message and the lifecycle event it may cause are deliberately
+separate. Existing result callers use the compatibility default (complete the
+current Turn); backends opt into non-terminal or detached output explicitly.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass, field
+from typing import Any, Mapping
+
+
+@dataclass(frozen=True)
+class MessageOutput:
+ """Lifecycle and hidden provenance for one user-visible agent output."""
+
+ completes_turn: bool = True
+ completes_run: bool | None = None
+ detached: bool = False
+ idempotency_key: str | None = None
+ activity_id: str | None = None
+ causation_id: str | None = None
+ sequence: int | None = None
+ run_id: str | None = None
+ metadata: Mapping[str, Any] = field(default_factory=dict)
+
+ @property
+ def settles_run(self) -> bool:
+ """Run completion defaults to legacy Turn completion unless separated."""
+
+ return self.completes_turn if self.completes_run is None else self.completes_run
+
+ def provenance(self, context: Any) -> dict[str, Any]:
+ spec = getattr(context, "platform_specific", None) or {}
+ trigger_kind = str(spec.get("task_trigger_kind") or "").strip()
+ inferred_run_id = (
+ str(spec.get("task_execution_id") or "").strip()
+ if trigger_kind == "agent_run"
+ else ""
+ )
+ values: dict[str, Any] = {
+ "turn_id": str(spec.get("turn_token") or "").strip() or None,
+ "activity_id": self.activity_id,
+ "run_id": self.run_id or inferred_run_id or None,
+ "causation_id": self.causation_id,
+ "sequence": self.sequence,
+ "output_id": self.idempotency_key,
+ "detached": self.detached,
+ }
+ values.update(dict(self.metadata))
+ return {key: value for key, value in values.items() if value is not None}
+
+ def native_message_id(self, context: Any) -> str | None:
+ """Stable persistence identity without exposing protocol text to users."""
+
+ key = str(self.idempotency_key or "").strip()
+ if not key:
+ return None
+ spec = getattr(context, "platform_specific", None) or {}
+ target = spec.get("agent_session_target")
+ backend = str(spec.get("vibe_agent_backend") or "").strip()
+ if not backend and isinstance(target, dict):
+ backend = str(target.get("agent_backend") or "").strip()
+ lineage = str(
+ self.run_id
+ or spec.get("task_execution_id")
+ or spec.get("agent_session_id")
+ or spec.get("agent_runtime_turn_key")
+ or "session"
+ ).strip()
+ return f"agent-output:{backend or 'unknown'}:{lineage}:{key}"
+
+
+def output_for_message(message_type: str, output: MessageOutput | None) -> MessageOutput:
+ """Return explicit semantics, preserving the legacy terminal-result contract."""
+
+ if output is not None:
+ return output
+ return MessageOutput(completes_turn=(message_type == "result"))
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index 5c2e3bf36..b559ecbac 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -300,6 +300,7 @@ def enqueue_session_callback(
message: str,
source_actor: str,
parent_run_id: Optional[str] = None,
+ output_id: Optional[str] = None,
) -> Optional["TaskExecutionRequest"]:
"""Enqueue a callback turn into an existing agent session — the shared entry used by Agent
Run / watch / scheduled-task callbacks and vault-request auto-resume. Resolves the session's
@@ -310,6 +311,13 @@ def enqueue_session_callback(
session_id = (session_id or "").strip()
if not session_id or not (message or "").strip():
return None
+ if parent_run_id:
+ existing = request_store.find_callback_run(
+ parent_run_id=parent_run_id,
+ source_actor=source_actor,
+ )
+ if existing is not None:
+ return TaskExecutionRequest.from_dict(existing)
target = resolve_session_id_target(session_id)
return request_store.enqueue_agent_run(
session_id=session_id,
@@ -324,6 +332,14 @@ def enqueue_session_callback(
source_kind="callback",
source_actor=source_actor,
parent_run_id=parent_run_id,
+ metadata={
+ key: value
+ for key, value in {
+ "callback_parent_run_id": parent_run_id,
+ "callback_output_id": output_id,
+ }.items()
+ if value is not None
+ },
)
@@ -1056,6 +1072,50 @@ class TaskExecutionStore:
]
return sorted(runs, key=lambda item: (item.get("completed_at") or "", item.get("id") or ""))[:limit]
+ def find_callback_run(
+ self,
+ *,
+ parent_run_id: str,
+ source_actor: str,
+ ) -> Optional[dict[str, Any]]:
+ if self._sqlite is not None:
+ return self._sqlite.find_callback_run(
+ parent_run_id=parent_run_id,
+ source_actor=source_actor,
+ )
+ for run in self._list_file_runs():
+ if (
+ run.get("request_type") == "agent_run"
+ and run.get("source_kind") == "callback"
+ and run.get("parent_run_id") == parent_run_id
+ and run.get("source_actor") == source_actor
+ ):
+ return run
+ return None
+
+ def settle_deferred_run(
+ self,
+ run_id: str,
+ *,
+ terminal_status: Optional[str] = None,
+ error: Optional[str] = None,
+ ) -> bool:
+ if self._sqlite is None:
+ return False
+ return self._sqlite.settle_deferred_run(
+ run_id,
+ terminal_status=terminal_status,
+ error=error,
+ )
+
+ def defer_run_terminal(self, run_id: str, *, terminal_status: str) -> bool:
+ if self._sqlite is None:
+ return False
+ return self._sqlite.defer_run_terminal(
+ run_id,
+ terminal_status=terminal_status,
+ )
+
def update_callback_status(
self,
run_id: str,
@@ -1740,6 +1800,84 @@ class ScheduledTaskService:
self.request_store.update_callback_status(run_id, status="sent", callback_run_id=callback_run.id)
self._drain_dirty = True
+ @staticmethod
+ def _structured_run_outputs(run: dict[str, Any]) -> list[dict[str, Any]]:
+ payload = run.get("result_payload")
+ outputs = payload.get("outputs") if isinstance(payload, dict) else None
+ if not isinstance(outputs, list):
+ return []
+ return [dict(item) for item in outputs if isinstance(item, dict)]
+
+ def forward_run_outputs(self, run_ids: list[str]) -> list[TaskExecutionRequest]:
+ """Forward every newly recorded output under the parent Run's callback policy."""
+
+ callbacks: list[TaskExecutionRequest] = []
+ for run_id in dict.fromkeys(str(value or "").strip() for value in run_ids):
+ if not run_id:
+ continue
+ run = self.request_store.get_run(run_id)
+ if not run or not str(run.get("callback_session_id") or "").strip():
+ continue
+ for output in self._structured_run_outputs(run):
+ output_id = str(output.get("id") or "").strip()
+ message = str(output.get("text") or "").strip()
+ if not output_id or not message:
+ continue
+ source_actor = f"{run_id}:output:{output_id}"
+ callback = enqueue_session_callback(
+ self.request_store,
+ session_id=str(run["callback_session_id"]),
+ message=message,
+ source_actor=source_actor,
+ parent_run_id=run_id,
+ output_id=output_id,
+ )
+ if callback is not None:
+ callbacks.append(callback)
+ self._drain_dirty = True
+ return callbacks
+
+ def settle_activity_runs(self, activity: Any) -> list[str]:
+ """Settle deferred Runs when a failed/stopped owned Activity is last."""
+
+ activity_status = str(getattr(activity, "status", "") or "").strip().lower()
+ if activity_status == "completed":
+ # A completed Claude task may still produce a user-visible follow-up;
+ # that Message owns Run settlement so output and callback stay aligned.
+ return []
+ terminal_status = "failed" if activity_status == "failed" else "canceled"
+ metadata = getattr(activity, "metadata", None) or {}
+ run_ids: list[str] = []
+ primary = str(getattr(activity, "run_id", "") or "").strip()
+ if primary:
+ run_ids.append(primary)
+ values = metadata.get("run_ids") if isinstance(metadata, dict) else None
+ if isinstance(values, list):
+ for value in values:
+ run_id = str(value or "").strip()
+ if run_id and run_id not in run_ids:
+ run_ids.append(run_id)
+
+ registry = getattr(getattr(self.controller, "agent_service", None), "activities", None)
+ has_blocker = getattr(registry, "has_blocking_run_activity", None)
+ settled: list[str] = []
+ for run_id in run_ids:
+ self.request_store.defer_run_terminal(
+ run_id,
+ terminal_status=terminal_status,
+ )
+ if callable(has_blocker) and has_blocker(run_id):
+ continue
+ error = f"Background Activity {getattr(activity, 'id', '')} {activity_status}"
+ if self.request_store.settle_deferred_run(
+ run_id,
+ error=error,
+ ):
+ settled.append(run_id)
+ if settled:
+ self._drain_dirty = True
+ return settled
+
async def _drain_vault_callbacks(self) -> None:
"""Auto-resume the requesting session when a vault request reaches a terminal state.
@@ -1811,6 +1949,23 @@ class ScheduledTaskService:
if not callback_session_id:
return None
run_id = str(run.get("id") or "")
+ output_callbacks = self.forward_run_outputs([run_id])
+ status = _normalize_requested_run_status(run.get("status")) or str(
+ run.get("status") or ""
+ )
+ if status in {"failed", "canceled"}:
+ terminal_message = self._fallback_callback_result(run, status=status)
+ terminal_callback = enqueue_session_callback(
+ self.request_store,
+ session_id=callback_session_id,
+ message=terminal_message,
+ source_actor=f"{run_id}:terminal:{status}",
+ parent_run_id=run_id or None,
+ )
+ if terminal_callback is not None:
+ return terminal_callback
+ if output_callbacks:
+ return output_callbacks[-1]
return enqueue_session_callback(
self.request_store,
session_id=callback_session_id,
diff --git a/core/session_activities.py b/core/session_activities.py
new file mode 100644
index 000000000..f372e72f2
--- /dev/null
+++ b/core/session_activities.py
@@ -0,0 +1,346 @@
+"""Backend-neutral, process-local Activity lifecycle registry.
+
+Activities are operational state: they answer what work is alive independently
+from foreground Turn ownership. Durable Messages and Harness Runs retain their
+own persistence aggregates.
+"""
+
+from __future__ import annotations
+
+import threading
+import time
+from collections import defaultdict, deque
+from dataclasses import dataclass, field, replace
+from datetime import datetime, timezone
+from typing import Any
+
+
+TERMINAL_ACTIVITY_STATUSES = frozenset({"completed", "failed", "stopped", "killed", "disconnected"})
+CONNECTION_STATES = frozenset({"connected", "reconnecting", "disconnected", "unknown"})
+
+
+def _now_iso() -> str:
+ return datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+@dataclass(frozen=True)
+class SessionActivity:
+ id: str
+ backend: str
+ runtime_key: str
+ session_id: str | None
+ kind: str
+ status: str = "running"
+ description: str | None = None
+ foreground: bool = False
+ detached_from_run: bool = False
+ parent_activity_id: str | None = None
+ turn_id: str | None = None
+ run_id: str | None = None
+ metadata: dict[str, Any] = field(default_factory=dict)
+ started_at: str = field(default_factory=_now_iso)
+ updated_at: str = field(default_factory=_now_iso)
+ completed_at: str | None = None
+
+ def to_dict(self) -> dict[str, Any]:
+ return {
+ "id": self.id,
+ "backend": self.backend,
+ "runtime_key": self.runtime_key,
+ "session_id": self.session_id,
+ "kind": self.kind,
+ "status": self.status,
+ "description": self.description,
+ "foreground": self.foreground,
+ "detached_from_run": self.detached_from_run,
+ "parent_activity_id": self.parent_activity_id,
+ "turn_id": self.turn_id,
+ "run_id": self.run_id,
+ "metadata": dict(self.metadata),
+ "started_at": self.started_at,
+ "updated_at": self.updated_at,
+ "completed_at": self.completed_at,
+ }
+
+
+class SessionActivityRegistry:
+ """One shared lifecycle owner for backend-native Activities."""
+
+ def __init__(self) -> None:
+ self._lock = threading.RLock()
+ self._active: dict[tuple[str, str, str], SessionActivity] = {}
+ self._connections: dict[tuple[str, str], tuple[str | None, str]] = {}
+ self._completed_outputs: dict[
+ tuple[str, str], deque[tuple[float, SessionActivity]]
+ ] = defaultdict(deque)
+
+ @staticmethod
+ def _key(backend: str, runtime_key: str, activity_id: str) -> tuple[str, str, str]:
+ return str(backend), str(runtime_key), str(activity_id)
+
+ def set_connection(
+ self,
+ *,
+ backend: str,
+ runtime_key: str,
+ session_id: str | None,
+ state: str,
+ ) -> None:
+ normalized = state if state in CONNECTION_STATES else "unknown"
+ with self._lock:
+ self._connections[(str(backend), str(runtime_key))] = (session_id, normalized)
+
+ def start(
+ self,
+ *,
+ backend: str,
+ runtime_key: str,
+ session_id: str | None,
+ activity_id: str,
+ kind: str,
+ description: str | None = None,
+ foreground: bool = False,
+ detached_from_run: bool = False,
+ parent_activity_id: str | None = None,
+ turn_id: str | None = None,
+ run_id: str | None = None,
+ metadata: dict[str, Any] | None = None,
+ ) -> SessionActivity:
+ key = self._key(backend, runtime_key, activity_id)
+ now = _now_iso()
+ with self._lock:
+ existing = self._active.get(key)
+ if existing is None:
+ activity = SessionActivity(
+ id=str(activity_id),
+ backend=str(backend),
+ runtime_key=str(runtime_key),
+ session_id=session_id,
+ kind=str(kind),
+ description=description,
+ foreground=foreground,
+ detached_from_run=detached_from_run,
+ parent_activity_id=parent_activity_id,
+ turn_id=turn_id,
+ run_id=run_id,
+ metadata=dict(metadata or {}),
+ started_at=now,
+ updated_at=now,
+ )
+ else:
+ merged = dict(existing.metadata)
+ merged.update(metadata or {})
+ activity = replace(
+ existing,
+ session_id=session_id or existing.session_id,
+ kind=str(kind or existing.kind),
+ status="running",
+ description=description or existing.description,
+ foreground=foreground,
+ detached_from_run=detached_from_run,
+ parent_activity_id=parent_activity_id or existing.parent_activity_id,
+ turn_id=turn_id or existing.turn_id,
+ run_id=run_id or existing.run_id,
+ metadata=merged,
+ updated_at=now,
+ completed_at=None,
+ )
+ self._active[key] = activity
+ return activity
+
+ def progress(
+ self,
+ *,
+ backend: str,
+ runtime_key: str,
+ session_id: str | None,
+ activity_id: str,
+ description: str | None = None,
+ metadata: dict[str, Any] | None = None,
+ ) -> SessionActivity:
+ key = self._key(backend, runtime_key, activity_id)
+ with self._lock:
+ existing = self._active.get(key)
+ return self.start(
+ backend=backend,
+ runtime_key=runtime_key,
+ session_id=session_id or (existing.session_id if existing else None),
+ activity_id=activity_id,
+ kind=existing.kind if existing else "background_task",
+ description=description or (existing.description if existing else None),
+ foreground=existing.foreground if existing else False,
+ detached_from_run=existing.detached_from_run if existing else False,
+ parent_activity_id=existing.parent_activity_id if existing else None,
+ turn_id=existing.turn_id if existing else None,
+ run_id=existing.run_id if existing else None,
+ metadata=metadata,
+ )
+
+ def complete(
+ self,
+ *,
+ backend: str,
+ runtime_key: str,
+ activity_id: str,
+ status: str,
+ metadata: dict[str, Any] | None = None,
+ expects_output: bool = False,
+ ) -> SessionActivity | None:
+ key = self._key(backend, runtime_key, activity_id)
+ normalized = status if status in TERMINAL_ACTIVITY_STATUSES else "completed"
+ now = _now_iso()
+ with self._lock:
+ existing = self._active.pop(key, None)
+ if existing is None:
+ return None
+ merged = dict(existing.metadata)
+ merged.update(metadata or {})
+ completed = replace(
+ existing,
+ status=normalized,
+ metadata=merged,
+ updated_at=now,
+ completed_at=now,
+ )
+ if expects_output:
+ self._completed_outputs[(str(backend), str(runtime_key))].append(
+ (time.monotonic(), completed)
+ )
+ return completed
+
+ def active_for_runtime(self, backend: str, runtime_key: str) -> list[SessionActivity]:
+ prefix = (str(backend), str(runtime_key))
+ with self._lock:
+ values = [
+ activity
+ for (item_backend, item_runtime, _), activity in self._active.items()
+ if (item_backend, item_runtime) == prefix
+ ]
+ return sorted(values, key=lambda item: (item.started_at, item.id))
+
+ def has_active(self, backend: str, runtime_key: str) -> bool:
+ return bool(self.active_for_runtime(backend, runtime_key))
+
+ def has_blocking_run_activity(self, run_id: str) -> bool:
+ """Whether a non-detached active Activity is owned by ``run_id``."""
+
+ identity = str(run_id or "").strip()
+ if not identity:
+ return False
+ with self._lock:
+ for activity in self._active.values():
+ run_ids = activity.metadata.get("run_ids")
+ owns_run = activity.run_id == identity or (
+ isinstance(run_ids, list) and identity in {str(item) for item in run_ids}
+ )
+ if owns_run and not activity.detached_from_run:
+ return True
+ return False
+
+ def claim_completed_output(
+ self,
+ backend: str,
+ runtime_key: str,
+ *,
+ max_age_seconds: float = 0,
+ ) -> SessionActivity | None:
+ key = (str(backend), str(runtime_key))
+ now = time.monotonic()
+ with self._lock:
+ queue = self._completed_outputs.get(key)
+ if not queue:
+ return None
+ while queue:
+ completed_at, activity = queue.popleft()
+ if max_age_seconds <= 0 or now - completed_at <= max_age_seconds:
+ if not queue:
+ self._completed_outputs.pop(key, None)
+ return activity
+ self._completed_outputs.pop(key, None)
+ return None
+
+ def requeue_completed_output(
+ self,
+ activity: SessionActivity,
+ *,
+ front: bool = True,
+ ) -> None:
+ """Restore a claimed completion when its causal output cannot be consumed yet."""
+
+ key = (str(activity.backend), str(activity.runtime_key))
+ item = (time.monotonic(), activity)
+ with self._lock:
+ queue = self._completed_outputs[key]
+ if front:
+ queue.appendleft(item)
+ else:
+ queue.append(item)
+
+ def has_completed_output(self, backend: str, runtime_key: str) -> bool:
+ """Whether a completed Activity is waiting for user-visible output."""
+
+ with self._lock:
+ return bool(self._completed_outputs.get((str(backend), str(runtime_key))))
+
+ def end_runtime(
+ self,
+ backend: str,
+ runtime_key: str,
+ *,
+ status: str = "disconnected",
+ ) -> list[SessionActivity]:
+ key = (str(backend), str(runtime_key))
+ with self._lock:
+ connection = self._connections.get(key)
+ active = [
+ activity
+ for (item_backend, item_runtime, _), activity in self._active.items()
+ if (item_backend, item_runtime) == key
+ ]
+ session_id = connection[0] if connection else None
+ if session_id is None:
+ session_id = next((item.session_id for item in active if item.session_id), None)
+ self._connections[key] = (
+ session_id,
+ status if status in CONNECTION_STATES else "disconnected",
+ )
+ active_ids = [activity.id for activity in active]
+ completed: list[SessionActivity] = []
+ for activity_id in active_ids:
+ activity = self.complete(
+ backend=backend,
+ runtime_key=runtime_key,
+ activity_id=activity_id,
+ status="disconnected",
+ )
+ if activity is not None:
+ completed.append(activity)
+ return completed
+
+ def session_state(self, session_id: str) -> dict[str, Any]:
+ with self._lock:
+ activities = sorted(
+ (
+ activity
+ for activity in self._active.values()
+ if activity.session_id == session_id and not activity.foreground
+ ),
+ key=lambda item: (item.started_at, item.id),
+ )
+ connection_states = [
+ state
+ for connection_session_id, state in self._connections.values()
+ if connection_session_id == session_id
+ ]
+ if "connected" in connection_states:
+ connection = "connected"
+ elif "reconnecting" in connection_states:
+ connection = "reconnecting"
+ elif connection_states and all(state == "disconnected" for state in connection_states):
+ connection = "disconnected"
+ else:
+ connection = "unknown"
+ return {
+ "background_activities": [activity.to_dict() for activity in activities],
+ "connection": connection,
+ }
diff --git a/core/session_turns.py b/core/session_turns.py
index 56831b13b..188a3c764 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -1017,9 +1017,7 @@ class SessionTurnManager:
return True
def turn_state(self, session_id: str) -> dict:
- """Whether a turn is currently RUNNING for the session. The fire-and-forget
- dispatch survives browser disconnects, so a freshly loaded / reconnected
- Chat page asks this to restore its working / Stop state (Codex P2)."""
+ """Compose orthogonal foreground, inbox, Activity, and connection facts."""
entry = self.in_flight.get(session_id)
active = entry is not None and not entry.task.done()
native_turn_started = False
@@ -1033,11 +1031,33 @@ class SessionTurnManager:
started = getattr(service, "runtime_turn_started", None)
if callable(started):
native_turn_started = started(entry.context) is True
+ pending_input_count = 0
+ try:
+ with self._sqlite_engine().begin() as conn:
+ pending_input_count = len(messages_service.list_queued(conn, session_id))
+ except Exception:
+ logger.debug("turn_state: failed to read queued input count", exc_info=True)
+ activity_state: dict[str, Any] = {
+ "background_activities": [],
+ "connection": "unknown",
+ }
+ service = getattr(self.controller, "agent_service", None) if self.controller is not None else None
+ registry = getattr(service, "activities", None)
+ project = getattr(registry, "session_state", None)
+ if callable(project):
+ try:
+ activity_state = project(session_id)
+ except Exception:
+ logger.debug("turn_state: failed to project Activity state", exc_info=True)
result = {
"ok": True,
"session_id": session_id,
"in_flight": active,
"native_turn_started": native_turn_started,
+ "foreground": "running" if active else "idle",
+ "pending_input_count": pending_input_count,
+ "background_activities": activity_state.get("background_activities", []),
+ "connection": activity_state.get("connection", "unknown"),
}
if backend:
result["backend"] = backend
diff --git a/docs/plans/full-duplex-sessions.md b/docs/plans/full-duplex-sessions.md
new file mode 100644
index 000000000..a0bc401fb
--- /dev/null
+++ b/docs/plans/full-duplex-sessions.md
@@ -0,0 +1,133 @@
+# Full-duplex Session implementation contract (#862)
+
+## Goal
+
+Make Session message flow independent from foreground execution ownership while
+preserving the existing `SessionTurnManager` as the single owner of foreground
+queueing, Stop, and completion.
+
+This change is a vertical slice across the shared dispatcher, backend activity
+reporting, Claude background-task output, and Harness Run callbacks. It does not
+introduce a global Session FSM or a new persistence aggregate.
+
+## Shared contracts
+
+### Message output
+
+`core.message_output.MessageOutput` accompanies an agent-visible output when its
+lifecycle differs from the compatibility default (`result` completes the current
+Turn):
+
+- `completes_turn`: whether this output is a terminal foreground signal;
+- `completes_run`: optional independent Run terminal signal (defaults to the
+ legacy `completes_turn` behavior);
+- `detached`: whether it is legitimate output from work whose foreground Turn is
+ already over; detached output can be delivered but cannot mutate another Turn;
+- `idempotency_key`: stable producer identity for delivery/persistence dedup;
+- `activity_id`, `causation_id`, and `sequence`: hidden provenance.
+
+The dispatcher makes delivery and lifecycle decisions separately. A detached
+output follows normal cleaning, persistence, delivery, and Session fan-out, but
+does not settle the dot, stream sink, runtime gate, processing indicator, status
+bubble, or a newer Turn. It may still settle its originating Run when
+`completes_run=True` and no non-detached owned Activity remains active.
+
+Existing callers remain compatible: an ordinary `result` still completes its
+current Turn. A backend can emit multiple result-shaped output Messages by using
+`completes_turn=False` for intermediate outputs and one terminal output.
+
+### Activity registry
+
+`core.session_activities.SessionActivityRegistry` is process-local operational
+state, not a new durable domain table. Backends report independently identified
+Activity start/progress/terminal events and connection changes. The registry
+projects, without a cross-product enum:
+
+- active background Activities;
+- backend connection state;
+- completed Activities waiting for a producer-owned follow-up output.
+
+`SessionTurnManager.turn_state()` composes this with its existing foreground
+state and the durable queued-message count. Existing response fields remain
+unchanged.
+
+### Run outputs and callbacks
+
+The existing `agent_runs.result_payload_json` stores an idempotent output ledger:
+
+```json
+{
+ "outputs": [
+ {
+ "id": "producer-stable-id",
+ "text": "clean user-visible output",
+ "message_id": "optional delivery id",
+ "sequence": 1,
+ "provenance": {"activity_id": "...", "run_id": "..."}
+ }
+ ]
+}
+```
+
+No visible wrapper text is added. Each new output can enqueue one callback turn
+immediately. Callback turns are deduplicated by structured Run lineage. Parent
+`callback_status` stays pending while the parent Run is active and settles once
+after the parent reaches its one idempotent terminal transition.
+
+If a Run fails or is canceled after forwarding partial outputs, its callback
+Session receives one additional terminal failure/cancellation Message. A
+successful Run with streamed outputs does not repeat them in a synthetic final
+summary.
+
+A terminal Run intent is retained in `result_payload_json` while a non-detached
+owned Activity remains active. A later Activity output can complete that Run
+without acquiring lifecycle authority over whichever foreground Turn is current.
+
+## Claude mapping
+
+Claude task frames map into the shared Activity registry:
+
+- `task_started`: start/upsert by `task_id`;
+- `task_progress`: refresh by `task_id`;
+- terminal `task_notification` or `task_updated`: complete exactly that Activity
+ for `completed`, `failed`, `stopped`, or `killed`.
+
+Typed SDK frames are used where available; raw `SystemMessage.subtype/data` is
+the forward-compatible fallback. A foreground `ResultMessage` does not clear
+active background Activities. When a completed Activity produces a later
+assistant/result sequence while another user Turn owns the runtime gate, Claude
+delivers only the final user-facing result as a detached Message output. The
+newer user Turn remains untouched.
+
+The Claude stream does not expose a reliable query/result correlation id. Avibe
+therefore accepts the next Session input normally but serializes that native
+query while a background Activity or its undelivered completion can still
+produce output. This is backend execution admission, not Session message
+admission. A terminal-only task notification is delivered after a bounded grace
+period; a timed flush never consumes Activity provenance from underneath a
+newer pending native request. Queued completions also survive runtime disconnect
+inside the process so a late flush can still deliver and settle their origin Run.
+
+## Compatibility and non-goals
+
+- No schema migration: Message provenance uses existing `metadata_json`; the Run
+ ledger uses existing `result_payload_json`.
+- No new Session enum and no replacement of `SessionTurnManager`.
+- No concurrent-inference requirement. Existing queueing remains the fallback.
+- No automatic user visibility for backend progress/tool frames.
+- Codex and OpenCode inherit the shared output and Activity APIs; they need no
+ adapter-specific Activity mapping until their native protocols expose such
+ work.
+
+## Acceptance evidence
+
+- `MESSAGE-DELIVERY-003`: Claude background completion is delivered while a
+ newer Turn remains active.
+- `MESSAGE-DELIVERY-004`: one Turn emits multiple output Messages and completes
+ once.
+- `MESSAGE-DELIVERY-005`: one Run forwards multiple callback outputs and reaches
+ one idempotent terminal transition.
+
+Focused unit/contract tests cover Activity transitions, state-axis projection,
+structured provenance, dedup, terminal isolation, and existing one-result
+compatibility across shared dispatcher paths.
diff --git a/modules/agents/base.py b/modules/agents/base.py
index 726b94546..3accee0a6 100644
--- a/modules/agents/base.py
+++ b/modules/agents/base.py
@@ -11,6 +11,7 @@ from typing import Any, Dict, List, Optional
from modules.im import MessageContext
from modules.im.base import FileAttachment
+from core.message_output import MessageOutput
from core.reply_enhancer import strip_silent_blocks
logger = logging.getLogger(__name__)
@@ -56,6 +57,8 @@ class AgentRequest:
# returns False so Workbench can distinguish a stale missing runtime from an
# interrupt refusal/failure.
stop_failure_reason: Optional[str] = None
+ # Optional output semantics for backend-initiated or multi-output turns.
+ output: Optional[MessageOutput] = None
@dataclass
@@ -462,7 +465,11 @@ class BaseAgent(ABC):
parse_mode: str = "markdown",
suffix: Optional[str] = None,
request: Optional[AgentRequest] = None,
+ output: MessageOutput | None = None,
) -> None:
+ if output is None and request is not None:
+ output = request.output
+ settles_request = output is None or (output.completes_turn and not output.detached)
# An error result subtype (e.g. Claude's ``error_max_turns`` /
# ``error_during_execution``) is a FAILED turn. Carry that on the terminal
# ``result`` emit via ``is_error`` so the outbound chokepoint flips the dot
@@ -480,8 +487,15 @@ class BaseAgent(ABC):
has_silent_directive = "<silent" in raw_result.lower() or "<silent" in raw_suffix.lower()
if has_silent_directive and not visible_result.strip() and not (visible_suffix or "").strip():
- await self.controller.emit_agent_message(context, "result", "", parse_mode=parse_mode, is_error=is_error)
- if request:
+ await self.controller.emit_agent_message(
+ context,
+ "result",
+ "",
+ parse_mode=parse_mode,
+ is_error=is_error,
+ **({"output": output} if output is not None else {}),
+ )
+ if request and settles_request:
await self._remove_ack_reaction(request)
return
@@ -495,14 +509,28 @@ class BaseAgent(ABC):
parts.append(visible_suffix)
if parts:
formatted = "\n".join(parts)
- await self.controller.emit_agent_message(context, "result", formatted, parse_mode=parse_mode, is_error=is_error)
+ await self.controller.emit_agent_message(
+ context,
+ "result",
+ formatted,
+ parse_mode=parse_mode,
+ is_error=is_error,
+ **({"output": output} if output is not None else {}),
+ )
else:
# No visible text (show_duration off + empty result/suffix) is still
# a TERMINAL turn: settle it through the OUTBOUND status chokepoint
# (empty result → dot idle / failed AND releases the web-Chat stream
# waiter), mirroring the silent-directive path above — otherwise the
# dot stays green and the stream hangs until the 600s timeout (Codex P2).
- await self.controller.emit_agent_message(context, "result", "", parse_mode=parse_mode, is_error=is_error)
+ await self.controller.emit_agent_message(
+ context,
+ "result",
+ "",
+ parse_mode=parse_mode,
+ is_error=is_error,
+ **({"output": output} if output is not None else {}),
+ )
else:
token_field = ""
get_token_field = getattr(self.controller, "session_token_field", None)
@@ -541,10 +569,11 @@ class BaseAgent(ABC):
parse_mode=parse_mode,
is_error=is_error,
result_footer=result_footer,
+ **({"output": output} if output is not None else {}),
)
# Remove ack reaction after result is sent
- if request:
+ if request and settles_request:
await self._remove_ack_reaction(request)
@abstractmethod
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 13ba2b2ba..82d00fcf8 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -1,9 +1,12 @@
import asyncio
import logging
import os
+import uuid
from typing import Callable, Optional
from core.agent_auth_service import classify_auth_error
+from core.message_output import MessageOutput
+from core.session_activities import SessionActivity
from modules.claude_sdk_compat import TextBlock, ToolUseBlock, is_claude_sdk_buffer_error
from modules.agents.claude_process_reaper import (
AVIBE_CLAUDE_SESSION_OWNER,
@@ -31,6 +34,9 @@ class ClaudeAgent(BaseAgent):
"""Existing Claude Code integration extracted into an agent backend."""
name = "claude"
+ # Preserve the usual task-notification -> assistant/result association while
+ # bounding terminal-only notifications on the otherwise long-lived stream.
+ ACTIVITY_OUTPUT_FLUSH_GRACE_SECONDS = 30.0
# AskUserQuestion support is disabled - SDK cannot respond programmatically
# Set to True when SDK adds support (see issue #10168)
@@ -53,6 +59,12 @@ class ClaudeAgent(BaseAgent):
# the list shape remains for defensive cleanup of older queued state.
self._pending_reactions: dict[str, list[tuple[str, str]]] = {}
self._pending_requests: dict[str, list[AgentRequest]] = {}
+ self._detached_activity_outputs: dict[str, SessionActivity] = {}
+ self._detached_assistant_text: dict[str, str] = {}
+ self._detached_unsolicited_outputs: set[str] = set()
+ self._detached_unsolicited_text: dict[str, str] = {}
+ self._activity_flush_tasks: dict[str, asyncio.Task] = {}
+ self._activity_settle_events: dict[str, asyncio.Event] = {}
# Question handler for AskUserQuestion support (disabled)
# NOTE: Uncomment when SDK adds AskUserQuestion support
@@ -104,6 +116,13 @@ class ClaudeAgent(BaseAgent):
if callable(mark_session_active):
mark_session_active(runtime_session_key)
+ # Claude does not expose a reliable query/result correlation id. If a
+ # native background Activity can still speak, serialize this accepted
+ # Inbox item until that output is delivered. The Session remains full
+ # duplex while this backend avoids attributing a background Result to
+ # the new user Turn.
+ await self._wait_for_activity_output(runtime_session_key)
+
# Queue reaction BEFORE sending query to avoid race condition where
# a fast result arrives before the reaction is queued
if request.ack_reaction_message_id and request.ack_reaction_emoji:
@@ -518,6 +537,7 @@ class ClaudeAgent(BaseAgent):
try:
session_key = self.controller._get_session_key(context)
composite_key = composite_key or f"{base_session_id}:{working_path}"
+ self._set_activity_connection(composite_key, context, "connected")
# Build a request object for question handler
request = AgentRequest(
@@ -553,6 +573,15 @@ class ClaudeAgent(BaseAgent):
)
logger.info(f"Captured Claude session id {claude_session_id} for {base_session_id}")
+ if self._handle_activity_message(message, composite_key, context):
+ registry = self._activity_registry()
+ if registry is not None and registry.has_completed_output(
+ self.name,
+ composite_key,
+ ):
+ self._schedule_completed_activity_flush(composite_key, context)
+ continue
+
if self.claude_client._is_skip_message(message):
continue
@@ -573,13 +602,15 @@ class ClaudeAgent(BaseAgent):
# active-turn guard. An actionable refusal-fallback frame is
# the one user-facing system exception: it belongs to the
# replacement run and must use that run's turn.
+ output_mode = None
if message_type in ("assistant", "result") or model_refusal_fallback_notice is not None:
- await self._maybe_begin_agent_initiated_turn(
+ output_mode = await self._maybe_begin_agent_initiated_turn(
context,
composite_key,
base_session_id,
working_path,
session_key,
+ message_type=message_type,
)
if message_type == "assistant":
@@ -625,6 +656,14 @@ class ClaudeAgent(BaseAgent):
auth_failure_assistant = self._is_auth_failure_assistant_message(message)
assistant_text = self._extract_text_blocks(message, context)
+ if output_mode == "detached":
+ if assistant_text:
+ self._detached_unsolicited_text[composite_key] = assistant_text
+ continue
+ if composite_key in self._detached_activity_outputs:
+ if assistant_text:
+ self._detached_assistant_text[composite_key] = assistant_text
+ continue
auth_failure_text = assistant_text or "OAuth authentication failed."
if await self._handle_auth_failure_result(
context,
@@ -747,8 +786,52 @@ class ClaudeAgent(BaseAgent):
continue
if message_type == "result":
- self._pending_assistant_message.pop(composite_key, None)
result_text = getattr(message, "result", None)
+ detached_activity = self._detached_activity_outputs.pop(composite_key, None)
+ if detached_activity is not None:
+ if not result_text:
+ result_text = self._detached_assistant_text.get(composite_key)
+ self._detached_assistant_text.pop(composite_key, None)
+ try:
+ await self.emit_result_message(
+ context,
+ result_text,
+ subtype=getattr(message, "subtype", "") or "",
+ duration_ms=getattr(message, "duration_ms", 0),
+ parse_mode="markdown",
+ output=self._activity_message_output(
+ detached_activity,
+ detached=True,
+ completes_turn=False,
+ ),
+ )
+ except Exception:
+ registry = self._activity_registry()
+ if registry is not None:
+ registry.requeue_completed_output(detached_activity)
+ raise
+ # The detached Activity output has no authority over
+ # a newer pending request. Its Turn stays owned by its
+ # own backend query and liveness/timeout path.
+ self._mark_session_idle_if_runtime_free(composite_key)
+ self._signal_activity_output_settled(composite_key)
+ continue
+ if output_mode == "detached":
+ if not result_text:
+ result_text = self._detached_unsolicited_text.get(composite_key)
+ self._detached_unsolicited_text.pop(composite_key, None)
+ self._detached_unsolicited_outputs.discard(composite_key)
+ if result_text:
+ await self.emit_result_message(
+ context,
+ result_text,
+ subtype=getattr(message, "subtype", "") or "",
+ duration_ms=getattr(message, "duration_ms", 0),
+ parse_mode="markdown",
+ output=self._unsolicited_message_output(message),
+ )
+ continue
+ self._pending_assistant_message.pop(composite_key, None)
if self._consume_suppressed_synthetic_result(composite_key, message, result_text):
self._last_assistant_text.pop(composite_key, None)
continue
@@ -852,6 +935,9 @@ class ClaudeAgent(BaseAgent):
except Exception as e:
logger.error(f"Error processing message from Claude: {e}", exc_info=True)
continue
+ await self._flush_completed_activity_outputs(composite_key, context)
+ await self._flush_detached_activity_output(composite_key, context)
+ await self._flush_detached_unsolicited_output(composite_key, context)
await self._handle_receiver_eof(composite_key, context)
except asyncio.CancelledError:
# Receiver task was explicitly cancelled (e.g. /stop, /clear,
@@ -924,6 +1010,16 @@ class ClaudeAgent(BaseAgent):
# inside the loop.
finally:
self._suppressed_synthetic_results.discard(composite_key)
+ detached_activity = self._detached_activity_outputs.pop(composite_key, None)
+ if detached_activity is not None:
+ registry = self._activity_registry()
+ if registry is not None:
+ registry.requeue_completed_output(detached_activity)
+ self._schedule_completed_activity_flush(composite_key, context)
+ self._detached_assistant_text.pop(composite_key, None)
+ self._detached_unsolicited_outputs.discard(composite_key)
+ self._detached_unsolicited_text.pop(composite_key, None)
+ self._end_activity_runtime(composite_key)
async def _handle_receiver_eof(self, composite_key: str, context: MessageContext) -> None:
"""Settle a Claude receiver that ended without a ResultMessage."""
@@ -1112,6 +1208,474 @@ class ClaudeAgent(BaseAgent):
def _has_pending_requests(self, composite_key: str) -> bool:
return bool(self._pending_requests.get(composite_key))
+ def _activity_registry(self):
+ service = getattr(self.controller, "agent_service", None)
+ return getattr(service, "activities", None)
+
+ def _activity_output_pending(self, composite_key: str) -> bool:
+ registry = self._activity_registry()
+ return bool(
+ composite_key in self._detached_activity_outputs
+ or (
+ registry is not None
+ and (
+ registry.has_active(self.name, composite_key)
+ or registry.has_completed_output(self.name, composite_key)
+ )
+ )
+ )
+
+ async def _wait_for_activity_output(self, composite_key: str) -> None:
+ """Serialize Claude inference until native background output is consumed."""
+
+ while self._activity_output_pending(composite_key):
+ event = self._activity_settle_events.setdefault(composite_key, asyncio.Event())
+ if not self._activity_output_pending(composite_key):
+ self._signal_activity_output_settled(composite_key)
+ return
+ await event.wait()
+
+ def _signal_activity_output_settled(self, composite_key: str) -> None:
+ if self._activity_output_pending(composite_key):
+ return
+ event = self._activity_settle_events.pop(composite_key, None)
+ if event is not None:
+ event.set()
+
+ @staticmethod
+ def _activity_session_id(context: MessageContext) -> str | None:
+ value = (getattr(context, "platform_specific", None) or {}).get("agent_session_id")
+ return str(value or "").strip() or None
+
+ def _set_activity_connection(
+ self,
+ composite_key: str,
+ context: MessageContext,
+ state: str,
+ ) -> None:
+ registry = self._activity_registry()
+ if registry is None:
+ return
+ registry.set_connection(
+ backend=self.name,
+ runtime_key=composite_key,
+ session_id=self._activity_session_id(context),
+ state=state,
+ )
+
+ def _end_activity_runtime(self, composite_key: str) -> None:
+ service = getattr(self.controller, "agent_service", None)
+ end_runtime = getattr(service, "end_activity_runtime", None)
+ completed = []
+ if callable(end_runtime) and composite_key:
+ completed = end_runtime(self.name, composite_key) or []
+ if completed:
+ self._mark_session_idle_if_runtime_free(composite_key)
+ self._signal_activity_output_settled(composite_key)
+
+ @staticmethod
+ def _task_field(message, name: str, default=None):
+ value = getattr(message, name, None)
+ if value is not None:
+ return value
+ data = getattr(message, "data", None)
+ return data.get(name, default) if isinstance(data, dict) else default
+
+ def _current_turn_id(
+ self,
+ composite_key: str,
+ context: MessageContext,
+ ) -> str | None:
+ pending = self._pending_requests.get(composite_key) or []
+ source = getattr(pending[0], "context", None) if pending else context
+ value = (getattr(source, "platform_specific", None) or {}).get(AGENT_TURN_TOKEN)
+ return str(value or "").strip() or None
+
+ def _activity_run_ids(
+ self,
+ composite_key: str,
+ context: MessageContext,
+ ) -> list[str]:
+ pending = self._pending_requests.get(composite_key) or []
+ source = getattr(pending[0], "context", None) if pending else context
+ spec = getattr(source, "platform_specific", None) or {}
+ if spec.get("task_trigger_kind") != "agent_run":
+ return []
+ run_ids: list[str] = []
+ primary = str(spec.get("task_execution_id") or "").strip()
+ if primary:
+ run_ids.append(primary)
+ coalesced = spec.get("coalesced_queue")
+ values = coalesced.get("execution_ids") if isinstance(coalesced, dict) else None
+ if isinstance(values, list):
+ for value in values:
+ run_id = str(value or "").strip()
+ if run_id and run_id not in run_ids:
+ run_ids.append(run_id)
+ return run_ids
+
+ def _handle_activity_message(
+ self,
+ message,
+ composite_key: str,
+ context: MessageContext,
+ ) -> bool:
+ """Project Claude task events into the backend-neutral Activity registry."""
+
+ subtype = str(getattr(message, "subtype", "") or "").strip().lower()
+ class_name = getattr(getattr(message, "__class__", None), "__name__", "")
+ event = {
+ "TaskStartedMessage": "task_started",
+ "TaskProgressMessage": "task_progress",
+ "TaskNotificationMessage": "task_notification",
+ "TaskUpdatedMessage": "task_updated",
+ }.get(class_name, subtype)
+ if event not in {"task_started", "task_progress", "task_notification", "task_updated"}:
+ return False
+
+ task_id = str(self._task_field(message, "task_id", "") or "").strip()
+ if not task_id:
+ logger.warning("Ignoring Claude %s without task_id for %s", event, composite_key)
+ return True
+ registry = self._activity_registry()
+ if registry is None:
+ return True
+
+ existing_activity = next(
+ (
+ activity
+ for activity in registry.active_for_runtime(self.name, composite_key)
+ if activity.id == task_id
+ ),
+ None,
+ )
+
+ session_id = self._activity_session_id(context)
+ 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()
+ metadata = {
+ key: value
+ for key, value in {
+ "task_type": task_type or None,
+ "last_tool_name": self._task_field(message, "last_tool_name"),
+ "output_file": self._task_field(message, "output_file"),
+ "summary": self._task_field(message, "summary"),
+ }.items()
+ if value not in (None, "")
+ }
+ if existing_activity is None:
+ run_ids = self._activity_run_ids(composite_key, context)
+ turn_id = self._current_turn_id(composite_key, context)
+ else:
+ run_ids = []
+ if existing_activity.run_id:
+ run_ids.append(existing_activity.run_id)
+ existing_run_ids = existing_activity.metadata.get("run_ids")
+ if isinstance(existing_run_ids, list):
+ for value in existing_run_ids:
+ run_id = str(value or "").strip()
+ if run_id and run_id not in run_ids:
+ run_ids.append(run_id)
+ turn_id = existing_activity.turn_id
+ if run_ids:
+ metadata["run_ids"] = run_ids
+ if event == "task_started":
+ registry.start(
+ backend=self.name,
+ runtime_key=composite_key,
+ session_id=session_id,
+ activity_id=task_id,
+ kind=task_type or "background_task",
+ description=description,
+ parent_activity_id=tool_use_id or None,
+ turn_id=turn_id,
+ run_id=run_ids[0] if run_ids else None,
+ metadata=metadata,
+ )
+ mark_active = getattr(self.session_handler, "mark_session_active", None)
+ if callable(mark_active):
+ mark_active(composite_key)
+ return True
+
+ status = str(self._task_field(message, "status", "") or "").strip().lower()
+ terminal = status in {"completed", "failed", "stopped", "killed"}
+ if event in {"task_progress", "task_updated"} and not terminal:
+ registry.progress(
+ backend=self.name,
+ runtime_key=composite_key,
+ session_id=session_id,
+ activity_id=task_id,
+ description=description,
+ metadata=metadata,
+ )
+ mark_active = getattr(self.session_handler, "mark_session_active", None)
+ if callable(mark_active):
+ mark_active(composite_key)
+ return True
+ if not terminal:
+ logger.warning("Ignoring Claude %s with non-terminal status %r", event, status)
+ return True
+
+ if existing_activity is None:
+ registry.start(
+ backend=self.name,
+ runtime_key=composite_key,
+ session_id=session_id,
+ activity_id=task_id,
+ kind=task_type or "background_task",
+ description=description,
+ parent_activity_id=tool_use_id or None,
+ turn_id=turn_id,
+ run_id=run_ids[0] if run_ids else None,
+ metadata=metadata,
+ )
+ completed = registry.complete(
+ backend=self.name,
+ runtime_key=composite_key,
+ activity_id=task_id,
+ status=status,
+ metadata=metadata,
+ expects_output=status == "completed",
+ )
+ service = getattr(self.controller, "agent_service", None)
+ on_terminal = getattr(service, "on_activity_terminal", None)
+ if completed is not None and callable(on_terminal):
+ on_terminal(completed)
+ if status != "completed":
+ self._mark_session_idle_if_runtime_free(composite_key)
+ self._signal_activity_output_settled(composite_key)
+ return True
+
+ @staticmethod
+ def _activity_message_output(
+ activity: SessionActivity,
+ *,
+ detached: bool,
+ completes_turn: bool,
+ ) -> MessageOutput:
+ return MessageOutput(
+ completes_turn=completes_turn,
+ completes_run=True,
+ detached=detached,
+ idempotency_key=(
+ f"claude-task:{activity.runtime_key}:{activity.id}:completion"
+ ),
+ activity_id=activity.id,
+ causation_id=activity.parent_activity_id,
+ sequence=1,
+ run_id=activity.run_id,
+ metadata={
+ "activity_kind": activity.kind,
+ "activity_status": activity.status,
+ "backend": activity.backend,
+ "run_ids": activity.metadata.get("run_ids"),
+ "turn_id": activity.turn_id,
+ },
+ )
+
+ @staticmethod
+ def _unsolicited_message_output(message) -> MessageOutput:
+ native_id = str(
+ getattr(message, "uuid", "")
+ or getattr(message, "message_id", "")
+ or ""
+ ).strip()
+ identity = native_id
+ if not identity:
+ session_id = str(getattr(message, "session_id", "") or "").strip()
+ num_turns = getattr(message, "num_turns", None)
+ if session_id and num_turns is not None:
+ frame_identity = ":".join(
+ [
+ session_id,
+ str(num_turns),
+ str(getattr(message, "duration_ms", "")),
+ str(getattr(message, "duration_api_ms", "")),
+ str(getattr(message, "subtype", "")),
+ ]
+ )
+ identity = uuid.uuid5(uuid.NAMESPACE_OID, frame_identity).hex
+ else:
+ # Older SDK frames expose no stable identity. Allocate one once
+ # for this MessageOutput instead of deduplicating by visible text.
+ identity = uuid.uuid4().hex
+ return MessageOutput(
+ completes_turn=False,
+ completes_run=False,
+ detached=True,
+ idempotency_key=f"claude-unsolicited:{identity}",
+ causation_id=native_id or None,
+ metadata={"backend": "claude", "source": "agent_initiated"},
+ )
+
+ async def _flush_detached_unsolicited_output(
+ self,
+ composite_key: str,
+ context: MessageContext,
+ ) -> None:
+ if composite_key not in self._detached_unsolicited_outputs:
+ return
+ text = self._detached_unsolicited_text.pop(composite_key, "").strip()
+ self._detached_unsolicited_outputs.discard(composite_key)
+ if not text:
+ return
+ await self.emit_result_message(
+ context,
+ text,
+ parse_mode="markdown",
+ output=self._unsolicited_message_output(None),
+ )
+
+ async def _flush_detached_activity_output(
+ self,
+ composite_key: str,
+ context: MessageContext,
+ ) -> None:
+ activity = self._detached_activity_outputs.pop(composite_key, None)
+ if activity is None:
+ return
+ text = self._detached_assistant_text.pop(composite_key, "").strip()
+ if not text:
+ text = str(activity.metadata.get("summary") or "").strip()
+ try:
+ await self.emit_result_message(
+ context,
+ text,
+ parse_mode="markdown",
+ output=self._activity_message_output(
+ activity,
+ detached=True,
+ completes_turn=False,
+ ),
+ )
+ except Exception:
+ registry = self._activity_registry()
+ if registry is not None:
+ registry.requeue_completed_output(activity)
+ raise
+ self._mark_session_idle_if_runtime_free(composite_key)
+ self._signal_activity_output_settled(composite_key)
+
+ async def _flush_completed_activity_outputs(
+ self,
+ composite_key: str,
+ context: MessageContext,
+ ) -> bool:
+ """Deliver task notifications that ended the receiver without a Result."""
+
+ registry = self._activity_registry()
+ if registry is None:
+ return False
+ while True:
+ activity = registry.claim_completed_output(self.name, composite_key)
+ if activity is None:
+ return False
+ pending = self._pending_requests.get(composite_key) or []
+ pending_request = pending[0] if pending else None
+ pending_turn_id = str(
+ (
+ getattr(
+ getattr(pending_request, "context", None),
+ "platform_specific",
+ None,
+ )
+ or {}
+ ).get(AGENT_TURN_TOKEN)
+ or ""
+ ).strip()
+ same_turn = bool(
+ pending_request is not None
+ and activity.turn_id
+ and activity.turn_id == pending_turn_id
+ )
+ if pending_request is not None and not same_turn:
+ # A timed summary flush cannot consume the only correlation for
+ # an Activity whose real assistant/result sequence may still be
+ # in flight. Leave it for the receiver so that later output is
+ # detached from, and cannot complete, this newer Turn.
+ registry.requeue_completed_output(activity)
+ return True
+ result_text = str(activity.metadata.get("summary") or "").strip()
+ if same_turn:
+ matched_request = self._pop_pending_request(composite_key)
+ self._adopt_pending_turn_token(context, matched_request)
+ try:
+ await self.emit_result_message(
+ context,
+ result_text,
+ parse_mode="markdown",
+ request=matched_request,
+ output=self._activity_message_output(
+ activity,
+ detached=False,
+ completes_turn=True,
+ ),
+ )
+ except Exception:
+ registry.requeue_completed_output(activity)
+ raise
+ finally:
+ await self._remove_result_pending_reaction(
+ composite_key,
+ context,
+ matched_request,
+ )
+ self._last_assistant_text.pop(composite_key, None)
+ self._pending_assistant_message.pop(composite_key, None)
+ self._mark_session_idle_if_no_pending_requests(composite_key)
+ self._signal_activity_output_settled(composite_key)
+ continue
+
+ try:
+ await self.emit_result_message(
+ context,
+ result_text,
+ parse_mode="markdown",
+ output=self._activity_message_output(
+ activity,
+ detached=True,
+ completes_turn=False,
+ ),
+ )
+ except Exception:
+ registry.requeue_completed_output(activity)
+ raise
+ self._mark_session_idle_if_runtime_free(composite_key)
+ self._signal_activity_output_settled(composite_key)
+
+ def _schedule_completed_activity_flush(
+ self,
+ composite_key: str,
+ context: MessageContext,
+ ) -> None:
+ existing = self._activity_flush_tasks.get(composite_key)
+ if existing is not None and not existing.done():
+ return
+
+ async def _flush_after_grace() -> None:
+ retry = False
+ try:
+ await asyncio.sleep(self.ACTIVITY_OUTPUT_FLUSH_GRACE_SECONDS)
+ retry = await self._flush_completed_activity_outputs(composite_key, context)
+ except asyncio.CancelledError:
+ raise
+ except Exception:
+ retry = True
+ logger.warning(
+ "Failed to flush completed Claude Activities for %s",
+ composite_key,
+ exc_info=True,
+ )
+ finally:
+ if self._activity_flush_tasks.get(composite_key) is task:
+ self._activity_flush_tasks.pop(composite_key, None)
+ if retry:
+ self._schedule_completed_activity_flush(composite_key, context)
+
+ task = asyncio.create_task(_flush_after_grace())
+ self._activity_flush_tasks[composite_key] = task
+
async def _maybe_begin_agent_initiated_turn(
self,
context: MessageContext,
@@ -1119,7 +1683,9 @@ class ClaudeAgent(BaseAgent):
base_session_id: str,
working_path: str,
session_key: str,
- ) -> None:
+ *,
+ message_type: str | None = None,
+ ) -> str | None:
"""Open a turn for UNSOLICITED backend output (no Avibe query behind it).
Claude Code re-invokes the agent loop inside this same SDK process when a
@@ -1130,18 +1696,17 @@ class ClaudeAgent(BaseAgent):
outbound active-turn guard would drop the whole reply — it would never be
persisted, delivered, or pushed.
- When output arrives with NO pending request, open an agent-initiated turn
- and synthesize a pending ``AgentRequest`` for it. The existing
- assistant/result handlers then treat it exactly like a normal turn (token
- adoption keeps the gate token live across the assistant→result sequence,
- the result pops the synthetic request and the dispatcher's result
- ``finally`` releases the gate, and an EOF/error/cancel settles it through
- the same paths). No-op when a turn is already in flight for this session
- (a real user turn, or an agent-initiated turn already opened for an
- earlier message of this same run).
+ A completed Activity carries its origin Turn. If that Turn is still
+ current, attach provenance to its request. If a newer user Turn owns the
+ runtime, preserve the Activity output as detached Session delivery and do
+ not pop or settle that request. With no pending request, open an
+ agent-initiated Turn and synthesize a pending ``AgentRequest`` so the
+ existing result path retains its normal lifecycle behavior.
"""
- if self._has_pending_requests(composite_key):
- return
+ if composite_key in self._detached_activity_outputs:
+ return "activity"
+ if composite_key in self._detached_unsolicited_outputs:
+ return "detached"
# A malformed-tool-use synthetic API error pops the turn's real pending
# request and arms ``_suppressed_synthetic_results`` for the PAIRED
# ResultMessage, which the result branch then skips (``continue``) with NO
@@ -1153,28 +1718,67 @@ class ClaudeAgent(BaseAgent):
# ``_consume_suppressed_synthetic_result`` / cleanup, so real later turns
# open normally.
if composite_key in self._suppressed_synthetic_results:
- return
+ return None
+ registry = self._activity_registry()
+ completed_activity = (
+ registry.claim_completed_output(self.name, composite_key)
+ if registry is not None
+ else None
+ )
+ if completed_activity is not None and self._has_pending_requests(composite_key):
+ pending_request = self._pending_requests[composite_key][0]
+ pending_turn_id = str(
+ (
+ getattr(
+ getattr(pending_request, "context", None),
+ "platform_specific",
+ None,
+ )
+ or {}
+ ).get(AGENT_TURN_TOKEN)
+ or ""
+ ).strip()
+ if completed_activity.turn_id and completed_activity.turn_id == pending_turn_id:
+ pending_request.output = self._activity_message_output(
+ completed_activity,
+ detached=False,
+ completes_turn=True,
+ )
+ return None
+ self._detached_activity_outputs[composite_key] = completed_activity
+ logger.info(
+ "Claude Activity %s output detached from the current user turn in %s",
+ completed_activity.id,
+ composite_key,
+ )
+ return "activity"
+ if self._has_pending_requests(composite_key):
+ return None
service = getattr(self.controller, "agent_service", None)
begin = getattr(service, "begin_agent_initiated_turn", None)
if not callable(begin):
- return
+ return None
payload = getattr(context, "platform_specific", None) or {}
runtime_key = str(payload.get(AGENT_RUNTIME_TURN_KEY) or "").strip() or composite_key
token = await begin(self.name, context, runtime_key)
if not token:
# The gate is CONTENDED — a user turn holds it, or one is queued on it
# and we must not block the receiver behind that waiter (deadlock; see
- # begin_agent_initiated_turn). If a turn actually holds the gate the
- # output rides that turn's machinery; in the narrow free-but-queued
- # window the outbound guard drops it. Log so that (rare, sub-tick) loss
- # is visible instead of silent — full preservation across a queued user
- # turn is a tracked follow-up.
+ # begin_agent_initiated_turn). Keep Activity provenance until its real
+ # result branch consumes it. A generic ScheduleWakeup output has no
+ # Activity, so mark just this assistant/result sequence detached.
logger.info(
"Agent-initiated output for %s not opened: runtime gate contended "
"(a user turn holds or is queued on it)",
composite_key,
)
- return
+ if completed_activity is not None:
+ self._detached_activity_outputs[composite_key] = completed_activity
+ return "activity"
+ if message_type in {"assistant", "result"}:
+ self._detached_unsolicited_outputs.add(composite_key)
+ return "detached"
+ return None
# Mark the session ACTIVE so this in-flight agent-initiated turn gets the
# SAME idle-eviction exemption a user turn gets in ``handle_message``.
# Without it the turn is protected only by per-message activity touches and
@@ -1195,21 +1799,41 @@ class ClaudeAgent(BaseAgent):
base_session_id=base_session_id,
composite_session_id=composite_key,
session_key=session_key,
+ output=(
+ self._activity_message_output(
+ completed_activity,
+ detached=False,
+ completes_turn=True,
+ )
+ if completed_activity is not None
+ else None
+ ),
)
self._pending_requests.setdefault(composite_key, []).append(request)
logger.info(
"Opened agent-initiated turn for session %s (unsolicited backend output)",
composite_key,
)
+ return None
def _mark_session_idle_if_no_pending_requests(self, composite_key: str) -> bool:
if self._has_pending_requests(composite_key):
return False
+ registry = self._activity_registry()
+ if registry is not None and registry.has_active(self.name, composite_key):
+ return False
mark_session_idle = getattr(self.session_handler, "mark_session_idle", None)
if callable(mark_session_idle):
mark_session_idle(composite_key)
return True
+ def _mark_session_idle_if_runtime_free(self, composite_key: str) -> bool:
+ service = getattr(self.controller, "agent_service", None)
+ runtime_turn_active = getattr(service, "runtime_turn_active", None)
+ if callable(runtime_turn_active) and runtime_turn_active(composite_key):
+ return False
+ return self._mark_session_idle_if_no_pending_requests(composite_key)
+
def _remove_pending_request(self, composite_key: str, request: AgentRequest) -> None:
requests = self._pending_requests.get(composite_key)
if not requests:
diff --git a/modules/agents/service.py b/modules/agents/service.py
index 16043f84a..9fcfb8121 100644
--- a/modules/agents/service.py
+++ b/modules/agents/service.py
@@ -4,6 +4,8 @@ import uuid
from dataclasses import dataclass, field
from typing import Any, Dict, Optional
+from core.session_activities import SessionActivityRegistry
+
from .base import (
AGENT_RUNTIME_TURN_KEY,
AGENT_RUNTIME_TURN_TOKEN,
@@ -25,6 +27,7 @@ class AgentService:
self.agents: Dict[str, BaseAgent] = {}
self.default_agent = "claude"
self._turn_gates: dict[str, _RuntimeTurnGate] = {}
+ self.activities = SessionActivityRegistry()
# Strong refs to fire-and-forget tasks (e.g. the cancellation tidy) so the
# event loop doesn't GC them before they run (asyncio only weak-refs tasks).
self._background_tasks: set[asyncio.Task] = set()
@@ -33,6 +36,30 @@ class AgentService:
self.agents[agent.name] = agent
logger.info(f"Registered agent backend: {agent.name}")
+ def on_activity_terminal(self, activity: Any) -> None:
+ """Let the Run owner react after the registry removed one Activity."""
+
+ service = getattr(self.controller, "scheduled_task_service", None)
+ settle = getattr(service, "settle_activity_runs", None)
+ if not callable(settle):
+ return
+ try:
+ settle(activity)
+ except Exception:
+ logger.warning(
+ "Failed to settle Runs for terminal Activity %s",
+ getattr(activity, "id", ""),
+ exc_info=True,
+ )
+
+ def end_activity_runtime(self, backend: str, runtime_key: str) -> list[Any]:
+ """Terminate one backend connection's Activities and notify Run owners."""
+
+ completed = self.activities.end_runtime(backend, runtime_key)
+ for activity in completed:
+ self.on_activity_terminal(activity)
+ return completed
+
def get(self, agent_name: Optional[str]) -> BaseAgent:
target = agent_name or self.default_agent
if target in self.agents:
@@ -253,6 +280,15 @@ class AgentService:
gate = self._turn_gates.get(runtime_key)
return bool(gate is not None and gate.token == runtime_token and gate.runtime_started)
+ def runtime_turn_active(self, runtime_key: str) -> bool:
+ """Whether a foreground turn holds or is queued on this backend runtime."""
+
+ gate = self._turn_gates.get(str(runtime_key or "").strip())
+ return bool(
+ gate is not None
+ and (gate.lock.locked() or self._lock_has_live_waiters(gate.lock))
+ )
+
@staticmethod
def _lock_has_live_waiters(lock: asyncio.Lock) -> bool:
"""True when ``lock`` has at least one not-yet-cancelled queued waiter.
diff --git a/modules/claude_sdk_compat.py b/modules/claude_sdk_compat.py
index 14531968d..5b9d116a5 100644
--- a/modules/claude_sdk_compat.py
+++ b/modules/claude_sdk_compat.py
@@ -29,6 +29,25 @@ try:
UserMessage,
)
from claude_agent_sdk._errors import CLIConnectionError, MessageParseError
+
+ try:
+ from claude_agent_sdk import ( # type: ignore[import-not-found]
+ TaskNotificationMessage,
+ TaskProgressMessage,
+ TaskStartedMessage,
+ )
+ except ImportError:
+ # Task lifecycle frames were added after the core SDK types. Avibe
+ # detects them by class name/subtype, so an older SDK can keep running.
+ class TaskStartedMessage(SystemMessage):
+ pass
+
+ class TaskProgressMessage(SystemMessage):
+ pass
+
+ class TaskNotificationMessage(SystemMessage):
+ pass
+
CLAUDE_SDK_AVAILABLE = True
def _should_ignore_message_parse_error(data: object) -> bool:
@@ -92,6 +111,15 @@ except ModuleNotFoundError: # pragma: no cover - exercised only in minimal test
class ResultMessage:
pass
+ class TaskStartedMessage(SystemMessage):
+ pass
+
+ class TaskProgressMessage(SystemMessage):
+ pass
+
+ class TaskNotificationMessage(SystemMessage):
+ pass
+
class TextBlock:
pass
diff --git a/storage/background.py b/storage/background.py
index bd9171abe..963ac4a80 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -96,12 +96,28 @@ _LIKE_ESCAPE = "\\"
DEFINITION_STATUS_COUNTS = ("all", "enabled", "disabled")
RUN_STATUS_COUNTS = ("all", "queued", "running", "succeeded", "failed", "canceled")
_DEFERRED_RUN_EVENT_ROWS_KEY = "avibe.deferred_run_event_rows"
+_TERMINAL_STATUS_PRIORITY = {
+ "succeeded": 0,
+ "canceled": 1,
+ "failed": 2,
+}
def normalize_run_status(status: Any) -> str:
return RUN_STATUS_ALIASES.get(str(status or "").strip(), str(status or "").strip() or "queued")
+def _stronger_terminal_status(current: Any, incoming: Any) -> str:
+ current_status = normalize_run_status(current)
+ incoming_status = normalize_run_status(incoming)
+ if _TERMINAL_STATUS_PRIORITY.get(current_status, -1) >= _TERMINAL_STATUS_PRIORITY.get(
+ incoming_status,
+ -1,
+ ):
+ return current_status
+ return incoming_status
+
+
def _status_query_values(status: str) -> list[str]:
normalized = normalize_run_status(status)
values = [raw for raw, public in RUN_STATUS_ALIASES.items() if public == normalized]
@@ -1196,6 +1212,256 @@ class SQLiteBackgroundTaskStore:
)
_publish_run_rows_updated([row_to_publish])
+ def record_run_output(
+ self,
+ run_id: str,
+ *,
+ output_id: str,
+ text: str,
+ message_id: str | None = None,
+ sequence: int | None = None,
+ provenance: Optional[dict[str, Any]] = None,
+ terminal_status: Optional[str] = None,
+ updated_at: Optional[str] = None,
+ ) -> dict[str, Any]:
+ """Append one idempotent Run output and optionally settle the Run once."""
+
+ now = updated_at or _utc_now_iso()
+ identity = str(output_id or "").strip()
+ if not identity:
+ raise ValueError("output_id is required")
+ recorded = False
+ terminal_transition = False
+ run_payload: Optional[dict[str, Any]] = None
+ row_to_publish = None
+ with self.engine.begin() as conn:
+ row = conn.execute(
+ select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
+ ).mappings().first()
+ if not row:
+ return {
+ "recorded": False,
+ "terminal_transition": False,
+ "run": None,
+ }
+
+ result_payload = _json_loads(row["result_payload_json"], {})
+ if not isinstance(result_payload, dict):
+ result_payload = {}
+ payload_changed = False
+ effective_terminal_status = terminal_status
+ if terminal_status and "deferred_terminal_status" in result_payload:
+ effective_terminal_status = _stronger_terminal_status(
+ result_payload.pop("deferred_terminal_status", None),
+ terminal_status,
+ )
+ payload_changed = True
+ raw_outputs = result_payload.get("outputs")
+ outputs = [dict(item) for item in raw_outputs if isinstance(item, dict)] if isinstance(raw_outputs, list) else []
+ visible_text = str(text or "")
+ if visible_text.strip() and not any(str(item.get("id") or "") == identity for item in outputs):
+ output_entry: dict[str, Any] = {
+ "id": identity,
+ "text": visible_text,
+ }
+ if message_id:
+ output_entry["message_id"] = message_id
+ if sequence is not None:
+ output_entry["sequence"] = sequence
+ if provenance:
+ output_entry["provenance"] = dict(provenance)
+ outputs.append(output_entry)
+ result_payload["outputs"] = outputs
+ recorded = True
+ payload_changed = True
+
+ existing_text = str(row["result_text"] or "")
+ if recorded:
+ result_text = f"{existing_text}\n\n{visible_text}" if existing_text else visible_text
+ else:
+ result_text = existing_text
+ message_ids = _json_loads(row["message_ids_json"], [])
+ if not isinstance(message_ids, list):
+ message_ids = []
+ if recorded and message_id and message_id not in message_ids:
+ message_ids.append(message_id)
+
+ if payload_changed:
+ values: dict[str, Any] = {
+ "result_payload_json": _json_dumps(result_payload),
+ "updated_at": now,
+ }
+ if recorded:
+ values.update(
+ result_text=result_text,
+ message_ids_json=_json_dumps(message_ids),
+ )
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .values(**values)
+ )
+ if effective_terminal_status:
+ transition = conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .where(
+ agent_runs.c.status.in_(
+ _status_query_values("queued")
+ + _status_query_values("running")
+ )
+ )
+ .values(
+ status=normalize_run_status(effective_terminal_status),
+ completed_at=now,
+ updated_at=now,
+ )
+ )
+ terminal_transition = bool(transition.rowcount)
+
+ if payload_changed or terminal_transition:
+ row_to_publish = dict(
+ conn.execute(
+ select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
+ ).mappings().one()
+ )
+ run_payload = self._run_from_row(row_to_publish)
+ else:
+ run_payload = self._run_from_row(row)
+ _publish_run_rows_updated([row_to_publish])
+ return {
+ "recorded": recorded,
+ "terminal_transition": terminal_transition,
+ "run": run_payload,
+ }
+
+ def defer_run_terminal(
+ self,
+ run_id: str,
+ *,
+ terminal_status: str,
+ updated_at: Optional[str] = None,
+ ) -> bool:
+ """Remember a terminal intent while an owned Activity still blocks it."""
+
+ now = updated_at or _utc_now_iso()
+ row_to_publish = None
+ with self.engine.begin() as conn:
+ row = conn.execute(
+ select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
+ ).mappings().first()
+ if not row or normalize_run_status(row["status"]) in {
+ "succeeded",
+ "failed",
+ "canceled",
+ }:
+ return False
+ result_payload = _json_loads(row["result_payload_json"], {})
+ if not isinstance(result_payload, dict):
+ result_payload = {}
+ normalized = _stronger_terminal_status(
+ result_payload.get("deferred_terminal_status"),
+ terminal_status,
+ )
+ if result_payload.get("deferred_terminal_status") == normalized:
+ return False
+ result_payload["deferred_terminal_status"] = normalized
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .values(
+ result_payload_json=_json_dumps(result_payload),
+ updated_at=now,
+ )
+ )
+ row_to_publish = dict(
+ conn.execute(
+ select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
+ ).mappings().one()
+ )
+ _publish_run_rows_updated([row_to_publish])
+ return True
+
+ def settle_deferred_run(
+ self,
+ run_id: str,
+ *,
+ terminal_status: Optional[str] = None,
+ error: Optional[str] = None,
+ updated_at: Optional[str] = None,
+ ) -> bool:
+ """Apply one stored terminal intent after owned Activities become terminal."""
+
+ now = updated_at or _utc_now_iso()
+ row_to_publish = None
+ transitioned = False
+ with self.engine.begin() as conn:
+ row = conn.execute(
+ select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
+ ).mappings().first()
+ if not row:
+ return False
+ result_payload = _json_loads(row["result_payload_json"], {})
+ if not isinstance(result_payload, dict):
+ return False
+ deferred_status = str(result_payload.get("deferred_terminal_status") or "").strip()
+ if not deferred_status:
+ return False
+ result_payload.pop("deferred_terminal_status", None)
+ status = (
+ _stronger_terminal_status(deferred_status, terminal_status)
+ if terminal_status
+ else normalize_run_status(deferred_status)
+ )
+ values: dict[str, Any] = {
+ "status": status,
+ "completed_at": now,
+ "updated_at": now,
+ "result_payload_json": _json_dumps(result_payload),
+ }
+ if error is not None:
+ values["error"] = error
+ transition = conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id == run_id)
+ .where(
+ agent_runs.c.status.in_(
+ _status_query_values("queued")
+ + _status_query_values("running")
+ )
+ )
+ .values(**values)
+ )
+ transitioned = bool(transition.rowcount)
+ if transitioned:
+ row_to_publish = dict(
+ conn.execute(
+ select(agent_runs).where(agent_runs.c.id == run_id).limit(1)
+ ).mappings().one()
+ )
+ _publish_run_rows_updated([row_to_publish])
+ return transitioned
+
+ def find_callback_run(
+ self,
+ *,
+ parent_run_id: str,
+ source_actor: str,
+ ) -> Optional[dict[str, Any]]:
+ """Return the callback Run for one structured parent-output identity."""
+
+ with self.engine.connect() as conn:
+ row = conn.execute(
+ select(agent_runs)
+ .where(agent_runs.c.run_type == "agent_run")
+ .where(agent_runs.c.source_kind == "callback")
+ .where(agent_runs.c.parent_run_id == parent_run_id)
+ .where(agent_runs.c.source_actor == source_actor)
+ .order_by(agent_runs.c.created_at, agent_runs.c.id)
+ .limit(1)
+ ).mappings().first()
+ return self._run_from_row(row) if row else None
+
def recover_processing_runs(self) -> None:
with run_update_event_transaction(self.engine) as conn:
now = _utc_now_iso()
diff --git a/tests/scenario_harness/message_delivery.py b/tests/scenario_harness/message_delivery.py
index b202f5c18..659d01dd9 100644
--- a/tests/scenario_harness/message_delivery.py
+++ b/tests/scenario_harness/message_delivery.py
@@ -3,6 +3,7 @@ from __future__ import annotations
from types import SimpleNamespace
from core.message_dispatcher import ConsolidatedMessageDispatcher
+from core.message_output import MessageOutput
from modules.im import MessageContext
from tests.scenario_harness.core import BaseScenarioHarness, ScenarioControllerBase
@@ -29,6 +30,26 @@ class MessageDeliveryController(ScenarioControllerBase):
self.config.reply_enhancements = False
self.session_handler = MessageDeliverySessionHandler()
self.settings_manager = MessageDeliverySettingsManager()
+ self.runtime_turn_current = True
+ self.runtime_release_calls = 0
+ self.turn_terminal_calls = 0
+ self.stream_completion_calls = 0
+ self.agent_service = SimpleNamespace(
+ agents={},
+ emit_matches_runtime_turn=lambda context: self.runtime_turn_current,
+ release_runtime_turn=lambda context: setattr(
+ self,
+ "runtime_release_calls",
+ self.runtime_release_calls + 1,
+ ),
+ )
+ self.session_turns = SimpleNamespace(
+ on_terminal_result=lambda context, is_error: setattr(
+ self,
+ "turn_terminal_calls",
+ self.turn_terminal_calls + 1,
+ )
+ )
def _get_session_key(self, context):
return f"{context.platform or self.config.platform}::{context.channel_id}"
@@ -36,6 +57,9 @@ class MessageDeliveryController(ScenarioControllerBase):
def get_settings_manager_for_context(self, context):
return self.settings_manager
+ def mark_turn_complete(self, context):
+ self.stream_completion_calls += 1
+
class MessageDeliveryHarness(BaseScenarioHarness):
def __init__(self, *, platform: str = "slack", user_id: str = "scheduled", channel_id: str = "C123", thread_id=None):
@@ -51,6 +75,14 @@ class MessageDeliveryHarness(BaseScenarioHarness):
async def emit_result(self, text: str):
return await self.dispatcher.emit_agent_message(self.context, "result", text)
+ async def emit_output(self, text: str, output: MessageOutput):
+ return await self.dispatcher.emit_agent_message(
+ self.context,
+ "result",
+ text,
+ output=output,
+ )
+
@property
def sent_messages(self):
return list(getattr(self.controller.im_client, "probe").matching("message"))
diff --git a/tests/scenarios/message_delivery/catalog.yaml b/tests/scenarios/message_delivery/catalog.yaml
index 71fd4955b..8702e70be 100644
--- a/tests/scenarios/message_delivery/catalog.yaml
+++ b/tests/scenarios/message_delivery/catalog.yaml
@@ -1,7 +1,7 @@
version: 1
capability:
id: message_delivery
- name: scheduled result delivery
+ name: full-duplex message delivery
canonical_tests:
- tests/scenarios/message_delivery/test_message_delivery_scenarios.py
shared_harness:
@@ -25,6 +25,24 @@ scenarios:
kind: happy_path
layer: scenario
test: tests/scenarios/message_delivery/test_message_delivery_scenarios.py::test_scheduled_result_delivery_override_scenario_uses_parent_channel_target
+ - id: MESSAGE-DELIVERY-003
+ name: Claude background output is delivered without settling a newer user Turn
+ status: covered
+ kind: concurrency
+ layer: scenario
+ test: tests/scenarios/message_delivery/test_message_delivery_scenarios.py::MessageDeliveryScenarioTests::test_background_output_scenario_does_not_settle_newer_turn
+ - id: MESSAGE-DELIVERY-004
+ name: One Turn emits multiple output Messages and completes once
+ status: covered
+ kind: lifecycle
+ layer: scenario
+ test: tests/scenarios/message_delivery/test_message_delivery_scenarios.py::MessageDeliveryScenarioTests::test_one_turn_multiple_outputs_scenario_completes_once
+ - id: MESSAGE-DELIVERY-005
+ name: One Run forwards multiple callback outputs and completes once
+ status: covered
+ kind: lifecycle
+ layer: contract
+ test: tests/test_scheduled_tasks.py::test_agent_run_forwards_multiple_outputs_and_completes_once
next_priority:
- MESSAGE-DELIVERY-101
- MESSAGE-DELIVERY-102
diff --git a/tests/scenarios/message_delivery/test_message_delivery_scenarios.py b/tests/scenarios/message_delivery/test_message_delivery_scenarios.py
index b1f8e7baa..7d06050c8 100644
--- a/tests/scenarios/message_delivery/test_message_delivery_scenarios.py
+++ b/tests/scenarios/message_delivery/test_message_delivery_scenarios.py
@@ -3,15 +3,91 @@ from __future__ import annotations
import sys
import unittest
from pathlib import Path
+from unittest.mock import patch
ROOT = Path(__file__).resolve().parents[3]
sys.path.insert(0, str(ROOT))
from tests.scenario_harness.core import ScenarioExpect, ScenarioRunner, ScenarioStep
+from core.message_output import MessageOutput
from tests.scenario_harness.message_delivery import MessageDeliveryHarness
class MessageDeliveryScenarioTests(unittest.IsolatedAsyncioTestCase):
+ async def test_background_output_scenario_does_not_settle_newer_turn(self):
+ """Scenario: MESSAGE-DELIVERY-003"""
+ harness = MessageDeliveryHarness(platform="slack")
+ harness.controller.runtime_turn_current = False
+ harness.context.platform_specific = {
+ "agent_runtime_turn_key": "runtime-1",
+ "agent_runtime_turn_token": "older-turn",
+ "turn_token": "older-turn",
+ }
+ runner = ScenarioRunner(harness)
+
+ with (
+ patch("core.message_dispatcher.agent_message_exists", return_value=False),
+ patch("core.message_dispatcher.persist_agent_message"),
+ ):
+ await runner.run(
+ ScenarioStep(
+ "deliver_background_result",
+ lambda h: h.emit_output(
+ "background result",
+ MessageOutput(
+ completes_turn=False,
+ detached=True,
+ idempotency_key="task-1:completion",
+ activity_id="task-1",
+ ),
+ ),
+ )
+ )
+
+ ScenarioExpect.text_contains(harness, "background result")
+ self.assertEqual(harness.controller.turn_terminal_calls, 0)
+ self.assertEqual(harness.controller.stream_completion_calls, 0)
+ self.assertEqual(harness.controller.runtime_release_calls, 0)
+
+ async def test_one_turn_multiple_outputs_scenario_completes_once(self):
+ """Scenario: MESSAGE-DELIVERY-004"""
+ harness = MessageDeliveryHarness(platform="slack")
+ runner = ScenarioRunner(harness)
+
+ with (
+ patch("core.message_dispatcher.agent_message_exists", return_value=False),
+ patch("core.message_dispatcher.persist_agent_message"),
+ ):
+ await runner.run(
+ ScenarioStep(
+ "emit_intermediate_output",
+ lambda h: h.emit_output(
+ "first output",
+ MessageOutput(
+ completes_turn=False,
+ idempotency_key="output-1",
+ sequence=1,
+ ),
+ ),
+ ),
+ ScenarioStep(
+ "emit_terminal_output",
+ lambda h: h.emit_output(
+ "final output",
+ MessageOutput(
+ completes_turn=True,
+ idempotency_key="output-2",
+ sequence=2,
+ ),
+ ),
+ ),
+ )
+
+ self.assertEqual(harness.rendered_texts(), ["first output", "final output"])
+ self.assertEqual(harness.controller.turn_terminal_calls, 1)
+ self.assertEqual(harness.controller.stream_completion_calls, 0)
+ self.assertEqual(harness.controller.runtime_release_calls, 1)
+
async def test_scheduled_result_delivery_scenario_finalizes_anchor(self):
"""Scenario: MESSAGE-DELIVERY-001"""
harness = MessageDeliveryHarness(platform="slack")
diff --git a/tests/test_agent_service.py b/tests/test_agent_service.py
index f15843d80..5ab521132 100644
--- a/tests/test_agent_service.py
+++ b/tests/test_agent_service.py
@@ -2,7 +2,7 @@ from __future__ import annotations
import asyncio
from types import SimpleNamespace
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, Mock
from modules.agents.service import AgentService
@@ -195,6 +195,30 @@ def test_agent_service_reports_missing_runtime_refresh_contract() -> None:
assert asyncio.run(service.refresh_runtime_config("claude", object())) is False
+def test_agent_service_notifies_run_owner_when_activity_runtime_disconnects() -> None:
+ settle = Mock()
+ controller = SimpleNamespace(
+ scheduled_task_service=SimpleNamespace(settle_activity_runs=settle),
+ )
+ service = AgentService(controller)
+ service.activities.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="session-1",
+ activity_id="task-1",
+ kind="background_task",
+ run_id="run-1",
+ )
+
+ service.end_activity_runtime("claude", "runtime-1")
+
+ assert service.activities.active_for_runtime("claude", "runtime-1") == []
+ activity = settle.call_args.args[0]
+ assert activity.id == "task-1"
+ assert activity.run_id == "run-1"
+ assert activity.status == "disconnected"
+
+
def test_agent_service_serializes_same_runtime_until_terminal_release() -> None:
async def _run():
controller = _Controller()
diff --git a/tests/test_claude_agent_initiated_turn.py b/tests/test_claude_agent_initiated_turn.py
index 100d358a1..c41ff74e8 100644
--- a/tests/test_claude_agent_initiated_turn.py
+++ b/tests/test_claude_agent_initiated_turn.py
@@ -45,6 +45,29 @@ class ResultMessage:
subtype = "success"
result = "✅ master 回归环境已就绪"
duration_ms = 1
+ duration_api_ms = 1
+ session_id = "claude-native-session"
+
+ def __init__(self, *, num_turns: int = 1):
+ self.num_turns = num_turns
+
+
+class TaskStartedMessage:
+ subtype = "task_started"
+ task_id = "task-690"
+ description = "Background verification"
+ task_type = "local_agent"
+ tool_use_id = "tool-690"
+ data = {}
+
+
+class TaskNotificationMessage:
+ subtype = "task_notification"
+ task_id = "task-690"
+ status = "completed"
+ output_file = "/tmp/task-690.output"
+ summary = "Background verification finished"
+ data = {}
def _assistant_then_result_client():
@@ -70,6 +93,68 @@ def _one_result_client():
return _Client()
+def _two_result_client():
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ yield ResultMessage(num_turns=1)
+ yield ResultMessage(num_turns=2)
+
+ return _iterate()
+
+ return _Client()
+
+
+def _completed_task_then_result_client():
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ yield TaskStartedMessage()
+ yield TaskNotificationMessage()
+ yield ResultMessage()
+
+ return _iterate()
+
+ return _Client()
+
+
+def _task_notification_then_result_client():
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ yield TaskNotificationMessage()
+ yield ResultMessage()
+
+ return _iterate()
+
+ return _Client()
+
+
+def _completed_task_notification_client():
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ yield TaskStartedMessage()
+ yield TaskNotificationMessage()
+
+ return _iterate()
+
+ return _Client()
+
+
+def _completed_task_notification_then_wait_client(release: asyncio.Event):
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ yield TaskStartedMessage()
+ yield TaskNotificationMessage()
+ await release.wait()
+
+ return _iterate()
+
+ return _Client()
+
+
def _fallback_client(data):
class ModelRefusalFallbackMessage:
subtype = "model_refusal_fallback"
@@ -234,6 +319,615 @@ class BeginAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
+ async def test_claude_query_waits_until_background_output_is_consumed(self):
+ agent, service = _build_agent()
+ composite_key = "session-serialized:/tmp/work"
+ service.activities.start(
+ backend="claude",
+ runtime_key=composite_key,
+ session_id="sess-serialized",
+ activity_id="task-690",
+ kind="local_agent",
+ )
+
+ waiter = asyncio.create_task(agent._wait_for_activity_output(composite_key))
+ await asyncio.sleep(0)
+ self.assertFalse(waiter.done())
+
+ service.activities.complete(
+ backend="claude",
+ runtime_key=composite_key,
+ activity_id="task-690",
+ status="completed",
+ expects_output=True,
+ )
+ agent._signal_activity_output_settled(composite_key)
+ await asyncio.sleep(0)
+ self.assertFalse(waiter.done())
+
+ self.assertIsNotNone(
+ service.activities.claim_completed_output("claude", composite_key)
+ )
+ agent._signal_activity_output_settled(composite_key)
+ await asyncio.wait_for(waiter, timeout=1)
+
+ async def test_terminal_only_task_event_keeps_current_turn_origin(self):
+ agent, service = _build_agent()
+ composite_key = "session-terminal-only:/tmp/work"
+ pending_context = SimpleNamespace(
+ platform_specific={"turn_token": "current-turn"},
+ )
+ agent._pending_requests[composite_key] = [SimpleNamespace(context=pending_context)]
+ context = SimpleNamespace(
+ platform_specific={"agent_session_id": "sess-terminal-only"},
+ )
+
+ self.assertTrue(
+ agent._handle_activity_message(
+ TaskNotificationMessage(),
+ composite_key,
+ context,
+ )
+ )
+
+ activity = service.activities.claim_completed_output("claude", composite_key)
+ self.assertIsNotNone(activity)
+ self.assertEqual(activity.turn_id, "current-turn")
+
+ async def test_completed_task_notification_at_eof_delivers_summary(self):
+ agent, service = _build_agent()
+ composite_key = "session-eof:/tmp/work"
+ context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform="avibe",
+ platform_specific={
+ "agent_runtime_turn_key": composite_key,
+ "agent_runtime_turn_token": "old-turn",
+ "turn_token": "origin-turn",
+ "agent_session_id": "sess-eof",
+ },
+ )
+ agent.emit_result_message = AsyncMock()
+
+ await agent._receive_messages(
+ _completed_task_notification_client(),
+ "session-eof",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+
+ agent.emit_result_message.assert_awaited_once()
+ self.assertEqual(
+ agent.emit_result_message.await_args.args[1],
+ "Background verification finished",
+ )
+ output = agent.emit_result_message.await_args.kwargs["output"]
+ self.assertTrue(output.detached)
+ self.assertFalse(output.completes_turn)
+ self.assertTrue(output.completes_run)
+ self.assertIsNone(service.activities.claim_completed_output("claude", composite_key))
+
+ async def test_completed_task_notification_flushes_while_receiver_stays_open(self):
+ agent, service = _build_agent()
+ agent.ACTIVITY_OUTPUT_FLUSH_GRACE_SECONDS = 0
+ composite_key = "session-live-flush:/tmp/work"
+ context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform="avibe",
+ platform_specific={
+ "agent_runtime_turn_key": composite_key,
+ "agent_runtime_turn_token": "old-turn",
+ "turn_token": "origin-turn",
+ "agent_session_id": "sess-live-flush",
+ },
+ )
+ emitted = asyncio.Event()
+
+ async def _emit(*_args, **_kwargs):
+ emitted.set()
+
+ agent.emit_result_message = AsyncMock(side_effect=_emit)
+ release = asyncio.Event()
+ receiver = asyncio.create_task(
+ agent._receive_messages(
+ _completed_task_notification_then_wait_client(release),
+ "session-live-flush",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+ )
+ try:
+ await asyncio.wait_for(emitted.wait(), timeout=1)
+ self.assertFalse(receiver.done())
+ output = agent.emit_result_message.await_args.kwargs["output"]
+ self.assertTrue(output.detached)
+ self.assertFalse(output.completes_turn)
+ self.assertTrue(output.completes_run)
+ self.assertIsNone(
+ service.activities.claim_completed_output("claude", composite_key)
+ )
+ finally:
+ release.set()
+ await receiver
+
+ async def test_timed_flush_keeps_activity_for_a_newer_pending_turn(self):
+ agent, service = _build_agent()
+ composite_key = "session-deferred-flush:/tmp/work"
+ pending_context = SimpleNamespace(platform_specific={"turn_token": "newer-turn"})
+ agent._pending_requests[composite_key] = [SimpleNamespace(context=pending_context)]
+ context = SimpleNamespace(platform_specific={"agent_session_id": "sess-deferred"})
+ service.activities.start(
+ backend="claude",
+ runtime_key=composite_key,
+ session_id="sess-deferred",
+ activity_id="task-690",
+ kind="local_agent",
+ turn_id="origin-turn",
+ )
+ service.activities.complete(
+ backend="claude",
+ runtime_key=composite_key,
+ activity_id="task-690",
+ status="completed",
+ metadata={"summary": "Background verification finished"},
+ expects_output=True,
+ )
+ agent.emit_result_message = AsyncMock()
+
+ should_retry = await agent._flush_completed_activity_outputs(composite_key, context)
+
+ self.assertTrue(should_retry)
+ agent.emit_result_message.assert_not_awaited()
+ claimed = service.activities.claim_completed_output("claude", composite_key)
+ self.assertIsNotNone(claimed)
+ self.assertEqual(claimed.turn_id, "origin-turn")
+
+ async def test_requeued_terminal_only_activity_flushes_after_pending_turn(self):
+ agent, service = _build_agent()
+ agent.ACTIVITY_OUTPUT_FLUSH_GRACE_SECONDS = 0
+ composite_key = "session-retry-flush:/tmp/work"
+ agent._pending_requests[composite_key] = [
+ SimpleNamespace(
+ context=SimpleNamespace(platform_specific={"turn_token": "newer-turn"})
+ )
+ ]
+ context = SimpleNamespace(platform_specific={"agent_session_id": "sess-retry"})
+ service.activities.start(
+ backend="claude",
+ runtime_key=composite_key,
+ session_id="sess-retry",
+ activity_id="task-690",
+ kind="local_agent",
+ turn_id="origin-turn",
+ )
+ service.activities.complete(
+ backend="claude",
+ runtime_key=composite_key,
+ activity_id="task-690",
+ status="completed",
+ metadata={"summary": "Background verification finished"},
+ expects_output=True,
+ )
+ requeued = asyncio.Event()
+ original_requeue = service.activities.requeue_completed_output
+
+ def _requeue(activity, *, front=True):
+ original_requeue(activity, front=front)
+ requeued.set()
+
+ service.activities.requeue_completed_output = _requeue
+ emitted = asyncio.Event()
+ agent.emit_result_message = AsyncMock(side_effect=lambda *_a, **_k: emitted.set())
+
+ agent._schedule_completed_activity_flush(composite_key, context)
+ await asyncio.wait_for(requeued.wait(), timeout=1)
+ agent._pending_requests.pop(composite_key)
+ await asyncio.wait_for(emitted.wait(), timeout=1)
+
+ self.assertFalse(service.activities.has_completed_output("claude", composite_key))
+ self.assertFalse(agent._activity_output_pending(composite_key))
+
+ async def test_runtime_disconnect_marks_session_idle_after_activity_cleanup(self):
+ mark_idle_calls: list[str] = []
+ agent, service = _build_agent(mark_idle_calls=mark_idle_calls)
+ composite_key = "session-disconnected:/tmp/work"
+ service.activities.start(
+ backend="claude",
+ runtime_key=composite_key,
+ session_id="sess-disconnected",
+ activity_id="task-690",
+ kind="local_agent",
+ )
+
+ agent._end_activity_runtime(composite_key)
+
+ self.assertFalse(service.activities.has_active("claude", composite_key))
+ self.assertEqual(mark_idle_calls, [composite_key])
+
+ async def test_task_start_uses_current_request_run_not_stale_receiver_run(self):
+ agent, service = _build_agent()
+ composite_key = "session-lineage:/tmp/work"
+ pending_context = SimpleNamespace(
+ platform_specific={
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-current",
+ "turn_token": "current-turn",
+ }
+ )
+ agent._pending_requests[composite_key] = [SimpleNamespace(context=pending_context)]
+ receiver_context = SimpleNamespace(
+ platform_specific={
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-stale",
+ "turn_token": "stale-turn",
+ "agent_session_id": "sess-lineage",
+ }
+ )
+
+ self.assertTrue(
+ agent._handle_activity_message(
+ TaskStartedMessage(),
+ composite_key,
+ receiver_context,
+ )
+ )
+
+ activity = service.activities.active_for_runtime("claude", composite_key)[0]
+ self.assertEqual(activity.run_id, "run-current")
+ self.assertEqual(activity.turn_id, "current-turn")
+ self.assertEqual(activity.metadata["run_ids"], ["run-current"])
+
+ async def test_task_progress_keeps_original_run_lineage(self):
+ agent, service = _build_agent()
+ composite_key = "session-progress-lineage:/tmp/work"
+ origin_context = SimpleNamespace(
+ platform_specific={
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-origin",
+ "turn_token": "turn-origin",
+ }
+ )
+ agent._pending_requests[composite_key] = [SimpleNamespace(context=origin_context)]
+ receiver_context = SimpleNamespace(
+ platform_specific={"agent_session_id": "sess-progress-lineage"},
+ )
+ self.assertTrue(
+ agent._handle_activity_message(
+ TaskStartedMessage(),
+ composite_key,
+ receiver_context,
+ )
+ )
+
+ newer_context = SimpleNamespace(
+ platform_specific={
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-newer",
+ "turn_token": "turn-newer",
+ }
+ )
+ agent._pending_requests[composite_key] = [SimpleNamespace(context=newer_context)]
+ progress = SimpleNamespace(
+ subtype="task_progress",
+ task_id="task-690",
+ description="Still working",
+ data={},
+ )
+ self.assertTrue(
+ agent._handle_activity_message(
+ progress,
+ composite_key,
+ receiver_context,
+ )
+ )
+
+ activity = service.activities.active_for_runtime("claude", composite_key)[0]
+ self.assertEqual(activity.run_id, "run-origin")
+ self.assertEqual(activity.turn_id, "turn-origin")
+ self.assertEqual(activity.metadata["run_ids"], ["run-origin"])
+
+ self.assertTrue(
+ agent._handle_activity_message(
+ TaskNotificationMessage(),
+ composite_key,
+ receiver_context,
+ )
+ )
+ completed = service.activities.claim_completed_output("claude", composite_key)
+ self.assertIsNotNone(completed)
+ self.assertEqual(completed.run_id, "run-origin")
+ self.assertEqual(completed.turn_id, "turn-origin")
+ self.assertEqual(completed.metadata["run_ids"], ["run-origin"])
+
+ async def test_failed_task_does_not_claim_a_missing_followup_output(self):
+ mark_idle_calls: list[str] = []
+ agent, service = _build_agent(mark_idle_calls=mark_idle_calls)
+ composite_key = "session-failed:/tmp/work"
+ context = SimpleNamespace(
+ platform_specific={"agent_session_id": "sess-failed"},
+ )
+ failed = TaskNotificationMessage()
+ failed.status = "failed"
+
+ self.assertTrue(agent._handle_activity_message(TaskStartedMessage(), composite_key, context))
+ self.assertTrue(agent._handle_activity_message(failed, composite_key, context))
+
+ self.assertIsNone(service.activities.claim_completed_output("claude", composite_key))
+ self.assertEqual(mark_idle_calls, [composite_key])
+
+ async def test_completed_background_task_output_does_not_settle_newer_user_turn(self):
+ agent, service = _build_agent()
+ composite_key = "session-690:/tmp/work"
+ gate = service._get_turn_gate(composite_key)
+ await gate.lock.acquire()
+ gate.token = "USER-TURN"
+ gate.backend = "claude"
+ gate.runtime_started = True
+ user_context = SimpleNamespace(
+ platform_specific={
+ "agent_runtime_turn_key": composite_key,
+ "agent_runtime_turn_token": "USER-TURN",
+ "turn_token": "user-turn",
+ }
+ )
+ user_request = SimpleNamespace(context=user_context)
+ agent._pending_requests[composite_key] = [user_request]
+ agent._pending_assistant_message[composite_key] = "newer turn draft"
+ receiver_context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform="avibe",
+ platform_specific={
+ "agent_runtime_turn_key": composite_key,
+ "agent_runtime_turn_token": "OLD-TURN",
+ "turn_token": "old-turn",
+ "agent_session_id": "sess-690",
+ },
+ )
+ agent.emit_result_message = AsyncMock()
+ service.activities.start(
+ backend="claude",
+ runtime_key=composite_key,
+ session_id="sess-690",
+ activity_id="task-690",
+ kind="local_agent",
+ parent_activity_id="tool-690",
+ turn_id="origin-turn",
+ )
+
+ await agent._receive_messages(
+ _task_notification_then_result_client(),
+ "session-690",
+ "/tmp/work",
+ receiver_context,
+ composite_key=composite_key,
+ )
+
+ agent.emit_result_message.assert_awaited_once()
+ output = agent.emit_result_message.await_args.kwargs["output"]
+ self.assertTrue(output.detached)
+ self.assertFalse(output.completes_turn)
+ self.assertTrue(output.completes_run)
+ self.assertEqual(output.activity_id, "task-690")
+ self.assertEqual(output.causation_id, "tool-690")
+ self.assertEqual(output.provenance(receiver_context)["turn_id"], "origin-turn")
+ self.assertEqual(agent._pending_requests[composite_key], [user_request])
+ self.assertEqual(agent._pending_assistant_message[composite_key], "newer turn draft")
+ # Hard #862 invariant: background delivery cannot settle a newer Turn.
+ self.assertEqual(gate.token, "USER-TURN")
+ self.assertTrue(gate.lock.locked())
+ agent.controller.emit_agent_message.assert_not_awaited()
+
+ async def test_contended_activity_result_does_not_poison_next_user_result(self):
+ agent, service = _build_agent()
+ composite_key = "session-contended:/tmp/work"
+ gate = service._get_turn_gate(composite_key)
+ await gate.lock.acquire()
+ gate.token = "USER-TURN"
+ gate.backend = "claude"
+ context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform="avibe",
+ platform_specific={
+ "agent_runtime_turn_key": composite_key,
+ "agent_runtime_turn_token": "OLD-TURN",
+ "turn_token": "old-turn",
+ "agent_session_id": "sess-contended",
+ },
+ )
+ agent.emit_result_message = AsyncMock()
+ service.activities.start(
+ backend="claude",
+ runtime_key=composite_key,
+ session_id="sess-contended",
+ activity_id="task-690",
+ kind="local_agent",
+ turn_id="origin-turn",
+ )
+ service.activities.complete(
+ backend="claude",
+ runtime_key=composite_key,
+ activity_id="task-690",
+ status="completed",
+ metadata={"summary": "Background verification finished"},
+ expects_output=True,
+ )
+
+ mode = await agent._maybe_begin_agent_initiated_turn(
+ context,
+ composite_key,
+ "session-contended",
+ "/tmp/work",
+ "session-key",
+ message_type="result",
+ )
+
+ self.assertEqual(mode, "activity")
+ agent.emit_result_message.assert_not_awaited()
+ self.assertIn(composite_key, agent._detached_activity_outputs)
+ self.assertEqual(gate.token, "USER-TURN")
+
+ await agent._receive_messages(
+ _one_result_client(),
+ "session-contended",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+
+ first_call = agent.emit_result_message.await_args
+ activity_output = first_call.kwargs["output"]
+ self.assertTrue(activity_output.detached)
+ self.assertFalse(activity_output.completes_turn)
+ self.assertNotIn(composite_key, agent._detached_activity_outputs)
+ self.assertEqual(gate.token, "USER-TURN")
+
+ user_request = SimpleNamespace(
+ context=SimpleNamespace(
+ platform_specific={
+ "agent_runtime_turn_key": composite_key,
+ "agent_runtime_turn_token": "USER-TURN",
+ "turn_token": "user-turn",
+ }
+ )
+ )
+ agent._pending_requests[composite_key] = [user_request]
+ await agent._receive_messages(
+ _one_result_client(),
+ "session-contended",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+
+ self.assertEqual(agent.emit_result_message.await_count, 2)
+ user_result_call = agent.emit_result_message.await_args
+ self.assertIs(user_result_call.kwargs["request"], user_request)
+ self.assertNotIn("output", user_result_call.kwargs)
+ self.assertFalse(agent._has_pending_requests(composite_key))
+ gate.lock.release()
+
+ async def test_contended_schedule_wakeup_result_is_delivered_detached(self):
+ agent, service = _build_agent()
+ composite_key = "session-wakeup:/tmp/work"
+ gate = service._get_turn_gate(composite_key)
+ await gate.lock.acquire()
+ gate.token = "USER-TURN"
+ gate.backend = "claude"
+ context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform="avibe",
+ platform_specific={
+ "agent_runtime_turn_key": composite_key,
+ "agent_runtime_turn_token": "OLD-TURN",
+ "agent_session_id": "sess-wakeup",
+ },
+ )
+ agent.emit_result_message = AsyncMock()
+ try:
+ await agent._receive_messages(
+ _one_result_client(),
+ "session-wakeup",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+ finally:
+ gate.lock.release()
+
+ agent.emit_result_message.assert_awaited_once()
+ output = agent.emit_result_message.await_args.kwargs["output"]
+ self.assertTrue(output.detached)
+ self.assertFalse(output.completes_turn)
+ self.assertFalse(output.completes_run)
+ self.assertEqual(gate.token, "USER-TURN")
+ self.assertFalse(agent._has_pending_requests(composite_key))
+
+ async def test_identical_schedule_wakeup_results_get_distinct_output_ids(self):
+ agent, service = _build_agent()
+ composite_key = "session-repeat-wakeup:/tmp/work"
+ gate = service._get_turn_gate(composite_key)
+ await gate.lock.acquire()
+ gate.token = "USER-TURN"
+ gate.backend = "claude"
+ context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform="avibe",
+ platform_specific={
+ "agent_runtime_turn_key": composite_key,
+ "agent_runtime_turn_token": "OLD-TURN",
+ "agent_session_id": "sess-repeat-wakeup",
+ },
+ )
+ agent.emit_result_message = AsyncMock()
+ try:
+ await agent._receive_messages(
+ _two_result_client(),
+ "session-repeat-wakeup",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+ finally:
+ gate.lock.release()
+
+ self.assertEqual(agent.emit_result_message.await_count, 2)
+ output_ids = [
+ call.kwargs["output"].idempotency_key
+ for call in agent.emit_result_message.await_args_list
+ ]
+ self.assertEqual(len(set(output_ids)), 2)
+
+ async def test_task_completed_inside_its_origin_turn_remains_attached(self):
+ agent, service = _build_agent()
+ composite_key = "session-current:/tmp/work"
+ gate = service._get_turn_gate(composite_key)
+ await gate.lock.acquire()
+ gate.token = "CURRENT-TURN"
+ gate.backend = "claude"
+ user_context = SimpleNamespace(
+ platform_specific={
+ "agent_runtime_turn_key": composite_key,
+ "agent_runtime_turn_token": "CURRENT-TURN",
+ "turn_token": "current-turn",
+ }
+ )
+ agent._pending_requests[composite_key] = [SimpleNamespace(context=user_context)]
+ receiver_context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform="avibe",
+ platform_specific={
+ "agent_runtime_turn_key": composite_key,
+ "agent_runtime_turn_token": "CURRENT-TURN",
+ "turn_token": "current-turn",
+ "agent_session_id": "sess-current",
+ },
+ )
+ agent.emit_result_message = AsyncMock()
+
+ await agent._receive_messages(
+ _completed_task_then_result_client(),
+ "session-current",
+ "/tmp/work",
+ receiver_context,
+ composite_key=composite_key,
+ )
+
+ output = agent.emit_result_message.await_args.kwargs["request"].output
+ self.assertFalse(output.detached)
+ self.assertTrue(output.completes_turn)
+ self.assertTrue(output.completes_run)
+ self.assertEqual(output.activity_id, "task-690")
+ self.assertFalse(agent._has_pending_requests(composite_key))
+
async def test_non_actionable_fallback_does_not_open_agent_initiated_turn(self):
active_calls: list[str] = []
agent, service = _build_agent(active_calls=active_calls)
@@ -331,9 +1025,12 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
# Capture whether the guard would pass at the moment the result is emitted.
guard_at_emit: list[bool] = []
+ token_at_emit: list[str] = []
async def _capture_result(ctx, *a, **k):
guard_at_emit.append(service.emit_matches_runtime_turn(ctx))
+ token_at_emit.append(service._get_turn_gate(composite_key).token)
+ service.release_runtime_turn(ctx)
agent.emit_result_message = AsyncMock(side_effect=_capture_result)
@@ -350,8 +1047,9 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(guard_at_emit, [True])
# A real agent-initiated turn was opened (fresh token, not the stale one).
gate = service._get_turn_gate(composite_key)
- self.assertNotEqual(gate.token, "OLD")
- self.assertTrue(gate.token)
+ self.assertNotEqual(token_at_emit, ["OLD"])
+ self.assertTrue(token_at_emit[0])
+ self.assertEqual(gate.token, "")
# INBOUND chokepoint fired once and the turn settled (synthetic request popped).
self.assertEqual(len(running_calls), 1)
# Marked active on open (eviction parity with a user turn) then idle on settle.
diff --git a/tests/test_claude_sdk_compat.py b/tests/test_claude_sdk_compat.py
index 503b8d46e..8dcd7e740 100644
--- a/tests/test_claude_sdk_compat.py
+++ b/tests/test_claude_sdk_compat.py
@@ -119,3 +119,31 @@ def test_missing_sdk_permission_allow_fallback_is_non_throwing(monkeypatch):
assert result.behavior == "allow"
assert result.updated_input is None
assert result.updated_permissions is None
+
+
+def test_older_sdk_without_task_message_classes_stays_available(monkeypatch):
+ original_import = builtins.__import__
+ task_types = {
+ "TaskNotificationMessage",
+ "TaskProgressMessage",
+ "TaskStartedMessage",
+ }
+
+ def _hide_task_types(name, globals=None, locals=None, fromlist=(), level=0):
+ if name == "claude_agent_sdk" and task_types.intersection(fromlist or ()):
+ raise ImportError("older SDK has no task message classes")
+ return original_import(name, globals, locals, fromlist, level)
+
+ monkeypatch.setattr(builtins, "__import__", _hide_task_types)
+ module_path = Path(__file__).resolve().parents[1] / "modules" / "claude_sdk_compat.py"
+ spec = importlib.util.spec_from_file_location("claude_sdk_compat_older", module_path)
+ assert spec is not None
+ assert spec.loader is not None
+ module = importlib.util.module_from_spec(spec)
+
+ spec.loader.exec_module(module)
+
+ assert module.CLAUDE_SDK_AVAILABLE is True
+ assert issubclass(module.TaskStartedMessage, module.SystemMessage)
+ assert issubclass(module.TaskProgressMessage, module.SystemMessage)
+ assert issubclass(module.TaskNotificationMessage, module.SystemMessage)
diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.py
index 543fff801..8c51ed647 100644
--- a/tests/test_message_dispatcher_result_fallback.py
+++ b/tests/test_message_dispatcher_result_fallback.py
@@ -1,5 +1,6 @@
from __future__ import annotations
+import asyncio
import sys
import unittest
from pathlib import Path
@@ -8,6 +9,7 @@ from unittest import mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from core.message_dispatcher import ConsolidatedMessageDispatcher
+from core.message_output import MessageOutput
from modules.im import MessageContext
@@ -128,6 +130,192 @@ class _StubController:
class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
+ async def test_detached_stale_result_delivers_without_mutating_newer_turn(self):
+ controller = _StubController(platform="slack")
+ controller.agent_service = type(
+ "Service",
+ (),
+ {
+ "emit_matches_runtime_turn": lambda self, context: False,
+ "release_runtime_turn": mock.Mock(),
+ },
+ )()
+ controller.session_turns = type(
+ "Turns",
+ (),
+ {"on_terminal_result": mock.Mock()},
+ )()
+ controller.mark_turn_complete = mock.Mock()
+ turn_chunk = mock.AsyncMock()
+ controller.get_turn_sink = lambda key: {
+ "on_chunk": turn_chunk,
+ "done_event": asyncio.Event(),
+ "turn_token": "newer-turn",
+ }
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="slack",
+ platform_specific={
+ "agent_runtime_turn_key": "runtime-1",
+ "agent_runtime_turn_token": "old-turn",
+ "turn_token": "old-turn",
+ },
+ )
+
+ with mock.patch("core.message_dispatcher.persist_agent_message") as persist:
+ message_id = await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "late background result",
+ output=MessageOutput(
+ completes_turn=False,
+ detached=True,
+ idempotency_key="task-1:completion",
+ activity_id="task-1",
+ sequence=1,
+ ),
+ )
+
+ self.assertEqual(message_id, "msg-1")
+ self.assertEqual(controller.im_client.sent_messages[0][1], "late background result")
+ controller.session_turns.on_terminal_result.assert_not_called()
+ controller.mark_turn_complete.assert_not_called()
+ controller.agent_service.release_runtime_turn.assert_not_called()
+ turn_chunk.assert_not_awaited()
+ persist.assert_called_once()
+ self.assertEqual(persist.call_args.kwargs["metadata"]["activity_id"], "task-1")
+ self.assertTrue(persist.call_args.kwargs["metadata"]["detached"])
+
+ async def test_one_turn_can_emit_multiple_outputs_and_complete_once(self):
+ controller = _StubController(platform="slack")
+ controller.agent_service = type(
+ "Service",
+ (),
+ {
+ "emit_matches_runtime_turn": lambda self, context: True,
+ "release_runtime_turn": mock.Mock(),
+ },
+ )()
+ controller.session_turns = type(
+ "Turns",
+ (),
+ {"on_terminal_result": mock.Mock()},
+ )()
+ done = asyncio.Event()
+ controller.get_turn_sink = lambda key: {
+ "on_chunk": mock.AsyncMock(),
+ "done_event": done,
+ "turn_token": "turn-1",
+ }
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="slack",
+ platform_specific={
+ "agent_runtime_turn_key": "runtime-1",
+ "agent_runtime_turn_token": "runtime-turn-1",
+ "turn_token": "turn-1",
+ },
+ )
+
+ await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "first output",
+ output=MessageOutput(
+ completes_turn=False,
+ idempotency_key="output-1",
+ sequence=1,
+ ),
+ )
+ self.assertFalse(done.is_set())
+ controller.session_turns.on_terminal_result.assert_not_called()
+ controller.agent_service.release_runtime_turn.assert_not_called()
+
+ await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "final output",
+ output=MessageOutput(
+ completes_turn=True,
+ idempotency_key="output-2",
+ sequence=2,
+ ),
+ )
+
+ self.assertTrue(done.is_set())
+ self.assertEqual(
+ [item[1] for item in controller.im_client.sent_messages],
+ ["first output", "final output"],
+ )
+ controller.session_turns.on_terminal_result.assert_called_once_with(context, is_error=False)
+ controller.agent_service.release_runtime_turn.assert_called_once_with(context)
+
+ async def test_duplicate_terminal_output_still_settles_lifecycle(self):
+ controller = _StubController(platform="slack")
+ controller.agent_service = type(
+ "Service",
+ (),
+ {
+ "emit_matches_runtime_turn": lambda self, context: True,
+ "release_runtime_turn": mock.Mock(),
+ },
+ )()
+ controller.session_turns = type(
+ "Turns",
+ (),
+ {"on_terminal_result": mock.Mock()},
+ )()
+ controller.mark_turn_complete = mock.Mock()
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ dispatcher._collapse_status_bubble = mock.AsyncMock()
+ dispatcher._clear_consolidated_state = mock.AsyncMock()
+ dispatcher._record_agent_run_terminal_result = mock.Mock()
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="slack",
+ platform_specific={
+ "agent_runtime_turn_key": "runtime-1",
+ "agent_runtime_turn_token": "runtime-turn-1",
+ "turn_token": "turn-1",
+ },
+ )
+ output = MessageOutput(
+ completes_turn=True,
+ completes_run=True,
+ idempotency_key="terminal-output",
+ )
+
+ with mock.patch(
+ "core.message_dispatcher.agent_message_exists",
+ return_value=True,
+ ):
+ message_id = await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "already delivered",
+ output=output,
+ )
+
+ self.assertIsNone(message_id)
+ self.assertEqual(controller.im_client.sent_messages, [])
+ controller.session_turns.on_terminal_result.assert_called_once_with(context, is_error=False)
+ dispatcher._record_agent_run_terminal_result.assert_called_once_with(
+ context,
+ "already delivered",
+ None,
+ is_error=False,
+ output_semantics=output,
+ )
+ dispatcher._collapse_status_bubble.assert_awaited_once()
+ dispatcher._clear_consolidated_state.assert_awaited_once_with(context)
+ controller.mark_turn_complete.assert_called_once_with(context)
+ controller.agent_service.release_runtime_turn.assert_called_once_with(context)
+
async def test_slack_result_uses_native_markdown_sender_when_available(self):
im_client = _NativeMarkdownIMClient()
controller = _StubController(platform="slack", im_client=im_client)
diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.py
index c3dc96449..6f13f8bbe 100644
--- a/tests/test_message_dispatcher_scheduled.py
+++ b/tests/test_message_dispatcher_scheduled.py
@@ -3,12 +3,14 @@ from __future__ import annotations
import sys
import unittest
from pathlib import Path
+from types import SimpleNamespace
from unittest.mock import patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
import core.message_dispatcher as message_dispatcher_module
from core.message_dispatcher import ConsolidatedMessageDispatcher
+from core.message_output import MessageOutput
from modules.im import MessageContext
@@ -79,6 +81,193 @@ class _StubController:
class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
+ async def test_detached_output_uses_explicit_run_lineage_over_receiver_context(self):
+ controller = _StubController()
+ controller.agent_service = SimpleNamespace(
+ activities=SimpleNamespace(has_blocking_run_activity=lambda run_id: False),
+ emit_matches_runtime_turn=lambda context: False,
+ release_runtime_turn=lambda context: self.fail("detached output released current Turn"),
+ )
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id="C123",
+ platform="slack",
+ platform_specific={
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-stale-receiver",
+ "agent_runtime_turn_key": "runtime-1",
+ "agent_runtime_turn_token": "older-turn",
+ },
+ )
+ calls = []
+
+ class _Store:
+ def get_run(self, run_id):
+ return {"status": "running"}
+
+ def record_run_output(self, run_id, **kwargs):
+ calls.append((run_id, kwargs["terminal_status"]))
+
+ def close(self):
+ pass
+
+ with (
+ patch.object(
+ message_dispatcher_module,
+ "SQLiteBackgroundTaskStore",
+ return_value=_Store(),
+ ),
+ patch.object(message_dispatcher_module, "agent_message_exists", return_value=False),
+ ):
+ message_id = await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "background work finished",
+ output=MessageOutput(
+ completes_turn=False,
+ completes_run=True,
+ detached=True,
+ idempotency_key="activity-complete",
+ run_id="run-origin",
+ metadata={"run_ids": ["run-origin", "run-coalesced"]},
+ ),
+ )
+
+ self.assertEqual(message_id, "bot-msg-1")
+ self.assertEqual(
+ calls,
+ [
+ ("run-origin", "succeeded"),
+ ("run-coalesced", "succeeded"),
+ ],
+ )
+
+ async def test_empty_detached_result_can_complete_origin_run_without_current_turn(self):
+ controller = _StubController()
+ controller.agent_service = SimpleNamespace(
+ activities=SimpleNamespace(has_blocking_run_activity=lambda run_id: False),
+ emit_matches_runtime_turn=lambda context: False,
+ release_runtime_turn=lambda context: self.fail("detached output released current Turn"),
+ )
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id="C123",
+ platform="slack",
+ platform_specific={
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-empty",
+ "agent_runtime_turn_key": "runtime-1",
+ "agent_runtime_turn_token": "older-turn",
+ },
+ )
+ calls = []
+
+ class _Store:
+ def get_run(self, run_id):
+ return {"status": "running"}
+
+ def record_run_output(self, run_id, **kwargs):
+ calls.append((run_id, kwargs["text"], kwargs["terminal_status"]))
+
+ def close(self):
+ pass
+
+ with patch.object(
+ message_dispatcher_module,
+ "SQLiteBackgroundTaskStore",
+ return_value=_Store(),
+ ):
+ message_id = await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "",
+ output=MessageOutput(
+ completes_turn=False,
+ completes_run=True,
+ detached=True,
+ idempotency_key="empty-terminal",
+ ),
+ )
+
+ self.assertIsNone(message_id)
+ self.assertEqual(calls, [("run-empty", "", "succeeded")])
+
+ async def test_owned_activity_defers_run_terminal_but_not_later_detached_output(self):
+ controller = _StubController()
+ blocking = [True]
+ controller.agent_service = SimpleNamespace(
+ activities=SimpleNamespace(
+ has_blocking_run_activity=lambda run_id: blocking[0],
+ ),
+ emit_matches_runtime_turn=lambda context: True,
+ release_runtime_turn=lambda context: None,
+ )
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id="C123",
+ platform="slack",
+ platform_specific={
+ "suppress_delivery": True,
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-owned",
+ },
+ )
+ calls = []
+
+ class _Store:
+ def get_run(self, run_id):
+ return {"status": "running"}
+
+ def defer_run_terminal(self, run_id, *, terminal_status):
+ calls.append(("defer", run_id, terminal_status))
+
+ def record_run_output(self, run_id, **kwargs):
+ calls.append(("output", run_id, kwargs["output_id"], kwargs["terminal_status"]))
+
+ def close(self):
+ pass
+
+ with (
+ patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=_Store()),
+ patch.object(message_dispatcher_module, "agent_message_exists", return_value=False),
+ ):
+ await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "started background work",
+ output=MessageOutput(
+ completes_turn=True,
+ completes_run=True,
+ idempotency_key="output-1",
+ sequence=1,
+ ),
+ )
+ blocking[0] = False
+ await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "background work finished",
+ output=MessageOutput(
+ completes_turn=False,
+ completes_run=True,
+ detached=True,
+ idempotency_key="output-2",
+ sequence=2,
+ ),
+ )
+
+ self.assertEqual(
+ calls,
+ [
+ ("defer", "run-owned", "succeeded"),
+ ("output", "run-owned", "output-1", None),
+ ("output", "run-owned", "output-2", "succeeded"),
+ ],
+ )
+
async def test_result_message_finalizes_scheduled_delivery(self):
controller = _StubController()
dispatcher = ConsolidatedMessageDispatcher(controller)
diff --git a/tests/test_message_mirror.py b/tests/test_message_mirror.py
index cd0fd340f..3e9983d59 100644
--- a/tests/test_message_mirror.py
+++ b/tests/test_message_mirror.py
@@ -17,6 +17,7 @@ rely on:
from __future__ import annotations
import asyncio
+import json
import sys
from pathlib import Path
@@ -116,6 +117,41 @@ def test_persist_agent_writes_typed_agent_row_on_same_scope(isolated_state):
assert agent_row["scope_id"] == user_row["scope_id"]
+def test_agent_output_provenance_is_hidden_metadata_and_deduplicated(isolated_state):
+ ctx = _slack_ctx()
+ mirror_inbound(ctx, "ping")
+
+ first = persist_agent_message(
+ ctx,
+ "result",
+ "background result",
+ metadata={"activity_id": "task-1", "detached": True},
+ native_message_id="agent-output:claude:task-1:completion",
+ )
+ duplicate = persist_agent_message(
+ ctx,
+ "result",
+ "background result",
+ metadata={"activity_id": "task-1", "detached": True},
+ native_message_id="agent-output:claude:task-1:completion",
+ )
+
+ engine = create_sqlite_engine()
+ with engine.connect() as conn:
+ rows = conn.execute(
+ select(messages).where(messages.c.author == "agent")
+ ).mappings().all()
+
+ assert first is not None
+ assert duplicate is None
+ assert len(rows) == 1
+ assert rows[0]["content_text"] == "background result"
+ assert json.loads(rows[0]["metadata_json"]) == {
+ "activity_id": "task-1",
+ "detached": True,
+ }
+
+
def test_persist_agent_reuses_cached_sqlite_engine(isolated_state, monkeypatch):
import storage.db as sqlite_db
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index f09119e89..ec20fbc9c 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -12,6 +12,7 @@ from sqlalchemy import select
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from config import paths
+from core.session_activities import SessionActivityRegistry
from core.scheduled_tasks import (
ParsedSessionKey,
ScheduledTaskService,
@@ -1989,6 +1990,355 @@ def test_agent_run_callback_enqueues_only_result_to_caller_session(tmp_path: Pat
assert callback_run["message"] == "complete delegated result"
+def test_agent_run_forwards_multiple_outputs_and_completes_once(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="codex",
+ callback_session_id=caller_session_id,
+ )
+ 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,
+ )
+ assert request_store.claim(request.id) is not None
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+ assert sqlite_store.defer_run_terminal(
+ request.id,
+ terminal_status="succeeded",
+ ) is True
+
+ first = sqlite_store.record_run_output(
+ request.id,
+ output_id="output-1",
+ text="first callback output",
+ sequence=1,
+ provenance={"run_id": request.id},
+ )
+ service.forward_run_outputs([request.id])
+ running = request_store.get_run(request.id)
+
+ assert first["recorded"] is True
+ assert first["terminal_transition"] is False
+ assert running is not None
+ assert running["status"] == "running"
+ assert running["callback_status"] == "pending"
+ assert running["result_payload"]["deferred_terminal_status"] == "succeeded"
+
+ second = sqlite_store.record_run_output(
+ request.id,
+ output_id="output-2",
+ text="second callback output",
+ sequence=2,
+ provenance={"run_id": request.id},
+ terminal_status="succeeded",
+ )
+ service.forward_run_outputs([request.id])
+ terminal = request_store.get_run(request.id)
+ assert terminal is not None
+ completed_at = terminal["completed_at"]
+
+ duplicate = sqlite_store.record_run_output(
+ request.id,
+ output_id="output-2",
+ text="second callback output",
+ sequence=2,
+ provenance={"run_id": request.id},
+ terminal_status="succeeded",
+ )
+ service.forward_run_outputs([request.id])
+ asyncio.run(service._drain_callbacks())
+
+ original = request_store.get_run(request.id)
+ assert original is not None
+ assert second["recorded"] is True
+ assert second["terminal_transition"] is True
+ assert duplicate["recorded"] is False
+ assert duplicate["terminal_transition"] is False
+ assert original["status"] == "succeeded"
+ assert original["completed_at"] == completed_at
+ assert original["callback_status"] == "sent"
+ assert "deferred_terminal_status" not in original["result_payload"]
+ assert original["result_text"] == "first callback output\n\nsecond callback output"
+ assert [item["id"] for item in original["result_payload"]["outputs"]] == [
+ "output-1",
+ "output-2",
+ ]
+
+ 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] == [
+ "first callback output",
+ "second callback output",
+ ]
+ assert {run["metadata"]["callback_output_id"] for run in callback_runs} == {
+ "output-1",
+ "output-2",
+ }
+
+
+ ("terminal_status", "expected_message"),
+ [
+ ("failed", "Error: backend disconnected"),
+ ("canceled", "The run was canceled before producing a result."),
+ ],
+)
+def test_agent_run_forwards_terminal_status_after_partial_output(
+ tmp_path: Path,
+ monkeypatch,
+ terminal_status: str,
+ expected_message: str,
+) -> 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="codex",
+ callback_session_id=caller_session_id,
+ )
+ 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,
+ )
+ assert request_store.claim(request.id) is not None
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+ recorded = sqlite_store.record_run_output(
+ request.id,
+ output_id="output-1",
+ text="partial callback output",
+ sequence=1,
+ provenance={"run_id": request.id},
+ )
+ assert recorded["recorded"] is True
+ service.forward_run_outputs([request.id])
+ if terminal_status == "failed":
+ request_store.complete(request, ok=False, error="backend disconnected")
+ else:
+ assert request_store.mark_run_canceled(request.id) is True
+
+ asyncio.run(service._drain_callbacks())
+ asyncio.run(service._drain_callbacks())
+
+ original = request_store.get_run(request.id)
+ assert original is not None
+ assert original["status"] == terminal_status
+ assert original["callback_status"] == "sent"
+ 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] == [
+ "partial callback output",
+ expected_message,
+ ]
+ assert callback_runs[1]["source_actor"] == f"{request.id}:terminal:{terminal_status}"
+ assert original["callback_run_id"] == callback_runs[1]["id"]
+
+
+def test_duplicate_terminal_output_does_not_append_result_text_again(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id="target-session",
+ message="delegated work",
+ agent_name="claude",
+ )
+ assert request_store.claim(request.id) is not None
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+ first = sqlite_store.record_run_output(
+ request.id,
+ output_id="output-1",
+ text="callback output",
+ )
+ assert first["recorded"] is True
+ assert sqlite_store.defer_run_terminal(
+ request.id,
+ terminal_status="succeeded",
+ ) is True
+
+ duplicate = sqlite_store.record_run_output(
+ request.id,
+ output_id="output-1",
+ text="callback output",
+ terminal_status="succeeded",
+ )
+
+ terminal = request_store.get_run(request.id)
+ assert terminal is not None
+ assert duplicate["recorded"] is False
+ assert duplicate["terminal_transition"] is True
+ assert terminal["result_text"] == "callback output"
+ assert [item["id"] for item in terminal["result_payload"]["outputs"]] == [
+ "output-1",
+ ]
+ assert "deferred_terminal_status" not in terminal["result_payload"]
+
+
+ ("activity_status", "expected_run_status"),
+ [
+ ("failed", "failed"),
+ ("stopped", "canceled"),
+ ("killed", "canceled"),
+ ],
+)
+def test_terminal_owned_activity_settles_deferred_run_once(
+ tmp_path: Path,
+ monkeypatch,
+ activity_status: str,
+ expected_run_status: str,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id="target-session",
+ message="delegated work",
+ agent_name="claude",
+ )
+ controller = _avibe_controller_double(
+ gate=SimpleNamespace(submit_scheduled=lambda *_args, **_kwargs: None, in_flight={}),
+ handle_scheduled_message=lambda *_args, **_kwargs: None,
+ )
+ registry = SessionActivityRegistry()
+ controller.agent_service = SimpleNamespace(activities=registry)
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+ assert request_store.claim(request.id) is not None
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+ assert sqlite_store.defer_run_terminal(
+ request.id,
+ terminal_status="succeeded",
+ ) is True
+ registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="target-session",
+ activity_id="task-failed",
+ kind="background_task",
+ run_id=request.id,
+ )
+ activity = registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-failed",
+ status=activity_status,
+ )
+ assert activity is not None
+
+ assert service.settle_activity_runs(activity) == [request.id]
+ terminal = request_store.get_run(request.id)
+ assert terminal is not None
+ completed_at = terminal["completed_at"]
+ assert terminal["status"] == expected_run_status
+ assert terminal["error"] == f"Background Activity task-failed {activity_status}"
+ assert "deferred_terminal_status" not in terminal["result_payload"]
+
+ assert service.settle_activity_runs(activity) == []
+ assert request_store.get_run(request.id)["completed_at"] == completed_at
+
+
+def test_failed_activity_intent_survives_until_last_owned_activity_finishes(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id="target-session",
+ message="delegated work",
+ agent_name="claude",
+ )
+ controller = _avibe_controller_double(
+ gate=SimpleNamespace(submit_scheduled=lambda *_args, **_kwargs: None, in_flight={}),
+ handle_scheduled_message=lambda *_args, **_kwargs: None,
+ )
+ registry = SessionActivityRegistry()
+ controller.agent_service = SimpleNamespace(activities=registry)
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+ assert request_store.claim(request.id) is not None
+ assert request_store.defer_run_terminal(
+ request.id,
+ terminal_status="succeeded",
+ ) is True
+ for activity_id in ("task-failed", "task-running"):
+ registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="target-session",
+ activity_id=activity_id,
+ kind="background_task",
+ run_id=request.id,
+ )
+
+ failed = registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-failed",
+ status="failed",
+ )
+ assert failed is not None
+ assert service.settle_activity_runs(failed) == []
+ running = request_store.get_run(request.id)
+ assert running is not None
+ assert running["status"] == "running"
+ assert running["result_payload"]["deferred_terminal_status"] == "failed"
+
+ completed = registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-running",
+ status="completed",
+ )
+ assert completed is not None
+ assert service.settle_activity_runs(completed) == []
+ sqlite_store = request_store._sqlite
+ assert sqlite_store is not None
+ result = sqlite_store.record_run_output(
+ request.id,
+ output_id="task-running:completion",
+ text="The other task completed",
+ terminal_status="succeeded",
+ )
+
+ terminal = request_store.get_run(request.id)
+ assert terminal is not None
+ assert result["terminal_transition"] is True
+ assert terminal["status"] == "failed"
+ assert "deferred_terminal_status" not in terminal["result_payload"]
+
+
def test_agent_run_callback_builds_failure_message_without_result_text(tmp_path: Path, monkeypatch) -> None:
monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
caller_session_id = _make_avibe_session(monkeypatch, tmp_path)
diff --git a/tests/test_session_activities.py b/tests/test_session_activities.py
new file mode 100644
index 000000000..41a01e4a4
--- /dev/null
+++ b/tests/test_session_activities.py
@@ -0,0 +1,180 @@
+from __future__ import annotations
+
+from contextlib import nullcontext
+from types import SimpleNamespace
+from unittest import mock
+
+from core.session_activities import SessionActivityRegistry
+from core.session_turns import SessionTurnManager
+
+
+def test_activity_lifecycle_keeps_state_axes_orthogonal():
+ registry = SessionActivityRegistry()
+
+ registry.set_connection(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ state="connected",
+ )
+ registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ activity_id="task-1",
+ kind="background_task",
+ description="Run checks",
+ )
+
+ state = registry.session_state("ses-1")
+ assert state["connection"] == "connected"
+ assert [item["id"] for item in state["background_activities"]] == ["task-1"]
+
+ completed = registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-1",
+ status="completed",
+ expects_output=True,
+ )
+ assert completed is not None
+ assert registry.session_state("ses-1") == {
+ "background_activities": [],
+ "connection": "connected",
+ }
+
+ claimed = registry.claim_completed_output("claude", "runtime-1")
+ assert claimed is not None
+ assert claimed.id == "task-1"
+ assert registry.claim_completed_output("claude", "runtime-1") is None
+
+
+def test_activity_updates_are_independent_and_runtime_disconnect_terminates_all():
+ registry = SessionActivityRegistry()
+ for task_id in ("task-1", "task-2"):
+ registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ activity_id=task_id,
+ kind="background_task",
+ )
+
+ registry.progress(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ activity_id="task-2",
+ description="Still running",
+ metadata={"last_tool_name": "Bash"},
+ )
+ registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-1",
+ status="failed",
+ )
+
+ active = registry.active_for_runtime("claude", "runtime-1")
+ assert [item.id for item in active] == ["task-2"]
+ assert active[0].metadata["last_tool_name"] == "Bash"
+
+ completed = registry.end_runtime("claude", "runtime-1", status="disconnected")
+ assert registry.active_for_runtime("claude", "runtime-1") == []
+ assert registry.session_state("ses-1")["connection"] == "disconnected"
+ assert [(item.id, item.status) for item in completed] == [
+ ("task-2", "disconnected"),
+ ]
+
+
+def test_runtime_disconnect_preserves_completed_output_until_delivery():
+ registry = SessionActivityRegistry()
+ registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ activity_id="task-1",
+ kind="background_task",
+ )
+ registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-1",
+ status="completed",
+ metadata={"summary": "Background work finished"},
+ expects_output=True,
+ )
+
+ registry.end_runtime("claude", "runtime-1", status="disconnected")
+
+ claimed = registry.claim_completed_output("claude", "runtime-1")
+ assert claimed is not None
+ assert claimed.id == "task-1"
+ assert claimed.metadata["summary"] == "Background work finished"
+
+
+def test_turn_state_composes_foreground_inbox_activity_and_connection_axes():
+ registry = SessionActivityRegistry()
+ registry.set_connection(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ state="connected",
+ )
+ registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ activity_id="task-1",
+ kind="background_task",
+ )
+ manager = SessionTurnManager(
+ controller=SimpleNamespace(
+ agent_service=SimpleNamespace(activities=registry),
+ )
+ )
+ manager._engine = SimpleNamespace(begin=lambda: nullcontext(object()))
+
+ with mock.patch(
+ "core.session_turns.messages_service.list_queued",
+ return_value=[{"id": "queued-1"}],
+ ):
+ state = manager.turn_state("ses-1")
+
+ assert state["in_flight"] is False
+ assert state["foreground"] == "idle"
+ assert state["pending_input_count"] == 1
+ assert state["connection"] == "connected"
+ assert [item["id"] for item in state["background_activities"]] == ["task-1"]
+
+
+def test_only_owned_non_detached_activities_block_run_completion():
+ registry = SessionActivityRegistry()
+ registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ activity_id="task-owned",
+ kind="background_task",
+ run_id="run-1",
+ )
+ registry.start(
+ backend="claude",
+ runtime_key="runtime-2",
+ session_id="ses-1",
+ activity_id="task-detached",
+ kind="background_task",
+ run_id="run-2",
+ detached_from_run=True,
+ )
+
+ assert registry.has_blocking_run_activity("run-1") is True
+ assert registry.has_blocking_run_activity("run-2") is False
+
+ registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-owned",
+ status="completed",
+ )
+ assert registry.has_blocking_run_activity("run-1") is False