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

Keep scan records in Rust with generation-scoped directory queries (#51)

Vishnu Srivatsava5ed6fbf92b07
diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml
index f9950ed..7096cbd 100644
--- a/.github/workflows/build.yml
+++ b/.github/workflows/build.yml
@@ -193,6 +193,10 @@ jobs:
- name: Test Rust bridge
run: cargo test --locked --manifest-path src-tauri/Cargo.toml --lib
+ - name: Test built scan UI with mocked IPC
+ if: runner.os == 'Linux'
+ run: python3 tests/check_scan_ui.py
+
# ── Fix AppImage: guarantee root icon + .DirIcon + sane modes ─────────
# Required for AppImage catalog validation. tauri-bundler 2.11.1 emits a
# .DirIcon whose target is an ABSOLUTE path into the build machine
diff --git a/docs/scan-store.md b/docs/scan-store.md
new file mode 100644
index 0000000..7c3844c
--- /dev/null
+++ b/docs/scan-store.md
@@ -0,0 +1,123 @@
+# Host-owned scan store
+
+A successful stream transfers verified records to Rust. `run_scan` returns
+statistics, the root summary, and a fresh public generation rather than a
+nested tree. Generations use independent random IDs; the daemon's secret
+session token never crosses IPC.
+
+`get_scan_view` accepts a generation, revision, node ID and optional cursor.
+It returns the current node, exact path, breadcrumbs, up to 128 children, and
+previous/next cursors. Directory indexes sort by size descending, name, then
+stable ID. Cursor seeks use `BTreeSet` ranges instead of walking earlier pages.
+All entries remain reachable; there is no silent 500-entry cutoff.
+
+The chart contains the largest 64 positive children plus an exact **Other**
+remainder. Other has no node ID and cannot zoom or delete. Recharts remains in
+use; #31 covers its separate SVG replacement. #30 still covers virtualized
+rows and broader navigation work.
+
+## Snapshot and deletion invariants
+
+- Starting a scan, reconnecting or stopping invalidates the current store
+ before fallible I/O. Completion publishes only after verified counts,
+ terminal EOF, bounded metadata serialization and the cancellation gate.
+- Every query, detail request, cursor and delete requires the current generation
+ and revision. IDs never renumber within a generation. Deleted nodes and their
+ descendants become unavailable; revision changes invalidate older cursors.
+- `delete_item` accepts IDs, never a frontend path. Rust reconstructs the exact
+ accepted UTF-8 path, refuses the root/read-only entries and line-protocol
+ delimiters/oversized commands, then uses the existing authenticated command
+ and descriptor-anchored C++ deletion boundary.
+- Successful deletion adjusts subtree counts/sizes along the ancestor chain,
+ updates directory indexes and advances the revision. JavaScript receives a
+ new summary and reloads visible pages; it does not clone a full tree.
+- Transport errors, malformed results and partial deletion failures quarantine
+ the snapshot. The UI discards results and returns to setup after stopping the
+ session. An obsolete result cannot clear a newer generation.
+- Connection/scan/delete operations share the existing operation lock. Queries
+ take only the store lock, with no network I/O while holding it. Queries see a
+ complete revision or fail as stale. Late UI responses cannot replace newer
+ requests, and old confirmations cannot survive a rescan.
+
+Stream v1 does not encode arbitrary raw-byte names. Non-UTF-8 data is rejected,
+never replaced with a different filename. Accepted names retain their bytes;
+full paths are reconstructed transiently, not stored on every UI row. Deleted
+subtree records remain allocated until the next scan/disconnect; tombstones
+preserve ID safety.
+
+The decoder keeps its existing 2,000,000-entry, depth-64, 16-KiB-path and
+128-MiB conservative ingestion bounds. Its estimate includes record/name/index
+and staging costs. Each query/summary/deletion response has a 1-MiB serialized
+limit; small daemon command replies have a 128-KiB read limit. These are data
+budgets, not a total-process RSS guarantee. `sort_ms` includes host aggregation,
+sorting and index construction; daemon timing fields retain their meanings.
+
+## Validation
+
+```sh
+npm test
+npm run build
+cargo test --locked --manifest-path src-tauri/Cargo.toml --lib
+cargo clippy --locked --manifest-path src-tauri/Cargo.toml --lib --tests -- -D warnings
+python3 -m unittest discover -s tests -v
+python3 tests/check_scan_ui.py
+python3 tests/benchmark_scan_store.py
+```
+
+The last two commands support macOS/Linux. The UI harness uses installed
+Chrome/Chromium (an executable may be passed as its first argument), the actual
+built frontend, and mocked IPC. It checks forward/backward paging, nested
+paging, delayed zoom, the Other tile, stale confirmation after rescan, ID-only
+deletion, revision refresh, partial-error recovery and read-only controls. It
+never launches Tauri or contacts ADB. Linux CI runs it after the desktop build;
+all three desktop targets run Rust and Node tests.
+
+Rust fixtures compare ordering, paths, parents and totals against the previous
+recursive representation, including repeated file/directory deletions,
+placeholders, a 64-level path, stale references and concurrent reads. Host daemon
+fixtures verify non-UTF-8 bytes on filesystems that support them; unsupported
+filesystems skip that case. The decoder also rejects invalid encoding directly.
+
+Native WebView behavior and connected-device interaction remain manual checks.
+To try the rebuilt host with the existing daemon:
+
+```sh
+npm run tauri dev
+```
+
+Check expansion, both page directions in a large directory, zoom/breadcrumbs,
+rescan/cancel, reconnect and read-only mode. If testing deletion, create a
+throwaway file/directory first and confirm its exact path and updated totals.
+The Android engine has not changed and does not need rebuilding for this PR.
+
+## Host fixture measurements
+
+On 2026-10-14, Darwin arm64, Rust 1.95.0 and Node 26.7.0, three release-harness
+runs used identical stream-v1 bytes: 86,666 synthetic files in 32 directories
+plus their root. Sizes are generated values; these are not phone measurements.
+Baseline: `9326b4221adb410c3cbf8562e2777471a4c30083`.
+
+| Metric (median of three runs) | Full-tree baseline | Host store |
+| --- | ---: | ---: |
+| IPC payload | 8,660,446 bytes | 27,606 bytes |
+| Host decode/build/serialize/file-write time | 58.80 ms | 32.36 ms |
+| Peak host RSS | 19,169,280 bytes | 17,317,888 bytes |
+| Node parse time | 27.21 ms | 0.17 ms |
+| Node full-tree clone time | 26.75 ms | No full-tree clone |
+| Node heap growth at measurement | 35,155,320 bytes | 248,272 bytes |
+| Peak Node RSS | 135,216 KiB | 49,184 KiB |
+
+The store payload includes the summary, root page and one 128-entry directory
+page. The baseline sends the whole tree. Node retains the baseline plus its
+copy to represent the old deletion path; the new model retains metadata/pages.
+RSS includes each runtime, and heap growth is a sampled value, not a GC-adjusted
+retained-size or peak-heap claim. These measurements exclude Tauri string
+encoding, WebView/React rendering, ADB and daemon traversal. Visiting every
+page creates additional bounded requests; the table measures initial browsing.
+The benchmark verifies totals, sample directory ordering and exact chart sums.
+It does not establish a change in Android scan speed or compare C++ with Rust.
+
+The ownership/query idea is inspired by
+[Shanmukh's fork](https://github.com/ksaishanmukh/SocketSweep/tree/d677b530e00dec75c305fc56318720aa8c161692),
+particularly `e7a7383`, `b0087a9` and `b03ae60`. The C++ daemon, authenticated
+transport and existing secure deletion boundary remain in place.
diff --git a/docs/scan-stream-v1.md b/docs/scan-stream-v1.md
index 726b685..62c397a 100644
--- a/docs/scan-stream-v1.md
+++ b/docs/scan-stream-v1.md
@@ -64,7 +64,7 @@ invalid ordering, mismatched counts, and any data after completion are errors.
Error counts and exclusions remain visible even for a successfully completed
scan with unreadable areas. Partial/cancelled scans are never successful
baselines. The bridge clears its deletion root before each attempt and only
-sets it after valid completion/EOF and successful response serialization.
+publishes its scan store after valid completion/EOF and bounded metadata serialization.
The daemon pins its pending root separately and promotes it only after an
unchanged-root check and successful completion write. Existing descriptor-
anchored deletion and root read-only checks remain in force.
@@ -87,7 +87,7 @@ interruptible by this socket cancellation mechanism.
The host accepts at most 2,000,000 records, depth 64, and path length 16 KiB.
A conservative catalog estimate (path bytes, name bytes, 256 bytes per node)
-is capped at 128 MiB; the final UI JSON is capped at 256 MiB. Integer values and
+is capped at 128 MiB; each UI query is capped at 1 MiB. Integer values and
computed totals must fit JavaScript's exact integer range. These are data
budgets, not promises that total process RSS equals those limits.
@@ -98,19 +98,19 @@ cannot affect a different scan ID. Cancellation bypasses the serialized
operation lock and closes the active socket. The UI discards failed rescan
results and returns to setup, avoiding actions based on an obsolete tree.
-The host keeps compact names, links and sizes, derives subtree totals, and
-serializes paths directly into the existing dashboard response. It does not
-buffer the whole wire response or build a second recursive host tree. The
-finished frontend still receives one full tree and locally clones it after
-deletion. Persistent Rust ownership, bounded queries and progressive browsing
-remain #29/#30 work; this change provides partial counts/recent entries during
-scanning rather than a browsable incomplete dashboard.
+The host retains compact verified records and directory indexes in a
+[generation-scoped scan store](scan-store.md). The frontend receives metadata,
+128-entry directory pages, and a bounded chart instead of the whole tree.
+Deletion updates host totals and advances the revision; JavaScript does not
+clone or edit a full tree. Scanning still shows partial counts/recent entries,
+not a browsable incomplete dashboard. Virtualized rows and the separate SVG
+chart work remain #30/#31.
## Timing and attribution
For streamed scans, `scan_time_ms`/`traverse_ms` measure daemon traversal with
interleaved encoding/writes. `serialize_ms` and `send_ms` are cumulative daemon
-encoding/write times; `sort_ms` measures host aggregation/sorting. These overlap
+encoding/write times; `sort_ms` measures host aggregation/sorting and directory index construction. These overlap
and must not be added or compared directly with the old exclusive phase split.
Final host response serialization and frontend rendering are not included.
diff --git a/package.json b/package.json
index 0738725..451a89f 100644
--- a/package.json
+++ b/package.json
@@ -7,7 +7,7 @@
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
- "test": "node --test tests/format_bytes.test.mjs",
+ "test": "node --test tests/format_bytes.test.mjs tests/scan_view.test.mjs",
"preview": "vite preview",
"tauri": "tauri"
},
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index cb7e81a..7dde1cf 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -18,6 +18,7 @@ use std::net::{Shutdown, TcpStream};
use std::sync::{Arc, atomic::{AtomicBool, Ordering}};
use tauri::ipc::Channel;
mod scan_stream;
+mod scan_store;
use std::process::Command;
use std::sync::Mutex;
use std::time::Duration;
@@ -29,10 +30,17 @@ const DAEMON_ADDR: &str = "127.0.0.1:5050";
const DEVICE_BIN_PATH: &str = "/data/local/tmp/socketsweep_daemon";
const DEVICE_TOKEN_PATH: &str = "/data/local/tmp/socketsweep_token";
const TCP_CONNECT_TIMEOUT: Duration = Duration::from_secs(5);
+const MAX_COMMAND_BYTES: usize = 16 * 1024;
+const MAX_COMMAND_RESPONSE_BYTES: usize = 128 * 1024;
const TCP_READ_TIMEOUT: Duration = Duration::from_secs(120); // scans can be slow
-/// Tracks the root path of the last successful scan so we can prevent its deletion.
-static SCAN_ROOT: Mutex<Option<String>> = Mutex::new(None);
+/// Only complete, current snapshots authorize queries and deletion IDs.
+static SCAN_STORE: Mutex<Option<scan_store::Catalog>> = Mutex::new(None);
+
+fn invalidate_scan() -> Result<(), String> {
+ *SCAN_STORE.lock().map_err(|_| "Scan state is unavailable")? = None;
+ Ok(())
+}
/// Tracks the serial of the connected device so all ADB calls target the right device.
static DEVICE_SERIAL: Mutex<Option<String>> = Mutex::new(None);
@@ -211,7 +219,7 @@ fn daemon_command(cmd: &str) -> Result<String, String> {
}
fn command_payload(cmd: &str, token: &str) -> Result<String, String> {
- if cmd.is_empty() || cmd.len() > 16 * 1024 || cmd.contains(['\r', '\n', '\0']) {
+ if cmd.is_empty() || cmd.len() > MAX_COMMAND_BYTES || cmd.contains(['\r', '\n', '\0']) {
return Err("This path cannot be sent safely: it contains a line break or null byte, or is too long.".into());
}
Ok(format!("AUTH {token}\n{cmd}\n"))
@@ -234,8 +242,9 @@ fn daemon_command_with_token(cmd: &str, token: &str) -> Result<String, String> {
.write_all(payload.as_bytes())
.map_err(|e| format!("Failed to send command to daemon: {e}"))?;
- let mut response_bytes = Vec::with_capacity(1024 * 1024);
+ let mut response_bytes = Vec::with_capacity(1024);
stream
+ .take((MAX_COMMAND_RESPONSE_BYTES + 1) as u64)
.read_to_end(&mut response_bytes)
.map_err(|e| format!("Failed to read daemon response: {e}"))?;
@@ -243,6 +252,9 @@ fn daemon_command_with_token(cmd: &str, token: &str) -> Result<String, String> {
}
fn decode_daemon_response(bytes: Vec<u8>) -> Result<String, String> {
+ if bytes.len() > MAX_COMMAND_RESPONSE_BYTES {
+ return Err("Daemon command response exceeds limit".into());
+ }
// Replacement characters would change paths, potentially selecting a
// different file when a displayed node is later deleted.
String::from_utf8(bytes)
@@ -284,9 +296,9 @@ fn require_ok(response: &str) -> Result<DaemonStatus, String> {
Ok(parsed)
}
-fn new_session_token() -> Result<String, String> {
+fn new_random_id() -> Result<String, String> {
let mut bytes = [0_u8; 32];
- getrandom::fill(&mut bytes).map_err(|e| format!("Failed to create daemon session: {e}"))?;
+ getrandom::fill(&mut bytes).map_err(|e| format!("Failed to create secure identifier: {e}"))?;
Ok(bytes.iter().map(|byte| format!("{byte:02x}")).collect())
}
@@ -303,12 +315,12 @@ fn check_adb(app: tauri::AppHandle) -> Result<String, String> {
#[tauri::command(async)]
fn init_daemon(app: tauri::AppHandle, root_mode: Option<bool>) -> Result<String, String> {
let _operation = DAEMON_OPERATION.lock().map_err(|_| "Daemon state is unavailable")?;
+ invalidate_scan()?;
let has_session = DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")?.is_some();
if has_session {
stop_daemon_inner(&app)?;
}
*SESSION_TOKEN.lock().map_err(|_| "Session state is unavailable")? = None;
- *SCAN_ROOT.lock().map_err(|_| "Scan state is unavailable")? = None;
*DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")? = None;
*READ_ONLY.lock().map_err(|_| "Session state is unavailable")? = false;
*DEVICE_PRIVILEGE.lock().map_err(|_| "Device state is unavailable")? = Privilege::Shell;
@@ -368,7 +380,7 @@ fn init_daemon_inner(app: tauri::AppHandle, root_mode: bool) -> Result<String, S
// Transfer the fresh secret over stdin into a shell-owned file. Neither
// the startup arguments nor the frontend response contain the secret.
- let token = new_session_token()?;
+ let token = new_random_id()?;
let serial = DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")?
.clone().ok_or("No connected device")?;
let token_cmd = format!("rm -f {DEVICE_TOKEN_PATH} && umask 077 && cat > {DEVICE_TOKEN_PATH}");
@@ -499,7 +511,7 @@ fn run_scan(
let _operation = DAEMON_OPERATION
.lock()
.map_err(|_| "Daemon state is unavailable")?;
- *SCAN_ROOT.lock().map_err(|_| "Scan state is unavailable")? = None;
+ invalidate_scan()?;
let effective_root = path
.filter(|p| !p.is_empty())
.unwrap_or_else(|| "/sdcard".into());
@@ -573,17 +585,17 @@ fn run_scan(
return Err("Daemon scanned an unexpected root".into());
}
}
- let json = response.json()?;
- // Serialize before authorization too: a result exceeding the UI limit
- // must not leave a bridge deletion root behind.
+ // Public snapshot generations are independent of the secret daemon token.
+ let catalog = scan_store::Catalog::new(response, new_random_id()?);
+ let json = catalog.summary_json()?;
+ // Serialize bounded metadata before publishing deletion authority.
let mut active = ACTIVE_SCAN
.lock()
.map_err(|_| "Scan state is unavailable")?;
if cancelled.load(Ordering::SeqCst) {
return Err("Scan cancelled".into());
}
- *SCAN_ROOT.lock().map_err(|_| "Scan state is unavailable")? =
- Some(response.root().to_string());
+ *SCAN_STORE.lock().map_err(|_| "Scan state is unavailable")? = Some(catalog);
active.take();
Ok(json)
})();
@@ -607,6 +619,7 @@ fn stop_daemon(app: tauri::AppHandle) -> Result<String, String> {
}
fn stop_daemon_inner(app: &tauri::AppHandle) -> Result<String, String> {
+ invalidate_scan()?;
let adb_path = get_bundled_binary(app, "adb")?;
let response = daemon_command("SHUTDOWN");
let has_device = DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")?.is_some();
@@ -618,7 +631,6 @@ fn stop_daemon_inner(app: &tauri::AppHandle) -> Result<String, String> {
let _ = adb_s(&adb_path, &["shell", "rm", "-f", DEVICE_BIN_PATH, DEVICE_TOKEN_PATH]);
}
*SESSION_TOKEN.lock().map_err(|_| "Session state is unavailable")? = None;
- *SCAN_ROOT.lock().map_err(|_| "Scan state is unavailable")? = None;
*DEVICE_SERIAL.lock().map_err(|_| "Device state is unavailable")? = None;
*DEVICE_PRIVILEGE.lock().map_err(|_| "Device state is unavailable")? = Privilege::Shell;
*READ_ONLY.lock().map_err(|_| "Session state is unavailable")? = false;
@@ -626,22 +638,43 @@ fn stop_daemon_inner(app: &tauri::AppHandle) -> Result<String, String> {
}
#[tauri::command(async)]
-fn delete_item(path: String) -> Result<String, String> {
- let _operation = DAEMON_OPERATION.lock().map_err(|_| "Daemon state is unavailable")?;
- if *READ_ONLY.lock().map_err(|_| "Session state is unavailable")? {
- return Err("Root scans are read-only; deletion is disabled.".into());
- }
- // Prevent deletion of the scan root directory.
- let root = SCAN_ROOT.lock().map_err(|_| "Scan state is unavailable")?;
- match root.as_ref() {
- Some(scan_root) if path == *scan_root => {
- return Err("Cannot delete the scan root directory.".into());
- }
- None => return Err("Scan your device before deleting files.".into()),
- _ => {}
- }
- drop(root);
- daemon_command(&format!("DELETE {path}"))
+fn get_scan_view(
+ generation: String,
+ revision: u32,
+ node_id: u32,
+ cursor: Option<scan_store::Cursor>,
+) -> Result<String, String> {
+ let store = SCAN_STORE.lock().map_err(|_| "Scan state is unavailable")?;
+ store
+ .as_ref()
+ .ok_or("Scan is unavailable; rescan required")?
+ .view_json(&generation, revision, node_id, cursor)
+}
+
+#[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")?;
+ store
+ .as_ref()
+ .ok_or("Scan is unavailable; rescan required")?
+ .detail_json(&generation, revision, node_id)
+}
+
+#[tauri::command(async)]
+fn delete_item(generation: String, revision: u32, node_id: u32) -> Result<String, String> {
+ let _operation = DAEMON_OPERATION
+ .lock()
+ .map_err(|_| "Daemon state is unavailable")?;
+ let plan = {
+ let store = SCAN_STORE.lock().map_err(|_| "Scan state is unavailable")?;
+ store
+ .as_ref()
+ .ok_or("Scan your device before deleting files.")?
+ .prepare_delete(&generation, revision, node_id)?
+ };
+ let response = daemon_command(&format!("DELETE {}", plan.path));
+ let mut store = SCAN_STORE.lock().map_err(|_| "Scan state is unavailable")?;
+ scan_store::finish_delete(&mut store, &plan, response)
}
// ── Tauri entry point ───────────────────────────────────────────────────────
@@ -658,6 +691,8 @@ pub fn run() {
ping_daemon,
stop_daemon,
delete_item,
+ get_scan_view,
+ get_scan_node,
])
.run(tauri::generate_context!())
.expect("error while running tauri application");
@@ -722,9 +757,9 @@ mod tests {
}
#[test]
- fn session_tokens_are_fresh_and_have_full_entropy() {
- let first = new_session_token().unwrap();
- let second = new_session_token().unwrap();
+ fn random_identifiers_are_fresh_and_have_full_entropy() {
+ let first = new_random_id().unwrap();
+ let second = new_random_id().unwrap();
assert_eq!(first.len(), 64);
assert!(first.bytes().all(|b| b.is_ascii_hexdigit()));
assert_ne!(first, second);
@@ -764,6 +799,12 @@ mod tests {
drop(ScanRegistration("next".into()));
}
+ #[test]
+ fn small_command_responses_have_a_hard_byte_limit() {
+ assert!(decode_daemon_response(vec![b'x'; MAX_COMMAND_RESPONSE_BYTES]).is_ok());
+ assert!(decode_daemon_response(vec![b'x'; MAX_COMMAND_RESPONSE_BYTES + 1]).is_err());
+ }
+
#[test]
fn invalid_filename_bytes_are_not_replaced() {
assert!(decode_daemon_response(b"{\"path\":\"/sdcard/report\xff\"}".to_vec()).is_err());
diff --git a/src-tauri/src/scan_store.rs b/src-tauri/src/scan_store.rs
new file mode 100644
index 0000000..20768ee
--- /dev/null
+++ b/src-tauri/src/scan_store.rs
@@ -0,0 +1,963 @@
+//! One verified scan owns all records. UI IDs/cursors require its generation
+//! and revision; paths are reconstructed here from exact validated names.
+use crate::scan_stream::{Kind, Node, Response, NONE};
+use serde::{Deserialize, Serialize};
+use std::cmp::Reverse;
+use std::collections::BTreeSet;
+use std::io::Write;
+use std::ops::Bound::{Excluded, Unbounded};
+use std::sync::Arc;
+use std::time::Instant;
+
+pub const PAGE_SIZE: usize = 128;
+const CHART_SIZE: usize = 64;
+const MAX_QUERY_BYTES: usize = 1024 * 1024;
+type Key = (Reverse<u64>, Arc<str>, u32);
+
+pub struct Catalog {
+ generation: String,
+ revision: u32,
+ response: Response,
+ children: Vec<BTreeSet<Key>>,
+}
+#[derive(Clone, Copy, Deserialize, Serialize)]
+#[serde(rename_all = "snake_case")]
+pub enum Direction {
+ Next,
+ Previous,
+}
+#[derive(Clone, Copy, Deserialize, Serialize)]
+#[serde(deny_unknown_fields)]
+pub struct Cursor {
+ direction: Direction,
+ node_id: u32,
+}
+#[derive(Serialize)]
+struct NodeSummary<'a> {
+ id: u32,
+ parent_id: Option<u32>,
+ name: &'a str,
+ #[serde(rename = "type")]
+ kind: &'static str,
+ size: u64,
+ counted: bool,
+ child_count: usize,
+ can_delete: bool,
+}
+#[derive(Serialize)]
+struct Summary<'a> {
+ #[serde(flatten)]
+ stats: &'a Response,
+ generation: &'a str,
+ revision: u32,
+ root_path: &'a str,
+ root: NodeSummary<'a>,
+}
+#[derive(Serialize)]
+struct Breadcrumb<'a> {
+ id: u32,
+ name: &'a str,
+}
+#[derive(Serialize)]
+struct Tile<'a> {
+ node_id: Option<u32>,
+ name: &'a str,
+ size: u64,
+}
+#[derive(Serialize)]
+struct View<'a> {
+ generation: &'a str,
+ revision: u32,
+ node: NodeSummary<'a>,
+ path: String,
+ breadcrumbs: Vec<Breadcrumb<'a>>,
+ children: Vec<NodeSummary<'a>>,
+ previous_cursor: Option<Cursor>,
+ next_cursor: Option<Cursor>,
+ chart: Vec<Tile<'a>>,
+}
+// Prepared only while the operation lock is held. No frontend path enters a
+// destructive command. Queries release their lock before any network I/O.
+pub struct DeletePlan {
+ generation: String,
+ revision: u32,
+ node_id: u32,
+ pub path: String,
+}
+
+fn json(value: &impl Serialize) -> Result<String, String> {
+ struct Limited(Vec<u8>);
+ impl Write for Limited {
+ fn write(&mut self, bytes: &[u8]) -> std::io::Result<usize> {
+ if bytes.len() > MAX_QUERY_BYTES.saturating_sub(self.0.len()) {
+ return Err(std::io::Error::other("Scan query exceeds response limit"));
+ }
+ self.0.extend_from_slice(bytes);
+ Ok(bytes.len())
+ }
+ fn flush(&mut self) -> std::io::Result<()> {
+ Ok(())
+ }
+ }
+ let mut output = Limited(Vec::new());
+ serde_json::to_writer(&mut output, value).map_err(|e| format!("Cannot display scan: {e}"))?;
+ String::from_utf8(output.0).map_err(|_| "Invalid scan encoding".into())
+}
+impl Catalog {
+ pub fn new(mut response: Response, generation: String) -> Self {
+ let started = Instant::now();
+ let mut children = vec![BTreeSet::new(); response.nodes.len()];
+ for (id, node) in response.nodes.iter().enumerate().skip(1) {
+ children[node.parent as usize].insert((
+ Reverse(node.size),
+ node.name.clone(),
+ id as u32,
+ ));
+ }
+ response.sort_ms += started.elapsed().as_millis() as u64;
+ Self {
+ generation,
+ revision: 0,
+ response,
+ children,
+ }
+ }
+ fn scope(&self, generation: &str, revision: u32) -> Result<(), String> {
+ if generation != self.generation || revision != self.revision {
+ return Err("Scan changed; refresh before continuing.".into());
+ }
+ Ok(())
+ }
+ fn node(&self, id: u32) -> Result<&Node, String> {
+ let node = self
+ .response
+ .nodes
+ .get(id as usize)
+ .ok_or("Invalid scan node")?;
+ let mut current = id;
+ while current != NONE {
+ let ancestor = &self.response.nodes[current as usize];
+ if ancestor.deleted {
+ return Err("Scan node is no longer available".into());
+ }
+ current = ancestor.parent;
+ }
+ Ok(node)
+ }
+ fn path(&self, id: u32) -> String {
+ let mut names = Vec::new();
+ let mut current = id;
+ while current != 0 {
+ let node = &self.response.nodes[current as usize];
+ names.push(node.name.as_ref());
+ current = node.parent;
+ }
+ let mut path = self.response.root.clone();
+ for name in names.into_iter().rev() {
+ if path != "/" {
+ path.push('/');
+ }
+ path.push_str(name);
+ }
+ path
+ }
+ fn can_delete(&self, id: u32) -> bool {
+ // Line protocol cannot represent CR/LF. Never replace or normalize
+ // these bytes: show the entry, but require deletion outside this app.
+ let path = self.path(id);
+ id != 0
+ && !self.response.read_only
+ && path.len() + "DELETE ".len() <= crate::MAX_COMMAND_BYTES
+ && !path.contains(['\r', '\n', '\0'])
+ }
+ fn summary_node(&self, id: u32) -> NodeSummary<'_> {
+ let node = &self.response.nodes[id as usize];
+ NodeSummary {
+ id,
+ parent_id: (node.parent != NONE).then_some(node.parent),
+ name: &node.name,
+ kind: if node.kind == Kind::Directory {
+ "directory"
+ } else {
+ "file"
+ },
+ size: node.size,
+ counted: node.counted,
+ child_count: self.children[id as usize].len(),
+ can_delete: self.can_delete(id),
+ }
+ }
+ fn summary(&self) -> Summary<'_> {
+ Summary {
+ stats: &self.response,
+ generation: &self.generation,
+ revision: self.revision,
+ root_path: &self.response.root,
+ root: self.summary_node(0),
+ }
+ }
+ pub fn summary_json(&self) -> Result<String, String> {
+ json(&self.summary())
+ }
+ fn key(&self, id: u32) -> Key {
+ let node = &self.response.nodes[id as usize];
+ (Reverse(node.size), node.name.clone(), id)
+ }
+ pub fn view_json(
+ &self,
+ generation: &str,
+ revision: u32,
+ id: u32,
+ cursor: Option<Cursor>,
+ ) -> Result<String, String> {
+ self.scope(generation, revision)?;
+ self.node(id)?;
+ let children = &self.children[id as usize];
+ let keys: Vec<&Key> = if let Some(cursor) = cursor {
+ let child = self.node(cursor.node_id)?;
+ if child.parent != id {
+ return Err("Invalid directory cursor".into());
+ }
+ let key = self.key(cursor.node_id);
+ if !children.contains(&key) {
+ return Err("Invalid directory cursor".into());
+ }
+ match cursor.direction {
+ Direction::Next => children
+ .range((Excluded(key), Unbounded))
+ .take(PAGE_SIZE)
+ .collect(),
+ Direction::Previous => {
+ let mut page: Vec<_> = children
+ .range((Unbounded, Excluded(key)))
+ .rev()
+ .take(PAGE_SIZE)
+ .collect();
+ page.reverse();
+ page
+ }
+ }
+ } else {
+ children.iter().take(PAGE_SIZE).collect()
+ };
+ // A fabricated boundary cursor must not hide a nonempty directory.
+ if keys.is_empty() && !children.is_empty() {
+ return Err("Directory cursor has no page".into());
+ }
+ let previous_cursor = keys
+ .first()
+ .filter(|key| {
+ children
+ .range((Unbounded, Excluded((**key).clone())))
+ .next()
+ .is_some()
+ })
+ .map(|key| Cursor {
+ direction: Direction::Previous,
+ node_id: key.2,
+ });
+ let next_cursor = keys
+ .last()
+ .filter(|key| {
+ children
+ .range((Excluded((**key).clone()), Unbounded))
+ .next()
+ .is_some()
+ })
+ .map(|key| Cursor {
+ direction: Direction::Next,
+ node_id: key.2,
+ });
+ let mut breadcrumbs = Vec::new();
+ let mut current = id;
+ while current != NONE {
+ let node = &self.response.nodes[current as usize];
+ breadcrumbs.push(Breadcrumb {
+ id: current,
+ name: &node.name,
+ });
+ current = node.parent;
+ }
+ breadcrumbs.reverse();
+ let mut chart: Vec<_> = children
+ .iter()
+ .take(CHART_SIZE)
+ .filter(|key| key.0 .0 > 0)
+ .map(|key| Tile {
+ node_id: Some(key.2),
+ name: &key.1,
+ size: key.0 .0,
+ })
+ .collect();
+ let remainder =
+ self.response.nodes[id as usize].size - chart.iter().map(|tile| tile.size).sum::<u64>();
+ // File views have no children; their bytes must not become an Other tile.
+ if remainder > 0 && !children.is_empty() {
+ chart.push(Tile {
+ node_id: None,
+ name: "Other",
+ size: remainder,
+ });
+ }
+ json(&View {
+ generation: &self.generation,
+ revision: self.revision,
+ node: self.summary_node(id),
+ path: self.path(id),
+ breadcrumbs,
+ children: keys.iter().map(|key| self.summary_node(key.2)).collect(),
+ previous_cursor,
+ next_cursor,
+ chart,
+ })
+ }
+ pub fn detail_json(&self, generation: &str, revision: u32, id: u32) -> Result<String, String> {
+ self.scope(generation, revision)?;
+ self.node(id)?;
+ #[derive(Serialize)]
+ struct Detail<'a> {
+ generation: &'a str,
+ revision: u32,
+ node: NodeSummary<'a>,
+ path: String,
+ }
+ json(&Detail {
+ generation: &self.generation,
+ revision: self.revision,
+ node: self.summary_node(id),
+ path: self.path(id),
+ })
+ }
+ pub fn prepare_delete(
+ &self,
+ generation: &str,
+ revision: u32,
+ id: u32,
+ ) -> Result<DeletePlan, String> {
+ self.scope(generation, revision)?;
+ self.node(id)?;
+ if id == 0 {
+ return Err("Cannot delete the scan root directory.".into());
+ }
+ if !self.can_delete(id) {
+ return Err("This scan entry cannot be deleted from the app.".into());
+ }
+ self.revision
+ .checked_add(1)
+ .ok_or("Scan revision limit reached; rescan first.")?;
+ Ok(DeletePlan {
+ generation: generation.into(),
+ revision,
+ node_id: id,
+ path: self.path(id),
+ })
+ }
+ fn commit_delete(&mut self, plan: &DeletePlan, message: &str) -> Result<String, String> {
+ self.scope(&plan.generation, plan.revision)?;
+ let node = self.node(plan.node_id)?;
+ let (size, files, dirs, parent) = (node.size, node.files, node.directories, node.parent);
+ let key = self.key(plan.node_id);
+ if !self.children[parent as usize].remove(&key) {
+ return Err("Scan deletion index is inconsistent".into());
+ }
+ self.response.nodes[plan.node_id as usize].deleted = true;
+ let mut ancestor = parent;
+ while ancestor != NONE {
+ let key = self.key(ancestor);
+ let node = &mut self.response.nodes[ancestor as usize];
+ let parent = node.parent;
+ node.size = node
+ .size
+ .checked_sub(size)
+ .ok_or("Invalid scan size after deletion")?;
+ node.files = node
+ .files
+ .checked_sub(files)
+ .ok_or("Invalid scan file count after deletion")?;
+ node.directories = node
+ .directories
+ .checked_sub(dirs)
+ .ok_or("Invalid scan directory count after deletion")?;
+ if parent != NONE {
+ if !self.children[parent as usize].remove(&key) {
+ return Err("Scan deletion index is inconsistent".into());
+ }
+ let updated = self.key(ancestor);
+ self.children[parent as usize].insert(updated);
+ }
+ ancestor = parent;
+ }
+ self.response.total_size = self.response.nodes[0].size;
+ self.response.total_files = self.response.nodes[0].files;
+ self.response.total_dirs = self.response.nodes[0].directories;
+ self.revision += 1;
+ #[derive(Serialize)]
+ struct Deleted<'a> {
+ summary: Summary<'a>,
+ message: &'a str,
+ removed: Removed,
+ }
+ #[derive(Serialize)]
+ struct Removed {
+ size: u64,
+ files: u64,
+ dirs: u64,
+ }
+ json(&Deleted {
+ summary: self.summary(),
+ message,
+ removed: Removed { size, files, dirs },
+ })
+ }
+}
+
+/// Once DELETE is sent, any failure may mean a partially changed filesystem.
+/// Quarantine the snapshot instead of offering stale IDs or retrying blindly.
+pub fn finish_delete(
+ store: &mut Option<Catalog>,
+ plan: &DeletePlan,
+ response: Result<String, String>,
+) -> Result<String, String> {
+ // A late result belongs only to its original snapshot. Never quarantine
+ // a newer generation if a caller violated the operation-lock ordering.
+ store
+ .as_ref()
+ .ok_or("Scan is unavailable; rescan required")?
+ .scope(&plan.generation, plan.revision)?;
+ let result = (|| {
+ let raw = response?;
+ let value: serde_json::Value =
+ serde_json::from_str(&raw).map_err(|_| "Invalid deletion response")?;
+ if value["status"] != "ok" {
+ return Err(value["message"]
+ .as_str()
+ .unwrap_or("Deletion failed; rescan required")
+ .to_string());
+ }
+ let message = value["message"]
+ .as_str()
+ .ok_or("Invalid deletion response")?;
+ store
+ .as_mut()
+ .ok_or("Scan is unavailable; rescan required")?
+ .commit_delete(plan, message)
+ })();
+ if result.is_err() {
+ *store = None;
+ }
+ result
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use crate::scan_stream;
+ use serde_json::{json, Value};
+ use std::io::Cursor as Reader;
+
+ 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
+ }
+ fn entry(
+ id: usize,
+ parent: Option<usize>,
+ name: &str,
+ kind: &str,
+ size: u64,
+ counted: bool,
+ ) -> Value {
+ json!({"id":id,"parent":parent,"name":name,"kind":kind,"size":size,"counted":counted})
+ }
+ fn fixture(entries: &[Value], read_only: bool) -> Response {
+ let mut bytes = frame(
+ "started",
+ json!({"stream_version":1,"root":"/fixture","read_only":read_only}),
+ );
+ for batch in entries.chunks(128) {
+ bytes.extend(frame("entries", json!({"entries":batch})));
+ }
+ let files = entries
+ .iter()
+ .filter(|e| e["kind"] == "file" && e["counted"] == true)
+ .count();
+ let dirs = entries
+ .iter()
+ .filter(|e| e["kind"] == "directory" && e["counted"] == true)
+ .count();
+ let size: u64 = entries.iter().map(|e| e["size"].as_u64().unwrap()).sum();
+ bytes.extend(frame("done", json!({"total_files":files,"total_dirs":dirs,"total_size":size,
+ "errors":0,"skipped":0,"scan_time_ms":1,"scan_threads":1,"serialize_ms":0,"send_ms":0,"bytes_sent":bytes.len()})));
+ scan_stream::read(&mut Reader::new(bytes), read_only, |_| Ok(())).unwrap()
+ }
+ fn root() -> Value {
+ entry(0, None, "fixture", "directory", 0, true)
+ }
+ fn wide(count: usize) -> Vec<Value> {
+ let mut entries = vec![root()];
+ // Lots of size ties and reversed insertion order exercise cursor keys.
+ for id in 1..=count {
+ entries.push(entry(
+ id,
+ Some(0),
+ &format!("file-{:05}", count - id),
+ "file",
+ (id % 7) as u64,
+ true,
+ ));
+ }
+ entries
+ }
+ fn value(raw: Result<String, String>) -> Value {
+ serde_json::from_str(&raw.unwrap()).unwrap()
+ }
+ fn view(store: &Catalog, id: u32) -> Value {
+ value(store.view_json("generation-a", store.revision, id, None))
+ }
+ fn success() -> Result<String, String> {
+ Ok(r#"{"status":"ok","message":"Deleted fixture entry"}"#.into())
+ }
+
+ #[test]
+ fn complete_wide_paging_forward_backward_matches_legacy_order() {
+ let response = fixture(&wide(1037), false);
+ let legacy = value(response.json());
+ let expected: Vec<_> = legacy["tree"]["children"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|e| e["name"].clone())
+ .collect();
+ let store = Catalog::new(response, "generation-a".into());
+ assert!(store.summary_json().unwrap().len() < 2048);
+ let mut page = view(&store, 0);
+ let mut all = Vec::new();
+ let mut pages = Vec::new();
+ loop {
+ let names: Vec<_> = page["children"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|e| e["name"].clone())
+ .collect();
+ assert!(names.len() <= PAGE_SIZE);
+ all.extend(names.clone());
+ pages.push(names);
+ if page["next_cursor"].is_null() {
+ break;
+ }
+ page = value(store.view_json(
+ "generation-a",
+ 0,
+ 0,
+ Some(serde_json::from_value(page["next_cursor"].clone()).unwrap()),
+ ));
+ }
+ assert_eq!(all, expected);
+ for expected in pages.iter().rev().skip(1) {
+ assert!(!page["previous_cursor"].is_null());
+ page = value(store.view_json(
+ "generation-a",
+ 0,
+ 0,
+ Some(serde_json::from_value(page["previous_cursor"].clone()).unwrap()),
+ ));
+ let names: Vec<_> = page["children"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|e| e["name"].clone())
+ .collect();
+ assert_eq!(&names, expected);
+ }
+ assert!(page["previous_cursor"].is_null());
+ }
+ #[test]
+ fn chart_has_exact_remainder_and_no_destructive_synthetic_id() {
+ let store = Catalog::new(fixture(&wide(600), false), "generation-a".into());
+ let page = view(&store, 0);
+ let chart = page["chart"].as_array().unwrap();
+ assert_eq!(chart.len(), CHART_SIZE + 1);
+ assert_eq!(
+ chart
+ .iter()
+ .map(|e| e["size"].as_u64().unwrap())
+ .sum::<u64>(),
+ page["node"]["size"].as_u64().unwrap()
+ );
+ assert_eq!(chart.last().unwrap()["name"], "Other");
+ assert!(chart.last().unwrap()["node_id"].is_null());
+ assert!(view(&store, 1)["chart"].as_array().unwrap().is_empty());
+ }
+ #[test]
+ fn deep_paths_parents_totals_and_placeholders_match_legacy_tree() {
+ let mut entries = vec![root()];
+ for id in 1..32 {
+ entries.push(entry(
+ id,
+ Some(id - 1),
+ &format!(" 写真 {id}"),
+ "directory",
+ 0,
+ true,
+ ));
+ }
+ entries.push(entry(32, Some(31), " leaf ", "file", 13, true));
+ entries.push(entry(33, Some(0), "fifo", "other", 0, false));
+ let response = fixture(&entries, false);
+ let legacy = value(response.json());
+ let store = Catalog::new(response, "generation-a".into());
+ let mut expected = &legacy["tree"];
+ for id in 0..=32 {
+ let page = view(&store, id);
+ assert_eq!(page["path"], expected["path"]);
+ assert_eq!(page["node"]["size"], expected["size"]);
+ assert_eq!(page["node"]["name"], expected["name"]);
+ assert_eq!(
+ page["node"]["parent_id"],
+ if id == 0 { Value::Null } else { json!(id - 1) }
+ );
+ assert_eq!(
+ page["breadcrumbs"].as_array().unwrap().len(),
+ id as usize + 1
+ );
+ if id < 32 {
+ expected = &expected["children"][0];
+ }
+ }
+ assert!(!view(&store, 33)["node"]["counted"].as_bool().unwrap());
+ assert_eq!(store.response.nodes[0].files, 1);
+ assert_eq!(store.response.nodes[0].directories, 32);
+ }
+ #[test]
+ fn maximum_depth_and_paths_stay_exact_without_recursive_ipc() {
+ let mut entries = vec![root()];
+ let mut expected = "/fixture".to_string();
+ for id in 1..=64 {
+ let length = if id == 64 { 247 } else { 255 };
+ let name = "x".repeat(length);
+ expected.push('/');
+ expected.push_str(&name);
+ entries.push(entry(
+ id,
+ Some(id - 1),
+ &name,
+ if id == 64 { "file" } else { "directory" },
+ if id == 64 { 1 } else { 0 },
+ true,
+ ));
+ }
+ assert_eq!(expected.len(), 16 * 1024);
+ let store = Catalog::new(fixture(&entries, false), "generation-a".into());
+ let page = view(&store, 64);
+ assert_eq!(page["path"], expected);
+ assert_eq!(page["breadcrumbs"].as_array().unwrap().len(), 65);
+ assert!(store.prepare_delete("generation-a", 0, 64).is_err());
+ assert_eq!(page["node"]["can_delete"], false);
+ assert_eq!(store.response.total_dirs, 64);
+ }
+ #[test]
+ fn bridge_queries_and_deletion_reject_invalidated_or_reconnected_snapshots() {
+ let _operation = crate::DAEMON_OPERATION.lock().unwrap();
+ *crate::SCAN_STORE.lock().unwrap() = Some(Catalog::new(
+ fixture(&wide(2), false),
+ "generation-a".into(),
+ ));
+ assert!(crate::get_scan_view("generation-a".into(), 0, 0, None).is_ok());
+ assert!(crate::get_scan_node("generation-a".into(), 0, 1).is_ok());
+ crate::invalidate_scan().unwrap();
+ assert!(crate::get_scan_view("generation-a".into(), 0, 0, None).is_err());
+ assert!(crate::get_scan_node("generation-a".into(), 0, 1).is_err());
+ *crate::SCAN_STORE.lock().unwrap() = Some(Catalog::new(
+ fixture(&wide(2), false),
+ "generation-b".into(),
+ ));
+ assert!(crate::get_scan_view("generation-a".into(), 0, 0, None).is_err());
+ assert!(crate::get_scan_node("generation-a".into(), 0, 1).is_err());
+ let guard = crate::SCAN_STORE.lock().unwrap();
+ assert!(guard
+ .as_ref()
+ .unwrap()
+ .prepare_delete("generation-a", 0, 1)
+ .is_err());
+ drop(guard);
+ crate::invalidate_scan().unwrap();
+ }
+ #[test]
+ fn exact_names_are_preserved_and_unrepresentable_deletes_are_blocked() {
+ let entries = vec![
+ root(),
+ entry(1, Some(0), " 写真 \" $() ", "directory", 0, true),
+ entry(2, Some(1), "ok", "file", 7, true),
+ entry(3, Some(0), "line\nbreak", "directory", 0, true),
+ entry(4, Some(3), "child", "file", 2, true),
+ ];
+ let store = Catalog::new(fixture(&entries, false), "generation-a".into());
+ let plan = store.prepare_delete("generation-a", 0, 2).unwrap();
+ assert_eq!(plan.path, "/fixture/ 写真 \" $() /ok");
+ assert_eq!(
+ value(store.detail_json("generation-a", 0, 2))["path"],
+ plan.path
+ );
+ assert!(store.prepare_delete("generation-a", 0, 0).is_err());
+ for id in [3, 4] {
+ assert!(store.prepare_delete("generation-a", 0, id).is_err());
+ assert_eq!(view(&store, id)["node"]["can_delete"], false);
+ }
+ let readonly = Catalog::new(fixture(&entries, true), "generation-a".into());
+ assert!(readonly.prepare_delete("generation-a", 0, 2).is_err());
+ assert_eq!(view(&readonly, 2)["node"]["can_delete"], false);
+ }
+ #[test]
+ fn delete_updates_ancestors_order_and_invalidates_descendants_and_cursors() {
+ let entries = vec![
+ root(),
+ entry(1, Some(0), "folder", "directory", 0, true),
+ entry(2, Some(1), "sub", "directory", 0, true),
+ entry(3, Some(2), "large", "file", 70, true),
+ entry(4, Some(1), "small", "file", 10, true),
+ entry(5, Some(0), "other", "file", 40, true),
+ ];
+ let mut store = Some(Catalog::new(
+ fixture(&entries, false),
+ "generation-a".into(),
+ ));
+ let plan = store
+ .as_ref()
+ .unwrap()
+ .prepare_delete("generation-a", 0, 2)
+ .unwrap();
+ let result = value(finish_delete(&mut store, &plan, success()));
+ assert_eq!(result["removed"], json!({"size":70,"files":1,"dirs":1}));
+ assert_eq!(result["summary"]["total_size"], 50);
+ assert_eq!(result["summary"]["total_files"], 2);
+ assert_eq!(result["summary"]["total_dirs"], 2);
+ let current = store.as_ref().unwrap();
+ assert_eq!(view(current, 0)["children"][0]["id"], 5);
+ assert_eq!(view(current, 1)["node"]["size"], 10);
+ for id in [2, 3] {
+ assert!(current.view_json("generation-a", 1, id, None).is_err());
+ assert!(current.prepare_delete("generation-a", 1, id).is_err());
+ }
+ assert!(current.view_json("generation-a", 0, 0, None).is_err());
+ assert!(current
+ .view_json(
+ "generation-a",
+ 0,
+ 0,
+ Some(Cursor {
+ direction: Direction::Next,
+ node_id: 1
+ })
+ )
+ .is_err());
+ let plan = current.prepare_delete("generation-a", 1, 1).unwrap();
+ let result = value(finish_delete(&mut store, &plan, success()));
+ assert_eq!(result["summary"]["total_dirs"], 1);
+ assert_eq!(result["summary"]["total_files"], 1);
+ assert_eq!(result["summary"]["total_size"], 40);
+ }
+ #[test]
+ fn repeated_file_and_directory_deletes_match_recursive_reference_totals() {
+ fn remove(tree: &mut Value, path: &str) -> bool {
+ let Some(children) = tree.get_mut("children").and_then(Value::as_array_mut) else {
+ return false;
+ };
+ if let Some(index) = children.iter().position(|node| node["path"] == path) {
+ children.remove(index);
+ return true;
+ }
+ children.iter_mut().any(|child| remove(child, path))
+ }
+ fn totals(tree: &mut Value) -> (u64, u64, u64) {
+ if tree["type"] == "file" {
+ return (
+ tree["size"].as_u64().unwrap(),
+ u64::from(tree["counted"] != false),
+ 0,
+ );
+ }
+ let mut result = (0, 0, u64::from(tree["counted"] != false));
+ for child in tree["children"].as_array_mut().unwrap() {
+ let (size, files, dirs) = totals(child);
+ result.0 += size;
+ result.1 += files;
+ result.2 += dirs;
+ }
+ tree["size"] = json!(result.0);
+ result
+ }
+ let mut entries = vec![root()];
+ for id in 1..=10 {
+ entries.push(entry(
+ id,
+ Some(0),
+ &format!("dir-{id}"),
+ "directory",
+ 0,
+ true,
+ ));
+ }
+ for id in 11..=610 {
+ entries.push(entry(
+ id,
+ Some(id % 10 + 1),
+ &format!("file-{id}"),
+ "file",
+ (id * 71 % 1000) as u64,
+ true,
+ ));
+ }
+ let response = fixture(&entries, false);
+ let mut reference = value(response.json())["tree"].take();
+ let mut store = Some(Catalog::new(response, "generation-a".into()));
+ for id in [1, 47, 123, 304, 2, 457, 602, 3, 9, 10] {
+ let current = store.as_ref().unwrap();
+ let plan = current
+ .prepare_delete("generation-a", current.revision, id)
+ .unwrap();
+ assert!(remove(&mut reference, &plan.path));
+ let expected = totals(&mut reference);
+ let result = value(finish_delete(&mut store, &plan, success()));
+ assert_eq!(result["summary"]["total_size"], expected.0);
+ assert_eq!(result["summary"]["total_files"], expected.1);
+ assert_eq!(result["summary"]["total_dirs"], expected.2);
+ }
+ }
+ #[test]
+ fn generation_replacement_invalidates_all_old_queries_and_delete_plans() {
+ let entries = wide(3);
+ let old = Catalog::new(fixture(&entries, false), "generation-a".into());
+ let plan = old.prepare_delete("generation-a", 0, 1).unwrap();
+ let new = Catalog::new(fixture(&entries, false), "generation-b".into());
+ assert!(new.view_json("generation-a", 0, 0, None).is_err());
+ assert!(new.detail_json("generation-a", 0, 1).is_err());
+ assert!(new.prepare_delete("generation-a", 0, 1).is_err());
+ let mut store = Some(new);
+ assert!(finish_delete(&mut store, &plan, success()).is_err());
+ assert_eq!(store.as_ref().unwrap().generation, "generation-b");
+ }
+ #[test]
+ fn invalid_nodes_and_wrong_parent_or_empty_page_cursors_fail() {
+ let entries = vec![
+ root(),
+ entry(1, Some(0), "folder", "directory", 0, true),
+ entry(2, Some(1), "file", "file", 1, true),
+ ];
+ let store = Catalog::new(fixture(&entries, false), "generation-a".into());
+ assert!(store.view_json("generation-a", 0, u32::MAX, None).is_err());
+ assert!(store
+ .view_json(
+ "generation-a",
+ 0,
+ 0,
+ Some(Cursor {
+ direction: Direction::Next,
+ node_id: 2
+ })
+ )
+ .is_err());
+ assert!(store
+ .view_json(
+ "generation-a",
+ 0,
+ 0,
+ Some(Cursor {
+ direction: Direction::Next,
+ node_id: 1
+ })
+ )
+ .is_err());
+ assert!(store
+ .view_json(
+ "generation-a",
+ 0,
+ 0,
+ Some(Cursor {
+ direction: Direction::Previous,
+ node_id: 1
+ })
+ )
+ .is_err());
+ assert!(serde_json::from_value::<Cursor>(
+ json!({"direction":"next","node_id":1,"extra":1})
+ )
+ .is_err());
+ assert!(
+ serde_json::from_value::<Cursor>(json!({"direction":"offset","node_id":1})).is_err()
+ );
+ }
+ #[test]
+ fn transport_partial_and_malformed_delete_failures_quarantine_snapshot() {
+ for response in [
+ Err("connection lost".into()),
+ Ok(r#"{"status":"error","message":"partially deleted directory"}"#.into()),
+ Ok("truncated".into()),
+ Ok(r#"{"status":"ok"}"#.into()),
+ ] {
+ let mut store = Some(Catalog::new(
+ fixture(&wide(2), false),
+ "generation-a".into(),
+ ));
+ let plan = store
+ .as_ref()
+ .unwrap()
+ .prepare_delete("generation-a", 0, 1)
+ .unwrap();
+ assert!(finish_delete(&mut store, &plan, response).is_err());
+ assert!(store.is_none());
+ }
+ }
+ #[test]
+ fn concurrent_reads_and_revision_commit_return_consistent_snapshots() {
+ use std::sync::{Barrier, Mutex};
+ let store = Arc::new(Mutex::new(Some(Catalog::new(
+ fixture(&wide(300), false),
+ "generation-a".into(),
+ ))));
+ let barrier = Arc::new(Barrier::new(5));
+ std::thread::scope(|threads| {
+ for _ in 0..4 {
+ let store = store.clone();
+ let barrier = barrier.clone();
+ threads.spawn(move || {
+ barrier.wait();
+ for _ in 0..40 {
+ let guard = store.lock().unwrap();
+ let result = guard
+ .as_ref()
+ .unwrap()
+ .view_json("generation-a", 0, 0, None);
+ if let Ok(raw) = result {
+ let page: Value = serde_json::from_str(&raw).unwrap();
+ assert_eq!(page["revision"], 0);
+ assert_eq!(page["node"]["child_count"], 300);
+ } else {
+ assert_eq!(guard.as_ref().unwrap().revision, 1);
+ }
+ }
+ });
+ }
+ barrier.wait();
+ let mut guard = store.lock().unwrap();
+ let plan = guard
+ .as_ref()
+ .unwrap()
+ .prepare_delete("generation-a", 0, 1)
+ .unwrap();
+ finish_delete(&mut guard, &plan, success()).unwrap();
+ });
+ assert_eq!(
+ view(store.lock().unwrap().as_ref().unwrap(), 0)["node"]["child_count"],
+ 299
+ );
+ }
+ #[test]
+ fn response_writer_is_bounded_even_when_serialization_escapes_expand() {
+ assert!(json(&"\u{0001}".repeat(MAX_QUERY_BYTES / 6 + 1)).is_err());
+ let store = Catalog::new(fixture(&wide(1000), false), "generation-a".into());
+ assert!(store.view_json("generation-a", 0, 0, None).unwrap().len() < MAX_QUERY_BYTES);
+ }
+}
diff --git a/src-tauri/src/scan_stream.rs b/src-tauri/src/scan_stream.rs
index 2eb7dc7..94f9ac9 100644
--- a/src-tauri/src/scan_stream.rs
+++ b/src-tauri/src/scan_stream.rs
@@ -1,19 +1,21 @@
-//! Bounded stream-v1 decoder. Compact records exist only for construction of
-//! the current UI response; persistent ownership/query APIs belong to #29.
-use serde::{
- ser::{SerializeSeq, SerializeStruct},
- Deserialize, Serialize,
-};
-use std::io::{Read, Write};
+//! Bounded stream-v1 decoder. Verified records transfer to the host scan store.
+#[cfg(test)]
+use serde::ser::{SerializeSeq, SerializeStruct};
+use serde::{Deserialize, Serialize};
+use std::io::Read;
+#[cfg(test)]
+use std::io::Write;
+use std::sync::Arc;
use std::time::{Duration, Instant};
pub const MAX_FRAME_BYTES: usize = 128 * 1024;
const MAX_BATCH_ENTRIES: usize = 128;
const MAX_NODES: usize = 2_000_000;
const MAX_TREE_BYTES: usize = 128 * 1024 * 1024;
+#[cfg(test)]
const MAX_RESULT_BYTES: usize = 256 * 1024 * 1024;
const MAX_SAFE_INTEGER: u64 = (1u64 << 53) - 1;
-const NONE: u32 = u32::MAX;
+pub(crate) const NONE: u32 = u32::MAX;
#[derive(Deserialize)]
#[serde(
@@ -59,36 +61,41 @@ struct Entry {
}
#[derive(Deserialize, PartialEq, Copy, Clone)]
#[serde(rename_all = "snake_case")]
-enum Kind {
+pub(crate) enum Kind {
File,
Directory,
Other,
}
-struct Node {
- name: String,
- size: u64,
- parent: u32,
+pub(crate) struct Node {
+ pub name: Arc<str>,
+ pub size: u64,
+ pub parent: u32,
first_child: u32,
next_sibling: u32,
path_bytes: u32,
depth: u8,
- kind: Kind,
- counted: bool,
+ pub kind: Kind,
+ pub counted: bool,
+ pub files: u64,
+ pub directories: u64,
+ pub deleted: bool,
}
// Serialize directly from compact records. Full paths and recursive child
// objects are never materialized in a second host tree.
+#[cfg(test)]
struct NodeView<'a> {
nodes: &'a [Node],
index: u32,
path: &'a str,
}
+#[cfg(test)]
impl Serialize for NodeView<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let node = &self.nodes[self.index as usize];
let directory = node.kind == Kind::Directory;
let fields = 4 + usize::from(directory) + usize::from(!node.counted);
let mut result = serializer.serialize_struct("Node", fields)?;
- result.serialize_field("name", &node.name)?;
+ result.serialize_field("name", node.name.as_ref())?;
result.serialize_field("path", &self.path)?;
result.serialize_field("type", if directory { "directory" } else { "file" })?;
result.serialize_field("size", &node.size)?;
@@ -110,11 +117,13 @@ impl Serialize for NodeView<'_> {
result.end()
}
}
+#[cfg(test)]
struct ChildrenView<'a> {
nodes: &'a [Node],
first: u32,
path: &'a str,
}
+#[cfg(test)]
impl Serialize for ChildrenView<'_> {
fn serialize<S: serde::Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
let mut sequence = serializer.serialize_seq(None)?;
@@ -147,21 +156,21 @@ pub struct Progress {
#[derive(Serialize)]
pub struct Response {
#[serde(skip)]
- nodes: Vec<Node>,
+ pub(crate) nodes: Vec<Node>,
#[serde(skip)]
- root: String,
+ pub(crate) root: String,
status: &'static str,
- total_files: u64,
- total_dirs: u64,
- total_size: u64,
+ pub(crate) total_files: u64,
+ pub(crate) total_dirs: u64,
+ pub(crate) total_size: u64,
errors: u64,
skipped: u64,
- read_only: bool,
+ pub(crate) read_only: bool,
scan_time_ms: u64,
scan_threads: u32,
streamed: bool,
traverse_ms: u64,
- sort_ms: u64,
+ pub(crate) sort_ms: u64,
serialize_ms: u64,
send_ms: u64,
bytes_sent: u64,
@@ -170,6 +179,7 @@ impl Response {
pub fn root(&self) -> &str {
&self.root
}
+ #[cfg(test)]
pub fn json(&self) -> Result<String, String> {
struct Limited(Vec<u8>);
impl Write for Limited {
@@ -359,8 +369,8 @@ pub fn read(
if path_bytes > 16 * 1024 || depth > 64 {
return Err("Scan path/depth limit exceeded".into());
}
- // Conservative budget also accounts for the final path
- // representation, not just the smaller compact records.
+ // Conservative budget covers records, shared names, directory
+ // indexes, and decoder staging; full paths stay transient.
tree_bytes = tree_bytes
.checked_add(path_bytes + entry.name.len() + 256)
.ok_or("Scan memory limit exceeded")?;
@@ -379,7 +389,7 @@ pub fn read(
nodes[parent].first_child = entry.id as u32;
}
nodes.push(Node {
- name: entry.name,
+ name: entry.name.into(),
size: entry.size,
parent: entry.parent.map_or(NONE, |id| id as u32),
first_child: NONE,
@@ -388,6 +398,9 @@ pub fn read(
depth: depth as u8,
kind: entry.kind,
counted: entry.counted,
+ files: u64::from(entry.counted && entry.kind == Kind::File),
+ directories: u64::from(entry.counted && entry.kind == Kind::Directory),
+ deleted: false,
});
}
if (!first_results_sent && nodes.len() > 1)
@@ -398,7 +411,7 @@ pub fn read(
.skip(1)
.rev()
.take(5)
- .map(|node| node.name.clone())
+ .map(|node| node.name.to_string())
.collect();
observed.recent_names.reverse();
progress(&observed)?;
@@ -452,6 +465,9 @@ pub fn read(
for index in (1..nodes.len()).rev() {
let parent = nodes[index].parent as usize;
nodes[parent].size = safe_add(nodes[parent].size, nodes[index].size)?;
+ nodes[parent].files = safe_add(nodes[parent].files, nodes[index].files)?;
+ nodes[parent].directories =
+ safe_add(nodes[parent].directories, nodes[index].directories)?;
}
if nodes[0].size != total_size {
return Err("Scan tree does not match completion totals".into());
@@ -490,7 +506,7 @@ pub fn read(
.skip(1)
.rev()
.take(5)
- .map(|node| node.name.clone())
+ .map(|node| node.name.to_string())
.collect();
observed.recent_names.reverse();
progress(&observed)?;
diff --git a/src/App.tsx b/src/App.tsx
index abf1cc4..adf1a7a 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -2,38 +2,13 @@ import { useState, useCallback, useEffect, useRef } from "react";
import { Channel, invoke } from "@tauri-apps/api/core";
import { Treemap, ResponsiveContainer, Tooltip as RechartsTooltip } from "recharts";
import { formatBytes } from "./formatBytes";
+import { sameScan } from "./scanView";
+import type { ScanNode, ScanResponse, NodeDetail, DeleteResult } from "./scanView";
+import { useScanView } from "./useScanView";
import "./App.css";
// ── Types ───────────────────────────────────────────────────────────────────
-interface FileNode {
- name: string;
- path: string;
- type: "file" | "directory";
- size: number;
- counted?: boolean;
- children?: FileNode[];
-}
-
-interface ScanResponse {
- status: string;
- streamed?: boolean;
- scan_time_ms: number;
- total_files: number;
- total_dirs: number;
- total_size: number;
- errors: number;
- read_only: boolean;
- skipped: number;
- /** Per-phase timings from daemon v1.2+ (issue #3); absent in older daemons. */
- traverse_ms?: number;
- sort_ms?: number;
- serialize_ms?: number;
- send_ms?: number;
- bytes_sent?: number;
- tree: FileNode;
-}
-
/** One-line phase breakdown for the terminal log; null if the daemon predates #3. */
const scanPhaseLog = (r: ScanResponse): string | null => {
if (r.traverse_ms === undefined) return null;
@@ -56,84 +31,6 @@ function formatNumber(n: number): string {
return n.toLocaleString("en-US");
}
-function findNodeByPath(root: FileNode, targetPath: string): FileNode | null {
- if (root.path === targetPath) return root;
- if (!root.children) return null;
- for (const child of root.children) {
- if (targetPath.startsWith(child.path)) {
- const found = findNodeByPath(child, targetPath);
- if (found) return found;
- }
- }
- return null;
-}
-
-function buildBreadcrumbs(root: FileNode, targetPath: string): { name: string; path: string }[] {
- const breadcrumbs: { name: string; path: string }[] = [];
- let current: FileNode | null = root;
-
- while (current) {
- breadcrumbs.push({ name: current.name, path: current.path });
- if (current.path === targetPath) break;
-
- let next: FileNode | null = null;
- if (current.children) {
- for (const child of current.children) {
- if (targetPath === child.path || targetPath.startsWith(child.path + "/")) {
- next = child;
- break;
- }
- }
- }
- current = next;
- }
- return breadcrumbs;
-}
-
-function countNodeStats(node: FileNode): { size: number; files: number; dirs: number } {
- if (node.type === "file") {
- return { size: node.size, files: node.counted === false ? 0 : 1, dirs: 0 };
- }
- let files = 0;
- let dirs = node.counted === false ? 0 : 1;
- if (node.children) {
- for (const child of node.children) {
- const stats = countNodeStats(child);
- files += stats.files;
- dirs += stats.dirs;
- }
- }
- return { size: node.size, files, dirs };
-}
-
-function removeNodeByPath(
- root: FileNode,
- targetPath: string
-): { removed: boolean; size: number; files: number; dirs: number } {
- if (!root.children) return { removed: false, size: 0, files: 0, dirs: 0 };
-
- const index = root.children.findIndex((child) => child.path === targetPath);
- if (index !== -1) {
- const node = root.children[index];
- const stats = countNodeStats(node);
- root.children.splice(index, 1);
- root.size -= stats.size;
- return { removed: true, ...stats };
- }
-
- for (const child of root.children) {
- if (targetPath.startsWith(child.path + "/")) {
- const result = removeNodeByPath(child, targetPath);
- if (result.removed) {
- root.size -= result.size;
- return result;
- }
- }
- }
-
- return { removed: false, size: 0, files: 0, dirs: 0 };
-}
-
// ── Icons (inline SVG) ──────────────────────────────────────────────────────
function IconFolder({ className = "" }: { className?: string }) {
@@ -431,99 +328,66 @@ function SizeBar({ ratio }: { ratio: number }) {
// ── File Tree Node ──────────────────────────────────────────────────────────
-function FileTreeNode({
- node,
- parentSize,
- depth,
- onNuke,
- onZoom,
-}: {
- node: FileNode;
+function QueryError({ error, retry }: { error: string; retry: () => void }) {
+ return <div role="alert" className="px-4 py-2 text-xs text-red-400">
+ {error} <button onClick={retry} className="underline ml-2">Retry</button>
+ </div>;
+}
+
+function FileTreeNode({ node, scope, parentSize, depth, onNuke, onZoom, expanded, toggle, busy, rootView }: {
+ node: ScanNode;
+ scope: ScanResponse;
parentSize: number;
depth: number;
- onNuke?: (path: string, name: string) => void;
- onZoom: (path: string) => void;
+ onNuke: (nodeId: number) => void;
+ onZoom: (nodeId: number) => void;
+ expanded: Set<number>;
+ toggle: (nodeId: number) => void;
+ busy: boolean;
+ rootView?: ReturnType<typeof useScanView>;
}) {
- const [open, setOpen] = useState(depth < 1);
+ const open = expanded.has(node.id);
const isDir = node.type === "directory";
+ const query = useScanView(scope, node.id, depth > 0 && isDir && open && node.child_count > 0);
+ const view = rootView ?? query;
+ const page = view.page;
const ratio = parentSize > 0 ? node.size / parentSize : 0;
-
+ const label = <>
+ <span className="w-4 flex-shrink-0 flex items-center justify-center">
+ {isDir ? <IconChevron open={open} className="text-zinc-500" /> : <span className="w-3" />}
+ </span>
+ <span className={isDir ? "text-accent-400" : "text-zinc-500"}>{isDir ? <IconFolder /> : <IconFile />}</span>
+ <span className={`truncate text-sm ${isDir ? "text-zinc-200 font-medium" : "text-zinc-400"}`}>{node.name}</span>
+ </>;
return (
- <div className="animate-fade-in-up" style={{ animationDelay: `${depth * 20}ms` }}>
- <div
- className={`
- file-row flex items-center gap-2 px-3 py-1.5 rounded-md cursor-pointer
- group select-none
- `}
- style={{ paddingLeft: `${12 + depth * 16}px` }}
- onClick={() => {
- if (isDir) setOpen(!open);
- }}
- >
- <span className="w-4 flex-shrink-0 flex items-center justify-center">
- {isDir ? (
- <IconChevron open={open} className="text-zinc-500" />
- ) : (
- <span className="w-3" />
- )}
- </span>
-
- <span className={isDir ? "text-accent-400" : "text-zinc-500"}>
- {isDir ? <IconFolder /> : <IconFile />}
- </span>
-
- <span className={`flex-1 truncate text-sm ${isDir ? "text-zinc-200 font-medium" : "text-zinc-400"}`}>
- {node.name}
- </span>
-
- {/* Action Buttons */}
- {isDir && (
- <button
- className="opacity-0 group-hover:opacity-100 mr-2 px-2 py-1 rounded text-[10px] uppercase font-bold tracking-wider bg-accent-500/10 text-accent-400 border border-accent-500/20 hover:bg-accent-500/30"
- onClick={(e) => { e.stopPropagation(); onZoom(node.path); }}
- >
- Zoom
- </button>
- )}
-
+ <div>
+ <div className="file-row flex items-center gap-2 px-3 py-1.5 rounded-md group select-none"
+ style={{ paddingLeft: `${12 + depth * 16}px` }}>
+ {isDir ? <button className="flex items-center gap-2 min-w-0 flex-1 text-left" disabled={busy}
+ aria-expanded={open} onClick={() => toggle(node.id)}>{label}</button>
+ : <span className="flex items-center gap-2 min-w-0 flex-1 text-left">{label}</span>}
+ {isDir && <button disabled={busy} onClick={() => onZoom(node.id)}
+ className="opacity-0 group-hover:opacity-100 focus:opacity-100 mr-2 px-2 py-1 rounded text-[10px] uppercase font-bold bg-accent-500/10 text-accent-400 border border-accent-500/20">Zoom</button>}
<SizeBar ratio={ratio} />
-
- <span className="w-20 text-right text-xs font-mono text-zinc-500 flex-shrink-0">
- {formatBytes(node.size)}
- </span>
-
- {depth > 0 && onNuke && (
- <button
- className="btn-nuke opacity-0 group-hover:opacity-100 ml-1 px-2 py-1 rounded-md
- bg-danger-600/20 border border-danger-500/30 text-danger-400
- hover:bg-danger-500/30 hover:text-danger-400 text-[10px] uppercase font-bold tracking-wider flex items-center gap-1
- cursor-pointer"
- onClick={(e) => {
- e.stopPropagation();
- onNuke?.(node.path, node.name);
- }}
- title={`Delete ${node.name}`}
- >
- <IconNuke />
- <span className="hidden sm:inline">Delete</span>
- </button>
- )}
+ <span className="w-20 text-right text-xs font-mono text-zinc-500 flex-shrink-0">{formatBytes(node.size)}</span>
+ {depth > 0 && node.can_delete && <button disabled={busy} onClick={() => onNuke(node.id)}
+ title={`Delete ${node.name}`} aria-label={`Delete ${node.name}`}
+ className="btn-nuke opacity-0 group-hover:opacity-100 focus:opacity-100 ml-1 px-2 py-1 rounded-md bg-danger-600/20 border border-danger-500/30 text-danger-400 hover:bg-danger-500/30 text-[10px] uppercase font-bold flex items-center gap-1">
+ <IconNuke /><span className="hidden sm:inline">Delete</span>
+ </button>}
</div>
-
- {isDir && open && node.children && (
- <div>
- {node.children.map((child, i) => (
- <FileTreeNode
- key={`${child.path}-${i}`}
- node={child}
- parentSize={node.size}
- depth={depth + 1}
- onNuke={onNuke}
- onZoom={onZoom}
- />
- ))}
- </div>
- )}
+ {isDir && open && node.child_count > 0 && <div>
+ {!page && !view.error && <p role="status" className="px-4 py-2 text-xs text-zinc-500">Loading entries…</p>}
+ {view.error && <QueryError error={view.error} retry={view.retry} />}
+ {page?.children.map(child => <FileTreeNode key={child.id} node={child} scope={scope} parentSize={node.size}
+ depth={depth + 1} onNuke={onNuke} onZoom={onZoom} expanded={expanded} toggle={toggle} busy={busy} />)}
+ {page && (page.previous_cursor || page.next_cursor) && <nav aria-label={`Pages in ${node.name}`}
+ className="flex items-center gap-3 py-2 text-xs text-zinc-400" style={{ paddingLeft: `${28 + depth * 16}px` }}>
+ <button disabled={!page.previous_cursor || busy} onClick={() => view.go(page.previous_cursor)} className="px-2 py-1 bg-zinc-800 rounded disabled:opacity-30">Previous</button>
+ <span>{page.children.length} entries on this page of {formatNumber(node.child_count)}</span>
+ <button disabled={!page.next_cursor || busy} onClick={() => view.go(page.next_cursor)} className="px-2 py-1 bg-zinc-800 rounded disabled:opacity-30">Next</button>
+ </nav>}
+ </div>}
</div>
);
}
@@ -582,32 +446,38 @@ function ResultScreen({
onRescan,
onDisconnect,
onNuke,
+ busy,
}: {
data: ScanResponse;
onRescan: () => void;
onDisconnect: () => void;
- onNuke: (path: string, name: string) => void;
+ onNuke: (nodeId: number) => void;
+ busy: boolean;
}) {
- const [zoomPath, setZoomPath] = useState<string>(data.tree.path);
-
- // Find node to render based on zoom
- const renderNode = findNodeByPath(data.tree, zoomPath) || data.tree;
+ const [zoomId, setZoomId] = useState(data.root.id);
+ const [expanded, setExpanded] = useState(() => new Set([data.root.id]));
+ const view = useScanView(data, zoomId, true);
+ const page = view.page;
+ const onZoom = (id: number) => {
+ setExpanded(previous => new Set(previous).add(id));
+ setZoomId(id);
+ };
+ const toggle = (id: number) => setExpanded(previous => {
+ const next = new Set(previous);
+ if (next.has(id)) next.delete(id); else next.add(id);
+ return next;
+ });
+ useEffect(() => {
+ if (view.error === "Scan node is no longer available") onZoom(data.root.id);
+ }, [view.error, data.root.id]);
const bgColors = [
"#0d9488", "#0284c7", "#4f46e5", "#7c3aed",
"#c026d3", "#e11d48", "#ea580c", "#ca8a04",
];
- // Flatten immediate children for a clean 1-level treemap
- const treemapData = (renderNode.children || [])
- .filter(c => c.size > 0)
- .map(c => ({
- name: c.name,
- size: c.size,
- path: c.path,
- }));
-
- const breadcrumbs = buildBreadcrumbs(data.tree, zoomPath);
+ const treemapData = (page?.chart ?? []).map(tile => ({ ...tile, nodeId: tile.node_id }));
+ const breadcrumbs = page?.breadcrumbs ?? [];
return (
<div className="flex flex-col h-full animate-fade-in-up">
@@ -618,9 +488,9 @@ function ResultScreen({
<h1 className="text-base font-semibold text-zinc-200 tracking-tight">SocketSweep</h1>
<div className="flex items-center text-xs text-zinc-500 font-mono">
{breadcrumbs.map((crumb, idx) => (
- <span key={crumb.path} className="inline-flex items-center">
+ <span key={crumb.id} className="inline-flex items-center">
<button
- onClick={() => setZoomPath(crumb.path)}
+ disabled={busy} onClick={() => onZoom(crumb.id)}
className={`hover:text-zinc-300 transition-colors ${idx === breadcrumbs.length - 1 ? 'text-zinc-300 font-semibold' : ''}`}
>
{crumb.name}
@@ -633,9 +503,9 @@ function ResultScreen({
</div>
</div>
<div className="flex items-center gap-2">
- {zoomPath !== data.tree.path && (
+ {zoomId !== data.root.id && (
<button
- onClick={() => setZoomPath(data.tree.path)}
+ disabled={busy} onClick={() => onZoom(data.root.id)}
className="px-3 py-1.5 rounded-lg text-xs font-medium bg-zinc-800 text-zinc-300 hover:bg-zinc-700"
>
← Back to Root
@@ -643,7 +513,7 @@ function ResultScreen({
)}
<button
id="btn-rescan"
- onClick={onRescan}
+ disabled={busy} onClick={onRescan}
className="px-3 py-1.5 rounded-lg text-xs font-medium bg-zinc-800 text-zinc-300
hover:bg-zinc-700 hover:text-zinc-100 border border-zinc-700/50"
>
@@ -651,7 +521,7 @@ function ResultScreen({
</button>
<button
id="btn-disconnect"
- onClick={onDisconnect}
+ disabled={busy} onClick={onDisconnect}
className="px-3 py-1.5 rounded-lg text-xs font-medium bg-zinc-800 text-zinc-400
hover:bg-red-950/50 hover:text-red-400 border border-zinc-700/50"
>
@@ -686,7 +556,7 @@ function ResultScreen({
content={<TreemapContent bgColors={bgColors} />}
isAnimationActive={false}
onClick={(e: any) => {
- if (e && e.path) setZoomPath(e.path);
+ if (!busy && typeof e?.nodeId === "number") onZoom(e.nodeId);
}}
>
<RechartsTooltip
@@ -697,7 +567,7 @@ function ResultScreen({
<div className="bg-zinc-900 border border-zinc-800 p-2 rounded shadow-xl text-xs z-50">
<p className="font-semibold text-zinc-200">{p.name}</p>
<p className="text-zinc-400 font-mono mt-1">{formatBytes(p.size)}</p>
- <p className="text-zinc-600 mt-1">Click to Zoom</p>
+ {p.node_id !== null && <p className="text-zinc-600 mt-1">Click to Zoom</p>}
</div>
);
}
@@ -717,13 +587,11 @@ function ResultScreen({
{[data.errors > 0 ? `${data.errors} access errors` : "", data.skipped > 0 ? `${data.skipped} excluded or duplicate entries` : ""].filter(Boolean).join(" · ")}
</span>
</div>
- <FileTreeNode
- node={renderNode}
- parentSize={renderNode.size}
- depth={0}
- onNuke={data.read_only ? undefined : onNuke}
- onZoom={setZoomPath}
- />
+ {!page && !view.error && <p role="status" className="px-3 py-2 text-xs text-zinc-500">Loading storage map…</p>}
+ {view.error && <QueryError error={view.error} retry={view.retry} />}
+ {page && <FileTreeNode node={page.node} scope={data} parentSize={page.node.size} depth={0}
+ onNuke={onNuke} onZoom={onZoom} expanded={expanded} toggle={toggle} busy={busy} rootView={view} />}
+
</div>
</div>
);
@@ -736,6 +604,11 @@ function App() {
const [rootMode, setRootMode] = useState(false);
const [rootPath, setRootPath] = useState("/data");
const [scanData, setScanData] = useState<ScanResponse | null>(null);
+ const snapshot = useRef<ScanResponse | null>(null);
+ const [busy, setBusy] = useState(false);
+ const deleting = useRef(false);
+ const confirmationRequest = useRef(0);
+ const [confirmDelete, setConfirmDelete] = useState<NodeDetail | null>(null);
const [scanProgress, setScanProgress] = useState<ScanProgress | null>(null);
const [cancelling, setCancelling] = useState(false);
const activeScan = useRef<string | null>(null);
@@ -774,6 +647,9 @@ function App() {
}, []);
const requestScan = useCallback(async (path: string): Promise<ScanResponse> => {
+ snapshot.current = null;
+ confirmationRequest.current += 1;
+ setConfirmDelete(null);
const scanId = crypto.randomUUID();
activeScan.current = scanId;
setScanProgress(null);
@@ -828,6 +704,7 @@ function App() {
if (parsed.status !== "ok") throw new Error("Scan returned non-ok status");
+ snapshot.current = parsed;
setScanData(parsed);
setPhase("result");
addLog(`[SCAN] Complete! ${parsed.total_files} files, ${parsed.scan_time_ms}ms.`);
@@ -847,12 +724,13 @@ function App() {
// ── Rescan ──────────────────────────────────────────────────────────────
const handleRescan = useCallback(async () => {
if (!scanData) return;
- const scanPath = scanData.tree.path;
+ const scanPath = scanData.root_path;
setPhase("scanning");
setStatusText(`Re-scanning ${scanPath} …`);
addLog(`[SCAN] Re-scanning ${scanPath}...`);
try {
const parsed = await requestScan(scanPath);
+ snapshot.current = parsed;
setScanData(parsed);
setPhase("result");
addLog(`[SCAN] Complete! ${parsed.scan_time_ms}ms.`);
@@ -872,6 +750,9 @@ function App() {
// ── Disconnect ──────────────────────────────────────────────────────────
const handleDisconnect = useCallback(async () => {
+ snapshot.current = null;
+ confirmationRequest.current += 1;
+ setConfirmDelete(null);
addLog("[SOCKET] Disconnecting daemon...");
try {
await invoke<string>("stop_daemon");
@@ -884,56 +765,61 @@ function App() {
setPhase("setup");
}, [pushToast, addLog]);
- const [confirmDelete, setConfirmDelete] = useState<{path: string, name: string} | null>(null);
-
- // ── Nuke (Delete) ───────────────────────────────────────────────────────
- const handleNuke = useCallback((path: string, name: string) => {
- if (scanData?.read_only) return;
- setConfirmDelete({ path, name });
- }, [scanData]);
+ // Resolve confirmation details separately; destructive IPC accepts only IDs.
+ const handleNuke = useCallback(async (nodeId: number) => {
+ const scope = snapshot.current;
+ if (!scope || scope.read_only || deleting.current) return;
+ const request = ++confirmationRequest.current;
+ try {
+ const raw = await invoke<string>("get_scan_node", { generation: scope.generation, revision: scope.revision, nodeId });
+ const detail: NodeDetail = JSON.parse(raw);
+ if (request === confirmationRequest.current && !deleting.current && sameScan(snapshot.current, scope) && sameScan(detail, scope) && detail.node.id === nodeId && detail.node.can_delete) {
+ setConfirmDelete(detail);
+ }
+ } catch (err) {
+ if (request === confirmationRequest.current && sameScan(snapshot.current, scope)) pushToast(String(err), "error");
+ }
+ }, [pushToast]);
const executeDelete = useCallback(async () => {
- if (!confirmDelete) return;
- const { path, name } = confirmDelete;
+ const target = confirmDelete;
+ confirmationRequest.current += 1;
setConfirmDelete(null);
- if (scanData?.read_only) return;
-
- // Guard: never delete the scan root
- if (scanData && path === scanData.tree.path) {
- pushToast("Cannot delete the scan root directory.", "error");
- addLog(`[DELETE] Blocked: ${path} is the scan root.`);
- return;
- }
-
- addLog(`[DELETE] Requesting deletion of ${path}...`);
+ if (!target || deleting.current || !sameScan(snapshot.current, target)) return;
+ deleting.current = true;
+ setBusy(true);
+ addLog(`[DELETE] Requesting deletion of ${target.path}...`);
try {
- const raw = await invoke<string>("delete_item", { path });
- const parsed = JSON.parse(raw);
- if (parsed.status === "ok") {
- pushToast(`Successfully deleted ${name}`, "success");
- addLog(`[DELETE] Success: ${parsed.message}`);
-
- // Update tree client-side instead of doing a full re-scan
- if (scanData) {
- const updated = JSON.parse(JSON.stringify(scanData)) as ScanResponse;
- const result = removeNodeByPath(updated.tree, path);
- if (result.removed) {
- updated.total_files -= result.files;
- updated.total_dirs -= result.dirs;
- updated.total_size -= result.size;
- addLog(`[DELETE] Tree updated locally (removed ${result.files} files, ${result.dirs} dirs, ${formatBytes(result.size)})`);
- }
- setScanData(updated);
- }
- } else {
- throw new Error(parsed.message || "Unknown error");
+ const raw = await invoke<string>("delete_item", {
+ generation: target.generation, revision: target.revision, nodeId: target.node.id,
+ });
+ if (!sameScan(snapshot.current, target)) return;
+ const result: DeleteResult = JSON.parse(raw);
+ if (result.summary.generation !== target.generation || result.summary.revision !== target.revision + 1) {
+ throw new Error("Deletion returned an unexpected scan snapshot");
}
+ snapshot.current = result.summary;
+ setScanData(result.summary);
+ pushToast(`Successfully deleted ${target.node.name}`, "success");
+ addLog(`[DELETE] Success: ${result.message}`);
+ addLog(`[DELETE] Scan updated (removed ${result.removed.files} files, ${result.removed.dirs} dirs, ${formatBytes(result.removed.size)})`);
} catch (err: unknown) {
+ if (!sameScan(snapshot.current, target)) return;
const message = err instanceof Error ? err.message : String(err);
- pushToast(`Delete failed: ${message}`, "error");
+ snapshot.current = null;
+ setScanData(null);
+ setPhase("connecting");
+ pushToast(`Delete failed: ${message}. Reconnect and rescan before continuing.`, "error");
addLog(`[ERROR] Delete failed: ${message}`);
+ // The daemon may have partially deleted a directory before reporting an
+ // error. Discard its snapshot; never offer a blind retry with stale IDs.
+ try { await invoke("stop_daemon"); } catch { /* retain the deletion error */ }
+ setPhase("setup");
+ } finally {
+ deleting.current = false;
+ setBusy(false);
}
- }, [confirmDelete, pushToast, addLog, scanData]);
+ }, [confirmDelete, pushToast, addLog]);
useEffect(() => {
const timers = timerRefs.current;
@@ -958,7 +844,9 @@ function App() {
{phase === "scanning" && <ScanningScreen statusText={statusText} progress={scanProgress} onCancel={handleCancelScan} cancelling={cancelling} />}
{phase === "result" && scanData && (
<ResultScreen
+ key={scanData.generation}
data={scanData}
+ busy={busy}
onRescan={handleRescan}
onDisconnect={handleDisconnect}
onNuke={handleNuke}
@@ -982,11 +870,11 @@ function App() {
Are you sure you want to permanently delete:
</p>
<p className="text-sm font-mono text-zinc-300 bg-zinc-950 p-2 rounded-lg break-all border border-zinc-800 mb-6">
- {confirmDelete.name}
+ {confirmDelete.path}
</p>
<div className="flex items-center gap-3 justify-end">
<button
- onClick={() => setConfirmDelete(null)}
+ onClick={() => { confirmationRequest.current += 1; setConfirmDelete(null); }}
className="px-4 py-2 rounded-lg text-sm font-medium text-zinc-400 hover:text-zinc-200 hover:bg-zinc-800 transition-colors"
>
Cancel
diff --git a/src/scanView.ts b/src/scanView.ts
new file mode 100644
index 0000000..aabab12
--- /dev/null
+++ b/src/scanView.ts
@@ -0,0 +1,79 @@
+/** IPC records contain IDs and labels; only Rust owns the scan tree and paths. */
+export interface ScanNode {
+ id: number;
+ parent_id: number | null;
+ name: string;
+ type: "file" | "directory";
+ size: number;
+ counted: boolean;
+ child_count: number;
+ can_delete: boolean;
+}
+export interface ScanResponse {
+ status: string;
+ generation: string;
+ revision: number;
+ root_path: string;
+ root: ScanNode;
+ streamed?: boolean;
+ scan_time_ms: number;
+ total_files: number;
+ total_dirs: number;
+ total_size: number;
+ errors: number;
+ read_only: boolean;
+ skipped: number;
+ /** Per-phase timings from daemon v1.2+ (issue #3); absent in older daemons. */
+ traverse_ms?: number;
+ sort_ms?: number;
+ serialize_ms?: number;
+ send_ms?: number;
+ bytes_sent?: number;
+}
+export interface PageCursor { direction: "next" | "previous"; node_id: number }
+export interface ScanView {
+ generation: string;
+ revision: number;
+ node: ScanNode;
+ path: string;
+ breadcrumbs: { id: number; name: string }[];
+ children: ScanNode[];
+ previous_cursor: PageCursor | null;
+ next_cursor: PageCursor | null;
+ chart: { node_id: number | null; name: string; size: number }[];
+}
+export interface NodeDetail {
+ generation: string;
+ revision: number;
+ node: ScanNode;
+ path: string;
+}
+export interface DeleteResult {
+ summary: ScanResponse;
+ message: string;
+ removed: { files: number; dirs: number; size: number };
+}
+export interface ScanScope { generation: string; revision: number }
+export function sameScan(a: ScanScope | null, b: ScanScope): boolean {
+ return a?.generation === b.generation && a.revision === b.revision;
+}
+export function viewKey(scope: ScanScope, nodeId: number, cursor: PageCursor | null): string {
+ return JSON.stringify([scope.generation, scope.revision, nodeId, cursor?.direction, cursor?.node_id]);
+}
+export interface ViewState {
+ request: number;
+ key: string;
+ page?: ScanView;
+ error?: string;
+}
+export type ViewAction =
+ | { type: "start"; request: number; key: string }
+ | { type: "success"; request: number; page: ScanView }
+ | { type: "error"; request: number; error: string };
+/** Responses to an older page/snapshot cannot replace the current request. */
+export function viewReducer(state: ViewState, action: ViewAction): ViewState {
+ if (action.type === "start") return { request: action.request, key: action.key };
+ if (action.request !== state.request) return state;
+ if (action.type === "success") return { ...state, page: action.page };
+ return { ...state, error: action.error };
+}
diff --git a/src/useScanView.ts b/src/useScanView.ts
new file mode 100644
index 0000000..8a39d1f
--- /dev/null
+++ b/src/useScanView.ts
@@ -0,0 +1,38 @@
+import { useEffect, useReducer, useRef, useState } from "react";
+import { invoke } from "@tauri-apps/api/core";
+import { sameScan, viewKey, viewReducer } from "./scanView";
+import type { PageCursor, ScanScope, ScanView } from "./scanView";
+
+export function useScanView(scope: ScanScope, nodeId: number, enabled: boolean) {
+ const base = viewKey(scope, nodeId, null);
+ const [position, setPosition] = useState<{ base: string; cursor: PageCursor | null }>({ base, cursor: null });
+ // Reset synchronously on deletion/rescan/zoom, before the query effect runs.
+ const cursor = position.base === base ? position.cursor : null;
+ const key = viewKey(scope, nodeId, cursor);
+ const [state, dispatch] = useReducer(viewReducer, { request: 0, key: "" });
+ const request = useRef(0);
+ const [retry, setRetry] = useState(0);
+ useEffect(() => {
+ if (!enabled) return;
+ const id = ++request.current;
+ let current = true;
+ dispatch({ type: "start", request: id, key });
+ void invoke<string>("get_scan_view", {
+ generation: scope.generation, revision: scope.revision, nodeId, cursor,
+ }).then(raw => {
+ const page: ScanView = JSON.parse(raw);
+ if (!sameScan(page, scope) || page.node.id !== nodeId) throw new Error("Scan query returned an unexpected view");
+ if (current) dispatch({ type: "success", request: id, page });
+ }).catch(error => {
+ if (current) dispatch({ type: "error", request: id, error: String(error) });
+ });
+ return () => { current = false; };
+ // key includes scope, node and cursor; primitive dependencies keep requests stable.
+ }, [key, enabled, retry]);
+ return {
+ page: enabled && state.key === key ? state.page : undefined,
+ error: enabled && state.key === key ? state.error : undefined,
+ go: (cursor: PageCursor | null) => setPosition({ base, cursor }),
+ retry: () => setRetry(value => value + 1),
+ };
+}
diff --git a/tests/benchmark_scan_store.py b/tests/benchmark_scan_store.py
new file mode 100644
index 0000000..21bc8db
--- /dev/null
+++ b/tests/benchmark_scan_store.py
@@ -0,0 +1,153 @@
+#!/usr/bin/env python3
+"""Headless host comparison; no app, device, or ADB. Requires Rust and Node.
+
+Runs the pinned pre-store decoder and current production store on identical
+stream-v1 bytes. Output includes initial IPC, host time/RSS, and Node memory.
+The temporary Rust harness uses the repository's existing serde dependencies.
+"""
+import json
+from pathlib import Path
+import shutil
+import struct
+import subprocess
+import sys
+import tempfile
+import tomllib
+
+REPO = Path(__file__).resolve().parents[1]
+if sys.platform not in ("darwin", "linux"):
+ sys.exit("RSS benchmark requires macOS or Linux /usr/bin/time")
+
+BASELINE = "9326b4221adb410c3cbf8562e2777471a4c30083"
+FILES = 86_666
+DIRS = 32
+
+
+def run(*args, **kwargs):
+ try:
+ return subprocess.run(args, check=True, text=True, **kwargs)
+ except subprocess.CalledProcessError as error:
+ if error.stderr:
+ print(error.stderr[-4000:], file=sys.stderr)
+ raise
+
+
+def frame(output, kind, data):
+ payload = json.dumps({"type": kind, "data": data}, ensure_ascii=False, separators=(",", ":")).encode()
+ output.write(struct.pack(">I", len(payload)))
+ output.write(payload)
+
+
+with tempfile.TemporaryDirectory(prefix="socketsweep-store-bench-") as directory:
+ work = Path(directory)
+ source = work / "src"
+ source.mkdir()
+ (source / "baseline_stream.rs").write_text(run("git", "show", f"{BASELINE}:src-tauri/src/scan_stream.rs", cwd=REPO, capture_output=True).stdout)
+ shutil.copy(REPO / "src-tauri/src/scan_stream.rs", source / "scan_stream.rs")
+ shutil.copy(REPO / "src-tauri/src/scan_store.rs", source / "scan_store.rs")
+ # Pin the versions in the app lockfile, then reuse its downloaded cache.
+ lock = tomllib.loads((REPO / "src-tauri/Cargo.lock").read_text())
+ versions = {package["name"]: package["version"] for package in lock["package"]}
+ (work / "Cargo.toml").write_text('''[package]
+name = "socketsweep-store-benchmark"
+version = "0.0.0"
+edition = "2021"
+[dependencies]
+serde = { version = "1", features = ["derive"] }
+serde_json = "1"
+[[bin]]
+name = "baseline"
+path = "src/baseline.rs"
+[[bin]]
+name = "current"
+path = "src/current.rs"
+'''.replace('version = "1", features', 'version = "=' + versions['serde'] + '", features').replace('serde_json = "1"', 'serde_json = "=' + versions['serde_json'] + '"'))
+ common = '''const TCP_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
+use std::io::{Read, Write};
+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 started = std::time::Instant::now();
+ 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();
+'''
+ (source / "baseline.rs").write_text('#[path="baseline_stream.rs"] mod scan_stream;\n' + common + '''
+ let payload = response.json().unwrap();
+ std::fs::File::create(&args[2]).unwrap().write_all(payload.as_bytes()).unwrap();
+ println!("{}", serde_json::json!({"ipc_bytes":payload.len(),"host_ms":started.elapsed().as_secs_f64()*1000.0}));
+}
+''')
+ (source / "current.rs").write_text('const MAX_COMMAND_BYTES: usize = 16*1024;\nmod scan_stream;\nmod scan_store;\n' + common + '''
+ let store = scan_store::Catalog::new(response, "a".repeat(64));
+ let summary = store.summary_json().unwrap();
+ let root = store.view_json(&"a".repeat(64), 0, 0, None).unwrap();
+ let page = store.view_json(&"a".repeat(64), 0, 1, None).unwrap();
+ let payload = format!("[{summary},{root},{page}]");
+ std::fs::File::create(&args[2]).unwrap().write_all(payload.as_bytes()).unwrap();
+ println!("{}", serde_json::json!({"ipc_bytes":summary.len()+root.len()+page.len(),"host_ms":started.elapsed().as_secs_f64()*1000.0}));
+}
+''')
+ stream = work / "fixture.stream"
+ entries = [{"id": 0, "parent": None, "name": "fixture", "kind": "directory", "size": 0, "counted": True}]
+ entries += [{"id": i+1, "parent": 0, "name": f"folder-{i:02}", "kind": "directory", "size": 0, "counted": True} for i in range(DIRS)]
+ total = 0
+ for i in range(FILES):
+ size = (i * 7919) % 10_000_000
+ total += size
+ entries.append({"id": i+DIRS+1, "parent": i % DIRS+1, "name": f"file-{i:06}.dat", "kind": "file", "size": size, "counted": True})
+ with stream.open("wb") as output:
+ frame(output, "started", {"stream_version": 1, "root": "/fixture", "read_only": False})
+ for offset in range(0, len(entries), 128):
+ frame(output, "entries", {"entries": entries[offset:offset+128]})
+ 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()})
+ run("cargo", "build", "--offline", "--release", cwd=work, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
+ results = {"baseline_commit": BASELINE, "files": FILES, "directories": DIRS+1, "total_size": total, "runs": {}}
+ node = work / "memory.mjs"
+ node.write_text('''import fs from "node:fs";
+import v8 from "node:v8";
+global.gc();
+const initialHeap = v8.getHeapStatistics().used_heap_size;
+const start = performance.now();
+const raw = fs.readFileSync(process.argv[2], "utf8");
+const data = JSON.parse(raw);
+const parseMs = performance.now() - start;
+let cloneMs = null;
+let copy;
+if (process.argv[3] === "baseline") {
+ const started = performance.now();
+ copy = JSON.parse(JSON.stringify(data));
+ cloneMs = performance.now() - started;
+}
+console.log(JSON.stringify({parse_ms:parseMs, clone_ms:cloneMs,
+ heap_delta_bytes:v8.getHeapStatistics().used_heap_size-initialHeap,
+ max_rss_kib:process.resourceUsage().maxRSS}));
+// Retain the objects through measurement, as the frontend's before/after trees.
+if (!data || (process.argv[3] === "baseline" && !copy)) throw Error("missing data");
+''')
+ for mode in ["baseline", "current"]:
+ output = work / f"{mode}.json"
+ samples = []
+ for _ in range(3):
+ command = ["/usr/bin/time", "-l" if sys.platform == "darwin" else "-v", str(work / "target/release" / mode), str(stream), str(output)]
+ measurement = run(*command, capture_output=True)
+ metrics = json.loads(measurement.stdout)
+ lines = measurement.stderr.splitlines()
+ rss = next(line for line in lines if "maximum resident set size" in line.lower())
+ metrics["host_max_rss_bytes"] = int(rss.strip().split()[0]) if sys.platform == "darwin" else int(rss.rsplit(":", 1)[1]) * 1024
+ metrics["javascript"] = json.loads(run("node", "--expose-gc", str(node), str(output), mode, capture_output=True).stdout)
+ samples.append(metrics)
+ results["runs"][mode] = samples
+ baseline = json.loads((work / "baseline.json").read_text())
+ current = json.loads((work / "current.json").read_text())
+ for key in ["total_files", "total_dirs", "total_size"]:
+ assert baseline[key] == current[0][key]
+ expected = next(child for child in baseline["tree"]["children"] if child["name"] == "folder-00")
+ assert current[2]["node"]["size"] == expected["size"]
+ assert [child["name"] for child in current[2]["children"]] == [child["name"] for child in expected["children"][:128]]
+ assert sum(tile["size"] for tile in current[2]["chart"]) == expected["size"]
+ results["verified"] = "totals, sample directory ordering, and exact treemap sum"
+ print(json.dumps(results, indent=2))
diff --git a/tests/check_scan_ui.py b/tests/check_scan_ui.py
new file mode 100644
index 0000000..7960b70
--- /dev/null
+++ b/tests/check_scan_ui.py
@@ -0,0 +1,84 @@
+#!/usr/bin/env python3
+"""Check the built UI in headless Chromium with mocked IPC, never ADB/Tauri.
+
+Run npm run build first. Uses installed Chrome/Chromium, no added packages.
+"""
+from functools import partial
+from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer
+import json
+import os
+from pathlib import Path
+from queue import Empty, Queue
+import shutil
+import signal
+import subprocess
+import sys
+import tempfile
+import threading
+
+if sys.platform not in ("darwin", "linux"):
+ sys.exit("Headless UI harness supports macOS and Linux")
+
+REPO = Path(__file__).resolve().parents[1]
+chrome = (sys.argv[1] if len(sys.argv) > 1 else
+ shutil.which('chromium') or shutil.which('google-chrome') or
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome')
+if not Path(chrome).is_file():
+ sys.exit('Chrome/Chromium missing; pass its executable as the first argument')
+reports = Queue()
+
+class Handler(SimpleHTTPRequestHandler):
+ def log_message(self, *args):
+ pass
+ def do_POST(self):
+ length = int(self.headers.get('Content-Length', '0'))
+ if self.path != '/report' or not 0 < length < 64 * 1024:
+ self.send_error(400)
+ return
+ value = json.loads(self.rfile.read(length))
+ self.send_response(200)
+ self.end_headers()
+ reports.put(value)
+
+with tempfile.TemporaryDirectory(prefix='socketsweep-ui-test-') as directory:
+ work = Path(directory)
+ shutil.copytree(REPO / 'dist', work / 'site')
+ shutil.copy(REPO / 'tests/scan_ui_fixture.js', work / 'site/fixture.js')
+ index = work / 'site/index.html'
+ html = index.read_text().replace('<head>', '<head><script src="/fixture.js"></script>')
+ # Avoid external font requests during this isolated local fixture.
+ html = '\n'.join(line for line in html.splitlines() if 'fonts.google' not in line)
+ index.write_text(html)
+ server = ThreadingHTTPServer(('127.0.0.1', 0), partial(Handler, directory=str(work / 'site')))
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ try:
+ with (work / 'chrome.log').open('w+') as log:
+ process = subprocess.Popen([chrome, '--headless', '--disable-gpu', '--no-first-run',
+ '--use-mock-keychain', '--password-store=basic', '--enable-logging=stderr',
+ '--disable-background-networking', '--disable-extensions', '--window-size=1280,1000',
+ f'--user-data-dir={work / "profile"}', f'http://127.0.0.1:{server.server_port}'],
+ stdout=log, stderr=log, start_new_session=True)
+ try:
+ value = reports.get(timeout=40)
+ print(json.dumps(value, indent=2))
+ if not value['passed']:
+ sys.exit(1)
+ except Empty:
+ log.seek(0)
+ sys.exit('Headless browser timed out: ' + log.read()[-3000:])
+ finally:
+ try:
+ os.killpg(process.pid, signal.SIGTERM)
+ except ProcessLookupError:
+ pass
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ finally:
+ server.shutdown()
+ server.server_close()
diff --git a/tests/scan_ui_fixture.js b/tests/scan_ui_fixture.js
new file mode 100644
index 0000000..b5ed174
--- /dev/null
+++ b/tests/scan_ui_fixture.js
@@ -0,0 +1,173 @@
+// Real built frontend, mocked Tauri IPC. No native app, ADB or device calls.
+(() => {
+ const calls = [];
+ let generation = 1;
+ let revision = 0;
+ let unavailable = false;
+ let readOnly = false;
+ let delayedZoom = true;
+ let delayedDetail = true;
+ let failDelete = false;
+ let callbacks = 0;
+ let rootChildren;
+ let folderChildren;
+ const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
+ const check = (condition, message) => { if (!condition) throw Error(message); };
+ const node = (id, parent_id, name, size, directory = false) => ({
+ id, parent_id, name, size, type: directory ? "directory" : "file", counted: true,
+ child_count: directory ? 200 : 0, can_delete: id !== 0 && !readOnly,
+ });
+ const reset = () => {
+ folderChildren = Array.from({ length: 200 }, (_, i) => node(i + 1001, 1, `nested-${i}`, 1));
+ rootChildren = [node(1, 0, "large-folder", 200, true), ...Array.from({ length: 270 }, (_, i) => node(i + 2, 0, ` file-${i} `, 1))];
+ unavailable = false;
+ revision = 0;
+ };
+ reset();
+ const scope = () => ({ generation: `fixture-${generation}`, revision });
+ const summary = () => ({
+ ...scope(), status: "ok", root_path: "/fixture", root: { ...node(0, null, "fixture", 470 - (271 - rootChildren.length), true), child_count: rootChildren.length },
+ total_files: rootChildren.length - 1 + folderChildren.length, total_dirs: 2,
+ total_size: 470 - (271 - rootChildren.length), errors: 0, skipped: 0, scan_time_ms: 1, read_only: readOnly,
+ });
+ const detail = id => {
+ const target = id === 0 ? summary().root : [...rootChildren, ...folderChildren].find(item => item.id === id);
+ check(target, "Unknown mock node");
+ return { ...scope(), node: target, path: `/fixture/${target.parent_id === 1 ? "large-folder/" : ""}${target.name}` };
+ };
+ const view = args => {
+ const directory = args.nodeId === 0 ? summary().root : detail(args.nodeId).node;
+ const all = args.nodeId === 0 ? rootChildren : args.nodeId === 1 ? folderChildren : [];
+ let offset = 0;
+ if (args.cursor) {
+ const position = all.findIndex(item => item.id === args.cursor.node_id);
+ offset = args.cursor.direction === "next" ? position + 1 : Math.max(0, position - 128);
+ }
+ const children = all.slice(offset, offset + 128);
+ const chart = all.slice(0, 64).map(item => ({ node_id: item.id, name: item.name, size: item.size }));
+ const remainder = directory.size - chart.reduce((sum, tile) => sum + tile.size, 0);
+ if (all.length && remainder) chart.push({ node_id: null, name: "Other", size: remainder });
+ return { ...scope(), node: directory, path: args.nodeId === 0 ? "/fixture" : detail(args.nodeId).path,
+ breadcrumbs: args.nodeId === 0 ? [{ id: 0, name: "fixture" }] : [{ id: 0, name: "fixture" }, { id: args.nodeId, name: directory.name }],
+ children, chart,
+ previous_cursor: offset ? { direction: "previous", node_id: children[0].id } : null,
+ next_cursor: offset + children.length < all.length ? { direction: "next", node_id: children.at(-1).id } : null,
+ };
+ };
+ window.__TAURI_INTERNALS__ = {
+ transformCallback: () => ++callbacks,
+ unregisterCallback: () => {},
+ invoke: async (command, args = {}) => {
+ calls.push({ command, args });
+ if (command === "check_adb") return "Mock ADB";
+ if (command === "init_daemon") return "Mock daemon";
+ if (command === "run_scan") { generation++; reset(); return JSON.stringify(summary()); }
+ if (command === "stop_daemon") { unavailable = true; return "Mock stopped"; }
+ check(!unavailable, "Snapshot unavailable");
+ check(args.generation === scope().generation && args.revision === revision, "Stale mock snapshot");
+ if (command === "get_scan_view") {
+ const response = JSON.stringify(view(args));
+ if (args.nodeId === 1 && delayedZoom) { delayedZoom = false; await pause(300); }
+ return response;
+ }
+ if (command === "get_scan_node") {
+ const response = JSON.stringify(detail(args.nodeId));
+ if (delayedDetail) { delayedDetail = false; await pause(300); }
+ return response;
+ }
+ if (command === "delete_item") {
+ check(!("path" in args), "Frontend passed a destructive path");
+ check(args.nodeId !== 0 && !readOnly, "Unsafe mock deletion");
+ if (failDelete) { unavailable = true; throw "Partially deleted directory"; }
+ const selected = detail(args.nodeId);
+ rootChildren = rootChildren.filter(item => item.id !== args.nodeId);
+ revision++;
+ return JSON.stringify({ summary: summary(), message: "Deleted fixture item", removed: { files: 1, dirs: 0, size: selected.node.size } });
+ }
+ throw Error(`Unexpected IPC ${command}`);
+ },
+ };
+ const waitFor = async (predicate, message) => {
+ const end = Date.now() + 3000;
+ while (!predicate()) { if (Date.now() > end) throw Error(message); await pause(20); }
+ };
+ const button = text => [...document.querySelectorAll("button")].find(item => item.textContent.trim() === text && !item.disabled);
+ const rows = () => [...document.querySelectorAll(".file-row")];
+ const zoomFolder = () => [...rows().find(item => item.textContent.includes("large-folder")).querySelectorAll("button")]
+ .find(item => item.textContent.trim() === "Zoom").click();
+ const report = (passed, error) => {
+ const output = document.createElement("pre");
+ output.id = "scan-test-report";
+ output.textContent = JSON.stringify({ passed, error, ipc_calls: calls.length, checks: passed ? ["file label semantics", "complete paging", "late zoom", "Other tile", "stale confirmation", "ID-only deletion", "revision refresh", "partial failure", "read-only"] : undefined });
+ document.body.append(output);
+ void fetch("/report", { method: "POST", body: output.textContent });
+ };
+ void (async () => {
+ await waitFor(() => document.querySelector("#btn-connect"), "Setup did not render");
+ document.querySelector("#btn-connect").click();
+ await waitFor(() => rows().length === 129, "Initial page did not render 128 children");
+ 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 firstNames = rows().map(item => item.textContent);
+ button("Next").click();
+ await waitFor(() => rows().some(item => item.textContent.includes("file-127")), "Next page missing");
+ button("Next").click();
+ await waitFor(() => rows().length === 16, "Final 15 children missing");
+ button("Previous").click();
+ await waitFor(() => rows().length === 129, "Previous page missing");
+ button("Previous").click();
+ await waitFor(() => rows().some(item => item.textContent.includes("large-folder")), "First page missing");
+ check(JSON.stringify(rows().map(item => item.textContent)) === JSON.stringify(firstNames), "Paging changed ordering");
+
+ zoomFolder();
+ await waitFor(() => button("← Back to Root"), "Zoom navigation missing");
+ button("← Back to Root").click();
+ await waitFor(() => rows()[0]?.textContent.includes("fixture") && !button("← Back to Root"), "Root did not reload");
+ // Folder expansion persists across zoom. Close it to isolate the late
+ // root-view response from an independent, valid child-directory query.
+ const folder = rows().find(item => item.textContent.includes("large-folder"));
+ if (folder.querySelector('[aria-expanded="true"]')) folder.querySelector('[aria-expanded]').click();
+ await pause(350);
+ check(rows().length === 129 && !button("← Back to Root"), "Late zoom replaced root view");
+ await waitFor(() => [...document.querySelectorAll("svg text")].some(item => item.textContent === "Other"), "Other tile missing");
+ const before = calls.filter(item => item.command === "get_scan_view").length;
+ const other = [...document.querySelectorAll("svg text")].find(item => item.textContent === "Other");
+ other.dispatchEvent(new MouseEvent("click", { bubbles: true }));
+ await pause(30);
+ check(calls.filter(item => item.command === "get_scan_view").length === before, "Other tile zoomed");
+
+ document.querySelector('[aria-label="Delete file-0 "]').click();
+ document.querySelector("#btn-rescan").click();
+ await waitFor(() => rows().length === 129, "Rescan did not reload");
+ await pause(350);
+ check(!button("NUKE IT"), "Old confirmation survived rescan");
+ 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");
+ check(calls.some(item => item.command === "delete_item" && item.args.nodeId === 2 && !("path" in item.args)), "ID-only delete was not invoked");
+
+ zoomFolder();
+ await waitFor(() => rows().some(item => item.textContent.includes("nested-0")), "Nested directory missing");
+ button("Next").click();
+ await waitFor(() => rows().length === 73, "Nested final page missing");
+ button("← Back to Root").click();
+ await waitFor(() => document.querySelector('[aria-label="Delete file-1 "]'), "Root after zoom missing");
+ failDelete = true;
+ document.querySelector('[aria-label="Delete file-1 "]').click();
+ await waitFor(() => button("NUKE IT"), "Second confirmation missing");
+ button("NUKE IT").click();
+ await waitFor(() => document.querySelector("#btn-connect") && !document.querySelector("#btn-connect").disabled, "Partial failure did not clear results");
+ check(rows().length === 0, "Invalid snapshot remained visible");
+ check(calls.at(-1).command === "stop_daemon", "Partial failure did not stop session");
+
+ failDelete = false;
+ readOnly = true;
+ 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");
+ check(!document.querySelector('[aria-label^="Delete "]'), "Read-only deletion enabled");
+ report(true);
+ })().catch(error => report(false, error.stack));
+})();
diff --git a/tests/scan_view.test.mjs b/tests/scan_view.test.mjs
new file mode 100644
index 0000000..1843aee
--- /dev/null
+++ b/tests/scan_view.test.mjs
@@ -0,0 +1,83 @@
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+import ts from "typescript";
+
+const source = await readFile(new URL("../src/scanView.ts", import.meta.url), "utf8");
+const { outputText } = ts.transpileModule(source, {
+ compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext },
+});
+const { sameScan, viewKey, viewReducer } = await import(
+ `data:text/javascript;base64,${Buffer.from(outputText).toString("base64")}`
+);
+const scope = { generation: "scan-a", revision: 0 };
+const page = (nodeId = 0, revision = 0, generation = "scan-a") => ({
+ generation, revision, node: { id: nodeId }, children: [],
+});
+
+test("scope rejects disconnected, replaced and deleted snapshots", () => {
+ assert.equal(sameScan(null, scope), false);
+ assert.equal(sameScan(scope, scope), true);
+ assert.equal(sameScan({ ...scope, generation: "scan-b" }, scope), false);
+ assert.equal(sameScan({ ...scope, revision: 1 }, scope), false);
+});
+
+test("query identity distinguishes nodes, cursor direction, revisions and generations", () => {
+ const keys = [
+ viewKey(scope, 0, null), viewKey(scope, 1, null),
+ viewKey(scope, 0, { direction: "next", node_id: 128 }),
+ viewKey(scope, 0, { direction: "previous", node_id: 128 }),
+ viewKey(scope, 0, { direction: "next", node_id: 256 }),
+ viewKey({ ...scope, revision: 1 }, 0, null),
+ viewKey({ ...scope, generation: "scan-b" }, 0, null),
+ ];
+ assert.equal(new Set(keys).size, keys.length);
+});
+
+test("late success and errors cannot replace a newer directory request", () => {
+ let state = viewReducer({ request: 0, key: "" }, { type: "start", request: 1, key: "root" });
+ state = viewReducer(state, { type: "start", request: 2, key: "folder" });
+ const pending = state;
+ assert.equal(viewReducer(state, { type: "success", request: 1, page: page() }), pending);
+ assert.equal(viewReducer(state, { type: "error", request: 1, error: "stale failure" }), pending);
+ state = viewReducer(state, { type: "success", request: 2, page: page(1) });
+ assert.equal(state.page.node.id, 1);
+ assert.equal(state.key, "folder");
+});
+
+test("revision refresh clears visible rows before old responses complete", () => {
+ let state = viewReducer({ request: 0, key: "" }, { type: "start", request: 1, key: viewKey(scope, 0, null) });
+ state = viewReducer(state, { type: "success", request: 1, page: page() });
+ state = viewReducer(state, { type: "start", request: 2, key: viewKey({ ...scope, revision: 1 }, 0, null) });
+ assert.equal(state.page, undefined);
+ assert.equal(state.error, undefined);
+ const waiting = state;
+ assert.equal(viewReducer(state, { type: "success", request: 1, page: page() }), waiting);
+ state = viewReducer(state, { type: "success", request: 2, page: page(0, 1) });
+ assert.equal(state.page.revision, 1);
+});
+
+test("page navigation A-B-A still rejects the first A response", async () => {
+ let resolveFirst;
+ const first = new Promise(resolve => { resolveFirst = resolve; });
+ let state = { request: 0, key: "" };
+ const complete = first.then(value => { state = viewReducer(state, { type: "success", request: 1, page: value }); });
+ for (const [request, key] of [[1, "A"], [2, "B"], [3, "A"]]) {
+ state = viewReducer(state, { type: "start", request, key });
+ }
+ resolveFirst(page(0));
+ await complete;
+ assert.equal(state.page, undefined);
+ state = viewReducer(state, { type: "success", request: 3, page: page(0, 1) });
+ assert.equal(state.page.revision, 1);
+});
+
+test("retry clears the error and ignores the prior failure", () => {
+ let state = viewReducer({ request: 0, key: "" }, { type: "start", request: 1, key: "root" });
+ state = viewReducer(state, { type: "error", request: 1, error: "connection lost" });
+ assert.equal(state.error, "connection lost");
+ state = viewReducer(state, { type: "start", request: 2, key: "root" });
+ assert.equal(state.error, undefined);
+ const pending = state;
+ assert.equal(viewReducer(state, { type: "error", request: 1, error: "old error" }), pending);
+});
diff --git a/tests/test_stream_scan.py b/tests/test_stream_scan.py
index 90fc4eb..e454b49 100644
--- a/tests/test_stream_scan.py
+++ b/tests/test_stream_scan.py
@@ -1,4 +1,5 @@
"""Stream contract and end-to-end daemon tests on disposable host fixtures."""
+import errno
import json
import os
import socket
@@ -102,6 +103,33 @@ class StreamScanTests(DaemonHarness):
self.assertEqual(actual, expected)
self.assertGreater(len(batches), 5)
+ def test_non_utf8_filename_bytes_are_not_silently_replaced(self):
+ path = os.fsencode(self.root) + b'/nonutf-\xff'
+ try:
+ fd = os.open(path, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600)
+ except OSError as error:
+ if error.errno in (errno.EILSEQ, errno.EINVAL):
+ self.skipTest('Filesystem does not support non-UTF-8 filenames')
+ raise
+ os.close(fd)
+ with self.connect_scan() as client:
+ found = False
+ while True:
+ size, = struct.unpack('!I', exact(client, 4))
+ self.assertTrue(0 < size <= MAX_FRAME)
+ payload = exact(client, size)
+ if b'nonutf-\xff' in payload:
+ # Stream v1 has no raw-byte filename field. Rust must reject
+ # this JSON rather than replace bytes and publish a wrong path.
+ with self.assertRaises(UnicodeDecodeError):
+ payload.decode('utf-8')
+ found = True
+ break
+ if json.loads(payload)['type'] in ('done', 'error'):
+ break
+ self.assertTrue(found)
+ self.assertEqual(self.request('PING')['status'], 'ok')
+
def test_root_and_first_entry_arrive_before_scan_completion(self):
for i in range(5000):
(self.root / str(i)).write_bytes(b'123')