Skip to content

Fix dashboard UI to show no message for cancelled commands #10893

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions src/Aspire.Dashboard/Model/DashboardCommandExecutor.cs
Original file line number Diff line number Diff line change
Expand Up @@ -151,6 +151,15 @@ public async Task ExecuteAsyncCore(ResourceViewModel resource, CommandViewModel
toastParameters.Intent = ToastIntent.Success;
toastParameters.Icon = GetIntentIcon(ToastIntent.Success);
}
else if (response.Kind == ResourceCommandResponseKind.Cancelled)
{
// For cancelled commands, just close the existing toast and don't show any success or error message
if (!toastClosed)
{
toastService.CloseToast(toastParameters.Id);
}
return;
}
else
{
toastParameters.Title = string.Format(CultureInfo.InvariantCulture, loc[nameof(Dashboard.Resources.Resources.ResourceCommandFailed)], messageResourceName, command.GetDisplayName(commandsLoc));
Expand Down
10 changes: 10 additions & 0 deletions src/Aspire.Hosting/ApplicationModel/ResourceCommandAnnotation.cs
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,11 @@ public static class CommandResults
/// <param name="errorMessage">An optional error message.</param>
public static ExecuteCommandResult Failure(string? errorMessage = null) => new() { Success = false, ErrorMessage = errorMessage };

/// <summary>
/// Produces a canceled result.
/// </summary>
public static ExecuteCommandResult Canceled() => new() { Success = false, Canceled = true };

/// <summary>
/// Produces an unsuccessful result from an <see cref="Exception"/>. <see cref="Exception.Message"/> is used as the error message.
/// </summary>
Expand All @@ -147,6 +152,11 @@ public sealed class ExecuteCommandResult
/// </summary>
public required bool Success { get; init; }

/// <summary>
/// A flag that indicates whether the command was canceled by the user.
/// </summary>
public bool Canceled { get; init; }

/// <summary>
/// An optional error message that can be set when the command is unsuccessful.
/// </summary>
Expand Down
26 changes: 22 additions & 4 deletions src/Aspire.Hosting/ApplicationModel/ResourceCommandService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -75,24 +75,37 @@ public async Task<ExecuteCommandResult> ExecuteCommandAsync(IResource resource,
tasks.Add(ExecuteCommandCoreAsync(name, resource, commandName, cancellationToken));
}

// Check for failures.
// Check for failures and cancellations.
var results = await Task.WhenAll(tasks).ConfigureAwait(false);
var failures = new List<(string resourceId, ExecuteCommandResult result)>();
var cancellations = new List<(string resourceId, ExecuteCommandResult result)>();
for (var i = 0; i < results.Length; i++)
{
if (!results[i].Success)
{
failures.Add((names[i], results[i]));
if (results[i].Canceled)
{
cancellations.Add((names[i], results[i]));
}
else
{
failures.Add((names[i], results[i]));
}
}
Comment on lines 84 to 94
Copy link
Preview

Copilot AI Aug 10, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[nitpick] The nested if-else structure could be simplified using pattern matching or early returns to improve readability. Consider restructuring to handle Success, Canceled, and Failed cases more clearly.

Suggested change
if (!results[i].Success)
{
failures.Add((names[i], results[i]));
if (results[i].Canceled)
{
cancellations.Add((names[i], results[i]));
}
else
{
failures.Add((names[i], results[i]));
}
}
var result = results[i];
if (result.Success)
{
// Do nothing, success case
continue;
}
else if (result.Canceled)
{
cancellations.Add((names[i], result));
}
else
{
failures.Add((names[i], result));
}

Copilot uses AI. Check for mistakes.

}

if (failures.Count == 0)
if (failures.Count == 0 && cancellations.Count == 0)
{
return new ExecuteCommandResult { Success = true };
}
else if (failures.Count == 0 && cancellations.Count > 0)
{
// All non-successful commands were cancelled
return new ExecuteCommandResult { Success = false, Canceled = true };
}
else
{
// Aggregate error results together.
// There were actual failures (possibly with some cancellations)
var errorMessage = $"{failures.Count} command executions failed.";
errorMessage += Environment.NewLine + string.Join(Environment.NewLine, failures.Select(f => $"Resource '{f.resourceId}' failed with error message: {f.result.ErrorMessage}"));

Expand Down Expand Up @@ -128,6 +141,11 @@ internal async Task<ExecuteCommandResult> ExecuteCommandCoreAsync(string resourc
logger.LogInformation("Successfully executed command '{CommandName}'.", commandName);
return result;
}
else if (result.Canceled)
{
logger.LogDebug("Command '{CommandName}' was canceled.", commandName);
return result;
}
else
{
logger.LogInformation("Failure executing command '{CommandName}'. Error message: {ErrorMessage}", commandName, result.ErrorMessage);
Expand Down
4 changes: 4 additions & 0 deletions src/Aspire.Hosting/Dashboard/DashboardServiceData.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,10 @@ public void Dispose()
try
{
var result = await _resourceCommandService.ExecuteCommandAsync(resourceId, type, cancellationToken).ConfigureAwait(false);
if (result.Canceled)
{
return (ExecuteCommandResultType.Canceled, result.ErrorMessage);
}
return (result.Success ? ExecuteCommandResultType.Success : ExecuteCommandResultType.Failure, result.ErrorMessage);
}
catch
Expand Down
4 changes: 4 additions & 0 deletions src/Aspire.Hosting/api/Aspire.Hosting.cs
Original file line number Diff line number Diff line change
Expand Up @@ -889,6 +889,8 @@ public partial class CommandOptions

public static partial class CommandResults
{
public static ExecuteCommandResult Canceled() { throw null; }

public static ExecuteCommandResult Failure(System.Exception exception) { throw null; }

public static ExecuteCommandResult Failure(string? errorMessage = null) { throw null; }
Expand Down Expand Up @@ -1387,6 +1389,8 @@ public sealed partial class ExecuteCommandContext

public sealed partial class ExecuteCommandResult
{
public bool Canceled { get { throw null; } init { } }

public string? ErrorMessage { get { throw null; } init { } }

public required bool Success { get { throw null; } init { } }
Expand Down
106 changes: 106 additions & 0 deletions tests/Aspire.Hosting.Tests/ResourceCommandServiceTests.cs
Original file line number Diff line number Diff line change
Expand Up @@ -188,6 +188,112 @@ 2 command executions failed.
""", result.ErrorMessage);
}

[Fact]
public async Task ExecuteCommandAsync_Canceled_Success()
{
// Arrange
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);

var custom = builder.AddResource(new CustomResource("myResource"));
custom.WithCommand(name: "mycommand",
displayName: "My command",
executeCommand: e =>
{
return Task.FromResult(CommandResults.Canceled());
});

var app = builder.Build();
await app.StartAsync();

// Act
var result = await app.ResourceCommands.ExecuteCommandAsync(custom.Resource, "mycommand");

// Assert
Assert.False(result.Success);
Assert.True(result.Canceled);
Assert.Null(result.ErrorMessage);
}

[Fact]
public async Task ExecuteCommandAsync_HasReplicas_Canceled_CalledPerReplica()
{
// Arrange
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);

var resourceBuilder = builder.AddProject<Projects.ServiceA>("servicea")
.WithReplicas(2)
.WithCommand(name: "mycommand",
displayName: "My command",
executeCommand: e =>
{
return Task.FromResult(CommandResults.Canceled());
});

// Act
var app = builder.Build();
await app.StartAsync();
await app.ResourceNotifications.WaitForResourceHealthyAsync("servicea").DefaultTimeout(TestConstants.LongTimeoutTimeSpan);

var result = await app.ResourceCommands.ExecuteCommandAsync(resourceBuilder.Resource, "mycommand");

// Assert
Assert.False(result.Success);
Assert.True(result.Canceled);
Assert.Null(result.ErrorMessage);
}

[Fact]
public async Task ExecuteCommandAsync_HasReplicas_MixedFailureAndCanceled_OnlyFailuresInErrorMessage()
{
// Arrange
using var builder = TestDistributedApplicationBuilder.Create(testOutputHelper);

var callCount = 0;
var resourceBuilder = builder.AddProject<Projects.ServiceA>("servicea")
.WithReplicas(3)
.WithCommand(name: "mycommand",
displayName: "My command",
executeCommand: e =>
{
var count = Interlocked.Increment(ref callCount);
return Task.FromResult(count switch
{
1 => CommandResults.Failure("Failure!"),
2 => CommandResults.Canceled(),
_ => CommandResults.Success()
});
});

// Act
var app = builder.Build();
await app.StartAsync();
await app.ResourceNotifications.WaitForResourceHealthyAsync("servicea").DefaultTimeout(TestConstants.LongTimeoutTimeSpan);

var result = await app.ResourceCommands.ExecuteCommandAsync(resourceBuilder.Resource, "mycommand");

// Assert
Assert.False(result.Success);
Assert.False(result.Canceled); // Should not be canceled since there was at least one failure

var resourceNames = resourceBuilder.Resource.GetResolvedResourceNames();
Assert.Equal($"""
1 command executions failed.
Resource '{resourceNames[0]}' failed with error message: Failure!
""", result.ErrorMessage);
}

[Fact]
public void CommandResults_Canceled_ProducesCorrectResult()
{
// Act
var result = CommandResults.Canceled();

// Assert
Assert.False(result.Success);
Assert.True(result.Canceled);
Assert.Null(result.ErrorMessage);
}

private sealed class CustomResource(string name) : Resource(name), IResourceWithEndpoints, IResourceWithWaitSupport
{

Expand Down
Loading