Skip to content

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

Queued mail says when it is dropped, and that a new session taking the name gets it (#91)

hiyouwhatsapp4af7a00db08e
diff --git a/src/daemon/mail.rs b/src/daemon/mail.rs
index 659e41a..4f913b2 100644
--- a/src/daemon/mail.rs
+++ b/src/daemon/mail.rs
@@ -74,6 +74,24 @@ const UPGRADE: &str =
const LOOP_NOTE: &str = "refused: these two agents have exchanged a lot of messages in the last few minutes, which \
looks like a loop. Check with your user before continuing.";
+/// The note for mail queued for a session that is offline. Its unread mail is deleted at the first cleanup a day after
+/// it was last seen, unless it is one of the person's own mailboxes (`cli`), which are kept. Until then, a new session
+/// that takes the name gets the mail.
+fn offline_note(r: Option<&crate::store::Remembered>, now: i64) -> String {
+ const NAME: &str = "a new session that takes this name gets it";
+ let Some(r) = r else { return format!("queued: the session is offline; {NAME}") };
+ let seen = util::ago(r.last_seen, now);
+ let forgotten = r.last_seen.saturating_add(super::sessions::FORGET_MS);
+ if r.agent == "cli" {
+ format!("queued: last seen {seen} ago; {NAME}")
+ } else if forgotten <= now {
+ format!("queued: last seen {seen} ago; unread mail may be dropped any time; {NAME}")
+ } else {
+ let left = util::ago(now, forgotten);
+ format!("queued: last seen {seen} ago; unread mail is dropped after about {left} if it stays offline; {NAME}")
+ }
+}
+
impl Daemon {
#[allow(clippy::too_many_arguments)]
pub(super) async fn send(
@@ -194,9 +212,11 @@ impl Daemon {
g.store.insert(&mut msg, false)?;
self.deliver(&mut g, &key, vec![msg.clone()], wake)
}
- Target::Session { key: None, .. } => {
+ Target::Session { key: None, address } => {
+ let name = address.split_once('/').map_or("", |(_, n)| n);
+ let note = offline_note(g.store.session_by_name(name)?.as_ref(), now);
g.store.insert(&mut msg, false)?;
- ("queued".into(), "queued: the session is offline; delivered when it is back".into())
+ ("queued".into(), note)
}
Target::Remote { machine, .. } => {
let takes_files = remotes.get(&machine).is_some_and(|r| r.presence.has(files::FEATURE));
@@ -274,7 +294,8 @@ impl Daemon {
wake: bool,
) -> (String, String) {
let Some(l) = g.live.get(key) else {
- return ("queued".into(), "queued: the session is offline; delivered when it is back".into());
+ let note = offline_note(g.store.session_by_key(key).ok().flatten().as_ref(), util::now_ms());
+ return ("queued".into(), note);
};
if !wake {
return ("queued".into(), "queued as FYI: it reads it at its next natural pause".into());
@@ -500,7 +521,8 @@ impl Daemon {
let mut g = self.inner.lock().unwrap();
self.prune(&mut g);
let key = g.live.iter().find(|(_, l)| l.name == name).map(|(k, _)| k.clone());
- if key.is_none() && g.store.session_by_name(name)?.is_none_or(|r| self.cfg.off_in(&r.cwd)) {
+ let remembered = if key.is_none() { g.store.session_by_name(name)? } else { None };
+ if key.is_none() && remembered.as_ref().is_none_or(|r| self.cfg.off_in(&r.cwd)) {
return Ok(("refused".into(), format!("no session called {} on {}", msg.to, self.machine)));
}
if g.store.has(&msg.id)? {
@@ -535,7 +557,7 @@ impl Daemon {
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),
- None => ("queued".into(), "queued: the session is offline; delivered when it is back".into()),
+ None => ("queued".into(), offline_note(remembered.as_ref(), util::now_ms())),
};
if msg.notify { (state, format!("{note}; {}", self.notify(&msg).1)) } else { (state, note) }
};
@@ -718,6 +740,7 @@ where
#[cfg(test)]
mod tests {
use super::*;
+ use crate::team::TeamState;
use iroh::SecretKey;
use serde::Deserialize;
@@ -741,6 +764,98 @@ mod tests {
assert_eq!(days.iter().map(|d| (d.sent, d.received)).collect::<Vec<_>>(), [(1, 1)]);
}
+ const HOUR: i64 = 3_600_000;
+
+ fn codex(key: &str) -> SessionReg {
+ SessionReg {
+ key: key.into(),
+ agent: "codex".into(),
+ cwd: "/work/api".into(),
+ agent_session_id: None,
+ pid: None,
+ tier: Tier::Pull,
+ name: None,
+ }
+ }
+
+ /// Takes a session here offline, last seen `ago` before now. Returns its name.
+ fn gone(d: &Daemon, key: &str, ago: i64) -> String {
+ let mut g = d.inner.lock().unwrap();
+ let name = g.live.remove(key).unwrap().name;
+ g.store.touch_session(&name, util::now_ms() - ago).unwrap();
+ name
+ }
+
+ #[test]
+ fn queued_mail_says_when_it_may_be_dropped_and_who_gets_it() {
+ let seen = |agent: &str| crate::store::Remembered {
+ name: "api-codex".into(),
+ key: "codex:1".into(),
+ agent: agent.into(),
+ cwd: "/work/api".into(),
+ repo: None,
+ branch: None,
+ doing: None,
+ tier: Tier::Pull,
+ last_seen: 0,
+ };
+ let name = "a new session that takes this name gets it";
+ assert_eq!(
+ offline_note(Some(&seen("codex")), 3 * HOUR),
+ format!("queued: last seen 3h ago; unread mail is dropped after about 21h if it stays offline; {name}")
+ );
+ assert_eq!(
+ offline_note(Some(&seen("codex")), 24 * HOUR),
+ format!("queued: last seen 1d ago; unread mail may be dropped any time; {name}")
+ );
+ // The person's own mailboxes are never forgotten.
+ assert_eq!(offline_note(Some(&seen("cli")), 30 * HOUR), format!("queued: last seen 1d ago; {name}"));
+ assert_eq!(offline_note(None, 0), format!("queued: the session is offline; {name}"));
+ }
+
+ #[tokio::test]
+ async fn sending_to_an_offline_session_here_says_when_its_mail_may_be_dropped() {
+ let d = Arc::new(super::super::test_daemon(crate::config::Config::default()));
+ d.register(Some(1), codex("codex:1"), crate::git::GitInfo::default()).unwrap();
+ let to = d.register(Some(2), codex("codex:2"), crate::git::GitInfo::default()).unwrap().address;
+ gone(&d, "codex:2", 3 * HOUR);
+ 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 note = &res.recipients[0].note;
+ assert!(note.starts_with("queued: last seen 3h ago; unread mail is dropped after about 2"), "{note}");
+ }
+
+ #[test]
+ fn a_teammate_sending_to_an_offline_session_is_told_when_its_mail_may_be_dropped() {
+ let cfg = crate::config::Config { person: Some("alex".into()), ..Default::default() };
+ let d = Arc::new(super::super::test_daemon(cfg));
+ let bob = SecretKey::generate();
+ let mut team = TeamState::found("acme", &d.person, &d.machine, &d.key);
+ team.put_member(&d.key, bob.public(), "bob", "xps", true);
+ d.inner.lock().unwrap().team = Some(team);
+ d.register(Some(1), codex("codex:1"), crate::git::GitInfo::default()).unwrap();
+ let name = gone(&d, "codex:1", 3 * HOUR);
+ let msg = Message {
+ id: Ulid::generate().to_string(),
+ from: "bob/web".into(),
+ from_agent: None,
+ from_repo: None,
+ to: format!("alex/{name}"),
+ via: None,
+ reply_to: None,
+ body: "hi".into(),
+ wake: true,
+ notify: false,
+ sent_at: 0,
+ approval: None,
+ files: Vec::new(),
+ };
+ let (state, note) = d.receive(bob.public(), msg).unwrap();
+ assert_eq!(state, "queued");
+ assert!(note.starts_with("queued: last seen 3h ago; unread mail is dropped after about 2"), "{note}");
+ assert!(note.ends_with("; a new session that takes this name gets it"), "{note}");
+ }
+
#[test]
fn a_peers_message_id_is_a_ulid_as_written() {
let msg = |id: &str| Message {
diff --git a/src/daemon/sessions.rs b/src/daemon/sessions.rs
index b7d8a10..ea5528c 100644
--- a/src/daemon/sessions.rs
+++ b/src/daemon/sessions.rs
@@ -17,7 +17,7 @@ use std::{collections::HashSet, sync::Arc, time::Instant};
/// A hook-only session that hasn't fired a hook for this long is considered gone.
const HOOK_TTL_MS: i64 = 6 * 3_600_000;
/// A session gone this long isn't coming back: it is forgotten, with the mail it never read.
-const FORGET_MS: i64 = 24 * 3_600_000;
+pub(super) const FORGET_MS: i64 = 24 * 3_600_000;
/// A session in a folder that is off counts as mid-turn this long after its last prompt or tool call.
const OFF_TURN_MS: i64 = 10 * 60_000;