Merge main into archy-hwconfig — reconcile probe/dedup/name work

Both sides independently fixed the serial-alias dedup and the ESP32
boot-reset races; kept the branch's defer-to-auto-detect for unpinned
preferred paths (single probe pass per cycle) on top of main's
advert-name threading, Reticulum name propagation and radio-first
routing. Modal keeps main's 'Set Recommended' naming + probe progress
bar alongside the branch's in-app firmware flasher step.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
archipelago
2026-07-28 19:03:19 -04:00
co-authored by Claude Fable 5
173 changed files with 10967 additions and 1925 deletions
+19 -1
View File
@@ -578,7 +578,7 @@ pub(super) async fn handle_identity_received(
.insert(contact_id, shared_secret);
// Update peer record
let peer = MeshPeer {
let mut peer = MeshPeer {
contact_id,
// .get(): a malformed DID shorter than the "did:key:" prefix must
// not panic the listener on a radio-supplied string.
@@ -607,6 +607,24 @@ pub(super) async fn handle_identity_received(
let is_new = {
let mut peers = state.peers.write().await;
let is_new = !peers.contains_key(&contact_id);
if let Some(existing) = peers.get(&contact_id) {
// This id is shared with the federation-seeded row for the same
// node (that's the point — identity adverts MERGE, not duplicate).
// The wholesale insert below must not stomp the federation row's
// real node name with our synthetic "Archy-…" placeholder — with
// Reticulum re-emitting identity adverts every announce tick,
// that renamed every federated contact once a minute. Same for a
// known position: keep it rather than nulling it out.
if !existing.advert_name.trim().is_empty()
&& !existing.advert_name.starts_with("Archy-")
{
peer.advert_name = existing.advert_name.clone();
}
if peer.lat.is_none() {
peer.lat = existing.lat;
peer.lon = existing.lon;
}
}
peers.insert(contact_id, peer.clone());
is_new
};
+13 -3
View File
@@ -450,7 +450,10 @@ impl MeshState {
let persisted: PersistedMessages = match serde_json::from_slice(&bytes) {
Ok(p) => p,
Err(e) => {
warn!("mesh: parsing {} failed (skipping restore): {e}", path.display());
warn!(
"mesh: parsing {} failed (skipping restore): {e}",
path.display()
);
return;
}
};
@@ -466,7 +469,10 @@ impl MeshState {
*id = max_id + 1;
}
}
info!("mesh: restored {count} persisted messages (next id {})", max_id + 1);
info!(
"mesh: restored {count} persisted messages (next id {})",
max_id + 1
);
}
}
@@ -510,7 +516,11 @@ pub fn spawn_message_persister(state: Arc<MeshState>) {
warn!("mesh: chmod {} failed: {e}", tmp.display());
}
if let Err(e) = tokio::fs::rename(&tmp, &path).await {
warn!("mesh: renaming {} -> {} failed: {e}", tmp.display(), path.display());
warn!(
"mesh: renaming {} -> {} failed: {e}",
tmp.display(),
path.display()
);
continue;
}
last_written = Some(json);
+143 -55
View File
@@ -269,10 +269,24 @@ async fn auto_detect_and_open(
our_ed_pubkey_hex: &str,
our_x25519_pubkey_hex: &str,
device_kind: Option<DeviceType>,
skip_path: Option<&str>,
advert_name: Option<&str>,
) -> Result<(String, MeshRadioDevice, DeviceInfo)> {
let paths = super::super::serial::detect_serial_devices().await;
let mut paths = super::super::serial::detect_serial_devices().await;
// When falling back from a just-failed preferred path, don't probe that
// same device again in the same cycle — every open() toggles DTR/RTS,
// which resets ESP32-family boards, and back-to-back re-probes are what
// keeps a mid-boot board from ever finishing its boot.
if let Some(skip) = skip_path {
let canon = |p: &str| std::fs::canonicalize(p).unwrap_or_else(|_| p.into());
let skip_canon = canon(skip);
paths.retain(|p| canon(p) != skip_canon);
}
if paths.is_empty() {
anyhow::bail!("No serial devices found in /dev");
anyhow::bail!(match skip_path {
Some(skip) => format!("No serial devices found in /dev besides {skip}, which was already probed this cycle"),
None => "No serial devices found in /dev".to_string(),
});
}
info!(candidates = ?paths, "Auto-detect candidate ports for this attempt");
for path in &paths {
@@ -292,6 +306,7 @@ async fn auto_detect_and_open(
data_dir,
Some(our_ed_pubkey_hex),
Some(our_x25519_pubkey_hex),
advert_name,
)
.await
{
@@ -360,6 +375,16 @@ pub struct DeviceProbe {
pub max_contacts: Option<u16>,
}
/// Serializes serial-port open sequences between the listener's session
/// opens and the RPC probe (`mesh.probe-device`). Linux happily double-opens
/// a tty, and two concurrent handshakes corrupt each other into silence —
/// observed live on .116 (2026-07-26): the kiosk browser's hot-swap
/// auto-probe collided with the listener's cycle on every backoff window, so
/// neither ever succeeded, and each collision's open() DTR/RTS-reset the
/// board again. The probe's retry-across-idle-gaps heuristic (5f01ec31)
/// narrowed but could not close the race; this closes it.
static PORT_OPEN_LOCK: tokio::sync::Mutex<()> = tokio::sync::Mutex::const_new(());
/// Probe a serial port for a mesh radio WITHOUT provisioning it: identify the
/// firmware (same strict Reticulum→Meshcore→Meshtastic order as auto-detect,
/// for the same RNode-wedging reason) and read what's currently configured on
@@ -367,11 +392,10 @@ pub struct DeviceProbe {
/// loop can pick the device up afterwards. Reticulum uses the bare KISS
/// DETECT probe — no daemon spawn just to identify a stick.
pub(crate) async fn probe_device(path: &str) -> Result<DeviceProbe> {
// The listener's reconnect loop may hold this port for ~10s of every
// backoff cycle, and Linux happily double-opens a tty — two concurrent
// handshakes corrupt each other into silence (observed on framework-pt:
// every firmware "failed" while the listener was mid-cycle). Retry across
// the listener's idle gaps instead of failing on first collision.
// Retries kept even with PORT_OPEN_LOCK closing the double-open race:
// the board may still be mid-boot from a previous open's DTR/RTS reset,
// and a later attempt after a quiet gap can succeed where the first
// couldn't.
let mut last_err = None;
for attempt in 0..3u32 {
if attempt > 0 {
@@ -386,6 +410,7 @@ pub(crate) async fn probe_device(path: &str) -> Result<DeviceProbe> {
}
async fn probe_device_once(path: &str) -> Result<DeviceProbe> {
let _port_guard = PORT_OPEN_LOCK.lock().await;
if super::super::reticulum::probe_rnode(path).await.is_ok() {
return Ok(DeviceProbe {
path: path.to_string(),
@@ -443,6 +468,7 @@ async fn open_preferred_path(
our_ed_pubkey_hex: &str,
our_x25519_pubkey_hex: &str,
device_kind: Option<DeviceType>,
advert_name: Option<&str>,
) -> Result<(MeshRadioDevice, DeviceInfo)> {
// Pinned: try only the configured firmware and surface its own error —
// never fall through to (and inject probe bytes into) another firmware's
@@ -475,6 +501,7 @@ async fn open_preferred_path(
data_dir,
Some(our_ed_pubkey_hex),
Some(our_x25519_pubkey_hex),
advert_name,
)
.await
.context("Could not open preferred path as Reticulum")?;
@@ -499,7 +526,9 @@ async fn open_preferred_path(
// Reticulum/Meshcore/Meshtastic's DTR/RTS toggle TWICE: once here, once
// again moments later in auto-detect. Bailing immediately (no port
// access at all) means auto-detect's single pass is the only one that
// ever touches the port when nothing is pinned yet.
// ever touches the port when nothing is pinned yet. (auto_detect_and_open
// carries the advert_name threading from main, so nothing is lost.)
let _ = advert_name;
anyhow::bail!("No device_kind pin — deferring to auto-detect for {path}")
}
@@ -513,6 +542,7 @@ async fn open_reticulum_tcp(
data_dir: &Path,
our_ed_pubkey_hex: &str,
our_x25519_pubkey_hex: &str,
advert_name: Option<&str>,
) -> Result<(String, MeshRadioDevice, DeviceInfo)> {
let mut dev = match cfg {
ReticulumTcpConfig::Server { bind } => ReticulumLink::open_tcp_server(
@@ -520,6 +550,7 @@ async fn open_reticulum_tcp(
data_dir,
Some(our_ed_pubkey_hex),
Some(our_x25519_pubkey_hex),
advert_name,
)
.await
.context("Could not open Reticulum TCP server interface")?,
@@ -528,6 +559,7 @@ async fn open_reticulum_tcp(
data_dir,
Some(our_ed_pubkey_hex),
Some(our_x25519_pubkey_hex),
advert_name,
)
.await
.context("Could not open Reticulum TCP client interface")?,
@@ -943,41 +975,93 @@ pub(super) async fn run_mesh_session(
// set, otherwise try the preferred serial path, falling back to
// auto-detect. TCP mode is additive/dev-only; it never changes behavior
// for existing serial/RNode deployments where `reticulum_tcp` is None.
let (device_path, mut device, device_info) = if let Some(tcp_cfg) = &reticulum_tcp {
open_reticulum_tcp(tcp_cfg, data_dir, our_ed_pubkey_hex, our_x25519_pubkey_hex).await?
} else if let Some(path) = preferred_path {
match open_preferred_path(
path,
data_dir,
our_ed_pubkey_hex,
our_x25519_pubkey_hex,
device_kind,
)
.await
{
Ok((dev, info)) => (path.to_string(), dev, info),
Err(e) => {
warn!(
"Preferred path {} probe failed: {} — trying auto-detect",
path, e
);
auto_detect_and_open(
data_dir,
our_ed_pubkey_hex,
our_x25519_pubkey_hex,
device_kind,
)
.await?
//
// The name we present on the mesh: the operator's configured mesh name /
// server name, falling back to a DID fragment. Computed BEFORE the open
// sequence because Reticulum needs it at daemon-spawn time — the RNS
// announce carries it from the very first announce. (Meshcore/Meshtastic
// still receive it via set_advert_name after connect, below.)
let desired_advert_name: String = match server_name {
// Meshcore firmware limits advert names — truncate to 20 chars.
Some(name) => name.chars().take(20).collect(),
None => format!(
"Archy-{}",
our_did.chars().skip(8).take(8).collect::<String>()
),
};
// The whole open sequence runs under PORT_OPEN_LOCK so an RPC probe
// can't interleave its own handshakes on the same tty (see the lock's
// doc comment). Held only until the device is opened, then released.
//
// The sequence is raced against the shutdown signal: probes/handshakes
// can take 10s+, and without this a stop() issued mid-probe (config
// change, disable, rename) always burned the full listener-shutdown
// timeout and ended in a hard abort — observed live on archi-dev-box
// 2026-07-28. Dropping the open future mid-probe is safe: it holds no
// session state yet and the port guard/serial handle close with it.
let open_fut = async {
let port_guard = PORT_OPEN_LOCK.lock().await;
let result = if let Some(tcp_cfg) = &reticulum_tcp {
open_reticulum_tcp(
tcp_cfg,
data_dir,
our_ed_pubkey_hex,
our_x25519_pubkey_hex,
Some(&desired_advert_name),
)
.await
} else if let Some(path) = preferred_path {
match open_preferred_path(
path,
data_dir,
our_ed_pubkey_hex,
our_x25519_pubkey_hex,
device_kind,
Some(&desired_advert_name),
)
.await
{
Ok((dev, info)) => Ok((path.to_string(), dev, info)),
Err(e) => {
warn!(
"Preferred path {} probe failed: {} — trying auto-detect",
path, e
);
auto_detect_and_open(
data_dir,
our_ed_pubkey_hex,
our_x25519_pubkey_hex,
device_kind,
Some(path),
Some(&desired_advert_name),
)
.await
}
}
} else {
auto_detect_and_open(
data_dir,
our_ed_pubkey_hex,
our_x25519_pubkey_hex,
device_kind,
None,
Some(&desired_advert_name),
)
.await
};
drop(port_guard);
result
};
let (device_path, mut device, device_info) = tokio::select! {
res = open_fut => res?,
_ = shutdown.changed() => {
if *shutdown.borrow() {
info!("Shutdown requested during device open — ending session");
return Ok(());
}
anyhow::bail!("shutdown signal changed during device open");
}
} else {
auto_detect_and_open(
data_dir,
our_ed_pubkey_hex,
our_x25519_pubkey_hex,
device_kind,
)
.await?
};
// Update status
@@ -1125,19 +1209,14 @@ pub(super) async fn run_mesh_session(
}
}
// Set advert name to the server's human-readable name (e.g. "ThinkPad"),
// falling back to the DID fragment if no name is configured. Skipped in
// keep-as-is mode — the radio keeps the name it came with (already
// reflected in status from the connect handshake).
if manage_radio {
let advert_name = if let Some(name) = server_name {
// Meshcore firmware limits advert names — truncate to 20 chars
name.chars().take(20).collect::<String>()
} else {
let short_did = our_did.chars().skip(8).take(8).collect::<String>();
format!("Archy-{}", short_did)
};
if let Err(e) = device.set_advert_name(&advert_name).await {
// Set advert name to the configured mesh/server name (computed above).
// Skipped in keep-as-is mode for radio-held names — the radio keeps the
// name it came with (already reflected in status from the connect
// handshake). Reticulum is exempt from keep-as-is: its display name
// lives in OUR daemon (the RNode holds no name), so "keep as is" has
// nothing to preserve and an unnamed node would be anonymous on RNS.
if manage_radio || matches!(device, MeshRadioDevice::Reticulum(_)) {
if let Err(e) = device.set_advert_name(&desired_advert_name).await {
warn!("Failed to set advert name: {}", e);
} else {
// Reflect the post-set name in MeshStatus too so the UI can filter
@@ -1145,7 +1224,7 @@ pub(super) async fn run_mesh_session(
// still carries whatever pre-set name the firmware reported and the
// self-filter never matches.
let mut status = state.status.write().await;
status.self_advert_name = Some(advert_name.clone());
status.self_advert_name = Some(desired_advert_name.clone());
}
}
@@ -1438,6 +1517,15 @@ async fn handle_send_command(
} else {
*consecutive_write_failures = 0;
}
// The self-advert alone is a no-op for discovery on Meshtastic
// (heartbeat + time carry no identity) — the NodeInfo broadcast
// is what makes peers learn/refresh us. want_response=true so
// neighbours answer with their own NodeInfo: the user pressed
// Broadcast to be seen AND to see who's out there. No-op on
// Meshcore/Reticulum, whose self-advert already carries identity.
if let Err(e) = device.send_nodeinfo_advert(true).await {
warn!("Failed to send NodeInfo advert: {}", e);
}
}
MeshCommand::RebootRadio { seconds } => {
if let Err(e) = device.reboot(seconds).await {
+7 -4
View File
@@ -191,10 +191,13 @@ impl MeshtasticDevice {
.current_modem_preset
.and_then(modem_preset_name)
.map(str::to_string),
primary_channel: self
.current_primary_channel
.as_ref()
.map(|(name, _)| if name.is_empty() { "(default public)".to_string() } else { name.clone() }),
primary_channel: self.current_primary_channel.as_ref().map(|(name, _)| {
if name.is_empty() {
"(default public)".to_string()
} else {
name.clone()
}
}),
secondary_channel: self
.current_secondary_channel
.as_ref()
+161 -4
View File
@@ -478,6 +478,31 @@ impl Default for MeshConfig {
}
}
/// Whether a mesh config file has ever been written for this node — lets the
/// boot path distinguish "operator explicitly disabled mesh" (file exists,
/// enabled=false) from "never configured" (no file), which is the only case
/// radio auto-enable should touch.
pub fn config_file_exists(data_dir: &Path) -> bool {
data_dir.join(MESH_CONFIG_FILE).exists()
}
/// True when `new` differs from `old` in any field a running mesh session
/// captured by value at spawn (device path/kind, advert name, region, PHY
/// params, channel, manage_radio, TCP interface) — i.e. when applying `new`
/// to a live service requires a listener restart. Fields the session reads
/// live from shared state (broadcast flags, assistant settings, steganography
/// mode, …) deliberately don't trigger a restart.
fn session_config_changed(old: &MeshConfig, new: &MeshConfig) -> bool {
old.device_path != new.device_path
|| old.device_kind != new.device_kind
|| old.advert_name != new.advert_name
|| old.lora_region != new.lora_region
|| old.lora_radio_params != new.lora_radio_params
|| old.channel_name != new.channel_name
|| old.manage_radio != new.manage_radio
|| old.reticulum_tcp != new.reticulum_tcp
}
pub async fn load_config(data_dir: &Path) -> Result<MeshConfig> {
let path = data_dir.join(MESH_CONFIG_FILE);
if !path.exists() {
@@ -773,7 +798,11 @@ impl MeshService {
self.our_ed_pubkey_hex.clone(),
self.our_x25519_secret,
self.our_x25519_pubkey_hex.clone(),
self.server_name.clone(),
// The mesh-page "Name on the mesh" (config.advert_name) wins over
// the server name — it existed as write-only config with no reader
// until this line, which is why renaming on the Mesh page never
// changed anything on the air.
self.config.advert_name.clone().or_else(|| self.server_name.clone()),
self.config.lora_region.clone(),
self.config.lora_radio_params,
self.config.channel_name.clone(),
@@ -1071,8 +1100,18 @@ impl MeshService {
/// the actual probe on purpose — see `probe_device`'s doc comment.
pub async fn ensure_probe_allowed(&self, path: &str) -> Result<()> {
let status = self.state.status.read().await;
if status.device_connected && status.device_path.as_deref() == Some(path) {
anyhow::bail!("{path} is the active mesh radio — already connected");
if status.device_connected {
if let Some(active) = status.device_path.as_deref() {
// Compare canonical paths: /dev/mesh-radio is a symlink to the
// ttyUSB*/ttyACM* node, and a probe through the alias would
// still open the very tty the live session is holding.
let canon = |p: &str| {
std::fs::canonicalize(p).unwrap_or_else(|_| std::path::PathBuf::from(p))
};
if canon(active) == canon(path) {
anyhow::bail!("{path} is the active mesh radio — already connected");
}
}
}
Ok(())
}
@@ -1121,7 +1160,32 @@ impl MeshService {
let peer = peers
.get(&contact_id)
.ok_or_else(|| anyhow::anyhow!("Peer not found"))?;
let pubkey_hex = peer
// Cross-transport twin resolution: callers frequently hold the
// FEDERATION twin's contact_id (the UI's merged conversation row),
// whose pubkey_hex is the Archipelago ed25519 key — NOT a radio
// routing key. Sending a Reticulum resource with that prefix fails
// with "Unknown Reticulum prefix" (observed live 2026-07-28,
// image-over-LoRa to a merged contact). Route via the radio twin —
// same arch identity, radio-range id — whose pubkey_hex is the
// actual over-the-air routing key (RNS dest hash / firmware key).
let radio_peer = if peer.contact_id >= FEDERATION_CONTACT_ID_BASE {
peer.arch_pubkey_hex
.as_deref()
.and_then(|arch| {
peers.values().find(|p| {
p.contact_id < FEDERATION_CONTACT_ID_BASE
&& p.arch_pubkey_hex.as_deref() == Some(arch)
})
})
.ok_or_else(|| {
anyhow::anyhow!(
"Peer is federation-only (no radio twin) — not reachable over the radio"
)
})?
} else {
peer
};
let pubkey_hex = radio_peer
.pubkey_hex
.as_ref()
.ok_or_else(|| anyhow::anyhow!("Peer has no public key"))?;
@@ -1259,12 +1323,44 @@ impl MeshService {
.map(|p| !p.reachable && p.arch_pubkey_hex.is_some())
.unwrap_or(false)
};
// Transport policy: LoRa first when it can actually carry the message,
// then FIPS, then Tor. A federation-synthetic id (what the UI's merged
// conversation holds) used to ALWAYS take the federation path, even
// when the very same node was sitting one LoRa hop away — so chats
// between two radio-equipped nodes silently rode FIPS/Tor. If the
// federation contact has a REACHABLE radio twin (same archipelago
// identity, radio-range id) and the payload fits the radio, skip the
// federation branch: the fall-through LoRa path twin-resolves the
// routing key via peer_dest_prefix.
let device_connected = self.state.status.read().await.device_connected;
let radio_twin_reachable = is_federation_synthetic && !exceeds_lora && device_connected && {
let peers = self.state.peers.read().await;
peers
.get(&contact_id)
.and_then(|p| p.arch_pubkey_hex.clone())
.map(|arch| {
peers.values().any(|p| {
p.contact_id < FEDERATION_CONTACT_ID_BASE
&& p.reachable
&& p.arch_pubkey_hex.as_deref() == Some(arch.as_str())
})
})
.unwrap_or(false)
};
let mesh_only_mode = load_config(&self.data_dir)
.await
.ok()
.and_then(|cfg| cfg.mesh_only_mode)
.unwrap_or(false);
if radio_twin_reachable && !mesh_only_mode {
tracing::info!(
contact_id,
bytes = wire.len(),
"Radio-first routing: federation contact has a reachable radio twin — sending over LoRa"
);
}
if !mesh_only_mode
&& !radio_twin_reachable
&& (is_federation_synthetic || exceeds_lora || radio_federated_unreachable)
{
// Resolve the peer's pubkey/did. Prefer the live mesh peer table,
@@ -2088,6 +2184,7 @@ impl MeshService {
save_config(&self.data_dir, &config).await?;
let was_enabled = self.config.enabled;
let needs_session_restart = session_config_changed(&self.config, &config);
self.config = config.clone();
// Update the status to reflect new config
@@ -2112,11 +2209,31 @@ impl MeshService {
status.firmware_version = None;
status.self_node_id = None;
status.peer_count = 0;
} else if config.enabled && was_enabled && needs_session_restart {
info!("Mesh session config changed — restarting listener to apply");
self.stop().await;
self.start()?;
}
Ok(())
}
/// The service's current (last-applied) config.
pub fn config(&self) -> &MeshConfig {
&self.config
}
/// Restart the listener (if running) so it picks up out-of-band state a
/// spawn captured by value — currently the server name pushed by
/// `server.set-name`.
pub async fn restart_listener_if_running(&mut self) -> Result<()> {
if self.listener_handle.is_some() {
self.stop().await;
self.start()?;
}
Ok(())
}
/// Get a reference to shared state (for RPC handlers).
pub fn shared_state(&self) -> Arc<MeshState> {
Arc::clone(&self.state)
@@ -2238,6 +2355,46 @@ async fn bitcoin_rpc_getblockheader_by_height(
mod tests {
use super::*;
#[test]
fn session_config_change_detection() {
let base = MeshConfig::default();
// Same config → no restart.
assert!(!session_config_changed(&base, &base.clone()));
// Every session-captured field individually triggers a restart.
let mut c = base.clone();
c.device_kind = Some(types::DeviceType::Reticulum);
assert!(session_config_changed(&base, &c));
let mut c = base.clone();
c.device_path = Some("/dev/ttyUSB0".into());
assert!(session_config_changed(&base, &c));
let mut c = base.clone();
c.advert_name = Some("RNode Shaza".into());
assert!(session_config_changed(&base, &c));
let mut c = base.clone();
c.manage_radio = !base.manage_radio;
assert!(session_config_changed(&base, &c));
let mut c = base.clone();
c.lora_region = Some("EU_868".into());
assert!(session_config_changed(&base, &c));
let mut c = base.clone();
c.channel_name = Some("private-net".into());
assert!(session_config_changed(&base, &c));
// Live-read fields must NOT force a session restart.
let mut c = base.clone();
c.broadcast_identity = !base.broadcast_identity;
c.announce_block_headers = !base.announce_block_headers;
c.assistant_enabled = !base.assistant_enabled;
assert!(!session_config_changed(&base, &c));
}
fn mk_peer(contact_id: u32, name: &str, arch: Option<&str>, reachable: bool) -> MeshPeer {
MeshPeer {
contact_id,
+261 -42
View File
@@ -121,6 +121,7 @@ fn daemon_command(
identity_key: &Path,
archy_ed_pubkey_hex: Option<&str>,
archy_x25519_pubkey_hex: Option<&str>,
display_name: Option<&str>,
) -> Command {
let bin = std::env::var("ARCHY_RETICULUM_DAEMON_BIN")
.unwrap_or_else(|_| "/usr/local/bin/archy-reticulum-daemon".to_string());
@@ -159,6 +160,15 @@ fn daemon_command(
.arg("--archy-x25519-pubkey-hex")
.arg(x);
}
// The RNS-visible display name (what Sideband/NomadNet/other archy nodes
// show for us). Without this the daemon falls back to its argparse
// default and every archy node announces the same anonymous name.
if let Some(name) = display_name {
let name = name.trim();
if !name.is_empty() {
cmd.arg("--display-name").arg(name);
}
}
// Run the daemon as its own process-group leader. The packaged binary is
// a PyInstaller one-file bootloader that forks the real Python process;
// making it a group leader lets shutdown signal the WHOLE group so the
@@ -207,6 +217,10 @@ struct ReticulumPeer {
/// `bind_federation_twins`, which those two transports rely on instead).
arch_pubkey_hex: Option<String>,
reachable: bool,
/// Unix time of the last announce heard from this peer over the air.
/// In-memory only (a persisted value would be stale by definition) —
/// `0` after a restart until the peer re-announces.
last_advert_at: u64,
}
/// On-disk shape of `ReticulumPeer` — `[u8; 16]` can't be a JSON object key,
@@ -245,6 +259,11 @@ pub struct ReticulumLink {
/// matching `resource_progress`/`resource_sent`/`resource_failed` events
/// back to a log line; sends are fire-and-forget (see `send_resource`).
resource_id_counter: u64,
/// Set when the daemon's RPC socket closes or its process exits. Once
/// true, `try_recv_frame` returns an error so the session loop tears
/// down and the outer reconnect loop respawns the daemon — without this
/// a dead daemon was invisible until the 30-minute RX-stall watchdog.
daemon_gone: bool,
}
impl ReticulumLink {
@@ -269,6 +288,7 @@ impl ReticulumLink {
data_dir: &Path,
our_ed_pubkey_hex: Option<&str>,
our_x25519_pubkey_hex: Option<&str>,
display_name: Option<&str>,
) -> Result<Self> {
probe_rnode(path)
.await
@@ -278,6 +298,7 @@ impl ReticulumLink {
data_dir,
our_ed_pubkey_hex,
our_x25519_pubkey_hex,
display_name,
)
.await
}
@@ -290,6 +311,7 @@ impl ReticulumLink {
data_dir: &Path,
our_ed_pubkey_hex: Option<&str>,
our_x25519_pubkey_hex: Option<&str>,
display_name: Option<&str>,
) -> Result<Self> {
let host = bind.rsplit_once(':').map(|(h, _)| h).unwrap_or(bind);
anyhow::ensure!(
@@ -302,6 +324,7 @@ impl ReticulumLink {
data_dir,
our_ed_pubkey_hex,
our_x25519_pubkey_hex,
display_name,
)
.await
}
@@ -313,6 +336,7 @@ impl ReticulumLink {
data_dir: &Path,
our_ed_pubkey_hex: Option<&str>,
our_x25519_pubkey_hex: Option<&str>,
display_name: Option<&str>,
) -> Result<Self> {
anyhow::ensure!(
!targets.is_empty(),
@@ -323,6 +347,7 @@ impl ReticulumLink {
data_dir,
our_ed_pubkey_hex,
our_x25519_pubkey_hex,
display_name,
)
.await
}
@@ -332,6 +357,7 @@ impl ReticulumLink {
data_dir: &Path,
our_ed_pubkey_hex: Option<&str>,
our_x25519_pubkey_hex: Option<&str>,
display_name: Option<&str>,
) -> Result<Self> {
// Keep the RPC socket under the archipelago-owned data dir (not the
// shared system temp dir) so its access is bounded by the same
@@ -379,6 +405,7 @@ impl ReticulumLink {
&identity_key,
our_ed_pubkey_hex,
our_x25519_pubkey_hex,
display_name,
);
cmd.env("TMPDIR", &tmp_dir);
let child = cmd
@@ -450,6 +477,7 @@ impl ReticulumLink {
peers_file: runtime_dir.join("peers.json"),
inbound: std::collections::VecDeque::new(),
resource_id_counter: 0,
daemon_gone: false,
};
link.load_persisted_peers();
Ok(link)
@@ -472,15 +500,25 @@ impl ReticulumLink {
};
let prefix: [u8; 6] = hash[..6].try_into().unwrap();
self.prefix_to_hash.insert(prefix, hash);
// Heal names persisted by pre-2026-07-28 builds, which could
// store a raw `ARCHY:…` identity blob as the display name (seen
// live on archi-dev-box). Blob-only announces assert no name, so
// nothing would ever overwrite it — swap in the placeholder.
let display_name = if p.display_name.starts_with("ARCHY:") {
format!("Reticulum {}", hex::encode(&hash[..4]))
} else {
p.display_name
};
self.peers.insert(
hash,
ReticulumPeer {
dest_hash: hash,
display_name: p.display_name,
display_name,
arch_pubkey_hex: p.arch_pubkey_hex,
// Reachability is a live property, not a persisted fact —
// start conservative and let the first real event refresh it.
reachable: false,
last_advert_at: 0,
},
);
}
@@ -533,10 +571,12 @@ impl ReticulumLink {
}
pub async fn set_advert_name(&mut self, name: &str) -> Result<()> {
// The daemon's display_name is fixed at spawn time (CLI arg); changing
// it live would require an RPC verb we haven't added. Track locally so
// `advert_name()` reflects the caller's intent even though the
// RNS-visible name doesn't change until the daemon restarts.
// Live rename: the daemon's `set_name` verb updates the LXMF delivery
// destination's display_name and re-announces, so peers pick the new
// name up on their next announce receipt. Also tracked locally so
// `advert_name()` reflects it immediately.
self.send_rpc(serde_json::json!({"cmd": "set_name", "name": name}))
.await?;
self.display_name = Some(name.to_string());
Ok(())
}
@@ -685,7 +725,7 @@ impl ReticulumLink {
.map(|p| ParsedContact {
public_key_hex: hex::encode(p.dest_hash),
advert_name: p.display_name.clone(),
last_advert: 0,
last_advert: p.last_advert_at as u32,
// Deliberately not 1 ("friend"/meshcore type), so the
// meshcore-only auto-heal `reset_contact_path` loop in
// `refresh_contacts` (session.rs) skips these — RNS does its
@@ -718,6 +758,12 @@ impl ReticulumLink {
pub async fn try_recv_frame(&mut self) -> Result<Option<InboundFrame>> {
self.drain_events().await;
if self.daemon_gone {
// Surface the dead daemon as a hard error so run_mesh_session
// bails and the outer reconnect loop respawns it, instead of
// idling on an empty queue until the RX-stall watchdog fires.
anyhow::bail!("reticulum-daemon is gone (process exited or RPC socket closed)");
}
Ok(self.inbound.pop_front())
}
@@ -743,6 +789,15 @@ impl ReticulumLink {
/// Drain any buffered daemon events (non-blocking) and translate them into
/// peer-table updates / synthetic InboundFrames.
async fn drain_events(&mut self) {
// A daemon that died without closing the socket cleanly (SIGKILL,
// OOM) leaves the socket readable-with-EOF or just silent — poll the
// child's exit status too so death is never mistaken for quiet.
if !self.daemon_gone {
if let Ok(Some(status)) = self.child.try_wait() {
warn!(%status, "reticulum-daemon process exited");
self.daemon_gone = true;
}
}
loop {
let mut line = String::new();
let read =
@@ -750,10 +805,16 @@ impl ReticulumLink {
.await;
let n = match read {
Ok(Ok(n)) => n,
_ => break, // timeout (no data) or read error — stop draining
Ok(Err(e)) => {
warn!("Reticulum daemon RPC read failed: {}", e);
self.daemon_gone = true;
break;
}
Err(_) => break, // timeout — no data buffered
};
if n == 0 {
warn!("Reticulum daemon RPC connection closed");
self.daemon_gone = true;
break;
}
let Ok(ev) = serde_json::from_str::<Value>(line.trim()) else {
@@ -775,6 +836,23 @@ impl ReticulumLink {
};
let prefix: [u8; 6] = hash[..6].try_into().unwrap();
self.prefix_to_hash.insert(prefix, hash);
// Current daemons decode the LXMF announce app_data themselves
// and hand us clean fields: `display_name` (LXMF-standard
// msgpack name, Sideband-interoperable) and `archy_blob` (the
// `ARCHY:n:` identity string, carried as an extra msgpack list
// element stock clients ignore). The raw `app_data` text path
// below remains for announces from pre-upgrade archy nodes,
// whose app_data was EITHER the blob OR a bare-utf8 name.
let explicit_name = ev
.get("display_name")
.and_then(Value::as_str)
.map(|s| s.trim().to_string())
.filter(|s| !s.is_empty());
let explicit_blob = ev
.get("archy_blob")
.and_then(Value::as_str)
.map(str::to_string)
.filter(|s| !s.is_empty());
let app_data_text = ev
.get("app_data")
.and_then(Value::as_str)
@@ -794,12 +872,17 @@ impl ReticulumLink {
// now carry the same `arch_pubkey_hex`, instead of relying on
// `bind_federation_twins`'s advert_name matching, which never
// matches here — see `display_name` below.
let parsed_identity = app_data_text
let legacy_identity = app_data_text
.as_deref()
.and_then(protocol::parse_identity_broadcast);
let is_identity_blob = parsed_identity.is_some();
if is_identity_blob {
let text = app_data_text.clone().unwrap();
let is_legacy_blob = legacy_identity.is_some();
let identity_blob_text = explicit_blob.or_else(|| {
app_data_text.clone().filter(|_| is_legacy_blob)
});
let parsed_identity = identity_blob_text
.as_deref()
.and_then(protocol::parse_identity_broadcast);
if let Some(text) = identity_blob_text.as_deref().filter(|_| parsed_identity.is_some()) {
let mut data = Vec::with_capacity(7 + text.len());
data.push(0); // channel index — unused by the identity path
data.extend_from_slice(&prefix);
@@ -812,23 +895,31 @@ impl ReticulumLink {
}
let arch_pubkey_hex = parsed_identity.map(|(_did, ed_pubkey, _x25519)| ed_pubkey);
let display_name = app_data_text
.filter(|_| !is_identity_blob)
.unwrap_or_else(|| format!("Reticulum {}", hex::encode(&hash[..4])));
let announced_name =
pick_announced_name(explicit_name, app_data_text, is_legacy_blob);
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap_or_default()
.as_secs();
self.peers
.entry(hash)
.and_modify(|p| {
p.display_name = display_name.clone();
if let Some(name) = announced_name.clone() {
p.display_name = name;
}
p.reachable = true;
p.last_advert_at = now;
if arch_pubkey_hex.is_some() {
p.arch_pubkey_hex = arch_pubkey_hex.clone();
}
})
.or_insert(ReticulumPeer {
.or_insert_with(|| ReticulumPeer {
dest_hash: hash,
display_name,
display_name: announced_name
.unwrap_or_else(|| format!("Reticulum {}", hex::encode(&hash[..4]))),
arch_pubkey_hex,
reachable: true,
last_advert_at: now,
});
self.persist_peers();
}
@@ -844,16 +935,24 @@ impl ReticulumLink {
// A peer that messages us without ever announcing still needs
// to survive a restart — give it a placeholder name (the real
// one, if any, arrives via a later "announce" and overwrites
// this) so its routing entry alone doesn't get lost.
if let std::collections::hash_map::Entry::Vacant(e) = self.peers.entry(source_hash)
{
e.insert(ReticulumPeer {
dest_hash: source_hash,
display_name: format!("Reticulum {}", hex::encode(&source_hash[..4])),
arch_pubkey_hex: None,
reachable: true,
});
self.persist_peers();
// this) so its routing entry alone doesn't get lost. An
// existing entry is proof of life too: mark it reachable so a
// restart-restored (reachable=false) peer that DMs us doesn't
// stay red-dotted until its next announce.
match self.peers.entry(source_hash) {
std::collections::hash_map::Entry::Vacant(e) => {
e.insert(ReticulumPeer {
dest_hash: source_hash,
display_name: format!("Reticulum {}", hex::encode(&source_hash[..4])),
arch_pubkey_hex: None,
reachable: true,
last_advert_at: 0,
});
self.persist_peers();
}
std::collections::hash_map::Entry::Occupied(mut e) => {
e.get_mut().reachable = true;
}
}
// A stock LXMF client (Sideband/NomadNet — not an archy peer)
@@ -932,15 +1031,20 @@ impl ReticulumLink {
};
let prefix: [u8; 6] = source_hash[..6].try_into().unwrap();
self.prefix_to_hash.insert(prefix, source_hash);
if let std::collections::hash_map::Entry::Vacant(e) = self.peers.entry(source_hash)
{
e.insert(ReticulumPeer {
dest_hash: source_hash,
display_name: format!("Reticulum {}", hex::encode(&source_hash[..4])),
arch_pubkey_hex: None,
reachable: true,
});
self.persist_peers();
match self.peers.entry(source_hash) {
std::collections::hash_map::Entry::Vacant(e) => {
e.insert(ReticulumPeer {
dest_hash: source_hash,
display_name: format!("Reticulum {}", hex::encode(&source_hash[..4])),
arch_pubkey_hex: None,
reachable: true,
last_advert_at: 0,
});
self.persist_peers();
}
std::collections::hash_map::Entry::Occupied(mut e) => {
e.get_mut().reachable = true;
}
}
use base64::{engine::general_purpose::STANDARD as B64, Engine as _};
let Some(data) = ev
@@ -1089,8 +1193,10 @@ pub(crate) async fn probe_rnode(path: &str) -> Result<()> {
// ESP32-S3 native-USB boards (Heltec V3/V4 etc. — no separate USB-UART
// bridge chip) treat a DTR/RTS transition on open as a reset signal, the
// same mechanism esptool uses to force bootloader entry. Deassert both
// and let the board settle before writing the probe, or the reboot eats
// the DETECT_RESP window below.
// before writing the probe. Boards behind a USB-UART bridge (CP2102 on
// the Heltec V3) get the reset pulse from the open() itself, before we
// can deassert anything — that case is handled by the boot-settle retry
// below.
let _ = port.set_dtr(false);
let _ = port.set_rts(false);
tokio::time::sleep(Duration::from_millis(300)).await;
@@ -1109,26 +1215,81 @@ pub(crate) async fn probe_rnode(path: &str) -> Result<()> {
0x00,
KISS_FEND,
];
// Attempt 1: probe immediately. A board that did NOT reset on open (it
// was already up — e.g. a re-probe of a running RNode) answers in well
// under a second, so the fast path stays fast.
tokio::time::timeout(Duration::from_millis(500), port.write_all(&probe))
.await
.context("RNode probe write timed out")?
.context("RNode probe write failed")?;
let mut buf = [0u8; 256];
let mut seen = Vec::new();
let deadline = tokio::time::Instant::now() + PROBE_READ_TIMEOUT;
while tokio::time::Instant::now() < deadline {
if await_detect_resp(&port, &mut buf, &mut seen, PROBE_READ_TIMEOUT).await {
return Ok(());
}
// No DETECT_RESP. If the open() power-cycled the board (verified live on
// a Heltec V3 RNode behind a CP2102: the ESP32 spends ~2.5-3s in boot
// ROM + app init and silently eats anything written meanwhile, so the
// first probe lands in the void), wait for its boot chatter to go quiet
// and probe once more with a fresh response window.
const BOOT_QUIET_WINDOW: Duration = Duration::from_millis(800);
const BOOT_SETTLE_MAX: Duration = Duration::from_secs(6);
let settle_deadline = tokio::time::Instant::now() + BOOT_SETTLE_MAX;
let mut last_data = tokio::time::Instant::now();
while tokio::time::Instant::now() < settle_deadline {
match tokio::time::timeout(Duration::from_millis(150), port.read(&mut buf)).await {
Ok(Ok(n)) if n > 0 => {
seen.extend_from_slice(&buf[..n]);
// A late DETECT_RESP to the first write still counts.
if contains_detect_resp(&seen) {
return Ok(());
}
last_data = tokio::time::Instant::now();
}
_ => {
if last_data.elapsed() >= BOOT_QUIET_WINDOW {
break;
}
}
}
}
tokio::time::timeout(Duration::from_millis(500), port.write_all(&probe))
.await
.context("RNode probe rewrite timed out")?
.context("RNode probe rewrite failed")?;
seen.clear();
if await_detect_resp(&port, &mut buf, &mut seen, PROBE_READ_TIMEOUT).await {
return Ok(());
}
anyhow::bail!(
"No RNode DETECT_RESP within {:?} (incl. post-boot-settle retry)",
PROBE_READ_TIMEOUT
)
}
/// Read from `port` for up to `window`, accumulating into `seen`; true once
/// the KISS DETECT_RESP sequence shows up anywhere in the stream.
async fn await_detect_resp(
port: &serial2_tokio::SerialPort,
buf: &mut [u8],
seen: &mut Vec<u8>,
window: Duration,
) -> bool {
let deadline = tokio::time::Instant::now() + window;
while tokio::time::Instant::now() < deadline {
match tokio::time::timeout(Duration::from_millis(150), port.read(buf)).await {
Ok(Ok(n)) if n > 0 => {
seen.extend_from_slice(&buf[..n]);
if contains_detect_resp(seen) {
return true;
}
}
_ => continue,
}
}
anyhow::bail!("No RNode DETECT_RESP within {:?}", PROBE_READ_TIMEOUT)
false
}
/// Look for the `[FEND, CMD_DETECT, DETECT_RESP]` sequence anywhere in the
@@ -1138,6 +1299,33 @@ fn contains_detect_resp(buf: &[u8]) -> bool {
.any(|w| w == [KISS_FEND, KISS_CMD_DETECT, KISS_DETECT_RESP])
}
/// The display name an announce actually asserted, if any.
///
/// Precedence: the daemon-decoded LXMF display name (`display_name` event
/// field), then — legacy peers only — bare-utf8 app_data that wasn't an
/// identity blob. The bare-utf8 fallback must actually look like text:
/// lossy-decoded msgpack (a new-format announce whose name the daemon failed
/// to decode) is full of U+FFFD/control chars and would otherwise become a
/// mojibake display name. `None` (e.g. a blob-only legacy announce) means
/// "no name asserted" and must NOT stomp a previously-learned name.
fn pick_announced_name(
explicit_name: Option<String>,
app_data_text: Option<String>,
is_legacy_blob: bool,
) -> Option<String> {
explicit_name
// A legacy blob-only announce utf8-decodes cleanly, so LXMF's
// display_name_from_app_data hands the daemon the ENTIRE `ARCHY:…`
// string as a "name" — seen live from a pre-upgrade Framework PT.
// An identity blob is never a display name.
.filter(|s| !s.starts_with("ARCHY:"))
.or_else(|| {
app_data_text
.filter(|_| !is_legacy_blob)
.filter(|s| !s.chars().any(|c| c.is_control() || c == '\u{FFFD}'))
})
}
impl Drop for ReticulumLink {
fn drop(&mut self) {
// Group-wide SIGTERM with a delayed SIGKILL backstop (`terminate_group`).
@@ -1154,6 +1342,37 @@ impl Drop for ReticulumLink {
mod tests {
use super::*;
#[test]
fn announced_name_precedence() {
// Daemon-decoded LXMF name always wins.
assert_eq!(
pick_announced_name(
Some("RNode Shaza".into()),
Some("ARCHY:2:aa:bb".into()),
true
),
Some("RNode Shaza".to_string())
);
// Legacy bare-utf8 name (old daemon, no explicit field).
assert_eq!(
pick_announced_name(None, Some("zaza".into()), false),
Some("zaza".to_string())
);
// Legacy blob-only announce asserts NO name (must not stomp).
assert_eq!(
pick_announced_name(None, Some("ARCHY:2:aa:bb".into()), true),
None
);
// Lossy-decoded msgpack must not become a mojibake name.
assert_eq!(
pick_announced_name(None, Some("\u{FFFD}\u{FFFD}Shaza\u{FFFD}".into()), false),
None
);
assert_eq!(pick_announced_name(None, Some("has\u{1}ctl".into()), false), None);
// Nothing at all.
assert_eq!(pick_announced_name(None, None, false), None);
}
#[test]
fn detect_resp_found_in_kiss_stream() {
let stream = [
+19 -6
View File
@@ -572,6 +572,8 @@ fn likely_non_mesh_serial_device(path: &str) -> bool {
/// was open (matches the reported "stops when I leave, resumes when I come
/// back"). SERIAL_CANDIDATES lists `/dev/mesh-radio` first, so it wins the
/// dedup and is what's reported when both alias and target are present.
/// (Independently re-discovered and fixed on main 2026-07-26 — both sides
/// of the 2026-07-28 merge carried an equivalent implementation.)
pub async fn detect_serial_devices() -> Vec<String> {
let mut devices = Vec::new();
let mut seen_real_paths = std::collections::HashSet::new();
@@ -618,12 +620,23 @@ pub async fn detect_serial_devices_info() -> Vec<DetectedDeviceInfo> {
let mut out = Vec::new();
for path in detect_serial_devices().await {
let usb = usb_info_for_tty(&path).await;
let plugged_at = tokio::fs::metadata(&path)
.await
.ok()
.and_then(|m| m.modified().ok())
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs());
// Birth time (btime), falling back to inode-change time (ctime) —
// NOT mtime: a tty node's mtime bumps on every open()/write, so with
// mtime here each probe/session open minted a "new" plugged_at, the
// UI's (path, plugged_at) dismissal key never matched again, and the
// setup modal re-fired forever on a device that never left the port
// (observed live on archi-dev-box 2026-07-28). btime/ctime only
// change when udev (re)creates/chowns the node — i.e. on real plugs.
let plugged_at = tokio::fs::metadata(&path).await.ok().and_then(|m| {
m.created()
.ok()
.and_then(|t| t.duration_since(std::time::UNIX_EPOCH).ok())
.map(|d| d.as_secs())
.or_else(|| {
use std::os::unix::fs::MetadataExt;
u64::try_from(m.ctime()).ok()
})
});
out.push(DetectedDeviceInfo {
path,
vid: usb.0,