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 retained diagnostic text and log rows (#58)

Vishnu Srivatsava983a5a2a0d54
diff --git a/docs/log-history.md b/docs/log-history.md
new file mode 100644
index 0000000..3083d7f
--- /dev/null
+++ b/docs/log-history.md
@@ -0,0 +1,65 @@
+# Diagnostic log retention
+
+The log shows the newest entries from the current app session, including across
+rescans and reconnects. It is not persisted or a complete session archive.
+`src/logHistory.ts` enforces these fixed limits at the log append boundary:
+
+- At most 500 retained entries and rendered log rows.
+- At most 131,072 UTF-16 code units of retained text (256 KiB at two bytes per unit).
+- At most 4,096 UTF-16 code units per entry, including `… [truncated]` when needed.
+
+Oldest entries are evicted until both count and text limits hold. Timestamps and
+chronological order are preserved. A notice outside the scrolling list reports
+how many older entries were discarded. Long-message truncation preserves the
+beginning and avoids cutting a surrogate pair. Only diagnostic display text is
+limited; scan data, exact paths, confirmation details and command arguments do
+not pass through this formatter.
+
+Bounded text is materialized with a JSON string round-trip so a slice/rope does
+not keep a large source string alive. History updates are immutable, and retained
+row keys follow their original sequence positions when oldest entries are evicted.
+The text budget does not claim a hard JavaScript heap, DOM or process-memory limit;
+object overhead, transient inputs and React state/render snapshots also consume memory.
+
+## Verification and measurements
+
+`npm test` checks chronological retention, both limits, multi-entry eviction,
+Unicode/control text, immutable updates, diagnostic truncation and 10,000 mixed
+messages with exact discard accounting. `npm run build` checks TypeScript and the
+production bundle. After building, `python3 tests/check_scan_ui.py` exercises the
+built app with oversized mocked ADB diagnostics, retains the existing safe deletion
+and session checks, and tests the actual log model/component using synthetic replays.
+The isolated browser fixtures are compiled only into a temporary test site.
+
+Host append/retention comparison:
+
+```sh
+node tests/benchmark_log_history.mjs
+```
+
+On 2026-10-14, macOS arm64 / Node 26.7.0, three isolated runs per version with
+20,000 synthetic path messages produced these medians:
+
+| Measurement | Former unbounded append | Bounded append |
+| --- | ---: | ---: |
+| Append loop | 311.970 ms | 28.193 ms |
+| Retained entries | 20,000 | 500 |
+| Retained text, two bytes per UTF-16 unit | 6,217,780 bytes | 156,000 bytes |
+| Sampled heap growth after explicit GC | 5,182,280 bytes | 167,368 bytes |
+
+The former loop uses the previous `[...entries, message]` operation. Both receive
+the same generated messages; timestamp formatting is outside the measured loop.
+Heap deltas depend on V8 and GC and do not describe total application memory.
+
+A single local headless Chromium replay at 1280×861 CSS pixels / 1× measured
+1,279.9 ms to mount/layout 20,000 rows versus 39.4 ms for 500 rows. This uses the
+same current log component with unbounded and bounded histories, separated by
+unmount; it is not a complete old/new-app benchmark. Timings include commit polling,
+layout and two animation frames, are hardware-dependent, and are not CI thresholds.
+A long-message replay retained 33 rows and 254,212 bytes after adding fresh error/
+shutdown diagnostics; its discard notice remained visible while scrolling.
+
+These are synthetic Node/Chromium checks, not native WebView, phone or scan-speed
+measurements. Native verification uses `npm run tauri dev`; no daemon rebuild is
+needed. Generate repeated operations and confirm newest diagnostics remain visible
+with clear notices whenever older or oversized text is omitted.
diff --git a/package.json b/package.json
index 451a89f..25d0bea 100644
--- a/package.json
+++ b/package.json
@@ -7,7 +7,7 @@
"scripts": {
"dev": "vite",
"build": "tsc && vite build",
- "test": "node --test tests/format_bytes.test.mjs tests/scan_view.test.mjs",
+ "test": "node --test tests/format_bytes.test.mjs tests/scan_view.test.mjs tests/log_history.test.mjs",
"preview": "vite preview",
"tauri": "tauri"
},
diff --git a/src/App.tsx b/src/App.tsx
index fe38f96..88d7702 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -7,6 +7,8 @@ import type { ScanNode, ScanResponse, NodeDetail, DeleteResult } from "./scanVie
import { useScanView } from "./useScanView";
import { ToastContainer } from "./ToastContainer";
import type { Toast } from "./ToastContainer";
+import { TerminalLog } from "./TerminalLog";
+import { appendLog, emptyLogHistory } from "./logHistory";
import "./App.css";
// ── Types ───────────────────────────────────────────────────────────────────
@@ -86,30 +88,6 @@ function Spinner({ size = 20, className = "" }: { size?: number; className?: str
let toastId = 0;
-// ── Terminal Log ────────────────────────────────────────────────────────────
-
-function TerminalLog({ logs }: { logs: string[] }) {
- const endRef = useRef<HTMLDivElement>(null);
-
- useEffect(() => {
- endRef.current?.scrollIntoView({ behavior: "smooth" });
- }, [logs]);
-
- if (logs.length === 0) return null;
-
- return (
- <div className="h-32 border-t border-zinc-800 bg-zinc-950 px-4 py-2 font-mono text-[11px] text-zinc-400 overflow-y-auto">
- {logs.map((log, i) => (
- <div key={i} className="mb-0.5 break-all">
- <span className="text-accent-500 mr-2">❯</span>
- {log}
- </div>
- ))}
- <div ref={endRef} />
- </div>
- );
-}
-
// ── Setup Screen ────────────────────────────────────────────────────────────
function SetupScreen({ onConnect, loading, rootMode, onRootModeChange, rootPath, onRootPathChange }: {
@@ -580,10 +558,11 @@ function App() {
const activeScan = useRef<string | null>(null);
const [statusText, setStatusText] = useState("Initializing…");
const [toasts, setToasts] = useState<Toast[]>([]);
- const [logs, setLogs] = useState<string[]>([]);
+ const [logs, setLogs] = useState(emptyLogHistory);
const addLog = useCallback((msg: string) => {
- setLogs((prev) => [...prev, `[${new Date().toLocaleTimeString()}] ${msg}`]);
+ const entry = `[${new Date().toLocaleTimeString()}] ${msg}`;
+ setLogs((prev) => appendLog(prev, entry));
}, []);
// ── Toast helpers ───────────────────────────────────────────────────────
@@ -819,7 +798,7 @@ function App() {
)}
</div>
- <TerminalLog logs={logs} />
+ <TerminalLog history={logs} />
{/* Custom Confirm Modal */}
{confirmDelete && (
diff --git a/src/TerminalLog.tsx b/src/TerminalLog.tsx
new file mode 100644
index 0000000..0efe714
--- /dev/null
+++ b/src/TerminalLog.tsx
@@ -0,0 +1,32 @@
+import { useEffect, useRef } from "react";
+import type { LogHistory } from "./logHistory";
+
+// ── Terminal Log ────────────────────────────────────────────────────────────
+
+export function TerminalLog({ history }: { history: LogHistory }) {
+ const endRef = useRef<HTMLDivElement>(null);
+
+ useEffect(() => {
+ endRef.current?.scrollIntoView({ behavior: "smooth" });
+ }, [history]);
+
+ if (history.entries.length === 0) return null;
+
+ return (
+ <section aria-label="Diagnostic log" id="terminal-log"
+ className="h-32 shrink-0 border-t border-zinc-800 bg-zinc-950 font-mono text-[11px] text-zinc-400 flex flex-col">
+ {history.discarded > 0 && <p id="log-retention-notice" className="m-0 px-4 pt-1 text-zinc-500 shrink-0">
+ Showing recent logs · {history.discarded.toLocaleString("en-US")} older {history.discarded === 1 ? "entry" : "entries"} discarded.
+ </p>}
+ <div className="flex-1 min-h-0 overflow-y-auto px-4 py-2">
+ {history.entries.map((log, i) => (
+ <div key={history.discarded + i} className="log-entry mb-0.5 break-all">
+ <span className="text-accent-500 mr-2">❯</span>
+ {log}
+ </div>
+ ))}
+ <div ref={endRef} />
+ </div>
+ </section>
+ );
+}
diff --git a/src/logHistory.ts b/src/logHistory.ts
new file mode 100644
index 0000000..bcbdc14
--- /dev/null
+++ b/src/logHistory.ts
@@ -0,0 +1,42 @@
+// Limits apply to diagnostic display text, never paths or command arguments.
+export const MAX_LOG_ENTRIES = 500;
+export const MAX_LOG_TEXT_UNITS = 128 * 1024; // 256 KiB using two bytes per UTF-16 unit.
+export const MAX_LOG_ENTRY_UNITS = 4096;
+const TRUNCATION_MARKER = "… [truncated]";
+
+export interface LogHistory {
+ entries: readonly string[];
+ textUnits: number;
+ discarded: number;
+}
+
+export function emptyLogHistory(): LogHistory {
+ return { entries: [], textUnits: 0, discarded: 0 };
+}
+
+function boundedEntry(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.
+ const last = message.charCodeAt(end - 1);
+ if (last >= 0xd800 && last <= 0xdbff) end--;
+ message = message.slice(0, end) + TRUNCATION_MARKER;
+ }
+ // Materialize bounded text: a substring/rope can otherwise retain a much
+ // larger source string. JSON round-tripping preserves UTF-16 code units.
+ return JSON.parse(JSON.stringify(message)) as string;
+}
+
+export function appendLog(history: LogHistory, message: string): LogHistory {
+ const entry = boundedEntry(message);
+ let textUnits = history.textUnits + entry.length;
+ let remove = 0;
+ while (history.entries.length - remove + 1 > MAX_LOG_ENTRIES || textUnits > MAX_LOG_TEXT_UNITS) {
+ textUnits -= history.entries[remove++].length;
+ }
+ return {
+ entries: [...history.entries.slice(remove), entry],
+ textUnits,
+ discarded: history.discarded + remove,
+ };
+}
diff --git a/tests/benchmark_log_history.mjs b/tests/benchmark_log_history.mjs
new file mode 100644
index 0000000..7da2fbc
--- /dev/null
+++ b/tests/benchmark_log_history.mjs
@@ -0,0 +1,41 @@
+// Host-only append/retention measurement, not native UI or daemon performance.
+import { spawnSync } from "node:child_process";
+import { readFile } from "node:fs/promises";
+import { fileURLToPath } from "node:url";
+import ts from "typescript";
+
+const count = 20000;
+if (process.argv[2] !== "--worker") {
+ const samples = {};
+ for (const mode of ["legacy", "bounded"]) {
+ samples[mode] = [];
+ for (let run = 0; run < 3; run++) {
+ const child = spawnSync(process.execPath, ["--expose-gc", fileURLToPath(import.meta.url), "--worker", mode], { encoding: "utf8" });
+ if (child.status !== 0) throw Error(child.stderr);
+ samples[mode].push(JSON.parse(child.stdout));
+ }
+ }
+ const median = values => values.sort((a, b) => a - b)[1];
+ console.log(JSON.stringify({ count, node: process.version, platform: process.platform, results:
+ Object.fromEntries(Object.entries(samples).map(([mode, runs]) => [mode,
+ Object.fromEntries(Object.keys(runs[0]).map(key => [key, median(runs.map(run => run[key]))]))])) }, null, 2));
+} else {
+ const source = await readFile(new URL("../src/logHistory.ts", import.meta.url), "utf8");
+ const { outputText } = ts.transpileModule(source, {
+ compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext },
+ });
+ const { appendLog, emptyLogHistory } = await import(`data:text/javascript;base64,${Buffer.from(outputText).toString("base64")}`);
+ let history = emptyLogHistory();
+ global.gc();
+ const before = process.memoryUsage().heapUsed;
+ const start = performance.now();
+ for (let i = 0; i < count; i++) {
+ const message = `[12:34:56] [SCAN] /sdcard/${i}/` + "synthetic-path-".repeat(8) + "文件😀";
+ history = process.argv[3] === "legacy" ? { entries: [...history.entries, message] } : appendLog(history, message);
+ }
+ const append_ms = performance.now() - start;
+ global.gc();
+ const retained_heap_delta = process.memoryUsage().heapUsed - before;
+ console.log(JSON.stringify({ append_ms, retained_heap_delta, entries: history.entries.length,
+ retained_text_bytes: history.entries.reduce((sum, entry) => sum + entry.length * 2, 0) }));
+}
diff --git a/tests/check_scan_ui.py b/tests/check_scan_ui.py
index 0d4cd40..d3da163 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 and toast lifecycle in headless Chromium, never ADB/Tauri.
+"""Check the built UI, toasts and log history in Chromium, never ADB/Tauri.
Run npm run build first. Uses installed Chrome/Chromium, no added packages.
"""
@@ -58,13 +58,13 @@ 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.
+ # 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' },
+ rollupOptions: { input: ['tests/toast_lifecycle_fixture.html', 'tests/log_history_fixture.html'] },
}});
''', str(work / 'site')], cwd=REPO, check=True, timeout=60)
server = ThreadingHTTPServer(('127.0.0.1', 0), partial(Handler, directory=str(work / 'site')))
@@ -80,7 +80,7 @@ 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:
- for expected in ('scan-ui', 'toast-lifecycle'):
+ for expected in ('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/log_history.test.mjs b/tests/log_history.test.mjs
new file mode 100644
index 0000000..e8a6a1b
--- /dev/null
+++ b/tests/log_history.test.mjs
@@ -0,0 +1,98 @@
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+import ts from "typescript";
+
+const source = await readFile(new URL("../src/logHistory.ts", import.meta.url), "utf8");
+const { outputText } = ts.transpileModule(source, {
+ compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext },
+});
+const { appendLog, emptyLogHistory, MAX_LOG_ENTRIES, MAX_LOG_TEXT_UNITS, MAX_LOG_ENTRY_UNITS } =
+ await import(`data:text/javascript;base64,${Buffer.from(outputText).toString("base64")}`);
+
+function verify(history) {
+ assert.ok(history.entries.length <= MAX_LOG_ENTRIES);
+ assert.ok(history.textUnits <= MAX_LOG_TEXT_UNITS);
+ assert.equal(history.textUnits, history.entries.reduce((sum, entry) => sum + entry.length, 0));
+ assert.ok(history.entries.every(entry => entry.length <= MAX_LOG_ENTRY_UNITS));
+}
+
+test("history starts empty and preserves timestamps, Unicode and chronological order", () => {
+ const empty = emptyLogHistory();
+ assert.deepEqual(empty, { entries: [], textUnits: 0, discarded: 0 });
+ let history = appendLog(empty, "[12:00:00] [SCAN] /sdcard/照片/😀");
+ history = appendLog(history, "[12:00:01] [ERROR] No Android device detected");
+ assert.deepEqual(history.entries, ["[12:00:00] [SCAN] /sdcard/照片/😀", "[12:00:01] [ERROR] No Android device detected"]);
+ verify(history);
+});
+
+test("entry count evicts oldest diagnostics and retains the latest shutdown/error", () => {
+ let history = emptyLogHistory();
+ for (let i = 0; i < 1500; i++) history = appendLog(history, `[${i}] [SCAN] Complete`);
+ history = appendLog(history, "[1500] [SOCKET] App disconnected; daemon shutdown could not be confirmed: No Android device detected");
+ assert.equal(history.entries.length, MAX_LOG_ENTRIES);
+ assert.equal(history.discarded, 1501 - MAX_LOG_ENTRIES);
+ assert.equal(history.entries[0], `[${1501 - MAX_LOG_ENTRIES}] [SCAN] Complete`);
+ assert.match(history.entries.at(-1), /shutdown could not be confirmed/);
+ verify(history);
+});
+
+test("text budget bounds long messages independently of entry count", () => {
+ let history = emptyLogHistory();
+ const count = Math.floor(MAX_LOG_TEXT_UNITS / MAX_LOG_ENTRY_UNITS) + 1;
+ for (let i = 0; i < count; i++) history = appendLog(history, String(i).padEnd(MAX_LOG_ENTRY_UNITS, "x"));
+ assert.equal(history.discarded, 1);
+ assert.equal(history.entries.length, count - 1);
+ assert.ok(history.entries.length < MAX_LOG_ENTRIES);
+ verify(history);
+});
+
+test("one append can evict multiple old entries to satisfy the text budget", () => {
+ let history = emptyLogHistory();
+ for (let i = 0; i < MAX_LOG_ENTRIES; i++) history = appendLog(history, "x".repeat(262));
+ const next = appendLog(history, "y".repeat(MAX_LOG_ENTRY_UNITS));
+ assert.ok(next.discarded > 1);
+ assert.equal(next.entries.at(-1), "y".repeat(MAX_LOG_ENTRY_UNITS));
+ verify(next);
+});
+
+test("oversized display text is marked without changing the source path", () => {
+ const path = "/sdcard/" + "📁".repeat(10000) + "/important.txt";
+ const message = `[12:34:56] [DELETE] Requesting deletion of ${path}...`;
+ const history = appendLog(emptyLogHistory(), message);
+ assert.ok(history.entries[0].startsWith("[12:34:56] [DELETE]"));
+ assert.ok(history.entries[0].endsWith("… [truncated]"));
+ assert.ok(path.endsWith("/important.txt") && message.endsWith("/important.txt..."));
+ verify(history);
+});
+
+test("truncation never splits a surrogate pair at the boundary", () => {
+ const prefix = "a".repeat(MAX_LOG_ENTRY_UNITS - "… [truncated]".length - 1);
+ const history = appendLog(emptyLogHistory(), prefix + "😀" + "b".repeat(100));
+ assert.equal(history.entries[0], prefix + "… [truncated]");
+ verify(history);
+});
+
+test("short text retains exact code units including quotes, controls and lone surrogates", () => {
+ const message = "\"\n\t\\\ud800<script>";
+ assert.equal(appendLog(emptyLogHistory(), message).entries[0], message);
+});
+
+test("updates do not mutate a previous React state snapshot", () => {
+ const previous = appendLog(emptyLogHistory(), "one");
+ Object.freeze(previous.entries);
+ Object.freeze(previous);
+ const next = appendLog(previous, "two");
+ assert.deepEqual(previous.entries, ["one"]);
+ assert.deepEqual(next.entries, ["one", "two"]);
+});
+
+test("mixed long-session input maintains both bounds and exact discard accounting", () => {
+ let history = emptyLogHistory();
+ for (let i = 0; i < 10000; i++) {
+ history = appendLog(history, `[${i}] ` + "😀".repeat(i % 7 === 0 ? 5000 : i % 200));
+ verify(history);
+ assert.equal(history.discarded + history.entries.length, i + 1);
+ }
+ assert.ok(history.entries.at(-1).startsWith("[9999]"));
+});
diff --git a/tests/log_history_fixture.html b/tests/log_history_fixture.html
new file mode 100644
index 0000000..1530625
--- /dev/null
+++ b/tests/log_history_fixture.html
@@ -0,0 +1,8 @@
+<!doctype html>
+<html lang="en">
+ <head><meta charset="UTF-8" /><title>Log history fixture</title></head>
+ <body>
+ <div id="root"></div>
+ <script type="module" src="/tests/log_history_fixture.jsx"></script>
+ </body>
+</html>
diff --git a/tests/log_history_fixture.jsx b/tests/log_history_fixture.jsx
new file mode 100644
index 0000000..a6a5931
--- /dev/null
+++ b/tests/log_history_fixture.jsx
@@ -0,0 +1,72 @@
+// Real log model/component. Synthetic replay only; no native app or IPC.
+import { createRoot } from "react-dom/client";
+import { TerminalLog } from "../src/TerminalLog";
+import { appendLog, emptyLogHistory, MAX_LOG_ENTRIES, MAX_LOG_TEXT_UNITS } from "../src/logHistory";
+import "../src/App.css";
+
+const root = createRoot(document.getElementById("root"));
+const rows = () => document.querySelectorAll("#terminal-log .log-entry");
+const check = (condition, message) => { if (!condition) throw Error(message); };
+const pause = () => new Promise(resolve => setTimeout(resolve, 20));
+const waitFor = async (predicate, message) => {
+ const deadline = Date.now() + 15000;
+ while (!predicate()) { if (Date.now() > deadline) throw Error(message); await pause(); }
+};
+const layout = () => document.querySelector("#terminal-log > div").scrollHeight;
+const renderMeasured = async history => {
+ const start = performance.now();
+ root.render(<TerminalLog history={history} />);
+ await waitFor(() => rows().length === history.entries.length, "Log rows missing");
+ layout();
+ await new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ return performance.now() - start;
+};
+const metrics = {};
+const violations = [];
+document.addEventListener("securitypolicyviolation", event => violations.push(event.blockedURI));
+const report = async (passed, error) => {
+ root.unmount();
+ await fetch("/report", { method: "POST", body: JSON.stringify({ fixture: "log-history", passed, error, metrics,
+ checks: passed ? ["bounded replay rows", "latest chronological entries", "visible discard notice", "long-message text budget", "truncation marker", "escaped diagnostic text", "fresh shutdown/error retained"] : undefined }) });
+};
+
+void (async () => {
+ const messages = Array.from({ length: 20000 }, (_, i) => `[12:34:56] [SCAN ${i}] /sdcard/文件😀/` + "synthetic-path-".repeat(8));
+ // Replay the former unbounded history through the same log component. This
+ // measures row-count effects, not a complete old-app/new-app comparison.
+ const legacy = { entries: messages, textUnits: messages.reduce((sum, entry) => sum + entry.length, 0), discarded: 0 };
+ metrics.unbounded_render_layout_ms = await renderMeasured(legacy);
+ metrics.unbounded_rows = rows().length;
+ root.render(null);
+ await waitFor(() => rows().length === 0, "Baseline did not unmount");
+
+ let history = messages.reduce(appendLog, emptyLogHistory());
+ metrics.bounded_render_layout_ms = await renderMeasured(history);
+ metrics.bounded_rows = rows().length;
+ check(rows().length === MAX_LOG_ENTRIES, "Replay exceeded row limit");
+ check(rows()[0].textContent.includes("[SCAN 19500]"), "Wrong first retained entry");
+ check(rows()[499].textContent.includes("[SCAN 19999]"), "Newest entry missing");
+ const notice = document.getElementById("log-retention-notice");
+ check(notice?.textContent.includes("19,500 older entries discarded"), "Discard notice missing");
+ const bounds = notice.getBoundingClientRect();
+ check(bounds.top >= 0 && bounds.bottom <= innerHeight, "Discard notice is outside the viewport");
+ const list = document.querySelector("#terminal-log > div");
+ list.scrollTop = list.scrollHeight;
+ check(notice.getBoundingClientRect().top === bounds.top, "Discard notice scrolled out of view");
+
+ history = emptyLogHistory();
+ for (let i = 0; i < 1000; i++) history = appendLog(history, `[${i}] /sdcard/` + "📁".repeat(10000));
+ await renderMeasured(history);
+ check(history.textUnits <= MAX_LOG_TEXT_UNITS && rows().length < MAX_LOG_ENTRIES, "Long messages escaped text bound");
+ check([...rows()].every(row => row.textContent.includes("… [truncated]")), "Truncation was not marked");
+ history = appendLog(history, '[12:35:00] [ERROR] <img src="invalid" onerror="alert(1)">');
+ history = appendLog(history, "[12:35:01] [SOCKET] App disconnected; daemon shutdown could not be confirmed: No Android device detected");
+ root.render(<TerminalLog history={history} />);
+ await waitFor(() => rows()[rows().length - 1]?.textContent.includes("shutdown could not be confirmed"), "Fresh shutdown/error missing");
+ check(!document.querySelector("#terminal-log img") && document.querySelector("#terminal-log").textContent.includes("<img"), "Diagnostic text became markup");
+ check(violations.length === 0, `CSP blocked resources: ${violations.join(", ")}`);
+ metrics.long_message_rows = rows().length;
+ metrics.long_message_text_bytes = history.textUnits * 2;
+ metrics.viewport = { width: innerWidth, height: innerHeight, scale: devicePixelRatio };
+ await report(true);
+})().catch(error => report(false, error.stack ?? String(error)));
diff --git a/tests/scan_ui_fixture.js b/tests/scan_ui_fixture.js
index bab754c..d568652 100644
--- a/tests/scan_ui_fixture.js
+++ b/tests/scan_ui_fixture.js
@@ -62,7 +62,7 @@
unregisterCallback: () => {},
invoke: async (command, args = {}) => {
calls.push({ command, args });
- if (command === "check_adb") return "Mock ADB";
+ if (command === "check_adb") return "Mock ADB " + "x".repeat(20000);
if (command === "init_daemon") return "Mock daemon";
if (command === "run_scan") { generation++; reset(); return JSON.stringify(summary()); }
if (command === "stop_daemon") {
@@ -109,7 +109,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", "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 });
+ 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", "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");
@@ -135,6 +135,9 @@
check(bounds.top >= 0 && bounds.bottom <= innerHeight, "Connect button is outside the viewport");
document.querySelector("#btn-connect").click();
await waitFor(() => rows().length === 129, "Initial page did not render 128 children");
+ const logRows = [...document.querySelectorAll("#terminal-log .log-entry")];
+ check(logRows.some(row => row.textContent.includes("[ADB] Found:") && row.textContent.includes("… [truncated]")), "App did not bound oversized diagnostics");
+ check(logRows.every(row => row.textContent.length < 4200), "App retained oversized log text");
const mono = document.querySelector(".font-mono");
check(mono && getComputedStyle(mono).fontFamily.includes("JetBrains Mono"), "Result does not use JetBrains Mono");
check(document.documentElement.scrollWidth <= innerWidth, "Results overflow horizontally");
diff --git a/tests/toast_lifecycle_fixture.jsx b/tests/toast_lifecycle_fixture.jsx
index b89c327..21debed 100644
--- a/tests/toast_lifecycle_fixture.jsx
+++ b/tests/toast_lifecycle_fixture.jsx
@@ -62,6 +62,7 @@ const report = async (passed, error) => {
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 }) });
+ if (passed) location.replace("/tests/log_history_fixture.html");
};
void (async () => {