Skip to content

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

A teammate's terminal shows in a receipt as its answer shows; ask sessions aren't kept for good (#111)

Lars Talian0bd89a1e9520
diff --git a/DESIGN.md b/DESIGN.md
index 0d470bc..52b05f0 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -80,9 +80,11 @@ isn't kept, and it doesn't push later sessions to `-2`, `-3`.
them.
- The person's own mailboxes (`listen --as <name>`, `terminal`) are kept for good, on their own machine. `listen --as`
a name that is kept for another session gets the next free one, and the name it asked for as soon as that is free
- again (with the mail from the other).
+ again (with the mail from the other). Other `cli` sessions, such as the Reason CLI's one-off ask sessions, are
+ sessions like any other: forgotten a day after they were last seen.
- Each machine has its own `terminal`: another machine's never makes it take a suffix. A teammate's machine shows a
- message from it as from `<you>/terminal@<machine>`, so a reply goes back to that machine. On one of your machines
+ message from it as from `<you>/terminal@<machine>`, so a reply goes back to that machine, and the receipt of a
+ message to it names it that way too, so an answer with no `reply_to` matches what was asked. On one of your machines
that has its own, `<you>/terminal` alone is that one; anywhere else, with two of yours on, it is ambiguous and the
error names each `@<machine>`, as for any two sessions of one name. An engine from before this shows the message as
from `<you>/terminal`, and couldn't tell two apart: while any machine in the team may be one (its presence lacks the
diff --git a/src/daemon/ask.rs b/src/daemon/ask.rs
index 41d17d2..789553f 100644
--- a/src/daemon/ask.rs
+++ b/src/daemon/ask.rs
@@ -230,6 +230,7 @@ impl Daemon {
doing: None,
name: Some("terminal".into()),
dirs: Vec::new(),
+ keep: false,
};
if let Err(e) = self.hook(call).await {
log(&format!("couldn't register {}/terminal: {e:#}", self.person));
diff --git a/src/daemon/directory.rs b/src/daemon/directory.rs
index 69886cb..6d51561 100644
--- a/src/daemon/directory.rs
+++ b/src/daemon/directory.rs
@@ -36,6 +36,14 @@ impl Target {
Target::Session { address, .. } | Target::Remote { address, .. } => address.clone(),
}
}
+
+ /// Its address as a message from it shows here, which a receipt names: a teammate's terminal with its machine.
+ pub(super) fn shown_address(&self) -> String {
+ match self {
+ Target::Session { address, .. } => address.clone(),
+ Target::Remote { address, machine_name, .. } => crate::render::shown_from(address, machine_name),
+ }
+ }
}
/// Something an address can match.
@@ -192,7 +200,7 @@ impl Daemon {
}
}
- fn row(&self, name: &str, agent: &str, cwd: &str, git: Option<&GitInfo>) -> SessionInfo {
+ pub(super) fn row(&self, name: &str, agent: &str, cwd: &str, git: Option<&GitInfo>) -> SessionInfo {
SessionInfo {
address: self.addr(name),
name: name.to_string(),
@@ -667,6 +675,7 @@ mod tests {
tier: Tier::Push,
last_seen: util::now_ms(),
attached: true,
+ mailbox: false,
};
d.inner.lock().unwrap().store.upsert_session(&r, &d.person).unwrap();
}
diff --git a/src/daemon/mail.rs b/src/daemon/mail.rs
index 2e50f49..c42792c 100644
--- a/src/daemon/mail.rs
+++ b/src/daemon/mail.rs
@@ -84,7 +84,7 @@ const LOOP_NOTE: &str = "refused: these two agents have exchanged a lot of messa
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 it waits for
+/// it was last seen, unless it is one of the person's own mailboxes (`terminal`, `listen --as`), which are kept. Until then it waits for
/// that session, when the session can come back to its name (see [`Remembered::kept`]); else a new session that takes
/// the name gets it.
fn offline_note(r: Option<&Remembered>, now: i64) -> String {
@@ -94,7 +94,7 @@ fn offline_note(r: Option<&Remembered>, now: i64) -> String {
let who = if r.kept() { BACK } else { NAME };
let seen = util::ago(r.last_seen, now);
let forgotten = r.last_seen.saturating_add(super::sessions::FORGET_MS);
- if r.agent == "cli" {
+ if r.mailbox {
format!("queued: last seen {seen} ago; {who}")
} else if forgotten <= now {
format!("queued: last seen {seen} ago; unread mail may be dropped any time; {who}")
@@ -217,6 +217,8 @@ impl Daemon {
files: files.clone(),
};
res.ids.push(msg.id.clone());
+ // The receipt names it as its answer will show here: a teammate's terminal with its machine.
+ let shown = t.shown_address();
let here = !matches!(t, Target::Remote { .. });
let (state, mut note): (String, String) = match t {
_ if !matches!(t, Target::Remote { .. }) && !g.loop_ok(&msg.from, &msg.to) => {
@@ -251,7 +253,7 @@ impl Daemon {
if notify && here && state != "refused" {
note = format!("{note}; {}", self.notify(&msg).1);
}
- res.recipients.push(Recipient { address: msg.to.clone(), state, note });
+ res.recipients.push(Recipient { address: shown, state, note });
}
}
self.arrived.notify_waiters();
@@ -586,9 +588,7 @@ impl Daemon {
return Ok(("refused".into(), note));
}
// Each machine has its own terminal: replies go back to the one this came from.
- if render::from_terminal(&msg.from) {
- msg.from = format!("{}@{machine}", msg.from);
- }
+ msg.from = render::shown_from(&msg.from, &machine);
// A held message's files are saved only once the person approves it.
let held = policy == Policy::Hold;
// Held for a session whose name is kept, it is that session's: it goes when the session does.
@@ -790,6 +790,7 @@ mod tests {
use crate::team::TeamState;
use iroh::SecretKey;
use serde::Deserialize;
+ use std::collections::HashMap;
#[tokio::test]
async fn a_message_between_sessions_here_counts_as_sent_and_received_once() {
@@ -846,6 +847,7 @@ mod tests {
tier: Tier::Pull,
last_seen: 0,
attached: true,
+ mailbox: agent == "cli",
};
// A conversation its agent gave an id waits for it, whoever takes the name meanwhile.
let back = "it reaches that session when it's back";
@@ -943,6 +945,34 @@ mod tests {
text.contains("From bob, typed in a terminal.") && text.contains("send_message to \"bob/terminal@xps\""),
"{text}"
);
+ // Asked the other way: a message to `bob/terminal` names it in its receipt as Bob's answer will show here, so a
+ // reply with no `reply_to` matches it (the Reason CLI and server match answers that way).
+ let mut terminal = d.row("terminal", "cli", "/", None);
+ terminal.tier = Tier::Pull;
+ let remotes = HashMap::from([(
+ bob.public(),
+ crate::net::Remote {
+ presence: crate::net::Presence { sessions: vec![terminal], ..Default::default() },
+ last_seen: util::now_ms(),
+ online: true,
+ },
+ )]);
+ let g = d.inner.lock().unwrap();
+ let targets = d.resolve(&g, &remotes, "bob/terminal", None).unwrap();
+ assert_eq!(targets.iter().map(|t| t.shown_address()).collect::<Vec<_>>(), [got[0].from.clone()]);
+ // A teammate's session goes by its name alone, there and here.
+ let mut web = d.row("web-codex", "codex", "/", None);
+ web.tier = Tier::Pull;
+ let remotes = HashMap::from([(
+ bob.public(),
+ crate::net::Remote {
+ presence: crate::net::Presence { sessions: vec![web], ..Default::default() },
+ last_seen: util::now_ms(),
+ online: true,
+ },
+ )]);
+ let targets = d.resolve(&g, &remotes, "bob/web-codex", None).unwrap();
+ assert_eq!(targets.iter().map(|t| t.shown_address()).collect::<Vec<_>>(), ["bob/web-codex"]);
}
#[tokio::test]
diff --git a/src/daemon/mod.rs b/src/daemon/mod.rs
index f5a76e0..8c22a89 100644
--- a/src/daemon/mod.rs
+++ b/src/daemon/mod.rs
@@ -174,6 +174,8 @@ struct Live {
stop_gen: u64,
/// Its MCP connection pushes into it (it registered as `push`, knowing the agent's inbox). Claude Code's only.
mcp_push: bool,
+ /// One of the person's own mailboxes: `terminal`, or a name they gave with `listen --as`. Kept for good.
+ mailbox: bool,
/// It could be reached beyond its own hooks: an MCP server connected for it or attached a call to it, a push channel
/// delivers into it (Claude Code's inbox, `codex queue`, the opencode and pi plugins, Reason), or it is one of the
/// person's own mailboxes. Only such a session keeps its name while offline: a run only its hooks ever saw (a
diff --git a/src/daemon/sessions.rs b/src/daemon/sessions.rs
index e8b83d5..2e23c10 100644
--- a/src/daemon/sessions.rs
+++ b/src/daemon/sessions.rs
@@ -119,6 +119,7 @@ impl Daemon {
stop_gen: 0,
attached,
mcp_push,
+ mailbox: key == TERMINAL,
},
);
self.presence_changed();
@@ -173,7 +174,7 @@ impl Daemon {
/// Whether a session remembered here still keeps its name from every other session: one that can come back to it
/// (see [`Remembered::kept`]), until it would be forgotten. The person's own mailboxes are never forgotten.
pub(super) fn holds(&self, r: &Remembered, now: i64) -> bool {
- r.kept() && (r.agent == "cli" || now - r.last_seen <= FORGET_MS || !self.forgetting(now))
+ r.kept() && (r.mailbox || now - r.last_seen <= FORGET_MS || !self.forgetting(now))
}
/// Whether sessions gone a day are forgotten yet: not just after a start, while sessions that are still up haven't
@@ -207,6 +208,19 @@ impl Daemon {
}
}
+ /// Marks a live session as one of the person's own mailboxes, kept for good.
+ fn mailbox(&self, key: &str, now: i64) -> Result<()> {
+ let mut g = self.inner.lock().unwrap();
+ let g = &mut *g;
+ if let Some(l) = g.live.get_mut(key)
+ && !l.mailbox
+ {
+ l.mailbox = true;
+ g.store.upsert_session(&remembered(l, now), &self.person)?;
+ }
+ Ok(())
+ }
+
/// Before `key` takes `name`: a session that kept the name until it lapsed is forgotten, with the mail it never
/// read, which is never another session's. A session known only by its process leaves its mail to the name.
fn take_over(&self, g: &mut Inner, name: &str, key: &str) -> Result<()> {
@@ -289,7 +303,7 @@ impl Daemon {
/// A hook fired in an agent: keep its session alive, track busy/idle, hand back mail to inject.
pub(super) async fn hook(self: &Arc<Self>, h: HookCall) -> Result<HookReply> {
- let HookCall { agent, event, session_id, cwd, pid, mail, transcript, doing, name, dirs } = h;
+ let HookCall { agent, event, session_id, cwd, pid, mail, transcript, doing, name, dirs, keep } = h;
let (agent, event) = (agent.as_str(), event.as_str());
let key = format!("{agent}:{session_id}");
let now = util::now_ms();
@@ -344,6 +358,10 @@ impl Daemon {
};
self.register_quiet(None, reg, git)?;
}
+ // A name the person gave with `listen --as`: one of their own mailboxes from now on.
+ if keep && agent == "cli" {
+ self.mailbox(&key, now)?;
+ }
let mut g = self.inner.lock().unwrap();
let g = &mut *g;
@@ -493,6 +511,7 @@ fn remembered(l: &Live, now: i64) -> Remembered {
tier: l.reg.tier,
last_seen: now,
attached: l.attached,
+ mailbox: l.mailbox,
}
}
@@ -620,10 +639,15 @@ mod tests {
}
}
- /// Registers a session through an MCP server of its own, as Claude Code runs one per session.
+ /// Registers a session through an MCP server of its own, as Claude Code runs one per session; a `cli` one as
+ /// `listen --as` does, as one of the person's own mailboxes.
fn join(d: &Daemon, reg: SessionReg) -> Registered {
- let conn = conn_of(&reg.key);
- d.register_quiet(Some(conn), reg, GitInfo::default()).unwrap().0
+ let (conn, key, cli) = (conn_of(&reg.key), reg.key.clone(), reg.agent == "cli");
+ let r = d.register_quiet(Some(conn), reg, GitInfo::default()).unwrap().0;
+ if cli {
+ d.mailbox(&key, util::now_ms()).unwrap();
+ }
+ r
}
/// The connection of the MCP server `join` registers a session through.
@@ -715,6 +739,7 @@ mod tests {
doing: None,
name: None,
dirs: Vec::new(),
+ keep: false,
};
// Its MCP server registered it; then it ends.
assert_eq!(join(&d, claude("a")).name, "api-claude");
@@ -799,6 +824,48 @@ mod tests {
assert_eq!((r.name.as_str(), r.unread), ("review", 1));
}
+ #[tokio::test]
+ async fn the_reason_clis_one_off_ask_sessions_are_sessions_like_any_other() {
+ let mut d = super::super::test_daemon(Default::default());
+ settled(&mut d);
+ let d = Arc::new(d);
+ let cli = |id: &str, keep: bool| HookCall {
+ agent: "cli".into(),
+ event: "stop".into(),
+ session_id: id.into(),
+ cwd: Some("/work/api".into()),
+ pid: None,
+ mail: false,
+ transcript: None,
+ doing: None,
+ name: Some(id.into()),
+ dirs: Vec::new(),
+ keep,
+ };
+ // `reason network <who> "…"` waits for its answer at a session of its own; `listen --as review` is a mailbox.
+ d.hook(cli("ask-1a2b3c", false)).await.unwrap();
+ d.hook(cli("review", true)).await.unwrap();
+ for key in ["cli:ask-1a2b3c", "cli:review"] {
+ leave(&d, key, 2 * DAY);
+ }
+ mail(&d, "m1", "ask-1a2b3c");
+ mail(&d, "m2", "review");
+ // Neither is named to the person's other machines (each machine has its own).
+ assert!(d.presence_of(Vec::new()).kept.is_empty());
+ // A day on, the ask session is forgotten with its mail, as any session is; the mailbox stays, mail and all.
+ {
+ let mut g = d.inner.lock().unwrap();
+ d.prune(&mut g);
+ assert!(g.store.session_by_key("cli:ask-1a2b3c").unwrap().is_none());
+ assert_eq!(g.store.unread_count(&d.addr("ask-1a2b3c")).unwrap(), 0);
+ assert!(g.store.session_by_key("cli:review").unwrap().is_some_and(|r| r.mailbox));
+ assert_eq!(g.store.unread_count(&d.addr("review")).unwrap(), 1);
+ }
+ // The terminal is always one of the person's own mailboxes, whoever registers it.
+ d.hook(cli("terminal", false)).await.unwrap();
+ assert!(d.inner.lock().unwrap().store.session_by_key(TERMINAL).unwrap().is_some_and(|r| r.mailbox));
+ }
+
#[test]
fn a_session_known_only_by_its_process_leaves_its_name_and_mail_to_the_next_in_its_place() {
let d = super::super::test_daemon(Default::default());
@@ -828,6 +895,7 @@ mod tests {
tier: Tier::Push,
last_seen: util::now_ms() - 3_600_000,
attached: true,
+ mailbox: false,
};
{
let g = d.inner.lock().unwrap();
@@ -873,6 +941,7 @@ mod tests {
tier: Tier::Push,
last_seen: util::now_ms(),
attached: true,
+ mailbox: false,
};
g.store.upsert_session(&r, &d.person).unwrap();
assert!(g.store.session_by_name("api-claude").unwrap().is_none());
@@ -928,6 +997,7 @@ mod tests {
doing: None,
name: None,
dirs: Vec::new(),
+ keep: false,
};
// A headless run: hooks only, never an MCP server, a push channel or a listen.
assert_eq!(d.hook(call("p", "start")).await.unwrap().address, Some(d.addr("api-claude")));
@@ -959,6 +1029,7 @@ mod tests {
doing: None,
name: None,
dirs: Vec::new(),
+ keep: false,
}
}
@@ -1199,6 +1270,7 @@ mod tests {
doing: None,
name: Some("terminal".into()),
dirs: Vec::new(),
+ keep: false,
};
assert_eq!(d.hook(call).await.unwrap().address, Some(d.addr("terminal")));
}
@@ -1221,6 +1293,7 @@ mod tests {
tier: Tier::Push,
last_seen: util::now_ms(),
attached: true,
+ mailbox: false,
};
d.inner.lock().unwrap().store.upsert_session(&r, &d.person).unwrap();
assert_eq!(join(&d, claude("old")).name, "api-claude");
@@ -1268,6 +1341,7 @@ mod tests {
tier: Tier::Pull,
last_seen: now - 1_000 * (120 - i),
attached: true,
+ mailbox: false,
};
g.store.upsert_session(&r, &d.person).unwrap();
}
@@ -1371,6 +1445,7 @@ mod tests {
doing: None,
name: None,
dirs: dirs.iter().map(|d| d.to_string()).collect(),
+ keep: false,
};
// Working in /work/api, with /work/private open too.
let e = d.hook(call("c1", "prompt", &["/work/private"])).await.unwrap_err();
diff --git a/src/hook.rs b/src/hook.rs
index 8a5849d..3e3dfb1 100644
--- a/src/hook.rs
+++ b/src/hook.rs
@@ -96,6 +96,7 @@ async fn handle(
doing,
name: None,
dirs: dirs.into_iter().skip(1).collect(),
+ keep: false,
});
let reply: HookReply = link.call(req).await.ok()?;
if off {
diff --git a/src/main.rs b/src/main.rs
index b2c5db4..c722675 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -374,6 +374,7 @@ async fn cli_session(link: &std::sync::Arc<Link>, id: &str, event: &str) -> Resu
doing: None,
name: Some(id.into()),
dirs: Vec::new(),
+ keep: true,
});
link.call(req).await
}
diff --git a/src/proto.rs b/src/proto.rs
index 73521bd..9d66319 100644
--- a/src/proto.rs
+++ b/src/proto.rs
@@ -74,6 +74,11 @@ pub struct HookCall {
/// What the session is doing, from agents that say so themselves (the opencode plugin).
#[serde(default)]
pub doing: Option<String>,
+ /// One of the person's own mailboxes, kept for good: a name they gave with `reason network listen --as` (the
+ /// terminal always is one). Other `cli` sessions, such as the Reason CLI's one-off ask sessions, are sessions like
+ /// any other. Older clients leave it out.
+ #[serde(default)]
+ pub keep: bool,
/// The session's name, for sessions that pick one (`reason network listen --as`).
#[serde(default)]
pub name: Option<String>,
diff --git a/src/render.rs b/src/render.rs
index cca9871..d199f4a 100644
--- a/src/render.rs
+++ b/src/render.rs
@@ -243,6 +243,12 @@ pub fn from_terminal(from: &str) -> bool {
without_machine(from).ends_with("/terminal")
}
+/// How a message from `address`, from machine `machine`, shows on another machine: a person's terminal with that
+/// machine, as each machine has its own (the address a reply to it goes to, and that its sender's receipt names).
+pub fn shown_from(address: &str, machine: &str) -> String {
+ if from_terminal(address) { format!("{address}@{machine}") } else { address.to_string() }
+}
+
/// An address without the `@<machine>` it may name.
pub fn without_machine(address: &str) -> &str {
address.split_once('@').map_or(address, |(a, _)| a)
diff --git a/src/store.rs b/src/store.rs
index ee0f4ad..8e5a7bb 100644
--- a/src/store.rs
+++ b/src/store.rs
@@ -1,5 +1,5 @@
//! SQLite: messages, and the sessions this machine has seen: live ones, ones gone for less than a day, and the
-//! person's own mailboxes (`cli`, such as `terminal`). Files that came with messages are saved in the inbox folder, one
+//! person's own mailboxes (`terminal`, `listen --as` names). Files that came with messages are saved in the inbox folder, one
//! folder per message, and go with their message.
use crate::{
@@ -60,6 +60,8 @@ pub struct Remembered {
pub last_seen: i64,
/// Whether it could ever be reached beyond its own hooks (see `Live::attached`).
pub attached: bool,
+ /// One of the person's own mailboxes (`terminal`, a `listen --as` name): kept for good, never forgotten.
+ pub mailbox: bool,
}
impl Remembered {
@@ -109,7 +111,8 @@ CREATE TABLE IF NOT EXISTS sessions (
doing TEXT,
tier TEXT NOT NULL,
last_seen INTEGER NOT NULL,
- attached INTEGER NOT NULL DEFAULT 1
+ attached INTEGER NOT NULL DEFAULT 1,
+ mailbox INTEGER NOT NULL DEFAULT 0
);
CREATE INDEX IF NOT EXISTS sessions_key ON sessions (key);
CREATE TABLE IF NOT EXISTS counts (
@@ -121,7 +124,7 @@ CREATE TABLE IF NOT EXISTS counts (
const MESSAGE_COLS: &str =
"id, sender, sender_agent, sender_repo, recipient, via, reply_to, body, wake, sent_at, approval, files";
-const SESSION_COLS: &str = "name, key, agent, cwd, repo, branch, doing, tier, last_seen, attached";
+const SESSION_COLS: &str = "name, key, agent, cwd, repo, branch, doing, tier, last_seen, attached, mailbox";
impl Store {
/// The database at `path`, and the folder `inbox` that messages' files are saved in.
@@ -155,6 +158,19 @@ impl Store {
if !db.prepare("SELECT 1 FROM pragma_table_info('sessions') WHERE name = 'attached'")?.exists([])? {
db.execute("ALTER TABLE sessions ADD COLUMN attached INTEGER NOT NULL DEFAULT 1", [])?;
}
+ // Added when the person's own mailboxes were told from other `cli` sessions. Before, every `cli` session was
+ // kept for good; of those remembered, the Reason CLI's one-off ask sessions (`ask-` and six hex digits, as it
+ // names them) are sessions like any other from now on.
+ if !db.prepare("SELECT 1 FROM pragma_table_info('sessions') WHERE name = 'mailbox'")?.exists([])? {
+ let tx = db.unchecked_transaction()?;
+ tx.execute("ALTER TABLE sessions ADD COLUMN mailbox INTEGER NOT NULL DEFAULT 0", [])?;
+ tx.execute(
+ "UPDATE sessions SET mailbox = 1 WHERE agent = 'cli'
+ AND NOT (length(name) = 10 AND name GLOB 'ask-[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]')",
+ [],
+ )?;
+ tx.commit()?;
+ }
Ok(Store { db, inbox })
}
@@ -467,12 +483,25 @@ impl Store {
// Once reachable, a session stays so for as long as it is remembered.
self.db.execute(
&format!(
- "INSERT INTO sessions ({SESSION_COLS}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)
+ "INSERT INTO sessions ({SESSION_COLS}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11)
ON CONFLICT (name) DO UPDATE SET key = ?2, agent = ?3, cwd = ?4, repo = ?5, branch = ?6,
doing = ?7, tier = ?8, last_seen = ?9,
- attached = CASE WHEN key = ?2 THEN max(attached, ?10) ELSE ?10 END"
+ attached = CASE WHEN key = ?2 THEN max(attached, ?10) ELSE ?10 END,
+ mailbox = CASE WHEN key = ?2 THEN max(mailbox, ?11) ELSE ?11 END"
),
- params![s.name, s.key, s.agent, s.cwd, s.repo, s.branch, s.doing, s.tier.as_str(), s.last_seen, s.attached],
+ params![
+ s.name,
+ s.key,
+ s.agent,
+ s.cwd,
+ s.repo,
+ s.branch,
+ s.doing,
+ s.tier.as_str(),
+ s.last_seen,
+ s.attached,
+ s.mailbox
+ ],
)?;
Ok(())
}
@@ -482,12 +511,12 @@ impl Store {
Ok(())
}
- /// Forgets the sessions not seen since `before`, other than `live` ones and the person's own mailboxes (`cli`), and
+ /// Forgets the sessions not seen since `before`, other than `live` ones and the person's own mailboxes (`mailbox`), and
/// deletes the mail they never read, so a session that takes the name later doesn't get it (see `forget_session`).
pub fn forget_sessions(&self, before: i64, live: &HashSet<&str>, person: &str) -> Result<()> {
let mut st = self
.db
- .prepare_cached(&format!("SELECT {SESSION_COLS} FROM sessions WHERE last_seen < ?1 AND agent != 'cli'"))?;
+ .prepare_cached(&format!("SELECT {SESSION_COLS} FROM sessions WHERE last_seen < ?1 AND mailbox = 0"))?;
let gone: Vec<Remembered> = st.query_map([before], remembered)?.collect::<rusqlite::Result<_>>()?;
for r in gone.iter().filter(|r| !live.contains(r.name.as_str())) {
self.forget_session(r, person)?;
@@ -578,6 +607,7 @@ fn remembered(r: &Row) -> rusqlite::Result<Remembered> {
tier: Tier::parse(&r.get::<_, String>(7)?),
last_seen: r.get(8)?,
attached: r.get(9)?,
+ mailbox: r.get(10)?,
})
}
@@ -712,6 +742,7 @@ mod tests {
let store = Store::open(Path::new(":memory:"), temp_inbox()).unwrap();
let day = 86_400_000;
let session = |name: &str, agent: &str, last_seen: i64| Remembered {
+ mailbox: agent == "cli",
name: name.into(),
key: name.into(),
agent: agent.into(),
@@ -776,6 +807,7 @@ mod tests {
tier: Tier::Push,
last_seen,
attached: true,
+ mailbox: false,
};
// As older engines could: the same session under two names, mail waiting under each.
for (name, seen) in [("api-claude", 1), ("api-claude-2", 2)] {
@@ -784,7 +816,7 @@ mod tests {
.db
.execute(
&format!(
- "INSERT INTO sessions ({SESSION_COLS}) VALUES (?1, ?2, ?3, ?4, NULL, NULL, NULL, ?5, ?6, 1)"
+ "INSERT INTO sessions ({SESSION_COLS}) VALUES (?1, ?2, ?3, ?4, NULL, NULL, NULL, ?5, ?6, 1, 0)"
),
params![s.name, s.key, s.agent, s.cwd, s.tier.as_str(), s.last_seen],
)
@@ -823,6 +855,40 @@ mod tests {
}
}
+ #[test]
+ fn a_store_from_before_keeps_the_persons_mailboxes_but_not_the_clis_ask_sessions() {
+ let dir = std::env::temp_dir().join(format!("reason-network-mailbox-{}", ulid::Ulid::generate()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let db = dir.join("network.db");
+ {
+ // The sessions table as 0.12.7 left it.
+ let old = Connection::open(&db).unwrap();
+ old.execute_batch(
+ "CREATE TABLE sessions (name TEXT PRIMARY KEY, key TEXT NOT NULL, agent TEXT NOT NULL, cwd TEXT NOT NULL,
+ repo TEXT, branch TEXT, doing TEXT, tier TEXT NOT NULL, last_seen INTEGER NOT NULL,
+ attached INTEGER NOT NULL DEFAULT 1);
+ INSERT INTO sessions (name, key, agent, cwd, tier, last_seen) VALUES
+ ('terminal', 'cli:terminal', 'cli', '~', 'pull', 0),
+ ('review', 'cli:review', 'cli', '~', 'pull', 0),
+ ('ask-1a2b3c', 'cli:ask-1a2b3c', 'cli', '~', 'pull', 0),
+ ('ask-lunch', 'cli:ask-lunch', 'cli', '~', 'pull', 0),
+ ('api-claude', 'claude-code:a', 'claude-code', '~', 'push', 0);",
+ )
+ .unwrap();
+ }
+ let mailboxes = |store: &Store| -> Vec<String> {
+ store.sessions().unwrap().into_iter().filter(|s| s.mailbox).map(|s| s.name).collect()
+ };
+ let store = Store::open(&db, temp_inbox()).unwrap();
+ assert_eq!(mailboxes(&store), ["ask-lunch", "review", "terminal"]);
+ drop(store);
+ // Opened again, nothing changes.
+ let store = Store::open(&db, temp_inbox()).unwrap();
+ assert_eq!(mailboxes(&store), ["ask-lunch", "review", "terminal"]);
+ drop(store);
+ std::fs::remove_dir_all(&dir).unwrap();
+ }
+
fn temp_inbox() -> PathBuf {
std::env::temp_dir().join(format!("reason-network-inbox-{}", ulid::Ulid::generate()))
}
@@ -990,6 +1056,7 @@ mod tests {
tier: Tier::Push,
last_seen: 0,
attached: true,
+ mailbox: false,
};
store.upsert_session(&session("gone"), "lars").unwrap();
store.upsert_session(&session("api"), "lars").unwrap();
diff --git a/tests/e2e/two_machines.py b/tests/e2e/two_machines.py
index 5ff5bed..91819f4 100644
--- a/tests/e2e/two_machines.py
+++ b/tests/e2e/two_machines.py
@@ -396,10 +396,21 @@ out = codex.tool("send_message", {"to": "alex/*", "message": "x", "notify": True
check("notify doesn't go to groups", "not a group" in out, out)
# No waiting for presence: the terminal that just messaged alice can be answered at once.
out = codex.tool("send_message", {"to": "alex/terminal", "message": "codex here: replying to your terminal"}, meta)
-check("an agent can reply at once to a terminal that just messaged it", "→ alex/terminal: queued" in out or "→ alex/terminal: delivered" in out, out)
+check("an agent can reply at once to a terminal that just messaged it", "→ alex/terminal@laptop: queued" in out or "→ alex/terminal@laptop: delivered" in out, out)
time.sleep(1)
out = cli("alex", "listen", "--as", "terminal", "--wait", "5")
check("…and `reason network listen --as terminal` shows the reply", "replying to your terminal" in out and 'from="alice/work-codex"' in out, out)
+# An ask of a teammate's terminal, answered there with no reply_to: the ask's receipt names the terminal as the answer
+# comes from, which is how the Reason CLI tells the answer.
+out = codex.tool("send_message", {"to": "alex/terminal", "message": "codex here: ok to ship? (e2e test, ignore)"}, meta)
+asked = re.search(r"→ (\S+): ", out)
+check("a teammate's terminal is named in the receipt with its machine", asked is not None and asked.group(1) == "alex/terminal@laptop", out)
+cli("alex", "listen", "--as", "terminal", "--wait", "5")
+cli("alex", "send", "alice/work-codex", "--from", "alex/terminal", "yes, ship it")
+time.sleep(1)
+out = codex.tool("check_inbox", {}, meta)
+answer = re.search(r'from="([^"]+)"[^>]*>\s*yes, ship it', out)
+check("…and the answer comes from exactly that address", answer is not None and asked is not None and answer.group(1) == asked.group(1), out)
cli("alice", "listen", "--as", "fresh", "--wait", "0")
cli("alice", "send", "alex/terminal", "--from", "alice/fresh", "first words from a new session")
out = cli("alex", "send", "alice/fresh", "answered at once")