atagen

macltok

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