Skip to main content

adk_surface/channels/matrix/
mod.rs

1//! The Matrix adapter (spec 3.5 §10 X12, on spec 3.3 §5.3): `/sync` long polling in,
2//! `m.room.message` out, reactions as answers.
3
4mod api;
5mod wire;
6
7use std::collections::{HashMap, HashSet, VecDeque};
8use std::fmt;
9use std::sync::{Arc, Mutex, PoisonError};
10use std::time::Duration;
11
12use adk_core::{AdkError, ErrorCategory, ErrorComponent};
13use adk_kernel::KernelError;
14use adk_kernel::channels::{
15    ChannelGateway, ChannelInbound, ChannelNotice, ChannelSink, DecisionCard, InboundBody,
16    StopNotice,
17};
18use async_trait::async_trait;
19use chrono::Utc;
20use reqwest::Method;
21use serde_json::{Value, json};
22use tokio::sync::mpsc;
23
24use super::shared::{
25    ANSWER_NOT_TAKEN, AbortOnDrop, ChannelConnection, HANDLING, Handling, Kit, MESSAGE_NOT_TAKEN,
26    PressedCard, Taker, Update, dispatch, kit_builder, notice_words, paired_binding, patient,
27    stopped_words,
28};
29use crate::error::{Result, SurfaceError};
30use api::{CALL, MatrixApi};
31use wire::CardRef;
32
33/// The channel the Matrix adapter serves, as the kernel names it: pairings, thread sessions
34/// and `kernel.channel` audit records carry it (spec 3.5 §10 X12).
35pub const MATRIX_CHANNEL: &str = "matrix";
36
37/// Matrix as a person reads it, in "You said yes in Matrix at 07:31" (spec 3.3 §8.1).
38pub const MATRIX: &str = "Matrix";
39
40/// How long one `/sync` waits for an event.
41const DEFAULT_POLL_TIMEOUT: Duration = Duration::from_secs(25);
42const MIN_BACKOFF: Duration = Duration::from_secs(1);
43const MAX_BACKOFF: Duration = Duration::from_secs(60);
44/// How many cards the adapter remembers; an older card is read back from the homeserver.
45const CARDS_KEPT: usize = 1024;
46/// The events `/sync` returns: a room's timeline and state, nothing about presence or
47/// account data.
48const FILTER: &str = r#"{"presence":{"types":[]},"account_data":{"types":[]},"room":{"ephemeral":{"types":[]},"account_data":{"types":[]},"timeline":{"limit":50}}}"#;
49
50/// Why the Matrix adapter could not talk to the homeserver (spec 3.5 §10 X12).
51///
52/// Never carries the access token. Converts into [`AdkError`] with a `surface.matrix.*` code
53/// and provider `matrix`.
54///
55/// # Example
56///
57/// ```rust
58/// use adk_surface::channels::MatrixError;
59///
60/// let error = MatrixError::Unauthorized;
61/// assert_eq!(error.code(), "surface.matrix.unauthorized");
62/// assert!(error.to_string().contains("MATRIX_ACCESS_TOKEN"));
63/// ```
64#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
65#[non_exhaustive]
66pub enum MatrixError {
67    /// The homeserver refused the access token.
68    #[error(
69        "the Matrix homeserver refused the access token: check MATRIX_ACCESS_TOKEN, or log the \
70         bot account in again for a new one"
71    )]
72    Unauthorized,
73    /// The homeserver asked the account to slow down for longer than the adapter waits.
74    #[error(
75        "the Matrix homeserver asked to wait {retry_after_ms} ms before {endpoint}: the account is sending too much"
76    )]
77    RateLimited {
78        /// The endpoint, such as `rooms`.
79        endpoint: String,
80        /// How long the homeserver asked to wait, in milliseconds.
81        retry_after_ms: u64,
82    },
83    /// The homeserver refused the call, such as a room the account is not in.
84    #[error("the Matrix homeserver refused {endpoint} (HTTP {status}, {errcode}): {error}")]
85    Refused {
86        /// The endpoint, such as `rooms`.
87        endpoint: String,
88        /// The HTTP status.
89        status: u16,
90        /// The Matrix error code, such as `M_FORBIDDEN`.
91        errcode: String,
92        /// The homeserver's description.
93        error: String,
94    },
95    /// The homeserver could not be reached.
96    #[error(
97        "the Matrix homeserver could not be reached for {endpoint}: {reason}; check the \
98         network and MATRIX_HOMESERVER"
99    )]
100    Unreachable {
101        /// The endpoint.
102        endpoint: String,
103        /// What failed.
104        reason: String,
105    },
106    /// The homeserver's answer was not the API's JSON.
107    #[error("the Matrix homeserver's answer to {endpoint} could not be read: {reason}")]
108    InvalidResponse {
109        /// The endpoint.
110        endpoint: String,
111        /// What was wrong with it.
112        reason: String,
113    },
114}
115
116impl MatrixError {
117    /// The error code: `surface.matrix.unauthorized`, `.rate_limited`, `.refused`,
118    /// `.unreachable` or `.invalid_response`.
119    pub fn code(&self) -> &'static str {
120        match self {
121            Self::Unauthorized => "surface.matrix.unauthorized",
122            Self::RateLimited { .. } => "surface.matrix.rate_limited",
123            Self::Refused { .. } => "surface.matrix.refused",
124            Self::Unreachable { .. } => "surface.matrix.unreachable",
125            Self::InvalidResponse { .. } => "surface.matrix.invalid_response",
126        }
127    }
128}
129
130impl From<MatrixError> for AdkError {
131    fn from(error: MatrixError) -> Self {
132        let category = match &error {
133            MatrixError::Unauthorized => ErrorCategory::Unauthorized,
134            MatrixError::RateLimited { .. } => ErrorCategory::RateLimited,
135            MatrixError::Refused { status: 403, .. } => ErrorCategory::Forbidden,
136            MatrixError::Refused { status: 404, .. } => ErrorCategory::NotFound,
137            MatrixError::Refused { status: 400, .. } => ErrorCategory::InvalidInput,
138            MatrixError::Refused { .. } | MatrixError::Unreachable { .. } => {
139                ErrorCategory::Unavailable
140            }
141            MatrixError::InvalidResponse { .. } => ErrorCategory::Internal,
142        };
143        AdkError::new(ErrorComponent::Server, category, error.code(), error.to_string())
144            .with_provider("matrix")
145    }
146}
147
148impl From<MatrixError> for KernelError {
149    fn from(error: MatrixError) -> Self {
150        Self::Core(error.into())
151    }
152}
153
154/// The `/sync` long polling a [`MatrixAdapter::start`] runs; dropping it stops it.
155pub type MatrixSync = ChannelConnection<MatrixError>;
156
157/// Builds a [`MatrixAdapter`].
158pub struct MatrixAdapterBuilder {
159    homeserver: String,
160    token: String,
161    user_id: Option<String>,
162    poll_timeout: Duration,
163    kit: Kit,
164}
165
166impl fmt::Debug for MatrixAdapterBuilder {
167    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
168        f.debug_struct("MatrixAdapterBuilder")
169            .field("homeserver", &self.homeserver)
170            .field("poll_timeout", &self.poll_timeout)
171            .finish_non_exhaustive()
172    }
173}
174
175impl MatrixAdapterBuilder {
176    /// The account's user id, such as `@agents:example.org`; asked of the homeserver
177    /// (`/account/whoami`) when the adapter starts when not set.
178    #[must_use]
179    pub fn user_id(mut self, user_id: impl Into<String>) -> Self {
180        self.user_id = Some(user_id.into());
181        self
182    }
183
184    /// How long one `/sync` waits for an event, at least a second; defaults to 25 s.
185    #[must_use]
186    pub fn poll_timeout(mut self, timeout: Duration) -> Self {
187        self.poll_timeout = timeout.max(Duration::from_secs(1));
188        self
189    }
190
191    kit_builder!("Matrix");
192
193    /// The adapter.
194    ///
195    /// # Errors
196    ///
197    /// Returns `surface.invalid` for an empty or malformed token, or a homeserver address
198    /// that is not `https` (or `http` on loopback).
199    pub fn build(self) -> Result<MatrixAdapter> {
200        let api = MatrixApi::new(&self.homeserver, &self.token).map_err(SurfaceError::Invalid)?;
201        Ok(MatrixAdapter {
202            inner: Arc::new(Inner {
203                api,
204                kit: self.kit,
205                poll_timeout: self.poll_timeout,
206                me: Mutex::new(self.user_id),
207                rooms: Mutex::default(),
208            }),
209        })
210    }
211}
212
213/// The Matrix adapter (spec 3.5 §10 X12): a Matrix account's direct chats as the person's
214/// chat thread with their agents, over the kernel's channel contract (spec 3.3 §10 K1).
215///
216/// It is the gateway's [`ChannelSink`] for the channel [`MATRIX_CHANNEL`], and
217/// [`start`](Self::start) reads the account's rooms by `/sync` long polling with the `since`
218/// token — no inbound port — and hands each event to [`ChannelGateway::receive`].
219///
220/// | Direction | What |
221/// |---|---|
222/// | Out | A card as `m.room.message`: "Waiting for you · since 18:00", the call in plain words, the agent and the risk, its answers as reaction keys — "To answer, react 👍 Allow once · 👎 Deny" — with the adapter's own reactions on it to tap, and "Open in home"; never the call's arguments (S-I5). Every `formatted_body` escapes what it shows; agent replies have a plain `body` only (S-I9) |
223/// | In | New text messages in a direct chat the account was invited to and joined, and reactions. Matrix has no buttons: only an `m.reaction` annotation from the account paired from that room, on one of the adapter's cards, with one of the keys the card offers, answers it; typed text never does (S-I4). Typed text loses the characters a chat app shows as nothing (S-I6) |
224/// | Rooms | Unencrypted direct chats only: an encrypted room is told once to use an unencrypted direct chat, and nothing in it reaches an agent. Rooms with more than two members are ignored. Events from before the adapter started are not read |
225/// | Commands | "stop all" and `/stop` stop everything; resuming is refused (S-I10) |
226///
227/// # Example
228///
229/// ```rust,no_run
230/// use std::sync::Arc;
231/// use adk_kernel::channels::{ChannelDoorbell, ChannelGateway, InMemoryChannelBindingStore};
232/// use adk_surface::channels::MatrixAdapter;
233///
234/// # async fn example(kernel: adk_kernel::Kernel, doorbell: Arc<ChannelDoorbell>) -> Result<(), Box<dyn std::error::Error>> {
235/// let matrix = MatrixAdapter::builder(std::env::var("MATRIX_HOMESERVER")?, std::env::var("MATRIX_ACCESS_TOKEN")?).build()?;
236/// let gateway = ChannelGateway::builder(Arc::new(kernel), Arc::new(InMemoryChannelBindingStore::new()))
237///     .sink(Arc::new(matrix.clone()))
238///     .home_url("http://127.0.0.1:8080/ui/")
239///     .doorbell(doorbell)
240///     .build();
241/// gateway.start().await?;
242/// let sync = matrix.start(gateway);
243/// sync.join().await?;
244/// # Ok(())
245/// # }
246/// ```
247#[derive(Clone)]
248pub struct MatrixAdapter {
249    inner: Arc<Inner>,
250}
251
252struct Inner {
253    api: MatrixApi,
254    kit: Kit,
255    poll_timeout: Duration,
256    /// The account's own user id.
257    me: Mutex<Option<String>>,
258    rooms: Mutex<Rooms>,
259}
260
261/// What an event carries beyond its inbound value.
262pub(crate) struct Carried {
263    /// The card a reaction annotates.
264    card: Option<String>,
265    /// The image an `m.image` event names.
266    files: Vec<crate::channels::media::FileRef>,
267}
268
269/// What the adapter knows of its rooms and cards.
270#[derive(Default)]
271struct Rooms {
272    /// Rooms whose events are encrypted.
273    encrypted: HashSet<String>,
274    /// Encrypted rooms already told to use an unencrypted chat.
275    told: HashSet<String>,
276    /// Rooms with more than two members.
277    groups: HashSet<String>,
278    /// The cards sent, by event id, newest last.
279    cards: HashMap<String, CardRef>,
280    order: VecDeque<String>,
281}
282
283impl Rooms {
284    fn keep(&mut self, event: String, card: CardRef) {
285        if self.cards.insert(event.clone(), card).is_none() {
286            self.order.push_back(event);
287        }
288        while self.order.len() > CARDS_KEPT {
289            if let Some(oldest) = self.order.pop_front() {
290                self.cards.remove(&oldest);
291            }
292        }
293    }
294}
295
296impl fmt::Debug for MatrixAdapter {
297    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
298        f.debug_struct("MatrixAdapter").field("channel", &MATRIX_CHANNEL).finish_non_exhaustive()
299    }
300}
301
302impl MatrixAdapter {
303    /// An adapter for the account with access token `token` on `homeserver`, such as
304    /// `https://matrix.example.org`.
305    pub fn builder(
306        homeserver: impl Into<String>,
307        token: impl Into<String>,
308    ) -> MatrixAdapterBuilder {
309        MatrixAdapterBuilder {
310            homeserver: homeserver.into(),
311            token: token.into(),
312            user_id: None,
313            poll_timeout: DEFAULT_POLL_TIMEOUT,
314            kit: Kit::default(),
315        }
316    }
317
318    fn rooms(&self) -> std::sync::MutexGuard<'_, Rooms> {
319        self.inner.rooms.lock().unwrap_or_else(PoisonError::into_inner)
320    }
321
322    fn me(&self) -> Option<String> {
323        self.inner.me.lock().unwrap_or_else(PoisonError::into_inner).clone()
324    }
325
326    /// What the adapter makes of one timeline event of `room` (spec 3.3 S-I4, S-I6): a typed
327    /// message, a reaction that answers one of its cards, or `None` for anything the gateway
328    /// is not given. A card the adapter no longer remembers is read back from the
329    /// homeserver, and counts only when the adapter's own account sent it.
330    ///
331    /// # Example
332    ///
333    /// ```rust
334    /// use adk_kernel::channels::InboundBody;
335    /// use adk_surface::channels::MatrixAdapter;
336    ///
337    /// # #[tokio::main(flavor = "current_thread")]
338    /// # async fn main() {
339    /// let matrix = MatrixAdapter::builder("https://matrix.example.org", "syt_example").build().unwrap();
340    /// let event = serde_json::json!({
341    ///     "type": "m.room.message",
342    ///     "sender": "@ana:example.org",
343    ///     "event_id": "$1",
344    ///     "content": { "msgtype": "m.text", "body": "stop all" },
345    /// });
346    /// let inbound = matrix.inbound("!dm:example.org", &event).await.unwrap();
347    /// assert_eq!(inbound.body, InboundBody::Text { text: "stop all".into() });
348    /// assert_eq!(inbound.thread, "!dm:example.org");
349    /// # }
350    /// ```
351    pub async fn inbound(&self, room: &str, event: &Value) -> Option<ChannelInbound> {
352        if event["type"] == "m.reaction" {
353            let (card, _) = wire::reaction(event)?;
354            let card = self.card(room, &card).await?;
355            return wire::answer(room, event, &card);
356        }
357        wire::typed(room, event, self.me().as_deref())
358    }
359
360    /// What the card `event` in `room` answers: remembered, or read back when the adapter's
361    /// own account sent it.
362    async fn card(&self, room: &str, event: &str) -> Option<CardRef> {
363        if let Some(card) = self.rooms().cards.get(event).cloned() {
364            return Some(card);
365        }
366        let me = self.me()?;
367        let path = ["rooms", room, "event", event];
368        let fetched = self.inner.api.call(Method::GET, &path, &[], None, CALL, true).await;
369        let fetched = match fetched {
370            Ok(fetched) => fetched,
371            Err(error) => {
372                tracing::debug!(error = %error, "a reacted-to matrix event could not be read");
373                return None;
374            }
375        };
376        if fetched["sender"].as_str() != Some(me.as_str()) {
377            return None;
378        }
379        let card = wire::card_ref(&fetched["content"])?;
380        self.rooms().keep(event.to_string(), card.clone());
381        Some(card)
382    }
383
384    /// Reads the account's rooms by `/sync` long polling and hands each event to `gateway`,
385    /// which must have this adapter as its sink, until [`MatrixSync::stop`].
386    ///
387    /// The first `/sync` only takes the position to read from, so nothing sent before the
388    /// adapter started is read. The account joins a room it is invited to as a direct chat
389    /// and no other. A paired account's events go to the gateway first, each account's in the
390    /// order sent (S-I6, S-I10); one the gateway fails on is taken again only when it is a
391    /// paired account's and the failure may clear. Transport failures are retried with
392    /// backoff; a refused token ends the polling with [`MatrixError::Unauthorized`].
393    pub fn start(&self, gateway: ChannelGateway) -> MatrixSync {
394        let adapter = self.clone();
395        ChannelConnection::spawn(async move { adapter.run(gateway).await })
396    }
397
398    async fn run(&self, gateway: ChannelGateway) -> std::result::Result<(), MatrixError> {
399        let mut backoff = MIN_BACKOFF;
400        let me = loop {
401            if let Some(me) = self.me() {
402                break me;
403            }
404            match self
405                .inner
406                .api
407                .call(Method::GET, &["account", "whoami"], &[], None, CALL, true)
408                .await
409            {
410                Ok(whoami) => {
411                    if let Some(me) = whoami["user_id"].as_str() {
412                        *self.inner.me.lock().unwrap_or_else(PoisonError::into_inner) =
413                            Some(me.to_string());
414                    }
415                }
416                Err(MatrixError::Unauthorized) => return Err(MatrixError::Unauthorized),
417                Err(error) => {
418                    tracing::warn!(error = %error, "the matrix account could not be read; retrying");
419                    tokio::time::sleep(backoff).await;
420                    backoff = (backoff * 2).min(MAX_BACKOFF);
421                }
422            }
423        };
424        let (sender, task) = dispatch(Arc::new(self.clone()), gateway);
425        let _dispatcher = AbortOnDrop(task);
426        let mut since: Option<String> = None;
427        let timeout = self.inner.poll_timeout.as_millis().to_string();
428        loop {
429            let mut query = vec![("timeout", timeout.as_str()), ("filter", FILTER)];
430            if let Some(since) = &since {
431                query.push(("since", since.as_str()));
432            }
433            let wait = self.inner.poll_timeout + CALL;
434            let batch = match self
435                .inner
436                .api
437                .call(Method::GET, &["sync"], &query, None, wait, false)
438                .await
439            {
440                Ok(batch) => {
441                    backoff = MIN_BACKOFF;
442                    batch
443                }
444                Err(MatrixError::Unauthorized) => return Err(MatrixError::Unauthorized),
445                Err(MatrixError::RateLimited { retry_after_ms, .. }) => {
446                    tokio::time::sleep(Duration::from_millis(retry_after_ms.max(100))).await;
447                    continue;
448                }
449                Err(error) => {
450                    tracing::warn!(error = %error, "reading matrix rooms failed; retrying");
451                    tokio::time::sleep(backoff).await;
452                    backoff = (backoff * 2).min(MAX_BACKOFF);
453                    continue;
454                }
455            };
456            let first = since.is_none();
457            if let Some(next) = batch["next_batch"].as_str() {
458                since = Some(next.to_string());
459            }
460            self.take_batch(&batch, first, &me, &sender).await;
461        }
462    }
463
464    /// Joins the direct chats the account was invited to, notes encrypted rooms and rooms of
465    /// more than two, and hands every new event of the others over.
466    async fn take_batch(
467        &self,
468        batch: &Value,
469        first: bool,
470        me: &str,
471        sender: &mpsc::UnboundedSender<Update<Carried>>,
472    ) {
473        let rooms = &batch["rooms"];
474        for (room, invite) in rooms["invite"].as_object().into_iter().flatten() {
475            let state = invite["invite_state"]["events"].as_array().cloned().unwrap_or_default();
476            let direct = state.iter().any(|event| {
477                event["type"] == "m.room.member"
478                    && event["state_key"] == me
479                    && event["content"]["is_direct"] == true
480            });
481            if !direct {
482                tracing::debug!("a matrix invite to a room that is not a direct chat was left");
483                continue;
484            }
485            if state.iter().any(|event| event["type"] == "m.room.encryption") {
486                self.rooms().encrypted.insert(room.clone());
487            }
488            if let Err(error) = self
489                .inner
490                .api
491                .call(Method::POST, &["join", room], &[], Some(&json!({})), CALL, true)
492                .await
493            {
494                tracing::warn!(error = %error, "a matrix direct chat could not be joined");
495            }
496        }
497        for (room, joined) in rooms["join"].as_object().into_iter().flatten() {
498            let timeline = joined["timeline"]["events"].as_array().cloned().unwrap_or_default();
499            let state = joined["state"]["events"].as_array().cloned().unwrap_or_default();
500            let encrypted = {
501                let mut rooms = self.rooms();
502                if state.iter().chain(&timeline).any(|event| event["type"] == "m.room.encryption") {
503                    rooms.encrypted.insert(room.clone());
504                }
505                match joined["summary"]["m.joined_member_count"].as_u64() {
506                    Some(count) if count > 2 => {
507                        rooms.groups.insert(room.clone());
508                    }
509                    Some(_) => {
510                        rooms.groups.remove(room);
511                    }
512                    None => {}
513                }
514                rooms.encrypted.contains(room)
515            };
516            if first {
517                continue;
518            }
519            let others: Vec<&Value> =
520                timeline.iter().filter(|event| event["sender"].as_str() != Some(me)).collect();
521            if encrypted {
522                let spoke = others.iter().any(|event| {
523                    matches!(event["type"].as_str(), Some("m.room.encrypted" | "m.room.message"))
524                });
525                if spoke && self.rooms().told.insert(room.clone()) {
526                    let notice = json!({ "msgtype": "m.notice", "body": wire::ENCRYPTED_ROOM });
527                    if let Err(error) = self.send(room, "m.room.message", &notice).await {
528                        tracing::debug!(error = %error, "an encrypted matrix room could not be told");
529                    }
530                }
531                continue;
532            }
533            if self.rooms().groups.contains(room) {
534                continue;
535            }
536            for event in others {
537                let Some(inbound) = self.inbound(room, event).await else { continue };
538                let card = wire::reaction(event).map(|(card, _)| card);
539                let files = wire::image(event).into_iter().collect();
540                let carried = Carried { card, files };
541                if sender.send(Update { inbound: Some(inbound), press: Some(carried) }).is_err() {
542                    return;
543                }
544            }
545        }
546    }
547
548    /// Sends `content` as an event of `kind` to `room`; returns its event id.
549    async fn send(&self, room: &str, kind: &str, content: &Value) -> adk_kernel::Result<String> {
550        let txn = uuid::Uuid::new_v4().simple().to_string();
551        // A rate limit on a reply to an account that is not paired is not waited out.
552        let patient = patient(MATRIX_CHANNEL, room);
553        let path = ["rooms", room, "send", kind, txn.as_str()];
554        let sent =
555            self.inner.api.call(Method::PUT, &path, &[], Some(content), CALL, patient).await?;
556        Ok(sent["event_id"].as_str().unwrap_or_default().to_string())
557    }
558}
559
560#[async_trait]
561impl Taker for MatrixAdapter {
562    /// The card a reaction annotates.
563    type Press = Carried;
564
565    fn channel_name(&self) -> &'static str {
566        MATRIX_CHANNEL
567    }
568
569    /// Hands one event to the gateway; a reaction counts only from the account paired from
570    /// the card's room.
571    async fn take(
572        &self,
573        gateway: &ChannelGateway,
574        update: &Update<Carried>,
575        paired: bool,
576    ) -> adk_kernel::Result<()> {
577        let Some(mut inbound) = update.inbound.clone() else { return Ok(()) };
578        let carried = update.press.as_ref();
579        // A paired account's images, for a host that takes them; a stranger's are never
580        // downloaded (spec 3.5 §10 X12).
581        let files = carried.map_or(&[][..], |carried| carried.files.as_slice());
582        if paired && !files.is_empty() {
583            let api = &self.inner.api;
584            let attachments =
585                crate::channels::media::fetch_all(files, |file| api.download(file)).await;
586            inbound = inbound.with_attachments(attachments);
587        }
588        let card = match &inbound.body {
589            InboundBody::Answer { decision, .. } => {
590                match paired_binding(gateway, MATRIX_CHANNEL, &inbound.account).await {
591                    Ok(Some(binding)) if binding.thread == inbound.thread => {}
592                    Ok(_) => {
593                        tracing::debug!(
594                            "a matrix reaction from an account not paired from its room was ignored"
595                        );
596                        return Ok(());
597                    }
598                    Err(()) => {
599                        return Err(KernelError::Core(AdkError::new(
600                            ErrorComponent::Server,
601                            ErrorCategory::Unavailable,
602                            "surface.matrix.pairing_unread",
603                            "the account's pairing could not be read",
604                        )));
605                    }
606                }
607                let card = carried.and_then(|carried| carried.card.clone());
608                Some(PressedCard { card, decision: decision.clone() })
609            }
610            _ => None,
611        };
612        let handling = Handling::of(MATRIX_CHANNEL, gateway, &inbound, paired, card);
613        HANDLING.scope(handling, gateway.receive(inbound)).await.map(drop)
614    }
615
616    async fn not_taken(&self, update: &Update<Carried>) {
617        let Some(inbound) = &update.inbound else { return };
618        let pressed = update.press.as_ref().is_some_and(|carried| carried.card.is_some());
619        let text = if pressed { ANSWER_NOT_TAKEN } else { MESSAGE_NOT_TAKEN };
620        for content in wire::plain(text) {
621            if let Err(error) = self.send(&inbound.thread, "m.room.message", &content).await {
622                tracing::debug!(error = %error, "a person could not be told their message was not taken");
623            }
624        }
625    }
626}
627
628#[async_trait]
629impl ChannelSink for MatrixAdapter {
630    fn channel(&self) -> &str {
631        MATRIX_CHANNEL
632    }
633
634    async fn send_message(&self, thread: &str, text: &str) -> adk_kernel::Result<()> {
635        for content in wire::plain(text) {
636            self.send(thread, "m.room.message", &content).await?;
637        }
638        Ok(())
639    }
640
641    /// Sends the card, remembers what it answers, and puts the adapter's own reaction with
642    /// each answer key on it, so the person has only to tap.
643    async fn send_decision(&self, thread: &str, card: &DecisionCard) -> adk_kernel::Result<()> {
644        let (heading, card) = self.inner.kit.prepare(card).await;
645        let (content, answers) = wire::card(&card, &heading, self.inner.kit.offset);
646        let event = self.send(thread, "m.room.message", &content).await?;
647        let Some(answers) = answers.filter(|_| !event.is_empty()) else { return Ok(()) };
648        let keys: Vec<String> = answers.answers.iter().map(|(key, _)| key.clone()).collect();
649        self.rooms().keep(event.clone(), answers);
650        for key in keys {
651            if let Err(error) = self.send(thread, "m.reaction", &wire::offer(&event, &key)).await {
652                tracing::debug!(error = %error, "a card's answer key could not be offered");
653            }
654        }
655        Ok(())
656    }
657
658    async fn send_stopped(&self, thread: &str, notice: &StopNotice) -> adk_kernel::Result<()> {
659        self.send(thread, "m.room.message", &wire::message(&stopped_words(notice))).await.map(drop)
660    }
661
662    /// A notice about an answered card records the answer with where it was given before the
663    /// confirmation is sent, as a reply to the card (spec 3.3 §8.1, §11).
664    async fn send_notice(&self, thread: &str, notice: &ChannelNotice) -> adk_kernel::Result<()> {
665        let card = self.inner.kit.before_notice(MATRIX_CHANNEL, MATRIX, thread, notice).await;
666        let words = notice_words(notice, self.inner.kit.offset, Utc::now(), card.is_some());
667        let mut content = wire::message(&words);
668        if let Some(card) = card.filter(|card| !card.is_empty()) {
669            content["m.relates_to"] = json!({ "m.in_reply_to": { "event_id": card } });
670        }
671        self.send(thread, "m.room.message", &content).await.map(drop)
672    }
673}
674
675#[cfg(test)]
676mod tests {
677    use super::*;
678
679    #[test]
680    fn errors_say_what_to_do_and_keep_their_category() {
681        let error: AdkError = MatrixError::Unauthorized.into();
682        assert_eq!(
683            (error.code, error.category),
684            ("surface.matrix.unauthorized", ErrorCategory::Unauthorized)
685        );
686        let forbidden = MatrixError::Refused {
687            endpoint: "rooms".into(),
688            status: 403,
689            errcode: "M_FORBIDDEN".into(),
690            error: "not in room".into(),
691        };
692        assert_eq!(AdkError::from(forbidden).category, ErrorCategory::Forbidden);
693    }
694
695    #[test]
696    fn the_builder_refuses_a_bad_token_or_address_without_echoing_the_token() {
697        let error =
698            MatrixAdapter::builder("http://matrix.example.org", "syt_secret").build().unwrap_err();
699        assert!(!error.to_string().contains("secret"), "{error}");
700        assert!(MatrixAdapter::builder("https://matrix.example.org", "").build().is_err());
701        let adapter =
702            MatrixAdapter::builder("https://matrix.example.org", "syt_secret").build().unwrap();
703        assert!(!format!("{adapter:?}").contains("secret"));
704        assert_eq!(ChannelSink::channel(&adapter), "matrix");
705    }
706
707    #[test]
708    fn the_adapter_remembers_its_newest_cards() {
709        let mut rooms = Rooms::default();
710        let card = CardRef { decision: "d".into(), version: 1, answers: Vec::new() };
711        for index in 0..CARDS_KEPT + 3 {
712            rooms.keep(format!("$e{index}"), card.clone());
713        }
714        assert_eq!(rooms.cards.len(), CARDS_KEPT);
715        assert!(
716            !rooms.cards.contains_key("$e0")
717                && rooms.cards.contains_key(&format!("$e{}", CARDS_KEPT + 2))
718        );
719    }
720}