XFE Git
XFE Studio Git
Git 首页 全局搜索
XFE 主站 文档 NuGet

XFEWorkflow

【WinUI】XFE基于windows的工作流

公开
关注 0 Fork 0 Star 0
UTF-8
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Text.Json.Nodes;
using System.Text.Json;
using System.Runtime.InteropServices;
using System.Runtime.InteropServices.WindowsRuntime;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Core.Runtime;
using XFEWorkflow.Infrastructure.Storage;

namespace XFEWorkflow.Services;

internal static partial class UiSmokeTest
{
    public static async Task RunAsync(string output)
    {
        Directory.CreateDirectory(output);
        var checks = new List<object>(); var errors = new List<string>();
        var selectedCheck = Environment.GetCommandLineArgs().FirstOrDefault(x => x.StartsWith("--ui-check=", StringComparison.Ordinal))?["--ui-check=".Length..];
        var selectedChecks = selectedCheck?.Split(',', StringSplitOptions.RemoveEmptyEntries | StringSplitOptions.TrimEntries).ToHashSet(StringComparer.Ordinal);
        async Task Check(string name, Func<Task> operation)
        {
            if (selectedChecks is not null && !selectedChecks.Contains(name)) return;
            try { await operation().WaitAsync(TimeSpan.FromSeconds(60)); checks.Add(new { name, passed = true }); }
            catch (Exception ex) { errors.Add(name + ":" + ex); checks.Add(new { name, passed = false, error = ex.Message }); }
            await AtomicJson.WriteAsync(Path.Combine(output, "ui-results.json"), new { checks, errors });
        }
        var window = App.MainWindow.AppWindow;
        var workArea = Microsoft.UI.Windowing.DisplayArea.GetFromWindowId(window.Id, Microsoft.UI.Windowing.DisplayAreaFallback.Nearest).WorkArea;
        // Windows cascades newly launched windows. Keep enlarged test views
        // on screen instead of sending a drag to an off-screen separator.
        var originalPosition = window.Position;
        window.Move(new(workArea.X + 16, workArea.Y + 16));
        var background = Environment.GetCommandLineArgs().Contains("--ui-background");
        App.MainWindow.AppWindow.Show(!background); if (!background) App.MainWindow.Activate();
        await AtomicJson.WriteAsync(Path.Combine(output, "ui-environment.json"), new { originalX = originalPosition.X, originalY = originalPosition.Y, x = window.Position.X, y = window.Position.Y, workArea = new { x = workArea.X, y = workArea.Y, width = workArea.Width, height = workArea.Height }, desktop = Plugins.Vision.ScreenCapture.DesktopBounds });
        var services = AppServices.Current; await services.Ready;
        AppShellPage.Current!.ViewModel.NavigationViewService.NavigateTo<MainPage>();
        await Task.Delay(350); // Allow the frame transition and initial layout to settle before UIA.
        await AtomicJson.WriteAsync(Path.Combine(output, "ui-results.json"), new { checks, errors });
        await Check("offline-monaco-and-canvas-undo", async () =>
        {
            var page = MainPage.Current ?? throw new InvalidOperationException("主页面未加载");
            await page.SmokeEditorAsync(Path.Combine(output, "editor.png"));
        });
        await Check("workflow-mode-preservation-and-categorized-palette", () => MainPage.Current!.SmokeModesAndPaletteAsync());
        await Check("graph-to-csharp-real-code-update-manual-preservation-preview-and-restore", () => MainPage.Current!.SmokeGraphCodeGenerationAsync(output));
        await Check("rapid-mode-switch-no-roslyn-cancellation-or-stale-diagnostics", () => MainPage.Current!.SmokeRapidModeSwitchAsync(output));
        await Check("winui-design-layout-themes-rename-and-docked-panels", () => MainPage.Current!.SmokeDesignAsync(output));
        await Check("compact-palette-collapse-favorites-recent-source-filter-and-keyboard", () => MainPage.Current!.SmokePaletteLibraryAsync(output));
        await Check("native-splitters-resize-constraints-persistence-navigation-and-browser", () => MainPage.Current!.SmokeResizablePanelsAsync(output));
        await Check("canvas-centered-mouse-pan-and-light-dark-theme", () => MainPage.Current!.SmokePanAsync(output));
        await Check("canvas-wheel-zooms-at-pointer-without-control", () => MainPage.Current!.SmokeWheelAsync(output));
        await Check("canvas-ring-centers-native-drag-preview-release-cancel-and-zoom", () => MainPage.Current!.SmokeWiresAsync(output));
        await Check("canvas-native-target-reconnect-blank-disconnect-escape-types-and-undo", () => MainPage.Current!.SmokeReconnectAsync(output));
        await Check("docked-editor-native-target-reconnect-disconnect-and-keyboard-undo", () => SmokeDockedReconnectAsync(output));
        await Check("canvas-target-reconnect-state-types-cycles-cancel-and-undo", () => MainPage.Current!.SmokeReconnectStateAsync(output));
        await Check("canvas-rounded-wire-caps-card-occlusion-and-port-terminals", () => MainPage.Current!.SmokeWirePresentationAsync(output));
        await Check("typed-ports-disconnect-tooltips-property-bindings-and-stable-mode-viewport", () => MainPage.Current!.SmokeTypedWorkbenchAsync(output));
        await Check("background-run-log-flood-bounded-batching-and-responsive-ui", () => MainPage.Current!.SmokeRunFloodAsync(output));
        await Check("docked-editor-native-breakpoints-f5-f10-f11-and-quiet-output", () => SmokeDebuggingAsync(output));
        await Check("object-fields-wired-parameters-native-f5-and-readable-unicode-json", () => SmokeObjectFieldsAsync(output));
        await Check("basic-nodes-csharp-keyword-search-literal-text-typed-wires-and-native-f5", () => SmokeBasicNodesAsync(output));
        await Check("typed-literal-inline-arrays-objects-variables-precision-save-and-winui-undo", () => SmokeTypedValuesAsync(output));
        await Check("log-operations-palette-file-picker-inline-port-details-and-themes", () => MainPage.Current!.SmokeLogOperationsAsync(output));
        await Check("workflow-library-triggers-circular-badges-and-xfe-log-output", () => MainPage.Current!.SmokeWorkflowChromeAsync(output));
        await Check("trigger-nodes-palette-properties-scheduling-delete-and-code-workflows", () => MainPage.Current!.SmokeTriggerNodesAsync(output));
        await Check("workflow-list-activation-editor-multiple-tabs-menus-and-device-icons", () => SmokeWorkflowDocumentsAsync(output));
        await Check("wecom-plugin-center-template-and-typed-trigger-form", () => SmokeWeComPanelAsync(output));
        await Check("output-diagnostics-connected-tab-surface-light-dark", () => MainPage.Current!.SmokeConnectedTabsAsync(output));
        await Check("management-plugin-runs-logs-settings-responsive-and-workflow-links", () => SmokeManagementPagesAsync(output));
        await Check("space-independent-navigation-plugin-and-workflow-publish-review-download-themes-and-resize", () => SmokeSpaceAsync(output));
        await Check("space-preview-readonly-graph-code-plugins-without-installation", () => SmokeSpaceAsync(Path.Combine(output, "preview-only"), false));
        await Check("agent-browser-plugin-deepseek-skill-webview-markdown-tools-and-stop", () => SmokeAgentBrowserAsync(output));
        await Check("agent-browser-session-history-persistence-and-restart", () => SmokeAgentSessionsAsync(output));
        await Check("vision-plugin-form-and-offline-ocr-through-runner", () => MainPage.Current!.SmokeVisionAsync(output));
        await Check("image-template-preview-reselect-similarity-export-and-runner", () => MainPage.Current!.SmokeImageTemplatesAsync(output));
        await Check("region-picker-mouse-drag-screen-ocr-point-and-cancel", () => Controls.ScreenRegionPicker.VerifyAsync(Path.Combine(output, "screen-region-picker.png")));
        await Check("tray-native-mica-light-dark-live-theme-and-dismissal", () => TrayMenuSmokeTest.ThemesAsync(output));
        await Check("tray-hidden-window-open-emergency-stop-and-resume", () => TrayMenuSmokeTest.CommandsAsync());
        var listener = new HttpListener(); var portSource = new TcpListener(IPAddress.Loopback, 0); portSource.Start();
        var port = ((IPEndPoint)portSource.LocalEndpoint).Port; portSource.Stop();
        var url = $"http://localhost:{port}/"; listener.Prefixes.Add(url); listener.Prefixes.Add($"http://127.0.0.1:{port}/"); listener.Start();
        var accountFixture = new AccountUiFixture(url);
        var server = Task.Run(async () =>
        {
            try
            {
                while (true)
                {
                    var request = await listener.GetContextAsync();
                    if (await accountFixture.HandleAsync(request)) continue;
                    if (request.Request.Url!.AbsolutePath == "/avatar.png")
                    {
                        request.Response.ContentType = "image/png";
                        await request.Response.OutputStream.WriteAsync(await File.ReadAllBytesAsync(Path.Combine(AppContext.BaseDirectory, "Assets", "icon.png")));
                        request.Response.Close(); continue;
                    }
                    var text = request.Request.Url!.AbsolutePath switch
                    {
                        "/frame" => "<html><body><input id='inside'><p id='nested'>跨域 iframe</p></body></html>",
                        "/download" => "XFEWorkflow 下载验收 中文",
                        _ => $"<html><body style='font:20px system-ui;padding:40px;background:#f1f5f9'><h1>XFEWorkflow 网页验收</h1><input id='text'><button onclick=\"document.querySelector('#result').textContent='clicked'\">点击</button><p id='result'>ready</p><iframe src='http://127.0.0.1:{port}/frame'></iframe></body></html>"
                    };
                    request.Response.ContentType = request.Request.Url.AbsolutePath == "/download" ? "application/octet-stream" : "text/html; charset=utf-8";
                    if (request.Request.Url.AbsolutePath == "/download") request.Response.Headers.Add("Content-Disposition", "attachment; filename=fixture.txt");
                    await request.Response.OutputStream.WriteAsync(Encoding.UTF8.GetBytes(text)); request.Response.Close();
                }
            }
            catch (Exception ex) when (ex is HttpListenerException or ObjectDisposedException) { }
        });
        string? tab = null; const string owner = "ui-smoke";
        var browser = services.Browser!;
        async Task<JsonObject> Invoke(string method, JsonObject input)
        {
            if (method != "open") input["tab"] = tab;
            return await browser.InvokeAsync(owner, "browser." + method, input, CancellationToken.None);
        }
        try
        {
            await Check("account-avatar-and-navigation-synchronization", async () =>
            {
                var address = services.State.SpaceAddress;
                services.State.SpaceAddress = url + "space/v1/";
                services.State.Store.Update(p => { p.InstanceSpaceUserAddress = services.State.SpaceAddress; p.InstanceSpaceUserJson = JsonSerializer.Serialize(new Space.Contracts.SpaceUser("smoke-user", "smoke-account", "验收用户", Space.Contracts.SpaceRole.Author, url + "avatar.png"), WorkflowJson.Options); });
                services.Space.Reconnect();
                var shell = AppShellPage.Current!;
                for (var i = 0; i < 40 && (shell.ViewModel.Avatar is not Microsoft.UI.Xaml.Media.Imaging.BitmapImage bitmap || bitmap.PixelWidth == 0); i++) await Task.Delay(100);
                shell.AssertAccountPresentation("验收用户", true);
                shell.ViewModel.NavigationViewService.NavigateTo<AccountPage>(); shell.SetNavigationOpenForSmoke(true); await Task.Delay(250);
                await CaptureWindowAsync(Path.Combine(output, "account-navigation.png"));
                await services.Space.LogoutAsync(); await Task.Delay(100); shell.AssertAccountPresentation("未登录", false);
                services.State.SpaceAddress = address; services.Space.Reconnect(); shell.SetNavigationOpenForSmoke(false);
                shell.ViewModel.NavigationViewService.NavigateTo<MainPage>();
            });
            await Check("account-header-popup-login-register-switch-logout-and-error", () => AppShellPage.Current!.SmokeAccountMenuAsync(output, url));
            await Check("account-profile-preview-save-error-reset-responsive-light-dark", () => AppShellPage.Current!.SmokeAccountProfileAsync(output, url, accountFixture));
            AppShellPage.Current?.ShowBrowser(true);
            await Check("webview-navigation-input-click-extract", async () =>
            {
                tab = (await Invoke("open", new() { ["profile"] = "smoke", ["url"] = url })).String("tab");
                await Invoke("wait", new() { ["selector"] = "#text" });
                await Invoke("input", new() { ["selector"] = "#text", ["text"] = "中文输入" });
                var value = await Invoke("script", new() { ["script"] = "return document.querySelector('#text').value;" });
                if (value.String("result") != "中文输入") throw new InvalidOperationException("中文输入不一致");
                await Invoke("click", new() { ["selector"] = "button" });
                if ((await Invoke("extract", new() { ["selector"] = "#result" })).String("text") != "clicked") throw new InvalidOperationException("点击或提取失败");
            });
            await Check("webview-screenshot", async () =>
            {
                var path = Path.Combine(output, "browser.png"); await Invoke("screenshot", new() { ["path"] = path }); var png = await File.ReadAllBytesAsync(path);
                if (png.Length < 2000 || System.Buffers.Binary.BinaryPrimitives.ReadInt32BigEndian(png.AsSpan(20, 4)) < 120) throw new InvalidOperationException("截图没有完整渲染的网页内容");
            });
            await Check("cross-origin-iframe", async () =>
            {
                await Invoke("wait", new() { ["selector"] = "#inside", ["frame"] = "0" });
                await Invoke("input", new() { ["selector"] = "#inside", ["frame"] = "0", ["text"] = "iframe中文" });
                if ((await Invoke("script", new() { ["frame"] = "0", ["script"] = "return document.querySelector('#inside').value;" })).String("result") != "iframe中文") throw new InvalidOperationException("iframe 输入失败");
            });
            await Check("element-picker", async () => { if (!(await browser.ProbePickerAsync(tab!)).Contains("selector=", StringComparison.Ordinal)) throw new InvalidOperationException("拾取未返回选择器"); });
            await Check("authenticated-profile-persistence", async () =>
            {
                await Invoke("script", new() { ["script"] = "document.cookie='xfe_smoke=persist;max-age=3600;path=/';return document.cookie;" });
                await Invoke("close", []); tab = (await Invoke("open", new() { ["profile"] = "smoke", ["url"] = url })).String("tab");
                if (!(await Invoke("script", new() { ["script"] = "return document.cookie;" })).String("result").Contains("xfe_smoke=persist", StringComparison.Ordinal)) throw new InvalidOperationException("登录配置未保留 Cookie");
            });
            await Check("webview-download", async () =>
            {
                var path = Path.Combine(output, "download.txt"); await Invoke("download", new() { ["url"] = url + "download", ["path"] = path });
                if (await File.ReadAllTextAsync(path) != "XFEWorkflow 下载验收 中文") throw new InvalidOperationException("下载内容错误");
            });
            await Check("desktop-uia3-fill-read-through-runner", async () =>
            {
                AppShellPage.Current?.ShowBrowser(false); MainPage.Current!.AddAutomationFixture(); await Task.Delay(250);
                var fill = new NodeDefinition { CapabilityId = "xfe.desktop.fill", TimeoutSeconds = 15, Parameters = new() { ["processId"] = Environment.ProcessId, ["automationId"] = "XfeSmokeInput", ["text"] = "中文自动化 🧩" } };
                var read = new NodeDefinition { CapabilityId = "xfe.desktop.read", TimeoutSeconds = 15, Parameters = new() { ["processId"] = Environment.ProcessId, ["automationId"] = "XfeSmokeInput" } };
                var flow = WorkflowTemplates.CreateGraph(); flow.Graph.Nodes.InsertRange(1, [fill, read]); flow.Graph.Edges.Clear();
                for (var i = 0; i < flow.Graph.Nodes.Count - 1; i++) flow.Graph.Edges.Add(new() { FromNode = flow.Graph.Nodes[i].Id, ToNode = flow.Graph.Nodes[i + 1].Id });
                flow.Graph.Nodes[^1].Parameters["result"] = new JsonObject { ["$node"] = read.Id + ".text" };
                var result = await services.Runs.RunAsync(flow); if (result.Status != RunStatus.Succeeded || result.Outputs.String("result") != "中文自动化 🧩") throw new InvalidOperationException(result.Error ?? "UIA3 中文读写不一致");
            });
            await Check("browser-runner-ipc-while-hidden", async () =>
            {
                var open = new NodeDefinition { CapabilityId = "xfe.browser.open", TimeoutSeconds = 20, Parameters = new() { ["profile"] = "ipc-smoke", ["url"] = url } };
                var script = new NodeDefinition { CapabilityId = "xfe.browser.script", Parameters = new() { ["tab"] = new JsonObject { ["$node"] = open.Id + ".tab" }, ["script"] = "return document.querySelector('#result').textContent;" } };
                var flow = WorkflowTemplates.CreateGraph(); flow.Graph.Nodes.InsertRange(1, [open, script]); flow.Graph.Edges.Clear();
                for (var i = 0; i < flow.Graph.Nodes.Count - 1; i++) flow.Graph.Edges.Add(new() { FromNode = flow.Graph.Nodes[i].Id, ToNode = flow.Graph.Nodes[i + 1].Id });
                flow.Graph.Nodes[^1].Parameters["result"] = new JsonObject { ["$node"] = script.Id + ".result" };
                App.MainWindow.AppWindow.Hide(); var result = await services.Runs.RunAsync(flow); App.MainWindow.AppWindow.Show();
                if (result.Status != RunStatus.Succeeded || result.Outputs.String("result") != "ready") throw new InvalidOperationException(result.Error ?? "浏览器 IPC 返回值错误");
            });
            await Check("navigation-pages", async () =>
            {
                var navigation = AppShellPage.Current!.ViewModel.NavigationViewService;
                foreach (var page in new[] { typeof(PluginsPage), typeof(SpacePage), typeof(AccountPage), typeof(RunsPage), typeof(CredentialsPage), typeof(LogViewPage), typeof(SettingPage), typeof(MainPage), typeof(BrowserPage), typeof(MainPage) })
                { navigation.NavigateTo(page.FullName!); await Task.Delay(200); }
                var invalid = WorkflowTemplates.CreateGraph(); invalid.Name = "错误定位验收";
                var code = new NodeDefinition { CapabilityId = "core.csharp", Code = "return invalid C#;" };
                invalid.Graph.Nodes.Insert(1, code); invalid.Graph.Edges.Clear();
                for (var i = 0; i < invalid.Graph.Nodes.Count - 1; i++) invalid.Graph.Edges.Add(new() { FromNode = invalid.Graph.Nodes[i].Id, ToNode = invalid.Graph.Nodes[i + 1].Id });
                await services.Workflows.SaveAsync(invalid);
                var failed = await services.Runs.RunAsync(invalid);
                if (failed.Status != RunStatus.Failed || failed.ErrorNodeId != code.Id) throw new InvalidOperationException("代码节点错误未定位");
                navigation.NavigateTo(typeof(RunsPage).FullName!); await Task.Delay(100);
                navigation.NavigateTo(typeof(MainPage).FullName!, failed.Id); await Task.Delay(500);
                if (MainPage.Current?.ViewModel.SelectedWorkflow?.Id != invalid.Id) throw new InvalidOperationException("运行记录未跳转到错误工作流");
            });
            await Check("hidden-window-runner-execution", async () =>
            {
                App.MainWindow.AppWindow.Hide(); var record = await services.Runs.RunAsync(WorkflowTemplates.Welcome());
                if (record.Status != RunStatus.Succeeded) throw new InvalidOperationException(record.Error);
            });
        }
        finally { listener.Close(); await server; await browser.ReleaseAsync(owner); }
        if (selectedCheck is not null && checks.Count == 0) errors.Add("未找到界面检查:" + selectedCheck);
        await AtomicJson.WriteAsync(Path.Combine(output, "ui-results.json"), new { passed = errors.Count == 0, checks, errors });
    }
    internal static async Task CaptureWindowAsync(string path)
    {
        var root = (Page)App.MainWindow.Content;
        var background = root.Background;
        try
        {
            root.Background = new Microsoft.UI.Xaml.Media.SolidColorBrush(root.ActualTheme == ElementTheme.Dark ? Microsoft.UI.ColorHelper.FromArgb(255, 32, 32, 32) : Microsoft.UI.ColorHelper.FromArgb(255, 243, 243, 243));
            await CaptureElementAsync(root, path);
        }
        finally { root.Background = background; }
    }
    internal static async Task CaptureElementAsync(FrameworkElement element, string path)
    {
        var bitmap = new Microsoft.UI.Xaml.Media.Imaging.RenderTargetBitmap(); await bitmap.RenderAsync(element);
        if (bitmap.PixelWidth <= 0 || bitmap.PixelHeight <= 0) throw new InvalidOperationException("测试界面未渲染,无法截图");
        var pixels = await bitmap.GetPixelsAsync();
        var folder = await Windows.Storage.StorageFolder.GetFolderFromPathAsync(Path.GetDirectoryName(path)!);
        var file = await folder.CreateFileAsync(Path.GetFileName(path), Windows.Storage.CreationCollisionOption.ReplaceExisting);
        using var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
        var encoder = await Windows.Graphics.Imaging.BitmapEncoder.CreateAsync(Windows.Graphics.Imaging.BitmapEncoder.PngEncoderId, stream);
        encoder.SetPixelData(Windows.Graphics.Imaging.BitmapPixelFormat.Bgra8, Windows.Graphics.Imaging.BitmapAlphaMode.Premultiplied, (uint)bitmap.PixelWidth, (uint)bitmap.PixelHeight, 96, 96, pixels.ToArray());
        await encoder.FlushAsync();
    }
    [StructLayout(LayoutKind.Sequential)] internal struct ScreenPoint { public int X, Y; }
    [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool ClientToScreen(nint window, ref ScreenPoint point);
    [DllImport("user32.dll", EntryPoint = "SetCursorPos", SetLastError = true)] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool MoveCursor(int x, int y);
    [DllImport("user32.dll")] [return: MarshalAs(UnmanagedType.Bool)] internal static extern bool SetForegroundWindow(nint window);
    [DllImport("user32.dll")] internal static extern nint GetForegroundWindow();
    [StructLayout(LayoutKind.Sequential)] private struct MousePacket
    { public int X, Y; public uint Data, Flags, Time; public nuint ExtraInfo; }
    [StructLayout(LayoutKind.Sequential)] private struct InputPacket
    { public uint Type; public InputData Data; }
    [StructLayout(LayoutKind.Sequential)] private struct KeyboardPacket
    { public ushort Key, Scan; public uint Flags, Time; public nuint ExtraInfo; }
    [StructLayout(LayoutKind.Explicit)] private struct InputData
    { [FieldOffset(0)] public MousePacket Mouse; [FieldOffset(0)] public KeyboardPacket Keyboard; }
    [DllImport("user32.dll", SetLastError = true)] private static extern uint SendInput(uint count, InputPacket[] inputs, int size);
    internal static void MouseButtonAt(int x, int y, bool down)
        => MouseAt(x, y, down ? 0x0002u : 0x0004u);
    internal static void MouseWheelAt(int x, int y, int delta)
        => MouseAt(x, y, 0x0800u, unchecked((uint)delta));
    internal static void MouseMoveAt(int x, int y) => MouseAt(x, y, 0);
    private static void MouseAt(int x, int y, uint flags, uint data = 0)
    {
        var bounds = XFEWorkflow.Plugins.Vision.ScreenCapture.DesktopBounds;
        // Move and button state form one native input packet, preventing a
        // physical mouse movement between separate test setup calls.
        var packet = new InputPacket { Data = new() { Mouse = new MousePacket {
            X = (int)Math.Round((x - bounds.X) * 65535d / (bounds.Width - 1)),
            Y = (int)Math.Round((y - bounds.Y) * 65535d / (bounds.Height - 1)),
            Flags = 0x8000u | 0x4000u | 0x0001u | flags, Data = data } } };
        if (SendInput(1, [packet], Marshal.SizeOf<InputPacket>()) != 1) throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
    }
    internal static IEnumerable<DependencyObject> Descendants(DependencyObject element)
    {
        yield return element;
        for (var i = 0; i < Microsoft.UI.Xaml.Media.VisualTreeHelper.GetChildrenCount(element); i++)
            foreach (var child in Descendants(Microsoft.UI.Xaml.Media.VisualTreeHelper.GetChild(element, i))) yield return child;
    }
    internal static void PressKey(Windows.System.VirtualKey key, bool control = false, Window? window = null, bool shift = false)
    {
        EnsureForeground(window);
        InputPacket Packet(Windows.System.VirtualKey value, bool up) => new() { Type = 1, Data = new() { Keyboard = new() { Key = (ushort)value, Flags = up ? 2u : 0 } } };
        var packets = new List<InputPacket>();
        if (control) packets.Add(Packet(Windows.System.VirtualKey.Control, false));
        if (shift) packets.Add(Packet(Windows.System.VirtualKey.Shift, false));
        packets.Add(Packet(key, false)); packets.Add(Packet(key, true));
        if (shift) packets.Add(Packet(Windows.System.VirtualKey.Shift, true));
        if (control) packets.Add(Packet(Windows.System.VirtualKey.Control, true));
        if (SendInput((uint)packets.Count, packets.ToArray(), Marshal.SizeOf<InputPacket>()) != packets.Count)
        {
            var releases = new[] { Packet(key, true), Packet(Windows.System.VirtualKey.Control, true), Packet(Windows.System.VirtualKey.Shift, true) };
            SendInput((uint)releases.Length, releases, Marshal.SizeOf<InputPacket>());
            throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error());
        }
    }
    private static nint EnsureForeground(Window? window = null)
    {
        var handle = WinRT.Interop.WindowNative.GetWindowHandle(window ?? App.MainWindow);
        var foreground = GetForegroundWindow();
        if (foreground != handle && GetAncestor(foreground, 3) != handle)
        {
            GetWindowThreadProcessId(foreground, out var processId);
            string owner; try { owner = System.Diagnostics.Process.GetProcessById((int)processId).ProcessName; } catch (ArgumentException) { owner = "unknown"; }
            throw new InvalidOperationException($"验收窗口失去焦点,已停止输入(目标 {handle},前台 {foreground},进程 {owner})");
        }
        return handle;
    }
    [DllImport("user32.dll")] private static extern nint GetAncestor(nint window, uint flags);
    private static (int X, int Y, double Scale) ElementCenter(FrameworkElement element)
    {
        var handle = EnsureForeground(); var root = (FrameworkElement)App.MainWindow.Content;
        if (element.ActualWidth <= 0 || element.ActualHeight <= 0 || element.Visibility != Visibility.Visible) throw new InvalidOperationException($"测试控件未显示:{element.Name}, {element.ActualWidth}x{element.ActualHeight}, {element.Visibility}");
        var point = element.TransformToVisual(root).TransformPoint(new(element.ActualWidth / 2, element.ActualHeight / 2));
        var origin = new ScreenPoint(); ClientToScreen(handle, ref origin); var scale = root.XamlRoot.RasterizationScale;
        var x = origin.X + (int)Math.Round(point.X * scale); var y = origin.Y + (int)Math.Round(point.Y * scale);
        var desktop = Plugins.Vision.ScreenCapture.DesktopBounds;
        if (x < desktop.X || y < desktop.Y || x >= desktop.X + desktop.Width || y >= desktop.Y + desktop.Height)
            throw new InvalidOperationException($"测试控件位于屏幕之外:{element.Name}, {x},{y}");
        return (x, y, scale);
    }
    internal static async Task ClickElementAsync(FrameworkElement element)
    {
        var (x, y, _) = ElementCenter(element);
        try { MouseButtonAt(x, y, true); await Task.Delay(50); EnsureForeground(); }
        finally { ReleaseMouseAt(x, y); }
        await Task.Delay(130);
    }
    internal static async Task ClickPointAsync(FrameworkElement element, Windows.Foundation.Point point)
    {
        var (centerX, centerY, scale) = ElementCenter(element);
        var x = centerX + (int)Math.Round((point.X - element.ActualWidth / 2) * scale);
        var y = centerY + (int)Math.Round((point.Y - element.ActualHeight / 2) * scale);
        try { MouseButtonAt(x, y, true); await Task.Delay(50); EnsureForeground(); }
        finally { ReleaseMouseAt(x, y); }
        await Task.Delay(140);
    }
    private static void ReleaseMouseAt(int x, int y)
    {
        try { EnsureForeground(); MouseButtonAt(x, y, false); }
        catch (InvalidOperationException) { FlaUI.Core.Input.Mouse.Up(FlaUI.Core.Input.MouseButton.Left); }
    }
    internal static async Task DragElementAsync(FrameworkElement element, double dx, double dy)
    {
        var (x, y, scale) = ElementCenter(element);
        try
        {
            MouseButtonAt(x, y, true); await Task.Delay(70);
            for (var i = 1; i <= 8; i++) { EnsureForeground(); MouseMoveAt(x + (int)Math.Round(dx * scale * i / 8), y + (int)Math.Round(dy * scale * i / 8)); await Task.Delay(25); }
        }
        finally { ReleaseMouseAt(x + (int)Math.Round(dx * scale), y + (int)Math.Round(dy * scale)); }
        await Task.Delay(160);
    }
    internal static async Task DragFromToAsync(FrameworkElement from, FrameworkElement to, Func<Task>? held = null)
    {
        var start = ElementCenter(from); var end = ElementCenter(to);
        // Mode/page changes and ChangeView finish on later UI frames. Starting
        // SendInput with a stale ring coordinate can hit the adjacent port.
        var stable = 0;
        for (var i = 0; i < 50 && stable < 3; i++)
        {
            await Task.Delay(40);
            var nextStart = ElementCenter(from); var nextEnd = ElementCenter(to);
            stable = Math.Abs(start.X - nextStart.X) <= 1 && Math.Abs(start.Y - nextStart.Y) <= 1
                && Math.Abs(end.X - nextEnd.X) <= 1 && Math.Abs(end.Y - nextEnd.Y) <= 1 ? stable + 1 : 0;
            start = nextStart; end = nextEnd;
        }
        if (stable < 3) throw new InvalidOperationException("拖动前端口位置没有稳定,已停止输入");
        try
        {
            MouseMoveAt(start.X, start.Y); await Task.Delay(100);
            MouseButtonAt(start.X, start.Y, true); await Task.Delay(70);
            for (var i = 1; i <= 8; i++) { EnsureForeground(); MouseMoveAt(start.X + (end.X - start.X) * i / 8, start.Y + (end.Y - start.Y) * i / 8); await Task.Delay(30); }
            if (held is not null) await held();
        }
        finally { ReleaseMouseAt(end.X, end.Y); }
        await Task.Delay(180);
    }
}