build: prepare Flutter management center for agent integration

This commit is contained in:
tongtong committed 2026-11-12 19:09:18 +08:00
1 parent 05d4d5fea6
commit e91fa0235c
34 files changed
+3481

No files matched your search

+110
View File
@@ -0,0 +1,110 @@
import 'dart:async';
import 'package:flutter/foundation.dart';
import '../data/manager_repository.dart';
class ManagerModel extends ChangeNotifier {
late final ManagerRepository repository;
List<Device> devices = [];
List<Map<String, dynamic>> nodes = [];
final List<String> logs = [];
final Set<String> pending = {};
String notice = '正在初始化', adbListing = '';
bool refreshing = false, closing = false, polling = false;
Timer? timer;
int ticks = 0;
ManagerModel() {
repository = ManagerRepository(log);
}
void log(String text) {
logs.insert(0, '${DateTime.now().toString().substring(11, 19)} $text');
if (logs.length > 500) {
logs.removeLast();
}
notifyListeners();
}
Future<void> action(Future<void> Function() operation) async {
try {
await operation();
} catch (e) {
notice = e.toString();
log(notice);
}
notifyListeners();
}
Future<void> init() async {
await action(() async {
await repository.init();
notice = '准备就绪';
});
await refresh();
timer = Timer.periodic(const Duration(seconds: 3), (_) async {
if (closing || refreshing || polling) {
return;
}
polling = true;
try {
await action(repository.monitor);
} finally {
polling = false;
}
if (++ticks % 4 == 0) {
await refresh();
}
});
}
Future<void> refresh() async {
if (refreshing || closing) {
return;
}
refreshing = true;
notifyListeners();
await action(() async {
devices = await repository.devices();
final response = await repository.get('v2/nodes') as Map<String, dynamic>;
nodes = (response['nodes'] as List<dynamic>).cast<Map<String, dynamic>>();
notice =
'已同步 ${devices.length} 台设备 · ${DateTime.now().toString().substring(11, 19)}';
});
refreshing = false;
notifyListeners();
}
Future<void> deviceAction(String id, Future<void> Function() fn) async {
if (closing || !pending.add(id)) {
return;
}
notifyListeners();
try {
await action(fn);
} finally {
pending.remove(id);
notifyListeners();
}
}
Future<void> connect(Device d) => deviceAction(d.id, () async {
await repository.connect(d.id);
log('已启动 ${d.id} 的连接');
});
Future<void> disconnect(String id) =>
deviceAction(id, () => repository.disconnect(id));
Future<void> localAdb() => action(() async {
adbListing = await repository.run(repository.settings.adb, [
'devices',
'-l',
]);
});
Future<void> shutdown() async {
closing = true;
timer?.cancel();
while (pending.isNotEmpty) {
await Future<void>.delayed(const Duration(milliseconds: 50));
}
await repository.shutdown();
}
}
+628
View File
@@ -0,0 +1,628 @@
import 'package:material_ui/material_ui.dart';
import 'package:flutter/services.dart';
import '../data/manager_repository.dart';
import 'manager_model.dart';
class ManagerView extends StatefulWidget {
final ManagerModel model;
final Future<void> Function() onQuit;
const ManagerView({super.key, required this.model, required this.onQuit});
@override
State<ManagerView> createState() => _ManagerViewState();
}
class _ManagerViewState extends State<ManagerView> {
int page = 0;
String search = '';
ManagerModel get m => widget.model;
@override
Widget build(BuildContext context) => ListenableBuilder(
listenable: m,
builder: (context, _) {
return Scaffold(
body: Row(
children: [
SizedBox(
width: 204,
child: Material(
color: const Color(0xFF14233F),
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Padding(
padding: EdgeInsets.fromLTRB(24, 30, 24, 8),
child: Text(
'ADS',
style: TextStyle(
color: Colors.white,
fontSize: 32,
fontWeight: FontWeight.w800,
),
),
),
const Padding(
padding: EdgeInsets.fromLTRB(24, 0, 16, 36),
child: Text(
'设备管理中心 / Flutter',
style: TextStyle(color: Colors.white60, fontSize: 12),
),
),
for (final (i, title, icon) in [
(0, '设备工作台', Icons.devices_rounded),
(1, '中继节点', Icons.hub_outlined),
(2, '本机 ADB', Icons.terminal_rounded),
(3, '连接配置', Icons.tune_rounded),
(4, '运行日志', Icons.receipt_long_outlined),
])
Padding(
padding: const EdgeInsets.symmetric(
horizontal: 12,
vertical: 4,
),
child: ListTile(
selected: page == i,
selectedTileColor: const Color(0xFF29446C),
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(10),
),
leading: Icon(icon, color: Colors.white70, size: 21),
title: Text(
title,
style: const TextStyle(
color: Colors.white,
fontSize: 14,
),
),
onTap: () => setState(() => page = i),
),
),
const Spacer(),
const Padding(
padding: EdgeInsets.all(20),
child: Text(
'Windows · 网络 ADB\n关闭窗口后保留在托盘',
style: TextStyle(
color: Colors.white54,
height: 1.8,
fontSize: 12,
),
),
),
TextButton.icon(
onPressed: widget.onQuit,
icon: const Icon(Icons.logout, size: 16),
label: const Text('退出管理中心'),
),
const SizedBox(height: 16),
],
),
),
),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
Container(
color: Colors.white,
padding: const EdgeInsets.symmetric(
horizontal: 28,
vertical: 20,
),
child: Row(
children: [
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
[
'设备工作台',
'中继节点',
'本机 ADB',
'连接配置',
'运行日志',
][page],
style: const TextStyle(
fontSize: 24,
fontWeight: FontWeight.w700,
),
),
const SizedBox(height: 5),
Text(
m.notice,
maxLines: 2,
overflow: TextOverflow.ellipsis,
style: const TextStyle(
color: Color(0xFF66758D),
fontSize: 12,
),
),
],
),
),
const SizedBox(width: 12),
OutlinedButton.icon(
onPressed: m.refreshing ? null : m.refresh,
icon: const Icon(Icons.refresh, size: 18),
label: Text(m.refreshing ? '同步中' : '刷新'),
),
],
),
),
if (m.refreshing) const LinearProgressIndicator(minHeight: 2),
Expanded(
child: Padding(
padding: const EdgeInsets.all(24),
child: switch (page) {
0 => devices(),
1 => nodes(),
2 => adb(),
3 => SettingsView(model: m),
_ => logs(),
},
),
),
],
),
),
],
),
);
},
);
Widget stat(String label, String value, IconData icon) => Expanded(
child: Card(
child: Padding(
padding: const EdgeInsets.all(20),
child: Row(
children: [
Icon(icon, color: const Color(0xFF305DDB), size: 26),
const SizedBox(width: 16),
Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
value,
style: const TextStyle(
fontSize: 25,
fontWeight: FontWeight.bold,
),
),
Text(
label,
style: const TextStyle(color: Colors.blueGrey, fontSize: 12),
),
],
),
],
),
),
),
);
Widget devices() {
final all = <String, Device>{for (final d in m.devices) d.id: d};
for (final id in m.repository.sessions.keys) {
all.putIfAbsent(id, () => Device(id, false));
}
final rows = all.values
.where((d) => d.id.toLowerCase().contains(search.toLowerCase()))
.toList();
return Column(
children: [
Row(
children: [
stat('网关在线设备', '${m.devices.length}', Icons.phone_android),
const SizedBox(width: 16),
stat('本机连接', '${m.repository.sessions.length}', Icons.link),
const SizedBox(width: 16),
stat(
'ADB 已就绪',
'${m.repository.sessions.values.where((s) => s.ready).length}',
Icons.check_circle_outline,
),
],
),
const SizedBox(height: 20),
Row(
children: [
Expanded(
child: TextField(
onChanged: (v) => setState(() => search = v),
decoration: const InputDecoration(
hintText: '搜索设备 ID',
prefixIcon: Icon(Icons.search),
filled: true,
fillColor: Colors.white,
),
),
),
const SizedBox(width: 16),
OutlinedButton(
onPressed: m.repository.sessions.isEmpty
? null
: () => m.action(() async {
for (final id in m.repository.sessions.keys.toList()) {
await m.disconnect(id);
}
}),
child: const Text('断开全部'),
),
],
),
const SizedBox(height: 16),
Expanded(
child: rows.isEmpty
? Center(
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
const Icon(
Icons.devices_other,
size: 52,
color: Colors.blueGrey,
),
const SizedBox(height: 16),
const Text('暂无设备'),
TextButton(
onPressed: () => setState(() => page = 3),
child: const Text('检查服务地址与客户端凭据'),
),
],
),
)
: ListView.separated(
itemCount: rows.length,
separatorBuilder: (_, index) => const SizedBox(height: 12),
itemBuilder: (context, i) => deviceCard(rows[i]),
),
),
],
);
}
Widget deviceCard(Device d) {
final s = m.repository.sessions[d.id];
final pending = m.pending.contains(d.id);
return Card(
child: Padding(
padding: const EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Row(
children: [
Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: const Color(0xFFEDF2FF),
borderRadius: BorderRadius.circular(12),
),
child: const Icon(
Icons.phone_android,
color: Color(0xFF305DDB),
),
),
const SizedBox(width: 16),
Expanded(
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Text(
d.id,
style: const TextStyle(
fontWeight: FontWeight.w700,
fontSize: 17,
),
),
const SizedBox(height: 5),
Text(
s?.state ?? (d.busy ? '其他客户端占用' : '空闲 · 可连接'),
style: TextStyle(
color: s?.ready == true
? Colors.teal
: Colors.blueGrey,
fontSize: 12,
),
),
],
),
),
if (pending)
const SizedBox(
width: 20,
height: 20,
child: CircularProgressIndicator(strokeWidth: 2),
),
const SizedBox(width: 12),
if (s == null)
FilledButton(
onPressed: pending || d.busy ? null : () => m.connect(d),
child: const Text('连接设备'),
)
else
Wrap(
spacing: 8,
children: [
FilledButton.icon(
onPressed: pending || !s.ready || s.screen != null
? null
: () => m.deviceAction(
d.id,
() => m.repository.screen(s),
),
icon: const Icon(Icons.open_in_new, size: 16),
label: Text(s.screen == null ? '打开 scrcpy' : '投屏运行中'),
),
OutlinedButton(
onPressed: pending ? null : () => m.disconnect(d.id),
child: const Text('断开'),
),
],
),
],
),
if (s != null) ...[
const Divider(height: 28),
Row(
children: [
Expanded(
child: Text(
'网络 ADB ${s.endpoint} · ${s.route}',
style: const TextStyle(fontSize: 12),
),
),
IconButton(
tooltip: '复制 ADB 地址',
onPressed: () =>
Clipboard.setData(ClipboardData(text: s.endpoint)),
icon: const Icon(Icons.copy, size: 16),
),
],
),
],
],
),
),
);
}
Widget nodes() => m.nodes.isEmpty
? const Center(child: Text('暂无中继节点,或服务尚未启用 v2 节点接口'))
: ListView.separated(
itemCount: m.nodes.length,
separatorBuilder: (_, index) => const SizedBox(height: 12),
itemBuilder: (_, i) {
final n = m.nodes[i];
return Card(
child: ListTile(
contentPadding: const EdgeInsets.all(20),
leading: Icon(
Icons.hub,
color: n['healthy'] == true ? Colors.teal : Colors.grey,
),
title: Text('${n["id"]}'),
subtitle: Text(n['healthy'] == true ? '在线' : '不可用'),
trailing: Text('通道 ${n["sessions"]} / ${n["capacity"]}'),
),
);
},
);
Widget adb() => Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
const Text(
'使用本机 ADB Server,显示本地 USB 设备和网络设备。',
style: TextStyle(color: Colors.blueGrey),
),
const SizedBox(height: 16),
Wrap(
spacing: 12,
children: [
FilledButton.icon(
onPressed: m.localAdb,
icon: const Icon(Icons.refresh),
label: const Text('读取设备列表'),
),
OutlinedButton(
onPressed: () => m.action(() async {
final result = await m.repository.run(m.repository.settings.adb, [
'start-server',
]);
m.log(result.isEmpty ? 'ADB Server 已启动' : result);
await m.localAdb();
}),
child: const Text('启动 ADB Server'),
),
],
),
const SizedBox(height: 20),
Expanded(
child: Container(
width: double.infinity,
padding: const EdgeInsets.all(20),
decoration: BoxDecoration(
color: const Color(0xFF14233F),
borderRadius: BorderRadius.circular(12),
),
child: SingleChildScrollView(
child: SelectableText(
m.adbListing.isEmpty ? '点击“读取设备列表”检查本机设备。' : m.adbListing,
style: const TextStyle(
color: Colors.white,
fontFamily: 'Consolas',
height: 1.8,
),
),
),
),
),
],
);
Widget logs() => Column(
children: [
Row(
children: [
const Text('最近 500 条 · 仅保存在内存'),
const Spacer(),
TextButton(
onPressed: () =>
Clipboard.setData(ClipboardData(text: m.logs.join('\n'))),
child: const Text('复制日志'),
),
],
),
Expanded(
child: ListView.builder(
itemCount: m.logs.length,
itemBuilder: (_, i) => Padding(
padding: const EdgeInsets.symmetric(vertical: 5),
child: SelectableText(
m.logs[i],
style: const TextStyle(fontSize: 12),
),
),
),
),
],
);
}
class SettingsView extends StatefulWidget {
final ManagerModel model;
const SettingsView({super.key, required this.model});
@override
State<SettingsView> createState() => _SettingsViewState();
}
class _SettingsViewState extends State<SettingsView> {
late final Map<String, TextEditingController> fields;
bool relayOnly = false;
@override
void initState() {
super.initState();
final s = widget.model.repository.settings;
fields = {
for (final entry in {
'server': s.server,
'origin': s.origin,
'credential': s.credential,
'client': s.client,
'adb': s.adb,
'scrcpy': s.scrcpy,
}.entries)
entry.key: TextEditingController(text: entry.value),
};
relayOnly = s.relayOnly;
}
void apply() {
final s = widget.model.repository.settings;
s.server = fields['server']!.text.trim();
s.origin = fields['origin']!.text.trim();
s.credential = fields['credential']!.text.trim();
s.client = fields['client']!.text.trim();
s.adb = fields['adb']!.text.trim();
s.scrcpy = fields['scrcpy']!.text.trim();
s.relayOnly = relayOnly;
}
@override
void dispose() {
for (final c in fields.values) {
c.dispose();
}
super.dispose();
}
@override
Widget build(BuildContext context) => ListView(
children: [
Card(
child: Padding(
padding: const EdgeInsets.all(24),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
const Text(
'控制中心与工具',
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
const SizedBox(height: 8),
const Text(
'修改后点击保存;已连接设备继续使用连接时的配置。令牌仅保存在内存。',
style: TextStyle(color: Colors.blueGrey, fontSize: 12),
),
const SizedBox(height: 24),
for (final (key, label) in [
('server', '控制中心 WSS 地址'),
('origin', '直连服务器(可留空)'),
('credential', '客户端凭据文件 client.env'),
('client', 'ads-client.exe 路径'),
('adb', 'adb.exe 路径'),
('scrcpy', 'scrcpy.exe 路径(需保留完整发行目录)'),
])
Padding(
padding: const EdgeInsets.only(bottom: 18),
child: TextField(
controller: fields[key],
decoration: InputDecoration(labelText: label),
),
),
SwitchListTile(
contentPadding: EdgeInsets.zero,
value: relayOnly,
title: const Text('仅使用中继'),
subtitle: const Text('关闭时优先尝试 P2P 直连'),
onChanged: (v) => setState(() => relayOnly = v),
),
const SizedBox(height: 16),
Wrap(
spacing: 12,
runSpacing: 12,
children: [
FilledButton(
onPressed: () => widget.model.action(() async {
apply();
widget.model.repository.settings.uri('v1/devices');
await widget.model.repository.save();
widget.model.notice = '配置已保存';
}),
child: const Text('保存配置'),
),
OutlinedButton(
onPressed: () => widget.model.action(() async {
apply();
await widget.model.repository.importCredential();
fields['origin']!.text =
widget.model.repository.settings.origin;
widget.model.notice = '客户端凭据已导入';
await widget.model.refresh();
}),
child: const Text('导入凭据并同步'),
),
OutlinedButton(
onPressed: () => widget.model.action(() async {
apply();
for (final (exe, args) in [
(fields['client']!.text, ['--version']),
(fields['adb']!.text, ['version']),
(fields['scrcpy']!.text, ['--version']),
]) {
widget.model.log(
await widget.model.repository.run(exe, args),
);
}
widget.model.notice = '工具检查完成';
}),
child: const Text('检查工具'),
),
],
),
],
),
),
),
],
);
}