Skip to content
Merged
Show file tree
Hide file tree
Changes from 4 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
@@ -1 +1,11 @@
#nullable enable
Microsoft.Testing.Extensions.PackagedApp.PackageDeployer
Microsoft.Testing.Extensions.PackagedApp.PackageRegistrationLock
Microsoft.Testing.Extensions.PackagedApp.RegisteredPackageInfo
Microsoft.Testing.Extensions.PackagedApp.RegisteredPackageInfo.FullName.get -> string!
Microsoft.Testing.Extensions.PackagedApp.RegisteredPackageInfo.InstalledPath.get -> string!
Microsoft.Testing.Extensions.PackagedApp.RegisteredPackageInfo.IsDevelopmentMode.get -> bool
Microsoft.Testing.Extensions.PackagedApp.RegisteredPackageInfo.RegisteredPackageInfo(string! fullName, string! installedPath, bool isDevelopmentMode) -> void
static Microsoft.Testing.Extensions.PackagedApp.PackageDeployer.RegisterAsync(string! manifestPath, System.Func<System.Threading.CancellationToken, System.Threading.Tasks.Task!>! registerPackage, System.Func<System.Collections.Generic.IReadOnlyList<Microsoft.Testing.Extensions.PackagedApp.RegisteredPackageInfo!>!>! findRegisteredPackages, System.Func<string!, System.Threading.CancellationToken, System.Threading.Tasks.Task<bool>!>! removeDevelopmentPackage, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task!
static Microsoft.Testing.Extensions.PackagedApp.PackageRegistrationLock.AcquireAsync(string! packageFamilyName, string! lockDirectory, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.IO.FileStream!>!
static Microsoft.Testing.Extensions.PackagedApp.PackageRegistrationLock.AcquireAsync(string! packageFamilyName, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task<System.IO.FileStream!>!
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,5 @@ Microsoft.Testing.Extensions.PackagedApp.ActivatedAppTestHostHandle.Terminate()
Microsoft.Testing.Extensions.PackagedApp.ActivatedAppTestHostHandle.WaitForExitAsync(System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task!
Microsoft.Testing.Extensions.PackagedApp.Interop.ApplicationActivationManager
static Microsoft.Testing.Extensions.PackagedApp.Interop.ApplicationActivationManager.ActivateApplication(string! appUserModelId, string? arguments) -> uint
Microsoft.Testing.Extensions.PackagedApp.PackageDeployer
static Microsoft.Testing.Extensions.PackagedApp.PackageDeployer.Activate(string! appUserModelId, string? activationArguments) -> uint
static Microsoft.Testing.Extensions.PackagedApp.PackageDeployer.RegisterAsync(string! manifestPath, System.Threading.CancellationToken cancellationToken) -> System.Threading.Tasks.Task!
10 changes: 10 additions & 0 deletions src/Platform/Microsoft.Testing.Extensions.PackagedApp/PACKAGE.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,16 @@ It is the consumer of the platform's `ITestHostLauncher` extension point for Win
- **Packaged AUMID activation** (Windows build): a packaged (MSIX) layout is registered in place with the `PackageManager` and the app is activated by AUMID via `IApplicationActivationManager`. `packagedClassicApp`/`win32App` hosts receive the platform-prepared command line through `argv`, including when their trust level is `appContainer`. `windowsApp`/UWP hosts receive one opaque launch string and restore the exact logical argument array through `PackagedAppExtensions.GetTestApplicationArguments(args.Arguments)` in `Application.OnLaunched` (see [#10485](https://github.com/microsoft/testfx/issues/10485)). Registering an unsigned build-output layout requires Developer Mode (or sideloading). The plain `net8.0`/`net9.0` build rejects a packaged layout with an actionable error pointing at the Windows TFM.
- **Deploy + launch loose layout** (opt-in): a non-packaged app — one without an `AppxManifest.xml` — is deployed to a deployment directory and the produced executable is launched from there.

## Switching packaged build layouts

Before activation, the launcher verifies that the current user's main package registration points to the directory containing the requested `AppxManifest.xml`. Windows can report registration success while retaining a different layout with the same package identity and version. In that case, the launcher removes only the stale **development registration**, using `PreserveApplicationData`, and registers the requested layout again. Repeated runs from the same layout do not remove its registration.

Launchers serialize the entire registration-and-activation sequence per user and package family, including across processes. Another launcher cannot switch the layout between verification and AUMID activation. Waiting for another launch respects cancellation.

If cancellation is observed before stale-registration removal starts, no destructive change is made. Once removal completes, the launcher finishes registering and verifying the replacement before it surfaces cancellation, so an interrupted run does not intentionally leave the package unregistered.

If the conflicting package is not a development registration, removal does not actually unregister it, or the requested location still cannot be registered, the launcher reports an error instead of activating another build. A failed replacement can leave the package unregistered, but its application data is retained; resolve the reported deployment error and retry. Callers do not need to uninstall their app or change its version for each build.

## When the launcher takes over

Registering an *enabled* test host launcher switches the run to the test host controller (process restart) model, because a launcher only has an effect when an out-of-process test host is started. To avoid charging that cost to apps that do not need it, the launcher enables itself only when it has real work to do:
Expand Down
166 changes: 135 additions & 31 deletions src/Platform/Microsoft.Testing.Extensions.PackagedApp/PackageDeployer.cs
Original file line number Diff line number Diff line change
@@ -1,37 +1,42 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

#if PACKAGEDAPP_WINRT
using Microsoft.Testing.Extensions.PackagedApp.Resources;

#if PACKAGEDAPP_WINRT
using Microsoft.Testing.Extensions.PackagedApp.Interop;
using Microsoft.Testing.Extensions.PackagedApp.Resources;

using Windows.Management.Deployment;
#endif

namespace Microsoft.Testing.Extensions.PackagedApp;

/// <summary>
/// Registers a packaged (MSIX) loose layout with the OS and activates it by Application User Model ID,
/// using only public, redistributable Windows APIs — the <see cref="PackageManager"/> WinRT class for
/// registration and <see cref="ApplicationActivationManager"/> for activation. This is the equivalent
/// using only public, redistributable Windows APIs — the <c>PackageManager</c> WinRT class for
/// registration and <c>ApplicationActivationManager</c> for activation. This is the equivalent
/// of the Visual-Studio-internal deployment components VSTest relies on, implemented without them.
/// Callers that activate the app must hold a <see cref="PackageRegistrationLock"/> lease across
/// registration and activation.
/// </summary>
[SupportedOSPlatform("windows10.0.19041.0")]
internal static class PackageDeployer
{
#if PACKAGEDAPP_WINRT
/// <summary>
/// Registers the loose layout described by <paramref name="manifestPath"/> in place (no copy) and
/// prepares its package-owned storage before any activation handoffs are written.
/// verifies its registered location before any activation handoffs are written.
/// </summary>
/// <param name="manifestPath">The full path to the layout's <c>AppxManifest.xml</c>.</param>
/// <param name="cancellationToken">A token to observe while registering.</param>
public static async Task RegisterAsync(
[SupportedOSPlatform("windows10.0.19041.0")]
public static Task RegisterAsync(
string manifestPath,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

var packageManager = new PackageManager();
string packageFamilyName = AppxManifestInfo.ReadFromManifest(manifestPath).PackageFamilyName;
Comment thread
Sergio0694 marked this conversation as resolved.
Resolved

// DeveloperMode registers the unsigned build-output layout in place. It requires Developer Mode
// (or sideloading) to be enabled on the machine, exactly like 'Add-AppxPackage -Register'.
Expand All @@ -40,13 +45,116 @@ public static async Task RegisterAsync(
DeveloperMode = true,
};

DeploymentResult result;
return RegisterAsync(
manifestPath,
async token =>
{
token.ThrowIfCancellationRequested();
// Windows deployment requests are not safely interruptible once started. Await the
// underlying operation so the registration lock covers every shared-state mutation.
DeploymentResult result = await packageManager
.RegisterPackageByUriAsync(new Uri(manifestPath), options)
.AsTask()
.ConfigureAwait(false);
token.ThrowIfCancellationRequested();

// IsRegistered is authoritative for registration; ExtendedErrorCode can be informational.
if (!result.IsRegistered)
{
throw new InvalidOperationException(result.ErrorText, result.ExtendedErrorCode);
}
},
() => packageManager
.FindPackagesForUserWithPackageTypes(string.Empty, packageFamilyName, PackageTypes.Main)
.Select(static package => new RegisteredPackageInfo(package.Id.FullName, package.InstalledPath, package.IsDevelopmentMode))
.ToArray(),
async (packageFullName, token) =>
{
token.ThrowIfCancellationRequested();
// Keep the lease until removal actually finishes; cancellation is handled by the
// transaction below, which restores a usable registration before surfacing it.
DeploymentResult result = await packageManager
.RemovePackageAsync(packageFullName, RemovalOptions.PreserveApplicationData)
.AsTask()
.ConfigureAwait(false);

return result.ExtendedErrorCode is { HResult: < 0 }
? throw new InvalidOperationException(result.ErrorText, result.ExtendedErrorCode)
: !result.IsRegistered;
},
cancellationToken);
}

/// <summary>Activates a registered packaged app and returns its process id.</summary>
[SupportedOSPlatform("windows10.0.19041.0")]
public static uint Activate(string appUserModelId, string? activationArguments)
=> ApplicationActivationManager.ActivateApplication(appUserModelId, activationArguments);
#endif

internal static async Task RegisterAsync(
string manifestPath,
Func<CancellationToken, Task> registerPackage,
Func<IReadOnlyList<RegisteredPackageInfo>> findRegisteredPackages,
Func<string, CancellationToken, Task<bool>> removeDevelopmentPackage,
CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

try
{
result = await packageManager
.RegisterPackageByUriAsync(new Uri(manifestPath), options)
.AsTask(cancellationToken)
.ConfigureAwait(false);
string layoutDirectory = Path.GetDirectoryName(Path.GetFullPath(manifestPath))!;

await registerPackage(cancellationToken).ConfigureAwait(false);
cancellationToken.ThrowIfCancellationRequested();
IReadOnlyList<RegisteredPackageInfo> packages = findRegisteredPackages();
cancellationToken.ThrowIfCancellationRequested();

if (!IsRegisteredFromLayout(packages, layoutDirectory))
{
if (packages.Count != 1)
{
throw CreateLocationMismatchException(layoutDirectory, packages);
}

RegisteredPackageInfo previousPackage = packages[0];
if (!previousPackage.IsDevelopmentMode)
{
throw new InvalidOperationException(
string.Format(
CultureInfo.CurrentCulture,
ExtensionResources.PackagedAppRegistrationNotDevelopment,
previousPackage.FullName,
previousPackage.InstalledPath,
layoutDirectory));
}

// A successful same-version registration can retain the old layout. Only development
// registrations support removal with PreserveApplicationData; never uninstall a retail app.
cancellationToken.ThrowIfCancellationRequested();
bool removed = await removeDevelopmentPackage(previousPackage.FullName, cancellationToken).ConfigureAwait(false);
if (!removed)
{
throw new InvalidOperationException(
string.Format(
CultureInfo.CurrentCulture,
ExtensionResources.PackagedAppRegistrationRemovalIncomplete,
previousPackage.FullName,
previousPackage.InstalledPath,
layoutDirectory));
}

// Once the previous registration is gone, finish restoring a usable package identity
// even if the caller cancels. Cancellation is observed after the replacement is verified.
await registerPackage(CancellationToken.None).ConfigureAwait(false);
packages = findRegisteredPackages();
cancellationToken.ThrowIfCancellationRequested();
if (!IsRegisteredFromLayout(packages, layoutDirectory))
{
throw CreateLocationMismatchException(layoutDirectory, packages);
}
Comment thread
Sergio0694 marked this conversation as resolved.
Resolved
Comment thread
Copilot marked this conversation as resolved.
Resolved
}

cancellationToken.ThrowIfCancellationRequested();
}
catch (OperationCanceledException)
{
Expand All @@ -55,29 +163,25 @@ public static async Task RegisterAsync(
}
catch (Exception ex)
{
// The WinRT operation can fault (rather than completing with a DeploymentResult), for example
// when Developer Mode is disabled or the layout is invalid. Surface it with the actionable
// registration message instead of a raw COM/WinRT exception.
// Include the requested manifest even when a Windows operation faults instead of returning
// a DeploymentResult, or Windows reports success without registering the requested location.
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture, ExtensionResources.PackagedAppRegistrationFailed, manifestPath, ex.Message),
Comment thread
Sergio0694 marked this conversation as resolved.
Resolved
ex);
}

// Registration reports success through IsRegistered; ExtendedErrorCode can also carry a non-fatal
// (informational) HRESULT, so IsRegistered is the authoritative signal.
if (!result.IsRegistered)
{
throw new InvalidOperationException(
string.Format(CultureInfo.CurrentCulture, ExtensionResources.PackagedAppRegistrationFailed, manifestPath, result.ErrorText),
result.ExtendedErrorCode);
}

cancellationToken.ThrowIfCancellationRequested();
}

/// <summary>Activates a registered packaged app and returns its process id.</summary>
public static uint Activate(string appUserModelId, string? activationArguments)
=> ApplicationActivationManager.ActivateApplication(appUserModelId, activationArguments);
}
private static bool IsRegisteredFromLayout(IReadOnlyList<RegisteredPackageInfo> packages, string layoutDirectory)
=> packages.Count == 1
&& string.Equals(
Path.TrimEndingDirectorySeparator(Path.GetFullPath(packages[0].InstalledPath)),
layoutDirectory,
StringComparison.OrdinalIgnoreCase);

#endif
private static InvalidOperationException CreateLocationMismatchException(string layoutDirectory, IReadOnlyList<RegisteredPackageInfo> packages)
=> new(string.Format(
CultureInfo.CurrentCulture,
ExtensionResources.PackagedAppRegistrationLocationMismatch,
layoutDirectory,
string.Join(", ", packages.Select(static package => package.InstalledPath))));
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.

using System.Security.Cryptography;

using Microsoft.Testing.Extensions.PackagedApp.Resources;

namespace Microsoft.Testing.Extensions.PackagedApp;

[SupportedOSPlatform("windows")]
internal static class PackageRegistrationLock
{
private const int SharingViolationHResult = unchecked((int)0x80070020);

public static Task<FileStream> AcquireAsync(string packageFamilyName, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

string localApplicationData = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData);
if (localApplicationData.Length == 0)
{
throw new InvalidOperationException(ExtensionResources.PackagedAppRegistrationLockDirectoryUnavailable);
}

// Keep the lock outside package-owned storage: registration may replace that storage and
// must establish its AppContainer ACL before the controller writes anything there.
string lockDirectory = Path.Combine(localApplicationData, "Microsoft.Testing.Platform", "PackagedApp", "RegistrationLocks");
return AcquireAsync(packageFamilyName, lockDirectory, cancellationToken);
}

internal static async Task<FileStream> AcquireAsync(string packageFamilyName, string lockDirectory, CancellationToken cancellationToken)
{
cancellationToken.ThrowIfCancellationRequested();

Directory.CreateDirectory(lockDirectory);
string lockName = Convert.ToHexString(SHA256.HashData(Encoding.UTF8.GetBytes(packageFamilyName.ToUpperInvariant())));
string lockPath = Path.Combine(lockDirectory, lockName + ".lock");

while (true)
{
cancellationToken.ThrowIfCancellationRequested();
try
{
// A file lease is not thread-affine and the OS releases it if the controller exits.
// Leave the file in place so every contender continues to lock the same file.
return new FileStream(lockPath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException ex) when (ex.HResult == SharingViolationHResult)
{
await Task.Delay(TimeSpan.FromMilliseconds(50), cancellationToken).ConfigureAwait(false);
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -314,6 +314,11 @@ private static async Task<ITestHostHandle> LaunchPackagedAsync(TestHostLaunchCon
manifestInfo.PackageFamilyName,
manifestPath));

// AUMID activation uses shared per-user registration state. Keep other controllers from
// switching this package's layout between registration verification and activation.
using FileStream registrationLock = await PackageRegistrationLock
.AcquireAsync(manifestInfo.PackageFamilyName, cancellationToken).ConfigureAwait(false);

// Registration provisions the package-owned LocalState directory and its AppContainer ACL.
// Handoffs must be written only after this completes; creating the directory from the unpackaged
// controller first would give it the controller's ACL and make it unreadable by the activated app.
Expand Down
Loading
Loading