Skip to content

A high-performance Android storage analyzer that bypasses MTP using a native C++ daemon, a Rust TCP bridge, and a React Treemap UI.

Rust

Add bounded largest-files view from completed scans (#68)

Vishnu Srivatsava67a6514e042e
diff --git a/docs/largest-files.md b/docs/largest-files.md
new file mode 100644
index 0000000..e190b3b
--- /dev/null
+++ b/docs/largest-files.md
@@ -0,0 +1,72 @@
+# Largest files from a completed scan
+
+Choose **Largest files** in the results to see the top 10, 25 (default), 50 or
+100 counted regular files across all scanned directories. Sizes and paths come
+from that scan, not a fresh device traversal. The global storage totals remain
+unchanged when switching views. Zero-byte counted files are included; excluded
+entries, special files and uncounted duplicate hard links are not ranked.
+
+**Show folder** opens the file's parent in the storage map. **Delete** uses the
+existing exact-path confirmation and generation/revision-scoped node ID flow.
+Root scans remain read-only. Names containing line-protocol delimiters remain
+visible with exact paths but cannot be deleted through the app. Device changes
+outside SocketSweep require a rescan; a failed or partial deletion invalidates
+the local snapshot through the existing deletion handling.
+
+## Ownership and bounds
+
+`Catalog::largest_json` traverses only reachable catalog children. Removing a
+directory makes its entire subtree unreachable, even though descendant records
+remain in the underlying scan allocation. A standard-library `BinaryHeap` holds
+at most K ranking keys; no whole-tree clone, sort or second persistent index is
+needed. Results sort by descending size, then exact file name and scan node ID,
+matching directory ordering. IDs break ties between equal names in different
+folders. Names are not normalized.
+
+The backend rejects limits outside 1–100 and stale scan generations/revisions.
+Ranking takes O(N log K) time and O(K + depth) auxiliary ranking/traversal memory.
+The decoder already bounds depth and individual paths. Only selected paths and
+node summaries are serialized. The existing 1 MiB response cap still applies:
+if many long paths exceed it, the query fails and asks for a smaller limit.
+The limit selector remains available after an error. Frontend queries hide old
+rows immediately when their scan revision or limit changes and ignore late
+responses after replacement or unmount.
+
+This is an adaptation of the largest-files idea in Shanmukh's fork at
+[`d677b530`](https://github.com/ksaishanmukh/SocketSweep/tree/d677b530e00dec75c305fc56318720aa8c161692)
+(commits `670736d`, `5e442e2`), implemented on SocketSweep's existing host catalog.
+No device daemon changes, dependencies or new ADB operations are needed.
+
+## Validation
+
+Rust tests compare every supported K against an exhaustive reference sort on
+1,040 counted files, including nested files and size/name/ID ties. Additional
+fixtures cover empty scans, zero-byte files, exact Unicode/whitespace/CR/LF
+paths, root read-only flags, invalid limits/scopes, deep-path response limits,
+removed subtrees and snapshot invalidation when a file is missing at deletion.
+
+The built frontend replay uses mocked IPC in headless Chrome. It covers limit
+changes with delayed old responses, query errors/retry, exact displayed paths,
+ID-only deletion and revision refresh in both views, read-only deletion controls,
+folder navigation and no additional scan commands. Existing paging, confirmation,
+shutdown, device selection, toast and diagnostic checks remain in the replay.
+
+Run the host-only release benchmark with:
+
+```sh
+python3 tests/benchmark_largest_files.py
+```
+
+On an Apple M2 (arm64 macOS), a synthetic scan of **250,000 files across 32 folders** produced an
+**18,510-byte** top-100 response. Across three processes, each with 31 queries,
+process medians were **4.81–4.91 ms**, and p95 values were **6.65–7.28 ms**.
+Process peak RSS was **48.37–48.40 MB** for loading the catalog alone and
+**48.78–48.82 MB** for loading plus repeated queries (decimal MB). These RSS
+measurements include decoder/catalog construction and allocator noise; they do
+not isolate query allocations or demonstrate a memory reduction. The hard
+100-key selection bound follows from the production heap algorithm.
+
+No native app or physical device was used for these automated checks. To check
+on a connected device yourself, run `npm run tauri dev`, scan normally, switch
+views and limits, use Show folder, then confirm a deletion only on a disposable
+file. Repeat with a root read-only scan if supported by your phone.
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 3bd4c19..af05bbc 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -527,6 +527,15 @@ fn get_scan_view(
.view_json(&generation, revision, node_id, cursor)
}
+#[tauri::command(async)]
+fn get_largest_files(generation: String, revision: u32, limit: usize) -> Result<String, String> {
+ let store = SCAN_STORE.lock().map_err(|_| "Scan state is unavailable")?;
+ store
+ .as_ref()
+ .ok_or("Scan is unavailable; rescan required")?
+ .largest_json(&generation, revision, limit)
+}
+
#[tauri::command(async)]
fn get_scan_node(generation: String, revision: u32, node_id: u32) -> Result<String, String> {
let store = SCAN_STORE.lock().map_err(|_| "Scan state is unavailable")?;
@@ -570,6 +579,7 @@ pub fn run() {
delete_item,
get_scan_view,
get_scan_node,
+ get_largest_files,
])
.build(tauri::generate_context!())
.expect("error while building tauri application")
diff --git a/src-tauri/src/scan_store.rs b/src-tauri/src/scan_store.rs
index 2e06609..af630cc 100644
--- a/src-tauri/src/scan_store.rs
+++ b/src-tauri/src/scan_store.rs
@@ -3,13 +3,14 @@
use crate::scan_stream::{Kind, Node, Response, NONE};
use serde::{Deserialize, Serialize};
use std::cmp::Reverse;
-use std::collections::BTreeSet;
+use std::collections::{BTreeSet, BinaryHeap};
use std::io::Write;
use std::ops::Bound::{Excluded, Unbounded};
use std::sync::Arc;
use std::time::Instant;
pub const PAGE_SIZE: usize = 128;
+pub const MAX_LARGEST_FILES: usize = 100;
const CHART_SIZE: usize = 64;
const MAX_QUERY_BYTES: usize = 1024 * 1024;
type Key = (Reverse<u64>, Arc<str>, u32);
@@ -311,6 +312,69 @@ impl Catalog {
chart,
})
}
+ /// Rank only live, counted regular files. Walking reachable children also
+ /// excludes descendants of removed directories without another live index.
+ /// The worst retained key is at the heap root: O(N log K), O(K + depth).
+ pub fn largest_json(
+ &self,
+ generation: &str,
+ revision: u32,
+ limit: usize,
+ ) -> Result<String, String> {
+ self.scope(generation, revision)?;
+ if !(1..=MAX_LARGEST_FILES).contains(&limit) {
+ return Err(format!(
+ "Largest-files limit must be between 1 and {MAX_LARGEST_FILES}"
+ ));
+ }
+ let mut best = BinaryHeap::<Key>::with_capacity(limit);
+ let mut pending = vec![self.children[0].iter()];
+ while let Some(children) = pending.last_mut() {
+ if let Some(key) = children.next() {
+ let node = &self.response.nodes[key.2 as usize];
+ if node.kind == Kind::Directory {
+ pending.push(self.children[key.2 as usize].iter());
+ } else if node.kind == Kind::File && node.counted {
+ if best.len() < limit {
+ best.push(key.clone());
+ } else if key < best.peek().unwrap() {
+ *best.peek_mut().unwrap() = key.clone();
+ }
+ }
+ } else {
+ pending.pop();
+ }
+ }
+ #[derive(Serialize)]
+ struct File<'a> {
+ node: NodeSummary<'a>,
+ path: String,
+ }
+ #[derive(Serialize)]
+ struct Largest<'a> {
+ generation: &'a str,
+ revision: u32,
+ limit: usize,
+ total_files: u64,
+ files: Vec<File<'a>>,
+ }
+ let files = best
+ .into_sorted_vec()
+ .into_iter()
+ .map(|key| File {
+ node: self.summary_node(key.2),
+ path: self.path(key.2),
+ })
+ .collect();
+ json(&Largest {
+ generation: &self.generation,
+ revision: self.revision,
+ limit,
+ total_files: self.response.total_files,
+ files,
+ })
+ .map_err(|error| format!("{error}. Try a smaller file limit."))
+ }
pub fn detail_json(&self, generation: &str, revision: u32, id: u32) -> Result<String, String> {
self.scope(generation, revision)?;
self.node(id)?;
@@ -520,6 +584,136 @@ mod tests {
Ok(r#"{"status":"ok","message":"Deleted fixture entry"}"#.into())
}
+ #[test]
+ fn largest_matches_exhaustive_sort_for_every_limit() {
+ let mut entries = wide(1037);
+ entries.push(entry(1038, Some(0), "nested", "directory", 0, true));
+ // Same name and size in different directories exercises the ID tie.
+ entries.push(entry(1039, Some(1038), "file-00001", "file", 0, true));
+ entries.push(entry(1040, Some(1038), "not-counted", "file", 0, false));
+ entries.push(entry(1041, Some(1038), "special", "other", 0, false));
+ entries.push(entry(1042, Some(0), "aaa", "file", 6, true));
+ entries.push(entry(1043, Some(1038), "aaa", "file", 6, true));
+ let store = Catalog::new(fixture(&entries, false), "generation-a".into());
+ let mut expected: Vec<_> = entries
+ .iter()
+ .filter(|e| e["kind"] == "file" && e["counted"] == true)
+ .collect();
+ expected.sort_by_key(|e| {
+ (
+ Reverse(e["size"].as_u64().unwrap()),
+ e["name"].as_str().unwrap(),
+ e["id"].as_u64().unwrap(),
+ )
+ });
+ for limit in 1..=MAX_LARGEST_FILES {
+ let result = value(store.largest_json("generation-a", 0, limit));
+ let ids: Vec<_> = result["files"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|file| file["node"]["id"].clone())
+ .collect();
+ assert_eq!(
+ ids,
+ expected
+ .iter()
+ .take(limit)
+ .map(|e| e["id"].clone())
+ .collect::<Vec<_>>()
+ );
+ assert_eq!(result["total_files"], expected.len());
+ }
+ for limit in [0, MAX_LARGEST_FILES + 1, usize::MAX] {
+ assert!(store.largest_json("generation-a", 0, limit).is_err());
+ }
+ assert!(store.largest_json("old", 0, 10).is_err());
+ assert!(store.largest_json("generation-a", 1, 10).is_err());
+ }
+
+ #[test]
+ fn largest_empty_zero_byte_exact_paths_and_read_only() {
+ let empty = Catalog::new(fixture(&[root()], false), "generation-a".into());
+ assert_eq!(
+ value(empty.largest_json("generation-a", 0, 10))["files"],
+ json!([])
+ );
+ let entries = vec![
+ root(),
+ entry(1, Some(0), " folder ", "directory", 0, true),
+ entry(2, Some(1), " ü <>&\r\n ", "file", 0, true),
+ entry(3, Some(0), "zero", "file", 0, true),
+ ];
+ for read_only in [false, true] {
+ let store = Catalog::new(fixture(&entries, read_only), "generation-a".into());
+ let files = value(store.largest_json("generation-a", 0, 100))["files"].clone();
+ assert_eq!(files.as_array().unwrap().len(), 2);
+ assert_eq!(files[0]["path"], "/fixture/ folder / ü <>&\r\n ");
+ assert_eq!(files[0]["node"]["can_delete"], false);
+ assert_eq!(files[1]["node"]["can_delete"], !read_only);
+ }
+ }
+
+ #[test]
+ fn largest_preserves_the_response_byte_limit_for_deep_paths() {
+ let mut entries = vec![root()];
+ for id in 1..=60 {
+ entries.push(entry(
+ id,
+ Some(id - 1),
+ &"d".repeat(250),
+ "directory",
+ 0,
+ true,
+ ));
+ }
+ for id in 61..=160 {
+ entries.push(entry(id, Some(60), &format!("file-{id}"), "file", 1, true));
+ }
+ let store = Catalog::new(fixture(&entries, false), "generation-a".into());
+ assert!(store
+ .largest_json("generation-a", 0, 100)
+ .unwrap_err()
+ .contains("Try a smaller file limit"));
+ let small = store.largest_json("generation-a", 0, 10).unwrap();
+ assert!(small.len() < MAX_QUERY_BYTES);
+ assert_eq!(value(Ok(small))["files"].as_array().unwrap().len(), 10);
+ }
+
+ #[test]
+ fn largest_tracks_deleted_subtrees_and_quarantines_missing_files() {
+ let entries = vec![
+ root(),
+ entry(1, Some(0), "folder", "directory", 0, true),
+ entry(2, Some(1), "large", "file", 99, true),
+ entry(3, Some(0), "small", "file", 1, true),
+ ];
+ let mut store = Some(Catalog::new(
+ fixture(&entries, false),
+ "generation-a".into(),
+ ));
+ let plan = store
+ .as_ref()
+ .unwrap()
+ .prepare_delete("generation-a", 0, 1)
+ .unwrap();
+ finish_delete(&mut store, &plan, success()).unwrap();
+ let current = store.as_ref().unwrap();
+ assert!(current.largest_json("generation-a", 0, 10).is_err());
+ let result = value(current.largest_json("generation-a", 1, 10));
+ assert_eq!(result["total_files"], 1);
+ assert_eq!(result["files"].as_array().unwrap().len(), 1);
+ assert_eq!(result["files"][0]["node"]["id"], 3);
+ let plan = current.prepare_delete("generation-a", 1, 3).unwrap();
+ assert!(finish_delete(
+ &mut store,
+ &plan,
+ Ok(r#"{"status":"error","message":"File no longer exists"}"#.into())
+ )
+ .is_err());
+ assert!(store.is_none());
+ }
+
#[test]
fn complete_wide_paging_forward_backward_matches_legacy_order() {
let response = fixture(&wide(1037), false);
diff --git a/src/App.tsx b/src/App.tsx
index 9c06409..05493ff 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -6,6 +6,7 @@ import { formatBytes } from "./formatBytes";
import { sameScan } from "./scanView";
import type { ScanNode, ScanResponse, NodeDetail, DeleteResult } from "./scanView";
import { useScanView } from "./useScanView";
+import { LargestFiles } from "./LargestFiles";
import { ToastContainer } from "./ToastContainer";
import type { Toast } from "./ToastContainer";
import { TerminalLog } from "./TerminalLog";
@@ -429,11 +430,13 @@ function ResultScreen({
}) {
const [zoomId, setZoomId] = useState(data.root.id);
const [expanded, setExpanded] = useState(() => new Set([data.root.id]));
- const view = useScanView(data, zoomId, true);
+ const [mode, setMode] = useState<"map" | "largest">("map");
+ const view = useScanView(data, zoomId, mode === "map");
const page = view.page;
const onZoom = (id: number) => {
setExpanded(previous => new Set(previous).add(id));
setZoomId(id);
+ setMode("map");
};
const toggle = (id: number) => setExpanded(previous => {
const next = new Set(previous);
@@ -518,6 +521,13 @@ function ResultScreen({
<StatCard label="Scan Time" value={`${data.scan_time_ms}ms`} />
</div>
+ <div className="flex gap-2 px-6 pb-3 shrink-0" role="group" aria-label="Scan view">
+ <button aria-pressed={mode === "map"} disabled={busy} onClick={() => setMode("map")}
+ className={`px-3 py-2 rounded-lg text-xs ${mode === "map" ? "bg-zinc-700 text-white" : "bg-zinc-900 text-zinc-400"}`}>Storage map</button>
+ <button aria-pressed={mode === "largest"} disabled={busy} onClick={() => setMode("largest")}
+ className={`px-3 py-2 rounded-lg text-xs ${mode === "largest" ? "bg-zinc-700 text-white" : "bg-zinc-900 text-zinc-400"}`}>Largest files</button>
+ </div>
+ {mode === "largest" ? <LargestFiles scope={data} busy={busy} onZoom={onZoom} onNuke={onNuke} /> : <>
{/* Treemap */}
<div className="px-6 mb-4 shrink-0 h-48">
<div className="glass-card rounded-xl p-2 w-full h-full relative group">
@@ -567,6 +577,7 @@ function ResultScreen({
onNuke={onNuke} onZoom={onZoom} expanded={expanded} toggle={toggle} busy={busy} rootView={view} />}
</div>
+ </>}
</div>
);
}
diff --git a/src/LargestFiles.tsx b/src/LargestFiles.tsx
new file mode 100644
index 0000000..0b78f6f
--- /dev/null
+++ b/src/LargestFiles.tsx
@@ -0,0 +1,64 @@
+import { useEffect, useState } from "react";
+import { invoke } from "@tauri-apps/api/core";
+import { sameScan } from "./scanView";
+import type { ScanScope, NodeDetail } from "./scanView";
+import { formatBytes } from "./formatBytes";
+
+interface LargestResponse extends ScanScope {
+ limit: number;
+ total_files: number;
+ files: Pick<NodeDetail, "node" | "path">[];
+}
+
+export function LargestFiles({ scope, busy, onZoom, onNuke }: {
+ scope: ScanScope;
+ busy: boolean;
+ onZoom: (id: number) => void;
+ onNuke: (id: number) => void;
+}) {
+ const { generation, revision } = scope;
+ const [limit, setLimit] = useState(25);
+ const [retry, setRetry] = useState(0);
+ const key = JSON.stringify([generation, revision, limit, retry]);
+ const [state, setState] = useState<{ key: string; data?: LargestResponse; error?: string }>({ key: "" });
+ useEffect(() => {
+ let current = true;
+ void invoke<string>("get_largest_files", { generation, revision, limit }).then(raw => {
+ const data: LargestResponse = JSON.parse(raw);
+ if (!sameScan(data, { generation, revision }) || data.limit !== limit) throw new Error("Scan query returned unexpected largest files");
+ if (current) setState({ key, data });
+ }).catch(error => {
+ if (current) setState({ key, error: String(error) });
+ });
+ return () => { current = false; };
+ }, [generation, revision, limit, key]);
+ // Hide the previous revision/limit synchronously, before its effect cleans up.
+ const data = state.key === key ? state.data : undefined;
+ const error = state.key === key ? state.error : undefined;
+ return <section aria-label="Largest files" className="flex-1 min-h-0 overflow-y-auto px-6 pb-4">
+ <div className="flex items-center justify-between gap-3 py-3">
+ <p role="status" className="text-xs text-zinc-400">{data ? `Showing ${data.files.length} of ${data.total_files.toLocaleString("en-US")} scanned files` : error ? "Largest files unavailable" : "Loading largest files…"}</p>
+ <label className="text-xs text-zinc-400 shrink-0">Show <select id="largest-limit" value={limit} disabled={busy}
+ onChange={event => setLimit(Number(event.target.value))} className="ml-2 bg-zinc-900 border border-zinc-700 rounded px-2 py-1">
+ {[10, 25, 50, 100].map(count => <option key={count} value={count}>{count}</option>)}
+ </select></label>
+ </div>
+ <p className="text-xs text-zinc-500 mb-3">From this scan, across all folders. Rescan to refresh device changes.</p>
+ {error && <div role="alert" className="text-xs text-red-400 py-2">{error} <button onClick={() => setRetry(value => value + 1)} className="underline">Retry</button></div>}
+ {data?.files.length === 0 && <p className="text-sm text-zinc-400 py-4">No counted files in this scan.</p>}
+ <ol className="divide-y divide-zinc-800/80">
+ {data?.files.map(({ node, path }) => <li key={node.id} className="largest-file-row flex items-center gap-3 py-3">
+ <div className="flex-1 min-w-0">
+ <p className="text-sm text-zinc-200 whitespace-pre-wrap break-all">{node.name}</p>
+ <p className="text-xs text-zinc-500 font-mono whitespace-pre-wrap break-all" dir="auto">{path}</p>
+ </div>
+ <span className="text-xs text-zinc-300 font-mono shrink-0">{formatBytes(node.size)}</span>
+ <div className="flex flex-col gap-2 shrink-0 text-xs">
+ <button disabled={busy || node.parent_id === null} onClick={() => onZoom(node.parent_id!)} className="text-accent-400 hover:underline">Show folder</button>
+ <button aria-label={`Delete ${node.name}`} disabled={busy || !node.can_delete} onClick={() => onNuke(node.id)}
+ className="text-red-400 hover:underline disabled:text-zinc-600">Delete</button>
+ </div>
+ </li>)}
+ </ol>
+ </section>;
+}
diff --git a/tests/benchmark_largest_files.py b/tests/benchmark_largest_files.py
new file mode 100644
index 0000000..9f28e70
--- /dev/null
+++ b/tests/benchmark_largest_files.py
@@ -0,0 +1,104 @@
+#!/usr/bin/env python3
+"""Measure production top-K queries on a synthetic scan; no app, ADB or phone.
+
+Requires cached Rust/serde dependencies and macOS/Linux /usr/bin/time.
+RSS covers decoding/catalog construction too; it is not isolated query memory.
+"""
+import json
+from pathlib import Path
+import shutil
+import struct
+import subprocess
+import sys
+import tempfile
+import tomllib
+
+REPO = Path(__file__).resolve().parents[1]
+FILES = 250_000
+DIRS = 32
+if sys.platform not in ("darwin", "linux"):
+ sys.exit("RSS measurement requires macOS or Linux")
+
+
+def frame(output, kind, data):
+ payload = json.dumps({"type": kind, "data": data}, separators=(",", ":")).encode()
+ output.write(struct.pack(">I", len(payload)) + payload)
+
+
+with tempfile.TemporaryDirectory(prefix="socketsweep-largest-bench-") as directory:
+ work = Path(directory)
+ source = work / "src"
+ source.mkdir()
+ for name in ("scan_stream.rs", "scan_store.rs"):
+ shutil.copy(REPO / "src-tauri/src" / name, source / name)
+ versions = {p["name"]: p["version"] for p in tomllib.loads((REPO / "src-tauri/Cargo.lock").read_text())["package"]}
+ (work / "Cargo.toml").write_text(f'''[package]
+name = "largest-files-benchmark"
+version = "0.0.0"
+edition = "2021"
+[dependencies]
+serde = {{ version = "={versions['serde']}", features = ["derive"] }}
+serde_json = "={versions['serde_json']}"
+''')
+ (source / "main.rs").write_text('''const TCP_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
+const MAX_COMMAND_BYTES: usize = 16*1024;
+mod scan_stream;
+mod scan_store;
+use std::io::Read;
+struct Reader(std::io::BufReader<std::fs::File>);
+impl Read for Reader { fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> { self.0.read(bytes) } }
+impl scan_stream::StreamReader for Reader {}
+fn main() {
+ let args: Vec<_> = std::env::args().collect();
+ let mut reader = Reader(std::io::BufReader::new(std::fs::File::open(&args[1]).unwrap()));
+ let response = scan_stream::read(&mut reader, false, |_| Ok(())).unwrap();
+ let store = scan_store::Catalog::new(response, "benchmark".into());
+ let mut samples = Vec::new();
+ let mut bytes = 0;
+ if args[2] == "query" {
+ for _ in 0..31 {
+ let started = std::time::Instant::now();
+ let output = store.largest_json("benchmark", 0, 100).unwrap();
+ samples.push(started.elapsed().as_secs_f64()*1000.0);
+ bytes = output.len();
+ let data: serde_json::Value = serde_json::from_str(&output).unwrap();
+ assert_eq!(data["files"].as_array().unwrap().len(), 100);
+ assert_eq!(data["total_files"], 250000);
+ }
+ }
+ samples.sort_by(f64::total_cmp);
+ println!("{}", serde_json::json!({"query_median_ms":samples.get(15), "query_p95_ms":samples.get(29), "ipc_bytes":bytes}));
+ std::hint::black_box(store);
+}
+''')
+ stream = work / "fixture.stream"
+ with stream.open("wb") as output:
+ frame(output, "started", {"stream_version": 1, "root": "/fixture", "read_only": False})
+ directories = [{"id": 0, "parent": None, "name": "fixture", "kind": "directory", "size": 0, "counted": True}]
+ directories += [{"id": i + 1, "parent": 0, "name": f"folder-{i:02}", "kind": "directory", "size": 0, "counted": True} for i in range(DIRS)]
+ frame(output, "entries", {"entries": directories})
+ total = 0
+ for offset in range(0, FILES, 128):
+ batch = []
+ for i in range(offset, min(offset + 128, FILES)):
+ size = (i * 7919) % 10_000_000
+ total += size
+ batch.append({"id": i + DIRS + 1, "parent": i % DIRS + 1, "name": f"file-{i:06}.dat", "kind": "file", "size": size, "counted": True})
+ frame(output, "entries", {"entries": batch})
+ frame(output, "done", {"total_files": FILES, "total_dirs": DIRS + 1, "total_size": total,
+ "errors": 0, "skipped": 0, "scan_time_ms": 1, "scan_threads": 4,
+ "serialize_ms": 0, "send_ms": 0, "bytes_sent": output.tell()})
+ subprocess.run(["cargo", "build", "--offline", "--release", "--quiet"], cwd=work, check=True, stderr=subprocess.PIPE)
+ results = {"files": FILES, "directories": DIRS + 1, "limit": 100, "samples_per_query_process": 31, "runs": {}}
+ for mode in ("load_only", "query"):
+ samples = []
+ for _ in range(3):
+ run = subprocess.run(["/usr/bin/time", "-l" if sys.platform == "darwin" else "-v",
+ str(work / "target/release/largest-files-benchmark"), str(stream), mode],
+ check=True, capture_output=True, text=True)
+ metrics = json.loads(run.stdout)
+ rss = next(line for line in run.stderr.splitlines() if "maximum resident set size" in line.lower())
+ metrics["process_peak_rss_bytes"] = int(rss.strip().split()[0]) if sys.platform == "darwin" else int(rss.rsplit(":", 1)[1]) * 1024
+ samples.append(metrics)
+ results["runs"][mode] = samples
+ print(json.dumps(results, indent=2))
diff --git a/tests/scan_ui_fixture.js b/tests/scan_ui_fixture.js
index 7c5fbbb..a49119c 100644
--- a/tests/scan_ui_fixture.js
+++ b/tests/scan_ui_fixture.js
@@ -9,6 +9,8 @@
let readOnly = false;
let delayedZoom = true;
let delayedDetail = true;
+ let delayedLargest = true;
+ let failLargest = false;
let failDelete = false;
let stopOutcome = "acknowledged";
const readyDevices = [
@@ -94,6 +96,16 @@
}
check(!unavailable, "Snapshot unavailable");
check(args.generation === scope().generation && args.revision === revision, "Stale mock snapshot");
+ if (command === "get_largest_files") {
+ check(Number.isInteger(args.limit) && args.limit > 0 && args.limit <= 100, "Unbounded largest-files query");
+ if (failLargest) { failLargest = false; throw "Mock largest-files failure"; }
+ const files = [...rootChildren, ...folderChildren].filter(item => item.type === "file")
+ .sort((a, b) => b.size - a.size || (a.name < b.name ? -1 : a.name > b.name ? 1 : a.id - b.id));
+ const response = JSON.stringify({ ...scope(), limit: args.limit, total_files: files.length,
+ files: files.slice(0, args.limit).map(item => detail(item.id)) });
+ if (delayedLargest) { delayedLargest = false; await pause(300); }
+ return response;
+ }
if (command === "get_scan_view") {
const response = JSON.stringify(view(args));
if (args.nodeId === 1 && delayedZoom) { delayedZoom = false; await pause(300); }
@@ -127,7 +139,7 @@
const report = (passed, error) => {
const output = document.createElement("pre");
output.id = "scan-test-report";
- output.textContent = JSON.stringify({ fixture: "scan-ui", passed, error, ipc_calls: calls.length, checks: passed ? ["offline fonts under CSP", "setup alignment", "result fonts", "file label semantics", "complete paging", "late zoom", "Other tile", "stale confirmation", "ID-only deletion", "revision refresh", "partial failure", "read-only", "acknowledged shutdown", "unconfirmed shutdown", "reconnect", "stop action ordering", "toast dismissal integration", "bounded diagnostic integration"] : undefined });
+ output.textContent = JSON.stringify({ fixture: "scan-ui", passed, error, ipc_calls: calls.length, checks: passed ? ["offline fonts under CSP", "setup alignment", "result fonts", "file label semantics", "complete paging", "bounded largest files", "late largest response", "largest query retry", "largest ID-only deletion", "largest read-only guards", "largest folder navigation without rescanning", "late zoom", "Other tile", "stale confirmation", "ID-only deletion", "revision refresh", "partial failure", "read-only", "acknowledged shutdown", "unconfirmed shutdown", "reconnect", "stop action ordering", "toast dismissal integration", "bounded diagnostic integration"] : undefined });
document.body.append(output);
void fetch("/report", { method: "POST", body: output.textContent }).then(() => {
if (passed) location.replace("/tests/toast_lifecycle_fixture.html");
@@ -206,6 +218,33 @@
check(document.documentElement.scrollWidth <= innerWidth, "Results overflow horizontally");
check(document.body.textContent.includes("128 entries on this page of 271"), "Missing full entry count");
check(!rows().find(item => item.textContent.includes("file-0")).querySelector("button:disabled"), "File label became an unavailable control");
+ const scanCount = calls.filter(item => item.command === "run_scan").length;
+ const largestRows = () => [...document.querySelectorAll(".largest-file-row")];
+ button("Largest files").click();
+ await waitFor(() => document.querySelector("#largest-limit"), "Largest-files controls missing");
+ const chooseLimit = count => {
+ const select = document.querySelector("#largest-limit");
+ select.value = String(count);
+ select.dispatchEvent(new Event("change", { bubbles: true }));
+ };
+ // The first response is delayed; switching limits must win permanently.
+ chooseLimit(10);
+ await waitFor(() => largestRows().length === 10, "Largest-files limit not applied");
+ await pause(350);
+ check(largestRows().length === 10, "Late largest-files response replaced the current limit");
+ check(largestRows()[0].textContent.includes("/fixture/ file-0 "), "Exact largest-file path missing");
+ check(!largestRows().some(row => row.textContent.includes("large-folder")), "Directory ranked as a file");
+ check(document.documentElement.scrollWidth <= innerWidth, "Largest files overflow horizontally");
+ failLargest = true;
+ chooseLimit(50);
+ await waitFor(() => button("Retry"), "Largest-files failure not shown");
+ button("Retry").click();
+ await waitFor(() => largestRows().length === 50, "Largest-files retry failed");
+ chooseLimit(100);
+ await waitFor(() => largestRows().length === 100, "Maximum largest-files page missing");
+ button("Show folder").click();
+ await waitFor(() => rows().length === 129, "Show folder did not restore map");
+ check(calls.filter(item => item.command === "run_scan").length === scanCount, "Largest-files browsing rescanned the phone");
const firstNames = rows().map(item => item.textContent);
button("Next").click();
await waitFor(() => rows().some(item => item.textContent.includes("file-127")), "Next page missing");
@@ -239,13 +278,24 @@
await waitFor(() => rows().length === 129, "Rescan did not reload");
await pause(350);
check(!button("NUKE IT"), "Old confirmation survived rescan");
+ button("Largest files").click();
+ await waitFor(() => largestRows().length === 25, "Largest files missing before delete");
document.querySelector('[aria-label="Delete file-0 "]').click();
await waitFor(() => button("NUKE IT"), "Confirmation missing");
check(document.body.textContent.includes("/fixture/ file-0 "), "Exact confirmation path missing");
button("NUKE IT").click();
- await waitFor(() => rows().length === 129 && !document.querySelector('[aria-label="Delete file-0 "]'), "Deleted row survived revision refresh");
+ await waitFor(() => largestRows().length === 25 && !document.querySelector('[aria-label="Delete file-0 "]'), "Deleted largest row survived revision refresh");
+ button("Storage map").click();
+ await waitFor(() => rows().length === 129 && !document.querySelector('[aria-label="Delete file-0 "]'), "Deleted map row survived revision refresh");
check(calls.some(item => item.command === "delete_item" && item.args.nodeId === 2 && !("path" in item.args)), "ID-only delete was not invoked");
+ button("Largest files").click();
+ await waitFor(() => largestRows().length === 25, "Largest files did not refresh after deletion");
+ check(!largestRows().some(row => row.textContent.includes("/fixture/ file-0 ")), "Deleted largest file survived revision");
+ const nested = largestRows().find(row => row.textContent.includes("/large-folder/"));
+ if (nested) nested.querySelector("button").click(); else button("Storage map").click();
+ await waitFor(() => rows().length > 0, "Map missing after largest-files navigation");
+ if (button("← Back to Root")) { button("← Back to Root").click(); await waitFor(() => rows()[0]?.textContent.includes("fixture"), "Root missing"); }
zoomFolder();
await waitFor(() => rows().some(item => item.textContent.includes("nested-0")), "Nested directory missing");
button("Next").click();
@@ -268,6 +318,11 @@
await waitFor(() => rows().length === 129, "Read-only page missing");
check(document.body.textContent.includes("Deletion disabled"), "Read-only banner missing");
check(!document.querySelector('[aria-label^="Delete "]'), "Read-only deletion enabled");
+ button("Largest files").click();
+ await waitFor(() => largestRows().length === 25, "Read-only largest files missing");
+ check([...document.querySelectorAll('.largest-file-row button[aria-label^="Delete "]')].every(item => item.disabled), "Read-only largest deletion enabled");
+ button("Storage map").click();
+ await waitFor(() => rows().length === 129, "Read-only map missing");
const previousAcknowledgements = () => (document.body.textContent.match(/Daemon acknowledged shutdown\./g) ?? []).length;
document.querySelector("#btn-disconnect").click();
await waitFor(() => document.querySelector("#btn-connect") && !document.querySelector("#btn-connect").disabled, "Acknowledged stop did not release the UI");