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
91.2 KB
Raw Blame
// Real built frontend, mocked Tauri IPC. No native app, ADB or device calls.
(() => {
  const calls = [];
  const violations = [];
  document.addEventListener("securitypolicyviolation", event => violations.push(event.blockedURI));
  let generation = 1;
  let revision = 0;
  let unavailable = false;
  let readOnly = false;
  let scanRoot = "/fixture";
  let delayedZoom = true;
  let holdView = false;
  let releaseView;
  let failView = false;
  let delayedDetail = true;
  let holdDetail = false;
  let releaseDetail;
  let badDetail = null;
  let delayedLargest = true;
  let failLargest = false;
  let malformedLargest = false;
  let holdSearch = false;
  let resolveSearch;
  let failSearch = false;
  let malformedSearch = false;
  let holdApps = false;
  let resolveApps;
  let failApps = false;
  let invalidApps = false;
  let holdTypes = false;
  let resolveTypes;
  let failTypes = false;
  let invalidTypes = false;
  let wideFolders = false;
  let expandedTree;
  let emptyScan = false;
  let coverageErrors = 0;
  let unreadableDirectories;
  let coverageSkipped = 0;
  let failDelete = false;
  let failScan = false;
  let holdScan = false;
  let heldScan;
  let stopOutcome = "acknowledged";
  const readyDevices = [
    { serial: "phone-one", state: "device", model: "Pixel <One>" },
    { serial: "phone-two", state: "device", model: "Tablet Two" },
    { serial: "offline-phone", state: "offline", model: null },
    { serial: "locked-phone", state: "unauthorized", model: null },
  ];
  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;
  const scanRecords = [];
  let callbacks = 0;
  let rootChildren;
  let folderChildren;
  const pause = ms => new Promise(resolve => setTimeout(resolve, ms));
  const check = (condition, message) => { if (!condition) throw Error(message); };
  const pressKey = async key => {
    const response = await fetch("/keyboard", { method: "POST", body: JSON.stringify({ key }) });
    check(response.ok, `Trusted keyboard input failed: ${key} (${response.status})`);
  };
  const node = (id, parent_id, name, size, directory = false) => ({
    id, parent_id, name, size, type: directory ? "directory" : "file", counted: true,
    child_count: directory ? 200 : 0, can_delete: id !== 0 && !readOnly,
  });
  const whitespaceName = " file-3  double\t  ";
  const reset = () => {
    folderChildren = Array.from({ length: 200 }, (_, i) => node(i + 1001, 1, `nested-${i}`, 1));
    rootChildren = [node(1, 0, "large-folder", 200, true), ...Array.from({ length: 536 }, (_, i) => node(i + 2, 0, i === 3 ? whitespaceName : ` file-${i} `, 1))];
    if (wideFolders) {
      rootChildren = Array.from({ length: 128 }, (_, index) => ({
        ...node(index + 1, 0, `wide-${String(index + 1).padStart(3, "0")}`, 128, true),
        child_count: 128,
      }));
      folderChildren = [];
    }
    if (emptyScan) { rootChildren = []; folderChildren = []; }
    unavailable = false;
    revision = 0;
  };
  reset();
  const scope = () => ({ generation: `fixture-${generation}`, revision });
  const summary = () => ({
    ...scope(), status: "ok", root_path: scanRoot, root: { ...node(0, null, "fixture", rootChildren.reduce((sum, item) => sum + item.size, 0), true), child_count: rootChildren.length },
    total_files: wideFolders ? 128 * 128 : rootChildren.filter(item => item.type === "file").length + folderChildren.length, total_dirs: 1 + rootChildren.filter(item => item.type === "directory").length,
    total_size: rootChildren.reduce((sum, item) => sum + item.size, 0), errors: coverageErrors, skipped: coverageSkipped, scan_time_ms: 1, read_only: readOnly,
    unreadable_directories: unreadableDirectories,
  });
  const wideEntries = parent => Array.from({ length: 128 }, (_, index) =>
    node(1000 + (parent - 1) * 128 + index, parent, `entry-${parent}-${index}`, 1));
  const detail = id => {
    const target = id === 0 ? summary().root : wideFolders && id >= 1000
      ? wideEntries(Math.floor((id - 1000) / 128) + 1).find(item => item.id === id)
      : [...rootChildren, ...folderChildren].find(item => item.id === id);
    check(target, "Unknown mock node");
    const parent = wideFolders && target.parent_id > 0
      ? rootChildren.find(item => item.id === target.parent_id).name + "/"
      : target.parent_id === 1 ? "large-folder/" : "";
    return { ...scope(), node: target, path: `${scanRoot}/${parent}${target.name}` };
  };
  const view = args => {
    const directory = args.nodeId === 0 ? summary().root : detail(args.nodeId).node;
    const all = args.nodeId === 0 ? rootChildren : wideFolders
      ? wideEntries(args.nodeId)
      : args.nodeId === 1 ? folderChildren : [];
    let offset = 0;
    if (args.cursor) {
      const position = all.findIndex(item => item.id === args.cursor.node_id);
      offset = args.cursor.direction === "next" ? position + 1 : Math.max(0, position - 128);
    }
    const children = all.slice(offset, offset + 128);
    const chart = all.slice(0, 64).map(item => ({ node_id: item.id, name: item.name, size: item.size }));
    const remainder = directory.size - chart.reduce((sum, tile) => sum + tile.size, 0);
    if (all.length && remainder) chart.push({ node_id: null, name: "Other", size: remainder });
    return { ...scope(), node: directory, path: args.nodeId === 0 ? scanRoot : detail(args.nodeId).path,
      breadcrumbs: args.nodeId === 0 ? [{ id: 0, name: "fixture" }] : [{ id: 0, name: "fixture" }, { id: args.nodeId, name: directory.name }],
      children, chart,
      previous_cursor: offset ? { direction: "previous", node_id: children[0].id } : null,
      next_cursor: offset + children.length < all.length ? { direction: "next", node_id: children.at(-1).id } : null,
    };
  };
  window.__TAURI_INTERNALS__ = {
    transformCallback: () => ++callbacks,
    unregisterCallback: () => {},
    invoke: async (command, args = {}) => {
      calls.push({ command, args });
      if (command === "list_devices") {
        await pause(50);
        if (discoveryError) throw discoveryDump;
        return listedDevices;
      }
      if (command === "check_adb") return "Mock ADB " + "x".repeat(20000);
      if (command === "init_daemon") {
        check(listedDevices.some(device => device.serial === args.serial && device.state === "device"), "Selected device disconnected before startup\nfixture startup details <stderr>");
        activeDevice = args.serial;
        return "Mock daemon";
      }
      if (command === "run_scan") {
        if (failScan) { failScan = false; throw "Fixture rescan failure"; }
        if (holdScan) {
          holdScan = false;
          return new Promise((_, reject) => { heldScan = { scanId: args.scanId, reject }; });
        }
        generation++;
        reset();
        const stats = summary();
        scanRecords.push({
          generation: scope().generation,
          device: activeDevice,
          readOnly, errors: stats.errors, skipped: stats.skipped, root: stats.root_path,
          totals: { total_files: stats.total_files, total_dirs: stats.total_dirs, total_size: stats.total_size },
          at: Date.now(),
        });
        return JSON.stringify(stats);
      }
      if (command === "cancel_scan") {
        check(heldScan && args.scanId === heldScan.scanId, "Cancellation targeted the wrong scan");
        heldScan.reject("Scan cancelled");
        heldScan = undefined;
        return;
      }
      if (command === "stop_daemon") {
        await pause(150);
        unavailable = true;
        if (stopOutcome === "unreachable") throw "No Android device detected";
        if (stopOutcome === "invalid") return "daemon already stopped";
        if (stopOutcome === "wrong-ack") return JSON.stringify({ status: "ok", message: "pong" });
        if (stopOutcome === "error-status") return JSON.stringify({ status: "error", message: "Authentication failed" });
        return JSON.stringify({ status: "ok", message: "shutting down" });
      }
      check(!unavailable, "Snapshot unavailable");
      check(args.generation === scope().generation && args.revision === revision, "Stale mock snapshot");
      if (command === "get_app_usage") {
        if (failApps) { failApps = false; throw "Fixture package query failure"; }
        const stats = summary();
        const all = emptyScan ? [] : Array.from({ length: 205 }, (_, id) => ({
          package_id: `com.fixture${String(id).padStart(3, "0")}`,
          scanned_size: id === 0 ? 0 : 1, locations: 1,
        }));
        const end = Math.min(args.skip + 100, all.length);
        const response = {
          ...scope(), total_size: stats.total_size, errors: stats.errors, skipped: stats.skipped,
          total_packages: all.length, attributed_size: emptyScan ? 0 : 204,
          unattributed_size: stats.total_size - (emptyScan ? 0 : 204),
          skip: args.skip, next_skip: end < all.length ? end : null,
          packages: all.slice(args.skip, end),
        };
        if (invalidApps) { invalidApps = false; response.packages = null; }
        if (holdApps) {
          holdApps = false;
          response.packages[0].package_id += "Old";
          return new Promise(resolve => { resolveApps = () => resolve(JSON.stringify(response)); });
        }
        return JSON.stringify(response);
      }
      if (command === "get_file_types") {
        if (failTypes) { failTypes = false; throw "Fixture file-type query failure"; }
        const stats = summary();
        const data = { ...scope(), total_files: stats.total_files, total_size: stats.total_size,
          categories: ["images", "videos", "audio", "documents", "archives", "android_packages", "no_extension", "other"].map(kind => ({ kind, files: kind === "no_extension" ? stats.total_files : 0, size: kind === "no_extension" ? stats.total_size : 0 })) };
        if (invalidTypes) { invalidTypes = false; data.categories[0].files = 1; }
        const raw = JSON.stringify(data);
        if (holdTypes) { holdTypes = false; return new Promise(resolve => { resolveTypes = () => resolve(raw); }); }
        return raw;
      }
      if (command === "get_largest_files") {
        check(Number.isInteger(args.limit) && args.limit > 0 && args.limit <= 100, "Unbounded largest-files query");
        if (failLargest) { failLargest = false; throw "Mock largest-files failure"; }
        if (malformedLargest) {
          malformedLargest = false;
          return JSON.stringify({ ...scope(), limit: args.limit, total_files: summary().total_files, files: null });
        }
        const files = [...rootChildren, ...folderChildren].filter(item => item.type === "file")
          .sort((a, b) => b.size - a.size || (a.name < b.name ? -1 : a.name > b.name ? 1 : a.id - b.id));
        const response = JSON.stringify({ ...scope(), limit: args.limit, total_files: files.length,
          files: files.slice(0, args.limit).map(item => detail(item.id)) });
        if (delayedLargest) { delayedLargest = false; await pause(300); }
        return response;
      }
      if (command === "get_search_results") {
        const category = args.fileType;
        check(typeof args.query === "string" && new TextEncoder().encode(args.query).length <= 255
          && (category ? args.query === "" && args.folderId === null : args.query !== ""), "Invalid search filter");
        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, folder_id: args.folderId, has_more: false, results: null });
        }
        const candidates = args.folderId === 1 ? folderChildren : [...rootChildren, ...folderChildren];
        const matches = candidates.filter(item => category
          ? category === "no_extension" && item.type === "file" && item.counted
          : item.name.toLowerCase().includes(args.query.toLowerCase()));
        // Simulate a page shortened by the backend's serialized-byte budget.
        const limit = category || args.query === "nested" ? 37 : 100;
        const response = JSON.stringify({ ...scope(), query: args.query, skip: args.skip, folder_id: args.folderId,
          ...(category && { file_type: category }),
          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); }); }
        return response;
      }
      if (command === "get_scan_comparison") {
        // Same shape as the Rust query: the delta compares the live totals
        // with the previous scan of the same device, so deletions count.
        const current = scanRecords.find(record => record.generation === scope().generation);
        check(current, "Comparison requested for an unknown mock scan");
        check(current.errors === 0, "Scans with access errors are not recorded as history baselines");
        const previous = scanRecords.slice(0, scanRecords.indexOf(current)).reverse()
          .find(record => record.errors === 0 && record.device === current.device
            && record.readOnly === current.readOnly && record.root === current.root && record.skipped === current.skipped);
        if (!previous) return JSON.stringify({ ...scope(), first: true, previous: null, delta: null });
        const stats = summary();
        return JSON.stringify({ ...scope(), first: false,
          previous: { recorded_at: Math.floor(previous.at / 1000), ...previous.totals },
          delta: {
            files: stats.total_files - previous.totals.total_files,
            dirs: stats.total_dirs - previous.totals.total_dirs,
            size: stats.total_size - previous.totals.total_size,
          } });
      }
      if (command === "get_scan_view") {
        const response = JSON.stringify(view(args));
        if (failView) { failView = false; throw Error("Directory page fixture failure"); }
        if (holdView) { holdView = false; await new Promise(resolve => { releaseView = resolve; }); }
        if (args.nodeId === 1 && delayedZoom) { delayedZoom = false; await pause(300); }
        return response;
      }
      if (command === "get_scan_node") {
        if (badDetail) {
          const path = badDetail === "object" ? {} : "/outside/file-0";
          badDetail = null;
          return JSON.stringify({ ...detail(args.nodeId), path });
        }
        const response = JSON.stringify(detail(args.nodeId));
        if (holdDetail) { holdDetail = false; return new Promise(resolve => { releaseDetail = () => resolve(response); }); }
        if (delayedDetail) { delayedDetail = false; await pause(300); }
        return response;
      }
      if (command === "delete_item") {
        check(!("path" in args), "Frontend passed a destructive path");
        check(args.nodeId !== 0 && !readOnly, "Unsafe mock deletion");
        if (failDelete) { unavailable = true; throw "Partially deleted directory"; }
        const selected = detail(args.nodeId);
        rootChildren = rootChildren.filter(item => item.id !== args.nodeId);
        revision++;
        return JSON.stringify({ summary: summary(), message: "Deleted fixture item", removed: { files: 1, dirs: 0, size: selected.node.size } });
      }
      throw Error(`Unexpected IPC ${command}`);
    },
  };
  const waitFor = async (predicate, message, timeout = 3000) => {
    const end = Date.now() + timeout;
    while (!predicate()) { if (Date.now() > end) throw Error(message); await pause(20); }
  };
  const button = text => [...document.querySelectorAll("button")].find(item => item.textContent.trim() === text && !item.disabled);
  const rows = () => [...document.querySelectorAll(".file-row")];
  const zoomFolder = () => [...rows().find(item => item.textContent.includes("large-folder")).querySelectorAll("button")]
    .find(item => item.textContent.trim() === "Zoom").click();
  let widePaging;
  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, wide_paging: widePaging, expanded_tree: expandedTree, checks: passed ? ["offline fonts under CSP", "bounded collapsed discovery diagnostics", "discovery retry recovery", "setup alignment", "result fonts", "file label semantics", "usable file workspace", "keyboard storage map visibility", "collapsible diagnostics", "complete paging", "directory paging focus and retries", "expanded-tree row growth and keyboard focus", "first-scan comparison", "unchanged comparison after rescan", "deletion delta comparison", "cross-device comparison isolation", "bounded package-folder paging and coverage", "analysis paging keyboard focus", "package query retries and stale replies", "bounded file-type totals", "file-type retry and malformed response", "file-type generation and deletion revision", "file-type coverage and empty scan", "file-type drilldown paging, keyboard and revision", "bounded largest files", "late largest response", "largest query retry", "malformed largest response recovery", "largest ID-only deletion", "largest read-only guards", "largest folder navigation without rescanning", "bounded search results", "scoped search selection", "search page selection", "late search response", "search retry and malformed response", "search ID-only deletion", "read-only search deletion disabled", "late zoom", "Other tile", "stale confirmation", "exact confirmation whitespace", "reachable long-path confirmation", "native modal keyboard focus and cancellation", "ID-only deletion", "revision refresh", "partial failure", "read-only", "acknowledged shutdown", "unconfirmed shutdown", "reconnect", "stop action ordering", "duplicate rescan guard", "rescan failure recovery", "rescan cancellation recovery", "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");
    });
  };
  void (async () => {
    await waitFor(() => document.querySelector("#btn-connect"), "Setup did not render");
    check(!document.querySelector('link[href^="http"]'), "External resource link remains");
    // load() returns actual matching FontFace objects; check() alone can succeed
    // through fallback even when no face exists. Exercise every shipped subset.
    for (const family of ["Inter", "JetBrains Mono"]) {
      const samples = family === "Inter" ? ["SocketSweep → —", "Łódź", "ắ", "Ω", "ἀ", "Я", "Ҁ"] : ["Scan 123 → —", "Łódź", "ắ", "Ω", "Я", "Ҁ"];
      const weights = family === "Inter" ? [300, 400, 500, 600, 700, 800] : [400, 500];
      for (const weight of weights) for (const sample of samples) {
        const faces = await document.fonts.load(`${weight} 16px "${family}"`, sample);
        check(faces.length > 0 && faces.every(face => face.status === "loaded"), `Font missing: ${family} ${weight} ${sample}`);
      }
    }
    const connect = document.querySelector("#btn-connect");
    await waitFor(() => !document.querySelector("#btn-refresh-devices").disabled, "Device discovery did not finish");
    const picker = () => document.querySelector("#android-device");
    const selectDevice = serial => {
      picker().value = serial;
      picker().dispatchEvent(new Event("change", { bubbles: true }));
    };
    const refreshDevices = async () => {
      document.querySelector("#btn-refresh-devices").click();
      await waitFor(() => document.querySelector("#btn-refresh-devices").disabled && picker().disabled && document.querySelector("#btn-connect").disabled, "Refresh did not block connection/selection");
      await waitFor(() => !document.querySelector("#btn-refresh-devices").disabled, "Refresh did not finish");
    };
    check(picker().value === "" && connect.disabled, "Multiple ready devices were selected implicitly");
    check(document.querySelector('label[for="android-device"]'), "Picker lacks an accessible label");
    for (const serial of ["offline-phone", "locked-phone"]) {
      check([...picker().options].find(option => option.value === serial).disabled, "Unavailable device is selectable");
    }
    check([...picker().options].some(option => option.textContent.includes("Pixel <One>")) && !document.querySelector("One"), "Model label was treated as markup");
    selectDevice("phone-two");
    await waitFor(() => !connect.disabled, "Selected ready device did not enable Connect");
    listedDevices = readyDevices.filter(device => device.serial !== "phone-two");
    await refreshDevices();
    check(picker().value === "phone-two" && connect.disabled && document.querySelector("#device-status").textContent.includes("disconnected"), "Unplugging switched devices");
    for (const state of ["unauthorized", "offline"]) {
      listedDevices = [readyDevices[0], { ...readyDevices[1], state }];
      await refreshDevices();
      check(picker().value === "phone-two" && connect.disabled, "Unavailable selection fell back to another phone");
    }
    discoveryError = true;
    await refreshDevices();
    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 = [null];
    await refreshDevices();
    check(picker().value === "phone-two" && connect.disabled && status.textContent.includes("Couldn't check connected devices"),
      "Malformed device discovery did not preserve the selection and disable Connect");
    listedDevices = [...readyDevices].reverse();
    await refreshDevices();
    check(picker().value === "phone-two" && !connect.disabled, "Reordered/reconnected devices lost selection");
    await waitFor(() => /Discovery \(refresh, 2 ready of 4\): response \d+ ms, picker effect \d+ ms/.test(document.querySelector("#terminal-log").textContent),
      "Discovery diagnostics did not include timings and readiness");
    // The display is only a snapshot. Native startup must reject a selected
    // device that vanished after this refresh, without choosing the first one.
    listedDevices = [readyDevices[0]];
    connect.click();
    connect.click();
    await waitFor(() => document.querySelector("#btn-connect") && !document.querySelector("#btn-refresh-devices").disabled && document.querySelector("#device-status").textContent.includes("disconnected"), "Stale selected device did not return to setup");
    check(calls.filter(call => call.command === "init_daemon").length === 1 && !calls.some(call => call.command === "run_scan"), "Failed/duplicate connect started a scan or silently chose another device");
    check(!document.querySelector("#toast-container").textContent.includes("fixture startup details"), "Startup diagnostics filled the toast");
    check(document.querySelector("#terminal-log").textContent.includes("fixture startup details <stderr>") && !document.querySelector("#terminal-log stderr"), "Startup diagnostics were lost or treated as markup");
    check(picker().value === "phone-two" && document.querySelector("#btn-connect").disabled, "Failed startup replaced selected serial");
    listedDevices = readyDevices;
    await refreshDevices();
    check(getComputedStyle(connect).fontFamily.includes("Inter"), "Setup does not use Inter");
    const bounds = connect.getBoundingClientRect();
    check(Math.abs((bounds.left + bounds.right) / 2 - innerWidth / 2) < 2, `Connect button is not centered: ${bounds.left}..${bounds.right}, viewport ${innerWidth}`);
    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");
    check(activeDevice === "phone-two" && document.querySelector("#connected-device").textContent.includes("phone-two"), "Results do not identify the selected device");
    await waitFor(() => document.querySelector("#scan-history")?.textContent.includes("No previous comparable scan"), "First-scan comparison missing");
    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");
    check(document.body.textContent.includes("128 entries on this page of 537"), "Missing full entry count");
    check(!rows().find(item => item.textContent.includes("file-0")).querySelector("button:disabled"), "File label became an unavailable control");
    const deletesBeforeWhitespace = calls.filter(call => call.command === "delete_item").length;
    const whitespaceDelete = [...document.querySelectorAll('button[aria-label^="Delete "]')]
      .find(item => item.getAttribute("aria-label") === `Delete ${whitespaceName}`);
    check(whitespaceDelete, "Whitespace filename missing from the initial page");
    const detailDelayBeforeWhitespace = delayedDetail;
    whitespaceDelete.click();
    await waitFor(() => button("NUKE IT"), "Whitespace confirmation missing");
    const exactPath = `/fixture/${whitespaceName}`;
    const confirmationPath = [...document.querySelectorAll("p")].find(item => item.textContent === exactPath);
    check(confirmationPath?.innerText === exactPath, "Confirmation collapses filename whitespace");
    for (let index = 0; index < exactPath.length; index++) {
      if (exactPath[index] !== " " && exactPath[index] !== "\t") continue;
      const range = document.createRange();
      range.setStart(confirmationPath.firstChild, index);
      range.setEnd(confirmationPath.firstChild, index + 1);
      check(range.getBoundingClientRect().width > 0, `Confirmation whitespace at ${index} has no rendered width`);
    }
    button("Cancel").click();
    await waitFor(() => !button("NUKE IT"), "Whitespace confirmation did not cancel");
    check(calls.filter(call => call.command === "delete_item").length === deletesBeforeWhitespace, "Cancelled whitespace confirmation issued a delete");
    delayedDetail = detailDelayBeforeWhitespace;
    const fileViewport = document.querySelector('[aria-label="Files and folders"]');
    const fileBounds = fileViewport.getBoundingClientRect();
    check(fileBounds.height >= innerHeight * 0.55, `File browser too short: ${fileBounds.height}px of ${innerHeight}px`);
    check(fileViewport.scrollHeight > fileViewport.clientHeight, "File browser cannot scroll its entries");
    const logDisclosure = document.querySelector("#terminal-log");
    check(logDisclosure.tagName === "DETAILS" && !logDisclosure.open, "Diagnostics did not start collapsed");
    logDisclosure.querySelector("summary").click();
    await waitFor(() => logDisclosure.open, "Diagnostics did not open");
    check(logDisclosure.getBoundingClientRect().height > 100 && logRows[0].getBoundingClientRect().height > 0, "Expanded diagnostics are not readable");
    check(fileViewport.clientHeight >= innerHeight * 0.3, "Expanded diagnostics made files unusable");
    logDisclosure.querySelector("summary").click();
    await waitFor(() => !logDisclosure.open, "Diagnostics did not close");
    check(Math.abs(fileViewport.getBoundingClientRect().height - fileBounds.height) < 2, "Closing diagnostics did not restore browsing space");
    const scrollBefore = fileViewport.scrollTop;
    fileViewport.scrollTop = 200;
    check(fileViewport.scrollTop > scrollBefore, "File list does not scroll independently");
    fileViewport.scrollTop = 0;
    const appsPanel = () => document.querySelector('section[aria-label="Package-folder usage"]');
    const appRows = () => [...document.querySelectorAll(".app-usage-row")];
    holdApps = true;
    button("Package folders").click();
    await waitFor(() => resolveApps, "Pending package query missing");
    const oldApps = resolveApps;
    button("Storage map").click();
    await waitFor(() => rows().length === 129, "Map missing after package query");
    button("Package folders").click();
    await waitFor(() => appRows().length === 100, "Package first page missing");
    oldApps();
    await pause(30);
    check(!appsPanel().textContent.includes("Old"), "Late package response replaced the current page");
    check(document.documentElement.scrollWidth <= innerWidth, "Package view overflowed horizontally");
    check(appsPanel().textContent.includes("Full app totals remain unknown") && appsPanel().textContent.includes("Missing and unreadable"),
      "Package coverage was presented as complete");
    check(appRows()[0].textContent.includes("0.0 B") || appRows()[0].textContent.includes("0 B"), "Zero scanned bytes were lost");
    holdApps = true;
    resolveApps = undefined;
    button("Next").focus();
    await pressKey("Enter");
    await waitFor(() => resolveApps && appRows().length === 0, "Package page did not enter its loading state");
    resolveApps();
    await waitFor(() => appRows()[0]?.textContent.includes("com.fixture100"), "Second package page missing");
    check(document.activeElement === button("Next"), "Next package page lost keyboard focus");
    failApps = true;
    await pressKey("Enter");
    await waitFor(() => button("Retry") && document.activeElement === button("Retry"), "Failed package page did not focus Retry");
    await pressKey("Enter");
    await waitFor(() => appRows().length === 5, "Last package page missing after retry");
    check(document.activeElement === button("Previous"), "Last package page did not focus Previous");
    await pressKey("Enter");
    await waitFor(() => appRows()[0]?.textContent.includes("com.fixture100"), "Previous package page missing");
    check(document.activeElement === button("Previous"), "Previous package page lost keyboard focus");
    holdApps = true;
    resolveApps = undefined;
    button("Next").focus();
    await pressKey("Enter");
    await waitFor(() => resolveApps, "Pending last package page missing");
    const packageTab = button("Package folders");
    packageTab.focus();
    resolveApps();
    await waitFor(() => appRows().length === 5, "Pending last package page did not load");
    check(document.activeElement === packageTab, "Loaded package page stole focus from the tab");
    check(!appsPanel().querySelector('[aria-label^="Delete "]'), "Package summary exposed a deletion target");
    for (const failure of ["error", "malformed"]) {
      button("Storage map").click();
      await waitFor(() => rows().length === 129, "Map missing before package retry");
      if (failure === "error") failApps = true; else invalidApps = true;
      button("Package folders").click();
      await waitFor(() => appsPanel()?.querySelector('[role="alert"]'), "Bad package response was not reported");
      check(appRows().length === 0, "Bad package response retained rows");
      button("Retry").click();
      await waitFor(() => appRows().length === 100, "Package retry failed");
    }
    button("Storage map").click();
    await waitFor(() => rows().length === 129, "Map missing after package folders");
    const scanCount = calls.filter(item => item.command === "run_scan").length;
    const typesPanel = () => document.querySelector('section[aria-label="File types"]');
    const typesReady = () => typesPanel()?.querySelector('table[aria-busy="false"]') && !typesPanel().querySelector('[role="alert"]');
    const checkTypes = count => {
      const panel = typesPanel();
      check(panel.querySelectorAll(".file-type-row").length === 8, "File-type rows are unbounded");
      check(panel.querySelector('[data-kind="no_extension"]').cells[1].textContent === String(count), "File-type count did not match scan");
      check(panel.querySelector("tfoot").textContent.includes(String(count)), "File-type total missing");
      check(document.documentElement.scrollWidth <= innerWidth, "File-type view overflows horizontally");
      check(!panel.querySelector('button[aria-label^="Delete "]'), "File type became a deletion target");
    };
    holdTypes = true;
    button("File types").click();
    await waitFor(() => resolveTypes && typesPanel()?.querySelector('table[aria-busy="true"]'), "Pending file-type query missing");
    const oldTypes = resolveTypes;
    const rescan = document.querySelector("#btn-rescan");
    rescan.click();
    rescan.click();
    await waitFor(() => rows().length === 129, "Rescan during file-type query failed");
    check(calls.filter(item => item.command === "run_scan").length === scanCount + 1, "Duplicate rescan queued a second scan");
    button("File types").click();
    await waitFor(typesReady, "File-type summary missing after rescan");
    oldTypes();
    await pause(30);
    checkTypes(736);
    check(!typesPanel().querySelector('[role="alert"]'), "Late file-type response crossed generations");
    const typeScanCount = calls.filter(item => item.command === "run_scan").length;
    for (const invalid of [false, true]) {
      button("Storage map").click();
      await waitFor(() => rows().length === 129, "Map missing before file-type retry");
      if (invalid) invalidTypes = true; else failTypes = true;
      button("File types").click();
      await waitFor(() => typesPanel()?.querySelector('[role="alert"]'), "Invalid file-type summary did not fail");
      check(!typesPanel().textContent.includes("736 scanned files"), "File-type failure retained old totals");
      button("Retry").click();
      await waitFor(typesReady, "File-type retry failed");
      checkTypes(736);
    }
    check(calls.filter(item => item.command === "run_scan").length === typeScanCount, "File-type browsing rescanned the phone");
    button("Storage map").click();
    await waitFor(() => rows().length === 129, "Map missing after file types");
    const largestRows = () => [...document.querySelectorAll(".largest-file-row")];
    button("Largest files").click();
    await waitFor(() => document.querySelector("#largest-limit"), "Largest-files controls missing");
    const chooseLimit = count => {
      const select = document.querySelector("#largest-limit");
      select.value = String(count);
      select.dispatchEvent(new Event("change", { bubbles: true }));
    };
    // The first response is delayed; switching limits must win permanently.
    chooseLimit(10);
    await waitFor(() => largestRows().length === 10, "Largest-files limit not applied");
    await pause(350);
    check(largestRows().length === 10, "Late largest-files response replaced the current limit");
    check(largestRows()[0].textContent.includes("/fixture/ file-0 "), "Exact largest-file path missing");
    check(!largestRows().some(row => row.textContent.includes("large-folder")), "Directory ranked as a file");
    check(document.documentElement.scrollWidth <= innerWidth, "Largest files overflow horizontally");
    failLargest = true;
    chooseLimit(50);
    await waitFor(() => button("Retry"), "Largest-files failure not shown");
    button("Retry").click();
    await waitFor(() => largestRows().length === 50, "Largest-files retry failed");
    chooseLimit(100);
    await waitFor(() => largestRows().length === 100, "Maximum largest-files page missing");
    malformedLargest = true;
    chooseLimit(25);
    await waitFor(() => button("Retry") || !document.querySelector("#btn-rescan"), "Malformed largest-files response did not offer retry");
    check(button("Retry") && largestRows().length === 0 && document.querySelector("#btn-rescan"), "Malformed largest-files response retained rows or crashed results");
    button("Retry").click();
    await waitFor(() => largestRows().length === 25, "Malformed largest-files response did not recover");
    button("Show folder").click();
    await waitFor(() => rows().length === 129, "Show folder did not restore map");
    check(calls.filter(item => item.command === "run_scan").length === scanCount + 1, "Largest-files browsing rescanned the phone");
    const visibleNames = () => rows().slice(1).map(row =>
      row.querySelector('[aria-label^="Delete "]')?.getAttribute("aria-label").slice("Delete ".length));
    const expectedNames = rootChildren.map(child => child.name);
    const expectedPages = [];
    for (let offset = 0; offset < expectedNames.length; offset += 128) {
      expectedPages.push(expectedNames.slice(offset, offset + 128));
    }
    const pageMatches = expected => JSON.stringify(visibleNames()) === JSON.stringify(expected);
    check(pageMatches(expectedPages[0]), "First page changed entry order");
    const focusTarget = rows()[1].querySelector('[aria-label^="Delete "]');
    focusTarget.focus();
    const pagingViewport = focusTarget.closest("section");
    pagingViewport.scrollTop = pagingViewport.scrollHeight;
    check(pagingViewport.scrollTop > 0, "Wide page could not scroll");
    check(document.activeElement === focusTarget, "Scrolling dropped keyboard focus");
    const pageTimes = [];
    const visitPage = async (direction, expected) => {
      const started = performance.now();
      button(direction).focus();
      await pressKey("Enter");
      await waitFor(() => pageMatches(expected), `${direction} page omitted, duplicated or reordered entries`);
      const expectedFocus = button(direction) ?? button(direction === "Next" ? "Previous" : "Next");
      check(document.activeElement === expectedFocus, `${direction} directory paging lost keyboard focus`);
      pageTimes.push(performance.now() - started);
      check(rows().length <= 129, "Page exceeded the rendered-row bound");
    };
    for (const page of expectedPages.slice(1)) await visitPage("Next", page);
    check(!button("Next"), "Final page had an unexpected continuation");
    for (const page of expectedPages.slice(0, -1).reverse()) await visitPage("Previous", page);
    check(!button("Previous"), "First page had an unexpected previous cursor");
    widePaging = { entries: expectedNames.length, max_rows: 129, transition_ms: pageTimes.map(ms => Math.round(ms)) };

    const activate = async target => { target.focus(); await pressKey("Enter"); };
    const holdPage = async target => {
      holdView = true;
      await activate(target);
      await waitFor(() => releaseView, "Held directory query missing");
      const release = releaseView;
      releaseView = null;
      return release;
    };
    const outside = document.querySelector("#btn-rescan");
    const releaseMovedFocus = await holdPage(button("Next"));
    outside.focus();
    releaseMovedFocus();
    await waitFor(() => pageMatches(expectedPages[1]), "Held page did not finish");
    check(document.activeElement === outside, "Paging stole focus from another control");
    await visitPage("Previous", expectedPages[0]);
    const releaseAbandonedFocus = await holdPage(button("Next"));
    outside.focus();
    outside.blur();
    releaseAbandonedFocus();
    await waitFor(() => pageMatches(expectedPages[1]), "Abandoned page did not finish");
    check(document.activeElement === document.body, "Paging reclaimed focus after the user left it");
    await visitPage("Previous", expectedPages[0]);

    failView = true;
    await activate(button("Next"));
    await waitFor(() => button("Retry") && document.activeElement === button("Retry"), "Failed page did not focus Retry");
    await activate(button("Retry"));
    await waitFor(() => pageMatches(expectedPages[1]), "Directory retry did not recover");
    check(document.activeElement === button("Previous"), "Directory retry lost paging focus");
    await visitPage("Previous", expectedPages[0]);

    const releaseSwitchedView = await holdPage(button("Next"));
    await activate(button("File types"));
    await waitFor(() => document.querySelector('section[aria-label="File types"]'), "Types view missing during held page");
    releaseSwitchedView();
    await pause(30);
    check(document.activeElement === button("File types"), "Late directory page stole focus after switching views");
    await activate(button("Storage map"));
    await waitFor(() => pageMatches(expectedPages[1]), "Returning to directory lost its cursor");
    check(document.activeElement === button("Storage map"), "Returning directory query stole tab focus");
    await visitPage("Previous", expectedPages[0]);

    const folderToggle = () => rows().find(row => row.textContent.includes("large-folder"))?.querySelector("button[aria-expanded]");
    const nestedPager = () => document.querySelector('nav[aria-label="Pages in large-folder"]');
    const nestedAction = action => nestedPager()?.querySelector(`button[data-page-action="${action}"]:enabled`);
    const nestedRows = () => rows().filter(row => row.textContent.includes("nested-"));
    await activate(folderToggle());
    await waitFor(() => nestedRows().length === 128, "Nested directory first page missing");
    await activate(nestedAction("next"));
    await waitFor(() => nestedRows().length === 72, "Nested directory last page missing");
    check(document.activeElement === nestedAction("previous"), "Nested last page lost Previous focus");
    await activate(nestedAction("previous"));
    await waitFor(() => nestedRows().length === 128, "Nested directory previous page missing");
    check(document.activeElement === nestedAction("next"), "Nested first page lost Next focus");
    failView = true;
    await activate(nestedAction("next"));
    await waitFor(() => button("Retry") && document.activeElement === button("Retry"), "Nested page error lost Retry focus");
    await activate(button("Retry"));
    await waitFor(() => nestedRows().length === 72, "Nested retry did not recover");
    check(document.activeElement === nestedAction("previous"), "Nested retry lost paging focus");
    await activate(nestedAction("previous"));
    await waitFor(() => nestedRows().length === 128, "Nested first page did not recover");
    const releaseCollapsedPage = await holdPage(nestedAction("next"));
    const collapseTrigger = folderToggle();
    await activate(collapseTrigger);
    releaseCollapsedPage();
    await pause(30);
    check(nestedRows().length === 0 && document.activeElement === collapseTrigger, "Late nested page restored collapsed focus");

    zoomFolder();
    await waitFor(() => button("← Back to Root") && rows()[0]?.textContent.includes("large-folder"), "Zoom during held page failed");
    const releaseZoomedPage = await holdPage(button("Next"));
    const backToRoot = button("← Back to Root");
    await activate(backToRoot);
    await waitFor(() => rows()[0]?.textContent.includes("fixture") && !button("← Back to Root"), "Root did not recover during held-page zoom");
    if (folderToggle()?.getAttribute("aria-expanded") === "true") await activate(folderToggle());
    const zoomFocus = document.querySelector("#btn-rescan");
    zoomFocus.focus();
    releaseZoomedPage();
    await pause(30);
    check(document.activeElement === zoomFocus && pageMatches(expectedPages[0]), "Late page stole zoom focus or replaced the root");

    // Search: bounded pages, a superseded held response, retry, malformed
    // recovery, and ID-only deletion. No rescan is ever allowed here.
    const searchRows = () => [...document.querySelectorAll(".search-result-row")];
    const searchCheckbox = (row = searchRows()[0]) => row?.querySelector('input[type="checkbox"]');
    const selectionCount = () => document.querySelector("#search-selection-count")?.textContent ?? "";
    const searchField = () => document.querySelector("#search-input");
    const searchSubmit = () => document.querySelector("#search-submit");
    const setSearchText = (text, inputType = "insertText") => {
      const input = searchField();
      const set = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;
      set.call(input, text);
      input.dispatchEvent(new InputEvent("input", { bubbles: true, inputType, data: text }));
    };
    const searchFor = text => {
      setSearchText(text);
      searchSubmit().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");
    searchNext().focus();
    await pressKey("Tab");
    check(document.activeElement === searchCheckbox(), "First search checkbox is missing from the tab order");
    await pressKey("Space");
    check(searchCheckbox().checked && selectionCount() === "1 file selected", "Space did not select a search result");
    check(searchField().getAttribute("aria-label") === "Search file and folder names", "Search field has no persistent name");
    holdSearch = true;
    searchNext().click();
    await waitFor(() => resolveSearch, "Folder page to clear did not start");
    setSearchText("", "deleteContentBackward");
    button("Clear search").focus();
    await pressKey("Enter");
    await waitFor(() => !selectionCount() && document.activeElement === searchField(), "Clear search did not reset selection and focus");
    resolveSearch();
    resolveSearch = undefined;
    await pause(30);
    check(searchField().value === "" && searchRows().length === 0 && !searchNext() && !button("Clear search")
      && button("Search entire scan"), "Cleared search restored a stale page or changed scope");

    const searchCalls = () => calls.filter(call => call.command === "get_search_results");
    const queriesBeforePaste = searchCalls().length;
    const atLimit = " " + "\u00e9".repeat(126) + "x ";
    setSearchText(atLimit + " ", "insertFromPaste");
    check(searchSubmit().disabled && searchField().getAttribute("aria-invalid") === "true"
      && document.getElementById(searchField().getAttribute("aria-describedby"))?.textContent.includes("255 UTF-8 bytes"),
    "Oversized multibyte paste was not described or blocked");
    await pressKey("Enter");
    check(searchCalls().length === queriesBeforePaste, "Oversized search reached IPC");
    setSearchText(atLimit, "insertFromPaste");
    check(!searchSubmit().disabled && searchField().getAttribute("aria-invalid") === "false", "255-byte multibyte search was blocked");
    await pressKey("Enter");
    await waitFor(() => searchCalls().length === queriesBeforePaste + 1, "255-byte search did not reach IPC");
    check(searchCalls().at(-1).args.query === atLimit && searchCalls().at(-1).args.folderId === 1
      && searchCalls().at(-1).args.skip === 0, "Search altered whitespace, scope, or offset after clearing");
    searchFor("nested");
    await waitFor(() => searchRows().length === 37, "Cleared query could not be entered again");
    check(!searchCheckbox().checked && !selectionCount(), "Cleared query restored its selection");
    searchCheckbox().click();

    holdSearch = true;
    searchNext().focus();
    await pressKey("Enter");
    await waitFor(() => typeof resolveSearch === "function", "Second folder page did not start");
    const entireScanButton = button("Search entire scan");
    entireScanButton.focus();
    entireScanButton.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");
    check(document.activeElement === entireScanButton, "Late folder page took focus from the scope control");
    check(!searchCheckbox().checked && !selectionCount(), "Folder selection leaked into the whole scan");
    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");
    searchFor("large-folder");
    await waitFor(() => searchRows().length === 1, "Folder-only search result missing");
    check(!searchCheckbox() && !button("Select this page"), "Folder-only results offered file selection");
    searchFor("l");
    await waitFor(() => searchRows().length === 100 && searchRows()[0]?.textContent.includes("large-folder"), "Mixed search page missing");
    button("Select this page").click();
    await waitFor(() => button("Deselect this page"), "Select this page did not finish updating the mixed page");
    check(!searchCheckbox() && searchRows().slice(1).every(row => searchCheckbox(row)?.checked)
      && selectionCount() === "99 files selected", "Page selection included a folder or missed a file");
    // The first response is held; an empty superseding query must win and
    // the held response must never replace it.
    holdSearch = true;
    searchFor("file");
    await waitFor(() => document.querySelector("#search-input").value === "file", "Search query not submitted");
    searchFor("zzz-no-match");
    await waitFor(() => document.body.textContent.includes("No matching names"), "Superseding search state missing");
    resolveSearch();
    await pause(60);
    check(searchRows().length === 0 && document.body.textContent.includes("No matching names"), "Held search response replaced the current results");
    searchFor("file");
    await waitFor(() => searchRows().length === 100, "Bounded search page missing");
    check(searchNext(), "Search continuation missing");
    searchNext().click();
    await waitFor(() => searchRows().length > 0, "Second search page missing");
    searchFor("nested");
    await waitFor(() => searchRows().length === 37, "Byte-bounded search page missing");
    const nestedCount = searchRows().length;
    searchCheckbox().click();
    const firstNestedNames = searchRows().map(row => row.textContent);
    failSearch = true;
    searchNext().focus();
    await pressKey("Enter");
    await waitFor(() => button("Retry") && document.activeElement === button("Retry"), "Failed search page did not focus Retry");
    await pressKey("Enter");
    await waitFor(() => searchRows()[0]?.textContent.includes("nested-37"), "Short-page continuation skipped matches");
    check(document.activeElement === searchNext(), "Retried search page did not restore paging focus");
    check(calls.filter(call => call.command === "get_search_results").at(-1).args.skip === 37, "Short-page continuation used a fixed offset");
    check(!searchCheckbox().checked && selectionCount() === "1 file selected", "Paging lost or applied selection to the wrong row");
    searchCheckbox().click();
    const selectPage = button("Select this page");
    selectPage.focus();
    await pressKey("Enter");
    await waitFor(() => button("Deselect this page") === selectPage, "Keyboard page selection did not finish updating");
    check(document.activeElement === selectPage
      && searchRows().every(row => searchCheckbox(row)?.checked) && selectionCount() === "38 files selected",
    "Keyboard page selection did not handle the short page or preserve the earlier selection");
    await pressKey("Enter");
    await waitFor(() => button("Select this page") === selectPage, "Keyboard page deselection did not finish updating");
    check(document.activeElement === selectPage && searchRows().every(row => !searchCheckbox(row)?.checked)
      && selectionCount() === "1 file selected", "Deselecting the page changed the selection on another page");
    searchCheckbox().click();
    check(selectionCount() === "2 files selected", "Selection count did not include both pages");
    button("Previous").focus();
    await pressKey("Enter");
    await waitFor(() => searchRows()[0]?.textContent.includes("nested-0"), "Short-page Previous failed");
    check(document.activeElement === searchNext(), "First search page did not focus Next");
    check(JSON.stringify(searchRows().map(row => row.textContent)) === JSON.stringify(firstNestedNames), "Previous changed short-page boundaries");
    check(searchCheckbox().checked && selectionCount() === "2 files selected", "Previous lost cross-page selection");
    button("Clear selection").focus();
    await pressKey("Enter");
    check(!searchCheckbox().checked && !selectionCount() && document.activeElement.id === "search-input",
      "Keyboard clearing did not reset selection and restore focus");
    searchCheckbox().click();
    searchFor("zzz-no-match");
    await waitFor(() => document.body.textContent.includes("No matching names"), "Empty search state missing");
    failSearch = true;
    searchFor("file");
    await waitFor(() => button("Retry"), "Search failure not shown");
    button("Retry").click();
    await waitFor(() => searchRows().length === 100, "Search retry failed");
    malformedSearch = true;
    searchFor("nested");
    await waitFor(() => button("Retry"), "Malformed search response did not offer retry");
    check(searchRows().length === 0, "Malformed search response retained rows");
    button("Retry").click();
    await waitFor(() => searchRows().length === nestedCount, "Malformed search response did not recover");
    check(!searchCheckbox().checked && !selectionCount(), "Returning to an old query restored its selection");
    searchFor("zzz-no-match");
    await waitFor(() => document.body.textContent.includes("No matching names"), "Pre-delete empty state missing");
    searchFor("file");
    await waitFor(() => searchRows().length === 100, "Search results missing before delete");
    searchNext().click();
    await waitFor(() => searchRows()[0]?.textContent.includes(" file-100 "), "Second page missing before delete");
    // Keep " file-0 "/" file-1 " for the later confirmation and
    // partial-failure phases; delete another root file so the search row
    // disappears on the revision refresh.
    const target = searchRows().find(row => !row.textContent.includes("/large-folder/")
      && !row.textContent.includes(" file-0 ") && !row.textContent.includes(" file-1 "));
    searchCheckbox(target).click();
    check(selectionCount() === "1 file selected", "Search target could not be selected before deletion");
    const targetLabel = target.querySelector('[aria-label^="Delete "]').getAttribute("aria-label");
    const deletesBeforeSearch = calls.filter(call => call.command === "delete_item").length;
    const trigger = target.querySelector('[aria-label^="Delete "]');
    trigger.focus();
    check(document.activeElement === trigger, "Search delete trigger cannot receive focus");
    holdDetail = true;
    const pendingConfirmation = pressKey("Enter");
    await waitFor(() => releaseDetail, "Delete detail request did not start");
    const rescanTrigger = document.querySelector("#btn-rescan");
    rescanTrigger.focus();
    check(document.activeElement === rescanTrigger, "Focus did not move during the detail request");
    releaseDetail();
    await pendingConfirmation;
    await waitFor(() => button("NUKE IT"), "Keyboard did not open search confirmation");
    const dialog = document.querySelector("dialog");
    check(dialog?.matches(":modal"), "Confirmation is not a native modal dialog");
    check(document.getElementById(dialog.getAttribute("aria-labelledby"))?.textContent === "Delete Item?", "Dialog has no accessible name");
    check(document.activeElement === button("Cancel"), "Confirmation did not focus the safe Cancel action");
    document.querySelector("#btn-rescan").focus();
    check(dialog.contains(document.activeElement), "Background stole modal focus");
    for (const key of ["Tab", "Shift+Tab"]) {
      for (let index = 0; index < 4; index++) {
        const previousFocus = document.activeElement;
        await pressKey(key);
        check(dialog.contains(document.activeElement) && document.activeElement !== previousFocus,
          `${key} did not move focus within the confirmation`);
      }
    }
    await pressKey("Escape");
    await waitFor(() => !document.querySelector("dialog") && document.activeElement === trigger, "Escape did not cancel and restore trigger focus");
    check(calls.filter(call => call.command === "delete_item").length === deletesBeforeSearch, "Escape issued a delete");
    await pressKey("Enter");
    await waitFor(() => document.activeElement === button("Cancel"), "Reopened confirmation lost safe focus");
    await pressKey("Enter");
    await waitFor(() => !document.querySelector("dialog") && document.activeElement === trigger, "Cancel did not restore trigger focus");
    check(calls.filter(call => call.command === "delete_item").length === deletesBeforeSearch, "Default Enter issued a delete");
    trigger.click();
    await waitFor(() => button("NUKE IT"), "Search confirmation missing");
    button("NUKE IT").click();
    await waitFor(() => !document.querySelector(`[aria-label="${targetLabel}"]`), "Deleted search row survived revision refresh");
    await waitFor(() => searchRows()[0]?.textContent.includes(" file-0 "), "Deletion did not restart search pagination");
    check(calls.filter(call => call.command === "get_search_results").at(-1).args.skip === 0, "Revision refresh retained the old offset");
    check(!button("Previous"), "Previous remained enabled after revision reset");
    check(!searchCheckbox().checked && !selectionCount(), "Selection survived a deletion revision");
    check(calls.filter(call => call.command === "delete_item").length === deletesBeforeSearch + 1, "Search deletion count wrong");
    check(calls.filter(item => item.command === "run_scan").length === scanCount + 1, "Search browsing rescanned the phone");
    button("Storage map").click();
    await waitFor(() => rows().length === 129, "Map missing after search");

    zoomFolder();
    await waitFor(() => button("← Back to Root"), "Zoom navigation missing");
    button("← Back to Root").click();
    await waitFor(() => rows()[0]?.textContent.includes("fixture") && !button("← Back to Root"), "Root did not reload");
    // Folder expansion persists across zoom. Close it to isolate the late
    // root-view response from an independent, valid child-directory query.
    const folder = rows().find(item => item.textContent.includes("large-folder"));
    if (folder.querySelector('[aria-expanded="true"]')) folder.querySelector('[aria-expanded]').click();
    await pause(350);
    check(rows().length === 129 && !button("← Back to Root"), "Late zoom replaced root view");
    await waitFor(() => [...document.querySelectorAll("svg text")].some(item => item.textContent === "Other"), "Other tile missing");
    const before = calls.filter(item => item.command === "get_scan_view").length;
    const other = [...document.querySelectorAll("svg text")].find(item => item.textContent === "Other");
    other.dispatchEvent(new MouseEvent("click", { bubbles: true }));
    await pause(30);
    check(calls.filter(item => item.command === "get_scan_view").length === before, "Other tile zoomed");

    const mapFolder = document.querySelector('svg [role="button"][aria-label^="large-folder"]');
    check(mapFolder, "Storage map folder is not keyboard accessible");
    mapFolder.focus();
    check(document.activeElement === mapFolder, "Storage map folder did not receive focus");
    await pressKey("Enter");
    await waitFor(() => button("← Back to Root") && rows().length === 129, "Keyboard map zoom failed");
    await waitFor(() => document.querySelector('svg [role="button"]'), "Zoomed map did not render");
    const mapToggle = button("Hide map");
    const mapPanel = document.getElementById(mapToggle.getAttribute("aria-controls"));
    check(mapPanel && !mapPanel.hidden && mapToggle.getAttribute("aria-expanded") === "true",
      "Toggle does not announce the visible map");
    const zoomedViewport = document.querySelector('[aria-label="Files and folders"]');
    const shownBounds = zoomedViewport.getBoundingClientRect();
    const zoomedRoot = zoomedViewport.querySelector('[role="treeitem"][aria-level="1"]');
    const zoomQueries = calls.filter(call => call.command === "get_scan_view").length;
    button("Package folders").focus();
    await pressKey("Tab");
    check(document.activeElement === mapToggle, "Map toggle is missing from the keyboard tab order");
    await pressKey("Enter");
    await waitFor(() => mapPanel.hidden && button("Show map") === mapToggle, "Keyboard did not hide the map");
    const hiddenBounds = zoomedViewport.getBoundingClientRect();
    check(mapToggle.getAttribute("aria-expanded") === "false" && !mapPanel.querySelector("svg"),
      "Hidden map did not clear its tiles or announce its state");
    check(document.activeElement === mapToggle, "Hiding the map lost toggle focus");
    check(hiddenBounds.width > shownBounds.width || hiddenBounds.height > shownBounds.height,
      `Hiding the map did not grow the file pane: ${shownBounds.width}×${shownBounds.height} to ${hiddenBounds.width}×${hiddenBounds.height}`);
    await pressKey("Enter");
    await waitFor(() => !mapPanel.hidden && mapPanel.querySelector('svg [role="button"]'), "Keyboard did not restore the map");
    check(document.activeElement === mapToggle && mapToggle.getAttribute("aria-expanded") === "true",
      "Restoring the map lost focus or did not announce the visible state");
    check(zoomedViewport.querySelector('[role="treeitem"][aria-level="1"]') === zoomedRoot
      && zoomedRoot.getAttribute("aria-expanded") === "true" && rows().length === 129
      && calls.filter(call => call.command === "get_scan_view").length === zoomQueries,
    "Toggling the map reset the current folder or its expanded rows");
    button("← Back to Root").click();
    await waitFor(() => !button("← Back to Root") && rows().some(row => row.textContent.includes("large-folder")), "Map zoom did not return to root");

    for (const invalidPath of ["object", "outside"]) {
      badDetail = invalidPath;
      const toastsBeforeBadDetail = new Set(document.querySelectorAll("#toast-container > div"));
      const deletesBeforeBadDetail = calls.filter(call => call.command === "delete_item").length;
      document.querySelector('[aria-label="Delete  file-0 "]').click();
      await waitFor(() => !document.querySelector("#btn-rescan") || button("NUKE IT") || [...document.querySelectorAll('#toast-container [role="alert"]')].some(toast =>
        !toastsBeforeBadDetail.has(toast) && toast.textContent.includes("Scan node response does not match this scan")), "Malformed confirmation was not reported");
      check(document.querySelector("#btn-rescan") && !button("NUKE IT"), "Malformed confirmation crashed results or opened a delete dialog");
      check(calls.filter(call => call.command === "delete_item").length === deletesBeforeBadDetail, "Malformed confirmation issued a delete");
    }

    document.querySelector('[aria-label="Delete  file-0 "]').click();
    document.querySelector("#btn-rescan").click();
    await waitFor(() => rows().length === 129, "Rescan did not reload");
    await waitFor(() => document.querySelector("#scan-history")?.textContent.includes("No change since"), "Unchanged comparison missing after rescan");
    await pause(350);
    check(!button("NUKE IT"), "Old confirmation survived rescan");
    button("Largest files").click();
    await waitFor(() => largestRows().length === 25, "Largest files missing before delete");
    document.querySelector('[aria-label="Delete  file-0 "]').click();
    await waitFor(() => button("NUKE IT"), "Confirmation missing");
    check(document.body.textContent.includes("/fixture/ file-0 "), "Exact confirmation path missing");
    button("NUKE IT").click();
    await waitFor(() => largestRows().length === 25 && !document.querySelector('[aria-label="Delete  file-0 "]'), "Deleted largest row survived revision refresh");
    const historyLine = () => document.querySelector("#scan-history")?.textContent ?? "";
    await waitFor(() => historyLine().includes("Since the previous scan"), "Deletion delta comparison missing");
    check(historyLine().includes("-1 files"), "Deletion did not change the comparison delta");
    button("Storage map").click();
    await waitFor(() => rows().length === 129 && !document.querySelector('[aria-label="Delete  file-0 "]'), "Deleted map row survived revision refresh");
    check(calls.some(item => item.command === "delete_item" && item.args.nodeId === 2 && !("path" in item.args)), "ID-only delete was not invoked");

    button("Largest files").click();
    await waitFor(() => largestRows().length === 25, "Largest files did not refresh after deletion");
    check(!largestRows().some(row => row.textContent.includes("/fixture/ file-0 ")), "Deleted largest file survived revision");
    button("File types").click();
    await waitFor(typesReady, "File types did not refresh after deletion");
    checkTypes(735);
    const filteredPanel = () => document.querySelector('section[aria-label="Files by type"]');
    const typeButton = kind => typesPanel()?.querySelector(`[data-kind="${kind}"] button`);
    const categoryQuery = () => calls.filter(call => call.command === "get_search_results" && call.args.fileType).at(-1).args;
    typeButton("no_extension").focus();
    await pressKey("Enter");
    await waitFor(() => searchRows().length === 37, "File-type drilldown did not open from the keyboard");
    check(filteredPanel().querySelector("h2").textContent === "No extension" && document.activeElement === button("Clear filter"),
      "File-type filter or keyboard focus missing");
    check(categoryQuery().skip === 0 && categoryQuery().fileType === "no_extension" && categoryQuery().folderId === null,
      "File-type drilldown sent the wrong first-page filter");
    holdSearch = true;
    resolveSearch = undefined;
    button("Next").focus();
    await pressKey("Enter");
    await waitFor(() => resolveSearch && categoryQuery().skip === 37, "File-type continuation skipped the short first page");
    button("Clear filter").focus();
    await pressKey("Enter");
    await waitFor(typesReady, "Keyboard did not clear the file-type filter");
    check(document.activeElement === typeButton("no_extension"), "Clearing the filter did not restore category focus");
    typeButton("images").click();
    await waitFor(() => filteredPanel()?.textContent.includes("No files of this type"), "Empty category did not render");
    resolveSearch();
    resolveSearch = undefined;
    await pause(30);
    check(searchRows().length === 0 && categoryQuery().fileType === "images" && categoryQuery().skip === 0,
      "A late category page crossed filters");
    check(document.activeElement === button("Clear filter"), "A late category page took focus from the new filter");
    button("Clear filter").click();
    await waitFor(typesReady, "File-type summary did not return");
    typeButton("no_extension").click();
    await waitFor(() => searchRows().length === 37 && categoryQuery().skip === 0, "Reopened category retained an old offset");
    failSearch = true;
    button("Next").focus();
    await pressKey("Enter");
    await waitFor(() => button("Retry") && document.activeElement === button("Retry"), "Failed category page did not focus Retry");
    await pressKey("Enter");
    await waitFor(() => searchRows()[0]?.textContent.includes(" file-38 ") && categoryQuery().skip === 37, "Second category page lost its first match");
    check(document.activeElement === button("Next"), "Retried category page did not restore paging focus");
    const revisionBeforeCategoryDelete = revision;
    filteredPanel().querySelector('[aria-label="Delete  file-38 "]').click();
    await waitFor(() => button("NUKE IT"), "Category file did not open the existing confirmation");
    button("NUKE IT").click();
    await waitFor(() => searchRows()[0]?.textContent.includes(" file-1 ")
      && categoryQuery().revision === revisionBeforeCategoryDelete + 1 && categoryQuery().skip === 0,
    "Category deletion did not refresh the filter at the new revision");
    check(calls.filter(call => call.command === "delete_item").at(-1).args.nodeId === 40,
      "Category deletion did not use the selected node ID");
    button("Clear filter").click();
    await waitFor(typesReady, "File type totals did not refresh after category deletion");
    checkTypes(734);
    button("Package folders").click();
    await waitFor(() => appRows().length === 100, "Package view missing after deletion");
    check(calls.filter(call => call.command === "get_app_usage").at(-1).args.revision === revision,
      "Package query used a stale deletion revision");
    button("Largest files").click();
    await waitFor(() => largestRows().length === 25, "Largest files missing after type refresh");
    const nested = largestRows().find(row => row.textContent.includes("/large-folder/"));
    if (nested) nested.querySelector("button").click(); else button("Storage map").click();
    await waitFor(() => rows().length > 0, "Map missing after largest-files navigation");
    if (button("← Back to Root")) { button("← Back to Root").click(); await waitFor(() => rows()[0]?.textContent.includes("fixture"), "Root missing"); }
    zoomFolder();
    await waitFor(() => rows().some(item => item.textContent.includes("nested-0")), "Nested directory missing");
    button("Next").click();
    await waitFor(() => rows().length === 73, "Nested final page missing");
    button("← Back to Root").click();
    await waitFor(() => document.querySelector('[aria-label="Delete  file-1 "]'), "Root after zoom missing");
    failDelete = true;
    document.querySelector('[aria-label="Delete  file-1 "]').click();
    await waitFor(() => button("NUKE IT"), "Second confirmation missing");
    button("NUKE IT").click();
    await waitFor(() => document.querySelector("#btn-connect") && !document.querySelector("#btn-connect").disabled, "Partial failure did not clear results");
    check(rows().length === 0, "Invalid snapshot remained visible");
    // Setup refreshes discovery after stopping; it must not replace the stop
    // as the final operation with device-side/session authority.
    check(calls.filter(call => call.command !== "list_devices").at(-1).command === "stop_daemon", "Partial failure did not stop session");

    failDelete = false;
    readOnly = true;
    coverageErrors = 2;
    coverageSkipped = 3;
    unreadableDirectories = { paths: [`${scanRoot}/large-folder`], omitted: 0 };
    document.querySelector("#btn-connect").click();
    await waitFor(() => rows().length === 129, "Read-only page missing");
    check(document.body.textContent.includes("Deletion disabled"), "Read-only banner missing");
    const unreadablePaths = document.querySelector('[aria-label="Unreadable folder paths"]');
    const unreadableDetails = unreadablePaths?.closest("details");
    check(unreadableDetails && !unreadableDetails.open, "Unreadable paths should start collapsed");
    const unreadableSummary = unreadableDetails.querySelector("summary");
    check(unreadableSummary.textContent.includes("1 folder could not be read"), "Unreadable folder count missing");
    unreadableSummary.click();
    await waitFor(() => unreadableDetails.open, "Unreadable paths did not expand");
    check(unreadablePaths.textContent === unreadableDirectories.paths[0]
      && !unreadablePaths.querySelector("a, button"), "Unreadable paths or actions are incorrect");
    unreadableSummary.click();
    await waitFor(() => document.querySelector("#scan-history")?.textContent.includes("comparison unavailable"), "Partial scan claimed a history comparison");
    check(!document.querySelector('[aria-label^="Delete "]'), "Read-only deletion enabled");
    button("Package folders").click();
    await waitFor(() => appRows().length === 100, "Read-only package view missing");
    check(appsPanel().textContent.includes("2 access errors") && !appsPanel().querySelector('[aria-label^="Delete "]'),
      "Read-only package coverage or controls are incorrect");
    button("Largest files").click();
    await waitFor(() => largestRows().length === 25, "Read-only largest files missing");
    check([...document.querySelectorAll('.largest-file-row button[aria-label^="Delete "]')].every(item => item.disabled), "Read-only largest deletion enabled");
    button("Search").click();
    await waitFor(() => document.querySelector("#search-input"), "Read-only search controls missing");
    searchFor("file");
    await waitFor(() => searchRows().length > 0, "Read-only search results missing");
    check(searchRows().length > 0 && [...document.querySelectorAll('.search-result-row button[aria-label^="Delete "]')].every(item => item.disabled), "Read-only search deletion enabled");
    button("Storage map").click();
    await waitFor(() => rows().length === 129, "Read-only map missing after search");
    button("File types").click();
    await waitFor(typesReady, "Read-only file types missing");
    checkTypes(736);
    check(typesPanel().textContent.includes("2 access errors") && typesPanel().textContent.includes("3 excluded or duplicate entries") && typesPanel().textContent.includes("/fixture"), "File-type coverage context missing");
    typeButton("no_extension").click();
    await waitFor(() => searchRows().length === 37, "Read-only category results missing");
    check(searchRows().every(row => row.querySelector('[aria-label^="Delete "]').disabled), "Read-only category deletion enabled");
    button("Storage map").click();
    await waitFor(() => rows().length === 129, "Read-only map missing");
    const previousAcknowledgements = () => (document.body.textContent.match(/Daemon acknowledged shutdown\./g) ?? []).length;
    document.querySelector("#btn-disconnect").click();
    await waitFor(() => document.querySelector("#btn-connect") && !document.querySelector("#btn-connect").disabled, "Acknowledged stop did not release the UI");
    check(previousAcknowledgements() === 1, "Acknowledged stop was not reported accurately");
    for (const outcome of ["unreachable", "invalid", "error-status", "wrong-ack"]) {
      stopOutcome = outcome;
      document.querySelector("#btn-connect").click();
      await waitFor(() => rows().length === 129, "Reconnect after stop failed");
      const warnings = (document.body.textContent.match(/daemon shutdown could not be confirmed:/g) ?? []).length;
      const priorStops = calls.filter(item => item.command === "stop_daemon").length;
      const disconnect = document.querySelector("#btn-disconnect");
      disconnect.click();
      disconnect.click();
      await waitFor(() => disconnect.disabled && document.querySelector("#btn-rescan").disabled, "Stop allowed overlapping actions");
      await waitFor(() => document.querySelector("#btn-connect") && !document.querySelector("#btn-connect").disabled, "Unconfirmed stop did not release the UI");
      check(previousAcknowledgements() === 1, "Unconfirmed stop was reported as acknowledged");
      check((document.body.textContent.match(/daemon shutdown could not be confirmed:/g) ?? []).length === warnings + 1, "Missing unconfirmed-stop warning");
      check(calls.filter(item => item.command === "stop_daemon").length === priorStops + 1, "Duplicate stop request");
      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");
    await waitFor(() => !document.querySelector("#btn-refresh-devices").disabled, "Post-stop device refresh did not finish");
    check(picker().value === "phone-two", "Stop forgot the selected phone");
    const previousGeneration = scope().generation;
    readOnly = false;
    coverageErrors = 0;
    coverageSkipped = 0;
    unreadableDirectories = undefined;
    stopOutcome = "acknowledged";
    selectDevice("phone-one");
    await waitFor(() => picker().value === "phone-one" && document.querySelector("#btn-connect:enabled"),
      "Connect did not become ready for phone-one");
    document.querySelector("#btn-connect").click();
    await waitFor(() => rows().length === 129, "Explicit device switch did not scan");
    check(activeDevice === "phone-one" && scope().generation !== previousGeneration && document.querySelector("#connected-device").textContent.includes("phone-one"), "Device switch reused old results/identity");
    await waitFor(() => document.querySelector("#scan-history")?.textContent.includes("No previous comparable scan"), "Cross-device comparison reused another device's baseline");
    check(!button("NUKE IT"), "Device switch retained a destructive confirmation");
    check(!document.querySelector('[aria-label="Unreadable folder paths"]'), "Device switch retained prior scan diagnostics");
    const deleteCallsBeforeSwitch = calls.filter(call => call.command === "delete_item").length;
    document.querySelector('[aria-label="Delete  file-0 "]').click();
    await waitFor(() => button("NUKE IT"), "Cross-device confirmation fixture did not open");
    document.querySelector("#btn-disconnect").click();
    await waitFor(() => document.querySelector("#btn-connect") && !document.querySelector("#btn-connect").disabled, "Stop with a pending confirmation did not finish");
    check(!button("NUKE IT") && picker().value === "phone-one", "Stop retained confirmation or forgot selection");
    selectDevice("phone-two");
    await waitFor(() => picker().value === "phone-two" && document.querySelector("#btn-connect:enabled"),
      "Connect did not become ready for phone-two");
    document.querySelector("#btn-connect").click();
    await waitFor(() => rows().length === 129, "Switch back to the second phone failed");
    check(activeDevice === "phone-two" && !button("NUKE IT") && calls.filter(call => call.command === "delete_item").length === deleteCallsBeforeSwitch, "An old confirmation crossed device sessions");
    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");
    emptyScan = true;
    document.querySelector("#btn-rescan").click();
    await waitFor(() => rows().length === 1, "Empty scan missing");
    button("File types").click();
    await waitFor(typesReady, "Empty file-type summary missing");
    checkTypes(0);
    check(typesPanel().textContent.includes("No counted files") && !typesPanel().textContent.includes("NaN") && !typesPanel().textContent.includes("Infinity"), "Empty file-type view is misleading");
    failView = true;
    await activate(button("Storage map"));
    await waitFor(() => button("Retry"), "Empty-directory query error missing");
    await activate(button("Retry"));
    await waitFor(() => rows().length === 1 && document.activeElement?.dataset.treeNode === "0",
      "Empty-directory retry did not focus its row without paging controls");
    button("Package folders").click();
    await waitFor(() => appsPanel()?.textContent.includes("No package folders were recognized"),
      "Empty package view did not retain unknown-coverage wording");
    check(appRows().length === 0 && appsPanel().textContent.includes("Full app totals remain unknown"),
      "Empty package view claimed complete app usage");
    // Exercise the actual App callbacks: duplicate/sibling actions must not
    // queue behind a rescan, and its guard must release on every outcome.
    for (const outcome of ["failure", "cancel"]) {
      const scansBefore = calls.filter(call => call.command === "run_scan").length;
      const stopsBefore = calls.filter(call => call.command === "stop_daemon").length;
      const rescanButton = document.querySelector("#btn-rescan");
      const stopButton = document.querySelector("#btn-disconnect");
      if (outcome === "failure") failScan = true; else holdScan = true;
      rescanButton.click();
      rescanButton.click();
      stopButton.click();
      check(calls.filter(call => call.command === "run_scan").length === scansBefore + 1, "Duplicate failed/pending rescan queued another scan");
      check(calls.filter(call => call.command === "stop_daemon").length === stopsBefore, "Disconnect competed with a pending rescan");
      if (outcome === "cancel") {
        await waitFor(() => heldScan && button("Cancel scan"), "Pending rescan cannot be cancelled");
        const pendingId = heldScan.scanId;
        button("Cancel scan").click();
        check(calls.some(call => call.command === "cancel_scan" && call.args.scanId === pendingId), "Rescan cancellation was not sent");
      }
      await waitFor(() => document.querySelector("#btn-connect") && !document.querySelector("#btn-connect").disabled, "Failed/cancelled rescan did not return to ready setup");
      check(rows().length === 0, "Failed/cancelled rescan retained old results");
      check(calls.filter(call => call.command === "stop_daemon").length === stopsBefore + 1, "Rescan failure did not clean up exactly once");
      document.querySelector("#btn-connect").click();
      await waitFor(() => rows().length === 1, "Rescan guard remained held after failure/cancellation");
      check(calls.filter(call => call.command === "run_scan").length === scansBefore + 2, "Recovery did not start exactly one fresh scan");
    }
    // A deep scan root keeps the catalog consistent without inventing parent IDs.
    emptyScan = false;
    scanRoot = "/" + Array.from({ length: 29 }, (_, index) => `directory-${index}-${"d".repeat(60)}`).join("/") + "/fixture";
    document.querySelector("#btn-rescan").click();
    await waitFor(() => rows().length === 129, "Deep-root scan did not render");
    const deletesBeforeLongPath = calls.filter(call => call.command === "delete_item").length;
    document.querySelector('[aria-label="Delete  file-0 "]').click();
    await waitFor(() => button("NUKE IT"), "Long-path confirmation missing");
    const fullPath = `${scanRoot}/ file-0 `;
    const longPath = [...document.querySelectorAll("p")].find(item => item.textContent === fullPath);
    check(longPath, "Confirmation truncated or changed the long path");
    for (const action of [button("Cancel"), button("NUKE IT")]) {
      const bounds = action.getBoundingClientRect();
      check(bounds.top >= 0 && bounds.bottom <= innerHeight && bounds.left >= 0 && bounds.right <= innerWidth,
        `Long-path action outside viewport: ${bounds.top}..${bounds.bottom} of ${innerHeight}`);
      const hit = document.elementFromPoint((bounds.left + bounds.right) / 2, (bounds.top + bounds.bottom) / 2);
      check(action === hit || action.contains(hit), "Long-path action is obscured");
    }
    check(longPath.scrollHeight > longPath.clientHeight, "Long path has no scrollable area");
    check(longPath.tabIndex === 0, "Long path cannot be reached by keyboard");
    longPath.focus();
    check(document.activeElement === longPath, "Long path cannot receive keyboard focus");
    longPath.scrollTop = longPath.scrollHeight;
    check(longPath.scrollTop > 0, "Long path cannot be scrolled");
    const lastCharacter = document.createRange();
    lastCharacter.setStart(longPath.firstChild, fullPath.length - 1);
    lastCharacter.setEnd(longPath.firstChild, fullPath.length);
    const lastBounds = lastCharacter.getBoundingClientRect();
    const pathBounds = longPath.getBoundingClientRect();
    check(lastBounds.top >= pathBounds.top && lastBounds.bottom <= pathBounds.bottom, "End of long path is unreachable");
    button("Cancel").click();
    await waitFor(() => !button("NUKE IT"), "Long-path confirmation did not cancel");
    check(calls.filter(call => call.command === "delete_item").length === deletesBeforeLongPath, "Long-path cancellation issued a delete");
    // Paging bounds each directory, while expanded siblings can accumulate.
    wideFolders = true;
    scanRoot = "/fixture";
    const viewportSettled = () => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)));
    document.querySelector("#btn-rescan").click();
    await waitFor(() => rows().length === 129 && document.querySelector('[aria-label="Delete wide-128"]'),
      "Wide-folder baseline did not load");
    const expanders = () => [...document.querySelectorAll('.file-row button[aria-expanded]')].slice(1);
    check(expanders().length === 128, "Wide-folder baseline lost directory entries");
    const expansionStarted = performance.now();
    for (const toggle of expanders()) toggle.click();
    const logicalRows = () => Number(document.querySelector('[role="tree"]').dataset.logicalRows);
    await waitFor(() => logicalRows() === 1 + 128 + 128 * 128, "Expanded folders omitted logical entries", 10000);
    await viewportSettled();
    const expansionMs = performance.now() - expansionStarted;
    const mountedRows = rows().length;
    check(mountedRows < 100, `Expanded tree mounted ${mountedRows} rows`);
    const focused = document.querySelector('[aria-label="Delete entry-1-0"]');
    focused.focus();
    check(document.activeElement === focused, "Expanded file action could not receive keyboard focus");
    const viewport = focused.closest("section");
    const scrollStarted = performance.now();
    viewport.scrollTop = viewport.scrollHeight;
    await viewportSettled();
    const scrollMs = performance.now() - scrollStarted;
    check(viewport.scrollTop > 0 && document.activeElement === focused, "Expanded-tree scrolling dropped keyboard focus");
    await waitFor(() => document.querySelector('[aria-label="Delete entry-128-127"]'), "Final virtual entry missing");
    check(rows().length < 100, "Scrolling grew the mounted-row bound");
    const last = document.querySelector('[aria-label="Delete entry-128-127"]');
    last.focus();
    await viewportSettled();
    check(document.activeElement === last, "Final expanded entry could not receive keyboard focus");
    const finalRowBounds = last.getBoundingClientRect();
    const viewportBounds = viewport.getBoundingClientRect();
    check(finalRowBounds.top >= viewportBounds.top && finalRowBounds.bottom <= viewportBounds.bottom,
      "Final expanded entry could not be scrolled into view");
    const wideMapToggle = button("Hide map");
    wideMapToggle.focus({ preventScroll: true });
    for (const visible of [false, true]) {
      await pressKey("Enter");
      await viewportSettled();
      check(document.activeElement === wideMapToggle && wideMapToggle.getAttribute("aria-expanded") === String(visible),
        "Toggling the map beside a virtualized tree lost toggle focus");
      check(logicalRows() === 1 + 128 + 128 * 128 && rows().length < 100,
        "Toggling the map reset expansion or broke the virtual row bound");
      check(viewport.querySelector('[data-tree-node="17383"][tabindex="0"] button[aria-label="Delete entry-128-127"]') === last,
        "Toggling the map discarded the active virtual row");
    }
    last.focus({ preventScroll: true });
    await pressKey("Home");
    await waitFor(() => document.activeElement?.dataset.treeNode === "0", "Home did not focus the first tree entry");
    await pressKey("ArrowDown");
    await waitFor(() => document.activeElement?.dataset.treeNode === "1", "ArrowDown did not focus the folder");
    await pressKey("ArrowLeft");
    await waitFor(() => logicalRows() === 1 + 128 + 127 * 128, "ArrowLeft did not collapse the focused folder");
    await pressKey("ArrowRight");
    await waitFor(() => logicalRows() === 1 + 128 + 128 * 128, "ArrowRight did not restore the focused folder");
    await pressKey("End");
    await waitFor(() => document.activeElement?.dataset.treeNode === "17383", "End did not reach the last logical entry");
    await pressKey("Tab");
    const deleteTrigger = document.querySelector('[aria-label="Delete entry-128-127"]');
    check(document.activeElement === deleteTrigger, "Last virtual entry action was unreachable by Tab");
    await pressKey("Enter");
    await waitFor(() => document.querySelector("dialog")?.matches(":modal"), "Virtual entry did not open confirmation");
    await pressKey("Escape");
    await waitFor(() => !document.querySelector("dialog") && document.activeElement === deleteTrigger,
      "Virtualized confirmation did not restore its trigger");
    await pressKey("Home");
    await waitFor(() => document.activeElement?.dataset.treeNode === "0", "Home did not restore root focus");
    const collapseStarted = performance.now();
    await pressKey("ArrowLeft");
    await waitFor(() => logicalRows() === 1 && rows().length === 1, "Root collapse retained virtual descendants");
    await viewportSettled();
    check(document.activeElement?.dataset.treeNode === "0", "Root collapse dropped keyboard focus");
    expandedTree = {
      directories: 128, entries_per_directory: 128, logical_rows: 1 + 128 + 128 * 128,
      mounted_rows: mountedRows, collapsed_rows: rows().length,
      expansion_ms: Math.round(expansionMs), scroll_ms: Math.round(scrollMs),
      root_collapse_ms: Math.round(performance.now() - collapseStarted),
    };
    wideFolders = false;
    button("↻ Rescan").click();
    await waitFor(() => rows().length === 129, "Ordinary tree missing before focus rescan check");
    const releaseRescannedPage = await holdPage(button("Next"));
    const oldGeneration = generation;
    await activate(document.querySelector("#btn-rescan"));
    await waitFor(() => generation > oldGeneration && rows().length === 129, "Rescan during held page did not finish");
    const freshFocus = document.querySelector("#btn-rescan");
    freshFocus.focus();
    releaseRescannedPage();
    await pause(30);
    check(document.activeElement === freshFocus && visibleNames()[0] === "large-folder",
      "Superseded generation restored old directory focus or entries");
    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");
    report(true);
  })().catch(error => report(false, error.stack ?? String(error)));
})();