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

Search within a folder in scan results (#206)

Vishnu Srivatsava7691538e8388
diff --git a/docs/search.md b/docs/search.md
index 9687c5c..2f23199 100644
--- a/docs/search.md
+++ b/docs/search.md
@@ -4,6 +4,9 @@ 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.
+Zoom into a folder in the storage map and choose **Search this folder** to
+search its descendants. Switch between that folder and the entire scan without
+retyping the query. Changing scope starts at the first page.
## Matching rules
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 5baa310..9593a87 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -601,12 +601,13 @@ fn get_search_results(
revision: u32,
query: String,
skip: u32,
+ folder_id: Option<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)
+ .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.rs
index cfde24e..0102ece 100644
--- a/src-tauri/src/scan_store.rs
+++ b/src-tauri/src/scan_store.rs
@@ -501,11 +501,12 @@ 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(
+ fn visit_entries_from(
&self,
+ folder: u32,
mut visit: impl FnMut(u32, &Node) -> Result<bool, String>,
) -> Result<(), String> {
- let mut pending = vec![self.children[0].iter()];
+ let mut pending = vec![self.children[folder as usize].iter()];
while let Some(children) = pending.last_mut() {
if let Some(key) = children.next() {
let id = key.2;
@@ -535,7 +536,7 @@ impl Catalog {
Ok(())
};
collect(0, &self.response.nodes[0])?;
- self.visit_entries(|id, node| { collect(id, node)?; Ok(true) })?;
+ self.visit_entries_from(0, |id, node| { collect(id, node)?; Ok(true) })?;
if skip > 0 && skip >= packages.len() {
return Err("Package page is no longer available".into());
}
@@ -620,8 +621,13 @@ impl Catalog {
revision: u32,
query: &str,
skip: u32,
+ folder_id: Option<u32>,
) -> Result<String, String> {
self.scope(generation, revision)?;
+ let folder = folder_id.unwrap_or(0);
+ if self.node(folder)?.kind != Kind::Directory {
+ return Err("Search scope must be a directory".into());
+ }
if query.is_empty() {
return Err("Enter text to search this scan".into());
}
@@ -641,6 +647,7 @@ impl Catalog {
revision: u32,
query: &'a str,
skip: u32,
+ folder_id: Option<u32>,
has_more: bool,
results: Vec<Entry<'a>>,
}
@@ -649,6 +656,7 @@ impl Catalog {
revision: self.revision,
query,
skip,
+ folder_id,
has_more: false,
results: Vec::with_capacity(MAX_SEARCH_RESULTS),
};
@@ -656,7 +664,7 @@ 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(|id, node| {
+ self.visit_entries_from(folder, |id, node| {
if !name_matches(&node.name, query.as_bytes()) {
return Ok(true);
}
@@ -1762,27 +1770,27 @@ mod tests {
.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]));
+ assert_eq!(ids(store.search_json("generation-a", 0, "PHOTO.JPG", 0, None)), json!([1, 2]));
+ assert_eq!(ids(store.search_json("generation-a", 0, "photo", 0, None)), json!([1, 2, 4]));
+ assert_eq!(ids(store.search_json("generation-a", 0, "PHÖ", 0, None)), json!([]));
+ assert_eq!(ids(store.search_json("generation-a", 0, "phö", 0, None)), 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!([]));
+ assert_eq!(ids(store.search_json("generation-a", 0, "link", 0, None)), json!([5]));
+ assert_eq!(ids(store.search_json("generation-a", 0, "\n", 0, None)), json!([6]));
+ assert_eq!(ids(store.search_json("generation-a", 0, "fixture", 0, None)), 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, query, 0, None).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());
+ assert!(store.search_json("generation-a", 0, &"x".repeat(255), 0, None).is_ok());
+ assert!(store.search_json("old", 0, "photo", 0, None).is_err());
+ assert!(store.search_json("generation-a", 1, "photo", 0, None).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));
+ let page = |skip: u32| value(store.search_json("generation-a", 0, "FILE-", skip, None));
// 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();
@@ -1844,7 +1852,7 @@ mod tests {
let mut seen = BTreeSet::new();
let mut skip = 0;
loop {
- let raw = store.search_json("generation-a", 0, "needle", skip).unwrap();
+ let raw = store.search_json("generation-a", 0, "needle", skip, None).unwrap();
assert!(raw.len() <= MAX_QUERY_BYTES);
let page: Value = serde_json::from_str(&raw).unwrap();
let rows = page["results"].as_array().unwrap();
@@ -1874,7 +1882,7 @@ mod tests {
let store = Catalog::new(fixture(&entries, false), "generation-a".into());
let mut visited = Vec::new();
store
- .visit_entries(|id, _| {
+ .visit_entries_from(0, |id, _| {
visited.push(id);
Ok(false)
})
@@ -1883,7 +1891,7 @@ mod tests {
let store = Catalog::new(fixture(&wide(250), false), "generation-a".into());
let mut matches = 0;
store
- .visit_entries(|_, node| {
+ .visit_entries_from(0, |_, node| {
matches += usize::from(name_matches(&node.name, b"file-"));
Ok(matches <= MAX_SEARCH_RESULTS)
})
@@ -1891,6 +1899,40 @@ mod tests {
assert_eq!(matches, MAX_SEARCH_RESULTS + 1);
}
+ #[test]
+ fn folder_search_pages_only_live_descendants() {
+ let mut entries = vec![
+ root(),
+ entry(1, Some(0), "Logs", "directory", 0, true),
+ entry(2, Some(0), "Logs-old", "directory", 0, true),
+ entry(3, Some(2), "log-outside", "file", 500, true),
+ entry(4, Some(1), "Nested", "directory", 0, true),
+ ];
+ for id in 5..106 {
+ entries.push(entry(id, Some(4), &format!("log-{id:03}"), "file", 1, true));
+ }
+ let mut store = Some(Catalog::new(fixture(&entries, false), "generation-a".into()));
+ let catalog = store.as_ref().unwrap();
+ let search = |skip| value(catalog.search_json("generation-a", 0, "log", skip, Some(1)));
+ let first = search(0);
+ assert_eq!(first["folder_id"], 1);
+ assert_eq!(first["has_more"], true);
+ let rows = first["results"].as_array().unwrap();
+ assert_eq!(rows.len(), MAX_SEARCH_RESULTS);
+ assert_eq!(rows[0]["node"]["id"], 5);
+ assert_eq!(rows[99]["node"]["id"], 104);
+ let last = search(100);
+ assert_eq!(last["has_more"], false);
+ assert_eq!(last["results"].as_array().unwrap().len(), 1);
+ assert_eq!(last["results"][0]["node"]["id"], 105);
+ for invalid in [3, 999] {
+ assert!(catalog.search_json("generation-a", 0, "log", 0, Some(invalid)).is_err());
+ }
+ let plan = catalog.prepare_delete("generation-a", 0, 1).unwrap();
+ finish_delete(&mut store, &plan, success()).unwrap();
+ assert!(store.as_ref().unwrap().search_json("generation-a", 1, "log", 0, Some(1)).is_err());
+ }
+
#[test]
fn search_excludes_deleted_subtrees_and_requires_current_revision() {
let entries = vec![
@@ -1902,7 +1944,7 @@ mod tests {
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)
+ store.as_ref().unwrap().search_json("generation-a", revision, query, 0, None)
)["results"]
.as_array()
.unwrap()
@@ -1919,6 +1961,6 @@ mod tests {
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());
+ assert!(store.as_ref().unwrap().search_json("generation-a", 0, "song", 0, None).is_err());
}
}
diff --git a/src/ResultScreen.tsx b/src/ResultScreen.tsx
index 7aef91d..1e21149 100644
--- a/src/ResultScreen.tsx
+++ b/src/ResultScreen.tsx
@@ -1,3 +1,4 @@
+import type { SearchFolder } from "./searchResults";
import { useEffect, useState } from "react";
import { StorageMap } from "./StorageMap";
import { formatBytes } from "./formatBytes";
@@ -41,6 +42,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" | "search" | "apps">("map");
+ const [searchFolder, setSearchFolder] = useState<SearchFolder | null>(null);
const view = useScanView(data, zoomId, mode === "map");
const page = view.page;
const onZoom = (id: number) => {
@@ -133,12 +135,12 @@ 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")}
+ <button aria-pressed={mode === "search"} disabled={busy} onClick={() => { setSearchFolder(null); 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>
<button aria-pressed={mode === "apps"} disabled={busy} onClick={() => setMode("apps")}
className={`px-3 py-2 rounded-lg text-xs whitespace-nowrap ${mode === "apps" ? "bg-zinc-700 text-white" : "bg-zinc-900 text-zinc-400"}`}>Package folders</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 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 === "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 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">
<div className="min-h-0 min-w-0">
<StorageMap page={page} busy={busy} onZoom={onZoom} />
</div>
@@ -147,6 +149,16 @@ export function ResultScreen({
<section aria-label="Files and folders" className="glass-card rounded-xl overflow-y-auto px-2 pb-3 min-h-0 min-w-0">
<div className="flex items-center gap-2 px-3 py-2 mb-1">
<span className="text-xs font-semibold text-zinc-500 uppercase tracking-wider flex-1">Files and folders</span>
+ {page?.node.type === "directory" && page.node.id !== data.root.id && (
+ <button
+ disabled={busy}
+ onClick={() => {
+ setSearchFolder({ id: page.node.id, name: page.node.name, path: page.path });
+ setMode("search");
+ }}
+ className="text-xs text-accent-400 hover:underline"
+ >Search this folder</button>
+ )}
<span className="text-xs text-zinc-500">
{[data.errors > 0 ? `${data.errors} access errors` : "", data.skipped > 0 ? `${data.skipped} excluded or duplicate entries` : ""].filter(Boolean).join(" · ")}
</span>
diff --git a/src/SearchFiles.tsx b/src/SearchFiles.tsx
index e55205c..e5486ff 100644
--- a/src/SearchFiles.tsx
+++ b/src/SearchFiles.tsx
@@ -1,11 +1,12 @@
import { useEffect, useState } from "react";
import { getSearchResults } from "./scanIpc";
-import type { SearchResponse } from "./searchResults";
+import type { SearchFolder, SearchResponse } from "./searchResults";
import type { ScanResponse } from "./scanView";
import { formatBytes } from "./formatBytes";
-export function SearchFiles({ scope, busy, onZoom, onNuke }: {
+export function SearchFiles({ scope, folder, busy, onZoom, onNuke }: {
scope: ScanResponse;
+ folder: SearchFolder | null;
busy: boolean;
onZoom: (id: number) => void;
onNuke: (id: number, trigger: HTMLButtonElement) => void;
@@ -13,25 +14,27 @@ export function SearchFiles({ scope, busy, onZoom, onNuke }: {
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 [entireScan, setEntireScan] = useState(false);
+ const activeFolder = entireScan ? null : folder;
+ const pageScope = JSON.stringify([generation, revision, activeFolder?.id]);
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 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;
let current = true;
- void getSearchResults({ generation, revision, root_path, read_only, total_size }, query, skip).then(data => {
+ void getSearchResults({ generation, revision, root_path, read_only, total_size }, query, skip, activeFolder).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, retry, key]);
+ }, [generation, revision, root_path, read_only, total_size, query, skip, activeFolder, 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;
@@ -41,18 +44,28 @@ export function SearchFiles({ scope, busy, onZoom, onNuke }: {
setPagination({ scope: pageScope, offsets: [0] });
};
const results = data?.results ?? [];
+ const changeScope = () => {
+ 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(); }}>
<input id="search-input" value={input} disabled={busy}
onChange={event => setInput(event.target.value)}
- placeholder="Search names in this scan"
+ 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>
+ {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">
+ {activeFolder ? "Search entire scan" : "Search this folder"}
+ </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" : "Search names in the completed scan."}
+ {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>
<div className="flex gap-2 shrink-0 text-xs">
<button disabled={busy || !data || skip === 0} onClick={() => setPagination({ scope: pageScope, offsets: offsets.slice(0, -1) })}
@@ -62,7 +75,7 @@ export function SearchFiles({ scope, 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 scan.</p>}
+ {data && results.length === 0 && <p className="text-sm text-zinc-400 py-4">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.ts
index 6696fa9..1d6a037 100644
--- a/src/scanIpc.ts
+++ b/src/scanIpc.ts
@@ -3,6 +3,7 @@ import { parseDeleteResult, parseNodeDetail, parseScanView } from "./scanView";
import type { PageCursor, ScanScope } from "./scanView";
import { parseLargestFiles } from "./largestFilesSummary";
import { parseSearchResults } from "./searchResults";
+import type { SearchFolder } from "./searchResults";
import { parseFileTypes } from "./fileTypeSummary";
import { parseAppUsage } from "./appUsageSummary";
import { parseScanComparison } from "./scanComparison";
@@ -12,9 +13,11 @@ export async function getLargestFiles(scope: Parameters<typeof parseLargestFiles
return parseLargestFiles(raw, scope, limit);
}
-export async function getSearchResults(scope: Parameters<typeof parseSearchResults>[1], query: string, skip: number) {
- const raw = await invoke<string>("get_search_results", { generation: scope.generation, revision: scope.revision, query, skip });
- return parseSearchResults(raw, scope, query, skip);
+export async function getSearchResults(scope: Parameters<typeof parseSearchResults>[1], query: string, skip: number, folder: SearchFolder | null) {
+ const raw = await invoke<string>("get_search_results", {
+ generation: scope.generation, revision: scope.revision, query, skip, folderId: folder?.id ?? null,
+ });
+ return parseSearchResults(raw, scope, query, skip, folder);
}
export async function getFileTypes(scope: Parameters<typeof parseFileTypes>[1]) {
diff --git a/src/searchResults.ts b/src/searchResults.ts
index d0536be..188828e 100644
--- a/src/searchResults.ts
+++ b/src/searchResults.ts
@@ -2,21 +2,25 @@ import { sameScan, isRecord, isCount, isU32, parseNodeReference } from "./scanVi
import type { ScanScope, ScanResponse, NodeDetail } from "./scanView";
export const MAX_SEARCH_RESULTS = 100;
+export type SearchFolder = { id: number; name: string; path: string };
export interface SearchResponse extends ScanScope {
query: string;
skip: number;
+ folder_id: number | null;
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 {
+export function parseSearchResults(raw: string, expected: Expected, query: string, skip: number, folder: SearchFolder | 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");
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
+ || data.folder_id !== folderId
|| typeof data.has_more !== "boolean"
|| !Array.isArray(data.results) || data.results.length > MAX_SEARCH_RESULTS
|| (data.results.length === 0 && data.has_more)) throw invalid();
@@ -27,9 +31,10 @@ export function parseSearchResults(raw: string, expected: Expected, query: strin
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();
+ 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, has_more: data.has_more, results };
+ return { generation: data.generation, revision: data.revision, query, skip, folder_id: folderId, has_more: data.has_more, results };
}
diff --git a/tests/benchmark_search.py b/tests/benchmark_search.py
index 4cc1eb4..9336e04 100644
--- a/tests/benchmark_search.py
+++ b/tests/benchmark_search.py
@@ -85,10 +85,10 @@ fn main() {{
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());
+ timed(&mut report, "fold_first_page", || store.search_json(&generation, 0, "NEEDLE", 0, None).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 value: serde_json::Value = serde_json::from_str(&store.search_json(&generation, 0, "NEEDLE", page as u32, None).unwrap()).unwrap();
let results = value["results"].as_array().unwrap().len();
page += results;
if !value["has_more"].as_bool().unwrap() {{ break; }}
@@ -96,15 +96,15 @@ fn main() {{
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());
+ timed(&mut report, "common_first_page", || store.search_json(&generation, 0, "file-0", 0, None).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(),
+ || store.search_json(&generation, 0, "file-0", (common_matches - 100) as u32, None).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());
+ timed(&mut report, "no_match", || store.search_json(&generation, 0, "zzz-no-match", 0, None).unwrap());
std::fs::File::create(&args[3]).unwrap().write_all(serde_json::to_string_pretty(&report).unwrap().as_bytes()).unwrap();
}}''')
stream = work / "fixture.stream"
diff --git a/tests/scan_ui_fixture.js b/tests/scan_ui_fixture.js
index a6344ed..f77ecd7 100644
--- a/tests/scan_ui_fixture.js
+++ b/tests/scan_ui_fixture.js
@@ -221,15 +221,17 @@
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");
+ check(args.folderId === null || args.folderId === 1, "Unexpected search folder");
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 });
+ return JSON.stringify({ ...scope(), query: args.query, skip: args.skip, folder_id: args.folderId, has_more: false, results: null });
}
- const matches = [...rootChildren, ...folderChildren].filter(item => item.name.toLowerCase().includes(args.query.toLowerCase()));
+ const candidates = args.folderId === 1 ? folderChildren : [...rootChildren, ...folderChildren];
+ const matches = candidates.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,
+ const response = JSON.stringify({ ...scope(), query: args.query, skip: args.skip, folder_id: args.folderId,
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); }); }
@@ -670,6 +672,30 @@
document.querySelector("#search-submit").click();
};
const searchNext = () => [...document.querySelectorAll("button")].find(item => item.textContent.trim() === "Next" && !item.disabled);
+ zoomFolder();
+ await waitFor(() => button("Search this folder"), "Folder search entry point missing");
+ button("Search this folder").click();
+ await waitFor(() => document.querySelector("#search-input"), "Folder search controls missing");
+ searchFor("nested");
+ await waitFor(() => searchRows().length === 37, "First folder search page missing");
+ check(calls.filter(call => call.command === "get_search_results").at(-1).args.folderId === 1, "Search lost the folder ID");
+ holdSearch = true;
+ searchNext().click();
+ await waitFor(() => typeof resolveSearch === "function", "Second folder page did not start");
+ button("Search entire scan").click();
+ await waitFor(() => searchRows()[0]?.textContent.includes("nested-0"), "Scope switch retained the page offset");
+ resolveSearch();
+ resolveSearch = undefined;
+ await pause(30);
+ check(searchRows()[0]?.textContent.includes("nested-0"), "Late folder page replaced whole-scan results");
+ searchFor("file");
+ await waitFor(() => searchRows().length === 100, "Whole-scan results missing");
+ button("Search this folder").click();
+ await waitFor(() => document.body.textContent.includes("No matching names in this folder"), "Folder search included outside filenames");
+ button("← Back to Root").click();
+ await waitFor(() => rows()[0]?.textContent.includes("fixture") && folderToggle(), "Root map missing after folder search");
+ if (folderToggle().getAttribute("aria-expanded") === "true") await activate(folderToggle());
+ await waitFor(() => rows().length === 129, "Root entries did not settle after folder search");
button("Search").click();
await waitFor(() => document.querySelector("#search-input"), "Search controls missing");
// The first response is held; an empty superseding query must win and
diff --git a/tests/search_results.test.mjs b/tests/search_results.test.mjs
index 174d482..0f2c846 100644
--- a/tests/search_results.test.mjs
+++ b/tests/search_results.test.mjs
@@ -12,7 +12,7 @@ const expected = { generation: "scan-a", revision: 2, root_path: "/fixture", rea
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,
+const report = () => ({ generation: "scan-a", revision: 2, query: "log", skip: 0, folder_id: null, 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);
@@ -88,3 +88,16 @@ test("directory rows, uncounted entries and Unicode labels stay exact and safe",
assert.throws(() => parse(deletable));
}
});
+
+test("scoped pages must echo the folder and contain only descendants", () => {
+ const folder = { id: 1, name: "Logs", path: "/fixture/Logs" };
+ const entry = row(3, "app.log", 7);
+ entry.path = "/fixture/Logs/app.log";
+ entry.node.parent_id = 1;
+ const data = { ...report(), folder_id: 1, results: [entry] };
+ const parseScoped = page => parseSearchResults(JSON.stringify(page), expected, "log", 0, folder);
+ assert.equal(parseScoped(data).results[0].path, entry.path);
+ assert.throws(() => parseScoped({ ...data, folder_id: null }));
+ assert.throws(() => parseScoped({ ...data, folder_id: 2 }));
+ assert.throws(() => parseScoped({ ...data, results: [{ ...entry, path: "/fixture/Logs-old/app.log" }] }));
+});