Reason Network: your team's coding agents, talking to each other. The engine behind `reason network`.
Rust agent-to-agentai-agentsclaude-codecodexcoding-agentscursorgrokirohmcpmcp-servermulti-agentpeer-to-peerreason
Session names stay with their conversation (#105)
Lars Taliand50e93c75caf
diff --git a/DESIGN.md b/DESIGN.mdindex 7c9b2ec..4a27e88 100644--- a/DESIGN.md+++ b/DESIGN.md@@ -54,8 +54,46 @@ The groups (`alice/*`, `repo:`, `*`, with or without `@machine`) are for a persoone session.Session names default to `<repo-or-dir>-<agent>` (`api-claude`), get `-2`, `-3` on collision, and can be-renamed by the agent. A new session in the same place with the same agent **inherits a stale name and its-unread mail**, so "tell the api agent X" survives restarts (idea from agentbus).+renamed by the agent.++**A name stays with its conversation.** Each machine binds a session's name to its key, the id its agent gives the+conversation (`<agent>:<id>`, see Session registration below): one name per key, in the `sessions` table. This holds for+a session the agent identifies and that could be reached: an MCP server connected for it or answered a call for it, a+push channel delivers into it (Claude Code's inbox, `codex queue`, the opencode and pi plugins, Reason), its hooks+handed it mail (Gemini, Copilot, Grok, Cursor, Codex without its binary), it sent or was sent mail, or it is one of the+person's own mailboxes. Once reachable, it stays so for as long as it is remembered. A run only its hooks ever saw,+that no mail reached (a one-shot or headless run without Reason Network's tools), couldn't be messaged, so its name+isn't kept, and it doesn't push later sessions to `-2`, `-3`.++- The same conversation coming back (the agent restarted or resumed it, or the daemon restarted) gets its name back,+ with the mail that waited for it, whichever sessions register first.+- While it is offline, its name is **kept**: a new session, on this machine or another of the person's, gets the next+ free name, also when it asks for that one (`listen --as`, a Claude Code session's own name), and a rename into it is+ refused (`'api-claude' belongs to a session that is offline (last seen 3h ago); pick another name`).+- The name lapses when its session would be forgotten (below: a day after it was last seen, never in the hours after the+ daemon starts). Then it is free again, without that session's unread mail, which is dropped as the sender was told:+ mail is never another conversation's. A conversation back after that is a new session.+- A conversation whose name a live session has when it comes back (another of the person's machines gave it out: one+ of an older engine, or one that hadn't heard yet that this machine keeps it) gets a new name, and its waiting mail+ moves to it.+- Another machine's kept names count while it is online or was in the last day: one off longer can't still be keeping+ 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).+- 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+ 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+ `terminals` feature, or it hasn't been heard from), the second terminal on at once is `terminal-2`, as before. A+ terminal named `terminal` while none was takes the next free name the next time it is used, once one is.+- Names are kept per machine: the same conversation turning up on another machine is a new session there, and mail+ queued for it stays where it was.+- A session whose agent gives it no id (`proc:<pid>`, one per MCP process: DeepSeek Harness, ZCode, and MCP clients+ such as Claude Desktop, Zed or Amp) can't come back, so its name isn't kept: a new session in the same place with the+ same agent takes the stale name and its unread mail, so "tell the api agent X" survives restarts (idea from+ agentbus).## Architecture@@ -164,7 +202,11 @@ machine asked is that old, nothing tells the joiner it's the same account, and t**Presence and directory.** Daemons keep a connection to every online member (full mesh; fine to ~50machines). On connect they exchange roster heads (anti-entropy) and full presence. On any local change adaemon pushes `Presence{machine, seq, sessions[], human_status}` to all peers. A dropped connection marks-that machine offline (sessions shown with last-seen).+that machine offline (sessions shown with last-seen). Presence also names the machine's offline sessions (`known`, so+mail for them is queued there) and, of those, the ones whose names are kept (`kept`, which the person's other machines+give to no new session; older engines leave it out and ignore it). Each list carries at most 100 names, the most+recent, which is what receivers take; a machine keeping more says so in its log, and its older kept names are then+protected on that machine only.**Messages.** `Envelope{id: ulid, from, to, reply_to, thread, body, sent_at}` sent directly to each targetmachine on ALPN `tincan/1`, length-prefixed JSON frames. The receiver persists, then acks with@@ -172,7 +214,12 @@ machine on ALPN `tincan/1`, length-prefixed JSON frames. The receiver persists,outbox and retries when the target machine comes back. Mail for an offline session waits in the targetmachine's mailbox under the session name, for a day: a session gone longer is forgotten, with the mail it neverread (not the person's own `listen` mailboxes, such as `terminal`, nor mail held for them; and nothing in the-hours after the daemon starts, while live sessions register again).+hours after the daemon starts, while live sessions register again). Until then the mail waits for that session, and the+sender is told so ("…; it reaches that session when it's back"); for a session whose agent gives it no id, a new session+that takes the name gets it, and the note says that instead. Mail held for the person's approval follows the same rule:+held for a session whose name is kept, it goes when that session is forgotten, never to the next one, and its sender is+told so up front ("held until alex approves it; dropped if that session is gone for a day first"). Live sessions are+marked seen every 10 minutes, so a daemon that stops without seeing them go keeps their names from then.**Files.** A message can carry small text files (`files: [{name, content}]`, at most 10, 256 KB each, 512 KB in all;UTF-8 with no control characters but tab and line ends), inside the same envelope, so they are as authenticated as its@@ -204,10 +251,31 @@ session connection also receives pushed `deliver` events for its sessions.**Session registration**, by priority:1. Per-call `_meta`: Codex `sessionId` (the root thread, same id its hooks see), opencode V2 `ai.opencode/sessionID`.-2. Env: `CLAUDE_CODE_SESSION_ID` (Claude), `COPILOT_AGENT_SESSION_ID` (Copilot), `GROK_SESSION_ID` (Grok).+2. Env: `REASON_NETWORK_SESSION` (set by our pi extension), else the agent's own: `CLAUDE_CODE_SESSION_ID` (Claude),+ `CODEX_THREAD_ID` (Codex), `OPENCODE_SESSION_ID` (opencode), `GEMINI_SESSION_ID` (Gemini), `COPILOT_AGENT_SESSION_ID`+ (Copilot), `GROK_SESSION_ID` (Grok).3. Hook stdin `session_id` (`SessionStart`), correlated to the MCP process by agent PID ancestry.4. Fallback: one session per MCP process.+The key is `<agent>:<id>`, and it is what a name is kept for (above). Where each agent's id comes from:++| Agent | Id | From |+|---|---|---|+| Claude Code | session id | `CLAUDE_CODE_SESSION_ID`, hooks' `session_id`, `~/.claude/sessions/<pid>.json` |+| Codex | thread id | `_meta.sessionId` / `threadId`, `CODEX_THREAD_ID`, hooks' `session_id` |+| opencode | session id | `_meta["ai.opencode/sessionID"]`, `OPENCODE_SESSION_ID`, the plugin's `--session` |+| pi | session id | the extension's `REASON_NETWORK_SESSION` and `--session` |+| Cursor | conversation id | hooks' `conversation_id` (its shared MCP server takes the session its hooks registered) |+| Gemini CLI | session id | `GEMINI_SESSION_ID`, hooks' `session_id` |+| Copilot CLI | session id | `COPILOT_AGENT_SESSION_ID`, hooks' `sessionId` |+| Grok CLI | session id | `GROK_SESSION_ID`, hooks' `session_id` |+| Reason | session id | `reason session list` |+| `listen --as <name>`, `terminal` | the name | `cli:<name>` |+| DeepSeek Harness, ZCode, other MCP clients | none | `proc:<pid>` (`REASON_NETWORK_SESSION`, when set, gives one) |++A conversation keeps its name across a resume as long as its agent keeps the id (Claude Code does unless told to fork+the session; `/clear` starts a new one).+Agent kind comes from MCP `clientInfo.name` plus env (`CLAUDECODE`, `CODEX_*`, `GEMINI_CLI`,`CURSOR_AGENT`, `OPENCODE`, `COPILOT_CLI`, `GROK_SESSION_ID`).diff --git a/README.md b/README.mdindex eaa9aed..c210b14 100644--- a/README.md+++ b/README.md@@ -89,6 +89,8 @@ That's Reason's, with computers finding each other through the address lookup ofyour team runs its own relay (`reason-network relay <url>`): then your computers contact nothing else, n0 included.Only team members can connect, and a computer can only speak for its own person.Messages to someone offline wait and go out when they're back.+An agent session's name stays with its conversation, for a session the agent identifies: resumed after a restart, it+gets the same name back with the messages that waited for it, and for a day no new session takes the name.Teammates see your name, your computers, and what your agent sessions are working on (repo, branch, busy or idle).Signed in with Reason, your name shows as verified: Reason signs that the computer is yours, every teammate's computerdiff --git a/src/daemon/ask.rs b/src/daemon/ask.rsindex 14fab89..4cdcd02 100644--- a/src/daemon/ask.rs+++ b/src/daemon/ask.rs@@ -5,6 +5,7 @@use super::{Daemon, MAX_WAIT, log, mail::unregistered};use crate::{proto::{Approval, HookCall, Message},+ render,team::Signed,util,};@@ -185,16 +186,7 @@ impl Daemon {}None => (text.to_string(), question.to_string()),};- let approval = Approval {- about: request.id.clone(),- asker: request.from.clone(),- approver: self.person.clone(),- approved,- question,- request: seen,- note: clip(note, 500),- at: util::now_ms(),- };+ let approval = self.approval(request, approved, question, seen, note);let signed = Box::new(Signed::new(approval, &self.key, team.name(), "approval"));let live = self.inner.lock().unwrap().live.contains_key(key);let from = if live { key.to_string() } else { self.terminal().await };@@ -210,6 +202,21 @@ impl Daemon {}}+ /// The person's answer to `request`, as signed for its sender.+ fn approval(&self, request: &Message, approved: bool, question: String, seen: String, note: &str) -> Approval {+ Approval {+ about: request.id.clone(),+ // Its address as its own machine knows it: one from another machine's terminal names that machine here.+ asker: render::without_machine(&request.from).to_string(),+ approver: self.person.clone(),+ approved,+ question,+ request: seen,+ note: clip(note, 500),+ at: util::now_ms(),+ }+ }+/// This person's own session (`<person>/terminal`), registered the way the CLI registers it.async fn terminal(self: &Arc<Self>) -> String {let call = HookCall {@@ -521,6 +528,34 @@ if ($script:choice) { "$($script:choice)`n$(& $chars $req $reqShown)`n$(& $charsmod tests {use super::*;+ #[test]+ fn an_answer_to_another_machines_terminal_verifies_there() {+ let cfg = crate::config::Config { person: Some("alex".into()), ..Default::default() };+ let d = super::super::test_daemon(cfg);+ let team = crate::team::TeamState::found("acme", &d.person, &d.machine, &d.key);+ // Bob typed it in his terminal on his laptop: here it is from `bob/terminal@laptop`.+ let request = Message {+ id: Ulid::generate().to_string(),+ from: "bob/terminal@laptop".into(),+ from_agent: Some("cli".into()),+ from_repo: None,+ to: "alex/api-claude".into(),+ via: None,+ reply_to: None,+ body: "may I deploy?".into(),+ wake: true,+ notify: false,+ sent_at: 0,+ approval: None,+ files: Vec::new(),+ };+ let a = d.approval(&request, true, "deploy?".into(), "may I deploy?".into(), "");+ assert_eq!(a.asker, "bob/terminal");+ // Bob's machine checks it against its own address for the terminal.+ let signed = Signed::new(a, &d.key, team.name(), "approval");+ assert!(super::super::mail::approval_holds(&signed, team.name(), &d.key.public(), "alex", "bob/terminal"));+ }+#[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()));diff --git a/src/daemon/directory.rs b/src/daemon/directory.rsindex ec936ad..bf45414 100644--- a/src/daemon/directory.rs+++ b/src/daemon/directory.rs@@ -19,6 +19,9 @@ use std::{sync::Arc,};+/// How many offline names (`known`, and `kept`) presence carries: what teammates' machines take.+const PRESENCE_NAMES: usize = 100;+/// A resolved recipient.pub(super) enum Target {/// A session on this machine; `key` is set when it is running.@@ -209,7 +212,7 @@ impl Daemon {self.presence_of(sessions)}- fn presence_of(&self, mut sessions: Vec<SessionInfo>) -> Presence {+ pub(super) fn presence_of(&self, mut sessions: Vec<SessionInfo>) -> Presence {if !self.cfg.share_paths {for s in &mut sessions {s.cwd =@@ -219,10 +222,22 @@ impl Daemon {let g = self.inner.lock().unwrap();let mut known = self.remembered(&g);known.sort_by_key(|r| -r.last_seen);+ // Not the person's own mailboxes: each machine has its own (`terminal`).+ let now = util::now_ms();+ let kept: Vec<String> =+ known.iter().filter(|r| r.agent != "cli" && self.holds(r, now)).map(|r| r.name.clone()).collect();+ // Teammates' machines take 100 of each, so only the most recent go; the rest are named only here.+ if kept.len() > PRESENCE_NAMES && !self.capped.swap(true, std::sync::atomic::Ordering::Relaxed) {+ super::log(&format!(+ "{} names are kept for offline sessions here: other machines hear of the {PRESENCE_NAMES} most recent",+ kept.len()+ ));+ }Presence {sessions,- known: known.into_iter().take(100).map(|r| r.name).collect(),- features: vec![crate::files::FEATURE.into()],+ known: known.into_iter().take(PRESENCE_NAMES).map(|r| r.name).collect(),+ kept: kept.into_iter().take(PRESENCE_NAMES).collect(),+ features: vec![crate::files::FEATURE.into(), super::sessions::TERMINALS.into()],}}@@ -432,7 +447,16 @@ impl Daemon {/// One session among same-named candidates: the live one, else an offline one to queue for.fn pick(&self, found: Vec<&Cand>, spec: &str, target: &dyn Fn(&Cand) -> Target) -> Result<Vec<Target>> {let live: Vec<&&Cand> = found.iter().filter(|c| c.live).collect();- let pool: Vec<&&Cand> = if live.is_empty() { found.iter().collect() } else { live };+ let mut pool: Vec<&&Cand> = if live.is_empty() { found.iter().collect() } else { live };+ // Each machine has its own `<you>/terminal`: unnamed on one that has its own, it is that one (another is+ // `…@<machine>`). Anywhere else, two are ambiguous, as two sessions of any one name are.+ let local = |c: &&&Cand| matches!(c.place, Place::Local(_));+ if pool.len() > 1+ && pool.iter().all(|c| c.name == "terminal" && c.person == pool[0].person)+ && pool.iter().any(local)+ {+ pool.retain(local);+ }match pool.as_slice() {[] => bail!("no session called '{spec}'. Run list_team (or `{CLI} who`) to see who is around (sessions without Reason Network can't \@@ -455,6 +479,78 @@ fn claude_match(c: &ClaudeSession, reg: &SessionReg) -> bool {mod tests {use super::*;+ #[test]+ fn each_machine_answers_for_its_own_terminal() {+ let cfg = crate::config::Config { person: Some("alex".into()), ..Default::default() };+ let d = Arc::new(super::super::test_daemon(cfg));+ let desk = iroh::SecretKey::generate();+ let mut team = crate::team::TeamState::found("acme", &d.person, &d.machine, &d.key);+ team.put_member(&d.key, desk.public(), "alex", "desk", true);+ d.inner.lock().unwrap().team = Some(team);+ let reg = SessionReg {+ key: "cli:terminal".into(),+ agent: "cli".into(),+ cwd: "/".into(),+ agent_session_id: None,+ pid: None,+ tier: Tier::Pull,+ name: Some("terminal".into()),+ };+ assert_eq!(d.register(Some(1), reg, GitInfo::default()).unwrap().name, "terminal");+ let mut theirs = d.row("terminal", "cli", "/", None);+ theirs.tier = Tier::Pull;+ let remotes = HashMap::from([(+ desk.public(),+ Remote {+ presence: Presence { sessions: vec![theirs], ..Default::default() },+ last_seen: util::now_ms(),+ online: true,+ },+ )]);+ let g = d.inner.lock().unwrap();+ let to = |spec: &str| {+ d.resolve(&g, &remotes, spec, None).unwrap().into_iter().map(|t| match t {+ Target::Session { .. } => "here".to_string(),+ Target::Remote { machine_name, .. } => machine_name,+ })+ };+ assert_eq!(to("alex/terminal").collect::<Vec<_>>(), ["here"]);+ assert_eq!(to("alex/terminal@desk").collect::<Vec<_>>(), ["desk"]);+ }++ #[test]+ fn on_a_teammates_machine_two_terminals_of_one_person_are_ambiguous_and_one_is_found() {+ let cfg = crate::config::Config { person: Some("bob".into()), ..Default::default() };+ let d = super::super::test_daemon(cfg);+ let (laptop, desk) = (iroh::SecretKey::generate(), iroh::SecretKey::generate());+ let mut team = crate::team::TeamState::found("acme", &d.person, &d.machine, &d.key);+ team.put_member(&d.key, laptop.public(), "alex", "laptop", true);+ team.put_member(&d.key, desk.public(), "alex", "desk", true);+ d.inner.lock().unwrap().team = Some(team);+ let mut terminal = d.row("terminal", "cli", "/", None);+ terminal.tier = Tier::Pull;+ let remote = |sessions: Vec<SessionInfo>| Remote {+ presence: Presence { sessions, ..Default::default() },+ last_seen: util::now_ms(),+ online: true,+ };+ let g = d.inner.lock().unwrap();+ // Only one of alex's machines has a terminal on: it is the one, as before.+ let remotes =+ HashMap::from([(laptop.public(), remote(vec![terminal.clone()])), (desk.public(), remote(vec![]))]);+ let found = d.resolve(&g, &remotes, "alex/terminal", None).unwrap();+ assert!(matches!(&found[..], [Target::Remote { machine_name, .. }] if machine_name == "laptop"));+ // Both: which one, by machine (a reply to a message from one names it).+ let remotes =+ HashMap::from([(laptop.public(), remote(vec![terminal.clone()])), (desk.public(), remote(vec![terminal]))]);+ let e = d.resolve(&g, &remotes, "alex/terminal", None).err().unwrap().to_string();+ assert!(+ e.contains("is ambiguous") && e.contains("alex/terminal@laptop") && e.contains("alex/terminal@desk"),+ "{e}"+ );+ assert_eq!(d.resolve(&g, &remotes, "alex/terminal@desk", None).unwrap().len(), 1);+ }+#[test]fn presence_leaves_out_sessions_in_a_folder_that_is_off() {let cfg = crate::config::Config {@@ -475,8 +571,9 @@ mod tests {doing: None,tier: Tier::Push,last_seen: util::now_ms(),+ attached: true,};- d.inner.lock().unwrap().store.upsert_session(&r).unwrap();+ d.inner.lock().unwrap().store.upsert_session(&r, &d.person).unwrap();}assert_eq!(d.presence_of(Vec::new()).known, ["api-claude"]);// Claude Code's own list: neither registered nor shown without Reason Network.diff --git a/src/daemon/mail.rs b/src/daemon/mail.rsindex 8d63d9d..64c2e97 100644--- a/src/daemon/mail.rs+++ b/src/daemon/mail.rs@@ -5,7 +5,16 @@//! don't show them a second time.use super::{Daemon, Inner, directory::Target, log};-use crate::{agent, claude, config::Policy, files, proto::*, render, store::Counted, team::Signed, util};+use crate::{+ agent, claude,+ config::Policy,+ files,+ proto::*,+ render,+ store::{Counted, Remembered},+ team::Signed,+ util,+};use anyhow::{Result, anyhow, bail};use iroh::EndpointId;use std::{@@ -75,20 +84,23 @@ const LOOP_NOTE: &str = "refused: these two agents have exchanged a lot of messalooks 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 {+/// it was last seen, unless it is one of the person's own mailboxes (`cli`), 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 {const NAME: &str = "a new session that takes this name gets the mail";+ const BACK: &str = "it reaches that session when it's back";let Some(r) = r else { return format!("queued: the session is offline; {NAME}") };+ 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" {- format!("queued: last seen {seen} ago; {NAME}")+ format!("queued: last seen {seen} ago; {who}")} else if forgotten <= now {- format!("queued: last seen {seen} ago; unread mail may be dropped any time; {NAME}")+ format!("queued: last seen {seen} ago; unread mail may be dropped any time; {who}")} 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}")+ format!("queued: last seen {seen} ago; unread mail is dropped after about {left} if it stays offline; {who}")}}@@ -141,6 +153,8 @@ impl Daemon {let (from_addr, from_agent, from_repo) =(self.addr(&sender.name), Some(sender.reg.agent.clone()), sender.git.repo.clone());let exclude = sender.reg.key.clone();+ // It talks to teammates: its name stays its own.+ self.reached(&mut g, &exclude);// A person at a terminal may message a group; an agent picks the one session it needs.if is_group(to) && !from_addr.ends_with("/terminal") {bail!("agents message one session, not a group: pick it with list_team, or ask your user");@@ -293,10 +307,13 @@ impl Daemon {msgs: Vec<Message>,wake: bool,) -> (String, String) {- let Some(l) = g.live.get(key) else {+ if !g.live.contains_key(key) {let note = offline_note(g.store.session_by_key(key).ok().flatten().as_ref(), util::now_ms());return ("queued".into(), note);- };+ }+ // Mail reached it: it is a session teammates talk to, whose name stays its own.+ self.reached(g, key);+ let l = &g.live[key];if !wake {return ("queued".into(), "queued as FYI: it reads it at its next natural pause".into());}@@ -475,9 +492,9 @@ impl Daemon {/// A message from a teammate's machine. Returns the state and a note for the sender. A `retry` state/// means "not now": the sender keeps it in its outbox.pub fn receive(self: &Arc<Self>, peer: EndpointId, msg: Message) -> Result<(String, String)> {- let sender = self+ let (sender, machine) = self.team_state()- .and_then(|t| t.member(&peer).map(|m| m.person.clone()))+ .and_then(|t| t.member(&peer).map(|m| (m.person.clone(), m.machine.clone()))).ok_or_else(|| anyhow!("not a team member"))?;let mut msg = clean(msg)?;// Messages go between agent sessions (or, with notify, to a person's screen); an older Reason Network may still send@@ -548,13 +565,23 @@ impl Daemon {let note = format!("refused: agents message one of {}'s sessions, not a group", self.person);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);+ }// 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.+ let kept = held && g.store.session_by_name(name)?.is_some_and(|r| r.kept());// 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 kept => (+ "held".into(),+ format!("held until {} approves it; dropped if that session is gone for a day first", self.person),+ ),_ 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(), offline_note(remembered.as_ref(), util::now_ms())),@@ -564,7 +591,7 @@ impl Daemon {self.arrived.notify_waiters();// The sender's session can be answered right away, before its machine's next presence names it.if let (Some(net), Some((_, from))) = (self.net(), msg.from.split_once('/')) {- net.note_session(&peer, from);+ net.note_session(&peer, from.split_once('@').map_or(from, |(n, _)| n));}Ok(res)}@@ -680,7 +707,7 @@ fn tidy(s: &str, extra: &str, max: usize) -> Option<String> {/// Whether an approval that came from `peer` (a machine of `sender`'s) to the session `to` stands: signed by that machine/// for this team, as its own person's answer, for that session, and of a sane size (in characters, as the sender cuts/// it). Which request it answers is the approver's machine's word: the frame shows `about`, for the agent to check.-fn approval_holds(a: &Signed<Approval>, team: &str, peer: &EndpointId, sender: &str, to: &str) -> bool {+pub(super) fn approval_holds(a: &Signed<Approval>, team: &str, peer: &EndpointId, sender: &str, to: &str) -> bool {let b = &a.body;let size: usize = [&b.about, &b.asker, &b.question, &b.request, &b.note].iter().map(|s| s.chars().count()).sum();size <= 2000 && a.by == *peer && b.approver == sender && b.asker == to && a.verify(team, "approval")@@ -788,9 +815,9 @@ mod tests {#[test]fn queued_mail_says_when_it_may_be_dropped_and_who_gets_it() {- let seen = |agent: &str| crate::store::Remembered {+ let seen = |key: &str, agent: &str| Remembered {name: "api-codex".into(),- key: "codex:1".into(),+ key: key.into(),agent: agent.into(),cwd: "/work/api".into(),repo: None,@@ -798,18 +825,26 @@ mod tests {doing: None,tier: Tier::Pull,last_seen: 0,+ attached: true,};- let name = "a new session that takes this name gets the mail";+ // 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";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}")+ offline_note(Some(&seen("codex:1", "codex")), 3 * HOUR),+ format!("queued: last seen 3h ago; unread mail is dropped after about 21h if it stays offline; {back}"));assert_eq!(- offline_note(Some(&seen("codex")), 24 * HOUR),- format!("queued: last seen 1d ago; unread mail may be dropped any time; {name}")+ offline_note(Some(&seen("codex:1", "codex")), 24 * HOUR),+ format!("queued: last seen 1d ago; unread mail may be dropped any time; {back}"));// 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(Some(&seen("cli:t", "cli")), 30 * HOUR), format!("queued: last seen 1d ago; {back}"));+ // A session known only by its process can't come back: a new one in its place gets the mail.+ let name = "a new session that takes this name gets the mail";+ assert_eq!(+ offline_note(Some(&seen("proc:7", "zed")), 3 * HOUR),+ format!("queued: last seen 3h ago; unread mail is dropped after about 21h if it stays offline; {name}")+ );assert_eq!(offline_note(None, 0), format!("queued: the session is offline; {name}"));}@@ -853,7 +888,41 @@ mod tests {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 the mail"), "{note}");+ assert!(note.ends_with("; it reaches that session when it's back"), "{note}");+ }++ #[test]+ fn a_message_from_a_teammates_terminal_is_answered_on_that_machine() {+ 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);+ let to = d.register(Some(1), codex("codex:1"), crate::git::GitInfo::default()).unwrap().address;+ let msg = Message {+ id: Ulid::generate().to_string(),+ from: "bob/terminal".into(),+ from_agent: Some("cli".into()),+ from_repo: None,+ to: to.clone(),+ via: None,+ reply_to: None,+ body: "hi".into(),+ wake: true,+ notify: false,+ sent_at: 0,+ approval: None,+ files: Vec::new(),+ };+ d.receive(bob.public(), msg).unwrap();+ let got = d.inner.lock().unwrap().store.unread(&to).unwrap();+ assert_eq!(got[0].from, "bob/terminal@xps");+ let text = render::for_agent(&got, Some("codex"), false);+ assert!(+ text.contains("From bob, typed in a terminal.") && text.contains("send_message to \"bob/terminal@xps\""),+ "{text}"+ );}#[test]diff --git a/src/daemon/mod.rs b/src/daemon/mod.rsindex f0eca38..b387b74 100644--- a/src/daemon/mod.rs+++ b/src/daemon/mod.rs@@ -117,8 +117,10 @@ pub struct Daemon {shown: Mutex<HashMap<String, Instant>>,/// Each session's `ask_user` question that is up, with its answer once there is one.asks: Mutex<HashMap<String, ask::Asking>>,- /// When this daemon started: sessions live before it register again in the while after.- started: Instant,+ /// When this daemon started (ms): sessions live before it register again in the while after.+ started: i64,+ /// Whether the log says presence names only some of the names kept here.+ capped: std::sync::atomic::AtomicBool,/// Until when Reason sessions are listed without `--fields`, which the installed `reason` refused.plain_until: Mutex<Option<Instant>>,}@@ -163,6 +165,11 @@ struct Live {retry: Option<(Instant, Duration)>,/// Bumped to end this session's `check_inbox` wait (its client gave up on it).stop_gen: u64,+ /// 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+ /// one-shot or headless run without Reason Network's tools) was never reachable, and won't be.+ attached: bool,}pub fn load_key() -> Result<SecretKey> {@@ -213,8 +220,9 @@ impl Daemon {rate: Mutex::new(HashMap::new()),shown: Mutex::new(HashMap::new()),asks: Mutex::new(HashMap::new()),- started: Instant::now(),+ started: util::now_ms(),plain_until: Mutex::new(None),+ capped: Default::default(),})}diff --git a/src/daemon/sessions.rs b/src/daemon/sessions.rsindex ea5528c..f923759 100644--- a/src/daemon/sessions.rs+++ b/src/daemon/sessions.rs@@ -11,8 +11,14 @@ use crate::{store::Remembered,util,};+use crate::{net::Remote, team::TeamState};use anyhow::{Result, anyhow, bail};-use std::{collections::HashSet, sync::Arc, time::Instant};+use iroh::EndpointId;+use std::{+ collections::{HashMap, 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;@@ -54,7 +60,7 @@ impl Daemon {bail!(OFF_HERE);}let now = util::now_ms();- let others = self.my_names_elsewhere();+ let others = self.my_names_elsewhere(now);let mut g = self.inner.lock().unwrap();let g = &mut *g;let key = reg.key.clone();@@ -66,8 +72,10 @@ impl Daemon {// Known already (e.g. from a hook, now the MCP server connects, or a reconnect).if conn.is_some() {l.conn = conn;+ l.attached = true;}l.reg.tier = if l.push_failed { l.reg.tier.max(Tier::Turn) } else { l.reg.tier.min(reg.tier) };+ l.attached |= l.reg.tier == Tier::Push;if l.last_hook.is_none() {l.reg.cwd = reg.cwd;l.git = git;@@ -77,7 +85,9 @@ impl Daemon {if conn.is_none() {reg.tier = reg.tier.min(self.hook_tier(®.agent, false));}- let name = pick_name(g, ®, &git, &others)?;+ let name = pick_name(g, ®, &git, &others, |r| self.holds(r, now))?;+ self.take_over(g, &name, &key)?;+ let attached = conn.is_some() || reg.tier == Tier::Push || reg.agent == "cli";g.live.insert(key.clone(),Live {@@ -93,12 +103,13 @@ impl Daemon {transcript: None,retry: None,stop_gen: 0,+ attached,},);self.presence_changed();}let l = &g.live[&key];- g.store.upsert_session(&remembered(l, now))?;+ g.store.upsert_session(&remembered(l, now), &self.person)?;let name = l.name.clone();let address = self.addr(&name);let pending: Vec<Message> = g.pending(&address)?;@@ -107,29 +118,103 @@ impl Daemon {Ok((Registered { name, address, unread: pending.len() as u32 }, (key, wake)))}- /// Session names in use on my other machines, so my addresses stay unique across them.- fn my_names_elsewhere(&self) -> HashSet<String> {- let Some(net) = self.net() else { return HashSet::new() };- let Some(team) = self.team_state() else { return HashSet::new() };- net.remotes()- .into_iter()- .filter(|(id, _)| team.member(id).is_some_and(|m| m.person == self.person))- .flat_map(|(_, r)| r.presence.sessions.into_iter().map(|s| s.name))- .collect()+ /// My session names on my other machines, so my addresses stay unique across them (see [`names_elsewhere`]).+ fn my_names_elsewhere(&self, now: i64) -> Elsewhere {+ let (Some(net), Some(team)) = (self.net(), self.team_state()) else { return Elsewhere::default() };+ names_elsewhere(&net.remotes(), &team, &self.person, &self.key.public(), now)+ }++ /// This machine's terminal took a name another of my machines' terminal has too, while every engine in the team+ /// could tell two apart in a reply. Once one that can't is in the team, it takes the next free name, as it would if+ /// it registered now. (Checked as the terminal is used: each command from it comes through here.)+ fn recheck_terminal(&self, others: &Elsewhere) -> Result<()> {+ let now = util::now_ms();+ let name = {+ let g = self.inner.lock().unwrap();+ let Some(l) = g.live.get(TERMINAL) else { return Ok(()) };+ if others.terminals || !others.live.contains(&l.name) {+ return Ok(());+ }+ pick_name(&g, &l.reg, &l.git, others, |r| self.holds(r, now))?+ };+ log(&format!(+ "{} is on another machine too, and an older engine is in the team: now {name}",+ self.addr("terminal")+ ));+ self.set_status(TERMINAL, None, Some(name))?;+ Ok(())+ }++ /// 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))+ }++ /// Whether sessions gone a day are forgotten yet: not just after a start, while sessions that are still up haven't+ /// registered again (each gets the time a hook-only session has to show it is there).+ fn forgetting(&self, now: i64) -> bool {+ now - self.started > HOOK_TTL_MS+ }++ /// A live session turned out reachable (mail went to it or came from it): from now on its name is kept for it.+ pub(super) fn reached(&self, g: &mut Inner, key: &str) {+ if let Some(l) = g.live.get_mut(key)+ && !l.attached+ {+ l.attached = true;+ let r = remembered(l, util::now_ms());+ if let Err(e) = g.store.upsert_session(&r, &self.person) {+ log(&format!("remembering {key}: {e:#}"));+ }+ }+ }++ /// 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<()> {+ if let Some(r) = g.store.session_by_name(name)?+ && r.key != key+ && r.kept()+ {+ log(&format!("{} lapsed: {key} takes the name", self.addr(name)));+ g.store.forget_session(&r, &self.person)?;+ }+ Ok(())}pub(super) fn set_status(&self, key: &str, doing: Option<String>, name: Option<String>) -> Result<Registered> {- let others = self.my_names_elsewhere();+ let now = util::now_ms();+ let others = self.my_names_elsewhere(now);let mut g = self.inner.lock().unwrap();let g = &mut *g;- let new_name = match name.as_deref().map(util::slug) {- Some(n) if n.is_empty() => bail!("a name needs letters or digits"),- Some(n) if g.live.iter().any(|(k, l)| l.name == n && k != key) || others.contains(&n) => {- bail!("'{n}' is taken by a live session")+ let new_name = name.as_deref().map(util::slug);+ if let Some(n) = new_name.as_deref() {+ if n.is_empty() {+ bail!("a name needs letters or digits");}- Some(n) if n == self.person => bail!("'{n}' is your person name; pick another session name"),- n => n,- };+ if g.live.iter().any(|(k, l)| l.name == n && k != key) || others.live.contains(n) {+ bail!("'{n}' is taken by a live session");+ }+ if n == self.person {+ bail!("'{n}' is your person name; pick another session name");+ }+ // A name kept for a session that is offline stays its own, with its mail: never renamed into.+ if let Some(r) = g.store.session_by_name(n)?.filter(|r| r.key != key && self.holds(r, now)) {+ bail!(+ "'{n}' belongs to a session that is offline (last seen {} ago); pick another name",+ util::ago(r.last_seen, now)+ );+ }+ if others.kept.contains(n) {+ bail!("'{n}' belongs to a session on another of your machines that is offline; pick another name");+ }+ }+ if let Some(n) = new_name.as_deref()+ && g.live.get(key).is_some_and(|l| l.name != n)+ {+ self.take_over(g, n, key)?;+ }let live = g.live.get_mut(key).ok_or_else(|| anyhow!("this session is not registered"))?;if let Some(d) = doing {let d = d.trim();@@ -146,7 +231,7 @@ impl Daemon {)?;live.name = n;}- g.store.upsert_session(&remembered(live, util::now_ms()))?;+ g.store.upsert_session(&remembered(live, now), &self.person)?;let address = self.addr(&live.name);Ok(Registered { name: live.name.clone(), unread: g.store.unread_count(&address)?, address })}@@ -204,6 +289,9 @@ impl Daemon {return Ok(HookReply::default());}let known = self.inner.lock().unwrap().live.contains_key(&key);+ if known && key == TERMINAL {+ self.recheck_terminal(&self.my_names_elsewhere(now))?;+ }if !known {let remembered_cwd = self.inner.lock().unwrap().store.session_by_key(&key)?.map(|r| r.cwd);let cwd = cwd.or(remembered_cwd).unwrap_or_else(|| "/".into());@@ -256,6 +344,10 @@ impl Daemon {for id in &ids {g.in_flight.insert(id.clone(), Instant::now());}+ // Its hooks hand it mail: it can be reached, and its name stays its own.+ if !ids.is_empty() {+ self.reached(g, &key);+ }let text = (!msgs.is_empty()).then(|| render::for_agent(&msgs, Some(&agent_kind), false));Ok(HookReply { address: Some(address), text, ids })}@@ -279,11 +371,20 @@ impl Daemon {}).collect();let here: Vec<&(&String, &Live)> = busy.iter().filter(|(_, l)| l.reg.cwd == cwd).collect();- Ok(match (here.as_slice(), busy.as_slice()) {+ let key = match (here.as_slice(), busy.as_slice()) {([(k, _)], _) => Some((*k).clone()),([], [(k, _)]) => Some((*k).clone()),_ => None,- })+ };+ // Its agent's MCP server answers for it now.+ if let Some(l) = key.as_ref().and_then(|k| g.live.get_mut(k))+ && !l.attached+ {+ l.attached = true;+ let r = remembered(l, now);+ g.store.upsert_session(&r, &self.person)?;+ }+ Ok(key)}pub(super) fn drop_conn(&self, conn: u64) {@@ -325,15 +426,17 @@ impl Daemon {}}g.off.retain(|_, (_, at)| now - *at <= HOOK_TTL_MS);- // Just after a start, sessions that are still up haven't registered again: none is forgotten until each has had- // the time a hook-only session gets to show it is there.- if self.started.elapsed().as_millis() > HOOK_TTL_MS as u128 {+ if self.forgetting(now) {let live: HashSet<&str> = g.live.values().map(|l| l.name.as_str()).collect();let _ = g.store.forget_sessions(now - FORGET_MS, &live, &self.person);}// Files of messages that are gone, or were read a day ago.if now - g.swept > 10 * 60_000 {g.swept = now;+ // Live sessions are seen now: if this daemon stops without seeing them go, their names are kept from then.+ for l in g.live.values() {+ let _ = g.store.touch_session(&l.name, now);+ }if let Err(e) = g.store.sweep_files(now) {log(&format!("sweeping the inbox folder: {e:#}"));}@@ -352,34 +455,731 @@ fn remembered(l: &Live, now: i64) -> Remembered {doing: l.doing.clone(),tier: l.reg.tier,last_seen: now,+ attached: l.attached,+ }+}++/// The key of a machine's own terminal mailbox (`<you>/terminal`).+const TERMINAL: &str = "cli:terminal";++/// What a machine's presence says when its engine shows a message from another machine's terminal as from+/// `<person>/terminal@<machine>`, so its agents' replies reach the one it came from.+pub(super) const TERMINALS: &str = "terminals";++/// My session names on my other machines.+#[derive(Default, Debug, PartialEq)]+struct Elsewhere {+ live: HashSet<String>,+ kept: HashSet<String>,+ /// Every teammate machine heard from routes replies to a terminal by machine (`TERMINALS`).+ terminals: bool,+}++/// The session names on `person`'s other machines, from their presence: live sessions', and those kept there for+/// sessions that are offline (older engines don't say which). Kept names count while that machine is online or was+/// in the last day: one off longer can't still be keeping them, and its last presence, loaded from disk, would+/// otherwise hold them for good.+fn names_elsewhere(+ remotes: &HashMap<EndpointId, Remote>,+ team: &TeamState,+ person: &str,+ me: &EndpointId,+ now: i64,+) -> Elsewhere {+ let mut out = Elsewhere { terminals: true, ..Default::default() };+ for m in team.active().filter(|m| m.endpoint != *me) {+ // A machine not heard from yet (offline since before this one joined) may be of an older engine.+ let r = remotes.get(&m.endpoint);+ out.terminals &= r.is_some_and(|r| r.presence.has(TERMINALS));+ let Some(r) = r else { continue };+ if m.person != person {+ continue;+ }+ out.live.extend(r.presence.sessions.iter().map(|s| s.name.clone()));+ if r.online || now - r.last_seen <= FORGET_MS {+ out.kept.extend(r.presence.kept.iter().cloned());+ }}+ out}-/// Reuse this session's previous name, else `<repo>-<agent>` (inheriting it and its mail if it is stale),-/// else the first free `-2`, `-3`, …-fn pick_name(g: &Inner, reg: &SessionReg, git: &GitInfo, elsewhere: &HashSet<String>) -> Result<String> {- let taken = |n: &str| g.live.values().any(|l| l.name == n) || elsewhere.contains(n);+/// The name of a session registering here. Its own from before (and the mail waiting for it), unless a live session+/// has that now; else the name it asks for or `<repo>-<agent>`, or the first `-2`, `-3`, … that is free: that no live+/// session has, here or on my other machines, and that isn't kept for another session that is offline (`holds`). One of+/// the person's own mailboxes (`listen --as`) takes the name it asks for whenever that is free.+fn pick_name(+ g: &Inner,+ reg: &SessionReg,+ git: &GitInfo,+ elsewhere: &Elsewhere,+ holds: impl Fn(&Remembered) -> bool,+) -> Result<String> {+ // A machine's own `terminal` is its own: another machine's never makes it take a suffix, once every engine in the+ // team shows which machine a terminal's message came from. (An older one couldn't tell two apart in a reply.)+ let none = Elsewhere::default();+ let elsewhere = if reg.key == TERMINAL && elsewhere.terminals { &none } else { elsewhere };+ let live = |n: &str| g.live.iter().any(|(k, l)| l.name == n && *k != reg.key) || elsewhere.live.contains(n);+ let free = |n: &str| -> Result<bool> {+ let kept_here = g.store.session_by_name(n)?.is_some_and(|r| r.key != reg.key && holds(&r));+ Ok(!live(n) && !kept_here && !elsewhere.kept.contains(n))+ };+ let asked = reg.name.as_deref().map(util::slug).filter(|s| !s.is_empty());+ // One of the person's own mailboxes is the name it asks for: once that is free again, it goes back to it (its mail+ // from the suffixed name comes along).+ if reg.key.starts_with("cli:")+ && let Some(n) = asked.as_deref()+ && free(n)?+ {+ return Ok(n.to_string());+ }if let Some(r) = g.store.session_by_key(®.key)?- && !taken(&r.name)+ && !live(&r.name){return Ok(r.name);}- let base = reg- .name- .as_deref()- .map(util::slug)- .filter(|s| !s.is_empty())- .unwrap_or_else(|| agent::default_name(®.agent, ®.cwd, git));- if !taken(&base) {+ let base = asked.unwrap_or_else(|| agent::default_name(®.agent, ®.cwd, git));+ if free(&base)? {return Ok(base);}- Ok((2..).map(|i| util::joined(&base, &i.to_string())).find(|n| !taken(n)).expect("some suffix is free"))+ for i in 2.. {+ let n = util::joined(&base, &i.to_string());+ if free(&n)? {+ return Ok(n);+ }+ }+ unreachable!("some suffix is free")}#[cfg(test)]mod tests {use super::*;+ const DAY: i64 = 24 * 3_600_000;++ fn claude(id: &str) -> SessionReg {+ SessionReg {+ key: format!("claude-code:{id}"),+ agent: agent::CLAUDE_CODE.into(),+ cwd: "/work/api".into(),+ agent_session_id: Some(id.into()),+ pid: None,+ tier: Tier::Push,+ name: None,+ }+ }++ fn named(key: &str, agent: &str, name: Option<&str>) -> SessionReg {+ SessionReg {+ key: key.into(),+ agent: agent.into(),+ cwd: "/work/api".into(),+ agent_session_id: None,+ pid: None,+ tier: Tier::Pull,+ name: name.map(str::to_string),+ }+ }++ fn join(d: &Daemon, reg: SessionReg) -> Registered {+ d.register_quiet(Some(1), reg, GitInfo::default()).unwrap().0+ }++ /// Takes a session here offline, last seen `ago` before now.+ fn leave(d: &Daemon, key: &str, ago: i64) {+ 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();+ }++ /// The daemon restarts: nothing is live until sessions register again.+ fn restart(d: &Daemon) {+ d.inner.lock().unwrap().live.clear();+ }++ /// Long enough after a start that sessions gone a day are forgotten.+ fn settled(d: &mut Daemon) {+ d.started -= HOOK_TTL_MS + 1;+ }++ fn mail(d: &Daemon, id: &str, name: &str) {+ let mut m = Message {+ id: id.into(),+ from: "sven/web-codex".into(),+ from_agent: None,+ from_repo: None,+ to: d.addr(name),+ via: None,+ reply_to: None,+ body: format!("for {name}"),+ wake: true,+ notify: false,+ sent_at: 0,+ approval: None,+ files: Vec::new(),+ };+ d.inner.lock().unwrap().store.insert(&mut m, false).unwrap();+ }++ #[test]+ fn a_conversation_gets_its_name_and_mail_back_after_a_restart_whoever_registers_first() {+ let d = super::super::test_daemon(Default::default());+ assert_eq!(join(&d, claude("a")).name, "api-claude");+ assert_eq!(join(&d, claude("b")).name, "api-claude-2");+ restart(&d);+ mail(&d, "m1", "api-claude");+ mail(&d, "m2", "api-claude-2");+ // A new conversation in the same folder comes back first: both names are kept, and it gets none of their mail.+ let new = join(&d, claude("c"));+ assert_eq!((new.name.as_str(), new.unread), ("api-claude-3", 0));+ // Then the two others, in the other order.+ let b = join(&d, claude("b"));+ assert_eq!((b.name.as_str(), b.unread), ("api-claude-2", 1));+ let a = join(&d, claude("a"));+ assert_eq!((a.name.as_str(), a.unread), ("api-claude", 1));+ }++ #[test]+ fn a_new_conversation_never_takes_the_name_or_mail_of_one_that_is_offline() {+ let d = super::super::test_daemon(Default::default());+ join(&d, claude("a"));+ leave(&d, "claude-code:a", 3 * 3_600_000);+ mail(&d, "m1", "api-claude");+ // Asking for the name doesn't get it either.+ let new = join(&d, named("cli:api-claude", "cli", Some("api-claude")));+ assert_eq!((new.name.as_str(), new.unread), ("api-claude-2", 0));+ let other = join(&d, claude("c"));+ assert_eq!((other.name.as_str(), other.unread), ("api-claude-3", 0));+ // Resumed hours later, the conversation is still api-claude, with its mail.+ let a = join(&d, claude("a"));+ assert_eq!((a.name.as_str(), a.unread), ("api-claude", 1));+ }++ #[tokio::test]+ async fn a_conversation_coming_back_through_its_hooks_gets_its_name_too() {+ let d = Arc::new(super::super::test_daemon(Default::default()));+ let call = |id: &str| HookCall {+ agent: "claude-code".into(),+ event: "start".into(),+ session_id: id.into(),+ cwd: Some("/work/api".into()),+ pid: None,+ mail: true,+ transcript: None,+ doing: None,+ name: None,+ dirs: Vec::new(),+ };+ // Its MCP server registered it; then it ends.+ assert_eq!(join(&d, claude("a")).name, "api-claude");+ d.hook(call("a")).await.unwrap();+ d.drop_conn(1);+ d.hook(HookCall { event: "end".into(), ..call("a") }).await.unwrap();+ mail(&d, "m1", "api-claude");+ assert_eq!(d.hook(call("b")).await.unwrap().address, Some(d.addr("api-claude-2")));+ let back = d.hook(call("a")).await.unwrap();+ assert_eq!(back.address, Some(d.addr("api-claude")));+ assert!(back.text.is_some_and(|t| t.contains("for api-claude")));+ }++ #[test]+ fn a_name_is_kept_until_its_conversation_would_be_forgotten_and_then_comes_without_its_mail() {+ let mut d = super::super::test_daemon(Default::default());+ join(&d, claude("a"));+ leave(&d, "claude-code:a", DAY + 60_000);+ mail(&d, "m1", "api-claude");+ // Just after a start, sessions still up may not have registered again: nothing has lapsed yet.+ assert_eq!(join(&d, claude("b")).name, "api-claude-2");+ settled(&mut d);+ // A day on, the name is free again, but the mail stays the forgotten conversation's: it is dropped.+ let c = join(&d, claude("c"));+ assert_eq!((c.name.as_str(), c.unread), ("api-claude", 0));+ assert_eq!(d.inner.lock().unwrap().store.unread_count(&d.addr("api-claude")).unwrap(), 0);+ // Back after that, the conversation is a new session.+ assert_eq!(join(&d, claude("a")).name, "api-claude-3");+ }++ #[test]+ fn live_sessions_are_seen_as_they_run_so_a_restart_after_days_up_keeps_their_names() {+ let mut d = super::super::test_daemon(Default::default());+ settled(&mut d);+ join(&d, claude("a"));+ // Registered days ago, and still up.+ d.inner.lock().unwrap().store.touch_session("api-claude", util::now_ms() - 3 * DAY).unwrap();+ let mut g = d.inner.lock().unwrap();+ d.prune(&mut g);+ let r = g.store.session_by_name("api-claude").unwrap().unwrap();+ assert!(util::now_ms() - r.last_seen < 60_000);+ }++ #[test]+ fn renaming_into_a_name_kept_for_an_offline_session_is_refused() {+ let mut d = super::super::test_daemon(Default::default());+ join(&d, claude("a"));+ leave(&d, "claude-code:a", 3 * 3_600_000);+ mail(&d, "m1", "api-claude");+ join(&d, claude("b"));+ let e = d.set_status("claude-code:b", None, Some("API Claude".into())).unwrap_err();+ assert_eq!(+ e.to_string(),+ "'api-claude' belongs to a session that is offline (last seen 3h ago); pick another name"+ );+ // A name of its own is fine, and its own mail comes along.+ mail(&d, "m2", "api-claude-2");+ let r = d.set_status("claude-code:b", None, Some("auth".into())).unwrap();+ assert_eq!((r.name.as_str(), r.unread), ("auth", 1));+ // Once the offline one has lapsed, the name can be taken, without that session's mail.+ leave(&d, "claude-code:b", 0);+ join(&d, claude("b"));+ d.inner.lock().unwrap().store.touch_session("api-claude", util::now_ms() - 2 * DAY).unwrap();+ settled(&mut d);+ let r = d.set_status("claude-code:b", None, Some("api-claude".into())).unwrap();+ assert_eq!(r.name, "api-claude");+ let unread = d.inner.lock().unwrap().store.unread(&r.address).unwrap();+ assert_eq!(unread.iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["m2"]);+ }++ #[test]+ fn the_persons_own_mailboxes_keep_their_names_for_good() {+ let mut d = super::super::test_daemon(Default::default());+ settled(&mut d);+ join(&d, named("cli:review", "cli", Some("review")));+ leave(&d, "cli:review", 30 * DAY);+ mail(&d, "m1", "review");+ // A Claude Code session someone named "review" can't have that mailbox.+ let c = join(&d, SessionReg { name: Some("Review".into()), ..claude("c") });+ assert_eq!((c.name.as_str(), c.unread), ("review-2", 0));+ let r = join(&d, named("cli:review", "cli", Some("review")));+ assert_eq!((r.name.as_str(), r.unread), ("review", 1));+ }++ #[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());+ assert_eq!(join(&d, named("proc:11", "zed", None)).name, "api-zed");+ leave(&d, "proc:11", 3 * 3_600_000);+ mail(&d, "m1", "api-zed");+ // As before: nothing could come back for it, so "tell the api agent" reaches the one there now.+ let next = join(&d, named("proc:12", "zed", None));+ assert_eq!((next.name.as_str(), next.unread), ("api-zed", 1));+ // But it can't take a name kept for a conversation.+ join(&d, claude("a"));+ leave(&d, "claude-code:a", 0);+ assert_eq!(join(&d, named("proc:13", "zed", Some("api-claude"))).name, "api-claude-2");+ }++ #[test]+ fn rows_an_older_engine_left_are_kept_for_their_sessions_and_others_work_as_before() {+ let d = super::super::test_daemon(Default::default());+ let row = |name: &str, key: &str| Remembered {+ name: name.into(),+ key: key.into(),+ agent: agent::CLAUDE_CODE.into(),+ cwd: "/work/api".into(),+ repo: None,+ branch: None,+ doing: None,+ tier: Tier::Push,+ last_seen: util::now_ms() - 3_600_000,+ attached: true,+ };+ {+ let g = d.inner.lock().unwrap();+ for (name, key) in+ [("api-claude", "claude-code:a"), ("api-claude-2", "claude-code:b"), ("api-claude-3", "proc:5")]+ {+ g.store.upsert_session(&row(name, key), &d.person).unwrap();+ }+ }+ for (id, name) in [("m1", "api-claude"), ("m2", "api-claude-2"), ("m3", "api-claude-3")] {+ mail(&d, id, name);+ }+ // Rows with an agent's id are kept for it from the start; one known by its process is taken, mail and all.+ let new = join(&d, claude("d"));+ assert_eq!((new.name.as_str(), new.unread), ("api-claude-3", 1));+ let b = join(&d, claude("b"));+ assert_eq!((b.name.as_str(), b.unread), ("api-claude-2", 1));+ let a = join(&d, claude("a"));+ assert_eq!((a.name.as_str(), a.unread), ("api-claude", 1));+ }++ #[test]+ fn a_session_whose_name_went_elsewhere_takes_its_mail_to_its_new_one() {+ let d = super::super::test_daemon(Default::default());+ join(&d, claude("a"));+ leave(&d, "claude-code:a", 3_600_000);+ mail(&d, "m1", "api-claude");+ // An older engine on another of my machines gave the name to a live session there.+ let elsewhere =+ Elsewhere { live: HashSet::from(["api-claude".to_string()]), kept: HashSet::new(), terminals: true };+ let mut g = d.inner.lock().unwrap();+ let g = &mut *g;+ let name = pick_name(g, &claude("a"), &GitInfo::default(), &elsewhere, |_| true).unwrap();+ assert_eq!(name, "api-claude-2");+ let r = Remembered {+ name: name.clone(),+ key: "claude-code:a".into(),+ agent: agent::CLAUDE_CODE.into(),+ cwd: "/work/api".into(),+ repo: None,+ branch: None,+ doing: None,+ tier: Tier::Push,+ last_seen: util::now_ms(),+ attached: true,+ };+ g.store.upsert_session(&r, &d.person).unwrap();+ assert!(g.store.session_by_name("api-claude").unwrap().is_none());+ assert_eq!(g.store.unread_count(&d.addr("api-claude-2")).unwrap(), 1);+ }++ #[test]+ fn names_kept_on_my_other_machines_go_to_no_new_session_here() {+ let d = super::super::test_daemon(Default::default());+ let elsewhere = Elsewhere {+ live: HashSet::from(["api-claude".to_string()]),+ kept: HashSet::from(["api-claude-2".to_string()]),+ terminals: true,+ };+ let g = d.inner.lock().unwrap();+ assert_eq!(pick_name(&g, &claude("c"), &GitInfo::default(), &elsewhere, |_| true).unwrap(), "api-claude-3");+ }++ #[test]+ fn presence_tells_my_other_machines_which_names_are_kept() {+ let mut d = super::super::test_daemon(Default::default());+ settled(&mut d);+ join(&d, claude("a"));+ join(&d, named("cli:terminal", "cli", Some("terminal")));+ join(&d, named("proc:9", "zed", None));+ join(&d, claude("old"));+ join(&d, claude("up"));+ leave(&d, "claude-code:a", 3_600_000);+ leave(&d, "cli:terminal", 3 * DAY);+ leave(&d, "proc:9", 3_600_000);+ leave(&d, "claude-code:old", 2 * DAY);+ let p = d.presence_of(Vec::new());+ let mut known = p.known.clone();+ known.sort();+ assert_eq!(known, ["api-claude", "api-claude-2", "api-zed", "terminal"]);+ // Not each machine's own `terminal`, nor a session that can't come back, nor one that has lapsed.+ assert_eq!(p.kept, ["api-claude"]);+ }+ #[tokio::test]+ async fn a_run_only_its_hooks_ever_saw_keeps_no_name() {+ let d = Arc::new(super::super::test_daemon(Default::default()));+ let call = |id: &str, event: &str| HookCall {+ agent: "claude-code".into(),+ event: event.into(),+ session_id: id.into(),+ cwd: Some("/work/api".into()),+ pid: None,+ mail: true,+ transcript: None,+ doing: None,+ name: None,+ dirs: Vec::new(),+ };+ // 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")));+ d.hook(call("p", "end")).await.unwrap();+ mail(&d, "m1", "api-claude");+ let r = d.inner.lock().unwrap().store.session_by_name("api-claude").unwrap().unwrap();+ assert!(!r.kept());+ // As for a session without an id: the next one in its place takes the name, mail and all.+ let next = join(&d, claude("q"));+ assert_eq!((next.name.as_str(), next.unread), ("api-claude", 1));+ // A run whose MCP server answers for it is reachable, so its name is kept from then on.+ assert_eq!(d.hook(call("r", "prompt")).await.unwrap().address, Some(d.addr("api-claude-2")));+ let mut cursor = call("r", "prompt");+ cursor.agent = "cursor".into();+ d.hook(cursor).await.unwrap();+ assert_eq!(d.attach("cursor", "/work/api").unwrap().as_deref(), Some("cursor:r"));+ assert!(d.inner.lock().unwrap().store.session_by_key("cursor:r").unwrap().unwrap().kept());+ }++ fn gemini(id: &str, event: &str) -> HookCall {+ HookCall {+ agent: "gemini".into(),+ event: event.into(),+ session_id: id.into(),+ cwd: Some("/work/api".into()),+ pid: None,+ mail: true,+ transcript: None,+ doing: None,+ name: None,+ dirs: Vec::new(),+ }+ }++ #[tokio::test]+ async fn a_session_its_hooks_hand_mail_to_keeps_its_name() {+ // Gemini is reached through its hooks only: no MCP connection or push channel ever.+ let d = Arc::new(super::super::test_daemon(Default::default()));+ assert_eq!(d.hook(gemini("g1", "start")).await.unwrap().address, Some(d.addr("api-gemini")));+ mail(&d, "m1", "api-gemini");+ let got = d.hook(gemini("g1", "stop")).await.unwrap();+ assert!(got.text.is_some_and(|t| t.contains("for api-gemini")));+ d.hook(gemini("g1", "end")).await.unwrap();+ mail(&d, "m2", "api-gemini");+ // A new conversation gets the next name, and none of g1's mail.+ let g2 = d.hook(gemini("g2", "start")).await.unwrap();+ assert_eq!((g2.address, g2.text.is_some()), (Some(d.addr("api-gemini-2")), false));+ // g1, resumed, is api-gemini again, with what came meanwhile.+ let back = d.hook(gemini("g1", "start")).await.unwrap();+ assert_eq!(back.address, Some(d.addr("api-gemini")));+ assert!(back.text.is_some_and(|t| t.contains("for api-gemini")));+ }++ #[tokio::test]+ async fn a_session_that_sends_or_is_sent_mail_keeps_its_name() {+ let d = Arc::new(super::super::test_daemon(Default::default()));+ d.hook(gemini("s", "start")).await.unwrap();+ let mut copilot = gemini("r", "start");+ copilot.agent = "copilot".into();+ d.hook(copilot.clone()).await.unwrap();+ // s writes to r, whose hooks haven't shown it yet.+ d.send("gemini:s".into(), &d.addr("api-copilot"), "hi", None, true, false, None, Vec::new()).await.unwrap();+ let g = d.inner.lock().unwrap();+ for key in ["gemini:s", "copilot:r"] {+ assert!(g.store.session_by_key(key).unwrap().unwrap().kept(), "{key}");+ }+ }++ #[tokio::test]+ async fn a_session_stays_reachable_once_it_has_been() {+ let d = Arc::new(super::super::test_daemon(Default::default()));+ d.hook(gemini("g1", "start")).await.unwrap();+ mail(&d, "m1", "api-gemini");+ d.hook(gemini("g1", "stop")).await.unwrap();+ d.hook(gemini("g1", "end")).await.unwrap();+ // Back through its hooks, with no mail this time, then gone again: still kept.+ d.hook(gemini("g1", "start")).await.unwrap();+ d.hook(gemini("g1", "end")).await.unwrap();+ assert!(d.inner.lock().unwrap().store.session_by_key("gemini:g1").unwrap().unwrap().kept());+ assert_eq!(d.hook(gemini("g2", "start")).await.unwrap().address, Some(d.addr("api-gemini-2")));+ }++ #[test]+ fn a_listen_mailbox_goes_back_to_the_name_it_asks_for_once_free() {+ let mut d = super::super::test_daemon(Default::default());+ join(&d, named("cli:review-x", "cli", Some("x")));+ join(&d, SessionReg { name: Some("review".into()), ..claude("a") });+ leave(&d, "claude-code:a", 3_600_000);+ // `listen --as review` while the name is kept for the conversation: the next free one.+ assert_eq!(join(&d, named("cli:review", "cli", Some("review"))).name, "review-2");+ leave(&d, "cli:review", 0);+ mail(&d, "m1", "review-2");+ assert_eq!(join(&d, named("cli:review", "cli", Some("review"))).name, "review-2");+ leave(&d, "cli:review", 0);+ // Once the conversation's name lapses, the mailbox takes it, and its mail comes along.+ d.inner.lock().unwrap().store.touch_session("review", util::now_ms() - 2 * DAY).unwrap();+ settled(&mut d);+ let r = join(&d, named("cli:review", "cli", Some("review")));+ assert_eq!((r.name.as_str(), r.unread), ("review", 1));+ assert!(d.inner.lock().unwrap().store.session_by_name("review-2").unwrap().is_none());+ }++ #[tokio::test]+ async fn mail_held_for_a_conversation_goes_with_it_and_never_to_the_next_session() {+ let cfg = crate::config::Config {+ person: Some("alex".into()),+ inbound: crate::config::Inbound { default: crate::config::Policy::Hold, ..Default::default() },+ ..Default::default()+ };+ let mut d = super::super::test_daemon(cfg);+ let bob = iroh::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);+ let d = {+ join(&d, claude("a"));+ join(&d, named("proc:5", "zed", None));+ leave(&d, "claude-code:a", 0);+ leave(&d, "proc:5", 0);+ settled(&mut d);+ Arc::new(d)+ };+ let (h1, h2) = (ulid::Ulid::generate().to_string(), ulid::Ulid::generate().to_string());+ let from_bob = |id: &str, to: &str| Message {+ id: id.into(),+ from: "bob/web".into(),+ from_agent: None,+ from_repo: None,+ to: d.addr(to),+ 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(), from_bob(&h1, "api-claude")).unwrap();+ assert_eq!(state, "held");+ assert_eq!(note, "held until alex approves it; dropped if that session is gone for a day first");+ // Held for a session without an id, it stays the person's to settle, for whoever has the name, as before.+ assert_eq!(d.receive(bob.public(), from_bob(&h2, "api-zed")).unwrap().1, "held until alex approves it");+ // A day on, both names lapse: the conversation's held mail goes with it.+ {+ let g = d.inner.lock().unwrap();+ g.store.touch_session("api-claude", util::now_ms() - 2 * DAY).unwrap();+ g.store.touch_session("api-zed", util::now_ms() - 2 * DAY).unwrap();+ }+ let next = join(&d, claude("b"));+ assert_eq!(next.name, "api-claude");+ let held: Vec<String> = d.inner.lock().unwrap().store.held().unwrap().into_iter().map(|m| m.id).collect();+ assert_eq!(held, [h2]);+ assert_eq!(d.settle(&[], true).unwrap(), 1);+ assert_eq!(d.inner.lock().unwrap().store.unread_count(&d.addr("api-claude")).unwrap(), 0);+ }++ #[test]+ fn names_elsewhere_are_my_other_machines_and_kept_ones_only_while_they_could_still_be_kept() {+ let d = super::super::test_daemon(crate::config::Config { person: Some("alex".into()), ..Default::default() });+ let (desk, old, bob) = (iroh::SecretKey::generate(), iroh::SecretKey::generate(), iroh::SecretKey::generate());+ let mut team = TeamState::found("acme", &d.person, &d.machine, &d.key);+ team.put_member(&d.key, desk.public(), "alex", "desk", true);+ team.put_member(&d.key, old.public(), "alex", "old", true);+ team.put_member(&d.key, bob.public(), "bob", "xps", true);+ let now = util::now_ms();+ let remote = |live: &str, kept: &str, online: bool, last_seen: i64| Remote {+ presence: crate::net::Presence {+ sessions: vec![SessionInfo {+ address: String::new(),+ name: live.into(),+ person: String::new(),+ machine: String::new(),+ agent: "codex".into(),+ cwd: String::new(),+ repo: None,+ branch: None,+ status: "idle".into(),+ since: None,+ doing: None,+ tier: Tier::Pull,+ unread: 0,+ is_me: false,+ }],+ known: vec![kept.into()],+ kept: vec![kept.into()],+ ..Default::default()+ },+ last_seen,+ online,+ };+ let remotes = HashMap::from([+ (desk.public(), remote("desk-live", "desk-kept", false, now - 3_600_000)),+ // Off for two days: what it kept then has lapsed by now.+ (old.public(), remote("old-live", "old-kept", false, now - 2 * DAY)),+ // Another person's names are theirs.+ (bob.public(), remote("bob-live", "bob-kept", true, now)),+ ]);+ let e = names_elsewhere(&remotes, &team, "alex", &d.key.public(), now);+ let set = |v: &[&str]| v.iter().map(|s| s.to_string()).collect::<HashSet<_>>();+ assert_eq!(e.live, set(&["desk-live", "old-live"]));+ assert_eq!(e.kept, set(&["desk-kept"]));+ // None of those engines said it tells terminals apart by machine.+ assert!(!e.terminals);+ }++ #[test]+ fn terminals_go_by_machine_only_once_every_machine_in_the_team_says_it_can() {+ let d = super::super::test_daemon(crate::config::Config { person: Some("alex".into()), ..Default::default() });+ let (desk, olga) = (iroh::SecretKey::generate(), iroh::SecretKey::generate());+ let mut team = TeamState::found("acme", &d.person, &d.machine, &d.key);+ team.put_member(&d.key, desk.public(), "alex", "desk", true);+ team.put_member(&d.key, olga.public(), "olga", "oldbox", true);+ let now = util::now_ms();+ let new = Remote {+ presence: crate::net::Presence { features: vec![TERMINALS.into()], ..Default::default() },+ last_seen: now,+ online: true,+ };+ let me = d.key.public();+ // olga's machine hasn't been heard from (it was off when this one joined): it may be an older engine.+ let remotes = HashMap::from([(desk.public(), new.clone())]);+ assert!(!names_elsewhere(&remotes, &team, "alex", &me, now).terminals);+ // Heard from, and an older engine.+ let old = Remote { presence: Default::default(), ..new.clone() };+ let remotes = HashMap::from([(desk.public(), new.clone()), (olga.public(), old)]);+ assert!(!names_elsewhere(&remotes, &team, "alex", &me, now).terminals);+ // Every other machine says it can (this one isn't asked).+ let remotes = HashMap::from([(desk.public(), new.clone()), (olga.public(), new)]);+ assert!(names_elsewhere(&remotes, &team, "alex", &me, now).terminals);+ }++ #[tokio::test]+ async fn a_terminal_takes_a_suffix_once_an_older_engine_turns_up() {+ let d = Arc::new(super::super::test_daemon(Default::default()));+ assert_eq!(join(&d, named(TERMINAL, "cli", Some("terminal"))).name, "terminal");+ mail(&d, "m1", "terminal");+ let mut others =+ Elsewhere { live: HashSet::from(["terminal".to_string()]), terminals: true, ..Default::default() };+ // Every engine tells two apart: it stays `terminal`.+ d.recheck_terminal(&others).unwrap();+ assert_eq!(d.inner.lock().unwrap().live[TERMINAL].name, "terminal");+ // An older one is in the team now: the next free name, with its mail.+ others.terminals = false;+ d.recheck_terminal(&others).unwrap();+ let g = d.inner.lock().unwrap();+ assert_eq!(g.live[TERMINAL].name, "terminal-2");+ assert_eq!(g.store.unread_count(&d.addr("terminal-2")).unwrap(), 1);+ }++ #[test]+ fn each_machine_has_its_own_terminal() {+ let d = super::super::test_daemon(Default::default());+ let mut elsewhere = Elsewhere {+ live: HashSet::from(["terminal".to_string()]),+ kept: HashSet::from(["review".to_string()]),+ terminals: false,+ };+ let g = d.inner.lock().unwrap();+ let terminal = named(TERMINAL, "cli", Some("terminal"));+ // While an older engine in the team couldn't tell two apart in a reply, the second one on is `terminal-2`.+ assert_eq!(pick_name(&g, &terminal, &GitInfo::default(), &elsewhere, |_| true).unwrap(), "terminal-2");+ elsewhere.terminals = true;+ assert_eq!(pick_name(&g, &terminal, &GitInfo::default(), &elsewhere, |_| true).unwrap(), "terminal");+ // Any other session asking for it, or for a name kept elsewhere, still gets the next free one.+ let other = named("cli:t2", "cli", Some("terminal"));+ assert_eq!(pick_name(&g, &other, &GitInfo::default(), &elsewhere, |_| true).unwrap(), "terminal-2");+ let review = named("cli:review", "cli", Some("review"));+ assert_eq!(pick_name(&g, &review, &GitInfo::default(), &elsewhere, |_| true).unwrap(), "review-2");+ }++ #[test]+ fn presence_names_the_most_recent_kept_names_when_there_are_too_many() {+ let d = super::super::test_daemon(Default::default());+ let now = util::now_ms();+ {+ let g = d.inner.lock().unwrap();+ for i in 0..120 {+ let r = Remembered {+ name: format!("s{i}"),+ key: format!("codex:{i}"),+ agent: "codex".into(),+ cwd: "/work/api".into(),+ repo: None,+ branch: None,+ doing: None,+ tier: Tier::Pull,+ last_seen: now - 1_000 * (120 - i),+ attached: true,+ };+ g.store.upsert_session(&r, &d.person).unwrap();+ }+ }+ let p = d.presence_of(Vec::new());+ assert_eq!(p.kept.len(), 100);+ assert_eq!(+ (p.kept.first().map(String::as_str), p.kept.last().map(String::as_str)),+ (Some("s119"), Some("s20"))+ );+ assert_eq!(p.known, p.kept);+ }+#[test]fn a_session_in_a_folder_that_is_off_never_registers() {let cfg = crate::config::Config {diff --git a/src/net.rs b/src/net.rsindex 1767a7f..8506ed3 100644--- a/src/net.rs+++ b/src/net.rs@@ -60,6 +60,10 @@ pub struct Presence {pub sessions: Vec<SessionInfo>,/// Names of this machine's offline sessions, so mail for them can be queued here.pub known: Vec<String>,+ /// Of those, the ones kept for their own sessions (conversations that can come back to them): the person's other+ /// machines give none of them to a new session. Older engines leave it out, and ignore it.+ #[serde(default, skip_serializing_if = "Vec::is_empty")]+ pub kept: Vec<String>,/// What this machine's engine takes beyond what every version does (`files`). Older engines leave it out, and/// ignore it.#[serde(default, skip_serializing_if = "Vec::is_empty")]@@ -1094,6 +1098,13 @@ fn tidy_presence(mut p: Presence) -> Presence {.map(|n| util::slug(n).chars().take(64).collect()).filter(|n: &String| !n.is_empty()).collect();+ p.kept = p+ .kept+ .iter()+ .take(100)+ .map(|n| util::slug(n).chars().take(64).collect())+ .filter(|n: &String| !n.is_empty())+ .collect();p.features.truncate(20);p.features.iter_mut().for_each(|f| *f = util::slug(f).chars().take(32).collect());p@@ -1194,7 +1205,7 @@ mod tests {unread: 0,is_me: false,};- let p = tidy_presence(Presence { sessions: vec![s], known: vec![], features: vec![] });+ let p = tidy_presence(Presence { sessions: vec![s], ..Default::default() });let d = crate::proto::Directory {team: None,person: "alex".into(),@@ -1346,4 +1357,28 @@ mod tests {assert!(!older.has("files"));assert!(tidy_presence(Presence { features: vec!["files".into()], ..Default::default() }).has("files"));}++ #[test]+ fn presence_says_which_names_are_kept_and_older_engines_read_it_as_before() {+ let new = Presence { known: vec!["api-claude".into()], kept: vec!["api-claude".into()], ..Default::default() };+ let wire = serde_json::to_string(&Wire::Presence { presence: new }).unwrap();+ #[derive(Deserialize)]+ struct OlderPresence {+ known: Vec<String>,+ }+ #[derive(Deserialize)]+ #[serde(tag = "t", rename_all = "snake_case")]+ enum OlderWire {+ Presence { presence: OlderPresence },+ }+ let OlderWire::Presence { presence } = serde_json::from_str(&wire).unwrap();+ assert_eq!(presence.known, ["api-claude"]);+ // An older engine keeps no names from new sessions on the person's other machines; nothing is sent when none are.+ let older: Presence = serde_json::from_str(r#"{"sessions":[],"known":["api-claude"]}"#).unwrap();+ assert!(older.kept.is_empty());+ assert!(!serde_json::to_string(&older).unwrap().contains("kept"));+ // Kept names are names like any other a teammate's machine sends.+ let p = tidy_presence(Presence { kept: vec!["<API Claude>".into(), "!!".into()], ..Default::default() });+ assert_eq!(p.kept, ["api-claude"]);+ }}diff --git a/src/render.rs b/src/render.rsindex e5c1d5a..cca9871 100644--- a/src/render.rs+++ b/src/render.rs@@ -238,6 +238,16 @@ pub fn send_result(r: &SendResult) -> String {/// Messages framed for an agent's context: clearly peer input, with what it needs to reply. `agent` is the/// recipient's agent kind, if known; `cli` when it has no Reason Network tools and replies with the CLI.+/// Whether a message comes from a person's terminal (`<person>/terminal`, or `…@<machine>` once it is here).+pub fn from_terminal(from: &str) -> bool {+ without_machine(from).ends_with("/terminal")+}++/// An address without the `@<machine>` it may name.+pub fn without_machine(address: &str) -> &str {+ address.split_once('@').map_or(address, |(a, _)| a)+}+pub fn for_agent(msgs: &[Message], agent: Option<&str>, cli: bool) -> String {let mut out = String::new();for m in msgs {@@ -269,7 +279,7 @@ pub fn for_agent(msgs: &[Message], agent: Option<&str>, cli: bool) -> String {let Some(last) = msgs.last() else { return out };// Every message comes from an agent session (`person/session`).let person = last.from.split_once('/').map_or(last.from.as_str(), |(p, _)| p);- let who = if last.from.ends_with("/terminal") {+ let who = if from_terminal(&last.from) {format!("From {person}, typed in a terminal.")} else {format!("From {person}'s agent.")diff --git a/src/store.rs b/src/store.rsindex 4d8f7dc..ee0f4ad 100644--- a/src/store.rs+++ b/src/store.rs@@ -58,6 +58,18 @@ pub struct Remembered {pub doing: Option<String>,pub tier: Tier,pub last_seen: i64,+ /// Whether it could ever be reached beyond its own hooks (see `Live::attached`).+ pub attached: bool,+}++impl Remembered {+ /// Whether the name stays this session's while it is offline: it is an agent's conversation, by the id its agent+ /// gave it (`<agent>:<id>`), so the same conversation can come back to it, or one of the person's own mailboxes+ /// (`cli:<name>`); and it could be reached while it ran. A session known only by its process (`proc:<pid>`) has+ /// nothing that could come back, and one only its hooks ever knew (a one-shot run) nothing anyone could reach.+ pub fn kept(&self) -> bool {+ self.attached && !self.key.starts_with("proc:")+ }}const SCHEMA: &str = "@@ -96,7 +108,8 @@ CREATE TABLE IF NOT EXISTS sessions (branch TEXT,doing TEXT,tier TEXT NOT NULL,- last_seen INTEGER NOT NULL+ last_seen INTEGER NOT NULL,+ attached INTEGER NOT NULL DEFAULT 1);CREATE INDEX IF NOT EXISTS sessions_key ON sessions (key);CREATE TABLE IF NOT EXISTS counts (@@ -108,7 +121,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";+const SESSION_COLS: &str = "name, key, agent, cwd, repo, branch, doing, tier, last_seen, attached";impl Store {/// The database at `path`, and the folder `inbox` that messages' files are saved in.@@ -137,6 +150,11 @@ impl Store {if !db.prepare("SELECT 1 FROM pragma_table_info('messages') WHERE name = 'files'")?.exists([])? {db.execute("ALTER TABLE messages ADD COLUMN files TEXT", [])?;}+ // Added with names kept for their sessions: whether a session could be reached beyond its own hooks. Sessions+ // remembered from before count as reachable, so their names stay theirs.+ 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", [])?;+ }Ok(Store { db, inbox })}@@ -436,14 +454,25 @@ impl Store {Ok(())}- pub fn upsert_session(&self, s: &Remembered) -> Result<()> {+ /// Remembers a session under its name. A session has one name: if it had another before (its own was taken by a+ /// live session meanwhile), that one goes, and its unread mail comes along to the new one.+ pub fn upsert_session(&self, s: &Remembered, person: &str) -> Result<()> {+ let before: Vec<String> = {+ let mut st = self.db.prepare_cached("SELECT name FROM sessions WHERE key = ?1 AND name != ?2")?;+ st.query_map(params![s.key, s.name], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?+ };+ for old in before {+ self.rename(&old, &s.name, &format!("{person}/{old}"), &format!("{person}/{}", s.name))?;+ }+ // 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)+ "INSERT INTO sessions ({SESSION_COLS}) VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10)ON CONFLICT (name) DO UPDATE SET key = ?2, agent = ?3, cwd = ?4, repo = ?5, branch = ?6,- doing = ?7, tier = ?8, last_seen = ?9"+ doing = ?7, tier = ?8, last_seen = ?9,+ attached = CASE WHEN key = ?2 THEN max(attached, ?10) ELSE ?10 END"),- params![s.name, s.key, s.agent, s.cwd, s.repo, s.branch, s.doing, s.tier.as_str(), s.last_seen],+ params![s.name, s.key, s.agent, s.cwd, s.repo, s.branch, s.doing, s.tier.as_str(), s.last_seen, s.attached],)?;Ok(())}@@ -454,24 +483,38 @@ impl Store {}/// Forgets the sessions not seen since `before`, other than `live` ones and the person's own mailboxes (`cli`), and- /// deletes the mail they never read, so a session that takes the name later doesn't get it (mail held for the- /// person stays theirs to settle).+ /// 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("SELECT name FROM sessions WHERE last_seen < ?1 AND agent != 'cli'")?;- let gone: Vec<String> = st.query_map([before], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?;- for name in gone.iter().filter(|n| !live.contains(n.as_str())) {- let unread = "FROM messages WHERE recipient = ?1 AND read_at IS NULL AND held = 0";- let to = format!("{person}/{name}");- let mut cols = self.db.prepare_cached(&format!("SELECT files {unread} AND files IS NOT NULL"))?;- let cols: Vec<String> = cols.query_map([&to], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?;- self.db.execute(&format!("DELETE {unread}"), [&to])?;- for kept in cols.iter().filter_map(|c| serde_json::from_str::<Kept>(c).ok()) {- if let Some(dir) = self.dir(&kept) {- let _ = std::fs::remove_dir_all(dir);- }+ let mut st = self+ .db+ .prepare_cached(&format!("SELECT {SESSION_COLS} FROM sessions WHERE last_seen < ?1 AND agent != 'cli'"))?;+ 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)?;+ }+ Ok(())+ }++ /// Forgets one session, with the mail it never read and that mail's files. Mail held for the person goes too when+ /// the name was kept for the session: it was that conversation's, never the next one's. Otherwise it stays the+ /// person's to settle, for whoever has the name.+ pub fn forget_session(&self, r: &Remembered, person: &str) -> Result<()> {+ let unread = if r.kept() {+ "FROM messages WHERE recipient = ?1 AND read_at IS NULL"+ } else {+ "FROM messages WHERE recipient = ?1 AND read_at IS NULL AND held = 0"+ };+ let name = r.name.as_str();+ let to = format!("{person}/{name}");+ let mut cols = self.db.prepare_cached(&format!("SELECT files {unread} AND files IS NOT NULL"))?;+ let cols: Vec<String> = cols.query_map([&to], |r| r.get(0))?.collect::<rusqlite::Result<_>>()?;+ self.db.execute(&format!("DELETE {unread}"), [&to])?;+ for kept in cols.iter().filter_map(|c| serde_json::from_str::<Kept>(c).ok()) {+ if let Some(dir) = self.dir(&kept) {+ let _ = std::fs::remove_dir_all(dir);}- self.db.execute("DELETE FROM sessions WHERE name = ?1", [name])?;}+ self.db.execute("DELETE FROM sessions WHERE name = ?1", [name])?;Ok(())}@@ -534,6 +577,7 @@ fn remembered(r: &Row) -> rusqlite::Result<Remembered> {doing: r.get(6)?,tier: Tier::parse(&r.get::<_, String>(7)?),last_seen: r.get(8)?,+ attached: r.get(9)?,})}@@ -664,7 +708,7 @@ mod tests {#[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.)+ // (Not one that is live, nor the person's own mailbox.)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 {@@ -677,14 +721,16 @@ mod tests {doing: None,tier: Tier::Push,last_seen,+ attached: true,};for s in [session("gone", "claude-code", 0),session("recent", "claude-code", 2 * day),session("still-up", "claude-code", 0),session("terminal", "cli", 0),+ Remembered { key: "proc:7".into(), ..session("no-id", "zed", 0) },] {- store.upsert_session(&s).unwrap();+ store.upsert_session(&s, "lars").unwrap();}let to = |id: &str, name: &str| Message {id: id.into(),@@ -705,13 +751,76 @@ mod tests {store.insert(&mut to("2", "recent"), false).unwrap();store.insert(&mut to("3", "terminal"), false).unwrap();store.insert(&mut to("4", "gone"), true).unwrap();+ store.insert(&mut to("5", "no-id"), true).unwrap();store.forget_sessions(day + 1, &HashSet::from(["still-up"]), "lars").unwrap();let names: Vec<String> = store.sessions().unwrap().into_iter().map(|s| s.name).collect();assert_eq!(names, ["recent", "still-up", "terminal"]);assert_eq!(store.unread_count("lars/gone").unwrap(), 0);assert_eq!(store.unread_count("lars/recent").unwrap(), 1);assert_eq!(store.unread_count("lars/terminal").unwrap(), 1);- assert_eq!(store.held().unwrap().len(), 1);+ // Mail held for a conversation goes with it; for a session without an id it stays the person's to settle.+ assert_eq!(store.held().unwrap().iter().map(|m| m.id.as_str()).collect::<Vec<_>>(), ["5"]);+ }++ #[test]+ fn a_session_has_one_name_and_one_an_older_engine_left_under_two_is_folded_into_its_latest() {+ let store = Store::open(Path::new(":memory:"), temp_inbox()).unwrap();+ let session = |name: &str, last_seen: i64| Remembered {+ name: name.into(),+ key: "claude-code:a".into(),+ agent: "claude-code".into(),+ cwd: "~".into(),+ repo: None,+ branch: None,+ doing: None,+ tier: Tier::Push,+ last_seen,+ attached: true,+ };+ // 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)] {+ let s = session(name, seen);+ store+ .db+ .execute(+ &format!(+ "INSERT INTO sessions ({SESSION_COLS}) VALUES (?1, ?2, ?3, ?4, NULL, NULL, NULL, ?5, ?6, 1)"+ ),+ params![s.name, s.key, s.agent, s.cwd, s.tier.as_str(), s.last_seen],+ )+ .unwrap();+ }+ for (id, name) in [("1", "api-claude"), ("2", "api-claude-2")] {+ store.insert(&mut message(id, &format!("lars/{name}")), false).unwrap();+ }+ assert_eq!(store.session_by_key("claude-code:a").unwrap().unwrap().name, "api-claude-2");+ store.upsert_session(&session("api-claude-2", 3), "lars").unwrap();+ let names: Vec<String> = store.sessions().unwrap().into_iter().map(|s| s.name).collect();+ assert_eq!(names, ["api-claude-2"]);+ assert_eq!(store.unread_count("lars/api-claude-2").unwrap(), 2);+ // Under a new name, the old one goes, and its mail comes along.+ store.upsert_session(&session("auth", 4), "lars").unwrap();+ let names: Vec<String> = store.sessions().unwrap().into_iter().map(|s| s.name).collect();+ assert_eq!(names, ["auth"]);+ assert_eq!(store.unread_count("lars/auth").unwrap(), 2);+ }++ fn message(id: &str, to: &str) -> Message {+ Message {+ id: id.into(),+ from: "sven/claude".into(),+ from_agent: None,+ from_repo: None,+ to: to.into(),+ via: None,+ reply_to: None,+ body: "hi".into(),+ wake: false,+ notify: false,+ sent_at: 0,+ approval: None,+ files: Vec::new(),+ }}fn temp_inbox() -> PathBuf {@@ -880,9 +989,10 @@ mod tests {doing: None,tier: Tier::Push,last_seen: 0,+ attached: true,};- store.upsert_session(&session("gone")).unwrap();- store.upsert_session(&session("api")).unwrap();+ store.upsert_session(&session("gone"), "lars").unwrap();+ store.upsert_session(&session("api"), "lars").unwrap();let mut gone = with_files("01GONE", "lars/gone");store.insert(&mut gone, false).unwrap();let mut stored = HashMap::new();diff --git a/tests/e2e/names.py b/tests/e2e/names.pynew file mode 100644index 0000000..02ece8e--- /dev/null+++ b/tests/e2e/names.py@@ -0,0 +1,251 @@+"""A session's name stays with its conversation across daemon restarts, here and on the person's other machine.++ cargo build && [REASON_NETWORK_OLD_BIN=<an older reason-network, e.g. 0.12.6>] \+ env -u CLAUDE_CODE_MESSAGING_SOCKET python3 tests/e2e/names.py++Needs internet for the other machines (iroh relays/discovery). With an older build, it also checks terminals with an+older engine in the team.+"""+import json, os, re, subprocess, sys, tempfile, time+sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from proofs import TRUST, proof, serve_relay_lists++ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))+BIN = os.path.join(ROOT, "target", "debug", "reason-network")+D = tempfile.mkdtemp(prefix="reason-network-names-")+MACHINE = {"one": "laptop", "two": "desk", "three": "pad", "olga": "oldbox"}+OLD = os.environ.get("REASON_NETWORK_OLD_BIN")+FAKE_BIN = os.path.join(D, "bin")+UNEXPECTED = os.path.join(D, "unexpected.log")+RELAYS_URL = serve_relay_lists({"all": ["sfo1", "iad1", "fra1", "sin1"]}) + "/all.json"+PROJ = os.path.join(D, "proj")+PROJ2 = os.path.join(D, "batch")+results = []+++def check(name, ok, detail=""):+ results.append(ok)+ print(f"{'PASS' if ok else 'FAIL'}: {name}" + ("" if ok else f"\n {detail}"))+++def env(who, **extra):+ e = {k: v for k, v in os.environ.items() if not k.startswith("CLAUDE")}+ e.update(HOME=os.path.join(D, "home"), PATH=FAKE_BIN + os.pathsep + os.environ["PATH"], CLAUDE_CONFIG_DIR=os.path.join(D, "claude"),+ REASON_NETWORK_HOME=os.path.join(D, who), REASON_NETWORK_MACHINE=MACHINE[who], REASON_NETWORK_NO_MDNS="1",+ REASON_NETWORK_NO_SERVICE="1", REASON_NETWORK_NO_UPDATE="1", REASON_NETWORK_NO_TRAY="1",+ REASON_NETWORK_TRUST_KEYS=TRUST, REASON_NETWORK_RELAYS_URL=RELAYS_URL,+ REASON_NETWORK_OSASCRIPT_BIN=os.path.join(FAKE_BIN, "osascript"), REASON_NETWORK_CODEX_BIN=os.path.join(FAKE_BIN, "codex"))+ e.update(extra)+ return e+++def cli(who, *args, **extra):+ exe = OLD if who == "olga" else BIN+ r = subprocess.run([exe, *args], env=env(who, **extra), capture_output=True, text=True, timeout=90, cwd=PROJ)+ return (r.stdout + r.stderr).strip()+++def claude(who, event, sid, cwd=PROJ):+ """A hook of a Claude Code session `sid` working in `cwd`; what it prints."""+ payload = {"session_id": sid, "cwd": cwd}+ r = subprocess.run([BIN, "hook", "claude-code", event], env=env(who), capture_output=True, text=True,+ input=json.dumps(payload), timeout=30, cwd=cwd)+ return r.stdout.strip()+++def you_are(out):+ m = re.search(r"you are (\S+?)\.", out)+ return m.group(1) if m else out+++def name_of(who, sid):+ """The address of Claude Code session `sid`, as `status` run in its shell says."""+ out = cli(who, "status", CLAUDECODE="1", CLAUDE_CODE_SESSION_ID=sid)+ m = re.search(r"You are (\S+?)\.$", out)+ return m.group(1) if m else out+++class Mcp:+ """An agent's MCP server: Claude Code's, with its session id, or a client's that gives none."""++ def __init__(self, who, client, **extra):+ self.p = subprocess.Popen([BIN, "mcp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL,+ env=env(who, **extra), cwd=PROJ, text=True, bufsize=1)+ self.id = 0+ self.req("initialize", {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": client, "version": "1"}})+ self.p.stdin.write(json.dumps({"jsonrpc": "2.0", "method": "notifications/initialized"}) + "\n")++ def req(self, method, params):+ self.id += 1+ self.p.stdin.write(json.dumps({"jsonrpc": "2.0", "id": self.id, "method": method, "params": params}) + "\n")+ while True:+ msg = json.loads(self.p.stdout.readline())+ if msg.get("id") == self.id:+ return msg++ def tool(self, name, args):+ res = self.req("tools/call", {"name": name, "arguments": args}).get("result", {})+ return "\n".join(c.get("text", "") for c in res.get("content", []))++ def close(self):+ self.p.stdin.close()+ self.p.wait(5)+++def until(fn, ok, secs=45):+ deadline = time.time() + secs+ while True:+ out = fn()+ if ok(out) or time.time() > deadline:+ return out+ time.sleep(1)+++os.makedirs(FAKE_BIN)+os.makedirs(os.path.join(D, "home"))+os.makedirs(os.path.join(D, "claude", "sessions"))+os.makedirs(PROJ)+for name in ("open", "xdg-open", "osascript", "notify-send", "codex"):+ with open(os.path.join(FAKE_BIN, name), "w") as f:+ f.write(f'#!/bin/sh\nprintf "{name} %s\\n" "$*" >> {UNEXPECTED}\n')+ os.chmod(os.path.join(FAKE_BIN, name), 0o755)++try:+ ep = {w: cli(w, "endpoint") for w in ("one", "two")}+ out = cli("one", "init", "names", "--proof", proof("u_lars", "lars", ep["one"]), "--no-setup")+ check("a team, signed in", "You are lars on laptop." in out, out)++ # --- one machine: restarts ---+ # Two Claude Code conversations, each with its hooks and its MCP server (which Claude Code gives the session id).+ servers = {}+ for sid in ("conv-a", "conv-b"):+ claude("one", "session-start", sid)+ servers[sid] = Mcp("one", "claude-code", CLAUDE_CODE_SESSION_ID=sid)+ servers[sid].tool("list_team", {})+ a, b = name_of("one", "conv-a"), name_of("one", "conv-b")+ check("two Claude Code conversations in one folder", (a, b) == ("lars/proj-claude", "lars/proj-claude-2"), (a, b))+ # Both end (Claude Code restarts), and so does the daemon.+ for sid, server in servers.items():+ server.close()+ claude("one", "session-end", sid)+ out = cli("one", "send", "proj-claude", "bug report for conversation A")+ check("mail for the offline conversation waits for it, and the sender is told so",+ "it reaches that session when it's back" in out and "a new session that takes this name" not in out, out)+ cli("one", "stop")+ # After the restart a new conversation in the same folder registers first.+ c = claude("one", "session-start", "conv-c")+ check("…a new conversation after the restart gets the next free name", you_are(c) == "lars/proj-claude-3", c)+ check("…and none of the other's mail", "bug report" not in c, c)+ back = claude("one", "session-start", "conv-a")+ check("the first conversation comes back as itself", name_of("one", "conv-a") == "lars/proj-claude", name_of("one", "conv-a"))+ check("…and its mail reaches it", "bug report for conversation A" in back, back)+ out = claude("one", "session-start", "conv-b")+ check("so does the second, whose name was kept through the restart", you_are(out) == "lars/proj-claude-2", out)+ out = cli("one", "who")+ check("who lists each under its own name", all(n in out for n in ("proj-claude ", "proj-claude-2", "proj-claude-3")), out)++ # Renames: never into a name kept for a conversation that is offline.+ claude("one", "session-end", "conv-a")+ out = cli("one", "status", "--name", "proj-claude", CLAUDECODE="1", CLAUDE_CODE_SESSION_ID="conv-c")+ check("a rename into the offline conversation's name is refused",+ "'proj-claude' belongs to a session that is offline" in out and "pick another name" in out, out)+ out = cli("one", "status", "--name", "auth", CLAUDECODE="1", CLAUDE_CODE_SESSION_ID="conv-c")+ check("…another name is fine", "You are lars/auth." in out, out)+ out = cli("one", "listen", "--as", "proj-claude", "--wait", "0")+ check("listen --as the offline conversation's name gets the next free one", "You are lars/proj-claude-3." in out, out)++ # A headless run only its hooks saw couldn't be messaged: its name isn't kept from the next one.+ os.makedirs(PROJ2)+ first = you_are(claude("one", "session-start", "run-1", cwd=PROJ2))+ claude("one", "session-end", "run-1", cwd=PROJ2)+ second = you_are(claude("one", "session-start", "run-2", cwd=PROJ2))+ claude("one", "session-end", "run-2", cwd=PROJ2)+ check("a one-shot run's name goes to the next run, not a suffix", first == second == "lars/batch-claude", (first, second))++ # Gemini is reached through its hooks only: once they hand it mail, its name is kept like any other.+ def gemini(event, sid):+ r = subprocess.run([BIN, "hook", "gemini", event], env=env("one"), capture_output=True, text=True,+ input=json.dumps({"session_id": sid, "cwd": PROJ}), timeout=30, cwd=PROJ)+ return r.stdout.strip()+ gemini("session-start", "g1")+ g1 = until(lambda: cli("one", "who"), lambda o: "proj-gemini" in o)+ cli("one", "send", "proj-gemini", "for gemini g1")+ got = gemini("stop", "g1")+ check("a Gemini session gets mail through its hooks", "for gemini g1" in got, got)+ gemini("session-end", "g1")+ cli("one", "send", "proj-gemini", "more for g1")+ gemini("session-start", "g2")+ out = cli("one", "who")+ check("…and once it's gone, a new Gemini session there gets the next name", "proj-gemini-2" in out, out)+ got = gemini("stop", "g1")+ check("…while g1, back, is proj-gemini with what came meanwhile", "more for g1" in got, got)++ # An agent that gives no session id: as before, the next session in its place takes the name and its mail.+ zed = Mcp("one", "zed")+ out = zed.tool("list_team", {})+ check("an MCP client without session ids registers", "proj-zed" in out, out)+ zed.close()+ time.sleep(1)+ out = cli("one", "send", "proj-zed", "for whoever runs zed here")+ check("…its mail's note says a new session there gets it", "a new session that takes this name gets the mail" in out, out)+ zed = Mcp("one", "zed")+ out = zed.tool("check_inbox", {})+ check("…and one does", "for whoever runs zed here" in out, out)+ zed.close()++ # --- two machines of the same person ---+ link = re.search(r"https://\S+/join/#\S+", cli("one", "link")).group(0)+ out = cli("two", "join", link, "--proof", proof("u_lars", "lars", ep["two"]), "--no-setup")+ check("lars's second computer joins", "Joined team names as lars on desk." in out, out)+ out = until(lambda: cli("two", "who"), lambda o: "proj-claude-2" in o)+ check("the second computer sees the first's sessions", "proj-claude-2" in out, out)+ # Its presence once proj-claude-2 is offline too: both names are kept on the first computer.+ claude("one", "session-end", "conv-b")+ out = until(lambda: cli("two", "who"), lambda o: "proj-claude-2" not in o)+ check("…and when one goes offline", "auth" in out and "proj-claude-2" not in out, out)+ d = claude("two", "session-start", "conv-d")+ check("a new conversation there gets none of the names kept on the first", you_are(d) not in ("lars/proj-claude", "lars/proj-claude-2"), d)+ # Each computer has its own terminal, whatever the other's is doing.+ out = cli("one", "listen", "--as", "terminal", "--wait", "0")+ check("the first computer's terminal", "You are lars/terminal." in out, out)+ until(lambda: cli("two", "who"), lambda o: re.search(r"terminal\s+cli", o) is not None)+ out = cli("two", "listen", "--as", "terminal", "--wait", "0")+ check("…and the second's, with the first's live: no suffix", "You are lars/terminal." in out, out)+ out = cli("two", "send", "lars/proj-claude", "from the desk")+ check("mail from there to the kept name goes to the first computer, for its conversation",+ "it reaches that session when it's back" in out, out)+ back = until(lambda: claude("one", "session-start", "conv-a"), lambda o: "from the desk" in o, secs=20)+ check("…which gets it when it's back, as itself", "from the desk" in back and name_of("one", "conv-a") == "lars/proj-claude", back)+ check("…from the desk's terminal, by name", 'send_message to "lars/terminal@desk"' in back, back)+ out = cli("one", "send", "lars/terminal@desk", "--from", "proj-claude", "got it, desk")+ check("a reply to it goes to that computer", "→ lars/terminal" in out and "refused" not in out, out)+ out = until(lambda: cli("two", "listen", "--as", "terminal", "--wait", "5"), lambda o: "got it, desk" in o, secs=30)+ check("…and its terminal reads it", "got it, desk" in out, out)+ out = cli("one", "listen", "--as", "terminal", "--wait", "0")+ check("…not this one's", "got it, desk" not in out, out)++ # An older engine can't tell two terminals of one person apart in a reply: while one is in the team, a second+ # terminal on at once is `terminal-2`, as before.+ if OLD:+ out = cli("olga", "join", link, "--as", "olga", "--no-setup")+ check("an older engine joins", "Joined team names as olga on oldbox." in out, out)+ until(lambda: cli("two", "team"), lambda o: re.search(r"olga\s+oldbox\s+(direct|relay)", o) is not None)+ out = until(lambda: cli("two", "listen", "--as", "terminal", "--wait", "0"), lambda o: "terminal-2" in o)+ check("…so the second computer's terminal, used again, is terminal-2", "You are lars/terminal-2." in out, out)+ # With the older machine off, a new computer of lars's joins: never having heard from it, it still counts it.+ cli("olga", "stop")+ until(lambda: cli("one", "team"), lambda o: not re.search(r"olga\s+oldbox\s+(direct|relay)", o))+ link = re.search(r"https://\S+/join/#\S+", cli("one", "link")).group(0)+ out = cli("three", "join", link, "--proof", proof("u_lars", "lars", cli("three", "endpoint")), "--no-setup")+ check("a third computer joins while the older one is off", "Joined team names as lars on pad." in out, out)+ until(lambda: cli("three", "who"), lambda o: "terminal-2" in o)+ out = cli("three", "listen", "--as", "terminal", "--wait", "0")+ check("…and its terminal takes the next free name", "You are lars/terminal-3." in out, out)+finally:+ for w in MACHINE:+ if w != "olga" or OLD:+ subprocess.run([OLD if w == "olga" else BIN, "stop"], env=env(w), capture_output=True, timeout=30)+log = open(UNEXPECTED).read() if os.path.exists(UNEXPECTED) else ""+check("nothing opened a browser or reached the real notifications", log == "", log)+print(f"\n{sum(results)}/{len(results)} checks passed (state in {D})")+raise SystemExit(0 if all(results) else 1)diff --git a/tests/e2e/two_machines.py b/tests/e2e/two_machines.pyindex a2107f9..5ff5bed 100644--- a/tests/e2e/two_machines.py+++ b/tests/e2e/two_machines.py@@ -332,7 +332,7 @@ r = subprocess.run([BIN, "send", "alice/work-codex", "from alex's terminal in thcapture_output=True, text=True, timeout=90)check("the person's own terminal there still sends", "→ alice/work-codex" in r.stdout, r.stdout + r.stderr)out = codex.tool("check_inbox", {}, meta)-check("…as alex/terminal", 'from="alex/terminal"' in out and "in the folder that is off" in out, out)+check("…as alex/terminal, from alex's laptop", 'from="alex/terminal@laptop"' in out and "in the folder that is off" in out, out)with open(os.path.join(PRIVATE, "notes.txt"), "w") as f:f.write("private\n")agent_shell = dict(person, CLAUDECODE="1", CLAUDE_CODE_SESSION_ID="44444444-dddd", CLAUDE_PROJECT_DIR=PRIVATE)@@ -376,7 +376,7 @@ 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)+check("remote message arrives in codex inbox, from alex's terminal on his laptop", 'from="alex/terminal@laptop"' in out and "hello from alex's terminal" in out, out)out = codex.tool("check_inbox", {}, meta)check("…and is gone once read", out.startswith("No messages."), out)out = cli("alice", "send", "alex", "dinner at 8?")