Skip to content

fix(Swal): handle concurrent modal actions - #8777

Merged
ArgoZhang merged 6 commits into
mainfrom
fix-swal
Nov 17, 2026
Merged

ArgoZhang merged 6 commits into
mainfrom
fix-swal

Conversation

@ArgoZhang

@ArgoZhang ArgoZhang commented Nov 17, 2026 •

Copy link
Copy Markdown
Member

Link issues

fixes #8776

Summary By Copilot

  • Return false when ShowModal is ignored because a SweetAlert is already active, including requests with a missing or previously-used confirmation context.
  • Prevent repeated close/confirm actions from executing their asynchronous callback more than once.
  • Add focused tests for true/false modal results, ignored requests, and the concurrent-action guard in SweetAlertBody.

Regression?

  • Yes
  • No

No known regression; the changes are limited to SweetAlert modal request and action handling.

Risk

  • High
  • Medium
  • Low

The changes coordinate confirmation contexts and asynchronous callbacks when modal requests or actions overlap.

Verification

  • Manual (required)

  • Automated

  • dotnet test test/UnitTest/UnitTest.csproj --no-restore --filter "FullyQualifiedName~UnitTest.Components.SwalTest.ShowModal_" — passed (3 tests).

  • dotnet test test/UnitTest/UnitTest.csproj --no-restore --filter "FullyQualifiedName~UnitTest.Components.SwalTest.CloseAsync_IgnoresConcurrentCall_Ok" — passed (1 test).

  • git diff --check origin/main...HEAD — passed.

  • Manual browser validation was not run.

Packaging changes reviewed?

  • Yes
  • No
  • N/A

☑️ Self Check before Merge

⚠️ Please check all items below before review. ⚠️

  • Doc is updated/provided or not needed
  • Demo is updated/provided or not needed
  • Merge the latest code from the main branch

Summary by Sourcery

Harden SweetAlert modal and action handling against concurrent requests and repeated user actions.

Bug Fixes:

  • Ensure concurrent SweetAlert modal requests are rejected with a false result without disturbing the active modal.
  • Prevent repeated close or confirm actions from invoking asynchronous callbacks more than once.

Enhancements:

  • Preserve modal confirmation state while coordinating accepted and ignored requests.

Tests:

  • Add coverage for modal confirmation results, ignored concurrent requests, and duplicate action prevention.

@sourcery-ai

sourcery-ai Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

Implementation

Guard SweetAlert close and confirm actions so overlapping calls do not rerun the callback, while still closing the modal after the action completes.

  • src/BootstrapBlazor/Components/SweetAlert/SweetAlertBody.razor.cs L177-211

Make ShowModal detect when a request was ignored by comparing confirmation contexts, return false in that case, and restore the option’s original IsConfirm value.

  • src/BootstrapBlazor/Extensions/SwalExtensions.cs L17-18, L25-39

Tests

Cover modal confirmation results, ignored requests while another alert is active, and suppression of concurrent confirm actions.

  • test/UnitTest/Components/SwalTest.cs L10-118

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@bb-auto bb-auto Bot added the bug Something isn't working label Nov 17, 2026

@bb-auto bb-auto Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Auto approved by bb-auto

@bb-auto bb-auto Bot added this to the v11.1.0 milestone Nov 17, 2026
@ArgoZhang
ArgoZhang merged commit 61ffc1e into main Nov 17, 2026
5 checks passed
@ArgoZhang
ArgoZhang deleted the fix-swal branch November 17, 2026 13:06
@codecov

codecov Bot commented Nov 17, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 100.00%. Comparing base (9409b12) to head (f884b22).
⚠️ Report is 1 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff            @@
##              main     #8777   +/-   ##
=========================================
  Coverage   100.00%   100.00%           
=========================================
  Files          663       663           
  Lines        30364     30377   +13     
=========================================
+ Hits         30364     30377   +13     
Flag Coverage Δ
BB 100.00% <100.00%> (?)

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

@sourcery-ai

sourcery-ai Bot commented Nov 17, 2026

Copy link
Copy Markdown
Contributor

Linked issues

Checked at commit f884b22

#8776 bug(Swal): handle concurrent modal requests and actions · 3 of 3 met

# Requirement Status Notes
1 Return false for an ignored modal request, including when its confirmation context is missing or stale, without changing the active popup. ✅ Met ShowModal compares the captured context with the option’s previous context and returns false when the request did not receive a new context.
2 Invoke each close or confirm callback at most once when actions are repeated while an asynchronous callback is pending. ✅ Met CloseAsync rejects concurrent calls with _isClosing and uses _actionCompleted to avoid invoking the callback again.
3 Return the active modal’s own confirmation result. ✅ Met ShowModal awaits the confirmation task from the context captured for that request.

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Hey - I've found 4 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="src/BootstrapBlazor/Components/SweetAlert/SweetAlertBody.razor.cs" line_range="199-201" />
<code_context>
+            {
+                if (callback != null)
+                {
+                    await callback();
+                }
+                _actionCompleted = true;
+            }
+
</code_context>
<issue_to_address>
**Callbacks repeat after exceptions**

When a close or confirm callback performs a side effect and then throws, and the user retries the action, `CloseAsync` leaves `_actionCompleted` false and resets `_isClosing`, so a later click invokes the callback again and repeats the side effect.

Prevent the callback from being invoked again after it has performed a side effect and thrown.
</issue_to_address>

### Comment 2
<location path="src/BootstrapBlazor/Components/SweetAlert/SweetAlertBody.razor.cs" line_range="201" />
<code_context>
+                {
+                    await callback();
+                }
+                _actionCompleted = true;
+            }
+
</code_context>
<issue_to_address>
**Auto-hide bypasses action guard**

When an auto-hide timer expires while a user-triggered close callback is in progress, the auto-hide path invokes `option.OnCloseAsync` directly while the button path invokes it through `CloseAsync`; if the timer expires while a close-button callback is running, both paths execute the callback and duplicate its side effects.

Route auto-hide through the same shared once-only close-action guard as button-triggered closes.
</issue_to_address>

### Comment 3
<location path="test/UnitTest/Components/SwalTest.cs" line_range="30" />
<code_context>
+
+        var modal = cut.FindComponents<Modal>().Last();
+        await cut.InvokeAsync(() => cut.Find(expected ? ".btn-danger" : ".btn-secondary").Click());
+        await cut.InvokeAsync(() => modal.Instance.CloseCallback());
+
+        Assert.Equal(expected, await modalTask);
</code_context>
<issue_to_address>
**Cancel result passes without canceling**

When the secondary-button handler fails to set the confirmation value and the modal is still closed, in `ShowModal_ReturnsConfirmationResult_Ok(false)`, the assertion at `SwalTest.cs:32` still passes if the secondary-button handler never writes `false`: line 30 calls `CloseCallback` directly, which resolves the task from the default-false `SweetContext.Value`, so the broken cancel action is reported as successful.

Make the cancellation case fail unless the secondary-button handler ran, for example by asserting an observable callback side effect before invoking `CloseCallback`.
</issue_to_address>

### Comment 4
<location path="test/UnitTest/Components/SwalTest.cs" line_range="10-118" />
<code_context>

 public class SwalTest : BootstrapBlazorTestBase
 {
+    [Theory]
+    [InlineData(true)]
+    [InlineData(false)]
+    public async Task ShowModal_ReturnsConfirmationResult_Ok(bool expected)
+    {
+        var cut = Context.Render<BootstrapBlazorRoot>(pb =>
+        {
+            pb.AddChildContent<MockSwalTest>();
+        });
+        var swal = cut.FindComponent<MockSwalTest>().Instance.SwalService;
+        var option = new SwalOption();
+        var modalTask = Task.FromResult(false);
+
+        await cut.InvokeAsync(() =>
+        {
</code_context>
<issue_to_address>
**Unrequested unit tests were added**

When the defect-fix task does not explicitly request new unit tests, `SwalTest` adds three unit tests even though no request to add tests was made, contrary to the repository’s default for defect fixes.

Remove the newly added unit tests unless adding tests is explicitly requested.
</issue_to_address>

Sourcery assessment

Approval pending. 3 findings to address first.

Blocking findings: src/BootstrapBlazor/Components/SweetAlert/SweetAlertBody.razor.cs:201, src/BootstrapBlazor/Components/SweetAlert/SweetAlertBody.razor.cs:201, test/UnitTest/Components/SwalTest.cs:30


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment on lines +199 to +201
await callback();
}
_actionCompleted = true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Medium · Callbacks repeat after exceptions

When a close or confirm callback performs a side effect and then throws, and the user retries the action, CloseAsync leaves _actionCompleted false and resets _isClosing, so a later click invokes the callback again and repeats the side effect.

Prevent the callback from being invoked again after it has performed a side effect and thrown.

Prompt for AI agents
In `src/BootstrapBlazor/Components/SweetAlert/SweetAlertBody.razor.cs` at lines 199-201:

**Callbacks repeat after exceptions**

When a close or confirm callback performs a side effect and then throws, and the user retries the action, `CloseAsync` leaves `_actionCompleted` false and resets `_isClosing`, so a later click invokes the callback again and repeats the side effect.

Prevent the callback from being invoked again after it has performed a side effect and thrown.

{
await callback();
}
_actionCompleted = true;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Medium · Auto-hide bypasses action guard

When an auto-hide timer expires while a user-triggered close callback is in progress, the auto-hide path invokes option.OnCloseAsync directly while the button path invokes it through CloseAsync; if the timer expires while a close-button callback is running, both paths execute the callback and duplicate its side effects.

Route auto-hide through the same shared once-only close-action guard as button-triggered closes.

Prompt for AI agents
In `src/BootstrapBlazor/Components/SweetAlert/SweetAlertBody.razor.cs` at line 201:

**Auto-hide bypasses action guard**

When an auto-hide timer expires while a user-triggered close callback is in progress, the auto-hide path invokes `option.OnCloseAsync` directly while the button path invokes it through `CloseAsync`; if the timer expires while a close-button callback is running, both paths execute the callback and duplicate its side effects.

Route auto-hide through the same shared once-only close-action guard as button-triggered closes.


var modal = cut.FindComponents<Modal>().Last();
await cut.InvokeAsync(() => cut.Find(expected ? ".btn-danger" : ".btn-secondary").Click());
await cut.InvokeAsync(() => modal.Instance.CloseCallback());

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Medium · Cancel result passes without canceling

When the secondary-button handler fails to set the confirmation value and the modal is still closed, in ShowModal_ReturnsConfirmationResult_Ok(false), the assertion at SwalTest.cs:32 still passes if the secondary-button handler never writes false: line 30 calls CloseCallback directly, which resolves the task from the default-false SweetContext.Value, so the broken cancel action is reported as successful.

Make the cancellation case fail unless the secondary-button handler ran, for example by asserting an observable callback side effect before invoking CloseCallback.

Prompt for AI agents
In `test/UnitTest/Components/SwalTest.cs` at line 30:

**Cancel result passes without canceling**

When the secondary-button handler fails to set the confirmation value and the modal is still closed, in `ShowModal_ReturnsConfirmationResult_Ok(false)`, the assertion at `SwalTest.cs:32` still passes if the secondary-button handler never writes `false`: line 30 calls `CloseCallback` directly, which resolves the task from the default-false `SweetContext.Value`, so the broken cancel action is reported as successful.

Make the cancellation case fail unless the secondary-button handler ran, for example by asserting an observable callback side effect before invoking `CloseCallback`.

Comment on lines +10 to +118
[Theory]
[InlineData(true)]
[InlineData(false)]
public async Task ShowModal_ReturnsConfirmationResult_Ok(bool expected)
{
var cut = Context.Render<BootstrapBlazorRoot>(pb =>
{
pb.AddChildContent<MockSwalTest>();
});
var swal = cut.FindComponent<MockSwalTest>().Instance.SwalService;
var option = new SwalOption();
var modalTask = Task.FromResult(false);

await cut.InvokeAsync(() =>
{
modalTask = swal.ShowModal(option);
});

var modal = cut.FindComponents<Modal>().Last();
await cut.InvokeAsync(() => cut.Find(expected ? ".btn-danger" : ".btn-secondary").Click());
await cut.InvokeAsync(() => modal.Instance.CloseCallback());

Assert.Equal(expected, await modalTask);
Assert.True(option.IsConfirm);
}

[Fact]
public async Task ShowModal_IgnoresRequestsWhileBusy_Ok()
{
var cut = Context.Render<BootstrapBlazorRoot>(pb =>
{
pb.AddChildContent<MockSwalTest>();
});
var swal = cut.FindComponent<MockSwalTest>().Instance.SwalService;
var option = new SwalOption()
{
Content = "Active Swal"
};
var modalTask = Task.FromResult(false);

await cut.InvokeAsync(() =>
{
modalTask = swal.ShowModal(option);
});

var newOption = new SwalOption()
{
Content = "Ignored Swal"
};
var newRequestTask = Task.FromResult(true);
await cut.InvokeAsync(() =>
{
newRequestTask = swal.ShowModal(newOption);
});

Assert.False(await newRequestTask);
Assert.False(newOption.IsConfirm);

var repeatedRequestTask = Task.FromResult(true);
await cut.InvokeAsync(() =>
{
repeatedRequestTask = swal.ShowModal(option);
});

Assert.False(await repeatedRequestTask);
Assert.True(option.IsConfirm);
Assert.Contains("Active Swal", cut.Markup);
Assert.DoesNotContain("Ignored Swal", cut.Markup);

var modal = cut.FindComponents<Modal>().Last();
await cut.InvokeAsync(() => cut.Find(".btn-danger").Click());
await cut.InvokeAsync(() => modal.Instance.CloseCallback());

Assert.True(await modalTask);
}

[Fact]
public async Task CloseAsync_IgnoresConcurrentCall_Ok()
{
var callbackStarted = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var continueCallback = new TaskCompletionSource(TaskCreationOptions.RunContinuationsAsynchronously);
var callbackCount = 0;
var cut = Context.Render<SweetAlertBody>(pb =>
{
pb.Add(a => a.IsConfirm, true);
pb.Add(a => a.OnConfirmAsync, async () =>
{
callbackCount++;
callbackStarted.TrySetResult();
await continueCallback.Task;
});
});

var firstClick = cut.InvokeAsync(() => cut.Find(".btn-danger").Click());
try
{
await callbackStarted.Task.WaitAsync(TimeSpan.FromSeconds(5), TestContext.Current.CancellationToken);
await cut.InvokeAsync(() => cut.Find(".btn-danger").Click());

Assert.Equal(1, callbackCount);
}
finally
{
continueCallback.TrySetResult();
}

await firstClick;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚪ Low · Unrequested unit tests were added

When the defect-fix task does not explicitly request new unit tests, SwalTest adds three unit tests even though no request to add tests was made, contrary to the repository’s default for defect fixes.

Remove the newly added unit tests unless adding tests is explicitly requested.

Prompt for AI agents
In `test/UnitTest/Components/SwalTest.cs` at lines 10-118:

**Unrequested unit tests were added**

When the defect-fix task does not explicitly request new unit tests, `SwalTest` adds three unit tests even though no request to add tests was made, contrary to the repository’s default for defect fixes.

Remove the newly added unit tests unless adding tests is explicitly requested.

From .github/copilot-instructions.md L10:

普通功能开发、缺陷修复等任务,默认不新增、修改或运行单元测试,除非用户明确要求

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

bug Something isn't working

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(Swal): handle concurrent modal requests and actions

1 participant