Introducing a new way to review your PRs.

Read the announcement

ayugram / ayugram4a

Just an exteraGram based client with ToS breaking features in mind.

View on GitHub

13 documents · Updated Nov 19, 2026

docs / chat-screen-message-flow

Chat Screen Message Flow

Overview

Owned coverage: TMessagesProj/…/ChatActivity.java, Chat*.java, Topic*.java, Topics*.java, DialogsActivity.java, ShareActivity.java, FilteredSearchView.java, Filter*.java, Filters*.java, chat/dialog cells under TMessagesProj/…/Chat*.java and Dialog*.java, and chat-specific components under TMessagesProj/…/Chat*.java, Dialogs*.java, MentionsContainerView.java, Message*.java, and EmbedBottomSheet.java. This doc is for the user-visible chat/dialog/topic flow, not for the backend message controllers themselves.

Dialog-to-chat navigation starts in TMessagesProj/…/DialogsActivity.java. Its createView() builds DialogsAdapter instances for the visible dialog pages, wires DialogCell button clicks for forum-topic shortcuts, and creates a SearchViewPager for global dialog/media/downloads search. Selecting a regular search result or sub-dialog builds a Bundle with user_id or chat_id, validates it through MessagesController.checkCanOpenChat(...), then presentFragment(new ChatActivity(args)); tablet mode also updates openedDialogId so DialogCell selection state follows the right pane. Selection-only modes, such as forwarding, route through DialogsActivityDelegate.didSelectDialogs(...) and can carry a MessagesStorage.TopicKey instead of opening the chat immediately.

Forum topics are a parallel entry layer in TMessagesProj/…/TopicsFragment.java. The fragment owns a TopicsController, renders topic rows with TopicDialogCell/DialogCell-style data, supports multi-select actions such as pin/mute/delete/hide, and opens a topic by calling ForumUtilities.openTopic(TopicsFragment.this, chatId, topic, 0). switchToChat(...) explicitly opens the parent chat with a plain chat_id bundle and marks the transition with ChatActivity.setSwitchFromTopics(true). Topic search is local to TopicsFragment: it creates a MessagesSearchContainer, animates searchContainer plus its tabs, and preserves parent-dialog search affordances with openParentSearch().

TMessagesProj/…/ChatActivity.java is the chat screen orchestrator. onFragmentCreate() resolves exactly one peer source from arguments (chat_id, user_id, or enc_id), falling back to MessagesStorage synchronously when MessagesController has not cached the peer. It sets dialog_id (-chatId for chats, positive for users, encrypted id for secrets), reads thread/topic arguments such as message_id, start_from_date, unread_count, chatMode, and threadMessageId, registers a large set of NotificationCenter observers, loads chat/user/full info, bot keyboards, peer settings, and initial history through MessagesController.loadMessages(...). State is kept in in-memory collections such as messages, messagesDict, messagesByDays, selected-message sparse arrays, pinned-message maps, and mergeDialogId for migrated channel history; persistent read/scroll hints use notification shared preferences via NotificationsController.getSharedPrefKey(dialog_id, getTopicId()).

ChatActivity.createView() constructs the chat UI: the custom ActionBar, ChatAvatarContainer, the reversed message RecyclerListView, ChatActivityEnterView, floating date/unread/pagedown controls, pinned/info panels, mention suggestions, and attachment/search overlays. ChatAvatarContainer.java is the header helper: when attached to ChatActivity or TopicsFragment, it creates a SharedMediaPreloader, displays avatar/title/subtitle/typing status, and opens profiles or auto-delete/secret timers. ChatBigEmptyView.java, ChatGreetingsView.java, ChatActivityEnterTopView.java, ChatNotificationsPopupWrapper.java, ChatThemeBottomSheet.java, and ChatScrimPopupContainerLayout.java provide the chat-specific empty states, reply/edit top bar, notification popup, wallpaper/theme, and scrim/popup surfaces.

Message rendering is adapter-driven inside ChatActivity and cell-driven under TMessagesProj/src/main/java/org/telegram/ui/Cells/. ChatActivity maintains a cache of ChatMessageCell instances, binds message rows via the chat adapter, and delegates user actions to ChatMessageCellDelegate. ChatMessageCell.java renders ordinary message bubbles, media, albums, replies, reactions, polls, waveforms, checkboxes, selection background, seek bars, download progress, and image receivers; it calls back for playback, profile opens, side share, web views, reply jumps, and context actions. ChatActionCell.java renders service/date/action rows and also handles downloadable action media, spoilers, invite links, premium gifts, and bot buttons. ChatUnreadCell.java and ChatLoadingCell.java are list boundary/status rows. Dialog list rows are handled by DialogCell.java, which knows both regular dialogs and forum topics (setForumTopic(...)), draws unread/sent/read state, topic icons, avatars, counters, swipe affordances, and last-message previews.

Compose/send flow is split between ChatActivity and TMessagesProj/…/ChatActivityEnterView.java. ChatActivityEnterView owns the input field, keyboard/emoji/sticker/gif panels, bot keyboard/buttons, slow-mode and schedule UI, reply/edit state, audio/video recording panels, and input-content handling. Its delegate reports text changes to ChatActivity, which updates typing state, mention search, link-preview search, action-bar text-selection state, and field panels. Pressing send calls ChatActivityEnterView.sendMessageInternal(...): it handles schedule date picking, silent-notification preference persistence, slow-mode limits, premium emoji checks, recorded audio/video, and then processSendingText(...). Text is trimmed/split by MessagesController.maxMessageLength, entities come from MediaDataController.getEntities(...), and final sends go through SendMessagesHelper.sendMessage(...) with dialog_id, replyingMessageObject, getThreadMessage(), webpage preview data, notify/schedule flags, and send-animation metadata. On success the delegate ChatActivityEnterViewDelegate.onMessageSend(...) clears panels, updates scheduled counters, stores hashtags in the mentions adapter, clears forum-topic drafts when replying across topics, and triggers post-send UI such as transcribe hints.

Attachments enter from the compose bar into ChatActivity.openAttachMenu() and TMessagesProj/…/ChatAttachAlert.java. ChatAttachAlert is a BottomSheet with modular layouts for gallery/camera preview (ChatAttachAlertPhotoLayout.java, ChatAttachAlertPhotoLayoutPreview.java), documents (ChatAttachAlertDocumentLayout.java), contacts, audio, location, polls, colors/wallpapers, restricted sends, and bot web apps. Its ChatAttachViewDelegate.didPressedButton(...) is implemented in ChatActivity: selected gallery items are converted from MediaController.PhotoEntry to SendMessagesHelper.SendingMediaInfo, chunked in batches of ten, and sent through SendMessagesHelper.prepareSendingMedia(...); document selection routes to didSelectFiles(...) and SendMessagesHelper.prepareSendingDocuments(...); poll creation calls openPollCreate(...) and sends via SendMessagesHelper.sendMessage(poll, ...). Camera and external picker activity/permission results are returned to the same alert/photo layout, so changes to attach-button ids or activity request codes must keep processSelectedAttach(...), onActivityResultFragment(...), and permission handling aligned.

Search and selection have two layers. In-chat search uses MessagesSearchAdapter and SearchItemListener in ChatActivity: search notifications (chatSearchResultsAvailable and chatSearchResultsLoading) update progress, notify the search list, and optionally scrollToMessageId(...) for a matched message, including migrated-history load index handling. Dialog/global search uses DialogsActivity plus SearchViewPager; filtered media search is rendered by TMessagesProj/…/FilteredSearchView.java, which switches adapters based on FiltersView.MediaFilterData (SharedPhotoVideoCell, SharedDocumentCell, SharedLinkCell, audio/voice adapters, or dialog tips), loads more through the photo viewer provider, and removes deleted messages from its section maps. Selection modes are maintained separately for dialogs (DialogsActivity.selectedDialogs and action-mode counters) and chat messages (ChatActivity.selectedMessagesIds, copy/star/save counters, and processRowSelect(...)), then routed to delete/forward/save/copy/pin/report menu actions.

Media previews and playback are shared with app-level controllers but initiated from this flow. ChatMessageCellDelegate.needPlayMessage(...) sends voice/round video and music to MediaController; media taps open PhotoViewer using cell ImageReceiver placement data, while FilteredSearchView provides a PhotoViewerProvider for shared-media grids/documents/context links. Web embeds use TMessagesProj/…/EmbedBottomSheet.java, which hosts a WebView/WebPlayerView, supports YouTube iframe playback, fullscreen custom views, orientation changes, and picture-in-picture integration. Saving selected chat media uses MediaController.saveFilesFromMessages(...) from ChatActivity; direct gallery saves fall back to FileLoader.getPathToMessage(...) when attachPath is absent.

TMessagesProj/…/ShareActivity.java is a narrow external entry point for tgb://share_game_score links. It reads a serialized message and optional link from the botshare shared preferences, wraps it in a MessageObject, and opens ShareAlert.createShareAlert(...); it does not open ChatActivity directly, but participates in the same share/forward UI surface used from message cells.

Path-routing notes: Chat*.java also matches admin/edit/support screens such as ChatUsersActivity.java, ChatRightsEditActivity.java, and ChatEditActivity.java; include them here only when the change affects chat-screen navigation/action-bar menu entries launched from ChatActivity or TopicsFragment. Filter*.java/Filters*.java are dialog-search/folder setup screens; changes limited to folder configuration belong in this doc only when they affect DialogsActivity tabs/search/selection. Shared controllers under org.telegram.messenger (MessagesController, MessagesStorage, SendMessagesHelper, MediaController, MediaDataController, DownloadController, FileLoader, TopicsController, NotificationCenter) are dependencies of this flow, not owned coverage.

Coupling

  • If ChatActivity argument names or dialog_id conventions change, update DialogsActivity.didPressedOnSubDialog(...), TopicsFragment.switchToChat(...), topic opening through ForumUtilities.openTopic(...), and all ChatActivity.onFragmentCreate() peer-resolution branches together. The flow relies on negative ids for chats, positive ids for users, and DialogObject.makeEncryptedDialogId(...) for secrets.
  • If topic/thread semantics change, verify every send/load path carries the same thread identity: ChatActivity.onFragmentCreate() passes threadMessageId/isTopic to MessagesController.loadMessages(...), ChatActivityEnterView.processSendingText(...) and attachment sends pass getThreadMessage(), DialogsActivity selection returns MessagesStorage.TopicKey, and TopicsFragment opens topics through ForumUtilities.openTopic(...).
  • If send validation changes, update both ChatActivityEnterView.java and ChatActivity.java. Text sends enforce slow mode, schedule mode, notification silence, premium emoji, entity extraction, link previews, and reply/edit state in ChatActivityEnterView, while ChatActivity updates scheduled counters, forwarding state, drafts, mentions, and panels after the delegate callback.
  • If attachment button ids or request codes change, check ChatAttachAlert.ChatAttachViewDelegate.didPressedButton(...), ChatActivity.processSelectedAttach(...), ChatActivity.didSelectPhotos(...), ChatActivity.didSelectFiles(...), ChatAttachAlertDocumentLayout delegates, and ChatActivity.onActivityResultFragment(...)/permission handlers. The alert uses numeric button tags and external activity request codes rather than a central enum.
  • If message row layout or grouping changes, verify ChatActivity adapter binding, ChatMessageCell.setMessageObject(...), ChatActionCell.setMessageObject(...), grouped-message maps, PhotoViewer place-provider logic, and selection hit-testing. Rendering, media preview animation, and multi-select depend on cell geometry and MessageObject.GroupedMessages positions matching.
  • If search result payloads change, update both MessagesSearchAdapter notifications consumed in ChatActivity.didReceivedNotification(...) and FilteredSearchView section/message maps. Chat search uses classGuid and notification args to jump; global media search keeps its own messages, messagesById, sections, and sectionArrays that must be pruned on delete notifications.
  • If dialog list filters/folders change, verify DialogsActivity, DialogCell, DialogsAdapter, SearchViewPager, FilteredSearchView, and filter setup screens remain consistent. Folder tabs affect action-mode visibility, archive/pin/remove-from-folder options, and dialog selection state.

Risks

  • TMessagesProj/…/ChatActivity.java and TMessagesProj/…/ChatActivityEnterView.java are fragile because the send path is split across UI state, delegate callbacks, and SendMessagesHelper. If one branch forgets replyingMessageObject, getThreadMessage(), schedule/notify flags, or edit state, messages can be sent to the wrong topic, lose reply context, or fail to update scheduled counters. Git history shows repeated fixes around scheduled hooks, topic-only behavior, deleted-message loading, and send-related UI regressions.
  • TMessagesProj/…/ChatActivity.java, TMessagesProj/…/TopicsFragment.java, and TMessagesProj/…/DialogsActivity.java are sensitive around forums/topics. If a dialog click, topic click, search result, or forwarding selection drops the topic id, users land in the parent chat or send to the wrong topic. Recent history includes targeted fixes such as “topics only” and “deleted messages loading in topics,” indicating this area has fix-of-fix churn.
  • TMessagesProj/…/ChatAttachAlert.java plus ChatActivity attachment handlers are easy to desynchronize. The consequence is silent media loss, wrong document/photo mode, or broken camera/gallery permission returns because selected media is transformed across MediaController.PhotoEntry, SendMessagesHelper.SendingMediaInfo, numeric button ids, and Android request codes.
  • TMessagesProj/…/ChatMessageCell.java is high-risk for visual and interaction regressions: the same cell computes bubble bounds, grouped album geometry, selection checkboxes, image receivers, seek bars, spoilers, reactions, and delegate hit targets. A layout-only change can break PhotoViewer transition placement, reply/side-button hit testing, or grouped-message selection.
  • TMessagesProj/…/FilteredSearchView.java and ChatActivity search notifications can show stale or wrong results if deletion/load notifications are missed. FilteredSearchView.messagesDeleted(...) manually removes messages from several parallel collections, while in-chat search jumps based on positional notification args; stale indexes can leave deleted messages visible or scroll to the wrong row.