feat: add headless agent management to CLI and both desktop clients

This commit is contained in:
tongtong committed 2026-11-12 21:17:44 +08:00
1 parent e91fa0235c
commit 6916dd54fb
50 files changed
+4837 -148

No files matched your search

+4 -2
View File
@@ -13,15 +13,17 @@
| 目录 | 作用 | 主要语言/格式 |
| --- | --- | --- |
| `agent/` | 远程设备守护程序 ads-agent,注册设备、连接手机 ADB、建立转发并重连;源码在 `src/` | Rust、TOML |
| `agent/` | 无界面多手机守护程序 ads-agent、独立监督进程、私有 IPC 和远程管理;兼容单设备参数;源码在 `src/` | Rust、TOML |
| `ctl/` | adsctl 命令行管理端,本机/远程设备、配置、日志、重启及系统启动托管;源码在 `src/` | Rust、TOML |
| `usb/` | 可选 ads-usb 本机虚拟 ADB USB 设备,提供回环 USB/IP、描述符和 ADB 帧适配;Windows 使用已签名 USBip 虚拟控制器 | Rust、TOML |
| `client/` | 本地守护程序 ads-client,维护设备租约、监听本地端口并自动调用 adb connect;源码在 `src/` | Rust、TOML |
| `server/` | ads-server 控制中心、旧协议兼容转发及独立 ads-relay 中继节点 | Go |
| `server/cmd/ads-relay/` | 独立中继入口,提供短期票据认证、WSS 数据配对及可选 STUN | Go |
| `server/internal/relay/` | 中继票据、数据通道、租约撤销、STUN 与测试 | Go |
| `crates/` | Rust 工作区共享库容器 | Rust、TOML |
| `crates/ads-management/` | Agent 配置及管理协议、Windows 命名管道/Unix socket、私有文件与系统服务操作;源码在 `src/` | Rust、TOML |
| `crates/ads-core/` | 共用网络与协议代码,包括 WSS、WebRTC P2P、节点回退、ADB smart socket 和流式转发;源码在 `src/` | Rust、TOML |
| `flutter_manager/` | 独立 Flutter Windows 管理中心,提供设备/中继总览、多设备连接、本机 ADB、托盘与独立 scrcpy 窗口 | Dart、C++、CMake、YAML、ICO |
| `flutter_manager/` | 独立 Flutter Windows 管理中心,提供设备/中继总览、Agent 管理、多设备连接、本机 ADB、托盘与独立 scrcpy 窗口 | Dart、C++、CMake、YAML、ICO |
| `desktop/` | 跨平台桌面客户端及其测试项目、.NET SDK 配置与使用说明 | C#、Avalonia XAML(AXAML)、JSON、Markdown |
| `desktop/Ads.Desktop/` | Avalonia 多设备工作台,管理独立连接、自动端口分配、USB 模拟、多个 scrcpy 窗口及托盘;`Assets/` 保存图标资源 | C#、AXAML、XML(csproj)、PNG |
| `desktop/Ads.Desktop.Tests/` | 桌面客户端单元测试 | C#、XML(csproj) |
Generated
+38 -4
View File
@@ -4,18 +4,24 @@ version = 4
[[package]]
name = "ads-agent"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"ads-core",
"ads-management",
"anyhow",
"clap",
"libc",
"serde",
"serde_json",
"tokio",
"tracing",
"tracing-subscriber",
"windows-sys 0.61.2",
]
[[package]]
name = "ads-client"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"ads-core",
"anyhow",
@@ -26,7 +32,7 @@ dependencies = [
[[package]]
name = "ads-core"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"anyhow",
"bytes",
@@ -43,9 +49,25 @@ dependencies = [
"webrtc",
]
[[package]]
name = "ads-management"
version = "0.2.0"
dependencies = [
"ads-core",
"anyhow",
"futures-util",
"libc",
"serde",
"serde_json",
"sha2",
"tokio",
"tokio-tungstenite",
"windows-sys 0.61.2",
]
[[package]]
name = "ads-usb"
version = "0.1.0"
version = "0.2.0"
dependencies = [
"anyhow",
"clap",
@@ -54,6 +76,18 @@ dependencies = [
"tracing-subscriber",
]
[[package]]
name = "adsctl"
version = "0.2.0"
dependencies = [
"ads-core",
"ads-management",
"anyhow",
"clap",
"serde_json",
"tokio",
]
[[package]]
name = "aead"
version = "0.5.2"
+2 -2
View File
@@ -1,9 +1,9 @@
[workspace]
members = ["crates/ads-core", "agent", "client", "usb"]
members = ["crates/ads-core", "agent", "client", "usb", "crates/ads-management", "ctl"]
resolver = "2"
[workspace.package]
version = "0.1.0"
version = "0.2.0"
edition = "2021"
license = "MIT"
+10 -3
View File
@@ -10,6 +10,8 @@
relay-1 / relay-2 / …
```
Agent 管理已同时接入 Avalonia 和 Flutter;服务器无需 GUI,可使用 `adsctl` 管理本机或远程 Agent。安装与命令示例见 [Agent 管理](docs/agent-management.md)。
Windows 现支持可选的 [USB ADB 模拟](docs/windows-usb.md),默认网络模式保持不变。
已部署的集群和使用方法见 [集群部署与协议](docs/cluster.md)。不配置集群时保留原有 v1 单中继模式,供兼容旧客户端;以下原有单机启动命令也仍可使用。
@@ -20,15 +22,17 @@ Windows 现支持可选的 [USB ADB 模拟](docs/windows-usb.md),默认网络
| 目录 | 作用 | 主要语言/格式 |
| --- | --- | --- |
| `agent/` | 远程设备守护程序 ads-agent,注册设备、连接手机 ADB、建立转发并重连;源码在 `src/` | Rust、TOML |
| `agent/` | 无界面多手机守护程序 ads-agent、独立监督进程、私有 IPC 和远程管理;兼容单设备参数;源码在 `src/` | Rust、TOML |
| `ctl/` | adsctl 命令行管理端,本机/远程设备、配置、日志、重启及系统启动托管;源码在 `src/` | Rust、TOML |
| `usb/` | 可选 ads-usb 本机虚拟 ADB USB 设备,提供回环 USB/IP、描述符和 ADB 帧适配;Windows 使用已签名 USBip 虚拟控制器 | Rust、TOML |
| `client/` | 本地守护程序 ads-client,维护设备租约、监听本地端口并自动调用 adb connect;源码在 `src/` | Rust、TOML |
| `server/` | ads-server 控制中心、旧协议兼容转发及独立 ads-relay 中继节点 | Go |
| `server/cmd/ads-relay/` | 独立中继入口,提供短期票据认证、WSS 数据配对及可选 STUN | Go |
| `server/internal/relay/` | 中继票据、数据通道、租约撤销、STUN 与测试 | Go |
| `crates/` | Rust 工作区共享库容器 | Rust、TOML |
| `crates/ads-management/` | Agent 配置及管理协议、Windows 命名管道/Unix socket、私有文件与系统服务操作;源码在 `src/` | Rust、TOML |
| `crates/ads-core/` | 共用网络与协议代码,包括 WSS、WebRTC P2P、节点回退、ADB smart socket 和流式转发;源码在 `src/` | Rust、TOML |
| `flutter_manager/` | 独立 Flutter Windows 管理中心,提供设备/中继总览、多设备连接、本机 ADB、托盘与独立 scrcpy 窗口 | Dart、C++、CMake、YAML、ICO |
| `flutter_manager/` | 独立 Flutter Windows 管理中心,提供设备/中继总览、Agent 管理、多设备连接、本机 ADB、托盘与独立 scrcpy 窗口 | Dart、C++、CMake、YAML、ICO |
| `desktop/` | 跨平台桌面客户端及其测试项目、.NET SDK 配置与使用说明 | C#、Avalonia XAML(AXAML)、JSON、Markdown |
| `desktop/Ads.Desktop/` | Avalonia 多设备工作台,管理独立连接、自动端口分配、USB 模拟、多个 scrcpy 窗口及托盘;`Assets/` 保存图标资源 | C#、AXAML、XML(csproj)、PNG |
| `desktop/Ads.Desktop.Tests/` | 桌面客户端单元测试 | C#、XML(csproj) |
@@ -59,10 +63,11 @@ Windows 现支持可选的 [USB ADB 模拟](docs/windows-usb.md),默认网络
| `server/` | `ads-server` / `ads-relay` | 控制中心:认证、注册、设备独占、信令、健康检查;独立中继:数据转发 |
| `agent/` | `ads-agent` | 远程电脑后台进程,主动注册设备、接通手机、断线重连 |
| `client/` | `ads-client` | 本地后台进程,保持设备租约,提供本地端口,自动调用 `adb connect` |
| `crates/ads-management/` | Agent 配置及管理协议、Windows 命名管道/Unix socket、私有文件与系统服务操作;源码在 `src/` | Rust、TOML |
| `crates/ads-core/` | 共用 Rust 库 | WSS、协议、ADB smart socket、流式转发 |
| `deploy/` | 部署示例 | Caddy、systemd、launchd 示例 |
四个网络后端与可选 ads-usb 均为独立可执行文件;另有 Avalonia 桌面工作台,不依赖 Python 运行正式程序。两端守护程序当前作为前台长运行进程,启动安装交给各平台进程管理器;尚未实现原生 Windows Service 安装器。
网络后端、adsctl 与可选 ads-usb 均为独立可执行文件,不依赖 Python 运行正式程序。Agent 可由 Windows 计划任务或 Linux systemd 托管;Avalonia 与 Flutter 管理界面是可选入口。Windows 使用计划任务,并非原生 SCM 服务。
## 编译
@@ -218,3 +223,5 @@ python tests/real_device.py --adb-server 192.168.5.222:5037 --serial 192.168.100
## 桌面客户端(Avalonia)
设备列表、配置、连接管理、托盘、运行日志及 scrcpy 独立窗口手机控制现已放在 `desktop/`。启动和工具路径配置见 [桌面客户端说明](desktop/README.md)。
Agent 管理发行入口:`scripts/build-desktop.ps1` 生成 `bin/desktop-win-x64/`,`scripts/build-flutter.ps1` 生成 `bin/flutter-win-x64/`,两者均包含 Agent/CLI,均不包含私有凭据。Avalonia 本机 Agent 托盘使用 `scripts/start-agent-tray.ps1`。
+9
View File
@@ -10,3 +10,12 @@ anyhow.workspace = true
clap.workspace = true
tokio.workspace = true
tracing.workspace = true
ads-management = { path = "../crates/ads-management" }
serde.workspace = true
serde_json.workspace = true
tracing-subscriber.workspace = true
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_System_JobObjects", "Win32_System_Threading"] }
[target.'cfg(unix)'.dependencies]
libc = "0.2"
+126
View File
@@ -0,0 +1,126 @@
use ads_core::{adb_tcp_connect, dial, next_control, relay, tcp_connect, NetworkArgs};
use anyhow::{bail, Context, Result};
use std::{sync::Arc, time::Duration};
use tokio::{net::TcpStream, task::JoinSet, time::sleep};
use tracing::{info, warn};
#[derive(Clone)]
pub struct Gateway {
pub network: NetworkArgs,
pub token: String,
pub device: String,
pub target: Option<String>,
pub adb_serial: Option<String>,
pub adb_server: String,
pub device_port: u16,
}
#[derive(Default, Clone)]
pub struct Health {
pub connected: bool,
pub last_error: Option<String>,
}
pub type WorkerHealth = Arc<std::sync::Mutex<Health>>;
async fn upstream(args: &Gateway) -> Result<TcpStream> {
match &args.target {
Some(address) => tcp_connect(address).await,
None => {
adb_tcp_connect(
&args.adb_server,
args.adb_serial.as_deref().context("missing serial")?,
args.device_port,
)
.await
}
}
}
async fn serve_session(
args: Arc<Gateway>,
session: String,
signal_key: Option<String>,
) -> Result<()> {
let tcp = upstream(&args).await.context("cannot reach phone adbd")?;
if let Some(key) = signal_key {
let signal = dial(
args.network
.url("/v2/signal", &[("session", &session), ("key", &key)])?,
&args.token,
args.network.connect_address.as_deref(),
)
.await?;
return ads_core::transport::agent_session(tcp, signal, &args.network).await;
}
let ws = dial(
args.network.url(
"/v1/data",
&[("device", &args.device), ("session", &session)],
)?,
&args.token,
args.network.connect_address.as_deref(),
)
.await?;
relay(tcp, ws).await
}
async fn online(args: Arc<Gateway>, health: &Option<WorkerHealth>) -> Result<()> {
let mut ws = dial(
args.network
.url("/v1/agent", &[("device", &args.device), ("v", "2")])?,
&args.token,
args.network.connect_address.as_deref(),
)
.await?;
let hello = next_control(&mut ws).await?;
if hello.kind != "registered" {
bail!("expected registered response");
}
if let Some(health) = health {
let mut state = health.lock().unwrap_or_else(|e| e.into_inner());
state.connected = true;
state.last_error = None;
}
info!(device = %args.device, "gateway registered");
let mut tasks = JoinSet::new();
loop {
tokio::select! {
message = next_control(&mut ws) => {
let message = message?;
if message.kind != "open" && message.kind != "open_v2" { bail!("unexpected gateway control message"); }
let signal_key = if message.kind == "open_v2" { Some(message.signal_key.context("missing signal key")?) } else { None };
let session = message.session.context("missing session ticket")?;
if tasks.len() >= 32 { warn!("gateway stream limit reached"); continue; }
let args = args.clone();
let health = health.clone();
tasks.spawn(async move {
let device=args.device.clone();
if let Err(error) = serve_session(args, session, signal_key).await {
if let Some(health)=health {health.lock().unwrap_or_else(|e|e.into_inner()).last_error=Some(error.to_string());}
warn!(%device,%error, "device stream ended");
}
});
},
_ = tasks.join_next(), if !tasks.is_empty() => {},
}
}
// JoinSet drop aborts all streams when the control connection is lost.
}
pub async fn run(args: Arc<Gateway>, health: Option<WorkerHealth>) {
let mut delay = 1;
loop {
let started = std::time::Instant::now();
if let Err(error) = online(args.clone(), &health).await {
if let Some(health) = &health {
let mut state = health.lock().unwrap_or_else(|e| e.into_inner());
state.connected = false;
state.last_error = Some(error.to_string());
}
warn!(device=%args.device,%error, "gateway offline; reconnecting");
}
if started.elapsed() > Duration::from_secs(30) {
delay = 1;
}
sleep(Duration::from_secs(delay)).await;
delay = (delay * 2).min(30);
}
}
+57 -113
View File
@@ -1,34 +1,34 @@
use ads_core::{
adb_tcp_connect, dial, init_logging, next_control, relay, tcp_connect, valid_device_id,
validate_token, NetworkArgs,
};
mod gateway;
mod managed;
mod supervisor;
use ads_core::{valid_device_id, validate_token, NetworkArgs};
use ads_management::{credential, AgentConfig};
use anyhow::{bail, Context, Result};
use clap::Parser;
use std::{sync::Arc, time::Duration};
use tokio::{net::TcpStream, task::JoinSet, time::sleep};
use tracing::{info, warn};
use std::{path::PathBuf, sync::Arc};
#[derive(Parser)]
#[command(
version,
about = "Remote device gateway: outbound-only connection to the ADS relay"
about = "ADS agent: managed multi-device gateway or legacy single-device worker"
)]
struct Args {
#[command(flatten)]
network: NetworkArgs,
#[arg(long, env = "ADS_AGENT_TOKEN", hide_env_values = true)]
token: String,
/// Stable public device alias, e.g. home-phone
token: Option<String>,
#[arg(long)]
device: String,
/// Direct phone adbd address reachable from this gateway, e.g. 192.168.100.141:5555
#[arg(
long,
required_unless_present = "adb_serial",
conflicts_with = "adb_serial"
)]
config: Option<PathBuf>,
/// Supervise the headless child; required for management restart
#[arg(long, requires = "config")]
supervise: bool,
/// Retain managed logs in memory without console output
#[arg(long)]
quiet: bool,
#[arg(long)]
device: Option<String>,
#[arg(long, conflicts_with = "adb_serial")]
target: Option<String>,
/// Alternative: choose a transport from an existing ADB server (phone must have TCP adbd enabled)
#[arg(long)]
adb_serial: Option<String>,
#[arg(long, default_value = "127.0.0.1:5037")]
@@ -36,105 +36,49 @@ struct Args {
#[arg(long, default_value_t = 5555)]
device_port: u16,
}
async fn upstream(args: &Args) -> Result<TcpStream> {
match &args.target {
Some(address) => tcp_connect(address).await,
None => {
adb_tcp_connect(
&args.adb_server,
args.adb_serial.as_deref().context("missing serial")?,
args.device_port,
)
.await
}
}
}
async fn serve_session(args: Arc<Args>, session: String, signal_key: Option<String>) -> Result<()> {
let tcp = upstream(&args).await.context("cannot reach phone adbd")?;
if let Some(key) = signal_key {
let signal = dial(
args.network
.url("/v2/signal", &[("session", &session), ("key", &key)])?,
&args.token,
args.network.connect_address.as_deref(),
)
.await?;
return ads_core::transport::agent_session(tcp, signal, &args.network).await;
}
let ws = dial(
args.network.url(
"/v1/data",
&[("device", &args.device), ("session", &session)],
)?,
&args.token,
args.network.connect_address.as_deref(),
)
.await?;
relay(tcp, ws).await
}
async fn online(args: Arc<Args>) -> Result<()> {
let mut ws = dial(
args.network
.url("/v1/agent", &[("device", &args.device), ("v", "2")])?,
&args.token,
args.network.connect_address.as_deref(),
)
.await?;
let hello = next_control(&mut ws).await?;
if hello.kind != "registered" {
bail!("expected registered response");
}
info!(device = %args.device, "gateway registered");
let mut tasks = JoinSet::new();
loop {
tokio::select! {
message = next_control(&mut ws) => {
let message = message?;
if message.kind != "open" && message.kind != "open_v2" { bail!("unexpected gateway control message"); }
let signal_key = if message.kind == "open_v2" { Some(message.signal_key.context("missing signal key")?) } else { None };
let session = message.session.context("missing session ticket")?;
if tasks.len() >= 32 { warn!("gateway stream limit reached"); continue; }
let args = args.clone();
tasks.spawn(async move {
if let Err(error) = serve_session(args, session, signal_key).await { warn!(%error, "device stream ended"); }
});
},
_ = tasks.join_next(), if !tasks.is_empty() => {},
}
}
// JoinSet drop aborts all streams when the control connection is lost.
}
async fn run(args: Arc<Args>) {
let mut delay = 1;
loop {
let started = std::time::Instant::now();
if let Err(error) = online(args.clone()).await {
warn!(%error, "gateway offline; reconnecting");
}
if started.elapsed() > Duration::from_secs(30) {
delay = 1;
}
sleep(Duration::from_secs(delay)).await;
delay = (delay * 2).min(30);
}
}
#[tokio::main]
async fn main() -> Result<()> {
init_logging();
let args = Args::parse();
validate_token(&args.token)?;
if !valid_device_id(&args.device) {
bail!("invalid device ID (use letters, digits, -, _, .; max 128 bytes)");
if args.quiet {
std::env::set_var("ADS_LOG_STDOUT", "0");
}
args.network.url("/v1/agent", &[])?;
tokio::select! {
_ = run(Arc::new(args)) => {},
result = tokio::signal::ctrl_c() => { result?; info!("gateway stopping"); },
if let Some(path) = args.config {
if args.device.is_some() || args.target.is_some() || args.adb_serial.is_some() {
bail!("managed config cannot be combined with single-device arguments")
}
let path = std::fs::canonicalize(path).context("agent config not found")?;
if args.supervise {
return supervisor::run(path).await;
}
let config = AgentConfig::load(&path)?;
let token = match args.token {
Some(value) => value,
None => credential(&path.with_file_name("agent.env"), "ADS_AGENT_TOKEN")?,
};
validate_token(&token)?;
let restart = managed::run(path, config, token).await?;
if restart {
std::process::exit(75)
}
} else {
ads_core::init_logging();
let token = args.token.context("provide ADS_AGENT_TOKEN")?;
validate_token(&token)?;
let device = args.device.context("provide --device or --config")?;
if !valid_device_id(&device) || args.target.is_none() == args.adb_serial.is_none() {
bail!("valid device and exactly one of --target / --adb-serial are required")
}
args.network.url("/v1/agent", &[])?;
let worker = gateway::Gateway {
network: args.network,
token,
device,
target: args.target,
adb_serial: args.adb_serial,
adb_server: args.adb_server,
device_port: args.device_port,
};
tokio::select! {_=gateway::run(Arc::new(worker),None)=>{},result=tokio::signal::ctrl_c()=>{result?;}}
}
Ok(())
}
+374
View File
@@ -0,0 +1,374 @@
use crate::gateway::{self, Gateway, Health, WorkerHealth};
use ads_management::{
now, read_ws, write_ws, AgentConfig, AgentStatus, DeviceStatus, LogEntry, LogPage, Request,
Response,
};
use anyhow::{bail, Context, Result};
use serde::Deserialize;
use std::{
collections::{BTreeMap, VecDeque},
path::PathBuf,
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use tokio::{
sync::{watch, Mutex as AsyncMutex},
task::JoinHandle,
time::{interval, sleep},
};
use tracing_subscriber::{
layer::{Context as LayerContext, SubscriberExt},
util::SubscriberInitExt,
Layer,
};
struct Logs {
entries: VecDeque<LogEntry>,
next: u64,
secret: String,
instance: String,
}
#[derive(Clone)]
struct LogLayer(Arc<Mutex<Logs>>);
struct Visitor(String);
impl tracing::field::Visit for Visitor {
fn record_debug(&mut self, field: &tracing::field::Field, value: &dyn std::fmt::Debug) {
if !self.0.is_empty() {
self.0.push(' ')
};
self.0.push_str(field.name());
self.0.push('=');
self.0.push_str(&format!("{value:?}"));
}
}
impl<S: tracing::Subscriber> Layer<S> for LogLayer {
fn on_event(&self, event: &tracing::Event<'_>, _: LayerContext<'_, S>) {
let mut visitor = Visitor(String::new());
event.record(&mut visitor);
let mut logs = self.0.lock().unwrap_or_else(|e| e.into_inner());
let message = visitor
.0
.replace(&logs.secret, "[REDACTED]")
.chars()
.take(1024)
.collect();
let entry = LogEntry {
seq: logs.next,
time: now(),
level: event.metadata().level().to_string(),
message,
};
logs.next += 1;
logs.entries.push_back(entry);
while logs.entries.len() > 500 {
logs.entries.pop_front();
}
}
}
struct Worker {
config: ads_management::DeviceConfig,
health: WorkerHealth,
task: JoinHandle<()>,
}
impl Drop for Worker {
fn drop(&mut self) {
self.task.abort();
}
}
struct State {
config: AgentConfig,
workers: BTreeMap<String, Worker>,
revision: u64,
}
struct Runtime {
path: PathBuf,
state: AsyncMutex<State>,
token: String,
logs: Arc<Mutex<Logs>>,
started: Instant,
restart: watch::Sender<bool>,
supervised: bool,
instance: String,
}
impl Runtime {
fn reconcile(&self, state: &mut State) {
let network = state.config.network();
let adb_server = state.config.adb_server.clone();
state.workers.retain(|id, worker| {
state
.config
.devices
.iter()
.any(|d| d.enabled && d.id == *id && *d == worker.config)
});
for device in &state.config.devices {
if !device.enabled || state.workers.contains_key(&device.id) {
continue;
}
let health = Arc::new(Mutex::new(Health::default()));
let gateway = Gateway {
network: network.clone(),
token: self.token.clone(),
device: device.id.clone(),
target: device.target.clone(),
adb_serial: device.adb_serial.clone(),
adb_server: device
.adb_server
.clone()
.unwrap_or_else(|| adb_server.clone()),
device_port: device.device_port,
};
let task = tokio::spawn(gateway::run(Arc::new(gateway), Some(health.clone())));
state.workers.insert(
device.id.clone(),
Worker {
config: device.clone(),
health,
task,
},
);
}
}
async fn status(&self) -> AgentStatus {
let state = self.state.lock().await;
let devices = state
.config
.devices
.iter()
.map(|config| {
let health = state
.workers
.get(&config.id)
.map(|w| w.health.lock().unwrap_or_else(|e| e.into_inner()).clone())
.unwrap_or_default();
DeviceStatus {
config: config.clone(),
connected: health.connected,
last_error: health
.last_error
.map(|e| e.replace(&self.token, "[REDACTED]")),
}
})
.collect();
AgentStatus {
id: state.config.id.clone(),
name: state.config.name.clone(),
hostname: std::env::var("COMPUTERNAME")
.or_else(|_| std::env::var("HOSTNAME"))
.unwrap_or_else(|_| "unknown".into()),
os: std::env::consts::OS.into(),
arch: std::env::consts::ARCH.into(),
version: env!("CARGO_PKG_VERSION").into(),
pid: std::process::id(),
uptime_seconds: self.started.elapsed().as_secs(),
supervised: self.supervised,
revision: state.revision,
instance: self.instance.clone(),
devices,
}
}
async fn execute(&self, request: Request) -> Result<Response> {
match request {
Request::Status => Ok(Response::success(self.status().await)),
Request::DevicesList => Ok(Response::success(self.status().await.devices)),
Request::ConfigGet => Ok(Response::success(&self.state.lock().await.config)),
Request::Logs { after, limit } => {
let logs = self.logs.lock().unwrap_or_else(|e| e.into_inner());
let after = if after >= logs.next { 0 } else { after };
let entries: Vec<_> = logs
.entries
.iter()
.filter(|e| e.seq > after)
.take(if limit == 0 { 50 } else { limit.min(50) } as usize)
.cloned()
.collect();
Ok(Response::success(LogPage {
instance: logs.instance.clone(),
next: entries.last().map(|e| e.seq).unwrap_or(after),
entries,
}))
}
Request::Restart => {
if !self.supervised {
bail!("restart requires --supervise or an installed managed service")
};
let sender = self.restart.clone();
tokio::spawn(async move {
sleep(Duration::from_millis(500)).await;
let _ = sender.send(true);
});
Ok(Response::success(serde_json::json!({"restarting":true})))
}
mutation => {
let mut state = self.state.lock().await;
let mut config = state.config.clone();
match mutation {
Request::DeviceAdd { device } => {
if config.devices.iter().any(|d| d.id == device.id) {
bail!("device ID already exists")
};
config.devices.push(device);
}
Request::DeviceRemove { id } => {
let count = config.devices.len();
config.devices.retain(|d| d.id != id);
if count == config.devices.len() {
bail!("device not found")
}
}
Request::DeviceEnable { id, enabled } => {
config
.devices
.iter_mut()
.find(|d| d.id == id)
.context("device not found")?
.enabled = enabled;
}
Request::ConfigSet { config: new } => {
if new.id != config.id {
bail!("agent ID is immutable; initialize a separate agent to change identity")
};
config = new;
}
_ => bail!("unsupported operation"),
}
config.validate()?;
let changed_network = config.server != state.config.server
|| config.connect_address != state.config.connect_address
|| config.allow_insecure != state.config.allow_insecure
|| config.adb_server != state.config.adb_server;
ads_management::save_private(&self.path, &serde_json::to_vec_pretty(&config)?)?;
if changed_network {
state.workers.clear();
}
state.config = config;
state.revision += 1;
self.reconcile(&mut state);
tracing::info!(revision = state.revision, "agent configuration applied");
Ok(Response::success(
serde_json::json!({"revision":state.revision}),
))
}
}
}
async fn handle(&self, request: Request) -> Response {
match self.execute(request).await {
Ok(value) => value,
Err(error) => Response::failure(error.to_string().replace(&self.token, "[REDACTED]")),
}
}
}
#[derive(Deserialize)]
struct Incoming {
#[serde(rename = "type")]
kind: String,
#[serde(default)]
request_id: String,
request: Option<Request>,
}
async fn online(runtime: Arc<Runtime>) -> Result<()> {
let config = runtime.state.lock().await.config.clone();
let network = config.network();
let mut ws = ads_core::dial(
network.url("/v3/agents/register", &[("agent", &config.id)])?,
&runtime.token,
network.connect_address.as_deref(),
)
.await?;
let hello: serde_json::Value = read_ws(&mut ws).await?;
if hello["type"] != "registered" {
bail!("invalid management registration")
}
tracing::info!(agent=%config.id,"agent management connected");
let mut heartbeat = interval(Duration::from_secs(5));
loop {
tokio::select! {
message=read_ws::<Incoming>(&mut ws)=>{
let message=message?;if message.kind!="request"||message.request_id.is_empty(){bail!("unexpected management message")}
let response=runtime.handle(message.request.context("missing request")?).await;
write_ws(&mut ws,&serde_json::json!({"type":"result","request_id":message.request_id,"response":response})).await?;
},
_=heartbeat.tick()=>{
let latest=runtime.state.lock().await.config.clone();
if latest.server!=config.server||latest.connect_address!=config.connect_address||latest.allow_insecure!=config.allow_insecure{bail!("management address changed")}
write_ws(&mut ws,&serde_json::json!({"type":"status","status":runtime.status().await})).await?;
}
}
}
}
pub async fn run(path: PathBuf, config: AgentConfig, token: String) -> Result<bool> {
let instance = format!(
"{}-{}-{}",
now(),
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)?
.subsec_nanos()
);
let logs = Arc::new(Mutex::new(Logs {
entries: VecDeque::new(),
next: 1,
secret: token.clone(),
instance: instance.clone(),
}));
tracing_subscriber::registry()
.with(
tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "ads_agent=info,ads_core=info,warn".into()),
)
.with(
tracing_subscriber::fmt::layer()
.with_ansi(false)
.with_filter(tracing_subscriber::filter::filter_fn(|_| {
std::env::var("ADS_LOG_STDOUT").as_deref() != Ok("0")
})),
)
.with(LogLayer(logs.clone()))
.init();
let (restart, mut restarting) = watch::channel(false);
let runtime = Arc::new(Runtime {
path: path.clone(),
state: AsyncMutex::new(State {
config,
workers: BTreeMap::new(),
revision: 1,
}),
token,
logs,
started: Instant::now(),
restart,
supervised: std::env::var("ADS_SUPERVISED").as_deref() == Ok("1"),
instance,
});
let handler: ads_management::ipc::Handler = {
let runtime = runtime.clone();
Arc::new(move |request| {
let runtime = runtime.clone();
Box::pin(async move { runtime.handle(request).await })
})
};
// Bind IPC before starting phone workers, so a duplicate process cannot steal devices.
let (ready_tx, ready_rx) = tokio::sync::oneshot::channel();
let ipc = ads_management::ipc::serve(&path, handler, ready_tx);
tokio::pin!(ipc);
let networking = async {
if ready_rx.await.is_err() {
std::future::pending::<()>().await;
}
{
let mut state = runtime.state.lock().await;
runtime.reconcile(&mut state);
}
let mut delay = 1;
loop {
if let Err(error) = online(runtime.clone()).await {
tracing::warn!(%error,"management offline; reconnecting")
};
sleep(Duration::from_secs(delay)).await;
delay = (delay * 2).min(30);
}
};
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}};
runtime.state.lock().await.workers.clear();
Ok(restart)
}
+120
View File
@@ -0,0 +1,120 @@
use ads_management::AgentConfig;
#[cfg(windows)]
use anyhow::Context;
use anyhow::Result;
use std::{path::PathBuf, time::Duration};
pub async fn shutdown() -> Result<()> {
#[cfg(unix)]
{
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
tokio::select! {value=tokio::signal::ctrl_c()=>{value?;},_=term.recv()=>{}}
}
#[cfg(windows)]
tokio::signal::ctrl_c().await?;
Ok(())
}
pub async fn run(path: PathBuf) -> Result<()> {
AgentConfig::load(&path)?;
let executable = std::env::current_exe()?;
let mut delay = 1;
#[cfg(windows)]
let job = Job::new()?;
loop {
let mut command = tokio::process::Command::new(&executable);
command
.arg("--config")
.arg(&path)
.env("ADS_SUPERVISED", "1")
.env("ADS_SUPERVISOR_PID", std::process::id().to_string())
.kill_on_drop(true);
#[cfg(windows)]
command.creation_flags(0x08000000);
#[cfg(target_os = "linux")]
{
let parent = std::process::id() as libc::pid_t;
unsafe {
command.pre_exec(move || {
if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM) != 0 {
return Err(std::io::Error::last_os_error());
}
if libc::getppid() != parent {
return Err(std::io::Error::other(
"supervisor exited before child startup",
));
}
Ok(())
});
}
}
let mut child = command.spawn()?;
#[cfg(windows)]
if let Err(error) = job.assign(
child
.raw_handle()
.context("child process handle unavailable")?,
) {
let _ = child.kill().await;
return Err(error);
}
let result = tokio::select! {
result=child.wait()=>result?,
result=shutdown()=>{
result?;
#[cfg(unix)]if let Some(pid)=child.id(){unsafe{libc::kill(pid as libc::pid_t,libc::SIGTERM);}}
#[cfg(unix)]if tokio::time::timeout(Duration::from_secs(3),child.wait()).await.is_ok(){return Ok(())}
let _=child.kill().await;return Ok(())
}
};
if result.success() {
return Ok(());
}
if result.code() == Some(75) {
delay = 1;
continue;
}
tokio::time::sleep(Duration::from_secs(delay)).await;
delay = (delay * 2).min(30);
}
}
#[cfg(windows)]
struct Job(windows_sys::Win32::Foundation::HANDLE);
#[cfg(windows)]
impl Job {
fn new() -> Result<Self> {
use windows_sys::Win32::System::JobObjects::*;
let handle = unsafe { CreateJobObjectW(std::ptr::null(), std::ptr::null()) };
if handle.is_null() {
return Err(std::io::Error::last_os_error().into());
}
let job = Self(handle);
let mut info: JOBOBJECT_EXTENDED_LIMIT_INFORMATION = unsafe { std::mem::zeroed() };
info.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
if unsafe {
SetInformationJobObject(
handle,
JobObjectExtendedLimitInformation,
&info as *const _ as _,
std::mem::size_of_val(&info) as u32,
)
} == 0
{
return Err(std::io::Error::last_os_error().into());
};
Ok(job)
}
fn assign(&self, child: std::os::windows::io::RawHandle) -> Result<()> {
if unsafe {
windows_sys::Win32::System::JobObjects::AssignProcessToJobObject(self.0, child as _)
} == 0
{
return Err(std::io::Error::last_os_error().into());
};
Ok(())
}
}
#[cfg(windows)]
impl Drop for Job {
fn drop(&mut self) {
unsafe { windows_sys::Win32::Foundation::CloseHandle(self.0) };
}
}
+21
View File
@@ -0,0 +1,21 @@
[package]
name = "ads-management"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
ads-core = { path = "../ads-core" }
anyhow.workspace = true
serde.workspace = true
serde_json.workspace = true
tokio.workspace = true
sha2 = "0.10"
futures-util.workspace = true
tokio-tungstenite.workspace = true
[target.'cfg(unix)'.dependencies]
libc = "0.2"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_Security", "Win32_Security_Authorization", "Win32_System_Memory"] }
+295
View File
@@ -0,0 +1,295 @@
use crate::{read_frame, write_frame, Request, Response};
use anyhow::{bail, Context, Result};
use sha2::{Digest, Sha256};
use std::{
future::Future,
path::{Path, PathBuf},
pin::Pin,
sync::Arc,
time::Duration,
};
use tokio::{
io::{AsyncRead, AsyncWrite},
task::JoinSet,
time::timeout,
};
pub type Handler =
Arc<dyn Fn(Request) -> Pin<Box<dyn Future<Output = Response> + Send>> + Send + Sync>;
fn absolute(path: &Path) -> Result<PathBuf> {
Ok(
std::fs::canonicalize(path.parent().context("missing config parent")?)?
.join(path.file_name().context("missing config filename")?),
)
}
pub fn endpoint(config: &Path) -> Result<String> {
let path = absolute(config)?;
if cfg!(windows) {
let normalized = path.to_string_lossy().to_lowercase();
let hash = Sha256::digest(normalized.as_bytes());
Ok(format!(r"\\.\pipe\ttstd-ads-{:x}", hash))
} else {
let hash = format!(
"{:x}",
Sha256::digest(path.file_name().unwrap().as_encoded_bytes())
);
Ok(path
.parent()
.unwrap()
.join(format!("agent-{}.sock", &hash[..16]))
.to_string_lossy()
.into_owned())
}
}
async fn connection(
mut socket: impl AsyncRead + AsyncWrite + Unpin,
handler: Handler,
) -> Result<()> {
let request = timeout(Duration::from_secs(5), read_frame(&mut socket)).await??;
let response = timeout(Duration::from_secs(12), handler(request)).await?;
timeout(Duration::from_secs(5), write_frame(&mut socket, &response)).await??;
Ok(())
}
pub async fn request(config: &Path, value: &Request) -> Result<Response> {
let name = endpoint(config)?;
timeout(Duration::from_secs(15), async {
#[cfg(windows)]
let connect_deadline = std::time::Instant::now() + Duration::from_secs(3);
#[cfg(windows)]
let mut socket = loop {
match tokio::net::windows::named_pipe::ClientOptions::new().open(&name) {
Ok(socket) => break socket,
Err(error)
if matches!(error.raw_os_error(), Some(2 | 231))
&& std::time::Instant::now() < connect_deadline =>
{
tokio::time::sleep(Duration::from_millis(50)).await
}
Err(error) => return Err(error.into()),
}
};
#[cfg(unix)]
let mut socket = tokio::net::UnixStream::connect(&name)
.await
.context("agent is not running or local socket is inaccessible")?;
write_frame(&mut socket, value).await?;
read_frame(&mut socket).await
})
.await
.context("local agent management timed out")?
}
#[cfg(unix)]
pub async fn serve(
config: &Path,
handler: Handler,
ready: tokio::sync::oneshot::Sender<()>,
) -> Result<()> {
use std::os::unix::fs::{FileTypeExt, MetadataExt, PermissionsExt};
let name = endpoint(config)?;
let path = PathBuf::from(&name);
let directory = std::fs::metadata(path.parent().unwrap())?;
if directory.mode() & 0o022 != 0 {
bail!("config directory must not be writable by other users")
}
let owner = directory.uid();
if path.exists() {
if tokio::net::UnixStream::connect(&path).await.is_ok() {
bail!("agent already running")
}
let metadata = std::fs::symlink_metadata(&path)?;
if !metadata.file_type().is_socket() || metadata.uid() != owner {
bail!("refusing to remove a foreign socket path")
}
std::fs::remove_file(&path)?;
}
let listener = tokio::net::UnixListener::bind(&path)?;
std::fs::set_permissions(&path, std::fs::Permissions::from_mode(0o600))?;
let cpath = std::ffi::CString::new(name)?;
if unsafe { libc::geteuid() } == 0
&& unsafe { libc::chown(cpath.as_ptr(), owner, u32::MAX) } != 0
{
bail!("cannot set local socket owner")
}
struct Cleanup(PathBuf);
impl Drop for Cleanup {
fn drop(&mut self) {
let _ = std::fs::remove_file(&self.0);
}
}
let _cleanup = Cleanup(path);
let _ = ready.send(());
let mut tasks = JoinSet::new();
loop {
tokio::select! {
accepted=listener.accept()=>{let(socket,_)=accepted?;if tasks.len()>=16{drop(socket);continue;}let handler=handler.clone();tasks.spawn(async move{let _=connection(socket,handler).await;});},
_=tasks.join_next(),if !tasks.is_empty()=>{},
}
}
}
#[cfg(windows)]
pub async fn serve(
config: &Path,
handler: Handler,
ready: tokio::sync::oneshot::Sender<()>,
) -> Result<()> {
use tokio::net::windows::named_pipe::ServerOptions;
let name = endpoint(config)?;
let security = Security::new(config.parent().context("missing config directory")?)?;
let create = |first: bool| -> Result<_> {
let mut attributes = security.attributes();
Ok(unsafe {
ServerOptions::new()
.first_pipe_instance(first)
.reject_remote_clients(true)
.create_with_security_attributes_raw(&name, &mut attributes as *mut _ as *mut _)
}?)
};
let mut server = create(true)
.context("cannot create private management pipe; agent may already be running")?;
let _ = ready.send(());
let mut tasks = JoinSet::new();
loop {
tokio::select! {
connected=server.connect()=>{connected?;let next=create(false)?;let socket=std::mem::replace(&mut server,next);if tasks.len()>=16{drop(socket);continue;}let handler=handler.clone();tasks.spawn(async move{let _=connection(socket,handler).await;});},
_=tasks.join_next(),if !tasks.is_empty()=>{},
}
}
}
#[cfg(windows)]
pub fn owner_sid(path: &Path) -> Result<String> {
use std::os::windows::ffi::OsStrExt;
use windows_sys::Win32::{
Foundation::LocalFree,
Security::{
Authorization::{ConvertSidToStringSidW, GetNamedSecurityInfoW, SE_FILE_OBJECT},
OWNER_SECURITY_INFORMATION,
},
};
let name: Vec<u16> = path.as_os_str().encode_wide().chain(Some(0)).collect();
let mut owner = std::ptr::null_mut();
let mut descriptor = std::ptr::null_mut();
let code = unsafe {
GetNamedSecurityInfoW(
name.as_ptr(),
SE_FILE_OBJECT,
OWNER_SECURITY_INFORMATION,
&mut owner,
std::ptr::null_mut(),
std::ptr::null_mut(),
std::ptr::null_mut(),
&mut descriptor,
)
};
if code != 0 {
bail!("cannot read config directory owner: {code}")
}
let mut sid = std::ptr::null_mut();
let result = unsafe { ConvertSidToStringSidW(owner, &mut sid) };
if result == 0 {
unsafe { LocalFree(descriptor) };
bail!("cannot format config owner SID")
}
let mut length = 0;
unsafe {
while *sid.add(length) != 0 {
length += 1;
}
}
let result = String::from_utf16_lossy(unsafe { std::slice::from_raw_parts(sid, length) });
unsafe {
LocalFree(sid as _);
LocalFree(descriptor);
}
Ok(result)
}
#[cfg(windows)]
struct Security(*mut std::ffi::c_void);
#[cfg(windows)]
unsafe impl Send for Security {}
#[cfg(windows)]
impl Security {
fn new(directory: &Path) -> Result<Self> {
use windows_sys::Win32::Security::Authorization::ConvertStringSecurityDescriptorToSecurityDescriptorW;
let owner = owner_sid(directory)?;
let sddl: Vec<u16> = format!("D:P(A;;GA;;;SY)(A;;GA;;;{owner})")
.encode_utf16()
.chain(Some(0))
.collect();
let mut descriptor = std::ptr::null_mut();
if unsafe {
ConvertStringSecurityDescriptorToSecurityDescriptorW(
sddl.as_ptr(),
1,
&mut descriptor,
std::ptr::null_mut(),
)
} == 0
{
bail!("cannot create private pipe ACL")
};
Ok(Self(descriptor))
}
fn attributes(&self) -> windows_sys::Win32::Security::SECURITY_ATTRIBUTES {
windows_sys::Win32::Security::SECURITY_ATTRIBUTES {
nLength: std::mem::size_of::<windows_sys::Win32::Security::SECURITY_ATTRIBUTES>()
as u32,
lpSecurityDescriptor: self.0,
bInheritHandle: 0,
}
}
}
#[cfg(windows)]
impl Drop for Security {
fn drop(&mut self) {
unsafe { windows_sys::Win32::Foundation::LocalFree(self.0) };
}
}
#[cfg(windows)]
pub fn protect_file(path: &Path, parent: &Path) -> Result<()> {
let sid = owner_sid(parent)?;
use std::os::windows::process::CommandExt;
let status = std::process::Command::new("icacls.exe")
.creation_flags(0x08000000)
.arg(path)
.args([
"/inheritance:r",
"/grant:r",
&format!("*{sid}:(F)"),
"*S-1-5-18:(F)",
"/Q",
])
.stdout(std::process::Stdio::null())
.stderr(std::process::Stdio::null())
.status()?;
if !status.success() {
bail!("cannot restrict private file permissions")
};
Ok(())
}
#[cfg(unix)]
pub fn protect_file(path: &Path, parent: &Path) -> Result<()> {
use std::os::unix::ffi::OsStrExt;
use std::os::unix::fs::MetadataExt;
let metadata = std::fs::metadata(parent)?;
if metadata.mode() & 0o022 != 0 {
bail!("config directory must not be writable by other users")
}
if unsafe { libc::geteuid() } == 0 {
let path = std::ffi::CString::new(path.as_os_str().as_bytes())?;
if unsafe { libc::chown(path.as_ptr(), metadata.uid(), u32::MAX) } != 0 {
bail!("cannot preserve config owner")
}
}
Ok(())
}
#[cfg(test)]
mod tests {
#[test]
fn config_filenames_have_isolated_management_endpoints() {
let folder = std::env::temp_dir();
assert_ne!(
super::endpoint(&folder.join("first-agent.json")).unwrap(),
super::endpoint(&folder.join("second-agent.json")).unwrap()
);
}
}
+367
View File
@@ -0,0 +1,367 @@
pub mod ipc;
pub mod service;
use ads_core::{valid_device_id, validate_token, NetworkArgs};
use anyhow::{bail, Context, Result};
use futures_util::{SinkExt, StreamExt};
use serde::{Deserialize, Serialize};
use std::{
collections::HashSet,
path::{Path, PathBuf},
time::{SystemTime, UNIX_EPOCH},
};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
use tokio_tungstenite::tungstenite::Message;
pub const MAX_FRAME: usize = 128 * 1024;
pub fn now() -> u64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap_or_default()
.as_secs()
}
fn yes() -> bool {
true
}
fn adb_port() -> u16 {
5555
}
fn adb_server() -> String {
"127.0.0.1:5037".into()
}
fn version() -> u32 {
1
}
#[derive(Clone, Serialize, Deserialize, PartialEq, Eq, Debug)]
#[serde(deny_unknown_fields)]
pub struct DeviceConfig {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub target: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub adb_serial: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub adb_server: Option<String>,
#[serde(default = "adb_port")]
pub device_port: u16,
#[serde(default = "yes")]
pub enabled: bool,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
#[serde(deny_unknown_fields)]
pub struct AgentConfig {
#[serde(default = "version")]
pub version: u32,
pub id: String,
pub name: String,
pub server: String,
#[serde(default)]
pub connect_address: Option<String>,
#[serde(default)]
pub allow_insecure: bool,
#[serde(default = "adb_server")]
pub adb_server: String,
#[serde(default)]
pub devices: Vec<DeviceConfig>,
}
impl AgentConfig {
pub fn network(&self) -> NetworkArgs {
NetworkArgs {
server: self.server.clone(),
connect_address: self.connect_address.clone(),
allow_insecure: self.allow_insecure,
}
}
pub fn validate(&self) -> Result<()> {
if self.version != 1
|| !valid_device_id(&self.id)
|| self.name.is_empty()
|| self.name.len() > 128
|| self.name.chars().any(char::is_control)
{
bail!("invalid agent version, ID or name")
}
if serde_json::to_vec_pretty(self)?.len() > 64 * 1024 {
bail!("agent config exceeds 64 KiB")
}
self.network().url("/v3/agents/register", &[])?;
validate_address(&self.adb_server)?;
if let Some(address) = &self.connect_address {
validate_address(address)?;
}
if self.devices.len() > 128 {
bail!("at most 128 devices per agent")
}
let mut ids = HashSet::new();
for device in &self.devices {
if !valid_device_id(&device.id) || !ids.insert(&device.id) || device.device_port == 0 {
bail!("invalid or duplicate device ID/port")
}
if device.target.is_some() == device.adb_serial.is_some() {
bail!("each device requires exactly one of target or adb_serial")
}
if let Some(target) = &device.target {
validate_address(target)?;
}
if let Some(server) = &device.adb_server {
validate_address(server)?;
}
if let Some(serial) = &device.adb_serial {
if serial.is_empty() || serial.len() > 256 || serial.chars().any(char::is_control) {
bail!("invalid adb_serial")
}
}
}
Ok(())
}
pub fn load(path: &Path) -> Result<Self> {
let data = std::fs::read(path).context("cannot read agent config")?;
if data.len() > 64 * 1024 {
bail!("agent config exceeds 64 KiB")
};
let config: Self = serde_json::from_slice(&data).context("invalid agent config JSON")?;
config.validate()?;
Ok(config)
}
}
fn validate_address(value: &str) -> Result<()> {
if value.is_empty()
|| value.len() > 256
|| value.chars().any(|c| c.is_whitespace() || c.is_control())
{
bail!("invalid host:port address")
}
let (host, port) = value
.rsplit_once(':')
.context("address requires host:port")?;
if host.is_empty() || port.parse::<u16>().unwrap_or(0) == 0 {
bail!("invalid host:port address")
};
Ok(())
}
#[derive(Clone, Serialize, Deserialize, Debug)]
#[serde(tag = "op", rename_all = "snake_case", deny_unknown_fields)]
pub enum Request {
Status,
DevicesList,
DeviceAdd {
device: DeviceConfig,
},
DeviceRemove {
id: String,
},
DeviceEnable {
id: String,
enabled: bool,
},
ConfigGet,
ConfigSet {
config: AgentConfig,
},
Logs {
#[serde(default)]
after: u64,
#[serde(default)]
limit: u32,
},
Restart,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct Response {
pub ok: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub data: Option<serde_json::Value>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub error: Option<String>,
}
impl Response {
pub fn success(value: impl Serialize) -> Self {
Self {
ok: true,
data: Some(serde_json::to_value(value).unwrap_or_default()),
error: None,
}
}
pub fn failure(error: impl ToString) -> Self {
Self {
ok: false,
data: None,
error: Some(error.to_string()),
}
}
pub fn value(self) -> Result<serde_json::Value> {
if !self.ok {
bail!(
"{}",
self.error
.unwrap_or_else(|| "management request failed".into())
)
};
Ok(self.data.unwrap_or_default())
}
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct DeviceStatus {
#[serde(flatten)]
pub config: DeviceConfig,
pub connected: bool,
pub last_error: Option<String>,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct AgentStatus {
pub id: String,
pub name: String,
pub hostname: String,
pub os: String,
pub arch: String,
pub version: String,
pub pid: u32,
pub uptime_seconds: u64,
pub supervised: bool,
pub revision: u64,
pub instance: String,
pub devices: Vec<DeviceStatus>,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct LogEntry {
pub seq: u64,
pub time: u64,
pub level: String,
pub message: String,
}
#[derive(Clone, Serialize, Deserialize, Debug)]
pub struct LogPage {
pub instance: String,
pub next: u64,
pub entries: Vec<LogEntry>,
}
pub fn default_config() -> PathBuf {
if cfg!(windows) {
PathBuf::from(std::env::var_os("LOCALAPPDATA").unwrap_or_else(|| ".".into()))
.join("AndroidDeviceStreaming/agent/agent.json")
} else {
PathBuf::from(
std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.unwrap_or_else(|| {
PathBuf::from(std::env::var_os("HOME").unwrap_or_else(|| ".".into()))
.join(".config")
}),
)
.join("ads/agent.json")
}
}
pub fn credential(path: &Path, key: &str) -> Result<String> {
if let Ok(value) = std::env::var(key) {
validate_token(&value)?;
return Ok(value);
}
let data = std::fs::read_to_string(path).context(
"credential file not found; set the role token in env or provide its private env file",
)?;
for line in data.lines() {
if let Some(value) = line.strip_prefix(&format!("{key}=")) {
validate_token(value)?;
return Ok(value.into());
}
}
bail!("missing {key}")
}
pub fn save_private(path: &Path, data: &[u8]) -> Result<()> {
let parent = path
.parent()
.context("configuration requires a parent directory")?;
std::fs::create_dir_all(parent)?;
let temporary = parent.join(format!(
".ads-{}-{}.tmp",
std::process::id(),
SystemTime::now().duration_since(UNIX_EPOCH)?.as_nanos()
));
use std::io::Write;
let mut options = std::fs::OpenOptions::new();
options.write(true).create_new(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
options.mode(0o600);
}
let result = (|| -> Result<()> {
let mut file = options.open(&temporary)?;
ipc::protect_file(&temporary, parent)?;
file.write_all(data)?;
file.sync_all()?;
drop(file);
std::fs::rename(&temporary, path)?;
Ok(())
})();
if result.is_err() {
let _ = std::fs::remove_file(&temporary);
}
result
}
pub async fn read_frame<T: for<'de> Deserialize<'de>>(
stream: &mut (impl AsyncRead + Unpin),
) -> Result<T> {
let size = stream.read_u32_le().await? as usize;
if size == 0 || size > MAX_FRAME {
bail!("invalid management frame length")
};
let mut data = vec![0; size];
stream.read_exact(&mut data).await?;
Ok(serde_json::from_slice(&data)?)
}
pub async fn write_frame(
stream: &mut (impl AsyncWrite + Unpin),
value: &impl Serialize,
) -> Result<()> {
let data = serde_json::to_vec(value)?;
if data.len() > MAX_FRAME {
bail!("management response too large")
};
stream.write_u32_le(data.len() as u32).await?;
stream.write_all(&data).await?;
stream.flush().await?;
Ok(())
}
pub async fn read_ws<T: for<'de> Deserialize<'de>>(ws: &mut ads_core::Ws) -> Result<T> {
loop {
match ws.next().await.context("management connection closed")?? {
Message::Text(data) => return Ok(serde_json::from_str(&data)?),
Message::Ping(data) => ws.send(Message::Pong(data)).await?,
Message::Pong(_) => {}
_ => bail!("management connection closed or invalid message"),
}
}
}
pub async fn write_ws(ws: &mut ads_core::Ws, value: &impl Serialize) -> Result<()> {
let data = serde_json::to_string(value)?;
if data.len() > MAX_FRAME {
bail!("management response too large")
};
ws.send(Message::Text(data.into())).await?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn accepted_config_fits_the_restart_loader_limit() {
let mut cfg: AgentConfig = serde_json::from_value(serde_json::json!({
"id":"host", "name":"Host", "server":"wss://example.com/ads", "devices":[]
}))
.unwrap();
cfg.validate().unwrap();
let host = format!("{}:5555", "a".repeat(240));
for index in 0..128 {
cfg.devices.push(DeviceConfig {
id: format!("phone-{index}"),
target: Some(host.clone()),
adb_serial: None,
adb_server: Some(host.clone()),
device_port: 5555,
enabled: true,
});
}
assert!(serde_json::to_vec_pretty(&cfg).unwrap().len() > 64 * 1024);
assert!(cfg.validate().unwrap_err().to_string().contains("64 KiB"));
}
}
+170
View File
@@ -0,0 +1,170 @@
#[cfg(unix)]
use crate::save_private;
use crate::AgentConfig;
use anyhow::{bail, Context, Result};
use std::path::Path;
#[cfg(unix)]
use std::path::PathBuf;
#[derive(Clone, Copy)]
pub enum Action {
Install,
Start,
Stop,
Restart,
Status,
Uninstall,
}
fn safe_path(path: &Path) -> Result<String> {
let text = path.to_str().context("service paths must be valid UTF-8")?;
#[cfg(windows)]
let text = text.strip_prefix(r"\\?\").unwrap_or(text);
if text.chars().any(char::is_control) {
bail!("service path contains control characters")
};
Ok(text.into())
}
#[cfg(windows)]
fn ps(value: &str) -> String {
format!("'{}'", value.replace(char::from(39), "''"))
}
#[cfg(windows)]
pub fn run(action: Action, config: &Path, _system: bool, start_now: bool) -> Result<()> {
let cfg = AgentConfig::load(config)?;
let config = std::fs::canonicalize(config)?;
let executable = std::env::current_exe()?.with_file_name("ads-agent.exe");
let executable =
std::fs::canonicalize(executable).context("place ads-agent.exe next to adsctl.exe")?;
let name = format!("ADS-Agent-{}", cfg.id);
let executable = safe_path(&executable)?;
let path = safe_path(&config)?;
let arguments = format!("--quiet --supervise --config \"{path}\"");
let guard=format!("$task=Get-ScheduledTask -TaskName {} -ErrorAction SilentlyContinue; if($task -and -not (@($task.Actions | Where-Object {{ $_.Execute -eq {} -and $_.Arguments -eq {} }}).Count)) {{ throw 'A foreign task owns this name' }};",ps(&name),ps(&executable),ps(&arguments));
let body=match action{
Action::Install=>format!("$action=New-ScheduledTaskAction -Execute {} -Argument {}; $trigger=New-ScheduledTaskTrigger -AtStartup; $settings=New-ScheduledTaskSettingsSet -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero) -StartWhenAvailable -MultipleInstances IgnoreNew; Register-ScheduledTask -TaskName {} -Action $action -Trigger $trigger -Settings $settings -User SYSTEM -RunLevel Highest -Force | Out-Null; {}",ps(&executable),ps(&arguments),ps(&name),if start_now {format!("Start-ScheduledTask -TaskName {};",ps(&name))} else {String::new()}),
Action::Start=>format!("Start-ScheduledTask -TaskName {};",ps(&name)),
Action::Stop=>format!("Stop-ScheduledTask -TaskName {};",ps(&name)),
Action::Restart=>format!("Stop-ScheduledTask -TaskName {}; Start-Sleep -Seconds 1; Start-ScheduledTask -TaskName {};",ps(&name),ps(&name)),
Action::Status=>format!("Get-ScheduledTask -TaskName {} | Select-Object TaskName,State; Get-ScheduledTaskInfo -TaskName {};",ps(&name),ps(&name)),
Action::Uninstall=>format!("Stop-ScheduledTask -TaskName {} -ErrorAction SilentlyContinue; Unregister-ScheduledTask -TaskName {} -Confirm:$false;",ps(&name),ps(&name)),
};
use std::os::windows::process::CommandExt;
let output = std::process::Command::new("powershell.exe")
.creation_flags(0x08000000)
.args([
"-NoProfile",
"-NonInteractive",
"-Command",
&format!("$ErrorActionPreference='Stop';{guard}{body}"),
])
.output()?;
eprint!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
if !output.status.success() {
bail!("Windows service operation failed; install/uninstall require an elevated administrator terminal")
};
Ok(())
}
#[cfg(unix)]
pub fn run(action: Action, config: &Path, system: bool, start_now: bool) -> Result<()> {
if !cfg!(target_os = "linux") {
bail!("native service install currently supports Linux systemd and Windows Task Scheduler; run ads-agent --supervise manually on this platform")
}
let cfg = AgentConfig::load(config)?;
let config = std::fs::canonicalize(config)?;
let executable = std::fs::canonicalize(std::env::current_exe()?.with_file_name("ads-agent"))
.context("place ads-agent next to adsctl")?;
let unit = format!("ads-agent-{}.service", cfg.id);
let folder = if system {
PathBuf::from("/etc/systemd/system")
} else {
PathBuf::from(std::env::var_os("HOME").context("HOME is missing")?)
.join(".config/systemd/user")
};
let path = folder.join(&unit);
let marker = format!(
"# Managed by ADSCTL {}\n# Config: {}\n# Executable: {}\n",
cfg.id,
safe_path(&config)?,
safe_path(&executable)?
);
let systemctl = |args: &[&str]| -> Result<()> {
let mut command = std::process::Command::new("systemctl");
if !system {
command.arg("--user");
}
let output = command.args(args).output()?;
eprint!(
"{}{}",
String::from_utf8_lossy(&output.stdout),
String::from_utf8_lossy(&output.stderr)
);
if !output.status.success() {
bail!("systemctl failed; check service privileges and availability")
};
Ok(())
};
let guard = || -> Result<()> {
if path.exists() && !std::fs::read_to_string(&path)?.starts_with(&marker) {
bail!("a foreign systemd unit owns this name")
};
Ok(())
};
guard()?;
match action {
Action::Install => {
let mut user = String::new();
if system {
use std::os::unix::fs::MetadataExt;
let owner = std::fs::metadata(config.parent().unwrap())?.uid();
let output = std::process::Command::new("id")
.args(["-un", &owner.to_string()])
.output()?;
if !output.status.success() {
bail!("cannot resolve service config owner")
};
let name = String::from_utf8(output.stdout)?.trim().to_string();
if name.is_empty()
|| !name
.bytes()
.all(|c| c.is_ascii_alphanumeric() || b"_-.".contains(&c))
{
bail!("unsupported service account name")
};
user = format!("User={name}\n");
}
fn quote(path: &Path) -> Result<String> {
Ok(format!(
"\"{}\"",
safe_path(path)?
.replace('%', "%%")
.replace('\\', "\\\\")
.replace('\"', "\\\"")
))
}
let body=format!("{marker}[Unit]\nDescription=ADS managed agent {}\nAfter=network-online.target\nWants=network-online.target\n[Service]\nType=simple\n{user}ExecStart={} --quiet --supervise --config {}\nRestart=on-failure\nRestartSec=3\nNoNewPrivileges=true\nPrivateTmp=true\n[Install]\nWantedBy={}\n",cfg.id,quote(&executable)?,quote(&config)?,if system{"multi-user.target"}else{"default.target"});
save_private(&path, body.as_bytes())?;
systemctl(&["daemon-reload"])?;
if start_now {
systemctl(&["enable", "--now", &unit])?;
} else {
systemctl(&["enable", &unit])?;
}
}
Action::Start => systemctl(&["start", &unit])?,
Action::Stop => systemctl(&["stop", &unit])?,
Action::Restart => systemctl(&["restart", &unit])?,
Action::Status => systemctl(&["status", "--no-pager", &unit])?,
Action::Uninstall => {
guard()?;
systemctl(&["disable", "--now", &unit])?;
if path.exists() {
std::fs::remove_file(path)?;
}
systemctl(&["daemon-reload"])?;
}
}
Ok(())
}
+12
View File
@@ -0,0 +1,12 @@
[package]
name = "adsctl"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
ads-core = { path = "../crates/ads-core" }
ads-management = { path = "../crates/ads-management" }
anyhow.workspace = true
clap.workspace = true
serde_json.workspace = true
tokio.workspace = true
+342
View File
@@ -0,0 +1,342 @@
use ads_core::{validate_token, NetworkArgs};
use ads_management::{AgentConfig, DeviceConfig, LogPage, Request, Response};
use anyhow::{bail, Context, Result};
use clap::{Parser, Subcommand};
use std::{path::PathBuf, time::Duration};
#[derive(Parser)]
#[command(version, about = "ADS headless agent management CLI")]
struct Args {
#[command(flatten)]
network: NetworkArgs,
#[arg(long, global = true)]
config: Option<PathBuf>,
/// Remote agent ID; omit for local named pipe / Unix socket
#[arg(long, global = true)]
agent: Option<String>,
#[arg(long, global = true)]
credentials: Option<PathBuf>,
#[arg(long, global = true)]
json: bool,
#[command(subcommand)]
command: Command,
}
#[derive(Subcommand, Clone)]
enum Command {
Init {
#[arg(long)]
id: String,
#[arg(long)]
name: Option<String>,
},
Status,
Restart,
/// Read one structured request from stdin (for GUI and automation clients)
Request,
Agents {
#[command(subcommand)]
command: Agents,
},
Devices {
#[command(subcommand)]
command: Devices,
},
Config {
#[command(subcommand)]
command: Config,
},
Logs {
#[arg(long)]
follow: bool,
#[arg(long, default_value_t = 0)]
after: u64,
#[arg(long, default_value_t = 50)]
limit: u32,
},
Service {
#[command(subcommand)]
command: Service,
#[arg(long, global = true)]
system: bool,
},
}
#[derive(Subcommand, Clone)]
enum Agents {
List,
}
#[derive(Subcommand, Clone)]
enum Devices {
List,
Add {
#[arg(long)]
id: String,
#[arg(
long,
conflicts_with = "adb_serial",
required_unless_present = "adb_serial"
)]
target: Option<String>,
#[arg(long)]
adb_serial: Option<String>,
#[arg(long)]
adb_server: Option<String>,
#[arg(long, default_value_t = 5555)]
device_port: u16,
},
Remove {
id: String,
},
Enable {
id: String,
},
Disable {
id: String,
},
}
#[derive(Subcommand, Clone)]
enum Config {
Get,
Validate {
#[arg(long)]
file: Option<PathBuf>,
},
Set {
#[arg(long)]
file: PathBuf,
},
}
#[derive(Subcommand, Clone)]
enum Service {
Install,
Start,
Stop,
Restart,
Status,
Uninstall,
}
fn print_value(value: &serde_json::Value, json: bool) -> Result<()> {
if json {
println!("{}", serde_json::to_string(value)?)
} else {
println!("{}", serde_json::to_string_pretty(value)?)
};
Ok(())
}
async fn invoke(args: &Args, request: &Request) -> Result<Response> {
if let Some(id) = &args.agent {
if !ads_core::valid_device_id(id) {
bail!("invalid remote agent ID")
}
let credential = args
.credentials
.clone()
.unwrap_or_else(|| ads_management::default_config().with_file_name("admin.env"));
let token = ads_management::credential(&credential, "ADS_ADMIN_TOKEN")?;
let mut ws = ads_core::dial(
args.network.url("/v3/rpc", &[("agent", id)])?,
&token,
args.network.connect_address.as_deref(),
)
.await?;
ads_management::write_ws(&mut ws, request).await?;
tokio::time::timeout(Duration::from_secs(20), ads_management::read_ws(&mut ws))
.await
.context("remote management request timed out")?
} else {
ads_management::ipc::request(
&args
.config
.clone()
.unwrap_or_else(ads_management::default_config),
request,
)
.await
}
}
#[tokio::main]
async fn main() -> Result<()> {
let mut args = Args::parse();
// A private admin.env may carry the same optional TCP origin override as client.env.
if args.network.connect_address.is_none() {
if let Some(path) = &args.credentials {
if let Ok(data) = std::fs::read_to_string(path) {
for line in data.lines() {
if let Some(value) = line.strip_prefix("ADS_CONNECT_ADDRESS=") {
args.network.connect_address = Some(value.into());
}
}
}
}
}
let config = args
.config
.clone()
.unwrap_or_else(ads_management::default_config);
match &args.command {
Command::Init { id, name } => {
if args.agent.is_some() {
bail!("init is a local operation")
};
if config.exists() {
bail!("config already exists; use config set to update it")
}
let cfg = AgentConfig {
version: 1,
id: id.clone(),
name: name.clone().unwrap_or_else(|| id.clone()),
server: args.network.server.clone(),
connect_address: args.network.connect_address.clone(),
allow_insecure: args.network.allow_insecure,
adb_server: "127.0.0.1:5037".into(),
devices: vec![],
};
cfg.validate()?;
let source = args
.credentials
.clone()
.unwrap_or_else(|| config.with_file_name("agent.env"));
let token = ads_management::credential(&source, "ADS_AGENT_TOKEN")?;
validate_token(&token)?;
ads_management::save_private(
&config.with_file_name("agent.env"),
format!("ADS_AGENT_TOKEN={token}\n").as_bytes(),
)?;
ads_management::save_private(&config, &serde_json::to_vec_pretty(&cfg)?)?;
return print_value(&serde_json::json!({"config":config,"agent":id}), args.json);
}
Command::Agents { .. } => {
let path = args
.credentials
.clone()
.unwrap_or_else(|| config.with_file_name("admin.env"));
let token = ads_management::credential(&path, "ADS_ADMIN_TOKEN")?;
let mut ws = ads_core::dial(
args.network.url("/v3/agents", &[])?,
&token,
args.network.connect_address.as_deref(),
)
.await?;
let value: serde_json::Value = ads_management::read_ws(&mut ws).await?;
return print_value(&value, args.json);
}
Command::Config {
command: Config::Validate { file },
} => {
let cfg = if args.agent.is_some() && file.is_none() {
let value = invoke(&args, &Request::ConfigGet).await?.value()?;
let value: AgentConfig = serde_json::from_value(value)?;
value.validate()?;
value
} else {
AgentConfig::load(file.as_ref().unwrap_or(&config))?
};
return print_value(
&serde_json::json!({"valid":true,"agent":cfg.id,"devices":cfg.devices.len()}),
args.json,
);
}
Command::Service { command, system } => {
if args.agent.is_some() {
bail!("service installation and OS service operations are local only; use restart for remote managed restart")
}
use ads_management::service::Action;
let action = match command {
Service::Install => Action::Install,
Service::Start => Action::Start,
Service::Stop => Action::Stop,
Service::Restart => Action::Restart,
Service::Status => Action::Status,
Service::Uninstall => Action::Uninstall,
};
let start_now = !matches!(action, Action::Install)
|| ads_management::ipc::request(&config, &Request::Status)
.await
.is_err();
ads_management::service::run(action, &config, *system, start_now)?;
return print_value(&serde_json::json!({"ok":true}), args.json);
}
Command::Logs {
follow,
after,
limit,
} => {
let mut cursor = *after;
let mut instance = String::new();
loop {
let value = invoke(
&args,
&Request::Logs {
after: cursor,
limit: *limit,
},
)
.await?
.value()?;
let page: LogPage = serde_json::from_value(value.clone())?;
if !instance.is_empty() && instance != page.instance {
cursor = 0;
instance = page.instance;
continue;
}
cursor = page.next;
instance = page.instance;
if args.json {
print_value(&value, true)?
} else {
for entry in page.entries {
println!("{} {} {}", entry.time, entry.level, entry.message)
}
}
if !follow {
return Ok(());
}
tokio::select! {_=tokio::time::sleep(Duration::from_secs(1))=>{},_=tokio::signal::ctrl_c()=>return Ok(())}
}
}
_ => {}
}
let request = match args.command.clone() {
Command::Request => {
use std::io::Read;
let mut input = Vec::new();
std::io::stdin().take(65537).read_to_end(&mut input)?;
if input.len() > 65536 {
bail!("request exceeds 64 KiB")
};
serde_json::from_slice::<Request>(&input)?
}
Command::Status => Request::Status,
Command::Restart => Request::Restart,
Command::Devices { command } => match command {
Devices::List => Request::DevicesList,
Devices::Add {
id,
target,
adb_serial,
adb_server,
device_port,
} => Request::DeviceAdd {
device: DeviceConfig {
id,
target,
adb_serial,
adb_server,
device_port,
enabled: true,
},
},
Devices::Remove { id } => Request::DeviceRemove { id },
Devices::Enable { id } => Request::DeviceEnable { id, enabled: true },
Devices::Disable { id } => Request::DeviceEnable { id, enabled: false },
},
Command::Config {
command: Config::Get,
} => Request::ConfigGet,
Command::Config {
command: Config::Set { ref file },
} => Request::ConfigSet {
config: AgentConfig::load(file)?,
},
_ => unreachable!(),
};
print_value(&invoke(&args, &request).await?.value()?, args.json)
}
+16
View File
@@ -54,3 +54,19 @@ Get-Content "$env:LOCALAPPDATA\AndroidDeviceStreaming\agent\logs\agent.log" -Tai
Start-ScheduledTask -TaskName ADS-Agent
Stop-ScheduledTask -TaskName ADS-Agent
```
## Managed multi-phone Agent (0.2)
The deployed computer has migrated to Agent ID `home-pc` (家里电脑), retaining `home-phone` and its TCP endpoint. `ADS-Agent-home-pc` runs the native supervised Agent as SYSTEM at startup; the old `ADS-Agent` task is disabled. The migration keeps a timestamped backup under the protected Agent directory and restores the legacy files/task on failure. No reboot was performed.
`migrate-managed.ps1` migrates the earlier TCP single-phone installation. Stage the new binaries as `ads-agent.exe.new` and `adsctl.exe.new` in its directory, then run the script in an elevated PowerShell 7 terminal. It verifies the legacy task belongs to that directory before stopping it. Parameters customize directory, Agent ID, display name and old task name. New installations should use `adsctl init` and `adsctl service install` instead.
For current status and logs, use:
```powershell
& "$env:LOCALAPPDATA/AndroidDeviceStreaming/agent/adsctl.exe" status
& "$env:LOCALAPPDATA/AndroidDeviceStreaming/agent/adsctl.exe" logs --follow
Get-ScheduledTask -TaskName ADS-Agent-home-pc
```
The managed log buffer is in memory; the old runner log is historical. See [Agent management](../../docs/agent-management.md) for Linux and Windows headless setup, CLI commands, role credentials and both GUIs.
+67
View File
@@ -0,0 +1,67 @@
param(
[string]$Directory = (Join-Path $env:LOCALAPPDATA 'AndroidDeviceStreaming/agent'),
[string]$Id = 'home-pc',
[string]$Name = '家里电脑',
[string]$LegacyTask = 'ADS-Agent'
)
$ErrorActionPreference = 'Stop'
$ProgressPreference = 'SilentlyContinue'
$root = [IO.Path]::GetFullPath($Directory).TrimEnd('\')
$configPath = Join-Path $root 'agent.json'
$exe = Join-Path $root 'ads-agent.exe'
$ctl = Join-Path $root 'adsctl.exe'
$old = Get-Content -LiteralPath $configPath -Raw | ConvertFrom-Json
if ($old.devices -or $old.id) { throw 'Already managed; use adsctl config commands instead' }
if (-not $old.device -or -not $old.target) { throw 'Expected legacy TCP phone configuration' }
$task = Get-ScheduledTask -TaskName $LegacyTask -ErrorAction Stop
if (-not @($task.Actions | Where-Object { $_.Arguments -and $_.Arguments.Contains($root) }).Count) { throw 'Legacy task does not belong to the requested Agent directory' }
if (Get-ScheduledTask -TaskName "ADS-Agent-$Id" -ErrorAction SilentlyContinue) { throw 'Managed task already exists' }
foreach ($file in @('ads-agent.exe.new', 'adsctl.exe.new')) {
if (-not (Test-Path -LiteralPath (Join-Path $root $file))) { throw "Missing staged $file" }
}
$backup = Join-Path $root ('backup-management-' + (Get-Date -Format yyyyMMdd-HHmmss))
New-Item -ItemType Directory -Path $backup | Out-Null
foreach ($file in @('agent.json','ads-agent.exe','adsctl.exe')) {
$path = Join-Path $root $file
if (Test-Path -LiteralPath $path) { Copy-Item -LiteralPath $path -Destination $backup }
}
Export-ScheduledTask -TaskName $LegacyTask | Set-Content -LiteralPath (Join-Path $backup 'legacy-task.xml') -Encoding utf8
$next = [ordered]@{version=1;id=$Id;name=$Name;server=$old.server;connect_address=$old.connect_address;adb_server='127.0.0.1:5037';devices=@(@{id=$old.device;target=$old.target;enabled=$true})}
try {
Disable-ScheduledTask -TaskName $LegacyTask | Out-Null
Stop-ScheduledTask -TaskName $LegacyTask
Get-CimInstance Win32_Process -Filter "Name='ads-agent.exe'" | Where-Object { $_.ExecutablePath -eq $exe } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }
Start-Sleep -Seconds 1
Move-Item -LiteralPath (Join-Path $root 'ads-agent.exe.new') -Destination $exe -Force
Move-Item -LiteralPath (Join-Path $root 'adsctl.exe.new') -Destination $ctl -Force
$next | ConvertTo-Json -Depth 10 | Set-Content -LiteralPath $configPath -Encoding utf8NoBOM
& $ctl --config $configPath config validate --file $configPath
if ($LASTEXITCODE) { throw 'Managed config validation failed' }
& $ctl --config $configPath service install
if ($LASTEXITCODE) { throw 'Managed service installation failed' }
$ready=$false
for ($i=0; $i -lt 10; $i++) {
Start-Sleep -Seconds 1
$raw = & $ctl --json --config $configPath status 2>$null
if ($LASTEXITCODE -eq 0 -and ($raw | ConvertFrom-Json).id -eq $Id) { $ready=$true;break }
}
if (-not $ready) { throw 'Managed Agent did not become ready' }
Write-Output "Migration succeeded; backup: $backup"
& $ctl --json --config $configPath status
} catch {
$failure=$_
$managed=Get-ScheduledTask -TaskName "ADS-Agent-$Id" -ErrorAction SilentlyContinue
if ($managed -and @($managed.Actions | Where-Object { $_.Execute -eq $exe -and $_.Arguments.Contains($configPath) }).Count) {
Stop-ScheduledTask -TaskName "ADS-Agent-$Id" -ErrorAction SilentlyContinue
Unregister-ScheduledTask -TaskName "ADS-Agent-$Id" -Confirm:$false
}
Get-CimInstance Win32_Process -Filter "Name='ads-agent.exe'" | Where-Object { $_.ExecutablePath -eq $exe } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
Start-Sleep -Seconds 1
foreach ($file in @('agent.json','ads-agent.exe','adsctl.exe')) {
$saved=Join-Path $backup $file
if (Test-Path -LiteralPath $saved) { Copy-Item -LiteralPath $saved -Destination (Join-Path $root $file) -Force }
}
Enable-ScheduledTask -TaskName $LegacyTask | Out-Null
Start-ScheduledTask -TaskName $LegacyTask
throw $failure
}
+2 -2
View File
@@ -14,8 +14,8 @@ $logFile = Join-Path $logDirectory 'agent.log'
if ((Test-Path -LiteralPath $logFile) -and (Get-Item -LiteralPath $logFile).Length -gt 10MB) {
Move-Item -LiteralPath $logFile -Destination ($logFile + '.1') -Force
}
$arguments = @('--server', [string]$config.server, '--device', [string]$config.device, '--target', [string]$config.target)
if ($config.connect_address) { $arguments += @('--connect-address', [string]$config.connect_address) }
$arguments = if ($config.id -and $config.devices -ne $null) { @('--quiet', '--supervise', '--config', (Join-Path $root 'agent.json')) } else { @('--server', [string]$config.server, '--device', [string]$config.device, '--target', [string]$config.target) }
if (-not $config.id -and $config.connect_address) { $arguments += @('--connect-address', [string]$config.connect_address) }
# Keep the child in this task's process tree. Task Scheduler owns its lifecycle.
# Tracing writes to stdout; stderr is also retained for startup diagnostics.
$ErrorActionPreference = 'Continue'
+40 -1
View File
@@ -24,7 +24,7 @@ internal static class Program
Exception? failure = null;
Dispatcher.UIThread.Post(async () =>
{
try { if (args.Contains("--multi")) await RunMultiAsync(args.Contains("--usb")); else await RunAsync(args.Contains("--live"), args.Contains("--screen"), args.Contains("--usb")); }
try { if (args.Contains("--agents")) await RunAgentsAsync(args.Contains("--local-agent")); else if (args.Contains("--multi")) await RunMultiAsync(args.Contains("--usb")); else await RunAsync(args.Contains("--live"), args.Contains("--screen"), args.Contains("--usb")); }
catch (Exception error) { failure = error; }
finally { finished.Cancel(); }
});
@@ -48,6 +48,45 @@ internal static class Program
}
}
private static async Task RunAgentsAsync(bool local)
{
var root=DesktopPaths.ProjectRoot()!;
using var vm=new MainViewModel(Path.Combine(root,"work","agent-gui-smoke",Guid.NewGuid().ToString("N")),backgroundMonitoring:false,loadLocalCredentials:true);
var m=vm.AgentManager;m.AutoRefresh=false;m.LocalMode=local;
if(local)m.ConfigPath=Environment.GetEnvironmentVariable("ADS_TEST_AGENT_CONFIG")!;
var id=Environment.GetEnvironmentVariable("ADS_TEST_MANAGED_AGENT")!;
var window=new MainWindow{DataContext=vm};window.Show();
window.FindControl<TabControl>("MainTabs")!.SelectedItem=window.FindControl<TabItem>("AgentManagementTab");
async Task WaitState(Func<bool> predicate,string message){var deadline=DateTime.UtcNow.AddSeconds(50);while(!predicate()){await m.RefreshAgentsCommand.ExecuteAsync(null);m.SelectedAgent=m.Agents.FirstOrDefault(a=>a.Id==id);if(DateTime.UtcNow>deadline)throw new InvalidOperationException(message+": "+m.Notice);await Task.Delay(300);}}
try {
await WaitState(()=>m.SelectedAgent?.Id==id&&m.SelectedAgent.Online,"Agent not discovered");
await m.LoadConfigCommand.ExecuteAsync(null);
using(var config=System.Text.Json.JsonDocument.Parse(m.ConfigJson))Require(config.RootElement.GetProperty("id").GetString()==id,"Wrong agent configuration");
var node=System.Text.Json.Nodes.JsonNode.Parse(m.ConfigJson)!;node["name"]="GUI managed test";m.ConfigJson=node.ToJsonString();await m.SaveConfigCommand.ExecuteAsync(null);
await WaitState(()=>m.SelectedAgent?.Status.Name=="GUI managed test","Config mutation not applied");
m.DeviceId=id+"-phone";m.Target="127.0.0.1:9";await m.AddDeviceCommand.ExecuteAsync(null);
await WaitState(()=>m.AgentDevices.Any(d=>d.Id==m.DeviceId),"Phone add not visible");
m.SelectedManagedDevice=m.AgentDevices.Single(d=>d.Id==m.DeviceId);await m.DisableDeviceCommand.ExecuteAsync(null);
await WaitState(()=>m.AgentDevices.Any(d=>d.Id==m.DeviceId&&!d.Enabled),"Phone disable failed");
await m.EnableDeviceCommand.ExecuteAsync(null);await WaitState(()=>m.AgentDevices.Any(d=>d.Id==m.DeviceId&&d.Enabled),"Phone enable failed");
await m.ReadLogsCommand.ExecuteAsync(null);Require(m.RemoteLogText.Length>0,"Managed logs were empty");
var view=window.GetVisualDescendants().OfType<AgentManagementView>().Single();
Require(view.FindControl<TextBox>("AgentConfigBox")?.Text==m.ConfigJson,"Agent config binding failed");
using(var frame=window.CaptureRenderedFrame())frame?.Save(Path.Combine(root,"work",local?"agent-local.png":"agent-management.png"));
await m.RemoveDeviceCommand.ExecuteAsync(null);await WaitState(()=>m.AgentDevices.All(d=>d.Id!=m.DeviceId),"Phone removal failed");
var pid=m.SelectedAgent!.Status.Pid;await m.RestartAgentCommand.ExecuteAsync(null);
await WaitState(()=>m.SelectedAgent?.Online==true&&m.SelectedAgent.Status.Pid>0&&m.SelectedAgent.Status.Pid!=pid,"Supervisor restart failed");
Require(!m.ConfigJson.Contains(m.AdminToken)||m.AdminToken.Length==0,"Admin token leaked to config");
Require(!m.RemoteLogText.Contains(m.AdminToken)||m.AdminToken.Length==0,"Admin token leaked to logs");
var oldPath=m.ConfigPath;var oldServer=vm.Server;
if(local)m.ConfigPath+=".different";else vm.Server="wss://changed-center.invalid/ads";
await m.LoadConfigCommand.ExecuteAsync(null);
Require(m.Notice.Contains("先刷新"),"A stale agent list allowed a request to a different source");
m.ConfigPath=oldPath;vm.Server=oldServer;
Console.WriteLine("PASS: "+(local?"local IPC":"remote admin")+" GUI status, config, device add/enable/disable/remove, logs, supervised restart and bindings");
} finally {await vm.ShutdownAsync();window.Close();}
}
private static async Task RunMultiAsync(bool usb)
{
var root = DesktopPaths.ProjectRoot()!;
+54
View File
@@ -0,0 +1,54 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Ads.Desktop;
public sealed record ManagedDevice(
string Id, string? Target, [property:JsonPropertyName("adb_serial")] string? AdbSerial,
[property:JsonPropertyName("adb_server")] string? AdbServer,
[property:JsonPropertyName("device_port")] int DevicePort, bool Enabled, bool Connected,
[property:JsonPropertyName("last_error")] string? LastError)
{
public string Description => $"{Id} · {(Enabled ? Connected ? LastError==null ? "已注册" : "转发异常" : "等待注册" : "已停用")} · {Target ?? AdbSerial}";
}
public sealed record ManagedStatus(string Id, string Name, string Hostname, string Os, string Arch, string Version, int Pid,
[property:JsonPropertyName("uptime_seconds")] long UptimeSeconds, bool Supervised, long Revision, string Instance, ManagedDevice[] Devices);
public sealed record ManagedAgent(string Id, bool Online, [property:JsonPropertyName("last_seen")] long LastSeen, ManagedStatus Status)
{
public string Description => $"{(string.IsNullOrWhiteSpace(Status.Name) ? Id : Status.Name)} · {(Online ? "在线" : "离线")} · {Status.Os} · {Status.Devices.Length} 台手机";
public string Details => $"{Id} · {Status.Hostname} · {Status.Os}/{Status.Arch} · v{Status.Version} · PID {Status.Pid} · 配置版本 {Status.Revision}";
}
public sealed record ManagementResponse(bool Ok, JsonElement? Data, string? Error)
{
public JsonElement Value() => Ok && Data.HasValue ? Data.Value : throw new InvalidOperationException(Error ?? "Agent 管理请求失败。");
}
public static class AgentManagementApi
{
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
private static Uri UriFor(RelayOptions options, string endpoint) => new UriBuilder(options.DevicesUri) {
Path = options.BaseUri.AbsolutePath.TrimEnd('/') + endpoint
}.Uri;
public static async Task<ManagedAgent[]> ListAsync(RelayOptions options, CancellationToken cancellation)
{
using var http = RelayApi.CreateClient(options);
using var request = new HttpRequestMessage(HttpMethod.Get, UriFor(options,"/v3/agents"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer",options.Token);
using var response = await http.SendAsync(request,cancellation); Check(response);
return await response.Content.ReadFromJsonAsync<ManagedAgent[]>(Json,cancellation) ?? [];
}
public static async Task<JsonElement> CallAsync(RelayOptions options, string agent, object operation, CancellationToken cancellation)
{
using var http = RelayApi.CreateClient(options); http.Timeout=TimeSpan.FromSeconds(20);
var uri = new UriBuilder(UriFor(options,"/v3/rpc")) { Query="agent="+Uri.EscapeDataString(agent) }.Uri;
using var request = new HttpRequestMessage(HttpMethod.Post,uri) { Content=JsonContent.Create(operation) };
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer",options.Token);
using var response = await http.SendAsync(request,cancellation); Check(response);
return (await response.Content.ReadFromJsonAsync<ManagementResponse>(Json,cancellation) ?? throw new InvalidOperationException("管理响应为空。")).Value();
}
private static void Check(HttpResponseMessage response)
{
if (response.StatusCode==System.Net.HttpStatusCode.Unauthorized) throw new InvalidOperationException("管理员凭据无效,需要 admin.env;手机连接令牌不具有管理权限。");
if (response.StatusCode==System.Net.HttpStatusCode.ServiceUnavailable) throw new InvalidOperationException("控制中心尚未配置 ADS_ADMIN_TOKEN。");
response.EnsureSuccessStatusCode();
}
}
@@ -0,0 +1,33 @@
<UserControl xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="Ads.Desktop.AgentManagementView">
<UserControl.Styles>
<Style Selector="Border.agentCard"><Setter Property="Background" Value="#192230"/><Setter Property="CornerRadius" Value="10"/><Setter Property="Padding" Value="16"/></Style>
<Style Selector="Button"><Setter Property="Padding" Value="12,8"/><Setter Property="Margin" Value="0,0,8,6"/></Style>
<Style Selector="TextBox"><Setter Property="Margin" Value="0,4,0,10"/></Style>
</UserControl.Styles>
<Grid RowDefinitions="Auto,*,Auto" Margin="0,14,0,0">
<StackPanel>
<WrapPanel><CheckBox x:Name="LocalAgentMode" Content="管理本机 Agent" IsChecked="{Binding LocalMode}" IsEnabled="{Binding !IsBusy}" Margin="0,0,20,8"/><CheckBox Content="自动刷新" IsChecked="{Binding AutoRefresh}"/><Button x:Name="RefreshAgentsButton" Content="刷新 Agent" Command="{Binding RefreshAgentsCommand}" IsEnabled="{Binding !IsBusy}" Margin="20,0,0,10"/></WrapPanel>
<StackPanel IsVisible="{Binding !LocalMode}"><TextBlock Text="远程管理使用工作台的控制中心地址,需要独立的管理员凭据。" TextWrapping="Wrap"/><Grid ColumnDefinitions="*,Auto"><TextBox x:Name="AdminTokenBox" Text="{Binding AdminToken}" PasswordChar="●" Watermark="ADS_ADMIN_TOKEN"/><Button Grid.Column="1" Content="导入 admin.env" Click="ImportAdminClick" Margin="12,4,0,10"/></Grid></StackPanel>
<StackPanel IsVisible="{Binding LocalMode}"><TextBlock Text="本机配置路径"/><TextBox Text="{Binding ConfigPath}"/><WrapPanel><Button Content="启动后台 Agent" Command="{Binding StartLocalCommand}"/><Button Content="安装开机服务" Command="{Binding InstallServiceCommand}"/></WrapPanel></StackPanel>
</StackPanel>
<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="#A8B7CC"/></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox></Grid></Border>
<ScrollViewer Grid.Column="1"><StackPanel Spacing="14">
<Border Classes="agentCard"><StackPanel Spacing="10"><TextBlock Text="{Binding SelectedAgent.Details}" TextWrapping="Wrap" Foreground="#66D9C0"/><WrapPanel><Button x:Name="LoadAgentConfigButton" Content="读取配置" Command="{Binding LoadConfigCommand}"/><Button Content="重启 Agent" Command="{Binding RestartAgentCommand}"/></WrapPanel><TextBlock Text="重启由监督进程执行,设备连接会短暂中断。" FontSize="12" Foreground="#A8B7CC"/></StackPanel></Border>
<Border Classes="agentCard"><StackPanel Spacing="8">
<TextBlock Text="手机管理" FontSize="18" FontWeight="SemiBold"/>
<ListBox x:Name="ManagedDevicesList" ItemsSource="{Binding AgentDevices}" SelectedItem="{Binding SelectedManagedDevice}" MinHeight="70" MaxHeight="180"><ListBox.ItemTemplate><DataTemplate><TextBlock Text="{Binding Description}" TextWrapping="Wrap" Margin="3,7"/></DataTemplate></ListBox.ItemTemplate></ListBox>
<WrapPanel><Button Content="启用" Command="{Binding EnableDeviceCommand}"/><Button Content="停用" Command="{Binding DisableDeviceCommand}"/><Button Content="移除配置" Command="{Binding RemoveDeviceCommand}"/></WrapPanel>
<Grid ColumnDefinitions="*,*"><StackPanel><TextBlock Text="设备 ID"/><TextBox Text="{Binding DeviceId}" Watermark="home-phone"/></StackPanel><StackPanel Grid.Column="1" Margin="12,0,0,0"><TextBlock Text="手机 adbd 地址"/><TextBox Text="{Binding Target}" Watermark="192.168.1.10:5555"/></StackPanel></Grid>
<Expander Header="通过已有 ADB server 接入"><StackPanel><TextBlock Text="ADB 序列号(与手机地址二选一)"/><TextBox Text="{Binding AdbSerial}"/><TextBlock Text="ADB server 地址(留空使用 Agent 默认值)"/><TextBox Text="{Binding AdbServer}" Watermark="127.0.0.1:5037"/><TextBlock Text="此模式仍要求手机启用 TCP adbd。" Foreground="#A8B7CC"/></StackPanel></Expander>
<Button x:Name="AddManagedDeviceButton" Content="添加手机" Command="{Binding AddDeviceCommand}" HorizontalAlignment="Left"/>
</StackPanel></Border>
<Border Classes="agentCard"><StackPanel Spacing="8"><TextBlock Text="Agent 配置" FontSize="18" FontWeight="SemiBold"/><TextBlock Text="修改设备或地址会重建受影响的连接;Agent ID 保持固定。" Foreground="#A8B7CC" TextWrapping="Wrap"/><TextBox x:Name="AgentConfigBox" Text="{Binding ConfigJson}" AcceptsReturn="True" FontFamily="Cascadia Mono,Consolas" FontSize="12" MinHeight="200" MaxHeight="380" ScrollViewer.VerticalScrollBarVisibility="Auto"/><Button Content="保存并应用配置" Command="{Binding SaveConfigCommand}" HorizontalAlignment="Left"/>
<StackPanel IsVisible="{Binding LocalMode}"><TextBlock Text="首次设置:填写上方配置及设备端凭据后初始化,再启动后台 Agent。" TextWrapping="Wrap"/><TextBox Text="{Binding EnrollmentToken}" PasswordChar="●" Watermark="ADS_AGENT_TOKEN"/><WrapPanel><Button Content="导入 agent.env" Click="ImportEnrollmentClick"/><Button Content="初始化本机配置" Command="{Binding InitializeLocalCommand}"/></WrapPanel></StackPanel>
</StackPanel></Border>
<Border Classes="agentCard"><StackPanel Spacing="8"><WrapPanel><Button Content="读取日志" Command="{Binding ReadLogsCommand}"/><CheckBox Content="持续跟随日志" IsChecked="{Binding FollowLogs}"/></WrapPanel><TextBox x:Name="AgentLogsBox" Text="{Binding RemoteLogText}" IsReadOnly="True" AcceptsReturn="True" FontFamily="Cascadia Mono,Consolas" FontSize="12" Height="200" ScrollViewer.VerticalScrollBarVisibility="Auto"/></StackPanel></Border>
</StackPanel></ScrollViewer>
</Grid>
<TextBlock Grid.Row="2" x:Name="AgentNotice" Text="{Binding Notice}" TextWrapping="Wrap" Foreground="#A8B7CC" Margin="0,12,0,0"/>
</Grid>
</UserControl>
@@ -0,0 +1,19 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
namespace Ads.Desktop;
public partial class AgentManagementView : UserControl
{
public AgentManagementView()=>InitializeComponent();
private async Task Import(bool enrollment)
{
if(DataContext is not AgentManagementViewModel vm)return;
try {
var top=TopLevel.GetTopLevel(this);if(top==null)return;
var files=await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions{Title=enrollment?"选择 agent.env":"选择 admin.env",AllowMultiple=false,FileTypeFilter=[new FilePickerFileType("环境配置"){Patterns=["*.env"]}]});
if(files.FirstOrDefault()?.TryGetLocalPath() is {} path){if(enrollment)vm.ImportEnrollment(path);else vm.ImportAdmin(path);}
}catch(Exception error){vm.Notice=error.Message;}
}
private async void ImportAdminClick(object? sender,RoutedEventArgs e)=>await Import(false);
private async void ImportEnrollmentClick(object? sender,RoutedEventArgs e)=>await Import(true);
}
@@ -0,0 +1,203 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text.Json;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace Ads.Desktop;
public partial class AgentManagementViewModel : ObservableObject, IDisposable
{
[ObservableProperty] private bool localMode;
[ObservableProperty] private string adminToken = "";
[ObservableProperty] private string enrollmentToken = "";
[ObservableProperty] private string configPath = DefaultConfig();
[ObservableProperty] private ManagedAgent? selectedAgent;
[ObservableProperty] private ManagedDevice? selectedManagedDevice;
[ObservableProperty] private string deviceId = "";
[ObservableProperty] private string target = "";
[ObservableProperty] private string adbSerial = "";
[ObservableProperty] private string adbServer = "";
[ObservableProperty] private string configJson = "";
[ObservableProperty] private string remoteLogText = "";
[ObservableProperty] private string notice = "管理员凭据用于远程管理;也可切换为管理本机 Agent。";
[ObservableProperty] private bool isBusy;
[ObservableProperty] private bool autoRefresh = true;
[ObservableProperty] private bool followLogs;
public ObservableCollection<ManagedAgent> Agents { get; } = new();
public ObservableCollection<ManagedDevice> AgentDevices { get; } = new();
private readonly Func<(string Server,string Origin)> server;
private readonly Action<string> log;
private readonly CancellationTokenSource lifetime = new();
private readonly DispatcherTimer timer;
private readonly HashSet<string> secrets = new(StringComparer.Ordinal);
private bool polling, disposed;
private long logCursor;
private string logInstance = "";
private string listedSource = "";
private string SourceKey()=>LocalMode ? "local:"+ConfigPath : "remote:"+JsonSerializer.Serialize(new[]{server().Server,server().Origin});
private string? lastError;
public AgentManagementViewModel(Func<(string,string)> server, Action<string>? logger=null, bool background=true, bool credentials=true)
{
this.server=server; log=logger ?? (_=>{});
var (initialServer,initialOrigin)=server();
ConfigJson=JsonSerializer.Serialize(new {version=1,id="local-pc",name=Environment.MachineName,server=initialServer,connect_address=string.IsNullOrWhiteSpace(initialOrigin)?null:initialOrigin,adb_server="127.0.0.1:5037",devices=Array.Empty<object>()}, new JsonSerializerOptions{WriteIndented=true});
if(credentials) {
var path=DesktopPaths.ProjectRoot() is {} root ? Path.Combine(root,"config","private","admin.env") : Path.Combine(AppContext.BaseDirectory,"admin.env");
if(File.Exists(path)) { try { ImportAdmin(path); } catch { } }
}
timer=new DispatcherTimer{Interval=TimeSpan.FromSeconds(5)};
timer.Tick+=async(_,_)=>await PollAsync(); if(background)timer.Start();
}
public static string DefaultConfig() => OperatingSystem.IsWindows()
? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"AndroidDeviceStreaming","agent","agent.json")
: Path.Combine(Environment.GetEnvironmentVariable("XDG_CONFIG_HOME") ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),".config"),"ads","agent.json");
public void StartMonitoring()=>timer.Start();
private string Redact(string value) { foreach(var secret in secrets) value=value.Replace(secret,"[REDACTED]",StringComparison.Ordinal);return value; }
partial void OnAdminTokenChanged(string value){if(value.Length>0)secrets.Add(value);}
partial void OnEnrollmentTokenChanged(string value){if(value.Length>0)secrets.Add(value);}
partial void OnSelectedAgentChanged(ManagedAgent? value)
{
var selected=SelectedManagedDevice?.Id; AgentDevices.Clear();
foreach(var device in value?.Status.Devices ?? [])AgentDevices.Add(device);
SelectedManagedDevice=AgentDevices.FirstOrDefault(d=>d.Id==selected) ?? AgentDevices.FirstOrDefault();
logCursor=0;logInstance="";RemoteLogText="";UpdateCommands();
}
partial void OnSelectedManagedDeviceChanged(ManagedDevice? value)=>UpdateCommands();
partial void OnIsBusyChanged(bool value)=>UpdateCommands();
partial void OnLocalModeChanged(bool value){Agents.Clear();SelectedAgent=null;Notice=value?"管理本机 Agent,不需要管理员令牌。":"管理控制中心中的 Agent,需要独立管理员凭据。";}
private bool CanManage()=>!IsBusy && SelectedAgent?.Online==true;
private bool CanDevice()=>CanManage() && SelectedManagedDevice!=null;
private bool CanRestart()=>CanManage() && SelectedAgent?.Status.Supervised==true;
private bool CanLocal()=>!IsBusy && LocalMode;
private void UpdateCommands()
{
LoadConfigCommand.NotifyCanExecuteChanged();SaveConfigCommand.NotifyCanExecuteChanged();AddDeviceCommand.NotifyCanExecuteChanged();
RemoveDeviceCommand.NotifyCanExecuteChanged();EnableDeviceCommand.NotifyCanExecuteChanged();DisableDeviceCommand.NotifyCanExecuteChanged();
ReadLogsCommand.NotifyCanExecuteChanged();RestartAgentCommand.NotifyCanExecuteChanged();
InitializeLocalCommand.NotifyCanExecuteChanged();StartLocalCommand.NotifyCanExecuteChanged();InstallServiceCommand.NotifyCanExecuteChanged();
}
public void ImportAdmin(string path)
{
if(new FileInfo(path).Length>65536)throw new InvalidOperationException("凭据文件过大。");
var token=File.ReadLines(path).Select(l=>l.Split('=',2)).FirstOrDefault(p=>p.Length==2&&p[0].Trim()=="ADS_ADMIN_TOKEN")?.ElementAt(1).Trim();
if(string.IsNullOrEmpty(token)||token.Length<32||token.Contains('\r')||token.Contains('\n'))throw new InvalidOperationException("文件中没有有效的 ADS_ADMIN_TOKEN。");
AdminToken=token;Notice="管理员凭据已加载,内容仅保存在内存中。";
}
public void ImportEnrollment(string path)
{
if(new FileInfo(path).Length>65536)throw new InvalidOperationException("凭据文件过大。");
var value=File.ReadLines(path).FirstOrDefault(l=>l.StartsWith("ADS_AGENT_TOKEN=",StringComparison.Ordinal))?[16..].Trim();
if(string.IsNullOrEmpty(value)||value.Length<32)throw new InvalidOperationException("文件中没有有效的 ADS_AGENT_TOKEN。");
EnrollmentToken=value;Notice="设备端凭据已加载,仅供本机初始化使用。";
}
private RelayOptions Options(){var(s,o)=server();return RelayOptions.Parse(s,o,AdminToken);}
private async Task Guard(Func<Task> action)
{
if(IsBusy)return;IsBusy=true;
try { await action(); }
catch(OperationCanceledException)when(lifetime.IsCancellationRequested){}
catch(Exception error){Notice=Redact(error.Message);log("[Agent管理] "+Notice);}
finally{IsBusy=false;}
}
private async Task<JsonElement> LocalRequestAsync(object request)
{
var executable=DesktopPaths.ResolveTool(DesktopPaths.FindTool("adsctl"),"adsctl");
var info=ProcessTools.CreateStartInfo(executable,["--json","--config",ConfigPath,"request"]);info.RedirectStandardInput=true;
using var process=Process.Start(info) ?? throw new InvalidOperationException("adsctl 无法启动。");
var output=process.StandardOutput.ReadToEndAsync();var error=process.StandardError.ReadToEndAsync();
await process.StandardInput.WriteAsync(JsonSerializer.Serialize(request));process.StandardInput.Close();
try { await process.WaitForExitAsync(lifetime.Token).WaitAsync(TimeSpan.FromSeconds(20),lifetime.Token); }
catch { if(!process.HasExited)process.Kill(entireProcessTree:true);throw; }
if(process.ExitCode!=0)throw new InvalidOperationException((await error).Trim());
using var value=JsonDocument.Parse(await output);return value.RootElement.Clone();
}
private Task<JsonElement> CallAsync(object request,string? agent=null) {
if(listedSource!=SourceKey())throw new InvalidOperationException("管理地址或配置路径已改变,请先刷新 Agent 列表。");
return LocalMode ? LocalRequestAsync(request) : AgentManagementApi.CallAsync(Options(),agent ?? SelectedAgent?.Id ?? throw new InvalidOperationException("请选择 Agent。"),request,lifetime.Token);
}
private async Task RefreshCoreAsync()
{
var selected=SelectedAgent?.Id;var selectedDevice=SelectedManagedDevice?.Id;
var local=LocalMode;var path=ConfigPath;var source=server();
ManagedAgent[] rows;
if(LocalMode) {
var value=await LocalRequestAsync(new{op="status"});
var status=value.Deserialize<ManagedStatus>(new JsonSerializerOptions(JsonSerializerDefaults.Web)) ?? throw new InvalidOperationException("Agent 状态无效。");
rows=[new ManagedAgent(status.Id,true,DateTimeOffset.UtcNow.ToUnixTimeSeconds(),status)];
}else rows=await AgentManagementApi.ListAsync(Options(),lifetime.Token);
if(local!=LocalMode||path!=ConfigPath||source!=server())return;
listedSource=SourceKey();
Agents.Clear();foreach(var row in rows)Agents.Add(row);
var chosen=Agents.FirstOrDefault(r=>r.Id==selected) ?? Agents.FirstOrDefault(r=>r.Online) ?? Agents.FirstOrDefault();
// Preserve log cursor and draft configuration during periodic metadata refreshes.
var cursor=logCursor;var instance=logInstance;var text=RemoteLogText;
SelectedAgent=chosen;
if(selected==chosen?.Id){logCursor=cursor;logInstance=instance;RemoteLogText=text;}
SelectedManagedDevice=AgentDevices.FirstOrDefault(d=>d.Id==selectedDevice) ?? AgentDevices.FirstOrDefault();
Notice=$"{rows.Length} 个 Agent · {rows.Count(r=>r.Online)} 个在线";lastError=null;
}
[RelayCommand]private Task RefreshAgentsAsync()=>Guard(RefreshCoreAsync);
[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="已读取配置,凭据不在配置中。";
});
[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="配置已持久化并应用。受影响设备将重建连接。";
});
[RelayCommand(CanExecute=nameof(CanManage))]private Task AddDeviceAsync()=>Guard(async()=>{
if(string.IsNullOrWhiteSpace(Target)==string.IsNullOrWhiteSpace(AdbSerial))throw new InvalidOperationException("手机地址与 ADB 序列号必须填写其中一项。");
await CallAsync(new{op="device_add",device=new{id=DeviceId.Trim(),target=string.IsNullOrWhiteSpace(Target)?null:Target.Trim(),adb_serial=string.IsNullOrWhiteSpace(AdbSerial)?null:AdbSerial.Trim(),adb_server=string.IsNullOrWhiteSpace(AdbServer)?null:AdbServer.Trim(),device_port=5555,enabled=true}});
await RefreshCoreAsync();Notice="手机已添加并启动连接。";
});
private Task DeviceOperation(string operation,bool? enabled=null)=>Guard(async()=>{
var id=SelectedManagedDevice?.Id ?? throw new InvalidOperationException("请选择手机。");
await CallAsync(enabled.HasValue?new{op=operation,id,enabled=enabled.Value}:(object)new{op=operation,id});await RefreshCoreAsync();
});
[RelayCommand(CanExecute=nameof(CanDevice))]private Task RemoveDeviceAsync()=>DeviceOperation("device_remove");
[RelayCommand(CanExecute=nameof(CanDevice))]private Task EnableDeviceAsync()=>DeviceOperation("device_enable",true);
[RelayCommand(CanExecute=nameof(CanDevice))]private Task DisableDeviceAsync()=>DeviceOperation("device_enable",false);
private async Task LogsCoreAsync()
{
var page=await CallAsync(new{op="logs",after=logCursor,limit=50});var instance=page.GetProperty("instance").GetString() ?? "";
if(logInstance.Length>0&&instance!=logInstance){logCursor=0;RemoteLogText="";logInstance=instance;return;}
logInstance=instance;logCursor=page.GetProperty("next").GetInt64();
foreach(var entry in page.GetProperty("entries").EnumerateArray())RemoteLogText+=Redact($"{entry.GetProperty("time")} {entry.GetProperty("level")} {entry.GetProperty("message").GetString()}\n");
if(RemoteLogText.Length>100000)RemoteLogText=RemoteLogText[^100000..];
}
[RelayCommand(CanExecute=nameof(CanManage))]private Task ReadLogsAsync()=>Guard(LogsCoreAsync);
[RelayCommand(CanExecute=nameof(CanRestart))]private Task RestartAgentAsync()=>Guard(async()=>{await CallAsync(new{op="restart"});Notice="监督进程将重启 Agent,手机连接会短暂中断。";});
[RelayCommand(CanExecute=nameof(CanLocal))]private Task InitializeLocalAsync()=>Guard(async()=>{
if(File.Exists(ConfigPath))throw new InvalidOperationException("本机配置已存在,请读取后修改。");
using var doc=JsonDocument.Parse(ConfigJson);var root=doc.RootElement;
var args=new List<string>{"--json","--config",ConfigPath,"--server",root.GetProperty("server").GetString()!,"init","--id",root.GetProperty("id").GetString()!,"--name",root.GetProperty("name").GetString()!};
// Origin is a global CLI option and must precede the subcommand.
if(root.TryGetProperty("connect_address",out var origin)&&origin.ValueKind==JsonValueKind.String)args.InsertRange(5,["--connect-address",origin.GetString()!]);
var info=ProcessTools.CreateStartInfo(DesktopPaths.ResolveTool(DesktopPaths.FindTool("adsctl"),"adsctl"),args);info.Environment["ADS_AGENT_TOKEN"]=EnrollmentToken;
var result=await ProcessTools.RunAsync(info,lifetime.Token);if(result.ExitCode!=0)throw new InvalidOperationException(result.Error);
EnrollmentToken="";Notice="本机配置已初始化,可启动后台 Agent 后应用设备配置。";
});
[RelayCommand(CanExecute=nameof(CanLocal))]private Task StartLocalAsync()=>Guard(async()=>{
try { await LocalRequestAsync(new{op="status"});Notice="本机 Agent 已在运行。";return; } catch(InvalidOperationException){}
var info=ProcessTools.CreateStartInfo(DesktopPaths.ResolveTool(DesktopPaths.FindTool("ads-agent"),"ads-agent"),["--quiet","--supervise","--config",ConfigPath]);
info.RedirectStandardOutput=false;info.RedirectStandardError=false;
using var process=Process.Start(info) ?? throw new InvalidOperationException("Agent 启动失败。");
await Task.Delay(700,lifetime.Token);await RefreshCoreAsync();Notice="后台 Agent 已启动,退出托盘不会停止它。";
});
[RelayCommand(CanExecute=nameof(CanLocal))]private Task InstallServiceAsync()=>Guard(async()=>{
if(!OperatingSystem.IsWindows())throw new InvalidOperationException("请在终端运行 adsctl service install;系统级服务可加 --system。");
var info=new ProcessStartInfo(DesktopPaths.ResolveTool(DesktopPaths.FindTool("adsctl"),"adsctl")){UseShellExecute=true,Verb="runas",WindowStyle=ProcessWindowStyle.Hidden};
foreach(var value in new[]{"--config",ConfigPath,"service","install"})info.ArgumentList.Add(value);
using var process=Process.Start(info) ?? throw new InvalidOperationException("安装命令无法启动。");await process.WaitForExitAsync(lifetime.Token);
if(process.ExitCode!=0)throw new InvalidOperationException("服务安装失败,请在管理员终端使用 adsctl 检查错误。");
await RefreshCoreAsync();Notice="已配置无界面开机启动。";
});
private async Task PollAsync()
{
if(polling||disposed||IsBusy||!AutoRefresh||(!LocalMode&&AdminToken.Length<32))return;polling=true;IsBusy=true;
try { await RefreshCoreAsync();if(FollowLogs&&SelectedAgent?.Online==true)await LogsCoreAsync(); }
catch(OperationCanceledException)when(lifetime.IsCancellationRequested){}
catch(Exception error){var message=Redact(error.Message);Notice=message;if(message!=lastError){log("[Agent管理] "+message);lastError=message;}}
finally{polling=false;IsBusy=false;}
}
public void Dispose(){if(disposed)return;disposed=true;timer.Stop();lifetime.Cancel();lifetime.Dispose();}
}
+16 -7
View File
@@ -13,8 +13,13 @@ public partial class App : Application
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var vm = new MainViewModel();
var window = new MainWindow { DataContext = vm };
var localAgentMode = desktop.Args?.Contains("--agent-tray") == true;
var vm = new MainViewModel(backgroundMonitoring: !localAgentMode, loadLocalCredentials: !localAgentMode);
Window window;
if(localAgentMode) {
vm.AgentManager.LocalMode=true;vm.AgentManager.StartMonitoring();
window=new Window {Title="ADS · 被控端 Agent 管理",Width=1100,Height=850,MinWidth=900,MinHeight=650,Background=Avalonia.Media.Brush.Parse("#10151F"),Content=new AgentManagementView{DataContext=vm.AgentManager,Margin=new Avalonia.Thickness(22)}};
} else window = new MainWindow { DataContext = vm };
desktop.MainWindow = window;
desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown;
void Show() { window.Show(); window.WindowState = WindowState.Normal; window.Activate(); }
@@ -26,19 +31,23 @@ public partial class App : Application
finally { desktop.Shutdown(); }
}
var menu = new NativeMenu();
var show = new NativeMenuItem("打开设备工作台"); show.Click += (_, _) => Show(); menu.Items.Add(show);
menu.Items.Add(new NativeMenuItem("断开全部设备") { Command = vm.DisconnectAllCommand });
var show = new NativeMenuItem(localAgentMode ? "打开本机 Agent 管理" : "打开设备工作台"); show.Click += (_, _) => Show(); menu.Items.Add(show);
if(localAgentMode)menu.Items.Add(new NativeMenuItem("重启本机 Agent") {Command=vm.AgentManager.RestartAgentCommand});
else menu.Items.Add(new NativeMenuItem("断开全部设备") { Command = vm.DisconnectAllCommand });
menu.Items.Add(new NativeMenuItemSeparator());
var quit = new NativeMenuItem("退出并断开连接");
var quit = new NativeMenuItem(localAgentMode ? "退出托盘(Agent 继续运行)" : "退出并断开连接");
quit.Click += async (_, _) => await QuitAsync();
menu.Items.Add(quit);
using var stream = Avalonia.Platform.AssetLoader.Open(new Uri("avares://Ads.Desktop/Assets/app.png"));
var tray = new TrayIcon { ToolTipText = "ADS · Android 设备工作台", Icon = new WindowIcon(stream), Menu = menu, Command = new RelayCommand(Show) };
var tray = new TrayIcon { ToolTipText = localAgentMode ? "ADS · 本机 Agent 管理" : "ADS · Android 设备工作台", Icon = new WindowIcon(stream), Menu = menu, Command = new RelayCommand(Show) };
TrayIcon.SetIcons(this, new TrayIcons { tray });
vm.PropertyChanged += (_, change) => {
if (change.PropertyName is nameof(vm.ConnectionSummary))
if (!localAgentMode && change.PropertyName is nameof(vm.ConnectionSummary))
tray.ToolTipText = "ADS · " + vm.ConnectionSummary;
};
if(localAgentMode)vm.AgentManager.PropertyChanged += (_, change) => {
if(change.PropertyName is nameof(AgentManagementViewModel.Notice)) tray.ToolTipText="ADS Agent · "+vm.AgentManager.Notice;
};
window.Closing += async (_, e) => {
if (quitting) return;
e.Cancel = true;
+4 -2
View File
@@ -52,6 +52,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
[ObservableProperty] private bool isWorking;
[ObservableProperty] private bool isRefreshing;
public AgentManagementViewModel AgentManager { get; }
public ObservableCollection<RelayNode> RelayNodes { get; } = new();
public ObservableCollection<DeviceItem> Devices { get; } = new();
public ObservableCollection<string> Logs { get; } = new();
@@ -106,6 +107,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
if (File.Exists(credentialFile)) LoadCredentials(credentialFile, useOrigin: false);
}
Notice = Token.Length >= 32 ? "配置已就绪,正在等待刷新设备。" : "请在连接配置中导入 client.env。";
AgentManager = new AgentManagementViewModel(() => (Server, Origin), Log, backgroundMonitoring, loadLocalCredentials);
timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(3) };
timer.Tick += async (_, _) => await MonitorAsync();
if (backgroundMonitoring) timer.Start();
@@ -484,7 +486,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
public async Task ShutdownAsync()
{
timer.Stop(); lifetime.Cancel();
AgentManager.Dispose(); timer.Stop(); lifetime.Cancel();
await connectionGate.WaitAsync();
try { await DisconnectAllCoreAsync(); }
finally { connectionGate.Release(); }
@@ -493,7 +495,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
public void Dispose()
{
if (disposed) return;
disposed = true; timer.Stop(); lifetime.Cancel();
disposed = true; AgentManager.Dispose(); timer.Stop(); lifetime.Cancel();
foreach (var session in sessions.Values) { session.PropertyChanged -= ConnectionChanged; session.Dispose(); }
sessions.Clear(); Connections.Clear();
lifetime.Dispose();
+2 -1
View File
@@ -1,4 +1,4 @@
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:Ads.Desktop"
x:Class="Ads.Desktop.MainWindow" Title="ADS · 公网设备工作台"
Width="1240" Height="880" MinWidth="980" MinHeight="700" Background="#10151F">
<Window.Styles>
@@ -99,6 +99,7 @@
</ScrollViewer>
</Grid>
</TabItem>
<TabItem x:Name="AgentManagementTab" Header="Agent 管理"><local:AgentManagementView DataContext="{Binding AgentManager}"/></TabItem>
<TabItem Header="连接配置">
<ScrollViewer>
<StackPanel Margin="4,18" MaxWidth="880" Spacing="16">
+1 -1
View File
@@ -14,7 +14,7 @@ public static class ProcessTools
RedirectStandardOutput = true, RedirectStandardError = true
};
foreach (var argument in arguments) info.ArgumentList.Add(argument);
foreach (var key in new[] { "ADB_SERVER_SOCKET", "ANDROID_ADB_SERVER_ADDRESS", "ANDROID_ADB_SERVER_PORT", "ADS_CLIENT_TOKEN", "ADS_AGENT_TOKEN", "ADS_CONNECT_ADDRESS" })
foreach (var key in new[] { "ADB_SERVER_SOCKET", "ANDROID_ADB_SERVER_ADDRESS", "ANDROID_ADB_SERVER_PORT", "ADS_CLIENT_TOKEN", "ADS_AGENT_TOKEN", "ADS_ADMIN_TOKEN", "ADS_CONNECT_ADDRESS" })
info.Environment.Remove(key);
info.Environment["NO_COLOR"] = "1";
return info;
+4
View File
@@ -72,3 +72,7 @@ ADB、USB/IP 和 scrcpy 转发端口分别自动分配,避开其他连接和
实现分工:MainViewModel 管理设备发现、连接集合、当前选择与批量操作;DeviceConnection 为每台设备持有进程、独立操作锁、USB 导出、状态文件和生命周期;ConnectionPorts 负责不终止外部监听者的端口分配。监控每个 ADB 可执行文件每轮仅查询一次 devices,再分别更新所有设备。
验证:`dotnet run --project Ads.Desktop.Smoke -c Debug -- --multi`,USB 模式加 `--usb`。需要 home-phone 与 smoke-multi-phone(可用 ADS_MULTI_SECOND_DEVICE 指定第二个已授权设备 ID),测试不会接管已占用设备。2026-11-12 使用两个独立设备别名映射到同一台测试手机,验证双 ADB/双 USB、不同端口/序列号、两个真实 scrcpy 视频、总览按钮绑定、重连/断开一个保留另一个以及释放全部租约。此验证覆盖并发通道,未作为多台物理手机的大规模负载测试。
## Agent 管理
工作台新增 Agent 管理页,与 Flutter 共用控制中心 v3 接口。支持多 Agent/多手机、本机私有 IPC、配置与日志、受监督重启;`--agent-tray` 可单独打开本机 Agent 管理窗口。发行包同时包含 adsctl 和 ads-agent,后台运行不依赖 GUI。完整安装及 CLI 示例见 [Agent 管理](../docs/agent-management.md)。
+118
View File
@@ -0,0 +1,118 @@
# Agent 管理与无界面部署
一个 `ads-agent --config` 进程管理一台电脑上的多部手机。`ads-server` 汇总所有 Agent,两套桌面客户端均提供“Agent 管理”:查看主机、选择手机、添加/移除/启用/停用、读取/应用配置、跟随日志、重启受监督 Agent。设备连接工作台继续使用同一组设备 ID。
手机状态“已注册”表示设备转发工作线程已向控制中心注册,并不证明手机当前 ADB 在线;实际连接失败会显示转发错误。
## 角色与连接
- Agent 使用 `ADS_AGENT_TOKEN`;普通连接客户端使用 `ADS_CLIENT_TOKEN`。
- 远程管理使用独立的 `ADS_ADMIN_TOKEN`,至少 32 字符,且不得与上述令牌相同。控制中心未配置该变量时,管理接口关闭。
- 私有凭据文件 `agent.env`/`admin.env` 不提交 Git、不打入发行包。GUI 仅在内存中保留导入的令牌。
- Agent 主动连接控制中心,无需开放电脑入站管理端口。远程管理经过已校验证书的 HTTPS/WSS;数据链路仍按原有 P2P 优先及中继回退运行。
- 本机管理使用配置路径对应的私有 Windows 命名管道或 Unix socket,无需管理员令牌。Windows 仅允许配置目录所有者和 SYSTEM;Unix socket 权限 0600。配置目录不能允许其他用户写入。
已部署控制中心地址为 `wss://ttstd.com/ads`,源站覆盖为 `175.178.213.60:443`;覆盖 TCP 地址仍按 ttstd.com 验证 TLS。自行部署时替换这些值。
## 首次初始化
将 `ads-agent` 和 `adsctl` 放在同一目录。通过受限权限的文件或环境变量提供设备端令牌,避免出现在命令行参数中。
```powershell
.\adsctl.exe --config C:\ADS\agent.json --credentials C:\private\agent.env --server wss://ttstd.com/ads --connect-address 175.178.213.60:443 init --id office-pc --name 办公室
.\ads-agent.exe --quiet --supervise --config C:\ADS\agent.json
```
初始化会生成非敏感的 `agent.json` 及同目录的私有 `agent.env`,已有配置不会覆盖。`init` 默认没有手机,启动后通过另一个终端添加:
```powershell
.\adsctl.exe --config C:\ADS\agent.json status
.\adsctl.exe --config C:\ADS\agent.json devices add --id phone-one --target 192.168.100.141:5555
.\adsctl.exe --config C:\ADS\agent.json devices add --id phone-two --adb-serial USB_SERIAL
.\adsctl.exe --config C:\ADS\agent.json devices list
.\adsctl.exe --config C:\ADS\agent.json devices disable phone-one
.\adsctl.exe --config C:\ADS\agent.json devices enable phone-one
.\adsctl.exe --config C:\ADS\agent.json devices remove phone-two
.\adsctl.exe --config C:\ADS\agent.json logs --follow
.\adsctl.exe --config C:\ADS\agent.json restart
```
`--target` 直接接手机 adbd TCP;`--adb-serial` 通过 Agent 主机已有 ADB server 接 USB 或网络设备,可加 `--adb-server host:5037`。设备 ID 在控制中心全局唯一;同一物理手机请使用一个 ID。
省略配置路径时,Windows 默认 `%LOCALAPPDATA%/AndroidDeviceStreaming/agent/agent.json`,Unix 默认 `$XDG_CONFIG_HOME/ads/agent.json` 或 `~/.config/ads/agent.json`。
## 配置
```json
{
"version": 1,
"id": "office-pc",
"name": "办公室",
"server": "wss://ttstd.com/ads",
"connect_address": "175.178.213.60:443",
"adb_server": "127.0.0.1:5037",
"devices": [
{"id": "phone-one", "target": "192.168.100.141:5555", "enabled": true}
]
}
```
```powershell
.\adsctl.exe --config C:\ADS\agent.json config get
.\adsctl.exe config validate --file edited.json
.\adsctl.exe --config C:\ADS\agent.json config set --file edited.json
```
Agent ID 不能运行中修改。合法配置先原子持久化,再应用;只重建发生变化的手机工作线程,其余活动连接保留。修改全局服务器或 ADB 地址会重建相关连接。手机最多 128 部。令牌放在独立私有文件中,替换令牌后重启 Agent。
## 远程 CLI
`admin.env` 包含 `ADS_ADMIN_TOKEN=...`,可另加 `ADS_CONNECT_ADDRESS=175.178.213.60:443`。
```powershell
.\adsctl.exe --credentials C:\private\admin.env agents list
.\adsctl.exe --credentials C:\private\admin.env --agent office-pc status
.\adsctl.exe --credentials C:\private\admin.env --agent office-pc devices list
.\adsctl.exe --credentials C:\private\admin.env --agent office-pc logs --follow
.\adsctl.exe --credentials C:\private\admin.env --agent office-pc restart
```
同样的 devices/config 子命令可加 `--agent` 远程执行。`--json` 输出机器可读结果,失败返回非零退出码;`request` 从 stdin 读取一条结构化 JSON 请求,供 GUI 调用。没有远程任意 shell 执行接口。
## 无 GUI 自动启动
Windows 在管理员终端执行:
```powershell
.\adsctl.exe --config C:\ADS\agent.json service install
.\adsctl.exe --config C:\ADS\agent.json service status
.\adsctl.exe --config C:\ADS\agent.json service restart
.\adsctl.exe --config C:\ADS\agent.json service uninstall
```
创建名为 `ADS-Agent-office-pc` 的 SYSTEM 开机计划任务。如果已手动启动 Agent,安装只配置自动启动,保留当前进程;下次开机由任务接管,避免重复守护进程。配置文件和目录须允许 SYSTEM 访问;ADB server 进程也须在开机后启动(使用 `--adb-serial` 时)。不依赖用户登录或托盘程序。
Linux 使用相同二进制和命令(去掉 `.exe`):
```sh
./adsctl --config "$HOME/.config/ads/agent.json" service install
./adsctl --config "$HOME/.config/ads/agent.json" service status
# 用户服务无登录运行时,按系统策略启用 loginctl enable-linger USER
# 或在管理员终端安装系统级 unit;配置目录应属于实际 Agent 用户
sudo ./adsctl --config /home/agent/.config/ads/agent.json service install --system
```
已运行 Agent 时,安装保留当前进程,只启用下次自动启动。用户模式使用 systemd --user,系统模式写入 /etc/systemd/system 并按配置目录所有者身份运行。支持 start/stop/restart/status/uninstall;已有同名但不属于本配置的任务/unit 会被拒绝覆盖。macOS 可手动监督运行,当前没有原生 launchd 安装命令。
`--supervise` 保持子进程存活并处理管理重启。Windows Job Object/Linux 父进程死亡信号确保监督进程被结束时回收子进程。日志为进程内最近 500 条、每条最多 1024 字符;Agent 重启后日志清空,CLI 和 UI 会重置游标。需要长期日志时另用系统日志设施。
## 两套 UI 与托盘
- Avalonia 和 Flutter:进入“Agent 管理”,导入 admin.env,刷新并选择目标 Agent。管理本机时切换“管理本机 Agent”,指定配置路径,无需 admin.env。
- 本机初始化导入 agent.env 后初始化,再启动后台 Agent 或安装开机服务。配置编辑器中的手机列表在后台启动后点击“保存并应用配置”保存;首次 init 只建立主机配置。
- Avalonia `Ads.Desktop.exe --agent-tray` 提供只面向本机 Agent 的管理窗口和托盘。`scripts/start-agent-tray.ps1` 为快捷入口。
- 关闭管理 UI 不会停止已托管的 Agent。手机投屏和 ADB 连接仍在设备工作台操作。
## 协议与限制
v3 增加 `/agents/register`(Agent WSS)、`/agents`(管理员 HTTP/WSS 列表)、`/rpc?agent=ID`(管理员 HTTP POST/WSS 请求)。均在 `/v3` 下,支持部署路径前缀。关联请求有超时与数量限制;服务端保留有限的离线主机快照,重启控制中心后重新注册。此版本不提供远程二进制升级、用户账号管理、任意命令执行或跨平台 USB 后端。
+7 -1
View File
@@ -28,7 +28,7 @@ flutter build windows --release
开发环境自动向上查找仓库,使用 bin/ads-client.exe、bin/tools/scrcpy/ 中的工具与 config/private/client.env。发行时请在应用旁放置 ads-client.exe、tools/scrcpy/ 完整发行目录,或在配置页填写绝对路径,并导入自己的凭据文件。配置在 %LOCALAPPDATA%/TTSTD/ADS-Flutter/settings.json,与原客户端分开。
服务地址支持 /ads 路径前缀和可选直连源站地址,HTTPS 仍按原域名校验证书。令牌仅使用 client 角色。现有 API 不包含用户增删、角色编辑或远端服务重启,因此本版提供设备/节点状态管理与本地连接操作,不提供这些服务端写操作。USB 模拟未在本工程接入。
服务地址支持 /ads 路径前缀和可选直连源站地址,HTTPS 仍按原域名校验证书。令牌仅使用 client 角色。Agent 管理使用独立 admin.env 管理角色,支持多 Agent/多手机、配置、日志及受监督重启;本机使用 adsctl 私有 IPC。用户账号和角色编辑不在此版本范围。USB 模拟未在本工程接入。
## 目录
@@ -62,3 +62,9 @@ dart run test/live_smoke.dart --connect --screen
```
2026-11-12:已验证真实设备/节点 API、本机 ADB 列表;真实远端设备当时被占用,因此跳过远端连接与投屏验收。原生 UI 自动化工具初始化失败,托盘点击行为仍需人工验收。
## Agent 管理
导航“Agent 管理”可选择多台被控电脑,添加/移除/启停手机,修改配置、跟随日志和重启。也可管理本机 Agent,初始化并安装无界面开机任务。发行包旁放置 adsctl.exe 和 ads-agent.exe;两者与 Avalonia 共用同一配置和后台,不应重复启动。详见 [Agent 管理](../docs/agent-management.md)。
`lib/data/agent_models.dart` 使用 Freezed 生成不可变快照(生成文件一并提交);`agent_service.dart` 封装 HTTP/本机 CLI,`agent_repository.dart` 解析数据,`lib/ui/agent_model.dart` 持有页面状态。模型变化后运行 `dart run build_runner build`。`test/agent_test.dart` 验证选择范围、日志脱敏、响应竞争和布局;`agent_live_smoke.dart` 仅面向显式提供的隔离测试 Agent。
@@ -0,0 +1,75 @@
import 'package:freezed_annotation/freezed_annotation.dart';
part 'agent_models.freezed.dart';
@freezed
abstract class ManagedPhone with _$ManagedPhone {
const ManagedPhone._();
const factory ManagedPhone({
required String id,
String? target,
String? adbSerial,
required bool enabled,
required bool connected,
String? lastError,
}) = _ManagedPhone;
factory ManagedPhone.fromMap(Map<String, Object?> map) => ManagedPhone(
id: map['id'] as String,
target: map['target'] as String?,
adbSerial: map['adb_serial'] as String?,
enabled: map['enabled'] == true,
connected: map['connected'] == true,
lastError: map['last_error'] as String?,
);
String get description =>
'$id · ${!enabled
? "已停用"
: connected
? lastError == null
? "已注册"
: "转发异常"
: "等待注册"} · ${target ?? adbSerial ?? ""}';
}
@freezed
abstract class ManagedAgent with _$ManagedAgent {
const ManagedAgent._();
const factory ManagedAgent({
required String id,
required String name,
required bool online,
required String hostname,
required String os,
required String arch,
required String version,
required int pid,
required int revision,
required bool supervised,
required List<ManagedPhone> devices,
}) = _ManagedAgent;
factory ManagedAgent.fromMap(Map<String, Object?> map) {
final status = Map<String, Object?>.from(
map['status']! as Map<String, Object?>,
);
return ManagedAgent(
id: map['id'] as String,
name: status['name'] as String? ?? '',
online: map['online'] == true,
hostname: status['hostname'] as String? ?? '',
os: status['os'] as String? ?? '',
arch: status['arch'] as String? ?? '',
version: status['version'] as String? ?? '',
pid: status['pid'] as int? ?? 0,
revision: status['revision'] as int? ?? 0,
supervised: status['supervised'] == true,
devices: (status['devices'] as List<Object?>? ?? [])
.map(
(v) => ManagedPhone.fromMap(
Map<String, Object?>.from(v! as Map<String, Object?>),
),
)
.toList(),
);
}
String get description =>
'${name.isEmpty ? id : name} · ${online ? "在线" : "离线"} · $os · ${devices.length} 台手机';
}
@@ -0,0 +1,594 @@
// GENERATED CODE - DO NOT MODIFY BY HAND
// coverage:ignore-file
// ignore_for_file: type=lint, type=warning, deprecated_member_use, deprecated_member_use_from_same_package
// ignore_for_file: unused_element, deprecated_member_use, deprecated_member_use_from_same_package, use_function_type_syntax_for_parameters, unnecessary_const, avoid_init_to_null, invalid_override_different_default_values_named, prefer_expression_function_bodies, annotate_overrides, invalid_annotation_target, unnecessary_question_mark
part of 'agent_models.dart';
// **************************************************************************
// FreezedGenerator
// **************************************************************************
// GENERATED CODE - DO NOT MODIFY BY HAND
// dart format off
T _$identity<T>(T value) => value;
/// @nodoc
mixin _$ManagedPhone {
String get id; String? get target; String? get adbSerial; bool get enabled; bool get connected; String? get lastError;
/// Create a copy of ManagedPhone
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$ManagedPhoneCopyWith<ManagedPhone> get copyWith => _$ManagedPhoneCopyWithImpl<ManagedPhone>(this as ManagedPhone, _$identity);
@override
bool operator ==(Object other) {
final _this = this as ManagedPhone;
return identical(this, other) || (other.runtimeType == runtimeType&&other is ManagedPhone&&(identical(other.id, _this.id) || other.id == _this.id)&&(identical(other.target, _this.target) || other.target == _this.target)&&(identical(other.adbSerial, _this.adbSerial) || other.adbSerial == _this.adbSerial)&&(identical(other.enabled, _this.enabled) || other.enabled == _this.enabled)&&(identical(other.connected, _this.connected) || other.connected == _this.connected)&&(identical(other.lastError, _this.lastError) || other.lastError == _this.lastError));
}
@override
int get hashCode {
final _this = this as ManagedPhone;
return Object.hash(runtimeType,_this.id,_this.target,_this.adbSerial,_this.enabled,_this.connected,_this.lastError);
}
@override
String toString() {
final _this = this as ManagedPhone;
return 'ManagedPhone(id: ${_this.id}, target: ${_this.target}, adbSerial: ${_this.adbSerial}, enabled: ${_this.enabled}, connected: ${_this.connected}, lastError: ${_this.lastError})';
}
}
/// @nodoc
abstract mixin class $ManagedPhoneCopyWith<$Res> {
factory $ManagedPhoneCopyWith(ManagedPhone value, $Res Function(ManagedPhone) _then) = _$ManagedPhoneCopyWithImpl;
@useResult
$Res call({
String id, String? target, String? adbSerial, bool enabled, bool connected, String? lastError
});
}
/// @nodoc
class _$ManagedPhoneCopyWithImpl<$Res>
implements $ManagedPhoneCopyWith<$Res> {
_$ManagedPhoneCopyWithImpl(this._self, this._then);
final ManagedPhone _self;
final $Res Function(ManagedPhone) _then;
/// Create a copy of ManagedPhone
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? target = freezed,Object? adbSerial = freezed,Object? enabled = null,Object? connected = null,Object? lastError = freezed,}) {
return _then(ManagedPhone(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,target: freezed == target ? _self.target : target // ignore: cast_nullable_to_non_nullable
as String?,adbSerial: freezed == adbSerial ? _self.adbSerial : adbSerial // ignore: cast_nullable_to_non_nullable
as String?,enabled: null == enabled ? _self.enabled : enabled // ignore: cast_nullable_to_non_nullable
as bool,connected: null == connected ? _self.connected : connected // ignore: cast_nullable_to_non_nullable
as bool,lastError: freezed == lastError ? _self.lastError : lastError // ignore: cast_nullable_to_non_nullable
as String?,
));
}
}
/// Adds pattern-matching-related methods to [ManagedPhone].
extension ManagedPhonePatterns on ManagedPhone {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _ManagedPhone value)? $default,{required TResult orElse(),}){
final _that = this;
switch (_that) {
case _ManagedPhone() when $default != null:
return $default(_that);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _ManagedPhone value) $default,){
final _that = this;
switch (_that) {
case _ManagedPhone():
return $default(_that);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _ManagedPhone value)? $default,){
final _that = this;
switch (_that) {
case _ManagedPhone() when $default != null:
return $default(_that);case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String id, String? target, String? adbSerial, bool enabled, bool connected, String? lastError)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _ManagedPhone() when $default != null:
return $default(_that.id,_that.target,_that.adbSerial,_that.enabled,_that.connected,_that.lastError);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String id, String? target, String? adbSerial, bool enabled, bool connected, String? lastError) $default,) {final _that = this;
switch (_that) {
case _ManagedPhone():
return $default(_that.id,_that.target,_that.adbSerial,_that.enabled,_that.connected,_that.lastError);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String id, String? target, String? adbSerial, bool enabled, bool connected, String? lastError)? $default,) {final _that = this;
switch (_that) {
case _ManagedPhone() when $default != null:
return $default(_that.id,_that.target,_that.adbSerial,_that.enabled,_that.connected,_that.lastError);case _:
return null;
}
}
}
/// @nodoc
class _ManagedPhone extends ManagedPhone {
const _ManagedPhone({required this.id, this.target, this.adbSerial, required this.enabled, required this.connected, this.lastError}): super._();
@override final String id;
@override final String? target;
@override final String? adbSerial;
@override final bool enabled;
@override final bool connected;
@override final String? lastError;
/// Create a copy of ManagedPhone
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$ManagedPhoneCopyWith<_ManagedPhone> get copyWith => __$ManagedPhoneCopyWithImpl<_ManagedPhone>(this, _$identity);
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _ManagedPhone&&(identical(other.id, id) || other.id == id)&&(identical(other.target, target) || other.target == target)&&(identical(other.adbSerial, adbSerial) || other.adbSerial == adbSerial)&&(identical(other.enabled, enabled) || other.enabled == enabled)&&(identical(other.connected, connected) || other.connected == connected)&&(identical(other.lastError, lastError) || other.lastError == lastError));
}
@override
int get hashCode {
return Object.hash(runtimeType,id,target,adbSerial,enabled,connected,lastError);
}
@override
String toString() {
return 'ManagedPhone(id: $id, target: $target, adbSerial: $adbSerial, enabled: $enabled, connected: $connected, lastError: $lastError)';
}
}
/// @nodoc
abstract mixin class _$ManagedPhoneCopyWith<$Res> implements $ManagedPhoneCopyWith<$Res> {
factory _$ManagedPhoneCopyWith(_ManagedPhone value, $Res Function(_ManagedPhone) _then) = __$ManagedPhoneCopyWithImpl;
@override @useResult
$Res call({
String id, String? target, String? adbSerial, bool enabled, bool connected, String? lastError
});
}
/// @nodoc
class __$ManagedPhoneCopyWithImpl<$Res>
implements _$ManagedPhoneCopyWith<$Res> {
__$ManagedPhoneCopyWithImpl(this._self, this._then);
final _ManagedPhone _self;
final $Res Function(_ManagedPhone) _then;
/// Create a copy of ManagedPhone
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? target = freezed,Object? adbSerial = freezed,Object? enabled = null,Object? connected = null,Object? lastError = freezed,}) {
return _then(_ManagedPhone(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,target: freezed == target ? _self.target : target // ignore: cast_nullable_to_non_nullable
as String?,adbSerial: freezed == adbSerial ? _self.adbSerial : adbSerial // ignore: cast_nullable_to_non_nullable
as String?,enabled: null == enabled ? _self.enabled : enabled // ignore: cast_nullable_to_non_nullable
as bool,connected: null == connected ? _self.connected : connected // ignore: cast_nullable_to_non_nullable
as bool,lastError: freezed == lastError ? _self.lastError : lastError // ignore: cast_nullable_to_non_nullable
as String?,
));
}
}
/// @nodoc
mixin _$ManagedAgent {
String get id; String get name; bool get online; String get hostname; String get os; String get arch; String get version; int get pid; int get revision; bool get supervised; List<ManagedPhone> get devices;
/// Create a copy of ManagedAgent
/// with the given fields replaced by the non-null parameter values.
@JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
$ManagedAgentCopyWith<ManagedAgent> get copyWith => _$ManagedAgentCopyWithImpl<ManagedAgent>(this as ManagedAgent, _$identity);
@override
bool operator ==(Object other) {
final _this = this as ManagedAgent;
return identical(this, other) || (other.runtimeType == runtimeType&&other is ManagedAgent&&(identical(other.id, _this.id) || other.id == _this.id)&&(identical(other.name, _this.name) || other.name == _this.name)&&(identical(other.online, _this.online) || other.online == _this.online)&&(identical(other.hostname, _this.hostname) || other.hostname == _this.hostname)&&(identical(other.os, _this.os) || other.os == _this.os)&&(identical(other.arch, _this.arch) || other.arch == _this.arch)&&(identical(other.version, _this.version) || other.version == _this.version)&&(identical(other.pid, _this.pid) || other.pid == _this.pid)&&(identical(other.revision, _this.revision) || other.revision == _this.revision)&&(identical(other.supervised, _this.supervised) || other.supervised == _this.supervised)&&const DeepCollectionEquality().equals(other.devices, _this.devices));
}
@override
int get hashCode {
final _this = this as ManagedAgent;
return Object.hash(runtimeType,_this.id,_this.name,_this.online,_this.hostname,_this.os,_this.arch,_this.version,_this.pid,_this.revision,_this.supervised,const DeepCollectionEquality().hash(_this.devices));
}
@override
String toString() {
final _this = this as ManagedAgent;
return 'ManagedAgent(id: ${_this.id}, name: ${_this.name}, online: ${_this.online}, hostname: ${_this.hostname}, os: ${_this.os}, arch: ${_this.arch}, version: ${_this.version}, pid: ${_this.pid}, revision: ${_this.revision}, supervised: ${_this.supervised}, devices: ${_this.devices})';
}
}
/// @nodoc
abstract mixin class $ManagedAgentCopyWith<$Res> {
factory $ManagedAgentCopyWith(ManagedAgent value, $Res Function(ManagedAgent) _then) = _$ManagedAgentCopyWithImpl;
@useResult
$Res call({
String id, String name, bool online, String hostname, String os, String arch, String version, int pid, int revision, bool supervised, List<ManagedPhone> devices
});
}
/// @nodoc
class _$ManagedAgentCopyWithImpl<$Res>
implements $ManagedAgentCopyWith<$Res> {
_$ManagedAgentCopyWithImpl(this._self, this._then);
final ManagedAgent _self;
final $Res Function(ManagedAgent) _then;
/// Create a copy of ManagedAgent
/// with the given fields replaced by the non-null parameter values.
@pragma('vm:prefer-inline') @override $Res call({Object? id = null,Object? name = null,Object? online = null,Object? hostname = null,Object? os = null,Object? arch = null,Object? version = null,Object? pid = null,Object? revision = null,Object? supervised = null,Object? devices = null,}) {
return _then(ManagedAgent(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable
as String,online: null == online ? _self.online : online // ignore: cast_nullable_to_non_nullable
as bool,hostname: null == hostname ? _self.hostname : hostname // ignore: cast_nullable_to_non_nullable
as String,os: null == os ? _self.os : os // ignore: cast_nullable_to_non_nullable
as String,arch: null == arch ? _self.arch : arch // ignore: cast_nullable_to_non_nullable
as String,version: null == version ? _self.version : version // ignore: cast_nullable_to_non_nullable
as String,pid: null == pid ? _self.pid : pid // ignore: cast_nullable_to_non_nullable
as int,revision: null == revision ? _self.revision : revision // ignore: cast_nullable_to_non_nullable
as int,supervised: null == supervised ? _self.supervised : supervised // ignore: cast_nullable_to_non_nullable
as bool,devices: null == devices ? _self.devices : devices // ignore: cast_nullable_to_non_nullable
as List<ManagedPhone>,
));
}
}
/// Adds pattern-matching-related methods to [ManagedAgent].
extension ManagedAgentPatterns on ManagedAgent {
/// A variant of `map` that fallback to returning `orElse`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeMap<TResult extends Object?>(TResult Function( _ManagedAgent value)? $default,{required TResult orElse(),}){
final _that = this;
switch (_that) {
case _ManagedAgent() when $default != null:
return $default(_that);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// Callbacks receives the raw object, upcasted.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case final Subclass2 value:
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult map<TResult extends Object?>(TResult Function( _ManagedAgent value) $default,){
final _that = this;
switch (_that) {
case _ManagedAgent():
return $default(_that);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `map` that fallback to returning `null`.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case final Subclass value:
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? mapOrNull<TResult extends Object?>(TResult? Function( _ManagedAgent value)? $default,){
final _that = this;
switch (_that) {
case _ManagedAgent() when $default != null:
return $default(_that);case _:
return null;
}
}
/// A variant of `when` that fallback to an `orElse` callback.
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return orElse();
/// }
/// ```
@optionalTypeArgs TResult maybeWhen<TResult extends Object?>(TResult Function( String id, String name, bool online, String hostname, String os, String arch, String version, int pid, int revision, bool supervised, List<ManagedPhone> devices)? $default,{required TResult orElse(),}) {final _that = this;
switch (_that) {
case _ManagedAgent() when $default != null:
return $default(_that.id,_that.name,_that.online,_that.hostname,_that.os,_that.arch,_that.version,_that.pid,_that.revision,_that.supervised,_that.devices);case _:
return orElse();
}
}
/// A `switch`-like method, using callbacks.
///
/// As opposed to `map`, this offers destructuring.
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case Subclass2(:final field2):
/// return ...;
/// }
/// ```
@optionalTypeArgs TResult when<TResult extends Object?>(TResult Function( String id, String name, bool online, String hostname, String os, String arch, String version, int pid, int revision, bool supervised, List<ManagedPhone> devices) $default,) {final _that = this;
switch (_that) {
case _ManagedAgent():
return $default(_that.id,_that.name,_that.online,_that.hostname,_that.os,_that.arch,_that.version,_that.pid,_that.revision,_that.supervised,_that.devices);case _:
throw StateError('Unexpected subclass');
}
}
/// A variant of `when` that fallback to returning `null`
///
/// It is equivalent to doing:
/// ```dart
/// switch (sealedClass) {
/// case Subclass(:final field):
/// return ...;
/// case _:
/// return null;
/// }
/// ```
@optionalTypeArgs TResult? whenOrNull<TResult extends Object?>(TResult? Function( String id, String name, bool online, String hostname, String os, String arch, String version, int pid, int revision, bool supervised, List<ManagedPhone> devices)? $default,) {final _that = this;
switch (_that) {
case _ManagedAgent() when $default != null:
return $default(_that.id,_that.name,_that.online,_that.hostname,_that.os,_that.arch,_that.version,_that.pid,_that.revision,_that.supervised,_that.devices);case _:
return null;
}
}
}
/// @nodoc
class _ManagedAgent extends ManagedAgent {
const _ManagedAgent({required this.id, required this.name, required this.online, required this.hostname, required this.os, required this.arch, required this.version, required this.pid, required this.revision, required this.supervised, required List<ManagedPhone> devices}): _devices = devices,super._();
@override final String id;
@override final String name;
@override final bool online;
@override final String hostname;
@override final String os;
@override final String arch;
@override final String version;
@override final int pid;
@override final int revision;
@override final bool supervised;
final List<ManagedPhone> _devices;
@override List<ManagedPhone> get devices {
if (_devices is EqualUnmodifiableListView) return _devices;
// ignore: implicit_dynamic_type
return EqualUnmodifiableListView(_devices);
}
/// Create a copy of ManagedAgent
/// with the given fields replaced by the non-null parameter values.
@override @JsonKey(includeFromJson: false, includeToJson: false)
@pragma('vm:prefer-inline')
_$ManagedAgentCopyWith<_ManagedAgent> get copyWith => __$ManagedAgentCopyWithImpl<_ManagedAgent>(this, _$identity);
@override
bool operator ==(Object other) {
return identical(this, other) || (other.runtimeType == runtimeType&&other is _ManagedAgent&&(identical(other.id, id) || other.id == id)&&(identical(other.name, name) || other.name == name)&&(identical(other.online, online) || other.online == online)&&(identical(other.hostname, hostname) || other.hostname == hostname)&&(identical(other.os, os) || other.os == os)&&(identical(other.arch, arch) || other.arch == arch)&&(identical(other.version, version) || other.version == version)&&(identical(other.pid, pid) || other.pid == pid)&&(identical(other.revision, revision) || other.revision == revision)&&(identical(other.supervised, supervised) || other.supervised == supervised)&&const DeepCollectionEquality().equals(other.devices, _devices));
}
@override
int get hashCode {
return Object.hash(runtimeType,id,name,online,hostname,os,arch,version,pid,revision,supervised,const DeepCollectionEquality().hash(_devices));
}
@override
String toString() {
return 'ManagedAgent(id: $id, name: $name, online: $online, hostname: $hostname, os: $os, arch: $arch, version: $version, pid: $pid, revision: $revision, supervised: $supervised, devices: $devices)';
}
}
/// @nodoc
abstract mixin class _$ManagedAgentCopyWith<$Res> implements $ManagedAgentCopyWith<$Res> {
factory _$ManagedAgentCopyWith(_ManagedAgent value, $Res Function(_ManagedAgent) _then) = __$ManagedAgentCopyWithImpl;
@override @useResult
$Res call({
String id, String name, bool online, String hostname, String os, String arch, String version, int pid, int revision, bool supervised, List<ManagedPhone> devices
});
}
/// @nodoc
class __$ManagedAgentCopyWithImpl<$Res>
implements _$ManagedAgentCopyWith<$Res> {
__$ManagedAgentCopyWithImpl(this._self, this._then);
final _ManagedAgent _self;
final $Res Function(_ManagedAgent) _then;
/// Create a copy of ManagedAgent
/// with the given fields replaced by the non-null parameter values.
@override @pragma('vm:prefer-inline') $Res call({Object? id = null,Object? name = null,Object? online = null,Object? hostname = null,Object? os = null,Object? arch = null,Object? version = null,Object? pid = null,Object? revision = null,Object? supervised = null,Object? devices = null,}) {
return _then(_ManagedAgent(
id: null == id ? _self.id : id // ignore: cast_nullable_to_non_nullable
as String,name: null == name ? _self.name : name // ignore: cast_nullable_to_non_nullable
as String,online: null == online ? _self.online : online // ignore: cast_nullable_to_non_nullable
as bool,hostname: null == hostname ? _self.hostname : hostname // ignore: cast_nullable_to_non_nullable
as String,os: null == os ? _self.os : os // ignore: cast_nullable_to_non_nullable
as String,arch: null == arch ? _self.arch : arch // ignore: cast_nullable_to_non_nullable
as String,version: null == version ? _self.version : version // ignore: cast_nullable_to_non_nullable
as String,pid: null == pid ? _self.pid : pid // ignore: cast_nullable_to_non_nullable
as int,revision: null == revision ? _self.revision : revision // ignore: cast_nullable_to_non_nullable
as int,supervised: null == supervised ? _self.supervised : supervised // ignore: cast_nullable_to_non_nullable
as bool,devices: null == devices ? _self._devices : devices // ignore: cast_nullable_to_non_nullable
as List<ManagedPhone>,
));
}
}
// dart format on
@@ -0,0 +1,54 @@
import 'dart:io';
import 'agent_models.dart';
import 'agent_service.dart';
class AgentRepository {
const AgentRepository(this.api);
final AgentApi api;
String get connectionKey => api.connectionKey;
String redact(String text) => api.redact(text);
Future<List<ManagedAgent>> list({
required bool local,
required String config,
}) async {
final values = local
? [
<String, Object?>{
'id': '',
'online': true,
'status': await api.local(config, {'op': 'status'}),
},
]
: await api.list();
if (local) {
final status = Map<String, Object?>.from(
values[0]['status']! as Map<String, Object?>,
);
values[0]['id'] = status['id'];
}
return values.map(ManagedAgent.fromMap).toList(growable: false);
}
Future<Object?> call(
bool local,
String config,
String agent,
JsonMap operation,
) => local ? api.local(config, operation) : api.request(agent, operation);
Future<void> importAdmin(String path) => api.importAdmin(path);
Future<String> enrollment(String path) async {
final file = File(path);
if (await file.length() > 65536) {
throw const FormatException('凭据文件过大');
}
final line = (await file.readAsLines())
.where((v) => v.startsWith('ADS_AGENT_TOKEN='))
.firstOrNull;
final value = line?.substring(16).trim() ?? '';
if (value.length < 32) {
throw const FormatException('请选择包含 ADS_AGENT_TOKEN 的 agent.env');
}
return value;
}
}
+181
View File
@@ -0,0 +1,181 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:path/path.dart' as p;
import 'manager_repository.dart';
typedef JsonMap = Map<String, Object?>;
abstract interface class AgentApi {
String get connectionKey;
Future<List<JsonMap>> list();
Future<Object?> request(String agent, JsonMap operation);
Future<Object?> local(String config, JsonMap operation);
Future<void> importAdmin(String path);
Future<void> initialize(String path, JsonMap config, String token);
Future<void> start(String path);
Future<void> install(String path);
String redact(String message);
}
class AgentService implements AgentApi {
AgentService(this.manager);
final ManagerRepository manager;
@override
String get connectionKey =>
jsonEncode([manager.settings.server, manager.settings.origin]);
String _token = '';
final Set<String> _secrets = {};
@override
String redact(String message) {
for (final secret in _secrets) {
message = message.replaceAll(secret, '[REDACTED]');
}
return message;
}
@override
Future<void> importAdmin(String path) async {
final file = File(path);
if (await file.length() > 65536) {
throw const FormatException('凭据文件过大');
}
final line = (await file.readAsLines())
.where((v) => v.startsWith('ADS_ADMIN_TOKEN='))
.firstOrNull;
final token = line?.substring(16).trim() ?? '';
if (token.length < 32 || token.contains(RegExp(r'[\r\n]'))) {
throw const FormatException('请选择包含 ADS_ADMIN_TOKEN 的 admin.env');
}
_token = token;
_secrets.add(token);
}
@override
Future<List<JsonMap>> list() async {
final value =
await manager.requestJson('v3/agents', bearer: _token) as List<Object?>;
return value.map((v) => Map<String, Object?>.from(v! as Map)).toList();
}
@override
Future<Object?> request(String agent, JsonMap operation) async {
final value = await manager.requestJson(
'v3/rpc',
bearer: _token,
payload: operation,
query: {'agent': agent},
) as Map<String, dynamic>;
if (value['ok'] != true) {
throw StateError(redact(value['error'] as String? ?? 'Agent 管理请求失败'));
}
return value['data'];
}
Future<ProcessResult> _cli(
List<String> args, {
String? input,
Map<String, String>? extra,
}) async {
final child = await Process.start(
manager.findTool('adsctl'),
args,
environment: {...manager.environment(), ...?extra},
includeParentEnvironment: false,
);
final out = child.stdout.transform(utf8.decoder).join();
final error = child.stderr.transform(utf8.decoder).join();
if (input != null) {
child.stdin.write(input);
}
await child.stdin.close();
try {
final code = await child.exitCode.timeout(const Duration(seconds: 22));
final result = ProcessResult(child.pid, code, await out, await error);
if (code != 0) {
throw StateError(redact(result.stderr as String));
}
return result;
} on TimeoutException {
child.kill();
rethrow;
}
}
@override
Future<Object?> local(String config, JsonMap operation) async {
final result = await _cli([
'--json',
'--config',
config,
'request',
], input: jsonEncode(operation));
return jsonDecode(result.stdout as String);
}
@override
Future<void> initialize(String path, JsonMap config, String token) async {
if (token.length < 32) {
throw const FormatException('请导入有效设备端凭据');
}
_secrets.add(token);
final args = [
'--json',
'--config',
path,
'--server',
config['server']! as String,
if (config['connect_address'] case final String origin) ...[
'--connect-address',
origin,
],
'init',
'--id',
config['id']! as String,
'--name',
config['name']! as String,
];
await _cli(args, extra: {'ADS_AGENT_TOKEN': token});
}
@override
Future<void> start(String path) async {
try {
await local(path, {'op': 'status'});
return;
} on StateError {
/* The private IPC lock prevents a duplicate daemon. */
}
await Process.start(
manager.findTool('ads-agent'),
['--quiet', '--supervise', '--config', path],
mode: ProcessStartMode.detached,
environment: manager.environment(),
includeParentEnvironment: false,
);
await Future<void>.delayed(const Duration(milliseconds: 700));
}
@override
Future<void> install(String path) async {
if (!Platform.isWindows) {
throw UnsupportedError('请在终端运行 adsctl service install,系统级服务加 --system');
}
String quote(String text) => "'${text.replaceAll("'", "''")}'";
final exe = manager.findTool('adsctl');
final escaped = '"${p.absolute(path)}"';
final script =
'\$p=Start-Process -FilePath ${quote(exe)} -ArgumentList @(\'--config\',${quote(escaped)},\'service\',\'install\') -Verb RunAs -WindowStyle Hidden -PassThru -Wait;exit \$p.ExitCode';
final result = await Process.run(
'powershell.exe',
['-NoProfile', '-NonInteractive', '-Command', script],
environment: manager.environment(),
includeParentEnvironment: false,
);
if (result.exitCode != 0) {
throw StateError('开机服务安装失败,请在管理员终端检查 adsctl service install');
}
}
}
@@ -159,9 +159,19 @@ class ManagerRepository {
}
}
Future<dynamic> get(String suffix) async {
if (token.length < 32) {
throw const FormatException('请先导入客户端凭据');
Future<dynamic> get(String suffix) => requestJson(suffix);
Future<dynamic> requestJson(
String suffix, {
String? bearer,
Map<String, Object?>? payload,
Map<String, String>? query,
}) async {
final authorization = bearer ?? token;
if (authorization.length < 32) {
throw FormatException(
bearer == null ? '请先导入客户端凭据' : '请先导入管理员凭据 admin.env',
);
}
final client = HttpClient()..connectionTimeout = const Duration(seconds: 8);
client.findProxy = (_) => 'DIRECT';
@@ -192,9 +202,16 @@ class ManagerRepository {
};
}
try {
final request = await client.getUrl(settings.uri(suffix));
final uri = settings.uri(suffix).replace(queryParameters: query);
final request = payload == null
? await client.getUrl(uri)
: await client.postUrl(uri);
request.followRedirects = false;
request.headers.set('Authorization', 'Bearer $token');
request.headers.set('Authorization', 'Bearer $authorization');
if (payload != null) {
request.headers.contentType = ContentType.json;
request.write(jsonEncode(payload));
}
final response = await request.close().timeout(
const Duration(seconds: 12),
);
@@ -234,6 +251,7 @@ class ManagerRepository {
'ANDROID_ADB_SERVER_PORT',
'ADS_CLIENT_TOKEN',
'ADS_AGENT_TOKEN',
'ADS_ADMIN_TOKEN',
'ADS_CONNECT_ADDRESS',
].contains(k),
)
+263
View File
@@ -0,0 +1,263 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:path/path.dart' as p;
import '../data/agent_models.dart';
import '../data/agent_repository.dart';
import '../data/agent_service.dart';
class AgentModel extends ChangeNotifier {
AgentModel(this.repository);
final AgentRepository repository;
List<ManagedAgent> _agents = [];
List<ManagedAgent> get agents => List.unmodifiable(_agents);
String? selectedId, selectedPhone;
ManagedAgent? get selected =>
_agents.where((a) => a.id == selectedId).firstOrNull;
bool localMode = false, busy = false, autoRefresh = true, followLogs = false;
String adminPath = '',
enrollmentPath = '',
enrollmentToken = '',
configPath = '',
configText = '',
logText = '';
String deviceId = '', target = '', adbSerial = '', adbServer = '';
String notice = '远程管理需要独立管理员凭据;也可选择管理本机 Agent。';
Timer? _timer;
bool _disposed = false, _hasAdmin = false;
int _cursor = 0;
String _instance = '', _listedSource = '';
String get _sourceKey =>
localMode ? 'local:$configPath' : 'remote:${repository.connectionKey}';
bool get canManage =>
!busy && selected?.online == true && _listedSource == _sourceKey;
bool get canDevice => canManage && selectedPhone != null;
Future<void> initialize({
required String adminFile,
required String server,
required String origin,
}) async {
adminPath = adminFile;
configPath = Platform.isWindows
? p.join(
Platform.environment['LOCALAPPDATA'] ?? Directory.current.path,
'AndroidDeviceStreaming',
'agent',
'agent.json',
)
: p.join(
Platform.environment['XDG_CONFIG_HOME'] ??
p.join(Platform.environment['HOME'] ?? '.', '.config'),
'ads',
'agent.json',
);
configText = const JsonEncoder.withIndent(' ').convert({
'version': 1,
'id': 'local-pc',
'name': Platform.localHostname,
'server': server,
'connect_address': origin.trim().isEmpty ? null : origin,
'adb_server': '127.0.0.1:5037',
'devices': <Object?>[],
});
if (await File(adminPath).exists()) {
await importAdmin();
}
_timer = Timer.periodic(const Duration(seconds: 5), (_) {
if (!busy && autoRefresh && (localMode || _hasAdmin)) {
unawaited(
run(() async {
await _refresh();
if (followLogs && selected?.online == true) {
await _logs();
}
}),
);
}
});
_notify();
}
void _notify() {
if (!_disposed) {
notifyListeners();
}
}
Future<void> run(Future<void> Function() operation) async {
if (busy || _disposed) {
return;
}
busy = true;
_notify();
try {
await operation();
} catch (error) {
notice = repository.redact(error.toString());
} finally {
busy = false;
_notify();
}
}
void select(String? id) {
if (id != selectedId) {
selectedId = id;
_cursor = 0;
_instance = '';
logText = '';
selectedPhone = selected?.devices.firstOrNull?.id;
_notify();
}
}
void setLocal(bool value) {
localMode = value;
_agents = [];
select(null);
notice = value ? '管理本机 Agent,无需管理员令牌。' : '远程管理使用连接配置中的控制中心地址。';
_notify();
}
Future<void> importAdmin() => run(() async {
await repository.importAdmin(adminPath);
_hasAdmin = true;
notice = '管理员凭据已导入,仅保存在内存中。';
await _refresh();
});
Future<void> importEnrollment() => run(() async {
enrollmentToken = await repository.enrollment(enrollmentPath);
notice = '设备端凭据已导入,仅用于本机初始化。';
});
Future<void> refresh() => run(_refresh);
Future<void> _refresh() async {
final source = _sourceKey;
final mode = localMode;
final config = configPath;
final rows = await repository.list(local: mode, config: config);
if (_disposed || source != _sourceKey) {
return;
}
_listedSource = source;
_agents = List.unmodifiable(rows);
if (!_agents.any((a) => a.id == selectedId)) {
select(
_agents.where((a) => a.online).firstOrNull?.id ??
_agents.firstOrNull?.id,
);
}
if (selected?.devices.any((d) => d.id == selectedPhone) != true) {
selectedPhone = selected?.devices.firstOrNull?.id;
}
notice =
'${rows.length} 个 Agent · ${rows.where((a) => a.online).length} 个在线';
}
Future<Object?> _call(JsonMap operation) {
if (_listedSource != _sourceKey) {
throw StateError('管理地址或配置路径已改变,请先刷新 Agent 列表');
}
return repository.call(localMode, configPath, selectedId ?? '', operation);
}
Future<void> loadConfig() => run(() async {
configText = const JsonEncoder.withIndent(' ')
.convert(await _call({'op': 'config_get'}));
notice = '已读取配置,凭据不在配置中。';
});
Future<void> saveConfig() => run(() async {
final data = jsonDecode(configText) as Map<String, Object?>;
await _call({'op': 'config_set', 'config': data});
await _refresh();
notice = '配置已保存并应用,受影响的设备会重建连接。';
});
Future<void> addDevice() => run(() async {
if (target.trim().isEmpty == adbSerial.trim().isEmpty) {
throw const FormatException('手机地址与 ADB 序列号必须填写其中一项');
}
await _call({
'op': 'device_add',
'device': {
'id': deviceId.trim(),
'target': target.trim().isEmpty ? null : target.trim(),
'adb_serial': adbSerial.trim().isEmpty ? null : adbSerial.trim(),
'adb_server': adbServer.trim().isEmpty ? null : adbServer.trim(),
'device_port': 5555,
'enabled': true,
},
});
await _refresh();
notice = '手机已添加。';
});
Future<void> deviceOperation(String op, {bool? enabled}) => run(() async {
if (selectedPhone == null) {
return;
}
await _call({'op': op, 'id': selectedPhone, 'enabled': ?enabled});
await _refresh();
});
Future<void> restart() => run(() async {
await _call({'op': 'restart'});
notice = '监督进程将重启 Agent,手机连接会短暂中断。';
});
Future<void> readLogs() => run(_logs);
Future<void> _logs() async {
final page = Map<String, Object?>.from(
(await _call({'op': 'logs', 'after': _cursor, 'limit': 50}))!
as Map<String, Object?>,
);
final instance = page['instance'] as String;
if (_instance.isNotEmpty && _instance != instance) {
_cursor = 0;
logText = '';
_instance = instance;
return;
}
_instance = instance;
_cursor = page['next'] as int;
for (final value in page['entries']! as List<Object?>) {
final line = value! as Map<String, Object?>;
logText += repository.redact(
'${line['time']} ${line['level']} ${line['message']}\n',
);
}
if (logText.length > 100000) {
logText = logText.substring(logText.length - 100000);
}
}
Future<void> initializeLocal() => run(() async {
if (await File(configPath).exists()) {
throw StateError('配置已经存在,请读取后修改');
}
await repository.api.initialize(
configPath,
jsonDecode(configText) as Map<String, Object?>,
enrollmentToken,
);
enrollmentToken = '';
notice = '本机配置已初始化,可启动后台 Agent 后应用设备配置。';
});
Future<void> startLocal() => run(() async {
await repository.api.start(configPath);
await _refresh();
notice = '后台 Agent 已启动,退出客户端不会停止它。';
});
Future<void> installLocal() => run(() async {
await repository.api.install(configPath);
await _refresh();
notice = '已安装无界面开机服务。';
});
@override
void dispose() {
if (_disposed) {
return;
}
_disposed = true;
_timer?.cancel();
super.dispose();
}
}
+322
View File
@@ -0,0 +1,322 @@
import 'package:material_ui/material_ui.dart';
import '../data/agent_models.dart';
import 'agent_model.dart';
class AgentView extends StatefulWidget {
const AgentView({super.key, required this.model});
final AgentModel model;
@override
State<AgentView> createState() => _AgentViewState();
}
class _AgentViewState extends State<AgentView> {
final Map<String, TextEditingController> _fields = {};
AgentModel get m => widget.model;
Widget field(
String key,
String label,
String value,
void Function(String) change, {
bool secret = false,
int lines = 1,
}) {
final controller = _fields.putIfAbsent(
key,
() => TextEditingController(text: value),
);
if (controller.text != value) {
controller.text = value;
}
return Padding(
padding: const EdgeInsets.only(bottom: 12),
child: TextField(
controller: controller,
onChanged: change,
obscureText: secret,
maxLines: lines,
minLines: lines > 1 ? 6 : 1,
style: lines > 1
? const TextStyle(fontFamily: 'Consolas', fontSize: 12)
: null,
decoration: InputDecoration(
labelText: label,
border: const OutlineInputBorder(),
),
),
);
}
Widget button(String text, Future<void> Function() action, {bool? enabled}) =>
Padding(
padding: const EdgeInsets.only(right: 8, bottom: 8),
child: OutlinedButton(
onPressed: enabled == false || m.busy ? null : action,
child: Text(text),
),
);
Widget card(List<Widget> children) => Card(
child: Padding(
padding: const EdgeInsets.all(18),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: children,
),
),
);
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: m,
builder: (context, _) => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
children: [
Checkbox(
value: m.localMode,
onChanged: m.busy ? null : (v) => m.setLocal(v ?? false),
),
const Text('管理本机 Agent'),
const SizedBox(width: 20),
button('刷新 Agent', m.refresh),
Checkbox(
value: m.autoRefresh,
onChanged: (v) => setState(() => m.autoRefresh = v ?? false),
),
const Text('自动刷新'),
],
),
if (m.localMode) ...[
field('configPath', '本机配置路径', m.configPath, (v) => m.configPath = v),
Wrap(
children: [
button('启动后台 Agent', m.startLocal),
button('安装开机服务', m.installLocal),
],
),
] else
Row(
children: [
Expanded(
child: field(
'admin',
'admin.env 路径',
m.adminPath,
(v) => m.adminPath = v,
),
),
const SizedBox(width: 12),
button('导入管理员凭据', m.importAdmin),
],
),
Text(m.notice, style: const TextStyle(color: Colors.blueGrey)),
const SizedBox(height: 10),
if (m.busy) const LinearProgressIndicator(),
Expanded(
child: LayoutBuilder(
builder: (context, size) {
final list = Card(
child: ListView(
children: [
for (final agent in m.agents)
ListTile(
selected: agent.id == m.selectedId,
title: Text(agent.id),
subtitle: Text(agent.description),
leading: Icon(
Icons.computer,
color: agent.online ? Colors.green : Colors.grey,
),
onTap: m.busy ? null : () => m.select(agent.id),
),
],
),
);
final detail = ListView(
children: [
card([
Text(
m.selected?.description ?? '选择 Agent / 被控电脑',
style: Theme.of(context).textTheme.titleMedium,
),
if (m.selected case final agent?)
Text(
'${agent.hostname} · ${agent.os}/${agent.arch} · v${agent.version} · PID ${agent.pid} · 配置版本 ${agent.revision}',
),
const SizedBox(height: 12),
Wrap(
children: [
button('读取配置', m.loadConfig, enabled: m.canManage),
button(
'重启 Agent',
m.restart,
enabled:
m.canManage && m.selected?.supervised == true,
),
],
),
]),
card([
const Text(
'手机管理',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
for (final device
in m.selected?.devices ?? <ManagedPhone>[])
ListTile(
selected: device.id == m.selectedPhone,
title: Text(device.description),
subtitle: device.lastError == null
? null
: Text(device.lastError!),
onTap: m.busy
? null
: () => setState(() => m.selectedPhone = device.id),
),
Wrap(
children: [
button(
'启用',
() =>
m.deviceOperation('device_enable', enabled: true),
enabled: m.canDevice,
),
button(
'停用',
() => m.deviceOperation(
'device_enable',
enabled: false,
),
enabled: m.canDevice,
),
button(
'移除配置',
() => m.deviceOperation('device_remove'),
enabled: m.canDevice,
),
],
),
field('device', '设备 ID', m.deviceId, (v) => m.deviceId = v),
field(
'target',
'手机 adbd 地址',
m.target,
(v) => m.target = v,
),
ExpansionTile(
title: const Text('通过已有 ADB server 接入'),
children: [
field(
'serial',
'ADB 序列号(与手机地址二选一)',
m.adbSerial,
(v) => m.adbSerial = v,
),
field(
'adbserver',
'ADB server 地址(留空使用默认值)',
m.adbServer,
(v) => m.adbServer = v,
),
const Text('此模式仍要求手机开启 TCP adbd。'),
],
),
button('添加手机', m.addDevice, enabled: m.canManage),
]),
card([
const Text(
'Agent 配置',
style: TextStyle(
fontSize: 18,
fontWeight: FontWeight.bold,
),
),
const SizedBox(height: 10),
field(
'json',
'读取、编辑 Agent JSON 配置',
m.configText,
(v) => m.configText = v,
lines: 12,
),
button('保存并应用配置', m.saveConfig, enabled: m.canManage),
if (m.localMode) ...[
field(
'enroll',
'agent.env 路径',
m.enrollmentPath,
(v) => m.enrollmentPath = v,
),
button('导入设备端凭据', m.importEnrollment),
field(
'agentToken',
'ADS_AGENT_TOKEN',
m.enrollmentToken,
(v) => m.enrollmentToken = v,
secret: true,
),
button('初始化本机配置', m.initializeLocal),
],
]),
card([
Wrap(
crossAxisAlignment: WrapCrossAlignment.center,
children: [
button('读取日志', m.readLogs, enabled: m.canManage),
Checkbox(
value: m.followLogs,
onChanged: (v) =>
setState(() => m.followLogs = v ?? false),
),
const Text('持续跟随日志'),
],
),
SizedBox(
height: 200,
child: SingleChildScrollView(
child: SelectableText(
m.logText,
style: const TextStyle(
fontFamily: 'Consolas',
fontSize: 12,
),
),
),
),
]),
],
);
return size.maxWidth < 800
? Column(
children: [
SizedBox(height: 160, child: list),
Expanded(child: detail),
],
)
: Row(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
SizedBox(width: 280, child: list),
const SizedBox(width: 12),
Expanded(child: detail),
],
);
},
),
),
],
),
);
@override
void dispose() {
for (final field in _fields.values) {
field.dispose();
}
super.dispose();
}
}
+24
View File
@@ -3,9 +3,17 @@ import 'dart:async';
import 'package:flutter/foundation.dart';
import '../data/manager_repository.dart';
import '../data/agent_repository.dart';
import '../data/agent_service.dart';
import 'agent_model.dart';
import 'dart:io';
import 'package:path/path.dart' as p;
class ManagerModel extends ChangeNotifier {
late final ManagerRepository repository;
late final AgentModel agents;
List<Device> devices = [];
List<Map<String, dynamic>> nodes = [];
final List<String> logs = [];
@@ -16,6 +24,7 @@ class ManagerModel extends ChangeNotifier {
int ticks = 0;
ManagerModel() {
repository = ManagerRepository(log);
agents = AgentModel(AgentRepository(AgentService(repository)));
}
void log(String text) {
logs.insert(0, '${DateTime.now().toString().substring(11, 19)} $text');
@@ -38,6 +47,13 @@ class ManagerModel extends ChangeNotifier {
Future<void> init() async {
await action(() async {
await repository.init();
await agents.initialize(
adminFile: repository.root == null
? p.join(p.dirname(Platform.resolvedExecutable), 'admin.env')
: p.join(repository.root!.path, 'config', 'private', 'admin.env'),
server: repository.settings.server,
origin: repository.settings.origin,
);
notice = '准备就绪';
});
await refresh();
@@ -99,8 +115,16 @@ class ManagerModel extends ChangeNotifier {
'-l',
]);
});
@override
void dispose() {
agents.dispose();
timer?.cancel();
super.dispose();
}
Future<void> shutdown() async {
closing = true;
agents.dispose();
timer?.cancel();
while (pending.isNotEmpty) {
await Future<void>.delayed(const Duration(milliseconds: 50));
+4
View File
@@ -3,6 +3,7 @@ import 'package:flutter/services.dart';
import '../data/manager_repository.dart';
import 'manager_model.dart';
import 'agent_view.dart';
class ManagerView extends StatefulWidget {
final ManagerModel model;
@@ -54,6 +55,7 @@ class _ManagerViewState extends State<ManagerView> {
(2, '本机 ADB', Icons.terminal_rounded),
(3, '连接配置', Icons.tune_rounded),
(4, '运行日志', Icons.receipt_long_outlined),
(5, 'Agent 管理', Icons.computer_outlined),
])
Padding(
padding: const EdgeInsets.symmetric(
@@ -122,6 +124,7 @@ class _ManagerViewState extends State<ManagerView> {
'本机 ADB',
'连接配置',
'运行日志',
'Agent 管理',
][page],
style: const TextStyle(
fontSize: 24,
@@ -159,6 +162,7 @@ class _ManagerViewState extends State<ManagerView> {
1 => nodes(),
2 => adb(),
3 => SettingsView(model: m),
5 => AgentView(model: m.agents),
_ => logs(),
},
),
@@ -0,0 +1,79 @@
import 'dart:convert';
import 'dart:io';
import 'package:ads_manager/data/manager_repository.dart';
import 'package:ads_manager/data/agent_service.dart';
Future<void> main(List<String> args) async {
final id = Platform.environment['ADS_TEST_MANAGED_AGENT'];
if (id == null || !id.startsWith('gui-test-')) {
throw StateError(
'Requires an isolated gui-test Agent; never targets a user Agent',
);
}
final manager = ManagerRepository((_) {});
await manager.init();
final service = AgentService(manager);
await service.importAdmin('${manager.root!.path}/config/private/admin.env');
final local = args.contains('--local');
Future<Object?> call(JsonMap operation) => local
? service.local(Platform.environment['ADS_TEST_AGENT_CONFIG']!, operation)
: service.request(id, operation);
Future<JsonMap> status() async =>
Map<String, Object?>.from((await call({'op': 'status'}))! as Map);
try {
final deadline = DateTime.now().add(const Duration(seconds: 50));
while (!(await service.list()).any(
(a) => a['id'] == id && a['online'] == true,
)) {
if (DateTime.now().isAfter(deadline)) {
throw StateError('Agent discovery timed out');
}
await Future<void>.delayed(const Duration(milliseconds: 300));
}
final config = Map<String, Object?>.from(
(await call({'op': 'config_get'}))! as Map,
);
config['name'] = 'Flutter managed test';
await call({'op': 'config_set', 'config': config});
await call({
'op': 'device_add',
'device': {'id': '$id-phone', 'target': '127.0.0.1:9', 'enabled': true},
});
await call({'op': 'device_enable', 'id': '$id-phone', 'enabled': false});
final devices = (await status())['devices']! as List<Object?>;
if ((devices.single! as Map)['enabled'] != false) {
throw StateError('Disable failed');
}
await call({'op': 'device_enable', 'id': '$id-phone', 'enabled': true});
final logs = Map<String, Object?>.from(
(await call({'op': 'logs', 'after': 0, 'limit': 50}))! as Map,
);
if ((logs['entries']! as List<Object?>).isEmpty) {
throw StateError('No logs');
}
await call({'op': 'device_remove', 'id': '$id-phone'});
final pid = (await status())['pid'];
await call({'op': 'restart'});
var restarted = false;
for (var i = 0; i < 40; i++) {
await Future<void>.delayed(const Duration(milliseconds: 400));
try {
if ((await status())['pid'] != pid) {
restarted = true;
break;
}
} catch (_) {}
}
if (!restarted) throw StateError('Restart failed');
// Serialization must remain valid and contain no credential fields.
if (jsonEncode(config).contains('TOKEN')) {
throw StateError('Credentials in configuration');
}
stdout.writeln(
'PASS: Flutter ${local ? "local IPC" : "remote admin"} discovery, config, phone CRUD, logs and supervised restart',
);
} finally {
await manager.shutdown();
}
}
+144
View File
@@ -0,0 +1,144 @@
import 'dart:async';
import 'package:material_ui/material_ui.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:ads_manager/data/agent_repository.dart';
import 'package:ads_manager/data/agent_service.dart';
import 'package:ads_manager/ui/agent_model.dart';
import 'package:ads_manager/ui/agent_view.dart';
class FakeApi implements AgentApi {
@override
String connectionKey = 'first-center';
final calls = <JsonMap>[];
Completer<List<JsonMap>>? pending;
JsonMap status(String id) => {
'id': id,
'name': id,
'pid': 123,
'supervised': true,
'devices': [
{
'id': '$id-phone',
'target': '127.0.0.1:5555',
'enabled': true,
'connected': true,
},
],
};
@override
Future<List<JsonMap>> list() async => pending == null
? [
for (final id in ['one', 'two'])
{'id': id, 'online': true, 'status': status(id)},
]
: pending!.future;
@override
Future<Object?> request(String agent, JsonMap operation) async {
calls.add({...operation, 'agent': agent});
return switch (operation['op']) {
'config_get' => {'id': agent, 'devices': <Object?>[]},
'logs' => {
'instance': 'i',
'next': 1,
'entries': [
{'time': 1, 'level': 'INFO', 'message': 'private-token'},
],
},
_ => <String, Object?>{},
};
}
@override
Future<Object?> local(String config, JsonMap operation) async =>
status('local');
@override
Future<void> importAdmin(String path) async {}
@override
Future<void> initialize(String path, JsonMap config, String token) async {}
@override
Future<void> start(String path) async {}
@override
Future<void> install(String path) async {}
@override
String redact(String text) => text.replaceAll('private-token', '[REDACTED]');
}
void main() {
test(
'selected agent scopes mutations and log secrets are redacted',
() async {
final api = FakeApi();
final m = AgentModel(AgentRepository(api));
await m.refresh();
expect(m.agents.length, 2);
m.select('two');
m.deviceId = 'new-phone';
m.target = '127.0.0.1:5555';
await m.addDevice();
expect(api.calls.last['agent'], 'two');
expect(api.calls.last['op'], 'device_add');
await m.deviceOperation('device_enable', enabled: false);
expect(api.calls.last['id'], 'two-phone');
expect(api.calls.last['enabled'], false);
await m.readLogs();
expect(m.logText, contains('[REDACTED]'));
expect(m.logText, isNot(contains('private-token')));
expect(m.logText.endsWith('\n'), true);
expect(() => m.agents.clear(), throwsUnsupportedError);
m.dispose();
},
);
test('late remote response cannot overwrite local mode', () async {
final api = FakeApi()..pending = Completer<List<JsonMap>>();
final m = AgentModel(AgentRepository(api));
final refresh = m.refresh();
m.setLocal(true);
api.pending!.complete([
{'id': 'old', 'online': true, 'status': api.status('old')},
]);
await refresh;
expect(m.agents, isEmpty);
await m.refresh();
expect(m.selectedId, 'local');
m.dispose();
});
test('changing center blocks mutations from a stale list', () async {
final api = FakeApi();
final m = AgentModel(AgentRepository(api));
await m.refresh();
api.connectionKey = 'second-center';
await m.restart();
expect(api.calls, isEmpty);
expect(m.notice, contains('先刷新'));
await m.refresh();
await m.restart();
expect(api.calls.last['op'], 'restart');
m.dispose();
});
for (final width in [620.0, 1280.0]) {
testWidgets('agent management layout and selection at $width', (
tester,
) async {
tester.view.physicalSize = Size(width, 900);
tester.view.devicePixelRatio = 1;
addTearDown(tester.view.resetPhysicalSize);
addTearDown(tester.view.resetDevicePixelRatio);
final m = AgentModel(AgentRepository(FakeApi()));
await m.refresh();
await tester.pumpWidget(
MaterialApp(
home: Scaffold(body: AgentView(model: m)),
),
);
await tester.pumpAndSettle();
expect(find.textContaining('two · 在线'), findsOneWidget);
await tester.tap(find.textContaining('two · 在线'));
await tester.pumpAndSettle();
expect(m.selectedId, 'two');
expect(tester.takeException(), isNull);
await tester.pumpWidget(const SizedBox());
m.dispose();
});
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ try {
if ($LASTEXITCODE -ne 0) { throw 'Desktop publish failed' }
} finally { Pop-Location }
$suffix = if ($Runtime.StartsWith('win-')) { '.exe' } else { '' }
foreach ($toolName in @('ads-client', 'ads-usb')) {
foreach ($toolName in @('ads-client', 'ads-usb', 'adsctl', 'ads-agent')) {
$client = Join-Path $projectRoot ('bin/' + $toolName + $suffix)
if (Test-Path -LiteralPath $client) {
Copy-Item -LiteralPath $client -Destination (Join-Path $outputDirectory ($toolName + $suffix)) -Force
+20
View File
@@ -0,0 +1,20 @@
$ErrorActionPreference = 'Stop'
$projectRoot = Split-Path $PSScriptRoot -Parent
$output = Join-Path $projectRoot 'bin/flutter-win-x64'
Push-Location (Join-Path $projectRoot 'flutter_manager')
try {
flutter build windows --release
if ($LASTEXITCODE -ne 0) { throw 'Flutter publish failed' }
} finally { Pop-Location }
New-Item -ItemType Directory -Force -Path $output | Out-Null
Copy-Item -Path (Join-Path $projectRoot 'flutter_manager/build/windows/x64/runner/Release/*') -Destination $output -Recurse -Force
foreach ($name in @('ads-client','ads-agent','adsctl')) {
$tool = Join-Path $projectRoot "bin/$name.exe"
if (-not (Test-Path -LiteralPath $tool)) { throw "先运行 scripts/build.ps1:缺少 $name" }
Copy-Item -LiteralPath $tool -Destination $output -Force
}
$tools = Join-Path $output 'tools/scrcpy'
New-Item -ItemType Directory -Force -Path $tools | Out-Null
Copy-Item -Path (Join-Path $projectRoot 'bin/tools/scrcpy/*') -Destination $tools -Recurse -Force
# Private credentials are deliberately excluded from distributable artifacts.
Write-Host "Flutter published to $output (credentials excluded)"
+1 -1
View File
@@ -8,7 +8,7 @@ try {
else { cargo build --workspace --release --locked }
if ($LASTEXITCODE -ne 0) { throw 'Rust build failed' }
New-Item -ItemType Directory -Force -Path (Join-Path $projectRoot 'bin') | Out-Null
foreach ($name in @('ads-agent', 'ads-client', 'ads-usb')) {
foreach ($name in @('ads-agent', 'ads-client', 'ads-usb', 'adsctl')) {
Copy-Item -LiteralPath (Join-Path $projectRoot "target/$configuration/$name.exe") -Destination (Join-Path $projectRoot "bin/$name.exe") -Force
}
Push-Location (Join-Path $projectRoot 'server')
+1 -1
View File
@@ -4,7 +4,7 @@ project_root=$(CDPATH='' cd -- "$(dirname -- "$0")/.." && pwd)
cd "$project_root"
cargo build --workspace --release --locked
mkdir -p bin
cp target/release/ads-agent target/release/ads-client target/release/ads-usb bin/
cp target/release/ads-agent target/release/ads-client target/release/ads-usb target/release/adsctl bin/
cd server
go build -trimpath -o ../bin/ads-server .
go build -trimpath -o ../bin/ads-relay ./cmd/ads-relay
+5
View File
@@ -0,0 +1,5 @@
$ErrorActionPreference = 'Stop'
$projectRoot = Split-Path $PSScriptRoot -Parent
$app = Join-Path $projectRoot 'bin/desktop-win-x64/Ads.Desktop.exe'
if (-not (Test-Path -LiteralPath $app)) { throw '先运行 scripts/build-desktop.ps1' }
Start-Process -FilePath $app -ArgumentList '--agent-tray' -WindowStyle Hidden
+16 -1
View File
@@ -49,13 +49,15 @@ type broker struct {
leases map[string]*lease // indexed by device, one owner per device
sessions map[string]*session
agentToken, clientToken string
adminToken string
managers map[string]*manager
ctx context.Context
cluster *cluster
}
func newBroker(ctx context.Context, agentToken, clientToken string) *broker {
return &broker{agents: make(map[string]*agent), leases: make(map[string]*lease),
sessions: make(map[string]*session), agentToken: agentToken, clientToken: clientToken, ctx: ctx}
sessions: make(map[string]*session), managers: make(map[string]*manager), agentToken: agentToken, clientToken: clientToken, ctx: ctx}
}
func newID() string {
var data [24]byte
@@ -353,6 +355,9 @@ func bridgeWebSockets(ctx context.Context, left, right *websocket.Conn) {
}
func (b *broker) handler() http.Handler {
mux := http.NewServeMux()
mux.HandleFunc("GET /v3/agents/register", b.auth(b.agentToken, b.managerRegister))
mux.HandleFunc("GET /v3/agents", b.managementAuth(b.managersEndpoint))
mux.HandleFunc("/v3/rpc", b.managementAuth(b.managerRPCEndpoint))
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { io.WriteString(w, "ok\n") })
mux.HandleFunc("GET /v1/agent", b.auth(b.agentToken, b.agentEndpoint))
mux.HandleFunc("GET /v1/data", b.auth(b.agentToken, b.dataEndpoint))
@@ -381,6 +386,10 @@ func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
b := newBroker(ctx, agentToken, clientToken)
b.adminToken = os.Getenv("ADS_ADMIN_TOKEN")
if b.adminToken != "" && (len(b.adminToken) < 32 || b.adminToken == agentToken || b.adminToken == clientToken) {
log.Fatal("ADS_ADMIN_TOKEN must be distinct and at least 32 characters")
}
if *clusterFile != "" {
configured, err := loadCluster(*clusterFile, os.Getenv("ADS_RELAY_SECRET"), *insecureNodes)
if err != nil {
@@ -393,6 +402,12 @@ func main() {
go func() {
<-ctx.Done()
b.mu.Lock()
for _, m := range b.managers {
m.cancel()
if m.ws != nil {
m.ws.CloseNow()
}
}
for _, a := range b.agents {
if a.ws != nil {
a.ws.CloseNow()
+284
View File
@@ -0,0 +1,284 @@
package main
import (
"context"
"encoding/json"
"github.com/coder/websocket"
"io"
"net/http"
"sort"
"strings"
"time"
)
type managedDevice struct {
ID string `json:"id"`
Target *string `json:"target,omitempty"`
ADBSerial *string `json:"adb_serial,omitempty"`
ADBServer *string `json:"adb_server,omitempty"`
DevicePort uint16 `json:"device_port"`
Enabled bool `json:"enabled"`
Connected bool `json:"connected"`
LastError *string `json:"last_error"`
}
type managedStatus struct {
ID string `json:"id"`
Name string `json:"name"`
Hostname string `json:"hostname"`
OS string `json:"os"`
Arch string `json:"arch"`
Version string `json:"version"`
PID uint32 `json:"pid"`
Uptime uint64 `json:"uptime_seconds"`
Supervised bool `json:"supervised"`
Revision uint64 `json:"revision"`
Instance string `json:"instance"`
Devices []managedDevice `json:"devices"`
}
type manager struct {
id string
ws *websocket.Conn
status managedStatus
lastSeen int64
ctx context.Context
cancel context.CancelFunc
pending map[string]chan json.RawMessage
}
func (b *broker) managementAuth(handler http.HandlerFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
if len(b.adminToken) < 32 {
http.Error(w, "management admin token is not configured", 503)
return
}
b.auth(b.adminToken, handler)(w, r)
}
}
func (b *broker) redactManagement(data []byte) []byte {
text := string(data)
for _, secret := range []string{b.agentToken, b.clientToken, b.adminToken} {
if secret != "" {
text = strings.ReplaceAll(text, secret, "[REDACTED]")
}
}
return []byte(text)
}
func (b *broker) managerRegister(w http.ResponseWriter, r *http.Request) {
id := r.URL.Query().Get("agent")
if !validID(id) {
http.Error(w, "invalid agent ID", 400)
return
}
b.mu.Lock()
if old := b.managers[id]; old != nil && old.ctx.Err() == nil {
b.mu.Unlock()
http.Error(w, "agent already registered", 409)
return
}
if b.managers[id] == nil && len(b.managers) >= 128 {
b.mu.Unlock()
http.Error(w, "agent registry full", 429)
return
}
ctx, cancel := context.WithCancel(b.ctx)
m := &manager{id: id, ctx: ctx, cancel: cancel, pending: map[string]chan json.RawMessage{}, status: managedStatus{ID: id, Devices: []managedDevice{}}, lastSeen: time.Now().Unix()}
b.managers[id] = m
b.mu.Unlock()
defer func() { cancel(); b.mu.Lock(); m.ws = nil; b.mu.Unlock() }()
ws, err := accept(w, r)
if err != nil {
return
}
defer ws.CloseNow()
b.mu.Lock()
m.ws = ws
b.mu.Unlock()
if writeJSON(ctx, ws, map[string]string{"type": "registered", "agent": id}) != nil {
return
}
go func() {
ticker := time.NewTicker(20 * time.Second)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
deadline, stop := context.WithTimeout(ctx, 10*time.Second)
err := ws.Ping(deadline)
stop()
if err != nil {
cancel()
return
}
}
}
}()
for {
typ, data, err := ws.Read(ctx)
if err != nil || typ != websocket.MessageText {
return
}
var message struct {
Type string `json:"type"`
RequestID string `json:"request_id"`
Status managedStatus `json:"status"`
Response json.RawMessage `json:"response"`
}
if json.Unmarshal(b.redactManagement(data), &message) != nil {
return
}
switch message.Type {
case "status":
s := message.Status
if s.ID != id || len(s.Name) > 128 || len(s.Hostname) > 256 || len(s.OS) > 64 || len(s.Arch) > 64 || len(s.Version) > 64 || len(s.Instance) > 128 || len(s.Devices) > 128 {
return
}
for _, d := range s.Devices {
if !validID(d.ID) || (d.Target != nil && len(*d.Target) > 256) || (d.ADBSerial != nil && len(*d.ADBSerial) > 256) || (d.LastError != nil && len(*d.LastError) > 2048) {
return
}
}
if s.Devices == nil {
s.Devices = []managedDevice{}
}
b.mu.Lock()
m.status = s
m.lastSeen = time.Now().Unix()
b.mu.Unlock()
case "result":
if len(message.Response) == 0 {
return
}
var check struct {
OK bool `json:"ok"`
}
if json.Unmarshal(message.Response, &check) != nil {
return
}
b.mu.Lock()
ch := m.pending[message.RequestID]
b.mu.Unlock()
if ch != nil {
select {
case ch <- message.Response:
default:
}
}
default:
return
}
}
}
func isWebSocket(r *http.Request) bool {
return strings.EqualFold(r.Header.Get("Upgrade"), "websocket")
}
func (b *broker) managersEndpoint(w http.ResponseWriter, r *http.Request) {
type record struct {
ID string `json:"id"`
Online bool `json:"online"`
LastSeen int64 `json:"last_seen"`
Status managedStatus `json:"status"`
}
b.mu.Lock()
records := []record{}
for _, m := range b.managers {
records = append(records, record{m.id, m.ws != nil, m.lastSeen, m.status})
}
b.mu.Unlock()
sort.Slice(records, func(i, j int) bool { return records[i].ID < records[j].ID })
if isWebSocket(r) {
ws, err := accept(w, r)
if err != nil {
return
}
defer ws.CloseNow()
writeJSON(r.Context(), ws, records)
return
}
w.Header().Set("Content-Type", "application/json")
json.NewEncoder(w).Encode(records)
}
func validManagementRequest(raw []byte) bool {
var request struct {
Op string `json:"op"`
}
if json.Unmarshal(raw, &request) != nil {
return false
}
switch request.Op {
case "status", "devices_list", "device_add", "device_remove", "device_enable", "config_get", "config_set", "logs", "restart":
return true
}
return false
}
func (b *broker) managerRPC(ctx context.Context, id string, request json.RawMessage) json.RawMessage {
failure := func(reason string) json.RawMessage {
data, _ := json.Marshal(map[string]any{"ok": false, "error": reason})
return data
}
if !validID(id) || !validManagementRequest(request) {
return failure("invalid management request")
}
b.mu.Lock()
m := b.managers[id]
if m == nil || m.ws == nil {
b.mu.Unlock()
return failure("agent is offline")
}
if len(m.pending) >= 16 {
b.mu.Unlock()
return failure("agent management request limit reached")
}
requestID := newID()
response := make(chan json.RawMessage, 1)
m.pending[requestID] = response
ws := m.ws
b.mu.Unlock()
defer func() { b.mu.Lock(); delete(m.pending, requestID); b.mu.Unlock() }()
deadline, cancel := context.WithTimeout(ctx, 15*time.Second)
defer cancel()
if writeJSON(deadline, ws, map[string]any{"type": "request", "request_id": requestID, "request": request}) != nil {
return failure("cannot reach agent")
}
select {
case data := <-response:
return data
case <-m.ctx.Done():
return failure("agent disconnected")
case <-deadline.Done():
return failure("agent management request timed out")
}
}
func (b *broker) managerRPCEndpoint(w http.ResponseWriter, r *http.Request) {
var request []byte
if isWebSocket(r) {
ws, err := accept(w, r)
if err != nil {
return
}
defer ws.CloseNow()
deadline, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
typ, data, err := ws.Read(deadline)
if err != nil || typ != websocket.MessageText || len(data) > 64*1024 {
return
}
response := b.managerRPC(r.Context(), r.URL.Query().Get("agent"), data)
writeJSON(r.Context(), ws, json.RawMessage(response))
return
}
if r.Method != "POST" {
http.Error(w, "POST required", 405)
return
}
var err error
request, err = io.ReadAll(http.MaxBytesReader(w, r.Body, 64*1024))
if err != nil {
http.Error(w, "request too large", 413)
return
}
response := b.managerRPC(r.Context(), r.URL.Query().Get("agent"), request)
w.Header().Set("Content-Type", "application/json")
w.Write(response)
}
+101
View File
@@ -0,0 +1,101 @@
package main
import (
"context"
"encoding/json"
"github.com/coder/websocket"
"net/http"
"strings"
"testing"
"time"
)
const testAdminToken = "management-admin-token-for-tests-1234567890"
func TestManagementRoleAndRequestCorrelation(t *testing.T) {
b, base := testServer(t)
b.adminToken = testAdminToken
for _, role := range []string{testAgentToken, testClientToken} {
if got := status(t, base, "/v3/agents", role); got != 401 {
t.Fatal(got)
}
}
if got := status(t, base, "/v3/agents/register?agent=host", testAdminToken); got != 401 {
t.Fatal(got)
}
manager := dialTest(t, base, "/v3/agents/register?agent=host", testAgentToken)
if readControl(t, manager)["type"] != "registered" {
t.Fatal("not registered")
}
if got := status(t, base, "/v3/agents/register?agent=host", testAgentToken); got != 409 {
t.Fatal(got)
}
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
defer cancel()
manager.Write(ctx, websocket.MessageText, []byte(`{"type":"status","status":{"id":"host","name":"test","devices":[]}}`))
admin := dialTest(t, base, "/v3/rpc?agent=host", testAdminToken)
admin.Write(ctx, websocket.MessageText, []byte(`{"op":"status"}`))
_, data, err := manager.Read(ctx)
if err != nil {
t.Fatal(err)
}
var request struct {
Type string `json:"type"`
RequestID string `json:"request_id"`
Request struct {
Op string `json:"op"`
} `json:"request"`
}
json.Unmarshal(data, &request)
if request.Type != "request" || request.RequestID == "" || request.Request.Op != "status" {
t.Fatal(string(data))
}
response, _ := json.Marshal(map[string]any{"type": "result", "request_id": request.RequestID, "response": map[string]any{"ok": true, "data": map[string]string{"secret": testAgentToken}}})
manager.Write(ctx, websocket.MessageText, response)
_, result, err := admin.Read(ctx)
if err != nil {
t.Fatal(err)
}
if strings.Contains(string(result), testAgentToken) || !strings.Contains(string(result), "REDACTED") {
t.Fatal("secret not redacted")
}
manager.CloseNow()
deadline := time.Now().Add(time.Second)
for time.Now().Before(deadline) {
b.mu.Lock()
offline := b.managers["host"].ws == nil
b.mu.Unlock()
if offline {
return
}
time.Sleep(time.Millisecond * 5)
}
t.Fatal("agent stayed online after disconnect")
}
func TestManagementDisabledAndOfflineLimits(t *testing.T) {
b, base := testServer(t)
if got := status(t, base, "/v3/agents", testClientToken); got != 503 {
t.Fatal(got)
}
b.adminToken = testAdminToken
for _, body := range []string{`{"op":"shell"}`, `{"op":"restart"}`} {
request, _ := http.NewRequest("POST", base+"/v3/rpc?agent=offline", strings.NewReader(body))
request.Header.Set("Authorization", "Bearer "+testAdminToken)
response, err := http.DefaultClient.Do(request)
if err != nil {
t.Fatal(err)
}
var result struct {
OK bool `json:"ok"`
Error string `json:"error"`
}
json.NewDecoder(response.Body).Decode(&result)
response.Body.Close()
if result.OK || result.Error == "" {
t.Fatal("offline or unsupported request accepted")
}
}
if got := status(t, base, "/v3/agents/register?agent=bad%20id", testAgentToken); got != 400 {
t.Fatal(got)
}
}
+112
View File
@@ -0,0 +1,112 @@
"""Real binaries: private local IPC, remote admin RPC, multi-device config and supervised restart."""
from e2e import *
import uuid
def main():
parser=argparse.ArgumentParser();parser.add_argument('--rust-dir',type=Path,default=ROOT/'target/debug');parser.add_argument('--bin-dir',type=Path,default=ROOT/'bin');parser.add_argument('--work-dir',type=Path,default=ROOT/'work/management-e2e');args=parser.parse_args()
folder=args.work_dir/uuid.uuid4().hex;folder.mkdir(parents=True,mode=0o700)
suffix='.exe' if os.name=='nt' else ''
agent=args.rust_dir/('ads-agent'+suffix);ctl=args.rust_dir/('adsctl'+suffix)
client=args.rust_dir/('ads-client'+suffix);server=args.bin_dir/('ads-server'+suffix)
tokens={k:secrets.token_hex(32) for k in ('ADS_AGENT_TOKEN','ADS_CLIENT_TOKEN','ADS_ADMIN_TOKEN')}
port=free_port();address=f'ws://127.0.0.1:{port}';api=address.replace('ws:','http:')
config=folder/'agent.json';processes=[];handles=[]
def environment(keys):
env=os.environ.copy()
for k in (*tokens,'ADS_CONNECT_ADDRESS'):env.pop(k,None)
env.update({k:tokens[k] for k in keys});env['RUST_LOG']='ads_agent=info,ads_client=info,ads_core=info';return env
def launch(name,args,keys=()):
handle=open(folder/(name+'.log'),'wb');handles.append(handle)
p=subprocess.Popen([str(a) for a in args],env=environment(keys),stdout=handle,stderr=handle,creationflags=subprocess.CREATE_NO_WINDOW if os.name=='nt' else 0);processes.append(p);return p
def stop(p):
if p.poll() is None:p.terminate();p.wait(timeout=10)
def cli(args,remote=False,expect=True,input=None):
command=[ctl,'--json','--config',config,'--server',address,'--allow-insecure']
if remote:command+=['--agent','test-host']
result=subprocess.run([str(x) for x in [*command,*args]],env=environment(('ADS_ADMIN_TOKEN',) if remote else ('ADS_AGENT_TOKEN',)),input=json.dumps(input) if input is not None else None,capture_output=True,text=True,timeout=25)
if expect:
assert result.returncode==0,result.stderr
return json.loads(result.stdout)
assert result.returncode!=0,(result.stdout,result.stderr);return result
def get(path,token='ADS_ADMIN_TOKEN'):
req=urllib.request.Request(api+path,headers={'Authorization':'Bearer '+tokens[token]})
with urllib.request.urlopen(req,timeout=3) as r:return json.load(r)
def active():
result=cli(['status']);return result if result['devices'] and all(d['connected'] for d in result['devices'] if d['enabled']) else None
with Phone(('127.0.0.1',0),Echo) as phone:
threading.Thread(target=phone.serve_forever,daemon=True).start();target=f'127.0.0.1:{phone.server_address[1]}'
try:
launch('server',[server,'--listen',f'127.0.0.1:{port}'],tokens)
wait_until(lambda:get('/v3/agents')==[],'controller')
cli(['init','--id','test-host','--name','Headless test host'])
launch('agent',[agent,'--supervise','--config',config])
wait_until(lambda:bool(cli(['status'])),'local IPC')
initial_pid=cli(['status'])['pid']
duplicate=launch('duplicate',[agent,'--config',config])
duplicate.wait(timeout=8);assert duplicate.returncode!=0,'duplicate daemon was allowed'
assert cli(['status'])['pid']==initial_pid
if os.name!='nt':
import stat
assert stat.S_IMODE(next(folder.glob('agent-*.sock')).stat().st_mode)==0o600
assert stat.S_IMODE(config.stat().st_mode)==0o600
wait_until(lambda:any(r['online'] and r['status']['id']=='test-host' for r in get('/v3/agents')),'management registration')
for key in ('ADS_CLIENT_TOKEN','ADS_AGENT_TOKEN'):
try:get('/v3/agents',key);raise AssertionError('non-admin role could manage agents')
except urllib.error.HTTPError as e:assert e.code==401
cli(['devices','add','--id','managed-one','--target',target])
cli(['devices','add','--id','managed-two','--target',target],remote=True)
wait_until(active,'two workers online')
original=config.read_bytes()
cli(['devices','add','--id','managed-one','--target',target],expect=False)
assert config.read_bytes()==original,'failed config operation modified persisted config'
invalid=json.loads(original);invalid['devices'][1]['id']='managed-one';bad=folder/'invalid.json';bad.write_text(json.dumps(invalid))
cli(['config','set','--file',bad],remote=True,expect=False);assert config.read_bytes()==original
current=cli(['config','get'],remote=True);assert len(current['devices'])==2
print('PASS: local IPC and admin-only remote CLI, two device workers, atomic validation',flush=True)
clients=[]
for name in ('managed-one','managed-two'):
local=free_port();p=launch(name,[client,'--server',address,'--allow-insecure','--device',name,'--listen',f'127.0.0.1:{local}','--no-auto-connect'],('ADS_CLIENT_TOKEN',));clients.append((p,local))
wait_until(lambda:len(get('/v1/devices','ADS_CLIENT_TOKEN'))==2 and all(d['busy'] for d in get('/v1/devices','ADS_CLIENT_TOKEN')),'both leases')
with socket.create_connection(('127.0.0.1',clients[1][1]),timeout=5) as live:
live.settimeout(5);live.sendall(b'before');assert live.recv(6)==b'before'
cli(['devices','disable','managed-one'],remote=True)
wait_until(lambda:len(get('/v1/devices','ADS_CLIENT_TOKEN'))==1,'one disabled')
live.sendall(b'after');assert live.recv(5)==b'after','editing one device interrupted another'
cli(['devices','enable','managed-one']);wait_until(active,'re-enable')
cli(['devices','remove','managed-one'],remote=True);wait_until(lambda:len(cli(['devices','list']))==1,'remove')
print('PASS: enable/disable/remove only affects its own device and active data stream',flush=True)
before=cli(['status'])
assert before['supervised']
cli(['restart'],remote=True)
def restarted():
try:return cli(['status'])['instance']!=before['instance']
except AssertionError:return False
wait_until(restarted,'supervised child restart',seconds=30)
wait_until(lambda:any(r['online'] and r['status']['pid']!=before['pid'] and r['status']['pid']>0 for r in get('/v3/agents')),'manager reconnection',seconds=30)
assert len(cli(['devices','list']))==1,'restart lost config'
logs=cli(['logs'],remote=True);assert isinstance(logs['entries'],list)
for value in (current,logs,cli(['status'],remote=True)):
text=json.dumps(value)
assert not any(token in text for token in tokens.values()),'token leaked in management response'
for p,_ in clients:stop(p)
child_pid=cli(['status'])['pid']
stop(processes[1])
if os.name=='nt':
import ctypes
PROCESS_QUERY_LIMITED_INFORMATION=0x1000
def child_gone():
handle=ctypes.windll.kernel32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION,False,child_pid)
if not handle:return True
code=ctypes.c_ulong();ctypes.windll.kernel32.GetExitCodeProcess(handle,ctypes.byref(code));ctypes.windll.kernel32.CloseHandle(handle);return code.value!=259
else:
def child_gone():
try:os.kill(child_pid,0);return False
except ProcessLookupError:return True
wait_until(child_gone,'child cleanup after terminating supervisor')
print('PASS: supervisor-owned restart, persistent config, reconnect and secret-free logs/status',flush=True)
finally:
for p in reversed(processes):stop(p)
for h in handles:h.close()
phone.shutdown()
if __name__=='__main__':main()