The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): match the chat id as text so ids containing ':' survive
kshitijk4poorf9e47df22ec5
diff --git a/gateway/run_busy.py b/gateway/run_busy.pyindex 74a4b25a51a..b2e5b091ae7 100644--- a/gateway/run_busy.py+++ b/gateway/run_busy.py@@ -20,7 +20,7 @@ from gateway.config import Platformfrom gateway.platforms.base import EphemeralReplyfrom gateway.platforms.event import MessageEvent, MessageTypefrom gateway.session import SessionSource-from typing import Any, Dict, Optional, Union+from typing import Any, Dict, Optional, Tuple, Unionif TYPE_CHECKING: # string annotations only; never imported at runtime (cycle)from gateway.run import GatewayRunner # noqa: F401@@ -35,30 +35,35 @@ def _key_namespace(key: str) -> str:return ":".join(key.split(":")[:2])+def _tail_has_slot(tail: str, slot: str) -> bool:+ """True when ``tail``'s FIRST slot is ``slot`` (``tail`` is ``""`` when the key ends at the+ chat id). Mirrors ``build_session_key``'s ``key == prefix or key.startswith(prefix + ":")``+ discipline, so an id that merely starts with another never matches."""+ return tail == slot or tail.startswith(slot + ":")++def _same_chat_key_slots(key: str, *, namespace: str, platform: str, chat_id: str, scope_id: Optional[str],-) -> Optional[tuple]:- """``(chat_type, trailing_slots)`` when ``key`` names the SAME chat, else None.+) -> Optional[Tuple[str, str]]:+ """``(chat_type, tail)`` when ``key`` names the SAME chat, else None.Key layout: ``agent:<profile>:<platform>:<chat_type>[:<scope_id>][:<chat_id>][:<thread_id>][:<user>]``.- The namespace occupies the first two slots (``agent:main`` is byte-identical to every legacy- key). ``scope_id`` is Slack's workspace slot; it may be absent from either side (an older source- without the slot still names the same chat), but a key carrying a DIFFERENT known scope is- another workspace's chat.+ Only that fixed-shape head is split into slots (the namespace is always the first two); the chat+ id and everything after it are matched as TEXT, because ids may themselves contain ``:`` (Matrix+ ``!room:example.org``). ``scope_id`` is Slack's workspace slot — ``build_session_key`` emits it+ there alone — and it may be absent from either side, since a key without it still names the same+ chat; a key carrying a DIFFERENT known scope is another workspace's chat. ``tail`` is ``""`` when+ the key ends at the chat id."""- slots = key.split(":")- if len(slots) < 5 or ":".join(slots[:2]) != namespace or slots[2] != platform:+ head = key.split(":", 3)+ if len(head) < 4 or ":".join(head[:2]) != namespace or head[2] != platform:return None- rest = slots[3:]- if rest[1] == chat_id:- return rest[0], rest[2:]- # Only Slack ever carries the scope slot (``build_session_key``). Tolerating it on other- # platforms would let a group key's trailing participant id alias a chat_id: a Telegram DM- # keys ``chat_id`` as the USER id, so ``group:<chat>:<user>`` would read as "<user>'s chat".- if platform == Platform.SLACK.value and len(rest) >= 3 and rest[2] == chat_id:- if scope_id and rest[1] != str(scope_id):- return None- return rest[0], rest[3:]+ chat_type, _, rem = head[3].partition(":")+ for prefix in ((f"{scope_id}:{chat_id}", chat_id) if scope_id else (chat_id,)):+ if rem == prefix:+ return chat_type, ""+ if rem.startswith(prefix + ":"):+ return chat_type, rem[len(prefix) + 1:]return None@@ -1064,7 +1069,8 @@ class GatewayBusySessionMixin:return f"⛔ /{canonical_cmd} is admin-only here. {suffix}"def _same_chat_runs(self, source: SessionSource, own_key: str) -> list:- """``(key, chat_type, trailing_slots)`` for every OTHER running turn in the caller's chat.+ """``(key, chat_type, tail)`` for every OTHER running turn in the caller's chat (``tail`` is+ the key text after the chat id, ``""`` when the key ends there).The namespace comes from ``own_key`` — the session store's own answer, so a named-profilestop matches that profile's runs and never a literal. ``_snapshot_running_agents`` already@@ -1092,14 +1098,14 @@ class GatewayBusySessionMixin:"""Running-agent keys of OTHER participants in the caller's own thread (per-user thread modekeys are ``...:{thread_id}:{user_id}``, so another user's run is invisible to the caller'sown ``/stop``). Callers still gate on authz."""- thread_id = getattr(source, "thread_id", None)+ thread_id = str(getattr(source, "thread_id", None) or "")chat_type = getattr(source, "chat_type", None) or ""if not thread_id or not chat_type:return []return [keyfor key, key_chat_type, tail in self._same_chat_runs(source, own_key)- if key_chat_type == chat_type and tail[:1] == [str(thread_id)]+ if key_chat_type == chat_type and _tail_has_slot(tail, thread_id)]def _chat_scoped_run_keys(self, source: SessionSource, own_key: str) -> list:@@ -1121,7 +1127,7 @@ class GatewayBusySessionMixin:return [keyfor key, _key_chat_type, tail in self._same_chat_runs(source, own_key)- if not (thread_id and tail and tail[0] != thread_id)+ if not thread_id or not tail or _tail_has_slot(tail, thread_id)]def _is_stale_restart_redelivery(self, event: MessageEvent) -> bool:diff --git a/gateway/slash_commands.py b/gateway/slash_commands.pyindex bde84049176..23d02e6febc 100644--- a/gateway/slash_commands.py+++ b/gateway/slash_commands.py@@ -436,10 +436,9 @@ class GatewaySlashCommandsMixin(return EphemeralReply(t("gateway.stop.stopped"))# No run under the caller's own key: a live turn in THIS chat may still carry a differently- # shaped key. Narrowest tier first — another participant's run in the caller's own thread- # (per-user thread mode) — then any run in the chat (a top-level channel turn vs an in-thread- # /stop, a rolling-DM run that keys without the stop's thread slot, a peer's per-sender group- # run). Both tiers are authorization-gated; the helpers carry the isolation bounds.+ # shaped key. Narrowest tier first (another participant's run in the caller's own thread),+ # then any run in the chat; both are authorization-gated. See `_chat_scoped_run_keys` for the+ # shapes it covers and its isolation bounds.fallback_keys = self._sibling_thread_run_keys(source, session_key)reason = "stop_command_thread_sibling"if not fallback_keys:diff --git a/tests/gateway/test_stop_chat_scope.py b/tests/gateway/test_stop_chat_scope.pyindex 62bbee01b72..444f50779a6 100644--- a/tests/gateway/test_stop_chat_scope.py+++ b/tests/gateway/test_stop_chat_scope.py@@ -45,7 +45,10 @@ def _runner_with_run(running_keys, own_key, authorized=True):runner = object.__new__(GatewayRunner)if isinstance(running_keys, str):running_keys = [running_keys]- runner._running_agents = dict.fromkeys(running_keys, _FakeAgent())+ runner._running_agents = (+ dict(running_keys) if isinstance(running_keys, dict)+ else dict.fromkeys(running_keys, _FakeAgent())+ )runner.session_store = _FakeStore(own_key)runner._is_user_authorized_for_source = lambda source, **kw: authorizedrunner.adapters = {}@@ -59,12 +62,12 @@ def _runner_with_run(running_keys, own_key, authorized=True):async def _stop(source, running_keys, authorized=True):- """Drive one /stop through the real handler; return (own_key, interrupted, reply)."""+ """Drive one /stop through the real handler; return (interrupted, reply)."""own_key = build_session_key(source)runner, interrupted = _runner_with_run(running_keys, own_key, authorized=authorized)event = MessageEvent(text="/stop", message_type=MessageType.TEXT, source=source)result = await runner._handle_stop_command(event)- return own_key, interrupted, result+ return interrupted, result@pytest.mark.asyncio@@ -76,7 +79,7 @@ async def test_stop_from_thread_reaches_top_level_channel_run():stop_source = _slack_source("thread", "C9", thread_id="170.100")assert build_session_key(stop_source) != running_key # the miss under test- _, interrupted, result = await _stop(stop_source, running_key)+ interrupted, result = await _stop(stop_source, running_key)assert interrupted == [(running_key, "stop_command_chat_scope")]assert result == t("gateway.stop.stopped")@@ -90,7 +93,7 @@ async def test_stop_with_thread_reaches_rolling_dm_run():stop_source = _slack_source("dm", "D1", thread_id="170.100")assert build_session_key(stop_source) != running_key- _, interrupted, result = await _stop(stop_source, running_key)+ interrupted, result = await _stop(stop_source, running_key)assert interrupted == [(running_key, "stop_command_chat_scope")]assert result == t("gateway.stop.stopped")@@ -105,7 +108,7 @@ async def test_stop_reaches_peer_run_in_per_sender_group():stop_source = _slack_source("group", "C9", user_id="U-alice")assert build_session_key(stop_source) != running_key- _, interrupted, result = await _stop(stop_source, running_key)+ interrupted, result = await _stop(stop_source, running_key)assert interrupted == [(running_key, "stop_command_chat_scope")]assert result == t("gateway.stop.stopped")@@ -118,7 +121,7 @@ async def test_stop_does_not_reach_a_different_thread_of_the_same_channel():other_thread = build_session_key(_slack_source("thread", "C9", thread_id="170.200"))stop_source = _slack_source("thread", "C9", thread_id="170.100")- _, interrupted, result = await _stop(stop_source, other_thread)+ interrupted, result = await _stop(stop_source, other_thread)assert interrupted == []assert result == t("gateway.stop.no_active")@@ -132,7 +135,7 @@ async def test_stop_does_not_reach_another_reply_thread_of_a_channel_keyed_run()other_reply_thread = build_session_key(_slack_source("channel", "C9", thread_id="170.200"))stop_source = _slack_source("thread", "C9", thread_id="170.100")- _, interrupted, result = await _stop(stop_source, other_reply_thread)+ interrupted, result = await _stop(stop_source, other_reply_thread)assert interrupted == []assert result == t("gateway.stop.no_active")@@ -149,7 +152,7 @@ async def test_stop_in_a_dm_does_not_reach_a_group_run_that_ends_in_the_same_usedm_stop = SessionSource(platform=Platform.TELEGRAM, chat_type="dm", chat_id="777",user_id="777")- _, interrupted, result = await _stop(dm_stop, group_run)+ interrupted, result = await _stop(dm_stop, group_run)assert interrupted == []assert result == t("gateway.stop.no_active")@@ -160,7 +163,7 @@ 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")- _, interrupted, result = await _stop(stop_source, running_key, authorized=False)+ interrupted, result = await _stop(stop_source, running_key, authorized=False)assert interrupted == []assert result == t("gateway.stop.no_active")@@ -172,17 +175,30 @@ async def test_pending_sentinel_is_never_interrupted():pending = 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(pending, own_key)- runner._running_agents[pending] = _AGENT_PENDING_SENTINEL- event = MessageEvent(text="/stop", message_type=MessageType.TEXT, source=stop_source)-- result = await runner._handle_stop_command(event)+ interrupted, result = await _stop(stop_source, {pending: _AGENT_PENDING_SENTINEL})assert interrupted == []assert result == t("gateway.stop.no_active")+async def test_stop_reaches_a_chat_whose_id_contains_a_colon():+ # Matrix ids carry ":" (`!room:example.org`), so the chat id must be matched as text after+ # the fixed-shape head — slot-splitting the key would silently disable both fallbacks.+ room = SessionSource(platform=Platform.MATRIX, chat_type="channel", chat_id="!room:example.org",+ thread_id="$t1", user_id="@alice:example.org")+ running_key = build_session_key(room)+ stop_source = SessionSource(platform=Platform.MATRIX, chat_type="thread",+ chat_id="!room:example.org", thread_id="$t1",+ user_id="@alice:example.org")+ assert build_session_key(stop_source) != running_key++ interrupted, result = await _stop(stop_source, running_key)++ assert interrupted == [(running_key, "stop_command_chat_scope")]+ assert result == t("gateway.stop.stopped")++@pytest.mark.asyncio@pytest.mark.parametrize("other_chat_id", ["C-other", "C90"])async def test_chat_scope_fallback_interrupts_only_the_callers_chat(other_chat_id):@@ -192,12 +208,25 @@ async def test_chat_scope_fallback_interrupts_only_the_callers_chat(other_chat_iforeign = build_session_key(_slack_source("channel", other_chat_id, thread_id="170.100"))stop_source = _slack_source("thread", "C9", thread_id="170.100")- _, interrupted, result = await _stop(stop_source, [same_chat, foreign])+ interrupted, result = await _stop(stop_source, [same_chat, foreign])assert interrupted == [(same_chat, "stop_command_chat_scope")]assert result == t("gateway.stop.stopped")+async def test_chat_scope_fallback_does_not_fold_in_a_prefix_of_the_chat_id():+ # A chat id that merely STARTS with the caller's ("C9" vs "C90") is a different chat. The run+ # ends at its chat id, so only the id boundary separates the two — the tail case cannot show it.+ foreign = build_session_key(_slack_source("channel", "C90"))+ stop_source = _slack_source("channel", "C9")++ interrupted, result = await _stop(stop_source, foreign)++ assert interrupted == []+ assert result == t("gateway.stop.no_active")++@pytest.mark.asyncioasync def test_chat_scope_fallback_does_not_cross_workspace_scope_or_profile():# A same-chat run stays live beside the foreign ones, so a parser that matched NOTHING@@ -212,7 +241,7 @@ async def test_chat_scope_fallback_does_not_cross_workspace_scope_or_profile():]stop_source = _slack_source("thread", "C9", thread_id="170.100")- _, interrupted, result = await _stop(stop_source, running_keys)+ interrupted, result = await _stop(stop_source, running_keys)assert interrupted == [(same_chat, "stop_command_chat_scope")]assert result == t("gateway.stop.stopped")