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

+40 -1
View File
@@ -24,7 +24,7 @@ internal static class Program
Exception? failure = null;
Dispatcher.UIThread.Post(async () =>
{
try { if (args.Contains("--multi")) await RunMultiAsync(args.Contains("--usb")); else await RunAsync(args.Contains("--live"), args.Contains("--screen"), args.Contains("--usb")); }
try { if (args.Contains("--agents")) await RunAgentsAsync(args.Contains("--local-agent")); else if (args.Contains("--multi")) await RunMultiAsync(args.Contains("--usb")); else await RunAsync(args.Contains("--live"), args.Contains("--screen"), args.Contains("--usb")); }
catch (Exception error) { failure = error; }
finally { finished.Cancel(); }
});
@@ -48,6 +48,45 @@ internal static class Program
}
}
private static async Task RunAgentsAsync(bool local)
{
var root=DesktopPaths.ProjectRoot()!;
using var vm=new MainViewModel(Path.Combine(root,"work","agent-gui-smoke",Guid.NewGuid().ToString("N")),backgroundMonitoring:false,loadLocalCredentials:true);
var m=vm.AgentManager;m.AutoRefresh=false;m.LocalMode=local;
if(local)m.ConfigPath=Environment.GetEnvironmentVariable("ADS_TEST_AGENT_CONFIG")!;
var id=Environment.GetEnvironmentVariable("ADS_TEST_MANAGED_AGENT")!;
var window=new MainWindow{DataContext=vm};window.Show();
window.FindControl<TabControl>("MainTabs")!.SelectedItem=window.FindControl<TabItem>("AgentManagementTab");
async Task WaitState(Func<bool> predicate,string message){var deadline=DateTime.UtcNow.AddSeconds(50);while(!predicate()){await m.RefreshAgentsCommand.ExecuteAsync(null);m.SelectedAgent=m.Agents.FirstOrDefault(a=>a.Id==id);if(DateTime.UtcNow>deadline)throw new InvalidOperationException(message+": "+m.Notice);await Task.Delay(300);}}
try {
await WaitState(()=>m.SelectedAgent?.Id==id&&m.SelectedAgent.Online,"Agent not discovered");
await m.LoadConfigCommand.ExecuteAsync(null);
using(var config=System.Text.Json.JsonDocument.Parse(m.ConfigJson))Require(config.RootElement.GetProperty("id").GetString()==id,"Wrong agent configuration");
var node=System.Text.Json.Nodes.JsonNode.Parse(m.ConfigJson)!;node["name"]="GUI managed test";m.ConfigJson=node.ToJsonString();await m.SaveConfigCommand.ExecuteAsync(null);
await WaitState(()=>m.SelectedAgent?.Status.Name=="GUI managed test","Config mutation not applied");
m.DeviceId=id+"-phone";m.Target="127.0.0.1:9";await m.AddDeviceCommand.ExecuteAsync(null);
await WaitState(()=>m.AgentDevices.Any(d=>d.Id==m.DeviceId),"Phone add not visible");
m.SelectedManagedDevice=m.AgentDevices.Single(d=>d.Id==m.DeviceId);await m.DisableDeviceCommand.ExecuteAsync(null);
await WaitState(()=>m.AgentDevices.Any(d=>d.Id==m.DeviceId&&!d.Enabled),"Phone disable failed");
await m.EnableDeviceCommand.ExecuteAsync(null);await WaitState(()=>m.AgentDevices.Any(d=>d.Id==m.DeviceId&&d.Enabled),"Phone enable failed");
await m.ReadLogsCommand.ExecuteAsync(null);Require(m.RemoteLogText.Length>0,"Managed logs were empty");
var view=window.GetVisualDescendants().OfType<AgentManagementView>().Single();
Require(view.FindControl<TextBox>("AgentConfigBox")?.Text==m.ConfigJson,"Agent config binding failed");
using(var frame=window.CaptureRenderedFrame())frame?.Save(Path.Combine(root,"work",local?"agent-local.png":"agent-management.png"));
await m.RemoveDeviceCommand.ExecuteAsync(null);await WaitState(()=>m.AgentDevices.All(d=>d.Id!=m.DeviceId),"Phone removal failed");
var pid=m.SelectedAgent!.Status.Pid;await m.RestartAgentCommand.ExecuteAsync(null);
await WaitState(()=>m.SelectedAgent?.Online==true&&m.SelectedAgent.Status.Pid>0&&m.SelectedAgent.Status.Pid!=pid,"Supervisor restart failed");
Require(!m.ConfigJson.Contains(m.AdminToken)||m.AdminToken.Length==0,"Admin token leaked to config");
Require(!m.RemoteLogText.Contains(m.AdminToken)||m.AdminToken.Length==0,"Admin token leaked to logs");
var oldPath=m.ConfigPath;var oldServer=vm.Server;
if(local)m.ConfigPath+=".different";else vm.Server="wss://changed-center.invalid/ads";
await m.LoadConfigCommand.ExecuteAsync(null);
Require(m.Notice.Contains("先刷新"),"A stale agent list allowed a request to a different source");
m.ConfigPath=oldPath;vm.Server=oldServer;
Console.WriteLine("PASS: "+(local?"local IPC":"remote admin")+" GUI status, config, device add/enable/disable/remove, logs, supervised restart and bindings");
} finally {await vm.ShutdownAsync();window.Close();}
}
private static async Task RunMultiAsync(bool usb)
{
var root = DesktopPaths.ProjectRoot()!;
+54
View File
@@ -0,0 +1,54 @@
using System.Net.Http.Headers;
using System.Net.Http.Json;
using System.Text.Json;
using System.Text.Json.Serialization;
namespace Ads.Desktop;
public sealed record ManagedDevice(
string Id, string? Target, [property:JsonPropertyName("adb_serial")] string? AdbSerial,
[property:JsonPropertyName("adb_server")] string? AdbServer,
[property:JsonPropertyName("device_port")] int DevicePort, bool Enabled, bool Connected,
[property:JsonPropertyName("last_error")] string? LastError)
{
public string Description => $"{Id} · {(Enabled ? Connected ? LastError==null ? "已注册" : "转发异常" : "等待注册" : "已停用")} · {Target ?? AdbSerial}";
}
public sealed record ManagedStatus(string Id, string Name, string Hostname, string Os, string Arch, string Version, int Pid,
[property:JsonPropertyName("uptime_seconds")] long UptimeSeconds, bool Supervised, long Revision, string Instance, ManagedDevice[] Devices);
public sealed record ManagedAgent(string Id, bool Online, [property:JsonPropertyName("last_seen")] long LastSeen, ManagedStatus Status)
{
public string Description => $"{(string.IsNullOrWhiteSpace(Status.Name) ? Id : Status.Name)} · {(Online ? "在线" : "离线")} · {Status.Os} · {Status.Devices.Length} 台手机";
public string Details => $"{Id} · {Status.Hostname} · {Status.Os}/{Status.Arch} · v{Status.Version} · PID {Status.Pid} · 配置版本 {Status.Revision}";
}
public sealed record ManagementResponse(bool Ok, JsonElement? Data, string? Error)
{
public JsonElement Value() => Ok && Data.HasValue ? Data.Value : throw new InvalidOperationException(Error ?? "Agent 管理请求失败。");
}
public static class AgentManagementApi
{
private static readonly JsonSerializerOptions Json = new(JsonSerializerDefaults.Web);
private static Uri UriFor(RelayOptions options, string endpoint) => new UriBuilder(options.DevicesUri) {
Path = options.BaseUri.AbsolutePath.TrimEnd('/') + endpoint
}.Uri;
public static async Task<ManagedAgent[]> ListAsync(RelayOptions options, CancellationToken cancellation)
{
using var http = RelayApi.CreateClient(options);
using var request = new HttpRequestMessage(HttpMethod.Get, UriFor(options,"/v3/agents"));
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer",options.Token);
using var response = await http.SendAsync(request,cancellation); Check(response);
return await response.Content.ReadFromJsonAsync<ManagedAgent[]>(Json,cancellation) ?? [];
}
public static async Task<JsonElement> CallAsync(RelayOptions options, string agent, object operation, CancellationToken cancellation)
{
using var http = RelayApi.CreateClient(options); http.Timeout=TimeSpan.FromSeconds(20);
var uri = new UriBuilder(UriFor(options,"/v3/rpc")) { Query="agent="+Uri.EscapeDataString(agent) }.Uri;
using var request = new HttpRequestMessage(HttpMethod.Post,uri) { Content=JsonContent.Create(operation) };
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer",options.Token);
using var response = await http.SendAsync(request,cancellation); Check(response);
return (await response.Content.ReadFromJsonAsync<ManagementResponse>(Json,cancellation) ?? throw new InvalidOperationException("管理响应为空。")).Value();
}
private static void Check(HttpResponseMessage response)
{
if (response.StatusCode==System.Net.HttpStatusCode.Unauthorized) throw new InvalidOperationException("管理员凭据无效,需要 admin.env;手机连接令牌不具有管理权限。");
if (response.StatusCode==System.Net.HttpStatusCode.ServiceUnavailable) throw new InvalidOperationException("控制中心尚未配置 ADS_ADMIN_TOKEN。");
response.EnsureSuccessStatusCode();
}
}
@@ -0,0 +1,33 @@
<UserControl xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" x:Class="Ads.Desktop.AgentManagementView">
<UserControl.Styles>
<Style Selector="Border.agentCard"><Setter Property="Background" Value="#192230"/><Setter Property="CornerRadius" Value="10"/><Setter Property="Padding" Value="16"/></Style>
<Style Selector="Button"><Setter Property="Padding" Value="12,8"/><Setter Property="Margin" Value="0,0,8,6"/></Style>
<Style Selector="TextBox"><Setter Property="Margin" Value="0,4,0,10"/></Style>
</UserControl.Styles>
<Grid RowDefinitions="Auto,*,Auto" Margin="0,14,0,0">
<StackPanel>
<WrapPanel><CheckBox x:Name="LocalAgentMode" Content="管理本机 Agent" IsChecked="{Binding LocalMode}" IsEnabled="{Binding !IsBusy}" Margin="0,0,20,8"/><CheckBox Content="自动刷新" IsChecked="{Binding AutoRefresh}"/><Button x:Name="RefreshAgentsButton" Content="刷新 Agent" Command="{Binding RefreshAgentsCommand}" IsEnabled="{Binding !IsBusy}" Margin="20,0,0,10"/></WrapPanel>
<StackPanel IsVisible="{Binding !LocalMode}"><TextBlock Text="远程管理使用工作台的控制中心地址,需要独立的管理员凭据。" TextWrapping="Wrap"/><Grid ColumnDefinitions="*,Auto"><TextBox x:Name="AdminTokenBox" Text="{Binding AdminToken}" PasswordChar="●" Watermark="ADS_ADMIN_TOKEN"/><Button Grid.Column="1" Content="导入 admin.env" Click="ImportAdminClick" Margin="12,4,0,10"/></Grid></StackPanel>
<StackPanel IsVisible="{Binding LocalMode}"><TextBlock Text="本机配置路径"/><TextBox Text="{Binding ConfigPath}"/><WrapPanel><Button Content="启动后台 Agent" Command="{Binding StartLocalCommand}"/><Button Content="安装开机服务" Command="{Binding InstallServiceCommand}"/></WrapPanel></StackPanel>
</StackPanel>
<Grid Grid.Row="1" ColumnDefinitions="300,*">
<Border Classes="agentCard" Margin="0,0,14,0"><Grid RowDefinitions="Auto,*"><TextBlock Text="Agent / 被控电脑" FontSize="18" FontWeight="SemiBold"/><ListBox x:Name="AgentList" Grid.Row="1" ItemsSource="{Binding Agents}" SelectedItem="{Binding SelectedAgent}" Margin="0,10,0,0"><ListBox.ItemTemplate><DataTemplate><StackPanel Spacing="5" Margin="4,8"><TextBlock Text="{Binding Id}" FontSize="16"/><TextBlock Text="{Binding Description}" TextWrapping="Wrap" Foreground="#A8B7CC"/></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox></Grid></Border>
<ScrollViewer Grid.Column="1"><StackPanel Spacing="14">
<Border Classes="agentCard"><StackPanel Spacing="10"><TextBlock Text="{Binding SelectedAgent.Details}" TextWrapping="Wrap" Foreground="#66D9C0"/><WrapPanel><Button x:Name="LoadAgentConfigButton" Content="读取配置" Command="{Binding LoadConfigCommand}"/><Button Content="重启 Agent" Command="{Binding RestartAgentCommand}"/></WrapPanel><TextBlock Text="重启由监督进程执行,设备连接会短暂中断。" FontSize="12" Foreground="#A8B7CC"/></StackPanel></Border>
<Border Classes="agentCard"><StackPanel Spacing="8">
<TextBlock Text="手机管理" FontSize="18" FontWeight="SemiBold"/>
<ListBox x:Name="ManagedDevicesList" ItemsSource="{Binding AgentDevices}" SelectedItem="{Binding SelectedManagedDevice}" MinHeight="70" MaxHeight="180"><ListBox.ItemTemplate><DataTemplate><TextBlock Text="{Binding Description}" TextWrapping="Wrap" Margin="3,7"/></DataTemplate></ListBox.ItemTemplate></ListBox>
<WrapPanel><Button Content="启用" Command="{Binding EnableDeviceCommand}"/><Button Content="停用" Command="{Binding DisableDeviceCommand}"/><Button Content="移除配置" Command="{Binding RemoveDeviceCommand}"/></WrapPanel>
<Grid ColumnDefinitions="*,*"><StackPanel><TextBlock Text="设备 ID"/><TextBox Text="{Binding DeviceId}" Watermark="home-phone"/></StackPanel><StackPanel Grid.Column="1" Margin="12,0,0,0"><TextBlock Text="手机 adbd 地址"/><TextBox Text="{Binding Target}" Watermark="192.168.1.10:5555"/></StackPanel></Grid>
<Expander Header="通过已有 ADB server 接入"><StackPanel><TextBlock Text="ADB 序列号(与手机地址二选一)"/><TextBox Text="{Binding AdbSerial}"/><TextBlock Text="ADB server 地址(留空使用 Agent 默认值)"/><TextBox Text="{Binding AdbServer}" Watermark="127.0.0.1:5037"/><TextBlock Text="此模式仍要求手机启用 TCP adbd。" Foreground="#A8B7CC"/></StackPanel></Expander>
<Button x:Name="AddManagedDeviceButton" Content="添加手机" Command="{Binding AddDeviceCommand}" HorizontalAlignment="Left"/>
</StackPanel></Border>
<Border Classes="agentCard"><StackPanel Spacing="8"><TextBlock Text="Agent 配置" FontSize="18" FontWeight="SemiBold"/><TextBlock Text="修改设备或地址会重建受影响的连接;Agent ID 保持固定。" Foreground="#A8B7CC" TextWrapping="Wrap"/><TextBox x:Name="AgentConfigBox" Text="{Binding ConfigJson}" AcceptsReturn="True" FontFamily="Cascadia Mono,Consolas" FontSize="12" MinHeight="200" MaxHeight="380" ScrollViewer.VerticalScrollBarVisibility="Auto"/><Button Content="保存并应用配置" Command="{Binding SaveConfigCommand}" HorizontalAlignment="Left"/>
<StackPanel IsVisible="{Binding LocalMode}"><TextBlock Text="首次设置:填写上方配置及设备端凭据后初始化,再启动后台 Agent。" TextWrapping="Wrap"/><TextBox Text="{Binding EnrollmentToken}" PasswordChar="●" Watermark="ADS_AGENT_TOKEN"/><WrapPanel><Button Content="导入 agent.env" Click="ImportEnrollmentClick"/><Button Content="初始化本机配置" Command="{Binding InitializeLocalCommand}"/></WrapPanel></StackPanel>
</StackPanel></Border>
<Border Classes="agentCard"><StackPanel Spacing="8"><WrapPanel><Button Content="读取日志" Command="{Binding ReadLogsCommand}"/><CheckBox Content="持续跟随日志" IsChecked="{Binding FollowLogs}"/></WrapPanel><TextBox x:Name="AgentLogsBox" Text="{Binding RemoteLogText}" IsReadOnly="True" AcceptsReturn="True" FontFamily="Cascadia Mono,Consolas" FontSize="12" Height="200" ScrollViewer.VerticalScrollBarVisibility="Auto"/></StackPanel></Border>
</StackPanel></ScrollViewer>
</Grid>
<TextBlock Grid.Row="2" x:Name="AgentNotice" Text="{Binding Notice}" TextWrapping="Wrap" Foreground="#A8B7CC" Margin="0,12,0,0"/>
</Grid>
</UserControl>
@@ -0,0 +1,19 @@
using Avalonia.Controls;
using Avalonia.Interactivity;
using Avalonia.Platform.Storage;
namespace Ads.Desktop;
public partial class AgentManagementView : UserControl
{
public AgentManagementView()=>InitializeComponent();
private async Task Import(bool enrollment)
{
if(DataContext is not AgentManagementViewModel vm)return;
try {
var top=TopLevel.GetTopLevel(this);if(top==null)return;
var files=await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions{Title=enrollment?"选择 agent.env":"选择 admin.env",AllowMultiple=false,FileTypeFilter=[new FilePickerFileType("环境配置"){Patterns=["*.env"]}]});
if(files.FirstOrDefault()?.TryGetLocalPath() is {} path){if(enrollment)vm.ImportEnrollment(path);else vm.ImportAdmin(path);}
}catch(Exception error){vm.Notice=error.Message;}
}
private async void ImportAdminClick(object? sender,RoutedEventArgs e)=>await Import(false);
private async void ImportEnrollmentClick(object? sender,RoutedEventArgs e)=>await Import(true);
}
@@ -0,0 +1,203 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text.Json;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace Ads.Desktop;
public partial class AgentManagementViewModel : ObservableObject, IDisposable
{
[ObservableProperty] private bool localMode;
[ObservableProperty] private string adminToken = "";
[ObservableProperty] private string enrollmentToken = "";
[ObservableProperty] private string configPath = DefaultConfig();
[ObservableProperty] private ManagedAgent? selectedAgent;
[ObservableProperty] private ManagedDevice? selectedManagedDevice;
[ObservableProperty] private string deviceId = "";
[ObservableProperty] private string target = "";
[ObservableProperty] private string adbSerial = "";
[ObservableProperty] private string adbServer = "";
[ObservableProperty] private string configJson = "";
[ObservableProperty] private string remoteLogText = "";
[ObservableProperty] private string notice = "管理员凭据用于远程管理;也可切换为管理本机 Agent。";
[ObservableProperty] private bool isBusy;
[ObservableProperty] private bool autoRefresh = true;
[ObservableProperty] private bool followLogs;
public ObservableCollection<ManagedAgent> Agents { get; } = new();
public ObservableCollection<ManagedDevice> AgentDevices { get; } = new();
private readonly Func<(string Server,string Origin)> server;
private readonly Action<string> log;
private readonly CancellationTokenSource lifetime = new();
private readonly DispatcherTimer timer;
private readonly HashSet<string> secrets = new(StringComparer.Ordinal);
private bool polling, disposed;
private long logCursor;
private string logInstance = "";
private string listedSource = "";
private string SourceKey()=>LocalMode ? "local:"+ConfigPath : "remote:"+JsonSerializer.Serialize(new[]{server().Server,server().Origin});
private string? lastError;
public AgentManagementViewModel(Func<(string,string)> server, Action<string>? logger=null, bool background=true, bool credentials=true)
{
this.server=server; log=logger ?? (_=>{});
var (initialServer,initialOrigin)=server();
ConfigJson=JsonSerializer.Serialize(new {version=1,id="local-pc",name=Environment.MachineName,server=initialServer,connect_address=string.IsNullOrWhiteSpace(initialOrigin)?null:initialOrigin,adb_server="127.0.0.1:5037",devices=Array.Empty<object>()}, new JsonSerializerOptions{WriteIndented=true});
if(credentials) {
var path=DesktopPaths.ProjectRoot() is {} root ? Path.Combine(root,"config","private","admin.env") : Path.Combine(AppContext.BaseDirectory,"admin.env");
if(File.Exists(path)) { try { ImportAdmin(path); } catch { } }
}
timer=new DispatcherTimer{Interval=TimeSpan.FromSeconds(5)};
timer.Tick+=async(_,_)=>await PollAsync(); if(background)timer.Start();
}
public static string DefaultConfig() => OperatingSystem.IsWindows()
? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),"AndroidDeviceStreaming","agent","agent.json")
: Path.Combine(Environment.GetEnvironmentVariable("XDG_CONFIG_HOME") ?? Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.UserProfile),".config"),"ads","agent.json");
public void StartMonitoring()=>timer.Start();
private string Redact(string value) { foreach(var secret in secrets) value=value.Replace(secret,"[REDACTED]",StringComparison.Ordinal);return value; }
partial void OnAdminTokenChanged(string value){if(value.Length>0)secrets.Add(value);}
partial void OnEnrollmentTokenChanged(string value){if(value.Length>0)secrets.Add(value);}
partial void OnSelectedAgentChanged(ManagedAgent? value)
{
var selected=SelectedManagedDevice?.Id; AgentDevices.Clear();
foreach(var device in value?.Status.Devices ?? [])AgentDevices.Add(device);
SelectedManagedDevice=AgentDevices.FirstOrDefault(d=>d.Id==selected) ?? AgentDevices.FirstOrDefault();
logCursor=0;logInstance="";RemoteLogText="";UpdateCommands();
}
partial void OnSelectedManagedDeviceChanged(ManagedDevice? value)=>UpdateCommands();
partial void OnIsBusyChanged(bool value)=>UpdateCommands();
partial void OnLocalModeChanged(bool value){Agents.Clear();SelectedAgent=null;Notice=value?"管理本机 Agent,不需要管理员令牌。":"管理控制中心中的 Agent,需要独立管理员凭据。";}
private bool CanManage()=>!IsBusy && SelectedAgent?.Online==true;
private bool CanDevice()=>CanManage() && SelectedManagedDevice!=null;
private bool CanRestart()=>CanManage() && SelectedAgent?.Status.Supervised==true;
private bool CanLocal()=>!IsBusy && LocalMode;
private void UpdateCommands()
{
LoadConfigCommand.NotifyCanExecuteChanged();SaveConfigCommand.NotifyCanExecuteChanged();AddDeviceCommand.NotifyCanExecuteChanged();
RemoveDeviceCommand.NotifyCanExecuteChanged();EnableDeviceCommand.NotifyCanExecuteChanged();DisableDeviceCommand.NotifyCanExecuteChanged();
ReadLogsCommand.NotifyCanExecuteChanged();RestartAgentCommand.NotifyCanExecuteChanged();
InitializeLocalCommand.NotifyCanExecuteChanged();StartLocalCommand.NotifyCanExecuteChanged();InstallServiceCommand.NotifyCanExecuteChanged();
}
public void ImportAdmin(string path)
{
if(new FileInfo(path).Length>65536)throw new InvalidOperationException("凭据文件过大。");
var token=File.ReadLines(path).Select(l=>l.Split('=',2)).FirstOrDefault(p=>p.Length==2&&p[0].Trim()=="ADS_ADMIN_TOKEN")?.ElementAt(1).Trim();
if(string.IsNullOrEmpty(token)||token.Length<32||token.Contains('\r')||token.Contains('\n'))throw new InvalidOperationException("文件中没有有效的 ADS_ADMIN_TOKEN。");
AdminToken=token;Notice="管理员凭据已加载,内容仅保存在内存中。";
}
public void ImportEnrollment(string path)
{
if(new FileInfo(path).Length>65536)throw new InvalidOperationException("凭据文件过大。");
var value=File.ReadLines(path).FirstOrDefault(l=>l.StartsWith("ADS_AGENT_TOKEN=",StringComparison.Ordinal))?[16..].Trim();
if(string.IsNullOrEmpty(value)||value.Length<32)throw new InvalidOperationException("文件中没有有效的 ADS_AGENT_TOKEN。");
EnrollmentToken=value;Notice="设备端凭据已加载,仅供本机初始化使用。";
}
private RelayOptions Options(){var(s,o)=server();return RelayOptions.Parse(s,o,AdminToken);}
private async Task Guard(Func<Task> action)
{
if(IsBusy)return;IsBusy=true;
try { await action(); }
catch(OperationCanceledException)when(lifetime.IsCancellationRequested){}
catch(Exception error){Notice=Redact(error.Message);log("[Agent管理] "+Notice);}
finally{IsBusy=false;}
}
private async Task<JsonElement> LocalRequestAsync(object request)
{
var executable=DesktopPaths.ResolveTool(DesktopPaths.FindTool("adsctl"),"adsctl");
var info=ProcessTools.CreateStartInfo(executable,["--json","--config",ConfigPath,"request"]);info.RedirectStandardInput=true;
using var process=Process.Start(info) ?? throw new InvalidOperationException("adsctl 无法启动。");
var output=process.StandardOutput.ReadToEndAsync();var error=process.StandardError.ReadToEndAsync();
await process.StandardInput.WriteAsync(JsonSerializer.Serialize(request));process.StandardInput.Close();
try { await process.WaitForExitAsync(lifetime.Token).WaitAsync(TimeSpan.FromSeconds(20),lifetime.Token); }
catch { if(!process.HasExited)process.Kill(entireProcessTree:true);throw; }
if(process.ExitCode!=0)throw new InvalidOperationException((await error).Trim());
using var value=JsonDocument.Parse(await output);return value.RootElement.Clone();
}
private Task<JsonElement> CallAsync(object request,string? agent=null) {
if(listedSource!=SourceKey())throw new InvalidOperationException("管理地址或配置路径已改变,请先刷新 Agent 列表。");
return LocalMode ? LocalRequestAsync(request) : AgentManagementApi.CallAsync(Options(),agent ?? SelectedAgent?.Id ?? throw new InvalidOperationException("请选择 Agent。"),request,lifetime.Token);
}
private async Task RefreshCoreAsync()
{
var selected=SelectedAgent?.Id;var selectedDevice=SelectedManagedDevice?.Id;
var local=LocalMode;var path=ConfigPath;var source=server();
ManagedAgent[] rows;
if(LocalMode) {
var value=await LocalRequestAsync(new{op="status"});
var status=value.Deserialize<ManagedStatus>(new JsonSerializerOptions(JsonSerializerDefaults.Web)) ?? throw new InvalidOperationException("Agent 状态无效。");
rows=[new ManagedAgent(status.Id,true,DateTimeOffset.UtcNow.ToUnixTimeSeconds(),status)];
}else rows=await AgentManagementApi.ListAsync(Options(),lifetime.Token);
if(local!=LocalMode||path!=ConfigPath||source!=server())return;
listedSource=SourceKey();
Agents.Clear();foreach(var row in rows)Agents.Add(row);
var chosen=Agents.FirstOrDefault(r=>r.Id==selected) ?? Agents.FirstOrDefault(r=>r.Online) ?? Agents.FirstOrDefault();
// Preserve log cursor and draft configuration during periodic metadata refreshes.
var cursor=logCursor;var instance=logInstance;var text=RemoteLogText;
SelectedAgent=chosen;
if(selected==chosen?.Id){logCursor=cursor;logInstance=instance;RemoteLogText=text;}
SelectedManagedDevice=AgentDevices.FirstOrDefault(d=>d.Id==selectedDevice) ?? AgentDevices.FirstOrDefault();
Notice=$"{rows.Length} 个 Agent · {rows.Count(r=>r.Online)} 个在线";lastError=null;
}
[RelayCommand]private Task RefreshAgentsAsync()=>Guard(RefreshCoreAsync);
[RelayCommand(CanExecute=nameof(CanManage))]private Task LoadConfigAsync()=>Guard(async()=>{
var value=await CallAsync(new{op="config_get"});ConfigJson=JsonSerializer.Serialize(value,new JsonSerializerOptions{WriteIndented=true});Notice="已读取配置,凭据不在配置中。";
});
[RelayCommand(CanExecute=nameof(CanManage))]private Task SaveConfigAsync()=>Guard(async()=>{
using var doc=JsonDocument.Parse(ConfigJson);await CallAsync(new{op="config_set",config=doc.RootElement});await RefreshCoreAsync();Notice="配置已持久化并应用。受影响设备将重建连接。";
});
[RelayCommand(CanExecute=nameof(CanManage))]private Task AddDeviceAsync()=>Guard(async()=>{
if(string.IsNullOrWhiteSpace(Target)==string.IsNullOrWhiteSpace(AdbSerial))throw new InvalidOperationException("手机地址与 ADB 序列号必须填写其中一项。");
await CallAsync(new{op="device_add",device=new{id=DeviceId.Trim(),target=string.IsNullOrWhiteSpace(Target)?null:Target.Trim(),adb_serial=string.IsNullOrWhiteSpace(AdbSerial)?null:AdbSerial.Trim(),adb_server=string.IsNullOrWhiteSpace(AdbServer)?null:AdbServer.Trim(),device_port=5555,enabled=true}});
await RefreshCoreAsync();Notice="手机已添加并启动连接。";
});
private Task DeviceOperation(string operation,bool? enabled=null)=>Guard(async()=>{
var id=SelectedManagedDevice?.Id ?? throw new InvalidOperationException("请选择手机。");
await CallAsync(enabled.HasValue?new{op=operation,id,enabled=enabled.Value}:(object)new{op=operation,id});await RefreshCoreAsync();
});
[RelayCommand(CanExecute=nameof(CanDevice))]private Task RemoveDeviceAsync()=>DeviceOperation("device_remove");
[RelayCommand(CanExecute=nameof(CanDevice))]private Task EnableDeviceAsync()=>DeviceOperation("device_enable",true);
[RelayCommand(CanExecute=nameof(CanDevice))]private Task DisableDeviceAsync()=>DeviceOperation("device_enable",false);
private async Task LogsCoreAsync()
{
var page=await CallAsync(new{op="logs",after=logCursor,limit=50});var instance=page.GetProperty("instance").GetString() ?? "";
if(logInstance.Length>0&&instance!=logInstance){logCursor=0;RemoteLogText="";logInstance=instance;return;}
logInstance=instance;logCursor=page.GetProperty("next").GetInt64();
foreach(var entry in page.GetProperty("entries").EnumerateArray())RemoteLogText+=Redact($"{entry.GetProperty("time")} {entry.GetProperty("level")} {entry.GetProperty("message").GetString()}\n");
if(RemoteLogText.Length>100000)RemoteLogText=RemoteLogText[^100000..];
}
[RelayCommand(CanExecute=nameof(CanManage))]private Task ReadLogsAsync()=>Guard(LogsCoreAsync);
[RelayCommand(CanExecute=nameof(CanRestart))]private Task RestartAgentAsync()=>Guard(async()=>{await CallAsync(new{op="restart"});Notice="监督进程将重启 Agent,手机连接会短暂中断。";});
[RelayCommand(CanExecute=nameof(CanLocal))]private Task InitializeLocalAsync()=>Guard(async()=>{
if(File.Exists(ConfigPath))throw new InvalidOperationException("本机配置已存在,请读取后修改。");
using var doc=JsonDocument.Parse(ConfigJson);var root=doc.RootElement;
var args=new List<string>{"--json","--config",ConfigPath,"--server",root.GetProperty("server").GetString()!,"init","--id",root.GetProperty("id").GetString()!,"--name",root.GetProperty("name").GetString()!};
// Origin is a global CLI option and must precede the subcommand.
if(root.TryGetProperty("connect_address",out var origin)&&origin.ValueKind==JsonValueKind.String)args.InsertRange(5,["--connect-address",origin.GetString()!]);
var info=ProcessTools.CreateStartInfo(DesktopPaths.ResolveTool(DesktopPaths.FindTool("adsctl"),"adsctl"),args);info.Environment["ADS_AGENT_TOKEN"]=EnrollmentToken;
var result=await ProcessTools.RunAsync(info,lifetime.Token);if(result.ExitCode!=0)throw new InvalidOperationException(result.Error);
EnrollmentToken="";Notice="本机配置已初始化,可启动后台 Agent 后应用设备配置。";
});
[RelayCommand(CanExecute=nameof(CanLocal))]private Task StartLocalAsync()=>Guard(async()=>{
try { await LocalRequestAsync(new{op="status"});Notice="本机 Agent 已在运行。";return; } catch(InvalidOperationException){}
var info=ProcessTools.CreateStartInfo(DesktopPaths.ResolveTool(DesktopPaths.FindTool("ads-agent"),"ads-agent"),["--quiet","--supervise","--config",ConfigPath]);
info.RedirectStandardOutput=false;info.RedirectStandardError=false;
using var process=Process.Start(info) ?? throw new InvalidOperationException("Agent 启动失败。");
await Task.Delay(700,lifetime.Token);await RefreshCoreAsync();Notice="后台 Agent 已启动,退出托盘不会停止它。";
});
[RelayCommand(CanExecute=nameof(CanLocal))]private Task InstallServiceAsync()=>Guard(async()=>{
if(!OperatingSystem.IsWindows())throw new InvalidOperationException("请在终端运行 adsctl service install;系统级服务可加 --system。");
var info=new ProcessStartInfo(DesktopPaths.ResolveTool(DesktopPaths.FindTool("adsctl"),"adsctl")){UseShellExecute=true,Verb="runas",WindowStyle=ProcessWindowStyle.Hidden};
foreach(var value in new[]{"--config",ConfigPath,"service","install"})info.ArgumentList.Add(value);
using var process=Process.Start(info) ?? throw new InvalidOperationException("安装命令无法启动。");await process.WaitForExitAsync(lifetime.Token);
if(process.ExitCode!=0)throw new InvalidOperationException("服务安装失败,请在管理员终端使用 adsctl 检查错误。");
await RefreshCoreAsync();Notice="已配置无界面开机启动。";
});
private async Task PollAsync()
{
if(polling||disposed||IsBusy||!AutoRefresh||(!LocalMode&&AdminToken.Length<32))return;polling=true;IsBusy=true;
try { await RefreshCoreAsync();if(FollowLogs&&SelectedAgent?.Online==true)await LogsCoreAsync(); }
catch(OperationCanceledException)when(lifetime.IsCancellationRequested){}
catch(Exception error){var message=Redact(error.Message);Notice=message;if(message!=lastError){log("[Agent管理] "+message);lastError=message;}}
finally{polling=false;IsBusy=false;}
}
public void Dispose(){if(disposed)return;disposed=true;timer.Stop();lifetime.Cancel();lifetime.Dispose();}
}
+16 -7
View File
@@ -13,8 +13,13 @@ public partial class App : Application
{
if (ApplicationLifetime is IClassicDesktopStyleApplicationLifetime desktop)
{
var vm = new MainViewModel();
var window = new MainWindow { DataContext = vm };
var localAgentMode = desktop.Args?.Contains("--agent-tray") == true;
var vm = new MainViewModel(backgroundMonitoring: !localAgentMode, loadLocalCredentials: !localAgentMode);
Window window;
if(localAgentMode) {
vm.AgentManager.LocalMode=true;vm.AgentManager.StartMonitoring();
window=new Window {Title="ADS · 被控端 Agent 管理",Width=1100,Height=850,MinWidth=900,MinHeight=650,Background=Avalonia.Media.Brush.Parse("#10151F"),Content=new AgentManagementView{DataContext=vm.AgentManager,Margin=new Avalonia.Thickness(22)}};
} else window = new MainWindow { DataContext = vm };
desktop.MainWindow = window;
desktop.ShutdownMode = ShutdownMode.OnExplicitShutdown;
void Show() { window.Show(); window.WindowState = WindowState.Normal; window.Activate(); }
@@ -26,19 +31,23 @@ public partial class App : Application
finally { desktop.Shutdown(); }
}
var menu = new NativeMenu();
var show = new NativeMenuItem("打开设备工作台"); show.Click += (_, _) => Show(); menu.Items.Add(show);
menu.Items.Add(new NativeMenuItem("断开全部设备") { Command = vm.DisconnectAllCommand });
var show = new NativeMenuItem(localAgentMode ? "打开本机 Agent 管理" : "打开设备工作台"); show.Click += (_, _) => Show(); menu.Items.Add(show);
if(localAgentMode)menu.Items.Add(new NativeMenuItem("重启本机 Agent") {Command=vm.AgentManager.RestartAgentCommand});
else menu.Items.Add(new NativeMenuItem("断开全部设备") { Command = vm.DisconnectAllCommand });
menu.Items.Add(new NativeMenuItemSeparator());
var quit = new NativeMenuItem("退出并断开连接");
var quit = new NativeMenuItem(localAgentMode ? "退出托盘(Agent 继续运行)" : "退出并断开连接");
quit.Click += async (_, _) => await QuitAsync();
menu.Items.Add(quit);
using var stream = Avalonia.Platform.AssetLoader.Open(new Uri("avares://Ads.Desktop/Assets/app.png"));
var tray = new TrayIcon { ToolTipText = "ADS · Android 设备工作台", Icon = new WindowIcon(stream), Menu = menu, Command = new RelayCommand(Show) };
var tray = new TrayIcon { ToolTipText = localAgentMode ? "ADS · 本机 Agent 管理" : "ADS · Android 设备工作台", Icon = new WindowIcon(stream), Menu = menu, Command = new RelayCommand(Show) };
TrayIcon.SetIcons(this, new TrayIcons { tray });
vm.PropertyChanged += (_, change) => {
if (change.PropertyName is nameof(vm.ConnectionSummary))
if (!localAgentMode && change.PropertyName is nameof(vm.ConnectionSummary))
tray.ToolTipText = "ADS · " + vm.ConnectionSummary;
};
if(localAgentMode)vm.AgentManager.PropertyChanged += (_, change) => {
if(change.PropertyName is nameof(AgentManagementViewModel.Notice)) tray.ToolTipText="ADS Agent · "+vm.AgentManager.Notice;
};
window.Closing += async (_, e) => {
if (quitting) return;
e.Cancel = true;
+4 -2
View File
@@ -52,6 +52,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
[ObservableProperty] private bool isWorking;
[ObservableProperty] private bool isRefreshing;
public AgentManagementViewModel AgentManager { get; }
public ObservableCollection<RelayNode> RelayNodes { get; } = new();
public ObservableCollection<DeviceItem> Devices { get; } = new();
public ObservableCollection<string> Logs { get; } = new();
@@ -106,6 +107,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
if (File.Exists(credentialFile)) LoadCredentials(credentialFile, useOrigin: false);
}
Notice = Token.Length >= 32 ? "配置已就绪,正在等待刷新设备。" : "请在连接配置中导入 client.env。";
AgentManager = new AgentManagementViewModel(() => (Server, Origin), Log, backgroundMonitoring, loadLocalCredentials);
timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(3) };
timer.Tick += async (_, _) => await MonitorAsync();
if (backgroundMonitoring) timer.Start();
@@ -484,7 +486,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
public async Task ShutdownAsync()
{
timer.Stop(); lifetime.Cancel();
AgentManager.Dispose(); timer.Stop(); lifetime.Cancel();
await connectionGate.WaitAsync();
try { await DisconnectAllCoreAsync(); }
finally { connectionGate.Release(); }
@@ -493,7 +495,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
public void Dispose()
{
if (disposed) return;
disposed = true; timer.Stop(); lifetime.Cancel();
disposed = true; AgentManager.Dispose(); timer.Stop(); lifetime.Cancel();
foreach (var session in sessions.Values) { session.PropertyChanged -= ConnectionChanged; session.Dispose(); }
sessions.Clear(); Connections.Clear();
lifetime.Dispose();
+2 -1
View File
@@ -1,4 +1,4 @@
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
<Window xmlns="https://github.com/avaloniaui" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="using:Ads.Desktop"
x:Class="Ads.Desktop.MainWindow" Title="ADS · 公网设备工作台"
Width="1240" Height="880" MinWidth="980" MinHeight="700" Background="#10151F">
<Window.Styles>
@@ -99,6 +99,7 @@
</ScrollViewer>
</Grid>
</TabItem>
<TabItem x:Name="AgentManagementTab" Header="Agent 管理"><local:AgentManagementView DataContext="{Binding AgentManager}"/></TabItem>
<TabItem Header="连接配置">
<ScrollViewer>
<StackPanel Margin="4,18" MaxWidth="880" Spacing="16">
+1 -1
View File
@@ -14,7 +14,7 @@ public static class ProcessTools
RedirectStandardOutput = true, RedirectStandardError = true
};
foreach (var argument in arguments) info.ArgumentList.Add(argument);
foreach (var key in new[] { "ADB_SERVER_SOCKET", "ANDROID_ADB_SERVER_ADDRESS", "ANDROID_ADB_SERVER_PORT", "ADS_CLIENT_TOKEN", "ADS_AGENT_TOKEN", "ADS_CONNECT_ADDRESS" })
foreach (var key in new[] { "ADB_SERVER_SOCKET", "ANDROID_ADB_SERVER_ADDRESS", "ANDROID_ADB_SERVER_PORT", "ADS_CLIENT_TOKEN", "ADS_AGENT_TOKEN", "ADS_ADMIN_TOKEN", "ADS_CONNECT_ADDRESS" })
info.Environment.Remove(key);
info.Environment["NO_COLOR"] = "1";
return info;
+4
View File
@@ -72,3 +72,7 @@ ADB、USB/IP 和 scrcpy 转发端口分别自动分配,避开其他连接和
实现分工:MainViewModel 管理设备发现、连接集合、当前选择与批量操作;DeviceConnection 为每台设备持有进程、独立操作锁、USB 导出、状态文件和生命周期;ConnectionPorts 负责不终止外部监听者的端口分配。监控每个 ADB 可执行文件每轮仅查询一次 devices,再分别更新所有设备。
验证:`dotnet run --project Ads.Desktop.Smoke -c Debug -- --multi`,USB 模式加 `--usb`。需要 home-phone 与 smoke-multi-phone(可用 ADS_MULTI_SECOND_DEVICE 指定第二个已授权设备 ID),测试不会接管已占用设备。2026-11-12 使用两个独立设备别名映射到同一台测试手机,验证双 ADB/双 USB、不同端口/序列号、两个真实 scrcpy 视频、总览按钮绑定、重连/断开一个保留另一个以及释放全部租约。此验证覆盖并发通道,未作为多台物理手机的大规模负载测试。
## Agent 管理
工作台新增 Agent 管理页,与 Flutter 共用控制中心 v3 接口。支持多 Agent/多手机、本机私有 IPC、配置与日志、受监督重启;`--agent-tray` 可单独打开本机 Agent 管理窗口。发行包同时包含 adsctl 和 ads-agent,后台运行不依赖 GUI。完整安装及 CLI 示例见 [Agent 管理](../docs/agent-management.md)。