A high-performance Android storage analyzer that bypasses MTP using a native C++ daemon, a Rust TCP bridge, and a React Treemap UI.
Rust
Browse counted files from storage type totals (#216)
Vishnu Srivatsava96bd4e42b1ce
diff --git a/docs/file-types.md b/docs/file-types.mdindex e38ff45..97dcacb 100644--- a/docs/file-types.md+++ b/docs/file-types.md@@ -34,8 +34,10 @@ Percentages use total scanned file bytes; displayed rounding may not sum toThe scan root, access-error count and excluded/duplicate-entry count remainvisible. This describes scanned data, not the phone's complete physical storageor 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.+Select a category to browse its counted files across the scan. The list uses+the same extension rules as the totals and the same navigation and confirmation+controls as Search. **Clear filter** returns to the breakdown. Root scans keep+deletion disabled. External device changes require a rescan.## Ownership and bounds@@ -52,6 +54,12 @@ filenames and paths are not returned. The existing response-size cap applies.The command uses the existing scan-store lock, so it observes one coherentrevision. Switching away and returning runs another host query.+Category results use the Search pager. The host filters live, counted files+before applying the offset and stops at 100 rows or the existing 1 MiB IPC+limit. Continue by the actual number of rows returned, including short pages.+The frontend checks the echoed category and scan revision. Changing categories+or deleting a file starts at the first page.+The frontend validates safe integer counts, all eight unique known categories,matching scan identity, both sums and the expected scan totals. It hides stalevalues immediately and ignores late results after rescan, revision change ordiff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rsindex f76a8d4..197eac8 100644--- a/src-tauri/src/lib.rs+++ b/src-tauri/src/lib.rs@@ -611,12 +611,17 @@ fn get_search_results(query: String,skip: u32,folder_id: Option<u32>,+ file_type: Option<scan_store::FileType>,) -> Result<String, String> {let store = SCAN_STORE.lock().map_err(|_| "Scan state is unavailable")?;- store- .as_ref()- .ok_or("Scan is unavailable; rescan required")?- .search_json(&generation, revision, &query, skip, folder_id)+ let catalog = store.as_ref().ok_or("Scan is unavailable; rescan required")?;+ match file_type {+ Some(kind) if query.is_empty() && folder_id.is_none() => {+ catalog.file_type_results_json(&generation, revision, kind, skip)+ }+ Some(_) => Err("File-type results require an entire-scan filter".into()),+ None => catalog.search_json(&generation, revision, &query, skip, folder_id),+ }}#[tauri::command(async)]diff --git a/src-tauri/src/scan_store.rs b/src-tauri/src/scan_store.rsindex 9792084..fb12163 100644--- a/src-tauri/src/scan_store.rs+++ b/src-tauri/src/scan_store.rs@@ -19,9 +19,9 @@ const CHART_SIZE: usize = 64;const MAX_QUERY_BYTES: usize = 1024 * 1024;type Key = (Reverse<u64>, Arc<str>, u32);-#[derive(Clone, Copy, Serialize)]+#[derive(Clone, Copy, Deserialize, PartialEq, Serialize)]#[serde(rename_all = "snake_case")]-enum FileType {+pub(super) enum FileType {Images,Videos,Audio,@@ -69,6 +69,12 @@ impl FileType {}}+#[derive(Clone, Copy)]+enum SearchFilter<'a> {+ Name(&'a str),+ FileType(FileType),+}+// Directory names identify package folders, including leftovers from removed// apps. They are never treated as verified installed-app labels.fn package_folder(path: &str) -> bool {@@ -651,6 +657,26 @@ impl Catalog {"Search text is longer than any stored name ({MAX_SEARCH_QUERY_BYTES} bytes)"));}+ self.entry_results_json(SearchFilter::Name(query), skip, folder_id)+ }++ pub fn file_type_results_json(+ &self,+ generation: &str,+ revision: u32,+ file_type: FileType,+ skip: u32,+ ) -> Result<String, String> {+ self.scope(generation, revision)?;+ self.entry_results_json(SearchFilter::FileType(file_type), skip, None)+ }++ fn entry_results_json(+ &self,+ filter: SearchFilter<'_>,+ skip: u32,+ folder_id: Option<u32>,+ ) -> Result<String, String> {#[derive(Serialize)]struct Entry<'a> {node: NodeSummary<'a>,@@ -661,15 +687,22 @@ impl Catalog {generation: &'a str,revision: u32,query: &'a str,+ #[serde(skip_serializing_if = "Option::is_none")]+ file_type: Option<FileType>,skip: u32,folder_id: Option<u32>,has_more: bool,results: Vec<Entry<'a>>,}+ let (query, file_type) = match filter {+ SearchFilter::Name(query) => (query, None),+ SearchFilter::FileType(kind) => ("", Some(kind)),+ };let mut page = Search {generation: &self.generation,revision: self.revision,query,+ file_type,skip,folder_id,has_more: false,@@ -679,8 +712,14 @@ impl Catalog {// byte longer than `true`, so this also covers a continuation page.let mut remaining = MAX_QUERY_BYTES - json(&page)?.len();let mut omitted = 0_usize;- self.visit_entries_from(folder, |id, node| {- if !name_matches(&node.name, query.as_bytes()) {+ self.visit_entries_from(folder_id.unwrap_or(0), |id, node| {+ let matches = match filter {+ SearchFilter::Name(query) => name_matches(&node.name, query.as_bytes()),+ SearchFilter::FileType(kind) => {+ node.kind == Kind::File && node.counted && FileType::of(&node.name) == kind+ }+ };+ if !matches {return Ok(true);}if omitted < skip as usize {@@ -1158,6 +1197,71 @@ mod tests {assert_eq!(result["total_size"], 0);}+ #[test]+ fn file_type_pages_match_totals_and_restart_after_deletion() {+ let folder_name = "\u{1}".repeat(255);+ let depth = 12;+ let mut entries = vec![root(), entry(1, Some(0), "album.JPG", "directory", 0, true)];+ for id in 2..=depth {+ entries.push(entry(id, Some(id - 1), &folder_name, "directory", 0, true));+ }+ let mut expected = BTreeSet::new();+ for index in 0..=130 {+ let id = entries.len();+ expected.insert(id as u64);+ entries.push(entry(id, Some(depth), &format!("photo-{index}.JPG"), "file", index as u64, true));+ entries.push(entry(id + 1, Some(depth), &format!("photo-{index}.txt"), "file", 1000, true));+ }+ entries.push(entry(entries.len(), Some(depth), "duplicate.jpg", "file", 0, false));+ entries.push(entry(entries.len(), Some(depth), "special.png", "other", 0, false));++ let mut store = Some(Catalog::new(fixture(&entries, false), "generation-a".into()));+ let catalog = store.as_ref().unwrap();+ let category = |catalog: &Catalog, revision| {+ value(catalog.file_types_json("generation-a", revision))["categories"][0].clone()+ };+ let totals = category(catalog, 0);+ let (mut skip, mut bytes) = (0, 0);+ let mut seen = BTreeSet::new();+ loop {+ let raw = catalog.file_type_results_json("generation-a", 0, FileType::Images, skip).unwrap();+ let page: Value = serde_json::from_str(&raw).unwrap();+ let rows = page["results"].as_array().unwrap();+ assert!(raw.len() <= MAX_QUERY_BYTES && !rows.is_empty() && rows.len() < MAX_SEARCH_RESULTS);+ assert_eq!(page["file_type"], "images");+ assert_eq!(page["skip"], skip);+ for row in rows {+ let node = &row["node"];+ assert!(seen.insert(node["id"].as_u64().unwrap()));+ assert_eq!(node["type"], "file");+ assert_eq!(node["counted"], true);+ bytes += node["size"].as_u64().unwrap();+ }+ skip += rows.len() as u32;+ assert_eq!(page["has_more"], (skip as usize) < expected.len());+ if page["has_more"] == false {+ break;+ }+ }+ assert_eq!(seen, expected);+ assert_eq!(totals["files"], skip);+ assert_eq!(totals["size"], bytes);++ let removed = depth as u32 + 1;+ let plan = catalog.prepare_delete("generation-a", 0, removed).unwrap();+ finish_delete(&mut store, &plan, success()).unwrap();+ let catalog = store.as_ref().unwrap();+ assert!(catalog.file_type_results_json("generation-a", 0, FileType::Images, 0).is_err());+ assert!(catalog.file_type_results_json("older", 1, FileType::Images, 0).is_err());+ let page = value(catalog.file_type_results_json("generation-a", 1, FileType::Images, 0));+ assert_eq!(page["revision"], 1);+ let last = value(catalog.file_type_results_json("generation-a", 1, FileType::Images, skip - 2));+ assert_eq!(last["results"].as_array().unwrap().len(), 1);+ assert_ne!(last["results"][0]["node"]["id"], removed);+ assert_eq!(last["has_more"], false);+ assert_eq!(category(catalog, 1)["files"], skip - 1);+ }+#[test]fn file_types_response_is_bounded_independent_of_extension_cardinality() {let mut entries = vec![root()];diff --git a/src/FileTypes.tsx b/src/FileTypes.tsxindex 86530e1..6f2e417 100644--- a/src/FileTypes.tsx+++ b/src/FileTypes.tsx@@ -1,13 +1,22 @@-import { useEffect, useState } from "react";+import { useEffect, useLayoutEffect, useRef, useState } from "react";import { getFileTypes } from "./scanIpc";import { FILE_TYPES, FILE_TYPE_LABELS } from "./fileTypeSummary";-import type { FileTypesResponse } from "./fileTypeSummary";+import type { FileType, FileTypesResponse } from "./fileTypeSummary";import type { ScanResponse } from "./scanView";import { formatBytes } from "./formatBytes";+import { SearchFiles } from "./SearchFiles";-export function FileTypes({ scope, busy }: { scope: ScanResponse; busy: boolean }) {+export function FileTypes({ scope, busy, onZoom, onNuke }: {+ scope: ScanResponse;+ busy: boolean;+ onZoom: (id: number) => void;+ onNuke: (id: number, trigger: HTMLButtonElement) => void;+}) {const { generation, revision, total_files, total_size } = scope;const [retry, setRetry] = useState(0);+ const [category, setCategory] = useState<FileType | null>(null);+ const returnFocus = useRef<FileType | null>(null);+ const summary = useRef<HTMLElement>(null);const key = JSON.stringify([generation, revision, total_files, total_size, retry]);const [state, setState] = useState<{ key: string; data?: FileTypesResponse; error?: string }>({ key: "" });useEffect(() => {@@ -21,7 +30,17 @@ export function FileTypes({ scope, busy }: { scope: ScanResponse; busy: boolean}, [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">+ useLayoutEffect(() => {+ if (category || !returnFocus.current) return;+ const button = summary.current?.querySelector<HTMLButtonElement>(`[data-kind="${returnFocus.current}"] button:enabled`);+ (button ?? summary.current)?.focus();+ returnFocus.current = null;+ }, [category]);+ if (category) {+ return <SearchFiles scope={scope} folder={null} busy={busy} onZoom={onZoom} onNuke={onNuke}+ category={{ kind: category, clear: () => { returnFocus.current = category; setCategory(null); } }} />;+ }+ return <section aria-label="File types" ref={summary} tabIndex={-1} 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>@@ -36,7 +55,13 @@ export function FileTypes({ scope, busy }: { scope: ScanResponse; busy: booleanconst 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>+ <th scope="row" className="py-3 font-medium text-zinc-200">+ <button type="button" aria-label={`Browse ${FILE_TYPE_LABELS[kind]}`} disabled={busy || !category}+ onClick={() => setCategory(kind)}+ className="text-left text-accent-400 hover:underline disabled:text-zinc-400 disabled:no-underline">+ {FILE_TYPE_LABELS[kind]}+ </button>+ </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">diff --git a/src/ResultScreen.tsx b/src/ResultScreen.tsxindex 268d352..70b6bab 100644--- a/src/ResultScreen.tsx+++ b/src/ResultScreen.tsx@@ -163,7 +163,7 @@ export function ResultScreen({</button>)}</div>- {mode === "apps" ? <AppUsage key={data.revision} scope={data} busy={busy} /> : mode === "types" ? <FileTypes scope={data} busy={busy} /> : mode === "largest" ? <LargestFiles scope={data} busy={busy} onZoom={onZoom} onNuke={onNuke} /> : mode === "search" ? <SearchFiles key={searchFolder?.id ?? "all"} scope={data} folder={searchFolder} busy={busy} onZoom={onZoom} onNuke={onNuke} /> : <div className={`flex-1 min-h-0 grid gap-3 px-4 pb-3 ${mapVisible+ {mode === "apps" ? <AppUsage key={data.revision} scope={data} busy={busy} /> : mode === "types" ? <FileTypes scope={data} busy={busy} onZoom={onZoom} onNuke={onNuke} /> : mode === "largest" ? <LargestFiles scope={data} busy={busy} onZoom={onZoom} onNuke={onNuke} /> : mode === "search" ? <SearchFiles key={searchFolder?.id ?? "all"} scope={data} folder={searchFolder} busy={busy} onZoom={onZoom} onNuke={onNuke} /> : <div className={`flex-1 min-h-0 grid gap-3 px-4 pb-3 ${mapVisible? "grid-rows-[7rem_minmax(0,1fr)] md:grid-rows-1 md:grid-cols-[minmax(0,1fr)_minmax(0,2fr)]": "grid-cols-1 grid-rows-1"}`}><div id="storage-map-panel" ref={mapPanel} hidden={!mapVisible} className="min-h-0 min-w-0">diff --git a/src/SearchFiles.tsx b/src/SearchFiles.tsxindex e5486ff..c186a0f 100644--- a/src/SearchFiles.tsx+++ b/src/SearchFiles.tsx@@ -1,12 +1,15 @@import { useEffect, useState } from "react";import { getSearchResults } from "./scanIpc";+import { FILE_TYPE_LABELS } from "./fileTypeSummary";+import type { FileType } from "./fileTypeSummary";import type { SearchFolder, SearchResponse } from "./searchResults";import type { ScanResponse } from "./scanView";import { formatBytes } from "./formatBytes";-export function SearchFiles({ scope, folder, busy, onZoom, onNuke }: {+export function SearchFiles({ scope, folder, category, busy, onZoom, onNuke }: {scope: ScanResponse;folder: SearchFolder | null;+ category?: { kind: FileType; clear: () => void };busy: boolean;onZoom: (id: number) => void;onNuke: (id: number, trigger: HTMLButtonElement) => void;@@ -15,8 +18,9 @@ export function SearchFiles({ scope, folder, busy, onZoom, onNuke }: {const [input, setInput] = useState("");const [query, setQuery] = useState("");const [entireScan, setEntireScan] = useState(false);+ const fileType = category?.kind ?? null;const activeFolder = entireScan ? null : folder;- const pageScope = JSON.stringify([generation, revision, activeFolder?.id]);+ const pageScope = JSON.stringify([generation, revision, activeFolder?.id, fileType]);const [pagination, setPagination] = useState({ scope: pageScope, offsets: [0] });// A revision changes DFS order. Reset synchronously before issuing a request;// keep the submitted query, but never carry offsets into a changed snapshot.@@ -26,15 +30,15 @@ export function SearchFiles({ scope, folder, busy, onZoom, onNuke }: {const key = JSON.stringify([pageScope, root_path, read_only, total_size, query, skip, retry]);const [state, setState] = useState<{ key: string; data?: SearchResponse; error?: string }>({ key: "" });useEffect(() => {- if (!query) return;+ if (!query && !fileType) return;let current = true;- void getSearchResults({ generation, revision, root_path, read_only, total_size }, query, skip, activeFolder).then(data => {+ void getSearchResults({ generation, revision, root_path, read_only, total_size }, query, skip, activeFolder, fileType).then(data => {if (current) setState({ key, data });}).catch(error => {if (current) setState({ key, error: String(error) });});return () => { current = false; };- }, [generation, revision, root_path, read_only, total_size, query, skip, activeFolder, key]);+ }, [generation, revision, root_path, read_only, total_size, query, skip, activeFolder, fileType, key]);// Hide the previous query/revision/page synchronously, before its effect cleans up.const data = state.key === key ? state.data : undefined;const error = state.key === key ? state.error : undefined;@@ -48,15 +52,24 @@ export function SearchFiles({ scope, folder, busy, onZoom, onNuke }: {setEntireScan(value => !value);setPagination({ scope: "", offsets: [0] });};- return <section aria-label="Search" className="flex-1 min-h-0 overflow-y-auto px-6 pb-4">- <form className="flex items-center gap-2 py-3" onSubmit={event => { event.preventDefault(); submit(); }}>+ const range = results.length ? `${skip + 1}–${skip + results.length}` : "0";+ const status = category+ ? data ? `Showing ${range} files` : error ? "Files unavailable" : "Loading files…"+ : data ? `Showing ${range} matches for “${query}”` : error ? "Search unavailable"+ : activeFolder ? "Search names in this folder." : "Search names in the completed scan.";+ return <section aria-label={category ? "Files by type" : "Search"} className="flex-1 min-h-0 overflow-y-auto px-6 pb-4">+ {category ? <div className="flex items-center gap-3 py-3">+ <h2 className="text-sm font-semibold text-zinc-200">{FILE_TYPE_LABELS[category.kind]}</h2>+ <button type="button" autoFocus disabled={busy} onClick={category.clear}+ className="text-xs text-accent-400 hover:underline">Clear filter</button>+ </div> : <form className="flex items-center gap-2 py-3" onSubmit={event => { event.preventDefault(); submit(); }}><input id="search-input" value={input} disabled={busy}onChange={event => setInput(event.target.value)}placeholder={activeFolder ? "Search names in this folder" : "Search names in this scan"}className="flex-1 bg-zinc-900 border border-zinc-700 rounded px-3 py-1.5 text-sm text-zinc-200" /><button type="submit" id="search-submit" disabled={busy || !input}className="px-3 py-1.5 rounded-lg text-xs font-medium bg-zinc-800 text-zinc-300 border border-zinc-700/50 disabled:text-zinc-600">Search</button>- </form>+ </form>}{folder && <div className="flex flex-wrap items-center gap-2 pb-3 text-xs text-zinc-400"><span className="min-w-0 break-all">{activeFolder ? "Folder: " + activeFolder.name : "Entire scan"}</span><button type="button" disabled={busy} onClick={changeScope} className="shrink-0 text-accent-400 hover:underline">@@ -64,9 +77,7 @@ export function SearchFiles({ scope, folder, busy, onZoom, onNuke }: {</button></div>}<div className="flex items-center justify-between gap-3 pb-3">- <p role="status" className="text-xs text-zinc-400">- {data ? `Showing ${results.length ? `${skip + 1}–${skip + results.length}` : "0"} matches for “${query}”` : error ? "Search unavailable" : (activeFolder ? "Search names in this folder." : "Search names in the completed scan.")}- </p>+ <p role="status" className="text-xs text-zinc-400">{status}</p><div className="flex gap-2 shrink-0 text-xs"><button disabled={busy || !data || skip === 0} onClick={() => setPagination({ scope: pageScope, offsets: offsets.slice(0, -1) })}className="text-zinc-300 hover:underline disabled:text-zinc-600">Previous</button>@@ -75,7 +86,9 @@ export function SearchFiles({ scope, folder, busy, onZoom, onNuke }: {</div></div>{error && <div role="alert" className="text-xs text-red-400 py-2">{error} <button onClick={() => setRetry(value => value + 1)} className="underline">Retry</button></div>}- {data && results.length === 0 && <p className="text-sm text-zinc-400 py-4">No matching names in this {activeFolder ? "folder" : "scan"}.</p>}+ {data && results.length === 0 && <p className="text-sm text-zinc-400 py-4">+ {category ? "No files of this type in the scan." : `No matching names in this ${activeFolder ? "folder" : "scan"}.`}+ </p>}<ol className="divide-y divide-zinc-800/80">{results.map(({ node, path }) => <li key={node.id} className="search-result-row flex items-center gap-3 py-3"><div className="flex-1 min-w-0">diff --git a/src/scanIpc.ts b/src/scanIpc.tsindex 1d6a037..d21da12 100644--- a/src/scanIpc.ts+++ b/src/scanIpc.ts@@ -5,6 +5,7 @@ import { parseLargestFiles } from "./largestFilesSummary";import { parseSearchResults } from "./searchResults";import type { SearchFolder } from "./searchResults";import { parseFileTypes } from "./fileTypeSummary";+import type { FileType } from "./fileTypeSummary";import { parseAppUsage } from "./appUsageSummary";import { parseScanComparison } from "./scanComparison";@@ -13,11 +14,14 @@ export async function getLargestFiles(scope: Parameters<typeof parseLargestFilesreturn parseLargestFiles(raw, scope, limit);}-export async function getSearchResults(scope: Parameters<typeof parseSearchResults>[1], query: string, skip: number, folder: SearchFolder | null) {+export async function getSearchResults(+ scope: Parameters<typeof parseSearchResults>[1], query: string, skip: number,+ folder: SearchFolder | null, fileType: FileType | null,+) {const raw = await invoke<string>("get_search_results", {- generation: scope.generation, revision: scope.revision, query, skip, folderId: folder?.id ?? null,+ generation: scope.generation, revision: scope.revision, query, skip, folderId: folder?.id ?? null, fileType,});- return parseSearchResults(raw, scope, query, skip, folder);+ return parseSearchResults(raw, scope, query, skip, folder, fileType);}export async function getFileTypes(scope: Parameters<typeof parseFileTypes>[1]) {diff --git a/src/searchResults.ts b/src/searchResults.tsindex 188828e..0c7d9e2 100644--- a/src/searchResults.ts+++ b/src/searchResults.ts@@ -1,5 +1,6 @@import { sameScan, isRecord, isCount, isU32, parseNodeReference } from "./scanView";import type { ScanScope, ScanResponse, NodeDetail } from "./scanView";+import type { FileType } from "./fileTypeSummary";export const MAX_SEARCH_RESULTS = 100;export type SearchFolder = { id: number; name: string; path: string };@@ -7,12 +8,16 @@ export interface SearchResponse extends ScanScope {query: string;skip: number;folder_id: number | null;+ file_type?: FileType;has_more: boolean;results: Pick<NodeDetail, "node" | "path">[];}type Expected = Pick<ScanResponse, "generation" | "revision" | "root_path" | "read_only" | "total_size">;/** Validate bounded, scoped search rows before rendering action controls. */-export function parseSearchResults(raw: string, expected: Expected, query: string, skip: number, folder: SearchFolder | null = null): SearchResponse {+export function parseSearchResults(+ raw: string, expected: Expected, query: string, skip: number,+ folder: SearchFolder | null = null, fileType: FileType | null = null,+): SearchResponse {const data: unknown = JSON.parse(raw);const folderId = folder?.id ?? null;const invalid = () => new Error("Search response does not match this scan");@@ -20,7 +25,7 @@ export function parseSearchResults(raw: string, expected: Expected, query: strin|| !sameScan({ generation: data.generation, revision: data.revision }, expected)|| typeof data.query !== "string" || data.query !== query|| !isCount(skip) || !isU32(skip) || !isCount(data.skip) || data.skip !== skip- || data.folder_id !== folderId+ || data.folder_id !== folderId || (data.file_type ?? null) !== fileType|| typeof data.has_more !== "boolean"|| !Array.isArray(data.results) || data.results.length > MAX_SEARCH_RESULTS|| (data.results.length === 0 && data.has_more)) throw invalid();@@ -31,10 +36,12 @@ export function parseSearchResults(raw: string, expected: Expected, query: strinconst reference = parseNodeReference(row, expected);const { node, path } = reference;if (node.id === 0 || node.parent_id === null || seen.has(node.id) || paths.has(path)) throw invalid();+ if (fileType && (node.type !== "file" || !node.counted)) throw invalid();if (folder && (node.id <= folder.id || !path.startsWith(folder.path + "/"))) throw invalid();seen.add(node.id);paths.add(path);results.push(reference);}- return { generation: data.generation, revision: data.revision, query, skip, folder_id: folderId, has_more: data.has_more, results };+ return { generation: data.generation, revision: data.revision, query, skip, folder_id: folderId,+ ...(fileType === null ? {} : { file_type: fileType }), has_more: data.has_more, results };}diff --git a/tests/scan_ui_fixture.js b/tests/scan_ui_fixture.jsindex bce39e4..471cc6f 100644--- a/tests/scan_ui_fixture.js+++ b/tests/scan_ui_fixture.js@@ -221,7 +221,9 @@return response;}if (command === "get_search_results") {- check(typeof args.query === "string" && args.query !== "" && args.query.length <= 255, "Unbounded search query");+ const category = args.fileType;+ check(typeof args.query === "string" && args.query.length <= 255+ && (category ? args.query === "" && args.folderId === null : args.query !== ""), "Invalid search filter");check(Number.isInteger(args.skip) && args.skip >= 0, "Invalid search skip");check(args.folderId === null || args.folderId === 1, "Unexpected search folder");if (failSearch) { failSearch = false; throw "Fixture search failure"; }@@ -230,10 +232,13 @@return JSON.stringify({ ...scope(), query: args.query, skip: args.skip, folder_id: args.folderId, has_more: false, results: null });}const candidates = args.folderId === 1 ? folderChildren : [...rootChildren, ...folderChildren];- const matches = candidates.filter(item => item.name.toLowerCase().includes(args.query.toLowerCase()));+ const matches = candidates.filter(item => category+ ? category === "no_extension" && item.type === "file" && item.counted+ : item.name.toLowerCase().includes(args.query.toLowerCase()));// Simulate a page shortened by the backend's serialized-byte budget.- const limit = args.query === "nested" ? 37 : 100;+ const limit = category || args.query === "nested" ? 37 : 100;const response = JSON.stringify({ ...scope(), query: args.query, skip: args.skip, folder_id: args.folderId,+ ...(category && { file_type: category }),has_more: matches.length > args.skip + limit,results: matches.slice(args.skip, args.skip + limit).map(item => detail(item.id)) });if (holdSearch) { holdSearch = false; return new Promise(resolve => { resolveSearch = () => resolve(response); }); }@@ -300,7 +305,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, wide_paging: widePaging, expanded_tree: expandedTree, checks: passed ? ["offline fonts under CSP", "bounded collapsed discovery diagnostics", "discovery retry recovery", "setup alignment", "result fonts", "file label semantics", "usable file workspace", "keyboard storage map visibility", "collapsible diagnostics", "complete paging", "directory paging focus and retries", "expanded-tree row growth and keyboard focus", "first-scan comparison", "unchanged comparison after rescan", "deletion delta comparison", "cross-device comparison isolation", "bounded package-folder paging and coverage", "package query retries and stale replies", "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", "malformed largest response recovery", "largest ID-only deletion", "largest read-only guards", "largest folder navigation without rescanning", "bounded search results", "late search response", "search retry and malformed response", "search ID-only deletion", "read-only search deletion disabled", "late zoom", "Other tile", "stale confirmation", "exact confirmation whitespace", "reachable long-path confirmation", "native modal keyboard focus and cancellation", "ID-only deletion", "revision refresh", "partial failure", "read-only", "acknowledged shutdown", "unconfirmed shutdown", "reconnect", "stop action ordering", "duplicate rescan guard", "rescan failure recovery", "rescan cancellation recovery", "toast dismissal integration", "bounded diagnostic integration"] : undefined });+ output.textContent = JSON.stringify({ fixture: "scan-ui", passed, error, ipc_calls: calls.length, wide_paging: widePaging, expanded_tree: expandedTree, checks: passed ? ["offline fonts under CSP", "bounded collapsed discovery diagnostics", "discovery retry recovery", "setup alignment", "result fonts", "file label semantics", "usable file workspace", "keyboard storage map visibility", "collapsible diagnostics", "complete paging", "directory paging focus and retries", "expanded-tree row growth and keyboard focus", "first-scan comparison", "unchanged comparison after rescan", "deletion delta comparison", "cross-device comparison isolation", "bounded package-folder paging and coverage", "package query retries and stale replies", "bounded file-type totals", "file-type retry and malformed response", "file-type generation and deletion revision", "file-type coverage and empty scan", "file-type drilldown paging, keyboard and revision", "bounded largest files", "late largest response", "largest query retry", "malformed largest response recovery", "largest ID-only deletion", "largest read-only guards", "largest folder navigation without rescanning", "bounded search results", "late search response", "search retry and malformed response", "search ID-only deletion", "read-only search deletion disabled", "late zoom", "Other tile", "stale confirmation", "exact confirmation whitespace", "reachable long-path confirmation", "native modal keyboard focus and cancellation", "ID-only deletion", "revision refresh", "partial failure", "read-only", "acknowledged shutdown", "unconfirmed shutdown", "reconnect", "stop action ordering", "duplicate rescan guard", "rescan failure recovery", "rescan cancellation recovery", "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");@@ -888,6 +893,49 @@button("File types").click();await waitFor(typesReady, "File types did not refresh after deletion");checkTypes(735);+ const filteredPanel = () => document.querySelector('section[aria-label="Files by type"]');+ const typeButton = kind => typesPanel()?.querySelector(`[data-kind="${kind}"] button`);+ const categoryQuery = () => calls.filter(call => call.command === "get_search_results" && call.args.fileType).at(-1).args;+ typeButton("no_extension").focus();+ await pressKey("Enter");+ await waitFor(() => searchRows().length === 37, "File-type drilldown did not open from the keyboard");+ check(filteredPanel().querySelector("h2").textContent === "No extension" && document.activeElement === button("Clear filter"),+ "File-type filter or keyboard focus missing");+ check(categoryQuery().skip === 0 && categoryQuery().fileType === "no_extension" && categoryQuery().folderId === null,+ "File-type drilldown sent the wrong first-page filter");+ holdSearch = true;+ resolveSearch = undefined;+ button("Next").click();+ await waitFor(() => resolveSearch && categoryQuery().skip === 37, "File-type continuation skipped the short first page");+ button("Clear filter").focus();+ await pressKey("Enter");+ await waitFor(typesReady, "Keyboard did not clear the file-type filter");+ check(document.activeElement === typeButton("no_extension"), "Clearing the filter did not restore category focus");+ typeButton("images").click();+ await waitFor(() => filteredPanel()?.textContent.includes("No files of this type"), "Empty category did not render");+ resolveSearch();+ resolveSearch = undefined;+ await pause(30);+ check(searchRows().length === 0 && categoryQuery().fileType === "images" && categoryQuery().skip === 0,+ "A late category page crossed filters");+ button("Clear filter").click();+ await waitFor(typesReady, "File-type summary did not return");+ typeButton("no_extension").click();+ await waitFor(() => searchRows().length === 37 && categoryQuery().skip === 0, "Reopened category retained an old offset");+ button("Next").click();+ await waitFor(() => searchRows()[0]?.textContent.includes(" file-38 ") && categoryQuery().skip === 37, "Second category page lost its first match");+ const revisionBeforeCategoryDelete = revision;+ filteredPanel().querySelector('[aria-label="Delete file-38 "]').click();+ await waitFor(() => button("NUKE IT"), "Category file did not open the existing confirmation");+ button("NUKE IT").click();+ await waitFor(() => searchRows()[0]?.textContent.includes(" file-1 ")+ && categoryQuery().revision === revisionBeforeCategoryDelete + 1 && categoryQuery().skip === 0,+ "Category deletion did not refresh the filter at the new revision");+ check(calls.filter(call => call.command === "delete_item").at(-1).args.nodeId === 40,+ "Category deletion did not use the selected node ID");+ button("Clear filter").click();+ await waitFor(typesReady, "File type totals did not refresh after category deletion");+ checkTypes(734);button("Package folders").click();await waitFor(() => appRows().length === 100, "Package view missing after deletion");check(calls.filter(call => call.command === "get_app_usage").at(-1).args.revision === revision,@@ -952,6 +1000,9 @@await waitFor(typesReady, "Read-only file types missing");checkTypes(736);check(typesPanel().textContent.includes("2 access errors") && typesPanel().textContent.includes("3 excluded or duplicate entries") && typesPanel().textContent.includes("/fixture"), "File-type coverage context missing");+ typeButton("no_extension").click();+ await waitFor(() => searchRows().length === 37, "Read-only category results missing");+ check(searchRows().every(row => row.querySelector('[aria-label^="Delete "]').disabled), "Read-only category deletion enabled");button("Storage map").click();await waitFor(() => rows().length === 129, "Read-only map missing");const previousAcknowledgements = () => (document.body.textContent.match(/Daemon acknowledged shutdown\./g) ?? []).length;diff --git a/tests/search_results.test.mjs b/tests/search_results.test.mjsindex 0f2c846..4ce130c 100644--- a/tests/search_results.test.mjs+++ b/tests/search_results.test.mjs@@ -101,3 +101,15 @@ test("scoped pages must echo the folder and contain only descendants", () => {assert.throws(() => parseScoped({ ...data, folder_id: 2 }));assert.throws(() => parseScoped({ ...data, results: [{ ...entry, path: "/fixture/Logs-old/app.log" }] }));});++test("file-type pages must echo the category and contain only counted files", () => {+ const page = { ...report(), query: "", file_type: "images", has_more: true, results: [row(2, "photo.JPG", 0)] };+ const filtered = data => parseSearchResults(JSON.stringify(data), expected, "", 0, null, "images");+ assert.deepEqual(filtered(page), page);+ for (const changes of [+ { file_type: undefined }, { file_type: "videos" }, { revision: 1 },+ { folder_id: 2 }, { results: [row(2, "album.JPG", 0, "directory")] },+ { results: [row(2, "photo.JPG", 0, "file", false)] },+ ]) assert.throws(() => filtered({ ...page, ...changes }));+ assert.throws(() => parse({ ...report(), file_type: "images" }));+});