hyperhive/hive-matrix-mcp/src/timeline.rs

163 lines
6.9 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};
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(Some(id.as_str()), false)
.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(Some(&invite_key(&id)), false)
.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.
for room in &current {
let room_id = room.room_id().to_owned();
let label = room.name().unwrap_or_else(|| room_id.to_string());
let summary = wake::tag_account(
account_tag,
format!(
"[matrix] invited to {label} ({room_id}) — \
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");
}
}
}
}
/// 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}")
}