using System.Collections.Concurrent;
using System.Text.Json.Nodes;
using Microsoft.UI.Xaml.Navigation;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Controls;
using XFEWorkflow.Infrastructure.Storage;
namespace XFEWorkflow.Views;
public sealed partial class RunsPage : ManagementPage
{
public static RunsPage? Current { get; private set; }
private readonly ListView list = new() { SelectionMode = ListViewSelectionMode.Single, HorizontalContentAlignment = HorizontalAlignment.Stretch };
private readonly TextBox query = new() { PlaceholderText = "搜索工作流或运行 ID", Width = 280 };
private readonly ComboBox state = new() { Width = 132, ItemsSource = new[] { "全部状态", "成功", "失败", "运行中", "已取消", "已中断", "已跳过" }, SelectedIndex = 0 };
private readonly ComboBox trigger = new() { Width = 170 };
private readonly ComboBox range = new() { Width = 130, ItemsSource = new[] { "最近 7 天", "今天", "最近 30 天", "全部时间" }, SelectedIndex = 0 };
private readonly TextBlock total = new() { FontSize = 26, FontWeight = Microsoft.UI.Text.FontWeights.SemiBold };
private readonly TextBlock succeeded = new() { FontSize = 26, FontWeight = Microsoft.UI.Text.FontWeights.SemiBold };
private readonly TextBlock failed = new() { FontSize = 26, FontWeight = Microsoft.UI.Text.FontWeights.SemiBold };
private readonly StackPanel detail = new() { Spacing = 14 };
private readonly DetailsWorkspace panels = new("runs.details");
private readonly TextBlock empty = new() { Text = "没有匹配的运行记录", HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Opacity = .65, IsHitTestVisible = false };
private readonly DispatcherTimer refreshTimer = new() { Interval = TimeSpan.FromSeconds(1) };
private readonly ConcurrentDictionary<string, RunRecord> live = new();
private List<RunRecord> records = [];
private bool updating, refreshing;
private int dirty;
private string? requestedRun;
public RunsPage() : base("运行记录", "查看触发来源、执行状态与节点详情")
{
Current = this; InitializeComponent();
HeaderActions.Children.Add(ActionButton("刷新", RefreshAsync, "RefreshRuns"));
var summary = new Grid { ColumnSpacing = 10 };
foreach (var _ in Enumerable.Range(0, 3)) summary.ColumnDefinitions.Add(new());
foreach (var item in new[] { ("今天运行", total), ("成功", succeeded), ("失败", failed) }.Select((x, i) => (x, i)))
{ var body = new StackPanel { Spacing = 6 }; body.Children.Add(Caption(item.x.Item1)); body.Children.Add(item.x.Item2); var card = Card(body); Grid.SetColumn(card, item.i); summary.Children.Add(card); }
var filters = new AdaptiveWrapPanel(); foreach (var control in new FrameworkElement[] { query, state, trigger, range }) filters.Children.Add(control);
var toolbar = new StackPanel { Spacing = 12 }; toolbar.Children.Add(summary); toolbar.Children.Add(filters); Toolbar.Children.Add(toolbar); Toolbar.SizeChanged += (_, e) => toolbar.Width = e.NewSize.Width;
list.ItemTemplate = (DataTemplate)Application.Current.Resources["ManagementRunTemplate"]; list.ItemContainerStyle = (Style)Application.Current.Resources["ManagementListItemStyle"];
var master = new Grid(); master.Children.Add(list); master.Children.Add(empty); var masterCard = Card(master); masterCard.Padding = new(6); panels.Master.Content = masterCard;
panels.Details.Content = Card(new ScrollViewer { Content = detail, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled }); Workspace.Children.Add(panels);
list.SelectionChanged += (_, _) => RenderDetails(); query.TextChanged += (_, _) => ApplyFilter();
foreach (var combo in new[] { state, trigger, range }) combo.SelectionChanged += (_, _) => { if (!updating) ApplyFilter(); };
refreshTimer.Tick += async (_, _) => { if (Interlocked.Exchange(ref dirty, 0) != 0) await Guard(RefreshAsync); };
Loaded += async (_, _) => { Services.Runs.RunChanged += RunChanged; refreshTimer.Start(); await Guard(RefreshAsync); };
Unloaded += (_, _) => { Services.Runs.RunChanged -= RunChanged; refreshTimer.Stop(); };
}
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); requestedRun = e.Parameter as string; }
private void RunChanged(RunRecord record) { live[record.Id] = record; Interlocked.Exchange(ref dirty, 1); }
private async Task RefreshAsync()
{
if (refreshing) return; refreshing = true;
try
{
records = await Task.Run(async () => (await Services.Runs.HistoryAsync()).Concat(live.Values).GroupBy(x => x.Id).Select(x => x.Last()).OrderByDescending(x => x.StartedAt).ToList());
var today = records.Where(x => x.StartedAt.LocalDateTime.Date == DateTime.Today).ToArray(); total.Text = today.Length.ToString(); succeeded.Text = today.Count(x => x.Status == RunStatus.Succeeded).ToString(); failed.Text = today.Count(x => x.Status == RunStatus.Failed).ToString();
updating = true; var selected = trigger.SelectedItem as string; trigger.ItemsSource = new[] { "全部触发" }.Concat(records.Select(x => x.Trigger).Distinct()).ToArray(); trigger.SelectedItem = ((IEnumerable<string>)trigger.ItemsSource).Contains(selected ?? "") ? selected : "全部触发"; updating = false;
ApplyFilter();
}
finally { refreshing = false; }
}
private void ApplyFilter()
{
var id = requestedRun ?? (list.SelectedItem as RunRowModel)?.Record.Id;
var since = range.SelectedIndex switch { 1 => DateTime.Today, 2 => DateTime.Today.AddDays(-30), 3 => DateTime.MinValue, _ => DateTime.Today.AddDays(-7) };
var states = new RunStatus?[] { null, RunStatus.Succeeded, RunStatus.Failed, RunStatus.Running, RunStatus.Cancelled, RunStatus.Interrupted, RunStatus.Skipped };
var status = states[Math.Clamp(state.SelectedIndex, 0, states.Length - 1)];
var rows = records.Where(x => x.StartedAt.LocalDateTime >= since && (status is null || x.Status == status) && (trigger.SelectedItem is not string source || source == "全部触发" || x.Trigger == source)
&& (x.WorkflowName.Contains(query.Text, StringComparison.OrdinalIgnoreCase) || x.Id.Contains(query.Text, StringComparison.OrdinalIgnoreCase))).Select(x => new RunRowModel(x)).ToArray();
list.ItemsSource = rows; list.SelectedItem = rows.FirstOrDefault(x => x.Record.Id == id) ?? rows.FirstOrDefault(); requestedRun = null;
empty.Visibility = rows.Length == 0 ? Visibility.Visible : Visibility.Collapsed; Status.Text = $"{rows.Length} 条运行记录 · 记录包含触发来源、输入、输出和节点日志";
if (rows.Length == 0) RenderDetails();
}
private Expander JsonSection(string title, JsonObject value) => new()
{
Header = title, HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Stretch,
Content = new TextBox { AcceptsReturn = true, Text = Services.Redactor.Redact(value.Display(true)), IsReadOnly = true, TextWrapping = TextWrapping.Wrap, FontFamily = new Microsoft.UI.Xaml.Media.FontFamily("Consolas"), MaxHeight = 220 }
};
private void RenderDetails()
{
detail.Children.Clear();
if (list.SelectedItem is not RunRowModel row) { detail.Children.Add(Caption("选择一次运行,查看节点过程与输入输出。")); return; }
var record = row.Record;
detail.Children.Add(new TextBlock { Text = record.WorkflowName, FontSize = 22, FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, TextWrapping = TextWrapping.Wrap });
detail.Children.Add(Label("状态:" + row.StatusLabel + " · " + row.Duration));
detail.Children.Add(Caption("运行 ID:" + record.Id)); detail.Children.Add(Label("触发来源:" + record.Trigger));
detail.Children.Add(Caption($"开始 {record.StartedAt.ToLocalTime():yyyy-MM-dd HH:mm:ss}\n结束 {(record.FinishedAt is { } end ? end.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss") : "尚未结束")}"));
if (record.Error is { } error) detail.Children.Add(new InfoBar { IsOpen = true, IsClosable = false, Severity = record.Status == RunStatus.Failed ? InfoBarSeverity.Error : InfoBarSeverity.Warning, Message = Services.Redactor.Redact(error) });
var actions = new AdaptiveWrapPanel();
actions.Children.Add(ActionButton("重新运行", () => RerunAsync(record), "RerunWorkflow", true));
actions.Children.Add(ActionButton("查看完整日志", () => { AppShellPage.Current!.ViewModel.NavigationViewService.NavigateTo<LogViewPage>(record.Id); return Task.CompletedTask; }, "RunFullLog"));
var locate = ActionButton("定位错误", () => { AppShellPage.Current!.ViewModel.NavigationViewService.NavigateTo<WorkflowEditorPage>(record.Id); return Task.CompletedTask; }, "LocateRunError"); locate.IsEnabled = record.ErrorNodeId is not null; actions.Children.Add(locate); detail.Children.Add(actions);
detail.Children.Add(JsonSection("输入参数", record.Inputs)); detail.Children.Add(JsonSection("输出结果", record.Outputs));
detail.Children.Add(new TextBlock { Text = "节点执行过程", FontWeight = Microsoft.UI.Text.FontWeights.SemiBold });
var events = WorkflowLogService.RunEntries(record);
var timeline = new ListView { ItemsSource = events, ItemTemplateSelector = (DataTemplateSelector)Application.Current.Resources["WorkflowLogTemplates"], ItemContainerStyle = (Style)Application.Current.Resources["ManagementListItemStyle"], MaxHeight = 450, SelectionMode = ListViewSelectionMode.None };
detail.Children.Add(timeline);
}
private async Task RerunAsync(RunRecord record)
{
var workflow = await Services.Workflows.GetAsync(record.WorkflowId) ?? throw new InvalidOperationException("此工作流已删除,运行记录仍保留");
var inputs = new TextBox { Header = "本次输入 JSON", AcceptsReturn = true, Text = record.Inputs.Display(true), TextWrapping = TextWrapping.Wrap, MinWidth = 380, MaxHeight = 350 };
var error = new InfoBar { Severity = InfoBarSeverity.Error, IsClosable = false }; JsonObject? values = null;
var dialog = new ContentDialog { Title = "重新运行 · " + workflow.Name, Content = new StackPanel { Spacing = 10, Children = { Caption("使用当前保存的工作流版本。已隐藏的敏感值请改用凭据引用。"), inputs, error } }, PrimaryButtonText = "运行", CloseButtonText = "取消", XamlRoot = XamlRoot };
dialog.PrimaryButtonClick += (_, e) => { try { values = JsonNode.Parse(inputs.Text)!.AsObject(); } catch (Exception ex) { e.Cancel = true; error.Message = ex.Message; error.IsOpen = true; } };
if (await dialog.ShowAsync() != ContentDialogResult.Primary) return;
var run = await Services.Runs.RunAsync(workflow, "手动重新运行", values, entryNodeId: record.EntryNodeId); requestedRun = run.Id; await RefreshAsync();
}
}
using System.Collections.Concurrent;
using System.Text.Json.Nodes;
using Microsoft.UI.Xaml.Navigation;
using XFEWorkflow.Abstractions;
using XFEWorkflow.Controls;
using XFEWorkflow.Infrastructure.Storage;
namespace XFEWorkflow.Views;
public sealed partial class RunsPage : ManagementPage
{
public static RunsPage? Current { get; private set; }
private readonly ListView list = new() { SelectionMode = ListViewSelectionMode.Single, HorizontalContentAlignment = HorizontalAlignment.Stretch };
private readonly TextBox query = new() { PlaceholderText = "搜索工作流或运行 ID", Width = 280 };
private readonly ComboBox state = new() { Width = 132, ItemsSource = new[] { "全部状态", "成功", "失败", "运行中", "已取消", "已中断", "已跳过" }, SelectedIndex = 0 };
private readonly ComboBox trigger = new() { Width = 170 };
private readonly ComboBox range = new() { Width = 130, ItemsSource = new[] { "最近 7 天", "今天", "最近 30 天", "全部时间" }, SelectedIndex = 0 };
private readonly TextBlock total = new() { FontSize = 26, FontWeight = Microsoft.UI.Text.FontWeights.SemiBold };
private readonly TextBlock succeeded = new() { FontSize = 26, FontWeight = Microsoft.UI.Text.FontWeights.SemiBold };
private readonly TextBlock failed = new() { FontSize = 26, FontWeight = Microsoft.UI.Text.FontWeights.SemiBold };
private readonly StackPanel detail = new() { Spacing = 14 };
private readonly DetailsWorkspace panels = new("runs.details");
private readonly TextBlock empty = new() { Text = "没有匹配的运行记录", HorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Center, Opacity = .65, IsHitTestVisible = false };
private readonly DispatcherTimer refreshTimer = new() { Interval = TimeSpan.FromSeconds(1) };
private readonly ConcurrentDictionary<string, RunRecord> live = new();
private List<RunRecord> records = [];
private bool updating, refreshing;
private int dirty;
private string? requestedRun;
public RunsPage() : base("运行记录", "查看触发来源、执行状态与节点详情")
{
Current = this; InitializeComponent();
HeaderActions.Children.Add(ActionButton("刷新", RefreshAsync, "RefreshRuns"));
var summary = new Grid { ColumnSpacing = 10 };
foreach (var _ in Enumerable.Range(0, 3)) summary.ColumnDefinitions.Add(new());
foreach (var item in new[] { ("今天运行", total), ("成功", succeeded), ("失败", failed) }.Select((x, i) => (x, i)))
{ var body = new StackPanel { Spacing = 6 }; body.Children.Add(Caption(item.x.Item1)); body.Children.Add(item.x.Item2); var card = Card(body); Grid.SetColumn(card, item.i); summary.Children.Add(card); }
var filters = new AdaptiveWrapPanel(); foreach (var control in new FrameworkElement[] { query, state, trigger, range }) filters.Children.Add(control);
var toolbar = new StackPanel { Spacing = 12 }; toolbar.Children.Add(summary); toolbar.Children.Add(filters); Toolbar.Children.Add(toolbar); Toolbar.SizeChanged += (_, e) => toolbar.Width = e.NewSize.Width;
list.ItemTemplate = (DataTemplate)Application.Current.Resources["ManagementRunTemplate"]; list.ItemContainerStyle = (Style)Application.Current.Resources["ManagementListItemStyle"];
var master = new Grid(); master.Children.Add(list); master.Children.Add(empty); var masterCard = Card(master); masterCard.Padding = new(6); panels.Master.Content = masterCard;
panels.Details.Content = Card(new ScrollViewer { Content = detail, HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled }); Workspace.Children.Add(panels);
list.SelectionChanged += (_, _) => RenderDetails(); query.TextChanged += (_, _) => ApplyFilter();
foreach (var combo in new[] { state, trigger, range }) combo.SelectionChanged += (_, _) => { if (!updating) ApplyFilter(); };
refreshTimer.Tick += async (_, _) => { if (Interlocked.Exchange(ref dirty, 0) != 0) await Guard(RefreshAsync); };
Loaded += async (_, _) => { Services.Runs.RunChanged += RunChanged; refreshTimer.Start(); await Guard(RefreshAsync); };
Unloaded += (_, _) => { Services.Runs.RunChanged -= RunChanged; refreshTimer.Stop(); };
}
protected override void OnNavigatedTo(NavigationEventArgs e) { base.OnNavigatedTo(e); requestedRun = e.Parameter as string; }
private void RunChanged(RunRecord record) { live[record.Id] = record; Interlocked.Exchange(ref dirty, 1); }
private async Task RefreshAsync()
{
if (refreshing) return; refreshing = true;
try
{
records = await Task.Run(async () => (await Services.Runs.HistoryAsync()).Concat(live.Values).GroupBy(x => x.Id).Select(x => x.Last()).OrderByDescending(x => x.StartedAt).ToList());
var today = records.Where(x => x.StartedAt.LocalDateTime.Date == DateTime.Today).ToArray(); total.Text = today.Length.ToString(); succeeded.Text = today.Count(x => x.Status == RunStatus.Succeeded).ToString(); failed.Text = today.Count(x => x.Status == RunStatus.Failed).ToString();
updating = true; var selected = trigger.SelectedItem as string; trigger.ItemsSource = new[] { "全部触发" }.Concat(records.Select(x => x.Trigger).Distinct()).ToArray(); trigger.SelectedItem = ((IEnumerable<string>)trigger.ItemsSource).Contains(selected ?? "") ? selected : "全部触发"; updating = false;
ApplyFilter();
}
finally { refreshing = false; }
}
private void ApplyFilter()
{
var id = requestedRun ?? (list.SelectedItem as RunRowModel)?.Record.Id;
var since = range.SelectedIndex switch { 1 => DateTime.Today, 2 => DateTime.Today.AddDays(-30), 3 => DateTime.MinValue, _ => DateTime.Today.AddDays(-7) };
var states = new RunStatus?[] { null, RunStatus.Succeeded, RunStatus.Failed, RunStatus.Running, RunStatus.Cancelled, RunStatus.Interrupted, RunStatus.Skipped };
var status = states[Math.Clamp(state.SelectedIndex, 0, states.Length - 1)];
var rows = records.Where(x => x.StartedAt.LocalDateTime >= since && (status is null || x.Status == status) && (trigger.SelectedItem is not string source || source == "全部触发" || x.Trigger == source)
&& (x.WorkflowName.Contains(query.Text, StringComparison.OrdinalIgnoreCase) || x.Id.Contains(query.Text, StringComparison.OrdinalIgnoreCase))).Select(x => new RunRowModel(x)).ToArray();
list.ItemsSource = rows; list.SelectedItem = rows.FirstOrDefault(x => x.Record.Id == id) ?? rows.FirstOrDefault(); requestedRun = null;
empty.Visibility = rows.Length == 0 ? Visibility.Visible : Visibility.Collapsed; Status.Text = $"{rows.Length} 条运行记录 · 记录包含触发来源、输入、输出和节点日志";
if (rows.Length == 0) RenderDetails();
}
private Expander JsonSection(string title, JsonObject value) => new()
{
Header = title, HorizontalAlignment = HorizontalAlignment.Stretch, HorizontalContentAlignment = HorizontalAlignment.Stretch,
Content = new TextBox { AcceptsReturn = true, Text = Services.Redactor.Redact(value.Display(true)), IsReadOnly = true, TextWrapping = TextWrapping.Wrap, FontFamily = new Microsoft.UI.Xaml.Media.FontFamily("Consolas"), MaxHeight = 220 }
};
private void RenderDetails()
{
detail.Children.Clear();
if (list.SelectedItem is not RunRowModel row) { detail.Children.Add(Caption("选择一次运行,查看节点过程与输入输出。")); return; }
var record = row.Record;
detail.Children.Add(new TextBlock { Text = record.WorkflowName, FontSize = 22, FontWeight = Microsoft.UI.Text.FontWeights.SemiBold, TextWrapping = TextWrapping.Wrap });
detail.Children.Add(Label("状态:" + row.StatusLabel + " · " + row.Duration));
detail.Children.Add(Caption("运行 ID:" + record.Id)); detail.Children.Add(Label("触发来源:" + record.Trigger));
detail.Children.Add(Caption($"开始 {record.StartedAt.ToLocalTime():yyyy-MM-dd HH:mm:ss}\n结束 {(record.FinishedAt is { } end ? end.ToLocalTime().ToString("yyyy-MM-dd HH:mm:ss") : "尚未结束")}"));
if (record.Error is { } error) detail.Children.Add(new InfoBar { IsOpen = true, IsClosable = false, Severity = record.Status == RunStatus.Failed ? InfoBarSeverity.Error : InfoBarSeverity.Warning, Message = Services.Redactor.Redact(error) });
var actions = new AdaptiveWrapPanel();
actions.Children.Add(ActionButton("重新运行", () => RerunAsync(record), "RerunWorkflow", true));
actions.Children.Add(ActionButton("查看完整日志", () => { AppShellPage.Current!.ViewModel.NavigationViewService.NavigateTo<LogViewPage>(record.Id); return Task.CompletedTask; }, "RunFullLog"));
var locate = ActionButton("定位错误", () => { AppShellPage.Current!.ViewModel.NavigationViewService.NavigateTo<WorkflowEditorPage>(record.Id); return Task.CompletedTask; }, "LocateRunError"); locate.IsEnabled = record.ErrorNodeId is not null; actions.Children.Add(locate); detail.Children.Add(actions);
detail.Children.Add(JsonSection("输入参数", record.Inputs)); detail.Children.Add(JsonSection("输出结果", record.Outputs));
detail.Children.Add(new TextBlock { Text = "节点执行过程", FontWeight = Microsoft.UI.Text.FontWeights.SemiBold });
var events = WorkflowLogService.RunEntries(record);
var timeline = new ListView { ItemsSource = events, ItemTemplateSelector = (DataTemplateSelector)Application.Current.Resources["WorkflowLogTemplates"], ItemContainerStyle = (Style)Application.Current.Resources["ManagementListItemStyle"], MaxHeight = 450, SelectionMode = ListViewSelectionMode.None };
detail.Children.Add(timeline);
}
private async Task RerunAsync(RunRecord record)
{
var workflow = await Services.Workflows.GetAsync(record.WorkflowId) ?? throw new InvalidOperationException("此工作流已删除,运行记录仍保留");
var inputs = new TextBox { Header = "本次输入 JSON", AcceptsReturn = true, Text = record.Inputs.Display(true), TextWrapping = TextWrapping.Wrap, MinWidth = 380, MaxHeight = 350 };
var error = new InfoBar { Severity = InfoBarSeverity.Error, IsClosable = false }; JsonObject? values = null;
var dialog = new ContentDialog { Title = "重新运行 · " + workflow.Name, Content = new StackPanel { Spacing = 10, Children = { Caption("使用当前保存的工作流版本。已隐藏的敏感值请改用凭据引用。"), inputs, error } }, PrimaryButtonText = "运行", CloseButtonText = "取消", XamlRoot = XamlRoot };
dialog.PrimaryButtonClick += (_, e) => { try { values = JsonNode.Parse(inputs.Text)!.AsObject(); } catch (Exception ex) { e.Cancel = true; error.Message = ex.Message; error.IsOpen = true; } };
if (await dialog.ShowAsync() != ContentDialogResult.Primary) return;
var run = await Services.Runs.RunAsync(workflow, "手动重新运行", values, entryNodeId: record.EntryNodeId); requestedRun = run.Id; await RefreshAsync();
}
}