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

Let mounted toasts own and clean up their phase timers (#57)

Vishnu Srivatsavafb6713549631
diff --git a/src/App.tsx b/src/App.tsx
index 55d4c1e..fe38f96 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -5,6 +5,8 @@ import { formatBytes } from "./formatBytes";
import { sameScan } from "./scanView";
import type { ScanNode, ScanResponse, NodeDetail, DeleteResult } from "./scanView";
import { useScanView } from "./useScanView";
+import { ToastContainer } from "./ToastContainer";
+import type { Toast } from "./ToastContainer";
import "./App.css";
// ── Types ───────────────────────────────────────────────────────────────────
@@ -16,13 +18,6 @@ const scanPhaseLog = (r: ScanResponse): string | null => {
return `[SCAN] ${r.streamed ? "Stream timings (overlap): scan" : "Phases: traverse"} ${r.traverse_ms}ms · sort ${r.sort_ms}ms · serialize ${r.serialize_ms}ms · send ${r.send_ms}ms${kb}`;
};
-interface Toast {
- id: number;
- message: string;
- type: "error" | "success" | "info";
- exiting?: boolean;
-}
-
type AppPhase = "setup" | "connecting" | "scanning" | "result";
// ── Helpers ─────────────────────────────────────────────────────────────────
@@ -91,35 +86,6 @@ function Spinner({ size = 20, className = "" }: { size?: number; className?: str
let toastId = 0;
-function ToastContainer({ toasts, onDismiss }: { toasts: Toast[]; onDismiss: (id: number) => void }) {
- return (
- <div className="fixed top-4 right-4 z-50 flex flex-col gap-2 max-w-sm" id="toast-container">
- {toasts.map((t) => (
- <div
- key={t.id}
- className={`
- ${t.exiting ? "animate-toast-out" : "animate-toast-in"}
- flex items-start gap-3 px-4 py-3 rounded-lg border shadow-xl cursor-pointer
- ${t.type === "error"
- ? "bg-red-950/80 border-red-800/50 text-red-200"
- : t.type === "success"
- ? "bg-emerald-950/80 border-emerald-800/50 text-emerald-200"
- : "bg-zinc-800/80 border-zinc-700/50 text-zinc-200"
- }
- backdrop-blur-md
- `}
- onClick={() => onDismiss(t.id)}
- >
- <span className="mt-0.5 text-base">
- {t.type === "error" ? "✕" : t.type === "success" ? "✓" : "ℹ"}
- </span>
- <p className="text-sm leading-relaxed flex-1">{t.message}</p>
- </div>
- ))}
- </div>
- );
-}
-
// ── Terminal Log ────────────────────────────────────────────────────────────
function TerminalLog({ logs }: { logs: string[] }) {
@@ -615,7 +581,6 @@ function App() {
const [statusText, setStatusText] = useState("Initializing…");
const [toasts, setToasts] = useState<Toast[]>([]);
const [logs, setLogs] = useState<string[]>([]);
- const timerRefs = useRef<Map<number, ReturnType<typeof setTimeout>>>(new Map());
const addLog = useCallback((msg: string) => {
setLogs((prev) => [...prev, `[${new Date().toLocaleTimeString()}] ${msg}`]);
@@ -625,25 +590,16 @@ function App() {
const pushToast = useCallback((message: string, type: Toast["type"] = "error") => {
const id = ++toastId;
setToasts((prev) => [...prev, { id, message, type }]);
- const timer = setTimeout(() => {
- setToasts((prev) =>
- prev.map((t) => (t.id === id ? { ...t, exiting: true } : t))
- );
- setTimeout(() => setToasts((prev) => prev.filter((t) => t.id !== id)), 300);
- }, 5000);
- timerRefs.current.set(id, timer);
}, []);
const dismissToast = useCallback((id: number) => {
- const timer = timerRefs.current.get(id);
- if (timer) {
- clearTimeout(timer);
- timerRefs.current.delete(id);
- }
setToasts((prev) =>
- prev.map((t) => (t.id === id ? { ...t, exiting: true } : t))
+ prev.map((t) => (t.id === id && !t.exiting ? { ...t, exiting: true } : t))
);
- setTimeout(() => setToasts((prev) => prev.filter((t) => t.id !== id)), 300);
+ }, []);
+
+ const removeToast = useCallback((id: number) => {
+ setToasts((prev) => prev.filter((t) => t.id !== id));
}, []);
const requestScan = useCallback(async (path: string): Promise<ScanResponse> => {
@@ -835,14 +791,9 @@ function App() {
}
}, [confirmDelete, pushToast, addLog]);
- useEffect(() => {
- const timers = timerRefs.current;
- return () => { timers.forEach((t) => clearTimeout(t)); };
- }, []);
-
return (
<div className="h-screen flex flex-col bg-surface-0 overflow-hidden">
- <ToastContainer toasts={toasts} onDismiss={dismissToast} />
+ <ToastContainer toasts={toasts} onDismiss={dismissToast} onRemove={removeToast} />
<div className="flex-1 flex flex-col min-h-0">
{(phase === "setup" || phase === "connecting") && (
diff --git a/src/ToastContainer.tsx b/src/ToastContainer.tsx
new file mode 100644
index 0000000..920a611
--- /dev/null
+++ b/src/ToastContainer.tsx
@@ -0,0 +1,49 @@
+import { useEffect } from "react";
+
+export interface Toast {
+ id: number;
+ message: string;
+ type: "error" | "success" | "info";
+ exiting?: boolean;
+}
+
+export function ToastContainer({ toasts, onDismiss, onRemove }: { toasts: Toast[]; onDismiss: (id: number) => void; onRemove: (id: number) => void }) {
+ return (
+ <div className="fixed top-4 right-4 z-50 flex flex-col gap-2 max-w-sm" id="toast-container">
+ {toasts.map((toast) => <ToastItem key={toast.id} toast={toast} onDismiss={onDismiss} onRemove={onRemove} />)}
+ </div>
+ );
+}
+
+function ToastItem({ toast: t, onDismiss, onRemove }: { toast: Toast; onDismiss: (id: number) => void; onRemove: (id: number) => void }) {
+ // A mounted toast owns exactly one timer; phase changes replace it and
+ // unmount cancels it. Repeated dismissal cannot restart the exit deadline.
+ useEffect(() => {
+ const timer = setTimeout(() => {
+ if (t.exiting) onRemove(t.id); else onDismiss(t.id);
+ }, t.exiting ? 300 : 5000);
+ return () => clearTimeout(timer);
+ }, [t.id, t.exiting, onDismiss, onRemove]);
+
+ return (
+ <div
+ className={`
+ ${t.exiting ? "animate-toast-out" : "animate-toast-in"}
+ flex items-start gap-3 px-4 py-3 rounded-lg border shadow-xl cursor-pointer
+ ${t.type === "error"
+ ? "bg-red-950/80 border-red-800/50 text-red-200"
+ : t.type === "success"
+ ? "bg-emerald-950/80 border-emerald-800/50 text-emerald-200"
+ : "bg-zinc-800/80 border-zinc-700/50 text-zinc-200"
+ }
+ backdrop-blur-md
+ `}
+ onClick={() => onDismiss(t.id)}
+ >
+ <span className="mt-0.5 text-base">
+ {t.type === "error" ? "✕" : t.type === "success" ? "✓" : "ℹ"}
+ </span>
+ <p className="text-sm leading-relaxed flex-1">{t.message}</p>
+ </div>
+ );
+}
diff --git a/tests/check_scan_ui.py b/tests/check_scan_ui.py
index f19361e..0d4cd40 100644
--- a/tests/check_scan_ui.py
+++ b/tests/check_scan_ui.py
@@ -1,5 +1,5 @@
#!/usr/bin/env python3
-"""Check the built UI in headless Chromium with mocked IPC, never ADB/Tauri.
+"""Check the built UI and toast lifecycle in headless Chromium, never ADB/Tauri.
Run npm run build first. Uses installed Chrome/Chromium, no added packages.
"""
@@ -58,6 +58,15 @@ with tempfile.TemporaryDirectory(prefix='socketsweep-ui-test-') as directory:
index = work / 'site/index.html'
html = index.read_text().replace('<head>', '<head><script src="/fixture.js"></script>')
index.write_text(html)
+ # Compile the actual toast component 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' },
+ }});
+ ''', 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:
@@ -71,10 +80,11 @@ with tempfile.TemporaryDirectory(prefix='socketsweep-ui-test-') as directory:
f'--user-data-dir={work / "profile"}', f'http://127.0.0.1:{server.server_port}'],
stdout=log, stderr=log, start_new_session=True)
try:
- value = reports.get(timeout=40)
- print(json.dumps(value, indent=2))
- if not value['passed']:
- sys.exit(1)
+ for expected in ('scan-ui', 'toast-lifecycle'):
+ 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:])
diff --git a/tests/scan_ui_fixture.js b/tests/scan_ui_fixture.js
index 58e1fc4..bab754c 100644
--- a/tests/scan_ui_fixture.js
+++ b/tests/scan_ui_fixture.js
@@ -109,9 +109,11 @@
const report = (passed, error) => {
const output = document.createElement("pre");
output.id = "scan-test-report";
- output.textContent = JSON.stringify({ passed, error, ipc_calls: calls.length, checks: passed ? ["offline fonts under CSP", "setup alignment", "result fonts", "file label semantics", "complete paging", "late zoom", "Other tile", "stale confirmation", "ID-only deletion", "revision refresh", "partial failure", "read-only", "acknowledged shutdown", "unconfirmed shutdown", "reconnect", "stop action ordering"] : undefined });
+ 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", "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"] : undefined });
document.body.append(output);
- void fetch("/report", { method: "POST", body: output.textContent });
+ void fetch("/report", { method: "POST", body: output.textContent }).then(() => {
+ if (passed) location.replace("/tests/toast_lifecycle_fixture.html");
+ });
};
void (async () => {
await waitFor(() => document.querySelector("#btn-connect"), "Setup did not render");
@@ -219,6 +221,10 @@
check(rows().length === 0, "Unconfirmed stop retained scan results");
}
check(!document.body.textContent.includes("Daemon successfully shut down.") && !document.body.textContent.includes("Daemon was already stopped."), "Unsupported shutdown claim survived");
+ const toast = document.querySelector("#toast-container > div:last-child");
+ check(toast, "No toast for dismissal integration");
+ toast.click();
+ await waitFor(() => !toast.isConnected, "App did not remove the dismissed toast");
check(violations.length === 0, `CSP blocked resources: ${violations.join(", ")}`);
const fonts = performance.getEntriesByType("resource").filter(entry => entry.name.includes(".woff2"));
check(fonts.length === 13 && fonts.every(entry => new URL(entry.name).origin === location.origin), "Fonts are missing or fetched off-site");
diff --git a/tests/toast_lifecycle_fixture.html b/tests/toast_lifecycle_fixture.html
new file mode 100644
index 0000000..32ce547
--- /dev/null
+++ b/tests/toast_lifecycle_fixture.html
@@ -0,0 +1,8 @@
+<!doctype html>
+<html lang="en">
+ <head><meta charset="UTF-8" /><title>Toast lifecycle fixture</title></head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/tests/toast_lifecycle_fixture.jsx"></script>
+ </body>
+</html>
diff --git a/tests/toast_lifecycle_fixture.jsx b/tests/toast_lifecycle_fixture.jsx
new file mode 100644
index 0000000..b89c327
--- /dev/null
+++ b/tests/toast_lifecycle_fixture.jsx
@@ -0,0 +1,133 @@
+// Production React and toast component, with controlled browser timers. No IPC.
+import { StrictMode } from "react";
+import { createRoot } from "react-dom/client";
+import { ToastContainer } from "../src/ToastContainer";
+import "../src/App.css";
+
+const nativeTimeout = window.setTimeout.bind(window);
+const nativeClear = window.clearTimeout.bind(window);
+const timers = new Map();
+let now = 0;
+let nextId = -1;
+window.setTimeout = (callback, delay, ...args) => {
+ if (delay !== 5000 && delay !== 300) return nativeTimeout(callback, delay, ...args);
+ const id = nextId--;
+ timers.set(id, { at: now + delay, callback: () => callback(...args) });
+ return id;
+};
+window.clearTimeout = id => { if (!timers.delete(id)) nativeClear(id); };
+const advance = milliseconds => {
+ const end = now + milliseconds;
+ for (;;) {
+ const next = [...timers].filter(([, timer]) => timer.at <= end).sort((a, b) => a[1].at - b[1].at)[0];
+ if (!next) break;
+ timers.delete(next[0]);
+ now = next[1].at;
+ next[1].callback();
+ }
+ now = end;
+};
+const check = (condition, message) => { if (!condition) throw Error(message); };
+const pause = () => new Promise(resolve => nativeTimeout(resolve, 20));
+const waitFor = async (predicate, message) => {
+ const deadline = Date.now() + 3000;
+ while (!predicate()) {
+ if (Date.now() > deadline) throw Error(message);
+ await pause();
+ }
+};
+const root = createRoot(document.getElementById("root"));
+let toasts = [];
+const exits = [];
+const removals = [];
+const dismiss = id => {
+ exits.push(id);
+ toasts = toasts.map(toast => toast.id === id && !toast.exiting ? { ...toast, exiting: true } : toast);
+ render();
+};
+const remove = id => {
+ removals.push(id);
+ toasts = toasts.filter(toast => toast.id !== id);
+ render();
+};
+const render = () => root.render(<StrictMode><ToastContainer toasts={toasts} onDismiss={dismiss} onRemove={remove} /></StrictMode>);
+const item = message => [...document.querySelectorAll("#toast-container > div")].find(element => element.textContent.includes(message));
+const add = (...ids) => {
+ toasts = ids.map(id => ({ id, message: `Toast ${id}`, type: id % 2 ? "info" : "error" }));
+ render();
+};
+const report = async (passed, error) => {
+ root.unmount();
+ window.setTimeout = nativeTimeout;
+ window.clearTimeout = nativeClear;
+ await fetch("/report", { method: "POST", body: JSON.stringify({ fixture: "toast-lifecycle", passed, error,
+ checks: passed ? ["natural expiry", "stable lifetime across rerenders", "early dismissal", "repeated dismissal", "dismissal during exit", "independent toasts", "unmount before expiry", "unmount during exit", "repeated notifications release timers"] : undefined }) });
+};
+
+void (async () => {
+ add(1);
+ await waitFor(() => item("Toast 1") && timers.size === 1, "Initial toast timer missing");
+ advance(4000);
+ toasts = toasts.map(toast => ({ ...toast, message: "Toast 1 updated" }));
+ render();
+ await waitFor(() => item("Toast 1 updated"), "Rerender missing");
+ check([...timers.values()][0].at === 5000, "Rerender restarted lifetime");
+ advance(999);
+ check(!item("Toast 1").classList.contains("animate-toast-out"), "Toast expired before five seconds");
+ advance(1);
+ await waitFor(() => item("Toast 1").classList.contains("animate-toast-out") && timers.size === 1, "Natural expiry did not enter exit phase");
+ check(getComputedStyle(item("Toast 1")).animationName === "toast-out", "Exit animation missing");
+ advance(100);
+ item("Toast 1").click();
+ item("Toast 1").click();
+ await pause();
+ check(timers.size === 1 && [...timers.values()][0].at === 5300, "Dismissal during exit restarted or duplicated removal");
+ advance(199);
+ check(item("Toast 1"), "Exit was removed before 300 ms");
+ advance(1);
+ await waitFor(() => !item("Toast 1") && timers.size === 0, "Natural removal retained toast/timer");
+ check(removals.filter(id => id === 1).length === 1, "Duplicate removal");
+
+ add(2, 3);
+ await waitFor(() => item("Toast 2") && item("Toast 3") && timers.size === 2, "Independent timers missing");
+ advance(100);
+ item("Toast 2").click();
+ await waitFor(() => item("Toast 2").classList.contains("animate-toast-out") && timers.size === 2, "Early dismissal failed");
+ advance(100);
+ item("Toast 2").click();
+ await pause();
+ advance(200);
+ await waitFor(() => !item("Toast 2") && timers.size === 1, "Repeated dismissal delayed removal");
+ check(item("Toast 3") && !item("Toast 3").classList.contains("animate-toast-out"), "Dismissal affected another toast");
+ advance(4599);
+ check(item("Toast 3"), "Other toast expired early");
+ advance(1);
+ await waitFor(() => item("Toast 3").classList.contains("animate-toast-out") && timers.size === 1, "Other toast lifetime changed");
+ advance(300);
+ await waitFor(() => !item("Toast 3") && timers.size === 0, "Other toast cleanup failed");
+
+ for (const phase of ["active", "exiting"]) {
+ add(4);
+ await waitFor(() => item("Toast 4") && timers.size === 1, "Unmount fixture did not mount");
+ if (phase === "exiting") {
+ advance(5000);
+ await waitFor(() => item("Toast 4").classList.contains("animate-toast-out") && timers.size === 1, "Unmount exit phase missing");
+ }
+ root.render(null);
+ await waitFor(() => !item("Toast 4") && timers.size === 0, "Unmount retained timer");
+ const callbacks = exits.length + removals.length;
+ advance(6000);
+ await pause();
+ check(exits.length + removals.length === callbacks, "Callback fired after unmount");
+ }
+
+ for (let id = 10; id < 30; id++) {
+ add(id);
+ await waitFor(() => item(`Toast ${id}`) && timers.size === 1, "Repeated notification did not mount");
+ advance(5000);
+ await waitFor(() => item(`Toast ${id}`).classList.contains("animate-toast-out") && timers.size === 1, "Repeated notification did not exit");
+ advance(300);
+ await waitFor(() => !item(`Toast ${id}`) && timers.size === 0, "Repeated notification retained resources");
+ }
+ await report(true);
+})().catch(error => report(false, error.stack ?? String(error)));