A high-performance Android storage analyzer that bypasses MTP using a native C++ daemon, a Rust TCP bridge, and a React Treemap UI.
Rust
Show unreadable folders in scan results (#214)
Vishnu Srivatsava49a8a3bc91a4
diff --git a/docs/scan-stream-v1.md b/docs/scan-stream-v1.mdindex 1939dfb..8aab6b1 100644--- a/docs/scan-stream-v1.md+++ b/docs/scan-stream-v1.md@@ -69,6 +69,32 @@ The daemon pins its pending root separately and promotes it only after anunchanged-root check and successful completion write. Existing descriptor-anchored deletion and root read-only checks remain in force.+## Unreadable directory diagnostics++A daemon that advertises `scan_directory_errors: true` in `PING` accepts+`SCAN_DETAIL <absolute root>`. It follows the same stream rules as+`SCAN_STREAM` and adds one field to the `done` payload:++```json+{"unreadable_directories":{"ids":[42,51],"omitted":0}}+```++The daemon records directory-open or iteration failures. The sample holds at+most eight distinct directory IDs. Additional failures increment `omitted`,+which is zero until the sample is full. The order in which parallel workers+encounter failures can change which directories appear. A directory that+could only be read in part may contain some scanned entries. Empty folders,+depth limits, failures to stat individual entries, exclusions, and duplicate+inodes do not produce unreadable-directory diagnostics. Existing error and+exclusion counters and scan totals keep their meanings.++The host validates the IDs against counted directories in the completed tree,+checks the sample and omitted count against the aggregate error count, and+reconstructs paths from the verified root and entry names. The results screen+displays those paths as text and keeps the details attached to the completed+scan until a rescan. Older clients and daemons can continue using+`SCAN_STREAM`, which retains its original payload.+## Bounds and cancellationNormal scanning retains immediate directory jobs rather than completed filediff --git a/engine/daemon.cpp b/engine/daemon.cppindex bcceb56..ee879d5 100644--- a/engine/daemon.cpp+++ b/engine/daemon.cpp@@ -331,14 +331,24 @@ static FileNode scan(const std::string& path, const std::string& name,if (depth >= cfg::MAX_DEPTH) { ++st.errors; return node; }DIR* dir = ::opendir(path.c_str());- if (!dir) { ++st.errors; return node; }+ if (!dir) {+ ++st.errors;+ if (output) output->unreadable_directory(id);+ return node;+ }struct dirent* ent;while (true) {if (output && !output->alive()) break;errno = 0;ent = ::readdir(dir);- if (!ent) { if (output && errno != 0) ++st.errors; break; }+ if (!ent) {+ if (output && errno != 0) {+ ++st.errors;+ output->unreadable_directory(id);+ }+ break;+ }if (ent->d_name[0] == '.') {if (ent->d_name[1] == '\0') continue;if (ent->d_name[1] == '.' && ent->d_name[2] == '\0') continue;@@ -394,7 +404,7 @@ static void handle_client(int fd) {}if (cmd == "PING") {- out.write("{\"status\":\"ok\",\"message\":\"pong\",\"protocol_version\":3,\"scan_stream_version\":1,\"uid\":");+ out.write("{\"status\":\"ok\",\"message\":\"pong\",\"protocol_version\":3,\"scan_stream_version\":1,\"scan_directory_errors\":true,\"uid\":");out.write(std::to_string(::geteuid()));out.write(",\"read_only\":");out.write(g_read_only ? "true" : "false");@@ -442,7 +452,11 @@ static void handle_client(int fd) {}}else if (cmd == "SCAN_STREAM" || cmd.rfind("SCAN_STREAM ", 0) == 0) {- stream_scan::handle(fd, cmd.size() > 11 ? cmd.substr(12) : cfg::DEFAULT_ROOT);+ stream_scan::handle(fd, cmd.size() > 11 ? cmd.substr(12) : cfg::DEFAULT_ROOT, false);+ return;+ }+ else if (cmd == "SCAN_DETAIL" || cmd.rfind("SCAN_DETAIL ", 0) == 0) {+ stream_scan::handle(fd, cmd.size() > 11 ? cmd.substr(12) : cfg::DEFAULT_ROOT, true);return;}else if (cmd == "SCAN" || cmd.rfind("SCAN ", 0) == 0) {diff --git a/engine/scan_output.h b/engine/scan_output.hindex 828dad0..274b95f 100644--- a/engine/scan_output.h+++ b/engine/scan_output.h@@ -1,5 +1,7 @@#pragma once+#include <array>+// Stream v1 is bounded, length-prefixed JSON, independent of the legacy SCAN// response. Entries precede their children; directory totals are computed by// the host. No lossy filename conversion is performed by either endpoint.@@ -9,7 +11,12 @@ class ScanOutput {bool write(const std::string& s) { text += s; return true; }bool write(const char* s, size_t n) { text.append(s, n); return true; }};+ static constexpr size_t MAX_UNREADABLE_DIRECTORIES = 8;int fd_;+ const bool report_directory_errors_;+ std::array<uint64_t, MAX_UNREADABLE_DIRECTORIES> unreadable_directories_{};+ size_t unreadable_sample_size_ = 0;+ uint64_t unreadable_omitted_ = 0;std::mutex mutex_;std::atomic<bool> failed_{false};uint64_t next_id_ = 0;@@ -76,7 +83,19 @@ class ScanOutput {public:static constexpr size_t MAX_FRAME_BYTES = 128 * 1024;static constexpr size_t MAX_BATCH_ENTRIES = 128;- explicit ScanOutput(int fd) : fd_(fd) { batch_.reserve(64 * 1024); }+ ScanOutput(int fd, bool report_directory_errors)+ : fd_(fd), report_directory_errors_(report_directory_errors) {+ batch_.reserve(64 * 1024);+ }+ void unreadable_directory(uint64_t id) {+ if (!report_directory_errors_) return;+ std::lock_guard<std::mutex> lock(mutex_);+ if (unreadable_sample_size_ < unreadable_directories_.size()) {+ unreadable_directories_[unreadable_sample_size_++] = id;+ } else {+ ++unreadable_omitted_;+ }+ }bool alive() {if (failed_ || !g_running) return false;std::lock_guard<std::mutex> lock(mutex_);@@ -136,13 +155,22 @@ public:bool finish(const ScanStats& stats, int64_t elapsed_ms, int workers) {std::lock_guard<std::mutex> lock(mutex_);if (failed_ || !flush_locked()) return false;- const std::string text = "{\"type\":\"done\",\"total_files\":" + std::to_string(stats.files) ++ std::string text = "{\"type\":\"done\",\"total_files\":" + std::to_string(stats.files) +",\"total_dirs\":" + std::to_string(stats.dirs) + ",\"total_size\":" + std::to_string(stats.total_size) +",\"errors\":" + std::to_string(stats.errors) + ",\"skipped\":" + std::to_string(stats.skipped) +",\"scan_time_ms\":" + std::to_string(elapsed_ms) + ",\"scan_threads\":" + std::to_string(workers) +",\"serialize_ms\":" + std::to_string(ns_to_ms(encode_ns_)) +",\"send_ms\":" + std::to_string(ns_to_ms(g_send_ns)) +- ",\"bytes_sent\":" + std::to_string(g_send_bytes) + "}";+ ",\"bytes_sent\":" + std::to_string(g_send_bytes);+ if (report_directory_errors_) {+ text += ",\"unreadable_directories\":{\"ids\":[";+ for (size_t i = 0; i < unreadable_sample_size_; ++i) {+ if (i) text += ',';+ text += std::to_string(unreadable_directories_[i]);+ }+ text += "],\"omitted\":" + std::to_string(unreadable_omitted_) + "}";+ }+ text += '}';return frame(text);}};diff --git a/engine/stream_scan.h b/engine/stream_scan.hindex 9905849..6e1b85f 100644--- a/engine/stream_scan.h+++ b/engine/stream_scan.h@@ -33,10 +33,18 @@ class Pool {++stats.dirs;if (task.depth >= cfg::MAX_DEPTH) { ++stats.errors; return; }safe_delete::Fd opened = parallel_scan::open_directory(root_, task.node);- if (opened.get() < 0) { ++stats.errors; return; }+ if (opened.get() < 0) {+ ++stats.errors;+ output_.unreadable_directory(task.id);+ return;+ }SOCKETSWEEP_SCAN_CHECKPOINT("opened", opened.get(), task.node.path.c_str());DIR* listing = ::fdopendir(opened.get());- if (!listing) { ++stats.errors; return; }+ if (!listing) {+ ++stats.errors;+ output_.unreadable_directory(task.id);+ return;+ }opened.release();std::vector<Task> directories;struct Staging {@@ -56,7 +64,13 @@ class Pool {while (output_.alive()) {errno = 0;const auto* entry = ::readdir(listing);- if (!entry) { if (errno) ++stats.errors; break; }+ if (!entry) {+ if (errno) {+ ++stats.errors;+ output_.unreadable_directory(task.id);+ }+ break;+ }const std::string name = entry->d_name;if (name == "." || name == "..") continue;#ifdef DT_LNK@@ -158,10 +172,10 @@ public:}};-static void handle(int fd, std::string root) {+static void handle(int fd, std::string root, bool report_directory_errors) {g_scan_root.clear();g_send_ns = 0; g_send_bytes = 0;- ScanOutput output(fd);+ ScanOutput output(fd, report_directory_errors);while (root.size() > 1 && root.back() == '/') root.pop_back();if (root.empty() || root.front() != '/') { output.error("Scan root must be an absolute directory"); return; }if (g_read_only) {diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex 9593a87..f76a8d4 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -264,6 +264,7 @@ struct DaemonStatus {message: Option<String>,protocol_version: Option<u32>,scan_stream_version: Option<u32>,+ scan_directory_errors: Option<bool>,uid: Option<u32>,read_only: Option<bool>,}@@ -408,7 +409,12 @@ fn run_scan(.unwrap_or_else(|| "/sdcard".into());let connection = active_connection()?;let serial = connection.serial.clone();- let payload = command_payload(&format!("SCAN_STREAM {effective_root}"), &connection.token)?;+ let command = if connection.scan_directory_errors {+ "SCAN_DETAIL"+ } else {+ "SCAN_STREAM"+ };+ let payload = command_payload(&format!("{command} {effective_root}"), &connection.token)?;let read_only = connection.read_only;let cancelled = Arc::new(AtomicBool::new(false));let progress_pending = Arc::new(AtomicBool::new(false));@@ -464,6 +470,9 @@ fn run_scan(.map_err(|e| format!("Cannot deliver scan progress: {e}"))},)?;+ if response.unreadable_directories.is_some() != connection.scan_directory_errors {+ return Err("Scan directory diagnostics do not match the daemon's capabilities".into());+ }if !read_only {let normalized = effective_root.trim_end_matches('/');let normalized = if normalized.is_empty() { "/" } else { normalized };diff --git a/src-tauri/src/scan_benchmark.rs b/src-tauri/src/scan_benchmark.rsindex b8b7a5b..911b539 100644--- a/src-tauri/src/scan_benchmark.rs+++ b/src-tauri/src/scan_benchmark.rs@@ -405,6 +405,7 @@ mod tests {token: "0".repeat(64),serial: "fixture-device".into(),read_only: false,+ scan_directory_errors: false,};let server = std::thread::spawn(move || {let (mut socket, _) = listener.accept().unwrap();diff --git a/src-tauri/src/scan_store.rs b/src-tauri/src/scan_store.rsindex 0102ece..9792084 100644--- a/src-tauri/src/scan_store.rs+++ b/src-tauri/src/scan_store.rs@@ -120,6 +120,11 @@ struct NodeSummary<'a> {can_delete: bool,}#[derive(Serialize)]+struct UnreadableDirectories {+ paths: Vec<String>,+ omitted: u64,+}+#[derive(Serialize)]struct Summary<'a> {#[serde(flatten)]stats: &'a Response,@@ -127,6 +132,8 @@ struct Summary<'a> {revision: u32,root_path: &'a str,root: NodeSummary<'a>,+ #[serde(skip_serializing_if = "Option::is_none")]+ unreadable_directories: Option<UnreadableDirectories>,}#[derive(Serialize)]struct Breadcrumb<'a> {@@ -310,6 +317,14 @@ impl Catalog {revision: self.revision,root_path: &self.response.root,root: self.summary_node(0),+ unreadable_directories: self.response.unreadable_directories.as_ref().map(|sample| {+ let mut paths: Vec<_> = sample.ids.iter().map(|&id| self.path(id)).collect();+ paths.sort_unstable();+ UnreadableDirectories {+ paths,+ omitted: sample.omitted,+ }+ }),}}pub fn summary_json(&self) -> Result<String, String> {diff --git a/src-tauri/src/scan_stream.rs b/src-tauri/src/scan_stream.rsindex 690ca8f..11e7ce3 100644--- a/src-tauri/src/scan_stream.rs+++ b/src-tauri/src/scan_stream.rs@@ -10,6 +10,8 @@ use std::time::{Duration, Instant};pub const MAX_FRAME_BYTES: usize = 128 * 1024;const MAX_BATCH_ENTRIES: usize = 128;+// Eight 16 KiB paths fit in the 1 MiB IPC summary even with JSON escaping.+const MAX_UNREADABLE_DIRECTORIES: usize = 8;const MAX_NODES: usize = 2_000_000;const MAX_TREE_BYTES: usize = 128 * 1024 * 1024;#[cfg(test)]@@ -44,11 +46,35 @@ enum Frame {serialize_ms: u64,send_ms: u64,bytes_sent: u64,+ unreadable_directories: Option<UnreadableDirectories>,},Error {message: String,},}+#[derive(Deserialize)]+#[serde(deny_unknown_fields)]+pub(crate) struct UnreadableDirectories {+ pub ids: Vec<u32>,+ pub omitted: u64,+}++impl UnreadableDirectories {+ fn valid(&self, nodes: &[Node], errors: u64) -> bool {+ let count = self.ids.len();+ count <= MAX_UNREADABLE_DIRECTORIES+ && (self.omitted == 0 || count == MAX_UNREADABLE_DIRECTORIES)+ && count as u64 <= errors+ && self.omitted <= errors - count as u64+ && self.ids.iter().enumerate().all(|(index, id)| {+ !self.ids[..index].contains(id)+ && nodes.get(*id as usize).is_some_and(|node| {+ node.kind == Kind::Directory && node.counted+ })+ })+ }+}+#[derive(Deserialize)]#[serde(deny_unknown_fields)]struct Entry {@@ -164,6 +190,8 @@ pub struct Response {pub(crate) total_dirs: u64,pub(crate) total_size: u64,pub(crate) errors: u64,+ #[serde(skip)]+ pub(crate) unreadable_directories: Option<UnreadableDirectories>,pub(crate) skipped: u64,pub(crate) read_only: bool,scan_time_ms: u64,@@ -430,6 +458,7 @@ pub fn read(serialize_ms,send_ms,bytes_sent,+ unreadable_directories,} => {if nodes.is_empty()|| total_files != observed.files@@ -453,6 +482,12 @@ pub fn read("Scan completion does not match received entries or negotiated mode".into(),);}+ if unreadable_directories+ .as_ref()+ .is_some_and(|sample| !sample.valid(&nodes, errors))+ {+ return Err("Invalid unreadable directory diagnostics".into());+ }let mut trailing = [0];if reader.read(&mut trailing)@@ -518,6 +553,7 @@ pub fn read(total_dirs,total_size,errors,+ unreadable_directories,skipped,read_only: expected_read_only,scan_time_ms,@@ -690,6 +726,43 @@ mod tests {.is_err());}#[test]+ fn unreadable_directories_are_bounded_counted_nodes_with_scoped_paths() {+ let mut entries = vec![root(), file()];+ for id in 2..=9 {+ let parent = if id == 3 { 2 } else { 0 };+ entries.push(json!({"id":id,"parent":parent,"name":format!(" folder {id} "),+ "kind":"directory","size":0,"counted":true}));+ }+ entries.push(json!({"id":10,"parent":0,"name":"excluded","kind":"directory","size":0,"counted":false}));+ let read = |ids: Vec<u32>, omitted| {+ parse(stream(entries.clone(), json!({"total_dirs":9,"errors":11,"skipped":1,+ "unreadable_directories":{"ids":ids,"omitted":omitted}})))+ };+ let ids = vec![0, 2, 3, 4, 5, 6, 7, 8];+ let response = read(ids.clone(), 2).unwrap();+ let catalog = crate::scan_store::Catalog::new(response, "generation".into());+ let summary: Value = serde_json::from_str(&catalog.summary_json().unwrap()).unwrap();+ let sample = &summary["unreadable_directories"];+ assert_eq!(sample["omitted"], 2);+ assert_eq!(sample["paths"].as_array().unwrap().len(), 8);+ assert!(sample["paths"].as_array().unwrap().contains(&json!("/fixture/ folder 2 / folder 3 ")));+ assert!(sample["paths"].as_array().unwrap().contains(&json!("/fixture")));+ assert_eq!(summary["errors"], 11);+ assert_eq!(summary["skipped"], 1);++ for (ids, omitted) in [+ ((2..=9).chain([0]).collect(), 0), // over sample budget+ (vec![1], 0), // file+ (vec![10], 0), // excluded directory+ (vec![99], 0), // unknown node+ (vec![2, 2], 0), // duplicate+ (vec![2], 1), // omissions before sample is full+ (ids, 4), // exceeds the access-error count+ ] {+ assert_eq!(read(ids, omitted).err().as_deref(), Some("Invalid unreadable directory diagnostics"));+ }+ }+ #[test]fn rejects_mismatched_completion_and_root_modes() {for changes in [json!({"total_files":0}),diff --git a/src-tauri/src/session.rs b/src-tauri/src/session.rsindex 4d74698..9eae447 100644--- a/src-tauri/src/session.rs+++ b/src-tauri/src/session.rs@@ -22,6 +22,7 @@ pub(super) struct Connection {pub token: String,pub serial: String,pub read_only: bool,+ pub scan_directory_errors: bool,}pub(super) struct Session {@@ -151,6 +152,7 @@ impl Session {token: new_random_id()?,serial,read_only: false,+ scan_directory_errors: false,},})}@@ -345,7 +347,9 @@ impl Session {&self.connection.token,remaining(deadline)?.min(Duration::from_secs(5)),)?;- self.connection.read_only = require_handshake(&pong, root_mode)?.read_only.unwrap();+ let handshake = require_handshake(&pong, root_mode)?;+ self.connection.read_only = handshake.read_only.unwrap();+ self.connection.scan_directory_errors = handshake.scan_directory_errors == Some(true);Ok(format!("{{\"daemon_pid\":\"{}\",\"ping_response\":{pong}}}",ready.piddiff --git a/src/ResultScreen.tsx b/src/ResultScreen.tsxindex 1e21149..88dc99c 100644--- a/src/ResultScreen.tsx+++ b/src/ResultScreen.tsx@@ -60,6 +60,8 @@ export function ResultScreen({}, [view.error, data.root.id]);const breadcrumbs = page?.breadcrumbs ?? [];+ const unreadable = data.unreadable_directories;+ const unreadableCount = unreadable ? unreadable.paths.length + unreadable.omitted : 0;return (<div className="flex flex-col h-full min-h-0 animate-fade-in-up">@@ -163,6 +165,19 @@ export function ResultScreen({{[data.errors > 0 ? `${data.errors} access errors` : "", data.skipped > 0 ? `${data.skipped} excluded or duplicate entries` : ""].filter(Boolean).join(" · ")}</span></div>+ {unreadable && unreadableCount > 0 && (+ <details className="px-3 pb-2 text-xs text-zinc-400">+ <summary className="cursor-pointer text-amber-300">+ {unreadableCount === 1 ? "1 folder could not be read" : `${unreadableCount.toLocaleString("en-US")} folders could not be read`}+ </summary>+ <ul aria-label="Unreadable folder paths" className="mt-1 max-h-32 overflow-y-auto font-mono">+ {unreadable.paths.map(path => (+ <li key={path} className="py-0.5 whitespace-pre-wrap break-all"><bdi>{path}</bdi></li>+ ))}+ </ul>+ {unreadable.omitted > 0 && <p className="mt-1">Plus {unreadable.omitted.toLocaleString("en-US")} more</p>}+ </details>+ )}{!page && !view.error && <p role="status" className="px-3 py-2 text-xs text-zinc-500">Loading storage map…</p>}{view.error && <div data-directory-query={zoomId} data-directory-request={view.request}><QueryError error={view.error} retry={view.retry} /></div>}{page && <FileTreeNode node={page.node} scope={data} parentSize={page.node.size} depth={0}diff --git a/src/scanView.ts b/src/scanView.tsindex 79af998..662b3c2 100644--- a/src/scanView.ts+++ b/src/scanView.ts@@ -21,6 +21,7 @@ export interface ScanResponse {total_dirs: number;total_size: number;errors: number;+ unreadable_directories?: { paths: string[]; omitted: number };read_only: boolean;skipped: number;/** Per-phase timings from daemon v1.2+ (issue #3); absent in older daemons. */@@ -58,6 +59,7 @@ export interface ScanScope { generation: string; revision: number }export const isRecord = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);export const isCount = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;export const isU32 = (value: unknown): value is number => isCount(value) && value <= 0xffff_ffff;+const maxUnreadableDirectories = 8;const encoder = new TextEncoder();const decoder = new TextDecoder("utf-8", { ignoreBOM: true });const textBytes = (value: string) => {@@ -153,6 +155,17 @@ export function parseScanSummary(data: unknown): ScanResponse {for (const field of ["traverse_ms", "sort_ms", "serialize_ms", "send_ms", "bytes_sent"]) {if (data[field] !== undefined && !isCount(data[field])) throw invalid();}+ const unreadable = data.unreadable_directories;+ if (unreadable !== undefined) {+ const prefix = data.root_path === "/" ? "/" : `${data.root_path}/`;+ if (!isRecord(unreadable) || !isCount(unreadable.omitted)+ || !Array.isArray(unreadable.paths) || unreadable.paths.length > maxUnreadableDirectories+ || (unreadable.omitted > 0 && unreadable.paths.length !== maxUnreadableDirectories)+ || unreadable.paths.length > data.errors || unreadable.omitted > data.errors - unreadable.paths.length+ || !unreadable.paths.every(path => typeof path === "string" && textBytes(path) <= 16 * 1024+ && (path === data.root_path || (path.startsWith(prefix) && path.slice(prefix.length).split("/").every(entryName))))+ || new Set(unreadable.paths).size !== unreadable.paths.length) throw invalid();+ }const { node } = parseNodeReference({ node: data.root, path: data.root_path }, {root_path: data.root_path, read_only: data.read_only, total_size: data.total_size,});diff --git a/tests/parallel_scan_test.cpp b/tests/parallel_scan_test.cppindex 0071456..3ba3c86 100644--- a/tests/parallel_scan_test.cpp+++ b/tests/parallel_scan_test.cpp@@ -67,7 +67,7 @@ static Snapshot run(const std::string& path, int workers, bool streaming = falserequire(::socketpair(AF_UNIX, SOCK_STREAM, 0, sockets) == 0, "socketpair failed");safe_delete::Fd writer(sockets[0]), reader(sockets[1]);std::thread drain([&] { char bytes[4096]; while (::recv(reader.get(), bytes, sizeof(bytes), 0) > 0) {} });- ScanOutput output(writer.get());+ ScanOutput output(writer.get(), false);require(output.start(path), "stream start failed");uint64_t id = 0;require(output.entry(snapshot.tree, 0, "directory", true, id), "stream root failed");@@ -248,7 +248,7 @@ static void stream_cancel() {blocked = true; ready.notify_one();ready.wait(lock, [&] { return release; });};- std::thread server([&] { stream_scan::handle(writer.get(), fixture.path); });+ std::thread server([&] { stream_scan::handle(writer.get(), fixture.path, false); });{std::unique_lock<std::mutex> lock(mutex);require(ready.wait_for(lock, std::chrono::seconds(5), [&] { return blocked; }), "traversal barrier not reached");@@ -288,7 +288,7 @@ static void stream_limits_and_root_replacement(bool replace) {require(::rename(path.c_str(), (fixture.path + "/moved").c_str()) == 0, "root rename failed");fixture.dir("root"); fixture.file("root/replacement", 1000000);};- stream_scan::handle(writer.get(), path);+ stream_scan::handle(writer.get(), path, false);checkpoint = {};require(fired && g_scan_root.fd.get() < 0, "changed root enabled deletion");} else {@@ -296,7 +296,7 @@ static void stream_limits_and_root_replacement(bool replace) {require(root.open(path), "root open failed");FileNode node; node.name = "root"; node.path = path; node.is_dir = true;node.device = root.identity.st_dev; node.inode = root.identity.st_ino;- ScanOutput output(writer.get());+ ScanOutput output(writer.get(), false);require(output.start(path), "stream start failed");uint64_t id = 0; require(output.entry(node, 0, "directory", true, id), "root entry failed");stream_scan::Pool pool(root, output, node, 256);diff --git a/tests/scan_ui_fixture.js b/tests/scan_ui_fixture.jsindex f77ecd7..6291330 100644--- a/tests/scan_ui_fixture.js+++ b/tests/scan_ui_fixture.js@@ -35,6 +35,7 @@let expandedTree;let emptyScan = false;let coverageErrors = 0;+ let unreadableDirectories;let coverageSkipped = 0;let failDelete = false;let failScan = false;@@ -86,6 +87,7 @@...scope(), status: "ok", root_path: scanRoot, root: { ...node(0, null, "fixture", rootChildren.reduce((sum, item) => sum + item.size, 0), true), child_count: rootChildren.length },total_files: wideFolders ? 128 * 128 : rootChildren.filter(item => item.type === "file").length + folderChildren.length, total_dirs: 1 + rootChildren.filter(item => item.type === "directory").length,total_size: rootChildren.reduce((sum, item) => sum + item.size, 0), errors: coverageErrors, skipped: coverageSkipped, scan_time_ms: 1, read_only: readOnly,+ unreadable_directories: unreadableDirectories,});const wideEntries = parent => Array.from({ length: 128 }, (_, index) =>node(1000 + (parent - 1) * 128 + index, parent, `entry-${parent}-${index}`, 1));@@ -888,9 +890,20 @@readOnly = true;coverageErrors = 2;coverageSkipped = 3;+ unreadableDirectories = { paths: [`${scanRoot}/large-folder`], omitted: 0 };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");+ const unreadablePaths = document.querySelector('[aria-label="Unreadable folder paths"]');+ const unreadableDetails = unreadablePaths?.closest("details");+ check(unreadableDetails && !unreadableDetails.open, "Unreadable paths should start collapsed");+ const unreadableSummary = unreadableDetails.querySelector("summary");+ check(unreadableSummary.textContent.includes("1 folder could not be read"), "Unreadable folder count missing");+ unreadableSummary.click();+ await waitFor(() => unreadableDetails.open, "Unreadable paths did not expand");+ check(unreadablePaths.textContent === unreadableDirectories.paths[0]+ && !unreadablePaths.querySelector("a, button"), "Unreadable paths or actions are incorrect");+ unreadableSummary.click();await waitFor(() => document.querySelector("#scan-history")?.textContent.includes("comparison unavailable"), "Partial scan claimed a history comparison");check(!document.querySelector('[aria-label^="Delete "]'), "Read-only deletion enabled");button("Package folders").click();@@ -940,6 +953,7 @@readOnly = false;coverageErrors = 0;coverageSkipped = 0;+ unreadableDirectories = undefined;stopOutcome = "acknowledged";selectDevice("phone-one");await waitFor(() => picker().value === "phone-one" && document.querySelector("#btn-connect:enabled"),@@ -949,6 +963,7 @@check(activeDevice === "phone-one" && scope().generation !== previousGeneration && document.querySelector("#connected-device").textContent.includes("phone-one"), "Device switch reused old results/identity");await waitFor(() => document.querySelector("#scan-history")?.textContent.includes("No previous comparable scan"), "Cross-device comparison reused another device's baseline");check(!button("NUKE IT"), "Device switch retained a destructive confirmation");+ check(!document.querySelector('[aria-label="Unreadable folder paths"]'), "Device switch retained prior scan diagnostics");const deleteCallsBeforeSwitch = calls.filter(call => call.command === "delete_item").length;document.querySelector('[aria-label="Delete file-0 "]').click();await waitFor(() => button("NUKE IT"), "Cross-device confirmation fixture did not open");diff --git a/tests/scan_view.test.mjs b/tests/scan_view.test.mjsindex 10f6ed2..c0e4f1f 100644--- a/tests/scan_view.test.mjs+++ b/tests/scan_view.test.mjs@@ -158,6 +158,28 @@ test("scan and deletion summaries validate before becoming the active snapshot",assert.throws(() => parseDeleteResult({ ...deletion, summary: {} }));});+test("unreadable folder paths and omitted counts stay within the scan scope", () => {+ const paths = Array.from({ length: 8 }, (_, index) => `/scan/parent/ folder ${index} `);+ const summary = {+ ...scope, status: "ok", root_path: "/scan", read_only: true,+ total_size: 0, total_files: 0, total_dirs: 10, errors: 11, skipped: 1, scan_time_ms: 0,+ root: { id: 0, parent_id: null, name: "scan", type: "directory", size: 0,+ counted: true, child_count: 9, can_delete: false },+ unreadable_directories: { paths, omitted: 2 },+ };+ assert.deepEqual(parseScanSummary(summary), summary);+ for (const sample of [+ { paths, omitted: 4 }, { paths: [...paths, "/scan"], omitted: 0 },+ { paths: ["/scan"], omitted: 1 }, { paths: ["/scan", "/scan"], omitted: 0 },+ { paths: ["/scan/../outside"], omitted: 0 }, { paths: ["/scan-neighbor"], omitted: 0 },+ { paths: ["/scan/\0"], omitted: 0 }, { paths: ["/scan/a//b"], omitted: 0 },+ ]) {+ assert.throws(() => parseScanSummary({ ...summary, unreadable_directories: sample }), /Invalid scan summary/);+ }+ assert.deepEqual(parseScanSummary({ ...summary, unreadable_directories: { paths: ["/scan"], omitted: 0 } })+ .unreadable_directories, { paths: ["/scan"], omitted: 0 });+});+test("folder views reject malformed children, cursor anchors and chart data", () => {const node = { id: 0, parent_id: null, name: "/", type: "directory", size: 1,counted: true, child_count: 1, can_delete: false };diff --git a/tests/test_root_scan.py b/tests/test_root_scan.pyindex 1b0b214..761e128 100644--- a/tests/test_root_scan.py+++ b/tests/test_root_scan.py@@ -99,13 +99,14 @@ class RootScanSandboxTests(unittest.TestCase):(self.root / "alias").symlink_to("/", target_is_directory=True)os.link(self.root / "data" / "private", self.root / "data" / "hard-link")for path in ["/alias/.", "/./", "/"]:- done, entries, _ = self.collect(path)+ done, entries, _ = self.collect(path, diagnostics=True)self.assertEqual(done["type"], "done")self.assertEqual(entries[0]["path"], "/")self.assertEqual(done["scan_threads"], 1)self.assertEqual(done["total_files"], 2)self.assertEqual(done["total_size"], len(b"private app data") + len(b"system files"))self.assertEqual(done["skipped"], 8)+ self.assertEqual(done["unreadable_directories"], dict(ids=[], omitted=0))self.assertTrue(all(not entry["path"].startswith("//") for entry in entries.values()))self.assertFalse(any(entry["name"] in {"proc", "mnt", "storage", "dev", "sys", "data_mirror", "apex"} for entry in entries.values()))result = self.request("DELETE /data/private")diff --git a/tests/test_stream_scan.py b/tests/test_stream_scan.pyindex cd79724..3c54889 100644--- a/tests/test_stream_scan.py+++ b/tests/test_stream_scan.py@@ -25,13 +25,14 @@ def frame(client):return dict(type=value["type"], **value["data"]), size + 4class StreamScanTests(DaemonHarness):- def connect_scan(self, root=None):+ def connect_scan(self, root=None, *, diagnostics=False):client = socket.create_connection(('127.0.0.1', self.port), timeout=3)- client.sendall(f'AUTH {self.token}\nSCAN_STREAM {root or self.root}\n'.encode())+ command = 'SCAN_DETAIL' if diagnostics else 'SCAN_STREAM'+ client.sendall(f'AUTH {self.token}\n{command} {root or self.root}\n'.encode())return client- def collect(self, root=None):- with self.connect_scan(root) as client:+ def collect(self, root=None, *, diagnostics=False):+ with self.connect_scan(root, diagnostics=diagnostics) as client:started, byte_count = frame(client)if started['type'] == 'error':return started, {}, []@@ -202,6 +203,53 @@ class StreamScanTests(DaemonHarness):result, _, _ = self.collect('relative-root')self.assertEqual(result['type'], 'error')+ def test_directory_diagnostics_distinguish_unreadable_from_empty_and_bound_the_sample(self):+ if os.geteuid() == 0:+ self.skipTest('Directory permissions require an unprivileged daemon')+ (self.root / 'empty').mkdir()+ blocked = [self.root / f'blocked {i}' for i in range(11)]++ def block(path):+ path.mkdir()+ (path / 'hidden.txt').write_bytes(b'hidden')+ self.addCleanup(path.chmod, 0o700)+ path.chmod(0)++ self.assertIs(self.request('PING')['scan_directory_errors'], True)+ block(blocked[0])+ done, entries, _ = self.collect(diagnostics=True)+ self.assertEqual(done['errors'], 1)+ self.assertEqual(done['skipped'], 0)+ self.assertEqual(done['total_files'], 0)+ self.assertEqual(done['total_dirs'], 3)+ sample = done['unreadable_directories']+ self.assertEqual(sample['omitted'], 0)+ self.assertEqual([entries[id]['name'] for id in sample['ids']], [blocked[0].name])++ for path in blocked[1:]:+ block(path)+ done, entries, _ = self.collect(diagnostics=True)+ self.assertEqual(done['errors'], len(blocked))+ self.assertEqual(done['total_dirs'], len(blocked) + 2)+ self.assertEqual(done['total_size'], 0)+ sample = done['unreadable_directories']+ names = {entries[id]['name'] for id in sample['ids']}+ self.assertEqual(len(sample['ids']), 8)+ self.assertEqual(len(names), 8)+ self.assertLessEqual(names, {path.name for path in blocked})+ self.assertEqual(sample['omitted'], 3)++ legacy, _, _ = self.collect()+ self.assertNotIn('unreadable_directories', legacy)+ self.assertEqual(legacy['errors'], done['errors'])++ for path in blocked:+ path.chmod(0o700)+ recovered, _, _ = self.collect(diagnostics=True)+ self.assertEqual(recovered['unreadable_directories'], dict(ids=[], omitted=0))+ self.assertEqual(recovered['errors'], 0)+ self.assertEqual(recovered['total_files'], len(blocked))+def test_depth_limit_preserves_counts_and_reports_error(self):directory = self.rootfor level in range(67):@@ -209,10 +257,11 @@ class StreamScanTests(DaemonHarness):directory = directory / 'next'directory.mkdir()legacy = self.scan()- done, _, _ = self.collect()+ done, _, _ = self.collect(diagnostics=True)for key in ['total_files', 'total_dirs', 'total_size', 'errors', 'skipped']:self.assertEqual(done[key], legacy[key], key)self.assertEqual(done['errors'], 1)+ self.assertEqual(done['unreadable_directories'], dict(ids=[], omitted=0))def test_extra_command_bytes_abort_the_stream(self):with socket.create_connection(('127.0.0.1', self.port), timeout=3) as client: