Skip to content

netresearch/matrix-skill / skills/matrix-communication

matrix-communication

Flagged

Use when communicating via Matrix chat, notifying teams, or managing E2EE. Triggers on #room:server references, Matrix URLs, and chat requests.

FileKindSize
README.mdmarkdown2.9 KB
SKILL.mdskill md6.7 KB
evals/evals.jsonconfig12.6 KB
references/agent-governance.mdmarkdown2.0 KB
references/api-reference.mdmarkdown7.3 KB
references/command-reference.mdmarkdown8.9 KB
references/e2ee-guide.mdmarkdown17.2 KB
references/hookshot-integration.mdmarkdown10.7 KB
references/messaging-guide.mdmarkdown13.8 KB
references/no-editorializing.mdmarkdown331 B
references/setup-guide.mdmarkdown13.8 KB
references/troubleshooting.mdmarkdown7.8 KB
scripts/_lib/__init__.pyscript3.6 KB
scripts/_lib/backup_mac.pyscript1.2 KB
scripts/_lib/config.pyscript4.6 KB
scripts/_lib/daemon_client.pyscript3.0 KB
scripts/_lib/deps.pyscript1.9 KB
scripts/_lib/downloads.pyscript1.1 KB
scripts/_lib/e2ee.pyscript13.2 KB
scripts/_lib/formatting.pyscript14.4 KB
scripts/_lib/http.pyscript4.8 KB
scripts/_lib/reactions.pyscript2.9 KB
scripts/_lib/roomlog.pyscript13.7 KB
scripts/_lib/rooms.pyscript15.5 KB
scripts/_lib/secret_input.pyscript2.0 KB
scripts/_lib/test_backup_mac.pyscript1.5 KB
scripts/_lib/test_config.pyscript7.1 KB
scripts/_lib/test_daemon_client.pyscript5.9 KB
scripts/_lib/test_downloads.pyscript2.3 KB
scripts/_lib/test_e2ee.pyscript14.3 KB
scripts/_lib/test_formatting.pyscript15.5 KB
scripts/_lib/test_http.pyscript4.1 KB
scripts/_lib/test_reactions.pyscript15.2 KB
scripts/_lib/test_roomlog.pyscript20.2 KB
scripts/_lib/test_rooms.pyscript13.7 KB
scripts/_lib/test_secret_input.pyscript2.2 KB
scripts/_lib/test_trust.pyscript8.3 KB
scripts/_lib/trust.pyscript5.3 KB
scripts/_lib/utils.pyscript1.7 KB
scripts/matrix-create-room.pyexecutablescript4.7 KB
scripts/matrix-doctor.pyexecutablescript22.2 KB
scripts/matrix-download-e2ee.pyexecutablescript7.7 KB
scripts/matrix-e2ee-setup.pyexecutablescript9.2 KB
scripts/matrix-e2ee-verify.pyexecutablescript29.2 KB
scripts/matrix-edit-e2ee.pyexecutablescript7.9 KB
scripts/matrix-edit.pyexecutablescript5.3 KB
scripts/matrix-fetch-keys.pyexecutablescript9.1 KB
scripts/matrix-invite.pyexecutablescript3.0 KB
scripts/matrix-key-backup.pyexecutablescript21.3 KB
scripts/matrix-power-level.pyexecutablescript7.0 KB
scripts/matrix-react.pyexecutablescript14.1 KB
scripts/matrix-read-e2ee.pyexecutablescript12.8 KB
scripts/matrix-read.pyexecutablescript4.7 KB
scripts/matrix-redact.pyexecutablescript5.0 KB
scripts/matrix-resolve.pyexecutablescript1.7 KB
scripts/matrix-rooms.pyexecutablescript3.8 KB
scripts/matrix-send-e2ee.pyexecutablescript19.4 KB
scripts/matrix-send.pyexecutablescript9.4 KB
scripts/matrix-watch.pyexecutablescript5.3 KB
scripts/matrix-watchd.pyexecutablescript23.5 KB
scripts/test_matrix_doctor.pyscript14.2 KB
scripts/test_matrix_read_e2ee.pyscript2.7 KB

scripts/_lib/test_reactions.py

View on GitHub
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Netresearch DTT GmbH

"""Tests for `_lib.reactions` and the status swap in `matrix-react.py`.

Run directly (stdlib only, no nio):

    python3 skills/matrix-communication/scripts/_lib/test_reactions.py
"""

import importlib.util
import os
import sys
import types
import unittest

HERE = os.path.dirname(os.path.abspath(__file__))
# The scripts directory, not _lib itself: _lib/http.py would shadow the stdlib
# `http` package that urllib.request imports.
sys.path.insert(0, os.path.dirname(HERE))
if sys.path[1:2] == [HERE]:
    del sys.path[1]  # a direct run puts the file's own directory there

from _lib.reactions import annotations, own_reactions

ME = "@agent:example.org"
TARGET = "$djnY5_1gyZe2Xkk-3xB437F_Sfwr0AaVhcDATMM40pE"

# A relations page as Synapse returned it for a test message carrying two
# reactions of one account (2026-11-04); only the user ID is replaced.
SYNAPSE_PAGE = {
    "chunk": [
        {
            "content": {
                "m.relates_to": {
                    "event_id": TARGET,
                    "key": "\U0001f916",
                    "rel_type": "m.annotation",
                }
            },
            "event_id": "$yBkEG80w7_Mw1QzR9TFPQUSvuOhpHAc1sGtMvevvdq4",
            "room_id": "!CkTNagkkIFSndMzpdc:netresearch.de",
            "sender": ME,
            "type": "m.reaction",
            "unsigned": {"membership": "join"},
        },
        {
            "content": {
                "m.relates_to": {
                    "event_id": TARGET,
                    "key": "▶️",
                    "rel_type": "m.annotation",
                }
            },
            "event_id": "$aSpdQ3N6_FzzWuJsjvf2VYSueIFWDmXOGJBSoSTbhzc",
            "room_id": "!CkTNagkkIFSndMzpdc:netresearch.de",
            "sender": ME,
            "type": "m.reaction",
            "unsigned": {"membership": "join"},
        },
    ]
}


def reaction(event_id, key, sender=ME, type_="m.reaction", **unsigned):
    return {
        "event_id": event_id,
        "sender": sender,
        "type": type_,
        "content": {"m.relates_to": {"rel_type": "m.annotation", "key": key}},
        "unsigned": unsigned,
    }


class OwnReactionsTest(unittest.TestCase):
    def test_synapse_page_yields_the_status_reaction(self):
        found = own_reactions(SYNAPSE_PAGE["chunk"], ME, {"▶️", "✅"})
        self.assertEqual(
            found,
            [{"event_id": "$aSpdQ3N6_FzzWuJsjvf2VYSueIFWDmXOGJBSoSTbhzc", "key": "▶️"}],
        )

    def test_other_senders_are_ignored(self):
        events = [reaction("$a", "x", sender="@human:example.org")]
        self.assertEqual(own_reactions(events, ME, {"x"}), [])

    def test_encrypted_reaction_counts(self):
        # m.relates_to stays in clear text on an encrypted event.
        events = [reaction("$a", "x", type_="m.room.encrypted")]
        self.assertEqual(
            own_reactions(events, ME, {"x"}), [{"event_id": "$a", "key": "x"}]
        )

    def test_redacted_reaction_is_skipped(self):
        events = [reaction("$a", "x", redacted_because={"type": "m.room.redaction"})]
        self.assertEqual(own_reactions(events, ME, {"x"}), [])

    def test_keys_none_returns_every_own_key(self):
        found = own_reactions(SYNAPSE_PAGE["chunk"], ME, None)
        self.assertEqual([r["key"] for r in found], ["\U0001f916", "▶️"])

    def test_other_relation_types_are_skipped(self):
        event = reaction("$a", "x")
        event["content"]["m.relates_to"]["rel_type"] = "m.thread"
        self.assertEqual(own_reactions([event], ME, {"x"}), [])


class AnnotationsTest(unittest.TestCase):
    def test_follows_next_batch(self):
        pages = {
            None: {"chunk": [reaction("$a", "x")], "next_batch": "t/2"},
            "t%2F2": {"chunk": [reaction("$b", "y")]},
        }
        seen = []

        def request(path):
            seen.append(path)
            token = path.split("&from=")[1] if "&from=" in path else None
            return pages[token]

        events = annotations(request, "!room:example.org", "$ev")
        self.assertEqual([e["event_id"] for e in events], ["$a", "$b"])
        self.assertIn("/relations/%24ev/m.annotation?limit=100", seen[0])

    def test_error_is_returned_not_swallowed(self):
        # A failed lookup must never read as "no reactions there".
        result = annotations(lambda path: {"error": "boom"}, "!r", "$e")
        self.assertEqual(result, {"error": "boom"})

    def test_endless_paging_stops(self):
        result = annotations(
            lambda path: {"chunk": [], "next_batch": "again"}, "!r", "$e"
        )
        self.assertIn("error", result)


def load_react():
    spec = importlib.util.spec_from_file_location(
        "matrix_react", os.path.join(os.path.dirname(HERE), "matrix-react.py")
    )
    module = importlib.util.module_from_spec(spec)
    spec.loader.exec_module(module)
    return module


class ApplyReactionTest(unittest.TestCase):
    """The swap order: new status first, old ones after, never twice."""

    def setUp(self):
        self.react = load_react()
        self.calls = []
        self.existing = []
        self.react.find_own = lambda config, room, event, keys: [
            r for r in self.existing if r["key"] in keys
        ]
        self.react.send_reaction = lambda config, room, event, key, trust=False: (
            self.calls.append(("send", key)) or {"event_id": f"$new-{key}"}
        )
        self.react.redact_reaction = lambda config, room, rid: (
            self.calls.append(("redact", rid)) or {"event_id": "$redaction"}
        )

    def apply(self, emoji, replace=(), remove=False):
        return self.react.apply_reaction({}, "!r", "$e", emoji, list(replace), remove)

    def test_swap_sends_new_then_redacts_old(self):
        self.existing = [
            {"event_id": "$old", "key": "A"},
            {"event_id": "$bot", "key": "R"},
        ]
        result = self.apply("B", replace=["A", "C"])
        self.assertEqual(self.calls, [("send", "B"), ("redact", "$old")])
        self.assertEqual(result, {"event_id": "$new-B", "removed": ["A"]})

    def test_existing_status_is_not_sent_again(self):
        self.existing = [{"event_id": "$have", "key": "B"}]
        result = self.apply("B", replace=["A"])
        self.assertEqual(self.calls, [])
        self.assertEqual(result["event_id"], "$have")

    def test_new_emoji_in_replace_list_is_kept(self):
        self.existing = [{"event_id": "$have", "key": "B"}]
        self.apply("B", replace=["A", "B"])
        self.assertEqual(self.calls, [])

    def test_failed_send_leaves_old_status(self):
        self.existing = [{"event_id": "$old", "key": "A"}]
        self.react.send_reaction = lambda *a, **k: {"error": "refused"}
        result = self.apply("B", replace=["A"])
        self.assertEqual(result, {"error": "refused"})
        self.assertEqual(self.calls, [])

    def test_remove_redacts_only_that_emoji(self):
        self.existing = [
            {"event_id": "$x", "key": "A"},
            {"event_id": "$bot", "key": "R"},
        ]
        result = self.apply("A", remove=True)
        self.assertEqual(self.calls, [("redact", "$x")])
        self.assertEqual(result, {"event_id": None, "removed": ["A"]})

    def test_failed_lookup_sends_nothing(self):
        self.react.find_own = lambda *a: {"error": "403"}
        result = self.apply("B", replace=["A"])
        self.assertIn("error", result)
        self.assertEqual(self.calls, [])

    def test_plain_react_skips_the_lookup(self):
        self.react.find_own = lambda *a: self.fail("plain react must not look up")
        self.apply("B")
        self.assertEqual(self.calls, [("send", "B")])


class ApplyReactionsTest(ApplyReactionTest):
    """Several emojis in one call: each in order, the swap's removals after the last."""

    def apply_all(self, emojis, replace=(), remove=False):
        return self.react.apply_reactions(
            {}, "!r", "$e", list(emojis), list(replace), remove
        )

    def test_claim_sets_status_and_marker_in_order(self):
        # A ticket claim: ▶️ and 🤖 on one ticket notification.
        results, error = self.apply_all(["▶️", "\U0001f916"])
        self.assertIsNone(error)
        self.assertEqual(self.calls, [("send", "▶️"), ("send", "\U0001f916")])
        self.assertEqual(
            [r["event_id"] for r in results], ["$new-▶️", "$new-\U0001f916"]
        )

    def test_swap_redacts_after_the_last_and_keeps_the_new_ones(self):
        self.existing = [
            {"event_id": "$play", "key": "▶️"},
            {"event_id": "$bot", "key": "R"},
        ]
        _, error = self.apply_all(["✅", "R"], replace=["▶️", "R"])
        self.assertIsNone(error)
        self.assertEqual(self.calls, [("send", "✅"), ("redact", "$play")])

    def test_replace_never_removes_an_emoji_set_in_the_same_call(self):
        self.existing = [{"event_id": "$have", "key": "A"}]
        _, error = self.apply_all(["A", "B"], replace=["A"])
        self.assertIsNone(error)
        self.assertNotIn(("redact", "$have"), self.calls)

    def test_swap_does_not_resend_an_earlier_emoji_already_set(self):
        self.existing = [
            {"event_id": "$have", "key": "A"},
            {"event_id": "$x", "key": "X"},
        ]
        results, failed = self.apply_all(["A", "B"], replace=["X"])
        self.assertIsNone(failed)
        self.assertEqual(self.calls, [("send", "B"), ("redact", "$x")])
        self.assertEqual(results[0]["event_id"], "$have")

    def test_single_emoji_replacing_itself_keeps_the_lookup(self):
        self.existing = [{"event_id": "$have", "key": "A"}]
        results, failed = self.apply_all(["A"], replace=["A"])
        self.assertIsNone(failed)
        self.assertEqual(self.calls, [])
        self.assertEqual(results[0]["event_id"], "$have")

    def test_failure_keeps_its_partial_effects(self):
        self.existing = [
            {"event_id": "$a", "key": "A"},
            {"event_id": "$c", "key": "C"},
        ]

        def redact(config, room, rid):
            if rid == "$c":
                return {"error": "403"}
            self.calls.append(("redact", rid))
            return {"event_id": "$redaction"}

        self.react.redact_reaction = redact
        results, failed = self.apply_all(["B"], replace=["A", "C"])
        self.assertEqual(results, [])
        self.assertEqual(failed["event_id"], "$new-B")
        self.assertEqual(failed["removed"], ["A"])
        self.assertIn("403", failed["error"])

    def test_empty_error_text_still_counts_as_failure(self):
        self.react.send_reaction = lambda *a, **k: {"error": ""}
        results, failed = self.apply_all(["A"])
        self.assertEqual(results, [])
        self.assertEqual(failed, {"error": ""})

    def test_first_error_stops_and_reports_what_was_applied(self):
        sent = []

        def send(config, room, event, key, trust=False):
            if key == "B":
                return {"error": "refused"}
            sent.append(key)
            return {"event_id": f"$new-{key}"}

        self.react.send_reaction = send
        results, failed = self.apply_all(["A", "B", "C"])
        self.assertEqual(failed, {"error": "refused"})
        self.assertEqual(sent, ["A"])
        self.assertEqual(len(results), 1)


class TransactionIdTest(unittest.TestCase):
    """Two direct sends in one run must not share a transaction ID."""

    def test_sends_and_redactions_in_the_same_millisecond_differ(self):
        react = load_react()
        paths = []
        react.daemon_request = lambda payload: None
        react.matrix_request = lambda config, method, endpoint, data=None: (
            paths.append(endpoint) or {"event_id": "$x"}
        )
        # Freeze the clock for this module only; time.time itself stays untouched.
        react.time = types.SimpleNamespace(time=lambda: 1794962519.123)
        react.send_reaction({}, "!r", "$e", "A")
        react.send_reaction({}, "!r", "$e", "B")
        react.redact_reaction({}, "!r", "$a")
        react.redact_reaction({}, "!r", "$b")
        sends = [p.rsplit("/", 1)[1] for p in paths[:2]]
        redacts = [p.rsplit("/", 1)[1] for p in paths[2:]]
        self.assertNotEqual(sends[0], sends[1])
        self.assertNotEqual(redacts[0], redacts[1])


class FindOwnTest(unittest.TestCase):
    """The lookup's wiring: v1 relations path, and whoami when user_id is missing."""

    def setUp(self):
        self.react = load_react()
        self.requests = []

        def fake_request(config, method, endpoint, data=None, api_version="v3"):
            self.requests.append((method, endpoint, api_version))
            if endpoint == "/account/whoami":
                return {"user_id": ME}
            return SYNAPSE_PAGE

        self.react.matrix_request = fake_request

    def test_relations_are_read_from_v1(self):
        found = self.react.find_own({"user_id": ME}, "!r:x", TARGET, {"▶️"})
        self.assertEqual([r["key"] for r in found], ["▶️"])
        self.assertEqual(len(self.requests), 1)
        method, endpoint, version = self.requests[0]
        self.assertEqual((method, version), ("GET", "v1"))
        self.assertIn("/relations/", endpoint)

    def test_user_id_falls_back_to_whoami(self):
        found = self.react.find_own({}, "!r:x", TARGET, {"\U0001f916"})
        self.assertEqual(self.requests[0][1], "/account/whoami")
        self.assertEqual([r["key"] for r in found], ["\U0001f916"])

    def test_failed_whoami_is_an_error(self):
        self.react.matrix_request = lambda *a, **k: {"error": "401"}
        self.assertEqual(
            self.react.find_own({}, "!r:x", TARGET, {"x"}), {"error": "401"}
        )


class ListModeTest(unittest.TestCase):
    """`--list` prints the account's own reactions and sends nothing."""

    def setUp(self):
        self.react = load_react()
        self.react.load_config = lambda: {"user_id": ME}
        self.react.matrix_request = (
            lambda config, method, endpoint, data=None, api_version="v3": SYNAPSE_PAGE
        )
        self.react.send_reaction = lambda *a, **k: self.fail("--list must not send")
        self.react.redact_reaction = lambda *a, **k: self.fail("--list must not redact")

    def run_main(self, *argv):
        import contextlib
        import io

        out = io.StringIO()
        old = sys.argv
        sys.argv = ["matrix-react.py", "!r:example.org", TARGET, *argv]
        try:
            with contextlib.redirect_stdout(out):
                self.react.main()
        finally:
            sys.argv = old
        return out.getvalue()

    def test_list_prints_every_own_reaction(self):
        lines = self.run_main("--list").splitlines()
        self.assertEqual(
            lines,
            [
                "\U0001f916\t$yBkEG80w7_Mw1QzR9TFPQUSvuOhpHAc1sGtMvevvdq4",
                "▶️\t$aSpdQ3N6_FzzWuJsjvf2VYSueIFWDmXOGJBSoSTbhzc",
            ],
        )

    def test_list_json(self):
        import json

        data = json.loads(self.run_main("--list", "--json"))
        self.assertEqual([r["key"] for r in data["reactions"]], ["\U0001f916", "▶️"])

    def test_list_with_emoji_is_refused(self):
        with self.assertRaises(SystemExit):
            self.run_main("✅", "--list")

    def test_emoji_required_without_list(self):
        with self.assertRaises(SystemExit):
            self.run_main()


if __name__ == "__main__":
    unittest.main()
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 197kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall