292 lines
22 KiB
C#
292 lines
22 KiB
C#
using Ads.Desktop;
|
|
using Avalonia;
|
|
using Avalonia.Controls;
|
|
using Avalonia.Headless;
|
|
using Avalonia.Threading;
|
|
using Avalonia.VisualTree;
|
|
|
|
internal static class Program
|
|
{
|
|
[STAThread]
|
|
public static int Main(string[] args)
|
|
{
|
|
if (args.Length == 2 && args[0] == "--port-child")
|
|
{
|
|
var listener = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, int.Parse(args[1]));
|
|
listener.Start();
|
|
Console.WriteLine("READY");
|
|
Console.Out.Flush();
|
|
Thread.Sleep(Timeout.Infinite);
|
|
return 0;
|
|
}
|
|
AppBuilder.Configure<App>().UseSkia().UseHeadless(new AvaloniaHeadlessPlatformOptions { UseHeadlessDrawing = false }).SetupWithoutStarting();
|
|
using var finished = new CancellationTokenSource();
|
|
Exception? failure = null;
|
|
Dispatcher.UIThread.Post(async () =>
|
|
{
|
|
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(); }
|
|
});
|
|
Dispatcher.UIThread.MainLoop(finished.Token);
|
|
if (failure != null) { Console.Error.WriteLine(failure); return 1; }
|
|
return 0;
|
|
}
|
|
|
|
private static void Require(bool condition, string message)
|
|
{
|
|
if (!condition) throw new InvalidOperationException(message);
|
|
}
|
|
|
|
private static async Task UntilAsync(Func<bool> condition, string message)
|
|
{
|
|
var deadline = DateTime.UtcNow.AddSeconds(60);
|
|
while (!condition())
|
|
{
|
|
if (DateTime.UtcNow > deadline) throw new InvalidOperationException(message);
|
|
await Task.Delay(150);
|
|
}
|
|
}
|
|
|
|
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()!;
|
|
var folder = Path.Combine(root, "work", "desktop-multi", Guid.NewGuid().ToString("N"));
|
|
using var vm = new MainViewModel(folder, backgroundMonitoring: true, loadLocalCredentials: true);
|
|
int FreePort() { var probe = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0); probe.Start(); var port = ((System.Net.IPEndPoint)probe.LocalEndpoint).Port; probe.Stop(); return port; }
|
|
vm.Port = FreePort(); vm.UsbPort = FreePort(); vm.UsbMode = usb;
|
|
var secondId = Environment.GetEnvironmentVariable("ADS_MULTI_SECOND_DEVICE") ?? "smoke-multi-phone";
|
|
var window = new MainWindow { DataContext = vm }; window.Show();
|
|
try {
|
|
await vm.InitializeAsync();
|
|
await UntilAsync(() => vm.Devices.Any(d => d.Id == "home-phone") && vm.Devices.Any(d => d.Id == secondId), "Two test devices were not discovered");
|
|
vm.SelectedDevice = vm.Devices.Single(d => d.Id == "home-phone");
|
|
Require(!vm.SelectedDevice.Busy, "First device is occupied");
|
|
await vm.ConnectCommand.ExecuteAsync(null);
|
|
await UntilAsync(() => vm.Ready, "First phone was not ready: " + vm.Notice);
|
|
var first = vm.Connections.Single(); var firstEndpoint = first.Endpoint;
|
|
vm.SelectedDevice = vm.Devices.Single(d => d.Id == secondId);
|
|
Require(vm.ConnectCommand.CanExecute(null), "A connected phone prevented connecting another");
|
|
await vm.ConnectCommand.ExecuteAsync(null);
|
|
await UntilAsync(() => vm.Connections.Count == 2 && vm.Connections.All(c => c.Ready && c.Model != "—"), "Both phones did not become ready: " + vm.Notice);
|
|
var second = vm.Connections.Single(c => c.DeviceId == secondId);
|
|
Require(first.Options.Port != second.Options.Port && first.Endpoint != second.Endpoint, "Device endpoints collided");
|
|
if (usb) Require(first.Options.UsbPort != second.Options.UsbPort && first.Options.UsbPort != second.Options.Port && second.Options.UsbPort != first.Options.Port, "USB/IP ports collided");
|
|
Require(first.Endpoint == firstEndpoint && first.HasConnection, "Selecting another phone altered the first connection");
|
|
Require(vm.Devices.Count(d => d.IsLocal) == 2, "Local ownership was only shown for the selected phone");
|
|
await vm.StartAllScreensCommand.ExecuteAsync(null);
|
|
await UntilAsync(() => vm.Connections.All(c => c.ScreenRunning) && vm.Logs.Any(l => l.Contains("[home-phone]") && l.Contains("INFO: Texture")) && vm.Logs.Any(l => l.Contains("[" + secondId + "]") && l.Contains("INFO: Texture")), "Two independent scrcpy streams did not start");
|
|
Require(first.ScreenPort != second.ScreenPort, "scrcpy forwarding ports collided");
|
|
Require(window.FindControl<ItemsControl>("ConnectionsList")?.ItemCount == 2, "Overview did not display both connections");
|
|
using (var frame = window.CaptureRenderedFrame()) frame?.Save(Path.Combine(root, "work", usb ? "desktop-multi-usb.png" : "desktop-multi.png"));
|
|
var buttons = window.GetVisualDescendants().OfType<Button>().Where(b => b.Content as string == "查看").ToArray();
|
|
Require(buttons.Length == 2 && buttons.All(b => b.Command != null), "Overview action bindings were not resolved");
|
|
var selectFirst = buttons.Single(b => b.CommandParameter == first);
|
|
selectFirst.Command!.Execute(selectFirst.CommandParameter);
|
|
Require(vm.Current == first && vm.Endpoint == firstEndpoint, "Overview did not select the requested device");
|
|
Console.WriteLine("PASS: two " + (usb ? "USB" : "network") + " connections, distinct ports/serials, overview actions, two real scrcpy video streams");
|
|
await vm.ReconnectDeviceCommand.ExecuteAsync(first);
|
|
await UntilAsync(() => vm.Connections.Count == 2 && vm.Connections.All(c => c.Ready), "Reconnecting first phone did not recover it");
|
|
Require(second.HasConnection && second.Ready && second.ScreenRunning, "Reconnecting one phone interrupted the other");
|
|
first = vm.Connections.Single(c => c.DeviceId == "home-phone");
|
|
if (usb) {
|
|
vm.SelectConnectionCommand.Execute(first);
|
|
await vm.ClearPortCommand.ExecuteAsync(null);
|
|
} else await vm.DisconnectDeviceCommand.ExecuteAsync(first);
|
|
await UntilAsync(() => vm.Connections.Count == 1, "Disconnect did not remove only the first phone");
|
|
Require(second.HasConnection && second.Ready && second.ScreenRunning, "Disconnecting one phone interrupted the other");
|
|
vm.SelectedDevice = vm.Devices.Single(d => d.Id == secondId);
|
|
await vm.ReadDeviceInfoCommand.ExecuteAsync(null);
|
|
Require(vm.Model != "—", "Second phone stopped responding after first disconnected");
|
|
Console.WriteLine("PASS: disconnecting one phone preserves the other's ADB and video");
|
|
await vm.DisconnectAllCommand.ExecuteAsync(null);
|
|
Require(vm.Connections.Count == 0 && !vm.HasConnections, "Disconnect all leaked a connection");
|
|
await vm.RefreshCommand.ExecuteAsync(null);
|
|
Require(vm.Devices.Where(d => d.Id == "home-phone" || d.Id == secondId).All(d => !d.Busy), "Multi-device leases were not released");
|
|
Require(!vm.Logs.Any(l => l.Contains(vm.Token)), "A multi-device log leaked a token");
|
|
Console.WriteLine("PASS: selected reconnect, disconnect all and independent lease cleanup");
|
|
} finally {
|
|
await vm.ShutdownAsync(); File.WriteAllLines(Path.Combine(root, "work", "desktop-multi.log"), vm.Logs); window.Close();
|
|
}
|
|
}
|
|
|
|
private static async Task RunAsync(bool live, bool screen, bool usb)
|
|
{
|
|
var root = DesktopPaths.ProjectRoot() ?? throw new InvalidOperationException("Project root not found");
|
|
var folder = Path.Combine(root, "work", "desktop-smoke", Guid.NewGuid().ToString("N"));
|
|
using var vm = new MainViewModel(folder, backgroundMonitoring: true, loadLocalCredentials: live);
|
|
// Avoid collisions with the interactive application or another local ADB device.
|
|
var temporary = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
|
|
temporary.Start(); vm.Port = ((System.Net.IPEndPoint)temporary.LocalEndpoint).Port; temporary.Stop();
|
|
vm.UsbMode = usb;
|
|
if (usb) {
|
|
var usbProbe = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
|
|
usbProbe.Start(); vm.UsbPort = ((System.Net.IPEndPoint)usbProbe.LocalEndpoint).Port; usbProbe.Stop();
|
|
}
|
|
var window = new MainWindow { DataContext = vm };
|
|
window.Show();
|
|
await Task.Delay(60);
|
|
try
|
|
{
|
|
Require(window.FindControl<TextBox>("ServerBox")?.Text == RelayOptions.DefaultServer, "Server binding is wrong");
|
|
Require(window.FindControl<TextBox>("OriginBox")?.Text == RelayOptions.DefaultOrigin, "Origin binding is wrong");
|
|
Require(window.FindControl<CheckBox>("RelayOnlyCheck")?.IsChecked == vm.RelayOnly, "Transport preference binding is wrong");
|
|
if (!live)
|
|
{
|
|
Require(window.FindControl<Button>("ConnectButton")?.IsEffectivelyEnabled == false, "Connect should be disabled before device selection");
|
|
vm.Devices.Add(new DeviceItem("busy-phone", true, false));
|
|
vm.SelectedDevice = vm.Devices[0];
|
|
vm.RelayOnline = true;
|
|
Require(!vm.ConnectCommand.CanExecute(null), "Busy device was connectable");
|
|
vm.Devices.Add(new DeviceItem("free-phone", false, false));
|
|
vm.SelectedDevice = vm.Devices[1];
|
|
Require(vm.ConnectCommand.CanExecute(null), "Available device was not connectable");
|
|
var occupied = new System.Net.Sockets.TcpListener(System.Net.IPAddress.Loopback, 0);
|
|
occupied.Start();
|
|
try
|
|
{
|
|
vm.Port = ((System.Net.IPEndPoint)occupied.LocalEndpoint).Port;
|
|
var allocated = ConnectionPorts.Allocate(vm.Port, []);
|
|
Require(allocated != vm.Port, "Automatic allocation did not skip occupied port");
|
|
Require(!vm.HasConnection, "Port check started an unwanted connection");
|
|
}
|
|
finally { occupied.Stop(); }
|
|
var childInfo = ProcessTools.CreateStartInfo("dotnet", [typeof(Program).Assembly.Location, "--port-child", vm.Port.ToString()]);
|
|
using var child = System.Diagnostics.Process.Start(childInfo)!;
|
|
try
|
|
{
|
|
Require(await child.StandardOutput.ReadLineAsync().WaitAsync(TimeSpan.FromSeconds(10)) == "READY", "Listener child did not start");
|
|
await vm.ClearPortCommand.ExecuteAsync(null);
|
|
Require(child.HasExited && vm.PortCleanupStatus.Contains("已释放"), "GUI clear-port action did not terminate listener");
|
|
Require(window.FindControl<Button>("ClearPortButton") != null, "Clear-port button is missing");
|
|
Console.WriteLine("PASS: GUI cleanup terminates the exact port owner and frees the port");
|
|
}
|
|
finally { if (!child.HasExited) { child.Kill(); child.WaitForExit(5000); } }
|
|
Console.WriteLine("PASS: Avalonia bindings and device action availability");
|
|
return;
|
|
}
|
|
await vm.InitializeAsync();
|
|
await UntilAsync(() => vm.RelayOnline && vm.Devices.Any(d => d.Id == "home-phone"), "Public gateway was not discovered: " + vm.Notice);
|
|
Require(vm.RelayNodes.Count == 2 && vm.RelayNodes.All(n => n.Healthy), "Both relay nodes should be healthy");
|
|
vm.SelectedDevice = vm.Devices.Single(d => d.Id == "home-phone");
|
|
Require(!vm.SelectedDevice.Busy, "The gateway is in use; smoke test will not steal its lease");
|
|
await vm.ConnectCommand.ExecuteAsync(null);
|
|
await UntilAsync(() => vm.Ready && vm.Model != "—", "Device did not become ready: " + vm.Notice);
|
|
await UntilAsync(() => vm.TransportStatus.Contains("P2P") || vm.TransportStatus.Contains("中继连接"), "Transport status was not updated");
|
|
Require(window.FindControl<TextBlock>("TransportStatusText")?.Text == vm.TransportStatus, "Actual route binding failed");
|
|
if (usb) Require(vm.Endpoint?.StartsWith("ADS-") == true, "USB mode did not select the USB serial");
|
|
Console.WriteLine("PASS: two healthy nodes and actual transport shown: " + vm.TransportStatus);
|
|
Require(window.FindControl<TextBlock>("ModelText")?.Text == vm.Model, "Model UI binding failed");
|
|
Require(window.FindControl<Button>("ReconnectButton")?.IsEffectivelyEnabled == true, "Reconnect button not enabled");
|
|
Console.WriteLine("PASS: public device list, GUI connect, local ADB ready and model information: " + vm.Model);
|
|
Require(vm.Devices.Single(d => d.Id == "home-phone").IsLocal, "Current device ownership label is wrong");
|
|
using (var frame = window.CaptureRenderedFrame()) frame?.Save(Path.Combine(root, "work", "desktop-live.png"));
|
|
window.Width = 980; window.Height = 700;
|
|
await Task.Delay(60);
|
|
using (var frame = window.CaptureRenderedFrame()) frame?.Save(Path.Combine(root, "work", "desktop-minimum.png"));
|
|
window.Width = 1240; window.Height = 880;
|
|
if (screen)
|
|
{
|
|
await vm.CheckToolsCommand.ExecuteAsync(null);
|
|
Require(!vm.ToolsStatus.Contains("未就绪"), "Missing tool: " + vm.ToolsStatus);
|
|
await vm.StartScrcpyCommand.ExecuteAsync(null);
|
|
Require(vm.ScreenRunning, "scrcpy did not start: " + vm.Notice);
|
|
try
|
|
{
|
|
await UntilAsync(() => vm.Logs.Any(line => line.Contains("INFO: Texture")),
|
|
"scrcpy did not report a video texture");
|
|
}
|
|
catch (Exception error)
|
|
{
|
|
throw new InvalidOperationException(error.Message + "; state=" + vm.ScreenRunning + "; notice=" + vm.Notice + "; logs=" + string.Join(" | ", vm.Logs.TakeLast(25)));
|
|
}
|
|
Require(vm.ScreenRunning, "scrcpy process exited unexpectedly");
|
|
if(usb && Environment.GetCommandLineArgs().Contains("--recover")) {
|
|
var connection=vm.Connections.Single(c=>c.DeviceId=="home-phone");
|
|
var oldPort=connection.Options.UsbPort;
|
|
var textures=vm.Logs.Count(l=>l.Contains("INFO: Texture"));
|
|
var field=typeof(DeviceConnection).GetField("client",System.Reflection.BindingFlags.NonPublic|System.Reflection.BindingFlags.Instance)!;
|
|
var owned=(System.Diagnostics.Process)field.GetValue(connection)!;
|
|
owned.Kill(entireProcessTree:true);
|
|
await owned.WaitForExitAsync();
|
|
await UntilAsync(()=>connection.Options.UsbPort!=oldPort && connection.Ready && connection.ScreenRunning && vm.Logs.Count(l=>l.Contains("INFO: Texture"))>textures,"USB remount and video recovery failed: "+connection.Notice);
|
|
Console.WriteLine("PASS: client failure automatically remounts USB and restores real scrcpy video");
|
|
}
|
|
await vm.StopScrcpyCommand.ExecuteAsync(null);
|
|
Require(!vm.ScreenRunning, "scrcpy did not stop");
|
|
if(usb && Environment.GetCommandLineArgs().Contains("--recover")) {
|
|
await Task.Delay(7000);
|
|
Require(!vm.ScreenRunning,"Manual stop must cancel automatic video restore");
|
|
}
|
|
Console.WriteLine("PASS: GUI starts real scrcpy video stream and stops its process");
|
|
}
|
|
await vm.ReconnectCommand.ExecuteAsync(null);
|
|
await UntilAsync(() => vm.Ready && vm.Model != "—", "Reconnect did not recover device: " + vm.Notice);
|
|
Console.WriteLine("PASS: GUI reconnect and information recovery");
|
|
await vm.DisconnectCommand.ExecuteAsync(null);
|
|
Require(!vm.HasConnection && !vm.Ready && vm.Endpoint == null, "Disconnect did not clean up local connection");
|
|
await vm.RefreshCommand.ExecuteAsync(null);
|
|
Require(vm.Devices.Single(d => d.Id == "home-phone").Busy == false, "Device lease was not released");
|
|
Console.WriteLine("PASS: GUI disconnect releases lease; remote gateway remains online");
|
|
|
|
vm.SelectedDevice = vm.Devices.Single(d => d.Id == "home-phone");
|
|
await vm.ConnectCommand.ExecuteAsync(null);
|
|
await UntilAsync(() => vm.Ready, "Device did not recover before own-port cleanup");
|
|
await vm.ClearPortCommand.ExecuteAsync(null);
|
|
Require(!vm.HasConnection && !vm.Ready && vm.PortCleanupStatus.Contains("已释放"), "Own connection was not cleared");
|
|
await vm.RefreshCommand.ExecuteAsync(null);
|
|
Require(!vm.Devices.Single(d => d.Id == "home-phone").Busy, "Own-port cleanup did not release lease");
|
|
Console.WriteLine("PASS: cleanup of the workbench's own port releases ADB and device lease");
|
|
vm.SaveCommand.Execute(null);
|
|
Require(!File.ReadAllText(Path.Combine(folder, "settings.json")).Contains(vm.Token), "Saved settings leaked the token");
|
|
Require(!vm.Logs.Any(line => line.Contains(vm.Token)), "UI log leaked token");
|
|
Console.WriteLine("PASS: settings and UI logs do not contain client token");
|
|
}
|
|
finally
|
|
{
|
|
await vm.ShutdownAsync();
|
|
File.WriteAllLines(Path.Combine(root, "work", "desktop-smoke.log"), vm.Logs);
|
|
window.Close();
|
|
}
|
|
}
|
|
}
|