Skip to content

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

Message totals: sent on delivery, once per message (#82)

Lars Talian5df89c470931
diff --git a/src/daemon/ask.rs b/src/daemon/ask.rs
index ffa74af..3496a7d 100644
--- a/src/daemon/ask.rs
+++ b/src/daemon/ask.rs
@@ -521,6 +521,25 @@ if ($script:choice) { "$($script:choice)`n$(& $chars $req $reqShown)`n$(& $chars
mod tests {
use super::*;
+ #[tokio::test]
+ async fn a_late_answer_reaches_the_session_but_isnt_counted_as_a_message() {
+ let d = Arc::new(super::super::test_daemon(crate::config::Config::default()));
+ let reg = crate::proto::SessionReg {
+ key: "codex:1".into(),
+ agent: "codex".into(),
+ cwd: "/work/api".into(),
+ agent_session_id: None,
+ pid: None,
+ tier: crate::proto::Tier::Pull,
+ name: None,
+ };
+ let address = d.register(None, reg, crate::git::GitInfo::default()).unwrap().address;
+ d.answer_later("codex:1", "ship it?", &Answer::Approved(String::new()));
+ let g = d.inner.lock().unwrap();
+ assert!(g.store.unread(&address).unwrap()[0].body.contains("ship it?"));
+ assert_eq!(g.store.counts(util::now_ms()).unwrap(), []);
+ }
+
#[test]
fn what_shows_is_what_is_there() {
// A direction override can't turn text around, nor a spacer or tag character hide in it; joiners stay.
diff --git a/src/daemon/mail.rs b/src/daemon/mail.rs
index 85809b8..79df3d8 100644
--- a/src/daemon/mail.rs
+++ b/src/daemon/mail.rs
@@ -209,12 +209,10 @@ impl Daemon {
}
}
};
- if state != "refused" {
- // Counting never stops a message.
+ // Counting never stops a message. One to another machine counts once that machine takes it.
+ if here && state != "refused" {
let _ = g.store.count(now, Counted::Sent);
- if here {
- let _ = g.store.count(now, Counted::Received);
- }
+ let _ = g.store.count(now, Counted::Received);
}
if notify && here && state != "refused" {
note = format!("{note}; {}", self.notify(&msg).1);
@@ -530,8 +528,10 @@ 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);
+ // Counted once, when it is new here; a held one once approved.
+ if g.store.insert(&mut msg, held)? && !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),
@@ -721,6 +721,26 @@ mod tests {
use iroh::SecretKey;
use serde::Deserialize;
+ #[tokio::test]
+ async fn a_message_between_sessions_here_counts_as_sent_and_received_once() {
+ let d = Arc::new(super::super::test_daemon(crate::config::Config::default()));
+ let reg = |key: &str, cwd: &str| SessionReg {
+ key: key.into(),
+ agent: "codex".into(),
+ cwd: cwd.into(),
+ agent_session_id: None,
+ pid: None,
+ tier: Tier::Pull,
+ name: None,
+ };
+ d.register(Some(1), reg("codex:1", "/work/api"), crate::git::GitInfo::default()).unwrap();
+ let to = d.register(Some(2), reg("codex:2", "/work/web"), crate::git::GitInfo::default()).unwrap().address;
+ let res = d.send("codex:1".into(), &to, "hi", None, true, false, None, Vec::new()).await.unwrap();
+ assert_eq!(res.recipients[0].state, "queued");
+ let days = d.inner.lock().unwrap().store.counts(util::now_ms()).unwrap();
+ assert_eq!(days.iter().map(|d| (d.sent, d.received)).collect::<Vec<_>>(), [(1, 1)]);
+ }
+
#[test]
fn a_peers_message_id_is_a_ulid_as_written() {
let msg = |id: &str| Message {
diff --git a/src/daemon/teamops.rs b/src/daemon/teamops.rs
index 158de82..142fbbb 100644
--- a/src/daemon/teamops.rs
+++ b/src/daemon/teamops.rs
@@ -99,8 +99,8 @@ impl Daemon {
self.inner.lock().unwrap().store.outbox_for(&id.to_string(), util::now_ms()).unwrap_or_default()
}
- pub fn outbox_done(&self, id: &str) {
- let _ = self.inner.lock().unwrap().store.outbox_done(id);
+ pub fn outbox_done(&self, id: &str, taken: bool) {
+ let _ = self.inner.lock().unwrap().store.outbox_done(id, taken);
}
/// Takes in a teammate's copy of the team state, passing it on if it taught us something.
diff --git a/src/net.rs b/src/net.rs
index f1df900..5e8a329 100644
--- a/src/net.rs
+++ b/src/net.rs
@@ -760,7 +760,7 @@ impl Net {
Wire::Ack { id, state, note } => {
// "retry": the other side is busy; keep it in the outbox for the next flush.
if state != "retry" {
- daemon.outbox_done(&id);
+ daemon.outbox_done(&id, state != "refused");
}
if let Some(waiter) = self.acks.lock().unwrap().remove(&id) {
let _ = waiter.send((state, note));
diff --git a/src/proto.rs b/src/proto.rs
index ba885da..37b1cb6 100644
--- a/src/proto.rs
+++ b/src/proto.rs
@@ -391,8 +391,9 @@ 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.
+ /// Per-day totals of messages sent and received on this machine, returned to local clients on the socket: sent
+ /// once the receiving machine took them, received once in a mailbox here (a held one once approved). For the days
+ /// (UTC) from six before today to tomorrow that had any. Older engines leave it out.
#[serde(default)]
pub messages: Vec<DayCount>,
}
diff --git a/src/store.rs b/src/store.rs
index 6246072..392e36d 100644
--- a/src/store.rs
+++ b/src/store.rs
@@ -29,15 +29,20 @@ struct Kept {
files: Vec<Attachment>,
}
-/// What [`Store::count`] counts: a message a session here sent, or one that reached a mailbox here.
+/// What [`Store::count`] counts: a message a session here sent, once the receiving machine took it, or one that reached
+/// a mailbox here (counted by whoever stores it, or once approved if it was held).
#[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";
+/// The days whose message counts are shown: today, the six before it, and tomorrow (SQLite date modifiers).
+const COUNTS_FROM: &str = "-6 days";
+const COUNTS_TO: &str = "+1 day";
+/// Days of counts kept: the last ones started, in the order they started rather than by date, so a clock that jumps
+/// doesn't push out the real ones.
+const COUNTS_KEPT: i64 = 8;
/// A held message that can't be approved now, and why (it stays held).
pub type Unsaved = (String, String);
@@ -320,6 +325,7 @@ impl Store {
}
return Err(e.into());
}
+ let _ = self.count(crate::util::now_ms(), Counted::Received);
done.push(m);
}
Ok((done, unsaved))
@@ -341,12 +347,16 @@ impl Store {
Ok(rows.filter_map(|r| r.ok().and_then(|s| serde_json::from_str(&s).ok())).collect())
}
- pub fn outbox_done(&self, id: &str) -> Result<()> {
- self.db.execute("DELETE FROM outbox WHERE id = ?1", [id])?;
+ /// The receiving machine answered for a message: it leaves the outbox, and counts as sent if that machine took it
+ /// (once, however many answers come).
+ pub fn outbox_done(&self, id: &str, taken: bool) -> Result<()> {
+ if self.db.execute("DELETE FROM outbox WHERE id = ?1", [id])? == 1 && taken {
+ let _ = self.count(crate::util::now_ms(), Counted::Sent);
+ }
Ok(())
}
- /// Adds one to today's count (by UTC day). Only numbers are kept, and only for a week.
+ /// Adds one to today's count (by UTC day). Only numbers are kept, and only for the last few days.
pub fn count(&self, now: i64, what: Counted) -> Result<()> {
let col = match what {
Counted::Sent => "sent",
@@ -359,17 +369,20 @@ impl Store {
),
[now],
)?;
- self.db
- .execute("DELETE FROM counts WHERE day < date(?1 / 1000, 'unixepoch', ?2)", params![now, COUNTS_SINCE])?;
+ self.db.execute(
+ "DELETE FROM counts WHERE rowid NOT IN (SELECT rowid FROM counts ORDER BY rowid DESC LIMIT ?1)",
+ [COUNTS_KEPT],
+ )?;
Ok(())
}
- /// The days kept that had messages, oldest first.
+ /// The days shown 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",
+ "SELECT day, sent, received FROM counts
+ WHERE day BETWEEN date(?1 / 1000, 'unixepoch', ?2) AND date(?1 / 1000, 'unixepoch', ?3) ORDER BY day",
)?;
- let rows = st.query_map(params![now, COUNTS_SINCE], |r| {
+ let rows = st.query_map(params![now, COUNTS_FROM, COUNTS_TO], |r| {
Ok(DayCount { day: r.get(0)?, sent: r.get(1)?, received: r.get(2)? })
})?;
Ok(rows.collect::<rusqlite::Result<_>>()?)
@@ -591,6 +604,62 @@ mod tests {
std::fs::remove_dir_all(&dir).unwrap();
}
+ #[test]
+ fn counts_are_shown_to_tomorrow_and_a_clock_that_jumps_loses_no_real_days() {
+ let store = Store::open(Path::new(":memory:"), temp_inbox()).unwrap();
+ let day = 86_400_000;
+ let oct20 = 1_792_454_400_000; // 2026-10-20T00:00:00Z
+ let count = |day: &str, sent| DayCount { day: day.into(), sent, received: 0 };
+ for at in [oct20 - 6 * day, oct20, oct20 + day, oct20 + 2 * day] {
+ store.count(at, Counted::Sent).unwrap();
+ }
+ let week = [count("2026-10-14", 1), count("2026-10-20", 1), count("2026-10-21", 1)];
+ assert_eq!(store.counts(oct20).unwrap(), week, "not the day after tomorrow");
+ // The clock is a year ahead for a while, then right again.
+ store.count(oct20 + 365 * day, Counted::Sent).unwrap();
+ assert_eq!(store.counts(oct20).unwrap(), week);
+ assert_eq!(store.counts(oct20 + 365 * day).unwrap(), [count("2027-10-20", 1)]);
+ // Only the last days begun are kept.
+ for i in 3..20 {
+ store.count(oct20 + i * day, Counted::Sent).unwrap();
+ }
+ let kept: i64 = store.db.query_row("SELECT COUNT(*) FROM counts", [], |r| r.get(0)).unwrap();
+ assert_eq!(kept, COUNTS_KEPT);
+ assert_eq!(store.counts(oct20 + 19 * day).unwrap().len(), 7);
+ }
+
+ #[test]
+ fn a_message_counts_as_sent_once_taken_and_as_received_once_in_a_mailbox() {
+ let inbox = temp_inbox();
+ let store = Store::open(Path::new(":memory:"), inbox.clone()).unwrap();
+ let totals = |store: &Store| {
+ let days = store.counts(util::now_ms()).unwrap();
+ (days.iter().map(|d| d.sent).sum::<u64>(), days.iter().map(|d| d.received).sum::<u64>())
+ };
+ // Sent: once the other machine takes it (answered twice, after a lost answer), not when it refuses it or it
+ // expires in the outbox.
+ for id in ["01TAKEN", "01REFUSED", "01EXPIRED"] {
+ store.outbox_add("peer", &with_files(id, "sven/api")).unwrap();
+ }
+ store.outbox_done("01TAKEN", true).unwrap();
+ store.outbox_done("01TAKEN", true).unwrap();
+ store.outbox_done("01REFUSED", false).unwrap();
+ assert!(store.outbox_for("peer", util::now_ms() + 8 * 86_400_000).unwrap().is_empty());
+ assert_eq!(totals(&store), (1, 0));
+ // Received: held, it counts once approved. Dropped, then sent again after a lost answer, it counts once.
+ store.insert(&mut with_files("01HELD", "lars/api"), true).unwrap();
+ store.settle_held(&["01HELD".into()], false).unwrap();
+ store.insert(&mut with_files("01HELD", "lars/api"), true).unwrap();
+ assert_eq!(totals(&store), (1, 0));
+ store.settle_held(&["01HELD".into()], true).unwrap();
+ assert!(!store.insert(&mut with_files("01HELD", "lars/api"), true).unwrap());
+ assert_eq!(totals(&store), (1, 1));
+ // Storing one that isn't held counts nothing: the caller counts it if it is a message.
+ store.insert(&mut with_files("01NEW", "lars/api"), false).unwrap();
+ assert_eq!(totals(&store), (1, 1));
+ std::fs::remove_dir_all(&inbox).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 078f02d..a2107f9 100644
--- a/tests/e2e/two_machines.py
+++ b/tests/e2e/two_machines.py
@@ -523,16 +523,22 @@ time.sleep(3)
cli("alice", "team")
time.sleep(5)
before = inbox("alice")
+totals = {who: counts(who) for who in H}
out = cli("alex", "send", "alice/work-codex", "--file", notes, "held message")
check("message to alice is held by her policy", "held until alice approves" in out, out)
+check("a held message counts as sent, and as received only once approved",
+ counts("alex")[0] == totals["alex"][0] + 1 and counts("alice") == totals["alice"], (totals, counts("alex"), counts("alice")))
out = codex.tool("check_inbox", {}, meta)
check("held message is not delivered", "held message" not in out, out)
check("…and its files aren't saved yet", inbox("alice") == before, inbox("alice"))
out = cli("alice", "held")
check("Reason Network held lists it", "held message" in out and "notes.md (saved once approved)" in out, out)
-cli("alice", "approve", "--all")
+approved = cli("alice", "approve", "--all")
out = codex.tool("check_inbox", {}, meta)
check("approved message is delivered", "held message" in out, out)
+# (With any of the quota test's messages that came back while alex was held.)
+n = int(re.search(r"Delivered (\d+)", approved).group(1))
+check("…and counted as received now", n >= 1 and counts("alice")[1] == totals["alice"][1] + n, (approved, totals, counts("alice")))
check("…with its files saved now", [os.path.basename(p) for p in saved(message_with(out, "held message"), "alice")] == ["notes.md"], out)
# Refused: nothing of it is kept.
text = open(cfg).read()
@@ -542,8 +548,10 @@ time.sleep(3)
cli("alice", "team")
time.sleep(5)
before = inbox("alice")
+totals = {who: counts(who) for who in H}
out = cli("alex", "send", "alice/work-codex", "--file", notes, "refused message")
check("a refused message's files are never saved", "doesn't accept messages from alex" in out and inbox("alice") == before, out)
+check("…and it counts as neither sent nor received", {who: counts(who) for who in H} == totals, totals)
open(cfg, "w").write(text)
cli("alice", "stop")
time.sleep(3)
@@ -554,14 +562,17 @@ time.sleep(5)
codex.close()
cli("alice", "stop")
time.sleep(1)
+sent = counts("alex")[0]
out = cli("alex", "send", "alice/work-codex", "sent while you were offline")
check("message to an offline machine is queued", "not connected" in out or "no answer" in out, out)
+check("…and not counted as sent while it waits in the outbox", counts("alex")[0] == sent, (sent, counts("alex")))
cli("alice", "team") # restarts alice's daemon
time.sleep(8)
cli("alice", "approve", "--all") # alice still holds messages from alex (the hold policy above)
codex = Mcp("alice", "codex-mcp-client", strip_claude=True, cwd=os.path.join(D, "work"))
out = codex.tool("check_inbox", {}, meta)
check("outbox delivers when the machine is back", "sent while you were offline" in out, out)
+check("…and counts as sent once it got there", counts("alex")[0] == sent + 1, (sent, counts("alex")))
codex.close()
# --- removal while away ---