Measure live peer throughput on the encrypted mesh path

Advertise an optional versioned diagnostic to authenticated peers. A small
control exchange negotiates limits and carries receiver feedback. Paced
IPv4 probes enter the ordinary WireGuard tunnel and follow its current
carrier or relay. Accept them only for an active session and the peer's
actual signed address pair. Agents without the capability still exchange
normal mesh traffic.

Raise the offered rate using receiver-clock windows and unique payload
bytes. Require sustained delivery before reporting a rate, distinguish a
lower bound from a measured ceiling, and discard interrupted live values.
An agent runs one exchange at a time, with a five-second deadline and a
cap at both ends. Queued exit tests share a separate batch budget. Keep
bounded per-network results in memory and cancel on session replacement,
network removal or a change to a metered underlay.

Add a fixed speed cell to desktop and Android device views. Show direction
and live rate, let a click on the result rerun the test, and offer a
stoppable sequential test of compatible exit nodes. Expose local actions
and progress over IPC v27. Mesh identity and stored state are unchanged.

On macOS arm64 the real WireGuard test covered both directions, a
control-only peer, the responder's metered limit and stopping a repeat.
The three-peer exit batch test passed. The diagnostic crate passed 17
tests including shaped throughput, loss, delay, duplication and bursts.
All 33 shared UI tests passed. Strict Clippy passed for the diagnostic
and core libraries and an ARM64 Android debug APK was built.
This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-25 19:25:58 +02:00
1 parent fb7a959d23
commit 200e716c28
34 files changed
+3658 -88

No files matched your search

+39 -2
View File
@@ -1,6 +1,9 @@
//! Commands and observations shared by both graphical clients.
use std::{path::PathBuf, time::Instant};
use tsunagi::ipc::StatusReport;
use std::{
path::PathBuf,
time::{Duration, Instant},
};
use tsunagi::ipc::{SpeedPhase, SpeedReport, StatusReport};
/// A request from the UI to the agent.
pub enum Command {
@@ -62,6 +65,18 @@ pub enum Command {
/// Selected member identity.
peer: Option<String>,
},
/// Measure one peer, or all compatible online exits in sequence.
StartSpeedTest {
/// Exact network identity.
network_id: String,
/// Exact peer identity, or all exits when absent.
peer: Option<String>,
},
/// Cancel this network's current test and any queued exits.
StopSpeedTest {
/// Exact network identity.
network_id: String,
},
/// Join a network, or start one already configured.
Join {
/// Network name.
@@ -119,3 +134,25 @@ pub trait Client {
/// An earlier action is waiting for an acknowledgement.
fn busy(&self) -> bool;
}
pub(crate) fn speed_running(report: &SpeedReport) -> bool {
report.batch.is_some()
|| report.peers.values().any(|peer| {
matches!(
peer.phase,
SpeedPhase::Queued
| SpeedPhase::Preparing
| SpeedPhase::Download
| SpeedPhase::Upload
)
})
}
/// Poll more frequently while showing a short, live speed measurement.
pub fn status_poll_interval(report: Option<&StatusReport>) -> Duration {
if report.is_some_and(|r| r.networks.iter().any(|n| speed_running(&n.speed))) {
Duration::from_millis(250)
} else {
Duration::from_secs(2)
}
}
+127 -34
View File
@@ -8,6 +8,9 @@
use std::collections::HashMap;
mod compact;
mod exit_picker;
mod speed;
#[cfg(test)]
mod speed_tests;
mod status;
pub use crate::exit::name_of;
pub use exit_picker::choose_exit;
@@ -160,6 +163,7 @@ pub fn show(
traffic: &Traffic,
) {
let (confirm, forget_confirm) = confirmations;
let speed = speed::Controls::new(network, agent);
egui::CentralPanel::default().show(ctx, |ui| {
ui.horizontal(|ui| {
// Reserve the unit switch even when a network name fills the viewport.
@@ -176,6 +180,17 @@ pub fn show(
});
// A copy of the chosen unit for the read-only rendering below.
let unit = *unit;
let devices = devices(network, own_id);
let roster_tools = |ui: &mut egui::Ui| {
let online = devices.iter().filter(|d| d.online).count();
ui.horizontal_wrapped(|ui| {
ui.strong(format!(
"devices ({online} online / {} known)",
devices.len()
));
speed.toolbar(ui);
});
};
if ctx.os() == egui::os::OperatingSystem::Android || ui.available_width() < 620.0 {
egui::ScrollArea::vertical()
@@ -189,24 +204,21 @@ pub fn show(
} else {
format::sparkline(ui, traffic.network(&network.network_id), unit, 34.0);
}
roster_tools(ui);
compact::roster(
ui,
network,
own_id,
&devices,
traffic,
unit,
(confirm, forget_confirm),
&speed,
);
});
return;
}
let devices = devices(network, own_id);
let online = devices.iter().filter(|d| d.online).count();
ui.columns(2, |columns| {
columns[0].strong(format!(
"devices ({online} online / {} known)",
devices.len()
));
roster_tools(&mut columns[0]);
columns[0].collapsing("Network details", |ui| summary(ui, network));
let plot = &mut columns[1];
plot.label("Network traffic");
@@ -217,18 +229,32 @@ pub fn show(
});
});
ui.add_space(8.0);
egui::ScrollArea::both()
egui::ScrollArea::vertical()
.auto_shrink([false, false])
.show(ui, |ui| {
device_table(
ui,
unit,
network,
&devices,
traffic,
confirm,
forget_confirm,
);
let table = desktop_columns(ui, unit, network, &devices, traffic);
let required = table.widths.iter().sum::<f32>() + crate::table::GAP * 8.;
if required <= ui.available_width() {
device_table(
ui,
network,
&devices,
(traffic, unit),
(confirm, forget_confirm),
&speed,
&table,
);
} else {
compact::roster(
ui,
network,
&devices,
traffic,
unit,
(confirm, forget_confirm),
&speed,
);
}
});
});
confirm_exit(ctx, agent, confirm, Some(&network.network_id));
@@ -652,22 +678,20 @@ fn exit_cell(
}
}
/// One table of all devices: online rows carry live counters and a plot,
/// offline rows show what is known (name and address) and dashes.
fn device_table(
ui: &mut egui::Ui,
struct DesktopColumns {
widths: [f32; 9],
total: String,
rate: String,
}
fn desktop_columns(
ui: &egui::Ui,
unit: Unit,
network: &NetworkReport,
devices: &[Device<'_>],
traffic: &Traffic,
confirm: &mut Option<ExitConfirm>,
forget_confirm: &mut Option<ForgetConfirm>,
) {
) -> DesktopColumns {
let network_id = network.network_id.as_str();
if devices.is_empty() {
ui.weak("none");
return;
}
let widths_id = egui::Id::new(("devices column widths", network_id));
let mut widths = column_widths(ui, widths_id);
let previous_widths = widths;
@@ -684,6 +708,7 @@ fn device_table(
for (column, header) in headers.iter().enumerate() {
widths[column] = widths[column].max(measure((*header).to_owned()));
}
widths[1] = widths[1].max(measure("exit".into()) + 4. + speed::WIDTH);
let (mut tx_total, mut rx_total) = (0_u64, 0_u64);
for device in devices {
let name = format!(
@@ -723,9 +748,51 @@ fn device_table(
}
ui.memory_mut(|m| m.data.insert_temp(widths_id, widths));
let widths = stretch_columns(widths, ui.available_width());
crate::table::row(ui, "device headers", &widths, false, |column, ui| {
DesktopColumns {
widths,
total,
rate,
}
}
/// One table of all devices: online rows carry live counters and a plot,
/// offline rows show what is known (name and address) and dashes.
fn device_table(
ui: &mut egui::Ui,
network: &NetworkReport,
devices: &[Device<'_>],
(traffic, unit): (&Traffic, Unit),
(confirm, forget_confirm): (&mut Option<ExitConfirm>, &mut Option<ForgetConfirm>),
speed: &speed::Controls<'_>,
table: &DesktopColumns,
) {
if devices.is_empty() {
ui.weak("none");
return;
}
let network_id = &network.network_id;
let headers = column_headers(unit);
let widths = &table.widths;
crate::table::row(ui, "device headers", widths, false, |column, ui| {
let response = ui.weak(headers[column]);
match column {
1 => {
let rect = ui.max_rect();
let speed_rect = rect.split_left_right_at_x(rect.right() - speed::WIDTH).1;
let r = ui.interact(
speed_rect,
ui.id().with("speed units"),
egui::Sense::click(),
);
ui.painter_at(speed_rect).text(
speed_rect.center(),
egui::Align2::CENTER_CENTER,
speed::HEADER,
egui::TextStyle::Body.resolve(ui.style()),
ui.visuals().weak_text_color(),
);
widgets::hint(r, speed::HEADER_HINT);
}
2 => {
response.on_hover_text("Encrypted data channel readiness.");
}
@@ -745,14 +812,19 @@ fn device_table(
crate::table::row(
ui,
device.id,
&widths,
widths,
index % 2 == 0,
|column, ui| match column {
0 => {
name_cell(ui, device);
forget_button(ui, device, network, forget_confirm);
}
1 => exit_cell(ui, device, network_id, confirm),
1 => {
let rect = ui.max_rect();
let speed_rect = rect.split_left_right_at_x(rect.right() - speed::WIDTH).1;
exit_cell(ui, device, network_id, confirm);
speed.cell(ui, speed_rect, device);
}
2 => tunnel_cell(ui, device),
3 => {
ui.label(rtt_pair(device)).on_hover_text(
@@ -789,17 +861,17 @@ fn device_table(
crate::table::row(
ui,
"device totals",
&widths,
widths,
false,
|column, ui| match column {
0 => {
ui.strong("total");
}
6 => {
ui.strong(&total);
ui.strong(&table.total);
}
7 => {
ui.strong(&rate);
ui.strong(&table.rate);
}
_ => {}
},
@@ -920,6 +992,27 @@ mod tests {
}
}
fn device_table(
ui: &mut egui::Ui,
unit: Unit,
network: &NetworkReport,
devices: &[Device<'_>],
traffic: &Traffic,
confirm: &mut Option<ExitConfirm>,
forget: &mut Option<ForgetConfirm>,
) {
let table = desktop_columns(ui, unit, network, devices, traffic);
super::device_table(
ui,
network,
devices,
(traffic, unit),
(confirm, forget),
&speed::Controls::new(network, &ReadOnly),
&table,
);
}
#[test]
fn phone_roster_fits_each_width_and_expands_only_the_tapped_member() {
let mut network = NetworkReport {
+44 -21
View File
@@ -1,8 +1,8 @@
//! A width-constrained device table for touch. Optional columns move into the
//! expanded row before any essential columns run out of space.
use super::{
AMBER, Device, ExitConfirm, ForgetConfirm, NetworkReport, Traffic, Unit, data_path_text,
devices, exit, forget_button, format, icon, rtt_text, traffic_pair, tunnel_cell,
AMBER, Device, ExitConfirm, ForgetConfirm, NetworkReport, Traffic, Unit, data_path_text, exit,
forget_button, format, icon, rtt_text, speed, traffic_pair, tunnel_cell,
};
use crate::widgets;
use egui::{Align2, Color32, FontId, Rect, Sense, Ui, Vec2, pos2, vec2};
@@ -10,6 +10,7 @@ use egui::{Align2, Color32, FontId, Rect, Sense, Ui, Vec2, pos2, vec2};
#[derive(Clone, Copy)]
enum Column {
Device,
Speed,
State,
Address,
Rtt,
@@ -23,6 +24,7 @@ impl Column {
fn title(self, unit: Unit) -> &'static str {
match self {
Self::Device => "device",
Self::Speed => speed::HEADER,
Self::State => "State",
Self::Address => "IPv4",
Self::Rtt => "Data RTT",
@@ -44,7 +46,17 @@ fn columns(ui: &Ui, width: f32, landscape: bool, unit: Unit) -> Vec<(Column, f32
.x
+ 10.
};
let mut cols = vec![(Column::Device, 0.)];
let mut cols = vec![
(Column::Device, 0.),
(
Column::Speed,
if landscape {
speed::WIDTH.min(width * 0.28)
} else {
speed::PORTRAIT_WIDTH.min(width * 0.18)
},
),
];
if landscape && width >= 510. {
cols.push((Column::State, measure("Control only").min(width * 0.16)));
}
@@ -56,7 +68,7 @@ fn columns(ui: &Ui, width: f32, landscape: bool, unit: Unit) -> Vec<(Column, f32
Column::Rtt,
measure("9999 ms").min(width * if landscape { 0.15 } else { 0.22 }),
));
if landscape {
if landscape && width >= 420. {
cols.push((
Column::Traffic,
measure(Column::Traffic.title(unit))
@@ -95,17 +107,12 @@ fn text_cell(ui: &Ui, rect: Rect, text: &str, font: &FontId, color: Color32) {
pub(super) fn roster(
ui: &mut Ui,
network: &NetworkReport,
own_id: &str,
members: &[Device<'_>],
traffic: &Traffic,
unit: Unit,
(exit, forget): (&mut Option<ExitConfirm>, &mut Option<ForgetConfirm>),
speed: &speed::Controls<'_>,
) {
let members = devices(network, own_id);
let online = members.iter().filter(|m| m.online).count();
ui.strong(format!(
"devices ({online} online / {} known)",
members.len()
));
// An Android rotation changes the surrounding scroll area but not the selected peer.
let id = egui::Id::new(("expanded device", &network.network_id));
let mut selected = ui.data(|d| d.get_temp::<String>(id));
@@ -121,13 +128,25 @@ pub(super) fn roster(
if matches!(column, Column::Device) {
rect.min.x += 20.;
}
text_cell(
ui,
rect,
column.title(unit),
&font,
ui.visuals().text_color(),
);
if matches!(column, Column::Speed) {
ui.painter_at(rect).text(
rect.center(),
Align2::CENTER_CENTER,
column.title(unit),
font.clone(),
ui.visuals().text_color(),
);
let r = ui.interact(rect, id.with("speed units"), Sense::click());
widgets::hint(r, speed::HEADER_HINT);
} else {
text_cell(
ui,
rect,
column.title(unit),
&font,
ui.visuals().text_color(),
);
}
x += w;
}
for (index, member) in members.iter().enumerate() {
@@ -176,6 +195,10 @@ pub(super) fn roster(
let mut rect = Rect::from_min_size(pos2(x, row.top()), vec2(w, row.height()));
x += w;
let text = match column {
Column::Speed => {
speed.cell(ui, rect, member);
continue;
}
Column::Device => {
channel.paint(
ui,
@@ -184,13 +207,13 @@ pub(super) fn roster(
rect.min.x += 20.;
if member.in_use || member.exit_node {
ui.painter_at(rect).text(
rect.left_center(),
Align2::LEFT_CENTER,
rect.right_center(),
Align2::RIGHT_CENTER,
icon::SIGN_OUT,
font.clone(),
if member.in_use { exit::GOOD } else { normal },
);
rect.min.x += font.size + 3.;
rect.max.x -= font.size + 3.;
}
member.name()
}
+315
View File
@@ -0,0 +1,315 @@
//! The same speed control occupies one fixed cell throughout a measurement.
use super::{Client, Command, Device, NetworkReport, format, icon, widgets};
use crate::client::speed_running;
use egui::{Align2, Color32, FontId, Rect, Sense, Ui, pos2, vec2};
use std::time::{Duration, SystemTime, UNIX_EPOCH};
use tsunagi::ipc::{SpeedPeerReport, SpeedPhase, SpeedRate};
pub(super) const WIDTH: f32 = 108.;
pub(super) const PORTRAIT_WIDTH: f32 = 56.;
pub(super) const HEADER: &str = "Mbit/s";
pub(super) const HEADER_HINT: &str = "Peer speed test · download / upload in megabits per second";
pub(super) struct Controls<'a> {
network: &'a NetworkReport,
client: &'a dyn Client,
running: bool,
}
impl<'a> Controls<'a> {
pub(super) fn new(network: &'a NetworkReport, client: &'a dyn Client) -> Self {
Self {
network,
client,
running: speed_running(&network.speed),
}
}
fn capable(&self, id: &str) -> bool {
self.network.speed.capable.iter().any(|peer| peer == id)
}
pub(super) fn toolbar(&self, ui: &mut Ui) {
let (label, help, available) = if self.running {
ui.ctx().request_repaint_after(Duration::from_millis(250));
let label = self.network.speed.batch.map_or_else(
|| format!("{} Stop test", icon::STOP),
|batch| format!("{} Stop {}/{}", icon::STOP, batch.done, batch.total),
);
(
label,
"Stop this speed test and skip any queued exits.",
true,
)
} else {
let available = self.network.active
&& self
.network
.peers
.iter()
.any(|p| p.exit_node && self.capable(&p.endpoint_id));
(
format!("{} Test exits", icon::GAUGE),
if available {
"Test each compatible online exit node in this network, one at a time."
} else {
"No online exit in this network supports peer speed tests."
},
available,
)
};
// Leave room for the batch count before starting. A wrapping toolbar
// must keep the same height when the button becomes Stop.
let width = ui
.painter()
.layout_no_wrap(
format!("{} Stop 9999/9999", icon::STOP),
egui::TextStyle::Button.resolve(ui.style()),
ui.visuals().text_color(),
)
.size()
.x
+ 2. * ui.spacing().button_padding.x;
let button = ui.add_enabled(
available && !self.client.busy(),
egui::Button::new(label).min_size(vec2(width, 0.)),
);
if widgets::hint(button, help).clicked() {
let network_id = self.network.network_id.clone();
let command = if self.running {
Command::StopSpeedTest { network_id }
} else {
Command::StartSpeedTest {
network_id,
peer: None,
}
};
self.client.send(command);
}
}
pub(super) fn cell(&self, ui: &mut Ui, rect: Rect, peer: &Device<'_>) {
if !ui.is_rect_visible(rect) {
return;
}
let reading = self.network.speed.peers.get(peer.id);
let supported = self.capable(peer.id);
let ready = self.network.active && peer.online && supported;
let can_start = ready && !self.running && !self.client.busy();
let id = ui.make_persistent_id(("test peer speed", &self.network.network_id, peer.id));
let r = ui.interact(rect, id, Sense::click());
let r = if can_start {
r.on_hover_cursor(egui::CursorIcon::PointingHand)
} else {
r
};
let v = ui.visuals();
let color = if ready {
v.hyperlink_color
} else {
v.weak_text_color()
};
if can_start && (r.hovered() || r.has_focus()) {
ui.painter()
.rect_filled(rect.shrink(1.), 3., v.widgets.hovered.weak_bg_fill);
}
paint_reading(ui, rect, reading, ready, color);
let hint = tooltip(peer, reading, supported, self.running);
r.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, can_start, &hint));
if widgets::hint(r, &hint).clicked() && can_start {
self.client.send(Command::StartSpeedTest {
network_id: self.network.network_id.clone(),
peer: Some(peer.id.into()),
});
}
}
}
fn paint_reading(
ui: &Ui,
rect: Rect,
reading: Option<&SpeedPeerReport>,
ready: bool,
color: Color32,
) {
let painter = ui.painter_at(rect);
let Some(test) = reading else {
let glyph = if ready { icon::GAUGE } else { "—" };
painter.text(
rect.center(),
Align2::CENTER_CENTER,
glyph,
FontId::proportional(16.),
color,
);
return;
};
let v = ui.visuals();
let small = egui::TextStyle::Small.resolve(ui.style());
let label = |s: &str, ink: Color32| {
painter.text(rect.center(), Align2::CENTER_CENTER, s, small.clone(), ink);
};
match test.phase {
SpeedPhase::Queued => label("Queued", v.weak_text_color()),
SpeedPhase::Preparing => {
label("Starting", color);
activity(ui, rect, color);
}
SpeedPhase::Failed(_) => label(&format!("{} Retry", icon::WARNING), v.error_fg_color),
SpeedPhase::Cancelled => label(&format!("{} Retry", icon::ARROW_CLOCKWISE), color),
SpeedPhase::Download | SpeedPhase::Upload | SpeedPhase::Done => {
// Reserve the same two slots for idle, live and completed readings.
let inline = rect.width() >= WIDTH - 1.;
let font = if inline {
small.clone()
} else {
FontId::proportional(small.size.min(rect.height() * 0.46))
};
for (offset, arrow, rate, phase) in [
(-0.23, icon::ARROW_DOWN, test.down, SpeedPhase::Download),
(0.23, icon::ARROW_UP, test.up, SpeedPhase::Upload),
] {
let measuring = test.phase == phase;
let value = rate.map_or_else(
|| if measuring { "…" } else { "—" }.to_owned(),
compact_rate,
);
let ink = if measuring {
v.hyperlink_color
} else if rate.is_some() {
v.text_color()
} else {
v.weak_text_color()
};
painter.text(
rect.center()
+ if inline {
vec2(rect.width() * offset, 0.)
} else {
vec2(0., rect.height() * offset)
},
Align2::CENTER_CENTER,
format!("{arrow} {value}"),
font.clone(),
ink,
);
}
if test.phase != SpeedPhase::Done {
activity(ui, rect, color);
}
}
}
}
// A moving mark indicates an active phase even before the first receiver
// report arrives. Repaint only visible, active cells.
fn activity(ui: &Ui, rect: Rect, color: Color32) {
let bar = rect.shrink2(vec2(4., 1.));
let width = bar.width() * 0.24;
let t = ui.input(|i| (i.time % 1.) as f32);
let x = bar.left() + (bar.width() - width) * (t * std::f32::consts::PI).sin().powi(2);
ui.painter_at(rect).line_segment(
[pos2(x, bar.bottom()), pos2(x + width, bar.bottom())],
(1., color),
);
ui.ctx().request_repaint_after(Duration::from_millis(80));
}
// Round positive lower bounds down so the displayed minimum is supported by
// the measurement, including near a precision or unit boundary.
fn rate_number(rate: SpeedRate, divisor: f64, precision: usize) -> String {
let mut value = rate.bps as f64 / divisor;
if rate.lower_bound {
let scale = 10_f64.powi(precision as i32);
value = (value * scale).floor() / scale;
}
format!("{value:.precision$}")
}
fn compact_rate(rate: SpeedRate) -> String {
let bound = if rate.lower_bound { "≥" } else { "" };
let (unit, precision, suffix) = match rate.bps {
0 => return "0".into(),
1..10_000 if rate.lower_bound => return ">0".into(),
1..10_000 => return "<0.01".into(),
10_000..1_000_000 => (1e6, 2, ""),
1_000_000..10_000_000 => (1e6, 1, ""),
10_000_000..10_000_000_000 => (1e6, 0, ""),
_ => (1e9, 0, "k"),
};
format!("{bound}{}{suffix}", rate_number(rate, unit, precision))
}
fn tooltip(
peer: &Device<'_>,
test: Option<&SpeedPeerReport>,
supported: bool,
running: bool,
) -> String {
let mut hint = format!("Speed to {}", peer.name());
if let Some(test) = test {
let phase = match &test.phase {
SpeedPhase::Queued => "Waiting for the previous exit",
SpeedPhase::Preparing => "Opening the data channel",
SpeedPhase::Download => "Measuring download",
SpeedPhase::Upload => "Measuring upload",
SpeedPhase::Done => "Completed",
SpeedPhase::Failed(error) => error.as_str(),
SpeedPhase::Cancelled => "Stopped",
};
hint.push_str(&format!("\n{phase}"));
for (label, rate) in [("Download", test.down), ("Upload", test.up)] {
if let Some(rate) = rate {
let (divisor, suffix) = if rate.bps < 1_000_000 {
(1000., "kbit/s")
} else {
(1e6, "Mbit/s")
};
let bound = if rate.lower_bound { "at least " } else { "" };
hint.push_str(&format!(
"\n{label} {bound}{} {suffix}",
rate_number(rate, divisor, 2)
));
}
}
if let Some(path) = &test.path {
hint.push_str(&format!("\nPath at start {path}"));
}
if test.elapsed_ms > 0 || test.bytes > 0 {
hint.push_str(&format!(
"\n{} transferred in {:.1} s",
format::bytes(test.bytes as f64),
f64::from(test.elapsed_ms) / 1000.
));
}
if test.measured_at_unix_secs > 0
&& matches!(
test.phase,
SpeedPhase::Done | SpeedPhase::Failed(_) | SpeedPhase::Cancelled
)
&& let Ok(now) = SystemTime::now().duration_since(UNIX_EPOCH)
{
let age = now.as_secs().saturating_sub(test.measured_at_unix_secs);
let age = if age < 60 {
format!("{age} s")
} else if age < 3600 {
format!("{} min", age / 60)
} else {
format!("{} h", age / 3600)
};
hint.push_str(&format!("\nMeasured {age} ago"));
}
}
if !peer.online {
hint.push_str("\nPeer is offline.");
} else if !supported {
hint.push_str("\nNo compatible speed-test session with this peer.");
} else if !running {
hint.push_str(if test.is_some() {
"\nTap to test again."
} else {
"\nTap to test download and upload."
});
}
hint
}
@@ -0,0 +1,280 @@
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use std::cell::RefCell;
use tsunagi::ipc::{PeerReport, SpeedBatchReport, SpeedPeerReport, SpeedPhase, SpeedRate};
#[derive(Default)]
struct ClientLog(RefCell<Vec<Command>>);
impl Client for ClientLog {
fn send(&self, cmd: Command) {
self.0.borrow_mut().push(cmd);
}
fn busy(&self) -> bool {
false
}
}
fn network() -> NetworkReport {
let mut n = NetworkReport {
active: true,
name: "mesh".into(),
network_id: "network".into(),
..Default::default()
};
for (id, offers_exit) in [("alice", true), ("ben", false), ("older", true)] {
n.peers.push(PeerReport {
endpoint_id: id.into(),
hostname: Some(id.into()),
exit_node: offers_exit,
..Default::default()
});
}
n.speed.capable = vec!["alice".into(), "ben".into()];
n
}
fn reading(phase: SpeedPhase) -> SpeedPeerReport {
SpeedPeerReport {
phase,
down: Some(SpeedRate {
bps: 125_000_000,
lower_bound: false,
}),
up: Some(SpeedRate {
bps: 35_995_000,
lower_bound: true,
}),
bytes: 1_900_000,
elapsed_ms: 600,
path: Some("wg direct".into()),
measured_at_unix_secs: 0,
}
}
struct Screen {
ctx: egui::Context,
width: f32,
log: ClientLog,
}
impl Screen {
fn new(width: f32, mobile: bool) -> Self {
let ctx = egui::Context::default();
ctx.set_fonts(crate::app_fonts());
if mobile {
ctx.set_os(egui::os::OperatingSystem::Android);
}
Self {
ctx,
width,
log: ClientLog::default(),
}
}
fn frame(&self, n: &NetworkReport, events: Vec<egui::Event>) -> egui::FullOutput {
self.frame_at(n, None, events)
}
fn frame_at(
&self,
n: &NetworkReport,
time: Option<f64>,
events: Vec<egui::Event>,
) -> egui::FullOutput {
self.ctx.run(
egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(
egui::Pos2::ZERO,
egui::vec2(self.width, 650.),
)),
events,
time,
..Default::default()
},
|ctx| {
show(
ctx,
&self.log,
&mut Unit::Bytes,
(&mut None, &mut None),
n,
"self",
&Traffic::default(),
)
},
)
}
fn click(&self, n: &NetworkReport, pos: egui::Pos2) {
for pressed in [true, false] {
self.frame(
n,
vec![
egui::Event::PointerMoved(pos),
egui::Event::PointerButton {
pos,
button: egui::PointerButton::Primary,
pressed,
modifiers: Default::default(),
},
],
);
}
}
}
fn positions(out: &egui::FullOutput, find: impl Fn(&str) -> bool) -> Vec<egui::Pos2> {
out.shapes
.iter()
.filter_map(|s| match &s.shape {
egui::Shape::Text(t) if find(t.galley.text()) => {
Some(t.pos + t.galley.rect.center().to_vec2())
}
_ => None,
})
.collect()
}
#[test]
fn live_and_completed_readings_keep_the_same_row_and_tapping_retests_a_non_exit_peer() {
for (width, mobile) in [(320., true), (860., true), (1440., false)] {
let mut n = network();
let s = Screen::new(width, mobile);
s.frame(&n, vec![]);
let idle = s.frame(&n, vec![]);
let gauges = positions(&idle, |s| s == icon::GAUGE);
assert_eq!(gauges.len(), 2, "capable peers only");
let button = gauges[1];
let peer_pos = positions(&idle, |s| s == "ben")[0];
let after = positions(&idle, |s| s == "older")[0];
s.click(&n, button);
for phase in [
SpeedPhase::Preparing,
SpeedPhase::Download,
SpeedPhase::Upload,
SpeedPhase::Done,
] {
let live_down = phase == SpeedPhase::Download;
let mut report = reading(phase);
if live_down {
report.down = Some(SpeedRate {
bps: 19_900_000,
lower_bound: false,
});
report.up = None;
}
n.speed.peers.insert("ben".into(), report);
let out = s.frame(&n, vec![]);
if live_down {
assert!(!positions(&out, |s| s == format!("{} 20", icon::ARROW_DOWN)).is_empty());
assert!(!positions(&out, |s| s == format!("{} —", icon::ARROW_UP)).is_empty());
}
assert_eq!(positions(&out, |s| s == "ben"), [peer_pos]);
assert_eq!(positions(&out, |s| s == "older"), [after]);
assert!(
positions(&out, |s| s == "Endpoint ID").is_empty(),
"speed tap expanded a row"
);
}
let done = s.frame(&n, vec![]);
for value in ["125", "≥35"] {
let lines = positions(&done, |s| s.ends_with(value));
assert_eq!(lines.len(), 1);
assert!((lines[0].x - button.x).abs() < 31.);
assert!((lines[0].y - button.y).abs() < 12.);
assert!(lines[0].x < width);
}
let down = positions(&done, |s| s.ends_with("125"))[0];
let up = positions(&done, |s| s.ends_with("≥35"))[0];
if width > 650. {
assert!(
(down.y - up.y).abs() < 1. && down.x < up.x,
"wide screens show both rates on one line"
);
} else {
assert!(
(down.x - up.x).abs() < 1. && down.y < up.y,
"portrait shows a rate on each line"
);
}
s.click(&n, button);
let log = s.log.0.borrow();
assert_eq!(log.len(), 2);
assert!(log.iter().all(|cmd| matches!(cmd, Command::StartSpeedTest { network_id, peer: Some(peer) } if network_id == "network" && peer == "ben")));
}
}
#[test]
fn long_press_explains_a_partial_result_without_requesting_another_test() {
let s = Screen::new(360., true);
let mut n = network();
n.speed.peers.insert(
"ben".into(),
reading(SpeedPhase::Failed("Peer timed out".into())),
);
let draw = |time, events| s.frame_at(&n, Some(time), events);
draw(0., vec![]);
let pos = positions(&draw(0.1, vec![]), |s| s.contains("Retry"))[0];
let touch = |phase| egui::Event::Touch {
device_id: egui::TouchDeviceId(0),
id: egui::TouchId(1),
phase,
pos,
force: None,
};
let pointer = |pressed| egui::Event::PointerButton {
pos,
button: egui::PointerButton::Primary,
pressed,
modifiers: Default::default(),
};
draw(
0.2,
vec![
touch(egui::TouchPhase::Start),
egui::Event::PointerMoved(pos),
pointer(true),
],
);
draw(1.2, vec![]);
let held = draw(1.3, vec![]);
let tips = positions(&held, |text| {
text.contains("Peer timed out")
&& text.contains("at least 35.99 Mbit/s")
&& text.contains("Path at start wg direct")
});
assert_eq!(tips.len(), 1);
draw(
1.4,
vec![
touch(egui::TouchPhase::End),
pointer(false),
egui::Event::PointerGone,
],
);
assert!(s.log.0.borrow().is_empty());
}
#[test]
fn exit_batch_requires_an_online_capable_exit_and_stops_in_its_own_network() {
let mut n = network();
let s = Screen::new(360., true);
s.frame(&n, vec![]);
let start = positions(&s.frame(&n, vec![]), |s| s.contains("Test exits"))[0];
n.peers[0].exit_node = false;
s.frame(&n, vec![]);
s.click(&n, start);
assert!(s.log.0.borrow().is_empty());
n.peers[0].exit_node = true;
s.frame(&n, vec![]);
s.click(&n, start);
n.speed.batch = Some(SpeedBatchReport { done: 0, total: 1 });
let batch = s.frame(&n, vec![]);
assert!(!positions(&batch, |s| s.contains("0/1")).is_empty());
s.click(&n, positions(&batch, |s| s.contains("Stop"))[0]);
assert!(matches!(s.log.0.borrow().as_slice(), [
Command::StartSpeedTest { network_id, peer: None },
Command::StopSpeedTest { network_id: stopped },
] if network_id == "network" && stopped == network_id));
}