Skip to content

DeepTutor: Lifelong Personalized Tutoring. https://deeptutor.info/.

minor fix & new channel

Bingxi Zhao (Frank)4fab44897770
diff --git a/README.md b/README.md
index 684f88593..e1b6733a4 100644
--- a/README.md
+++ b/README.md
@@ -478,7 +478,7 @@ Each partner has a `SOUL.md`, model selection, channels, tool policy, and assign
<img src="assets/figs/web-1.4.6+/partners/02-IM%20config%20for%20each%20partner.png" alt="Per-partner IM channel configuration" width="900">
</div>
-The channel layer is schema-driven and can connect to IM platforms such as Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Matrix, Mochat, and Microsoft Teams depending on installed extras and configured credentials. A partner can also be connected as a subagent and consulted from a normal chat turn — see **My Agents** below.
+The channel layer is schema-driven and can connect to IM platforms such as Feishu, Telegram, Slack, Discord, DingTalk, QQ/NapCat, WeCom, WhatsApp, Zulip, Mattermost, Matrix, Mochat, and Microsoft Teams depending on installed extras and configured credentials. A partner can also be connected as a subagent and consulted from a normal chat turn — see **My Agents** below.
</details>
diff --git a/deeptutor/capabilities/mastery/choices.py b/deeptutor/capabilities/mastery/choices.py
new file mode 100644
index 000000000..b506b05a6
--- /dev/null
+++ b/deeptutor/capabilities/mastery/choices.py
@@ -0,0 +1,143 @@
+"""The data contract for multiple-choice mastery questions.
+
+A choice question crosses four boundaries with different shapes for the same
+data: the model registers option *bodies* through ``mastery_quiz``, the learner
+answers a *label* (``"C"``) on an interactive ``ask_user`` card, deterministic
+grading must compare like with like, and the Question Bank persists the full
+option text. This module owns the translation between those shapes so the tool
+layer (:mod:`deeptutor.capabilities.mastery.tools`) reads as orchestration:
+
+* :func:`parse_options` — option strings → a ``{label: body}`` map.
+* :func:`has_option_bodies` — did the model send real bodies, not bare labels?
+* :func:`format_options` — a ``{label: body}`` map → canonical option strings.
+* :func:`resolve_answer` — a model-supplied answer → its stable option label.
+* :func:`recover_options_from_turn` — bodies recovered from a legacy turn's
+ ``ask_user`` event, for paths registered before the contract was enforced.
+
+Everything here is pure except :func:`recover_options_from_turn`, which takes a
+session store by dependency injection rather than importing one, keeping this
+module free of infrastructure wiring.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+from typing import Any
+
+logger = logging.getLogger(__name__)
+
+# Matches a labelled option like ``"C: body"`` / ``"C) body"`` / ``"C、body"``,
+# capturing the label letter and the body. Used to recover the label a model
+# embedded in the option text instead of supplying it positionally.
+OPTION_PREFIX_RE = re.compile(r"^\s*([A-Z])\s*[.::、))-]\s*(.+)$", re.IGNORECASE)
+
+
+def parse_options(options: list[str]) -> dict[str, str]:
+ """Map option strings to ``{label: body}``.
+
+ ``"C: the answer"`` → ``{"C": "the answer"}``; a bare single character
+ ``"C"`` maps to itself (a label-only registration); anything else gets a
+ positional label (A, B, C, … then 27, 28, … past Z).
+ """
+ result: dict[str, str] = {}
+ for idx, raw in enumerate(options):
+ text = str(raw or "").strip()
+ if not text:
+ continue
+ match = OPTION_PREFIX_RE.match(text)
+ if match:
+ result[match.group(1).upper()] = match.group(2).strip()
+ elif len(text) == 1 and text.isalnum():
+ result[text.upper()] = text
+ else:
+ result[chr(ord("A") + idx) if idx < 26 else str(idx + 1)] = text
+ return result
+
+
+def has_option_bodies(options: dict[str, str]) -> bool:
+ """Whether a choice map holds real answer text, not only A/B/C labels."""
+ return len(options) >= 2 and all(
+ value.strip() and value.strip().upper() != key.upper() for key, value in options.items()
+ )
+
+
+def format_options(options: dict[str, str]) -> list[str]:
+ """Render a ``{label: body}`` map back to canonical ``"label: body"`` strings."""
+ return [f"{label}: {body}" for label, body in options.items()]
+
+
+def resolve_answer(expected_answer: str, options: dict[str, str]) -> str:
+ """Resolve a model-supplied choice answer to its stable option label.
+
+ Models occasionally send ``"Step 6"`` or the full option text even though
+ the interactive card returns ``"C"``. Resolve a unique textual match at
+ registration time so deterministic grading compares like with like. Returns
+ ``""`` when nothing matches or the match is ambiguous.
+ """
+ expected = str(expected_answer or "").strip()
+ if not expected:
+ return ""
+
+ key = expected.upper()
+ if key in options:
+ return key
+
+ prefix_match = OPTION_PREFIX_RE.match(expected)
+ if prefix_match and prefix_match.group(1).upper() in options:
+ return prefix_match.group(1).upper()
+
+ needle = expected.casefold()
+ exact = [label for label, text in options.items() if text.casefold() == needle]
+ if len(exact) == 1:
+ return exact[0]
+ contained = [label for label, text in options.items() if needle in text.casefold()]
+ return contained[0] if len(contained) == 1 else ""
+
+
+def _normalized_prompt(value: str) -> str:
+ """Alphanumeric-only, case-folded form for tolerant prompt matching."""
+ return "".join(char.casefold() for char in str(value or "") if char.isalnum())
+
+
+async def recover_options_from_turn(store: Any, turn_id: str, question: str) -> dict[str, str]:
+ """Recover choice bodies from the most recent matching ``ask_user`` card.
+
+ A compatibility fallback for questions registered by older versions, where
+ ``mastery_quiz`` persisted only ``["A", "B", ...]`` even though the full
+ descriptions were present in the turn's ``ask_user`` event. ``store`` is
+ injected so this stays decoupled from the session layer.
+ """
+ if not turn_id or not hasattr(store, "get_turn_events"):
+ return {}
+ try:
+ events = await store.get_turn_events(turn_id)
+ except Exception:
+ logger.warning("Failed to load turn events for mastery option recovery", exc_info=True)
+ return {}
+
+ target = _normalized_prompt(question)
+ for event in reversed(events):
+ if event.get("type") != "tool_call":
+ continue
+ metadata = event.get("metadata") or {}
+ if metadata.get("tool_name") != "ask_user":
+ continue
+ for item in reversed((metadata.get("args") or {}).get("questions") or []):
+ if not isinstance(item, dict):
+ continue
+ recovered = {
+ str(option.get("label") or "").strip().upper(): str(
+ option.get("description") or ""
+ ).strip()
+ for option in (item.get("options") or [])
+ if isinstance(option, dict)
+ and str(option.get("label") or "").strip()
+ and str(option.get("description") or "").strip()
+ }
+ if not has_option_bodies(recovered):
+ continue
+ prompt = _normalized_prompt(str(item.get("prompt") or ""))
+ if prompt == target or prompt.startswith(target) or target.startswith(prompt):
+ return recovered
+ return {}
diff --git a/deeptutor/capabilities/mastery/tools.py b/deeptutor/capabilities/mastery/tools.py
index 846597d60..023a96f38 100644
--- a/deeptutor/capabilities/mastery/tools.py
+++ b/deeptutor/capabilities/mastery/tools.py
@@ -17,10 +17,16 @@ from __future__ import annotations
import json
import logging
-import re
from typing import TYPE_CHECKING, Any
import uuid
+from deeptutor.capabilities.mastery.choices import (
+ format_options,
+ has_option_bodies,
+ parse_options,
+ recover_options_from_turn,
+ resolve_answer,
+)
from deeptutor.core.tool_protocol import BaseTool, ToolDefinition, ToolParameter, ToolResult
# ``learning.models`` and ``learning.policy`` only depend on pydantic — safe to
@@ -62,8 +68,6 @@ _QUESTION_TYPES = ("choice", "short", "open")
_ALLOWED_KP_TYPES = {t.value for t in KnowledgeType}
logger = logging.getLogger(__name__)
-_OPTION_PREFIX_RE = re.compile(r"^\s*([A-Z])\s*[.::、))-]\s*(.+)$", re.IGNORECASE)
-
def _new_service() -> LearningService:
from deeptutor.learning.service import LearningService
@@ -93,108 +97,28 @@ def _question_bank_type(question_type: str) -> str:
return "short_answer"
-def _question_bank_options(options: list[str]) -> dict[str, str]:
- result: dict[str, str] = {}
- for idx, raw in enumerate(options):
- text = str(raw or "").strip()
- if not text:
- continue
- match = _OPTION_PREFIX_RE.match(text)
- if match:
- key = match.group(1).upper()
- result[key] = match.group(2).strip()
- elif len(text) == 1 and text.isalnum():
- key = text.upper()
- result[key] = text
- else:
- key = chr(ord("A") + idx) if idx < 26 else str(idx + 1)
- result[key] = text
- return result
-
-
-def _has_choice_option_bodies(options: dict[str, str]) -> bool:
- """Whether a choice map contains real answer text, not only A/B/C labels."""
- return len(options) >= 2 and all(
- value.strip() and value.strip().upper() != key.upper() for key, value in options.items()
- )
-
+async def _resolve_pending_choice(
+ pending: PendingQuestion, turn_id: str
+) -> tuple[dict[str, str], str]:
+ """Resolve a pending choice question's ``({label: body}, expected_label)``.
-def _normalized_choice_prompt(value: str) -> str:
- return "".join(char.casefold() for char in str(value or "") if char.isalnum())
-
-
-def _resolve_choice_answer(expected_answer: str, options: dict[str, str]) -> str:
- """Resolve a model-supplied choice answer to its stable option label.
-
- Models occasionally send ``"Step 6"`` or the full option text even though
- the interactive card returns ``"C"``. Resolve a unique textual match at
- registration time so deterministic grading compares like with like.
- """
- expected = str(expected_answer or "").strip()
- key = expected.upper()
- if key in options:
- return key
- if not expected:
- return ""
-
- prefix_match = _OPTION_PREFIX_RE.match(expected)
- if prefix_match and prefix_match.group(1).upper() in options:
- return prefix_match.group(1).upper()
-
- needle = expected.casefold()
- exact = [label for label, text in options.items() if text.casefold() == needle]
- if len(exact) == 1:
- return exact[0]
- contained = [label for label, text in options.items() if needle in text.casefold()]
- return contained[0] if len(contained) == 1 else ""
-
-
-async def _recover_choice_options_from_turn(
- store: Any,
- turn_id: str,
- question: str,
-) -> dict[str, str]:
- """Recover choice descriptions from the most recent matching ask_user card.
-
- This is a compatibility fallback for questions registered by older
- versions, where ``mastery_quiz`` persisted only ``["A", "B", ...]`` even
- though the full descriptions were present in the turn's ``ask_user``
- event.
+ Re-parses the bodies stored at registration; for legacy paths that stored
+ only ``["A", "B", ...]`` it recovers the real bodies from the turn's
+ ``ask_user`` event. The expected answer is normalised to a stable label
+ when it resolves, else left as registered.
"""
- if not turn_id or not hasattr(store, "get_turn_events"):
- return {}
- try:
- events = await store.get_turn_events(turn_id)
- except Exception:
- logger.warning("Failed to load turn events for mastery option recovery", exc_info=True)
- return {}
+ options = parse_options(list(pending.options or []))
+ if not has_option_bodies(options):
+ try:
+ from deeptutor.services.session import get_sqlite_session_store
- target = _normalized_choice_prompt(question)
- for event in reversed(events):
- if event.get("type") != "tool_call":
- continue
- metadata = event.get("metadata") or {}
- if metadata.get("tool_name") != "ask_user":
- continue
- questions = (metadata.get("args") or {}).get("questions") or []
- for item in reversed(questions):
- if not isinstance(item, dict):
- continue
- recovered = {
- str(option.get("label") or "").strip().upper(): str(
- option.get("description") or ""
- ).strip()
- for option in (item.get("options") or [])
- if isinstance(option, dict)
- and str(option.get("label") or "").strip()
- and str(option.get("description") or "").strip()
- }
- if not _has_choice_option_bodies(recovered):
- continue
- prompt = _normalized_choice_prompt(str(item.get("prompt") or ""))
- if prompt == target or prompt.startswith(target) or target.startswith(prompt):
- return recovered
- return {}
+ options = await recover_options_from_turn(
+ get_sqlite_session_store(), turn_id, pending.prompt
+ )
+ except Exception:
+ logger.warning("Failed to recover legacy mastery choice options", exc_info=True)
+ options = {}
+ return options, resolve_answer(pending.expected_answer, options) or pending.expected_answer
async def _sync_mastery_attempt_to_question_bank(
@@ -214,7 +138,7 @@ async def _sync_mastery_attempt_to_question_bank(
"question_id": pending.question_id,
"question": pending.prompt,
"question_type": _question_bank_type(pending.question_type),
- "options": choice_options or _question_bank_options(list(pending.options or [])),
+ "options": choice_options or parse_options(list(pending.options or [])),
"correct_answer": correct_answer or pending.expected_answer,
"explanation": "",
"difficulty": "",
@@ -366,8 +290,8 @@ class MasteryQuizTool(BaseTool):
q_type = "short"
options = [str(o) for o in (kwargs.get("options") or []) if str(o).strip()]
if q_type == "choice":
- choice_options = _question_bank_options(options)
- if not _has_choice_option_bodies(choice_options):
+ choice_options = parse_options(options)
+ if not has_option_bodies(choice_options):
return ToolResult(
content=(
"Choice questions need full option bodies in mastery_quiz.options "
@@ -377,7 +301,7 @@ class MasteryQuizTool(BaseTool):
),
success=False,
)
- resolved_expected = _resolve_choice_answer(expected, choice_options)
+ resolved_expected = resolve_answer(expected, choice_options)
if not resolved_expected:
return ToolResult(
content=(
@@ -388,7 +312,7 @@ class MasteryQuizTool(BaseTool):
success=False,
)
expected = resolved_expected
- options = [f"{key}: {text}" for key, text in choice_options.items()]
+ options = format_options(choice_options)
service = _new_service()
progress = service.get_or_create(path_id)
@@ -466,21 +390,9 @@ class MasteryGradeTool(BaseTool):
choice_options: dict[str, str] = {}
expected_answer = pending.expected_answer
if pending.question_type == "choice":
- choice_options = _question_bank_options(list(pending.options or []))
- if not _has_choice_option_bodies(choice_options):
- try:
- from deeptutor.services.session import get_sqlite_session_store
-
- choice_options = await _recover_choice_options_from_turn(
- get_sqlite_session_store(),
- _resolve_turn_id(kwargs),
- pending.prompt,
- )
- except Exception:
- logger.warning("Failed to recover legacy mastery choice options", exc_info=True)
- resolved_expected = _resolve_choice_answer(expected_answer, choice_options)
- if resolved_expected:
- expected_answer = resolved_expected
+ choice_options, expected_answer = await _resolve_pending_choice(
+ pending, _resolve_turn_id(kwargs)
+ )
is_correct = service.grade_and_record(
progress,
diff --git a/deeptutor/learning/tests/test_mastery_choices.py b/deeptutor/learning/tests/test_mastery_choices.py
new file mode 100644
index 000000000..b5064e5d9
--- /dev/null
+++ b/deeptutor/learning/tests/test_mastery_choices.py
@@ -0,0 +1,177 @@
+"""Unit tests for the choice-question data contract
+(:mod:`deeptutor.capabilities.mastery.choices`).
+
+These exercise the pure option-handling rules in isolation — parsing, body
+validation, answer normalisation, and legacy recovery — independent of the
+tool/engine wiring that :mod:`test_mastery_tools` drives end to end."""
+
+from __future__ import annotations
+
+import pytest
+
+from deeptutor.capabilities.mastery.choices import (
+ format_options,
+ has_option_bodies,
+ parse_options,
+ recover_options_from_turn,
+ resolve_answer,
+)
+
+# ── parse_options ────────────────────────────────────────────────────────────
+
+
+def test_parse_options_reads_labelled_bodies():
+ assert parse_options(["A: first", "B) second", "C、third"]) == {
+ "A": "first",
+ "B": "second",
+ "C": "third",
+ }
+
+
+def test_parse_options_keeps_bare_labels_for_legacy_data():
+ assert parse_options(["A", "B", "C", "D"]) == {"A": "A", "B": "B", "C": "C", "D": "D"}
+
+
+def test_parse_options_assigns_positional_labels_to_unprefixed_text():
+ assert parse_options(["first answer", "second answer"]) == {
+ "A": "first answer",
+ "B": "second answer",
+ }
+
+
+def test_parse_options_skips_blank_entries():
+ assert parse_options(["A: keep", " ", ""]) == {"A": "keep"}
+
+
+# ── has_option_bodies ────────────────────────────────────────────────────────
+
+
+def test_has_option_bodies_true_for_real_text():
+ assert has_option_bodies({"A": "first", "B": "second"}) is True
+
+
+def test_has_option_bodies_false_for_bare_labels():
+ assert has_option_bodies({"A": "A", "B": "B"}) is False
+
+
+def test_has_option_bodies_false_when_fewer_than_two():
+ assert has_option_bodies({"A": "only one"}) is False
+
+
+# ── format_options ───────────────────────────────────────────────────────────
+
+
+def test_format_options_round_trips_with_parse():
+ options = {"A": "first", "B": "second"}
+ assert parse_options(format_options(options)) == options
+
+
+# ── resolve_answer ───────────────────────────────────────────────────────────
+
+
+def test_resolve_answer_accepts_direct_label():
+ assert resolve_answer("C", {"A": "x", "B": "y", "C": "z"}) == "C"
+
+
+def test_resolve_answer_strips_label_prefix():
+ assert resolve_answer("C: the answer", {"A": "x", "C": "the answer"}) == "C"
+
+
+def test_resolve_answer_matches_full_body_exactly():
+ assert (
+ resolve_answer(
+ "Step 6 — add the stop condition",
+ {
+ "A": "Step 2 — write the first tool",
+ "C": "Step 6 — add the stop condition",
+ },
+ )
+ == "C"
+ )
+
+
+def test_resolve_answer_matches_unique_substring():
+ assert (
+ resolve_answer(
+ "Step 6",
+ {
+ "A": "Step 2 — write the first tool",
+ "C": "Step 6 — add the stop condition",
+ },
+ )
+ == "C"
+ )
+
+
+def test_resolve_answer_blank_when_ambiguous():
+ assert resolve_answer("Step", {"A": "Step 2", "B": "Step 6"}) == ""
+
+
+def test_resolve_answer_blank_when_empty():
+ assert resolve_answer("", {"A": "x", "B": "y"}) == ""
+
+
+# ── recover_options_from_turn ────────────────────────────────────────────────
+
+
+class _FakeStore:
+ def __init__(self, events):
+ self._events = events
+
+ async def get_turn_events(self, turn_id, after_seq=0):
+ return self._events
+
+
+def _ask_user_event(prompt, options):
+ return {
+ "type": "tool_call",
+ "metadata": {
+ "tool_name": "ask_user",
+ "args": {"questions": [{"prompt": prompt, "options": options}]},
+ },
+ }
+
+
+async def test_recover_options_from_turn_pulls_bodies_from_ask_user():
+ store = _FakeStore(
+ [
+ _ask_user_event(
+ "Where is the stop condition added?",
+ [
+ {"label": "A", "description": "Step 2"},
+ {"label": "B", "description": "Step 4"},
+ {"label": "C", "description": "Step 6"},
+ ],
+ )
+ ]
+ )
+ recovered = await recover_options_from_turn(
+ store, "turn_1", "Where is the stop condition added?"
+ )
+ assert recovered == {"A": "Step 2", "B": "Step 4", "C": "Step 6"}
+
+
+async def test_recover_options_from_turn_ignores_non_matching_prompt():
+ store = _FakeStore(
+ [
+ _ask_user_event(
+ "An unrelated question",
+ [{"label": "A", "description": "x"}, {"label": "B", "description": "y"}],
+ )
+ ]
+ )
+ assert await recover_options_from_turn(store, "turn_1", "Different prompt") == {}
+
+
+async def test_recover_options_from_turn_handles_missing_capability_and_errors():
+ assert await recover_options_from_turn(object(), "turn_1", "q") == {}
+
+ class _Raising:
+ async def get_turn_events(self, turn_id, after_seq=0):
+ raise RuntimeError("boom")
+
+ assert await recover_options_from_turn(_Raising(), "turn_1", "q") == {}
+ assert await recover_options_from_turn(_FakeStore([]), "", "q") == {}
diff --git a/deeptutor/partners/channels/mattermost.py b/deeptutor/partners/channels/mattermost.py
new file mode 100644
index 000000000..38f9bd8bc
--- /dev/null
+++ b/deeptutor/partners/channels/mattermost.py
@@ -0,0 +1,440 @@
+"""Mattermost channel implementation using the native v4 WebSocket + REST API.
+
+Mattermost is a self-hostable, open-source team chat platform. This channel
+talks to its *own* API (``/api/v4/websocket`` for events, ``/api/v4`` REST for
+sending), so self-hosted deployments get a first-class integration instead of
+routing through Mattermost's Slack-compatibility shim.
+
+Transport mirrors the Discord channel — ``httpx`` for REST and ``websockets``
+for the event stream — so no extra dependency is needed. Keepalive relies on
+the standard WebSocket ping/pong (Mattermost has no app-level heartbeat opcode,
+unlike Discord's gateway), and Mattermost renders Markdown natively, so replies
+need no format conversion (unlike Slack's mrkdwn).
+"""
+
+from __future__ import annotations
+
+import asyncio
+import json
+from pathlib import Path
+import re
+import ssl
+from typing import Any, Literal
+
+import httpx
+from loguru import logger
+from pydantic import Field
+import websockets
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels.base import BaseChannel
+from deeptutor.partners.config.paths import get_media_dir
+from deeptutor.partners.config.schema import DeliveryOverrides
+from deeptutor.partners.helpers import split_message
+
+MATTERMOST_API_PATH = "/api/v4"
+# Mattermost's default max post length is 16383 chars; stay safely under it.
+MAX_MESSAGE_LEN = 16000
+# Mattermost's default max file size is 50MB.
+MAX_ATTACHMENT_BYTES = 50 * 1024 * 1024
+# Standard WebSocket keepalive — the lib pings, the server pongs.
+WS_PING_INTERVAL_S = 30.0
+WS_PING_TIMEOUT_S = 30.0
+# Posts are bounded text; bump the frame cap above the 1MB default for headroom.
+WS_MAX_MESSAGE_BYTES = 8 * 1024 * 1024
+WS_RECONNECT_DELAY_S = 5.0
+
+
+class MattermostConfig(DeliveryOverrides):
+ """Mattermost channel configuration."""
+
+ enabled: bool = False
+ # Base server URL, e.g. ``https://mattermost.example.com`` (scheme optional).
+ server_url: str = ""
+ # Bot account personal access token (Integrations → Bot Accounts).
+ bot_token: str = Field(default="", repr=False)
+ allow_from: list[str] = Field(default_factory=list)
+ # In multi-user channels, respond only when @-mentioned, or to every message.
+ group_policy: Literal["mention", "open"] = "mention"
+ reply_in_thread: bool = True
+ # Self-hosted servers may use a self-signed cert; allow opting out of verify.
+ verify_ssl: bool = True
+
+
+class MattermostChannel(BaseChannel):
+ """Mattermost channel using the native v4 WebSocket event stream."""
+
+ name = "mattermost"
+ display_name = "Mattermost"
+
+ @classmethod
+ def default_config(cls) -> dict[str, Any]:
+ return MattermostConfig().model_dump(by_alias=True)
+
+ def __init__(self, config: Any, bus: MessageBus):
+ if isinstance(config, dict):
+ config = MattermostConfig.model_validate(config)
+ super().__init__(config, bus)
+ self.config: MattermostConfig = config
+ self._api_base = self._api_base_url(self.config.server_url)
+ self._http: httpx.AsyncClient | None = None
+ self._ws: websockets.WebSocketClientProtocol | None = None
+ self._bot_user_id: str | None = None
+ self._bot_username: str = ""
+
+ # ── URL helpers (pure, testable) ──────────────────────────────────
+
+ @staticmethod
+ def _normalize_base_url(server_url: str) -> str:
+ """Strip trailing slashes and default to https when no scheme is given."""
+ base = (server_url or "").strip().rstrip("/")
+ if not base:
+ return ""
+ if not base.startswith(("http://", "https://")):
+ base = f"https://{base}"
+ return base
+
+ @classmethod
+ def _api_base_url(cls, server_url: str) -> str:
+ base = cls._normalize_base_url(server_url)
+ return f"{base}{MATTERMOST_API_PATH}" if base else ""
+
+ @classmethod
+ def _websocket_url(cls, server_url: str) -> str:
+ base = cls._normalize_base_url(server_url)
+ if not base:
+ return ""
+ if base.startswith("https://"):
+ ws_base = "wss://" + base[len("https://") :]
+ else:
+ ws_base = "ws://" + base[len("http://") :]
+ return f"{ws_base}{MATTERMOST_API_PATH}/websocket"
+
+ # ── Lifecycle ─────────────────────────────────────────────────────
+
+ async def start(self) -> None:
+ """Connect to the Mattermost WebSocket, reconnecting on drop."""
+ if not self.config.server_url or not self.config.bot_token:
+ logger.error("Mattermost serverUrl/botToken not configured")
+ return
+
+ self._running = True
+ self._http = httpx.AsyncClient(
+ headers={"Authorization": f"Bearer {self.config.bot_token}"},
+ timeout=30.0,
+ verify=self.config.verify_ssl,
+ )
+
+ ws_url = self._websocket_url(self.config.server_url)
+ connect_kwargs = self._ws_connect_kwargs(ws_url)
+
+ while self._running:
+ try:
+ # Resolve our own identity first — we must know it to skip our
+ # own posts (echo loop) and to detect @-mentions.
+ if not await self._ensure_bot_identity():
+ if self._running:
+ await asyncio.sleep(WS_RECONNECT_DELAY_S)
+ continue
+
+ logger.info("Connecting to Mattermost WebSocket {}...", ws_url)
+ async with websockets.connect(ws_url, **connect_kwargs) as ws:
+ self._ws = ws
+ await self._authenticate()
+ logger.info("Mattermost WebSocket connected as @{}", self._bot_username)
+ await self._event_loop()
+ except asyncio.CancelledError:
+ break
+ except Exception as e:
+ logger.warning("Mattermost WebSocket error: {}", e)
+ finally:
+ self._ws = None
+
+ if self._running:
+ logger.info("Reconnecting to Mattermost in {}s...", WS_RECONNECT_DELAY_S)
+ await asyncio.sleep(WS_RECONNECT_DELAY_S)
+
+ async def stop(self) -> None:
+ """Stop the channel and release the WebSocket + HTTP client."""
+ self._running = False
+ if self._ws:
+ try:
+ await self._ws.close()
+ except Exception as e:
+ logger.warning("Mattermost WebSocket close failed: {}", e)
+ self._ws = None
+ if self._http:
+ await self._http.aclose()
+ self._http = None
+
+ def _ws_connect_kwargs(self, ws_url: str) -> dict[str, Any]:
+ kwargs: dict[str, Any] = {
+ "ping_interval": WS_PING_INTERVAL_S,
+ "ping_timeout": WS_PING_TIMEOUT_S,
+ "max_size": WS_MAX_MESSAGE_BYTES,
+ }
+ if ws_url.startswith("wss://") and not self.config.verify_ssl:
+ ctx = ssl.create_default_context()
+ ctx.check_hostname = False
+ ctx.verify_mode = ssl.CERT_NONE
+ kwargs["ssl"] = ctx
+ return kwargs
+
+ async def _ensure_bot_identity(self) -> bool:
+ """Resolve the bot's user id / username via REST (validates the token)."""
+ if self._bot_user_id:
+ return True
+ if not self._http:
+ return False
+ try:
+ resp = await self._http.get(f"{self._api_base}/users/me")
+ resp.raise_for_status()
+ me = resp.json()
+ self._bot_user_id = me.get("id")
+ self._bot_username = me.get("username") or ""
+ logger.info(
+ "Mattermost bot identity: @{} ({})", self._bot_username, self._bot_user_id
+ )
+ return bool(self._bot_user_id)
+ except Exception as e:
+ logger.error("Mattermost: failed to resolve bot identity via /users/me: {}", e)
+ return False
+
+ async def _authenticate(self) -> None:
+ """Send the WebSocket auth challenge with the bot token."""
+ if not self._ws:
+ return
+ await self._ws.send(
+ json.dumps(
+ {
+ "seq": 1,
+ "action": "authentication_challenge",
+ "data": {"token": self.config.bot_token},
+ }
+ )
+ )
+
+ # ── Inbound ───────────────────────────────────────────────────────
+
+ async def _event_loop(self) -> None:
+ """Read events until the socket closes; dispatch ``posted`` events."""
+ if not self._ws:
+ return
+ async for raw in self._ws:
+ try:
+ data = json.loads(raw)
+ except (json.JSONDecodeError, TypeError):
+ logger.debug("Mattermost: non-JSON frame ignored")
+ continue
+ if data.get("event") != "posted":
+ continue
+ try:
+ await self._handle_posted(data.get("data") or {})
+ except Exception:
+ logger.exception("Mattermost: error handling posted event")
+
+ async def _handle_posted(self, data: dict[str, Any]) -> None:
+ """Handle a ``posted`` event: filter, gate, then forward to the bus."""
+ raw_post = data.get("post")
+ if not isinstance(raw_post, str):
+ return
+ try:
+ post = json.loads(raw_post)
+ except json.JSONDecodeError:
+ return
+
+ # System messages (joins, header edits, …) carry a non-empty ``type``.
+ if post.get("type"):
+ return
+
+ user_id = str(post.get("user_id") or "")
+ channel_id = str(post.get("channel_id") or "")
+ if not user_id or not channel_id:
+ return
+ # Never react to our own posts — that would loop forever.
+ if self._bot_user_id and user_id == self._bot_user_id:
+ return
+ if not self.is_allowed(user_id):
+ return
+
+ channel_type = data.get("channel_type") or "" # D / O / P / G
+ is_direct = channel_type == "D"
+ message = post.get("message") or ""
+
+ if not is_direct and not self._should_respond_in_channel(message, data):
+ return
+
+ message = self._strip_bot_mention(message)
+
+ # Threading: a reply carries ``root_id``; a root post is its own thread.
+ reply_root = post.get("root_id") or ""
+ if self.config.reply_in_thread and not reply_root:
+ reply_root = str(post.get("id") or "")
+
+ media_paths = await self._download_files(post)
+
+ if not message and not media_paths:
+ return
+
+ # Thread-scoped session key for channel/group messages (DMs stay
+ # channel-scoped via the default key).
+ session_key = (
+ f"{self.name}:{channel_id}:{reply_root}" if reply_root and not is_direct else None
+ )
+
+ await self._handle_message(
+ sender_id=user_id,
+ chat_id=channel_id,
+ content=message or "[empty message]",
+ media=media_paths,
+ metadata={
+ "mattermost": {
+ "root_id": reply_root,
+ "channel_type": channel_type,
+ "post_id": post.get("id"),
+ },
+ },
+ session_key=session_key,
+ )
+
+ def _should_respond_in_channel(self, message: str, data: dict[str, Any]) -> bool:
+ """Apply the group-channel policy (open vs. mention-only)."""
+ if self.config.group_policy == "open":
+ return True
+ # "mention": the event carries a JSON-encoded list of mentioned user ids;
+ # fall back to scanning the rendered text for ``@username``.
+ if self._bot_user_id:
+ mentions = data.get("mentions")
+ if isinstance(mentions, str):
+ try:
+ if self._bot_user_id in json.loads(mentions):
+ return True
+ except json.JSONDecodeError:
+ pass
+ if self._bot_username and f"@{self._bot_username}" in message:
+ return True
+ return False
+
+ def _strip_bot_mention(self, text: str) -> str:
+ if not text or not self._bot_username:
+ return text
+ return re.sub(rf"@{re.escape(self._bot_username)}\b\s*", "", text).strip()
+
+ async def _download_files(self, post: dict[str, Any]) -> list[str]:
+ file_ids = post.get("file_ids") or []
+ if not file_ids or not self._http:
+ return []
+ media_dir = get_media_dir("mattermost")
+ paths: list[str] = []
+ for file_id in file_ids:
+ local = await self._download_file(str(file_id), media_dir)
+ if local:
+ paths.append(local)
+ return paths
+
+ async def _download_file(self, file_id: str, media_dir: Path) -> str | None:
+ assert self._http is not None
+ try:
+ info_resp = await self._http.get(f"{self._api_base}/files/{file_id}/info")
+ info_resp.raise_for_status()
+ info = info_resp.json()
+ name = info.get("name") or file_id
+ size = info.get("size") or 0
+ if size and size > MAX_ATTACHMENT_BYTES:
+ logger.warning("Mattermost attachment too large, skipping: {}", name)
+ return None
+
+ data_resp = await self._http.get(f"{self._api_base}/files/{file_id}")
+ data_resp.raise_for_status()
+
+ media_dir.mkdir(parents=True, exist_ok=True)
+ safe_name = re.sub(r"[^\w.\-]", "_", name).strip("._") or file_id
+ dest = media_dir / f"{file_id}_{safe_name}"
+ dest.write_bytes(data_resp.content)
+ return str(dest)
+ except Exception as e:
+ logger.warning("Mattermost: failed to download attachment {}: {}", file_id, e)
+ return None
+
+ # ── Outbound ──────────────────────────────────────────────────────
+
+ async def send(self, msg: OutboundMessage) -> None:
+ """Send a message through Mattermost, threading and uploading as needed.
+
+ Raises on text-post failure so the channel manager's retry policy
+ applies; per-file upload failures stay best-effort.
+ """
+ if not self._http:
+ logger.warning("Mattermost HTTP client not running")
+ return
+
+ meta = msg.metadata.get("mattermost", {}) if msg.metadata else {}
+ root_id = meta.get("root_id") or ""
+
+ # Upload attachments first; the first post carries their file ids.
+ file_ids: list[str] = []
+ for media_path in msg.media or []:
+ file_id = await self._upload_file(msg.chat_id, media_path)
+ if file_id:
+ file_ids.append(file_id)
+
+ chunks = split_message(msg.content or "", MAX_MESSAGE_LEN)
+ if not chunks:
+ if not file_ids:
+ return
+ chunks = [""] # media-only message still needs one post to carry files
+
+ for i, chunk in enumerate(chunks):
+ await self._create_post(
+ msg.chat_id,
+ chunk,
+ root_id=root_id,
+ file_ids=file_ids if i == 0 else None,
+ )
+
+ async def _create_post(
+ self,
+ channel_id: str,
+ message: str,
+ *,
+ root_id: str = "",
+ file_ids: list[str] | None = None,
+ ) -> None:
+ assert self._http is not None
+ payload: dict[str, Any] = {"channel_id": channel_id, "message": message}
+ if root_id:
+ payload["root_id"] = root_id
+ if file_ids:
+ payload["file_ids"] = file_ids
+ resp = await self._http.post(f"{self._api_base}/posts", json=payload)
+ resp.raise_for_status()
+
+ async def _upload_file(self, channel_id: str, file_path: str) -> str | None:
+ assert self._http is not None
+ path = Path(file_path)
+ if not path.is_file():
+ logger.warning("Mattermost file not found, skipping: {}", file_path)
+ return None
+ if path.stat().st_size > MAX_ATTACHMENT_BYTES:
+ logger.warning(
+ "Mattermost file too large (>{}MB), skipping: {}",
+ MAX_ATTACHMENT_BYTES // (1024 * 1024),
+ path.name,
+ )
+ return None
+ try:
+ with open(path, "rb") as f:
+ files = {"files": (path.name, f, "application/octet-stream")}
+ resp = await self._http.post(
+ f"{self._api_base}/files",
+ params={"channel_id": channel_id},
+ files=files,
+ )
+ resp.raise_for_status()
+ infos = resp.json().get("file_infos") or []
+ if infos:
+ return infos[0].get("id")
+ except Exception as e:
+ logger.error("Mattermost file upload failed for {}: {}", path.name, e)
+ return None
diff --git a/tests/services/partners/test_mattermost_channel.py b/tests/services/partners/test_mattermost_channel.py
new file mode 100644
index 000000000..d1528dd5f
--- /dev/null
+++ b/tests/services/partners/test_mattermost_channel.py
@@ -0,0 +1,360 @@
+"""Unit tests for the Mattermost channel implementation."""
+
+from __future__ import annotations
+
+import json
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+
+from deeptutor.partners.bus.events import OutboundMessage
+from deeptutor.partners.bus.queue import MessageBus
+from deeptutor.partners.channels import mattermost as mm_module
+from deeptutor.partners.channels.mattermost import MattermostChannel, MattermostConfig
+
+
+def _make_channel(**overrides) -> MattermostChannel:
+ defaults = {
+ "enabled": True,
+ "server_url": "https://mm.example.com",
+ "bot_token": "tok-123",
+ "allow_from": ["*"],
+ "group_policy": "mention",
+ "reply_in_thread": True,
+ }
+ defaults.update(overrides)
+ config = MattermostConfig.model_validate(defaults)
+ bus = MagicMock(spec=MessageBus)
+ bus.publish_inbound = AsyncMock()
+ ch = MattermostChannel(config, bus)
+ ch._bot_user_id = "bot-id"
+ ch._bot_username = "tutor"
+ return ch
+
+
+def _event(post: dict, *, channel_type: str = "O", mentions: list[str] | None = None) -> dict:
+ data: dict = {"post": json.dumps(post), "channel_type": channel_type}
+ if mentions is not None:
+ data["mentions"] = json.dumps(mentions)
+ return data
+
+
+def _post(**overrides) -> dict:
+ base = {
+ "id": "post-1",
+ "channel_id": "chan-1",
+ "user_id": "user-9",
+ "message": "hello",
+ "root_id": "",
+ "type": "",
+ }
+ base.update(overrides)
+ return base
+
+
+def _ok_http() -> AsyncMock:
+ """An AsyncMock httpx client whose responses pass ``raise_for_status``."""
+ http = AsyncMock()
+ resp = MagicMock()
+ resp.raise_for_status = MagicMock()
+ resp.json = MagicMock(return_value={"file_infos": [{"id": "file-xyz"}]})
+ http.post = AsyncMock(return_value=resp)
+ return http
+
+
+class TestMattermostConfig:
+ def test_default_values(self):
+ cfg = MattermostConfig()
+ assert cfg.enabled is False
+ assert cfg.server_url == ""
+ assert cfg.bot_token == ""
+ assert cfg.allow_from == []
+ assert cfg.group_policy == "mention"
+ assert cfg.reply_in_thread is True
+ assert cfg.verify_ssl is True
+
+ def test_bot_token_repr_hidden(self):
+ cfg = MattermostConfig(bot_token="super-secret")
+ assert cfg.bot_token == "super-secret"
+ assert "super-secret" not in repr(cfg)
+
+ def test_camel_case_alias_roundtrip(self):
+ cfg = MattermostConfig(server_url="https://x", bot_token="t")
+ dumped = cfg.model_dump(by_alias=True)
+ assert "serverUrl" in dumped
+ assert "botToken" in dumped
+ assert "groupPolicy" in dumped
+
+ def test_from_camel_case_dict(self):
+ cfg = MattermostConfig.model_validate(
+ {
+ "enabled": True,
+ "serverUrl": "https://mm.example.com",
+ "botToken": "t",
+ "allowFrom": ["*"],
+ "groupPolicy": "open",
+ "replyInThread": False,
+ }
+ )
+ assert cfg.server_url == "https://mm.example.com"
+ assert cfg.bot_token == "t"
+ assert cfg.group_policy == "open"
+ assert cfg.reply_in_thread is False
+
+
+class TestDefaultConfig:
+ def test_returns_dict(self):
+ cfg = MattermostChannel.default_config()
+ assert isinstance(cfg, dict)
+ assert cfg["enabled"] is False
+ assert "serverUrl" in cfg
+ assert "botToken" in cfg
+
+
+class TestUrlHelpers:
+ def test_api_base_https(self):
+ assert MattermostChannel._api_base_url("https://mm.example.com") == (
+ "https://mm.example.com/api/v4"
+ )
+
+ def test_api_base_strips_trailing_slash(self):
+ assert MattermostChannel._api_base_url("https://mm.example.com/") == (
+ "https://mm.example.com/api/v4"
+ )
+
+ def test_ws_url_https_to_wss(self):
+ assert MattermostChannel._websocket_url("https://mm.example.com") == (
+ "wss://mm.example.com/api/v4/websocket"
+ )
+
+ def test_ws_url_http_to_ws(self):
+ assert MattermostChannel._websocket_url("http://localhost:8065") == (
+ "ws://localhost:8065/api/v4/websocket"
+ )
+
+ def test_no_scheme_defaults_https(self):
+ assert MattermostChannel._websocket_url("mm.example.com") == (
+ "wss://mm.example.com/api/v4/websocket"
+ )
+
+ def test_empty_url(self):
+ assert MattermostChannel._api_base_url("") == ""
+ assert MattermostChannel._websocket_url("") == ""
+
+
+class TestIsAllowed:
+ def test_wildcard_allows_all(self):
+ assert _make_channel(allow_from=["*"]).is_allowed("anyone") is True
+
+ def test_empty_denies_all(self):
+ assert _make_channel(allow_from=[]).is_allowed("anyone") is False
+
+ def test_specific_match(self):
+ ch = _make_channel(allow_from=["user-9"])
+ assert ch.is_allowed("user-9") is True
+ assert ch.is_allowed("user-x") is False
+
+
+class TestStripBotMention:
+ def test_removes_leading_mention(self):
+ ch = _make_channel()
+ assert ch._strip_bot_mention("@tutor what is 2+2?") == "what is 2+2?"
+
+ def test_no_username_noop(self):
+ ch = _make_channel()
+ ch._bot_username = ""
+ assert ch._strip_bot_mention("@tutor hi") == "@tutor hi"
+
+
+class TestShouldRespondInChannel:
+ def test_open_policy_always_true(self):
+ ch = _make_channel(group_policy="open")
+ assert ch._should_respond_in_channel("no mention here", {}) is True
+
+ def test_mention_via_mentions_list(self):
+ ch = _make_channel(group_policy="mention")
+ data = {"mentions": json.dumps(["bot-id"])}
+ assert ch._should_respond_in_channel("hey", data) is True
+
+ def test_mention_via_text(self):
+ ch = _make_channel(group_policy="mention")
+ assert ch._should_respond_in_channel("hi @tutor", {}) is True
+
+ def test_no_mention_false(self):
+ ch = _make_channel(group_policy="mention")
+ assert ch._should_respond_in_channel("just chatting", {}) is False
+
+
+class TestHandlePosted:
+ async def test_channel_mention_forwarded(self):
+ ch = _make_channel(group_policy="mention")
+ await ch._handle_posted(_event(_post(message="@tutor explain"), mentions=["bot-id"]))
+ ch.bus.publish_inbound.assert_awaited_once()
+ msg = ch.bus.publish_inbound.call_args[0][0]
+ assert msg.channel == "mattermost"
+ assert msg.sender_id == "user-9"
+ assert msg.chat_id == "chan-1"
+ assert msg.content == "explain"
+ # Root post → thread root is its own id; channel msgs get a thread key.
+ assert msg.metadata["mattermost"]["root_id"] == "post-1"
+ assert msg.session_key == "mattermost:chan-1:post-1"
+
+ async def test_dm_bypasses_group_policy(self):
+ ch = _make_channel(group_policy="mention")
+ await ch._handle_posted(_event(_post(message="no mention"), channel_type="D"))
+ ch.bus.publish_inbound.assert_awaited_once()
+ msg = ch.bus.publish_inbound.call_args[0][0]
+ # DMs use the default channel-scoped session key (no thread suffix).
+ assert msg.session_key == "mattermost:chan-1"
+
+ async def test_own_message_skipped(self):
+ ch = _make_channel()
+ await ch._handle_posted(_event(_post(user_id="bot-id"), channel_type="D"))
+ ch.bus.publish_inbound.assert_not_awaited()
+
+ async def test_system_message_skipped(self):
+ ch = _make_channel()
+ await ch._handle_posted(
+ _event(_post(type="system_join_channel"), channel_type="D")
+ )
+ ch.bus.publish_inbound.assert_not_awaited()
+
+ async def test_disallowed_sender_skipped(self):
+ ch = _make_channel(allow_from=["someone-else"])
+ await ch._handle_posted(_event(_post(), channel_type="D"))
+ ch.bus.publish_inbound.assert_not_awaited()
+
+ async def test_unmentioned_channel_message_skipped(self):
+ ch = _make_channel(group_policy="mention")
+ await ch._handle_posted(_event(_post(message="just chatting"), channel_type="O"))
+ ch.bus.publish_inbound.assert_not_awaited()
+
+ async def test_reply_keeps_existing_thread_root(self):
+ ch = _make_channel(group_policy="open")
+ await ch._handle_posted(_event(_post(root_id="root-7"), channel_type="O"))
+ msg = ch.bus.publish_inbound.call_args[0][0]
+ assert msg.metadata["mattermost"]["root_id"] == "root-7"
+ assert msg.session_key == "mattermost:chan-1:root-7"
+
+ async def test_no_thread_when_reply_in_thread_disabled(self):
+ ch = _make_channel(group_policy="open", reply_in_thread=False)
+ await ch._handle_posted(_event(_post(), channel_type="O"))
+ msg = ch.bus.publish_inbound.call_args[0][0]
+ assert msg.metadata["mattermost"]["root_id"] == ""
+ # No thread root → default channel-scoped session key.
+ assert msg.session_key == "mattermost:chan-1"
+
+ async def test_malformed_post_ignored(self):
+ ch = _make_channel()
+ await ch._handle_posted({"post": "not-json"})
+ await ch._handle_posted({}) # no post key
+ ch.bus.publish_inbound.assert_not_awaited()
+
+
+class TestSend:
+ async def test_text_post_with_thread(self):
+ ch = _make_channel()
+ ch._http = _ok_http()
+ msg = OutboundMessage(
+ channel="mattermost",
+ chat_id="chan-1",
+ content="answer",
+ metadata={"mattermost": {"root_id": "root-7"}},
+ )
+ await ch.send(msg)
+ ch._http.post.assert_awaited_once()
+ url = ch._http.post.call_args[0][0]
+ body = ch._http.post.call_args.kwargs["json"]
+ assert url.endswith("/api/v4/posts")
+ assert body == {"channel_id": "chan-1", "message": "answer", "root_id": "root-7"}
+
+ async def test_long_message_split(self, monkeypatch):
+ monkeypatch.setattr(mm_module, "MAX_MESSAGE_LEN", 10)
+ ch = _make_channel()
+ ch._http = _ok_http()
+ await ch.send(OutboundMessage(channel="mattermost", chat_id="c", content="x" * 25))
+ assert ch._http.post.await_count == 3
+
+ async def test_media_only_sends_empty_post_with_files(self):
+ ch = _make_channel()
+ ch._http = _ok_http()
+ ch._upload_file = AsyncMock(return_value="file-1")
+ await ch.send(
+ OutboundMessage(channel="mattermost", chat_id="c", content="", media=["/tmp/a.png"])
+ )
+ body = ch._http.post.call_args.kwargs["json"]
+ assert body["message"] == ""
+ assert body["file_ids"] == ["file-1"]
+
+ async def test_files_only_on_first_chunk(self, monkeypatch):
+ monkeypatch.setattr(mm_module, "MAX_MESSAGE_LEN", 10)
+ ch = _make_channel()
+ ch._http = _ok_http()
+ ch._upload_file = AsyncMock(return_value="file-1")
+ await ch.send(
+ OutboundMessage(
+ channel="mattermost", chat_id="c", content="x" * 25, media=["/tmp/a.png"]
+ )
+ )
+ first_body = ch._http.post.await_args_list[0].kwargs["json"]
+ second_body = ch._http.post.await_args_list[1].kwargs["json"]
+ assert first_body["file_ids"] == ["file-1"]
+ assert "file_ids" not in second_body
+
+ async def test_empty_message_no_media_is_noop(self):
+ ch = _make_channel()
+ ch._http = _ok_http()
+ await ch.send(OutboundMessage(channel="mattermost", chat_id="c", content=""))
+ ch._http.post.assert_not_awaited()
+
+ async def test_post_failure_propagates_for_retry(self):
+ ch = _make_channel()
+ http = _ok_http()
+ http.post.return_value.raise_for_status.side_effect = RuntimeError("500")
+ ch._http = http
+ with pytest.raises(RuntimeError):
+ await ch.send(OutboundMessage(channel="mattermost", chat_id="c", content="hi"))
+
+ async def test_no_client_is_noop(self):
+ ch = _make_channel()
+ ch._http = None
+ # Should not raise even though the client isn't running.
+ await ch.send(OutboundMessage(channel="mattermost", chat_id="c", content="hi"))
+
+
+class TestUploadFile:
+ async def test_uploads_existing_file(self, tmp_path):
+ f = tmp_path / "a.txt"
+ f.write_text("data")
+ ch = _make_channel()
+ ch._http = _ok_http()
+ file_id = await ch._upload_file("chan-1", str(f))
+ assert file_id == "file-xyz"
+ assert ch._http.post.call_args[0][0].endswith("/api/v4/files")
+ assert ch._http.post.call_args.kwargs["params"] == {"channel_id": "chan-1"}
+
+ async def test_missing_file_returns_none(self):
+ ch = _make_channel()
+ ch._http = _ok_http()
+ assert await ch._upload_file("chan-1", "/nope/missing.txt") is None
+ ch._http.post.assert_not_awaited()
+
+ async def test_oversize_file_skipped(self, tmp_path, monkeypatch):
+ monkeypatch.setattr(mm_module, "MAX_ATTACHMENT_BYTES", 1)
+ f = tmp_path / "big.bin"
+ f.write_bytes(b"xx")
+ ch = _make_channel()
+ ch._http = _ok_http()
+ assert await ch._upload_file("chan-1", str(f)) is None
+ ch._http.post.assert_not_awaited()
+
+
+class TestDownloadFiles:
+ async def test_no_file_ids_returns_empty(self):
+ ch = _make_channel()
+ ch._http = _ok_http()
+ assert await ch._download_files(_post()) == []
diff --git a/web/components/partners/ChannelIcon.tsx b/web/components/partners/ChannelIcon.tsx
index a047e32d1..1f038fa4a 100644
--- a/web/components/partners/ChannelIcon.tsx
+++ b/web/components/partners/ChannelIcon.tsx
@@ -24,6 +24,10 @@ const BRAND_PATHS: Record<string, { hex: string; path: string }> = {
hex: "#5865F2",
path: "M20.317 4.3698a19.7913 19.7913 0 00-4.8851-1.5152.0741.0741 0 00-.0785.0371c-.211.3753-.4447.8648-.6083 1.2495-1.8447-.2762-3.68-.2762-5.4868 0-.1636-.3933-.4058-.8742-.6177-1.2495a.077.077 0 00-.0785-.037 19.7363 19.7363 0 00-4.8852 1.515.0699.0699 0 00-.0321.0277C.5334 9.0458-.319 13.5799.0992 18.0578a.0824.0824 0 00.0312.0561c2.0528 1.5076 4.0413 2.4228 5.9929 3.0294a.0777.0777 0 00.0842-.0276c.4616-.6304.8731-1.2952 1.226-1.9942a.076.076 0 00-.0416-.1057c-.6528-.2476-1.2743-.5495-1.8722-.8923a.077.077 0 01-.0076-.1277c.1258-.0943.2517-.1923.3718-.2914a.0743.0743 0 01.0776-.0105c3.9278 1.7933 8.18 1.7933 12.0614 0a.0739.0739 0 01.0785.0095c.1202.099.246.1981.3728.2924a.077.077 0 01-.0066.1276 12.2986 12.2986 0 01-1.873.8914.0766.0766 0 00-.0407.1067c.3604.698.7719 1.3628 1.225 1.9932a.076.076 0 00.0842.0286c1.961-.6067 3.9495-1.5219 6.0023-3.0294a.077.077 0 00.0313-.0552c.5004-5.177-.8382-9.6739-3.5485-13.6604a.061.061 0 00-.0312-.0286zM8.02 15.3312c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9555-2.4189 2.157-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.9555 2.4189-2.1569 2.4189zm7.9748 0c-1.1825 0-2.1569-1.0857-2.1569-2.419 0-1.3332.9554-2.4189 2.1569-2.4189 1.2108 0 2.1757 1.0952 2.1568 2.419 0 1.3332-.946 2.4189-2.1568 2.4189Z",
},
+ mattermost: {
+ hex: "#0058CC",
+ path: "M12.081 0C7.048-.034 2.339 3.125.637 8.153c-2.125 6.276 1.24 13.086 7.516 15.21 6.276 2.125 13.086-1.24 15.21-7.516 1.727-5.1-.172-10.552-4.311-13.557l.126 2.547c2.065 2.282 2.88 5.512 1.852 8.549-1.534 4.532-6.594 6.915-11.3 5.321-4.708-1.593-7.28-6.559-5.745-11.092 1.031-3.046 3.655-5.121 6.694-5.67l1.642-1.94A4.87 4.87 0 0 0 12.08 0zm3.528 1.094a.284.284 0 0 0-.123.024l-.004.001a.33.33 0 0 0-.109.071c-.145.142-.657.828-.657.828L13.6 3.4l-1.3 1.585-2.232 2.776s-1.024 1.278-.798 2.851c.226 1.574 1.396 2.34 2.304 2.648.907.307 2.302.408 3.438-.704 1.135-1.112 1.098-2.75 1.098-2.75l-.087-3.56-.07-2.05-.047-1.775s.01-.856-.02-1.057a.33.33 0 0 0-.035-.107l-.006-.012-.007-.011a.277.277 0 0 0-.229-.14z",
+ },
matrix: {
hex: "#000000",
path: "M.632.55v22.9H2.28V24H0V0h2.28v.55zm7.043 7.26v1.157h.033c.309-.443.683-.784 1.117-1.024.433-.245.936-.365 1.5-.365.54 0 1.033.107 1.481.314.448.208.785.582 1.02 1.108.254-.374.6-.706 1.034-.992.434-.287.95-.43 1.546-.43.453 0 .872.056 1.26.167.388.11.716.286.993.53.276.245.489.559.646.951.152.392.23.863.23 1.417v5.728h-2.349V11.52c0-.286-.01-.559-.032-.812a1.755 1.755 0 0 0-.18-.66 1.106 1.106 0 0 0-.438-.448c-.194-.11-.457-.166-.785-.166-.332 0-.6.064-.803.189a1.38 1.38 0 0 0-.48.499 1.946 1.946 0 0 0-.231.696 5.56 5.56 0 0 0-.06.785v4.768h-2.35v-4.8c0-.254-.004-.503-.018-.752a2.074 2.074 0 0 0-.143-.688 1.052 1.052 0 0 0-.415-.503c-.194-.125-.476-.19-.854-.19-.111 0-.259.024-.439.074-.18.051-.36.143-.53.282-.171.138-.319.337-.439.595-.12.259-.18.6-.18 1.02v4.966H5.46V7.81zm15.693 15.64V.55H21.72V0H24v24h-2.28v-.55z",