Repository navigation
Add multi-account support - #143
justin13888 wants to merge 35 commits into
Conversation
|
Finally verified all the individual checks on checklist one-by-one. |
8a97462 to
d7ef70e
Compare
|
Made some more updates so now blocked on CI. I'd like to merge in this so I can proceed with other bugs that I noticed. I did all the testing again but it may be good to test on another device once more. I installed a release build using this but I think there should be documented commands for these standard things so there would be no discrepancies: Also note that I skipped translations on some new strings (they're marked so they can be localized). |
|
Thank you for the PR! The changes are very large and it touches on many parts of the application so it will take some time to properly review. I've only quickly tried to run it locally and then skimmed some of the code (I'm still trying to understand it all). First, a small comment. I really like the user selection drop down, and it's very similar to what I had in mind myself. I've actually left the bottom view with the text "Sync: online" as a placeholder for exactly this dropdown. Can you move it to that spot instead of the placeholder text? Multiple accounts simultaneouslyI've noticed that it doesn't support presenting multiple accounts simultaneously (in different windows). I'd eventually really like that to be supported. Such that the I can see the benefit for implementing this in a separate PR (if that is easier) as this one is already very large. But I want to be sure that we make the implementation ready to support this without issues. Notifications from different accountsWhen testing it, I sometimes got notifications from my other account (the one not actively selected in the dropdown). But when I clicked the notification, the window showed the "you have been logged out" popup asking me to log in again, and then the app crashed. I tried reopening the app and the same happended again. I haven't traced down what exactly is happening here, and the crash stack trace was unfortunately not very useful. I'm wondering if we can actually simplify the implementation already by moving the active account to the // From AppState.swift class
public var matrixClient: MatrixClient? {
accounts.first { $0.storeID == activeAccountID }
}Then opening a notification simply becomes creating a new window (or reusing an existing one) configured with the right These are just my initial thoughts. I still have to go through all the changes more throughly. |
Noted
Most Matrix desktop clients that I use on other platforms design the UI so it toggles in between, which is consistent with apps like Discord. I think there is a discussion about which modes we support, such as:
I'd just fold it into this PR (just review the new commits after the current 13) so it can be tested as one unit because this is just an extra app setting change. @viktorstrate could you list the "window modes" you want for multi-account feature? I'll work on it this week. |
I will check. |
|
I couldn't reproduce the notification → signed out → crash on the current head (eb91c2b). with 3 OAuth accounts on tuwunel: clicking inactive-account notifications switches account and opens the room fine. Could you check:
log stream --level debug --predicate 'subsystem BEGINSWITH "dk.qpqp.mactrix"My suspicion: accounts signed in during a session don't save refreshed OAuth tokens to the keychain (this also affects main's first login). On servers that rotate refresh tokens, the next launch then gets a hard logout. If so, you'll need to sign that account in again once after the fix. |
|
Thank you for trying to troubleshoot it. I'll investigate it myself more to see if I can reproduce it reliably and find the cause.
I was thinking that each window can load an account independently of the other windows. And to keep window restoration such that if the app is quit and reopened, then all the same windows will show up again in the spot the user left them (including the active account and the selected room). This is already how the app works for the selected room in each restored window. When creating a new window (From Does this design make sense, what do you think? |
I understand what you mean. I'll push any updates to this PR directly since the changes required mostly rewrites the current diff. Ownership of the clients belongs to the AppState regardless and windows have weak references to the clients. I'd like one setting that supports both of our workflows: you prefer one window per account, and I prefer a single window that switches accounts. Both run on the same per-window model. The setting only changes where things for another account open: in the current window or in that account's own window. That covers notification clicks, verification requests, the switcher, the Account menu and Matrix links. Questions
Defaults (please let me know if there is any that you'd change)
|
|
I see. I agree with you in opening notifications in the same window. I don't think we need a setting for that. I was mainly talking about supporting multiple windows if the user explicitly opens them. |
|
Ahh kk. Just to confirm before I start, so it's one per-window model with no setting: anything for another account (e.g., notifications, verification, links, Account menu) switches the frontmost window, and extra windows only come from ⌘ N/⌘ T. I'll leave the unified room list out of this PR. One detail: if another window is already showing that account, I'd bring that window forward rather than switching the frontmost one, and only switch the frontmost window when no window shows the account. Does that make sense? |
|
Yes that sounds like a good design |
eb91c2b to
2ea36ef
Compare
Replace the single "UserSession" keychain item with one item per account
("session.<storeID>"), 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.
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.
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.
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.
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.
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.
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".
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
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.
Add the switcher's strings for a verification request in an account no window shows to the catalog.
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.
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.
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.
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.
"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.
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.
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.
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.
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.
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.
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.
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.
f94665c to
d5ba41b
Compare
Summary
Lets Mactrix stay signed in to several Matrix accounts at once. Each window shows one account, and every account keeps syncing in the background, so notifications and the Dock badge cover all of them.
Behaviour
Migration
storeID, so no files move.Testing
xcodebuild testpasses on every commit. New tests:AccountStoreTests,StoreDirectoriesTests,WindowStateAccountTests,WindowAccountFallbackTests,NotificationRouterTests,NotificationWindowTests,OpenFileLimitTests, andOfflineRestarterTestsin a newMatrixIntegrationTeststarget (added to the test plan).main, adding/switching/signing out accounts, notifications across accounts, revoked sessions, and going offline and back online with queued messages.Not covered