feat(#2569): matrix producer — sweep_unread pushes per-room todos instead of direct wakes

This commit is contained in:
damocles 2026-07-19 01:40:32 +02:00 committed by mara
commit 711e0ece2a
4 changed files with 125 additions and 71 deletions

View file

@ -901,6 +901,21 @@ pub fn unread_count(client: &Client) -> DaemonResponse {
/// mind if latency becomes a concern. /// mind if latency becomes a concern.
#[must_use] #[must_use]
pub async fn collect_unread(client: &Client) -> Vec<crate::protocol::RoomUnread> { pub async fn collect_unread(client: &Client) -> Vec<crate::protocol::RoomUnread> {
collect_unread_with_ids(client)
.await
.into_iter()
.map(|(_, ru)| ru)
.collect()
}
/// Like [`collect_unread`] but pairs each entry with its `OwnedRoomId`.
/// The todo producer (loose-ends v2, #2569) needs the room id as the
/// per-room upsert/dedup key, which the claude-facing `RoomUnread`
/// payload intentionally doesn't carry.
#[must_use]
pub async fn collect_unread_with_ids(
client: &Client,
) -> Vec<(matrix_sdk::ruma::OwnedRoomId, crate::protocol::RoomUnread)> {
use crate::protocol::RoomUnread; use crate::protocol::RoomUnread;
let mut result = Vec::new(); let mut result = Vec::new();
for room in client.joined_rooms() { for room in client.joined_rooms() {
@ -915,12 +930,15 @@ pub async fn collect_unread(client: &Client) -> Vec<crate::protocol::RoomUnread>
} else { } else {
(None, None) (None, None)
}; };
result.push(RoomUnread { result.push((
label, room.room_id().to_owned(),
count, RoomUnread {
last_body, label,
last_sender, count,
}); last_body,
last_sender,
},
));
} }
result result
} }

View file

@ -299,6 +299,11 @@ async fn bring_up_account(
// each sweep (see the sweep fns) so re-invites / new messages re-wake. // each sweep (see the sweep fns) so re-invites / new messages re-wake.
let invite_notified = Arc::new(tokio::sync::Mutex::new(std::collections::HashSet::new())); let invite_notified = Arc::new(tokio::sync::Mutex::new(std::collections::HashSet::new()));
let unread_notified = Arc::new(tokio::sync::Mutex::new(std::collections::HashSet::new())); let unread_notified = Arc::new(tokio::sync::Mutex::new(std::collections::HashSet::new()));
// Startup cancel-and-recreate (loose-ends v2, #2569): wipe this agent's
// matrix todos so stale ones (rooms read while the daemon was down) don't
// linger, then let the first sweep rebuild the set to match current
// unread reality. Best-effort; the sweep converges regardless.
let _ = crate::wake::send_todo_clear(hyperhive_socket, None, true).await;
let sync_loop: SyncLoop = Box::pin(async move { let sync_loop: SyncLoop = Box::pin(async move {
sync_client sync_client
.sync_with_callback(SyncSettings::default(), move |_response| { .sync_with_callback(SyncSettings::default(), move |_response| {

View file

@ -20,23 +20,19 @@ use tokio::sync::Mutex;
use crate::{handlers, wake}; use crate::{handlers, wake};
/// Wake the agent for any joined room carrying unread notifications it has /// Push a *todo* (loose-ends v2, #2569) for each joined room carrying
/// not yet been successfully woken about. Driven from the post-sync /// unread notifications, and clear the todo for rooms that have been read.
/// callback — the same reliable path `sweep_invites` uses — rather than a /// Replaces the old direct-wake path: instead of firing an all-rooms wake,
/// one-shot `m.room.message` event handler: a message-wake whose /// each unread room becomes a per-room `upsert_todo` keyed by its room id,
/// `send_wake` raced a hive-c0re / socket-down window (a container rebuild) /// and hive-c0re coalesces exactly one wake when the todo set changes.
/// was dropped with no retry, so the agent went deaf until manually
/// prompted. The sync callback fires on every sync response (so promptly on
/// new activity), so this re-checks unread each tick and retries a dropped
/// wake on the next one — self-healing once the socket is back.
/// ///
/// `notified` dedups so a standing unread wakes the agent once, not on /// Driven from the post-sync callback — the same reliable path
/// every sync tick; it is pruned to the current unread set each pass so a /// `sweep_invites` uses — so it re-checks unread each tick; a dropped
/// room that has been read and then receives a new message wakes again. On /// upsert is retried on the next one (self-healing once the socket is
/// a wake-send failure the freshly-seen rooms are rolled back out of /// back). `notified` tracks which rooms currently have an active todo so
/// `notified` so the next pass retries them. `account_tag` is `Some(name)` /// a room that becomes read gets its todo cleared. `account_tag` is
/// only in multi-account mode, prepended so the agent knows which account /// `Some(name)` only in multi-account mode, prepended so the agent knows
/// to `read_room` on. /// which account to `read_room` on.
/// ///
/// Self-sent messages don't raise an unread notification server-side, so /// Self-sent messages don't raise an unread notification server-side, so
/// no explicit self-filter is needed here. /// no explicit self-filter is needed here.
@ -46,55 +42,42 @@ pub async fn sweep_unread(
notified: &Mutex<HashSet<OwnedRoomId>>, notified: &Mutex<HashSet<OwnedRoomId>>,
account_tag: Option<&str>, account_tag: Option<&str>,
) { ) {
// Current set of joined rooms carrying unread notifications. let unread = handlers::collect_unread_with_ids(client).await;
let unread_ids: HashSet<OwnedRoomId> = client let unread_ids: HashSet<OwnedRoomId> = unread.iter().map(|(id, _)| id.clone()).collect();
.joined_rooms()
.into_iter()
.filter(|r| r.unread_notification_counts().notification_count > 0)
.map(|r| r.room_id().to_owned())
.collect();
// Which unread rooms are newly-seen (not already successfully woken)? // Rooms we previously pushed a todo for that are no longer unread → the
let mut fresh = Vec::new(); // agent read them; clear their todo. Snapshot under the lock, send
{ // outside it, drop from `notified` on success (retry next tick on fail).
let mut seen = notified.lock().await; let stale: Vec<OwnedRoomId> = {
// Drop rooms no longer unread (read / left) so a future new message let active = notified.lock().await;
// in them wakes the agent again. active.difference(&unread_ids).cloned().collect()
seen.retain(|id| unread_ids.contains(id)); };
for id in &unread_ids { for id in stale {
if seen.insert(id.clone()) { if wake::send_todo_clear(socket, Some(id.as_str()), false)
fresh.push(id.clone()); .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");
} }
} }
} }
if fresh.is_empty() {
return;
}
// Roll the freshly-seen rooms back out of `notified` so the next sweep
// retries them. Used on both the sync-race (empty collect) and the
// wake-send-failure paths.
let rollback = || async {
let mut seen = notified.lock().await;
for id in &fresh {
seen.remove(id);
}
};
// Same all-rooms unread summary the wake body has always used. Empty
// only under a sync race (counts changed between the scan and collect).
let unread = handlers::collect_unread(client).await;
if unread.is_empty() {
rollback().await;
return;
}
let body = wake::tag_account(account_tag, wake::format_unread_summary(&unread));
if let Err(e) = wake::send_wake(socket, &body).await {
rollback().await;
tracing::warn!(error = %e, "matrix: unread-sweep wake failed; will retry next sync");
} else {
tracing::info!(rooms = fresh.len(), "matrix: unread-sweep wake delivered");
}
} }
/// Wake the agent for any pending room invite it has not yet been /// Wake the agent for any pending room invite it has not yet been

View file

@ -34,15 +34,65 @@ use tokio::net::UnixStream;
/// Returns an error on socket connect failure, serialisation failure, /// Returns an error on socket connect failure, serialisation failure,
/// or I/O error writing to or reading from the socket. /// or I/O error writing to or reading from the socket.
pub async fn send_wake(socket: &Path, body: impl AsRef<str>) -> Result<()> { pub async fn send_wake(socket: &Path, body: impl AsRef<str>) -> Result<()> {
use tokio::io::AsyncBufReadExt;
let payload = serde_json::json!({ let payload = serde_json::json!({
"cmd": "wake", "cmd": "wake",
"from": "matrix", "from": "matrix",
"body": body.as_ref(), "body": body.as_ref(),
"transient": true, "transient": true,
}); });
let line = format!("{}\n", serde_json::to_string(&payload)?); send_line(socket, &payload).await
}
/// Upsert a matrix-subsystem *todo* (loose-ends v2, #2569) on the
/// hyperhive control socket — the replacement for a direct wake. `key` is
/// the room id (the dedup key); hive-c0re coalesces a wake iff the todo is
/// new or its `summary` changed. Best-effort like [`send_wake`].
///
/// # Errors
///
/// Returns an error on socket connect failure, serialisation failure,
/// or I/O error writing to or reading from the socket.
pub async fn send_todo_upsert(socket: &Path, key: &str, summary: impl AsRef<str>) -> Result<()> {
let payload = serde_json::json!({
"cmd": "upsert_todo",
"subsystem": "matrix",
"key": key,
"summary": summary.as_ref(),
});
send_line(socket, &payload).await
}
/// Clear matrix-subsystem todos. `key = Some(room)` clears one room's
/// todo (it was read); `all = true` wipes the whole matrix set
/// (cancel-and-recreate on daemon restart). Best-effort.
///
/// # Errors
///
/// Returns an error on socket connect failure, serialisation failure,
/// or I/O error writing to or reading from the socket.
pub async fn send_todo_clear(socket: &Path, key: Option<&str>, all: bool) -> Result<()> {
let payload = serde_json::json!({
"cmd": "clear_todo",
"subsystem": "matrix",
"key": key,
"all": all,
});
send_line(socket, &payload).await
}
/// Write one JSON request line to the hyperhive control socket and drain
/// the response line (best-effort — the reply is not acted on, we just
/// read it so the server doesn't get ECONNRESET on its write-back).
/// Shared by [`send_wake`] and the todo senders.
///
/// # Errors
///
/// Returns an error on socket connect failure, serialisation failure,
/// or I/O error writing to or reading from the socket.
async fn send_line(socket: &Path, payload: &serde_json::Value) -> Result<()> {
use tokio::io::AsyncBufReadExt;
let line = format!("{}\n", serde_json::to_string(payload)?);
let stream = UnixStream::connect(socket) let stream = UnixStream::connect(socket)
.await .await
.with_context(|| format!("connect hyperhive socket {}", socket.display()))?; .with_context(|| format!("connect hyperhive socket {}", socket.display()))?;
@ -50,13 +100,11 @@ pub async fn send_wake(socket: &Path, body: impl AsRef<str>) -> Result<()> {
write write
.write_all(line.as_bytes()) .write_all(line.as_bytes())
.await .await
.with_context(|| format!("write wake to {}", socket.display()))?; .with_context(|| format!("write to {}", socket.display()))?;
write write
.shutdown() .shutdown()
.await .await
.with_context(|| format!("shutdown write to {}", socket.display()))?; .with_context(|| format!("shutdown write to {}", socket.display()))?;
// Drain the response line so the server doesn't get ECONNRESET on
// its write-back. We don't act on the response — best-effort wake.
let mut reader = tokio::io::BufReader::new(read); let mut reader = tokio::io::BufReader::new(read);
let mut resp = String::new(); let mut resp = String::new();
let _ = reader.read_line(&mut resp).await; let _ = reader.read_line(&mut resp).await;