Skip to content

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

Agents never get the team link, and a teammate's message keeps the send limits (#142)

Lars Talian10c78ef88ada
diff --git a/Cargo.lock b/Cargo.lock
index 9ac1fb0..da9362c 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2757,7 +2757,7 @@ dependencies = [
[[package]]
name = "reason-network"
-version = "0.12.11"
+version = "0.12.12"
dependencies = [
"anyhow",
"blake3",
diff --git a/Cargo.toml b/Cargo.toml
index 2bc184a..ed757b7 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -1,6 +1,6 @@
[package]
name = "reason-network"
-version = "0.12.11"
+version = "0.12.12"
edition = "2024"
description = "Reason Network: the team directory and message bus behind reason network, for coding agents across machines"
license = "MIT OR Apache-2.0"
diff --git a/DESIGN.md b/DESIGN.md
index 100be54..b1b89dc 100644
--- a/DESIGN.md
+++ b/DESIGN.md
@@ -159,7 +159,8 @@ That is the "HTTPS and local network, MagicDNS style" requirement with one stack
all machines converge on the same roster.
- *members*: each machine's latest entry (person, machine name, active or removed), last writer wins.
- *invites*: `hash(secret)`, expiry, optional "for this person's own machine", and who used it.
-- *meta*: team name and optional relay.
+- *meta*: team name and optional relay. The name is kept whole, but shown (and carried in links) cut to 60
+ characters.
Any member may invite and remove. No machine can admit itself; it can sign its own departure. Invites die with
the machine that made them and are single use. Entries stamped more than a day ahead are refused. A removed
@@ -178,7 +179,9 @@ sign in with Reason, and their computer joins with a sign-in proof (see below).
without signing in. A code can't show the joiner which team answers it (whoever listens on
the code's key knows the code, so could make up a team), so a sign-in never joins with one: only with a link, which
names the team. Links are `rn1-…` (older builds wrote `tincan1…`, with the same payload; both are read). After `init`
-and `join` the CLI prints the invite line, `Join the Reason Network: <team link>`, and agents get it from `list_team`.
+and `join` the CLI prints the invite line, `Join the Reason Network: <team link>`, and `link` (or `invite`) shows it
+again. Agents never get it from `list_team`, `who` or `team --json`: a reusable way in has no place in an agent's
+context, which ends up in its provider's logs; `list_team` tells them their user runs `reason-network invite`.
**Sign-in proofs.** Signed in with Reason, a machine carries a proof: a compact JWS from Reason's cloud-access
issuer (`iss` `https://reasonmachines.com/network`), RS256 only, saying this endpoint id belongs to account `sub`,
@@ -213,7 +216,9 @@ protected on that machine only.
**Messages.** `Envelope{id: ulid, from, to, reply_to, thread, body, sent_at}` sent directly to each target
machine on ALPN `tincan/1`, length-prefixed JSON frames. The receiver persists, then acks with
`stored | delivered | held | refused`; later receipts (`delivered`, `read`) flow back. The sender keeps an
-outbox and retries when the target machine comes back. Mail for an offline session waits in the target
+outbox and retries when the target machine comes back. A message's text is at most 64 KB; the receiver holds a
+teammate's message to that as well (and its files to theirs, below): one past it is refused, not retried, and none of it
+is kept. Mail for an offline session waits in the target
machine's mailbox under the session name, for a day: a session gone longer is forgotten, with the mail it never
read (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). Until then the mail waits for that session, and the
@@ -371,7 +376,9 @@ session's title (Claude Code's `ai-title` transcript entries, Codex's thread nam
(Claude Code's `~/.claude/tasks/<session>/`, TodoWrite, Codex's `update_plan`, Gemini's `write_todos`,
Cursor's `todo_write`, opencode 1.x's todos). Transcripts come from hooks (`transcript_path`) or, for Claude Code,
from its session id; only what was appended since the last look is read. A Claude Code session renamed with
-`/rename` keeps that name on Reason Network.
+`/rename` keeps that name on Reason Network. A team link in a title or task (a first prompt that was a pasted invite
+line) is taken out before it is kept or shared, and shows as `(team link)`; one from a teammate on an earlier build is
+taken out when it arrives.
Incoming messages are framed as peer input, never as the user:
diff --git a/src/daemon/directory.rs b/src/daemon/directory.rs
index 6d51561..c030bec 100644
--- a/src/daemon/directory.rs
+++ b/src/daemon/directory.rs
@@ -282,7 +282,8 @@ impl Daemon {
let mut row = self.row(&r.name, &r.agent, &r.cwd, Some(&git));
row.status = "offline".into();
row.since = Some(r.last_seen);
- row.doing = r.doing.clone();
+ // Kept by a build that left team links in.
+ row.doing = r.doing.as_deref().map(crate::team::without_tickets);
row.tier = r.tier;
row.unread = g.store.unread_count(&row.address)?;
rows.push(row);
@@ -335,7 +336,6 @@ impl Daemon {
machine: self.machine.clone(),
machines,
sessions: rows,
- invite_line: self.current_link().map(|l| crate::invite_line(&l)),
})
}
@@ -582,6 +582,48 @@ mod tests {
assert_eq!(live, ["claude-code:inner", "claude-code:outer"]);
}
+ #[tokio::test]
+ async fn the_directory_never_carries_the_team_link() {
+ let cfg = crate::config::Config { person: Some("alex".into()), ..Default::default() };
+ let d = Arc::new(super::super::test_daemon(cfg));
+ let mut team = crate::team::TeamState::found("acme", &d.person, &d.machine, &d.key);
+ team.new_link(&d.key);
+ let secret = team.link_secret().expect("a team link").to_string();
+ d.inner.lock().unwrap().team = Some(team);
+ let ticket = d.link(false).await.unwrap().ticket;
+ let dir = d.who(None, None, false).await.unwrap();
+ // `list_team`; `who --json` (an agent's shell, and the Reason CLI's relay for hosted assistants); `who`.
+ let json = serde_json::to_string(&dir).unwrap();
+ let agent = crate::render::directory_for_agent(&dir);
+ let person = crate::render::directory(&dir, false, crate::render::Paint::PLAIN);
+ for out in [&json, &agent, &person] {
+ assert!(!out.contains("rn1-") && !out.contains(&ticket) && !out.contains(&secret), "{out}");
+ }
+ assert!(agent.contains("your user runs `reason-network invite`"), "{agent}");
+ }
+
+ #[tokio::test]
+ async fn a_long_team_name_is_shown_cut_and_given_whole_to_the_reason_cli() {
+ let cfg = crate::config::Config { person: Some("alex".into()), ..Default::default() };
+ let d = Arc::new(super::super::test_daemon(cfg));
+ let long = format!("acme {}", "y".repeat(200));
+ let mut team = crate::team::TeamState::found(&long, &d.person, &d.machine, &d.key);
+ team.new_link(&d.key);
+ d.inner.lock().unwrap().team = Some(team);
+ let dir = d.who(None, None, false).await.unwrap();
+ let shown = dir.team.clone().unwrap();
+ assert!(shown.chars().count() == 60 && shown.starts_with("acme yyy") && shown.ends_with('…'), "{shown}");
+ let agent = crate::render::directory_for_agent(&dir);
+ let t = d.team_info().unwrap();
+ let person = crate::render::team(&t);
+ for out in [&agent, &person] {
+ assert!(out.contains(&shown) && !out.contains(&"y".repeat(60)), "{out}");
+ }
+ // The Reason CLI compares the name with the ones it kept: it gets it whole, as before.
+ assert_eq!((t.name.as_str(), t.team_name.as_str()), (long.as_str(), long.as_str()));
+ assert_eq!(d.link(false).await.unwrap().team, long);
+ }
+
#[test]
fn each_machine_answers_for_its_own_terminal() {
let cfg = crate::config::Config { person: Some("alex".into()), ..Default::default() };
diff --git a/src/daemon/mail.rs b/src/daemon/mail.rs
index 928d646..af08144 100644
--- a/src/daemon/mail.rs
+++ b/src/daemon/mail.rs
@@ -23,6 +23,7 @@ use std::{
};
use ulid::Ulid;
+/// The most text a message carries, in bytes. A teammate's machine is held to it too (see [`clean`]).
const MAX_BODY: usize = 64 * 1024;
/// Messages per minute accepted from one teammate's machine; more are deferred, not dropped.
const RATE_LIMIT: usize = 60;
@@ -126,14 +127,7 @@ impl Daemon {
if notify && is_group(to) {
bail!("notify is for one session or one person, not a group");
}
- if body.len() > MAX_BODY {
- // A path means nothing on the recipient's computer.
- bail!(
- "message is {} KB; the limit is {} KB (send a small text file with `files`, or a link)",
- body.len().div_ceil(1024),
- MAX_BODY / 1024
- );
- }
+ fits(body)?;
let files = files::check(files)?;
let now = util::now_ms();
let net = self.net();
@@ -784,6 +778,19 @@ pub(super) fn approval_holds(a: &Signed<Approval>, team: &str, peer: &EndpointId
size <= 2000 && a.by == *peer && b.approver == sender && b.asker == to && a.verify(team, "approval")
}
+/// A message's text within [`MAX_BODY`].
+fn fits(body: &str) -> Result<()> {
+ if body.len() > MAX_BODY {
+ // A path means nothing on the recipient's computer.
+ bail!(
+ "message is {} KB; the limit is {} KB (send a small text file with `files`, or a link)",
+ body.len().div_ceil(1024),
+ MAX_BODY / 1024
+ );
+ }
+ Ok(())
+}
+
/// Validates a message from a peer and strips its metadata down to safe characters.
fn clean(m: Message) -> Result<Message> {
let ok = |s: &str, extra: &str| {
@@ -794,6 +801,8 @@ fn clean(m: Message) -> Result<Message> {
if !canonical || !ok(&m.from, "-/") || !ok(&m.to, "-/") {
bail!("malformed message");
}
+ // Held to what its sender's machine checks (as are its files, below): past that, it is refused and nothing kept.
+ fits(&m.body)?;
Ok(Message {
from_agent: m.from_agent.as_deref().and_then(|s| tidy(s, "-", 30)),
from_repo: m.from_repo.as_deref().and_then(|s| tidy(s, "-_./", 100)),
@@ -1208,4 +1217,80 @@ mod tests {
let wire = serde_json::to_string(&msg("port = 1")).unwrap();
assert_eq!(serde_json::from_str::<Older>(&wire).unwrap().body, "the config");
}
+
+ /// A daemon for alex, with bob's machine on the team and a session here. Returns it, bob's key and the session.
+ fn with_teammate() -> (Arc<Daemon>, SecretKey, String) {
+ 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;
+ (d, bob, to)
+ }
+
+ fn from_bob(to: &str, body: String, files: Vec<Attachment>) -> Message {
+ Message {
+ id: Ulid::generate().to_string(),
+ from: "bob/web".into(),
+ from_agent: None,
+ from_repo: None,
+ to: to.into(),
+ via: None,
+ reply_to: None,
+ body,
+ wake: false,
+ notify: false,
+ sent_at: 0,
+ approval: None,
+ files,
+ }
+ }
+
+ /// Takes `msg` from bob's machine: its error, if refused, after checking nothing of it was kept.
+ fn refused(d: &Arc<Daemon>, bob: &SecretKey, to: &str, msg: Message) -> String {
+ let id = msg.id.clone();
+ let e = d.receive(bob.public(), msg).expect_err("refused").to_string();
+ let g = d.inner.lock().unwrap();
+ assert!(!g.store.has(&id).unwrap() && g.store.unread(to).unwrap().is_empty(), "kept: {e}");
+ e
+ }
+
+ #[test]
+ fn a_teammates_message_is_held_to_the_size_limit_it_was_sent_under() {
+ let (d, bob, to) = with_teammate();
+ // Past the limit (an engine changed to skip its own check): refused, and none of it kept or shown.
+ let e = refused(&d, &bob, &to, from_bob(&to, "x".repeat(MAX_BODY + 1), Vec::new()));
+ assert_eq!(e, "message is 65 KB; the limit is 64 KB (send a small text file with `files`, or a link)");
+ let e = refused(&d, &bob, &to, from_bob(&to, "x".repeat(4 << 20), Vec::new()));
+ assert!(e.starts_with("message is 4096 KB; the limit is 64 KB"), "{e}");
+ // At the limit, as an honest engine may send it: taken as before.
+ let (state, _) = d.receive(bob.public(), from_bob(&to, "x".repeat(MAX_BODY), Vec::new())).unwrap();
+ assert_eq!(state, "queued");
+ let got = d.inner.lock().unwrap().store.unread(&to).unwrap();
+ assert_eq!(got.iter().map(|m| m.body.len()).collect::<Vec<_>>(), [MAX_BODY]);
+ }
+
+ #[test]
+ fn a_teammates_files_are_held_to_the_limits_they_were_sent_under() {
+ use files::{MAX_FILE, MAX_FILES, MAX_TOTAL};
+ let (d, bob, to) = with_teammate();
+ let file =
+ |i: usize, bytes: usize| Attachment { name: format!("{i}.txt"), content: "x".repeat(bytes), path: None };
+ let msg = |files: Vec<Attachment>| from_bob(&to, "the logs".into(), files);
+ let e = refused(&d, &bob, &to, msg((0..=MAX_FILES).map(|i| file(i, 1)).collect()));
+ assert_eq!(e, format!("{} files; a message carries at most {MAX_FILES}", MAX_FILES + 1));
+ let e = refused(&d, &bob, &to, msg(vec![file(0, MAX_FILE + 1)]));
+ assert!(e.starts_with("0.txt is 257 KB; a file can be at most 256 KB"), "{e}");
+ let e = refused(&d, &bob, &to, msg(vec![file(0, MAX_FILE), file(1, MAX_FILE), file(2, 1)]));
+ assert!(e.starts_with("the files come to more than 512 KB"), "{e}");
+ // The most an honest engine sends in one message: the most text, the most files, as many bytes as files carry.
+ let mut most: Vec<Attachment> = (0..MAX_FILES - 2).map(|i| file(i, 0)).collect();
+ most.extend([file(8, MAX_FILE), file(9, MAX_TOTAL - MAX_FILE)]);
+ let (state, _) = d.receive(bob.public(), from_bob(&to, "x".repeat(MAX_BODY), most)).unwrap();
+ assert_eq!(state, "queued");
+ let got = d.inner.lock().unwrap().store.unread(&to).unwrap();
+ assert_eq!((got.len(), got[0].body.len(), got[0].files.len()), (1, MAX_BODY, MAX_FILES));
+ }
}
diff --git a/src/daemon/reason.rs b/src/daemon/reason.rs
index 8a1a626..057f192 100644
--- a/src/daemon/reason.rs
+++ b/src/daemon/reason.rs
@@ -122,7 +122,7 @@ impl Daemon {
let Some(id) = s["session_id"].as_str().or(s["id"].as_str()) else { continue };
let key = format!("reason:{id}");
let text = |k: &str| s[k].as_str().filter(|v| !v.is_empty()).map(str::to_string);
- let title = text("title");
+ let title = text("title").map(|t| crate::team::without_tickets(&t));
seen.insert(key.clone());
if !self.inner.lock().unwrap().live.contains_key(&key) {
let git = GitInfo { root: None, repo: text("repo"), branch: text("branch") };
@@ -208,13 +208,18 @@ mod tests {
impl Stub {
fn new(narrow_err: &str, plain_err: Option<&str>) -> Stub {
- let dir = std::env::temp_dir().join(format!("reason-network-reason-{}", ulid::Ulid::generate()));
- std::fs::create_dir_all(&dir).unwrap();
- let (bin, calls) = (dir.join("reason"), dir.join("calls"));
let plain = match plain_err {
Some(e) => format!("echo '{e}' >&2; exit 1"),
None => r#"echo '{"items":[{"session_id":"r-1","status":"running","title":"Fix flaky billing test","finished_at":null,"is_archived":false}]}'"#.into(),
};
+ Stub::running(narrow_err, plain)
+ }
+
+ /// The same, with the plain list running `plain`.
+ fn running(narrow_err: &str, plain: String) -> Stub {
+ let dir = std::env::temp_dir().join(format!("reason-network-reason-{}", ulid::Ulid::generate()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let (bin, calls) = (dir.join("reason"), dir.join("calls"));
let script = format!(
"#!/bin/sh\necho \"$*\" >> '{}'\ncase \" $* \" in *' --fields '*) echo '{narrow_err}' >&2; exit 1;; esac\n{plain}\n",
calls.display()
@@ -257,6 +262,18 @@ mod tests {
assert!(d.inner.lock().unwrap().live.contains_key("reason:r-1"));
}
+ #[tokio::test]
+ async fn a_reason_session_titled_with_an_invite_line_shows_it_without_the_link() {
+ let d = Arc::new(super::super::test_daemon(Default::default()));
+ let ticket = format!("rn1-{}", "AbCd_-09".repeat(12));
+ let title = format!("Join the Reason Network: https://reasonmachines.com/network/join/#{ticket}");
+ let item = serde_json::json!({"session_id": "r-1", "status": "running", "title": title, "finished_at": null});
+ let stub = Stub::running("no", format!("echo '{}'", serde_json::json!({ "items": [item] })));
+ d.sync_from(&stub.bin).await.unwrap();
+ let doing = d.inner.lock().unwrap().live["reason:r-1"].doing.clone();
+ assert_eq!(doing.as_deref(), Some("Join the Reason Network: (team link)"));
+ }
+
#[tokio::test]
async fn a_list_that_fails_either_way_is_one_error_and_tries_narrow_again() {
let d = Arc::new(super::super::test_daemon(Default::default()));
diff --git a/src/daemon/sessions.rs b/src/daemon/sessions.rs
index 0f93131..ad9174d 100644
--- a/src/daemon/sessions.rs
+++ b/src/daemon/sessions.rs
@@ -268,7 +268,7 @@ impl Daemon {
}
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();
+ let d = crate::team::without_tickets(d.trim());
live.doing = (!d.is_empty()).then(|| d.chars().take(200).collect());
}
if let Some(n) = new_name
@@ -378,7 +378,8 @@ impl Daemon {
// Only a report: it says nothing about the session's activity or how to reach it.
if event == "doing" {
if let Some(d) = doing {
- l.doing = Some(d.trim().chars().take(200).collect::<String>()).filter(|d| !d.is_empty());
+ let d = crate::team::without_tickets(d.trim());
+ l.doing = Some(d.chars().take(200).collect::<String>()).filter(|d| !d.is_empty());
}
return Ok(HookReply::default());
}
@@ -731,6 +732,65 @@ mod tests {
assert_eq!((a.name.as_str(), a.unread), ("api-claude", 1));
}
+ #[tokio::test]
+ async fn a_pasted_invite_line_never_reaches_teammates_through_what_a_session_is_doing() {
+ let cfg = crate::config::Config { person: Some("alex".into()), ..Default::default() };
+ let d = Arc::new(super::super::test_daemon(cfg));
+ let mut team = crate::team::TeamState::found("acme", &d.person, &d.machine, &d.key);
+ team.new_link(&d.key);
+ let secret = team.link_secret().expect("a team link").to_string();
+ d.inner.lock().unwrap().team = Some(team);
+ let l = d.link(false).await.unwrap();
+ let line = crate::invite_line(&l.url);
+ // `status <doing>` from an agent's shell; a `doing` hook; a session kept by a build that stored the line.
+ join(&d, claude("a"));
+ d.set_status("claude-code:a", Some(format!("{line} then fix CI")), None).unwrap();
+ join(&d, claude("b"));
+ let doing = HookCall {
+ agent: "claude-code".into(),
+ event: "doing".into(),
+ session_id: "b".into(),
+ cwd: Some("/work/api".into()),
+ pid: None,
+ mail: false,
+ transcript: None,
+ doing: Some(line.clone()),
+ name: None,
+ dirs: Vec::new(),
+ keep: false,
+ };
+ d.hook(doing).await.unwrap();
+ let old = Remembered {
+ name: "old".into(),
+ key: "claude-code:old".into(),
+ agent: "claude-code".into(),
+ cwd: "/work/api".into(),
+ repo: None,
+ branch: None,
+ doing: Some(line.clone()),
+ tier: Tier::Push,
+ last_seen: util::now_ms() - 60_000,
+ attached: true,
+ mailbox: false,
+ };
+ d.inner.lock().unwrap().store.upsert_session(&old, &d.person).unwrap();
+
+ let dir = d.who(None, None, true).await.unwrap();
+ let presence = serde_json::to_string(&d.presence().await).unwrap();
+ let stored = format!("{:?}", d.inner.lock().unwrap().store.session_by_name("api-claude").unwrap());
+ let agent = crate::render::directory_for_agent(&dir);
+ for out in [&serde_json::to_string(&dir).unwrap(), &agent, &presence, &stored] {
+ assert!(!out.contains("rn1-") && !out.contains(&l.ticket) && !out.contains(&secret), "{out}");
+ }
+ let doings: Vec<_> = dir.sessions.iter().filter_map(|s| s.doing.as_deref()).collect();
+ assert_eq!(
+ doings.iter().filter(|d| d.starts_with("Join the Reason Network: (team link)")).count(),
+ 3,
+ "{doings:?}"
+ );
+ assert!(agent.contains("doing: Join the Reason Network: (team link) then fix CI"), "{agent}");
+ }
+
#[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()));
diff --git a/src/daemon/teamops.rs b/src/daemon/teamops.rs
index 7b31656..ba5258f 100644
--- a/src/daemon/teamops.rs
+++ b/src/daemon/teamops.rs
@@ -360,8 +360,8 @@ impl Daemon {
}
let info = TeamInfo {
id: state.id.clone(),
- name: state.shown_name(),
- team_name: state.shown_name(),
+ name: state.whole_name(),
+ team_name: state.whole_name(),
relay: state.meta.body.relay.clone(),
relay_connected: None,
person: person.clone(),
@@ -487,14 +487,7 @@ impl Daemon {
}
let secret = state.link_secret().expect("just made").to_string();
let ticket = self.ticket(&state, secret).encode();
- Ok(LinkInfo { team: state.shown_name(), url: crate::join_url(&ticket), ticket })
- }
-
- /// The team link as it is now, without making one (for `list_team`).
- pub(super) fn current_link(&self) -> Option<String> {
- let state = self.team_state()?;
- let secret = state.link_secret()?.to_string();
- Some(crate::join_url(&self.ticket(&state, secret).encode()))
+ Ok(LinkInfo { team: state.whole_name(), url: crate::join_url(&ticket), ticket })
}
pub(super) fn team_info(&self) -> Result<TeamInfo> {
@@ -503,8 +496,8 @@ impl Daemon {
.ok_or_else(|| anyhow!("not in a team yet: `{CLI} init <team>` or `{CLI} join <invite>`"))?;
Ok(TeamInfo {
id: team.id.clone(),
- name: team.shown_name(),
- team_name: team.shown_name(),
+ name: team.whole_name(),
+ team_name: team.whole_name(),
relay: team.meta.body.relay.clone(),
relay_connected: self.net().map(|n| n.relay_connected()),
person: self.person.clone(),
diff --git a/src/doing.rs b/src/doing.rs
index c111e72..d2c3502 100644
--- a/src/doing.rs
+++ b/src/doing.rs
@@ -40,7 +40,7 @@ pub fn of(s: &Source) -> Option<String> {
(None, Some(k)) => k,
(None, None) => return None,
};
- Some(clip(&line))
+ Some(clip(&crate::team::without_tickets(&line)))
}
fn clip(s: &str) -> String {
@@ -263,4 +263,19 @@ mod tests {
assert_eq!(scan(&g).task, Some(Some("Fix login".into())));
let _ = std::fs::remove_dir_all(&dir);
}
+
+ #[test]
+ fn a_title_or_task_made_from_a_pasted_invite_line_leaves_the_link_out() {
+ let dir = std::env::temp_dir().join(format!("reason-network-doing-link-{}", std::process::id()));
+ std::fs::create_dir_all(&dir).unwrap();
+ let p = dir.join("t.jsonl");
+ let ticket = format!("rn1-{}", "AbCd_-09".repeat(12));
+ let title = format!("Join the Reason Network: https://reasonmachines.com/network/join/#{ticket}");
+ let line = |v: Value| format!("{v}\n");
+ let todo = serde_json::json!({"todos": [{"content": format!("join {ticket}"), "status": "in_progress"}]});
+ std::fs::write(&p, line(serde_json::json!({"type": "ai-title", "aiTitle": title})) + &line(todo)).unwrap();
+ let s = Source { agent: "cursor".into(), session: None, transcript: Some(p) };
+ assert_eq!(of(&s).as_deref(), Some("Join the Reason Network: (team link) · join (team link)"));
+ let _ = std::fs::remove_dir_all(&dir);
+ }
}
diff --git a/src/main.rs b/src/main.rs
index 83128f6..a391691 100644
--- a/src/main.rs
+++ b/src/main.rs
@@ -497,12 +497,12 @@ async fn cli(cmd: Cmd) -> Result<()> {
Cmd::Link { new, json } => {
let l: LinkInfo = link.call(Request::Link { new }).await?;
if json {
- println!("{}", shown(&serde_json::to_string_pretty(&team_json(&link, None).await?)?));
+ println!("{}", shown(&serde_json::to_string_pretty(&team_json(&link, None, true).await?)?));
return Ok(());
}
let line = invite_line(&l.url);
let copied = wizard::interactive() && wizard::copy(&line);
- let team = shown(&l.team);
+ let team = shown(&team::shown_name(&l.team));
println!("Team link for {team}{}:\n\n{line}\n", if copied { " (on your clipboard)" } else { "" });
println!("Whoever pastes this line to their coding agent joins the team. `{CLI} link --new` replaces it.");
}
@@ -519,10 +519,11 @@ async fn cli(cmd: Cmd) -> Result<()> {
wait_exit(daemon_pid()).await;
if json {
let agents = if no_setup { None } else { Some(setup::quietly().await?) };
- println!("{}", shown(&serde_json::to_string_pretty(&team_json(&Link::new(None), agents).await?)?));
+ let j = team_json(&Link::new(None), agents, true).await?;
+ println!("{}", shown(&serde_json::to_string_pretty(&j)?));
return Ok(());
}
- println!("Created team {}. You are {} on {}.", t.name, t.person, t.machine);
+ println!("Created team {}. You are {} on {}.", team::shown_name(&t.name), t.person, t.machine);
if !no_setup {
println!();
setup::run(false, false, false).await?;
@@ -537,7 +538,7 @@ async fn cli(cmd: Cmd) -> Result<()> {
wait_exit(daemon_pid()).await;
let agents = if no_setup || !json { None } else { Some(setup::quietly().await?) };
if !json {
- println!("Joined team {} as {} on {}.", shown(&t.name), t.person, t.machine);
+ println!("Joined team {} as {} on {}.", shown(&team::shown_name(&t.name)), t.person, t.machine);
}
if !no_setup && !json {
println!();
@@ -554,7 +555,7 @@ async fn cli(cmd: Cmd) -> Result<()> {
}
}
if json {
- println!("{}", shown(&serde_json::to_string_pretty(&team_json(&fresh, agents).await?)?));
+ println!("{}", shown(&serde_json::to_string_pretty(&team_json(&fresh, agents, true).await?)?));
return Ok(());
}
if let Ok(t) = fresh.call::<TeamInfo>(Request::Team).await {
@@ -613,7 +614,7 @@ async fn cli(cmd: Cmd) -> Result<()> {
}
}
Cmd::Team { json: true } => {
- println!("{}", shown(&serde_json::to_string_pretty(&team_json(&link, None).await?)?))
+ println!("{}", shown(&serde_json::to_string_pretty(&team_json(&link, None, false).await?)?))
}
Cmd::Team { json: false } => {
let t: TeamInfo = link.call(Request::Team).await?;
@@ -697,14 +698,19 @@ async fn cli(cmd: Cmd) -> Result<()> {
Ok(())
}
-/// The team as `--json` gives it, for the Reason CLI: `set_up_for` names the agents set up, when setup ran.
-async fn team_json(link: &std::sync::Arc<Link>, set_up_for: Option<Vec<&str>>) -> Result<serde_json::Value> {
+/// The team as `--json` gives it: `set_up_for` names the agents set up, when setup ran. `with_link`: with the team link
+/// and invite line, for `init`, `join` and `link`; never for `team`, which agents run to see the team.
+async fn team_json(
+ link: &std::sync::Arc<Link>,
+ set_up_for: Option<Vec<&str>>,
+ with_link: bool,
+) -> Result<serde_json::Value> {
let t: TeamInfo = link.call(Request::Team).await?;
- let l: LinkInfo = link.call(Request::Link { new: false }).await?;
- team_value(&t, &l, set_up_for)
+ let l: Option<LinkInfo> = if with_link { Some(link.call(Request::Link { new: false }).await?) } else { None };
+ team_value(&t, l.as_ref(), set_up_for)
}
-fn team_value(t: &TeamInfo, l: &LinkInfo, set_up_for: Option<Vec<&str>>) -> Result<serde_json::Value> {
+fn team_value(t: &TeamInfo, l: Option<&LinkInfo>, set_up_for: Option<Vec<&str>>) -> Result<serde_json::Value> {
// A daemon from before team ids were in its reply (it was running when this binary was updated).
if t.id.is_empty() {
bail!(
@@ -722,9 +728,13 @@ fn team_value(t: &TeamInfo, l: &LinkInfo, set_up_for: Option<Vec<&str>>) -> Resu
})
.collect();
let mut out = serde_json::json!({
- "team_id": t.id, "team_name": t.name, "link": l.url, "invite_line": invite_line(&l.url),
+ "team_id": t.id, "team_name": team::shown_name(&t.name),
"person": t.person, "machine": t.machine, "endpoint": endpoint, "members": members,
});
+ if let Some(l) = l {
+ out["link"] = serde_json::json!(l.url);
+ out["invite_line"] = serde_json::json!(invite_line(&l.url));
+ }
if let Some(agents) = set_up_for {
out["set_up_for"] = serde_json::json!(agents);
}
@@ -920,9 +930,9 @@ mod tests {
udp: None,
};
let l = LinkInfo { team: "vibes".into(), url: join_url("rn1-AAAA"), ticket: "rn1-AAAA".into() };
- assert!(team_value(&t, &l, None).unwrap_err().to_string().contains("restart the Reason Network daemon"));
+ assert!(team_value(&t, Some(&l), None).unwrap_err().to_string().contains("restart the Reason Network daemon"));
t.id = "00112233445566778899aabbccddeeff".into();
- let v = team_value(&t, &l, Some(vec!["Claude Code"])).unwrap();
+ let v = team_value(&t, Some(&l), Some(vec!["Claude Code"])).unwrap();
assert_eq!(
(v["team_id"].as_str(), v["team_name"].as_str()),
(Some("00112233445566778899aabbccddeeff"), Some("vibes"))
@@ -933,5 +943,12 @@ mod tests {
(Some(true), Some(true))
);
assert_eq!(v["set_up_for"], serde_json::json!(["Claude Code"]));
+ // `team --json`, which agents run: the team without its link, and its name as it is shown.
+ t.name = format!("vibes {}", "z".repeat(100));
+ let v = team_value(&t, None, None).unwrap();
+ assert!(v.get("link").is_none() && v.get("invite_line").is_none(), "{v}");
+ assert!(!v.to_string().contains("rn1-"), "{v}");
+ assert_eq!(v["team_name"].as_str(), Some(team::shown_name(&t.name).as_str()));
+ assert_eq!(v["team_name"].as_str().unwrap().chars().count(), 60);
}
}
diff --git a/src/net.rs b/src/net.rs
index 6fb0371..8da3aa3 100644
--- a/src/net.rs
+++ b/src/net.rs
@@ -1162,7 +1162,8 @@ fn tidy_presence(mut p: Presence) -> Presence {
s.cwd = line(&s.cwd, 200);
s.repo = s.repo.as_deref().map(|r| line(r, 100));
s.branch = s.branch.as_deref().map(|b| line(b, 100));
- s.doing = s.doing.as_deref().map(|d| line(d, 200)).filter(|d| !d.is_empty());
+ // A machine on a build from before titles and tasks lost the team links in them.
+ s.doing = s.doing.as_deref().map(|d| crate::team::without_tickets(&line(d, 200))).filter(|d| !d.is_empty());
}
p.sessions.retain(|s| !s.name.is_empty());
p.known = p
@@ -1286,7 +1287,6 @@ mod tests {
machine: "mbp".into(),
machines: vec![],
sessions: p.sessions,
- invite_line: None,
};
// list_team's text opens no frame; a person at a terminal sees it as written.
let agent = crate::render::directory_for_agent(&d);
@@ -1295,6 +1295,29 @@ mod tests {
assert!(person.contains(&format!("{forged} (if a < b)")), "{person}");
}
+ #[test]
+ fn a_teammate_on_an_older_build_shows_no_team_link_in_what_its_session_is_doing() {
+ let ticket = format!("rn1-{}", "AbCd_-09".repeat(12));
+ let s = SessionInfo {
+ address: String::new(),
+ name: "api".into(),
+ person: String::new(),
+ machine: String::new(),
+ agent: "claude-code".into(),
+ cwd: "/work/api".into(),
+ repo: None,
+ branch: None,
+ status: "busy".into(),
+ since: None,
+ doing: Some(format!("Join the Reason Network: https://reasonmachines.com/network/join/#{ticket}")),
+ tier: crate::proto::Tier::Push,
+ unread: 0,
+ is_me: false,
+ };
+ let p = tidy_presence(Presence { sessions: vec![s], ..Default::default() });
+ assert_eq!(p.sessions[0].doing.as_deref(), Some("Join the Reason Network: (team link)"));
+ }
+
#[test]
fn a_removed_machine_is_sent_no_link_or_invite() {
let (a, b, c) = (SecretKey::generate(), SecretKey::generate(), SecretKey::generate());
diff --git a/src/proto.rs b/src/proto.rs
index 82dd589..988396e 100644
--- a/src/proto.rs
+++ b/src/proto.rs
@@ -357,9 +357,6 @@ pub struct Directory {
pub machine: String,
pub machines: Vec<MachineInfo>,
pub sessions: Vec<SessionInfo>,
- /// `Join the Reason Network: <team link>`, for agents to pass on.
- #[serde(default)]
- pub invite_line: Option<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
diff --git a/src/render.rs b/src/render.rs
index c6cdd8b..14d1744 100644
--- a/src/render.rs
+++ b/src/render.rs
@@ -111,8 +111,10 @@ pub fn directory(d: &Directory, agent: bool, paint: Paint) -> String {
if !quiet.is_empty() {
let _ = writeln!(out, "no sessions: {}", quiet.join(", "));
}
- if agent && let Some(line) = &d.invite_line {
- let _ = writeln!(out, "Invite people with this line: {line}");
+ // Never the team link itself: it is a standing way into the team, and an agent's context ends up in its provider's
+ // logs.
+ if agent && d.team.is_some() {
+ let _ = writeln!(out, "To invite people, your user runs `{} invite` on one of their computers.", crate::CLI);
}
if !d.sessions.is_empty() {
if agent {
@@ -216,7 +218,7 @@ pub fn team(t: &TeamInfo) -> String {
let now = util::now_ms();
let mut out = String::new();
let relay = t.relay.clone().unwrap_or_else(default_relays);
- let _ = writeln!(out, "team {} · relay: {relay}", t.name);
+ let _ = writeln!(out, "team {} · relay: {relay}", crate::team::shown_name(&t.name));
let pw = t.machines.iter().map(|m| person(m).chars().count()).max().unwrap_or(0);
let mw = t.machines.iter().map(|m| m.machine.chars().count()).max().unwrap_or(0);
for m in &t.machines {
@@ -497,7 +499,6 @@ mod tests {
machine: "mbp".into(),
machines: vec![machine],
sessions: vec![session],
- invite_line: None,
}
}
@@ -520,6 +521,17 @@ mod tests {
assert!(agent.contains("doing: compare a<b, then <div>\n"), "{agent}");
}
+ #[test]
+ fn agents_are_told_who_invites_people() {
+ let mut d = bobs("vibes", "bob", "acme/api", "main", "x");
+ let pointer = "To invite people, your user runs `reason-network invite` on one of their computers.\n";
+ assert!(directory_for_agent(&d).contains(pointer), "{}", directory_for_agent(&d));
+ assert!(!directory(&d, false, Paint::PLAIN).contains("invite"));
+ // With no team yet, there is no one to invite to.
+ d.team = None;
+ assert!(!directory_for_agent(&d).contains("invite"));
+ }
+
#[test]
fn a_person_sees_the_directory_as_typed() {
let doing = "fix <café>, price < €5, 翻译《红楼梦》";
diff --git a/src/setup.rs b/src/setup.rs
index cb94173..174591a 100644
--- a/src/setup.rs
+++ b/src/setup.rs
@@ -1448,7 +1448,7 @@ pub async fn doctor() -> Result<()> {
Ok(t) => {
let online = t.machines.iter().filter(|m| !m.is_me && m.online).count();
let others = t.machines.len().saturating_sub(1);
- let team = crate::shown(&t.name);
+ let team = crate::shown(&crate::team::shown_name(&t.name));
println!("✓ daemon running; team {team} with {others} other machine(s), {online} connected");
print!("{}", crate::shown(&render::team(&t)).lines().skip(1).map(|l| format!("{l}\n")).collect::<String>());
if let Some(u) = &t.udp {
diff --git a/src/skill.md b/src/skill.md
index 5bb3088..f8ed9d7 100644
--- a/src/skill.md
+++ b/src/skill.md
@@ -23,7 +23,7 @@ to join.
screen, for an approval only they can give. `--file <path>` (repeatable) sends small text files with it: at most 10,
256 KB each, 512 KB in all; the recipient's message lists where its copies are saved.
- `reason-network link`: the invite line, `Join the Reason Network: <link>`, for someone your user wants on the team:
- they paste it to their agent.
+ they paste it to their agent. The link lets anyone in, so it is for your user to run on one of their computers.
- `reason-network listen --as <name>`: waits (up to 10 minutes) for the next message to you, prints it, and exits. You
are reachable as `<your user>/<name>`. After handling a message and replying, run it again to keep listening.
- `reason-network folder <path> off|on`: only when your user asks you to. Keeps the sessions in that folder off the
diff --git a/src/team.rs b/src/team.rs
index a0fb17d..edc388a 100644
--- a/src/team.rs
+++ b/src/team.rs
@@ -243,9 +243,14 @@ impl TeamState {
&self.meta.body.name
}
- /// The name as it is shown: one line. The founder picked it, and any member's machine can sign a new one.
+ /// The name as it is shown: see `shown_name`.
pub fn shown_name(&self) -> String {
- self.name().replace(|c: char| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}'), " ")
+ shown_name(self.name())
+ }
+
+ /// The whole name, in one line, for the Reason CLI, which compares it with the names it keeps (`team`, `link`).
+ pub fn whole_name(&self) -> String {
+ one_line(self.name())
}
/// Drops member entries with names no real client writes (see `plain_names`), kept by a build from before they
@@ -541,6 +546,92 @@ pub struct Ticket {
pub peers: Vec<EndpointId>,
}
+/// How much of a team's name is shown, as much as its links carry.
+pub const SHOWN_NAME: usize = 60;
+
+/// A team's name as it is shown to people and agents: one line, cut to `SHOWN_NAME` characters. The founder picked it,
+/// and any member's machine can sign a new one, of any length: it is kept whole, so a team with a long one works as
+/// before.
+pub fn shown_name(name: &str) -> String {
+ let line = one_line(name);
+ if line.chars().count() <= SHOWN_NAME {
+ return line;
+ }
+ format!("{}…", line.chars().take(SHOWN_NAME - 1).collect::<String>())
+}
+
+fn one_line(name: &str) -> String {
+ name.replace(|c: char| c.is_control() || matches!(c, '\u{2028}' | '\u{2029}'), " ")
+}
+
+/// `text` with each team link or ticket in it (`rn1-…`, earlier builds' `tincan1…`, and the link around one) taken out.
+/// A session's title and task are read from its transcript and shown to teammates, and an invite line pasted in a
+/// prompt can end up in them.
+pub fn without_tickets(text: &str) -> String {
+ if !Ticket::is_ticket(&text.replace(unseen, "")) {
+ return text.to_string();
+ }
+ let mut out = String::with_capacity(text.len());
+ for piece in text.split_inclusive(char::is_whitespace) {
+ let word = piece.trim_end_matches(char::is_whitespace);
+ if holds_ticket(word) {
+ out.push_str("(team link)");
+ out.push_str(&piece[word.len()..]);
+ } else {
+ out.push_str(piece);
+ }
+ }
+ out
+}
+
+/// Of a ticket's payload, how much is only the team's id (16 bytes: 21 base64url characters hold 126 of its 128 bits):
+/// one more already holds part of the link's secret.
+const TICKET_ID_CHARS: usize = 21;
+
+/// Whether a word holds a ticket, or enough of one to hold part of its secret: its prefix, not right after an ASCII
+/// letter (`turn1-`), then more of the payload than the team's id. Whatever comes before it otherwise (a digit, `%23`
+/// where a link's `#` was encoded, a word in another script, a character nobody sees) doesn't make it any less one, nor
+/// do characters slipped into it that nobody sees (a zero-width space, a soft hyphen, a direction mark) or a Markdown
+/// escape's `\`.
+fn holds_ticket(word: &str) -> bool {
+ // The word as it reads: each character that shows, and whether one that doesn't came right before it.
+ let mut shown = Vec::new();
+ let mut after_unseen = false;
+ for c in word.chars() {
+ if unseen(c) {
+ after_unseen = true;
+ } else {
+ shown.push((c, after_unseen));
+ after_unseen = false;
+ }
+ }
+ [TICKET_PREFIX, OLD_TICKET_PREFIX].iter().any(|prefix| {
+ let n = prefix.chars().count();
+ // Each check only where the one before it passed, and the payload counted no further than it needs to be: a
+ // long word stays quick.
+ (0..shown.len().saturating_sub(n - 1)).any(|at| {
+ let before = if shown[at].1 { None } else { at.checked_sub(1).map(|i| shown[i].0) };
+ shown[at..at + n].iter().map(|(c, _)| *c).eq(prefix.chars())
+ && before.is_none_or(|c| !c.is_ascii_alphabetic())
+ && shown[at + n..]
+ .iter()
+ .take_while(|(c, _)| c.is_ascii_alphanumeric() || matches!(c, '-' | '_'))
+ .take(TICKET_ID_CHARS + 1)
+ .count()
+ > TICKET_ID_CHARS
+ })
+ })
+}
+
+/// Characters that show as nothing (Unicode's default-ignorable ones, a zero-width space or a direction mark among
+/// them), and a Markdown escape's `\`.
+fn unseen(c: char) -> bool {
+ matches!(c, '\\' | '\u{00AD}' | '\u{034F}' | '\u{061C}' | '\u{115F}'..='\u{1160}' | '\u{17B4}'..='\u{17B5}'
+ | '\u{180B}'..='\u{180F}' | '\u{200B}'..='\u{200F}' | '\u{202A}'..='\u{202E}' | '\u{2060}'..='\u{206F}'
+ | '\u{3164}' | '\u{FE00}'..='\u{FE0F}' | '\u{FEFF}' | '\u{FFA0}' | '\u{1BCA0}'..='\u{1BCA3}'
+ | '\u{E0000}'..='\u{E0FFF}')
+}
+
/// What a ticket starts with. The payload after it is shared with every peer (and earlier builds): never change it.
const TICKET_PREFIX: &str = "rn1-";
/// What earlier builds wrote: still read.
@@ -926,6 +1017,160 @@ mod tests {
assert_eq!(TeamState::found("Acme Team <dev> & co", "alex", "mbp", &a).shown_name(), "Acme Team <dev> & co");
}
+ #[test]
+ fn a_long_team_name_is_shown_cut_and_kept_whole() {
+ let (a, b) = (key(), key());
+ let long = format!("vibes {}", "x".repeat(300));
+ let mut sa = TeamState::found(&long, "alex", "mbp", &a);
+ let shown = sa.shown_name();
+ assert_eq!(shown.chars().count(), SHOWN_NAME, "{shown}");
+ assert!(shown.starts_with("vibes xxx") && shown.ends_with('…'), "{shown}");
+ // Kept whole, and a machine joining takes it as it is: a team with a long name works as before.
+ assert_eq!(sa.whole_name(), long);
+ sa.put_member(&a, b.public(), "alice", "xps", true);
+ let sb = TeamState::verified(&sa).unwrap();
+ assert!(sb.is_active(&b.public()) && sb.name() == long);
+ // Up to the cut, as typed.
+ let exact = "y".repeat(SHOWN_NAME);
+ assert_eq!(TeamState::found(&exact, "alex", "mbp", &a).shown_name(), exact);
+ assert_eq!(shown_name("開発\nチーム"), "開発 チーム");
+ }
+
+ #[test]
+ fn team_links_are_taken_out_of_what_teammates_see() {
+ let t = Ticket {
+ team: "00112233445566778899aabbccddeeff".into(),
+ name: "vibes".into(),
+ secret: random_secret(),
+ relay: None,
+ hint_relay: None,
+ hint_ips: vec![],
+ peers: vec![key().public()],
+ };
+ let enc = t.encode();
+ let payload = enc.strip_prefix(TICKET_PREFIX).unwrap();
+ let url = format!("https://reasonmachines.com/network/join/#{enc}");
+ for (text, want) in [
+ (format!("Join the Reason Network: {url}"), "Join the Reason Network: (team link)".to_string()),
+ (format!("{enc} please"), "(team link) please".into()),
+ (format!("join ({url}), then fix CI"), "join (team link) then fix CI".into()),
+ (format!("old tincan1{payload}"), "old (team link)".into()),
+ (format!("https://tincan.example/join#tincan1{payload} and more"), "(team link) and more".into()),
+ // Cut off where a title or task is shortened, it still holds the secret.
+ (
+ format!("Join the Reason Network: {}", &url[..url.len() - 40]),
+ "Join the Reason Network: (team link)".into(),
+ ),
+ (format!("a\t{enc}\nb"), "a\t(team link)\nb".into()),
+ ] {
+ let got = without_tickets(&text);
+ assert_eq!(got, want, "{text}");
+ assert!(!got.contains(payload) && !got.contains(&payload[..32]));
+ }
+ // Glued to whatever comes before it that isn't an ASCII letter, or with the link's `#` percent-encoded (as
+ // mail link wrappers write it), it is still one.
+ for before in [
+ "邀请码",
+ "é",
+ "1",
+ "%23",
+ "https://safelinks.example/?url=https%3A%2F%2Freasonmachines.com%2Fnetwork%2Fjoin%2F%23",
+ ] {
+ for ticket in [enc.clone(), format!("tincan1{payload}")] {
+ let got = without_tickets(&format!("see {before}{ticket} now"));
+ assert_eq!(got, "see (team link) now", "{before}{ticket}");
+ }
+ }
+ // Words that only look like one stay: after an ASCII letter, or with no more than the team's id after the
+ // prefix (no part of the secret).
+ let id_only = &payload[..TICKET_ID_CHARS];
+ for text in [
+ "turn1-left at the light".to_string(),
+ "burn1-".to_string() + payload,
+ "rn1- notes".into(),
+ "tincan1 notes".into(),
+ "fix rn1 and tincan1.".into(),
+ "plain text".into(),
+ "rn1-2".into(),
+ "rn1-beta".into(),
+ "fix-rn1-prefix".into(),
+ "x/rn1-tickets".into(),
+ "docs/rn1-notes/for/the/whole/story.md".into(),
+ "tincan10".into(),
+ format!("#rn1-{id_only}"),
+ format!("tincan1{id_only}"),
+ ] {
+ assert_eq!(without_tickets(&text), text);
+ }
+ // Characters a paste or an editor can slip into a link without anyone seeing them (a zero-width space, a soft
+ // hyphen, a direction mark, a Markdown `\_`) don't hide it.
+ let marks = [
+ "\u{200B}",
+ "\u{200C}",
+ "\u{200D}",
+ "\u{2060}",
+ "\u{FEFF}",
+ "\u{00AD}",
+ "\\",
+ "\u{200E}",
+ "\u{200F}",
+ "\u{061C}",
+ "\u{202E}",
+ "\u{2066}",
+ "\u{2063}",
+ "\u{FE0F}",
+ "\u{E0041}",
+ "\u{3164}",
+ ];
+ for mark in marks {
+ for at in [1, 8, 20] {
+ let mangled = format!("rn1-{}{mark}{}", &payload[..at], &payload[at..]);
+ assert_eq!(without_tickets(&format!("see {mangled} now")), "see (team link) now", "{mangled:?}");
+ }
+ // Nor in the prefix, nor right before it.
+ for prefix in ["rn1-", "tincan1"] {
+ for at in 1..prefix.len() {
+ let mangled = format!("{}{mark}{}{payload}", &prefix[..at], &prefix[at..]);
+ assert_eq!(without_tickets(&format!("see {mangled} now")), "see (team link) now", "{mangled:?}");
+ }
+ }
+ assert_eq!(without_tickets(&format!("a{mark}rn1-{payload}")), "(team link)", "{mark:?}");
+ // A mark doesn't make a word that only looks like one into a link.
+ let text = format!("turn1-{mark}{payload}");
+ assert_eq!(without_tickets(&text), text);
+ let text = format!("rn1-{}{mark}", &payload[..TICKET_ID_CHARS]);
+ assert_eq!(without_tickets(&text), text);
+ }
+ // A long word with no spaces is gone through quickly, whatever is in it.
+ let started = std::time::Instant::now();
+ for long in [format!("x{}rn1-", "A".repeat(50_000)), "arn1-".repeat(10_000), "rn1\u{200B}".repeat(10_000)] {
+ assert_eq!(without_tickets(&long), long);
+ }
+ assert!(started.elapsed() < std::time::Duration::from_secs(1), "{:?}", started.elapsed());
+ // One character more holds part of the secret.
+ assert_eq!(without_tickets(&format!("#rn1-{}", &payload[..TICKET_ID_CHARS + 1])), "(team link)");
+ assert_eq!(without_tickets(&format!("tincan1{}", &payload[..TICKET_ID_CHARS + 1])), "(team link)");
+ }
+
+ #[test]
+ fn a_tickets_first_characters_are_only_the_team_id() {
+ let t = |team: &str, secret: &str| Ticket {
+ team: team.into(),
+ name: "vibes".into(),
+ secret: secret.into(),
+ relay: None,
+ hint_relay: None,
+ hint_ips: vec![],
+ peers: vec![key().public()],
+ };
+ let team = "00112233445566778899aabbccddeeff";
+ let (a, b) = (t(team, &"00".repeat(16)).encode(), t(team, &"ff".repeat(16)).encode());
+ let at = TICKET_PREFIX.len() + TICKET_ID_CHARS;
+ // The same team id: the same first 21 characters, whatever the secret; the 22nd already differs with it.
+ assert_eq!(a[..at], b[..at]);
+ assert_ne!(a[at..at + 1], b[at..at + 1]);
+ }
+
#[test]
fn a_teammate_cannot_take_someone_elses_name() {
let (a, b, fake, mine) = (key(), key(), key(), key());
diff --git a/src/wizard.rs b/src/wizard.rs
index 1cabb9a..a3f5a14 100644
--- a/src/wizard.rs
+++ b/src/wizard.rs
@@ -7,7 +7,9 @@ use crate::{
config::{Config, Policy},
install_lines, invite,
proto::*,
- render, setup, util,
+ render, setup,
+ team::shown_name,
+ util,
};
use anyhow::{Result, anyhow};
use cliclack::{confirm, input, intro, log, multiselect, note, outro, outro_cancel, select, spinner};
@@ -59,7 +61,7 @@ pub async fn onboard(
intro(format!(" {CLI} "))?;
let link = Link::new(None);
if let Ok(t) = link.call::<TeamInfo>(Request::Team).await {
- log::info(crate::shown(&format!("You're in team {} as {} on {}.", t.name, t.person, t.machine)))?;
+ log::info(crate::shown(&format!("You're in team {} as {} on {}.", shown_name(&t.name), t.person, t.machine)))?;
outro(format!("`{CLI}` shows who's around; `{CLI} invite` gives you the team link."))?;
return Ok(());
}
@@ -88,7 +90,7 @@ pub async fn onboard(
.await
.inspect_err(|e| sp.error(crate::shown(&format!("{e:#}"))))?;
crate::wait_exit(crate::daemon_pid()).await;
- sp.stop(crate::shown(&format!("Created team {}. You are {} on {}.", t.name, t.person, t.machine)));
+ sp.stop(crate::shown(&format!("Created team {}. You are {} on {}.", shown_name(&t.name), t.person, t.machine)));
} else {
let mut invite = invite;
loop {
@@ -107,7 +109,12 @@ pub async fn onboard(
{
Ok(t) => {
crate::wait_exit(crate::daemon_pid()).await;
- sp.stop(crate::shown(&format!("Joined team {} as {} on {}.", t.name, t.person, t.machine)));
+ sp.stop(crate::shown(&format!(
+ "Joined team {} as {} on {}.",
+ shown_name(&t.name),
+ t.person,
+ t.machine
+ )));
break;
}
Err(e) if e.to_string().starts_with("already in team") => {
@@ -244,7 +251,7 @@ pub async fn agents_and_preferences() -> Result<()> {
pub async fn show_link(new: bool) -> Result<String> {
let l: LinkInfo = Link::new(None).call(Request::Link { new }).await?;
let copied = copy(&l.url);
- let team = crate::shown(&l.team);
+ let team = crate::shown(&shown_name(&l.team));
let title =
if copied { format!("Team link for {team} (on your clipboard)") } else { format!("Team link for {team}") };
note(
diff --git a/tests/e2e/hooks.py b/tests/e2e/hooks.py
index 00eb053..63223db 100644
--- a/tests/e2e/hooks.py
+++ b/tests/e2e/hooks.py
@@ -2,7 +2,7 @@
cargo build && python3 tests/e2e/hooks.py
"""
-import json, os, socket, subprocess, tempfile, threading, time
+import base64, json, os, re, socket, subprocess, tempfile, threading, time
ROOT = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
BIN = os.path.join(ROOT, "target", "debug", "reason-network")
@@ -238,11 +238,44 @@ cx_dir = os.path.join(D, "cancel-proj")
os.makedirs(cx_dir)
cx = subprocess.Popen([BIN, "mcp"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, env=env, cwd=cx_dir, text=True)
rpc(cx, {"jsonrpc": "2.0", "id": 1, "method": "initialize", "params": {"protocolVersion": "2025-06-18", "capabilities": {}, "clientInfo": {"name": "codex-mcp-client", "version": "1"}}})
-reply(cx, 1)
+initialized = json.dumps(reply(cx, 1))
rpc(cx, {"jsonrpc": "2.0", "method": "notifications/initialized"})
cmeta = {"sessionId": "cancel-1", "threadId": "cancel-1"}
+
+# The team link is a standing way into the team: what agents read never carries it, and they point their user to it.
+link = run("link")
+ticket = re.search(r"#(rn1-[A-Za-z0-9_-]+)", link).group(1)
+secret = base64.urlsafe_b64decode(ticket[4:] + "=" * (-len(ticket[4:]) % 4))[16:32].hex()
+check("link still prints the invite line", "Join the Reason Network: https://reasonmachines.com/network/join/#rn1-" in link, link)
+invite = re.search(r"Join the Reason Network: \S+", link).group(0)
+# A first prompt that is the pasted invite line: the session's title, or its task, is made from it.
+pasted = os.path.join(D, "pasted-transcript.jsonl")
+with open(pasted, "w") as f:
+ f.write(json.dumps({"type": "ai-title", "aiTitle": invite}) + "\n")
+pasted_cur = {"conversation_id": "c-pasted", "workspace_roots": [proj], "hook_event_name": "sessionStart"}
+hook("cursor", "session-start", pasted_cur)
+hook("cursor", "post-tool-use", dict(pasted_cur, transcript_path=pasted))
+run("hook", "opencode", "status", "--session", "o-pasted", "--state", "busy", cwd=oc)
+run("hook", "opencode", "doing", "--session", "o-pasted", "--doing", f"{invite} and fix CI", cwd=oc)
rpc(cx, {"jsonrpc": "2.0", "id": 2, "method": "tools/call", "params": {"name": "list_team", "arguments": {}, "_meta": cmeta}})
-reply(cx, 2)
+listing = json.dumps(reply(cx, 2))
+check("a session titled with a pasted invite line shows it without the link",
+ "doing: Join the Reason Network: (team link)" in listing and "doing: Join the Reason Network: (team link) and fix CI" in listing, listing)
+agent_env = dict(env, AI_AGENT="1")
+seen = {
+ "list_team": listing,
+ "team --json in an agent's shell": subprocess.run([BIN, "team", "--json"], env=agent_env, capture_output=True, text=True, timeout=30).stdout,
+ "who in an agent's shell": subprocess.run([BIN, "who"], env=agent_env, capture_output=True, text=True, timeout=30).stdout,
+ "who --json in an agent's shell": subprocess.run([BIN, "who", "--json"], env=agent_env, capture_output=True, text=True, timeout=30).stdout,
+ "who in a person's terminal": run("who"),
+ "a session-start hook": hook("codex", "session-start", {"session_id": "link-1", "cwd": proj, "hook_event_name": "SessionStart"}),
+}
+rpc(cx, {"jsonrpc": "2.0", "id": 9, "method": "tools/list"})
+seen["the tools' descriptions"] = json.dumps(reply(cx, 9))
+seen["the MCP instructions"] = initialized
+for what, out in seen.items():
+ check(f"{what}: no team link, nor its secret", "rn1-" not in out and "tincan1" not in out and secret not in out, out)
+check("list_team says who invites people", "your user runs `reason-network invite` on one of their computers" in listing, listing)
rpc(cx, {"jsonrpc": "2.0", "id": 3, "method": "tools/call", "params": {"name": "check_inbox", "arguments": {"wait_secs": 60}, "_meta": cmeta}})
time.sleep(1.5)
rpc(cx, {"jsonrpc": "2.0", "method": "notifications/cancelled", "params": {"requestId": 3, "reason": "user pressed Esc"}})
diff --git a/tests/e2e/two_machines.py b/tests/e2e/two_machines.py
index 91819f4..7f93fca 100644
--- a/tests/e2e/two_machines.py
+++ b/tests/e2e/two_machines.py
@@ -167,7 +167,8 @@ check("a team without a relay of its own is on Reason's: the link names the one
and "relay: Reason's (the default)" in out, out)
j = as_json(cli("alex", "team", "--json"))
check("team --json marks people verified, and each machine's proof", [(m["verified"], m["has_proof"]) for m in j.get("members", [])] == [(True, True)] * 2
- and j.get("link", "").startswith("https://") and j.get("team_name") == "vibes" and len(j.get("team_id", "")) == 32, j)
+ and j.get("team_name") == "vibes" and len(j.get("team_id", "")) == 32, j)
+check("…and leaves out the team link (agents run it)", "link" not in j and "invite_line" not in j and "rn1-" not in json.dumps(j), j)
j = as_json(cli("alex", "link", "--json"))
check("link --json gives the invite line", j.get("invite_line", "").startswith("Join the Reason Network: https://reasonmachines.com/network/join/#rn1-"), j)
out = cli("alex", "link")
@@ -263,6 +264,54 @@ out = subprocess.run([BIN, "link"], env=bob, capture_output=True, text=True, tim
check("any member can show the same team link", link.group(1).split("#")[1][:40] in out.replace("\n", ""), out)
subprocess.run([BIN, "stop"], env=bob, capture_output=True)
+# --- a team with a long name: shown cut, but whole where the Reason CLI keeps and compares it ---
+LONG = "Acme platform and infrastructure engineering, west coast + EMEA" + " (2026)" * 3
+CUT = LONG[:59] + "…"
+lena = dict(env("alice"), REASON_NETWORK_HOME=os.path.join(D, "lena"), REASON_NETWORK_MACHINE="ws")
+lou = dict(env("alice"), REASON_NETWORK_HOME=os.path.join(D, "lou"), REASON_NETWORK_MACHINE="pad")
+
+
+def over_socket(e, req):
+ import socket
+ with socket.socket(socket.AF_UNIX) as sock:
+ sock.settimeout(90)
+ sock.connect(os.path.join(e["REASON_NETWORK_HOME"], "network.sock"))
+ sock.sendall((json.dumps(dict(id=1, **req)) + "\n").encode())
+ return as_json(sock.makefile().readline()).get("result") or {}
+
+
+_, out = run(lena, "init", LONG, "--as", "lena", "--no-setup")
+check("init with a long team name prints it cut", f"Created team {CUT}." in out and LONG not in out, out)
+lj = as_json(run(lena, "link", "--json")[0])
+check("…link --json too, with the link", lj.get("team_name") == CUT and lj.get("link", "").startswith("https://"), lj)
+run(lou, "who", "--json") # starts lou's daemon
+joined = over_socket(lou, {"op": "join", "ticket": lj.get("link", ""), "person": "lou"})
+check("the join reply over the socket names the team whole (the Reason CLI keeps it)",
+ joined.get("team_name") == LONG and joined.get("name") == LONG, joined)
+# Its daemon restarts onto the team once it has answered (the Reason CLI waits for that too): wait for the new one.
+for _ in range(60):
+ run(lou, "who", "--json")
+ if "as lou@pad" in open(os.path.join(lou["REASON_NETWORK_HOME"], "daemon.log")).read():
+ break
+ time.sleep(0.5)
+for want, got in (("team", over_socket(lou, {"op": "team"}).get("name")), ("link", over_socket(lou, {"op": "link", "new": False}).get("team"))):
+ check(f"…as do {want} over the socket on the joined machine, the same as the join reply", got == LONG, got)
+tj = as_json(run(lou, "team", "--json")[0])
+check("team --json on the joined machine: cut, and no link", tj.get("team_name") == CUT and "link" not in tj, tj)
+check("…who --json too", as_json(run(lou, "who", "--json")[0]).get("team") == CUT)
+for _ in range(30):
+ if re.search(r"lou\s+pad\s+(direct|relay)", run(lena, "team")[1]):
+ break
+ time.sleep(1)
+_, out = run(lena, "team")
+check("the joined machine connects to the founder's", re.search(r"lou\s+pad\s+(direct|relay)", out) is not None and CUT in out and LONG not in out, out)
+run(lena, "listen", "--as", "notes", "--wait", "0")
+_, out = run(lou, "send", "lena/notes", "hello across a team with a long name")
+_, out = run(lena, "listen", "--as", "notes", "--wait", "30")
+check("…and a message reaches it", "hello across a team with a long name" in out, out)
+for e in (lena, lou):
+ subprocess.run([BIN, "stop"], env=e, capture_output=True)
+
# --- removal while online: the removed machine never gets the link that replaces the one it knew ---
eve = dict(env("alice"), REASON_NETWORK_HOME=os.path.join(D, "eve"), REASON_NETWORK_MACHINE="tab")
eve_link = re.search(r"(https://\S+#rn1-\S+)", cli("alex", "link")).group(1)
@@ -317,7 +366,7 @@ time.sleep(7) # Claude's session registers after 3s; presence propagates every
out = codex.tool("list_team", {}, meta)
claude_name = os.path.basename(ROOT).lower() + "-claude"
check("alice's agent sees alex's session across machines", claude_name in out and "alex (verified) · laptop" in out, out)
-check("list_team gives the invite line", "Invite people with this line: Join the Reason Network: https://reasonmachines.com/network/join/#rn1-" in out, out)
+check("list_team gives no team link, and says who invites people", "rn1-" not in out and "your user runs `reason-network invite`" in out, out)
check("…but not the one in alex's folder that is off", "private-claude" not in out, out)
out = hidden.tool("list_team", {})
check("in a folder that is off, the tools say so", out == "Your user turned Reason Network off for this folder", out)