From be70e6b7cdb679a961ee45a8c01ecb93865e8320 Mon Sep 17 00:00:00 2001 From: Corina <14900841+corinagum@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:43:45 -0800 Subject: [PATCH 1/5] Post Plan completion to the reply chain in 1:1 threads Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- examples/plan/README.md | 2 +- .../apps/src/microsoft_teams/apps/__init__.py | 3 +- .../apps/src/microsoft_teams/apps/plan.py | 50 ++++++++++++++--- packages/apps/tests/test_plan.py | 54 ++++++++++++++++++- 4 files changed, 100 insertions(+), 9 deletions(-) diff --git a/examples/plan/README.md b/examples/plan/README.md index 222a7fd5..613e3434 100644 --- a/examples/plan/README.md +++ b/examples/plan/README.md @@ -14,7 +14,7 @@ Each step includes a description that changes as it progresses through the demo. - Send `proactive` to manage a Plan proactively. `PlanOptions` requires `conversation_id`, `reply_to_id`, and `api_client`, but -`Plan.model_dump()` serializes only the two IDs. Store those IDs and supply the configured API client when rebuilding `PlanOptions`. +`Plan.model_dump()` serializes the two IDs and, in a chat thread, the `reply_chain` binding that places the completion. Store that data and supply the configured API client when rebuilding `PlanOptions`. The delays stand in for longer-running work. diff --git a/packages/apps/src/microsoft_teams/apps/__init__.py b/packages/apps/src/microsoft_teams/apps/__init__.py index 25130127..10245424 100644 --- a/packages/apps/src/microsoft_teams/apps/__init__.py +++ b/packages/apps/src/microsoft_teams/apps/__init__.py @@ -16,7 +16,7 @@ from .http_stream import HttpStream, StreamOptions, StreamReplyChain from .oauth_flow import OAuthFlow, OAuthFlowRegistry from .options import AppOptions, AppTelemetryOptions -from .plan import Plan, PlanOptions +from .plan import Plan, PlanOptions, PlanReplyChain from .plugins import * # noqa: F401, F403 from .routing import ActivityContext from .socket_mode import ( @@ -54,6 +54,7 @@ "HttpStream", "Plan", "PlanOptions", + "PlanReplyChain", "StreamOptions", "StreamReplyChain", "ActivityContext", diff --git a/packages/apps/src/microsoft_teams/apps/plan.py b/packages/apps/src/microsoft_teams/apps/plan.py index 2689bbf7..ffa2d094 100644 --- a/packages/apps/src/microsoft_teams/apps/plan.py +++ b/packages/apps/src/microsoft_teams/apps/plan.py @@ -5,7 +5,7 @@ import logging from collections.abc import Sequence -from typing import Literal, TypedDict, Unpack +from typing import Any, Literal, NotRequired, TypedDict, Unpack from microsoft_teams.api import ( ApiClient, @@ -20,10 +20,21 @@ ) from microsoft_teams.common import EventEmitter from microsoft_teams.common.experimental import experimental +from pydantic import model_serializer logger = logging.getLogger(__name__) +class PlanReplyChain(CustomBaseModel): + """Reply chain (thread) of a chat that a Plan completion is posted to, as for ``ctx.send``. + + ``chat_or_channel_id`` is ``channel_data.chat.id`` and ``reply_chain_id`` is ``channel_data.reply_chain.id``. + """ + + chat_or_channel_id: str + reply_chain_id: str + + class PlanOptions(TypedDict): """ Metadata for a prompt-bound Plan continuation. @@ -38,12 +49,18 @@ class PlanOptions(TypedDict): service URL before sends, while the serialized Plan itself remains a lightweight record of the conversation and prompt binding. + ``reply_chain`` is the reply chain (thread) of a chat that ``complete`` posts to, as ``ctx.send`` does. + Omit it when ``conversation_id`` already identifies the thread, as in a channel, or when the prompt is not + inside a thread. Typing updates (start, update, stop, error) are sent to the conversation, as ``ctx.send`` + does for typing activities. + ``api_client`` is runtime-only and intentionally excluded from model serialization. """ conversation_id: str reply_to_id: str api_client: ApiClient + reply_chain: NotRequired[PlanReplyChain | None] @experimental("ExperimentalTeamsPlan") @@ -63,9 +80,22 @@ class Plan(CustomBaseModel): conversation_id: str reply_to_id: str + reply_chain: PlanReplyChain | None = None + + @model_serializer(mode="wrap") + def _serialize(self, handler: Any) -> dict[str, Any]: + data = handler(self) + if self.reply_chain is None: + data.pop("reply_chain", None) + data.pop("replyChain", None) + return data def __init__(self, **options: Unpack[PlanOptions]) -> None: - data = {"conversation_id": options["conversation_id"], "reply_to_id": options["reply_to_id"]} + data = { + "conversation_id": options["conversation_id"], + "reply_to_id": options["reply_to_id"], + "reply_chain": options.get("reply_chain"), + } super().__init__(**data) self._api = options["api_client"] self._events = EventEmitter[Literal["sent"]]() @@ -179,11 +209,19 @@ async def complete(self, message: str | MessageActivityInput) -> SentActivity: raise ValueError("complete() cannot send non-complete Plan operations.") if not plan_entities: activity.add_entity(PlanInfoEntity(plan_type="complete")) - return await self._send_activity(activity) + return await self._send_activity(activity, self.reply_chain) - async def _send_activity(self, activity: MessageActivityInput | TypingActivityInput) -> SentActivity: + async def _send_activity( + self, activity: MessageActivityInput | TypingActivityInput, reply_chain: PlanReplyChain | None = None + ) -> SentActivity: activity.reply_to_id = self.reply_to_id - activity.conversation = ConversationAccount(id=self.conversation_id) - result = await self._api.conversations.create_activity(self.conversation_id, activity) + if reply_chain is None: + activity.conversation = ConversationAccount(id=self.conversation_id) + result = await self._api.conversations.create_activity(self.conversation_id, activity) + else: + activity.conversation = ConversationAccount(id=reply_chain.chat_or_channel_id) + result = await self._api.conversations._create_reply_chain_activity( # pyright: ignore[reportPrivateUsage] + reply_chain.chat_or_channel_id, reply_chain.reply_chain_id, activity + ) self.events.emit("sent", result) return result diff --git a/packages/apps/tests/test_plan.py b/packages/apps/tests/test_plan.py index 8e3eec8c..90057c01 100644 --- a/packages/apps/tests/test_plan.py +++ b/packages/apps/tests/test_plan.py @@ -24,7 +24,7 @@ UnknownEntity, ) from microsoft_teams.api.auth.cloud_environment import PUBLIC -from microsoft_teams.apps import ActivityContext, Plan, PlanOptions +from microsoft_teams.apps import ActivityContext, Plan, PlanOptions, PlanReplyChain from microsoft_teams.apps.activity_send import send_or_update_activity from microsoft_teams.cards import AdaptiveCard, TextBlock from microsoft_teams.common.experimental import ExperimentalWarning @@ -417,3 +417,55 @@ async def test_plan_serialization_round_trip(api, ref): assert all(call.args[1].reply_to_id == "original-prompt" for call in sent) assert [call.args[1].entities[0].plan_type for call in sent] == ["continue", "complete"] assert sent[0].args[1].entities[0].steps == steps + + +async def test_rebuilt_plan_completes_in_the_saved_reply_chain(api): + api.conversations._create_reply_chain_activity = AsyncMock( + side_effect=lambda chat_id, root_id, activity: SentActivity(id="answer", activity_params=activity) + ) + saved = { + "conversation_id": "a:opaque", + "reply_to_id": "prompt", + "reply_chain": {"chat_or_channel_id": "19:chat@unq.gbl.spaces", "reply_chain_id": "root"}, + } + original = Plan( + conversation_id="a:opaque", + reply_to_id="prompt", + reply_chain=PlanReplyChain(chat_or_channel_id="19:chat@unq.gbl.spaces", reply_chain_id="root"), + api_client=api, + ) + assert json.loads(json.dumps(original.model_dump(mode="json", by_alias=False))) == saved + + restored = Plan(**saved, api_client=api) + await restored.complete("Done") + + reply = api.conversations._create_reply_chain_activity + assert reply.call_args.args[:2] == ("19:chat@unq.gbl.spaces", "root") + assert reply.call_args.args[2].reply_to_id == "prompt" + assert reply.call_args.args[2].conversation.id == "19:chat@unq.gbl.spaces" + api.conversations.create_activity.assert_not_awaited() + assert restored.model_dump(mode="json", by_alias=False) == saved + + +async def test_rebuilt_plan_from_a_saved_shape_without_placement_completes_in_the_conversation(api, target): + restored = Plan(**target, api_client=api) + + await restored.complete("Done") + + assert api.conversations.create_activity.call_args.args[0] == "chat" + assert restored.model_dump(mode="json", by_alias=False) == target + assert restored.model_dump(mode="json", by_alias=True) == {"conversationId": "chat", "replyToId": "prompt"} + + +async def test_typing_updates_go_to_the_conversation_with_a_saved_placement(api, target): + api.conversations._create_reply_chain_activity = AsyncMock() + plan = Plan( + **target, + reply_chain=PlanReplyChain(chat_or_channel_id="19:chat@unq.gbl.spaces", reply_chain_id="root"), + api_client=api, + ) + + await plan.stop() + + api.conversations._create_reply_chain_activity.assert_not_awaited() + api.conversations.create_activity.assert_awaited_once() From f62a569173be28630fd798231be9b210b6a78fac Mon Sep 17 00:00:00 2001 From: Corina <14900841+corinagum@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:44:29 -0800 Subject: [PATCH 2/5] Fill the Plan reply chain from channel_data in ctx.plan() Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../apps/routing/activity_context.py | 10 ++- packages/apps/tests/test_activity_context.py | 83 +++++++++++++++++++ 2 files changed, 92 insertions(+), 1 deletion(-) diff --git a/packages/apps/src/microsoft_teams/apps/routing/activity_context.py b/packages/apps/src/microsoft_teams/apps/routing/activity_context.py index c9e62e71..160e441a 100644 --- a/packages/apps/src/microsoft_teams/apps/routing/activity_context.py +++ b/packages/apps/src/microsoft_teams/apps/routing/activity_context.py @@ -76,7 +76,7 @@ record_pending_oauth_sign_in, replace_pending_oauth_sign_ins, ) -from ..plan import Plan +from ..plan import Plan, PlanReplyChain from ..plugins.streamer import StreamerProtocol from ..state import TurnStateContainer from ..utils import create_graph_client @@ -261,9 +261,17 @@ def files(self) -> FilesAccessor: def plan(self) -> Plan: """Create or reference the existing Plan for the incoming activity. Diagnostic: ExperimentalTeamsPlan""" if self._plan is None: + placement = self._get_inbound_reply_chain_placement() self._plan = Plan( conversation_id=self.conversation_ref.conversation.id, reply_to_id=self.activity.id, + reply_chain=( + PlanReplyChain( + chat_or_channel_id=placement.chat_or_channel_id, reply_chain_id=placement.reply_chain_id + ) + if placement is not None and not placement.in_channel + else None + ), api_client=self.api.from_service_url(self.conversation_ref.service_url), ) return self._plan diff --git a/packages/apps/tests/test_activity_context.py b/packages/apps/tests/test_activity_context.py index b0b27a5c..4867996e 100644 --- a/packages/apps/tests/test_activity_context.py +++ b/packages/apps/tests/test_activity_context.py @@ -3270,3 +3270,86 @@ def test_api_client_keeps_the_endpoint_name(self) -> None: assert hasattr(UserClient, "get_token_status") assert not hasattr(UserClient, "get_connection_status") + + +class TestActivityContextPlanPlacement: + """A Plan completion is placed like ``ctx.send``: in the reply chain of a chat thread, else in the conversation.""" + + @staticmethod + def _plan_context(activity: Any) -> ActivityContext[Any]: + ctx = _context_with_reply_chain_methods(activity) + ctx.conversation_ref = ctx.conversation_ref.model_copy(update={"conversation": activity.conversation}) + ctx.api.from_service_url.return_value = ctx.api + ctx.api.conversations.create_activity = AsyncMock( + side_effect=lambda conversation_id, activity: SentActivity(id="answer", activity_params=activity) + ) + return ctx + + @pytest.mark.asyncio + async def test_complete_goes_to_the_reply_chain_of_a_chat_thread(self) -> None: + ctx = self._plan_context( + _inbound_message( + "reply-2", {"chat": {"id": CHAT_ID}, "replyChain": {"id": "root-1"}}, conversation_id="a:opaque" + ) + ) + + await ctx.plan().complete("Done") + + reply = ctx.api.conversations._create_reply_chain_activity + reply.assert_awaited_once() + assert reply.call_args.args[:2] == (CHAT_ID, "root-1") + sent = reply.call_args.args[2] + assert sent.reply_to_id == "reply-2" + assert sent.conversation.id == CHAT_ID + ctx.api.conversations.create_activity.assert_not_awaited() + + @pytest.mark.asyncio + async def test_complete_goes_to_the_conversation_for_a_top_level_chat_message(self) -> None: + ctx = self._plan_context( + _inbound_message( + "root-1", {"chat": {"id": CHAT_ID}, "replyChain": {"id": "root-1"}}, conversation_id="a:opaque" + ) + ) + + await ctx.plan().complete("Done") + + ctx.api.conversations._create_reply_chain_activity.assert_not_awaited() + assert ctx.api.conversations.create_activity.call_args.args[0] == "a:opaque" + + @pytest.mark.asyncio + async def test_complete_goes_to_the_conversation_for_a_channel_message(self) -> None: + ctx = self._plan_context( + _inbound_message( + "reply-2", + {"channel": {"id": CHANNEL_ID}, "replyChain": {"id": "root-1"}}, + conversation_id=f"{CHANNEL_ID};messageid=root-1", + conversation_type="channel", + ) + ) + + await ctx.plan().complete("Done") + + ctx.api.conversations._create_reply_chain_activity.assert_not_awaited() + assert ctx.api.conversations.create_activity.call_args.args[0] == f"{CHANNEL_ID};messageid=root-1" + + @pytest.mark.asyncio + async def test_typing_updates_go_to_the_conversation_in_a_chat_thread(self) -> None: + ctx = self._plan_context(_inbound_message("reply-2", {"chat": {"id": CHAT_ID}, "replyChain": {"id": "root-1"}})) + + await ctx.plan().start([]) + + ctx.api.conversations._create_reply_chain_activity.assert_not_awaited() + ctx.api.conversations.create_activity.assert_awaited_once() + + def test_the_saved_plan_keeps_the_placement(self) -> None: + ctx = self._plan_context( + _inbound_message( + "reply-2", {"chat": {"id": CHAT_ID}, "replyChain": {"id": "root-1"}}, conversation_id="a:opaque" + ) + ) + + assert ctx.plan().model_dump(mode="json", by_alias=False) == { + "conversation_id": "a:opaque", + "reply_to_id": "reply-2", + "reply_chain": {"chat_or_channel_id": CHAT_ID, "reply_chain_id": "root-1"}, + } From 7b6c7b085cff3979d4daa7947bbeb97e181b53be Mon Sep 17 00:00:00 2001 From: Corina <14900841+corinagum@users.noreply.github.com> Date: Wed, 4 Nov 2026 17:56:34 -0800 Subject: [PATCH 3/5] docs: document the PlanReplyChain fields Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/apps/src/microsoft_teams/apps/plan.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/apps/src/microsoft_teams/apps/plan.py b/packages/apps/src/microsoft_teams/apps/plan.py index ffa2d094..c98ec57f 100644 --- a/packages/apps/src/microsoft_teams/apps/plan.py +++ b/packages/apps/src/microsoft_teams/apps/plan.py @@ -32,7 +32,10 @@ class PlanReplyChain(CustomBaseModel): """ chat_or_channel_id: str + """The chat id, ``channel_data.chat.id``. Not ``conversation.id``.""" + reply_chain_id: str + """The id of the message at the root of the reply chain, ``channel_data.reply_chain.id``.""" class PlanOptions(TypedDict): From ad4ac8f8071aa487d05f8e19a08aa2f185b13307 Mon Sep 17 00:00:00 2001 From: Corina <14900841+corinagum@users.noreply.github.com> Date: Thu, 5 Nov 2026 09:13:33 -0800 Subject: [PATCH 4/5] docs: describe Plan placement in ctx.plan() Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- examples/plan/README.md | 2 +- .../src/microsoft_teams/apps/routing/activity_context.py | 8 +++++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/examples/plan/README.md b/examples/plan/README.md index 613e3434..d1b97fa5 100644 --- a/examples/plan/README.md +++ b/examples/plan/README.md @@ -14,7 +14,7 @@ Each step includes a description that changes as it progresses through the demo. - Send `proactive` to manage a Plan proactively. `PlanOptions` requires `conversation_id`, `reply_to_id`, and `api_client`, but -`Plan.model_dump()` serializes the two IDs and, in a chat thread, the `reply_chain` binding that places the completion. Store that data and supply the configured API client when rebuilding `PlanOptions`. +`plan.model_dump(mode="json", by_alias=False)` serializes the two IDs and, in a chat thread, the `reply_chain` binding that places the completion. Store that data and supply the configured API client when rebuilding `PlanOptions`. The delays stand in for longer-running work. diff --git a/packages/apps/src/microsoft_teams/apps/routing/activity_context.py b/packages/apps/src/microsoft_teams/apps/routing/activity_context.py index 160e441a..de613dd3 100644 --- a/packages/apps/src/microsoft_teams/apps/routing/activity_context.py +++ b/packages/apps/src/microsoft_teams/apps/routing/activity_context.py @@ -259,7 +259,13 @@ def files(self) -> FilesAccessor: @experimental("ExperimentalTeamsPlan") def plan(self) -> Plan: - """Create or reference the existing Plan for the incoming activity. Diagnostic: ExperimentalTeamsPlan""" + """Create or reference the existing Plan for the incoming activity. + + In a chat thread, a standalone ``complete()`` is posted to the reply chain, as ``ctx.send`` does. + Typing updates, completions in a channel, and prompts outside a thread use the conversation. + + Diagnostic: ExperimentalTeamsPlan + """ if self._plan is None: placement = self._get_inbound_reply_chain_placement() self._plan = Plan( From e05db757ed7c00c46573ee3f13cceee0c39fcdfa Mon Sep 17 00:00:00 2001 From: Corina <14900841+corinagum@users.noreply.github.com> Date: Thu, 5 Nov 2026 10:50:08 -0800 Subject: [PATCH 5/5] refactor: use Optional for the plan reply chain type Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- packages/apps/src/microsoft_teams/apps/plan.py | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/packages/apps/src/microsoft_teams/apps/plan.py b/packages/apps/src/microsoft_teams/apps/plan.py index c98ec57f..7cdc940d 100644 --- a/packages/apps/src/microsoft_teams/apps/plan.py +++ b/packages/apps/src/microsoft_teams/apps/plan.py @@ -5,7 +5,7 @@ import logging from collections.abc import Sequence -from typing import Any, Literal, NotRequired, TypedDict, Unpack +from typing import Any, Literal, NotRequired, Optional, TypedDict, Unpack from microsoft_teams.api import ( ApiClient, @@ -63,7 +63,7 @@ class PlanOptions(TypedDict): conversation_id: str reply_to_id: str api_client: ApiClient - reply_chain: NotRequired[PlanReplyChain | None] + reply_chain: NotRequired[Optional[PlanReplyChain]] @experimental("ExperimentalTeamsPlan") @@ -83,7 +83,7 @@ class Plan(CustomBaseModel): conversation_id: str reply_to_id: str - reply_chain: PlanReplyChain | None = None + reply_chain: Optional[PlanReplyChain] = None @model_serializer(mode="wrap") def _serialize(self, handler: Any) -> dict[str, Any]: @@ -215,7 +215,7 @@ async def complete(self, message: str | MessageActivityInput) -> SentActivity: return await self._send_activity(activity, self.reply_chain) async def _send_activity( - self, activity: MessageActivityInput | TypingActivityInput, reply_chain: PlanReplyChain | None = None + self, activity: MessageActivityInput | TypingActivityInput, reply_chain: Optional[PlanReplyChain] = None ) -> SentActivity: activity.reply_to_id = self.reply_to_id if reply_chain is None: