atagen

macltok

public
Star0
Watch0
cbb715e119632f60c9b3ec1bc8803f1f33e39dce
3
ssh://brewery@pls.lobotomise.me:33/atagen/macltok.git

Blame: src/engine/timeline.rs

1fe480c16a3catagen2026-09-26 08:44 UTC1
use std::{collections::HashSet, future::Future, panic::AssertUnwindSafe, sync::Arc};
31ce2453c82fatagen2026-09-24 13:07 UTC2
31ce2453c82fatagen2026-09-24 13:07 UTC3
use futures_util::{FutureExt, StreamExt};
1fe480c16a3catagen2026-09-26 08:44 UTC4
use matrix_sdk::SendOutsideWasm;
31ce2453c82fatagen2026-09-24 13:07 UTC5
use matrix_sdk::{
31ce2453c82fatagen2026-09-24 13:07 UTC6
    room::edit::EditedContent,
31ce2453c82fatagen2026-09-24 13:07 UTC7
    room::reply::{EnforceThread, Reply as SdkReply},
31ce2453c82fatagen2026-09-24 13:07 UTC8
    ruma::{
31ce2453c82fatagen2026-09-24 13:07 UTC9
        api::client::receipt::create_receipt::v3::ReceiptType,
0827ad2d24e9atagen2026-10-23 06:49 UTC10
        events::room::message::{
0827ad2d24e9atagen2026-10-23 06:49 UTC11
            AddMentions, Relation, ReplyWithinThread, RoomMessageEventContentWithoutRelation,
31ce2453c82fatagen2026-09-24 13:07 UTC12
        },
31ce2453c82fatagen2026-09-24 13:07 UTC13
    },
31ce2453c82fatagen2026-09-24 13:07 UTC14
};
31ce2453c82fatagen2026-09-24 13:07 UTC15
use matrix_sdk_ui::timeline::{Timeline, TimelineEventItemId};
31ce2453c82fatagen2026-09-24 13:07 UTC16
use ruma::{OwnedEventId, OwnedUserId};
1fe480c16a3catagen2026-09-26 08:44 UTC17
use tokio::sync::mpsc;
31ce2453c82fatagen2026-09-24 13:07 UTC18
1fe480c16a3catagen2026-09-26 08:44 UTC19
use super::executor::{EngineBoxFuture, JoinHandle, TaskSet, spawn};
31ce2453c82fatagen2026-09-24 13:07 UTC20
use crate::{
960ac0721079atagen2026-09-25 00:24 UTC21
    Error, ErrorKind, Event, EventRef, HistoryState, MessageContent, MessageEditContent,
960ac0721079atagen2026-09-25 00:24 UTC22
    MessageMentions, RichText, TimelineCommand, TimelineId,
31ce2453c82fatagen2026-09-24 13:07 UTC23
    engine::MediaService,
31ce2453c82fatagen2026-09-24 13:07 UTC24
    normalise::{MediaScope, normalise_timeline, normalise_timeline_diffs},
31ce2453c82fatagen2026-09-24 13:07 UTC25
    transport::{EventSender, Responder, SendEventError},
0827ad2d24e9atagen2026-10-23 06:49 UTC26
    upload::sdk_mentions,
31ce2453c82fatagen2026-09-24 13:07 UTC27
};
31ce2453c82fatagen2026-09-24 13:07 UTC28
31ce2453c82fatagen2026-09-24 13:07 UTC29
const PAGINATION_QUEUE: usize = 32;
31ce2453c82fatagen2026-09-24 13:07 UTC30
31ce2453c82fatagen2026-09-24 13:07 UTC31
/// long-lived tasks inside a room actor report panics here so the actor can die loudly
31ce2453c82fatagen2026-09-24 13:07 UTC32
#[derive(Clone)]
31ce2453c82fatagen2026-09-24 13:07 UTC33
pub(super) struct Supervisor(mpsc::UnboundedSender<&'static str>);
31ce2453c82fatagen2026-09-24 13:07 UTC34
31ce2453c82fatagen2026-09-24 13:07 UTC35
impl Supervisor {
31ce2453c82fatagen2026-09-24 13:07 UTC36
    pub(super) fn new() -> (Self, mpsc::UnboundedReceiver<&'static str>) {
31ce2453c82fatagen2026-09-24 13:07 UTC37
        let (sender, receiver) = mpsc::unbounded_channel();
31ce2453c82fatagen2026-09-24 13:07 UTC38
        (Self(sender), receiver)
31ce2453c82fatagen2026-09-24 13:07 UTC39
    }
31ce2453c82fatagen2026-09-24 13:07 UTC40
31ce2453c82fatagen2026-09-24 13:07 UTC41
    pub(super) fn spawn(
31ce2453c82fatagen2026-09-24 13:07 UTC42
        &self,
31ce2453c82fatagen2026-09-24 13:07 UTC43
        label: &'static str,
1fe480c16a3catagen2026-09-26 08:44 UTC44
        task: impl Future<Output = ()> + SendOutsideWasm + 'static,
31ce2453c82fatagen2026-09-24 13:07 UTC45
    ) -> JoinHandle<()> {
31ce2453c82fatagen2026-09-24 13:07 UTC46
        let panics = self.0.clone();
1fe480c16a3catagen2026-09-26 08:44 UTC47
        spawn(async move {
31ce2453c82fatagen2026-09-24 13:07 UTC48
            if AssertUnwindSafe(task).catch_unwind().await.is_err() {
31ce2453c82fatagen2026-09-24 13:07 UTC49
                let _ = panics.send(label);
31ce2453c82fatagen2026-09-24 13:07 UTC50
            }
31ce2453c82fatagen2026-09-24 13:07 UTC51
        })
31ce2453c82fatagen2026-09-24 13:07 UTC52
    }
31ce2453c82fatagen2026-09-24 13:07 UTC53
}
31ce2453c82fatagen2026-09-24 13:07 UTC54
5a52012c9b1datagen2026-09-24 23:45 UTC55
/// aborts its task when dropped, so an actor that dies mid-flight takes its helpers with it
5a52012c9b1datagen2026-09-24 23:45 UTC56
pub(super) struct TaskGuard(pub(super) JoinHandle<()>);
5a52012c9b1datagen2026-09-24 23:45 UTC57
5a52012c9b1datagen2026-09-24 23:45 UTC58
impl Drop for TaskGuard {
5a52012c9b1datagen2026-09-24 23:45 UTC59
    fn drop(&mut self) {
5a52012c9b1datagen2026-09-24 23:45 UTC60
        self.0.abort();
5a52012c9b1datagen2026-09-24 23:45 UTC61
    }
5a52012c9b1datagen2026-09-24 23:45 UTC62
}
5a52012c9b1datagen2026-09-24 23:45 UTC63
31ce2453c82fatagen2026-09-24 13:07 UTC64
/// what a timeline session needs from the room that owns it
31ce2453c82fatagen2026-09-24 13:07 UTC65
#[derive(Clone)]
31ce2453c82fatagen2026-09-24 13:07 UTC66
pub(super) struct SessionContext {
31ce2453c82fatagen2026-09-24 13:07 UTC67
    pub(super) events: EventSender,
31ce2453c82fatagen2026-09-24 13:07 UTC68
    pub(super) media: Arc<MediaService>,
31ce2453c82fatagen2026-09-24 13:07 UTC69
    pub(super) current_user_id: Option<OwnedUserId>,
31ce2453c82fatagen2026-09-24 13:07 UTC70
    pub(super) initial_history_limit: u16,
31ce2453c82fatagen2026-09-24 13:07 UTC71
    pub(super) supervisor: Supervisor,
31ce2453c82fatagen2026-09-24 13:07 UTC72
}
31ce2453c82fatagen2026-09-24 13:07 UTC73
31ce2453c82fatagen2026-09-24 13:07 UTC74
pub(super) struct TimelineSession {
31ce2453c82fatagen2026-09-24 13:07 UTC75
    pub(super) id: TimelineId,
31ce2453c82fatagen2026-09-24 13:07 UTC76
    timeline: Arc<Timeline>,
31ce2453c82fatagen2026-09-24 13:07 UTC77
    context: SessionContext,
31ce2453c82fatagen2026-09-24 13:07 UTC78
    scope: MediaScope,
31ce2453c82fatagen2026-09-24 13:07 UTC79
    watcher: JoinHandle<()>,
31ce2453c82fatagen2026-09-24 13:07 UTC80
    pagination: mpsc::Sender<PaginationRequest>,
31ce2453c82fatagen2026-09-24 13:07 UTC81
    pagination_worker: JoinHandle<()>,
6ed8c0ef3a2aatagen2026-10-24 10:13 UTC82
    member_fetch: JoinHandle<()>,
31ce2453c82fatagen2026-09-24 13:07 UTC83
}
31ce2453c82fatagen2026-09-24 13:07 UTC84
31ce2453c82fatagen2026-09-24 13:07 UTC85
struct PaginationRequest {
31ce2453c82fatagen2026-09-24 13:07 UTC86
    limit: u16,
31ce2453c82fatagen2026-09-24 13:07 UTC87
    reply: Option<Responder>,
31ce2453c82fatagen2026-09-24 13:07 UTC88
}
31ce2453c82fatagen2026-09-24 13:07 UTC89
31ce2453c82fatagen2026-09-24 13:07 UTC90
impl TimelineSession {
31ce2453c82fatagen2026-09-24 13:07 UTC91
    pub(super) async fn start(
31ce2453c82fatagen2026-09-24 13:07 UTC92
        id: TimelineId,
31ce2453c82fatagen2026-09-24 13:07 UTC93
        timeline: Timeline,
31ce2453c82fatagen2026-09-24 13:07 UTC94
        context: SessionContext,
31ce2453c82fatagen2026-09-24 13:07 UTC95
    ) -> Result<Self, SendEventError> {
31ce2453c82fatagen2026-09-24 13:07 UTC96
        let timeline = Arc::new(timeline);
31ce2453c82fatagen2026-09-24 13:07 UTC97
        let scope = MediaScope::new();
31ce2453c82fatagen2026-09-24 13:07 UTC98
        let watcher = start_watcher(&id, &timeline, &context, &scope).await?;
31ce2453c82fatagen2026-09-24 13:07 UTC99
        let (pagination, requests) = mpsc::channel(PAGINATION_QUEUE);
31ce2453c82fatagen2026-09-24 13:07 UTC100
        let pagination_worker = context.supervisor.spawn(
31ce2453c82fatagen2026-09-24 13:07 UTC101
            "pagination worker",
31ce2453c82fatagen2026-09-24 13:07 UTC102
            run_pagination(
31ce2453c82fatagen2026-09-24 13:07 UTC103
                requests,
31ce2453c82fatagen2026-09-24 13:07 UTC104
                timeline.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC105
                context.events.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC106
                id.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC107
            ),
31ce2453c82fatagen2026-09-24 13:07 UTC108
        );
6ed8c0ef3a2aatagen2026-10-24 10:13 UTC109
        // under lazy-loaded members the sdk leaves sender profiles unavailable until someone
6ed8c0ef3a2aatagen2026-10-24 10:13 UTC110
        // asks, and a /members fetched any other way never reaches the timeline's items
6ed8c0ef3a2aatagen2026-10-24 10:13 UTC111
        let member_fetch = context.supervisor.spawn("member fetch", {
6ed8c0ef3a2aatagen2026-10-24 10:13 UTC112
            let timeline = timeline.clone();
6ed8c0ef3a2aatagen2026-10-24 10:13 UTC113
            async move { timeline.fetch_members().await }
6ed8c0ef3a2aatagen2026-10-24 10:13 UTC114
        });
31ce2453c82fatagen2026-09-24 13:07 UTC115
        let session = Self {
31ce2453c82fatagen2026-09-24 13:07 UTC116
            id,
31ce2453c82fatagen2026-09-24 13:07 UTC117
            timeline,
31ce2453c82fatagen2026-09-24 13:07 UTC118
            scope,
31ce2453c82fatagen2026-09-24 13:07 UTC119
            watcher,
31ce2453c82fatagen2026-09-24 13:07 UTC120
            pagination,
31ce2453c82fatagen2026-09-24 13:07 UTC121
            pagination_worker,
6ed8c0ef3a2aatagen2026-10-24 10:13 UTC122
            member_fetch,
31ce2453c82fatagen2026-09-24 13:07 UTC123
            context,
31ce2453c82fatagen2026-09-24 13:07 UTC124
        };
31ce2453c82fatagen2026-09-24 13:07 UTC125
        if session.context.initial_history_limit > 0 {
31ce2453c82fatagen2026-09-24 13:07 UTC126
            session.paginate(session.context.initial_history_limit, None);
31ce2453c82fatagen2026-09-24 13:07 UTC127
        }
31ce2453c82fatagen2026-09-24 13:07 UTC128
        Ok(session)
31ce2453c82fatagen2026-09-24 13:07 UTC129
    }
31ce2453c82fatagen2026-09-24 13:07 UTC130
31ce2453c82fatagen2026-09-24 13:07 UTC131
    /// swaps in a fresh watcher. the old one is dead before the reset goes out,
31ce2453c82fatagen2026-09-24 13:07 UTC132
    /// so no stale diff can land after it
31ce2453c82fatagen2026-09-24 13:07 UTC133
    pub(super) async fn resync(&mut self) -> Result<(), Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC134
        self.watcher.abort();
31ce2453c82fatagen2026-09-24 13:07 UTC135
        let _ = (&mut self.watcher).await;
31ce2453c82fatagen2026-09-24 13:07 UTC136
        self.watcher = start_watcher(&self.id, &self.timeline, &self.context, &self.scope)
31ce2453c82fatagen2026-09-24 13:07 UTC137
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC138
            .map_err(|_| Error::new(ErrorKind::Timeline, "timeline reset could not be sent"))?;
31ce2453c82fatagen2026-09-24 13:07 UTC139
        Ok(())
31ce2453c82fatagen2026-09-24 13:07 UTC140
    }
31ce2453c82fatagen2026-09-24 13:07 UTC141
31ce2453c82fatagen2026-09-24 13:07 UTC142
    pub(super) fn paginate(&self, limit: u16, reply: Option<Responder>) {
31ce2453c82fatagen2026-09-24 13:07 UTC143
        if let Err(error) = self.pagination.try_send(PaginationRequest { limit, reply }) {
31ce2453c82fatagen2026-09-24 13:07 UTC144
            let (request, error) = match error {
31ce2453c82fatagen2026-09-24 13:07 UTC145
                mpsc::error::TrySendError::Full(request) => (
31ce2453c82fatagen2026-09-24 13:07 UTC146
                    request,
31ce2453c82fatagen2026-09-24 13:07 UTC147
                    Error::new(ErrorKind::QueueFull, "pagination queue is full"),
31ce2453c82fatagen2026-09-24 13:07 UTC148
                ),
31ce2453c82fatagen2026-09-24 13:07 UTC149
                mpsc::error::TrySendError::Closed(request) => (
31ce2453c82fatagen2026-09-24 13:07 UTC150
                    request,
31ce2453c82fatagen2026-09-24 13:07 UTC151
                    Error::new(ErrorKind::TimelineNotOpen, "timeline is closing"),
31ce2453c82fatagen2026-09-24 13:07 UTC152
                ),
31ce2453c82fatagen2026-09-24 13:07 UTC153
            };
31ce2453c82fatagen2026-09-24 13:07 UTC154
            if let Some(reply) = request.reply {
31ce2453c82fatagen2026-09-24 13:07 UTC155
                reply.done(Err(error));
31ce2453c82fatagen2026-09-24 13:07 UTC156
            }
31ce2453c82fatagen2026-09-24 13:07 UTC157
        }
31ce2453c82fatagen2026-09-24 13:07 UTC158
    }
31ce2453c82fatagen2026-09-24 13:07 UTC159
31ce2453c82fatagen2026-09-24 13:07 UTC160
    /// pending paginations answer `Interrupted` as their responders drop
31ce2453c82fatagen2026-09-24 13:07 UTC161
    pub(super) async fn close(mut self) {
6ed8c0ef3a2aatagen2026-10-24 10:13 UTC162
        self.member_fetch.abort();
31ce2453c82fatagen2026-09-24 13:07 UTC163
        self.pagination_worker.abort();
31ce2453c82fatagen2026-09-24 13:07 UTC164
        let _ = (&mut self.pagination_worker).await;
31ce2453c82fatagen2026-09-24 13:07 UTC165
        self.watcher.abort();
31ce2453c82fatagen2026-09-24 13:07 UTC166
        let _ = (&mut self.watcher).await;
5a52012c9b1datagen2026-09-24 23:45 UTC167
        // after the watcher, or a last diff could register media for a timeline that's gone
5a52012c9b1datagen2026-09-24 23:45 UTC168
        self.context.media.release(&self.scope).await;
0bfa3f46f0beatagen2026-09-26 09:12 UTC169
        let _ = self
0bfa3f46f0beatagen2026-09-26 09:12 UTC170
            .context
0bfa3f46f0beatagen2026-09-26 09:12 UTC171
            .events
0bfa3f46f0beatagen2026-09-26 09:12 UTC172
            .send(Event::TimelineClosed {
0bfa3f46f0beatagen2026-09-26 09:12 UTC173
                timeline_id: self.id.clone(),
0bfa3f46f0beatagen2026-09-26 09:12 UTC174
            })
0bfa3f46f0beatagen2026-09-26 09:12 UTC175
            .await;
31ce2453c82fatagen2026-09-24 13:07 UTC176
    }
31ce2453c82fatagen2026-09-24 13:07 UTC177
31ce2453c82fatagen2026-09-24 13:07 UTC178
    pub(super) async fn execute(
31ce2453c82fatagen2026-09-24 13:07 UTC179
        &self,
31ce2453c82fatagen2026-09-24 13:07 UTC180
        command: TimelineCommand,
31ce2453c82fatagen2026-09-24 13:07 UTC181
        reply: Responder,
1fe480c16a3catagen2026-09-26 08:44 UTC182
        work: &mut TaskSet<()>,
31ce2453c82fatagen2026-09-24 13:07 UTC183
    ) {
31ce2453c82fatagen2026-09-24 13:07 UTC184
        let timeline = self.timeline.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC185
        let thread_root = self.id.thread_root().cloned();
1fe480c16a3catagen2026-09-26 08:44 UTC186
        let background: EngineBoxFuture<'static, Result<(), Error>> = match command {
31ce2453c82fatagen2026-09-24 13:07 UTC187
            TimelineCommand::Paginate { limit, .. } => return self.paginate(limit, Some(reply)),
31ce2453c82fatagen2026-09-24 13:07 UTC188
            // network-bound, so it runs beside the actor instead of queueing the room behind it
960ac0721079atagen2026-09-25 00:24 UTC189
            TimelineCommand::Redact { target, reason, .. } => Box::pin(async move {
31ce2453c82fatagen2026-09-24 13:07 UTC190
                timeline
960ac0721079atagen2026-09-25 00:24 UTC191
                    .redact(&item_id(target), reason.as_deref())
31ce2453c82fatagen2026-09-24 13:07 UTC192
                    .await
31ce2453c82fatagen2026-09-24 13:07 UTC193
                    .map_err(timeline_error)
31ce2453c82fatagen2026-09-24 13:07 UTC194
            }),
8fa8a7cde89catagen2026-10-08 12:39 UTC195
            TimelineCommand::ToggleReaction {
8fa8a7cde89catagen2026-10-08 12:39 UTC196
                target,
8fa8a7cde89catagen2026-10-08 12:39 UTC197
                key,
8fa8a7cde89catagen2026-10-08 12:39 UTC198
                shortcode,
8fa8a7cde89catagen2026-10-08 12:39 UTC199
                ..
8fa8a7cde89catagen2026-10-08 12:39 UTC200
            } => Box::pin(async move {
31ce2453c82fatagen2026-09-24 13:07 UTC201
                timeline
8fa8a7cde89catagen2026-10-08 12:39 UTC202
                    .toggle_reaction_with_shortcode(&item_id(target), &key, shortcode.as_deref())
31ce2453c82fatagen2026-09-24 13:07 UTC203
                    .await
31ce2453c82fatagen2026-09-24 13:07 UTC204
                    .map(drop)
31ce2453c82fatagen2026-09-24 13:07 UTC205
                    .map_err(timeline_error)
31ce2453c82fatagen2026-09-24 13:07 UTC206
            }),
31ce2453c82fatagen2026-09-24 13:07 UTC207
            TimelineCommand::MarkRead { event_id, .. } => Box::pin(async move {
31ce2453c82fatagen2026-09-24 13:07 UTC208
                let receipt_failed =
31ce2453c82fatagen2026-09-24 13:07 UTC209
                    |source| Error::from_sdk("sending read receipt failed", source);
31ce2453c82fatagen2026-09-24 13:07 UTC210
                timeline
31ce2453c82fatagen2026-09-24 13:07 UTC211
                    .send_single_receipt(ReceiptType::Read, event_id.clone())
31ce2453c82fatagen2026-09-24 13:07 UTC212
                    .await
31ce2453c82fatagen2026-09-24 13:07 UTC213
                    .map_err(receipt_failed)?;
31ce2453c82fatagen2026-09-24 13:07 UTC214
                if thread_root.is_none() {
31ce2453c82fatagen2026-09-24 13:07 UTC215
                    timeline
31ce2453c82fatagen2026-09-24 13:07 UTC216
                        .send_single_receipt(ReceiptType::FullyRead, event_id)
31ce2453c82fatagen2026-09-24 13:07 UTC217
                        .await
31ce2453c82fatagen2026-09-24 13:07 UTC218
                        .map_err(receipt_failed)?;
31ce2453c82fatagen2026-09-24 13:07 UTC219
                }
31ce2453c82fatagen2026-09-24 13:07 UTC220
                Ok(())
31ce2453c82fatagen2026-09-24 13:07 UTC221
            }),
31ce2453c82fatagen2026-09-24 13:07 UTC222
            command => return reply.done(self.execute_serial(command).await),
31ce2453c82fatagen2026-09-24 13:07 UTC223
        };
31ce2453c82fatagen2026-09-24 13:07 UTC224
        work.spawn(async move { reply.done(background.await) });
31ce2453c82fatagen2026-09-24 13:07 UTC225
    }
31ce2453c82fatagen2026-09-24 13:07 UTC226
31ce2453c82fatagen2026-09-24 13:07 UTC227
    /// sends stay on the actor so they hit the send queue in the order they were asked for
31ce2453c82fatagen2026-09-24 13:07 UTC228
    async fn execute_serial(&self, command: TimelineCommand) -> Result<(), Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC229
        let timeline = &self.timeline;
31ce2453c82fatagen2026-09-24 13:07 UTC230
        match command {
31ce2453c82fatagen2026-09-24 13:07 UTC231
            TimelineCommand::Send { content, .. } => {
31ce2453c82fatagen2026-09-24 13:07 UTC232
                let body = match &content {
31ce2453c82fatagen2026-09-24 13:07 UTC233
                    MessageContent::Text { content, .. }
31ce2453c82fatagen2026-09-24 13:07 UTC234
                    | MessageContent::Emote { content, .. }
9bd34e25bb86atagen2026-10-24 07:23 UTC235
                    | MessageContent::Notice { content, .. }
31ce2453c82fatagen2026-09-24 13:07 UTC236
                    | MessageContent::Reply { content, .. } => &content.body,
31ce2453c82fatagen2026-09-24 13:07 UTC237
                };
31ce2453c82fatagen2026-09-24 13:07 UTC238
                if body.trim().is_empty() {
31ce2453c82fatagen2026-09-24 13:07 UTC239
                    return Err(Error::new(ErrorKind::EmptyBody, "message body is empty"));
31ce2453c82fatagen2026-09-24 13:07 UTC240
                }
31ce2453c82fatagen2026-09-24 13:07 UTC241
                let content = match content {
31ce2453c82fatagen2026-09-24 13:07 UTC242
                    MessageContent::Text { content, mentions } => {
9bd34e25bb86atagen2026-10-24 07:23 UTC243
                        message_content(content, mentions, Msgtype::Text).with_relation(None)
31ce2453c82fatagen2026-09-24 13:07 UTC244
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC245
                    MessageContent::Emote { content, mentions } => {
9bd34e25bb86atagen2026-10-24 07:23 UTC246
                        message_content(content, mentions, Msgtype::Emote).with_relation(None)
9bd34e25bb86atagen2026-10-24 07:23 UTC247
                    }
9bd34e25bb86atagen2026-10-24 07:23 UTC248
                    MessageContent::Notice { content, mentions } => {
9bd34e25bb86atagen2026-10-24 07:23 UTC249
                        message_content(content, mentions, Msgtype::Notice).with_relation(None)
31ce2453c82fatagen2026-09-24 13:07 UTC250
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC251
                    MessageContent::Reply {
31ce2453c82fatagen2026-09-24 13:07 UTC252
                        event_id,
31ce2453c82fatagen2026-09-24 13:07 UTC253
                        content,
31ce2453c82fatagen2026-09-24 13:07 UTC254
                        mentions,
31ce2453c82fatagen2026-09-24 13:07 UTC255
                        notify_replied_to,
31ce2453c82fatagen2026-09-24 13:07 UTC256
                    } => {
31ce2453c82fatagen2026-09-24 13:07 UTC257
                        self.reply_content(event_id, content, mentions, notify_replied_to)
31ce2453c82fatagen2026-09-24 13:07 UTC258
                            .await?
31ce2453c82fatagen2026-09-24 13:07 UTC259
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC260
                };
31ce2453c82fatagen2026-09-24 13:07 UTC261
                timeline
31ce2453c82fatagen2026-09-24 13:07 UTC262
                    .send(content.into())
31ce2453c82fatagen2026-09-24 13:07 UTC263
                    .await
31ce2453c82fatagen2026-09-24 13:07 UTC264
                    .map(drop)
31ce2453c82fatagen2026-09-24 13:07 UTC265
                    .map_err(timeline_error)
31ce2453c82fatagen2026-09-24 13:07 UTC266
            }
31ce2453c82fatagen2026-09-24 13:07 UTC267
            TimelineCommand::Edit {
960ac0721079atagen2026-09-25 00:24 UTC268
                target, content, ..
31ce2453c82fatagen2026-09-24 13:07 UTC269
            } => {
9bd34e25bb86atagen2026-10-24 07:23 UTC270
                let (content, mentions, msgtype) = match content {
9bd34e25bb86atagen2026-10-24 07:23 UTC271
                    MessageEditContent::Text { content, mentions } => {
9bd34e25bb86atagen2026-10-24 07:23 UTC272
                        (content, mentions, Msgtype::Text)
9bd34e25bb86atagen2026-10-24 07:23 UTC273
                    }
9bd34e25bb86atagen2026-10-24 07:23 UTC274
                    MessageEditContent::Emote { content, mentions } => {
9bd34e25bb86atagen2026-10-24 07:23 UTC275
                        (content, mentions, Msgtype::Emote)
9bd34e25bb86atagen2026-10-24 07:23 UTC276
                    }
31ce2453c82fatagen2026-09-24 13:07 UTC277
                };
31ce2453c82fatagen2026-09-24 13:07 UTC278
                if content.body.trim().is_empty() {
31ce2453c82fatagen2026-09-24 13:07 UTC279
                    return Err(Error::new(ErrorKind::EmptyBody, "message body is empty"));
31ce2453c82fatagen2026-09-24 13:07 UTC280
                }
31ce2453c82fatagen2026-09-24 13:07 UTC281
                timeline
31ce2453c82fatagen2026-09-24 13:07 UTC282
                    .edit(
960ac0721079atagen2026-09-25 00:24 UTC283
                        &item_id(target),
9bd34e25bb86atagen2026-10-24 07:23 UTC284
                        EditedContent::RoomMessage(message_content(content, mentions, msgtype)),
31ce2453c82fatagen2026-09-24 13:07 UTC285
                    )
31ce2453c82fatagen2026-09-24 13:07 UTC286
                    .await
31ce2453c82fatagen2026-09-24 13:07 UTC287
                    .map_err(timeline_error)
31ce2453c82fatagen2026-09-24 13:07 UTC288
            }
31ce2453c82fatagen2026-09-24 13:07 UTC289
            _ => Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC290
                ErrorKind::Other,
31ce2453c82fatagen2026-09-24 13:07 UTC291
                "timeline command was misrouted",
31ce2453c82fatagen2026-09-24 13:07 UTC292
            )),
31ce2453c82fatagen2026-09-24 13:07 UTC293
        }
31ce2453c82fatagen2026-09-24 13:07 UTC294
    }
31ce2453c82fatagen2026-09-24 13:07 UTC295
31ce2453c82fatagen2026-09-24 13:07 UTC296
    async fn reply_content(
31ce2453c82fatagen2026-09-24 13:07 UTC297
        &self,
31ce2453c82fatagen2026-09-24 13:07 UTC298
        event_id: OwnedEventId,
31ce2453c82fatagen2026-09-24 13:07 UTC299
        content: RichText,
31ce2453c82fatagen2026-09-24 13:07 UTC300
        mentions: MessageMentions,
31ce2453c82fatagen2026-09-24 13:07 UTC301
        notify_replied_to: bool,
31ce2453c82fatagen2026-09-24 13:07 UTC302
    ) -> Result<matrix_sdk::ruma::events::room::message::RoomMessageEventContent, Error> {
31ce2453c82fatagen2026-09-24 13:07 UTC303
        let thread_root = self.id.thread_root();
31ce2453c82fatagen2026-09-24 13:07 UTC304
        let content = self
31ce2453c82fatagen2026-09-24 13:07 UTC305
            .timeline
31ce2453c82fatagen2026-09-24 13:07 UTC306
            .room()
31ce2453c82fatagen2026-09-24 13:07 UTC307
            .make_reply_event(
9bd34e25bb86atagen2026-10-24 07:23 UTC308
                message_content(content, mentions, Msgtype::Text),
31ce2453c82fatagen2026-09-24 13:07 UTC309
                SdkReply {
31ce2453c82fatagen2026-09-24 13:07 UTC310
                    event_id,
31ce2453c82fatagen2026-09-24 13:07 UTC311
                    enforce_thread: if thread_root.is_some() {
31ce2453c82fatagen2026-09-24 13:07 UTC312
                        EnforceThread::Threaded(ReplyWithinThread::Yes)
31ce2453c82fatagen2026-09-24 13:07 UTC313
                    } else {
31ce2453c82fatagen2026-09-24 13:07 UTC314
                        EnforceThread::MaybeThreaded
31ce2453c82fatagen2026-09-24 13:07 UTC315
                    },
31ce2453c82fatagen2026-09-24 13:07 UTC316
                    add_mentions: if notify_replied_to {
31ce2453c82fatagen2026-09-24 13:07 UTC317
                        AddMentions::Yes
31ce2453c82fatagen2026-09-24 13:07 UTC318
                    } else {
31ce2453c82fatagen2026-09-24 13:07 UTC319
                        AddMentions::No
31ce2453c82fatagen2026-09-24 13:07 UTC320
                    },
31ce2453c82fatagen2026-09-24 13:07 UTC321
                },
31ce2453c82fatagen2026-09-24 13:07 UTC322
            )
31ce2453c82fatagen2026-09-24 13:07 UTC323
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC324
            .map_err(|source| {
31ce2453c82fatagen2026-09-24 13:07 UTC325
                Error::with_source(ErrorKind::Timeline, "reply operation failed", source)
31ce2453c82fatagen2026-09-24 13:07 UTC326
            })?;
31ce2453c82fatagen2026-09-24 13:07 UTC327
        if let Some(thread_root) = thread_root
31ce2453c82fatagen2026-09-24 13:07 UTC328
            && !matches!(
31ce2453c82fatagen2026-09-24 13:07 UTC329
                content.relates_to.as_ref(),
31ce2453c82fatagen2026-09-24 13:07 UTC330
                Some(Relation::Thread(thread)) if &thread.event_id == thread_root
31ce2453c82fatagen2026-09-24 13:07 UTC331
            )
31ce2453c82fatagen2026-09-24 13:07 UTC332
        {
31ce2453c82fatagen2026-09-24 13:07 UTC333
            return Err(Error::new(
31ce2453c82fatagen2026-09-24 13:07 UTC334
                ErrorKind::Invalid,
31ce2453c82fatagen2026-09-24 13:07 UTC335
                "reply target does not belong to the selected thread",
31ce2453c82fatagen2026-09-24 13:07 UTC336
            ));
31ce2453c82fatagen2026-09-24 13:07 UTC337
        }
31ce2453c82fatagen2026-09-24 13:07 UTC338
        Ok(content)
31ce2453c82fatagen2026-09-24 13:07 UTC339
    }
31ce2453c82fatagen2026-09-24 13:07 UTC340
}
31ce2453c82fatagen2026-09-24 13:07 UTC341
31ce2453c82fatagen2026-09-24 13:07 UTC342
impl Drop for TimelineSession {
31ce2453c82fatagen2026-09-24 13:07 UTC343
    fn drop(&mut self) {
31ce2453c82fatagen2026-09-24 13:07 UTC344
        self.watcher.abort();
31ce2453c82fatagen2026-09-24 13:07 UTC345
        self.pagination_worker.abort();
6ed8c0ef3a2aatagen2026-10-24 10:13 UTC346
        self.member_fetch.abort();
31ce2453c82fatagen2026-09-24 13:07 UTC347
    }
31ce2453c82fatagen2026-09-24 13:07 UTC348
}
31ce2453c82fatagen2026-09-24 13:07 UTC349
960ac0721079atagen2026-09-25 00:24 UTC350
fn item_id(target: EventRef) -> TimelineEventItemId {
960ac0721079atagen2026-09-25 00:24 UTC351
    match target {
960ac0721079atagen2026-09-25 00:24 UTC352
        EventRef::Remote(event_id) => TimelineEventItemId::EventId(event_id),
960ac0721079atagen2026-09-25 00:24 UTC353
        EventRef::Local(transaction_id) => TimelineEventItemId::TransactionId(transaction_id),
960ac0721079atagen2026-09-25 00:24 UTC354
    }
960ac0721079atagen2026-09-25 00:24 UTC355
}
960ac0721079atagen2026-09-25 00:24 UTC356
960ac0721079atagen2026-09-25 00:24 UTC357
/// the sdk leaves a reply's target unloaded until someone asks, so the watcher asks, once per event
960ac0721079atagen2026-09-25 00:24 UTC358
struct ReplyFetcher {
960ac0721079atagen2026-09-25 00:24 UTC359
    timeline: Arc<Timeline>,
960ac0721079atagen2026-09-25 00:24 UTC360
    asked: HashSet<OwnedEventId>,
1fe480c16a3catagen2026-09-26 08:44 UTC361
    fetches: TaskSet<()>,
960ac0721079atagen2026-09-25 00:24 UTC362
}
960ac0721079atagen2026-09-25 00:24 UTC363
960ac0721079atagen2026-09-25 00:24 UTC364
impl ReplyFetcher {
960ac0721079atagen2026-09-25 00:24 UTC365
    fn fetch(&mut self, missing: Vec<OwnedEventId>) {
960ac0721079atagen2026-09-25 00:24 UTC366
        for event_id in missing {
960ac0721079atagen2026-09-25 00:24 UTC367
            if self.asked.insert(event_id.clone()) {
960ac0721079atagen2026-09-25 00:24 UTC368
                let timeline = self.timeline.clone();
960ac0721079atagen2026-09-25 00:24 UTC369
                self.fetches.spawn(async move {
960ac0721079atagen2026-09-25 00:24 UTC370
                    if let Err(error) = timeline.fetch_details_for_event(&event_id).await {
960ac0721079atagen2026-09-25 00:24 UTC371
                        tracing::debug!(%event_id, %error, "fetching reply details failed");
960ac0721079atagen2026-09-25 00:24 UTC372
                    }
960ac0721079atagen2026-09-25 00:24 UTC373
                });
960ac0721079atagen2026-09-25 00:24 UTC374
            }
960ac0721079atagen2026-09-25 00:24 UTC375
        }
960ac0721079atagen2026-09-25 00:24 UTC376
    }
960ac0721079atagen2026-09-25 00:24 UTC377
}
960ac0721079atagen2026-09-25 00:24 UTC378
31ce2453c82fatagen2026-09-24 13:07 UTC379
async fn start_watcher(
31ce2453c82fatagen2026-09-24 13:07 UTC380
    id: &TimelineId,
31ce2453c82fatagen2026-09-24 13:07 UTC381
    timeline: &Arc<Timeline>,
31ce2453c82fatagen2026-09-24 13:07 UTC382
    context: &SessionContext,
31ce2453c82fatagen2026-09-24 13:07 UTC383
    scope: &MediaScope,
31ce2453c82fatagen2026-09-24 13:07 UTC384
) -> Result<JoinHandle<()>, SendEventError> {
31ce2453c82fatagen2026-09-24 13:07 UTC385
    let (items, mut stream) = timeline.subscribe().await;
31ce2453c82fatagen2026-09-24 13:07 UTC386
    let current_user_id = context.current_user_id.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC387
    let normalised = normalise_timeline(items.iter(), current_user_id.as_deref(), scope);
31ce2453c82fatagen2026-09-24 13:07 UTC388
    context.media.register(normalised.media).await;
31ce2453c82fatagen2026-09-24 13:07 UTC389
    context
31ce2453c82fatagen2026-09-24 13:07 UTC390
        .events
31ce2453c82fatagen2026-09-24 13:07 UTC391
        .send(Event::TimelineReset {
31ce2453c82fatagen2026-09-24 13:07 UTC392
            timeline_id: id.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC393
            items: normalised.items,
31ce2453c82fatagen2026-09-24 13:07 UTC394
        })
31ce2453c82fatagen2026-09-24 13:07 UTC395
        .await?;
960ac0721079atagen2026-09-25 00:24 UTC396
    let mut replies = ReplyFetcher {
960ac0721079atagen2026-09-25 00:24 UTC397
        timeline: timeline.clone(),
960ac0721079atagen2026-09-25 00:24 UTC398
        asked: HashSet::new(),
1fe480c16a3catagen2026-09-26 08:44 UTC399
        fetches: TaskSet::new(),
960ac0721079atagen2026-09-25 00:24 UTC400
    };
960ac0721079atagen2026-09-25 00:24 UTC401
    replies.fetch(normalised.missing_replies);
31ce2453c82fatagen2026-09-24 13:07 UTC402
    let id = id.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC403
    let events = context.events.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC404
    let media = context.media.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC405
    let scope = scope.clone();
31ce2453c82fatagen2026-09-24 13:07 UTC406
    Ok(context.supervisor.spawn("timeline watcher", async move {
960ac0721079atagen2026-09-25 00:24 UTC407
        loop {
960ac0721079atagen2026-09-25 00:24 UTC408
            let diffs = tokio::select! {
960ac0721079atagen2026-09-25 00:24 UTC409
                diffs = stream.next() => match diffs {
960ac0721079atagen2026-09-25 00:24 UTC410
                    Some(diffs) => diffs,
960ac0721079atagen2026-09-25 00:24 UTC411
                    None => return,
960ac0721079atagen2026-09-25 00:24 UTC412
                },
960ac0721079atagen2026-09-25 00:24 UTC413
                Some(_) = replies.fetches.join_next(), if !replies.fetches.is_empty() => continue,
960ac0721079atagen2026-09-25 00:24 UTC414
            };
31ce2453c82fatagen2026-09-24 13:07 UTC415
            let normalised = normalise_timeline_diffs(diffs, current_user_id.as_deref(), &scope);
31ce2453c82fatagen2026-09-24 13:07 UTC416
            media.register(normalised.media).await;
960ac0721079atagen2026-09-25 00:24 UTC417
            replies.fetch(normalised.missing_replies);
31ce2453c82fatagen2026-09-24 13:07 UTC418
            let event = Event::TimelineChanged {
31ce2453c82fatagen2026-09-24 13:07 UTC419
                timeline_id: id.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC420
                diffs: normalised.diffs,
31ce2453c82fatagen2026-09-24 13:07 UTC421
            };
31ce2453c82fatagen2026-09-24 13:07 UTC422
            if events.send(event).await.is_err() {
31ce2453c82fatagen2026-09-24 13:07 UTC423
                return;
31ce2453c82fatagen2026-09-24 13:07 UTC424
            }
31ce2453c82fatagen2026-09-24 13:07 UTC425
        }
31ce2453c82fatagen2026-09-24 13:07 UTC426
    }))
31ce2453c82fatagen2026-09-24 13:07 UTC427
}
31ce2453c82fatagen2026-09-24 13:07 UTC428
31ce2453c82fatagen2026-09-24 13:07 UTC429
async fn run_pagination(
31ce2453c82fatagen2026-09-24 13:07 UTC430
    mut requests: mpsc::Receiver<PaginationRequest>,
31ce2453c82fatagen2026-09-24 13:07 UTC431
    timeline: Arc<Timeline>,
31ce2453c82fatagen2026-09-24 13:07 UTC432
    events: EventSender,
31ce2453c82fatagen2026-09-24 13:07 UTC433
    timeline_id: TimelineId,
31ce2453c82fatagen2026-09-24 13:07 UTC434
) {
31ce2453c82fatagen2026-09-24 13:07 UTC435
    while let Some(PaginationRequest { limit, reply }) = requests.recv().await {
31ce2453c82fatagen2026-09-24 13:07 UTC436
        let history = |state| Event::HistoryChanged {
31ce2453c82fatagen2026-09-24 13:07 UTC437
            timeline_id: timeline_id.clone(),
31ce2453c82fatagen2026-09-24 13:07 UTC438
            state,
31ce2453c82fatagen2026-09-24 13:07 UTC439
        };
31ce2453c82fatagen2026-09-24 13:07 UTC440
        if events.send(history(HistoryState::Loading)).await.is_err() {
31ce2453c82fatagen2026-09-24 13:07 UTC441
            return;
31ce2453c82fatagen2026-09-24 13:07 UTC442
        }
31ce2453c82fatagen2026-09-24 13:07 UTC443
        let result = timeline
31ce2453c82fatagen2026-09-24 13:07 UTC444
            .paginate_backwards(limit.max(1))
31ce2453c82fatagen2026-09-24 13:07 UTC445
            .await
31ce2453c82fatagen2026-09-24 13:07 UTC446
            .map_err(timeline_error);
31ce2453c82fatagen2026-09-24 13:07 UTC447
        let state = match &result {
31ce2453c82fatagen2026-09-24 13:07 UTC448
            Ok(true) => HistoryState::StartReached,
31ce2453c82fatagen2026-09-24 13:07 UTC449
            Ok(false) => HistoryState::Idle,
31ce2453c82fatagen2026-09-24 13:07 UTC450
            Err(error) => HistoryState::Failed(error.to_string()),
31ce2453c82fatagen2026-09-24 13:07 UTC451
        };
31ce2453c82fatagen2026-09-24 13:07 UTC452
        let _ = events.send(history(state)).await;
31ce2453c82fatagen2026-09-24 13:07 UTC453
        if let Some(reply) = reply {
31ce2453c82fatagen2026-09-24 13:07 UTC454
            reply.done(result.map(drop));
31ce2453c82fatagen2026-09-24 13:07 UTC455
        }
31ce2453c82fatagen2026-09-24 13:07 UTC456
    }
31ce2453c82fatagen2026-09-24 13:07 UTC457
}
31ce2453c82fatagen2026-09-24 13:07 UTC458
9bd34e25bb86atagen2026-10-24 07:23 UTC459
#[derive(Clone, Copy)]
9bd34e25bb86atagen2026-10-24 07:23 UTC460
enum Msgtype {
9bd34e25bb86atagen2026-10-24 07:23 UTC461
    Text,
9bd34e25bb86atagen2026-10-24 07:23 UTC462
    Emote,
9bd34e25bb86atagen2026-10-24 07:23 UTC463
    Notice,
9bd34e25bb86atagen2026-10-24 07:23 UTC464
}
9bd34e25bb86atagen2026-10-24 07:23 UTC465
31ce2453c82fatagen2026-09-24 13:07 UTC466
fn message_content(
31ce2453c82fatagen2026-09-24 13:07 UTC467
    content: RichText,
31ce2453c82fatagen2026-09-24 13:07 UTC468
    mentions: MessageMentions,
9bd34e25bb86atagen2026-10-24 07:23 UTC469
    msgtype: Msgtype,
31ce2453c82fatagen2026-09-24 13:07 UTC470
) -> RoomMessageEventContentWithoutRelation {
9bd34e25bb86atagen2026-10-24 07:23 UTC471
    type Content = RoomMessageEventContentWithoutRelation;
9bd34e25bb86atagen2026-10-24 07:23 UTC472
    let (body, formatted_body) = (content.body, content.formatted_body);
9bd34e25bb86atagen2026-10-24 07:23 UTC473
    let content = match (msgtype, formatted_body) {
9bd34e25bb86atagen2026-10-24 07:23 UTC474
        (Msgtype::Text, Some(html)) => Content::text_html(body, html),
9bd34e25bb86atagen2026-10-24 07:23 UTC475
        (Msgtype::Text, None) => Content::text_plain(body),
9bd34e25bb86atagen2026-10-24 07:23 UTC476
        (Msgtype::Emote, Some(html)) => Content::emote_html(body, html),
9bd34e25bb86atagen2026-10-24 07:23 UTC477
        (Msgtype::Emote, None) => Content::emote_plain(body),
9bd34e25bb86atagen2026-10-24 07:23 UTC478
        (Msgtype::Notice, Some(html)) => Content::notice_html(body, html),
9bd34e25bb86atagen2026-10-24 07:23 UTC479
        (Msgtype::Notice, None) => Content::notice_plain(body),
31ce2453c82fatagen2026-09-24 13:07 UTC480
    };
0827ad2d24e9atagen2026-10-23 06:49 UTC481
    content.add_mentions(sdk_mentions(mentions))
31ce2453c82fatagen2026-09-24 13:07 UTC482
}
31ce2453c82fatagen2026-09-24 13:07 UTC483
31ce2453c82fatagen2026-09-24 13:07 UTC484
pub(super) fn timeline_error(source: matrix_sdk_ui::timeline::Error) -> Error {
31ce2453c82fatagen2026-09-24 13:07 UTC485
    Error::with_source(ErrorKind::Timeline, "timeline operation failed", source)
31ce2453c82fatagen2026-09-24 13:07 UTC486
}