using System.Net;
using System.Net.Sockets;
using System.Text.Json.Nodes;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.Web.WebView2.Core;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Desktop.Sdk;
namespace XFEWorkflow.Plugins.AgentBrowser.WinUI;
/// <summary>A conversation owns its WebView2 environment, profile, CDP endpoint and live tabs.</summary>
internal sealed class AgentBrowserWorkspace : IDisposable
{
private sealed class Tab(AgentBrowserTab state)
{
public AgentBrowserTab State = state;
public readonly WebView2 Web = new();
public readonly TabViewItem Item = new() { Header = state.Title, Tag = state.Id, IconSource = new FontIconSource { Glyph = "\uE774" }, IsClosable = true };
public string TargetId = "";
}
private readonly IPluginPageContext host;
private readonly AgentSession document;
private readonly Action changed, cancel;
private readonly Action<string> error;
private readonly CancellationToken lifetime;
private readonly List<Tab> tabs = [];
private readonly SemaphoreSlim gate = new(1);
private CoreWebView2Environment? environment;
private CancellationTokenSource? selection;
private bool selecting, disposed;
public TabView Tabs { get; } = new() { Height = 44, TabWidthMode = TabViewWidthMode.SizeToContent, HorizontalContentAlignment = HorizontalAlignment.Stretch, VerticalContentAlignment = VerticalAlignment.Stretch };
public Grid View { get; } = new();
private readonly Grid surface = new();
public string Endpoint { get; private set; } = "";
private Tab Active => tabs.Single(x => x.State.Id == document.ActiveBrowserTabId);
public WebView2 ActiveView => Active.Web;
public string TargetId => Active.TargetId;
public AgentBrowserWorkspace(AgentSession document, IPluginPageContext host, Action changed, Action cancel, Action<string> error, CancellationToken lifetime)
{
this.document = document; this.host = host; this.changed = () => { if (!disposed) changed(); }; this.cancel = cancel; this.error = error; this.lifetime = lifetime;
View.RowDefinitions.Add(new() { Height = GridLength.Auto }); View.RowDefinitions.Add(new() { Height = new(1, GridUnitType.Star) });
View.Children.Add(Tabs); View.Children.Add(surface); Grid.SetRow(surface, 1);
document.EnsureBrowserTabs();
selecting = true;
foreach (var state in document.BrowserTabs) AddItem(state);
Tabs.SelectedItem = Active.Item; selecting = false; ShowActiveSurface();
Microsoft.UI.Xaml.Automation.AutomationProperties.SetAutomationId(Tabs, "AgentBrowserTabs");
Tabs.AddTabButtonClick += async (_, _) => await GuardAsync(() => OpenAsync("about:blank"));
Tabs.TabCloseRequested += async (_, args) => { cancel(); await GuardAsync(() => CloseAsync((string)args.Tab.Tag)); };
Tabs.SelectionChanged += async (_, _) =>
{
if (selecting || disposed || Tabs.SelectedItem is not TabViewItem item) return;
document.ActiveBrowserTabId = (string)item.Tag; ShowActiveSurface();
await GuardAsync(EnsureActiveAsync); Capture(); changed();
};
}
private void AddItem(AgentBrowserTab state)
{
var tab = new Tab(state); tabs.Add(tab); Tabs.TabItems.Add(tab.Item);
Microsoft.UI.Xaml.Automation.AutomationProperties.SetAutomationId(tab.Web, "AgentBrowserWeb");
ToolTipService.SetToolTip(tab.Item, state.Url);
}
private void ShowActiveSurface()
{
selection?.Cancel(); selection?.Dispose(); selection = CancellationTokenSource.CreateLinkedTokenSource(lifetime);
surface.Children.Clear(); surface.Children.Add(Active.Web);
}
public void Suspend() => selection?.Cancel();
public void Resume() => ShowActiveSurface();
public async Task EnsureActiveAsync()
{
var tab = Active; var selected = selection?.Token ?? lifetime;
await gate.WaitAsync(selected);
try
{
ObjectDisposedException.ThrowIf(disposed, this);
if (environment is null)
{
var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); Endpoint = $"http://127.0.0.1:{port}";
var profile = document.UseLegacyBrowserProfile ? Path.Combine(host.DataDirectory, "BrowserProfile") : Path.Combine(host.DataDirectory, "BrowserSessions", document.Id, "Profile");
environment = await CoreWebView2Environment.CreateWithOptionsAsync(null, profile, new CoreWebView2EnvironmentOptions
{ AdditionalBrowserArguments = $"--remote-debugging-address=127.0.0.1 --remote-debugging-port={port} --disable-features=CalculateNativeWinOcclusion --disable-background-timer-throttling --disable-renderer-backgrounding" });
}
selected.ThrowIfCancellationRequested();
if (tab.Web.CoreWebView2 is not null && tab.TargetId.Length > 0) return;
if (!tab.Web.IsLoaded)
{
var loaded = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
void Loaded(object sender, RoutedEventArgs args) => loaded.TrySetResult();
tab.Web.Loaded += Loaded;
try { if (!tab.Web.IsLoaded) await loaded.Task.WaitAsync(selected); }
finally { tab.Web.Loaded -= Loaded; }
}
host.InitializeWebView(tab.Web); await tab.Web.EnsureCoreWebView2Async(environment);
if (disposed) { tab.Web.Close(); return; }
var core = tab.Web.CoreWebView2 ?? throw new InvalidOperationException("浏览器标签初始化未完成");
core.SourceChanged += (_, _) => Update(tab);
core.DocumentTitleChanged += (_, _) => Update(tab);
core.NewWindowRequested += async (_, args) =>
{
args.Handled = true;
if (!AgentSession.AllowedUrl(args.Uri)) { error("仅允许打开 HTTP(S) 网页和空白标签页"); return; }
var deferral = args.GetDeferral();
try { await OpenAsync("about:blank"); args.NewWindow = Active.Web.CoreWebView2; }
catch (Exception ex) { error(ex.Message); }
finally { deferral.Complete(); }
};
core.NavigationStarting += (_, args) => { if (!AgentSession.AllowedUrl(args.Uri)) { args.Cancel = true; error("仅允许访问 HTTP(S) 网页和 about:blank"); } };
core.ProcessFailed += (_, _) => { cancel(); error("浏览器进程已退出,请重新启用插件"); };
core.DownloadStarting += (_, args) =>
{
var downloads = Path.Combine(host.DataDirectory, "Downloads"); Directory.CreateDirectory(downloads);
var name = Path.GetFileName(args.ResultFilePath); if (string.IsNullOrWhiteSpace(name)) name = "download.bin";
args.ResultFilePath = Path.Combine(downloads, Guid.NewGuid().ToString("N")[..8] + "-" + name); args.Handled = true;
};
var target = JsonNode.Parse(await core.CallDevToolsProtocolMethodAsync("Target.getTargetInfo", "{}"))!;
tab.TargetId = target["targetInfo"]!["targetId"]!.GetValue<string>();
tab.Web.Source = new Uri(tab.State.Url);
changed();
}
finally { gate.Release(); }
}
private void Update(Tab tab)
{
if (disposed || tab.Web.CoreWebView2 is not { } core) return;
var url = core.Source;
if (!AgentSession.AllowedUrl(url)) return;
var title = string.IsNullOrWhiteSpace(core.DocumentTitle) ? url == "about:blank" ? "新标签页" : new Uri(url).Host : core.DocumentTitle;
tab.State = tab.State with { Url = url, Title = title };
tab.Item.Header = title.Length > 36 ? title[..36] + "…" : title;
ToolTipService.SetToolTip(tab.Item, title + "\n" + url); Capture(); changed();
}
public void Capture()
{
document.BrowserTabs = tabs.Select(x => x.State).ToList();
if (tabs.Count > 0) document.BrowserUrl = Active.State.Url;
}
public async Task OpenAsync(string url)
{
if (!AgentSession.AllowedUrl(url)) throw new ArgumentException("新标签页只支持 HTTP(S) 地址");
var state = new AgentBrowserTab(Guid.NewGuid().ToString("N"), url);
selecting = true;
try { AddItem(state); document.ActiveBrowserTabId = state.Id; Tabs.SelectedItem = Active.Item; ShowActiveSurface(); Capture(); }
finally { selecting = false; }
await EnsureActiveAsync(); changed();
}
public async Task CloseAsync(string id)
{
var tab = tabs.SingleOrDefault(x => x.State.Id == id) ?? throw new ArgumentException("标签页不存在");
selecting = true;
try
{
var index = tabs.IndexOf(tab); tabs.Remove(tab); Tabs.TabItems.Remove(tab.Item); tab.Web.Close();
if (tabs.Count == 0) AddItem(new(Guid.NewGuid().ToString("N")));
if (document.ActiveBrowserTabId == id) document.ActiveBrowserTabId = tabs[Math.Min(index, tabs.Count - 1)].State.Id;
Tabs.SelectedItem = Active.Item; ShowActiveSurface(); Capture();
}
finally { selecting = false; }
await EnsureActiveAsync(); changed();
}
public async Task<JsonObject> InvokeAsync(JsonObject args)
{
var operation = args.String("operation", "list");
switch (operation)
{
case "list": await EnsureActiveAsync(); break;
case "open": await OpenAsync(args.String("url", "about:blank")); break;
case "select":
var tab = tabs.SingleOrDefault(x => x.State.Id == args.String("tabId")) ?? throw new ArgumentException("标签页不存在");
selecting = true; document.ActiveBrowserTabId = tab.State.Id; Tabs.SelectedItem = tab.Item; selecting = false; ShowActiveSurface();
await EnsureActiveAsync(); Capture(); changed(); break;
case "close": await CloseAsync(args.String("tabId")); break;
default: throw new ArgumentException("未知标签操作");
}
return new()
{
["activeTabId"] = document.ActiveBrowserTabId, ["targetId"] = TargetId,
["tabs"] = new JsonArray(tabs.Select(x => (JsonNode?)new JsonObject { ["id"] = x.State.Id, ["title"] = x.State.Title, ["url"] = x.State.Url, ["selected"] = x.State.Id == document.ActiveBrowserTabId }).ToArray())
};
}
private async Task GuardAsync(Func<Task> operation) { try { await operation(); } catch (OperationCanceledException) { } catch (Exception ex) { if (!disposed) error(ex.Message); } }
public void Dispose()
{
if (disposed) return; disposed = true;
selection?.Cancel(); selection?.Dispose();
foreach (var tab in tabs) tab.Web.Close();
Tabs.TabItems.Clear();
}
}
using System.Net;
using System.Net.Sockets;
using System.Text.Json.Nodes;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.Web.WebView2.Core;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Desktop.Sdk;
namespace XFEWorkflow.Plugins.AgentBrowser.WinUI;
/// <summary>A conversation owns its WebView2 environment, profile, CDP endpoint and live tabs.</summary>
internal sealed class AgentBrowserWorkspace : IDisposable
{
private sealed class Tab(AgentBrowserTab state)
{
public AgentBrowserTab State = state;
public readonly WebView2 Web = new();
public readonly TabViewItem Item = new() { Header = state.Title, Tag = state.Id, IconSource = new FontIconSource { Glyph = "\uE774" }, IsClosable = true };
public string TargetId = "";
}
private readonly IPluginPageContext host;
private readonly AgentSession document;
private readonly Action changed, cancel;
private readonly Action<string> error;
private readonly CancellationToken lifetime;
private readonly List<Tab> tabs = [];
private readonly SemaphoreSlim gate = new(1);
private CoreWebView2Environment? environment;
private CancellationTokenSource? selection;
private bool selecting, disposed;
public TabView Tabs { get; } = new() { Height = 44, TabWidthMode = TabViewWidthMode.SizeToContent, HorizontalContentAlignment = HorizontalAlignment.Stretch, VerticalContentAlignment = VerticalAlignment.Stretch };
public Grid View { get; } = new();
private readonly Grid surface = new();
public string Endpoint { get; private set; } = "";
private Tab Active => tabs.Single(x => x.State.Id == document.ActiveBrowserTabId);
public WebView2 ActiveView => Active.Web;
public string TargetId => Active.TargetId;
public AgentBrowserWorkspace(AgentSession document, IPluginPageContext host, Action changed, Action cancel, Action<string> error, CancellationToken lifetime)
{
this.document = document; this.host = host; this.changed = () => { if (!disposed) changed(); }; this.cancel = cancel; this.error = error; this.lifetime = lifetime;
View.RowDefinitions.Add(new() { Height = GridLength.Auto }); View.RowDefinitions.Add(new() { Height = new(1, GridUnitType.Star) });
View.Children.Add(Tabs); View.Children.Add(surface); Grid.SetRow(surface, 1);
document.EnsureBrowserTabs();
selecting = true;
foreach (var state in document.BrowserTabs) AddItem(state);
Tabs.SelectedItem = Active.Item; selecting = false; ShowActiveSurface();
Microsoft.UI.Xaml.Automation.AutomationProperties.SetAutomationId(Tabs, "AgentBrowserTabs");
Tabs.AddTabButtonClick += async (_, _) => await GuardAsync(() => OpenAsync("about:blank"));
Tabs.TabCloseRequested += async (_, args) => { cancel(); await GuardAsync(() => CloseAsync((string)args.Tab.Tag)); };
Tabs.SelectionChanged += async (_, _) =>
{
if (selecting || disposed || Tabs.SelectedItem is not TabViewItem item) return;
document.ActiveBrowserTabId = (string)item.Tag; ShowActiveSurface();
await GuardAsync(EnsureActiveAsync); Capture(); changed();
};
}
private void AddItem(AgentBrowserTab state)
{
var tab = new Tab(state); tabs.Add(tab); Tabs.TabItems.Add(tab.Item);
Microsoft.UI.Xaml.Automation.AutomationProperties.SetAutomationId(tab.Web, "AgentBrowserWeb");
ToolTipService.SetToolTip(tab.Item, state.Url);
}
private void ShowActiveSurface()
{
selection?.Cancel(); selection?.Dispose(); selection = CancellationTokenSource.CreateLinkedTokenSource(lifetime);
surface.Children.Clear(); surface.Children.Add(Active.Web);
}
public void Suspend() => selection?.Cancel();
public void Resume() => ShowActiveSurface();
public async Task EnsureActiveAsync()
{
var tab = Active; var selected = selection?.Token ?? lifetime;
await gate.WaitAsync(selected);
try
{
ObjectDisposedException.ThrowIf(disposed, this);
if (environment is null)
{
var listener = new TcpListener(IPAddress.Loopback, 0); listener.Start();
var port = ((IPEndPoint)listener.LocalEndpoint).Port; listener.Stop(); Endpoint = $"http://127.0.0.1:{port}";
var profile = document.UseLegacyBrowserProfile ? Path.Combine(host.DataDirectory, "BrowserProfile") : Path.Combine(host.DataDirectory, "BrowserSessions", document.Id, "Profile");
environment = await CoreWebView2Environment.CreateWithOptionsAsync(null, profile, new CoreWebView2EnvironmentOptions
{ AdditionalBrowserArguments = $"--remote-debugging-address=127.0.0.1 --remote-debugging-port={port} --disable-features=CalculateNativeWinOcclusion --disable-background-timer-throttling --disable-renderer-backgrounding" });
}
selected.ThrowIfCancellationRequested();
if (tab.Web.CoreWebView2 is not null && tab.TargetId.Length > 0) return;
if (!tab.Web.IsLoaded)
{
var loaded = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
void Loaded(object sender, RoutedEventArgs args) => loaded.TrySetResult();
tab.Web.Loaded += Loaded;
try { if (!tab.Web.IsLoaded) await loaded.Task.WaitAsync(selected); }
finally { tab.Web.Loaded -= Loaded; }
}
host.InitializeWebView(tab.Web); await tab.Web.EnsureCoreWebView2Async(environment);
if (disposed) { tab.Web.Close(); return; }
var core = tab.Web.CoreWebView2 ?? throw new InvalidOperationException("浏览器标签初始化未完成");
core.SourceChanged += (_, _) => Update(tab);
core.DocumentTitleChanged += (_, _) => Update(tab);
core.NewWindowRequested += async (_, args) =>
{
args.Handled = true;
if (!AgentSession.AllowedUrl(args.Uri)) { error("仅允许打开 HTTP(S) 网页和空白标签页"); return; }
var deferral = args.GetDeferral();
try { await OpenAsync("about:blank"); args.NewWindow = Active.Web.CoreWebView2; }
catch (Exception ex) { error(ex.Message); }
finally { deferral.Complete(); }
};
core.NavigationStarting += (_, args) => { if (!AgentSession.AllowedUrl(args.Uri)) { args.Cancel = true; error("仅允许访问 HTTP(S) 网页和 about:blank"); } };
core.ProcessFailed += (_, _) => { cancel(); error("浏览器进程已退出,请重新启用插件"); };
core.DownloadStarting += (_, args) =>
{
var downloads = Path.Combine(host.DataDirectory, "Downloads"); Directory.CreateDirectory(downloads);
var name = Path.GetFileName(args.ResultFilePath); if (string.IsNullOrWhiteSpace(name)) name = "download.bin";
args.ResultFilePath = Path.Combine(downloads, Guid.NewGuid().ToString("N")[..8] + "-" + name); args.Handled = true;
};
var target = JsonNode.Parse(await core.CallDevToolsProtocolMethodAsync("Target.getTargetInfo", "{}"))!;
tab.TargetId = target["targetInfo"]!["targetId"]!.GetValue<string>();
tab.Web.Source = new Uri(tab.State.Url);
changed();
}
finally { gate.Release(); }
}
private void Update(Tab tab)
{
if (disposed || tab.Web.CoreWebView2 is not { } core) return;
var url = core.Source;
if (!AgentSession.AllowedUrl(url)) return;
var title = string.IsNullOrWhiteSpace(core.DocumentTitle) ? url == "about:blank" ? "新标签页" : new Uri(url).Host : core.DocumentTitle;
tab.State = tab.State with { Url = url, Title = title };
tab.Item.Header = title.Length > 36 ? title[..36] + "…" : title;
ToolTipService.SetToolTip(tab.Item, title + "\n" + url); Capture(); changed();
}
public void Capture()
{
document.BrowserTabs = tabs.Select(x => x.State).ToList();
if (tabs.Count > 0) document.BrowserUrl = Active.State.Url;
}
public async Task OpenAsync(string url)
{
if (!AgentSession.AllowedUrl(url)) throw new ArgumentException("新标签页只支持 HTTP(S) 地址");
var state = new AgentBrowserTab(Guid.NewGuid().ToString("N"), url);
selecting = true;
try { AddItem(state); document.ActiveBrowserTabId = state.Id; Tabs.SelectedItem = Active.Item; ShowActiveSurface(); Capture(); }
finally { selecting = false; }
await EnsureActiveAsync(); changed();
}
public async Task CloseAsync(string id)
{
var tab = tabs.SingleOrDefault(x => x.State.Id == id) ?? throw new ArgumentException("标签页不存在");
selecting = true;
try
{
var index = tabs.IndexOf(tab); tabs.Remove(tab); Tabs.TabItems.Remove(tab.Item); tab.Web.Close();
if (tabs.Count == 0) AddItem(new(Guid.NewGuid().ToString("N")));
if (document.ActiveBrowserTabId == id) document.ActiveBrowserTabId = tabs[Math.Min(index, tabs.Count - 1)].State.Id;
Tabs.SelectedItem = Active.Item; ShowActiveSurface(); Capture();
}
finally { selecting = false; }
await EnsureActiveAsync(); changed();
}
public async Task<JsonObject> InvokeAsync(JsonObject args)
{
var operation = args.String("operation", "list");
switch (operation)
{
case "list": await EnsureActiveAsync(); break;
case "open": await OpenAsync(args.String("url", "about:blank")); break;
case "select":
var tab = tabs.SingleOrDefault(x => x.State.Id == args.String("tabId")) ?? throw new ArgumentException("标签页不存在");
selecting = true; document.ActiveBrowserTabId = tab.State.Id; Tabs.SelectedItem = tab.Item; selecting = false; ShowActiveSurface();
await EnsureActiveAsync(); Capture(); changed(); break;
case "close": await CloseAsync(args.String("tabId")); break;
default: throw new ArgumentException("未知标签操作");
}
return new()
{
["activeTabId"] = document.ActiveBrowserTabId, ["targetId"] = TargetId,
["tabs"] = new JsonArray(tabs.Select(x => (JsonNode?)new JsonObject { ["id"] = x.State.Id, ["title"] = x.State.Title, ["url"] = x.State.Url, ["selected"] = x.State.Id == document.ActiveBrowserTabId }).ToArray())
};
}
private async Task GuardAsync(Func<Task> operation) { try { await operation(); } catch (OperationCanceledException) { } catch (Exception ex) { if (!disposed) error(ex.Message); } }
public void Dispose()
{
if (disposed) return; disposed = true;
selection?.Cancel(); selection?.Dispose();
foreach (var tab in tabs) tab.Web.Close();
Tabs.TabItems.Clear();
}
}