Skip to content
Open
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
35 changes: 22 additions & 13 deletions src/Components/Web.JS/src/Rendering/JSRootComponents.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,9 @@ let nextPendingDynamicRootComponentIdentifier = 0;
type ComponentParameters = object | null | undefined;

let manager: DotNet.DotNetObject | undefined;
let currentRendererId: number | undefined;
let jsComponentParametersByIdentifier: JSComponentParametersByIdentifier;
let hasInitializedJsComponents = false;

// These are the public APIs at Blazor.rootComponents.*
export const RootComponentsFunctions = {
Expand Down Expand Up @@ -116,28 +118,35 @@ class DynamicRootComponent {

// Called by the framework
export function enableJSRootComponents(
rendererId: number,
managerInstance: DotNet.DotNetObject,
jsComponentParameters: JSComponentParametersByIdentifier,
jsComponentInitializers: JSComponentIdentifiersByInitializer
): void {
if (manager) {
// This will only happen in very nonstandard cases where someone has multiple hosts.
// It's up to the developer to ensure that only one of them enables dynamic root components.
if (manager && currentRendererId === rendererId) {
// A different renderer type (e.g., Server vs WebAssembly) is trying to enable JS root components.
// This is a multi-host scenario which is not supported for dynamic root components.
throw new Error('Dynamic root components have already been enabled.');
}
Comment on lines +126 to 130

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🔴 Critical

Fix renderer-id guard to allow same-renderer re-enable.
Line 126 currently throws when the same renderer re-attaches, which blocks circuit restart (the scenario this change targets). Flip the comparison to only throw on a different renderer id.

🔧 Proposed fix
-  if (manager && currentRendererId === rendererId) {
+  if (manager && currentRendererId !== rendererId) {
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if (manager && currentRendererId === rendererId) {
// A different renderer type (e.g., Server vs WebAssembly) is trying to enable JS root components.
// This is a multi-host scenario which is not supported for dynamic root components.
throw new Error('Dynamic root components have already been enabled.');
}
if (manager && currentRendererId !== rendererId) {
// A different renderer type (e.g., Server vs WebAssembly) is trying to enable JS root components.
// This is a multi-host scenario which is not supported for dynamic root components.
throw new Error('Dynamic root components have already been enabled.');
}
🤖 Prompt for AI Agents
In `@src/Components/Web.JS/src/Rendering/JSRootComponents.ts` around lines 126 -
130, The guard in JSRootComponents.ts incorrectly throws when the same renderer
re-attaches; update the condition in the block that checks manager and renderer
ids so it only throws when a different renderer is present (i.e., keep the check
for manager but change the comparison between currentRendererId and rendererId
to detect inequality), allowing same-renderer re-enable; refer to the variables
manager, currentRendererId, and rendererId in the JSRootComponents module to
locate and fix the condition.


// When the same renderer type re-enables (e.g., circuit restart or new circuit on same page),
// accept the new manager. The old manager's DotNetObjectReference is no longer valid anyway
// because the old circuit is gone. We don't dispose the old manager - doing so would cause
// JSDisconnectedException because the circuit that created it no longer exists.
currentRendererId = rendererId;
manager = managerInstance;
jsComponentParametersByIdentifier = jsComponentParameters;

// Call the registered initializers. This is an arbitrary subset of the JS component types that are registered
// on the .NET side - just those of them that require some JS-side initialization (e.g., to register them
// as custom elements).
for (const [initializerIdentifier, componentIdentifiers] of Object.entries(jsComponentInitializers)) {
const initializerFunc = DotNet.findJSFunction(initializerIdentifier, 0) as JSComponentInitializerCallback;
for (const componentIdentifier of componentIdentifiers) {
const parameters = jsComponentParameters[componentIdentifier];
initializerFunc(componentIdentifier, parameters);

Comment on lines +136 to +138

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

Refresh JS component parameter metadata on re-enable.
Line 137 updates the manager but never updates jsComponentParametersByIdentifier, so dynamic root additions can read undefined or stale metadata after re-init.

🛠️ Proposed fix
  currentRendererId = rendererId;
  manager = managerInstance;
+  jsComponentParametersByIdentifier = jsComponentParameters;
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
currentRendererId = rendererId;
manager = managerInstance;
jsComponentParametersByIdentifier = jsComponentParameters;
// Call the registered initializers. This is an arbitrary subset of the JS component types that are registered
// on the .NET side - just those of them that require some JS-side initialization (e.g., to register them
// as custom elements).
for (const [initializerIdentifier, componentIdentifiers] of Object.entries(jsComponentInitializers)) {
const initializerFunc = DotNet.findJSFunction(initializerIdentifier, 0) as JSComponentInitializerCallback;
for (const componentIdentifier of componentIdentifiers) {
const parameters = jsComponentParameters[componentIdentifier];
initializerFunc(componentIdentifier, parameters);
currentRendererId = rendererId;
manager = managerInstance;
jsComponentParametersByIdentifier = jsComponentParameters;
🤖 Prompt for AI Agents
In `@src/Components/Web.JS/src/Rendering/JSRootComponents.ts` around lines 136 -
138, When reassigning the renderer/manager (the lines that set currentRendererId
= rendererId and manager = managerInstance), also refresh the cached component
metadata by updating jsComponentParametersByIdentifier from the new manager;
e.g., call the managerInstance method that returns current component parameter
metadata (or invoke the existing refresh helper) and assign its result to
jsComponentParametersByIdentifier so dynamic root additions read fresh metadata
after re-init.

if (!hasInitializedJsComponents) {
// Call the registered initializers. This is an arbitrary subset of the JS component types that are registered
// on the .NET side - just those of them that require some JS-side initialization (e.g., to register them
// as custom elements).
for (const [initializerIdentifier, componentIdentifiers] of Object.entries(jsComponentInitializers)) {
const initializerFunc = DotNet.findJSFunction(initializerIdentifier, 0) as JSComponentInitializerCallback;
for (const componentIdentifier of componentIdentifiers)
initializerFunc(componentIdentifier, jsComponentParameters[componentIdentifier]);
}

hasInitializedJsComponents = true;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ export function attachWebRendererInterop(

if (jsComponentParameters && jsComponentInitializers && Object.keys(jsComponentParameters).length > 0) {
const manager = getInteropMethods(rendererId);
enableJSRootComponents(manager, jsComponentParameters, jsComponentInitializers);
enableJSRootComponents(rendererId, manager, jsComponentParameters, jsComponentInitializers);
}

rendererByIdResolverMap.get(rendererId)?.[0]?.();
Expand Down
42 changes: 0 additions & 42 deletions src/Components/test/E2ETest/Tests/StatePersistanceJSRootTest.cs

This file was deleted.

14 changes: 14 additions & 0 deletions src/Components/test/E2ETest/Tests/StatePersistenceTest.cs
Original file line number Diff line number Diff line change
Expand Up @@ -276,6 +276,20 @@ public async Task StateIsProvidedEveryTimeACircuitGetsCreated(string streaming)
RenderComponentsWithPersistentStateAndValidate(suppressEnhancedNavigation: false, mode, typeof(InteractiveServerRenderMode), streaming, stateValue: "other");
}

[Theory]
[InlineData("ServerNonPrerendered")]
[InlineData("WebAssemblyNonPrerendered")]
public void PersistentStateIsSupportedInDynamicJSRoots(string renderMode)
{
Navigate($"subdir/WasmMinimal/dynamic-js-root.html?renderMode={renderMode}");

Browser.Equal("Counter", () => Browser.Exists(By.TagName("h1")).Text);
Browser.Equal("Current count: 0", () => Browser.Exists(By.CssSelector("p[role='status']")).Text);

Browser.Click(By.CssSelector("button.btn-primary"));
Browser.Equal("Current count: 1", () => Browser.Exists(By.CssSelector("p[role='status']")).Text);
}

private void BlockWebAssemblyResourceLoad()
{
// Clear local storage so that the resource hash is not found
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,6 @@ public static async Task Main(string[] args)
["CORS (WASM)"] = (BuildWebHost<CorsStartup>(CreateAdditionalArgs(args)), "/subdir"),
["Prerendering (Server-side)"] = (BuildWebHost<PrerenderedStartup>(CreateAdditionalArgs(args)), "/prerendered"),
["Razor Component Endpoints"] = (BuildWebHost<RazorComponentEndpointsStartup<App>>(CreateAdditionalArgs(args)), "/subdir"),
["Razor Component Endpoints with JS Root Component"] = (BuildWebHost<RazorComponentEndpointsStartup<App>>(CreateAdditionalArgs([.. args, "--RegisterDynamicJSRootComponent", "true"])), "/subdir"),
["Deferred component content (Server-side)"] = (BuildWebHost<DeferredComponentContentStartup>(CreateAdditionalArgs(args)), "/deferred-component-content"),
["Locked navigation (Server-side)"] = (BuildWebHost<LockedNavigationStartup>(CreateAdditionalArgs(args)), "/locked-navigation"),
["Client-side with fallback"] = (BuildWebHost<StartupWithMapFallbackToClientSideBlazor>(CreateAdditionalArgs(args)), "/fallback"),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -51,10 +51,7 @@ public void ConfigureServices(IServiceCollection services)
options.DisconnectedCircuitMaxRetained = 0;
options.DetailedErrors = true;
}
if (Configuration.GetValue<bool>("RegisterDynamicJSRootComponent"))
{
options.RootComponents.RegisterForJavaScript<TestContentPackage.PersistentComponents.ComponentWithPersistentState>("dynamic-js-root-counter");
}
options.RootComponents.RegisterForJavaScript<TestContentPackage.PersistentComponents.ComponentWithPersistentState>("dynamic-js-root-counter");
})
.AddAuthenticationStateSerialization(options =>
{
Expand Down