Main Account and Session Domain
Overview
The main account/session domain is the object graph that connects persisted local state, MTProto transport, per-account server configuration, per-session data/API helpers, and windows. Main::Domain in Telegram/…/main_domain.h and Telegram/…/main_domain.cpp is the top-level owner for this area: it owns a Storage::Domain, a vector of indexed Main::Account objects, the active account pointer, and aggregate unread badge state. Startup enters through Domain::start(passcode), which delegates account loading to Storage::Domain::start(), receives accounts back through accountAddedInStorage(), records the stored active index through activateFromStorage(), then activateAfterStarting() watches every account session and activates either the stored account or the first loaded account.
Main::Account in Telegram/…/main_account.h and Telegram/…/main_account.cpp is the per-login-slot owner. Each account owns its Storage::Account, an MTP::Instance, a Main::AppConfig, and at most one Main::Session. Account::start() creates AppConfig, constructs the MTProto instance from either persisted authorization/config or the domain fallback production config, starts app-config refreshes, and wires proxy/session watchers. Storage flows through prepareToStart(), prepareToStartAdded(), setMtpAuthorization(), setSessionFromStorage(), and serializeMtpAuthorization(): persisted auth keys, pending keys-to-destroy, main DC id, self user id, serialized self user, and SessionSettings are staged until startMtp() can create the MTProto instance and, if a user id exists, create the session.
Main::Session in Telegram/…/main_session.h and Telegram/…/main_session.cpp is the authenticated runtime object. Its constructor builds the per-session service graph in dependency order: Data::Changes, ApiWrap, API updates and send progress, MTProto downloader/uploader, storage facade, Data::Session, sticker packs, SendAsPeers, bot attach webview, recent/top-peer and feature data components, settings search helpers, support helpers, and cached reaction icons. It immediately requests terms/full-self information, attaches the user's phone to MTProto, tracks self updates for Storage::Account::writeSelf(), defers heavy sticker/gif reads with crl::on_main_queue(), tracks the session in the global download manager, listens to app-config refreshes, and initializes blocked-peer markers from the API. Session-owned windows register through Session::addWindow(), and tryResolveWindow() may activate the account through Domain::activate() before returning a primary or matching window.
Lifecycle teardown runs in the reverse direction. Account::~Account() flushes pending session settings and search suggestions before destroySession(Quitting). Explicit logout goes through Account::logOut()/loggedOut(): MTProto logout completes, media playback is cleared, destroySession(LoggedOut) fires sessionChanges() by setting _sessionValue to null, Session::finishLogout() clears data/local storage, and Storage::Account::reset() removes account-local persisted data. Domain::watchSession() responds to a null session by scheduling unread-badge recomputation, closing separate windows for that account, and eventually calling removeRedundantAccounts(). removeRedundantAccounts() deliberately retries if any account is currently inside Account::destroySession() to avoid erasing an account from a nested event dispatch while its own stack frame is active.
Account activation is both a UI and persistence boundary. Domain::activate() switches the active account, starts forwarding its sessionValue() into _activeSessions, remembers the previous authed active index, schedules Storage::Domain::writeAccounts() when the stored active account changes, and drops inactive session-less accounts when switching away from an unauthenticated slot. Domain::orderedAccounts() sorts accounts using Core::App().settings().accountsOrder(), whose entries are Session::uniqueId() values (user id plus a test-DC bit). Adding accounts through Domain::add() clones an MTProto config from an existing account in the same environment when possible, or uses Core::App().fallbackProductionConfig() for production, then calls Storage::Domain::startAdded() and starts watching the new account. If the second account is added, Core::Settings::mainMenuAccountsShown is enabled and global settings are saved.
Application-wide settings live in Core::Settings (Telegram/…/core_settings.h, Telegram/…/core_settings.cpp). This object is not owned by Main::Domain, but the domain/session code reads and mutates it through Core::App().settings(). It serializes UI, notification, media, calls, translation, account ordering, proxy, passcode/system-unlock, tonsite token, and generic preference state into one binary blob. Settings::addFromSerialized() is migration-heavy: it reads many legacy fields conditionally, translates older session/global settings into current fields, validates enum values before assigning, and calls Ui::GL::ForceDisable() if stored OpenGL disablement is set. Settings::resetOnLastLogout() resets user-facing app preferences while preserving selected low-level values such as platform notification defaults and the screen-reader disabled pref.
Proxy settings are a nested part of Core::Settings. SettingsProxy in Telegram/…/core_settings_proxy.h and Telegram/…/core_settings_proxy.cpp stores proxy mode (system/enabled/disabled), selected proxy, proxy list, IPv6/calls flags, IP-warning state, and proxy-rotation preferences. Account::watchProxyChanges() listens to Core::Application::proxyChanges() and restarts active MTProto instances; for MTProto/Web proxy host-port changes it also reinitializes the main DC connection. SettingsProxy::connectionTypeChangesNotify() is invoked from Account::startMtp() when MTProto main DC connection state changes, allowing settings UI to observe connection type changes.
Per-session settings are Main::SessionSettings (Telegram/…/main_session_settings.h, Telegram/…/main_session_settings.cpp). These settings are owned by Main::Session, serialized by SessionSettings::serialize(), persisted by Session::saveSettings() via Storage::Account::writeSessionSettings(), and flushed by Session::saveSettingsNowIfNeeded() during account destruction. They include per-session UI state (archive collapsed/in main menu, selector tab, hidden group sticker/emoji sections, hidden pinned messages keyed by peer/topic/monoforum), support-mode settings, auto-download config, per-thread ringtone volumes, voice-transcription ratings, unreviewed authorizations, login-email setup state, moderated common groups, phone-hidden state, and extra favorite reactions. addFromSerialized() keeps backward compatibility with older layouts and moves legacy app-wide settings back into Core::Settings for old blobs.
Server-side app configuration is per account. Main::AppConfig in Telegram/…/main_app_config.h and Telegram/…/main_app_config.cpp owns an MTP::Sender, fetches help.getAppConfig, stores JSON object values by key, caches the server hash, and refreshes hourly or immediately on forced refresh. It starts after account MTProto main-session availability via Account::mtpMainSessionValue(), so a main DC change recreates the sender and refreshes configuration. Consumers use typed get() helpers with local fallbacks. Session::appConfigRefreshed() reads account-freeze fields, premium-purchase availability, and message edited-date display from this store. Telegram/…/main_app_config_values.cpp contains a small derived lookup, AppConfig::FragmentLink(), which searches whitelisted_domains for a fragment domain.
The small session controllers under Telegram/SourceFiles/main/session/** add session-aware behaviors to UI/API helpers. SessionShow in Telegram/…/session_show.h and .cpp wraps a generic Ui::Show with a Main::Session; showFrozenError() blocks an action by showing the frozen-account info box when Session::frozen() is set from app config. SendAsPeers in Telegram/…/send_as_peers.h and .cpp is owned by Session and caches channel send-as lists per (peer, type) key. It refreshes at most every 30 seconds unless forced by rights/signature changes, requests channels.getSendAs for messages, paid reactions, and live stories, persists the default send-as choice with messages.saveDefaultSendAs, and falls back to either the session user or the anonymous channel peer.
Cloud password helpers in Telegram/…/core_cloud_password.h and .cpp are stateless support code for account/security flows. They parse Telegram password KDF algorithms, validate new algorithms by extending salts with local randomness, compute Telegram SRP password hashes/checks, compute secure-secret hashes, and parse account.password into CloudPasswordState with flags such as hasPassword, hasRecovery, notEmptyPassport, outdatedClient, patterns, and pending reset date. Telegram/…/cached_webview_availability.h provides a process-wide cached Webview::Availability() result for startup-sensitive webview availability checks.
Coupling
- If account/session destruction changes in Telegram/…/main_account.cpp, verify Telegram/…/main_domain.cpp still handles synchronous
sessionChanges()safely.Account::destroySession()fires listeners before_sessionis freed, andDomain::removeRedundantAccounts()relies onAccount::destroyingSession()to avoid erasing the account during nested main-loop dispatch. - If
Session::uniqueId()orAccount::willHaveSessionUniqueId()changes in Telegram/…/main_session.cpp or Telegram/…/main_account.cpp, update account ordering logic inDomain::orderedAccounts()and persisted_accountsOrdersemantics in Telegram/…/core_settings.h; production/test disambiguation is encoded by OR-ing the user id with the test-DC bit. - If the binary layout in Telegram/…/main_session_settings.cpp or Telegram/…/core_settings.cpp changes, update both the explicit size calculation and the write/read order. Both serializers reserve and assert exact byte sizes, and deserializers depend on append-only conditional reads to keep old settings loadable.
- If app-config keys are renamed or their fallback semantics change in Telegram/…/main_app_config.cpp, check the session consumers in Telegram/…/main_session.cpp and the helper in Telegram/…/main_app_config_values.cpp; the getters silently return fallbacks on missing or wrong-typed JSON values, so server/client key drift may not fail loudly.
- If proxy mode, selected proxy, or proxy list representation changes in Telegram/…/core_settings_proxy.cpp, verify account-level MTProto restart behavior in Telegram/…/main_account.cpp. Host/port changes for MTProto and Web proxies trigger
reInitConnection(mainDcId), while other proxy changes only restart the instance. - If per-session window registration changes in Telegram/…/main_session.cpp, verify account activation and separate-window behavior in Telegram/…/main_domain.cpp;
Session::tryResolveWindow()can activate its account as a side effect when no window is currently registered or a peer-specific window is requested. - If
SendAsPeerscache keys or refresh rules change in Telegram/…/send_as_peers.cpp, verify callers distinguish message send-as, paid reactions, and video streams. Only message refreshes also fetch paid-reaction data, and non-channel peers fall back to the session user except for video-stream requests. - If cloud password algorithm parsing changes in Telegram/…/core_cloud_password.cpp, verify callers handle
CloudPasswordState::outdatedClientandunknownAlgorithm; compute functions callUnexpected()for null algorithms and should only receive validated Telegram KDF data.
Risks
- Telegram/…/main_account.cpp and Telegram/…/main_domain.cpp: session teardown is re-entrant. The history contains
14861f3b0 Fixed account deleted from inside its own teardownand5a7639be8 Fix crash on forced logout with pending requests; removing_destroyingSessionor the retry inDomain::removeRedundantAccounts()can free an account whileAccount::destroySession()is still on the stack. - Telegram/…/main_app_config.cpp:
AppConfig::callsDisabledForSession()computesauthorizationsas null when no session exists but still dereferences it as the fallback argument. Callers currently need an existing session; using this getter during account startup or after logout would crash. - Telegram/…/main_session_settings.cpp and Telegram/…/core_settings.cpp: binary settings migration is fragile because many legacy fields are skipped conditionally and some old global settings are migrated from session settings into
Core::Settings. The history includesb6b6e1889 Don't break old settings reading, so adding/removing fields without preserving read order can make older user data fail to load or silently map values to the wrong setting. - Telegram/…/main_session.cpp: constructor side effects depend on
_sessionbeing assigned after construction. The code defers local sticker reads becauseStorage::AccountcallsMain::Account::session()and cannot be used duringSessionconstruction; moving those reads back into the constructor body beforeAccount::_sessionis set can trigger invalid session access.