From 642c0e77dbb3ff3562f2b62354c1be8fd74c5477 Mon Sep 17 00:00:00 2001 From: AlexMorbo Date: Tue, 17 Nov 2026 11:19:11 +0300 Subject: [PATCH] feat: declare group mentions and mentions of everyone, and pass the kind of a mention --- README.md | 57 +++++++++++++++++++++++++++++++-- api/bridge.yaml | 56 ++++++++++++++++++++++++++++++-- examples/memory_bridge.py | 34 +++++++++++++++++--- src/muster_bridge/__init__.py | 4 +++ src/muster_bridge/config.py | 1 + src/muster_bridge/mentions.py | 17 +++++++--- src/muster_bridge/models.py | 34 ++++++++++++++++++-- tests/conftest.py | 11 +++++++ tests/test_app.py | 28 ++++++++++++++++ tests/test_config.py | 36 +++++++++++++++++++++ tests/test_mentions.py | 60 ++++++++++++++++++++++++++++++++++- tests/test_spec.py | 11 +++++++ 12 files changed, 330 insertions(+), 19 deletions(-) diff --git a/README.md b/README.md index 68fa990..e7d85cd 100644 --- a/README.md +++ b/README.md @@ -39,8 +39,8 @@ or with the package installed beside uvicorn (`pip install muster-bridge uvicorn It listens on `127.0.0.1:18095` (`--listen`), knows the channels `alerts` and `ops` (`--channels`) and the people `alice` and `bob` (`--users`), and offers every feature of the protocol, or only those that `BRIDGE_FEATURES` lists: `buttons`, `thread_messages`, `direct_messages` (which also turns on `user_lookup` `login`), `private_answers`, -`native_mentions`, `quiet_messages`, `status_color`, `deletion_events` and `delete`. With `--push-url` and -`--push-secret-file` it pushes its events as well. In another terminal: +`native_mentions`, `group_mentions`, `everyone_mentions`, `quiet_messages`, `status_color`, `deletion_events` and +`delete`. With `--push-url` and `--push-secret-file` it pushes its events as well. In another terminal: ```sh curl -s -o /dev/null -w '%{http_code}\n' 127.0.0.1:18095/v1/info # 401: no token @@ -179,7 +179,8 @@ reach Muster late. `UnknownBotError`, `NotOfferedError` for a feature the bridge does not offer and `InvalidEventError` for an event that would not match the protocol. From another thread, hand the coroutine to the loop with `asyncio.run_coroutine_threadsafe`. -5. Turn Mention markers into native mentions or plain names with `replace_mentions(body, mentions, render)`. +5. Turn Mention markers into native mentions or plain names with `replace_mentions(body, mentions, render)`; see + _Mentions of groups and of everyone in the chat_ below. 6. For pushes, give a bot a `PushTarget` — the callback URL and the push secret that its Bridge Connection in Muster shows — in `Bot(push=...)` or later with `bridge.set_push(bot, target)`, from the thread of the event loop that serves the bridge (from another thread, `loop.call_soon_threadsafe(bridge.set_push, bot, target)`). The pushers @@ -205,6 +206,56 @@ A few more things to know: every exception it logs; keep anything else secret, such as an event's Account link token, out of the exceptions of your messenger and your store. +## Mentions of groups and of everyone in the chat + +A `Mention` of the message names a person (`kind` `user`, which a Mention without `kind` is), a group of the messenger +(`group`) or everyone in the chat (`everyone`). For a group, `external_id` and `display_name` both carry the name an +Admin typed, which the bridge maps to its messenger's group; for everyone in the chat they carry the symbolic name: +`channel`, `here`, `all` or `everyone`. Declare what the messenger has in `Capabilities`: `group_mentions=True`, and +`everyone_mentions` with the symbolic names, each once, as `CapabilitiesEveryoneMention` members. A name outside the +four fails when `Capabilities` is built (pydantic's `ValidationError`), and a repeated one makes `BridgeApp` raise +`ConfigError`. Muster sends a group or everyone mention only while its copy of +`info` declares it, whether or not the bridge has `native_mentions`. + +`replace_mentions` hands `render` the whole entry, with its `kind`. The library never refuses a Mention for its kind, +because Muster decides from a copy of `info` that may be older than the bridge's own: when `render` returns `None` for +a kind the bridge did not declare, the marker becomes its link text. +The protocol's own models stay closed, so a `kind` beyond `user`, `group` and `everyone` is answered `invalid`, as the +specification says; Muster sends no other kind in protocol version 1. + +```python +from muster_bridge import Capabilities, CapabilitiesEveryoneMention, Mention, MentionKind, replace_mentions + +capabilities = Capabilities( + native_mentions=True, + group_mentions=True, + everyone_mentions=[CapabilitiesEveryoneMention.EveryoneMentionHere], +) + + +def render_mention(mention: Mention) -> str | None: + """Render a Mention for a messenger that writes <@id> for a person, and .""" + if mention.kind == MentionKind.MentionKindGroup and capabilities.group_mentions: + return f"" + if mention.kind == MentionKind.MentionKindEveryone: + names = [name.value for name in capabilities.everyone_mentions or []] + return f"" if mention.external_id in names else None + if mention.kind == MentionKind.MentionKindUser: + return f"<@{mention.external_id}>" + return None + + +body = "[@Alice](muster-mention:m1) [@oncall](muster-mention:m2) [@here](muster-mention:m3) [@all](muster-mention:m4)" +mentions = [ + Mention(ref="m1", external_id="u-alice", display_name="Alice"), + Mention(ref="m2", kind=MentionKind.MentionKindGroup, external_id="oncall", display_name="oncall"), + Mention(ref="m3", kind=MentionKind.MentionKindEveryone, external_id="here", display_name="here"), + Mention(ref="m4", kind=MentionKind.MentionKindEveryone, external_id="all", display_name="all"), +] +text = replace_mentions(body, mentions, render_mention) +assert text == "<@u-alice> @all" # all is not declared: its link text +``` + ## Rendering the layout A Root message and a test message carry their content twice: as CommonMark in `body`, and as plain-text data in diff --git a/api/bridge.yaml b/api/bridge.yaml index a3d82dd..3aab434 100644 --- a/api/bridge.yaml +++ b/api/bridge.yaml @@ -54,8 +54,12 @@ info: paragraphs, hard line breaks, emphasis, strong emphasis, strikethrough, code spans, links, bullet lists and block quotes; never headings, tables, images or raw HTML. Alert data in the body is already escaped for CommonMark and cannot mention anyone. Links are `http(s)` links, plus Mention markers: a link `[@Display Name](muster-mention:)` - whose `ref` names an entry of `mentions`. A bridge with `native_mentions` renders the marker as its messenger's - mention of that account; any other bridge renders the link text alone, as plain text. Muster keeps the body within + whose `ref` names an entry of `mentions`. A bridge with `native_mentions` renders the marker of a person as its + messenger's mention of that account; any other bridge renders the link text alone, as plain text. Muster sends the + marker of a group, whose entry has the `kind` `group`, only while its copy of `info`, at most `bridge.info_max_age` + (10 minutes) old, declares `group_mentions`, and that of everyone in the chat, of the `kind` `everyone`, only while + that copy lists its symbolic name in `everyone_mentions`; the bridge renders either as its messenger's mention of + the group or of everyone in the chat, whether or not it declares `native_mentions`. Muster keeps the body within `limits.max_body_length` code points; the bridge makes the final cut where its rendered markup needs it — never inside an entity, a tag or a surrogate pair — and reports it with `truncated`. @@ -826,6 +830,29 @@ components: native_mentions: type: boolean description: Mention markers become the messenger's own mentions, which notify the person. + group_mentions: + type: boolean + description: The bridge renders a group mention that Muster sends as a `mentions` entry of the kind `group`; + the Team mentions and group entries of a Destination need it. Missing or false, Muster offers no group + mention for the bridge's Connections. + everyone_mentions: + type: array + description: The mentions of everyone in the chat that the bridge's messenger has, by their symbolic names. + Muster sends only those listed here, each as a `mentions` entry of the kind `everyone`; missing or empty, + none. + uniqueItems: true + items: + type: string + enum: + - channel + - here + - all + - everyone + x-enum-varnames: + - EveryoneMentionChannel + - EveryoneMentionHere + - EveryoneMentionAll + - EveryoneMentionEveryone quiet_messages: type: boolean description: The messenger can post a new message without notifying anyone (`notify` false). @@ -899,6 +926,11 @@ components: pattern: ^[!-~]{1,64}$ Mention: type: object + description: 'One Mention of the envelope, which a marker `[@Display Name](muster-mention:)` in the body + places: a person (`kind` `user`, the default), a group of the messenger (`group`), or everyone in the chat + (`everyone`). Muster sends `group` only while its copy of the bridge''s `info`, at most `bridge.info_max_age` + (10 minutes) old, declares `group_mentions`, and `everyone` only with a symbolic name that copy lists in + `everyone_mentions`; it sends a person without `kind`.' required: - ref - external_id @@ -908,15 +940,33 @@ components: type: string description: Names the marker `muster-mention:` in the body. pattern: ^[a-z0-9]{1,16}$ + kind: + type: string + description: What the Mention names; missing, it is `user`. Muster sends the Mention of a person without + it. + enum: + - user + - group + - everyone + default: user + x-enum-varnames: + - MentionKindUser + - MentionKindGroup + - MentionKindEveryone external_id: type: string minLength: 1 maxLength: 512 - description: The account's id in the messenger, as the bridge reported it when the account was linked. + description: 'For a person, the account''s id in the messenger, as the bridge reported it when the account + was linked; for a group, the name an Admin typed for the Team mention or the Destination''s entry, 1 to 64 + letters, digits, `.`, `_` and `-` starting with a letter or a digit, which the bridge maps to its + messenger''s group; for everyone in the chat, the symbolic name: `channel`, `here`, `all` or `everyone`.' display_name: type: string minLength: 1 maxLength: 200 + description: The name the marker shows; for a group its name and for everyone in the chat its symbolic + name, as `external_id`. Link: type: object required: diff --git a/examples/memory_bridge.py b/examples/memory_bridge.py index eb9549e..cf06e9d 100644 --- a/examples/memory_bridge.py +++ b/examples/memory_bridge.py @@ -9,10 +9,11 @@ python examples/memory_bridge.py --token-file /tmp/bt It offers every feature, or with BRIDGE_FEATURES only those it lists, comma-separated: buttons, thread_messages, -direct_messages (which also turns on user_lookup login), private_answers, native_mentions, quiet_messages, -status_color, deletion_events and delete. Outside the protocol it serves POST /demo/press {"message_id", "user"}, -which presses the first button of the message as the person with that login. Unlike the protocol, which needs the -token, it has no authentication of its own: the example listens on loopback by default. +direct_messages (which also turns on user_lookup login), private_answers, native_mentions, group_mentions, +everyone_mentions (channel and here), quiet_messages, status_color, deletion_events and delete. Outside the protocol it +serves POST /demo/press {"message_id", "user"}, which presses the first button of the message as the person with that +login. Unlike the protocol, which needs the token, it has no authentication of its own: the example listens on +loopback by default. """ from __future__ import annotations @@ -44,6 +45,7 @@ CapabilitiesButtons, CapabilitiesDelete, CapabilitiesDirectMessages, + CapabilitiesEveryoneMention, CapabilitiesPrivateAnswer, CapabilitiesThreadMessages, Config, @@ -53,6 +55,7 @@ Gone, Limits, Mention, + MentionKind, MessageContent, MessageEdited, MessageInput, @@ -73,11 +76,17 @@ "direct_messages", "private_answers", "native_mentions", + "group_mentions", + "everyone_mentions", "quiet_messages", "status_color", "deletion_events", "delete", ) +EVERYONE_MENTIONS = [ + CapabilitiesEveryoneMention.EveryoneMentionChannel, + CapabilitiesEveryoneMention.EveryoneMentionHere, +] MAX_DEMO_BODY = 64 << 10 log = logging.getLogger("memory_bridge") @@ -146,6 +155,8 @@ def capabilities(on: set[str]) -> Capabilities: direct_messages=CapabilitiesDirectMessages(bot_can_start=True) if "direct_messages" in on else None, private_answers=[CapabilitiesPrivateAnswer.ephemeral] if "private_answers" in on else None, native_mentions=True if "native_mentions" in on else None, + group_mentions=True if "group_mentions" in on else None, + everyone_mentions=EVERYONE_MENTIONS if "everyone_mentions" in on else None, quiet_messages=True if "quiet_messages" in on else None, status_color=True if "status_color" in on else None, delete=CapabilitiesDelete(max_age_seconds=None) if "delete" in on else None, @@ -178,6 +189,8 @@ class MemoryChat: people: dict[str, Person] private: bool native: bool + groups: bool = False + everyone: bool = False id_prefix: str = field(default_factory=lambda: secrets.token_hex(3)) messages: dict[str, Message] = field(default_factory=dict) last: int = 0 @@ -332,7 +345,16 @@ def _next_id(self) -> str: def _mentions(self, body: str, mentions: list[Mention]) -> str: """Return body with its Mention markers as the messenger shows them: @login or the name.""" - return replace_mentions(body, mentions, lambda m: f"@{m.external_id}" if self.native else m.display_name) + return replace_mentions(body, mentions, self._mention) + + def _mention(self, mention: Mention) -> str | None: + """Return how the messenger shows a Mention, or None for a kind it does not offer: the marker's link text.""" + if mention.kind == MentionKind.MentionKindGroup: + return f"@{mention.external_id}" if self.groups else None + if mention.kind == MentionKind.MentionKindEveryone: + listed = {name.value for name in EVERYONE_MENTIONS} + return f"@{mention.external_id}" if self.everyone and mention.external_id in listed else None + return f"@{mention.external_id}" if self.native else mention.display_name def labels(buttons: list[Button]) -> list[str]: @@ -370,6 +392,8 @@ def configure(args: argparse.Namespace) -> tuple[Config, MemoryChat]: people=people, private="private_answers" in on, native="native_mentions" in on, + groups="group_mentions" in on, + everyone="everyone_mentions" in on, ) return config, chat diff --git a/src/muster_bridge/__init__.py b/src/muster_bridge/__init__.py index ef3db6d..1facf5c 100644 --- a/src/muster_bridge/__init__.py +++ b/src/muster_bridge/__init__.py @@ -29,6 +29,7 @@ CapabilitiesButtons, CapabilitiesDelete, CapabilitiesDirectMessages, + CapabilitiesEveryoneMention, CapabilitiesPrivateAnswer, CapabilitiesThreadMessages, DirectMessageInput, @@ -48,6 +49,7 @@ Limits, Link, Mention, + MentionKind, MessageContent, MessageEdited, MessageInput, @@ -74,6 +76,7 @@ "CapabilitiesButtons", "CapabilitiesDelete", "CapabilitiesDirectMessages", + "CapabilitiesEveryoneMention", "CapabilitiesPrivateAnswer", "CapabilitiesThreadMessages", "ClosedError", @@ -106,6 +109,7 @@ "Link", "MemoryStore", "Mention", + "MentionKind", "MessageContent", "MessageEdited", "MessageInput", diff --git a/src/muster_bridge/config.py b/src/muster_bridge/config.py index 411a055..c716f04 100644 --- a/src/muster_bridge/config.py +++ b/src/muster_bridge/config.py @@ -329,6 +329,7 @@ def _build_info(config: Config) -> tuple[bytes, Info | None, list[str]]: ("/event_delivery", checked.event_delivery), ("/capabilities/buttons/styles", checked.capabilities.buttons.styles if checked.capabilities.buttons else []), ("/capabilities/private_answers", checked.capabilities.private_answers or []), + ("/capabilities/everyone_mentions", checked.capabilities.everyone_mentions or []), ): if len(set(items)) != len(items): problems.append(f"{_SPEC_MISMATCH}{pointer}: the items are not unique") diff --git a/src/muster_bridge/mentions.py b/src/muster_bridge/mentions.py index cd9b503..f737859 100644 --- a/src/muster_bridge/mentions.py +++ b/src/muster_bridge/mentions.py @@ -20,12 +20,18 @@ _REF = re.compile(r"\]\(muster-mention:([a-z0-9]{1,16})\)") -def replace_mentions(body: str, mentions: Sequence[Mention], render: Callable[[Mention], str] | None) -> str: +def replace_mentions(body: str, mentions: Sequence[Mention], render: Callable[[Mention], str | None] | None) -> str: """Replace each Mention marker [@name](muster-mention:ref) of body by what render makes of its entry of mentions. - render makes the messenger's own mention for a bridge with native_mentions, or the plain name. A marker whose ref - names no entry, or every marker when render is None, becomes its link text, the @name as the body escapes it. The - first entry of a ref wins. The rest of body is unchanged. It takes time linear in the length of body. + render gets the whole entry and makes the messenger's own mention of it, or the plain name. Look at its kind: a + person (user, also when the entry has no kind), a group, whose external_id and display_name are the group's name, + or everyone in the chat, whose two fields are the symbolic name (channel, here, all or everyone). A bridge renders + a group or everyone mention whether or not it declares native_mentions, and never refuses an entry for its kind: + Muster decides from a copy of info that may be older than the bridge's own, so render returns None for a kind the + bridge did not declare (capabilities.group_mentions, capabilities.everyone_mentions). A marker whose ref names no + entry, a marker whose render returns None, and every marker when render is None, become the link text, the @name + as the body escapes it. The first entry of a ref wins. The rest of body is unchanged. It takes time linear in the + length of body. """ if _TAIL not in body: return body @@ -36,7 +42,8 @@ def replace_mentions(body: str, mentions: Sequence[Mention], render: Callable[[M done = 0 for start, end, text, ref in _markers(body): found = by_ref.get(ref) - parts += (body[done:start], render(found) if found is not None and render is not None else text) + shown = render(found) if found is not None and render is not None else None + parts += (body[done:start], text if shown is None else shown) done = end parts.append(body[done:]) return "".join(parts) diff --git a/src/muster_bridge/models.py b/src/muster_bridge/models.py index c59d74b..3375023 100644 --- a/src/muster_bridge/models.py +++ b/src/muster_bridge/models.py @@ -59,6 +59,13 @@ class CapabilitiesPrivateAnswer(StrEnum): popup = "popup" +class CapabilitiesEveryoneMention(StrEnum): + EveryoneMentionChannel = "channel" + EveryoneMentionHere = "here" + EveryoneMentionAll = "all" + EveryoneMentionEveryone = "everyone" + + class CapabilitiesDelete(BaseModel): max_age_seconds: int | None = Field(..., ge=1) @@ -97,17 +104,32 @@ class Button(BaseModel): ) +class MentionKind(StrEnum): + MentionKindUser = "user" + MentionKindGroup = "group" + MentionKindEveryone = "everyone" + + class Mention(BaseModel): ref: str = Field( ..., description="Names the marker `muster-mention:` in the body.", pattern="^[a-z0-9]{1,16}$" ) + kind: MentionKind = Field( + default=MentionKind.MentionKindUser, + description="What the Mention names; missing, it is `user`. Muster sends the Mention of a person without it.", + ) external_id: str = Field( ..., - description="The account's id in the messenger, as the bridge reported it when the account was linked.", + description="For a person, the account's id in the messenger, as the bridge reported it when the account was linked; for a group, the name an Admin typed for the Team mention or the Destination's entry, 1 to 64 letters, digits, `.`, `_` and `-` starting with a letter or a digit, which the bridge maps to its messenger's group; for everyone in the chat, the symbolic name: `channel`, `here`, `all` or `everyone`.", max_length=512, min_length=1, ) - display_name: str = Field(..., max_length=200, min_length=1) + display_name: str = Field( + ..., + description="The name the marker shows; for a group its name and for everyone in the chat its symbolic name, as `external_id`.", + max_length=200, + min_length=1, + ) class Link(BaseModel): @@ -445,6 +467,14 @@ class Capabilities(BaseModel): native_mentions: bool | None = Field( default=None, description="Mention markers become the messenger's own mentions, which notify the person." ) + group_mentions: bool | None = Field( + default=None, + description="The bridge renders a group mention that Muster sends as a `mentions` entry of the kind `group`; the Team mentions and group entries of a Destination need it. Missing or false, Muster offers no group mention for the bridge's Connections.", + ) + everyone_mentions: list[CapabilitiesEveryoneMention] | None = Field( + default=None, + description="The mentions of everyone in the chat that the bridge's messenger has, by their symbolic names. Muster sends only those listed here, each as a `mentions` entry of the kind `everyone`; missing or empty, none.", + ) quiet_messages: bool | None = Field( default=None, description="The messenger can post a new message without notifying anyone (`notify` false)." ) diff --git a/tests/conftest.py b/tests/conftest.py index 1395b34..dfe9b7c 100644 --- a/tests/conftest.py +++ b/tests/conftest.py @@ -29,6 +29,7 @@ CapabilitiesButtons, CapabilitiesDelete, CapabilitiesDirectMessages, + CapabilitiesEveryoneMention, CapabilitiesPrivateAnswer, CapabilitiesThreadMessages, Config, @@ -81,6 +82,11 @@ def with_body(body: str, text: str) -> str: return body.replace('"body":"b"', '"body":' + json.dumps(text), 1) +def with_mentions(body: str, mentions: list[dict[str, str]]) -> str: + """Return a request body with its mentions replaced by the entries.""" + return body.replace('"mentions":[]', '"mentions":' + json.dumps(mentions), 1) + + def with_buttons(body: str, n: int, data: str) -> str: """Return a request body with n buttons whose data is data.""" buttons = ",".join(f'{{"label":"B{i}","style":"primary","data":{json.dumps(data)}}}' for i in range(n)) @@ -308,6 +314,11 @@ def all_capabilities() -> Capabilities: direct_messages=CapabilitiesDirectMessages(bot_can_start=True), private_answers=[CapabilitiesPrivateAnswer.ephemeral], native_mentions=True, + group_mentions=True, + everyone_mentions=[ + CapabilitiesEveryoneMention.EveryoneMentionChannel, + CapabilitiesEveryoneMention.EveryoneMentionHere, + ], quiet_messages=True, status_color=True, delete=CapabilitiesDelete(max_age_seconds=None), diff --git a/tests/test_app.py b/tests/test_app.py index effc60d..ec5de94 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -30,6 +30,7 @@ raising, with_body, with_buttons, + with_mentions, ) from starlette.applications import Starlette from starlette.routing import Mount @@ -989,3 +990,30 @@ async def test_the_messenger_gets_the_layout_that_muster_sent_and_none_without_i assert (await bridge.call(method, path, key=key and "k2", body=with_layout(plain))).is_success got = [cast(MessageContent, call.payload).layout for call in bridge.messenger.calls] assert [layout and layout.model_dump(mode="json") for layout in got] == [None, LAYOUT, None, LAYOUT] + + +KIND_MENTIONS = [ + {"ref": "m1", "external_id": "u-alice", "display_name": "Alice Smith"}, + {"ref": "m2", "kind": "group", "external_id": "oncall", "display_name": "oncall"}, + {"ref": "m3", "kind": "everyone", "external_id": "channel", "display_name": "channel"}, +] + + +async def test_the_messenger_gets_the_kind_of_each_mention(bridge: Harness) -> None: + response = await bridge.call("POST", "/v1/messages", key="k1", body=with_mentions(POST_BODY, KIND_MENTIONS)) + assert response.status_code == 201, response.text + mentions = getattr(bridge.messenger.calls[-1].payload, "mentions", []) + assert [(m.kind.value, m.external_id, m.display_name) for m in mentions] == [ + ("user", "u-alice", "Alice Smith"), + ("group", "oncall", "oncall"), + ("everyone", "channel", "channel"), + ] + + +async def test_a_bridge_without_group_or_everyone_mentions_never_refuses_their_entries(make_bridge: MakeBridge) -> None: + capabilities = all_capabilities().model_copy(update={"group_mentions": None, "everyone_mentions": ["here"]}) + bridge = await make_bridge(capabilities=capabilities) + mentions = [*KIND_MENTIONS, {"ref": "m4", "kind": "everyone", "external_id": "all", "display_name": "all"}] + response = await bridge.call("POST", "/v1/messages", key="k1", body=with_mentions(POST_BODY, mentions)) + assert response.status_code == 201, response.text + assert bridge.messenger.count("post_message") == 1 diff --git a/tests/test_config.py b/tests/test_config.py index 2ecd559..f60f2ca 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -20,6 +20,7 @@ Capabilities, CapabilitiesButtons, CapabilitiesDelete, + CapabilitiesEveryoneMention, CapabilitiesPrivateAnswer, Config, ConfigError, @@ -102,6 +103,8 @@ async def test_info_with_every_member() -> None: "direct_messages": {"bot_can_start": True}, "private_answers": ["ephemeral"], "native_mentions": True, + "group_mentions": True, + "everyone_mentions": ["channel", "here"], "quiet_messages": True, "status_color": True, "delete": {"max_age_seconds": None}, @@ -271,6 +274,28 @@ def nan_limits() -> Limits: "/capabilities/private_answers: the items are not unique", id="duplicate private answer", ), + pytest.param( + { + "capabilities": Capabilities( + everyone_mentions=[ + CapabilitiesEveryoneMention.EveryoneMentionHere, + CapabilitiesEveryoneMention.EveryoneMentionHere, + ] + ) + }, + "/capabilities/everyone_mentions: the items are not unique", + id="duplicate everyone mention", + ), + pytest.param( + {"capabilities": Capabilities.model_construct(everyone_mentions=["channel", "room"])}, + "/capabilities/everyone_mentions/1: Input should be 'channel', 'here', 'all' or 'everyone'", + id="unknown everyone mention", + ), + pytest.param( + {"capabilities": Capabilities.model_construct(group_mentions="yes")}, + "/capabilities/group_mentions: Input should be a valid boolean", + id="group_mentions not a boolean", + ), pytest.param( {"capabilities": Capabilities(delete=CapabilitiesDelete.model_construct(max_age_seconds=0))}, "/capabilities/delete/max_age_seconds: Input should be greater than or equal to 1", @@ -412,3 +437,14 @@ async def test_system_clock() -> None: clock = SystemClock() assert clock.now().tzinfo is UTC await clock.sleep(0) + + +async def test_group_and_everyone_mentions_are_declared_in_info() -> None: + capabilities = Capabilities(group_mentions=True, everyone_mentions=list(CapabilitiesEveryoneMention)) + info = (await get_info(BridgeApp(minimal_config(capabilities=capabilities), MinimalMessenger()), "t")).json() + assert info["capabilities"] == {"group_mentions": True, "everyone_mentions": ["channel", "here", "all", "everyone"]} + + +async def test_info_declares_no_group_or_everyone_mentions_by_default() -> None: + info = (await get_info(BridgeApp(minimal_config(), MinimalMessenger()), "t")).json() + assert info["capabilities"] == {} diff --git a/tests/test_mentions.py b/tests/test_mentions.py index b7dd4a5..573f867 100644 --- a/tests/test_mentions.py +++ b/tests/test_mentions.py @@ -5,10 +5,12 @@ import re import time from collections.abc import Callable, Sequence +from pathlib import Path +from typing import Any import pytest -from muster_bridge import Mention, replace_mentions +from muster_bridge import Mention, MentionKind, replace_mentions MENTIONS = [ Mention(ref="m1", external_id="u-alice", display_name="Alice Smith"), @@ -129,3 +131,59 @@ def test_replace_mentions_takes_linear_time(body: str, want: str) -> None: assert replace_mentions(body, MENTIONS, native) == want # A quadratic scan takes minutes over 100 000 characters, a linear one milliseconds; 5 s leaves room for any CI. assert time.perf_counter() - started < 5 + + +GROUP = Mention(ref="g1", kind=MentionKind.MentionKindGroup, external_id="oncall", display_name="oncall") +EVERYONE = Mention(ref="e1", kind=MentionKind.MentionKindEveryone, external_id="here", display_name="here") + + +def test_a_mention_without_kind_is_a_user() -> None: + assert ( + Mention.model_validate_json('{"ref":"m1","external_id":"u","display_name":"U"}').kind + == MentionKind.MentionKindUser + ) + assert Mention(ref="m1", external_id="u", display_name="U").kind == MentionKind.MentionKindUser + + +def test_render_gets_each_entry_with_its_kind() -> None: + seen: list[tuple[MentionKind, str, str]] = [] + + def render(mention: Mention) -> str: + seen.append((mention.kind, mention.external_id, mention.display_name)) + return f"<{mention.kind.value}>" + + body = "[@Alice Smith](muster-mention:m1) [@oncall](muster-mention:g1) [@here](muster-mention:e1)" + got = replace_mentions(body, [*MENTIONS, GROUP, EVERYONE], render) + assert got == " " + assert seen == [ + (MentionKind.MentionKindUser, "u-alice", "Alice Smith"), + (MentionKind.MentionKindGroup, "oncall", "oncall"), + (MentionKind.MentionKindEveryone, "here", "here"), + ] + + +def test_an_undeclared_kind_is_shown_as_the_link_text_of_its_marker() -> None: + def render(mention: Mention) -> str | None: + return native(mention) if mention.kind == MentionKind.MentionKindUser else None + + body = "[@Alice Smith](muster-mention:m1) [@oncall](muster-mention:g1) [@here](muster-mention:e1)" + assert replace_mentions(body, [*MENTIONS, GROUP, EVERYONE], render) == "<@u-alice> @oncall @here" + + +def readme_example() -> dict[str, Any]: + """Run the README's example for group mentions and mentions of everyone in the chat and return its names.""" + readme = (Path(__file__).parents[1] / "README.md").read_text(encoding="utf-8") + section = readme.split("## Mentions of groups and of everyone in the chat", 1)[1].split("\n## ", 1)[0] + match = re.search(r"```python\n(.*?)```", section, re.DOTALL) + assert match, "README.md has no example under Mentions of groups and of everyone in the chat" + scope: dict[str, Any] = {} + exec(compile(match.group(1), "README.md", "exec"), scope) # noqa: S102 - the repository's own example + return scope + + +def test_the_readme_example_renders_a_user_a_group_and_here() -> None: + scope = readme_example() + assert scope["text"] == "<@u-alice> @all" + capabilities = scope["capabilities"] + assert capabilities.group_mentions is True + assert [name.value for name in capabilities.everyone_mentions] == ["here"] diff --git a/tests/test_spec.py b/tests/test_spec.py index ff2d46d..8e16227 100644 --- a/tests/test_spec.py +++ b/tests/test_spec.py @@ -29,6 +29,7 @@ raising, two_bots, with_body, + with_mentions, ) from openapi_core import Config, OpenAPI from openapi_core.datatypes import RequestParameters @@ -161,6 +162,14 @@ class Exchange: """The request does not match the specification, so only the answer is validated.""" +MENTIONS = [ + {"ref": "m1", "external_id": "u-alice", "display_name": "Alice Smith"}, + {"ref": "m2", "kind": "user", "external_id": "u-bob", "display_name": "Bob"}, + {"ref": "m3", "kind": "group", "external_id": "oncall", "display_name": "oncall"}, + {"ref": "m4", "kind": "everyone", "external_id": "here", "display_name": "here"}, +] +BAD_KIND = {"ref": "m5", "kind": "team", "external_id": "x", "display_name": "x"} + EXCHANGES = [ Exchange("getInfo", "200", "GET", "/v1/info", 200), Exchange("getInfo", "401", "GET", "/v1/info", 401, token="wrong"), @@ -168,6 +177,8 @@ class Exchange: Exchange("postMessage", "201 replayed", "POST", POST, 201, POST_BODY, setup=replay(POST, POST_BODY)), Exchange("postMessage", "201 layout", "POST", POST, 201, with_layout(POST_BODY)), Exchange("postMessage", "201 layout dropped", "POST", POST, 201, with_layout(POST_BODY, "{}"), invalid=True), + Exchange("postMessage", "201 mentions of every kind", "POST", POST, 201, with_mentions(POST_BODY, MENTIONS)), + Exchange("postMessage", "400 unknown kind", "POST", POST, 400, with_mentions(POST_BODY, [BAD_KIND]), invalid=True), Exchange("postMessage", "400 spec", "POST", POST, 400, "{}", invalid=True), Exchange("postMessage", "400 limit", "POST", POST, 400, with_body(POST_BODY, "x" * 501)), Exchange("postMessage", "401", "POST", POST, 401, POST_BODY, token="wrong"),