From 79c6dbc000e8973f916d6ae10ac142dded247676 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Mon, 23 Nov 2026 15:53:53 -0500 Subject: [PATCH 01/35] Store sessions per account in the keychain Replace the single "UserSession" keychain item with one item per account ("session."), managed by a new AccountStore. Display order and the active account are kept in UserDefaults; the keychain stays the source of truth for which accounts exist. Existing sessions are migrated on launch. The new item is written and read back before the legacy item is deleted, so an interrupted migration is retried safely, and an unreadable legacy item is left untouched. Store directories are already keyed by storeID, so no files move. Signing out now removes only that account's item instead of every item in the app's keychain service. The SDK session delegate reads and writes the client's own item, so token refreshes can't overwrite another account. Also removes the unused MatrixClientSessionDelegate. --- Sources/MatrixIntegration/AccountStore.swift | 166 ++++++++++++++++++ Sources/MatrixIntegration/AppKeychain.swift | 34 +++- .../MatrixIntegration/HomeserverLogin.swift | 12 +- Sources/MatrixIntegration/MatrixClient.swift | 49 +++--- .../MatrixClientSessionDelegate.swift | 46 ----- Sources/MatrixIntegration/UserSession.swift | 23 +-- Tests/MactrixAppTests/AccountStoreTests.swift | 154 ++++++++++++++++ 7 files changed, 385 insertions(+), 99 deletions(-) create mode 100644 Sources/MatrixIntegration/AccountStore.swift delete mode 100644 Sources/MatrixIntegration/MatrixClientSessionDelegate.swift create mode 100644 Tests/MactrixAppTests/AccountStoreTests.swift diff --git a/Sources/MatrixIntegration/AccountStore.swift b/Sources/MatrixIntegration/AccountStore.swift new file mode 100644 index 00000000..2046bd36 --- /dev/null +++ b/Sources/MatrixIntegration/AccountStore.swift @@ -0,0 +1,166 @@ +import Foundation +import OSLog + +/// Persists the sessions of all signed-in accounts. +/// +/// Each account is identified by its `storeID`, which also names its SQLite store directories. +/// Secrets live in one keychain item per account (`session.`); the keychain is the +/// source of truth for which accounts exist. Non-secret metadata (display order, active account) +/// lives in `UserDefaults`. +public struct AccountStore: Sendable { + static let legacySessionKey = "UserSession" + static let sessionKeyPrefix = "session." + static let currentSchemaVersion = 1 + + enum DefaultsKey { + static let order = "accounts.order" + static let active = "accounts.active" + static let schemaVersion = "accounts.schemaVersion" + } + + private let keychain: any KeychainStore + nonisolated(unsafe) private let defaults: UserDefaults + + public init() { + self.init(keychain: AppKeychain(), defaults: .standard) + } + + init(keychain: any KeychainStore, defaults: UserDefaults) { + self.keychain = keychain + self.defaults = defaults + } + + static func sessionKey(for storeID: String) -> String { + sessionKeyPrefix + storeID + } + + // MARK: Sessions + + /// Returns all stored sessions in display order. Unreadable items are skipped. + func loadAll() throws -> [UserSession] { + let storeIDs = try keychain.keys(withPrefix: Self.sessionKeyPrefix) + .map { String($0.dropFirst(Self.sessionKeyPrefix.count)) } + + var sessions: [String: UserSession] = [:] + for storeID in storeIDs { + do { + if let session = try load(storeID: storeID) { + sessions[storeID] = session + } + } catch { + Logger.matrixClient.error("Skipping unreadable session \(storeID): \(error)") + } + } + + let order = orderedStoreIDs(existing: Set(sessions.keys)) + return order.compactMap { sessions[$0] } + } + + func load(storeID: String) throws -> UserSession? { + guard let data = try keychain.load(forKey: Self.sessionKey(for: storeID)) else { return nil } + return try JSONDecoder().decode(UserSession.self, from: data) + } + + /// Creates or updates the session for `session.storeID`, appending new accounts to the order. + func save(_ session: UserSession) throws { + let data = try JSONEncoder().encode(session) + try keychain.save(data, forKey: Self.sessionKey(for: session.storeID)) + + var order = storedOrder + if !order.contains(session.storeID) { + order.append(session.storeID) + defaults.set(order, forKey: DefaultsKey.order) + } + } + + /// Removes the account's session and metadata. Other accounts are untouched. + func remove(storeID: String) throws { + try keychain.delete(forKey: Self.sessionKey(for: storeID)) + defaults.set(storedOrder.filter { $0 != storeID }, forKey: DefaultsKey.order) + if activeStoreID == storeID { + activeStoreID = nil + } + } + + // MARK: Metadata + + /// The account that was last active, if it still exists. + public var activeStoreID: String? { + get { defaults.string(forKey: DefaultsKey.active) } + nonmutating set { defaults.set(newValue, forKey: DefaultsKey.active) } + } + + /// Persists the display order of accounts. + func setOrder(_ storeIDs: [String]) { + defaults.set(storeIDs, forKey: DefaultsKey.order) + } + + private var storedOrder: [String] { + defaults.stringArray(forKey: DefaultsKey.order) ?? [] + } + + /// Orders `existing` by the stored order, appending unknown IDs (sorted, for stability), and + /// prunes stored IDs that no longer have a session. + private func orderedStoreIDs(existing: Set) -> [String] { + let stored = storedOrder + var order = stored.filter { existing.contains($0) } + order += existing.subtracting(order).sorted() + if order != stored { + defaults.set(order, forKey: DefaultsKey.order) + } + return order + } + + // MARK: Migration + + /// Moves a session stored by earlier versions under the single `UserSession` key to the + /// per-account format. + /// + /// Safe to run on every launch and to interrupt at any point: the new item is written and + /// verified before the legacy item is removed, and an unreadable legacy item is never removed. + func migrateLegacyIfNeeded() throws { + if defaults.integer(forKey: DefaultsKey.schemaVersion) >= Self.currentSchemaVersion { + // A previous migration may have been interrupted before removing the legacy item. + removeLegacySession() + return + } + + guard let legacyData = try keychain.load(forKey: Self.legacySessionKey) else { + defaults.set(Self.currentSchemaVersion, forKey: DefaultsKey.schemaVersion) + return + } + + let legacySession: UserSession + do { + legacySession = try JSONDecoder().decode(UserSession.self, from: legacyData) + } catch { + Logger.matrixClient.error("Legacy session is unreadable, leaving it in place: \(error)") + return + } + + Logger.matrixClient.info("Migrating legacy session to store \(legacySession.storeID)") + try save(legacySession) + guard try load(storeID: legacySession.storeID) == legacySession else { + throw AccountStoreError.migrationVerificationFailed + } + if activeStoreID == nil { + activeStoreID = legacySession.storeID + } + defaults.set(Self.currentSchemaVersion, forKey: DefaultsKey.schemaVersion) + removeLegacySession() + } + + /// The session is already migrated at this point, so failing to remove the old copy must not + /// fail the migration; it is retried on the next launch. + private func removeLegacySession() { + do { + try keychain.delete(forKey: Self.legacySessionKey) + } catch { + Logger.matrixClient.error("Failed to remove legacy session, will retry: \(error)") + } + } +} + +enum AccountStoreError: Error { + case migrationVerificationFailed +} diff --git a/Sources/MatrixIntegration/AppKeychain.swift b/Sources/MatrixIntegration/AppKeychain.swift index e7462add..47e028fa 100644 --- a/Sources/MatrixIntegration/AppKeychain.swift +++ b/Sources/MatrixIntegration/AppKeychain.swift @@ -5,7 +5,15 @@ enum KeychainError: Error { case unexpectedStatus(OSStatus) } -struct AppKeychain { +/// Key-value storage for secrets. Abstracted so account storage can be tested without the system keychain. +protocol KeychainStore: Sendable { + func save(_ data: Data, forKey key: String) throws + func load(forKey key: String) throws -> Data? + func delete(forKey key: String) throws + func keys(withPrefix prefix: String) throws -> [String] +} + +struct AppKeychain: KeychainStore { private let service: String init(service: String = Bundle.main.bundleIdentifier!) { @@ -58,11 +66,29 @@ struct AppKeychain { return result as? Data } - /// Removes all keychain items stored under this service. - func removeAll() throws { - let status = SecItemDelete(baseQuery as CFDictionary) + /// Removes the item stored for the given key. Succeeds if no item exists. + func delete(forKey key: String) throws { + var query = baseQuery + query[kSecAttrAccount] = key + let status = SecItemDelete(query as CFDictionary) guard status == errSecSuccess || status == errSecItemNotFound else { throw KeychainError.unexpectedStatus(status) } } + + /// Returns the keys of all items in this service starting with `prefix`. + func keys(withPrefix prefix: String) throws -> [String] { + var query = baseQuery + query[kSecReturnAttributes] = true + query[kSecMatchLimit] = kSecMatchLimitAll + + var result: AnyObject? + let status = unsafe SecItemCopyMatching(query as CFDictionary, &result) + if status == errSecItemNotFound { return [] } + guard status == errSecSuccess else { + throw KeychainError.unexpectedStatus(status) + } + let items = result as? [[CFString: Any]] ?? [] + return items.compactMap { $0[kSecAttrAccount] as? String }.filter { $0.hasPrefix(prefix) } + } } diff --git a/Sources/MatrixIntegration/HomeserverLogin.swift b/Sources/MatrixIntegration/HomeserverLogin.swift index daf964e9..a216d7c1 100644 --- a/Sources/MatrixIntegration/HomeserverLogin.swift +++ b/Sources/MatrixIntegration/HomeserverLogin.swift @@ -60,15 +60,13 @@ public struct HomeserverLogin { @MainActor fileprivate func onSuccessfullLogin() async throws -> MatrixClient { + let accountStore = AccountStore() let matrixClient = await MatrixClient( - storeID: storeID, storePassphrase: storePassphrase, client: unauthenticatedClient) + storeID: storeID, storePassphrase: storePassphrase, client: unauthenticatedClient, + accountStore: accountStore) - let userSession = try matrixClient.userSession() - do { - try userSession.saveUserToKeychain() - } catch { - print(error.localizedDescription) - } + try accountStore.save(matrixClient.userSession()) + accountStore.activeStoreID = storeID return matrixClient } diff --git a/Sources/MatrixIntegration/MatrixClient.swift b/Sources/MatrixIntegration/MatrixClient.swift index e4196da6..42dd5946 100644 --- a/Sources/MatrixIntegration/MatrixClient.swift +++ b/Sources/MatrixIntegration/MatrixClient.swift @@ -15,6 +15,7 @@ public class MatrixClient { @ObservationIgnored public private(set) lazy var recentReactions = RecentReactionsStore( client: SDKRecentReactionsClient(client: client)) private let storePassphrase: String + @ObservationIgnored nonisolated let accountStore: AccountStore public internal(set) var client: ClientProtocol! public internal(set) var rooms: [SidebarRoom] = [] @@ -35,9 +36,10 @@ public class MatrixClient { return (hints + viaServers).filter { seen.insert($0).inserted } } - init(userSession: UserSession) async throws { + init(userSession: UserSession, accountStore: AccountStore) async throws { storeID = userSession.storeID storePassphrase = userSession.storePassphrase + self.accountStore = accountStore client = try await Self.clientBuilder( homeServer: userSession.homeserverURL, storeId: storeID, storePassphrase: storePassphrase @@ -53,9 +55,12 @@ public class MatrixClient { observeDockIconUnreadCount() } - init(storeID: String, storePassphrase: String, client: ClientProtocol) async { + init( + storeID: String, storePassphrase: String, client: ClientProtocol, accountStore: AccountStore + ) async { self.storeID = storeID self.storePassphrase = storePassphrase + self.accountStore = accountStore self.client = client spaceService = LiveSpaceService(client: self.client, spaceService: await client.spaceService()) @@ -123,10 +128,17 @@ public class MatrixClient { loginDetails: details) } - public static func attemptRestore() async throws -> MatrixClient? { - guard let userSession = try UserSession.loadUserFromKeychain() else { return nil } - - return try await MatrixClient(userSession: userSession) + public static func attemptRestore(accountStore: AccountStore = AccountStore()) async throws + -> MatrixClient? + { + try accountStore.migrateLegacyIfNeeded() + let sessions = try accountStore.loadAll() + guard + let userSession = sessions.first(where: { $0.storeID == accountStore.activeStoreID }) + ?? sessions.first + else { return nil } + + return try await MatrixClient(userSession: userSession, accountStore: accountStore) } public func reset() async throws { @@ -137,7 +149,7 @@ public class MatrixClient { try? await client.logout() try? FileManager.default.removeItem(at: .sessionData(for: storeID)) try? FileManager.default.removeItem(at: .sessionCaches(for: storeID)) - try AppKeychain().removeAll() + try accountStore.remove(storeID: storeID) Logger.matrixClient.debug("matrix client sign out complete") } @@ -304,26 +316,23 @@ extension MatrixClient: MatrixRustSDK.ClientSessionDelegate { Logger.matrixClient.debug( "client session delegate: retrieve session from keychain: \(userId, privacy: .sensitive)") - let userSession = try UserSession.loadUserFromKeychain() - if let userSession { - if userSession.userID == userId { - return userSession.session - } else { - Logger.matrixClient.debug( - "restored user session has wrong userId: \(userSession.userID, privacy: .sensitive), expected \(userId, privacy: .sensitive)" - ) - throw MatrixClientRestoreSessionError.wrongUserId - } - } else { + guard let userSession = try accountStore.load(storeID: storeID) else { throw MatrixClientRestoreSessionError.sessionNotFound } + guard userSession.userID == userId else { + Logger.matrixClient.debug( + "restored user session has wrong userId: \(userSession.userID, privacy: .sensitive), expected \(userId, privacy: .sensitive)" + ) + throw MatrixClientRestoreSessionError.wrongUserId + } + return userSession.session } public nonisolated func saveSessionInKeychain(session: MatrixRustSDK.Session) { Logger.matrixClient.debug("client session delegate: save session in keychain") do { - try UserSession(session: session, storeID: storeID, storePassphrase: storePassphrase) - .saveUserToKeychain() + try accountStore.save( + UserSession(session: session, storeID: storeID, storePassphrase: storePassphrase)) } catch { Logger.matrixClient.error("failed to save session in keychain: \(error)") } diff --git a/Sources/MatrixIntegration/MatrixClientSessionDelegate.swift b/Sources/MatrixIntegration/MatrixClientSessionDelegate.swift deleted file mode 100644 index f0d60d6f..00000000 --- a/Sources/MatrixIntegration/MatrixClientSessionDelegate.swift +++ /dev/null @@ -1,46 +0,0 @@ -import Foundation -import MatrixRustSDK -import OSLog -import Observation -import UniformTypeIdentifiers -import Utils - -final class MatrixClientSessionDelegate: MatrixRustSDK.ClientSessionDelegate { - let storeID: String - let storePassphrase: String - - init(storeID: String, storePassphrase: String) { - self.storeID = storeID - self.storePassphrase = storePassphrase - } - - func retrieveSessionFromKeychain(userId: String) throws -> MatrixRustSDK.Session { - Logger.matrixClient.debug( - "client session delegate: retrieve session from keychain: \(userId, privacy: .sensitive)" - ) - - let userSession = try UserSession.loadUserFromKeychain() - if let userSession { - if userSession.userID == userId { - return userSession.session - } else { - Logger.matrixClient.debug( - "restored user session has wrong userId: \(userSession.userID, privacy: .sensitive), expected \(userId, privacy: .sensitive)" - ) - throw MatrixClientRestoreSessionError.wrongUserId - } - } else { - throw MatrixClientRestoreSessionError.sessionNotFound - } - } - - func saveSessionInKeychain(session: MatrixRustSDK.Session) { - Logger.matrixClient.debug("client session delegate: save session in keychain") - do { - try UserSession(session: session, storeID: storeID, storePassphrase: storePassphrase) - .saveUserToKeychain() - } catch { - Logger.matrixClient.error("failed to save session in keychain: \(error)") - } - } -} diff --git a/Sources/MatrixIntegration/UserSession.swift b/Sources/MatrixIntegration/UserSession.swift index b80a0bfe..55f7dee1 100644 --- a/Sources/MatrixIntegration/UserSession.swift +++ b/Sources/MatrixIntegration/UserSession.swift @@ -1,13 +1,7 @@ -import AsyncAlgorithms import Foundation import MatrixRustSDK -import OSLog -import Observation -import Security -import UniformTypeIdentifiers -import Utils -struct UserSession: Codable { +struct UserSession: Codable, Equatable { let accessToken: String let refreshToken: String? let userID: String @@ -38,19 +32,4 @@ struct UserSession: Codable { oauthData: oauthData, slidingSyncVersion: .native) } - - fileprivate static var keychainKey: String { "UserSession" } - - func saveUserToKeychain() throws { - let keychainData = try JSONEncoder().encode(self) - try AppKeychain().save(keychainData, forKey: Self.keychainKey) - } - - static func loadUserFromKeychain() throws -> Self? { - Logger.matrixClient.debug("Load user from keychain") - if let keychainData = try AppKeychain().load(forKey: keychainKey) { - return try JSONDecoder().decode(Self.self, from: keychainData) - } - return nil - } } diff --git a/Tests/MactrixAppTests/AccountStoreTests.swift b/Tests/MactrixAppTests/AccountStoreTests.swift new file mode 100644 index 00000000..d78b024e --- /dev/null +++ b/Tests/MactrixAppTests/AccountStoreTests.swift @@ -0,0 +1,154 @@ +import Foundation +import MatrixRustSDK +import Synchronization +import Testing + +@testable import MatrixIntegration + +final class FakeKeychain: KeychainStore, Sendable { + let items = Mutex<[String: Data]>([:]) + let failingDeletes = Mutex>([]) + + func save(_ data: Data, forKey key: String) throws { + items.withLock { $0[key] = data } + } + + func load(forKey key: String) throws -> Data? { + items.withLock { $0[key] } + } + + func delete(forKey key: String) throws { + if failingDeletes.withLock({ $0.contains(key) }) { + throw KeychainError.unexpectedStatus(-1) + } + items.withLock { $0[key] = nil } + } + + func keys(withPrefix prefix: String) throws -> [String] { + items.withLock { Array($0.keys) }.filter { $0.hasPrefix(prefix) } + } +} + +func makeUserSession(storeID: String, userID: String = "@alice:example.org", token: String = "t") + -> UserSession +{ + UserSession( + session: Session( + accessToken: token, refreshToken: nil, userId: userID, deviceId: "DEVICE", + homeserverUrl: "https://example.org", oauthData: nil, slidingSyncVersion: .native), + storeID: storeID, storePassphrase: "passphrase") +} + +struct AccountStoreTests { + let keychain = FakeKeychain() + let defaults: UserDefaults + let store: AccountStore + + init() { + let suite = "AccountStoreTests.\(UUID().uuidString)" + defaults = UserDefaults(suiteName: suite)! + defaults.removePersistentDomain(forName: suite) + store = AccountStore(keychain: keychain, defaults: defaults) + } + + func storeLegacy(_ session: UserSession) throws { + try keychain.save(JSONEncoder().encode(session), forKey: AccountStore.legacySessionKey) + } + + @Test func freshInstallHasNoAccounts() throws { + try store.migrateLegacyIfNeeded() + #expect(try store.loadAll().isEmpty) + #expect(store.activeStoreID == nil) + #expect(defaults.integer(forKey: AccountStore.DefaultsKey.schemaVersion) == 1) + } + + @Test func migratesLegacySession() throws { + let legacy = makeUserSession(storeID: "A") + try storeLegacy(legacy) + + try store.migrateLegacyIfNeeded() + + #expect(try store.loadAll() == [legacy]) + #expect(store.activeStoreID == "A") + #expect(try keychain.load(forKey: AccountStore.legacySessionKey) == nil) + } + + @Test func migrationIsIdempotent() throws { + let legacy = makeUserSession(storeID: "A") + try storeLegacy(legacy) + + try store.migrateLegacyIfNeeded() + try store.migrateLegacyIfNeeded() + + #expect(try store.loadAll() == [legacy]) + } + + @Test func interruptedMigrationRemovesLegacyWithoutOverwritingNewerSession() throws { + let legacy = makeUserSession(storeID: "A", token: "old") + try storeLegacy(legacy) + keychain.failingDeletes.withLock { $0.insert(AccountStore.legacySessionKey) } + + // The legacy item survives the first run. The migrated account is still usable. + try store.migrateLegacyIfNeeded() + #expect(try keychain.load(forKey: AccountStore.legacySessionKey) != nil) + #expect(try store.loadAll() == [legacy]) + + // The SDK refreshes the token before the next launch. + let refreshed = makeUserSession(storeID: "A", token: "new") + try store.save(refreshed) + + keychain.failingDeletes.withLock { $0.removeAll() } + try store.migrateLegacyIfNeeded() + + #expect(try store.loadAll() == [refreshed]) + #expect(try keychain.load(forKey: AccountStore.legacySessionKey) == nil) + } + + @Test func unreadableLegacySessionIsKept() throws { + try keychain.save(Data("not json".utf8), forKey: AccountStore.legacySessionKey) + + try store.migrateLegacyIfNeeded() + + #expect(try store.loadAll().isEmpty) + #expect(try keychain.load(forKey: AccountStore.legacySessionKey) == Data("not json".utf8)) + } + + @Test func accountsAreIsolated() throws { + let a = makeUserSession(storeID: "A", userID: "@a:example.org") + let b = makeUserSession(storeID: "B", userID: "@b:example.org") + try store.save(a) + try store.save(b) + + let refreshedA = makeUserSession(storeID: "A", userID: "@a:example.org", token: "new") + try store.save(refreshedA) + #expect(try store.load(storeID: "B") == b) + + try store.remove(storeID: "A") + #expect(try store.loadAll() == [b]) + } + + @Test func preservesOrderAndPrunesMissingAccounts() throws { + try store.save(makeUserSession(storeID: "B")) + try store.save(makeUserSession(storeID: "A")) + try store.save(makeUserSession(storeID: "C")) + #expect(try store.loadAll().map(\.storeID) == ["B", "A", "C"]) + + // An item removed behind our back is dropped from the order. + try keychain.delete(forKey: AccountStore.sessionKey(for: "A")) + #expect(try store.loadAll().map(\.storeID) == ["B", "C"]) + #expect(defaults.stringArray(forKey: AccountStore.DefaultsKey.order) == ["B", "C"]) + } + + @Test func removingActiveAccountClearsActive() throws { + try store.save(makeUserSession(storeID: "A")) + store.activeStoreID = "A" + try store.remove(storeID: "A") + #expect(store.activeStoreID == nil) + } + + @Test func skipsUnreadableSessions() throws { + try store.save(makeUserSession(storeID: "A")) + try keychain.save(Data("garbage".utf8), forKey: AccountStore.sessionKey(for: "B")) + #expect(try store.loadAll().map(\.storeID) == ["A"]) + } +} From 0118561867acdee641abaf755eca71b9c14d1f1f Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Mon, 23 Nov 2026 15:55:40 -0500 Subject: [PATCH 02/35] Keep signed-out accounts and clean up abandoned stores When the server ends a session, stop that client's sync and show a "You were signed out" banner in the sidebar instead of dropping the client immediately. Previously the stale session stayed in the keychain and was restored again on the next launch. Every login attempt creates a store directory before the user signs in, and abandoned attempts left those directories behind. On launch, remove UUID-named store directories that belong to no account and are more than ten minutes old. The sweep is skipped while an unmigrated legacy session exists, and it keeps the stores of sessions that can't be decoded. Store path helpers move to StoreDirectories. --- Sources/MactrixApp/MainView.swift | 6 -- .../Views/Sidebar/SidebarSignedOutView.swift | 45 +++++++++++++++ .../Views/Sidebar/SidebarView.swift | 1 + Sources/MatrixIntegration/AccountStore.swift | 17 ++++-- .../MatrixClient+Listeners.swift | 2 + Sources/MatrixIntegration/MatrixClient.swift | 39 ++++++------- .../MatrixIntegration/StoreDirectories.swift | 57 +++++++++++++++++++ .../StoreDirectoriesTests.swift | 48 ++++++++++++++++ 8 files changed, 186 insertions(+), 29 deletions(-) create mode 100644 Sources/MactrixApp/Views/Sidebar/SidebarSignedOutView.swift create mode 100644 Sources/MatrixIntegration/StoreDirectories.swift create mode 100644 Tests/MactrixAppTests/StoreDirectoriesTests.swift diff --git a/Sources/MactrixApp/MainView.swift b/Sources/MactrixApp/MainView.swift index 6775c089..c6407df3 100644 --- a/Sources/MactrixApp/MainView.swift +++ b/Sources/MactrixApp/MainView.swift @@ -146,12 +146,6 @@ public struct MainView: View { showWelcomeSheet = true } } - .onChange(of: appState.matrixClient?.authenticationFailed) { _, authFailed in - if authFailed == true { - Logger.viewCycle.info("Logging out since auth failed") - appState.matrixClient = nil - } - } .onOpenURL { url in Logger.viewCycle.debug("onOpenUrl \(url)") diff --git a/Sources/MactrixApp/Views/Sidebar/SidebarSignedOutView.swift b/Sources/MactrixApp/Views/Sidebar/SidebarSignedOutView.swift new file mode 100644 index 00000000..20c4e739 --- /dev/null +++ b/Sources/MactrixApp/Views/Sidebar/SidebarSignedOutView.swift @@ -0,0 +1,45 @@ +import OSLog +import SwiftUI + +/// Shown when the server has ended the active account's session. +struct SidebarSignedOutView: View { + @Environment(AppState.self) var appState + @Environment(\.colorScheme) var colorScheme + + @State private var signingOut = false + + var body: some View { + if let matrixClient = appState.matrixClient, matrixClient.authenticationFailed { + VStack { + Label { + Text("You were signed out.") + .bold() + Text("This session was ended by the server or another device.") + .lineLimit(9) + } icon: { + Image(systemName: "person.crop.circle.badge.exclamationmark") + .bold() + } + .labelStyle(.multiline) + .frame(maxWidth: .infinity) + + Button("Sign In Again…") { + Task { + signingOut = true + defer { signingOut = false } + do { + try await appState.reset() + } catch { + Logger.viewCycle.error("Failed to remove signed out account: \(error)") + } + } + } + .disabled(signingOut) + } + .padding(10) + .background(Color.orange.opacity(0.2)) + .foregroundStyle(Color.orange.mix(with: colorScheme == .light ? .black : .white, by: 0.5)) + .clipShape(RoundedRectangle(cornerRadius: 8)) + } + } +} diff --git a/Sources/MactrixApp/Views/Sidebar/SidebarView.swift b/Sources/MactrixApp/Views/Sidebar/SidebarView.swift index 2ff497da..f8f52444 100644 --- a/Sources/MactrixApp/Views/Sidebar/SidebarView.swift +++ b/Sources/MactrixApp/Views/Sidebar/SidebarView.swift @@ -100,6 +100,7 @@ struct SidebarView: View { private var statusContent: some View { VStack(spacing: 8) { + SidebarSignedOutView() SidebarSyncStateView() SessionVerificationStatusView() } diff --git a/Sources/MatrixIntegration/AccountStore.swift b/Sources/MatrixIntegration/AccountStore.swift index 2046bd36..3119dfcf 100644 --- a/Sources/MatrixIntegration/AccountStore.swift +++ b/Sources/MatrixIntegration/AccountStore.swift @@ -38,11 +38,8 @@ public struct AccountStore: Sendable { /// Returns all stored sessions in display order. Unreadable items are skipped. func loadAll() throws -> [UserSession] { - let storeIDs = try keychain.keys(withPrefix: Self.sessionKeyPrefix) - .map { String($0.dropFirst(Self.sessionKeyPrefix.count)) } - var sessions: [String: UserSession] = [:] - for storeID in storeIDs { + for storeID in try allStoreIDs() { do { if let session = try load(storeID: storeID) { sessions[storeID] = session @@ -56,6 +53,18 @@ public struct AccountStore: Sendable { return order.compactMap { sessions[$0] } } + /// The store IDs of every stored session, including ones that can't be decoded. + func allStoreIDs() throws -> Set { + Set( + try keychain.keys(withPrefix: Self.sessionKeyPrefix) + .map { String($0.dropFirst(Self.sessionKeyPrefix.count)) }) + } + + /// Whether a session from before per-account storage is still present. + func hasLegacySession() throws -> Bool { + try keychain.load(forKey: Self.legacySessionKey) != nil + } + func load(storeID: String) throws -> UserSession? { guard let data = try keychain.load(forKey: Self.sessionKey(for: storeID)) else { return nil } return try JSONDecoder().decode(UserSession.self, from: data) diff --git a/Sources/MatrixIntegration/MatrixClient+Listeners.swift b/Sources/MatrixIntegration/MatrixClient+Listeners.swift index d89e949b..62ca8f33 100644 --- a/Sources/MatrixIntegration/MatrixClient+Listeners.swift +++ b/Sources/MatrixIntegration/MatrixClient+Listeners.swift @@ -136,6 +136,8 @@ extension MatrixClient: MatrixRustSDK.ClientDelegate { "did receive auth error: soft logout \(isSoftLogout, privacy: .public)") if !isSoftLogout { authenticationFailed = true + // The session is gone; keep the account listed but stop using it. + await syncService?.stop() } } } diff --git a/Sources/MatrixIntegration/MatrixClient.swift b/Sources/MatrixIntegration/MatrixClient.swift index 42dd5946..4c57625b 100644 --- a/Sources/MatrixIntegration/MatrixClient.swift +++ b/Sources/MatrixIntegration/MatrixClient.swift @@ -77,8 +77,8 @@ public class MatrixClient { -> ClientBuilder { let sqliteConfig = SqliteStoreBuilder( - dataPath: URL.sessionData(for: storeId).path(percentEncoded: false), - cachePath: URL.sessionCaches(for: storeId).path(percentEncoded: false) + dataPath: StoreDirectories.data(for: storeId).path(percentEncoded: false), + cachePath: StoreDirectories.caches(for: storeId).path(percentEncoded: false) ) .passphrase(passphrase: storePassphrase) @@ -86,7 +86,7 @@ public class MatrixClient { .serverNameOrHomeserverUrl(serverNameOrUrl: homeServer) .sqliteStore(config: sqliteConfig) .withSearchIndexStore( - path: URL.sessionCaches(for: storeId).appending(component: "SearchIndex") + path: StoreDirectories.caches(for: storeId).appending(component: "SearchIndex") .path(percentEncoded: false), key: storePassphrase ) @@ -132,6 +132,7 @@ public class MatrixClient { -> MatrixClient? { try accountStore.migrateLegacyIfNeeded() + removeOrphanedStores(accountStore: accountStore) let sessions = try accountStore.loadAll() guard let userSession = sessions.first(where: { $0.storeID == accountStore.activeStoreID }) @@ -141,14 +142,28 @@ public class MatrixClient { return try await MatrixClient(userSession: userSession, accountStore: accountStore) } + /// Deletes store directories left behind by abandoned logins. + static func removeOrphanedStores(accountStore: AccountStore) { + do { + // An unmigrated legacy session's store isn't listed yet, so it must not be swept. + guard try !accountStore.hasLegacySession() else { return } + StoreDirectories.removeOrphans( + in: [StoreDirectories.dataRoot, StoreDirectories.cachesRoot], + keeping: try accountStore.allStoreIDs(), + createdBefore: Date.now.addingTimeInterval(-10 * 60)) + } catch { + Logger.matrixClient.error("Skipping orphaned store cleanup: \(error)") + } + } + public func reset() async throws { recentReactions.invalidate() isResettingSession = true await roomSubscriptions.invalidate() Logger.matrixClient.debug("matrix client sign out") try? await client.logout() - try? FileManager.default.removeItem(at: .sessionData(for: storeID)) - try? FileManager.default.removeItem(at: .sessionCaches(for: storeID)) + try? FileManager.default.removeItem(at: StoreDirectories.data(for: storeID)) + try? FileManager.default.removeItem(at: StoreDirectories.caches(for: storeID)) try accountStore.remove(storeID: storeID) Logger.matrixClient.debug("matrix client sign out complete") } @@ -338,17 +353,3 @@ extension MatrixClient: MatrixRustSDK.ClientSessionDelegate { } } } - -extension URL { - fileprivate static func sessionData(for sessionID: String) -> URL { - applicationSupportDirectory - .appending(component: "dk.qpqp.mactrix") - .appending(component: sessionID) - } - - fileprivate static func sessionCaches(for sessionID: String) -> URL { - cachesDirectory - .appending(component: "dk.qpqp.mactrix") - .appending(component: sessionID) - } -} diff --git a/Sources/MatrixIntegration/StoreDirectories.swift b/Sources/MatrixIntegration/StoreDirectories.swift new file mode 100644 index 00000000..ab5e7785 --- /dev/null +++ b/Sources/MatrixIntegration/StoreDirectories.swift @@ -0,0 +1,57 @@ +import Foundation +import OSLog + +/// Locations of the per-account SQLite stores, which are named by `storeID`. +enum StoreDirectories { + static let appDirectoryName = "dk.qpqp.mactrix" + + static var dataRoot: URL { + URL.applicationSupportDirectory.appending(component: appDirectoryName) + } + + static var cachesRoot: URL { + URL.cachesDirectory.appending(component: appDirectoryName) + } + + static func data(for storeID: String) -> URL { + dataRoot.appending(component: storeID) + } + + static func caches(for storeID: String) -> URL { + cachesRoot.appending(component: storeID) + } + + /// Deletes store directories that belong to no account, such as those created for a login + /// that was abandoned. + /// + /// Only directories named by a UUID (as created for new stores) and created before `cutoff` + /// are removed. Returns the removed directories. + @discardableResult + static func removeOrphans( + in roots: [URL], keeping storeIDs: Set, createdBefore cutoff: Date, + fileManager: FileManager = .default + ) -> [URL] { + var removed: [URL] = [] + for root in roots { + let children = + (try? fileManager.contentsOfDirectory( + at: root, includingPropertiesForKeys: [.creationDateKey, .isDirectoryKey])) ?? [] + for child in children { + let name = child.lastPathComponent + guard UUID(uuidString: name) != nil, !storeIDs.contains(name) else { continue } + let values = try? child.resourceValues(forKeys: [.creationDateKey, .isDirectoryKey]) + guard values?.isDirectory == true, + let created = values?.creationDate, created < cutoff + else { continue } + do { + try fileManager.removeItem(at: child) + removed.append(child) + Logger.matrixClient.info("Removed orphaned store \(name)") + } catch { + Logger.matrixClient.error("Failed to remove orphaned store \(name): \(error)") + } + } + } + return removed + } +} diff --git a/Tests/MactrixAppTests/StoreDirectoriesTests.swift b/Tests/MactrixAppTests/StoreDirectoriesTests.swift new file mode 100644 index 00000000..762ad511 --- /dev/null +++ b/Tests/MactrixAppTests/StoreDirectoriesTests.swift @@ -0,0 +1,48 @@ +import Foundation +import Testing + +@testable import MatrixIntegration + +struct StoreDirectoriesTests { + let root: URL + let fileManager = FileManager.default + + init() throws { + root = fileManager.temporaryDirectory.appending(component: "StoreDirectoriesTests-\(UUID())") + try fileManager.createDirectory(at: root, withIntermediateDirectories: true) + } + + func makeDirectory(_ name: String, createdAt date: Date) throws -> URL { + let url = root.appending(component: name) + try fileManager.createDirectory(at: url, withIntermediateDirectories: true) + try fileManager.setAttributes([.creationDate: date], ofItemAtPath: url.path) + return url + } + + @Test func removesOnlyOldUnreferencedStores() throws { + let old = Date.now.addingTimeInterval(-3600) + let kept = UUID().uuidString + let orphan = UUID().uuidString + let inProgress = UUID().uuidString + + let keptURL = try makeDirectory(kept, createdAt: old) + let orphanURL = try makeDirectory(orphan, createdAt: old) + let inProgressURL = try makeDirectory(inProgress, createdAt: .now) + let unrelatedURL = try makeDirectory("not-a-store", createdAt: old) + + let removed = StoreDirectories.removeOrphans( + in: [root], keeping: [kept], createdBefore: Date.now.addingTimeInterval(-600)) + + #expect(removed.map(\.lastPathComponent) == [orphan]) + #expect(fileManager.fileExists(atPath: keptURL.path)) + #expect(!fileManager.fileExists(atPath: orphanURL.path)) + #expect(fileManager.fileExists(atPath: inProgressURL.path)) + #expect(fileManager.fileExists(atPath: unrelatedURL.path)) + } + + @Test func missingRootIsIgnored() { + let removed = StoreDirectories.removeOrphans( + in: [root.appending(component: "missing")], keeping: [], createdBefore: .now) + #expect(removed.isEmpty) + } +} From aac396a74651d58bcedb0c37a89abfef3c3c0aff Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Mon, 23 Nov 2026 15:58:31 -0500 Subject: [PATCH 03/35] Support multiple signed-in accounts AppState now holds every signed-in account and which one is active. `matrixClient` returns the active account, so existing views are unchanged. All accounts are restored at launch and keep syncing in the background. An account that fails to restore is skipped instead of blocking the others. Signing in adds an account rather than replacing the current one. Signing in to an account that's already listed is rejected, and the new session is signed out again so it doesn't linger as an extra device. If the listed account was signed out by the server, the new session replaces it in the same position. Each window remembers the selected room and space per account and restores them when switching back. Window state saved by earlier versions has no account and is adopted by the first account shown, so existing windows reopen on the same room. Signing out of one account no longer quits the app when others remain. --- Sources/MactrixApp/MainView.swift | 38 ++---- Sources/MactrixApp/Models/AppState.swift | 124 +++++++++++++++++- Sources/MactrixApp/Models/WindowState.swift | 46 +++++++ .../MactrixApp/Views/WelcomeSheetView.swift | 4 +- Sources/MatrixIntegration/AccountStore.swift | 2 +- .../MatrixIntegration/HomeserverLogin.swift | 3 +- Sources/MatrixIntegration/MatrixClient.swift | 40 ++++-- .../WindowStateAccountTests.swift | 100 ++++++++++++++ 8 files changed, 305 insertions(+), 52 deletions(-) create mode 100644 Tests/MactrixAppTests/WindowStateAccountTests.swift diff --git a/Sources/MactrixApp/MainView.swift b/Sources/MactrixApp/MainView.swift index c6407df3..9047e573 100644 --- a/Sources/MactrixApp/MainView.swift +++ b/Sources/MactrixApp/MainView.swift @@ -140,9 +140,12 @@ public struct MainView: View { } } ) - .onChange(of: appState.matrixClient == nil) { _, matrixClientIsNil in - if matrixClientIsNil { - Logger.viewCycle.info("Matrix client is nil, present welcome sheet") + .onChange(of: appState.restoration, initial: true) { _, restoration in + guard case .restored(let activeAccountID) = restoration else { return } + windowState.showAccount( + activeAccountID, knownAccountIDs: Set(appState.accounts.map(\.storeID))) + if activeAccountID == nil { + Logger.viewCycle.info("No signed in accounts, present welcome sheet") showWelcomeSheet = true } } @@ -165,39 +168,14 @@ public struct MainView: View { } func attemptLoadUserSession() async { - guard appState.matrixClient == nil else { return } - - do { - if let matrixClient = try await MatrixClient.attemptRestore() { - appState.matrixClient = matrixClient - } - } catch { - Logger.viewCycle.error("Failed to restore matrix session: \(error)") - } - - showWelcomeSheet = appState.matrixClient == nil - if let matrixClient = appState.matrixClient { - onMatrixLoaded(matrixClient: matrixClient) - } - } - - func onMatrixLoaded(matrixClient: MatrixClient) { - Task { - do { - try await matrixClient.startSync() - } catch { - Logger.matrixClient.error("Failed to start sync: \(error)") - } - } + await appState.restoreAccounts() } func onLoginModalDismiss() { Task { do { try await Task.sleep(for: .milliseconds(100)) - if let matrixClient = appState.matrixClient { - onMatrixLoaded(matrixClient: matrixClient) - } else { + if appState.accounts.isEmpty { NSApp.terminate(nil) } } catch is CancellationError { diff --git a/Sources/MactrixApp/Models/AppState.swift b/Sources/MactrixApp/Models/AppState.swift index 83f347a7..6ab77821 100644 --- a/Sources/MactrixApp/Models/AppState.swift +++ b/Sources/MactrixApp/Models/AppState.swift @@ -1,19 +1,135 @@ +import Foundation import MatrixIntegration import OSLog import Observation +/// The signed-in accounts and which one is shown. +/// +/// Every account syncs in the background; the UI shows the active one, exposed as `matrixClient`. @MainActor @Observable public final class AppState { - public var matrixClient: MatrixClient? + public enum Restoration: Equatable { + case pending + /// Stored accounts have been restored; carries the active account's `storeID`. + case restored(activeAccountID: String?) + } + + public enum AccountError: LocalizedError { + case alreadySignedIn(userID: String) + + public var errorDescription: String? { + switch self { + case .alreadySignedIn(let userID): + "You're already signed in as \(userID)." + } + } + } + + /// Signed-in accounts in display order. + public private(set) var accounts: [MatrixClient] = [] + public private(set) var activeAccountID: String? + private var hasRestored = false + + @ObservationIgnored private let accountStore: AccountStore + @ObservationIgnored private var restoreTask: Task? + + public init() { + accountStore = AccountStore() + } + + /// The active account. + public var matrixClient: MatrixClient? { + accounts.first { $0.storeID == activeAccountID } + } + + public var restoration: Restoration { + hasRestored ? .restored(activeAccountID: activeAccountID) : .pending + } - public init() {} + /// Restores stored accounts and starts syncing them. Runs once; later calls wait for the first. + public func restoreAccounts() async { + if let restoreTask { + await restoreTask.value + return + } + let task = Task { await performRestore() } + restoreTask = task + await task.value + } + private func performRestore() async { + let clients = await MatrixClient.restoreAll(accountStore: accountStore) + accounts = clients + let storedActive = accountStore.activeStoreID + hasRestored = true + activate(clients.first { $0.storeID == storedActive } ?? clients.first) + for client in clients { + startSync(client) + } + } + + /// Adds a newly signed-in account and makes it active. + /// + /// Signing in to an account that is already listed is rejected: the new session is signed out + /// again so it doesn't linger as an extra device. If the listed account was signed out by the + /// server, the new session replaces it instead. + public func add(_ client: MatrixClient) async throws { + if let existing = accounts.first(where: { $0.userID == client.userID }) { + if existing.authenticationFailed { + let index = accounts.firstIndex { $0 === existing }! + await discard(existing) + accounts.insert(client, at: min(index, accounts.count)) + accountStore.setOrder(accounts.map(\.storeID)) + } else { + Logger.matrixClient.info("Rejecting duplicate sign-in for store \(client.storeID)") + await discard(client) + activate(existing) + throw AccountError.alreadySignedIn(userID: client.userID) + } + } else { + accounts.append(client) + } + activate(client) + startSync(client) + } + + public func activate(_ client: MatrixClient?) { + activeAccountID = client?.storeID + accountStore.activeStoreID = client?.storeID + } + + /// Signs out of `client` and removes it, activating another account if it was active. + public func remove(_ client: MatrixClient) async { + accounts.removeAll { $0 === client } + // Switch before signing out, which waits for the server. + if client.storeID == activeAccountID { + activate(accounts.first) + } + await discard(client) + } + + /// Signs out of the active account. public func reset() async throws { + guard let matrixClient else { return } + await remove(matrixClient) + } + + private func discard(_ client: MatrixClient) async { + accounts.removeAll { $0 === client } do { - try await matrixClient?.reset() + try await client.reset() } catch { Logger.viewCycle.error("Failed to reset matrix client: \(error)") } - matrixClient = nil + } + + private func startSync(_ client: MatrixClient) { + Task { + do { + try await client.startSync() + } catch { + Logger.matrixClient.error("Failed to start sync: \(error)") + } + } } } diff --git a/Sources/MactrixApp/Models/WindowState.swift b/Sources/MactrixApp/Models/WindowState.swift index f635bc14..ea92bf6a 100644 --- a/Sources/MactrixApp/Models/WindowState.swift +++ b/Sources/MactrixApp/Models/WindowState.swift @@ -87,6 +87,9 @@ public final class WindowState { var conversationSelection: ConversationMessageSelection? + /// The account whose rooms `selectedRoomId` and `selectedSpaceId` refer to. + public private(set) var accountID: String? + public var selectedRoomId: String? { get { switch selectedScreen.content { @@ -122,6 +125,8 @@ public final class WindowState { } public var selectedSpaceId: String? + /// The last selection of accounts other than `accountID`, restored when switching back. + var accountSelections: [String: AccountSelection] = [:] public var inspectorVisible: Bool = false public var inspectorContent: InspectorContent = .roomInfo @@ -151,6 +156,35 @@ public final class WindowState { ) } + /// Shows `newAccountID`, remembering the current account's selection and restoring the new one's. + /// + /// `knownAccountIDs` lists the accounts that still exist; selections of others are dropped. + public func showAccount(_ newAccountID: String?, knownAccountIDs: Set) { + accountSelections = accountSelections.filter { knownAccountIDs.contains($0.key) } + guard newAccountID != accountID else { return } + + // State saved before multi-account support has no account; it belongs to the first one shown. + if accountID == nil, newAccountID != nil, accountSelections.isEmpty { + accountID = newAccountID + return + } + + if let accountID, knownAccountIDs.contains(accountID) { + accountSelections[accountID] = AccountSelection( + roomId: selectedRoomId, spaceId: selectedSpaceId) + } + let restored = newAccountID.flatMap { accountSelections.removeValue(forKey: $0) } + accountID = newAccountID + selectedScreen = .none + selectedRoomId = restored?.roomId + selectedSpaceId = restored?.spaceId + inspectorContent = .roomInfo + searchQuery = "" + searchTokens = [] + searchDirectResult = nil + requestedVerification = false + } + public func toggleInspector() { if inspectorVisible { if inspectorContent == .roomInfo { @@ -235,18 +269,28 @@ public final class WindowState { } } +struct AccountSelection: Codable, Equatable { + var roomId: String? + var spaceId: String? +} + extension WindowState: @MainActor RawRepresentable { public struct SceneStorageRepresentation: Codable { let selectedRoomId: String? let selectedSpaceId: String? let inspectorVisible: Bool let sidebarSections: SidebarSectionCollapsibility + // Absent in state saved before multi-account support. + let accountID: String? + let accountSelections: [String: AccountSelection]? @MainActor init(windowState: WindowState) { self.selectedRoomId = windowState.selectedRoomId self.selectedSpaceId = windowState.selectedSpaceId self.inspectorVisible = windowState.inspectorVisible self.sidebarSections = windowState.sidebarSections + self.accountID = windowState.accountID + self.accountSelections = windowState.accountSelections } @MainActor func restore(windowState: WindowState) { @@ -254,6 +298,8 @@ extension WindowState: @MainActor RawRepresentable { windowState.selectedSpaceId = selectedSpaceId windowState.inspectorVisible = inspectorVisible windowState.sidebarSections = sidebarSections + windowState.accountID = accountID + windowState.accountSelections = accountSelections ?? [:] } } diff --git a/Sources/MactrixApp/Views/WelcomeSheetView.swift b/Sources/MactrixApp/Views/WelcomeSheetView.swift index b835ec81..c819d353 100644 --- a/Sources/MactrixApp/Views/WelcomeSheetView.swift +++ b/Sources/MactrixApp/Views/WelcomeSheetView.swift @@ -58,7 +58,7 @@ struct WelcomeSheetView: View { do { let client = try await homeserverLogin.loginPassword( homeServer: homeserverField, username: usernameField, password: passwordField) - appState.matrixClient = client + try await appState.add(client) dismiss() } catch { showError = error @@ -74,7 +74,7 @@ struct WelcomeSheetView: View { do { let client = try await homeserverLogin.loginOidc(webAuthSession: webAuthenticationSession) - appState.matrixClient = client + try await appState.add(client) dismiss() } catch { showError = error diff --git a/Sources/MatrixIntegration/AccountStore.swift b/Sources/MatrixIntegration/AccountStore.swift index 3119dfcf..6a7755c7 100644 --- a/Sources/MatrixIntegration/AccountStore.swift +++ b/Sources/MatrixIntegration/AccountStore.swift @@ -100,7 +100,7 @@ public struct AccountStore: Sendable { } /// Persists the display order of accounts. - func setOrder(_ storeIDs: [String]) { + public func setOrder(_ storeIDs: [String]) { defaults.set(storeIDs, forKey: DefaultsKey.order) } diff --git a/Sources/MatrixIntegration/HomeserverLogin.swift b/Sources/MatrixIntegration/HomeserverLogin.swift index a216d7c1..38f0ef53 100644 --- a/Sources/MatrixIntegration/HomeserverLogin.swift +++ b/Sources/MatrixIntegration/HomeserverLogin.swift @@ -61,12 +61,11 @@ public struct HomeserverLogin { @MainActor fileprivate func onSuccessfullLogin() async throws -> MatrixClient { let accountStore = AccountStore() - let matrixClient = await MatrixClient( + let matrixClient = try await MatrixClient( storeID: storeID, storePassphrase: storePassphrase, client: unauthenticatedClient, accountStore: accountStore) try accountStore.save(matrixClient.userSession()) - accountStore.activeStoreID = storeID return matrixClient } diff --git a/Sources/MatrixIntegration/MatrixClient.swift b/Sources/MatrixIntegration/MatrixClient.swift index 4c57625b..888dc42b 100644 --- a/Sources/MatrixIntegration/MatrixClient.swift +++ b/Sources/MatrixIntegration/MatrixClient.swift @@ -11,6 +11,8 @@ import Utils @MainActor @Observable public class MatrixClient { public let storeID: String + /// The Matrix user ID of this account. + public let userID: String @ObservationIgnored let roomSubscriptions = RoomSubscriptions() @ObservationIgnored public private(set) lazy var recentReactions = RecentReactionsStore( client: SDKRecentReactionsClient(client: client)) @@ -38,6 +40,7 @@ public class MatrixClient { init(userSession: UserSession, accountStore: AccountStore) async throws { storeID = userSession.storeID + userID = userSession.userID storePassphrase = userSession.storePassphrase self.accountStore = accountStore @@ -57,8 +60,9 @@ public class MatrixClient { init( storeID: String, storePassphrase: String, client: ClientProtocol, accountStore: AccountStore - ) async { + ) async throws { self.storeID = storeID + self.userID = try client.userId() self.storePassphrase = storePassphrase self.accountStore = accountStore self.client = client @@ -128,18 +132,27 @@ public class MatrixClient { loginDetails: details) } - public static func attemptRestore(accountStore: AccountStore = AccountStore()) async throws - -> MatrixClient? - { - try accountStore.migrateLegacyIfNeeded() - removeOrphanedStores(accountStore: accountStore) - let sessions = try accountStore.loadAll() - guard - let userSession = sessions.first(where: { $0.storeID == accountStore.activeStoreID }) - ?? sessions.first - else { return nil } - - return try await MatrixClient(userSession: userSession, accountStore: accountStore) + /// Restores every stored account. Accounts that fail to restore are skipped and logged. + public static func restoreAll(accountStore: AccountStore) async -> [MatrixClient] { + let sessions: [UserSession] + do { + try accountStore.migrateLegacyIfNeeded() + removeOrphanedStores(accountStore: accountStore) + sessions = try accountStore.loadAll() + } catch { + Logger.matrixClient.error("Failed to load stored accounts: \(error)") + return [] + } + + var clients: [MatrixClient] = [] + for session in sessions { + do { + clients.append(try await MatrixClient(userSession: session, accountStore: accountStore)) + } catch { + Logger.matrixClient.error("Failed to restore store \(session.storeID): \(error)") + } + } + return clients } /// Deletes store directories left behind by abandoned logins. @@ -160,6 +173,7 @@ public class MatrixClient { recentReactions.invalidate() isResettingSession = true await roomSubscriptions.invalidate() + await syncService?.stop() Logger.matrixClient.debug("matrix client sign out") try? await client.logout() try? FileManager.default.removeItem(at: StoreDirectories.data(for: storeID)) diff --git a/Tests/MactrixAppTests/WindowStateAccountTests.swift b/Tests/MactrixAppTests/WindowStateAccountTests.swift new file mode 100644 index 00000000..5667c2ed --- /dev/null +++ b/Tests/MactrixAppTests/WindowStateAccountTests.swift @@ -0,0 +1,100 @@ +import Foundation +import Testing + +@testable import MactrixApp + +@MainActor +struct WindowStateAccountTests { + @Test func stateSavedBeforeMultiAccountIsAdoptedByFirstAccount() throws { + let legacy = """ + {"selectedRoomId":"!room:example.org","selectedSpaceId":"!space:example.org",\ + "inspectorVisible":true,"sidebarSections":\(try sidebarJSON())} + """ + let windowState = try #require(WindowState(rawValue: legacy)) + #expect(windowState.accountID == nil) + + windowState.showAccount("A", knownAccountIDs: ["A"]) + + #expect(windowState.accountID == "A") + #expect(windowState.selectedRoomId == "!room:example.org") + #expect(windowState.selectedSpaceId == "!space:example.org") + #expect(windowState.inspectorVisible) + } + + @Test func switchingRestoresEachAccountsSelection() { + let windowState = WindowState() + windowState.showAccount("A", knownAccountIDs: ["A", "B"]) + windowState.selectedRoomId = "!a:example.org" + windowState.selectedSpaceId = "!a-space:example.org" + + windowState.showAccount("B", knownAccountIDs: ["A", "B"]) + #expect(windowState.selectedRoomId == nil) + #expect(windowState.selectedSpaceId == nil) + windowState.selectedRoomId = "!b:example.org" + + windowState.showAccount("A", knownAccountIDs: ["A", "B"]) + #expect(windowState.selectedRoomId == "!a:example.org") + #expect(windowState.selectedSpaceId == "!a-space:example.org") + + windowState.showAccount("B", knownAccountIDs: ["A", "B"]) + #expect(windowState.selectedRoomId == "!b:example.org") + } + + @Test func switchingResetsTransientState() { + let windowState = WindowState() + windowState.showAccount("A", knownAccountIDs: ["A", "B"]) + windowState.inspectorContent = .roomThreads + windowState.searchQuery = "hello" + windowState.searchTokens = [.rooms] + + windowState.showAccount("B", knownAccountIDs: ["A", "B"]) + + #expect(windowState.inspectorContent == .roomInfo) + #expect(windowState.searchQuery.isEmpty) + #expect(windowState.searchTokens.isEmpty) + if case .none = windowState.selectedScreen.content {} else { Issue.record("screen not reset") } + } + + @Test func removedAccountsAreForgotten() { + let windowState = WindowState() + windowState.showAccount("A", knownAccountIDs: ["A", "B"]) + windowState.selectedRoomId = "!a:example.org" + windowState.showAccount("B", knownAccountIDs: ["A", "B"]) + #expect(windowState.accountSelections.keys.contains("A")) + + // Account A is signed out while B is shown. + windowState.showAccount("B", knownAccountIDs: ["B"]) + #expect(windowState.accountSelections.isEmpty) + } + + @Test func signingOutOfLastAccountClearsSelection() { + let windowState = WindowState() + windowState.showAccount("A", knownAccountIDs: ["A"]) + windowState.selectedRoomId = "!a:example.org" + + windowState.showAccount(nil, knownAccountIDs: []) + #expect(windowState.accountID == nil) + #expect(windowState.selectedRoomId == nil) + + windowState.showAccount("C", knownAccountIDs: ["C"]) + #expect(windowState.accountID == "C") + #expect(windowState.selectedRoomId == nil) + } + + @Test func roundTripsThroughSceneStorage() throws { + let windowState = WindowState() + windowState.showAccount("A", knownAccountIDs: ["A", "B"]) + windowState.selectedRoomId = "!a:example.org" + windowState.showAccount("B", knownAccountIDs: ["A", "B"]) + windowState.selectedRoomId = "!b:example.org" + + let restored = try #require(WindowState(rawValue: windowState.rawValue)) + #expect(restored.accountID == "B") + #expect(restored.selectedRoomId == "!b:example.org") + #expect(restored.accountSelections["A"] == AccountSelection(roomId: "!a:example.org")) + } + + private func sidebarJSON() throws -> String { + String(decoding: try JSONEncoder().encode(SidebarSectionCollapsibility()), as: UTF8.self) + } +} From 75131f11f7963d3a85efbede1193f78712ab4c54 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Mon, 23 Nov 2026 16:00:35 -0500 Subject: [PATCH 04/35] Add account switcher A menu at the top of the sidebar shows the active account. It lists every account with its unread count, and has Add Account and Sign Out (with a confirmation). A new Account menu in the menu bar lists accounts with Command-Control-1 through 9 and also offers Add Account. The sign-in sheet now knows why it's shown. When adding an account it has a Cancel button. When an account was signed out by the server, the banner offers Sign In Again, which opens the sheet pre-filled with that user ID and replaces the old session in place. It also offers Remove Account. The Account and Sessions settings tabs show which account they apply to. MatrixClient loads its own display name and avatar for these labels. --- Mactrix/MactrixApp.swift | 2 +- Sources/MactrixApp/Commands.swift | 33 +++++- Sources/MactrixApp/MainView.swift | 8 +- Sources/MactrixApp/Models/WindowState.swift | 19 ++++ .../Views/Settings/AccountSettingsView.swift | 16 ++- .../Views/Settings/SessionsSettingsView.swift | 10 ++ .../Views/Sidebar/AccountSwitcher.swift | 104 ++++++++++++++++++ .../Views/Sidebar/SidebarSignedOutView.swift | 23 ++-- .../Views/Sidebar/SidebarView.swift | 16 ++- .../MactrixApp/Views/WelcomeSheetView.swift | 25 ++++- .../MatrixClient+Listeners.swift | 3 +- Sources/MatrixIntegration/MatrixClient.swift | 18 +++ 12 files changed, 250 insertions(+), 27 deletions(-) create mode 100644 Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift diff --git a/Mactrix/MactrixApp.swift b/Mactrix/MactrixApp.swift index a964ab88..6c64d06d 100644 --- a/Mactrix/MactrixApp.swift +++ b/Mactrix/MactrixApp.swift @@ -15,7 +15,7 @@ struct MactrixApp: App { .windowToolbarStyle(.automatic) .environment(appState) .commands { - AppCommands() + AppCommands(appState: appState) } .onChange(of: windowState == nil, focusNotification) .onChange(of: appState.matrixClient?.notifications.selectedRoomId == nil, focusNotification) diff --git a/Sources/MactrixApp/Commands.swift b/Sources/MactrixApp/Commands.swift index da73544c..0a09302d 100644 --- a/Sources/MactrixApp/Commands.swift +++ b/Sources/MactrixApp/Commands.swift @@ -1,10 +1,13 @@ import SwiftUI public struct AppCommands: Commands { + let appState: AppState @FocusedValue(WindowState.self) private var windowState: WindowState? @AppStorage("fontSize") var fontSize: Int = 13 - public init() {} + public init(appState: AppState) { + self.appState = appState + } public var body: some Commands { SidebarCommands() @@ -17,9 +20,37 @@ public struct AppCommands: Commands { createRoom quickNavigation fontSizeCommands + accountCommands conversationCommands } + var accountCommands: some Commands { + CommandMenu("Account") { + ForEach(Array(appState.accounts.enumerated()), id: \.element.storeID) { index, account in + Toggle( + isOn: Binding( + get: { appState.activeAccountID == account.storeID }, + set: { if $0 { appState.activate(account) } }) + ) { + Text(account.accountName) + } + .keyboardShortcut( + index < 9 + ? KeyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: [.command, .control]) + : nil) + } + + if !appState.accounts.isEmpty { + Divider() + } + + Button("Add Account…") { + windowState?.loginSheet = .addAccount + } + .disabled(windowState == nil) + } + } + var about: some Commands { CommandGroup(replacing: .appInfo) { Button("About Mactrix") { diff --git a/Sources/MactrixApp/MainView.swift b/Sources/MactrixApp/MainView.swift index 9047e573..43a5ffe4 100644 --- a/Sources/MactrixApp/MainView.swift +++ b/Sources/MactrixApp/MainView.swift @@ -11,8 +11,6 @@ public struct MainView: View { @SceneStorage("MainView.windowState") private var windowState: WindowState = .init() - @State private var showWelcomeSheet: Bool = false - let x: Bool = false public init() {} @@ -102,8 +100,8 @@ public struct MainView: View { }) } .task { await attemptLoadUserSession() } - .sheet(isPresented: $showWelcomeSheet, onDismiss: onLoginModalDismiss) { - WelcomeSheetView() + .sheet(item: $windowState.loginSheet, onDismiss: onLoginModalDismiss) { request in + WelcomeSheetView(request: request) } .sheet( isPresented: verificationSheetPresented, @@ -146,7 +144,7 @@ public struct MainView: View { activeAccountID, knownAccountIDs: Set(appState.accounts.map(\.storeID))) if activeAccountID == nil { Logger.viewCycle.info("No signed in accounts, present welcome sheet") - showWelcomeSheet = true + windowState.loginSheet = .firstAccount } } .onOpenURL { url in diff --git a/Sources/MactrixApp/Models/WindowState.swift b/Sources/MactrixApp/Models/WindowState.swift index ea92bf6a..0155fdc8 100644 --- a/Sources/MactrixApp/Models/WindowState.swift +++ b/Sources/MactrixApp/Models/WindowState.swift @@ -70,6 +70,23 @@ public final class SelectedScreen: Identifiable { public static var none: SelectedScreen { SelectedScreen(.none) } } +/// Why the sign-in sheet is shown. +public enum LoginSheet: Identifiable, Equatable { + /// No account is signed in. + case firstAccount + case addAccount + /// The server ended this account's session. + case signInAgain(userID: String) + + public var id: String { + switch self { + case .firstAccount: "first" + case .addAccount: "add" + case .signInAgain(let userID): "again:\(userID)" + } + } +} + @MainActor @Observable public final class WindowState { public var selectedScreen: SelectedScreen = .none { @@ -133,6 +150,8 @@ public final class WindowState { public var requestedVerification = false + public var loginSheet: LoginSheet? + public var searchQuery: String = "" public var searchTokens: [SearchToken] = [] public var searchDirectResult: SearchDirectResult? diff --git a/Sources/MactrixApp/Views/Settings/AccountSettingsView.swift b/Sources/MactrixApp/Views/Settings/AccountSettingsView.swift index a9b82a3d..53f726e0 100644 --- a/Sources/MactrixApp/Views/Settings/AccountSettingsView.swift +++ b/Sources/MactrixApp/Views/Settings/AccountSettingsView.swift @@ -50,18 +50,30 @@ struct AccountSettingsView: View { var body: some View { if let matrixClient = appState.matrixClient { Form { + Section { + AccountLabel(account: matrixClient) + } header: { + Text("Active Account") + } footer: { + if appState.accounts.count > 1 { + Text("Switch accounts from the sidebar or the Account menu.") + } + } + ChangableField( name: "Display name", value: displayName ?? String(localized: "Loading…"), onSave: { newDisplayName in do { try await matrixClient.client.setDisplayName(name: newDisplayName) displayName = newDisplayName + await matrixClient.refreshOwnProfile() } catch { Logger.viewCycle.error("Failed to update display name: \(error)") } } ) - .task { + .task(id: matrixClient.storeID) { + displayName = nil do { displayName = try await matrixClient.client.displayName() } catch { @@ -80,7 +92,7 @@ struct AccountSettingsView: View { } HStack { - Button("Sign out", role: .destructive) { + Button(appState.accounts.count > 1 ? "Sign Out of This Account" : "Sign out", role: .destructive) { Task { do { try await appState.reset() diff --git a/Sources/MactrixApp/Views/Settings/SessionsSettingsView.swift b/Sources/MactrixApp/Views/Settings/SessionsSettingsView.swift index b22a7f54..5104fd13 100644 --- a/Sources/MactrixApp/Views/Settings/SessionsSettingsView.swift +++ b/Sources/MactrixApp/Views/Settings/SessionsSettingsView.swift @@ -120,6 +120,16 @@ struct SessionsSettingsView: View { var body: some View { if let matrixClient = appState.matrixClient { Form { + Section { + AccountLabel(account: matrixClient) + } header: { + Text("Active Account") + } footer: { + if appState.accounts.count > 1 { + Text("Switch accounts from the sidebar or the Account menu.") + } + } + Section("Device Verification") { sessionVerificationView(matrixClient: matrixClient) if matrixClient.verificationState == .unverified { diff --git a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift new file mode 100644 index 00000000..e382e530 --- /dev/null +++ b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift @@ -0,0 +1,104 @@ +import MactrixUI +import MatrixIntegration +import SwiftUI + +extension MatrixClient { + /// The name shown for this account in account lists. + var accountName: String { + ownDisplayName ?? userID + } +} + +/// The active account's avatar and name. +struct AccountLabel: View { + let account: MatrixClient + var showsUserID = true + + var body: some View { + HStack(spacing: 8) { + AvatarImage( + userID: account.userID, kind: .user, displayName: account.ownDisplayName, + avatarUrl: account.ownAvatarUrl, imageLoader: account) + VStack(alignment: .leading, spacing: 0) { + Text(account.accountName) + .lineLimit(1) + if showsUserID, account.ownDisplayName != nil { + Text(account.userID) + .font(.caption) + .foregroundStyle(.secondary) + .lineLimit(1) + } + } + } + } +} + +/// A menu at the top of the sidebar for switching, adding, and signing out of accounts. +struct AccountSwitcher: View { + @Environment(AppState.self) var appState + @Environment(WindowState.self) var windowState + + @State private var accountToSignOut: MatrixClient? + + var body: some View { + Menu { + ForEach(appState.accounts, id: \.storeID) { account in + Toggle( + isOn: Binding( + get: { appState.activeAccountID == account.storeID }, + set: { if $0 { appState.activate(account) } }) + ) { + Text(menuTitle(for: account)) + } + } + + Divider() + + Button("Add Account…") { + windowState.loginSheet = .addAccount + } + + if let active = appState.matrixClient { + Button("Sign Out of \(active.accountName)…") { + accountToSignOut = active + } + } + } label: { + if let active = appState.matrixClient { + AccountLabel(account: active) + } else { + Text("No Account") + } + } + .menuStyle(.borderlessButton) + .menuIndicator(.visible) + .fixedSize(horizontal: false, vertical: true) + .help("Switch account") + .confirmationDialog( + "Sign out of \(accountToSignOut?.accountName ?? "")?", + isPresented: Binding( + get: { accountToSignOut != nil }, + set: { if !$0 { accountToSignOut = nil } }), + presenting: accountToSignOut + ) { account in + Button("Sign Out", role: .destructive) { + Task { await appState.remove(account) } + } + } message: { account in + Text("\(account.userID) will be signed out on this Mac. Your other accounts stay signed in.") + } + } + + private func menuTitle(for account: MatrixClient) -> String { + var title = account.accountName + if account.ownDisplayName != nil { + title += " (\(account.userID))" + } + if account.authenticationFailed { + title += " — Signed Out" + } else if account.unreadRoomCount > 0 { + title += " — \(account.unreadRoomCount) unread" + } + return title + } +} diff --git a/Sources/MactrixApp/Views/Sidebar/SidebarSignedOutView.swift b/Sources/MactrixApp/Views/Sidebar/SidebarSignedOutView.swift index 20c4e739..47ba4e8b 100644 --- a/Sources/MactrixApp/Views/Sidebar/SidebarSignedOutView.swift +++ b/Sources/MactrixApp/Views/Sidebar/SidebarSignedOutView.swift @@ -1,12 +1,12 @@ -import OSLog import SwiftUI /// Shown when the server has ended the active account's session. struct SidebarSignedOutView: View { @Environment(AppState.self) var appState + @Environment(WindowState.self) var windowState @Environment(\.colorScheme) var colorScheme - @State private var signingOut = false + @State private var removing = false var body: some View { if let matrixClient = appState.matrixClient, matrixClient.authenticationFailed { @@ -23,18 +23,19 @@ struct SidebarSignedOutView: View { .labelStyle(.multiline) .frame(maxWidth: .infinity) - Button("Sign In Again…") { - Task { - signingOut = true - defer { signingOut = false } - do { - try await appState.reset() - } catch { - Logger.viewCycle.error("Failed to remove signed out account: \(error)") + HStack { + Button("Sign In Again…") { + windowState.loginSheet = .signInAgain(userID: matrixClient.userID) + } + Button("Remove Account") { + Task { + removing = true + defer { removing = false } + await appState.remove(matrixClient) } } } - .disabled(signingOut) + .disabled(removing) } .padding(10) .background(Color.orange.opacity(0.2)) diff --git a/Sources/MactrixApp/Views/Sidebar/SidebarView.swift b/Sources/MactrixApp/Views/Sidebar/SidebarView.swift index f8f52444..519cfed1 100644 --- a/Sources/MactrixApp/Views/Sidebar/SidebarView.swift +++ b/Sources/MactrixApp/Views/Sidebar/SidebarView.swift @@ -63,12 +63,18 @@ struct SidebarView: View { } var content: some View { - HStack(spacing: 0) { - SidebarGroupsList() + VStack(spacing: 0) { + AccountSwitcher() + .padding(.horizontal, 12) + .padding(.vertical, 8) Divider() - listView - // force list view to re-render to avoid a rendering bug - .id(windowState.selectedSpaceId) + HStack(spacing: 0) { + SidebarGroupsList() + Divider() + listView + // force list view to re-render to avoid a rendering bug + .id(windowState.selectedSpaceId) + } } .task(id: selectedSpace?.id) { await selectedSpace?.loadChildren() diff --git a/Sources/MactrixApp/Views/WelcomeSheetView.swift b/Sources/MactrixApp/Views/WelcomeSheetView.swift index c819d353..0ee8dc0f 100644 --- a/Sources/MactrixApp/Views/WelcomeSheetView.swift +++ b/Sources/MactrixApp/Views/WelcomeSheetView.swift @@ -4,6 +4,8 @@ import MatrixRustSDK import SwiftUI struct WelcomeSheetView: View { + var request: LoginSheet = .firstAccount + @Environment(AppState.self) private var appState @Environment(\.dismiss) private var dismiss @@ -113,7 +115,7 @@ struct WelcomeSheetView: View { @ViewBuilder var content: some View { VStack { - Text("Welcome to Mactrix") + Text(title) .font(.headline) .padding(.bottom) @@ -159,8 +161,29 @@ struct WelcomeSheetView: View { .foregroundStyle(Color.red) .textSelection(.enabled) } + + if request != .firstAccount { + Button("Cancel", role: .cancel) { dismiss() } + .keyboardShortcut(.cancelAction) + .padding(.top) + } } .padding() + .onAppear { + // Look up the homeserver straight away when signing in to a known account again. + if case .signInAgain(let userID) = request, homeserverField.isEmpty { + homeserverField = userID + loadHomeserver() + } + } + } + + private var title: String { + switch request { + case .firstAccount: "Welcome to Mactrix" + case .addAccount: "Add Account" + case .signInAgain(let userID): "Sign In Again as \(userID)" + } } var body: some View { diff --git a/Sources/MatrixIntegration/MatrixClient+Listeners.swift b/Sources/MatrixIntegration/MatrixClient+Listeners.swift index 62ca8f33..a109607e 100644 --- a/Sources/MatrixIntegration/MatrixClient+Listeners.swift +++ b/Sources/MatrixIntegration/MatrixClient+Listeners.swift @@ -51,7 +51,8 @@ extension MatrixClient { } } - var unreadRoomCount: Int { + /// The number of rooms with unread messages, notifications, or mentions. + public var unreadRoomCount: Int { rooms.reduce(0) { count, room in guard let info = room.roomInfo else { return count } let isUnread = diff --git a/Sources/MatrixIntegration/MatrixClient.swift b/Sources/MatrixIntegration/MatrixClient.swift index 888dc42b..cd309829 100644 --- a/Sources/MatrixIntegration/MatrixClient.swift +++ b/Sources/MatrixIntegration/MatrixClient.swift @@ -29,6 +29,10 @@ public class MatrixClient { private var clientDelegateHandle: TaskHandle? public internal(set) var authenticationFailed: Bool = false + /// This account's own display name and avatar, for identifying the account in the UI. + public private(set) var ownDisplayName: String? + public private(set) var ownAvatarUrl: String? + public let notifications: MatrixNotifications = .init() public let viaServers = ["matrix.org"] @@ -296,11 +300,25 @@ public class MatrixClient { ignoredUsersHandle = client.subscribeToIgnoredUsers(listener: self) ignoredUserIds = try await client.ignoredUsers() + Task { [weak self] in await self?.refreshOwnProfile() } + // Start the sync loop. await _syncService.start() Logger.matrixClient.info("Matrix sync started") } + /// Reloads `ownDisplayName` and `ownAvatarUrl`, falling back to cached values when offline. + public func refreshOwnProfile() async { + if let displayName = try? await client.displayName() { + ownDisplayName = displayName + } + if let avatarUrl = try? await client.avatarUrl() { + ownAvatarUrl = avatarUrl + } else if ownAvatarUrl == nil { + ownAvatarUrl = try? await client.cachedAvatarUrl() + } + } + public func clearCache() async throws { try await client.clearCaches(syncService: syncService) } From 92ec77321d4c734752357676288ff8bcab247a87 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Mon, 23 Nov 2026 16:02:36 -0500 Subject: [PATCH 05/35] Route notifications and the Dock badge across accounts The notification center has a single delegate, but every account's MatrixNotifications set itself as that delegate, so only the last account could handle clicks. A NotificationRouter owned by AppState now handles clicks for all accounts. Notifications carry the receiving account's storeID and are grouped by account. When more than one account is signed in, the subtitle names the account. Clicking a notification switches to its account and opens the room. A click that launches the app is held until accounts are restored. The Dock badge shows unread rooms summed across all accounts. AppState is now its only writer; previously each client overwrote the others' count. Logs for sync, sign-out, auth errors and session saves now include the account's storeID, so logs from different accounts can be told apart. --- Mactrix/MactrixApp.swift | 10 ++-- Sources/MactrixApp/Models/AppState.swift | 51 ++++++++++++++++++- .../MatrixClient+Listeners.swift | 16 +----- Sources/MatrixIntegration/MatrixClient.swift | 18 +++---- .../MatrixNotifications.swift | 34 +++++++------ .../NotificationRouter.swift | 36 +++++++++++++ 6 files changed, 117 insertions(+), 48 deletions(-) create mode 100644 Sources/MatrixIntegration/NotificationRouter.swift diff --git a/Mactrix/MactrixApp.swift b/Mactrix/MactrixApp.swift index 6c64d06d..4605d00f 100644 --- a/Mactrix/MactrixApp.swift +++ b/Mactrix/MactrixApp.swift @@ -18,7 +18,8 @@ struct MactrixApp: App { AppCommands(appState: appState) } .onChange(of: windowState == nil, focusNotification) - .onChange(of: appState.matrixClient?.notifications.selectedRoomId == nil, focusNotification) + .onChange(of: appState.notificationRouter.pendingTarget, focusNotification) + .onChange(of: appState.restoration, focusNotification) Settings { SettingsView() @@ -28,11 +29,6 @@ struct MactrixApp: App { func focusNotification() { guard let windowState else { return } - guard let notificationRoomId = appState.matrixClient?.notifications.selectedRoomId else { - return - } - - windowState.selectedRoomId = notificationRoomId - appState.matrixClient?.notifications.selectedRoomId = nil + appState.showNotificationTarget(in: windowState) } } diff --git a/Sources/MactrixApp/Models/AppState.swift b/Sources/MactrixApp/Models/AppState.swift index 6ab77821..ddd3f4ac 100644 --- a/Sources/MactrixApp/Models/AppState.swift +++ b/Sources/MactrixApp/Models/AppState.swift @@ -1,3 +1,4 @@ +import AppKit import Foundation import MatrixIntegration import OSLog @@ -26,15 +27,22 @@ public final class AppState { } /// Signed-in accounts in display order. - public private(set) var accounts: [MatrixClient] = [] + public private(set) var accounts: [MatrixClient] = [] { + didSet { updateNotificationLabels() } + } public private(set) var activeAccountID: String? private var hasRestored = false @ObservationIgnored private let accountStore: AccountStore @ObservationIgnored private var restoreTask: Task? + @ObservationIgnored private var lastAppliedDockUnreadCount: Int? + + /// Routes clicked notifications from every account. + public let notificationRouter = NotificationRouter() public init() { accountStore = AccountStore() + observeDockBadge() } /// The active account. @@ -123,6 +131,47 @@ public final class AppState { } } + /// Opens the room of a clicked notification in `windowState`, switching to its account. + public func showNotificationTarget(in windowState: WindowState) { + // A click that launched the app arrives before accounts are restored; handle it afterwards. + guard hasRestored, let target = notificationRouter.pendingTarget else { return } + notificationRouter.pendingTarget = nil + + if let accountID = target.accountID { + guard let account = accounts.first(where: { $0.storeID == accountID }) else { + Logger.viewCycle.info("Ignoring notification from a removed account") + return + } + activate(account) + // Switch the window now so the room below isn't treated as the previous account's. + windowState.showAccount(account.storeID, knownAccountIDs: Set(accounts.map(\.storeID))) + } + windowState.selectedRoomId = target.roomId + } + + /// Names the receiving account in notifications once more than one account is signed in. + private func updateNotificationLabels() { + let showsLabels = accounts.count > 1 + for account in accounts { + account.notifications.accountLabel = showsLabels ? account.userID : nil + } + } + + /// Shows the number of unread rooms across all accounts on the Dock icon. + private func observeDockBadge() { + let count = withObservationTracking { + accounts.reduce(0) { $0 + $1.unreadRoomCount } + } onChange: { [weak self] in + Task { @MainActor [weak self] in + self?.observeDockBadge() + } + } + + guard count != lastAppliedDockUnreadCount else { return } + NSApp?.dockTile.badgeLabel = count > 0 ? "\(count)" : nil + lastAppliedDockUnreadCount = count + } + private func startSync(_ client: MatrixClient) { Task { do { diff --git a/Sources/MatrixIntegration/MatrixClient+Listeners.swift b/Sources/MatrixIntegration/MatrixClient+Listeners.swift index a109607e..f844d8b8 100644 --- a/Sources/MatrixIntegration/MatrixClient+Listeners.swift +++ b/Sources/MatrixIntegration/MatrixClient+Listeners.swift @@ -60,20 +60,6 @@ extension MatrixClient { return count + (isUnread ? 1 : 0) } } - - func observeDockIconUnreadCount() { - let count = withObservationTracking { - unreadRoomCount - } onChange: { [weak self] in - Task { @MainActor [weak self] in - self?.observeDockIconUnreadCount() - } - } - - guard count != lastAppliedDockUnreadCount else { return } - NSApp.dockTile.badgeLabel = count > 0 ? "\(count)" : nil - lastAppliedDockUnreadCount = count - } } extension MatrixClient: SyncServiceStateObserver { @@ -134,7 +120,7 @@ extension MatrixClient: MatrixRustSDK.ClientDelegate { nonisolated public func didReceiveAuthError(isSoftLogout: Bool) { Task { @MainActor in Logger.matrixClient.debug( - "did receive auth error: soft logout \(isSoftLogout, privacy: .public)") + "did receive auth error: soft logout \(isSoftLogout, privacy: .public), store \(self.storeID)") if !isSoftLogout { authenticationFailed = true // The session is gone; keep the account listed but stop using it. diff --git a/Sources/MatrixIntegration/MatrixClient.swift b/Sources/MatrixIntegration/MatrixClient.swift index cd309829..f39f4241 100644 --- a/Sources/MatrixIntegration/MatrixClient.swift +++ b/Sources/MatrixIntegration/MatrixClient.swift @@ -22,8 +22,6 @@ public class MatrixClient { public internal(set) var rooms: [SidebarRoom] = [] - @ObservationIgnored var lastAppliedDockUnreadCount: Int? - public internal(set) var spaceService: LiveSpaceService! private var clientDelegateHandle: TaskHandle? @@ -33,7 +31,7 @@ public class MatrixClient { public private(set) var ownDisplayName: String? public private(set) var ownAvatarUrl: String? - public let notifications: MatrixNotifications = .init() + public let notifications: MatrixNotifications public let viaServers = ["matrix.org"] @@ -45,6 +43,7 @@ public class MatrixClient { init(userSession: UserSession, accountStore: AccountStore) async throws { storeID = userSession.storeID userID = userSession.userID + notifications = MatrixNotifications(accountID: userSession.storeID) storePassphrase = userSession.storePassphrase self.accountStore = accountStore @@ -59,7 +58,6 @@ public class MatrixClient { spaceService = LiveSpaceService(client: self.client, spaceService: await client.spaceService()) clientDelegateHandle = try? client.setDelegate(delegate: self) - observeDockIconUnreadCount() } init( @@ -67,13 +65,13 @@ public class MatrixClient { ) async throws { self.storeID = storeID self.userID = try client.userId() + notifications = MatrixNotifications(accountID: storeID) self.storePassphrase = storePassphrase self.accountStore = accountStore self.client = client spaceService = LiveSpaceService(client: self.client, spaceService: await client.spaceService()) clientDelegateHandle = try? self.client.setDelegate(delegate: self) - observeDockIconUnreadCount() } func userSession() throws -> UserSession { @@ -178,12 +176,12 @@ public class MatrixClient { isResettingSession = true await roomSubscriptions.invalidate() await syncService?.stop() - Logger.matrixClient.debug("matrix client sign out") + Logger.matrixClient.debug("matrix client sign out, store \(self.storeID)") try? await client.logout() try? FileManager.default.removeItem(at: StoreDirectories.data(for: storeID)) try? FileManager.default.removeItem(at: StoreDirectories.caches(for: storeID)) try accountStore.remove(storeID: storeID) - Logger.matrixClient.debug("matrix client sign out complete") + Logger.matrixClient.debug("matrix client sign out complete, store \(self.storeID)") } public internal(set) var syncService: SyncService? @@ -304,7 +302,7 @@ public class MatrixClient { // Start the sync loop. await _syncService.start() - Logger.matrixClient.info("Matrix sync started") + Logger.matrixClient.info("Matrix sync started, store \(self.storeID)") } /// Reloads `ownDisplayName` and `ownAvatarUrl`, falling back to cached values when offline. @@ -376,12 +374,12 @@ extension MatrixClient: MatrixRustSDK.ClientSessionDelegate { } public nonisolated func saveSessionInKeychain(session: MatrixRustSDK.Session) { - Logger.matrixClient.debug("client session delegate: save session in keychain") + Logger.matrixClient.debug("client session delegate: save session in keychain, store \(self.storeID)") do { try accountStore.save( UserSession(session: session, storeID: storeID, storePassphrase: storePassphrase)) } catch { - Logger.matrixClient.error("failed to save session in keychain: \(error)") + Logger.matrixClient.error("failed to save session in keychain, store \(self.storeID): \(error)") } } } diff --git a/Sources/MatrixIntegration/MatrixNotifications.swift b/Sources/MatrixIntegration/MatrixNotifications.swift index e5f927f0..b868fd66 100644 --- a/Sources/MatrixIntegration/MatrixNotifications.swift +++ b/Sources/MatrixIntegration/MatrixNotifications.swift @@ -5,7 +5,15 @@ import UserNotifications // This class is Sendable because MatrixRustSDK.SyncNotificationListener requires it to be so @MainActor @Observable public final class MatrixNotifications: NSObject, Sendable { - public var selectedRoomId: String? + enum UserInfoKey { + static let roomId = "roomId" + static let accountID = "accountID" + } + + /// The `storeID` of the account these notifications belong to. + let accountID: String + /// Names the account in notifications; set when more than one account is signed in. + public var accountLabel: String? typealias NotificationEvent = (item: MatrixRustSDK.NotificationItem, roomId: String) @@ -13,12 +21,12 @@ import UserNotifications AsyncStream.Continuation @ObservationIgnored private var streamTask: Task? - public override init() { + init(accountID: String) { + self.accountID = accountID let (stream, continuation) = AsyncStream.makeStream() notificationContinuation = continuation super.init() - UNUserNotificationCenter.current().delegate = self streamTask = Task { [weak self] in for await (notification, roomId) in stream { @@ -29,16 +37,6 @@ import UserNotifications } } -extension MatrixNotifications: @MainActor UNUserNotificationCenterDelegate { - public func userNotificationCenter( - _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse - ) async { - let roomId = response.notification.request.content.userInfo["roomId"] as? String - Logger.notification.info("Notification delegate didReceive: \(roomId ?? "")") - selectedRoomId = roomId - } -} - extension MatrixNotifications: MatrixRustSDK.SyncNotificationListener { public nonisolated func onNotification( notification: MatrixRustSDK.NotificationItem, roomId: String @@ -65,10 +63,16 @@ extension MatrixNotifications { let content = UNMutableNotificationContent() content.title = notificationTitle(for: notification) - content.subtitle = notificationBody(for: notification) + if let accountLabel { + content.subtitle = accountLabel + content.body = notificationBody(for: notification) + } else { + content.subtitle = notificationBody(for: notification) + } content.sound = UNNotificationSound.default content.interruptionLevel = .timeSensitive - content.userInfo = ["roomId": roomId] + content.threadIdentifier = accountID + content.userInfo = [UserInfoKey.roomId: roomId, UserInfoKey.accountID: accountID] let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false) let request = UNNotificationRequest( diff --git a/Sources/MatrixIntegration/NotificationRouter.swift b/Sources/MatrixIntegration/NotificationRouter.swift new file mode 100644 index 00000000..0aefc464 --- /dev/null +++ b/Sources/MatrixIntegration/NotificationRouter.swift @@ -0,0 +1,36 @@ +import OSLog +import Observation +import UserNotifications + +/// Receives clicks on notifications from every account. +/// +/// The notification center has a single delegate, so this is owned by the app rather than by each +/// account's ``MatrixNotifications``. +@MainActor @Observable public final class NotificationRouter: NSObject { + public struct Target: Equatable, Sendable { + /// The `storeID` of the account that received the notification. `nil` for notifications + /// posted by versions without multi-account support. + public let accountID: String? + public let roomId: String + } + + /// The room of the most recently clicked notification, until the app has shown it. + public var pendingTarget: Target? + + public override init() { + super.init() + UNUserNotificationCenter.current().delegate = self + } +} + +extension NotificationRouter: @MainActor UNUserNotificationCenterDelegate { + public func userNotificationCenter( + _ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse + ) async { + let userInfo = response.notification.request.content.userInfo + guard let roomId = userInfo[MatrixNotifications.UserInfoKey.roomId] as? String else { return } + let accountID = userInfo[MatrixNotifications.UserInfoKey.accountID] as? String + Logger.notification.info("Notification clicked for room \(roomId) in store \(accountID ?? "?")") + pendingTarget = Target(accountID: accountID, roomId: roomId) + } +} From 4cea0f4dc1633afe1243722a2140d775ae27ae05 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Mon, 23 Nov 2026 17:24:08 -0500 Subject: [PATCH 06/35] Start a fresh login after each sign-in attempt A login client can only sign in once. After a rejected duplicate sign-in, the Add Account sheet reused the spent client, so signing in as another account on the same homeserver failed with "new logged-in session is different than current client session". Fetch new login details after every failed attempt. --- Sources/MactrixApp/Views/WelcomeSheetView.swift | 14 ++++++++++++++ Sources/MatrixIntegration/HomeserverLogin.swift | 3 +++ 2 files changed, 17 insertions(+) diff --git a/Sources/MactrixApp/Views/WelcomeSheetView.swift b/Sources/MactrixApp/Views/WelcomeSheetView.swift index 0ee8dc0f..610330e1 100644 --- a/Sources/MactrixApp/Views/WelcomeSheetView.swift +++ b/Sources/MactrixApp/Views/WelcomeSheetView.swift @@ -1,6 +1,7 @@ import AuthenticationServices import MatrixIntegration import MatrixRustSDK +import OSLog import SwiftUI struct WelcomeSheetView: View { @@ -51,6 +52,17 @@ struct WelcomeSheetView: View { } } + /// Replaces the spent login with a fresh one, since a client can't sign in a second time. + /// + /// Failures are ignored so the sign-in error stays on screen. + private func renewHomeserverLogin() async { + do { + homeserverLogin = try await MatrixClient.loginDetails(homeServer: homeserverField) + } catch { + Logger.viewCycle.error("Failed to renew homeserver login: \(error)") + } + } + func signInPassword() { Task { guard let homeserverLogin = homeserverLogin else { return } @@ -64,6 +76,7 @@ struct WelcomeSheetView: View { dismiss() } catch { showError = error + await renewHomeserverLogin() } } } @@ -80,6 +93,7 @@ struct WelcomeSheetView: View { dismiss() } catch { showError = error + await renewHomeserverLogin() } } } diff --git a/Sources/MatrixIntegration/HomeserverLogin.swift b/Sources/MatrixIntegration/HomeserverLogin.swift index 38f0ef53..e27b5e01 100644 --- a/Sources/MatrixIntegration/HomeserverLogin.swift +++ b/Sources/MatrixIntegration/HomeserverLogin.swift @@ -4,6 +4,9 @@ import MatrixRustSDK import OSLog import SwiftUI +/// Login details and the client that signs in with them. +/// +/// Single use: after a login attempt, request new login details. public struct HomeserverLogin { public let storeID: String private let storePassphrase: String From 1513cd1047f78c3ddd3d7236aec9763c84d825e1 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Mon, 23 Nov 2026 17:24:55 -0500 Subject: [PATCH 07/35] Show avatars and Matrix IDs in the account switcher MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The sidebar switcher was a native menu, which drops custom labels, so it showed only the display name without an avatar. Display names aren't unique either. Replace it with a button that opens a popover listing each account's avatar, display name, and Matrix ID, with the active account checked and unread counts or a signed-out tag. The Account menu now titles items "Name — @user:server". --- Sources/MactrixApp/Commands.swift | 2 +- .../Views/Sidebar/AccountSwitcher.swift | 210 ++++++++++++++---- 2 files changed, 165 insertions(+), 47 deletions(-) diff --git a/Sources/MactrixApp/Commands.swift b/Sources/MactrixApp/Commands.swift index 0a09302d..8952edd3 100644 --- a/Sources/MactrixApp/Commands.swift +++ b/Sources/MactrixApp/Commands.swift @@ -32,7 +32,7 @@ public struct AppCommands: Commands { get: { appState.activeAccountID == account.storeID }, set: { if $0 { appState.activate(account) } }) ) { - Text(account.accountName) + Text(account.accountMenuTitle) } .keyboardShortcut( index < 9 diff --git a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift index e382e530..f6c1f996 100644 --- a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift +++ b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift @@ -3,102 +3,220 @@ import MatrixIntegration import SwiftUI extension MatrixClient { - /// The name shown for this account in account lists. + /// The primary name shown for this account: its display name, or its Matrix ID. var accountName: String { ownDisplayName ?? userID } + + /// A one-line title that always includes the Matrix ID, since display names aren't unique. + var accountMenuTitle: String { + ownDisplayName.map { "\($0) — \(userID)" } ?? userID + } } -/// The active account's avatar and name. +/// An account's avatar, display name, and Matrix ID. struct AccountLabel: View { let account: MatrixClient var showsUserID = true + var avatarSize: CGFloat = 28 var body: some View { HStack(spacing: 8) { AvatarImage( userID: account.userID, kind: .user, displayName: account.ownDisplayName, - avatarUrl: account.ownAvatarUrl, imageLoader: account) - VStack(alignment: .leading, spacing: 0) { + avatarUrl: account.ownAvatarUrl, imageLoader: account + ) + .frame(width: avatarSize, height: avatarSize) + + VStack(alignment: .leading, spacing: 1) { Text(account.accountName) + .font(.body.weight(.semibold)) .lineLimit(1) if showsUserID, account.ownDisplayName != nil { Text(account.userID) - .font(.caption) + .font(.callout) .foregroundStyle(.secondary) .lineLimit(1) + .truncationMode(.middle) } } } + .accessibilityElement(children: .combine) } } -/// A menu at the top of the sidebar for switching, adding, and signing out of accounts. +/// A button at the top of the sidebar that opens a popover for switching, adding, and signing +/// out of accounts. struct AccountSwitcher: View { @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState + @State private var isPresented = false + @State private var isHovered = false @State private var accountToSignOut: MatrixClient? var body: some View { - Menu { + Button { + isPresented.toggle() + } label: { + HStack(spacing: 6) { + if let active = appState.matrixClient { + AccountLabel(account: active) + } else { + Text("No Account") + .font(.body.weight(.semibold)) + } + Spacer(minLength: 0) + Image(systemName: "chevron.up.chevron.down") + .font(.caption.weight(.semibold)) + .foregroundStyle(.secondary) + } + .padding(.horizontal, 6) + .padding(.vertical, 4) + .contentShape(.rect) + .background( + .quaternary.opacity(isHovered || isPresented ? 1 : 0), + in: RoundedRectangle(cornerRadius: 6, style: .continuous)) + } + .buttonStyle(.plain) + .onHover { isHovered = $0 } + .help("Switch account") + .accessibilityLabel(accessibilityLabel) + .popover(isPresented: $isPresented, arrowEdge: .bottom) { + popoverContent + } + .confirmationDialog( + "Sign out of \(accountToSignOut?.userID ?? "")?", + isPresented: Binding( + get: { accountToSignOut != nil }, + set: { if !$0 { accountToSignOut = nil } }), + presenting: accountToSignOut + ) { account in + Button("Sign Out", role: .destructive) { + Task { await appState.remove(account) } + } + } message: { _ in + Text("This account will be signed out on this Mac. Your other accounts stay signed in.") + } + } + + private var accessibilityLabel: String { + guard let active = appState.matrixClient else { return "Switch account" } + return "Switch account, current: \(active.accountMenuTitle)" + } + + private var popoverContent: some View { + VStack(alignment: .leading, spacing: 2) { ForEach(appState.accounts, id: \.storeID) { account in - Toggle( - isOn: Binding( - get: { appState.activeAccountID == account.storeID }, - set: { if $0 { appState.activate(account) } }) - ) { - Text(menuTitle(for: account)) + AccountRow(account: account, isActive: appState.activeAccountID == account.storeID) { + appState.activate(account) + isPresented = false } } Divider() + .padding(.vertical, 4) - Button("Add Account…") { + PopoverActionRow(title: "Add Account…", systemImage: "plus") { + isPresented = false windowState.loginSheet = .addAccount } if let active = appState.matrixClient { - Button("Sign Out of \(active.accountName)…") { + PopoverActionRow( + title: "Sign Out of \(active.accountName)…", + systemImage: "rectangle.portrait.and.arrow.right" + ) { + isPresented = false accountToSignOut = active } } - } label: { - if let active = appState.matrixClient { - AccountLabel(account: active) - } else { - Text("No Account") - } } - .menuStyle(.borderlessButton) - .menuIndicator(.visible) - .fixedSize(horizontal: false, vertical: true) - .help("Switch account") - .confirmationDialog( - "Sign out of \(accountToSignOut?.accountName ?? "")?", - isPresented: Binding( - get: { accountToSignOut != nil }, - set: { if !$0 { accountToSignOut = nil } }), - presenting: accountToSignOut - ) { account in - Button("Sign Out", role: .destructive) { - Task { await appState.remove(account) } + .padding(6) + .frame(width: 300) + } +} + +/// A selectable account in the switcher popover. +private struct AccountRow: View { + let account: MatrixClient + let isActive: Bool + let action: () -> Void + + @State private var isHovered = false + + var body: some View { + Button(action: action) { + HStack(spacing: 8) { + Image(systemName: "checkmark") + .font(.callout.weight(.semibold)) + .foregroundStyle(.tint) + .opacity(isActive ? 1 : 0) + .frame(width: 14) + + AccountLabel(account: account) + + Spacer(minLength: 8) + + if account.authenticationFailed { + Text("Signed Out") + .font(.caption.weight(.medium)) + .foregroundStyle(.orange) + } else if account.unreadRoomCount > 0 { + Text("\(account.unreadRoomCount)") + .font(.caption.weight(.semibold).monospacedDigit()) + .foregroundStyle(.white) + .padding(.horizontal, 6) + .padding(.vertical, 1) + .background(.tint, in: Capsule()) + } } - } message: { account in - Text("\(account.userID) will be signed out on this Mac. Your other accounts stay signed in.") + .padding(.horizontal, 6) + .padding(.vertical, 5) + .contentShape(.rect) + .background( + .quaternary.opacity(isHovered ? 1 : 0), + in: RoundedRectangle(cornerRadius: 6, style: .continuous)) } + .buttonStyle(.plain) + .onHover { isHovered = $0 } + .accessibilityAddTraits(isActive ? .isSelected : []) + .accessibilityValue(accessibilityValue) } - private func menuTitle(for account: MatrixClient) -> String { - var title = account.accountName - if account.ownDisplayName != nil { - title += " (\(account.userID))" - } - if account.authenticationFailed { - title += " — Signed Out" - } else if account.unreadRoomCount > 0 { - title += " — \(account.unreadRoomCount) unread" + private var accessibilityValue: String { + if account.authenticationFailed { return "Signed out" } + if account.unreadRoomCount > 0 { return "\(account.unreadRoomCount) unread" } + return "" + } +} + +/// An action such as "Add Account…" at the bottom of the switcher popover. +private struct PopoverActionRow: View { + let title: String + let systemImage: String + let action: () -> Void + + @State private var isHovered = false + + var body: some View { + Button(action: action) { + HStack(spacing: 8) { + Image(systemName: systemImage) + .frame(width: 14) + .foregroundStyle(.secondary) + Text(title) + .lineLimit(1) + Spacer(minLength: 0) + } + .padding(.horizontal, 6) + .padding(.vertical, 5) + .contentShape(.rect) + .background( + .quaternary.opacity(isHovered ? 1 : 0), + in: RoundedRectangle(cornerRadius: 6, style: .continuous)) } - return title + .buttonStyle(.plain) + .onHover { isHovered = $0 } } } From c3931955cfcc9bc0b9218a1585caf234400d54af Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Mon, 23 Nov 2026 17:45:14 -0500 Subject: [PATCH 08/35] Cap the SQLite connection pool of each account store The SDK sizes each store's connection pool at four connections per CPU core, and every connection holds two file descriptors. With four databases per account, two accounts on a 12-core Mac held over 300 descriptors, past the default limit of 256. Further sign-in attempts, which each build a client with its own store, then failed to open databases ("unable to open database file") or sockets, stalled syncing accounts, and crashed when AppKit could not create a Metal context. Limit each pool to 8 connections, about 64 descriptors per account. --- Sources/MatrixIntegration/MatrixClient.swift | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/Sources/MatrixIntegration/MatrixClient.swift b/Sources/MatrixIntegration/MatrixClient.swift index f39f4241..d9b6a93e 100644 --- a/Sources/MatrixIntegration/MatrixClient.swift +++ b/Sources/MatrixIntegration/MatrixClient.swift @@ -79,6 +79,13 @@ public class MatrixClient { session: client.session(), storeID: storeID, storePassphrase: storePassphrase) } + /// The most connections each of an account's SQLite databases keeps open. + /// + /// The SDK otherwise sizes each pool at four connections per CPU core. With four databases per + /// account and two file descriptors per connection, a few accounts would then exhaust the + /// process's file descriptors, failing database opens, network requests, and rendering. + static let sqlitePoolMaxSize: UInt32 = 8 + static func clientBuilder(homeServer: String, storeId: String, storePassphrase: String) -> ClientBuilder { @@ -87,6 +94,7 @@ public class MatrixClient { cachePath: StoreDirectories.caches(for: storeId).path(percentEncoded: false) ) .passphrase(passphrase: storePassphrase) + .poolMaxSize(poolMaxSize: sqlitePoolMaxSize) return ClientBuilder() .serverNameOrHomeserverUrl(serverNameOrUrl: homeServer) From 8cbb86437c30994f76873787a21f150ffbd15fd2 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Mon, 23 Nov 2026 17:46:09 -0500 Subject: [PATCH 09/35] Raise the open file limit at launch Apps start with a soft limit of 256 open files. Every signed-in account keeps its SQLite stores and sync connections open, and each sign-in attempt opens another store, so a few accounts can run out even with capped connection pools. Raise the soft limit to 4096 (or the hard limit, if lower) before any account opens its stores. --- Sources/MactrixApp/Models/AppState.swift | 2 ++ Sources/MatrixIntegration/OpenFileLimit.swift | 35 +++++++++++++++++++ .../MactrixAppTests/OpenFileLimitTests.swift | 30 ++++++++++++++++ 3 files changed, 67 insertions(+) create mode 100644 Sources/MatrixIntegration/OpenFileLimit.swift create mode 100644 Tests/MactrixAppTests/OpenFileLimitTests.swift diff --git a/Sources/MactrixApp/Models/AppState.swift b/Sources/MactrixApp/Models/AppState.swift index ddd3f4ac..433b4f2f 100644 --- a/Sources/MactrixApp/Models/AppState.swift +++ b/Sources/MactrixApp/Models/AppState.swift @@ -41,6 +41,8 @@ public final class AppState { public let notificationRouter = NotificationRouter() public init() { + // Before any account opens its stores. + OpenFileLimit.raise() accountStore = AccountStore() observeDockBadge() } diff --git a/Sources/MatrixIntegration/OpenFileLimit.swift b/Sources/MatrixIntegration/OpenFileLimit.swift new file mode 100644 index 00000000..0917c3df --- /dev/null +++ b/Sources/MatrixIntegration/OpenFileLimit.swift @@ -0,0 +1,35 @@ +import Darwin +import OSLog + +/// The number of files the process may have open at once. +/// +/// Each signed-in account keeps dozens of SQLite files and sockets open, so the default soft +/// limit of 256 leaves little room for several accounts. +public enum OpenFileLimit { + /// The soft limit to raise to, well below the kernel's `OPEN_MAX` of 10240. + static let target: rlim_t = 4096 + + /// Raises the soft limit to `target`, or as far as the hard limit allows. Never lowers it. + public static func raise() { + var limit = rlimit() + guard getrlimit(RLIMIT_NOFILE, &limit) == 0 else { + Logger.matrixClient.error("Failed to read the open file limit: errno \(errno)") + return + } + guard let soft = raisedSoftLimit(current: limit.rlim_cur, hard: limit.rlim_max) else { return } + + let previous = limit.rlim_cur + limit.rlim_cur = soft + if setrlimit(RLIMIT_NOFILE, &limit) == 0 { + Logger.matrixClient.info("Raised the open file limit from \(previous) to \(soft)") + } else { + Logger.matrixClient.error("Failed to raise the open file limit: errno \(errno)") + } + } + + /// The soft limit to set, or `nil` if `current` is already at least `target` or the hard limit. + static func raisedSoftLimit(current: rlim_t, hard: rlim_t, target: rlim_t = target) -> rlim_t? { + let soft = min(target, hard) + return soft > current ? soft : nil + } +} diff --git a/Tests/MactrixAppTests/OpenFileLimitTests.swift b/Tests/MactrixAppTests/OpenFileLimitTests.swift new file mode 100644 index 00000000..715fccdf --- /dev/null +++ b/Tests/MactrixAppTests/OpenFileLimitTests.swift @@ -0,0 +1,30 @@ +import Darwin +import Testing + +@testable import MatrixIntegration + +struct OpenFileLimitTests { + /// Darwin's `RLIM_INFINITY`, which isn't imported into Swift. + let unlimited = rlim_t(Int64.max) + + @Test func raisesToTarget() { + #expect(OpenFileLimit.raisedSoftLimit(current: 256, hard: unlimited, target: 4096) == 4096) + } + + @Test func stopsAtHardLimit() { + #expect(OpenFileLimit.raisedSoftLimit(current: 256, hard: 1024, target: 4096) == 1024) + } + + @Test func neverLowers() { + #expect(OpenFileLimit.raisedSoftLimit(current: 8192, hard: unlimited, target: 4096) == nil) + #expect(OpenFileLimit.raisedSoftLimit(current: 1024, hard: 1024, target: 4096) == nil) + } + + @Test func raiseAppliesToProcess() { + OpenFileLimit.raise() + + var limit = rlimit() + #expect(getrlimit(RLIMIT_NOFILE, &limit) == 0) + #expect(limit.rlim_cur >= min(OpenFileLimit.target, limit.rlim_max)) + } +} From f70686cb18b1b975ce131bb50b951952851ee6de Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Mon, 23 Nov 2026 17:46:48 -0500 Subject: [PATCH 10/35] Show inactive accounts' notifications while Mactrix is frontmost macOS hides notifications from the frontmost app unless its delegate asks to present them, so while Mactrix was focused nothing showed that another account had received a message. Present those with a banner and sound. The active account stays silent as before, since its rooms are already in the sidebar. --- Sources/MactrixApp/Models/AppState.swift | 1 + .../NotificationRouter.swift | 21 ++++++++++++++++ .../NotificationRouterTests.swift | 24 +++++++++++++++++++ 3 files changed, 46 insertions(+) create mode 100644 Tests/MactrixAppTests/NotificationRouterTests.swift diff --git a/Sources/MactrixApp/Models/AppState.swift b/Sources/MactrixApp/Models/AppState.swift index 433b4f2f..585b2b7a 100644 --- a/Sources/MactrixApp/Models/AppState.swift +++ b/Sources/MactrixApp/Models/AppState.swift @@ -106,6 +106,7 @@ public final class AppState { public func activate(_ client: MatrixClient?) { activeAccountID = client?.storeID accountStore.activeStoreID = client?.storeID + notificationRouter.activeAccountID = client?.storeID } /// Signs out of `client` and removes it, activating another account if it was active. diff --git a/Sources/MatrixIntegration/NotificationRouter.swift b/Sources/MatrixIntegration/NotificationRouter.swift index 0aefc464..0f01a531 100644 --- a/Sources/MatrixIntegration/NotificationRouter.swift +++ b/Sources/MatrixIntegration/NotificationRouter.swift @@ -17,6 +17,10 @@ import UserNotifications /// The room of the most recently clicked notification, until the app has shown it. public var pendingTarget: Target? + /// The `storeID` of the account shown in the app, whose notifications stay silent while the app + /// is frontmost. + @ObservationIgnored public var activeAccountID: String? + public override init() { super.init() UNUserNotificationCenter.current().delegate = self @@ -33,4 +37,21 @@ extension NotificationRouter: @MainActor UNUserNotificationCenterDelegate { Logger.notification.info("Notification clicked for room \(roomId) in store \(accountID ?? "?")") pendingTarget = Target(accountID: accountID, roomId: roomId) } + + /// Shows notifications from accounts other than the active one while the app is frontmost, + /// since their rooms aren't visible. macOS would otherwise hide them. + public func userNotificationCenter( + _ center: UNUserNotificationCenter, willPresent notification: UNNotification + ) async -> UNNotificationPresentationOptions { + let accountID = + notification.request.content.userInfo[MatrixNotifications.UserInfoKey.accountID] as? String + return Self.foregroundPresentation(forAccountID: accountID, activeAccountID: activeAccountID) + } + + static func foregroundPresentation(forAccountID accountID: String?, activeAccountID: String?) + -> UNNotificationPresentationOptions + { + guard let accountID, accountID != activeAccountID else { return [] } + return [.banner, .list, .sound] + } } diff --git a/Tests/MactrixAppTests/NotificationRouterTests.swift b/Tests/MactrixAppTests/NotificationRouterTests.swift new file mode 100644 index 00000000..0a4b5705 --- /dev/null +++ b/Tests/MactrixAppTests/NotificationRouterTests.swift @@ -0,0 +1,24 @@ +import Testing + +@testable import MatrixIntegration + +@MainActor +struct NotificationRouterTests { + @Test func showsInactiveAccountsWhileFrontmost() { + let options = NotificationRouter.foregroundPresentation( + forAccountID: "inactive", activeAccountID: "active") + #expect(options == [.banner, .list, .sound]) + } + + @Test func keepsActiveAccountSilentWhileFrontmost() { + let options = NotificationRouter.foregroundPresentation( + forAccountID: "active", activeAccountID: "active") + #expect(options.isEmpty) + } + + @Test func keepsNotificationsWithoutAccountSilent() { + let options = NotificationRouter.foregroundPresentation( + forAccountID: nil, activeAccountID: "active") + #expect(options.isEmpty) + } +} From 91f3f29641836198b49c8956cc1ad9cace8f9a75 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Mon, 23 Nov 2026 17:47:26 -0500 Subject: [PATCH 11/35] Badge the account switcher with other accounts' unread rooms Unread rooms in inactive accounts were only visible after opening the switcher popover. Show their total next to the switcher's chevron and include it in the button's accessibility label. Signed-out accounts are left out, matching the popover, which marks them instead of counting. --- Sources/MactrixApp/Models/AppState.swift | 8 +++++ .../Views/Sidebar/AccountSwitcher.swift | 29 ++++++++++++++----- 2 files changed, 30 insertions(+), 7 deletions(-) diff --git a/Sources/MactrixApp/Models/AppState.swift b/Sources/MactrixApp/Models/AppState.swift index 585b2b7a..f77bac23 100644 --- a/Sources/MactrixApp/Models/AppState.swift +++ b/Sources/MactrixApp/Models/AppState.swift @@ -52,6 +52,14 @@ public final class AppState { accounts.first { $0.storeID == activeAccountID } } + /// The number of unread rooms across accounts other than the active one. + public var inactiveUnreadRoomCount: Int { + accounts.reduce(0) { count, account in + guard account.storeID != activeAccountID, !account.authenticationFailed else { return count } + return count + account.unreadRoomCount + } + } + public var restoration: Restoration { hasRestored ? .restored(activeAccountID: activeAccountID) : .pending } diff --git a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift index f6c1f996..b5cb6768 100644 --- a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift +++ b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift @@ -67,6 +67,10 @@ struct AccountSwitcher: View { .font(.body.weight(.semibold)) } Spacer(minLength: 0) + if appState.inactiveUnreadRoomCount > 0 { + UnreadBadge(count: appState.inactiveUnreadRoomCount) + .help("Unread rooms in your other accounts") + } Image(systemName: "chevron.up.chevron.down") .font(.caption.weight(.semibold)) .foregroundStyle(.secondary) @@ -102,7 +106,9 @@ struct AccountSwitcher: View { private var accessibilityLabel: String { guard let active = appState.matrixClient else { return "Switch account" } - return "Switch account, current: \(active.accountMenuTitle)" + let label = "Switch account, current: \(active.accountMenuTitle)" + let unread = appState.inactiveUnreadRoomCount + return unread > 0 ? "\(label), \(unread) unread in other accounts" : label } private var popoverContent: some View { @@ -163,12 +169,7 @@ private struct AccountRow: View { .font(.caption.weight(.medium)) .foregroundStyle(.orange) } else if account.unreadRoomCount > 0 { - Text("\(account.unreadRoomCount)") - .font(.caption.weight(.semibold).monospacedDigit()) - .foregroundStyle(.white) - .padding(.horizontal, 6) - .padding(.vertical, 1) - .background(.tint, in: Capsule()) + UnreadBadge(count: account.unreadRoomCount) } } .padding(.horizontal, 6) @@ -191,6 +192,20 @@ private struct AccountRow: View { } } +/// The number of unread rooms, in a tinted capsule. +private struct UnreadBadge: View { + let count: Int + + var body: some View { + Text("\(count)") + .font(.caption.weight(.semibold).monospacedDigit()) + .foregroundStyle(.white) + .padding(.horizontal, 6) + .padding(.vertical, 1) + .background(.tint, in: Capsule()) + } +} + /// An action such as "Add Account…" at the bottom of the switcher popover. private struct PopoverActionRow: View { let title: String From 3e1dafcf26003e998f0a894b43daee892b341dd0 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Tue, 24 Nov 2026 18:07:29 -0500 Subject: [PATCH 12/35] Keep the app commands within older SDKs' builder limit CommandsBuilder on the macOS 15 and 26 SDKs accepts at most ten children, and the Account menu pushed AppCommands.body to eleven. Group the built-in command sets into one property. --- Sources/MactrixApp/Commands.swift | 15 +++++++++++---- 1 file changed, 11 insertions(+), 4 deletions(-) diff --git a/Sources/MactrixApp/Commands.swift b/Sources/MactrixApp/Commands.swift index 8952edd3..3cd722f6 100644 --- a/Sources/MactrixApp/Commands.swift +++ b/Sources/MactrixApp/Commands.swift @@ -10,10 +10,9 @@ public struct AppCommands: Commands { } public var body: some Commands { - SidebarCommands() - InspectorCommands() - TextEditingCommands() - ToolbarCommands() + // Older SDKs' CommandsBuilder accepts at most 10 children, so the + // built-in command sets are grouped into one property. + builtInCommands about newTab @@ -24,6 +23,14 @@ public struct AppCommands: Commands { conversationCommands } + @CommandsBuilder + var builtInCommands: some Commands { + SidebarCommands() + InspectorCommands() + TextEditingCommands() + ToolbarCommands() + } + var accountCommands: some Commands { CommandMenu("Account") { ForEach(Array(appState.accounts.enumerated()), id: \.element.storeID) { index, account in From 86231ee4549ef6f402e8c445478bf903023d004f Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Wed, 25 Nov 2026 01:48:00 -0500 Subject: [PATCH 13/35] Localize the multi-account strings Wrap the account strings that were plain Swift strings (accessibility labels, popover rows, the duplicate sign-in error, and the sign-out button title) in String(localized:), and make the welcome sheet title a LocalizedStringKey. The unread badge shows a bare number, so it's now verbatim. Add the new strings to Mactrix/Localizable.xcstrings with scripts/sync-strings.sh, keeping the catalog's existing key order. --- Mactrix/Localizable.xcstrings | 32 +++++++++++++++++++ Sources/MactrixApp/Models/AppState.swift | 2 +- .../Views/Settings/AccountSettingsView.swift | 6 +++- .../Views/Sidebar/AccountSwitcher.swift | 17 +++++----- .../MactrixApp/Views/WelcomeSheetView.swift | 2 +- 5 files changed, 48 insertions(+), 11 deletions(-) diff --git a/Mactrix/Localizable.xcstrings b/Mactrix/Localizable.xcstrings index e4b75d61..804f49fa 100644 --- a/Mactrix/Localizable.xcstrings +++ b/Mactrix/Localizable.xcstrings @@ -4,6 +4,17 @@ "" : { "shouldTranslate" : false }, + "%@, %lld unread in other accounts" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$@, %2$lld unread in other accounts" + } + } + } + }, + "%lld unread" : {}, "(edited)" : { "localizations" : { "da" : { @@ -458,6 +469,7 @@ } } }, + "Active Account" : {}, "Activities" : { "localizations" : { "da" : { @@ -474,6 +486,8 @@ } } }, + "Add Account" : {}, + "Add Account…" : {}, "Add Reaction" : { "localizations" : { "da" : { @@ -3955,6 +3969,7 @@ } } }, + "No Account" : {}, "No backup found" : { "localizations" : { "da" : { @@ -4896,6 +4911,7 @@ } } }, + "Remove Account" : {}, "Reply" : { "localizations" : { "da" : { @@ -5773,6 +5789,8 @@ } } }, + "Sign In Again as %@" : {}, + "Sign In Again…" : {}, "Sign in to continue." : { "localizations" : { "da" : { @@ -5815,6 +5833,12 @@ } } }, + "Sign Out" : {}, + "Sign out of %@?" : {}, + "Sign Out of %@…" : {}, + "Sign Out of This Account" : {}, + "Signed Out" : {}, + "Signed out" : {}, "Smileys & Emotion" : { "localizations" : { "da" : { @@ -7415,6 +7439,9 @@ } } }, + "Switch account" : {}, + "Switch account, current: %@" : {}, + "Switch accounts from the sidebar or the Account menu." : {}, "Symbols" : { "localizations" : { "da" : { @@ -7537,6 +7564,7 @@ } } }, + "This account will be signed out on this Mac. Your other accounts stay signed in." : {}, "This device is verified" : { "localizations" : { "da" : { @@ -7601,6 +7629,7 @@ } } }, + "This session was ended by the server or another device." : {}, "This will remove the message for everyone in the room. This action cannot be undone." : { "localizations" : { "da" : { @@ -8095,6 +8124,7 @@ } } }, + "Unread rooms in your other accounts" : {}, "Unsupported attachment (%@): %@" : { "localizations" : { "da" : { @@ -8725,6 +8755,8 @@ } } }, + "You were signed out." : {}, + "You're already signed in as %@." : {}, "Your account recognizes this device as trusted." : { "localizations" : { "da" : { diff --git a/Sources/MactrixApp/Models/AppState.swift b/Sources/MactrixApp/Models/AppState.swift index f77bac23..ed73a1dd 100644 --- a/Sources/MactrixApp/Models/AppState.swift +++ b/Sources/MactrixApp/Models/AppState.swift @@ -21,7 +21,7 @@ public final class AppState { public var errorDescription: String? { switch self { case .alreadySignedIn(let userID): - "You're already signed in as \(userID)." + String(localized: "You're already signed in as \(userID).") } } } diff --git a/Sources/MactrixApp/Views/Settings/AccountSettingsView.swift b/Sources/MactrixApp/Views/Settings/AccountSettingsView.swift index 53f726e0..f1ed2a17 100644 --- a/Sources/MactrixApp/Views/Settings/AccountSettingsView.swift +++ b/Sources/MactrixApp/Views/Settings/AccountSettingsView.swift @@ -92,7 +92,11 @@ struct AccountSettingsView: View { } HStack { - Button(appState.accounts.count > 1 ? "Sign Out of This Account" : "Sign out", role: .destructive) { + Button( + appState.accounts.count > 1 + ? String(localized: "Sign Out of This Account") : String(localized: "Sign out"), + role: .destructive + ) { Task { do { try await appState.reset() diff --git a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift index b5cb6768..9cafe239 100644 --- a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift +++ b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift @@ -105,10 +105,11 @@ struct AccountSwitcher: View { } private var accessibilityLabel: String { - guard let active = appState.matrixClient else { return "Switch account" } - let label = "Switch account, current: \(active.accountMenuTitle)" + guard let active = appState.matrixClient else { return String(localized: "Switch account") } + let label = String(localized: "Switch account, current: \(active.accountMenuTitle)") let unread = appState.inactiveUnreadRoomCount - return unread > 0 ? "\(label), \(unread) unread in other accounts" : label + return unread > 0 + ? String(localized: "\(label), \(unread) unread in other accounts") : label } private var popoverContent: some View { @@ -123,14 +124,14 @@ struct AccountSwitcher: View { Divider() .padding(.vertical, 4) - PopoverActionRow(title: "Add Account…", systemImage: "plus") { + PopoverActionRow(title: String(localized: "Add Account…"), systemImage: "plus") { isPresented = false windowState.loginSheet = .addAccount } if let active = appState.matrixClient { PopoverActionRow( - title: "Sign Out of \(active.accountName)…", + title: String(localized: "Sign Out of \(active.accountName)…"), systemImage: "rectangle.portrait.and.arrow.right" ) { isPresented = false @@ -186,8 +187,8 @@ private struct AccountRow: View { } private var accessibilityValue: String { - if account.authenticationFailed { return "Signed out" } - if account.unreadRoomCount > 0 { return "\(account.unreadRoomCount) unread" } + if account.authenticationFailed { return String(localized: "Signed out") } + if account.unreadRoomCount > 0 { return String(localized: "\(account.unreadRoomCount) unread") } return "" } } @@ -197,7 +198,7 @@ private struct UnreadBadge: View { let count: Int var body: some View { - Text("\(count)") + Text(verbatim: "\(count)") .font(.caption.weight(.semibold).monospacedDigit()) .foregroundStyle(.white) .padding(.horizontal, 6) diff --git a/Sources/MactrixApp/Views/WelcomeSheetView.swift b/Sources/MactrixApp/Views/WelcomeSheetView.swift index 610330e1..4500906f 100644 --- a/Sources/MactrixApp/Views/WelcomeSheetView.swift +++ b/Sources/MactrixApp/Views/WelcomeSheetView.swift @@ -192,7 +192,7 @@ struct WelcomeSheetView: View { } } - private var title: String { + private var title: LocalizedStringKey { switch request { case .firstAccount: "Welcome to Mactrix" case .addAccount: "Add Account" From 1f55ac71239a77b3b617e2227562c964380382a2 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Wed, 25 Nov 2026 13:20:20 -0500 Subject: [PATCH 14/35] Move the account switcher into the sidebar's status bar The bottom status bar was a placeholder for the account switcher, so the switcher now lives there instead of at the top of the sidebar, and its popover opens upward. The "Sync: online" text is folded into the switcher: each account's avatar carries a dot coloured by its sync state, and when the active account isn't syncing, the popover says so at the top and offers to restart sync. --- .../Views/Sidebar/AccountStatus.swift | 142 ++++++++++++++++++ .../Views/Sidebar/AccountSwitcher.swift | 37 ++++- .../Views/Sidebar/SidebarSyncState.swift | 54 ------- .../Views/Sidebar/SidebarView.swift | 20 +-- 4 files changed, 179 insertions(+), 74 deletions(-) create mode 100644 Sources/MactrixApp/Views/Sidebar/AccountStatus.swift delete mode 100644 Sources/MactrixApp/Views/Sidebar/SidebarSyncState.swift diff --git a/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift b/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift new file mode 100644 index 00000000..91ff6701 --- /dev/null +++ b/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift @@ -0,0 +1,142 @@ +import MatrixIntegration +import MatrixRustSDK +import OSLog +import SwiftUI + +extension SyncServiceState { + var label: String { + switch self { + case .idle: + String(localized: "idle") + case .running: + String(localized: "online") + case .terminated: + String(localized: "terminated") + case .error: + String(localized: "error") + case .offline: + String(localized: "offline") + } + } + + var color: Color { + switch self { + case .running: .green + case .idle: .gray + case .offline: .orange + case .terminated, .error: .red + } + } + + var canRestart: Bool { + [.error, .offline, .terminated].contains(self) + } +} + +extension MatrixClient { + /// Whether the account switcher popover has anything to say about this account's status. + var hasStatus: Bool { + syncState != .running + } +} + +/// A small dot showing an account's sync state. +struct SyncStateDot: View { + let state: SyncServiceState + var size: CGFloat = 8 + + var body: some View { + Circle() + .fill(state.color) + .frame(width: size, height: size) + } +} + +/// The active account's status at the top of the account switcher popover: its sync state, and +/// anything that needs the user's attention. +struct AccountStatusSection: View { + let account: MatrixClient + + @State private var restarting = false + + var body: some View { + VStack(alignment: .leading, spacing: 10) { + if account.syncState != .running { + syncStatus + } + } + } + + private var syncStatus: some View { + AccountStatusItem(systemImage: "arrow.triangle.2.circlepath", tint: account.syncState.color) { + Text("Sync: \(account.syncState.label)") + } actions: { + if account.syncState.canRestart { + Button("Restart sync") { + Task { + restarting = true + defer { restarting = false } + + do { + try await account.startSync() + } catch { + Logger.viewCycle.error("failed to restart sync: \(error)") + } + } + } + .disabled(restarting) + } + } + } +} + +/// One status message in the account switcher popover, with optional actions below it. +struct AccountStatusItem: View { + let systemImage: String + let tint: Color + @ViewBuilder let title: Title + @ViewBuilder let message: Message + @ViewBuilder let actions: Actions + + init( + systemImage: String, tint: Color, + @ViewBuilder title: () -> Title, + @ViewBuilder message: () -> Message = { EmptyView() }, + @ViewBuilder actions: () -> Actions = { EmptyView() } + ) { + self.systemImage = systemImage + self.tint = tint + self.title = title() + self.message = message() + self.actions = actions() + } + + var body: some View { + HStack(alignment: .firstTextBaseline, spacing: 8) { + Image(systemName: systemImage) + .foregroundStyle(tint) + .frame(width: 14) + + VStack(alignment: .leading, spacing: 6) { + VStack(alignment: .leading, spacing: 2) { + title + .font(.body.weight(.semibold)) + message + .font(.callout) + .foregroundStyle(.secondary) + } + .fixedSize(horizontal: false, vertical: true) + + if Actions.self != EmptyView.self { + HStack(spacing: 6) { + actions + } + .controlSize(.small) + } + } + Spacer(minLength: 0) + } + .padding(.horizontal, 6) + .padding(.vertical, 4) + } +} diff --git a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift index 9cafe239..cb709752 100644 --- a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift +++ b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift @@ -1,5 +1,6 @@ import MactrixUI import MatrixIntegration +import MatrixRustSDK import SwiftUI extension MatrixClient { @@ -14,7 +15,7 @@ extension MatrixClient { } } -/// An account's avatar, display name, and Matrix ID. +/// An account's avatar with its sync state, display name, and Matrix ID. struct AccountLabel: View { let account: MatrixClient var showsUserID = true @@ -27,6 +28,13 @@ struct AccountLabel: View { avatarUrl: account.ownAvatarUrl, imageLoader: account ) .frame(width: avatarSize, height: avatarSize) + .overlay(alignment: .bottomTrailing) { + SyncStateDot(state: account.syncState) + .padding(1.5) + .background(.background, in: Circle()) + .offset(x: 2, y: 2) + .help(String(localized: "Sync: \(account.syncState.label)")) + } VStack(alignment: .leading, spacing: 1) { Text(account.accountName) @@ -45,8 +53,8 @@ struct AccountLabel: View { } } -/// A button at the top of the sidebar that opens a popover for switching, adding, and signing -/// out of accounts. +/// A button at the bottom of the sidebar that shows the active account's status and opens a +/// popover for switching, adding, and signing out of accounts. struct AccountSwitcher: View { @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState @@ -86,7 +94,7 @@ struct AccountSwitcher: View { .onHover { isHovered = $0 } .help("Switch account") .accessibilityLabel(accessibilityLabel) - .popover(isPresented: $isPresented, arrowEdge: .bottom) { + .popover(isPresented: $isPresented, arrowEdge: .top) { popoverContent } .confirmationDialog( @@ -106,7 +114,10 @@ struct AccountSwitcher: View { private var accessibilityLabel: String { guard let active = appState.matrixClient else { return String(localized: "Switch account") } - let label = String(localized: "Switch account, current: \(active.accountMenuTitle)") + var label = String(localized: "Switch account, current: \(active.accountMenuTitle)") + if active.syncState != .running { + label = String(localized: "\(label), sync: \(active.syncState.label)") + } let unread = appState.inactiveUnreadRoomCount return unread > 0 ? String(localized: "\(label), \(unread) unread in other accounts") : label @@ -114,6 +125,12 @@ struct AccountSwitcher: View { private var popoverContent: some View { VStack(alignment: .leading, spacing: 2) { + if let active = appState.matrixClient, active.hasStatus { + AccountStatusSection(account: active) + Divider() + .padding(.vertical, 4) + } + ForEach(appState.accounts, id: \.storeID) { account in AccountRow(account: account, isActive: appState.activeAccountID == account.storeID) { appState.activate(account) @@ -188,8 +205,14 @@ private struct AccountRow: View { private var accessibilityValue: String { if account.authenticationFailed { return String(localized: "Signed out") } - if account.unreadRoomCount > 0 { return String(localized: "\(account.unreadRoomCount) unread") } - return "" + var values: [String] = [] + if account.syncState != .running { + values.append(String(localized: "Sync: \(account.syncState.label)")) + } + if account.unreadRoomCount > 0 { + values.append(String(localized: "\(account.unreadRoomCount) unread")) + } + return values.joined(separator: ", ") } } diff --git a/Sources/MactrixApp/Views/Sidebar/SidebarSyncState.swift b/Sources/MactrixApp/Views/Sidebar/SidebarSyncState.swift deleted file mode 100644 index f61b420e..00000000 --- a/Sources/MactrixApp/Views/Sidebar/SidebarSyncState.swift +++ /dev/null @@ -1,54 +0,0 @@ -import MatrixRustSDK -import OSLog -import SwiftUI - -struct SidebarSyncStateView: View { - @Environment(AppState.self) var appState - - @State var restarting: Bool = false - - var syncState: String { - switch appState.matrixClient?.syncState { - case .idle: - String(localized: "idle") - case .running: - String(localized: "online") - case .terminated: - String(localized: "terminated") - case .error: - String(localized: "error") - case .offline: - String(localized: "offline") - case nil: - String(localized: "logged out") - } - } - - var canRestart: Bool { - return [.error, .offline, .terminated].contains(where: { - $0 == appState.matrixClient?.syncState - }) - } - - var body: some View { - VStack { - Text("Sync: \(syncState)") - .foregroundStyle(.secondary) - if canRestart { - Button("Restart sync") { - Task { - restarting = true - defer { restarting = false } - - do { - try await appState.matrixClient?.startSync() - } catch { - Logger.viewCycle.error("failed to restart sync: \(error)") - } - } - } - .disabled(restarting) - } - } - } -} diff --git a/Sources/MactrixApp/Views/Sidebar/SidebarView.swift b/Sources/MactrixApp/Views/Sidebar/SidebarView.swift index 519cfed1..26b6ea48 100644 --- a/Sources/MactrixApp/Views/Sidebar/SidebarView.swift +++ b/Sources/MactrixApp/Views/Sidebar/SidebarView.swift @@ -63,18 +63,12 @@ struct SidebarView: View { } var content: some View { - VStack(spacing: 0) { - AccountSwitcher() - .padding(.horizontal, 12) - .padding(.vertical, 8) + HStack(spacing: 0) { + SidebarGroupsList() Divider() - HStack(spacing: 0) { - SidebarGroupsList() - Divider() - listView - // force list view to re-render to avoid a rendering bug - .id(windowState.selectedSpaceId) - } + listView + // force list view to re-render to avoid a rendering bug + .id(windowState.selectedSpaceId) } .task(id: selectedSpace?.id) { await selectedSpace?.loadChildren() @@ -107,11 +101,11 @@ struct SidebarView: View { private var statusContent: some View { VStack(spacing: 8) { SidebarSignedOutView() - SidebarSyncStateView() SessionVerificationStatusView() + AccountSwitcher() } .frame(maxWidth: .infinity) - .padding(12) + .padding(6) } /// The room name, or the linked contact's name for direct chats. From ca609330c5fa97a5f7e052d2d59e8648a81533b4 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Wed, 25 Nov 2026 13:20:42 -0500 Subject: [PATCH 15/35] Fold the signed-out notice into the account switcher MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit When the server ends the active account's session, the switcher shows an attention mark and its popover offers Sign In Again… and Remove Account, replacing the orange card above the status bar. --- .../Views/Sidebar/AccountStatus.swift | 39 +++++++++++++++- .../Views/Sidebar/AccountSwitcher.swift | 9 +++- .../Views/Sidebar/SidebarSignedOutView.swift | 46 ------------------- .../Views/Sidebar/SidebarView.swift | 1 - 4 files changed, 45 insertions(+), 50 deletions(-) delete mode 100644 Sources/MactrixApp/Views/Sidebar/SidebarSignedOutView.swift diff --git a/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift b/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift index 91ff6701..9a823cd0 100644 --- a/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift +++ b/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift @@ -34,9 +34,14 @@ extension SyncServiceState { } extension MatrixClient { + /// Whether this account needs the user to act, which the account switcher flags. + var needsAttention: Bool { + authenticationFailed + } + /// Whether the account switcher popover has anything to say about this account's status. var hasStatus: Bool { - syncState != .running + needsAttention || syncState != .running } } @@ -55,18 +60,48 @@ struct SyncStateDot: View { /// The active account's status at the top of the account switcher popover: its sync state, and /// anything that needs the user's attention. struct AccountStatusSection: View { + @Environment(AppState.self) var appState + @Environment(WindowState.self) var windowState + let account: MatrixClient + /// Closes the popover, before presenting a sheet. + let dismiss: () -> Void @State private var restarting = false + @State private var removing = false var body: some View { VStack(alignment: .leading, spacing: 10) { - if account.syncState != .running { + if account.authenticationFailed { + signedOut + } else if account.syncState != .running { syncStatus } } } + /// Shown when the server has ended the account's session. + private var signedOut: some View { + AccountStatusItem(systemImage: "person.crop.circle.badge.exclamationmark", tint: .orange) { + Text("You were signed out.") + } message: { + Text("This session was ended by the server or another device.") + } actions: { + Button("Sign In Again…") { + dismiss() + windowState.loginSheet = .signInAgain(userID: account.userID) + } + Button("Remove Account") { + Task { + removing = true + defer { removing = false } + await appState.remove(account) + } + } + .disabled(removing) + } + } + private var syncStatus: some View { AccountStatusItem(systemImage: "arrow.triangle.2.circlepath", tint: account.syncState.color) { Text("Sync: \(account.syncState.label)") diff --git a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift index cb709752..4332256b 100644 --- a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift +++ b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift @@ -75,6 +75,10 @@ struct AccountSwitcher: View { .font(.body.weight(.semibold)) } Spacer(minLength: 0) + if appState.matrixClient?.needsAttention == true { + Image(systemName: "exclamationmark.circle.fill") + .foregroundStyle(.orange) + } if appState.inactiveUnreadRoomCount > 0 { UnreadBadge(count: appState.inactiveUnreadRoomCount) .help("Unread rooms in your other accounts") @@ -118,6 +122,9 @@ struct AccountSwitcher: View { if active.syncState != .running { label = String(localized: "\(label), sync: \(active.syncState.label)") } + if active.needsAttention { + label = String(localized: "\(label), needs attention") + } let unread = appState.inactiveUnreadRoomCount return unread > 0 ? String(localized: "\(label), \(unread) unread in other accounts") : label @@ -126,7 +133,7 @@ struct AccountSwitcher: View { private var popoverContent: some View { VStack(alignment: .leading, spacing: 2) { if let active = appState.matrixClient, active.hasStatus { - AccountStatusSection(account: active) + AccountStatusSection(account: active) { isPresented = false } Divider() .padding(.vertical, 4) } diff --git a/Sources/MactrixApp/Views/Sidebar/SidebarSignedOutView.swift b/Sources/MactrixApp/Views/Sidebar/SidebarSignedOutView.swift deleted file mode 100644 index 47ba4e8b..00000000 --- a/Sources/MactrixApp/Views/Sidebar/SidebarSignedOutView.swift +++ /dev/null @@ -1,46 +0,0 @@ -import SwiftUI - -/// Shown when the server has ended the active account's session. -struct SidebarSignedOutView: View { - @Environment(AppState.self) var appState - @Environment(WindowState.self) var windowState - @Environment(\.colorScheme) var colorScheme - - @State private var removing = false - - var body: some View { - if let matrixClient = appState.matrixClient, matrixClient.authenticationFailed { - VStack { - Label { - Text("You were signed out.") - .bold() - Text("This session was ended by the server or another device.") - .lineLimit(9) - } icon: { - Image(systemName: "person.crop.circle.badge.exclamationmark") - .bold() - } - .labelStyle(.multiline) - .frame(maxWidth: .infinity) - - HStack { - Button("Sign In Again…") { - windowState.loginSheet = .signInAgain(userID: matrixClient.userID) - } - Button("Remove Account") { - Task { - removing = true - defer { removing = false } - await appState.remove(matrixClient) - } - } - } - .disabled(removing) - } - .padding(10) - .background(Color.orange.opacity(0.2)) - .foregroundStyle(Color.orange.mix(with: colorScheme == .light ? .black : .white, by: 0.5)) - .clipShape(RoundedRectangle(cornerRadius: 8)) - } - } -} diff --git a/Sources/MactrixApp/Views/Sidebar/SidebarView.swift b/Sources/MactrixApp/Views/Sidebar/SidebarView.swift index 26b6ea48..4ce9011c 100644 --- a/Sources/MactrixApp/Views/Sidebar/SidebarView.swift +++ b/Sources/MactrixApp/Views/Sidebar/SidebarView.swift @@ -100,7 +100,6 @@ struct SidebarView: View { private var statusContent: some View { VStack(spacing: 8) { - SidebarSignedOutView() SessionVerificationStatusView() AccountSwitcher() } From 3681e2bec33c786a5f955ddf70275dfee2771252 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Wed, 25 Nov 2026 13:21:07 -0500 Subject: [PATCH 16/35] Fold session verification into the account switcher MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit An unverified session or an incoming verification request now marks the switcher for attention, and its popover offers Verify session… or Start Verification / Decline, replacing the red and green cards in the status bar. Verification requests time out, so the popover opens on its own when one arrives. That leaves the switcher as the status bar's only content. --- .../Views/Sidebar/AccountStatus.swift | 83 ++++++++++++- .../Views/Sidebar/AccountSwitcher.swift | 4 + .../Sidebar/SidebarSessionVerification.swift | 109 ------------------ .../Views/Sidebar/SidebarView.swift | 9 +- 4 files changed, 86 insertions(+), 119 deletions(-) delete mode 100644 Sources/MactrixApp/Views/Sidebar/SidebarSessionVerification.swift diff --git a/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift b/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift index 9a823cd0..bbd65f8e 100644 --- a/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift +++ b/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift @@ -36,12 +36,12 @@ extension SyncServiceState { extension MatrixClient { /// Whether this account needs the user to act, which the account switcher flags. var needsAttention: Bool { - authenticationFailed + authenticationFailed || sessionVerificationRequest != nil || verificationState == .unverified } /// Whether the account switcher popover has anything to say about this account's status. var hasStatus: Bool { - needsAttention || syncState != .running + needsAttention || verificationState == .unknown || syncState != .running } } @@ -74,8 +74,83 @@ struct AccountStatusSection: View { VStack(alignment: .leading, spacing: 10) { if account.authenticationFailed { signedOut - } else if account.syncState != .running { - syncStatus + } else { + if let request = account.sessionVerificationRequest { + verificationRequest(request) + } else { + switch account.verificationState { + case .unverified: + unverified + case .unknown: + AccountStatusItem(systemImage: "questionmark.circle", tint: .secondary) { + Text("Unknown verification state") + } + case .verified, nil: + EmptyView() + } + } + if account.syncState != .running { + syncStatus + } + } + } + } + + /// Another of the user's devices asked to verify this session. + private func verificationRequest(_ request: SessionVerificationRequestDetails) -> some View { + AccountStatusItem(systemImage: "person.badge.key", tint: .green) { + Text("Verification request from \(request.senderProfile.userId)") + } actions: { + Button("Start Verification") { + dismiss() + Task { + do { + try await account.acceptVerificationRequest(request: request) + } catch { + Logger.viewCycle.error("failed to accept verification request: \(error)") + account.sessionVerificationRequest = nil + } + } + } + .buttonStyle(.borderedProminent) + + Button("Decline") { + Task { + do { + try await account.declineVerificationRequest(request: request) + } catch { + Logger.viewCycle.error("failed to decline verification request: \(error)") + account.sessionVerificationRequest = nil + } + } + } + } + } + + private var unverified: some View { + AccountStatusItem(systemImage: "exclamationmark.shield", tint: .red) { + Text("This session is unverified.") + } message: { + VStack(alignment: .leading, spacing: 4) { + Text("Verify the session for better security and to decrypt all messages.") + if windowState.requestedVerification { + HStack(spacing: 6) { + ProgressView() + .controlSize(.mini) + Text("Requesting verification from your trusted devices...") + } + } + } + } actions: { + Button(windowState.requestedVerification ? "Try again" : "Verify session...") { + Task { + do { + try await account.requestDeviceVerification() + windowState.requestedVerification = true + } catch { + Logger.viewCycle.error("request device verification failed: \(error)") + } + } } } } diff --git a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift index 4332256b..f7a1880e 100644 --- a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift +++ b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift @@ -101,6 +101,10 @@ struct AccountSwitcher: View { .popover(isPresented: $isPresented, arrowEdge: .top) { popoverContent } + // Verification requests time out, so don't leave one waiting behind a closed popover. + .onChange(of: appState.matrixClient?.sessionVerificationRequest?.flowId) { _, flowID in + if flowID != nil { isPresented = true } + } .confirmationDialog( "Sign out of \(accountToSignOut?.userID ?? "")?", isPresented: Binding( diff --git a/Sources/MactrixApp/Views/Sidebar/SidebarSessionVerification.swift b/Sources/MactrixApp/Views/Sidebar/SidebarSessionVerification.swift deleted file mode 100644 index c99f0044..00000000 --- a/Sources/MactrixApp/Views/Sidebar/SidebarSessionVerification.swift +++ /dev/null @@ -1,109 +0,0 @@ -import MatrixRustSDK -import OSLog -import SwiftUI - -struct SessionVerificationStatusView: View { - @Environment(AppState.self) var appState - @Environment(WindowState.self) var windowState - @Environment(\.colorScheme) var colorScheme - - @ViewBuilder - var selfVerificationView: some View { - switch appState.matrixClient?.verificationState { - case nil: - EmptyView() - case .unknown: - Text("Unknown verification state") - .padding(10) - .background(Color.gray.opacity(0.2)) - .clipShape(RoundedRectangle(cornerRadius: 8)) - .frame(maxWidth: .infinity) - case .verified: - EmptyView() - case .unverified: - VStack { - Label { - Text("This session is unverified.") - .bold() - - // NOTE(alicerunsonfedora): Setting a hard line limit because SwiftUI will otherwise truncate the - // text, even when there's enough room to do so. - Text("Verify the session for better security and to decrypt all messages.") - .lineLimit(9) - } icon: { - Image(systemName: "exclamationmark.shield") - .bold() - } - .labelStyle(.multiline) - .frame(maxWidth: .infinity) - HStack { - if windowState.requestedVerification { - ProgressView("Requesting verification from your trusted devices...") - } - Button(windowState.requestedVerification ? "Try again" : "Verify session...") { - Task { - await startVerificationRequest() - } - } - } - } - .padding(10) - .background(Color.red.opacity(0.2)) - .foregroundStyle(Color.red.mix(with: colorScheme == .light ? .black : .white, by: 0.5)) - .clipShape(RoundedRectangle(cornerRadius: 8)) - } - } - - var body: some View { - if let verificationRequest = appState.matrixClient?.sessionVerificationRequest { - VStack { - Label( - "Verification request from \(verificationRequest.senderProfile.userId)", - systemImage: "person.badge.key" - ) - .frame(maxWidth: .infinity) - HStack { - Button("Start Verification") { - Task { - do { - try await appState.matrixClient?.acceptVerificationRequest( - request: verificationRequest) - } catch { - Logger.viewCycle.error("failed to accept verification request: \(error)") - appState.matrixClient?.sessionVerificationRequest = nil - } - } - } - .buttonStyle(.borderedProminent) - - Button("Decline") { - Task { - do { - try await appState.matrixClient?.declineVerificationRequest( - request: verificationRequest) - } catch { - Logger.viewCycle.error("failed to decline verification request: \(error)") - appState.matrixClient?.sessionVerificationRequest = nil - } - } - } - } - } - .padding(10) - .background(Color.green.opacity(0.2)) - .foregroundStyle(Color.green.mix(with: colorScheme == .light ? .black : .white, by: 0.5)) - .clipShape(RoundedRectangle(cornerRadius: 8)) - } else { - selfVerificationView - } - } - - private func startVerificationRequest() async { - do { - try await appState.matrixClient?.requestDeviceVerification() - windowState.requestedVerification = true - } catch { - Logger.viewCycle.error("request device verification failed: \(error)") - } - } -} diff --git a/Sources/MactrixApp/Views/Sidebar/SidebarView.swift b/Sources/MactrixApp/Views/Sidebar/SidebarView.swift index 4ce9011c..ac677e61 100644 --- a/Sources/MactrixApp/Views/Sidebar/SidebarView.swift +++ b/Sources/MactrixApp/Views/Sidebar/SidebarView.swift @@ -99,12 +99,9 @@ struct SidebarView: View { } private var statusContent: some View { - VStack(spacing: 8) { - SessionVerificationStatusView() - AccountSwitcher() - } - .frame(maxWidth: .infinity) - .padding(6) + AccountSwitcher() + .frame(maxWidth: .infinity) + .padding(6) } /// The room name, or the linked contact's name for direct chats. From efce9439051e14a5c80a1c04bdbc564410d68a46 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Wed, 25 Nov 2026 13:21:49 -0500 Subject: [PATCH 17/35] Localize the account status strings Add the switcher's new accessibility strings to the catalog and mark "logged out" stale now that the sync state view is gone. Every other status string reuses an existing key, keeping its translations. --- Mactrix/Localizable.xcstrings | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/Mactrix/Localizable.xcstrings b/Mactrix/Localizable.xcstrings index 804f49fa..c8b6867c 100644 --- a/Mactrix/Localizable.xcstrings +++ b/Mactrix/Localizable.xcstrings @@ -14,6 +14,17 @@ } } }, + "%@, needs attention" : {}, + "%@, sync: %@" : { + "localizations" : { + "en" : { + "stringUnit" : { + "state" : "new", + "value" : "%1$@, sync: %2$@" + } + } + } + }, "%lld unread" : {}, "(edited)" : { "localizations" : { @@ -3560,6 +3571,7 @@ } }, "logged out" : { + "extractionState" : "stale", "localizations" : { "da" : { "stringUnit" : { @@ -8791,4 +8803,4 @@ } }, "version" : "1.0" -} \ No newline at end of file +} From 352767e64256a6e95cc4235698cb2b0533972e7e Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Thu, 26 Nov 2026 15:58:33 -0500 Subject: [PATCH 18/35] Read the account from the window instead of the app Each WindowState now holds a weak reference to the client of the account it shows, and the window's views read the client from it rather than from AppState. AppState still owns the clients and decides which account every window shows, so behaviour is unchanged; this prepares for windows showing different accounts. --- Sources/MactrixApp/MainView.swift | 35 ++++++++++--------- Sources/MactrixApp/Models/AppState.swift | 2 +- Sources/MactrixApp/Models/WindowState.swift | 9 +++++ .../ChatView/ChatRoomViewController.swift | 8 ++--- .../ChatView/ChatRoomViewRepresentable.swift | 3 +- .../MactrixApp/Views/ChatView/ChatView.swift | 5 +-- .../TimelineView/TimelineTableView.swift | 24 ++++++------- .../Views/Inspector/InspectorScreen.swift | 3 +- .../Views/Inspector/InspectorUserInfo.swift | 11 +++--- .../Views/LoadDestinationScreen.swift | 11 +++--- .../MactrixApp/Views/MatrixImageView.swift | 4 +-- .../Views/Search/SearchInspectorView.swift | 20 +++++------ .../Search/SearchMessagesInspectorView.swift | 12 ++++--- .../Search/SearchRoomInspectorView.swift | 3 +- .../Search/SearchUserInspectorView.swift | 5 ++- .../Views/Search/SearchViewModifier.swift | 3 +- .../Views/Sidebar/AccountSwitcher.swift | 12 +++---- .../Views/Sidebar/SidebarGroupsList.swift | 10 +++--- .../Views/Sidebar/SidebarView.swift | 13 ++++--- .../Views/Sidebar/SpaceContextMenu.swift | 7 ++-- .../Views/Sidebar/SpaceDisclosureGroup.swift | 11 +++--- .../WindowStateAccountTests.swift | 2 +- 22 files changed, 108 insertions(+), 105 deletions(-) diff --git a/Sources/MactrixApp/MainView.swift b/Sources/MactrixApp/MainView.swift index 43a5ffe4..530dfad3 100644 --- a/Sources/MactrixApp/MainView.swift +++ b/Sources/MactrixApp/MainView.swift @@ -23,20 +23,21 @@ public struct MainView: View { case .previewRoom(let room, let eventId, let routingVia): MactrixUI.RoomPreviewView( preview: room.info(), - imageLoader: appState.matrixClient, - actions: appState.matrixClient?.roomPreviewActions( + imageLoader: windowState.matrixClient, + actions: windowState.matrixClient?.roomPreviewActions( forRoomWithId: room.info().roomId, windowState: windowState, eventId: eventId, routingVia: routingVia) ) .id(screen.id) case .newRoom: MactrixUI.CreateRoomScreen(onSubmit: { params in - guard let matrixClient = appState.matrixClient else { return } + guard let matrixClient = windowState.matrixClient else { return } guard windowState.selectedScreen === screen else { return } let newRoom = try await matrixClient.client.createRoom( request: params.asMatrixRequest) try Task.checkCancellation() - guard windowState.selectedScreen === screen, appState.matrixClient === matrixClient else { + guard windowState.selectedScreen === screen, windowState.matrixClient === matrixClient + else { return } windowState.selectRoom(newRoom) @@ -47,11 +48,11 @@ public struct MainView: View { case .user(let profile): UserProfileView( profile: profile, - isUserIgnored: appState.matrixClient?.isUserIgnored(profile.userId) ?? false, - actions: appState.matrixClient?.userProfileActions( + isUserIgnored: windowState.matrixClient?.isUserIgnored(profile.userId) ?? false, + actions: windowState.matrixClient?.userProfileActions( forUserId: profile.userId, windowState: windowState), timelineActions: nil, - imageLoader: appState.matrixClient + imageLoader: windowState.matrixClient ) case .none: ContentUnavailableView("Select a room", systemImage: "message.fill") @@ -60,16 +61,16 @@ public struct MainView: View { var verificationSheetPresented: Binding { Binding( - get: { appState.matrixClient?.sessionVerificationData != nil }, + get: { windowState.matrixClient?.sessionVerificationData != nil }, set: { isPresented in if !isPresented { Task { do { - try await appState.matrixClient?.client + try await windowState.matrixClient?.client .getSessionVerificationController().declineVerification() } catch { Logger.viewCycle.error("failed to decline verification: \(error)") - appState.matrixClient?.sessionVerificationData = nil + windowState.matrixClient?.sessionVerificationData = nil } } } @@ -92,7 +93,7 @@ public struct MainView: View { } ) .background { - let matrixClient = appState.matrixClient + let matrixClient = windowState.matrixClient QuickNavigationOverlayAttachment( coordinator: windowState.quickNavigation, matrixClient: matrixClient, onSelectRoom: { [weak windowState] roomID in @@ -106,7 +107,7 @@ public struct MainView: View { .sheet( isPresented: verificationSheetPresented, content: { - if let verificationData = appState.matrixClient?.sessionVerificationData { + if let verificationData = windowState.matrixClient?.sessionVerificationData { MactrixUI.SessionVerificationModal( verificationData: verificationData.asModel, onComplete: { response in @@ -114,23 +115,23 @@ public struct MainView: View { switch response { case .accept: do { - try await appState.matrixClient?.client + try await windowState.matrixClient?.client .getSessionVerificationController() .approveVerification() } catch { Logger.viewCycle.error( "failed to approve verification: \(error)") - appState.matrixClient?.sessionVerificationData = nil + windowState.matrixClient?.sessionVerificationData = nil } case .decline: do { - try await appState.matrixClient?.client + try await windowState.matrixClient?.client .getSessionVerificationController() .declineVerification() } catch { Logger.viewCycle.error( "failed to decline verification: \(error)") - appState.matrixClient?.sessionVerificationData = nil + windowState.matrixClient?.sessionVerificationData = nil } } } @@ -141,7 +142,7 @@ public struct MainView: View { .onChange(of: appState.restoration, initial: true) { _, restoration in guard case .restored(let activeAccountID) = restoration else { return } windowState.showAccount( - activeAccountID, knownAccountIDs: Set(appState.accounts.map(\.storeID))) + appState.matrixClient, knownAccountIDs: Set(appState.accounts.map(\.storeID))) if activeAccountID == nil { Logger.viewCycle.info("No signed in accounts, present welcome sheet") windowState.loginSheet = .firstAccount diff --git a/Sources/MactrixApp/Models/AppState.swift b/Sources/MactrixApp/Models/AppState.swift index ed73a1dd..f5e40b8a 100644 --- a/Sources/MactrixApp/Models/AppState.swift +++ b/Sources/MactrixApp/Models/AppState.swift @@ -155,7 +155,7 @@ public final class AppState { } activate(account) // Switch the window now so the room below isn't treated as the previous account's. - windowState.showAccount(account.storeID, knownAccountIDs: Set(accounts.map(\.storeID))) + windowState.showAccount(account, knownAccountIDs: Set(accounts.map(\.storeID))) } windowState.selectedRoomId = target.roomId } diff --git a/Sources/MactrixApp/Models/WindowState.swift b/Sources/MactrixApp/Models/WindowState.swift index 0155fdc8..3cc554fb 100644 --- a/Sources/MactrixApp/Models/WindowState.swift +++ b/Sources/MactrixApp/Models/WindowState.swift @@ -107,6 +107,9 @@ public final class WindowState { /// The account whose rooms `selectedRoomId` and `selectedSpaceId` refer to. public private(set) var accountID: String? + /// The client of the account this window shows. `AppState` owns the clients. + public private(set) weak var matrixClient: MatrixClient? + public var selectedRoomId: String? { get { switch selectedScreen.content { @@ -175,6 +178,12 @@ public final class WindowState { ) } + /// Shows `account`, remembering the current account's selection and restoring the new one's. + public func showAccount(_ account: MatrixClient?, knownAccountIDs: Set) { + showAccount(account?.storeID, knownAccountIDs: knownAccountIDs) + matrixClient = account + } + /// Shows `newAccountID`, remembering the current account's selection and restoring the new one's. /// /// `knownAccountIDs` lists the accounts that still exist; selections of others are dropped. diff --git a/Sources/MactrixApp/Views/ChatView/ChatRoomViewController.swift b/Sources/MactrixApp/Views/ChatView/ChatRoomViewController.swift index 76be2171..d8b9babf 100644 --- a/Sources/MactrixApp/Views/ChatView/ChatRoomViewController.swift +++ b/Sources/MactrixApp/Views/ChatView/ChatRoomViewController.swift @@ -8,15 +8,15 @@ final class ChatRoomViewController: NSViewController { private var composerAccessory: NSViewController? init( - appState: AppState, windowState: WindowState, timeline: LiveTimeline, + windowState: WindowState, timeline: LiveTimeline, composer: ChatComposerState ) { timelineController = TimelineViewController( - appState: appState, windowState: windowState, timeline: timeline, composer: composer) + windowState: windowState, timeline: timeline, composer: composer) composerController = ChatInputViewController( room: timeline.room.room, timeline: timeline, composer: composer, - imageLoader: appState.matrixClient, - avatarURLLookup: { [weak matrixClient = appState.matrixClient] userID in + imageLoader: windowState.matrixClient, + avatarURLLookup: { [weak matrixClient = windowState.matrixClient] userID in guard let matrixClient else { return nil } let profile = try await matrixClient.client.getProfile(userId: userID) return profile.avatarUrl diff --git a/Sources/MactrixApp/Views/ChatView/ChatRoomViewRepresentable.swift b/Sources/MactrixApp/Views/ChatView/ChatRoomViewRepresentable.swift index 5060c824..c03847e9 100644 --- a/Sources/MactrixApp/Views/ChatView/ChatRoomViewRepresentable.swift +++ b/Sources/MactrixApp/Views/ChatView/ChatRoomViewRepresentable.swift @@ -2,7 +2,6 @@ import MatrixIntegration import SwiftUI struct ChatRoomViewRepresentable: NSViewControllerRepresentable { - @Environment(AppState.self) private var appState @Environment(WindowState.self) private var windowState @Environment(\.accessibilityReduceTransparency) private var reduceTransparency @AppStorage("fontSize") private var fontSize = 13 @@ -12,7 +11,7 @@ struct ChatRoomViewRepresentable: NSViewControllerRepresentable { func makeNSViewController(context: Context) -> ChatRoomViewController { ChatRoomViewController( - appState: appState, windowState: windowState, timeline: timeline, composer: composer) + windowState: windowState, timeline: timeline, composer: composer) } func updateNSViewController(_ controller: ChatRoomViewController, context: Context) { diff --git a/Sources/MactrixApp/Views/ChatView/ChatView.swift b/Sources/MactrixApp/Views/ChatView/ChatView.swift index 4910ebdb..54ce03a9 100644 --- a/Sources/MactrixApp/Views/ChatView/ChatView.swift +++ b/Sources/MactrixApp/Views/ChatView/ChatView.swift @@ -13,7 +13,7 @@ private struct TimelineReadKey: Equatable { } struct ChatJoinedRoom: View { - @Environment(AppState.self) private var appState + @Environment(WindowState.self) private var windowState @Environment(\.appearsActive) private var appearsActive @Bindable var timeline: LiveTimeline @State private var composer = ChatComposerState() @@ -42,7 +42,8 @@ struct ChatJoinedRoom: View { .task(priority: .background) { do { try await Task.sleep(for: .seconds(2)) - try await appState.matrixClient?.client.trackRecentlyVisitedRoom(room: timeline.room.id) + try await windowState.matrixClient?.client.trackRecentlyVisitedRoom( + room: timeline.room.id) Logger.viewCycle.debug("marked room as recently visited: \(timeline.room.id)") } catch is CancellationError { /* sleep cancelled */ diff --git a/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineTableView.swift b/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineTableView.swift index bda75862..da137c2e 100644 --- a/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineTableView.swift +++ b/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineTableView.swift @@ -104,7 +104,6 @@ extension TimelineItemRowInfo: Identifiable { class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveTimelineDiffDelegate { - let appState: AppState let windowState: WindowState private var actionTasks: [UUID: Task] = [:] @@ -156,10 +155,9 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT private(set) var timelineItems: [TimelineItemRowInfo] = [] init( - appState: AppState, windowState: WindowState, timeline: LiveTimeline, + windowState: WindowState, timeline: LiveTimeline, composer: ChatComposerState ) { - self.appState = appState self.windowState = windowState self.timeline = timeline self.composer = composer @@ -266,7 +264,7 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT } else { let view = MessageProfileRowView() view.initialize( - imageLoader: appState.matrixClient, + imageLoader: windowState.matrixClient, focusUser: { [weak self] in self?.windowState.focusUser(userId: $0) }) @@ -338,12 +336,12 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT onThreadClick: { [weak self] in self?.windowState.focusThread(rootEventId: event.eventOrTransactionId.id) }, - ownUserId: try? self.appState.matrixClient?.client.userId(), + ownUserId: try? self.windowState.matrixClient?.client.userId(), onReactionClick: { [weak self] key in self?.toggleReaction(key, for: event) }, roomMembers: self.timeline.room.members, - matrixClient: self.appState.matrixClient, + matrixClient: self.windowState.matrixClient, handleMatrixUri: { [weak self] matrixUri in guard let self else { return false } self.handleMatrixUri(matrixUri) @@ -412,7 +410,7 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT listenForRecentReactions() listenForRoomInfo() listenForTimelinePagination() - if let recentReactions = appState.matrixClient?.recentReactions { + if let recentReactions = windowState.matrixClient?.recentReactions { startActionTask { _ = await recentReactions.refresh() } @@ -549,7 +547,7 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT } private func listenForRecentReactions() { - guard let recentReactions = appState.matrixClient?.recentReactions else { return } + guard let recentReactions = windowState.matrixClient?.recentReactions else { return } let keys = withObservationTracking { recentReactions.isActive ? recentReactions.cachedKeys : [] } onChange: { [weak self] in @@ -701,7 +699,7 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT private func toggleReaction(_ key: String, for event: MatrixRustSDK.EventTimelineItem) { guard let sdkTimeline = timeline.timeline else { return } - let recents = appState.matrixClient?.recentReactions + let recents = windowState.matrixClient?.recentReactions startActionTask { do { if let recents { @@ -767,7 +765,7 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT case .showSource: return true case .downloadToFile(let index): - return appState.matrixClient != nil + return windowState.matrixClient != nil && MessageDownloadAttachment.attachments(for: event).indices.contains(index) } } @@ -806,7 +804,7 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT let attachments = MessageDownloadAttachment.attachments(for: event) guard attachments.indices.contains(index) else { return } startActionTask { [weak self] in - guard let self = self, let matrixClient = appState.matrixClient else { return } + guard let self = self, let matrixClient = windowState.matrixClient else { return } await MessageDownloadAttachment.downloadToFile( view: view, matrixClient: matrixClient, attachment: attachments[index]) } @@ -1375,7 +1373,7 @@ extension TimelineViewController: NSPopoverDelegate { let picker = ReactionPickerViewController( model: try ReactionPickerModel.loadBundled(), - recentReactions: appState.matrixClient?.recentReactions) + recentReactions: windowState.matrixClient?.recentReactions) let popover = NSPopover() popover.behavior = .transient popover.contentViewController = picker @@ -1622,7 +1620,7 @@ extension TimelineViewController { let state = MessageEditState(id: event.eventOrTransactionId, text: text) state.mentionCandidateProvider = { [weak room = timeline.room] in room?.members ?? [] } - state.imageLoader = appState.matrixClient + state.imageLoader = windowState.matrixClient state.onChange = { [weak self, weak state] in guard let self, let state, self.messageEdit === state, let row = self.rowForEventId(id: state.id) diff --git a/Sources/MactrixApp/Views/Inspector/InspectorScreen.swift b/Sources/MactrixApp/Views/Inspector/InspectorScreen.swift index 878a0baf..c3c86dd4 100644 --- a/Sources/MactrixApp/Views/Inspector/InspectorScreen.swift +++ b/Sources/MactrixApp/Views/Inspector/InspectorScreen.swift @@ -6,7 +6,6 @@ import OSLog import SwiftUI struct InspectorScreen: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState func onSelectUser(user: MatrixRustSDK.RoomMember) { @@ -38,7 +37,7 @@ struct InspectorScreen: View { case .joinedRoom(let timeline): MactrixUI.RoomInspectorView( room: timeline.room, members: timeline.room.members, roomInfo: timeline.room.roomInfo, - imageLoader: appState.matrixClient, onSelectUser: onSelectUser, + imageLoader: windowState.matrixClient, onSelectUser: onSelectUser, inspectorVisible: $windowState.inspectorVisible) case .none, .newRoom, .previewRoom, .loadMatrixUrl(_), .loadingRoom, .user(profile: _): Text("No room selected") diff --git a/Sources/MactrixApp/Views/Inspector/InspectorUserInfo.swift b/Sources/MactrixApp/Views/Inspector/InspectorUserInfo.swift index 4b791b91..dbff01d6 100644 --- a/Sources/MactrixApp/Views/Inspector/InspectorUserInfo.swift +++ b/Sources/MactrixApp/Views/Inspector/InspectorUserInfo.swift @@ -5,7 +5,6 @@ import OSLog import SwiftUI struct InspectorUserInfo: View { - @Environment(AppState.self) private var appState @Environment(WindowState.self) private var windowState let userId: String @@ -13,7 +12,7 @@ struct InspectorUserInfo: View { @State private var profile: MatrixRustSDK.UserProfile? var isUserIgnored: Bool { - appState.matrixClient?.ignoredUserIds.contains(userId) == true + windowState.matrixClient?.ignoredUserIds.contains(userId) == true } @ViewBuilder @@ -22,10 +21,10 @@ struct InspectorUserInfo: View { MactrixUI.UserProfileView( profile: profile, isUserIgnored: isUserIgnored, - actions: appState.matrixClient?.userProfileActions( + actions: windowState.matrixClient?.userProfileActions( forUserId: userId, windowState: windowState), timelineActions: nil, - imageLoader: appState.matrixClient + imageLoader: windowState.matrixClient ) } else { MactrixUI.UserProfileView( @@ -33,7 +32,7 @@ struct InspectorUserInfo: View { isUserIgnored: isUserIgnored, actions: nil, timelineActions: nil, - imageLoader: appState.matrixClient + imageLoader: windowState.matrixClient ) .redacted(reason: .placeholder) } @@ -42,7 +41,7 @@ struct InspectorUserInfo: View { var body: some View { content .task(id: userId) { - guard let matrixClient = appState.matrixClient else { return } + guard let matrixClient = windowState.matrixClient else { return } do { profile = try await matrixClient.client.getProfile(userId: userId) diff --git a/Sources/MactrixApp/Views/LoadDestinationScreen.swift b/Sources/MactrixApp/Views/LoadDestinationScreen.swift index 041bd23b..bd4ff0a3 100644 --- a/Sources/MactrixApp/Views/LoadDestinationScreen.swift +++ b/Sources/MactrixApp/Views/LoadDestinationScreen.swift @@ -5,7 +5,6 @@ import SwiftUI import Utils struct LoadDestinationScreen: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState let screen: SelectedScreen @@ -51,7 +50,7 @@ struct LoadDestinationScreen: View { } .task( id: LoadRequest( - attempt: retryAttempt, client: appState.matrixClient.map { ObjectIdentifier($0) }) + attempt: retryAttempt, client: windowState.matrixClient.map { ObjectIdentifier($0) }) ) { await load() } @@ -61,7 +60,7 @@ struct LoadDestinationScreen: View { private func load() async { guard windowState.selectedScreen === screen, !Task.isCancelled else { return } errorMessage = nil - guard let matrixClient = appState.matrixClient else { + guard let matrixClient = windowState.matrixClient else { errorMessage = String(localized: "Sign in to continue.") return } @@ -69,13 +68,13 @@ struct LoadDestinationScreen: View { do { let destination = try await resolve(using: matrixClient) try Task.checkCancellation() - guard windowState.selectedScreen === screen, appState.matrixClient === matrixClient else { + guard windowState.selectedScreen === screen, windowState.matrixClient === matrixClient else { return } windowState.selectedScreen = destination } catch { guard !Task.isCancelled, windowState.selectedScreen === screen, - appState.matrixClient === matrixClient + windowState.matrixClient === matrixClient else { return } Logger.viewCycle.error("Failed to open destination: \(error)") errorMessage = error.localizedDescription @@ -112,7 +111,7 @@ struct LoadDestinationScreen: View { } try Task.checkCancellation() - guard windowState.selectedScreen === screen, appState.matrixClient === matrixClient else { + guard windowState.selectedScreen === screen, windowState.matrixClient === matrixClient else { throw CancellationError() } diff --git a/Sources/MactrixApp/Views/MatrixImageView.swift b/Sources/MactrixApp/Views/MatrixImageView.swift index a8637f03..f7efd472 100644 --- a/Sources/MactrixApp/Views/MatrixImageView.swift +++ b/Sources/MactrixApp/Views/MatrixImageView.swift @@ -7,7 +7,7 @@ struct MatrixImageView: View { let mediaSource: MediaSource? let mimeType: String? - @Environment(AppState.self) private var appState + @Environment(WindowState.self) private var windowState @State private var image: Image? = nil @State private var errorMessage: String? = nil @@ -44,7 +44,7 @@ struct MatrixImageView: View { content .task(id: mediaSource?.url(), priority: .utility) { guard image == nil else { return } - guard let matrixClient = appState.matrixClient else { + guard let matrixClient = windowState.matrixClient else { errorMessage = String(localized: "Matrix client not available") return } diff --git a/Sources/MactrixApp/Views/Search/SearchInspectorView.swift b/Sources/MactrixApp/Views/Search/SearchInspectorView.swift index 4699df3d..7ff24d54 100644 --- a/Sources/MactrixApp/Views/Search/SearchInspectorView.swift +++ b/Sources/MactrixApp/Views/Search/SearchInspectorView.swift @@ -5,7 +5,6 @@ import OSLog import SwiftUI struct SearchResolvedRoomInspectorView: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState @State private var roomPreview: MatrixRustSDK.RoomPreview? @@ -15,7 +14,7 @@ struct SearchResolvedRoomInspectorView: View { var roomActions: RoomPreviewActions? { guard let preview = roomPreview else { return nil } - return appState.matrixClient?.roomPreviewActions( + return windowState.matrixClient?.roomPreviewActions( forRoomWithId: preview.info().roomId, windowState: windowState, routingVia: resolvedRoom.servers) } @@ -25,13 +24,13 @@ struct SearchResolvedRoomInspectorView: View { if let roomPreview { MactrixUI.RoomPreviewView( preview: roomPreview.info(), - imageLoader: appState.matrixClient, + imageLoader: windowState.matrixClient, actions: roomActions ) } else { MactrixUI.RoomPreviewView( preview: MockRoomPreviewInfo(), - imageLoader: appState.matrixClient, + imageLoader: windowState.matrixClient, actions: roomActions ) .redacted(reason: .placeholder) @@ -39,7 +38,7 @@ struct SearchResolvedRoomInspectorView: View { } .task(id: alias, priority: .utility) { do { - guard let matrixClient = appState.matrixClient else { return } + guard let matrixClient = windowState.matrixClient else { return } let preview = try await matrixClient.client.getRoomPreviewFromRoomId( roomId: resolvedRoom.roomId, viaServers: matrixClient.routingServers(hints: resolvedRoom.servers)) @@ -52,7 +51,6 @@ struct SearchResolvedRoomInspectorView: View { } struct SearchInspectorView: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState @ViewBuilder @@ -71,18 +69,18 @@ struct SearchInspectorView: View { case .resolvedRoomId(let roomPreview): MactrixUI.RoomPreviewView( preview: roomPreview.info(), - imageLoader: appState.matrixClient, - actions: appState.matrixClient?.roomPreviewActions( + imageLoader: windowState.matrixClient, + actions: windowState.matrixClient?.roomPreviewActions( forRoomWithId: roomPreview.info().roomId, windowState: windowState) ) case .resolvedUser(profile: let userProfile): MactrixUI.UserProfileView( profile: userProfile, - isUserIgnored: appState.matrixClient?.isUserIgnored(userProfile.userId) == true, - actions: appState.matrixClient?.userProfileActions( + isUserIgnored: windowState.matrixClient?.isUserIgnored(userProfile.userId) == true, + actions: windowState.matrixClient?.userProfileActions( forUserId: userProfile.userId, windowState: windowState), timelineActions: nil, - imageLoader: appState.matrixClient + imageLoader: windowState.matrixClient ) case nil: ContentUnavailableView("Select a search term", systemImage: "magnifyingglass") diff --git a/Sources/MactrixApp/Views/Search/SearchMessagesInspectorView.swift b/Sources/MactrixApp/Views/Search/SearchMessagesInspectorView.swift index 6ba81007..4a6c40a5 100644 --- a/Sources/MactrixApp/Views/Search/SearchMessagesInspectorView.swift +++ b/Sources/MactrixApp/Views/Search/SearchMessagesInspectorView.swift @@ -4,22 +4,24 @@ import OSLog import SwiftUI struct SearchMessagesInspectorView: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState @State var selectedMessage: String? = nil @State var searchService: LiveSearchService? = nil + /// The account `searchService` searches. + @State private var searchServiceStoreID: String? = nil @ViewBuilder var content: some View { let results = searchService?.results ?? [] let query = windowState.searchQuery + let matrixClient = windowState.matrixClient ForEach(results) { searchResult in let paginationQuery = searchResult.id == results.last?.id && searchService?.activeQuery == query ? query : nil - SearchMessageRowView(result: searchResult, query: query, matrixClient: appState.matrixClient) + SearchMessageRowView(result: searchResult, query: query, matrixClient: matrixClient) .task(id: paginationQuery) { guard let paginationQuery, paginationQuery == windowState.searchQuery else { return } do { @@ -59,16 +61,18 @@ struct SearchMessagesInspectorView: View { .task(id: query) { do { try await Task.sleep(for: .milliseconds(500)) - guard let matrixClient = appState.matrixClient else { return } + guard let matrixClient = windowState.matrixClient else { return } + // The window may have switched accounts since the service was made. let searchService: LiveSearchService - if let s = self.searchService { + if let s = self.searchService, searchServiceStoreID == matrixClient.storeID { searchService = s } else { searchService = await LiveSearchService( searchService: matrixClient.client.searchService()) try Task.checkCancellation() self.searchService = searchService + searchServiceStoreID = matrixClient.storeID } try await searchService.search(query: query) diff --git a/Sources/MactrixApp/Views/Search/SearchRoomInspectorView.swift b/Sources/MactrixApp/Views/Search/SearchRoomInspectorView.swift index fdab1e25..781b8880 100644 --- a/Sources/MactrixApp/Views/Search/SearchRoomInspectorView.swift +++ b/Sources/MactrixApp/Views/Search/SearchRoomInspectorView.swift @@ -5,7 +5,6 @@ import OSLog import SwiftUI struct SearchRoomInspectorView: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState @State var searching: Bool = true @@ -46,7 +45,7 @@ struct SearchRoomInspectorView: View { } .task(id: windowState.searchQuery) { do { - guard let matrixClient = appState.matrixClient else { return } + guard let matrixClient = windowState.matrixClient else { return } let roomSearch: LiveRoomSearch if let rs = self.roomSearch { diff --git a/Sources/MactrixApp/Views/Search/SearchUserInspectorView.swift b/Sources/MactrixApp/Views/Search/SearchUserInspectorView.swift index 2f88c305..422f286b 100644 --- a/Sources/MactrixApp/Views/Search/SearchUserInspectorView.swift +++ b/Sources/MactrixApp/Views/Search/SearchUserInspectorView.swift @@ -4,7 +4,6 @@ import OSLog import SwiftUI struct SearchUserInspectorView: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState @State var searchedUsers: [UserProfile] = [] @@ -22,7 +21,7 @@ struct SearchUserInspectorView: View { }.redacted(reason: .placeholder) } else { ForEach(searchedUsers) { user in - MactrixUI.UserProfileRow(profile: user, imageLoader: appState.matrixClient) + MactrixUI.UserProfileRow(profile: user, imageLoader: windowState.matrixClient) } } } @@ -34,7 +33,7 @@ struct SearchUserInspectorView: View { } .task(id: windowState.searchQuery) { do { - guard let matrixClient = appState.matrixClient else { return } + guard let matrixClient = windowState.matrixClient else { return } guard !windowState.searchQuery.isEmpty else { searchedUsers = [] return diff --git a/Sources/MactrixApp/Views/Search/SearchViewModifier.swift b/Sources/MactrixApp/Views/Search/SearchViewModifier.swift index a40f7e1b..1ba290dc 100644 --- a/Sources/MactrixApp/Views/Search/SearchViewModifier.swift +++ b/Sources/MactrixApp/Views/Search/SearchViewModifier.swift @@ -4,7 +4,6 @@ import SwiftUI import Utils struct SearchViewModifier: ViewModifier { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState func body(content: Content) -> some View { @@ -129,7 +128,7 @@ struct SearchViewModifier: ViewModifier { }() do { - guard let matrixClient = appState.matrixClient else { return } + guard let matrixClient = windowState.matrixClient else { return } try await Task.sleep(for: .milliseconds(300)) let roomAliasRegex = /\#[^:]+\:[^\s]*/ diff --git a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift index f7a1880e..4c33dc72 100644 --- a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift +++ b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift @@ -68,14 +68,14 @@ struct AccountSwitcher: View { isPresented.toggle() } label: { HStack(spacing: 6) { - if let active = appState.matrixClient { + if let active = windowState.matrixClient { AccountLabel(account: active) } else { Text("No Account") .font(.body.weight(.semibold)) } Spacer(minLength: 0) - if appState.matrixClient?.needsAttention == true { + if windowState.matrixClient?.needsAttention == true { Image(systemName: "exclamationmark.circle.fill") .foregroundStyle(.orange) } @@ -102,7 +102,7 @@ struct AccountSwitcher: View { popoverContent } // Verification requests time out, so don't leave one waiting behind a closed popover. - .onChange(of: appState.matrixClient?.sessionVerificationRequest?.flowId) { _, flowID in + .onChange(of: windowState.matrixClient?.sessionVerificationRequest?.flowId) { _, flowID in if flowID != nil { isPresented = true } } .confirmationDialog( @@ -121,7 +121,7 @@ struct AccountSwitcher: View { } private var accessibilityLabel: String { - guard let active = appState.matrixClient else { return String(localized: "Switch account") } + guard let active = windowState.matrixClient else { return String(localized: "Switch account") } var label = String(localized: "Switch account, current: \(active.accountMenuTitle)") if active.syncState != .running { label = String(localized: "\(label), sync: \(active.syncState.label)") @@ -136,7 +136,7 @@ struct AccountSwitcher: View { private var popoverContent: some View { VStack(alignment: .leading, spacing: 2) { - if let active = appState.matrixClient, active.hasStatus { + if let active = windowState.matrixClient, active.hasStatus { AccountStatusSection(account: active) { isPresented = false } Divider() .padding(.vertical, 4) @@ -157,7 +157,7 @@ struct AccountSwitcher: View { windowState.loginSheet = .addAccount } - if let active = appState.matrixClient { + if let active = windowState.matrixClient { PopoverActionRow( title: String(localized: "Sign Out of \(active.accountName)…"), systemImage: "rectangle.portrait.and.arrow.right" diff --git a/Sources/MactrixApp/Views/Sidebar/SidebarGroupsList.swift b/Sources/MactrixApp/Views/Sidebar/SidebarGroupsList.swift index cca53bfc..5a7df241 100644 --- a/Sources/MactrixApp/Views/Sidebar/SidebarGroupsList.swift +++ b/Sources/MactrixApp/Views/Sidebar/SidebarGroupsList.swift @@ -4,15 +4,15 @@ import MatrixRustSDK import SwiftUI struct SidebarGroupsList: View { - @Environment(AppState.self) var appState + @Environment(WindowState.self) var windowState var spaces: [SidebarSpaceRoom] { - appState.matrixClient?.spaceService.spaceRooms ?? [] + windowState.matrixClient?.spaceService.spaceRooms ?? [] } var unreadRoomIDs: Set { Set( - (appState.matrixClient?.rooms ?? []).compactMap { room in + (windowState.matrixClient?.rooms ?? []).compactMap { room in guard !room.room.isSpace(), let info = room.roomInfo else { return nil } let isUnread = info.isMarkedUnread || info.numUnreadNotifications > 0 || info.numUnreadMentions > 0 @@ -23,7 +23,7 @@ struct SidebarGroupsList: View { var body: some View { let unreadIDs = unreadRoomIDs - let service = appState.matrixClient?.spaceService + let service = windowState.matrixClient?.spaceService let homeNotifications = unreadIDs.subtracting(service?.roomsWithJoinedSpaceParents ?? []).count let spaceNotifications = Dictionary( (service?.spaceFilters ?? []) @@ -47,7 +47,7 @@ struct SidebarGroupsList: View { ) { AvatarImage( userID: space.id, kind: .room, displayName: space.spaceRoom.displayName, - avatarUrl: space.spaceRoom.avatarUrl, imageLoader: appState.matrixClient) + avatarUrl: space.spaceRoom.avatarUrl, imageLoader: windowState.matrixClient) } .contextMenu { SpaceContextMenu(space: space) diff --git a/Sources/MactrixApp/Views/Sidebar/SidebarView.swift b/Sources/MactrixApp/Views/Sidebar/SidebarView.swift index ac677e61..c2168fba 100644 --- a/Sources/MactrixApp/Views/Sidebar/SidebarView.swift +++ b/Sources/MactrixApp/Views/Sidebar/SidebarView.swift @@ -5,7 +5,6 @@ import MatrixRustSDK import SwiftUI struct SidebarView: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState @State private var members: [MatrixRustSDK.RoomMember] = [] @@ -14,8 +13,8 @@ struct SidebarView: View { var visibleRooms: [SidebarRoom] { // filter out rooms whose room info hasn't loaded yet, to avoid flickering - let joinedRooms = (appState.matrixClient?.rooms ?? []).filter { $0.roomInfo != nil } - let spaceService = appState.matrixClient?.spaceService + let joinedRooms = (windowState.matrixClient?.rooms ?? []).filter { $0.roomInfo != nil } + let spaceService = windowState.matrixClient?.spaceService if let selectedSpaceId = windowState.selectedSpaceId { let roomIDs = Set( @@ -59,7 +58,7 @@ struct SidebarView: View { } var spaces: [SidebarSpaceRoom] { - appState.matrixClient?.spaceService.spaceRooms ?? [] + windowState.matrixClient?.spaceService.spaceRooms ?? [] } var content: some View { @@ -122,7 +121,7 @@ struct SidebarView: View { title: title(for: room, fallback: String(localized: "Unknown room")), avatarUrl: room.room.avatarUrl(), roomInfo: room.roomInfo, - imageLoader: appState.matrixClient, + imageLoader: windowState.matrixClient, joinRoom: nil ) .contextMenu { @@ -138,7 +137,7 @@ struct SidebarView: View { title: title(for: room, fallback: String(localized: "Unknown user")), avatarUrl: room.room.avatarUrl(), roomInfo: room.roomInfo, - imageLoader: appState.matrixClient, + imageLoader: windowState.matrixClient, joinRoom: nil ) .contextMenu { @@ -153,7 +152,7 @@ struct SidebarView: View { title: room.room.displayName() ?? String(localized: "Unknown room"), avatarUrl: room.room.avatarUrl(), roomInfo: room.roomInfo, - imageLoader: appState.matrixClient, + imageLoader: windowState.matrixClient, joinRoom: nil ) .contextMenu { diff --git a/Sources/MactrixApp/Views/Sidebar/SpaceContextMenu.swift b/Sources/MactrixApp/Views/Sidebar/SpaceContextMenu.swift index c4aa038f..4844ca22 100644 --- a/Sources/MactrixApp/Views/Sidebar/SpaceContextMenu.swift +++ b/Sources/MactrixApp/Views/Sidebar/SpaceContextMenu.swift @@ -4,7 +4,6 @@ import OSLog import SwiftUI struct SpaceContextMenu: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState let space: SidebarSpaceRoom @@ -14,7 +13,8 @@ struct SpaceContextMenu: View { Button { Task { do { - guard let room = try appState.matrixClient?.client.getRoom(roomId: space.spaceRoom.roomId) + guard + let room = try windowState.matrixClient?.client.getRoom(roomId: space.spaceRoom.roomId) else { Logger.viewCycle.error("unable to copy space room link: could not get room") return @@ -35,7 +35,8 @@ struct SpaceContextMenu: View { Button { Task { do { - guard let room = try appState.matrixClient?.client.getRoom(roomId: space.spaceRoom.roomId) + guard + let room = try windowState.matrixClient?.client.getRoom(roomId: space.spaceRoom.roomId) else { Logger.viewCycle.error("unable to leave space: could not get room") return diff --git a/Sources/MactrixApp/Views/Sidebar/SpaceDisclosureGroup.swift b/Sources/MactrixApp/Views/Sidebar/SpaceDisclosureGroup.swift index 49ee6b78..4db3a1c0 100644 --- a/Sources/MactrixApp/Views/Sidebar/SpaceDisclosureGroup.swift +++ b/Sources/MactrixApp/Views/Sidebar/SpaceDisclosureGroup.swift @@ -5,7 +5,6 @@ import OSLog import SwiftUI struct SpaceDisclosureGroup: View { - @Environment(AppState.self) var appState @Environment(WindowState.self) var windowState @State var space: SidebarSpaceRoom @@ -52,10 +51,10 @@ struct SpaceDisclosureGroup: View { } var joinRoom: (() async throws -> Void)? { - if appState.matrixClient?.rooms.contains(where: { $0.room.id() == space.id }) == false { + if windowState.matrixClient?.rooms.contains(where: { $0.room.id() == space.id }) == false { return { Logger.viewCycle.error("Joining room: \(space.id)") - guard let matrixClient = appState.matrixClient else { return } + guard let matrixClient = windowState.matrixClient else { return } let sourceScreen = windowState.selectedScreen let room = try await matrixClient.client.joinRoomById(roomId: space.id) try Task.checkCancellation() @@ -69,7 +68,7 @@ struct SpaceDisclosureGroup: View { } var joinedRoom: SidebarRoom? { - return appState.matrixClient?.rooms.first(where: { $0.room.id() == space.id }) + return windowState.matrixClient?.rooms.first(where: { $0.room.id() == space.id }) } @ViewBuilder @@ -79,7 +78,7 @@ struct SpaceDisclosureGroup: View { title: space.spaceRoom.displayName, avatarUrl: space.spaceRoom.avatarUrl, roomInfo: joinedRoom.roomInfo, - imageLoader: appState.matrixClient, + imageLoader: windowState.matrixClient, joinRoom: nil ) } else { @@ -87,7 +86,7 @@ struct SpaceDisclosureGroup: View { title: space.spaceRoom.displayName, avatarUrl: space.spaceRoom.avatarUrl, roomInfo: nil, - imageLoader: appState.matrixClient, + imageLoader: windowState.matrixClient, joinRoom: joinRoom ) } diff --git a/Tests/MactrixAppTests/WindowStateAccountTests.swift b/Tests/MactrixAppTests/WindowStateAccountTests.swift index 5667c2ed..672ffa24 100644 --- a/Tests/MactrixAppTests/WindowStateAccountTests.swift +++ b/Tests/MactrixAppTests/WindowStateAccountTests.swift @@ -72,7 +72,7 @@ struct WindowStateAccountTests { windowState.showAccount("A", knownAccountIDs: ["A"]) windowState.selectedRoomId = "!a:example.org" - windowState.showAccount(nil, knownAccountIDs: []) + windowState.showAccount(nil as String?, knownAccountIDs: []) #expect(windowState.accountID == nil) #expect(windowState.selectedRoomId == nil) From 98b7e59831f2379c187ce1485abf53f49fb8c608 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Thu, 26 Nov 2026 16:01:06 -0500 Subject: [PATCH 19/35] Give each window its own account MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Picking an account in the switcher, the Account menu or with ⌃⌘1–9 now switches only the focused window, so windows can show different accounts. A restored window reopens on the account it showed; a new window (⌘N, ⌘T, or the Dock icon) opens on the most recently focused window's account, which replaces the app-wide active account in user defaults under the same key. If a window's account is signed out and removed, the window falls back to the last focused window's account, then to the first account. Notification banners stay hidden only for the focused window's account, and Settings shows that account. --- Mactrix/MactrixApp.swift | 5 +- Sources/MactrixApp/Commands.swift | 8 +- Sources/MactrixApp/MainView.swift | 18 ++- Sources/MactrixApp/Models/AppState.swift | 142 ++++++++++++++---- .../Views/Settings/AccountSettingsView.swift | 4 +- .../RecoveryKeyVerificationSheet.swift | 4 +- .../Views/Settings/SessionsSettingsView.swift | 2 +- .../Views/Sidebar/AccountSwitcher.swift | 4 +- .../MactrixApp/Views/WelcomeSheetView.swift | 5 +- Sources/MatrixIntegration/AccountStore.swift | 19 +-- Tests/MactrixAppTests/AccountStoreTests.swift | 8 +- .../WindowAccountFallbackTests.swift | 36 +++++ 12 files changed, 191 insertions(+), 64 deletions(-) create mode 100644 Tests/MactrixAppTests/WindowAccountFallbackTests.swift diff --git a/Mactrix/MactrixApp.swift b/Mactrix/MactrixApp.swift index 4605d00f..f224b653 100644 --- a/Mactrix/MactrixApp.swift +++ b/Mactrix/MactrixApp.swift @@ -17,7 +17,10 @@ struct MactrixApp: App { .commands { AppCommands(appState: appState) } - .onChange(of: windowState == nil, focusNotification) + .onChange(of: windowState.map(ObjectIdentifier.init)) { + if let windowState { appState.focus(windowState) } + focusNotification() + } .onChange(of: appState.notificationRouter.pendingTarget, focusNotification) .onChange(of: appState.restoration, focusNotification) diff --git a/Sources/MactrixApp/Commands.swift b/Sources/MactrixApp/Commands.swift index 3cd722f6..36eb4705 100644 --- a/Sources/MactrixApp/Commands.swift +++ b/Sources/MactrixApp/Commands.swift @@ -36,14 +36,16 @@ public struct AppCommands: Commands { ForEach(Array(appState.accounts.enumerated()), id: \.element.storeID) { index, account in Toggle( isOn: Binding( - get: { appState.activeAccountID == account.storeID }, - set: { if $0 { appState.activate(account) } }) + get: { windowState?.accountID == account.storeID }, + set: { if $0, let windowState { appState.show(account, in: windowState) } }) ) { Text(account.accountMenuTitle) } + .disabled(windowState == nil) .keyboardShortcut( index < 9 - ? KeyboardShortcut(KeyEquivalent(Character("\(index + 1)")), modifiers: [.command, .control]) + ? KeyboardShortcut( + KeyEquivalent(Character("\(index + 1)")), modifiers: [.command, .control]) : nil) } diff --git a/Sources/MactrixApp/MainView.swift b/Sources/MactrixApp/MainView.swift index 530dfad3..972f011f 100644 --- a/Sources/MactrixApp/MainView.swift +++ b/Sources/MactrixApp/MainView.swift @@ -103,6 +103,7 @@ public struct MainView: View { .task { await attemptLoadUserSession() } .sheet(item: $windowState.loginSheet, onDismiss: onLoginModalDismiss) { request in WelcomeSheetView(request: request) + .environment(windowState) } .sheet( isPresented: verificationSheetPresented, @@ -139,14 +140,15 @@ public struct MainView: View { } } ) - .onChange(of: appState.restoration, initial: true) { _, restoration in - guard case .restored(let activeAccountID) = restoration else { return } - windowState.showAccount( - appState.matrixClient, knownAccountIDs: Set(appState.accounts.map(\.storeID))) - if activeAccountID == nil { - Logger.viewCycle.info("No signed in accounts, present welcome sheet") - windowState.loginSheet = .firstAccount - } + // Scene storage may swap in the restored window state after the first render. + .onChange(of: ObjectIdentifier(windowState), initial: true) { + appState.register(windowState) + } + .onChange(of: appState.restoration == .restored && appState.accounts.isEmpty, initial: true) { + _, signedOut in + guard signedOut else { return } + Logger.viewCycle.info("No signed in accounts, present welcome sheet") + windowState.loginSheet = .firstAccount } .onOpenURL { url in Logger.viewCycle.debug("onOpenUrl \(url)") diff --git a/Sources/MactrixApp/Models/AppState.swift b/Sources/MactrixApp/Models/AppState.swift index f5e40b8a..70ee5050 100644 --- a/Sources/MactrixApp/Models/AppState.swift +++ b/Sources/MactrixApp/Models/AppState.swift @@ -4,15 +4,16 @@ import MatrixIntegration import OSLog import Observation -/// The signed-in accounts and which one is shown. +/// The signed-in accounts, and the windows showing them. /// -/// Every account syncs in the background; the UI shows the active one, exposed as `matrixClient`. +/// Every account syncs in the background. Each window shows one account of its own choosing, +/// holding a weak reference to its client. @MainActor @Observable public final class AppState { public enum Restoration: Equatable { case pending - /// Stored accounts have been restored; carries the active account's `storeID`. - case restored(activeAccountID: String?) + /// Stored accounts have been restored. + case restored } public enum AccountError: LocalizedError { @@ -30,8 +31,11 @@ public final class AppState { public private(set) var accounts: [MatrixClient] = [] { didSet { updateNotificationLabels() } } - public private(set) var activeAccountID: String? + /// The account of the most recently focused window, which new windows open on. + public private(set) var lastFocusedAccountID: String? private var hasRestored = false + /// Open windows, most recently focused first. + @ObservationIgnored private var windows: [WeakWindowState] = [] @ObservationIgnored private let accountStore: AccountStore @ObservationIgnored private var restoreTask: Task? @@ -47,21 +51,23 @@ public final class AppState { observeDockBadge() } - /// The active account. - public var matrixClient: MatrixClient? { - accounts.first { $0.storeID == activeAccountID } + /// The account of the most recently focused window, which the Settings window shows. + public var lastFocusedAccount: MatrixClient? { + accounts.first { $0.storeID == lastFocusedAccountID } } - /// The number of unread rooms across accounts other than the active one. + /// The number of unread rooms across accounts other than the last focused window's. public var inactiveUnreadRoomCount: Int { accounts.reduce(0) { count, account in - guard account.storeID != activeAccountID, !account.authenticationFailed else { return count } + guard account.storeID != lastFocusedAccountID, !account.authenticationFailed else { + return count + } return count + account.unreadRoomCount } } public var restoration: Restoration { - hasRestored ? .restored(activeAccountID: activeAccountID) : .pending + hasRestored ? .restored : .pending } /// Restores stored accounts and starts syncing them. Runs once; later calls wait for the first. @@ -78,59 +84,128 @@ public final class AppState { private func performRestore() async { let clients = await MatrixClient.restoreAll(accountStore: accountStore) accounts = clients - let storedActive = accountStore.activeStoreID + setLastFocusedAccount(accountStore.lastFocusedStoreID) hasRestored = true - activate(clients.first { $0.storeID == storedActive } ?? clients.first) + for window in openWindows { + attach(window) + } for client in clients { startSync(client) } } - /// Adds a newly signed-in account and makes it active. + /// Adds a newly signed-in account and shows it in `windowState`. /// /// Signing in to an account that is already listed is rejected: the new session is signed out /// again so it doesn't linger as an extra device. If the listed account was signed out by the - /// server, the new session replaces it instead. - public func add(_ client: MatrixClient) async throws { + /// server, the new session replaces it, in every window showing it. + public func add(_ client: MatrixClient, in windowState: WindowState) async throws { if let existing = accounts.first(where: { $0.userID == client.userID }) { if existing.authenticationFailed { let index = accounts.firstIndex { $0 === existing }! + let replacedWindows = openWindows.filter { $0.accountID == existing.storeID } await discard(existing) accounts.insert(client, at: min(index, accounts.count)) accountStore.setOrder(accounts.map(\.storeID)) + for window in replacedWindows { + show(client, in: window) + } } else { Logger.matrixClient.info("Rejecting duplicate sign-in for store \(client.storeID)") await discard(client) - activate(existing) + show(existing, in: windowState) throw AccountError.alreadySignedIn(userID: client.userID) } } else { accounts.append(client) } - activate(client) + show(client, in: windowState) startSync(client) } - public func activate(_ client: MatrixClient?) { - activeAccountID = client?.storeID - accountStore.activeStoreID = client?.storeID - notificationRouter.activeAccountID = client?.storeID + /// Shows `account` in `windowState`. + public func show(_ account: MatrixClient, in windowState: WindowState) { + windowState.showAccount(account, knownAccountIDs: Set(accounts.map(\.storeID))) + if windowState === openWindows.first { + setLastFocusedAccount(account.storeID) + } } - /// Signs out of `client` and removes it, activating another account if it was active. + /// Signs out of `client` and removes it, switching the windows that showed it to another account. public func remove(_ client: MatrixClient) async { accounts.removeAll { $0 === client } // Switch before signing out, which waits for the server. - if client.storeID == activeAccountID { - activate(accounts.first) + if lastFocusedAccountID == client.storeID { + setLastFocusedAccount(nil) + } + for window in openWindows where window.accountID == client.storeID { + attach(window) } await discard(client) } - /// Signs out of the active account. + /// Signs out of the account the Settings window shows. public func reset() async throws { - guard let matrixClient else { return } - await remove(matrixClient) + guard let lastFocusedAccount else { return } + await remove(lastFocusedAccount) + } + + // MARK: Windows + + /// Records that `windowState` is open, and shows an account in it once accounts are restored. + public func register(_ windowState: WindowState) { + windows.removeAll { $0.value == nil || $0.value === windowState } + windows.append(WeakWindowState(windowState)) + if hasRestored { + attach(windowState) + } + } + + /// Records that `windowState` is the focused window. + public func focus(_ windowState: WindowState) { + windows.removeAll { $0.value == nil || $0.value === windowState } + windows.insert(WeakWindowState(windowState), at: 0) + if let accountID = windowState.accountID { + setLastFocusedAccount(accountID) + } + } + + /// Open windows, most recently focused first. + var openWindows: [WindowState] { + windows.compactMap(\.value) + } + + /// Connects `windowState` to its account's client, or to a fallback if its account is gone. + /// + /// A window keeps its own account if it still exists. Otherwise it shows the last focused + /// window's account, then the first account. + func attach(_ windowState: WindowState) { + let account = Self.accountToShow( + windowAccountID: windowState.accountID, lastFocusedAccountID: lastFocusedAccountID, + accountIDs: accounts.map(\.storeID) + ).flatMap { id in accounts.first { $0.storeID == id } } + guard account !== windowState.matrixClient || account?.storeID != windowState.accountID else { + return + } + windowState.showAccount(account, knownAccountIDs: Set(accounts.map(\.storeID))) + } + + /// Which account a window shows, given the account it showed before. + static func accountToShow( + windowAccountID: String?, lastFocusedAccountID: String?, accountIDs: [String] + ) -> String? { + [windowAccountID, lastFocusedAccountID].lazy.compactMap { $0 } + .first { accountIDs.contains($0) } ?? accountIDs.first + } + + private func setLastFocusedAccount(_ storeID: String?) { + let storeID = + storeID.flatMap { id in accounts.contains { $0.storeID == id } ? id : nil } + ?? accounts.first?.storeID + lastFocusedAccountID = storeID + accountStore.lastFocusedStoreID = storeID + // Banners for the focused window's account would duplicate what is on screen. + notificationRouter.activeAccountID = storeID } private func discard(_ client: MatrixClient) async { @@ -153,9 +228,8 @@ public final class AppState { Logger.viewCycle.info("Ignoring notification from a removed account") return } - activate(account) // Switch the window now so the room below isn't treated as the previous account's. - windowState.showAccount(account, knownAccountIDs: Set(accounts.map(\.storeID))) + show(account, in: windowState) } windowState.selectedRoomId = target.roomId } @@ -193,3 +267,11 @@ public final class AppState { } } } + +private struct WeakWindowState { + weak var value: WindowState? + + init(_ value: WindowState) { + self.value = value + } +} diff --git a/Sources/MactrixApp/Views/Settings/AccountSettingsView.swift b/Sources/MactrixApp/Views/Settings/AccountSettingsView.swift index f1ed2a17..67833f8f 100644 --- a/Sources/MactrixApp/Views/Settings/AccountSettingsView.swift +++ b/Sources/MactrixApp/Views/Settings/AccountSettingsView.swift @@ -48,7 +48,7 @@ struct AccountSettingsView: View { @State private var displayName: String? = nil var body: some View { - if let matrixClient = appState.matrixClient { + if let matrixClient = appState.lastFocusedAccount { Form { Section { AccountLabel(account: matrixClient) @@ -115,7 +115,7 @@ struct AccountSettingsView: View { Button("Clear cache") { Task { do { - try await appState.matrixClient?.clearCache() + try await appState.lastFocusedAccount?.clearCache() } catch { Logger.viewCycle.error("Failed to clear cache: \(error)") } diff --git a/Sources/MactrixApp/Views/Settings/RecoveryKeyVerificationSheet.swift b/Sources/MactrixApp/Views/Settings/RecoveryKeyVerificationSheet.swift index 3dbbb9b6..450cc7d4 100644 --- a/Sources/MactrixApp/Views/Settings/RecoveryKeyVerificationSheet.swift +++ b/Sources/MactrixApp/Views/Settings/RecoveryKeyVerificationSheet.swift @@ -114,7 +114,7 @@ struct RecoveryKeyVerificationSheet: View { .frame(width: 440) .interactiveDismissDisabled(state.isVerifying) .onAppear { keyFieldFocused = true } - .onChange(of: appState.matrixClient.map { ObjectIdentifier($0) }) { + .onChange(of: appState.lastFocusedAccount.map { ObjectIdentifier($0) }) { dismiss() } .onDisappear { verificationTask?.cancel() } @@ -129,7 +129,7 @@ struct RecoveryKeyVerificationSheet: View { } private func verify() { - guard appState.matrixClient === matrixClient, + guard appState.lastFocusedAccount === matrixClient, verificationTask == nil, canVerify, !matrixClient.isRecoveringWithRecoveryKey else { return } diff --git a/Sources/MactrixApp/Views/Settings/SessionsSettingsView.swift b/Sources/MactrixApp/Views/Settings/SessionsSettingsView.swift index 5104fd13..9a07bc86 100644 --- a/Sources/MactrixApp/Views/Settings/SessionsSettingsView.swift +++ b/Sources/MactrixApp/Views/Settings/SessionsSettingsView.swift @@ -118,7 +118,7 @@ struct SessionsSettingsView: View { } var body: some View { - if let matrixClient = appState.matrixClient { + if let matrixClient = appState.lastFocusedAccount { Form { Section { AccountLabel(account: matrixClient) diff --git a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift index 4c33dc72..6888f711 100644 --- a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift +++ b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift @@ -143,8 +143,8 @@ struct AccountSwitcher: View { } ForEach(appState.accounts, id: \.storeID) { account in - AccountRow(account: account, isActive: appState.activeAccountID == account.storeID) { - appState.activate(account) + AccountRow(account: account, isActive: windowState.accountID == account.storeID) { + appState.show(account, in: windowState) isPresented = false } } diff --git a/Sources/MactrixApp/Views/WelcomeSheetView.swift b/Sources/MactrixApp/Views/WelcomeSheetView.swift index 4500906f..9bfd56eb 100644 --- a/Sources/MactrixApp/Views/WelcomeSheetView.swift +++ b/Sources/MactrixApp/Views/WelcomeSheetView.swift @@ -8,6 +8,7 @@ struct WelcomeSheetView: View { var request: LoginSheet = .firstAccount @Environment(AppState.self) private var appState + @Environment(WindowState.self) private var windowState @Environment(\.dismiss) private var dismiss @Environment(\.webAuthenticationSession) private var webAuthenticationSession @@ -72,7 +73,7 @@ struct WelcomeSheetView: View { do { let client = try await homeserverLogin.loginPassword( homeServer: homeserverField, username: usernameField, password: passwordField) - try await appState.add(client) + try await appState.add(client, in: windowState) dismiss() } catch { showError = error @@ -89,7 +90,7 @@ struct WelcomeSheetView: View { do { let client = try await homeserverLogin.loginOidc(webAuthSession: webAuthenticationSession) - try await appState.add(client) + try await appState.add(client, in: windowState) dismiss() } catch { showError = error diff --git a/Sources/MatrixIntegration/AccountStore.swift b/Sources/MatrixIntegration/AccountStore.swift index 6a7755c7..fffbd4c3 100644 --- a/Sources/MatrixIntegration/AccountStore.swift +++ b/Sources/MatrixIntegration/AccountStore.swift @@ -14,7 +14,8 @@ public struct AccountStore: Sendable { enum DefaultsKey { static let order = "accounts.order" - static let active = "accounts.active" + // Named before each window had its own account; kept so the stored value carries over. + static let lastFocused = "accounts.active" static let schemaVersion = "accounts.schemaVersion" } @@ -86,17 +87,17 @@ public struct AccountStore: Sendable { func remove(storeID: String) throws { try keychain.delete(forKey: Self.sessionKey(for: storeID)) defaults.set(storedOrder.filter { $0 != storeID }, forKey: DefaultsKey.order) - if activeStoreID == storeID { - activeStoreID = nil + if lastFocusedStoreID == storeID { + lastFocusedStoreID = nil } } // MARK: Metadata - /// The account that was last active, if it still exists. - public var activeStoreID: String? { - get { defaults.string(forKey: DefaultsKey.active) } - nonmutating set { defaults.set(newValue, forKey: DefaultsKey.active) } + /// The account of the most recently focused window, if it still exists. New windows open on it. + public var lastFocusedStoreID: String? { + get { defaults.string(forKey: DefaultsKey.lastFocused) } + nonmutating set { defaults.set(newValue, forKey: DefaultsKey.lastFocused) } } /// Persists the display order of accounts. @@ -152,8 +153,8 @@ public struct AccountStore: Sendable { guard try load(storeID: legacySession.storeID) == legacySession else { throw AccountStoreError.migrationVerificationFailed } - if activeStoreID == nil { - activeStoreID = legacySession.storeID + if lastFocusedStoreID == nil { + lastFocusedStoreID = legacySession.storeID } defaults.set(Self.currentSchemaVersion, forKey: DefaultsKey.schemaVersion) removeLegacySession() diff --git a/Tests/MactrixAppTests/AccountStoreTests.swift b/Tests/MactrixAppTests/AccountStoreTests.swift index d78b024e..a4df31a4 100644 --- a/Tests/MactrixAppTests/AccountStoreTests.swift +++ b/Tests/MactrixAppTests/AccountStoreTests.swift @@ -58,7 +58,7 @@ struct AccountStoreTests { @Test func freshInstallHasNoAccounts() throws { try store.migrateLegacyIfNeeded() #expect(try store.loadAll().isEmpty) - #expect(store.activeStoreID == nil) + #expect(store.lastFocusedStoreID == nil) #expect(defaults.integer(forKey: AccountStore.DefaultsKey.schemaVersion) == 1) } @@ -69,7 +69,7 @@ struct AccountStoreTests { try store.migrateLegacyIfNeeded() #expect(try store.loadAll() == [legacy]) - #expect(store.activeStoreID == "A") + #expect(store.lastFocusedStoreID == "A") #expect(try keychain.load(forKey: AccountStore.legacySessionKey) == nil) } @@ -141,9 +141,9 @@ struct AccountStoreTests { @Test func removingActiveAccountClearsActive() throws { try store.save(makeUserSession(storeID: "A")) - store.activeStoreID = "A" + store.lastFocusedStoreID = "A" try store.remove(storeID: "A") - #expect(store.activeStoreID == nil) + #expect(store.lastFocusedStoreID == nil) } @Test func skipsUnreadableSessions() throws { diff --git a/Tests/MactrixAppTests/WindowAccountFallbackTests.swift b/Tests/MactrixAppTests/WindowAccountFallbackTests.swift new file mode 100644 index 00000000..14c962e9 --- /dev/null +++ b/Tests/MactrixAppTests/WindowAccountFallbackTests.swift @@ -0,0 +1,36 @@ +import Testing + +@testable import MactrixApp + +@MainActor +struct WindowAccountFallbackTests { + @Test func windowKeepsItsOwnAccount() { + let shown = AppState.accountToShow( + windowAccountID: "B", lastFocusedAccountID: "A", accountIDs: ["A", "B"]) + #expect(shown == "B") + } + + @Test func newWindowOpensOnLastFocusedAccount() { + let shown = AppState.accountToShow( + windowAccountID: nil, lastFocusedAccountID: "B", accountIDs: ["A", "B"]) + #expect(shown == "B") + } + + @Test func removedAccountFallsBackToLastFocused() { + let shown = AppState.accountToShow( + windowAccountID: "C", lastFocusedAccountID: "B", accountIDs: ["A", "B"]) + #expect(shown == "B") + } + + @Test func fallsBackToFirstAccountWhenLastFocusedIsGone() { + let shown = AppState.accountToShow( + windowAccountID: "C", lastFocusedAccountID: "D", accountIDs: ["A", "B"]) + #expect(shown == "A") + } + + @Test func showsNothingWithoutAccounts() { + let shown = AppState.accountToShow( + windowAccountID: "A", lastFocusedAccountID: "A", accountIDs: []) + #expect(shown == nil) + } +} From 99caaf96b50c72a770a16f116ae8348e204151d4 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Thu, 26 Nov 2026 16:01:33 -0500 Subject: [PATCH 20/35] Badge each window's switcher with its other accounts' unread rooms The switcher badge counted unread rooms in every account but the last focused window's, so a background window showing another account counted its own rooms. It now counts the accounts other than the one its window shows. The Dock badge still totals every account. --- Sources/MactrixApp/Models/AppState.swift | 8 +++----- Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift | 10 +++++++--- 2 files changed, 10 insertions(+), 8 deletions(-) diff --git a/Sources/MactrixApp/Models/AppState.swift b/Sources/MactrixApp/Models/AppState.swift index 70ee5050..c7eba112 100644 --- a/Sources/MactrixApp/Models/AppState.swift +++ b/Sources/MactrixApp/Models/AppState.swift @@ -56,12 +56,10 @@ public final class AppState { accounts.first { $0.storeID == lastFocusedAccountID } } - /// The number of unread rooms across accounts other than the last focused window's. - public var inactiveUnreadRoomCount: Int { + /// The number of unread rooms across accounts other than `accountID`. + public func unreadRoomCount(excludingAccountID accountID: String?) -> Int { accounts.reduce(0) { count, account in - guard account.storeID != lastFocusedAccountID, !account.authenticationFailed else { - return count - } + guard account.storeID != accountID, !account.authenticationFailed else { return count } return count + account.unreadRoomCount } } diff --git a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift index 6888f711..4bdc49b4 100644 --- a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift +++ b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift @@ -79,8 +79,8 @@ struct AccountSwitcher: View { Image(systemName: "exclamationmark.circle.fill") .foregroundStyle(.orange) } - if appState.inactiveUnreadRoomCount > 0 { - UnreadBadge(count: appState.inactiveUnreadRoomCount) + if otherAccountsUnreadCount > 0 { + UnreadBadge(count: otherAccountsUnreadCount) .help("Unread rooms in your other accounts") } Image(systemName: "chevron.up.chevron.down") @@ -120,6 +120,10 @@ struct AccountSwitcher: View { } } + private var otherAccountsUnreadCount: Int { + appState.unreadRoomCount(excludingAccountID: windowState.accountID) + } + private var accessibilityLabel: String { guard let active = windowState.matrixClient else { return String(localized: "Switch account") } var label = String(localized: "Switch account, current: \(active.accountMenuTitle)") @@ -129,7 +133,7 @@ struct AccountSwitcher: View { if active.needsAttention { label = String(localized: "\(label), needs attention") } - let unread = appState.inactiveUnreadRoomCount + let unread = otherAccountsUnreadCount return unread > 0 ? String(localized: "\(label), \(unread) unread in other accounts") : label } From 405444ac80d710c13c3235b939856c78a36e7d0e Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Thu, 26 Nov 2026 16:02:59 -0500 Subject: [PATCH 21/35] Open notifications in the window showing their account Clicking a notification opens its room in the most recently focused window already showing that account, bringing it to the front. Only if no window shows the account does the frontmost window switch to it, as before. Each window now records its NSWindow so it can be raised, un-minimized, and selected in its tab group, and is forgotten once it closes so nothing is routed to it. --- Mactrix/MactrixApp.swift | 3 +- Sources/MactrixApp/MainView.swift | 9 ++++ Sources/MactrixApp/Models/AppState.swift | 26 +++++++-- Sources/MactrixApp/Models/WindowState.swift | 13 +++++ Sources/MactrixApp/Views/WindowReader.swift | 54 +++++++++++++++++++ .../NotificationWindowTests.swift | 41 ++++++++++++++ 6 files changed, 140 insertions(+), 6 deletions(-) create mode 100644 Sources/MactrixApp/Views/WindowReader.swift create mode 100644 Tests/MactrixAppTests/NotificationWindowTests.swift diff --git a/Mactrix/MactrixApp.swift b/Mactrix/MactrixApp.swift index f224b653..700de409 100644 --- a/Mactrix/MactrixApp.swift +++ b/Mactrix/MactrixApp.swift @@ -31,7 +31,6 @@ struct MactrixApp: App { } func focusNotification() { - guard let windowState else { return } - appState.showNotificationTarget(in: windowState) + appState.showNotificationTarget() } } diff --git a/Sources/MactrixApp/MainView.swift b/Sources/MactrixApp/MainView.swift index 972f011f..fe9d80c8 100644 --- a/Sources/MactrixApp/MainView.swift +++ b/Sources/MactrixApp/MainView.swift @@ -100,6 +100,15 @@ public struct MainView: View { windowState?.selectRoom(roomID) }) } + .background { + WindowReader( + onChange: { [weak windowState] window in + windowState?.window = window + }, + onClose: { [weak windowState] in + if let windowState { appState.unregister(windowState) } + }) + } .task { await attemptLoadUserSession() } .sheet(item: $windowState.loginSheet, onDismiss: onLoginModalDismiss) { request in WelcomeSheetView(request: request) diff --git a/Sources/MactrixApp/Models/AppState.swift b/Sources/MactrixApp/Models/AppState.swift index c7eba112..45255fbd 100644 --- a/Sources/MactrixApp/Models/AppState.swift +++ b/Sources/MactrixApp/Models/AppState.swift @@ -159,6 +159,11 @@ public final class AppState { } } + /// Records that `windowState`'s window closed, so nothing is routed to it. + public func unregister(_ windowState: WindowState) { + windows.removeAll { $0.value == nil || $0.value === windowState } + } + /// Records that `windowState` is the focused window. public func focus(_ windowState: WindowState) { windows.removeAll { $0.value == nil || $0.value === windowState } @@ -215,10 +220,16 @@ public final class AppState { } } - /// Opens the room of a clicked notification in `windowState`, switching to its account. - public func showNotificationTarget(in windowState: WindowState) { - // A click that launched the app arrives before accounts are restored; handle it afterwards. - guard hasRestored, let target = notificationRouter.pendingTarget else { return } + /// Opens the room of a clicked notification. + /// + /// The room opens in the most recently focused window already showing its account, brought to + /// the front. If no window shows the account, the frontmost window switches to it. + public func showNotificationTarget() { + // A click that launched the app arrives before accounts are restored or a window opens; + // handle it afterwards. + guard hasRestored, let target = notificationRouter.pendingTarget, + let windowState = Self.window(forAccountID: target.accountID, in: openWindows) + else { return } notificationRouter.pendingTarget = nil if let accountID = target.accountID { @@ -230,6 +241,13 @@ public final class AppState { show(account, in: windowState) } windowState.selectedRoomId = target.roomId + windowState.bringToFront() + } + + /// The window to show something of `accountID` in: the most recently focused window showing + /// that account, or else the frontmost window. `windows` is ordered most recently focused first. + static func window(forAccountID accountID: String?, in windows: [WindowState]) -> WindowState? { + windows.first { accountID != nil && $0.accountID == accountID } ?? windows.first } /// Names the receiving account in notifications once more than one account is signed in. diff --git a/Sources/MactrixApp/Models/WindowState.swift b/Sources/MactrixApp/Models/WindowState.swift index 3cc554fb..60b788cd 100644 --- a/Sources/MactrixApp/Models/WindowState.swift +++ b/Sources/MactrixApp/Models/WindowState.swift @@ -110,6 +110,19 @@ public final class WindowState { /// The client of the account this window shows. `AppState` owns the clients. public private(set) weak var matrixClient: MatrixClient? + /// The window showing this state. + @ObservationIgnored weak var window: NSWindow? + + /// Brings this window to the front, selecting its tab and restoring it from the Dock. + func bringToFront() { + guard let window else { return } + if window.isMiniaturized { + window.deminiaturize(nil) + } + window.tabGroup?.selectedWindow = window + window.makeKeyAndOrderFront(nil) + } + public var selectedRoomId: String? { get { switch selectedScreen.content { diff --git a/Sources/MactrixApp/Views/WindowReader.swift b/Sources/MactrixApp/Views/WindowReader.swift new file mode 100644 index 00000000..6625921f --- /dev/null +++ b/Sources/MactrixApp/Views/WindowReader.swift @@ -0,0 +1,54 @@ +import AppKit +import SwiftUI + +/// Reports the window that hosts it, the window it moves to later, and when that window closes. +struct WindowReader: NSViewRepresentable { + let onChange: (NSWindow?) -> Void + let onClose: () -> Void + + func makeNSView(context: Context) -> ReportingView { + ReportingView(onChange: onChange, onClose: onClose) + } + + func updateNSView(_ view: ReportingView, context: Context) { + view.onChange = onChange + view.onClose = onClose + // The receiver may be new, so report the current window to it too. + if let window = view.window { + onChange(window) + } + } + + final class ReportingView: NSView { + var onChange: (NSWindow?) -> Void + var onClose: () -> Void + private var closeObserver: NSObjectProtocol? + + init(onChange: @escaping (NSWindow?) -> Void, onClose: @escaping () -> Void) { + self.onChange = onChange + self.onClose = onClose + super.init(frame: .zero) + } + + @available(*, unavailable) + required init?(coder: NSCoder) { + fatalError("init(coder:) has not been implemented") + } + + override func viewDidMoveToWindow() { + super.viewDidMoveToWindow() + if let closeObserver { + NotificationCenter.default.removeObserver(closeObserver) + self.closeObserver = nil + } + if let window { + closeObserver = NotificationCenter.default.addObserver( + forName: NSWindow.willCloseNotification, object: window, queue: .main + ) { [weak self] _ in + MainActor.assumeIsolated { self?.onClose() } + } + } + onChange(window) + } + } +} diff --git a/Tests/MactrixAppTests/NotificationWindowTests.swift b/Tests/MactrixAppTests/NotificationWindowTests.swift new file mode 100644 index 00000000..9727b7b6 --- /dev/null +++ b/Tests/MactrixAppTests/NotificationWindowTests.swift @@ -0,0 +1,41 @@ +import Testing + +@testable import MactrixApp + +@MainActor +struct NotificationWindowTests { + @Test func notificationOpensInWindowShowingItsAccount() { + let frontmost = window(showing: "A") + let background = window(showing: "B") + let older = window(showing: "B") + + let chosen = AppState.window(forAccountID: "B", in: [frontmost, background, older]) + #expect(chosen === background) + } + + @Test func notificationSwitchesFrontmostWindowWhenNoneShowsItsAccount() { + let frontmost = window(showing: "A") + let background = window(showing: "B") + + let chosen = AppState.window(forAccountID: "C", in: [frontmost, background]) + #expect(chosen === frontmost) + } + + @Test func notificationWithoutAccountOpensInFrontmostWindow() { + let frontmost = window(showing: nil) + let background = window(showing: "B") + + let chosen = AppState.window(forAccountID: nil, in: [frontmost, background]) + #expect(chosen === frontmost) + } + + @Test func notificationWaitsForAWindow() { + #expect(AppState.window(forAccountID: "A", in: []) == nil) + } + + private func window(showing accountID: String?) -> WindowState { + let windowState = WindowState() + windowState.showAccount(accountID, knownAccountIDs: Set([accountID].compactMap { $0 })) + return windowState + } +} From ba7fce02a616227a2b6475fa88c50d08aaeb85c5 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Thu, 26 Nov 2026 16:04:09 -0500 Subject: [PATCH 22/35] Flag verification requests for accounts no window shows A verification request opens the switcher popover only in the most recently focused window showing its account, rather than in every such window. When no window shows the account, the frontmost window's switcher gets the attention mark and the account's row is flagged; picking it switches the window, and the popover then offers the request. --- Sources/MactrixApp/Models/AppState.swift | 18 ++++++++++++- .../Views/Sidebar/AccountSwitcher.swift | 27 ++++++++++++++++--- 2 files changed, 41 insertions(+), 4 deletions(-) diff --git a/Sources/MactrixApp/Models/AppState.swift b/Sources/MactrixApp/Models/AppState.swift index 45255fbd..7a638c97 100644 --- a/Sources/MactrixApp/Models/AppState.swift +++ b/Sources/MactrixApp/Models/AppState.swift @@ -35,7 +35,7 @@ public final class AppState { public private(set) var lastFocusedAccountID: String? private var hasRestored = false /// Open windows, most recently focused first. - @ObservationIgnored private var windows: [WeakWindowState] = [] + private var windows: [WeakWindowState] = [] @ObservationIgnored private let accountStore: AccountStore @ObservationIgnored private var restoreTask: Task? @@ -193,6 +193,22 @@ public final class AppState { windowState.showAccount(account, knownAccountIDs: Set(accounts.map(\.storeID))) } + /// The window that handles `accountID`'s verification requests: the most recently focused + /// window showing that account. + func verificationWindow(forAccountID accountID: String?) -> WindowState? { + guard let accountID else { return nil } + return openWindows.first { $0.accountID == accountID } + } + + /// Accounts with a verification request that no window shows, which the frontmost window's + /// switcher flags. + var accountsWithUnseenVerificationRequests: [MatrixClient] { + accounts.filter { account in + account.sessionVerificationRequest != nil + && !openWindows.contains { $0.accountID == account.storeID } + } + } + /// Which account a window shows, given the account it showed before. static func accountToShow( windowAccountID: String?, lastFocusedAccountID: String?, accountIDs: [String] diff --git a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift index 4bdc49b4..25521b5a 100644 --- a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift +++ b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift @@ -75,7 +75,7 @@ struct AccountSwitcher: View { .font(.body.weight(.semibold)) } Spacer(minLength: 0) - if windowState.matrixClient?.needsAttention == true { + if windowState.matrixClient?.needsAttention == true || !unseenVerificationAccounts.isEmpty { Image(systemName: "exclamationmark.circle.fill") .foregroundStyle(.orange) } @@ -101,9 +101,14 @@ struct AccountSwitcher: View { .popover(isPresented: $isPresented, arrowEdge: .top) { popoverContent } - // Verification requests time out, so don't leave one waiting behind a closed popover. + // Verification requests time out, so don't leave one waiting behind a closed popover. Only + // one window per account opens it. .onChange(of: windowState.matrixClient?.sessionVerificationRequest?.flowId) { _, flowID in - if flowID != nil { isPresented = true } + if flowID != nil, + appState.verificationWindow(forAccountID: windowState.accountID) === windowState + { + isPresented = true + } } .confirmationDialog( "Sign out of \(accountToSignOut?.userID ?? "")?", @@ -120,6 +125,12 @@ struct AccountSwitcher: View { } } + /// Accounts with a verification request that no window shows, flagged in the frontmost window. + private var unseenVerificationAccounts: [MatrixClient] { + guard appState.openWindows.first === windowState else { return [] } + return appState.accountsWithUnseenVerificationRequests + } + private var otherAccountsUnreadCount: Int { appState.unreadRoomCount(excludingAccountID: windowState.accountID) } @@ -133,6 +144,9 @@ struct AccountSwitcher: View { if active.needsAttention { label = String(localized: "\(label), needs attention") } + if !unseenVerificationAccounts.isEmpty { + label = String(localized: "\(label), verification requested in another account") + } let unread = otherAccountsUnreadCount return unread > 0 ? String(localized: "\(label), \(unread) unread in other accounts") : label @@ -201,6 +215,10 @@ private struct AccountRow: View { Text("Signed Out") .font(.caption.weight(.medium)) .foregroundStyle(.orange) + } else if !isActive, account.sessionVerificationRequest != nil { + Image(systemName: "exclamationmark.circle.fill") + .foregroundStyle(.orange) + .help("Verification requested") } else if account.unreadRoomCount > 0 { UnreadBadge(count: account.unreadRoomCount) } @@ -221,6 +239,9 @@ private struct AccountRow: View { private var accessibilityValue: String { if account.authenticationFailed { return String(localized: "Signed out") } var values: [String] = [] + if !isActive, account.sessionVerificationRequest != nil { + values.append(String(localized: "Verification requested")) + } if account.syncState != .running { values.append(String(localized: "Sync: \(account.syncState.label)")) } From 34a7ccc55635c66345ff89dd679eb37cf45dc01a Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Thu, 26 Nov 2026 16:05:03 -0500 Subject: [PATCH 23/35] Localize the verification flag strings Add the switcher's strings for a verification request in an account no window shows to the catalog. --- Mactrix/Localizable.xcstrings | 2 ++ 1 file changed, 2 insertions(+) diff --git a/Mactrix/Localizable.xcstrings b/Mactrix/Localizable.xcstrings index c8b6867c..e5dbe2a6 100644 --- a/Mactrix/Localizable.xcstrings +++ b/Mactrix/Localizable.xcstrings @@ -146,6 +146,7 @@ } } }, + "%@, verification requested in another account" : {}, "%lld other events" : { "localizations" : { "da" : { @@ -8351,6 +8352,7 @@ } } }, + "Verification requested" : {}, "Verification status unknown" : { "localizations" : { "da" : { From 3b8e525d9b2ec3efb85d62c4c715a9c5c4db5976 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Thu, 26 Nov 2026 16:43:10 -0500 Subject: [PATCH 24/35] Show a loading state in the switcher until accounts are restored MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Restoring the stored accounts at launch takes a moment, during which the switcher said "No Account" as if none were signed in. It now shows a spinner and "Loading…" until the accounts are back, and can't be opened in the meantime. "No Account" is kept for when none are signed in. --- .../Views/Sidebar/AccountSwitcher.swift | 16 +++++++++++++++- 1 file changed, 15 insertions(+), 1 deletion(-) diff --git a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift index 25521b5a..3025eaf0 100644 --- a/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift +++ b/Sources/MactrixApp/Views/Sidebar/AccountSwitcher.swift @@ -70,6 +70,12 @@ struct AccountSwitcher: View { HStack(spacing: 6) { if let active = windowState.matrixClient { AccountLabel(account: active) + } else if isLoading { + ProgressView() + .controlSize(.small) + Text("Loading…") + .font(.body.weight(.semibold)) + .foregroundStyle(.secondary) } else { Text("No Account") .font(.body.weight(.semibold)) @@ -95,6 +101,7 @@ struct AccountSwitcher: View { in: RoundedRectangle(cornerRadius: 6, style: .continuous)) } .buttonStyle(.plain) + .disabled(isLoading) .onHover { isHovered = $0 } .help("Switch account") .accessibilityLabel(accessibilityLabel) @@ -125,6 +132,11 @@ struct AccountSwitcher: View { } } + /// Whether stored accounts are still being restored at launch. + private var isLoading: Bool { + windowState.matrixClient == nil && appState.restoration == .pending + } + /// Accounts with a verification request that no window shows, flagged in the frontmost window. private var unseenVerificationAccounts: [MatrixClient] { guard appState.openWindows.first === windowState else { return [] } @@ -136,7 +148,9 @@ struct AccountSwitcher: View { } private var accessibilityLabel: String { - guard let active = windowState.matrixClient else { return String(localized: "Switch account") } + guard let active = windowState.matrixClient else { + return isLoading ? String(localized: "Loading…") : String(localized: "Switch account") + } var label = String(localized: "Switch account, current: \(active.accountMenuTitle)") if active.syncState != .running { label = String(localized: "\(label), sync: \(active.syncState.label)") From 9b3c79aff239e934e2a2f8175e1495b00fce44c7 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Thu, 26 Nov 2026 16:44:20 -0500 Subject: [PATCH 25/35] Restore accounts in parallel Stored accounts were restored one after another, and none appeared until the last was done, so launch took the sum of every account's restore. They now restore concurrently, so launch waits only for the slowest. The stored account order is kept. --- Sources/MatrixIntegration/MatrixClient.swift | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/Sources/MatrixIntegration/MatrixClient.swift b/Sources/MatrixIntegration/MatrixClient.swift index d9b6a93e..2afdccad 100644 --- a/Sources/MatrixIntegration/MatrixClient.swift +++ b/Sources/MatrixIntegration/MatrixClient.swift @@ -154,10 +154,17 @@ public class MatrixClient { return [] } + // Start every restore before awaiting any, so launch waits for the slowest account rather + // than all of them in turn. Awaiting in order keeps the stored account order. + let restores = sessions.map { session in + Task { @MainActor in + try await MatrixClient(userSession: session, accountStore: accountStore) + } + } var clients: [MatrixClient] = [] - for session in sessions { + for (session, restore) in zip(sessions, restores) { do { - clients.append(try await MatrixClient(userSession: session, accountStore: accountStore)) + clients.append(try await restore.value) } catch { Logger.matrixClient.error("Failed to restore store \(session.storeID): \(error)") } From 8b7c410f42217a23671a4841382bed64049b2ff8 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Thu, 26 Nov 2026 16:45:35 -0500 Subject: [PATCH 26/35] Restore sessions without contacting the homeserver Building a restored account's client looked up its homeserver and asked it whether it supports native sliding sync, so launch waited on network requests for every account. A stored session already records its homeserver URL and uses native sliding sync, so restoring now builds the client from those without any requests. Signing in still discovers the homeserver. --- Sources/MatrixIntegration/MatrixClient.swift | 36 ++++++++++++++++---- 1 file changed, 30 insertions(+), 6 deletions(-) diff --git a/Sources/MatrixIntegration/MatrixClient.swift b/Sources/MatrixIntegration/MatrixClient.swift index 2afdccad..465c4d76 100644 --- a/Sources/MatrixIntegration/MatrixClient.swift +++ b/Sources/MatrixIntegration/MatrixClient.swift @@ -48,7 +48,8 @@ public class MatrixClient { self.accountStore = accountStore client = try await Self.clientBuilder( - homeServer: userSession.homeserverURL, storeId: storeID, storePassphrase: storePassphrase + homeserver: .stored(url: userSession.homeserverURL), storeId: storeID, + storePassphrase: storePassphrase ) // .enableOidcRefreshLock() .setSessionDelegate(sessionDelegate: self) @@ -86,7 +87,18 @@ public class MatrixClient { /// process's file descriptors, failing database opens, network requests, and rendering. static let sqlitePoolMaxSize: UInt32 = 8 - static func clientBuilder(homeServer: String, storeId: String, storePassphrase: String) + /// Where a client's homeserver comes from. + enum Homeserver { + /// A server name or URL entered at sign-in. Building the client looks up the homeserver and + /// checks that it supports native sliding sync, which takes network requests. + case discover(serverNameOrURL: String) + /// The homeserver of a stored session, which already uses native sliding sync. Building the + /// client takes no network requests, so restoring at launch doesn't wait for, or need, the + /// network. + case stored(url: String) + } + + static func clientBuilder(homeserver: Homeserver, storeId: String, storePassphrase: String) -> ClientBuilder { let sqliteConfig = SqliteStoreBuilder( @@ -96,18 +108,29 @@ public class MatrixClient { .passphrase(passphrase: storePassphrase) .poolMaxSize(poolMaxSize: sqlitePoolMaxSize) - return ClientBuilder() - .serverNameOrHomeserverUrl(serverNameOrUrl: homeServer) + let builder = ClientBuilder() .sqliteStore(config: sqliteConfig) .withSearchIndexStore( path: StoreDirectories.caches(for: storeId).appending(component: "SearchIndex") .path(percentEncoded: false), key: storePassphrase ) - .slidingSyncVersionBuilder(versionBuilder: .discoverNative) .threadsEnabled(enabled: true, threadSubscriptions: true) .autoEnableCrossSigning(autoEnableCrossSigning: true) .userAgent(userAgent: "Mactrix macOS") + + switch homeserver { + case .discover(let serverNameOrURL): + return + builder + .serverNameOrHomeserverUrl(serverNameOrUrl: serverNameOrURL) + .slidingSyncVersionBuilder(versionBuilder: .discoverNative) + case .stored(let url): + return + builder + .homeserverUrl(url: url) + .slidingSyncVersionBuilder(versionBuilder: .native) + } } struct SecureRandomBytesError: LocalizedError { @@ -133,7 +156,8 @@ public class MatrixClient { let storePassphrase = try Self.generateStorePassphrase() let client = try await Self.clientBuilder( - homeServer: homeServer, storeId: storeID, storePassphrase: storePassphrase + homeserver: .discover(serverNameOrURL: homeServer), storeId: storeID, + storePassphrase: storePassphrase ).build() let details = await client.homeserverLoginDetails() From b9245f72d4fe4372fe1dc0a156a2cd98da2ebe55 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Thu, 26 Nov 2026 17:05:58 -0500 Subject: [PATCH 27/35] Start syncing even when account setup fails offline Starting sync set up the room list, notifications, the verification delegate and the ignored users before starting the sync loop, and gave up at the first step that threw. Launched without a network, one of them threw, so the sync loop never started and the account stayed "idle" even once the network came back. Each setup step now fails on its own, logging its name, and the sync loop starts regardless, its offline mode reconnecting by itself. Steps that failed are retried whenever sync comes back online. The own profile is one such step, so an account launched offline gets its display name once it reconnects. --- .../MatrixClient+Listeners.swift | 4 + Sources/MatrixIntegration/MatrixClient.swift | 117 ++++++++++++++---- 2 files changed, 97 insertions(+), 24 deletions(-) diff --git a/Sources/MatrixIntegration/MatrixClient+Listeners.swift b/Sources/MatrixIntegration/MatrixClient+Listeners.swift index f844d8b8..f70b496f 100644 --- a/Sources/MatrixIntegration/MatrixClient+Listeners.swift +++ b/Sources/MatrixIntegration/MatrixClient+Listeners.swift @@ -66,6 +66,10 @@ extension MatrixClient: SyncServiceStateObserver { nonisolated public func onUpdate(state: MatrixRustSDK.SyncServiceState) { Task { @MainActor in syncState = state + // Setup that failed while offline can succeed now that the homeserver answers. + if state == .running { + retryPendingSetupSteps() + } } } } diff --git a/Sources/MatrixIntegration/MatrixClient.swift b/Sources/MatrixIntegration/MatrixClient.swift index 465c4d76..00fbc4a0 100644 --- a/Sources/MatrixIntegration/MatrixClient.swift +++ b/Sources/MatrixIntegration/MatrixClient.swift @@ -298,6 +298,22 @@ public class MatrixClient { var notificationClient: NotificationClient? + /// Account setup that comes with syncing. + /// + /// Some steps fail while the homeserver can't be reached, so none of them stop the sync loop from + /// starting. A failed step is retried whenever sync comes back online. + enum SyncSetupStep: String, CaseIterable { + case roomList = "room list" + case notifications + case verification + case ignoredUsers = "ignored users" + case ownProfile = "own profile" + } + + /// The setup steps that haven't succeeded yet. + @ObservationIgnored private var pendingSetupSteps = SyncSetupStep.allCases + @ObservationIgnored private var setupRetryTask: Task? + public func startSync() async throws { let _syncService = try await client.syncService().withOfflineMode().finish() syncService = _syncService @@ -310,45 +326,98 @@ public class MatrixClient { syncIndicatorHandle = _roomListService.syncIndicator( delayBeforeShowingInMs: 200, delayBeforeHidingInMs: 200, listener: self) - let roomEntriesListener = AsyncSDKListener<[RoomListEntriesUpdate]>() - let _roomListEntriesHandle = try await _roomListService.allRooms().entriesWithDynamicAdapters( - pageSize: 100, listener: roomEntriesListener) - _ = _roomListEntriesHandle.controller().setFilter(kind: .all(filters: [])) - roomListEntriesHandle = _roomListEntriesHandle - - Task { [weak self] in - for await roomEntries in roomEntriesListener { - guard let self else { break } - self.updateRoomEntries(roomEntriesUpdate: roomEntries) - } - } - - notificationClient = try await client.notificationClient( - processSetup: .singleProcess(syncService: _syncService)) - await client.registerNotificationHandler(listener: notifications) - - try await client.getSessionVerificationController().setDelegate(delegate: self) - let encryption = client.encryption() verificationStateHandle = encryption.verificationStateListener(listener: self) recoveryStateHandle = encryption.recoveryStateListener(listener: self) backupStateHandle = encryption.backupStateListener(listener: self) ignoredUsersHandle = client.subscribeToIgnoredUsers(listener: self) - ignoredUserIds = try await client.ignoredUsers() - Task { [weak self] in await self?.refreshOwnProfile() } + // The room list and notification handler come from the local store. Set them up before the + // first sync, so it doesn't miss rooms or notifications. No retry can overlap this: retries + // only start once sync is running. + await runSetupSteps([.roomList, .notifications]) - // Start the sync loop. + // Start the sync loop. In offline mode it keeps retrying until the homeserver can be reached. await _syncService.start() Logger.matrixClient.info("Matrix sync started, store \(self.storeID)") + + retryPendingSetupSteps() + } + + /// Retries the setup steps that haven't succeeded yet, unless a retry is already running. + func retryPendingSetupSteps() { + guard setupRetryTask == nil, !pendingSetupSteps.isEmpty, !isResettingSession else { return } + setupRetryTask = Task { [weak self] in + guard let self else { return } + await self.runSetupSteps(self.pendingSetupSteps) + self.setupRetryTask = nil + } + } + + /// Runs each of `steps` that is still pending, keeping the ones that fail for a later retry. + private func runSetupSteps(_ steps: [SyncSetupStep]) async { + for step in steps where pendingSetupSteps.contains(step) { + guard !isResettingSession else { return } + do { + try await runSetupStep(step) + pendingSetupSteps.removeAll { $0 == step } + } catch { + Logger.matrixClient.error( + "Sync setup step \(step.rawValue, privacy: .public) failed, store \(self.storeID): \(error)" + ) + } + } + } + + private func runSetupStep(_ step: SyncSetupStep) async throws { + switch step { + case .roomList: + guard let roomListService else { return } + let roomEntriesListener = AsyncSDKListener<[RoomListEntriesUpdate]>() + let _roomListEntriesHandle = try await roomListService.allRooms() + .entriesWithDynamicAdapters(pageSize: 100, listener: roomEntriesListener) + _ = _roomListEntriesHandle.controller().setFilter(kind: .all(filters: [])) + roomListEntriesHandle = _roomListEntriesHandle + + Task { [weak self] in + for await roomEntries in roomEntriesListener { + guard let self else { break } + self.updateRoomEntries(roomEntriesUpdate: roomEntries) + } + } + case .notifications: + guard let syncService else { return } + notificationClient = try await client.notificationClient( + processSetup: .singleProcess(syncService: syncService)) + await client.registerNotificationHandler(listener: notifications) + case .verification: + try await client.getSessionVerificationController().setDelegate(delegate: self) + case .ignoredUsers: + ignoredUserIds = try await client.ignoredUsers() + case .ownProfile: + try await loadOwnProfile() + } } /// Reloads `ownDisplayName` and `ownAvatarUrl`, falling back to cached values when offline. public func refreshOwnProfile() async { - if let displayName = try? await client.displayName() { - ownDisplayName = displayName + try? await loadOwnProfile() + } + + /// Reloads `ownDisplayName` and `ownAvatarUrl`, throwing if the homeserver can't be reached. The + /// cached avatar fills in while there is none yet. + private func loadOwnProfile() async throws { + let displayName: String + do { + displayName = try await client.displayName() + } catch { + if ownAvatarUrl == nil { + ownAvatarUrl = try? await client.cachedAvatarUrl() + } + throw error } + ownDisplayName = displayName if let avatarUrl = try? await client.avatarUrl() { ownAvatarUrl = avatarUrl } else if ownAvatarUrl == nil { From e8573fd430ffc764b7bf1340268c4271e36a317c Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Thu, 26 Nov 2026 17:06:59 -0500 Subject: [PATCH 28/35] Tie "Restart sync" to the sync lifecycle MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit "Restart sync" was hidden while sync was idle, so an account whose sync never started had no way back. Its busy flag was per view, so another window's button, or the launch start still in flight, could build a second sync service with duplicate listeners. The account now tracks one start at a time: a start requested while another is in flight waits for it, and once the sync service exists a restart only calls its start(), which does nothing while running and reconnects straight away when offline. The button shows whenever sync isn't running, reads "Restarting…" and is disabled in every window while a start is in flight. Signing out waits for an in-flight start, which stops before syncing a session being removed. --- Mactrix/Localizable.xcstrings | 1 + Sources/MactrixApp/Models/AppState.swift | 8 +--- .../Views/Sidebar/AccountStatus.swift | 28 +++++------- Sources/MatrixIntegration/MatrixClient.swift | 44 ++++++++++++++++++- 4 files changed, 55 insertions(+), 26 deletions(-) diff --git a/Mactrix/Localizable.xcstrings b/Mactrix/Localizable.xcstrings index e5dbe2a6..eacb3d4b 100644 --- a/Mactrix/Localizable.xcstrings +++ b/Mactrix/Localizable.xcstrings @@ -5117,6 +5117,7 @@ } } }, + "Restarting…" : {}, "Restoring encryption secrets…" : { "localizations" : { "da" : { diff --git a/Sources/MactrixApp/Models/AppState.swift b/Sources/MactrixApp/Models/AppState.swift index 7a638c97..45091f16 100644 --- a/Sources/MactrixApp/Models/AppState.swift +++ b/Sources/MactrixApp/Models/AppState.swift @@ -290,13 +290,7 @@ public final class AppState { } private func startSync(_ client: MatrixClient) { - Task { - do { - try await client.startSync() - } catch { - Logger.matrixClient.error("Failed to start sync: \(error)") - } - } + Task { await client.startSync() } } } diff --git a/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift b/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift index bbd65f8e..58940263 100644 --- a/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift +++ b/Sources/MactrixApp/Views/Sidebar/AccountStatus.swift @@ -27,10 +27,6 @@ extension SyncServiceState { case .terminated, .error: .red } } - - var canRestart: Bool { - [.error, .offline, .terminated].contains(self) - } } extension MatrixClient { @@ -67,7 +63,6 @@ struct AccountStatusSection: View { /// Closes the popover, before presenting a sheet. let dismiss: () -> Void - @State private var restarting = false @State private var removing = false var body: some View { @@ -181,21 +176,18 @@ struct AccountStatusSection: View { AccountStatusItem(systemImage: "arrow.triangle.2.circlepath", tint: account.syncState.color) { Text("Sync: \(account.syncState.label)") } actions: { - if account.syncState.canRestart { - Button("Restart sync") { - Task { - restarting = true - defer { restarting = false } - - do { - try await account.startSync() - } catch { - Logger.viewCycle.error("failed to restart sync: \(error)") - } - } + // The account tracks whether a start is in flight, so every window's button reflects it + // and repeated clicks join the same start. + Button { + Task { await account.startSync() } + } label: { + if account.isStartingSync { + Text("Restarting…") + } else { + Text("Restart sync") } - .disabled(restarting) } + .disabled(account.isStartingSync) } } } diff --git a/Sources/MatrixIntegration/MatrixClient.swift b/Sources/MatrixIntegration/MatrixClient.swift index 00fbc4a0..832ec9f4 100644 --- a/Sources/MatrixIntegration/MatrixClient.swift +++ b/Sources/MatrixIntegration/MatrixClient.swift @@ -214,6 +214,9 @@ public class MatrixClient { recentReactions.invalidate() isResettingSession = true await roomSubscriptions.invalidate() + // A start in flight stops at its next step; wait so it can't start syncing a signed-out + // session after the stop below. + await syncStartTask?.value await syncService?.stop() Logger.matrixClient.debug("matrix client sign out, store \(self.storeID)") try? await client.logout() @@ -314,8 +317,46 @@ public class MatrixClient { @ObservationIgnored private var pendingSetupSteps = SyncSetupStep.allCases @ObservationIgnored private var setupRetryTask: Task? - public func startSync() async throws { + /// Whether a call to `startSync()` is in flight. + public private(set) var isStartingSync = false + @ObservationIgnored private var syncStartTask: Task? + + /// Starts syncing, or restarts a sync that stopped, failed, or went offline. + /// + /// Calls made while a start is in flight wait for it instead of starting another, so this is + /// safe to call repeatedly. + public func startSync() async { + if let syncStartTask { + await syncStartTask.value + return + } + let task = Task { await performStartSync() } + syncStartTask = task + isStartingSync = true + await task.value + syncStartTask = nil + isStartingSync = false + } + + private func performStartSync() async { + guard !isResettingSession, !authenticationFailed else { return } + // Once built, the sync service is only restarted, keeping its listeners. Its `start()` does + // nothing while running, and reconnects straight away when offline. + if let syncService { + await syncService.start() + retryPendingSetupSteps() + return + } + do { + try await setUpSync() + } catch { + Logger.matrixClient.error("Failed to start sync, store \(self.storeID): \(error)") + } + } + + private func setUpSync() async throws { let _syncService = try await client.syncService().withOfflineMode().finish() + guard !isResettingSession else { return } syncService = _syncService syncStateHandle = _syncService.state(listener: self) @@ -337,6 +378,7 @@ public class MatrixClient { // first sync, so it doesn't miss rooms or notifications. No retry can overlap this: retries // only start once sync is running. await runSetupSteps([.roomList, .notifications]) + guard !isResettingSession else { return } // Start the sync loop. In offline mode it keeps retrying until the homeserver can be reached. await _syncService.start() From 2cc5081bd1b64f336712522c3b9c38871e29c011 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Thu, 26 Nov 2026 17:20:56 -0500 Subject: [PATCH 29/35] Resend queued messages when sync comes back online When sending a message fails on a network error, the SDK turns that room's send queue off and keeps the message queued until the queue is turned back on. Nothing turned it back on, so a message sent while offline never went out, even once the account was back online. Every send queue is now turned back on whenever sync comes back online. --- Sources/MatrixIntegration/MatrixClient+Listeners.swift | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/Sources/MatrixIntegration/MatrixClient+Listeners.swift b/Sources/MatrixIntegration/MatrixClient+Listeners.swift index f70b496f..8605ee16 100644 --- a/Sources/MatrixIntegration/MatrixClient+Listeners.swift +++ b/Sources/MatrixIntegration/MatrixClient+Listeners.swift @@ -66,9 +66,12 @@ extension MatrixClient: SyncServiceStateObserver { nonisolated public func onUpdate(state: MatrixRustSDK.SyncServiceState) { Task { @MainActor in syncState = state - // Setup that failed while offline can succeed now that the homeserver answers. if state == .running { + // Setup that failed while offline can succeed now that the homeserver answers. retryPendingSetupSteps() + // A send that fails on a network error turns its room's send queue off, holding the + // message until the queue is turned back on. Resend those now. + await client.enableAllSendQueues(enable: true) } } } From 73e4c96c8472215b16de07b71ba5a2cbc6caa558 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Thu, 26 Nov 2026 17:23:49 -0500 Subject: [PATCH 30/35] Show which messages haven't been sent, with Retry A message that hadn't reached the server looked exactly like a sent one, so a send that failed went unnoticed. Until it's sent, a message is dimmed and its timestamp is replaced by a clock, or a red mark once sending failed. Hovering the mark gives the reason. Clicking it offers Retry Sending and Delete, and Retry Sending is in the message's More actions menu too. Retrying turns the room's send queue back on and resends the message, covering both network failures and errors the user has since fixed. --- Mactrix/Localizable.xcstrings | 12 +++- .../MessageHoverOverlayView.swift | 15 +++- .../TimelineRowViews/MessageRowView.swift | 38 ++++++++++ .../Support/MessageSendStatus.swift | 69 +++++++++++++++++++ .../TimelineView/TimelineTableView.swift | 63 +++++++++++++++++ 5 files changed, 195 insertions(+), 2 deletions(-) create mode 100644 Sources/MactrixApp/Views/ChatView/TimelineView/TimelineRowViews/Support/MessageSendStatus.swift diff --git a/Mactrix/Localizable.xcstrings b/Mactrix/Localizable.xcstrings index eacb3d4b..42f6e315 100644 --- a/Mactrix/Localizable.xcstrings +++ b/Mactrix/Localizable.xcstrings @@ -4159,6 +4159,8 @@ } } }, + "Not sent yet" : {}, + "Not sent. %@ Click to retry or delete." : {}, "Not signed in" : { "localizations" : { "da" : { @@ -5166,6 +5168,7 @@ } } }, + "Retry Sending" : {}, "revoked invitation for %@ to join the room" : { "localizations" : { "da" : { @@ -5869,6 +5872,8 @@ } } }, + "Some devices in this room aren't verified." : {}, + "Someone in this room changed their identity." : {}, "Space" : { "localizations" : { "da" : { @@ -7504,6 +7509,8 @@ } } }, + "The attachment is no longer available." : {}, + "The attachment's file type isn't recognized." : {}, "The original message isn't loaded." : { "localizations" : { "da" : { @@ -7546,6 +7553,7 @@ } } }, + "The server couldn't be reached." : {}, "They don't match" : { "localizations" : { "da" : { @@ -8434,6 +8442,7 @@ } } }, + "Verify this session to send messages." : {}, "Verify with Recovery Key" : { "localizations" : { "da" : { @@ -8803,7 +8812,8 @@ } } } - } + }, + "Your session expired." : {} }, "version" : "1.0" } diff --git a/Sources/MactrixApp/Views/ChatView/TimelineView/MessageHoverOverlayView.swift b/Sources/MactrixApp/Views/ChatView/TimelineView/MessageHoverOverlayView.swift index 3e1777ec..30487cc6 100644 --- a/Sources/MactrixApp/Views/ChatView/TimelineView/MessageHoverOverlayView.swift +++ b/Sources/MactrixApp/Views/ChatView/TimelineView/MessageHoverOverlayView.swift @@ -10,6 +10,7 @@ final class MessageHoverOverlayView: NSView { case pin case edit case delete + case retrySend case copyMessageLink case showSource case downloadToFile(Int) @@ -44,6 +45,8 @@ final class MessageHoverOverlayView: NSView { private let copyLinkMenuItem = NSMenuItem( title: String(localized: "Copy Message Link"), action: #selector(copyMessageLink), keyEquivalent: "") + private let retrySendMenuItem = NSMenuItem( + title: String(localized: "Retry Sending"), action: #selector(retrySend), keyEquivalent: "") private let deleteMenuItem = NSMenuItem( title: String(localized: "Delete message"), action: #selector(deleteMessage), keyEquivalent: "") private let editButton = HoverActionButton( @@ -119,6 +122,11 @@ final class MessageHoverOverlayView: NSView { let sourceMenuItem = NSMenuItem( title: String(localized: "Show Source"), action: #selector(showSource), keyEquivalent: "") + retrySendMenuItem.target = self + retrySendMenuItem.image = NSImage( + systemSymbolName: "arrow.clockwise", accessibilityDescription: retrySendMenuItem.title) + menu.addItem(retrySendMenuItem) + pinMenuItem.target = self menu.addItem(pinMenuItem) @@ -165,8 +173,9 @@ final class MessageHoverOverlayView: NSView { func configure( canReply: Bool, canEdit: Bool = false, canDelete: Bool = false, canReact: Bool = true, canPin: Bool = false, isPinned: Bool = false, - canCopyLink: Bool = false, downloadFilenames: [String] = [] + canCopyLink: Bool = false, canRetrySend: Bool = false, downloadFilenames: [String] = [] ) { + retrySendMenuItem.isHidden = !canRetrySend reactionPickerButton.isEnabled = canReact for button in quickReactionButtons { button.isEnabled = canReact @@ -250,6 +259,10 @@ final class MessageHoverOverlayView: NSView { onAction?(.pin) } + @objc private func retrySend() { + onAction?(.retrySend) + } + @objc private func deleteMessage() { onAction?(.delete) } diff --git a/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineRowViews/MessageRowView.swift b/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineRowViews/MessageRowView.swift index c42344ff..140fd2a3 100644 --- a/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineRowViews/MessageRowView.swift +++ b/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineRowViews/MessageRowView.swift @@ -11,6 +11,8 @@ final class MessageRowView: NSView { var onHoverChange: ((MessageRowView, Bool, NSEvent) -> Bool)? var onSelectRequest: ((MessageRowView) -> Void)? var onArrowKey: ((TimelineSelectionDirection) -> Void)? + /// Called when the send status icon of an unsent message is clicked, with the icon to anchor to. + var onSendStatusClick: ((NSView) -> Void)? var onMediaPreviewRequest: (() -> Bool)? { didSet { (contentView as? any MessageMediaPreviewContentView)?.onMediaPreviewRequest = @@ -34,6 +36,8 @@ final class MessageRowView: NSView { private let timestamp = NSTextField(labelWithString: "") private let editedLabel = NSTextField(labelWithString: String(localized: "(edited)")) + /// Takes the timestamp's place while the message hasn't reached the server. + private let sendStatusButton = NSButton() private lazy var timestampWidthConstraint = timestamp.widthAnchor.constraint( equalToConstant: Self.timestampWidth) private let contentView: any MessageContentRowView @@ -94,6 +98,13 @@ final class MessageRowView: NSView { editedLabel.isHidden = true editedLabel.translatesAutoresizingMaskIntoConstraints = false + sendStatusButton.isBordered = false + sendStatusButton.imagePosition = .imageOnly + sendStatusButton.target = self + sendStatusButton.action = #selector(sendStatusClicked) + sendStatusButton.isHidden = true + sendStatusButton.translatesAutoresizingMaskIntoConstraints = false + contentView.translatesAutoresizingMaskIntoConstraints = false contentView.onSelectRequest = { [weak self] in guard let self else { return } @@ -115,6 +126,7 @@ final class MessageRowView: NSView { addSubview(timestamp) addSubview(editedLabel) + addSubview(sendStatusButton) addSubview(contentView) // NSTableView may retain an old encapsulated height while a reused row is reconfigured. @@ -126,6 +138,8 @@ final class MessageRowView: NSView { editedLabel.leadingAnchor.constraint(equalTo: timestamp.leadingAnchor), editedLabel.trailingAnchor.constraint(equalTo: timestamp.trailingAnchor), editedLabel.topAnchor.constraint(equalTo: timestamp.bottomAnchor, constant: 1), + sendStatusButton.trailingAnchor.constraint(equalTo: timestamp.trailingAnchor), + sendStatusButton.centerYAnchor.constraint(equalTo: timestamp.centerYAnchor), contentView.leadingAnchor.constraint(equalTo: timestamp.trailingAnchor, constant: 16), contentView.trailingAnchor.constraint(equalTo: trailingAnchor, constant: -10), @@ -177,6 +191,7 @@ final class MessageRowView: NSView { let date = Date(timeIntervalSince1970: Double(event.timestamp) / 1000) timestamp.stringValue = Self.timeFormatter.string(from: date) editedLabel.isHidden = !Self.hasBeenEdited(content) + configureSendStatus(MessageSendStatus(event.localSendState)) contentView.handleMatrixUri = handleMatrixUri contentView.configure(content: content, matrixClient: matrixClient) configureReply(details: replyDetails, onClick: onReplyClick) @@ -189,6 +204,29 @@ final class MessageRowView: NSView { updateBackground() } + private func configureSendStatus(_ status: MessageSendStatus?) { + timestamp.isHidden = status != nil + sendStatusButton.isHidden = status == nil + // Dimmed until the message reaches the server, so it doesn't pass for a sent one. + contentView.alphaValue = status == nil ? 1 : 0.5 + guard let status else { + sendStatusButton.toolTip = nil + return + } + let configuration = NSImage.SymbolConfiguration( + pointSize: TimelineTypography.scaled(NSFont.labelFontSize), weight: .regular) + sendStatusButton.image = NSImage( + systemSymbolName: status.symbolName, accessibilityDescription: status.toolTip)? + .withSymbolConfiguration(configuration) + sendStatusButton.contentTintColor = status.tintColor + sendStatusButton.toolTip = status.toolTip + sendStatusButton.setAccessibilityLabel(status.toolTip) + } + + @objc private func sendStatusClicked() { + onSendStatusClick?(sendStatusButton) + } + private func configureThread(summary: MatrixRustSDK.ThreadSummary?, onClick: (() -> Void)?) { guard let summary else { threadSummaryView?.isHidden = true diff --git a/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineRowViews/Support/MessageSendStatus.swift b/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineRowViews/Support/MessageSendStatus.swift new file mode 100644 index 00000000..8b843150 --- /dev/null +++ b/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineRowViews/Support/MessageSendStatus.swift @@ -0,0 +1,69 @@ +import AppKit +import MatrixRustSDK + +/// Whether a message the user sent is still on its way to the server, or failed to get there. +/// +/// Messages that reached the server, and other people's messages, have no status. +enum MessageSendStatus: Equatable { + /// The message is queued or being sent. + case queued + /// Sending failed. The message stays queued until it's retried or deleted. + case failed(reason: String) + + init?(_ state: MatrixRustSDK.EventSendState?) { + switch state { + case .notSentYet: + self = .queued + case .sendingFailed(let error, let isRecoverable): + // A recoverable failure is a network or server error, which the error itself doesn't + // describe any better. + self = .failed( + reason: isRecoverable + ? String(localized: "The server couldn't be reached.") : Self.reason(for: error)) + case .sent, nil: + return nil + } + } + + var symbolName: String { + switch self { + case .queued: "clock" + case .failed: "exclamationmark.circle.fill" + } + } + + var tintColor: NSColor { + switch self { + case .queued: .secondaryLabelColor + case .failed: .systemRed + } + } + + var toolTip: String { + switch self { + case .queued: + String(localized: "Not sent yet") + case .failed(let reason): + String(localized: "Not sent. \(reason) Click to retry or delete.") + } + } + + private static func reason(for error: MatrixRustSDK.QueueWedgeError) -> String { + switch error { + case .insecureDevices: + String(localized: "Some devices in this room aren't verified.") + case .identityViolations: + String(localized: "Someone in this room changed their identity.") + case .crossVerificationRequired: + String(localized: "Verify this session to send messages.") + case .expiredAccessToken: + String(localized: "Your session expired.") + case .missingMediaContent: + String(localized: "The attachment is no longer available.") + case .invalidMimeType: + String(localized: "The attachment's file type isn't recognized.") + case .genericApiError(let message): + message + } + } +} diff --git a/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineTableView.swift b/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineTableView.swift index da137c2e..013f02ac 100644 --- a/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineTableView.swift +++ b/Sources/MactrixApp/Views/ChatView/TimelineView/TimelineTableView.swift @@ -327,6 +327,9 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT self.showMediaPreview( url: url, handle: handle, eventIdentifier: event.eventOrTransactionId.id) } + view.onSendStatusClick = { [weak self] anchor in + self?.showSendStatusMenu(for: event, from: anchor) + } view.configureEditing(messageEdit?.id == event.eventOrTransactionId ? messageEdit : nil) view.configure( event: event, @@ -595,6 +598,7 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT canPin: canPerformMessageAction(.pin, for: event), isPinned: isMessagePinned(event), canCopyLink: canPerformMessageAction(.copyMessageLink, for: event), + canRetrySend: canPerformMessageAction(.retrySend, for: event), downloadFilenames: MessageDownloadAttachment.attachments(for: event).map(\.suggestedFilename)) } @@ -716,6 +720,35 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT } } + /// Shows what can be done with a message that hasn't been sent, below its send status icon. + private func showSendStatusMenu(for event: MatrixRustSDK.EventTimelineItem, from anchor: NSView) { + let menu = NSMenu() + menu.autoenablesItems = false + for (action, title, symbol) in [ + ( + MessageHoverOverlayView.Action.retrySend, String(localized: "Retry Sending"), + "arrow.clockwise" + ), + (.delete, String(localized: "Delete message"), "trash"), + ] where canPerformMessageAction(action, for: event) { + let item = NSMenuItem( + title: title, action: #selector(performSendStatusMenuItem(_:)), keyEquivalent: "") + item.target = self + item.image = NSImage(systemSymbolName: symbol, accessibilityDescription: title) + item.representedObject = PendingMessageAction(action: action, event: event) + menu.addItem(item) + } + guard !menu.items.isEmpty else { return } + let origin = NSPoint( + x: anchor.bounds.minX, y: anchor.isFlipped ? anchor.bounds.maxY + 4 : anchor.bounds.minY - 4) + menu.popUp(positioning: nil, at: origin, in: anchor) + } + + @objc private func performSendStatusMenuItem(_ sender: NSMenuItem) { + guard let pending = sender.representedObject as? PendingMessageAction else { return } + performMessageAction(pending.action, for: pending.event) + } + private func canDeleteMessage(_ event: MatrixRustSDK.EventTimelineItem) -> Bool { guard let powerLevels = timeline.room.roomInfo?.powerLevels else { return false } return event.isOwn @@ -759,6 +792,9 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT && timeline.room.roomInfo?.powerLevels?.canOwnUserPinUnpin() == true case .delete: return timeline.timeline != nil && canDeleteMessage(event) + case .retrySend: + guard case .sendingFailed = event.localSendState else { return false } + return event.lazyProvider.getSendHandle() != nil case .copyMessageLink: if case .eventId = event.eventOrTransactionId { return true } return false @@ -798,6 +834,22 @@ class TimelineViewController: NSViewController, LiveTimelineFocusDelegate, LiveT Logger.timelineTableView.error("Failed to copy message link: \(error)") } } + case .retrySend: + guard case .sendingFailed = event.localSendState, + let sendHandle = event.lazyProvider.getSendHandle() + else { return } + let room = timeline.room.room + startActionTask { + // A network failure turned the room's send queue off; an unrecoverable one parked the + // message. Undo both, so the message goes out whichever it was. + room.enableSendQueue(enable: true) + do { + try await sendHandle.tryResend() + } catch { + guard !Task.isCancelled else { return } + Logger.timelineTableView.error("Failed to retry sending message: \(error)") + } + } case .showSource: MessageSourceWindowController.show(source: event.lazyProvider.latestJson()) case .downloadToFile(let index): @@ -1881,3 +1933,14 @@ final class TimelineDocumentView: NSView { scrollView.reflectScrolledClipView(clipView) } } + +/// A message action waiting on a menu item, which can only hold an object. +private final class PendingMessageAction: NSObject { + let action: MessageHoverOverlayView.Action + let event: MatrixRustSDK.EventTimelineItem + + init(action: MessageHoverOverlayView.Action, event: MatrixRustSDK.EventTimelineItem) { + self.action = action + self.event = event + } +} From f18b012da5f2c05353e2cf8d928b3c9fba8f418e Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Thu, 26 Nov 2026 18:51:47 -0500 Subject: [PATCH 31/35] Log sync state changes and restarts The log showed when sync started but not when it went offline, came back, or was restarted, so a capture couldn't tell how long reconnecting took. Each state change and each restart is now logged, with the state public. --- Sources/MatrixIntegration/MatrixClient+Listeners.swift | 2 ++ Sources/MatrixIntegration/MatrixClient.swift | 3 +++ 2 files changed, 5 insertions(+) diff --git a/Sources/MatrixIntegration/MatrixClient+Listeners.swift b/Sources/MatrixIntegration/MatrixClient+Listeners.swift index 8605ee16..e336d0b3 100644 --- a/Sources/MatrixIntegration/MatrixClient+Listeners.swift +++ b/Sources/MatrixIntegration/MatrixClient+Listeners.swift @@ -65,6 +65,8 @@ extension MatrixClient { extension MatrixClient: SyncServiceStateObserver { nonisolated public func onUpdate(state: MatrixRustSDK.SyncServiceState) { Task { @MainActor in + Logger.matrixClient.info( + "Sync state \(String(describing: state), privacy: .public), store \(self.storeID)") syncState = state if state == .running { // Setup that failed while offline can succeed now that the homeserver answers. diff --git a/Sources/MatrixIntegration/MatrixClient.swift b/Sources/MatrixIntegration/MatrixClient.swift index 832ec9f4..3ff85ee4 100644 --- a/Sources/MatrixIntegration/MatrixClient.swift +++ b/Sources/MatrixIntegration/MatrixClient.swift @@ -343,6 +343,9 @@ public class MatrixClient { // Once built, the sync service is only restarted, keeping its listeners. Its `start()` does // nothing while running, and reconnects straight away when offline. if let syncService { + Logger.matrixClient.info( + "Restarting sync from \(String(describing: self.syncState), privacy: .public), store \(self.storeID)" + ) await syncService.start() retryPendingSetupSteps() return From c9a7ac412a40548aa18c512d2c9c681f12177157 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Thu, 26 Nov 2026 18:52:07 -0500 Subject: [PATCH 32/35] Reconnect as soon as the network comes back In offline mode, the sync service only noticed the network was back at its next reachability check, which backs off to several seconds apart, so accounts stayed offline for a while after reconnecting. A network monitor now restarts every account's sync when the network comes back or moves to another interface, which makes an offline sync service retry at once. Accounts already online are unaffected. A restart also turns the send queues back on, so the Restart sync button resends queued messages too. --- Sources/MactrixApp/Models/AppState.swift | 10 +++++ .../MactrixApp/Models/NetworkMonitor.swift | 41 +++++++++++++++++++ Sources/MatrixIntegration/MatrixClient.swift | 1 + 3 files changed, 52 insertions(+) create mode 100644 Sources/MactrixApp/Models/NetworkMonitor.swift diff --git a/Sources/MactrixApp/Models/AppState.swift b/Sources/MactrixApp/Models/AppState.swift index 45091f16..9009e2e7 100644 --- a/Sources/MactrixApp/Models/AppState.swift +++ b/Sources/MactrixApp/Models/AppState.swift @@ -40,6 +40,7 @@ public final class AppState { @ObservationIgnored private let accountStore: AccountStore @ObservationIgnored private var restoreTask: Task? @ObservationIgnored private var lastAppliedDockUnreadCount: Int? + @ObservationIgnored private var networkMonitor: NetworkMonitor? /// Routes clicked notifications from every account. public let notificationRouter = NotificationRouter() @@ -90,6 +91,15 @@ public final class AppState { for client in clients { startSync(client) } + networkMonitor = NetworkMonitor { [weak self] in self?.reconnectAccounts() } + } + + /// Restarts every account's sync, so accounts that went offline reconnect now that the network + /// is back instead of at their next scheduled check. Accounts already online are unaffected. + private func reconnectAccounts() { + for client in accounts { + startSync(client) + } } /// Adds a newly signed-in account and shows it in `windowState`. diff --git a/Sources/MactrixApp/Models/NetworkMonitor.swift b/Sources/MactrixApp/Models/NetworkMonitor.swift new file mode 100644 index 00000000..bc399715 --- /dev/null +++ b/Sources/MactrixApp/Models/NetworkMonitor.swift @@ -0,0 +1,41 @@ +import Foundation +import Network +import OSLog + +/// Reports when the Mac's network comes back, or switches to another interface. +/// +/// The sync service's offline mode only notices the network is back on its next scheduled check, +/// which backs off to several seconds apart. Restarting sync when this fires reconnects at once. +@MainActor +final class NetworkMonitor { + private let monitor = NWPathMonitor() + private var lastPath: NWPath? + + /// Starts calling `onReconnect` each time the network comes back or switches interface. + init(onReconnect: @escaping @MainActor () -> Void) { + monitor.pathUpdateHandler = { [weak self] path in + Task { @MainActor in + guard let self else { return } + let previous = self.lastPath + self.lastPath = path + guard let previous, Self.isReconnect(from: previous, to: path) else { return } + Logger.matrixClient.info( + "Network came back on \(path.availableInterfaces.map(\.name), privacy: .public)") + onReconnect() + } + } + monitor.start(queue: DispatchQueue(label: "Mactrix.NetworkMonitor")) + } + + deinit { + monitor.cancel() + } + + /// Whether going from `previous` to `path` means requests that failed may work now: the + /// network came back, or it moved to other interfaces, such as from Wi-Fi to Ethernet. + nonisolated static func isReconnect(from previous: NWPath, to path: NWPath) -> Bool { + guard path.status == .satisfied else { return false } + return previous.status != .satisfied + || previous.availableInterfaces.map(\.name) != path.availableInterfaces.map(\.name) + } +} diff --git a/Sources/MatrixIntegration/MatrixClient.swift b/Sources/MatrixIntegration/MatrixClient.swift index 3ff85ee4..812ca8ca 100644 --- a/Sources/MatrixIntegration/MatrixClient.swift +++ b/Sources/MatrixIntegration/MatrixClient.swift @@ -348,6 +348,7 @@ public class MatrixClient { ) await syncService.start() retryPendingSetupSteps() + await client.enableAllSendQueues(enable: true) return } do { From 6697901609339a17809fb6d37eb6ed01b633bb03 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Thu, 26 Nov 2026 19:15:56 -0500 Subject: [PATCH 33/35] Restart accounts that stay offline a few times After the network came back, an account whose requests failed again went back to offline mode. Its reachability checks then ran on a connection that had gone dead with the network change and hung until they timed out, keeping it offline for over a minute while the other accounts synced. While the network is up and an account stays offline, its sync is now restarted after 2, 4, 8, 16 and 30 seconds, each shortened by up to half at random so clients of a homeserver that went down don't retry at once. A restart cancels the hung check and tries again at once. After that, offline mode's own checks take over: a homeserver that's down can stay down for a long time, and restarting for longer would only spend battery. Going offline again or the network coming back starts another round. --- Sources/MactrixApp/Models/AppState.swift | 15 ++++++- .../MactrixApp/Models/NetworkMonitor.swift | 19 +++++++-- .../MatrixClient+Listeners.swift | 3 ++ Sources/MatrixIntegration/MatrixClient.swift | 40 +++++++++++++++++++ 4 files changed, 72 insertions(+), 5 deletions(-) diff --git a/Sources/MactrixApp/Models/AppState.swift b/Sources/MactrixApp/Models/AppState.swift index 9009e2e7..25f63beb 100644 --- a/Sources/MactrixApp/Models/AppState.swift +++ b/Sources/MactrixApp/Models/AppState.swift @@ -41,6 +41,14 @@ public final class AppState { @ObservationIgnored private var restoreTask: Task? @ObservationIgnored private var lastAppliedDockUnreadCount: Int? @ObservationIgnored private var networkMonitor: NetworkMonitor? + /// Whether the Mac has a network connection, passed on to every account. + @ObservationIgnored private var isNetworkAvailable = true { + didSet { + for client in accounts { + client.isNetworkAvailable = isNetworkAvailable + } + } + } /// Routes clicked notifications from every account. public let notificationRouter = NotificationRouter() @@ -91,7 +99,11 @@ public final class AppState { for client in clients { startSync(client) } - networkMonitor = NetworkMonitor { [weak self] in self?.reconnectAccounts() } + networkMonitor = NetworkMonitor( + onAvailabilityChange: { [weak self] isAvailable in + self?.isNetworkAvailable = isAvailable + }, + onReconnect: { [weak self] in self?.reconnectAccounts() }) } /// Restarts every account's sync, so accounts that went offline reconnect now that the network @@ -300,6 +312,7 @@ public final class AppState { } private func startSync(_ client: MatrixClient) { + client.isNetworkAvailable = isNetworkAvailable Task { await client.startSync() } } } diff --git a/Sources/MactrixApp/Models/NetworkMonitor.swift b/Sources/MactrixApp/Models/NetworkMonitor.swift index bc399715..af7a8516 100644 --- a/Sources/MactrixApp/Models/NetworkMonitor.swift +++ b/Sources/MactrixApp/Models/NetworkMonitor.swift @@ -2,22 +2,33 @@ import Foundation import Network import OSLog -/// Reports when the Mac's network comes back, or switches to another interface. +/// Reports whether the Mac has a network connection, and when it comes back or switches to +/// another interface. /// /// The sync service's offline mode only notices the network is back on its next scheduled check, -/// which backs off to several seconds apart. Restarting sync when this fires reconnects at once. +/// which backs off to several seconds apart. Restarting sync on a reconnect reconnects at once. @MainActor final class NetworkMonitor { private let monitor = NWPathMonitor() private var lastPath: NWPath? - /// Starts calling `onReconnect` each time the network comes back or switches interface. - init(onReconnect: @escaping @MainActor () -> Void) { + /// Starts reporting network changes. + /// + /// - Parameters: + /// - onAvailabilityChange: Called with whether there is a connection, whenever that changes. + /// - onReconnect: Called each time the network comes back or switches interface. + init( + onAvailabilityChange: @escaping @MainActor (Bool) -> Void, + onReconnect: @escaping @MainActor () -> Void + ) { monitor.pathUpdateHandler = { [weak self] path in Task { @MainActor in guard let self else { return } let previous = self.lastPath self.lastPath = path + if previous?.status != path.status { + onAvailabilityChange(path.status == .satisfied) + } guard let previous, Self.isReconnect(from: previous, to: path) else { return } Logger.matrixClient.info( "Network came back on \(path.availableInterfaces.map(\.name), privacy: .public)") diff --git a/Sources/MatrixIntegration/MatrixClient+Listeners.swift b/Sources/MatrixIntegration/MatrixClient+Listeners.swift index e336d0b3..6963e780 100644 --- a/Sources/MatrixIntegration/MatrixClient+Listeners.swift +++ b/Sources/MatrixIntegration/MatrixClient+Listeners.swift @@ -68,6 +68,9 @@ extension MatrixClient: SyncServiceStateObserver { Logger.matrixClient.info( "Sync state \(String(describing: state), privacy: .public), store \(self.storeID)") syncState = state + if state == .offline { + scheduleOfflineRestarts() + } if state == .running { // Setup that failed while offline can succeed now that the homeserver answers. retryPendingSetupSteps() diff --git a/Sources/MatrixIntegration/MatrixClient.swift b/Sources/MatrixIntegration/MatrixClient.swift index 812ca8ca..bae2b437 100644 --- a/Sources/MatrixIntegration/MatrixClient.swift +++ b/Sources/MatrixIntegration/MatrixClient.swift @@ -213,6 +213,7 @@ public class MatrixClient { public func reset() async throws { recentReactions.invalidate() isResettingSession = true + offlineRestartTask?.cancel() await roomSubscriptions.invalidate() // A start in flight stops at its next step; wait so it can't start syncing a signed-out // session after the stop below. @@ -338,6 +339,45 @@ public class MatrixClient { isStartingSync = false } + /// Whether the Mac has a network connection. While it doesn't, an offline account isn't + /// restarted until it comes back. + @ObservationIgnored public var isNetworkAvailable = true + + @ObservationIgnored private var offlineRestartTask: Task? + + /// How long to wait before each restart of an offline account. Each wait is shortened by up to + /// half at random, so clients of a homeserver that went down don't all retry at once. + static let offlineRestartDelays: [Duration] = [2, 4, 8, 16, 30].map { .seconds($0) } + + /// Restarts sync a few times while the account stays offline, at `offlineRestartDelays`, then + /// leaves reconnecting to the sync service's offline mode. + /// + /// The sync service's offline mode only reconnects once a reachability check succeeds, and a + /// check on a connection that went dead when the network changed hangs until it times out, + /// keeping the account offline for a minute or more. A restart cancels that check and tries + /// again at once. A homeserver that's down or unreachable can stay that way for a long time, + /// though, and offline mode keeps checking on its own, so restarting for longer would only + /// spend battery. Going offline again, or the network coming back, starts another round. + func scheduleOfflineRestarts() { + guard offlineRestartTask == nil, !isResettingSession else { return } + offlineRestartTask = Task { [weak self] in + for delay in Self.offlineRestartDelays { + try? await Task.sleep(for: delay * Double.random(in: 0.5...1)) + // A restart briefly reports running before it can fail again, so only a later check + // that finds the account online ends the restarts. Errors other than being offline + // aren't the network's, so restarting wouldn't help them. Without a network, the + // restart when it comes back takes over. + guard let self, !Task.isCancelled, [.offline, .idle].contains(self.syncState), + !self.isResettingSession, !self.authenticationFailed, self.isNetworkAvailable + else { break } + await self.startSync() + } + if !Task.isCancelled { + self?.offlineRestartTask = nil + } + } + } + private func performStartSync() async { guard !isResettingSession, !authenticationFailed else { return } // Once built, the sync service is only restarted, keeping its listeners. Its `start()` does From ac6bbd572ae1fe45143523fa46772337c2ba6c24 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Fri, 27 Nov 2026 12:37:16 -0500 Subject: [PATCH 34/35] Restart offline accounts less on battery saving or metered networks Each restart of an offline account opens a new connection and sends a full sync request, which wakes the radio and costs data. In Low Power Mode, on an expensive connection such as a phone's hotspot, or with Low Data Mode on, an offline account is now restarted only after 5 and 20 seconds instead of five times over about a minute. This is checked before each restart, so turning Low Power Mode on or joining a hotspot partway through cuts the round short. The network monitor now reports whether the connection is expensive or constrained along with whether there is one, and passes all three on to every account. --- Sources/MactrixApp/Models/AppState.swift | 12 ++++---- .../MactrixApp/Models/NetworkMonitor.swift | 20 +++++++++---- Sources/MatrixIntegration/MatrixClient.swift | 29 ++++++++++++++----- .../MatrixIntegration/NetworkConditions.swift | 18 ++++++++++++ 4 files changed, 59 insertions(+), 20 deletions(-) create mode 100644 Sources/MatrixIntegration/NetworkConditions.swift diff --git a/Sources/MactrixApp/Models/AppState.swift b/Sources/MactrixApp/Models/AppState.swift index 25f63beb..a61d4d91 100644 --- a/Sources/MactrixApp/Models/AppState.swift +++ b/Sources/MactrixApp/Models/AppState.swift @@ -41,11 +41,11 @@ public final class AppState { @ObservationIgnored private var restoreTask: Task? @ObservationIgnored private var lastAppliedDockUnreadCount: Int? @ObservationIgnored private var networkMonitor: NetworkMonitor? - /// Whether the Mac has a network connection, passed on to every account. - @ObservationIgnored private var isNetworkAvailable = true { + /// The Mac's network connection, passed on to every account. + @ObservationIgnored private var networkConditions = NetworkConditions() { didSet { for client in accounts { - client.isNetworkAvailable = isNetworkAvailable + client.networkConditions = networkConditions } } } @@ -100,8 +100,8 @@ public final class AppState { startSync(client) } networkMonitor = NetworkMonitor( - onAvailabilityChange: { [weak self] isAvailable in - self?.isNetworkAvailable = isAvailable + onConditionsChange: { [weak self] conditions in + self?.networkConditions = conditions }, onReconnect: { [weak self] in self?.reconnectAccounts() }) } @@ -312,7 +312,7 @@ public final class AppState { } private func startSync(_ client: MatrixClient) { - client.isNetworkAvailable = isNetworkAvailable + client.networkConditions = networkConditions Task { await client.startSync() } } } diff --git a/Sources/MactrixApp/Models/NetworkMonitor.swift b/Sources/MactrixApp/Models/NetworkMonitor.swift index af7a8516..04dd07e8 100644 --- a/Sources/MactrixApp/Models/NetworkMonitor.swift +++ b/Sources/MactrixApp/Models/NetworkMonitor.swift @@ -1,9 +1,10 @@ import Foundation +import MatrixIntegration import Network import OSLog -/// Reports whether the Mac has a network connection, and when it comes back or switches to -/// another interface. +/// Reports the Mac's network connection: whether there is one and what it allows, and when it +/// comes back or switches to another interface. /// /// The sync service's offline mode only notices the network is back on its next scheduled check, /// which backs off to several seconds apart. Restarting sync on a reconnect reconnects at once. @@ -15,10 +16,10 @@ final class NetworkMonitor { /// Starts reporting network changes. /// /// - Parameters: - /// - onAvailabilityChange: Called with whether there is a connection, whenever that changes. + /// - onConditionsChange: Called with the connection's conditions, whenever they change. /// - onReconnect: Called each time the network comes back or switches interface. init( - onAvailabilityChange: @escaping @MainActor (Bool) -> Void, + onConditionsChange: @escaping @MainActor (NetworkConditions) -> Void, onReconnect: @escaping @MainActor () -> Void ) { monitor.pathUpdateHandler = { [weak self] path in @@ -26,8 +27,9 @@ final class NetworkMonitor { guard let self else { return } let previous = self.lastPath self.lastPath = path - if previous?.status != path.status { - onAvailabilityChange(path.status == .satisfied) + let conditions = Self.conditions(of: path) + if previous.map(Self.conditions(of:)) != conditions { + onConditionsChange(conditions) } guard let previous, Self.isReconnect(from: previous, to: path) else { return } Logger.matrixClient.info( @@ -42,6 +44,12 @@ final class NetworkMonitor { monitor.cancel() } + nonisolated static func conditions(of path: NWPath) -> NetworkConditions { + NetworkConditions( + isAvailable: path.status == .satisfied, isExpensive: path.isExpensive, + isConstrained: path.isConstrained) + } + /// Whether going from `previous` to `path` means requests that failed may work now: the /// network came back, or it moved to other interfaces, such as from Wi-Fi to Ethernet. nonisolated static func isReconnect(from previous: NWPath, to path: NWPath) -> Bool { diff --git a/Sources/MatrixIntegration/MatrixClient.swift b/Sources/MatrixIntegration/MatrixClient.swift index bae2b437..6a4bd634 100644 --- a/Sources/MatrixIntegration/MatrixClient.swift +++ b/Sources/MatrixIntegration/MatrixClient.swift @@ -339,9 +339,9 @@ public class MatrixClient { isStartingSync = false } - /// Whether the Mac has a network connection. While it doesn't, an offline account isn't - /// restarted until it comes back. - @ObservationIgnored public var isNetworkAvailable = true + /// The Mac's network connection. Without one, an offline account isn't restarted until it + /// comes back, and on a connection that saves data it's restarted fewer times. + @ObservationIgnored public var networkConditions = NetworkConditions() @ObservationIgnored private var offlineRestartTask: Task? @@ -349,8 +349,19 @@ public class MatrixClient { /// half at random, so clients of a homeserver that went down don't all retry at once. static let offlineRestartDelays: [Duration] = [2, 4, 8, 16, 30].map { .seconds($0) } - /// Restarts sync a few times while the account stays offline, at `offlineRestartDelays`, then - /// leaves reconnecting to the sync service's offline mode. + /// The waits used instead of `offlineRestartDelays` in Low Power Mode or on a connection that + /// saves data, where each restart's new connection and full sync request cost more. + static let savingOfflineRestartDelays: [Duration] = [5, 20].map { .seconds($0) } + + /// The waits before each restart of an offline account, given the current power and network. + private var currentOfflineRestartDelays: [Duration] { + ProcessInfo.processInfo.isLowPowerModeEnabled || networkConditions.isSavingData + ? Self.savingOfflineRestartDelays : Self.offlineRestartDelays + } + + /// Restarts sync a few times while the account stays offline, at `currentOfflineRestartDelays`, + /// then leaves reconnecting to the sync service's offline mode. Turning on Low Power Mode or + /// moving to a connection that saves data partway through cuts the round short. /// /// The sync service's offline mode only reconnects once a reachability check succeeds, and a /// check on a connection that went dead when the network changed hangs until it times out, @@ -361,16 +372,18 @@ public class MatrixClient { func scheduleOfflineRestarts() { guard offlineRestartTask == nil, !isResettingSession else { return } offlineRestartTask = Task { [weak self] in - for delay in Self.offlineRestartDelays { - try? await Task.sleep(for: delay * Double.random(in: 0.5...1)) + var restarts = 0 + while let delays = self?.currentOfflineRestartDelays, restarts < delays.count { + try? await Task.sleep(for: delays[restarts] * Double.random(in: 0.5...1)) // A restart briefly reports running before it can fail again, so only a later check // that finds the account online ends the restarts. Errors other than being offline // aren't the network's, so restarting wouldn't help them. Without a network, the // restart when it comes back takes over. guard let self, !Task.isCancelled, [.offline, .idle].contains(self.syncState), - !self.isResettingSession, !self.authenticationFailed, self.isNetworkAvailable + !self.isResettingSession, !self.authenticationFailed, self.networkConditions.isAvailable else { break } await self.startSync() + restarts += 1 } if !Task.isCancelled { self?.offlineRestartTask = nil diff --git a/Sources/MatrixIntegration/NetworkConditions.swift b/Sources/MatrixIntegration/NetworkConditions.swift new file mode 100644 index 00000000..210a8682 --- /dev/null +++ b/Sources/MatrixIntegration/NetworkConditions.swift @@ -0,0 +1,18 @@ +/// What the Mac's current network connection allows. +public struct NetworkConditions: Sendable, Equatable { + /// Whether there is a connection at all. + public var isAvailable: Bool + /// Whether the connection is one the user may pay for, such as a phone's hotspot. + public var isExpensive: Bool + /// Whether the user turned on Low Data Mode for the connection. + public var isConstrained: Bool + + public init(isAvailable: Bool = true, isExpensive: Bool = false, isConstrained: Bool = false) { + self.isAvailable = isAvailable + self.isExpensive = isExpensive + self.isConstrained = isConstrained + } + + /// Whether requests that can wait should be kept to a minimum on this connection. + public var isSavingData: Bool { isExpensive || isConstrained } +} From d5ba41bd71abad7ad9a7901ac48e2634cf38f138 Mon Sep 17 00:00:00 2001 From: Justin Chung Date: Fri, 27 Nov 2026 22:19:14 -0500 Subject: [PATCH 35/35] Test how offline accounts are restarted The restart loop lived inside MatrixClient, so it couldn't run without a live sync session, and its limits had only been checked by hand. It's now an OfflineRestarter that takes the wait, the random shortening, and the checks for whether to restart and whether to save power, so tests can run it without waiting. The tests cover five restarts normally, two when saving power, Low Power Mode turning on partway through, coming back online, not restarting when it can't, the random shortening, and one round at a time. They found that turning on Low Power Mode during a wait still allowed the restart after it, one more than saving power allows. Whether to save power is now checked after the wait as well as before. --- Mactrix.xctestplan | 7 ++ Package.swift | 1 + Sources/MatrixIntegration/MatrixClient.swift | 68 ++++------- .../MatrixIntegration/OfflineRestarter.swift | 77 ++++++++++++ .../OfflineRestarterTests.swift | 113 ++++++++++++++++++ 5 files changed, 220 insertions(+), 46 deletions(-) create mode 100644 Sources/MatrixIntegration/OfflineRestarter.swift create mode 100644 Tests/MatrixIntegrationTests/OfflineRestarterTests.swift diff --git a/Mactrix.xctestplan b/Mactrix.xctestplan index 96cc2b41..35370c3f 100644 --- a/Mactrix.xctestplan +++ b/Mactrix.xctestplan @@ -41,6 +41,13 @@ "identifier" : "ContactLinkingTests", "name" : "ContactLinkingTests" } + }, + { + "target" : { + "containerPath" : "container:", + "identifier" : "MatrixIntegrationTests", + "name" : "MatrixIntegrationTests" + } } ], "version" : 1 diff --git a/Package.swift b/Package.swift index 65aeedb6..65efe71c 100644 --- a/Package.swift +++ b/Package.swift @@ -41,6 +41,7 @@ let package = Package( .product(name: "MatrixRustSDK", package: "matrix-rust-components-swift"), ] ), + .testTarget(name: "MatrixIntegrationTests", dependencies: ["MatrixIntegration"]), .target( name: "MactrixApp", dependencies: [ diff --git a/Sources/MatrixIntegration/MatrixClient.swift b/Sources/MatrixIntegration/MatrixClient.swift index 6a4bd634..9a6aaa12 100644 --- a/Sources/MatrixIntegration/MatrixClient.swift +++ b/Sources/MatrixIntegration/MatrixClient.swift @@ -213,7 +213,7 @@ public class MatrixClient { public func reset() async throws { recentReactions.invalidate() isResettingSession = true - offlineRestartTask?.cancel() + offlineRestarter.cancel() await roomSubscriptions.invalidate() // A start in flight stops at its next step; wait so it can't start syncing a signed-out // session after the stop below. @@ -343,52 +343,28 @@ public class MatrixClient { /// comes back, and on a connection that saves data it's restarted fewer times. @ObservationIgnored public var networkConditions = NetworkConditions() - @ObservationIgnored private var offlineRestartTask: Task? - - /// How long to wait before each restart of an offline account. Each wait is shortened by up to - /// half at random, so clients of a homeserver that went down don't all retry at once. - static let offlineRestartDelays: [Duration] = [2, 4, 8, 16, 30].map { .seconds($0) } - - /// The waits used instead of `offlineRestartDelays` in Low Power Mode or on a connection that - /// saves data, where each restart's new connection and full sync request cost more. - static let savingOfflineRestartDelays: [Duration] = [5, 20].map { .seconds($0) } - - /// The waits before each restart of an offline account, given the current power and network. - private var currentOfflineRestartDelays: [Duration] { - ProcessInfo.processInfo.isLowPowerModeEnabled || networkConditions.isSavingData - ? Self.savingOfflineRestartDelays : Self.offlineRestartDelays - } - - /// Restarts sync a few times while the account stays offline, at `currentOfflineRestartDelays`, - /// then leaves reconnecting to the sync service's offline mode. Turning on Low Power Mode or - /// moving to a connection that saves data partway through cuts the round short. - /// - /// The sync service's offline mode only reconnects once a reachability check succeeds, and a - /// check on a connection that went dead when the network changed hangs until it times out, - /// keeping the account offline for a minute or more. A restart cancels that check and tries - /// again at once. A homeserver that's down or unreachable can stay that way for a long time, - /// though, and offline mode keeps checking on its own, so restarting for longer would only - /// spend battery. Going offline again, or the network coming back, starts another round. + @ObservationIgnored private lazy var offlineRestarter = OfflineRestarter( + canRestart: { [weak self] in + // A restart briefly reports running before it can fail again, so only a later check that + // finds the account online ends the restarts. Errors other than being offline aren't the + // network's, so restarting wouldn't help them. Without a network, the restart when it + // comes back takes over. + guard let self else { return false } + return [.offline, .idle].contains(syncState) && !isResettingSession + && !authenticationFailed && networkConditions.isAvailable + }, + isSavingPower: { [weak self] in + ProcessInfo.processInfo.isLowPowerModeEnabled + || self?.networkConditions.isSavingData == true + }, + restart: { [weak self] in await self?.startSync() }) + + /// Restarts sync a few times while the account stays offline, fewer in Low Power Mode or on a + /// connection that saves data. Going offline again, or the network coming back, starts another + /// round. See `OfflineRestarter`. func scheduleOfflineRestarts() { - guard offlineRestartTask == nil, !isResettingSession else { return } - offlineRestartTask = Task { [weak self] in - var restarts = 0 - while let delays = self?.currentOfflineRestartDelays, restarts < delays.count { - try? await Task.sleep(for: delays[restarts] * Double.random(in: 0.5...1)) - // A restart briefly reports running before it can fail again, so only a later check - // that finds the account online ends the restarts. Errors other than being offline - // aren't the network's, so restarting wouldn't help them. Without a network, the - // restart when it comes back takes over. - guard let self, !Task.isCancelled, [.offline, .idle].contains(self.syncState), - !self.isResettingSession, !self.authenticationFailed, self.networkConditions.isAvailable - else { break } - await self.startSync() - restarts += 1 - } - if !Task.isCancelled { - self?.offlineRestartTask = nil - } - } + guard !isResettingSession else { return } + offlineRestarter.start() } private func performStartSync() async { diff --git a/Sources/MatrixIntegration/OfflineRestarter.swift b/Sources/MatrixIntegration/OfflineRestarter.swift new file mode 100644 index 00000000..8f082b15 --- /dev/null +++ b/Sources/MatrixIntegration/OfflineRestarter.swift @@ -0,0 +1,77 @@ +/// Restarts an offline account's sync a few times, then leaves reconnecting to the sync service's +/// offline mode. +/// +/// The sync service's offline mode only reconnects once a reachability check succeeds, and a +/// check on a connection that went dead when the network changed hangs until it times out, +/// keeping the account offline for a minute or more. A restart cancels that check and tries again +/// at once. A homeserver that's down or unreachable can stay that way for a long time, though, and +/// offline mode keeps checking on its own, so restarting for longer would only spend battery. +@MainActor +final class OfflineRestarter { + /// How long to wait before each restart. Each wait is shortened by up to half at random, so + /// clients of a homeserver that went down don't all retry at once. + static let delays: [Duration] = [2, 4, 8, 16, 30].map { .seconds($0) } + + /// The waits used instead of `delays` in Low Power Mode or on a connection that saves data, + /// where each restart's new connection and full sync request cost more. + static let savingDelays: [Duration] = [5, 20].map { .seconds($0) } + + private let canRestart: @MainActor () -> Bool + private let isSavingPower: @MainActor () -> Bool + private let restart: @MainActor () async -> Void + private let sleep: @MainActor (Duration) async -> Void + private let jitter: @MainActor () -> Double + private var task: Task? + + /// - Parameters: + /// - canRestart: Whether the account is still offline and a restart could help. Checked + /// after each wait; the round ends once it's `false`. + /// - isSavingPower: Whether to use `savingDelays`. Checked before and after each wait, so + /// turning it on partway through cuts the round short. + /// - restart: Restarts sync. + /// - sleep: Waits for the given time. Replaced in tests. + /// - jitter: The fraction of each delay to wait, from 0.5 to 1. Replaced in tests. + init( + canRestart: @escaping @MainActor () -> Bool, + isSavingPower: @escaping @MainActor () -> Bool, + restart: @escaping @MainActor () async -> Void, + sleep: @escaping @MainActor (Duration) async -> Void = { try? await Task.sleep(for: $0) }, + jitter: @escaping @MainActor () -> Double = { .random(in: 0.5...1) } + ) { + self.canRestart = canRestart + self.isSavingPower = isSavingPower + self.restart = restart + self.sleep = sleep + self.jitter = jitter + } + + /// Starts a round of restarts, unless one is already going. + func start() { + guard task == nil else { return } + task = Task { [weak self] in + await self?.run() + if !Task.isCancelled { + self?.task = nil + } + } + } + + /// Ends the current round. + func cancel() { + task?.cancel() + } + + private var currentDelays: [Duration] { isSavingPower() ? Self.savingDelays : Self.delays } + + /// Runs one round of restarts, returning when it ends. + func run() async { + var restarts = 0 + while restarts < currentDelays.count { + await sleep(currentDelays[restarts] * jitter()) + // Saving power may have turned on during the wait, leaving no restarts in this round. + guard !Task.isCancelled, restarts < currentDelays.count, canRestart() else { return } + await restart() + restarts += 1 + } + } +} diff --git a/Tests/MatrixIntegrationTests/OfflineRestarterTests.swift b/Tests/MatrixIntegrationTests/OfflineRestarterTests.swift new file mode 100644 index 00000000..87334060 --- /dev/null +++ b/Tests/MatrixIntegrationTests/OfflineRestarterTests.swift @@ -0,0 +1,113 @@ +import Testing + +@testable import MatrixIntegration + +/// Drives an `OfflineRestarter` with no real waiting, recording each wait and restart. +@MainActor +final class RestarterHarness { + var isOffline = true + var isSavingPower = false + var jitter = 1.0 + var waits: [Duration] = [] + var restarts = 0 + /// Called after each wait, before the restarter checks whether to restart. + var afterWait: (RestarterHarness) -> Void = { _ in } + + lazy var restarter = OfflineRestarter( + canRestart: { [unowned self] in isOffline }, + isSavingPower: { [unowned self] in isSavingPower }, + restart: { [unowned self] in restarts += 1 }, + sleep: { [unowned self] duration in + waits.append(duration) + afterWait(self) + }, + jitter: { [unowned self] in jitter }) +} + +@MainActor +struct OfflineRestarterTests { + @Test func restartsFiveTimesThenStops() async { + let harness = RestarterHarness() + await harness.restarter.run() + + #expect(harness.restarts == 5) + #expect(harness.waits == [2, 4, 8, 16, 30].map { .seconds($0) }) + } + + @Test func restartsTwiceWhenSavingPower() async { + let harness = RestarterHarness() + harness.isSavingPower = true + await harness.restarter.run() + + #expect(harness.restarts == 2) + #expect(harness.waits == [5, 20].map { .seconds($0) }) + } + + @Test func savingPowerPartwayThroughCutsTheRoundShort() async { + let harness = RestarterHarness() + // Low Power Mode turns on during the third wait: two restarts are already as many as saving + // power allows, so none follow it. + harness.afterWait = { harness in + if harness.waits.count == 3 { harness.isSavingPower = true } + } + await harness.restarter.run() + + #expect(harness.restarts == 2) + #expect(harness.waits.count == 3) + } + + @Test func savingPowerAfterOneRestartAllowsOneMore() async { + let harness = RestarterHarness() + harness.afterWait = { harness in + if harness.waits.count == 1 { harness.isSavingPower = true } + } + await harness.restarter.run() + + // The second wait is the saving one. + #expect(harness.restarts == 2) + #expect(harness.waits == [.seconds(2), .seconds(20)]) + } + + @Test func stopsOnceOnline() async { + let harness = RestarterHarness() + harness.afterWait = { harness in + if harness.waits.count == 2 { harness.isOffline = false } + } + await harness.restarter.run() + + #expect(harness.restarts == 1) + #expect(harness.waits.count == 2) + } + + @Test func doesNotRestartWhenItCannot() async { + // Covers no network, a reset in progress, or a failed sign-in: `canRestart` is false. + let harness = RestarterHarness() + harness.isOffline = false + await harness.restarter.run() + + #expect(harness.restarts == 0) + #expect(harness.waits.count == 1) + } + + @Test func waitsAreScaledByJitter() async { + let harness = RestarterHarness() + harness.jitter = 0.5 + await harness.restarter.run() + + #expect(harness.waits == [1, 2, 4, 8, 15].map { .seconds($0) }) + } + + @Test func startRunsOneRoundAtATimeAndAnotherAfterItEnds() async { + let harness = RestarterHarness() + harness.restarter.start() + harness.restarter.start() + while harness.restarts < 5 { await Task.yield() } + // Let the finished round clear itself so the next start runs. + for _ in 0..<10 { await Task.yield() } + #expect(harness.restarts == 5) + + harness.restarter.start() + while harness.restarts < 10 { await Task.yield() } + #expect(harness.restarts == 10) + } +}