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): recover full-duplex Session activities (#873)

Call White9fadd2ca6f1c
diff --git a/core/agent_auth_service.py b/core/agent_auth_service.py
index 5b9fdc7ef..9ec8aabfd 100644
--- a/core/agent_auth_service.py
+++ b/core/agent_auth_service.py
@@ -34,6 +34,7 @@ from modules.agents.opencode.message_processor import (
from modules.agents.opencode.utils import resolve_opencode_model_id, resolve_opencode_reasoning_effort
from modules.im import InlineButton, InlineKeyboard, MessageContext
from core.resource_governance import governor_from_controller
+from core.message_output import terminal_turn_output
from vibe.i18n import t as i18n_t
from vibe.opencode_config import remove_opencode_provider_api_key
@@ -917,7 +918,13 @@ class AgentAuthService:
# without adding a second visible message (the recovery button above is the
# visible one). No-op off-workbench.
try:
- await self.controller.emit_agent_message(context, "result", "", is_error=True)
+ await self.controller.emit_agent_message(
+ context,
+ "result",
+ "",
+ is_error=True,
+ output=terminal_turn_output(),
+ )
except Exception:
logger.debug("auth recovery: failed to settle turn status", exc_info=True)
return True
diff --git a/core/controller.py b/core/controller.py
index a66020077..1748eacd8 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -641,11 +641,18 @@ class Controller:
self.message_handler.set_session_handler(self.session_handler)
def _init_agents(self):
+ from core.session_activities import SessionActivityRegistry
from modules.agents.claude_agent import ClaudeAgent
from modules.agents.codex import CodexAgent
from modules.agents.opencode import OpenCodeAgent
+ from storage.db import get_cached_sqlite_engine
+ from storage.session_activities import SQLiteSessionActivityStore
- self.agent_service = AgentService(self)
+ activity_store = SQLiteSessionActivityStore(get_cached_sqlite_engine())
+ self.agent_service = AgentService(
+ self,
+ activities=SessionActivityRegistry(activity_store),
+ )
self.agent_service.register(ClaudeAgent(self))
if self.config.codex:
try:
diff --git a/core/handlers/message_handler.py b/core/handlers/message_handler.py
index 850a33da8..ea8847dc3 100644
--- a/core/handlers/message_handler.py
+++ b/core/handlers/message_handler.py
@@ -12,6 +12,7 @@ from core.audio_asr import (
detect_audio_mime_from_sample,
format_audio_transcript_echo,
)
+from core.message_output import terminal_output_for, terminal_turn_output
from modules.agents.base import AgentRequest
from modules.agents.catalog import display_name_for_backend, is_agent_backend
from modules.im import MessageContext
@@ -80,6 +81,7 @@ class MessageHandler(BaseHandler):
async def _handle_turn(self, context: MessageContext, message: str, *, source: str) -> Optional[str]:
"""Shared turn-processing pipeline used by both human and scheduled turns."""
processing_indicator = None
+ request: AgentRequest | None = None
# Tracks whether we actually dispatched an agent turn (whose reply
# streams in asynchronously). If we leave this method WITHOUT having
# dispatched — early returns, missing/disabled backend, errors — no
@@ -508,7 +510,13 @@ class MessageHandler(BaseHandler):
# turn through the OUTBOUND status chokepoint: an empty terminal
# error result turns the dot red + releases the SSE waiter (the
# missing-agent message was already shown above). No separate latch.
- await self.controller.emit_agent_message(context, "result", "", is_error=True)
+ await self.controller.emit_agent_message(
+ context,
+ "result",
+ "",
+ is_error=True,
+ output=terminal_output_for(request),
+ )
# Clean up reaction on error
await self._remove_ack_reaction(context, request)
return f"agent '{agent_name}' is not available"
@@ -519,15 +527,15 @@ class MessageHandler(BaseHandler):
except Exception as e:
logger.error(f"Error processing user message: {e}", exc_info=True)
# Clean up reaction on any exception
- # Use try/except to safely access possibly-unbound local variables
try:
- try:
- # Try using request object if it was created. This also
- # clears typing indicators, which do not have a reaction ID.
- await self._remove_ack_reaction(context, request) # type: ignore[possibly-undefined]
- except NameError:
- if processing_indicator is not None:
- await self.controller.processing_indicator.finish(processing_indicator)
+ # Use the request once it exists; otherwise finish any indicator
+ # selected during pre-dispatch context preparation.
+ if request is not None:
+ await self._remove_ack_reaction(context, request)
+ elif processing_indicator is not None:
+ await self.controller.processing_indicator.finish(
+ processing_indicator
+ )
except Exception as cleanup_err:
logger.debug(f"Failed to clean up reaction on error: {cleanup_err}")
error_text = self.formatter.format_error(self._t("error.processMessageFailed", error=str(e)))
@@ -537,7 +545,17 @@ class MessageHandler(BaseHandler):
# ...then settle the failed turn through the OUTBOUND status chokepoint:
# an empty terminal error result turns the dot red + releases the SSE
# waiter (the visible error was sent + streamed above). No separate latch.
- await self.controller.emit_agent_message(context, "result", "", is_error=True)
+ await self.controller.emit_agent_message(
+ context,
+ "result",
+ "",
+ is_error=True,
+ output=(
+ terminal_output_for(request)
+ if request is not None
+ else terminal_turn_output()
+ ),
+ )
return str(e)
finally:
if not agent_dispatched:
diff --git a/core/message_dispatcher.py b/core/message_dispatcher.py
index e3e21d5f7..a3219f132 100644
--- a/core/message_dispatcher.py
+++ b/core/message_dispatcher.py
@@ -1037,7 +1037,12 @@ class ConsolidatedMessageDispatcher:
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:
+ def _forward_agent_run_outputs(
+ self,
+ run_ids: list[str],
+ *,
+ raise_on_error: bool = False,
+ ) -> None:
service = getattr(self.controller, "scheduled_task_service", None)
forward = getattr(service, "forward_run_outputs", None)
if not callable(forward):
@@ -1046,6 +1051,8 @@ class ConsolidatedMessageDispatcher:
forward(run_ids)
except Exception:
logger.warning("Failed to forward Agent Run outputs for %s", ",".join(run_ids), exc_info=True)
+ if raise_on_error:
+ raise
def _record_agent_run_terminal_result(
self,
@@ -1059,6 +1066,7 @@ class ConsolidatedMessageDispatcher:
) -> None:
payload = context.platform_specific or {}
semantics = output_semantics or MessageOutput(completes_turn=True)
+ require_confirmation = semantics.requires_delivery_for_run_settlement
run_ids: list[str] = []
explicit_run_id = str(semantics.run_id or "").strip()
if explicit_run_id:
@@ -1090,10 +1098,15 @@ class ConsolidatedMessageDispatcher:
)
except Exception as err:
logger.warning("Failed to record %s for %s: %s", log_label, ",".join(run_ids), err)
+ if require_confirmation:
+ raise
finally:
if store is not None:
store.close()
- self._forward_agent_run_outputs(run_ids)
+ self._forward_agent_run_outputs(
+ run_ids,
+ raise_on_error=require_confirmation,
+ )
def _record_suppressed_agent_run_terminal_result(
self,
@@ -1455,7 +1468,11 @@ class ConsolidatedMessageDispatcher:
await self._collapse_status_bubble(context, im_client, reason=terminal_reason)
await self._clear_consolidated_state(context)
self._signal_turn_complete(context)
- return None
+ # A previously persisted output is a successful idempotent
+ # delivery attempt. Return its stable identity so a recovered
+ # Activity can acknowledge its durable Outbox snapshot instead
+ # of retrying forever after a crash between emit and ack.
+ return native_output_id
finally:
if mutates_turn_lifecycle:
await self._finish_processing_indicator_turn(context)
@@ -1758,18 +1775,20 @@ class ConsolidatedMessageDispatcher:
# mutated) and is a no-op when there is no footer.
persisted_result_text = self._fold_footer(persist_text, folded_footer)
- self._record_agent_run_terminal_result(
- context,
- persisted_result_text,
- primary_message_id,
- is_error=is_error,
- output_semantics=output_semantics,
- )
+ if not output_semantics.requires_delivery_for_run_settlement:
+ self._record_agent_run_terminal_result(
+ context,
+ persisted_result_text,
+ primary_message_id,
+ is_error=is_error,
+ output_semantics=output_semantics,
+ )
# Persist the delivered result (cleaned text == what was shown).
# avibe always persists (SSE is its delivery); for IM a result that
# failed every send/upload (primary_message_id is None) is NOT
# recorded, matching the old outbound mirror's success-only rule.
+ persisted_output = None
if persists_without_delivery or primary_message_id is not None:
# A failed terminal result persists as type='error' so it shows in
# the transcript/inbox like any terminal message but is NOT counted
@@ -1787,7 +1806,7 @@ class ConsolidatedMessageDispatcher:
text, include_quick_replies=quick_replies_on, keep_file_links=True
)
avibe_text = self._fold_footer(avibe_enhanced.text or persist_text, folded_footer)
- persist_agent_message(
+ persisted_output = persist_agent_message(
target_context,
result_type,
avibe_text,
@@ -1796,7 +1815,7 @@ class ConsolidatedMessageDispatcher:
native_message_id=native_output_id,
)
else:
- persist_agent_message(
+ persisted_output = persist_agent_message(
target_context,
result_type,
persisted_result_text,
@@ -1804,6 +1823,22 @@ class ConsolidatedMessageDispatcher:
native_message_id=native_output_id,
)
+ if output_semantics.requires_delivery_for_run_settlement:
+ if persisted_output is None and not (
+ native_output_id
+ and agent_message_exists(target_context, native_output_id)
+ ):
+ raise RuntimeError(
+ "Activity output was not durably persisted after delivery"
+ )
+ self._record_agent_run_terminal_result(
+ context,
+ persisted_result_text,
+ primary_message_id,
+ is_error=is_error,
+ output_semantics=output_semantics,
+ )
+
if primary_message_id and display_text and not output_semantics.detached:
# Stream the delivered result to live consumers (avibe SSE).
await _stream_chunk(
diff --git a/core/message_output.py b/core/message_output.py
index ace7fc0d6..ffead5a0a 100644
--- a/core/message_output.py
+++ b/core/message_output.py
@@ -1,8 +1,8 @@
"""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.
+separate. Live runtime paths carry explicit lifecycle authority; one quarantined
+dispatcher fallback preserves older callers that still use terminal ``result``.
"""
from __future__ import annotations
@@ -15,7 +15,7 @@ from typing import Any, Mapping
class MessageOutput:
"""Lifecycle and hidden provenance for one user-visible agent output."""
- completes_turn: bool = True
+ completes_turn: bool = False
completes_run: bool | None = None
detached: bool = False
idempotency_key: str | None = None
@@ -23,6 +23,7 @@ class MessageOutput:
causation_id: str | None = None
sequence: int | None = None
run_id: str | None = None
+ requires_delivery_for_run_settlement: bool = False
metadata: Mapping[str, Any] = field(default_factory=dict)
@property
@@ -59,11 +60,15 @@ class MessageOutput:
return None
spec = getattr(context, "platform_specific", None) or {}
target = spec.get("agent_session_target")
- backend = str(spec.get("vibe_agent_backend") or "").strip()
+ backend = str(
+ self.metadata.get("backend") or spec.get("vibe_agent_backend") or ""
+ ).strip()
if not backend and isinstance(target, dict):
backend = str(target.get("agent_backend") or "").strip()
+ activity_lineage = f"activity:{self.activity_id}" if self.activity_id else ""
lineage = str(
self.run_id
+ or activity_lineage
or spec.get("task_execution_id")
or spec.get("agent_session_id")
or spec.get("agent_runtime_turn_key")
@@ -73,8 +78,28 @@ class MessageOutput:
def output_for_message(message_type: str, output: MessageOutput | None) -> MessageOutput:
- """Return explicit semantics, preserving the legacy terminal-result contract."""
+ """Normalize output semantics at the legacy dispatcher boundary.
+
+ Live backend and shared-core paths provide explicit ``MessageOutput``. The
+ result fallback remains only as a compatibility adapter for external callers
+ while the visible Message role and lifecycle authority evolve separately.
+ """
if output is not None:
return output
- return MessageOutput(completes_turn=(message_type == "result"))
+ if message_type == "result":
+ return terminal_turn_output()
+ return MessageOutput(completes_turn=False, completes_run=False)
+
+
+def terminal_turn_output() -> MessageOutput:
+ """Explicitly grant one output authority to settle its Turn and Run."""
+
+ return MessageOutput(completes_turn=True, completes_run=True)
+
+
+def terminal_output_for(request: Any) -> MessageOutput:
+ """Use a request's explicit output policy or the terminal Turn default."""
+
+ output = getattr(request, "output", None)
+ return output if isinstance(output, MessageOutput) else terminal_turn_output()
diff --git a/core/scheduled_tasks.py b/core/scheduled_tasks.py
index b559ecbac..52eecb58b 100644
--- a/core/scheduled_tasks.py
+++ b/core/scheduled_tasks.py
@@ -21,6 +21,8 @@ from sqlalchemy.exc import SQLAlchemyError
from config import paths
from core.message_context import resolve_context_platform
+from core.reply_enhancer import strip_silent_blocks
+from core.session_activities import activity_completion_output
from modules.im import MessageContext
from storage.db import create_sqlite_engine, get_cached_sqlite_engine
from storage.background import SQLiteBackgroundTaskStore
@@ -1072,6 +1074,18 @@ class TaskExecutionStore:
]
return sorted(runs, key=lambda item: (item.get("completed_at") or "", item.get("id") or ""))[:limit]
+ def list_deferred_runs(self) -> list[dict[str, Any]]:
+ if self._sqlite is not None:
+ return self._sqlite.list_deferred_runs()
+ return [
+ run
+ for run in self._list_file_runs()
+ if isinstance(run.get("result_payload"), dict)
+ and run["result_payload"].get("deferred_terminal_status")
+ and (_normalize_requested_run_status(run.get("status")) or run.get("status"))
+ not in TERMINAL_RUN_STATUSES
+ ]
+
def find_callback_run(
self,
*,
@@ -1543,10 +1557,207 @@ class ScheduledTaskService:
self._inflight_sessions: set[str] = set()
# Cache of session_id -> canonical lock key (resolution hits SQLite).
self._session_lock_cache: Dict[str, str] = {}
+ self._pending_recovered_activity_terminals: list[Any] = []
self._requires_service_lease = runtime.service_instance_lock_attached_to_process()
self._drain_dirty = True
+ self._recover_activity_lifecycle()
self.request_store.recover_processing()
+ @staticmethod
+ def _activity_run_ids(activity: Any) -> list[str]:
+ run_ids: list[str] = []
+ primary = str(getattr(activity, "run_id", "") or "").strip()
+ if primary:
+ run_ids.append(primary)
+ metadata = getattr(activity, "metadata", None) or {}
+ 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)
+ return run_ids
+
+ def _activity_registry(self) -> Any:
+ return getattr(getattr(self.controller, "agent_service", None), "activities", None)
+
+ def _recover_activity_lifecycle(self) -> None:
+ """Reconcile persisted Activity blockers before queued-Run recovery."""
+
+ registry = self._activity_registry()
+ drain_terminals = getattr(registry, "drain_recovered_terminals", None)
+ ack_terminal = getattr(registry, "ack_recovered_terminal", None)
+ has_pending_output = getattr(registry, "has_pending_run_output", None)
+ if callable(drain_terminals):
+ for activity in drain_terminals():
+ try:
+ self.settle_activity_runs(activity)
+ except Exception:
+ self._pending_recovered_activity_terminals.append(activity)
+ logger.warning(
+ "Failed to settle recovered terminal Activity %s during startup",
+ getattr(activity, "id", ""),
+ exc_info=True,
+ )
+ continue
+ if callable(has_pending_output) and any(
+ has_pending_output(run_id)
+ for run_id in self._activity_run_ids(activity)
+ ):
+ self._pending_recovered_activity_terminals.append(activity)
+ continue
+ try:
+ if callable(ack_terminal):
+ ack_terminal(activity)
+ except Exception:
+ self._pending_recovered_activity_terminals.append(activity)
+ logger.warning(
+ "Failed to acknowledge recovered terminal Activity %s during startup",
+ getattr(activity, "id", ""),
+ exc_info=True,
+ )
+
+ has_blocker = getattr(registry, "has_blocking_run_activity", None)
+ for run in self.request_store.list_deferred_runs():
+ run_id = str(run.get("id") or "").strip()
+ if not run_id:
+ continue
+ if callable(has_blocker) and has_blocker(run_id):
+ continue
+ if callable(has_pending_output) and has_pending_output(run_id):
+ continue
+ if self.request_store.settle_deferred_run(run_id):
+ self._drain_dirty = True
+
+ def _settle_pending_recovered_activity_terminals(self) -> None:
+ """Acknowledge terminal snapshots only after owned output leaves the Outbox."""
+
+ if not self._pending_recovered_activity_terminals:
+ return
+ registry = self._activity_registry()
+ has_pending_output = getattr(registry, "has_pending_run_output", None)
+ ack_terminal = getattr(registry, "ack_recovered_terminal", None)
+ remaining: list[Any] = []
+ for activity in self._pending_recovered_activity_terminals:
+ if callable(has_pending_output) and any(
+ has_pending_output(run_id)
+ for run_id in self._activity_run_ids(activity)
+ ):
+ remaining.append(activity)
+ continue
+ try:
+ self.settle_activity_runs(activity)
+ if callable(ack_terminal):
+ ack_terminal(activity)
+ except Exception:
+ remaining.append(activity)
+ logger.warning(
+ "Failed to settle recovered terminal Activity %s",
+ getattr(activity, "id", ""),
+ exc_info=True,
+ )
+ self._pending_recovered_activity_terminals = remaining
+
+ def _settle_activity_without_output(self, activity: Any) -> None:
+ """Finish an Activity Run without manufacturing user-visible text."""
+
+ for run_id in self._activity_run_ids(activity):
+ self.request_store.defer_run_terminal(
+ run_id,
+ terminal_status="succeeded",
+ )
+ if self.request_store.settle_deferred_run(run_id):
+ self._drain_dirty = True
+
+ async def _deliver_recovered_activity_output(self, activity: Any) -> None:
+ registry = self._activity_registry()
+ summary = str((getattr(activity, "metadata", None) or {}).get("summary") or "").strip()
+ session_id = str(getattr(activity, "session_id", "") or "").strip()
+ if not strip_silent_blocks(summary).strip() or not session_id:
+ self._settle_activity_without_output(activity)
+ registry.ack_completed_output(activity)
+ return
+
+ try:
+ target = resolve_session_id_target(session_id)
+ except ValueError:
+ logger.info(
+ "Recovered Activity %s has no live Session route; settling without output",
+ getattr(activity, "id", ""),
+ )
+ self._settle_activity_without_output(activity)
+ registry.ack_completed_output(activity)
+ return
+
+ if target.suppress_delivery:
+ logger.info(
+ "Recovered Activity %s targets a no-delivery Session; settling without output",
+ getattr(activity, "id", ""),
+ )
+ self._settle_activity_without_output(activity)
+ registry.ack_completed_output(activity)
+ return
+
+ delivery_target = target.session_key
+ delivery_key = str(
+ (getattr(activity, "metadata", None) or {}).get("delivery_key_external")
+ or ""
+ ).strip()
+ if delivery_key and delivery_key != target.session_key.to_key():
+ delivery_target = parse_session_key(delivery_key)
+ if delivery_target.platform != target.session_key.platform:
+ raise ValueError("recovered Activity delivery target changed platform")
+
+ context = await self._build_context(
+ target.session_key,
+ delivery_target=delivery_target,
+ execution_id=f"activity:{getattr(activity, 'backend', '')}:{getattr(activity, 'id', '')}",
+ trigger_kind="activity_recovery",
+ session_id=session_id,
+ agent_name=target.agent_name,
+ target_info=target,
+ metadata={
+ "source_kind": "activity_recovery",
+ "source_actor": getattr(activity, "id", None),
+ },
+ )
+ message_id = await self.controller.emit_agent_message(
+ context,
+ "result",
+ summary,
+ output=activity_completion_output(
+ activity,
+ detached=True,
+ completes_turn=False,
+ ),
+ )
+ if message_id is None:
+ raise RuntimeError("recovered Activity output was not persisted or delivered")
+ registry.ack_completed_output(activity)
+
+ async def _drain_recovered_activity_outputs(self) -> None:
+ registry = self._activity_registry()
+ runtimes = getattr(registry, "recovered_output_runtimes", None)
+ claim = getattr(registry, "claim_completed_output", None)
+ if not callable(runtimes) or not callable(claim):
+ return
+ for backend, runtime_key in runtimes():
+ while True:
+ activity = claim(backend, runtime_key, recovered_only=True)
+ if activity is None:
+ break
+ try:
+ await self._deliver_recovered_activity_output(activity)
+ except Exception:
+ registry.requeue_completed_output(activity, recovered=True)
+ logger.warning(
+ "Failed to deliver recovered Activity output %s",
+ getattr(activity, "id", ""),
+ exc_info=True,
+ )
+ break
+ self._settle_pending_recovered_activity_terminals()
+
def validate_platform(self, platform: str) -> None:
# The real IM platforms have a settings manager; ``avibe`` (the web
# workbench) is a virtual platform with an IM client but no settings
@@ -1646,6 +1857,7 @@ class ScheduledTaskService:
if not self._owns_service_instance():
return
try:
+ await self._drain_recovered_activity_outputs()
store_changed = self.store.maybe_reload()
request_store_changed = self.request_store.maybe_reload()
should_drain = store_changed or request_store_changed or self._drain_dirty
@@ -1860,6 +2072,7 @@ class ScheduledTaskService:
registry = getattr(getattr(self.controller, "agent_service", None), "activities", None)
has_blocker = getattr(registry, "has_blocking_run_activity", None)
+ has_pending_output = getattr(registry, "has_pending_run_output", None)
settled: list[str] = []
for run_id in run_ids:
self.request_store.defer_run_terminal(
@@ -1868,6 +2081,8 @@ class ScheduledTaskService:
)
if callable(has_blocker) and has_blocker(run_id):
continue
+ if callable(has_pending_output) and has_pending_output(run_id):
+ continue
error = f"Background Activity {getattr(activity, 'id', '')} {activity_status}"
if self.request_store.settle_deferred_run(
run_id,
diff --git a/core/session_activities.py b/core/session_activities.py
index ea38fcb27..b53bb9043 100644
--- a/core/session_activities.py
+++ b/core/session_activities.py
@@ -1,22 +1,30 @@
-"""Backend-neutral, process-local Activity lifecycle registry.
+"""Backend-neutral 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 foreground Turn ownership. The registry can persist restart snapshots in
+the existing runtime-record aggregate; durable Messages and Harness Runs retain
+their own persistence aggregates.
"""
from __future__ import annotations
+import logging
import threading
import time
from collections import defaultdict, deque
from dataclasses import dataclass, field, replace
from datetime import datetime, timezone
-from typing import Any
+from typing import Any, Callable
+
+from core.message_output import MessageOutput
+
+
+logger = logging.getLogger(__name__)
TERMINAL_ACTIVITY_STATUSES = frozenset({"completed", "failed", "stopped", "killed", "disconnected"})
CONNECTION_STATES = frozenset({"connected", "reconnecting", "disconnected", "unknown"})
+TERMINAL_SNAPSHOT_PHASE = "terminal"
def _now_iso() -> str:
@@ -62,22 +70,221 @@ class SessionActivity:
"completed_at": self.completed_at,
}
+ @classmethod
+ def from_dict(cls, payload: dict[str, Any]) -> "SessionActivity":
+ return cls(
+ id=str(payload.get("id") or ""),
+ backend=str(payload.get("backend") or ""),
+ runtime_key=str(payload.get("runtime_key") or ""),
+ session_id=(str(payload["session_id"]) if payload.get("session_id") else None),
+ kind=str(payload.get("kind") or "background_task"),
+ status=str(payload.get("status") or "running"),
+ description=(str(payload["description"]) if payload.get("description") else None),
+ foreground=bool(payload.get("foreground")),
+ detached_from_run=bool(payload.get("detached_from_run")),
+ parent_activity_id=(
+ str(payload["parent_activity_id"])
+ if payload.get("parent_activity_id")
+ else None
+ ),
+ turn_id=str(payload["turn_id"]) if payload.get("turn_id") else None,
+ run_id=str(payload["run_id"]) if payload.get("run_id") else None,
+ metadata=(dict(payload["metadata"]) if isinstance(payload.get("metadata"), dict) else {}),
+ started_at=str(payload.get("started_at") or _now_iso()),
+ updated_at=str(payload.get("updated_at") or _now_iso()),
+ completed_at=(str(payload["completed_at"]) if payload.get("completed_at") else None),
+ )
+
+
+def activity_completion_output(
+ activity: SessionActivity,
+ *,
+ detached: bool,
+ completes_turn: bool,
+) -> MessageOutput:
+ """Build stable Message/Run provenance for one Activity completion."""
+
+ return MessageOutput(
+ completes_turn=completes_turn,
+ completes_run=True,
+ detached=detached,
+ idempotency_key=(
+ f"{activity.backend}-task:{activity.runtime_key}:{activity.id}:completion"
+ ),
+ activity_id=activity.id,
+ causation_id=activity.parent_activity_id,
+ sequence=1,
+ run_id=activity.run_id,
+ requires_delivery_for_run_settlement=True,
+ metadata={
+ "activity_kind": activity.kind,
+ "activity_status": activity.status,
+ "backend": activity.backend,
+ "run_ids": activity.metadata.get("run_ids"),
+ "turn_id": activity.turn_id,
+ },
+ )
+
class SessionActivityRegistry:
"""One shared lifecycle owner for backend-native Activities."""
- def __init__(self) -> None:
+ def __init__(self, store: Any = None) -> None:
self._lock = threading.RLock()
+ self._store = store
+ self._output_settled_callback: Callable[[SessionActivity], None] | None = None
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)
+ self._claimed_completed_outputs: dict[
+ tuple[str, str, str], tuple[SessionActivity, bool]
+ ] = {}
+ self._recovered_output_ids: set[tuple[str, str, str]] = set()
+ self._recovered_terminals: deque[SessionActivity] = deque()
+ self._restore()
+
+ def set_output_settled_callback(
+ self,
+ callback: Callable[[SessionActivity], None] | None,
+ ) -> None:
+ """Register the runtime wakeup invoked after a completion is acknowledged."""
+
+ with self._lock:
+ self._output_settled_callback = callback
@staticmethod
def _key(backend: str, runtime_key: str, activity_id: str) -> tuple[str, str, str]:
return str(backend), str(runtime_key), str(activity_id)
+ @classmethod
+ def _activity_key(cls, activity: SessionActivity) -> tuple[str, str, str]:
+ return cls._key(activity.backend, activity.runtime_key, activity.id)
+
+ @staticmethod
+ def _activity_run_ids(activity: SessionActivity) -> set[str]:
+ run_ids = {str(activity.run_id)} if activity.run_id else set()
+ values = activity.metadata.get("run_ids")
+ if isinstance(values, list):
+ run_ids.update(str(value) for value in values if str(value or "").strip())
+ return run_ids
+
+ def _persist_activity(self, activity: SessionActivity, *, phase: str) -> None:
+ upsert = getattr(self._store, "upsert_activity", None)
+ if not callable(upsert):
+ return
+ try:
+ upsert(activity.to_dict(), phase=phase)
+ except Exception:
+ logger.warning("Failed to persist Activity %s", activity.id, exc_info=True)
+ raise
+
+ def _delete_activity(self, activity: SessionActivity) -> None:
+ delete = getattr(self._store, "delete_activity", None)
+ if not callable(delete):
+ return
+ try:
+ delete(
+ backend=activity.backend,
+ runtime_key=activity.runtime_key,
+ activity_id=activity.id,
+ )
+ except Exception:
+ logger.warning("Failed to delete Activity snapshot %s", activity.id, exc_info=True)
+ raise
+
+ def _persist_connection(
+ self,
+ *,
+ backend: str,
+ runtime_key: str,
+ session_id: str | None,
+ state: str,
+ ) -> None:
+ upsert = getattr(self._store, "upsert_connection", None)
+ if not callable(upsert):
+ return
+ try:
+ upsert(
+ backend=backend,
+ runtime_key=runtime_key,
+ session_id=session_id,
+ state=state,
+ )
+ except Exception:
+ logger.warning(
+ "Failed to persist %s Activity connection %s",
+ backend,
+ runtime_key,
+ exc_info=True,
+ )
+
+ def _restore(self) -> None:
+ list_connections = getattr(self._store, "list_connections", None)
+ if callable(list_connections):
+ try:
+ connections = list_connections()
+ except Exception:
+ connections = []
+ logger.warning("Failed to restore Activity connections", exc_info=True)
+ for payload in connections:
+ backend = str(payload.get("backend") or "")
+ runtime_key = str(payload.get("runtime_key") or "")
+ if not backend or not runtime_key:
+ continue
+ session_id = str(payload["session_id"]) if payload.get("session_id") else None
+ self._connections[(backend, runtime_key)] = (session_id, "disconnected")
+ self._persist_connection(
+ backend=backend,
+ runtime_key=runtime_key,
+ session_id=session_id,
+ state="disconnected",
+ )
+
+ list_activities = getattr(self._store, "list_activities", None)
+ if not callable(list_activities):
+ return
+ try:
+ records = list_activities()
+ except Exception:
+ logger.warning("Failed to restore Activities", exc_info=True)
+ return
+ now = _now_iso()
+ for record in records:
+ raw_activity = record.get("activity")
+ if not isinstance(raw_activity, dict):
+ continue
+ activity = SessionActivity.from_dict(raw_activity)
+ if not activity.id or not activity.backend or not activity.runtime_key:
+ continue
+ key = self._activity_key(activity)
+ connection_key = (activity.backend, activity.runtime_key)
+ self._connections[connection_key] = (activity.session_id, "disconnected")
+ self._persist_connection(
+ backend=activity.backend,
+ runtime_key=activity.runtime_key,
+ session_id=activity.session_id,
+ state="disconnected",
+ )
+ phase = record.get("phase")
+ if phase == "awaiting_output":
+ self._completed_outputs[connection_key].append((time.monotonic(), activity))
+ self._recovered_output_ids.add(key)
+ continue
+
+ recovered = (
+ activity
+ if phase == TERMINAL_SNAPSHOT_PHASE
+ else replace(
+ activity,
+ status="disconnected",
+ updated_at=now,
+ completed_at=now,
+ )
+ )
+ self._recovered_terminals.append(recovered)
+
def set_connection(
self,
*,
@@ -89,6 +296,12 @@ class SessionActivityRegistry:
normalized = state if state in CONNECTION_STATES else "unknown"
with self._lock:
self._connections[(str(backend), str(runtime_key))] = (session_id, normalized)
+ self._persist_connection(
+ backend=str(backend),
+ runtime_key=str(runtime_key),
+ session_id=session_id,
+ state=normalized,
+ )
def start(
self,
@@ -145,6 +358,7 @@ class SessionActivityRegistry:
updated_at=now,
completed_at=None,
)
+ self._persist_activity(activity, phase="active")
self._active[key] = activity
return activity
@@ -185,12 +399,13 @@ class SessionActivityRegistry:
status: str,
metadata: dict[str, Any] | None = None,
expects_output: bool = False,
+ retain_terminal_snapshot: 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)
+ existing = self._active.get(key)
if existing is None:
return None
merged = dict(existing.metadata)
@@ -203,9 +418,17 @@ class SessionActivityRegistry:
completed_at=now,
)
if expects_output:
+ self._persist_activity(completed, phase="awaiting_output")
+ self._active.pop(key, None)
self._completed_outputs[(str(backend), str(runtime_key))].append(
(time.monotonic(), completed)
)
+ elif retain_terminal_snapshot:
+ self._persist_activity(completed, phase=TERMINAL_SNAPSHOT_PHASE)
+ self._active.pop(key, None)
+ else:
+ self._delete_activity(completed)
+ self._active.pop(key, None)
return completed
def active_for_runtime(self, backend: str, runtime_key: str) -> list[SessionActivity]:
@@ -243,6 +466,7 @@ class SessionActivityRegistry:
runtime_key: str,
*,
max_age_seconds: float = 0,
+ recovered_only: bool = False,
) -> SessionActivity | None:
key = (str(backend), str(runtime_key))
now = time.monotonic()
@@ -250,13 +474,29 @@ class SessionActivityRegistry:
queue = self._completed_outputs.get(key)
if not queue:
return None
- while queue:
+ candidates = len(queue)
+ while queue and candidates > 0:
+ candidates -= 1
completed_at, activity = queue.popleft()
+ activity_key = self._activity_key(activity)
+ is_recovered = activity_key in self._recovered_output_ids
+ if recovered_only and not is_recovered:
+ queue.append((completed_at, activity))
+ continue
if max_age_seconds <= 0 or now - completed_at <= max_age_seconds:
+ self._claimed_completed_outputs[activity_key] = (activity, is_recovered)
+ self._recovered_output_ids.discard(activity_key)
if not queue:
self._completed_outputs.pop(key, None)
return activity
- self._completed_outputs.pop(key, None)
+ try:
+ self._delete_activity(activity)
+ except Exception:
+ queue.appendleft((completed_at, activity))
+ raise
+ self._recovered_output_ids.discard(activity_key)
+ if not queue:
+ self._completed_outputs.pop(key, None)
return None
def requeue_completed_output(
@@ -264,32 +504,110 @@ class SessionActivityRegistry:
activity: SessionActivity,
*,
front: bool = True,
- ) -> None:
+ recovered: bool | None = None,
+ ) -> bool:
"""Restore a claimed completion when its causal output cannot be consumed yet."""
key = (str(activity.backend), str(activity.runtime_key))
+ activity_key = self._activity_key(activity)
item = (time.monotonic(), activity)
with self._lock:
+ claimed = self._claimed_completed_outputs.pop(activity_key, None)
+ if claimed is None:
+ return False
+ if recovered is None:
+ recovered = claimed[1]
queue = self._completed_outputs[key]
if front:
queue.appendleft(item)
else:
queue.append(item)
+ if recovered:
+ self._recovered_output_ids.add(activity_key)
+ return True
+
+ def ack_completed_output(self, activity: SessionActivity) -> bool:
+ """Forget a durable completion only after its output policy succeeds."""
+
+ activity_key = self._activity_key(activity)
+ with self._lock:
+ claimed = self._claimed_completed_outputs.get(activity_key)
+ if claimed is None:
+ return False
+ self._delete_activity(claimed[0])
+ self._claimed_completed_outputs.pop(activity_key, None)
+ self._recovered_output_ids.discard(activity_key)
+ callback = self._output_settled_callback
+ if callback is not None:
+ try:
+ callback(activity)
+ except Exception:
+ logger.warning(
+ "Failed to signal settled Activity output %s",
+ activity.id,
+ exc_info=True,
+ )
+ return True
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))))
+ prefix = (str(backend), str(runtime_key))
+ return bool(self._completed_outputs.get(prefix)) or any(
+ (item.backend, item.runtime_key) == prefix
+ for item, _recovered in self._claimed_completed_outputs.values()
+ )
+
+ def has_pending_run_output(self, run_id: str) -> bool:
+ identity = str(run_id or "").strip()
+ if not identity:
+ return False
+ with self._lock:
+ pending = [
+ activity
+ for queue in self._completed_outputs.values()
+ for _created_at, activity in queue
+ ]
+ pending.extend(activity for activity, _recovered in self._claimed_completed_outputs.values())
+ return any(identity in self._activity_run_ids(activity) for activity in pending)
+
+ def recovered_output_runtimes(self) -> list[tuple[str, str]]:
+ """Runtime queues containing completion output restored after restart."""
+
+ with self._lock:
+ runtimes = {
+ (activity.backend, activity.runtime_key)
+ for queue in self._completed_outputs.values()
+ for _created_at, activity in queue
+ if self._activity_key(activity) in self._recovered_output_ids
+ }
+ return sorted(runtimes)
+
+ def drain_recovered_terminals(self) -> list[SessionActivity]:
+ with self._lock:
+ values = list(self._recovered_terminals)
+ self._recovered_terminals.clear()
+ return values
+
+ def ack_recovered_terminal(self, activity: SessionActivity) -> None:
+ """Delete a recovered live snapshot only after its Run policy settles."""
+
+ with self._lock:
+ self._delete_activity(activity)
def has_backend_work(self, backend: str) -> bool:
"""Whether a backend has live Activities or undelivered completions."""
identity = str(backend)
with self._lock:
- return any(key[0] == identity for key in self._active) or any(
- key[0] == identity and bool(queue)
- for key, queue in self._completed_outputs.items()
+ return (
+ any(key[0] == identity for key in self._active)
+ or any(
+ key[0] == identity and bool(queue)
+ for key, queue in self._completed_outputs.items()
+ )
+ or any(key[0] == identity for key in self._claimed_completed_outputs)
)
def end_backend(self, backend: str, *, status: str = "killed") -> list[SessionActivity]:
@@ -312,28 +630,54 @@ class SessionActivityRegistry:
for item_backend, runtime_key in self._completed_outputs
if item_backend == identity
)
+ runtime_keys.update(
+ runtime_key
+ for item_backend, runtime_key, _activity_id in self._claimed_completed_outputs
+ if item_backend == identity
+ )
completed: list[SessionActivity] = []
for runtime_key in runtime_keys:
- completed.extend(self.end_runtime(identity, runtime_key, status=status))
+ completed.extend(
+ self.end_runtime(
+ identity,
+ runtime_key,
+ status=status,
+ retain_terminal_snapshots=True,
+ )
+ )
+ now = _now_iso()
with self._lock:
- pending = [
- activity
+ pending_by_key = {
+ self._activity_key(activity): activity
for key, queue in self._completed_outputs.items()
if key[0] == identity
for _completed_at, activity in queue
+ }
+ pending_by_key.update(
+ {
+ key: activity
+ for key, (activity, _recovered) in self._claimed_completed_outputs.items()
+ if key[0] == identity
+ }
+ )
+ terminated_pending = [
+ replace(
+ activity,
+ status=status if status in TERMINAL_ACTIVITY_STATUSES else "killed",
+ updated_at=now,
+ completed_at=now,
+ )
+ for activity in pending_by_key.values()
]
+ for activity in terminated_pending:
+ self._persist_activity(activity, phase=TERMINAL_SNAPSHOT_PHASE)
for key in [key for key in self._completed_outputs if key[0] == identity]:
self._completed_outputs.pop(key, None)
- now = _now_iso()
- completed.extend(
- replace(
- activity,
- status=status if status in TERMINAL_ACTIVITY_STATUSES else "killed",
- updated_at=now,
- completed_at=now,
- )
- for activity in pending
- )
+ for key in [key for key in self._claimed_completed_outputs if key[0] == identity]:
+ self._claimed_completed_outputs.pop(key, None)
+ for activity in terminated_pending:
+ self._recovered_output_ids.discard(self._activity_key(activity))
+ completed.extend(terminated_pending)
return completed
def end_runtime(
@@ -342,6 +686,7 @@ class SessionActivityRegistry:
runtime_key: str,
*,
status: str = "disconnected",
+ retain_terminal_snapshots: bool = False,
) -> list[SessionActivity]:
key = (str(backend), str(runtime_key))
with self._lock:
@@ -358,6 +703,12 @@ class SessionActivityRegistry:
session_id,
status if status in CONNECTION_STATES else "disconnected",
)
+ self._persist_connection(
+ backend=str(backend),
+ runtime_key=str(runtime_key),
+ session_id=session_id,
+ state=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:
@@ -366,6 +717,7 @@ class SessionActivityRegistry:
runtime_key=runtime_key,
activity_id=activity_id,
status=status if status in TERMINAL_ACTIVITY_STATUSES else "disconnected",
+ retain_terminal_snapshot=retain_terminal_snapshots,
)
if activity is not None:
completed.append(activity)
@@ -386,6 +738,16 @@ class SessionActivityRegistry:
for connection_session_id, state in self._connections.values()
if connection_session_id == session_id
]
+ pending_output_count = sum(
+ 1
+ for queue in self._completed_outputs.values()
+ for _created_at, activity in queue
+ if activity.session_id == session_id
+ ) + sum(
+ 1
+ for activity, _recovered in self._claimed_completed_outputs.values()
+ if activity.session_id == session_id
+ )
if "connected" in connection_states:
connection = "connected"
elif "reconnecting" in connection_states:
@@ -396,5 +758,6 @@ class SessionActivityRegistry:
connection = "unknown"
return {
"background_activities": [activity.to_dict() for activity in activities],
+ "pending_activity_output_count": pending_output_count,
"connection": connection,
}
diff --git a/core/session_turns.py b/core/session_turns.py
index 6f969f356..72b5c9f0a 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -32,6 +32,7 @@ from core.services.dispatch import SOURCE_HUMAN, SOURCE_SCHEDULED, dispatch_turn
from storage import messages_service
from storage.db import get_cached_sqlite_engine
from storage.models import messages
+from core.message_output import terminal_turn_output
from vibe.i18n import t as i18n_t
if TYPE_CHECKING:
@@ -773,7 +774,13 @@ class SessionTurnManager:
# any backend turn (missing/disabled backend) → empty error result
# → dot red. This is a real terminal FAILURE, not a timeout.
if failed:
- await self.controller.emit_agent_message(context, "result", "", is_error=True)
+ await self.controller.emit_agent_message(
+ context,
+ "result",
+ "",
+ is_error=True,
+ output=terminal_turn_output(),
+ )
# Flush intents ride on the popped Turn (set by cancel / send_now),
# so they retire with it — no parallel set to discard. Don't flush
# after a plain Stop (keep the queue) or a terminal failure; send-now
@@ -1105,6 +1112,7 @@ class SessionTurnManager:
logger.debug("turn_state: failed to read queued input count", exc_info=True)
activity_state: dict[str, Any] = {
"background_activities": [],
+ "pending_activity_output_count": 0,
"connection": "unknown",
}
service = getattr(self.controller, "agent_service", None) if self.controller is not None else None
@@ -1123,6 +1131,10 @@ class SessionTurnManager:
"foreground": "running" if active else "idle",
"pending_input_count": pending_input_count,
"background_activities": activity_state.get("background_activities", []),
+ "pending_activity_output_count": activity_state.get(
+ "pending_activity_output_count",
+ 0,
+ ),
"connection": activity_state.get("connection", "unknown"),
}
if backend:
diff --git a/docs/plans/full-duplex-sessions.md b/docs/plans/full-duplex-sessions.md
index a0bc401fb..ad561c496 100644
--- a/docs/plans/full-duplex-sessions.md
+++ b/docs/plans/full-duplex-sessions.md
@@ -2,25 +2,23 @@
## 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.
+Make the durable Session message stream independent from foreground execution
+ownership while preserving `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.
+The implementation spans the shared dispatcher, durable Activity recovery,
+Claude background-task output, Harness Run callbacks, and Workbench projection.
+It does not introduce a global Session FSM or a speculative public schema.
## 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):
+`core.message_output.MessageOutput` accompanies every live agent output whose
+lifecycle authority must be explicit:
- `completes_turn`: whether this output is a terminal foreground signal;
-- `completes_run`: optional independent Run terminal signal (defaults to the
- legacy `completes_turn` behavior);
+- `completes_run`: optional independent Run terminal signal;
- `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;
@@ -32,24 +30,54 @@ 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.
+Live core and backend paths no longer infer lifecycle authority from the visible
+`result` role. One dispatcher-boundary fallback keeps older external callers
+compatible while they migrate. A backend can emit multiple result-shaped output
+Messages by using `completes_turn=False` for intermediate outputs and one
+terminal output.
-### Activity registry
+### Activity registry and restart recovery
-`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:
+`core.session_activities.SessionActivityRegistry` owns backend-neutral
+operational state. 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.
+Restart snapshots use the existing `runtime_records` aggregate rather than a new
+Activity table. An active Activity snapshot, a completed Activity waiting for
+output, and backend connection state are persisted independently. Completed
+output remains backend work while queued or claimed for delivery and is removed
+only after its delivery policy is acknowledged. A claimed output cannot be
+requeued or acknowledged after a forced backend terminal transition supersedes
+that delivery attempt.
+
+On controller restart:
+
+- active native work becomes `disconnected`; any owned Run reaches its existing
+ failure/cancellation policy exactly once, and its snapshot remains durable
+ until that Run policy is acknowledged, whether the transition comes from a
+ controller restart, a normal backend disconnect, or a forced restart;
+- completed output remains pending with its stable producer identity;
+- a stored summary is delivered once as detached Session output, without
+ lifecycle authority over any newer Turn;
+- the originating context's already-resolved delivery key is retained as
+ Activity metadata, so recovery preserves `post_to` / `deliver_key` routing;
+- if no summary or valid Session route exists, or the Session is explicitly
+ no-delivery, the Run settles silently and no user-visible text is invented;
+- a forced backend restart converts live and pending-output Activities into
+ terminal snapshots that remain durable until their Run policy is acknowledged;
+- every recovered native connection projects as `disconnected` until the backend
+ reconnects.
+
`SessionTurnManager.turn_state()` composes this with its existing foreground
-state and the durable queued-message count. Existing response fields remain
-unchanged.
+state and the durable queued-message count. The Workbench API and UI consume the
+orthogonal `foreground`, `pending_input_count`, `background_activities`,
+`pending_activity_output_count`, and `connection` facts. `in_flight` remains a
+read-only compatibility alias for older clients, not the Session state model.
### Run outputs and callbacks
@@ -82,6 +110,8 @@ 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.
+Deferred terminal intent is excluded from generic restart requeueing, then
+reconciled against recovered Activity/output snapshots before normal Run drain.
## Claude mapping
@@ -105,19 +135,49 @@ 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.
+newer pending native request. Queued completions survive both runtime disconnect
+and controller restart so a late flush can still deliver and settle their origin
+Run. A same-Turn delivery attempt consumes that Turn exactly once; if IM
+delivery fails, the Activity remains in the Outbox and retries as detached
+Session output without reusing the settled Turn token; the failure tidy closes
+only that Turn, while the retry retains Run-completion authority. Recovered
+terminal Activities wait behind any output still owed by the same Run. Output
+containing only `<silent>` directives uses the same silent Run-settlement path
+as an empty summary. Activity output follows a durable handoff order: persist the
+Outbox snapshot, deliver and persist the Message, settle the Run and its callback
+outputs, then delete the snapshot. A failed snapshot write, Run write, or delete
+keeps the Activity active, queued, or claimed for an idempotent retry.
+
+## Other backend protocol disposition
+
+The shared contracts are used by Claude, Codex, and OpenCode, including explicit
+terminal output authority. Native Activity mapping remains capability-driven:
+
+- Codex app-server currently exposes thread/turn/item events scoped to an active
+ Turn, but no independently identified unit of work that can complete after
+ that Turn;
+- OpenCode polling exposes Session messages/tool parts plus Session idle/error,
+ but no independently identified background work with its own post-Turn
+ lifecycle.
+
+Inventing Activities from ordinary tool or Turn events would freeze the wrong
+schema and conflate foreground execution with background agency. These backends
+therefore keep serialized accepted Inbox work today and will inherit native
+Activity mapping when their protocols expose a stable independent identity and
+lifecycle.
## Compatibility and non-goals
-- No schema migration: Message provenance uses existing `metadata_json`; the Run
- ledger uses existing `result_payload_json`.
+- No schema migration: Message provenance uses existing `metadata_json`, the Run
+ ledger uses existing `result_payload_json`, and restart snapshots use existing
+ `runtime_records`.
- 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.
+- No classification of ordinary Codex/OpenCode Turn or tool events as fake
+ Activities.
+- No removal of the quarantined dispatcher compatibility fallback in the same
+ change; all live runtime paths already use explicit output semantics.
## Acceptance evidence
@@ -128,6 +188,8 @@ inside the process so a late flush can still deliver and settle their origin Run
- `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.
+Focused unit/contract tests cover Activity transitions, restart recovery,
+summary and no-summary policies, state-axis projection, structured provenance,
+dedup, terminal isolation, Run/callback settlement, and existing one-result
+compatibility across Claude, Codex, OpenCode, dispatcher, scheduler, and
+Workbench paths.
diff --git a/modules/agents/base.py b/modules/agents/base.py
index 3accee0a6..85524ec6d 100644
--- a/modules/agents/base.py
+++ b/modules/agents/base.py
@@ -11,7 +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.message_output import MessageOutput, terminal_turn_output
from core.reply_enhancer import strip_silent_blocks
logger = logging.getLogger(__name__)
@@ -57,8 +57,12 @@ 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
+ # Explicit output semantics for the Turn. Backend-initiated/multi-output
+ # paths override this instead of relying on the visible Message role.
+ output: Optional[MessageOutput] = field(default_factory=terminal_turn_output)
+ # Producer-owned lifecycle object retained until durable output delivery is
+ # acknowledged. The shared dispatcher sees only ``output`` provenance.
+ output_activity: Optional[Any] = None
@dataclass
@@ -116,6 +120,11 @@ class BaseAgent(ABC):
"""Return runtime identities scoped to a persisted Avibe settings key."""
return set()
+ def on_activity_output_settled(self, runtime_key: str) -> None:
+ """Wake backend-local admission blocked on acknowledged Activity output."""
+
+ return None
+
def backend_alive(self, context: Any) -> Optional[bool]:
"""Best-effort liveness of this backend for the given turn context.
@@ -466,10 +475,12 @@ class BaseAgent(ABC):
suffix: Optional[str] = None,
request: Optional[AgentRequest] = None,
output: MessageOutput | None = None,
- ) -> None:
+ ) -> Optional[str]:
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)
+ if output is None:
+ output = terminal_turn_output()
+ settles_request = 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
@@ -485,19 +496,20 @@ class BaseAgent(ABC):
visible_result = strip_silent_blocks(raw_result)
visible_suffix = strip_silent_blocks(raw_suffix) if raw_suffix else None
has_silent_directive = "<silent" in raw_result.lower() or "<silent" in raw_suffix.lower()
+ message_id: Optional[str] = None
if has_silent_directive and not visible_result.strip() and not (visible_suffix or "").strip():
- await self.controller.emit_agent_message(
+ message_id = await self.controller.emit_agent_message(
context,
"result",
"",
parse_mode=parse_mode,
is_error=is_error,
- **({"output": output} if output is not None else {}),
+ output=output,
)
if request and settles_request:
await self._remove_ack_reaction(request)
- return
+ return message_id
# When show_duration is disabled, skip the entire result line
# unless there is actual result_text or suffix to deliver.
@@ -509,13 +521,13 @@ class BaseAgent(ABC):
parts.append(visible_suffix)
if parts:
formatted = "\n".join(parts)
- await self.controller.emit_agent_message(
+ message_id = 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 {}),
+ output=output,
)
else:
# No visible text (show_duration off + empty result/suffix) is still
@@ -523,13 +535,13 @@ class BaseAgent(ABC):
# (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(
+ message_id = await self.controller.emit_agent_message(
context,
"result",
"",
parse_mode=parse_mode,
is_error=is_error,
- **({"output": output} if output is not None else {}),
+ output=output,
)
else:
token_field = ""
@@ -562,19 +574,20 @@ class BaseAgent(ABC):
if not body.strip() and result_footer:
body = result_footer
result_footer = None
- await self.controller.emit_agent_message(
+ message_id = await self.controller.emit_agent_message(
context,
"result",
body,
parse_mode=parse_mode,
is_error=is_error,
result_footer=result_footer,
- **({"output": output} if output is not None else {}),
+ output=output,
)
# Remove ack reaction after result is sent
if request and settles_request:
await self._remove_ack_reaction(request)
+ return message_id
@abstractmethod
async def handle_message(self, request: AgentRequest) -> None:
diff --git a/modules/agents/claude_agent.py b/modules/agents/claude_agent.py
index 82d00fcf8..7db9c52f5 100644
--- a/modules/agents/claude_agent.py
+++ b/modules/agents/claude_agent.py
@@ -5,8 +5,9 @@ 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 core.message_output import MessageOutput, terminal_output_for, terminal_turn_output
+from core.reply_enhancer import strip_silent_blocks
+from core.session_activities import SessionActivity, activity_completion_output
from modules.claude_sdk_compat import TextBlock, ToolUseBlock, is_claude_sdk_buffer_error
from modules.agents.claude_process_reaper import (
AVIBE_CLAUDE_SESSION_OWNER,
@@ -196,7 +197,13 @@ class ClaudeAgent(BaseAgent):
# web-Chat stream waiter (the visible error was sent + persisted
# above), instead of waiting out the safety timeout. No-op off-workbench.
try:
- await self.controller.emit_agent_message(context, "result", "", is_error=True)
+ await self.controller.emit_agent_message(
+ context,
+ "result",
+ "",
+ is_error=True,
+ output=terminal_output_for(request),
+ )
finally:
self._release_service_runtime_turn(context)
finally:
@@ -392,7 +399,9 @@ class ClaudeAgent(BaseAgent):
self._suppressed_synthetic_results.discard(composite_key)
if not preserve_pending_request_state:
self._pending_reactions.pop(composite_key, None)
- self._pending_requests.pop(composite_key, None)
+ pending_requests = self._pending_requests.pop(composite_key, None) or []
+ for pending_request in pending_requests:
+ self._requeue_request_activity(pending_request)
cleanup = getattr(self.session_handler, "cleanup_session", None)
if callable(cleanup):
await cleanup(composite_key, current_receiver_task=current_receiver_task)
@@ -422,6 +431,7 @@ class ClaudeAgent(BaseAgent):
result can adopt the stale request/token.
"""
pending_request = self._pop_pending_request(composite_key)
+ self._requeue_request_activity(pending_request)
context = getattr(pending_request, "context", None)
if context is not None:
self._adopt_pending_turn_token(context, pending_request)
@@ -453,6 +463,7 @@ class ClaudeAgent(BaseAgent):
"",
is_error=True,
level="silent",
+ output=terminal_output_for(pending_request),
)
except Exception:
logger.debug(
@@ -491,6 +502,7 @@ class ClaudeAgent(BaseAgent):
return False
stopped_request = self._pop_pending_request(composite_key)
+ self._requeue_request_activity(stopped_request)
self._adopt_pending_turn_token(request.context, stopped_request)
if stopped_request is not None:
try:
@@ -517,7 +529,13 @@ class ClaudeAgent(BaseAgent):
# WITHOUT a bubble. Emit only after cleanup so the next turn cannot
# acquire the gate and reuse a client that this stop is still
# disconnecting.
- await self.controller.emit_agent_message(request.context, "result", "", level="silent")
+ await self.controller.emit_agent_message(
+ request.context,
+ "result",
+ "",
+ level="silent",
+ output=terminal_output_for(request),
+ )
except Exception as err:
logger.error("Failed to emit Claude stop result for session %s: %s", composite_key, err, exc_info=True)
self._release_service_runtime_turn(request.context)
@@ -793,18 +811,18 @@ class ClaudeAgent(BaseAgent):
result_text = self._detached_assistant_text.get(composite_key)
self._detached_assistant_text.pop(composite_key, None)
try:
- await self.emit_result_message(
+ await self._emit_activity_result(
context,
+ detached_activity,
result_text,
+ detached=True,
+ completes_turn=False,
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,
- ),
)
+ registry = self._activity_registry()
+ if registry is not None:
+ registry.ack_completed_output(detached_activity)
except Exception:
registry = self._activity_registry()
if registry is not None:
@@ -863,6 +881,7 @@ class ClaudeAgent(BaseAgent):
# so sending both would duplicate the content.
pending_request = self._pop_pending_request(composite_key)
+ output_activity = getattr(pending_request, "output_activity", None)
# The receiver is long-lived and reused across a session's
# turns, so ``context`` still carries the FIRST turn's
@@ -873,23 +892,45 @@ class ClaudeAgent(BaseAgent):
# stale straggler. No-op for fresh sessions / absent tokens.
self._adopt_pending_turn_token(context, pending_request)
- # A terminal result settles the turn. The pending request
- # was already popped above, so the idle transition must run
- # even if emitting the result or backfilling the title
- # raises — otherwise the inner ``except … continue`` below
- # would swallow the error, skip the mark-idle, and leave the
- # session pinned ``active`` (exempt from idle eviction until
- # the next service restart). Run it in a ``finally``.
+ # A terminal result consumes this Turn even when IM delivery
+ # fails. A failed Activity delivery is requeued below, but its
+ # retry is detached and cannot reuse this Turn's token.
emit_failed = False
try:
- await self.emit_result_message(
- context,
- result_text,
- subtype=getattr(message, "subtype", "") or "",
- duration_ms=getattr(message, "duration_ms", 0),
- parse_mode="markdown",
- request=pending_request,
- )
+ if output_activity is not None:
+ await self._emit_activity_result(
+ context,
+ output_activity,
+ result_text,
+ detached=False,
+ completes_turn=True,
+ subtype=getattr(message, "subtype", "") or "",
+ duration_ms=getattr(message, "duration_ms", 0),
+ request=pending_request,
+ )
+ registry = self._activity_registry()
+ if registry is not None:
+ registry.ack_completed_output(output_activity)
+ else:
+ await self.emit_result_message(
+ context,
+ result_text,
+ subtype=getattr(message, "subtype", "") or "",
+ duration_ms=getattr(message, "duration_ms", 0),
+ parse_mode="markdown",
+ request=pending_request,
+ )
+ except Exception:
+ emit_failed = True
+ if output_activity is not None:
+ registry = self._activity_registry()
+ if registry is not None:
+ registry.requeue_completed_output(output_activity)
+ await self._settle_activity_turn_after_delivery_failure(
+ context
+ )
+ raise
+ else:
native_session_id = self._native_session_ids.get(composite_key) or self._reserved_native_session_id(
context,
self.name,
@@ -898,15 +939,17 @@ class ClaudeAgent(BaseAgent):
self.name,
)
if pending_request is not None and native_session_id:
- self._maybe_backfill_session_title(pending_request, native_session_id)
- except Exception:
- emit_failed = True
- raise
+ try:
+ self._maybe_backfill_session_title(
+ pending_request,
+ native_session_id,
+ )
+ except Exception:
+ logger.warning(
+ "Claude result delivered but session title backfill failed",
+ exc_info=True,
+ )
finally:
- # Settle the turn regardless of an emit/backfill
- # failure: clear the loading reaction and the stale
- # assistant-text fallback, then release the active
- # flag so the session can be idle-evicted.
await self._remove_result_pending_reaction(
composite_key,
context,
@@ -998,7 +1041,13 @@ class ClaudeAgent(BaseAgent):
# releases the SSE waiter) instead of letting the avibe Chat hang to
# the 600s stream timeout and then settle idle. No-op off-workbench
# (Codex P2).
- await self.controller.emit_agent_message(context, "result", "", is_error=True)
+ await self.controller.emit_agent_message(
+ context,
+ "result",
+ "",
+ is_error=True,
+ output=terminal_turn_output(),
+ )
self._release_service_runtime_turn(context)
# NOTE: no `finally` cleanup of pending reactions here.
# When the receiver ends normally (stream exhausted after a result),
@@ -1036,6 +1085,7 @@ class ClaudeAgent(BaseAgent):
if not pending_token:
self._pending_requests.setdefault(composite_key, []).insert(0, pending_request)
return
+ self._requeue_request_activity(pending_request)
logger.warning("Claude receiver ended without a result for session %s", composite_key)
self._adopt_pending_turn_token(context, pending_request)
await self._remove_specific_pending_reaction(composite_key, context, pending_request)
@@ -1050,7 +1100,13 @@ class ClaudeAgent(BaseAgent):
preserve_pending_request_state=True,
)
try:
- await self.controller.emit_agent_message(context, "result", "", is_error=True)
+ await self.controller.emit_agent_message(
+ context,
+ "result",
+ "",
+ is_error=True,
+ output=terminal_output_for(pending_request),
+ )
finally:
self._release_service_runtime_turn(context)
@@ -1067,13 +1123,20 @@ class ClaudeAgent(BaseAgent):
return False
pending_request = self._pop_pending_request(composite_key)
+ self._requeue_request_activity(pending_request)
self._adopt_pending_turn_token(context, pending_request)
logger.warning(
"Claude malformed tool-use synthetic API error for session %s suppressed from user-visible transcript: %s",
composite_key,
text or "<empty>",
)
- await self.controller.emit_agent_message(context, "result", "", is_error=True)
+ await self.controller.emit_agent_message(
+ context,
+ "result",
+ "",
+ is_error=True,
+ output=terminal_output_for(pending_request),
+ )
if pending_request is not None:
await self._remove_ack_reaction(pending_request)
self._last_assistant_text.pop(composite_key, None)
@@ -1200,6 +1263,7 @@ class ClaudeAgent(BaseAgent):
and release its Chat stream now. Called from auth-failure terminal paths
after the recovery notify has been persisted."""
failed_request = self._pop_pending_request(composite_key)
+ self._requeue_request_activity(failed_request)
self._adopt_pending_turn_token(context, failed_request)
_mark = getattr(self.controller, "mark_turn_complete", None)
if callable(_mark):
@@ -1212,6 +1276,16 @@ class ClaudeAgent(BaseAgent):
service = getattr(self.controller, "agent_service", None)
return getattr(service, "activities", None)
+ def _requeue_request_activity(self, request: AgentRequest | None) -> None:
+ activity = getattr(request, "output_activity", None)
+ if activity is None or request is None:
+ return
+ registry = self._activity_registry()
+ if registry is not None:
+ registry.requeue_completed_output(activity)
+ request.output_activity = None
+ request.output = terminal_turn_output()
+
def _activity_output_pending(self, composite_key: str) -> bool:
registry = self._activity_registry()
return bool(
@@ -1242,6 +1316,9 @@ class ClaudeAgent(BaseAgent):
if event is not None:
event.set()
+ def on_activity_output_settled(self, runtime_key: str) -> None:
+ self._signal_activity_output_settled(runtime_key)
+
@staticmethod
def _activity_session_id(context: MessageContext) -> str | None:
value = (getattr(context, "platform_specific", None) or {}).get("agent_session_id")
@@ -1365,6 +1442,16 @@ class ClaudeAgent(BaseAgent):
if value not in (None, "")
}
if existing_activity is None:
+ pending = self._pending_requests.get(composite_key) or []
+ source = getattr(pending[0], "context", None) if pending else context
+ delivery_key = str(
+ (getattr(source, "platform_specific", None) or {}).get(
+ "delivery_key_external"
+ )
+ or ""
+ ).strip()
+ if delivery_key:
+ metadata["delivery_key_external"] = delivery_key
run_ids = self._activity_run_ids(composite_key, context)
turn_id = self._current_turn_id(composite_key, context)
else:
@@ -1437,6 +1524,7 @@ class ClaudeAgent(BaseAgent):
status=status,
metadata=metadata,
expects_output=status == "completed",
+ retain_terminal_snapshot=status != "completed",
)
service = getattr(self.controller, "agent_service", None)
on_terminal = getattr(service, "on_activity_terminal", None)
@@ -1454,25 +1542,81 @@ class ClaudeAgent(BaseAgent):
detached: bool,
completes_turn: bool,
) -> MessageOutput:
- return MessageOutput(
+ return activity_completion_output(
+ activity,
+ detached=detached,
completes_turn=completes_turn,
- completes_run=True,
+ )
+
+ @staticmethod
+ def _require_activity_delivery(
+ activity: SessionActivity,
+ message_id: str | None,
+ ) -> None:
+ if message_id is None:
+ raise RuntimeError(
+ f"Claude Activity output {activity.id} was not persisted or delivered"
+ )
+
+ async def _settle_activity_turn_after_delivery_failure(
+ self,
+ context: MessageContext,
+ ) -> None:
+ """Close the origin Turn if delivery failed before its terminal chokepoint."""
+
+ try:
+ await self.controller.emit_agent_message(
+ context,
+ "result",
+ "",
+ level="silent",
+ output=MessageOutput(completes_turn=True, completes_run=False),
+ )
+ except Exception:
+ logger.debug(
+ "Failed to settle Activity Turn after delivery failure",
+ exc_info=True,
+ )
+
+ async def _emit_activity_result(
+ self,
+ context: MessageContext,
+ activity: SessionActivity,
+ text: str | None,
+ *,
+ detached: bool,
+ completes_turn: bool,
+ subtype: str = "success",
+ duration_ms: int = 0,
+ request: AgentRequest | None = None,
+ ) -> None:
+ """Apply the Activity's explicit visible-or-silent output policy."""
+
+ output = self._activity_message_output(
+ activity,
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,
- },
+ completes_turn=completes_turn,
)
+ visible_text = str(text or "")
+ if not strip_silent_blocks(visible_text).strip():
+ await self.controller.emit_agent_message(
+ context,
+ "result",
+ "",
+ is_error=(subtype or "").startswith("error"),
+ output=output,
+ )
+ return
+ message_id = await self.emit_result_message(
+ context,
+ visible_text,
+ subtype=subtype,
+ duration_ms=duration_ms,
+ parse_mode="markdown",
+ request=request,
+ output=output,
+ )
+ self._require_activity_delivery(activity, message_id)
@staticmethod
def _unsolicited_message_output(message) -> MessageOutput:
@@ -1539,16 +1683,16 @@ class ClaudeAgent(BaseAgent):
if not text:
text = str(activity.metadata.get("summary") or "").strip()
try:
- await self.emit_result_message(
+ await self._emit_activity_result(
context,
+ activity,
text,
- parse_mode="markdown",
- output=self._activity_message_output(
- activity,
- detached=True,
- completes_turn=False,
- ),
+ detached=True,
+ completes_turn=False,
)
+ registry = self._activity_registry()
+ if registry is not None:
+ registry.ack_completed_output(activity)
except Exception:
registry = self._activity_registry()
if registry is not None:
@@ -1601,19 +1745,18 @@ class ClaudeAgent(BaseAgent):
matched_request = self._pop_pending_request(composite_key)
self._adopt_pending_turn_token(context, matched_request)
try:
- await self.emit_result_message(
+ await self._emit_activity_result(
context,
+ activity,
result_text,
- parse_mode="markdown",
+ detached=False,
+ completes_turn=True,
request=matched_request,
- output=self._activity_message_output(
- activity,
- detached=False,
- completes_turn=True,
- ),
)
+ registry.ack_completed_output(activity)
except Exception:
registry.requeue_completed_output(activity)
+ await self._settle_activity_turn_after_delivery_failure(context)
raise
finally:
await self._remove_result_pending_reaction(
@@ -1628,16 +1771,14 @@ class ClaudeAgent(BaseAgent):
continue
try:
- await self.emit_result_message(
+ await self._emit_activity_result(
context,
+ activity,
result_text,
- parse_mode="markdown",
- output=self._activity_message_output(
- activity,
- detached=True,
- completes_turn=False,
- ),
+ detached=True,
+ completes_turn=False,
)
+ registry.ack_completed_output(activity)
except Exception:
registry.requeue_completed_output(activity)
raise
@@ -1744,6 +1885,7 @@ class ClaudeAgent(BaseAgent):
detached=False,
completes_turn=True,
)
+ pending_request.output_activity = completed_activity
return None
self._detached_activity_outputs[composite_key] = completed_activity
logger.info(
@@ -1808,6 +1950,7 @@ class ClaudeAgent(BaseAgent):
if completed_activity is not None
else None
),
+ output_activity=completed_activity,
)
self._pending_requests.setdefault(composite_key, []).append(request)
logger.info(
@@ -1883,6 +2026,7 @@ class ClaudeAgent(BaseAgent):
logger.debug(f"Failed to remove reaction ack: {err}")
if requests:
for request in requests:
+ self._requeue_request_activity(request)
await self._remove_ack_reaction(request)
def get_relative_path(self, abs_path: str, context: Optional[MessageContext] = None) -> str:
diff --git a/modules/agents/codex/agent.py b/modules/agents/codex/agent.py
index bd640b796..9e5e24af0 100644
--- a/modules/agents/codex/agent.py
+++ b/modules/agents/codex/agent.py
@@ -17,6 +17,7 @@ from config.v2_config import (
)
from core.avibe_cloud import avibe_cloud_url_available
from core.caller_context import caller_env_for_platform_payload
+from core.message_output import terminal_output_for
from core.services.session_fork import fork_source_state, pending_native_fork
from core.system_prompt_injection import (
build_forked_session_correction_prompt,
@@ -136,6 +137,7 @@ class CodexAgent(BaseAgent):
"result",
"❌ Codex CLI not found. Please install it or set CODEX_CLI_PATH.",
is_error=True,
+ output=terminal_output_for(request),
)
await self._remove_ack_reaction(request)
self._event_handler._release_stream_turn(request.context)
@@ -147,6 +149,7 @@ class CodexAgent(BaseAgent):
"result",
f"❌ Failed to start Codex CLI: {e}",
is_error=True,
+ output=terminal_output_for(request),
)
await self._remove_ack_reaction(request)
self._event_handler._release_stream_turn(request.context)
@@ -189,6 +192,7 @@ class CodexAgent(BaseAgent):
"result",
f"❌ Failed to interrupt previous Codex turn: {e}",
is_error=True,
+ output=terminal_output_for(request),
)
await self._remove_ack_reaction(request)
self._event_handler._release_stream_turn(request.context)
@@ -245,6 +249,7 @@ class CodexAgent(BaseAgent):
"result",
error_text,
is_error=True,
+ output=terminal_output_for(request),
)
await self._remove_ack_reaction(request)
# The turn never started (all retries failed) — release the
@@ -281,7 +286,11 @@ class CodexAgent(BaseAgent):
# idle; IM shows the ack reaction removed above). ``level="silent"`` is
# the explicit visibility grade rather than faking it via empty text.
await self.controller.emit_agent_message(
- request.context, "result", "", level="silent"
+ request.context,
+ "result",
+ "",
+ level="silent",
+ output=terminal_output_for(request),
)
logger.info("Codex turn %s interrupted via /stop", turn_id)
return True
@@ -554,7 +563,14 @@ class CodexAgent(BaseAgent):
emit = getattr(controller, "emit_agent_message", None)
if callable(emit):
try:
- await emit(context, "result", "", is_error=True, level="silent")
+ await emit(
+ context,
+ "result",
+ "",
+ is_error=True,
+ level="silent",
+ output=terminal_output_for(request),
+ )
return
except Exception:
logger.warning(
diff --git a/modules/agents/codex/event_handler.py b/modules/agents/codex/event_handler.py
index 4c762a275..5e7397fcf 100644
--- a/modules/agents/codex/event_handler.py
+++ b/modules/agents/codex/event_handler.py
@@ -9,6 +9,7 @@ from pathlib import Path
from typing import TYPE_CHECKING, Any
from vibe.i18n import t as i18n_t
+from core.message_output import terminal_output_for
if TYPE_CHECKING:
from modules.agents.base import AgentRequest
@@ -173,6 +174,7 @@ class CodexEventHandler:
"result",
message,
is_error=True,
+ output=terminal_output_for(tracked_request),
)
# handled == True persists the durable recovery notify centrally in
# ``maybe_emit_auth_recovery_message`` (the auth service is the single
@@ -356,6 +358,7 @@ class CodexEventHandler:
"result",
text,
is_error=True,
+ output=terminal_output_for(request),
)
turn_state.terminal_error_notified = True
else:
@@ -375,6 +378,7 @@ class CodexEventHandler:
"result",
text,
is_error=True,
+ output=terminal_output_for(request),
)
def _extract_error_message(self, error: Any) -> str:
diff --git a/modules/agents/opencode/agent.py b/modules/agents/opencode/agent.py
index 9b1cdead8..0c01d6e75 100644
--- a/modules/agents/opencode/agent.py
+++ b/modules/agents/opencode/agent.py
@@ -14,6 +14,7 @@ import time
from typing import Dict, Optional
from core.avibe_cloud import avibe_cloud_url_available
+from core.message_output import terminal_output_for
from core.resource_governance import governor_from_controller
from core.system_prompt_injection import build_system_prompt_injection, get_enabled_agents_for_prompt
from modules.agents.base import AgentRequest, BaseAgent
@@ -203,6 +204,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
"result",
f"Failed to start OpenCode server: {e}",
is_error=True,
+ output=terminal_output_for(request),
)
await self._remove_ack_reaction(request)
return
@@ -216,7 +218,13 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
# The previous session is gone server-side — surface it as a terminal
# ERROR result (outbound chokepoint turns the dot red), don't silently
# fork a fresh session and lose context.
- await self.controller.emit_agent_message(request.context, "result", f"❌ {e}", is_error=True)
+ await self.controller.emit_agent_message(
+ request.context,
+ "result",
+ f"❌ {e}",
+ is_error=True,
+ output=terminal_output_for(request),
+ )
await self._remove_ack_reaction(request)
return
except Exception as e:
@@ -231,7 +239,13 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
request.context, "opencode", message
)
if not handled:
- await self.controller.emit_agent_message(request.context, "result", message, is_error=True)
+ await self.controller.emit_agent_message(
+ request.context,
+ "result",
+ message,
+ is_error=True,
+ output=terminal_output_for(request),
+ )
await self._remove_ack_reaction(request)
return
if not session_id:
@@ -240,6 +254,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
"result",
"Failed to obtain OpenCode session ID",
is_error=True,
+ output=terminal_output_for(request),
)
await self._remove_ack_reaction(request)
return
@@ -468,6 +483,7 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
"result",
message,
is_error=True,
+ output=terminal_output_for(request),
)
# handled == True persists the durable recovery notify centrally in
# ``maybe_emit_auth_recovery_message`` (which also latches the turn
@@ -506,7 +522,13 @@ class OpenCodeAgent(OpenCodeMessageProcessorMixin, BaseAgent):
# user-facing message: a single SILENT result settles the dot to idle +
# releases the SSE waiter through the outbound chokepoint without a bubble
# (``level="silent"`` makes that explicit rather than faking it via empty text).
- await self.controller.emit_agent_message(request.context, "result", "", level="silent")
+ await self.controller.emit_agent_message(
+ request.context,
+ "result",
+ "",
+ level="silent",
+ output=terminal_output_for(request),
+ )
logger.info(f"OpenCode session {request.base_session_id} terminated via /stop")
return True
diff --git a/modules/agents/opencode/poll_loop.py b/modules/agents/opencode/poll_loop.py
index 6d91bac21..ff20eecf4 100644
--- a/modules/agents/opencode/poll_loop.py
+++ b/modules/agents/opencode/poll_loop.py
@@ -9,6 +9,7 @@ from typing import Any, Dict, Optional
from config.v2_config import DEFAULT_OPENCODE_ERROR_RETRY_LIMIT
from core.message_context import build_context_session_key
+from core.message_output import terminal_output_for, terminal_turn_output
from modules.agents.base import AgentRequest
from modules.im import MessageContext
from vibe.i18n import t as i18n_t
@@ -162,6 +163,7 @@ class OpenCodePollLoop:
message,
is_error=True,
level="silent",
+ output=terminal_turn_output(),
)
def _build_restored_ack_request(self, poll_info) -> AgentRequest:
@@ -311,7 +313,13 @@ class OpenCodePollLoop:
logger.warning("Aborting OpenCode session %s after disabled question tool call", session_id)
# Terminal abort → error RESULT so the outbound chokepoint
# turns the dot red (not a bare notify that never settles it).
- await self._agent.controller.emit_agent_message(request.context, "result", message, is_error=True)
+ await self._agent.controller.emit_agent_message(
+ request.context,
+ "result",
+ message,
+ is_error=True,
+ output=terminal_output_for(request),
+ )
try:
await server.abort_session(session_id, request.working_path)
except Exception as abort_err:
@@ -416,6 +424,7 @@ class OpenCodePollLoop:
"result",
message,
is_error=True,
+ output=terminal_output_for(request),
)
# Terminal: stop polling AND signal the caller NOT to emit the
# "(No response from OpenCode)" warning result — that warning is
@@ -552,7 +561,13 @@ class OpenCodePollLoop:
session_id,
)
# Terminal abort → error RESULT (settles the dot red).
- await self._agent.controller.emit_agent_message(context, "result", message, is_error=True)
+ await self._agent.controller.emit_agent_message(
+ context,
+ "result",
+ message,
+ is_error=True,
+ output=terminal_turn_output(),
+ )
try:
await server.abort_session(session_id, poll_info.working_path)
except Exception as abort_err:
@@ -619,6 +634,7 @@ class OpenCodePollLoop:
"result",
message,
is_error=True,
+ output=terminal_turn_output(),
)
self._agent.sessions.remove_active_poll(session_id)
await self.remove_restored_ack(poll_info)
@@ -714,4 +730,5 @@ class OpenCodePollLoop:
"result",
message,
is_error=True,
+ output=terminal_turn_output(),
)
diff --git a/modules/agents/service.py b/modules/agents/service.py
index 0328d80b4..acfdf5133 100644
--- a/modules/agents/service.py
+++ b/modules/agents/service.py
@@ -5,6 +5,7 @@ from dataclasses import dataclass, field
from typing import Any, Dict, Optional
from core.session_activities import SessionActivityRegistry
+from core.message_output import terminal_output_for, terminal_turn_output
from .base import (
AGENT_RUNTIME_TURN_KEY,
@@ -22,12 +23,24 @@ STALE_STOP_REASONS = {"not_active", "runtime_unavailable"}
class AgentService:
"""Registry and dispatcher for agent implementations."""
- def __init__(self, controller):
+ def __init__(
+ self,
+ controller,
+ *,
+ activities: SessionActivityRegistry | None = None,
+ ):
self.controller = controller
self.agents: Dict[str, BaseAgent] = {}
self.default_agent = "claude"
self._turn_gates: dict[str, _RuntimeTurnGate] = {}
- self.activities = SessionActivityRegistry()
+ self.activities = activities or SessionActivityRegistry()
+ set_output_settled_callback = getattr(
+ self.activities,
+ "set_output_settled_callback",
+ None,
+ )
+ if callable(set_output_settled_callback):
+ set_output_settled_callback(self._on_activity_output_settled)
# 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()
@@ -79,26 +92,40 @@ 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."""
+ def _on_activity_output_settled(self, activity: Any) -> None:
+ agent = self.agents.get(str(getattr(activity, "backend", "") or ""))
+ notify = getattr(agent, "on_activity_output_settled", None)
+ if callable(notify):
+ notify(str(getattr(activity, "runtime_key", "") or ""))
+
+ def on_activity_terminal(self, activity: Any) -> bool:
+ """Let the Run owner acknowledge one terminal Activity."""
service = getattr(self.controller, "scheduled_task_service", None)
settle = getattr(service, "settle_activity_runs", None)
if not callable(settle):
- return
+ return False
try:
settle(activity)
+ if str(getattr(activity, "status", "") or "") != "completed":
+ self.activities.ack_recovered_terminal(activity)
+ return True
except Exception:
logger.warning(
"Failed to settle Runs for terminal Activity %s",
getattr(activity, "id", ""),
exc_info=True,
)
+ return False
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)
+ completed = self.activities.end_runtime(
+ backend,
+ runtime_key,
+ retain_terminal_snapshots=True,
+ )
for activity in completed:
self.on_activity_terminal(activity)
return completed
@@ -245,7 +272,14 @@ class AgentService:
async def _tidy_on_cancel() -> None:
try:
- await emit(request.context, "result", "", is_error=True, level="silent")
+ await emit(
+ request.context,
+ "result",
+ "",
+ is_error=True,
+ level="silent",
+ output=terminal_output_for(request),
+ )
except Exception:
logger.debug("Failed to emit terminal tidy on cancellation", exc_info=True)
finally:
@@ -270,7 +304,14 @@ class AgentService:
emit = getattr(self.controller, "emit_agent_message", None)
if callable(emit):
try:
- await emit(request.context, "result", "", is_error=True, level="silent")
+ await emit(
+ request.context,
+ "result",
+ "",
+ is_error=True,
+ level="silent",
+ output=terminal_output_for(request),
+ )
except Exception:
logger.debug("Failed to emit terminal result for backend exception", exc_info=True)
finally:
@@ -507,7 +548,14 @@ class AgentService:
context = gate.context
if context is not None and callable(emit):
try:
- await emit(context, "result", "", is_error=True, level="silent")
+ await emit(
+ context,
+ "result",
+ "",
+ is_error=True,
+ level="silent",
+ output=terminal_turn_output(),
+ )
except Exception:
logger.debug("Failed to settle forced backend turn %s", runtime_key, exc_info=True)
self.release_runtime_turn_key(runtime_key, token)
diff --git a/storage/background.py b/storage/background.py
index 963ac4a80..dbc5c43b8 100644
--- a/storage/background.py
+++ b/storage/background.py
@@ -920,6 +920,29 @@ class SQLiteBackgroundTaskStore:
row = conn.execute(select(agent_runs).where(agent_runs.c.id == run_id).limit(1)).mappings().first()
return self._run_from_row(row) if row else None
+ def list_deferred_runs(self) -> list[dict[str, Any]]:
+ """Return non-terminal Runs carrying a durable terminal intent."""
+
+ with self.engine.connect() as conn:
+ rows = list(
+ conn.execute(
+ select(agent_runs)
+ .where(
+ agent_runs.c.status.in_(
+ _status_query_values("queued")
+ + _status_query_values("running")
+ )
+ )
+ .order_by(agent_runs.c.created_at, agent_runs.c.id)
+ ).mappings()
+ )
+ deferred: list[dict[str, Any]] = []
+ for row in rows:
+ result_payload = _json_loads(row["result_payload_json"], {})
+ if isinstance(result_payload, dict) and result_payload.get("deferred_terminal_status"):
+ deferred.append(self._run_from_row(row))
+ return deferred
+
def list_pending_callbacks(self, *, limit: int = 20) -> list[dict[str, Any]]:
terminal_statuses = _status_query_values("succeeded") + _status_query_values("failed") + _status_query_values("canceled")
with self.engine.connect() as conn:
@@ -1467,18 +1490,25 @@ class SQLiteBackgroundTaskStore:
now = _utc_now_iso()
rows = list(
conn.execute(
- select(agent_runs.c.id)
+ select(agent_runs.c.id, agent_runs.c.result_payload_json)
.where(agent_runs.c.status.in_(_status_query_values("running")))
.where(agent_runs.c.run_type != "watch_runtime")
).mappings()
)
- recovered_ids = [str(row["id"]) for row in rows]
- conn.execute(
- update(agent_runs)
- .where(agent_runs.c.status.in_(_status_query_values("running")))
- .where(agent_runs.c.run_type != "watch_runtime")
- .values(status="queued", started_at=None, pid=None, updated_at=now)
- )
+ recovered_ids = []
+ for row in rows:
+ result_payload = _json_loads(row["result_payload_json"], {})
+ if isinstance(result_payload, dict) and result_payload.get(
+ "deferred_terminal_status"
+ ):
+ continue
+ recovered_ids.append(str(row["id"]))
+ if recovered_ids:
+ conn.execute(
+ update(agent_runs)
+ .where(agent_runs.c.id.in_(recovered_ids))
+ .values(status="queued", started_at=None, pid=None, updated_at=now)
+ )
_refresh_recovered_coalesced_workbench_runs_in_connection(conn, now=now)
_defer_run_ids_updated_from_connection(conn, recovered_ids)
diff --git a/storage/session_activities.py b/storage/session_activities.py
new file mode 100644
index 000000000..c759cc118
--- /dev/null
+++ b/storage/session_activities.py
@@ -0,0 +1,183 @@
+"""Durable operational snapshots for Session Activities.
+
+Activity is intentionally stored in the existing ``runtime_records`` aggregate:
+these rows are restart/recovery state, not a new public schema or transcript.
+The shared Activity registry owns lifecycle semantics and keeps this adapter
+limited to structured snapshot persistence.
+"""
+
+from __future__ import annotations
+
+import hashlib
+import json
+from datetime import datetime, timezone
+from typing import Any
+
+from sqlalchemy import delete, select
+from sqlalchemy.dialects.sqlite import insert as sqlite_insert
+from sqlalchemy.engine import Engine
+
+from storage.models import runtime_records
+
+
+ACTIVITY_RECORD_TYPE = "session_activity"
+CONNECTION_RECORD_TYPE = "session_activity_connection"
+ACTIVE_PHASE = "active"
+AWAITING_OUTPUT_PHASE = "awaiting_output"
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _json_dumps(value: Any) -> str:
+ return json.dumps(value, ensure_ascii=False, separators=(",", ":"))
+
+
+def _record_key(*parts: str) -> str:
+ identity = _json_dumps([str(part) for part in parts])
+ return hashlib.sha256(identity.encode("utf-8")).hexdigest()
+
+
+def _payload(row: Any) -> dict[str, Any] | None:
+ try:
+ value = json.loads(row["payload_json"] or "{}")
+ except (TypeError, json.JSONDecodeError):
+ return None
+ return value if isinstance(value, dict) else None
+
+
+class SQLiteSessionActivityStore:
+ """Persist current Activity/connection facts without defining a new table."""
+
+ def __init__(self, engine: Engine):
+ self.engine = engine
+
+ @staticmethod
+ def activity_key(*, backend: str, runtime_key: str, activity_id: str) -> str:
+ return _record_key(backend, runtime_key, activity_id)
+
+ @staticmethod
+ def connection_key(*, backend: str, runtime_key: str) -> str:
+ return _record_key(backend, runtime_key)
+
+ def upsert_activity(self, activity: dict[str, Any], *, phase: str) -> None:
+ backend = str(activity.get("backend") or "")
+ runtime_key = str(activity.get("runtime_key") or "")
+ activity_id = str(activity.get("id") or "")
+ if not backend or not runtime_key or not activity_id:
+ raise ValueError("Activity persistence requires backend, runtime_key, and id")
+ now = _utc_now_iso()
+ record_key = self.activity_key(
+ backend=backend,
+ runtime_key=runtime_key,
+ activity_id=activity_id,
+ )
+ values = {
+ "id": f"runtime::{ACTIVITY_RECORD_TYPE}::{record_key}",
+ "record_type": ACTIVITY_RECORD_TYPE,
+ "record_key": record_key,
+ "scope_id": None,
+ "session_anchor": activity.get("session_id"),
+ "workdir": None,
+ "payload_json": _json_dumps(
+ {
+ "version": 1,
+ "phase": phase,
+ "activity": activity,
+ }
+ ),
+ "expires_at": None,
+ "created_at": now,
+ "updated_at": now,
+ }
+ stmt = sqlite_insert(runtime_records).values(**values)
+ with self.engine.begin() as conn:
+ conn.execute(
+ stmt.on_conflict_do_update(
+ index_elements=[runtime_records.c.record_type, runtime_records.c.record_key],
+ set_={
+ "session_anchor": stmt.excluded.session_anchor,
+ "payload_json": stmt.excluded.payload_json,
+ "updated_at": stmt.excluded.updated_at,
+ },
+ )
+ )
+
+ def delete_activity(self, *, backend: str, runtime_key: str, activity_id: str) -> None:
+ record_key = self.activity_key(
+ backend=backend,
+ runtime_key=runtime_key,
+ activity_id=activity_id,
+ )
+ with self.engine.begin() as conn:
+ conn.execute(
+ delete(runtime_records)
+ .where(runtime_records.c.record_type == ACTIVITY_RECORD_TYPE)
+ .where(runtime_records.c.record_key == record_key)
+ )
+
+ def list_activities(self) -> list[dict[str, Any]]:
+ with self.engine.connect() as conn:
+ rows = list(
+ conn.execute(
+ select(runtime_records)
+ .where(runtime_records.c.record_type == ACTIVITY_RECORD_TYPE)
+ .order_by(runtime_records.c.created_at, runtime_records.c.id)
+ ).mappings()
+ )
+ return [payload for row in rows if (payload := _payload(row)) is not None]
+
+ def upsert_connection(
+ self,
+ *,
+ backend: str,
+ runtime_key: str,
+ session_id: str | None,
+ state: str,
+ ) -> None:
+ now = _utc_now_iso()
+ record_key = self.connection_key(backend=backend, runtime_key=runtime_key)
+ values = {
+ "id": f"runtime::{CONNECTION_RECORD_TYPE}::{record_key}",
+ "record_type": CONNECTION_RECORD_TYPE,
+ "record_key": record_key,
+ "scope_id": None,
+ "session_anchor": session_id,
+ "workdir": None,
+ "payload_json": _json_dumps(
+ {
+ "version": 1,
+ "backend": str(backend),
+ "runtime_key": str(runtime_key),
+ "session_id": session_id,
+ "state": str(state),
+ }
+ ),
+ "expires_at": None,
+ "created_at": now,
+ "updated_at": now,
+ }
+ stmt = sqlite_insert(runtime_records).values(**values)
+ with self.engine.begin() as conn:
+ conn.execute(
+ stmt.on_conflict_do_update(
+ index_elements=[runtime_records.c.record_type, runtime_records.c.record_key],
+ set_={
+ "session_anchor": stmt.excluded.session_anchor,
+ "payload_json": stmt.excluded.payload_json,
+ "updated_at": stmt.excluded.updated_at,
+ },
+ )
+ )
+
+ def list_connections(self) -> list[dict[str, Any]]:
+ with self.engine.connect() as conn:
+ rows = list(
+ conn.execute(
+ select(runtime_records)
+ .where(runtime_records.c.record_type == CONNECTION_RECORD_TYPE)
+ .order_by(runtime_records.c.created_at, runtime_records.c.id)
+ ).mappings()
+ )
+ return [payload for row in rows if (payload := _payload(row)) is not None]
diff --git a/tests/test_agent_auth_service.py b/tests/test_agent_auth_service.py
index 9a89b0677..850d5eaa3 100644
--- a/tests/test_agent_auth_service.py
+++ b/tests/test_agent_auth_service.py
@@ -6,7 +6,7 @@ import unittest
from contextlib import contextmanager
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock, Mock, patch
+from unittest.mock import ANY, AsyncMock, Mock, patch
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
@@ -214,7 +214,13 @@ class AgentAuthServiceTests(_IsolatedClaudeConfigDirMixin, unittest.IsolatedAsyn
)
self.assertTrue(handled)
- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True)
+ controller.emit_agent_message.assert_awaited_once_with(
+ context,
+ "result",
+ "",
+ is_error=True,
+ output=ANY,
+ )
async def test_maybe_emit_auth_recovery_message_defers_non_auth_error_to_caller(self):
# A NON-auth terminal error returns False: the calling backend emits its
diff --git a/tests/test_agent_service.py b/tests/test_agent_service.py
index d8288a3b8..b8430be3f 100644
--- a/tests/test_agent_service.py
+++ b/tests/test_agent_service.py
@@ -1,12 +1,18 @@
from __future__ import annotations
import asyncio
+from pathlib import Path
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
import pytest
+from core.message_output import terminal_turn_output
+from core.session_activities import SessionActivityRegistry
from modules.agents.service import AgentService
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.session_activities import SQLiteSessionActivityStore
class _RuntimeAgent:
@@ -211,6 +217,8 @@ def test_agent_service_notifies_run_owner_when_activity_runtime_disconnects() ->
kind="background_task",
run_id="run-1",
)
+ original_ack = service.activities.ack_recovered_terminal
+ service.activities.ack_recovered_terminal = Mock(wraps=original_ack)
service.end_activity_runtime("claude", "runtime-1")
@@ -219,6 +227,46 @@ def test_agent_service_notifies_run_owner_when_activity_runtime_disconnects() ->
assert activity.id == "task-1"
assert activity.run_id == "run-1"
assert activity.status == "disconnected"
+ service.activities.ack_recovered_terminal.assert_called_once_with(activity)
+
+
+def test_activity_runtime_disconnect_retains_snapshot_until_run_settles(
+ tmp_path: Path,
+) -> None:
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ ensure_sqlite_state(db_path=db_path, primary_platform="avibe")
+ engine = create_sqlite_engine(db_path)
+ store = SQLiteSessionActivityStore(engine)
+ controller = SimpleNamespace(
+ scheduled_task_service=SimpleNamespace(
+ settle_activity_runs=Mock(side_effect=RuntimeError("store unavailable")),
+ ),
+ )
+ service = AgentService(
+ controller,
+ activities=SessionActivityRegistry(store),
+ )
+ 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")
+
+ records = store.list_activities()
+ assert len(records) == 1
+ assert records[0]["phase"] == "terminal"
+ assert records[0]["activity"]["status"] == "disconnected"
+ recovered = SessionActivityRegistry(store)
+ terminal = recovered.drain_recovered_terminals()
+ assert [(item.id, item.run_id, item.status) for item in terminal] == [
+ ("task-1", "run-1", "disconnected"),
+ ]
+ engine.dispose()
def test_agent_service_serializes_same_runtime_until_terminal_release() -> None:
@@ -334,6 +382,8 @@ def test_force_end_backend_activities_settles_pending_runs() -> None:
status="completed",
expects_output=True,
)
+ original_ack = service.activities.ack_recovered_terminal
+ service.activities.ack_recovered_terminal = Mock(wraps=original_ack)
service.force_end_backend_activities("claude")
@@ -341,6 +391,33 @@ def test_force_end_backend_activities_settles_pending_runs() -> None:
("task-active", "killed"),
("task-pending", "killed"),
]
+ assert service.activities.ack_recovered_terminal.call_count == 2
+
+
+def test_force_end_backend_activities_waits_for_run_settlement_before_ack() -> None:
+ controller = SimpleNamespace(
+ scheduled_task_service=SimpleNamespace(
+ settle_activity_runs=Mock(side_effect=RuntimeError("store unavailable")),
+ ),
+ )
+ service = AgentService(controller=controller)
+ service.activities.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ activity_id="task-active",
+ kind="background_task",
+ run_id="run-active",
+ )
+ original_ack = service.activities.ack_recovered_terminal
+ service.activities.ack_recovered_terminal = Mock(wraps=original_ack)
+
+ completed = service.force_end_backend_activities("claude")
+
+ assert [(item.id, item.status) for item in completed] == [
+ ("task-active", "killed"),
+ ]
+ service.activities.ack_recovered_terminal.assert_not_called()
def test_force_cancel_backend_turns_emits_terminal_before_release() -> None:
@@ -365,6 +442,7 @@ def test_force_cancel_backend_turns_emits_terminal_before_release() -> None:
"",
is_error=True,
level="silent",
+ output=terminal_turn_output(),
)
assert service.runtime_turn_tokens_for_backend("claude") == {}
diff --git a/tests/test_agent_silent_result.py b/tests/test_agent_silent_result.py
index ab10ce376..c43899cbe 100644
--- a/tests/test_agent_silent_result.py
+++ b/tests/test_agent_silent_result.py
@@ -25,10 +25,20 @@ class _StubController:
return self._token_field
async def emit_agent_message(
- self, context, message_type, text, parse_mode="markdown", *, is_error=False, level="normal", result_footer=None
+ self,
+ context,
+ message_type,
+ text,
+ parse_mode="markdown",
+ *,
+ is_error=False,
+ level="normal",
+ result_footer=None,
+ output=None,
):
self.messages.append((message_type, text, parse_mode))
self.result_footers.append(result_footer)
+ return "message-id"
class _StubAgent(BaseAgent):
@@ -44,7 +54,7 @@ class AgentSilentResultTests(unittest.IsolatedAsyncioTestCase):
agent = _StubAgent(controller)
context = MessageContext(user_id="U1", channel_id="C1", platform="slack")
- await agent.emit_result_message(
+ message_id = await agent.emit_result_message(
context,
"<silent>not relevant</silent>",
subtype="success",
@@ -52,6 +62,7 @@ class AgentSilentResultTests(unittest.IsolatedAsyncioTestCase):
)
self.assertEqual(controller.messages, [("result", "", "markdown")])
+ self.assertEqual(message_id, "message-id")
async def test_no_visible_result_with_duration_hidden_settles_via_outbound(self):
# show_duration off + empty result/suffix is still a TERMINAL turn: it is
diff --git a/tests/test_claude_agent_initiated_turn.py b/tests/test_claude_agent_initiated_turn.py
index c41ff74e8..be4da0bbd 100644
--- a/tests/test_claude_agent_initiated_turn.py
+++ b/tests/test_claude_agent_initiated_turn.py
@@ -22,12 +22,13 @@ import sys
import unittest
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock
+from unittest.mock import AsyncMock, Mock
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
from modules.agents.claude_agent import ClaudeAgent
from modules.agents.service import AgentService
+from core.message_output import terminal_output_for
# Class names mirror the Claude SDK frames so ``_detect_message_type`` (which maps
@@ -345,10 +346,9 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
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)
+ claimed = service.activities.claim_completed_output("claude", composite_key)
+ self.assertIsNotNone(claimed)
+ self.assertTrue(service.activities.ack_completed_output(claimed))
await asyncio.wait_for(waiter, timeout=1)
async def test_terminal_only_task_event_keeps_current_turn_origin(self):
@@ -374,6 +374,96 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
self.assertIsNotNone(activity)
self.assertEqual(activity.turn_id, "current-turn")
+ async def test_failed_activity_snapshot_waits_for_run_owner_ack(self):
+ agent, service = _build_agent()
+ composite_key = "session-failed-activity:/tmp/work"
+ context = SimpleNamespace(
+ platform_specific={"agent_session_id": "sess-failed-activity"},
+ )
+ service.activities.start(
+ backend="claude",
+ runtime_key=composite_key,
+ session_id="sess-failed-activity",
+ activity_id="task-failed",
+ kind="local_agent",
+ run_id="run-failed",
+ )
+ agent.controller.scheduled_task_service = SimpleNamespace(
+ settle_activity_runs=Mock(side_effect=RuntimeError("store unavailable")),
+ )
+ original_complete = service.activities.complete
+ service.activities.complete = Mock(wraps=original_complete)
+ original_ack = service.activities.ack_recovered_terminal
+ service.activities.ack_recovered_terminal = Mock(wraps=original_ack)
+ failed = SimpleNamespace(
+ subtype="task_notification",
+ task_id="task-failed",
+ status="failed",
+ summary="Background verification failed",
+ data={},
+ )
+
+ self.assertTrue(
+ agent._handle_activity_message(
+ failed,
+ composite_key,
+ context,
+ )
+ )
+
+ call = service.activities.complete.call_args
+ self.assertTrue(call.kwargs["retain_terminal_snapshot"])
+ completed = agent.controller.scheduled_task_service.settle_activity_runs.call_args.args[0]
+ self.assertEqual(completed.status, "failed")
+ service.activities.ack_recovered_terminal.assert_not_called()
+
+ async def test_activity_keeps_origin_delivery_target_when_a_newer_turn_arrives(self):
+ agent, service = _build_agent()
+ composite_key = "session-delivery-origin:/tmp/work"
+ origin_context = SimpleNamespace(
+ platform_specific={
+ "turn_token": "origin-turn",
+ "delivery_key_external": "slack::channel::C-ORIGIN",
+ },
+ )
+ agent._pending_requests[composite_key] = [SimpleNamespace(context=origin_context)]
+ receiver_context = SimpleNamespace(
+ platform_specific={"agent_session_id": "sess-delivery-origin"},
+ )
+
+ self.assertTrue(
+ agent._handle_activity_message(
+ TaskStartedMessage(),
+ composite_key,
+ receiver_context,
+ )
+ )
+ agent._pending_requests[composite_key] = [
+ SimpleNamespace(
+ context=SimpleNamespace(
+ platform_specific={
+ "turn_token": "newer-turn",
+ "delivery_key_external": "slack::channel::C-NEWER",
+ },
+ )
+ )
+ ]
+
+ self.assertTrue(
+ agent._handle_activity_message(
+ TaskNotificationMessage(),
+ composite_key,
+ receiver_context,
+ )
+ )
+
+ activity = service.activities.claim_completed_output("claude", composite_key)
+ self.assertIsNotNone(activity)
+ self.assertEqual(
+ activity.metadata["delivery_key_external"],
+ "slack::channel::C-ORIGIN",
+ )
+
async def test_completed_task_notification_at_eof_delivers_summary(self):
agent, service = _build_agent()
composite_key = "session-eof:/tmp/work"
@@ -388,7 +478,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
"agent_session_id": "sess-eof",
},
)
- agent.emit_result_message = AsyncMock()
+ agent.emit_result_message = AsyncMock(return_value="message-id")
await agent._receive_messages(
_completed_task_notification_client(),
@@ -428,6 +518,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
async def _emit(*_args, **_kwargs):
emitted.set()
+ return "message-id"
agent.emit_result_message = AsyncMock(side_effect=_emit)
release = asyncio.Event()
@@ -454,6 +545,82 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
release.set()
await receiver
+ async def test_summaryless_completed_activity_settles_silently(self):
+ agent, service = _build_agent()
+ composite_key = "session-silent-activity:/tmp/work"
+ context = SimpleNamespace(
+ platform_specific={"agent_session_id": "sess-silent-activity"}
+ )
+ service.activities.start(
+ backend="claude",
+ runtime_key=composite_key,
+ session_id="sess-silent-activity",
+ activity_id="task-silent",
+ kind="local_agent",
+ turn_id="origin-turn",
+ )
+ service.activities.complete(
+ backend="claude",
+ runtime_key=composite_key,
+ activity_id="task-silent",
+ status="completed",
+ expects_output=True,
+ )
+ agent.emit_result_message = AsyncMock()
+ agent.controller.emit_agent_message = AsyncMock(return_value=None)
+
+ should_retry = await agent._flush_completed_activity_outputs(
+ composite_key,
+ context,
+ )
+
+ self.assertFalse(should_retry)
+ agent.emit_result_message.assert_not_awaited()
+ agent.controller.emit_agent_message.assert_awaited_once()
+ silent_call = agent.controller.emit_agent_message.await_args
+ self.assertEqual(silent_call.args[:3], (context, "result", ""))
+ output = silent_call.kwargs["output"]
+ self.assertTrue(output.detached)
+ self.assertFalse(output.completes_turn)
+ self.assertTrue(output.completes_run)
+ self.assertFalse(service.activities.has_completed_output("claude", composite_key))
+
+ async def test_silent_only_completed_activity_settles_without_retry(self):
+ agent, service = _build_agent()
+ composite_key = "session-silent-directive:/tmp/work"
+ context = SimpleNamespace(
+ platform_specific={"agent_session_id": "sess-silent-directive"}
+ )
+ service.activities.start(
+ backend="claude",
+ runtime_key=composite_key,
+ session_id="sess-silent-directive",
+ activity_id="task-silent",
+ kind="local_agent",
+ turn_id="origin-turn",
+ )
+ service.activities.complete(
+ backend="claude",
+ runtime_key=composite_key,
+ activity_id="task-silent",
+ status="completed",
+ metadata={"summary": "<silent>no visible follow-up</silent>"},
+ expects_output=True,
+ )
+ agent.emit_result_message = AsyncMock()
+ agent.controller.emit_agent_message = AsyncMock(return_value=None)
+
+ should_retry = await agent._flush_completed_activity_outputs(
+ composite_key,
+ context,
+ )
+
+ self.assertFalse(should_retry)
+ agent.emit_result_message.assert_not_awaited()
+ silent_call = agent.controller.emit_agent_message.await_args
+ self.assertEqual(silent_call.args[:3], (context, "result", ""))
+ self.assertFalse(service.activities.has_completed_output("claude", composite_key))
+
async def test_timed_flush_keeps_activity_for_a_newer_pending_turn(self):
agent, service = _build_agent()
composite_key = "session-deferred-flush:/tmp/work"
@@ -486,6 +653,81 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
self.assertIsNotNone(claimed)
self.assertEqual(claimed.turn_id, "origin-turn")
+ async def test_detached_activity_output_requeues_when_delivery_returns_none(self):
+ agent, service = _build_agent()
+ composite_key = "session-delivery-failed:/tmp/work"
+ context = SimpleNamespace(
+ platform_specific={"agent_session_id": "sess-delivery-failed"}
+ )
+ service.activities.start(
+ backend="claude",
+ runtime_key=composite_key,
+ session_id="sess-delivery-failed",
+ 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,
+ )
+ activity = service.activities.claim_completed_output("claude", composite_key)
+ self.assertIsNotNone(activity)
+ agent._detached_activity_outputs[composite_key] = activity
+ agent._detached_assistant_text[composite_key] = "Full background result"
+ agent.emit_result_message = AsyncMock(return_value=None)
+
+ with self.assertRaisesRegex(RuntimeError, "was not persisted or delivered"):
+ await agent._flush_detached_activity_output(composite_key, context)
+
+ claimed = service.activities.claim_completed_output("claude", composite_key)
+ self.assertIsNotNone(claimed)
+ self.assertEqual(claimed.id, "task-690")
+
+ async def test_requeued_request_activity_restores_terminal_turn_policy(self):
+ agent, service = _build_agent()
+ composite_key = "session-requeued-policy:/tmp/work"
+ service.activities.start(
+ backend="claude",
+ runtime_key=composite_key,
+ session_id="sess-requeued-policy",
+ 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",
+ expects_output=True,
+ )
+ activity = service.activities.claim_completed_output("claude", composite_key)
+ self.assertIsNotNone(activity)
+ request = SimpleNamespace(
+ output_activity=activity,
+ output=agent._activity_message_output(
+ activity,
+ detached=False,
+ completes_turn=True,
+ ),
+ )
+
+ agent._requeue_request_activity(request)
+
+ self.assertIsNone(request.output_activity)
+ restored = terminal_output_for(request)
+ self.assertTrue(restored.completes_turn)
+ self.assertTrue(restored.settles_run)
+ self.assertIsNone(restored.activity_id)
+ self.assertIsNotNone(
+ service.activities.claim_completed_output("claude", composite_key)
+ )
+
async def test_requeued_terminal_only_activity_flushes_after_pending_turn(self):
agent, service = _build_agent()
agent.ACTIVITY_OUTPUT_FLUSH_GRACE_SECONDS = 0
@@ -521,7 +763,11 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
service.activities.requeue_completed_output = _requeue
emitted = asyncio.Event()
- agent.emit_result_message = AsyncMock(side_effect=lambda *_a, **_k: emitted.set())
+ async def _emit(*_args, **_kwargs):
+ emitted.set()
+ return "message-id"
+
+ agent.emit_result_message = AsyncMock(side_effect=_emit)
agent._schedule_completed_activity_flush(composite_key, context)
await asyncio.wait_for(requeued.wait(), timeout=1)
@@ -531,6 +777,149 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
self.assertFalse(service.activities.has_completed_output("claude", composite_key))
self.assertFalse(agent._activity_output_pending(composite_key))
+ async def test_same_turn_summary_delivery_failure_retries_detached(self):
+ agent, service = _build_agent()
+ composite_key = "session-same-turn-retry:/tmp/work"
+ pending_request = SimpleNamespace(
+ context=SimpleNamespace(platform_specific={"turn_token": "origin-turn"})
+ )
+ agent._pending_requests[composite_key] = [pending_request]
+ context = SimpleNamespace(
+ platform_specific={"agent_session_id": "sess-same-turn-retry"}
+ )
+ service.activities.start(
+ backend="claude",
+ runtime_key=composite_key,
+ session_id="sess-same-turn-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,
+ )
+ agent.emit_result_message = AsyncMock(
+ side_effect=[None, "delivered-message-id"],
+ )
+ agent._remove_result_pending_reaction = AsyncMock()
+
+ with self.assertRaisesRegex(RuntimeError, "was not persisted or delivered"):
+ await agent._flush_completed_activity_outputs(composite_key, context)
+
+ self.assertFalse(agent._has_pending_requests(composite_key))
+ agent._remove_result_pending_reaction.assert_awaited_once_with(
+ composite_key,
+ context,
+ pending_request,
+ )
+ self.assertTrue(service.activities.has_completed_output("claude", composite_key))
+ tidy_output = agent.controller.emit_agent_message.await_args.kwargs["output"]
+ self.assertTrue(tidy_output.completes_turn)
+ self.assertFalse(tidy_output.settles_run)
+
+ await agent._flush_completed_activity_outputs(composite_key, context)
+
+ self.assertFalse(agent._has_pending_requests(composite_key))
+ first_output = agent.emit_result_message.await_args_list[0].kwargs["output"]
+ second_output = agent.emit_result_message.await_args_list[1].kwargs["output"]
+ self.assertFalse(first_output.detached)
+ self.assertTrue(first_output.completes_turn)
+ self.assertTrue(second_output.detached)
+ self.assertFalse(second_output.completes_turn)
+ self.assertFalse(service.activities.has_completed_output("claude", composite_key))
+
+ async def test_result_frame_activity_delivery_failure_retries_detached(self):
+ agent, service = _build_agent()
+ agent.ACTIVITY_OUTPUT_FLUSH_GRACE_SECONDS = 3600
+ composite_key = "session-result-retry:/tmp/work"
+ pending_context = SimpleNamespace(
+ platform_specific={"turn_token": "origin-turn"},
+ )
+ context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform="avibe",
+ platform_specific={
+ "agent_session_id": "sess-result-retry",
+ "turn_token": "origin-turn",
+ },
+ )
+ service.activities.start(
+ backend="claude",
+ runtime_key=composite_key,
+ session_id="sess-result-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,
+ )
+ activity = service.activities.claim_completed_output("claude", composite_key)
+ self.assertIsNotNone(activity)
+ pending_request = SimpleNamespace(
+ context=pending_context,
+ output_activity=activity,
+ )
+ agent._pending_requests[composite_key] = [pending_request]
+ agent.emit_result_message = AsyncMock(
+ side_effect=[None, "delivered-message-id"],
+ )
+ agent._remove_result_pending_reaction = AsyncMock()
+ result_processed = asyncio.Event()
+ release_receiver = asyncio.Event()
+
+ class _Client:
+ def receive_messages(self):
+ async def _iterate():
+ yield ResultMessage()
+ result_processed.set()
+ await release_receiver.wait()
+
+ return _iterate()
+
+ receiver = asyncio.create_task(
+ agent._receive_messages(
+ _Client(),
+ "session-result-retry",
+ "/tmp/work",
+ context,
+ composite_key=composite_key,
+ )
+ )
+ await asyncio.wait_for(result_processed.wait(), timeout=1)
+
+ self.assertFalse(agent._has_pending_requests(composite_key))
+ agent._remove_result_pending_reaction.assert_awaited_once_with(
+ composite_key,
+ context,
+ pending_request,
+ )
+ self.assertTrue(service.activities.has_completed_output("claude", composite_key))
+
+ release_receiver.set()
+ await receiver
+
+ self.assertFalse(agent._has_pending_requests(composite_key))
+ self.assertEqual(agent.emit_result_message.await_count, 2)
+ first_output = agent.emit_result_message.await_args_list[0].kwargs["output"]
+ second_output = agent.emit_result_message.await_args_list[1].kwargs["output"]
+ self.assertFalse(first_output.detached)
+ self.assertTrue(first_output.completes_turn)
+ self.assertTrue(second_output.detached)
+ self.assertFalse(second_output.completes_turn)
+ self.assertFalse(service.activities.has_completed_output("claude", 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)
@@ -688,7 +1077,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
"agent_session_id": "sess-690",
},
)
- agent.emit_result_message = AsyncMock()
+ agent.emit_result_message = AsyncMock(return_value="message-id")
service.activities.start(
backend="claude",
runtime_key=composite_key,
@@ -722,6 +1111,63 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
self.assertTrue(gate.lock.locked())
agent.controller.emit_agent_message.assert_not_awaited()
+ async def test_title_backfill_failure_does_not_requeue_delivered_activity(self):
+ agent, service = _build_agent()
+ composite_key = "session-title-backfill:/tmp/work"
+ pending_context = SimpleNamespace(
+ platform_specific={"turn_token": "origin-turn"},
+ )
+ pending_request = SimpleNamespace(context=pending_context)
+ agent._pending_requests[composite_key] = [pending_request]
+ receiver_context = SimpleNamespace(
+ user_id="U1",
+ channel_id="C1",
+ platform="avibe",
+ platform_specific={
+ "agent_session_id": "sess-title-backfill",
+ "turn_token": "origin-turn",
+ },
+ )
+ service.activities.start(
+ backend="claude",
+ runtime_key=composite_key,
+ session_id="sess-title-backfill",
+ 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(return_value="message-id")
+ agent._native_session_ids[composite_key] = "claude-native-session"
+ agent._maybe_backfill_session_title = Mock(
+ side_effect=RuntimeError("title store unavailable")
+ )
+
+ await agent._receive_messages(
+ _one_result_client(),
+ "session-title-backfill",
+ "/tmp/work",
+ receiver_context,
+ composite_key=composite_key,
+ )
+
+ agent.emit_result_message.assert_awaited_once()
+ agent._maybe_backfill_session_title.assert_called_once_with(
+ pending_request,
+ "claude-native-session",
+ )
+ self.assertFalse(service.activities.has_completed_output("claude", composite_key))
+ self.assertIsNone(
+ service.activities.claim_completed_output("claude", composite_key)
+ )
+
async def test_contended_activity_result_does_not_poison_next_user_result(self):
agent, service = _build_agent()
composite_key = "session-contended:/tmp/work"
@@ -740,7 +1186,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
"agent_session_id": "sess-contended",
},
)
- agent.emit_result_message = AsyncMock()
+ agent.emit_result_message = AsyncMock(return_value="message-id")
service.activities.start(
backend="claude",
runtime_key=composite_key,
@@ -829,7 +1275,7 @@ class ReceiverOpensAgentInitiatedTurnTests(unittest.IsolatedAsyncioTestCase):
"agent_session_id": "sess-wakeup",
},
)
- agent.emit_result_message = AsyncMock()
+ agent.emit_result_message = AsyncMock(return_value="message-id")
try:
await agent._receive_messages(
_one_result_client(),
diff --git a/tests/test_claude_agent_sessions.py b/tests/test_claude_agent_sessions.py
index 211071cc0..ca93a41e7 100644
--- a/tests/test_claude_agent_sessions.py
+++ b/tests/test_claude_agent_sessions.py
@@ -3,7 +3,7 @@ import sys
import unittest
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock, MagicMock, patch
+from unittest.mock import ANY, AsyncMock, MagicMock, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
@@ -348,7 +348,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(queries, [("first", runtime_key)])
self.assertEqual(mark_active_calls, [runtime_key])
self.assertIn(runtime_key, mark_idle_calls)
- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True)
+ controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)
agent._remove_ack_reaction.assert_awaited_once_with(request)
self.assertNotIn(runtime_key, agent._pending_requests)
self.assertNotIn(runtime_key, controller.claude_sessions)
@@ -1219,7 +1219,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
await agent._receive_messages(_FailingClient(), "session-1", "/tmp/work", context)
agent.session_handler.handle_session_error.assert_awaited_once()
- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True)
+ controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)
persist.assert_called_once()
self.assertEqual(persist.call_args.args[1], "notify")
self.assertEqual(persist.call_args.args[2], "❌ Claude error: Connection lost")
@@ -1253,7 +1253,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
await agent._receive_messages(_FailingClient(), "session-1", "/tmp/work", context)
agent.session_handler.handle_session_error.assert_awaited_once()
- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True)
+ controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)
controller.agent_auth_service.maybe_emit_auth_recovery_message.assert_awaited_once_with(
context,
"claude",
@@ -1678,7 +1678,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
await asyncio.wait_for(receiver_task, timeout=1)
- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True)
+ controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)
self.assertFalse(service._turn_gates[composite_key].lock.locked())
self.assertNotIn(composite_key, controller.claude_sessions)
self.assertNotIn(composite_key, agent._pending_requests)
@@ -1784,6 +1784,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
"",
is_error=True,
level="silent",
+ output=ANY,
)
self.assertEqual(pending_context.platform_specific["turn_token"], "current")
self.assertEqual(pending_context.platform_specific["agent_runtime_turn_token"], "current-runtime")
@@ -1851,7 +1852,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
await asyncio.wait_for(receiver_task, timeout=1)
- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True)
+ controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)
self.assertEqual(context.platform_specific["turn_token"], "current-turn")
self.assertEqual(context.platform_specific["agent_runtime_turn_token"], "current-runtime")
self.assertFalse(service._turn_gates[composite_key].lock.locked())
@@ -1992,7 +1993,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
await agent._receive_messages(_Client(), "session-1", "/tmp/work", context, composite_key=composite_key)
- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True)
+ controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)
agent.emit_result_message.assert_not_awaited()
agent._remove_ack_reaction.assert_awaited_once_with(pending_request)
self.assertEqual(context.platform_specific["turn_token"], "T1")
@@ -2047,7 +2048,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
await agent._receive_messages(_Client(), "session-1", "/tmp/work", context, composite_key=composite_key)
- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True)
+ controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)
agent.emit_result_message.assert_not_awaited()
self.assertEqual(agent._pending_requests[composite_key], [next_request])
self.assertEqual(agent._pending_reactions[composite_key], [("m2", ":eyes:")])
@@ -2105,7 +2106,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
await agent._receive_messages(_Client(), "session-1", "/tmp/work", context, composite_key=composite_key)
- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True)
+ controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)
agent.emit_result_message.assert_not_awaited()
self.assertEqual(agent._pending_requests[composite_key], [next_request])
self.assertEqual(agent._pending_reactions[composite_key], [("m2", ":eyes:")])
@@ -2177,7 +2178,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
client.ready.set()
await receiver_task
- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True)
+ controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)
agent.emit_result_message.assert_not_awaited()
self.assertEqual(agent._pending_requests[composite_key], [followup_request])
self.assertEqual(agent._pending_reactions[composite_key], [("m2", ":eyes:")])
@@ -2250,7 +2251,7 @@ class ClaudeAgentSessionTests(unittest.IsolatedAsyncioTestCase):
client.ready.set()
await receiver_task
- controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True)
+ controller.emit_agent_message.assert_awaited_once_with(context, "result", "", is_error=True, output=ANY)
agent.emit_result_message.assert_awaited_once_with(
context,
"next turn result",
diff --git a/tests/test_codex_agent.py b/tests/test_codex_agent.py
index 97c8f1128..c6f208fbb 100644
--- a/tests/test_codex_agent.py
+++ b/tests/test_codex_agent.py
@@ -7,7 +7,7 @@ import types
import unittest
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock, Mock, patch
+from unittest.mock import ANY, AsyncMock, Mock, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
@@ -621,7 +621,7 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
# Force-reaped stuck turns must settle Workbench status + runtime gate
# through the shared terminal-result chokepoint.
agent.controller.emit_agent_message.assert_awaited_once_with(
- "ctx-1", "result", "", is_error=True, level="silent"
+ "ctx-1", "result", "", is_error=True, level="silent", output=ANY
)
self.assertEqual(agent._event_handler.release_calls, [])
@@ -641,7 +641,7 @@ class CodexAgentStopTests(unittest.IsolatedAsyncioTestCase):
self.assertEqual(evicted, 1)
self.assertEqual(stop_calls, ["stop"])
agent.controller.emit_agent_message.assert_awaited_once_with(
- "ctx-latest", "result", "", is_error=True, level="silent"
+ "ctx-latest", "result", "", is_error=True, level="silent", output=ANY
)
self.assertEqual(agent._event_handler.release_calls, [])
@@ -911,6 +911,7 @@ class CodexAgentHandleMessageTests(unittest.IsolatedAsyncioTestCase):
"result",
"❌ Failed to interrupt previous Codex turn: interrupt failed",
is_error=True,
+ output=ANY,
)
async def test_handle_message_recovers_from_broken_transport_once(self):
diff --git a/tests/test_codex_event_handler.py b/tests/test_codex_event_handler.py
index f331c64f8..23f97789a 100644
--- a/tests/test_codex_event_handler.py
+++ b/tests/test_codex_event_handler.py
@@ -5,7 +5,7 @@ import tempfile
import unittest
from pathlib import Path
from types import SimpleNamespace
-from unittest.mock import AsyncMock, Mock, patch
+from unittest.mock import ANY, AsyncMock, Mock, patch
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
@@ -185,6 +185,7 @@ class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):
"result",
"❌ Codex turn failed: unexpected status 401 Unauthorized:",
is_error=True,
+ output=ANY,
)
await handler._on_turn_completed(
@@ -230,6 +231,7 @@ class CodexEventHandlerTests(unittest.IsolatedAsyncioTestCase):
"result",
"❌ Codex turn failed: fallback message",
is_error=True,
+ output=ANY,
)
agent._remove_ack_reaction.assert_awaited_once_with(request)
diff --git a/tests/test_message_dispatcher_result_fallback.py b/tests/test_message_dispatcher_result_fallback.py
index 8c51ed647..c666809f4 100644
--- a/tests/test_message_dispatcher_result_fallback.py
+++ b/tests/test_message_dispatcher_result_fallback.py
@@ -301,7 +301,10 @@ class MessageDispatcherResultFallbackTests(unittest.IsolatedAsyncioTestCase):
output=output,
)
- self.assertIsNone(message_id)
+ self.assertEqual(
+ message_id,
+ "agent-output:unknown:runtime-1:terminal-output",
+ )
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(
diff --git a/tests/test_message_dispatcher_scheduled.py b/tests/test_message_dispatcher_scheduled.py
index 6f13f8bbe..a9dc3b983 100644
--- a/tests/test_message_dispatcher_scheduled.py
+++ b/tests/test_message_dispatcher_scheduled.py
@@ -194,6 +194,161 @@ class MessageDispatcherScheduledTests(unittest.IsolatedAsyncioTestCase):
self.assertIsNone(message_id)
self.assertEqual(calls, [("run-empty", "", "succeeded")])
+ async def test_activity_run_settlement_waits_for_successful_delivery(self):
+ controller = _StubController()
+ controller.im_client = _FailingIMClient()
+ 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: None,
+ )
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id="C123",
+ platform="slack",
+ )
+ recorded = []
+
+ class _Store:
+ def get_run(self, run_id):
+ return {"status": "running"}
+
+ def record_run_output(self, run_id, **kwargs):
+ recorded.append((run_id, kwargs))
+
+ 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),
+ patch.object(message_dispatcher_module, "persist_agent_message") as persist,
+ ):
+ with self.assertRaisesRegex(RuntimeError, "not durably persisted"):
+ await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "background work finished",
+ output=MessageOutput(
+ completes_turn=False,
+ completes_run=True,
+ detached=True,
+ idempotency_key="activity-output",
+ run_id="run-origin",
+ requires_delivery_for_run_settlement=True,
+ ),
+ )
+
+ self.assertEqual(recorded, [])
+ persist.assert_not_called()
+
+ async def test_activity_run_store_failure_propagates_after_message_persistence(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: None,
+ )
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id="C123",
+ platform="slack",
+ )
+ events = []
+
+ class _Store:
+ def get_run(self, run_id):
+ return {"status": "running"}
+
+ def record_run_output(self, run_id, **_kwargs):
+ events.append(("run", run_id))
+ raise RuntimeError("run store unavailable")
+
+ def close(self):
+ pass
+
+ def persist(*_args, **_kwargs):
+ events.append(("message", "persisted"))
+ return {"id": "message-row"}
+
+ with (
+ patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=_Store()),
+ patch.object(message_dispatcher_module, "agent_message_exists", return_value=False),
+ patch.object(message_dispatcher_module, "persist_agent_message", side_effect=persist),
+ ):
+ with self.assertRaisesRegex(RuntimeError, "run store unavailable"):
+ await dispatcher.emit_agent_message(
+ context,
+ "result",
+ "background work finished",
+ output=MessageOutput(
+ completes_turn=False,
+ completes_run=True,
+ detached=True,
+ idempotency_key="activity-output",
+ run_id="run-origin",
+ requires_delivery_for_run_settlement=True,
+ ),
+ )
+
+ self.assertEqual(events, [("message", "persisted"), ("run", "run-origin")])
+
+ async def test_activity_run_settlement_follows_message_persistence(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: None,
+ )
+ dispatcher = ConsolidatedMessageDispatcher(controller)
+ context = MessageContext(
+ user_id="scheduled",
+ channel_id="C123",
+ platform="slack",
+ )
+ events = []
+
+ class _Store:
+ def get_run(self, run_id):
+ return {"status": "running"}
+
+ def record_run_output(self, run_id, **kwargs):
+ events.append(("run", run_id, kwargs["terminal_status"]))
+
+ def close(self):
+ pass
+
+ def persist(*_args, **_kwargs):
+ events.append(("message", "persisted"))
+ return {"id": "message-row"}
+
+ with (
+ patch.object(message_dispatcher_module, "SQLiteBackgroundTaskStore", return_value=_Store()),
+ patch.object(message_dispatcher_module, "agent_message_exists", return_value=False),
+ patch.object(message_dispatcher_module, "persist_agent_message", side_effect=persist),
+ ):
+ 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-output",
+ run_id="run-origin",
+ requires_delivery_for_run_settlement=True,
+ ),
+ )
+
+ self.assertEqual(message_id, "bot-msg-1")
+ self.assertEqual(
+ events,
+ [("message", "persisted"), ("run", "run-origin", "succeeded")],
+ )
+
async def test_owned_activity_defers_run_terminal_but_not_later_detached_output(self):
controller = _StubController()
blocking = [True]
diff --git a/tests/test_message_handler_typing.py b/tests/test_message_handler_typing.py
index 4a7785db9..ee0b1a6d1 100644
--- a/tests/test_message_handler_typing.py
+++ b/tests/test_message_handler_typing.py
@@ -192,7 +192,17 @@ class _StubController:
def update_thread_message_id(self, context):
return None
- async def emit_agent_message(self, context, message_type, text, parse_mode="markdown", *, is_error=False, level="normal"):
+ async def emit_agent_message(
+ self,
+ context,
+ message_type,
+ text,
+ parse_mode="markdown",
+ *,
+ is_error=False,
+ level="normal",
+ output=None,
+ ):
# Terminal error results settle the dot + release the SSE waiter via the
# outbound chokepoint; a no-op here (these are IM turns, no workbench dot).
return None
@@ -264,6 +274,39 @@ class _StubSessionHandler:
class MessageHandlerTypingTests(unittest.IsolatedAsyncioTestCase):
+ async def test_pre_request_failure_uses_plain_terminal_output(self):
+ controller = _StubController(
+ platform="slack",
+ ack_mode="reaction",
+ typing_result=True,
+ )
+ controller.emit_agent_message = AsyncMock(return_value=None)
+ handler = MessageHandler(controller)
+ handler.set_session_handler(_StubSessionHandler())
+ handler._prepare_turn_context = AsyncMock(
+ side_effect=RuntimeError("context preparation failed")
+ )
+ context = MessageContext(
+ user_id="U1",
+ channel_id="C1",
+ platform="slack",
+ )
+
+ error = await handler._handle_turn(
+ context,
+ "hello",
+ source=handler.TURN_SOURCE_HUMAN,
+ )
+
+ self.assertEqual(error, "context preparation failed")
+ controller.emit_agent_message.assert_awaited_once()
+ call = controller.emit_agent_message.await_args
+ self.assertEqual(call.args[:3], (context, "result", ""))
+ output = call.kwargs["output"]
+ self.assertTrue(output.completes_turn)
+ self.assertTrue(output.settles_run)
+ self.assertIsNone(output.activity_id)
+
async def test_wechat_forces_typing_even_when_ack_mode_is_message(self):
controller = _StubController(platform="wechat", ack_mode="message", typing_result=True)
handler = MessageHandler(controller)
diff --git a/tests/test_multi_platform_runtime.py b/tests/test_multi_platform_runtime.py
index 07446594b..75feee3c4 100644
--- a/tests/test_multi_platform_runtime.py
+++ b/tests/test_multi_platform_runtime.py
@@ -1233,7 +1233,17 @@ def test_opencode_poll_aborts_disabled_question_toolcall():
def _t(self, key):
return f"translated:{key}"
- async def emit_agent_message(self, context, message_type, text, parse_mode=None, *, is_error=False, level="normal"):
+ async def emit_agent_message(
+ self,
+ context,
+ message_type,
+ text,
+ parse_mode=None,
+ *,
+ is_error=False,
+ level="normal",
+ output=None,
+ ):
emitted.append((message_type, text))
class _Agent:
@@ -1324,7 +1334,17 @@ def test_opencode_poll_emits_error_result_on_retry_exhaustion():
def _t(self, key):
return f"translated:{key}"
- async def emit_agent_message(self, context, message_type, text, parse_mode=None, *, is_error=False, level="normal"):
+ async def emit_agent_message(
+ self,
+ context,
+ message_type,
+ text,
+ parse_mode=None,
+ *,
+ is_error=False,
+ level="normal",
+ output=None,
+ ):
emitted.append((message_type, is_error))
class _Agent:
@@ -1413,7 +1433,17 @@ def test_opencode_poll_emits_notify_and_silent_error_result_on_empty_terminal_me
return "provider:{provider}/{model}/{variant}:{detail}".format(**kwargs)
return f"translated:{key}"
- async def emit_agent_message(self, context, message_type, text, parse_mode=None, *, is_error=False, level="normal"):
+ async def emit_agent_message(
+ self,
+ context,
+ message_type,
+ text,
+ parse_mode=None,
+ *,
+ is_error=False,
+ level="normal",
+ output=None,
+ ):
emitted.append((message_type, text, is_error, level))
class _Agent:
@@ -1532,7 +1562,17 @@ def test_opencode_restored_poll_preserves_model_details_for_empty_terminal_probe
return "provider:{provider}/{model}/{variant}:{detail}".format(**kwargs)
return f"translated:{key}"
- async def emit_agent_message(self, context, message_type, text, parse_mode=None, *, is_error=False, level="normal"):
+ async def emit_agent_message(
+ self,
+ context,
+ message_type,
+ text,
+ parse_mode=None,
+ *,
+ is_error=False,
+ level="normal",
+ output=None,
+ ):
emitted.append((message_type, text, is_error, level))
class _Sessions:
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index ec20fbc9c..b74a169e3 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -5,6 +5,7 @@ import json
import sys
from pathlib import Path
from types import SimpleNamespace
+from unittest.mock import AsyncMock, Mock
import pytest
from sqlalchemy import select
@@ -29,6 +30,7 @@ from modules.im import MessageContext
from storage.db import create_sqlite_engine
from storage.background import SQLiteBackgroundTaskStore
from storage.pagination import PageRequest
+from storage.session_activities import SQLiteSessionActivityStore
class _StubScheduler:
@@ -2339,6 +2341,546 @@ def test_failed_activity_intent_survives_until_last_owned_activity_finishes(
assert "deferred_terminal_status" not in terminal["result_payload"]
+def test_restart_delivers_persisted_activity_summary_and_settles_run_once(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id=session_id,
+ 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
+ activity_store = SQLiteSessionActivityStore(sqlite_store.engine)
+ first_registry = SessionActivityRegistry(activity_store)
+ first_registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id=session_id,
+ activity_id="task-complete",
+ kind="background_task",
+ run_id=request.id,
+ )
+ first_registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-complete",
+ status="completed",
+ metadata={"summary": "Recovered task result"},
+ expects_output=True,
+ )
+ assert request_store.defer_run_terminal(
+ request.id,
+ terminal_status="succeeded",
+ ) is True
+
+ recovered_registry = SessionActivityRegistry(activity_store)
+ emitted: list[tuple[str, bool, bool]] = []
+
+ async def emit_agent_message(context, message_type, text, *, output, **_kwargs):
+ emitted.append((text, output.detached, output.completes_turn))
+ result = sqlite_store.record_run_output(
+ request.id,
+ output_id=str(output.idempotency_key),
+ text=text,
+ terminal_status="succeeded" if output.settles_run else None,
+ provenance=output.provenance(context),
+ )
+ assert result["terminal_transition"] is True
+ return "recovered-message"
+
+ controller = _avibe_controller_double(
+ gate=SimpleNamespace(submit_scheduled=lambda *_args, **_kwargs: None, in_flight={}),
+ handle_scheduled_message=lambda *_args, **_kwargs: None,
+ )
+ controller.agent_service = SimpleNamespace(activities=recovered_registry)
+ controller.emit_agent_message = emit_agent_message
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ running = request_store.get_run(request.id)
+ assert running is not None
+ assert running["status"] == "running"
+ asyncio.run(service._drain_recovered_activity_outputs())
+
+ terminal = request_store.get_run(request.id)
+ assert terminal is not None
+ assert terminal["status"] == "succeeded"
+ assert emitted == [("Recovered task result", True, False)]
+ assert activity_store.list_activities() == []
+
+ asyncio.run(service._drain_recovered_activity_outputs())
+ assert emitted == [("Recovered task result", True, False)]
+
+
+def test_recovered_terminal_waits_for_pending_activity_output(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ session_id = _make_avibe_session(monkeypatch, tmp_path)
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id=session_id,
+ 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
+ activity_store = SQLiteSessionActivityStore(sqlite_store.engine)
+ first_registry = SessionActivityRegistry(activity_store)
+ for activity_id in ("task-failed", "task-output"):
+ first_registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id=session_id,
+ activity_id=activity_id,
+ kind="background_task",
+ run_id=request.id,
+ )
+ failed = first_registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-failed",
+ status="failed",
+ retain_terminal_snapshot=True,
+ )
+ assert failed is not None
+ output = first_registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-output",
+ status="completed",
+ metadata={"summary": "Recovered output before failure callback"},
+ expects_output=True,
+ )
+ assert output is not None
+ assert request_store.defer_run_terminal(
+ request.id,
+ terminal_status="succeeded",
+ ) is True
+
+ recovered_registry = SessionActivityRegistry(activity_store)
+ statuses_during_delivery: list[str] = []
+
+ async def emit_agent_message(context, _message_type, text, *, output, **_kwargs):
+ current = request_store.get_run(request.id)
+ assert current is not None
+ statuses_during_delivery.append(current["status"])
+ result = sqlite_store.record_run_output(
+ request.id,
+ output_id=str(output.idempotency_key),
+ text=text,
+ terminal_status="succeeded" if output.settles_run else None,
+ provenance=output.provenance(context),
+ )
+ assert result["terminal_transition"] is True
+ return "recovered-message"
+
+ controller = _avibe_controller_double(
+ gate=SimpleNamespace(submit_scheduled=lambda *_args, **_kwargs: None, in_flight={}),
+ handle_scheduled_message=lambda *_args, **_kwargs: None,
+ )
+ controller.agent_service = SimpleNamespace(activities=recovered_registry)
+ controller.emit_agent_message = emit_agent_message
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ before_output = request_store.get_run(request.id)
+ assert before_output is not None
+ assert before_output["status"] == "running"
+ assert before_output["result_payload"]["deferred_terminal_status"] == "failed"
+ assert len(activity_store.list_activities()) == 2
+
+ asyncio.run(service._drain_recovered_activity_outputs())
+
+ terminal = request_store.get_run(request.id)
+ assert terminal is not None
+ assert statuses_during_delivery == ["running"]
+ assert terminal["status"] == "failed"
+ assert terminal["result_text"] == "Recovered output before failure callback"
+ assert activity_store.list_activities() == []
+
+
+def test_recovered_terminal_settlement_failure_does_not_abort_startup(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from storage.importer import ensure_sqlite_state
+
+ ensure_sqlite_state()
+ 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
+ activity_store = SQLiteSessionActivityStore(sqlite_store.engine)
+ first_registry = SessionActivityRegistry(activity_store)
+ first_registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="target-session",
+ activity_id="task-failed",
+ kind="background_task",
+ run_id=request.id,
+ )
+ failed = first_registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-failed",
+ status="failed",
+ retain_terminal_snapshot=True,
+ )
+ assert failed is not None
+
+ recovered_registry = SessionActivityRegistry(activity_store)
+ original_defer = request_store.defer_run_terminal
+ attempts = 0
+
+ def transient_defer_failure(*args, **kwargs):
+ nonlocal attempts
+ attempts += 1
+ if attempts == 1:
+ raise RuntimeError("database is locked")
+ return original_defer(*args, **kwargs)
+
+ request_store.defer_run_terminal = transient_defer_failure
+ controller = SimpleNamespace(
+ agent_service=SimpleNamespace(activities=recovered_registry),
+ )
+
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ assert attempts == 1
+ assert len(service._pending_recovered_activity_terminals) == 1
+ assert len(activity_store.list_activities()) == 1
+
+ asyncio.run(service._drain_recovered_activity_outputs())
+
+ terminal = request_store.get_run(request.id)
+ assert terminal is not None
+ assert attempts == 2
+ assert terminal["status"] == "failed"
+ assert terminal["error"] == "Background Activity task-failed failed"
+ assert service._pending_recovered_activity_terminals == []
+ assert activity_store.list_activities() == []
+
+
+def test_restart_preserves_activity_delivery_override(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from storage.importer import ensure_sqlite_state
+ from storage.sessions_service import SQLiteSessionsService
+
+ ensure_sqlite_state()
+ session_target = parse_session_key(
+ "slack::channel::C-SOURCE::thread::171717.123"
+ )
+ sessions = SQLiteSessionsService(paths.get_sqlite_state_path())
+ try:
+ session_id = sessions.reserve_agent_session(
+ scope_key=session_target.session_scope,
+ agent_backend="claude",
+ session_anchor=session_anchor_for_target(session_target),
+ )
+ finally:
+ sessions.close()
+ assert session_id is not None
+
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id=session_id,
+ session_key=session_target.to_key(),
+ 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
+ activity_store = SQLiteSessionActivityStore(sqlite_store.engine)
+ first_registry = SessionActivityRegistry(activity_store)
+ first_registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id=session_id,
+ activity_id="task-routed",
+ kind="background_task",
+ run_id=request.id,
+ metadata={"delivery_key_external": "slack::channel::C-DESTINATION"},
+ )
+ first_registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-routed",
+ status="completed",
+ metadata={"summary": "Recovered routed result"},
+ expects_output=True,
+ )
+ assert request_store.defer_run_terminal(
+ request.id,
+ terminal_status="succeeded",
+ ) is True
+
+ recovered_registry = SessionActivityRegistry(activity_store)
+ emitted_contexts: list[MessageContext] = []
+
+ async def emit_agent_message(context, _message_type, text, *, output, **_kwargs):
+ emitted_contexts.append(context)
+ result = sqlite_store.record_run_output(
+ request.id,
+ output_id=str(output.idempotency_key),
+ text=text,
+ terminal_status="succeeded" if output.settles_run else None,
+ provenance=output.provenance(context),
+ )
+ assert result["terminal_transition"] is True
+ return "recovered-routed-message"
+
+ settings_manager = SimpleNamespace(
+ get_store=lambda: SimpleNamespace(get_user=lambda *_args, **_kwargs: None)
+ )
+ controller = SimpleNamespace(
+ platform_settings_managers={"slack": settings_manager},
+ im_clients={},
+ get_im_client_for_context=lambda _context: SimpleNamespace(
+ should_use_thread_for_reply=lambda: True,
+ should_use_thread_for_dm_session=lambda: False,
+ ),
+ agent_service=SimpleNamespace(activities=recovered_registry),
+ emit_agent_message=emit_agent_message,
+ )
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ asyncio.run(service._drain_recovered_activity_outputs())
+
+ assert len(emitted_contexts) == 1
+ context = emitted_contexts[0]
+ assert context.thread_id == "171717.123"
+ assert context.platform_specific["delivery_key_external"] == (
+ "slack::channel::C-DESTINATION"
+ )
+ assert context.platform_specific["delivery_override"]["channel_id"] == (
+ "C-DESTINATION"
+ )
+ assert context.platform_specific["delivery_override"]["thread_id"] is None
+ assert request_store.get_run(request.id)["status"] == "succeeded"
+ assert activity_store.list_activities() == []
+
+
+def test_recovered_silent_directive_activity_settles_without_emit() -> None:
+ activity = SimpleNamespace(
+ id="task-silent",
+ session_id="session-1",
+ metadata={"summary": "<silent>internal completion</silent>"},
+ )
+ registry = SimpleNamespace(ack_completed_output=Mock())
+ service = ScheduledTaskService.__new__(ScheduledTaskService)
+ service.controller = SimpleNamespace(
+ agent_service=SimpleNamespace(activities=registry),
+ emit_agent_message=AsyncMock(),
+ )
+ service._settle_activity_without_output = Mock()
+
+ asyncio.run(service._deliver_recovered_activity_output(activity))
+
+ service._settle_activity_without_output.assert_called_once_with(activity)
+ registry.ack_completed_output.assert_called_once_with(activity)
+ service.controller.emit_agent_message.assert_not_awaited()
+
+
+def test_restart_no_delivery_activity_settles_real_run_without_emit(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ session_id = _make_avibe_session(
+ monkeypatch,
+ tmp_path,
+ metadata={"no_delivery": True},
+ )
+ request_store = TaskExecutionStore()
+ request = request_store.enqueue_agent_run(
+ session_id=session_id,
+ 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
+ activity_store = SQLiteSessionActivityStore(sqlite_store.engine)
+ first_registry = SessionActivityRegistry(activity_store)
+ first_registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id=session_id,
+ activity_id="task-private",
+ kind="background_task",
+ run_id=request.id,
+ )
+ first_registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-private",
+ status="completed",
+ metadata={"summary": "Private task result"},
+ expects_output=True,
+ )
+ assert request_store.defer_run_terminal(
+ request.id,
+ terminal_status="succeeded",
+ ) is True
+
+ recovered_registry = SessionActivityRegistry(activity_store)
+ controller = _avibe_controller_double(
+ gate=SimpleNamespace(submit_scheduled=lambda *_args, **_kwargs: None, in_flight={}),
+ handle_scheduled_message=lambda *_args, **_kwargs: None,
+ )
+ controller.agent_service = SimpleNamespace(activities=recovered_registry)
+ controller.emit_agent_message = AsyncMock()
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ asyncio.run(service._drain_recovered_activity_outputs())
+
+ terminal = request_store.get_run(request.id)
+ assert terminal is not None
+ assert terminal["status"] == "succeeded"
+ assert terminal["result_text"] in {None, ""}
+ assert not terminal["result_payload"].get("outputs")
+ controller.emit_agent_message.assert_not_awaited()
+ assert activity_store.list_activities() == []
+
+
+def test_restart_settles_terminal_activity_without_inventing_visible_text(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from storage.importer import ensure_sqlite_state
+
+ ensure_sqlite_state()
+ 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
+ activity_store = SQLiteSessionActivityStore(sqlite_store.engine)
+ first_registry = SessionActivityRegistry(activity_store)
+ first_registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="target-session",
+ activity_id="task-silent",
+ kind="background_task",
+ run_id=request.id,
+ )
+ first_registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-silent",
+ status="completed",
+ expects_output=True,
+ )
+ assert request_store.defer_run_terminal(
+ request.id,
+ terminal_status="succeeded",
+ ) is True
+
+ recovered_registry = SessionActivityRegistry(activity_store)
+ controller = SimpleNamespace(
+ agent_service=SimpleNamespace(activities=recovered_registry),
+ )
+ service = ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ asyncio.run(service._drain_recovered_activity_outputs())
+
+ terminal = request_store.get_run(request.id)
+ assert terminal is not None
+ assert terminal["status"] == "succeeded"
+ assert terminal["result_text"] in {None, ""}
+ assert activity_store.list_activities() == []
+
+
+def test_restart_marks_live_activity_disconnected_and_cancels_owned_run(
+ tmp_path: Path,
+ monkeypatch,
+) -> None:
+ monkeypatch.setenv("AVIBE_HOME", str(tmp_path))
+ from storage.importer import ensure_sqlite_state
+
+ ensure_sqlite_state()
+ 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
+ activity_store = SQLiteSessionActivityStore(sqlite_store.engine)
+ first_registry = SessionActivityRegistry(activity_store)
+ first_registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="target-session",
+ activity_id="task-live",
+ kind="background_task",
+ run_id=request.id,
+ )
+
+ recovered_registry = SessionActivityRegistry(activity_store)
+ controller = SimpleNamespace(
+ agent_service=SimpleNamespace(activities=recovered_registry),
+ )
+ ScheduledTaskService(
+ controller=controller,
+ store=ScheduledTaskStore(tmp_path / "scheduled_tasks.json"),
+ request_store=request_store,
+ )
+
+ terminal = request_store.get_run(request.id)
+ assert terminal is not None
+ assert terminal["status"] == "canceled"
+ assert terminal["error"] == "Background Activity task-live disconnected"
+ assert activity_store.list_activities() == []
+
+
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)
@@ -3478,7 +4020,12 @@ def _avibe_controller_double(*, gate, handle_scheduled_message):
)
-def _make_avibe_session(monkeypatch, tmp_path) -> str:
+def _make_avibe_session(
+ monkeypatch,
+ tmp_path,
+ *,
+ metadata: dict | None = None,
+) -> str:
"""Create a real avibe workbench session so ``resolve_session_id_target``
resolves it to ``platform='avibe'`` (the gate trigger)."""
from core.services import sessions as sessions_service
@@ -3513,7 +4060,11 @@ def _make_avibe_session(monkeypatch, tmp_path) -> str:
)
)
session = sessions_service.create_session(
- conn, scope_id=scope_id, agent_backend="claude", agent_name="worker"
+ conn,
+ scope_id=scope_id,
+ agent_backend="claude",
+ agent_name="worker",
+ metadata=metadata,
)
return session["id"]
diff --git a/tests/test_session_activities.py b/tests/test_session_activities.py
index 5b418b4b4..8dc90bdbd 100644
--- a/tests/test_session_activities.py
+++ b/tests/test_session_activities.py
@@ -1,11 +1,21 @@
from __future__ import annotations
from contextlib import nullcontext
+from pathlib import Path
from types import SimpleNamespace
from unittest import mock
-from core.session_activities import SessionActivityRegistry
+import pytest
+
+from core.session_activities import (
+ SessionActivity,
+ SessionActivityRegistry,
+ activity_completion_output,
+)
from core.session_turns import SessionTurnManager
+from storage.db import create_sqlite_engine
+from storage.importer import ensure_sqlite_state
+from storage.session_activities import SQLiteSessionActivityStore
def test_activity_lifecycle_keeps_state_axes_orthogonal():
@@ -40,6 +50,7 @@ def test_activity_lifecycle_keeps_state_axes_orthogonal():
assert completed is not None
assert registry.session_state("ses-1") == {
"background_activities": [],
+ "pending_activity_output_count": 1,
"connection": "connected",
}
@@ -47,6 +58,111 @@ def test_activity_lifecycle_keeps_state_axes_orthogonal():
assert claimed is not None
assert claimed.id == "task-1"
assert registry.claim_completed_output("claude", "runtime-1") is None
+ registry.ack_completed_output(claimed)
+ assert registry.has_completed_output("claude", "runtime-1") is False
+
+
+def test_activity_output_native_id_is_stable_across_recovery_contexts():
+ activity = SessionActivity(
+ id="task-1",
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ kind="background_task",
+ status="completed",
+ )
+ output = activity_completion_output(
+ activity,
+ detached=True,
+ completes_turn=False,
+ )
+ live_context = SimpleNamespace(
+ platform_specific={
+ "vibe_agent_backend": "claude",
+ "agent_session_id": "ses-1",
+ }
+ )
+ recovered_context = SimpleNamespace(
+ platform_specific={
+ "vibe_agent_backend": "codex",
+ "task_execution_id": "activity:claude:task-1",
+ "agent_session_id": "ses-1",
+ }
+ )
+
+ live_id = output.native_message_id(live_context)
+ recovered_id = output.native_message_id(recovered_context)
+
+ assert live_id == recovered_id
+ assert live_id is not None
+ assert live_id.startswith("agent-output:claude:activity:task-1:")
+ assert output.requires_delivery_for_run_settlement is True
+
+
+def test_activity_completion_persistence_failure_keeps_output_unclaimable():
+ def upsert_activity(_activity, *, phase):
+ if phase == "awaiting_output":
+ raise RuntimeError("database is locked")
+
+ store = SimpleNamespace(
+ upsert_activity=upsert_activity,
+ delete_activity=mock.Mock(),
+ )
+ registry = SessionActivityRegistry(store)
+ registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ activity_id="task-1",
+ kind="background_task",
+ )
+
+ with pytest.raises(RuntimeError, match="database is locked"):
+ registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-1",
+ status="completed",
+ expects_output=True,
+ )
+
+ assert [item.id for item in registry.active_for_runtime("claude", "runtime-1")] == [
+ "task-1"
+ ]
+ assert registry.has_completed_output("claude", "runtime-1") is False
+
+
+def test_activity_ack_keeps_claim_until_snapshot_delete_succeeds():
+ delete_activity = mock.Mock(side_effect=RuntimeError("database is locked"))
+ store = SimpleNamespace(
+ upsert_activity=mock.Mock(),
+ delete_activity=delete_activity,
+ )
+ registry = SessionActivityRegistry(store)
+ 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",
+ expects_output=True,
+ )
+ claimed = registry.claim_completed_output("claude", "runtime-1")
+ assert claimed is not None
+
+ with pytest.raises(RuntimeError, match="database is locked"):
+ registry.ack_completed_output(claimed)
+
+ assert registry.has_completed_output("claude", "runtime-1") is True
+ delete_activity.side_effect = None
+ assert registry.ack_completed_output(claimed) is True
+ assert registry.has_completed_output("claude", "runtime-1") is False
def test_activity_updates_are_independent_and_runtime_disconnect_terminates_all():
@@ -148,6 +264,116 @@ def test_turn_state_composes_foreground_inbox_activity_and_connection_axes():
assert [item["id"] for item in state["background_activities"]] == ["task-1"]
+def test_activity_restart_recovers_connection_and_interrupts_live_work(tmp_path: Path):
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ ensure_sqlite_state(db_path=db_path, primary_platform="avibe")
+ engine = create_sqlite_engine(db_path)
+ store = SQLiteSessionActivityStore(engine)
+ first = SessionActivityRegistry(store)
+ first.set_connection(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ state="connected",
+ )
+ first.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ activity_id="task-live",
+ kind="background_task",
+ run_id="run-1",
+ )
+
+ recovered = SessionActivityRegistry(store)
+
+ assert recovered.active_for_runtime("claude", "runtime-1") == []
+ assert recovered.session_state("ses-1")["connection"] == "disconnected"
+ terminals = recovered.drain_recovered_terminals()
+ assert [(item.id, item.status, item.run_id) for item in terminals] == [
+ ("task-live", "disconnected", "run-1"),
+ ]
+ assert len(store.list_activities()) == 1
+
+ restarted_again = SessionActivityRegistry(store)
+ repeated = restarted_again.drain_recovered_terminals()
+ assert [(item.id, item.status, item.run_id) for item in repeated] == [
+ ("task-live", "disconnected", "run-1"),
+ ]
+ restarted_again.ack_recovered_terminal(repeated[0])
+ assert store.list_activities() == []
+ engine.dispose()
+
+
+def test_completed_activity_output_is_durable_until_ack(tmp_path: Path):
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ ensure_sqlite_state(db_path=db_path, primary_platform="avibe")
+ engine = create_sqlite_engine(db_path)
+ store = SQLiteSessionActivityStore(engine)
+ first = SessionActivityRegistry(store)
+ first.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ activity_id="task-complete",
+ kind="background_task",
+ run_id="run-1",
+ )
+ first.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-complete",
+ status="completed",
+ metadata={"summary": "Recovered summary"},
+ expects_output=True,
+ )
+
+ recovered = SessionActivityRegistry(store)
+ claimed = recovered.claim_completed_output(
+ "claude",
+ "runtime-1",
+ recovered_only=True,
+ )
+
+ assert claimed is not None
+ assert claimed.metadata["summary"] == "Recovered summary"
+ assert recovered.has_pending_run_output("run-1") is True
+ assert len(store.list_activities()) == 1
+
+ recovered.ack_completed_output(claimed)
+ assert recovered.has_pending_run_output("run-1") is False
+ assert store.list_activities() == []
+ engine.dispose()
+
+
+def test_activity_restart_persists_inferred_disconnected_connection(tmp_path: Path):
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ ensure_sqlite_state(db_path=db_path, primary_platform="avibe")
+ engine = create_sqlite_engine(db_path)
+ store = SQLiteSessionActivityStore(engine)
+ first = SessionActivityRegistry(store)
+ first.start(
+ backend="claude",
+ runtime_key="runtime-without-connection",
+ session_id="ses-1",
+ activity_id="task-live",
+ kind="background_task",
+ )
+
+ SessionActivityRegistry(store)
+
+ assert store.list_connections() == [
+ {
+ "version": 1,
+ "backend": "claude",
+ "runtime_key": "runtime-without-connection",
+ "session_id": "ses-1",
+ "state": "disconnected",
+ }
+ ]
+ engine.dispose()
+
+
def test_only_owned_non_detached_activities_block_run_completion():
registry = SessionActivityRegistry()
registry.start(
@@ -213,3 +439,98 @@ def test_force_end_backend_settles_active_and_discards_pending_output():
]
assert registry.has_backend_work("claude") is False
assert registry.claim_completed_output("claude", "runtime-2") is None
+
+
+def test_force_end_backend_retains_terminal_snapshot_until_ack(tmp_path: Path):
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ ensure_sqlite_state(db_path=db_path, primary_platform="avibe")
+ engine = create_sqlite_engine(db_path)
+ store = SQLiteSessionActivityStore(engine)
+ registry = SessionActivityRegistry(store)
+ registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ activity_id="task-active",
+ kind="background_task",
+ )
+ registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ activity_id="task-complete",
+ kind="background_task",
+ )
+ registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-complete",
+ status="completed",
+ metadata={"summary": "Do not deliver after forced restart"},
+ expects_output=True,
+ )
+ assert len(store.list_activities()) == 2
+
+ completed = registry.end_backend("claude", status="killed")
+
+ assert sorted((item.id, item.status) for item in completed) == [
+ ("task-active", "killed"),
+ ("task-complete", "killed"),
+ ]
+ records = store.list_activities()
+ assert len(records) == 2
+ assert {record["phase"] for record in records} == {"terminal"}
+ assert {record["activity"]["status"] for record in records} == {"killed"}
+ recovered = SessionActivityRegistry(store)
+ assert recovered.recovered_output_runtimes() == []
+ assert recovered.claim_completed_output("claude", "runtime-1") is None
+ terminals = recovered.drain_recovered_terminals()
+ assert sorted((item.id, item.status) for item in terminals) == [
+ ("task-active", "killed"),
+ ("task-complete", "killed"),
+ ]
+ for activity in terminals:
+ recovered.ack_recovered_terminal(activity)
+ assert store.list_activities() == []
+ engine.dispose()
+
+
+def test_force_end_backend_claimed_output_wins_late_delivery_race(tmp_path: Path):
+ db_path = tmp_path / "state" / "vibe.sqlite"
+ ensure_sqlite_state(db_path=db_path, primary_platform="avibe")
+ engine = create_sqlite_engine(db_path)
+ store = SQLiteSessionActivityStore(engine)
+ registry = SessionActivityRegistry(store)
+ registry.start(
+ backend="claude",
+ runtime_key="runtime-1",
+ session_id="ses-1",
+ activity_id="task-claimed",
+ kind="background_task",
+ run_id="run-1",
+ )
+ registry.complete(
+ backend="claude",
+ runtime_key="runtime-1",
+ activity_id="task-claimed",
+ status="completed",
+ metadata={"summary": "Delivery is in flight"},
+ expects_output=True,
+ )
+ claimed = registry.claim_completed_output("claude", "runtime-1")
+ assert claimed is not None
+ assert registry.has_backend_work("claude") is True
+
+ completed = registry.end_backend("claude", status="killed")
+
+ assert [(item.id, item.status) for item in completed] == [
+ ("task-claimed", "killed"),
+ ]
+ assert registry.has_backend_work("claude") is False
+ assert registry.requeue_completed_output(claimed) is False
+ assert registry.ack_completed_output(claimed) is False
+ records = store.list_activities()
+ assert len(records) == 1
+ assert records[0]["phase"] == "terminal"
+ assert records[0]["activity"]["status"] == "killed"
+ engine.dispose()
diff --git a/tests/test_ui_session_stream.py b/tests/test_ui_session_stream.py
index a364d264c..68ed63278 100644
--- a/tests/test_ui_session_stream.py
+++ b/tests/test_ui_session_stream.py
@@ -497,7 +497,25 @@ def test_chat_bootstrap_returns_first_screen_payload(isolated_state, tmp_path):
async def in_flight(session_id_inner):
assert session_id_inner == session_id
- return {"status_code": 200, "body": {"in_flight": True}}
+ return {
+ "status_code": 200,
+ "body": {
+ "in_flight": True,
+ "foreground": "running",
+ "pending_input_count": 1,
+ "background_activities": [
+ {
+ "id": "task-1",
+ "backend": "claude",
+ "runtime_key": "runtime-1",
+ "kind": "background_task",
+ "status": "running",
+ }
+ ],
+ "pending_activity_output_count": 0,
+ "connection": "connected",
+ },
+ }
with (
patch("vibe.internal_client.turn_state", in_flight),
@@ -523,6 +541,10 @@ def test_chat_bootstrap_returns_first_screen_payload(isolated_state, tmp_path):
assert body["queued"][0]["text"] == "follow-up"
assert body["draft"]["text"] == "draft text"
assert body["turn_state"]["in_flight"] is True
+ assert body["turn_state"]["foreground"] == "running"
+ assert body["turn_state"]["pending_input_count"] == 1
+ assert body["turn_state"]["background_activities"][0]["id"] == "task-1"
+ assert body["turn_state"]["connection"] == "connected"
def test_chat_bootstrap_keeps_timeout_turn_state_unknown(isolated_state, tmp_path):
@@ -695,6 +717,48 @@ def test_turn_state_idle_recovers_stale_running_status(isolated_state, tmp_path)
assert sessions_service.get_session(conn, session_id)["agent_status"] == "idle"
+def test_turn_state_route_preserves_orthogonal_runtime_axes(isolated_state, tmp_path):
+ from vibe.ui_server import app
+
+ _, session_id = _make_session(tmp_path)
+
+ async def projected(session_id_inner):
+ assert session_id_inner == session_id
+ return {
+ "status_code": 200,
+ "body": {
+ "in_flight": False,
+ "foreground": "idle",
+ "native_turn_started": False,
+ "pending_input_count": 2,
+ "background_activities": [
+ {
+ "id": "task-1",
+ "backend": "claude",
+ "runtime_key": "runtime-1",
+ "kind": "background_task",
+ "status": "running",
+ }
+ ],
+ "pending_activity_output_count": 1,
+ "connection": "reconnecting",
+ },
+ }
+
+ with patch("vibe.internal_client.turn_state", projected):
+ client = app.test_client()
+ response = client.get(f"/api/sessions/{session_id}/turn-state")
+
+ assert response.status_code == 200
+ body = response.get_json()
+ assert body["foreground"] == "idle"
+ assert body["in_flight"] is False
+ assert body["pending_input_count"] == 2
+ assert body["pending_activity_output_count"] == 1
+ assert [item["id"] for item in body["background_activities"]] == ["task-1"]
+ assert body["connection"] == "reconnecting"
+
+
def test_turn_state_idle_does_not_recover_failed_status(isolated_state, tmp_path):
from core.services import sessions as sessions_service
from storage.db import create_sqlite_engine
diff --git a/ui/src/components/workbench/ChatPage.tsx b/ui/src/components/workbench/ChatPage.tsx
index 796513195..acc070169 100644
--- a/ui/src/components/workbench/ChatPage.tsx
+++ b/ui/src/components/workbench/ChatPage.tsx
@@ -1,14 +1,14 @@
import { memo, useCallback, useEffect, useMemo, useRef, useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Link, useLocation, useNavigate, useParams, useSearchParams } from 'react-router-dom';
-import { ArrowLeft, Bell, Bot, ChevronDown, Clock, GitFork, Info, Loader2, MessageSquare, Pencil, Presentation, Undo2, UploadCloud, X } from 'lucide-react';
+import { Activity, ArrowLeft, Bell, Bot, ChevronDown, Clock, GitFork, Info, Loader2, MessageSquare, Pencil, Presentation, Undo2, UploadCloud, X } from 'lucide-react';
import clsx from 'clsx';
import { useApi } from '../../context/ApiContext';
import { useToast } from '../../context/ToastContext';
import { useWorkbenchInbox } from '../../context/WorkbenchInboxContext';
import { useRegisterComposerTarget, type ComposerInsertTarget } from '../../context/ComposerBridgeContext';
-import type { VaultRequest, VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
+import type { SessionRuntimeState, VaultRequest, VibeAgentBrief, WorkbenchMessage, WorkbenchSession } from '../../context/ApiContext';
import { apiFetch } from '../../lib/apiFetch';
import { normalizeChatMessageFontSize } from '../../lib/chatDisplay';
import { useIosKeyboardInset } from '../../lib/useIosKeyboardInset';
@@ -51,6 +51,17 @@ const WORKING_RECONCILE_INTERVAL_MS = 60 * 1000;
// idle check clear Stop. A genuinely stale turn (missed ``turn.end``) was set
// working far longer ago than this, so it still clears (Codex P2).
const WORKING_SETTLE_GRACE_MS = 4000;
+const ACTIVITY_RECONCILE_INTERVAL_MS = 10 * 1000;
+
+const emptyRuntimeState = (): SessionRuntimeState => ({
+ in_flight: false,
+ foreground: 'idle',
+ native_turn_started: false,
+ pending_input_count: 0,
+ background_activities: [],
+ pending_activity_output_count: 0,
+ connection: 'unknown',
+});
// The transcript-visible message types — mirrors the server filter on
// ``GET /api/sessions/{id}/messages`` so the live ``message.new`` feed appends
@@ -263,6 +274,7 @@ export const ChatPage: React.FC = () => {
// ``working`` = a turn is in flight for this session (from our send, or any
// other origin we observe). Drives the thinking bubble + the Send→Stop swap.
const [working, setWorking] = useState(false);
+ const [runtimeState, setRuntimeState] = useState<SessionRuntimeState>(emptyRuntimeState);
// Bumped on resume (tab visible again / network back) to force the transcript
// subscription effect to reopen a possibly-dead SSE stream — see the
// visibility effect below.
@@ -541,8 +553,9 @@ export const ChatPage: React.FC = () => {
try {
const res = await api.getTurnState(sessionId);
if (sessionId !== sessionIdRef.current) return;
- if (res.in_flight === null) return;
- if (res.in_flight) {
+ if (res.foreground === 'unknown') return;
+ setRuntimeState(res);
+ if (res.foreground === 'running') {
// markWorking (not setWorking): bump the epoch + timestamp so an OLDER
// overlapping sync whose idle response lands AFTER this one can't clear
// the Stop we just confirmed live — its captured epoch is now stale (P2).
@@ -602,12 +615,13 @@ export const ChatPage: React.FC = () => {
setHistoricalWindow(false);
setQueue(bootstrap.queued ?? []);
setInitialDraft(bootstrap.draft?.text ?? '');
+ setRuntimeState(bootstrap.turn_state);
// Restore Stop for a turn that is still running (e.g. opened in another tab
// or reloaded mid-turn). markWorking on the live branch so a racing
// syncTurnState idle response can't clear it; an idle load is authoritative
// for the fresh page, so clear directly (Codex P2).
- if (bootstrap.turn_state.in_flight) markWorking();
- else if (bootstrap.turn_state.in_flight === false) setWorking(false);
+ if (bootstrap.turn_state.foreground === 'running') markWorking();
+ else if (bootstrap.turn_state.foreground === 'idle') setWorking(false);
} catch (err: any) {
// Only surface the error if we're still on the session that failed — a
// stale failure must not stamp an error onto the chat the user moved to.
@@ -650,6 +664,7 @@ export const ChatPage: React.FC = () => {
highlightTimerRef.current = null;
}
setWorking(false);
+ setRuntimeState(emptyRuntimeState());
setQueue([]);
setInitialDraft(null);
// Drop any pending grace-resync so it can't fire against the new session.
@@ -696,19 +711,24 @@ export const ChatPage: React.FC = () => {
onTurnStart: (data) => {
// markWorking (not setWorking): bump the epoch so a syncTurnState idle
// reading already in flight can't clear this freshly-started turn.
- if (data.session_id === sessionIdRef.current) markWorking();
+ if (data.session_id === sessionIdRef.current) {
+ setRuntimeState((current) => ({ ...current, in_flight: true, foreground: 'running' }));
+ markWorking();
+ }
},
onTurnEnd: (data) => {
// The controller confirms the turn settled (terminal result, agent error,
// or user cancel) — the authoritative end of the working state. There is
// no turn-duration timeout, so this only fires on a REAL terminal signal.
if (data.session_id === sessionIdRef.current) {
+ setRuntimeState((current) => ({ ...current, in_flight: false, foreground: 'idle' }));
setWorking(false);
// The first turn binds the native; pick it up so the header's backend
// lock engages without a reload. A failed first turn leaves no native
// (the refresh confirms that), keeping the backend switchable so the
// user can recover by re-routing.
void refreshSessionRowUntilNativeBound();
+ void syncTurnState();
}
},
onQueueUpdated: (data) => {
@@ -784,7 +804,11 @@ export const ChatPage: React.FC = () => {
};
}, [sessionId, reconcile, refreshQueue, syncTurnState]);
- // Reconcile (don't kill) while a turn is in flight: there is no turn-duration
+ useEffect(() => {
+ setRuntimeState((current) => ({ ...current, pending_input_count: queue.length }));
+ }, [queue.length]);
+
+ // Reconcile (don't kill) while foreground or background work is present: there is no turn-duration
// timeout, so a long agent can run for hours and must keep Stop + the indicator
// the whole time. Instead of a force-clear timer, poll the controller's
// authoritative ``GET /turn-state`` on an interval while ``working`` is true AND
@@ -794,13 +818,17 @@ export const ChatPage: React.FC = () => {
// flips false / on unmount; skipped while hidden (visibilitychange already
// reconciles on resume).
useEffect(() => {
- if (!working) return;
+ const hasBackgroundState =
+ runtimeState.background_activities.length > 0 ||
+ runtimeState.pending_activity_output_count > 0 ||
+ runtimeState.connection === 'reconnecting';
+ if (!working && !hasBackgroundState) return;
const interval = window.setInterval(() => {
if (document.visibilityState !== 'visible') return;
void syncTurnState();
- }, WORKING_RECONCILE_INTERVAL_MS);
+ }, hasBackgroundState ? ACTIVITY_RECONCILE_INTERVAL_MS : WORKING_RECONCILE_INTERVAL_MS);
return () => window.clearInterval(interval);
- }, [working, syncTurnState]);
+ }, [working, runtimeState.background_activities.length, runtimeState.pending_activity_output_count, runtimeState.connection, syncTurnState]);
const sendMessage = useCallback(
async (
@@ -1480,6 +1508,7 @@ export const ChatPage: React.FC = () => {
) : null
}
/>
+ <ActivityStrip state={runtimeState} />
<QueueStrip queue={queue} onRemove={removeQueued} onRecall={recallQueued} onSendNow={sendQueueNow} />
{sessionId && pendingApprovals.length > 0 ? (
<VaultApprovalFloat offscreen={offscreenApprovals} pending={pendingApprovals} onResolved={refreshVaultRequests} />
@@ -1580,6 +1609,36 @@ const QueueRow: React.FC<{
);
};
+const ActivityStrip: React.FC<{ state: SessionRuntimeState }> = ({ state }) => {
+ const { t } = useTranslation();
+ const active = state.background_activities;
+ const pendingOutputs = state.pending_activity_output_count;
+ if (active.length === 0 && pendingOutputs === 0) return null;
+
+ const firstDescription = active.find((item) => item.description)?.description;
+ const connectionVisible =
+ active.length > 0 &&
+ (state.connection === 'reconnecting' || state.connection === 'disconnected');
+ return (
+ <div className="shrink-0 border-t border-border/70 bg-surface-2/60 px-4 py-1.5 md:px-8">
+ <div className="mx-auto flex min-h-7 w-full max-w-[1080px] items-center gap-2 text-[11px] text-muted">
+ <Activity className="size-3.5 shrink-0 text-mint" aria-hidden="true" />
+ <span className="min-w-0 truncate" title={firstDescription ?? undefined}>
+ {active.length > 0
+ ? t('chat.activities.running', { count: active.length })
+ : t('chat.activities.delivering', { count: pendingOutputs })}
+ {firstDescription ? ` · ${firstDescription}` : ''}
+ </span>
+ {connectionVisible ? (
+ <span className="ml-auto shrink-0 text-gold">
+ {t(`chat.activities.connection.${state.connection}`)}
+ </span>
+ ) : null}
+ </div>
+ </div>
+ );
+};
+
const QueueStrip: React.FC<{
queue: WorkbenchMessage[];
onRemove: (id: string) => void;
diff --git a/ui/src/context/ApiContext.tsx b/ui/src/context/ApiContext.tsx
index ddb1ef6e5..4b41cb61e 100644
--- a/ui/src/context/ApiContext.tsx
+++ b/ui/src/context/ApiContext.tsx
@@ -530,7 +530,7 @@ export type ApiContextType = {
listSessionQueue: (sessionId: string, options?: { cache?: boolean }) => Promise<{ queued: WorkbenchMessage[] }>;
removeQueuedMessage: (sessionId: string, messageId: string) => Promise<{ removed: boolean }>;
sendQueuedNow: (sessionId: string, messageId: string) => Promise<{ ok: boolean; status?: string; code?: string; detail?: string }>;
- getTurnState: (sessionId: string) => Promise<{ in_flight: boolean | null }>;
+ getTurnState: (sessionId: string) => Promise<SessionRuntimeState>;
getSessionDraft: (sessionId: string) => Promise<{ text: string }>;
setSessionDraft: (sessionId: string, text: string) => Promise<{ ok: boolean }>;
listInbox: (params?: { platform?: string; unreadOnly?: boolean; limit?: number; before?: string; cache?: boolean }) => Promise<InboxFeedResult>;
@@ -953,6 +953,30 @@ export type MessageSearchResult = {
session_count: number;
};
+export type SessionActivityState = {
+ id: string;
+ backend: string;
+ runtime_key: string;
+ session_id: string | null;
+ kind: string;
+ status: string;
+ description: string | null;
+ started_at: string;
+ updated_at: string;
+};
+
+export type SessionRuntimeState = {
+ in_flight: boolean | null;
+ foreground: 'idle' | 'running' | 'unknown';
+ native_turn_started: boolean;
+ pending_input_count: number;
+ background_activities: SessionActivityState[];
+ pending_activity_output_count: number;
+ connection: 'connected' | 'reconnecting' | 'disconnected' | 'unknown';
+ backend?: string;
+ recovered_agent_status?: boolean;
+};
+
export type WorkbenchSessionBootstrap = {
session: WorkbenchSession;
agents: VibeAgentBrief[];
@@ -963,7 +987,7 @@ export type WorkbenchSessionBootstrap = {
next_before_id?: string | null;
queued: WorkbenchMessage[];
draft: { text: string };
- turn_state: { in_flight: boolean | null };
+ turn_state: SessionRuntimeState;
};
// One row of the per-session ("Slack-like") inbox feed from ``GET /api/inbox``.
@@ -2306,7 +2330,15 @@ export const ApiProvider: React.FC<{ children: React.ReactNode }> = ({ children
const res = await apiFetch(path);
if (res.status === 504) {
readCacheRef.current.delete(path);
- return { in_flight: null };
+ return {
+ in_flight: null,
+ foreground: 'unknown',
+ native_turn_started: false,
+ pending_input_count: 0,
+ background_activities: [],
+ pending_activity_output_count: 0,
+ connection: 'unknown',
+ };
}
if (!res.ok) {
await handleApiError(res, path);
diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json
index 412193754..ac07b3a71 100644
--- a/ui/src/i18n/en.json
+++ b/ui/src/i18n/en.json
@@ -2210,6 +2210,14 @@
"zoomIn": "Zoom in",
"zoomOut": "Zoom out"
},
+ "activities": {
+ "running": "Background work · {{count}}",
+ "delivering": "Delivering background output · {{count}}",
+ "connection": {
+ "reconnecting": "Reconnecting",
+ "disconnected": "Disconnected"
+ }
+ },
"queue": {
"title": "Queued · {{count}}",
"sendNow": "Send now",
diff --git a/ui/src/i18n/zh.json b/ui/src/i18n/zh.json
index 1e59375cf..5d693123e 100644
--- a/ui/src/i18n/zh.json
+++ b/ui/src/i18n/zh.json
@@ -2210,6 +2210,14 @@
"zoomIn": "放大",
"zoomOut": "缩小"
},
+ "activities": {
+ "running": "后台工作 · {{count}}",
+ "delivering": "正在投递后台输出 · {{count}}",
+ "connection": {
+ "reconnecting": "重连中",
+ "disconnected": "已断开"
+ }
+ },
"queue": {
"title": "排队中 · {{count}}",
"sendNow": "立即发送",
diff --git a/vibe/ui_server.py b/vibe/ui_server.py
index bc4879829..476cc1be9 100644
--- a/vibe/ui_server.py
+++ b/vibe/ui_server.py
@@ -5623,6 +5623,62 @@ def sessions_get(session_id: str):
return jsonify({"error": str(err)}), 404
+def _session_runtime_projection(
+ body: dict[str, Any] | None,
+ *,
+ pending_input_count: int | None = None,
+ controller_available: bool | None = True,
+) -> dict[str, Any]:
+ """Normalize the controller's orthogonal Session runtime axes for the UI."""
+
+ payload = body if isinstance(body, dict) else {}
+ raw_foreground = str(payload.get("foreground") or "").strip()
+ if raw_foreground not in {"idle", "running"}:
+ if controller_available is None:
+ foreground = "unknown"
+ else:
+ foreground = "running" if bool(payload.get("in_flight")) else "idle"
+ else:
+ foreground = raw_foreground
+
+ raw_connection = str(payload.get("connection") or "").strip()
+ if raw_connection not in {"connected", "reconnecting", "disconnected", "unknown"}:
+ raw_connection = "disconnected" if controller_available is False else "unknown"
+
+ if pending_input_count is None:
+ try:
+ pending_input_count = max(0, int(payload.get("pending_input_count") or 0))
+ except (TypeError, ValueError):
+ pending_input_count = 0
+ try:
+ pending_output_count = max(
+ 0,
+ int(payload.get("pending_activity_output_count") or 0),
+ )
+ except (TypeError, ValueError):
+ pending_output_count = 0
+ raw_activities = payload.get("background_activities")
+ activities = (
+ [dict(item) for item in raw_activities if isinstance(item, dict)]
+ if isinstance(raw_activities, list)
+ else []
+ )
+ projection: dict[str, Any] = {
+ # Retained as a read-only compatibility alias for older clients.
+ "in_flight": None if foreground == "unknown" else foreground == "running",
+ "foreground": foreground,
+ "native_turn_started": bool(payload.get("native_turn_started")),
+ "pending_input_count": pending_input_count,
+ "background_activities": activities,
+ "pending_activity_output_count": pending_output_count,
+ "connection": raw_connection,
+ }
+ backend = str(payload.get("backend") or "").strip()
+ if backend:
+ projection["backend"] = backend
+ return projection
+
+
@app.route("/api/sessions/<session_id>/bootstrap", methods=["GET"])
async def sessions_bootstrap(session_id: str):
"""First-screen payload for the Workbench Chat page.
@@ -5670,11 +5726,22 @@ async def sessions_bootstrap(session_id: str):
try:
turn_result = await internal_client.turn_state(session_id)
turn_body = turn_result.get("body") or {}
- turn_state = {"in_flight": bool(turn_body.get("in_flight"))}
+ turn_state = _session_runtime_projection(
+ turn_body,
+ pending_input_count=len(queued),
+ )
except internal_client.InternalServerUnavailable:
- turn_state = {"in_flight": False}
+ turn_state = _session_runtime_projection(
+ None,
+ pending_input_count=len(queued),
+ controller_available=False,
+ )
except internal_client.InternalServerTimeout:
- turn_state = {"in_flight": None}
+ turn_state = _session_runtime_projection(
+ None,
+ pending_input_count=len(queued),
+ controller_available=None,
+ )
return jsonify(
{
@@ -6896,15 +6963,18 @@ def sessions_mark_read(session_id: str):
@app.route("/api/sessions/<session_id>/turn-state", methods=["GET"])
async def sessions_turn_state(session_id: str):
- """Whether a turn is currently in flight (so a freshly loaded / reconnected
- Chat page can restore its Stop/working state). Degrades to idle if the
- controller socket is unreachable."""
+ """Return independent foreground, Inbox, Activity, and connection facts."""
from vibe import internal_client
try:
result = await internal_client.turn_state(session_id)
except internal_client.InternalServerUnavailable:
- return jsonify({"in_flight": False})
+ return jsonify(
+ _session_runtime_projection(
+ None,
+ controller_available=False,
+ )
+ )
except internal_client.InternalServerTimeout:
return (
jsonify(
@@ -6918,11 +6988,13 @@ async def sessions_turn_state(session_id: str):
504,
)
body = result.get("body") or {}
- in_flight = bool(body.get("in_flight"))
+ projection = _session_runtime_projection(body)
+ in_flight = projection["foreground"] == "running"
recovered = False
if not in_flight:
recovered = _recover_stale_session_status(session_id)
- return jsonify({"in_flight": in_flight, "recovered_agent_status": recovered})
+ projection["recovered_agent_status"] = recovered
+ return jsonify(projection)
@app.route("/api/sessions/<session_id>/queue", methods=["GET"])