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

+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();
});
}
}