feat: improve desktop path selection and USB connection recovery
This commit is contained in:
1 parent
5aa575f182
commit
6490665af8
28 files changed
+846
-51
No files matched your search
@@ -240,8 +240,23 @@ internal static class Program
|
||||
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);
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
using Ads.Desktop;
|
||||
using Xunit;
|
||||
namespace Ads.Desktop.Tests;
|
||||
public class SelectedPathTests
|
||||
{
|
||||
[Fact]
|
||||
public void SelectedToolIsSavedEvenWhileServerTextIsInvalid()
|
||||
{
|
||||
var folder=Path.Combine(Path.GetTempPath(),"ads-path-"+Guid.NewGuid().ToString("N"));
|
||||
try {
|
||||
using var vm=new MainViewModel(folder,backgroundMonitoring:false,loadLocalCredentials:false);
|
||||
vm.Server="incomplete address";
|
||||
vm.AdbPath="C:/tools/adb.exe";
|
||||
vm.UsbipPath="C:/tools/usbip.exe";
|
||||
vm.PersistSelectedPaths();
|
||||
var saved=DesktopPaths.LoadSettings(Path.Combine(folder,"settings.json"));
|
||||
Assert.Equal(vm.AdbPath,saved.Adb);
|
||||
Assert.Equal(vm.UsbipPath,saved.UsbipPath);
|
||||
} finally {if(Directory.Exists(folder))Directory.Delete(folder,true);}
|
||||
}
|
||||
}
|
||||
@@ -7,8 +7,8 @@
|
||||
<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 IsVisible="{Binding !LocalMode}"><TextBlock Text="远程管理使用工作台的控制中心地址,需要独立的管理员凭据。" TextWrapping="Wrap"/><TextBlock Text="{Binding AdminPath}" 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="本机配置路径"/><Grid ColumnDefinitions="*,Auto"><TextBox Text="{Binding ConfigPath}"/><Button Grid.Column="1" Content="选择" Click="ChooseConfigClick"/></Grid><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>
|
||||
@@ -25,7 +25,7 @@
|
||||
<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 IsVisible="{Binding LocalMode}"><TextBlock Text="首次设置:填写上方配置及设备端凭据后初始化,再启动后台 Agent。" TextWrapping="Wrap"/><TextBlock Text="{Binding EnrollmentPath}" 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>
|
||||
|
||||
@@ -10,8 +10,19 @@ public partial class AgentManagementView : UserControl
|
||||
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);}
|
||||
var directory=Path.GetDirectoryName(vm.RememberedPath(enrollment?"enrollment":"admin"));
|
||||
var location=directory is not null && Directory.Exists(directory) ? await top.StorageProvider.TryGetFolderFromPathAsync(new Uri(Path.GetFullPath(directory))) : null;
|
||||
var files=await top.StorageProvider.OpenFilePickerAsync(new FilePickerOpenOptions{SuggestedStartLocation=location,Title=enrollment?"选择 agent.env":"选择 admin.env",AllowMultiple=false,FileTypeFilter=[new FilePickerFileType("环境配置"){Patterns=["*.env"]}]});
|
||||
if(files.FirstOrDefault()?.TryGetLocalPath() is {} path){vm.RememberPath(enrollment?"enrollment":"admin",path);if(enrollment)vm.ImportEnrollment(path);else vm.ImportAdmin(path);}
|
||||
}catch(Exception error){vm.Notice=error.Message;}
|
||||
}
|
||||
private async void ChooseConfigClick(object? sender,RoutedEventArgs e)
|
||||
{
|
||||
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="选择 Agent 配置",AllowMultiple=false,FileTypeFilter=[new FilePickerFileType("JSON"){Patterns=["*.json"]},FilePickerFileTypes.All]});
|
||||
if(files.FirstOrDefault()?.TryGetLocalPath() is {} path){vm.ConfigPath=path;vm.RememberPath("config",path);}
|
||||
}catch(Exception error){vm.Notice=error.Message;}
|
||||
}
|
||||
private async void ImportAdminClick(object? sender,RoutedEventArgs e)=>await Import(false);
|
||||
|
||||
@@ -56,6 +56,11 @@ public partial class AgentManagementViewModel : ObservableObject, IDisposable
|
||||
public AgentManagementViewModel(Func<(string,string)> server, Action<string>? logger=null, bool background=true, bool credentials=true)
|
||||
{
|
||||
this.server=server; log=logger ?? (_=>{});
|
||||
try {
|
||||
var paths=Path.Combine(DesktopPaths.SettingsFolder,"agent-ui-paths.json");
|
||||
if(File.Exists(paths))foreach(var entry in JsonSerializer.Deserialize<Dictionary<string,string>>(File.ReadAllText(paths)) ?? new())chosenPaths[entry.Key]=entry.Value;
|
||||
if(chosenPaths.TryGetValue("config",out var config))ConfigPath=config;
|
||||
}catch(Exception e){Notice="读取文件位置失败:"+e.Message;}
|
||||
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) {
|
||||
@@ -68,6 +73,16 @@ public partial class AgentManagementViewModel : ObservableObject, IDisposable
|
||||
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");
|
||||
private readonly Dictionary<string,string> chosenPaths = new();
|
||||
public string AdminPath=>RememberedPath("admin");
|
||||
public string EnrollmentPath=>RememberedPath("enrollment");
|
||||
public string RememberedPath(string key) => chosenPaths.GetValueOrDefault(key,"");
|
||||
public void RememberPath(string key,string path) {
|
||||
chosenPaths[key]=path;OnPropertyChanged(nameof(AdminPath));OnPropertyChanged(nameof(EnrollmentPath));
|
||||
Directory.CreateDirectory(DesktopPaths.SettingsFolder);
|
||||
var file=Path.Combine(DesktopPaths.SettingsFolder,"agent-ui-paths.json");
|
||||
File.WriteAllText(file,JsonSerializer.Serialize(chosenPaths));
|
||||
}
|
||||
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);}
|
||||
@@ -98,14 +113,14 @@ public partial class AgentManagementViewModel : ObservableObject, IDisposable
|
||||
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="管理员凭据已加载,内容仅保存在内存中。";
|
||||
RememberPath("admin",path);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="设备端凭据已加载,仅供本机初始化使用。";
|
||||
RememberPath("enrollment",path);EnrollmentToken=value;Notice="设备端凭据已加载,仅供本机初始化使用。";
|
||||
}
|
||||
private RelayOptions Options(){var(s,o)=server();return RelayOptions.Parse(s,o,AdminToken);}
|
||||
private async Task Guard(Func<Task> action)
|
||||
|
||||
@@ -12,7 +12,7 @@ public sealed record ConnectionOptions(RelayOptions Relay, string Client, string
|
||||
public partial class DeviceConnection : ObservableObject, IDisposable
|
||||
{
|
||||
public string DeviceId { get; }
|
||||
public ConnectionOptions Options { get; }
|
||||
public ConnectionOptions Options { get; private set; }
|
||||
public string Mode => Options.UsbMode ? "USB ADB" : "网络 ADB";
|
||||
public string PortSummary => $"隧道 {Options.Port}" + (Options.UsbPort is { } u ? $" · USB/IP {u}" : "") + (ScreenPort is { } p ? $" · 投屏 {p}" : "");
|
||||
public string RawEndpoint => $"127.0.0.1:{Options.Port}";
|
||||
@@ -29,6 +29,11 @@ public partial class DeviceConnection : ObservableObject, IDisposable
|
||||
[ObservableProperty] private string apiLevel = "—";
|
||||
[ObservableProperty] private string notice = "";
|
||||
private Process? client, scrcpy;
|
||||
private bool screenWanted, usbBroken;
|
||||
private (string Path,int Size,int Fps,bool Audio,bool ViewOnly,int Port)? screenRequest;
|
||||
private int missingUsbPolls, recoveryAttempts, stablePolls;
|
||||
private DateTime nextRecovery=DateTime.MinValue;
|
||||
private CancellationTokenSource? recoveryCancellation;
|
||||
private WindowsUsbSession? usb;
|
||||
private string? transportFile, leaseFile;
|
||||
private readonly Action<string> log;
|
||||
@@ -94,10 +99,11 @@ public partial class DeviceConnection : ObservableObject, IDisposable
|
||||
if (disposed || !HasConnection || !await gate.WaitAsync(0)) return;
|
||||
try {
|
||||
if (scrcpy is { HasExited: true }) {
|
||||
if(scrcpy.ExitCode==0)screenWanted=false; else if(scrcpy.ExitCode==2 && Options.UsbMode)usbBroken=true;
|
||||
log($"手机控制窗口已关闭,退出码 {scrcpy.ExitCode}。");
|
||||
scrcpy.Dispose(); scrcpy = null; ScreenRunning = false; ScreenPort = null;
|
||||
}
|
||||
if (client is { HasExited: true } || usb is { HasExited: true }) {
|
||||
if (!Options.UsbMode && client is { HasExited: true }) {
|
||||
var reason = client is { HasExited: true } ? $"连接程序退出,代码 {client.ExitCode}" : "USB 模拟进程退出";
|
||||
await DisconnectCoreAsync(); Status = reason; Notice = reason + ",可重新连接。"; log(Notice); return;
|
||||
}
|
||||
@@ -119,11 +125,50 @@ public partial class DeviceConnection : ObservableObject, IDisposable
|
||||
"device" => "已连接 · 可调试和控制", "unauthorized" => "等待手机允许此电脑调试",
|
||||
"offline" => "设备离线 · 正在恢复连接", _ => "正在恢复连接 · 等待设备或网络"
|
||||
};
|
||||
if(Options.UsbMode) {
|
||||
var unauthorized=row?[1]=="unauthorized";
|
||||
if(Ready && !usbBroken && usb is not {HasExited:true} && client is not {HasExited:true}) {missingUsbPolls=0;if(++stablePolls>=10)recoveryAttempts=0;}
|
||||
else if(!unauthorized && (++missingUsbPolls>=3 || usbBroken || usb is {HasExited:true} || client is {HasExited:true}) && DateTime.UtcNow>=nextRecovery) {
|
||||
stablePolls=0;await RecoverUsbCoreAsync();return;
|
||||
}
|
||||
}
|
||||
if(Ready && screenWanted && !ScreenRunning && screenRequest is {} request && DateTime.UtcNow>=nextRecovery) {
|
||||
nextRecovery=DateTime.UtcNow.AddSeconds(5);
|
||||
var restoredPort=ConnectionPorts.Allocate(request.Port,new[]{Options.Port,Options.UsbPort??0});
|
||||
await StartScreenCoreAsync(request.Path,request.Size,request.Fps,request.Audio,request.ViewOnly,restoredPort);
|
||||
}
|
||||
if (Ready && !wasReady) { log("设备已就绪。"); await ReadInfoCoreAsync(); }
|
||||
} catch (OperationCanceledException) when (lifetime.IsCancellationRequested) { }
|
||||
catch (Exception error) { Ready = false; Notice = error.Message; log(error.Message); }
|
||||
finally { gate.Release(); }
|
||||
}
|
||||
private async Task RecoverUsbCoreAsync()
|
||||
{
|
||||
recoveryCancellation?.Dispose();
|
||||
recoveryCancellation=CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token);
|
||||
var cancellation=recoveryCancellation.Token;
|
||||
nextRecovery=DateTime.UtcNow.AddSeconds(new[]{2,4,8,16,30}[Math.Min(recoveryAttempts++,4)]);
|
||||
Status="USB 会话中断 · 正在重新挂载";Ready=false;missingUsbPolls=0;
|
||||
log($"USB 自动恢复,第 {recoveryAttempts} 次。");
|
||||
try {
|
||||
await StopScreenCoreAsync(false);
|
||||
if(usb!=null){await usb.StopAsync(log);usb.Dispose();usb=null;}
|
||||
cancellation.ThrowIfCancellationRequested();
|
||||
if(client is null || client.HasExited) {
|
||||
client?.Dispose();
|
||||
if(File.Exists(leaseFile!))File.Delete(leaseFile!);
|
||||
var info=ProcessTools.ClientStartInfo(Options.Client,Options.Adb,Options.Relay,DeviceId,RawEndpoint);
|
||||
foreach(var arg in new[]{"--transport",Options.RelayOnly?"relay":"auto","--status-file",transportFile!,"--no-auto-connect","--lease-status-file",leaseFile!})info.ArgumentList.Add(arg);
|
||||
client=Start(info);
|
||||
}
|
||||
var newPort=ConnectionPorts.Allocate(Options.UsbPort is >=65535 ?3240:Options.UsbPort!.Value+1,new[]{Options.Port,ScreenPort??0});
|
||||
Options=Options with {UsbPort=newPort};OnPropertyChanged(nameof(PortSummary));
|
||||
usb=new WindowsUsbSession(DeviceId);
|
||||
await usb.StartAsync(Options.Usbip,newPort,RawEndpoint,leaseFile!,log,cancellation);
|
||||
Endpoint=usb.Serial;usbBroken=false;Status="USB 已重新挂载 · 等待 ADB 就绪";
|
||||
} catch(OperationCanceledException) when(cancellation.IsCancellationRequested) { }
|
||||
catch(Exception error){Notice="USB 恢复失败,稍后重试:"+error.Message;log(Notice);}
|
||||
}
|
||||
public void MonitoringFailed(string message) { Ready = false; Status = "ADB 检测失败"; Notice = message; }
|
||||
public Task ReadInfoAsync() => Exclusive(ReadInfoCoreAsync);
|
||||
private async Task ReadInfoCoreAsync()
|
||||
@@ -136,7 +181,8 @@ public partial class DeviceConnection : ObservableObject, IDisposable
|
||||
ApiLevel = lines.ElementAtOrDefault(2)?.Trim() ?? "未知";
|
||||
Notice = "设备信息已更新。";
|
||||
}
|
||||
public Task StartScreenAsync(string path, int size, int fps, bool audio, bool viewOnly, int port) => Exclusive(async () =>
|
||||
public Task StartScreenAsync(string path, int size, int fps, bool audio, bool viewOnly, int port) => Exclusive(()=>StartScreenCoreAsync(path,size,fps,audio,viewOnly,port));
|
||||
private async Task StartScreenCoreAsync(string path, int size, int fps, bool audio, bool viewOnly, int port)
|
||||
{
|
||||
if (!Ready || Endpoint == null || ScreenRunning) return;
|
||||
if (size is < 256 or > 8192 || fps is < 1 or > 240) throw new InvalidOperationException("分辨率范围 256–8192,帧率范围 1–240。");
|
||||
@@ -145,19 +191,22 @@ public partial class DeviceConnection : ObservableObject, IDisposable
|
||||
var args = new List<string> { "--serial", Endpoint, "--force-adb-forward", "--window-title", $"ADS · {DeviceId}", "--max-size", size.ToString(), "--max-fps", fps.ToString(), "--port", port.ToString() };
|
||||
if (!audio) args.Add("--no-audio"); if (viewOnly) args.Add("--no-control");
|
||||
var info = ProcessTools.CreateStartInfo(executable, args); info.Environment["ADB"] = Options.Adb;
|
||||
screenRequest=(path,size,fps,audio,viewOnly,port);screenWanted=true;
|
||||
scrcpy = Start(info); ScreenPort = port; ScreenRunning = true; Notice = "手机控制窗口已启动。"; log(Notice);
|
||||
});
|
||||
public Task StopScreenAsync() => Exclusive(StopScreenCoreAsync);
|
||||
private async Task StopScreenCoreAsync()
|
||||
}
|
||||
public Task StopScreenAsync() {screenWanted=false;return Exclusive(()=>StopScreenCoreAsync());}
|
||||
private async Task StopScreenCoreAsync(bool cancelResume=true)
|
||||
{
|
||||
if(cancelResume)screenWanted=false;
|
||||
var current = scrcpy; scrcpy = null;
|
||||
try { await ProcessTools.StopAsync(current); }
|
||||
finally { ScreenRunning = false; ScreenPort = null; }
|
||||
}
|
||||
public Task DisconnectAsync() => Exclusive(DisconnectCoreAsync);
|
||||
public Task DisconnectAsync() {screenWanted=false;recoveryCancellation?.Cancel();return Exclusive(DisconnectCoreAsync);}
|
||||
// Shutdown must also work after the shared cancellation token has been cancelled.
|
||||
public async Task ShutdownAsync()
|
||||
{
|
||||
screenWanted=false;recoveryCancellation?.Cancel();
|
||||
await gate.WaitAsync();
|
||||
try { await DisconnectCoreAsync(); }
|
||||
finally { gate.Release(); }
|
||||
|
||||
@@ -454,6 +454,17 @@ public partial class MainViewModel : ObservableObject, IDisposable
|
||||
ToolsStatus = string.Join(" · ", results); Notice = ToolsStatus;
|
||||
});
|
||||
|
||||
public void PersistSelectedPaths()
|
||||
{
|
||||
try {
|
||||
var selected=DesktopPaths.LoadSettings(settingsFile);
|
||||
selected.Client=ClientPath;selected.Adb=AdbPath;selected.Scrcpy=ScrcpyPath;
|
||||
selected.UsbipPath=UsbipPath;selected.CredentialFile=credentialFile;
|
||||
DesktopPaths.SaveSettings(settingsFile,selected);
|
||||
Notice="文件位置已保存。";
|
||||
}catch(Exception error){Report(error);}
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void Save()
|
||||
{
|
||||
|
||||
@@ -128,7 +128,7 @@
|
||||
<TextBlock Text="可选 USB 模拟 · Windows" Classes="section"/>
|
||||
<CheckBox x:Name="UsbModeCheck" Content="将远程手机挂载为本机 USB ADB 设备" IsChecked="{Binding UsbMode}"/>
|
||||
<TextBlock Text="需要安装 USBip 虚拟控制器驱动。仅模拟 ADB 接口;首次使用仍需手机授权,修改在下次连接生效。" Classes="label" TextWrapping="Wrap"/>
|
||||
<TextBlock Text="usbip.exe 路径"/><TextBox Text="{Binding UsbipPath}" Watermark="C:\Program Files\USBip\usbip.exe"/>
|
||||
<TextBlock Text="usbip.exe 路径"/><Grid ColumnDefinitions="*,Auto"><TextBox Text="{Binding UsbipPath}" Watermark="usbip.exe"/><Button Grid.Column="1" Content="选择" Tag="usbip" Click="ChooseToolClick"/></Grid>
|
||||
<Grid ColumnDefinitions="*,180"><TextBlock Text="起始 USB/IP 端口(自动分配)" VerticalAlignment="Center"/><NumericUpDown Grid.Column="1" Value="{Binding UsbPort}" Minimum="1024" Maximum="65535"/></Grid>
|
||||
<TextBlock Text="驱动安装方式见项目 docs/windows-usb.md;默认网络 ADB 模式不需要此组件。" Classes="label" TextWrapping="Wrap"/>
|
||||
</StackPanel></Border>
|
||||
|
||||
@@ -20,7 +20,7 @@ public partial class MainWindow : Window
|
||||
Title = "选择客户端凭据 client.env", AllowMultiple = false,
|
||||
FileTypeFilter = [new FilePickerFileType("环境配置文件") { Patterns = ["*.env"] }, FilePickerFileTypes.All]
|
||||
});
|
||||
if (files.FirstOrDefault()?.TryGetLocalPath() is { } path) vm.LoadCredentials(path);
|
||||
if (files.FirstOrDefault()?.TryGetLocalPath() is { } path) { vm.LoadCredentials(path); vm.PersistSelectedPaths(); }
|
||||
}
|
||||
catch { vm.Notice = "无法打开凭据文件,请检查文件访问权限。"; }
|
||||
}
|
||||
@@ -36,8 +36,9 @@ public partial class MainWindow : Window
|
||||
{
|
||||
case "client": vm.ClientPath = path; break;
|
||||
case "adb": vm.AdbPath = path; break;
|
||||
case "scrcpy": vm.ScrcpyPath = path; break;
|
||||
case "scrcpy": vm.ScrcpyPath = path; break; case "usbip": vm.UsbipPath = path; break;
|
||||
}
|
||||
vm.PersistSelectedPaths();
|
||||
}
|
||||
catch { vm.Notice = "无法选择工具,请检查文件访问权限。"; }
|
||||
}
|
||||
|
||||
@@ -80,3 +80,9 @@ ADB、USB/IP 和 scrcpy 转发端口分别自动分配,避开其他连接和
|
||||
## Windows 单实例
|
||||
|
||||
Windows 桌面入口与 Flutter 共用同一会话级单实例锁(包括 --agent-tray 入口和不同安装路径)。重复启动会唤起正在运行的桌面窗口并退出新进程,避免重复托盘及重复设备管理。后台 Agent 和设备连接进程不受该 UI 锁限制。DesktopInstance.cs 使用 Windows 命名事件通知,由 Avalonia UI 线程恢复窗口。非 Windows 暂保留原启动行为。
|
||||
|
||||
## 路径选择与 USB 自动恢复
|
||||
|
||||
本机工具、USBip、客户端凭据及本机 Agent 配置提供文件选择对话框,选取后立即记忆文件位置。Agent 管理记忆管理员及初始化凭据文件位置,令牌内容仍仅在内存。URL/IP/端口继续按网络地址填写。
|
||||
|
||||
USB 连续缺失 3 轮、USB 后端退出或投屏报告设备断开后,自动等待租约、选择新回环端口重挂载;必要时重启本次 ads-client,并按原分辨率、帧率和控制设置恢复 scrcpy。重试带 2/4/8/16/30 秒退避,等待手机授权时暂停重挂载。主动停止投屏、关闭投屏窗口、主动断开和退出取消相应恢复。其他设备与物理 USB 手机不受影响。
|
||||
@@ -113,3 +113,15 @@ USB 模式禁用网络 adb connect,等待租约后挂载,ADB 与 scrcpy 使
|
||||
Windows 下 Flutter 和 Avalonia 两个桌面入口共享会话级单实例锁,安装版、便携版和 Agent 托盘入口都不能重复启动第二个 ADS 桌面实例。重复启动会退出新进程并唤起已有窗口(包括托盘隐藏或最小化状态)。仅限制桌面管理 UI,不限制无界面 Agent/client 或多个设备的 scrcpy 子进程。非 Windows 平台尚未接入此单实例机制。
|
||||
|
||||
本轮验证:Flutter 17 项测试与 Avalonia 20 项测试通过。真实虚拟 USB 上验证内嵌转独立窗口实际显示、USB 连接与桥接进程保持不变;重复启动退出并恢复隐藏主窗口通过。Avalonia 作为主实例时,重复启动 Avalonia 或 Flutter 均退出,主实例正常保留。
|
||||
|
||||
## 文件位置与 USB 自动恢复
|
||||
|
||||
工具/凭据/Agent 配置的文件路径输入框带文件选择按钮,选中后立即保存位置;取消不修改设置。服务器 URL、IP 和端口仍为网络地址输入。保存的只是文件路径,不保存凭据内容。Agent 路径随连接设置一同记忆。
|
||||
|
||||
USB ADB 连续 3 轮监控缺失(约 9 秒)、USB 后端退出或 scrcpy 以设备断开退出时,自动关闭本次旧导出、选择新的回环端口、等待租约并重新挂载。ads-client 异常退出时按该连接启动时的参数重启。失败按 2/4/8/16/30 秒退避,等待手机授权时不循环重挂载;多个恢复不会并行操作同一设备。
|
||||
|
||||
记住用户是否希望投屏及原内嵌/独立模式,USB/ADB 就绪后恢复投屏。主动停止投屏、关闭独立窗口、主动断开和退出取消相应恢复,不重启已停止的投屏,也不操作物理 USB 手机或其他客户端的设备。这是断线后的恢复流程,不承诺原有视频/ADB 字节流无缝续传,也不等于已消除网络断开的根因。
|
||||
|
||||
内嵌投屏的自动恢复遵循页面可见性:离开投屏页或缩到托盘时继续修复 USB 连接,但暂不重新创建内嵌画面;返回投屏页并显示窗口后恢复。独立窗口模式按原模式恢复。
|
||||
|
||||
本轮验证:文件路径选择/取消及立即保存测试、USB 恢复状态机与窗口可见性测试通过。真机主动结束本次 ads-client 后,USB 和软件渲染投屏自动恢复并重新出图;主动停止不再自动启动。测试使用了仅中继对照,恢复逻辑不依赖选择 P2P 或中继。Avalonia 真机亦验证客户端故障后 USB 重挂载及 scrcpy 重新出图。
|
||||
@@ -5,11 +5,13 @@ import 'dart:io';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
import 'windows_usb.dart';
|
||||
import 'usb_recovery.dart';
|
||||
|
||||
class Settings {
|
||||
String server = 'wss://ttstd.com/ads';
|
||||
String origin = '175.178.213.60:443';
|
||||
String credential = '';
|
||||
Map<String, String> agentPaths = {};
|
||||
String client = '', adb = '', scrcpy = '';
|
||||
bool relayOnly = false, usbMode = false;
|
||||
String usbip = UsbDriver.defaultUsbip();
|
||||
@@ -17,6 +19,7 @@ class Settings {
|
||||
'server': server,
|
||||
'origin': origin,
|
||||
'credential': credential,
|
||||
'agentPaths': agentPaths,
|
||||
'client': client,
|
||||
'adb': adb,
|
||||
'scrcpy': scrcpy,
|
||||
@@ -28,6 +31,7 @@ class Settings {
|
||||
server = j['server'] as String? ?? server;
|
||||
origin = j['origin'] as String? ?? origin;
|
||||
credential = j['credential'] as String? ?? credential;
|
||||
agentPaths = Map<String, String>.from(j['agentPaths'] as Map? ?? {});
|
||||
client = j['client'] as String? ?? client;
|
||||
adb = j['adb'] as String? ?? adb;
|
||||
scrcpy = j['scrcpy'] as String? ?? scrcpy;
|
||||
@@ -64,7 +68,16 @@ class Session {
|
||||
WindowsUsbSession? usb;
|
||||
String get endpoint => usb?.serial ?? tunnel;
|
||||
String get mode => usb == null ? "网络 ADB" : "虚拟 USB";
|
||||
final Process process;
|
||||
Process process;
|
||||
Future<Process> Function()? restartClient;
|
||||
final recovery = UsbRecoveryPolicy();
|
||||
String usbip = '', usbExecutable = '';
|
||||
bool recovering = false,
|
||||
initialized = false,
|
||||
screenWanted = false,
|
||||
usbBroken = false;
|
||||
Future<void>? recoveryTask;
|
||||
bool screenPageVisible = false;
|
||||
Process? screen;
|
||||
bool screenEmbedded = false;
|
||||
String state = '连接中', route = '协商中';
|
||||
@@ -77,6 +90,7 @@ class ManagerRepository {
|
||||
final Map<String, Session> sessions = {};
|
||||
final Set<int> reservedPorts = {};
|
||||
final void Function(String) log;
|
||||
bool allowEmbeddedResume = true;
|
||||
String token = '';
|
||||
Directory? root;
|
||||
late Directory storage;
|
||||
@@ -336,19 +350,24 @@ class ManagerRepository {
|
||||
'transport-$id-${DateTime.now().microsecondsSinceEpoch}.json',
|
||||
);
|
||||
final lease = usbMode ? "$status.lease" : null;
|
||||
final proc = await Process.start(
|
||||
settings.client,
|
||||
final clientExecutable = settings.client, adbExecutable = settings.adb;
|
||||
final serverAddress = settings.server.trim(),
|
||||
originAddress = settings.origin.trim();
|
||||
final transportMode = settings.relayOnly ? 'relay' : 'auto';
|
||||
final clientEnvironment = environment()..['ADS_CLIENT_TOKEN'] = token;
|
||||
Future<Process> startClient() => Process.start(
|
||||
clientExecutable,
|
||||
[
|
||||
'--server',
|
||||
settings.server.trim(),
|
||||
serverAddress,
|
||||
'--device',
|
||||
id,
|
||||
'--listen',
|
||||
endpoint,
|
||||
'--adb',
|
||||
settings.adb,
|
||||
adbExecutable,
|
||||
'--transport',
|
||||
settings.relayOnly ? 'relay' : 'auto',
|
||||
transportMode,
|
||||
'--status-file',
|
||||
status,
|
||||
if (lease != null) ...[
|
||||
@@ -356,26 +375,21 @@ class ManagerRepository {
|
||||
'--lease-status-file',
|
||||
lease,
|
||||
],
|
||||
if (settings.origin.trim().isNotEmpty) ...[
|
||||
'--connect-address',
|
||||
settings.origin.trim(),
|
||||
],
|
||||
if (originAddress.isNotEmpty) ...['--connect-address', originAddress],
|
||||
],
|
||||
environment: environment()..['ADS_CLIENT_TOKEN'] = token,
|
||||
environment: clientEnvironment,
|
||||
includeParentEnvironment: false,
|
||||
);
|
||||
final proc = await startClient();
|
||||
watch(proc, id);
|
||||
session = Session(id, endpoint, settings.adb, status, proc);
|
||||
final current = session;
|
||||
sessions[id] = current;
|
||||
current.leaseFile = lease;
|
||||
unawaited(
|
||||
proc.exitCode.then((code) {
|
||||
current.exited = true;
|
||||
current.ready = false;
|
||||
current.state = '连接程序已退出 ($code)';
|
||||
}),
|
||||
);
|
||||
current.restartClient = startClient;
|
||||
current.usbip = usbip;
|
||||
current.usbExecutable = findTool('ads-usb');
|
||||
observeClient(current, proc);
|
||||
if (usbMode) {
|
||||
final usb = WindowsUsbSession(id, usbPort!);
|
||||
current.usb = usb;
|
||||
@@ -392,6 +406,7 @@ class ManagerRepository {
|
||||
);
|
||||
log('USB 已挂载:${usb.serial}');
|
||||
}
|
||||
current.initialized = true;
|
||||
return current;
|
||||
} catch (_) {
|
||||
if (session != null) {
|
||||
@@ -442,11 +457,11 @@ class ManagerRepository {
|
||||
Future<void> monitor() async {
|
||||
final listings = <String, String>{};
|
||||
for (final s in sessions.values.toList()) {
|
||||
if (!s.stopping && (s.exited || s.usb?.exited == true)) {
|
||||
if (s.usb == null && !s.stopping && s.exited) {
|
||||
await disconnect(s.id);
|
||||
continue;
|
||||
}
|
||||
if (s.stopping) {
|
||||
if (s.stopping || s.recovering || !s.initialized) {
|
||||
continue;
|
||||
}
|
||||
try {
|
||||
@@ -458,6 +473,29 @@ class ManagerRepository {
|
||||
.where((r) => r.length >= 2 && r[0] == s.endpoint)
|
||||
.firstOrNull;
|
||||
s.ready = row?[1] == 'device';
|
||||
if (s.usb != null &&
|
||||
s.recovery.due(
|
||||
DateTime.now(),
|
||||
ready: s.ready,
|
||||
unauthorized: row?[1] == 'unauthorized',
|
||||
broken: s.exited || s.usb!.exited || s.usbBroken,
|
||||
)) {
|
||||
scheduleUsbRecovery(s);
|
||||
continue;
|
||||
}
|
||||
if (s.ready &&
|
||||
s.screenWanted &&
|
||||
(!s.screenEmbedded ||
|
||||
(s.screenPageVisible && allowEmbeddedResume)) &&
|
||||
s.screen == null &&
|
||||
!DateTime.now().isBefore(s.recovery.retryAt)) {
|
||||
s.recovery.attempted(DateTime.now());
|
||||
try {
|
||||
await screen(s, embedded: s.screenEmbedded);
|
||||
} catch (e) {
|
||||
log('[${s.id}] 恢复投屏失败:$e');
|
||||
}
|
||||
}
|
||||
s.state = row == null ? '等待设备 / 自动重连' : row[1];
|
||||
final file = File(s.statusFile);
|
||||
if (await file.exists()) {
|
||||
@@ -473,16 +511,107 @@ class ManagerRepository {
|
||||
}
|
||||
}
|
||||
|
||||
void observeClient(Session s, Process process) {
|
||||
unawaited(
|
||||
process.exitCode.then((code) {
|
||||
if (s.process != process) {
|
||||
return;
|
||||
}
|
||||
s.exited = true;
|
||||
s.ready = false;
|
||||
s.state = '连接程序已退出 ($code)';
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
Future<void> stopScreen(Session s) async {
|
||||
s.screenWanted = false;
|
||||
final process = s.screen;
|
||||
s.screen = null;
|
||||
await stop(process);
|
||||
log('[${s.id}] 用户停止投屏,取消自动恢复');
|
||||
}
|
||||
|
||||
void scheduleUsbRecovery(Session s) {
|
||||
if (s.stopping || s.recovering) {
|
||||
return;
|
||||
}
|
||||
s.recovering = true;
|
||||
s.ready = false;
|
||||
s.recovery.attempted(DateTime.now());
|
||||
s.state = 'USB 会话中断 · 正在重新挂载';
|
||||
log('[${s.id}] USB 自动恢复,第 ${s.recovery.attempts} 次');
|
||||
s.recoveryTask = recoverUsb(s).whenComplete(() => s.recovering = false);
|
||||
}
|
||||
|
||||
Future<void> recoverUsb(Session s) async {
|
||||
try {
|
||||
final screen = s.screen;
|
||||
s.screen = null;
|
||||
await stop(screen);
|
||||
final old = s.usb!;
|
||||
await stop(old.bridge);
|
||||
reservedPorts.remove(old.port);
|
||||
if (s.stopping) {
|
||||
return;
|
||||
}
|
||||
if (s.exited) {
|
||||
final lease = File(s.leaseFile!);
|
||||
if (await lease.exists()) {
|
||||
await lease.delete();
|
||||
}
|
||||
s.process = await s.restartClient!();
|
||||
s.exited = false;
|
||||
watch(s.process, s.id);
|
||||
observeClient(s, s.process);
|
||||
}
|
||||
if (s.stopping) {
|
||||
return;
|
||||
}
|
||||
final port = await allocateUsbPort();
|
||||
final usb = WindowsUsbSession(s.id, port);
|
||||
s.usb = usb;
|
||||
await usb.start(
|
||||
leaseFile: s.leaseFile!,
|
||||
upstream: s.tunnel,
|
||||
executable: s.usbExecutable,
|
||||
usbip: s.usbip,
|
||||
environment: environment(),
|
||||
run: run,
|
||||
watch: watch,
|
||||
cancelled: () => s.stopping || s.exited,
|
||||
);
|
||||
s.usbBroken = false;
|
||||
s.recovery.missing = 0;
|
||||
s.state = 'USB 已重新挂载 · 等待 ADB 就绪';
|
||||
log('[${s.id}] USB 已重新挂载;设备就绪后恢复投屏');
|
||||
} catch (e) {
|
||||
// No unhandled async exception; monitor retries with bounded backoff.
|
||||
try {
|
||||
await stop(s.usb?.bridge);
|
||||
} catch (_) {}
|
||||
if (!s.stopping) {
|
||||
s.state = 'USB 恢复失败 · 稍后重试';
|
||||
log('[${s.id}] USB 恢复失败:$e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Future<void> screen(Session s, {bool embedded = false}) async {
|
||||
if (!s.ready) {
|
||||
if (s.stopping) {
|
||||
return;
|
||||
}
|
||||
s.screenWanted = true;
|
||||
if (!s.ready || s.recovering || s.stopping) {
|
||||
return;
|
||||
}
|
||||
if (s.screen != null) {
|
||||
if (s.screenEmbedded == embedded) {
|
||||
return;
|
||||
}
|
||||
await stop(s.screen);
|
||||
final previous = s.screen;
|
||||
s.screen = null;
|
||||
await stop(previous);
|
||||
}
|
||||
final proc = await launchScreen(
|
||||
s.endpoint,
|
||||
@@ -490,6 +619,10 @@ class ManagerRepository {
|
||||
s.id,
|
||||
embedded: embedded,
|
||||
);
|
||||
if (s.stopping || !s.screenWanted) {
|
||||
await stop(proc);
|
||||
return;
|
||||
}
|
||||
s.screen = proc;
|
||||
s.screenEmbedded = embedded;
|
||||
watch(proc, 'scrcpy ${s.id}');
|
||||
@@ -497,6 +630,11 @@ class ManagerRepository {
|
||||
proc.exitCode.then((code) {
|
||||
if (s.screen == proc) {
|
||||
s.screen = null;
|
||||
if (code == 0) {
|
||||
s.screenWanted = false;
|
||||
} else if (!s.stopping && code == 2 && s.usb != null) {
|
||||
s.usbBroken = true;
|
||||
}
|
||||
}
|
||||
log('投屏窗口关闭 ($code)');
|
||||
}),
|
||||
@@ -549,6 +687,8 @@ class ManagerRepository {
|
||||
return;
|
||||
}
|
||||
s.stopping = true;
|
||||
s.screenWanted = false;
|
||||
await s.recoveryTask;
|
||||
for (final proc in [s.screen, s.usb?.bridge, s.process]) {
|
||||
try {
|
||||
await stop(proc);
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
/// Poll-based hysteresis and bounded retry delay, independent of processes/UI.
|
||||
class UsbRecoveryPolicy {
|
||||
int missing = 0, attempts = 0, stable = 0;
|
||||
DateTime retryAt = DateTime.fromMillisecondsSinceEpoch(0);
|
||||
bool due(
|
||||
DateTime now, {
|
||||
required bool ready,
|
||||
bool unauthorized = false,
|
||||
bool broken = false,
|
||||
}) {
|
||||
if (unauthorized) {
|
||||
missing = 0;
|
||||
stable = 0;
|
||||
return false;
|
||||
}
|
||||
if (ready && !broken) {
|
||||
missing = 0;
|
||||
if (++stable >= 10) {
|
||||
attempts = 0;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
stable = 0;
|
||||
missing++;
|
||||
return (broken || missing >= 3) && !now.isBefore(retryAt);
|
||||
}
|
||||
|
||||
void attempted(DateTime now) {
|
||||
final seconds = [2, 4, 8, 16, 30][attempts.clamp(0, 4)];
|
||||
attempts++;
|
||||
missing = 0;
|
||||
retryAt = now.add(Duration(seconds: seconds));
|
||||
}
|
||||
}
|
||||
@@ -12,7 +12,7 @@ class UsbDriver {
|
||||
static const hash =
|
||||
'38cad6d4432b52d5bb9409d9ad03b72fdffc4ada4cd3a48fbeca1a2752a8518a';
|
||||
static String defaultUsbip() => p.join(
|
||||
Platform.environment['ProgramFiles'] ?? r'C:Program Files',
|
||||
Platform.environment['ProgramFiles'] ?? 'C:/Program Files',
|
||||
'USBip',
|
||||
'usbip.exe',
|
||||
);
|
||||
|
||||
@@ -82,6 +82,7 @@ class _ManagerAppState extends State<ManagerApp>
|
||||
@override
|
||||
void onWindowClose() {
|
||||
if (trayReady) {
|
||||
widget.model.repository.allowEmbeddedResume = false;
|
||||
unawaited(windowManager.hide());
|
||||
} else {
|
||||
unawaited(quit());
|
||||
@@ -90,10 +91,26 @@ class _ManagerAppState extends State<ManagerApp>
|
||||
|
||||
@override
|
||||
void onTrayIconMouseDown() {
|
||||
widget.model.repository.allowEmbeddedResume = true;
|
||||
unawaited(windowManager.show());
|
||||
unawaited(windowManager.focus());
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowMinimize() {
|
||||
widget.model.repository.allowEmbeddedResume = false;
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowRestore() {
|
||||
widget.model.repository.allowEmbeddedResume = true;
|
||||
}
|
||||
|
||||
@override
|
||||
void onWindowFocus() {
|
||||
widget.model.repository.allowEmbeddedResume = true;
|
||||
}
|
||||
|
||||
@override
|
||||
void onTrayIconRightMouseDown() {
|
||||
unawaited(trayManager.popUpContextMenu());
|
||||
|
||||
@@ -18,6 +18,7 @@ class AgentModel extends ChangeNotifier {
|
||||
ManagedAgent? get selected =>
|
||||
_agents.where((a) => a.id == selectedId).firstOrNull;
|
||||
bool localMode = false, busy = false, autoRefresh = true, followLogs = false;
|
||||
Future<void> Function(String, String)? savePath;
|
||||
String adminPath = '',
|
||||
enrollmentPath = '',
|
||||
enrollmentToken = '',
|
||||
|
||||
@@ -3,6 +3,7 @@ import 'package:material_ui/material_ui.dart';
|
||||
import '../data/agent_models.dart';
|
||||
|
||||
import 'agent_model.dart';
|
||||
import 'path_picker.dart';
|
||||
|
||||
class AgentView extends StatefulWidget {
|
||||
const AgentView({super.key, required this.model});
|
||||
@@ -42,6 +43,24 @@ class _AgentViewState extends State<AgentView> {
|
||||
: null,
|
||||
decoration: InputDecoration(
|
||||
labelText: label,
|
||||
suffixIcon: ['configPath', 'admin', 'enroll'].contains(key)
|
||||
? IconButton(
|
||||
tooltip: '选择文件并保存',
|
||||
icon: const Icon(Icons.folder_open),
|
||||
onPressed: m.busy
|
||||
? null
|
||||
: () => m.run(() async {
|
||||
final selected = await pickPath(controller.text);
|
||||
if (selected == null || !mounted) {
|
||||
return;
|
||||
}
|
||||
controller.text = selected;
|
||||
change(selected);
|
||||
await m.savePath?.call(key, selected);
|
||||
m.notice = '文件位置已保存';
|
||||
}),
|
||||
)
|
||||
: null,
|
||||
border: const OutlineInputBorder(),
|
||||
),
|
||||
),
|
||||
|
||||
@@ -172,7 +172,13 @@ class ScreenPage extends StatelessWidget {
|
||||
const SizedBox(height: 12),
|
||||
Expanded(
|
||||
child: pid == null
|
||||
? const Center(child: Text('投屏已停止,请返回设备重新打开。'))
|
||||
? Center(
|
||||
child: Text(
|
||||
s?.screenWanted == true
|
||||
? '连接中断,正在恢复 USB 和投屏…'
|
||||
: '投屏已停止,请返回设备重新打开。',
|
||||
),
|
||||
)
|
||||
: s?.screenEmbedded == true
|
||||
? EmbeddedScreen(key: ValueKey(pid), pid: pid)
|
||||
: const Center(child: Text('投屏已在独立窗口运行,设备连接保持不变。')),
|
||||
|
||||
@@ -47,13 +47,28 @@ class ManagerModel extends ChangeNotifier {
|
||||
Future<void> init() async {
|
||||
await action(() async {
|
||||
await repository.init();
|
||||
agents.savePath = (key, value) async {
|
||||
repository.settings.agentPaths[key] = value;
|
||||
await repository.save();
|
||||
};
|
||||
await agents.initialize(
|
||||
adminFile: repository.root == null
|
||||
? p.join(p.dirname(Platform.resolvedExecutable), 'admin.env')
|
||||
: p.join(repository.root!.path, 'config', 'private', 'admin.env'),
|
||||
adminFile:
|
||||
repository.settings.agentPaths['admin'] ??
|
||||
(repository.root == null
|
||||
? p.join(p.dirname(Platform.resolvedExecutable), 'admin.env')
|
||||
: p.join(
|
||||
repository.root!.path,
|
||||
'config',
|
||||
'private',
|
||||
'admin.env',
|
||||
)),
|
||||
server: repository.settings.server,
|
||||
origin: repository.settings.origin,
|
||||
);
|
||||
agents.configPath =
|
||||
repository.settings.agentPaths['configPath'] ?? agents.configPath;
|
||||
agents.enrollmentPath =
|
||||
repository.settings.agentPaths['enroll'] ?? agents.enrollmentPath;
|
||||
notice = '准备就绪';
|
||||
});
|
||||
await refresh();
|
||||
|
||||
@@ -9,6 +9,7 @@ import '../data/manager_repository.dart';
|
||||
import 'manager_model.dart';
|
||||
import 'agent_view.dart';
|
||||
import 'embedded_screen.dart';
|
||||
import 'path_picker.dart';
|
||||
|
||||
class ManagerView extends StatefulWidget {
|
||||
final ManagerModel model;
|
||||
@@ -82,7 +83,13 @@ class _ManagerViewState extends State<ManagerView> {
|
||||
fontSize: 14,
|
||||
),
|
||||
),
|
||||
onTap: () => setState(() => page = i),
|
||||
onTap: () {
|
||||
for (final session
|
||||
in m.repository.sessions.values) {
|
||||
session.screenPageVisible = false;
|
||||
}
|
||||
setState(() => page = i);
|
||||
},
|
||||
),
|
||||
),
|
||||
const Spacer(),
|
||||
@@ -183,12 +190,18 @@ class _ManagerViewState extends State<ManagerView> {
|
||||
}
|
||||
}),
|
||||
session: m.repository.sessions[screenDevice],
|
||||
onBack: () => setState(() => page = 0),
|
||||
onBack: () {
|
||||
m
|
||||
.repository
|
||||
.sessions[screenDevice]
|
||||
?.screenPageVisible =
|
||||
false;
|
||||
setState(() => page = 0);
|
||||
},
|
||||
onStop: () => m.deviceAction(screenDevice!, () async {
|
||||
final s = m.repository.sessions[screenDevice];
|
||||
if (s != null) {
|
||||
await m.repository.stop(s.screen);
|
||||
s.screen = null;
|
||||
await m.repository.stopScreen(s);
|
||||
}
|
||||
}),
|
||||
),
|
||||
@@ -384,6 +397,7 @@ class _ManagerViewState extends State<ManagerView> {
|
||||
await m.repository.screen(s, embedded: true);
|
||||
if (mounted) {
|
||||
setState(() {
|
||||
s.screenPageVisible = true;
|
||||
screenDevice = s.id;
|
||||
page = 6;
|
||||
});
|
||||
@@ -529,7 +543,13 @@ class _ManagerViewState extends State<ManagerView> {
|
||||
class SettingsView extends StatefulWidget {
|
||||
final ManagerModel model;
|
||||
final Future<bool> Function()? driverInstalled;
|
||||
const SettingsView({super.key, required this.model, this.driverInstalled});
|
||||
final Future<String?> Function(String, bool)? chooseFile;
|
||||
const SettingsView({
|
||||
super.key,
|
||||
required this.model,
|
||||
this.driverInstalled,
|
||||
this.chooseFile,
|
||||
});
|
||||
@override
|
||||
State<SettingsView> createState() => _SettingsViewState();
|
||||
}
|
||||
@@ -692,7 +712,33 @@ class _SettingsViewState extends State<SettingsView> {
|
||||
padding: const EdgeInsets.only(bottom: 18),
|
||||
child: TextField(
|
||||
controller: fields[key],
|
||||
decoration: InputDecoration(labelText: label),
|
||||
decoration: InputDecoration(
|
||||
labelText: label,
|
||||
suffixIcon: ['server', 'origin'].contains(key)
|
||||
? null
|
||||
: IconButton(
|
||||
tooltip: '选择文件并保存',
|
||||
icon: const Icon(Icons.folder_open),
|
||||
onPressed: () => widget.model.action(() async {
|
||||
final selected =
|
||||
await (widget.chooseFile?.call(
|
||||
fields[key]!.text,
|
||||
key != "credential",
|
||||
) ??
|
||||
pickPath(
|
||||
fields[key]!.text,
|
||||
executable: key != 'credential',
|
||||
));
|
||||
if (selected == null || !mounted) {
|
||||
return;
|
||||
}
|
||||
fields[key]!.text = selected;
|
||||
apply();
|
||||
await widget.model.repository.save();
|
||||
widget.model.notice = '文件位置已保存';
|
||||
}),
|
||||
),
|
||||
),
|
||||
),
|
||||
),
|
||||
SwitchListTile(
|
||||
|
||||
@@ -0,0 +1,19 @@
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:file_selector/file_selector.dart';
|
||||
import 'package:path/path.dart' as p;
|
||||
|
||||
Future<String?> pickPath(String value, {bool executable = false}) async {
|
||||
final directory = value.isEmpty ? null : p.dirname(value);
|
||||
final selected = await openFile(
|
||||
initialDirectory: directory != null && Directory(directory).existsSync()
|
||||
? directory
|
||||
: null,
|
||||
acceptedTypeGroups: executable
|
||||
? [
|
||||
const XTypeGroup(label: '可执行程序', extensions: ['exe']),
|
||||
]
|
||||
: [],
|
||||
);
|
||||
return selected?.path;
|
||||
}
|
||||
@@ -137,6 +137,14 @@ packages:
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "3.1.2"
|
||||
cross_file:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: cross_file
|
||||
sha256: f141ea4f277af142a0356955707f6556f37b03947d39d55585981a06ca437bd6
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "0.3.5+5"
|
||||
crypto:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
@@ -185,6 +193,70 @@ packages:
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "7.0.1"
|
||||
file_selector:
|
||||
dependency: "direct main"
|
||||
description:
|
||||
name: file_selector
|
||||
sha256: bd15e43e9268db636b53eeaca9f56324d1622af30e5c34d6e267649758c84d9a
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.1.0"
|
||||
file_selector_android:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_selector_android
|
||||
sha256: d670cd0ce77a2e785b18d8b4d0a8d6a222d6a813ec9b7ddf2790a1b4fb6fa92c
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "0.5.2+11"
|
||||
file_selector_ios:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_selector_ios
|
||||
sha256: "5b42ec0ef7626124b4624ea244341e9df780406793c204e89fa68a2e71af115c"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "0.5.3+7"
|
||||
file_selector_linux:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_selector_linux
|
||||
sha256: da76400e7872ce7637ffdce12749ec24169c25f6195c28372208e65a24bcd2ab
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "0.9.4+1"
|
||||
file_selector_macos:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_selector_macos
|
||||
sha256: d785431f1910aac8a50e5c492cae912320158030a88703c67b9ef7f1f96fd7ba
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "0.9.5+2"
|
||||
file_selector_platform_interface:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_selector_platform_interface
|
||||
sha256: "35e0bd61ebcdb91a3505813b055b09b79dfdc7d0aee9c09a7ba59ae4bb13dc85"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.7.0"
|
||||
file_selector_web:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_selector_web
|
||||
sha256: "73181fbc5257776d8ecaa6a94ab3c8e920ad143b9132a6d984a9271dfc6928d3"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "0.9.5"
|
||||
file_selector_windows:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: file_selector_windows
|
||||
sha256: fbefc5fb92c6d3cbe8d284a2cd971b593bb07d2cd6da8557b81a862250b4acec
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "0.9.3+6"
|
||||
fixnum:
|
||||
dependency: transitive
|
||||
description:
|
||||
@@ -216,6 +288,11 @@ packages:
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
flutter_web_plugins:
|
||||
dependency: transitive
|
||||
description: flutter
|
||||
source: sdk
|
||||
version: "0.0.0"
|
||||
freezed:
|
||||
dependency: "direct dev"
|
||||
description:
|
||||
@@ -248,6 +325,14 @@ packages:
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "2.3.2"
|
||||
http:
|
||||
dependency: transitive
|
||||
description:
|
||||
name: http
|
||||
sha256: "87721a4a50b19c7f1d49001e51409bddc46303966ce89a65af4f4e6004896412"
|
||||
url: "https://pub.flutter-io.cn"
|
||||
source: hosted
|
||||
version: "1.6.0"
|
||||
http_multi_server:
|
||||
dependency: transitive
|
||||
description:
|
||||
|
||||
@@ -40,6 +40,7 @@ dependencies:
|
||||
path: ^1.9.1
|
||||
freezed_annotation: ^3.1.0
|
||||
crypto: ^3.0.8
|
||||
file_selector: ^1.1.0
|
||||
|
||||
dev_dependencies:
|
||||
flutter_test:
|
||||
|
||||
@@ -7,6 +7,7 @@ Future<void> main(List<String> args) async {
|
||||
try {
|
||||
await repo.init();
|
||||
repo.settings.usbMode = args.contains('--usb');
|
||||
repo.settings.relayOnly = args.contains('--relay-only');
|
||||
final devices = await repo.devices();
|
||||
stdout.writeln(
|
||||
'API devices: ${devices.map((d) => "${d.id} busy=${d.busy}").join(", ")}',
|
||||
@@ -23,6 +24,7 @@ Future<void> main(List<String> args) async {
|
||||
return;
|
||||
}
|
||||
final s = await repo.connect(device.id);
|
||||
s.screenPageVisible = true;
|
||||
for (var i = 0; i < 20 && !s.ready && !s.exited; i++) {
|
||||
await Future<void>.delayed(const Duration(seconds: 3));
|
||||
await repo.monitor();
|
||||
@@ -34,13 +36,53 @@ Future<void> main(List<String> args) async {
|
||||
'Remote model: ${await repo.run(s.adb, ['-s', s.endpoint, 'shell', 'getprop', 'ro.product.model'])}',
|
||||
);
|
||||
if (args.contains('--screen')) {
|
||||
await repo.screen(s);
|
||||
await repo.screen(s, embedded: args.contains('--embedded'));
|
||||
await Future<void>.delayed(const Duration(seconds: 8));
|
||||
if (s.screen == null) {
|
||||
throw StateError('scrcpy exited early');
|
||||
}
|
||||
stdout.writeln('scrcpy process alive: ${s.screen!.pid}');
|
||||
}
|
||||
if (args.contains('--recover')) {
|
||||
final original = s.process.pid;
|
||||
final oldBridge = s.usb!.bridge!.pid;
|
||||
final wantedMode = s.screenEmbedded;
|
||||
await repo.stop(s.process);
|
||||
var recovered = false;
|
||||
for (var i = 0; i < 80; i++) {
|
||||
await Future<void>.delayed(const Duration(seconds: 1));
|
||||
await repo.monitor();
|
||||
if (!s.recovering &&
|
||||
s.ready &&
|
||||
s.process.pid != original &&
|
||||
s.usb!.bridge!.pid != oldBridge &&
|
||||
s.screen != null) {
|
||||
recovered = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!recovered) {
|
||||
throw StateError(
|
||||
'USB/client/screen automatic recovery did not complete: ${s.state}',
|
||||
);
|
||||
}
|
||||
if (s.screenEmbedded != wantedMode) {
|
||||
throw StateError('Screen mode was not preserved');
|
||||
}
|
||||
await Future<void>.delayed(const Duration(seconds: 8));
|
||||
if (s.screen == null || !s.ready) {
|
||||
throw StateError('Recovered screen did not remain running');
|
||||
}
|
||||
stdout.writeln('RECOVERY PASS: client + USB remount + scrcpy restored');
|
||||
await repo.stopScreen(s);
|
||||
for (var i = 0; i < 4; i++) {
|
||||
await Future<void>.delayed(const Duration(seconds: 1));
|
||||
await repo.monitor();
|
||||
}
|
||||
if (s.screen != null || s.screenWanted) {
|
||||
throw StateError('Manual stop restarted screen');
|
||||
}
|
||||
}
|
||||
if (args.contains('--usb')) {
|
||||
final path = await repo.run(s.adb, ['-s', s.endpoint, 'get-devpath']);
|
||||
// Windows ADB may return "unknown" for get-devpath. USB-only selection
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
import 'dart:io';
|
||||
import 'dart:convert';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:material_ui/material_ui.dart';
|
||||
import 'package:ads_manager/ui/manager_model.dart';
|
||||
import 'package:ads_manager/ui/manager_view.dart';
|
||||
|
||||
void main() {
|
||||
for (final cancelled in [false, true]) {
|
||||
testWidgets('file picker saves immediately; cancelled=$cancelled', (
|
||||
tester,
|
||||
) async {
|
||||
tester.view.physicalSize = const Size(1280, 1800);
|
||||
tester.view.devicePixelRatio = 1;
|
||||
addTearDown(tester.view.resetPhysicalSize);
|
||||
addTearDown(tester.view.resetDevicePixelRatio);
|
||||
final folder = Directory.systemTemp.createTempSync('ads-path-test');
|
||||
final model = ManagerModel();
|
||||
model.repository.storage = folder;
|
||||
try {
|
||||
await tester.pumpWidget(
|
||||
MaterialApp(
|
||||
home: Scaffold(
|
||||
body: SettingsView(
|
||||
model: model,
|
||||
chooseFile: (current, executable) async {
|
||||
expect(executable, true);
|
||||
return cancelled ? null : 'C:/SDK/adb.exe';
|
||||
},
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
final buttons = find.byTooltip('选择文件并保存');
|
||||
expect(buttons, findsNWidgets(5));
|
||||
await tester.ensureVisible(buttons.at(2));
|
||||
await tester.runAsync(() async {
|
||||
await tester.tap(buttons.at(2));
|
||||
for (
|
||||
var i = 0;
|
||||
i < 100 && !cancelled && model.notice != '文件位置已保存';
|
||||
i++
|
||||
) {
|
||||
await Future<void>.delayed(const Duration(milliseconds: 20));
|
||||
}
|
||||
});
|
||||
await tester.pumpAndSettle();
|
||||
final file = File('${folder.path}/settings.json');
|
||||
if (cancelled) {
|
||||
expect(file.existsSync(), false);
|
||||
} else {
|
||||
expect(model.repository.settings.adb, 'C:/SDK/adb.exe');
|
||||
final saved =
|
||||
jsonDecode(file.readAsStringSync()) as Map<String, dynamic>;
|
||||
expect(saved['adb'], 'C:/SDK/adb.exe');
|
||||
expect(saved.containsKey('token'), false);
|
||||
}
|
||||
await tester.pumpWidget(const SizedBox());
|
||||
model.dispose();
|
||||
} finally {
|
||||
folder.deleteSync(recursive: true);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
import 'dart:async';
|
||||
import 'dart:io';
|
||||
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
import 'package:ads_manager/data/manager_repository.dart';
|
||||
import 'package:ads_manager/data/windows_usb.dart';
|
||||
import 'package:ads_manager/data/usb_recovery.dart';
|
||||
|
||||
class FakeProcess extends Fake implements Process {
|
||||
final exit = Completer<int>();
|
||||
@override
|
||||
int get pid => 123;
|
||||
@override
|
||||
Future<int> get exitCode => exit.future;
|
||||
@override
|
||||
bool kill([ProcessSignal signal = ProcessSignal.sigterm]) {
|
||||
if (!exit.isCompleted) {
|
||||
exit.complete(-1);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
class RecoveryRepo extends ManagerRepository {
|
||||
RecoveryRepo() : super((_) {});
|
||||
@override
|
||||
void watch(Process process, String label) {}
|
||||
String listing = '';
|
||||
int remounts = 0, screens = 0;
|
||||
bool? resumedEmbedded;
|
||||
Completer<void>? hold;
|
||||
@override
|
||||
Future<String> run(String exe, List<String> args) async => listing;
|
||||
@override
|
||||
Future<void> recoverUsb(Session s) async {
|
||||
remounts++;
|
||||
if (hold != null) {
|
||||
await hold!.future;
|
||||
}
|
||||
s.usbBroken = false;
|
||||
}
|
||||
|
||||
@override
|
||||
Future<Process> launchScreen(
|
||||
String endpoint,
|
||||
String adb,
|
||||
String id, {
|
||||
bool embedded = false,
|
||||
}) async {
|
||||
screens++;
|
||||
resumedEmbedded = embedded;
|
||||
return FakeProcess();
|
||||
}
|
||||
}
|
||||
|
||||
void main() {
|
||||
test('embedded video waits for its page and visible main window', () async {
|
||||
final repo = RecoveryRepo();
|
||||
final s =
|
||||
Session('phone', '127.0.0.1:15555', 'adb', 'missing', FakeProcess())
|
||||
..usb = WindowsUsbSession('phone', 3240)
|
||||
..initialized = true
|
||||
..screenWanted = true
|
||||
..screenEmbedded = true;
|
||||
repo.sessions[s.id] = s;
|
||||
repo.listing = '${s.endpoint}\tdevice\n';
|
||||
await repo.monitor();
|
||||
expect(repo.screens, 0);
|
||||
s.screenPageVisible = true;
|
||||
repo.allowEmbeddedResume = false;
|
||||
await repo.monitor();
|
||||
expect(repo.screens, 0);
|
||||
repo.allowEmbeddedResume = true;
|
||||
await repo.monitor();
|
||||
expect(repo.screens, 1);
|
||||
await repo.stopScreen(s);
|
||||
});
|
||||
test('requires three missed polls; ignores unauthorized and backs off', () {
|
||||
final policy = UsbRecoveryPolicy();
|
||||
final now = DateTime(2026);
|
||||
expect(policy.due(now, ready: false), false);
|
||||
expect(policy.due(now, ready: false), false);
|
||||
expect(policy.due(now, ready: false), true);
|
||||
policy.attempted(now);
|
||||
expect(policy.due(now, ready: false, broken: true), false);
|
||||
expect(
|
||||
policy.due(
|
||||
now.add(const Duration(seconds: 2)),
|
||||
ready: false,
|
||||
broken: true,
|
||||
),
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
policy.due(
|
||||
now.add(const Duration(seconds: 30)),
|
||||
ready: false,
|
||||
unauthorized: true,
|
||||
broken: true,
|
||||
),
|
||||
false,
|
||||
);
|
||||
for (var i = 0; i < 12; i++) {
|
||||
policy.attempted(now);
|
||||
}
|
||||
expect(policy.retryAt.difference(now).inSeconds, 30);
|
||||
});
|
||||
test('one remount task at a time, then resumes the requested mode', () async {
|
||||
final repo = RecoveryRepo();
|
||||
final session =
|
||||
Session('phone', '127.0.0.1:15555', 'adb', 'missing', FakeProcess())
|
||||
..usb = WindowsUsbSession('phone', 3240)
|
||||
..initialized = true
|
||||
..screenWanted = true
|
||||
..screenPageVisible = true
|
||||
..screenEmbedded = true;
|
||||
repo.sessions[session.id] = session;
|
||||
repo.hold = Completer<void>();
|
||||
for (var i = 0; i < 5; i++) {
|
||||
await repo.monitor();
|
||||
}
|
||||
expect(repo.remounts, 1);
|
||||
expect(session.recovering, true);
|
||||
repo.hold!.complete();
|
||||
await session.recoveryTask;
|
||||
session.recovery.retryAt = DateTime(2026);
|
||||
repo.listing = '${session.endpoint}\tdevice\n';
|
||||
await repo.monitor();
|
||||
expect(repo.screens, 1);
|
||||
expect(repo.resumedEmbedded, true);
|
||||
expect(session.screenWanted, true);
|
||||
await repo.stopScreen(session);
|
||||
await repo.monitor();
|
||||
expect(repo.screens, 1);
|
||||
expect(session.screenWanted, false);
|
||||
});
|
||||
test('stopping a session prevents remount and screen restart', () async {
|
||||
final repo = RecoveryRepo();
|
||||
final session =
|
||||
Session('phone', '127.0.0.1:15555', 'adb', 'missing', FakeProcess())
|
||||
..usb = WindowsUsbSession('phone', 3240)
|
||||
..initialized = true
|
||||
..stopping = true;
|
||||
repo.sessions[session.id] = session;
|
||||
for (var i = 0; i < 5; i++) {
|
||||
await repo.monitor();
|
||||
}
|
||||
await repo.screen(session, embedded: true);
|
||||
expect(repo.remounts, 0);
|
||||
expect(repo.screens, 0);
|
||||
expect(session.screenWanted, false);
|
||||
});
|
||||
test('path settings persist paths, not credential contents', () {
|
||||
final settings = Settings()
|
||||
..agentPaths = {'admin': 'C:/admin.env', 'configPath': 'C:/agent.json'};
|
||||
final loaded = Settings()..load(settings.toJson());
|
||||
expect(loaded.agentPaths, settings.agentPaths);
|
||||
});
|
||||
}
|
||||
@@ -6,11 +6,14 @@
|
||||
|
||||
#include "generated_plugin_registrant.h"
|
||||
|
||||
#include <file_selector_windows/file_selector_windows.h>
|
||||
#include <screen_retriever_windows/screen_retriever_windows_plugin_c_api.h>
|
||||
#include <tray_manager/tray_manager_plugin.h>
|
||||
#include <window_manager/window_manager_plugin.h>
|
||||
|
||||
void RegisterPlugins(flutter::PluginRegistry* registry) {
|
||||
FileSelectorWindowsRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("FileSelectorWindows"));
|
||||
ScreenRetrieverWindowsPluginCApiRegisterWithRegistrar(
|
||||
registry->GetRegistrarForPlugin("ScreenRetrieverWindowsPluginCApi"));
|
||||
TrayManagerPluginRegisterWithRegistrar(
|
||||
|
||||
@@ -3,6 +3,7 @@
|
||||
#
|
||||
|
||||
list(APPEND FLUTTER_PLUGIN_LIST
|
||||
file_selector_windows
|
||||
screen_retriever_windows
|
||||
tray_manager
|
||||
window_manager
|
||||
|
||||
Reference in new issue
Block a user