Skip to content

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

Rust

Add reconciled file-type breakdown from the scan catalog (#87)

Vishnu Srivatsava3dd4a5686592
diff --git a/README.md b/README.md
index d5b5ac2..396c395 100644
--- a/README.md
+++ b/README.md
@@ -99,6 +99,9 @@ Go to **Settings → About Phone → tap "Build Number" 7 times** to unlock Deve
That's it. No apps to install on your phone, no Wi-Fi setup, no root required.
+In development builds, **File types** shows counts and bytes by filename extension
+from the completed scan. See [classification rules and coverage](docs/file-types.md).
+
In a source build, choose the device in setup before connecting when multiple
devices are ready. Refresh after plugging in or authorizing a phone. A selected
device that disappears stays selected and blocks connection; another phone is
diff --git a/docs/file-types.md b/docs/file-types.md
new file mode 100644
index 0000000..e38ff45
--- /dev/null
+++ b/docs/file-types.md
@@ -0,0 +1,88 @@
+# File types from a completed scan
+
+Choose **File types** in the results to see file counts, bytes and percentage of
+scanned file bytes across the entire scan root. Switching from a zoomed storage
+map still summarizes the whole scan. The view queries the existing host catalog;
+it does not rescan the phone, read file contents or issue ADB commands.
+
+Classification uses the final filename suffix, compared case-insensitively for
+ASCII letters. Names are not trimmed or normalized. A name without a suffix,
+a single leading-dot name such as `.nomedia`, or a trailing-dot name such as
+`backup.` belongs to **No extension**. `.config.JPG` belongs to Images;
+`backup.tar.gz` belongs to Archives; `photo.jpg.exe` and `photo.jpg ` belong to
+Other extensions. This is a filename heuristic, not content or MIME detection.
+
+| Category | Recognized extensions |
+| --- | --- |
+| Images | jpg jpeg png gif webp heic heif avif bmp tif tiff svg ico dng |
+| Videos | mp4 m4v mkv webm avi mov 3gp 3g2 mpeg mpg wmv flv |
+| Audio | mp3 m4a aac flac ogg opus wav wma amr mid midi aiff ape oga |
+| Documents | pdf txt md rtf doc docx odt xls xlsx ods csv ppt pptx odp epub mobi |
+| Archives | zip 7z rar tar gz bz2 xz zst tgz tbz tbz2 txz |
+| Android packages | apk apks xapk aab |
+| No extension | No nonempty suffix with a nonempty stem |
+| Other extensions | All remaining suffixes, including ambiguous `ts` |
+
+Only live, counted regular files contribute, using the same bytes and counting
+rules as the scan. Zero-byte files contribute to file counts. Directories,
+special entries and uncounted placeholders or duplicate hard links do not.
+Both category sums must equal the scan's file count and bytes; a mismatch fails
+instead of displaying a partial breakdown. Empty scans retain eight zero rows.
+Percentages use total scanned file bytes; displayed rounding may not sum to
+100%, and a zero-byte scan shows 0%.
+
+The scan root, access-error count and excluded/duplicate-entry count remain
+visible. This describes scanned data, not the phone's complete physical storage
+or Android app ownership. Root scans retain the existing read-only banner.
+There are no deletion controls in this view. External device changes require a
+rescan, as with the other snapshot views.
+
+## Ownership and bounds
+
+`Catalog::file_types_json` checks generation/revision before traversing the live
+children index. The shared traversal also serves Largest files. Removing a
+directory excludes its entire subtree; successful deletions update the revision
+and totals through the existing deletion flow. Failed or partial deletions still
+invalidate the snapshot through that flow.
+
+Each query takes O(N) time with O(depth + 8) traversal/aggregation state and a
+temporary suffix string bounded by the current filename. There is no additional
+persistent index or full-tree copy. Exactly eight category records cross IPC;
+filenames and paths are not returned. The existing response-size cap applies.
+The command uses the existing scan-store lock, so it observes one coherent
+revision. Switching away and returning runs another host query.
+
+The frontend validates safe integer counts, all eight unique known categories,
+matching scan identity, both sums and the expected scan totals. It hides stale
+values immediately and ignores late results after rescan, revision change or
+unmount. Query errors offer Retry.
+
+The feature adapts the file-type breakdown idea tracked in #34 from
+[Shanmukh's fork](https://github.com/ksaishanmukh/SocketSweep/tree/d677b530e00dec75c305fc56318720aa8c161692)
+(commits `670736d`, `0aca98a`) to the existing host catalog. It adds no dependency
+or device daemon change.
+
+## Validation
+
+Rust fixtures cover all categories, filename boundaries, unknown extensions,
+zero bytes, read-only counting, excluded placeholders, empty scans, deleted
+subtrees, stale scopes and reconciliation failure. A 20,000-distinct-extension
+fixture still returns eight categories in less than 1 KiB.
+
+A host-only release experiment reused the synthetic stream and 31-query,
+three-process method from `tests/benchmark_largest_files.py`, substituting
+`Catalog::file_types_json` for the ranking query. With 250,000 files in 32
+folders, every response contained eight categories and was 434 bytes. Process
+median query times were 35.6–43.3 ms on this arm64 macOS machine. These are host
+aggregation timings under local load, not Android traversal measurements or a
+scan-speed improvement claim.
+
+Node tests reject malformed, stale, duplicated, unsafe or inconsistent summaries.
+The built UI replay uses mocked IPC in headless Chrome to check eight rows,
+rescan races, errors/retry, malformed results, deletion revisions, coverage,
+read-only context, empty scans, horizontal layout and no implicit device scan.
+These are host-only automated checks, not physical-device validation.
+
+For a manual check, restart `npm run tauri dev`, scan normally and select
+**File types**. Compare its Total with the scan header, then switch views and
+rescan. No Android daemon rebuild is required for this host-side feature.
diff --git a/package.json b/package.json
index 3dd8600..9ea00d2 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,7 @@
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint src tests vite.config.ts eslint.config.js --max-warnings 0",
- "test": "node --test tests/format_bytes.test.mjs tests/scan_view.test.mjs tests/log_history.test.mjs tests/lint_gate.test.mjs tests/devices.test.mjs",
+ "test": "node --test tests/format_bytes.test.mjs tests/scan_view.test.mjs tests/log_history.test.mjs tests/lint_gate.test.mjs tests/devices.test.mjs tests/file_types.test.mjs",
"preview": "vite preview",
"tauri": "tauri"
},
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 9ab2d7c..e09a4fd 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -538,6 +538,15 @@ fn get_largest_files(generation: String, revision: u32, limit: usize) -> Result<
.largest_json(&generation, revision, limit)
}
+#[tauri::command(async)]
+fn get_file_types(generation: String, revision: 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")?
+ .file_types_json(&generation, revision)
+}
+
#[tauri::command(async)]
fn get_scan_node(generation: String, revision: u32, node_id: u32) -> Result<String, String> {
let store = SCAN_STORE.lock().map_err(|_| "Scan state is unavailable")?;
@@ -582,6 +591,7 @@ pub fn run() {
get_scan_view,
get_scan_node,
get_largest_files,
+ get_file_types,
])
.build(tauri::generate_context!())
.expect("error while building tauri application")
diff --git a/src-tauri/src/scan_store.rs b/src-tauri/src/scan_store.rs
index af630cc..9cab5c2 100644
--- a/src-tauri/src/scan_store.rs
+++ b/src-tauri/src/scan_store.rs
@@ -15,6 +15,56 @@ const CHART_SIZE: usize = 64;
const MAX_QUERY_BYTES: usize = 1024 * 1024;
type Key = (Reverse<u64>, Arc<str>, u32);
+#[derive(Clone, Copy, Serialize)]
+#[serde(rename_all = "snake_case")]
+enum FileType {
+ Images,
+ Videos,
+ Audio,
+ Documents,
+ Archives,
+ AndroidPackages,
+ NoExtension,
+ Other,
+}
+impl FileType {
+ const ALL: [Self; 8] = [
+ Self::Images,
+ Self::Videos,
+ Self::Audio,
+ Self::Documents,
+ Self::Archives,
+ Self::AndroidPackages,
+ Self::NoExtension,
+ Self::Other,
+ ];
+
+ // Filename metadata only: preserve whitespace, inspect the final suffix,
+ // and treat a single leading dot or trailing dot as no extension.
+ fn of(name: &str) -> Self {
+ let Some((stem, suffix)) = name.rsplit_once('.') else {
+ return Self::NoExtension;
+ };
+ if stem.is_empty() || suffix.is_empty() {
+ return Self::NoExtension;
+ }
+ match suffix.to_ascii_lowercase().as_str() {
+ "jpg" | "jpeg" | "png" | "gif" | "webp" | "heic" | "heif" | "avif" | "bmp" | "tif"
+ | "tiff" | "svg" | "ico" | "dng" => Self::Images,
+ "mp4" | "m4v" | "mkv" | "webm" | "avi" | "mov" | "3gp" | "3g2" | "mpeg" | "mpg"
+ | "wmv" | "flv" => Self::Videos,
+ "mp3" | "m4a" | "aac" | "flac" | "ogg" | "opus" | "wav" | "wma" | "amr" | "mid"
+ | "midi" | "aiff" | "ape" | "oga" => Self::Audio,
+ "pdf" | "txt" | "md" | "rtf" | "doc" | "docx" | "odt" | "xls" | "xlsx" | "ods"
+ | "csv" | "ppt" | "pptx" | "odp" | "epub" | "mobi" => Self::Documents,
+ "zip" | "7z" | "rar" | "tar" | "gz" | "bz2" | "xz" | "zst" | "tgz" | "tbz" | "tbz2"
+ | "txz" => Self::Archives,
+ "apk" | "apks" | "xapk" | "aab" => Self::AndroidPackages,
+ _ => Self::Other,
+ }
+ }
+}
+
pub struct Catalog {
generation: String,
revision: u32,
@@ -328,23 +378,13 @@ impl Catalog {
));
}
let mut best = BinaryHeap::<Key>::with_capacity(limit);
- let mut pending = vec![self.children[0].iter()];
- while let Some(children) = pending.last_mut() {
- if let Some(key) = children.next() {
- let node = &self.response.nodes[key.2 as usize];
- if node.kind == Kind::Directory {
- pending.push(self.children[key.2 as usize].iter());
- } else if node.kind == Kind::File && node.counted {
- if best.len() < limit {
- best.push(key.clone());
- } else if key < best.peek().unwrap() {
- *best.peek_mut().unwrap() = key.clone();
- }
- }
- } else {
- pending.pop();
+ self.visit_files(|key, _| {
+ if best.len() < limit {
+ best.push(key.clone());
+ } else if key < best.peek().unwrap() {
+ *best.peek_mut().unwrap() = key.clone();
}
- }
+ });
#[derive(Serialize)]
struct File<'a> {
node: NodeSummary<'a>,
@@ -375,6 +415,64 @@ impl Catalog {
})
.map_err(|error| format!("{error}. Try a smaller file limit."))
}
+ // Traverse the live index, so removed directories' descendants are absent.
+ // Both analyses use O(depth) traversal state rather than copying the tree.
+ fn visit_files(&self, mut visit: impl FnMut(&Key, &Node)) {
+ let mut pending = vec![self.children[0].iter()];
+ while let Some(children) = pending.last_mut() {
+ if let Some(key) = children.next() {
+ let node = &self.response.nodes[key.2 as usize];
+ if node.kind == Kind::Directory {
+ pending.push(self.children[key.2 as usize].iter());
+ } else if node.kind == Kind::File && node.counted {
+ visit(key, node);
+ }
+ } else {
+ pending.pop();
+ }
+ }
+ }
+
+ pub fn file_types_json(&self, generation: &str, revision: u32) -> Result<String, String> {
+ self.scope(generation, revision)?;
+ #[derive(Serialize)]
+ struct Category {
+ kind: FileType,
+ files: u64,
+ size: u64,
+ }
+ let mut categories = FileType::ALL.map(|kind| Category {
+ kind,
+ files: 0,
+ size: 0,
+ });
+ self.visit_files(|_, node| {
+ let category = &mut categories[FileType::of(&node.name) as usize];
+ category.files += 1;
+ category.size += node.size;
+ });
+ if categories.iter().map(|c| c.files).sum::<u64>() != self.response.total_files
+ || categories.iter().map(|c| c.size).sum::<u64>() != self.response.total_size
+ {
+ return Err("File-type totals do not match this scan; rescan required".into());
+ }
+ #[derive(Serialize)]
+ struct Breakdown<'a> {
+ generation: &'a str,
+ revision: u32,
+ total_files: u64,
+ total_size: u64,
+ categories: [Category; 8],
+ }
+ json(&Breakdown {
+ generation: &self.generation,
+ revision: self.revision,
+ total_files: self.response.total_files,
+ total_size: self.response.total_size,
+ categories,
+ })
+ }
+
pub fn detail_json(&self, generation: &str, revision: u32, id: u32) -> Result<String, String> {
self.scope(generation, revision)?;
self.node(id)?;
@@ -584,6 +682,149 @@ mod tests {
Ok(r#"{"status":"ok","message":"Deleted fixture entry"}"#.into())
}
+ #[test]
+ fn file_type_rules_preserve_filename_boundaries() {
+ for (name, expected) in [
+ ("photo.JPG", "images"),
+ ("影像.heIC", "images"),
+ ("movie.MP4", "videos"),
+ ("song.FLAC", "audio"),
+ ("report.PdF", "documents"),
+ ("backup.tar.gz", "archives"),
+ ("app.XAPK", "android_packages"),
+ ("README", "no_extension"),
+ (".nomedia", "no_extension"),
+ (".apk", "no_extension"),
+ ("trailing.", "no_extension"),
+ (".config.JPG", "images"),
+ ("photo.jpg ", "other"),
+ ("name.İMG", "other"),
+ ("script.ts", "other"),
+ ("image.jpg.exe", "other"),
+ ] {
+ assert_eq!(
+ serde_json::to_value(FileType::of(name)).unwrap(),
+ expected,
+ "{name}"
+ );
+ }
+ }
+
+ #[test]
+ fn file_types_reconcile_counting_modes_zero_bytes_and_placeholders() {
+ let entries = vec![
+ root(),
+ entry(1, Some(0), "folder.pdf", "directory", 0, true),
+ entry(2, Some(1), "photo.JPG", "file", 5, true),
+ entry(3, Some(1), "song.FLAC", "file", 0, true),
+ entry(4, Some(0), ".nomedia", "file", 7, true),
+ entry(5, Some(0), "unknown.abc", "file", 0, true),
+ entry(6, Some(0), "uncounted.jpg", "file", 0, false),
+ entry(7, Some(0), "special.zip", "other", 0, false),
+ entry(8, Some(1), "movie.mp4", "file", 1, true),
+ entry(9, Some(1), "notes.pdf", "file", 2, true),
+ entry(10, Some(1), "backup.tar.gz", "file", 3, true),
+ entry(11, Some(1), "app.APK", "file", 4, true),
+ ];
+ for read_only in [false, true] {
+ let store = Catalog::new(fixture(&entries, read_only), "generation-a".into());
+ let result = value(store.file_types_json("generation-a", 0));
+ assert_eq!(result["total_files"], 8);
+ assert_eq!(result["total_size"], 22);
+ let categories = result["categories"].as_array().unwrap();
+ assert_eq!(categories.len(), 8);
+ for (kind, files, size) in [
+ ("images", 1, 5),
+ ("audio", 1, 0),
+ ("videos", 1, 1),
+ ("documents", 1, 2),
+ ("archives", 1, 3),
+ ("android_packages", 1, 4),
+ ("no_extension", 1, 7),
+ ("other", 1, 0),
+ ] {
+ let category = categories.iter().find(|c| c["kind"] == kind).unwrap();
+ assert_eq!(category["files"], files);
+ assert_eq!(category["size"], size);
+ }
+ assert_eq!(
+ categories
+ .iter()
+ .map(|c| c["files"].as_u64().unwrap())
+ .sum::<u64>(),
+ 8
+ );
+ assert_eq!(
+ categories
+ .iter()
+ .map(|c| c["size"].as_u64().unwrap())
+ .sum::<u64>(),
+ 22
+ );
+ assert!(!result.to_string().contains("photo.JPG"));
+ }
+ let empty = Catalog::new(fixture(&[root()], false), "generation-a".into());
+ let result = value(empty.file_types_json("generation-a", 0));
+ assert!(result["categories"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .all(|c| c["files"] == 0 && c["size"] == 0));
+ let mut inconsistent = fixture(&entries, false);
+ inconsistent.total_size += 1;
+ assert!(Catalog::new(inconsistent, "generation-a".into())
+ .file_types_json("generation-a", 0)
+ .is_err());
+ }
+
+ #[test]
+ fn file_types_follow_deleted_subtrees_and_reject_stale_scopes() {
+ let entries = vec![
+ root(),
+ entry(1, Some(0), "folder", "directory", 0, true),
+ entry(2, Some(1), "large.jpg", "file", 99, true),
+ entry(3, Some(0), "small.apk", "file", 1, true),
+ ];
+ let mut store = Some(Catalog::new(
+ fixture(&entries, false),
+ "generation-a".into(),
+ ));
+ assert!(store.as_ref().unwrap().file_types_json("old", 0).is_err());
+ let plan = store
+ .as_ref()
+ .unwrap()
+ .prepare_delete("generation-a", 0, 1)
+ .unwrap();
+ finish_delete(&mut store, &plan, success()).unwrap();
+ let current = store.as_ref().unwrap();
+ assert!(current.file_types_json("generation-a", 0).is_err());
+ let result = value(current.file_types_json("generation-a", 1));
+ assert_eq!(result["total_files"], 1);
+ assert_eq!(result["total_size"], 1);
+ assert_eq!(result["categories"][0]["files"], 0);
+ assert_eq!(result["categories"][5]["files"], 1);
+ let plan = current.prepare_delete("generation-a", 1, 3).unwrap();
+ finish_delete(&mut store, &plan, success()).unwrap();
+ let result = value(store.as_ref().unwrap().file_types_json("generation-a", 2));
+ assert_eq!(result["total_files"], 0);
+ assert_eq!(result["total_size"], 0);
+ }
+
+ #[test]
+ fn file_types_response_is_bounded_independent_of_extension_cardinality() {
+ let mut entries = vec![root()];
+ for id in 1..=20_000 {
+ entries.push(entry(id, Some(0), &format!("file.{id}"), "file", 1, true));
+ }
+ let store = Catalog::new(fixture(&entries, false), "generation-a".into());
+ let output = store.file_types_json("generation-a", 0).unwrap();
+ assert!(output.len() < 1024);
+ let result = value(Ok(output));
+ assert_eq!(result["categories"].as_array().unwrap().len(), 8);
+ assert_eq!(result["categories"][7]["files"], 20_000);
+ assert_eq!(result["categories"][7]["size"], 20_000);
+ }
+
#[test]
fn largest_matches_exhaustive_sort_for_every_limit() {
let mut entries = wide(1037);
@@ -1151,10 +1392,14 @@ mod tests {
#[test]
fn stop_releases_local_authority_on_success_and_unconfirmed_failures() {
let _operation = crate::DAEMON_OPERATION.lock().unwrap();
- for outcome in [Ok(r#"{"status":"ok","message":"shutting down"}"#.into()),
- Err("Phone disconnected".into()), Err("Bundled ADB unavailable".into())] {
+ for outcome in [
+ Ok(r#"{"status":"ok","message":"shutting down"}"#.into()),
+ Err("Phone disconnected".into()),
+ Err("Bundled ADB unavailable".into()),
+ ] {
let expected = outcome.clone();
- *crate::SCAN_STORE.lock().unwrap() = Some(Catalog::new(fixture(&wide(2), true), "generation-a".into()));
+ *crate::SCAN_STORE.lock().unwrap() =
+ Some(Catalog::new(fixture(&wide(2), true), "generation-a".into()));
*crate::SESSION.lock().unwrap() = Some(crate::session::Session::test_session());
assert!(crate::active_connection().unwrap().read_only);
assert_eq!(crate::finish_stop(outcome), expected);
diff --git a/src/App.tsx b/src/App.tsx
index dcd3b42..aefd2f6 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -9,6 +9,7 @@ import { useScanView } from "./useScanView";
import { FileTreeNode, QueryError } from "./FileTree";
import { IconNuke } from "./Icons";
import { LargestFiles } from "./LargestFiles";
+import { FileTypes } from "./FileTypes";
import { ToastContainer } from "./ToastContainer";
import type { Toast } from "./ToastContainer";
import { TerminalLog } from "./TerminalLog";
@@ -318,7 +319,7 @@ function ResultScreen({
}) {
const [zoomId, setZoomId] = useState(data.root.id);
const [expanded, setExpanded] = useState(() => new Set([data.root.id]));
- const [mode, setMode] = useState<"map" | "largest">("map");
+ const [mode, setMode] = useState<"map" | "largest" | "types">("map");
const view = useScanView(data, zoomId, mode === "map");
const page = view.page;
const onZoom = (id: number) => {
@@ -414,8 +415,10 @@ function ResultScreen({
className={`px-3 py-2 rounded-lg text-xs ${mode === "map" ? "bg-zinc-700 text-white" : "bg-zinc-900 text-zinc-400"}`}>Storage map</button>
<button aria-pressed={mode === "largest"} disabled={busy} onClick={() => setMode("largest")}
className={`px-3 py-2 rounded-lg text-xs ${mode === "largest" ? "bg-zinc-700 text-white" : "bg-zinc-900 text-zinc-400"}`}>Largest files</button>
+ <button aria-pressed={mode === "types"} disabled={busy} onClick={() => setMode("types")}
+ className={`px-3 py-2 rounded-lg text-xs ${mode === "types" ? "bg-zinc-700 text-white" : "bg-zinc-900 text-zinc-400"}`}>File types</button>
</div>
- {mode === "largest" ? <LargestFiles scope={data} busy={busy} onZoom={onZoom} onNuke={onNuke} /> : <>
+ {mode === "types" ? <FileTypes scope={data} busy={busy} /> : mode === "largest" ? <LargestFiles scope={data} busy={busy} onZoom={onZoom} onNuke={onNuke} /> : <>
{/* Treemap */}
<div className="px-6 mb-4 shrink-0 h-48">
<div className="glass-card rounded-xl p-2 w-full h-full relative group">
diff --git a/src/FileTypes.tsx b/src/FileTypes.tsx
new file mode 100644
index 0000000..6bc24bd
--- /dev/null
+++ b/src/FileTypes.tsx
@@ -0,0 +1,53 @@
+import { useEffect, useState } from "react";
+import { invoke } from "@tauri-apps/api/core";
+import { FILE_TYPES, FILE_TYPE_LABELS, parseFileTypes } from "./fileTypeSummary";
+import type { FileTypesResponse } from "./fileTypeSummary";
+import type { ScanResponse } from "./scanView";
+import { formatBytes } from "./formatBytes";
+
+export function FileTypes({ scope, busy }: { scope: ScanResponse; busy: boolean }) {
+ const { generation, revision, total_files, total_size } = scope;
+ const [retry, setRetry] = useState(0);
+ const key = JSON.stringify([generation, revision, total_files, total_size, retry]);
+ const [state, setState] = useState<{ key: string; data?: FileTypesResponse; error?: string }>({ key: "" });
+ useEffect(() => {
+ let current = true;
+ void invoke<string>("get_file_types", { generation, revision }).then(raw => {
+ const data = parseFileTypes(raw, { generation, revision, total_files, total_size });
+ if (current) setState({ key, data });
+ }).catch(error => {
+ if (current) setState({ key, error: String(error) });
+ });
+ return () => { current = false; };
+ }, [generation, revision, total_files, total_size, key]);
+ const data = state.key === key ? state.data : undefined;
+ const error = state.key === key ? state.error : undefined;
+ return <section aria-label="File types" className="flex-1 min-h-0 overflow-y-auto px-6 pb-4">
+ <p role="status" className="text-xs text-zinc-400 py-3">{data ? `${data.total_files.toLocaleString("en-US")} scanned files · ${formatBytes(data.total_size)}` : error ? "File types unavailable" : "Loading file types…"}</p>
+ <p className="text-xs text-zinc-500 mb-2 break-all">Scan root: <span className="font-mono">{scope.root_path}</span></p>
+ <p className="text-xs text-zinc-500 mb-2">Across all folders in this scan. Grouped by filename extension; file contents are not inspected.</p>
+ <p className="text-xs text-zinc-500 mb-3">Scanned data only: {scope.errors.toLocaleString("en-US")} access errors · {scope.skipped.toLocaleString("en-US")} excluded or duplicate entries.</p>
+ {error && <div role="alert" className="text-xs text-red-400 py-2">{error} <button disabled={busy} onClick={() => setRetry(value => value + 1)} className="underline disabled:opacity-50">Retry</button></div>}
+ {data?.total_files === 0 && <p className="text-sm text-zinc-400 py-3">No counted files in this scan.</p>}
+ <table aria-busy={!data && !error} className="w-full text-xs text-left">
+ <caption className="sr-only">File-type storage breakdown</caption>
+ <thead className="text-zinc-500"><tr><th scope="col" className="py-2">Type</th><th scope="col" className="text-right px-2">Files</th><th scope="col" className="text-right px-2">Size</th><th scope="col" className="text-right pl-2">Share</th></tr></thead>
+ <tbody className="divide-y divide-zinc-800/80">
+ {FILE_TYPES.map((kind, index) => {
+ const category = data?.categories[index];
+ const percent = data && category ? (data.total_size > 0 ? category.size / data.total_size * 100 : 0) : undefined;
+ return <tr key={kind} className="file-type-row" data-kind={kind}>
+ <th scope="row" className="py-3 font-medium text-zinc-200">{FILE_TYPE_LABELS[kind]}</th>
+ <td className="text-right px-2 font-mono text-zinc-400">{category ? category.files.toLocaleString("en-US") : "—"}</td>
+ <td className="text-right px-2 font-mono text-zinc-300">{category ? formatBytes(category.size) : "—"}</td>
+ <td className="pl-2"><div className="flex items-center justify-end gap-2">
+ <div aria-hidden="true" className="hidden sm:block w-16 h-1.5 rounded-full bg-zinc-800 overflow-hidden"><div className="h-full bg-accent-500" style={{ width: `${percent ?? 0}%` }} /></div>
+ <span className="text-right font-mono text-zinc-400 w-12">{percent !== undefined ? `${percent.toFixed(1)}%` : "—"}</span>
+ </div></td>
+ </tr>;
+ })}
+ </tbody>
+ <tfoot className="border-t border-zinc-700 text-zinc-200"><tr><th scope="row" className="py-3 font-medium">Total</th><td className="text-right px-2 font-mono">{data ? data.total_files.toLocaleString("en-US") : "—"}</td><td className="text-right px-2 font-mono">{data ? formatBytes(data.total_size) : "—"}</td><td className="text-right pl-2 font-mono">{data ? (data.total_size > 0 ? "100.0%" : "0.0%") : "—"}</td></tr></tfoot>
+ </table>
+ </section>;
+}
diff --git a/src/fileTypeSummary.ts b/src/fileTypeSummary.ts
new file mode 100644
index 0000000..bae5c5a
--- /dev/null
+++ b/src/fileTypeSummary.ts
@@ -0,0 +1,49 @@
+import { sameScan } from "./scanView";
+import type { ScanScope } from "./scanView";
+
+export const FILE_TYPE_LABELS = {
+ images: "Images",
+ videos: "Videos",
+ audio: "Audio",
+ documents: "Documents",
+ archives: "Archives",
+ android_packages: "Android packages",
+ no_extension: "No extension",
+ other: "Other extensions",
+} as const;
+export type FileType = keyof typeof FILE_TYPE_LABELS;
+export const FILE_TYPES = Object.keys(FILE_TYPE_LABELS) as FileType[];
+export interface FileTypeCount { kind: FileType; files: number; size: number }
+export interface FileTypesResponse extends ScanScope {
+ total_files: number;
+ total_size: number;
+ categories: FileTypeCount[];
+}
+type Expected = ScanScope & { total_files: number; total_size: number };
+const object = (value: unknown): value is Record<string, unknown> => typeof value === "object" && value !== null && !Array.isArray(value);
+const count = (value: unknown): value is number => typeof value === "number" && Number.isSafeInteger(value) && value >= 0;
+
+/** Reject stale, malformed or non-reconciling summaries before showing totals. */
+export function parseFileTypes(raw: string, expected: Expected): FileTypesResponse {
+ const data: unknown = JSON.parse(raw);
+ const invalid = () => new Error("File-type summary does not match this scan");
+ if (!object(data) || typeof data.generation !== "string" || !count(data.revision)
+ || !sameScan({ generation: data.generation, revision: data.revision }, expected)
+ || !count(data.total_files) || !count(data.total_size)
+ || data.total_files !== expected.total_files || data.total_size !== expected.total_size
+ || !Array.isArray(data.categories) || data.categories.length !== FILE_TYPES.length) throw invalid();
+ const categories = new Map<FileType, FileTypeCount>();
+ for (const category of data.categories) {
+ if (!object(category) || typeof category.kind !== "string"
+ || !Object.prototype.hasOwnProperty.call(FILE_TYPE_LABELS, category.kind)
+ || !count(category.files) || !count(category.size) || (category.files === 0 && category.size !== 0)) throw invalid();
+ const kind = category.kind as FileType;
+ if (categories.has(kind)) throw invalid();
+ categories.set(kind, { kind, files: category.files, size: category.size });
+ }
+ const ordered = FILE_TYPES.map(kind => categories.get(kind)!);
+ const files = ordered.reduce((sum, category) => sum + category.files, 0);
+ const size = ordered.reduce((sum, category) => sum + category.size, 0);
+ if (!count(files) || !count(size) || files !== data.total_files || size !== data.total_size) throw invalid();
+ return { generation: data.generation, revision: data.revision, total_files: files, total_size: size, categories: ordered };
+}
diff --git a/tests/file_types.test.mjs b/tests/file_types.test.mjs
new file mode 100644
index 0000000..bed6e16
--- /dev/null
+++ b/tests/file_types.test.mjs
@@ -0,0 +1,79 @@
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+import ts from "typescript";
+
+const transpile = source => ts.transpileModule(source, { compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext } }).outputText;
+const url = source => `data:text/javascript;base64,${Buffer.from(source).toString("base64")}`;
+const scanView = url(transpile(await readFile(new URL("../src/scanView.ts", import.meta.url), "utf8")));
+const source = transpile(await readFile(new URL("../src/fileTypeSummary.ts", import.meta.url), "utf8")).replace('"./scanView"', JSON.stringify(scanView));
+const { FILE_TYPES, parseFileTypes } = await import(url(source));
+const expected = { generation: "scan-a", revision: 2, total_files: 3, total_size: 15 };
+const report = () => ({ ...expected, categories: FILE_TYPES.map(kind => ({ kind,
+ files: kind === "images" ? 1 : kind === "no_extension" ? 2 : 0,
+ size: kind === "images" ? 5 : kind === "no_extension" ? 10 : 0 })) });
+const parse = (data, scope = expected) => parseFileTypes(JSON.stringify(data), scope);
+
+test("valid file-type summaries reconcile and use canonical category order", () => {
+ const input = report();
+ input.categories.reverse();
+ const result = parse(input);
+ assert.deepEqual(result.categories.map(row => row.kind), FILE_TYPES);
+ assert.equal(result.categories.reduce((sum, row) => sum + row.files, 0), 3);
+ assert.equal(result.categories.reduce((sum, row) => sum + row.size, 0), 15);
+});
+
+test("empty scans and counted zero-byte files remain distinct", () => {
+ const empty = { ...expected, total_files: 0, total_size: 0,
+ categories: FILE_TYPES.map(kind => ({ kind, files: 0, size: 0 })) };
+ assert.equal(parse(empty, empty).total_files, 0);
+ empty.categories[0].files = 1;
+ empty.total_files = 1;
+ assert.equal(parse(empty, empty).categories[0].size, 0);
+});
+
+test("stale scopes and summaries from a different counted workload are rejected", () => {
+ for (const changes of [{ generation: "old" }, { revision: 1 }, { total_files: 4 }, { total_size: 16 }]) {
+ assert.throws(() => parse({ ...report(), ...changes }), /does not match/);
+ }
+});
+
+test("missing, duplicate, unknown and oversized category sets are rejected", () => {
+ for (const change of [
+ rows => rows.pop(),
+ rows => rows.push(rows[0]),
+ rows => { rows[1] = { ...rows[0] }; },
+ rows => { rows[0].kind = "unknown"; },
+ rows => { rows[0].kind = "__proto__"; },
+ rows => { rows[0] = null; },
+ ]) {
+ const input = report();
+ change(input.categories);
+ assert.throws(() => parse(input));
+ }
+});
+
+test("invalid counts, byte values and non-reconciling category totals are rejected", () => {
+ for (const field of ["files", "size"]) for (const value of [-1, 0.5, null, "5", Number.MAX_SAFE_INTEGER + 1]) {
+ const input = report();
+ input.categories[0][field] = value;
+ assert.throws(() => parse(input));
+ }
+ for (const change of [
+ input => { input.categories[0].files++; },
+ input => { input.categories[0].size++; },
+ input => { input.categories[0] = { kind: "images", files: 0, size: 5 }; },
+ input => {
+ input.total_size = Number.MAX_SAFE_INTEGER;
+ input.categories[0].size = Number.MAX_SAFE_INTEGER;
+ },
+ ]) {
+ const input = report();
+ change(input);
+ assert.throws(() => parse(input, { ...expected, total_size: input.total_size }));
+ }
+});
+
+test("malformed JSON and non-object payloads fail at the query boundary", () => {
+ for (const raw of ["{", "null", "[]", "5", '"text"']) assert.throws(() => parseFileTypes(raw, expected));
+});
diff --git a/tests/scan_ui_fixture.js b/tests/scan_ui_fixture.js
index ee3068d..4a68364 100644
--- a/tests/scan_ui_fixture.js
+++ b/tests/scan_ui_fixture.js
@@ -11,6 +11,13 @@
let delayedDetail = true;
let delayedLargest = true;
let failLargest = false;
+ let holdTypes = false;
+ let resolveTypes;
+ let failTypes = false;
+ let invalidTypes = false;
+ let emptyScan = false;
+ let coverageErrors = 0;
+ let coverageSkipped = 0;
let failDelete = false;
let stopOutcome = "acknowledged";
const readyDevices = [
@@ -35,15 +42,16 @@
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))];
+ if (emptyScan) { rootChildren = []; folderChildren = []; }
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,
+ ...scope(), status: "ok", root_path: "/fixture", root: { ...node(0, null, "fixture", rootChildren.reduce((sum, item) => sum + item.size, 0), true), child_count: rootChildren.length },
+ total_files: 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,
});
const detail = id => {
const target = id === 0 ? summary().root : [...rootChildren, ...folderChildren].find(item => item.id === id);
@@ -97,6 +105,16 @@
}
check(!unavailable, "Snapshot unavailable");
check(args.generation === scope().generation && args.revision === revision, "Stale mock snapshot");
+ if (command === "get_file_types") {
+ if (failTypes) { failTypes = false; throw "Fixture file-type query failure"; }
+ const stats = summary();
+ const data = { ...scope(), total_files: stats.total_files, total_size: stats.total_size,
+ categories: ["images", "videos", "audio", "documents", "archives", "android_packages", "no_extension", "other"].map(kind => ({ kind, files: kind === "no_extension" ? stats.total_files : 0, size: kind === "no_extension" ? stats.total_size : 0 })) };
+ if (invalidTypes) { invalidTypes = false; data.categories[0].files = 1; }
+ const raw = JSON.stringify(data);
+ if (holdTypes) { holdTypes = false; return new Promise(resolve => { resolveTypes = () => resolve(raw); }); }
+ return raw;
+ }
if (command === "get_largest_files") {
check(Number.isInteger(args.limit) && args.limit > 0 && args.limit <= 100, "Unbounded largest-files query");
if (failLargest) { failLargest = false; throw "Mock largest-files failure"; }
@@ -140,7 +158,7 @@
const report = (passed, error) => {
const output = document.createElement("pre");
output.id = "scan-test-report";
- output.textContent = JSON.stringify({ fixture: "scan-ui", passed, error, ipc_calls: calls.length, checks: passed ? ["offline fonts under CSP", "bounded collapsed discovery diagnostics", "discovery retry recovery", "setup alignment", "result fonts", "file label semantics", "complete paging", "bounded largest files", "late largest response", "largest query retry", "largest ID-only deletion", "largest read-only guards", "largest folder navigation without rescanning", "late zoom", "Other tile", "stale confirmation", "ID-only deletion", "revision refresh", "partial failure", "read-only", "acknowledged shutdown", "unconfirmed shutdown", "reconnect", "stop action ordering", "toast dismissal integration", "bounded diagnostic integration"] : undefined });
+ output.textContent = JSON.stringify({ fixture: "scan-ui", passed, error, ipc_calls: calls.length, checks: passed ? ["offline fonts under CSP", "bounded collapsed discovery diagnostics", "discovery retry recovery", "setup alignment", "result fonts", "file label semantics", "complete paging", "bounded file-type totals", "file-type retry and malformed response", "file-type generation and deletion revision", "file-type coverage and empty scan", "bounded largest files", "late largest response", "largest query retry", "largest ID-only deletion", "largest read-only guards", "largest folder navigation without rescanning", "late zoom", "Other tile", "stale confirmation", "ID-only deletion", "revision refresh", "partial failure", "read-only", "acknowledged shutdown", "unconfirmed shutdown", "reconnect", "stop action ordering", "toast dismissal integration", "bounded diagnostic integration"] : undefined });
document.body.append(output);
void fetch("/report", { method: "POST", body: output.textContent }).then(() => {
if (passed) location.replace("/tests/toast_lifecycle_fixture.html");
@@ -235,6 +253,43 @@
check(document.body.textContent.includes("128 entries on this page of 271"), "Missing full entry count");
check(!rows().find(item => item.textContent.includes("file-0")).querySelector("button:disabled"), "File label became an unavailable control");
const scanCount = calls.filter(item => item.command === "run_scan").length;
+ const typesPanel = () => document.querySelector('section[aria-label="File types"]');
+ const typesReady = () => typesPanel()?.querySelector('table[aria-busy="false"]') && !typesPanel().querySelector('[role="alert"]');
+ const checkTypes = count => {
+ const panel = typesPanel();
+ check(panel.querySelectorAll(".file-type-row").length === 8, "File-type rows are unbounded");
+ check(panel.querySelector('[data-kind="no_extension"]').cells[1].textContent === String(count), "File-type count did not match scan");
+ check(panel.querySelector("tfoot").textContent.includes(String(count)), "File-type total missing");
+ check(document.documentElement.scrollWidth <= innerWidth, "File-type view overflows horizontally");
+ check(!panel.querySelector('button[aria-label^="Delete "]'), "File type became a deletion target");
+ };
+ holdTypes = true;
+ button("File types").click();
+ await waitFor(() => resolveTypes && typesPanel()?.querySelector('table[aria-busy="true"]'), "Pending file-type query missing");
+ const oldTypes = resolveTypes;
+ document.querySelector("#btn-rescan").click();
+ await waitFor(() => rows().length === 129, "Rescan during file-type query failed");
+ button("File types").click();
+ await waitFor(typesReady, "File-type summary missing after rescan");
+ oldTypes();
+ await pause(30);
+ checkTypes(470);
+ check(!typesPanel().querySelector('[role="alert"]'), "Late file-type response crossed generations");
+ const typeScanCount = calls.filter(item => item.command === "run_scan").length;
+ for (const invalid of [false, true]) {
+ button("Storage map").click();
+ await waitFor(() => rows().length === 129, "Map missing before file-type retry");
+ if (invalid) invalidTypes = true; else failTypes = true;
+ button("File types").click();
+ await waitFor(() => typesPanel()?.querySelector('[role="alert"]'), "Invalid file-type summary did not fail");
+ check(!typesPanel().textContent.includes("470 scanned files"), "File-type failure retained old totals");
+ button("Retry").click();
+ await waitFor(typesReady, "File-type retry failed");
+ checkTypes(470);
+ }
+ check(calls.filter(item => item.command === "run_scan").length === typeScanCount, "File-type browsing rescanned the phone");
+ button("Storage map").click();
+ await waitFor(() => rows().length === 129, "Map missing after file types");
const largestRows = () => [...document.querySelectorAll(".largest-file-row")];
button("Largest files").click();
await waitFor(() => document.querySelector("#largest-limit"), "Largest-files controls missing");
@@ -260,7 +315,7 @@
await waitFor(() => largestRows().length === 100, "Maximum largest-files page missing");
button("Show folder").click();
await waitFor(() => rows().length === 129, "Show folder did not restore map");
- check(calls.filter(item => item.command === "run_scan").length === scanCount, "Largest-files browsing rescanned the phone");
+ check(calls.filter(item => item.command === "run_scan").length === scanCount + 1, "Largest-files browsing rescanned the phone");
const firstNames = rows().map(item => item.textContent);
button("Next").click();
await waitFor(() => rows().some(item => item.textContent.includes("file-127")), "Next page missing");
@@ -308,6 +363,11 @@
button("Largest files").click();
await waitFor(() => largestRows().length === 25, "Largest files did not refresh after deletion");
check(!largestRows().some(row => row.textContent.includes("/fixture/ file-0 ")), "Deleted largest file survived revision");
+ button("File types").click();
+ await waitFor(typesReady, "File types did not refresh after deletion");
+ checkTypes(469);
+ button("Largest files").click();
+ await waitFor(() => largestRows().length === 25, "Largest files missing after type refresh");
const nested = largestRows().find(row => row.textContent.includes("/large-folder/"));
if (nested) nested.querySelector("button").click(); else button("Storage map").click();
await waitFor(() => rows().length > 0, "Map missing after largest-files navigation");
@@ -330,6 +390,8 @@
failDelete = false;
readOnly = true;
+ coverageErrors = 2;
+ coverageSkipped = 3;
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");
@@ -337,6 +399,10 @@
button("Largest files").click();
await waitFor(() => largestRows().length === 25, "Read-only largest files missing");
check([...document.querySelectorAll('.largest-file-row button[aria-label^="Delete "]')].every(item => item.disabled), "Read-only largest deletion enabled");
+ button("File types").click();
+ await waitFor(typesReady, "Read-only file types missing");
+ checkTypes(470);
+ check(typesPanel().textContent.includes("2 access errors") && typesPanel().textContent.includes("3 excluded or duplicate entries") && typesPanel().textContent.includes("/fixture"), "File-type coverage context missing");
button("Storage map").click();
await waitFor(() => rows().length === 129, "Read-only map missing");
const previousAcknowledgements = () => (document.body.textContent.match(/Daemon acknowledged shutdown\./g) ?? []).length;
@@ -364,6 +430,8 @@
check(picker().value === "phone-two", "Stop forgot the selected phone");
const previousGeneration = scope().generation;
readOnly = false;
+ coverageErrors = 0;
+ coverageSkipped = 0;
stopOutcome = "acknowledged";
selectDevice("phone-one");
await pause(20);
@@ -386,6 +454,13 @@
check(toast, "No toast for dismissal integration");
toast.click();
await waitFor(() => !toast.isConnected, "App did not remove the dismissed toast");
+ emptyScan = true;
+ document.querySelector("#btn-rescan").click();
+ await waitFor(() => rows().length === 1, "Empty scan missing");
+ button("File types").click();
+ await waitFor(typesReady, "Empty file-type summary missing");
+ checkTypes(0);
+ check(typesPanel().textContent.includes("No counted files") && !typesPanel().textContent.includes("NaN") && !typesPanel().textContent.includes("Infinity"), "Empty file-type view is misleading");
check(violations.length === 0, `CSP blocked resources: ${violations.join(", ")}`);
const fonts = performance.getEntriesByType("resource").filter(entry => entry.name.includes(".woff2"));
check(fonts.length === 13 && fonts.every(entry => new URL(entry.name).origin === location.origin), "Fonts are missing or fetched off-site");