The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): /stop falls back to any running turn in the same chat
Ben Barclay59c426725cbb
diff --git a/gateway/run_busy.py b/gateway/run_busy.pyindex 344c7ad2494..12f583ebb83 100644--- a/gateway/run_busy.py+++ b/gateway/run_busy.py@@ -1060,6 +1060,43 @@ class GatewayBusySessionMixin:and (key == prefix or key.startswith(prefix + ":"))]+ def _chat_scoped_run_keys(self, source: SessionSource, own_key: str) -> list:+ """Running-agent keys for ANY session of the same (platform[, scope], chat), regardless of+ the chat_type/thread/participant slots. Two supported shapes make a /stop key miss a run in+ the same chat (found via Slack's native stop button, gateway-gateway#286): a top-level+ channel turn keys ``channel`` while an in-thread /stop normalizes to ``thread``, and+ rolling-DM configs key without the thread slot the stop carries. "/stop" means "stop what's+ running in THIS chat", so the handler falls back chat-wide on an exact+sibling miss.+ Never crosses chat_id; Slack keys are matched with and without the scope_id slot (older+ sources may lack it). Excludes the pending sentinel and ``own_key``; callers gate on authz.+ """+ from gateway.run import _AGENT_PENDING_SENTINEL+ chat_id = getattr(source, "chat_id", None)+ if not chat_id:+ return []+ platform = source.platform.value+ # Derive the namespace from the caller's own key (profile-aware), not a literal.+ marker = f":{platform}:"+ namespace = own_key.split(marker, 1)[0] if marker in own_key else "agent:main"+ scope_id = getattr(source, "scope_id", None)+ chat_types = {getattr(source, "chat_type", None), "dm", "group", "channel", "thread"}+ prefixes = []+ for chat_type in chat_types:+ if not chat_type:+ continue+ base = f"{namespace}:{platform}:{chat_type}"+ prefixes.append(f"{base}:{chat_id}")+ if scope_id:+ prefixes.append(f"{base}:{scope_id}:{chat_id}")+ return [+ key+ for key, agent in self._running_agent_items()+ if key != own_key+ and agent is not _AGENT_PENDING_SENTINEL and agent+ # Exact key or prefix + ":" so a chat id that merely starts with this one never matches.+ and any(key == prefix or key.startswith(prefix + ":") for prefix in prefixes)+ ]+def _is_stale_restart_redelivery(self, event: MessageEvent) -> bool:"""True if this /restart is a Telegram re-delivery we already handled.diff --git a/gateway/slash_commands.py b/gateway/slash_commands.pyindex eefeb2264b1..c019141f985 100644--- a/gateway/slash_commands.py+++ b/gateway/slash_commands.py@@ -446,6 +446,19 @@ class GatewaySlashCommandsMixin(session_key, len(sibling_keys), ", ".join(sibling_keys))return EphemeralReply(t("gateway.stop.stopped"))+ # Exact and thread-sibling misses can still leave a running turn in THIS chat under a+ # differently-shaped key: a top-level channel turn keys ``channel`` while an in-thread+ # /stop (incl. Slack's native stop button, gateway-gateway#286) normalizes to ``thread``,+ # and rolling-DM configs key without the thread slot the stop carries. "/stop" means+ # "stop what's running in this chat" — fall back chat-wide, gated on authorization.+ chat_keys = self._chat_scoped_run_keys(source, session_key)+ if chat_keys and self._is_user_authorized_for_source(source):+ for chat_key in chat_keys:+ await _stop(chat_key, "stop_command_chat_scope")+ logger.info("STOP (chat scope) by %s — interrupted %d run(s) in chat: %s",+ session_key, len(chat_keys), ", ".join(chat_keys))+ return EphemeralReply(t("gateway.stop.stopped"))+# No running agent anywhere for this scope. A platform status indicator can still be stuck —# e.g. Slack's persistent assistant.threads.setStatus survives a gateway restart or a turn# that died without a final send.diff --git a/tests/gateway/test_stop_chat_scope.py b/tests/gateway/test_stop_chat_scope.pynew file mode 100644index 00000000000..f8bf8646e73--- /dev/null+++ b/tests/gateway/test_stop_chat_scope.py@@ -0,0 +1,129 @@+"""Regression tests: /stop falls back to ANY running turn in the same chat when+the caller's exact session key (and thread-sibling keys) miss.++Two real shapes produce the miss (found via the Slack native stop button,+gateway-gateway#286 review):++- A turn triggered by a TOP-LEVEL channel message keys ``chat_type=channel``+ (with the relay's thread_id fallback), while a stop/`/stop` arriving from+ inside the reply thread normalizes to ``chat_type=thread`` — different key,+ same chat, and the run was invisible to /stop.+- Rolling-DM configs key the DM session WITHOUT a thread slot; a stop event+ carrying the thread keys a different session.++Semantics: "/stop" means "stop what's running in this chat". On an exact ++thread-sibling miss, an AUTHORIZED user's /stop interrupts the chat's running+turns; other chats are never touched.+"""++import pytest++from gateway.run import GatewayRunner+from gateway.session import SessionSource, build_session_key+from gateway.platforms.base import Platform+from gateway.platforms.event import MessageEvent, MessageType+++class _FakeAgent:+ pass+++class _StoreEntry:+ def __init__(self, session_key):+ self.session_key = session_key+++class _FakeStore:+ def __init__(self, session_key):+ self._key = session_key++ def get_or_create_session(self, source):+ return _StoreEntry(self._key)+++def _slack_source(chat_type, chat_id, thread_id=None, user_id="U-alice", scope_id="T1"):+ return SessionSource(+ platform=Platform.SLACK, chat_type=chat_type, chat_id=chat_id,+ thread_id=thread_id, user_id=user_id, scope_id=scope_id,+ )+++def _runner_with_run(running_key, own_key, authorized=True):+ runner = object.__new__(GatewayRunner)+ runner._running_agents = {running_key: _FakeAgent()}+ runner.session_store = _FakeStore(own_key)+ runner._is_user_authorized_for_source = lambda source, **kw: authorized+ interrupted = []++ async def _fake_interrupt(session_key, source, *, interrupt_reason, invalidation_reason):+ interrupted.append((session_key, invalidation_reason))++ runner._interrupt_and_clear_session = _fake_interrupt+ return runner, interrupted+++async def test_stop_from_thread_reaches_top_level_channel_run():+ # Running turn: triggered by a top-level channel message (relay stamps the+ # message's own ts as thread_id; chat_type slot stays "channel").+ running_key = build_session_key(_slack_source("channel", "C9", thread_id="170.100"))+ # The stop arrives from inside the reply thread → normalizes to "thread".+ stop_source = _slack_source("thread", "C9", thread_id="170.100")+ own_key = build_session_key(stop_source)+ assert own_key != running_key # the miss under test++ runner, interrupted = _runner_with_run(running_key, own_key)+ event = MessageEvent(text="/stop", message_type=MessageType.TEXT, source=stop_source)+ result = await runner._handle_stop_command(event)++ assert [k for k, _ in interrupted] == [running_key]+ assert "no active" not in str(getattr(result, "text", result)).lower()+++async def test_stop_with_thread_reaches_rolling_dm_run():+ # Rolling-DM config: the running session keys WITHOUT a thread slot.+ running_key = build_session_key(_slack_source("dm", "D1"))+ # The stop event carries the session thread → keys a different session.+ stop_source = _slack_source("dm", "D1", thread_id="170.100")+ own_key = build_session_key(stop_source)+ assert own_key != running_key++ runner, interrupted = _runner_with_run(running_key, own_key)+ event = MessageEvent(text="/stop", message_type=MessageType.TEXT, source=stop_source)+ result = await runner._handle_stop_command(event)++ assert [k for k, _ in interrupted] == [running_key]+ assert "no active" not in str(getattr(result, "text", result)).lower()+++async def test_chat_scope_fallback_is_authorization_gated():+ running_key = build_session_key(_slack_source("channel", "C9", thread_id="170.100"))+ stop_source = _slack_source("thread", "C9", thread_id="170.100")+ own_key = build_session_key(stop_source)++ runner, interrupted = _runner_with_run(running_key, own_key, authorized=False)+ # The no-active tail touches adapters; keep it inert for this harness.+ runner.adapters = {}+ event = MessageEvent(text="/stop", message_type=MessageType.TEXT, source=stop_source)+ result = await runner._handle_stop_command(event)++ assert interrupted == []+ assert "no active" in str(getattr(result, "text", result)).lower()+++async def test_chat_scope_fallback_never_crosses_chats():+ # A run in ANOTHER chat of the same workspace must stay invisible.+ running_key = build_session_key(_slack_source("channel", "C-other", thread_id="170.100"))+ stop_source = _slack_source("thread", "C9", thread_id="170.100")+ own_key = build_session_key(stop_source)++ runner, interrupted = _runner_with_run(running_key, own_key)+ runner.adapters = {}+ event = MessageEvent(text="/stop", message_type=MessageType.TEXT, source=stop_source)+ result = await runner._handle_stop_command(event)++ assert interrupted == []+ assert "no active" in str(getattr(result, "text", result)).lower()