Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions gateway/platforms/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -1850,6 +1850,17 @@ def __init__(self, config: PlatformConfig, platform: Platform):
self._active_sessions: Dict[str, asyncio.Event] = {}
self._pending_messages: Dict[str, MessageEvent] = {}
self._session_tasks: Dict[str, asyncio.Task] = {}
# Channel turn-coalescing index: "chat_id\x1fuser_id" -> the session_key
# of that user's in-flight *top-level* group/channel turn. Lets a rapid
# same-user top-level follow-up join the active turn (routed through the
# normal busy handler so it queues/cascades — or interrupts only a cheap
# turn) instead of racing it in its own per-message session. Only used
# when each top-level message gets its own session (reply_in_thread=true,
# the default); under reply_in_thread=false the sessions already share a
# key and this no-ops. Synced with _active_sessions by
# _start_session_processing / _release_session_guard /
# _heal_stale_session_lock.
self._active_topfollow: Dict[str, str] = {}
# Legacy busy_text_mode env var; when unset the runner syncs the
# resolved value (driven by busy_input_mode) onto the adapter after
# construction (gateway/run.py). Default to "interrupt" so a stray
Expand Down Expand Up @@ -3653,6 +3664,37 @@ def _release_session_guard(
if guard is not None and current_guard is not guard:
return
del self._active_sessions[session_key]
self._drop_topfollow_for(session_key)

def _topfollow_key(self, event: MessageEvent) -> Optional[str]:
"""Composite ``chat_id\\x1fuser_id`` key for channel turn-coalescing.

Returns a key only for a *top-level* group/channel message that carries
a participant id — the case where the platform mints a fresh per-message
session (Slack with ``reply_in_thread=true`` falls back to
``thread_ts = ts``), so rapid same-user follow-ups would otherwise race
the in-flight turn in their own sessions. Returns None for DMs, thread
replies, and messages with no user id (their session keys already
coalesce correctly), which leaves every other platform/route untouched.
"""
src = getattr(event, "source", None)
if src is None or src.chat_type not in ("group", "channel"):
return None
user = src.user_id or src.user_id_alt
if not user or not src.chat_id:
return None
# Top-level when there is no thread anchor, or the anchor is the
# message's own id (the per-message session fallback). A genuine thread
# reply (anchor points at an earlier parent) is left alone.
thread_id = src.thread_id
if thread_id and event.message_id and thread_id != event.message_id:
return None
return f"{src.chat_id}\x1f{user}"

def _drop_topfollow_for(self, session_key: str) -> None:
"""Remove any channel-coalescing index entry pointing at ``session_key``."""
for k in [k for k, v in self._active_topfollow.items() if v == session_key]:
self._active_topfollow.pop(k, None)

def _session_task_is_stale(self, session_key: str) -> bool:
"""Return True if the owner task for ``session_key`` is done/cancelled.
Expand Down Expand Up @@ -3695,6 +3737,7 @@ def _heal_stale_session_lock(self, session_key: str) -> bool:
self._active_sessions.pop(session_key, None)
self._pending_messages.pop(session_key, None)
self._session_tasks.pop(session_key, None)
self._drop_topfollow_for(session_key)
self._discard_text_debounce(session_key)
return True

Expand Down Expand Up @@ -3728,6 +3771,9 @@ def _start_session_processing(
if hasattr(task, "add_done_callback"):
task.add_done_callback(self._background_tasks.discard)
task.add_done_callback(self._expected_cancelled_tasks.discard)
_tf = self._topfollow_key(event)
if _tf is not None:
self._active_topfollow[_tf] = session_key
return True

async def cancel_session_processing(
Expand Down Expand Up @@ -3908,6 +3954,33 @@ async def handle_message(self, event: MessageEvent) -> None:
if session_key in self._active_sessions:
self._heal_stale_session_lock(session_key)

# Channel turn coalescing: a top-level group/channel message whose own
# per-message session is idle, but whose author already has an in-flight
# top-level turn in this chat, joins that turn rather than racing it in a
# separate concurrent session. Rebinding to the active session_key routes
# the message through the busy handler below — so it queues/cascades
# after the active turn (and the runner's #30170 demotion keeps a running
# delegation from being interrupted), instead of answering a question the
# in-flight turn is about to make moot. Same user only (per-user session
# isolation); thread replies and other users are untouched, and under
# reply_in_thread=false the keys already match so this never fires.
if session_key not in self._active_sessions:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This rebind runs before the command bypass at line 3999 and the clarify interception below it. A top-level same-user /stop, /new, /approve, or clarify response is therefore treated as belonging to the sibling active session. Exempt those paths before rebinding and add regressions.

_tf = self._topfollow_key(event)
if _tf is not None:
_sibling = self._active_topfollow.get(_tf)
if (
_sibling
and _sibling != session_key
and _sibling in self._active_sessions
and not self._session_task_is_stale(_sibling)
):
logger.debug(
"[%s] Coalescing top-level follow-up into active "
"session %s (own key %s)",
self.name, _sibling, session_key,
)
session_key = _sibling

# Check if there's already an active handler for this session
if session_key in self._active_sessions:
# Certain commands must bypass the active-session guard and be
Expand Down
23 changes: 22 additions & 1 deletion gateway/platforms/slack.py
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,10 @@ def __init__(self, config: PlatformConfig):
# Track active assistant thread status indicators so stop_typing can
# clear them (chat_id → thread_ts).
self._active_status_threads: Dict[str, str] = {}
# Heartbeat: monotonic start time of the current status indicator per
# chat, so a long-running turn surfaces elapsed time ("still working…
# (2m03s)") instead of a static "is thinking..." that reads as stuck.
self._status_started: Dict[str, float] = {}
# Slash-command contexts: stash response_url + user_id so send()
# can route the first reply ephemerally. Keyed by
# (channel_id, user_id) to avoid cross-user collisions.
Expand Down Expand Up @@ -1290,11 +1294,27 @@ async def send_typing(self, chat_id: str, metadata=None) -> None:
return # Can only set status in a thread context

self._active_status_threads[chat_id] = thread_ts
# Heartbeat: _keep_typing refreshes this on an interval, so deriving the
# label from elapsed time turns the static "is thinking..." into visible
# progress for a long turn (e.g. a multi-minute delegation). A turn that
# visibly advances doesn't provoke a mid-turn "you there?" — which would
# otherwise race the in-flight answer in its own session.
started = self._status_started.get(chat_id)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This timer is keyed only by chat_id, but different users' top-level channel turns are intentionally still concurrent. Their status refreshes can share elapsed time, and either stop_typing(chat_id) clears the shared state. Key status/timing by (chat_id, thread_ts) and test concurrent threads.

if started is None:
started = time.monotonic()
self._status_started[chat_id] = started
elapsed = int(time.monotonic() - started)
if elapsed >= 30:
mins, secs = divmod(elapsed, 60)
human = f"{mins}m{secs:02d}s" if mins else f"{secs}s"
status = f"still working… ({human})"
else:
status = "is thinking..."
try:
await self._get_client(chat_id).assistant_threads_setStatus(
channel_id=chat_id,
thread_ts=thread_ts,
status="is thinking...",
status=status,
)
except Exception as e:
# Silently ignore — may lack assistant:write scope or not be
Expand All @@ -1306,6 +1326,7 @@ async def stop_typing(self, chat_id: str, metadata=None) -> None:
if not self._app:
return
thread_ts = self._active_status_threads.pop(chat_id, None)
self._status_started.pop(chat_id, None)
if not thread_ts:
return
try:
Expand Down
217 changes: 217 additions & 0 deletions tests/gateway/test_channel_turn_coalescing.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,217 @@
"""Tests for channel turn-coalescing.

A platform that mints a fresh per-message session for each top-level channel
message (Slack with ``reply_in_thread=true`` — the default — falls back to
``thread_ts = ts``) would otherwise let a rapid same-user follow-up race the
in-flight turn in its own session — the classic "agent answers a now-stale
question right after the real answer lands" bug. The coalescing index reattaches
such a follow-up to the author's active top-level turn so it is routed through
the normal busy handler (queue/cascade, or interrupt only a cheap turn).

Same-user / same-chat only: thread replies, other users, and DMs are untouched,
and under ``reply_in_thread=false`` the sessions already share a key so this
never fires.
"""

from __future__ import annotations

import asyncio
import sys
import types
from unittest.mock import AsyncMock, MagicMock

import pytest

# Minimal telegram stub so importing gateway.platforms.base does not pull in the
# real python-telegram-bot dependency (mirrors test_active_session_text_merge).
_tg = sys.modules.get("telegram") or types.ModuleType("telegram")
_tg.constants = sys.modules.get("telegram.constants") or types.ModuleType("telegram.constants")
_ct = MagicMock()
_ct.PRIVATE = "private"
_ct.GROUP = "group"
_ct.SUPERGROUP = "supergroup"
_tg.constants.ChatType = _ct
sys.modules.setdefault("telegram", _tg)
sys.modules.setdefault("telegram.constants", _tg.constants)
sys.modules.setdefault("telegram.ext", types.ModuleType("telegram.ext"))

from gateway.config import Platform, PlatformConfig
from gateway.platforms.base import (
BasePlatformAdapter,
MessageEvent,
MessageType,
SendResult,
)
from gateway.session import SessionSource, build_session_key


def _make_event(
text: str,
*,
chat_id: str = "C1",
chat_type: str = "channel",
user_id: str = "u1",
ts: str | None = None,
thread_id: str | None = "__own__",
) -> MessageEvent:
"""Build an event. ``thread_id="__own__"`` mimics Slack's per-message
top-level session (``thread_ts = ts``); pass an explicit value for a reply."""
message_id = ts or f"ts-{text[:8]}"
resolved_thread = message_id if thread_id == "__own__" else thread_id
source = SessionSource(
platform=Platform.SLACK,
chat_id=chat_id,
chat_type=chat_type,
user_id=user_id,
thread_id=resolved_thread,
)
return MessageEvent(
text=text,
message_type=MessageType.TEXT,
source=source,
message_id=message_id,
)


class _DummyAdapter(BasePlatformAdapter): # type: ignore[misc]
async def connect(self):
pass

async def disconnect(self):
pass

async def get_chat_info(self, chat_id):
return None

async def send(self, *args, **kwargs):
return SendResult(success=True, message_id="x")


def _make_adapter() -> BasePlatformAdapter:
adapter = object.__new__(_DummyAdapter)
adapter.config = PlatformConfig(enabled=True, token="***")
adapter.platform = Platform.SLACK
adapter._message_handler = AsyncMock(return_value=None)
adapter._busy_session_handler = None
adapter._active_sessions = {}
adapter._pending_messages = {}
adapter._session_tasks = {}
adapter._active_topfollow = {}
adapter._background_tasks = set()
adapter._post_delivery_callbacks = {}
adapter._expected_cancelled_tasks = set()
adapter._fatal_error_code = None
adapter._fatal_error_message = None
adapter._fatal_error_retryable = True
adapter._fatal_error_handler = None
adapter._running = True
adapter._busy_text_mode = "" # direct-merge, no debounce
adapter._busy_text_debounce_seconds = 0.1
adapter._busy_text_hard_cap_seconds = 1.0
adapter._text_debounce = {}
adapter._auto_tts_default = False
adapter._auto_tts_enabled_chats = set()
adapter._auto_tts_disabled_chats = set()
adapter._typing_paused = set()
return adapter


# ---- _topfollow_key ---------------------------------------------------------

def test_topfollow_key_for_top_level_channel():
adapter = _make_adapter()
ev = _make_event("hi", ts="ts1")
assert adapter._topfollow_key(ev) == "C1\x1fu1"


def test_topfollow_key_none_for_dm():
adapter = _make_adapter()
assert adapter._topfollow_key(_make_event("hi", chat_type="dm")) is None


def test_topfollow_key_none_for_thread_reply():
adapter = _make_adapter()
# Anchor points at an earlier parent (!= this message's id) → real reply.
ev = _make_event("hi", ts="ts2", thread_id="parent-ts")
assert adapter._topfollow_key(ev) is None


def test_topfollow_key_none_without_user():
adapter = _make_adapter()
ev = _make_event("hi", ts="ts1")
ev.source.user_id = None
assert adapter._topfollow_key(ev) is None


# ---- coalescing in handle_message -------------------------------------------

@pytest.mark.asyncio
async def test_same_user_top_level_followup_coalesces_into_active_turn():
adapter = _make_adapter()
first = _make_event("which pipeline?", ts="ts1")
active_key = build_session_key(first.source)
# Simulate the first turn being in flight, registered in both structures.
adapter._active_sessions[active_key] = asyncio.Event()
adapter._active_topfollow["C1\x1fu1"] = active_key

followup = _make_event("you there?", ts="ts2") # new top-level → new key
assert build_session_key(followup.source) != active_key

await adapter.handle_message(followup)

# No second concurrent session was started; it queued behind the active one.
assert set(adapter._active_sessions) == {active_key}
assert adapter._pending_messages[active_key].text == "you there?"


@pytest.mark.asyncio
async def test_other_user_top_level_does_not_coalesce():
adapter = _make_adapter()
first = _make_event("which pipeline?", ts="ts1", user_id="u1")
active_key = build_session_key(first.source)
adapter._active_sessions[active_key] = asyncio.Event()
adapter._active_topfollow["C1\x1fu1"] = active_key

other = _make_event("status?", ts="ts9", user_id="u2")
await adapter.handle_message(other)

# Different user → not folded into u1's turn; u1's pending stays empty.
assert active_key not in adapter._pending_messages


@pytest.mark.asyncio
async def test_thread_reply_does_not_coalesce():
adapter = _make_adapter()
first = _make_event("which pipeline?", ts="ts1")
active_key = build_session_key(first.source)
adapter._active_sessions[active_key] = asyncio.Event()
adapter._active_topfollow["C1\x1fu1"] = active_key

reply = _make_event("reply in old thread", ts="ts2", thread_id="old-parent")
await adapter.handle_message(reply)

assert active_key not in adapter._pending_messages


# ---- index lifecycle --------------------------------------------------------

def test_release_session_guard_clears_topfollow_index():
adapter = _make_adapter()
adapter._active_sessions["k"] = asyncio.Event()
adapter._active_topfollow["C1\x1fu1"] = "k"
adapter._release_session_guard("k")
assert adapter._active_topfollow == {}


def test_heal_stale_lock_clears_topfollow_index():
adapter = _make_adapter()
adapter._active_sessions["k"] = asyncio.Event()
adapter._active_topfollow["C1\x1fu1"] = "k"

class _DoneTask:
def done(self):
return True

adapter._session_tasks["k"] = _DoneTask()
assert adapter._heal_stale_session_lock("k") is True
assert adapter._active_topfollow == {}