Skip to content

Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.

Daily message totals in the team reply

Lars Talian8d4b8c361616
diff --git a/src/daemon/mail.rs b/src/daemon/mail.rs
index 3215a30..85809b8 100644
--- a/src/daemon/mail.rs
+++ b/src/daemon/mail.rs
@@ -5,7 +5,7 @@
//! don't show them a second time.
use super::{Daemon, Inner, directory::Target, log};
-use crate::{agent, claude, config::Policy, files, proto::*, render, team::Signed, util};
+use crate::{agent, claude, config::Policy, files, proto::*, render, store::Counted, team::Signed, util};
use anyhow::{Result, anyhow, bail};
use iroh::EndpointId;
use std::{
@@ -209,6 +209,13 @@ impl Daemon {
}
}
};
+ if state != "refused" {
+ // Counting never stops a message.
+ let _ = g.store.count(now, Counted::Sent);
+ if here {
+ let _ = g.store.count(now, Counted::Received);
+ }
+ }
if notify && here && state != "refused" {
note = format!("{note}; {}", self.notify(&msg).1);
}
@@ -524,6 +531,7 @@ impl Daemon {
// A held message's files are saved only once the person approves it.
let held = policy == Policy::Hold;
g.store.insert(&mut msg, held)?;
+ let _ = g.store.count(util::now_ms(), Counted::Received);
let (state, note) = match key {
_ if held => ("held".into(), format!("held until {} approves it", self.person)),
Some(key) => self.deliver(&mut g, &key, vec![msg.clone()], msg.wake),
diff --git a/src/daemon/teamops.rs b/src/daemon/teamops.rs
index 165308f..158de82 100644
--- a/src/daemon/teamops.rs
+++ b/src/daemon/teamops.rs
@@ -222,6 +222,7 @@ impl Daemon {
machine: self.machine.clone(),
machines: Vec::new(),
features: vec![crate::files::FEATURE.into()],
+ messages: Vec::new(),
})
}
@@ -334,6 +335,7 @@ impl Daemon {
machine: self.machine.clone(),
machines: Vec::new(),
features: vec![crate::files::FEATURE.into()],
+ messages: Vec::new(),
};
{
let mut g = self.inner.lock().unwrap();
@@ -473,6 +475,7 @@ impl Daemon {
machine: self.machine.clone(),
machines: self.machines(),
features: vec![crate::files::FEATURE.into()],
+ messages: self.inner.lock().unwrap().store.counts(util::now_ms()).unwrap_or_default(),
})
}
diff --git a/src/main.rs b/src/main.rs
index ae8133b..b2c5db4 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -914,6 +914,7 @@ mod tests {
machine: "mbp".into(),
machines: vec![me],
features: vec![],
+ messages: vec![],
};
let l = LinkInfo { team: "vibes".into(), url: join_url("rn1-AAAA"), ticket: "rn1-AAAA".into() };
assert!(team_value(&t, &l, None).unwrap_err().to_string().contains("restart the Reason Network daemon"));
diff --git a/src/proto.rs b/src/proto.rs
index 3856eba..ba885da 100644
--- a/src/proto.rs
+++ b/src/proto.rs
@@ -391,6 +391,18 @@ pub struct TeamInfo {
/// for others. Older engines leave it out.
#[serde(default)]
pub features: Vec<String>,
+ /// How many messages sessions here sent, and how many reached mailboxes here, on each of the last seven days
+ /// (UTC) that had any: counts only, kept on this machine and sent nowhere. Older engines leave it out.
+ #[serde(default)]
+ pub messages: Vec<DayCount>,
+}
+
+#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
+pub struct DayCount {
+ /// `YYYY-MM-DD`, UTC.
+ pub day: String,
+ pub sent: u64,
+ pub received: u64,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
@@ -484,16 +496,19 @@ mod tests {
machine: "mbp".into(),
machines: vec![],
features: vec![],
+ messages: vec![DayCount { day: "2026-10-20".into(), sent: 3, received: 1 }],
};
let v = serde_json::to_value(&t).unwrap();
assert_eq!(v["team_id"], "00112233445566778899aabbccddeeff");
assert_eq!((v["team_name"].as_str(), v["name"].as_str()), (Some("vibes"), Some("vibes")));
+ assert_eq!(v["messages"], serde_json::json!([{"day": "2026-10-20", "sent": 3, "received": 1}]));
// A reply from a daemon before these fields still reads.
let old: TeamInfo =
serde_json::from_value(serde_json::json!({"name": "vibes", "relay": null, "person": "alex",
"machine": "mbp", "machines": []}))
.unwrap();
assert_eq!((old.id.as_str(), old.name.as_str()), ("", "vibes"));
+ assert!(old.messages.is_empty());
}
#[test]
diff --git a/src/render.rs b/src/render.rs
index 7fcccaf..c00af18 100644
--- a/src/render.rs
+++ b/src/render.rs
@@ -416,6 +416,7 @@ mod tests {
machine: "mbp".into(),
machines: Vec::new(),
features: Vec::new(),
+ messages: Vec::new(),
};
assert_eq!(team(&t), "team vibes · relay: Reason's (the default)\n");
t.relay = Some("https://relay.example.com".into());
diff --git a/src/store.rs b/src/store.rs
index bf25d22..6246072 100644
--- a/src/store.rs
+++ b/src/store.rs
@@ -4,7 +4,7 @@
use crate::{
files,
- proto::{Attachment, Message, Tier},
+ proto::{Attachment, DayCount, Message, Tier},
};
use anyhow::Result;
use rusqlite::{Connection, OptionalExtension, Row, params};
@@ -29,6 +29,16 @@ struct Kept {
files: Vec<Attachment>,
}
+/// What [`Store::count`] counts: a message a session here sent, or one that reached a mailbox here.
+#[derive(Clone, Copy)]
+pub enum Counted {
+ Sent,
+ Received,
+}
+
+/// Message counts are kept for today and the six days before it (an SQLite date modifier).
+const COUNTS_SINCE: &str = "-6 days";
+
/// A held message that can't be approved now, and why (it stays held).
pub type Unsaved = (String, String);
@@ -84,6 +94,11 @@ CREATE TABLE IF NOT EXISTS sessions (
last_seen INTEGER NOT NULL
);
CREATE INDEX IF NOT EXISTS sessions_key ON sessions (key);
+CREATE TABLE IF NOT EXISTS counts (
+ day TEXT PRIMARY KEY,
+ sent INTEGER NOT NULL DEFAULT 0,
+ received INTEGER NOT NULL DEFAULT 0
+);
";
const MESSAGE_COLS: &str =
@@ -331,6 +346,35 @@ impl Store {
Ok(())
}
+ /// Adds one to today's count (by UTC day). Only numbers are kept, and only for a week.
+ pub fn count(&self, now: i64, what: Counted) -> Result<()> {
+ let col = match what {
+ Counted::Sent => "sent",
+ Counted::Received => "received",
+ };
+ self.db.execute(
+ &format!(
+ "INSERT INTO counts (day, {col}) VALUES (date(?1 / 1000, 'unixepoch'), 1)
+ ON CONFLICT (day) DO UPDATE SET {col} = {col} + 1"
+ ),
+ [now],
+ )?;
+ self.db
+ .execute("DELETE FROM counts WHERE day < date(?1 / 1000, 'unixepoch', ?2)", params![now, COUNTS_SINCE])?;
+ Ok(())
+ }
+
+ /// The days kept that had messages, oldest first.
+ pub fn counts(&self, now: i64) -> Result<Vec<DayCount>> {
+ let mut st = self.db.prepare_cached(
+ "SELECT day, sent, received FROM counts WHERE day >= date(?1 / 1000, 'unixepoch', ?2) ORDER BY day",
+ )?;
+ let rows = st.query_map(params![now, COUNTS_SINCE], |r| {
+ Ok(DayCount { day: r.get(0)?, sent: r.get(1)?, received: r.get(2)? })
+ })?;
+ Ok(rows.collect::<rusqlite::Result<_>>()?)
+ }
+
pub fn get(&self, key: &str) -> Result<Option<String>> {
Ok(self.db.query_row("SELECT value FROM kv WHERE key = ?1", [key], |r| r.get(0)).optional()?)
}
@@ -511,6 +555,42 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
+ #[test]
+ fn messages_are_counted_by_day_for_a_week_and_kept_across_restarts() {
+ let dir = std::env::temp_dir().join(format!("reason-network-counts-{}", ulid::Ulid::new()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let db = dir.join("network.db");
+ let day = 86_400_000;
+ let oct20 = 1_792_454_400_000; // 2026-10-20T00:00:00Z
+ let store = Store::open(&db, temp_inbox()).unwrap();
+ assert_eq!(store.counts(oct20).unwrap(), []);
+ for (at, what) in [
+ (oct20 - 7 * day, Counted::Sent),
+ (oct20 - 6 * day, Counted::Received),
+ (oct20 - 1, Counted::Sent),
+ (oct20, Counted::Sent),
+ (oct20 + day - 1, Counted::Sent),
+ (oct20 + 5, Counted::Received),
+ ] {
+ store.count(at, what).unwrap();
+ }
+ drop(store);
+ let store = Store::open(&db, temp_inbox()).unwrap();
+ let count = |day: &str, sent, received| DayCount { day: day.into(), sent, received };
+ assert_eq!(
+ store.counts(oct20 + 1).unwrap(),
+ [count("2026-10-14", 0, 1), count("2026-10-19", 1, 0), count("2026-10-20", 2, 1)]
+ );
+ // The next day, the oldest goes.
+ store.count(oct20 + day, Counted::Received).unwrap();
+ assert_eq!(
+ store.counts(oct20 + day).unwrap(),
+ [count("2026-10-19", 1, 0), count("2026-10-20", 2, 1), count("2026-10-21", 0, 1)]
+ );
+ drop(store);
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
#[test]
fn a_session_gone_a_day_is_forgotten_with_the_mail_it_never_read() {
// (Not one that is live, nor the person's own mailbox, nor mail held for the person.)
diff --git a/tests/e2e/two_machines.py b/tests/e2e/two_machines.py
index e799b32..078f02d 100644
--- a/tests/e2e/two_machines.py
+++ b/tests/e2e/two_machines.py
@@ -356,11 +356,25 @@ out = cli("alex", "who")
check("alex sees what alice's codex is doing, read from its plan", "work-codex" in out and "testing cross-machine Reason Network" in out, out)
# --- messages across machines ---
+def counts(who):
+ """Today's (sent, received) on `who`'s machine, from the daemon's team reply, where the Reason CLI reads them."""
+ import socket
+ with socket.socket(socket.AF_UNIX) as sock:
+ sock.settimeout(30)
+ sock.connect(os.path.join(H[who], "network.sock"))
+ sock.sendall(b'{"id": 1, "op": "team"}\n')
+ days = as_json(sock.makefile().readline()).get("result", {}).get("messages", [])
+ today = next((d for d in days if d["day"] == time.strftime("%Y-%m-%d", time.gmtime())), {})
+ return today.get("sent", 0), today.get("received", 0)
+before = {who: counts(who) for who in H}
out = codex.tool("send_message", {"to": f"alex/{claude_name}", "message": "Reason Network e2e (cross-machine push): ignore this."}, meta)
want = "delivered into the session" if IN_CLAUDE else "only sees it when it checks"
check("cross-machine send reaches the Claude session", want in out, out)
out = cli("alex", "send", "alice/work-codex", "hello from alex's terminal")
check("a terminal send to a remote pull session is queued there", "only sees it when it checks its inbox" in out, out)
+after = {who: counts(who) for who in H}
+check("each machine counts the messages it sent and received today",
+ all(after[who] == (before[who][0] + 1, before[who][1] + 1) for who in H), (before, after))
out = codex.tool("check_inbox", {}, meta)
check("remote message arrives in codex inbox, from alex/terminal", 'from="alex/terminal"' in out and "hello from alex's terminal" in out, out)
out = codex.tool("check_inbox", {}, meta)