feat(#1137): rich unread summary in loose ends and wake signal

- hive-sh4re: UnreadMatrix gains summary: String field (per-room breakdown)
- hive-matrix-mcp/protocol: add RoomUnread struct + UnreadSummary request
- hive-matrix-mcp/handlers: collect_unread() fetches per-room data;
  single-unread rooms include truncated last-message body + sender;
  multi-unread rooms carry count only
- hive-matrix-mcp/wake: format_unread_summary() builds wake body from
  RoomUnread slice; terse one-liner for single-room/single-message,
  bulleted list for multi-room; always appends read-hint
- hive-matrix-mcp/timeline: wake body now covers all rooms with unread
  at fire time, not just the triggering event; falls back to per-event
  teaser if notification counts haven't updated yet
- hive-ag3nt/mcp: matrix_unread_summary() replaces matrix_unread_rooms();
  UnreadMatrix loose end carries per-room summary lines; render shows
  room breakdown with sender: body for single-unread rooms
This commit is contained in:
atlas 2026-06-03 12:52:24 +02:00
commit 68e30b857c
19 changed files with 421 additions and 108 deletions

View file

@ -357,3 +357,73 @@ pub fn unread_count(client: &Client) -> DaemonResponse {
.count() as u32;
DaemonResponse::ok(&serde_json::json!({ "rooms": rooms }))
}
/// Collect all rooms with unread notifications and build per-room
/// [`crate::protocol::RoomUnread`] entries. For rooms with exactly
/// one unread notification the last message body is fetched via the
/// `/messages` endpoint (best-effort; failures leave `last_body` as
/// `None`). Rooms with zero unreads are omitted.
pub async fn collect_unread(client: &Client) -> Vec<crate::protocol::RoomUnread> {
use crate::protocol::RoomUnread;
let mut result = Vec::new();
for room in client.joined_rooms() {
let count = room.unread_notification_counts().notification_count as u32;
if count == 0 {
continue;
}
let label = room
.canonical_alias()
.map(|a| a.to_string())
.unwrap_or_else(|| room.room_id().to_string());
let (last_body, last_sender) = if count == 1 {
fetch_last_message(client, &room).await
} else {
(None, None)
};
result.push(RoomUnread {
label,
count,
last_body,
last_sender,
});
}
result
}
/// Fetch the body + sender of the most recent room message. Returns
/// `(None, None)` on any error or when the timeline contains no text
/// events.
async fn fetch_last_message(
client: &Client,
room: &matrix_sdk::Room,
) -> (Option<String>, Option<String>) {
use matrix_sdk::ruma::api::Direction;
use matrix_sdk::ruma::api::client::message::get_message_events;
let mut req =
get_message_events::v3::Request::new(room.room_id().to_owned(), Direction::Backward);
req.limit = matrix_sdk::ruma::UInt::from(1u32);
let resp = match client.send(req).await {
Ok(r) => r,
Err(_) => return (None, None),
};
for raw in &resp.chunk {
if let Ok(ev) = raw.deserialize() {
let body = extract_body(&ev);
if !body.is_empty() {
return (
Some(crate::wake::truncate_chars(&body, 100)),
Some(ev.sender().to_string()),
);
}
}
}
(None, None)
}
/// Return per-room unread summaries. For rooms with exactly one
/// unread notification, attempts to include the sender + truncated
/// body; rooms with multiple unreads carry only the count.
pub async fn unread_summary(client: &Client) -> DaemonResponse {
let rooms = collect_unread(client).await;
DaemonResponse::ok(&rooms)
}

View file

@ -87,6 +87,13 @@ pub enum DaemonRequest {
#[serde(rename = "unread_count")]
UnreadCount,
/// Return per-room unread summaries. For rooms with exactly one
/// unread notification, attempts to include the sender + truncated
/// body; rooms with multiple unreads carry only the count. Used by
/// `get_loose_ends` and the wake-signal formatter.
#[serde(rename = "unread_summary")]
UnreadSummary,
/// Liveness probe — fast "are you up?" round-trip that doesn't
/// touch matrix-sdk. Not used by the in-tree stdio MCP bridge
/// (which surfaces a daemon-down condition as a normal tool-call
@ -96,6 +103,23 @@ pub enum DaemonRequest {
Ping,
}
/// One entry in the [`DaemonRequest::UnreadSummary`] response payload.
#[derive(Debug, Serialize, Deserialize)]
pub struct RoomUnread {
/// Canonical alias (`#name:server`) or room id (`!id:server`).
pub label: String,
/// Server-side push-notification count for this room. Always ≥ 1.
pub count: u32,
/// Truncated body of the last message in the room. Present only when
/// `count == 1` and the fetch succeeded; absent otherwise.
#[serde(skip_serializing_if = "Option::is_none")]
pub last_body: Option<String>,
/// Sender of the last message (`@user:server`). Present when
/// `last_body` is present.
#[serde(skip_serializing_if = "Option::is_none")]
pub last_sender: Option<String>,
}
/// Response shape: `ok` carries the payload (any JSON; the MCP bridge
/// passes it back to claude as the tool result), `error` carries a
/// human-readable error string.

View file

@ -84,5 +84,6 @@ async fn dispatch(req: DaemonRequest, client: &Client) -> DaemonResponse {
DaemonRequest::ListRoomMembers { room } => handlers::list_room_members(client, &room).await,
DaemonRequest::ReadRoom { room, limit } => handlers::read_room(client, &room, limit).await,
DaemonRequest::UnreadCount => handlers::unread_count(client),
DaemonRequest::UnreadSummary => handlers::unread_summary(client).await,
}
}

View file

@ -16,18 +16,20 @@ use matrix_sdk::{
ruma::events::room::message::{MessageType, OriginalSyncRoomMessageEvent},
};
use crate::wake;
use crate::{handlers, wake};
/// Install the room-message handler on `client`. Fires on every
/// `m.room.message` event in a joined room; non-self text messages
/// trigger a wake signal to the hyperhive harness via the unix socket
/// at `hyperhive_socket`.
/// `m.room.message` event in a joined room; non-self messages trigger
/// a wake signal to the hyperhive harness via the unix socket at
/// `hyperhive_socket`. The wake body summarises ALL rooms with unread
/// notifications at wake time (not just the triggering event) so the
/// agent receives a full picture in one prompt.
pub fn install_message_handler(client: &Client, hyperhive_socket: PathBuf) {
let socket = Arc::new(hyperhive_socket);
let own_user = client.user_id().map(std::borrow::ToOwned::to_owned);
client.add_event_handler({
let socket = socket.clone();
move |event: OriginalSyncRoomMessageEvent, room: Room, _client: Client| {
move |event: OriginalSyncRoomMessageEvent, room: Room, client: Client| {
let socket = socket.clone();
let own_user = own_user.clone();
async move {
@ -39,21 +41,29 @@ pub fn install_message_handler(client: &Client, hyperhive_socket: PathBuf) {
if own_user.as_ref().is_some_and(|u| u == &event.sender) {
return;
}
let text = match &event.content.msgtype {
MessageType::Text(t) => t.body.clone(),
MessageType::Notice(n) => n.body.clone(),
MessageType::Emote(e) => format!("* {}", e.body),
_ => {
// Non-text content (image / file / location / etc.) —
// still wake, but with a placeholder body so the
// agent knows something landed and can read_room.
format!("[{}]", event.content.msgtype())
}
// Build a wake body that covers all rooms with unread
// notifications, not just the triggering event. This lets
// the agent see the full backlog in a single wake prompt.
// Falls back to the per-event teaser if the collect fails
// (empty result means daemon is not seeing any unread yet —
// unlikely but possible during a sync race).
let unread = handlers::collect_unread(&client).await;
let body = if unread.is_empty() {
// Sync hasn't updated notification counts yet; fall back
// to the current event so the agent still wakes.
let text = match &event.content.msgtype {
MessageType::Text(t) => t.body.clone(),
MessageType::Notice(n) => n.body.clone(),
MessageType::Emote(e) => format!("* {}", e.body),
_ => format!("[{}]", event.content.msgtype()),
};
let room_label = room
.canonical_alias()
.map_or_else(|| room.room_id().to_string(), |a| a.to_string());
wake::format_wake_body(event.sender.as_str(), &room_label, &text)
} else {
wake::format_unread_summary(&unread)
};
let room_label = room
.canonical_alias()
.map_or_else(|| room.room_id().to_string(), |a| a.to_string());
let body = wake::format_wake_body(event.sender.as_str(), &room_label, &text);
if let Err(e) = wake::send_wake(&socket, &body).await {
tracing::warn!(error = %e, "failed to deliver matrix wake to hyperhive");
} else {

View file

@ -72,10 +72,51 @@ pub fn format_wake_body(sender: &str, room: &str, text: &str) -> String {
format!("[matrix] {sender} in {room}: {truncated}")
}
/// Format a wake-message body from a list of per-room unread summaries.
/// Single-room / single-message case collapses to the terse one-liner
/// format; multiple rooms expand to a bulleted list. Always appends a
/// read-hint line so the agent knows which tools to reach for.
#[must_use]
pub fn format_unread_summary(rooms: &[crate::protocol::RoomUnread]) -> String {
use std::fmt::Write as _;
if rooms.is_empty() {
return String::new();
}
// Terse path: exactly one room, exactly one unread with body.
if rooms.len() == 1 {
let r = &rooms[0];
if r.count == 1 {
if let (Some(body), Some(sender)) = (&r.last_body, &r.last_sender) {
return format!(
"[matrix] {sender} in {label}: {body} — use read_room to view, mark_read to clear",
label = r.label
);
}
}
return format!(
"[matrix] {} unread in {} — use read_room to view, mark_read to clear",
r.count, r.label
);
}
// Multi-room path.
let mut out = String::from("[matrix] unread messages:");
for r in rooms {
if r.count == 1 {
if let (Some(body), Some(sender)) = (&r.last_body, &r.last_sender) {
let _ = write!(out, "\n- {}: {sender}: {body}", r.label);
continue;
}
}
let _ = write!(out, "\n- {}: {} unread", r.label, r.count);
}
out.push_str("\nUse list_rooms + read_room to view, mark_read to clear.");
out
}
/// Truncate `s` to `max` Unicode chars, appending `…` when cut.
/// Char-based not byte-based so multi-byte content (most chat) doesn't
/// get cut mid-codepoint.
fn truncate_chars(s: &str, max: usize) -> String {
pub fn truncate_chars(s: &str, max: usize) -> String {
let mut end = s.len();
for (count, (i, _)) in s.char_indices().enumerate() {
if count == max {