Add opt-in physical USB device enrollment and remembered choices in 0.2.7

This commit is contained in:
tongtong committed 2026-11-14 04:06:01 +08:00
1 parent dc29a20a41
commit 208d37b7d8
20 files changed
+515 -18

No files matched your search

+1 -1
View File
@@ -14,7 +14,7 @@
| 目录 | 作用 | 主要语言/格式 |
| --- | --- | --- |
| `android_agent/` | 手机直接联网的 Android 设备端,Kotlin 传统 View、前台服务与 Rust JNI 网关;不申请运行时权限 | Kotlin、Rust、Gradle Kotlin DSL、XML、TOML |
| `agent/` | 无界面多手机守护程序 ads-agent、独立监督进程、私有 IPC 和远程管理;兼容单设备参数;源码在 `src/` | Rust、TOML |
| `agent/` | 无界面多手机守护程序 ads-agent、独立监督进程、私有 IPC、远程管理与可选真实 USB 自动注册;兼容单设备参数;源码在 `src/` | Rust、TOML |
| `ctl/` | adsctl 命令行管理端,本机/远程设备、配置、日志、重启及系统启动托管;源码在 `src/` | Rust、TOML |
| `usb/` | 可选 ads-usb 本机虚拟 ADB USB 设备,提供回环 USB/IP、描述符和 ADB 帧适配;Windows 使用已签名 USBip 虚拟控制器,Linux 使用内核 vhci_hcd(CLI) | Rust、TOML |
| `client/` | 本地守护程序 ads-client,维护设备租约、监听本地端口并自动调用 adb connect;源码在 `src/` | Rust、TOML |
Generated
+7 -6
View File
@@ -4,7 +4,7 @@ version = 4
[[package]]
name = "ads-agent"
version = "0.2.6"
version = "0.2.7"
dependencies = [
"ads-core",
"ads-management",
@@ -13,6 +13,7 @@ dependencies = [
"libc",
"serde",
"serde_json",
"sha2",
"tokio",
"tracing",
"tracing-subscriber",
@@ -21,7 +22,7 @@ dependencies = [
[[package]]
name = "ads-client"
version = "0.2.6"
version = "0.2.7"
dependencies = [
"ads-core",
"anyhow",
@@ -32,7 +33,7 @@ dependencies = [
[[package]]
name = "ads-core"
version = "0.2.6"
version = "0.2.7"
dependencies = [
"anyhow",
"bytes",
@@ -51,7 +52,7 @@ dependencies = [
[[package]]
name = "ads-management"
version = "0.2.6"
version = "0.2.7"
dependencies = [
"ads-core",
"anyhow",
@@ -67,7 +68,7 @@ dependencies = [
[[package]]
name = "ads-usb"
version = "0.2.6"
version = "0.2.7"
dependencies = [
"anyhow",
"clap",
@@ -78,7 +79,7 @@ dependencies = [
[[package]]
name = "adsctl"
version = "0.2.6"
version = "0.2.7"
dependencies = [
"ads-core",
"ads-management",
+1 -1
View File
@@ -3,7 +3,7 @@ members = ["crates/ads-core", "agent", "client", "usb", "crates/ads-management",
resolver = "2"
[workspace.package]
version = "0.2.6"
version = "0.2.7"
edition = "2021"
license = "MIT"
+2 -2
View File
@@ -23,7 +23,7 @@ Windows 现支持可选的 [USB ADB 模拟](docs/windows-usb.md),默认网络
| 目录 | 作用 | 主要语言/格式 |
| --- | --- | --- |
| `android_agent/` | 手机直接联网的 Android 设备端,Kotlin 传统 View、前台服务与 Rust JNI 网关;不申请运行时权限 | Kotlin、Rust、Gradle Kotlin DSL、XML、TOML |
| `agent/` | 无界面多手机守护程序 ads-agent、独立监督进程、私有 IPC 和远程管理;兼容单设备参数;源码在 `src/` | Rust、TOML |
| `agent/` | 无界面多手机守护程序 ads-agent、独立监督进程、私有 IPC、远程管理与可选真实 USB 自动注册;兼容单设备参数;源码在 `src/` | Rust、TOML |
| `ctl/` | adsctl 命令行管理端,本机/远程设备、配置、日志、重启及系统启动托管;源码在 `src/` | Rust、TOML |
| `usb/` | 可选 ads-usb 本机虚拟 ADB USB 设备,提供回环 USB/IP、描述符和 ADB 帧适配;Windows 使用已签名 USBip 虚拟控制器,Linux 使用内核 vhci_hcd(CLI) | Rust、TOML |
| `client/` | 本地守护程序 ads-client,维护设备租约、监听本地端口并自动调用 adb connect;源码在 `src/` | Rust、TOML |
@@ -251,4 +251,4 @@ Android APK 交付目录固定为 `bin/apk/`(APK 格式,无业务源码,
Linux 桌面 deb 安装后自动通过 update-alternatives 注册 `/usr/bin/adsctl`、`ads-agent`、`ads-client`、`ads-usb`,支持多包共存及卸载回退;无需手动创建链接,详见 [Linux 打包](docs/linux-packaging.md)。
已配置的 Agent ADB 设备会持续检测上下线,离线撤销注册、恢复沿用原 ID;同一 ADB server 共享查询,未配置的新手机仍需手动添加。详见 [Agent 管理与设备监听](docs/agent-management.md#持续监听设备上下线026)。
已配置的 Agent ADB 设备会持续检测上下线,离线撤销注册、恢复沿用原 ID;同一 ADB server 共享查询,默认未配置的新手机仍需手动添加;0.2.7 可按 Agent 开启真实 USB 自动注册。详见 [Agent 管理与设备监听](docs/agent-management.md#持续监听设备上下线026)。
+1
View File
@@ -13,6 +13,7 @@ tracing.workspace = true
ads-management = { path = "../crates/ads-management" }
serde.workspace = true
serde_json.workspace = true
sha2 = "0.10"
tracing-subscriber.workspace = true
[target.'cfg(windows)'.dependencies]
+1
View File
@@ -2,6 +2,7 @@ mod adb_monitor;
mod gateway;
mod managed;
mod supervisor;
mod usb_discovery;
use ads_core::{valid_device_id, validate_token, NetworkArgs};
use ads_management::{credential, AgentConfig};
use anyhow::{bail, Context, Result};
+97 -2
View File
@@ -89,6 +89,7 @@ struct Runtime {
restart: watch::Sender<bool>,
supervised: bool,
instance: String,
ready: std::sync::atomic::AtomicBool,
}
impl Runtime {
fn reconcile(&self, state: &mut State) {
@@ -105,6 +106,7 @@ impl Runtime {
.clone()
.unwrap_or_else(|| adb_server.clone())
})
.chain(state.config.auto_register_usb.then(|| adb_server.clone()))
.collect();
state.monitors.retain(|server, _| servers.contains(server));
for server in servers {
@@ -242,6 +244,9 @@ impl Runtime {
if config.devices.iter().any(|d| d.id == device.id) {
bail!("device ID already exists")
};
if let Some(serial) = &device.adb_serial {
config.ignored_usb_serials.retain(|s| s != serial);
}
config.devices.push(device);
}
Request::DeviceRemove { id } => {
@@ -259,7 +264,16 @@ impl Runtime {
.context("device not found")?
.enabled = enabled;
}
Request::ConfigSet { config: new } => {
Request::ConfigSet {
config: new,
expected_config,
} => {
if expected_config
.as_ref()
.is_some_and(|expected| expected != &state.config)
{
bail!("Agent 配置已变化,请刷新后重试,避免覆盖自动发现或其他管理操作")
}
if new.id != config.id {
bail!("agent ID is immutable; initialize a separate agent to change identity")
};
@@ -267,6 +281,16 @@ impl Runtime {
}
_ => bail!("unsupported operation"),
}
// Deleting an ADB entry means "do not add it again" even after a restart.
for old in &state.config.devices {
if !config.devices.iter().any(|d| d.id == old.id) {
if let Some(serial) = &old.adb_serial {
if !config.ignored_usb_serials.contains(serial) {
config.ignored_usb_serials.push(serial.clone());
}
}
}
}
config.validate()?;
let changed_network = config.server != state.config.server
|| config.connect_address != state.config.connect_address
@@ -286,6 +310,63 @@ impl Runtime {
}
}
}
async fn discover_usb(&self) -> Result<()> {
if !self.ready.load(std::sync::atomic::Ordering::Acquire) {
return Ok(());
}
{
let state = self.state.lock().await;
if !state.config.auto_register_usb
|| !crate::usb_discovery::local_server(&state.config.adb_server)
{
return Ok(());
}
// Native PnP enumeration is only needed for new eligible ADB serials.
// Previewing candidates does not authorize or persist any device.
let online = match state
.monitors
.get(&state.config.adb_server)
.map(|m| m.receiver.borrow().clone())
{
Some(crate::adb_monitor::Snapshot::Devices(devices)) => devices
.into_iter()
.filter(|(_, s)| s == "device")
.map(|(serial, _)| serial)
.collect(),
_ => return Ok(()),
};
let mut preview = state.config.clone();
if crate::usb_discovery::add_online(&mut preview, &online, &online) == 0 {
return Ok(());
}
}
let physical = crate::usb_discovery::physical_serials().await?;
let mut state = self.state.lock().await;
let online = match state
.monitors
.get(&state.config.adb_server)
.map(|m| m.receiver.borrow().clone())
{
Some(crate::adb_monitor::Snapshot::Devices(devices)) => devices
.into_iter()
.filter(|(_, s)| s == "device")
.map(|(s, _)| s)
.collect(),
_ => return Ok(()),
};
let mut config = state.config.clone();
let count = crate::usb_discovery::add_online(&mut config, &online, &physical);
if count == 0 {
return Ok(());
}
config.validate()?;
ads_management::save_private(&self.path, &serde_json::to_vec_pretty(&config)?)?;
state.config = config;
state.revision += 1;
self.reconcile(&mut state);
tracing::info!(count, "physical USB devices automatically added");
Ok(())
}
async fn handle(&self, request: Request) -> Response {
match self.execute(request).await {
Ok(value) => value,
@@ -375,6 +456,7 @@ pub async fn run(path: PathBuf, config: AgentConfig, token: String) -> Result<bo
restart,
supervised: std::env::var("ADS_SUPERVISED").as_deref() == Ok("1"),
instance,
ready: std::sync::atomic::AtomicBool::new(false),
});
let handler: ads_management::ipc::Handler = {
let runtime = runtime.clone();
@@ -394,6 +476,9 @@ pub async fn run(path: PathBuf, config: AgentConfig, token: String) -> Result<bo
{
let mut state = runtime.state.lock().await;
runtime.reconcile(&mut state);
runtime
.ready
.store(true, std::sync::atomic::Ordering::Release);
}
let mut delay = 1;
loop {
@@ -405,7 +490,17 @@ pub async fn run(path: PathBuf, config: AgentConfig, token: String) -> Result<bo
}
};
tokio::pin!(networking);
let restart = tokio::select! {result=&mut ipc=>{result?;false},_=&mut networking=>false,result=restarting.changed()=>{result?;sleep(Duration::from_millis(400)).await;true},result=crate::supervisor::shutdown()=>{result?;false}};
let discovery = async {
let mut ticks = interval(Duration::from_secs(5));
loop {
ticks.tick().await;
if let Err(error) = runtime.discover_usb().await {
tracing::warn!(%error,"USB auto-registration scan failed");
}
}
};
tokio::pin!(discovery);
let restart = tokio::select! {_=&mut discovery=>false,result=&mut ipc=>{result?;false},_=&mut networking=>false,result=restarting.changed()=>{result?;sleep(Duration::from_millis(400)).await;true},result=crate::supervisor::shutdown()=>{result?;false}};
let mut state = runtime.state.lock().await;
state.workers.clear();
state.monitors.clear();
+194
View File
@@ -0,0 +1,194 @@
//! Fail closed: only native USB devices on a physical host controller are eligible.
use ads_management::{AgentConfig, DeviceConfig};
use sha2::{Digest, Sha256};
use std::collections::BTreeSet;
pub fn local_server(server: &str) -> bool {
server
.rsplit_once(':')
.is_some_and(|(host, _)| matches!(host, "127.0.0.1" | "localhost" | "[::1]"))
}
fn allowed_serial(serial: &str) -> bool {
!serial.is_empty()
&& serial.len() <= 256
&& !serial.chars().any(char::is_control)
&& !serial.to_ascii_lowercase().starts_with("ads-")
&& !serial.starts_with("emulator-")
&& !serial.contains(':')
}
pub fn add_online(
config: &mut AgentConfig,
online: &BTreeSet<String>,
physical: &BTreeSet<String>,
) -> usize {
if !config.auto_register_usb || !local_server(&config.adb_server) {
return 0;
}
let mut added = 0;
for serial in online.intersection(physical) {
if !allowed_serial(serial)
|| config.ignored_usb_serials.contains(serial)
|| config
.devices
.iter()
.any(|d| d.adb_serial.as_ref() == Some(serial))
|| config.devices.len() >= 128
{
continue;
}
let id = config
.usb_device_ids
.get(serial)
.cloned()
.unwrap_or_else(|| {
let hash = Sha256::digest(format!("{}:{serial}", config.id).as_bytes());
format!("usb-{:x}", hash)[..36].to_owned()
});
if config.devices.iter().any(|d| d.id == id)
|| (!config.usb_device_ids.contains_key(serial) && config.usb_device_ids.len() >= 512)
{
continue;
}
config.usb_device_ids.insert(serial.clone(), id.clone());
config.devices.push(DeviceConfig {
id,
target: None,
adb_serial: Some(serial.clone()),
adb_server: None,
device_port: 5555,
enabled: true,
});
added += 1;
}
added
}
#[cfg(target_os = "linux")]
pub async fn physical_serials() -> anyhow::Result<BTreeSet<String>> {
tokio::task::spawn_blocking(|| {
let mut serials = BTreeSet::new();
for entry in std::fs::read_dir("/sys/bus/usb/devices")? {
let Ok(path) = std::fs::canonicalize(entry?.path()) else {
continue;
};
let name = path.to_string_lossy().to_ascii_lowercase();
if name.contains("vhci") || !name.contains("/pci") {
continue;
}
let product = std::fs::read_to_string(path.join("product")).unwrap_or_default();
if product.to_ascii_lowercase().contains("ads virtual") {
continue;
}
if let Ok(serial) = std::fs::read_to_string(path.join("serial")) {
let serial = serial.trim();
if allowed_serial(serial) {
serials.insert(serial.to_owned());
}
}
}
Ok(serials)
})
.await?
}
#[cfg(windows)]
pub async fn physical_serials() -> anyhow::Result<BTreeSet<String>> {
// No interpolated serials or credentials; bounded child is killed on timeout/cancellation.
let script = r#"
$ErrorActionPreference='Stop'
[Console]::OutputEncoding=[Text.UTF8Encoding]::new($false)
$devices=Get-PnpDevice -PresentOnly | Where-Object { $_.InstanceId -like 'USB\VID_*' -and $_.InstanceId -notlike '*&MI_*' }
foreach($d in $devices) {
if($d.FriendlyName -like '*ADS Virtual*') {continue}
$serial=($d.InstanceId -split '\\')[-1]
if($serial.Contains('&')) {continue}
$parent=$d.InstanceId;$physical=$false
for($i=0;$i -lt 16;$i++) {
if($parent -match '(?i)USBIP|VHCI|UDE|^ROOT\\') {break}
if($parent.StartsWith('PCI\',[StringComparison]::OrdinalIgnoreCase)) {$physical=$true;break}
$parent=(Get-PnpDeviceProperty -InstanceId $parent -KeyName 'DEVPKEY_Device_Parent' -ErrorAction SilentlyContinue).Data
if(!$parent) {break}
}
if($physical) {[Console]::WriteLine($serial)}
}
"#;
let exe = std::env::var_os("SystemRoot")
.map(std::path::PathBuf::from)
.unwrap_or_else(|| r"C:\Windows".into())
.join("System32/WindowsPowerShell/v1.0/powershell.exe");
let mut command = tokio::process::Command::new(exe);
command
.args(["-NoProfile", "-NonInteractive", "-Command", script])
.kill_on_drop(true);
command.creation_flags(0x08000000);
let output =
tokio::time::timeout(std::time::Duration::from_secs(15), command.output()).await??;
anyhow::ensure!(output.status.success(), "native USB inventory failed");
Ok(String::from_utf8(output.stdout)?
.lines()
.map(str::trim)
.filter(|s| allowed_serial(s))
.map(str::to_owned)
.collect())
}
#[cfg(not(any(windows, target_os = "linux")))]
pub async fn physical_serials() -> anyhow::Result<BTreeSet<String>> {
anyhow::bail!("USB auto-registration requires Windows or Linux physical USB inventory")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn registration_is_opt_in_and_preserves_user_choices() {
let mut c: AgentConfig = serde_json::from_value(
serde_json::json!({"id":"pc","name":"pc","server":"wss://example.com","devices":[]}),
)
.unwrap();
let online = [
"real",
"ignored",
"ADS-test",
"emulator-5554",
"192.168.1.2:5555",
"unauthorized",
]
.map(str::to_owned)
.into_iter()
.collect();
let physical = [
"real",
"ignored",
"ADS-test",
"emulator-5554",
"192.168.1.2:5555",
]
.map(str::to_owned)
.into_iter()
.collect();
assert_eq!(add_online(&mut c, &online, &physical), 0);
c.auto_register_usb = true;
c.ignored_usb_serials.push("ignored".into());
assert_eq!(add_online(&mut c, &online, &physical), 1);
let id = c.devices[0].id.clone();
c = serde_json::from_slice(&serde_json::to_vec(&c).unwrap()).unwrap();
c.devices[0].enabled = false;
c.devices[0].adb_server = Some("localhost:5037".into());
assert_eq!(add_online(&mut c, &online, &physical), 0);
assert!(!c.devices[0].enabled);
c.devices.clear();
assert_eq!(add_online(&mut c, &online, &physical), 1);
assert_eq!(c.devices[0].id, id);
c.adb_server = "192.168.1.5:5037".into();
c.devices.clear();
assert_eq!(add_online(&mut c, &online, &physical), 0);
}
}
#[cfg(all(test, windows))]
mod native_tests {
#[tokio::test]
async fn native_inventory_runs_without_a_visible_console() {
super::physical_serials()
.await
.expect("Windows PnP inventory");
}
}
+24 -1
View File
@@ -45,7 +45,7 @@ pub struct DeviceConfig {
#[serde(default = "yes")]
pub enabled: bool,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
#[derive(Clone, Serialize, Deserialize, Debug, PartialEq, Eq)]
#[serde(deny_unknown_fields)]
pub struct AgentConfig {
#[serde(default = "version")]
@@ -61,6 +61,12 @@ pub struct AgentConfig {
pub adb_server: String,
#[serde(default)]
pub devices: Vec<DeviceConfig>,
#[serde(default)]
pub auto_register_usb: bool,
#[serde(default)]
pub ignored_usb_serials: Vec<String>,
#[serde(default)]
pub usb_device_ids: std::collections::BTreeMap<String, String>,
}
impl AgentConfig {
pub fn network(&self) -> NetworkArgs {
@@ -90,6 +96,21 @@ impl AgentConfig {
if self.devices.len() > 128 {
bail!("at most 128 devices per agent")
}
if self.ignored_usb_serials.len() > 512 || self.usb_device_ids.len() > 512 {
bail!("at most 512 remembered USB devices")
}
for serial in self
.ignored_usb_serials
.iter()
.chain(self.usb_device_ids.keys())
{
if serial.is_empty() || serial.len() > 256 || serial.chars().any(char::is_control) {
bail!("invalid remembered USB serial")
}
}
if self.usb_device_ids.values().any(|id| !valid_device_id(id)) {
bail!("invalid remembered USB ID")
}
let mut ids = HashSet::new();
for device in &self.devices {
if !valid_device_id(&device.id) || !ids.insert(&device.id) || device.device_port == 0 {
@@ -156,6 +177,8 @@ pub enum Request {
ConfigGet,
ConfigSet {
config: AgentConfig,
#[serde(default)]
expected_config: Option<AgentConfig>,
},
Logs {
#[serde(default)]
+33
View File
@@ -67,6 +67,15 @@ enum Agents {
enum Devices {
/// Discover devices already known to the Agent host ADB server
Discover,
/// Enable or disable automatic registration of authorized physical USB phones
AutoUsb {
#[arg(value_parser=["on","off"])]
mode: String,
},
/// Allow a previously removed USB phone to be registered again
Unignore {
serial: String,
},
List,
Add {
#[arg(long)]
@@ -190,6 +199,9 @@ async fn main() -> Result<()> {
allow_insecure: args.network.allow_insecure,
adb_server: "127.0.0.1:5037".into(),
devices: vec![],
auto_register_usb: false,
ignored_usb_serials: vec![],
usb_device_ids: Default::default(),
};
cfg.validate()?;
let source = args
@@ -327,6 +339,26 @@ async fn main() -> Result<()> {
enabled: true,
},
},
Devices::AutoUsb { mode } => {
let mut config: AgentConfig =
serde_json::from_value(invoke(&args, &Request::ConfigGet).await?.value()?)?;
let expected_config = Some(config.clone());
config.auto_register_usb = mode == "on";
Request::ConfigSet {
config,
expected_config,
}
}
Devices::Unignore { serial } => {
let mut config: AgentConfig =
serde_json::from_value(invoke(&args, &Request::ConfigGet).await?.value()?)?;
let expected_config = Some(config.clone());
config.ignored_usb_serials.retain(|s| s != &serial);
Request::ConfigSet {
config,
expected_config,
}
}
Devices::Remove { id } => Request::DeviceRemove { id },
Devices::Enable { id } => Request::DeviceEnable { id, enabled: true },
Devices::Disable { id } => Request::DeviceEnable { id, enabled: false },
@@ -338,6 +370,7 @@ async fn main() -> Result<()> {
command: Config::Set { ref file },
} => Request::ConfigSet {
config: AgentConfig::load(file)?,
expected_config: None,
},
_ => unreachable!(),
};
+1 -1
View File
@@ -1,4 +1,4 @@
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup><Version>0.2.6</Version><OutputType>WinExe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<PropertyGroup><Version>0.2.7</Version><OutputType>WinExe</OutputType><TargetFramework>net8.0</TargetFramework><Nullable>enable</Nullable><ImplicitUsings>enable</ImplicitUsings></PropertyGroup>
<ItemGroup><PackageReference Include="Avalonia.Desktop" Version="11.3.8"/><PackageReference Include="Semi.Avalonia" Version="11.3.7.3"/><PackageReference Include="CommunityToolkit.Mvvm" Version="8.4.0"/></ItemGroup>
<ItemGroup><AvaloniaResource Include="Assets/**"/></ItemGroup></Project>
@@ -8,7 +8,7 @@
<Grid Grid.Row="1" ColumnDefinitions="300,*">
<Border Classes="agentCard" Margin="0,0,14,0"><Grid RowDefinitions="Auto,*"><TextBlock Text="Agent / 被控电脑" FontSize="18" FontWeight="SemiBold"/><ListBox x:Name="AgentList" Grid.Row="1" ItemsSource="{Binding Agents}" SelectedItem="{Binding SelectedAgent}" Margin="0,10,0,0"><ListBox.ItemTemplate><DataTemplate><StackPanel Spacing="5" Margin="4,8"><TextBlock Text="{Binding Id}" FontSize="16"/><TextBlock Text="{Binding Description}" TextWrapping="Wrap" Foreground="{DynamicResource SemiColorText2}"/></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox></Grid></Border>
<ScrollViewer Grid.Column="1"><StackPanel Spacing="14">
<Border Classes="agentCard"><StackPanel Spacing="10"><TextBlock Text="{Binding SelectedAgentDetails}" TextWrapping="Wrap" Foreground="{DynamicResource SemiColorPrimary}"/><WrapPanel><Button x:Name="LoadAgentConfigButton" Content="读取配置" Command="{Binding LoadConfigCommand}"/><Button Content="重启 Agent" Command="{Binding RestartAgentCommand}"/></WrapPanel><TextBlock Text="重启由监督进程执行,设备连接会短暂中断。" FontSize="12" Foreground="{DynamicResource SemiColorText2}"/></StackPanel></Border>
<Border Classes="agentCard"><StackPanel Spacing="10"><TextBlock Text="{Binding SelectedAgentDetails}" TextWrapping="Wrap" Foreground="{DynamicResource SemiColorPrimary}"/><WrapPanel><Button x:Name="LoadAgentConfigButton" Content="读取配置" Command="{Binding LoadConfigCommand}"/><Button Content="开启 USB 自动注册" Command="{Binding EnableAutoUsbCommand}"/><Button Content="关闭 USB 自动注册" Command="{Binding DisableAutoUsbCommand}"/><Button Content="取消所选发现设备的忽略" Command="{Binding UnignoreUsbCommand}"/><Button Content="重启 Agent" Command="{Binding RestartAgentCommand}"/></WrapPanel><TextBlock Text="USB 自动注册默认关闭,仅支持 Windows/Linux 真实 USB。删除后记为忽略,停用不会自动恢复;当前开关和忽略列表可读取配置查看。重启会短暂中断设备连接。" FontSize="12" Foreground="{DynamicResource SemiColorText2}"/></StackPanel></Border>
<Border Classes="agentCard"><StackPanel Spacing="8">
<Button Content="发现 ADB 设备" Command="{Binding DiscoverDevicesCommand}" HorizontalAlignment="Left"/>
<ListBox ItemsSource="{Binding DiscoveredDevices}" SelectedItem="{Binding SelectedDiscoveredDevice}" MaxHeight="160"><ListBox.ItemTemplate><DataTemplate><TextBlock Text="{Binding Description}" TextWrapping="Wrap"/></DataTemplate></ListBox.ItemTemplate></ListBox>
@@ -179,6 +179,22 @@ public partial class AgentManagementViewModel : ObservableObject, IDisposable
[RelayCommand(CanExecute=nameof(CanManage))]private Task LoadConfigAsync()=>Guard(async()=>{
var value=await CallAsync(new{op="config_get"});ConfigJson=JsonSerializer.Serialize(value,new JsonSerializerOptions{WriteIndented=true});Notice="已读取配置,凭据不在配置中。";
});
private Task UpdateUsbPolicy(bool? enabled)=>Guard(async()=>{
var value=await CallAsync(new{op="config_get"});
var config=System.Text.Json.Nodes.JsonNode.Parse(value.GetRawText())!.AsObject();
var expected_config=config.DeepClone();
if(enabled.HasValue)config["auto_register_usb"]=enabled.Value;
else {
var serial=SelectedDiscoveredDevice?.Serial ?? throw new InvalidOperationException("请先发现并选择需要取消忽略的设备。");
var ignored=config["ignored_usb_serials"]?.AsArray() ?? new System.Text.Json.Nodes.JsonArray();
config["ignored_usb_serials"]=new System.Text.Json.Nodes.JsonArray(ignored.Where(n=>n?.GetValue<string>()!=serial).Select(n=>n?.DeepClone()).ToArray());
}
await CallAsync(new{op="config_set",config,expected_config});ConfigJson=config.ToJsonString(new JsonSerializerOptions{WriteIndented=true});
await RefreshCoreAsync();Notice=enabled.HasValue?(enabled.Value?"已开启真实 USB 自动注册。":"已关闭自动注册,已有设备保留。 "):"已取消该设备的忽略记录;开启自动注册后将重新检查。";
});
[RelayCommand(CanExecute=nameof(CanManage))]private Task EnableAutoUsbAsync()=>UpdateUsbPolicy(true);
[RelayCommand(CanExecute=nameof(CanManage))]private Task DisableAutoUsbAsync()=>UpdateUsbPolicy(false);
[RelayCommand(CanExecute=nameof(CanManage))]private Task UnignoreUsbAsync()=>UpdateUsbPolicy(null);
[RelayCommand(CanExecute=nameof(CanManage))]private Task SaveConfigAsync()=>Guard(async()=>{
using var doc=JsonDocument.Parse(ConfigJson);await CallAsync(new{op="config_set",config=doc.RootElement});await RefreshCoreAsync();Notice="配置已持久化并应用。受影响设备将重建连接。";
});
+25 -1
View File
@@ -129,7 +129,31 @@ Agent 对已配置且启用的 `adb_serial` 持续检查 ADB 列表,同一个
- 设备消失、`offline`、`unauthorized` 或 ADB server 不可达:撤销该手机的控制中心注册,关闭旧数据流及租约;Agent 管理连接继续保留,显示未就绪原因。
- 手机重新在线并授权后:使用原设备 ID 自动注册,本地连接客户端可重新获取租约;不重启 Agent、不改写配置,不中断其他在线手机。
- 手动停用的设备保持停用。发现新插入的未配置设备仍需通过“发现 ADB 设备”或 CLI 添加,不会自动公开新手机。
- 手动停用的设备保持停用。默认仍需通过“发现 ADB 设备”或 CLI 添加新手机;0.2.7 可按 Agent 开启下述真实 USB 自动注册。
- 使用 `target` 直连手机的配置不依赖本机 ADB 列表,注册前及每 5 秒检测 TCP 连接,单次检测超时 3 秒。TCP 可达仅表示端口可连接,不代表所有 ADB 命令必定成功。
工作台可能保留已建立的本地连接行,便于手机恢复后重连;该行会明确显示远端离线,不再沿用旧的 ADB 就绪提示。若 Agent 状态仍显示旧版本,请更新实际运行的守护程序,仅更新桌面 UI 不会替换已启动的 Agent。
## 可选真实 USB 自动注册(0.2.7)
默认关闭,每台 Agent 单独设置。两套桌面客户端的 Agent 管理提供“开启 USB 自动注册”“关闭 USB 自动注册”和“取消所选 USB 设备的忽略”。先选择目标 Agent,再操作;读取配置可查看当前开关、忽略列表及 ID 映射。关闭只停止自动添加,已配置的手机继续按原有方式工作。
无界面主机可使用 CLI(远程管理加 `--agent ID` 及管理员凭据):
```sh
adsctl devices auto-usb on
adsctl devices auto-usb off
adsctl devices unignore USB_SERIAL
adsctl config get
```
对应 agent.json 字段:`auto_register_usb`(缺省 false)、`ignored_usb_serials`(删除后不再自动加入的序列号)与 `usb_device_ids`(序列号到稳定设备 ID 的映射)。保存和自动添加均经过校验及原子持久化;退出/重启保留这些记录。开启后约每 5 秒扫描一次物理 USB,并与 ADB 在线列表交叉确认;Windows 本机设备查询有 15 秒超时,查询失败只跳过本轮,不影响管理连接和已配置设备。
- 只处理 Agent 主机回环地址 ADB server 中状态为 `device` 的已授权手机。默认 127.0.0.1:5037,外部 ADB server 不自动注册。
- Windows 通过 PnP 父设备链确认 USB 设备位于 PCI 物理控制器下;Linux 检查 sysfs 的 PCI USB 设备并排除 vhci。模拟器、网络 ADB、ADS 虚拟 USB 与无法确认物理来源的设备均不自动添加。Windows/Linux 的特殊非 PCI 控制器也会跳过,可手动添加;macOS 此开关尚未支持物理设备检测。
- 新 ID 使用 Agent ID 与 USB 序列号的稳定散列并保存映射;拔插/重启不会换 ID。已手动添加的同序列号设备不会再添加一条,也不会覆盖其 ID 或停用状态。
- 删除手机会保存忽略记录;停用保留设备条目和 enabled=false,两者均不会被扫描自动恢复。恢复忽略可用上述 CLI,或在“发现 ADB 设备”中选择手机再取消忽略;手动重新添加也会取消对应忽略。
- 手机必须有可识别的 USB 序列号。序列号变化视为新设备;设备条目最多 128 个,历史映射与忽略列表各最多 512 条,并受配置文件 64 KiB 上限约束。
- 自动注册不会执行 `adb tcpip`,也不改变现有 ADB 数据通道实现。若手机已在线但转发提示无法访问 adbd,请按原有部署要求准备手机调试端口;注册不代表所有后续命令一定成功。
操作复用现有 config_get/config_set,控制中心无需新增管理协议;Agent 本身必须更新到 0.2.7。建议先更新实际守护程序,再从桌面端开启。
+10
View File
@@ -110,3 +110,13 @@ Port cleanup follow-up:
- 本机 local-pc 已从 0.2.4 更新到 0.2.6,原程序备份在忽略的 work 目录,配置哈希保持一致。实测 ADB 列表为空时,Agent connected=false 并显示“ADB 未发现该设备”,管理 IPC 持续可用;本轮未要求插拔真实手机,恢复路径由真实三端集成测试覆盖。
- 0.2.6 Windows Avalonia/Flutter Setup 与 Linux Agent/Avalonia/Flutter deb 已生成。Windows Avalonia 正式包启动检查通过;Linux Flutter 原生静态分析及 37 项测试通过,Linux Agent/Avalonia 正式 deb 的 6 项临时根安装/卸载测试通过。
- Ubuntu 24.04 对正式 Flutter/Agent deb 的 6 项隔离安装测试通过;正式 Flutter deb 解包后在真实桌面会话执行 --package-check,输出 ADS_FLUTTER_PACKAGE_OK 并退出 0。
### 0.2.7:可选真实 USB 自动注册
- Agent 配置新增默认关闭的 auto_register_usb、ignored_usb_serials 与 usb_device_ids。后台扫描仅允许回环 ADB server 的 device 状态与原生物理 USB 清单的交集,排除模拟器、网络设备和 ADS 虚拟 USB;已有同序列号配置优先,不覆盖手动 ID/停用状态。
- Windows PnP 查询实际运行通过;纯逻辑测试覆盖默认关闭、非物理来源排除、忽略、持久化 ID、停用、ADB 地址别名去重与非本机 ADB 排除。当前没有接入可用于插拔的新真实 USB 手机,因此尚未做真实新手机自动添加的插拔验收。
- 真实控制中心、Agent 和 CLI 集成测试验证开启/关闭、删除写入忽略、取消忽略与过期配置拒绝;原设备离线注销、恢复、管理 IPC、受监督重启、多设备流隔离测试仍通过。
- Flutter 38 项测试、静态分析,以及 Avalonia 30 项测试通过;Windows/Linux 管理界面均接入开启/关闭与取消忽略。策略操作使用配置比对,配置有并发修改时拒绝覆盖并提示刷新。
- 本机 local-pc 已更新到最终 0.2.7,确认 auto_register_usb=false,配置哈希未变;运行程序与两套 Windows 发行目录 Agent 的 SHA256 一致。正式发布二进制的策略/上下线集成测试通过,Avalonia 正式包启动检查通过。
- Windows 两套 Setup 与 Linux Agent/Avalonia/Flutter deb 已生成;Linux Agent/Avalonia 0.2.7 正式 deb 的 6 项临时根安装、版本和 CLI 链接回退测试通过。
- Ubuntu 24.04 的正式 Flutter/Agent deb 也通过 6 项隔离安装测试;解包后的 Flutter GUI 在真实桌面会话输出 ADS_FLUTTER_PACKAGE_OK,退出 0。
+34
View File
@@ -192,6 +192,40 @@ class AgentModel extends ChangeNotifier {
.convert(await _call({'op': 'config_get'}));
notice = '已读取配置,凭据不在配置中。';
});
Future<void> setAutoUsb(bool enabled) => run(() async {
final config = Map<String, Object?>.from(
await _call({'op': 'config_get'}) as Map,
);
final expected = Map<String, Object?>.from(config);
config['auto_register_usb'] = enabled;
await _call({
'op': 'config_set',
'config': config,
'expected_config': expected,
});
configText = const JsonEncoder.withIndent(' ').convert(config);
await _refresh();
notice = enabled ? '已开启真实 USB 自动注册。' : '已关闭自动注册,已有设备保留。';
});
Future<void> unignoreUsb() => run(() async {
final serial = adbSerial.trim();
if (serial.isEmpty) throw StateError('请先发现并选择需要取消忽略的 USB 设备');
final config = Map<String, Object?>.from(
await _call({'op': 'config_get'}) as Map,
);
final expected = Map<String, Object?>.from(config);
config['ignored_usb_serials'] =
(config['ignored_usb_serials'] as List? ?? [])
.where((s) => s != serial)
.toList();
await _call({
'op': 'config_set',
'config': config,
'expected_config': expected,
});
configText = const JsonEncoder.withIndent(' ').convert(config);
notice = '已取消该设备的忽略记录;开启自动注册后将重新检查。';
});
Future<void> saveConfig() => run(() async {
final data = jsonDecode(configText) as Map<String, Object?>;
await _call({'op': 'config_set', 'config': data});
+15
View File
@@ -171,6 +171,21 @@ class _AgentViewState extends State<AgentView> {
Wrap(
children: [
button('读取配置', m.loadConfig, enabled: m.canManage),
button(
'开启 USB 自动注册',
() => m.setAutoUsb(true),
enabled: m.canManage,
),
button(
'关闭 USB 自动注册',
() => m.setAutoUsb(false),
enabled: m.canManage,
),
button(
'取消所选 USB 设备的忽略',
m.unignoreUsb,
enabled: m.canManage,
),
button(
'重启 Agent',
m.restart,
+1 -1
View File
@@ -16,7 +16,7 @@ publish_to: 'none' # Remove this line if you wish to publish to pub.dev
# https://developer.apple.com/library/archive/documentation/General/Reference/InfoPlistKeyReference/Articles/CoreFoundationKeys.html
# In Windows, build-name is used as the major, minor, and patch parts
# of the product and file versions while build-number is used as the build suffix.
version: 0.2.6+7
version: 0.2.7+8
environment:
sdk: ^3.14.0
+34 -1
View File
@@ -44,7 +44,12 @@ class FakeApi implements AgentApi {
'configured': false,
},
],
'config_get' => {'id': agent, 'devices': <Object?>[]},
'config_get' => {
'id': agent,
'devices': <Object?>[],
'ignored_usb_serials': ['USB-A', 'USB-B'],
'usb_device_ids': {'USB-A': 'stable-id'},
},
'logs' => {
'instance': 'i',
'next': 1,
@@ -72,6 +77,34 @@ class FakeApi implements AgentApi {
}
void main() {
test(
'USB policy applies only to selected agent and preserves identity memory',
() async {
final api = FakeApi();
final m = AgentModel(AgentRepository(api));
await m.refresh();
m.select('two');
await m.setAutoUsb(true);
final enabled = api.calls.lastWhere((c) => c['op'] == 'config_set');
expect(enabled['agent'], 'two');
expect((enabled['config'] as Map)['auto_register_usb'], true);
expect((enabled['config'] as Map)['usb_device_ids'], {
'USB-A': 'stable-id',
});
m.adbSerial = 'USB-A';
await m.unignoreUsb();
expect((api.calls.last['config'] as Map)['ignored_usb_serials'], [
'USB-B',
]);
await m.setAutoUsb(false);
expect(
(api.calls.lastWhere((c) => c['op'] == 'config_set')['config']
as Map)['auto_register_usb'],
false,
);
m.dispose();
},
);
test(
'selected agent scopes mutations and log secrets are redacted',
() async {
+17
View File
@@ -202,6 +202,23 @@ def main():
wait_until(lambda: listed() == {'direct-phone'}, 'hung ADB query expires')
adb.set(delay=0)
wait_until(lambda: listed() == {'direct-phone', 'phone-a'}, 'query timeout recovery respects disabled device')
# Policy operations use existing ConfigGet/Set so older controllers need no protocol upgrade.
assert cli('config', 'get')['auto_register_usb'] is False
cli('devices', 'auto-usb', 'on')
assert cli('config', 'get')['auto_register_usb'] is True
cli('devices', 'remove', 'phone-b')
saved = cli('config', 'get')
assert 'USB-B' in saved['ignored_usb_serials']
cli('devices', 'unignore', 'USB-B')
assert 'USB-B' not in cli('config', 'get')['ignored_usb_serials']
stale = cli('config', 'get')
cli('devices', 'auto-usb', 'off')
conflict = subprocess.run([str(args.rust_dir/('adsctl'+suffix)), '--json', '--config', str(config), 'request'],
input=json.dumps({'op':'config_set','config':stale,'expected_config':stale}),
env=environment(), capture_output=True, text=True, encoding='utf-8', timeout=8)
assert conflict.returncode != 0, 'stale policy overwrote a concurrent configuration change'
assert cli('config', 'get')['auto_register_usb'] is False
print('PASS: USB policy defaults off; removal persists ignore; CLI can unignore and disable')
print('PASS: missing/offline/unauthorized/server failure withdraw registration; recovery preserves IDs and PID')
print('PASS: one poll per ADB server; other phone stream stays live; old stream closes and reconnects; disabled stays disabled')
finally: