A treemap for finding and removing what fills your disk, for Omarchy. Rust + GPUI.
Rust
app: show live treemap previews with stable sidebar progress
Tobi Lutke9b18b272ca3c
diff --git a/AGENTS.md b/AGENTS.mdindex 03416ac..0342b30 100644--- a/AGENTS.md+++ b/AGENTS.md@@ -114,6 +114,11 @@ and `cargo build --release` directly; CI runs the gate on both systems.Switching machines clears marks and identity. The Unix SSH helper streamsrecords and never retains the tree.+11. **A live overview is not an actionable tree.** Keep provisional,+ bounded display summaries separate from `Disktree::tree` and all path,+ mark and removal APIs. Only a complete scan may replace the real tree.+ Counters and sampled paths belong in fixed, monospace progress lanes.+## Where changes belong| change | where |diff --git a/README.md b/README.mdindex 6097a1a..bf9bc21 100644--- a/README.md+++ b/README.md@@ -219,11 +219,23 @@ compact identity index to count each inode once. The helper keeps noper-file identity table in negotiated desktop-de-duplication mode; linksoutside the chosen root cannot fill one. Older clients retain boundedhelper-side accounting for wire compatibility. A resource limit fails-explicitly instead of returning a partial tree. Symlinks are not followed and every nested mount is skipped, even a-bind mount or same-device subvolume. Select those as separate roots.--While indexing, the window shows live files, directories, measured bytes,-read errors, elapsed time and average throughput. Remote scans also show a+explicitly instead of returning a partial tree. Symlinks are not followed,+and every nested mount is skipped, even a bind mount or same-device+subvolume. Select those as separate roots.++While indexing, a quiet sidebar shows live files, directories, measured+bytes, read errors and elapsed time. Counters and paths use monospace type+in fixed lanes; changing values do not re-center or reflow the screen.+Narrow windows use a compact progress footer instead.++Ordinary local walks and current SSH helpers paint a **live top-level+overview** before the full tree arrives. These are measured contributions,+not complete directory sizes. Updates are limited to once a second, in+arrival order, with at most 128 named buckets plus an overflow bucket. The+preview is kept separate from the real tree: it cannot be navigated,+marked or removed. On completion the full, actionable treemap replaces it;+on error or cancellation the preview is discarded. The Windows file-table+fast path still waits for its complete tree. Remote scans also show asampled recent directory and connection / helper setup / indexing / treemapstages. Progress uses a single replaceable snapshot, not a growing eventqueue; path updates are throttled to five per second. There is no guesseddiff --git a/crates/disktree-app/src/state.rs b/crates/disktree-app/src/state.rsindex 5ad2871..efb9730 100644--- a/crates/disktree-app/src/state.rs+++ b/crates/disktree-app/src/state.rs@@ -330,6 +330,8 @@ pub struct Disktree {remote_disk: bool,pub remote_scan: Option<disktree_core::remote::RemoteScan>,pub remote_progress: disktree_core::remote_progress::Progress,+ pub scan_preview: Option<Arc<disktree_core::scan_preview::Preview>>,+ preview_updated: Option<Instant>,remote_platform: String,pub remote_identity: Option<disktree_core::identity::HostIdentity>,pub home: Option<PathBuf>,@@ -525,6 +527,8 @@ impl Disktree {remote,remote_disk,remote_scan: None,+ scan_preview: None,+ preview_updated: None,remote_progress: disktree_core::remote_progress::Progress::default(),remote_platform: String::new(),@@ -1104,6 +1108,7 @@ impl Disktree {/// were the whole one: a first scan leaves the panel saying it stopped,/// and a widening scan leaves the tree it started from on screen.pub fn cancel_scan(&mut self, cx: &mut Context<'_, Self>) {+ self.scan_preview = None;if self.remote_scan.take().is_some() {self.scan_epoch += 1;self.progress.cancelled = true;@@ -1241,6 +1246,8 @@ impl Disktree {self.scan_error = None;self.remote_progress =disktree_core::remote_progress::Progress::default();+ self.scan_preview = None;+ self.preview_updated = None;// A new scan starts at its root; where it was is one `<` away.if !self.crumbs.is_empty() {self.remember();@@ -1331,6 +1338,7 @@ impl Disktree {if let Some(scan) = &self.remote_scan {let outcome = scan.poll();self.remote_progress = scan.progress();+ self.scan_preview.clone_from(&self.remote_progress.preview);self.progress.files = self.remote_progress.files;self.progress.dirs = self.remote_progress.dirs;self.progress.bytes = self.remote_progress.bytes;@@ -1366,6 +1374,7 @@ impl Disktree {}}self.remote_scan = None;+ self.scan_preview = None;self.progress.finished = true;cx.notify();return false;@@ -1374,6 +1383,16 @@ impl Disktree {return false;};self.progress = scan.progress.snapshot();+ if self+ .preview_updated+ .is_none_or(|at| at.elapsed().as_secs() >= 1)+ {+ let preview = scan.progress.preview();+ if !preview.entries.is_empty() {+ self.scan_preview = Some(Arc::new(preview));+ self.preview_updated = Some(Instant::now());+ }+ }let Some(outcome) = scan.poll() else {cx.notify();return true;@@ -1415,6 +1434,7 @@ impl Disktree {Err(error) => self.scan_error = Some(error.to_string()),}self.scan = None;+ self.scan_preview = None;self.progress.finished = true;cx.notify();false@@ -1475,6 +1495,10 @@ impl Disktree {// ── navigation ──────────────────────────────────────────────────────+ pub const fn is_indexing(&self) -> bool {+ self.scan.is_some() || self.remote_scan.is_some()+ }+pub fn tree(&self) -> Option<&Node> {self.tree.as_deref()}diff --git a/crates/disktree-app/src/tests.rs b/crates/disktree-app/src/tests.rsindex 8bc9fe5..0520e4c 100644--- a/crates/disktree-app/src/tests.rs+++ b/crates/disktree-app/src/tests.rs@@ -102,6 +102,10 @@ fn remote_indexing_draws_live_activity_and_the_sampled_directory(update(&view, cx, |app, _| {app.tree = None;app.remote = Some("fixture-only".into());+ app.scan = Some(disktree_core::scan::ScanHandle::spawn(+ temp.path().into(),+ options(),+ ));app.scan_started = Some(std::time::Instant::now());app.progress.files = 1234;app.progress.bytes = 123_456;@@ -110,7 +114,7 @@ fn remote_indexing_draws_live_activity_and_the_sampled_directory(app.remote_progress.directory = Some(temp.path().join("junk/deeper"));});draw(cx);- assert!(cx.debug_bounds("scan-activity").is_some());+ assert!(cx.debug_bounds("indexing-progress").is_some());assert!(cx.debug_bounds("scan-directory").is_some());update(&view, cx, |app, _| {app.scan_error = Some("fixture scan failed".into());@@ -120,6 +124,94 @@ fn remote_indexing_draws_live_activity_and_the_sampled_directory(assert!(cx.debug_bounds("scan-reading").is_none());}+#[gpui_kit::test]+fn loading_values_and_paths_do_not_move_the_sidebar(cx: &mut TestAppContext) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ update(&view, cx, |app, _| {+ app.tree = None;+ app.scan = Some(disktree_core::scan::ScanHandle::spawn(+ temp.path().into(),+ options(),+ ));+ app.scan_preview =+ Some(std::sync::Arc::new(disktree_core::scan_preview::Preview {+ entries: vec![disktree_core::scan_preview::Entry {+ name: "junk".into(),+ bytes: 100,+ files: 1,+ }],+ directory: Some(temp.path().join("short")),+ }));+ });+ draw(cx);+ draw(cx);+ let panel = cx.debug_bounds("indexing-progress").unwrap();+ let files = cx.debug_bounds("indexing-files").unwrap();+ let path = cx.debug_bounds("scan-directory").unwrap();+ assert!(cx.debug_bounds("scan-preview").is_some());+ assert!(cx.debug_bounds("scan-reading").is_none());+ update(&view, cx, |app, _| {+ app.progress.files = 99_999_999;+ app.progress.bytes = u64::MAX / 2;+ app.remote = Some("fixture-only".into());+ app.remote_progress.directory = Some(PathBuf::from(+ "/a/very/long/directory/whose/text/must/not/move/the/layout",+ ));+ });+ draw(cx);+ assert_eq!(panel, cx.debug_bounds("indexing-progress").unwrap());+ assert_eq!(files, cx.debug_bounds("indexing-files").unwrap());+ assert_eq!(path, cx.debug_bounds("scan-directory").unwrap());+ let preview = cx.debug_bounds("scan-preview").unwrap();+ cx.simulate_click(preview.center(), gpui_kit::Modifiers::none());+ press(cx, "space");+ read(&view, cx, |app| {+ assert!(app.marks.is_empty());+ assert!(app.tree.is_none());+ });+ update(&view, cx, Disktree::cancel_scan);+ draw(cx);+ assert!(cx.debug_bounds("scan-preview").is_none());+ assert!(read(&view, cx, |app| app.scan_preview.is_none()));+}++#[gpui_kit::test]+fn narrow_indexing_keeps_a_preview_and_compact_progress_in_bounds(+ cx: &mut TestAppContext,+) {+ cx.update(gpui_omarchy::init);+ let temp = fixture();+ let (view, cx) = view_over(temp.path(), cx);+ update(&view, cx, |app, _| {+ app.tree = None;+ app.scan = Some(disktree_core::scan::ScanHandle::spawn(+ temp.path().into(),+ options(),+ ));+ app.scan_preview =+ Some(std::sync::Arc::new(disktree_core::scan_preview::Preview {+ entries: vec![disktree_core::scan_preview::Entry {+ name: "junk".into(),+ bytes: 100,+ files: 1,+ }],+ directory: None,+ }));+ });+ cx.simulate_resize(gpui_kit::size(px(900.), px(600.)));+ cx.update(|window, _| window.set_rem_size(px(28.)));+ draw(cx);+ draw(cx);+ let compact = cx.debug_bounds("indexing-compact").unwrap();+ assert!(compact.origin.x >= px(0.) && compact.right() <= px(900.));+ assert!(compact.origin.y >= px(0.) && compact.bottom() <= px(600.));+ let preview = cx.debug_bounds("scan-preview").unwrap();+ assert!(preview.size.height > px(50.), "{preview:?}");+ assert!(preview.bottom() <= compact.origin.y, "{preview:?}");+}+#[gpui_kit::test]fn startup_chooser_never_scans_before_explicit_acceptance(cx: &mut TestAppContext,diff --git a/crates/disktree-app/src/treemap_view.rs b/crates/disktree-app/src/treemap_view.rsindex 84b5605..68410e9 100644--- a/crates/disktree-app/src/treemap_view.rs+++ b/crates/disktree-app/src/treemap_view.rs@@ -65,6 +65,76 @@ pub fn mosaic(app: &Disktree,window: &Window,cx: &Context<'_, Disktree>,+) -> impl IntoElement {+ mosaic_inner(mosaic, app, window, cx, true)+}++/// A coarse, explicitly non-actionable picture of measured contributions.+pub fn preview(+ preview: &disktree_core::scan_preview::Preview,+ app: &Disktree,+ window: &Window,+ cx: &Context<'_, Disktree>,+) -> impl IntoElement {+ use disktree_core::tree::{Node, NodeKind};+ use disktree_core::treemap::{LayoutOptions, layout};+ let mut root = Node::directory("preview");+ // These are display buckets, never exposed through state.tree/path_at.+ for entry in &preview.entries {+ let mut node =+ Node::entry(entry.name.as_str(), NodeKind::File, entry.bytes);+ node.files = entry.files;+ root.children.push(node);+ }+ let area = app.treemap_size.get();+ let tiles = layout(+ &root,+ &[],+ Rect::new(0., 0., area.width.as_f32(), area.height.as_f32()),+ app.options.metric,+ &LayoutOptions {+ max_depth: 1,+ max_children: 129,+ ..LayoutOptions::default()+ },+ );+ let mut mosaic = Mosaic::default();+ for tile in tiles {+ let Some(node) = root.resolve(tile.crumbs()) else {+ continue;+ };+ mosaic.labels.push(Label {+ text: node.name.to_string(),+ rect: tile.rect,+ header: None,+ depth: 0,+ dim: false,+ marked: false,+ size_text: crate::widgets::short_value(node, app.options.metric),+ });+ mosaic.tiles.push(TileDeco {+ rect: tile.rect,+ depth: 0,+ category: Category::Other,+ age_bucket: None,+ reclaimable: false,+ filtered: Filtered::Shown,+ unreadable: false,+ marked: false,+ covered: false,+ hovered: false,+ selected: false,+ });+ }+ mosaic_inner(mosaic, app, window, cx, false)+}++fn mosaic_inner(+ mosaic: Mosaic,+ app: &Disktree,+ window: &Window,+ cx: &Context<'_, Disktree>,+ interactive: bool,) -> impl IntoElement {let theme = cx.omarchy().clone();let rem = window.rem_size();@@ -86,31 +156,31 @@ pub fn mosaic(div().id("disktree-treemap")- .debug_selector(|| "treemap".into())+ .debug_selector(move || if interactive { "treemap" } else { "scan-preview" }.into()).relative().flex_1().min_h_0().min_w_0().overflow_hidden().bg(theme.inset)- .on_hover(cx.listener(|this, hovered: &bool, _, cx| {- if !hovered {+ .on_hover(cx.listener(move |this, hovered: &bool, _, cx| {+ if interactive && !hovered {this.on_mouse_leave(cx);}}))- .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| {- this.on_mouse_move(event, cx);+ .on_mouse_move(cx.listener(move |this, event: &MouseMoveEvent, _, cx| {+ if interactive { this.on_mouse_move(event, cx); }}))// One listener for every button, because the interesting ones are not// the three the platform names: buttons 8 and 9 arrive as// `MouseButton::Navigate`, and a per-button registration would have// to be repeated for each.- .on_any_mouse_down(cx.listener(|this, event: &MouseDownEvent, _, cx| {- this.on_mouse_down(event, cx);+ .on_any_mouse_down(cx.listener(move |this, event: &MouseDownEvent, _, cx| {+ if interactive { this.on_mouse_down(event, cx); }})).on_scroll_wheel(cx.listener(- |this, event: &ScrollWheelEvent, _, cx| {- this.on_scroll_wheel(event, cx);+ move |this, event: &ScrollWheelEvent, _, cx| {+ if interactive { this.on_scroll_wheel(event, cx); }},)).child(diff --git a/crates/disktree-app/src/ui.rs b/crates/disktree-app/src/ui.rsindex 3f43a67..c21d026 100644--- a/crates/disktree-app/src/ui.rs+++ b/crates/disktree-app/src/ui.rs@@ -61,7 +61,6 @@ pub mod icon {pub const SM: Rems = Rems(0.75);pub const MD: Rems = Rems(0.875);- pub const LG: Rems = Rems(1.375);}/// Region and lane widths. Each is the comfortable default for its content at@@ -84,7 +83,9 @@ pub mod size {pub const SWATCH: Rems = Rems(0.625);/// A thin meter: share of the scan, the disk.pub const METER: Rems = Rems(0.3125);- /// The meter on the scanning panel.+ /// 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);/// The Size | Files | Age choice in the settings row.pub const RANKING_CHOICE: Rems = Rems(11.0);/// The review screen's summary column.diff --git a/crates/disktree-app/src/views.rs b/crates/disktree-app/src/views.rsindex b9ea289..32aedf5 100644--- a/crates/disktree-app/src/views.rs+++ b/crates/disktree-app/src/views.rs@@ -459,7 +459,8 @@ fn explore(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.- let panel = app.show_selection && width_rems >= PANEL_SHOWN_REMS;+ let panel = (app.show_selection || app.is_indexing())+ && width_rems >= PANEL_SHOWN_REMS;if panel && let Some(path) = selection_checkout(app) {app.ensure_git(&path, cx);}@@ -467,7 +468,13 @@ fn explore(let viewport = if app.tree().is_none() {// The first walk of a home directory takes long enough that an// empty viewport would look broken; count the work instead.- scanning_panel(app, &theme, cx).into_any_element()+ if app.scan_error.is_none()+ && let Some(preview) = &app.scan_preview+ {+ treemap_view::preview(preview, app, window, cx).into_any_element()+ } else {+ scanning_panel(app, &theme, cx).into_any_element()+ }} else {treemap_view::mosaic(mosaic, app, window, cx).into_any_element()};@@ -517,6 +524,12 @@ fn explore().children(panel.then(|| side_panel(app, &theme, cx))),)+ .children((app.is_indexing() && !panel).then(|| {+ div()+ .px(space::LG)+ .py(space::SM)+ .child(indexing_compact(app, &theme, cx))+ })).child(key_bar(app, &theme, cx))}@@ -1332,6 +1345,12 @@ fn trail_and_legend(/// What the whole scan found, as one quiet line; unreadable paths are/// flagged in the warning colour when there are any.fn scan_totals(app: &Disktree, theme: &Theme) -> Div {+ if app.is_indexing() {+ return div()+ .text_size(text::CAPTION)+ .text_color(theme.secondary)+ .child("Live overview · incomplete · top-level contributions");+ }let tree = app.tree();let bytes = tree.map_or(app.progress.bytes, |node| node.bytes);let files = tree.map_or(app.progress.files, |node| node.files);@@ -1454,7 +1473,9 @@ fn side_panel(.border_color(theme.divider()).bg(theme.surface).child(handle)- .child(selection_section(app, theme, cx))+ .child(if app.is_indexing() {+ indexing_progress(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.@@ -2383,11 +2404,7 @@ fn key_bar(app: &Disktree, theme: &Theme, cx: &App) -> Div {);}let scan = if app.scan.is_some() || app.remote_scan.is_some() {- format!(- "scanning \u{00b7} {} entries \u{00b7} {}",- widgets::human_count(app.progress.files),- human_bytes(app.progress.bytes)- )+ "Indexing · incomplete".to_string()} else if app.progress.cancelled {format!("scan cancelled \u{00b7} {} entries \u{00b7} r scans again",@@ -2418,162 +2435,211 @@ fn scanning_panel(theme: &Theme,cx: &Context<'_, Disktree>,) -> Div {- if let Some(error) = &app.scan_error {- return div()- .debug_selector(|| "scan-error".into())- .flex()- .flex_col()- .flex_1()- .min_h_0()- .items_center()- .justify_center()- .gap(space::LG)- .bg(theme.inset)- .child(- gpui_omarchy::icon(gpui_omarchy::IconName::X)- .size(icon::LG)- .text_color(theme.danger),- )- .child(- div()- .text_size(text::TITLE)- .text_color(theme.bright)- .child("Scan failed"),- )- .child(- div()- .max_w(size::HELP)- .p(space::MD)- .border_1()- .border_color(theme.danger)- .text_color(theme.danger)- .text_size(text::BODY)- .child(error.clone()),- )- .children(app.remote_progress.directory.as_ref().map(|path| {- div()- .max_w(size::HELP)- .truncate()- .text_size(text::CAPTION)- .text_color(theme.secondary)- .child(format!("Last directory: {}", path.display()))- }))- .child(widgets::hint("r", "retry scan", cx));- }- let progress = &app.progress;- let cancelled =- app.scan.is_none() && app.remote_scan.is_none() && progress.cancelled;+ let error = app.scan_error.as_ref();div()- .debug_selector(|| "scan-reading".into())+ .debug_selector(move || {+ if error.is_some() {+ "scan-error"+ } else {+ "scan-reading"+ }+ .into()+ }).flex().flex_col().flex_1().min_h_0()- .items_center()- .justify_center()- .gap(space::LG)+ .items_start()+ .justify_start()+ .p(space::XL)+ .gap(space::MD).bg(theme.inset)- .when(!cancelled, |panel| {+ .text_size(text::BODY)+ .text_color(theme.secondary)+ .child(if error.is_some() {+ "Scan failed"+ } else if app.progress.cancelled {+ "Indexing stopped"+ } else {+ "Waiting for the first indexed entries…"+ })+ .children(error.map(|error| {+ div()+ .max_w(size::HELP)+ .text_color(theme.danger)+ .child(error.clone())+ }))+ .when(!app.is_indexing(), |panel| {panel.child(- gpui_omarchy::icon(gpui_omarchy::IconName::Loader)- .size(icon::LG)- .text_color(theme.accent),+ button("scan-again", "Scan again", ButtonVariant::Outline, cx)+ .on_click(cx.listener(|this, _, window, cx| {+ this.start_scan(cx);+ window.focus(&this.focus, cx);+ })),)})+}++/// Narrow windows retain the essential counters in a compact footer.+fn indexing_compact(+ app: &Disktree,+ theme: &Theme,+ cx: &Context<'_, Disktree>,+) -> Div {+ div()+ .debug_selector(|| "indexing-compact".into())+ .flex()+ .items_center()+ .gap(space::MD)+ .min_w_0()+ .text_size(text::BODY).child(div()- .text_size(text::TITLE)- .font_weight(FontWeight::SEMIBOLD)- .text_color(theme.bright)- .child(if cancelled {- format!("Stopped reading {}", widgets::display_root(app))- } else if app.remote.is_some() {- format!("{} · {}", app.remote_progress.stage.label(),- widgets::display_root(app))- } else {- format!("Indexing {}", widgets::display_root(app))- }),+ .flex_1()+ .min_w_0()+ .truncate()+ .font_family(theme.mono_font.clone())+ .child(format!(+ "{} files",+ widgets::human_count(app.progress.files)+ )),).child(div()- .flex()- .flex_row()- .gap(space::XL)- .child(widgets::stat(- "files",- widgets::human_count(progress.files),- cx,- ))- .child(widgets::stat("directories", widgets::human_count(progress.dirs), cx))- .child(widgets::stat("measured", human_bytes(progress.bytes), cx))- .child(widgets::stat_colored(- "unreadable",- widgets::human_count(progress.errors),- if progress.errors > 0 {- theme.warning- } else {- theme.secondary- },- cx,- )),+ .flex_1()+ .min_w_0()+ .truncate()+ .font_family(theme.mono_font.clone())+ .child(format!("{} measured", human_bytes(app.progress.bytes))),)- .when(!cancelled, |panel| {- panel.child(+ .child(+ button("cancel-scan", "Stop", ButtonVariant::Outline, cx).on_click(+ cx.listener(|this, _, window, cx| {+ this.cancel_scan(cx);+ window.focus(&this.focus, cx);+ }),+ ),+ )+}++/// Progress has one owner. Stable rows and mono values prevent digit,+// unit and path changes from pushing the rest of the screen around.+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(|| "scan-activity".into())- .text_size(text::BODY)- .text_color(theme.accent)- .child(scan_activity(app)),+ .debug_selector(move || id.into())+ .w(size::PROGRESS_VALUE)+ .text_right()+ .font_family(theme.mono_font.clone())+ .child(value),)+ };+ let path = if app.remote.is_some() {+ app.remote_progress.directory.as_ref()+ } else {+ app.scan_preview+ .as_ref()+ .and_then(|preview| preview.directory.as_ref())+ };+ let full_path = path.map_or_else(+ || "Directory not reported yet".into(),+ |path| path.display().to_string(),+ );+ let mut parts = path+ .map(|path| {+ path.components()+ .rev()+ .take(3)+ .map(|part| part.as_os_str().to_string_lossy().into_owned())+ .collect::<Vec<_>>()})- .children(app.remote_progress.directory.as_ref().map(|path| {- div().debug_selector(|| "scan-directory".into())- .max_w(size::HELP).min_w_0().truncate()- .text_size(text::CAPTION).text_color(theme.secondary)- .child(format!("Recent directory: {}", path.display()))- }))+ .unwrap_or_default();+ parts.reverse();+ let short_path = if path.is_some_and(|path| path.components().count() > 3) {+ format!("…/{}", parts.join("/"))+ } else {+ full_path.clone()+ };+ 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("Indexing", cx))+ .child(div().h(size::PROGRESS_ROW).truncate().child(+ if app.remote.is_some() {+ app.remote_progress.stage.label()+ } else {+ "Reading this computer"+ },+ ))+ .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()- .text_size(text::BODY)+ .h(size::PROGRESS_ROW)+ .text_size(text::CAPTION).text_color(theme.secondary)- .child(if cancelled {- "Nothing is shown from a scan that did not finish."- } else {- "Total unknown until indexing finishes. Results stream live."- }),+ .child("Recent directory"),)- // A failed scan has nothing left to cancel either.- .child(if app.scan.is_none() && app.remote_scan.is_none() {- button("scan-again", "Scan again", ButtonVariant::Outline, cx)- .on_click(cx.listener(|this, _, window, cx| {- this.start_scan(cx);- window.focus(&this.focus, cx);- }))- } else {- button("cancel-scan", "Cancel", ButtonVariant::Outline, cx)+ .child(with_tooltip(+ div()+ .id("indexing-directory")+ .debug_selector(|| "scan-directory".into())+ .h(size::PROGRESS_ROW)+ .min_w_0()+ .truncate()+ .font_family(theme.mono_font.clone())+ .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 scan_activity(app: &Disktree) -> String {- let elapsed = app- .scan_started- .map_or(0.0, |start| start.elapsed().as_secs_f64());- let phase = (elapsed * 8.0) as usize % 4;- let spinner = ["◐", "◓", "◑", "◒"][phase];- let rate = app.progress.files as f64 / elapsed.max(1.0);- let quiet = app- .remote_progress- .updated- .map_or(0, |at| at.elapsed().as_secs());- if app.remote.is_some() && quiet >= 5 {- format!("{spinner} {elapsed:.0}s elapsed · no new entries for {quiet}s")- } else {- format!("{spinner} {elapsed:.0}s elapsed · {rate:.0} files/s avg")- }+ })),+ )}fn find_field(app: &Disktree, theme: &Theme) -> Div {diff --git a/crates/disktree-app/src/widgets.rs b/crates/disktree-app/src/widgets.rsindex 905c04f..cc2927b 100644--- a/crates/disktree-app/src/widgets.rs+++ b/crates/disktree-app/src/widgets.rs@@ -15,13 +15,6 @@ use gpui_omarchy::{ActiveTheme, Status};use crate::ui::{space, text};-use crate::state::Disktree;--/// The scanned root, shortened to `~` where it is the home directory.-pub fn display_root(app: &Disktree) -> String {- crate::marks::display_path(&app.root_path, app.home.as_deref())-}-/// File counts, which is what a directory count is too.pub fn human_count(value: u64) -> String {disktree_core::size::human_count(value)diff --git a/crates/disktree-core/src/lib.rs b/crates/disktree-core/src/lib.rsindex 5b020a1..0f58c7b 100644--- a/crates/disktree-core/src/lib.rs+++ b/crates/disktree-core/src/lib.rs@@ -23,6 +23,7 @@ pub mod remote_progress;mod remote_walk;pub mod removal;pub mod scan;+pub mod scan_preview;pub mod scan_threads;pub mod size;pub mod space;diff --git a/crates/disktree-core/src/remote.rs b/crates/disktree-core/src/remote.rsindex 07d3edd..27da007 100644--- a/crates/disktree-core/src/remote.rs+++ b/crates/disktree-core/src/remote.rs@@ -64,6 +64,8 @@ pub struct SessionRequest {pub live_progress: bool,#[serde(default)]pub client_dedup: bool,+ #[serde(default)]+ pub live_tree: bool,}/// The target's root candidates, without walking or probing any of them.@@ -124,6 +126,7 @@ pub(crate) struct Record(#[derive(Deserialize)]struct Control {directory: Option<PathBuf>,+ enter: Option<String>,entry: Option<Record>,link: Option<(u64, u64)>,}@@ -191,6 +194,7 @@ pub fn serve_session(out,session.live_progress,session.client_dedup,+ session.live_tree,),Operation::Discover { discover_version } => {if discover_version != VERSION {@@ -215,7 +219,7 @@ pub fn serve_session(/// Scan a decoded request. The standalone helper supervises its lifetime.pub fn serve_request(request: Request, out: &mut impl Write) -> io::Result<()> {- serve_request_with_progress(request, out, false, false)+ serve_request_with_progress(request, out, false, false, false)}fn serve_request_with_progress(@@ -223,8 +227,9 @@ fn serve_request_with_progress(out: &mut impl Write,live_progress: bool,client_dedup: bool,+ live_tree: bool,) -> io::Result<()> {- let _ = (live_progress, client_dedup); // Only Unix has the streaming walker.+ let _ = (live_progress, client_dedup, live_tree); // Only Unix has the streaming walker.let home = std::env::home_dir();let root = request.root@@ -259,6 +264,7 @@ fn serve_request_with_progress(out,live_progress,client_dedup,+ live_tree,)?;#[cfg(not(unix))]write_node(out, &scan(&root, request.options)?)?;@@ -320,6 +326,9 @@ fn read_snapshot_with_progress(let mut stack = Vec::<Node>::new();let mut line = String::new();let seen = crate::tree::Seen::new();+ let mut preview = crate::scan_preview::Builder::default();+ let mut ancestors = Vec::<String>::new();+ let mut preview_published = Instant::now();loop {receive_line(input, &mut line)?;let text = line.trim_start();@@ -330,6 +339,19 @@ fn read_snapshot_with_progress(} else if text.starts_with('{') {let control: Control =serde_json::from_str(text).map_err(json_error)?;+ if let Some(name) = control.enter {+ if !(name.is_empty() && ancestors.is_empty())+ && (name.is_empty()+ || name == "."+ || name == ".."+ || name.contains(['/', '\0'])+ || (cfg!(windows) && name.contains(['\\', ':'])))+ {+ return Err(io::Error::other("invalid preview directory"));+ }+ ancestors.push(name);+ continue;+ }if let Some(directory) = control.directory {progress.directory = Some(directory);progress.updated = Some(Instant::now());@@ -401,6 +423,18 @@ fn read_snapshot_with_progress(node.read_error = read_error;node.children = children;stack.push(node);+ let mut preview_changed = false;+ if !ancestors.is_empty() {+ if kind.is_dir() {+ ancestors.pop();+ } else {+ preview.add(ancestors.get(1).map(String::as_str), bytes, files);+ if progress.preview.is_none() {+ progress.preview = Some(Arc::new(preview.snapshot()));+ preview_changed = true;+ }+ }+ }progress.dirs += u64::from(kind.is_dir());// Legacy helpers include direct totals in directory records too.// Count each leaf once, never charge its parent's totals again.@@ -409,12 +443,21 @@ fn read_snapshot_with_progress(progress.bytes += bytes;}progress.errors += u64::from(read_error);- if published.elapsed() >= INTERVAL {+ if published.elapsed() >= INTERVAL || preview_changed {+ if progress.preview.is_some()+ && preview_published.elapsed().as_secs() >= 1+ {+ progress.preview = Some(Arc::new(preview.snapshot()));+ preview_published = Instant::now();+ }progress.updated = Some(Instant::now());*shared.lock().expect("remote progress lock") = progress.clone();published = Instant::now();}}+ if progress.preview.is_some() {+ progress.preview = Some(Arc::new(preview.snapshot()));+ }progress.stage = Stage::Finalizing;progress.updated = Some(Instant::now());*shared.lock().expect("remote progress lock") = progress;@@ -630,6 +673,7 @@ impl<T: Send + 'static> RemoteJob<T> {watch_disconnect: true,live_progress: true,client_dedup: true,+ live_tree: true,},)?;decode(&mut input, &live)@@ -773,6 +817,7 @@ mod tests {watch_disconnect: true,live_progress: true,client_dedup: true,+ live_tree: true,};let bytes = serde_json::to_vec(&session).unwrap();assert!(serde_json::from_slice::<Request>(&bytes).is_err());@@ -1103,6 +1148,7 @@ mod tests {read_snapshot_with_progress(&mut BufReader::new(input), &live)});output.write_all(header).unwrap();+ send(&mut output, &serde_json::json!({"enter": ""})).unwrap();output.write_all(leaf).unwrap();send(&mut output, &serde_json::json!({"directory": dir.path()})).unwrap();@@ -1112,6 +1158,10 @@ mod tests {if progress.files == 1 {assert_eq!(progress.bytes, 5);assert_eq!(progress.stage, Stage::Indexing);+ let preview =+ progress.preview.as_ref().expect("preview before done");+ assert_eq!(preview.entries[0].bytes, 5);+ assert_eq!(preview.entries[0].name, "Files in root");assert!(!worker.is_finished());break;}@@ -1133,6 +1183,8 @@ mod tests {std::fs::hard_link(root.join("first"), root.join("alias")).unwrap();std::fs::hard_link(root.join("first"), dir.path().join("outside")).unwrap();+ std::fs::create_dir_all(root.join("nested/deeper")).unwrap();+ std::fs::write(root.join("nested/deeper/file"), b"world").unwrap();for dedup in [true, false] {let session = SessionRequest {operation: Operation::Scan(Request {@@ -1146,13 +1198,29 @@ mod tests {}),live_progress: true,client_dedup: true,+ live_tree: true,watch_disconnect: false,};let mut data = Vec::new();serve_session(session, &mut data).unwrap();- let snapshot = read_snapshot(&mut data.as_slice()).unwrap();- assert_eq!(snapshot.tree.bytes, if dedup { 5 } else { 10 });- assert_eq!(snapshot.tree.files, 2);+ let shared = Shared::default();+ let snapshot =+ read_snapshot_with_progress(&mut data.as_slice(), &shared)+ .unwrap();+ assert_eq!(snapshot.tree.bytes, if dedup { 10 } else { 15 });+ assert_eq!(snapshot.tree.files, 3);+ let preview = shared.lock().unwrap().preview.clone().unwrap();+ let nested = preview+ .entries+ .iter()+ .find(|entry| entry.name == "nested")+ .unwrap();+ assert_eq!(nested.bytes, 5);+ assert_eq!(nested.files, 1);+ assert_eq!(+ preview.entries.iter().map(|e| e.bytes).sum::<u64>(),+ snapshot.tree.bytes+ );}}diff --git a/crates/disktree-core/src/remote_progress.rs b/crates/disktree-core/src/remote_progress.rsindex 8a78fa8..7389d22 100644--- a/crates/disktree-core/src/remote_progress.rs+++ b/crates/disktree-core/src/remote_progress.rs@@ -36,6 +36,7 @@ pub struct Progress {pub errors: u64,pub directory: Option<PathBuf>,pub updated: Option<Instant>,+ pub preview: Option<Arc<crate::scan_preview::Preview>>,}/// Cap both wire heartbeats and UI publications at five per second.diff --git a/crates/disktree-core/src/remote_walk.rs b/crates/disktree-core/src/remote_walk.rsindex 7193b79..8bbe425 100644--- a/crates/disktree-core/src/remote_walk.rs+++ b/crates/disktree-core/src/remote_walk.rs@@ -36,6 +36,7 @@ pub fn stream(out: &mut impl Write,live_progress: bool,client_dedup: bool,+ live_tree: bool,) -> io::Result<()> {if options.follow_links || !options.one_filesystem {return Err(io::Error::other(@@ -56,6 +57,7 @@ pub fn stream(out,live_progress,client_dedup,+ live_tree,)}@@ -66,7 +68,11 @@ fn stream_with_boundaries(out: &mut impl Write,live_progress: bool,client_dedup: bool,+ live_tree: bool,) -> io::Result<()> {+ if live_tree {+ send(out, &serde_json::json!({"enter": ""}))?;+ }let device = fs::metadata(root)?.dev();let mut frames = vec![Frame::open(root, "root".into())];// Only the legacy wire mode needs a table. Modern sessions emit each@@ -125,6 +131,9 @@ fn stream_with_boundaries(}frames.last_mut().expect("parent exists").record.6 += 1;directory.clone_from(&path);+ if live_tree {+ send(out, &serde_json::json!({"enter": name}))?;+ }frames.push(Frame::open(&path, name.to_owned()));continue;}@@ -209,6 +218,7 @@ mod tests {&mut bytes,false,false,+ false,).unwrap();bytes@@ -302,8 +312,15 @@ mod tests {},] {assert!(- stream(dir.path(), &options, &mut Vec::new(), false, false)- .is_err()+ stream(+ dir.path(),+ &options,+ &mut Vec::new(),+ false,+ false,+ false+ )+ .is_err());}}diff --git a/crates/disktree-core/src/scan.rs b/crates/disktree-core/src/scan.rsindex 13202f7..5ffe81a 100644--- a/crates/disktree-core/src/scan.rs+++ b/crates/disktree-core/src/scan.rs@@ -95,6 +95,8 @@ pub struct ScanProgress {finished: AtomicBool,cancelled: AtomicBool,messages: Mutex<Vec<String>>,+ preview_root: OnceLock<PathBuf>,+ preview: Mutex<crate::scan_preview::Builder>,pub(crate) threads: AtomicUsize,pub(crate) threads_settled: AtomicBool,pub(crate) thread_tuning_complete: AtomicBool,@@ -122,6 +124,26 @@ pub struct ScanSnapshot {}impl ScanProgress {+ pub fn preview(&self) -> crate::scan_preview::Preview {+ lock(&self.preview).snapshot()+ }++ fn preview_add(&self, path: &Path, bytes: u64, files: u64) {+ let Some(root) = self.preview_root.get() else {+ return;+ };+ let Ok(below) = path.strip_prefix(root) else {+ return;+ };+ let name = below+ .components()+ .next()+ .map(|part| part.as_os_str().to_string_lossy());+ let mut preview = lock(&self.preview);+ preview.add(name.as_deref(), bytes, files);+ preview.directory(path);+ }+pub(crate) fn entries(&self) -> u64 {self.files.load(Ordering::Relaxed) + self.dirs.load(Ordering::Relaxed)}@@ -825,6 +847,7 @@ impl PendingDir {}fn scan_blocking(root: &Path, context: &Arc<WalkContext>) -> io::Result<Node> {+ let _ = context.progress.preview_root.set(root.to_path_buf());let owned = fixed_pool(context.options.threads)?;let pool = owned.as_ref().unwrap_or_else(|| &WALK_POOL);scan_on_pool(root, context, pool)@@ -1021,7 +1044,8 @@ impl Tally {self.bytes += node.bytes;}- fn flush(&mut self, progress: &ScanProgress) {+ fn flush(&mut self, progress: &ScanProgress, path: &Path) {+ progress.preview_add(path, self.bytes, self.files);progress.add(self.files, self.dirs, self.bytes);*self = Self::default();}@@ -1103,7 +1127,7 @@ fn walk(dir: &Arc<PendingDir>, context: &WalkContext) -> Vec<Arc<PendingDir>> {Classified::Skipped => {}}if tally.files + tally.dirs >= TALLY_EVERY {- tally.flush(&context.progress);+ tally.flush(&context.progress, &dir.path);}}Err(error) => {@@ -1117,7 +1141,7 @@ fn walk(dir: &Arc<PendingDir>, context: &WalkContext) -> Vec<Arc<PendingDir>> {dir.read_error.store(true, Ordering::Relaxed);}}- tally.flush(&context.progress);+ tally.flush(&context.progress, &dir.path);// A depth-limited scan still measures what is directly in the directory,// it just does not descend further.@@ -1779,6 +1803,23 @@ mod tests {assert!(snapshot.finished);assert_eq!(snapshot.files, 2);assert_eq!(snapshot.errors, 0);+ let preview = handle.progress.preview();+ assert!(+ preview+ .entries+ .iter()+ .any(|e| e.name == "a" && e.bytes == 1024)+ );+ assert!(+ preview+ .entries+ .iter()+ .any(|e| e.name == "b" && e.bytes == 2048)+ );+ assert_eq!(+ preview.entries.iter().map(|e| e.bytes).sum::<u64>(),+ tree.bytes+ );}#[test]diff --git a/crates/disktree-core/src/scan_preview.rs b/crates/disktree-core/src/scan_preview.rsnew file mode 100644index 0000000..0030daa--- /dev/null+++ b/crates/disktree-core/src/scan_preview.rs@@ -0,0 +1,85 @@+//! Bounded, non-actionable overview; never a replacement filesystem tree.+use rustc_hash::FxHashMap;++/// A measured contribution, not the total size of an unfinished directory.+#[derive(Clone, Debug, Default)]+pub struct Entry {+ pub name: String,+ pub bytes: u64,+ pub files: u64,+}++#[derive(Clone, Debug, Default)]+pub struct Preview {+ pub entries: Vec<Entry>,+ pub directory: Option<std::path::PathBuf>,+}++/// Keep top-level arrival order, rather than re-ranking the view every tick.+/// Extra names share one overflow bucket; no tree or per-file copy is kept.+#[derive(Debug, Default)]+pub(crate) struct Builder {+ index: FxHashMap<String, usize>,+ entries: Vec<Entry>,+ directory: Option<std::path::PathBuf>,+}++impl Builder {+ pub(crate) fn add(&mut self, name: Option<&str>, bytes: u64, files: u64) {+ const LIMIT: usize = 128;+ let key = name.unwrap_or("");+ let index = if let Some(index) = self.index.get(key) {+ *index+ } else if self.index.len() < LIMIT {+ let index = self.entries.len();+ self.index.insert(key.into(), index);+ self.entries.push(Entry {+ name: name.unwrap_or("Files in root").into(),+ ..Entry::default()+ });+ index+ } else {+ if self.entries.len() == LIMIT {+ self.entries.push(Entry {+ name: "Other indexed paths".into(),+ ..Entry::default()+ });+ }+ LIMIT+ };+ let entry = &mut self.entries[index];+ entry.bytes = entry.bytes.saturating_add(bytes);+ entry.files = entry.files.saturating_add(files);+ }++ pub(crate) fn directory(&mut self, path: &std::path::Path) {+ path.clone_into(self.directory.get_or_insert_default());+ }++ pub(crate) fn snapshot(&self) -> Preview {+ Preview {+ entries: self.entries.clone(),+ directory: self.directory.clone(),+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn bounded_buckets_preserve_all_weight_and_arrival_order() {+ let mut builder = Builder::default();+ for index in 0..1000 {+ builder.add(Some(&format!("dir-{index}")), 2, 1);+ }+ builder.add(Some("dir-0"), 3, 4);+ let preview = builder.snapshot();+ assert_eq!(preview.entries.len(), 129);+ assert_eq!(preview.entries[0].name, "dir-0");+ assert_eq!(preview.entries[0].bytes, 5);+ assert_eq!(preview.entries.iter().map(|e| e.bytes).sum::<u64>(), 2003);+ assert_eq!(preview.entries.iter().map(|e| e.files).sum::<u64>(), 1004);+ }+}diff --git a/crates/disktree-scan/tests/stdio.rs b/crates/disktree-scan/tests/stdio.rsindex aed13b1..b29f4c7 100644--- a/crates/disktree-scan/tests/stdio.rs+++ b/crates/disktree-scan/tests/stdio.rs@@ -201,7 +201,7 @@ fn assert_bounded_stream_memory(root: &std::path::Path) {&serde_json::json!({"root": root, "disk": false,"options": ScanOptions::default(), "watch_disconnect": true,- "live_progress": true, "client_dedup": true,+ "live_progress": true, "client_dedup": true, "live_tree": true,}),).unwrap();