Swift 6 Migration (#5733)

* Enable Swift 6.2 with default main actor isolation for the app target

Turn on SWIFT_VERSION 6.2, SWIFT_APPROACHABLE_CONCURRENCY and SWIFT_DEFAULT_ACTOR_ISOLATION = MainActor for the ElementX target, matching the NSE and Share Extension (which already use 6.2 without the main actor default).

# Conflicts:
#	ElementX.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved

* Update the code generation templates for Swift 6

Emit nonisolated/@unchecked Sendable mocks and nonisolated string enums, and mark async mock methods @concurrent so they keep suspending like the real implementations (otherwise intermediate states are unobservable in tests). Includes the regenerated mocks and strings.

# Conflicts:
#	ElementX/Sources/Mocks/Generated/GeneratedMocks.swift

* Make the data layer and services nonisolated and Sendable

Annotate the value-type models, Rust SDK proxy wrappers, timeline item graph, settings, logging and NSE-shared types as nonisolated, and conform the service protocols to Sendable so their existentials can cross isolation boundaries. These types run off the main actor and no longer inherit the target's default main actor isolation.

* Adopt the new isolation across call sites, mocks and signatures

Update call sites, closure signatures and mock configuration helpers to match the nonisolated/Sendable data layer, including the main actor isolated mock inits and the @Sendable filter on recentlyVisitedRooms.

^ Conflicts:
^	ElementX/Sources/Services/SecureBackup/SecureBackupController.swift

* Remove redundant @MainActor annotations

With the app target defaulting to main actor isolation, the explicit @MainActor on view models, coordinators, views and their protocols is no longer required.

* Fix concurrency hotspots surfaced by the migration

Resolve the room summary main-thread deadlock by moving diff processing onto AsyncStreams, add the SDKListener.onMainActor FIFO bridge for SDK callbacks, hop KVO/timer/UIKit callbacks to the main actor via assumeIsolated, add isolated deinits, and apply the few justified nonisolated(unsafe) escapes for queue-confined Apple APIs.

* Fix the unit tests for Swift 6 concurrency

Hop the waitForConfirmation body onto the caller's actor (Swift Testing runs confirmation closures off-actor), and adjust the affected suites and async signatures.

* offload diffs on concurrent threads instead of main actor

* make room info protocols sendable

* use a task group for fetching data so that everything runs concurrently in the TextRoomTimelineView when getting the preview.

* use the generic onMainActor implementation, which already makes a stream and send the continuation on the main actor.

* small pr comments issues being addressed

* update enterprise

* Update StaticCode to 1.1.0 and specify the required Swift isolation.

* fix ElementCallServiceTests

* update enterprise

* re-generate mocks

* update enterprise

* enterprise new code conformed to swift 6

---------

Co-authored-by: Doug <douglase@element.io>
This commit is contained in:
Mauro
2026-06-18 17:55:31 +02:00
committed by GitHub
parent 7edca8b5a1
commit a520d94760
444 changed files with 3677 additions and 3361 deletions
@@ -9,7 +9,7 @@
import Foundation
/// A type that represents how to set up the analytics module in the app.
struct AnalyticsConfiguration {
nonisolated struct AnalyticsConfiguration {
/// The host to use for PostHog analytics.
let host: String
/// The public key for submitting analytics.
@@ -8,7 +8,7 @@
import Foundation
enum AnalyticsConsentState: String, Codable {
nonisolated enum AnalyticsConsentState: String, Codable {
case optedOut
case optedIn
case unknown
@@ -9,7 +9,7 @@
import SwiftUI
/// Used to specify the user's app specific appearance preference
enum AppAppearance: CaseIterable, Codable {
nonisolated enum AppAppearance: CaseIterable, Codable {
case system
case dark
case light
@@ -14,7 +14,7 @@ import Foundation
import SwiftUI
/// Common settings between app and NSE
protocol CommonSettingsProtocol: AnyObject, Sendable {
nonisolated protocol CommonSettingsProtocol: AnyObject, Sendable {
var lastNotificationBootTime: TimeInterval? { get set }
var selectedNotificationTone: NotificationTone? { get set }
@@ -27,7 +27,7 @@ protocol CommonSettingsProtocol: AnyObject, Sendable {
var hideQuietNotificationAlerts: Bool { get }
}
enum AppBuildType {
nonisolated enum AppBuildType {
case debug
case nightly
case release
@@ -36,7 +36,7 @@ enum AppBuildType {
/// Store Element specific app settings.
///
/// State is persisted in `UserDefaults`, which is thread-safe per Apple's documentation, hence `@unchecked`.
final class AppSettings: @unchecked Sendable {
final nonisolated class AppSettings: @unchecked Sendable {
fileprivate enum UserDefaultsKeys: String, PreferenceKeyable {
case lastVersionLaunched
case seenInvites
@@ -173,16 +173,16 @@ final class AppSettings: @unchecked Sendable {
/// used to detect when migrations should be run. When `nil` the app may have been
/// deleted between runs so should clear data in the shared container and keychain.
@UserPreference
var lastVersionLaunched: String?
nonisolated(unsafe) var lastVersionLaunched: String?
/// The Set of room identifiers of invites that the user already saw in the invites list.
/// This Set is being used to implement badges for unread invites.
@UserPreference
var seenInvites: Set<String>
nonisolated(unsafe) var seenInvites: Set<String>
/// Defaults to `true` for new users, and we use a migration to set it to `false` for existing users.
@UserPreference
var hasSeenNewSoundBanner: Bool
nonisolated(unsafe) var hasSeenNewSoundBanner: Bool
/// The initial set of account providers shown to the user in the authentication flow.
///
@@ -227,7 +227,7 @@ final class AppSettings: @unchecked Sendable {
let elementProAppStoreURL: URL = "https://apps.apple.com/app/element-pro-for-work/id6502951615"
@UserPreference
var appAppearance: AppAppearance
nonisolated(unsafe) var appAppearance: AppAppearance
// MARK: - Security
@@ -239,7 +239,7 @@ final class AppSettings: @unchecked Sendable {
let appLockPINCodeBlockList = ["0000", "1234"]
/// The number of attempts the user has made to unlock the app with a PIN code (resets when unlocked).
@UserPreference
var appLockNumberOfPINAttempts: Int
nonisolated(unsafe) var appLockNumberOfPINAttempts: Int
// MARK: - Authentication
@@ -247,15 +247,17 @@ final class AppSettings: @unchecked Sendable {
let oAuthStaticRegistrations: [URL: String] = ["https://id.thirdroom.io/realms/thirdroom": "elementx"]
/// The redirect URL used for OAuth. For the normal case we don't actually need the bundle ID as the web authentication session handles the redirect internally.
/// However in the case where MAS sends the user to an external app, we need to make sure that the system will open the correct variant of the app (e.g. Nightly).
private(set) var oAuthRedirectURL: URL! = URL(string: "https://element.io/oauth/ios/\(InfoPlistReader.main.bundleIdentifier)")
private(set) nonisolated(unsafe) var oAuthRedirectURL: URL! = URL(string: "https://element.io/oauth/ios/\(InfoPlistReader.main.bundleIdentifier)")
private(set) lazy var oAuthConfiguration = OAuthConfiguration(clientName: InfoPlistReader.main.bundleDisplayName,
redirectURI: oAuthRedirectURL,
clientURI: websiteURL,
logoURI: logoURL,
tosURI: acceptableUseURL,
policyURI: privacyURL,
staticRegistrations: oAuthStaticRegistrations.mapKeys { $0.absoluteString })
var oAuthConfiguration: OAuthConfiguration {
OAuthConfiguration(clientName: InfoPlistReader.main.bundleDisplayName,
redirectURI: oAuthRedirectURL,
clientURI: websiteURL,
logoURI: logoURL,
tosURI: acceptableUseURL,
policyURI: privacyURL,
staticRegistrations: oAuthStaticRegistrations.mapKeys { $0.absoluteString })
}
/// Whether or not the Create Account button is shown on the start screen.
///
@@ -278,33 +280,33 @@ final class AppSettings: @unchecked Sendable {
}
@UserPreference
var enableNotifications: Bool
nonisolated(unsafe) var enableNotifications: Bool
@UserPreference
var enableInAppNotifications: Bool
nonisolated(unsafe) var enableInAppNotifications: Bool
@UserPreference
var hideQuietNotificationAlerts: Bool
nonisolated(unsafe) var hideQuietNotificationAlerts: Bool
/// Tag describing which set of device specific rules a pusher executes.
@UserPreference
var pusherProfileTag: String?
nonisolated(unsafe) var pusherProfileTag: String?
/// The device's last boot time as recorded by the NSE.
@UserPreference
var lastNotificationBootTime: TimeInterval?
nonisolated(unsafe) var lastNotificationBootTime: TimeInterval?
/// The sound played when delivering noisy notifications. If nil, use the ElementX default
@UserPreference
var selectedNotificationTone: NotificationTone?
nonisolated(unsafe) var selectedNotificationTone: NotificationTone?
// MARK: - Logging
@UserPreference
var logLevel: LogLevel
nonisolated(unsafe) var logLevel: LogLevel
@UserPreference
var traceLogPacks: Set<TraceLogPack>
nonisolated(unsafe) var traceLogPacks: Set<TraceLogPack>
// MARK: - Bug report
@@ -332,46 +334,46 @@ final class AppSettings: @unchecked Sendable {
/// Whether the user has opted in to send analytics.
@UserPreference
var analyticsConsentState: AnalyticsConsentState
nonisolated(unsafe) var analyticsConsentState: AnalyticsConsentState
@UserPreference
var hasRunNotificationPermissionsOnboarding: Bool
nonisolated(unsafe) var hasRunNotificationPermissionsOnboarding: Bool
@UserPreference
var hasRunIdentityConfirmationOnboarding: Bool
nonisolated(unsafe) var hasRunIdentityConfirmationOnboarding: Bool
@UserPreference
var hasRequestedLocationAlwaysLocationAuthorization: Bool
nonisolated(unsafe) var hasRequestedLocationAlwaysLocationAuthorization: Bool
@UserPreference
var frequentlyUsedSystemEmojis: [FrequentlyUsedEmoji]
nonisolated(unsafe) var frequentlyUsedSystemEmojis: [FrequentlyUsedEmoji]
// MARK: - Live Location
@UserPreference
var liveLocationSharingSessionsByRoomID: [String: LiveLocationSession]
nonisolated(unsafe) var liveLocationSharingSessionsByRoomID: [String: LiveLocationSession]
@UserPreference
var liveLocationMinimumDistanceUpdate: Int
nonisolated(unsafe) var liveLocationMinimumDistanceUpdate: Int
@UserPreference
var liveLocationDisclaimerDisplayed: Bool
nonisolated(unsafe) var liveLocationDisclaimerDisplayed: Bool
// MARK: - Home Screen
@UserPreference
var roomListActivityVisibility: RoomListActivityVisibility
nonisolated(unsafe) var roomListActivityVisibility: RoomListActivityVisibility
// MARK: - Room Screen
@UserPreference
var viewSourceEnabled: Bool
nonisolated(unsafe) var viewSourceEnabled: Bool
@UserPreference
var optimizeMediaUploads: Bool
nonisolated(unsafe) var optimizeMediaUploads: Bool
@UserPreference
var voiceMessagePlaybackSpeed: AudioPlaybackSpeed
nonisolated(unsafe) var voiceMessagePlaybackSpeed: AudioPlaybackSpeed
/// Whether or not to show a warning on the media caption composer so the user knows
/// that captions might not be visible to users who are using other Matrix clients.
@@ -390,7 +392,7 @@ final class AppSettings: @unchecked Sendable {
let elementCallPosthogSentryDSN = "https://3bd2f95ba5554d4497da7153b552ffb5@sentry.tools.element.io/41"
@UserPreference
var elementCallBaseURLOverride: URL?
nonisolated(unsafe) var elementCallBaseURLOverride: URL?
// MARK: - Users
@@ -413,50 +415,50 @@ final class AppSettings: @unchecked Sendable {
// MARK: - Presence
@UserPreference
var sharePresence: Bool
nonisolated(unsafe) var sharePresence: Bool
// MARK: - Feature Flags
/// Others
@UserPreference
var fuzzyRoomListSearchEnabled: Bool
nonisolated(unsafe) var fuzzyRoomListSearchEnabled: Bool
@UserPreference
var lowPriorityFilterEnabled: Bool
nonisolated(unsafe) var lowPriorityFilterEnabled: Bool
/// Configuration to enable only signed device isolation mode for crypto. In this mode only devices signed by their owner will be considered in e2ee rooms.
@UserPreference
var enableOnlySignedDeviceIsolationMode: Bool
nonisolated(unsafe) var enableOnlySignedDeviceIsolationMode: Bool
@UserPreference
var knockingEnabled: Bool
nonisolated(unsafe) var knockingEnabled: Bool
@UserPreference
var threadsEnabled: Bool
nonisolated(unsafe) var threadsEnabled: Bool
@UserPreference
var roomThreadListEnabled: Bool
nonisolated(unsafe) var roomThreadListEnabled: Bool
@UserPreference
var focusEventOnNotificationTap: Bool
nonisolated(unsafe) var focusEventOnNotificationTap: Bool
@UserPreference
var linkPreviewsEnabled: Bool
nonisolated(unsafe) var linkPreviewsEnabled: Bool
@UserPreference
var jumpToReadMarkerEnabled: Bool
nonisolated(unsafe) var jumpToReadMarkerEnabled: Bool
@UserPreference
var linkNewDeviceEnabled: Bool
nonisolated(unsafe) var linkNewDeviceEnabled: Bool
@UserPreference
var automaticBackPaginationEnabled: Bool
nonisolated(unsafe) var automaticBackPaginationEnabled: Bool
@UserPreference
var clientPausingAndResumingEnabled: Bool
nonisolated(unsafe) var clientPausingAndResumingEnabled: Bool
@UserPreference
var developerOptionsEnabled: Bool
nonisolated(unsafe) var developerOptionsEnabled: Bool
init(store: UserDefaultsProtocol) {
// UserDefaults to be used on reads and writes.
@@ -509,9 +511,9 @@ final class AppSettings: @unchecked Sendable {
}
}
extension AppSettings: CommonSettingsProtocol { }
nonisolated extension AppSettings: CommonSettingsProtocol { }
private extension UserPreference {
private nonisolated extension UserPreference {
convenience init(key: AppSettings.UserDefaultsKeys, defaultValue: T, storage backingStorage: UserDefaultsProtocol, mode: Mode = .localOverRemote) {
self.init(key: key as any PreferenceKeyable, defaultValue: defaultValue, storage: backingStorage, mode: mode)
}
@@ -5,7 +5,7 @@
// Please see LICENSE files in the repository root for full details.
//
enum AudioPlaybackSpeed: Float, CaseIterable, Codable {
nonisolated enum AudioPlaybackSpeed: Float, CaseIterable, Codable {
case `default` = 1.0
case fast = 1.5
case fastest = 2.0
@@ -6,7 +6,7 @@
// Please see LICENSE files in the repository root for full details.
//
struct FrequentlyUsedEmoji: Codable, Hashable {
nonisolated struct FrequentlyUsedEmoji: Codable, Hashable {
let count: UInt
let key: String
@@ -7,7 +7,7 @@
import Foundation
struct LiveLocationSession: Codable, Equatable {
nonisolated struct LiveLocationSession: Codable, Equatable {
let eventID: String
let expirationDate: Date
}
@@ -12,7 +12,7 @@ import Foundation
///
/// Either resolves to a locally-bundled MapTiler configuration, or to a remote
/// `style.json` URL
enum MapTilerSettings: Equatable {
nonisolated enum MapTilerSettings: Equatable {
/// All of the configuration necessary to use MapTiler maps.
///
/// The style IDs need to be generated with the account that the API key belongs to. For more information read
@@ -9,7 +9,7 @@
import Foundation
import MatrixRustSDK
struct OAuthConfiguration {
nonisolated struct OAuthConfiguration {
let clientName: String
let redirectURI: URL
let clientURI: URL
@@ -22,7 +22,7 @@ struct OAuthConfiguration {
#if canImport(MatrixRustSDK)
import MatrixRustSDK
extension OAuthConfiguration {
nonisolated extension OAuthConfiguration {
var rustValue: MatrixRustSDK.OAuthConfiguration {
MatrixRustSDK.OAuthConfiguration(clientName: clientName,
redirectUri: redirectURI.absoluteString,
@@ -9,7 +9,7 @@
import Foundation
/// A type that represents how rageshakes are collected by the app.
enum RageshakeConfiguration: Equatable, Codable {
nonisolated enum RageshakeConfiguration: Equatable, Codable {
/// Rageshakes should be sent to the provided URL
case url(URL)
/// Rageshakes are disabled.
@@ -13,7 +13,7 @@ import Combine
///
/// Unlike ``UserPreference``, this type of setting isn't settable by the user, nor is the
/// remote value persisted between app launches.
class RemotePreference<T: Equatable> {
nonisolated class RemotePreference<T: Equatable> {
private let defaultValue: T
private let subject: CurrentValueSubject<T, Never>
var publisher: CurrentValuePublisher<T, Never> {
@@ -5,7 +5,7 @@
// Please see LICENSE files in the repository root for full details.
//
enum RoomListActivityVisibility: String, CaseIterable, Codable {
nonisolated enum RoomListActivityVisibility: String, CaseIterable, Codable {
/// Show unread badges for all unread messages (the default).
case current
/// Don't show badges but bold unread room names and their latest message
@@ -7,7 +7,7 @@
import Foundation
final class TrackedUserDefaults: UserDefaults, UserDefaultsProtocol {
final nonisolated class TrackedUserDefaults: UserDefaults, UserDefaultsProtocol {
private let lock = NSLock()
private nonisolated(unsafe) var _trackedSuites: [String] = []
@@ -8,7 +8,7 @@
import Foundation
public protocol UserDefaultsProtocol: AnyObject {
public nonisolated protocol UserDefaultsProtocol: AnyObject {
func data(forKey key: String) -> Data?
func object(forKey key: String) -> Any?
func removeObject(forKey key: String)
@@ -13,7 +13,7 @@ import Foundation
/// to listen for value changes. The publisher does not skip consecutive duplicates, as there is no
/// `Equatable` enforcement at this level.
@propertyWrapper
final class UserPreference<T: Codable> {
final nonisolated class UserPreference<T: Codable> {
static var remotePrefix: String {
"remote-"
}
@@ -94,7 +94,7 @@ final class UserPreference<T: Codable> {
// MARK: - UserPreference convenience initializers
extension UserPreference {
nonisolated extension UserPreference {
convenience init(key: any PreferenceKeyable, defaultValue: T, storage backingStorage: UserDefaultsProtocol, mode: Mode = .localOverRemote) {
let storage: any KeyedStorage<T> = UserDefaultsStorage(userDefaults: backingStorage)
@@ -108,11 +108,11 @@ extension UserPreference {
// MARK: - Keys
protocol PreferenceKeyable: RawRepresentable where RawValue == String { }
nonisolated protocol PreferenceKeyable: RawRepresentable where RawValue == String { }
// MARK: - Storage
protocol KeyedStorage<Value> {
nonisolated protocol KeyedStorage<Value> {
associatedtype Value: Codable
subscript(key: String) -> Value? { get set }
@@ -122,7 +122,7 @@ protocol KeyedStorage<Value> {
///
/// When used with a `Value` that conforms to `PlistRepresentable` the Codable encode/decode
/// phase is skipped, and values are stored natively in the plist.
final class UserDefaultsStorage<Value: Codable>: KeyedStorage {
final nonisolated class UserDefaultsStorage<Value: Codable>: KeyedStorage {
private let userDefaults: UserDefaultsProtocol
init(userDefaults: UserDefaultsProtocol) {
@@ -181,11 +181,11 @@ final class UserDefaultsStorage<Value: Codable>: KeyedStorage {
}
}
private protocol Nullable {
private nonisolated protocol Nullable {
var isNil: Bool { get }
}
extension Optional: Nullable {
nonisolated extension Optional: Nullable {
var isNil: Bool {
switch self {
case .none:
@@ -198,13 +198,13 @@ extension Optional: Nullable {
}
}
extension Dictionary: KeyedStorage where Key == String, Value: Codable { }
nonisolated extension Dictionary: KeyedStorage where Key == String, Value: Codable { }
// MARK: - PlistRepresentable
/// A protocol to mark types as being plist compliant.
/// UserDefaultsStorage uses this protocol to avoid to encode/decode with Codable plist compliant values.
protocol PlistRepresentable { }
nonisolated protocol PlistRepresentable { }
extension Bool: PlistRepresentable { }
extension String: PlistRepresentable { }
@@ -7,7 +7,7 @@
import Foundation
public final class VolatileUserDefaults: UserDefaultsProtocol, Sendable {
public final nonisolated class VolatileUserDefaults: UserDefaultsProtocol, Sendable {
private let lock = NSLock()
private nonisolated(unsafe) var _storage: [String: Any]