Skip to content

A high-performance Android storage analyzer that bypasses MTP using a native C++ daemon, a Rust TCP bridge, and a React Treemap UI.

Rust

Add explicit Android device selection (#67)

Vishnu Srivatsava294285037490
diff --git a/README.md b/README.md
index fbbbc11..1817212 100644
--- a/README.md
+++ b/README.md
@@ -99,6 +99,12 @@ Go to **Settings → About Phone → tap "Build Number" 7 times** to unlock Deve
That's it. No apps to install on your phone, no Wi-Fi setup, no root required.
+In a source build, choose the device in setup before connecting when multiple
+devices are ready. Refresh after plugging in or authorizing a phone. A selected
+device that disappears stays selected and blocks connection; another phone is
+never substituted automatically. See [device selection](docs/device-selection.md)
+for behavior and manual checks.
+
### Optional: scan with root access
This option is included in source builds and the next release; v1.1.1 does not
@@ -162,7 +168,7 @@ flowchart TB
end
subgraph Transport["ADB Protocol"]
- Tunnel["ADB Port Forwarding<br>TCP:5050 -> TCP:5050"]
+ Tunnel["Targeted ADB Port Forwarding<br>Allocated loopback ports"]
end
subgraph Device["Android Device"]
@@ -186,16 +192,19 @@ sequenceDiagram
participant D as C++ Daemon (Android)
%% Connect Phase
- U->>R: invoke("init_daemon")
- R->>A: pkill daemon (Cleanup)
- R->>A: push daemon /data/local/tmp
- R->>A: appops set MANAGE_EXTERNAL_STORAGE allow
- R->>A: Write private startup secret, launch daemon
- R->>A: adb forward tcp:5050 tcp:5050
+ U->>R: invoke("list_devices")
+ R->>A: adb devices -l
+ R-->>U: Serials, models and states
+ U->>R: invoke("init_daemon", { serial, rootMode })
+ R->>A: Release only this app's previous session
+ R->>A: Revalidate the chosen serial with adb devices -l
+ R->>A: -s serial: private directory, binary and startup secret
+ R->>A: -s serial: shell -T launch, allocate device port
+ R->>A: -s serial: forward --no-rebind tcp:0 tcp:device-port
R->>D: AUTH session secret (on every connection)
- R->>D: Ping-Retry Loop (150ms)
- D-->>R: ACK Connection
- R-->>U: Connected!
+ R->>D: PING with a bounded deadline
+ D-->>R: Protocol, UID and read-only handshake
+ R-->>U: Connected to selected serial
%% Scan Phase
U->>R: invoke("run_scan", { path, scanId, onProgress })
@@ -206,14 +215,15 @@ sequenceDiagram
R-->>U: Partial counts and recent entries
end
D-->>R: Completion totals, then EOF
- R-->>U: Validate and render finished tree
+ R-->>U: Validated scan summary and bounded directory pages
%% Delete Phase
- U->>R: invoke("delete_item", { path })
+ U->>R: invoke("delete_item", { generation, revision, nodeId })
+ Note over R: Resolve the allowed path from the current host scan
R->>D: TCP Send: `DELETE /sdcard/... \n`
Note over D: Descriptor-relative traversal and unlinkat<br/>Child symlinks are never followed
D-->>R: {"status":"ok"}
- R-->>U: Update UI / Rescan
+ R-->>U: Update summary/revision and refresh affected pages
```
---
diff --git a/docs/daemon-sessions.md b/docs/daemon-sessions.md
index c42e0ac..e03c726 100644
--- a/docs/daemon-sessions.md
+++ b/docs/daemon-sessions.md
@@ -24,8 +24,9 @@ port. It atomically publishes a complete 0600 `ready` record containing its port
and PID, without replacing an existing file or symlink. The host then asks ADB
for `forward --no-rebind tcp:0 tcp:<device-port>` and records the returned host
port. All subsequent device commands use the selected `-s <serial>` explicitly.
-Device selection still follows the existing first-authorized-device behavior;
-the selection UI remains [#4](https://github.com/VishnuSrivatsava/SocketSweep/issues/4).
+Setup offers [explicit device selection](device-selection.md). Startup checks
+that the chosen serial is still ready before creating new session resources;
+it never falls back to another serial.
The foreground daemon is launched through **`adb shell -T`**, with an owned stdin
pipe held open by the Rust session. `--session-ready` also enables its lifetime
diff --git a/docs/device-selection.md b/docs/device-selection.md
new file mode 100644
index 0000000..4d8cc73
--- /dev/null
+++ b/docs/device-selection.md
@@ -0,0 +1,80 @@
+# Selecting an Android device
+
+Tracked in [#4](https://github.com/VishnuSrivatsava/SocketSweep/issues/4).
+
+Setup lists the serial, available model, and state of devices reported by
+`adb devices -l`. Exactly one ready device is selected initially. With multiple
+ready devices, choose one explicitly before connecting. Offline, unauthorized,
+USB-permission-denied, and other unavailable states cannot be connected.
+
+Refresh updates the list. The chosen serial remains selected even when it
+disappears, becomes unavailable, or the list order changes. A disconnected
+selection stays visible and blocks Connect; choosing another phone is an
+explicit action. Selection survives refreshes, connection errors, and stopping
+within the running app. It is not saved across app restarts.
+If discovery fails, the selected device's status is unavailable rather than
+claimed disconnected; Connect stays blocked until discovery succeeds.
+
+Discovery runs on entering setup and on Refresh, without background polling.
+Its result is a snapshot. Connect checks the selected serial against a fresh
+list in Rust before pushing or launching the daemon. If it vanished after the
+displayed snapshot, startup fails; there is no first-device fallback. If it
+vanishes after that check, subsequent `-s` commands still target only that serial
+and fail normally. A model label is display text, never a connection identifier.
+Results show the serial that was selected for their session.
+
+## Ownership and bounds
+
+[ADB's documented CLI](https://android.googlesource.com/platform/packages/modules/adb/+/refs/heads/main/docs/user/adb.1.md)
+provides long device listing and explicit `-s SERIAL` targeting. No native ADB
+library is added. Listing uses the existing 15-second command deadline and
+256 KiB limits for each captured output stream. Invalid lists and duplicate
+serials fail rather than guessing a transport. Resolve duplicate serials by
+disconnecting duplicate transports; transport-ID selection is not implemented.
+
+Version checks and device discovery are host-wide read-only commands. Session
+startup, privilege checks, file operations, and forwarding cleanup retain the
+selected serial through [owned daemon sessions](daemon-sessions.md). Reconnect
+releases the app's previous session and invalidates scan authority before
+validating the requested device. A new scan gets a new generation; old IDs and
+destructive confirmations cannot be reused for a different session. Root mode
+still requires verified read-only root access and never restarts adbd.
+
+Refresh and selection are disabled during connection. Connect is disabled while
+discovery is pending/failed or the selected device is unavailable. A synchronous
+action guard prevents repeated clicks from starting duplicate connections.
+Discovery responses from a superseded request or a completed setup phase cannot
+replace current state. Native select/label controls retain keyboard access;
+unavailable states have visible explanations and status text.
+
+## Validation
+
+Rust parsing tests cover USB, wireless, emulator, model metadata, CRLF, empty and
+invalid output, unavailable states, and duplicate serials. A fake ADB fixture
+checks discovery afresh, starts the second selected serial with the real
+host-built daemon, and rejects unavailable/missing/invalid selections while
+another ready device remains listed. The fixture rejects any device command
+that does not target its configured serial. Existing same/different-serial
+session isolation, generation invalidation, authentication, deletion, and root
+tests remain enabled.
+
+Node tests cover initial selection, preservation, and status guidance. The
+built-UI mocked-IPC replay covers multiple ready devices, disabled unavailable
+options, model-text escaping, refresh locks/failure, unplugging, reordering,
+reconnection, a stale displayed device at startup, duplicate clicks, result
+identity, explicit switching, and confirmation invalidation. These fixtures do
+not prove real USB transport, physical hotplug timing, or root-manager behavior.
+
+No native app, real ADB, or phone test was run locally. For a manual check, build
+the app yourself using the README steps, then:
+
+1. Connect two authorized phones/emulators. Confirm that neither is chosen
+ initially and select the second one. Scan and verify the displayed serial.
+2. Stop, unplug that device, and refresh. It must remain selected as disconnected;
+ the other phone must not be used automatically.
+3. Reconnect/authorize it, refresh, and scan again. Also try unplugging between
+ Refresh and Connect; startup must fail instead of switching phones.
+4. Stop, explicitly select the other phone, and scan. Old results and deletion
+ confirmations must be gone. Root mode, if available, remains read-only.
+5. Repeat with two app instances; stopping one must leave the other's session
+ functional. Keep real device results separate from host/mock validation.
diff --git a/package.json b/package.json
index 80379bf..3dd8600 100644
--- a/package.json
+++ b/package.json
@@ -8,7 +8,7 @@
"dev": "vite",
"build": "tsc && vite build",
"lint": "eslint src tests vite.config.ts eslint.config.js --max-warnings 0",
- "test": "node --test tests/format_bytes.test.mjs tests/scan_view.test.mjs tests/log_history.test.mjs tests/lint_gate.test.mjs",
+ "test": "node --test tests/format_bytes.test.mjs tests/scan_view.test.mjs tests/log_history.test.mjs tests/lint_gate.test.mjs tests/devices.test.mjs",
"preview": "vite preview",
"tauri": "tauri"
},
diff --git a/src-tauri/src/devices.rs b/src-tauri/src/devices.rs
new file mode 100644
index 0000000..e518406
--- /dev/null
+++ b/src-tauri/src/devices.rs
@@ -0,0 +1,99 @@
+//! Discovery is read-only. Only an explicitly selected, currently ready serial
+//! may be handed to a session; discovery order never grants selection authority.
+use std::collections::HashSet;
+use std::path::Path;
+
+#[derive(Debug, serde::Serialize)]
+pub(super) struct Device {
+ serial: String,
+ state: String,
+ model: Option<String>,
+}
+
+pub(super) fn list(adb: &Path) -> Result<Vec<Device>, String> {
+ parse(&crate::adb(adb, &["devices", "-l"])?)
+}
+
+pub(super) fn require_selected(adb: &Path, serial: &str) -> Result<(), String> {
+ if serial.is_empty() || serial.chars().any(|c| c.is_whitespace() || c.is_control()) {
+ return Err("Choose a device before connecting.".into());
+ }
+ let devices = list(adb)?;
+ let device = devices
+ .iter()
+ .find(|device| device.serial == serial)
+ .ok_or("Selected device is disconnected. Refresh the list and choose a device.")?;
+ match device.state.as_str() {
+ "device" => Ok(()),
+ "unauthorized" => Err("Selected device is unauthorized. Unlock it and approve USB debugging, then refresh.".into()),
+ "offline" => Err("Selected device is offline. Reconnect it and refresh.".into()),
+ "no permissions" => Err("No USB permission for the selected device. Check your host's USB/udev permissions and refresh.".into()),
+ _ => Err("Selected device is not ready for scanning. Reconnect it and refresh.".into()),
+ }
+}
+
+fn parse(output: &str) -> Result<Vec<Device>, String> {
+ let mut lines = output.lines().filter(|line| !line.trim().is_empty());
+ if lines.next().map(str::trim) != Some("List of devices attached") {
+ return Err("ADB returned an invalid device list.".into());
+ }
+ let mut serials = HashSet::new();
+ let mut devices = Vec::new();
+ for line in lines {
+ let mut fields = line.split_whitespace();
+ let serial = fields.next().ok_or("Missing ADB device serial")?;
+ let state = fields.next().ok_or("Missing ADB device state")?;
+ if serial.chars().any(char::is_control) || !serials.insert(serial.to_string()) {
+ return Err("ADB reported invalid or duplicate device serials. Reconnect duplicate transports before scanning.".into());
+ }
+ let state = if state == "no" && fields.next() == Some("permissions") {
+ "no permissions"
+ } else {
+ state
+ };
+ let model = fields
+ .find_map(|field| field.strip_prefix("model:"))
+ .filter(|value| !value.is_empty())
+ .map(|value| value.replace('_', " "));
+ devices.push(Device {
+ serial: serial.into(),
+ state: state.into(),
+ model,
+ });
+ }
+ Ok(devices)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn parses_ready_usb_wireless_emulator_and_unavailable_devices() {
+ let output = "List of devices attached\r\nusb-one\tdevice usb:1 product:foo model:Pixel_9_Pro device:foo transport_id:1\r\n192.0.2.1:5555 device model:Tablet transport_id:2\r\nemulator-5554 offline transport_id:3\r\nphone-two unauthorized usb:2 transport_id:4\r\n???????????? no permissions (check udev rules); transport_id:5\r\nrecovery-phone recovery\r\n";
+ let devices = parse(output).unwrap();
+ assert_eq!(devices.len(), 6);
+ assert_eq!(devices[0].serial, "usb-one");
+ assert_eq!(devices[0].model.as_deref(), Some("Pixel 9 Pro"));
+ assert_eq!(devices[1].serial, "192.0.2.1:5555");
+ assert_eq!(devices[2].state, "offline");
+ assert_eq!(devices[3].state, "unauthorized");
+ assert_eq!(devices[4].state, "no permissions");
+ assert_eq!(devices[5].state, "recovery");
+ assert!(devices[5].model.is_none());
+ }
+
+ #[test]
+ fn empty_valid_lists_are_distinct_from_bad_or_ambiguous_output() {
+ assert!(parse("List of devices attached\n\n").unwrap().is_empty());
+ for output in [
+ "",
+ "error: no devices",
+ "one device",
+ "List of devices attached\none",
+ "List of devices attached\none device\none offline\n",
+ ] {
+ assert!(parse(output).is_err(), "accepted {output:?}");
+ }
+ }
+}
diff --git a/src-tauri/src/lib.rs b/src-tauri/src/lib.rs
index 7857475..3bd4c19 100644
--- a/src-tauri/src/lib.rs
+++ b/src-tauri/src/lib.rs
@@ -2,8 +2,8 @@
// lib.rs — SocketSweep Tauri Bridge (Phase 2)
// ============================================================================
// Orchestrates the C++ Android daemon via ADB and communicates with it
-// over a TCP tunnel. All commands return Result<String, String> so the
-// React frontend can display meaningful error messages.
+// over a TCP tunnel. Commands return typed data or protocol JSON, with errors
+// the React frontend can display meaningfully.
//
// Wire protocol (matches Phase 1 daemon):
// Each connection starts with "AUTH <session token>\n", then one command.
@@ -20,6 +20,7 @@ use tauri::ipc::Channel;
mod scan_stream;
mod scan_store;
mod session;
+mod devices;
use std::process::Command;
use std::sync::Mutex;
use std::time::Duration;
@@ -287,7 +288,12 @@ fn check_adb(app: tauri::AppHandle) -> Result<String, String> {
}
#[tauri::command(async)]
-fn init_daemon(app: tauri::AppHandle, root_mode: Option<bool>) -> Result<String, String> {
+fn list_devices(app: tauri::AppHandle) -> Result<Vec<devices::Device>, String> {
+ devices::list(&get_bundled_binary(&app, "adb")?)
+}
+
+#[tauri::command(async)]
+fn init_daemon(app: tauri::AppHandle, serial: String, root_mode: Option<bool>) -> Result<String, String> {
let _operation = DAEMON_OPERATION.lock().map_err(|_| "Daemon state is unavailable")?;
// Reconnect can release only this app's previous session. An unconfirmed
// remote stop still clears local authority before a fresh session starts.
@@ -295,12 +301,7 @@ fn init_daemon(app: tauri::AppHandle, root_mode: Option<bool>) -> Result<String,
let adb_path = get_bundled_binary(&app, "adb")?;
let daemon = get_bundled_binary(&app, "daemon")?;
adb(&adb_path, &["version"])?;
- let devices = adb(&adb_path, &["devices"])?;
- let serial = devices.lines().find(|line| line.ends_with("\tdevice") && !line.starts_with("List"))
- .and_then(|line| line.split('\t').next()).map(str::to_string)
- .ok_or_else(|| if devices.lines().any(|line| line.contains("unauthorized")) {
- "USB Debugging not authorised. Check the confirmation dialog on your phone.".to_string()
- } else { "No Android device detected. Connect your phone via USB and enable USB Debugging.".to_string() })?;
+ devices::require_selected(&adb_path, &serial)?;
let (session, response) = session::Session::start(adb_path, &daemon, serial, root_mode.unwrap_or(false))?;
*SESSION.lock().map_err(|_| "Session state is unavailable")? = Some(session);
Ok(response)
@@ -559,6 +560,7 @@ pub fn run() {
tauri::Builder::default()
.invoke_handler(tauri::generate_handler![
check_adb,
+ list_devices,
init_daemon,
run_scan,
cancel_scan,
diff --git a/src-tauri/src/session.rs b/src-tauri/src/session.rs
index 3b4d396..a7d14d3 100644
--- a/src-tauri/src/session.rs
+++ b/src-tauri/src/session.rs
@@ -445,6 +445,45 @@ mod tests {
crate::daemon_command_at(c.address, "PING", &c.token, Duration::from_secs(2)).unwrap()
}
+ #[test]
+ fn discovery_checks_the_exact_selected_serial_without_falling_back() {
+ let device = Device::new();
+ let adb = device.client("selected-second", "second");
+ let list = adb.parent().unwrap().join("devices.txt");
+ fs::write(
+ &list,
+ "List of devices attached\nfirst device model:One\nsecond device model:Two\n",
+ )
+ .unwrap();
+ crate::devices::require_selected(&adb, "second").unwrap();
+ let (mut selected, _) =
+ Session::start(adb.clone(), daemon(), "second".into(), false).unwrap();
+ assert!(ping(&selected).contains("\"status\":\"ok\""));
+ assert!(selected.cleanup().is_empty());
+ for state in ["offline", "unauthorized", "no permissions", "recovery"] {
+ fs::write(
+ &list,
+ format!("List of devices attached\nfirst device\nsecond {state}\n"),
+ )
+ .unwrap();
+ assert!(
+ crate::devices::require_selected(&adb, "second").is_err(),
+ "accepted {state}"
+ );
+ }
+ fs::write(&list, "List of devices attached\nfirst device\n").unwrap();
+ for serial in ["second", "", " first", "first\n", "first\0"] {
+ assert!(
+ crate::devices::require_selected(&adb, serial).is_err(),
+ "accepted {serial:?}"
+ );
+ }
+ assert_eq!(device.directories(), 0);
+ assert_eq!(device.rows().len(), 1);
+ let calls = fs::read_to_string(adb.parent().unwrap().join("calls.jsonl")).unwrap();
+ assert!(calls.contains("[\"devices\", \"-l\"]"));
+ }
+
#[test]
fn two_sessions_on_same_or_different_devices_remain_independent() {
for serials in [("same", "same"), ("first", "second")] {
diff --git a/src/App.tsx b/src/App.tsx
index d7f8d31..9c06409 100644
--- a/src/App.tsx
+++ b/src/App.tsx
@@ -10,6 +10,8 @@ import { ToastContainer } from "./ToastContainer";
import type { Toast } from "./ToastContainer";
import { TerminalLog } from "./TerminalLog";
import { appendLog, emptyLogHistory } from "./logHistory";
+import { useDevices } from "./useDevices";
+import { deviceSelectionHint, deviceStateLabel } from "./devices";
import "./App.css";
// ── Types ───────────────────────────────────────────────────────────────────
@@ -91,16 +93,18 @@ let toastId = 0;
// ── Setup Screen ────────────────────────────────────────────────────────────
-function SetupScreen({ onConnect, loading, rootMode, onRootModeChange, rootPath, onRootPathChange }: {
+function SetupScreen({ onConnect, loading, rootMode, onRootModeChange, rootPath, onRootPathChange, deviceSelection }: {
onConnect: () => void;
loading: boolean;
rootMode: boolean;
onRootModeChange: (enabled: boolean) => void;
rootPath: string;
onRootPathChange: (path: string) => void;
+ deviceSelection: ReturnType<typeof useDevices>;
}) {
+ const { devices, serial, select, loading: refreshing, error, refresh, ready } = deviceSelection;
return (
- <div className="flex-1 min-h-0 overflow-y-auto px-6 py-8">
+ <div className="flex-1 min-h-0 overflow-y-auto px-6 py-8" style={{ scrollbarGutter: "stable both-edges" }}>
<div className="min-h-full flex flex-col items-center justify-center gap-8 animate-fade-in-up">
{/* Hero */}
<div className="flex flex-col items-center gap-6">
@@ -127,6 +131,28 @@ function SetupScreen({ onConnect, loading, rootMode, onRootModeChange, rootPath,
</div>
<div className="w-full max-w-xs flex flex-col items-center gap-5 text-sm">
+ <div className="w-full space-y-2">
+ <div className="flex items-center justify-between gap-3">
+ <label htmlFor="android-device" className="text-xs text-zinc-400">Android device</label>
+ <button type="button" id="btn-refresh-devices" disabled={loading || refreshing}
+ onClick={() => void refresh()} className="text-xs text-accent-400 disabled:text-zinc-600">
+ {refreshing ? "Refreshing…" : "Refresh"}
+ </button>
+ </div>
+ <select id="android-device" aria-describedby="device-status" value={serial}
+ disabled={loading || refreshing} onChange={event => select(event.target.value)}
+ className="w-full min-w-0 truncate rounded-lg border border-zinc-700 bg-zinc-900 px-3 py-2 text-zinc-200 disabled:opacity-60">
+ <option value="" disabled>Choose a device</option>
+ {serial && !devices.some(device => device.serial === serial) &&
+ <option value={serial} disabled>{serial} · {refreshing ? "Checking…" : error ? "Status unavailable" : "Disconnected"}</option>}
+ {devices.map(device => <option key={device.serial} value={device.serial} disabled={device.state !== "device"}>
+ {device.model ? `${device.model} · ` : ""}{device.serial} · {deviceStateLabel(device.state)}
+ </option>)}
+ </select>
+ <p id="device-status" role={error ? "alert" : "status"} className="text-xs leading-relaxed text-zinc-400">
+ {refreshing ? "Checking connected devices…" : error ?? deviceSelectionHint(devices, serial)}
+ </p>
+ </div>
<label className="flex items-center justify-center gap-2.5 text-zinc-300 cursor-pointer">
<input
id="scan-as-root"
@@ -163,11 +189,11 @@ function SetupScreen({ onConnect, loading, rootMode, onRootModeChange, rootPath,
<button
id="btn-connect"
onClick={onConnect}
- disabled={loading}
+ disabled={loading || !ready}
className={`
group relative w-full flex justify-center px-8 py-3 rounded-xl font-semibold text-sm
transition-all duration-300 cursor-pointer
- ${loading
+ ${loading || !ready
? "bg-zinc-800 text-zinc-500 cursor-wait"
: "bg-gradient-to-r from-accent-600 to-accent-500 text-white hover:from-accent-500 hover:to-accent-400 hover:shadow-lg hover:shadow-accent-500/20 hover:-translate-y-0.5"
}
@@ -392,12 +418,14 @@ function ResultScreen({
onDisconnect,
onNuke,
busy,
+ deviceSerial,
}: {
data: ScanResponse;
onRescan: () => void;
onDisconnect: () => void;
onNuke: (nodeId: number) => void;
busy: boolean;
+ deviceSerial: string;
}) {
const [zoomId, setZoomId] = useState(data.root.id);
const [expanded, setExpanded] = useState(() => new Set([data.root.id]));
@@ -475,6 +503,7 @@ function ResultScreen({
</div>
</header>
+ <p id="connected-device" className="px-6 pt-3 text-xs text-zinc-500 break-all">Device: <span className="font-mono">{deviceSerial}</span></p>
{data.read_only && (
<div className="px-6 pt-3 text-xs text-accent-300">
Root access · Read-only · Deletion disabled
@@ -546,6 +575,8 @@ function ResultScreen({
function App() {
const [phase, setPhase] = useState<AppPhase>("setup");
+ const deviceSelection = useDevices(phase === "setup");
+ const { serial: selectedSerial, ready: deviceReady } = deviceSelection;
const [rootMode, setRootMode] = useState(false);
const [rootPath, setRootPath] = useState("/data");
const [scanData, setScanData] = useState<ScanResponse | null>(null);
@@ -618,6 +649,8 @@ function App() {
// ── Connect flow ────────────────────────────────────────────────────────
const handleConnect = useCallback(async () => {
+ if (actionPending.current || !deviceReady || !selectedSerial) return;
+ actionPending.current = true;
setPhase("connecting");
const scanPath = rootMode ? rootPath : "/sdcard";
let initialized = false;
@@ -628,8 +661,8 @@ function App() {
addLog(`[ADB] Found: ${adbVersion}`);
setStatusText(rootMode ? "Requesting root access…" : "Pushing daemon to device…");
- addLog("[ADB] Killing old daemon, pushing new binary...");
- await invoke<string>("init_daemon", { rootMode });
+ addLog(`[ADB] Starting an owned daemon session on ${selectedSerial}...`);
+ await invoke<string>("init_daemon", { serial: selectedSerial, rootMode });
initialized = true;
addLog("[SOCKET] Daemon started and connected via TCP tunnel!");
@@ -654,8 +687,10 @@ function App() {
pushToast(message, message === "Scan cancelled" ? "info" : "error");
addLog(`${message === "Scan cancelled" ? "[SCAN]" : "[ERROR]"} ${message}`);
setPhase("setup");
+ } finally {
+ actionPending.current = false;
}
- }, [pushToast, addLog, rootMode, rootPath, requestScan]);
+ }, [pushToast, addLog, rootMode, rootPath, requestScan, selectedSerial, deviceReady]);
// ── Rescan ──────────────────────────────────────────────────────────────
const handleRescan = useCallback(async () => {
@@ -784,6 +819,7 @@ function App() {
onRootModeChange={setRootMode}
rootPath={rootPath}
onRootPathChange={setRootPath}
+ deviceSelection={deviceSelection}
/>
)}
{phase === "scanning" && <ScanningScreen statusText={statusText} progress={scanProgress} onCancel={handleCancelScan} cancelling={cancelling} />}
@@ -791,6 +827,7 @@ function App() {
<ResultScreen
key={scanData.generation}
data={scanData}
+ deviceSerial={selectedSerial}
busy={busy}
onRescan={handleRescan}
onDisconnect={handleDisconnect}
diff --git a/src/devices.ts b/src/devices.ts
new file mode 100644
index 0000000..c5c0111
--- /dev/null
+++ b/src/devices.ts
@@ -0,0 +1,34 @@
+/** A read-only discovery record. Only Rust grants connection authority. */
+export interface AndroidDevice {
+ serial: string;
+ state: string;
+ model: string | null;
+}
+
+export function preserveDeviceSelection(current: string, devices: AndroidDevice[]): string {
+ if (current) return current;
+ const ready = devices.filter(device => device.state === "device");
+ return ready.length === 1 ? ready[0].serial : "";
+}
+
+export function deviceStateLabel(state: string): string {
+ switch (state) {
+ case "device": return "Ready";
+ case "offline": return "Offline";
+ case "unauthorized": return "USB debugging not authorized";
+ case "no permissions": return "No USB permission";
+ default: return state;
+ }
+}
+
+export function deviceSelectionHint(devices: AndroidDevice[], serial: string): string {
+ const selected = devices.find(device => device.serial === serial);
+ if (serial && !selected) return "Selected device is disconnected. Reconnect it or choose another device, then refresh.";
+ if (selected?.state === "unauthorized") return "Unlock the selected phone and approve USB debugging, then refresh.";
+ if (selected?.state === "offline") return "Selected device is offline. Reconnect it and refresh.";
+ if (selected?.state === "no permissions") return "Check this computer's USB/udev permissions, then refresh.";
+ if (selected && selected.state !== "device") return "Selected device is not ready for scanning. Reconnect it and refresh.";
+ if (!devices.length) return "No devices found. Connect your phone and refresh.";
+ if (!serial) return "Choose a ready device. Unlock and authorize phones marked unavailable, then refresh.";
+ return "Only this device will be scanned.";
+}
diff --git a/src/useDevices.ts b/src/useDevices.ts
new file mode 100644
index 0000000..4738027
--- /dev/null
+++ b/src/useDevices.ts
@@ -0,0 +1,38 @@
+import { useCallback, useEffect, useRef, useState } from "react";
+import { invoke } from "@tauri-apps/api/core";
+import { preserveDeviceSelection } from "./devices";
+import type { AndroidDevice } from "./devices";
+
+export function useDevices(enabled: boolean) {
+ const [devices, setDevices] = useState<AndroidDevice[]>([]);
+ const [serial, select] = useState("");
+ const [loading, setLoading] = useState(true);
+ const [error, setError] = useState<string | null>(null);
+ const request = useRef(0);
+ const refresh = useCallback(async () => {
+ const id = ++request.current;
+ setLoading(true);
+ setError(null);
+ try {
+ const result = await invoke<AndroidDevice[]>("list_devices");
+ if (id !== request.current) return;
+ setDevices(result);
+ select(previous => preserveDeviceSelection(previous, result));
+ } catch (error) {
+ if (id !== request.current) return;
+ setDevices([]);
+ setError(String(error));
+ } finally {
+ if (id === request.current) setLoading(false);
+ }
+ }, []);
+ useEffect(() => {
+ if (!enabled) return;
+ void refresh();
+ return () => { request.current += 1; };
+ }, [enabled, refresh]);
+ return {
+ devices, serial, select, loading, error, refresh,
+ ready: !loading && error === null && devices.some(device => device.serial === serial && device.state === "device"),
+ };
+}
diff --git a/tests/devices.test.mjs b/tests/devices.test.mjs
new file mode 100644
index 0000000..3e61003
--- /dev/null
+++ b/tests/devices.test.mjs
@@ -0,0 +1,40 @@
+import assert from "node:assert/strict";
+import { readFile } from "node:fs/promises";
+import test from "node:test";
+import ts from "typescript";
+
+const source = await readFile(new URL("../src/devices.ts", import.meta.url), "utf8");
+const { outputText } = ts.transpileModule(source, {
+ compilerOptions: { target: ts.ScriptTarget.ES2020, module: ts.ModuleKind.ESNext },
+});
+const { preserveDeviceSelection, deviceSelectionHint, deviceStateLabel } = await import(
+ `data:text/javascript;base64,${Buffer.from(outputText).toString("base64")}`
+);
+const phone = (serial, state = "device") => ({ serial, state, model: null });
+
+test("initial selection requires exactly one ready device", () => {
+ assert.equal(preserveDeviceSelection("", []), "");
+ assert.equal(preserveDeviceSelection("", [phone("locked", "unauthorized")]), "");
+ assert.equal(preserveDeviceSelection("", [phone("one"), phone("locked", "unauthorized")]), "one");
+ assert.equal(preserveDeviceSelection("", [phone("one"), phone("two")]), "");
+});
+
+test("refresh and unplugging never replace an existing selection", () => {
+ for (const devices of [[], [phone("other")], [phone("other"), phone("chosen", "offline")], [phone("chosen"), phone("other")]]) {
+ assert.equal(preserveDeviceSelection("chosen", devices), "chosen");
+ }
+ const wireless = "[2001:db8::1]:5555";
+ assert.equal(preserveDeviceSelection("", [phone(wireless)]), wireless);
+});
+
+test("unavailable selections explain the required action without claiming readiness", () => {
+ assert.match(deviceSelectionHint([], "chosen"), /disconnected/);
+ assert.match(deviceSelectionHint([phone("chosen", "offline")], "chosen"), /offline/);
+ assert.match(deviceSelectionHint([phone("chosen", "unauthorized")], "chosen"), /approve USB debugging/);
+ assert.match(deviceSelectionHint([phone("chosen", "no permissions")], "chosen"), /permissions/);
+ assert.match(deviceSelectionHint([phone("chosen", "recovery")], "chosen"), /not ready/);
+ assert.match(deviceSelectionHint([], ""), /No devices/);
+ assert.match(deviceSelectionHint([phone("one"), phone("two")], ""), /Choose/);
+ assert.equal(deviceStateLabel("device"), "Ready");
+ assert.equal(deviceStateLabel("recovery"), "recovery");
+});
diff --git a/tests/fake_session_adb.py b/tests/fake_session_adb.py
index b9be20d..7463f59 100644
--- a/tests/fake_session_adb.py
+++ b/tests/fake_session_adb.py
@@ -16,8 +16,9 @@ import time
config = json.loads(Path(sys.argv[1]).read_text())
args = sys.argv[2:]
-assert args[:2] == ["-s", config["serial"]], args
-args = args[2:]
+if args != ["devices", "-l"]:
+ assert args[:2] == ["-s", config["serial"]], args
+ args = args[2:]
base = Path(config["base"])
with (base / "calls.jsonl").open("a") as stream:
stream.write(json.dumps(args) + "\n") # the token is stdin, never logged
@@ -34,7 +35,11 @@ def mapped(command):
return command.replace("/data/local/tmp/", str(Path(config["phone"])) + "/")
-if args == ["features"]:
+if args == ["devices", "-l"]:
+ discovery = base / "devices.txt"
+ print(discovery.read_text() if discovery.exists() else
+ f'List of devices attached\n{config["serial"]}\tdevice model:Fixture\n')
+elif args == ["features"]:
print("shell_v2" if failure != "features" else "other_feature")
elif args[0] == "push":
fail("push")
diff --git a/tests/scan_ui_fixture.js b/tests/scan_ui_fixture.js
index d568652..7c5fbbb 100644
--- a/tests/scan_ui_fixture.js
+++ b/tests/scan_ui_fixture.js
@@ -11,6 +11,15 @@
let delayedDetail = true;
let failDelete = false;
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;
+ let activeDevice = null;
let callbacks = 0;
let rootChildren;
let folderChildren;
@@ -62,8 +71,17 @@
unregisterCallback: () => {},
invoke: async (command, args = {}) => {
calls.push({ command, args });
+ if (command === "list_devices") {
+ await pause(50);
+ if (discoveryError) throw "Mock discovery failed";
+ return listedDevices;
+ }
if (command === "check_adb") return "Mock ADB " + "x".repeat(20000);
- if (command === "init_daemon") return "Mock daemon";
+ if (command === "init_daemon") {
+ check(listedDevices.some(device => device.serial === args.serial && device.state === "device"), "Selected device disconnected before startup");
+ activeDevice = args.serial;
+ return "Mock daemon";
+ }
if (command === "run_scan") { generation++; reset(); return JSON.stringify(summary()); }
if (command === "stop_daemon") {
await pause(150);
@@ -129,12 +147,57 @@
}
}
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();
+ check(picker().value === "phone-two" && connect.disabled && picker().selectedOptions[0].textContent.includes("Status unavailable") && document.querySelector("#device-status").textContent.includes("Mock discovery failed"), "Discovery failure did not preserve an unknown, blocked selection");
+ discoveryError = false;
+ listedDevices = [...readyDevices].reverse();
+ await refreshDevices();
+ check(picker().value === "phone-two" && !connect.disabled, "Reordered/reconnected devices lost selection");
+ // 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(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");
+ 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");
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");
@@ -195,7 +258,9 @@
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");
- check(calls.at(-1).command === "stop_daemon", "Partial failure did not stop session");
+ // 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;
@@ -224,6 +289,28 @@
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;
+ stopOutcome = "acknowledged";
+ selectDevice("phone-one");
+ await pause(20);
+ 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");
+ check(!button("NUKE IT"), "Device switch retained a destructive confirmation");
+ 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 pause(20);
+ 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();