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

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