fix(#1666): wake on pending matrix invites via post-sync sweep

This commit is contained in:
damocles 2026-06-14 22:07:04 +02:00 committed by mara
commit ca84cf427b
2 changed files with 68 additions and 52 deletions

View file

@ -65,7 +65,6 @@ async fn main() -> Result<()> {
.context("build matrix client")?; .context("build matrix client")?;
timeline::install_message_handler(&matrix_client, hyperhive_socket.clone()); timeline::install_message_handler(&matrix_client, hyperhive_socket.clone());
timeline::install_invite_handler(&matrix_client, hyperhive_socket);
// Spawn the unix socket server before sync starts so the MCP // Spawn the unix socket server before sync starts so the MCP
// bridge can connect as soon as the first claude turn fires. The // bridge can connect as soon as the first claude turn fires. The
@ -79,10 +78,26 @@ async fn main() -> Result<()> {
} }
}); });
// Sync forever; matrix-sdk handles reconnection internally. // Sync forever; matrix-sdk handles reconnection internally. After
// every sync, sweep pending invites and wake the agent for any new
// one: the StrippedRoomMemberEvent handler dispatched unreliably
// (cold-start invites + handler races produced no wake), so
// invite-waking lives on this post-sync sweep with a dedup set.
let invite_socket = std::sync::Arc::new(hyperhive_socket);
let invite_notified =
std::sync::Arc::new(tokio::sync::Mutex::new(std::collections::HashSet::new()));
let sweep_client = matrix_client.clone();
let sync_settings = SyncSettings::default(); let sync_settings = SyncSettings::default();
matrix_client matrix_client
.sync(sync_settings) .sync_with_callback(sync_settings, move |_response| {
let client = sweep_client.clone();
let socket = invite_socket.clone();
let notified = invite_notified.clone();
async move {
timeline::sweep_invites(&client, &socket, &notified).await;
matrix_sdk::LoopCtrl::Continue
}
})
.await .await
.context("matrix-sdk sync loop exited")?; .context("matrix-sdk sync loop exited")?;

View file

@ -8,14 +8,16 @@
//! Self-events (events sent by this agent) are filtered out so an //! Self-events (events sent by this agent) are filtered out so an
//! agent posting a message doesn't wake itself. //! agent posting a message doesn't wake itself.
use std::path::PathBuf; use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::sync::Arc; use std::sync::Arc;
use matrix_sdk::{ use matrix_sdk::{
Client, Room, RoomState, Client, Room, RoomState,
ruma::events::room::member::{MembershipState, StrippedRoomMemberEvent}, ruma::OwnedRoomId,
ruma::events::room::message::{MessageType, OriginalSyncRoomMessageEvent}, ruma::events::room::message::{MessageType, OriginalSyncRoomMessageEvent},
}; };
use tokio::sync::Mutex;
use crate::{handlers, wake}; use crate::{handlers, wake};
@ -93,54 +95,53 @@ pub fn install_message_handler(client: &Client, hyperhive_socket: PathBuf) {
tracing::info!("matrix message handler installed"); tracing::info!("matrix message handler installed");
} }
/// Install a handler that wakes the agent when a room invite arrives. /// Wake the agent for any pending room invite it has not yet been
/// The agent decides whether to accept or reject by calling /// notified about. Driven from the post-sync callback rather than a
/// `resolve_invite`. /// `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.
/// ///
/// When the daemon receives an `m.room.member` state event with /// `notified` dedups so a standing invite wakes the agent once rather
/// `membership: invite` for the agent's own user ID during sync, it /// than on every sync tick; it is pruned to the current invite set each
/// fires a hyperhive wake so the agent can inspect the invite via /// pass so a withdrawn-then-reissued invite wakes again. The agent
/// `list_invites` and act on it with `resolve_invite`. /// decides whether to accept or reject by calling `resolve_invite`.
/// pub async fn sweep_invites(client: &Client, socket: &Path, notified: &Mutex<HashSet<OwnedRoomId>>) {
/// This closes the gap where invites accumulated in `invited_rooms()` let current = client.invited_rooms();
/// forever without the agent being notified — the daemon's message let current_ids: HashSet<OwnedRoomId> =
/// handler only fires for joined rooms. current.iter().map(|r| r.room_id().to_owned()).collect();
pub fn install_invite_handler(client: &Client, hyperhive_socket: PathBuf) {
let socket = Arc::new(hyperhive_socket); let mut fresh = Vec::new();
let own_user = client.user_id().map(std::borrow::ToOwned::to_owned); {
client.add_event_handler({ let mut seen = notified.lock().await;
move |event: StrippedRoomMemberEvent, room: Room, client: Client| { // Drop invites that are no longer pending (joined/rejected/withdrawn)
let socket = socket.clone(); // so a future re-invite to the same room wakes the agent again.
let own_user = own_user.clone(); seen.retain(|id| current_ids.contains(id));
async move { for room in &current {
// Only handle invite events for our own user. if seen.insert(room.room_id().to_owned()) {
if event.content.membership != MembershipState::Invite { fresh.push(room.clone());
return;
}
let is_ours = own_user
.as_ref()
.is_some_and(|u| u.as_str() == event.state_key.as_str());
if !is_ours {
return;
}
let room_id = room.room_id().to_owned();
let label = room.name().unwrap_or_else(|| room_id.to_string());
tracing::info!(%room_id, "matrix: received room invite, waking agent");
// 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;
let body = 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"
);
}
} }
} }
}); }
tracing::info!("matrix invite handler installed"); 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 = 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");
}
}
} }