Skip to content

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.

feat(host): network view for phones, live network event, invite expiry

leepokaif77bdfb1b370
diff --git a/host/crates/network/src/lib.rs b/host/crates/network/src/lib.rs
index ba8c3231..ec142010 100644
--- a/host/crates/network/src/lib.rs
+++ b/host/crates/network/src/lib.rs
@@ -23,7 +23,7 @@ mod roster;
mod types;
mod wire;
-pub use node::Node;
+pub use node::{INVITE_FOR, Node};
pub use reach::Reach;
pub use roster::Role;
pub use types::{Address, Connector, Letter, Message, Peer, Sent};
diff --git a/host/crates/network/src/node/directory.rs b/host/crates/network/src/node/directory.rs
index 5ff5a7bb..071e40f3 100644
--- a/host/crates/network/src/node/directory.rs
+++ b/host/crates/network/src/node/directory.rs
@@ -8,6 +8,7 @@ use anyhow::{Result, anyhow, bail};
use iroh::EndpointId;
/// What a computer offered when it last answered, and whether the last try got through.
+#[derive(Clone, PartialEq, Eq)]
pub(super) struct Seen {
agents: Vec<Agent>,
answered: bool,
@@ -20,13 +21,16 @@ impl Inner {
/// Notes that `id` answered with `agents`, or (`None`) that it didn't.
pub(super) fn saw(&self, id: EndpointId, agents: Option<Vec<Agent>>) {
let mut seen = locked(&self.seen);
- match agents {
- Some(agents) => {
- seen.insert(id, Seen { agents, answered: true });
- }
- None => {
- seen.entry(id).or_insert(Seen { agents: Vec::new(), answered: false }).answered = false;
- }
+ let changed = if let Some(agents) = agents {
+ let now = Seen { agents, answered: true };
+ seen.insert(id, now.clone()).is_none_or(|before| before != now)
+ } else {
+ let heard = seen.entry(id).or_insert(Seen { agents: Vec::new(), answered: false });
+ std::mem::replace(&mut heard.answered, false)
+ };
+ drop(seen);
+ if changed {
+ self.changed.send_replace(());
}
}
diff --git a/host/crates/network/src/node/inbound.rs b/host/crates/network/src/node/inbound.rs
index 230981ac..9b6bb268 100644
--- a/host/crates/network/src/node/inbound.rs
+++ b/host/crates/network/src/node/inbound.rs
@@ -167,7 +167,7 @@ impl Inner {
.sign(key, wire::now_ms(), Change::Admit { id: peer, name })
.map_err(|_| anyhow!("this computer can no longer invite: only the owner and admins can"))?;
let welcome = Response::Welcome { roster: roster.clone() };
- roster.save(&self.dir)?;
+ self.save(roster)?;
drop(guard);
self.saw(peer, Some(Vec::new()));
tracing::info!(peer = %peer.fmt_short(), "a computer joined the network");
diff --git a/host/crates/network/src/node/mod.rs b/host/crates/network/src/node/mod.rs
index 355d3966..9019d761 100644
--- a/host/crates/network/src/node/mod.rs
+++ b/host/crates/network/src/node/mod.rs
@@ -18,11 +18,12 @@ use std::path::{Path, PathBuf};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex, MutexGuard};
use std::time::{Duration, Instant};
-use tokio::sync::mpsc;
+use tokio::sync::{mpsc, watch};
use tokio::task::JoinSet;
const KEY_FILE: &str = "secret.key";
-const INVITE_FOR: Duration = Duration::from_hours(1);
+/// How long an invite stays good.
+pub const INVITE_FOR: Duration = Duration::from_hours(1);
const CONNECT_TIMEOUT: Duration = Duration::from_secs(10);
/// Long enough for the other computer to knock on its agent's harness.
const CALL_TIMEOUT: Duration = Duration::from_secs(20);
@@ -55,6 +56,9 @@ struct Inner {
inbox: mpsc::Sender<Message>,
/// The command an agent the network knocks on runs to answer.
reply_command: Mutex<String>,
+ /// Ticks when the members, their roles or names, or what the others offer or whether they
+ /// answer, change.
+ changed: watch::Sender<()>,
}
fn locked<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
@@ -84,6 +88,7 @@ impl Node {
outbox: Mutex::default(),
inbox: tx,
reply_command: Mutex::new("codync-network".into()),
+ changed: watch::Sender::new(()),
});
let router = Router::builder(endpoint).accept(ALPN, inbound::Handler(inner.clone())).spawn();
settle(&inner.endpoint, connector).await;
@@ -116,7 +121,7 @@ impl Node {
}
let key = self.inner.endpoint.secret_key();
let (new, root) = Roster::create(key, check_name(name)?, self.inner.endpoint.addr(), wire::now_ms());
- new.save(&self.inner.dir)?;
+ self.inner.save(&new)?;
*roster = Some(new);
Ok(roster::recovery_code(&root))
}
@@ -152,7 +157,7 @@ impl Node {
// Where this computer is; nothing to add when it knows no address yet.
let addr = self.inner.endpoint.addr();
let _ = roster.sign(self.inner.endpoint.secret_key(), wire::now_ms(), Change::Locate { addr });
- roster.save(&self.inner.dir)?;
+ self.inner.save(&roster)?;
*locked(&self.inner.roster) = Some(roster);
self.inner.clone().hello_all();
Ok(())
@@ -189,18 +194,20 @@ impl Node {
}
let name = roster.name(&self.id());
roster.sign(&root, wire::now_ms(), Change::Owner { id: self.id(), name })?;
- roster.save(&self.inner.dir)?;
+ self.inner.save(roster)?;
drop(guard);
self.inner.clone().hello_all();
Ok(())
}
- /// The agents this computer offers, and how each is reached. Others see them the next time
- /// they ask.
/// What this computer offers. The first call opens it to letters, and the others hear at once,
/// so what waited for it while it started comes now.
pub fn set_agents(&self, agents: impl IntoIterator<Item = (Agent, Reach)>) {
+ let before = self.inner.offered();
*locked(&self.inner.agents) = agents.into_iter().collect();
+ if self.inner.offered() != before {
+ self.inner.changed.send_replace(());
+ }
if !self.inner.ready.swap(true, Ordering::AcqRel) {
self.inner.clone().hello_all();
}
@@ -228,6 +235,13 @@ impl Node {
self.inner.directory()
}
+ /// Changes whenever what [`Node::directory`] shows does: a computer joins or leaves, a role
+ /// or name changes, another computer offers different agents, or it starts or stops
+ /// answering. Ticks only; read the directory for what changed.
+ pub fn changes(&self) -> watch::Receiver<()> {
+ self.inner.changed.subscribe()
+ }
+
/// Where a bare agent name or a full `agent@computer` points: this computer first, then the
/// directory. Refuses a name more than one computer has, naming them.
pub fn resolve(&self, name: &str) -> Result<Address> {
@@ -321,7 +335,7 @@ impl Inner {
let mut guard = locked(&self.roster);
let roster = guard.as_mut().ok_or_else(|| anyhow!("this computer isn't in a network"))?;
roster.sign(self.endpoint.secret_key(), wire::now_ms(), change).map_err(|_| anyhow!("{refused}"))?;
- roster.save(&self.dir)?;
+ self.save(roster)?;
drop(guard);
self.clone().hello_all();
Ok(())
@@ -336,7 +350,14 @@ impl Inner {
return Ok(());
}
roster.sign(self.endpoint.secret_key(), wire::now_ms(), Change::Locate { addr })?;
- roster.save(&self.dir)
+ self.save(roster)
+ }
+
+ /// Keeps `roster` on disk and tells whoever watches [`Node::changes`].
+ fn save(&self, roster: &Roster) -> Result<()> {
+ roster.save(&self.dir)?;
+ self.changed.send_replace(());
+ Ok(())
}
async fn connect(&self, id: EndpointId) -> Result<Connection> {
@@ -397,7 +418,7 @@ impl Inner {
let mut guard = locked(&self.roster);
let Some(mine) = guard.as_mut() else { return Ok(()) };
if mine.merge(theirs) {
- mine.save(&self.dir)?;
+ self.save(mine)?;
}
Ok(())
}
diff --git a/host/crates/network/src/roster.rs b/host/crates/network/src/roster.rs
index 2891455b..93b6f6b4 100644
--- a/host/crates/network/src/roster.rs
+++ b/host/crates/network/src/roster.rs
@@ -34,6 +34,20 @@ pub enum Role {
Owner,
}
+impl Role {
+ /// Whether a computer with this role may remove one with `other`: the owner removes anyone,
+ /// admins remove plain members.
+ pub fn removes(self, other: Role) -> bool {
+ self == Role::Owner || (self == Role::Admin && other == Role::Member)
+ }
+
+ /// Whether a computer with this role may make one with `other` an admin: only the owner, and
+ /// only a plain member.
+ pub fn promotes(self, other: Role) -> bool {
+ self == Role::Owner && other == Role::Member
+ }
+}
+
/// One computer in the network, as the log has it now.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Member {
diff --git a/host/crates/network/tests/two_computers.rs b/host/crates/network/tests/two_computers.rs
index 46918a3a..fe678ed6 100644
--- a/host/crates/network/tests/two_computers.rs
+++ b/host/crates/network/tests/two_computers.rs
@@ -232,3 +232,46 @@ async fn a_reply_reaches_an_agent_renamed_since_it_asked_and_carries_the_chain_o
let _ = std::fs::remove_dir_all(dir);
}
}
+
+#[tokio::test]
+async fn changes_tick_when_who_is_in_or_around_changes() {
+ let (desk_dir, laptop_dir) = (temp_dir("desk6"), temp_dir("laptop6"));
+ let (desk, _) = Node::start(&desk_dir, &Connector::Private).await.unwrap();
+ let mut changes = desk.changes();
+ desk.create("desk").unwrap();
+ assert!(changes.has_changed().unwrap(), "creating the network");
+ changes.mark_unchanged();
+
+ let (laptop, _) = Node::start(&laptop_dir, &Connector::Private).await.unwrap();
+ offer(&laptop, "coder");
+ laptop.join(&desk.invite().unwrap(), "laptop").await.unwrap();
+ tokio::time::timeout(Duration::from_secs(5), changes.changed()).await.expect("a join within 5 s").unwrap();
+ desk.peers().await.unwrap();
+ changes.mark_unchanged();
+
+ // Asking again with nothing new is quiet.
+ desk.peers().await.unwrap();
+ assert!(!changes.has_changed().unwrap());
+ desk.promote("laptop").unwrap();
+ assert!(changes.has_changed().unwrap(), "a promotion");
+ changes.mark_unchanged();
+ offer(&laptop, "reviewer");
+ desk.peers().await.unwrap();
+ assert!(changes.has_changed().unwrap(), "what the laptop offers");
+ changes.mark_unchanged();
+ laptop.shutdown().await;
+ desk.peers().await.unwrap();
+ assert!(changes.has_changed().unwrap(), "the laptop went away");
+ assert!(!desk.directory()[1].online);
+ for dir in [desk_dir, laptop_dir] {
+ let _ = std::fs::remove_dir_all(dir);
+ }
+}
+
+#[test]
+fn roles_decide_who_removes_and_promotes() {
+ use Role::{Admin, Member, Owner};
+ assert!(Owner.removes(Admin) && Owner.removes(Member) && Admin.removes(Member));
+ assert!(!Admin.removes(Admin) && !Admin.removes(Owner) && !Member.removes(Member));
+ assert!(Owner.promotes(Member) && !Owner.promotes(Admin) && !Admin.promotes(Member));
+}
diff --git a/host/src/analytics.rs b/host/src/analytics.rs
index 998f572e..22c29b35 100644
--- a/host/src/analytics.rs
+++ b/host/src/analytics.rs
@@ -98,6 +98,7 @@ pub enum Event {
HostUpdateInstalled,
/// `networkCreate` or `networkJoin`: this computer is in a network of the user's computers.
NetworkJoined,
+ NetworkChanged,
/// Error tracking (`errors`): a panic or an uncaught error.
Exception,
}
@@ -158,6 +159,7 @@ impl Event {
Self::SettingChanged => "setting_changed",
Self::HostUpdateInstalled => "host_update_installed",
Self::NetworkJoined => "network_joined",
+ Self::NetworkChanged => "network_changed",
Self::Exception => "$exception",
}
}
diff --git a/host/src/analytics/observe.rs b/host/src/analytics/observe.rs
index 9545cdb0..e21d119e 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); 8] = [
+const FIXED: [(&str, Event, &str, &str); 12] = [
("editHandoff", Event::HandoffAnswered, "action", "edit"),
("keepConversation", Event::HandoffAnswered, "action", "keep"),
("credentialSaveLogin", Event::CredentialSaved, "kind", "login"),
@@ -17,6 +17,11 @@ const FIXED: [(&str, Event, &str, &str); 8] = [
("setComposioKey", Event::CredentialSaved, "kind", "composio"),
("setVoiceKey", Event::CredentialSaved, "kind", "voice"),
("setAgentEnv", Event::CredentialSaved, "kind", "agent_env"),
+ // Never the computer's name, the invite or the recovery code.
+ ("networkInvite", Event::NetworkChanged, "action", "invite"),
+ ("networkPromote", Event::NetworkChanged, "action", "promote"),
+ ("networkRemove", Event::NetworkChanged, "action", "remove"),
+ ("networkRecover", Event::NetworkChanged, "action", "recover"),
];
/// Switches the host owns (`setting_changed`): the method and the setting it names.
diff --git a/host/src/analytics/reported.rs b/host/src/analytics/reported.rs
index 9293e41f..eb8a4aa8 100644
--- a/host/src/analytics/reported.rs
+++ b/host/src/analytics/reported.rs
@@ -158,6 +158,7 @@ pub enum Screen {
Help,
Library,
Artifact,
+ Network,
#[serde(other)]
Other,
}
diff --git a/host/src/api/network.rs b/host/src/api/network.rs
index a041a372..bdbe12e6 100644
--- a/host/src/api/network.rs
+++ b/host/src/api/network.rs
@@ -1,5 +1,5 @@
//! Methods for this computer's network (codync-network): only this computer's own apps call
-//! them (`devices::LOCAL_ONLY`).
+//! them (`devices::LOCAL_ONLY`), except `networkView`, which paired phones read.
use super::str_arg;
use crate::hub::Hub;
@@ -13,6 +13,7 @@ pub(super) async fn call(hub: &Arc<Hub>, method: &str, b: Value) -> Result<Contr
let text = |k: &str| b[k].as_str().filter(|s| !s.trim().is_empty());
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)?,
diff --git a/host/src/chat/team/assistant.rs b/host/src/chat/team/assistant.rs
index 722ad8df..82b1fc48 100644
--- a/host/src/chat/team/assistant.rs
+++ b/host/src/chat/team/assistant.rs
@@ -28,7 +28,7 @@ const MAX_RUNNING: usize = 16;
const KEEP: usize = 50;
const SHOW: usize = 20;
const OFF: &str = "Cloud assistants are off on this computer. To let ChatGPT or Claude message its bots, \
-run `codync-host cloud --assistants on` on it.";
+turn on Cloud assistants in Codync's settings on it (or run `codync-host cloud --assistants on`).";
pub fn enabled(store: &Store) -> bool {
store.kv_get(KV).as_deref() == Some("on")
@@ -40,6 +40,8 @@ pub fn set_enabled(hub: &Hub, on: bool) -> Result<CloudStatus> {
hub.store.kv_set(KV, if on { "on" } else { "off" })?;
tracing::info!(on, "cloud assistants changed");
cloud::update_status(hub, |s| s.assistants = on);
+ // Phones see the switch through the network view.
+ crate::network::emit(hub);
Ok(hub.cloud.status())
}
diff --git a/host/src/network/mod.rs b/host/src/network/mod.rs
index bc8ea43e..d9178f1a 100644
--- a/host/src/network/mod.rs
+++ b/host/src/network/mod.rs
@@ -9,7 +9,7 @@ mod handles;
use crate::LockExt;
use crate::hub::Hub;
use anyhow::{Context, Result, anyhow, bail};
-use codync_network::{Address, Agent, Connector, Node, Peer, Reach};
+use codync_network::{Address, Agent, Connector, Node, Peer, Reach, Role};
use serde_json::{Value, json};
use std::collections::HashMap;
use std::path::PathBuf;
@@ -58,24 +58,31 @@ impl Network {
/// and waited for (briefly) the first time.
pub async fn directory(&self) -> Vec<Peer> {
let Some(node) = self.node() else { return Vec::new() };
- let (first, stale) = {
- let mut asked = self.asked.locked();
- let first = asked.is_none();
- let stale = asked.is_none_or(|at| at.elapsed() >= FRESH_FOR);
- if stale {
- *asked = Some(Instant::now());
+ match self.stale() {
+ Some(true) => {
+ let _ = tokio::time::timeout(FIRST_LOOK, node.peers()).await;
}
- (first, stale)
- };
- if first {
- let _ = tokio::time::timeout(FIRST_LOOK, node.peers()).await;
- } else if stale {
- let refresh = node.clone();
- tokio::spawn(async move { refresh.peers().await });
+ Some(false) => {
+ let refresh = node.clone();
+ tokio::spawn(async move { refresh.peers().await });
+ }
+ None => {}
}
node.directory().into_iter().filter(|p| !p.me).collect()
}
+ /// Whether what the other computers offer is due to be asked again (now counted as asked), and
+ /// if so whether it is the first time.
+ fn stale(&self) -> Option<bool> {
+ let mut asked = self.asked.locked();
+ let first = asked.is_none();
+ if !asked.is_none_or(|at| at.elapsed() >= FRESH_FOR) {
+ return None;
+ }
+ *asked = Some(Instant::now());
+ Some(first)
+ }
+
/// 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.
@@ -119,12 +126,26 @@ async fn boot(hub: &Arc<Hub>) -> Result<Arc<Node>> {
let (node, inbox) = Node::start(&dir(), &connector).await.context("couldn't start the network")?;
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()));
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)
}
+/// Tells this computer's apps and paired phones what the network looks like now, after every
+/// change the node reports.
+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": view_of(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.
pub fn publish(hub: &Hub) {
@@ -164,26 +185,51 @@ fn joined(hub: &Hub) -> Result<Arc<Node>> {
.ok_or_else(|| anyhow!("this computer isn't in a network: create one or join with an invite"))
}
-/// `networkStatus`: this computer and the others, as last heard.
+/// `networkStatus`: this computer and the others, as last heard, with what this computer may do
+/// to each (`canRemove`, `canPromote`).
pub fn status(hub: &Hub) -> Value {
let Some(node) = hub.network.node().filter(|n| n.name().is_some()) else {
return json!({"joined": false});
};
+ let mine = node.role();
let computers: Vec<Value> = node
.directory()
.into_iter()
.map(|p| {
let bots: Vec<&str> = p.agents.iter().map(|a| a.id.as_str()).collect();
- json!({"name": p.name, "role": p.role, "me": p.me, "online": p.online, "bots": bots})
+ 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, "bots": bots, "agents": agents,
+ "canRemove": may(Role::removes), "canPromote": may(Role::promotes),
+ })
})
.collect();
json!({
- "joined": true, "computer": node.name(), "role": node.role(),
+ "joined": true, "computer": node.name(), "role": mine,
"connector": hub.store.kv_get(KV_CONNECTOR).unwrap_or_else(|| "public".into()),
"computers": computers,
})
}
+/// `networkView`: what phones may see of the network (status, never an invite), plus whether
+/// cloud assistants may reach this computer's bots. Asks the others in the background when
+/// stale; the `network` event brings what they answer.
+pub fn view(hub: &Hub) -> Value {
+ if let Some(node) = hub.network.node()
+ && hub.network.stale().is_some()
+ {
+ tokio::spawn(async move { node.peers().await });
+ }
+ view_of(hub)
+}
+
+fn view_of(hub: &Hub) -> Value {
+ let mut v = status(hub);
+ v["assistants"] = crate::chat::team::assistant::enabled(&hub.store).into();
+ v
+}
+
/// `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() {
@@ -208,8 +254,11 @@ pub async fn join(hub: &Arc<Hub>, invite: &str, name: Option<&str>, connector: O
Ok(status(hub))
}
+/// `networkInvite`: a one-time invite and when it stops working (Unix ms).
pub fn invite(hub: &Hub) -> Result<Value> {
- Ok(json!({"invite": joined(hub)?.invite()?}))
+ let invite = joined(hub)?.invite()?;
+ let until = crate::store::now_ms() + i64::try_from(codync_network::INVITE_FOR.as_millis()).unwrap_or(i64::MAX);
+ Ok(json!({"invite": invite, "expiresAt": until}))
}
/// `networkPeers`: asks every computer now.
diff --git a/host/tests/network_e2e.rs b/host/tests/network_e2e.rs
index 8260543c..44601019 100644
--- a/host/tests/network_e2e.rs
+++ b/host/tests/network_e2e.rs
@@ -159,3 +159,68 @@ async fn a_stopped_or_failed_request_ends_the_senders_notice() {
let finals = history["entries"].as_array().unwrap().iter().filter(|e| is_final(e)).count();
assert_eq!(finals, 3, "two requests and one reply turn: {history}");
}
+
+/// The first `network` event on the host's stream that `predicate` accepts. The stream is open
+/// once this returns its future's first poll; the caller gives it a moment before changing things.
+async fn network_event(base: String, token: String, predicate: impl Fn(&Value) -> bool) -> Value {
+ use futures::StreamExt as _;
+ let res = reqwest::Client::new()
+ .get(format!("{base}/events?since={}&client=test", i64::MAX))
+ .bearer_auth(token)
+ .send()
+ .await
+ .unwrap();
+ let mut body = res.bytes_stream();
+ let mut buf = String::new();
+ tokio::time::timeout(Duration::from_secs(20), async {
+ while let Some(Ok(chunk)) = body.next().await {
+ buf.push_str(&String::from_utf8_lossy(&chunk));
+ while let Some(i) = buf.find('\n') {
+ let line: String = buf.drain(..=i).collect();
+ let event = line.trim_end().strip_prefix("data:").and_then(|d| serde_json::from_str::<Value>(d).ok());
+ if let Some(event) = event.filter(|e| e["type"] == "network" && predicate(&e["network"])) {
+ return event["network"].clone();
+ }
+ }
+ }
+ panic!("the event stream ended");
+ })
+ .await
+ .expect("no network event")
+}
+
+fn computer<'a>(view: &'a Value, name: &str) -> &'a Value {
+ view["computers"].as_array().unwrap().iter().find(|c| c["name"] == name).unwrap()
+}
+
+#[tokio::test]
+async fn the_network_view_says_who_may_do_what_and_changes_reach_the_apps() {
+ let (desk, laptop, _reviewer, _lead) = two_computers().await;
+ 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)));
+ 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}");
+ assert_eq!(computer(&view, "desk")["canRemove"], false, "not itself");
+ let invite = desk.call("networkInvite", json!({})).await;
+ let in_an_hour = chrono::Utc::now().timestamp_millis() + 3_500_000;
+ assert!(invite["expiresAt"].as_i64().unwrap() > in_an_hour, "{invite}");
+ // 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()),
+ (Some(false), Some("member"))
+ );
+
+ // 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 here = tokio::spawn(network_event(desk.base.clone(), desk.token.clone(), |v| {
+ computer(v, "laptop")["role"] == "admin"
+ }));
+ tokio::time::sleep(Duration::from_millis(500)).await;
+ desk.call("networkPromote", json!({"computer": "laptop"})).await;
+ let there = there.await.unwrap();
+ assert_eq!(computer(&there, "desk")["canRemove"], false, "an admin doesn't remove the owner");
+ assert_eq!(computer(&here.await.unwrap(), "laptop")["canPromote"], false, "already an admin");
+}