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
3 changes: 2 additions & 1 deletion eng/Signing.props
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,8 @@
<!-- We don't need to code sign most .js files because they are coming from other repos and are already signed -->
<FileExtensionSignInfo Update=".js" CertificateName="None" />

<FileSignInfo Include="Microsoft.DotNet.HotReload.WebAssembly.Browser.lib.module.js" CertificateName="MicrosoftDotNet500" />
<FileSignInfo Include="dotnet-watch-browser-tools.js" CertificateName="MicrosoftDotNet500" />
<FileSignInfo Include="Microsoft.NET.Sdk.BlazorWeb.DotNetWatch.lib.module.js" CertificateName="MicrosoftDotNet500" />

<!-- Skip signing .py files because they are already signed -->
<FileExtensionSignInfo Update=".py" CertificateName="None" />
Expand Down
138 changes: 137 additions & 1 deletion src/Dotnet.Watch/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ Reload).
| `dotnet-watch` | The tool executable and CLI surface. Its command/options are defined in `CommandLine/DotnetWatchCommandDefinition.cs`. |
| `Watch` (`Microsoft.DotNet.HotReload.Watch`) | Core watcher library: file-set computation, process launching, Hot Reload, app models. |
| `DotNetWatchTasks` | MSBuild task bundled into the tool for design-time file collection. |
| `DotNetDeltaApplier`, `Web.Middleware`, `BrowserRefresh` | Assemblies **injected into the running app** via `DOTNET_STARTUP_HOOKS`. |
| `DotNetDeltaApplier`, `Web.Middleware`, `BrowserRefresh` | Assemblies injected into compatible app models through the hosting-startup path. |
| `HotReloadAgent.*`, `HotReloadClient`, `AspireService` | Shared code consumed via `.projitems`.|

## Conventions & gotchas
Expand All @@ -26,6 +26,142 @@ Reload).
named-pipe protocol; Blazor WASM uses JSON over WebSocket. Each protocol has its
own `HotReloadClient` subclass (e.g. `DefaultHotReloadClient`,
`WebAssemblyHotReloadClient`); a new app model may need its own implementation.
- **The browser-tools provider owns the browser protocol and replay
state.** Its fixed `/_framework/dotnet-browser-tools` endpoints live under
[`HotReloadClient/Web`](HotReloadClient/Web) and are reduced to `connect` (WebSocket)
`clear-cache`, and the non-executable `hot-reload-settings.json`; the provider serves no
JavaScript, no session descriptor, no protocol version, and no HTTP replay. Most
application hosts reach it through the
shared-framework-only [`BrowserToolsForwarder`](Web.Middleware/BrowserToolsForwarder.cs)
installed by the hosting-startup path. Standalone Blazor WebAssembly is the exception:
it is served by the Blazor Gateway, a separate YARP host that does not activate ASP.NET
Core hosting startups, so
[`BlazorWebAssemblyAppModel`](Watch/AppModels/BlazorWebAssemblyAppModel.cs) configures a
gateway reverse-proxy route through `ReverseProxy__*` environment variables instead. Keep
destinations fixed to the trusted loopback provider address, the route root-relative, and
the encrypted shared-secret WebSocket subprotocol intact. Do not add YARP to arbitrary
applications.
- **The browser authenticates the provider, so the provider must not serve code.** The
*build* owns the browser-tools RSA keypair:
[`EnsureDotNetWatchBrowserToolsKey`](../StaticWebAssetsSdk/Tasks/EnsureDotNetWatchBrowserToolsKey.cs)
writes both halves to deterministic paths under the browser-facing project's intermediate
output, and
only the public half is pinned into an application-hosted configuration module. There is
no watch-to-MSBuild property flow: `dotnet watch` reads the private half back through
[`BrowserToolsBuildOutputs`](Watch/Browser/BrowserToolsBuildOutputs.cs) when each browser
connects. This lets the per-project provider bind before `dotnet run` builds the
application, avoids a separate watcher build, and observes key rotation after `Clean`.
The provider validates and imports the current matching pair only long enough to decrypt
that connection's credential, so a provider can never supply the key that authenticates
it. The existing `EnableHotReloadInRuntimeConfigDevFile` SDK property controls whether
the build generates the browser-tools assets and defaults to `true` for Debug builds.
When present, the initializer fetches the provider-owned
`/_framework/dotnet-browser-tools/hot-reload-settings.json` route and starts the client
only for `{ "hotReload": true }`; the response is non-executable, contains no key
material, and is served with `Cache-Control: no-store`. The ASP.NET Core disabled
fallback for non-watch launches is supplied by the runtime/host, not by the SDK or
`dotnet watch`. Watch never activates the client by mutating an application file. Hosted
WebAssembly uses the client as the browser-tools project even though the server remains
the launching project.
See
[`Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets`](../StaticWebAssetsSdk/Targets/Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets).
Never move executable browser-tools code back into the provider, never let the private
key or the browser's shared secret reach a build property, an application asset or a log,
and keep the generated assets build only.
- **Replay lives in the WebSocket handshake.** The provider sends the current snapshot as
the first message on an accepted connection and releases live messages for that
connection only after the browser acknowledges it, so there is no wire-level generation
id. The internal epoch in
[`AbstractBrowserRefreshServer`](HotReloadClient/Web/AbstractBrowserRefreshServer.cs)
exists only to drop work produced by a superseded client; do not surface it on the wire.
- **Activation is app-model-specific, but the browser client is shared.** MVC and Razor
Pages use
[`BrowserRefreshTagHelperComponent`](Web.Middleware/BrowserRefreshTagHelperComponent.cs)
through the built-in body TagHelper; it never runs for `.razor` root components, so
Blazor apps rendered on the server rely on the Web SDK's build-only `afterWebStarted`
initializer instead. Standalone and hosted Blazor WASM use a build-only watch activation
initializer added by the WASM SDK for every supported target
framework; from `onRuntimeConfigLoaded` it sets the watch-private activation variable
`__DOTNET_WATCH_BROWSER_TOOLS` and `DOTNET_MODIFIABLE_ASSEMBLIES`, and from
`onRuntimeReady` it imports the application-hosted configuration module. Blazor guarantees
every `onRuntimeConfigLoaded`
callback runs before any `onRuntimeReady` callback and passes the same config object to
all initializers, so pass *activation state* between initializer modules through that
config rather
than through `globalThis` or a cross-module import: initializer load order is unspecified
and each module's URL is subject to fingerprinting. Do not use
`__ASPNETCORE_BROWSER_TOOLS` as that handshake, because .NET 8 interprets it as a request
to load the removed application-hosted `blazor-hotreload.js`. On .NET 10+ the
same WebAssembly watch initializer loads the SDK Hot Reload agent assembly and applies managed
updates; older target frameworks fall back to the runtime's own
`window.Blazor._internal.applyHotReload`. The configuration module may also be imported
by a host activation path; duplicate activation is absorbed by module caching and the
client's injection sentinel.
Static/custom HTML that has no supported
initializer requires user-provided activation; do not add build-time `index.html`
rewriting. Apps that disable `StaticWebAssetsEnabled` or `JSModulesEnabled` cannot host
the client and therefore cannot receive browser tools.
- **The replay handshake waits for the Hot Reload agent through a `globalThis`
rendezvous.** The provider sends the replay snapshot exactly once, so applying it before
the agent is ready would drop those updates while the browser still acknowledged success.
The WebAssembly watch initializer publishes
`globalThis.__DOTNET_WATCH_HOT_RELOAD_AGENT = { ready, setReady }` before its first
`await`, attaches the SDK agent's apply functions directly to that shared object, and
resolves readiness in a `finally`; the browser tools client awaits it before replaying.
This is the one case that cannot use the runtime config object, because the value is a
promise that only exists once `onRuntimeReady` has started. Keep the rendezvous helpers in
the [WebAssembly initializer](../WasmSdk/Sdk/DotNetWatch/Microsoft.NET.Sdk.WebAssembly.DotNetWatch.lib.module.js.template)
and the Static Web Assets SDK's `dotnet-watch-browser-tools.js` in sync. The wait is
bounded and best effort for older runtimes that install the apply API through their own
bootstrap, or pages that never boot WebAssembly, so they degrade to a logged warning
instead of a reload loop.
- **A browser that cannot apply an update must fail the acknowledgement.** `dotnet watch`
treats an acknowledged update as applied, so any path that answers with an empty log is
indistinguishable from a successful apply and produces "C# and Razor changes applied"
while nothing changed. [`WebAssemblyHotReload`](HotReloadAgent.WebAssembly.Browser/WebAssemblyHotReload.cs)
therefore records why the agent was not created and throws that reason from
`ApplyHotReloadDeltas` instead of returning an empty log; the throw surfaces through
`[JSExport]`, the client reports `success: false`, and
[`RunningProjectsManager`](Watch/HotReload/RunningProjectsManager.cs) suppresses both the
applied message and the Aspire notification when any client's apply task failed. Replay is
the deliberate exception: an apply failure while initializing is logged as an error but
does not fail initialization, because the provider disposes a connection whose
initialization reported failure and the client reloads on close, which would loop.
- **.NET 9 WebAssembly is the one target framework that needs
`__ASPNETCORE_BROWSER_TOOLS`.** Its `WebAssemblyHotReload` creates the Hot Reload agent
only inside `InitializeAsync`, which the runtime calls only when that variable is set, so
without it nothing is applied. The
[initializer template](../WasmSdk/Sdk/DotNetWatch/Microsoft.NET.Sdk.WebAssembly.DotNetWatch.lib.module.js.template)
therefore has a `__RUNTIME_HOT_RELOAD_AGENT__` placeholder that
[`Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets`](../StaticWebAssetsSdk/Targets/Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets)
substitutes with `true` only when `TargetFrameworkVersion` equals `9.0`. .NET 8 must not
get it (it would import the removed `blazor-hotreload.js`) and .NET 10+ must not get it
(the SDK ships its own agent). That initialization path also fetches
`/_framework/blazor-hotreload` for previously applied deltas, so
[`HostingStartup`](Web.Middleware/HostingStartup.cs) answers that route locally with an
empty update array: replay belongs to the authenticated WebSocket, and serving deltas over
an unauthenticated route would be a security regression. The route is not forwarded to the
provider, and its only consumer is the .NET 9 WebAssembly runtime.
- **The forwarder preserves the provider's pre-upgrade rejection.** The provider answers an
invalid encrypted subprotocol with a status-only HTTP 400 *before* accepting the
WebSocket. [`BrowserToolsForwarder`](Web.Middleware/BrowserToolsForwarder.cs) opts into
`ClientWebSocketOptions.CollectHttpResponseDetails` and, on a failed upgrade, relays
`ClientWebSocket.HttpStatusCode` only when it is an error status, falling back to 502
otherwise. The narrowing matters: that property is recorded before the upgrade response is
validated, so a handshake that failed *after* the provider switched protocols reports 101,
and relaying it would make the application announce an upgrade it never performed. Both
members are .NET 7+ while the
assembly targets `net6.0`, so they are reached through cached reflection. Do not widen this
into a blanket status mapping and do not swallow genuine transport failures.
- **Server hosting startup is intentionally thin.**
[`HostingStartup.cs`](Web.Middleware/HostingStartup.cs) registers only the MVC/Razor
TagHelper component and the reserved forwarder for the modern path. The BrowserRefresh
assembly still appears in `DOTNET_STARTUP_HOOKS` so the out-of-application hosting
startup assembly can be resolved, but its
[`StartupHook`](Web.Middleware/StartupHook.cs) is a no-op. Managed server updates
continue to use the separate `Microsoft.Extensions.DotNetDeltaApplier` startup hook.
Do not restore response rewriting, application-hosted browser scripts, or parallel
legacy endpoints.
- **`CompilationHandler` drives Roslyn** via
`Microsoft.CodeAnalysis.ExternalAccess.HotReload`; unsupported edits fall
back to a full rebuild + restart.
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,6 @@
<Import Project="..\HotReloadAgent.Data\Microsoft.DotNet.HotReload.Agent.Data.projitems" Label="Shared" />

<ItemGroup>
<Content Include="wwwroot\**\*.*" CopyToOutputDirectory="PreserveNewest" />
<InternalsVisibleTo Include="DynamicProxyGenAssembly2" Key="$(MoqPublicKey)" />
</ItemGroup>

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -34,15 +34,6 @@ public readonly struct LogEntry
public int Severity { get; init; }
}

/// <summary>
/// For framework use only.
/// </summary>
internal sealed class Update
{
public int Id { get; set; }
public Delta[] Deltas { get; set; } = default!;
}

/// <summary>
/// For framework use only.
/// </summary>
Expand All @@ -55,20 +46,34 @@ public readonly struct Delta
public int[] UpdatedTypes { get; init; }
}

private static readonly JsonSerializerOptions s_jsonSerializerOptions = new(JsonSerializerDefaults.Web);

private static bool s_initialized;
private static HotReloadAgent? s_hotReloadAgent;

/// <summary>
/// Why <see cref="s_hotReloadAgent"/> is null, so that a caller that asks for a managed code update
/// gets an actionable error instead of an update that is acknowledged but silently not applied.
/// </summary>
private static string? s_unavailableReason;

[JSExport]
[SupportedOSPlatform("browser")]
public static async Task InitializeAsync(string baseUri)
public static Task InitializeAsync(string baseUri)
{
if (MetadataUpdater.IsSupported && Environment.GetEnvironmentVariable("__ASPNETCORE_BROWSER_TOOLS") == "true" &&
OperatingSystem.IsBrowser())
if (!OperatingSystem.IsBrowser())
{
s_unavailableReason = "the runtime is not running in a browser";
}
else if (Environment.GetEnvironmentVariable("__DOTNET_WATCH_BROWSER_TOOLS") != "true")
{
s_unavailableReason = "the app was not started by 'dotnet watch'";
}
else if (!MetadataUpdater.IsSupported)
{
// Reached when the app was built without the runtime assets that support metadata updates,
// which happens with stale or mismatched build output. Applying an update would be a no-op.
s_unavailableReason = "this build of the app does not support runtime metadata updates (System.Reflection.Metadata.MetadataUpdater.IsSupported is false). Rebuild the app and reload the browser";
}
else
{
s_initialized = true;

// TODO: Implement hotReloadExceptionCreateHandler: https://github.com/dotnet/sdk/issues/51056
var agent = new HotReloadAgent(assemblyResolvingHandler: null, hotReloadExceptionCreateHandler: null);

Expand All @@ -77,67 +82,24 @@ public static async Task InitializeAsync(string baseUri)
{
throw new InvalidOperationException("Hot Reload agent already initialized");
}

await ApplyPreviousDeltasAsync(agent, baseUri);
}
}

private static async ValueTask ApplyPreviousDeltasAsync(HotReloadAgent agent, string baseUri)
{
string errorMessage;

using var client = new HttpClient()
{
BaseAddress = new Uri(baseUri, UriKind.Absolute)
};

try
{
var response = await client.GetAsync("/_framework/blazor-hotreload");
if (response.IsSuccessStatusCode)
{
var deltasJson = await response.Content.ReadAsStringAsync();
var updates = deltasJson != "" ? JsonSerializer.Deserialize<Update[]>(deltasJson, s_jsonSerializerOptions) : null;
if (updates == null)
{
agent.Reporter.Report($"No previous updates to apply.", AgentMessageSeverity.Verbose);
return;
}

var i = 1;
foreach (var update in updates)
{
agent.Reporter.Report($"Reapplying update {i}/{updates.Length}.", AgentMessageSeverity.Verbose);

agent.ApplyManagedCodeUpdates(
update.Deltas.Select(d => new RuntimeManagedCodeUpdate(Guid.Parse(d.ModuleId, CultureInfo.InvariantCulture), d.MetadataDelta, d.ILDelta, d.PdbDelta, d.UpdatedTypes)));

i++;
}

return;
}

errorMessage = $"HTTP GET '/_framework/blazor-hotreload' returned {response.StatusCode}";
}
catch (Exception e)
{
errorMessage = e.ToString();
}

agent.Reporter.Report($"Failed to retrieve and apply previous deltas from the server: {errorMessage}", AgentMessageSeverity.Error);
// Updates applied before the browser connected are replayed by the browser tools client.
return Task.CompletedTask;
}

private static HotReloadAgent? GetAgent()
=> s_hotReloadAgent ?? (s_initialized ? throw new InvalidOperationException("Hot Reload agent not initialized") : null);
/// <summary>
/// The agent, or an exception explaining why managed code updates cannot be applied. Never reports
/// success without applying, because dotnet-watch reports an update as applied when the browser
/// acknowledges it without an error.
/// </summary>
private static HotReloadAgent GetRequiredAgent()
=> s_hotReloadAgent ?? throw new InvalidOperationException(
$"Unable to apply managed code updates because {s_unavailableReason ?? "the Hot Reload agent has not been initialized"}.");

private static LogEntry[] ApplyHotReloadDeltas(Delta[] deltas, int loggingLevel)
{
var agent = GetAgent();
if (agent == null)
{
return [];
}
var agent = GetRequiredAgent();

agent.ApplyManagedCodeUpdates(
deltas.Select(d => new RuntimeManagedCodeUpdate(Guid.Parse(d.ModuleId, CultureInfo.InvariantCulture), d.MetadataDelta, d.ILDelta, d.PdbDelta, d.UpdatedTypes)));
Expand All @@ -152,7 +114,7 @@ private static LogEntry[] ApplyHotReloadDeltas(Delta[] deltas, int loggingLevel)
[SupportedOSPlatform("browser")]
public static string GetApplyUpdateCapabilities()
{
return GetAgent()?.Capabilities ?? "";
return s_hotReloadAgent?.Capabilities ?? "";
}

[JSExport]
Expand Down
Loading
Loading