feat: improve desktop path selection and USB connection recovery

This commit is contained in:
tongtong committed 2026-11-13 03:14:00 +08:00
1 parent 5aa575f182
commit 6490665af8
28 files changed
+846 -51

No files matched your search

+162 -22
View File
@@ -5,11 +5,13 @@ import 'dart:io';
import 'package:path/path.dart' as p;
import 'windows_usb.dart';
import 'usb_recovery.dart';
class Settings {
String server = 'wss://ttstd.com/ads';
String origin = '175.178.213.60:443';
String credential = '';
Map<String, String> agentPaths = {};
String client = '', adb = '', scrcpy = '';
bool relayOnly = false, usbMode = false;
String usbip = UsbDriver.defaultUsbip();
@@ -17,6 +19,7 @@ class Settings {
'server': server,
'origin': origin,
'credential': credential,
'agentPaths': agentPaths,
'client': client,
'adb': adb,
'scrcpy': scrcpy,
@@ -28,6 +31,7 @@ class Settings {
server = j['server'] as String? ?? server;
origin = j['origin'] as String? ?? origin;
credential = j['credential'] as String? ?? credential;
agentPaths = Map<String, String>.from(j['agentPaths'] as Map? ?? {});
client = j['client'] as String? ?? client;
adb = j['adb'] as String? ?? adb;
scrcpy = j['scrcpy'] as String? ?? scrcpy;
@@ -64,7 +68,16 @@ class Session {
WindowsUsbSession? usb;
String get endpoint => usb?.serial ?? tunnel;
String get mode => usb == null ? "网络 ADB" : "虚拟 USB";
final Process process;
Process process;
Future<Process> Function()? restartClient;
final recovery = UsbRecoveryPolicy();
String usbip = '', usbExecutable = '';
bool recovering = false,
initialized = false,
screenWanted = false,
usbBroken = false;
Future<void>? recoveryTask;
bool screenPageVisible = false;
Process? screen;
bool screenEmbedded = false;
String state = '连接中', route = '协商中';
@@ -77,6 +90,7 @@ class ManagerRepository {
final Map<String, Session> sessions = {};
final Set<int> reservedPorts = {};
final void Function(String) log;
bool allowEmbeddedResume = true;
String token = '';
Directory? root;
late Directory storage;
@@ -336,19 +350,24 @@ class ManagerRepository {
'transport-$id-${DateTime.now().microsecondsSinceEpoch}.json',
);
final lease = usbMode ? "$status.lease" : null;
final proc = await Process.start(
settings.client,
final clientExecutable = settings.client, adbExecutable = settings.adb;
final serverAddress = settings.server.trim(),
originAddress = settings.origin.trim();
final transportMode = settings.relayOnly ? 'relay' : 'auto';
final clientEnvironment = environment()..['ADS_CLIENT_TOKEN'] = token;
Future<Process> startClient() => Process.start(
clientExecutable,
[
'--server',
settings.server.trim(),
serverAddress,
'--device',
id,
'--listen',
endpoint,
'--adb',
settings.adb,
adbExecutable,
'--transport',
settings.relayOnly ? 'relay' : 'auto',
transportMode,
'--status-file',
status,
if (lease != null) ...[
@@ -356,26 +375,21 @@ class ManagerRepository {
'--lease-status-file',
lease,
],
if (settings.origin.trim().isNotEmpty) ...[
'--connect-address',
settings.origin.trim(),
],
if (originAddress.isNotEmpty) ...['--connect-address', originAddress],
],
environment: environment()..['ADS_CLIENT_TOKEN'] = token,
environment: clientEnvironment,
includeParentEnvironment: false,
);
final proc = await startClient();
watch(proc, id);
session = Session(id, endpoint, settings.adb, status, proc);
final current = session;
sessions[id] = current;
current.leaseFile = lease;
unawaited(
proc.exitCode.then((code) {
current.exited = true;
current.ready = false;
current.state = '连接程序已退出 ($code)';
}),
);
current.restartClient = startClient;
current.usbip = usbip;
current.usbExecutable = findTool('ads-usb');
observeClient(current, proc);
if (usbMode) {
final usb = WindowsUsbSession(id, usbPort!);
current.usb = usb;
@@ -392,6 +406,7 @@ class ManagerRepository {
);
log('USB 已挂载:${usb.serial}');
}
current.initialized = true;
return current;
} catch (_) {
if (session != null) {
@@ -442,11 +457,11 @@ class ManagerRepository {
Future<void> monitor() async {
final listings = <String, String>{};
for (final s in sessions.values.toList()) {
if (!s.stopping && (s.exited || s.usb?.exited == true)) {
if (s.usb == null && !s.stopping && s.exited) {
await disconnect(s.id);
continue;
}
if (s.stopping) {
if (s.stopping || s.recovering || !s.initialized) {
continue;
}
try {
@@ -458,6 +473,29 @@ class ManagerRepository {
.where((r) => r.length >= 2 && r[0] == s.endpoint)
.firstOrNull;
s.ready = row?[1] == 'device';
if (s.usb != null &&
s.recovery.due(
DateTime.now(),
ready: s.ready,
unauthorized: row?[1] == 'unauthorized',
broken: s.exited || s.usb!.exited || s.usbBroken,
)) {
scheduleUsbRecovery(s);
continue;
}
if (s.ready &&
s.screenWanted &&
(!s.screenEmbedded ||
(s.screenPageVisible && allowEmbeddedResume)) &&
s.screen == null &&
!DateTime.now().isBefore(s.recovery.retryAt)) {
s.recovery.attempted(DateTime.now());
try {
await screen(s, embedded: s.screenEmbedded);
} catch (e) {
log('[${s.id}] 恢复投屏失败:$e');
}
}
s.state = row == null ? '等待设备 / 自动重连' : row[1];
final file = File(s.statusFile);
if (await file.exists()) {
@@ -473,16 +511,107 @@ class ManagerRepository {
}
}
void observeClient(Session s, Process process) {
unawaited(
process.exitCode.then((code) {
if (s.process != process) {
return;
}
s.exited = true;
s.ready = false;
s.state = '连接程序已退出 ($code)';
}),
);
}
Future<void> stopScreen(Session s) async {
s.screenWanted = false;
final process = s.screen;
s.screen = null;
await stop(process);
log('[${s.id}] 用户停止投屏,取消自动恢复');
}
void scheduleUsbRecovery(Session s) {
if (s.stopping || s.recovering) {
return;
}
s.recovering = true;
s.ready = false;
s.recovery.attempted(DateTime.now());
s.state = 'USB 会话中断 · 正在重新挂载';
log('[${s.id}] USB 自动恢复,第 ${s.recovery.attempts} 次');
s.recoveryTask = recoverUsb(s).whenComplete(() => s.recovering = false);
}
Future<void> recoverUsb(Session s) async {
try {
final screen = s.screen;
s.screen = null;
await stop(screen);
final old = s.usb!;
await stop(old.bridge);
reservedPorts.remove(old.port);
if (s.stopping) {
return;
}
if (s.exited) {
final lease = File(s.leaseFile!);
if (await lease.exists()) {
await lease.delete();
}
s.process = await s.restartClient!();
s.exited = false;
watch(s.process, s.id);
observeClient(s, s.process);
}
if (s.stopping) {
return;
}
final port = await allocateUsbPort();
final usb = WindowsUsbSession(s.id, port);
s.usb = usb;
await usb.start(
leaseFile: s.leaseFile!,
upstream: s.tunnel,
executable: s.usbExecutable,
usbip: s.usbip,
environment: environment(),
run: run,
watch: watch,
cancelled: () => s.stopping || s.exited,
);
s.usbBroken = false;
s.recovery.missing = 0;
s.state = 'USB 已重新挂载 · 等待 ADB 就绪';
log('[${s.id}] USB 已重新挂载;设备就绪后恢复投屏');
} catch (e) {
// No unhandled async exception; monitor retries with bounded backoff.
try {
await stop(s.usb?.bridge);
} catch (_) {}
if (!s.stopping) {
s.state = 'USB 恢复失败 · 稍后重试';
log('[${s.id}] USB 恢复失败:$e');
}
}
}
Future<void> screen(Session s, {bool embedded = false}) async {
if (!s.ready) {
if (s.stopping) {
return;
}
s.screenWanted = true;
if (!s.ready || s.recovering || s.stopping) {
return;
}
if (s.screen != null) {
if (s.screenEmbedded == embedded) {
return;
}
await stop(s.screen);
final previous = s.screen;
s.screen = null;
await stop(previous);
}
final proc = await launchScreen(
s.endpoint,
@@ -490,6 +619,10 @@ class ManagerRepository {
s.id,
embedded: embedded,
);
if (s.stopping || !s.screenWanted) {
await stop(proc);
return;
}
s.screen = proc;
s.screenEmbedded = embedded;
watch(proc, 'scrcpy ${s.id}');
@@ -497,6 +630,11 @@ class ManagerRepository {
proc.exitCode.then((code) {
if (s.screen == proc) {
s.screen = null;
if (code == 0) {
s.screenWanted = false;
} else if (!s.stopping && code == 2 && s.usb != null) {
s.usbBroken = true;
}
}
log('投屏窗口关闭 ($code)');
}),
@@ -549,6 +687,8 @@ class ManagerRepository {
return;
}
s.stopping = true;
s.screenWanted = false;
await s.recoveryTask;
for (final proc in [s.screen, s.usb?.bridge, s.process]) {
try {
await stop(proc);
@@ -0,0 +1,34 @@
/// Poll-based hysteresis and bounded retry delay, independent of processes/UI.
class UsbRecoveryPolicy {
int missing = 0, attempts = 0, stable = 0;
DateTime retryAt = DateTime.fromMillisecondsSinceEpoch(0);
bool due(
DateTime now, {
required bool ready,
bool unauthorized = false,
bool broken = false,
}) {
if (unauthorized) {
missing = 0;
stable = 0;
return false;
}
if (ready && !broken) {
missing = 0;
if (++stable >= 10) {
attempts = 0;
}
return false;
}
stable = 0;
missing++;
return (broken || missing >= 3) && !now.isBefore(retryAt);
}
void attempted(DateTime now) {
final seconds = [2, 4, 8, 16, 30][attempts.clamp(0, 4)];
attempts++;
missing = 0;
retryAt = now.add(Duration(seconds: seconds));
}
}
+1 -1
View File
@@ -12,7 +12,7 @@ class UsbDriver {
static const hash =
'38cad6d4432b52d5bb9409d9ad03b72fdffc4ada4cd3a48fbeca1a2752a8518a';
static String defaultUsbip() => p.join(
Platform.environment['ProgramFiles'] ?? r'C:Program Files',
Platform.environment['ProgramFiles'] ?? 'C:/Program Files',
'USBip',
'usbip.exe',
);
+17
View File
@@ -82,6 +82,7 @@ class _ManagerAppState extends State<ManagerApp>
@override
void onWindowClose() {
if (trayReady) {
widget.model.repository.allowEmbeddedResume = false;
unawaited(windowManager.hide());
} else {
unawaited(quit());
@@ -90,10 +91,26 @@ class _ManagerAppState extends State<ManagerApp>
@override
void onTrayIconMouseDown() {
widget.model.repository.allowEmbeddedResume = true;
unawaited(windowManager.show());
unawaited(windowManager.focus());
}
@override
void onWindowMinimize() {
widget.model.repository.allowEmbeddedResume = false;
}
@override
void onWindowRestore() {
widget.model.repository.allowEmbeddedResume = true;
}
@override
void onWindowFocus() {
widget.model.repository.allowEmbeddedResume = true;
}
@override
void onTrayIconRightMouseDown() {
unawaited(trayManager.popUpContextMenu());
+1
View File
@@ -18,6 +18,7 @@ class AgentModel extends ChangeNotifier {
ManagedAgent? get selected =>
_agents.where((a) => a.id == selectedId).firstOrNull;
bool localMode = false, busy = false, autoRefresh = true, followLogs = false;
Future<void> Function(String, String)? savePath;
String adminPath = '',
enrollmentPath = '',
enrollmentToken = '',
+19
View File
@@ -3,6 +3,7 @@ import 'package:material_ui/material_ui.dart';
import '../data/agent_models.dart';
import 'agent_model.dart';
import 'path_picker.dart';
class AgentView extends StatefulWidget {
const AgentView({super.key, required this.model});
@@ -42,6 +43,24 @@ class _AgentViewState extends State<AgentView> {
: null,
decoration: InputDecoration(
labelText: label,
suffixIcon: ['configPath', 'admin', 'enroll'].contains(key)
? IconButton(
tooltip: '选择文件并保存',
icon: const Icon(Icons.folder_open),
onPressed: m.busy
? null
: () => m.run(() async {
final selected = await pickPath(controller.text);
if (selected == null || !mounted) {
return;
}
controller.text = selected;
change(selected);
await m.savePath?.call(key, selected);
m.notice = '文件位置已保存';
}),
)
: null,
border: const OutlineInputBorder(),
),
),
+7 -1
View File
@@ -172,7 +172,13 @@ class ScreenPage extends StatelessWidget {
const SizedBox(height: 12),
Expanded(
child: pid == null
? const Center(child: Text('投屏已停止,请返回设备重新打开。'))
? Center(
child: Text(
s?.screenWanted == true
? '连接中断,正在恢复 USB 和投屏…'
: '投屏已停止,请返回设备重新打开。',
),
)
: s?.screenEmbedded == true
? EmbeddedScreen(key: ValueKey(pid), pid: pid)
: const Center(child: Text('投屏已在独立窗口运行,设备连接保持不变。')),
+18 -3
View File
@@ -47,13 +47,28 @@ class ManagerModel extends ChangeNotifier {
Future<void> init() async {
await action(() async {
await repository.init();
agents.savePath = (key, value) async {
repository.settings.agentPaths[key] = value;
await repository.save();
};
await agents.initialize(
adminFile: repository.root == null
? p.join(p.dirname(Platform.resolvedExecutable), 'admin.env')
: p.join(repository.root!.path, 'config', 'private', 'admin.env'),
adminFile:
repository.settings.agentPaths['admin'] ??
(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,
);
agents.configPath =
repository.settings.agentPaths['configPath'] ?? agents.configPath;
agents.enrollmentPath =
repository.settings.agentPaths['enroll'] ?? agents.enrollmentPath;
notice = '准备就绪';
});
await refresh();
+52 -6
View File
@@ -9,6 +9,7 @@ import '../data/manager_repository.dart';
import 'manager_model.dart';
import 'agent_view.dart';
import 'embedded_screen.dart';
import 'path_picker.dart';
class ManagerView extends StatefulWidget {
final ManagerModel model;
@@ -82,7 +83,13 @@ class _ManagerViewState extends State<ManagerView> {
fontSize: 14,
),
),
onTap: () => setState(() => page = i),
onTap: () {
for (final session
in m.repository.sessions.values) {
session.screenPageVisible = false;
}
setState(() => page = i);
},
),
),
const Spacer(),
@@ -183,12 +190,18 @@ class _ManagerViewState extends State<ManagerView> {
}
}),
session: m.repository.sessions[screenDevice],
onBack: () => setState(() => page = 0),
onBack: () {
m
.repository
.sessions[screenDevice]
?.screenPageVisible =
false;
setState(() => page = 0);
},
onStop: () => m.deviceAction(screenDevice!, () async {
final s = m.repository.sessions[screenDevice];
if (s != null) {
await m.repository.stop(s.screen);
s.screen = null;
await m.repository.stopScreen(s);
}
}),
),
@@ -384,6 +397,7 @@ class _ManagerViewState extends State<ManagerView> {
await m.repository.screen(s, embedded: true);
if (mounted) {
setState(() {
s.screenPageVisible = true;
screenDevice = s.id;
page = 6;
});
@@ -529,7 +543,13 @@ class _ManagerViewState extends State<ManagerView> {
class SettingsView extends StatefulWidget {
final ManagerModel model;
final Future<bool> Function()? driverInstalled;
const SettingsView({super.key, required this.model, this.driverInstalled});
final Future<String?> Function(String, bool)? chooseFile;
const SettingsView({
super.key,
required this.model,
this.driverInstalled,
this.chooseFile,
});
@override
State<SettingsView> createState() => _SettingsViewState();
}
@@ -692,7 +712,33 @@ class _SettingsViewState extends State<SettingsView> {
padding: const EdgeInsets.only(bottom: 18),
child: TextField(
controller: fields[key],
decoration: InputDecoration(labelText: label),
decoration: InputDecoration(
labelText: label,
suffixIcon: ['server', 'origin'].contains(key)
? null
: IconButton(
tooltip: '选择文件并保存',
icon: const Icon(Icons.folder_open),
onPressed: () => widget.model.action(() async {
final selected =
await (widget.chooseFile?.call(
fields[key]!.text,
key != "credential",
) ??
pickPath(
fields[key]!.text,
executable: key != 'credential',
));
if (selected == null || !mounted) {
return;
}
fields[key]!.text = selected;
apply();
await widget.model.repository.save();
widget.model.notice = '文件位置已保存';
}),
),
),
),
),
SwitchListTile(
+19
View File
@@ -0,0 +1,19 @@
import 'dart:io';
import 'package:file_selector/file_selector.dart';
import 'package:path/path.dart' as p;
Future<String?> pickPath(String value, {bool executable = false}) async {
final directory = value.isEmpty ? null : p.dirname(value);
final selected = await openFile(
initialDirectory: directory != null && Directory(directory).existsSync()
? directory
: null,
acceptedTypeGroups: executable
? [
const XTypeGroup(label: '可执行程序', extensions: ['exe']),
]
: [],
);
return selected?.path;
}