Skip to content

fix(devserver): isolate add-ins in a custom AssemblyLoadContext - #23287

Merged
carldebilly merged 20 commits into
masterfrom
dev/agzi/host-addin-load-context
May 20, 2026
Merged

carldebilly merged 20 commits into
masterfrom
dev/agzi/host-addin-load-context

Conversation

@agneszitte

@agneszitte agneszitte commented May 18, 2026 •

Copy link
Copy Markdown
Member

Fixes https://github.com/unoplatform/kahua-private/issues/483

Summary

Replaces Assembly.LoadFrom(dll) add-in loading in Uno.UI.RemoteControl.Host with the Microsoft-recommended plugin pattern: a shared custom AssemblyLoadContext backed by per-add-in AssemblyDependencyResolver instances, plus a default-ALC Resolving fallback for cross-major-version framework assembly references.

This fixes the three FileNotFoundException crashes that surface during DevServer startup with the latest Uno.Sdk dev build (6.7.0-dev.50, which pulls Uno.WinUI.DevServer 6.7.0-dev.144 + the latest Uno.Settings.DevServer 1.8.0-dev.125 + Uno.UI.App.Mcp 1.3.0-dev.16):

  1. User-reported crash using Uno.Sdk 6.7.0-dev.48, still reproducing on Uno.Sdk 6.7.0-dev.50 with the latest licensing add-in:

    Unhandled exception. ... ---> System.IO.FileNotFoundException: Could not load file or assembly
    'System.Text.Encodings.Web, Version=8.0.0.0, Culture=neutral, PublicKeyToken=cc7b13ffcd2ddd51'.
       at Microsoft.Kiota.Serialization.Json.KiotaJsonSerializationContext..cctor()
       ...
       at Uno.Licensing.Sdk.Client.LicensingClient..ctor(IOptionsMonitor`1 options, IHttpClientFactory httpClients)
       ...
       at Microsoft.Extensions.Hosting.Internal.Host.StartAsync(CancellationToken cancellationToken)
       at Uno.UI.RemoteControl.Host.Program.Main(String[] args)
    

    Note: Uno.Settings.DevServer 1.8.0-dev.125 is the post-NetCurrent-flip licensing build (Uno.Licensing.Sdk.dll now net9.0, Kiota bumped to 1.22.2). The crash still happens because Kiota 1.22.2 only ships lib/net8.0/ (no net9.0 TFM yet), so the net9.0 licensing project still resolves the net8.0 Kiota binary, which hard-references System.Text.Encodings.Web v8.0.0.0. The host's TPA carries v10 (or v9 on vanilla .NET 9) and the default ALC won't lax-bind across the major-version gap.

  2. Uno.UI.App.Mcp.Server.MCPServicesRegistration..ctor → FNF Microsoft.Extensions.Configuration, Version=10.0.0.0 (MCP add-in built for net10.0; host TPA has v9).

  3. ModelContextProtocol.McpJsonUtilities.JsonContext..cctor() → FNF System.Text.Encodings.Web, Version=10.0.0.0. ModelContextProtocol 1.1.0 for net9.0 was compiled against v10 reference assemblies of System.Text.*; on a .NET 9 runtime the framework's v9 is forced into TPA and the strict version match fails. This one is pre-existing in the host's own dependency graph — it was previously masked by the licensing crash, and would have started biting clients independently as soon as that crash went away.

Why this change

The existing loader uses Assembly.LoadFrom(dll), which loads every add-in into the default AssemblyLoadContext. That:

  • pollutes the host's process with the add-in's transitive NuGet graph,
  • can't bridge cross-major-version AssemblyRefs (the default ALC's TPA binder enforces strict version match for shared-framework OOB packages like System.Text.Encodings.Web), and
  • makes one add-in's dependency choices break startup for every other add-in.

Microsoft explicitly steers against this pattern; the tutorial and AssemblyDependencyResolver's design note recommend isolated AssemblyLoadContexts backed by per-plugin .deps.json, with framework assemblies deliberately not resolved by the plugin's resolver so host and plugin share the same Type identity.

What this PR does

Host change (3 files in Uno.UI.RemoteControl.Host):

  • Helpers/AddInLoadContext.cs (new) — single AssemblyLoadContext shared by all DevServer add-ins, holding per-add-in AssemblyDependencyResolvers. Load(AssemblyName) runs a three-step lookup:

    1. Walk Default.Assemblies for a matching simple name (so IServiceCollection, IHostedService, ILogger, IConfiguration, etc. resolve to the host's instance and cross-version refs like Kiota's v8 are satisfied by the host's v9/v10).
    2. Ask Default.LoadFromAssemblyName(new AssemblyName(simpleName)) to trigger TPA-based lookup for lazily-loaded framework OOB packages the host knows about but hasn't yet loaded.
    3. Fall back to each plugin's .deps.json through its AssemblyDependencyResolver.

    Steps 1 and 2 both skip IsDynamic candidates (so reflection-emit / source-gen assemblies can't be coincidentally substituted) and enforce PublicKeyToken compatibility (so a strong-named request is never bridged to a differently-signed instance — that's a security-relevant identity swap rather than a version mismatch papered over). Step 2 also catches FileLoadException / BadImageFormatException in addition to FileNotFoundException so a TPA strong-name / image rejection still falls through to step 3.

    The ctor constructs each AssemblyDependencyResolver in its own try/catch and emits a stderr breadcrumb on failure, so a corrupt or missing .deps.json on one add-in doesn't abort loading of the others — preserving the per-add-in failure isolation the original Assembly.LoadFrom loop provided.

    Add-ins still share the context, so types defined in one (e.g. Uno.Licensing.Sdk.Contracts) can be consumed by another (e.g. Uno.UI.App.Mcp.Server).

  • Helpers/AssemblyHelper.cs — swaps Assembly.LoadFrom(dll) for loadContext.LoadFromAssemblyPath(dll) (the entry-point load is by path so the caller's exact DLL always wins, even if the add-in's simple name happens to collide with something in the default ALC; transitive deps still flow through AddInLoadContext.Load).

  • Program.cs — adds an explicit ConfigureAssemblyResolution() method called from the first line of Main (not from a static constructor — any failure now surfaces as a normal exception via the existing try/catch in Main rather than being wrapped in TypeInitializationException). It hooks AssemblyLoadContext.Default.Resolving as the .NET-Core equivalent of binding redirects with the same IsDynamic / PKT guards described above, and eager-loads System.Text.Json.dll + System.Text.Encodings.Web.dll from the apphost directory by file path (extracted to a private static readonly string[] for extensibility) so the Resolving handler has candidates ready. Loading by AssemblyName would hit the .NET 9 framework's "platform assembly" override for System.Text.Encodings.Web and fail outright; typeof(...).Assembly would itself emit a v10 AssemblyRef and trigger the same crash. Loading by file path side-steps both traps. Eager-load failures are logged via stderr (the host's ILoggerFactory isn't built yet at this point) so a regression in the preload step doesn't silently disable the safety net.

Regression test (new in Uno.UI.RemoteControl.DevServer.Tests):

  • Fixtures/AddInWithCrossMajorVersionRefs/ (new) — purpose-built net8.0 class library following Microsoft's plugin-tutorial conventions (<EnableDynamicLoading>true</EnableDynamicLoading>). Pins System.Text.Encodings.Web 8.0.0 + Microsoft.Extensions.DependencyInjection.Abstractions 8.0.2 so its compiled AssemblyRefs embed at v8.0.0.0. Declares [assembly: Uno.Utils.DependencyInjection.ServiceCollectionExtension(typeof(ServicesRegistration))] so the host's AddFromServiceExtensionAttributes actually invokes the ctor via Activator.CreateInstance at startup — the v8.0.0.0 AssemblyRefs get resolved at runtime instead of sitting dormant in metadata. Maintenance contract documented inline: bump the TFM + matching PackageReferences when the host's lowest supported TFM advances past net8.0.
  • DevServerTests.cs — new DevServer_ShouldStart_WithAddInThatHasCrossMajorVersionFrameworkRefs test. Hands the fixture DLL to the host via --addins, asserts the host loads + activates the add-in, reaches Now listening on:, and helper.IsRunning stays true past that log (the runtime-stable invariant — a fatal CLR Unhandled exception banner terminates the process before the listening state). The comment block explicitly notes this is a positive-outcome regression: depending on the .NET runtime point release, the binder can also lax-bind the v8 ref on its own even without the host's fix, so a "must throw FNF without fix" assertion isn't deterministic across runtimes. The end-to-end repro under D:\Dev\Uno-Pocs\DevServerLicensingRepro\ still covers the runtime-strict scenario against the real Kiota / Uno.Settings.DevServer payload.
  • Uno.UI.RemoteControl.DevServer.Tests.csproj — removes Fixtures\** from the default Compile / None / EmbeddedResource globs (so the fixture's compile graph stays decoupled from the test project's), declares the fixture as a <ProjectReference ReferenceOutputAssembly="false" SkipGetTargetFrameworkProperties="true" UndefineProperties="TargetFramework" /> so CI restore picks it up, and adds a _BuildAndCopyAddInTestFixtures MSBuild target that builds the fixture and stages its entire bin (via **\* glob) under $(OutDir)Fixtures\ so the per-add-in AssemblyDependencyResolver branch has a real graph to consult.
  • Uno.UI.slnx, Uno.UI-Skia-only.slnf, Uno.UI-UnitTests-only.slnf — register the fixture project so it appears in the IDE solution views.

Diff stats (vs origin/master):

 src/Uno.UI-Skia-only.slnf                                                                   |   1 +
 src/Uno.UI-UnitTests-only.slnf                                                              |   1 +
 src/Uno.UI.RemoteControl.DevServer.Tests/DevServerTests.cs                                  |  62 +
 src/Uno.UI.RemoteControl.DevServer.Tests/Fixtures/AddInWithCrossMajorVersionRefs/*.csproj   |  39 (new)
 src/Uno.UI.RemoteControl.DevServer.Tests/Fixtures/AddInWithCrossMajorVersionRefs/Stub.cs    |  62 (new)
 src/Uno.UI.RemoteControl.DevServer.Tests/Uno.UI.RemoteControl.DevServer.Tests.csproj        |  63 +
 src/Uno.UI.RemoteControl.Host/Helpers/AddInLoadContext.cs                                   | 183 (new)
 src/Uno.UI.RemoteControl.Host/Helpers/AssemblyHelper.cs                                     |  25 ±
 src/Uno.UI.RemoteControl.Host/Program.cs                                                    | 148 +
 src/Uno.UI.slnx                                                                             |   3 +
 10 files changed, 585 insertions(+), 2 deletions(-)

Test plan

Validated locally end-to-end against the published latest packages on nuget.org (no licensing-side change required for this fix to work):

  • Uno.Sdk 6.7.0-dev.50
  • → Uno.WinUI.DevServer 6.7.0-dev.144
  • → Uno.Settings.DevServer 1.8.0-dev.125 (the latest licensing build, post-NetCurrent-flip)
  • → Uno.UI.App.Mcp 1.3.0-dev.16
Scenario Host build Result Log
Baseline (no fix), cached 6.7.0-dev.144 host — Crashes — Encodings.Web 8.0.0.0 FNF at KiotaJsonSerializationContext..cctor (matches client report) repro-output-sdk-dev50-unmodified.log
net9.0 host with this PR (UnoTargetFrameworkOverride=net9.0) 0 errors DevServer reaches Application started. Press Ctrl+C to shut down., Uno.Licensing.Sdk.LicensesStore[1]: Refreshing licenses token... looping; 0 unhandled repro-final-net9-sdk-dev50.log
net10.0 host with this PR (UnoTargetFrameworkOverride=net10.0) 0 errors same clean startup, 0 unhandled repro-final-net10-sdk-dev50.log

Repro project at D:\Dev\Uno-Pocs\DevServerLicensingRepro (blank Uno desktop app pinned to Uno.Sdk 6.7.0-dev.50). For each TFM the test stages the host's bin/Debug/net{9,10}.0/ over the cached Uno.WinUI.DevServer package and invokes Uno.UI.RemoteControl.Host.exe --solution <repro>.sln against the broken add-ins.

Test plan for reviewers / CI

  • Build Uno.UI.RemoteControl.Host for net9.0 and net10.0; both should build clean
  • Smoke-launch the built host against any Uno app's .sln and confirm Application started. (no System.Text.Encodings.Web / Microsoft.Extensions.Configuration FileNotFoundExceptions in the log)
  • Hot Reload + IDE channel scenarios still work (regression check: add-ins are now in an isolated ALC instead of the default, so anything reflecting across the host/add-in boundary by Type could in theory regress — none observed in the manual runs, but worth a smoke pass)
  • No regression on add-ins that previously loaded fine

Considered alternative (not in this PR, kept locally for reference)

A licensing-repo workaround was drafted on dev/agzi/fix-devserver-encodings-web in uno.licensing: ship System.Text.Encodings.Web v8.0.0.dll inside Uno.Settings.DevServer's tools/devserver/ package output via GeneratePathProperty + <None>. Local validation showed it only relocates the crash — once the v8 DLL satisfies Kiota's AssemblyRef, the host's System.Text.Json v10 follow-on requests Encodings.Web v10 and the single-version-per-simple-name rule of AssemblyLoadContext makes it fatal. It also doesn't help the MCP path (which lives entirely in the default ALC of the host process). The host-side fix in this PR resolves all three failure modes with no licensing-repo change required.

References

Copilot AI review requested due to automatic review settings May 18, 2026 21:15
DevServer add-ins were being loaded into the default AssemblyLoadContext
via Assembly.LoadFrom — the textbook plugin antipattern .NET docs
explicitly steer away from. With the latest published Uno.Sdk dev train,
this surfaces three FileNotFoundException crashes during host startup:

  - Kiota's net8.0 binary (loaded by Uno.Licensing.Sdk) hard-references
    System.Text.Encodings.Web 8.0.0.0. The host's TPA carries v10 (or v9
    on a vanilla .NET 9 runtime) and won't lax-bind across the major
    version gap → unhandled FNF from KiotaJsonSerializationContext..cctor
    inside LicensingClient.InitClient (Uno.Sdk 6.7.0-dev.48, client-
    reported on master and the 6.6/6.5 release lines).
  - Uno.UI.App.Mcp.Server is built for net10.0 and references
    Microsoft.Extensions.Configuration 10.0.0.0; on a net9.0 host TPA
    only has v9 → MCPServicesRegistration ctor throws FNF.
  - ModelContextProtocol 1.1.0 for net9.0 was compiled with v10 refs to
    System.Text.Json / System.Text.Encodings.Web; on a .NET 9 runtime
    the framework's v9 is forced into TPA and the strict-version match
    fails inside McpJsonUtilities.JsonContext..cctor.

Move add-in loading to the pattern Microsoft documents in
docs.microsoft.com/dotnet/core/tutorials/creating-app-with-plugin-support:
one custom AssemblyLoadContext shared across add-ins, backed by per-
add-in AssemblyDependencyResolver instances. Framework / contract types
that the host already has loaded are bridged back into the AddIn ALC
(preserves IServiceCollection / IHostedService / ILogger type identity
and silently satisfies cross-major-version refs from add-in deps).

The MCP / ModelContextProtocol failures happen in the default ALC
before any add-in runs, so an AssemblyLoadContext.Default.Resolving
handler is also added in Program's static cctor as the equivalent of
the .NET-Framework-era binding redirect: when normal probing fails,
fall back to any already-loaded assembly with the same simple name.
System.Text.Json.dll / System.Text.Encodings.Web.dll are eager-loaded
from the apphost directory by file path so the Resolving handler has
candidates before the first versioned request fires.

Validated end-to-end against the published broken
Uno.Settings.DevServer 1.8.0-dev.46 (no licensing-side change needed):

  - net9.0 host (UnoTargetFrameworkOverride=net9.0) — DevServer boots,
    'Application started. Press Ctrl+C to shut down.',
    Uno.Licensing.Sdk.LicensesStore: 'Refreshing licenses token...'
    looping normally, 0 unhandled exceptions over 20s.
  - net10.0 host (UnoTargetFrameworkOverride=net10.0) — same clean
    startup, 0 unhandled exceptions.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

Copilot AI 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.

Pull request overview

Isolates DevServer add-ins from the host's default AssemblyLoadContext to fix cross-major-version FileNotFoundException failures (notably System.Text.Encodings.Web from Kiota/Licensing and Microsoft.Extensions.Configuration/System.Text.Encodings.Web from MCP/ModelContextProtocol) during host startup with recent Uno.Sdk builds.

Changes:

  • New AddInLoadContext (a custom AssemblyLoadContext backed by per-add-in AssemblyDependencyResolvers) bridges host-shared framework/contract assemblies by simple name while resolving private add-in deps through each add-in's .deps.json.
  • AssemblyHelper.Load now loads add-ins via AddInLoadContext.LoadFromAssemblyName instead of Assembly.LoadFrom.
  • Program static constructor registers a Default.Resolving "binding redirect" handler and eager-loads System.Text.Json.dll / System.Text.Encodings.Web.dll by path so the handler has candidates for later cross-version refs.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 6 comments.

File Description
src/Uno.UI.RemoteControl.Host/Helpers/AddInLoadContext.cs New isolated ALC for add-ins with default-ALC bridging and per-add-in dependency resolution.
src/Uno.UI.RemoteControl.Host/Helpers/AssemblyHelper.cs Switches add-in loading from Assembly.LoadFrom to the new AddInLoadContext.
src/Uno.UI.RemoteControl.Host/Program.cs Adds default-ALC Resolving lax-binding handler and apphost-dir preload of OOB framework DLLs in the static constructor.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@unodevops

Copy link
Copy Markdown
Contributor

@agneszitte agneszitte added the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label May 18, 2026
…ging

Adds an integration test that loads a purpose-built net8.0 add-in DLL into
the DevServer host via the --addins CLI flag and asserts the host reaches
'Now listening on:' without an unhandled FileNotFoundException on
System.Text.Encodings.Web — the exact client-reported failure mode this
PR's host changes fix.

Fixture project follows Microsoft's documented plugin-testing pattern (a
separate class library built independently of the host, see
learn.microsoft.com/dotnet/core/tutorials/creating-app-with-plugin-support
and the AppWithPlugin sample): targets a TFM older than the host's lowest
supported runtime so its compiled AssemblyRef to
System.Text.Encodings.Web embeds at v8.0.0.0 — the strict version mismatch
the host has to satisfy from its own newer-major loaded instance via the
AddInLoadContext and AssemblyLoadContext.Default.Resolving handler.

Wiring decisions:
  - Fixture is built via an MSBuild task, not a ProjectReference, so its
    net8.0 TargetFramework stays decoupled from the test project's TFM
    negotiation and from its compile / AssemblyInfo graph.
  - The default Compile/None/EmbeddedResource globs in the test project
    explicitly Remove Fixtures\** so the fixture's obj-AssemblyInfo and
    source files don't collide with the test project's own attributes.
  - Negative assertion in the new test matches by class-of-bug (regex on
    "Unhandled exception ... FileNotFoundException ... System.Text.Encodings.Web")
    rather than today's specific version, so the test stays meaningful as
    host TFMs roll forward through net10 and net11.

Validation:
  - Build: src/Uno.UI.RemoteControl.DevServer.Tests on net10 — 0 errors.
  - New test DevServer_ShouldStart_WithAddInThatHasCrossMajorVersionFrameworkRefs
    passes (615 ms).
  - Existing DevServer_ShouldStart and DevServer_ShouldStopCleanly still pass
    alongside it — no regression to the existing helper.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 18, 2026 22:29
Six points from the Copilot review on #23287:

1. AssemblyHelper now loads the top-level add-in via LoadFromAssemblyPath
   instead of LoadFromAssemblyName, so the caller's exact DLL is always what
   ends up in the context. The Default-ALC short-circuit and TPA fallback
   in AddInLoadContext.Load could otherwise silently substitute a
   host-loaded assembly if an add-in's simple name happened to collide.
   Transitive deps still flow through that override as intended.

2. AddInLoadContext.Load now catches FileLoadException and
   BadImageFormatException in addition to FileNotFoundException when
   probing Default.LoadFromAssemblyName. TPA can match an assembly by
   simple name and reject the load on a strong-name / version mismatch —
   exactly the cross-major scenario this class exists for — and we
   shouldn't bubble that out: the add-in's own deps.json may still carry
   a usable copy.

3. The Default.Resolving handler now skips IsDynamic assemblies (so
   reflection-emit / source-generator-emitted assemblies can't be
   coincidentally substituted for a real AssemblyRef) and requires
   PublicKeyToken compatibility (so a strong-named request is never
   bridged to a differently-signed instance — that would be a security-
   relevant identity swap rather than a version mismatch papered over).

4. The eager-load catch in Program's static constructor now writes a
   one-line breadcrumb to stderr (the ILoggerFactory isn't built yet at
   this point) so a regression in the preload step doesn't silently
   disable the safety net.

5. The list of shared-framework OOB DLLs to eager-load is extracted to a
   private static readonly array at class scope, making the contract
   explicit and easier to extend (e.g. Microsoft.Extensions.Configuration.*
   if a future MCP or add-in bump needs it).

6. `using System.Runtime.Loader;` reordered into the System.* block to
   match the project's using-block convention.

All three DevServer integration tests still pass on net10
(DevServer_ShouldStart, DevServer_ShouldStopCleanly, and
DevServer_ShouldStart_WithAddInThatHasCrossMajorVersionFrameworkRefs).
Manual net9 host run against Uno.Sdk 6.7.0-dev.50 + the broken
Uno.Settings.DevServer 1.8.0-dev.125 still reaches 'Now listening on:'
with zero unhandled exceptions and the licensing add-in actively
refreshing tokens.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

Copilot AI 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.

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated 4 comments.

@unodevops

Copy link
Copy Markdown
Contributor

agneszitte added a commit that referenced this pull request May 18, 2026
Four follow-up points from the latest Copilot review on #23287:

1. DevServerTests.cs:125 — assertion message referenced the wrong MSBuild
   target name (`_CopyAddInTestFixtures` vs the actual
   `_BuildAndCopyAddInTestFixtures`). Fixed.

2. AddInWithCrossMajorVersionRefs.csproj — fixture now sets
   `<EnableDynamicLoading>true</EnableDynamicLoading>` per the Microsoft
   plugin tutorial, so it ships a self-contained .deps.json and the
   per-add-in AssemblyDependencyResolver branch in AddInLoadContext.Load
   actually has a graph to consult. Also added a
   Microsoft.Extensions.DependencyInjection.Abstractions 8.0.2
   PackageReference so the registration ctor's IServiceCollection
   parameter is a real v8.0.0.0 cross-major AssemblyRef.

3. Stub.cs — fixture's ServicesRegistration is now annotated as
   `[assembly: ServiceCollectionExtension(typeof(ServicesRegistration))]`
   under the same `Uno.Utils.DependencyInjection` namespace the host
   matches by full type name (same convention as Uno.Settings.DevServer
   and Uno.UI.App.Mcp.Server). The host's AddFromServiceExtensionAttributes
   now actually invokes the ctor at startup via Activator.CreateInstance,
   so this assembly's v8.0.0.0 AssemblyRefs get resolved at runtime
   instead of sitting dormant in metadata.

   The DevServerTests assertion is reframed accordingly: the test is now
   an explicit positive-outcome regression (host loads + activates the
   add-in + reaches "Now listening on:" without an unhandled exception),
   not a deterministic reproduction of the original v8.0.0.0
   FileNotFoundException. The strict-vs-lax binding behaviour at the FNF
   call site varies by .NET runtime point release (.NET 9.0.16 currently
   lax-binds v8 → v9 for the simple `JavaScriptEncoder.Default` access,
   even though the same code path crashes for real clients on slightly
   older runtimes and for the real Kiota source-gen pattern). The
   end-to-end repro under D:\Dev\Uno-Pocs\DevServerLicensingRepro\ covers
   the runtime-strict scenario; this unit test covers the runtime-stable
   "host load pipeline must not break" invariant.

4. AddInLoadContext.Load — step 1 now applies the same IsDynamic skip
   and PublicKeyToken compatibility check that the
   AssemblyLoadContext.Default.Resolving handler in Program.cs uses,
   eliminating the asymmetric identity-swap window the reviewer flagged.

Plus a small csproj hygiene fix: the fixture is now declared as a
`<ProjectReference Include="..." ReferenceOutputAssembly="false"
SkipGetTargetFrameworkProperties="true" UndefineProperties="TargetFramework" />`
so CI restore picks it up automatically. The default Compile / None /
EmbeddedResource globs Remove="Fixtures\**" keep the fixture's compile
graph (and its own AssemblyInfo) out of the test project, and the
existing `_BuildAndCopyAddInTestFixtures` target keeps driving the build
+ output staging.

Validation:
  - dotnet build src/Uno.UI.RemoteControl.DevServer.Tests on net10:
    0 errors, 2 unrelated MSB3836 warnings.
  - DevServer_ShouldStart, DevServer_ShouldStopCleanly,
    DevServer_ShouldStart_WithAddInThatHasCrossMajorVersionFrameworkRefs
    all pass on net10.
  - Manual net9 host run against the cached Uno.Settings.DevServer
    1.8.0-dev.46 + Uno.WinUI.DevServer 6.7.0-dev.144 still reaches
    "Now listening on:" with 0 unhandled exceptions and the licensing
    add-in actively refreshing tokens.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@agneszitte
agneszitte requested a review from Copilot May 18, 2026 23:08

Copilot AI 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.

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated 3 comments.

Two follow-up Copilot review passes on #23287 combined into one commit
with a Conventional-Commits-compliant title (the previous attempt used
`test(devserver) + fix(devserver):` which the Azure pipeline's commit
validator rejected — only a single type is allowed).

Round 2 (test fixture / load-context consistency):

  - Fixture's `ServicesRegistration` is now annotated as
    `[assembly: Uno.Utils.DependencyInjection.ServiceCollectionExtension(typeof(ServicesRegistration))]`
    so the host's `AddFromServiceExtensionAttributes` actually invokes the
    ctor at startup via `Activator.CreateInstance` — the v8.0.0.0
    AssemblyRefs baked into the fixture (Encodings.Web,
    DependencyInjection.Abstractions) get resolved at runtime instead of
    sitting dormant in metadata. Reviewer correctly noted the previous
    static-cctor pattern wouldn't fire from a plain `LoadFromAssemblyPath`
    and the test would have passed even on an unmodified host.

  - Fixture csproj sets `<EnableDynamicLoading>true</EnableDynamicLoading>`
    + adds a `Microsoft.Extensions.DependencyInjection.Abstractions 8.0.2`
    PackageReference so the registration ctor's `IServiceCollection`
    parameter is itself a v8 cross-major AssemblyRef.

  - DevServerTests' assertion message references the correct target name
    `_BuildAndCopyAddInTestFixtures` (was `_CopyAddInTestFixtures`).

  - The test itself is reframed as a runtime-stable positive-outcome
    regression (host loads + activates the add-in + reaches
    `Now listening on:` without an unhandled exception). Current
    .NET 9.0.16 / .NET 10 runtimes lax-bind the simple
    `JavaScriptEncoder.Default` access on their own even without the
    host's fix, so a "must FNF without fix" assertion isn't deterministic
    across runtime point releases. The end-to-end repro under
    D:\Dev\Uno-Pocs\DevServerLicensingRepro\ still covers the
    runtime-strict scenario against the real Kiota / Uno.Settings.DevServer
    payload.

  - AddInLoadContext.Load step 1 now applies the same `IsDynamic` skip
    + `PublicKeyToken` compatibility check that the
    `AssemblyLoadContext.Default.Resolving` handler in Program.cs uses,
    closing the asymmetric identity-swap window the reviewer flagged.

  - AddInLoadContext.Load step 2 also catches `FileLoadException` and
    `BadImageFormatException` in addition to `FileNotFoundException`, so
    a TPA strong-name / version / image mismatch on a shared-framework
    OOB package keeps falling through to the per-add-in deps.json
    resolvers in step 3 instead of bubbling out.

Round 3 (staging + lifecycle / assertion tightening):

  - The fixture Copy step now stages the *entire* fixture bin via a
    `**\*` glob instead of just `*.dll`, `*.pdb` and `*.deps.json` of
    the main assembly. With `EnableDynamicLoading=true` the fixture's
    output directory also contains the private NuGet payloads its
    `.deps.json` points at (e.g. the v8
    Microsoft.Extensions.DependencyInjection.Abstractions.dll); those
    now actually land at the paths `AssemblyDependencyResolver` returns,
    so step 3 of AddInLoadContext.Load has a real graph to consult
    rather than silently no-opping back to step 1.

  - Program.cs: the Resolving handler install + the apphost-dir
    eager-load moved out of a static constructor into an explicit
    `ConfigureAssemblyResolution` method called from the first line of
    `Main`. Any failure inside the install now surfaces as a normal
    exception (logged via stderr) rather than being wrapped in a
    `TypeInitializationException` the first time `Program` is touched,
    which on .NET Core terminates the process with a stack frame that
    points at the type rather than the offending statement.

  - DevServerTests no longer substring-matches on the literal
    `"Unhandled exception"` phrase (which would also match a non-fatal
    logger message containing that text). The assertion is now
    `helper.IsRunning.Should().BeTrue()` after the listening-state log,
    which is the real invariant: a fatal CLR `Unhandled exception`
    banner terminates the host process before `Now listening on:` is
    reached, so a still-alive host past that point covers the
    regression deterministically.

Validation:

  - `dotnet build src/Uno.UI.RemoteControl.DevServer.Tests` on net10:
    0 errors.
  - All 3 DevServer integration tests pass on net10
    (DevServer_ShouldStart, DevServer_ShouldStopCleanly,
    DevServer_ShouldStart_WithAddInThatHasCrossMajorVersionFrameworkRefs).
  - Staged fixture output now contains
    `Microsoft.Extensions.DependencyInjection.Abstractions.dll` next to
    the main fixture DLL (confirming the per-add-in resolver branch is
    actually wired up).
  - Manual net9 host run against the cached Uno.Settings.DevServer
    1.8.0-dev.46 + Uno.WinUI.DevServer 6.7.0-dev.144 still reaches
    `Now listening on:` with 0 unhandled exceptions and the licensing
    add-in actively refreshing tokens.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@agneszitte
agneszitte force-pushed the dev/agzi/host-addin-load-context branch from 327ec40 to 386c86f Compare May 18, 2026 23:31
@agneszitte
agneszitte requested a review from Copilot May 18, 2026 23:38

Copilot AI 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.

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated 2 comments.

@agneszitte
agneszitte requested a review from Copilot May 18, 2026 23:48
Two follow-up points from the latest Copilot review pass on #23287:

1. AddInLoadContext.cs:104 — step 2 (the `Default.LoadFromAssemblyName(new
   AssemblyName(name))` fallback through host TPA) now validates the
   loaded assembly's `PublicKeyToken` against the requested one before
   returning. If the request carries a non-empty PKT and the loaded
   assembly's PKT differs (or is unsigned), the call falls through to
   the per-add-in resolvers in step 3 instead of substituting across
   different strong-name identities. Closes the asymmetric identity-swap
   window between step 1 / the Default.Resolving handler (both of which
   already enforce PKT compatibility) and step 2.

2. AssemblyHelper.cs:45 — the `AddInLoadContext` ctor now constructs each
   `AssemblyDependencyResolver` in its own try/catch and emits a stderr
   breadcrumb on failure, rather than letting a single bad add-in path
   abort the whole add-in loading loop via the outer catch in
   `AssemblyHelper.Load`. Restores the per-add-in failure isolation the
   original `Assembly.LoadFrom` loop provided: a corrupt or missing
   `.deps.json` for one add-in no longer prevents the others from loading.
   The per-DLL try/catch in `AssemblyHelper.Load` still surfaces the
   actual load failure for the offending add-in with a meaningful error.

Validation:

  - `dotnet build src/Uno.UI.RemoteControl.DevServer.Tests` on net10:
    0 errors.
  - All 3 DevServer integration tests pass on net10
    (DevServer_ShouldStart, DevServer_ShouldStopCleanly,
    DevServer_ShouldStart_WithAddInThatHasCrossMajorVersionFrameworkRefs).
  - Manual net9 host run against the cached Uno.Settings.DevServer
    1.8.0-dev.46 + Uno.WinUI.DevServer 6.7.0-dev.144 still reaches
    `Now listening on:` with 0 unhandled exceptions and the licensing
    add-in actively refreshing tokens.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

Copilot AI 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.

Pull request overview

Copilot reviewed 10 out of 10 changed files in this pull request and generated no new comments.

@agneszitte agneszitte removed the do-not-merge/work-in-progress Indicates that a PR should not merge because it is a work in progress. label May 18, 2026
Copilot AI review requested due to automatic review settings May 19, 2026 20:27

Copilot AI 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.

Pull request overview

Copilot reviewed 18 out of 18 changed files in this pull request and generated 6 comments.

@unodevops

Copy link
Copy Markdown
Contributor

- AddInLoadContext.cs: declare 'loaded' as Assembly? to fix CS8625
  nullable warning when the variable is set to null on PKT mismatch
- Program.cs: move HostAssemblyResolution.Install() inside the try
  block so failures surface through the normal startup error path
- AssemblyHelper.cs: move addin-loading-start telemetry event after
  the empty-DLL-list early-return to avoid orphaned start events
- HostAssemblyResolution.cs: fix misleading XML comment on IsKillSwitchActive
  (remove "Evaluated once at first access" which contradicted "re-read each call")
- AddInLoadContext.cs step 2: apply symmetric PKT policy for unsigned requests
  (refuse a strong-named loaded assembly when the request carries no PKT)
- AddInLoadContext.cs step 2: add version downgrade guard mirroring step 1
  (refuse loaded assembly when its version is lower than the requested version)
- Stub.cs: fix comment "defined in AddInLoadContext" -> "defined here in the fixture"
Copilot AI review requested due to automatic review settings May 19, 2026 23:04
@unodevops

Copy link
Copy Markdown
Contributor

Copilot AI 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.

Pull request overview

Copilot reviewed 18 out of 18 changed files in this pull request and generated 4 comments.

Comments suppressed due to low confidence (1)

src/Uno.UI.RemoteControl.DevServer.Tests/DevServerTests.cs:185

  • Same potential race as the previous test: StartAsync may return before hosted services have actually started (it matches early output), but this test immediately checks for the hosted-service sentinel file. Consider waiting for "Now listening on:" (or another definitive post-start log) and/or polling for the sentinel file with a timeout to avoid flaky failures.
				var started = await helper.StartAsync(CT, extraArgs: $"--addins \"{fixtureDll}\"");
				helper.EnsureStarted();

				started.Should().BeTrue("dev server should start with the DI fixture add-in loaded");
				helper.AssertRunning();

Comment thread src/Uno.UI.slnx Resolved
Comment thread src/Uno.UI-UnitTests-only.slnf Resolved
Comment thread src/Uno.UI-Skia-only.slnf Resolved
@unodevops

Copy link
Copy Markdown
Contributor

Include AddInWithDiServiceRegistration.csproj in Uno.UI.slnx,
Uno.UI-UnitTests-only.slnf, and Uno.UI-Skia-only.slnf alongside
the existing AddInWithCrossMajorVersionRefs fixture so developers
can navigate and build all DevServer test fixtures from any filter.
@carldebilly
carldebilly merged commit d6a4359 into master May 20, 2026
9 of 14 checks passed
@carldebilly
carldebilly deleted the dev/agzi/host-addin-load-context branch May 20, 2026 12:33
@unodevops

Copy link
Copy Markdown
Contributor

carldebilly added a commit that referenced this pull request May 21, 2026
…e-system probe

The previous fix pre-loaded `Uno.Licensing.*.dll` from each add-in directory
into Default ALC via a hardcoded glob list (`AddInSharedAssemblyPatterns`).
That couples the generic DevServer host to specific Uno Platform product
names and grows every time a new contract assembly hits the same packaging
quirk. Replace the white-list with a probe that has zero knowledge of which
add-ins are loaded and requires no changes to the currently-published
add-in packages.

Root cause precisely: when a contract DLL is physically present in one
add-in's directory but absent from every add-in's deps.json, steps 1-3 of
`AddInLoadContext.Load` all return null because
`AssemblyDependencyResolver` only consults deps.json — it does not probe
the file system.

Fix: add a fourth resolution step inside `AddInLoadContext.Load` that scans
each registered add-in directory for a matching `{simpleName}.dll` and
loads it via `LoadFromAssemblyPath`. The DLL ends up in the shared add-in
ALC, so every add-in sees the same Type identity and DI resolves cleanly.
This mirrors the implicit probing `Assembly.LoadFrom` performed before
PR #23287 introduced ALC isolation.

Also drop unused machinery:
- Remove `AddInSharedAssemblyPatterns` constant and its companion eager-load
  loop in `AssemblyHelper.Load`.
- Drop the `patterns` parameter from `EagerLoadFromDirectory`. The default
  host-directory eager-load (`System.*` / `Microsoft.Extensions.*`) remains
  unchanged — it is what keeps the cross-major-version scenarios from
  PR #23287 working.
- Promote `DefaultEagerLoadPatterns` to `ImmutableArray<string>`.
- Strip the PKT symmetry check from `TryBridgeBySimpleName` and from step 2
  of `AddInLoadContext.Load`. Add-ins and contract DLLs are unsigned in
  practice; the guard never triggered. Dynamic-skip and version-downgrade
  guards stay.
- Replace duplicate kill-switch read in `Install()` with the existing
  `IsKillSwitchActive` property.
- Rename `_contract` primary-ctor parameter to `contract` in the consumer
  fixture.

Tests:
- New `Given_AddInLoadContext` step-4 tests (red->green TDD): file-system
  probe finds DLLs absent from every deps.json, probes every registered
  add-in directory (not only the first), and returns null/throws cleanly
  when nothing matches.
- Drop the `AddInSharedAssemblyPatterns_*` constant tests and the custom
  `patterns` parameter tests.
- Drop `TryBridgeBySimpleName_RejectsStrongNamedLoaded_WhenRequestedIsUnsigned`.
- `DevServer_ShouldResolveSharedContractAcrossAddIns_WhenContractOnlyInProviderDirectory`:
  switch `--addins` arg to semicolon-separated paths (host parses a single
  string, two space-separated tokens silently dropped the consumer),
  and assert the sentinel's AssemblyQualifiedName references the shared
  contracts assembly to prove single Type identity end-to-end.
carldebilly added a commit that referenced this pull request May 22, 2026
…d-graph walk

The first iteration scanned every DLL in each add-in's tools/* + lib/* and compared
AssemblyRef tables flatly. That model overcounts: it includes client-side DLLs in
lib/net9.0/ that the DevServer host never loads (MEA v9.8 from HotDesign was a
false positive of this kind), and it ignores intra-add-in forward rolls (Settings
internally referencing SkiaSharp v2.88 in one DLL and v3.119 in another is not a
conflict — the v3.119 DLL it ships is what gets loaded, and the v2.88 ref forward-
rolls cleanly).

The new model walks the actual runtime load graph instead:

  1. The host's effective TPA is computed from the .NET shared frameworks
     (Microsoft.NETCore.App + Microsoft.AspNetCore.App per the host's runtimeconfig.json)
     plus the bundled host deps under tools/rc/host/net10.0/.
  2. For each add-in, the BFS root is the primary server DLL declared via the
     tools/devserver/*.Server.dll or tools/<tfm>/server/*.Server.dll convention.
  3. At every visited DLL, each AssemblyRef is resolved:
       host TPA hit          → forward-roll OK (don't walk into host DLLs)
       host TPA hit, low ver → bridge would refuse; check loadable dir for bundled
                               copy. If found → case 1 latent (works via
                               LoadFromResolveHandler, pollutes Default ALC).
                               If not → case 1 fatal (guaranteed FNFE).
       no host hit, bundled  → enqueue the bundled DLL, record this add-in's
                               contribution for cross-add-in comparison.
       no host hit, unbundled → record as unresolved (potential case 2 trigger
                                or surprise FNFE at runtime).
  4. Cross-add-in case 2 = same simple name absent from host TPA, contributed at
     different versions by two or more add-ins (their LoadFromResolveHandler-
     reachable bundles or unresolved demands).

The report distinguishes:
  - Case 1 fatal: guaranteed FileNotFoundException at runtime (the kind of bug
    PR #23287 documented — host version lower than what an add-in needs, with
    no bundled fallback). Currently shows the ModelContextProtocol family for
    Uno.UI.App.Mcp.
  - Case 1 latent: works today through LoadFromResolveHandler, but Default ALC
    ends up carrying two versions of the same simple name. Cross-component code
    that tries to mix them gets TypeLoadException. Currently shows
    Microsoft.IO.RecyclableMemoryStream (Settings) and Uno.DevTools.Telemetry
    (HotDesign).
  - Case 2: load-order non-determinism. Empty under the current manifest.

Also adds Uno.WinUI.DevServer to the test's PackageReference set so the host's
runtime payload is restored and walked alongside the three add-ins.
carldebilly added a commit that referenced this pull request May 22, 2026
…sharing

PR #23287 isolated add-in loading into a custom AssemblyLoadContext to fix three
cross-major-version FileNotFoundException scenarios (Kiota, Mcp, ModelContextProtocol).
The isolation worked for those scenarios but introduced a structural fragility:
add-ins registering their types in the host's IServiceCollection (which lives in the
default ALC) cannot reliably be resolved by other add-ins that reference the same
types — the cross-ALC Type identity mismatch surfaces as either FileNotFoundException
during JIT inspection of a constructor signature or InvalidOperationException from DI
("Unable to resolve service for type ..."). The bug is visible to end users as the
Uno Platform Studio overlay never finishing initialization (issue #23304).

Three ALCs coexisted in the host before this change: Default (host + IServiceCollection),
AddInLoadContext (the --addins payload), and the per-applicationId ALC built by
RemoteControlServer.GetAssemblyLoadContext for client-sent processors. Sharing Type
identities across these boundaries is structurally impossible to do reliably — no
amount of probing inside any single ALC can fix it.

Fix: load every add-in via Assembly.LoadFrom directly into the default ALC. All
add-in types — including private contract assemblies physically co-located with one
add-in but absent from every add-in's deps.json — observe a single Type identity,
which is what DI needs to match service registrations with constructor parameters.

The three cross-major-version scenarios that PR #23287 originally fixed remain handled
by the Default.Resolving handler in HostAssemblyResolution.Install + TryBridgeBySimpleName,
which existed independently of the ALC isolation and stays in place. The runtime's
LoadFromResolveHandler also probes the loaded-from directories of every Assembly.LoadFrom'd
assembly, so contract DLLs co-located with one add-in are discoverable from another.

Diagnostic enrichments — both layers route through stdout/stderr so the operator sees
them in the host log:

  * Proactive: AssemblyHelper.Load now walks each loaded add-in's AssemblyRef table
    and warns on version/PKT mismatches against the host's loaded set. The warning
    names the add-in, the misaligned reference, the runtime consequence, and the
    two remediation paths (align the package version, or load the conflicting
    dependency in a private AssemblyLoadContext owned by the add-in). Verbose mode
    via env-var UNO_DEVSERVER_VERBOSE_ADDIN_REFS=1.

  * Reactive: TryBridgeBySimpleName logs info-level when a successful bridge involves
    a version substitution, and warning-level when it returns null — naming the
    same-simple-name variants currently loaded so the operator has a concrete
    starting point.

PKT match in TryBridgeBySimpleName is now asymmetric: a signed request (non-empty
PublicKeyToken) requires a matching loaded PKT, while unsigned requests skip the
check entirely. This is identity validation, not an allow-list — no static trusted
PKT table. The previous symmetric "unsigned request refuses strong-named loaded"
rule was over-conservative and is removed; the unused s_trustedPkts allow-list +
IsTrustedPkt warning are gone with it.

Other simplifications: the UNO_DEVSERVER_DISABLE_ADDIN_ALC kill switch is removed
(no ALC isolation to disable any longer). The Given_AddInLoadContext and
Given_AssemblyHelper unit tests are gone (their subjects no longer exist).

Tests:
  * New cross-add-in regression DevServer_ShouldResolveSharedContractAcrossAddIns_WhenContractOnlyInProviderDirectory
    spins up a real DevServer host with two fixture add-ins (provider shipping
    Uno.Licensing.TestContracts.dll, consumer not), asserts the consumer's IHostedService
    receives the DI-injected contract — verified RED on master and GREEN after the fix.
  * Asymmetric PKT match is locked in by three new TryBridgeBySimpleName tests covering
    signed-mismatch (refused), signed-match (bridged), and unsigned-request (bridged).
  * The existing AddInWithCrossMajorVersionRefs integration test is preserved as
    non-regression for the three scenarios PR #23287 fixed.

CI: a new Linux-only stage (devserver_tests_linux) runs the DevServer test project
independently — fast PR feedback for add-in resolution regressions, no dependency on
the heavier unit_tests stage. The existing Windows unit_tests stage continues to
include the same tests via Uno.UI-UnitTests-only.slnf (with the new fixtures added).

Fixes #23304.
MartinZikmund pushed a commit that referenced this pull request May 28, 2026
Six points from the Copilot review on #23287:

1. AssemblyHelper now loads the top-level add-in via LoadFromAssemblyPath
   instead of LoadFromAssemblyName, so the caller's exact DLL is always what
   ends up in the context. The Default-ALC short-circuit and TPA fallback
   in AddInLoadContext.Load could otherwise silently substitute a
   host-loaded assembly if an add-in's simple name happened to collide.
   Transitive deps still flow through that override as intended.

2. AddInLoadContext.Load now catches FileLoadException and
   BadImageFormatException in addition to FileNotFoundException when
   probing Default.LoadFromAssemblyName. TPA can match an assembly by
   simple name and reject the load on a strong-name / version mismatch —
   exactly the cross-major scenario this class exists for — and we
   shouldn't bubble that out: the add-in's own deps.json may still carry
   a usable copy.

3. The Default.Resolving handler now skips IsDynamic assemblies (so
   reflection-emit / source-generator-emitted assemblies can't be
   coincidentally substituted for a real AssemblyRef) and requires
   PublicKeyToken compatibility (so a strong-named request is never
   bridged to a differently-signed instance — that would be a security-
   relevant identity swap rather than a version mismatch papered over).

4. The eager-load catch in Program's static constructor now writes a
   one-line breadcrumb to stderr (the ILoggerFactory isn't built yet at
   this point) so a regression in the preload step doesn't silently
   disable the safety net.

5. The list of shared-framework OOB DLLs to eager-load is extracted to a
   private static readonly array at class scope, making the contract
   explicit and easier to extend (e.g. Microsoft.Extensions.Configuration.*
   if a future MCP or add-in bump needs it).

6. `using System.Runtime.Loader;` reordered into the System.* block to
   match the project's using-block convention.

All three DevServer integration tests still pass on net10
(DevServer_ShouldStart, DevServer_ShouldStopCleanly, and
DevServer_ShouldStart_WithAddInThatHasCrossMajorVersionFrameworkRefs).
Manual net9 host run against Uno.Sdk 6.7.0-dev.50 + the broken
Uno.Settings.DevServer 1.8.0-dev.125 still reaches 'Now listening on:'
with zero unhandled exceptions and the licensing add-in actively
refreshing tokens.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
MartinZikmund pushed a commit that referenced this pull request May 28, 2026
Two follow-up Copilot review passes on #23287 combined into one commit
with a Conventional-Commits-compliant title (the previous attempt used
`test(devserver) + fix(devserver):` which the Azure pipeline's commit
validator rejected — only a single type is allowed).

Round 2 (test fixture / load-context consistency):

  - Fixture's `ServicesRegistration` is now annotated as
    `[assembly: Uno.Utils.DependencyInjection.ServiceCollectionExtension(typeof(ServicesRegistration))]`
    so the host's `AddFromServiceExtensionAttributes` actually invokes the
    ctor at startup via `Activator.CreateInstance` — the v8.0.0.0
    AssemblyRefs baked into the fixture (Encodings.Web,
    DependencyInjection.Abstractions) get resolved at runtime instead of
    sitting dormant in metadata. Reviewer correctly noted the previous
    static-cctor pattern wouldn't fire from a plain `LoadFromAssemblyPath`
    and the test would have passed even on an unmodified host.

  - Fixture csproj sets `<EnableDynamicLoading>true</EnableDynamicLoading>`
    + adds a `Microsoft.Extensions.DependencyInjection.Abstractions 8.0.2`
    PackageReference so the registration ctor's `IServiceCollection`
    parameter is itself a v8 cross-major AssemblyRef.

  - DevServerTests' assertion message references the correct target name
    `_BuildAndCopyAddInTestFixtures` (was `_CopyAddInTestFixtures`).

  - The test itself is reframed as a runtime-stable positive-outcome
    regression (host loads + activates the add-in + reaches
    `Now listening on:` without an unhandled exception). Current
    .NET 9.0.16 / .NET 10 runtimes lax-bind the simple
    `JavaScriptEncoder.Default` access on their own even without the
    host's fix, so a "must FNF without fix" assertion isn't deterministic
    across runtime point releases. The end-to-end repro under
    D:\Dev\Uno-Pocs\DevServerLicensingRepro\ still covers the
    runtime-strict scenario against the real Kiota / Uno.Settings.DevServer
    payload.

  - AddInLoadContext.Load step 1 now applies the same `IsDynamic` skip
    + `PublicKeyToken` compatibility check that the
    `AssemblyLoadContext.Default.Resolving` handler in Program.cs uses,
    closing the asymmetric identity-swap window the reviewer flagged.

  - AddInLoadContext.Load step 2 also catches `FileLoadException` and
    `BadImageFormatException` in addition to `FileNotFoundException`, so
    a TPA strong-name / version / image mismatch on a shared-framework
    OOB package keeps falling through to the per-add-in deps.json
    resolvers in step 3 instead of bubbling out.

Round 3 (staging + lifecycle / assertion tightening):

  - The fixture Copy step now stages the *entire* fixture bin via a
    `**\*` glob instead of just `*.dll`, `*.pdb` and `*.deps.json` of
    the main assembly. With `EnableDynamicLoading=true` the fixture's
    output directory also contains the private NuGet payloads its
    `.deps.json` points at (e.g. the v8
    Microsoft.Extensions.DependencyInjection.Abstractions.dll); those
    now actually land at the paths `AssemblyDependencyResolver` returns,
    so step 3 of AddInLoadContext.Load has a real graph to consult
    rather than silently no-opping back to step 1.

  - Program.cs: the Resolving handler install + the apphost-dir
    eager-load moved out of a static constructor into an explicit
    `ConfigureAssemblyResolution` method called from the first line of
    `Main`. Any failure inside the install now surfaces as a normal
    exception (logged via stderr) rather than being wrapped in a
    `TypeInitializationException` the first time `Program` is touched,
    which on .NET Core terminates the process with a stack frame that
    points at the type rather than the offending statement.

  - DevServerTests no longer substring-matches on the literal
    `"Unhandled exception"` phrase (which would also match a non-fatal
    logger message containing that text). The assertion is now
    `helper.IsRunning.Should().BeTrue()` after the listening-state log,
    which is the real invariant: a fatal CLR `Unhandled exception`
    banner terminates the host process before `Now listening on:` is
    reached, so a still-alive host past that point covers the
    regression deterministically.

Validation:

  - `dotnet build src/Uno.UI.RemoteControl.DevServer.Tests` on net10:
    0 errors.
  - All 3 DevServer integration tests pass on net10
    (DevServer_ShouldStart, DevServer_ShouldStopCleanly,
    DevServer_ShouldStart_WithAddInThatHasCrossMajorVersionFrameworkRefs).
  - Staged fixture output now contains
    `Microsoft.Extensions.DependencyInjection.Abstractions.dll` next to
    the main fixture DLL (confirming the per-add-in resolver branch is
    actually wired up).
  - Manual net9 host run against the cached Uno.Settings.DevServer
    1.8.0-dev.46 + Uno.WinUI.DevServer 6.7.0-dev.144 still reaches
    `Now listening on:` with 0 unhandled exceptions and the licensing
    add-in actively refreshing tokens.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
MartinZikmund pushed a commit that referenced this pull request May 28, 2026
Two follow-up points from the latest Copilot review pass on #23287:

1. AddInLoadContext.cs:104 — step 2 (the `Default.LoadFromAssemblyName(new
   AssemblyName(name))` fallback through host TPA) now validates the
   loaded assembly's `PublicKeyToken` against the requested one before
   returning. If the request carries a non-empty PKT and the loaded
   assembly's PKT differs (or is unsigned), the call falls through to
   the per-add-in resolvers in step 3 instead of substituting across
   different strong-name identities. Closes the asymmetric identity-swap
   window between step 1 / the Default.Resolving handler (both of which
   already enforce PKT compatibility) and step 2.

2. AssemblyHelper.cs:45 — the `AddInLoadContext` ctor now constructs each
   `AssemblyDependencyResolver` in its own try/catch and emits a stderr
   breadcrumb on failure, rather than letting a single bad add-in path
   abort the whole add-in loading loop via the outer catch in
   `AssemblyHelper.Load`. Restores the per-add-in failure isolation the
   original `Assembly.LoadFrom` loop provided: a corrupt or missing
   `.deps.json` for one add-in no longer prevents the others from loading.
   The per-DLL try/catch in `AssemblyHelper.Load` still surfaces the
   actual load failure for the offending add-in with a meaningful error.

Validation:

  - `dotnet build src/Uno.UI.RemoteControl.DevServer.Tests` on net10:
    0 errors.
  - All 3 DevServer integration tests pass on net10
    (DevServer_ShouldStart, DevServer_ShouldStopCleanly,
    DevServer_ShouldStart_WithAddInThatHasCrossMajorVersionFrameworkRefs).
  - Manual net9 host run against the cached Uno.Settings.DevServer
    1.8.0-dev.46 + Uno.WinUI.DevServer 6.7.0-dev.144 still reaches
    `Now listening on:` with 0 unhandled exceptions and the licensing
    add-in actively refreshing tokens.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
MartinZikmund pushed a commit that referenced this pull request May 28, 2026
…sharing

PR #23287 isolated add-in loading into a custom AssemblyLoadContext to fix three
cross-major-version FileNotFoundException scenarios (Kiota, Mcp, ModelContextProtocol).
The isolation worked for those scenarios but introduced a structural fragility:
add-ins registering their types in the host's IServiceCollection (which lives in the
default ALC) cannot reliably be resolved by other add-ins that reference the same
types — the cross-ALC Type identity mismatch surfaces as either FileNotFoundException
during JIT inspection of a constructor signature or InvalidOperationException from DI
("Unable to resolve service for type ..."). The bug is visible to end users as the
Uno Platform Studio overlay never finishing initialization (issue #23304).

Three ALCs coexisted in the host before this change: Default (host + IServiceCollection),
AddInLoadContext (the --addins payload), and the per-applicationId ALC built by
RemoteControlServer.GetAssemblyLoadContext for client-sent processors. Sharing Type
identities across these boundaries is structurally impossible to do reliably — no
amount of probing inside any single ALC can fix it.

Fix: load every add-in via Assembly.LoadFrom directly into the default ALC. All
add-in types — including private contract assemblies physically co-located with one
add-in but absent from every add-in's deps.json — observe a single Type identity,
which is what DI needs to match service registrations with constructor parameters.

The three cross-major-version scenarios that PR #23287 originally fixed remain handled
by the Default.Resolving handler in HostAssemblyResolution.Install + TryBridgeBySimpleName,
which existed independently of the ALC isolation and stays in place. The runtime's
LoadFromResolveHandler also probes the loaded-from directories of every Assembly.LoadFrom'd
assembly, so contract DLLs co-located with one add-in are discoverable from another.

Diagnostic enrichments — both layers route through stdout/stderr so the operator sees
them in the host log:

  * Proactive: AssemblyHelper.Load now walks each loaded add-in's AssemblyRef table
    and warns on version/PKT mismatches against the host's loaded set. The warning
    names the add-in, the misaligned reference, the runtime consequence, and the
    two remediation paths (align the package version, or load the conflicting
    dependency in a private AssemblyLoadContext owned by the add-in). Verbose mode
    via env-var UNO_DEVSERVER_VERBOSE_ADDIN_REFS=1.

  * Reactive: TryBridgeBySimpleName logs info-level when a successful bridge involves
    a version substitution, and warning-level when it returns null — naming the
    same-simple-name variants currently loaded so the operator has a concrete
    starting point.

PKT match in TryBridgeBySimpleName is now asymmetric: a signed request (non-empty
PublicKeyToken) requires a matching loaded PKT, while unsigned requests skip the
check entirely. This is identity validation, not an allow-list — no static trusted
PKT table. The previous symmetric "unsigned request refuses strong-named loaded"
rule was over-conservative and is removed; the unused s_trustedPkts allow-list +
IsTrustedPkt warning are gone with it.

Other simplifications: the UNO_DEVSERVER_DISABLE_ADDIN_ALC kill switch is removed
(no ALC isolation to disable any longer). The Given_AddInLoadContext and
Given_AssemblyHelper unit tests are gone (their subjects no longer exist).

Tests:
  * New cross-add-in regression DevServer_ShouldResolveSharedContractAcrossAddIns_WhenContractOnlyInProviderDirectory
    spins up a real DevServer host with two fixture add-ins (provider shipping
    Uno.Licensing.TestContracts.dll, consumer not), asserts the consumer's IHostedService
    receives the DI-injected contract — verified RED on master and GREEN after the fix.
  * Asymmetric PKT match is locked in by three new TryBridgeBySimpleName tests covering
    signed-mismatch (refused), signed-match (bridged), and unsigned-request (bridged).
  * The existing AddInWithCrossMajorVersionRefs integration test is preserved as
    non-regression for the three scenarios PR #23287 fixed.

CI: a new Linux-only stage (devserver_tests_linux) runs the DevServer test project
independently — fast PR feedback for add-in resolution regressions, no dependency on
the heavier unit_tests stage. The existing Windows unit_tests stage continues to
include the same tests via Uno.UI-UnitTests-only.slnf (with the new fixtures added).

Fixes #23304.
MartinZikmund pushed a commit that referenced this pull request May 28, 2026
…d-graph walk

The first iteration scanned every DLL in each add-in's tools/* + lib/* and compared
AssemblyRef tables flatly. That model overcounts: it includes client-side DLLs in
lib/net9.0/ that the DevServer host never loads (MEA v9.8 from HotDesign was a
false positive of this kind), and it ignores intra-add-in forward rolls (Settings
internally referencing SkiaSharp v2.88 in one DLL and v3.119 in another is not a
conflict — the v3.119 DLL it ships is what gets loaded, and the v2.88 ref forward-
rolls cleanly).

The new model walks the actual runtime load graph instead:

  1. The host's effective TPA is computed from the .NET shared frameworks
     (Microsoft.NETCore.App + Microsoft.AspNetCore.App per the host's runtimeconfig.json)
     plus the bundled host deps under tools/rc/host/net10.0/.
  2. For each add-in, the BFS root is the primary server DLL declared via the
     tools/devserver/*.Server.dll or tools/<tfm>/server/*.Server.dll convention.
  3. At every visited DLL, each AssemblyRef is resolved:
       host TPA hit          → forward-roll OK (don't walk into host DLLs)
       host TPA hit, low ver → bridge would refuse; check loadable dir for bundled
                               copy. If found → case 1 latent (works via
                               LoadFromResolveHandler, pollutes Default ALC).
                               If not → case 1 fatal (guaranteed FNFE).
       no host hit, bundled  → enqueue the bundled DLL, record this add-in's
                               contribution for cross-add-in comparison.
       no host hit, unbundled → record as unresolved (potential case 2 trigger
                                or surprise FNFE at runtime).
  4. Cross-add-in case 2 = same simple name absent from host TPA, contributed at
     different versions by two or more add-ins (their LoadFromResolveHandler-
     reachable bundles or unresolved demands).

The report distinguishes:
  - Case 1 fatal: guaranteed FileNotFoundException at runtime (the kind of bug
    PR #23287 documented — host version lower than what an add-in needs, with
    no bundled fallback). Currently shows the ModelContextProtocol family for
    Uno.UI.App.Mcp.
  - Case 1 latent: works today through LoadFromResolveHandler, but Default ALC
    ends up carrying two versions of the same simple name. Cross-component code
    that tries to mix them gets TypeLoadException. Currently shows
    Microsoft.IO.RecyclableMemoryStream (Settings) and Uno.DevTools.Telemetry
    (HotDesign).
  - Case 2: load-order non-determinism. Empty under the current manifest.

Also adds Uno.WinUI.DevServer to the test's PackageReference set so the host's
runtime payload is restored and walked alongside the three add-ins.
dr1rrb pushed a commit that referenced this pull request Jul 3, 2026
…ontext

fix(devserver): isolate add-ins in a custom AssemblyLoadContext
dr1rrb added a commit that referenced this pull request Jul 3, 2026
fix(devserver): bridge cross-major AssemblyRef requests in host (backport #23287 + #23308)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants