Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.
Rust acpagent-client-protocolai-agentsai-assistantclaudeclaude-codecodexcoding-agentscursorgeminigemini-cligrok-bot-alternativeiosiphonelinuxmacosmcpopen-sourcerustself-hosted
feat(host): a computer can be in several networks
leepokaif05d66d09642
diff --git a/host/crates/network/src/lib.rs b/host/crates/network/src/lib.rsindex 227cb98d..af7df218 100644--- a/host/crates/network/src/lib.rs+++ b/host/crates/network/src/lib.rs@@ -26,7 +26,7 @@ pub mod rules;mod types;mod wire;-pub use node::{INVITE_FOR, Node};+pub use node::{INVITE_FOR, InviteInfo, Node, read_invite};pub use reach::Reach;pub use roster::Role;pub use rules::{Access, Rule};diff --git a/host/crates/network/src/node/mod.rs b/host/crates/network/src/node/mod.rsindex f345155e..080f2787 100644--- a/host/crates/network/src/node/mod.rs+++ b/host/crates/network/src/node/mod.rs@@ -65,6 +65,8 @@ struct Inner {inbox: mpsc::Sender<Message>,/// The command an agent the network knocks on runs to answer.reply_command: Mutex<String>,+ /// What the app calls this network; invites carry it (`set_network_name`).+ network_name: Mutex<Option<String>>,/// Ticks when the members, their roles or names, or what the others offer or whether they/// answer, change.changed: watch::Sender<()>,@@ -100,6 +102,7 @@ impl Node {outbox: Mutex::default(),inbox: tx,reply_command: Mutex::new("codync-network".into()),+ network_name: Mutex::default(),changed: watch::Sender::new(()),});let router = Router::builder(endpoint).accept(ALPN, inbound::Handler(inner.clone())).spawn();@@ -121,6 +124,11 @@ impl Node {locked(&self.inner.roster).as_ref().map(|r| r.name(&self.id()))}+ /// The network's id (its root key), once this computer is in one.+ pub fn network_id(&self) -> Option<String> {+ locked(&self.inner.roster).as_ref().map(|r| r.network.to_string())+ }+pub fn role(&self) -> Option<Role> {locked(&self.inner.roster).as_ref().and_then(|r| r.role(&self.id()))}@@ -147,7 +155,8 @@ impl Node {}let secret = wire::random_hex(16);locked(&self.inner.invites).insert(secret.clone(), Instant::now() + INVITE_FOR);- Ticket { network: roster.network, secret, addr: self.inner.endpoint.addr() }.encode()+ let name = locked(&self.inner.network_name).clone();+ Ticket { network: roster.network, secret, addr: self.inner.endpoint.addr(), name }.encode()}pub async fn join(&self, ticket: &str, name: &str) -> Result<()> {@@ -248,6 +257,12 @@ impl Node {locked(&self.inner.rules).clone()}+ /// What the app calls this network (`home`, `work`) when a computer is in several: the invites+ /// it makes carry the name, so the computer that joins can call it the same ([`read_invite`]).+ pub fn set_network_name(&self, name: Option<String>) {+ *locked(&self.inner.network_name) = name;+ }+/// The command agents the network knocks on run to reply (default `codync-network`).pub fn set_reply_command(&self, command: impl Into<String>) {*locked(&self.inner.reply_command) = command.into();@@ -338,7 +353,8 @@ impl Node {}}- pub async fn shutdown(self) {+ /// Stops answering and closes the endpoint (leaving a network, or quitting).+ pub async fn shutdown(&self) {let _ = self.router.shutdown().await;}}@@ -480,6 +496,19 @@ impl Inner {}}+/// What an invite says about its network, before joining it.+pub struct InviteInfo {+ /// The network's id (its root key), as [`Node::network_id`] gives it.+ pub network: String,+ /// What the inviting computer calls the network, if it named it.+ pub name: Option<String>,+}++pub fn read_invite(invite: &str) -> Result<InviteInfo> {+ let ticket = Ticket::decode(invite)?;+ Ok(InviteInfo { network: ticket.network.to_string(), name: ticket.name })+}+/// Signs where this computer is again whenever its addresses change (a laptop that moved to/// another network) and tells the others, so they find it without a restart: with the `private`/// connector, nothing else would. The roster keeps only each computer's newest location.diff --git a/host/crates/network/src/wire.rs b/host/crates/network/src/wire.rsindex ea7aba51..485ba25c 100644--- a/host/crates/network/src/wire.rs+++ b/host/crates/network/src/wire.rs@@ -97,6 +97,9 @@ pub struct Ticket {pub network: EndpointId,pub secret: String,pub addr: EndpointAddr,+ /// What the inviting computer calls the network, for a computer in several of them.+ #[serde(default, skip_serializing_if = "Option::is_none")]+ pub name: Option<String>,}impl Ticket {@@ -168,7 +171,7 @@ mod tests {#[test]fn tickets_round_trip_and_reject_garbage() {let addr = EndpointAddr::new(iroh::SecretKey::generate().public());- let ticket = Ticket { network: addr.id, secret: random_hex(16), addr: addr.clone() };+ let ticket = Ticket { network: addr.id, secret: random_hex(16), addr: addr.clone(), name: None };let text = ticket.encode().unwrap();let back = Ticket::decode(&format!(" {text}\n")).unwrap();assert_eq!((back.network, back.secret, back.addr), (ticket.network, ticket.secret, addr));diff --git a/host/crates/network/tests/two_computers.rs b/host/crates/network/tests/two_computers.rsindex 478ff713..53d6deff 100644--- a/host/crates/network/tests/two_computers.rs+++ b/host/crates/network/tests/two_computers.rs@@ -339,3 +339,16 @@ async fn an_unlisted_sender_asks_and_hears_back_but_isnt_offered() {let _ = std::fs::remove_dir_all(dir);}}++#[tokio::test]+async fn an_invite_carries_the_networks_name() {+ let dir = temp_dir("named");+ let (desk, _) = Node::start(&dir, &Connector::Private).await.unwrap();+ desk.create("desk").unwrap();+ assert_eq!(codync_network::read_invite(&desk.invite().unwrap()).unwrap().name, None);+ desk.set_network_name(Some("home".into()));+ let read = codync_network::read_invite(&desk.invite().unwrap()).unwrap();+ assert_eq!((read.name.as_deref(), Some(read.network)), (Some("home"), desk.network_id()));+ desk.shutdown().await;+ let _ = std::fs::remove_dir_all(dir);+}diff --git a/host/src/analytics/observe.rs b/host/src/analytics/observe.rsindex 029f5461..3ad3976a 100644--- a/host/src/analytics/observe.rs+++ b/host/src/analytics/observe.rs@@ -8,7 +8,7 @@ use crate::store::BotConfig;use serde_json::{Map, Value};/// Methods that stand for one event with one fixed property.-const FIXED: [(&str, Event, &str, &str); 13] = [+const FIXED: [(&str, Event, &str, &str); 14] = [("editHandoff", Event::HandoffAnswered, "action", "edit"),("keepConversation", Event::HandoffAnswered, "action", "keep"),("credentialSaveLogin", Event::CredentialSaved, "kind", "login"),@@ -23,6 +23,7 @@ const FIXED: [(&str, Event, &str, &str); 13] = [("networkRemove", Event::NetworkChanged, "action", "remove"),("networkRecover", Event::NetworkChanged, "action", "recover"),("setNetworkRules", Event::NetworkChanged, "action", "rules"),+ ("networkLeave", Event::NetworkChanged, "action", "leave"),];/// Switches the host owns (`setting_changed`): the method and the setting it names.diff --git a/host/src/api/devices.rs b/host/src/api/devices.rsindex 491c6208..e770a794 100644--- a/host/src/api/devices.rs+++ b/host/src/api/devices.rs@@ -70,6 +70,7 @@ const LOCAL_ONLY: &[&str] = &["networkStatus","networkCreate","networkJoin",+ "networkLeave","networkInvite","networkPeers","networkRemove",diff --git a/host/src/api/network.rs b/host/src/api/network.rsindex 56c00830..4d233495 100644--- a/host/src/api/network.rs+++ b/host/src/api/network.rs@@ -1,5 +1,6 @@-//! Methods for this computer's network (codync-network): only this computer's own apps call-//! them (`devices::LOCAL_ONLY`), except `networkView`, which paired phones read.+//! Methods for this computer's networks (codync-network): only this computer's own apps call+//! them (`devices::LOCAL_ONLY`), except `networkView`, which paired phones read. `network` names+//! one by its id or name, and may be left out while the computer is in only one.use super::str_arg;use crate::hub::Hub;@@ -11,17 +12,19 @@ use std::sync::Arc;pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<ControlFlow<Value, Value>> {let text = |k: &str| b[k].as_str().filter(|s| !s.trim().is_empty());+ let which = text("network");Ok(ControlFlow::Break(match method {"networkStatus" => network::status(hub),"networkView" => network::view(hub),- "networkCreate" => network::create(hub, text("name"), text("connector")).await?,- "networkJoin" => network::join(hub, str_arg(&b, "invite")?, text("name"), text("connector")).await?,- "networkInvite" => network::invite(hub)?,- "networkPeers" => network::peers(hub).await?,- "networkRemove" => network::remove(hub, str_arg(&b, "computer")?, b["cascade"] == true)?,- "networkPromote" => network::promote(hub, str_arg(&b, "computer")?)?,- "networkRecover" => network::recover(hub, str_arg(&b, "code")?)?,- "setNetworkRules" => network::set_rules(hub, &b["rules"])?,+ "networkCreate" => network::create(hub, which, text("name"), text("connector")).await?,+ "networkJoin" => network::join(hub, str_arg(&b, "invite")?, which, text("name"), text("connector")).await?,+ "networkLeave" => network::leave(hub, which).await?,+ "networkInvite" => network::invite(hub, which)?,+ "networkPeers" => network::peers(hub, which).await?,+ "networkRemove" => network::remove(hub, which, str_arg(&b, "computer")?, b["cascade"] == true)?,+ "networkPromote" => network::promote(hub, which, str_arg(&b, "computer")?)?,+ "networkRecover" => network::recover(hub, which, str_arg(&b, "code")?)?,+ "setNetworkRules" => network::set_rules(hub, which, &b["rules"])?,_ => return Ok(ControlFlow::Continue(b)),}))}diff --git a/host/src/chat/team.rs b/host/src/chat/team.rsindex 2a71459b..7b51cbf4 100644--- a/host/src/chat/team.rs+++ b/host/src/chat/team.rs@@ -354,7 +354,7 @@ pub async fn call_async(hub: &Arc<Hub>, from: &str, name: &str, args: &Value) ->"message_bot" => {let (to, message) = message_args(args)?;match hub.network.recipient(to)? {- Recipient::There(address) => remote::message(hub, &visible_bot(hub, from)?, &address, message).await,+ Recipient::There(target) => remote::message(hub, &visible_bot(hub, from)?, &target, message).await,Recipient::Here(_) => call(hub, from, name, args),}}@@ -371,7 +371,7 @@ fn call(hub: &Arc<Hub>, from: &str, name: &str, args: &Value) -> Result<Value> {let (to, message) = message_args(args)?;match hub.network.recipient(to)? {Recipient::Here(to) => message_bot(hub, &source, &to, message),- Recipient::There(address) => bail!("{address} is on another computer"),+ Recipient::There(target) => bail!("{} is on another computer", target.address),}}_ => bail!("unknown team tool: {name}"),diff --git a/host/src/chat/team/assistant.rs b/host/src/chat/team/assistant.rsindex 26ed1b7c..70a12c62 100644--- a/host/src/chat/team/assistant.rs+++ b/host/src/chat/team/assistant.rs@@ -182,7 +182,7 @@ fn message(hub: &Arc<Hub>, asker: &Asker, args: &Value) -> Result<Value> {/// A bot on another of the user's computers (`reviewer@laptop`): a letter from this computer,/// whose answer comes back here. That computer's own rules decide whether it takes it.-fn message_elsewhere(hub: &Arc<Hub>, asker: &Asker, to: &codync_network::Address, message: &str) -> Result<Value> {+fn message_elsewhere(hub: &Arc<Hub>, asker: &Asker, to: &crate::network::Target, message: &str) -> Result<Value> {let (request, peer) = remote::ask_for_assistant(hub, &asker.handle, to, message)?;hub.assistant.add(Reply {asker: asker.id.clone(),@@ -194,7 +194,7 @@ fn message_elsewhere(hub: &Arc<Hub>, asker: &Asker, to: &codync_network::Addressat: now_ms(),});Ok(json!({- "requestId": request, "botId": to.to_string(), "name": peer, "status": RequestStatus::Queued,+ "requestId": request, "botId": hub.network.address_text(to), "name": peer, "status": RequestStatus::Queued,"note": "Queued on that computer. Bots can take minutes: get the reply later with read_replies.",}))}diff --git a/host/src/chat/team/assistant/tests.rs b/host/src/chat/team/assistant/tests.rsindex e11d3dd5..7fb1e6ca 100644--- a/host/src/chat/team/assistant/tests.rs+++ b/host/src/chat/team/assistant/tests.rs@@ -120,7 +120,7 @@ async fn an_answer_from_another_computer_waits_in_the_replies() {remote::awaits_for_assistant(hub, request, "Coder on laptop", "status?");}let (tx, rx) = tokio::sync::mpsc::channel(4);- tokio::spawn(remote::listen(hub.clone(), rx));+ tokio::spawn(remote::listen(hub.clone(), "network".into(), rx));let answer = |request: &str, body: &str, status: &str| codync_network::Message {id: format!("re-{request}"),from: "coder@laptop".parse().unwrap(),diff --git a/host/src/chat/team/directory.rs b/host/src/chat/team/directory.rsindex 909240c6..d53c8104 100644--- a/host/src/chat/team/directory.rs+++ b/host/src/chat/team/directory.rs@@ -31,7 +31,7 @@ pub(super) fn list(keep: fn(&BotConfig) -> bool,) -> Result<Value> {let filter = Filter::of(args);- let here = hub.network.node().and_then(|n| n.name());+ let here = hub.network.my_name();let rows: Vec<Row> =rows(hub, from, remote, keep)?.into_iter().filter(|r| filter.keeps(r, here.as_deref())).collect();Ok(page(&rows, args, !filter.narrows()))@@ -95,7 +95,11 @@ impl Filter {/// `here` is this computer's name in its network.fn keeps(&self, row: &Row, here: Option<&str>) -> bool {let at = row.computer.as_deref().or(here).map(str::to_lowercase);- let on = |c: &String| at.as_ref() == Some(c) || (row.computer.is_none() && c == HERE);+ // `desk` also finds `desk.home`, a computer in one of this computer's several networks.+ let at_computer = |c: &String| {+ at.as_ref().is_some_and(|a| a == c || a.strip_prefix(c.as_str()).is_some_and(|rest| rest.starts_with('.')))+ };+ let on = |c: &String| at_computer(c) || (row.computer.is_none() && c == HERE);self.words.iter().all(|w| row.words.contains(w))&& self.computer.as_ref().is_none_or(on)&& (!self.online || row.online)diff --git a/host/src/chat/team/remote.rs b/host/src/chat/team/remote.rsindex de92fa55..95ecd392 100644--- a/host/src/chat/team/remote.rs+++ b/host/src/chat/team/remote.rs@@ -11,6 +11,7 @@ use crate::LockExt;use crate::agent::acp::truncate;use crate::agent::bot::Cmd;use crate::hub::Hub;+use crate::network::Target;use crate::store::{BotConfig, EntryKind, Lane};use anyhow::{Result, anyhow};use codync_network::{Address, Letter, Message, Node, Sent};@@ -51,6 +52,8 @@ impl Waiting {/// Where the outcome of a request from another computer goes.pub(crate) struct Return {+ /// The network the request came through (`network::Slot::id`).+ network: String,to: Address,request: String,/// The answering bot's address name when the request came.@@ -58,28 +61,28 @@ pub(crate) struct Return {}/// The letters that reach this computer's bots.-pub async fn listen(hub: Arc<Hub>, mut inbox: mpsc::Receiver<Message>) {+pub async fn listen(hub: Arc<Hub>, network: String, mut inbox: mpsc::Receiver<Message>) {while let Some(m) = inbox.recv().await {- if let Err(error) = take(&hub, &m) {+ if let Err(error) = take(&hub, &network, &m) {tracing::warn!(error = format!("{error:#}"), "couldn't take a letter from another computer");}}}-fn take(hub: &Arc<Hub>, m: &Message) -> Result<()> {+fn take(hub: &Arc<Hub>, network: &str, m: &Message) -> Result<()> {if let Some((id, waiter)) = m.reply_to.as_deref().and_then(|id| Some((id, hub.waiting.take(id)?))) {replied(hub, id, waiter, m);return Ok(());}- let back = Return { to: m.from.clone(), request: m.id.clone(), from: m.to.clone() };+ let back = Return { network: network.to_owned(), to: m.from.clone(), request: m.id.clone(), from: m.to.clone() };let target = hub.network.bot_for(&m.to).ok_or_else(|| anyhow!("no bot called {} here", m.to));match target.and_then(|bot| visible_bot(hub, &bot)) {// A note, or a reply this computer no longer waits for (it restarted): the chat shows it.Ok(target) if !m.wake || m.reply_to.is_some() => {- note(hub, &target, m);+ note(hub, network, &target, m);Ok(())}- Ok(target) => requested(hub, &target, m, back),+ Ok(target) => requested(hub, network, &target, m, back),// The bot went away after this computer took the request: its sender would wait for good.Err(error) if m.wake && m.reply_to.is_none() => {send_back(hub, &back, format!("Couldn't take it: {error:#}"), RequestStatus::Failed, m.hops);@@ -89,13 +92,14 @@ fn take(hub: &Arc<Hub>, m: &Message) -> Result<()> {}}-/// How a bot on another computer is shown: its name and computer, from the directory.-fn peer_name(hub: &Hub, address: &Address) -> String {+/// How a bot on another computer is shown: its name and computer, from that network's directory.+fn peer_name(hub: &Hub, network: &str, address: &Address) -> String {if address.agent == super::assistant::HANDLE {return format!("{} on {}", super::assistant::NAME, address.computer);}- let name = hub.network.node().and_then(|node| {- node.directory()+ let name = hub.network.slot(Some(network)).ok().and_then(|slot| {+ slot.node+ .directory().into_iter().find(|p| p.name == address.computer).and_then(|p| p.agents.into_iter().find(|a| a.id == address.agent))@@ -105,20 +109,21 @@ fn peer_name(hub: &Hub, address: &Address) -> String {}/// One of this computer's bots asks a bot on another computer.-pub(super) async fn message(hub: &Arc<Hub>, source: &BotConfig, to: &Address, message: &str) -> Result<Value> {+pub(super) async fn message(hub: &Arc<Hub>, source: &BotConfig, to: &Target, message: &str) -> Result<Value> {check_request(hub, source, message)?;- let node = hub.network.node().ok_or_else(|| anyhow!("this computer isn't in a network"))?;+ let node = hub.network.slot(Some(&to.network))?.node;let from = hub.network.handle_of(&source.id).ok_or_else(|| anyhow!("this bot isn't on the network"))?;let hops = hub.team.reserve_message(&source.id)?;// ponytail: the slot covers sending only; the other computer bounds the work it takes on.- let result = send(hub, &node, source, Letter::new(from, to.clone(), message).hops(hops)).await;+ let letter = Letter::new(from, to.address.clone(), message).hops(hops);+ let result = send(hub, &node, source, to, letter).await;hub.team.release_message(&source.id);result}-async fn send(hub: &Arc<Hub>, node: &Node, source: &BotConfig, letter: Letter) -> Result<Value> {- let (id, address, computer) = (letter.id.clone(), letter.to.to_string(), letter.to.computer.clone());- let peer = peer_name(hub, &letter.to);+async fn send(hub: &Arc<Hub>, node: &Node, source: &BotConfig, to: &Target, letter: Letter) -> Result<Value> {+ let (id, address, computer) = (letter.id.clone(), hub.network.address_text(to), letter.to.computer.clone());+ let peer = peer_name(hub, &to.network, &letter.to);let heading = format!("Messaged {peer}: {}", letter.body);let exchange =Exchange { request: &id, source: &source.id, target: &address, text: &letter.body, peer_name: Some(&peer) };@@ -152,11 +157,11 @@ async fn send(hub: &Arc<Hub>, node: &Node, source: &BotConfig, letter: Letter) -/// The user's cloud assistant asks a bot on another computer. Returns the request's id (the/// letter's) at once: the letter goes in the background, and its outcome waits in the/// assistant's replies.-pub(super) fn ask_for_assistant(hub: &Arc<Hub>, from: &str, to: &Address, message: &str) -> Result<(String, String)> {- let node = hub.network.node().ok_or_else(|| anyhow!("this computer isn't in a network"))?;+pub(super) fn ask_for_assistant(hub: &Arc<Hub>, from: &str, to: &Target, message: &str) -> Result<(String, String)> {+ let node = hub.network.slot(Some(&to.network))?.node;hub.network.send_as(from)?;- let letter = Letter::new(from, to.clone(), message);- let (id, peer) = (letter.id.clone(), peer_name(hub, to));+ let letter = Letter::new(from, to.address.clone(), message);+ let (id, peer) = (letter.id.clone(), peer_name(hub, &to.network, &to.address));awaits_for_assistant(hub, &id, &peer, message);let (hub, request) = (hub.clone(), id.clone());tokio::spawn(async move {@@ -190,8 +195,8 @@ fn waiting(hub: &Hub, id: &str, text: &str, status: RequestStatus) {}/// A bot on another computer (or any agent there) asks one of this computer's bots.-fn requested(hub: &Arc<Hub>, target: &BotConfig, m: &Message, back: Return) -> Result<()> {- let peer = peer_name(hub, &m.from);+fn requested(hub: &Arc<Hub>, network: &str, target: &BotConfig, m: &Message, back: Return) -> Result<()> {+ let peer = peer_name(hub, network, &m.from);let from = m.from.to_string();let mut lifetime = MessageLifetime::new(hub, &m.id, &m.body, Back::Remote(back), &target.name);let exchange =@@ -202,8 +207,8 @@ fn requested(hub: &Arc<Hub>, target: &BotConfig, m: &Message, back: Return) -> R}/// A letter that starts no turn: the bot's chat shows it.-fn note(hub: &Hub, target: &BotConfig, m: &Message) {- let peer = peer_name(hub, &m.from);+fn note(hub: &Hub, network: &str, target: &BotConfig, m: &Message) {+ let peer = peer_name(hub, network, &m.from);let heading = format!("Note from {peer}");hub.add_entry(&Lane::main(&target.id),@@ -226,7 +231,8 @@ pub(super) fn cancelled(hub: &Hub, to: &Return, hops: u8) {}fn send_back(hub: &Hub, to: &Return, mut body: String, status: RequestStatus, hops: u8) {- let Some(node) = hub.network.node() else { return };+ let Ok(slot) = hub.network.slot(Some(&to.network)) else { return };+ let node = slot.node;if body.trim().is_empty() {body = "(no reply)".into();}diff --git a/host/src/network/api.rs b/host/src/network/api.rsnew file mode 100644index 00000000..28a1b636--- /dev/null+++ b/host/src/network/api.rs@@ -0,0 +1,212 @@+//! The `network*` API methods: what the apps show of this computer's networks, and the changes+//! made at the computer (loopback only, like pairing a device).++use super::saved::{self, Saved};+use super::{Slot, default_name, start_node, take_in};+use crate::LockExt;+use crate::hub::Hub;+use anyhow::{Context, Result, bail};+use codync_network::{Connector, Node, Role, Rule};+use serde_json::{Value, json};+use std::sync::Arc;+use std::time::Instant;++/// The `network` event: what `networkView` answers.+pub fn emit(hub: &Hub) {+ let _ = hub.events.send(json!({"type": "network", "network": status(hub)}));+}++/// `networkStatus`, the `network` event and the stream's hello: every network this computer is in+/// (`networks`, the default first), each with its computers as last heard, what this computer may+/// do there (`canInvite`, `canRecover`) and to each (`canRemove`, `canPromote`), and its rules;+/// plus the cloud assistants switch, and whether they can reach this computer at all+/// (`assistantsAvailable`). Never an invite: phones read it too.+pub fn status(hub: &Hub) -> Value {+ let saved = saved::load(hub);+ let networks: Vec<Value> = hub+ .network+ .slots()+ .iter()+ .filter(|s| s.node.name().is_some())+ .map(|s| network(s, saved.iter().find(|x| x.id == s.id)))+ .collect();+ json!({+ "joined": !networks.is_empty(), "networks": networks,+ "assistants": crate::chat::team::assistant::enabled(&hub.store),+ "assistantsAvailable": crate::chat::team::assistant::available(hub),+ })+}++fn network(slot: &Slot, saved: Option<&Saved>) -> Value {+ let node = &slot.node;+ let mine = node.role();+ let computers: Vec<Value> = node+ .directory()+ .into_iter()+ .map(|p| {+ let agents: Vec<Value> = p.agents.iter().map(|a| json!({"id": a.id, "name": a.name})).collect();+ let may = |rule: fn(Role, Role) -> bool| !p.me && mine.is_some_and(|me| rule(me, p.role));+ json!({+ "name": p.name, "role": p.role, "me": p.me, "online": p.online, "agents": agents,+ "canRemove": may(Role::removes), "canPromote": may(Role::promotes),+ })+ })+ .collect();+ json!({+ "id": slot.id, "name": slot.name, "computer": node.name(), "role": mine,+ "canInvite": mine.is_some_and(Role::invites), "canRecover": mine.is_some_and(|r| r != Role::Owner),+ "connector": saved.map_or("public", |s| s.connector.as_str()),+ "computers": computers, "rules": node.rules(),+ })+}++/// `networkView`: `status`, asking the others in the background when what they offer is stale;+/// the `network` event brings what they answer. The first look since the host started is left to+/// bot listings, which wait for it (`Network::directory`).+pub fn view(hub: &Hub) -> Value {+ let looked = hub.network.asked.locked().is_some();+ if looked && hub.network.due().is_some() {+ for slot in hub.network.slots() {+ tokio::spawn(async move { slot.node.peers().await });+ }+ }+ status(hub)+}++/// A new network's node in a folder of its own, taken in once `make` (create or join) worked;+/// gone again, folder and all, when it didn't.+async fn add<T>(+ hub: &Arc<Hub>,+ name: &str,+ connector: Option<&str>,+ first: impl AsyncFnOnce(&Node) -> Result<T>,+) -> Result<(Slot, T)> {+ let _one = hub.network.changing.lock().await;+ let mut all = saved::load(hub);+ let connector = connector.unwrap_or("public");+ connector.parse::<Connector>()?;+ let id = saved::new_id(&all);+ let saved =+ Saved { id: id.clone(), name: saved::free_name(&all, name)?, connector: connector.into(), rules: Vec::new() };+ let (node, inbox) = start_node(&saved).await?;+ let made = match first(&node).await {+ Ok(it) => it,+ Err(error) => {+ node.shutdown().await;+ let _ = std::fs::remove_dir_all(saved::dir(&id));+ return Err(error);+ }+ };+ all.push(saved.clone());+ saved::save(hub, &all)?;+ let slot = take_in(hub, &saved, node, inbox);+ emit(hub);+ Ok((slot, made))+}++/// `networkCreate`: a new network (`network`, its name) with this computer as its owner, under+/// `name`. Returns the recovery code: the apps show it once, and it is kept nowhere.+pub async fn create(+ hub: &Arc<Hub>,+ network: Option<&str>,+ name: Option<&str>,+ connector: Option<&str>,+) -> Result<Value> {+ let name = name.map_or_else(default_name, str::to_owned);+ let (slot, code) = add(hub, network.unwrap_or("home"), connector, async |node: &Node| node.create(&name)).await?;+ Ok(json!({"network": slot.id, "computer": slot.node.name(), "recoveryCode": code}))+}++/// `networkJoin`: joins a network with an invite from its owner or an admin, under the name the+/// invite gives it unless `network` says otherwise.+pub async fn join(+ hub: &Arc<Hub>,+ invite: &str,+ network: Option<&str>,+ name: Option<&str>,+ connector: Option<&str>,+) -> Result<Value> {+ let ticket = codync_network::read_invite(invite)?;+ if let Some(slot) = hub.network.slots().iter().find(|s| s.node.network_id().as_ref() == Some(&ticket.network)) {+ bail!("this computer is already in that network ({})", slot.name);+ }+ let network = network.or(ticket.name.as_deref()).unwrap_or("home");+ let name = name.map_or_else(default_name, str::to_owned);+ add(hub, network, connector, async |node: &Node| node.join(invite, &name).await).await?;+ Ok(status(hub))+}++/// `networkLeave`: stops this computer's node for a network and forgets it here. The others keep+/// listing this computer until the owner or an admin removes it.+pub async fn leave(hub: &Arc<Hub>, network: Option<&str>) -> Result<Value> {+ let _one = hub.network.changing.lock().await;+ let slot = hub.network.slot(network)?;+ hub.network.slots.locked().retain(|s| s.id != slot.id);+ slot.node.shutdown().await;+ let mut all = saved::load(hub);+ all.retain(|s| s.id != slot.id);+ saved::save(hub, &all)?;+ tokio::task::spawn_blocking(move || std::fs::remove_dir_all(saved::dir(&slot.id)))+ .await?+ .context("couldn't delete the network's folder")?;+ emit(hub);+ Ok(status(hub))+}++fn joined(hub: &Hub, network: Option<&str>) -> Result<Slot> {+ let slot = hub.network.slot(network)?;+ if slot.node.name().is_none() {+ bail!("this computer isn't in {} yet", slot.name);+ }+ Ok(slot)+}++/// `networkInvite`: a one-time invite and when it stops working (Unix ms).+pub fn invite(hub: &Hub, network: Option<&str>) -> Result<Value> {+ let invite = joined(hub, network)?.node.invite()?;+ let lasts = i64::try_from(codync_network::INVITE_FOR.as_millis()).expect("an invite lasts an hour");+ let until = crate::store::now_ms().saturating_add(lasts);+ Ok(json!({"invite": invite, "expiresAt": until}))+}++/// `networkPeers`: asks every computer now, in one network or all of them.+pub async fn peers(hub: &Arc<Hub>, network: Option<&str>) -> Result<Value> {+ let slots = match network {+ Some(_) => vec![joined(hub, network)?],+ None => hub.network.slots(),+ };+ futures::future::try_join_all(slots.iter().map(|s| s.node.peers())).await?;+ *hub.network.asked.locked() = Some(Instant::now());+ Ok(status(hub))+}++pub fn remove(hub: &Hub, network: Option<&str>, computer: &str, cascade: bool) -> Result<Value> {+ joined(hub, network)?.node.remove(computer, cascade)?;+ Ok(json!({}))+}++pub fn promote(hub: &Hub, network: Option<&str>, computer: &str) -> Result<Value> {+ joined(hub, network)?.node.promote(computer)?;+ Ok(json!({}))+}++pub fn recover(hub: &Hub, network: Option<&str>, code: &str) -> Result<Value> {+ joined(hub, network)?.node.recover(code)?;+ Ok(json!({}))+}++/// `setNetworkRules`: who on a network's other computers may write to this computer's bots, in+/// order (the first match decides); an empty list lets everyone.+pub fn set_rules(hub: &Hub, network: Option<&str>, rules: &Value) -> Result<Value> {+ let rules: Vec<Rule> =+ serde_json::from_value(rules.clone()).context("rules are {fromComputer, fromAgent, toAgent, access}")?;+ let slot = joined(hub, network)?;+ slot.node.set_rules(rules.clone())?;+ let mut all = saved::load(hub);+ if let Some(saved) = all.iter_mut().find(|s| s.id == slot.id) {+ saved.rules = rules;+ }+ saved::save(hub, &all)?;+ emit(hub);+ Ok(status(hub))+}diff --git a/host/src/network/mod.rs b/host/src/network/mod.rsindex 8900a344..d2b0562e 100644--- a/host/src/network/mod.rs+++ b/host/src/network/mod.rs@@ -1,28 +1,31 @@//! This computer on codync-network: the user's other computers and the bots on them.//!-//! The node stays off until the user creates or joins a network. Once it is on, this computer's-//! visible bots are its agents, each under an address name (`reviewer`, so `reviewer@desk` from-//! elsewhere), and the letters that reach them become bot requests (`chat::team::remote`).-+//! A computer can be in several networks (`home`, `work`). Each one has its own node, with its+//! own key, roster, connector and rules, in its own folder, so the networks stay apart: members of+//! one can't tell this computer is in another, and nothing one network decides reaches the+//! others. No node runs until the user creates or joins a network. This computer's visible bots+//! are offered in every network, each under one address name (`reviewer`, so `reviewer@desk` from+//! elsewhere, or `[email protected]` to name the network), and the letters that reach them become+//! bot requests (`chat::team::remote`).++mod api;mod handles;+mod saved;use crate::LockExt;use crate::hub::Hub;use anyhow::{Context, Result, anyhow, bail};-use codync_network::{Address, Agent, Connector, Node, Peer, Reach, Role, Rule};-use serde_json::{Value, json};-use std::collections::HashMap;-use std::path::PathBuf;-use std::sync::{Arc, Mutex, OnceLock};+use codync_network::{Address, Agent, Connector, Node, Peer, Reach};+use serde_json::json;+use std::collections::{BTreeSet, HashMap};+use std::sync::{Arc, Mutex};use std::time::{Duration, Instant};+pub use api::{create, emit, invite, join, leave, peers, promote, recover, remove, set_rules, status, view};pub use handles::handle;-const KV_CONNECTOR: &str = "network_connector";/// Every address name ever given to one of this computer's bots (name → bot id).const KV_HANDLES: &str = "network_handles";-/// Who on the other computers may write to this computer's bots (`codync_network::Rule`s).-const KV_RULES: &str = "network_rules";/// How long what the other computers offer is good for before a listing asks them again.const FRESH_FOR: Duration = Duration::from_mins(1);/// How long a listing waits for computers it has never heard from.@@ -36,30 +39,65 @@ enum Due {Again,}+/// One network this computer is in.+#[derive(Clone)]+pub struct Slot {+ /// Its folder in the data directory, and its id in the API.+ pub id: String,+ /// What the user calls it (`home`), unique on this computer.+ pub name: String,+ pub node: Arc<Node>,+}+#[derive(Default)]pub struct Network {- node: OnceLock<Arc<Node>>,+ /// The first is the default: bare names look there first.+ slots: Mutex<Vec<Slot>>,asked: Mutex<Option<Instant>>,handles: Mutex<handles::Handles>,/// Names this computer sends letters as without offering them (`Node::set_senders`): the cloud/// assistant, and agents that aren't bots (`codync-host mcp network`).- senders: Mutex<std::collections::BTreeSet<String>>,+ senders: Mutex<BTreeSet<String>>,+ /// One create, join or leave at a time.+ changing: tokio::sync::Mutex<()>,}/// Who a `message_bot` request is for.pub enum Recipient {/// One of this computer's bots, by id (whether it exists is the caller's to check).Here(String),- There(Address),+ There(Target),}-fn dir() -> PathBuf {- crate::service::data_dir().join("network")+/// A bot on another computer, and the network the letter goes through.+#[derive(Clone)]+pub struct Target {+ pub network: String,+ pub address: Address,}impl Network {- pub fn node(&self) -> Option<Arc<Node>> {- self.node.get().cloned()+ pub fn slots(&self) -> Vec<Slot> {+ self.slots.locked().clone()+ }++ /// A network by its id or its name; the only one when `which` is `None`.+ pub fn slot(&self, which: Option<&str>) -> Result<Slot> {+ let slots = self.slots.locked();+ match which {+ Some(w) => slots.iter().find(|s| s.id == w || s.name.eq_ignore_ascii_case(w)).cloned().ok_or_else(|| {+ let names: Vec<&str> = slots.iter().map(|s| s.name.as_str()).collect();+ anyhow!("no network called {w} here (this computer is in: {})", list(&names))+ }),+ None => match &slots[..] {+ [only] => Ok(only.clone()),+ [] => bail!("this computer isn't in a network: create one or join with an invite"),+ many => {+ let names: Vec<&str> = many.iter().map(|s| s.name.as_str()).collect();+ bail!("this computer is in several networks ({}): say which", list(&names))+ }+ },+ }}/// The address name of one of this computer's bots.@@ -67,21 +105,41 @@ impl Network {self.handles.locked().handle(bot)}- /// The other computers and their bots, as last heard; refreshed in the background when stale,- /// and waited for (briefly) the first time.+ /// This computer's name in its first network, if it is in one.+ pub fn my_name(&self) -> Option<String> {+ self.slots.locked().first().and_then(|s| s.node.name())+ }++ /// The other computers and their bots in every network, as last heard; refreshed in the+ /// background when stale, and waited for (briefly) the first time. A computer in several+ /// networks names each of their computers with the network (`desk.home`).pub async fn directory(&self) -> Vec<Peer> {- let Some(node) = self.node() else { return Vec::new() };+ let slots = self.slots();match self.due() {Some(Due::First) => {- let _ = tokio::time::timeout(FIRST_LOOK, node.peers()).await;+ let asks = slots.iter().map(|s| s.node.peers());+ let _ = tokio::time::timeout(FIRST_LOOK, futures::future::join_all(asks)).await;}Some(Due::Again) => {- let refresh = node.clone();- tokio::spawn(async move { refresh.peers().await });+ for slot in &slots {+ let node = slot.node.clone();+ tokio::spawn(async move { node.peers().await });+ }}None => {}}- node.directory().into_iter().filter(|p| !p.me).collect()+ let several = slots.len() > 1;+ slots+ .iter()+ .flat_map(|s| {+ s.node.directory().into_iter().filter(|p| !p.me).map(move |mut p| {+ if several {+ p.name = format!("{}.{}", p.name, s.name);+ }+ p+ })+ })+ .collect()}/// Whether what the other computers offer is due to be asked again; counted as asked from now.@@ -96,35 +154,68 @@ impl Network {Some(due)}- /// Where `name` points: a bot id, an address name, `name@` this computer or a bare name none of- /// its bots has are this computer's; `name@computer`, or a bare name one other computer offers,- /// is a bot there.+ /// Where `name` points. A bot id or address name of this computer's is here, and so is a bare+ /// name no network offers. `name@computer` is that computer in whichever network has it, and+ /// `[email protected]` names the network; a bare name one other computer offers is there.+ /// Refuses a name that two networks would both take, naming the full addresses.pub fn recipient(&self, name: &str) -> Result<Recipient> {- let (handle, computer) = name.rsplit_once('@').map_or((name, None), |(handle, c)| (handle, Some(c)));+ let (handle, at) = name.rsplit_once('@').map_or((name, None), |(handle, at)| (handle, Some(at)));let here = self.handles.locked().bot(handle);- let local = Ok(Recipient::Here(here.clone().unwrap_or_else(|| name.to_owned())));- let Some(node) = self.node() else { return local };- if computer.is_none() && here.is_some() {- return local;+ let local = || Ok(Recipient::Here(here.clone().unwrap_or_else(|| name.to_owned())));+ if at.is_none() && here.is_some() {+ return local();}- match node.resolve(name) {- Ok(address) if node.name().as_deref() == Some(&address.computer) => local,- Ok(address) => Ok(Recipient::There(address)),- Err(_) if computer.is_none() => local,- Err(error) => Err(error),+ let (computer, network) = match at.map(|at| at.split_once('.').map_or((at, None), |(c, n)| (c, Some(n)))) {+ Some((computer, network)) => (Some(computer), network),+ None => (None, None),+ };+ let slots = match network {+ Some(n) => vec![self.slot(Some(n))?],+ None => self.slots(),+ };+ let mut found: Vec<Target> = Vec::new();+ let mut errors = Vec::new();+ for slot in &slots {+ let ask = computer.map_or_else(|| handle.to_owned(), |c| format!("{handle}@{c}"));+ match slot.node.resolve(&ask) {+ Ok(address) if slot.node.name().as_deref() == Some(&address.computer) => return local(),+ Ok(address) => found.push(Target { network: slot.id.clone(), address }),+ Err(error) => errors.push(error),+ }+ }+ match &found[..] {+ [] if computer.is_none() => local(),+ [] => Err(errors.into_iter().next().unwrap_or_else(|| anyhow!("this computer isn't in a network"))),+ [only] => Ok(Recipient::There(only.clone())),+ many => {+ let names: Vec<String> = many.iter().map(|t| self.full_address(t)).collect();+ bail!("more than one network has {name}: {}; use the full address", list(&names))+ }}}+ /// How a target reads in listings and chats: `agent@computer`, with the network+ /// (`[email protected]`) while this computer is in several.+ pub fn address_text(&self, target: &Target) -> String {+ if self.slots.locked().len() > 1 { self.full_address(target) } else { target.address.to_string() }+ }++ /// `[email protected]`.+ fn full_address(&self, target: &Target) -> String {+ let network = self.slot(Some(&target.network)).map_or_else(|_| target.network.clone(), |s| s.name);+ format!("{}.{network}", target.address)+ }+/// Lets this computer send letters as `name` without offering it, unless a bot goes by it.pub fn send_as(&self, name: &str) -> Result<()> {if let Some(bot) = self.bot_for(name) {bail!("a bot here ({bot}) already goes by {name} on the network: give the agent another name");}let mut senders = self.senders.locked();- if senders.insert(name.to_owned())- && let Some(node) = self.node()- {- node.set_senders(senders.iter().cloned());+ if senders.insert(name.to_owned()) {+ for slot in self.slots() {+ slot.node.set_senders(senders.iter().cloned());+ }}Ok(())}@@ -135,52 +226,74 @@ impl Network {}}-/// Starts the node when this computer is in a network.-pub async fn start(hub: &Arc<Hub>) {- if !dir().join("network.json").exists() {- return;- }- if let Err(error) = boot(hub).await {- tracing::warn!(error = format!("{error:#}"), "couldn't start the network");+/// `a, b and c`.+fn list(names: &[impl AsRef<str>]) -> String {+ let names: Vec<&str> = names.iter().map(AsRef::as_ref).collect();+ match &names[..] {+ [] => "none".into(),+ [one] => (*one).to_owned(),+ [rest @ .., last] => format!("{} and {last}", rest.join(", ")),}}-async fn boot(hub: &Arc<Hub>) -> Result<Arc<Node>> {- if let Some(node) = hub.network.node() {- return Ok(node);+/// Starts the node of every network this computer is in.+pub async fn start(hub: &Arc<Hub>) {+ for saved in saved::load(hub) {+ let id = saved.id.clone();+ if let Err(error) = boot(hub, &saved).await {+ tracing::warn!(network = id, error = format!("{error:#}"), "couldn't start a network");+ }}- let connector: Connector = hub.store.kv_get(KV_CONNECTOR).as_deref().unwrap_or("public").parse()?;- let (node, inbox) = Node::start(&dir(), &connector).await.context("couldn't start the network")?;- let rules: Vec<Rule> = hub.store.kv_get(KV_RULES).and_then(|v| serde_json::from_str(&v).ok()).unwrap_or_default();- if let Err(error) = node.set_rules(rules) {+}++/// Starts one network's node and takes it in.+async fn boot(hub: &Arc<Hub>, saved: &saved::Saved) -> Result<Slot> {+ let (node, inbox) = start_node(saved).await?;+ Ok(take_in(hub, saved, node, inbox))+}++async fn start_node(saved: &saved::Saved) -> Result<(Node, tokio::sync::mpsc::Receiver<codync_network::Message>)> {+ let connector: Connector = saved.connector.parse()?;+ Node::start(&saved::dir(&saved.id), &connector).await.context("couldn't start the network")+}++/// A started node becomes one of this computer's networks: its rules and name, what this computer+/// offers, and the letters that reach it.+fn take_in(+ hub: &Arc<Hub>,+ saved: &saved::Saved,+ node: Node,+ inbox: tokio::sync::mpsc::Receiver<codync_network::Message>,+) -> Slot {+ if let Err(error) = node.set_rules(saved.rules.clone()) {tracing::warn!(error = format!("{error:#}"), "couldn't apply the network's rules; none apply");}- let node = Arc::new(node);- hub.network.node.set(node.clone()).map_err(|_| anyhow!("the network is already starting; try again"))?;- tokio::spawn(watch(hub.clone(), node.changes()));+ node.set_network_name(Some(saved.name.clone()));+ node.set_senders(hub.network.senders.locked().iter().cloned());+ let slot = Slot { id: saved.id.clone(), name: saved.name.clone(), node: Arc::new(node) };+ hub.network.slots.locked().push(slot.clone());+ tokio::spawn(watch(hub.clone(), slot.node.changes()));publish(hub);- tokio::spawn(crate::chat::team::remote::listen(hub.clone(), inbox));- tracing::info!(computer = node.name().as_deref().unwrap_or("(none yet)"), "network on");- Ok(node)+ tokio::spawn(crate::chat::team::remote::listen(hub.clone(), slot.id.clone(), inbox));+ tracing::info!(network = slot.name, computer = slot.node.name().as_deref().unwrap_or("(none yet)"), "network on");+ slot}-/// Tells this computer's apps and paired phones what the network looks like now, after every-/// change the node reports.+/// Tells this computer's apps and paired phones what the networks look like now, after every+/// change a node reports. Ends when the node goes (leaving the network).async fn watch(hub: Arc<Hub>, mut changes: tokio::sync::watch::Receiver<()>) {while changes.changed().await.is_ok() {emit(&hub);}}-/// The `network` event: what `networkView` answers.-pub fn emit(hub: &Hub) {- let _ = hub.events.send(json!({"type": "network", "network": status(hub)}));-}--/// Offers this computer's visible bots to the network, under their address names. Called after-/// every change to a bot's name, description or visibility.+/// Offers this computer's visible bots to every network, under their address names. Called+/// after every change to a bot's name, description or visibility.pub fn publish(hub: &Hub) {- let Some(node) = hub.network.node() else { return };+ let slots = hub.network.slots();+ if slots.is_empty() {+ return;+ }let bots = match crate::chat::team::visible_bots(&hub.store) {Ok(bots) => bots,Err(error) => {@@ -209,133 +322,9 @@ pub fn publish(hub: &Hub) {}).collect();drop(handles);- node.set_agents(agents);-}--fn joined(hub: &Hub) -> Result<Arc<Node>> {- hub.network- .node()- .filter(|n| n.name().is_some())- .ok_or_else(|| anyhow!("this computer isn't in a network: create one or join with an invite"))-}--/// `networkStatus`, the `network` event and the stream's hello: this computer and the others, as-/// last heard, with what this computer may do (`canInvite`, `canRecover`) and do to each-/// (`canRemove`, `canPromote`); plus the cloud assistants switch, and whether they can reach this-/// computer at all (`assistantsAvailable`). Never an invite: phones read it too.-pub fn status(hub: &Hub) -> Value {- let assistants = crate::chat::team::assistant::enabled(&hub.store);- let available = crate::chat::team::assistant::available(hub);- let Some(node) = hub.network.node().filter(|n| n.name().is_some()) else {- return json!({"joined": false, "assistants": assistants, "assistantsAvailable": available});- };- let mine = node.role();- let computers: Vec<Value> = node- .directory()- .into_iter()- .map(|p| {- let agents: Vec<Value> = p.agents.iter().map(|a| json!({"id": a.id, "name": a.name})).collect();- let may = |rule: fn(Role, Role) -> bool| !p.me && mine.is_some_and(|me| rule(me, p.role));- json!({- "name": p.name, "role": p.role, "me": p.me, "online": p.online, "agents": agents,- "canRemove": may(Role::removes), "canPromote": may(Role::promotes),- })- })- .collect();- json!({- "joined": true, "computer": node.name(), "role": mine,- "canInvite": mine.is_some_and(Role::invites), "canRecover": mine.is_some_and(|r| r != Role::Owner),- "connector": hub.store.kv_get(KV_CONNECTOR).unwrap_or_else(|| "public".into()),- "computers": computers, "assistants": assistants, "assistantsAvailable": available,- "rules": node.rules(),- })-}--/// `networkView`: `status`, asking the others in the background when what they offer is stale;-/// the `network` event brings what they answer. The first look since the host started is left to-/// bot listings, which wait for it (`Network::directory`).-pub fn view(hub: &Hub) -> Value {- let looked = hub.network.asked.locked().is_some();- if looked- && let Some(node) = hub.network.node()- && hub.network.due().is_some()- {- tokio::spawn(async move { node.peers().await });- }- status(hub)-}--/// `networkCreate`: a new network with this computer as its owner; returns the recovery code.-pub async fn create(hub: &Arc<Hub>, name: Option<&str>, connector: Option<&str>) -> Result<Value> {- if joined(hub).is_ok() {- bail!("this computer is already in a network");- }- set_connector(hub, connector)?;- let node = boot(hub).await?;- let code = node.create(&name.map_or_else(default_name, str::to_owned))?;- publish(hub);- Ok(json!({"computer": node.name(), "recoveryCode": code}))-}--/// `networkJoin`: joins with an invite from the owner or an admin.-pub async fn join(hub: &Arc<Hub>, invite: &str, name: Option<&str>, connector: Option<&str>) -> Result<Value> {- if joined(hub).is_ok() {- bail!("this computer is already in a network");- }- set_connector(hub, connector)?;- let node = boot(hub).await?;- node.join(invite, &name.map_or_else(default_name, str::to_owned)).await?;- publish(hub);- Ok(status(hub))-}--/// `networkInvite`: a one-time invite and when it stops working (Unix ms).-pub fn invite(hub: &Hub) -> Result<Value> {- let invite = joined(hub)?.invite()?;- let lasts = i64::try_from(codync_network::INVITE_FOR.as_millis()).expect("an invite lasts an hour");- let until = crate::store::now_ms().saturating_add(lasts);- Ok(json!({"invite": invite, "expiresAt": until}))-}--/// `networkPeers`: asks every computer now.-pub async fn peers(hub: &Arc<Hub>) -> Result<Value> {- joined(hub)?.peers().await?;- *hub.network.asked.locked() = Some(Instant::now());- Ok(status(hub))-}--pub fn remove(hub: &Hub, computer: &str, cascade: bool) -> Result<Value> {- joined(hub)?.remove(computer, cascade)?;- Ok(json!({}))-}--/// `setNetworkRules`: who on the other computers may write to this computer's bots, in order-/// (the first match decides); an empty list lets everyone.-pub fn set_rules(hub: &Hub, rules: &Value) -> Result<Value> {- let rules: Vec<Rule> =- serde_json::from_value(rules.clone()).context("rules are {fromComputer, fromAgent, toAgent, access}")?;- joined(hub)?.set_rules(rules.clone())?;- hub.store.kv_set(KV_RULES, &json!(rules).to_string())?;- emit(hub);- Ok(status(hub))-}--pub fn promote(hub: &Hub, computer: &str) -> Result<Value> {- joined(hub)?.promote(computer)?;- Ok(json!({}))-}--pub fn recover(hub: &Hub, code: &str) -> Result<Value> {- joined(hub)?.recover(code)?;- Ok(json!({}))-}--fn set_connector(hub: &Hub, connector: Option<&str>) -> Result<()> {- if let Some(connector) = connector {- connector.parse::<Connector>()?;- hub.store.kv_set(KV_CONNECTOR, connector)?;+ for slot in slots {+ slot.node.set_agents(agents.clone());}- Ok(())}/// This computer's host name, as a network name can hold it.diff --git a/host/src/network/saved.rs b/host/src/network/saved.rsnew file mode 100644index 00000000..d73ff8af--- /dev/null+++ b/host/src/network/saved.rs@@ -0,0 +1,96 @@+//! The networks this computer is in, as kept between runs: kv `networks`, each with its node's+//! folder in the data directory.++use crate::hub::Hub;+use anyhow::{Result, bail};+use codync_network::Rule;+use serde::{Deserialize, Serialize};+use std::path::PathBuf;++const KV: &str = "networks";+/// The folder of the network a computer joined before it could be in several.+const FIRST: &str = "network";++#[derive(Serialize, Deserialize, Clone, Debug, PartialEq, Eq)]+pub struct Saved {+ /// Its node's folder, and its id in the API.+ pub id: String,+ pub name: String,+ /// `public`, `private` or a relay URL.+ pub connector: String,+ #[serde(default)]+ pub rules: Vec<Rule>,+}++pub fn dir(id: &str) -> PathBuf {+ crate::service::data_dir().join(id)+}++/// The networks to start: kv `networks`, or the one network a computer was in before.+pub fn load(hub: &Hub) -> Vec<Saved> {+ if let Some(saved) = hub.store.kv_get(KV).and_then(|v| serde_json::from_str(&v).ok()) {+ return saved;+ }+ if !dir(FIRST).join("network.json").exists() {+ return Vec::new();+ }+ let first = Saved {+ id: FIRST.into(),+ name: "home".into(),+ connector: hub.store.kv_get("network_connector").unwrap_or_else(|| "public".into()),+ rules: hub.store.kv_get("network_rules").and_then(|v| serde_json::from_str(&v).ok()).unwrap_or_default(),+ };+ if let Err(error) = save(hub, std::slice::from_ref(&first)) {+ tracing::warn!(error = format!("{error:#}"), "couldn't keep the network's settings");+ }+ vec![first]+}++pub fn save(hub: &Hub, all: &[Saved]) -> Result<()> {+ hub.store.kv_set(KV, &serde_json::to_string(all)?)+}++/// A folder no network uses yet: `network`, then `network-<random>`.+pub fn new_id(all: &[Saved]) -> String {+ if all.iter().all(|s| s.id != FIRST) && !dir(FIRST).exists() {+ return FIRST.into();+ }+ loop {+ let id = format!("{FIRST}-{}", &uuid::Uuid::new_v4().simple().to_string()[..8]);+ if !dir(&id).exists() {+ return id;+ }+ }+}++/// `name` as a network name (like a computer's: no spaces, `@` or `.`, which addresses use),+/// numbered when another network here has it (`home-2`).+pub fn free_name(all: &[Saved], name: &str) -> Result<String> {+ let name = super::handle(name.trim());+ if name.len() > 40 {+ bail!("a network's name is at most 40 characters");+ }+ let taken = |n: &str| all.iter().any(|s| s.name.eq_ignore_ascii_case(n));+ // One more number than there are networks: one of them is free.+ Ok(std::iter::once(name.clone())+ .chain((2..=all.len() + 2).map(|i| format!("{name}-{i}")))+ .find(|n| !taken(n))+ .expect("a number is free"))+}++#[cfg(test)]+mod tests {+ use super::*;++ fn saved(id: &str, name: &str) -> Saved {+ Saved { id: id.into(), name: name.into(), connector: "public".into(), rules: Vec::new() }+ }++ #[test]+ fn a_taken_network_name_gets_a_number() {+ let all = [saved("network", "home"), saved("network-1", "home-2")];+ assert_eq!(free_name(&all, "Work").unwrap(), "work");+ assert_eq!(free_name(&all, "home").unwrap(), "home-3");+ assert_eq!(free_name(&all, "my.lab").unwrap(), "my-lab", "no dots: addresses use them");+ }+}diff --git a/host/src/network_cli.rs b/host/src/network_cli.rsindex d61f05f2..70c7d72c 100644--- a/host/src/network_cli.rs+++ b/host/src/network_cli.rs@@ -10,6 +10,10 @@ pub struct NetworkArgs {/// The running host's port (also after the action).#[arg(long, global = true, default_value_t = crate::service::DEFAULT_PORT)]port: u16,+ /// Which network, by name, when this computer is in several (for create and join: the new+ /// network's name; join takes the invite's otherwise).+ #[arg(long, global = true)]+ network: Option<String>,#[command(subcommand)]action: Option<Action>,}@@ -37,6 +41,8 @@ enum Action {},/// Ask every computer now.Peers,+ /// Stop being in a network on this computer (the others list it until it is removed there).+ Leave,/// Take a computer out of the network for good.Remove {computer: String,@@ -52,10 +58,12 @@ enum Action {pub async fn run(args: NetworkArgs) -> Result<()> {let port = args.port;+ let network = args.network;match args.action.unwrap_or(Action::Status) {Action::Status => print_status(&local_call(port, "networkStatus", json!({})).await?),Action::Create { name, connector } => {- let v = local_call(port, "networkCreate", json!({"name": name, "connector": connector})).await?;+ let body = json!({"name": name, "connector": connector, "network": network});+ let v = local_call(port, "networkCreate", body).await?;println!("Created a network with {} as its owner.", v["computer"].as_str().unwrap_or("this computer"));println!("Recovery code (shown once; keep it in a password manager: it makes another computer the owner");println!("if this one is lost):\n {}", v["recoveryCode"].as_str().unwrap_or_default());@@ -64,27 +72,31 @@ pub async fn run(args: NetworkArgs) -> Result<()> {);}Action::Invite => {- let v = local_call(port, "networkInvite", json!({})).await?;+ let v = local_call(port, "networkInvite", json!({"network": network})).await?;println!("{}", v["invite"].as_str().unwrap_or_default());println!("One use, for an hour, while this computer stays on: `codync-host network join '<invite>'` on the other one.");}Action::Join { invite, name, connector } => {- let body = json!({"invite": invite, "name": name, "connector": connector});+ let body = json!({"invite": invite, "name": name, "connector": connector, "network": network});print_status(&local_call(port, "networkJoin", body).await?);}- Action::Peers => print_status(&local_call(port, "networkPeers", json!({})).await?),+ Action::Peers => print_status(&local_call(port, "networkPeers", json!({"network": network})).await?),+ Action::Leave => {+ print_status(&local_call(port, "networkLeave", json!({"network": network})).await?);+ }Action::Remove { computer, cascade } => {- local_call(port, "networkRemove", json!({"computer": computer, "cascade": cascade})).await?;+ let body = json!({"computer": computer, "cascade": cascade, "network": network});+ local_call(port, "networkRemove", body).await?;println!("Removed {computer}.");}Action::Promote { computer } => {- local_call(port, "networkPromote", json!({"computer": computer})).await?;+ local_call(port, "networkPromote", json!({"computer": computer, "network": network})).await?;println!("{computer} is an admin.");}Action::Recover { code } => {- local_call(port, "networkRecover", json!({"code": code})).await?;+ local_call(port, "networkRecover", json!({"code": code, "network": network})).await?;println!("This computer is the owner now. Remove the lost one with `codync-host network remove <name>`.");}}@@ -92,24 +104,29 @@ pub async fn run(args: NetworkArgs) -> Result<()> {}fn print_status(v: &Value) {- if v["joined"] != true {+ let networks = v["networks"].as_array().map_or(&[][..], Vec::as_slice);+ if networks.is_empty() {println!("This computer isn't in a network. Create one (`codync-host network create`) or join with an invite.");return;}- let me = v["computer"].as_str().unwrap_or_default();- let role = v["role"].as_str().unwrap_or_default();- println!("{me} ({role}) · connector {}", v["connector"].as_str().unwrap_or("public"));- for c in v["computers"].as_array().into_iter().flatten() {- let state = if c["me"] == true {- "this computer"- } else if c["online"] == true {- "online"- } else {- "away"- };- let bots: Vec<&str> = c["agents"].as_array().into_iter().flatten().filter_map(|a| a["id"].as_str()).collect();- let name = c["name"].as_str().unwrap_or_default();- let role = c["role"].as_str().unwrap_or_default();- println!(" {name:<20} {role:<7} {state:<14} {}", bots.join(", "));+ for n in networks {+ let me = n["computer"].as_str().unwrap_or_default();+ let role = n["role"].as_str().unwrap_or_default();+ let name = n["name"].as_str().unwrap_or_default();+ println!("{name}: {me} ({role}) · connector {}", n["connector"].as_str().unwrap_or("public"));+ for c in n["computers"].as_array().into_iter().flatten() {+ let state = if c["me"] == true {+ "this computer"+ } else if c["online"] == true {+ "online"+ } else {+ "away"+ };+ let bots: Vec<&str> =+ c["agents"].as_array().into_iter().flatten().filter_map(|a| a["id"].as_str()).collect();+ let name = c["name"].as_str().unwrap_or_default();+ let role = c["role"].as_str().unwrap_or_default();+ println!(" {name:<20} {role:<7} {state:<14} {}", bots.join(", "));+ }}}diff --git a/host/tests/fixtures/wire-shape.json b/host/tests/fixtures/wire-shape.jsonindex 0cf2814c..762b0c6a 100644--- a/host/tests/fixtures/wire-shape.json+++ b/host/tests/fixtures/wire-shape.json@@ -184,6 +184,7 @@"event:hello.network.assistants": "bool","event:hello.network.assistantsAvailable": "bool","event:hello.network.joined": "bool",+ "event:hello.network.networks": "array","event:hello.rev": "number","event:hello.type": "string","hello": "object",diff --git a/host/tests/network_e2e.rs b/host/tests/network_e2e.rsindex f07cae48..a3105b4a 100644--- a/host/tests/network_e2e.rs+++ b/host/tests/network_e2e.rs@@ -98,7 +98,8 @@ async fn two_computers() -> (Host, Host, String, String) {assert!(created["recoveryCode"].as_str().unwrap().len() > 60);let invite = desk.call("networkInvite", json!({})).await["invite"].as_str().unwrap().to_owned();let joined = laptop.call("networkJoin", json!({"invite": invite, "name": "laptop", "connector": "private"})).await;- assert_eq!((joined["computer"].as_str(), joined["role"].as_str()), (Some("laptop"), Some("member")));+ let home = &joined["networks"][0];+ assert_eq!((home["computer"].as_str(), home["role"].as_str()), (Some("laptop"), Some("member")));let reviewer = desk.bot("Reviewer").await;let lead = laptop.bot("Lead").await;(desk, laptop, reviewer, lead)@@ -108,7 +109,7 @@ async fn two_computers() -> (Host, Host, String, String) {async fn a_bot_messages_a_bot_on_another_computer_and_relays_its_reply() {let (desk, laptop, reviewer, lead) = two_computers().await;let peers = laptop.call("networkPeers", json!({})).await;- let desk_row = peers["computers"].as_array().unwrap().iter().find(|c| c["name"] == "desk").unwrap().clone();+ let desk_row = computer(&peers, "desk").clone();assert_eq!((desk_row["online"].as_bool(), desk_row["role"].as_str()), (Some(true), Some("owner")));// Every visible bot goes by its address name (the host's own lead bot too).assert!(desk_row["agents"].as_array().unwrap().iter().any(|a| a["id"] == "reviewer"), "{desk_row}");@@ -136,7 +137,7 @@ async fn a_bot_messages_a_bot_on_another_computer_and_relays_its_reply() {let history = laptop.call("botConversation", json!({"botId": lead, "peerId": "reviewer@desk"})).await;assert_eq!(history["entries"].as_array().unwrap().len(), 1);let status = laptop.call("networkStatus", json!({})).await;- assert_eq!(status["computers"].as_array().unwrap().len(), 2);+ assert_eq!(status["networks"][0]["computers"].as_array().unwrap().len(), 2);}#[tokio::test]@@ -189,8 +190,9 @@ async fn network_event(base: String, token: String, predicate: impl Fn(&Value) -.expect("no network event")}+/// A computer in the view's first network.fn computer<'a>(view: &'a Value, name: &str) -> &'a Value {- view["computers"].as_array().unwrap().iter().find(|c| c["name"] == name).unwrap()+ view["networks"][0]["computers"].as_array().unwrap().iter().find(|c| c["name"] == name).unwrap()}#[tokio::test]@@ -199,7 +201,8 @@ async fn the_network_view_says_who_may_do_what_and_changes_reach_the_apps() {desk.call("networkPeers", json!({})).await;let view = desk.call("networkView", json!({})).await;assert_eq!((view["joined"].as_bool(), view["assistants"].as_bool()), (Some(true), Some(false)));- assert_eq!((&view["canInvite"], &view["canRecover"]), (&json!(true), &json!(false)), "the owner invites");+ let home = &view["networks"][0];+ assert_eq!((&home["canInvite"], &home["canRecover"]), (&json!(true), &json!(false)), "the owner invites");let row = computer(&view, "laptop");assert_eq!((row["canRemove"].as_bool(), row["canPromote"].as_bool()), (Some(true), Some(true)));assert!(row["agents"].as_array().unwrap().iter().any(|a| a["name"] == "Lead"), "{row}");@@ -210,13 +213,15 @@ async fn the_network_view_says_who_may_do_what_and_changes_reach_the_apps() {// A member may do nothing to the owner.let theirs = laptop.call("networkView", json!({})).await;assert_eq!(- (computer(&theirs, "desk")["canRemove"].as_bool(), theirs["role"].as_str()),+ (computer(&theirs, "desk")["canRemove"].as_bool(), theirs["networks"][0]["role"].as_str()),(Some(false), Some("member")));- assert_eq!((&theirs["canInvite"], &theirs["canRecover"]), (&json!(false), &json!(true)));+ let home = &theirs["networks"][0];+ assert_eq!((&home["canInvite"], &home["canRecover"]), (&json!(false), &json!(true)));// The owner promotes the laptop: both computers' apps hear of it without asking.- let there = tokio::spawn(network_event(laptop.base.clone(), laptop.token.clone(), |v| v["role"] == "admin"));+ let there =+ tokio::spawn(network_event(laptop.base.clone(), laptop.token.clone(), |v| v["networks"][0]["role"] == "admin"));let here = tokio::spawn(network_event(desk.base.clone(), desk.token.clone(), |v| {computer(v, "laptop")["role"] == "admin"}));@@ -233,14 +238,15 @@ async fn a_bot_kept_off_the_network_and_a_deny_rule_keep_letters_out() {let secret = desk.bot("Secret").await;desk.call("updateBot", json!({"id": secret, "offeredToNetwork": false})).await;let peers = laptop.call("networkPeers", json!({})).await;- let offered: Vec<&Value> = computer(&peers, "desk")["agents"].as_array().unwrap().iter().map(|a| &a["id"]).collect();+ let offered: Vec<&Value> =+ computer(&peers, "desk")["agents"].as_array().unwrap().iter().map(|a| &a["id"]).collect();assert!(offered.contains(&&json!("reviewer")), "{offered:?}");assert!(!offered.contains(&&json!("secret")), "kept off the network: {offered:?}");// The desk takes nothing from the laptop's bots; the lead's message_bot says why.let rules = json!([{"fromComputer": "laptop", "fromAgent": "*", "toAgent": "*", "access": "deny"}]);let view = desk.call("setNetworkRules", json!({"rules": rules})).await;- assert_eq!(view["rules"][0]["access"], "deny");+ assert_eq!(view["networks"][0]["rules"][0]["access"], "deny");laptop.call("send", json!({"botId": lead, "text": "TRY reviewer@desk review this"})).await;let refused = laptop.wait_for(&lead, is_final).await;let text = refused["data"]["text"].as_str().unwrap();@@ -253,3 +259,56 @@ async fn a_bot_kept_off_the_network_and_a_deny_rule_keep_letters_out() {let history = desk.call("history", json!({"botId": reviewer})).await;assert!(!history.to_string().contains("review this"), "nothing reached the reviewer");}++#[tokio::test]+async fn a_computer_in_two_networks_keeps_them_apart() {+ let (desk, laptop, _reviewer, lead) = two_computers().await;+ let server = Host::start().await;+ // The desk makes a second network for the server; the invite carries its name.+ let work = desk.call("networkCreate", json!({"network": "work", "name": "desk", "connector": "private"})).await;+ let invite = desk.call("networkInvite", json!({"network": "work"})).await["invite"].as_str().unwrap().to_owned();+ let joined = server.call("networkJoin", json!({"invite": invite, "name": "server", "connector": "private"})).await;+ assert_eq!(joined["networks"][0]["name"], "work");+ let tester = server.bot("Tester").await;+ let status = desk.call("networkPeers", json!({})).await;+ let names: Vec<&str> = status["networks"].as_array().unwrap().iter().map(|n| n["name"].as_str().unwrap()).collect();+ assert_eq!(names, ["home", "work"]);+ // The laptop is in one network: it never sees the server.+ let laptops = laptop.call("networkPeers", json!({})).await;+ assert_eq!(laptops["networks"].as_array().unwrap().len(), 1);+ assert!(!laptops.to_string().contains("server"));+ // Joining a network twice is refused; inviting needs the network named now.+ let again = desk.call("networkInvite", json!({"network": "work"})).await["invite"].as_str().unwrap().to_owned();+ let refused = reqwest::Client::new()+ .post(format!("{}/api/networkJoin", server.base))+ .bearer_auth(&server.token)+ .json(&json!({"invite": again}))+ .send()+ .await+ .unwrap();+ assert!(!refused.status().is_success());+ let unnamed = reqwest::Client::new()+ .post(format!("{}/api/networkInvite", desk.base))+ .bearer_auth(&desk.token)+ .json(&json!({}))+ .send()+ .await+ .unwrap();+ assert!(unnamed.text().await.unwrap().contains("several networks"));+ assert!(work["recoveryCode"].as_str().unwrap().len() > 60);++ // The desk's bots list both networks' computers with the network named.+ let desk_lead = desk.bot("Lead").await;+ let _ = (lead, tester);+ desk.call("send", json!({"botId": desk_lead, "text": "TRY [email protected] hello"})).await;+ let sent = desk.wait_for(&desk_lead, is_final).await;+ assert!(sent["data"]["text"].as_str().unwrap().starts_with("Sent: "), "{sent}");+ let exchange = desk.wait_for(&desk_lead, |e| e["kind"] == "notice" && e["data"]["botMessage"].is_object()).await;+ assert_eq!(exchange["data"]["botMessage"]["targetBotId"], "[email protected]");++ // Leaving work forgets it here; home stays.+ let left = desk.call("networkLeave", json!({"network": "work"})).await;+ let names: Vec<&str> = left["networks"].as_array().unwrap().iter().map(|n| n["name"].as_str().unwrap()).collect();+ assert_eq!(names, ["home"]);+ assert!(!desk.home.join(work["network"].as_str().unwrap()).exists());+}