Skip to content

Unify dotnet watch browser tools activation and forwarding - #56118

Merged
javiercn merged 27 commits into
mainfrom
javiercn-browser-tools-combined-review
Sep 21, 2026
Merged

javiercn merged 27 commits into
mainfrom
javiercn-browser-tools-combined-review

Conversation

@javiercn

@javiercn javiercn commented Sep 3, 2026 •

Copy link
Copy Markdown
Member

Summary

This change unifies how applications running under dotnet watch load browser tools and communicate with the watch process.

Browser tooling is produced as development-time application assets. The browser loads those assets from the application, opens an authenticated WebSocket through the application origin, and exchanges Hot Reload updates, static-file updates, reload requests, acknowledgements, and diagnostics with a provider hosted by dotnet watch.

The design supports MVC, Razor Pages, Blazor server rendering, standalone WebAssembly, and hosted WebAssembly across .NET 8-11.

Goals

  • Use one browser-tools client and session model across supported web application types.
  • Serve executable browser code from the application build.
  • Authenticate the provider associated with that build.
  • Deliver updates produced before a browser connects before delivering live updates.
  • Keep multiple browser windows synchronized with the same application baseline.
  • Reset replay state when a rebuild or restart establishes a new baseline.
  • Preserve the hosting models used by ASP.NET Core applications, historical blazor-devserver, and the standalone WebAssembly Gateway.
  • Report browser-side update failures back to dotnet watch.

Non-goals

  • Browser tooling is not included in publish output.
  • The provider is not a general-purpose static-file server.
  • The protocol does not expose generation or update identifiers to the browser.
  • This change does not alter how Roslyn computes managed-code deltas.

Architecture

The system has four participants:

Participant Responsibility
Application build Produces the initializer, browser client, and session configuration as build-only Static Web Assets
Application host Serves the application assets and forwards the browser-tools route to the provider
Browser client Authenticates the provider, applies replay and live commands, and reports results
dotnet watch provider Owns the session key, browser connections, retained updates, and baseline lifecycle
flowchart LR
    Watch[dotnet watch] -->|public key and activation properties| Build[Application build]
    Build -->|initializer, client, config| App[Application host]
    Browser[Browser client] -->|load trusted assets| App
    Browser -->|same-origin WebSocket| App
    App -->|forward browser-tools route| Provider[Watch provider]
    Watch -->|publish updates| Provider
    Provider -->|replay and live commands| Browser
    Browser -->|acknowledgements and diagnostics| Provider
Loading

The application build and provider form one browser-tools session. BrowserRefreshServerFactory creates one ephemeral RSA keypair per watch invocation before project evaluation. Only the public key enters MSBuild; the private key remains in the watch process. Each supported web project has its own provider and loopback address while providers in the same invocation share the invocation trust domain.

Build contract

dotnet watch reserves two global MSBuild properties and applies them consistently to evaluation and build:

Property Meaning
DotNetWatchBrowserTools Indicates that browser tooling is active for this watch build
DotNetWatchBrowserToolsPublicKey Base64 X.509 SubjectPublicKeyInfo for the invocation key

The public-key property is empty when browser refresh is suppressed, preventing browser-tool assets from being generated without a provider.

The Static Web Assets SDK generates three assets under the project's intermediate output:

Asset Purpose
SDK-specific initializer Starts browser tooling at the correct framework lifecycle point
Shared browser client Implements connection, replay, live commands, CSS refresh, and diagnostics
Generated configuration module Pins the provider public key and fixed same-origin routes

The assets use AssetKind=Build and CopyToPublishDirectory=Never. They participate in the normal Static Web Assets endpoint and fingerprinting pipeline but are not published.

Application types activate the same client through different lifecycle hooks:

Application type Activation
MVC and Razor Pages Body TagHelper component imports the generated configuration module
Blazor server rendering Web SDK afterWebStarted initializer
Standalone and hosted WebAssembly WebAssembly SDK initializer after runtime configuration

Provider HTTP contract

The browser uses a root-relative route through the application origin:

/_framework/dotnet-browser-tools

The provider exposes only:

Method/transport Path Behavior
WebSocket /connect Authenticates and establishes a browser session
HTTP /clear-cache Returns 204 with Clear-Site-Data: "cache" for static-asset refresh

All other provider paths return 404. Executable JavaScript and replay data are not provider HTTP resources.

Application routing

The browser always connects through the application origin. The application routes the reserved path to the loopback provider:

  • ASP.NET Core applications and historical blazor-devserver load the hosting-startup assembly and use BrowserToolsForwarder.
  • The standalone WebAssembly Gateway does not activate ASP.NET Core hosting startups, so its app model supplies an equivalent YARP ReverseProxy__* route.
  • The standalone WebAssembly app model configures both forms; the selected development host consumes the applicable one.

The forwarder copies ordinary request and response headers while excluding hop-by-hop headers. For WebSockets it pumps frames in both directions and preserves deliberate provider handshake errors, such as authentication 400 responses. Upstream transport failures remain 502.

flowchart LR
    Browser -->|wss://application/_framework/dotnet-browser-tools/connect| Host{Application host}
    Host -->|ASP.NET Core hosting startup| Forwarder[BrowserToolsForwarder]
    Host -->|Standalone Gateway route| Gateway[YARP reverse proxy]
    Forwarder --> Provider[Loopback provider]
    Gateway --> Provider
Loading

Connection authentication

  1. The browser generates a random 32-byte secret.
  2. It encrypts the secret with RSA-OAEP/SHA-256 using the public key pinned into the application build.
  3. It offers the encrypted value as the WebSocket subprotocol.
  4. The provider decrypts the value before accepting the upgrade.
  5. Missing, malformed, or undecryptable credentials receive HTTP 400 and never obtain a socket.
  6. The provider echoes the plaintext secret in the first message.
  7. The browser compares the echo with its generated secret before accepting the session.
sequenceDiagram
    participant B as Browser
    participant A as Application route
    participant P as Watch provider

    B->>B: Generate random secret
    B->>B: Encrypt with build-pinned public key
    B->>A: WebSocket handshake with encrypted subprotocol
    A->>P: Forward handshake
    P->>P: Decrypt with invocation private key
    alt Invalid credential
        P-->>B: HTTP 400
    else Valid credential
        P-->>B: WebSocket 101
        P->>B: InitializeSession(secret, retained updates)
        B->>B: Verify echoed secret
        B-->>P: Initialization result and diagnostics
    end
Loading

Session initialization and update ordering

Each browser connection captures a snapshot of retained managed updates when it is registered. The provider sends that snapshot in InitializeSession and waits for the browser to acknowledge it. Live messages for that connection wait on the initialization result.

A single state guard protects:

  • the active connection list;
  • retained update batches; and
  • the current baseline epoch.

Registering a connection with its replay snapshot and appending an update with its live-recipient snapshot are atomic relative to each other. This establishes the central ordering invariant:

For a given baseline, each browser receives each managed update exactly once: either in its initialization replay or as a live update, never both and never neither.

No wire-level update ID is needed to deduplicate replay from live delivery.

Opening a second browser

sequenceDiagram
    participant W as dotnet watch
    participant P as Provider
    participant A as Browser A
    participant B as Browser B

    A->>P: Connect
    P-->>A: InitializeSession([])
    A-->>P: Success

    W->>P: Publish delta 1
    P->>P: Retain delta 1
    P-->>A: Delta 1 live
    A-->>P: Applied

    B->>P: Connect
    P-->>B: InitializeSession([delta 1])
    B-->>P: Replay applied

    W->>P: Publish delta 2
    P->>P: Retain delta 2
    par Live delivery
        P-->>A: Delta 2
    and
        P-->>B: Delta 2
    end
Loading

Browser A reaches the current state through two live updates. Browser B reaches the same state through one replayed update and one live update.

Baseline lifecycle

A baseline is the application binary/static-asset state against which incremental updates were produced. Retained updates are valid only for that baseline.

When a WebAssembly client is created for a rebuilt application, the provider resets its session state:

  1. Clear retained updates.
  2. Increment an internal epoch.
  3. Close connections associated with the old baseline.
  4. Let browsers reload against the rebuilt application.
  5. Drop any late update produced by a client carrying the prior epoch.
sequenceDiagram
    participant W as dotnet watch
    participant P as Provider
    participant A as Application
    participant B as Browsers

    W->>P: Publish delta 1 for baseline N
    P-->>B: Apply delta 1
    W->>A: Rebuild/restart
    Note over A: Baseline N+1 binaries contain change 1
    W->>P: ResetUpdates()
    P->>P: Clear replay and increment epoch
    P-->>B: Close old-baseline connections
    B->>A: Reload application
    B->>P: Connect for baseline N+1
    P-->>B: InitializeSession([])
    W->>P: Publish delta 2 for baseline N+1
    P-->>B: Apply delta 2
Loading

Delta 1 is not replayed after restart because it is already present in the new binaries.

Browser command handling

After initialization, the shared client handles these message classes:

Message Browser behavior
ApplyManagedCodeUpdates Apply runtime deltas and return success plus agent logs
UpdateStaticFile Refresh matching CSS in place; reload for unsupported assets
Reload Reload the page
Wait Show that the application is rebuilding
RefreshBrowser Use Blazor refresh integration when available, otherwise reload
ReportDiagnostics Display or clear compilation diagnostics

Connections are processed independently, so one browser waiting to initialize does not block delivery to other initialized browsers. Per-connection messages remain ordered.

If the application restarts and the proxied socket closes before a reload command arrives, the browser polls its application-hosted configuration module. Once the application is available again, it reloads the page and creates a session for the new baseline.

WebAssembly compatibility

The client dispatches managed updates through the Hot Reload API appropriate to the target framework:

Target Agent behavior
.NET 8 Uses the runtime's lazy legacy apply API; __ASPNETCORE_BROWSER_TOOLS remains unset
.NET 9 Enables the runtime's built-in Hot Reload agent and locally answers its compatibility probe with JSON []
.NET 10+ Uses the SDK-provided WebAssembly Hot Reload agent

The .NET 9 compatibility endpoint does not carry replay data. Replay remains on the authenticated WebSocket.

The browser waits for the applicable delta API before replaying retained updates. If the SDK agent cannot be created—for example because runtime metadata updates are unavailable—the managed export throws an actionable error. The browser returns success: false for live updates, and watch-side success messages and applied notifications are suppressed when the client reports failure.

Failure behavior

Failure Result
Missing or invalid WebSocket credential Provider rejects handshake with HTTP 400
Provider unavailable through application route Application returns 502
Initialization payload invalid or authentication echo mismatched Browser closes the connection
Replay apply problem Browser reports diagnostics to watch while retaining the connection for reload/CSS/diagnostic commands
Live managed update cannot be applied Browser returns failure; watch reports the update batch as failed
Application restart closes the socket Browser waits for the app-hosted module to return, then reloads
Update belongs to a superseded baseline epoch Provider discards it

Scope and ownership

  • BrowserRefreshServerFactory owns the invocation-scoped key and per-project providers.
  • AbstractBrowserRefreshServer owns connection state, replay retention, ordering, delivery, and baseline epochs.
  • BrowserConnection owns one socket and its initialization/replay state.
  • BrowserToolsForwarder and Gateway configuration adapt the application host to the provider.
  • Static Web Assets targets own generation and registration of trusted browser modules.
  • Web and WebAssembly initializers own framework lifecycle activation.
  • WebAssemblyHotReloadClient converts watch update batches into browser protocol messages.

Validation

Validation class Result
Full redist build Passed with 0 warnings and 0 errors
Isolated .NET 8-11 and mixed-TFM applications 34/34 restored and built
Standalone browser scenarios .NET 8, 9, 10, and 11 passed
Browser-refresh inactivity Ordinary run and suppressed-refresh scenarios passed
Gateway routing discriminator Route-only active; forwarder-only inactive; combined active
Complete Playwright matrix 34/34 passed with no browser/page errors
Process cleanup No remaining application processes

The active browser scenarios covered application-hosted executable assets, a valid build-pinned RSA-2048 key, authenticated same-origin /connect, rejection of invalid credentials, 404 for non-contract provider endpoints, observable managed and CSS updates, stable host processes, and nonempty runtime apply capabilities.

@javiercn javiercn changed the title [Combined review] Unify browser tools activation and forwarding [Combined review] Simplify browser tools to the provider contract Sep 3, 2026
@javiercn javiercn changed the title [Combined review] Simplify browser tools to the provider contract Unify dotnet watch browser tools activation and forwarding Sep 8, 2026
@javiercn
javiercn marked this pull request as ready for review September 8, 2026 09:39
Copilot AI lite review requested due to automatic review settings September 8, 2026 09:39
@javiercn
javiercn force-pushed the javiercn-browser-tools-combined-review branch from e75615c to fb1d854 Compare September 8, 2026 09:52

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.

🟡 Changes recommended

The hosting startup forwards browser-tools routes using case-insensitive path matching even though the provider/router compares paths case-sensitively, which can intercept casing-variant paths that the provider will treat as unknown.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

This PR unifies how dotnet watch enables browser tools and forwards browser connections through the application origin to a watch-hosted provider, with the browser-tools client and configuration emitted as watch-only, build-only static web assets (keyed by a per-invocation public key).

Changes:

  • Adds Static Web Assets MSBuild integration to generate watch-only browser-tools assets (initializer/client/config) and keep them out of publish output.
  • Reworks watch/browser refresh plumbing to use a minimal provider HTTP surface (/connect + /clear-cache), authenticated via an invocation-scoped RSA public key pinned into build output.
  • Updates/expands tests across Static Web Assets, WebAssembly SDK, dotnet-watch, and Hot Reload components to cover endpoint routing, replay behavior, and reserved build properties.
File summaries
File Description
test/Microsoft.NET.Sdk.StaticWebAssets.Tests/JsModulesIntegrationTest.cs Adds test asserting watch-only/build-only JS module behavior for browser-tools initializer.
test/Microsoft.NET.Sdk.StaticWebAssets.Tests/DotNetWatchBrowserToolsIntegrationTest.cs New integration tests pinning generated config/client assets and ensuring build-only + publish exclusion.
test/Microsoft.NET.Sdk.BlazorWebAssembly.Tests/WasmJsModulesIntegrationTests.cs Adds test ensuring WASM watch initializer is added when browser tools are enabled and validates per-TFM behavior flags.
test/Microsoft.Extensions.DotNetDeltaApplier.Tests/WebAssemblyHotReloadClientTests.cs New tests for retained updates and baseline reset behavior via browser refresh server mocks.
test/Microsoft.Extensions.DotNetDeltaApplier.Tests/Mocks/TestBrowserRefreshServer.cs Updates mock to match new server constructor/auth model and captures live delivery sets.
test/Microsoft.Extensions.DotNetDeltaApplier.Tests/BrowserToolsEndpointRouterTests.cs New unit tests for provider router surface (404/405) and WebSocket auth failure modes.
test/Microsoft.Extensions.DotNetDeltaApplier.Tests/BrowserRefreshServerReplayTests.cs New unit tests for replay invariants across connect/live/reset/epoch behavior.
test/Microsoft.DotNet.HotReload.Client.Tests/SharedSecretProviderTests.cs Updates comment to match new browser-tools client encryption terminology.
test/Microsoft.AspNetCore.Watch.BrowserRefresh.Tests/HostingStartupTest.cs Refactors/updates hosting-startup tests around forwarder + legacy probe handling.
test/Microsoft.AspNetCore.Watch.BrowserRefresh.Tests/BrowserToolsForwarderTest.cs New tests validating HTTP and WebSocket forwarding preservation and error mapping.
test/Microsoft.AspNetCore.Watch.BrowserRefresh.Tests/BrowserScriptMiddlewareTest.cs Removes tests for deleted script-serving middleware.
test/Microsoft.AspNetCore.Watch.BrowserRefresh.Tests/BrowserRefreshTagHelperComponentTest.cs New tests ensuring TagHelper injects the app-hosted config module and respects PathBase.
test/Microsoft.AspNetCore.Watch.BrowserRefresh.Tests/BlazorWasmHotReloadMiddlewareTest.cs Removes tests for deleted legacy WASM hot reload middleware.
test/dotnet-watch.Tests/Watch/NoRestoreTests.cs Updates assertions and adds coverage for reserved property insertion behavior in process args.
test/dotnet-watch.Tests/TestUtilities/TestBrowserRefreshServer.cs Updates test server wiring to supply session key/configure callback.
test/dotnet-watch.Tests/TestUtilities/MockFileSetFactory.cs Updates MSBuildFileSetFactory construction for new browserToolsPublicKey parameter.
test/dotnet-watch.Tests/HotReload/RazorHotReloadTests.cs Removes assertions tied to removed legacy middleware/script injection logs.
test/dotnet-watch.Tests/HotReload/BuildProjectsTests.cs Normalizes build invocation assertions to account for reserved browser-tools properties.
test/dotnet-watch.Tests/Build/EvaluationTests.cs Updates MSBuildFileSetFactory construction for new browserToolsPublicKey parameter.
test/dotnet-watch.Tests/Build/EvaluationResultTests.cs Adds test ensuring reserved browser-tools properties override user-supplied values.
test/dotnet-watch.Tests/Browser/BrowserToolsEndpointRouterTests.cs New end-to-end tests of provider router auth and HTTP surface.
test/dotnet-watch.Tests/Browser/BrowserTests.cs Updates output expectations to match new “Received:” logging semantics.
test/dotnet-watch.Tests/Browser/BrowserRefreshServerTests.cs Refactors tests for new environment variables and app-model delegated environment configuration.
test/dotnet-watch-test-browser/Program.cs Updates browser test harness to read config module, authenticate via encrypted subprotocol, and acknowledge replay/batches.
src/WebSdk/Web/Targets/Sdk.Server.targets Opts Web SDK into watch browser-tools initializer via shared DotNetWatch SWA targets.
src/WebSdk/Web/Targets/DotNetWatch/Microsoft.NET.Sdk.Web.DotNetWatch.lib.module.js Adds server-rendered Blazor initializer to import the app-hosted config module.
src/WasmSdk/Sdk/Sdk.targets Opts WASM SDK into watch browser-tools initializer via shared DotNetWatch SWA targets.
src/WasmSdk/Sdk/DotNetWatch/Microsoft.NET.Sdk.WebAssembly.DotNetWatch.lib.module.js.template Adds WASM initializer template to set env vars and import app-hosted config module, with per-TFM token substitution.
src/StaticWebAssetsSdk/Targets/Microsoft.NET.Sdk.StaticWebAssets.targets Imports new DotNetWatch SWA targets into the SWA pipeline.
src/StaticWebAssetsSdk/Targets/Microsoft.NET.Sdk.StaticWebAssets.DotNetWatch.targets New MSBuild target generating build-only watch browser-tools assets and endpoints.
src/StaticWebAssetsSdk/Targets/DotNetWatch/dotnet-watch-browser-tools.config.js.template New config-module template pinning public key + fixed provider route and importing the client module.
src/StaticWebAssetsSdk/AGENTS.md Documents why DotNetWatch browser-tools assets live in StaticWebAssetsSdk and must remain app-hosted + build-only.
src/Dotnet.Watch/Web.Middleware/StartupHook.cs Removes setting __ASPNETCORE_BROWSER_TOOLS from startup hook (no-op now).
src/Dotnet.Watch/Web.Middleware/ScriptInjectingStream.cs Removes HTML response rewriting implementation.
src/Dotnet.Watch/Web.Middleware/ResponseStreamWrapper.cs Removes response wrapper previously used for script injection.
src/Dotnet.Watch/Web.Middleware/HostingStartup.cs Replaces legacy middleware/script endpoints with browser-tools forwarding + legacy probe handler + tag helper registration.
src/Dotnet.Watch/Web.Middleware/BrowserToolsForwarder.cs New HTTP/WebSocket forwarder from application origin to watch provider, preserving pre-upgrade rejection status when available.
src/Dotnet.Watch/Web.Middleware/BrowserToolsEnvironment.cs New environment parsing/validation for loopback provider address.
src/Dotnet.Watch/Web.Middleware/BrowserScriptMiddleware.cs Removes legacy script-serving middleware.
src/Dotnet.Watch/Web.Middleware/BrowserRefreshTagHelperComponent.cs New TagHelper component that injects app-hosted config module into MVC/Razor Pages responses.
src/Dotnet.Watch/Web.Middleware/BrowserRefreshMiddleware.cs Removes legacy browser-refresh middleware and its response/script injection behavior.
src/Dotnet.Watch/Web.Middleware/BlazorWasmHotReloadMiddleware.cs Removes legacy WASM hot reload delta caching middleware.
src/Dotnet.Watch/Web.Middleware/BlazorHotReload.js Removes legacy JS module for older WASM hot reload replay.
src/Dotnet.Watch/Web.Middleware/ApplicationPaths.cs Updates paths to browser-tools routes + legacy probe + app-hosted config module path.
src/Dotnet.Watch/Watch/Process/RunningProject.cs Changes apply completion to return success/failure bool and suppress errors on cancellation.
src/Dotnet.Watch/Watch/HotReload/RunningProjectsManager.cs Tracks managed-code apply success across processes/browsers to avoid “applied” false positives and suppresses notifications on failure.
src/Dotnet.Watch/Watch/HotReload/HotReloadDotNetWatcher.cs Passes reserved browser-tools properties into evaluation/build and ensures reserved properties override user values.
src/Dotnet.Watch/Watch/Build/ReservedBuildProperties.cs New helper centralizing reserved watch MSBuild properties and argument injection.
src/Dotnet.Watch/Watch/Build/EvaluationResult.cs Ensures global build properties include reserved browser-tools properties consistently.
src/Dotnet.Watch/Watch/Build/BuildUtilities.cs Adds helper to parse build properties into a case-insensitive ImmutableDictionary with last-wins behavior.
src/Dotnet.Watch/Watch/Build/BuildNames.cs Adds reserved property name constants for browser tools and public key.
src/Dotnet.Watch/Watch/Browser/BrowserRefreshServerFactory.cs Introduces invocation-scoped RSA keypair and exposes public key for builds; disposes session key on factory dispose.
src/Dotnet.Watch/Watch/AppModels/WebApplicationAppModel.cs Delegates environment configuration for exposing provider routes and uses invocation session key for servers; initializes baseline epoch for WASM client.
src/Dotnet.Watch/Watch/AppModels/BlazorWebAssemblyHostedAppModel.cs Updates doc comment to reflect provider-based browser updates.
src/Dotnet.Watch/Watch/AppModels/BlazorWebAssemblyAppModel.cs Adds YARP gateway proxy route env vars for standalone WASM hosts that don’t activate hosting startups.
src/Dotnet.Watch/HotReloadClient/Web/WebSocketConfig.cs Adds WithHostName helper.
src/Dotnet.Watch/HotReloadClient/Web/WebServerHost.cs Changes host to track HTTP endpoints separately from WebSocket endpoints.
src/Dotnet.Watch/HotReloadClient/Web/WebAssemblyHotReloadClient.cs Routes managed updates through provider replay/live mechanism with baseline epoch and removes legacy update-id wire contract.
src/Dotnet.Watch/HotReloadClient/Web/StaticWebAssetsManifest.cs Excludes generated watcher outputs and JS module manifest from watch file enumeration.
src/Dotnet.Watch/HotReloadClient/Web/StaticWebAsset.cs Adds helpers to detect and exclude browser-tools generated assets and JS modules manifest from watch inputs.
src/Dotnet.Watch/HotReloadClient/Web/MiddlewareEnvironmentVariables.cs Replaces legacy WS endpoint/key vars with provider address var.
src/Dotnet.Watch/HotReloadClient/Web/KestrelWebSocketServer.cs Returns both WebSocket and HTTP server URLs for provider address selection.
src/Dotnet.Watch/HotReloadClient/Web/BrowserToolsProtocol.cs Defines fixed provider route prefix and update batch record types.
src/Dotnet.Watch/HotReloadClient/Web/BrowserToolsEndpointRouter.cs New provider router implementing minimal HTTP surface and delegating WebSocket auth/acceptance to server.
src/Dotnet.Watch/HotReloadClient/Web/BrowserRefreshServer.cs Uses BrowserToolsEndpointRouter and enforces loopback listening; returns both ws and http endpoints.
src/Dotnet.Watch/HotReloadClient/Web/BrowserConnection.cs Adds per-connection initialization gate and pending replay updates snapshot to enforce replay/live ordering invariants.
src/Dotnet.Watch/HotReloadClient/HotReloadClients.cs Returns apply success bool and only triggers browser reload when all clients succeed.
src/Dotnet.Watch/HotReloadAgent.WebAssembly.Browser/wwwroot/Microsoft.DotNet.HotReload.WebAssembly.Browser.lib.module.js Coordinates readiness with browser-tools client and installs apply APIs only when watch activation variable is set.
src/Dotnet.Watch/HotReloadAgent.WebAssembly.Browser/WebAssemblyHotReload.cs Removes unauthenticated HTTP replay fetch and ensures apply attempts throw actionable errors when agent is unavailable.
src/Dotnet.Watch/dotnet-watch/Watch/MsBuildFileSetFactory.cs Adds reserved browser-tools properties to design-time graph evaluation and MSBuild invocation.
src/Dotnet.Watch/dotnet-watch/Watch/DotNetWatcher.cs Re-initializes environment per iteration and updates launch environment configuration call shape.
src/Dotnet.Watch/dotnet-watch/Watch/BuildEvaluator.cs Injects reserved browser-tools properties into supported commands before application args.
src/Dotnet.Watch/dotnet-watch/Program.cs Ensures --list does not activate browser-tools asset generation by using empty public key.
src/Dotnet.Watch/AGENTS.md Updates agent-facing architecture/conventions documentation for the new browser-tools activation and provider/forwarder model.
.github/memory/KNOWN_ISSUES.md Documents stale WASM runtime asset hazard when reusing app trees across locally built SDKs.
.github/memory/FILE_MAP.md Updates Dotnet.Watch entry description to reflect browser-tools provider/forwarding terminology.
.github/memory/ARCHITECTURE.md Adds architecture documentation for dotnet watch browser-tools activation, assets, auth, forwarding, and replay semantics.
Review details
  • Files reviewed: 83/83 changed files
  • Comments generated: 1
  • Review effort level: Lite

@maraf maraf left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good to me from the blazor/wasm point-of-view. Leaving some comment mostly for clean-up.

@maraf

maraf commented Sep 9, 2026

Copy link
Copy Markdown
Member

This property should be removed once we have a dotnet-watch specific build

<_WasmEnableHotReload>$(WasmEnableHotReload)</_WasmEnableHotReload>
<_WasmEnableHotReload Condition="'$(_WasmEnableHotReload)' == '' and '$(Configuration)' != 'Debug'">false</_WasmEnableHotReload>
<_WasmEnableHotReload Condition="'$(_WasmEnableHotReload)' == '' and '$(TargetFrameworkIdentifier)' == '.NETCoreApp' and $([MSBuild]::VersionGreaterThanOrEquals('$(TargetFrameworkVersion)', '10.0'))">true</_WasmEnableHotReload>

Move standalone net11 Blazor WASM activation to a watch-owned provider reached through Blazor Gateway's existing reverse proxy.

Behavior: changed: standalone net11 WASM discovers provider-owned browser tooling without BrowserRefresh startup injection

State: builds; regression coverage follows in the next commit

Review hint: focus on provider discovery, generation replay, and the fixed Gateway route; the remainder is wiring

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 49a13c60-1d66-4321-bfdb-01275ead89d6
Add provider endpoint, replay-store, launch-selection, and build-only WASM asset coverage for the Gateway-native implementation.

Behavior: preserved

State: complete for PR #56071

Review hint: generated Static Web Assets baseline additions represent the two build-only hot reload modules

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 49a13c60-1d66-4321-bfdb-01275ead89d6
Use the built-in BodyTagHelper component pipeline to append one external browser-tools script for supported net11 MVC and Razor Pages responses.

Behavior: changed: supported MVC and Razor Pages activate browser tooling without generic HTML rewriting

State: builds; regression coverage follows in the next commit

Review hint: the supported boundary is the TagHelper registration and body-only PostContent append; static HTML remains user-activated

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 49a13c60-1d66-4321-bfdb-01275ead89d6
Cover body-only script insertion, hosting-startup registration, legacy fallback, and app-model selection for the MVC/Razor Pages boundary.

Behavior: preserved

State: complete for PR #56072

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 49a13c60-1d66-4321-bfdb-01275ead89d6
Move net11 server-hosted browser tooling onto the watch-owned protocol through a fixed loopback HTTP/WebSocket forwarder, including hosted WASM when both sides target net11.

Behavior: changed: modern server-hosted applications share provider-owned scripts, state, replay, and connection protocol

State: builds; regression coverage follows in the next commit

Review hint: verify the fixed destination/route, WebSocket subprotocol forwarding, and explicit TFM selection; legacy hosting startup remains isolated

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 49a13c60-1d66-4321-bfdb-01275ead89d6
Cover HTTP and WebSocket forwarding, provider-hosted resources, reconnect behavior, and explicit net8/net9/net10/net11 and mixed hosted-WASM launch strategies.

Behavior: preserved

State: complete for modern forwarding and compatibility selection

Review hint: the net8-net10 and mixed hosted-WASM rows prove that only all-net11 hosted applications select the provider path

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 49a13c60-1d66-4321-bfdb-01275ead89d6
Stop publishing the provider-hosted client as an application static asset, remove the obsolete legacy-injection switch and test-only launch facade, and reduce launch features to the managed-hot-reload decision.

Behavior: preserved: required pre-net11 and mixed hosted-WASM legacy paths remain selected and functional

State: complete

Review hint: the large baseline deletions are the removed static client asset; the client source remains embedded in and served by dotnet watch

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 49a13c60-1d66-4321-bfdb-01275ead89d6
@javiercn

Copy link
Copy Markdown
Member Author

@maraf Agreed that EnableHotReloadInRuntimeConfigDevFile should go away once there is a dedicated dotnet-watch build mode. This change still intentionally uses the existing Debug/Hot Reload build gate, so I left that property in place and kept the cleanup scoped to the future build-mode change.

Ignore the expected close-propagation failure when the peer aborts between the WebSocket state check and CloseOutputAsync. Add deterministic coverage for the race reproduced by the Playwright replay scenario.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 73e5ae8a-3258-40da-9a27-a1fb7a8feffe
Regenerate Static Web Assets and Blazor WebAssembly baselines for the build-only browser tools assets and consolidated WebAssembly initializer. Normalize generated endpoint fingerprints and account for exact template reads in the evaluator fast-path test.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 73e5ae8a-3258-40da-9a27-a1fb7a8feffe
@javiercn
javiercn requested a review from a team as a code owner September 21, 2026 05:39
@github-actions

Copy link
Copy Markdown
Contributor

🔍 Build Failure Analysis

Summary — The build failed due to a transient NuGet feed outage, not a code or PR issue.

Root cause: NuGet feed 503 Service Unavailable (infrastructure flake)

Of the 19 build legs analyzed (Windows x64/arm64, Linux x64/arm64, macOS arm64, each with AOT/FullFramework variants), 18 compiled with zero errors. Only the 9_0_Windows_x64_FullFramework leg failed, and the failure is a NuGet package download error, not a compiler/task/analyzer error:

  • RestoreTask for test/TestAssets/TestPackages/dotnet-outputsframeworkversion/dotnet-outputsframeworkversion-netcoreapp1.0/dotnet-outputsframeworkversion-netcoreapp1.0.csproj failed to restore System.Reflection.Emit.4.0.1 from the dotnet-public Azure DevOps feed.
  • The download attempt returned 503 (Service Unavailable) from pkgs.dev.azure.com, and after multiple retries the feed reported the package could not be fetched even though it is listed in the feed index.
  • This is a well-known pattern for a transient feed/CDN hiccup, not a missing or misconfigured package reference — the same package/version is referenced only in a pre-existing test asset project, and nothing in this PR touches NuGet configuration, package references, or feed settings.

Affected error (leg 9_0_Windows_x64_FullFramework)

  • test/TestAssets/TestPackages/dotnet-outputsframeworkversion/dotnet-outputsframeworkversion-netcoreapp1.0/dotnet-outputsframeworkversion-netcoreapp1.0.csproj — RestoreTask: "Failed to download package 'System.Reflection.Emit.4.0.1' ... Response status code does not indicate success: 503 (Service Unavailable)."
  • Same project — "The feed 'dotnet-public' lists package 'System.Reflection.Emit.4.0.1' but multiple attempts to download the nupkg have failed."

Proposed fix

No code change is warranted. Recommend re-running the failed Windows_x64_FullFramework leg (or the whole build) — the feed outage should not reproduce on retry. If it recurs consistently across multiple runs, that would indicate a real feed/package availability problem worth escalating to the NuGet feed owners rather than a fix in this PR.


Build overview
  • Failing leg: 9_0_Windows_x64_FullFramework_Logs_Attempt1.binlog
  • Failed project: test/TestAssets/TestPackages/dotnet-outputsframeworkversion/dotnet-outputsframeworkversion-netcoreapp1.0/dotnet-outputsframeworkversion-netcoreapp1.0.csproj
  • Target: Restore (task RestoreTask, via NuGet.targets:200)
  • All other 18 legs (Windows x64/arm64, Linux x64/arm64, Mac arm64 — including AOT and multiple sub-legs) reported no errors.
All MSBuild errors (2 + terminal build failure)
Code Project File:Line Message
(NuGet restore) dotnet-outputsframeworkversion-netcoreapp1.0.csproj NuGet.targets:200 Failed to download package 'System.Reflection.Emit.4.0.1' — 503 (Service Unavailable)
(NuGet restore) dotnet-outputsframeworkversion-netcoreapp1.0.csproj NuGet.targets:200 Feed 'dotnet-public' lists the package but multiple download attempts failed
— — — Build failed.

🤖 Generated by the Build Failure Analysis workflow using (a href="(dev.azure.com/redacted) · commit 11959de

🤖 Automated content by GitHub Copilot. Generated by the Build Failure Analysis workflow. · auto · 49.1 AIC · ⌖ 1.76 AIC · ⊞ 6.8K · [◷]( · ◷)

Templatize runtime identifier segments in relative static web asset item specs so single-file browser tools baselines are portable across Windows, Linux, and macOS.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 73e5ae8a-3258-40da-9a27-a1fb7a8feffe
Log rejected browser-tools WebSocket connections explicitly and update browser tests to wait for the application-hosted configuration module instead of the removed legacy script.

Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com>

Copilot-Session: 73e5ae8a-3258-40da-9a27-a1fb7a8feffe
@javiercn
javiercn enabled auto-merge (squash) September 21, 2026 13:28
@javiercn
javiercn merged commit c7567eb into main Sep 21, 2026
23 checks passed
@javiercn
javiercn deleted the javiercn-browser-tools-combined-review branch September 21, 2026 13:30
@javiercn

Copy link
Copy Markdown
Member Author

/backport to release/11.0.1xx

@github-actions

Copy link
Copy Markdown
Contributor

Started backporting to release/11.0.1xx (link to workflow run)

@github-actions

Copy link
Copy Markdown
Contributor

@javiercn an error occurred while backporting to release/11.0.1xx. See the workflow output for details.

javiercn added a commit that referenced this pull request Sep 21, 2026
…activation and forwarding (#56362)

The application build now owns the browser-tools RSA key pair and emits build-only, non-published browser assets containing the client and pinned public key. Browsers connect through the application’s origin to a loopback `dotnet watch` provider, using an RSA-OAEP-encrypted browser-generated secret for authentication. ASP.NET Core applications use a lightweight forwarding middleware, while standalone Blazor WebAssembly uses the development Gateway/YARP route.
The change also:
- Supports Blazor WebAssembly, Blazor Web SSR/Interactive WebAssembly, Razor Pages, and other web applications across supported target frameworks.
- Removes legacy response rewriting and provider-served executable scripts.
- Preserves origin validation and explicit additional-origin configuration.
- Provides ordered replay for browsers connecting after updates and parallel delivery to multiple browser windows.
- Reports browser update failures accurately instead of presenting unsuccessful changes as applied.
- Loads the current build-generated private key when each browser connects, allowing ordinary `dotnet run` build behavior and clean key rotation.
- Consolidates WebAssembly activation and Hot Reload agent initialization into one initializer.
- Keeps all browser-tools assets out of publish output.
- Updates Static Web Assets and WebAssembly baselines for the new build-only assets.
@dotnet-milestone-bot dotnet-milestone-bot Bot added this to the 12.0-preview1 milestone Sep 22, 2026
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.

5 participants