feat: add control center, multiple relay nodes and P2P-first transport

This commit is contained in:
tongtong committed 2026-11-12 16:56:06 +08:00
1 parent 0988e9c363
commit 2abfb63da9
44 files changed
+3477 -67

No files matched your search

+5
View File
@@ -62,6 +62,7 @@ internal static class Program
{
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");
@@ -97,10 +98,14 @@ internal static class Program
}
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");
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);
@@ -13,6 +13,7 @@ public sealed class DesktopSettings
public int Port { get; set; } = 15555;
public int Size { get; set; } = 1920;
public int Fps { get; set; } = 60;
public bool RelayOnly { get; set; }
public bool Audio { get; set; }
public bool ViewOnly { get; set; }
public bool Tray { get; set; } = true;
+38 -4
View File
@@ -1,5 +1,6 @@
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Text.Json;
using System.Text.RegularExpressions;
using Avalonia.Threading;
using CommunityToolkit.Mvvm.ComponentModel;
@@ -23,6 +24,8 @@ public partial class MainViewModel : ObservableObject, IDisposable
[ObservableProperty] private int port = 15555;
[ObservableProperty] private int maxSize = 1920;
[ObservableProperty] private int maxFps = 60;
[ObservableProperty] private bool relayOnly;
[ObservableProperty] private string transportStatus = "尚未建立数据通道";
[ObservableProperty] private bool audio;
[ObservableProperty] private bool viewOnly;
[ObservableProperty] private bool minimizeToTray = true;
@@ -46,13 +49,14 @@ public partial class MainViewModel : ObservableObject, IDisposable
[ObservableProperty] private bool isWorking;
[ObservableProperty] private bool isRefreshing;
public ObservableCollection<RelayNode> RelayNodes { get; } = new();
public ObservableCollection<DeviceItem> Devices { get; } = new();
public ObservableCollection<string> Logs { get; } = new();
public string? Endpoint => endpoint;
public string? ActiveDeviceId => activeId;
private Process? client, scrcpy;
private string? endpoint, activeAdb, activeId;
private string? endpoint, activeAdb, activeId, transportFile;
private string credentialFile = "", preferredDevice = "home-phone";
private bool monitoring, disposed, initialized;
private DateTime lastRefresh;
@@ -77,7 +81,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
if (settings.Adb.Length > 0) AdbPath = settings.Adb;
if (settings.Scrcpy.Length > 0) ScrcpyPath = settings.Scrcpy;
Port = settings.Port; MaxSize = settings.Size; MaxFps = settings.Fps;
Audio = settings.Audio; ViewOnly = settings.ViewOnly;
RelayOnly = settings.RelayOnly; Audio = settings.Audio; ViewOnly = settings.ViewOnly;
MinimizeToTray = settings.Tray; AutoRefresh = settings.AutoRefresh;
credentialFile = settings.CredentialFile;
preferredDevice = settings.PreferredDevice;
@@ -186,7 +190,15 @@ public partial class MainViewModel : ObservableObject, IDisposable
foreach (var row in rows) Devices.Add(new DeviceItem(row.Id, row.Busy, HasConnection && row.Id == activeId));
SelectedDevice = Devices.FirstOrDefault(d => d.Id == selectedId) ?? Devices.FirstOrDefault(d => !d.Busy) ?? Devices.FirstOrDefault();
RelayOnline = true;
RelayStatus = "中继在线";
RelayStatus = "控制中心在线";
try {
var nodes = await RelayApi.GetNodesAsync(options, lifetime.Token);
if (Server.Trim() != options.BaseUri.OriginalString || Origin.Trim() != options.Origin || Token != options.Token) return;
RelayNodes.Clear(); foreach (var node in nodes) RelayNodes.Add(node);
if (nodes.Length > 0) RelayStatus += $" · 中继 {nodes.Count(n => n.Healthy)}/{nodes.Length} 在线";
} catch (Exception error) when (error is HttpRequestException or TaskCanceledException) {
RelayNodes.Clear(); RelayStatus += " · 节点状态暂不可用";
}
DeviceSummary = $"{rows.Length} 台在线 · {DateTime.Now:HH:mm:ss} 更新";
lastRefreshError = null;
if (announce) { Notice = "设备列表已更新。"; Log($"中继在线,发现 {rows.Length} 台设备。"); }
@@ -274,6 +286,11 @@ public partial class MainViewModel : ObservableObject, IDisposable
var adb = DesktopPaths.ResolveTool(AdbPath, "adb");
var address = $"127.0.0.1:{Port}";
var info = ProcessTools.ClientStartInfo(clientExecutable, adb, relay, device.Id, address);
Directory.CreateDirectory(folder);
transportFile = Path.Combine(folder, "transport-" + Guid.NewGuid().ToString("N") + ".json");
info.ArgumentList.Add("--transport"); info.ArgumentList.Add(RelayOnly ? "relay" : "auto");
info.ArgumentList.Add("--status-file"); info.ArgumentList.Add(transportFile);
TransportStatus = "正在协商连接路线";
client = Start(info);
endpoint = address; activeAdb = adb; activeId = device.Id; preferredDevice = device.Id;
OnPropertyChanged(nameof(Endpoint)); OnPropertyChanged(nameof(ActiveDeviceId));
@@ -326,6 +343,21 @@ public partial class MainViewModel : ObservableObject, IDisposable
Log($"手机控制窗口已关闭,退出码 {scrcpy.ExitCode}。");
scrcpy.Dispose(); scrcpy = null; ScreenRunning = false;
}
if (transportFile != null && File.Exists(transportFile))
{
try {
using var state = JsonDocument.Parse(await File.ReadAllTextAsync(transportFile, lifetime.Token));
var root = state.RootElement;
var nodes = string.Join("、", root.GetProperty("nodes").EnumerateArray().Select(n => n.GetString()));
TransportStatus = root.GetProperty("transport").GetString() switch {
"p2p" => "P2P 直连 · 数据不经过中继",
"relay" => "中继连接 · " + nodes,
"mixed" => "P2P 与中继并用 · " + nodes,
"negotiating" => "正在协商连接路线",
_ => "等待 ADB 数据通道"
};
} catch (IOException) { } catch (JsonException) { }
}
var current = client;
if (current != null)
{
@@ -418,6 +450,8 @@ public partial class MainViewModel : ObservableObject, IDisposable
if (endpoint != null && activeAdb != null)
try { await AdbAsync(activeAdb, CancellationToken.None, "disconnect", endpoint); }
catch (Exception error) { Log(error.Message); }
if (transportFile != null) { try { File.Delete(transportFile); } catch (IOException) { } }
transportFile = null; TransportStatus = "尚未建立数据通道";
endpoint = activeAdb = activeId = null;
HasConnection = Ready = false;
UpdateLocalOwnership();
@@ -486,7 +520,7 @@ public partial class MainViewModel : ObservableObject, IDisposable
DesktopPaths.SaveSettings(settingsFile, new DesktopSettings
{
Server = Server.Trim(), Origin = Origin.Trim(), Client = ClientPath, Adb = AdbPath, Scrcpy = ScrcpyPath,
Port = Port, Size = MaxSize, Fps = MaxFps, Audio = Audio, ViewOnly = ViewOnly, Tray = MinimizeToTray,
RelayOnly = RelayOnly, Port = Port, Size = MaxSize, Fps = MaxFps, Audio = Audio, ViewOnly = ViewOnly, Tray = MinimizeToTray,
AutoRefresh = AutoRefresh, CredentialFile = credentialFile, PreferredDevice = activeId ?? SelectedDevice?.Id ?? preferredDevice
});
Notice = "配置已保存;令牌内容未写入配置。";
+5 -2
View File
@@ -39,6 +39,7 @@
<StackPanel Spacing="12">
<TextBlock Text="连接管理" Classes="section"/>
<TextBlock x:Name="ConnectionStatusText" Text="{Binding Status}" Foreground="#66D9C0" FontSize="19" TextWrapping="Wrap"/>
<TextBlock x:Name="TransportStatusText" Text="{Binding TransportStatus}" Foreground="#A8B7CC" TextWrapping="Wrap"/>
<TextBlock x:Name="EndpointText" Text="{Binding ActiveEndpoint}" Classes="label" TextWrapping="Wrap"/>
<WrapPanel><Button x:Name="ConnectButton" Content="连接所选设备" Command="{Binding ConnectCommand}"/><Button x:Name="ReconnectButton" Content="重新连接" Command="{Binding ReconnectCommand}"/><Button x:Name="DisconnectButton" Content="断开连接" Command="{Binding DisconnectCommand}"/><Button Content="复制 ADB 地址" IsEnabled="{Binding HasConnection}" Click="CopyEndpointClick"/><Button x:Name="ClearPortButton" Content="清理占用端口" Command="{Binding ClearPortCommand}"/></WrapPanel>
<TextBlock Text="断开连接只释放本机通道,远程手机守护程序会继续在线。" TextWrapping="Wrap" Classes="label" FontSize="12"/>
@@ -74,8 +75,9 @@
<ScrollViewer>
<StackPanel Margin="4,18" MaxWidth="880" Spacing="16">
<Border Classes="card"><StackPanel>
<TextBlock Text="公网中继" Classes="section" Margin="0,0,0,12"/>
<TextBlock Text="中继地址(WSS,可包含路径)"/><TextBox x:Name="ServerBox" Text="{Binding Server}" Watermark="wss://ttstd.com/ads"/>
<TextBlock Text="控制中心" Classes="section" Margin="0,0,0,12"/>
<ItemsControl ItemsSource="{Binding RelayNodes}" Margin="0,0,0,12"><ItemsControl.ItemTemplate><DataTemplate><TextBlock Text="{Binding Description}" Foreground="#66D9C0" Margin="0,3"/></DataTemplate></ItemsControl.ItemTemplate></ItemsControl>
<TextBlock Text="控制中心地址(WSS,可包含路径)"/><TextBox x:Name="ServerBox" Text="{Binding Server}" Watermark="wss://ttstd.com/ads"/>
<TextBlock Text="直连服务器(可选)"/><TextBox x:Name="OriginBox" Text="{Binding Origin}" Watermark="175.178.213.60:443"/>
<TextBlock Text="留空则按域名解析;指定公网 IP 时仍验证域名证书。当前部署使用此设置避开 Cloudflare 连接超时。" Classes="label" TextWrapping="Wrap"/>
</StackPanel></Border>
@@ -95,6 +97,7 @@
</StackPanel></Border>
<Border Classes="card"><StackPanel Spacing="12">
<TextBlock Text="本地连接" Classes="section"/>
<CheckBox x:Name="RelayOnlyCheck" Content="仅使用中继(关闭时 P2P 优先,失败自动选择中继节点)" IsChecked="{Binding RelayOnly}"/>
<Grid ColumnDefinitions="*,180"><TextBlock Text="本地 ADB 端口" VerticalAlignment="Center"/><NumericUpDown Grid.Column="1" Value="{Binding Port}" Minimum="1024" Maximum="65535"/></Grid>
<WrapPanel><Button Content="清理占用端口" Command="{Binding ClearPortCommand}" ToolTip.Tip="结束当前所选端口的监听进程"/><TextBlock Text="{Binding PortCleanupStatus}" Classes="label" TextWrapping="Wrap" MaxWidth="580" VerticalAlignment="Center"/></WrapPanel>
<CheckBox Content="关闭窗口时保留连接并最小化到托盘" IsChecked="{Binding MinimizeToTray}"/>
+18
View File
@@ -50,6 +50,12 @@ public sealed record RelayOptions(Uri BaseUri, string Origin, string Token)
public sealed record RelayDevice(string Id, bool Busy);
public sealed record RelayNode(string Id, bool Healthy, int Sessions, int Capacity)
{
public string Description => $"{Id} · {(Healthy ? "在线" : "不可用")} · 通道 {Sessions}/{Capacity}";
}
public sealed record RelayCluster(RelayNode[] Nodes);
public static class RelayApi
{
public static HttpClient CreateClient(RelayOptions options)
@@ -79,6 +85,18 @@ public static class RelayApi
return new HttpClient(handler) { Timeout = TimeSpan.FromSeconds(12) };
}
public static async Task<RelayNode[]> GetNodesAsync(RelayOptions options, CancellationToken cancellation = default)
{
using var http = CreateClient(options);
using var request = new HttpRequestMessage(HttpMethod.Get,
new UriBuilder(options.DevicesUri) { Path = options.BaseUri.AbsolutePath.TrimEnd('/') + "/v2/nodes" }.Uri);
request.Headers.Authorization = new AuthenticationHeaderValue("Bearer", options.Token);
using var response = await http.SendAsync(request, cancellation);
if (response.StatusCode == HttpStatusCode.NotFound) return [];
response.EnsureSuccessStatusCode();
return (await response.Content.ReadFromJsonAsync<RelayCluster>(cancellationToken: cancellation))?.Nodes ?? [];
}
public static async Task<RelayDevice[]> GetDevicesAsync(RelayOptions options, CancellationToken cancellation = default)
{
using var http = CreateClient(options);
+4
View File
@@ -54,3 +54,7 @@ dotnet run --project Ads.Desktop.Smoke -c Debug -- --live --screen
```
单元测试覆盖路径前缀、源站配置、旧默认地址迁移、角色凭据隔离、不可信证书拒绝、环境变量与保存配置。离屏测试加载真实 XAML,覆盖按钮可用状态、实际设备发现/连接/型号显示/重连/释放、scrcpy 视频纹理启动与停止。示例布局图片写入 `work/`。原生 Windows 自动化运行时本次初始化失败,因此未自动点击真实原生窗口或验证托盘菜单;不是把无头测试当作原生点击验收。
## 集群连接
地址指向控制中心。默认 P2P 优先,连接配置的“仅使用中继”可跳过直连;修改在下次连接生效。连接管理显示实际 P2P/中继节点,控制中心配置卡显示节点健康及通道数。节点健康约每 5 秒由中心探测,桌面刷新设备时读取。