A high-performance Android storage analyzer that bypasses MTP using a native C++ daemon, a Rust TCP bridge, and a React Treemap UI.
Rust
Persist verified scan history with scoped comparisons and atomic writes (#92)
Vishnu Srivatsavae417c9117fde
diff --git a/README.md b/README.mdindex 88c33f1..1d26b1f 100644--- a/README.md+++ b/README.md@@ -7,7 +7,7 @@<img src="https://img.shields.io/badge/Tauri-v2-FFC131.svg?logo=tauri&logoColor=white" alt="Tauri v2" /><img src="https://img.shields.io/badge/React-19-61DAFB.svg?logo=react&logoColor=black" alt="React 19" /><img src="https://img.shields.io/badge/C%2B%2B-17-00599C.svg?logo=c%2B%2B&logoColor=white" alt="C++17" />- <img src="https://img.shields.io/badge/Rust-1.70+-000000.svg?logo=rust&logoColor=white" alt="Rust" />+ <img src="https://img.shields.io/badge/Rust-1.89+-000000.svg?logo=rust&logoColor=white" alt="Rust" /><br /><a href="https://github.com/sponsors/VishnuSrivatsava"><img src="https://img.shields.io/badge/♥_Sponsor-EA4AAA?style=for-the-badge&logo=github-sponsors&logoColor=white" alt="Sponsor" /></a></div>@@ -102,6 +102,12 @@ That's it. No apps to install on your phone, no Wi-Fi setup, no root required.In development builds, **File types** shows counts and bytes by filename extensionfrom the completed scan. See [classification rules and coverage](docs/file-types.md).+Verified scans without access errors are recorded locally when history storage+is available. The results header compares compatible scans of the same device,+folder and access mode; failed or cancelled scans never become baselines. See+[successful-scan history](docs/scan-history.md) for the storage location,+durability and comparison rules.+In a source build, choose the device in setup before connecting when multipledevices are ready. Refresh after plugging in or authorizing a phone. A selecteddevice that disappears stays selected and blocks connection; another phone is@@ -235,7 +241,7 @@ sequenceDiagram### Prerequisites1. **Node.js** (`^20.19.0`, `^22.13.0`, or `>=24`, including frontend lint tooling)-2. **Rust** (v1.70+ with Cargo)+2. **Rust** (v1.89+ with Cargo; native file locking for scan history)3. **Android NDK** (v26d or newer)4. **Android SDK / ADB** installed and added to your system `$PATH`.diff --git a/docs/scan-history.md b/docs/scan-history.mdnew file mode 100644index 0000000..5eb0044--- /dev/null+++ b/docs/scan-history.md@@ -0,0 +1,100 @@+# Successful-scan history++The results header compares current totals with the previous comparable recorded+scan: no previous comparable scan, unchanged totals, or signed changes in bytes,+files and folders. Queries use the existing host catalog, with no new ADB calls+or device traversal. Deletion permissions are unchanged.++Only verified, published scan completions with **zero access errors** become+history baselines. Failed, cancelled, truncated, root-changed and partially+readable scans leave previous history intact. History failures never turn a+successful scan into a failed scan; the comparison becomes unavailable and the+reason is written to stderr. A complete scan with legitimate exclusions can be+recorded, but different exclusion/duplicate counts do not compare.++## Stored data and comparison boundaries++`scan-history.json` lives in Tauri's app data directory:++- macOS: `~/Library/Application Support/com.mathcuber.socketsweep`+- Linux: `$XDG_DATA_HOME/com.mathcuber.socketsweep`, normally+ `~/.local/share/com.mathcuber.socketsweep`+- Windows: `%APPDATA%\com.mathcuber.socketsweep`++The file contains **device serials and scan-root paths**, access mode, exclusion+policy, counting-semantics version, skipped-entry counts, totals and Unix+recording times. It stores no descendant filenames, per-file inventory, file+contents or authentication secrets. Files created on Unix have mode 0600;+Windows uses the app data directory's inherited permissions. This is local+plaintext metadata, not encrypted storage.++Comparisons require matching device serial, daemon-confirmed root, access mode,+exclusion policy, counting-semantics version and skipped-entry count. Root mode+reports its resolved root; shell mode retains the confirmed requested root.+Different shell aliases remain separate keys rather than being guessed+identical on the host. A counting/exclusion rule change must bump the semantics+version. Version 1 is the first history format; unsupported format versions are+left unchanged, with no speculative migration.++Deltas describe logical scanned bytes and counts, not file-content changes,+physical free-space changes or Android app ownership. Equal exclusion counts+are a conservative comparison gate, not proof that every excluded entry is+identical. External changes require a rescan. Deleted catalog entries change the+live comparison immediately, but only another successful scan records a new+baseline. Previously recorded totals are not edited after an in-app deletion.++## Storage and failure behavior++A persistent `scan-history.lock` uses Rust's native, nonblocking OS file lock+across the complete read/modify/replace operation. Another writer skips history+recording for that scan instead of waiting or losing an update. Closing or+crashing the process releases the OS lock; the lock file itself stays present+and must not be deleted while any app instance is running. Rust **1.89+** is+required for the standard-library locking API. Unix opening flags use the+already-transitive `libc` dependency directly; no locking library is added.++History reads reject symlinks and special files and read at most 256 KiB+plus one byte. Oversized or unreadable files are left untouched. Within the+budget, the format version is checked before decoding entries. Malformed+current-format content is renamed to `scan-history.invalid-<timestamp>.json`+and retained for inspection. Unknown versions are never quarantined or+rewritten merely because their entry schema differs.++Retention keeps at most ten entries per device/root/mode/policy key, at most+100 overall, and at most 256 KiB serialized, dropping oldest entries first.+Each replacement uses an exclusively created temporary file in the same+directory, flushes its data, closes it and atomically renames it over the old+file. A write or rename failure leaves the previous valid file intact. Unix+also syncs the containing directory after publication; if that fails, the+update has already been published and the error says so. Windows has no+portable standard-library directory-sync equivalent. Universal power-loss+durability across filesystems and hardware is not claimed.++Unpublished temporaries are never used as baselines. A writer cleans them only+after acquiring the cross-process lock, so it cannot delete another cooperating+writer's active temporary. Its own failed writes clean up their temporary.+Quarantined files remain until manually removed. To reset history, close all+app instances and remove `scan-history.json`; the next eligible scan starts a+new history.++## Validation++Host tests cover key separation, coverage eligibility, malformed and future+schemas, bounded reads/retention, interrupted temporary writes, permission and+non-regular-path failures, Unix symlinks/private file modes, and a separate+process holding the OS lock. Rust serialization and frontend parsing share a+first-scan wire fixture, preventing null-versus-omitted fields from drifting.+Scoped queries reject old generations/revisions and compare live catalog+totals. Existing stream tests cover invalid/truncated completion and cancellation+before publication; the history hook runs strictly after that publication gate.++Node tests validate numbers, timestamps, scopes and reconciliation. The built+UI replay uses mocked IPC for first comparisons, unchanged rescans, deletion+deltas, device separation and partial-scan unavailability. These are offline+checks, not physical-device validation. To check manually, restart+`npm run tauri dev`, scan twice, then use a disposable deletion and rescan.+No Android daemon rebuild is required.++Tracked in #36, adapting the history idea from+[Shanmukh's fork](https://github.com/ksaishanmukh/SocketSweep/tree/d677b530e00dec75c305fc56318720aa8c161692)+(commits `d8918df`, `5e442e2`) to verified completions and the current host store.diff --git a/package.json b/package.jsonindex 9ea00d2..671ee4f 100644--- a/package.json+++ b/package.json@@ -8,7 +8,7 @@"dev": "vite","build": "tsc && vite build","lint": "eslint src tests vite.config.ts eslint.config.js --max-warnings 0",- "test": "node --test tests/format_bytes.test.mjs tests/scan_view.test.mjs tests/log_history.test.mjs tests/lint_gate.test.mjs tests/devices.test.mjs tests/file_types.test.mjs",+ "test": "node --test tests/format_bytes.test.mjs tests/scan_view.test.mjs tests/log_history.test.mjs tests/lint_gate.test.mjs tests/devices.test.mjs tests/file_types.test.mjs tests/scan_history.test.mjs","preview": "vite preview","tauri": "tauri"},diff --git a/src-tauri/Cargo.lock b/src-tauri/Cargo.lockindex f2fff76..47b596f 100644--- a/src-tauri/Cargo.lock+++ b/src-tauri/Cargo.lock@@ -3030,6 +3030,7 @@ name = "tauri-app"version = "0.1.0"dependencies = ["getrandom 0.3.4",+ "libc","serde","serde_json","tauri",diff --git a/src-tauri/Cargo.toml b/src-tauri/Cargo.tomlindex d5b5354..c2ee415 100644--- a/src-tauri/Cargo.toml+++ b/src-tauri/Cargo.toml@@ -5,6 +5,7 @@ description = "A Tauri App"authors = ["you"]license = "GPL-3.0"edition = "2021"+rust-version = "1.89"# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html@@ -23,3 +24,6 @@ tauri = { version = "2", features = [] }serde = { version = "1", features = ["derive"] }serde_json = "1"getrandom = "0.3"++[target.'cfg(unix)'.dependencies]+libc = "0.2"diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex e09a4fd..cc3256c 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -21,6 +21,7 @@ use tauri::ipc::Channel;mod scan_benchmark;mod scan_stream;mod scan_store;+mod scan_history;mod session;mod devices;use std::process::Command;@@ -38,6 +39,7 @@ const TCP_READ_TIMEOUT: Duration = Duration::from_secs(120); // scans can be slostatic SCAN_STORE: Mutex<Option<scan_store::Catalog>> = Mutex::new(None);fn invalidate_scan() -> Result<(), String> {+ scan_history::clear_comparison();*SCAN_STORE.lock().map_err(|_| "Scan state is unavailable")? = None;Ok(())}@@ -367,6 +369,7 @@ fn cancel_scan(scan_id: String) -> Result<(), String> {#[tauri::command(async)]fn run_scan(+ app: tauri::AppHandle,path: Option<String>,scan_id: String,on_progress: Channel<ScanProgress>,@@ -387,6 +390,7 @@ fn run_scan(.filter(|p| !p.is_empty()).unwrap_or_else(|| "/sdcard".into());let connection = active_connection()?;+ let serial = connection.serial.clone();let payload = command_payload(&format!("SCAN_STREAM {effective_root}"), &connection.token)?;let read_only = connection.read_only;let cancelled = Arc::new(AtomicBool::new(false));@@ -451,8 +455,10 @@ fn run_scan(}}// Public snapshot generations are independent of the secret daemon token.- let catalog = scan_store::Catalog::new(response, new_random_id()?);+ let generation = new_random_id()?;+ let catalog = scan_store::Catalog::new(response, generation.clone());let json = catalog.summary_json()?;+ let history_entry = scan_history::completed_entry(&serial, &catalog);// Serialize bounded metadata before publishing deletion authority.let mut active = ACTIVE_SCAN.lock()@@ -462,6 +468,21 @@ fn run_scan(}*SCAN_STORE.lock().map_err(|_| "Scan state is unavailable")? = Some(catalog);active.take();+ drop(active);+ // Completion and cancellation are committed above. History I/O happens+ // outside the catalog lock and never changes whether the scan succeeded.+ let recorded = history_entry.and_then(|entry| {+ let directory = app.path().app_data_dir()+ .map_err(|e| format!("Cannot locate the app data directory: {e}"))?;+ scan_history::record(&directory, entry)+ });+ match recorded {+ Ok(recorded) => scan_history::note_comparison(generation, recorded.previous),+ Err(error) => {+ eprintln!("Scan history unavailable: {error}");+ scan_history::clear_comparison();+ }+ }Ok(json)})();if cancelled.load(Ordering::SeqCst) {@@ -547,6 +568,15 @@ fn get_file_types(generation: String, revision: u32) -> Result<String, String> {.file_types_json(&generation, revision)}+#[tauri::command(async)]+fn get_scan_comparison(generation: String, revision: u32) -> Result<String, String> {+ let store = SCAN_STORE.lock().map_err(|_| "Scan state is unavailable")?;+ let catalog = store+ .as_ref()+ .ok_or("Scan is unavailable; rescan required")?;+ scan_history::comparison_json(catalog, &generation, revision)+}+#[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")?;@@ -592,6 +622,7 @@ pub fn run() {get_scan_node,get_largest_files,get_file_types,+ get_scan_comparison,]).build(tauri::generate_context!()).expect("error while building tauri application")diff --git a/src-tauri/src/scan_benchmark.rs b/src-tauri/src/scan_benchmark.rsindex 9c0bb24..3384ad6 100644--- a/src-tauri/src/scan_benchmark.rs+++ b/src-tauri/src/scan_benchmark.rs@@ -401,6 +401,7 @@ mod tests {let connection = session::Connection {address: listener.local_addr().unwrap(),token: "0".repeat(64),+ serial: "fixture-device".into(),read_only: false,};let server = std::thread::spawn(move || {diff --git a/src-tauri/src/scan_history.rs b/src-tauri/src/scan_history.rsnew file mode 100644index 0000000..f78c612--- /dev/null+++ b/src-tauri/src/scan_history.rs@@ -0,0 +1,1063 @@+//! Comparable totals for verified scans. Only a completion that passed the+//! stream decoder and published a catalog may be recorded; failed, cancelled+//! or truncated scans never become baselines.+use crate::scan_store::Catalog;+use serde::{Deserialize, Serialize};+use std::collections::HashMap;+use std::io::{Read, Write};+use std::path::{Path, PathBuf};+use std::sync::Mutex;+use std::time::{SystemTime, UNIX_EPOCH};++/// Bump when daemon counting or exclusion rules change the meaning of the+/// stored totals (v1: regular files and directories counted separately,+/// st_size bytes, symlink/`.`/`..` exclusion everywhere; root read-only adds+/// serial traversal, inode deduplication, virtual-filesystem and root mount+/// alias exclusions). Old entries stay unread comparisons, not false deltas.+pub(crate) const COUNTING_SEMANTICS: u32 = 1;+const FORMAT_VERSION: u32 = 1;+const MAX_PER_KEY: usize = 10;+const MAX_ENTRIES: usize = 100;+const MAX_FILE_BYTES: usize = 256 * 1024;+const MAX_SAFE_INTEGER: u64 = (1u64 << 53) - 1;+const MAX_TIMESTAMP: u64 = 8_640_000_000_000;+const MAX_SERIAL_BYTES: usize = 512;+const MAX_ROOT_BYTES: usize = 16 * 1024;+const FILE_NAME: &str = "scan-history.json";+const LOCK_NAME: &str = "scan-history.lock";+const TEMP_PREFIX: &str = "scan-history.json.tmp-";+const INVALID_PREFIX: &str = "scan-history.invalid-";++// Serialize local callers too; the persistent OS lock below protects the+// complete read/modify/replace transaction across app instances.+static FILE_LOCK: Mutex<()> = Mutex::new(());++#[derive(Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Hash, Debug)]+#[serde(rename_all = "snake_case")]+pub(crate) enum AccessMode {+ Shell,+ RootReadOnly,+}++#[derive(Clone, Copy, Deserialize, Serialize, PartialEq, Eq, Hash, Debug)]+#[serde(rename_all = "snake_case")]+pub(crate) enum ExclusionPolicy {+ /// Shell traversal: only symlinks, `.` and `..` are excluded.+ SymlinksOnly,+ /// Root read-only: adds inode deduplication, virtual filesystems and+ /// root mount aliases.+ RootDeduplicated,+}++#[derive(Clone, Deserialize, Serialize, PartialEq, Eq, Hash, Debug)]+#[serde(deny_unknown_fields)]+pub(crate) struct HistoryKey {+ serial: String,+ /// The daemon-confirmed root: realpath-resolved in root mode, and+ /// compared against the requested root otherwise.+ root: String,+ access: AccessMode,+ exclusions: ExclusionPolicy,+ counting_semantics: u32,+}++#[derive(Clone, Deserialize, Serialize, PartialEq, Eq, Debug)]+#[serde(deny_unknown_fields)]+pub(crate) struct HistoryEntry {+ key: HistoryKey,+ total_files: u64,+ total_dirs: u64,+ total_size: u64,+ recorded_at: u64,+ skipped: u64,+}++impl HistoryEntry {+ pub(crate) fn new(+ serial: &str,+ root: &str,+ read_only: bool,+ total_files: u64,+ total_dirs: u64,+ total_size: u64,+ recorded_at: u64,+ ) -> Result<Self, String> {+ let entry = Self {+ key: HistoryKey {+ serial: serial.to_string(),+ root: root.to_string(),+ access: if read_only {+ AccessMode::RootReadOnly+ } else {+ AccessMode::Shell+ },+ exclusions: if read_only {+ ExclusionPolicy::RootDeduplicated+ } else {+ ExclusionPolicy::SymlinksOnly+ },+ counting_semantics: COUNTING_SEMANTICS,+ },+ total_files,+ total_dirs,+ total_size,+ recorded_at,+ skipped: 0,+ };+ entry.validate()?;+ Ok(entry)+ }++ fn validate(&self) -> Result<(), String> {+ let serial = self.key.serial.as_bytes();+ if serial.is_empty()+ || serial.len() > MAX_SERIAL_BYTES+ || serial.iter().any(|b| b.is_ascii_control())+ {+ return Err("Invalid history device serial".into());+ }+ let root = self.key.root.as_bytes();+ if !self.key.root.starts_with('/')+ || root.len() > MAX_ROOT_BYTES+ || root.contains(&0)+ || (self.key.root.len() > 1 && self.key.root.ends_with('/'))+ {+ return Err("Invalid history scan root".into());+ }+ if self.key.counting_semantics == 0 {+ return Err("Invalid history counting semantics".into());+ }+ for value in [+ self.total_files,+ self.total_dirs,+ self.total_size,+ self.recorded_at,+ self.skipped,+ ] {+ if value > MAX_SAFE_INTEGER {+ return Err("History totals exceed the exact integer range".into());+ }+ }+ if self.total_dirs == 0+ || (self.total_files == 0 && self.total_size != 0)+ || !matches!(+ (self.key.access, self.key.exclusions),+ (AccessMode::Shell, ExclusionPolicy::SymlinksOnly)+ | (AccessMode::RootReadOnly, ExclusionPolicy::RootDeduplicated)+ )+ {+ return Err("Invalid history counting or exclusion metadata".into());+ }+ if self.recorded_at == 0 || self.recorded_at > MAX_TIMESTAMP {+ return Err("History entries require a recording time".into());+ }+ Ok(())+ }+}++#[derive(Deserialize, Serialize)]+#[serde(deny_unknown_fields)]+struct HistoryFile {+ format_version: u32,+ entries: Vec<HistoryEntry>,+}++/// The outcome of recording: the immediately previous baseline for the same+/// key, if a comparable scan was recorded before this one.+#[derive(Debug, PartialEq, Eq)]+pub(crate) struct Recorded {+ pub(crate) previous: Option<HistoryEntry>,+}++fn history_path(directory: &Path) -> PathBuf {+ directory.join(FILE_NAME)+}++enum Loaded {+ Missing,+ Entries(Vec<HistoryEntry>),+ /// A file this version cannot interpret; it must stay untouched.+ UnsupportedFormat,+ Corrupt(String),+}++// Refuse symlinks and special files before opening; platform flags also+// prevent a swapped symlink/FIFO from being followed or blocking the caller.+fn open_regular(path: &Path, create: bool) -> std::io::Result<std::fs::File> {+ match std::fs::symlink_metadata(path) {+ Ok(metadata) if !metadata.file_type().is_file() => {+ return Err(std::io::Error::other("History path is not a regular file"));+ }+ Err(error) if !(create && error.kind() == std::io::ErrorKind::NotFound) => {+ return Err(error)+ }+ _ => {}+ }+ let mut options = std::fs::OpenOptions::new();+ options+ .read(true)+ .write(create)+ .create(create)+ .truncate(false);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ options+ .mode(0o600)+ .custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);+ }+ #[cfg(windows)]+ {+ use std::os::windows::fs::OpenOptionsExt;+ options.custom_flags(0x0020_0000); // FILE_FLAG_OPEN_REPARSE_POINT+ }+ let file = options.open(path)?;+ let metadata = file.metadata()?;+ if !metadata.file_type().is_file() {+ return Err(std::io::Error::other("History path is not a regular file"));+ }+ #[cfg(windows)]+ {+ use std::os::windows::fs::MetadataExt;+ if metadata.file_attributes() & 0x400 != 0 {+ // FILE_ATTRIBUTE_REPARSE_POINT+ return Err(std::io::Error::other("History path is a reparse point"));+ }+ }+ Ok(file)+}++fn load(path: &Path) -> Result<Loaded, String> {+ let file = match open_regular(path, false) {+ Ok(file) => file,+ Err(error) if error.kind() == std::io::ErrorKind::NotFound => return Ok(Loaded::Missing),+ Err(error) => return Err(format!("Cannot read the history file: {error}")),+ };+ // Read at most the budget plus one byte, even if another program grows it.+ // Oversized files may belong to a newer format; leave them untouched.+ let mut bytes = Vec::new();+ file.take((MAX_FILE_BYTES + 1) as u64)+ .read_to_end(&mut bytes)+ .map_err(|e| format!("Cannot read the history file: {e}"))?;+ if bytes.len() > MAX_FILE_BYTES {+ return Err("History file exceeds its size bound and was left unchanged".into());+ }+ #[derive(Deserialize)]+ struct Version {+ format_version: u32,+ }+ let parsed = (|| -> Result<Loaded, String> {+ let version: Version = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;+ if version.format_version != FORMAT_VERSION {+ return Ok(Loaded::UnsupportedFormat);+ }+ let parsed: HistoryFile = serde_json::from_slice(&bytes).map_err(|e| e.to_string())?;+ if parsed.entries.len() > MAX_ENTRIES {+ return Err("History file exceeds its entry bound".into());+ }+ for entry in &parsed.entries {+ entry.validate()?;+ }+ Ok(Loaded::Entries(parsed.entries))+ })();+ // Only malformed content is quarantined, never an I/O/permission failure.+ Ok(parsed.unwrap_or_else(Loaded::Corrupt))+}++/// Quarantine an unreadable file by renaming it aside. The bytes stay on+/// disk for inspection; recording then starts a fresh history.+fn quarantine(path: &Path, now_ns: u128) -> Result<(), String> {+ let quarantine_path = path.with_file_name(format!("{INVALID_PREFIX}{now_ns}.json"));+ if quarantine_path.exists() {+ return Err("Cannot quarantine the history file uniquely".into());+ }+ std::fs::rename(path, &quarantine_path)+ .map_err(|e| format!("Cannot quarantine the corrupt history file: {e}"))+}++/// Only called under the cross-process lock: no cooperating writer can own+/// one of these temporaries while cleanup runs. Never remove the lock file.+fn remove_stale_temporaries(directory: &Path) {+ let Ok(children) = std::fs::read_dir(directory) else {+ return;+ };+ for child in children.flatten() {+ if child+ .file_name()+ .to_str()+ .is_some_and(|name| name.starts_with(TEMP_PREFIX))+ {+ let _ = std::fs::remove_file(child.path());+ }+ }+}++fn nanos_now() -> u128 {+ SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|time| time.as_nanos())+ .unwrap_or_default()+}++/// Append one verified completion and return the previous comparable+/// baseline. The replacement is atomic: one rename publishes the new file,+/// or the previous content survives untouched.+pub(crate) fn record(directory: &Path, entry: HistoryEntry) -> Result<Recorded, String> {+ entry.validate()?;+ let _guard = FILE_LOCK+ .lock()+ .map_err(|_| "History state is unavailable")?;+ let path = history_path(directory);+ std::fs::create_dir_all(directory)+ .map_err(|e| format!("Cannot create the history directory: {e}"))?;+ let lock = open_regular(&directory.join(LOCK_NAME), true)+ .map_err(|e| format!("Cannot open the history lock: {e}"))?;+ lock.try_lock()+ .map_err(|e| format!("History is busy or cannot be locked: {e}"))?;+ let mut entries = match load(&path)? {+ Loaded::Missing => Vec::new(),+ Loaded::Entries(entries) => entries,+ Loaded::UnsupportedFormat => {+ return Err("Unsupported history format; file was left unchanged".into())+ }+ Loaded::Corrupt(error) => {+ // Malformed bytes are preserved for inspection. Other I/O errors+ // return before this branch, leaving the baseline untouched.+ quarantine(&path, nanos_now()).map_err(|q| format!("{error}; {q}"))?;+ eprintln!("Malformed scan history was quarantined; starting a new history");+ Vec::new()+ }+ };+ let previous = entries+ .iter()+ .rev()+ .find(|recorded| recorded.key == entry.key && recorded.skipped == entry.skipped)+ .cloned();+ entries.push(entry);+ // Keep the newest MAX_PER_KEY entries of every key, then the newest+ // MAX_ENTRIES entries overall; insertion order defines recency.+ let mut kept = vec![0usize; entries.len()];+ let mut per_key = HashMap::new();+ for (index, kept) in kept.iter_mut().enumerate().rev() {+ let seen = per_key.entry(entries[index].key.clone()).or_insert(0usize);+ *kept = *seen;+ *seen += 1;+ }+ let mut retained: Vec<_> = entries+ .into_iter()+ .zip(kept)+ .filter(|(_, seen)| *seen < MAX_PER_KEY)+ .map(|(entry, _)| entry)+ .collect();+ let overflow = retained.len().saturating_sub(MAX_ENTRIES);+ retained.drain(..overflow);+ let mut history = HistoryFile {+ format_version: FORMAT_VERSION,+ entries: retained,+ };+ let contents = loop {+ let contents = serde_json::to_vec(&history)+ .map_err(|e| format!("Cannot encode the history file: {e}"))?;+ if contents.len() <= MAX_FILE_BYTES {+ break contents;+ }+ if history.entries.len() <= 1 {+ return Err("History entry exceeds its size bound".into());+ }+ history.entries.remove(0);+ };+ remove_stale_temporaries(directory);+ let temporary = directory.join(format!(+ "{TEMP_PREFIX}{}-{}",+ std::process::id(),+ nanos_now()+ ));+ // Exclusive creation cannot truncate an existing file or follow a symlink.+ let mut options = std::fs::OpenOptions::new();+ options.write(true).create_new(true);+ #[cfg(unix)]+ {+ use std::os::unix::fs::OpenOptionsExt;+ options.mode(0o600);+ }+ let mut file = options+ .open(&temporary)+ .map_err(|e| format!("Cannot create the history file: {e}"))?;+ struct Temporary(PathBuf);+ impl Drop for Temporary {+ fn drop(&mut self) {+ let _ = std::fs::remove_file(&self.0);+ }+ }+ let _cleanup = Temporary(temporary.clone());+ let written = file.write_all(&contents).and_then(|()| file.sync_all());+ drop(file); // Windows replacement also needs our write handle closed.+ written.map_err(|e| format!("Cannot write the history file: {e}"))?;+ std::fs::rename(&temporary, &path)+ .map_err(|e| format!("Cannot publish the history file: {e}"))?;+ // Atomic visibility and crash durability are distinct. Sync directory+ // metadata on Unix; Windows has no equivalent portable std operation.+ #[cfg(unix)]+ std::fs::File::open(directory)+ .and_then(|dir| dir.sync_all())+ .map_err(|e| format!("History was published but directory sync failed: {e}"))?;+ Ok(Recorded { previous })+}++pub(crate) fn completed_entry(serial: &str, catalog: &Catalog) -> Result<HistoryEntry, String> {+ let (errors, skipped) = catalog.coverage();+ if errors != 0 {+ return Err("Scans with access errors are not recorded as history baselines".into());+ }+ let recorded_at = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .map(|time| time.as_secs())+ .map_err(|_| "Clock is before the Unix epoch".to_string())?;+ let mut entry = HistoryEntry::new(+ serial,+ catalog.root_path(),+ catalog.read_only(),+ catalog.total_files(),+ catalog.total_dirs(),+ catalog.total_size(),+ recorded_at,+ )?;+ entry.skipped = skipped;+ entry.validate()?;+ Ok(entry)+}++// ── Current-scan comparison ──────────────────────────────────────────────────++struct Noted {+ previous: Option<HistoryEntry>,+}+static COMPARISON: Mutex<Option<(String, Noted)>> = Mutex::new(None);++pub(crate) fn note_comparison(generation: String, previous: Option<HistoryEntry>) {+ if let Ok(mut comparison) = COMPARISON.lock() {+ *comparison = Some((generation, Noted { previous }));+ }+}++pub(crate) fn clear_comparison() {+ if let Ok(mut comparison) = COMPARISON.lock() {+ *comparison = None;+ }+}++#[derive(Serialize)]+struct Previous {+ recorded_at: u64,+ total_files: u64,+ total_dirs: u64,+ total_size: u64,+}++#[derive(Serialize)]+struct Delta {+ files: i64,+ dirs: i64,+ size: i64,+}++#[derive(Serialize)]+struct Comparison {+ generation: String,+ revision: u32,+ first: bool,+ previous: Option<Previous>,+ delta: Option<Delta>,+}++/// Deltas come from the live catalog, so deletions keep the comparison+/// consistent with the totals the UI shows now, not just at scan time.+pub(crate) fn comparison_json(+ catalog: &Catalog,+ generation: &str,+ revision: u32,+) -> Result<String, String> {+ catalog.require_scope(generation, revision)?;+ let previous = COMPARISON+ .lock()+ .map_err(|_| "History state is unavailable")?+ .as_ref()+ .filter(|(noted_generation, _)| noted_generation.as_str() == generation)+ .map(|(_, noted)| noted.previous.clone())+ .ok_or("No comparison available for this scan")?;+ let Some(previous) = previous else {+ return serde_json::to_string(&Comparison {+ generation: generation.to_string(),+ revision,+ first: true,+ previous: None,+ delta: None,+ })+ .map_err(|e| e.to_string());+ };+ // Totals are bounded by MAX_SAFE_INTEGER, so signed differences cannot+ // overflow the exact integer range.+ serde_json::to_string(&Comparison {+ generation: generation.to_string(),+ revision,+ first: false,+ previous: Some(Previous {+ recorded_at: previous.recorded_at,+ total_files: previous.total_files,+ total_dirs: previous.total_dirs,+ total_size: previous.total_size,+ }),+ delta: Some(Delta {+ files: catalog.total_files() as i64 - previous.total_files as i64,+ dirs: catalog.total_dirs() as i64 - previous.total_dirs as i64,+ size: catalog.total_size() as i64 - previous.total_size as i64,+ }),+ })+ .map_err(|e| e.to_string())+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::scan_stream::{self, Response};+ use serde_json::{json, Value};+ use std::io::Cursor as Reader;++ struct Directory(PathBuf);+ impl Directory {+ fn new(tag: &str) -> Self {+ let nanos = SystemTime::now()+ .duration_since(UNIX_EPOCH)+ .unwrap()+ .as_nanos();+ Self(std::env::temp_dir().join(format!(+ "socketsweep-history-{tag}-{}-{nanos}",+ std::process::id()+ )))+ }+ fn path(&self) -> &Path {+ &self.0+ }+ fn write(&self, bytes: &[u8]) {+ std::fs::create_dir_all(&self.0).unwrap();+ std::fs::write(history_path(&self.0), bytes).unwrap();+ }+ fn read(&self) -> Vec<u8> {+ std::fs::read(history_path(&self.0)).unwrap()+ }+ }+ impl Drop for Directory {+ fn drop(&mut self) {+ let _ = std::fs::remove_dir_all(&self.0);+ }+ }++ fn entry(+ serial: &str,+ root: &str,+ read_only: bool,+ files: u64,+ size: u64,+ at: u64,+ ) -> HistoryEntry {+ HistoryEntry::new(serial, root, read_only, files, 3, size, at).unwrap()+ }++ fn parsed(directory: &Directory) -> HistoryFile {+ serde_json::from_slice(&directory.read()).unwrap()+ }++ fn response(size: u64) -> Response {+ fn frame(kind: &str, data: Value) -> Vec<u8> {+ let data = serde_json::to_vec(&json!({"type":kind,"data":data})).unwrap();+ let mut bytes = (data.len() as u32).to_be_bytes().to_vec();+ bytes.extend(data);+ bytes+ }+ let entries = vec![+ json!({"id":0,"parent":null,"name":"fixture","kind":"directory","size":0,"counted":true}),+ json!({"id":1,"parent":0,"name":"leaf","kind":"file","size":size,"counted":true}),+ ];+ let mut bytes = frame(+ "started",+ json!({"stream_version":1,"root":"/fixture","read_only":false}),+ );+ bytes.extend(frame("entries", json!({"entries":entries})));+ let count = bytes.len();+ bytes.extend(frame(+ "done",+ json!({"total_files":1,"total_dirs":1,"total_size":size,"errors":0,+ "skipped":0,"scan_time_ms":1,"scan_threads":4,"serialize_ms":0,+ "send_ms":0,"bytes_sent":count}),+ ));+ scan_stream::read(&mut Reader::new(bytes), false, |_| Ok(())).unwrap()+ }++ #[test]+ fn keys_separate_devices_roots_and_access_modes() {+ let directory = Directory::new("keys");+ let first = record(+ directory.path(),+ entry("phone-a", "/sdcard", false, 10, 100, 1),+ )+ .unwrap();+ assert_eq!(first.previous, None);+ let other_device = record(+ directory.path(),+ entry("phone-b", "/sdcard", false, 20, 200, 2),+ )+ .unwrap();+ assert_eq!(other_device.previous, None);+ let other_root = record(+ directory.path(),+ entry("phone-a", "/data", false, 30, 300, 3),+ )+ .unwrap();+ assert_eq!(other_root.previous, None);+ let other_mode = record(+ directory.path(),+ entry("phone-a", "/sdcard", true, 40, 400, 4),+ )+ .unwrap();+ assert_eq!(other_mode.previous, None);+ let same = record(+ directory.path(),+ entry("phone-a", "/sdcard", false, 50, 500, 5),+ )+ .unwrap();+ let previous = same.previous.unwrap();+ assert_eq!((previous.total_files, previous.total_size), (10, 100));+ let file = parsed(&directory);+ assert_eq!(file.format_version, FORMAT_VERSION);+ assert_eq!(file.entries.len(), 5);+ assert_eq!(file.entries.last().unwrap().recorded_at, 5);+ }++ #[test]+ fn root_paths_serials_and_totals_validate_before_any_write() {+ assert!(HistoryEntry::new("phone", "/sdcard/backup", false, 0, 1, 0, 1).is_ok());+ assert!(HistoryEntry::new("phone", "/", true, 0, 1, 0, 1).is_ok());+ for root in ["sdcard", "", "/sdcard/", "/a\0b"] {+ assert!(+ HistoryEntry::new("phone", root, false, 0, 1, 0, 1).is_err(),+ "{root}"+ );+ }+ for serial in ["", "phone\n", &"x".repeat(MAX_SERIAL_BYTES + 1)] {+ assert!(+ HistoryEntry::new(serial, "/sdcard", false, 0, 1, 0, 1).is_err(),+ "{serial:?}"+ );+ }+ for at in [0, MAX_SAFE_INTEGER + 1] {+ assert!(+ HistoryEntry::new("phone", "/sdcard", false, 0, 1, 0, at).is_err(),+ "{at}"+ );+ }+ assert!(+ HistoryEntry::new("phone", "/sdcard", false, MAX_SAFE_INTEGER + 1, 1, 0, 1).is_err()+ );+ let directory = Directory::new("validate");+ // Directly constructed entries keep record()'s own validation testable.+ let relative_root = HistoryEntry {+ key: HistoryKey {+ serial: "phone".into(),+ root: "relative".into(),+ access: AccessMode::Shell,+ exclusions: ExclusionPolicy::SymlinksOnly,+ counting_semantics: COUNTING_SEMANTICS,+ },+ total_files: 1,+ total_dirs: 1,+ total_size: 1,+ recorded_at: 1,+ skipped: 0,+ };+ assert!(record(directory.path(), relative_root).is_err());+ assert!(!history_path(directory.path()).exists());+ }++ #[test]+ fn interrupted_writes_and_corrupt_files_are_quarantined_not_deleted() {+ let directory = Directory::new("corrupt");+ directory.write(b"{\"format_version\":1,\"entries\":[{\"key\"");+ let result = record(directory.path(), entry("phone", "/sdcard", false, 1, 1, 1)).unwrap();+ assert_eq!(result.previous, None);+ let children: Vec<String> = std::fs::read_dir(directory.path())+ .unwrap()+ .map(|child| child.unwrap().file_name().to_str().unwrap().into())+ .collect();+ assert_eq!(children.len(), 3, "{children:?}");+ let quarantined = children+ .iter()+ .find(|name| name.starts_with(INVALID_PREFIX))+ .unwrap();+ assert_eq!(+ std::fs::read(directory.path().join(quarantined)).unwrap(),+ b"{\"format_version\":1,\"entries\":[{\"key\""+ );+ assert_eq!(parsed(&directory).entries.len(), 1);+ }++ #[test]+ fn oversized_and_invalid_entry_files_restart_the_history() {+ let directory = Directory::new("invalid");+ directory.write(&vec![b'x'; MAX_FILE_BYTES + 1]);+ assert!(record(directory.path(), entry("phone", "/sdcard", false, 1, 1, 1)).is_err());+ assert_eq!(directory.read(), vec![b'x'; MAX_FILE_BYTES + 1]);+ // Valid JSON with impossible entries is corrupt, not a baseline.+ let bad_entries = serde_json::to_vec(&HistoryFile {+ format_version: FORMAT_VERSION,+ entries: vec![HistoryEntry {+ key: HistoryKey {+ serial: "phone".into(),+ root: "/sdcard".into(),+ access: AccessMode::Shell,+ exclusions: ExclusionPolicy::SymlinksOnly,+ counting_semantics: COUNTING_SEMANTICS,+ },+ total_files: MAX_SAFE_INTEGER + 1,+ total_dirs: 0,+ total_size: 0,+ recorded_at: 9,+ skipped: 0,+ }],+ })+ .unwrap();+ directory.write(&bad_entries);+ let result = record(directory.path(), entry("phone", "/sdcard", false, 1, 1, 1)).unwrap();+ assert_eq!(result.previous, None);+ assert_eq!(parsed(&directory).entries.len(), 1);+ }++ #[test]+ fn newer_format_files_are_preserved_without_recording() {+ let directory = Directory::new("newer");+ let newer =+ b"{\"format_version\":2,\"entries\":[{\"future_schema\":true}],\"new_field\":1}";+ directory.write(newer);+ let error =+ record(directory.path(), entry("phone", "/sdcard", false, 1, 1, 1)).unwrap_err();+ assert!(error.contains("Unsupported history format"), "{error}");+ assert_eq!(directory.read(), newer);+ }++ #[test]+ fn retention_bounds_each_key_and_the_whole_file() {+ let directory = Directory::new("retention");+ for number in 1..=12u64 {+ record(+ directory.path(),+ entry("phone", "/sdcard", false, number, number, number),+ )+ .unwrap();+ }+ let file = parsed(&directory);+ assert_eq!(file.entries.len(), MAX_PER_KEY);+ assert_eq!(+ file.entries+ .iter()+ .map(|entry| entry.recorded_at)+ .collect::<Vec<_>>(),+ (3..=12).collect::<Vec<_>>()+ );+ let latest = record(+ directory.path(),+ entry("phone", "/sdcard", false, 13, 13, 13),+ )+ .unwrap();+ assert_eq!(latest.previous.unwrap().recorded_at, 12);+ for number in 1..=95u64 {+ record(+ directory.path(),+ entry(+ "phone",+ &format!("/root-{number}"),+ false,+ number,+ number,+ number,+ ),+ )+ .unwrap();+ }+ let file = parsed(&directory);+ assert_eq!(file.entries.len(), MAX_ENTRIES);+ // The overall bound dropped the oldest same-key entries first.+ let sdcard: Vec<_> = file+ .entries+ .iter()+ .filter(|entry| entry.key.root == "/sdcard")+ .map(|entry| entry.recorded_at)+ .collect();+ assert_eq!(sdcard, (9..=13).collect::<Vec<_>>());+ assert_eq!(+ file.entries+ .iter()+ .filter(|entry| entry.key.root.starts_with("/root-"))+ .count(),+ 95+ );+ }++ #[test]+ fn stale_temporaries_are_removed_and_successful_writes_leave_none() {+ let directory = Directory::new("temporaries");+ record(directory.path(), entry("phone", "/sdcard", false, 1, 1, 1)).unwrap();+ let original = directory.read();+ let stale = directory.path().join(format!("{TEMP_PREFIX}stale"));+ std::fs::write(&stale, b"interrupted").unwrap();+ match load(&history_path(directory.path())).unwrap() {+ Loaded::Entries(entries) => assert_eq!(entries[0].total_files, 1),+ _ => panic!("Interrupted temporary replaced the baseline"),+ }+ assert_eq!(directory.read(), original);+ let recorded = record(directory.path(), entry("phone", "/sdcard", false, 2, 2, 2)).unwrap();+ assert_eq!(recorded.previous.unwrap().total_files, 1);+ assert!(!stale.exists());+ let children: Vec<String> = std::fs::read_dir(directory.path())+ .unwrap()+ .map(|child| child.unwrap().file_name().to_str().unwrap().into())+ .collect();+ assert_eq!(children.len(), 2);+ assert!(children.contains(&FILE_NAME.to_string()));+ assert!(children.contains(&LOCK_NAME.to_string()));+ }++ #[test]+ #[cfg(unix)]+ fn unwritable_directories_fail_without_losing_the_previous_baseline() {+ use std::os::unix::fs::PermissionsExt;+ let directory = Directory::new("unwritable");+ record(directory.path(), entry("phone", "/sdcard", false, 1, 1, 1)).unwrap();+ let permissions = std::fs::metadata(directory.path()).unwrap().permissions();+ std::fs::set_permissions(directory.path(), std::fs::Permissions::from_mode(0o500)).unwrap();+ assert!(record(directory.path(), entry("phone", "/sdcard", false, 2, 2, 2)).is_err());+ std::fs::set_permissions(directory.path(), permissions).unwrap();+ assert_eq!(parsed(&directory).entries.len(), 1);+ let previous = record(directory.path(), entry("phone", "/sdcard", false, 2, 2, 2))+ .unwrap()+ .previous;+ assert_eq!(previous.unwrap().recorded_at, 1);+ }++ #[test]+ fn a_blocked_history_path_fails_without_moving_anything_aside() {+ let directory = Directory::new("blocked");+ std::fs::create_dir_all(history_path(directory.path())).unwrap();+ assert!(record(directory.path(), entry("phone", "/sdcard", false, 1, 1, 1)).is_err());+ assert!(history_path(directory.path()).is_dir());+ }++ #[test]+ fn comparison_deltas_track_the_live_catalog_and_scope() {+ let _operation = crate::DAEMON_OPERATION.lock().unwrap();+ let catalog = crate::scan_store::Catalog::new(response(70), "generation-a".into());+ note_comparison(+ "generation-a".into(),+ Some(entry("phone", "/fixture", false, 6, 50, 1)),+ );+ let raw = comparison_json(&catalog, "generation-a", 0).unwrap();+ let value: Value = serde_json::from_str(&raw).unwrap();+ assert_eq!(value["first"], false);+ assert_eq!(value["previous"]["total_size"], 50);+ assert_eq!(value["previous"]["recorded_at"], 1);+ assert_eq!(value["delta"]["files"], -5);+ assert_eq!(value["delta"]["dirs"], -2);+ assert_eq!(value["delta"]["size"], 20);+ // Repeated queries are consistent; wrong scopes never compare.+ assert_eq!(+ serde_json::from_str::<Value>(&comparison_json(&catalog, "generation-a", 0).unwrap())+ .unwrap()["delta"]["size"],+ 20+ );+ assert!(comparison_json(&catalog, "old", 0).is_err());+ assert!(comparison_json(&catalog, "generation-a", 1).is_err());+ // Another generation's note never serves this catalog.+ note_comparison("generation-b".into(), None);+ assert!(comparison_json(&catalog, "generation-a", 0).is_err());+ clear_comparison();+ let fresh = crate::scan_store::Catalog::new(response(70), "generation-b".into());+ note_comparison("generation-b".into(), None);+ let raw = comparison_json(&fresh, "generation-b", 0).unwrap();+ assert_eq!(+ raw,+ include_str!("../../tests/fixtures/scan-history-first.json").trim()+ );+ assert_eq!(serde_json::from_str::<Value>(&raw).unwrap()["first"], true);+ clear_comparison();+ assert!(comparison_json(&fresh, "generation-b", 0).is_err());+ }++ #[test]+ fn recording_reports_positive_negative_and_zero_directions() {+ let directory = Directory::new("directions");+ record(+ directory.path(),+ entry("phone", "/sdcard", false, 60, 50, 1),+ )+ .unwrap();+ let same = record(+ directory.path(),+ entry("phone", "/sdcard", false, 60, 50, 2),+ )+ .unwrap();+ assert_eq!(same.previous.unwrap().total_size, 50);+ let grew = record(+ directory.path(),+ entry("phone", "/sdcard", false, 70, 60, 3),+ )+ .unwrap();+ assert_eq!(grew.previous.unwrap().total_files, 60);+ let shrank = record(directory.path(), entry("phone", "/sdcard", false, 10, 5, 4)).unwrap();+ assert_eq!(shrank.previous.unwrap().total_size, 60);+ let file = parsed(&directory);+ assert_eq!(file.entries.len(), 4);+ assert_eq!(file.entries.last().unwrap().total_files, 10);+ }+ #[test]+ fn access_errors_do_not_replace_history_and_exclusion_counts_must_match() {+ let directory = Directory::new("coverage");+ let catalog = Catalog::new(response(7), "coverage".into());+ record(+ directory.path(),+ completed_entry("phone", &catalog).unwrap(),+ )+ .unwrap();+ let original = directory.read();+ let mut partial = response(3);+ partial.errors = 1;+ let partial = Catalog::new(partial, "partial".into());+ assert!(completed_entry("phone", &partial).is_err());+ assert_eq!(directory.read(), original);+ let mut excluded = response(3);+ excluded.skipped = 2;+ let excluded = Catalog::new(excluded, "excluded".into());+ let changed = completed_entry("phone", &excluded).unwrap();+ assert!(record(directory.path(), changed.clone())+ .unwrap()+ .previous+ .is_none());+ assert!(record(directory.path(), changed)+ .unwrap()+ .previous+ .is_some());+ }++ #[test]+ fn long_comparison_keys_evict_old_entries_to_meet_the_byte_budget() {+ let directory = Directory::new("bytes");+ for n in 1..=20 {+ let root = format!("/{}-{n}", "x".repeat(MAX_ROOT_BYTES - 8));+ record(directory.path(), entry("phone", &root, false, n, n, n)).unwrap();+ }+ let stored = parsed(&directory);+ assert!(stored.entries.len() < 20);+ assert_eq!(stored.entries.last().unwrap().recorded_at, 20);+ assert!(directory.read().len() <= MAX_FILE_BYTES);+ }++ #[cfg(unix)]+ #[test]+ fn symlinks_and_unreadable_files_are_not_moved_or_replaced() {+ use std::os::unix::fs::{symlink, PermissionsExt};+ let directory = Directory::new("symlink");+ std::fs::create_dir_all(directory.path()).unwrap();+ let target = directory.path().join("target.json");+ std::fs::write(&target, b"fixture target").unwrap();+ let path = history_path(directory.path());+ symlink(&target, &path).unwrap();+ assert!(record(directory.path(), entry("phone", "/sdcard", false, 1, 1, 1)).is_err());+ assert!(std::fs::symlink_metadata(&path)+ .unwrap()+ .file_type()+ .is_symlink());+ assert_eq!(std::fs::read(&target).unwrap(), b"fixture target");+ std::fs::remove_file(&path).unwrap();+ record(directory.path(), entry("phone", "/sdcard", false, 1, 1, 1)).unwrap();+ assert_eq!(+ std::fs::metadata(&path).unwrap().permissions().mode() & 0o777,+ 0o600+ );+ if unsafe { libc::geteuid() } == 0 {+ return;+ }+ let original = directory.read();+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0)).unwrap();+ assert!(record(directory.path(), entry("phone", "/sdcard", false, 2, 2, 2)).is_err());+ std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600)).unwrap();+ assert_eq!(directory.read(), original);+ assert!(!std::fs::read_dir(directory.path())+ .unwrap()+ .any(|child| child+ .unwrap()+ .file_name()+ .to_string_lossy()+ .starts_with(INVALID_PREFIX)));+ }++ #[test]+ fn another_process_cannot_lose_updates_or_remove_an_active_temporary() {+ use std::process::{Command, Stdio};+ use std::time::{Duration, Instant};+ const CHILD: &str = "SOCKETSWEEP_HISTORY_LOCK_TEST";+ if let Some(path) = std::env::var_os(CHILD) {+ let directory = PathBuf::from(path);+ let lock = open_regular(&directory.join(LOCK_NAME), true).unwrap();+ lock.try_lock().unwrap();+ std::fs::write(directory.join("ready"), b"locked").unwrap();+ let deadline = Instant::now() + Duration::from_secs(10);+ while !directory.join("release").exists() {+ assert!(+ Instant::now() < deadline,+ "Parent did not release lock test"+ );+ std::thread::sleep(Duration::from_millis(10));+ }+ return; // OS releases the lock even if this process exits abruptly.+ }+ let directory = Directory::new("process-lock");+ record(directory.path(), entry("phone", "/sdcard", false, 1, 1, 1)).unwrap();+ let original = directory.read();+ let temporary = directory.path().join(format!("{TEMP_PREFIX}active-writer"));+ std::fs::write(&temporary, b"in-progress").unwrap();+ struct Child(std::process::Child);+ impl Drop for Child {+ fn drop(&mut self) {+ let _ = self.0.kill();+ let _ = self.0.wait();+ }+ }+ let mut child = Child(Command::new(std::env::current_exe().unwrap())+ .args(["--exact", "scan_history::tests::another_process_cannot_lose_updates_or_remove_an_active_temporary"])+ .env(CHILD, directory.path()).stdout(Stdio::null()).spawn().unwrap());+ let deadline = Instant::now() + Duration::from_secs(5);+ while !directory.path().join("ready").exists() {+ assert!(+ child.0.try_wait().unwrap().is_none(),+ "Lock child exited early"+ );+ assert!(Instant::now() < deadline, "Lock child never became ready");+ std::thread::sleep(Duration::from_millis(10));+ }+ let error =+ record(directory.path(), entry("phone", "/sdcard", false, 2, 2, 2)).unwrap_err();+ assert!(error.contains("locked"), "{error}");+ assert_eq!(directory.read(), original);+ assert_eq!(std::fs::read(&temporary).unwrap(), b"in-progress");+ std::fs::write(directory.path().join("release"), b"release").unwrap();+ let deadline = Instant::now() + Duration::from_secs(5);+ loop {+ if let Some(status) = child.0.try_wait().unwrap() {+ assert!(status.success());+ break;+ }+ assert!(Instant::now() < deadline, "Lock child did not exit");+ std::thread::sleep(Duration::from_millis(10));+ }+ let recorded = record(directory.path(), entry("phone", "/sdcard", false, 2, 2, 2)).unwrap();+ assert_eq!(recorded.previous.unwrap().total_files, 1);+ assert!(!temporary.exists());+ }+}diff --git a/src-tauri/src/scan_store.rs b/src-tauri/src/scan_store.rsindex 9cab5c2..fbd9754 100644--- a/src-tauri/src/scan_store.rs+++ b/src-tauri/src/scan_store.rs@@ -179,6 +179,29 @@ impl Catalog {}Ok(())}+ /// Public generation/revision gate for sibling modules that serve+ /// snapshot-scoped queries without exposing catalog internals.+ pub fn require_scope(&self, generation: &str, revision: u32) -> Result<(), String> {+ self.scope(generation, revision)+ }+ pub fn coverage(&self) -> (u64, u64) {+ (self.response.errors, self.response.skipped)+ }+ pub fn root_path(&self) -> &str {+ &self.response.root+ }+ pub fn read_only(&self) -> bool {+ self.response.read_only+ }+ pub fn total_files(&self) -> u64 {+ self.response.total_files+ }+ pub fn total_dirs(&self) -> u64 {+ self.response.total_dirs+ }+ pub fn total_size(&self) -> u64 {+ self.response.total_size+ }fn node(&self, id: u32) -> Result<&Node, String> {let node = self.responsediff --git a/src-tauri/src/scan_stream.rs b/src-tauri/src/scan_stream.rsindex 94f9ac9..6b2d7cc 100644--- a/src-tauri/src/scan_stream.rs+++ b/src-tauri/src/scan_stream.rs@@ -163,8 +163,8 @@ pub struct Response {pub(crate) total_files: u64,pub(crate) total_dirs: u64,pub(crate) total_size: u64,- errors: u64,- skipped: u64,+ pub(crate) errors: u64,+ pub(crate) skipped: u64,pub(crate) read_only: bool,scan_time_ms: u64,scan_threads: u32,diff --git a/src-tauri/src/session.rs b/src-tauri/src/session.rsindex 8e959fc..8f91970 100644--- a/src-tauri/src/session.rs+++ b/src-tauri/src/session.rs@@ -18,6 +18,7 @@ const CLEANUP_TIMEOUT: Duration = Duration::from_secs(5);pub(super) struct Connection {pub address: SocketAddr,pub token: String,+ pub serial: String,pub read_only: bool,}@@ -105,7 +106,7 @@ impl Session {fn new(adb: PathBuf, serial: String) -> Result<Self, String> {Ok(Self {adb,- serial,+ serial: serial.clone(),directory: format!("/data/local/tmp/socketsweep-{}", new_random_id()?),privilege: Privilege::Shell,owned_directory: false,@@ -116,6 +117,7 @@ impl Session {connection: Connection {address: (Ipv4Addr::LOCALHOST, 0).into(),token: new_random_id()?,+ serial,read_only: false,},})diff --git a/src/App.tsx b/src/App.tsxindex 4510d32..7e1949e 100644--- a/src/App.tsx+++ b/src/App.tsx@@ -10,6 +10,7 @@ import { FileTreeNode, QueryError } from "./FileTree";import { IconNuke } from "./Icons";import { LargestFiles } from "./LargestFiles";import { FileTypes } from "./FileTypes";+import { ScanHistory } from "./ScanHistory";import { ToastContainer } from "./ToastContainer";import type { Toast } from "./ToastContainer";import { TerminalLog } from "./TerminalLog";@@ -244,6 +245,7 @@ function ResultScreen({Root access · Read-only · Deletion disabled</div>)}+ <ScanHistory scope={data} />{/* Stats row */}<div className="grid grid-cols-2 sm:grid-cols-4 gap-3 px-6 py-4 shrink-0">diff --git a/src/ScanHistory.tsx b/src/ScanHistory.tsxnew file mode 100644index 0000000..b7b2187--- /dev/null+++ b/src/ScanHistory.tsx@@ -0,0 +1,57 @@+import { useEffect, useState } from "react";+import { invoke } from "@tauri-apps/api/core";+import { parseScanComparison } from "./scanComparison";+import type { ScanComparison } from "./scanComparison";+import type { ScanResponse } from "./scanView";+import { formatBytes } from "./formatBytes";++const formatCount = (value: number): string =>+ `${value > 0 ? "+" : value < 0 ? "-" : ""}${Math.abs(value).toLocaleString("en-US")}`;++const formatChange = (value: number, unit: (bytes: number) => string): string =>+ value === 0 ? "0" : `${value > 0 ? "+" : "-"}${unit(Math.abs(value))}`;++/**+ * One line comparing the live snapshot with the previous successful scan of+ * the same device, folder and access mode. History is recorded only for+ * verified completions; queries never rescan the device.+ */+export function ScanHistory({ scope }: { scope: ScanResponse }) {+ const { generation, revision, total_files, total_dirs, total_size } = scope;+ const key = JSON.stringify([generation, revision, total_files, total_dirs, total_size]);+ const [state, setState] = useState<{ key: string; data?: ScanComparison; error?: string }>({ key: "" });+ useEffect(() => {+ let current = true;+ void invoke<string>("get_scan_comparison", { generation, revision }).then(raw => {+ const data = parseScanComparison(raw, { generation, revision, total_files, total_dirs, total_size });+ if (current) setState({ key, data });+ }).catch(() => {+ // The comparison is context, not a scan result; a failed query must not+ // claim anything about previous scans.+ if (current) setState({ key, error: "unavailable" });+ });+ return () => { current = false; };+ }, [generation, revision, total_files, total_dirs, total_size, key]);+ const data = state.key === key ? state.data : undefined;+ const error = state.key === key ? state.error : undefined;+ if (!data && !error) return null;+ let text: string;+ if (error || !data) {+ text = "Previous-scan comparison unavailable.";+ } else if (data.first) {+ text = "No previous comparable scan for this device and folder.";+ } else if (data.delta && data.previous) {+ const date = new Date(data.previous.recorded_at * 1000).toLocaleDateString("en-US");+ const unchanged = data.delta.files === 0 && data.delta.dirs === 0 && data.delta.size === 0;+ text = unchanged+ ? `No change since the scan recorded on ${date}.`+ : `Since the previous scan (${date}): ${[+ formatChange(data.delta.size, formatBytes),+ `${formatCount(data.delta.files)} files`,+ `${formatCount(data.delta.dirs)} folders`,+ ].join(" · ")}`;+ } else {+ text = "Previous-scan comparison unavailable.";+ }+ return <p id="scan-history" role="status" className="px-6 pt-1 text-xs text-zinc-500">{text}</p>;+}diff --git a/src/scanComparison.ts b/src/scanComparison.tsnew file mode 100644index 0000000..ee173f7--- /dev/null+++ b/src/scanComparison.ts@@ -0,0 +1,50 @@+import { sameScan } from "./scanView";+import type { ScanScope } from "./scanView";++export interface PreviousScan {+ recorded_at: number;+ total_files: number;+ total_dirs: number;+ total_size: number;+}+export interface ScanComparison extends ScanScope {+ first: boolean;+ previous?: PreviousScan;+ delta?: { files: number; dirs: number; size: number };+}+type Expected = ScanScope & { total_files: number; total_dirs: number; total_size: number };+const object = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);+const count = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;+const change = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value);++/** Reject stale, malformed or non-reconciling comparisons before display. */+export function parseScanComparison(raw: string, expected: Expected): ScanComparison {+ const data: unknown = JSON.parse(raw);+ const invalid = () => new Error("Scan comparison does not match this scan");+ if (!object(data) || typeof data.generation !== "string" || !count(data.revision)+ || !sameScan({ generation: data.generation, revision: data.revision }, expected)+ || typeof data.first !== "boolean") throw invalid();+ if (data.first) {+ if (data.previous !== null || data.delta !== null) throw invalid();+ return { generation: data.generation, revision: data.revision, first: true };+ }+ if (!object(data.previous) || !count(data.previous.recorded_at) || (data.previous.recorded_at === 0 || data.previous.recorded_at > 8_640_000_000_000)+ || !count(data.previous.total_files) || !count(data.previous.total_dirs) || !count(data.previous.total_size)+ || !object(data.delta) || !change(data.delta.files) || !change(data.delta.dirs) || !change(data.delta.size)) throw invalid();+ // Previous totals plus the deltas must rebuild the totals the UI shows now.+ if (data.previous.total_files + data.delta.files !== expected.total_files+ || data.previous.total_dirs + data.delta.dirs !== expected.total_dirs+ || data.previous.total_size + data.delta.size !== expected.total_size) throw invalid();+ return {+ generation: data.generation,+ revision: data.revision,+ first: false,+ previous: {+ recorded_at: data.previous.recorded_at,+ total_files: data.previous.total_files,+ total_dirs: data.previous.total_dirs,+ total_size: data.previous.total_size,+ },+ delta: { files: data.delta.files, dirs: data.delta.dirs, size: data.delta.size },+ };+}diff --git a/tests/fixtures/scan-history-first.json b/tests/fixtures/scan-history-first.jsonnew file mode 100644index 0000000..ae6c93f--- /dev/null+++ b/tests/fixtures/scan-history-first.json@@ -0,0 +1 @@+{"generation":"generation-b","revision":0,"first":true,"previous":null,"delta":null}diff --git a/tests/scan_history.test.mjs b/tests/scan_history.test.mjsnew file mode 100644index 0000000..244640b--- /dev/null+++ b/tests/scan_history.test.mjs@@ -0,0 +1,92 @@+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import test from "node:test";+import ts from "typescript";++const transpile = source => ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext } }).outputText;+const url = source => `data:text/javascript;base64,${Buffer.from(source).toString("base64")}`;+const scanView = url(transpile(await readFile(new URL("../src/scanView.ts", import.meta.url), "utf8")));+const source = transpile(await readFile(new URL("../src/scanComparison.ts", import.meta.url), "utf8")).replace('"./scanView"', JSON.stringify(scanView));+const { parseScanComparison } = await import(url(source));+const expected = { generation: "scan-a", revision: 2, total_files: 100, total_dirs: 10, total_size: 4096 };+const comparison = () => ({+ ...expected,+ first: false,+ previous: { recorded_at: 1700000000, total_files: 90, total_dirs: 12, total_size: 3072 },+ delta: { files: 10, dirs: -2, size: 1024 },+});+const parse = (data, scope = expected) => parseScanComparison(JSON.stringify(data), scope);++test("valid comparisons reconcile previous totals with the live snapshot", () => {+ const result = parse(comparison());+ assert.equal(result.first, false);+ assert.equal(result.previous.total_size, 3072);+ assert.equal(result.delta.size, 1024);+ assert.deepEqual(+ [result.previous.total_files + result.delta.files, result.previous.total_dirs + result.delta.dirs, result.previous.total_size + result.delta.size],+ [expected.total_files, expected.total_dirs, expected.total_size],+ );+});++test("first scans carry no previous totals or deltas", () => {+ const result = parse({ ...expected, first: true, previous: null, delta: null });+ assert.equal(result.first, true);+ assert.equal(result.previous, undefined);+ assert.equal(result.delta, undefined);+ for (const extra of [{ previous: comparison().previous }, { delta: comparison().delta }, { previous: undefined }, { delta: undefined }]) {+ assert.throws(() => parse({ ...expected, first: true, previous: null, delta: null, ...extra }), /does not match/);+ }+});++test("stale scopes and generations are rejected", () => {+ for (const change of [{ generation: "old" }, { revision: 1 }, { revision: -1 }]) {+ assert.throws(() => parse({ ...comparison(), ...change }), /does not match/);+ }+});++test("non-reconciling deltas are rejected", () => {+ for (const change of [+ data => { data.delta.files++; },+ data => { data.delta.dirs--; },+ data => { data.delta.size = 0; },+ data => { data.previous.total_size = 0; },+ data => { data.previous.total_files = expected.total_files; },+ ]) {+ const input = comparison();+ change(input);+ assert.throws(() => parse(input), /does not match/);+ }+});++test("invalid numbers, timestamps and shapes are rejected", () => {+ for (const field of ["total_files", "total_dirs", "total_size"]) for (const value of [-1, 0.5, null, "5", Number.MAX_SAFE_INTEGER + 1]) {+ const input = comparison();+ input.previous[field] = value;+ input.delta[field === "total_size" ? "size" : field === "total_files" ? "files" : "dirs"] = expected[field] - (value >= 0 && Number.isInteger(value) ? value : 0);+ assert.throws(() => parse(input), /does not match/);+ }+ for (const value of [0, -1, 0.5, 8_640_000_000_001, Number.MAX_SAFE_INTEGER + 1]) {+ assert.throws(() => parse({ ...comparison(), previous: { ...comparison().previous, recorded_at: value } }), /does not match/);+ }+ for (const change of [+ data => { delete data.first; },+ data => { data.first = "yes"; },+ data => { data.previous = null; },+ data => { data.delta = { files: 1, dirs: 0 }; },+ data => { data.delta = { files: 1.5, dirs: 0, size: 0 }; },+ ]) {+ const input = comparison();+ change(input);+ assert.throws(() => parse(input), /does not match/);+ }+});++test("malformed JSON and non-object payloads fail at the query boundary", () => {+ for (const raw of ["{", "null", "[]", "5", '"text"']) assert.throws(() => parseScanComparison(raw, expected));+});+++test("production first-scan wire fixture is accepted", async () => {+ const raw = await readFile(new URL("fixtures/scan-history-first.json", import.meta.url), "utf8");+ assert.equal(parseScanComparison(raw, { ...expected, generation: "generation-b", revision: 0 }).first, true);+});diff --git a/tests/scan_ui_fixture.js b/tests/scan_ui_fixture.jsindex 4a68364..c80a918 100644--- a/tests/scan_ui_fixture.js+++ b/tests/scan_ui_fixture.js@@ -30,6 +30,7 @@let discoveryError = false;const discoveryDump = "adb devices -l failed (exit 1):\n* daemon not running; starting now at tcp:5037\nADB server didn't ACK\nFull server startup log: /tmp/adb.fixture.log\ncould not install *smartsocket* listener: Address already in use\n<img src=invalid onerror=alert(1)>\n" + "startup diagnostics\n".repeat(2000);let activeDevice = null;+ const scanRecords = [];let callbacks = 0;let rootChildren;let folderChildren;@@ -93,7 +94,19 @@activeDevice = args.serial;return "Mock daemon";}- if (command === "run_scan") { generation++; reset(); return JSON.stringify(summary()); }+ if (command === "run_scan") {+ generation++;+ reset();+ const stats = summary();+ scanRecords.push({+ generation: scope().generation,+ device: activeDevice,+ readOnly, errors: stats.errors, skipped: stats.skipped, root: stats.root_path,+ totals: { total_files: stats.total_files, total_dirs: stats.total_dirs, total_size: stats.total_size },+ at: Date.now(),+ });+ return JSON.stringify(stats);+ }if (command === "stop_daemon") {await pause(150);unavailable = true;@@ -125,6 +138,25 @@if (delayedLargest) { delayedLargest = false; await pause(300); }return response;}+ if (command === "get_scan_comparison") {+ // Same shape as the Rust query: the delta compares the live totals+ // with the previous scan of the same device, so deletions count.+ const current = scanRecords.find(record => record.generation === scope().generation);+ check(current, "Comparison requested for an unknown mock scan");+ check(current.errors === 0, "Scans with access errors are not recorded as history baselines");+ const previous = scanRecords.slice(0, scanRecords.indexOf(current)).reverse()+ .find(record => record.errors === 0 && record.device === current.device+ && record.readOnly === current.readOnly && record.root === current.root && record.skipped === current.skipped);+ if (!previous) return JSON.stringify({ ...scope(), first: true, previous: null, delta: null });+ const stats = summary();+ return JSON.stringify({ ...scope(), first: false,+ previous: { recorded_at: Math.floor(previous.at / 1000), ...previous.totals },+ delta: {+ files: stats.total_files - previous.totals.total_files,+ dirs: stats.total_dirs - previous.totals.total_dirs,+ size: stats.total_size - previous.totals.total_size,+ } });+ }if (command === "get_scan_view") {const response = JSON.stringify(view(args));if (args.nodeId === 1 && delayedZoom) { delayedZoom = false; await pause(300); }@@ -158,7 +190,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", "bounded collapsed discovery diagnostics", "discovery retry recovery", "setup alignment", "result fonts", "file label semantics", "complete paging", "bounded file-type totals", "file-type retry and malformed response", "file-type generation and deletion revision", "file-type coverage and empty scan", "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 });+ output.textContent = JSON.stringify({ fixture: "scan-ui", passed, error, ipc_calls: calls.length, checks: passed ? ["offline fonts under CSP", "bounded collapsed discovery diagnostics", "discovery retry recovery", "setup alignment", "result fonts", "file label semantics", "complete paging", "first-scan comparison", "unchanged comparison after rescan", "deletion delta comparison", "cross-device comparison isolation", "bounded file-type totals", "file-type retry and malformed response", "file-type generation and deletion revision", "file-type coverage and empty scan", "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");@@ -244,6 +276,7 @@document.querySelector("#btn-connect").click();await waitFor(() => rows().length === 129, "Initial page did not render 128 children");check(activeDevice === "phone-two" && document.querySelector("#connected-device").textContent.includes("phone-two"), "Results do not identify the selected device");+ await waitFor(() => document.querySelector("#scan-history")?.textContent.includes("No previous comparable scan"), "First-scan comparison missing");const logRows = [...document.querySelectorAll("#terminal-log .log-entry")];check(logRows.some(row => row.textContent.includes("[ADB] Found:") && row.textContent.includes("… [truncated]")), "App did not bound oversized diagnostics");check(logRows.every(row => row.textContent.length < 4200), "App retained oversized log text");@@ -347,6 +380,7 @@document.querySelector('[aria-label="Delete file-0 "]').click();document.querySelector("#btn-rescan").click();await waitFor(() => rows().length === 129, "Rescan did not reload");+ await waitFor(() => document.querySelector("#scan-history")?.textContent.includes("No change since"), "Unchanged comparison missing after rescan");await pause(350);check(!button("NUKE IT"), "Old confirmation survived rescan");button("Largest files").click();@@ -356,6 +390,9 @@check(document.body.textContent.includes("/fixture/ file-0 "), "Exact confirmation path missing");button("NUKE IT").click();await waitFor(() => largestRows().length === 25 && !document.querySelector('[aria-label="Delete file-0 "]'), "Deleted largest row survived revision refresh");+ const historyLine = () => document.querySelector("#scan-history")?.textContent ?? "";+ await waitFor(() => historyLine().includes("Since the previous scan"), "Deletion delta comparison missing");+ check(historyLine().includes("-1 files"), "Deletion did not change the comparison delta");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");@@ -395,6 +432,7 @@document.querySelector("#btn-connect").click();await waitFor(() => rows().length === 129, "Read-only page missing");check(document.body.textContent.includes("Deletion disabled"), "Read-only banner missing");+ await waitFor(() => document.querySelector("#scan-history")?.textContent.includes("comparison unavailable"), "Partial scan claimed a history comparison");check(!document.querySelector('[aria-label^="Delete "]'), "Read-only deletion enabled");button("Largest files").click();await waitFor(() => largestRows().length === 25, "Read-only largest files missing");@@ -438,6 +476,7 @@document.querySelector("#btn-connect").click();await waitFor(() => rows().length === 129, "Explicit device switch did not scan");check(activeDevice === "phone-one" && scope().generation !== previousGeneration && document.querySelector("#connected-device").textContent.includes("phone-one"), "Device switch reused old results/identity");+ await waitFor(() => document.querySelector("#scan-history")?.textContent.includes("No previous comparable scan"), "Cross-device comparison reused another device's baseline");check(!button("NUKE IT"), "Device switch retained a destructive confirmation");const deleteCallsBeforeSwitch = calls.filter(call => call.command === "delete_item").length;document.querySelector('[aria-label="Delete file-0 "]').click();