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

140 lines
5.9 KiB
Rust

//! Matrix → hyperhive wake bridge. 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 wake whose `send_wake` raced a hive-c0re / 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 wake on
//! the next one.
//!
//! Wake bodies stay short: `sweep_unread` sends the all-rooms unread
//! summary (`wake::format_unread_summary`); the message stays unread
//! server-side so the agent fetches detail via `read_room`. Self-sent
//! messages never raise an unread notification, so they never wake.
use std::collections::HashSet;
use std::path::Path;
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.
///
/// Self-sent messages don't raise an unread notification server-side, so
/// no explicit self-filter is needed here.
pub async fn sweep_unread(
client: &Client,
socket: &Path,
notified: &Mutex<HashSet<OwnedRoomId>>,
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.difference(&unread_ids).cloned().collect()
};
for id in stale {
if wake::send_todo_clear(socket, Some(id.as_str()), false)
.await
.is_ok()
{
notified.lock().await.remove(&id);
}
}
// Upsert a todo per currently-unread room. hive-c0re coalesces the wake
// iff the summary is new or changed, so re-upserting an unchanged room
// every sync tick is a cheap server-side 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(socket, 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(
client: &Client,
socket: &Path,
notified: &Mutex<HashSet<OwnedRoomId>>,
account_tag: Option<&str>,
) {
let current = client.invited_rooms();
let current_ids: HashSet<OwnedRoomId> =
current.iter().map(|r| r.room_id().to_owned()).collect();
let mut fresh = Vec::new();
{
let mut seen = notified.lock().await;
// Drop invites that are no longer pending (joined/rejected/withdrawn)
// so a future re-invite to the same room wakes the agent again.
seen.retain(|id| current_ids.contains(id));
for room in &current {
if seen.insert(room.room_id().to_owned()) {
fresh.push(room.clone());
}
}
}
if fresh.is_empty() {
return;
}
// Refresh loose-ends before waking so the invite is visible in
// get_loose_ends during the agent's turn.
handlers::refresh_invite_loose_ends(client).await;
for room in fresh {
let room_id = room.room_id().to_owned();
let label = room.name().unwrap_or_else(|| room_id.to_string());
tracing::info!(%room_id, "matrix: pending invite swept, waking agent");
let body = 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"
),
);
if let Err(e) = wake::send_wake(socket, &body).await {
tracing::warn!(error = %e, "matrix: failed to deliver invite-wake to hyperhive");
}
}
}