AyuGram Custom Features
Overview
AyuGram's custom desktop layer lives under Telegram/SourceFiles/ayu/** and is initialized through Telegram/…/ayu_infra.cpp. AyuInfra::init() attaches the fork-specific pieces to Telegram Desktop startup in this order: language overlays (ayu_lang.cpp), the SQLite-backed Ayu database (data/ayu_database.cpp), UI style settings copied into Telegram UI globals (ayu_settings.cpp via AyuUiSettings and Ui::SetAppliedBubbleRadius), platform icon replacement on Windows, the periodic ghost-mode worker (ayu_worker.cpp), the remote configuration/badge manager (utils/rc_manager.cpp), and the translation manager (features/…/ayu_translator.cpp). The public README files describe the major shipped features as ghost mode, message history/anti-recall, filters, streamer mode, local Premium, translator, appearance customization, and media preview; those are implemented as hooks into existing Telegram subsystems rather than as a separate application shell.
Persistent Ayu settings are centralized in Telegram/…/ayu_settings.h and Telegram/…/ayu_settings.cpp. They are stored as tdata/ayu_settings.json, using nlohmann::json from Telegram/…/json.hpp and json_ext.hpp. Settings are exposed as rpl::variable values so UI sections and patched Telegram code can observe changes. Important groups include per-account/global ghost-mode switches, deleted/edited message storage, regex filters and shadow-ban ids, appearance toggles, drawer/tray visibility, message context-menu visibility, translation provider selection, message-shot options, streamer mode, and badge/app-icon behavior. AyuSettings::load() migrates old flat ghost-mode keys into ghostModeSettings, validates enum/range values, and respects the legacy cGhost() flag by forcing the global ghost account into no-read/no-online mode. Many setters only save JSON; some have side effects into Telegram Desktop subsystems, for example setHideNotificationBadge() refreshes app/tray counters, setTranslationProvider() resets the custom translation cache, setAvatarCorners() updates AyuUiSettings, and setStreamerMode() calls AyuFeatures::StreamerMode::apply().
Message history and anti-recall state is stored separately in tdata/ayudata.db, defined in Telegram/…/ayu_database.cpp with bundled sqlite_orm and SQLite under Telegram/SourceFiles/ayu/libs/sqlite/**. Tables store schema version, deleted messages, edited message revisions, deleted dialogs, regex filters, filter exclusions, and read-spy records; database access is guarded by one process-wide mutex. Telegram/…/messages_storage.cpp maps live HistoryItem objects into DeletedMessage and EditedMessage rows by extracting the account id, dialog id, topic id, Telegram message id, date/edit date, flags, sender, post author, text, and serialized text entities. The mapping currently stores text-centric rows and leaves media fields mostly as placeholders. Telegram/SourceFiles/ayu/ui/message_history/** then builds a custom history section that renders those stored rows as non-history/admin-log-like HistoryItem views with a search bar, pagination, and generated text messages.
Ghost mode is split between settings, helper hooks, and a small worker. GhostModeAccountSettings in ayu_settings.cpp computes isGhostModeActive() from read receipt, story read, online packet, upload progress, and offline-after-online settings, with optional per-account override through _useGlobalGhostMode. Telegram/…/telegram_helpers.cpp provides read helpers such as MarkAsReadThread(), readHistory(), markReadAfterAction(), and processMessageDelete(); these are the paths reviewers should inspect when Telegram read/delete behavior changes. Telegram/…/ayu_worker.cpp runs every three seconds, walks Core::App().domain().accounts(), and for accounts whose ghost settings require sendOfflinePacketAfterOnline, sends MTPaccount_UpdateStatus(MTP_bool(true)) after the account was seen online. AyuWorker::markAsOnline() is called after manual reads and when ghost mode is enabled so the worker knows to send an offline status packet again.
Regex filters and shadow bans attach to history rendering through Telegram/SourceFiles/ayu/features/filters/**. Filter definitions and per-dialog exclusions are persisted in RegexFilter and RegexFilterGlobalExclusion rows in data/ayu_database.cpp. features/…/filters_cache_controller.cpp compiles enabled ICU regex patterns into a shared snapshot, tracks per-message filtered results, remembers dialogs with hidden blocked/shadow-banned messages, and emits an update stream for UI refreshes. features/…/filters_controller.cpp decides whether a HistoryItem is hidden: it ignores outgoing messages, checks blocked users and shadow-ban ids from AyuSettings, extracts text/buttons/message type via features/…/filters_utils.cpp, and applies per-dialog patterns before shared patterns minus exclusions. Import/export and publishing of filters are also in filters_utils.cpp; it supports backup version 2 JSON, peer hint resolution through Telegram API calls, and publishing to https://dpaste.com/api/v2/. The settings UI for these controls is under ui/…/settings_filters.cpp and ui/settings/filters/**, while quick-add/shadow-ban actions are injected by ui/…/context_menu.cpp.
Custom context-menu behavior is concentrated in Telegram/…/context_menu.cpp. It adds peer-level AyuGram submenus for filters and deleted-message history, a jump-to-beginning action, discussion-channel open action, shadow-ban toggles, delete-my-messages automation, edit-history links, hide-message, user-message search, message-details submenus, repeat-message, read-until, burn/read self-destructing media, and quick regex filter creation. These actions route back into Telegram Desktop controllers (Window::SessionController, History, ApiWrap, Data::Session) and into Ayu storage/state (AyuMessages, AyuState, FiltersController, AyuForward). Telegram/…/ayu_state.cpp holds process-only hidden message ids and the story-close ghost-mode reset marker; hidden messages are destroyed from the live history but not persisted across restarts.
Custom forwarding lives in Telegram/SourceFiles/ayu/features/forward/**. features/…/ayu_forward.cpp decides when Telegram's regular forwarding is insufficient, notably for deleted messages, no-forward peers/items, and TTL media, then chunks selected items, reports state through peer updates, downloads/reuploads media, and sends reconstructed messages through Api::SendAction. features/…/ayu_sync.cpp provides synchronous download/upload/send helpers around Telegram media objects, including document download coalescing with latches and timeouts. features/…/ayu_forward_rich.cpp handles premium rich messages by serializing/pruning rich-page blocks and remapping reuploaded photos/documents. The "repeat message" context-menu action in ui/…/context_menu.cpp is the main user-facing entrypoint into this forwarding stack.
Translation customization wraps Telegram Desktop's translate-provider abstraction. Telegram/…/settings_general.cpp lets users choose Telegram, Google, Yandex, or the platform-native provider if available. For Google/Yandex, Telegram/…/ayu_translate_provider.cpp creates a Ui::TranslateProvider backed by TranslateManager in features/…/ayu_translator.cpp. The manager accepts Telegram-style MTPmessages_TranslateText inputs, resolves either explicit text or message ids, caches up to 500 translations by text/message and target language, then delegates to features/…/google.cpp or yandex.cpp. Those implementations use QNetworkAccessManager, 15-second per-request timers, HTML/text conversion helpers in html_parser.cpp, retry/concurrency logic in implementations/base.cpp, and external endpoints translate-pa.googleapis.com and translate.yandex.net.
Custom UI and settings are organized under Telegram/SourceFiles/ayu/ui/**. ui/…/settings_main.cpp registers the AyuGram top-level settings section under Telegram settings and links to AyuGram resources; subpages in settings_ayu.cpp, settings_general.cpp, settings_appearance.cpp, settings_chats.cpp, settings_other.cpp, and settings_filters.cpp are built with wrappers from ui/…/ayu_builder.cpp so each control can be searchable/highlightable by ids like ayu/translationProvider. ayu_url_handlers.cpp uses that search registry in HandleAyuSettings() so tg:///local links can open a specific Ayu setting and highlight the control. Custom widgets and boxes include icon/font/theme selectors, message-shot configuration, import filters, donate dialogs, saved music, image preview, avatar-corner preview, custom userpic painting, toasts, and menu rows with subtext.
Message Shot is implemented in Telegram/SourceFiles/ayu/features/message_shot/** and ui/boxes/message_shot_box.*. It takes selected HistoryItems from either HistoryView::ListWidget or HistoryInner, builds a temporary wide-mode chat style, preloads needed media thumbnails/photos for up to three seconds, renders the selected message views into a transparent QImage, trims empty space, adds padding/background according to MessageShotSettings, and exposes theme selection through message_shot_theme_state.cpp. The render path marks takingShot so patched history view code can call MessageShot::ignoreRender() for dates, reactions, and header decorations.
Streamer mode is a thin platform abstraction in Telegram/SourceFiles/ayu/features/streamer_mode/**. streamer_mode.cpp enumerates Telegram windows and top-level widgets, tags them with an AyuStreamerModeHidden Qt property, and calls platform code to exclude or include windows from capture. Windows uses SetWindowDisplayAffinity(..., WDA_EXCLUDEFROMCAPTURE) in platform/…/streamer_mode_win.cpp; macOS sets NSWindow.sharingType in platform/mac/streamer_mode_mac.mm; Linux is currently a no-op in platform/…/streamer_mode_linux.cpp.
Remote Ayu metadata and badges are handled by Telegram/…/rc_manager.cpp and helper functions in utils/telegram_helpers.cpp. RCManager::start() fetches https://update.ayugram.one/rc/current/desktop2 hourly, falling back once to https://api.exteragram.app/api/v1/profiles/compact, and loads developer/channel/supporter/custom-badge ids plus donation defaults. telegram_helpers.cpp turns that state into Extera/Ayu badge content and toast click handlers. The same helper file also contains reviewer-relevant utility code for dialog id normalization, DC/media metadata display, user/chat id resolving through bots/API, Zalgo filtering support, and anti-recall/read helpers.
URL and external-link handling is in Telegram/…/ayu_url_handlers.cpp. ResolveUser() and ResolveChat() parse id= parameters, use already-loaded peers when possible, otherwise call Ayu helper resolution and show peer info/history. HandleAyu() opens the Ayu settings page for /settings, /preferences, or /prefs; HandleSupport() opens the donation info box; HandleAyuSettings() opens and highlights individual Ayu settings based on the s= parameter. TryHandleSpotify() rewrites Spotify web URLs into spotify: scheme links. IsWebUrl() and IsUnsafeExternalUrl() are guard helpers; the latter blocks empty/short schemes, local file/share/search/script schemes, and ms-* schemes before handing URLs to external applications.
The WEB proxy documents in docs/web-proxy-plan.md and docs/web-proxy-test-plan.md describe a Telegram Desktop transport feature rather than the Ayu UI modules, but they are owned with this area because they document custom fork behavior. The plan specifies MTP::ProxyData::Type::Web as type code 4, a hidden process-wide native WebView carrier, a worker-thread transport, MTProxy-secret reuse, tg://webproxy/https://t.me/webproxy import links, hostname/base-path validation, browser fallback, and the invariant that Telegram Desktop itself opens no external MTProto socket while WEB is active. The test plan is a release gate for server-ready WEB proxy validation, including native WebView and explicit browser fallback checks, canonical host/link validation, network-origin verification, reconnect/lifecycle behavior, and no-secret logging requirements.
Coupling
- If
AyuSettingsgains, renames, or removes a persisted field in Telegram/…/ayu_settings.h, update bothto_json()andfrom_json()in Telegram/…/ayu_settings.cpp, validation defaults, and any settings UI ids inTelegram/SourceFiles/ayu/ui/settings/**; ayu_url_handlers.cpp can deep-link to settings by search-registry id. - If Telegram Desktop changes
HistoryItem,PeerId,MsgId, text entities, or media fields, verify Telegram/…/messages_storage.cpp, Telegram/…/ayu_mapper.cpp, and Telegram/…/history_item.cpp; anti-recall/edit history reconstructs stored rows from these assumptions and can silently lose sender, topic, or entity fidelity. - If read receipt, unread mention/reaction, online status, or story-read behavior changes upstream, review Telegram/…/telegram_helpers.cpp, Telegram/…/ayu_worker.cpp, Telegram/…/ayu_state.cpp, and
GhostModeAccountSettingsin ayu_settings.cpp; ghost mode depends on these helpers being used instead of direct Telegram read/status calls. - If history rendering starts hiding/destroying items differently, verify
Telegram/SourceFiles/ayu/utils/telegram_helpers.cpp::isMessageHidden(), features/…/filters_controller.cpp, features/…/filters_cache_controller.cpp, and ayu_state.cpp; filters and manual hide state cache results by peer/message id and callHistoryItem::destroy()for visual removal. - If filter JSON format changes, update Telegram/…/filters_utils.cpp together with Telegram/…/entities.h, data/ayu_database.cpp, and the import/export UI under
ui/settings/filters/**; backup version, UUID parsing, dialog id resolution, and exclusions are all hand-parsed. - If Telegram's forwarding, media upload/download, rich message, or no-forward APIs change, inspect Telegram/…/ayu_forward.cpp, ayu_sync.cpp, ayu_forward_rich.cpp, and the repeat-message action in ui/…/context_menu.cpp; the custom forwarding path bypasses ordinary forwarding by downloading and re-sending media and reconstructed rich content.
- If Telegram's translate provider interface changes, update Telegram/…/ayu_translate_provider.cpp and ayu_translator.cpp together; they translate between
Ui::TranslateProviderRequestandMTPmessages_TranslateTextsemantics and currently report custom provider failures as localRESPONSE_PARSE_FAILEDerrors. - If platform window creation or top-level widget ownership changes, verify Telegram/…/streamer_mode.cpp and platform files; streamer mode enumerates existing top-level widgets and depends on Qt
winId()/window handles being valid. - If badge/profile UI types or Extera badge enum values change, check Telegram/…/telegram_helpers.cpp and utils/rc_manager.cpp; remote RC JSON is mapped into
Info::Profile::Badge::Contentand toast/profile badge display. - If WEB proxy code or proxy serialization changes outside this doc's source files, reconcile it with docs/web-proxy-plan.md and docs/web-proxy-test-plan.md; the docs assert exact
ProxyDatafield meanings, link formats, hidden-WebView behavior, and security invariants.
Risks
- Telegram/…/messages_storage.cpp deliberately records mostly text and leaves media serialization fields unset (
mediaPathis"/", document/thumb fields are TODOs). If reviewers expect anti-recall history to preserve deleted media, this path currently only reliably reconstructs text and entities. - Telegram/…/ayu_settings.cpp uses one namespace-scope
rpl::lifetimefor allGhostModeAccountSettingsreactivity because per-object lifetime was noted as broken. If settings objects are reset or moved, ghost-mode-active computation can retain surprising lifetime behavior. - Telegram/…/ayu_worker.cpp sends
MTPaccount_UpdateStatus(MTP_bool(true))every three seconds when conditions match and tracks accounts only by bare user id in a process-local map. A mistaken ghost-mode setting or account lifecycle change can repeatedly emit offline packets for the wrong session timing. - Telegram/…/filters_controller.cpp compiles and executes user-supplied ICU regexes against message text, URLs, buttons, and type tags. Complex expressions can make message rendering/filter evaluation expensive, and invalid patterns only log failures during cache building/matching.
- Telegram/…/google.cpp embeds a Google API key and both Google/Yandex translators rely on unofficial public endpoints. Endpoint, response-shape, quota, or key changes will make custom translation fail through
TranslateManager::triggerFail()in Telegram/…/ayu_translator.cpp. - Telegram/…/rc_manager.cpp trusts remote RC JSON to populate developer/supporter/custom badge ids and donation metadata, with a fallback endpoint. Bad or compromised responses affect badge/donation UI until the next successful fetch, though default developer/channel sets are compiled in.
- Telegram/…/streamer_mode_linux.cpp is a no-op. Enabling streamer mode on Linux changes Ayu settings/UI state but does not prevent screen capture.
- docs/web-proxy-plan.md documents a security-sensitive invariant: while WEB proxy is active, Telegram Desktop must not open external MTProto sockets and the MTProxy secret must never enter HTML or JavaScript. Any implementation drift outside the docs can break that invariant even if the Ayu UI still offers the feature.