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
Format with rustfmt
Lars Talianbf9cc13f6fa1
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 2d6994e..50d4f17 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -17,7 +17,8 @@ jobs:- uses: dtolnay/rust-toolchain@686976e191b89faba57d3206551f0f330d8cb249 # stablewith:toolchain: stable- components: clippy+ components: clippy, rustfmt- uses: Swatinem/rust-cache@6323deb102c322ba6fcbdcafc7e3dddab59af2b6 # v2+ - run: cargo fmt --check- run: cargo clippy --all-targets --locked -- -D warnings- run: cargo test --lockeddiff --git a/rustfmt.toml b/rustfmt.tomlnew file mode 100644index 0000000..c775577--- /dev/null+++ b/rustfmt.toml@@ -0,0 +1,2 @@+max_width = 120+use_small_heuristics = "Max"diff --git a/src/agent.rs b/src/agent.rsindex f9199e2..d883d8f 100644--- a/src/agent.rs+++ b/src/agent.rs@@ -121,7 +121,10 @@ pub fn find_bin(name: &str) -> Option<PathBuf> {let extra = [home.join(r".local\bin"), home.join(r"AppData\Roaming\npm"), home.join(r".bun\bin")];let exts: &[&str] = if cfg!(windows) { &[".exe", ".cmd"] } else { &[""] };let path = std::env::var_os("PATH").unwrap_or_default();- std::env::split_paths(&path).chain(extra).flat_map(|d| exts.iter().map(move |ext| d.join(format!("{name}{ext}")))).find(|p| executable(p))+ std::env::split_paths(&path)+ .chain(extra)+ .flat_map(|d| exts.iter().map(move |ext| d.join(format!("{name}{ext}"))))+ .find(|p| executable(p))}#[cfg(unix)]diff --git a/src/claude.rs b/src/claude.rsindex dda3a9b..3aa2c10 100644--- a/src/claude.rs+++ b/src/claude.rs@@ -70,9 +70,9 @@ pub fn wired() -> bool {/// The messaging socket of a live session, by its id or process.pub fn socket_for(session_id: Option<&str>, pid: Option<u32>) -> Option<ClaudeSocket> {- let c = scan()- .into_iter()- .find(|c| (session_id.is_some() && c.session_id.as_deref() == session_id) || (pid.is_some() && Some(c.pid) == pid))?;+ let c = scan().into_iter().find(|c| {+ (session_id.is_some() && c.session_id.as_deref() == session_id) || (pid.is_some() && Some(c.pid) == pid)+ })?;Some(ClaudeSocket { path: c.messaging_socket_path?.into(), token: peer_token(c.pid) })}diff --git a/src/client.rs b/src/client.rsindex 47cb704..a3deeb7 100644--- a/src/client.rs+++ b/src/client.rs@@ -110,7 +110,8 @@ impl Link {}}});- let (pending, alive, events, link) = (conn.pending.clone(), conn.alive.clone(), self.events.clone(), Arc::downgrade(self));+ let (pending, alive, events, link) =+ (conn.pending.clone(), conn.alive.clone(), self.events.clone(), Arc::downgrade(self));tokio::spawn(async move {let mut lines = BufReader::new(rd).lines();while let Ok(Some(line)) = lines.next_line().await {diff --git a/src/config.rs b/src/config.rsindex 0d4e70d..67dafc3 100644--- a/src/config.rs+++ b/src/config.rs@@ -43,7 +43,16 @@ pub enum Policy {impl Default for Config {fn default() -> Self {- Config { person: None, share_paths: false, share_unmanaged: false, lan: true, tray: true, reason: false, auto_update: true, inbound: Inbound::default() }+ Config {+ person: None,+ share_paths: false,+ share_unmanaged: false,+ lan: true,+ tray: true,+ reason: false,+ auto_update: true,+ inbound: Inbound::default(),+ }}}diff --git a/src/daemon/directory.rs b/src/daemon/directory.rsindex 9ed8bf1..e4a2a9b 100644--- a/src/daemon/directory.rs+++ b/src/daemon/directory.rs@@ -114,7 +114,8 @@ impl Daemon {(k.clone(), doing::Source { agent: l.reg.agent.clone(), session, transcript: l.transcript.clone() })});let unmanaged = claude.iter().map(|c| {- let source = doing::Source { agent: agent::CLAUDE_CODE.into(), session: c.session_id.clone(), transcript: None };+ let source =+ doing::Source { agent: agent::CLAUDE_CODE.into(), session: c.session_id.clone(), transcript: None };(format!("pid:{}", c.pid), source)});live.chain(unmanaged).collect()@@ -192,7 +193,8 @@ impl Daemon {let mut sessions = self.local_rows(None, self.cfg.share_unmanaged).await.unwrap_or_default();if !self.cfg.share_paths {for s in &mut sessions {- s.cwd = std::path::Path::new(&s.cwd).file_name().map_or("~".into(), |n| n.to_string_lossy().into_owned());+ s.cwd =+ std::path::Path::new(&s.cwd).file_name().map_or("~".into(), |n| n.to_string_lossy().into_owned());}}let g = self.inner.lock().unwrap();@@ -203,7 +205,12 @@ impl Daemon {Presence { sessions, known: known.into_iter().take(100).map(|r| r.name).collect() }}- pub(super) async fn who(self: &Arc<Self>, me: Option<String>, filter: Option<String>, all: bool) -> Result<Directory> {+ pub(super) async fn who(+ self: &Arc<Self>,+ me: Option<String>,+ filter: Option<String>,+ all: bool,+ ) -> Result<Directory> {let mut rows = self.local_rows(me.as_deref(), true).await?;if all {let g = self.inner.lock().unwrap();@@ -250,7 +257,14 @@ impl Daemon {}// Me first, then teammates; on tincan before not; live before offline.let rank = |r: &SessionInfo| {- (r.person != self.person, r.person.clone(), r.machine.clone(), r.tier == Tier::None, r.status == "offline", r.name.clone())+ (+ r.person != self.person,+ r.person.clone(),+ r.machine.clone(),+ r.tier == Tier::None,+ r.status == "offline",+ r.name.clone(),+ )};rows.sort_by_key(rank);Ok(Directory {@@ -367,12 +381,19 @@ impl Daemon {if name == "*" {live_matching(&|c| c.person == person)} else {- self.pick(cands.iter().copied().filter(|c| c.person == person && c.name == name).collect(), spec, &target)?+ self.pick(+ cands.iter().copied().filter(|c| c.person == person && c.name == name).collect(),+ spec,+ &target,+ )?}} else if people.iter().any(|p| p == spec) && !cands.iter().any(|c| c.name == spec) {// Messages go to agents, never to a person.- let mut theirs: Vec<String> =- cands.iter().filter(|c| c.person == spec && c.live).map(|c| format!("{}/{}", c.person, c.name)).collect();+ let mut theirs: Vec<String> = cands+ .iter()+ .filter(|c| c.person == spec && c.live)+ .map(|c| format!("{}/{}", c.person, c.name))+ .collect();theirs.sort();theirs.dedup();if theirs.is_empty() {diff --git a/src/daemon/mail.rs b/src/daemon/mail.rsindex 6fca62e..7615566 100644--- a/src/daemon/mail.rs+++ b/src/daemon/mail.rs@@ -5,8 +5,7 @@//! show them a second time.use super::{Daemon, Inner, directory::Target, log};-use crate::{- claude,agent, config::Policy, proto::*, render, util};+use crate::{agent, claude, config::Policy, proto::*, render, util};use anyhow::{Result, anyhow, bail};use iroh::EndpointId;use std::{@@ -84,7 +83,11 @@ impl Daemon {bail!("empty message");}if body.len() > MAX_BODY {- bail!("message is {} KB; the limit is {} KB (send a path or link instead)", body.len() / 1024, MAX_BODY / 1024);+ bail!(+ "message is {} KB; the limit is {} KB (send a path or link instead)",+ body.len() / 1024,+ MAX_BODY / 1024+ );}let now = util::now_ms();let net = self.net();@@ -103,7 +106,8 @@ impl Daemon {.get(k).or_else(|| g.live.values().find(|l| self.addr(&l.name) == k || l.name == k)).ok_or_else(unregistered)?;- let (from_addr, from_agent, from_repo) = (self.addr(&sender.name), Some(sender.reg.agent.clone()), sender.git.repo.clone());+ 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();let targets = self.resolve(&g, &remotes, to, Some(&exclude))?;for t in targets {@@ -135,7 +139,10 @@ impl Daemon {Target::Remote { machine, machine_name, online, .. } => {g.store.outbox_add(&machine.to_string(), &msg)?;remote_jobs.push((res.recipients.len(), machine, machine_name.clone(), online, msg.clone()));- ("queued".into(), format!("queued: not connected to {machine_name} right now; it goes out as soon as it is"))+ (+ "queued".into(),+ format!("queued: not connected to {machine_name} right now; it goes out as soon as it is"),+ )}};res.recipients.push(Recipient { address: msg.to.clone(), state, note });@@ -166,7 +173,13 @@ impl Daemon {}/// Hands messages to a session here by the fastest way it has. Returns the state and a note for the sender.- pub(super) fn deliver(self: &Arc<Self>, g: &mut Inner, key: &str, msgs: Vec<Message>, wake: bool) -> (String, String) {+ pub(super) fn deliver(+ self: &Arc<Self>,+ g: &mut Inner,+ key: &str,+ msgs: Vec<Message>,+ wake: bool,+ ) -> (String, String) {let Some(l) = g.live.get(key) else {return ("queued".into(), "queued: the session is offline; delivered when it is back".into());};@@ -218,21 +231,33 @@ impl Daemon {for id in ids {g.in_flight.insert(id, Instant::now());}- ("pushed".into(), "delivered into the session: it reads it between tool calls, or wakes up if idle".into())+ (+ "pushed".into(),+ "delivered into the session: it reads it between tool calls, or wakes up if idle".into(),+ )}Channel::Command(bin, args) => {for id in &ids {g.in_flight.insert(id.clone(), Instant::now());}self.send_with(bin, args, key.to_string(), ids, text);- ("pushed".into(), format!("queued into the {} session: it runs after the current turn, or now if idle", agent::label(bin)))+ (+ "pushed".into(),+ format!(+ "queued into the {} session: it runs after the current turn, or now if idle",+ agent::label(bin)+ ),+ )}Channel::ClaudeDirect(sock) => {for id in &ids {g.in_flight.insert(id.clone(), Instant::now());}self.post_direct(key.to_string(), sock, ids, text);- ("pushed".into(), "delivered into the session: it reads it between tool calls, or wakes up if idle".into())+ (+ "pushed".into(),+ "delivered into the session: it reads it between tool calls, or wakes up if idle".into(),+ )}Channel::Hook => ("queued".into(), hook_note.into()),Channel::Pull => ("queued".into(), "queued: this agent only sees it when it checks its inbox".into()),@@ -243,7 +268,7 @@ impl Daemon {fn post_direct(self: &Arc<Self>, key: String, sock: agent::ClaudeSocket, ids: Vec<String>, text: String) {let this = self.clone();tokio::spawn(async move {- let res =tokio::task::spawn_blocking(move || agent::post_to_claude(&sock, &text)).await;+ let res = tokio::task::spawn_blocking(move || agent::post_to_claude(&sock, &text)).await;let mut g = this.inner.lock().unwrap();for id in &ids {g.in_flight.remove(id);@@ -316,7 +341,8 @@ impl Daemon {if l.retry.is_none() {log(&format!("{bin} delivery to {key} failed ({why}); retrying with backoff"));}- let wait = l.retry.map_or(Duration::from_secs(15), |(_, w)| (w * 2).min(Duration::from_secs(1800)));+ let wait =+ l.retry.map_or(Duration::from_secs(15), |(_, w)| (w * 2).min(Duration::from_secs(1800)));l.retry = Some((Instant::now() + wait, wait));}}@@ -353,7 +379,10 @@ impl Daemon {return Ok(("refused".into(), format!("{} doesn't accept messages from {sender}", self.person)));}if !self.allow(&peer) {- return Ok(("retry".into(), format!("queued: {} is receiving a lot right now; retrying shortly", self.machine)));+ return Ok((+ "retry".into(),+ format!("queued: {} is receiving a lot right now; retrying shortly", self.machine),+ ));}let Some((person, name)) = msg.to.split_once('/') else { bail!(UPGRADE) };if person != self.person {@@ -498,7 +527,9 @@ fn tidy(s: &str, extra: &str, max: usize) -> Option<String> {/// 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| !s.is_empty() && s.len() <= 120 && s.chars().all(|c| c.is_ascii_alphanumeric() || extra.contains(c));+ let ok = |s: &str, extra: &str| {+ !s.is_empty() && s.len() <= 120 && s.chars().all(|c| c.is_ascii_alphanumeric() || extra.contains(c))+ };if !ok(&m.id, "") || !ok(&m.from, "-/") || !ok(&m.to, "-/") {bail!("malformed message");}diff --git a/src/daemon/mod.rs b/src/daemon/mod.rsindex c71a4cd..7361cbb 100644--- a/src/daemon/mod.rs+++ b/src/daemon/mod.rs@@ -225,7 +225,9 @@ impl Daemon {let f = match serde_json::from_str::<Frame<Request>>(&line) {Ok(f) => f,Err(e) => {- let _ = tx.send(serde_json::to_string(&Reply::err(0, anyhow!("bad request: {e}"))).expect("reply serializes"));+ let _ = tx.send(+ serde_json::to_string(&Reply::err(0, anyhow!("bad request: {e}"))).expect("reply serializes"),+ );continue;}};@@ -258,7 +260,9 @@ impl Daemon {}Request::SetStatus { key, doing, name } => json!(self.set_status(&key, doing, name)?),Request::Who { me, filter, all } => json!(self.who(me, filter, all).await?),- Request::Send { from, to, body, reply_to, wake } => json!(self.send(from, &to, &body, reply_to, wake).await?),+ Request::Send { from, to, body, reply_to, wake } => {+ json!(self.send(from, &to, &body, reply_to, wake).await?)+ }Request::Inbox { key, wait_secs, peek } => json!(self.inbox(key, wait_secs.min(MAX_WAIT), peek).await?),Request::Unread { key } => json!(self.unread(&key)?),Request::StopWaiting { key } => {diff --git a/src/daemon/reason.rs b/src/daemon/reason.rsindex cc4a3bb..7b54b3f 100644--- a/src/daemon/reason.rs+++ b/src/daemon/reason.rs@@ -54,7 +54,12 @@ impl Daemon {if !self.inner.lock().unwrap().live.contains_key(&key) {let git = GitInfo { root: None, repo: text("repo"), branch: text("branch") };// Named for its repo, else for the first words of its title (kept once chosen).- let name = git.repo.is_none().then(|| title.as_deref().map(first_words)).flatten().map(|t| format!("{t}-reason"));+ let name = git+ .repo+ .is_none()+ .then(|| title.as_deref().map(first_words))+ .flatten()+ .map(|t| format!("{t}-reason"));let reg = SessionReg {key: key.clone(),agent: "reason".into(),@@ -86,7 +91,12 @@ impl Daemon {}}let mut g = self.inner.lock().unwrap();- let gone: Vec<String> = g.live.iter().filter(|(k, l)| l.reg.agent == "reason" && !seen.contains(*k)).map(|(k, _)| k.clone()).collect();+ let gone: Vec<String> = g+ .live+ .iter()+ .filter(|(k, l)| l.reg.agent == "reason" && !seen.contains(*k))+ .map(|(k, _)| k.clone())+ .collect();for key in gone {if let Some(l) = g.live.remove(&key) {let _ = g.store.touch_session(&l.name, now);diff --git a/src/daemon/sessions.rs b/src/daemon/sessions.rsindex 216f5ec..dbc63ac 100644--- a/src/daemon/sessions.rs+++ b/src/daemon/sessions.rs@@ -2,14 +2,7 @@//! kept alive by hook events and the agent's process).use super::{Daemon, Inner, Live, log};-use crate::{- agent,- git::GitInfo,- proto::*,- render,- store::Remembered,- util,-};+use crate::{agent, git::GitInfo, proto::*, render, store::Remembered, util};use anyhow::{Result, anyhow, bail};use std::{collections::HashSet, sync::Arc};@@ -38,7 +31,12 @@ impl Daemon {Ok(registered)}- fn register_quiet(&self, conn: Option<u64>, mut reg: SessionReg, git: GitInfo) -> Result<(Registered, (String, Vec<Message>))> {+ fn register_quiet(+ &self,+ conn: Option<u64>,+ mut reg: SessionReg,+ git: GitInfo,+ ) -> Result<(Registered, (String, Vec<Message>))> {let now = util::now_ms();let others = self.my_names_elsewhere();let mut g = self.inner.lock().unwrap();@@ -120,7 +118,12 @@ impl Daemon {if let Some(n) = new_name&& n != live.name{- g.store.rename(&live.name, &n, &format!("{}/{}", self.person, live.name), &format!("{}/{n}", self.person))?;+ g.store.rename(+ &live.name,+ &n,+ &format!("{}/{}", self.person, live.name),+ &format!("{}/{n}", self.person),+ )?;live.name = n;}g.store.upsert_session(&remembered(live, util::now_ms()))?;@@ -220,7 +223,9 @@ impl Daemon {let busy: Vec<(&String, &Live)> = g.live.iter()- .filter(|(_, l)| l.reg.agent == agent && l.last_hook.is_some() && l.status.as_ref().is_some_and(|(s, _)| s == "busy"))+ .filter(|(_, l)| {+ l.reg.agent == agent && l.last_hook.is_some() && l.status.as_ref().is_some_and(|(s, _)| s == "busy")+ }).collect();let here: Vec<&(&String, &Live)> = busy.iter().filter(|(_, l)| l.reg.cwd == cwd).collect();match (here.as_slice(), busy.as_slice()) {@@ -258,7 +263,8 @@ impl Daemon {.iter().filter(|(_, l)| {l.conn.is_none()- && (l.reg.pid.is_some_and(|p| !util::pid_alive(p)) || l.last_hook.is_none_or(|t| now - t > HOOK_TTL_MS))+ && (l.reg.pid.is_some_and(|p| !util::pid_alive(p))+ || l.last_hook.is_none_or(|t| now - t > HOOK_TTL_MS))}).map(|(k, _)| k.clone()).collect();diff --git a/src/daemon/teamops.rs b/src/daemon/teamops.rsindex 7fd5f50..1745021 100644--- a/src/daemon/teamops.rs+++ b/src/daemon/teamops.rs@@ -3,9 +3,9 @@use super::{Daemon, Inner, log};use crate::{config::Config,+ invite,net::{self, JoinRequest, Net, Remote, Wire},proto::*,- invite,team::{TeamState, Ticket},util,};@@ -56,7 +56,11 @@ impl Daemon {{let g = self.inner.lock().unwrap();for m in team.active() {- if let Some(rem) = g.store.get(&format!("presence:{}", m.endpoint))?.and_then(|s| serde_json::from_str::<Remote>(&s).ok()) {+ if let Some(rem) = g+ .store+ .get(&format!("presence:{}", m.endpoint))?+ .and_then(|s| serde_json::from_str::<Remote>(&s).ok())+ {remote.insert(m.endpoint, rem);}}@@ -67,7 +71,11 @@ impl Daemon {// Invite codes made here that are still good: listen for them again.let codes: Vec<(String, i64)> = {let g = self.inner.lock().unwrap();- g.store.prefixed("code:")?.into_iter().filter_map(|(k, v)| Some((k.strip_prefix("code:")?.to_string(), v.parse().ok()?))).collect()+ g.store+ .prefixed("code:")?+ .into_iter()+ .filter_map(|(k, v)| Some((k.strip_prefix("code:")?.to_string(), v.parse().ok()?)))+ .collect()};for (code, expires) in codes {if team.invite_unused(&invite::secret(&code)) {@@ -160,7 +168,12 @@ impl Daemon {}/// Starts a team, with its own relay from the first moment if `relay` is given.- pub(super) async fn create_team(self: &Arc<Self>, name: &str, person: &str, relay: Option<String>) -> Result<TeamInfo> {+ pub(super) async fn create_team(+ self: &Arc<Self>,+ name: &str,+ person: &str,+ relay: Option<String>,+ ) -> Result<TeamInfo> {if let Some(t) = self.team_state() {bail!("already in team '{}'; run `tincan leave` first", t.name());}@@ -180,7 +193,14 @@ impl Daemon {}self.become_person(&person)?;self.restart_soon();- Ok(TeamInfo { name: name.into(), relay, relay_connected: None, person, machine: self.machine.clone(), machines: Vec::new() })+ Ok(TeamInfo {+ name: name.into(),+ relay,+ relay_connected: None,+ person,+ machine: self.machine.clone(),+ machines: Vec::new(),+ })}/// Joins with an invite code (`plum-tiger-lake-orbit`) or a long `tincan1…` ticket.@@ -218,7 +238,9 @@ impl Daemon {}// A code points at the key the inviting machine listens on for it; a ticket lists machines.let (team, secret, relay, peers) = match invite::normalize(invite_text) {- Some(code) => (String::new(), invite::secret(&code), None, vec![EndpointAddr::new(invite::key(&code).public())]),+ Some(code) => {+ (String::new(), invite::secret(&code), None, vec![EndpointAddr::new(invite::key(&code).public())])+ }None if invite_text.contains("tincan1") => {let t = Ticket::decode(invite_text)?;let addrs = t.addrs();@@ -253,7 +275,8 @@ impl Daemon {}fn become_person(&self, person: &str) -> Result<()> {- let mut cfg = Config::load_strict().map_err(|e| anyhow!("fix {} first: {e}", crate::paths::config().display()))?;+ let mut cfg =+ Config::load_strict().map_err(|e| anyhow!("fix {} first: {e}", crate::paths::config().display()))?;cfg.person = Some(person.to_string());cfg.save()}@@ -261,7 +284,8 @@ impl Daemon {/// Makes an invite: a code (this machine listens for it until it is used or expires) and the equivalent/// long ticket (which any teammate's machine can redeem).pub(super) async fn invite(&self, me: bool, hours: u64) -> Result<InviteInfo> {- let net = self.net().ok_or_else(|| anyhow!("not connected to a team yet (run `tincan init` or `tincan join`)"))?;+ let net =+ self.net().ok_or_else(|| anyhow!("not connected to a team yet (run `tincan init` or `tincan join`)"))?;net.online(Duration::from_secs(5)).await;let hours = hours.clamp(1, 24 * 30);let code = invite::generate();@@ -335,7 +359,9 @@ impl Daemon {}pub(super) fn team_info(&self) -> Result<TeamInfo> {- let team = self.team_state().ok_or_else(|| anyhow!("not in a team yet: `tincan init <team>` or `tincan join <invite>`"))?;+ let team = self+ .team_state()+ .ok_or_else(|| anyhow!("not in a team yet: `tincan init <team>` or `tincan join <invite>`"))?;Ok(TeamInfo {name: team.name().into(),relay: team.meta.body.relay.clone(),@@ -389,7 +415,11 @@ impl Daemon {.active().filter(|m| match who.split_once('/') {Some((p, mach)) => m.person == p && m.machine == mach,- None => m.person == who || m.machine == who || (who.len() >= 6 && m.endpoint.to_string().starts_with(who)),+ None => {+ m.person == who+ || m.machine == who+ || (who.len() >= 6 && m.endpoint.to_string().starts_with(who))+ }}).map(|m| (m.endpoint, m.person.clone(), m.machine.clone())).collect();@@ -467,8 +497,11 @@ impl Daemon {};let me = self.key.public();let online = |id: &EndpointId| self.net().is_some_and(|n| n.is_online(id));- let away: Vec<String> =- state.active().filter(|m| m.endpoint != me && !online(&m.endpoint)).map(|m| format!("{}/{}", m.person, m.machine)).collect();+ let away: Vec<String> = state+ .active()+ .filter(|m| m.endpoint != me && !online(&m.endpoint))+ .map(|m| format!("{}/{}", m.person, m.machine))+ .collect();if let Some(net) = self.net() {net.broadcast(&Wire::State { state: Box::new(state) });tokio::time::sleep(Duration::from_millis(800)).await;@@ -481,7 +514,10 @@ impl Daemon {let mut out = format!("{now} Team links from before stop working: `tincan link` shows the new one.");// A machine that is off can't hear about it, and won't find the team where it looks when it's back.if !away.is_empty() {- out += &format!("\nOffline now: {}. When back, each needs `{cmd}` too, unless it already uses that relay.", away.join(", "));+ out += &format!(+ "\nOffline now: {}. When back, each needs `{cmd}` too, unless it already uses that relay.",+ away.join(", ")+ );}Ok(out)}diff --git a/src/daemon/update.rs b/src/daemon/update.rsindex 7a192ab..d31ac65 100644--- a/src/daemon/update.rs+++ b/src/daemon/update.rs@@ -40,7 +40,10 @@ async fn update() -> Result<Option<String>> {}let dir = crate::util::current_exe()?.parent().map(|d| d.to_path_buf()).unwrap_or_default();let mut cmd = tokio::process::Command::from(crate::installer(&dir));- cmd.stdin(std::process::Stdio::null()).stdout(std::process::Stdio::piped()).stderr(std::process::Stdio::piped()).kill_on_drop(true);+ cmd.stdin(std::process::Stdio::null())+ .stdout(std::process::Stdio::piped())+ .stderr(std::process::Stdio::piped())+ .kill_on_drop(true);// In its own process group, so a timeout kills the whole pipeline (curl and the inner sh too). (On Windows the// installer is one PowerShell, which `kill_on_drop` ends.)#[cfg(unix)]@@ -66,7 +69,8 @@ async fn update() -> Result<Option<String>> {let installed = dir.join(format!("tincan{}", std::env::consts::EXE_SUFFIX));let installed = tokio::process::Command::new(installed).arg("--version").kill_on_drop(true).output();let installed = tokio::time::timeout(Duration::from_secs(30), installed).await??;- let installed = String::from_utf8_lossy(&installed.stdout).trim().rsplit(' ').next().unwrap_or_default().to_string();+ let installed =+ String::from_utf8_lossy(&installed.stdout).trim().rsplit(' ').next().unwrap_or_default().to_string();if !newer(&installed, env!("CARGO_PKG_VERSION")) {bail!("the latest release installed as {installed:?}, which is not newer than this one; not restarting");}@@ -78,7 +82,16 @@ async fn latest_version() -> Result<String> {let repo = std::env::var("TINCAN_REPO").unwrap_or_else(|_| "larstalian/tincan".into());let null = if cfg!(windows) { "NUL" } else { "/dev/null" };let out = tokio::process::Command::new("curl")- .args(["-fsSLI", "--max-time", "50", "-o", null, "-w", "%{url_effective}", &format!("https://github.com/{repo}/releases/latest")])+ .args([+ "-fsSLI",+ "--max-time",+ "50",+ "-o",+ null,+ "-w",+ "%{url_effective}",+ &format!("https://github.com/{repo}/releases/latest"),+ ]).stdin(std::process::Stdio::null()).kill_on_drop(true).output();diff --git a/src/doing.rs b/src/doing.rsindex 9f3c6e9..502cefe 100644--- a/src/doing.rs+++ b/src/doing.rs@@ -29,7 +29,8 @@ pub struct Source {/// `title · task in progress`, either alone, or nothing.pub fn of(s: &Source) -> Option<String> {let claude = s.agent == agent::CLAUDE_CODE;- let transcript = s.transcript.clone().or_else(|| claude.then(|| claude_transcript(s.session.as_deref()?)).flatten());+ let transcript =+ s.transcript.clone().or_else(|| claude.then(|| claude_transcript(s.session.as_deref()?)).flatten());let seen = transcript.as_deref().map(scan).unwrap_or_default();let task = claude.then(|| claude_task(s.session.as_deref()?)).flatten().or(seen.task.flatten());let title = seen.title.or_else(|| (s.agent == "codex").then(|| codex_title(s.session.as_deref()?)).flatten());@@ -109,7 +110,12 @@ fn scan(path: &Path) -> Seen {let Ok(meta) = std::fs::metadata(path) else { return Seen::default() };let (len, modified) = (meta.len(), meta.modified().ok());let mut tails = TAILS.get_or_init(Default::default).lock().unwrap();- let t = tails.entry(path.to_path_buf()).or_insert(Tail { modified: None, offset: 0, whole: false, seen: Seen::default() });+ let t = tails.entry(path.to_path_buf()).or_insert(Tail {+ modified: None,+ offset: 0,+ whole: false,+ seen: Seen::default(),+ });// Nothing new to read (by its length too: Windows' file times are too coarse to tell appends apart).if t.modified == modified && t.offset == len {return t.seen.clone();@@ -173,7 +179,9 @@ fn claude_task(session: &str) -> Option<String> {.filter_map(|e| serde_json::from_slice::<Value>(&std::fs::read(e.path()).ok()?).ok()).filter(in_progress).max_by_key(|t| t.get("id").and_then(Value::as_str).and_then(|i| i.parse::<u64>().ok()))- .and_then(|t| ["activeForm", "subject"].iter().find_map(|k| t.get(*k).and_then(Value::as_str)).map(str::to_string))+ .and_then(|t| {+ ["activeForm", "subject"].iter().find_map(|k| t.get(*k).and_then(Value::as_str)).map(str::to_string)+ })}/// Codex names its threads in `~/.codex/session_index.jsonl` (appended to; the last entry wins).@@ -181,7 +189,9 @@ fn codex_title(thread: &str) -> Option<String> {/// Thread names as of the file's modification time.type Names = (Option<SystemTime>, HashMap<String, String>);static INDEX: OnceLock<Mutex<Names>> = OnceLock::new();- let path = std::env::var_os("CODEX_HOME").map_or_else(|| paths::user_home().join(".codex"), PathBuf::from).join("session_index.jsonl");+ let path = std::env::var_os("CODEX_HOME")+ .map_or_else(|| paths::user_home().join(".codex"), PathBuf::from)+ .join("session_index.jsonl");let modified = std::fs::metadata(&path).and_then(|m| m.modified()).ok()?;let mut index = INDEX.get_or_init(Default::default).lock().unwrap();if index.0 != Some(modified) {@@ -190,9 +200,10 @@ fn codex_title(thread: &str) -> Option<String> {file.seek(SeekFrom::Start(len.saturating_sub(1 << 20))).ok()?;let mut text = String::new();file.read_to_string(&mut text).ok()?;- let names = text.lines().filter_map(|l| serde_json::from_str::<Value>(l).ok()).filter_map(|v| {- Some((v.get("id")?.as_str()?.to_string(), v.get("thread_name")?.as_str()?.to_string()))- });+ let names = text+ .lines()+ .filter_map(|l| serde_json::from_str::<Value>(l).ok())+ .filter_map(|v| Some((v.get("id")?.as_str()?.to_string(), v.get("thread_name")?.as_str()?.to_string())));*index = (Some(modified), names.collect());}index.1.get(thread).cloned()@@ -240,7 +251,11 @@ mod tests {let p = dir.join("t.jsonl");std::fs::write(&p, "{\"type\":\"ai-title\",\"aiTitle\":\"First\"}\n{\"partial\":").unwrap();assert_eq!(scan(&p).title.as_deref(), Some("First"));- std::fs::write(&p, "{\"type\":\"ai-title\",\"aiTitle\":\"First\"}\n{\"type\":\"ai-title\",\"aiTitle\":\"Second\"}\n").unwrap();+ std::fs::write(+ &p,+ "{\"type\":\"ai-title\",\"aiTitle\":\"First\"}\n{\"type\":\"ai-title\",\"aiTitle\":\"Second\"}\n",+ )+ .unwrap();assert_eq!(scan(&p).title.as_deref(), Some("Second"));// Gemini: one JSON document, rewritten.let g = dir.join("chat.json");diff --git a/src/hook.rs b/src/hook.rsindex 0194ed4..92c11f7 100644--- a/src/hook.rs+++ b/src/hook.rs@@ -13,7 +13,8 @@ pub async fn run(agent_name: &str, event: &str, session: Option<String>, state:let input = if session.is_none() { read_stdin(Duration::from_secs(3)) } else { String::new() };let link = Link::new(None);let Ok(Some((out, key, ids))) =- tokio::time::timeout(Duration::from_secs(8), handle(&link, agent_name, event, &input, session, state, doing)).await+ tokio::time::timeout(Duration::from_secs(8), handle(&link, agent_name, event, &input, session, state, doing))+ .awaitelse {return;};@@ -50,10 +51,15 @@ async fn handle(let agent = agent::from_client_name(agent_name).unwrap_or(agent_name);let str_at = |k: &str| v.get(k).and_then(Value::as_str).filter(|s| !s.is_empty()).map(str::to_string);- let session_id = session.or_else(|| str_at("session_id")).or_else(|| str_at("conversation_id")).or_else(|| str_at("sessionId"))?;+ let session_id = session+ .or_else(|| str_at("session_id"))+ .or_else(|| str_at("conversation_id"))+ .or_else(|| str_at("sessionId"))?;let cwd = str_at("cwd").or_else(|| v["workspace_roots"][0].as_str().map(str::to_string))- .or_else(|| ["CURSOR_PROJECT_DIR", "GEMINI_CWD", "CLAUDE_PROJECT_DIR"].iter().find_map(|k| std::env::var(k).ok()))+ .or_else(|| {+ ["CURSOR_PROJECT_DIR", "GEMINI_CWD", "CLAUDE_PROJECT_DIR"].iter().find_map(|k| std::env::var(k).ok())+ }).or_else(|| std::env::current_dir().ok().map(|p| p.display().to_string()));let ev = match (event, state.as_deref()) {("session-start", _) => "start",@@ -118,7 +124,15 @@ fn format_for(agent: &str, event: &str, ev: &str, text: &str) -> String {if !cfg!(windows) {return out;}- out.chars().map(|c| if c.is_ascii() { c.to_string() } else { c.encode_utf16(&mut [0; 2]).iter().map(|u| format!("\\u{u:04x}")).collect() }).collect()+ out.chars()+ .map(|c| {+ if c.is_ascii() {+ c.to_string()+ } else {+ c.encode_utf16(&mut [0; 2]).iter().map(|u| format!("\\u{u:04x}")).collect()+ }+ })+ .collect()}#[cfg(test)]diff --git a/src/invite.rs b/src/invite.rsindex 2daf46f..3d64748 100644--- a/src/invite.rs+++ b/src/invite.rs@@ -34,8 +34,11 @@ pub fn generate() -> String {/// `Plum Tiger lake-ORBIT` -> `plum-tiger-lake-orbit`, if it is four known words.pub fn normalize(input: &str) -> Option<String> {let words = words();- let parts: Vec<String> =- input.split(|c: char| !c.is_ascii_alphabetic()).filter(|p| !p.is_empty()).map(|p| p.to_ascii_lowercase()).collect();+ let parts: Vec<String> = input+ .split(|c: char| !c.is_ascii_alphabetic())+ .filter(|p| !p.is_empty())+ .map(|p| p.to_ascii_lowercase())+ .collect();(parts.len() == LEN && parts.iter().all(|p| words.contains(&p.as_str()))).then(|| parts.join("-"))}diff --git a/src/ipc.rs b/src/ipc.rsindex 4b9f2f2..ae1cbde 100644--- a/src/ipc.rs+++ b/src/ipc.rs@@ -28,7 +28,11 @@ pub async fn connect() -> io::Result<Stream> {let pipe = loop {match ClientOptions::new().open(paths::socket()) {// Every instance is taken for a moment while the daemon opens the next one.- Err(e) if e.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PIPE_BUSY as i32) && tries < 20 => tries += 1,+ Err(e)+ if e.raw_os_error() == Some(windows_sys::Win32::Foundation::ERROR_PIPE_BUSY as i32) && tries < 20 =>+ {+ tries += 1+ }r => break r?,}tokio::time::sleep(std::time::Duration::from_millis(25)).await;diff --git a/src/main.rs b/src/main.rsindex 247b261..550161d 100644--- a/src/main.rs+++ b/src/main.rs@@ -245,7 +245,9 @@ async fn main() -> Result<()> {return wizard::guided(wizard::onboard(None, None, None, None)).await;}if !in_team {- println!("Not in a team yet. Run `tincan` in a terminal to get set up (or `tincan init <team>` / `tincan join <code>`).");+ println!(+ "Not in a team yet. Run `tincan` in a terminal to get set up (or `tincan init <team>` / `tincan join <code>`)."+ );return Ok(());}cli(Cmd::Who { filter: None, all: false, json: false }).await@@ -284,7 +286,9 @@ async fn cli(cmd: Cmd) -> Result<()> {// Like other command-line tools, stop quietly when whatever reads our output goes away. (`listen` marks// messages read only after printing them, so nothing is lost.)#[cfg(unix)]- unsafe { libc::signal(libc::SIGPIPE, libc::SIG_DFL) };+ unsafe {+ libc::signal(libc::SIGPIPE, libc::SIG_DFL)+ };let link = Link::new(None);match cmd {Cmd::Who { filter, all, json } => {@@ -306,7 +310,13 @@ async fn cli(cmd: Cmd) -> Result<()> {}// Messages come from agent sessions: `--from`'s, this agent's, or from a plain terminal, `<you>/terminal`.// An agent shell tincan doesn't know (its tools aren't loaded) counts as a terminal.- let send = |from: String| Request::Send { from, to: to.clone(), body: body.clone(), reply_to: reply_to.clone(), wake: !fyi };+ let send = |from: String| Request::Send {+ from,+ to: to.clone(),+ body: body.clone(),+ reply_to: reply_to.clone(),+ wake: !fyi,+ };let explicit = from.is_some();let r: SendResult = match from.or_else(current_session) {Some(f) => match link.call(send(f)).await {@@ -349,8 +359,11 @@ async fn cli(cmd: Cmd) -> Result<()> {wizard::guided(wizard::setup_agents()).await?}Cmd::Init { team, person, no_setup, relay } => {- let Some(team) = team else { bail!("name the team: `tincan init <team>` (or run it in a terminal to be asked)") };- let t: TeamInfo = link.call(Request::CreateTeam { name: team, person: default_person(person), relay }).await?;+ let Some(team) = team else {+ bail!("name the team: `tincan init <team>` (or run it in a terminal to be asked)")+ };+ let t: TeamInfo =+ link.call(Request::CreateTeam { name: team, person: default_person(person), relay }).await?;wait_exit(daemon_pid()).await;println!("Created team {}. You are {} on {}.", t.name, t.person, t.machine);if !no_setup {@@ -389,10 +402,17 @@ async fn cli(cmd: Cmd) -> Result<()> {let [unix, windows] = install_lines(&i.code);println!("They run this, which installs tincan and joins the team (the second line on Windows):\n");println!(" {unix}\n {windows}\n");- println!("(or `tincan join {}` if they have tincan). Works once, within {}h, while this machine is online.", i.code, i.hours);+ println!(+ "(or `tincan join {}` if they have tincan). Works once, within {}h, while this machine is online.",+ i.code, i.hours+ );println!("If this machine will be offline, use the long form instead: tincan join {}", i.ticket);if me {- println!("\nFor a cloud agent of yours (Grok Bot, Dots, Muse, …), send it: join my tincan team as {}: {}", default_person(None), join_url(&i.ticket));+ println!(+ "\nFor a cloud agent of yours (Grok Bot, Dots, Muse, …), send it: join my tincan team as {}: {}",+ default_person(None),+ join_url(&i.ticket)+ );}}Cmd::Listen { name, wait } => {@@ -438,9 +458,7 @@ async fn cli(cmd: Cmd) -> Result<()> {println!("`tincan approve <id>` delivers, `tincan reject <id>` drops (or --all).");}}- Cmd::Approve { ids, all } | Cmd::Reject { ids, all }- if ids.is_empty() && !all =>- {+ Cmd::Approve { ids, all } | Cmd::Reject { ids, all } if ids.is_empty() && !all => {bail!("give message ids, or --all")}Cmd::Approve { ids, .. } => {diff --git a/src/mcp.rs b/src/mcp.rsindex 36be83d..aab08fb 100644--- a/src/mcp.rs+++ b/src/mcp.rs@@ -133,7 +133,9 @@ impl TincanMcp {Ok(self.finish(&key, res, true).await)}- #[tool(description = "Send a message to a teammate's agent session, all of a person's sessions, everyone in a repo, or everyone.")]+ #[tool(+ description = "Send a message to a teammate's agent session, all of a person's sessions, everyone in a repo, or everyone."+ )]async fn send_message(&self,Parameters(a): Parameters<SendArgs>,@@ -207,9 +209,10 @@ impl TincanMcp {if let Some(a) = *self.client_agent.lock().unwrap() {return a;}- let name = peer.peer_info().map(|i| i.client_info.name.clone()).or_else(|| {- meta?.get("io.modelcontextprotocol/clientInfo")?.get("name")?.as_str().map(str::to_string)- });+ let name = peer+ .peer_info()+ .map(|i| i.client_info.name.clone())+ .or_else(|| meta?.get("io.modelcontextprotocol/clientInfo")?.get("name")?.as_str().map(str::to_string));match name.as_deref().and_then(agent::from_client_name) {Some(a) => {*self.client_agent.lock().unwrap() = Some(a);@@ -228,7 +231,8 @@ impl TincanMcp {async fn session(&self, agent: &'static str, meta_id: Option<String>) -> Result<String> {if meta_id.is_none()&& agent::multiplexed(agent)- && let Ok(Some(key)) = self.link.call::<Option<String>>(Request::Attach { agent: agent.into(), cwd: agent::cwd() }).await+ && let Ok(Some(key)) =+ self.link.call::<Option<String>>(Request::Attach { agent: agent.into(), cwd: agent::cwd() }).await{return Ok(key);}diff --git a/src/net.rs b/src/net.rsindex 0216d07..215ad9b 100644--- a/src/net.rs+++ b/src/net.rs@@ -119,7 +119,8 @@ pub async fn bind(key: SecretKey, relay: Option<&str>, lan: bool) -> Result<Endp};// The team's own relay and nothing of n0's: none of its relays, no publishing or looking up addresses in its DNS.// Teammates are dialed through the relay instead.- let url: RelayUrl = url.parse().map_err(|_| anyhow!("not a relay url: {url} (expected e.g. https://relay.example.com)"))?;+ let url: RelayUrl =+ url.parse().map_err(|_| anyhow!("not a relay url: {url} (expected e.g. https://relay.example.com)"))?;let mut b = Endpoint::builder(presets::Minimal).secret_key(key.clone()).relay_mode(RelayMode::custom([url]));if lan {b = b.address_lookup(NoRelays(MdnsAddressLookup::builder().build(key.public())?));@@ -220,7 +221,10 @@ pub async fn join(endpoint: &Endpoint, peers: &[EndpointAddr], req: &JoinRequest/// Nothing is known yet about where that machine is.fn unpublished(e: &anyhow::Error) -> bool {- matches!(e.downcast_ref::<ConnectError>(), Some(ConnectError::Connect { source: ConnectWithOptsError::NoAddress { .. }, .. }))+ matches!(+ e.downcast_ref::<ConnectError>(),+ Some(ConnectError::Connect { source: ConnectWithOptsError::NoAddress { .. }, .. })+ )}#[derive(Debug, Clone)]@@ -296,7 +300,12 @@ impl ProtocolHandler for JoinProto {}impl Net {- pub fn start(daemon: &Arc<Daemon>, endpoint: Endpoint, relay: Option<&str>, remote: HashMap<EndpointId, Remote>) -> Arc<Net> {+ pub fn start(+ daemon: &Arc<Daemon>,+ endpoint: Endpoint,+ relay: Option<&str>,+ remote: HashMap<EndpointId, Remote>,+ ) -> Arc<Net> {let net = Arc::new_cyclic(|weak: &Weak<Net>| Net {me: endpoint.id(),router: Mutex::new(Some(@@ -352,7 +361,13 @@ impl Net {}/// Listens for a joiner on an invite code's own key until `expires` (ms) or until it is used.- pub async fn listen_invite(self: &Arc<Self>, key: SecretKey, expires: i64, relay: Option<&str>, lan: bool) -> Result<()> {+ pub async fn listen_invite(+ self: &Arc<Self>,+ key: SecretKey,+ expires: i64,+ relay: Option<&str>,+ lan: bool,+ ) -> Result<()> {let endpoint = bind(key, relay, lan).await?;let id = endpoint.id();let router = Router::builder(endpoint).accept(JOIN_ALPN, JoinProto(Arc::downgrade(self), Some(id))).spawn();@@ -663,6 +678,12 @@ fn tidy_presence(mut p: Presence) -> Presence {s.doing = s.doing.as_deref().map(|d| line(d, 200)).filter(|d| !d.is_empty());}p.sessions.retain(|s| !s.name.is_empty());- p.known = p.known.iter().take(100).map(|n| util::slug(n).chars().take(64).collect()).filter(|n: &String| !n.is_empty()).collect();+ p.known = p+ .known+ .iter()+ .take(100)+ .map(|n| util::slug(n).chars().take(64).collect())+ .filter(|n: &String| !n.is_empty())+ .collect();p}diff --git a/src/paths.rs b/src/paths.rsindex 7ef61ca..d41036f 100644--- a/src/paths.rs+++ b/src/paths.rs@@ -4,7 +4,9 @@use std::path::{Path, PathBuf};pub fn user_home() -> PathBuf {- std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" }).map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/"))+ std::env::var_os(if cfg!(windows) { "USERPROFILE" } else { "HOME" })+ .map(PathBuf::from)+ .unwrap_or_else(|| PathBuf::from("/"))}pub fn home() -> PathBuf {@@ -30,7 +32,10 @@ pub fn socket() -> PathBuf {/// FNV-1a: stable across builds, unlike `DefaultHasher`.fn hash(path: &Path) -> u64 {- path.as_os_str().as_encoded_bytes().iter().fold(0xcbf29ce484222325u64, |h, &b| (h ^ b as u64).wrapping_mul(0x100000001b3))+ path.as_os_str()+ .as_encoded_bytes()+ .iter()+ .fold(0xcbf29ce484222325u64, |h, &b| (h ^ b as u64).wrapping_mul(0x100000001b3))}#[cfg(unix)]diff --git a/src/render.rs b/src/render.rsindex 420eb70..18a2df5 100644--- a/src/render.rs+++ b/src/render.rs@@ -68,8 +68,9 @@ pub fn directory(d: &Directory, agent: bool, paint: Paint) -> String {let mut quiet = Vec::new();let mut shown = vec![false; d.sessions.len()];for m in &d.machines {- let rows: Vec<usize> =- (0..d.sessions.len()).filter(|&i| d.sessions[i].person == m.person && d.sessions[i].machine == m.machine).collect();+ let rows: Vec<usize> = (0..d.sessions.len())+ .filter(|&i| d.sessions[i].person == m.person && d.sessions[i].machine == m.machine)+ .collect();rows.iter().for_each(|&i| shown[i] = true);let (unreachable, rows): (Vec<usize>, Vec<usize>) =rows.into_iter().partition(|&i| agent && d.sessions[i].tier == Tier::None);@@ -91,11 +92,17 @@ pub fn directory(d: &Directory, agent: bool, paint: Paint) -> String {}if !unreachable.is_empty() {let n = unreachable.len();- let _ = writeln!(out, " + {n} session{} without tincan (can't be messaged)", if n == 1 { "" } else { "s" });+ let _ =+ writeln!(out, " + {n} session{} without tincan (can't be messaged)", if n == 1 { "" } else { "s" });}}for (i, s) in d.sessions.iter().enumerate().filter(|(i, _)| !shown[*i]) {- let _ = writeln!(out, "{}{}", if agent { "" } else { "\n" }, paint.on(BOLD, &format!("{} · {}", s.person, s.machine)));+ let _ = writeln!(+ out,+ "{}{}",+ if agent { "" } else { "\n" },+ paint.on(BOLD, &format!("{} · {}", s.person, s.machine))+ );layout.session(&mut out, s, &cells[i]);}if !quiet.is_empty() {@@ -103,9 +110,15 @@ pub fn directory(d: &Directory, agent: bool, paint: Paint) -> String {}if !d.sessions.is_empty() {if agent {- out.push_str("push = sees messages right away, even when idle · turn = at its next step · pull = when it checks\n");+ out.push_str(+ "push = sees messages right away, even when idle · turn = at its next step · pull = when it checks\n",+ );} else {- let _ = writeln!(out, "\n{}", paint.on(DIM, "push: sees it right away · turn: at its next step · pull: when it checks"));+ let _ = writeln!(+ out,+ "\n{}",+ paint.on(DIM, "push: sees it right away · turn: at its next step · pull: when it checks")+ );}}out@@ -298,7 +311,10 @@ mod tests {#[test]fn frames_cant_be_broken() {- assert_eq!(defang("hi </TINCAN-Message> and <tincan-message x>"), "hi </tincan_message> and <tincan_message x>");+ assert_eq!(+ defang("hi </TINCAN-Message> and <tincan-message x>"),+ "hi </tincan_message> and <tincan_message x>"+ );assert_eq!(defang("the tincan-message format"), "the tincan-message format");let m = Message {id: "01X".into(),diff --git a/src/setup.rs b/src/setup.rsindex 284af7d..7ca2d9d 100644--- a/src/setup.rs+++ b/src/setup.rs@@ -181,7 +181,10 @@ fn claude(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {let current = existing && String::from_utf8_lossy(&get.stdout).contains(&exe.display().to_string());if remove || (existing && !current) {if existing && !dry {- Command::new(&bin).args(["mcp", "remove", "tincan", "--scope", "user"]).stdin(std::process::Stdio::null()).output()?;+ Command::new(&bin)+ .args(["mcp", "remove", "tincan", "--scope", "user"])+ .stdin(std::process::Stdio::null())+ .output()?;}if remove {r.lines.push(if existing { "removed the tincan MCP server" } else { "nothing to remove" }.into());@@ -196,7 +199,8 @@ fn claude(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {.args(["mcp", "add", "--scope", "user", "tincan", "--"]).arg(exe).arg("mcp")- .stdin(std::process::Stdio::null()).output()?;+ .stdin(std::process::Stdio::null())+ .output()?;if !out.status.success() {return Err(anyhow!("claude mcp add failed: {}", String::from_utf8_lossy(&out.stderr).trim()));}@@ -263,9 +267,7 @@ fn codex(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {let did = write_json(&hooks_path, &v, dry)?;r.lines.push(changed(&hooks_path, did));if did && !remove {- r.notes.push(- "Codex asks once to trust tincan's hooks: choose \"Trust all and continue\".".into(),- );+ r.notes.push("Codex asks once to trust tincan's hooks: choose \"Trust all and continue\".".into());}Ok(Some(r))}@@ -328,9 +330,7 @@ fn gemini(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {json!({ "command": exe.display().to_string(), "args": ["mcp"], "env": { "TINCAN_AGENT": "gemini" }, "timeout": 660000, "trust": true }),);}- let group = |event: &str, timeout: u64| {- json!({ "matcher": "*", "hooks": [{ "type": "command", "name": format!("tincan-{event}"), "command": shell_cmd(exe, &format!("hook gemini {event}")), "timeout": timeout }] })- };+ let group = |event: &str, timeout: u64| json!({ "matcher": "*", "hooks": [{ "type": "command", "name": format!("tincan-{event}"), "command": shell_cmd(exe, &format!("hook gemini {event}")), "timeout": timeout }] });let groups = vec![("SessionStart", group("session-start", 10000)),("BeforeAgent", group("user-prompt-submit", 10000)),@@ -427,7 +427,8 @@ fn opencode(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {r.lines.push(format!("removed {}", crate::util::tilde(&plugin.display().to_string())));}} else {- let code = include_str!("opencode-plugin.ts").replace("__TINCAN_EXE__", &exe.display().to_string().replace('\\', "\\\\").replace('"', "\\\""));+ let code = include_str!("opencode-plugin.ts")+ .replace("__TINCAN_EXE__", &exe.display().to_string().replace('\\', "\\\\").replace('"', "\\\""));r.lines.push(changed(&plugin, write_file(&plugin, &code, dry)?));}Ok(Some(r))@@ -451,7 +452,8 @@ fn pi(exe: &Path, remove: bool, dry: bool) -> Result<Option<Report>> {r.lines.push(format!("removed {}", crate::util::tilde(&ext.display().to_string())));}} else {- let code = include_str!("pi-extension.ts").replace("__TINCAN_EXE__", &exe.display().to_string().replace('\\', "\\\\").replace('"', "\\\""));+ let code = include_str!("pi-extension.ts")+ .replace("__TINCAN_EXE__", &exe.display().to_string().replace('\\', "\\\\").replace('"', "\\\""));r.lines.push(changed(&ext, write_file(&ext, &code, dry)?));}Ok(Some(r))@@ -492,9 +494,15 @@ pub fn service_installed() -> bool {pub fn start_service() -> bool {let out = if cfg!(target_os = "macos") {let uid = unsafe { libc::getuid() };- Command::new("launchctl").args(["kickstart", &format!("gui/{uid}/{}", service_name())]).stdin(std::process::Stdio::null()).output()+ Command::new("launchctl")+ .args(["kickstart", &format!("gui/{uid}/{}", service_name())])+ .stdin(std::process::Stdio::null())+ .output()} else {- Command::new("systemctl").args(["--user", "start", &format!("{}.service", service_name())]).stdin(std::process::Stdio::null()).output()+ Command::new("systemctl")+ .args(["--user", "start", &format!("{}.service", service_name())])+ .stdin(std::process::Stdio::null())+ .output()};out.is_ok_and(|o| o.status.success())}@@ -512,7 +520,9 @@ fn service_path() -> PathBuf {#[cfg(unix)]fn service_path_env() -> String {let h = home().display().to_string();- format!("{h}/.local/bin:{h}/.bun/bin:{h}/.npm-global/bin:{h}/.cargo/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin")+ format!(+ "{h}/.local/bin:{h}/.bun/bin:{h}/.npm-global/bin:{h}/.cargo/bin:/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin"+ )}#[cfg(unix)]@@ -524,12 +534,15 @@ async fn service(exe: &Path, remove: bool, dry: bool) -> Result<String> {let target = format!("gui/{uid}/{}", service_name());if remove {if !dry {- let _ = Command::new("launchctl").args(["bootout", &target]).stdin(std::process::Stdio::null()).output();+ let _ =+ Command::new("launchctl").args(["bootout", &target]).stdin(std::process::Stdio::null()).output();let _ = std::fs::remove_file(&path);}return Ok("removed the login service".into());}- let home_env = tincan_home.map(|h| format!("\n <key>TINCAN_HOME</key><string>{}</string>", xml(&h))).unwrap_or_default();+ let home_env = tincan_home+ .map(|h| format!("\n <key>TINCAN_HOME</key><string>{}</string>", xml(&h)))+ .unwrap_or_default();let plist = format!(r#"<?xml version="1.0" encoding="UTF-8"?><!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">@@ -554,20 +567,35 @@ async fn service(exe: &Path, remove: bool, dry: bool) -> Result<String> {xml(&service_path_env()),);let did = write_file(&path, &plist, dry)?;- let loaded = Command::new("launchctl").args(["print", &target]).stdin(std::process::Stdio::null()).output().is_ok_and(|o| o.status.success());+ let loaded = Command::new("launchctl")+ .args(["print", &target])+ .stdin(std::process::Stdio::null())+ .output()+ .is_ok_and(|o| o.status.success());if !dry && (did || !loaded) {let _ = Command::new("launchctl").args(["bootout", &target]).stdin(std::process::Stdio::null()).output();crate::stop_daemon().await;- let out = Command::new("launchctl").args(["bootstrap", &format!("gui/{uid}")]).arg(&path).stdin(std::process::Stdio::null()).output()?;+ let out = Command::new("launchctl")+ .args(["bootstrap", &format!("gui/{uid}")])+ .arg(&path)+ .stdin(std::process::Stdio::null())+ .output()?;if !out.status.success() {return Err(anyhow!("launchctl bootstrap: {}", String::from_utf8_lossy(&out.stderr).trim()));}}- Ok(if did || !loaded { "installed the login service (launchd)".into() } else { "login service already running".into() })+ Ok(if did || !loaded {+ "installed the login service (launchd)".into()+ } else {+ "login service already running".into()+ })} else {if remove {if !dry {- let _ = Command::new("systemctl").args(["--user", "disable", "--now", &format!("{}.service", service_name())]).stdin(std::process::Stdio::null()).output();+ let _ = Command::new("systemctl")+ .args(["--user", "disable", "--now", &format!("{}.service", service_name())])+ .stdin(std::process::Stdio::null())+ .output();let _ = std::fs::remove_file(&path);}return Ok("removed the login service".into());@@ -593,14 +621,18 @@ async fn service(exe: &Path, remove: bool, dry: bool) -> Result<String> {paths::ensure_home()?;crate::stop_daemon().await;Command::new("systemctl").args(["--user", "daemon-reload"]).stdin(std::process::Stdio::null()).output()?;- let out = Command::new("systemctl").args(["--user", "enable", "--now", &format!("{}.service", service_name())]).stdin(std::process::Stdio::null()).output()?;+ let out = Command::new("systemctl")+ .args(["--user", "enable", "--now", &format!("{}.service", service_name())])+ .stdin(std::process::Stdio::null())+ .output()?;if !out.status.success() {let _ = std::fs::remove_file(&path);return Err(anyhow!("systemctl: {}", String::from_utf8_lossy(&out.stderr).trim()));}// Keep running after logout (servers, SSH boxes). Best effort: some systems want a password.if let Ok(user) = std::env::var("USER") {- let _ = Command::new("loginctl").args(["enable-linger", &user]).stdin(std::process::Stdio::null()).output();+ let _ =+ Command::new("loginctl").args(["enable-linger", &user]).stdin(std::process::Stdio::null()).output();}}Ok(if did { "installed the login service (systemd --user)".into() } else { "login service already set".into() })@@ -632,7 +664,11 @@ pub fn start_service() -> bool {/// Our Run entry, as `reg query` shows it.#[cfg(windows)]fn run_entry() -> Option<String> {- let out = Command::new("reg").args(["query", RUN_KEY, "/v", &service_name()]).stdin(std::process::Stdio::null()).output().ok()?;+ let out = Command::new("reg")+ .args(["query", RUN_KEY, "/v", &service_name()])+ .stdin(std::process::Stdio::null())+ .output()+ .ok()?;out.status.success().then(|| String::from_utf8_lossy(&out.stdout).into_owned())}@@ -696,8 +732,13 @@ const AGENTS: [Agent; 8] = [hint: "messages arrive instantly",installed: || agent::find_bin("claude").is_some(),wired: |_| {- agent::find_bin("claude")- .is_some_and(|b| Command::new(b).args(["mcp", "get", "tincan"]).stdin(std::process::Stdio::null()).output().is_ok_and(|o| o.status.success()))+ agent::find_bin("claude").is_some_and(|b| {+ Command::new(b)+ .args(["mcp", "get", "tincan"])+ .stdin(std::process::Stdio::null())+ .output()+ .is_ok_and(|o| o.status.success())+ })},apply: claude,},@@ -707,7 +748,10 @@ const AGENTS: [Agent; 8] = [hint: "instant; asks once to trust the hooks",installed: || agent::find_bin("codex").is_some() || codex_home().exists(),// TOML keeps a Windows path as it is ('C:\…').- wired: |exe| has(codex_home().join("config.toml"), &exe.display().to_string()) && has(codex_home().join("hooks.json"), "hook codex"),+ wired: |exe| {+ has(codex_home().join("config.toml"), &exe.display().to_string())+ && has(codex_home().join("hooks.json"), "hook codex")+ },apply: codex,},Agent {@@ -830,10 +874,18 @@ pub async fn apply(exe: &Path, install: &[&str], remove: &[&str], service: Optiopub async fn run(dry: bool, remove: bool, no_service: bool) -> Result<()> {let exe = exe()?;let found = detect(&exe);- let verb = if dry { "Would change" } else if remove { "Removing tincan" } else { "Setting up tincan" };+ let verb = if dry {+ "Would change"+ } else if remove {+ "Removing tincan"+ } else {+ "Setting up tincan"+ };println!("{verb} ({}):", crate::util::tilde(&exe.display().to_string()));if found.is_empty() && !remove {- println!(" no supported agents found (Claude Code, Codex, Cursor, Gemini CLI, Copilot CLI, opencode, pi, Reason)");+ println!(+ " no supported agents found (Claude Code, Codex, Cursor, Gemini CLI, Copilot CLI, opencode, pi, Reason)"+ );}let ids: Vec<&str> = found.iter().map(|f| f.id).collect();let (install, removing): (&[&str], &[&str]) = if remove { (&[], &ids) } else { (&ids, &[]) };@@ -864,12 +916,18 @@ pub async fn doctor() -> Result<()> {if let Some(relay) = &t.relay&& t.relay_connected == Some(false){- println!(" ! can't reach the team's relay {relay}: until it's up, teammates are only found on this network");+ println!(+ " ! can't reach the team's relay {relay}: until it's up, teammates are only found on this network"+ );}if others > 0 && online == 0 {- println!(" ! no teammate connected: check your internet, or that their machines are on (`tincan doctor` there)");+ println!(+ " ! no teammate connected: check your internet, or that their machines are on (`tincan doctor` there)"+ );// Nothing tells a machine that was off when the team changed relays where the team went.- println!(" ! if the team changed relays while this machine was off, set the same one here: `tincan relay <url>`");+ println!(+ " ! if the team changed relays while this machine was off, set the same one here: `tincan relay <url>`"+ );println!(" (or `default` for n0's); `tincan team` on a teammate's machine shows which");}}@@ -906,8 +964,14 @@ mod tests {"PostToolUse": [{ "matcher": "*", "hooks": [{ "type": "command", "command": "/x/tincan hook codex post-tool-use" }] }],})).unwrap();- let ours = |e: &str| json!({ "hooks": [{ "type": "command", "command": format!("/y/tincan hook codex {e} ") }] });- merge_hook_groups(&mut hooks, "codex", vec![("Stop", ours("stop")), ("PostToolUse", ours("post-tool-use"))], false);+ let ours =+ |e: &str| json!({ "hooks": [{ "type": "command", "command": format!("/y/tincan hook codex {e} ") }] });+ merge_hook_groups(+ &mut hooks,+ "codex",+ vec![("Stop", ours("stop")), ("PostToolUse", ours("post-tool-use"))],+ false,+ );assert_eq!(hooks["Stop"].as_array().unwrap().len(), 2, "keeps other tools' hooks");assert_eq!(hooks["PostToolUse"].as_array().unwrap().len(), 1, "replaces the old tincan hook");merge_hook_groups(&mut hooks, "codex", vec![], true);@@ -925,8 +989,14 @@ mod tests {#[test]#[cfg(windows)]fn quoting() {- assert_eq!(shell_cmd(Path::new(r"C:\Users\alex\.local\bin\tincan.exe"), "mcp"), r"C:\Users\alex\.local\bin\tincan.exe mcp");- assert_eq!(shell_cmd(Path::new(r"C:\Users\Alex O'Neil\tincan.exe"), "mcp"), r"& 'C:\Users\Alex O''Neil\tincan.exe' mcp");+ assert_eq!(+ shell_cmd(Path::new(r"C:\Users\alex\.local\bin\tincan.exe"), "mcp"),+ r"C:\Users\alex\.local\bin\tincan.exe mcp"+ );+ assert_eq!(+ shell_cmd(Path::new(r"C:\Users\Alex O'Neil\tincan.exe"), "mcp"),+ r"& 'C:\Users\Alex O''Neil\tincan.exe' mcp"+ );assert_eq!(me(Path::new(r"C:\a\tincan.exe")), r"C:\\a\\tincan.exe");}}diff --git a/src/store.rs b/src/store.rsindex c9875c0..cec54f0 100644--- a/src/store.rs+++ b/src/store.rs@@ -117,7 +117,8 @@ impl Store {pub fn settle_held(&self, ids: &[String], release: bool) -> Result<Vec<Message>> {let held = self.held()?;let picked: Vec<Message> = held.into_iter().filter(|m| ids.is_empty() || ids.contains(&m.id)).collect();- let sql = if release { "UPDATE messages SET held = 0 WHERE id = ?1" } else { "DELETE FROM messages WHERE id = ?1" };+ let sql =+ if release { "UPDATE messages SET held = 0 WHERE id = ?1" } else { "DELETE FROM messages WHERE id = ?1" };let mut st = self.db.prepare_cached(sql)?;for m in &picked {st.execute([&m.id])?;diff --git a/src/team.rs b/src/team.rsindex 596e0a6..7e7a1d4 100644--- a/src/team.rs+++ b/src/team.rs@@ -149,7 +149,8 @@ impl TeamState {let mut raw = [0u8; 16];getrandom::fill(&mut raw).expect("system randomness");let secret = HEXLOWER.encode(&raw);- let body = Invite { hash: hash(&secret), expires: i64::MAX / 4, person: None, used_by: None, ts: now, reusable: true };+ let body =+ Invite { hash: hash(&secret), expires: i64::MAX / 4, person: None, used_by: None, ts: now, reusable: true };self.invites.insert(body.hash.clone(), Signed::new(body, key, &self.id, "invite"));let ts = next_ts(self.link.as_ref().map_or(0, |l| l.body.ts));self.link = Some(Signed::new(Link { secret, ts }, key, &self.id, "link"));@@ -226,8 +227,14 @@ impl TeamState {/// Creates an invite for `secret` (an invite code's, or random for a ticket).pub fn invite(&mut self, key: &SecretKey, secret: &str, hours: u64, person: Option<String>) {let now = util::now_ms();- let body =- Invite { hash: hash(secret), expires: now + hours as i64 * 3_600_000, person, used_by: None, ts: now, reusable: false };+ let body = Invite {+ hash: hash(secret),+ expires: now + hours as i64 * 3_600_000,+ person,+ used_by: None,+ ts: now,+ reusable: false,+ };self.invites.insert(body.hash.clone(), Signed::new(body, key, &self.id, "invite"));}@@ -250,7 +257,11 @@ impl TeamState {None => {}}if inv.expires <= util::now_ms() {- bail!(if inv.reusable { "this team link was replaced; ask for the new one" } else { "this invite expired; ask for a new one" });+ bail!(if inv.reusable {+ "this team link was replaced; ask for the new one"+ } else {+ "this invite expired; ask for a new one"+ });}match &inv.person {Some(p) if p != person => bail!("this invite is for {p}'s own machines"),@@ -283,7 +294,11 @@ impl TeamState {let admitted = self.admitted();let mut added = false;for (k, a) in &other.admissions {- if self.admissions.contains_key(k) || *k != a.body.endpoint.to_string() || !a.body.active || !plausible(a.body.ts) {+ if self.admissions.contains_key(k)+ || *k != a.body.endpoint.to_string()+ || !a.body.active+ || !plausible(a.body.ts)+ {continue;}let vouched = if a.by == a.body.endpoint { a.by == self.founder } else { admitted.contains(&a.by) };@@ -420,7 +435,8 @@ fn put_text(b: &mut Vec<u8>, text: &str) {fn n0_relay(url: &str) -> Option<&str> {let host = url.strip_prefix("https://")?.trim_end_matches('/');let region = host.strip_suffix(".relay.n0.iroh.link.").or_else(|| host.strip_suffix(".relay.n0.iroh.link"))?;- (!region.is_empty() && region.len() < 32 && region.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-')).then_some(region)+ (!region.is_empty() && region.len() < 32 && region.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'-'))+ .then_some(region)}impl Ticket {@@ -468,7 +484,8 @@ impl Ticket {pub fn decode(s: &str) -> Result<Self> {let s = s.trim().rsplit('#').next().unwrap_or_default();let data = s.strip_prefix(TICKET_PREFIX).ok_or_else(|| anyhow!("not a tincan invite"))?;- let b = BASE64URL_NOPAD.decode(data.as_bytes()).map_err(|_| anyhow!("this invite is damaged (was it cut off?)"))?;+ let b =+ BASE64URL_NOPAD.decode(data.as_bytes()).map_err(|_| anyhow!("this invite is damaged (was it cut off?)"))?;let damaged = || anyhow!("this invite is damaged (was it cut off?)");let mut at = 0;let mut take = |n: usize| -> Result<&[u8]> {diff --git a/src/tray.rs b/src/tray.rsindex 1d5d64e..96e53c8 100644--- a/src/tray.rs+++ b/src/tray.rs@@ -70,7 +70,14 @@ mod mac {loop {let until = NSDate::dateWithTimeIntervalSinceNow(0.5);// SAFETY: the main thread's event loop, with AppKit's own run loop mode.- let ev = unsafe { app.nextEventMatchingMask_untilDate_inMode_dequeue(NSEventMask::Any, Some(&until), NSDefaultRunLoopMode, true) };+ let ev = unsafe {+ app.nextEventMatchingMask_untilDate_inMode_dequeue(+ NSEventMask::Any,+ Some(&until),+ NSDefaultRunLoopMode,+ true,+ )+ };if let Some(ev) = ev {app.sendEvent(&ev);}@@ -124,8 +131,10 @@ mod mac {fn set_icon(tray: &TrayIcon, online: bool, title: Option<&str>, mtm: MainThreadMarker) {let name = if online { "bubble.left.and.bubble.right.fill" } else { "bubble.left.and.bubble.right" };if let Some(button) = tray.ns_status_item().and_then(|i| i.button(mtm)) {- let image =- NSImage::imageWithSystemSymbolName_accessibilityDescription(&NSString::from_str(name), Some(&NSString::from_str("tincan")));+ let image = NSImage::imageWithSystemSymbolName_accessibilityDescription(+ &NSString::from_str(name),+ Some(&NSString::from_str("tincan")),+ );button.setImage(image.as_deref());button.setImagePosition(NSCellImagePosition::ImageLeft);}@@ -248,7 +257,8 @@ mod mac {.iter().map(|m| {let mine = |s: &&SessionInfo| s.person == m.person && s.machine == m.machine;- let on: Vec<SessionInfo> = d.sessions.iter().filter(mine).filter(|s| s.tier != Tier::None).cloned().collect();+ let on: Vec<SessionInfo> =+ d.sessions.iter().filter(mine).filter(|s| s.tier != Tier::None).cloned().collect();let without = d.sessions.iter().filter(mine).filter(|s| s.tier == Tier::None).count();(m.clone(), on, without)})diff --git a/src/wizard.rs b/src/wizard.rsindex 4549e15..334c561 100644--- a/src/wizard.rs+++ b/src/wizard.rs@@ -32,18 +32,29 @@ fn name_ok(s: &str) -> Result<(), &'static str> {}fn invite_ok(s: &str) -> Result<(), &'static str> {- if s.contains("tincan1") || invite::normalize(s).is_some() { Ok(()) } else { Err("paste the team link your friend sent") }+ if s.contains("tincan1") || invite::normalize(s).is_some() {+ Ok(())+ } else {+ Err("paste the team link your friend sent")+ }}fn ask_name() -> Result<String> {- let name: String =- input("What should teammates call you?").default_input(&Config::load().person()).validate(|s: &String| name_ok(s)).interact()?;+ let name: String = input("What should teammates call you?")+ .default_input(&Config::load().person())+ .validate(|s: &String| name_ok(s))+ .interact()?;Ok(util::slug(&name))}/// Start or join a team. With an invite (a team link, from the installer), it only asks for your name./// `start`: `Some(true)` from `tincan init`, `Some(false)` from `tincan join`, `None` to ask.-pub async fn onboard(start: Option<bool>, team: Option<String>, invite: Option<String>, person: Option<String>) -> Result<()> {+pub async fn onboard(+ start: Option<bool>,+ team: Option<String>,+ invite: Option<String>,+ person: Option<String>,+) -> Result<()> {intro(" tincan ")?;let link = Link::new(None);if let Ok(t) = link.call::<TeamInfo>(Request::Team).await {@@ -71,7 +82,10 @@ pub async fn onboard(start: Option<bool>, team: Option<String>, invite: Option<S};let sp = spinner();sp.start("Creating the team...");- let t: TeamInfo = link.call(Request::CreateTeam { name, person, relay: None }).await.inspect_err(|e| sp.error(format!("{e:#}")))?;+ let t: TeamInfo = link+ .call(Request::CreateTeam { name, person, relay: None })+ .await+ .inspect_err(|e| sp.error(format!("{e:#}")))?;crate::wait_exit(crate::daemon_pid()).await;sp.stop(format!("Created team {}. You are {} on {}.", t.name, t.person, t.machine));} else {@@ -79,7 +93,10 @@ pub async fn onboard(start: Option<bool>, team: Option<String>, invite: Option<Sloop {let text: String = match invite.take() {Some(t) => t,- None => input("Paste the team link").placeholder("https://…/join/#tincan1…").validate(|s: &String| invite_ok(s)).interact()?,+ None => input("Paste the team link")+ .placeholder("https://…/join/#tincan1…")+ .validate(|s: &String| invite_ok(s))+ .interact()?,};let sp = spinner();sp.start("Joining...");@@ -102,7 +119,8 @@ pub async fn onboard(start: Option<bool>, team: Option<String>, invite: Option<S}Err(e) if e.to_string().contains("already in this team") => {sp.error(format!("Someone in the team is already called {person}."));- person = util::slug(&input("Pick another name").validate(|s: &String| name_ok(s)).interact::<String>()?);+ person =+ util::slug(&input("Pick another name").validate(|s: &String| name_ok(s)).interact::<String>()?);invite = Some(text);}Err(e) => {@@ -169,17 +187,23 @@ pub async fn agents_and_preferences() -> Result<()> {let exe = setup::exe()?;let found = setup::detect(&exe);let chosen: Vec<&str> = if found.is_empty() {- log::warning("No coding agents found here (Claude Code, Codex, Cursor, Gemini CLI, Copilot CLI, opencode, pi, Reason). Install one, then run `tincan setup`.")?;+ log::warning(+ "No coding agents found here (Claude Code, Codex, Cursor, Gemini CLI, Copilot CLI, opencode, pi, Reason). Install one, then run `tincan setup`.",+ )?;Vec::new()} else {let initial: Vec<&str> = found.iter().filter(|f| f.wired).map(|f| f.id).collect();- let mut pick = multiselect("Which agents should be on tincan? (space to toggle, enter to confirm)").required(false).initial_values(initial);+ let mut pick = multiselect("Which agents should be on tincan? (space to toggle, enter to confirm)")+ .required(false)+ .initial_values(initial);for f in &found {pick = pick.item(f.id, f.name, f.hint);}pick.interact()?};- let service = confirm("Keep tincan running in the background, so teammates can always reach you?").initial_value(true).interact()?;+ let service = confirm("Keep tincan running in the background, so teammates can always reach you?")+ .initial_value(true)+ .interact()?;let mut cfg = Config::load_strict().map_err(|e| anyhow!("fix {} first: {e}", crate::paths::config().display()))?;cfg.inbound.default = select("When a teammate's agent messages one of yours").item(Policy::Accept, "Deliver it", "recommended")@@ -216,8 +240,15 @@ 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 title = if copied { format!("Team link for {} (on your clipboard)", l.team) } else { format!("Team link for {}", l.team) };- note(title, "Send it to your friends: one paste and their name, and they're in.\nIt works for everyone until `tincan link --new`.")?;+ let title = if copied {+ format!("Team link for {} (on your clipboard)", l.team)+ } else {+ format!("Team link for {}", l.team)+ };+ note(+ title,+ "Send it to your friends: one paste and their name, and they're in.\nIt works for everyone until `tincan link --new`.",+ )?;Ok(l.url)}@@ -239,8 +270,11 @@ pub async fn show_code(me: bool) -> Result<()> {/// Puts text on the clipboard, if there's a clipboard tool. True if it worked.pub fn copy(text: &str) -> bool {use std::io::Write;- let tools: &[(&str, &[&str])] =- if cfg!(windows) { &[("clip", &[])] } else { &[("pbcopy", &[]), ("wl-copy", &[]), ("xclip", &["-selection", "clipboard"])] };+ let tools: &[(&str, &[&str])] = if cfg!(windows) {+ &[("clip", &[])]+ } else {+ &[("pbcopy", &[]), ("wl-copy", &[]), ("xclip", &["-selection", "clipboard"])]+ };tools.iter().any(|(bin, args)| {let Ok(mut child) = std::process::Command::new(bin).args(*args)