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

Bound discovery error details and coalesce pending device requests (#72)

Vishnu Srivatsava28812d69cc0f
diff --git a/docs/device-selection.md b/docs/device-selection.md
index 4d8cc73..b193a5d 100644
--- a/docs/device-selection.md
+++ b/docs/device-selection.md
@@ -13,9 +13,16 @@ selection stays visible and blocks Connect; choosing another phone is an
explicit action. Selection survives refreshes, connection errors, and stopping
within the running app. It is not saved across app restarts.
If discovery fails, the selected device's status is unavailable rather than
-claimed disconnected; Connect stays blocked until discovery succeeds.
+claimed disconnected; Connect stays blocked until discovery succeeds. Setup shows
+a short error with recovery guidance. Raw command diagnostics are escaped,
+limited to 4,096 UTF-16 code units using the shared diagnostic-text bound, and
+collapsed under **Technical details**. Expanded details scroll within a bounded
+panel instead of filling the setup screen.
Discovery runs on entering setup and on Refresh, without background polling.
+Repeated requests from that setup hook share one pending `list_devices` call,
+including development StrictMode's effect replay. Once it settles, Refresh
+starts a new command; completed device lists are never reused as a cache.
Its result is a snapshot. Connect checks the selected serial against a fresh
list in Rust before pushing or launching the daemon. If it vanished after the
displayed snapshot, startup fails; there is no first-device fallback. If it
@@ -59,11 +66,17 @@ session isolation, generation invalidation, authentication, deletion, and root
tests remain enabled.
Node tests cover initial selection, preservation, and status guidance. The
-built-UI mocked-IPC replay covers multiple ready devices, disabled unavailable
-options, model-text escaping, refresh locks/failure, unplugging, reordering,
+built-UI mocked-IPC replay covers an oversized ADB-server startup dump, bounded
+collapsed details, markup escaping, retry recovery, multiple ready devices,
+disabled unavailable options, model-text escaping, refresh locks/failure, unplugging, reordering,
reconnection, a stale displayed device at startup, duplicate clicks, result
identity, explicit switching, and confirmation invalidation. These fixtures do
not prove real USB transport, physical hotplug timing, or root-manager behavior.
+A separate development-React fixture requires StrictMode's two effect setups,
+asserts that they launch one discovery command, and checks repeated refreshes,
+success/error retries and late responses after unmount. These requests are
+mocked; the fixture neither starts nor stops a real ADB server. Coalescing this
+app's discovery does not resolve an external process occupying ADB's port.
No native app, real ADB, or phone test was run locally. For a manual check, build
the app yourself using the README steps, then:
diff --git a/src/App.tsx b/src/App.tsx
index 05493ff..9df0cba 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -151,8 +151,12 @@ function SetupScreen({ onConnect, loading, rootMode, onRootModeChange, rootPath,
</option>)}
</select>
<p id="device-status" role={error ? "alert" : "status"} className="text-xs leading-relaxed text-zinc-400">
- {refreshing ? "Checking connected devices…" : error ?? deviceSelectionHint(devices, serial)}
+ {refreshing ? "Checking connected devices…" : error?.message ?? deviceSelectionHint(devices, serial)}
</p>
+ {error && <details id="device-error-details" className="text-xs text-zinc-500">
+ <summary className="cursor-pointer hover:text-zinc-300">Technical details</summary>
+ <pre className="mt-2 max-h-40 overflow-auto whitespace-pre-wrap break-all rounded-lg border border-zinc-800 bg-zinc-900 p-3 font-mono">{error.details}</pre>
+ </details>}
</div>
<label className="flex items-center justify-center gap-2.5 text-zinc-300 cursor-pointer">
<input
diff --git a/src/devices.ts b/src/devices.ts
index c5c0111..1ce8ea2 100644
--- a/src/devices.ts
+++ b/src/devices.ts
@@ -32,3 +32,13 @@ export function deviceSelectionHint(devices: AndroidDevice[], serial: string): s
if (!serial) return "Choose a ready device. Unlock and authorize phones marked unavailable, then refresh.";
return "Only this device will be scanned.";
}
+
+/** Diagnostic dumps belong in explicit details, never in the setup status. */
+export function deviceDiscoveryMessage(details: string): string {
+ const error = details.toLowerCase();
+ if (["adb server didn't ack", "failed to start daemon", "cannot connect to daemon", "smartsocket", "address already in use"].some(text => error.includes(text))) {
+ return "ADB could not start. Wait a moment and refresh. If it persists, close other Android tools and retry.";
+ }
+ if (error.includes("timed out")) return "Checking devices timed out. Reconnect the USB cable and refresh.";
+ return "Couldn't check connected devices. Refresh to try again.";
+}
diff --git a/src/logHistory.ts b/src/logHistory.ts
index bcbdc14..70de0a0 100644
--- a/src/logHistory.ts
+++ b/src/logHistory.ts
@@ -14,7 +14,7 @@ export function emptyLogHistory(): LogHistory {
return { entries: [], textUnits: 0, discarded: 0 };
}
-function boundedEntry(message: string): string {
+export function boundDiagnostic(message: string): string {
if (message.length > MAX_LOG_ENTRY_UNITS) {
let end = MAX_LOG_ENTRY_UNITS - TRUNCATION_MARKER.length;
// Do not split an astral character at the truncation boundary.
@@ -28,7 +28,7 @@ function boundedEntry(message: string): string {
}
export function appendLog(history: LogHistory, message: string): LogHistory {
- const entry = boundedEntry(message);
+ const entry = boundDiagnostic(message);
let textUnits = history.textUnits + entry.length;
let remove = 0;
while (history.entries.length - remove + 1 > MAX_LOG_ENTRIES || textUnits > MAX_LOG_TEXT_UNITS) {
diff --git a/src/useDevices.ts b/src/useDevices.ts
index 4738027..092cc5d 100644
--- a/src/useDevices.ts
+++ b/src/useDevices.ts
@@ -1,27 +1,33 @@
import { useCallback, useEffect, useRef, useState } from "react";
import { invoke } from "@tauri-apps/api/core";
-import { preserveDeviceSelection } from "./devices";
+import { deviceDiscoveryMessage, preserveDeviceSelection } from "./devices";
+import { boundDiagnostic } from "./logHistory";
import type { AndroidDevice } from "./devices";
export function useDevices(enabled: boolean) {
const [devices, setDevices] = useState<AndroidDevice[]>([]);
const [serial, select] = useState("");
const [loading, setLoading] = useState(true);
- const [error, setError] = useState<string | null>(null);
+ const [error, setError] = useState<{ message: string; details: string } | null>(null);
const request = useRef(0);
+ const pending = useRef<Promise<AndroidDevice[]> | null>(null);
const refresh = useCallback(async () => {
const id = ++request.current;
setLoading(true);
setError(null);
try {
- const result = await invoke<AndroidDevice[]>("list_devices");
+ // StrictMode replays setup effects while their IPC is still pending.
+ // Share only that in-flight command; settled lists are never cached.
+ const result = await (pending.current ??= invoke<AndroidDevice[]>("list_devices")
+ .finally(() => { pending.current = null; }));
if (id !== request.current) return;
setDevices(result);
select(previous => preserveDeviceSelection(previous, result));
} catch (error) {
if (id !== request.current) return;
setDevices([]);
- setError(String(error));
+ const details = String(error);
+ setError({ message: deviceDiscoveryMessage(details), details: boundDiagnostic(details) });
} finally {
if (id === request.current) setLoading(false);
}
diff --git a/tests/check_scan_ui.py b/tests/check_scan_ui.py
index d3da163..25b2395 100644
--- a/tests/check_scan_ui.py
+++ b/tests/check_scan_ui.py
@@ -67,6 +67,15 @@ with tempfile.TemporaryDirectory(prefix='socketsweep-ui-test-') as directory:
rollupOptions: { input: ['tests/toast_lifecycle_fixture.html', 'tests/log_history_fixture.html'] },
}});
''', str(work / 'site')], cwd=REPO, check=True, timeout=60)
+ # A separate development-React bundle verifies StrictMode's double effect;
+ # the production UI and other fixtures retain their production bundles.
+ subprocess.run(['node', '--input-type=module', '-e', """
+ import { build } from 'vite';
+ await build({ logLevel: 'error', define: { 'process.env.NODE_ENV': '"development"' }, build: {
+ outDir: process.argv[1], emptyOutDir: false,
+ rollupOptions: { input: 'tests/device_discovery_fixture.html' },
+ }});
+ """, str(work / 'site')], cwd=REPO, check=True, timeout=60)
server = ThreadingHTTPServer(('127.0.0.1', 0), partial(Handler, directory=str(work / 'site')))
threading.Thread(target=server.serve_forever, daemon=True).start()
try:
@@ -77,10 +86,10 @@ with tempfile.TemporaryDirectory(prefix='socketsweep-ui-test-') as directory:
'--host-resolver-rules=MAP * ~NOTFOUND, EXCLUDE 127.0.0.1',
f'--window-size={os.environ.get("UI_TEST_WINDOW", "1280,1000")}',
f'--force-device-scale-factor={os.environ.get("UI_TEST_SCALE", "1")}',
- f'--user-data-dir={work / "profile"}', f'http://127.0.0.1:{server.server_port}'],
+ f'--user-data-dir={work / "profile"}', f'http://127.0.0.1:{server.server_port}/tests/device_discovery_fixture.html'],
stdout=log, stderr=log, start_new_session=True)
try:
- for expected in ('scan-ui', 'toast-lifecycle', 'log-history'):
+ for expected in ('device-discovery', 'scan-ui', 'toast-lifecycle', 'log-history'):
value = reports.get(timeout=40)
print(json.dumps(value, indent=2))
if value.get('fixture') != expected or not value['passed']:
diff --git a/tests/device_discovery_fixture.html b/tests/device_discovery_fixture.html
new file mode 100644
index 0000000..4907d5b
--- /dev/null
+++ b/tests/device_discovery_fixture.html
@@ -0,0 +1,8 @@
+<!doctype html>
+<html lang="en">
+ <head><meta charset="UTF-8" /><title>Device discovery lifecycle fixture</title></head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/tests/device_discovery_fixture.jsx"></script>
+ </body>
+</html>
diff --git a/tests/device_discovery_fixture.jsx b/tests/device_discovery_fixture.jsx
new file mode 100644
index 0000000..7cd745f
--- /dev/null
+++ b/tests/device_discovery_fixture.jsx
@@ -0,0 +1,65 @@
+// Development React exercises the real StrictMode effect replay. IPC is mocked.
+import { StrictMode, useEffect } from "react";
+import { createRoot } from "react-dom/client";
+import { useDevices } from "../src/useDevices";
+
+let model;
+let effects = 0;
+let calls = 0;
+const pending = [];
+const check = (condition, message) => { if (!condition) throw Error(message); };
+const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
+const waitFor = async (predicate, message) => {
+ const end = Date.now() + 3000;
+ while (!predicate()) { if (Date.now() > end) throw Error(message); await pause(10); }
+};
+window.__TAURI_INTERNALS__ = {
+ invoke: command => {
+ check(command === "list_devices", "Unexpected device operation");
+ calls++;
+ return new Promise((resolve, reject) => pending.push({ resolve, reject }));
+ },
+};
+function Probe() {
+ model = useDevices(true);
+ useEffect(() => { effects++; }, []);
+ return <p>{model.loading ? "Checking" : "Finished"}</p>;
+}
+const root = createRoot(document.getElementById("root"));
+const report = async (passed, error) => {
+ await fetch("/report", { method: "POST", body: JSON.stringify({ fixture: "device-discovery", passed, error, effects, calls,
+ checks: passed ? ["development StrictMode replay", "coalesced pending discovery", "refresh after success/error", "unmount invalidation"] : undefined }) });
+ if (passed) location.replace("/");
+};
+void (async () => {
+ root.render(<StrictMode><Probe /></StrictMode>);
+ await waitFor(() => effects === 2, "Fixture did not exercise development StrictMode");
+ check(calls === 1, `StrictMode launched ${calls} simultaneous discovery commands`);
+ const a = model.refresh();
+ const b = model.refresh();
+ check(calls === 1, "Repeated refresh launched another pending command");
+ pending.shift().resolve([{ serial: "chosen", state: "device", model: null }]);
+ await Promise.all([a, b]);
+ await waitFor(() => model.ready, "Latest subscriber did not receive discovery");
+
+ const failed = model.refresh();
+ check(calls === 2, "Settled discovery was reused as a cached result");
+ pending.shift().reject("ADB server didn't ACK\n<bad diagnostic>");
+ await failed;
+ await waitFor(() => model.error && !model.loading, "Discovery failure did not finish");
+ check(model.serial === "chosen" && !model.ready, "Failure replaced selection or granted readiness");
+
+ const recovered = model.refresh();
+ check(calls === 3, "Failed discovery prevented a fresh retry");
+ pending.shift().resolve([{ serial: "chosen", state: "device", model: null }]);
+ await recovered;
+ await waitFor(() => model.ready && !model.error, "Discovery retry did not recover");
+
+ const abandoned = model.refresh();
+ check(calls === 4, "Final discovery missing");
+ root.unmount();
+ pending.shift().reject("late failure");
+ await abandoned;
+ check(!document.querySelector("#root").textContent, "Unmounted discovery changed the UI");
+ await report(true);
+})().catch(error => report(false, error.stack ?? String(error)));
diff --git a/tests/devices.test.mjs b/tests/devices.test.mjs
index 3e61003..d0d0abd 100644
--- a/tests/devices.test.mjs
+++ b/tests/devices.test.mjs
@@ -7,7 +7,7 @@ const source = await readFile(new URL("../src/devices.ts", import.meta.url), "ut
const { outputText } = ts.transpileModule(source, {
compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext },
});
-const { preserveDeviceSelection, deviceSelectionHint, deviceStateLabel } = await import(
+const { preserveDeviceSelection, deviceSelectionHint, deviceStateLabel, deviceDiscoveryMessage } = await import(
`data:text/javascript;base64,${Buffer.from(outputText).toString("base64")}`
);
const phone = (serial, state = "device") => ({ serial, state, model: null });
@@ -38,3 +38,16 @@ test("unavailable selections explain the required action without claiming readin
assert.equal(deviceStateLabel("device"), "Ready");
assert.equal(deviceStateLabel("recovery"), "recovery");
});
+
+test("discovery failures show actionable summaries without raw diagnostics", () => {
+ for (const detail of ["ADB server didn't ACK", "* failed to start daemon", "could not install *smartsocket* listener: Address already in use", "cannot connect to daemon"]) {
+ const message = deviceDiscoveryMessage("adb devices -l failed (exit 1): " + detail + "\n" + "x".repeat(10000));
+ assert.match(message, /ADB could not start/);
+ assert.match(message, /refresh/);
+ assert.ok(message.length < 120);
+ assert.ok(!message.includes(detail));
+ }
+ assert.match(deviceDiscoveryMessage("ADB command timed out"), /timed out.*refresh/);
+ const raw = "<img src=x onerror=alert(1)> /private/log " + "x".repeat(100000);
+ assert.equal(deviceDiscoveryMessage(raw), "Couldn't check connected devices. Refresh to try again.");
+});
diff --git a/tests/scan_ui_fixture.js b/tests/scan_ui_fixture.js
index a49119c..e03517f 100644
--- a/tests/scan_ui_fixture.js
+++ b/tests/scan_ui_fixture.js
@@ -21,6 +21,7 @@
];
let listedDevices = readyDevices;
let discoveryError = false;
+ const discoveryDump = "adb devices -l failed (exit 1):\n* daemon not running; starting now at tcp:5037\nADB server didn't ACK\nFull server startup log: /tmp/adb.fixture.log\ncould not install *smartsocket* listener: Address already in use\n<img src=invalid onerror=alert(1)>\n" + "startup diagnostics\n".repeat(2000);
let activeDevice = null;
let callbacks = 0;
let rootChildren;
@@ -75,7 +76,7 @@
calls.push({ command, args });
if (command === "list_devices") {
await pause(50);
- if (discoveryError) throw "Mock discovery failed";
+ if (discoveryError) throw discoveryDump;
return listedDevices;
}
if (command === "check_adb") return "Mock ADB " + "x".repeat(20000);
@@ -139,7 +140,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", "setup alignment", "result fonts", "file label semantics", "complete paging", "bounded largest files", "late largest response", "largest query retry", "largest ID-only deletion", "largest read-only guards", "largest folder navigation without rescanning", "late zoom", "Other tile", "stale confirmation", "ID-only deletion", "revision refresh", "partial failure", "read-only", "acknowledged shutdown", "unconfirmed shutdown", "reconnect", "stop action ordering", "toast dismissal integration", "bounded diagnostic integration"] : undefined });
+ output.textContent = JSON.stringify({ fixture: "scan-ui", passed, error, ipc_calls: calls.length, checks: passed ? ["offline fonts under CSP", "bounded collapsed discovery diagnostics", "discovery retry recovery", "setup alignment", "result fonts", "file label semantics", "complete paging", "bounded largest files", "late largest response", "largest query retry", "largest ID-only deletion", "largest read-only guards", "largest folder navigation without rescanning", "late zoom", "Other tile", "stale confirmation", "ID-only deletion", "revision refresh", "partial failure", "read-only", "acknowledged shutdown", "unconfirmed shutdown", "reconnect", "stop action ordering", "toast dismissal integration", "bounded diagnostic integration"] : undefined });
document.body.append(output);
void fetch("/report", { method: "POST", body: output.textContent }).then(() => {
if (passed) location.replace("/tests/toast_lifecycle_fixture.html");
@@ -188,7 +189,20 @@
}
discoveryError = true;
await refreshDevices();
- check(picker().value === "phone-two" && connect.disabled && picker().selectedOptions[0].textContent.includes("Status unavailable") && document.querySelector("#device-status").textContent.includes("Mock discovery failed"), "Discovery failure did not preserve an unknown, blocked selection");
+ const status = document.querySelector("#device-status");
+ check(picker().value === "phone-two" && connect.disabled && picker().selectedOptions[0].textContent.includes("Status unavailable"), "Discovery failure did not preserve an unknown, blocked selection");
+ check(status.textContent.includes("ADB could not start") && status.textContent.length < 120 && !status.textContent.includes("startup log"), "Raw diagnostics leaked into setup status");
+ const diagnostics = document.querySelector("#device-error-details");
+ check(diagnostics && !diagnostics.open, "Technical details were expanded by default");
+ const closedHeight = diagnostics.getBoundingClientRect().height;
+ diagnostics.querySelector("summary").click();
+ await waitFor(() => diagnostics.open, "Technical details did not expand");
+ const detailText = diagnostics.querySelector("pre");
+ check(detailText.textContent.includes("ADB server didn't ACK") && detailText.textContent.includes("… [truncated]") && detailText.textContent.length <= 4096, "Diagnostics were lost or unbounded");
+ check(!diagnostics.querySelector("img") && detailText.textContent.includes("<img"), "Diagnostic text became markup");
+ check(detailText.getBoundingClientRect().height <= 161 && document.documentElement.scrollWidth <= innerWidth, "Expanded diagnostics broke setup layout");
+ diagnostics.querySelector("summary").click();
+ check(!diagnostics.open && diagnostics.getBoundingClientRect().height <= closedHeight + 1, "Collapsed diagnostics still occupied the screen");
discoveryError = false;
listedDevices = [...readyDevices].reverse();
await refreshDevices();