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

+5 -4
View File
@@ -29,6 +29,7 @@ impl Client for AgentClient {
}
/// Handle the UI holds: send commands, read the latest snapshot.
#[derive(Clone)]
pub(crate) struct AgentClient {
tx: mpsc::UnboundedSender<Command>,
shared: Arc<Mutex<Snapshot>>,
@@ -122,7 +123,7 @@ async fn worker(
run(&resolve_socket(), command, &shared, &pending_copy, &ctx).await;
refresh(&shared, &ctx).await;
lock(&shared).busy = false;
ctx.request_repaint();
ctx.request_repaint_of(egui::ViewportId::ROOT);
}
}
}
@@ -145,7 +146,7 @@ async fn refresh(shared: &Arc<Mutex<Snapshot>>, ctx: &egui::Context) {
guard.at = Some(Instant::now());
guard.socket = socket;
}
ctx.request_repaint();
ctx.request_repaint_of(egui::ViewportId::ROOT);
}
/// Runs one command and records its outcome.
@@ -157,7 +158,7 @@ async fn run(
ctx: &egui::Context,
) {
lock(shared).busy = true;
ctx.request_repaint();
ctx.request_repaint_of(egui::ViewportId::ROOT);
let outcome: Result<String, String> = match command {
Command::SaveVip {
@@ -302,7 +303,7 @@ async fn run(
Some(outcome)
};
}
ctx.request_repaint();
ctx.request_repaint_of(egui::ViewportId::ROOT);
}
/// Where the GUI looks for the agent: `TSUNAGI_CONTROL_SOCKET` if set, else the
+135 -56
View File
@@ -5,7 +5,7 @@
//! and gone when the window is closed. The tray, which has to outlive the
//! window, lives in the other process; see [`crate::tray`].
use std::time::Duration;
use std::sync::{Arc, Mutex};
use eframe::egui;
@@ -17,14 +17,19 @@ use crate::ui::{self, UiState};
use tsunagi_ui::app_fonts;
#[derive(Default)]
struct Views {
state: UiState,
traffic: Traffic,
}
/// The window's state.
pub(crate) struct App {
agent: AgentClient,
runtime: tokio::runtime::Handle,
monitor: Option<crate::monitor::Monitor>,
state: UiState,
/// Traffic rates derived from successive snapshots.
traffic: Traffic,
views: Arc<Mutex<Views>>,
device_revision: Option<(u64, tsunagi_ui::stats::Unit, bool)>,
/// The snapshot generation last folded into `traffic`.
sampled: u64,
}
@@ -45,8 +50,8 @@ impl App {
agent,
runtime,
monitor: None,
state: UiState::default(),
traffic: Traffic::default(),
views: Default::default(),
device_revision: None,
sampled: 0,
})
}
@@ -55,50 +60,64 @@ impl App {
impl eframe::App for App {
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
let snapshot = self.agent.snapshot();
let mut views = self.views.lock().unwrap_or_else(|e| e.into_inner());
let Views { state, traffic } = &mut *views;
if snapshot.generation != self.sampled
&& let (Some(Ok(report)), Some(at)) = (&snapshot.status, snapshot.at)
{
self.traffic.observe(report, at);
traffic.observe(report, at);
self.sampled = snapshot.generation;
}
ui::draw(ctx, &self.agent, &mut self.state, &snapshot, &self.traffic);
if self.state.monitor_open {
ui::draw(ctx, &self.agent, state, &snapshot, traffic);
if state.monitor_open {
let monitor = self.monitor.get_or_insert_with(|| {
crate::monitor::Monitor::new(&self.runtime, self.agent.socket())
});
if !monitor.show(ctx, &snapshot) {
self.monitor = None;
self.state.monitor_open = false;
state.monitor_open = false;
}
}
self.show_devices_windows(ctx, &snapshot);
self.show_vip_windows(ctx, &snapshot);
self.show_about_window(ctx, &snapshot);
Self::show_vip_windows(ctx, &self.agent, state, &snapshot);
Self::show_about_window(ctx, &self.agent, state, &snapshot);
let revision = (snapshot.generation, state.unit, snapshot.busy);
let refresh = self.device_revision != Some(revision);
self.device_revision = Some(revision);
if let Some(Ok(report)) = &snapshot.status {
state
.open_devices
.retain(|id| report.networks.iter().any(|n| n.network_id == *id));
let open: Vec<_> = state.open_devices.iter().cloned().collect();
// The embedded fallback can run the child callback immediately.
drop(views);
self.show_devices_windows(ctx, report, &open, refresh);
}
// A secret the worker fetched for the clipboard: copy it here, on the
// UI thread that owns the clipboard, exactly once.
if let Some(secret) = self.agent.take_pending_copy() {
ctx.copy_text(secret);
}
// Keep ticking so fresh status is picked up.
ctx.request_repaint_after(Duration::from_millis(500));
}
}
impl App {
fn show_vip_windows(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) {
fn show_vip_windows(
ctx: &egui::Context,
agent: &AgentClient,
state: &mut UiState,
snapshot: &crate::agent::Snapshot,
) {
let Some(Ok(report)) = &snapshot.status else {
return;
};
let ids: Vec<_> = self.state.vip_windows.keys().cloned().collect();
let ids: Vec<_> = state.vip_windows.keys().cloned().collect();
for id in ids {
let Some(network) = report.networks.iter().find(|n| n.network_id == id) else {
self.state.vip_windows.remove(&id);
state.vip_windows.remove(&id);
continue;
};
let Some(state) = self.state.vip_windows.get_mut(&id) else {
let Some(editor) = state.vip_windows.get_mut(&id) else {
continue;
};
let builder = egui::ViewportBuilder::default()
@@ -111,13 +130,13 @@ impl App {
egui::ViewportId::from_hash_of(("vip", &id)),
builder,
|vctx, _| {
let close = crate::vip::show(vctx, &self.agent, state, network, snapshot);
let close = crate::vip::show(vctx, agent, editor, network, snapshot);
if close {
return false;
}
if vctx.input(|i| i.viewport().close_requested()) {
if state.dirty() {
state.request_close();
if editor.dirty() {
editor.request_close();
vctx.send_viewport_cmd(egui::ViewportCommand::CancelClose);
true
} else {
@@ -129,13 +148,18 @@ impl App {
},
);
if !keep {
self.state.vip_windows.remove(&id);
state.vip_windows.remove(&id);
}
}
}
/// Renders the About window while it is open.
fn show_about_window(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) {
if !self.state.about_open {
fn show_about_window(
ctx: &egui::Context,
agent: &AgentClient,
state: &mut UiState,
snapshot: &crate::agent::Snapshot,
) {
if !state.about_open {
return;
}
let builder = egui::ViewportBuilder::default()
@@ -144,7 +168,7 @@ impl App {
.with_icon(crate::icon::window())
.with_inner_size([560.0, 520.0])
.with_min_inner_size([380.0, 280.0]);
let socket = self.agent.socket();
let socket = agent.socket();
let keep = ctx.show_viewport_immediate(
egui::ViewportId::from_hash_of("about"),
builder,
@@ -154,50 +178,57 @@ impl App {
},
);
if !keep {
self.state.about_open = false;
state.about_open = false;
}
}
/// Renders one separate window per open network-devices view.
fn show_devices_windows(&mut self, ctx: &egui::Context, snapshot: &crate::agent::Snapshot) {
let Some(Ok(report)) = &snapshot.status else {
return;
};
let open: Vec<String> = self.state.open_devices.iter().cloned().collect();
fn show_devices_windows(
&self,
ctx: &egui::Context,
report: &Arc<tsunagi::ipc::StatusReport>,
open: &[String],
refresh: bool,
) {
for id in open {
let Some(network) = report.networks.iter().find(|n| n.network_id == id) else {
// The network is gone (left/forgotten); close its window.
self.state.open_devices.remove(&id);
let Some(index) = report.networks.iter().position(|n| n.network_id == *id) else {
continue;
};
let viewport_id = egui::ViewportId::from_hash_of(("devices", &id));
let viewport = egui::ViewportId::from_hash_of(("devices", id));
let builder = egui::ViewportBuilder::default()
.with_title(devices::title(network))
.with_title(devices::title(&report.networks[index]))
.with_app_id(crate::icon::APP_ID)
.with_icon(crate::icon::window())
.with_inner_size([1000.0, 640.0])
.with_min_inner_size([560.0, 400.0]);
let agent = &self.agent;
let traffic = &self.traffic;
// The window shares the single unit setting, so its toggle and the
// main window's stay in step.
let unit = &mut self.state.unit;
let confirm = &mut self.state.exit_confirm;
let forget_confirm = &mut self.state.forget_confirm;
let keep = ctx.show_viewport_immediate(viewport_id, builder, |vctx, _class| {
.with_inner_size([1000., 640.])
.with_min_inner_size([560., 400.]);
let views = self.views.clone();
let agent = self.agent.clone();
let report = report.clone();
ctx.show_viewport_deferred(viewport, builder, move |ctx, _| {
let mut views = views.lock().unwrap_or_else(|e| e.into_inner());
let Views { state, traffic } = &mut *views;
let network = &report.networks[index];
if ctx.input(|i| i.viewport().close_requested()) {
state.open_devices.remove(&network.network_id);
ctx.request_repaint_of(egui::ViewportId::ROOT);
return;
}
let old_unit = state.unit;
devices::show(
vctx,
agent,
unit,
(confirm, forget_confirm),
ctx,
&agent,
&mut state.unit,
(&mut state.exit_confirm, &mut state.forget_confirm),
network,
&report.endpoint_id,
traffic,
);
!vctx.input(|i| i.viewport().close_requested())
if old_unit != state.unit {
ctx.request_repaint_of(egui::ViewportId::ROOT);
}
});
if !keep {
self.state.open_devices.remove(&id);
if refresh {
ctx.request_repaint_of(viewport);
}
}
}
@@ -205,8 +236,56 @@ impl App {
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
#[test]
fn device_frames_are_scheduled_independently_of_the_main_window() {
let runtime = tokio::runtime::Builder::new_current_thread()
.enable_all()
.build()
.unwrap();
let ctx = egui::Context::default();
ctx.set_embed_viewports(false);
let agent = AgentClient::spawn(runtime.handle(), ctx.clone());
let app = App {
agent,
runtime: runtime.handle().clone(),
monitor: None,
views: Default::default(),
sampled: 0,
device_revision: None,
};
let report = Arc::new(tsunagi::ipc::StatusReport {
networks: vec![tsunagi::ipc::NetworkReport {
network_id: "test-id".into(),
name: "lab".into(),
..Default::default()
}],
..Default::default()
});
let id = egui::ViewportId::from_hash_of(("devices", "test-id"));
let open = ["test-id".to_string()].into_iter().collect();
app.views.lock().unwrap().state.open_devices = open;
let out = ctx.run(Default::default(), |ctx| {
app.show_devices_windows(ctx, &report, &["test-id".to_string()], true);
});
assert!(out.viewport_output[&id].class == egui::ViewportClass::Deferred);
let draw = out.viewport_output[&id].viewport_ui_cb.as_ref().unwrap();
let mut input = egui::RawInput {
viewport_id: id,
..Default::default()
};
input
.viewports
.entry(id)
.or_default()
.events
.push(egui::ViewportEvent::Close);
let _ = ctx.run(input, |ctx| draw(ctx));
assert!(app.views.lock().unwrap().state.open_devices.is_empty());
}
#[test]
fn route_icons_have_an_embedded_font_in_the_app() {
let fonts = app_fonts();
+19 -6
View File
@@ -4,6 +4,7 @@
//! It is the same shape as `dist/linux/tsunagi.svg` (a disc, a ring, a dot).
use crate::watch::Health;
use std::sync::{Arc, LazyLock};
/// Normal operation. The colour of the logo itself.
const BLUE: [u8; 3] = [0x2f, 0x80, 0xd8];
@@ -89,12 +90,17 @@ pub(crate) fn tray(health: Health) -> Option<tray_icon::Icon> {
}
/// The icon of the application's windows.
pub(crate) fn window() -> eframe::egui::IconData {
eframe::egui::IconData {
rgba: rgba(BLUE),
width: SIZE,
height: SIZE,
}
pub(crate) fn window() -> Arc<eframe::egui::IconData> {
// egui compares viewport icons by Arc identity. Reuse both the pixels and
// their allocation so animating a row does not update a native window icon.
static ICON: LazyLock<Arc<eframe::egui::IconData>> = LazyLock::new(|| {
Arc::new(eframe::egui::IconData {
rgba: rgba(BLUE),
width: SIZE,
height: SIZE,
})
});
Arc::clone(&ICON)
}
#[cfg(test)]
@@ -122,6 +128,13 @@ mod tests {
assert_eq!(body, [GREEN[0], GREEN[1], GREEN[2], 255]);
}
#[test]
fn repainting_a_devices_viewport_does_not_ask_the_os_to_replace_its_icon() {
let viewport = || eframe::egui::ViewportBuilder::default().with_icon(window());
let (commands, recreate) = viewport().patch(viewport());
assert!(!recreate && commands.is_empty(), "{commands:?}");
}
#[test]
fn each_state_has_its_own_colour() {
let colours = [