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 actionable headless browser failure diagnostics (#80)

Vishnu Srivatsava9260f385851e
diff --git a/docs/scan-store.md b/docs/scan-store.md
index 978241d..1605900 100644
--- a/docs/scan-store.md
+++ b/docs/scan-store.md
@@ -74,6 +74,11 @@ deletion, revision refresh, partial-error recovery and read-only controls. It
never launches Tauri or contacts ADB. Linux CI runs it after the desktop build;
all three desktop targets run Rust and Node tests.
+The UI harness logs its selected browser/version. Missing-report failures include
+the expected fixture, browser exit status, elapsed time, first/latest HTTP
+requests and a bounded browser-log tail. An exited browser fails promptly;
+the existing 40-second report deadline and fixture assertions remain in force.
+
Rust fixtures compare ordering, paths, parents and totals against the previous
recursive representation, including repeated file/directory deletions,
placeholders, a 64-level path, stale references and concurrent reads. Host daemon
diff --git a/tests/check_scan_ui.py b/tests/check_scan_ui.py
index 25b2395..d02dd8b 100644
--- a/tests/check_scan_ui.py
+++ b/tests/check_scan_ui.py
@@ -15,101 +15,164 @@ import subprocess
import sys
import tempfile
import threading
+from time import monotonic
-if sys.platform not in ("darwin", "linux"):
- sys.exit("Headless UI harness supports macOS and Linux")
-
-REPO = Path(__file__).resolve().parents[1]
-chrome = (sys.argv[1] if len(sys.argv) > 1 else
- shutil.which('chromium') or shutil.which('google-chrome') or
- '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome')
-if not Path(chrome).is_file():
- sys.exit('Chrome/Chromium missing; pass its executable as the first argument')
-reports = Queue()
-# Keep the production resource policy. Only the fixture's local report endpoint
-# needs an extra connect-src origin; native IPC remains mocked.
-csp = json.loads((REPO / 'src-tauri/tauri.conf.json').read_text())['app']['security']['csp']
-csp = csp.replace('connect-src ', "connect-src 'self' ")
-
-class Handler(SimpleHTTPRequestHandler):
- def end_headers(self):
- self.send_header('Content-Security-Policy', csp)
- super().end_headers()
- def log_message(self, *args):
- pass
- def do_POST(self):
- length = int(self.headers.get('Content-Length', '0'))
- if self.path != '/report' or not 0 < length < 64 * 1024:
- self.send_error(400)
- return
- value = json.loads(self.rfile.read(length))
- self.send_response(200)
- self.end_headers()
- reports.put(value)
-
-with tempfile.TemporaryDirectory(prefix='socketsweep-ui-test-') as directory:
- work = Path(directory)
- shutil.copytree(REPO / 'dist', work / 'site')
- for name in ('inter-OFL.txt', 'jetbrainsmono-OFL.txt'):
- source = REPO / 'public/font-licenses' / name
- bundled = work / 'site/font-licenses' / name
- assert bundled.read_bytes() == source.read_bytes(), 'Bundled font license differs'
- shutil.copy(REPO / 'tests/scan_ui_fixture.js', work / 'site/fixture.js')
- index = work / 'site/index.html'
- html = index.read_text().replace('<head>', '<head><script src="/fixture.js"></script>')
- index.write_text(html)
- # Compile the actual UI components with the installed Vite/React tooling.
- # The isolated fixture stays in this temporary site, never the shipped dist.
- subprocess.run(['node', '--input-type=module', '-e', '''
- import { build } from 'vite';
- await build({ logLevel: 'error', build: {
- outDir: process.argv[1], emptyOutDir: false,
- 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()
+
+def browser_version(chrome):
try:
- with (work / 'chrome.log').open('w+') as log:
- process = subprocess.Popen([chrome, '--headless', '--disable-gpu', '--no-first-run',
- '--use-mock-keychain', '--password-store=basic', '--enable-logging=stderr',
- '--disable-background-networking', '--disable-extensions',
- '--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}/tests/device_discovery_fixture.html'],
- stdout=log, stderr=log, start_new_session=True)
- try:
- 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']:
- sys.exit(1)
- except Empty:
- log.seek(0)
- sys.exit('Headless browser timed out: ' + log.read()[-3000:])
- finally:
- try:
- os.killpg(process.pid, signal.SIGTERM)
- except ProcessLookupError:
- pass
+ result = subprocess.run([chrome, '--version'], capture_output=True, text=True,
+ encoding='utf-8', errors='replace', timeout=5)
+ return f"exit {result.returncode}: {(result.stdout + result.stderr).strip()}"[:512]
+ except (OSError, subprocess.TimeoutExpired) as error:
+ return f"Version unavailable: {error}"[:512]
+
+
+def wait_for_report(reports, process, expected, timeout=40):
+ deadline = monotonic() + timeout
+ while True:
+ try:
+ # Consume an already queued report even if the browser has exited.
+ return reports.get(timeout=min(0.1, max(0, deadline - monotonic())))
+ except Empty:
+ status = process.poll()
+ if status is not None:
+ raise RuntimeError(f"Browser exited with status {status} while waiting for {expected}")
+ if monotonic() >= deadline:
+ raise TimeoutError(f"Headless browser timed out waiting for {expected}")
+
+
+def log_tail(log):
+ log.seek(0, os.SEEK_END)
+ log.seek(max(0, log.tell() - 3000))
+ return log.read(3000).decode('utf-8', errors='replace')
+
+
+class HttpActivity:
+ def __init__(self):
+ self.started = monotonic()
+ self.lock = threading.Lock()
+ self.count = 0
+ self.first = None
+ self.latest = None
+
+ def record(self, method, path, status):
+ event = {"method": method, "path": path.split('?', 1)[0][:256], "status": status}
+ with self.lock:
+ event["elapsed_ms"] = round((monotonic() - self.started) * 1000)
+ self.count += 1
+ if self.first is None:
+ self.first = event
+ self.latest = event
+
+ def snapshot(self):
+ with self.lock:
+ return {"elapsed_ms": round((monotonic() - self.started) * 1000),
+ "http_requests": self.count, "first_request": self.first, "latest_request": self.latest}
+
+
+def main():
+ if sys.platform not in ("darwin", "linux"):
+ sys.exit("Headless UI harness supports macOS and Linux")
+
+ REPO = Path(__file__).resolve().parents[1]
+ chrome = (sys.argv[1] if len(sys.argv) > 1 else
+ shutil.which('chromium') or shutil.which('google-chrome') or
+ '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome')
+ if not Path(chrome).is_file():
+ sys.exit('Chrome/Chromium missing; pass its executable as the first argument')
+ reports = Queue()
+ print(json.dumps({"browser": chrome, "version": browser_version(chrome)}), flush=True)
+ # Keep the production resource policy. Only the fixture's local report endpoint
+ # needs an extra connect-src origin; native IPC remains mocked.
+ csp = json.loads((REPO / 'src-tauri/tauri.conf.json').read_text())['app']['security']['csp']
+ csp = csp.replace('connect-src ', "connect-src 'self' ")
+
+ class Handler(SimpleHTTPRequestHandler):
+ def end_headers(self):
+ self.send_header('Content-Security-Policy', csp)
+ super().end_headers()
+ def log_message(self, *args):
+ pass
+ def log_request(self, code="-", size="-"):
+ activity.record(self.command, self.path, code)
+ def do_POST(self):
+ length = int(self.headers.get('Content-Length', '0'))
+ if self.path != '/report' or not 0 < length < 64 * 1024:
+ self.send_error(400)
+ return
+ value = json.loads(self.rfile.read(length))
+ self.send_response(200)
+ self.end_headers()
+ reports.put(value)
+
+ with tempfile.TemporaryDirectory(prefix='socketsweep-ui-test-') as directory:
+ work = Path(directory)
+ shutil.copytree(REPO / 'dist', work / 'site')
+ for name in ('inter-OFL.txt', 'jetbrainsmono-OFL.txt'):
+ source = REPO / 'public/font-licenses' / name
+ bundled = work / 'site/font-licenses' / name
+ assert bundled.read_bytes() == source.read_bytes(), 'Bundled font license differs'
+ shutil.copy(REPO / 'tests/scan_ui_fixture.js', work / 'site/fixture.js')
+ index = work / 'site/index.html'
+ html = index.read_text().replace('<head>', '<head><script src="/fixture.js"></script>')
+ index.write_text(html)
+ # Compile the actual UI components with the installed Vite/React tooling.
+ # The isolated fixture stays in this temporary site, never the shipped dist.
+ subprocess.run(['node', '--input-type=module', '-e', '''
+ import { build } from 'vite';
+ await build({ logLevel: 'error', build: {
+ outDir: process.argv[1], emptyOutDir: false,
+ 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)
+ activity = HttpActivity()
+ server = ThreadingHTTPServer(('127.0.0.1', 0), partial(Handler, directory=str(work / 'site')))
+ threading.Thread(target=server.serve_forever, daemon=True).start()
+ try:
+ with (work / 'chrome.log').open('w+b') as log:
+ process = subprocess.Popen([chrome, '--headless', '--disable-gpu', '--no-first-run',
+ '--use-mock-keychain', '--password-store=basic', '--enable-logging=stderr',
+ '--disable-background-networking', '--disable-extensions',
+ '--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}/tests/device_discovery_fixture.html'],
+ stdout=log, stderr=log, start_new_session=True)
try:
- process.wait(timeout=5)
- except subprocess.TimeoutExpired:
+ for expected in ('device-discovery', 'scan-ui', 'toast-lifecycle', 'log-history'):
+ value = wait_for_report(reports, process, expected)
+ print(json.dumps(value, indent=2), flush=True)
+ if value.get('fixture') != expected or not value['passed']:
+ sys.exit(1)
+ except (TimeoutError, RuntimeError) as error:
+ context = {"waiting_for": expected, "browser_status": process.poll(), **activity.snapshot()}
+ sys.exit(f"{error}\n{json.dumps(context)}\nBrowser log tail:\n{log_tail(log)}")
+ finally:
try:
- os.killpg(process.pid, signal.SIGKILL)
+ os.killpg(process.pid, signal.SIGTERM)
except ProcessLookupError:
pass
- process.wait()
- finally:
- server.shutdown()
- server.server_close()
+ try:
+ process.wait(timeout=5)
+ except subprocess.TimeoutExpired:
+ try:
+ os.killpg(process.pid, signal.SIGKILL)
+ except ProcessLookupError:
+ pass
+ process.wait()
+ finally:
+ server.shutdown()
+ server.server_close()
+
+
+if __name__ == "__main__":
+ main()
diff --git a/tests/test_ui_browser_diagnostics.py b/tests/test_ui_browser_diagnostics.py
new file mode 100644
index 0000000..11b867e
--- /dev/null
+++ b/tests/test_ui_browser_diagnostics.py
@@ -0,0 +1,77 @@
+"""UI harness diagnostics without opening a browser, Tauri or ADB."""
+import io
+from queue import Empty, Queue
+import subprocess
+import unittest
+from unittest.mock import Mock, patch
+
+import check_scan_ui as harness
+
+
+class UiBrowserDiagnosticsTests(unittest.TestCase):
+ def test_queued_report_wins_over_a_browser_exit(self):
+ reports = Queue()
+ value = {"fixture": "last", "passed": True}
+ reports.put(value)
+ process = Mock()
+ process.poll.return_value = 0
+ self.assertEqual(harness.wait_for_report(reports, process, "last"), value)
+ process.poll.assert_not_called()
+
+ def test_browser_exit_is_reported_without_waiting_for_full_deadline(self):
+ for status in (0, 7, -15):
+ with self.subTest(status=status):
+ reports = Mock()
+ reports.get.side_effect = Empty
+ process = Mock()
+ process.poll.return_value = status
+ with self.assertRaisesRegex(RuntimeError, f"status {status}.*device-discovery"):
+ harness.wait_for_report(reports, process, "device-discovery")
+ self.assertEqual(reports.get.call_count, 1)
+ self.assertLessEqual(reports.get.call_args.kwargs["timeout"], 0.1)
+
+ def test_live_browser_times_out_with_expected_fixture(self):
+ process = Mock()
+ process.poll.return_value = None
+ with self.assertRaisesRegex(TimeoutError, "waiting for scan-ui"):
+ harness.wait_for_report(Queue(), process, "scan-ui", timeout=0)
+
+ def test_empty_queue_does_not_reset_the_deadline(self):
+ process = Mock()
+ process.poll.return_value = None
+ reports = Mock()
+ reports.get.side_effect = Empty
+ with patch.object(harness, "monotonic", side_effect=[0, 1, 39, 39.5, 40]):
+ with self.assertRaises(TimeoutError):
+ harness.wait_for_report(reports, process, "scan-ui")
+ self.assertEqual(reports.get.call_count, 2)
+
+ def test_http_activity_keeps_only_first_and_latest_bounded_paths(self):
+ activity = harness.HttpActivity()
+ self.assertEqual(activity.snapshot()["http_requests"], 0)
+ self.assertIsNone(activity.snapshot()["first_request"])
+ activity.record("GET", "/fixture.html?omit-query", 200)
+ for index in range(1000):
+ activity.record("GET", "/" + str(index) + "x" * 1000, 404)
+ state = activity.snapshot()
+ self.assertEqual(state["http_requests"], 1001)
+ self.assertEqual(state["first_request"]["path"], "/fixture.html")
+ self.assertTrue(state["latest_request"]["path"].startswith("/999"))
+ self.assertEqual(len(state["latest_request"]["path"]), 256)
+ self.assertEqual(state["latest_request"]["status"], 404)
+ self.assertGreaterEqual(state["elapsed_ms"], 0)
+
+ def test_log_tail_is_byte_bounded_and_tolerates_invalid_utf8(self):
+ stream = io.BytesIO(b"not retained" * 1000 + b"\xff" * 3000)
+ self.assertEqual(harness.log_tail(stream), "\ufffd" * 3000)
+ self.assertEqual(harness.log_tail(io.BytesIO(b"short")), "short")
+
+ def test_browser_version_probe_is_bounded_and_failure_is_diagnostic(self):
+ with patch.object(harness.subprocess, "run") as run:
+ run.return_value = Mock(returncode=0, stdout="Browser fixture" + "x" * 1000, stderr="")
+ self.assertEqual(len(harness.browser_version("chosen-browser")), 512)
+ self.assertEqual(run.call_args.args[0], ["chosen-browser", "--version"])
+ self.assertEqual(run.call_args.kwargs["timeout"], 5)
+ for error in (OSError("not executable"), subprocess.TimeoutExpired("browser", 5)):
+ run.side_effect = error
+ self.assertIn("Version unavailable", harness.browser_version("chosen-browser"))