diff --git a/AGENTS.md b/AGENTS.md index beca9ba..c1d06b1 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -23,7 +23,7 @@ | `crates/` | Rust 工作区共享库容器 | Rust、TOML | | `crates/ads-management/` | Agent 配置及管理协议、Windows 命名管道/Unix socket、私有文件与系统服务操作;源码在 `src/` | Rust、TOML | | `crates/ads-core/` | 共用网络与协议代码,包括 WSS、WebRTC P2P、节点回退、ADB smart socket 和流式转发;源码在 `src/` | Rust、TOML | -| `flutter_manager/` | 独立 Flutter Windows 管理中心,提供设备/中继总览、Agent 管理、多设备连接、本机 ADB、可选虚拟 USB、托盘与 Windows 内嵌 scrcpy 投屏 | Dart、C++、CMake、YAML、ICO | +| `flutter_manager/` | 独立 Flutter Windows 管理中心,使用 Cupertino UI,提供电脑分组设备、Agent 管理、按天滚动日志、多设备连接、虚拟 USB、托盘与内嵌投屏 | Dart、C++、CMake、YAML、ICO | | `desktop/` | 跨平台桌面客户端及其测试项目、.NET SDK 配置与使用说明 | C#、Avalonia XAML(AXAML)、JSON、Markdown | | `desktop/Ads.Desktop/` | Avalonia 多设备工作台,管理独立连接、自动端口分配、USB 模拟、多个 scrcpy 窗口及托盘;`Assets/` 保存图标资源 | C#、AXAML、XML(csproj)、PNG | | `desktop/Ads.Desktop.Tests/` | 桌面客户端单元测试 | C#、XML(csproj) | diff --git a/README.md b/README.md index 13c1c25..61a310f 100644 --- a/README.md +++ b/README.md @@ -32,7 +32,7 @@ Windows 现支持可选的 [USB ADB 模拟](docs/windows-usb.md),默认网络 | `crates/` | Rust 工作区共享库容器 | Rust、TOML | | `crates/ads-management/` | Agent 配置及管理协议、Windows 命名管道/Unix socket、私有文件与系统服务操作;源码在 `src/` | Rust、TOML | | `crates/ads-core/` | 共用网络与协议代码,包括 WSS、WebRTC P2P、节点回退、ADB smart socket 和流式转发;源码在 `src/` | Rust、TOML | -| `flutter_manager/` | 独立 Flutter Windows 管理中心,提供设备/中继总览、Agent 管理、多设备连接、本机 ADB、可选虚拟 USB、托盘与 Windows 内嵌 scrcpy 投屏 | Dart、C++、CMake、YAML、ICO | +| `flutter_manager/` | 独立 Flutter Windows 管理中心,使用 Cupertino UI,提供电脑分组设备、Agent 管理、按天滚动日志、多设备连接、虚拟 USB、托盘与内嵌投屏 | Dart、C++、CMake、YAML、ICO | | `desktop/` | 跨平台桌面客户端及其测试项目、.NET SDK 配置与使用说明 | C#、Avalonia XAML(AXAML)、JSON、Markdown | | `desktop/Ads.Desktop/` | Avalonia 多设备工作台,管理独立连接、自动端口分配、USB 模拟、多个 scrcpy 窗口及托盘;`Assets/` 保存图标资源 | C#、AXAML、XML(csproj)、PNG | | `desktop/Ads.Desktop.Tests/` | 桌面客户端单元测试 | C#、XML(csproj) | @@ -229,3 +229,5 @@ Agent 管理发行入口:`scripts/build-desktop.ps1` 生成 `bin/desktop-win-x Linux 安装包:`bash scripts/build-linux-packages.sh`,提供 `.deb` 和 `.tar.gz`,详见 [Linux 打包](docs/linux-packaging.md)。 Linux 原生虚拟 USB 已在 Ubuntu 实机通过 CLI 验证,部署和权限说明见 [Linux USB](docs/linux-usb.md)。Avalonia Linux GUI 已接入 pkexec 挂载,Flutter Linux 尚未接入。 + +Flutter 管理中心已迁移 Cupertino UI,设备按电脑归属分组,支持按电脑名搜索;运行日志按天保存并按大小滚动,路径及策略见 [Flutter 使用说明](flutter_manager/README.md)。 diff --git a/flutter_manager/README.md b/flutter_manager/README.md index a750575..1e10a54 100644 --- a/flutter_manager/README.md +++ b/flutter_manager/README.md @@ -125,3 +125,11 @@ USB ADB 连续 3 轮监控缺失(约 9 秒)、USB 后端退出或 scrcpy 以 内嵌投屏的自动恢复遵循页面可见性:离开投屏页或缩到托盘时继续修复 USB 连接,但暂不重新创建内嵌画面;返回投屏页并显示窗口后恢复。独立窗口模式按原模式恢复。 本轮验证:文件路径选择/取消及立即保存测试、USB 恢复状态机与窗口可见性测试通过。真机主动结束本次 ads-client 后,USB 和软件渲染投屏自动恢复并重新出图;主动停止不再自动启动。测试使用了仅中继对照,恢复逻辑不依赖选择 P2P 或中继。Avalonia 真机亦验证客户端故障后 USB 重挂载及 scrcpy 重新出图。 + +## Cupertino UI、电脑归属和本地日志 + +应用根、按钮、表单、列表选择、开关、展开区域与确认对话框采用官方 cupertino_ui;app_widgets.dart 封装统一的 Cupertino 组件,兼容层只为现有选择菜单、图标、文本选择和插件提供主题/本地化上下文。设备工作台根据控制中心返回的 agent_id/computer_name 按电脑分组,每张手机卡片显示所属电脑,并支持按电脑名搜索。旧单设备 Agent 没有上报主机信息时明确显示未上报,不猜测归属。普通 client 角色即可读取这些字段。 + +运行日志保存到 `%LOCALAPPDATA%/TTSTD/ADS-Flutter/logs/ads-YYYY-MM-DD.log`。单文件达到约 5 MiB 后滚动,每天最多 5 份(含当天主文件),保留 14 天;应用关闭前等待写入完成。已加载令牌在内存和磁盘日志中均脱敏,单条磁盘日志最多 16384 字符。包括客户端/USB/scrcpy 子进程日志、Agent 管理操作错误,以及主动读取/跟随的 Agent 日志。日志页显示实际路径和写入错误。文件中可能包含设备地址、路径等诊断信息,分享前按需检查。 + +工作台和 Agent 页的刷新指示器使用固定高度占位。Agent 发现列表保留到切换主机;旧后端不支持 devices_discover 时提示同步更新 CLI 和 Agent。`test/daily_log_test.dart` 验证跨天、大小滚动、保留及脱敏,`test/cupertino_layout_test.dart` 验证电脑名和刷新布局不移位。 diff --git a/flutter_manager/lib/data/agent_service.dart b/flutter_manager/lib/data/agent_service.dart index 5129a50..34fad01 100644 --- a/flutter_manager/lib/data/agent_service.dart +++ b/flutter_manager/lib/data/agent_service.dart @@ -95,7 +95,12 @@ class AgentService implements AgentApi { final code = await child.exitCode.timeout(const Duration(seconds: 22)); final result = ProcessResult(child.pid, code, await out, await error); if (code != 0) { - throw StateError(redact(result.stderr as String)); + var message = redact(result.stderr as String); + if (message.contains('unknown variant') && + message.contains('devices_discover')) { + message = '本机 adsctl 或 Agent 版本过旧,请同步更新两者后重启 Agent'; + } + throw StateError(message); } return result; } on TimeoutException { @@ -142,6 +147,9 @@ class AgentService implements AgentApi { @override Future start(String path) async { + if (!await File(path).exists()) { + throw StateError("请先导入 agent.env 并初始化本机配置,再启动 Agent"); + } try { await local(path, {'op': 'status'}); return; @@ -160,6 +168,10 @@ class AgentService implements AgentApi { @override Future install(String path) async { + if (Platform.isLinux) { + await _cli(['--config', path, 'service', 'install']); + return; + } if (!Platform.isWindows) { throw UnsupportedError('请在终端运行 adsctl service install,系统级服务加 --system'); } diff --git a/flutter_manager/lib/data/daily_log.dart b/flutter_manager/lib/data/daily_log.dart new file mode 100644 index 0000000..f55b3f3 --- /dev/null +++ b/flutter_manager/lib/data/daily_log.dart @@ -0,0 +1,71 @@ +import 'dart:async'; +import 'dart:io'; + +import 'package:path/path.dart' as p; + +class DailyLog { + DailyLog( + this.directory, { + this.maxBytes = 5 * 1024 * 1024, + this.maxParts = 5, + this.keepDays = 14, + DateTime Function()? clock, + }) : assert(maxBytes > 0 && maxParts > 0 && keepDays > 0), + clock = clock ?? DateTime.now; + final Directory directory; + final int maxBytes, maxParts, keepDays; + final DateTime Function() clock; + Future _pending = Future.value(); + String? error; + String _cleaned = ''; + void add(String text) { + final time = clock(); + _pending = _pending + .then((_) async { + await directory.create(recursive: true); + final day = time.toIso8601String().substring(0, 10); + if (_cleaned != day) { + final cutoff = DateTime( + time.year, + time.month, + time.day, + ).subtract(Duration(days: keepDays - 1)); + await for (final entry in directory.list()) { + if (entry is! File) continue; + final match = RegExp(r'^ads-(\d{4}-\d{2}-\d{2})(?:\.\d+)?\.log$') + .firstMatch(p.basename(entry.path)); + if (match != null && DateTime.parse(match[1]!).isBefore(cutoff)) { + await entry.delete(); + } + } + _cleaned = day; + } + final base = p.join(directory.path, 'ads-$day'); + final file = File('$base.log'); + if (await file.exists() && await file.length() >= maxBytes) { + final oldest = File('$base.${maxParts - 1}.log'); + if (await oldest.exists()) await oldest.delete(); + for (var part = maxParts - 2; part >= 1; part--) { + final old = File('$base.$part.log'); + if (await old.exists()) await old.rename('$base.${part + 1}.log'); + } + if (maxParts > 1) { + await file.rename('$base.1.log'); + } else { + await file.delete(); + } + } + await file.writeAsString( + '${time.toIso8601String()} $text\n', + mode: FileMode.append, + flush: true, + ); + error = null; + }) + .catchError((Object e) { + error = e.toString(); + }); + } + + Future flush() => _pending; +} diff --git a/flutter_manager/lib/data/manager_repository.dart b/flutter_manager/lib/data/manager_repository.dart index 8547fb5..bb71bea 100644 --- a/flutter_manager/lib/data/manager_repository.dart +++ b/flutter_manager/lib/data/manager_repository.dart @@ -59,7 +59,8 @@ class Settings { class Device { final String id; final bool busy; - const Device(this.id, this.busy); + final String agentId, computerName; + const Device(this.id, this.busy, {this.agentId = "", this.computerName = ""}); } class Session { @@ -144,14 +145,16 @@ class ManagerRepository { } String findTool(String name) { - final exe = '$name.exe'; + final exe = Platform.isWindows ? '$name.exe' : name; final base = p.dirname(Platform.resolvedExecutable); final candidates = [ p.join(base, exe), p.join(base, 'tools', 'scrcpy', exe), if (root != null) p.join(root!.path, 'bin', exe), if (root != null) p.join(root!.path, 'bin', 'tools', 'scrcpy', exe), - for (final dir in (Platform.environment['PATH'] ?? '').split(';')) + for (final dir in (Platform.environment['PATH'] ?? '').split( + Platform.isWindows ? ';' : ':', + )) p.join(dir, exe), ]; return candidates.firstWhere( @@ -265,7 +268,12 @@ class ManagerRepository { if (!RegExp(r'^[a-zA-Z0-9_.-]{1,128}$').hasMatch(id)) { throw const FormatException('无效设备 ID'); } - return Device(id, j['busy'] == true); + return Device( + id, + j['busy'] == true, + agentId: j['agent_id'] as String? ?? '', + computerName: j['computer_name'] as String? ?? '', + ); }).toList()..sort((a, b) => a.id.compareTo(b.id)); } diff --git a/flutter_manager/lib/main.dart b/flutter_manager/lib/main.dart index 3b6d7a7..041ab49 100644 --- a/flutter_manager/lib/main.dart +++ b/flutter_manager/lib/main.dart @@ -1,7 +1,11 @@ import 'dart:async'; import 'dart:io'; +import 'dart:ui' show PlatformDispatcher; + +import 'package:cupertino_ui/cupertino_ui.dart'; + +import 'ui/app_widgets.dart' show AdsCupertinoApp; -import 'package:material_ui/material_ui.dart'; import 'package:tray_manager/tray_manager.dart'; import 'package:window_manager/window_manager.dart'; @@ -12,6 +16,18 @@ Future main() async { WidgetsFlutterBinding.ensureInitialized(); await windowManager.ensureInitialized(); final model = ManagerModel(); + FlutterError.onError = (details) { + FlutterError.presentError(details); + scheduleMicrotask( + () => model.log( + '[Flutter] ${details.exceptionAsString()}\n${details.stack ?? ""}', + ), + ); + }; + PlatformDispatcher.instance.onError = (error, stack) { + scheduleMicrotask(() => model.log('[Unhandled] $error\n$stack')); + return true; + }; runApp(ManagerApp(model: model)); await windowManager.waitUntilReadyToShow( const WindowOptions( @@ -143,24 +159,7 @@ class _ManagerAppState extends State } @override - Widget build(BuildContext context) => MaterialApp( - debugShowCheckedModeBanner: false, - title: 'ADS 管理中心', - theme: ThemeData( - useMaterial3: true, - fontFamily: 'Microsoft YaHei', - colorScheme: ColorScheme.fromSeed(seedColor: const Color(0xFF305DDB)), - scaffoldBackgroundColor: const Color(0xFFF3F5FA), - cardTheme: const CardThemeData( - elevation: 0, - color: Colors.white, - margin: EdgeInsets.zero, - ), - inputDecorationTheme: const InputDecorationTheme( - border: OutlineInputBorder(), - isDense: true, - ), - ), + Widget build(BuildContext context) => AdsCupertinoApp( home: ManagerView(model: widget.model, onQuit: quit), ); } diff --git a/flutter_manager/lib/ui/agent_model.dart b/flutter_manager/lib/ui/agent_model.dart index c0e5d4b..6b0383e 100644 --- a/flutter_manager/lib/ui/agent_model.dart +++ b/flutter_manager/lib/ui/agent_model.dart @@ -12,6 +12,7 @@ import '../data/agent_service.dart'; class AgentModel extends ChangeNotifier { AgentModel(this.repository); final AgentRepository repository; + void Function(String)? onLog; List _agents = []; List get agents => List.unmodifiable(_agents); String? selectedId, selectedPhone; @@ -111,6 +112,7 @@ class AgentModel extends ChangeNotifier { if (busy || _disposed) { return; } + final previousNotice = notice; busy = true; _notify(); try { @@ -118,6 +120,7 @@ class AgentModel extends ChangeNotifier { } catch (error) { notice = repository.redact(error.toString()); } finally { + if (notice != previousNotice) onLog?.call(notice); busy = false; _notify(); } @@ -241,9 +244,11 @@ class AgentModel extends ChangeNotifier { _cursor = page['next'] as int; for (final value in page['entries']! as List) { final line = value! as Map; - logText += repository.redact( - '${line['time']} ${line['level']} ${line['message']}\n', + final text = repository.redact( + '${line['time']} ${line['level']} ${line['message']}', ); + logText += '$text\n'; + onLog?.call('[${selectedId ?? "local"}] $text'); } if (logText.length > 100000) { logText = logText.substring(logText.length - 100000); diff --git a/flutter_manager/lib/ui/agent_view.dart b/flutter_manager/lib/ui/agent_view.dart index 2810c38..ffe9755 100644 --- a/flutter_manager/lib/ui/agent_view.dart +++ b/flutter_manager/lib/ui/agent_view.dart @@ -1,4 +1,4 @@ -import 'package:material_ui/material_ui.dart'; +import 'app_widgets.dart'; import '../data/agent_models.dart'; @@ -132,7 +132,10 @@ class _AgentViewState extends State { ), Text(m.notice, style: const TextStyle(color: Colors.blueGrey)), const SizedBox(height: 10), - if (m.busy) const LinearProgressIndicator(), + SizedBox( + height: 3, + child: m.busy ? const LinearProgressIndicator(minHeight: 3) : null, + ), Expanded( child: LayoutBuilder( builder: (context, size) { diff --git a/flutter_manager/lib/ui/app_widgets.dart b/flutter_manager/lib/ui/app_widgets.dart new file mode 100644 index 0000000..bb8757d --- /dev/null +++ b/flutter_manager/lib/ui/app_widgets.dart @@ -0,0 +1,380 @@ +import 'package:cupertino_ui/cupertino_ui.dart' as c; +import 'package:material_ui/material_ui.dart' as m; +export 'package:material_ui/material_ui.dart' + hide + Scaffold, + Card, + FilledButton, + OutlinedButton, + TextButton, + IconButton, + TextField, + Checkbox, + SwitchListTile, + ListTile, + ExpansionTile, + AlertDialog, + showDialog; +export 'package:cupertino_ui/cupertino_ui.dart' + show + CupertinoApp, + CupertinoThemeData, + CupertinoColors, + CupertinoActivityIndicator, + CupertinoPageScaffold; + +class Scaffold extends m.StatelessWidget { + const Scaffold({super.key, required this.body}); + final m.Widget body; + @override + m.Widget build(m.BuildContext context) => + c.CupertinoPageScaffold(child: body); +} + +class Card extends m.StatelessWidget { + const Card({super.key, required this.child}); + final m.Widget child; + @override + m.Widget build(m.BuildContext context) => m.DecoratedBox( + decoration: m.BoxDecoration( + color: c.CupertinoColors.secondarySystemGroupedBackground.resolveFrom( + context, + ), + borderRadius: m.BorderRadius.circular(14), + border: m.Border.all( + color: c.CupertinoColors.separator + .resolveFrom(context) + .withValues(alpha: .18), + ), + ), + child: child, + ); +} + +class ActionButton extends m.StatelessWidget { + const ActionButton({ + super.key, + required this.onPressed, + required this.child, + this.primary = false, + }) : icon = null; + const ActionButton.icon({ + super.key, + required this.onPressed, + required m.Widget label, + required this.icon, + this.primary = false, + }) : child = label; + final m.VoidCallback? onPressed; + final m.Widget child; + final m.Widget? icon; + final bool primary; + @override + m.Widget build(m.BuildContext context) { + final content = icon == null + ? child + : m.Row( + mainAxisSize: m.MainAxisSize.min, + children: [icon!, const m.SizedBox(width: 7), child], + ); + return c.CupertinoButton( + padding: const m.EdgeInsets.symmetric(horizontal: 14, vertical: 9), + minimumSize: const m.Size(0, 36), + color: primary ? c.CupertinoColors.activeBlue : null, + onPressed: onPressed, + child: m.DefaultTextStyle.merge( + style: m.TextStyle( + fontSize: 13, + color: primary ? c.CupertinoColors.white : null, + ), + child: content, + ), + ); + } +} + +class FilledButton extends ActionButton { + const FilledButton({ + super.key, + required super.onPressed, + required super.child, + }) : super(primary: true); + const FilledButton.icon({ + super.key, + required super.onPressed, + required super.label, + required super.icon, + }) : super.icon(primary: true); +} + +class OutlinedButton extends ActionButton { + const OutlinedButton({ + super.key, + required super.onPressed, + required super.child, + }); + const OutlinedButton.icon({ + super.key, + required super.onPressed, + required super.label, + required super.icon, + }) : super.icon(); +} + +class TextButton extends ActionButton { + const TextButton({super.key, required super.onPressed, required super.child}); + const TextButton.icon({ + super.key, + required super.onPressed, + required super.label, + required super.icon, + }) : super.icon(); +} + +class IconButton extends m.StatelessWidget { + const IconButton({ + super.key, + required this.onPressed, + required this.icon, + this.tooltip, + }); + final m.VoidCallback? onPressed; + final m.Widget icon; + final String? tooltip; + @override + m.Widget build(m.BuildContext context) => m.Tooltip( + message: tooltip ?? '', + child: c.CupertinoButton( + padding: const m.EdgeInsets.all(6), + minimumSize: const m.Size(32, 32), + onPressed: onPressed, + child: icon, + ), + ); +} + +class TextField extends m.StatelessWidget { + const TextField({ + super.key, + this.controller, + this.onChanged, + this.decoration = const m.InputDecoration(), + this.obscureText = false, + this.maxLines = 1, + this.minLines, + this.style, + }); + final m.TextEditingController? controller; + final m.ValueChanged? onChanged; + final m.InputDecoration decoration; + final bool obscureText; + final int? maxLines, minLines; + final m.TextStyle? style; + @override + m.Widget build(m.BuildContext context) => m.Column( + crossAxisAlignment: m.CrossAxisAlignment.start, + children: [ + if (decoration.labelText != null) + m.Padding( + padding: const m.EdgeInsets.only(bottom: 6), + child: m.Text( + decoration.labelText!, + style: const m.TextStyle( + fontSize: 12, + color: c.CupertinoColors.secondaryLabel, + ), + ), + ), + c.CupertinoTextField( + controller: controller, + onChanged: onChanged, + obscureText: obscureText, + maxLines: maxLines, + minLines: minLines, + style: style, + placeholder: decoration.hintText, + prefix: decoration.prefixIcon, + suffix: decoration.suffixIcon, + padding: const m.EdgeInsets.all(12), + ), + ], + ); +} + +class Checkbox extends m.StatelessWidget { + const Checkbox({super.key, required this.value, required this.onChanged}); + final bool? value; + final m.ValueChanged? onChanged; + @override + m.Widget build(m.BuildContext context) => + c.CupertinoCheckbox(value: value ?? false, onChanged: onChanged); +} + +class SwitchListTile extends m.StatelessWidget { + const SwitchListTile({ + super.key, + required this.value, + required this.onChanged, + required this.title, + this.subtitle, + this.contentPadding, + }); + final bool value; + final m.ValueChanged? onChanged; + final m.Widget title; + final m.Widget? subtitle; + final m.EdgeInsetsGeometry? contentPadding; + @override + m.Widget build(m.BuildContext context) => m.GestureDetector( + behavior: m.HitTestBehavior.opaque, + onTap: onChanged == null ? null : () => onChanged!(!value), + child: m.Padding( + padding: contentPadding ?? m.EdgeInsets.zero, + child: m.Row( + children: [ + m.Expanded( + child: m.Column( + crossAxisAlignment: m.CrossAxisAlignment.start, + children: [title, ?subtitle], + ), + ), + c.CupertinoSwitch(value: value, onChanged: onChanged), + ], + ), + ), + ); +} + +class ListTile extends m.StatelessWidget { + const ListTile({ + super.key, + this.title, + this.subtitle, + this.leading, + this.trailing, + this.onTap, + this.selected = false, + this.selectedTileColor, + this.shape, + this.contentPadding, + }); + final m.Widget? title, subtitle, leading, trailing; + final m.VoidCallback? onTap; + final bool selected; + final m.Color? selectedTileColor; + final m.ShapeBorder? shape; + final m.EdgeInsetsGeometry? contentPadding; + @override + m.Widget build(m.BuildContext context) => m.GestureDetector( + behavior: m.HitTestBehavior.opaque, + onTap: onTap, + child: m.Container( + padding: + contentPadding ?? + const m.EdgeInsets.symmetric(horizontal: 12, vertical: 11), + decoration: m.BoxDecoration( + color: selected + ? (selectedTileColor ?? + c.CupertinoColors.activeBlue.withValues(alpha: .12)) + : null, + borderRadius: m.BorderRadius.circular(9), + ), + child: m.Row( + children: [ + if (leading != null) ...[leading!, const m.SizedBox(width: 10)], + m.Expanded( + child: m.Column( + crossAxisAlignment: m.CrossAxisAlignment.start, + children: [ + ?title, + if (subtitle != null) + m.DefaultTextStyle.merge( + style: const m.TextStyle( + fontSize: 12, + color: c.CupertinoColors.secondaryLabel, + ), + child: subtitle!, + ), + ], + ), + ), + ?trailing, + ], + ), + ), + ); +} + +class AlertDialog extends m.StatelessWidget { + const AlertDialog({ + super.key, + this.title, + this.content, + this.actions = const [], + }); + final m.Widget? title, content; + final List actions; + @override + m.Widget build(m.BuildContext context) => + c.CupertinoAlertDialog(title: title, content: content, actions: actions); +} + +Future showDialog({ + required m.BuildContext context, + required m.WidgetBuilder builder, +}) => c.showCupertinoDialog(context: context, builder: builder); + +class AdsCupertinoApp extends m.StatelessWidget { + const AdsCupertinoApp({super.key, required this.home}); + final m.Widget home; + @override + m.Widget build(m.BuildContext context) => c.CupertinoApp( + debugShowCheckedModeBanner: false, + title: 'ADS 管理中心', + theme: const c.CupertinoThemeData( + primaryColor: c.CupertinoColors.activeBlue, + scaffoldBackgroundColor: c.CupertinoColors.systemGroupedBackground, + ), + builder: (context, child) => m.Theme( + data: m.ThemeData(), + child: m.Localizations.override( + context: context, + delegates: const [m.DefaultMaterialLocalizations.delegate], + child: m.Material(type: m.MaterialType.transparency, child: child!), + ), + ), + home: home, + ); +} + +class ExpansionTile extends m.StatefulWidget { + const ExpansionTile({super.key, required this.title, required this.children}); + final m.Widget title; + final List children; + @override + m.State createState() => _ExpansionTileState(); +} + +class _ExpansionTileState extends m.State { + bool expanded = false; + @override + m.Widget build(m.BuildContext context) => m.Column( + children: [ + c.CupertinoButton( + onPressed: () => setState(() => expanded = !expanded), + child: m.Row( + children: [ + m.Expanded(child: widget.title), + m.Icon( + expanded + ? c.CupertinoIcons.chevron_up + : c.CupertinoIcons.chevron_down, + size: 16, + ), + ], + ), + ), + if (expanded) ...widget.children, + ], + ); +} diff --git a/flutter_manager/lib/ui/embedded_screen.dart b/flutter_manager/lib/ui/embedded_screen.dart index 9b6b61d..ced9495 100644 --- a/flutter_manager/lib/ui/embedded_screen.dart +++ b/flutter_manager/lib/ui/embedded_screen.dart @@ -1,7 +1,8 @@ import 'dart:async'; import 'package:flutter/services.dart'; -import 'package:material_ui/material_ui.dart'; + +import 'app_widgets.dart'; import '../data/manager_repository.dart'; diff --git a/flutter_manager/lib/ui/manager_model.dart b/flutter_manager/lib/ui/manager_model.dart index 984ea64..f670a0b 100644 --- a/flutter_manager/lib/ui/manager_model.dart +++ b/flutter_manager/lib/ui/manager_model.dart @@ -4,6 +4,7 @@ import 'package:flutter/foundation.dart'; import '../data/manager_repository.dart'; import '../data/agent_repository.dart'; +import '../data/daily_log.dart'; import '../data/agent_service.dart'; import 'agent_model.dart'; @@ -11,23 +12,50 @@ import 'dart:io'; import 'package:path/path.dart' as p; +DailyLog defaultLog() => DailyLog( + Directory( + p.join( + Platform.environment['LOCALAPPDATA'] ?? + p.join( + Platform.environment['HOME'] ?? Directory.systemTemp.path, + '.local', + 'share', + ), + 'TTSTD', + 'ADS-Flutter', + 'logs', + ), + ), +); + class ManagerModel extends ChangeNotifier { late final ManagerRepository repository; late final AgentModel agents; List devices = []; List> nodes = []; final List logs = []; + late final DailyLog diskLog; + String get logDirectory => diskLog.directory.path; final Set pending = {}; String notice = '正在初始化', adbListing = ''; bool refreshing = false, closing = false, polling = false; Timer? timer; int ticks = 0; - ManagerModel() { + ManagerModel({DailyLog? logWriter}) { + diskLog = logWriter ?? defaultLog(); repository = ManagerRepository(log); agents = AgentModel(AgentRepository(AgentService(repository))); + agents.onLog = (text) => log("[Agent] $text"); } void log(String text) { - logs.insert(0, '${DateTime.now().toString().substring(11, 19)} $text'); + var safe = agents.repository.redact(text); + for (final secret in [repository.token, agents.enrollmentToken]) { + if (secret.isNotEmpty) safe = safe.replaceAll(secret, '[REDACTED]'); + } + logs.insert(0, '${DateTime.now().toString().substring(11, 19)} $safe'); + diskLog.add( + safe.length > 16384 ? '${safe.substring(0, 16384)} [truncated]' : safe, + ); if (logs.length > 500) { logs.removeLast(); } @@ -72,6 +100,7 @@ class ManagerModel extends ChangeNotifier { notice = '准备就绪'; }); await refresh(); + log('ADS Flutter / Cupertino 已启动,本地日志目录:$logDirectory'); timer = Timer.periodic(const Duration(seconds: 3), (_) async { if (closing || refreshing || polling) { return; @@ -145,5 +174,6 @@ class ManagerModel extends ChangeNotifier { await Future.delayed(const Duration(milliseconds: 50)); } await repository.shutdown(); + await diskLog.flush(); } } diff --git a/flutter_manager/lib/ui/manager_view.dart b/flutter_manager/lib/ui/manager_view.dart index 3530a49..c7a009b 100644 --- a/flutter_manager/lib/ui/manager_view.dart +++ b/flutter_manager/lib/ui/manager_view.dart @@ -1,6 +1,7 @@ import 'dart:io'; -import 'package:material_ui/material_ui.dart'; +import 'app_widgets.dart'; + import 'package:flutter/services.dart'; import '../data/windows_usb.dart'; @@ -34,7 +35,7 @@ class _ManagerViewState extends State { SizedBox( width: 204, child: Material( - color: const Color(0xFF14233F), + color: const Color(0xFFF0F2F7), child: Column( crossAxisAlignment: CrossAxisAlignment.stretch, children: [ @@ -43,7 +44,7 @@ class _ManagerViewState extends State { child: Text( 'ADS', style: TextStyle( - color: Colors.white, + color: Color(0xFF182235), fontSize: 32, fontWeight: FontWeight.w800, ), @@ -53,7 +54,7 @@ class _ManagerViewState extends State { padding: EdgeInsets.fromLTRB(24, 0, 16, 36), child: Text( '设备管理中心 / Flutter', - style: TextStyle(color: Colors.white60, fontSize: 12), + style: TextStyle(color: Colors.blueGrey, fontSize: 12), ), ), for (final (i, title, icon) in [ @@ -71,15 +72,15 @@ class _ManagerViewState extends State { ), child: ListTile( selected: page == i, - selectedTileColor: const Color(0xFF29446C), + selectedTileColor: const Color(0xFFE4ECFF), shape: RoundedRectangleBorder( borderRadius: BorderRadius.circular(10), ), - leading: Icon(icon, color: Colors.white70, size: 21), + leading: Icon(icon, color: Colors.blueGrey, size: 21), title: Text( title, style: const TextStyle( - color: Colors.white, + color: Color(0xFF182235), fontSize: 14, ), ), @@ -98,7 +99,7 @@ class _ManagerViewState extends State { child: Text( 'Windows · 网络 ADB\n关闭窗口后保留在托盘', style: TextStyle( - color: Colors.white54, + color: Colors.blueGrey, height: 1.8, fontSize: 12, ), @@ -167,7 +168,12 @@ class _ManagerViewState extends State { ], ), ), - if (m.refreshing) const LinearProgressIndicator(minHeight: 2), + SizedBox( + height: 3, + child: m.refreshing + ? const LinearProgressIndicator(minHeight: 3) + : null, + ), Expanded( child: Padding( padding: const EdgeInsets.all(24), @@ -252,8 +258,18 @@ class _ManagerViewState extends State { all.putIfAbsent(id, () => Device(id, false)); } final rows = all.values - .where((d) => d.id.toLowerCase().contains(search.toLowerCase())) + .where( + (d) => '${d.id} ${d.computerName} ${d.agentId}' + .toLowerCase() + .contains(search.toLowerCase()), + ) .toList(); + rows.sort((a, b) { + final host = '${a.computerName} ${a.agentId}'.compareTo( + '${b.computerName} ${b.agentId}', + ); + return host != 0 ? host : a.id.compareTo(b.id); + }); return Column( children: [ Row( @@ -276,7 +292,7 @@ class _ManagerViewState extends State { child: TextField( onChanged: (v) => setState(() => search = v), decoration: const InputDecoration( - hintText: '搜索设备 ID', + hintText: '搜索手机或电脑名', prefixIcon: Icon(Icons.search), filled: true, fillColor: Colors.white, @@ -320,7 +336,24 @@ class _ManagerViewState extends State { : ListView.separated( itemCount: rows.length, separatorBuilder: (_, index) => const SizedBox(height: 12), - itemBuilder: (context, i) => deviceCard(rows[i]), + itemBuilder: (context, i) => Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + if (i == 0 || rows[i].agentId != rows[i - 1].agentId) + Padding( + padding: const EdgeInsets.only(top: 6, bottom: 10), + child: Text( + '电脑 · ${rows[i].computerName.isEmpty ? "未上报电脑名" : rows[i].computerName}${rows[i].agentId.isEmpty ? "" : " / ${rows[i].agentId}"}', + style: const TextStyle( + fontSize: 13, + fontWeight: FontWeight.w600, + color: Colors.blueGrey, + ), + ), + ), + deviceCard(rows[i]), + ], + ), ), ), ], @@ -361,6 +394,13 @@ class _ManagerViewState extends State { fontSize: 17, ), ), + Text( + '电脑:${d.computerName.isEmpty ? "旧 Agent(未上报电脑名)" : d.computerName}${d.agentId.isEmpty ? "" : " · ${d.agentId}"}', + style: const TextStyle( + fontSize: 12, + color: Colors.blueGrey, + ), + ), const SizedBox(height: 5), Text( s?.state ?? (d.busy ? '其他客户端占用' : '空闲 · 可连接'), @@ -515,7 +555,12 @@ class _ManagerViewState extends State { children: [ Row( children: [ - const Text('最近 500 条 · 仅保存在内存'), + Expanded( + child: Text( + '最近 500 条 · 按天保存,单文件 5 MiB,保留 14 天\n${m.logDirectory}${m.diskLog.error == null ? "" : "\n日志写入失败:${m.diskLog.error}"}', + style: const TextStyle(fontSize: 12), + ), + ), const Spacer(), TextButton( onPressed: () => diff --git a/flutter_manager/pubspec.lock b/flutter_manager/pubspec.lock index 7244640..248e01f 100644 --- a/flutter_manager/pubspec.lock +++ b/flutter_manager/pubspec.lock @@ -162,7 +162,7 @@ packages: source: hosted version: "1.0.9" cupertino_ui: - dependency: transitive + dependency: "direct main" description: name: cupertino_ui sha256: "369e39a1c5c030a6212589c3da1809920b1c2cfade7b02aade7695bfa4b88c3a" diff --git a/flutter_manager/pubspec.yaml b/flutter_manager/pubspec.yaml index 0632115..015396d 100644 --- a/flutter_manager/pubspec.yaml +++ b/flutter_manager/pubspec.yaml @@ -41,6 +41,7 @@ dependencies: freezed_annotation: ^3.1.0 crypto: ^3.0.8 file_selector: ^1.1.0 + cupertino_ui: ^1.1.6 dev_dependencies: flutter_test: diff --git a/flutter_manager/test/cupertino_layout_test.dart b/flutter_manager/test/cupertino_layout_test.dart new file mode 100644 index 0000000..ae5337a --- /dev/null +++ b/flutter_manager/test/cupertino_layout_test.dart @@ -0,0 +1,67 @@ +import 'dart:io'; +import 'dart:ui' as ui; + +import 'package:flutter/rendering.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:ads_manager/ui/app_widgets.dart'; +import 'package:ads_manager/ui/manager_model.dart'; +import 'package:ads_manager/ui/manager_view.dart'; +import 'package:ads_manager/data/manager_repository.dart'; + +void main() { + testWidgets( + 'Cupertino workbench shows computers without refresh layout shift', + (tester) async { + tester.view.physicalSize = const Size(1280, 820); + tester.view.devicePixelRatio = 1; + addTearDown(tester.view.resetPhysicalSize); + addTearDown(tester.view.resetDevicePixelRatio); + final m = ManagerModel(); + m.devices = [ + const Device('phone-one', false, agentId: 'home', computerName: '家里电脑'), + const Device( + 'phone-two', + false, + agentId: 'office', + computerName: '办公室电脑', + ), + ]; + final key = GlobalKey(); + await tester.pumpWidget( + RepaintBoundary( + key: key, + child: AdsCupertinoApp( + home: ManagerView(model: m, onQuit: () async {}), + ), + ), + ); + await tester.pumpAndSettle(); + expect(find.textContaining('办公室电脑'), findsWidgets); + final before = tester.getTopLeft(find.text('phone-one')); + await m.action(() async { + m.refreshing = true; + }); + await tester.pump(); + expect(tester.getTopLeft(find.text('phone-one')), before); + await m.action(() async { + m.refreshing = false; + }); + await tester.pumpAndSettle(); + expect(tester.takeException(), isNull); + if (const bool.fromEnvironment('ADS_CAPTURE')) { + await tester.runAsync(() async { + final image = + await (key.currentContext!.findRenderObject()! + as RenderRepaintBoundary) + .toImage(); + final bytes = await image.toByteData(format: ui.ImageByteFormat.png); + await File('../work/flutter-cupertino.png') + .writeAsBytes(bytes!.buffer.asUint8List()); + image.dispose(); + }); + } + await tester.pumpWidget(const SizedBox()); + m.dispose(); + }, + ); +} diff --git a/flutter_manager/test/daily_log_test.dart b/flutter_manager/test/daily_log_test.dart new file mode 100644 index 0000000..92da50e --- /dev/null +++ b/flutter_manager/test/daily_log_test.dart @@ -0,0 +1,65 @@ +import 'dart:io'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:ads_manager/data/daily_log.dart'; +import 'package:ads_manager/ui/manager_model.dart'; + +void main() { + test('memory and persisted logs redact connection credentials', () async { + final dir = await Directory.systemTemp.createTemp('ads-redact'); + final model = ManagerModel(logWriter: DailyLog(dir)); + try { + final secret = 'c' * 64; + model.repository.token = secret; + model.log('connection error $secret'); + await model.diskLog.flush(); + expect(model.logs.single, contains('[REDACTED]')); + final file = (await dir.list().toList()).whereType().single; + final value = await file.readAsString(); + expect(value, isNot(contains(secret))); + } finally { + model.dispose(); + await dir.delete(recursive: true); + } + }); + test('daily files, bounded size rotation and retention', () async { + final folder = await Directory.systemTemp.createTemp('ads-log-test'); + try { + var now = DateTime(2026, 11, 13, 23, 59); + await File('${folder.path}/ads-2026-10-01.log').writeAsString('expired'); + await File('${folder.path}/other.txt').writeAsString('keep'); + final log = DailyLog( + folder, + maxBytes: 1, + maxParts: 2, + keepDays: 14, + clock: () => now, + ); + log.add('first'); + log.add('second'); + log.add('third'); + await log.flush(); + expect( + await File('${folder.path}/ads-2026-11-13.log').readAsString(), + contains('third'), + ); + expect( + await File('${folder.path}/ads-2026-11-13.1.log').readAsString(), + contains('second'), + ); + expect(await File('${folder.path}/ads-2026-11-13.2.log').exists(), false); + expect(await File('${folder.path}/ads-2026-10-01.log').exists(), false); + expect(await File('${folder.path}/other.txt').exists(), true); + now = DateTime(2026, 11, 14); + log.add('new day'); + await log.flush(); + expect( + await File('${folder.path}/ads-2026-11-14.log').readAsString(), + contains('new day'), + ); + expect(log.error, isNull); + } finally { + await folder.delete(recursive: true); + } + }); +} diff --git a/flutter_manager/test/live_smoke.dart b/flutter_manager/test/live_smoke.dart index 636c92b..b3b0a9f 100644 --- a/flutter_manager/test/live_smoke.dart +++ b/flutter_manager/test/live_smoke.dart @@ -10,7 +10,7 @@ Future main(List args) async { repo.settings.relayOnly = args.contains('--relay-only'); final devices = await repo.devices(); stdout.writeln( - 'API devices: ${devices.map((d) => "${d.id} busy=${d.busy}").join(", ")}', + 'API devices: ${devices.map((d) => "${d.id} busy=${d.busy} computer=${d.computerName} agent=${d.agentId}").join(", ")}', ); final nodes = await repo.get('v2/nodes') as Map; stdout.writeln('Relay nodes: ${(nodes["nodes"] as List).length}'); diff --git a/flutter_manager/test/widget_test.dart b/flutter_manager/test/widget_test.dart index e10eea3..a9aa5e6 100644 --- a/flutter_manager/test/widget_test.dart +++ b/flutter_manager/test/widget_test.dart @@ -1,5 +1,9 @@ import 'dart:io'; +import 'package:ads_manager/ui/app_widgets.dart' show AdsCupertinoApp; + +import 'package:cupertino_ui/cupertino_ui.dart' show CupertinoTextField; + import 'package:material_ui/material_ui.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:ads_manager/data/manager_repository.dart'; @@ -49,13 +53,13 @@ void main() { const Device('busy-phone', true), ]; await tester.pumpWidget( - MaterialApp( + AdsCupertinoApp( home: ManagerView(model: m, onQuit: () async {}), ), ); expect(find.text('test-phone'), findsOneWidget); expect(find.text('其他客户端占用'), findsOneWidget); - await tester.enterText(find.byType(TextField), 'test'); + await tester.enterText(find.byType(CupertinoTextField), 'test'); await tester.pumpAndSettle(); expect(find.text('busy-phone'), findsNothing); await tester.tap(find.text('连接配置')); diff --git a/flutter_manager/test/windows_usb_test.dart b/flutter_manager/test/windows_usb_test.dart index 8c41b39..739c36f 100644 --- a/flutter_manager/test/windows_usb_test.dart +++ b/flutter_manager/test/windows_usb_test.dart @@ -1,5 +1,7 @@ import 'dart:io'; +import 'package:ads_manager/ui/app_widgets.dart' as ads; + import 'package:material_ui/material_ui.dart'; import 'package:ads_manager/ui/manager_model.dart'; import 'package:ads_manager/ui/manager_view.dart'; @@ -24,7 +26,10 @@ void main() { ), ), ); - final toggle = find.widgetWithText(SwitchListTile, '挂载为 USB 设备 · Windows'); + final toggle = find.widgetWithText( + ads.SwitchListTile, + '挂载为 USB 设备 · Windows', + ); await tester.ensureVisible(toggle); await tester.tap(toggle); await tester.pumpAndSettle(); @@ -32,7 +37,7 @@ void main() { expect(find.text('安装驱动'), findsOneWidget); await tester.tap(find.text('暂不安装')); await tester.pumpAndSettle(); - expect(tester.widget(toggle).value, false); + expect(tester.widget(toggle).value, false); expect(model.repository.settings.usbMode, false); await tester.pumpWidget(const SizedBox()); model.dispose(); diff --git a/server/main.go b/server/main.go index ad4353b..2b0353a 100644 --- a/server/main.go +++ b/server/main.go @@ -188,14 +188,35 @@ func (b *broker) agentEndpoint(w http.ResponseWriter, r *http.Request) { } func (b *broker) devicesEndpoint(w http.ResponseWriter, r *http.Request) { type device struct { - ID string `json:"id"` - Busy bool `json:"busy"` + ID string `json:"id"` + Busy bool `json:"busy"` + AgentID string `json:"agent_id,omitempty"` + ComputerName string `json:"computer_name,omitempty"` } devices := []device{} b.mu.Lock() for id, a := range b.agents { if a.ws != nil { - devices = append(devices, device{id, b.leases[id] != nil}) + item := device{ID: id, Busy: b.leases[id] != nil} + for agentID, m := range b.managers { + if m.ws == nil { + continue + } + for _, phone := range m.status.Devices { + if phone.ID == id { + item.AgentID = agentID + item.ComputerName = m.status.Name + if item.ComputerName == "" { + item.ComputerName = m.status.Hostname + } + break + } + } + if item.AgentID != "" { + break + } + } + devices = append(devices, item) } } b.mu.Unlock() diff --git a/server/main_test.go b/server/main_test.go index 0efeea8..fc0695f 100644 --- a/server/main_test.go +++ b/server/main_test.go @@ -150,3 +150,29 @@ func TestAgentDisconnectReleasesOwnership(t *testing.T) { time.Sleep(time.Millisecond) } } + +func TestClientDeviceListIncludesComputerName(t *testing.T) { + b, base := testServer(t) + b.mu.Lock() + b.agents["phone"] = &agent{id: "phone", ws: &websocket.Conn{}} + b.managers["host"] = &manager{ws: &websocket.Conn{}, status: managedStatus{Name: "Office PC", Hostname: "desktop", Devices: []managedDevice{{ID: "phone"}}}} + b.mu.Unlock() + req, _ := http.NewRequest("GET", base+"/v1/devices", nil) + req.Header.Set("Authorization", "Bearer "+testClientToken) + resp, err := http.DefaultClient.Do(req) + if err != nil { + t.Fatal(err) + } + defer resp.Body.Close() + var rows []struct { + ID string `json:"id"` + Agent string `json:"agent_id"` + Computer string `json:"computer_name"` + } + if err = json.NewDecoder(resp.Body).Decode(&rows); err != nil { + t.Fatal(err) + } + if len(rows) != 1 || rows[0].Agent != "host" || rows[0].Computer != "Office PC" { + t.Fatalf("wrong computer association: %+v", rows) + } +}