Sync Avalonia management features and separate desktop instances

This commit is contained in:
tongtong committed 2026-11-20 10:32:47 +08:00
1 parent 0a04d5990f
commit 8d3dbe296a
12 files changed
+157 -15

No files matched your search

+4 -4
View File
@@ -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;
}
+20
View File
@@ -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();
}));
}
+6
View File
@@ -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) {
+23 -2
View File
@@ -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>
+2 -2
View File
@@ -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);
+39
View File
@@ -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="中继节点配置已更新。";
}
}