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;
using System.Text.Json.Nodes;
using Microsoft.UI.Xaml.Automation;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Infrastructure.Storage;
using XFEWorkflow.Views;

namespace XFEWorkflow.Services;

internal static partial class UiSmokeTest
{
    // Run twice with the same isolated workspace/output to verify an actual application restart.
    private static async Task SmokeAgentSessionsAsync(string output)
    {
        output = Path.Combine(output, "agent-sessions"); Directory.CreateDirectory(output);
        var markerPath = Path.Combine(output, "restart.json");
        var marker = File.Exists(markerPath) ? JsonNode.Parse(await File.ReadAllTextAsync(markerPath))!.AsObject() : null;
        var restoring = marker is not null;
        var services = AppServices.Current; var shell = AppShellPage.Current!; var frame = (Frame)shell.FindName("navigationFrame");
        var root = (FrameworkElement)App.MainWindow.Content; var oldSize = App.MainWindow.AppWindow.Size; var oldTheme = root.RequestedTheme;
        const string pluginId = "xfe.agent-browser", firstPrompt = "会话 A 初始消息 😀", secondPrompt = "会话 B 独立消息", draft = "重启后继续的草稿 😀";
        var port = marker?.Integer("port") ?? 0;
        if (port == 0) { var portSource = new TcpListener(IPAddress.Loopback, 0); portSource.Start(); 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 errors = new List<string>(); var continued = false; var firstBrowserTab = "";
        var server = Task.Run(async () =>
        {
            try
            {
                while (listener.IsListening)
                {
                    var request = await listener.GetContextAsync();
                    try
                    {
                        string response;
                        if (request.Request.Url!.AbsolutePath == "/chat/completions")
                        {
                            using var reader = new StreamReader(request.Request.InputStream);
                            var body = JsonNode.Parse(await reader.ReadToEndAsync())!.AsObject();
                            var messages = body["messages"]!.AsArray().OfType<JsonObject>().ToArray();
                            var prompt = messages.Last(x => x.String("role") == "user" && x["content"] is JsonValue && !x.String("content").StartsWith("以下为宿主刚读取", StringComparison.Ordinal)).String("content");
                            var text = prompt == firstPrompt ? "已记住会话 A 的第一条消息 😀" : prompt == secondPrompt ? "这是独立的会话 B" : "已恢复会话 A 的上下文并继续完成";
                            if (prompt == "继续会话 A")
                            {
                                if (!messages.Any(x => x.String("content") == firstPrompt) || !messages.Any(x => x.String("content") == "已记住会话 A 的第一条消息 😀") || messages.Any(x => x.String("content") == secondPrompt))
                                    throw new InvalidOperationException("重启后模型请求缺少原上下文,或混入其他会话");
                                continued = true;
                            }
                            var reply = new JsonObject { ["role"] = "assistant", ["content"] = text }; var finish = "stop";
                            var outputs = messages.Where(x => x.String("role") == "tool").ToArray();
                            if (prompt == firstPrompt && outputs.Length < 5)
                            {
                                var stage = outputs.Length; var name = stage is 1 or 3 ? "browser_execute" : "browser_tabs";
                                JsonObject arguments = stage switch
                                {
                                    0 => new() { ["operation"] = "open", ["url"] = url + "ai-tab" },
                                    1 => new() { ["code"] = "await page.waitForURL(" + JsonSerializer.Serialize(url + "ai-tab") + "); return { url: page.url(), title: await page.title() };" },
                                    2 => new() { ["operation"] = "select", ["tabId"] = firstBrowserTab },
                                    3 => new() { ["code"] = "return { url: page.url(), draft: await page.locator('#page-draft').inputValue() };" },
                                    _ => new() { ["operation"] = "close", ["tabId"] = JsonNode.Parse(outputs[0].String("content"))!.AsObject().String("activeTabId") }
                                };
                                if (stage == 2 && !outputs[1].String("content").Contains("ai-tab")) throw new InvalidOperationException("AI 新标签操作没有切换到正确目标");
                                if (stage == 4 && !outputs[3].String("content").Contains("原标签未提交内容")) throw new InvalidOperationException("AI 重新选中原标签时页面状态丢失");
                                reply["content"] = ""; reply["tool_calls"] = new JsonArray(new JsonObject { ["id"] = "tabs-" + stage, ["type"] = "function", ["function"] = new JsonObject { ["name"] = name, ["arguments"] = arguments.ToJsonString() } }); finish = "tool_calls";
                            }
                            response = new JsonObject { ["choices"] = new JsonArray(new JsonObject { ["message"] = reply, ["finish_reason"] = finish }) }.ToJsonString();
                            request.Response.ContentType = "application/json";
                        }
                        else { response = "<!doctype html><html lang=zh-CN><meta charset=utf-8><title>会话历史验收</title><body style='font:22px Segoe UI;padding:40px'><h1>会话历史 · 本地验收</h1><p>只操作本应用的 WebView2,无外部账号。</p><input id=page-draft aria-label=页面草稿></body></html>"; request.Response.ContentType = "text/html; charset=utf-8"; }
                        await request.Response.OutputStream.WriteAsync(Encoding.UTF8.GetBytes(response)); request.Response.Close();
                    }
                    catch (Exception ex) { errors.Add(ex.Message); request.Response.StatusCode = 500; request.Response.Close(); }
                }
            }
            catch (HttpListenerException) { } catch (ObjectDisposedException) { }
        });
        T Control<T>(string id) where T : FrameworkElement => Descendants<T>(frame).Single(x => AutomationProperties.GetAutomationId(x) == id);
        async Task Until(Func<Task<bool>> condition)
        {
            var limit = DateTime.UtcNow.AddSeconds(20);
            while (DateTime.UtcNow < limit) { if (await condition()) return; await Task.Delay(80); }
            throw new TimeoutException("会话验收超时:" + string.Join(" / ", Descendants<InfoBar>(frame).Where(x => x.IsOpen).Select(x => x.Message)));
        }
        async Task Send(string prompt)
        {
            Control<TextBox>("AgentComposer").Text = prompt; await InvokeButtonAsync(Control<Button>("AgentSend"));
            await Until(() => Task.FromResult(Control<Button>("AgentSend").IsEnabled));
            if (Descendants<InfoBar>(frame).Any(x => x.IsOpen)) throw new InvalidOperationException(string.Join(" / ", Descendants<InfoBar>(frame).Where(x => x.IsOpen).Select(x => x.Message)));
        }
        async Task SelectSession(string title, string id, WebView2 chat)
        {
            var picker = Control<ComboBox>("AgentSessionPicker"); picker.SelectedItem = picker.Items.Single(x => x.ToString() == title);
            await Until(async () => await chat.ExecuteScriptAsync("document.documentElement.dataset.sessionId") == JsonSerializer.Serialize(id) && Control<Button>("AgentSend").IsEnabled);
        }
        async Task SelectTab(string id)
        {
            var tabs = Control<TabView>("AgentBrowserTabs"); tabs.SelectedItem = tabs.TabItems.OfType<TabViewItem>().Single(x => x.Tag as string == id);
            await Until(() => Task.FromResult(Control<WebView2>("AgentBrowserWeb").CoreWebView2 is not null));
        }
        async Task AddTab(string targetUrl)
        {
            var tabs = Control<TabView>("AgentBrowserTabs"); var count = tabs.TabItems.Count;
            await InvokeButtonAsync(Descendants<Button>(tabs).Single(x => x.Name == "AddButton"));
            await Until(() => Task.FromResult(tabs.TabItems.Count == count + 1 && Control<WebView2>("AgentBrowserWeb").CoreWebView2 is not null));
            var view = Control<WebView2>("AgentBrowserWeb"); view.Source = new Uri(targetUrl);
            await Until(() => Task.FromResult(view.CoreWebView2.Source == targetUrl));
        }
        async Task Screenshot(string name, WebView2 chat)
        {
            await chat.ExecuteScriptAsync("scrollTo(0,0)"); await Task.Delay(100);
            var result = JsonNode.Parse(await chat.CoreWebView2.CallDevToolsProtocolMethodAsync("Page.captureScreenshot", "{\"format\":\"png\",\"captureBeyondViewport\":false,\"fromSurface\":true}"))!;
            await File.WriteAllBytesAsync(Path.Combine(output, name + "-chat.png"), Convert.FromBase64String(result["data"]!.GetValue<string>()));
            await CaptureWindowAsync(Path.Combine(output, name + "-native.png"));
            var browserView = Control<WebView2>("AgentBrowserWeb");
            var browserPixels = JsonNode.Parse(await browserView.CoreWebView2.CallDevToolsProtocolMethodAsync("Page.captureScreenshot", "{\"format\":\"png\",\"captureBeyondViewport\":false,\"fromSurface\":true}"))!;
            await File.WriteAllBytesAsync(Path.Combine(output, name + "-browser.png"), Convert.FromBase64String(browserPixels["data"]!.GetValue<string>()));
            using var bitmap = new System.Drawing.Bitmap(Path.Combine(output, name + "-native.png"));
            using var graphics = System.Drawing.Graphics.FromImage(bitmap); var pixelScale = bitmap.Width / root.ActualWidth;
            foreach (var (view, suffix) in new[] { (browserView, "browser"), (chat, "chat") })
            {
                var position = view.TransformToVisual(root).TransformPoint(new());
                using var pixels = System.Drawing.Image.FromFile(Path.Combine(output, name + "-" + suffix + ".png"));
                graphics.DrawImage(pixels, new System.Drawing.RectangleF((float)(position.X * pixelScale), (float)(position.Y * pixelScale), (float)(view.ActualWidth * pixelScale), (float)(view.ActualHeight * pixelScale)));
            }
            bitmap.Save(Path.Combine(output, name + "-composited.png"), System.Drawing.Imaging.ImageFormat.Png);
        }
        try
        {
            var scale = root.XamlRoot.RasterizationScale; App.MainWindow.AppWindow.Resize(new((int)(1500 * scale), (int)(950 * scale))); root.RequestedTheme = ElementTheme.Dark;
            if (!restoring)
            {
                services.State.SetPluginSettings(pluginId, new() { ["endpoint"] = url, ["model"] = "deepseek-v4-flash", ["credential"] = "", ["skillDirectory"] = "Z:/not-installed/skill", ["nodeExecutable"] = "Z:/not-installed/node.exe" }); await services.State.SaveAsync();
            }
            else if (marker!.Integer("processId") == Environment.ProcessId) throw new InvalidOperationException("必须重新启动进程验证会话持久化");
            var plugin = services.Plugins.Installed.Single(x => x.Manifest.Id == pluginId && x.Enabled);
            shell.ShowBrowser(false); shell.ViewModel.NavigationViewService.NavigateTo<PluginPageHostPage>(new PluginPageReference(pluginId, plugin.Manifest.Version, pluginId + ".page"));
            await Until(() => Task.FromResult(Descendants<WebView2>(frame).Count(x => x.CoreWebView2 is not null) == 2));
            var chat = Control<WebView2>("AgentChatWeb"); var web = Control<WebView2>("AgentBrowserWeb");
            await Until(async () => await chat.ExecuteScriptAsync("Boolean(window.agentChatReady && document.documentElement.dataset.sessionId)") == "true" && Control<Button>("AgentSend").IsEnabled);
            if (!restoring)
            {
                web.Source = new Uri(url); await Until(async () => JsonNode.Parse(await web.ExecuteScriptAsync("document.title"))?.GetValue<string>() == "会话历史验收");
                await web.ExecuteScriptAsync("document.querySelector('#page-draft').value='原标签未提交内容';document.cookie='conversation=A;max-age=31536000;path=/'");
                firstBrowserTab = (string)((TabViewItem)Control<TabView>("AgentBrowserTabs").SelectedItem).Tag;
                var firstId = JsonNode.Parse(await chat.ExecuteScriptAsync("document.documentElement.dataset.sessionId"))!.GetValue<string>();
                await Send(firstPrompt);
                if (Control<TabView>("AgentBrowserTabs").TabItems.Count != 1 || await chat.ExecuteScriptAsync("Boolean(document.querySelector('details.failed'))") != "false") throw new InvalidOperationException("AI 多标签操作有失败或未关闭新建标签");
                if (JsonSerializer.SerializeToNode(Control<ComboBox>("AgentSessionPicker").SelectedItem, WorkflowJson.Options)!.AsObject().Integer("messages") != 2) throw new InvalidOperationException("完成回复后会话消息数未更新");
                await AddTab(url + "second");
                var secondBrowserTab = (string)((TabViewItem)Control<TabView>("AgentBrowserTabs").SelectedItem).Tag;
                var popupExpression = "window.open(" + JsonSerializer.Serialize(url + "popup") + ")";
                await Control<WebView2>("AgentBrowserWeb").CoreWebView2.CallDevToolsProtocolMethodAsync("Runtime.evaluate", new JsonObject { ["expression"] = popupExpression, ["userGesture"] = true }.ToJsonString());
                await Until(() => Task.FromResult(Control<TabView>("AgentBrowserTabs").TabItems.Count == 3 && Control<WebView2>("AgentBrowserWeb").CoreWebView2?.Source == url + "popup"));
                await InvokeButtonAsync(Descendants<Button>((TabViewItem)Control<TabView>("AgentBrowserTabs").SelectedItem).Single(x => x.Name == "CloseButton"));
                await Until(() => Task.FromResult(Control<TabView>("AgentBrowserTabs").TabItems.Count == 2));
                await SelectTab(firstBrowserTab);
                if (Control<WebView2>("AgentBrowserWeb") != web || await web.ExecuteScriptAsync("document.querySelector('#page-draft').value==='原标签未提交内容'") != "true") throw new InvalidOperationException("标签切换重建了原页面");
                await SelectTab(secondBrowserTab);
                Control<TextBox>("AgentComposer").Text = "会话 A 切换草稿";
                await InvokeButtonAsync(Control<Button>("AgentNewConversation"));
                await Until(async () => await chat.ExecuteScriptAsync("document.documentElement.dataset.sessionId") != JsonSerializer.Serialize(firstId) && Control<Button>("AgentSend").IsEnabled);
                if (Control<TabView>("AgentBrowserTabs").TabItems.Count != 1 || Control<WebView2>("AgentBrowserWeb") == web) throw new InvalidOperationException("新会话没有独立浏览器");
                var secondBrowser = Control<WebView2>("AgentBrowserWeb"); secondBrowser.Source = new Uri(url + "session-b");
                await Until(async () => JsonNode.Parse(await secondBrowser.ExecuteScriptAsync("document.title"))?.GetValue<string>() == "会话历史验收");
                if (await secondBrowser.ExecuteScriptAsync("document.cookie.includes('conversation=A')") != "false") throw new InvalidOperationException("不同会话共享了登录 Cookie");
                await secondBrowser.ExecuteScriptAsync("document.cookie='conversation=B;max-age=31536000;path=/'");
                await Send(secondPrompt);
                var secondId = JsonNode.Parse(await chat.ExecuteScriptAsync("document.documentElement.dataset.sessionId"))!.GetValue<string>();
                if (await chat.ExecuteScriptAsync("document.body.innerText.includes('会话 A 初始消息')") != "false") throw new InvalidOperationException("新会话混入旧记录");
                await SelectSession(firstPrompt, firstId, chat);
                if (Control<TabView>("AgentBrowserTabs").TabItems.Count != 2 || ((TabViewItem)Control<TabView>("AgentBrowserTabs").SelectedItem).Tag as string != secondBrowserTab || await Control<WebView2>("AgentBrowserWeb").ExecuteScriptAsync("document.cookie.includes('conversation=A')") != "true") throw new InvalidOperationException("切换会话未还原对应标签或 Cookie");
                if (Control<TextBox>("AgentComposer").Text != "会话 A 切换草稿" || await chat.ExecuteScriptAsync("document.body.innerText.includes('已记住会话 A')") != "true") throw new InvalidOperationException("切换会话未恢复草稿或消息");
                Control<TextBox>("AgentComposer").Text = draft;
                await SelectSession(secondPrompt, secondId, chat); await SelectSession(firstPrompt, firstId, chat);
                if (Control<TextBox>("AgentComposer").Text != draft) throw new InvalidOperationException("二次切换丢失草稿");
                await Screenshot("seed", chat);
                await AtomicJson.WriteAsync(markerPath, new { port, firstId, secondId, firstTitle = firstPrompt, secondTitle = secondPrompt, firstBrowserTab, secondBrowserTab, draft, processId = Environment.ProcessId });
                await AtomicJson.WriteAsync(Path.Combine(output, "seed-verified.json"), new { multipleSessions = true, draftRestored = true, contextIndependent = true, aiTabsOpenSelectClose = true, nativeAddAndClose = true, popup = true, livePagePreserved = true, cookieIsolation = true, bundledWithoutLocalSetup = true, processId = Environment.ProcessId, errors });
            }
            else
            {
                var firstId = marker!.String("firstId"); var secondId = marker!.String("secondId");
                if (Control<ComboBox>("AgentSessionPicker").Items.Count != 2 || await chat.ExecuteScriptAsync("document.documentElement.dataset.sessionId") != JsonSerializer.Serialize(firstId)) throw new InvalidOperationException("重启没有恢复会话列表或最后活动会话");
                if (Control<TextBox>("AgentComposer").Text != draft || await chat.ExecuteScriptAsync("document.body.innerText.includes('已记住会话 A')") != "true") throw new InvalidOperationException("重启后草稿或公开回复丢失");
                await Until(async () => JsonNode.Parse(await web.ExecuteScriptAsync("document.title"))?.GetValue<string>() == "会话历史验收");
                if (Control<TabView>("AgentBrowserTabs").TabItems.Count != 2 || ((TabViewItem)Control<TabView>("AgentBrowserTabs").SelectedItem).Tag as string != marker!.String("secondBrowserTab") || web.Source.AbsoluteUri != url + "second") throw new InvalidOperationException("重启未恢复多标签列表、顺序或选中标签");
                if (await web.ExecuteScriptAsync("document.cookie.includes('conversation=A')") != "true") throw new InvalidOperationException("会话 A 的登录 Cookie 没有持久保存");
                await SelectSession(secondPrompt, secondId, chat);
                if (Control<TabView>("AgentBrowserTabs").TabItems.Count != 1) throw new InvalidOperationException("重启后会话 B 混入其他会话标签");
                var restoredB = Control<WebView2>("AgentBrowserWeb"); await Until(async () => JsonNode.Parse(await restoredB.ExecuteScriptAsync("document.title"))?.GetValue<string>() == "会话历史验收");
                if (restoredB.Source.AbsoluteUri != url + "session-b" || await restoredB.ExecuteScriptAsync("document.cookie.includes('conversation=B') && !document.cookie.includes('conversation=A')") != "true") throw new InvalidOperationException("会话 B 的网址或独立登录状态未恢复");
                if (await chat.ExecuteScriptAsync("document.body.innerText.includes('这是独立的会话 B') && !document.body.innerText.includes('已记住会话 A')") != "true") throw new InvalidOperationException("重启后历史会话不能独立切换");
                await SelectSession(firstPrompt, firstId, chat); await Send("继续会话 A");
                if (!continued || await chat.ExecuteScriptAsync("document.body.innerText.includes('已恢复会话 A 的上下文并继续完成')") != "true") throw new InvalidOperationException("只有界面记录恢复,模型上下文未恢复");
                await Screenshot("restored", chat);
                await AtomicJson.WriteAsync(Path.Combine(output, "restart-verified.json"), new { realRestart = true, previousProcessId = marker!.Integer("processId"), processId = Environment.ProcessId, sessionListRestored = true, activeSessionRestored = true, draftRestored = true, browserUrlRestored = true, browserTabsRestored = true, cookieProfilesRestored = true, continuedWithPriorContext = true, defaultMaximumSteps = services.State.PluginSettings(pluginId).Integer("maximumSteps"), errors });
            }
        }
        finally
        {
            shell.ViewModel.NavigationViewService.NavigateTo<MainPage>(); root.RequestedTheme = oldTheme; App.MainWindow.AppWindow.Resize(oldSize); listener.Stop(); await server;
        }
    }
}