using System.Text.Json;
using System.Text.Json.Nodes;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using XFEWorkflow.Abstractions;
namespace XFEWorkflow.Plugins.AgentBrowser.WinUI;
public sealed partial class AgentBrowserPage
{
private async Task ShowSettingsAsync()
{
if (active is not null) return;
using var editing = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token);
var endpointBox = new TextBox { Header = "DeepSeek API 地址", Text = options.Endpoint };
var modelBox = new ComboBox { Header = "模型", IsEditable = true, HorizontalAlignment = HorizontalAlignment.Stretch };
foreach (var model in new[] { "deepseek-v4-flash", "deepseek-v4-pro", "deepseek-v4-flash-vision-exp" }) modelBox.Items.Add(model);
if (modelBox.Items.Contains(options.Model)) modelBox.SelectedItem = options.Model;
modelBox.Text = options.Model; modelBox.Loaded += (_, _) => modelBox.Text = options.Model;
var secret = new PasswordBox { Header = "DeepSeek API Key", PlaceholderText = "粘贴新的密钥;留空保留已保存的密钥", PasswordRevealMode = PasswordRevealMode.Peek, MaxLength = 4096 };
AutomationId(secret, "AgentApiKey");
var keyState = new InfoBar { IsOpen = true, IsClosable = false };
AutomationId(keyState, "AgentApiKeyState");
var existing = new ComboBox { Header = "使用已有凭据", HorizontalAlignment = HorizontalAlignment.Stretch };
existing.Items.Add(new ComboBoxItem { Content = "未选择(在上方填写 API Key)", Tag = "" }); existing.SelectedIndex = 0;
foreach (var reference in host.CredentialReferences.Where(x => !x.StartsWith("space.session.", StringComparison.Ordinal)))
{
var item = new ComboBoxItem { Content = reference, Tag = reference }; existing.Items.Add(item);
if (reference == options.Credential) existing.SelectedItem = item;
}
string SelectedReference() => (existing.SelectedItem as ComboBoxItem)?.Tag as string ?? "";
void UpdateKeyState()
{
try
{
var key = AgentApiSettings.NormalizeKey(secret.Password);
if (key.Length > 0) { keyState.Title = "新密钥待保存"; keyState.Message = "点击保存后生效;不会覆盖所选的其他共享凭据。"; keyState.Severity = InfoBarSeverity.Informational; }
else if (SelectedReference() is { Length: > 0 } reference)
{
if (AgentApiSettings.NormalizeKey(host.GetCredential(reference)).Length == 0) throw new ArgumentException("保存的密钥为空,请重新填写");
keyState.Title = "API Key 已配置"; keyState.Message = "密钥已加密保存。留空保持原密钥,填写新值后保存即可更换。"; keyState.Severity = InfoBarSeverity.Success;
}
else { keyState.Title = "尚未配置 API Key"; keyState.Message = "直接在上方粘贴密钥并保存,无需填写凭据名称。"; keyState.Severity = InfoBarSeverity.Informational; }
}
catch (Exception ex) { keyState.Title = "请检查 API Key"; keyState.Message = host.Redact(ex.Message); keyState.Severity = InfoBarSeverity.Warning; }
}
secret.PasswordChanged += (_, _) => UpdateKeyState();
existing.SelectionChanged += (_, _) => UpdateKeyState(); UpdateKeyState();
var verify = new Button { Content = "验证 API Key / 获取模型" }; AutomationId(verify, "AgentVerifyApiKey");
var connection = new InfoBar { IsOpen = false, IsClosable = true }; AutomationId(connection, "AgentApiConnection");
secret.PasswordChanged += (_, _) => connection.IsOpen = false;
existing.SelectionChanged += (_, _) => connection.IsOpen = false;
endpointBox.TextChanged += (_, _) => connection.IsOpen = false;
modelBox.RegisterPropertyChangedCallback(ComboBox.TextProperty, (_, _) => connection.IsOpen = false);
var thinking = new CheckBox { Content = "启用 DeepSeek 思考模式", IsChecked = options.Thinking };
var vision = new CheckBox { Content = "将截图发送给模型(仅用于支持图片输入的模型)", IsChecked = options.Vision };
var steps = new NumberBox { Header = "最多工具轮数(0 为不限,默认不限)", Minimum = 0, Maximum = int.MaxValue, Value = options.MaximumSteps, SpinButtonPlacementMode = NumberBoxSpinButtonPlacementMode.Compact };
AutomationId(steps, "AgentMaximumSteps");
var fields = new StackPanel { Spacing = 12, MinWidth = Math.Min(380, Math.Max(240, root.XamlRoot.Size.Width - 120)), MaxWidth = 620 };
foreach (var item in new UIElement[] { secret, keyState, verify, connection, endpointBox, modelBox,
new Expander { Header = "使用已有密钥(可选)", Content = existing, HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Stretch },
thinking, vision, steps }) fields.Children.Add(item);
var dialog = new ContentDialog
{
Title = "DeepSeek 浏览器 Agent 设置", Content = new ScrollViewer { Content = fields, MaxHeight = Math.Max(240, root.XamlRoot.Size.Height - 260) },
PrimaryButtonText = "保存", CloseButtonText = "取消", DefaultButton = ContentDialogButton.Primary, XamlRoot = root.XamlRoot, RequestedTheme = root.ActualTheme
};
dialog.Resources["ContentDialogMaxWidth"] = 680d;
AgentOptions Proposed() => new()
{
Endpoint = endpointBox.Text.Trim(), Model = modelBox.Text.Trim(),
Credential = AgentApiSettings.ResolveReference(secret.Password, SelectedReference(), host.CredentialReferences),
MaximumSteps = (int)steps.Value,
MigratedContextKeys = [.. options.MigratedContextKeys],
MigrationContextKey = options.MigrationContextKey,
Thinking = thinking.IsChecked == true, Vision = vision.IsChecked == true
};
verify.Click += async (_, _) =>
{
verify.IsEnabled = dialog.IsPrimaryButtonEnabled = false; connection.IsOpen = true;
connection.Title = "正在验证 API Key"; connection.Message = "读取模型列表,不发送对话内容。"; connection.Severity = InfoBarSeverity.Informational;
var entered = secret.Password; var selected = SelectedReference(); var address = endpointBox.Text; var model = modelBox.Text;
try
{
var proposed = Proposed();
var key = AgentApiSettings.NormalizeKey(entered);
if (key.Length == 0) key = GetConfiguredKey(proposed);
var models = await AgentApiSettings.VerifyAsync(http, proposed, key, editing.Token);
if (entered != secret.Password || selected != SelectedReference() || address != endpointBox.Text || model != modelBox.Text)
{ connection.Title = "配置已修改"; connection.Message = "请重新验证当前配置。"; return; }
foreach (var name in models) if (!modelBox.Items.Contains(name)) modelBox.Items.Add(name);
connection.Title = "API Key 验证通过"; connection.Message = $"已读取 {models.Count} 个模型;未发送聊天请求。" + (models.Contains(proposed.Model) ? "" : " 当前模型未列出,请确认模型别名或重新选择。");
connection.Severity = models.Contains(proposed.Model) ? InfoBarSeverity.Success : InfoBarSeverity.Warning;
}
catch (OperationCanceledException) { if (!editing.IsCancellationRequested) { connection.Title = "验证超时"; connection.Message = "请检查服务地址或网络后重试。"; connection.Severity = InfoBarSeverity.Error; } }
catch (Exception ex) { connection.Title = "API Key 验证失败"; connection.Message = host.Redact(ex.Message); connection.Severity = InfoBarSeverity.Error; }
finally { verify.IsEnabled = dialog.IsPrimaryButtonEnabled = true; }
};
var validation = new InfoBar { Severity = InfoBarSeverity.Error, IsOpen = false }; fields.Children.Insert(0, validation);
dialog.PrimaryButtonClick += async (_, args) =>
{
var deferral = args.GetDeferral();
try
{
var proposed = Proposed(); proposed.CompletionUri();
var key = AgentApiSettings.NormalizeKey(secret.Password);
var settings = JsonSerializer.SerializeToNode(proposed, WorkflowJson.Options)!.AsObject();
if (key.Length > 0) await host.SaveSettingsWithCredentialAsync(settings, proposed.Credential, key, editing.Token);
else await host.SaveSettingsAsync(settings, editing.Token);
if (proposed.Endpoint != options.Endpoint || proposed.Model != options.Model || proposed.Thinking != options.Thinking || proposed.Vision != options.Vision)
{ conversation!.Clear(); session.Context = []; }
options = proposed; modelLabel.Text = options.Model; ToolTipService.SetToolTip(modelLabel, "DeepSeek · " + options.Model);
session.ContextKey = AgentSession.Key(options); await FlushSessionAsync();
status.Text = "设置已保存 · 对话记录保留";
}
catch (Exception ex) { args.Cancel = true; validation.Message = host.Redact(ex.Message); validation.IsOpen = true; }
finally { deferral.Complete(); }
};
try { await dialog.ShowAsync(); }
finally { editing.Cancel(); }
}
private static void AutomationId(DependencyObject element, string id) => Microsoft.UI.Xaml.Automation.AutomationProperties.SetAutomationId(element, id);
}
using System.Text.Json;
using System.Text.Json.Nodes;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using XFEWorkflow.Abstractions;
namespace XFEWorkflow.Plugins.AgentBrowser.WinUI;
public sealed partial class AgentBrowserPage
{
private async Task ShowSettingsAsync()
{
if (active is not null) return;
using var editing = CancellationTokenSource.CreateLinkedTokenSource(lifetime.Token);
var endpointBox = new TextBox { Header = "DeepSeek API 地址", Text = options.Endpoint };
var modelBox = new ComboBox { Header = "模型", IsEditable = true, HorizontalAlignment = HorizontalAlignment.Stretch };
foreach (var model in new[] { "deepseek-v4-flash", "deepseek-v4-pro", "deepseek-v4-flash-vision-exp" }) modelBox.Items.Add(model);
if (modelBox.Items.Contains(options.Model)) modelBox.SelectedItem = options.Model;
modelBox.Text = options.Model; modelBox.Loaded += (_, _) => modelBox.Text = options.Model;
var secret = new PasswordBox { Header = "DeepSeek API Key", PlaceholderText = "粘贴新的密钥;留空保留已保存的密钥", PasswordRevealMode = PasswordRevealMode.Peek, MaxLength = 4096 };
AutomationId(secret, "AgentApiKey");
var keyState = new InfoBar { IsOpen = true, IsClosable = false };
AutomationId(keyState, "AgentApiKeyState");
var existing = new ComboBox { Header = "使用已有凭据", HorizontalAlignment = HorizontalAlignment.Stretch };
existing.Items.Add(new ComboBoxItem { Content = "未选择(在上方填写 API Key)", Tag = "" }); existing.SelectedIndex = 0;
foreach (var reference in host.CredentialReferences.Where(x => !x.StartsWith("space.session.", StringComparison.Ordinal)))
{
var item = new ComboBoxItem { Content = reference, Tag = reference }; existing.Items.Add(item);
if (reference == options.Credential) existing.SelectedItem = item;
}
string SelectedReference() => (existing.SelectedItem as ComboBoxItem)?.Tag as string ?? "";
void UpdateKeyState()
{
try
{
var key = AgentApiSettings.NormalizeKey(secret.Password);
if (key.Length > 0) { keyState.Title = "新密钥待保存"; keyState.Message = "点击保存后生效;不会覆盖所选的其他共享凭据。"; keyState.Severity = InfoBarSeverity.Informational; }
else if (SelectedReference() is { Length: > 0 } reference)
{
if (AgentApiSettings.NormalizeKey(host.GetCredential(reference)).Length == 0) throw new ArgumentException("保存的密钥为空,请重新填写");
keyState.Title = "API Key 已配置"; keyState.Message = "密钥已加密保存。留空保持原密钥,填写新值后保存即可更换。"; keyState.Severity = InfoBarSeverity.Success;
}
else { keyState.Title = "尚未配置 API Key"; keyState.Message = "直接在上方粘贴密钥并保存,无需填写凭据名称。"; keyState.Severity = InfoBarSeverity.Informational; }
}
catch (Exception ex) { keyState.Title = "请检查 API Key"; keyState.Message = host.Redact(ex.Message); keyState.Severity = InfoBarSeverity.Warning; }
}
secret.PasswordChanged += (_, _) => UpdateKeyState();
existing.SelectionChanged += (_, _) => UpdateKeyState(); UpdateKeyState();
var verify = new Button { Content = "验证 API Key / 获取模型" }; AutomationId(verify, "AgentVerifyApiKey");
var connection = new InfoBar { IsOpen = false, IsClosable = true }; AutomationId(connection, "AgentApiConnection");
secret.PasswordChanged += (_, _) => connection.IsOpen = false;
existing.SelectionChanged += (_, _) => connection.IsOpen = false;
endpointBox.TextChanged += (_, _) => connection.IsOpen = false;
modelBox.RegisterPropertyChangedCallback(ComboBox.TextProperty, (_, _) => connection.IsOpen = false);
var thinking = new CheckBox { Content = "启用 DeepSeek 思考模式", IsChecked = options.Thinking };
var vision = new CheckBox { Content = "将截图发送给模型(仅用于支持图片输入的模型)", IsChecked = options.Vision };
var steps = new NumberBox { Header = "最多工具轮数(0 为不限,默认不限)", Minimum = 0, Maximum = int.MaxValue, Value = options.MaximumSteps, SpinButtonPlacementMode = NumberBoxSpinButtonPlacementMode.Compact };
AutomationId(steps, "AgentMaximumSteps");
var fields = new StackPanel { Spacing = 12, MinWidth = Math.Min(380, Math.Max(240, root.XamlRoot.Size.Width - 120)), MaxWidth = 620 };
foreach (var item in new UIElement[] { secret, keyState, verify, connection, endpointBox, modelBox,
new Expander { Header = "使用已有密钥(可选)", Content = existing, HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Stretch },
thinking, vision, steps }) fields.Children.Add(item);
var dialog = new ContentDialog
{
Title = "DeepSeek 浏览器 Agent 设置", Content = new ScrollViewer { Content = fields, MaxHeight = Math.Max(240, root.XamlRoot.Size.Height - 260) },
PrimaryButtonText = "保存", CloseButtonText = "取消", DefaultButton = ContentDialogButton.Primary, XamlRoot = root.XamlRoot, RequestedTheme = root.ActualTheme
};
dialog.Resources["ContentDialogMaxWidth"] = 680d;
AgentOptions Proposed() => new()
{
Endpoint = endpointBox.Text.Trim(), Model = modelBox.Text.Trim(),
Credential = AgentApiSettings.ResolveReference(secret.Password, SelectedReference(), host.CredentialReferences),
MaximumSteps = (int)steps.Value,
MigratedContextKeys = [.. options.MigratedContextKeys],
MigrationContextKey = options.MigrationContextKey,
Thinking = thinking.IsChecked == true, Vision = vision.IsChecked == true
};
verify.Click += async (_, _) =>
{
verify.IsEnabled = dialog.IsPrimaryButtonEnabled = false; connection.IsOpen = true;
connection.Title = "正在验证 API Key"; connection.Message = "读取模型列表,不发送对话内容。"; connection.Severity = InfoBarSeverity.Informational;
var entered = secret.Password; var selected = SelectedReference(); var address = endpointBox.Text; var model = modelBox.Text;
try
{
var proposed = Proposed();
var key = AgentApiSettings.NormalizeKey(entered);
if (key.Length == 0) key = GetConfiguredKey(proposed);
var models = await AgentApiSettings.VerifyAsync(http, proposed, key, editing.Token);
if (entered != secret.Password || selected != SelectedReference() || address != endpointBox.Text || model != modelBox.Text)
{ connection.Title = "配置已修改"; connection.Message = "请重新验证当前配置。"; return; }
foreach (var name in models) if (!modelBox.Items.Contains(name)) modelBox.Items.Add(name);
connection.Title = "API Key 验证通过"; connection.Message = $"已读取 {models.Count} 个模型;未发送聊天请求。" + (models.Contains(proposed.Model) ? "" : " 当前模型未列出,请确认模型别名或重新选择。");
connection.Severity = models.Contains(proposed.Model) ? InfoBarSeverity.Success : InfoBarSeverity.Warning;
}
catch (OperationCanceledException) { if (!editing.IsCancellationRequested) { connection.Title = "验证超时"; connection.Message = "请检查服务地址或网络后重试。"; connection.Severity = InfoBarSeverity.Error; } }
catch (Exception ex) { connection.Title = "API Key 验证失败"; connection.Message = host.Redact(ex.Message); connection.Severity = InfoBarSeverity.Error; }
finally { verify.IsEnabled = dialog.IsPrimaryButtonEnabled = true; }
};
var validation = new InfoBar { Severity = InfoBarSeverity.Error, IsOpen = false }; fields.Children.Insert(0, validation);
dialog.PrimaryButtonClick += async (_, args) =>
{
var deferral = args.GetDeferral();
try
{
var proposed = Proposed(); proposed.CompletionUri();
var key = AgentApiSettings.NormalizeKey(secret.Password);
var settings = JsonSerializer.SerializeToNode(proposed, WorkflowJson.Options)!.AsObject();
if (key.Length > 0) await host.SaveSettingsWithCredentialAsync(settings, proposed.Credential, key, editing.Token);
else await host.SaveSettingsAsync(settings, editing.Token);
if (proposed.Endpoint != options.Endpoint || proposed.Model != options.Model || proposed.Thinking != options.Thinking || proposed.Vision != options.Vision)
{ conversation!.Clear(); session.Context = []; }
options = proposed; modelLabel.Text = options.Model; ToolTipService.SetToolTip(modelLabel, "DeepSeek · " + options.Model);
session.ContextKey = AgentSession.Key(options); await FlushSessionAsync();
status.Text = "设置已保存 · 对话记录保留";
}
catch (Exception ex) { args.Cancel = true; validation.Message = host.Redact(ex.Message); validation.IsOpen = true; }
finally { deferral.Complete(); }
};
try { await dialog.ShowAsync(); }
finally { editing.Cancel(); }
}
private static void AutomationId(DependencyObject element, string id) => Microsoft.UI.Xaml.Automation.AutomationProperties.SetAutomationId(element, id);
}