Watch
0
0
Fork
You've already forked hyperhive
0
hyperhive/hive-matrix-mcp/src/timeline.rs

260 lines
11 KiB
Rust

//! Matrix → hyperhive todo bridge (loose-ends v2). Both room messages and
//! room invites are surfaced to the agent by SWEEPING state on every
//! post-sync callback, not by one-shot `m.room.message` /
//! `StrippedRoomMemberEvent` handlers: a one-shot signal that raced a
//! socket-down window (a container rebuild) was dropped with no retry,
//! leaving the agent deaf to matrix activity until manually prompted.
//! Sweeping the reliable sync path re-checks each tick and self-heals a
//! dropped push on the next one — each todo is idempotent by room key.
//!
//! Todo summaries stay short: `sweep_unread` pushes the per-room unread
//! summary (`wake::format_unread_summary`); the message stays unread
//! server-side so the agent fetches detail via `read_room`. A self-authored
//! newest message can still read as unread after a rebuild (the read receipt
//! lags), so `collect_unread_with_ids` filters those rooms out — the agent
//! never wakes on its own message.
use std::collections::HashSet;
use std::hash::BuildHasher;
use matrix_sdk::{
Client,
ruma::{OwnedRoomId, ServerName, UserId},
};
use tokio::sync::Mutex;
use crate::{handlers, wake};
/// Push a *todo* (loose-ends v2) for each joined room carrying
/// unread notifications, and clear the todo for rooms that have been read.
/// Replaces the old direct-wake path: instead of firing an all-rooms wake,
/// each unread room becomes a per-room `upsert_todo` keyed by its room id,
/// and hive-c0re coalesces exactly one wake when the todo set changes.
///
/// Driven from the post-sync callback — the same reliable path
/// `sweep_invites` uses — so it re-checks unread each tick; a dropped
/// upsert is retried on the next one (self-healing once the socket is
/// back). `notified` tracks which rooms currently have an active todo so
/// a room that becomes read gets its todo cleared. `account_tag` is
/// `Some(name)` only in multi-account mode, prepended so the agent knows
/// which account to `read_room` on.
///
/// Rooms whose newest unread event is the agent's own message are filtered
/// out by `collect_unread_with_ids` (after a rebuild a stale read receipt can
/// otherwise leave a self-authored message counted as unread and self-wake
/// the agent).
pub async fn sweep_unread<S: BuildHasher>(
client: &Client,
notified: &Mutex<HashSet<OwnedRoomId, S>>,
account_tag: Option<&str>,
) {
let unread = handlers::collect_unread_with_ids(client).await;
let unread_ids: HashSet<OwnedRoomId> = unread.iter().map(|(id, _)| id.clone()).collect();
// Rooms we previously pushed a todo for that are no longer unread → the
// agent read them; clear their todo. Snapshot under the lock, send
// outside it, drop from `notified` on success (retry next tick on fail).
let stale: Vec<OwnedRoomId> = {
let active = notified.lock().await;
active
.iter()
.filter(|id| !unread_ids.contains(*id))
.cloned()
.collect()
};
for id in stale {
if wake::send_todo_clear(id.as_str()).await.is_ok() {
notified.lock().await.remove(&id);
}
}
// Upsert a todo per currently-unread room. The harness coalesces the
// wake iff the summary is new or changed, so re-upserting an unchanged
// room every sync tick is a cheap no-op (no re-wake).
for (id, ru) in &unread {
let summary = wake::tag_account(
account_tag,
wake::format_unread_summary(std::slice::from_ref(ru)),
);
match wake::send_todo_upsert(id.as_str(), &summary).await {
Ok(()) => {
notified.lock().await.insert(id.clone());
}
Err(e) => {
tracing::warn!(error = %e, room = %id, "matrix: todo upsert failed; will retry next sync");
}
}
}
}
/// Wake the agent for any pending room invite it has not yet been
/// notified about. Driven from the post-sync callback rather than a
/// `StrippedRoomMemberEvent` handler: that handler dispatched
/// unreliably — an invite that arrived while the daemon was down, or
/// one that raced the handler, produced no wake at all (the message
/// handler, by contrast, fires reliably for joined-room timeline
/// events). Sweeping `invited_rooms()` after every sync catches both
/// the cold-start and the race cases on the proven sync path.
///
/// `notified` dedups so a standing invite wakes the agent once rather
/// than on every sync tick; it is pruned to the current invite set each
/// pass so a withdrawn-then-reissued invite wakes again. The agent
/// decides whether to accept or reject by calling `resolve_invite`.
pub async fn sweep_invites<S: BuildHasher>(
client: &Client,
notified: &Mutex<HashSet<OwnedRoomId, S>>,
account_tag: Option<&str>,
) {
let current = client.invited_rooms();
let current_ids: HashSet<OwnedRoomId> =
current.iter().map(|r| r.room_id().to_owned()).collect();
// Invites we previously pushed a todo for that are no longer pending
// (joined / rejected / withdrawn) → clear their todo, then drop from
// `notified` on success so a future re-invite re-upserts (retry next
// tick on failure).
let stale: Vec<OwnedRoomId> = {
let seen = notified.lock().await;
seen.iter()
.filter(|id| !current_ids.contains(*id))
.cloned()
.collect()
};
for id in stale {
if wake::send_todo_clear(&invite_key(&id)).await.is_ok() {
notified.lock().await.remove(&id);
}
}
// Upsert a todo per pending invite. Keyed `invite:<room>` (distinct
// from the unread sweep's `<room>` key) so the two never collide; the
// harness coalesces the wake iff the summary is new or changed, so
// re-upserting an unchanged invite every tick is a cheap no-op.
let own_server = swarm_server(client);
for room in &current {
let room_id = room.room_id().to_owned();
let inviter = room
.invite_details()
.await
.ok()
.and_then(|d| d.inviter)
.map(|m| m.user_id().to_owned());
// An invite from a user of the swarm's own homeserver, to an account
// that lives on it, is trusted: join it without waking the agent. A failed join falls through to the todo
// below, so the invite is never lost.
if is_local(own_server.as_deref(), inviter.as_deref()) {
match room.join().await {
Ok(()) => {
tracing::info!(room = %room_id, inviter = ?inviter, "matrix: auto-joined an invite from the swarm homeserver");
continue;
}
Err(e) => {
tracing::warn!(error = %e, room = %room_id, "matrix: auto-join failed; leaving the invite as a todo");
}
}
}
let label = room.name().unwrap_or_else(|| room_id.to_string());
let source = match &inviter {
Some(u) if !is_local(own_server.as_deref(), Some(u)) => {
format!("an external matrix user ({u})")
}
Some(u) => u.to_string(),
None => "an unknown inviter".to_owned(),
};
let summary = wake::tag_account(
account_tag,
format!(
"[matrix] invited to {label} ({room_id}) by {source} — \
use list_invites to see pending invites, resolve_invite to accept or reject"
),
);
match wake::send_todo_upsert(&invite_key(&room_id), &summary).await {
Ok(()) => {
notified.lock().await.insert(room_id);
}
Err(e) => {
tracing::warn!(error = %e, room = %room_id, "matrix: invite todo upsert failed; will retry next sweep");
}
}
}
}
/// The swarm homeserver's server name when `client` is an account on it, else
/// `None`. The swarm homeserver is the daemon-wide `HIVE_MATRIX_URL`; a linked
/// account on another server (matrix.org, catgirl.cloud, ...) is not on it, so
/// its same-server inviters are strangers, not swarm members.
fn swarm_server(client: &Client) -> Option<matrix_sdk::ruma::OwnedServerName> {
let swarm = reqwest::Url::parse(&crate::paths::homeserver_url()?).ok()?;
same_homeserver(&swarm, &client.homeserver())
.then(|| client.user_id().map(|u| u.server_name().to_owned()))
.flatten()
}
/// Whether two homeserver URLs point at the same host and port.
fn same_homeserver(a: &reqwest::Url, b: &reqwest::Url) -> bool {
a.host_str() == b.host_str() && a.port_or_known_default() == b.port_or_known_default()
}
/// Whether `inviter` is a user of the swarm homeserver `own` (the account's
/// server when the account is on it, else `None`). No known inviter or no
/// swarm server counts as external.
fn is_local(own: Option<&ServerName>, inviter: Option<&UserId>) -> bool {
matches!((own, inviter), (Some(own), Some(u)) if u.server_name() == own)
}
/// Todo dedup key for a pending invite. Namespaced with an `invite:`
/// prefix so an invited room and an unread room (which the unread sweep
/// keys by bare room id) never share a todo row. `pub(crate)` so the
/// invite-resolution handlers can clear the matching todo immediately.
pub(crate) fn invite_key(room_id: &matrix_sdk::ruma::RoomId) -> String {
format!("invite:{room_id}")
}
#[cfg(test)]
mod invite_tests {
use matrix_sdk::ruma::{server_name, user_id};
use super::{is_local, same_homeserver};
#[test]
fn only_an_inviter_on_the_own_homeserver_is_local() {
let own = server_name!("pr1ma.darkest.space");
assert!(is_local(
Some(own),
Some(user_id!("@mara:pr1ma.darkest.space"))
));
assert!(!is_local(Some(own), Some(user_id!("@mara:matrix.org"))));
// A look-alike server name is not the own homeserver.
assert!(!is_local(
Some(own),
Some(user_id!("@x:pr1ma.darkest.space.evil.example"))
));
// Anything unknown is external.
assert!(!is_local(Some(own), None));
assert!(!is_local(None, Some(user_id!("@mara:pr1ma.darkest.space"))));
}
#[test]
fn an_account_is_on_the_swarm_homeserver_only_by_host_and_port() {
let u = |s: &str| reqwest::Url::parse(s).expect("url");
let swarm = u("https://matrix.pr1ma.darkest.space");
assert!(same_homeserver(
&swarm,
&u("https://matrix.pr1ma.darkest.space/")
));
assert!(same_homeserver(
&swarm,
&u("https://matrix.pr1ma.darkest.space:443")
));
// A public server is a different host, and a different port is a
// different server.
assert!(!same_homeserver(&swarm, &u("https://catgirl.cloud")));
assert!(!same_homeserver(
&swarm,
&u("https://matrix.pr1ma.darkest.space:8448")
));
// An external account gets no swarm server, so even its own
// same-server inviter is not local.
assert!(!is_local(None, Some(user_id!("@x:catgirl.cloud"))));
}
}