From 62002039c02f9e2b00702cc6759d834970d13f8f Mon Sep 17 00:00:00 2001 From: "jh.xiong" Date: Tue, 20 Oct 2026 04:26:15 -0700 Subject: [PATCH] Clear DevLoadingView when its host is invalidated (#59165) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Summary: In an iOS app that creates a React Native host for an individual screen, closing that screen and releasing its host while the bundle is still loading can leave the “Loading from Metro…” banner visible over the native screen. If the host is released before the initial banner delay expires, the banner can appear after the screen has already closed. `RCTDevLoadingView` retains `_initialMessageBlock`, whose callback captures the module. Normally, bundle progress or completion clears this block. When the host is released before the first bundle progress update, the module can remain retained by this cycle. Cleanup in `dealloc` cannot break the cycle, and the module currently has no `invalidate` implementation to clear its pending work and window during host teardown. Cleanup also needs to reject queued display work. An initial-message or download-progress callback can enqueue a display block before invalidation, and that block can run after invalidation has cleared the window. The invalidation check runs inside the queued block so it cannot recreate the banner after teardown. This change: - Implements `invalidate` to cancel the pending initial message and hide and release the loading window and its views on the main queue. - Records that the module has been invalidated and checks that state inside the queued display block, preventing queued messages from recreating the window after teardown. - Adds three XCTest regression tests for pending-message cancellation, visible-window cleanup, and queued display work after invalidation. ## Changelog: [IOS] [FIXED] - Clear the development loading banner when its React Native host is invalidated, including pending messages that could appear after teardown. Pull Request resolved: https://github.com/react/react-native/pull/59165 Test Plan: Reproduced on main baseline `27e77216ef2557ccbf31a01067a44dc1dd2ec846` and verified with the fix applied, using RNTester in Debug, Xcode 27.0, and an iPhone 18 Pro simulator running iOS 27.0. The [reproduction branch](https://github.com/fairysword/react-native/tree/repro/devloadingview-invalidation) contains the native RNTester controller, a six-second Metro delay proxy, and the Run configuration. [Setup and run instructions](https://github.com/fairysword/react-native/blob/9c5b7edd806ec332fe0f25772b13b4357fb3184b/packages/rn-tester/devloading-invalidation/README.md) are included with the demo. The controller creates and releases a real `RCTReactNativeFactory` / `RCTHost`; it does not call DevLoadingView's display, hide, or invalidation methods. Native controls sit above the loading window so the close button remains tappable while loading. ### Reproduction 1. Follow the demo README to install dependencies, start Metro and the delay proxy, and run RNTester in Xcode. 2. Tap **Open RN page** and wait for **Loading from Metro…**. 3. Before the six-second delay expires, tap **Close RN page and release Host**. Wait at least ten seconds after closing. 4. Apply the fix, rebuild and restart the app, and repeat the same steps. 5. On the patched build, reopen the RN page and let the bundle finish loading. **Before the fix:** the RN view is removed and the weak reference to its host is nil, but the loading banner remains over the native screen. **With the fix:** the banner clears during invalidation and does not reappear. A new host still displays its loading banner normally and clears it when RNTester finishes loading. ### Additional lifecycle checks | Scenario | Before the fix | With the fix | | --- | --- | --- | | Release the host while the banner is visible | Banner remains at the 2-, 8-, and 11-second checkpoints | No banner at those checkpoints | | Release the host before the initial 200 ms display delay | Banner appears after the host is released | Banner stays absent | | Allow the bundle to finish loading | — | RNTester loads and the banner clears | | Close during loading, reopen with a new host, then close | — | Old banner clears; the new host loads normally and leaves no banner after closing | ### Queued display regression Compared the same cleanup implementation with and without the `_invalidated` check, using repeated real host creation and release in the simulator. The controller did not call DevLoadingView methods directly or retain the module. Each variant ran 60 cycles per timing scenario: | Scenario | Cleanup without the invalidation check | Cleanup with the invalidation check | | --- | --- | --- | | Close 150–250 ms after opening, around the initial display delay | 11 queued display blocks recreated the window after cleanup; those modules then deallocated shortly afterward | 11 late display blocks were rejected; no window was recreated | | Close 40–1,000 ms after opening while real Metro multipart responses were throttled to 32 KiB every 20 ms | 2 queued display blocks recreated the window after cleanup; “Downloading 0%…” was still visible at post-close checks with the RN page closed and its host's weak reference nil | The late display block was rejected; no window was recreated and no post-close banner was observed | For both download races, the module deallocated about 3.9 seconds after recreating the window. This confirms that relying on eventual `dealloc` does not ensure the banner disappears when its host is released. Both baseline and patched Debug simulator builds succeeded. The build command used from `packages/rn-tester` was: ```bash xcodebuild \ -workspace RNTesterPods.xcworkspace \ -scheme RNTester \ -configuration Debug \ -sdk iphonesimulator \ -destination 'generic/platform=iOS Simulator' \ -derivedDataPath build/devloading-invalidation/DerivedData \ -jobs 6 \ ARCHS=arm64 ONLY_ACTIVE_ARCH=YES CODE_SIGNING_ALLOWED=NO \ build ``` ### Automated regression tests `RCTDevLoadingViewTests` is included in the `RNTesterUnitTests` target and covers: - Cancelling and releasing the pending initial message during invalidation. - Hiding an existing loading window and releasing its window, container, label, and dismiss-button references. - Preventing queued `showMessage` and `updateProgress` callbacks from creating a window after invalidation. A test subclass overrides a private wrapper around `RCTRunningInTestEnvironment()` so the tests exercise the real display path instead of returning early under XCTest. The production implementation still uses the same environment check. The targeted run used the repository's default AddressSanitizer and UndefinedBehaviorSanitizer test configuration: **3 tests passed, 0 failed, 0 skipped**. For negative controls, the pending-message cancellation, window cleanup, and invalidation guard were each removed independently. Each variant failed its corresponding test while the other two tests passed. After restoring the complete fix, all three tests passed again. Run the regression tests from `packages/rn-tester`, selecting an available iOS simulator: ```bash xcodebuild test \ -workspace RNTesterPods.xcworkspace \ -scheme RNTester \ -configuration Debug \ -sdk iphonesimulator \ -destination 'platform=iOS Simulator,name=iPhone 18 Pro,OS=27.0' \ -derivedDataPath build/devloading-invalidation/DerivedData \ -only-testing:RNTesterUnitTests/RCTDevLoadingViewTests \ -parallel-testing-enabled NO \ -jobs 6 \ ARCHS=arm64 ONLY_ACTIVE_ARCH=YES CODE_SIGNING_ALLOWED=NO ``` Reviewed By: cipolleschi Differential Revision: D126289730 Pulled By: vzaidman fbshipit-source-id: 23d35b10e09c5a95da95a0524c975aec8410dc36 --- .../React/CoreModules/RCTDevLoadingView.mm | 22 ++- .../RNTesterPods.xcodeproj/project.pbxproj | 4 + .../RCTDevLoadingViewTests.m | 141 ++++++++++++++++++ 3 files changed, 166 insertions(+), 1 deletion(-) create mode 100644 packages/rn-tester/RNTesterUnitTests/RCTDevLoadingViewTests.m diff --git a/packages/react-native/React/CoreModules/RCTDevLoadingView.mm b/packages/react-native/React/CoreModules/RCTDevLoadingView.mm index 94a22481935..100dc3ce064 100644 --- a/packages/react-native/React/CoreModules/RCTDevLoadingView.mm +++ b/packages/react-native/React/CoreModules/RCTDevLoadingView.mm @@ -35,6 +35,7 @@ using namespace facebook::react; UIButton *_dismissButton; NSDate *_showDate; BOOL _hiding; + BOOL _invalidated; dispatch_block_t _initialMessageBlock; } @@ -59,6 +60,20 @@ RCT_EXPORT_MODULE() return self; } +- (void)invalidate +{ + RCTExecuteOnMainQueue(^{ + self->_invalidated = YES; + // The delayed message retains this module, so dealloc cannot cancel it when the host is invalidated. + [self clearInitialMessageDelay]; + self->_window.hidden = YES; + self->_window = nil; + self->_container = nil; + self->_label = nil; + self->_dismissButton = nil; + }); +} + - (void)dealloc { [self clearInitialMessageDelay]; @@ -127,7 +142,7 @@ RCT_EXPORT_MODULE() } dispatch_async(dispatch_get_main_queue(), ^{ - if (RCTRunningInTestEnvironment()) { + if (self->_invalidated || [self isRunningInTestEnvironment]) { return; } @@ -324,6 +339,11 @@ RCT_EXPORT_MODULE() [self showMessage:message color:color backgroundColor:backgroundColor dismissButton:false]; } +- (BOOL)isRunningInTestEnvironment +{ + return RCTRunningInTestEnvironment(); +} + - (BOOL)isDarkModeEnabled { // We pass nil here to match the behavior of the native module. diff --git a/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj b/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj index 76c55b4f55e..725e8a28823 100644 --- a/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj +++ b/packages/rn-tester/RNTesterPods.xcodeproj/project.pbxproj @@ -56,6 +56,7 @@ E7DB218C22B41FCD005AC45F /* XCTest.framework in Frameworks */ = {isa = PBXBuildFile; fileRef = E7DB218B22B41FCD005AC45F /* XCTest.framework */; }; F0D621C32BBB9E38005960AC /* PrivacyInfo.xcprivacy in Resources */ = {isa = PBXBuildFile; fileRef = F0D621C22BBB9E38005960AC /* PrivacyInfo.xcprivacy */; }; F1A0B1C23D4E5F6071829302 /* RCTTurboModuleArrayBufferTests.mm in Sources */ = {isa = PBXBuildFile; fileRef = F1A0B1C23D4E5F6071829301 /* RCTTurboModuleArrayBufferTests.mm */; }; + D1A60AD11B9247A080734F02 /* RCTDevLoadingViewTests.m in Sources */ = {isa = PBXBuildFile; fileRef = D1A60AD11B9247A080734F01 /* RCTDevLoadingViewTests.m */; }; /* End PBXBuildFile section */ /* Begin PBXContainerItemProxy section */ @@ -163,6 +164,7 @@ E7DB218B22B41FCD005AC45F /* XCTest.framework */ = {isa = PBXFileReference; lastKnownFileType = wrapper.framework; path = XCTest.framework; sourceTree = DEVELOPER_DIR; }; F0D621C22BBB9E38005960AC /* PrivacyInfo.xcprivacy */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = text.xml; path = PrivacyInfo.xcprivacy; sourceTree = ""; }; F1A0B1C23D4E5F6071829301 /* RCTTurboModuleArrayBufferTests.mm */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.cpp.objcpp; path = RCTTurboModuleArrayBufferTests.mm; sourceTree = ""; }; + D1A60AD11B9247A080734F01 /* RCTDevLoadingViewTests.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = RCTDevLoadingViewTests.m; sourceTree = ""; }; /* End PBXFileReference section */ /* Begin PBXFrameworksBuildPhase section */ @@ -328,6 +330,7 @@ E7DB20CA22B2BAA5005AC45F /* RCTConvert_NSURLTests.m */, E7DB20CE22B2BAA5005AC45F /* RCTConvert_YGValueTests.m */, 383889D923A7398900D06C3E /* RCTConvert_UIColorTests.m */, + D1A60AD11B9247A080734F01 /* RCTDevLoadingViewTests.m */, E7DB20C822B2BAA5005AC45F /* RCTDevMenuTests.m */, E7DB20AF22B2BAA4005AC45F /* RCTFontTests.m */, E7DB20C722B2BAA5005AC45F /* RCTFormatErrorTests.m */, @@ -770,6 +773,7 @@ E7DB20E722B2BAA6005AC45F /* RCTConvert_NSURLTests.m in Sources */, E7DB20EA22B2BAA6005AC45F /* RCTImageUtilTests.m in Sources */, E7DB20D722B2BAA6005AC45F /* RCTModuleInitTests.m in Sources */, + D1A60AD11B9247A080734F02 /* RCTDevLoadingViewTests.m in Sources */, E7DB20E522B2BAA6005AC45F /* RCTDevMenuTests.m in Sources */, E7DB20DE22B2BAA6005AC45F /* RCTUnicodeDecodeTests.m in Sources */, CD10C7A5290BD4EB0033E1ED /* RCTEventEmitterTests.m in Sources */, diff --git a/packages/rn-tester/RNTesterUnitTests/RCTDevLoadingViewTests.m b/packages/rn-tester/RNTesterUnitTests/RCTDevLoadingViewTests.m new file mode 100644 index 00000000000..73e217893cc --- /dev/null +++ b/packages/rn-tester/RNTesterUnitTests/RCTDevLoadingViewTests.m @@ -0,0 +1,141 @@ +/* + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */ + +#import +#import +#import +#import +#import + +#if RCT_DEV_MENU + +@interface RCTDevLoadingView (Tests) +- (void)invalidate; +- (BOOL)isRunningInTestEnvironment; +@end + +@interface RCTDevLoadingViewForTests : RCTDevLoadingView +@end + +@implementation RCTDevLoadingViewForTests +- (BOOL)isRunningInTestEnvironment +{ + // Exercise the real display path instead of the XCTest early return. + return NO; +} +@end + +@interface RCTDevLoadingViewTests : XCTestCase +@end + +@implementation RCTDevLoadingViewTests { + BOOL _wasEnabled; + NSMutableArray *_loadingViews; +} + +- (void)setUp +{ + [super setUp]; + XCTAssertTrue(RCTIsMainQueue()); + _wasEnabled = RCTDevLoadingViewGetEnabled(); + RCTDevLoadingViewSetEnabled(YES); + _loadingViews = [NSMutableArray new]; +} + +- (void)tearDown +{ + for (RCTDevLoadingView *loadingView in _loadingViews) { + [loadingView invalidate]; + } + [self drainMainQueue]; + _loadingViews = nil; + RCTDevLoadingViewSetEnabled(_wasEnabled); + [super tearDown]; +} + +- (RCTDevLoadingView *)newLoadingView +{ + RCTDevLoadingView *loadingView = [RCTDevLoadingViewForTests new]; + [_loadingViews addObject:loadingView]; + return loadingView; +} + +- (void)drainMainQueue +{ + XCTestExpectation *drained = [self expectationWithDescription:@"Queued loading messages finished"]; + dispatch_async(dispatch_get_main_queue(), ^{ + // updateProgress enqueues another display block from its main-queue callback. + dispatch_async(dispatch_get_main_queue(), ^{ + [drained fulfill]; + }); + }); + [self waitForExpectations:@[ drained ] timeout:2]; +} + +- (void)showMessage:(RCTDevLoadingView *)loadingView +{ + [loadingView showMessage:@"Loading from Metro…" + color:UIColor.whiteColor + backgroundColor:UIColor.blackColor + dismissButton:YES]; +} + +- (void)testInvalidateClearsVisibleWindow +{ + RCTDevLoadingView *loadingView = [self newLoadingView]; + [self showMessage:loadingView]; + [self drainMainQueue]; + + UIWindow *window = [loadingView valueForKey:@"window"]; + XCTAssertNotNil(window); + XCTAssertFalse(window.hidden); + XCTAssertNotNil([loadingView valueForKey:@"dismissButton"]); + + [loadingView invalidate]; + [self drainMainQueue]; + + XCTAssertTrue(window.hidden); + for (NSString *key in @[ @"window", @"container", @"label", @"dismissButton" ]) { + XCTAssertNil([loadingView valueForKey:key], @"%@ should be released during invalidation", key); + } +} + +- (void)testInvalidateCancelsPendingInitialMessage +{ + RCTDevLoadingView *loadingView = [self newLoadingView]; + [loadingView showWithURL:[NSURL URLWithString:@"http://localhost:8081/index.bundle"]]; + dispatch_block_t pendingMessage = [loadingView valueForKey:@"initialMessageBlock"]; + XCTAssertNotNil(pendingMessage); + XCTAssertEqual(dispatch_block_testcancel(pendingMessage), 0L); + + [loadingView invalidate]; + [self drainMainQueue]; + + XCTAssertNil([loadingView valueForKey:@"initialMessageBlock"]); + XCTAssertNotEqual(dispatch_block_testcancel(pendingMessage), 0L); +} + +- (void)testInvalidatePreventsQueuedMessagesFromRecreatingWindow +{ + RCTDevLoadingView *messageView = [self newLoadingView]; + RCTDevLoadingView *progressView = [self newLoadingView]; + RCTLoadingProgress *progress = [RCTLoadingProgress new]; + progress.status = @"Downloading"; + + [self showMessage:messageView]; + [progressView updateProgress:progress]; + [messageView invalidate]; + [progressView invalidate]; + [self drainMainQueue]; + + XCTAssertNil([messageView valueForKey:@"window"]); + XCTAssertNil([progressView valueForKey:@"window"]); +} + +@end + +#endif