using System.Net; using System.Net.Sockets; using System.Text; using System.Text.Json; using System.Text.Json.Nodes; using Microsoft.UI.Xaml.Automation; using XFEWorkflow.Abstractions; using XFEWorkflow.Controls; using XFEWorkflow.Infrastructure.Storage; using XFEWorkflow.Views; namespace XFEWorkflow.Services; internal static partial class UiSmokeTest { private static async Task SmokeAgentBrowserAsync(string output) { output = Path.Combine(output, "agent-browser"); Directory.CreateDirectory(output); Task Phase(string value) => File.WriteAllTextAsync(Path.Combine(output, "phase.txt"), value); var services = AppServices.Current; var shell = AppShellPage.Current!; var frame = (Frame)shell.FindName("navigationFrame"); var root = (FrameworkElement)App.MainWindow.Content; var oldTheme = root.RequestedTheme; var oldSize = App.MainWindow.AppWindow.Size; const string pluginId = "xfe.agent-browser"; var oldSettings = services.State.PluginSettings(pluginId); var uploadFile = Path.Combine(output, "upload-fixture.txt"); await File.WriteAllTextAsync(uploadFile, "真实上传文件:中文 😀"); var portSource = new TcpListener(IPAddress.Loopback, 0); portSource.Start(); var port = ((IPEndPoint)portSource.LocalEndpoint).Port; portSource.Stop(); var url = $"http://127.0.0.1:{port}/"; using var listener = new HttpListener(); listener.Prefixes.Add(url); listener.Start(); var requests = new List(); var serverErrors = new List(); var server = Task.Run(async () => { try { while (listener.IsListening) { var request = await listener.GetContextAsync(); try { string response; var type = "text/html; charset=utf-8"; if (request.Request.Url!.AbsolutePath == "/chat/completions") { using var reader = new StreamReader(request.Request.InputStream); var input = JsonNode.Parse(await reader.ReadToEndAsync())!.AsObject(); lock (requests) requests.Add(input); var messages = input["messages"]!.AsArray(); var cancelling = messages.OfType().Any(x => x.String("role") == "user" && x["content"] is JsonValue && x.String("content") == "测试停止"); var tools = messages.OfType().Count(x => x.String("role") == "tool"); var delta = new JsonObject(); var finish = "stop"; if (!cancelling && tools >= 3) delta["content"] = "## 操作已完成\n\n**测试联系人 😀** 已填写并点击。\n\n| 验证 | 结果 |\n|---|---|\n| 页面 | 已更新 |\n| iframe | 已读取 |\n\n- [x] 观察页面\n- [x] 操作并截图\n\n> 仅使用本地测试网页。\n\n" + new string('`', 3) + "csharp\nConsole.WriteLine(\"中文 😀\");\n" + new string('`', 3) + "\n"; else { var name = cancelling || tools == 1 ? "browser_execute" : tools == 0 ? "read_skill" : "browser_screenshot"; JsonObject args = cancelling ? new() { ["code"] = "await new Promise(resolve => setTimeout(resolve, 60000)); return 'never';" } : tools == 0 ? new() { ["path"] = "references/browser-actions.md" } : tools == 1 ? new() { ["code"] = "await page.locator('#name').fill('测试联系人 😀'); await page.locator('#apply').click(); await page.locator('#upload').setInputFiles(" + JsonSerializer.Serialize(uploadFile) + "); const pendingDownload = page.waitForEvent('download'); await page.locator('#download').click(); const download = await pendingDownload; await download.saveAs(outputDir + '/test-download.txt'); return { result: await page.locator('#result').innerText(), iframe: await page.frames()[1].locator('body').innerText(), uploaded: await page.locator('#upload').evaluate(e => e.files[0].name), download: download.suggestedFilename(), url: page.url() };" } : new() { ["fullPage"] = false }; delta["tool_calls"] = new JsonArray(new JsonObject { ["index"] = 0, ["id"] = "ui-tool-" + tools, ["type"] = "function", ["function"] = new JsonObject { ["name"] = name, ["arguments"] = args.ToJsonString() } }); finish = "tool_calls"; } type = "text/event-stream"; string Chunk(JsonObject value, string? reason) => "data: " + new JsonObject { ["choices"] = new JsonArray(new JsonObject { ["index"] = 0, ["delta"] = value, ["finish_reason"] = reason }) }.ToJsonString() + "\n\n"; response = Chunk(delta, null) + Chunk(new(), finish) + "data: [DONE]\n\n"; } else if (request.Request.Url.AbsolutePath == "/download") { type = "application/octet-stream"; request.Response.Headers["Content-Disposition"] = "attachment; filename=agent-download.txt"; response = "真实下载文件:中文 😀"; } else if (request.Request.Url.AbsolutePath == "/frame") response = "iframe 真实内容 😀"; else response = """ Agent 本地验收

WebView2 · Agent 验收

本地网页,验证填写、点击、iframe 与截图。

尚未填写

下载测试文件

"""; var bytes = Encoding.UTF8.GetBytes(response); request.Response.ContentType = type; request.Response.ContentLength64 = bytes.Length; await request.Response.OutputStream.WriteAsync(bytes); request.Response.Close(); } catch (Exception ex) { lock (serverErrors) serverErrors.Add(ex.ToString()); try { request.Response.Abort(); } catch { } } } } catch (HttpListenerException) { } catch (ObjectDisposedException) { } }); T Control(string id) where T : FrameworkElement => Descendants(frame).Single(x => AutomationProperties.GetAutomationId(x) == id); async Task Until(Func> condition, int seconds = 30) { var limit = DateTime.UtcNow.AddSeconds(seconds); while (DateTime.UtcNow < limit) { if (await condition()) return; await Task.Delay(100); } throw new TimeoutException("Agent 浏览器未达到期望状态:" + string.Join(" / ", Descendants(frame).Where(x => x.IsOpen).Select(x => x.Message))); } async Task Viewport(WebView2 web, string file) { var value = JsonNode.Parse(await web.CoreWebView2.CallDevToolsProtocolMethodAsync("Page.captureScreenshot", "{\"format\":\"png\",\"fromSurface\":true,\"captureBeyondViewport\":false}"))!; await File.WriteAllBytesAsync(file, Convert.FromBase64String(value["data"]!.GetValue())); } async Task Composite(string theme, WebView2 web, WebView2 chat) { // RTB omits WebView2's native surfaces. Combine only this app's own native and CDP renders. var native = Path.Combine(output, "page-" + theme + ".png"); await CaptureWindowAsync(native); var browserFile = Path.Combine(output, "browser-" + theme + ".png"); var chatFile = Path.Combine(output, "chat-" + theme + ".png"); await Viewport(web, browserFile); await Viewport(chat, chatFile); using var bitmap = new System.Drawing.Bitmap(native); using var graphics = System.Drawing.Graphics.FromImage(bitmap); var scale = bitmap.Width / root.ActualWidth; foreach (var (view, file) in new[] { (web, browserFile), (chat, chatFile) }) { var position = view.TransformToVisual(root).TransformPoint(new()); using var pixels = System.Drawing.Image.FromFile(file); graphics.DrawImage(pixels, new System.Drawing.RectangleF((float)(position.X * scale), (float)(position.Y * scale), (float)(view.ActualWidth * scale), (float)(view.ActualHeight * scale))); } bitmap.Save(Path.Combine(output, "page-" + theme + "-composited.png"), System.Drawing.Imaging.ImageFormat.Png); } try { var plugin = services.Plugins.Installed.Single(x => x.Manifest.Id == pluginId && x.Enabled); services.State.SetPluginSettings(pluginId, new() { ["endpoint"] = url, ["model"] = "deepseek-v4-flash", ["credential"] = "", ["maximumSteps"] = 12 }); await services.State.SaveAsync(); var scale = root.XamlRoot.RasterizationScale; App.MainWindow.AppWindow.Resize(new((int)(1500 * scale), (int)(950 * scale))); root.RequestedTheme = ElementTheme.Dark; shell.ShowBrowser(false); var pageRef = new PluginPageReference(pluginId, plugin.Manifest.Version, pluginId + ".page"); await Phase("navigate"); shell.ViewModel.NavigationViewService.NavigateTo(pageRef); await Until(() => Task.FromResult(Descendants(frame).Count(x => x.CoreWebView2 is not null) >= 2)); var web = Control("AgentBrowserWeb"); var chat = Control("AgentChatWeb"); await Until(async () => await chat.ExecuteScriptAsync("Boolean(window.agentChatReady)") == "true"); await Phase("webviews-ready"); web.Source = new Uri(url); await Until(async () => JsonNode.Parse(await web.ExecuteScriptAsync("document.title"))?.GetValue() == "Agent 本地验收"); if (web.ActualWidth < 400 || chat.ActualHeight < 300) throw new InvalidOperationException("浏览器或聊天视图没有填满布局"); var input = Control("AgentComposer"); var send = Control