Skip to content

armgit / avibe

Public Imported from GitHub
0

Make your computer a home for your AI partner. Avibe is the local-first Agent OS: Vibey, its built-in AI partner, works out of the box, and Claude Code, Codex & OpenCode run unchanged beside it — reach them from your browser, phone, or any chat app.

fix(agent-run): settle external stops so Running-tab End doesn't wedge the session queue (#665)

Call White7edd87209858
diff --git a/core/controller.py b/core/controller.py
index be48ffbba..686355028 100644
--- a/core/controller.py
+++ b/core/controller.py
@@ -958,9 +958,13 @@ class Controller:
# Owned by the turn owner (FSM); exposed here for back-compat readers.
return self.session_turns.active_turn_sinks
- def register_turn_sink(self, session_key: str, *, on_chunk, done_event, turn_token=None) -> None:
+ def register_turn_sink(self, session_key: str, *, on_chunk, done_event, turn_token=None, context=None) -> None:
self.session_turns.register_turn_sink(
- session_key, on_chunk=on_chunk, done_event=done_event, turn_token=turn_token
+ session_key,
+ on_chunk=on_chunk,
+ done_event=done_event,
+ turn_token=turn_token,
+ context=context,
)
def pop_turn_sink(self, session_key: str, done_event=None) -> None:
@@ -969,6 +973,22 @@ class Controller:
def get_turn_sink(self, session_key: str) -> Optional[Dict[str, Any]]:
return self.session_turns.get_turn_sink(session_key)
+ def bind_context_to_turn_sink(
+ self,
+ context: MessageContext,
+ *,
+ agent_session_id: Optional[str] = None,
+ backend_base_session_id: Optional[str] = None,
+ ) -> Optional[Dict[str, Any]]:
+ return self.session_turns.bind_context_to_turn_sink(
+ context,
+ agent_session_id=agent_session_id,
+ backend_base_session_id=backend_base_session_id,
+ )
+
+ def settle_bound_turn_sink(self, binding: Optional[Dict[str, Any]]) -> bool:
+ return self.session_turns.settle_bound_turn_sink(binding)
+
def mark_turn_complete(self, context: Optional[MessageContext] = None) -> None:
"""Release a streaming turn sink whose turn finished WITHOUT emitting a
result (missing/disabled backend, dedup, inline-stop, error, or any
diff --git a/core/services/dispatch.py b/core/services/dispatch.py
index e6710c4c5..cf0cd2fb0 100644
--- a/core/services/dispatch.py
+++ b/core/services/dispatch.py
@@ -104,7 +104,13 @@ async def dispatch_turn(
context.platform_specific = {}
context.platform_specific["turn_token"] = turn_token
done = asyncio.Event()
- controller.register_turn_sink(session_key, on_chunk=on_chunk, done_event=done, turn_token=turn_token)
+ controller.register_turn_sink(
+ session_key,
+ on_chunk=on_chunk,
+ done_event=done,
+ turn_token=turn_token,
+ context=context,
+ )
try:
result = await _run()
# Wait for the agent's REAL terminal result, however long it takes — a
diff --git a/core/services/running_agents.py b/core/services/running_agents.py
index 371218a3e..0cf3e94cf 100644
--- a/core/services/running_agents.py
+++ b/core/services/running_agents.py
@@ -806,6 +806,97 @@ def _live_workdir_for_backend(
return None
+def _effective_base_session_id(base_session_id: Optional[str], composite_key: Optional[str]) -> Optional[str]:
+ return base_session_id or (_base_from_composite(composite_key) if composite_key else None)
+
+
+def _resolve_session_key_context(
+ controller: "Controller",
+ target: Any,
+) -> dict[str, Any]:
+ platform = target.session_key.platform
+ channel_id = target.session_key.scope_id
+ user_id = "scheduled"
+ if target.session_key.is_dm:
+ user_id = target.session_key.scope_id
+ try:
+ settings_managers = getattr(controller, "platform_settings_managers", {}) or {}
+ settings_manager = settings_managers.get(platform)
+ store = settings_manager.get_store() if settings_manager is not None else None
+ bound_user = store.get_user(target.session_key.scope_id, platform=platform) if store is not None else None
+ except Exception: # noqa: BLE001
+ bound_user = None
+ dm_chat_id = str(getattr(bound_user, "dm_chat_id", "") or "").strip()
+ if dm_chat_id:
+ channel_id = dm_chat_id
+ return {"user_id": user_id, "channel_id": channel_id}
+
+
+def _build_session_row_stop_context(
+ controller: "Controller",
+ *,
+ backend: Optional[str],
+ session_id: Optional[str],
+ composite_key: Optional[str],
+ base_session_id: Optional[str],
+) -> Any:
+ """Build a stop context from the agent_sessions row's real scope.
+
+ Running-tab End for a private ``vibe agent run`` targets an agent_sessions
+ row whose scope is a placeholder primary-platform channel, not a Workbench
+ ``avibe`` session. The Workbench context builder would produce
+ ``avibe::<session_id>``, which can stop the backend when backend ids are
+ patched in, but cannot find the dispatch sink registered under the original
+ scope key. Rebuild the same scope context that ``_execute_agent_run`` used so
+ ``controller._get_session_key`` resolves to the live sink.
+ """
+ if not session_id:
+ return None
+ try:
+ from core.scheduled_tasks import resolve_session_id_target
+ from modules.im import MessageContext
+ except Exception: # noqa: BLE001
+ return None
+ try:
+ target = resolve_session_id_target(session_id)
+ except Exception: # noqa: BLE001
+ logger.debug("end: failed to resolve stop session target for %s", session_id, exc_info=True)
+ return None
+ scope_context = _resolve_session_key_context(controller, target)
+ platform = target.session_key.platform
+ payload = {
+ "platform": platform,
+ "is_dm": target.session_key.is_dm,
+ "turn_source": "scheduled",
+ "agent_session_id": session_id,
+ "session_key_external": target.session_key.to_key(),
+ "delivery_key_external": target.session_key.to_key(),
+ "delivery_scope_session_key": target.session_key.session_scope,
+ "suppress_delivery": bool(target.suppress_delivery),
+ "agent_session_target": {
+ "id": target.session_id,
+ "agent_id": target.agent_id,
+ "agent_name": target.agent_name,
+ "agent_backend": target.agent_backend or backend,
+ "agent_variant": target.agent_variant,
+ "model": target.model,
+ "reasoning_effort": target.reasoning_effort,
+ "native_session_id": target.native_session_id,
+ "workdir": target.workdir,
+ "session_anchor": target.session_anchor or base_session_id,
+ "metadata": target.metadata or {},
+ "suppress_delivery": bool(target.suppress_delivery),
+ },
+ }
+ return MessageContext(
+ user_id=scope_context["user_id"],
+ channel_id=scope_context["channel_id"],
+ platform=platform,
+ thread_id=target.session_key.thread_id,
+ platform_specific=payload,
+ )
+
+
def _build_stop_context(
controller: "Controller",
*,
@@ -816,10 +907,20 @@ def _build_stop_context(
) -> Any:
manager = getattr(controller, "session_turns", None)
build_context = getattr(manager, "_build_context", None)
- context = None
- if session_id and callable(build_context):
+ context = _build_session_row_stop_context(
+ controller,
+ backend=backend,
+ session_id=session_id,
+ composite_key=composite_key,
+ base_session_id=base_session_id,
+ )
+ if context is None and session_id and callable(build_context):
try:
- context = build_context(session_id)
+ workbench_context = build_context(session_id)
+ if workbench_context is not None:
+ spec = getattr(workbench_context, "platform_specific", None) or {}
+ if spec.get("workbench_session_id") == session_id and getattr(workbench_context, "platform", None) == "avibe":
+ context = workbench_context
except Exception: # noqa: BLE001
logger.debug("end: failed to rebuild stop context for %s", session_id, exc_info=True)
if context is None:
@@ -833,7 +934,7 @@ def _build_stop_context(
context.platform_specific = {}
payload = context.platform_specific
payload["suppress_stop_no_active_notice"] = True
- effective_base_session_id = base_session_id or (_base_from_composite(composite_key) if composite_key else None)
+ effective_base_session_id = _effective_base_session_id(base_session_id, composite_key)
if effective_base_session_id:
payload["backend_base_session_id"] = effective_base_session_id
if composite_key:
@@ -881,13 +982,28 @@ async def _stop_active_agent(
)
if context is None:
return {"ok": False, "error": "context_unavailable"}
+ sink_binding = None
+ bind_sink = getattr(controller, "bind_context_to_turn_sink", None)
+ if callable(bind_sink):
+ sink_binding = bind_sink(
+ context,
+ agent_session_id=session_id,
+ backend_base_session_id=_effective_base_session_id(base_session_id, composite_key),
+ )
try:
handled = bool(await handle_stop(context))
except Exception: # noqa: BLE001
logger.debug("end: canonical stop failed for %s", base_session_id or session_id, exc_info=True)
return {"ok": False, "error": "stop_failed"}
if handled:
- return {"ok": True, "action": "stopped", "backend": backend, "turn_settled": False}
+ settle_sink = getattr(controller, "settle_bound_turn_sink", None)
+ fallback_settled = bool(settle_sink(sink_binding)) if callable(settle_sink) else False
+ return {
+ "ok": True,
+ "action": "stopped",
+ "backend": backend,
+ "turn_settled": bool(sink_binding) or fallback_settled,
+ }
payload = getattr(context, "platform_specific", None) or {}
return {"ok": False, "error": str(payload.get("stop_failure_reason") or "stop_failed")}
diff --git a/core/session_turns.py b/core/session_turns.py
index eb643e36d..a0b506e20 100644
--- a/core/session_turns.py
+++ b/core/session_turns.py
@@ -1246,7 +1246,40 @@ class SessionTurnManager:
# --- the live streaming turn sink (owned here; Controller delegates) ----------
- def register_turn_sink(self, session_key: str, *, on_chunk, done_event, turn_token=None) -> None:
+ @staticmethod
+ def _turn_sink_identity(context: Optional["MessageContext"]) -> dict[str, Any]:
+ raw_spec = getattr(context, "platform_specific", None) or {}
+ spec = raw_spec if isinstance(raw_spec, dict) else {}
+ target = spec.get("agent_session_target")
+ target = target if isinstance(target, dict) else {}
+ agent_session_id = str(spec.get("agent_session_id") or target.get("id") or "").strip()
+ backend_base_session_id = str(
+ spec.get("backend_base_session_id")
+ or target.get("session_anchor")
+ or ""
+ ).strip()
+ identity: dict[str, Any] = {
+ "agent_session_id": agent_session_id,
+ "backend_base_session_id": backend_base_session_id,
+ }
+ task_trigger_kind = str(spec.get("task_trigger_kind") or "").strip()
+ if task_trigger_kind:
+ identity["task_trigger_kind"] = task_trigger_kind
+ task_execution_id = str(spec.get("task_execution_id") or "").strip()
+ if task_execution_id:
+ identity["task_execution_id"] = task_execution_id
+ coalesced_queue = spec.get("coalesced_queue")
+ if isinstance(coalesced_queue, dict):
+ copied_queue = dict(coalesced_queue)
+ execution_ids = copied_queue.get("execution_ids")
+ if isinstance(execution_ids, list):
+ copied_queue["execution_ids"] = list(execution_ids)
+ identity["coalesced_queue"] = copied_queue
+ elif coalesced_queue is not None:
+ identity["coalesced_queue"] = coalesced_queue
+ return identity
+
+ def register_turn_sink(self, session_key: str, *, on_chunk, done_event, turn_token=None, context=None) -> None:
if session_key in self.active_turn_sinks:
# dispatch_turn serializes streaming turns per session, so this should not
# happen; if it does, keep the in-flight turn's sink rather than clobbering
@@ -1255,10 +1288,12 @@ class SessionTurnManager:
return
# turn_token correlates emits to this exact turn so a late straggler from a
# superseded turn (same session key) is dropped in _stream_chunk.
+ identity = self._turn_sink_identity(context)
self.active_turn_sinks[session_key] = {
"on_chunk": on_chunk,
"done_event": done_event,
"turn_token": turn_token,
+ **identity,
}
def pop_turn_sink(self, session_key: str, done_event=None) -> None:
@@ -1276,6 +1311,111 @@ class SessionTurnManager:
def get_turn_sink(self, session_key: str) -> Optional[dict]:
return self.active_turn_sinks.get(session_key)
+ @staticmethod
+ def _sink_identity_matches(
+ sink: dict,
+ *,
+ agent_session_id: Optional[str],
+ backend_base_session_id: Optional[str],
+ ) -> bool:
+ expected_session = str(agent_session_id or "").strip()
+ expected_base = str(backend_base_session_id or "").strip()
+ if expected_session and sink.get("agent_session_id") != expected_session:
+ return False
+ if expected_base and sink.get("backend_base_session_id") != expected_base:
+ return False
+ return True
+
+ def bind_context_to_turn_sink(
+ self,
+ context: "MessageContext",
+ *,
+ agent_session_id: Optional[str] = None,
+ backend_base_session_id: Optional[str] = None,
+ ) -> Optional[dict]:
+ """Stamp the live sink's token onto an external stop context.
+
+ Running-tab End may stop an agent-run turn from outside the original
+ dispatch context. Rebuild the context to the same session key, require the
+ registered sink's session/base identity to match the clicked row, then copy
+ that sink's token so the backend's silent terminal result satisfies the
+ normal active-turn guard. The returned binding can be used as an
+ identity-guarded fallback if the backend stops without emitting.
+ """
+ if self.controller is None:
+ return None
+ get_key = getattr(self.controller, "_get_session_key", None)
+ if not callable(get_key):
+ return None
+ try:
+ session_key = get_key(context)
+ except Exception:
+ logger.debug("turn sink bind: failed to derive session key", exc_info=True)
+ return None
+ sink = self.active_turn_sinks.get(session_key)
+ if sink is None:
+ return None
+ if not self._sink_identity_matches(
+ sink,
+ agent_session_id=agent_session_id,
+ backend_base_session_id=backend_base_session_id,
+ ):
+ return None
+ token = sink.get("turn_token")
+ attribution_keys = ("task_trigger_kind", "task_execution_id", "coalesced_queue")
+ if token or any(key in sink for key in attribution_keys):
+ if context.platform_specific is None:
+ context.platform_specific = {}
+ if token:
+ context.platform_specific["turn_token"] = token
+ for key in attribution_keys:
+ if key not in sink:
+ continue
+ value = sink[key]
+ if isinstance(value, dict):
+ copied_value = dict(value)
+ execution_ids = copied_value.get("execution_ids")
+ if isinstance(execution_ids, list):
+ copied_value["execution_ids"] = list(execution_ids)
+ value = copied_value
+ context.platform_specific[key] = value
+ return {
+ "session_key": session_key,
+ "sink": sink,
+ "done_event": sink.get("done_event"),
+ "turn_token": token,
+ }
+
+ def settle_bound_turn_sink(self, binding: Optional[dict]) -> bool:
+ """Settle the same sink returned by ``bind_context_to_turn_sink``.
+
+ This is a fallback for stop paths that successfully interrupt a backend
+ but do not emit a terminal result. It only releases the dispatch waiter;
+ run completion is still owned by the backend's terminal emit. Current
+ live backends emit that terminal before ``handle_stop`` returns, and the
+ bound stop context carries the original agent-run attribution so the emit
+ records the run terminal. The identity guard is intentionally object-based
+ so a late stop cannot complete a newer sink registered under the same
+ session key.
+ """
+ if not isinstance(binding, dict):
+ return False
+ session_key = binding.get("session_key")
+ sink = binding.get("sink")
+ if not session_key or self.active_turn_sinks.get(session_key) is not sink:
+ return False
+ done = sink.get("done_event") if isinstance(sink, dict) else None
+ if done is None or done is not binding.get("done_event"):
+ return False
+ token = binding.get("turn_token")
+ if token is not None and sink.get("turn_token") != token:
+ return False
+ is_set = getattr(done, "is_set", None)
+ if callable(is_set) and is_set():
+ return False
+ done.set()
+ return True
+
# --- boot / restore edge transitions -----------------------------------------
@staticmethod
diff --git a/tests/test_core_services_dispatch.py b/tests/test_core_services_dispatch.py
index f981e61fb..2b41fa08d 100644
--- a/tests/test_core_services_dispatch.py
+++ b/tests/test_core_services_dispatch.py
@@ -86,11 +86,12 @@ def test_streaming_registers_turn_sink_and_waits_for_result():
captured: dict = {}
- def _register(session_key, *, on_chunk, done_event, turn_token=None):
+ def _register(session_key, *, on_chunk, done_event, turn_token=None, context=None):
captured["session_key"] = session_key
captured["on_chunk"] = on_chunk
captured["done_event"] = done_event
captured["turn_token"] = turn_token
+ captured["context"] = context
# Simulate the agent's background receiver emitting the result,
# which sets the done event so dispatch_turn returns promptly
# instead of waiting out the safety timeout.
@@ -105,6 +106,7 @@ def test_streaming_registers_turn_sink_and_waits_for_result():
assert captured["session_key"] == "slack::C"
assert captured["on_chunk"] is _on_chunk
+ assert captured["context"] is ctx
assert isinstance(captured["done_event"], asyncio.Event)
# Cleanup passes our own done event so a superseded turn can't evict a
# newer concurrent turn's sink.
diff --git a/tests/test_dispatcher_stream_chunk.py b/tests/test_dispatcher_stream_chunk.py
index 09b8fc4a1..25afd7b25 100644
--- a/tests/test_dispatcher_stream_chunk.py
+++ b/tests/test_dispatcher_stream_chunk.py
@@ -32,7 +32,7 @@ class _ControllerDouble:
def _get_session_key(self, ctx):
return f"{ctx.platform}::{ctx.channel_id}"
- def register_turn_sink(self, session_key, *, on_chunk, done_event, turn_token=None):
+ def register_turn_sink(self, session_key, *, on_chunk, done_event, turn_token=None, context=None):
self.active_turn_sinks[session_key] = {
"on_chunk": on_chunk,
"done_event": done_event,
diff --git a/tests/test_internal_server.py b/tests/test_internal_server.py
index 7d822d462..6cc6d85f7 100644
--- a/tests/test_internal_server.py
+++ b/tests/test_internal_server.py
@@ -79,7 +79,7 @@ def _build_controller_double(handler=None):
controller.active_turn_sinks = sinks
controller._get_session_key = lambda ctx: f"{getattr(ctx, 'platform', None)}::{getattr(ctx, 'channel_id', None)}"
- def _register(session_key, *, on_chunk, done_event, turn_token=None):
+ def _register(session_key, *, on_chunk, done_event, turn_token=None, context=None):
sinks[session_key] = {"on_chunk": on_chunk, "done_event": done_event, "turn_token": turn_token}
controller.register_turn_sink = _register
diff --git a/tests/test_running_agents_service.py b/tests/test_running_agents_service.py
index af2b22fea..eb4b80c36 100644
--- a/tests/test_running_agents_service.py
+++ b/tests/test_running_agents_service.py
@@ -873,6 +873,204 @@ def test_end_active_im_turn_uses_canonical_stop_path(monkeypatch):
assert payload["suppress_stop_no_active_notice"] is True
+def test_end_active_agent_run_binds_stop_context_to_matching_turn_sink(monkeypatch):
+ from core.scheduled_tasks import ParsedSessionKey, ResolvedSessionIdTarget
+ from core.session_turns import SessionTurnManager
+ from modules.im import MessageContext
+
+ session_id = "ses-run"
+ base_session_id = "slack_private-agent-abc"
+ sink_done = asyncio.Event()
+ seen = {}
+
+ target = ResolvedSessionIdTarget(
+ session_id=session_id,
+ session_key=ParsedSessionKey(
+ platform="slack",
+ scope_type="channel",
+ scope_id="private-agent-run-scope",
+ thread_id="private-agent-abc",
+ ),
+ agent_backend="codex",
+ agent_variant="codex",
+ native_session_id="",
+ agent_name="codex",
+ workdir="/w",
+ session_anchor=base_session_id,
+ metadata={"no_delivery": True},
+ suppress_delivery=True,
+ )
+ monkeypatch.setattr(
+ "core.scheduled_tasks.resolve_session_id_target",
+ lambda sid: target if sid == session_id else None,
+ )
+
+ async def _handle_stop(context):
+ seen["context"] = context
+ return True
+
+ class _Controller:
+ platform_settings_managers = {}
+
+ def __init__(self):
+ self.command_handler = types.SimpleNamespace(handle_stop=_handle_stop)
+ self.session_turns = SessionTurnManager(self)
+
+ def _get_session_key(self, context):
+ return f"{context.platform}::{context.channel_id}"
+
+ def bind_context_to_turn_sink(self, context, *, agent_session_id=None, backend_base_session_id=None):
+ return self.session_turns.bind_context_to_turn_sink(
+ context,
+ agent_session_id=agent_session_id,
+ backend_base_session_id=backend_base_session_id,
+ )
+
+ def settle_bound_turn_sink(self, binding):
+ return self.session_turns.settle_bound_turn_sink(binding)
+
+ controller = _Controller()
+ dispatch_context = MessageContext(
+ user_id="scheduled",
+ channel_id="private-agent-run-scope",
+ platform="slack",
+ thread_id="private-agent-abc",
+ platform_specific={
+ "agent_session_id": session_id,
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-primary",
+ "coalesced_queue": {"execution_ids": ["run-coalesced"]},
+ "agent_session_target": {
+ "id": session_id,
+ "agent_backend": "codex",
+ "session_anchor": base_session_id,
+ },
+ },
+ )
+ controller.session_turns.register_turn_sink(
+ "slack::private-agent-run-scope",
+ on_chunk=lambda _envelope: None,
+ done_event=sink_done,
+ turn_token="sink-token",
+ context=dispatch_context,
+ )
+
+ res = asyncio.run(
+ running_agents._stop_active_agent(
+ controller,
+ backend="codex",
+ session_id=session_id,
+ composite_key=None,
+ base_session_id=base_session_id,
+ )
+ )
+
+ assert res["ok"] is True
+ assert res["turn_settled"] is True
+ assert sink_done.is_set()
+ stopped_context = seen["context"]
+ assert controller._get_session_key(stopped_context) == "slack::private-agent-run-scope"
+ assert stopped_context.platform_specific["turn_token"] == "sink-token"
+ assert stopped_context.platform_specific["task_trigger_kind"] == "agent_run"
+ assert stopped_context.platform_specific["task_execution_id"] == "run-primary"
+ assert stopped_context.platform_specific["coalesced_queue"] == {"execution_ids": ["run-coalesced"]}
+ assert stopped_context.platform_specific["agent_session_target"]["session_anchor"] == base_session_id
+
+
+def test_end_active_agent_run_does_not_settle_mismatched_turn_sink(monkeypatch):
+ from core.scheduled_tasks import ParsedSessionKey, ResolvedSessionIdTarget
+ from core.session_turns import SessionTurnManager
+ from modules.im import MessageContext
+
+ session_id = "ses-clicked"
+ sink_done = asyncio.Event()
+ target = ResolvedSessionIdTarget(
+ session_id=session_id,
+ session_key=ParsedSessionKey(
+ platform="slack",
+ scope_type="channel",
+ scope_id="private-agent-run-scope",
+ thread_id="private-agent-abc",
+ ),
+ agent_backend="codex",
+ agent_variant="codex",
+ native_session_id="",
+ session_anchor="slack_private-agent-clicked",
+ )
+ monkeypatch.setattr(
+ "core.scheduled_tasks.resolve_session_id_target",
+ lambda sid: target if sid == session_id else None,
+ )
+
+ seen = {}
+
+ async def _handle_stop(context):
+ seen["context"] = context
+ return True
+
+ class _Controller:
+ platform_settings_managers = {}
+
+ def __init__(self):
+ self.command_handler = types.SimpleNamespace(handle_stop=_handle_stop)
+ self.session_turns = SessionTurnManager(self)
+
+ def _get_session_key(self, context):
+ return f"{context.platform}::{context.channel_id}"
+
+ def bind_context_to_turn_sink(self, context, *, agent_session_id=None, backend_base_session_id=None):
+ return self.session_turns.bind_context_to_turn_sink(
+ context,
+ agent_session_id=agent_session_id,
+ backend_base_session_id=backend_base_session_id,
+ )
+
+ def settle_bound_turn_sink(self, binding):
+ return self.session_turns.settle_bound_turn_sink(binding)
+
+ controller = _Controller()
+ newer_context = MessageContext(
+ user_id="scheduled",
+ channel_id="private-agent-run-scope",
+ platform="slack",
+ platform_specific={
+ "agent_session_id": "ses-newer",
+ "task_trigger_kind": "agent_run",
+ "task_execution_id": "run-newer",
+ "agent_session_target": {
+ "id": "ses-newer",
+ "agent_backend": "codex",
+ "session_anchor": "slack_private-agent-newer",
+ },
+ },
+ )
+ controller.session_turns.register_turn_sink(
+ "slack::private-agent-run-scope",
+ on_chunk=lambda _envelope: None,
+ done_event=sink_done,
+ turn_token="new-token",
+ context=newer_context,
+ )
+
+ res = asyncio.run(
+ running_agents._stop_active_agent(
+ controller,
+ backend="codex",
+ session_id=session_id,
+ composite_key=None,
+ base_session_id="slack_private-agent-clicked",
+ )
+ )
+
+ assert res["ok"] is True
+ assert res["turn_settled"] is False
+ assert not sink_done.is_set()
+ stopped_context = seen["context"]
+ assert stopped_context.platform_specific.get("turn_token") is None
+ assert stopped_context.platform_specific.get("task_trigger_kind") is None
+ assert stopped_context.platform_specific.get("task_execution_id") is None
+
+
def test_end_active_codex_frees_runtime_after_stop():
# Active Codex End must FREE the runtime after the canonical stop (which only
# interrupts the turn): clear the session mappings + stop the now-unused shared
diff --git a/tests/test_scheduled_tasks.py b/tests/test_scheduled_tasks.py
index 7fa0fe7ee..08b39806c 100644
--- a/tests/test_scheduled_tasks.py
+++ b/tests/test_scheduled_tasks.py
@@ -1393,7 +1393,7 @@ def test_agent_run_stays_running_until_terminal_result(tmp_path: Path, monkeypat
def get_turn_sink(self, session_key):
return self.active_turn_sinks.get(session_key)
- def register_turn_sink(self, session_key, *, on_chunk, done_event, turn_token=None):
+ def register_turn_sink(self, session_key, *, on_chunk, done_event, turn_token=None, context=None):
self.active_turn_sinks[session_key] = {
"on_chunk": on_chunk,
"done_event": done_event,
@@ -1485,7 +1485,7 @@ def test_agent_run_preserves_failed_terminal_status(tmp_path: Path, monkeypatch)
def get_turn_sink(self, session_key):
return self.active_turn_sinks.get(session_key)
- def register_turn_sink(self, session_key, *, on_chunk, done_event, turn_token=None):
+ def register_turn_sink(self, session_key, *, on_chunk, done_event, turn_token=None, context=None):
self.active_turn_sinks[session_key] = {
"on_chunk": on_chunk,
"done_event": done_event,
@@ -1855,7 +1855,7 @@ def test_agent_run_synchronous_dispatch_error_marks_failed(tmp_path: Path, monke
def get_turn_sink(self, session_key):
return self.active_turn_sinks.get(session_key)
- def register_turn_sink(self, session_key, *, on_chunk, done_event, turn_token=None):
+ def register_turn_sink(self, session_key, *, on_chunk, done_event, turn_token=None, context=None):
self.active_turn_sinks[session_key] = {
"on_chunk": on_chunk,
"done_event": done_event,
@@ -2310,7 +2310,7 @@ def test_drain_requests_agent_run_passes_agent_name(tmp_path: Path) -> None:
def get_turn_sink(self, session_key):
return self.active_turn_sinks.get(session_key)
- def register_turn_sink(self, session_key, *, on_chunk, done_event, turn_token=None):
+ def register_turn_sink(self, session_key, *, on_chunk, done_event, turn_token=None, context=None):
self.active_turn_sinks[session_key] = {
"on_chunk": on_chunk,
"done_event": done_event,