From 00456903cabbdc2f1cc153bbd4ac949ebd1f0ac5 Mon Sep 17 00:00:00 2001 From: Tobi Lutke Date: Thu, 26 Nov 2026 12:46:40 -0500 Subject: [PATCH] feat(remote,ui): full-duplex --connected mode with depth-4 wire pruning, helper_version, O(N) shard splice, and unified dense sidebar progress card --- crates/disktree-app/src/state.rs | 121 +++++-- crates/disktree-app/src/ui.rs | 1 - crates/disktree-app/src/views.rs | 338 +++++++++----------- crates/disktree-cli/src/main.rs | 4 +- crates/disktree-cli/src/stdio.rs | 189 ++++++++++- crates/disktree-cli/tests/stdio.rs | 62 ++++ crates/disktree-core/src/remote.rs | 278 +++++++++++++++- crates/disktree-core/src/remote_progress.rs | 6 +- crates/disktree-scanner/src/tree.rs | 80 +++-- 9 files changed, 793 insertions(+), 286 deletions(-) diff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rs index a06a18a..53e31d8 100644 --- a/crates/disktree-app/src/state.rs +++ b/crates/disktree-app/src/state.rs @@ -1139,6 +1139,7 @@ pub struct Disktree { pub remote: Option, remote_disk: bool, pub remote_progress: disktree_core::remote_progress::Progress, + remote_stale_seq: u64, /// Tailscale SSH check URL opened in the browser while waiting for approval. pub auth_url: Option, pub scan_preview: Option>, @@ -1351,6 +1352,7 @@ impl Disktree { preview_updated: None, remote_progress: disktree_core::remote_progress::Progress::default( ), + remote_stale_seq: 0, auth_url: None, remote_platform: String::new(), remote_identity: None, @@ -2231,6 +2233,7 @@ impl Disktree { self.progress = ScanSnapshot::default(); self.remote_progress = disktree_core::remote_progress::Progress::default(); + self.remote_stale_seq = 0; self.scan_error = None; self.scan_preview = None; self.preview_updated = None; @@ -2306,6 +2309,7 @@ impl Disktree { self.scan_error = None; self.remote_progress = disktree_core::remote_progress::Progress::default(); + self.remote_stale_seq = 0; self.scan_preview = None; self.preview_updated = None; // A new scan starts at its root; where it was is one `<` away. @@ -2478,10 +2482,16 @@ impl Disktree { self.remote_progress = handle.progress(); let auth_url = self.remote_progress.auth_url.clone(); self.handle_auth_url(auth_url, cx); - if self.tree.is_none() + if self.remote_progress.stale_seq > self.remote_stale_seq && let Some(stale) = self.remote_progress.stale_snapshot.clone() { + self.remote_stale_seq = self.remote_progress.stale_seq; + let had_tree = self.tree.is_some(); + let prev_dir = had_tree.then(|| self.current_path()); + let prev_sel = had_tree.then(|| { + self.selected.as_deref().and_then(|c| self.path_at(c)) + }); let stale_dirs = stale.tree.dirs; self.root_path.clone_from(&stale.header.root); self.home.clone_from(&stale.header.home); @@ -2489,8 +2499,13 @@ impl Disktree { self.space = stale.header.space; self.remote_platform.clone_from(&stale.header.platform); self.update_remote_identity(stale.header.identity.clone()); + let ver = stale + .header + .helper_version + .as_deref() + .map_or_else(String::new, |v| format!(" · v{v}")); self.device = self.remote.as_ref().map(|host| { - format!("{host} · read-only · cached (refreshing…)") + format!("{host}{ver} · read-only · live updating") }); self.arena = Some(Arc::new(disktree_core::scan::node_to_arena_at( @@ -2503,7 +2518,17 @@ impl Disktree { newest_at: 1, stale_dirs, }); - self.install_tree(stale.tree.clone(), None, cx); + if let Some(directory) = prev_dir { + self.install_refresh( + stale.tree.clone(), + self.options.metric, + &directory, + prev_sel.flatten(), + cx, + ); + } else { + self.install_tree(stale.tree.clone(), None, cx); + } } if self.remote_progress.preview.is_some() && (self.scan_preview.is_none() @@ -2539,8 +2564,13 @@ impl Disktree { self.space = snapshot.header.space; self.remote_platform = snapshot.header.platform; self.update_remote_identity(snapshot.header.identity); + let ver = snapshot + .header + .helper_version + .as_deref() + .map_or_else(String::new, |v| format!(" · v{v}")); self.device = self.remote.as_ref().map(|host| { - format!("{host} · read-only · space at scan") + format!("{host}{ver} · read-only · space at scan") }); let node = snapshot.tree; let scanned_at = std::time::SystemTime::now() @@ -3357,9 +3387,16 @@ impl Disktree { self.cache = None; // Entering a directory while a background SWR refresh is running // prioritizes that subtree first. - if let Some(ActiveScan::Local { handle, .. }) = &self.active_scan { - let target = self.current_path(); - handle.prioritize(&target); + match &self.active_scan { + Some(ActiveScan::Local { handle, .. }) => { + let target = self.current_path(); + handle.prioritize(&target); + } + Some(ActiveScan::Remote { handle, .. }) => { + let target = self.current_path(); + handle.prioritize(&target); + } + None => {} } cx.notify(); } @@ -5253,48 +5290,68 @@ impl Disktree { self.tick_freshness_fades(window); } - /// Plain-language explanation of active background work for the sidebar - /// Activity card (`(heading, why)`), when a tree is already on screen. + /// Plain-language explanation of active scan work for the unified sidebar + /// status card (`(heading, why)`). #[must_use] - pub fn scan_activity_summary(&self) -> Option<(&'static str, String)> { - self.tree.as_ref()?; + pub fn scan_activity_summary(&self) -> Option<(String, String)> { let active = self.active_scan.as_ref()?; + let has_tree = self.tree.is_some(); match active { ActiveScan::Remote { intent, .. } => { let host = self.remote.as_deref().unwrap_or("remote"); - Some(match intent { + let stage = self.remote_progress.stage; + let (heading, why) = match intent { ScanIntent::Refresh { forced: true, .. } => ( - "Rescanning remote", - format!("Rescanning {host} on request"), + format!("Rescanning {host}"), + "Rescanning on request — keep browsing".into(), ), ScanIntent::Refresh { forced: false, .. } => ( - "Refreshing cache", - format!("Updating stale {host} cache in background"), + format!("Refreshing {host}"), + "Updating stale cache — keep browsing".into(), ), ScanIntent::Widening { .. } => ( - "Expanding scan", - format!("Reading parent folder on {host}"), + format!("Expanding {host}"), + "Reading parent folder — keep browsing".into(), ), - ScanIntent::Initial => { - ("Scanning remote", format!("Indexing {host} over SSH")) - } - }) + ScanIntent::Initial if has_tree => ( + format!("Updating {host}"), + "Filling remaining folders — keep browsing".into(), + ), + ScanIntent::Initial => ( + format!("Scanning {host}"), + if stage + == disktree_core::remote_progress::Stage::Indexing + { + "Building initial index — preview is provisional" + .into() + } else { + stage.label().to_owned() + }, + ), + }; + Some((heading, why)) } ActiveScan::Local { intent, .. } => Some(match intent { - ScanIntent::Refresh { forced: true, .. } => { - ("Rescanning", "Rescanning this folder on request".into()) - } + ScanIntent::Refresh { forced: true, .. } => ( + "Rescanning".into(), + "Rescanning on request — keep browsing".into(), + ), ScanIntent::Refresh { forced: false, .. } => ( - "Refreshing cache", - "Updating folders older than 15 min — keep browsing".into(), + "Refreshing cache".into(), + "Updating folders >15m old — keep browsing".into(), ), ScanIntent::Widening { .. } => ( - "Expanding scan", - "Reading parent folder around current view".into(), + "Expanding scan".into(), + "Reading parent folder — keep browsing".into(), + ), + ScanIntent::Initial if has_tree => ( + "Updating".into(), + "Filling remaining folders — keep browsing".into(), + ), + ScanIntent::Initial => ( + "Scanning".into(), + "Building initial index — preview is provisional".into(), ), - ScanIntent::Initial => { - ("Scanning", "Indexing this folder".into()) - } }), } } diff --git a/crates/disktree-app/src/ui.rs b/crates/disktree-app/src/ui.rs index 50559cc..95a4202 100644 --- a/crates/disktree-app/src/ui.rs +++ b/crates/disktree-app/src/ui.rs @@ -77,7 +77,6 @@ pub mod size { pub const METER: Rems = Rems(0.3125); /// Fixed progress rows keep paths and changing counters from reflowing. pub const PROGRESS_ROW: Rems = Rems(1.375); - pub const PROGRESS_VALUE: Rems = Rems(9.0); /// Fixed height of the top-right Selection card so the lists below never /// jump while hovering or selecting different tiles. pub const SELECTION_HEIGHT: Rems = Rems(12.25); diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rs index 734ce26..7127dc9 100644 --- a/crates/disktree-app/src/views.rs +++ b/crates/disktree-app/src/views.rs @@ -1872,9 +1872,11 @@ fn side_panel( .border_color(theme.divider()) .bg(theme.surface) .child(handle) - .child(if app.is_indexing() { + .child(if app.tree().is_none() && app.is_indexing() { indexing_progress(app, theme, cx) - } else { selection_section(app, theme, cx) }) + } else { + selection_section(app, theme, cx) + }) .child(rule()) // The lists scroll; the selection above and the disk below stay put, // so the two numbers that matter never leave the screen. @@ -1891,122 +1893,15 @@ fn side_panel( .child(rule()) .child(marked_section(app, theme, cx)), ) - .children(activity_section(app, theme, cx)) + .when(app.tree().is_some() && app.is_indexing(), |panel| { + panel.child(indexing_progress(app, theme, cx)) + }) .children(notice_line(app, theme, cx)) .children(privacy_line(app, theme, cx)) .children(administrator_line(app, theme, cx)) .child(disk_section(app, theme, cx)) } -/// Calm, fixed-height sidebar banner explaining WHEN background scanning is -/// running and WHY (stale cache refresh, explicit rescan, widening, or remote), -/// with live monospace counters and current folder lane plus a Stop control. -fn activity_section( - app: &Disktree, - theme: &Theme, - cx: &Context<'_, Disktree>, -) -> Option
{ - let (heading, why) = app.scan_activity_summary()?; - let counts = if app.progress.files > 0 || app.progress.dirs > 0 { - format!( - "{} · {} files · {} dirs", - human_bytes(app.progress.bytes), - disktree_core::size::human_count(app.progress.files), - disktree_core::size::human_count(app.progress.dirs), - ) - } else if app.remote.is_some() { - app.remote_progress.stage.label().to_owned() - } else { - "Checking cached folders…".to_owned() - }; - let current_path = app - .remote - .as_ref() - .and(app.remote_progress.directory.as_deref()) - .or(app.active_scan_path.as_deref()) - .map(|p| app.display_path(p)) - .unwrap_or_default(); - - Some( - div() - .debug_selector(|| "sidebar-activity".into()) - .flex() - .flex_col() - .gap(space::XXS) - .px(space::LG) - .py(space::SM) - .bg(theme.inset) - .border_t_1() - .border_color(theme.divider()) - .child( - div() - .flex() - .flex_row() - .items_center() - .justify_between() - .gap(space::SM) - .child( - div() - .flex() - .flex_row() - .items_center() - .gap(space::XS) - .child( - gpui_omarchy::icon( - gpui_omarchy::IconName::RotateCw, - ) - .size(icon::SM) - .text_color(theme.accent), - ) - .child(widgets::eyebrow(heading, cx)), - ) - .child( - button( - "activity-stop", - "Stop", - ButtonVariant::Outline, - cx, - ) - .tab_stop(false) - .px(space::XS) - .py(space::XXS) - .on_click(cx.listener( - |this, _, window, cx| { - this.cancel_scan(cx); - window.focus(&this.focus, cx); - }, - )), - ), - ) - .child( - div() - .h(size::PROGRESS_ROW) - .truncate() - .text_size(text::CAPTION) - .text_color(theme.foreground) - .child(why), - ) - .child( - div() - .h(size::PROGRESS_ROW) - .truncate() - .font_family(theme.mono_font.clone()) - .text_size(text::CAPTION) - .text_color(theme.secondary) - .child(counts), - ) - .child( - div() - .h(size::PROGRESS_ROW) - .truncate() - .font_family(theme.mono_font.clone()) - .text_size(text::CAPTION) - .text_color(theme.secondary) - .child(current_path), - ), - ) -} - /// What the keys act on: compact, static-height summary with Open, Mark and /// Refresh icon controls in the top right so the lists below never jump. fn selection_section( @@ -3120,37 +3015,48 @@ fn indexing_compact( /// Progress has one owner. Stable rows and mono values prevent digit, // unit and path changes from pushing the rest of the screen around. +/// Dense, unified scan status card used for both initial cold indexing and +/// background cache refreshes. Every row uses fixed heights and equal flex +/// columns so live counters and long paths never shift the sidebar layout. fn indexing_progress( app: &Disktree, theme: &Theme, cx: &Context<'_, Disktree>, ) -> Div { let elapsed = app.scan_started.map_or(0, |at| at.elapsed().as_secs()); - let row = |label: &'static str, value: String, id: &'static str| { - div() - .flex() - .items_center() - .justify_between() - .h(size::PROGRESS_ROW) - .child(div().text_color(theme.secondary).child(label)) - .child( - div() - .debug_selector(move || id.into()) - .w(size::PROGRESS_VALUE) - .text_right() - .font_family(theme.mono_font.clone()) - .child(value), - ) + let (heading, why) = app.scan_activity_summary().unwrap_or_else(|| { + ( + if app.is_refreshing() { + "Refreshing".into() + } else { + "Scanning".into() + }, + if app.remote.is_some() { + app.remote_progress.stage.label().to_owned() + } else { + "Reading this computer".into() + }, + ) + }); + let meta_badge = if app.progress.errors > 0 { + format!( + "{elapsed} s · {} err", + widgets::human_count(app.progress.errors) + ) + } else { + format!("{elapsed} s") }; let path = if app.remote.is_some() { - app.remote_progress.directory.as_ref() + app.remote_progress.directory.as_deref() } else { - app.scan_preview - .as_ref() - .and_then(|preview| preview.directory.as_ref()) + app.active_scan_path.as_deref().or_else(|| { + app.scan_preview + .as_ref() + .and_then(|preview| preview.directory.as_deref()) + }) }; let full_path = path.map_or_else( - || "Directory not reported yet".into(), + || "Waiting for first directory…".into(), |path| path.display().to_string(), ); // Split by the scanned machine's rules: a Unix host's `a\b` is one name. @@ -3161,29 +3067,104 @@ fn indexing_progress( } else { full_path.clone() }; + + let stat = |label: &'static str, value: String, id: &'static str| { + div() + .flex() + .flex_col() + .flex_1() + .min_w_0() + .child( + div() + .debug_selector(move || id.into()) + .h(size::PROGRESS_ROW) + .truncate() + .font_family(theme.mono_font.clone()) + .text_size(text::BODY) + .font_weight(FontWeight::MEDIUM) + .text_color(theme.bright) + .child(value), + ) + .child( + div() + .h(size::PROGRESS_ROW) + .truncate() + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(label), + ) + }; + div() .debug_selector(|| "indexing-progress".into()) .flex() .flex_col() .min_w_0() .gap(space::XS) - .text_size(text::BODY) - .text_color(theme.foreground) - .child(widgets::eyebrow( - if app.is_refreshing() { - "Refreshing" - } else { - "Indexing" - }, - cx, - )) - .child(div().h(size::PROGRESS_ROW).truncate().child( - if app.remote.is_some() { - app.remote_progress.stage.label() - } else { - "Reading this computer" - }, - )) + .p(space::MD) + .bg(theme.inset) + .border_1() + .border_color(theme.divider()) + .child( + div() + .flex() + .flex_row() + .items_center() + .justify_between() + .gap(space::SM) + .h(size::PROGRESS_ROW) + .child( + div() + .flex() + .flex_row() + .items_center() + .gap(space::XS) + .min_w_0() + .flex_1() + .child( + gpui_omarchy::icon( + gpui_omarchy::IconName::RotateCw, + ) + .size(icon::SM) + .text_color(theme.accent) + .flex_shrink_0(), + ) + .child( + div() + .min_w_0() + .truncate() + .child(widgets::eyebrow(heading, cx)), + ) + .child( + div() + .flex_shrink_0() + .font_family(theme.mono_font.clone()) + .text_size(text::CAPTION) + .text_color(theme.secondary) + .child(format!("· {meta_badge}")), + ), + ) + .child(with_tooltip( + button("cancel-scan", "Stop", ButtonVariant::Outline, cx) + .tab_stop(false) + .px(space::XS) + .py(space::XXS) + .on_click(cx.listener(|this, _, window, cx| { + this.cancel_scan(cx); + window.focus(&this.focus, cx); + })), + "Stop scan · Esc", + )), + ) + .child( + div() + .h(size::PROGRESS_ROW) + .min_w_0() + .truncate() + .text_size(text::CAPTION) + .text_color(theme.foreground) + .child(why), + ) .when_some(app.auth_url.clone(), |panel, url| { panel.child( button( @@ -3197,33 +3178,27 @@ fn indexing_progress( }), ) }) - .child(row( - "Files", - widgets::human_count(app.progress.files), - "indexing-files", - )) - .child(row( - "Directories", - widgets::human_count(app.progress.dirs), - "indexing-dirs", - )) - .child(row( - "Measured", - human_bytes(app.progress.bytes), - "indexing-bytes", - )) - .child(row( - "Read errors", - widgets::human_count(app.progress.errors), - "indexing-errors", - )) - .child(row("Elapsed", format!("{elapsed} s"), "indexing-elapsed")) .child( div() - .h(size::PROGRESS_ROW) - .text_size(text::CAPTION) - .text_color(theme.secondary) - .child("Recent directory"), + .flex() + .flex_row() + .gap(space::SM) + .pt(space::XXS) + .child(stat( + "Measured", + human_bytes(app.progress.bytes), + "indexing-bytes", + )) + .child(stat( + "Files", + widgets::human_count(app.progress.files), + "indexing-files", + )) + .child(stat( + "Dirs", + widgets::human_count(app.progress.dirs), + "indexing-dirs", + )), ) .child(with_tooltip( div() @@ -3233,22 +3208,11 @@ fn indexing_progress( .min_w_0() .truncate() .font_family(theme.mono_font.clone()) + .text_size(text::CAPTION) + .text_color(theme.secondary) .child(short_path), full_path, )) - .child( - div() - .text_size(text::CAPTION) - .text_color(theme.secondary) - .child("Preview only · provisional totals"), - ) - .child( - button("cancel-scan", "Stop indexing", ButtonVariant::Outline, cx) - .on_click(cx.listener(|this, _, window, cx| { - this.cancel_scan(cx); - window.focus(&this.focus, cx); - })), - ) } fn find_field(app: &Disktree, theme: &Theme) -> Div { diff --git a/crates/disktree-cli/src/main.rs b/crates/disktree-cli/src/main.rs index f975c2e..08f4a79 100644 --- a/crates/disktree-cli/src/main.rs +++ b/crates/disktree-cli/src/main.rs @@ -26,7 +26,9 @@ fn main() -> Result<()> { // kernel resource limits before reading stdin. let raw_args: Vec = std::env::args_os().skip(1).collect(); - if raw_args.len() == 1 && raw_args[0] == "--stdio-v1" { + if raw_args.len() == 1 + && (raw_args[0] == "--connected" || raw_args[0] == "--stdio-v1") + { return stdio::serve_stdio_v1().map_err(Into::into); } diff --git a/crates/disktree-cli/src/stdio.rs b/crates/disktree-cli/src/stdio.rs index c861e24..d914f89 100644 --- a/crates/disktree-cli/src/stdio.rs +++ b/crates/disktree-cli/src/stdio.rs @@ -10,24 +10,30 @@ //! immediately if the SSH pipe closes so a blocked filesystem never outlives //! the connection. -use std::io::{self, BufReader, BufWriter, Read as _, Write}; +use std::io::{self, BufRead as _, BufReader, BufWriter, Read as _, Write}; use std::path::{Path, PathBuf}; +use std::sync::mpsc::{self, Receiver}; use std::sync::{Arc, Mutex}; use std::time::{Duration, Instant}; use disktree_core::remote::{ - Operation, Request, SessionRequest, write_arena, write_header, - write_marker, write_progress, + ConnectedCommand, Operation, Request, SessionRequest, write_arena_pruned, + write_header, write_marker, write_progress, }; use disktree_core::scan_preview; use disktree_scanner::{ CachePolicy, DirTallyHook, Freshness, HostKey, ScanEvent, Scanner, - StorageMode, + StorageMode, TreeArena, }; const STDOUT_BUFFER_BYTES: usize = 256 * 1024; const HEARTBEAT_INTERVAL: Duration = Duration::from_millis(200); const PREVIEW_INTERVAL: Duration = Duration::from_millis(500); +const PARTIAL_STREAM_INTERVAL: Duration = Duration::from_secs(3); +const FINAL_WIRE_MAX_DEPTH: usize = 4; +const FINAL_WIRE_MAX_CHILDREN: usize = 48; +const PARTIAL_WIRE_MAX_DEPTH: usize = 4; +const PARTIAL_WIRE_MAX_CHILDREN: usize = 32; pub fn serve_stdio_v1() -> io::Result<()> { limit_resources()?; @@ -42,7 +48,43 @@ pub fn serve_stdio_v1() -> io::Result<()> { })?; let mut input = BufReader::new(io::stdin()); let session = disktree_core::remote::read_request(&mut input)?; - if session.watch_disconnect { + let cmd_rx: Option> = if session.full_duplex { + let (cmd_tx, cmd_rx) = mpsc::channel(); + std::thread::Builder::new() + .name("scan-duplex-stdin".into()) + .spawn(move || { + let mut line = String::new(); + loop { + line.clear(); + match input.read_line(&mut line) { + Err(error) + if error.kind() == io::ErrorKind::Interrupted => {} + Ok(0) => { + // Exit the process, not just a scan task: a + // blocked filesystem must not outlive SSH. + std::process::exit(0); + } + Ok(_) => { + let trimmed = line.trim(); + if trimmed.is_empty() { + continue; + } + if let Ok(cmd) = + serde_json::from_str::( + trimmed, + ) + { + let _ = cmd_tx.send(cmd); + } + } + Err(_) => { + std::process::exit(0); + } + } + } + })?; + Some(cmd_rx) + } else if session.watch_disconnect { std::thread::Builder::new() .name("scan-connection".into()) .spawn(move || { @@ -65,14 +107,18 @@ pub fn serve_stdio_v1() -> io::Result<()> { } } })?; - } + None + } else { + None + }; let mut out = BufWriter::with_capacity(STDOUT_BUFFER_BYTES, io::stdout().lock()); - serve_with_remote_db(session, &mut out) + serve_with_remote_db(session, cmd_rx.as_ref(), &mut out) } fn serve_with_remote_db( session: SessionRequest, + cmd_rx: Option<&Receiver>, out: &mut impl Write, ) -> io::Result<()> { let SessionRequest { @@ -83,6 +129,7 @@ fn serve_with_remote_db( live_tree, stream_stale, force_refresh, + full_duplex, } = session; let request = match operation { Operation::Discover { .. } => { @@ -95,6 +142,7 @@ fn serve_with_remote_db( live_tree, stream_stale, force_refresh, + full_duplex, }, out, ); @@ -140,6 +188,7 @@ fn serve_with_remote_db( live_tree, stream_stale, force_refresh, + full_duplex, }, out, ); @@ -156,6 +205,7 @@ fn serve_with_remote_db( stream_stale, force_refresh, }, + cmd_rx, out, ) } @@ -177,6 +227,7 @@ fn serve_scan_from_scanner( root: PathBuf, request: &Request, flags: StreamFlags, + cmd_rx: Option<&Receiver>, out: &mut W, ) -> io::Result<()> { let policy = CachePolicy { @@ -206,6 +257,7 @@ fn serve_scan_from_scanner( }); hook }); + let session_root = root.clone(); let session = scanner.open_with_tally( HostKey::Local, root, @@ -216,8 +268,11 @@ fn serve_scan_from_scanner( let mut last_heartbeat = Instant::now(); let mut last_preview: Option = None; + let mut last_partial = Instant::now(); let mut streamed_final = false; let mut streamed_stale = false; + let mut live_root: Option = None; + let mut live_dirty = false; let emit_progress = |last: &mut Instant, last_preview: &mut Option, @@ -266,61 +321,164 @@ fn serve_scan_from_scanner( }; loop { + if let Some(rx) = cmd_rx { + while let Ok(cmd) = rx.try_recv() { + match cmd { + ConnectedCommand::Prioritize { path } => { + let _ = session.prioritize(&path); + } + ConnectedCommand::Focus { path, depth } => { + let _ = session.prioritize(&path); + let depth = depth.clamp(1, FINAL_WIRE_MAX_DEPTH); + if flags.stream_stale + && !streamed_final + && let Some((cached, _)) = scanner.lookup_cached( + &HostKey::Local, + &path, + &request.options.to_scanner(), + &CachePolicy::default(), + ) + { + write_arena_pruned( + &cached, + &request.options, + flags.client_dedup, + depth, + PARTIAL_WIRE_MAX_CHILDREN, + out, + )?; + write_marker("partial", out)?; + } + } + ConnectedCommand::Cancel => { + session.cancel(); + } + } + } + } + if flags.stream_stale + && !streamed_final + && live_dirty + && last_partial.elapsed() >= PARTIAL_STREAM_INTERVAL + && let Some(arena) = live_root.as_mut() + { + arena.aggregate( + request.options.dedup_hardlinks, + request.options.include_hidden, + ); + write_arena_pruned( + arena, + &request.options, + flags.client_dedup, + PARTIAL_WIRE_MAX_DEPTH, + PARTIAL_WIRE_MAX_CHILDREN, + out, + )?; + write_marker("partial", out)?; + live_dirty = false; + streamed_stale = true; + last_partial = Instant::now(); + last_heartbeat = Instant::now(); + } + match session.recv_timeout(HEARTBEAT_INTERVAL) { Ok(ScanEvent::Snapshot(snap)) => match snap.freshness { Freshness::Partial { .. } => { - // If an earlier or interrupted scan already checkpointed - // completed folders in the remote DB, stream that - // approximate tree right away so the user can explore - // while the remaining holes fill in. if flags.stream_stale && !streamed_stale && snap.arena.node(snap.arena.root()).files > 0 { - write_arena( + write_arena_pruned( &snap.arena, &request.options, flags.client_dedup, + PARTIAL_WIRE_MAX_DEPTH, + PARTIAL_WIRE_MAX_CHILDREN, out, )?; write_marker("stale", out)?; + live_root = Some((*snap.arena).clone()); streamed_stale = true; + last_partial = Instant::now(); last_heartbeat = Instant::now(); } } Freshness::Fresh { .. } => { - write_arena( + write_arena_pruned( &snap.arena, &request.options, flags.client_dedup, + FINAL_WIRE_MAX_DEPTH, + FINAL_WIRE_MAX_CHILDREN, out, )?; streamed_final = true; } Freshness::Stale { .. } => { if flags.stream_stale && !streamed_stale { - write_arena( + write_arena_pruned( &snap.arena, &request.options, flags.client_dedup, + PARTIAL_WIRE_MAX_DEPTH, + PARTIAL_WIRE_MAX_CHILDREN, out, )?; write_marker("stale", out)?; + live_root = Some((*snap.arena).clone()); streamed_stale = true; + last_partial = Instant::now(); last_heartbeat = Instant::now(); } } Freshness::Live { .. } => { - write_arena( + write_arena_pruned( &snap.arena, &request.options, flags.client_dedup, + FINAL_WIRE_MAX_DEPTH, + FINAL_WIRE_MAX_CHILDREN, out, )?; out.flush()?; streamed_final = true; } }, + Ok(ScanEvent::SubtreeRefreshed { path, arena, .. }) => { + if flags.stream_stale && !streamed_final { + let root_arena = live_root.get_or_insert_with(|| { + let root_name = session_root.file_name().map_or_else( + || "root".to_owned(), + |n| n.to_string_lossy().into_owned(), + ); + TreeArena::new(session_root.clone(), &root_name) + }); + if let Ok(rel) = path.strip_prefix(&session_root) { + let parts: Vec = rel + .components() + .map(|c| { + c.as_os_str().to_string_lossy().into_owned() + }) + .collect(); + if parts.len() == 1 { + if let Some(existing) = root_arena + .find_relative(parts.iter().map(String::as_str)) + { + root_arena + .replace_node_contents(existing, &arena); + } else { + root_arena.graft_subtree( + root_arena.root(), + &arena, + Some(&parts[0]), + ); + } + live_dirty = true; + } + } + } + emit_progress(&mut last_heartbeat, &mut last_preview, out)?; + } Ok(ScanEvent::Finished) => { // Waiting until `Finished` guarantees the remote host's cache // DB commit completed before `"done"` lets the client close @@ -338,7 +496,6 @@ fn serve_scan_from_scanner( } Ok( ScanEvent::SubtreeUpdating { .. } - | ScanEvent::SubtreeRefreshed { .. } | ScanEvent::Progress { .. } | ScanEvent::StorageFallback { .. }, ) diff --git a/crates/disktree-cli/tests/stdio.rs b/crates/disktree-cli/tests/stdio.rs index dafa439..07a8af3 100644 --- a/crates/disktree-cli/tests/stdio.rs +++ b/crates/disktree-cli/tests/stdio.rs @@ -325,3 +325,65 @@ fn stdio_persists_to_remote_cache_db_and_revalidates_on_force_refresh() { let after = run(false); assert_eq!(after.tree.bytes, 350); } + +#[cfg(unix)] +#[test] +fn connected_full_duplex_accepts_prioritize_over_stdin_and_reports_version() { + let dir = tempfile::tempdir().unwrap(); + let cache_home = tempfile::tempdir().unwrap(); + let sub = dir.path().join("focus"); + std::fs::create_dir(&sub).unwrap(); + std::fs::write(sub.join("data.bin"), [0_u8; 128]).unwrap(); + + let mut child = Command::new(env!("CARGO_BIN_EXE_disktree-cli")) + .arg("--connected") + .env("XDG_CACHE_HOME", cache_home.path()) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .unwrap(); + let mut input = child.stdin.take().unwrap(); + let req = serde_json::json!({ + "root": dir.path(), + "disk": false, + "options": ScanOptions { + apparent_size: true, + ..ScanOptions::default() + }, + "watch_disconnect": true, + "full_duplex": true, + "stream_stale": true, + }); + serde_json::to_writer(&mut input, &req).unwrap(); + input + .write_all( + b" +", + ) + .unwrap(); + // Send a full-duplex prioritize command on the same open stdin pipe. + let cmd = serde_json::json!({ + "cmd": "prioritize", + "path": sub, + }); + serde_json::to_writer(&mut input, &cmd).unwrap(); + input + .write_all( + b" +", + ) + .unwrap(); + input.flush().unwrap(); + + let snapshot = + read_snapshot(&mut BufReader::new(child.stdout.take().unwrap())) + .unwrap(); + drop(input); + assert!(child.wait().unwrap().success()); + assert_eq!(snapshot.tree.bytes, 128); + assert_eq!( + snapshot.header.helper_version.as_deref(), + Some(env!("CARGO_PKG_VERSION")) + ); +} diff --git a/crates/disktree-core/src/remote.rs b/crates/disktree-core/src/remote.rs index a41d019..beb69e4 100644 --- a/crates/disktree-core/src/remote.rs +++ b/crates/disktree-core/src/remote.rs @@ -159,6 +159,23 @@ pub struct SessionRequest { /// Ask the remote host to bypass its own 15m cache TTL and revalidate. #[serde(default)] pub force_refresh: bool, + /// Opt-in: keep stdin open for full-duplex [`ConnectedCommand`] messages + /// (`prioritize`, `focus`, `cancel`) while streaming snapshots on stdout. + #[serde(default)] + pub full_duplex: bool, +} + +/// Client-to-server control message sent over `stdin` during a full-duplex +/// `--connected` session. +#[derive(Clone, Debug, Serialize, Deserialize, PartialEq, Eq)] +#[serde(tag = "cmd", rename_all = "snake_case")] +pub enum ConnectedCommand { + /// Preempt background walking on the remote host to refresh `path` first. + Prioritize { path: PathBuf }, + /// Focus a depth-bounded view rooted at `path` (clamped to depth <= 4). + Focus { path: PathBuf, depth: usize }, + /// Cancel the active remote scan cleanly. + Cancel, } /// The target's root candidates, without walking or probing any of them. @@ -199,6 +216,10 @@ pub struct Header { pub platform: String, #[serde(default)] pub identity: Option, + /// Semantic version of the remote `disktree-cli` helper (e.g. `"1.0.0"`), + /// reported so the client can surface version mismatches cleanly. + #[serde(default)] + pub helper_version: Option, } #[derive(Debug)] @@ -336,6 +357,7 @@ pub fn write_header( home, platform: std::env::consts::OS.into(), identity: crate::identity::HostIdentity::current(), + helper_version: Some(env!("CARGO_PKG_VERSION").to_owned()), }, )?; out.flush() @@ -383,6 +405,213 @@ pub fn write_marker(marker: &str, out: &mut impl Write) -> io::Result<()> { out.flush() } +/// Node threshold above which `--connected` uses depth-pruned wire streaming. +/// +/// Avoids shipping 25M+ JSON lines (>1 GiB) over SSH to render a depth-4 +/// treemap. +pub const FULL_WIRE_NODE_LIMIT: usize = 4_000; + +/// Serialize a `disktree_scanner::TreeArena` over the wire. +/// +/// Streams every node when `arena.len() <= FULL_WIRE_NODE_LIMIT`, or an exact +/// depth-pruned tree (top `max_children` per directory down to `max_depth`, +/// rolling deeper/tail entries into a summary leaf with exact byte and file +/// totals). +pub fn write_arena_pruned( + arena: &disktree_scanner::TreeArena, + options: &ScanOptions, + client_dedup: bool, + max_depth: usize, + max_children: usize, + out: &mut impl Write, +) -> io::Result<()> { + if arena.len() <= FULL_WIRE_NODE_LIMIT { + return write_arena(arena, options, client_dedup, out); + } + write_arena_summary(arena, options, max_depth, max_children, out) +} + +fn write_arena_summary( + arena: &disktree_scanner::TreeArena, + options: &ScanOptions, + max_depth: usize, + max_children: usize, + out: &mut impl Write, +) -> io::Result<()> { + use disktree_scanner::{NodeFlags, NodeId, NodeKind as ScannerKind}; + + struct Frame { + id: NodeId, + depth: usize, + emitted_children: usize, + tail_bytes: u64, + tail_files: u64, + tail_modified: i64, + children: Vec, + next_idx: usize, + } + + let node_bytes = |id: NodeId| -> u64 { + let n = arena.node(id); + if options.apparent_size { + if n.is_dir() { + n.apparent_bytes + } else { + n.effective_apparent_bytes() + } + } else if n.is_dir() { + n.allocated_bytes + } else { + n.effective_allocated_bytes() + } + }; + + let make_frame = |id: NodeId, depth: usize| -> Frame { + let mut kids: Vec = Vec::new(); + for cid in arena.children(id) { + let child = arena.node(cid); + if !options.include_hidden && child.flags.has(NodeFlags::HIDDEN) { + continue; + } + let name = arena.name(cid); + if name.is_empty() + || name == "." + || name == ".." + || name.contains(['/', '\0']) + { + continue; + } + kids.push(cid); + } + kids.sort_unstable_by_key(|&b| std::cmp::Reverse(node_bytes(b))); + let mut tail_bytes = 0u64; + let mut tail_files = 0u64; + let mut tail_modified = 0i64; + if kids.len() > max_children { + for &cid in &kids[max_children..] { + let cn = arena.node(cid); + tail_bytes = tail_bytes.saturating_add(node_bytes(cid)); + tail_files = tail_files.saturating_add(cn.files); + if cn.modified > tail_modified { + tail_modified = cn.modified; + } + } + kids.truncate(max_children); + } + Frame { + id, + depth, + emitted_children: 0, + tail_bytes, + tail_files, + tail_modified, + children: kids, + next_idx: 0, + } + }; + + let mut frames = vec![make_frame(arena.root(), 0)]; + while let Some(top) = frames.last_mut() { + if top.next_idx < top.children.len() { + let child_id = top.children[top.next_idx]; + top.next_idx += 1; + let child = arena.node(child_id); + let child_depth = top.depth + 1; + let name = arena.name(child_id); + + if child.kind() == ScannerKind::Directory { + if options.max_depth.is_some_and(|limit| child_depth > limit) { + continue; + } + top.emitted_children += 1; + if child_depth >= max_depth { + // Emit this directory with one rolled-up summary leaf so + // its total size and file count stay 100% exact without + // streaming millions of deep leaf records over SSH. + let bytes = node_bytes(child_id); + let files = child.files; + let dir_children = if bytes > 0 || files > 0 { + let summary = Record( + "(deeper files)".to_owned(), + 1, + bytes, + files, + child.modified, + false, + 0, + ); + send(out, &summary)?; + 1 + } else { + 0 + }; + let dir_record = Record( + name.to_owned(), + 0, + 0, + 0, + child.modified, + child.read_error(), + dir_children, + ); + send(out, &dir_record)?; + } else { + frames.push(make_frame(child_id, child_depth)); + } + continue; + } + + top.emitted_children += 1; + let kind_code = match child.kind() { + ScannerKind::Directory => 0, + ScannerKind::File => 1, + ScannerKind::Symlink => 2, + ScannerKind::Other => 3, + }; + let bytes = node_bytes(child_id); + let files = u64::from(kind_code == 1); + let record = Record( + name.to_owned(), + kind_code, + bytes, + files, + child.modified, + child.read_error(), + 0, + ); + send(out, &record)?; + continue; + } + + let done = frames.pop().expect("checked non-empty"); + let mut count = done.emitted_children; + if done.tail_bytes > 0 || done.tail_files > 0 { + let tail_record = Record( + "(smaller entries)".to_owned(), + 1, + done.tail_bytes, + done.tail_files, + done.tail_modified, + false, + 0, + ); + send(out, &tail_record)?; + count += 1; + } + let an = arena.node(done.id); + let wire_name = if done.depth == 0 { + "root".to_owned() + } else { + arena.name(done.id).to_owned() + }; + let record = + Record(wire_name, 0, 0, 0, an.modified, an.read_error(), count); + send(out, &record)?; + } + + Ok(()) +} + /// Serialize a `disktree_scanner::TreeArena` in the postorder `Record` wire /// format expected by `read_snapshot` / `RemoteScan`. pub fn write_arena( @@ -571,6 +800,7 @@ fn serve_request_with_progress( home, platform: std::env::consts::OS.into(), identity: crate::identity::HostIdentity::current(), + helper_version: Some(env!("CARGO_PKG_VERSION").to_owned()), }, )?; out.flush()?; @@ -730,7 +960,7 @@ fn read_snapshot_with_progress( if marker == "done" { break; } - if marker == "stale" { + if marker == "stale" || marker == "partial" { if stack.len() != 1 { return Err(io::Error::other( "incomplete remote stale tree", @@ -743,10 +973,7 @@ fn read_snapshot_with_progress( header: header.clone(), tree: stale_tree, })); - progress.files = 0; - progress.dirs = 0; - progress.bytes = 0; - progress.errors = 0; + progress.stale_seq += 1; progress.updated = Some(Instant::now()); *shared.lock().expect("remote progress lock") = progress.clone(); @@ -931,6 +1158,7 @@ fn ssh_error(host: &str, details: &str, fallback: &io::Error) -> io::Error { #[derive(Debug)] pub struct RemoteJob { child: Arc>, + stdin: Arc>>, result: mpsc::Receiver>, progress: Shared, } @@ -1061,6 +1289,9 @@ impl RemoteJob { let mut stdin = child.stdin.take().expect("piped stdin"); let stdout = child.stdout.take().expect("piped stdout"); let child = Arc::new(Mutex::new(child)); + let stdin_shared: Arc>> = + Arc::new(Mutex::new(None)); + let stdin_worker = Arc::clone(&stdin_shared); let worker = child.clone(); let host = host.to_owned(); let (tx, result) = mpsc::channel(); @@ -1087,11 +1318,21 @@ impl RemoteJob { live_tree: true, stream_stale: true, force_refresh, + full_duplex: true, }, )?; + stdin.flush()?; + *stdin_worker + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) = + Some(stdin); decode(&mut input, &live) })(); - drop(stdin); + // Drop stdin cleanly so the remote helper observes EOF and exits. + let _ = stdin_worker + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + .take(); if response.is_err() { let _ = worker.lock().expect("SSH process lock").kill(); } @@ -1123,11 +1364,32 @@ impl RemoteJob { }); Ok(Self { child, + stdin: stdin_shared, result, progress, }) } + /// Send a full-duplex [`ConnectedCommand`] to the running remote helper + /// over its open `stdin` pipe. Returns `false` if the pipe is closed. + pub fn send_command(&self, cmd: &ConnectedCommand) -> bool { + let mut guard = self + .stdin + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let Some(stdin) = guard.as_mut() else { + return false; + }; + send(stdin, cmd).is_ok() && stdin.flush().is_ok() + } + + /// Preempt background walking on the remote host to refresh `path` first. + pub fn prioritize(&self, path: &Path) { + let _ = self.send_command(&ConnectedCommand::Prioritize { + path: path.to_path_buf(), + }); + } + pub fn progress(&self) -> Progress { self.progress.lock().expect("remote progress lock").clone() } @@ -1285,6 +1547,7 @@ mod tests { live_tree: true, stream_stale: false, force_refresh: false, + full_duplex: false, }; let bytes = serde_json::to_vec(&session).unwrap(); assert!(serde_json::from_slice::(&bytes).is_err()); @@ -1567,6 +1830,7 @@ mod tests { space: None, platform: platform.into(), identity: None, + helper_version: None, }; send(&mut data, &header).unwrap(); for name in [r"a\b", "c:d"] { @@ -1731,6 +1995,7 @@ mod tests { watch_disconnect: false, stream_stale: false, force_refresh: false, + full_duplex: false, }; let mut data = Vec::new(); serve_session(session, &mut data).unwrap(); @@ -1770,6 +2035,7 @@ mod tests { space: None, platform: std::env::consts::OS.into(), identity: None, + helper_version: None, }, ) .unwrap(); diff --git a/crates/disktree-core/src/remote_progress.rs b/crates/disktree-core/src/remote_progress.rs index 7c70334..2f9d443 100644 --- a/crates/disktree-core/src/remote_progress.rs +++ b/crates/disktree-core/src/remote_progress.rs @@ -40,9 +40,11 @@ pub struct Progress { pub auth_url: Option, pub updated: Option, pub preview: Option>, - /// Stale cached snapshot streamed from the remote host's own cache DB - /// while parallel revalidation runs on the remote host. + /// Stale or incremental partial snapshot streamed from the remote host + /// while parallel scanning/revalidation runs on the remote host. pub stale_snapshot: Option>, + /// Monotonic counter incremented each time a new `stale_snapshot` arrives. + pub stale_seq: u64, } /// Extract a Tailscale SSH check/login URL from SSH stderr diagnostics. diff --git a/crates/disktree-scanner/src/tree.rs b/crates/disktree-scanner/src/tree.rs index 520f1e9..f312378 100644 --- a/crates/disktree-scanner/src/tree.rs +++ b/crates/disktree-scanner/src/tree.rs @@ -543,7 +543,8 @@ impl TreeArena { } /// Replace the children and metadata of an existing node `target` with - /// the contents of `replacement`. + /// the contents of `replacement` via a single linear index-shift pass + /// (zero DFS stack, zero `id_map`, zero hash-table probing). pub fn replace_node_contents( &mut self, target: NodeId, @@ -563,49 +564,46 @@ impl TreeArena { } self.last_child[target.index()] = None; - let mut id_map: Vec> = - vec![None; replacement.nodes.len()]; - id_map[replacement.root().index()] = Some(target); - - let mut stack: Vec<(NodeId, NodeId)> = replacement - .children(replacement.root()) - .collect::>() - .into_iter() - .rev() - .map(|kid| (kid, target)) - .collect(); - let mut kids = Vec::new(); - - while let Some((src_id, dst_parent)) = stack.pop() { - let src = replacement.node(src_id); - let name_id = self.strings.intern(replacement.name(src_id)); - let dst_id = NodeId::from_index(self.nodes.len()) - .expect("arena node count fits in u32"); - let mut copy = *src; - copy.name = name_id; - copy.parent = Some(dst_parent); - copy.first_child = None; - copy.next_sibling = None; - self.nodes.push(copy); - self.last_child.push(None); - self.link_child(dst_parent, dst_id); - id_map[src_id.index()] = Some(dst_id); - - kids.clear(); - kids.extend(replacement.children(src_id)); - for &kid in kids.iter().rev() { - stack.push((kid, dst_id)); - } + if replacement.nodes.len() <= 1 { + return; } - for link in &replacement.hardlinks { - if let Some(mapped) = id_map[link.node.index()] { - self.hardlinks.push(HardlinkEntry { - node: mapped, - dev: link.dev, - ino: link.ino, - }); + // Index 0 in `replacement` maps onto `target`; indices 1..len append + // contiguously starting at `base_node`. + let base_node = self.nodes.len(); + let base_name = self.strings.append_raw(&replacement.strings); + let shift = |id: NodeId| { + if id == NodeId::ROOT { + target + } else { + NodeId::from_index(id.index() - 1 + base_node) + .expect("arena node count fits in u32") } + }; + + self.nodes[target.index()].first_child = + src_root.first_child.map(shift); + self.last_child[target.index()] = replacement.last_child[0].map(shift); + + self.nodes.reserve(replacement.nodes.len() - 1); + self.last_child.reserve(replacement.last_child.len() - 1); + for (i, src) in replacement.nodes.iter().enumerate().skip(1) { + let mut copy = *src; + copy.name = NameId(src.name.0 + base_name); + copy.parent = src.parent.map(shift); + copy.first_child = src.first_child.map(shift); + copy.next_sibling = src.next_sibling.map(shift); + self.nodes.push(copy); + self.last_child.push(replacement.last_child[i].map(shift)); + } + + self.hardlinks.reserve(replacement.hardlinks.len()); + for link in &replacement.hardlinks { + self.hardlinks.push(HardlinkEntry { + node: shift(link.node), + dev: link.dev, + ino: link.ino, + }); } }