Skip to content
TypeScript

fix(mobile): synchronize native notification delegates (#12483)

Julius Marminge4c61e3d7ecc4
diff --git a/apps/mobile/package.json b/apps/mobile/package.json
index 031a23b666d..b32117c0315 100644
--- a/apps/mobile/package.json
+++ b/apps/mobile/package.json
@@ -96,7 +96,7 @@
"expo-keep-awake": "~57.0.2",
"expo-linking": "~57.0.8",
"expo-network": "~57.0.1",
- "expo-notifications": "~57.0.15",
+ "expo-notifications": "57.0.15",
"expo-paste-input": "^0.1.15",
"expo-quick-actions": "^6.0.2",
"expo-secure-store": "~57.0.2",
diff --git a/apps/mobile/scripts/fixtures/NotificationCenterManagerRegression.swift b/apps/mobile/scripts/fixtures/NotificationCenterManagerRegression.swift
new file mode 100644
index 00000000000..6d13972d574
--- /dev/null
+++ b/apps/mobile/scripts/fixtures/NotificationCenterManagerRegression.swift
@@ -0,0 +1,189 @@
+import Foundation
+
+// The registry runs on macOS without starting a simulator. Only the OS-facing
+// types are replaced; the tests compile the dependency's actual Swift source.
+public enum UIBackgroundFetchResult {
+ case noData
+}
+
+public struct UNNotificationPresentationOptions: OptionSet {
+ public let rawValue: Int
+ public init(rawValue: Int) { self.rawValue = rawValue }
+}
+
+public final class UNNotification: NSObject {}
+
+public final class UNNotificationResponse: NSObject {
+ let identifier: String
+ init(_ identifier: String) { self.identifier = identifier }
+}
+
+public protocol UNUserNotificationCenterDelegate: AnyObject {}
+
+public final class UNUserNotificationCenter: NSObject {
+ private static let instance = UNUserNotificationCenter()
+ public weak var delegate: UNUserNotificationCenterDelegate?
+ public static func current() -> UNUserNotificationCenter { instance }
+}
+
+private final class TestDelegate: NotificationDelegate {
+ private let lock = NSLock()
+ private var recordedEvents: [String] = []
+ var onEvent: ((String) -> Void)?
+ var onResponse: ((UNNotificationResponse) -> Bool)?
+
+ var events: [String] { lock.withLock { recordedEvents } }
+
+ private func record(_ event: String) {
+ lock.withLock { recordedEvents.append(event) }
+ onEvent?(event)
+ }
+
+ func didRegister(_ deviceToken: String) { record("registered") }
+ func didFailRegistration(_ error: Error) { record("failed") }
+ func openSettings(_ notification: UNNotification?) { record("settings") }
+
+ func willPresent(_ notification: UNNotification, completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) -> Bool {
+ record("present")
+ return false
+ }
+
+ func didReceive(_ userInfo: [AnyHashable: Any], completionHandler: @escaping (UIBackgroundFetchResult) -> Void) -> Bool {
+ record("background")
+ return false
+ }
+
+ func didReceive(_ response: UNNotificationResponse, completionHandler: @escaping () -> Void) -> Bool {
+ record(response.identifier)
+ return onResponse?(response) ?? false
+ }
+}
+
+private func require(_ condition: @autoclosure () -> Bool, _ message: String) throws {
+ if !condition() {
+ throw NSError(domain: "NotificationCenterManagerRegression", code: 1, userInfo: [NSLocalizedDescriptionKey: message])
+ }
+}
+
+private func deliver(_ identifier: String) {
+ NotificationCenterManager.shared.userNotificationCenter(
+ UNUserNotificationCenter.current(),
+ didReceive: UNNotificationResponse(identifier),
+ withCompletionHandler: {}
+ )
+}
+
+private func reentrantCallbacks() throws {
+ let manager = NotificationCenterManager.shared
+ let center = UNUserNotificationCenter.current()
+ let callbacks: [(String, () -> Void)] = [
+ ("registered", { manager.didRegister("token") }),
+ ("failed", { manager.didFailRegistration(NSError(domain: "test", code: 1)) }),
+ ("settings", { manager.userNotificationCenter(center, openSettingsFor: nil) }),
+ ("present", { manager.userNotificationCenter(center, willPresent: UNNotification(), withCompletionHandler: { _ in }) }),
+ ("background", { manager.didReceive([:], completionHandler: { _ in }) })
+ ]
+
+ for (event, callback) in callbacks {
+ let original = TestDelegate()
+ let replacement = TestDelegate()
+ original.onEvent = { [weak original] _ in
+ guard let original else { return }
+ manager.removeDelegate(original)
+ manager.addDelegate(replacement)
+ }
+ manager.addDelegate(original)
+ callback()
+ try require(original.events == [event], "The original delegate must receive the callback once")
+ try require(replacement.events.isEmpty, "New delegates must not join an in-flight callback snapshot")
+ callback()
+ try require(replacement.events == [event], "Reentrant registration must take effect for the next callback")
+ manager.removeDelegate(replacement)
+ }
+}
+
+private func registrationDuringDelivery() throws {
+ let manager = NotificationCenterManager.shared
+ let original = TestDelegate()
+ let receiver = TestDelegate()
+ receiver.onResponse = { _ in true }
+ original.onResponse = { _ in
+ manager.addDelegate(receiver)
+ return false
+ }
+ manager.addDelegate(original)
+ deliver("handoff")
+ try require(receiver.events == ["handoff"], "A delegate registering during delivery must not miss the pending response")
+ manager.removeDelegate(original)
+ manager.removeDelegate(receiver)
+}
+
+private func responseDuringReplay() throws {
+ let manager = NotificationCenterManager.shared
+ deliver("first")
+ let original = TestDelegate()
+ original.onResponse = { response in
+ if response.identifier == "first" {
+ deliver("second")
+ return true
+ }
+ return false
+ }
+ manager.addDelegate(original)
+ let receiver = TestDelegate()
+ receiver.onResponse = { _ in true }
+ manager.addDelegate(receiver)
+ try require(receiver.events == ["second"], "Finishing a replay must retain responses received during callbacks")
+ manager.removeDelegate(original)
+ manager.removeDelegate(receiver)
+}
+
+private func concurrentRegistrations() throws {
+ let manager = NotificationCenterManager.shared
+ let delegates = (0..<512).map { _ in
+ let delegate = TestDelegate()
+ delegate.onResponse = { _ in true }
+ return delegate
+ }
+ DispatchQueue.concurrentPerform(iterations: delegates.count) { index in
+ manager.addDelegate(delegates[index])
+ if index.isMultiple(of: 16) {
+ manager.didRegister("during-add")
+ deliver("during-add")
+ }
+ }
+ let before = delegates.map { $0.events.count }
+ manager.didRegister("after-add")
+ for (index, delegate) in delegates.enumerated() {
+ try require(delegate.events.count == before[index] + 1, "Concurrent registration must retain every delegate exactly once")
+ }
+ DispatchQueue.concurrentPerform(iterations: delegates.count) { index in
+ manager.removeDelegate(delegates[index])
+ if index.isMultiple(of: 16) {
+ manager.didRegister("during-remove")
+ deliver("during-remove")
+ }
+ }
+ let removed = delegates.map { $0.events.count }
+ manager.didRegister("after-remove")
+ try require(delegates.map { $0.events.count } == removed, "Removed delegates must not receive new callbacks")
+}
+
+@main
+private enum RegressionTests {
+ static func main() {
+ do {
+ switch CommandLine.arguments.last {
+ case "reentrant": try reentrantCallbacks()
+ case "handoff": try registrationDuringDelivery()
+ case "pending": try responseDuringReplay()
+ case "concurrent": try concurrentRegistrations()
+ default: throw NSError(domain: "NotificationCenterManagerRegression", code: 2)
+ }
+ print("passed")
+ } catch {
+ FileHandle.standardError.write(Data("\(error.localizedDescription)\n".utf8))
+ exit(1)
+ }
+ }
+}
diff --git a/apps/mobile/scripts/notification-center-manager.test.ts b/apps/mobile/scripts/notification-center-manager.test.ts
new file mode 100644
index 00000000000..e7a059496af
--- /dev/null
+++ b/apps/mobile/scripts/notification-center-manager.test.ts
@@ -0,0 +1,65 @@
+// @effect-diagnostics nodeBuiltinImport:off - Compiles and runs the native dependency regression directly.
+import * as NodeChildProcess from "node:child_process";
+import * as NodeFS from "node:fs";
+import * as NodeOS from "node:os";
+import * as NodePath from "node:path";
+import * as NodeURL from "node:url";
+import { afterAll, beforeAll, describe, expect, it } from "vite-plus/test";
+
+// oxlint-disable-next-line t3code/no-global-process-runtime -- This native integration test uses the host Swift compiler.
+describe.skipIf(NodeOS.platform() !== "darwin")(
+ "NotificationCenterManager native concurrency",
+ () => {
+ let directory: string;
+ let executable: string;
+
+ beforeAll(() => {
+ directory = NodeFS.mkdtempSync(NodePath.join(NodeOS.tmpdir(), "t3-notifications-test-"));
+ executable = NodePath.join(directory, "notification-regression");
+ const source = NodeFS.readFileSync(
+ new URL(
+ "../node_modules/expo-notifications/ios/ExpoNotifications/Notifications/NotificationCenterManager.swift",
+ import.meta.url,
+ ),
+ "utf8",
+ );
+ const manager = NodePath.join(directory, "NotificationCenterManager.swift");
+ NodeFS.writeFileSync(
+ manager,
+ source.replace(/^import (ExpoModulesCore|UserNotifications)\n/gm, ""),
+ );
+ NodeChildProcess.execFileSync(
+ "swiftc",
+ [
+ "-swift-version",
+ "5",
+ "-sanitize=thread",
+ manager,
+ NodeURL.fileURLToPath(
+ new URL("./fixtures/NotificationCenterManagerRegression.swift", import.meta.url),
+ ),
+ "-o",
+ executable,
+ ],
+ { timeout: 30_000, encoding: "utf8" },
+ );
+ });
+
+ afterAll(() => {
+ if (directory) NodeFS.rmSync(directory, { recursive: true, force: true });
+ });
+
+ it.each([
+ ["reentrant", "allows callbacks to replace delegates without deadlocking"],
+ ["handoff", "delivers responses to delegates registering during delivery"],
+ ["pending", "retains new responses received while replaying pending responses"],
+ ["concurrent", "registers, removes, and broadcasts concurrently without data races"],
+ ])("%s: %s", (name) => {
+ const output = NodeChildProcess.execFileSync(executable, [name], {
+ encoding: "utf8",
+ timeout: 15_000,
+ });
+ expect(output.trim()).toBe("passed");
+ });
+ },
+);
diff --git a/patches/[email protected] b/patches/[email protected]
new file mode 100644
index 00000000000..93ad9e704dd
--- /dev/null
+++ b/patches/[email protected]
@@ -0,0 +1,119 @@
+diff --git a/ios/ExpoNotifications/Notifications/NotificationCenterManager.swift b/ios/ExpoNotifications/Notifications/NotificationCenterManager.swift
+--- a/ios/ExpoNotifications/Notifications/NotificationCenterManager.swift
++++ b/ios/ExpoNotifications/Notifications/NotificationCenterManager.swift
+@@ -42,8 +42,10 @@
+ @objc
+ public static let shared = NotificationCenterManager()
+
+- var delegates: [NotificationDelegate] = []
+- var pendingResponses: [UNNotificationResponse] = []
++ // Module creation and destruction can overlap across React runtimes.
++ private let stateLock = NSLock()
++ private var delegates: [NotificationDelegate] = []
++ private var pendingResponses: [UNNotificationResponse] = []
+ let userNotificationCenter: UNUserNotificationCenter = UNUserNotificationCenter.current()
+
+ private override init() {
+@@ -62,32 +64,49 @@
+ }
+
+ public func addDelegate(_ delegate: NotificationDelegate) {
+- delegates.append(delegate)
++ let responses = stateLock.withLock {
++ delegates.append(delegate)
++ return pendingResponses
++ }
+ var handled = false
+- for pendingResponse in pendingResponses {
++ for pendingResponse in responses {
+ handled = delegate.didReceive(pendingResponse, completionHandler: {}) || handled
+ }
+ if handled {
+- pendingResponses.removeAll()
++ removePendingResponses(responses)
+ }
+ }
+
+ public func removeDelegate(_ delegate: AnyObject) {
+- if let index = delegates.firstIndex(where: { $0 === delegate }) {
+- delegates.remove(at: index)
++ stateLock.withLock {
++ if let index = delegates.firstIndex(where: { $0 === delegate }) {
++ delegates.remove(at: index)
++ }
++ }
++ }
++
++ private func snapshotDelegates() -> [NotificationDelegate] {
++ stateLock.withLock { delegates }
++ }
++
++ private func removePendingResponses(_ responses: [UNNotificationResponse]) {
++ let identifiers = Set(responses.map(ObjectIdentifier.init))
++ stateLock.withLock {
++ // Keep responses received while delegate callbacks were running.
++ pendingResponses.removeAll { identifiers.contains(ObjectIdentifier($0)) }
+ }
+ }
+
+ // MARK: - Called by PushTokenAppDelegateSubscriber
+
+ public func didFailRegistration(_ error: any Error) {
+- for delegate in delegates {
++ for delegate in snapshotDelegates() {
+ delegate.didFailRegistration(error)
+ }
+ }
+
+ public func didRegister(_ deviceToken: String) {
+- for delegate in delegates {
++ for delegate in snapshotDelegates() {
+ delegate.didRegister(deviceToken)
+ }
+ }
+@@ -100,7 +119,7 @@
+ withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void
+ ) {
+ var handled = false
+- for delegate in delegates {
++ for delegate in snapshotDelegates() {
+ handled = delegate.willPresent(notification, completionHandler: completionHandler) || handled
+ }
+ if !handled {
+@@ -113,18 +132,23 @@
+ didReceive response: UNNotificationResponse,
+ withCompletionHandler completionHandler: @escaping () -> Void
+ ) {
++ let currentDelegates = stateLock.withLock {
++ // A delegate registering during delivery must see this response too.
++ pendingResponses.append(response)
++ return delegates
++ }
+ var handled = false
+- for delegate in delegates {
++ for delegate in currentDelegates {
+ handled = delegate.didReceive(response, completionHandler: completionHandler) || handled
+ }
+- if !handled {
+- pendingResponses.append(response)
++ if handled {
++ removePendingResponses([response])
+ }
+ completionHandler()
+ }
+
+ public func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
+- for delegate in delegates {
++ for delegate in snapshotDelegates() {
+ delegate.openSettings(notification)
+ }
+ }
+@@ -132,7 +156,7 @@
+ // MARK: - Called from NotificationsAppDelegateSubscriber
+ public func didReceive(_ userInfo: [AnyHashable: Any], completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
+ var handled = false
+- for delegate in delegates {
++ for delegate in snapshotDelegates() {
+ handled = delegate.didReceive(userInfo, completionHandler: completionHandler) || handled
+ }
+ if !handled {
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index 10143c8498e..a0daed3ff96 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -103,6 +103,7 @@ patchedDependencies:
[email protected]: 0dfc4bb8ebd80fb3e06b91ef61346f5259517ab0f2437644fe95ae531084b1f5
[email protected]: fa9a3e0442ed395d4071bb406e08c3a471c9a84700bdfa0b9ad7ff144c96041a
[email protected]: 6be7092f8c6f03a57b75c797d98b5f19ed62d2dd205bfc4c8adf4cef45655d7e
+ [email protected]: f89252c2c08dc7b3acb8415f319ebbe15fff8c9f88a64ebe1830cd5ac5c9ac40
[email protected]: 8d2e3b10eb3f52036a9a086800180ec6cebf3b75bccc5b1775117a7244d4ac45
[email protected]: 319a9ded5db49c5b5215c511a138b33f44c7ea2972eb418192e8d5342fe75ce6
[email protected]: 0579f8e4dad02bf3183d95b02620358412983c36f9bda7425dc8bcb9643b5ce2
@@ -389,8 +390,8 @@ importers:
specifier: ~57.0.1
expo-notifications:
- specifier: ~57.0.15
+ specifier: 57.0.15
+ version: 57.0.15(patch_hash=f89252c2c08dc7b3acb8415f319ebbe15fff8c9f88a64ebe1830cd5ac5c9ac40)([email protected])([email protected](@babel/[email protected])(@react-native/[email protected](@babel/[email protected])([email protected])([email protected]))(@types/[email protected])([email protected])([email protected])([email protected]))([email protected])([email protected])
expo-paste-input:
specifier: ^0.1.15
@@ -17449,7 +17450,7 @@ snapshots:
expo: 57.0.18(41fd11498a34454c91128cdad32f22f8)
react: 19.2.3
dependencies:
'@expo/image-utils': 0.11.5([email protected])
abort-controller: 3.0.0
diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml
index ca80c41bc73..0b4e86c2d5d 100644
--- a/pnpm-workspace.yaml
+++ b/pnpm-workspace.yaml
@@ -190,6 +190,7 @@ patchedDependencies: