Files
CommandForge/src/CommandForge.Wpf/ViewModels/ExecutionViewModel.cs
T
poli0981andClaude Opus 4.8 9332722997 feat(recipes): command chains / macros with stop-on-error (v-next Đợt 4)
Implements B2 from docs/Extra.md Part 1 (Macro / recipe).

- Domain: Recipe (named, ordered list of catalog command ids).
- Application: IRecipeStore port + pure RecipeFlow.ShouldStop
  (stop on failure / cancel / reboot-required).
- Infrastructure: JsonRecipeStore -> %AppData%\CommandForge\recipes.json
  (source-gen, schema version, corrupt-file fallback). No telemetry;
  recipes reference only vetted catalog ids.
- WPF: ExecutionViewModel.RunRecipeAsync runs steps sequentially
  through the same broker session (one UAC for an all-admin chain),
  streaming a per-step header and stopping per RecipeFlow. New Recipes
  shell section (sidebar + View menu) with RecipesViewModel/RecipesView:
  build/reorder/remove steps from the catalog, save/delete recipes, and
  Run with a single aggregated confirmation (warns on dangerous steps).
  Each finished step is recorded in the execution history.
- EN/VI .resx keys; tests for RecipeFlow and the recipe store.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-19 14:51:39 +07:00

230 lines
7.6 KiB
C#

using System.Collections.ObjectModel;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Threading.Channels;
using System.Windows;
using CommandForge.Application.Recipes;
using CommandForge.Application.UseCases;
using CommandForge.Domain;
using CommandForge.Wpf.Resources;
using CommunityToolkit.Mvvm.ComponentModel;
using CommunityToolkit.Mvvm.Input;
namespace CommandForge.Wpf.ViewModels;
/// <summary>
/// Hosts a single command run: live console output (streamed off the UI thread via a channel),
/// cancellation, and the result (exit code, duration, restart-required).
/// </summary>
public sealed partial class ExecutionViewModel : ObservableObject
{
private readonly RunCommandUseCase _run;
private CancellationTokenSource? _cancellation;
public ExecutionViewModel(RunCommandUseCase run) => _run = run;
/// <summary>Live output lines (stdout + stderr).</summary>
public ObservableCollection<OutputLine> OutputLines { get; } = [];
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowConsole))]
private bool _isRunning;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(ShowConsole))]
private bool _hasResult;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(StatusText))]
private bool _success;
[ObservableProperty]
[NotifyPropertyChangedFor(nameof(StatusText))]
private bool _cancelled;
[ObservableProperty]
private bool _requiresRestart;
[ObservableProperty]
private int _exitCode;
[ObservableProperty]
private string _durationText = string.Empty;
/// <summary>Whether the console panel should be visible (running or has a result).</summary>
public bool ShowConsole => IsRunning || HasResult;
/// <summary>
/// The result of the most recent finished run (the main command, not the restore point),
/// or null if nothing has run yet. Used by callers to record execution history.
/// </summary>
public ExecutionResult? LastResult { get; private set; }
/// <summary>Localized result status (Success / Failed / Cancelled).</summary>
public string StatusText => Cancelled
? Strings.Get("Result_Cancelled")
: Success ? Strings.Get("Result_Success") : Strings.Get("Result_Failed");
/// <summary>
/// Runs <paramref name="command"/>, streaming output to <see cref="OutputLines"/>. If
/// <paramref name="restorePointCommand"/> is supplied it runs first (before a risky command);
/// both go through the same broker, so they share one UAC prompt.
/// </summary>
public async Task RunAsync(CommandDefinition command, CommandDefinition? restorePointCommand = null)
{
ArgumentNullException.ThrowIfNull(command);
if (IsRunning)
{
return;
}
OutputLines.Clear();
HasResult = false;
IsRunning = true;
_cancellation = new CancellationTokenSource();
var token = _cancellation.Token;
try
{
if (restorePointCommand is not null)
{
OutputLines.Add(new OutputLine(Strings.Get("Restore_Creating"), IsError: false));
var restoreResult = await RunOneAsync(restorePointCommand, token);
if (restoreResult.Cancelled)
{
ApplyResult(restoreResult);
return;
}
OutputLines.Add(new OutputLine(
Strings.Get(restoreResult.Success ? "Restore_Created" : "Restore_Failed"),
IsError: !restoreResult.Success));
}
ApplyResult(await RunOneAsync(command, token));
}
finally
{
IsRunning = false;
_cancellation.Dispose();
_cancellation = null;
}
}
/// <summary>
/// Runs a recipe's <paramref name="steps"/> sequentially through the same broker session (one
/// UAC prompt for an all-admin chain), streaming output with a header per step. Stops on the
/// first failure, cancellation, or reboot-required step (see <see cref="RecipeFlow.ShouldStop"/>).
/// Returns the (commandId, result) of each executed step, for history recording.
/// </summary>
public async Task<IReadOnlyList<(string CommandId, ExecutionResult Result)>> RunRecipeAsync(
IReadOnlyList<CommandDefinition> steps)
{
ArgumentNullException.ThrowIfNull(steps);
var executed = new List<(string CommandId, ExecutionResult Result)>();
if (IsRunning || steps.Count == 0)
{
return executed;
}
OutputLines.Clear();
HasResult = false;
IsRunning = true;
_cancellation = new CancellationTokenSource();
var token = _cancellation.Token;
ExecutionResult? last = null;
try
{
for (var i = 0; i < steps.Count; i++)
{
var step = steps[i];
OutputLines.Add(new OutputLine(
string.Format(
CultureInfo.CurrentCulture,
Strings.Get("Recipe_StepHeader"),
i + 1,
steps.Count,
Strings.Get(step.TitleKey)),
IsError: false));
var result = await RunOneAsync(step, token);
last = result;
executed.Add((step.Id, result));
if (RecipeFlow.ShouldStop(result))
{
var key = result.Cancelled ? "Recipe_Cancelled"
: result.RequiresRestart ? "Recipe_StoppedRestart"
: "Recipe_StoppedOnError";
OutputLines.Add(new OutputLine(Strings.Get(key), IsError: !result.Success && !result.Cancelled));
break;
}
}
if (last is not null)
{
ApplyResult(last);
}
}
finally
{
IsRunning = false;
_cancellation.Dispose();
_cancellation = null;
}
return executed;
}
private async Task<ExecutionResult> RunOneAsync(CommandDefinition command, CancellationToken token)
{
var channel = Channel.CreateBounded<OutputLine>(
new BoundedChannelOptions(4096) { SingleReader = true, SingleWriter = false });
// Executor runs off the UI thread; we consume on the UI thread (safe to touch the collection).
var execution = Task.Run(() => _run.RunAsync(command, channel.Writer, token), CancellationToken.None);
await foreach (var line in channel.Reader.ReadAllAsync(CancellationToken.None))
{
OutputLines.Add(line);
}
return await execution;
}
private void ApplyResult(ExecutionResult result)
{
LastResult = result;
ExitCode = result.ExitCode;
Success = result.Success;
Cancelled = result.Cancelled;
RequiresRestart = result.RequiresRestart;
DurationText = FormatDuration(result.Duration);
HasResult = true;
}
[RelayCommand]
private void Cancel() => _cancellation?.Cancel();
[RelayCommand]
private void CopyOutput()
{
var text = string.Join(Environment.NewLine, OutputLines.Select(l => l.Text));
try
{
Clipboard.SetText(text);
}
catch (COMException)
{
// Clipboard temporarily locked — safe to ignore.
}
}
private static string FormatDuration(TimeSpan duration)
=> duration.TotalSeconds < 1
? $"{duration.TotalMilliseconds:F0} ms"
: $"{duration.TotalSeconds:F1} s";
}