Keep the devices window responsive and make traffic flows sortable

A waiting peer or speed-test animation in an immediate egui viewport
repainted the parent and its other windows. Each pass also supersampled
the same 64-pixel logo and handed the new allocation to the OS. Give
each Devices window its own repaint schedule. Wake it when status or
shared controls change, reuse the native icon, and skip measuring the
wide roster when its remembered minimum width exceeds the viewport.
Use the bundled Phosphor StopCircle for single and batch tests.

Bind incoming throughput probes to the signed address pair for the
running diagnostic. Cache its validity across packets under a routing
revision. A change of ownership, including removal or reassignment,
revalidates the pair under the routing read lock. This removes a lock
and a linear peer search from the steady-state receive path and keeps
the timing, byte limits and wire protocol compatible.

Give the traffic inspector a pinned header and compact, aligned rows
with readable text in both themes. The column chooser keeps the peer
visible on a narrow screen. Clicking a header sorts the complete
filtered capture with a stable cursor across pages. Maintain one sort
index on the window's scratch database and expire idle rates there.
Address sorting uses numeric IP and port values. Peer and network
sorting follows displayed names, including live name changes.

Bump the applications, Android package and Nix package to 1.0.8.
On macOS, verified formatting, workspace Clippy and all-target tests,
including real encrypted tests between local agents. Rendered the
monitor in light and dark desktop themes and at phone width. Built the
arm64 Android debug APK and cross-checked the Windows GNU target.
Across 500 optimized viewport updates, egui produced 500 native icon
replacements on 1.0.7 and zero with this change.
This commit is contained in:
Aleksandr Bogomiakov committed 2026-11-25 21:57:14 +02:00
1 parent b47acb8321
commit d8b7787430
27 files changed
+1500 -399

No files matched your search

+112 -213
View File
@@ -1,17 +1,17 @@
//! Live traffic inspector shared by the tray and Android clients.
mod columns;
mod history;
mod table;
use columns::{Column, Sort};
#[cfg(test)]
mod tests;
mod worker;
use crate::{
format::{bytes, short},
widgets,
};
use egui::{RichText, Ui};
use crate::{format::short, widgets};
use egui::Ui;
use egui_phosphor::regular as icon;
use history::{Filter, Row};
use std::{collections::BTreeMap, net::Ipv4Addr, path::PathBuf, time::Duration};
use history::{Cursor, Filter};
use std::{collections::BTreeMap, net::Ipv4Addr, path::PathBuf, sync::Arc, time::Duration};
use tsunagi::{
NetworkId,
ipc::StatusReport,
@@ -22,12 +22,12 @@ pub use worker::Feed;
use worker::Worker;
type Id = [u8; 32];
#[derive(Default)]
#[derive(Clone, Default)]
struct Network {
name: String,
peers: BTreeMap<Id, String>,
}
#[derive(Default)]
#[derive(Clone, Default)]
struct Names {
networks: BTreeMap<Id, Network>,
generation: Option<u64>,
@@ -37,18 +37,25 @@ fn public_id(id: &Id) -> String {
id.iter().map(|b| format!("{b:02x}")).collect()
}
impl Names {
fn refresh(&mut self, report: Option<&StatusReport>, generation: u64) {
let Some(report) = report else { return };
fn refresh(&mut self, report: Option<&StatusReport>, generation: u64) -> bool {
let Some(report) = report else { return false };
if self.generation == Some(generation) {
return;
return false;
}
self.generation = Some(generation);
let mut changed = false;
for n in &report.networks {
let Ok(id) = n.network_id.parse::<NetworkId>() else {
continue;
};
let entry = self.networks.entry(*id.as_bytes()).or_default();
entry.name = n.name.clone();
if entry.name != n.name {
entry.name.clone_from(&n.name);
changed = true;
}
// Resolve duplicate membership and live entries first. A stale member name
// must not trigger a rebuild of a multi-day capture's index every poll.
let mut reported = BTreeMap::new();
for (key, name) in n
.members
.iter()
@@ -63,18 +70,32 @@ impl Names {
Some(report.hostname.as_str()),
)))
{
let label = reported.entry(key).or_default();
if let Some(name) = name.filter(|s| !s.is_empty()) {
*label = Some(name);
}
}
for (key, name) in reported {
if let Ok(peer) = key.parse::<EndpointId>() {
let label = name.filter(|s| !s.is_empty()).map(str::to_owned);
let current = entry
.peers
.entry(*peer.as_bytes())
.or_insert_with(|| short(key));
if let Some(label) = label {
*current = label;
use std::collections::btree_map::Entry;
match entry.peers.entry(*peer.as_bytes()) {
Entry::Vacant(e) => {
e.insert(name.map_or_else(|| short(key), str::to_owned));
changed = true;
}
Entry::Occupied(mut e) => {
if let Some(name) = name
&& name != e.get()
{
*e.get_mut() = name.into();
changed = true;
}
}
}
}
}
}
changed
}
fn network(&self, id: &Id) -> String {
let Some(n) = self.networks.get(id) else {
@@ -115,17 +136,6 @@ fn role_name(r: Role) -> &'static str {
Role::Relay => "Encrypted relay",
}
}
fn role_text(role: Role) -> String {
let glyph = match role {
Role::ViaExit => icon::SIGN_OUT,
Role::ServeExit => icon::SIGN_IN,
Role::Relay => icon::GIT_FORK,
Role::Broadcast => icon::BROADCAST,
Role::SpeedTest => icon::GAUGE,
_ => return role_name(role).to_owned(),
};
format!("{glyph} {}", role_name(role))
}
fn protocol(n: u8) -> String {
match n {
1 => "ICMP".into(),
@@ -189,8 +199,8 @@ pub struct Window {
names: Names,
filter: Filter,
keep: bool,
previous: Vec<Option<i64>>,
selected: Option<i64>,
previous: Vec<Option<Cursor>>,
column_page: usize,
}
impl Window {
/// Creates an empty view. Android supplies its application-private cache directory.
@@ -201,7 +211,7 @@ impl Window {
filter: Filter::default(),
keep: false,
previous: Vec::new(),
selected: None,
column_page: 0,
}
}
/// The endpoint into which this window's subscription feeds interval snapshots.
@@ -209,31 +219,57 @@ impl Window {
self.worker.feed.clone()
}
fn controls(&mut self, ui: &mut Ui) {
ui.horizontal_wrapped(|ui| {
let layer = self.filter.transport;
ui.selectable_value(&mut self.filter.transport, false, format!("{} IP flows", icon::ARROWS_LEFT_RIGHT));
ui.selectable_value(&mut self.filter.transport, true, format!("{} Transport", icon::GIT_FORK))
.on_hover_text("Authenticated control sessions and encrypted traffic relayed between peers");
if layer != self.filter.transport {
self.filter.role = None;
self.filter.protocol = None;
}
widgets::hint(ui.checkbox(&mut self.keep,"Keep until close"),
"Keep inactive flows for this window session. Otherwise they expire after 60 seconds.");
});
let width = ((ui.available_width() - ui.spacing().item_spacing.x) / 2.).clamp(60., 135.);
fn controls(&mut self, ui: &mut Ui, grid: &table::Grid) {
if ui.available_width() < 540. {
ui.horizontal(|ui| self.layers(ui));
ui.horizontal(|ui| self.history_controls(ui, grid));
} else {
ui.horizontal(|ui| {
self.layers(ui);
self.history_controls(ui, grid);
});
}
if ui.available_width() < 580. {
let width = ((ui.available_width() - ui.spacing().item_spacing.x) / 2.).max(60.);
ui.horizontal(|ui| self.identity_filters(ui, width));
ui.horizontal(|ui| self.flow_filters(ui, width));
} else {
ui.horizontal(|ui| {
self.identity_filters(ui, width);
self.flow_filters(ui, width);
self.identity_filters(ui, 135.);
self.flow_filters(ui, 135.);
});
}
}
fn layers(&mut self, ui: &mut Ui) {
let layer = self.filter.transport;
ui.selectable_value(
&mut self.filter.transport,
false,
format!("{} IP flows", icon::ARROWS_LEFT_RIGHT),
);
ui.selectable_value(
&mut self.filter.transport,
true,
format!("{} Transport", icon::GIT_FORK),
)
.on_hover_text(
"Authenticated control sessions and encrypted traffic relayed between peers",
);
if layer != self.filter.transport {
self.filter.role = None;
self.filter.protocol = None;
}
}
fn history_controls(&mut self, ui: &mut Ui, grid: &table::Grid) {
widgets::hint(
ui.checkbox(&mut self.keep, "Keep until close"),
"Keep inactive flows for this window session. Otherwise they expire after 60 seconds.",
);
grid.chooser(ui, &mut self.column_page);
}
fn identity_filters(&mut self, ui: &mut Ui, width: f32) {
let network = self.filter.network;
egui::ComboBox::from_id_salt("flow-network")
@@ -322,14 +358,18 @@ impl Window {
/// Draw the responsive inspector inside the current viewport.
pub fn show(&mut self, ui: &mut Ui, report: Option<&StatusReport>, generation: u64) {
self.names.refresh(report, generation);
if self.names.refresh(report, generation) {
self.worker.names(Arc::new(self.names.clone()));
}
table::style(ui);
let before = self.filter.clone();
let keep = self.keep;
self.controls(ui);
let grid = table::Grid::new(ui);
self.column_page = self.column_page.min(grid.pages.len() - 1);
self.controls(ui, &grid);
if self.filter != before {
self.filter.before = None;
self.previous.clear();
self.selected = None;
}
if self.filter != before || self.keep != keep {
self.worker.options(self.filter.clone(), self.keep);
@@ -346,40 +386,44 @@ impl Window {
}
ui.separator();
let now = self.worker.feed.elapsed();
let wide = ui.available_width() >= 690.;
if !self.previous.is_empty() || page.more {
ui.horizontal(|ui| {
ui.horizontal_wrapped(|ui| {
if ui
.add_enabled(
!self.previous.is_empty(),
egui::Button::new(format!("{} Newer", icon::CARET_LEFT)),
egui::Button::new(format!("{} Previous", icon::CARET_LEFT)),
)
.clicked()
&& let Some(cursor) = self.previous.pop()
{
self.filter.before = cursor;
self.selected = None;
self.worker.options(self.filter.clone(), self.keep);
}
ui.weak(format!("Page {}", self.previous.len() + 1));
ui.label(format!("Page {}", self.previous.len() + 1));
if ui
.add_enabled(
page.more,
egui::Button::new(format!("Older {}", icon::CARET_RIGHT)),
egui::Button::new(format!("Next {}", icon::CARET_RIGHT)),
)
.clicked()
&& let Some(r) = page.rows.last()
&& let Some(row) = page.rows.last()
{
self.previous.push(self.filter.before);
self.filter.before = Some(r.id);
self.selected = None;
self.previous.push(self.filter.before.clone());
self.filter.before = Some(row.cursor());
self.worker.options(self.filter.clone(), self.keep);
}
});
}
let columns = &grid.pages[self.column_page];
if let Some(column) = grid.header(ui, columns, self.filter.sort) {
self.filter.sort.select(column);
self.filter.before = None;
self.previous.clear();
self.worker.options(self.filter.clone(), self.keep);
}
if page.rows.is_empty() {
ui.add_space(14.);
ui.weak(if error.is_some() {
ui.add_space(10.);
ui.label(if error.is_some() {
"No captured flows in this view."
} else if self.filter.network.is_some()
|| self.filter.role.is_some()
@@ -391,160 +435,15 @@ impl Window {
"Listening for traffic…"
});
} else {
if wide {
desktop_header(ui);
}
egui::ScrollArea::vertical()
.id_salt("flow-rows")
.auto_shrink([false, false])
.show(ui, |ui| {
for row in &page.rows {
let chosen = self.selected == Some(row.id);
egui::Frame::new()
.inner_margin(egui::Margin::symmetric(5, 3))
.fill(if chosen {
ui.visuals().selection.bg_fill
} else if row.id % 2 == 0 {
ui.visuals().faint_bg_color
} else {
egui::Color32::TRANSPARENT
})
.show(ui, |ui| {
let summary = ui.scope(|ui| self.row(ui, row, now, wide)).response;
let selected = ui.interact(
summary.rect,
ui.id().with(("flow", row.id)),
egui::Sense::click(),
);
if selected.clicked() {
self.selected = if chosen { None } else { Some(row.id) };
}
if chosen {
ui.separator();
let key = &row.data.key;
let (a, b, p) = endpoints(key, &self.names);
ui.label(format!("{a} ↔ {b} · {p}"));
ui.label(format!(
"{} {} packets sent {} {} received",
icon::ARROW_UP,
row.data.tx_packets,
icon::ARROW_DOWN,
row.data.rx_packets
));
let id = public_id(&key.peer);
ui.horizontal_wrapped(|ui| {
ui.weak("Peer ID");
crate::format::copy_field(ui, &short(&id), &id);
});
}
});
.show_rows(ui, grid.row_height, page.rows.len(), |ui, visible| {
for index in visible {
grid.row(ui, columns, &page.rows[index], &self.names, now, index);
}
});
}
ui.ctx().request_repaint_after(Duration::from_secs(1));
}
fn row(&self, ui: &mut Ui, r: &Row, now: u64, wide: bool) {
let k = &r.data.key;
let (a, b, p) = endpoints(k, &self.names);
let network = self.names.network(&k.network);
let peer = self.names.peer(&k.network, &k.peer);
let role = role_text(k.role);
let current = now.saturating_sub(r.sampled) < 1900;
let rates = |n: f32| format!("{}/s", bytes(if current { n as f64 } else { 0. }));
let (tx, rx) = (bytes(r.data.tx_bytes as f64), bytes(r.data.rx_bytes as f64));
let age = ago(now.saturating_sub(r.last));
if wide {
let widths = widths(ui);
ui.horizontal(|ui| {
cell(ui, widths[0], &peer, &network);
cell(ui, widths[1], &a, &b);
cell(ui, widths[2], &p, &role);
cell(ui, widths[3], &tx, &rates(r.tx_rate));
cell(ui, widths[4], &rx, &rates(r.rx_rate));
cell(ui, widths[5], &age, "");
});
} else {
ui.set_min_width(ui.available_width());
ui.horizontal_wrapped(|ui| {
ui.strong(peer);
ui.weak(&network);
ui.label(role);
ui.weak(age);
});
ui.horizontal_wrapped(|ui| {
ui.label(&p);
ui.monospace(&a);
ui.weak("↔");
ui.monospace(&b);
});
ui.horizontal_wrapped(|ui| {
ui.label(format!("{} {tx}", icon::ARROW_UP))
.on_hover_text("Sent");
ui.weak(rates(r.tx_rate));
ui.separator();
ui.label(format!("{} {rx}", icon::ARROW_DOWN))
.on_hover_text("Received");
ui.weak(rates(r.rx_rate));
});
}
}
}
fn widths(ui: &Ui) -> [f32; 6] {
let usable = (ui.available_width() - ui.spacing().item_spacing.x * 5. - 4.).max(0.);
[0.18, 0.30, 0.18, 0.13, 0.13, 0.08].map(|s| s * usable)
}
fn cell(ui: &mut Ui, width: f32, one: &str, two: &str) {
ui.allocate_ui_with_layout(
egui::vec2(width, 0.),
egui::Layout::top_down(egui::Align::Min),
|ui| {
ui.add(egui::Label::new(one).truncate()).on_hover_text(one);
if !two.is_empty() {
ui.add(egui::Label::new(RichText::new(two).weak().small()).truncate())
.on_hover_text(two);
}
},
);
}
fn desktop_header(ui: &mut Ui) {
egui::Frame::new()
.inner_margin(egui::Margin::symmetric(5, 2))
.show(ui, |ui| {
let widths = widths(ui);
ui.horizontal(|ui| {
for ((title, hint), width) in [
("Peer / network", "Authenticated peer and local network"),
(
"Endpoints",
"This side ↔ peer side. Encrypted relay shows the two named endpoints.",
),
(
"Protocol / role",
"IP protocol or transport observation and forwarding role",
),
(
"↑ Sent",
"Total and rate toward the peer (first to second endpoint for relay)",
),
(
"↓ Received",
"Total and rate from the peer (second to first endpoint for relay)",
),
("Seen", "Time since last activity"),
]
.into_iter()
.zip(widths)
{
ui.add_sized(
[width, 17.],
egui::Label::new(RichText::new(title).small().weak())
.halign(egui::Align::Min)
.truncate(),
)
.on_hover_text(hint);
}
});
});
}