Skip to content
Merged
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
2 changes: 1 addition & 1 deletion examples/plan/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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(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.

Expand Down
3 changes: 2 additions & 1 deletion packages/apps/src/microsoft_teams/apps/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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 (
Expand Down Expand Up @@ -54,6 +54,7 @@
"HttpStream",
"Plan",
"PlanOptions",
"PlanReplyChain",
"StreamOptions",
"StreamReplyChain",
"ActivityContext",
Expand Down
53 changes: 47 additions & 6 deletions packages/apps/src/microsoft_teams/apps/plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

import logging
from collections.abc import Sequence
from typing import Literal, TypedDict, Unpack
from typing import Any, Literal, NotRequired, Optional, TypedDict, Unpack

from microsoft_teams.api import (
ApiClient,
Expand All @@ -20,10 +20,24 @@
)
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
Comment thread
corinagum marked this conversation as resolved.
Resolved
"""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):
"""
Metadata for a prompt-bound Plan continuation.
Expand All @@ -38,12 +52,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.
Comment thread
Copilot marked this conversation as resolved.
Resolved

``api_client`` is runtime-only and intentionally excluded from model serialization.
"""

conversation_id: str
reply_to_id: str
api_client: ApiClient
reply_chain: NotRequired[Optional[PlanReplyChain]]


@experimental("ExperimentalTeamsPlan")
Expand All @@ -63,9 +83,22 @@ class Plan(CustomBaseModel):

conversation_id: str
reply_to_id: str
reply_chain: Optional[PlanReplyChain] = 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"]]()
Expand Down Expand Up @@ -179,11 +212,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: Optional[PlanReplyChain] = 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
18 changes: 16 additions & 2 deletions packages/apps/src/microsoft_teams/apps/routing/activity_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -259,11 +259,25 @@ 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(
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
Expand Down
83 changes: 83 additions & 0 deletions packages/apps/tests/test_activity_context.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"},
}
54 changes: 53 additions & 1 deletion packages/apps/tests/test_plan.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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()
Loading