AutoGPT is the vision of accessible AI for everyone, to use and to build on. Our mission is to provide the tools, so that you can focus on what matters.
fix(backend/copilot): a channel's approval button wakes its turn the way a web click does, so the gate judges it against the user's request (#15131)
Reinier van der Leerae3c67d7e6cf
diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py b/autogpt_platform/backend/backend/copilot/bot/adapters/base.pyindex 1b1e49bb9b..cfb35056eb 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/base.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/base.py@@ -18,6 +18,7 @@ from fastapi.responses import PlainTextResponsefrom pydantic import BaseModelfrom backend.copilot.bot.choices import QUESTION_KIND, ButtonKind+from backend.platform_linking.models import CardTurn# Callback signature: (ctx, adapter) -> awaitable NoneMessageCallback = Callable[["MessageContext", "PlatformAdapter"], Awaitable[None]]@@ -187,6 +188,8 @@ class MessageContext:# failed), as ``(filename, reason)`` pairs — surfaced to the user and the# model so neither thinks the file was read.skipped_attachments: tuple[tuple[str, str], ...] = ()+ # Set by a click that answered a card: carry the turn it woke, say nothing.+ follow: Optional[CardTurn] = None@propertydef is_dm(self) -> bool:diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/choice_ui.py b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/choice_ui.pyindex 765bcef1e8..cbf6acebc0 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/discord/choice_ui.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/discord/choice_ui.py@@ -128,7 +128,7 @@ class _ChoiceButton(str(interaction.user.id),_server_id(interaction),)- if answer.reply is None:+ if not answer.answered:await interaction.followup.send(answer.text, ephemeral=True)return# The token is already consumed, so the answer exists only in this@@ -138,8 +138,9 @@ class _ChoiceButton(await interaction.edit_original_response(content=answer.text, view=None)except discord.HTTPException:logger.exception("Failed to acknowledge choice click; continuing the turn")- ctx = _context_from_interaction(interaction, answer.reply)+ ctx = _context_from_interaction(interaction, answer.reply or "")if ctx is not None:+ ctx.follow = answer.followawait _on_message(ctx, _adapter)diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.pyindex ab899b93aa..fc99d241ae 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/slack/adapter.py@@ -273,7 +273,7 @@ class SlackAdapter(WebhookAdapter):# Keyed as the context keys it: a DM ("D…") bills to the user.None if channel_id.startswith("D") else team_id,)- if answer.reply is None:+ if not answer.answered:if client and channel_id:await client.chat_postEphemeral(channel=channel_id, user=clicker_id, text=answer.text@@ -302,8 +302,9 @@ class SlackAdapter(WebhookAdapter):)if self._on_message_callback is None:return- ctx = await self._context_from_block_action(payload, answer.reply)+ ctx = await self._context_from_block_action(payload, answer.reply or "")if ctx is not None:+ ctx.follow = answer.followawait self._on_message_callback(ctx, self)async def _context_from_block_action(diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter.pyindex 6a11dce32d..d724f3e3e9 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/teams/adapter.py@@ -255,7 +255,7 @@ class TeamsAdapter(WebhookAdapter):answer = await choices.answer_button(self._api, "teams", kind, token, index, ctx.user_id, ctx.server_id)- if answer.reply is None:+ if not answer.answered:await self._post(conversation_id, {"type": "message", "text": answer.text})return# The token is already consumed, so the answer exists only here. The@@ -276,7 +276,8 @@ class TeamsAdapter(WebhookAdapter):# from the activity yields False, and in a *channel* the turn is then# dropped by the handler's `if not ctx.bot_mentioned: return` — after# the ack above has already told the user their answer was accepted.- ctx.text = answer.reply+ ctx.text = answer.reply or ""+ ctx.follow = answer.followctx.bot_mentioned = Trueawait self._on_message_callback(ctx, self)diff --git a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter.py b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter.pyindex 0f8a6208ca..aadba54848 100644--- a/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter.py+++ b/autogpt_platform/backend/backend/copilot/bot/adapters/telegram/adapter.py@@ -207,7 +207,7 @@ class TelegramAdapter(WebhookAdapter):answer = await choices.answer_button(self._api, "telegram", kind, token, index, ctx.user_id, ctx.server_id)- if answer.reply is None:+ if not answer.answered:if query_id:await self._answer_callback_query(query_id, text=answer.text, show_alert=True@@ -233,7 +233,8 @@ class TelegramAdapter(WebhookAdapter):)if self._on_message_callback is None:return- ctx.text = answer.reply+ ctx.text = answer.reply or ""+ ctx.follow = answer.followawait self._on_message_callback(ctx, self)async def _answer_callback_query(self, query_id: str, **kwargs: Any) -> None:diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend.pyindex 74ecd4c59f..9eea3c74ed 100644--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend.py+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend.py@@ -9,13 +9,14 @@ discord/telegram/slack code never touches Pyro / Redis Streams plumbing.import asyncioimport jsonimport logging+import timefrom dataclasses import dataclassfrom datetime import datetimefrom typing import Any, AsyncGenerator, Awaitable, Callable, Optionalfrom pydantic import BaseModel-from backend.copilot import stream_registry+from backend.copilot import stream_registry, woken_turnsfrom backend.copilot.model import get_chat_sessionfrom backend.copilot.response_model import (StreamError,@@ -23,13 +24,16 @@ from backend.copilot.response_model import (StreamTextDelta,StreamToolOutputAvailable,)+from backend.data.redis_client import get_redis_asyncfrom backend.platform_linking.models import (MAX_BOT_MESSAGE_CHARS,BotChatRequest,BotEventInput,BotGuildInput,CardAnswer,+ CardTurn,ChannelCard,+ ChatTurnHandle,CreateLinkTokenRequest,CreateUserLinkTokenRequest,EnsureSessionResult,@@ -54,6 +58,14 @@ from .prompt import clamp_prompt# ``StreamFinish`` — without this, the bot would hang forever on ``queue.get()``.STREAM_CHUNK_TIMEOUT_SECONDS = 120+# A card answered mid-reply is woken by that turn's end, so a follow waits out+# any running turn, up to the life of a turn's stream.+_WAKE_POLL_SECONDS = 0.5+_WAKE_WAIT_SECONDS = 60 * 60+# Between a turn's end and the wake it starts, the chat briefly reads idle.+_WAKE_GRACE_SECONDS = 15+_FOLLOWED_KEY = "copilot-bot:followed-turn:"+logger = logging.getLogger(__name__)@@ -516,13 +528,50 @@ class BotBackend:raise ChatTurnDeniedError(handle.denial)if on_session_id:await on_session_id(handle.session_id)+ async for chunk in self.stream_turn(+ handle,+ on_setup_required=on_setup_required,+ on_setup_dropped=on_setup_dropped,+ on_clarification_needed=on_clarification_needed,+ on_approval_needed=on_approval_needed,+ ):+ yield chunk++ async def woken_turn(self, follow: CardTurn) -> ChatTurnHandle | None:+ """The turn a wake started to carry this card, once one has; None when+ no wake carries it, or another click already follows that turn."""+ started = time.monotonic()+ idle_since: float | None = None+ while time.monotonic() - started < _WAKE_WAIT_SECONDS:+ turn_id = await woken_turns.turn_for(follow.session_id, follow.review_id)+ if turn_id is not None:+ return await _claim(follow, turn_id)+ current = await stream_registry.get_session(follow.session_id)+ if current is not None and current.status == "running":+ idle_since = None+ elif idle_since is None:+ idle_since = time.monotonic()+ elif time.monotonic() - idle_since > _WAKE_GRACE_SECONDS:+ return None+ await asyncio.sleep(_WAKE_POLL_SECONDS)+ return None- queue = await stream_registry.subscribe_to_session(- session_id=handle.session_id,- user_id=handle.user_id,- last_message_id=handle.subscribe_from,- )- if queue is None:+ async def stream_turn(+ self,+ handle: ChatTurnHandle,+ on_setup_required: SetupRequiredCallback | None = None,+ on_setup_dropped: SetupDroppedCallback | None = None,+ on_clarification_needed: ClarificationNeededCallback | None = None,+ on_approval_needed: ApprovalNeededCallback | None = None,+ ) -> AsyncGenerator[str, None]:+ """Yield a running or finished turn's text deltas, from its start."""+ try:+ queue = await stream_registry.subscribe_to_turn(+ handle.session_id, handle.user_id, handle.turn_id, handle.subscribe_from+ )+ except (stream_registry.TurnStreamGone, stream_registry.TurnStreamTrimmed):+ # Trimmed: the turn ended before we subscribed and kept only its+ # tail from the last checkpoint, which holds none of its text.raise BotStreamError("subscribe_failed","failed to subscribe to response stream",@@ -625,6 +674,18 @@ class BotBackend:)+async def _claim(follow: CardTurn, turn_id: str) -> ChatTurnHandle | None:+ """Cards answered together wake one turn; the first click carries it."""+ redis = await get_redis_async()+ if not await redis.set(+ f"{_FOLLOWED_KEY}{turn_id}", "1", nx=True, ex=_WAKE_WAIT_SECONDS+ ):+ return None+ return ChatTurnHandle(+ session_id=follow.session_id, turn_id=turn_id, user_id=follow.user_id+ )++def _is_corrupted_setup_requirements(output: str | dict[str, Any]) -> bool:"""True when *output* names setup_requirements but doesn't parse as JSON.diff --git a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.pyindex 15b2cce824..28e3319d54 100644--- a/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/bot_backend_test.py@@ -8,6 +8,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytest+from backend.copilot import stream_registryfrom backend.copilot.response_model import (StreamError,StreamFinish,@@ -173,7 +174,7 @@ class TestStreamChat:with (patch(- "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_session",+ "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_turn",new=AsyncMock(return_value=queue),),patch(@@ -209,7 +210,7 @@ class TestStreamChat:with (patch(- "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_session",+ "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_turn",new=AsyncMock(return_value=queue),),patch(@@ -237,7 +238,7 @@ class TestStreamChat:with (patch(- "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_session",+ "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_turn",new=AsyncMock(return_value=queue),),patch(@@ -280,7 +281,7 @@ class TestStreamChat:with (patch(- "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_session",+ "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_turn",new=AsyncMock(return_value=queue),),patch(@@ -335,7 +336,7 @@ class TestStreamChat:with (patch(- "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_session",+ "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_turn",new=AsyncMock(return_value=queue),),patch(@@ -398,7 +399,7 @@ class TestStreamChat:with (patch(- "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_session",+ "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_turn",new=AsyncMock(return_value=queue),),patch(@@ -463,7 +464,7 @@ class TestStreamChat:with (patch(- "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_session",+ "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_turn",new=AsyncMock(return_value=queue),),patch(@@ -509,14 +510,20 @@ class TestStreamChat:pass@pytest.mark.asyncio- async def test_subscribe_returns_none_raises(self, api: BotBackend):+ @pytest.mark.parametrize(+ "unavailable",+ [stream_registry.TurnStreamGone(), stream_registry.TurnStreamTrimmed(None)],+ )+ async def test_a_turn_stream_gone_or_trimmed_raises(+ self, api: BotBackend, unavailable: Exception+ ):handle = ChatTurnHandle(session_id="sess", turn_id="turn", user_id="u1")api._client.start_chat_turn = AsyncMock(return_value=handle)with (patch(- "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_session",- new=AsyncMock(return_value=None),+ "backend.copilot.bot.bot_backend.stream_registry.subscribe_to_turn",+ new=AsyncMock(side_effect=unavailable),),patch("backend.copilot.bot.bot_backend.stream_registry.unsubscribe_from_session",diff --git a/autogpt_platform/backend/backend/copilot/bot/card_buttons_db_test.py b/autogpt_platform/backend/backend/copilot/bot/card_buttons_db_test.pyindex 67ca16f33c..c830eea07e 100644--- a/autogpt_platform/backend/backend/copilot/bot/card_buttons_db_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/card_buttons_db_test.py@@ -1,8 +1,8 @@"""Approval cards in a linked channel, clicked through each adapter against areal held row (Postgres + Redis).-A click answers the row and starts the channel's next turn, which is the turn-that runs the call. Who may click is ``cards.ANSWER_POLICY``: anyone in the+A click answers the row and wakes the chat's next turn, which runs the call;+the bot carries that turn's reply into the channel. Who may click is ``cards.ANSWER_POLICY``: anyone in theconversation, or only the linking owner. The card is opened from a member'smessage, so owner-only means the linking owner, not whoever was talking."""@@ -17,26 +17,36 @@ import pytestfrom prisma.enums import ReviewStatusfrom prisma.models import PendingHumanReview, PlatformLink+from backend.copilot import stream_registry+from backend.copilot.active_turns import acquire_turn_slot+from backend.copilot.bot import sessions as bot_sessionsfrom backend.copilot.bot.adapters.discord import choice_ui as discord_uifrom backend.copilot.bot.adapters.slack.adapter import SlackAdapterfrom backend.copilot.bot.adapters.teams.adapter import TeamsAdapterfrom backend.copilot.bot.adapters.telegram.adapter import TelegramAdapterfrom backend.copilot.bot.bot_backend import BotBackendfrom backend.copilot.bot.choices import CARD_KIND+from backend.copilot.bot.handler import MessageHandler+from backend.copilot.bot.text import format_batchfrom backend.copilot.gate import channel as gate_channelfrom backend.copilot.gate import chat_rules, check_action, held, resolve_mode+from backend.copilot.gate.classifier import Judgementfrom backend.copilot.gate.reads import read_review_id, screen_readfrom backend.copilot.model import (+ ChatMessage,ChatSession,+ append_and_save_message,get_chat_session,update_session_autopilot_mode,upsert_chat_session,)+from backend.copilot.response_model import StreamCheckpoint, StreamTextDeltafrom backend.copilot.tools.base import BaseToolfrom backend.copilot.tools.models import ResponseType, ToolResponseBasefrom backend.data.db_accessors import review_dbfrom backend.data.redis_client import get_redis_asyncfrom backend.platform_linking import cards+from backend.platform_linking import chat as bot_chatfrom backend.platform_linking.models import CardAnswer, ChannelCard, Platformfrom backend.util.exceptions import NotFoundError@@ -77,6 +87,79 @@ def _direct_api() -> BotBackend:return cast(BotBackend, api)+class _InProcessBot:+ """The bot's own handler and backend, with the linking manager in-process."""++ def __init__(self) -> None:+ client = MagicMock()+ client.resolve_server_link = AsyncMock(return_value=MagicMock(linked=True))+ client.answer_channel_card = AsyncMock(side_effect=cards.answer_card)+ client.start_chat_turn = AsyncMock(side_effect=bot_chat.start_chat_turn)+ self.api = BotBackend.__new__(BotBackend)+ self.api._client = client+ self.api._analytics_tasks = set()+ self.api.track_event = MagicMock()+ self.adapter = MagicMock()+ self.adapter.chunk_flush_at = 1900+ self.adapter.supports_stream_drafts = False+ for method in ("send_message", "send_reply", "start_typing", "stop_typing"):+ setattr(self.adapter, method, AsyncMock())+ self.handler = MessageHandler(self.api)+++class _Executor:+ """Runs a dispatched turn as the executor would, minus the model: the turn+ registers, says ``reply`` and ends. With ``then``, a turn the user starts+ from the web follows the instant it ends, and says that. ``live`` turns+ persist and checkpoint as the engines do, and run until ``finish``."""++ def __init__(self, reply: str, then: str | None = None, live: bool = False):+ self.reply = reply+ self.then = then+ self.live = live+ self.running: tuple[str, str] | None = None++ async def enqueue(self, **turn: Any) -> None:+ await self._finish(turn["session_id"], turn["turn_id"])++ async def dispatch(self, slot: Any, **turn: Any) -> None:+ await stream_registry.create_session(+ turn["session_id"], turn["user_id"], "chat_stream", "chat", turn["turn_id"]+ )+ if self.live:+ slot.keep()+ await stream_registry.publish_chunk(+ turn["turn_id"], StreamTextDelta(id="reply", delta=self.reply)+ )+ await stream_registry.publish_chunk(+ turn["turn_id"], StreamCheckpoint(rows=2, sequence=0, digest="")+ )+ self.running = (turn["session_id"], turn["turn_id"])+ return+ await self._finish(turn["session_id"], turn["turn_id"])+ if self.then is not None:+ web = str(uuid.uuid4())+ await stream_registry.create_session(+ turn["session_id"], turn["user_id"], "chat_stream", "chat", web+ )+ await self._finish(turn["session_id"], web, self.then)++ async def finish(self) -> None:+ """End the live turn; completion trims its stream to the checkpoint."""+ if self.running is not None:+ session_id, turn_id = self.running+ self.running = None+ await stream_registry.mark_session_completed(session_id, turn_id=turn_id)++ async def _finish(+ self, session_id: str, turn_id: str, reply: str | None = None+ ) -> None:+ await stream_registry.publish_chunk(+ turn_id, StreamTextDelta(id="reply", delta=reply or self.reply)+ )+ await stream_registry.mark_session_completed(session_id, turn_id=turn_id)++class _Channel:"""One platform's click, and what the platform was asked to show."""@@ -95,6 +178,7 @@ class _Channel:class _Discord(_Channel):platform, server_id = "discord", "222000000000000001"+ thread_id = 111owner, member = "900100000000000001", "900200000000000002"def __init__(self, api: BotBackend) -> None:@@ -107,7 +191,7 @@ class _Discord(_Channel):async def click(self, card: ChannelCard, clicker: str, index: int = 0) -> None:interaction = MagicMock()interaction.guild_id = int(self.server_id)- interaction.channel_id = 111+ interaction.channel_id = self.thread_idinteraction.channel = MagicMock(spec=discord.Thread)interaction.id = 555interaction.user = MagicMock(id=int(clicker), display_name="Someone")@@ -236,6 +320,15 @@ class _Teams(_Channel):_CHANNELS = [_Discord, _Slack, _Telegram, _Teams][email protected](autouse=True)+def dispatched():+ """An answer wakes its turn, which goes no further than dispatch unless a+ test sets ``side_effect``. The one patch of it: a second, torn down after+ this one, would leave every later test dispatching into a mock."""+ with patch("backend.copilot.executor.utils.dispatch_turn", AsyncMock()) as dispatch:+ yield dispatch++@pytest.fixturedef gate_on():with patch("backend.copilot.gate.is_feature_enabled", AsyncMock(return_value=True)):@@ -352,7 +445,7 @@ async def test_the_owners_approve_runs_the_call_in_the_channels_next_turn(assert "✅ Post a message · Approved" in linked.shown()linked.on_message.assert_awaited_once()ctx, _ = linked.on_message.await_args.args- assert ctx.text == held.WAKE_MESSAGE+ assert ctx.follow is not None and ctx.follow.session_id == session.session_idassert ctx.user_id == linked.owner# That turn folds the answered card in, and the call runs as it was held.[result] = await held.resolve_answered(test_user_id, session)@@ -444,7 +537,7 @@ async def test_a_double_click_answers_once(one_linked: _Channel, test_user_id, g)assert answer.await_count == 1- assert sorted(a.follow_up is not None for a in answers) == [False, True]+ assert sorted(a.follow is not None for a in answers) == [False, True]@pytest.mark.asyncio(loop_scope="session")@@ -464,8 +557,8 @@ async def test_a_failure_before_the_answer_lands_leaves_the_card_answerable(platform, one_linked.server_id, one_linked.owner, card.token, 0)- assert failed.follow_up is None and "Try again" in failed.text- assert retried.follow_up is not None+ assert failed.follow is None and "Try again" in failed.text+ assert retried.follow is not Noneassert await _status(review_id, test_user_id) == ReviewStatus.APPROVED@@ -486,7 +579,7 @@ async def test_a_rule_lost_after_the_answer_lands_still_starts_the_turn()lost.assert_awaited_once()- assert answer.follow_up is not None+ assert answer.follow is not Noneassert await _status(review_id, test_user_id) == ReviewStatus.APPROVED@@ -526,7 +619,7 @@ async def test_the_card_offers_the_web_cards_choices_and_each_sets_its_rule(past_the_card = await cards.answer_card(platform, one_linked.server_id, one_linked.owner, card.token, len(card.options))- assert past_the_card.follow_up is None+ assert past_the_card.follow is Noneassert await _status(review_id, test_user_id) == ReviewStatus.WAITINGawait cards.answer_card(@@ -666,3 +759,140 @@ async def test_a_linked_chat_runs_in_auto_whatever_mode_it_stored(# Unsupervised would run an outward post; Auto holds it for the owner.decision = await check_action(_POST, {"text": stored}, test_user_id, session)assert not decision.allowed and decision.review_id++[email protected](loop_scope="session")+async def test_a_channel_click_wakes_a_turn_judged_on_the_request_and_answered_here(+ one_linked: _Channel, test_user_id, gate_on, dispatched+):+ """Through the real bot: the turn the click starts reads the user's request+ as their last words, and its reply, streamed with entry ids and a+ checkpoint as the engines stream it, lands where the card was."""+ session, _, card = await _held_card(one_linked, test_user_id)+ request = format_batch(+ [("Someone", one_linked.owner, "Post hello, then pause my weekly report")],+ one_linked.platform,+ )+ await append_and_save_message(+ session.session_id, ChatMessage(role="user", content=request)+ )+ thread = str(_Discord.thread_id)+ await bot_sessions.set_session(one_linked.platform, thread, session.session_id)+ executor = _Executor("Posted it; pausing the report next.", live=True)+ dispatched.side_effect = executor.dispatch+ supervise = AsyncMock(return_value=Judgement(allowed=True, reason=""))+ subscribed = asyncio.Event()+ subscribe = stream_registry.subscribe_to_turn++ async def subscribe_and_tell(*args: Any) -> Any:+ queue = await subscribe(*args)+ subscribed.set()+ return queue++ with (+ patch.object(bot_chat, "enqueue_copilot_turn", executor.enqueue),+ patch("backend.copilot.gate.supervise", supervise),+ patch.object(stream_registry, "subscribe_to_turn", subscribe_and_tell),+ ):+ bot = _InProcessBot()+ discord_ui.register_choice_handler(+ MagicMock(), bot.adapter, bot.handler.handle, bot.api+ )+ click = asyncio.create_task(one_linked.click(card, one_linked.owner))+ try:+ await asyncio.wait_for(subscribed.wait(), timeout=30)+ finally:+ await executor.finish()+ await asyncio.wait_for(click, timeout=30)+ woken = await get_chat_session(session.session_id, test_user_id)+ assert woken is not None+ await check_action(+ "pause_schedule", {"schedule_id": "weekly"}, test_user_id, woken+ )++ assert supervise.await_args.kwargs["user_message"] == request+ said = [c.args[:2] for c in bot.adapter.send_message.await_args_list]+ assert said == [(thread, executor.reply)]++[email protected](loop_scope="session")+async def test_a_click_carries_the_turn_its_answer_woke_not_the_one_after_it(+ one_linked: _Channel, test_user_id, gate_on, dispatched+):+ """The user starts a web turn the moment the woken one ends: the channel+ gets the woken turn's reply, never the web one's."""+ session, _, card = await _held_card(one_linked, test_user_id)+ executor = _Executor("Posted it.", then="Here is your web answer.")++ bot = await _bot_following(one_linked, session, executor, dispatched)+ await one_linked.click(card, one_linked.owner)++ said = [c.args[1] for c in bot.adapter.send_message.await_args_list]+ assert said == ["Posted it."]++[email protected](loop_scope="session")+async def test_cards_answered_mid_reply_are_carried_once_when_that_turn_ends(+ one_linked: _Channel, test_user_id, gate_on, dispatched+):+ """Two clicks while a turn runs: neither answer can start a turn, so both+ wait for the one that turn's end wakes, which carries both, once."""+ session, _, first = await _held_card(one_linked, test_user_id)+ second = await _another_card(one_linked, test_user_id, session)+ running = str(uuid.uuid4())+ async with acquire_turn_slot(test_user_id, session.session_id) as slot:+ assert slot.admitted+ await stream_registry.create_session(+ session.session_id, test_user_id, "chat_stream", "chat", running+ )+ slot.keep()+ executor = _Executor("Posted both.")++ bot = await _bot_following(one_linked, session, executor, dispatched)+ clicks = [+ asyncio.create_task(one_linked.click(card, one_linked.owner))+ for card in (first, second)+ ]+ try:+ await asyncio.sleep(1)+ assert not any(click.done() for click in clicks)+ finally:+ # Left running, the turn holds one of the shared test user's slots.+ await stream_registry.mark_session_completed(+ session.session_id, turn_id=running+ )+ await asyncio.wait_for(asyncio.gather(*clicks), timeout=30)++ said = [c.args[1] for c in bot.adapter.send_message.await_args_list]+ assert said == ["Posted both."]+++async def _bot_following(+ channel: _Channel, session: ChatSession, executor: _Executor, dispatched+) -> _InProcessBot:+ """The real bot, wired to the channel's clicks and the session's thread,+ with ``executor`` running whatever turn a wake dispatches."""+ thread = str(_Discord.thread_id)+ await bot_sessions.set_session(channel.platform, thread, session.session_id)+ bot = _InProcessBot()+ discord_ui.register_choice_handler(+ MagicMock(), bot.adapter, bot.handler.handle, bot.api+ )+ dispatched.side_effect = executor.dispatch+ return bot+++async def _another_card(+ channel: _Channel, user_id: str, session: ChatSession+) -> ChannelCard:+ decision = await check_action(_POST, {"text": "again"}, user_id, session, "call-2")+ assert not decision.allowed and decision.review_id+ card = await cards.open_card(+ Platform(channel.platform.upper()),+ channel.server_id,+ channel.member,+ session.session_id,+ decision.review_id,+ )+ assert card is not None+ return carddiff --git a/autogpt_platform/backend/backend/copilot/bot/choices.py b/autogpt_platform/backend/backend/copilot/bot/choices.pyindex 2689fc26b8..c9eaf35d38 100644--- a/autogpt_platform/backend/backend/copilot/bot/choices.py+++ b/autogpt_platform/backend/backend/copilot/bot/choices.py@@ -26,6 +26,7 @@ from typing import TYPE_CHECKING, Literal, Optionalfrom pydantic import BaseModelfrom backend.data.redis_client import get_redis_async+from backend.platform_linking.models import CardTurnif TYPE_CHECKING:from .bot_backend import BotBackend@@ -68,13 +69,19 @@ class ResolvedChoice(BaseModel):class ButtonAnswer(BaseModel):"""A click on either kind of button.- ``reply`` is what the click says as the clicker's next message, or None- when it answered nothing. ``text`` replaces the buttons when it answered,- and is otherwise shown to the clicker alone.+ ``reply`` is what a question's click says as the clicker's next message;+ ``follow`` is the turn a card's click woke, which the bot carries here.+ ``text`` replaces the buttons when the click answered, and is otherwise+ shown to the clicker alone."""reply: Optional[str]text: str+ follow: Optional[CardTurn] = None++ @property+ def answered(self) -> bool:+ return self.reply is not None or self.follow is not Noneasync def answer_button(@@ -90,7 +97,7 @@ async def answer_button(try:if kind == CARD_KIND:card = await api.answer_card(platform, server_id, clicker_id, token, index)- return ButtonAnswer(reply=card.follow_up, text=card.text)+ return ButtonAnswer(reply=None, follow=card.follow, text=card.text)resolved = await resolve_choice(platform, token, index, clicker_id)except Exception:logger.exception(f"A {kind} click on {platform} could not be answered")diff --git a/autogpt_platform/backend/backend/copilot/bot/handler.py b/autogpt_platform/backend/backend/copilot/bot/handler.pyindex 0484fe2cbf..fb1250dd06 100644--- a/autogpt_platform/backend/backend/copilot/bot/handler.py+++ b/autogpt_platform/backend/backend/copilot/bot/handler.py@@ -11,7 +11,7 @@ import loggingfrom pydantic import BaseModel, Field-from backend.platform_linking.models import TurnDenial+from backend.platform_linking.models import CardTurn, ChatTurnHandle, TurnDenialfrom backend.util.exceptions import LinkAlreadyExistsErrorfrom . import sessions, threads@@ -52,6 +52,8 @@ class TargetState(BaseModel):# turn so it uses the same session (not a separate Redis read that could# diverge). None for text-only batches, which resolve the session normally.session_id: str | None = None+ # Turns woken by a card answered here, streamed before the next batch.+ follows: list[ChatTurnHandle] = Field(default_factory=list)class MessageHandler:@@ -65,6 +67,9 @@ class MessageHandler:self._session_locks: dict[str, asyncio.Lock] = {}async def handle(self, ctx: MessageContext, adapter: PlatformAdapter) -> None:+ if ctx.follow is not None:+ await self._follow(ctx, ctx.follow, adapter)+ return# Skipped attachments (too large / failed download) count as content:# the user sent something and must hear why nothing happened.has_content = bool(@@ -176,6 +181,28 @@ class MessageHandler:ctx, adapter, target_id, message_text, file_ids, session_id)+ async def _follow(+ self, ctx: MessageContext, follow: CardTurn, adapter: PlatformAdapter+ ) -> None:+ """A card answered here woke the turn that runs it; its reply belongs+ where the card was, after any reply already streaming there."""+ if not await self._ensure_linked(ctx, adapter):+ return+ try:+ turn = await self._api.woken_turn(follow)+ except Exception:+ # The answer stands and its turn runs; only the reply here is lost.+ logger.exception("Could not find the turn a card answer woke")+ return+ if turn is None:+ return+ target_id = await self._resolve_target(ctx, adapter)+ if not target_id:+ return+ state = self._targets.setdefault(target_id, TargetState())+ state.follows.append(turn)+ await self._process(ctx, adapter, target_id, state)+async def _report_skipped_only(self, ctx: MessageContext, adapter: PlatformAdapter) -> None:@@ -275,9 +302,16 @@ class MessageHandler:target_id: str,file_ids: list[str] | None = None,session_id: str | None = None,+ turn: ChatTurnHandle | None = None,) -> None:await self._streamer.stream_batch(- batch, ctx, adapter, target_id, file_ids=file_ids, session_id=session_id+ batch,+ ctx,+ adapter,+ target_id,+ file_ids=file_ids,+ session_id=session_id,+ turn=turn,)async def _enqueue_and_process(@@ -297,15 +331,27 @@ class MessageHandler:# resolved the same session (serialised by _session_lock), so keep it.if session_id and state.session_id is None:state.session_id = session_id+ await self._process(ctx, adapter, target_id, state)+ async def _process(+ self,+ ctx: MessageContext,+ adapter: PlatformAdapter,+ target_id: str,+ state: TargetState,+ ) -> None:if state.processing:# Another invocation is streaming for this target — it will pick- # up the message we just appended when its current stream ends.+ # up what we just queued when its current stream ends.returnstate.processing = Truetry:- while state.pending:+ while state.pending or state.follows:+ if state.follows:+ turn = state.follows.pop(0)+ await self._stream_batch([], ctx, adapter, target_id, turn=turn)+ continuebatch = list(state.pending)batch_file_ids = list(state.pending_file_ids)batch_session_id = state.session_id@@ -331,7 +377,7 @@ class MessageHandler:state.processing = False# Drop the empty state so the dict doesn't grow unbounded across# the bot's lifetime.- if not state.pending:+ if not state.pending and not state.follows:self._targets.pop(target_id, None)# -- Linking --diff --git a/autogpt_platform/backend/backend/copilot/bot/handler_test.py b/autogpt_platform/backend/backend/copilot/bot/handler_test.pyindex b3fd3a133f..f122aa3203 100644--- a/autogpt_platform/backend/backend/copilot/bot/handler_test.py+++ b/autogpt_platform/backend/backend/copilot/bot/handler_test.py@@ -7,6 +7,7 @@ from unittest.mock import AsyncMock, MagicMock, patchimport pytestfrom backend.platform_linking.models import (+ ChatTurnHandle,EnsureSessionResult,TurnDenial,WorkspaceArtifact,@@ -539,6 +540,25 @@ class TestBatching:]assert "target-1" not in handler._targets+ @pytest.mark.asyncio+ async def test_a_turn_a_card_woke_mid_reply_streams_after_that_reply(self):+ handler = MessageHandler(_api())+ state = TargetState()+ handler._targets["target-1"] = state+ woken = ChatTurnHandle(session_id="s", turn_id="woken", user_id="u")+ streamed: list[tuple[list, ChatTurnHandle | None]] = []++ async def fake_stream_batch(batch, ctx, ad, tid, turn=None, **_):+ streamed.append((list(batch), turn))+ if len(streamed) == 1:+ state.follows.append(woken)++ handler._stream_batch = fake_stream_batch # type: ignore[method-assign]+ await handler._enqueue_and_process(_ctx(text="first"), _adapter(), "target-1")++ assert streamed == [([("Bently", "user-1", "first")], None), ([], woken)]+ assert "target-1" not in handler._targets+@pytest.mark.asyncioasync def test_duplicate_message_is_silently_dropped(self):api = _api()diff --git a/autogpt_platform/backend/backend/copilot/bot/turn_stream.py b/autogpt_platform/backend/backend/copilot/bot/turn_stream.pyindex 664ed9ede2..df294fd8c5 100644--- a/autogpt_platform/backend/backend/copilot/bot/turn_stream.py+++ b/autogpt_platform/backend/backend/copilot/bot/turn_stream.py@@ -20,7 +20,7 @@ from backend.data.sharing.workspace_refs import (WorkspaceArtifactLink,extract_artifact_links,)-from backend.platform_linking.models import TurnDenial+from backend.platform_linking.models import ChatTurnHandle, TurnDenialfrom backend.util.exceptions import DuplicateChatMessageError, NotFoundErrorfrom backend.util.settings import Settings@@ -145,8 +145,10 @@ class TurnStreamer:target_id: str,file_ids: list[str] | None = None,session_id: str | None = None,+ turn: ChatTurnHandle | None = None,) -> None:- prefixed = format_batch(batch, ctx.platform)+ """Start a turn from ``batch`` and stream its reply here; with+ ``turn``, stream that one instead, which something else started."""redis = await get_redis_async()cache_key = sessions.session_cache_key(ctx.platform, target_id)@@ -280,19 +282,30 @@ class TurnStreamer:draft = DraftStreamer(adapter, target_id)typing_task = asyncio.create_task(_keep_typing(adapter, target_id))try:- async for chunk in self._api.stream_chat(- platform=ctx.platform,- platform_user_id=ctx.user_id,- message=prefixed,- session_id=active_session_id,- platform_server_id=ctx.server_id,- file_ids=file_ids,- on_session_id=_on_session_id,- on_setup_required=_on_setup_required,- on_setup_dropped=_on_setup_dropped,- on_clarification_needed=_on_clarification_needed,- on_approval_needed=_on_approval_needed,- ):+ if turn is not None:+ await _on_session_id(turn.session_id)+ chunks = self._api.stream_turn(+ turn,+ on_setup_required=_on_setup_required,+ on_setup_dropped=_on_setup_dropped,+ on_clarification_needed=_on_clarification_needed,+ on_approval_needed=_on_approval_needed,+ )+ else:+ chunks = self._api.stream_chat(+ platform=ctx.platform,+ platform_user_id=ctx.user_id,+ message=format_batch(batch, ctx.platform),+ session_id=active_session_id,+ platform_server_id=ctx.server_id,+ file_ids=file_ids,+ on_session_id=_on_session_id,+ on_setup_required=_on_setup_required,+ on_setup_dropped=_on_setup_dropped,+ on_clarification_needed=_on_clarification_needed,+ on_approval_needed=_on_approval_needed,+ )+ async for chunk in chunks:buffer += chunkreply_chars += len(chunk)await draft.update(buffer)diff --git a/autogpt_platform/backend/backend/copilot/gate/channel.py b/autogpt_platform/backend/backend/copilot/gate/channel.pyindex 3fc2b67b1e..58a4ea3f3d 100644--- a/autogpt_platform/backend/backend/copilot/gate/channel.py+++ b/autogpt_platform/backend/backend/copilot/gate/channel.py@@ -78,8 +78,8 @@ def card_for(row: PendingHumanReviewModel) -> CardView:async def answer(user_id: str, session_id: str, review_id: str, choice: Choice) -> Outcome:- """Answer the row as the web card's approve endpoint does, minus the wake:- the channel's own next turn carries the result, so its reply lands there."""+ """Answer the row as the web card's approve endpoint does, waking the turn+ that runs it."""approved, rule = _ANSWERS[choice]# Up to the commit a failure leaves the card answerable; after it, the# answer stands and only its rule can be lost.@@ -114,6 +114,7 @@ async def answer()except Exception:logger.warning(f"Rule from {review_id} not saved", exc_info=True)+ await held.wake(user_id, session_id, answered.values())return "answered"diff --git a/autogpt_platform/backend/backend/copilot/gate/held.py b/autogpt_platform/backend/backend/copilot/gate/held.pyindex ab24b71df8..bbfa611fc9 100644--- a/autogpt_platform/backend/backend/copilot/gate/held.py+++ b/autogpt_platform/backend/backend/copilot/gate/held.py@@ -18,6 +18,7 @@ from typing import TYPE_CHECKING, Any, Callable, Iterable, Literalfrom prisma.enums import ReviewStatusfrom pydantic import BaseModel, Field, ValidationError+from backend.copilot import woken_turnsfrom backend.copilot.constants import COPILOT_NODE_EXEC_ID_SEPARATORfrom backend.copilot.model import ChatSessionfrom backend.copilot.pending_messages import PendingMessage@@ -246,11 +247,12 @@ async def wake(is None):return+ turn_id = str(uuid.uuid4())await dispatch_turn(slot,session_id=session_id,user_id=user_id,- turn_id=str(uuid.uuid4()),+ turn_id=turn_id,message=WAKE_MESSAGE,organization_id=info.organization_id,team_id=info.team_id,@@ -259,6 +261,10 @@ async def wake(permissions=permissions,message_metadata=metadata,)+ # A channel that answered one of these follows this turn.+ await woken_turns.record(+ session_id, [c.review_id for c in calls], turn_id+ )except ConcurrentTurnLimitError:await try_enqueue_turn(user_id=user_id,diff --git a/autogpt_platform/backend/backend/copilot/woken_turns.py b/autogpt_platform/backend/backend/copilot/woken_turns.pynew file mode 100644index 0000000000..d369201c37--- /dev/null+++ b/autogpt_platform/backend/backend/copilot/woken_turns.py@@ -0,0 +1,35 @@+"""Which turn a wake started to carry an answered card, so a channel that+answered the card can stream that turn's reply and no other."""++import logging+from typing import Iterable++from backend.data.redis_client import get_redis_async++logger = logging.getLogger(__name__)++# Read moments after the wake, or once the turn that was running ends.+_TTL_SECONDS = 60 * 60+_KEY = "copilot:woken-turn:"+++async def record(session_id: str, review_ids: Iterable[str], turn_id: str) -> None:+ """Best effort: the turn runs either way; only a channel's reply is lost."""+ try:+ redis = await get_redis_async()+ async with redis.pipeline(transaction=True) as pipe:+ pipe.hset(_key(session_id), mapping={r: turn_id for r in review_ids})+ pipe.expire(_key(session_id), _TTL_SECONDS)+ await pipe.execute()+ except Exception:+ logger.warning(f"Woken turn {turn_id} not recorded", exc_info=True)+++async def turn_for(session_id: str, review_id: str) -> str | None:+ redis = await get_redis_async()+ turn_id = await redis.hget(_key(session_id), review_id)+ return turn_id.decode() if isinstance(turn_id, bytes) else turn_id+++def _key(session_id: str) -> str:+ return f"{_KEY}{session_id}"diff --git a/autogpt_platform/backend/backend/platform_linking/cards.py b/autogpt_platform/backend/backend/platform_linking/cards.pyindex 7b4e27e248..71b915b76a 100644--- a/autogpt_platform/backend/backend/platform_linking/cards.py+++ b/autogpt_platform/backend/backend/platform_linking/cards.py@@ -14,13 +14,12 @@ from prisma.enums import ReviewStatusfrom pydantic import BaseModelfrom backend.copilot.gate import channel-from backend.copilot.gate.held import WAKE_MESSAGEfrom backend.copilot.gate.review import GATE_NODE_PREFIXfrom backend.data.db_accessors import platform_linking_db, review_dbfrom backend.data.redis_client import get_redis_asyncfrom .chat import resolve_owner-from .models import CardAnswer, ChannelCard, Platform+from .models import CardAnswer, CardTurn, ChannelCard, PlatformAnswerPolicy = Literal["linking_owner", "any_member"]# Toran, 2026-09-30: anyone who can message the bot can already make it do@@ -99,7 +98,8 @@ async def answer_card("""Answer the row a button names, if the clicker may.A read first, so a click the policy refuses changes nothing; then GETDEL,- so the answerer's own double-click answers once.+ so the answerer's own double-click answers once. The answer wakes the+ chat's next turn, which the bot carries into the channel."""redis = await get_redis_async()raw = await redis.get(_key(token))@@ -125,7 +125,14 @@ async def answer_card(return CardAnswer(text=_EXPIRED)if outcome == "answered_elsewhere":return CardAnswer(text=_ANSWERED)- return CardAnswer(text=option.receipt, follow_up=WAKE_MESSAGE)+ return CardAnswer(+ text=option.receipt,+ follow=CardTurn(+ session_id=card.session_id,+ user_id=card.user_id,+ review_id=card.review_id,+ ),+ )def may_answer(card: PostedCard, clicker_id: str, server_id: str | None) -> bool:diff --git a/autogpt_platform/backend/backend/platform_linking/models.py b/autogpt_platform/backend/backend/platform_linking/models.pyindex 2512f80346..b26b17594c 100644--- a/autogpt_platform/backend/backend/platform_linking/models.py+++ b/autogpt_platform/backend/backend/platform_linking/models.py@@ -318,13 +318,22 @@ class ChannelCard(BaseModel):class CardAnswer(BaseModel):"""What a click on a card's button did.- ``follow_up`` is set only when the click answered the row: it is the- clicker's next message, whose turn carries the result. ``text`` then- replaces the buttons; otherwise only the clicker is shown it.+ ``follow`` is set only when the click answered the row: the answer woke+ the turn that carries the result, for the bot to stream where the card+ was. ``text`` then replaces the buttons; otherwise only the clicker is+ shown it."""text: str- follow_up: str | None = None+ follow: "CardTurn | None" = None+++class CardTurn(BaseModel):+ """The card a click answered, whose wake the bot carries into the channel."""++ session_id: str+ user_id: str+ review_id: strclass ChatSessionSummary(BaseModel):