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

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