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