Skip to content
Merged
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
Original file line number Diff line number Diff line change
Expand Up @@ -20,9 +20,7 @@ public static MauiAppBuilder ConfigureTestBuilder(this MauiAppBuilder mauiAppBui
.OpenUrl((app, url, options) =>
ApplicationModel.Platform.OpenUrl(app, url, options))
.ContinueUserActivity((application, userActivity, completionHandler) =>
ApplicationModel.Platform.ContinueUserActivity(application, userActivity, completionHandler))
.PerformActionForShortcutItem((application, shortcutItem, completionHandler) =>
ApplicationModel.Platform.PerformActionForShortcutItem(application, shortcutItem, completionHandler)));
ApplicationModel.Platform.ContinueUserActivity(application, userActivity, completionHandler)));
#elif WINDOWS
lifecycle
.AddWindows(windows =>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
#nullable enable
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Maui.ApplicationModel;
using Microsoft.Maui.LifecycleEvents;
using UIKit;
using Xunit;

namespace Microsoft.Maui.MauiBlazorWebView.DeviceTests;

[Category("AppActions")]
public class AppActionsHostConfigurationTests : Microsoft.Maui.DeviceTests.ControlsHandlerTestBase
{
[Fact]
public async Task ConfigureTestBuilderDeliversAppActionAndCompletesOnce()
{
await InvokeOnMainThreadAsync(async () =>
{
var lifecycleService = ApplicationServices.GetRequiredService<ILifecycleEventService>();
var forwarder = Assert.Single(
lifecycleService.GetEventDelegates<iOSLifecycle.PerformActionForShortcutItem>(
nameof(iOSLifecycle.PerformActionForShortcutItem)));
var originalShortcutItems = UIApplication.SharedApplication.ShortcutItems;
var activationCount = 0;
var completionCount = 0;
bool? completionResult = null;
string? receivedId = null;
EventHandler<AppActionEventArgs> activated = (_, args) =>
{
activationCount++;
receivedId = args.AppAction.Id;
};
AppActions.OnAppAction += activated;

try
{
await AppActions.SetAsync(new AppAction("configured-host-action", "Configured Host Action"));
var shortcutItems = UIApplication.SharedApplication.ShortcutItems;
Assert.NotNull(shortcutItems);
var shortcutItem = Assert.Single(shortcutItems);

forwarder(
UIApplication.SharedApplication,
shortcutItem,
handled =>
{
completionCount++;
completionResult = handled;
});

Assert.Equal(1, activationCount);
Assert.Equal("configured-host-action", receivedId);
Assert.Equal(1, completionCount);
Assert.Equal(true, completionResult);
}
finally
{
AppActions.OnAppAction -= activated;
UIApplication.SharedApplication.ShortcutItems = originalShortcutItems;
}
});
}
}
6 changes: 5 additions & 1 deletion src/Controls/samples/Controls.Sample/MauiProgram.cs
Original file line number Diff line number Diff line change
Expand Up @@ -277,7 +277,11 @@ static string GetTags(IEnumerable<KeyValuePair<string, object?>> tags) =>
.OnActivated((a) => LogEvent(nameof(iOSLifecycle.OnActivated)))
.OnResignActivation((a) => LogEvent(nameof(iOSLifecycle.OnResignActivation)))
.OpenUrl((a, b, c) => LogEvent(nameof(iOSLifecycle.OpenUrl)) && false)
.PerformActionForShortcutItem((a, b, c) => LogEvent(nameof(iOSLifecycle.PerformActionForShortcutItem)))
.PerformActionForShortcutItem((a, b, completionHandler) =>
{
LogEvent(nameof(iOSLifecycle.PerformActionForShortcutItem));
completionHandler(false);
})
.WillEnterForeground((a) => LogEvent(nameof(iOSLifecycle.WillEnterForeground)))
.ApplicationSignificantTimeChange((a) => LogEvent(nameof(iOSLifecycle.ApplicationSignificantTimeChange)))
.WillTerminate((a) => LogEvent(nameof(iOSLifecycle.WillTerminate))));
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,9 +26,7 @@ public static MauiAppBuilder ConfigureTestBuilder(this MauiAppBuilder mauiAppBui
.OpenUrl((app, url, options) =>
ApplicationModel.Platform.OpenUrl(app, url, options))
.ContinueUserActivity((application, userActivity, completionHandler) =>
ApplicationModel.Platform.ContinueUserActivity(application, userActivity, completionHandler))
.PerformActionForShortcutItem((application, shortcutItem, completionHandler) =>
ApplicationModel.Platform.PerformActionForShortcutItem(application, shortcutItem, completionHandler)));
ApplicationModel.Platform.ContinueUserActivity(application, userActivity, completionHandler)));
#elif WINDOWS
lifecycle
.AddWindows(windows =>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
#nullable enable
using System;
using System.Threading.Tasks;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Maui.ApplicationModel;
using Microsoft.Maui.LifecycleEvents;
using UIKit;
using Xunit;

namespace Microsoft.Maui.DeviceTests
{
[Category("AppActions")]
public class AppActionsHostConfigurationTests : ControlsHandlerTestBase
{
[Fact]
public async Task ConfigureTestBuilderDeliversAppActionAndCompletesOnce()
{
await InvokeOnMainThreadAsync(async () =>
{
var lifecycleService = ApplicationServices.GetRequiredService<ILifecycleEventService>();
var forwarder = Assert.Single(
lifecycleService.GetEventDelegates<iOSLifecycle.PerformActionForShortcutItem>(
nameof(iOSLifecycle.PerformActionForShortcutItem)));
var originalShortcutItems = UIApplication.SharedApplication.ShortcutItems;
var activationCount = 0;
var completionCount = 0;
bool? completionResult = null;
string? receivedId = null;
EventHandler<AppActionEventArgs> activated = (_, args) =>
{
activationCount++;
receivedId = args.AppAction.Id;
};
AppActions.OnAppAction += activated;

try
{
await AppActions.SetAsync(new AppAction("configured-host-action", "Configured Host Action"));
var shortcutItems = UIApplication.SharedApplication.ShortcutItems;
Assert.NotNull(shortcutItems);
var shortcutItem = Assert.Single(shortcutItems);

forwarder(
UIApplication.SharedApplication,
shortcutItem,
handled =>
{
completionCount++;
completionResult = handled;
});

Assert.Equal(1, activationCount);
Assert.Equal("configured-host-action", receivedId);
Assert.Equal(1, completionCount);
Assert.Equal(true, completionResult);
}
finally
{
AppActions.OnAppAction -= activated;
UIApplication.SharedApplication.ShortcutItems = originalShortcutItems;
}
});
}
}
}
34 changes: 31 additions & 3 deletions src/Core/src/Hosting/EssentialsMauiAppBuilderExtensions.cs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@
using Microsoft.Maui.ApplicationModel;
using Microsoft.Maui.ApplicationModel.Communication;
using Microsoft.Maui.ApplicationModel.DataTransfer;
using MauiContacts = Microsoft.Maui.ApplicationModel.Communication.Contacts;
using Microsoft.Maui.Authentication;
using Microsoft.Maui.Devices;
using Microsoft.Maui.Devices.Sensors;
Expand All @@ -17,8 +16,12 @@
using Microsoft.Maui.Media;
using Microsoft.Maui.Networking;
using Microsoft.Maui.Storage;
using MauiContacts = Microsoft.Maui.ApplicationModel.Communication.Contacts;
#if ANDROID
using Android.App;
#elif __IOS__
using System.Linq;
using Foundation;
#endif

namespace Microsoft.Maui.Hosting
Expand Down Expand Up @@ -90,9 +93,12 @@ internal static MauiAppBuilder UseEssentials(this MauiAppBuilder builder)
{
return ApplicationModel.Platform.OpenUrl(application, url, options);
})
.PerformActionForShortcutItem((application, shortcutItem, completionHandler) =>
.SceneOpenUrl((scene, urlContexts) =>
OpenWebAuthenticatorUrls(urlContexts.Select<UIKit.UIOpenUrlContext, NSUrl>(context => context.Url), WebAuthenticator.Default))
.SceneContinueUserActivity((scene, userActivity) =>
{
ApplicationModel.Platform.PerformActionForShortcutItem(application, shortcutItem, completionHandler);
var url = userActivity?.WebPageUrl?.AbsoluteString;
return !string.IsNullOrEmpty(url) && WebAuthenticator.Default.OpenUrl(new Uri(url));
}));
#elif WINDOWS
life.AddWindows(windows => windows
Expand All @@ -110,12 +116,34 @@ internal static MauiAppBuilder UseEssentials(this MauiAppBuilder builder)
}));
#elif TIZEN

#endif

#if IOS || MACCATALYST
life.AddiOS(ios => ios
.PerformActionForShortcutItem((application, shortcutItem, completionHandler) =>
{
ApplicationModel.Platform.PerformActionForShortcutItem(application, shortcutItem, completionHandler);
}));
Comment thread
Copilot marked this conversation as resolved.
Resolved
#endif
});

return builder;
}

#if __IOS__
internal static bool OpenWebAuthenticatorUrls(IEnumerable<NSUrl> urls, IWebAuthenticator webAuthenticator)
{
var wasHandled = false;
foreach (var url in urls)
{
if (url?.AbsoluteString is string absoluteUrl)
wasHandled = webAuthenticator.OpenUrl(new Uri(absoluteUrl)) || wasHandled;
}

return wasHandled;
}
#endif

public static MauiAppBuilder ConfigureEssentials(this MauiAppBuilder builder, Action<IEssentialsBuilder>? configureDelegate = null)
{
if (configureDelegate != null)
Expand Down
97 changes: 97 additions & 0 deletions src/Core/src/LifecycleEvents/LifecycleEventServiceExtensions.cs
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
#nullable enable
using System;
using System.Collections.Generic;
using System.Threading;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;

namespace Microsoft.Maui.LifecycleEvents
{
Expand Down Expand Up @@ -31,6 +33,49 @@ internal static void InvokeLifecycleEvents<TDelegate>(this IServiceProvider serv
action?.Invoke(del);
}

internal static void InvokeLifecycleEventsWithCompletion<TDelegate>(
this IServiceProvider? services,
Action<TDelegate, Action<bool>> invoke,
Action<bool> completionHandler)
where TDelegate : Delegate
{
if (invoke is null)
throw new ArgumentNullException(nameof(invoke));
if (completionHandler is null)
throw new ArgumentNullException(nameof(completionHandler));

var completion = new LifecycleEventCompletion(completionHandler);

try
{
if (services is not null)
{
var delegates = new List<TDelegate>(services.GetLifecycleEventDelegates<TDelegate>());
var logger = delegates.Count > 0
? services.GetService<ILoggerFactory>()?.CreateLogger<LifecycleEventService>()
: null;

for (var i = 0; i < delegates.Count; i++)
invoke(delegates[i], completion.CreateCallback(logger, typeof(TDelegate).Name));
Comment thread
Copilot marked this conversation as resolved.
Resolved

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

🔍 AI-Generated Review (multi-model)

[major] Logic and Correctness — InvokeLifecycleEventsWithCompletion now depends on every registered PerformActionForShortcutItem observer invoking its callback. Concrete failure mode: if any observer returns without calling its callback and no observer reports handled=true, _remaining never reaches zero, so the native shortcut completion is never invoked and scene-based quick-action dispatch can hang indefinitely.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

The all-unhandled + missing-acknowledgement case is real. 35432d159a fixes the concrete repository observer, removes the duplicate forwarders, and explicitly documents the per-registration compatibility contract.

I did not add the proposed arbitrary timeout or treat returning from a void handler as false: a logging-only observer and a legitimate asynchronous handler are indistinguishable at that point. Either fallback can discard a valid delayed true. Existing one-shot aggregation and asynchronous behavior are unchanged. Every registration, including a logging observer, must acknowledge once; unknown/unhandled observers acknowledge false.

This is an explicit limitation, not a claim that arbitrary non-cooperative third-party callbacks now complete automatically: if no registration reports true and one never replies, native completion can remain pending. Dispatch itself is not a blocking wait. The public delegate/builder/scene documentation and migration guidance now state this directly, so maintainers can review the contract without an invented platform deadline.

I also investigated the actual CI failure rather than attributing it to this pending-callback case. Both Release Helix consoles showed ObjectDisposedException from shared dispatcher state. The new completion-test fixture unnecessarily used the full default builder. Locally, the complete Release suite failed 29 tests, while the same assembly excluding that fixture had zero failures. With lifecycle-only useDefaults: false, the complete Debug and Release suites each pass 865 tests, with 3 skipped. The native host regression tests also demonstrate the duplicate registrations before correction and single delivery/completion afterward.

}
}
catch (Exception exception)
{
try
{
completion.Fail();
}
catch (Exception completionException)
{
throw new AggregateException(exception, completionException);
}

throw;
}

completion.CompleteInvocation();
}

internal static IEnumerable<TDelegate> GetLifecycleEventDelegates<TDelegate>(this IServiceProvider services, string? eventName = null)
where TDelegate : Delegate
{
Expand Down Expand Up @@ -60,5 +105,57 @@ internal static bool ContainsLifecycleEvent<TDelegate>(this IServiceProvider ser

return false;
}

sealed class LifecycleEventCompletion
{
Action<bool>? _completionHandler;
// Keep one response pending until every handler invocation has returned successfully.
int _remaining = 1;
int _handled;
int _invocationCompleted;

public LifecycleEventCompletion(Action<bool> completionHandler) =>
_completionHandler = completionHandler;

public Action<bool> CreateCallback(ILogger? logger, string eventName)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

💡 Testing — The "handler never acknowledges and nobody reports true" path is the one documented way to strand native completion, and it has no test.

Flagged by: 3/3 reviewers (converged after dispute; the stronger ❌ framing of this area was discarded)

CreateCallback increments _remaining per registration and Complete only calls Finish when _invocationCompleted != 0 && (wasHandled || remaining == 0). There is deliberately no timeout and no default acknowledgement, which the README documents: "If no handler reports true, an observer that never acknowledges prevents the native warm-action completion from finishing."

The existing tests cover the true short-circuit (AsyncTrueCompletesWithOutstandingHandler…), double-ack, zero handlers, and throw → Fail(). What is not covered is the exact documented failure mode: one handler acknowledges false, a second never acknowledges at all, and Finish is therefore never reached. A test asserting that the native completion is not invoked in that configuration would pin the contract in place.

Why it is worth pinning: this is the discriminating negative case for the new contract. Without it, a future refactor that adds a default-false-on-return or a timeout would pass the whole existing suite while silently changing documented behavior in the opposite direction. The repo's own Regression Prevention dimension calls this out — a new branch needs a test for the input that must not trip it, not only the happy path.

Suggested fix: add a case to LifecycleEventCompletionTests registering two handlers, one replying false and one never replying, asserting the aggregate completion handler is never invoked. Cheap, deterministic, no platform dependency.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Added FalseAndSilentHandlersDoNotCompleteOnReturn in 299fa05175.

It registers the requested pair: the first handler acknowledges false, the second is explicitly verified to run without acknowledging, and the completion count remains zero after the real invocation pass returns. It reuses the lifecycle-only useDefaults: false fixture, with no sleep, timer, or awaited pending task.

I also checked the discriminating negative case: temporarily acknowledging false automatically after each handler returns makes this exact test fail with expected completion count 0, actual 1. The helper was then restored byte-for-byte. The final completion fixture passes 22/22, and the full Core Release suite passes 866 tests, 0 failed, 3 skipped.

The name and assertion deliberately pin non-completion by dispatch return. An immediate deterministic test cannot prove the absence of every possible future timeout, so I have not made that stronger claim or added timing-dependent coverage. No runtime acknowledgement policy changed.

{
Interlocked.Increment(ref _remaining);
var invoked = 0;

return handled =>
{
if (Interlocked.Exchange(ref invoked, 1) != 0)
{
logger?.LogWarning("The {LifecycleEvent} lifecycle event handler invoked its completion callback more than once.", eventName);
return;
}

Complete(handled);
};
}

public void CompleteInvocation()
{
Interlocked.Exchange(ref _invocationCompleted, 1);
Complete(false);
}

void Complete(bool handled)
{
if (handled)
Interlocked.Exchange(ref _handled, 1);

var remaining = Interlocked.Decrement(ref _remaining);
var wasHandled = Volatile.Read(ref _handled) != 0;
if (Volatile.Read(ref _invocationCompleted) != 0 && (wasHandled || remaining == 0))
Finish(wasHandled);
Comment thread
Copilot marked this conversation as resolved.
Resolved
}

public void Fail() =>
Finish(false);

void Finish(bool handled) =>
Interlocked.Exchange(ref _completionHandler, null)?.Invoke(handled);
}
}
}
Loading
Loading