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 bounded search over the existing scan with complete pagination (#116)

Vishnu Srivatsava56692be1c5ae
diff --git a/README.md b/README.md
index c9bfb9a..d70725d 100644
--- a/README.md
+++ b/README.md
@@ -102,6 +102,9 @@ 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 development builds, **Search** finds entry names across the completed scan
+with bounded, fully paginated results. See [matching rules and bounds](docs/search.md).
+
Verified scans without access errors are recorded locally when history storage
is available. The results header compares compatible scans of the same device,
folder and access mode; failed or cancelled scans never become baselines. See
diff --git a/docs/search.md b/docs/search.md
new file mode 100644
index 0000000..9687c5c
--- /dev/null
+++ b/docs/search.md
@@ -0,0 +1,74 @@
+# Search from a completed scan
+
+Choose **Search** in the results to look for entry names anywhere in the
+current scan. The query runs against the existing host catalog: it does not
+rescan the phone, read file contents, or issue ADB commands. Switching from a
+zoomed storage map searches the whole scan, not the visible directory.
+
+## Matching rules
+
+- The query matches as a **substring of the entry's exact stored name**.
+ ASCII letters compare case-insensitively (`PHOTO.JPG` matches `photo.jpg`);
+ every other byte, including all non-ASCII UTF-8, compares exactly. Matching
+ bytes must start on a UTF-8 character boundary, so a multi-byte character
+ can never contribute a partial-byte match.
+- Names are never trimmed, normalized, or locale-collated. A query with
+ leading/trailing spaces only matches names that contain those spaces.
+- The stream contract guarantees stored names are valid UTF-8, so displayed
+ names are the raw names. Full paths shown under each result are
+ reconstructed by Rust from validated names, exactly as browsing shows them.
+- An empty query is rejected. A query longer than 255 bytes is rejected:
+ the stream decoder rejects entry names over 255 bytes, so nothing can match.
+
+## What is searched
+
+Every live entry of the current scan except the root: counted and uncounted
+files, directories, and symlink/special placeholders — the same entries
+browsing shows. Deleted subtrees are absent because their keys leave the
+catalog's parent indexes. Directory results offer **Show folder** on the
+directory itself; file results open the parent.
+
+## Pagination and scope
+
+- Pages hold at most 100 results in the live index's deterministic
+ depth-first order (children sorted by size descending, then name, then ID).
+ Pages can be shorter to keep serialized responses within 1 MiB, including
+ JSON escaping. Next advances by the returned row count; Previous returns
+ to the actual preceding page offset.
+ **Previous**/**Next** step whole pages, and `has_more` gates Next; every
+ matching entry stays reachable, with no fixed result cutoff.
+- Requests are scoped to the current scan generation and revision. Deleting
+ anything advances the revision and automatically restarts pagination from
+ the first page while retaining the query. A stale or malformed reply is
+ rejected by the frontend parser and shown through the existing error/retry view.
+- Deletion uses the existing node-ID confirmation flow with the same
+ eligibility rules as browsing: disabled for read-only scans and for names
+ containing line-protocol delimiters.
+
+## Bounds and measurements
+
+The response is bounded by the 1 MiB scan-query limit. The backend measures
+each serialized row and reserves space for the response envelope and commas.
+Traversal stops at the first match that exceeds the row or byte budget;
+that match starts the next page. Each request walks from the root — O(N)
+worst-case matching time and O(depth + page) auxiliary state — with no
+persistent per-query index and no whole-tree copy.
+
+`python3 tests/benchmark_search.py` measures an 86,666-file fixture
+(32 directories) built from the production sources on the host — no app,
+device, or ADB; warm cache; three runs. These baseline timings predate
+byte-budget paging and early traversal termination:
+
+| Query shape | Median response time |
+| --- | ---: |
+| First page of 894 scattered matches, ASCII-folded query | ~2.2 ms |
+| First page of 85,772 common matches | ~0.5 ms |
+| Worst-case deep skip (page 858 of 858) | ~1.3 ms |
+| No match | ~1.3 ms |
+
+Catalog ingestion of the same fixture took 34–51 ms, and the process peak
+RSS including the full catalog was 17.7–19.9 MB. These are host pipeline
+measurements, not Android/USB or Tauri IPC benchmarks; worst-case time grows
+linearly with scan size and skip depth, so a 2,000,000-record scan should still serve
+a deep page in tens of milliseconds, but that projection is not measured
+here.
diff --git a/package.json b/package.json
index 8f95824..c9a547d 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,7 @@
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint src tests vite.config.ts eslint.config.js --max-warnings 0",
- "test": "node --test tests/format_bytes.test.mjs tests/scan_view.test.mjs tests/log_history.test.mjs tests/lint_gate.test.mjs tests/devices.test.mjs tests/file_types.test.mjs tests/scan_history.test.mjs tests/largest_files.test.mjs",
+ "test": "node --test tests/format_bytes.test.mjs tests/scan_view.test.mjs tests/log_history.test.mjs tests/lint_gate.test.mjs tests/devices.test.mjs tests/file_types.test.mjs tests/scan_history.test.mjs tests/largest_files.test.mjs tests/search_results.test.mjs",
"preview": "vite preview",
"tauri": "tauri"
},
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index e464566..18e2c79 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -571,6 +571,20 @@ fn get_file_types(generation: String, revision: u32) -> Result<String, String> {
.file_types_json(&generation, revision)
}
+#[tauri::command(async)]
+fn get_search_results(
+ generation: String,
+ revision: u32,
+ query: String,
+ skip: 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")?
+ .search_json(&generation, revision, &query, skip)
+}
+
#[tauri::command(async)]
fn get_scan_comparison(generation: String, revision: u32) -> Result<String, String> {
let store = SCAN_STORE.lock().map_err(|_| "Scan state is unavailable")?;
@@ -625,6 +639,7 @@ pub fn run() {
get_scan_node,
get_largest_files,
get_file_types,
+ get_search_results,
get_scan_comparison,
])
.build(tauri::generate_context!())
diff --git a/src-tauri/src/scan_store.rs b/src-tauri/src/scan_store.rs
index fbd9754..6895c76 100644
--- a/src-tauri/src/scan_store.rs
+++ b/src-tauri/src/scan_store.rs
@@ -11,6 +11,10 @@ use std::time::Instant;
pub const PAGE_SIZE: usize = 128;
pub const MAX_LARGEST_FILES: usize = 100;
+/// A search needle longer than any stored name cannot match: the stream
+/// decoder rejects entry names over 255 bytes.
+pub const MAX_SEARCH_QUERY_BYTES: usize = 255;
+pub const MAX_SEARCH_RESULTS: usize = 100;
const CHART_SIZE: usize = 64;
const MAX_QUERY_BYTES: usize = 1024 * 1024;
type Key = (Reverse<u64>, Arc<str>, u32);
@@ -136,6 +140,24 @@ pub struct DeletePlan {
pub path: String,
}
+/// ASCII letters compare case-insensitively, matching the file-type
+/// classifier's fold rule; every other byte compares exactly. Candidates must
+/// start on a UTF-8 character boundary so a multi-byte character can never
+/// contribute a partial-byte match. Worst case O(name × needle) byte work.
+fn name_matches(name: &str, needle: &[u8]) -> bool {
+ if needle.is_empty() || needle.len() > name.len() {
+ return false;
+ }
+ let hay = name.as_bytes();
+ (0..=hay.len() - needle.len()).any(|start| {
+ name.is_char_boundary(start)
+ && hay[start..start + needle.len()]
+ .iter()
+ .zip(needle)
+ .all(|(h, n)| (n.is_ascii() && h.eq_ignore_ascii_case(n)) || h == n)
+ })
+}
+
fn json(value: &impl Serialize) -> Result<String, String> {
struct Limited(Vec<u8>);
impl Write for Limited {
@@ -456,6 +478,31 @@ impl Catalog {
}
}
+ // Traverse the live index like visit_files, but report every entry kind
+ // and counted state, so search mirrors exactly what browsing shows.
+ // Returning false stops traversal, including descent into the current node.
+ fn visit_entries(
+ &self,
+ mut visit: impl FnMut(u32, &Node) -> Result<bool, String>,
+ ) -> Result<(), String> {
+ let mut pending = vec![self.children[0].iter()];
+ while let Some(children) = pending.last_mut() {
+ if let Some(key) = children.next() {
+ let id = key.2;
+ let node = &self.response.nodes[id as usize];
+ if !visit(id, node)? {
+ break;
+ }
+ if node.kind == Kind::Directory {
+ pending.push(self.children[id as usize].iter());
+ }
+ } else {
+ pending.pop();
+ }
+ }
+ Ok(())
+ }
+
pub fn file_types_json(&self, generation: &str, revision: u32) -> Result<String, String> {
self.scope(generation, revision)?;
#[derive(Serialize)]
@@ -496,6 +543,87 @@ impl Catalog {
})
}
+ /// Substring search over live entry names with explicit paging; matching,
+ /// ordering and bounds are documented in docs/search.md. Results follow
+ /// the live index's depth-first order, which is deterministic within a
+ /// revision. Traversal stops at the first match beyond the row/byte budget:
+ /// O(N) worst-case matching time and O(depth + page) auxiliary state, with
+ /// no persistent per-query index. Deleted subtrees are absent because
+ /// their keys leave the parent indexes.
+ pub fn search_json(
+ &self,
+ generation: &str,
+ revision: u32,
+ query: &str,
+ skip: u32,
+ ) -> Result<String, String> {
+ self.scope(generation, revision)?;
+ if query.is_empty() {
+ return Err("Enter text to search this scan".into());
+ }
+ if query.len() > MAX_SEARCH_QUERY_BYTES {
+ return Err(format!(
+ "Search text is longer than any stored name ({MAX_SEARCH_QUERY_BYTES} bytes)"
+ ));
+ }
+ #[derive(Serialize)]
+ struct Entry<'a> {
+ node: NodeSummary<'a>,
+ path: String,
+ }
+ #[derive(Serialize)]
+ struct Search<'a> {
+ generation: &'a str,
+ revision: u32,
+ query: &'a str,
+ skip: u32,
+ has_more: bool,
+ results: Vec<Entry<'a>>,
+ }
+ let mut page = Search {
+ generation: &self.generation,
+ revision: self.revision,
+ query,
+ skip,
+ has_more: false,
+ results: Vec::with_capacity(MAX_SEARCH_RESULTS),
+ };
+ // The empty envelope includes brackets and metadata. `false` is one
+ // 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(|id, node| {
+ if !name_matches(&node.name, query.as_bytes()) {
+ return Ok(true);
+ }
+ if omitted < skip as usize {
+ omitted += 1;
+ return Ok(true);
+ }
+ if page.results.len() == MAX_SEARCH_RESULTS {
+ page.has_more = true;
+ return Ok(false);
+ }
+ let entry = Entry {
+ node: self.summary_node(id),
+ path: self.path(id),
+ };
+ // Measure JSON escaping as well as raw path/name bytes and commas.
+ let bytes = json(&entry)?.len() + usize::from(!page.results.is_empty());
+ if bytes > remaining {
+ if page.results.is_empty() {
+ return Err("Search result exceeds response limit".into());
+ }
+ page.has_more = true;
+ return Ok(false);
+ }
+ remaining -= bytes;
+ page.results.push(entry);
+ Ok(true)
+ })?;
+ json(&page)
+ }
+
pub fn detail_json(&self, generation: &str, revision: u32, id: u32) -> Result<String, String> {
self.scope(generation, revision)?;
self.node(id)?;
@@ -1438,4 +1566,185 @@ mod tests {
let store = Catalog::new(fixture(&wide(1000), false), "generation-a".into());
assert!(store.view_json("generation-a", 0, 0, None).unwrap().len() < MAX_QUERY_BYTES);
}
+
+ #[test]
+ fn search_matches_ascii_folded_exact_bytes_and_every_entry_kind() {
+ let entries = vec![
+ root(),
+ entry(1, Some(0), "Photo.JPG", "file", 5, true),
+ entry(2, Some(0), "photo.jpg", "file", 3, true),
+ entry(3, Some(0), "phöt", "file", 1, true),
+ entry(4, Some(0), "Photos", "directory", 0, true),
+ entry(5, Some(4), "link", "other", 0, false),
+ entry(6, Some(0), "a\nb", "file", 0, true),
+ ];
+ let store = Catalog::new(fixture(&entries, false), "generation-a".into());
+ let ids = |raw: Result<String, String>| {
+ json!(value(raw)["results"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|row| row["node"]["id"].clone())
+ .collect::<Vec<_>>())
+ };
+ // ASCII letters fold; non-ASCII bytes compare exactly.
+ assert_eq!(ids(store.search_json("generation-a", 0, "PHOTO.JPG", 0)), json!([1, 2]));
+ assert_eq!(ids(store.search_json("generation-a", 0, "photo", 0)), json!([1, 2, 4]));
+ assert_eq!(ids(store.search_json("generation-a", 0, "PHÖ", 0)), json!([]));
+ assert_eq!(ids(store.search_json("generation-a", 0, "phö", 0)), json!([3]));
+ // Other/uncounted entries and newline names stay searchable; the root
+ // itself never matches.
+ assert_eq!(ids(store.search_json("generation-a", 0, "link", 0)), json!([5]));
+ assert_eq!(ids(store.search_json("generation-a", 0, "\n", 0)), json!([6]));
+ assert_eq!(ids(store.search_json("generation-a", 0, "fixture", 0)), json!([]));
+ for query in ["", "x".repeat(256).as_str()] {
+ assert!(store.search_json("generation-a", 0, query, 0).is_err());
+ }
+ assert!(store.search_json("generation-a", 0, &"x".repeat(255), 0).is_ok());
+ assert!(store.search_json("old", 0, "photo", 0).is_err());
+ assert!(store.search_json("generation-a", 1, "photo", 0).is_err());
+ }
+
+ #[test]
+ fn search_pagination_reaches_every_match_in_deterministic_order() {
+ let store = Catalog::new(fixture(&wide(250), false), "generation-a".into());
+ let page = |skip: u32| value(store.search_json("generation-a", 0, "FILE-", skip));
+ // Every root child is a matched sibling, so pages follow the child
+ // index order: size descending, then name, then ID.
+ let mut seen = Vec::new();
+ let mut skip = 0;
+ loop {
+ let result = page(skip);
+ let results = result["results"].as_array().unwrap();
+ assert!(results.len() <= MAX_SEARCH_RESULTS);
+ assert_eq!(result["query"], "FILE-");
+ assert_eq!(result["skip"], skip);
+ for (left, right) in results.iter().zip(results.iter().skip(1)) {
+ let order = |row: &Value| {
+ (
+ Reverse(row["node"]["size"].as_u64().unwrap()),
+ row["node"]["name"].as_str().unwrap().to_string(),
+ row["node"]["id"].as_u64().unwrap(),
+ )
+ };
+ assert!(order(left) <= order(right));
+ }
+ let ids: Vec<_> = results.iter().map(|row| row["node"]["id"].clone()).collect();
+ assert!(!ids.iter().any(|id| seen.contains(id)));
+ let done = !result["has_more"].as_bool().unwrap();
+ seen.extend(ids);
+ if done {
+ break;
+ }
+ skip += MAX_SEARCH_RESULTS as u32;
+ }
+ assert_eq!(seen.len(), 250);
+ assert_eq!(page(250)["results"], json!([]));
+ assert_eq!(page(250)["has_more"], false);
+ assert_eq!(page(400)["results"], json!([]));
+ assert_eq!(page(0), page(0));
+ }
+
+ #[test]
+ fn search_pages_fit_the_byte_budget_and_reach_every_long_path_match() {
+ for (name, depth) in [
+ ("d".repeat(255), 43),
+ ("\u{1}".repeat(250), 8),
+ ("\u{1}".repeat(255), 63),
+ ] {
+ let mut entries = vec![root()];
+ for id in 1..=depth {
+ entries.push(entry(id, Some(id - 1), &name, "directory", 0, true));
+ }
+ for index in 0..250 {
+ entries.push(entry(
+ depth + index + 1,
+ Some(depth),
+ &format!("needle-{index:03}"),
+ "file",
+ 1,
+ true,
+ ));
+ }
+ let store = Catalog::new(fixture(&entries, false), "generation-a".into());
+ let mut seen = BTreeSet::new();
+ let mut skip = 0;
+ loop {
+ let raw = store.search_json("generation-a", 0, "needle", skip).unwrap();
+ assert!(raw.len() <= MAX_QUERY_BYTES);
+ let page: Value = serde_json::from_str(&raw).unwrap();
+ let rows = page["results"].as_array().unwrap();
+ assert!(!rows.is_empty() && rows.len() < MAX_SEARCH_RESULTS);
+ assert_eq!(page["skip"], skip);
+ for row in rows {
+ assert!(seen.insert(row["node"]["id"].as_u64().unwrap()));
+ }
+ skip += rows.len() as u32;
+ assert_eq!(page["has_more"], skip < 250);
+ if page["has_more"] == false {
+ break;
+ }
+ }
+ assert_eq!(seen.len(), 250);
+ }
+ }
+
+ #[test]
+ fn entry_traversal_stops_at_lookahead_without_descending_further() {
+ let entries = vec![
+ root(),
+ entry(1, Some(0), "folder", "directory", 0, true),
+ entry(2, Some(1), "child", "file", 1, true),
+ entry(3, Some(0), "sibling", "file", 0, true),
+ ];
+ let store = Catalog::new(fixture(&entries, false), "generation-a".into());
+ let mut visited = Vec::new();
+ store
+ .visit_entries(|id, _| {
+ visited.push(id);
+ Ok(false)
+ })
+ .unwrap();
+ assert_eq!(visited, [1]);
+ let store = Catalog::new(fixture(&wide(250), false), "generation-a".into());
+ let mut matches = 0;
+ store
+ .visit_entries(|_, node| {
+ matches += usize::from(name_matches(&node.name, b"file-"));
+ Ok(matches <= MAX_SEARCH_RESULTS)
+ })
+ .unwrap();
+ assert_eq!(matches, MAX_SEARCH_RESULTS + 1);
+ }
+
+ #[test]
+ fn search_excludes_deleted_subtrees_and_requires_current_revision() {
+ let entries = vec![
+ root(),
+ entry(1, Some(0), "Music", "directory", 0, true),
+ entry(2, Some(1), "song.mp3", "file", 4, true),
+ entry(3, Some(0), "readme.txt", "file", 2, true),
+ ];
+ let mut store = Some(Catalog::new(fixture(&entries, false), "generation-a".into()));
+ let results = |store: &Option<Catalog>, revision: u32, query: &str| {
+ json!(value(
+ store.as_ref().unwrap().search_json("generation-a", revision, query, 0)
+ )["results"]
+ .as_array()
+ .unwrap()
+ .iter()
+ .map(|row| row["node"]["id"].clone())
+ .collect::<Vec<_>>())
+ };
+ assert_eq!(results(&store, 0, "song"), json!([2]));
+ let plan = store
+ .as_ref()
+ .unwrap()
+ .prepare_delete("generation-a", 0, 1)
+ .unwrap();
+ finish_delete(&mut store, &plan, success()).unwrap();
+ assert_eq!(results(&store, 1, "song"), json!([]));
+ assert_eq!(results(&store, 1, "readme"), json!([3]));
+ assert!(store.as_ref().unwrap().search_json("generation-a", 0, "song", 0).is_err());
+ }
}
diff --git a/src/ResultScreen.tsx b/src/ResultScreen.tsx
index e78ddc1..e1d663f 100644
--- a/src/ResultScreen.tsx
+++ b/src/ResultScreen.tsx
@@ -6,6 +6,7 @@ import type { ScanResponse } from "./scanView";
import { useScanView } from "./useScanView";
import { FileTreeNode, QueryError } from "./FileTree";
import { LargestFiles } from "./LargestFiles";
+import { SearchFiles } from "./SearchFiles";
import { FileTypes } from "./FileTypes";
import { ScanHistory } from "./ScanHistory";
@@ -75,7 +76,7 @@ export function ResultScreen({
}) {
const [zoomId, setZoomId] = useState(data.root.id);
const [expanded, setExpanded] = useState(() => new Set([data.root.id]));
- const [mode, setMode] = useState<"map" | "largest" | "types">("map");
+ const [mode, setMode] = useState<"map" | "largest" | "types" | "search">("map");
const view = useScanView(data, zoomId, mode === "map");
const page = view.page;
const onZoom = (id: number) => {
@@ -174,8 +175,10 @@ export function ResultScreen({
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>
+ <button aria-pressed={mode === "search"} disabled={busy} onClick={() => setMode("search")}
+ className={`px-3 py-2 rounded-lg text-xs ${mode === "search" ? "bg-zinc-700 text-white" : "bg-zinc-900 text-zinc-400"}`}>Search</button>
</div>
- {mode === "types" ? <FileTypes scope={data} busy={busy} /> : mode === "largest" ? <LargestFiles scope={data} busy={busy} onZoom={onZoom} onNuke={onNuke} /> : <div className="flex-1 min-h-0 grid grid-rows-[7rem_minmax(0,1fr)] md:grid-rows-1 md:grid-cols-[minmax(0,1fr)_minmax(0,2fr)] gap-3 px-4 pb-3">
+ {mode === "types" ? <FileTypes scope={data} busy={busy} /> : mode === "largest" ? <LargestFiles scope={data} busy={busy} onZoom={onZoom} onNuke={onNuke} /> : mode === "search" ? <SearchFiles scope={data} busy={busy} onZoom={onZoom} onNuke={onNuke} /> : <div className="flex-1 min-h-0 grid grid-rows-[7rem_minmax(0,1fr)] md:grid-rows-1 md:grid-cols-[minmax(0,1fr)_minmax(0,2fr)] gap-3 px-4 pb-3">
{/* Treemap */}
<div className="min-h-0 min-w-0">
<div className="glass-card rounded-xl p-2 w-full h-full relative group">
diff --git a/src/SearchFiles.tsx b/src/SearchFiles.tsx
new file mode 100644
index 0000000..65d9dda
--- /dev/null
+++ b/src/SearchFiles.tsx
@@ -0,0 +1,85 @@
+import { useEffect, useState } from "react";
+import { invoke } from "@tauri-apps/api/core";
+import { parseSearchResults } from "./searchResults";
+import type { SearchResponse } from "./searchResults";
+import type { ScanResponse } from "./scanView";
+import { formatBytes } from "./formatBytes";
+
+export function SearchFiles({ scope, busy, onZoom, onNuke }: {
+ scope: ScanResponse;
+ busy: boolean;
+ onZoom: (id: number) => void;
+ onNuke: (id: number) => void;
+}) {
+ const { generation, revision, root_path, read_only, total_size } = scope;
+ const [input, setInput] = useState("");
+ const [query, setQuery] = useState("");
+ const pageScope = JSON.stringify([generation, revision]);
+ 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.
+ const offsets = pagination.scope === pageScope ? pagination.offsets : [0];
+ const skip = offsets[offsets.length - 1];
+ const [retry, setRetry] = useState(0);
+ const key = JSON.stringify([generation, revision, root_path, read_only, total_size, query, skip, retry]);
+ const [state, setState] = useState<{ key: string; data?: SearchResponse; error?: string }>({ key: "" });
+ useEffect(() => {
+ if (!query) return;
+ let current = true;
+ void invoke<string>("get_search_results", { generation, revision, query, skip }).then(raw => {
+ const data = parseSearchResults(raw, { generation, revision, root_path, read_only, total_size }, query, skip);
+ 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, retry, 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;
+ const submit = () => {
+ if (!input) return;
+ setQuery(input);
+ setPagination({ scope: pageScope, offsets: [0] });
+ };
+ const results = data?.results ?? [];
+ 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(); }}>
+ <input id="search-input" value={input} disabled={busy}
+ onChange={event => setInput(event.target.value)}
+ placeholder="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>
+ <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" : "Search names in the completed scan."}
+ </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>
+ <button disabled={busy || !data?.has_more} onClick={() => setPagination({ scope: pageScope, offsets: [...offsets, skip + results.length] })}
+ className="text-zinc-300 hover:underline disabled:text-zinc-600">Next</button>
+ </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 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">
+ <p className="text-sm text-zinc-200 whitespace-pre-wrap break-all">{node.name}</p>
+ <p className="text-xs text-zinc-500 font-mono whitespace-pre-wrap break-all" dir="auto">{path}</p>
+ </div>
+ <span className="text-xs text-zinc-300 font-mono shrink-0">{node.counted ? formatBytes(node.size) : "—"}</span>
+ <div className="flex flex-col gap-2 shrink-0 text-xs">
+ <button disabled={busy || node.parent_id === null}
+ onClick={() => onZoom(node.type === "directory" ? node.id : node.parent_id!)}
+ className="text-accent-400 hover:underline">Show folder</button>
+ <button aria-label={`Delete ${node.name}`} disabled={busy || !node.can_delete} onClick={() => onNuke(node.id)}
+ className="text-red-400 hover:underline disabled:text-zinc-600">Delete</button>
+ </div>
+ </li>)}
+ </ol>
+ </section>;
+}
diff --git a/src/searchResults.ts b/src/searchResults.ts
new file mode 100644
index 0000000..d0536be
--- /dev/null
+++ b/src/searchResults.ts
@@ -0,0 +1,35 @@
+import { sameScan, isRecord, isCount, isU32, parseNodeReference } from "./scanView";
+import type { ScanScope, ScanResponse, NodeDetail } from "./scanView";
+
+export const MAX_SEARCH_RESULTS = 100;
+export interface SearchResponse extends ScanScope {
+ query: string;
+ skip: number;
+ 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): SearchResponse {
+ const data: unknown = JSON.parse(raw);
+ const invalid = () => new Error("Search response does not match this scan");
+ if (!isRecord(data) || typeof data.generation !== "string" || !isU32(data.revision)
+ || !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
+ || typeof data.has_more !== "boolean"
+ || !Array.isArray(data.results) || data.results.length > MAX_SEARCH_RESULTS
+ || (data.results.length === 0 && data.has_more)) throw invalid();
+ const results: SearchResponse["results"] = [];
+ const seen = new Set<number>();
+ const paths = new Set<string>();
+ for (const row of data.results) {
+ const 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();
+ seen.add(node.id);
+ paths.add(path);
+ results.push(reference);
+ }
+ return { generation: data.generation, revision: data.revision, query, skip, has_more: data.has_more, results };
+}
diff --git a/tests/benchmark_search.py b/tests/benchmark_search.py
new file mode 100644
index 0000000..4cc1eb4
--- /dev/null
+++ b/tests/benchmark_search.py
@@ -0,0 +1,142 @@
+#!/usr/bin/env python3
+"""Headless host search benchmark; no app, device, or ADB. Requires Rust.
+
+Builds a large catalog from the production scan_stream/scan_store sources,
+then measures search response times across query shapes, full pagination
+cost, and host peak RSS via /usr/bin/time. Correctness is verified against
+match counts computed independently in this script.
+"""
+import json
+from pathlib import Path
+import shutil
+import struct
+import subprocess
+import sys
+import tempfile
+import tomllib
+
+REPO = Path(__file__).resolve().parents[1]
+if sys.platform not in ("darwin", "linux"):
+ sys.exit("RSS benchmark requires macOS or Linux /usr/bin/time")
+
+FILES = 86_666
+DIRS = 32
+NEEDLE_EVERY = 97
+
+
+def run(*args, **kwargs):
+ try:
+ return subprocess.run(args, check=True, text=True, **kwargs)
+ except subprocess.CalledProcessError as error:
+ if error.stderr:
+ print(error.stderr[-4000:], file=sys.stderr)
+ raise
+
+
+def frame(output, kind, data):
+ payload = json.dumps({"type": kind, "data": data}, ensure_ascii=False, separators=(",", ":")).encode()
+ output.write(struct.pack(">I", len(payload)))
+ output.write(payload)
+
+
+with tempfile.TemporaryDirectory(prefix="socketsweep-search-bench-") as directory:
+ work = Path(directory)
+ source = work / "src"
+ source.mkdir()
+ shutil.copy(REPO / "src-tauri/src/scan_stream.rs", source / "scan_stream.rs")
+ shutil.copy(REPO / "src-tauri/src/scan_store.rs", source / "scan_store.rs")
+ lock = tomllib.loads((REPO / "src-tauri/Cargo.lock").read_text())
+ versions = {package["name"]: package["version"] for package in lock["package"]}
+ (work / "Cargo.toml").write_text(f'''[package]
+name = "socketsweep-search-benchmark"
+version = "0.0.0"
+edition = "2021"
+[dependencies]
+serde = {{ version = "={versions['serde']}", features = ["derive"] }}
+serde_json = {{ version = "={versions['serde_json']}" }}
+[[bin]]
+name = "search-bench"
+path = "src/main.rs"
+''')
+ expected_matches = len(range(0, FILES, NEEDLE_EVERY))
+ (source / "main.rs").write_text(f'''const MAX_COMMAND_BYTES: usize = 16*1024;
+const TCP_READ_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(120);
+mod scan_stream;
+mod scan_store;
+use std::io::{{Read, Write}};
+struct Reader(std::io::BufReader<std::fs::File>);
+impl Read for Reader {{ fn read(&mut self, bytes: &mut [u8]) -> std::io::Result<usize> {{ self.0.read(bytes) }} }}
+impl scan_stream::StreamReader for Reader {{}}
+fn timed(report: &mut serde_json::Map<String, serde_json::Value>, name: &str, query: impl FnOnce() -> String) -> String {{
+ let started = std::time::Instant::now();
+ let payload = query();
+ report.insert(name.to_string(), serde_json::json!({{
+ "ms": started.elapsed().as_secs_f64()*1000.0, "response_bytes": payload.len() }}));
+ payload
+}}
+fn main() {{
+ let args: Vec<_> = std::env::args().collect();
+ let expected_matches: usize = args[2].parse().unwrap();
+ let started = std::time::Instant::now();
+ let mut reader = Reader(std::io::BufReader::new(std::fs::File::open(&args[1]).unwrap()));
+ let response = scan_stream::read(&mut reader, false, |_| Ok(())).unwrap();
+ let mut report = serde_json::Map::new();
+ let store = scan_store::Catalog::new(response, "a".repeat(64));
+ report.insert("ingest_ms".into(), serde_json::json!(started.elapsed().as_secs_f64()*1000.0));
+ let generation = "a".repeat(64);
+ // ASCII-folded query over ~{expected_matches} scattered matches, then every page.
+ timed(&mut report, "fold_first_page", || store.search_json(&generation, 0, "NEEDLE", 0).unwrap());
+ let mut page = 0usize;
+ loop {{
+ let value: serde_json::Value = serde_json::from_str(&store.search_json(&generation, 0, "NEEDLE", page as u32).unwrap()).unwrap();
+ let results = value["results"].as_array().unwrap().len();
+ page += results;
+ if !value["has_more"].as_bool().unwrap() {{ break; }}
+ }}
+ assert_eq!(page, expected_matches, "pagination must reach every match");
+ // Worst-case deep skip over the common matches: the scan restarts each
+ // page, so a page near the end re-checks every earlier entry.
+ timed(&mut report, "common_first_page", || store.search_json(&generation, 0, "file-0", 0).unwrap());
+ let common_matches = 86_666usize - expected_matches;
+ let deep: serde_json::Value = serde_json::from_str(&timed(
+ &mut report, "common_deep_skip",
+ || store.search_json(&generation, 0, "file-0", (common_matches - 100) as u32).unwrap(),
+ )).unwrap();
+ assert_eq!(deep["results"].as_array().unwrap().len(), 100);
+ assert_eq!(deep["has_more"], false);
+ timed(&mut report, "no_match", || store.search_json(&generation, 0, "zzz-no-match", 0).unwrap());
+ std::fs::File::create(&args[3]).unwrap().write_all(serde_json::to_string_pretty(&report).unwrap().as_bytes()).unwrap();
+}}''')
+ stream = work / "fixture.stream"
+ entries = [{"id": 0, "parent": None, "name": "fixture", "kind": "directory", "size": 0, "counted": True}]
+ entries += [{"id": i + 1, "parent": 0, "name": f"folder-{i:02}", "kind": "directory", "size": 0, "counted": True} for i in range(DIRS)]
+ total = 0
+ for i in range(FILES):
+ size = (i * 7919) % 10_000_000
+ total += size
+ name = f"needle-{i:06}.log" if i % NEEDLE_EVERY == 0 else f"file-{i:06}.dat"
+ entries.append({"id": i + DIRS + 1, "parent": i % DIRS + 1, "name": name, "kind": "file", "size": size, "counted": True})
+ with stream.open("wb") as output:
+ frame(output, "started", {"stream_version": 1, "root": "/fixture", "read_only": False})
+ for offset in range(0, len(entries), 128):
+ frame(output, "entries", {"entries": entries[offset:offset + 128]})
+ frame(output, "done", {"total_files": FILES, "total_dirs": DIRS + 1, "total_size": total,
+ "errors": 0, "skipped": 0, "scan_time_ms": 1, "scan_threads": 4,
+ "serialize_ms": 0, "send_ms": 0, "bytes_sent": output.tell()})
+ run("cargo", "build", "--offline", "--release", cwd=work, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE)
+ samples = []
+ for _ in range(3):
+ measurement = run("/usr/bin/time", "-l" if sys.platform == "darwin" else "-v",
+ str(work / "target/release/search-bench"), str(stream), str(expected_matches),
+ str(work / "report.json"), capture_output=True)
+ lines = measurement.stderr.splitlines()
+ rss = next(line for line in lines if "maximum resident set size" in line.lower())
+ peak = int(rss.strip().split()[0]) if sys.platform == "darwin" else int(rss.rsplit(":", 1)[1]) * 1024
+ report = json.loads((work / "report.json").read_text())
+ report["host_max_rss_bytes"] = peak
+ samples.append(report)
+ results = {"files": FILES, "directories": DIRS + 1, "expected_matches": expected_matches, "runs": samples}
+ assert all(run["fold_first_page"]["response_bytes"] == samples[0]["fold_first_page"]["response_bytes"] for run in samples)
+ assert samples[0]["no_match"]["response_bytes"] < 200
+ results["verified"] = "full NEEDLE pagination reaches every expected match; no-match page is empty"
+ print(json.dumps(results, indent=2))
diff --git a/tests/scan_ui_fixture.js b/tests/scan_ui_fixture.js
index ddad75e..f3d8747 100644
--- a/tests/scan_ui_fixture.js
+++ b/tests/scan_ui_fixture.js
@@ -13,6 +13,10 @@
let delayedLargest = true;
let failLargest = false;
let malformedLargest = false;
+ let holdSearch = false;
+ let resolveSearch;
+ let failSearch = false;
+ let malformedSearch = false;
let holdTypes = false;
let resolveTypes;
let failTypes = false;
@@ -158,6 +162,23 @@
if (delayedLargest) { delayedLargest = false; await pause(300); }
return response;
}
+ if (command === "get_search_results") {
+ check(typeof args.query === "string" && args.query !== "" && args.query.length <= 255, "Unbounded search query");
+ check(Number.isInteger(args.skip) && args.skip >= 0, "Invalid search skip");
+ if (failSearch) { failSearch = false; throw "Fixture search failure"; }
+ if (malformedSearch) {
+ malformedSearch = false;
+ return JSON.stringify({ ...scope(), query: args.query, skip: args.skip, has_more: false, results: null });
+ }
+ const matches = [...rootChildren, ...folderChildren].filter(item => 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 response = JSON.stringify({ ...scope(), query: args.query, skip: args.skip,
+ 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); }); }
+ return response;
+ }
if (command === "get_scan_comparison") {
// Same shape as the Rust query: the delta compares the live totals
// with the previous scan of the same device, so deletions count.
@@ -215,7 +236,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", "usable file workspace", "collapsible diagnostics", "complete paging", "first-scan comparison", "unchanged comparison after rescan", "deletion delta comparison", "cross-device comparison isolation", "bounded file-type totals", "file-type retry and malformed response", "file-type generation and deletion revision", "file-type coverage and empty scan", "bounded largest files", "late largest response", "largest query retry", "malformed largest response recovery", "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", "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, checks: passed ? ["offline fonts under CSP", "bounded collapsed discovery diagnostics", "discovery retry recovery", "setup alignment", "result fonts", "file label semantics", "usable file workspace", "collapsible diagnostics", "complete paging", "first-scan comparison", "unchanged comparison after rescan", "deletion delta comparison", "cross-device comparison isolation", "bounded file-type totals", "file-type retry and malformed response", "file-type generation and deletion revision", "file-type coverage and empty scan", "bounded largest files", "late largest response", "largest query retry", "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", "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");
@@ -411,6 +432,82 @@
await waitFor(() => rows().some(item => item.textContent.includes("large-folder")), "First page missing");
check(JSON.stringify(rows().map(item => item.textContent)) === JSON.stringify(firstNames), "Paging changed ordering");
+ // Search: bounded pages, a superseded held response, retry, malformed
+ // recovery, and ID-only deletion. No rescan is ever allowed here.
+ const searchRows = () => [...document.querySelectorAll(".search-result-row")];
+ const searchFor = text => {
+ const input = document.querySelector("#search-input");
+ const set = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
+ set.call(input, text);
+ input.dispatchEvent(new Event("input", { bubbles: true }));
+ document.querySelector("#search-submit").click();
+ };
+ const searchNext = () => [...document.querySelectorAll("button")].find(item => item.textContent.trim() === "Next" && !item.disabled);
+ button("Search").click();
+ await waitFor(() => document.querySelector("#search-input"), "Search controls missing");
+ // The first response is held; an empty superseding query must win and
+ // the held response must never replace it.
+ holdSearch = true;
+ searchFor("file");
+ await waitFor(() => document.querySelector("#search-input").value === "file", "Search query not submitted");
+ searchFor("zzz-no-match");
+ await waitFor(() => document.body.textContent.includes("No matching names"), "Superseding search state missing");
+ resolveSearch();
+ await pause(60);
+ check(searchRows().length === 0 && document.body.textContent.includes("No matching names"), "Held search response replaced the current results");
+ searchFor("file");
+ await waitFor(() => searchRows().length === 100, "Bounded search page missing");
+ check(searchNext(), "Search continuation missing");
+ searchNext().click();
+ await waitFor(() => searchRows().length > 0, "Second search page missing");
+ searchFor("nested");
+ await waitFor(() => searchRows().length === 37, "Byte-bounded search page missing");
+ const nestedCount = searchRows().length;
+ const firstNestedNames = searchRows().map(row => row.textContent);
+ searchNext().click();
+ await waitFor(() => searchRows()[0]?.textContent.includes("nested-37"), "Short-page continuation skipped matches");
+ check(calls.filter(call => call.command === "get_search_results").at(-1).args.skip === 37, "Short-page continuation used a fixed offset");
+ button("Previous").click();
+ await waitFor(() => searchRows()[0]?.textContent.includes("nested-0"), "Short-page Previous failed");
+ check(JSON.stringify(searchRows().map(row => row.textContent)) === JSON.stringify(firstNestedNames), "Previous changed short-page boundaries");
+ searchFor("zzz-no-match");
+ await waitFor(() => document.body.textContent.includes("No matching names"), "Empty search state missing");
+ failSearch = true;
+ searchFor("file");
+ await waitFor(() => button("Retry"), "Search failure not shown");
+ button("Retry").click();
+ await waitFor(() => searchRows().length === 100, "Search retry failed");
+ malformedSearch = true;
+ searchFor("nested");
+ await waitFor(() => button("Retry"), "Malformed search response did not offer retry");
+ check(searchRows().length === 0, "Malformed search response retained rows");
+ button("Retry").click();
+ await waitFor(() => searchRows().length === nestedCount, "Malformed search response did not recover");
+ searchFor("zzz-no-match");
+ await waitFor(() => document.body.textContent.includes("No matching names"), "Pre-delete empty state missing");
+ searchFor("file");
+ await waitFor(() => searchRows().length === 100, "Search results missing before delete");
+ searchNext().click();
+ await waitFor(() => searchRows()[0]?.textContent.includes(" file-100 "), "Second page missing before delete");
+ // Keep " file-0 "/" file-1 " for the later confirmation and
+ // partial-failure phases; delete another root file so the search row
+ // disappears on the revision refresh.
+ const target = searchRows().find(row => !row.textContent.includes("/large-folder/")
+ && !row.textContent.includes(" file-0 ") && !row.textContent.includes(" file-1 "));
+ const targetLabel = target.querySelector('[aria-label^="Delete "]').getAttribute("aria-label");
+ const deletesBeforeSearch = calls.filter(call => call.command === "delete_item").length;
+ target.querySelector('[aria-label^="Delete "]').click();
+ await waitFor(() => button("NUKE IT"), "Search confirmation missing");
+ button("NUKE IT").click();
+ await waitFor(() => !document.querySelector(`[aria-label="${targetLabel}"]`), "Deleted search row survived revision refresh");
+ await waitFor(() => searchRows()[0]?.textContent.includes(" file-0 "), "Deletion did not restart search pagination");
+ check(calls.filter(call => call.command === "get_search_results").at(-1).args.skip === 0, "Revision refresh retained the old offset");
+ check(!button("Previous"), "Previous remained enabled after revision reset");
+ check(calls.filter(call => call.command === "delete_item").length === deletesBeforeSearch + 1, "Search deletion count wrong");
+ check(calls.filter(item => item.command === "run_scan").length === scanCount + 1, "Search browsing rescanned the phone");
+ button("Storage map").click();
+ await waitFor(() => rows().length === 129, "Map missing after search");
+
zoomFolder();
await waitFor(() => button("← Back to Root"), "Zoom navigation missing");
button("← Back to Root").click();
@@ -498,6 +595,13 @@
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("Search").click();
+ await waitFor(() => document.querySelector("#search-input"), "Read-only search controls missing");
+ searchFor("file");
+ await waitFor(() => searchRows().length > 0, "Read-only search results missing");
+ check(searchRows().length > 0 && [...document.querySelectorAll('.search-result-row button[aria-label^="Delete "]')].every(item => item.disabled), "Read-only search deletion enabled");
+ button("Storage map").click();
+ await waitFor(() => rows().length === 129, "Read-only map missing after search");
button("File types").click();
await waitFor(typesReady, "Read-only file types missing");
checkTypes(470);
diff --git a/tests/search_results.test.mjs b/tests/search_results.test.mjs
new file mode 100644
index 0000000..174d482
--- /dev/null
+++ b/tests/search_results.test.mjs
@@ -0,0 +1,90 @@
+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/searchResults.ts", import.meta.url), "utf8")).replace('"./scanView"', JSON.stringify(scanView));
+const { parseSearchResults, MAX_SEARCH_RESULTS } = await import(url(source));
+const expected = { generation: "scan-a", revision: 2, root_path: "/fixture", read_only: false, total_size: 10 };
+const row = (id, name, size, type = "file", counted = true) => ({ path: `/fixture/${name}`, node: {
+ id, parent_id: 0, name, type, size, counted, child_count: type === "directory" ? 1 : 0, can_delete: true,
+} });
+const report = () => ({ generation: "scan-a", revision: 2, query: "log", skip: 0, has_more: false,
+ results: [row(3, "app.log", 7), row(5, "Logs", 3, "directory", true)] });
+const parse = (data, scope = expected, query = "log", skip = 0) => parseSearchResults(JSON.stringify(data), scope, query, skip);
+
+test("valid pages keep exact labels, IDs and both entry kinds", () => {
+ assert.deepEqual(parse(report()).results, report().results);
+ assert.equal(parse(report()).has_more, false);
+ const page = report();
+ page.skip = 100;
+ assert.equal(parse(page, expected, "log", 100).skip, 100);
+ page.results[0].ignored = "not part of the contract";
+ assert.equal(parse(page, expected, "log", 100).results[0].ignored, undefined);
+});
+
+test("empty results and byte-bounded short pages with a continuation are accepted", () => {
+ const empty = { ...report(), results: [] };
+ assert.equal(parse(empty).results.length, 0);
+ const full = { ...report(), has_more: true, results: Array(MAX_SEARCH_RESULTS).fill(row(2, "app.log", 7)) };
+ full.results = full.results.map((entry, index) => row(index + 2, `app-${index}.log`, 1));
+ assert.equal(parse(full).has_more, true);
+ assert.equal(parse({ ...report(), has_more: true }).has_more, true);
+});
+
+test("malformed payloads, pages, queries and continuations are rejected", () => {
+ for (const raw of ["{", "null", "[]", "5"]) assert.throws(() => parseSearchResults(raw, expected, "log", 0));
+ for (const results of [null, {}, [null], [null, report().results[1]], [{ node: null, path: "/fixture/app.log" }, report().results[1]]]) {
+ assert.throws(() => parse({ ...report(), results }));
+ }
+ assert.throws(() => parse({ ...report(), results: Array(MAX_SEARCH_RESULTS + 1).fill(report().results[0]) }));
+ for (const changes of [{ generation: "old" }, { revision: 1 }, { revision: -1 }, { query: "LOG" }, { skip: 1 }, { has_more: "no" }]) {
+ assert.throws(() => parse({ ...report(), ...changes }));
+ }
+ // A continuation must make progress; skip must echo the request.
+ assert.throws(() => parse({ ...report(), results: [], has_more: true }));
+ assert.throws(() => parse(report(), expected, "log", 3));
+ assert.throws(() => parse(report(), expected, "log", -1));
+ assert.throws(() => parse(report(), expected, "", 0));
+ assert.throws(() => parseSearchResults(JSON.stringify(report()), expected, undefined, 0));
+});
+
+test("duplicate or root node IDs and duplicate paths are rejected", () => {
+ const duplicate = report(); duplicate.results[1] = { ...duplicate.results[1], node: { ...duplicate.results[1].node, id: 3 } };
+ assert.throws(() => parse(duplicate));
+ const root = report(); root.results[0] = { path: "/fixture", node: { id: 0, parent_id: null, name: "fixture", type: "directory", size: 10, counted: true, child_count: 2, can_delete: false } };
+ assert.throws(() => parse(root));
+ const path = report(); path.results[1] = { ...path.results[1], path: "/fixture/app.log" };
+ assert.throws(() => parse(path));
+});
+
+test("paths must match the scan root, exact name and parent shape", () => {
+ for (const path of ["/another/app.log", "/fixture/../app.log", "/fixture//app.log", "/fixture/wrong.log", "/fixture/nested/app.log"]) {
+ const data = report(); data.results[0].path = path; assert.throws(() => parse(data));
+ }
+ for (const name of ["", ".", "..", "a/b", "bad\0name", "x".repeat(256), "\ud800"]) {
+ const data = report(); data.results[0] = row(2, name, 7); assert.throws(() => parse(data));
+ }
+ const nested = report(); nested.results[0].path = "/fixture/nested/app.log"; nested.results[0].node.parent_id = 1;
+ assert.equal(parse(nested).results[0].node.parent_id, 1);
+ const atRoot = report(); atRoot.results.forEach(entry => { entry.path = `/${entry.node.name}`; });
+ assert.equal(parse(atRoot, { ...expected, root_path: "/" }).results.length, 2);
+});
+
+test("directory rows, uncounted entries and Unicode labels stay exact and safe", () => {
+ const uncounted = report(); uncounted.results[0] = row(4, "placeholder", 0, "file", false);
+ assert.equal(parse(uncounted).results[0].node.counted, false);
+ for (const name of [" leading trailing ", "\ufeffname", "photo-🙂", "报告.log"]) {
+ const data = report(); data.results[0] = row(2, name, 7);
+ assert.equal(parse(data).results[0].node.name, name);
+ }
+ for (const delimiter of ["line\nname", "line\rname"]) {
+ const data = report(); data.results[0] = row(2, delimiter, 7); data.results[0].node.can_delete = false;
+ assert.equal(parse(data).results[0].node.can_delete, false);
+ const deletable = report(); deletable.results[0] = row(2, delimiter, 7);
+ assert.throws(() => parse(deletable));
+ }
+});