Move mesh networking logic into the SDK and fix lifecycle bugs

SDK:
- Add build_config/migrate_config, mesh_cidrs, route_generation, health
  and start_bridged; expose abi_info (capability revision 2).
- Add wait_routes long-poll; stop wakes waiters, and context_free now
  stops the network immediately instead of waiting for waiters to time out.

Hosts:
- Dart: waitRoutes(), MeshProxySession route watcher, ABI capability check.
- Android: fix a deadlock where every VPN request waited on its own
  single-thread worker; requests are now async, status is served from a
  snapshot, and combined mode reports Partial when the mesh stops.
- macOS helper: mesh-only unified mode stops when the mesh is lost;
  installed_subnet_routes excludes the overlay.
- Lab: restore Partial sessions, write migrated profiles back, remove the
  unreachable TOML import dialog; native test now connects via the form.

Docs updated accordingly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-15 18:17:42 +09:00
co-authored by Claude Opus 5.5
parent 29d236f3fe
commit dc1bfc99d2
34 changed files with 1724 additions and 715 deletions
@@ -1,86 +0,0 @@
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
/// The dialog owns its controller until the route has actually been removed.
class ConfigImportDialog extends StatefulWidget {
const ConfigImportDialog({super.key});
@override
State<ConfigImportDialog> createState() => _ConfigImportDialogState();
}
class _ConfigImportDialogState extends State<ConfigImportDialog> {
final editor = TextEditingController();
@override
void dispose() {
editor.dispose();
super.dispose();
}
String error = '';
Future<void> read(String method) async {
try {
final value = await const MethodChannel(
'meshport/system_vpn',
).invokeMethod<String>(method);
if (value != null && mounted) {
setState(() {
editor.text = value;
error = '';
});
}
} catch (_) {
if (mounted) setState(() => error = '导入失败,请检查权限或文件格式');
}
}
@override
Widget build(BuildContext context) => AlertDialog(
title: const Text('导入 TOML'),
content: SizedBox(
width: 560,
child: Column(
mainAxisSize: MainAxisSize.min,
children: [
Wrap(
spacing: 8,
children: [
TextButton(
onPressed: () => read('import_file'),
child: const Text('文件'),
),
TextButton(
onPressed: () => read('scan_qr'),
child: const Text('扫码'),
),
TextButton(
onPressed: () => read('import_qr_image'),
child: const Text('二维码图片'),
),
],
),
if (error.isNotEmpty) Text(error),
Flexible(
child: TextField(
controller: editor,
maxLines: 12,
autofocus: true,
decoration: const InputDecoration(
hintText: '粘贴完整配置。不支持的配置将拒绝导入。',
),
),
),
],
),
),
actions: [
TextButton(
onPressed: () => Navigator.pop(context),
child: const Text('取消'),
),
FilledButton(
onPressed: () => Navigator.pop(context, editor.text),
child: const Text('校验并连接'),
),
],
);
}
@@ -54,11 +54,9 @@ class NodeDetailBody extends StatelessWidget {
});
@override
Widget build(BuildContext context) {
final direct =
peer?['direct'] == true &&
(node['next_hop_peer_id'] == null ||
node['next_hop_peer_id'] == node['peer_id']);
final measured = direct ? (peer?['latency_ms']) : null;
// Path and latency source come classified from the SDK `nodes` projection.
final direct = node['path'] == 'direct';
final latency = node['latency_ms'];
return Column(
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
@@ -75,14 +73,12 @@ class NodeDetailBody extends StatelessWidget {
ListTile(
title: const Text('直连能力'),
subtitle: Text(
'${peer?['direct'] == true ? '有直连可用' : '未发现直连'} · ${peer?['hole_punched'] == true ? '打洞建立' : '未确认打洞'}',
'${node['direct_available'] == true ? '有直连可用' : '未发现直连'} · ${peer?['hole_punched'] == true ? '打洞建立' : '未确认打洞'}',
),
),
ListTile(
title: Text(measured != null ? '链路 RTT' : '路由估算'),
subtitle: Text(
'${measured ?? node['estimated_latency_ms'] ?? '未测得'}${measured != null || node['estimated_latency_ms'] != null ? ' ms' : ''}',
),
title: Text(node['latency_source'] == 'link_rtt' ? '链路 RTT' : '路由估算'),
subtitle: Text(latency == null ? '未测得' : '$latency ms'),
),
ListTile(
title: const Text('虚拟地址 / NAT'),
+62 -67
View File
@@ -6,7 +6,6 @@ import 'package:flutter/services.dart';
import 'package:meshport_flutter/meshport_flutter.dart';
import 'package:meshport_client_core/meshport_client_core.dart';
import 'package:singbox_flutter/singbox_flutter.dart';
import 'config_import_dialog.dart';
import 'network_telemetry.dart';
import 'proxy_panel.dart';
import 'configuration_pages.dart';
@@ -107,10 +106,15 @@ class _LabScreenState extends State<LabScreen> {
Future<void> initialize() async {
try {
log('客户端启动 · ${Platform.operatingSystem} · 代理诊断日志已开启');
const path = String.fromEnvironment('MESHPORT_LIBRARY');
// A --dart-define wins; the process environment serves `flutter test`
// and development runs. Release builds use the bundled library.
const defined = String.fromEnvironment('MESHPORT_LIBRARY');
final path = defined.isNotEmpty
? defined
: Platform.environment['MESHPORT_LIBRARY'];
final opened = await diagnosticStage(
'加载 MeshPort 动态库',
() => MeshPortClient.open(libraryPath: path.isEmpty ? null : path),
() => MeshPortClient.open(libraryPath: path),
);
if (!mounted) {
await opened.close();
@@ -139,9 +143,7 @@ class _LabScreenState extends State<LabScreen> {
bool restored = false;
if (profileSupported) {
try {
final stored = (await vpnChannel.invokeMethod<String>(
'load_profile',
))?.replaceAll(RegExp(r'^subnet_routes\s*=.*$', multiLine: true), '');
final stored = await loadMigratedProfile();
if (stored != null) {
await loadForm(stored);
restored = true;
@@ -197,7 +199,8 @@ class _LabScreenState extends State<LabScreen> {
if (Platform.isAndroid) {
final snapshot = await androidVpnRequest({'op': 'status'});
final data = snapshot['data'] as Map?;
if (data?['state'] == 'Running') {
// Partial: a combined VPN whose mesh stopped still carries the proxy.
if (data?['state'] == 'Running' || data?['state'] == 'Partial') {
systemClient = client = MeshPortClient.fromTransport(
request: androidVpnRequest,
close: () async {
@@ -227,7 +230,7 @@ class _LabScreenState extends State<LabScreen> {
(singBoxEnabled && proxyProfile.feature == 'proxy'))) {
log('按已保存配置自动连接');
await perform((_) async {
await startConfig(buildFormConfig());
await startConfig(await startableFormConfig());
runningProxyMode = proxyProfile.modeLabel;
runningProxyLabel =
proxyProfile.nodes
@@ -393,8 +396,8 @@ class _LabScreenState extends State<LabScreen> {
}
}
String buildConfig() {
final form = buildFormConfig();
Future<String> buildConfig() async {
final form = await buildFormConfig();
return loadedForm == form && loadedConfig != null ? loadedConfig! : form;
}
@@ -421,9 +424,13 @@ class _LabScreenState extends State<LabScreen> {
routeMode = optimization['mode'] as String;
preferUdp = optimization['prefer_udp'] == true;
relayIds.text = (optimization['relay_peer_ids'] as List).join(',');
loadedConfig = config;
loadedForm = buildFormConfig();
});
// Rendered from the fields just loaded, so an untouched form maps back
// to the original text (and keeps options the form cannot show).
final form = await buildFormConfig();
if (!mounted) return;
loadedConfig = config;
loadedForm = form;
}
Map<String, dynamic> networkValues() => {
@@ -455,7 +462,39 @@ class _LabScreenState extends State<LabScreen> {
.toList(),
},
};
String buildFormConfig() => NetworkProfile(networkValues()).toToml();
Future<String> buildFormConfig() =>
NetworkProfile(networkValues()).toToml(applicationClient!);
/// Application-mode internet-only proxying never starts the mesh, so an
/// incomplete network form must not block it.
Future<String> startableFormConfig() async =>
runtimeMode == 'application' &&
singBoxEnabled &&
proxyProfile.feature == 'proxy'
? ''
: await buildFormConfig();
/// Drops options earlier releases saved; the SDK owns the migration rules.
Future<String?> migratedProfile(String? stored) async =>
stored == null ? null : await applicationClient!.migrateConfig(stored);
/// Loads the saved network profile and, when the SDK migrates it, writes
/// the migrated text back so the legacy form is not reloaded next launch.
Future<String?> loadMigratedProfile() async {
final stored = await vpnChannel.invokeMethod<String>('load_profile');
final migrated = await migratedProfile(stored);
if (migrated != null && migrated != stored) {
try {
await applicationClient!.validate(migrated);
await vpnChannel.invokeMethod<void>('save_profile', migrated);
log('已移除旧版配置项并保存迁移后的网络配置');
} catch (_) {
log('旧版配置已在内存中迁移,但未能写回 $profileStorage');
}
}
return migrated;
}
Future<void> saveNetworkValues(Map<String, dynamic> values) async {
final incoming = NetworkProfile(values).values;
final policy = incoming['optimization'] as Map;
@@ -463,7 +502,7 @@ class _LabScreenState extends State<LabScreen> {
.map((v) => v is int ? v : int.parse('$v'))
.toList();
if (incoming['runtime_mode'] != 'application') incoming['dhcp'] = false;
final toml = NetworkProfile(incoming).toToml();
final toml = await NetworkProfile(incoming).toToml(applicationClient!);
await applicationClient!.request({'op': 'validate', 'toml': toml});
await saveProfile(toml, explicit: true);
await loadForm(toml);
@@ -497,7 +536,7 @@ class _LabScreenState extends State<LabScreen> {
}
Future<void> connect(MeshPortClient c) async {
final config = buildConfig();
final config = await buildConfig();
await startConfig(config);
proxyProfile.entry = runtimeMode;
proxyProfile.proxyEnabled = singBoxEnabled;
@@ -633,9 +672,7 @@ class _LabScreenState extends State<LabScreen> {
Future<void> migrateLegacyProfiles() async {
await vpnChannel.invokeMethod<void>('migrate_profiles');
final proxy = await vpnChannel.invokeMethod<String>('load_proxy_profile');
final network = (await vpnChannel.invokeMethod<String>(
'load_profile',
))?.replaceAll(RegExp(r'^subnet_routes\s*=.*$', multiLine: true), '');
final network = await loadMigratedProfile();
if (network != null) await loadForm(network);
if (proxy != null) {
final imported = ProxyProfile.fromJson(
@@ -1227,22 +1264,7 @@ class _LabScreenState extends State<LabScreen> {
NodeTelemetry(
status: status,
onNode: (node, peer) => openDetail('节点详情', () {
final id = node['peer_id'];
final routes = (status['routes'] as List? ?? []).where(
(v) => v['peer_id'] == id,
);
final peers = (status['peers'] as List? ?? []).where(
(v) => v['peer_id'] == id,
);
return NodeDetailBody(
node: routes.isEmpty
? {'peer_id': id, 'hostname': node['hostname']}
: Map<String, dynamic>.from(routes.first),
peer: peers.isEmpty
? null
: Map<String, dynamic>.from(peers.first),
status: status,
);
return NodeDetailBody(node: node, peer: peer, status: status);
}),
),
]),
@@ -1356,8 +1378,9 @@ class _LabScreenState extends State<LabScreen> {
FilledButton.icon(
onPressed: busy || client == null
? null
: () =>
perform((_) => saveProfile(buildConfig(), explicit: true)),
: () => perform(
(_) async => saveProfile(await buildConfig(), explicit: true),
),
icon: const Icon(Icons.save_outlined),
label: const Text('保存配置'),
),
@@ -1606,18 +1629,13 @@ class _LabScreenState extends State<LabScreen> {
await proxySaveTail;
proxyProfile.entry = runtimeMode;
if (profileSupported) await saveProxyProfile();
final nextConfig = buildFormConfig();
if (proxyProfile.feature != 'proxy') {
await applicationClient!.request({
'op': 'validate',
'toml': nextConfig,
});
}
// build_config validates, so a bad form fails before stopping anything.
if (proxyProfile.feature != 'proxy') await buildFormConfig();
if (running) await stopActive(c);
singBoxEnabled =
runtimeMode == 'unified_vpn' ||
(runtimeMode == 'application' && proxyProfile.feature != 'mesh');
await startConfig(buildFormConfig());
await startConfig(await startableFormConfig());
runningProxyLabel =
proxyProfile.nodes
.where((n) => n.id == proxyProfile.selectedId)
@@ -1655,29 +1673,6 @@ class _LabScreenState extends State<LabScreen> {
LogsPageBody(logs: logs, onClear: () => setState(() => logs.clear())),
),
);
Future<void> importConfig() async {
final text = await showDialog<String>(
context: context,
builder: (_) => const ConfigImportDialog(),
);
if (text != null && mounted) {
await perform((c) async {
await loadForm(text);
proxyProfile.feature = 'mesh';
proxyProfile.entry = runtimeMode;
proxyProfile.proxyEnabled = false;
singBoxEnabled = false;
await startConfig(text);
try {
await saveProxyProfile();
} catch (_) {
log('组网已连接,但连接方式未能保存,请重试保存');
}
log('导入配置并启动引擎');
});
}
}
@override
Widget build(BuildContext context) {
final pages = [overview, proxyPage, nodes, settings];
@@ -23,15 +23,12 @@ class NodeTelemetry extends StatelessWidget {
for (final peer in status['peers'] as List? ?? [])
peer['peer_id']: Map<String, dynamic>.from(peer),
};
final nodes = <dynamic, Map<String, dynamic>>{
for (final route in status['routes'] as List? ?? [])
route['peer_id']: Map<String, dynamic>.from(route),
};
for (final id in peers.keys) {
nodes.putIfAbsent(id, () => {'peer_id': id});
}
// The SDK merges routes and links and classifies path and latency source.
final nodes = [
for (final node in status['nodes'] as List? ?? [])
Map<String, dynamic>.from(node as Map),
];
final local = status['local_peer'] as Map?;
if (local != null) nodes.remove(local['peer_id']);
if (nodes.isEmpty && local == null) {
return const Text('尚未发现节点,连接后显示链路延迟与流量。');
}
@@ -77,17 +74,15 @@ class NodeTelemetry extends StatelessWidget {
),
if (local != null && nodes.isNotEmpty) const Divider(),
if (local != null && nodes.isEmpty) const Text('尚未发现其他节点。'),
...nodes.values.map((node) {
...nodes.map((node) {
final peer = peers[node['peer_id']];
final directAvailable = peer?['direct'] == true;
final direct =
directAvailable &&
(node['next_hop_peer_id'] == null ||
node['next_hop_peer_id'] == node['peer_id']);
final measured = direct ? (peer?['latency_ms'] as num?) : null;
final estimated = node['estimated_latency_ms'] as num?;
final latency = measured ?? estimated;
final latencyLabel = measured != null ? '链路 RTT' : '路由估算';
final directAvailable = node['direct_available'] == true;
final direct = node['path'] == 'direct';
final metered = node['metered'] == true;
final latency = node['latency_ms'] as num?;
final latencyLabel = node['latency_source'] == 'link_rtt'
? '链路 RTT'
: '路由估算';
return InkWell(
onTap: onNode == null ? null : () => onNode!(node, peer),
child: Padding(
@@ -122,7 +117,7 @@ class NodeTelemetry extends StatelessWidget {
),
const SizedBox(height: 6),
Text(
'${node['ipv4'] ?? '无虚拟地址'} · ${direct ? '直连' : '中继'}${direct && peer?['hole_punched'] == true ? ' · 打洞建立' : ''}${!direct && directAvailable ? ' · 有直连可用' : ''}${latency == null ? '' : ' · $latencyLabel'}',
'${node['ipv4'] ?? '无虚拟地址'} · ${direct ? '直连' : '中继'}${node['hole_punched'] == true ? ' · 打洞建立' : ''}${!direct && directAvailable ? ' · 有直连可用' : ''}${latency == null ? '' : ' · $latencyLabel'}',
),
if (node['udp_nat_type'] != null)
Text(
@@ -134,13 +129,13 @@ class NodeTelemetry extends StatelessWidget {
),
const SizedBox(height: 6),
Text(
peer == null
!metered
? '流量经下一跳 ${node['next_hop_peer_id'] ?? '—'},未单独计量'
: '↓ ${formatBytes(peer['rx_bytes_per_second'] as num?, rate: true)} ↑ ${formatBytes(peer['tx_bytes_per_second'] as num?, rate: true)}',
: '↓ ${formatBytes(node['rx_bytes_per_second'] as num?, rate: true)} ↑ ${formatBytes(node['tx_bytes_per_second'] as num?, rate: true)}',
),
if (peer != null)
if (metered)
Text(
'当前链路累计 ↓ ${formatBytes(peer['rx_bytes'] as num?)} ↑ ${formatBytes(peer['tx_bytes'] as num?)}',
'当前链路累计 ↓ ${formatBytes(node['rx_bytes'] as num?)} ↑ ${formatBytes(node['tx_bytes'] as num?)}',
style: Theme.of(context).textTheme.bodySmall,
),
],