Merge pull request #28 from poli0981/claude/vnext-dot5-usercmds
feat(user-commands): non-elevated user-defined commands (v-next Đợt 5)
This commit is contained in:
17 files changed
+778
No files matched your search
@@ -0,0 +1,19 @@
|
||||
using CommandForge.Domain;
|
||||
|
||||
namespace CommandForge.Application.Ports;
|
||||
|
||||
/// <summary>
|
||||
/// Stores user-defined commands locally, fully separate from the vetted embedded catalog
|
||||
/// (golden rule #1). These commands always run without elevation.
|
||||
/// </summary>
|
||||
public interface IUserCommandStore
|
||||
{
|
||||
/// <summary>All user-defined commands, in stored order.</summary>
|
||||
public IReadOnlyList<UserCommand> GetAll();
|
||||
|
||||
/// <summary>Creates or overwrites a command (matched by id) and persists.</summary>
|
||||
public void Save(UserCommand command);
|
||||
|
||||
/// <summary>Deletes the command <paramref name="id"/> (no-op if absent) and persists.</summary>
|
||||
public void Delete(string id);
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
using CommandForge.Domain;
|
||||
|
||||
namespace CommandForge.Application.UserCommands;
|
||||
|
||||
/// <summary>
|
||||
/// Builds an executable <see cref="CommandDefinition"/> for a user-defined command.
|
||||
///
|
||||
/// SAFETY (golden rule #1): the produced definition ALWAYS has <see cref="CommandDefinition.RequiresAdmin"/>
|
||||
/// = false, so user commands run as the current (non-elevated) user and can never be routed to the
|
||||
/// elevation broker by <c>RunCommandUseCase</c>. The id is namespaced with <see cref="IdPrefix"/> so it
|
||||
/// can never collide with — or be mistaken for — a vetted catalog id; even if a bug routed it to the
|
||||
/// Elevator, the Elevator validates ids against its own embedded catalog and rejects anything else.
|
||||
/// </summary>
|
||||
public static class UserCommandFactory
|
||||
{
|
||||
/// <summary>Prefix marking an id as user-defined (never present in the vetted catalog).</summary>
|
||||
public const string IdPrefix = "user:";
|
||||
|
||||
/// <summary>Converts a user command to a non-elevated executable definition.</summary>
|
||||
public static CommandDefinition ToDefinition(UserCommand command)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
|
||||
return new CommandDefinition
|
||||
{
|
||||
Id = IdPrefix + command.Id,
|
||||
CategoryId = "user",
|
||||
TitleKey = command.Name,
|
||||
DescriptionKey = command.Name,
|
||||
Executable = command.Executable,
|
||||
ArgsTemplate = command.Arguments,
|
||||
ExecutionMode = ExecutionMode.Capture,
|
||||
RequiresAdmin = false, // INVARIANT — a user command must never elevate.
|
||||
DangerLevel = DangerLevel.Caution,
|
||||
Restart = RestartPolicy.No,
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
namespace CommandForge.Domain;
|
||||
|
||||
/// <summary>
|
||||
/// A user-defined command. These are NOT part of the vetted, embedded catalog and ALWAYS run
|
||||
/// without elevation (asInvoker) — see golden rule #1. Stored separately from the catalog.
|
||||
/// </summary>
|
||||
public sealed record UserCommand
|
||||
{
|
||||
/// <summary>Stable local id (generated when the command is created).</summary>
|
||||
public required string Id { get; init; }
|
||||
|
||||
/// <summary>User-visible name.</summary>
|
||||
public required string Name { get; init; }
|
||||
|
||||
/// <summary>Executable to run (e.g. <c>cmd</c>, <c>powershell</c>, or a full path).</summary>
|
||||
public required string Executable { get; init; }
|
||||
|
||||
/// <summary>Command-line arguments (optional).</summary>
|
||||
public string Arguments { get; init; } = "";
|
||||
}
|
||||
@@ -29,6 +29,9 @@ public static class AppPaths
|
||||
/// <summary><c>%AppData%\CommandForge\recipes.json</c> — user-defined recipes (command chains).</summary>
|
||||
public static string RecipesFilePath { get; } = Path.Combine(DataDirectory, "recipes.json");
|
||||
|
||||
/// <summary><c>%AppData%\CommandForge\user-commands.json</c> — user-defined (non-elevated) commands.</summary>
|
||||
public static string UserCommandsFilePath { get; } = Path.Combine(DataDirectory, "user-commands.json");
|
||||
|
||||
/// <summary>Ensures the data and logs directories exist.</summary>
|
||||
public static void EnsureCreated()
|
||||
{
|
||||
|
||||
@@ -40,6 +40,7 @@ public static class ServiceCollectionExtensions
|
||||
services.AddSingleton<ISettingsFile, Portability.JsonSettingsFile>();
|
||||
services.AddSingleton<IProfileService, Portability.JsonProfileService>();
|
||||
services.AddSingleton<IRecipeStore, Recipes.JsonRecipeStore>();
|
||||
services.AddSingleton<IUserCommandStore, UserCommands.JsonUserCommandStore>();
|
||||
services.AddSingleton<ISystemInfoService, WindowsSystemInfoService>();
|
||||
services.AddSingleton<ICatalogProvider, JsonCatalogProvider>();
|
||||
services.AddSingleton<IProcessRunner, SystemProcessRunner>();
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
using System.Text.Json;
|
||||
using CommandForge.Application.Ports;
|
||||
using CommandForge.Domain;
|
||||
|
||||
namespace CommandForge.Infrastructure.UserCommands;
|
||||
|
||||
/// <summary>
|
||||
/// <see cref="IUserCommandStore"/> backed by a local <c>user-commands.json</c>, kept entirely
|
||||
/// separate from the embedded catalog (golden rule #1). All data stays on the machine (no telemetry).
|
||||
/// </summary>
|
||||
public sealed class JsonUserCommandStore : IUserCommandStore
|
||||
{
|
||||
private readonly string _path;
|
||||
private List<UserCommand> _commands;
|
||||
|
||||
/// <summary>Creates a store backed by the default <see cref="AppPaths.UserCommandsFilePath"/>.</summary>
|
||||
public JsonUserCommandStore()
|
||||
: this(AppPaths.UserCommandsFilePath)
|
||||
{
|
||||
}
|
||||
|
||||
/// <summary>Creates a store backed by an explicit path (used in tests).</summary>
|
||||
public JsonUserCommandStore(string path)
|
||||
{
|
||||
_path = path;
|
||||
_commands = Load(path);
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public IReadOnlyList<UserCommand> GetAll() => _commands;
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Save(UserCommand command)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(command);
|
||||
|
||||
_commands.RemoveAll(c => string.Equals(c.Id, command.Id, StringComparison.Ordinal));
|
||||
_commands.Add(command);
|
||||
SaveFile();
|
||||
}
|
||||
|
||||
/// <inheritdoc />
|
||||
public void Delete(string id)
|
||||
{
|
||||
if (_commands.RemoveAll(c => string.Equals(c.Id, id, StringComparison.Ordinal)) > 0)
|
||||
{
|
||||
SaveFile();
|
||||
}
|
||||
}
|
||||
|
||||
private void SaveFile()
|
||||
{
|
||||
var directory = Path.GetDirectoryName(_path);
|
||||
if (!string.IsNullOrEmpty(directory))
|
||||
{
|
||||
Directory.CreateDirectory(directory);
|
||||
}
|
||||
|
||||
var file = new UserCommandsFile { Commands = _commands };
|
||||
var json = JsonSerializer.Serialize(file, UserCommandJsonContext.Default.UserCommandsFile);
|
||||
File.WriteAllText(_path, json);
|
||||
}
|
||||
|
||||
private static List<UserCommand> Load(string path)
|
||||
{
|
||||
if (!File.Exists(path))
|
||||
{
|
||||
return [];
|
||||
}
|
||||
|
||||
try
|
||||
{
|
||||
var json = File.ReadAllText(path);
|
||||
var file = JsonSerializer.Deserialize(json, UserCommandJsonContext.Default.UserCommandsFile);
|
||||
return file?.Commands.ToList() ?? [];
|
||||
}
|
||||
catch (JsonException)
|
||||
{
|
||||
// Corrupt file: start empty rather than crashing on startup.
|
||||
return [];
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
using System.Text.Json.Serialization;
|
||||
using CommandForge.Domain;
|
||||
|
||||
namespace CommandForge.Infrastructure.UserCommands;
|
||||
|
||||
/// <summary>Persisted shape of <c>user-commands.json</c>: a schema version plus the user commands.</summary>
|
||||
internal sealed record UserCommandsFile
|
||||
{
|
||||
public int Version { get; init; } = 1;
|
||||
|
||||
public IReadOnlyList<UserCommand> Commands { get; init; } = [];
|
||||
}
|
||||
|
||||
/// <summary>System.Text.Json source-generation context for <c>user-commands.json</c> (camelCase, indented).</summary>
|
||||
[JsonSourceGenerationOptions(
|
||||
PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase,
|
||||
WriteIndented = true,
|
||||
AllowTrailingCommas = true)]
|
||||
[JsonSerializable(typeof(UserCommandsFile))]
|
||||
internal sealed partial class UserCommandJsonContext : JsonSerializerContext;
|
||||
@@ -124,6 +124,9 @@
|
||||
<data name="SidebarRecipes" xml:space="preserve">
|
||||
<value>Recipes</value>
|
||||
</data>
|
||||
<data name="SidebarUserCommands" xml:space="preserve">
|
||||
<value>My commands</value>
|
||||
</data>
|
||||
<data name="SidebarSettings" xml:space="preserve">
|
||||
<value>Settings</value>
|
||||
</data>
|
||||
@@ -1198,6 +1201,49 @@
|
||||
<data name="Recipe_DeleteConfirm" xml:space="preserve">
|
||||
<value>Delete recipe "{0}"?</value>
|
||||
</data>
|
||||
<data name="UserCmd_Warning" xml:space="preserve">
|
||||
<value>These commands are not part of the vetted catalog and always run without administrator rights. You alone are responsible for what they do.</value>
|
||||
</data>
|
||||
<data name="UserCmd_Saved" xml:space="preserve">
|
||||
<value>Saved commands</value>
|
||||
</data>
|
||||
<data name="UserCmd_New" xml:space="preserve">
|
||||
<value>New</value>
|
||||
</data>
|
||||
<data name="UserCmd_Delete" xml:space="preserve">
|
||||
<value>Delete</value>
|
||||
</data>
|
||||
<data name="UserCmd_NameHint" xml:space="preserve">
|
||||
<value>Name</value>
|
||||
</data>
|
||||
<data name="UserCmd_ExecutableHint" xml:space="preserve">
|
||||
<value>Executable (e.g. cmd, powershell)</value>
|
||||
</data>
|
||||
<data name="UserCmd_ArgumentsHint" xml:space="preserve">
|
||||
<value>Arguments</value>
|
||||
</data>
|
||||
<data name="UserCmd_Save" xml:space="preserve">
|
||||
<value>Save</value>
|
||||
</data>
|
||||
<data name="UserCmd_Run" xml:space="preserve">
|
||||
<value>Run</value>
|
||||
</data>
|
||||
<data name="UserCmd_NoCommands" xml:space="preserve">
|
||||
<value>No commands yet.</value>
|
||||
</data>
|
||||
<data name="UserCmd_RunTitle" xml:space="preserve">
|
||||
<value>Run this command?</value>
|
||||
</data>
|
||||
<data name="UserCmd_RunConfirm" xml:space="preserve">
|
||||
<value>This runs WITHOUT administrator rights:
|
||||
|
||||
{0}
|
||||
|
||||
Continue?</value>
|
||||
</data>
|
||||
<data name="UserCmd_DeleteConfirm" xml:space="preserve">
|
||||
<value>Delete "{0}"?</value>
|
||||
</data>
|
||||
<data name="Favorite_Toggle" xml:space="preserve">
|
||||
<value>Toggle favorite</value>
|
||||
</data>
|
||||
|
||||
@@ -124,6 +124,9 @@
|
||||
<data name="SidebarRecipes" xml:space="preserve">
|
||||
<value>Chuỗi lệnh</value>
|
||||
</data>
|
||||
<data name="SidebarUserCommands" xml:space="preserve">
|
||||
<value>Lệnh của tôi</value>
|
||||
</data>
|
||||
<data name="SidebarSettings" xml:space="preserve">
|
||||
<value>Cài đặt</value>
|
||||
</data>
|
||||
@@ -1198,6 +1201,49 @@
|
||||
<data name="Recipe_DeleteConfirm" xml:space="preserve">
|
||||
<value>Xóa chuỗi "{0}"?</value>
|
||||
</data>
|
||||
<data name="UserCmd_Warning" xml:space="preserve">
|
||||
<value>Các lệnh này không thuộc catalog đã kiểm duyệt và luôn chạy KHÔNG có quyền quản trị. Bạn hoàn toàn chịu trách nhiệm về những gì chúng thực hiện.</value>
|
||||
</data>
|
||||
<data name="UserCmd_Saved" xml:space="preserve">
|
||||
<value>Lệnh đã lưu</value>
|
||||
</data>
|
||||
<data name="UserCmd_New" xml:space="preserve">
|
||||
<value>Tạo mới</value>
|
||||
</data>
|
||||
<data name="UserCmd_Delete" xml:space="preserve">
|
||||
<value>Xóa</value>
|
||||
</data>
|
||||
<data name="UserCmd_NameHint" xml:space="preserve">
|
||||
<value>Tên</value>
|
||||
</data>
|
||||
<data name="UserCmd_ExecutableHint" xml:space="preserve">
|
||||
<value>Tệp thực thi (vd cmd, powershell)</value>
|
||||
</data>
|
||||
<data name="UserCmd_ArgumentsHint" xml:space="preserve">
|
||||
<value>Đối số</value>
|
||||
</data>
|
||||
<data name="UserCmd_Save" xml:space="preserve">
|
||||
<value>Lưu</value>
|
||||
</data>
|
||||
<data name="UserCmd_Run" xml:space="preserve">
|
||||
<value>Chạy</value>
|
||||
</data>
|
||||
<data name="UserCmd_NoCommands" xml:space="preserve">
|
||||
<value>Chưa có lệnh nào.</value>
|
||||
</data>
|
||||
<data name="UserCmd_RunTitle" xml:space="preserve">
|
||||
<value>Chạy lệnh này?</value>
|
||||
</data>
|
||||
<data name="UserCmd_RunConfirm" xml:space="preserve">
|
||||
<value>Lệnh này chạy KHÔNG có quyền quản trị:
|
||||
|
||||
{0}
|
||||
|
||||
Tiếp tục?</value>
|
||||
</data>
|
||||
<data name="UserCmd_DeleteConfirm" xml:space="preserve">
|
||||
<value>Xóa "{0}"?</value>
|
||||
</data>
|
||||
<data name="Favorite_Toggle" xml:space="preserve">
|
||||
<value>Bật/tắt yêu thích</value>
|
||||
</data>
|
||||
|
||||
@@ -41,6 +41,7 @@ public sealed partial class MainViewModel : ObservableObject
|
||||
IExecutionHistoryService history,
|
||||
IClock clock,
|
||||
IRecipeStore recipeStore,
|
||||
IUserCommandStore userCommandStore,
|
||||
ISystemInfoService systemInfo,
|
||||
SettingsViewModel settingsViewModel,
|
||||
LogViewerViewModel logViewer,
|
||||
@@ -55,6 +56,7 @@ public sealed partial class MainViewModel : ObservableObject
|
||||
ArgumentNullException.ThrowIfNull(history);
|
||||
ArgumentNullException.ThrowIfNull(clock);
|
||||
ArgumentNullException.ThrowIfNull(recipeStore);
|
||||
ArgumentNullException.ThrowIfNull(userCommandStore);
|
||||
ArgumentNullException.ThrowIfNull(systemInfo);
|
||||
ArgumentNullException.ThrowIfNull(settingsViewModel);
|
||||
ArgumentNullException.ThrowIfNull(logViewer);
|
||||
@@ -97,6 +99,7 @@ public sealed partial class MainViewModel : ObservableObject
|
||||
Home = new HomeViewModel(_itemsById, settings, systemInfo, item => SelectCommandById(item.Command.Id));
|
||||
History = new HistoryViewModel(_itemsById, history, SelectCommandById, RunCommandByIdAsync);
|
||||
Recipes = new RecipesViewModel(_itemsById, execution, recipeStore, history, clock);
|
||||
UserCommands = new UserCommandsViewModel(userCommandStore, execution);
|
||||
|
||||
Categories.Add(new CategoryViewModel(null, "Sidebar_AllCommands", "ViewGridOutline", vms.Items.Count));
|
||||
foreach (var category in catalog.GetCategories())
|
||||
@@ -128,6 +131,9 @@ public sealed partial class MainViewModel : ObservableObject
|
||||
/// <summary>The recipes view-model (shown when <see cref="CurrentSection"/> is Recipes).</summary>
|
||||
public RecipesViewModel Recipes { get; }
|
||||
|
||||
/// <summary>The user-defined commands view-model (shown when <see cref="CurrentSection"/> is UserCommands).</summary>
|
||||
public UserCommandsViewModel UserCommands { get; }
|
||||
|
||||
/// <summary>The Settings screen view-model (shown when <see cref="CurrentSection"/> is Settings).</summary>
|
||||
public SettingsViewModel Settings { get; }
|
||||
|
||||
@@ -199,6 +205,13 @@ public sealed partial class MainViewModel : ObservableObject
|
||||
CurrentSection = ShellSection.Recipes;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void ShowUserCommands()
|
||||
{
|
||||
UserCommands.Refresh();
|
||||
CurrentSection = ShellSection.UserCommands;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void ShowSettings() => CurrentSection = ShellSection.Settings;
|
||||
|
||||
|
||||
@@ -15,6 +15,9 @@ public enum ShellSection
|
||||
/// <summary>The recipes screen (build/run command chains).</summary>
|
||||
Recipes,
|
||||
|
||||
/// <summary>The user-defined commands screen (non-elevated, separate from the catalog).</summary>
|
||||
UserCommands,
|
||||
|
||||
/// <summary>The Settings screen.</summary>
|
||||
Settings,
|
||||
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
using System.Collections.ObjectModel;
|
||||
using System.Globalization;
|
||||
using System.Windows;
|
||||
using CommandForge.Application.Ports;
|
||||
using CommandForge.Application.UserCommands;
|
||||
using CommandForge.Domain;
|
||||
using CommandForge.Wpf.Resources;
|
||||
using CommunityToolkit.Mvvm.ComponentModel;
|
||||
using CommunityToolkit.Mvvm.Input;
|
||||
|
||||
namespace CommandForge.Wpf.ViewModels;
|
||||
|
||||
/// <summary>
|
||||
/// "My commands" screen: create and run user-defined commands. These are kept entirely separate
|
||||
/// from the vetted catalog and ALWAYS run without elevation (golden rule #1) — the run path uses
|
||||
/// <see cref="UserCommandFactory.ToDefinition"/>, which forces RequiresAdmin = false.
|
||||
/// </summary>
|
||||
public sealed partial class UserCommandsViewModel : ObservableObject
|
||||
{
|
||||
private readonly IUserCommandStore _store;
|
||||
private readonly ExecutionViewModel _execution;
|
||||
private string? _editingId;
|
||||
|
||||
public UserCommandsViewModel(IUserCommandStore store, ExecutionViewModel execution)
|
||||
{
|
||||
ArgumentNullException.ThrowIfNull(store);
|
||||
ArgumentNullException.ThrowIfNull(execution);
|
||||
|
||||
_store = store;
|
||||
_execution = execution;
|
||||
|
||||
_execution.PropertyChanged += (_, e) =>
|
||||
{
|
||||
if (e.PropertyName == nameof(ExecutionViewModel.IsRunning))
|
||||
{
|
||||
RunCommand.NotifyCanExecuteChanged();
|
||||
}
|
||||
};
|
||||
|
||||
Refresh();
|
||||
}
|
||||
|
||||
/// <summary>The shared execution view-model — drives the console output panel.</summary>
|
||||
public ExecutionViewModel Execution => _execution;
|
||||
|
||||
/// <summary>Saved user commands.</summary>
|
||||
public ObservableCollection<UserCommand> Commands { get; } = [];
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(DeleteCommand))]
|
||||
private UserCommand? _selectedCommand;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(SaveCommand))]
|
||||
private string _editName = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
[NotifyCanExecuteChangedFor(nameof(SaveCommand))]
|
||||
[NotifyCanExecuteChangedFor(nameof(RunCommand))]
|
||||
private string _editExecutable = string.Empty;
|
||||
|
||||
[ObservableProperty]
|
||||
private string _editArguments = string.Empty;
|
||||
|
||||
/// <summary>Reloads the saved-command list from the store.</summary>
|
||||
public void Refresh()
|
||||
{
|
||||
Commands.Clear();
|
||||
foreach (var command in _store.GetAll())
|
||||
{
|
||||
Commands.Add(command);
|
||||
}
|
||||
}
|
||||
|
||||
partial void OnSelectedCommandChanged(UserCommand? value)
|
||||
{
|
||||
if (value is null)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_editingId = value.Id;
|
||||
EditName = value.Name;
|
||||
EditExecutable = value.Executable;
|
||||
EditArguments = value.Arguments;
|
||||
}
|
||||
|
||||
[RelayCommand]
|
||||
private void New()
|
||||
{
|
||||
SelectedCommand = null;
|
||||
_editingId = null;
|
||||
EditName = string.Empty;
|
||||
EditExecutable = string.Empty;
|
||||
EditArguments = string.Empty;
|
||||
}
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanSave))]
|
||||
private void Save()
|
||||
{
|
||||
var name = EditName.Trim();
|
||||
var executable = EditExecutable.Trim();
|
||||
if (name.Length == 0 || executable.Length == 0)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var id = _editingId ?? Guid.NewGuid().ToString("N");
|
||||
_store.Save(new UserCommand { Id = id, Name = name, Executable = executable, Arguments = EditArguments.Trim() });
|
||||
_editingId = id;
|
||||
Refresh();
|
||||
SelectedCommand = Commands.FirstOrDefault(c => string.Equals(c.Id, id, StringComparison.Ordinal));
|
||||
}
|
||||
|
||||
private bool CanSave() => !string.IsNullOrWhiteSpace(EditName) && !string.IsNullOrWhiteSpace(EditExecutable);
|
||||
|
||||
[RelayCommand(CanExecute = nameof(HasSelected))]
|
||||
private void Delete()
|
||||
{
|
||||
if (SelectedCommand is not { } command)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
if (MessageBox.Show(
|
||||
string.Format(CultureInfo.CurrentCulture, Strings.Get("UserCmd_DeleteConfirm"), command.Name),
|
||||
Strings.Get("UserCmd_Delete"),
|
||||
MessageBoxButton.YesNo,
|
||||
MessageBoxImage.Warning) != MessageBoxResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
_store.Delete(command.Id);
|
||||
New();
|
||||
Refresh();
|
||||
}
|
||||
|
||||
private bool HasSelected() => SelectedCommand is not null;
|
||||
|
||||
[RelayCommand(CanExecute = nameof(CanRun))]
|
||||
private async Task RunAsync()
|
||||
{
|
||||
var executable = EditExecutable.Trim();
|
||||
if (executable.Length == 0 || _execution.IsRunning)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
var userCommand = new UserCommand
|
||||
{
|
||||
Id = _editingId ?? "unsaved",
|
||||
Name = string.IsNullOrWhiteSpace(EditName) ? executable : EditName.Trim(),
|
||||
Executable = executable,
|
||||
Arguments = EditArguments.Trim(),
|
||||
};
|
||||
|
||||
// Transparency (Security.md §3): show the exact command line, and that it runs without admin.
|
||||
var commandLine = string.IsNullOrEmpty(userCommand.Arguments)
|
||||
? executable
|
||||
: executable + " " + userCommand.Arguments;
|
||||
if (MessageBox.Show(
|
||||
string.Format(CultureInfo.CurrentCulture, Strings.Get("UserCmd_RunConfirm"), commandLine),
|
||||
Strings.Get("UserCmd_RunTitle"),
|
||||
MessageBoxButton.YesNo,
|
||||
MessageBoxImage.Warning) != MessageBoxResult.Yes)
|
||||
{
|
||||
return;
|
||||
}
|
||||
|
||||
// SAFETY: ToDefinition forces RequiresAdmin = false → runs asInvoker, never via the broker.
|
||||
await _execution.RunAsync(UserCommandFactory.ToDefinition(userCommand));
|
||||
}
|
||||
|
||||
private bool CanRun() => !string.IsNullOrWhiteSpace(EditExecutable) && !_execution.IsRunning;
|
||||
}
|
||||
@@ -32,6 +32,9 @@
|
||||
<DataTemplate x:Key="RecipesTemplate">
|
||||
<views:RecipesView DataContext="{Binding Recipes}" />
|
||||
</DataTemplate>
|
||||
<DataTemplate x:Key="UserCommandsTemplate">
|
||||
<views:UserCommandsView DataContext="{Binding UserCommands}" />
|
||||
</DataTemplate>
|
||||
<DataTemplate x:Key="SettingsTemplate">
|
||||
<views:SettingsView DataContext="{Binding Settings}" />
|
||||
</DataTemplate>
|
||||
@@ -73,6 +76,7 @@
|
||||
<MenuItem Header="{res:Loc SidebarFavorites}" Command="{Binding ShowFavoritesCommand}" />
|
||||
<MenuItem Header="{res:Loc SidebarHistory}" Command="{Binding ShowHistoryCommand}" />
|
||||
<MenuItem Header="{res:Loc SidebarRecipes}" Command="{Binding ShowRecipesCommand}" />
|
||||
<MenuItem Header="{res:Loc SidebarUserCommands}" Command="{Binding ShowUserCommandsCommand}" />
|
||||
<Separator />
|
||||
<MenuItem Header="{res:Loc Settings_Theme}">
|
||||
<MenuItem Header="{res:Loc Settings_ThemeSystem}" Command="{Binding Settings.SetThemeCommand}"
|
||||
@@ -203,6 +207,16 @@
|
||||
</StackPanel>
|
||||
</Button>
|
||||
|
||||
<Button DockPanel.Dock="Top" Style="{StaticResource SidebarButtonStyle}"
|
||||
Command="{Binding ShowUserCommandsCommand}"
|
||||
AutomationProperties.Name="{res:Loc SidebarUserCommands}"
|
||||
ToolTip="{res:Loc SidebarUserCommands}">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<materialDesign:PackIcon Kind="ScriptTextOutline" Width="22" Height="22" />
|
||||
<TextBlock Text="{res:Loc SidebarUserCommands}" Style="{StaticResource SidebarLabelStyle}" />
|
||||
</StackPanel>
|
||||
</Button>
|
||||
|
||||
<Button DockPanel.Dock="Bottom" Style="{StaticResource SidebarButtonStyle}"
|
||||
Margin="0,0,0,10"
|
||||
Command="{Binding ShowSettingsCommand}"
|
||||
@@ -261,6 +275,9 @@
|
||||
<DataTrigger Binding="{Binding CurrentSection}" Value="Recipes">
|
||||
<Setter Property="ContentTemplate" Value="{StaticResource RecipesTemplate}" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding CurrentSection}" Value="UserCommands">
|
||||
<Setter Property="ContentTemplate" Value="{StaticResource UserCommandsTemplate}" />
|
||||
</DataTrigger>
|
||||
<DataTrigger Binding="{Binding CurrentSection}" Value="Settings">
|
||||
<Setter Property="ContentTemplate" Value="{StaticResource SettingsTemplate}" />
|
||||
</DataTrigger>
|
||||
|
||||
@@ -0,0 +1,157 @@
|
||||
<UserControl x:Class="CommandForge.Wpf.Views.UserCommandsView"
|
||||
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
|
||||
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
|
||||
xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
|
||||
xmlns:res="clr-namespace:CommandForge.Wpf.Resources"
|
||||
xmlns:conv="clr-namespace:CommandForge.Wpf.Converters"
|
||||
xmlns:beh="clr-namespace:CommandForge.Wpf.Behaviors">
|
||||
<UserControl.Resources>
|
||||
<BooleanToVisibilityConverter x:Key="BoolToVis" />
|
||||
<Style x:Key="RowLabel" TargetType="TextBlock">
|
||||
<Setter Property="FontWeight" Value="Medium" />
|
||||
<Setter Property="Margin" Value="0,12,0,4" />
|
||||
</Style>
|
||||
</UserControl.Resources>
|
||||
|
||||
<Grid Margin="16">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<TextBlock Grid.Row="0" Text="{res:Loc SidebarUserCommands}" FontSize="20" FontWeight="Bold"
|
||||
AutomationProperties.HeadingLevel="Level1" />
|
||||
|
||||
<!-- Prominent, always-visible warning: these are untrusted and never elevated. -->
|
||||
<Border Grid.Row="1" Margin="0,8,0,4" CornerRadius="4" Padding="12,8"
|
||||
Background="#33E0884D" BorderBrush="#E0884D" BorderThickness="1">
|
||||
<StackPanel Orientation="Horizontal">
|
||||
<materialDesign:PackIcon Kind="AlertOutline" Width="20" Height="20" VerticalAlignment="Center"
|
||||
Margin="0,0,10,0" Foreground="#E0884D" />
|
||||
<TextBlock Text="{res:Loc UserCmd_Warning}" TextWrapping="Wrap" VerticalAlignment="Center"
|
||||
MaxWidth="820" />
|
||||
</StackPanel>
|
||||
</Border>
|
||||
|
||||
<Grid Grid.Row="2" Margin="0,8,0,0">
|
||||
<Grid.ColumnDefinitions>
|
||||
<ColumnDefinition Width="220" />
|
||||
<ColumnDefinition Width="*" MinWidth="340" />
|
||||
</Grid.ColumnDefinitions>
|
||||
|
||||
<!-- Left: saved commands -->
|
||||
<DockPanel Grid.Column="0" Margin="0,0,12,0">
|
||||
<TextBlock DockPanel.Dock="Top" Text="{res:Loc UserCmd_Saved}" FontWeight="Bold" Margin="0,0,0,8"
|
||||
AutomationProperties.HeadingLevel="Level2" />
|
||||
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" Margin="0,8,0,0">
|
||||
<Button Content="{res:Loc UserCmd_New}" Command="{Binding NewCommand}"
|
||||
Style="{StaticResource MaterialDesignOutlinedButton}" Margin="0,0,8,0"
|
||||
AutomationProperties.Name="{res:Loc UserCmd_New}" />
|
||||
<Button Content="{res:Loc UserCmd_Delete}" Command="{Binding DeleteCommand}"
|
||||
Style="{StaticResource MaterialDesignOutlinedButton}"
|
||||
AutomationProperties.Name="{res:Loc UserCmd_Delete}" />
|
||||
</StackPanel>
|
||||
<Grid>
|
||||
<ListBox ItemsSource="{Binding Commands}" SelectedItem="{Binding SelectedCommand}"
|
||||
DisplayMemberPath="Name" BorderThickness="0" Background="Transparent"
|
||||
AutomationProperties.Name="{res:Loc UserCmd_Saved}" />
|
||||
<TextBlock Text="{res:Loc UserCmd_NoCommands}" Opacity="0.6" Margin="6,8" TextWrapping="Wrap"
|
||||
VerticalAlignment="Top">
|
||||
<TextBlock.Style>
|
||||
<Style TargetType="TextBlock">
|
||||
<Setter Property="Visibility" Value="Collapsed" />
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding Commands.Count}" Value="0">
|
||||
<Setter Property="Visibility" Value="Visible" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</TextBlock.Style>
|
||||
</TextBlock>
|
||||
</Grid>
|
||||
</DockPanel>
|
||||
|
||||
<!-- Right: editor + console -->
|
||||
<Grid Grid.Column="1">
|
||||
<Grid.RowDefinitions>
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="Auto" />
|
||||
<RowDefinition Height="*" />
|
||||
</Grid.RowDefinitions>
|
||||
|
||||
<StackPanel Grid.Row="0">
|
||||
<TextBlock Text="{res:Loc UserCmd_NameHint}" Style="{StaticResource RowLabel}" />
|
||||
<TextBox Text="{Binding EditName, UpdateSourceTrigger=PropertyChanged}"
|
||||
AutomationProperties.Name="{res:Loc UserCmd_NameHint}" />
|
||||
<TextBlock Text="{res:Loc UserCmd_ExecutableHint}" Style="{StaticResource RowLabel}" />
|
||||
<TextBox Text="{Binding EditExecutable, UpdateSourceTrigger=PropertyChanged}"
|
||||
FontFamily="Cascadia Mono, Consolas, Courier New"
|
||||
AutomationProperties.Name="{res:Loc UserCmd_ExecutableHint}" />
|
||||
<TextBlock Text="{res:Loc UserCmd_ArgumentsHint}" Style="{StaticResource RowLabel}" />
|
||||
<TextBox Text="{Binding EditArguments, UpdateSourceTrigger=PropertyChanged}"
|
||||
FontFamily="Cascadia Mono, Consolas, Courier New" TextWrapping="Wrap"
|
||||
AcceptsReturn="False"
|
||||
AutomationProperties.Name="{res:Loc UserCmd_ArgumentsHint}" />
|
||||
</StackPanel>
|
||||
|
||||
<StackPanel Grid.Row="1" Orientation="Horizontal" Margin="0,16,0,0">
|
||||
<Button Content="{res:Loc UserCmd_Save}" Command="{Binding SaveCommand}"
|
||||
Style="{StaticResource MaterialDesignOutlinedButton}" Margin="0,0,8,0"
|
||||
AutomationProperties.Name="{res:Loc UserCmd_Save}" />
|
||||
<Button Content="{res:Loc UserCmd_Run}" Command="{Binding RunCommand}"
|
||||
Style="{StaticResource MaterialDesignRaisedButton}"
|
||||
AutomationProperties.Name="{res:Loc UserCmd_Run}" />
|
||||
</StackPanel>
|
||||
|
||||
<!-- Console + result (shared execution VM) -->
|
||||
<materialDesign:Card Grid.Row="2" Margin="0,12,0,0" Padding="12" MaxHeight="280"
|
||||
VerticalAlignment="Top"
|
||||
Visibility="{Binding Execution.ShowConsole, Converter={StaticResource BoolToVis}}">
|
||||
<DockPanel>
|
||||
<Grid DockPanel.Dock="Top">
|
||||
<TextBlock Text="{res:Loc PaneConsole}" FontWeight="Bold" VerticalAlignment="Center" />
|
||||
<StackPanel Orientation="Horizontal" HorizontalAlignment="Right"
|
||||
Visibility="{Binding Execution.IsRunning, Converter={StaticResource BoolToVis}}">
|
||||
<ProgressBar IsIndeterminate="True" Width="90" Height="4" VerticalAlignment="Center" Margin="0,0,8,0" />
|
||||
<Button Content="{res:Loc Console_Cancel}" Command="{Binding Execution.CancelCommand}"
|
||||
Style="{StaticResource MaterialDesignOutlinedButton}" Padding="8,2" Height="28" MinWidth="0" />
|
||||
</StackPanel>
|
||||
</Grid>
|
||||
|
||||
<StackPanel DockPanel.Dock="Bottom" Orientation="Horizontal" Margin="0,8,0,0"
|
||||
Visibility="{Binding Execution.HasResult, Converter={StaticResource BoolToVis}}">
|
||||
<TextBlock Text="{Binding Execution.StatusText}" FontWeight="Medium" />
|
||||
<TextBlock Text="{res:Loc Result_ExitCode}" Opacity="0.7" Margin="14,0,4,0" />
|
||||
<TextBlock Text="{Binding Execution.ExitCode}" Opacity="0.7" />
|
||||
<TextBlock Text="{Binding Execution.DurationText}" Opacity="0.7" Margin="14,0,0,0" />
|
||||
</StackPanel>
|
||||
|
||||
<Border Background="{DynamicResource MaterialDesignToolBarBackground}" CornerRadius="4" Margin="0,8,0,0">
|
||||
<ScrollViewer beh:AutoScroll.Enabled="True" VerticalScrollBarVisibility="Auto" MaxHeight="180" Padding="8">
|
||||
<ItemsControl ItemsSource="{Binding Execution.OutputLines}">
|
||||
<ItemsControl.ItemTemplate>
|
||||
<DataTemplate>
|
||||
<TextBlock Text="{Binding Text}" TextWrapping="Wrap"
|
||||
FontFamily="Cascadia Mono, Consolas, Courier New" FontSize="12">
|
||||
<TextBlock.Style>
|
||||
<Style TargetType="TextBlock">
|
||||
<Style.Triggers>
|
||||
<DataTrigger Binding="{Binding IsError}" Value="True">
|
||||
<Setter Property="Foreground" Value="#E0884D" />
|
||||
</DataTrigger>
|
||||
</Style.Triggers>
|
||||
</Style>
|
||||
</TextBlock.Style>
|
||||
</TextBlock>
|
||||
</DataTemplate>
|
||||
</ItemsControl.ItemTemplate>
|
||||
</ItemsControl>
|
||||
</ScrollViewer>
|
||||
</Border>
|
||||
</DockPanel>
|
||||
</materialDesign:Card>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</Grid>
|
||||
</UserControl>
|
||||
@@ -0,0 +1,9 @@
|
||||
using System.Windows.Controls;
|
||||
|
||||
namespace CommandForge.Wpf.Views;
|
||||
|
||||
/// <summary>The user-defined commands view (non-elevated, separate from the catalog).</summary>
|
||||
public partial class UserCommandsView : UserControl
|
||||
{
|
||||
public UserCommandsView() => InitializeComponent();
|
||||
}
|
||||
@@ -233,4 +233,28 @@ public sealed class ResxKeyTests
|
||||
Assert.True(vietnamese!.GetString(key) is not null, $"Missing VI resource for key '{key}'.");
|
||||
}
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void UserCommandsUiKeys_ExistInResx_EN_and_VI()
|
||||
{
|
||||
var manager = new ResourceManager("CommandForge.Wpf.Resources.Strings", typeof(Strings).Assembly);
|
||||
var english = manager.GetResourceSet(CultureInfo.InvariantCulture, createIfNotExists: true, tryParents: true);
|
||||
var vietnamese = manager.GetResourceSet(new CultureInfo("vi"), createIfNotExists: true, tryParents: false);
|
||||
|
||||
Assert.NotNull(english);
|
||||
Assert.NotNull(vietnamese);
|
||||
|
||||
string[] keys =
|
||||
[
|
||||
"SidebarUserCommands", "UserCmd_Warning", "UserCmd_Saved", "UserCmd_New", "UserCmd_Delete",
|
||||
"UserCmd_NameHint", "UserCmd_ExecutableHint", "UserCmd_ArgumentsHint", "UserCmd_Save", "UserCmd_Run",
|
||||
"UserCmd_NoCommands", "UserCmd_RunTitle", "UserCmd_RunConfirm", "UserCmd_DeleteConfirm",
|
||||
];
|
||||
|
||||
foreach (var key in keys)
|
||||
{
|
||||
Assert.True(english!.GetString(key) is not null, $"Missing EN resource for key '{key}'.");
|
||||
Assert.True(vietnamese!.GetString(key) is not null, $"Missing VI resource for key '{key}'.");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,103 @@
|
||||
using System.Threading.Channels;
|
||||
using CommandForge.Application.Ports;
|
||||
using CommandForge.Application.UseCases;
|
||||
using CommandForge.Application.UserCommands;
|
||||
using CommandForge.Domain;
|
||||
using CommandForge.Infrastructure.UserCommands;
|
||||
|
||||
namespace CommandForge.Tests;
|
||||
|
||||
/// <summary>
|
||||
/// Safety tests for user-defined commands (golden rule #1): they must never elevate, carry the
|
||||
/// namespaced id (so the Elevator rejects them), and persist locally.
|
||||
/// </summary>
|
||||
public sealed class UserCommandsTests
|
||||
{
|
||||
private static UserCommand Sample(string id = "abc") => new()
|
||||
{
|
||||
Id = id,
|
||||
Name = "My tool",
|
||||
Executable = "cmd",
|
||||
Arguments = "/c echo hi",
|
||||
};
|
||||
|
||||
[Fact]
|
||||
public void ToDefinition_NeverRequiresAdmin()
|
||||
=> Assert.False(UserCommandFactory.ToDefinition(Sample()).RequiresAdmin);
|
||||
|
||||
[Fact]
|
||||
public void ToDefinition_NamespacesId_SoElevatorRejectsIt()
|
||||
{
|
||||
var def = UserCommandFactory.ToDefinition(Sample("abc"));
|
||||
|
||||
Assert.StartsWith(UserCommandFactory.IdPrefix, def.Id, StringComparison.Ordinal);
|
||||
Assert.Equal("user:abc", def.Id);
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public async Task UserCommand_RoutesToExecutor_NotElevation()
|
||||
{
|
||||
var executor = new RecordingExecutor();
|
||||
var elevation = new RecordingElevation();
|
||||
var useCase = new RunCommandUseCase(executor, elevation);
|
||||
|
||||
await useCase.RunAsync(
|
||||
UserCommandFactory.ToDefinition(Sample()),
|
||||
Channel.CreateUnbounded<OutputLine>().Writer);
|
||||
|
||||
Assert.True(executor.Called);
|
||||
Assert.False(elevation.Called); // never elevated
|
||||
}
|
||||
|
||||
[Fact]
|
||||
public void Store_Save_Get_Delete_Persists()
|
||||
{
|
||||
var path = Path.Combine(Path.GetTempPath(), $"cf-usercmd-{Guid.NewGuid():N}.json");
|
||||
try
|
||||
{
|
||||
var store = new JsonUserCommandStore(path);
|
||||
store.Save(Sample("a"));
|
||||
store.Save(Sample("b") with { Name = "Second" });
|
||||
|
||||
Assert.Equal(2, store.GetAll().Count);
|
||||
|
||||
var reloaded = new JsonUserCommandStore(path);
|
||||
Assert.Equal(2, reloaded.GetAll().Count);
|
||||
Assert.Equal("cmd", reloaded.GetAll()[0].Executable);
|
||||
|
||||
reloaded.Delete("a");
|
||||
Assert.Single(reloaded.GetAll());
|
||||
Assert.DoesNotContain(new JsonUserCommandStore(path).GetAll(), c => c.Id == "a");
|
||||
}
|
||||
finally
|
||||
{
|
||||
File.Delete(path);
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class RecordingExecutor : ICommandExecutor
|
||||
{
|
||||
public bool Called { get; private set; }
|
||||
|
||||
public Task<ExecutionResult> ExecuteAsync(CommandDefinition command, ChannelWriter<OutputLine> output, CancellationToken cancellationToken)
|
||||
{
|
||||
Called = true;
|
||||
output.TryComplete();
|
||||
return Task.FromResult(new ExecutionResult { ExitCode = 0, Success = true, Duration = TimeSpan.Zero });
|
||||
}
|
||||
}
|
||||
|
||||
private sealed class RecordingElevation : IElevationService
|
||||
{
|
||||
public bool Called { get; private set; }
|
||||
|
||||
public bool IsElevationAvailable => true;
|
||||
|
||||
public Task<ExecutionResult> RunElevatedAsync(CommandDefinition command, ChannelWriter<OutputLine> output, CancellationToken cancellationToken)
|
||||
{
|
||||
Called = true;
|
||||
output.TryComplete();
|
||||
return Task.FromResult(new ExecutionResult { ExitCode = 0, Success = true, Duration = TimeSpan.Zero });
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user