feat(remote,ui): cache remote SSH scans with SWR, smooth 200ms freshness fades, raise remote deadline to 30m

This commit is contained in:
Tobi Lutke
2026-11-25 19:11:49 -05:00
parent 8df1c08f7d
commit b1edd42da8
7 changed files with 371 additions and 30 deletions
+203 -8
View File
@@ -112,6 +112,52 @@ pub fn panel_width(pointer_x: f32, viewport: f32, rem: f32) -> f32 {
/// How many "worth a look" findings the panel lists.
const INSIGHT_LIMIT: usize = 6;
/// Duration of the tile freshness colour fade when a square becomes fresh.
const FRESHNESS_FADE_MS: f32 = 200.0;
#[derive(Clone, Copy, Debug)]
struct TileFade {
from: f32,
target: f32,
started: Instant,
}
impl TileFade {
fn settled(value: f32, now: Instant) -> Self {
let elapsed = Duration::from_millis(250);
Self {
from: value,
target: value,
started: now.checked_sub(elapsed).unwrap_or(now),
}
}
fn value(&self, now: Instant) -> f32 {
if (self.from - self.target).abs() < f32::EPSILON {
return self.target;
}
let elapsed_ms =
now.saturating_duration_since(self.started).as_secs_f32() * 1000.0;
let t = (elapsed_ms / FRESHNESS_FADE_MS).clamp(0.0, 1.0);
let eased = 1.0 - (1.0 - t).powi(3);
(self.target - self.from).mul_add(eased, self.from)
}
fn is_running(&self, now: Instant) -> bool {
(self.from - self.target).abs() >= f32::EPSILON
&& now.saturating_duration_since(self.started).as_secs_f32()
* 1000.0
< FRESHNESS_FADE_MS
}
}
fn remote_cache_host(host: &str) -> disktree_scanner::HostKey {
disktree_scanner::HostKey::Remote(disktree_scanner::HostIdentity {
hostname: host.to_owned(),
machine_id: None,
})
}
/// Which screen the app is showing.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Screen {
@@ -985,6 +1031,8 @@ pub struct Disktree {
pub view: View,
/// The in-flight layout transition, if a level was just entered or left.
pub transition: Option<LayoutTransition>,
/// Per-tile smooth colour fade when freshness changes (200 ms ease-out).
tile_fades: FxHashMap<PathBuf, TileFade>,
pub layout_options: LayoutOptions,
cache: Option<LayoutCache>,
marked: Option<MarkedCrumbs>,
@@ -1166,6 +1214,7 @@ impl Disktree {
pointer_active: false,
view: View::default(),
transition: None,
tile_fades: FxHashMap::default(),
layout_options: LayoutOptions {
max_depth: depth.clamp(1, 6),
..LayoutOptions::default()
@@ -2060,6 +2109,7 @@ impl Disktree {
self.updating_paths.clear();
self.refreshed_paths.clear();
self.active_scan_path = None;
self.tile_fades.clear();
self.crumbs.clear();
self.selected = None;
self.hovered = None;
@@ -2071,22 +2121,63 @@ impl Disktree {
self.clear_filter();
self.scan_started = Some(Instant::now());
self.scan_elapsed = None;
if let Some(host) = &self.remote {
if let Some(host) = self.remote.clone() {
let intent = if !self.root_path.as_os_str().is_empty()
&& let Some((arena, freshness)) = self.scanner.lookup_cached(
&remote_cache_host(&host),
&self.root_path,
&self.options.to_scanner(),
&policy,
)
&& !matches!(freshness, Freshness::Partial { .. })
{
let is_fresh = matches!(freshness, Freshness::Fresh { .. });
let node = disktree_core::scan::arena_to_node(
&arena,
self.options.apparent_size,
self.options.include_hidden,
self.options.dedup_hardlinks,
self.options.metric,
);
self.arena = Some(arena);
self.freshness = Some(freshness);
self.device = Some(format!("{host} · read-only · cached"));
self.install_tree(node, None, cx);
if is_fresh && !policy.force_refresh {
self.progress.finished = true;
self.scan_elapsed = self.scan_started.map(|t| t.elapsed());
cx.notify();
return;
}
ScanIntent::Refresh {
metric: self.options.metric,
forced: policy.force_refresh,
}
} else {
ScanIntent::Initial
};
let request = disktree_core::remote::Request {
root: (!self.root_path.as_os_str().is_empty())
.then(|| self.root_path.clone()),
disk: self.remote_disk,
options: self.options,
};
match disktree_core::remote::RemoteScan::spawn(host, &request) {
match disktree_core::remote::RemoteScan::spawn(&host, &request) {
Ok(handle) => {
self.active_scan = Some(ActiveScan::Remote {
handle,
intent: ScanIntent::Initial,
});
self.active_scan =
Some(ActiveScan::Remote { handle, intent });
Self::poll_scan(epoch, cx);
}
Err(error) => self.scan_error = Some(error.to_string()),
Err(error) => {
if self.tree.is_some() {
self.notice = Some((
format!("Refresh failed: {error}"),
Status::Warning,
));
} else {
self.scan_error = Some(error.to_string());
}
}
}
cx.notify();
return;
@@ -2201,6 +2292,25 @@ impl Disktree {
format!("{host} · read-only · space at scan")
});
let node = snapshot.tree;
let scanned_at = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
let arena =
Arc::new(disktree_core::scan::node_to_arena_at(
self.root_path.clone(),
&node,
scanned_at,
));
if let Some(host) = self.remote.as_deref() {
self.scanner.store_snapshot(
&remote_cache_host(host),
&arena,
&self.options.to_scanner(),
scanned_at,
);
}
self.arena = Some(arena);
self.freshness = Some(Freshness::Live { scanned_at });
if let Some((metric, directory, selected)) =
refresh_paths
{
@@ -2222,7 +2332,14 @@ impl Disktree {
self.scan_started.map(|t| t.elapsed());
}
Err(error) => {
self.scan_error = Some(error.to_string());
if self.tree.is_some() {
self.notice = Some((
format!("Refresh failed: {error}"),
Status::Warning,
));
} else {
self.scan_error = Some(error.to_string());
}
}
}
self.active_scan = None;
@@ -3507,6 +3624,9 @@ impl Disktree {
let refresh_mode = self.refresh_mode();
let mut decorations = Vec::with_capacity(tiles.len());
let mut slots: Vec<LabelSlot<'_>> = Vec::new();
let now_instant = Instant::now();
let mut tile_fades = std::mem::take(&mut self.tile_fades);
let mut visible_fade_keys = FxHashSet::default();
for tile in tiles {
let crumbs = tile.crumbs();
let node = match &tile.kind {
@@ -3527,6 +3647,23 @@ impl Disktree {
};
let freshness =
self.tile_freshness_at(crumbs, now_unix, refresh_mode);
let target_fade = freshness.fade_amount();
let freshness_fade = match &tile.kind {
TileKind::Node { crumbs } => {
if let Some(path) = self.path_at(crumbs) {
visible_fade_keys.insert(path.clone());
sample_tile_fade(
&mut tile_fades,
path,
target_fade,
now_instant,
)
} else {
target_fade
}
}
TileKind::Others { .. } => target_fade,
};
let is_marked = marked.contains(crumbs);
// Everything inside a marked directory goes with it, so it is
// drawn marked too.
@@ -3542,6 +3679,7 @@ impl Disktree {
reclaimable: node.is_some_and(|n| n.reclaim.is_some()),
filtered,
freshness,
freshness_fade,
unreadable: node.is_some_and(|n| n.read_error),
marked: is_marked,
covered: is_covered,
@@ -3581,6 +3719,10 @@ impl Disktree {
marked: node.is_some() && (is_marked || is_covered),
});
}
tile_fades.retain(|path, fade| {
visible_fade_keys.contains(path) || fade.is_running(now_instant)
});
drop(visible_fade_keys);
slots.sort_by(|left, right| {
let left_area = left.rect.w * left.rect.h;
@@ -3609,6 +3751,7 @@ impl Disktree {
})
.collect();
self.cache = Some(cache);
self.tile_fades = tile_fades;
Mosaic {
tiles: decorations,
@@ -4790,8 +4933,40 @@ impl Disktree {
self.transition = None;
}
}
self.tick_freshness_fades(window);
}
/// Keep animation frames flowing while any tile is mid-fade after a
/// freshness change (200 ms ease-out), then stop cleanly at 0% idle CPU.
pub fn tick_freshness_fades(&self, window: &Window) {
let now = Instant::now();
if self.tile_fades.values().any(|fade| fade.is_running(now)) {
window.request_animation_frame();
}
}
}
fn sample_tile_fade(
tile_fades: &mut FxHashMap<PathBuf, TileFade>,
path: PathBuf,
target: f32,
now: Instant,
) -> f32 {
if let Some(fade) = tile_fades.get_mut(&path) {
if (fade.target - target).abs() >= f32::EPSILON {
let current = fade.value(now);
fade.from = current;
fade.target = target;
fade.started = now;
}
fade.value(now)
} else {
tile_fades.insert(path, TileFade::settled(target, now));
target
}
}
impl Disktree {
/// A tile's rectangle for this frame: mid-transition it is on its way from
/// where it was to where it is.
fn animated_rect(&self, rect: Rect) -> Rect {
@@ -5322,4 +5497,24 @@ mod tests {
assert!(matches!(state.phase, Phase::Idle));
assert!(effects.is_empty());
}
#[test]
fn tile_fade_eases_smoothly_over_200ms() {
let start = Instant::now();
let fade = TileFade {
from: 0.28,
target: 0.0,
started: start,
};
assert!((fade.value(start) - 0.28).abs() < 1e-5);
assert!(fade.is_running(start));
let mid = fade.value(start + Duration::from_millis(100));
assert!(
mid > 0.0 && mid < 0.28,
"expected smooth mid fade, got {mid}"
);
let done = fade.value(start + Duration::from_millis(200));
assert!(done.abs() < 1e-5);
assert!(!fade.is_running(start + Duration::from_millis(200)));
}
}
+23 -7
View File
@@ -44,6 +44,19 @@ pub enum TileFreshness {
Updating,
}
impl TileFreshness {
/// Target fade toward `inset` for this freshness state (`0.0` = full colour).
#[must_use]
pub const fn fade_amount(self) -> f32 {
match self {
Self::Fresh => 0.0,
Self::Updating => 0.14,
Self::Stale => 0.28,
Self::Scheduled => 0.42,
}
}
}
/// How one tile should be drawn, resolved before the paint callback runs so
/// that painting never has to look anything up.
#[derive(Clone, Debug)]
@@ -62,6 +75,9 @@ pub struct TileDeco {
pub filtered: Filtered,
/// Cache freshness / background refresh queue state.
pub freshness: TileFreshness,
/// Animated fade factor toward `inset` (`0.0..=0.42`) so freshness
/// transitions glide smoothly into colour over ~200 ms instead of popping.
pub freshness_fade: f32,
/// Part of it could not be read: flagged in its corner.
pub unreadable: bool,
pub marked: bool,
@@ -140,6 +156,7 @@ pub fn preview(
reclaimable: false,
filtered: Filtered::Shown,
freshness: TileFreshness::Fresh,
freshness_fade: 0.0,
unreadable: false,
marked: false,
covered: false,
@@ -326,13 +343,12 @@ impl Colors {
None => self.fill[category_index(tile.category)][depth],
};
// Freshness uses subtle fades toward `inset` so category hues stay
// calm: queued folders step back slightly, stale folders soften a bit,
// and actively updating folders lift back toward full colour.
let fill = match tile.freshness {
TileFreshness::Fresh => fill,
TileFreshness::Updating => palette::mix(fill, self.inset, 0.14),
TileFreshness::Stale => palette::mix(fill, self.inset, 0.28),
TileFreshness::Scheduled => palette::mix(fill, self.inset, 0.42),
// calm; `freshness_fade` interpolates smoothly over 200 ms when a
// square finishes scanning instead of snapping into colour.
let fill = if tile.freshness_fade > 0.001 {
palette::mix(fill, self.inset, tile.freshness_fade)
} else {
fill
};
// Only what matches keeps its colour; a directory holding matches
// steps back less, so the way to them stays readable.
+1
View File
@@ -900,6 +900,7 @@ fn explore(
);
}
let mosaic: Mosaic = app.prepare();
app.tick_freshness_fades(window);
let width_rems = window.viewport_size().width.as_f32() / app.rem;
// The panel is where the selection, the marks and the disk live; it
// only gives way when the mosaic would be too narrow to read.
+6 -6
View File
@@ -2,12 +2,14 @@
//!
//! Invoked over SSH by `disktree` (auto-deployed from the portable binary or
//! found on the server's `PATH`). Enforces a 1 GiB address-space ceiling on
//! Linux, a 5-minute wall deadline, and exits immediately if the SSH pipe
//! Linux, a 30-minute wall deadline, and exits immediately if the SSH pipe
//! closes so a blocked filesystem never outlives the connection.
use std::io::{self, BufReader, BufWriter, Read as _};
use std::time::Duration;
const STDOUT_BUFFER_BYTES: usize = 256 * 1024;
pub fn serve_stdio_v1() -> io::Result<()> {
limit_resources()?;
// A live client is not permission to monopolise the server forever,
@@ -15,10 +17,8 @@ pub fn serve_stdio_v1() -> io::Result<()> {
std::thread::Builder::new()
.name("scan-deadline".into())
.spawn(|| {
std::thread::park_timeout(Duration::from_mins(5));
eprintln!(
"Remote scan exceeded five minutes; scan a smaller path."
);
std::thread::park_timeout(Duration::from_mins(30));
eprintln!("Remote scan exceeded 30 minutes; scan a smaller path.");
std::process::exit(1);
})?;
let mut input = BufReader::new(io::stdin());
@@ -49,7 +49,7 @@ pub fn serve_stdio_v1() -> io::Result<()> {
}
disktree_core::remote::serve_session(
session,
&mut BufWriter::new(io::stdout().lock()),
&mut BufWriter::with_capacity(STDOUT_BUFFER_BYTES, io::stdout().lock()),
)
}
+14 -6
View File
@@ -10,10 +10,21 @@ use disktree_scanner::{
NodeKind, StreamConfig, StreamItem, stream_walk_with_config,
};
use rustc_hash::FxHashSet;
use serde::Serialize;
use crate::remote::{Record, send};
use crate::scan::ScanOptions;
#[derive(Serialize)]
struct Enter<'a> {
enter: &'a str,
}
#[derive(Serialize)]
struct Heartbeat<'a> {
directory: &'a Path,
}
// Legacy peers require helper-side accounting. Modern clients explicitly
// negotiate desktop de-duplication and never populate this table.
const MAX_PENDING_LINKS: usize = 65_536;
@@ -76,11 +87,8 @@ fn stream_with_boundaries(
last.elapsed() >= crate::remote_progress::INTERVAL
})
{
serde_json::to_writer(
&mut *out,
&serde_json::json!({"directory": dir}),
)
.map_err(io::Error::other)?;
serde_json::to_writer(&mut *out, &Heartbeat { directory: dir })
.map_err(io::Error::other)?;
out.write_all(b"\n")?;
// Flush on a timer even when few tree records fill the buffer.
out.flush()?;
@@ -97,7 +105,7 @@ fn stream_with_boundaries(
maybe_heartbeat(&path, &mut heartbeat, out)?;
if live_tree {
let wire_name = if depth == 0 { "" } else { name.as_str() };
send(out, &serde_json::json!({"enter": wire_name}))?;
send(out, &Enter { enter: wire_name })?;
}
}
StreamItem::LeaveDir {
+51 -3
View File
@@ -618,17 +618,37 @@ fn build_node(
/// a pre-built tree or in tests).
#[must_use]
pub fn node_to_arena(root_path: PathBuf, root: &Node) -> TreeArena {
node_to_arena_at(root_path, root, 0)
}
/// Convert a [`Node`] tree into a [`TreeArena`] and stamp every directory with
/// `scanned_at` (used when persisting completed remote SSH scans to SWR cache).
#[must_use]
pub fn node_to_arena_at(
root_path: PathBuf,
root: &Node,
scanned_at: u64,
) -> TreeArena {
let mut arena = TreeArena::new(root_path, root.name.as_ref());
let root_id = arena.root();
copy_node_into_arena(&mut arena, root_id, root);
copy_node_into_arena(&mut arena, root_id, root, scanned_at);
arena.aggregate(true, true);
if scanned_at > 0 {
arena.refresh_statuses(scanned_at, 1);
}
arena
}
fn copy_node_into_arena(arena: &mut TreeArena, parent: NodeId, node: &Node) {
fn copy_node_into_arena(
arena: &mut TreeArena,
parent: NodeId,
node: &Node,
scanned_at: u64,
) {
{
let target = arena.node_mut(parent);
target.modified = node.modified;
target.scanned_at = scanned_at;
target.flags.set(NodeFlags::READ_ERROR, node.read_error);
target
.flags
@@ -662,7 +682,7 @@ fn copy_node_into_arena(arena: &mut TreeArena, parent: NodeId, node: &Node) {
arena.record_hardlink(id, dev, ino.get());
}
if kind == ScannerKind::Directory {
copy_node_into_arena(arena, id, child);
copy_node_into_arena(arena, id, child, scanned_at);
}
}
}
@@ -1088,6 +1108,34 @@ mod tests {
assert_eq!(tree.bytes, 250);
}
#[test]
fn node_to_arena_roundtrips_remote_trees_for_swr_cache() {
let mut root = Node::directory("dev-home");
root.modified = 1_700_000_000;
let mut sub = Node::directory(".cache");
sub.read_error = true;
sub.children
.push(Node::entry("blob.bin", NodeKind::File, 4096));
root.children.push(sub);
root.children
.push(Node::entry("readme.md", NodeKind::File, 512));
aggregate(&mut root, Metric::Bytes);
let arena =
node_to_arena_at(PathBuf::from("/home/dev"), &root, 1_700_000_123);
let roundtrip = arena_to_node(&arena, false, true, true, Metric::Bytes);
assert_eq!(roundtrip.bytes, 4608);
assert_eq!(roundtrip.files, 2);
let cache = roundtrip.child_named(".cache").expect(".cache");
assert!(cache.read_error);
assert_eq!(cache.bytes, 4096);
let without_hidden =
arena_to_node(&arena, false, false, true, Metric::Bytes);
assert_eq!(without_hidden.bytes, 512);
assert!(without_hidden.child_named(".cache").is_none());
}
#[test]
#[ignore = "walks the whole disk"]
fn whole_disk_smoke() {
+73
View File
@@ -607,6 +607,79 @@ impl Scanner {
}
}
/// Look up a cached subtree for `host` and `root` without starting a walk.
///
/// Useful for remote SSH hosts whose live walk runs over the network rather
/// than on the local filesystem.
pub fn lookup_cached(
&self,
host: &HostKey,
root: &Path,
options: &ScanOptions,
policy: &CachePolicy,
) -> Option<(Arc<TreeArena>, Freshness)> {
let db_opt = self
.storage
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.db();
let (tx, _rx) = mpsc::channel();
let cached = self.try_load_cached(
db_opt.as_ref(),
host,
root,
options,
unix_now(),
policy,
&tx,
)?;
Some((Arc::new(cached.arena), cached.freshness))
}
/// Persist a completed snapshot (for example, a finished remote SSH scan)
/// into the in-memory cache immediately and into the on-disk cache DB in
/// the background.
pub fn store_snapshot(
&self,
host: &HostKey,
arena: &Arc<TreeArena>,
options: &ScanOptions,
scanned_at: u64,
) {
let db_opt = {
let mut guard = self
.storage
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(cache) = guard.mem_cache_mut() {
cache.insert(
(host.as_db_key(), arena.root_path().to_path_buf()),
(
Arc::clone(arena),
scanned_at,
options.cache_topology_mask(),
),
);
}
guard.db()
};
if let Some(db) = db_opt {
let storage = Arc::clone(&self.storage);
let host = host.clone();
let arena = Arc::clone(arena);
let options = *options;
let _ = thread::Builder::new()
.name("disktree-cache-write".into())
.spawn(move || {
if let Err(reason) =
db.store_subtree(&host, &arena, &options, scanned_at)
{
downgrade_storage(&storage, reason);
}
});
}
}
/// Return diagnostic stats for the persistent/temp cache database.
pub fn cache_stats(&self) -> io::Result<CacheStats> {
let db_opt = self