Sync Avalonia management features and separate desktop instances
This commit is contained in:
1 parent
0a04d5990f
commit
8d3dbe296a
12 files changed
+157
-15
No files matched your search
@@ -0,0 +1,32 @@
|
||||
using Ads.Desktop;
|
||||
using System.Reflection;
|
||||
using System.Text.Json;
|
||||
using Xunit;
|
||||
namespace Ads.Desktop.Tests;
|
||||
public class DesktopParityTests
|
||||
{
|
||||
[Fact] public void SeparateEditionsCanOwnTheirLocksAndDuplicateWakesSameEdition()
|
||||
{
|
||||
if(!OperatingSystem.IsWindows())return;
|
||||
var scope=@"Local\TTSTD.ADS.Test."+Guid.NewGuid().ToString("N");
|
||||
var type=typeof(MainViewModel).Assembly.GetType("Ads.Desktop.DesktopInstance")!;
|
||||
using var first=(IDisposable)Activator.CreateInstance(type,new object[]{scope+".Avalonia"})!;
|
||||
using var flutter=new Mutex(true,scope+".Flutter.Instance",out var flutterPrimary);
|
||||
try {
|
||||
Assert.True(flutterPrimary);
|
||||
Assert.True((bool)type.GetProperty("Primary")!.GetValue(first)!);
|
||||
using var duplicate=(IDisposable)Activator.CreateInstance(type,new object[]{scope+".Avalonia"})!;
|
||||
Assert.False((bool)type.GetProperty("Primary")!.GetValue(duplicate)!);
|
||||
using var wake=new ManualResetEventSlim();
|
||||
type.GetMethod("Listen")!.Invoke(first,new object[]{(Action)(()=>wake.Set())});
|
||||
type.GetMethod("Activate")!.Invoke(duplicate,null);
|
||||
Assert.True(wake.Wait(TimeSpan.FromSeconds(3)));
|
||||
} finally { if(flutterPrimary)flutter.ReleaseMutex(); }
|
||||
}
|
||||
[Fact] public void RelayManagementReadsServerNodeConfiguration()
|
||||
{
|
||||
var json="""{"id":"relay-1","url":"wss://example.com/relay","connect_address":"127.0.0.1:443","priority":5,"default":true,"healthy":true,"sessions":2,"capacity":32}""";
|
||||
var node=JsonSerializer.Deserialize<RelayNode>(json,new JsonSerializerOptions(JsonSerializerDefaults.Web))!;
|
||||
Assert.True(node.Default);Assert.Equal(5,node.Priority);Assert.Equal("127.0.0.1:443",node.ConnectAddress);Assert.Contains("默认",node.Description);
|
||||
}
|
||||
}
|
||||
@@ -2,7 +2,7 @@ using System.Runtime.InteropServices;
|
||||
|
||||
namespace Ads.Desktop;
|
||||
|
||||
/// <summary>Shares the Windows desktop UI lease with Flutter, including tray mode.</summary>
|
||||
/// <summary>Owns the Avalonia Windows desktop UI lease, including tray mode.</summary>
|
||||
internal sealed class DesktopInstance : IDisposable
|
||||
{
|
||||
private readonly Mutex mutex;
|
||||
@@ -10,10 +10,10 @@ internal sealed class DesktopInstance : IDisposable
|
||||
private RegisteredWaitHandle? registration;
|
||||
public bool Primary { get; }
|
||||
|
||||
public DesktopInstance()
|
||||
public DesktopInstance(string scope = @"Local\TTSTD.ADS.Avalonia")
|
||||
{
|
||||
activation = new EventWaitHandle(false, EventResetMode.AutoReset, @"Local\TTSTD.ADS.Desktop.Activate");
|
||||
mutex = new Mutex(true, @"Local\TTSTD.ADS.Desktop.Instance", out var primary);
|
||||
activation = new EventWaitHandle(false, EventResetMode.AutoReset, scope + ".Activate");
|
||||
mutex = new Mutex(true, scope + ".Instance", out var primary);
|
||||
Primary = primary;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,20 @@
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
namespace Ads.Desktop;
|
||||
public partial class MainViewModel
|
||||
{
|
||||
[ObservableProperty] private string localAdbListing="";
|
||||
[RelayCommand] private Task ReadLocalAdbAsync()=>Guard(()=>Exclusive(ReadLocalAdbCoreAsync));
|
||||
private async Task ReadLocalAdbCoreAsync()
|
||||
{
|
||||
var adb=DesktopPaths.ResolveTool(AdbPath,"adb");
|
||||
LocalAdbListing=await AdbAsync(adb,lifetime.Token,"devices","-l");
|
||||
Notice="本机 ADB 设备列表已更新。";
|
||||
}
|
||||
[RelayCommand] private Task StartLocalAdbServerAsync()=>Guard(()=>Exclusive(async()=>{
|
||||
var adb=DesktopPaths.ResolveTool(AdbPath,"adb");
|
||||
var result=await AdbAsync(adb,lifetime.Token,"start-server");
|
||||
Log(string.IsNullOrWhiteSpace(result)?"本机 ADB Server 已启动。":result.Trim());
|
||||
await ReadLocalAdbCoreAsync();
|
||||
}));
|
||||
}
|
||||
@@ -215,6 +215,12 @@ public partial class MainViewModel : ObservableObject, IDisposable
|
||||
var options = RelayOptions.Parse(Server, Origin, Token);
|
||||
var rows = await RelayApi.GetDevicesAsync(options, lifetime.Token);
|
||||
if (Server.Trim() != options.BaseUri.OriginalString || Origin.Trim() != options.Origin || Token != options.Token) return;
|
||||
foreach (var connection in Connections.Where(c => c.HasConnection).ToArray()) {
|
||||
if (rows.Any(r => r.Id == connection.DeviceId)) { missingRelayDevices.Remove(connection.DeviceId); continue; }
|
||||
var misses=missingRelayDevices.GetValueOrDefault(connection.DeviceId)+1;
|
||||
missingRelayDevices[connection.DeviceId]=misses;
|
||||
if(misses>=3) { await connection.DisconnectAsync(); missingRelayDevices.Remove(connection.DeviceId); Log($"[{connection.DeviceId}] 设备连续三轮不在列表,停止自动重连。"); }
|
||||
}
|
||||
var selectedId = SelectedDevice?.Id ?? preferredDevice;
|
||||
Devices.Clear();
|
||||
foreach (var row in rows) {
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
<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="{DynamicResource SemiColorBackground0}">
|
||||
<Grid RowDefinitions="Auto,*,Auto" Margin="24">
|
||||
<Grid RowDefinitions="112,*,32" Margin="24,24,24,12">
|
||||
<Grid ColumnDefinitions="*,Auto" Margin="0,0,0,20">
|
||||
<StackPanel Spacing="5">
|
||||
<TextBlock Text="ANDROID DEVICE STREAMING" Foreground="{DynamicResource SemiColorPrimary}" FontSize="11" LetterSpacing="3"/>
|
||||
@@ -94,6 +94,27 @@
|
||||
</Grid>
|
||||
</TabItem>
|
||||
<TabItem x:Name="AgentManagementTab" Header="Agent 管理"><local:AgentManagementView DataContext="{Binding AgentManager}"/></TabItem>
|
||||
<TabItem Header="本机 ADB">
|
||||
<Grid RowDefinitions="Auto,Auto,*" Margin="8,16">
|
||||
<TextBlock Text="使用本机 ADB Server,显示本地 USB 设备和网络设备,无需连接公网中继。" TextWrapping="Wrap"/>
|
||||
<WrapPanel Grid.Row="1" Margin="0,16"><Button Content="读取设备列表" Command="{Binding ReadLocalAdbCommand}"/><Button Content="启动 ADB Server" Command="{Binding StartLocalAdbServerCommand}"/></WrapPanel>
|
||||
<TextBox Grid.Row="2" Text="{Binding LocalAdbListing, Mode=OneWay}" IsReadOnly="True" AcceptsReturn="True" TextWrapping="Wrap" FontFamily="Consolas,Microsoft YaHei UI" Watermark="点击读取设备列表检查本机设备。"/>
|
||||
</Grid>
|
||||
</TabItem>
|
||||
<TabItem Header="中继节点"><ScrollViewer><StackPanel Margin="8,16" Spacing="12">
|
||||
<TextBlock Text="中继节点管理" Classes="section"/>
|
||||
<TextBlock Text="修改使用 Agent 管理页已导入的管理员凭据;节点列表使用客户端凭据。" TextWrapping="Wrap"/>
|
||||
<Button Content="刷新节点" Command="{Binding RefreshCommand}"/>
|
||||
<ListBox ItemsSource="{Binding RelayNodes}" SelectedItem="{Binding SelectedRelayNode}"><ListBox.ItemTemplate><DataTemplate><StackPanel><TextBlock Text="{Binding Description}"/><TextBlock Text="{Binding Url}"/></StackPanel></DataTemplate></ListBox.ItemTemplate></ListBox>
|
||||
<WrapPanel><Button Content="设为默认" Command="{Binding SetDefaultRelayCommand}"/><Button Content="删除所选节点" Command="{Binding DeleteRelayCommand}"/></WrapPanel>
|
||||
<CheckBox Content="确认删除所选节点(服务器至少保留一个节点)" IsChecked="{Binding ConfirmRelayDelete}"/>
|
||||
<TextBlock Text="新增节点" Classes="section"/>
|
||||
<TextBox Text="{Binding NewRelayId}" Watermark="节点 ID"/>
|
||||
<TextBox Text="{Binding NewRelayUrl}" Watermark="wss://中继地址,可含路径"/>
|
||||
<TextBox Text="{Binding NewRelayOrigin}" Watermark="可选源站 host:port"/>
|
||||
<NumericUpDown Value="{Binding NewRelayPriority}" Minimum="1" Maximum="100000"/>
|
||||
<Button Content="新增节点" Command="{Binding AddRelayCommand}"/>
|
||||
</StackPanel></ScrollViewer></TabItem>
|
||||
<TabItem Header="连接配置">
|
||||
<ScrollViewer>
|
||||
<StackPanel Margin="4,18" MaxWidth="880" Spacing="16">
|
||||
@@ -145,6 +166,6 @@
|
||||
</Grid>
|
||||
</TabItem>
|
||||
</TabControl>
|
||||
<TextBlock Grid.Row="2" x:Name="NoticeText" Text="{Binding Notice}" Foreground="{DynamicResource SemiColorText2}" Margin="0,18,0,0" TextWrapping="Wrap" MaxHeight="70"/>
|
||||
<TextBlock Grid.Row="2" x:Name="NoticeText" Text="{Binding Notice}" Foreground="{DynamicResource SemiColorText2}" Margin="0,8,0,0" VerticalAlignment="Center" TextWrapping="NoWrap" TextTrimming="CharacterEllipsis" ToolTip.Tip="{Binding Notice}" MaxHeight="24"/>
|
||||
</Grid>
|
||||
</Window>
|
||||
@@ -50,9 +50,9 @@ public sealed record RelayOptions(Uri BaseUri, string Origin, string Token)
|
||||
|
||||
public sealed record RelayDevice(string Id, bool Busy, [property:System.Text.Json.Serialization.JsonPropertyName("agent_id")] string AgentId="", [property:System.Text.Json.Serialization.JsonPropertyName("computer_name")] string ComputerName="");
|
||||
|
||||
public sealed record RelayNode(string Id, bool Healthy, int Sessions, int Capacity)
|
||||
public sealed record RelayNode(string Id, bool Healthy, int Sessions, int Capacity, string Url="", [property:System.Text.Json.Serialization.JsonPropertyName("connect_address")] string ConnectAddress="", int Priority=100, bool Default=false)
|
||||
{
|
||||
public string Description => $"{Id} · {(Healthy ? "在线" : "不可用")} · 通道 {Sessions}/{Capacity}";
|
||||
public string Description => $"{Id}{(Default ? " ★默认" : "")} · {(Healthy ? "在线" : "不可用")} · 通道 {Sessions}/{Capacity}";
|
||||
}
|
||||
public sealed record RelayCluster(RelayNode[] Nodes);
|
||||
|
||||
|
||||
@@ -0,0 +1,39 @@
|
||||
using System.Net.Http.Headers;
|
||||
using System.Net.Http.Json;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
namespace Ads.Desktop;
|
||||
public partial class MainViewModel
|
||||
{
|
||||
[ObservableProperty] private RelayNode? selectedRelayNode;
|
||||
[ObservableProperty] private string newRelayId="";
|
||||
[ObservableProperty] private string newRelayUrl="";
|
||||
[ObservableProperty] private string newRelayOrigin="";
|
||||
[ObservableProperty] private int newRelayPriority=100;
|
||||
[ObservableProperty] private bool confirmRelayDelete;
|
||||
private readonly Dictionary<string,int> missingRelayDevices=new();
|
||||
[RelayCommand] private Task AddRelayAsync()=>Guard(()=>Exclusive(async()=>{
|
||||
var id=NewRelayId.Trim();
|
||||
if(id.Length is <1 or >128 || id.Any(c=>!char.IsAsciiLetterOrDigit(c)&&c!='-'&&c!='_'&&c!='.'))throw new InvalidOperationException("节点 ID 格式无效。");
|
||||
RelayOptions.ParseBaseUri(NewRelayUrl);
|
||||
if(!string.IsNullOrWhiteSpace(NewRelayOrigin))RelayOptions.ParseOrigin(NewRelayOrigin.Trim());
|
||||
await MutateRelayAsync(HttpMethod.Post,"/v2/nodes",new{id,url=NewRelayUrl.Trim(),connect_address=NewRelayOrigin.Trim(),priority=NewRelayPriority});
|
||||
}));
|
||||
[RelayCommand] private Task SetDefaultRelayAsync()=>Guard(()=>Exclusive(()=>MutateRelayAsync(HttpMethod.Post,"/v2/nodes/default",new{id=(SelectedRelayNode??throw new InvalidOperationException("请选择节点。")).Id})));
|
||||
[RelayCommand] private Task DeleteRelayAsync()=>Guard(()=>Exclusive(async()=>{
|
||||
if(!ConfirmRelayDelete)throw new InvalidOperationException("请先勾选删除确认。");
|
||||
var node=SelectedRelayNode??throw new InvalidOperationException("请选择节点。");
|
||||
await MutateRelayAsync(HttpMethod.Delete,"/v2/nodes/"+Uri.EscapeDataString(node.Id),null);ConfirmRelayDelete=false;
|
||||
}));
|
||||
private async Task MutateRelayAsync(HttpMethod method,string path,object? body)
|
||||
{
|
||||
var options=RelayOptions.Parse(Server,Origin,AgentManager.AdminToken);
|
||||
using var http=RelayApi.CreateClient(options);
|
||||
using var req=new HttpRequestMessage(method,new UriBuilder(options.DevicesUri){Path=options.BaseUri.AbsolutePath.TrimEnd('/')+path}.Uri);
|
||||
req.Headers.Authorization=new AuthenticationHeaderValue("Bearer",options.Token);
|
||||
if(body!=null)req.Content=JsonContent.Create(body);
|
||||
using var res=await http.SendAsync(req,lifetime.Token);
|
||||
if(!res.IsSuccessStatusCode)throw new InvalidOperationException($"节点操作失败 HTTP {(int)res.StatusCode};请检查管理员凭据、节点参数及服务器配置写入权限。");
|
||||
await RefreshDevicesAsync(false);Notice="中继节点配置已更新。";
|
||||
}
|
||||
}
|
||||
+9
-1
@@ -79,7 +79,7 @@ ADB、USB/IP 和 scrcpy 转发端口分别自动分配,避开其他连接和
|
||||
|
||||
## Windows 单实例
|
||||
|
||||
Windows 桌面入口与 Flutter 共用同一会话级单实例锁(包括 --agent-tray 入口和不同安装路径)。重复启动会唤起正在运行的桌面窗口并退出新进程,避免重复托盘及重复设备管理。后台 Agent 和设备连接进程不受该 UI 锁限制。DesktopInstance.cs 使用 Windows 命名事件通知,由 Avalonia UI 线程恢复窗口。非 Windows 暂保留原启动行为。
|
||||
Windows Avalonia 桌面入口使用独立于 Flutter 的会话级单实例锁(包括 --agent-tray 入口和不同安装路径)。重复启动会唤起正在运行的桌面窗口并退出新进程,避免重复托盘及重复设备管理。后台 Agent 和设备连接进程不受该 UI 锁限制。DesktopInstance.cs 使用 Windows 命名事件通知,由 Avalonia UI 线程恢复窗口。非 Windows 暂保留原启动行为。
|
||||
|
||||
## 路径选择与 USB 自动恢复
|
||||
|
||||
@@ -102,3 +102,11 @@ Windows 自包含发布把托管程序集打包到主程序,保留原生图形
|
||||
Avalonia 使用锁定的 Semi.Avalonia 11.3.7.3(兼容 Avalonia 11.3.8)。`Ads.Desktop/WorkbenchStyles.axaml`(AXAML)统一侧边导航、卡片、表单和文本样式,颜色引用 Semi 语义资源,支持浅色/深色切换;Agent 托盘窗口共享主题。`dotnet run --project Ads.Desktop.Smoke -- --theme-preview` 可离线渲染 4 个页面的明暗主题和最小窗口尺寸,结果写入根目录 work(PNG)。
|
||||
|
||||
子进程 stdout/stderr 显式按 UTF-8 解码,包含 Rust、ADB、scrcpy 及 USB 工具;Agent JSON stdin 也使用 UTF-8。已生成的历史乱码日志保留,不猜测或改写丢失的字符。测试覆盖中文和 emoji 的一次性输出、流式日志及中文配置输入。
|
||||
|
||||
## 独立单实例与功能同步
|
||||
|
||||
Windows 两端分别使用 Avalonia / Flutter 专属互斥锁及唤醒事件,允许两端同时打开,各自重复启动只唤醒本端窗口;安装版、便携版和托盘入口在各自端内共享限制。旧版使用共享锁,需要退出并升级两端。设备独占租约仍由服务器控制,同一设备不能被两端同时占用。
|
||||
|
||||
Avalonia 新增中继节点列表、新增、删除确认与设默认功能,复用 Agent 管理页管理员凭据;成功写入后刷新节点状态。设备连续三轮从服务器列表消失会断开并停止自动重连;请求失败不累计缺失次数。
|
||||
|
||||
本机 ADB 页签支持读取 adb devices -l 与启动本机 ADB Server,使用连接配置中的 ADB 工具路径,不依赖中继或客户端令牌。
|
||||
Reference in new issue
Block a user