NextGram/plugins Build a plugin Screens & slots

Screen Replacement and Slots

Replace five host screens, add header slots and protect sensitive surfaces.

Plugins can replace a catalogued Telegram screen with a normal android.view.View (Java/hybrid) or a declarative tree (all kinds). The host keeps ownership of the stock fragment, navigation, lifecycle, insets, back handling, permissions and protected surfaces. A plugin view is an overlay, not a plugin-owned BaseFragment.

Status: the SDK catalogue contains 14 screen keys and 13 slot keys. This host build wires seams for CHAT_LIST, CHAT, SETTINGS, PROFILE and MAIN_NAVIGATION; the remaining keys are registered and validated but resolve to stock until their upstream seam is added. TypeScript plugins use the same keys through ctx.screens.

1. Module and imports#

The view contract lives in nextgram-plugin-sdk-android:

text
nextgram-plugin-sdk-android/
  src/main/java/dev/nextgram/plugin/v1/android/
    AndroidHost.java
    Screens.java
    ScreenKey.java
    SlotKey.java
    PluginScreen.java
    PluginScreenFactory.java
    ScreenContext.java
    ChatListScreenContext.java
    ChatScreenContext.java
    SettingsScreenContext.java
    ProfileScreenContext.java
    MainNavigationScreenContext.java
    MainTab.java
    Navigation.java
    ScreenInsets.java
    SlotContribution.java
    SlotContext.java
    SlotSpec.java

The module depends on the core SDK and must not depend on TMessagesProj or org.telegram.*. The host provides both modules at runtime; a plugin compiles against them as compileOnly and must not bundle them.

2. Permissions#

PermissionRiskRequired for
ui.screenshighScreens.replace and screen overlays
ui.custom_screenslowAndroidHost.openScreen
ui.chatlistmediumCHAT_LIST_HEADER slot
ui.settingslowSETTINGS_HEADER slot

ui.screens is off by default at install. Its consent copy says:

This plugin can replace app screens and imitate the interface. Only install it from an author you trust.

A registration without the permission throws PermissionDeniedException and creates no partial state. The host checks the permission again when it creates the view.

3. Host and registry#

java
public interface AndroidHost extends PlatformHost {
    Screens screens();
    Context themedContext();
    void openScreen(PluginScreen screen);
}

public interface Screens {
    Registration replace(ScreenKey key, PluginScreenFactory factory);
    Registration addSlot(SlotKey key, SlotContribution contribution);
    boolean isReplaced(ScreenKey key);
}

isReplaced reports whether the calling plugin currently owns the top provider for that key and screen overrides are enabled.

Resolve the host once per plugin lifetime:

java
AndroidHost host = context.require(AndroidHost.class);

themedContext() returns a context with the current Telegram theme, density and layout direction. Do not cache it beyond the current screen or app foreground state.

Registration comes from the core SDK. close() removes the provider or contribution immediately; isActive() reports whether it is still registered.

Rules:

  • Multiple plugins may replace the same key. The top of a per-key stack wins.
  • Removing the top provider restores the previous provider; removing all providers restores the stock screen.
  • One plugin cannot register the same key twice.
  • A plugin cannot register a protected key or a key it does not own.
  • Registrations are removed automatically on disable, uninstall, revocation and safe mode.

4. Screen keys#

java
public final class ScreenKey {
    public static final ScreenKey CHAT_LIST;
    public static final ScreenKey CHAT;
    public static final ScreenKey SETTINGS;
    public static final ScreenKey PROFILE;
    public static final ScreenKey MAIN_NAVIGATION;
    public static final ScreenKey CONTACTS;
    public static final ScreenKey CHAT_TOPICS;
    public static final ScreenKey CHAT_EDIT;
    public static final ScreenKey CHAT_MEMBERS;
    public static final ScreenKey INVITE_LINKS;
    public static final ScreenKey GROUP_CREATE;
    public static final ScreenKey CHANNEL_CREATE;
    public static final ScreenKey THEME;
    public static final ScreenKey DATA;

    public static ScreenKey of(String id);
    public String id();
}

The set is exactly these 14 values. ScreenKey.of accepts only catalogued, non-protected ids. There is no drawer key: this Telegram tree has no classic drawer.

KeyStock hostArea coveredReplacement permissionSlot
CHAT_LISTDialogsActivityContent rootui.screensCHAT_LIST_HEADER, ui.chatlist
CHATChatActivityContent rootui.screensnone
SETTINGSSettingsActivityContent rootui.screensSETTINGS_HEADER, ui.settings
PROFILEProfileActivity / ProfileActivity2Content rootui.screensnone
MAIN_NAVIGATIONMainTabsActivity tab barBottom tab area onlyui.screensMAIN_NAVIGATION_START, MAIN_NAVIGATION_END
CONTACTScontacts listContent rootui.screensnone
CHAT_TOPICStopic listContent rootui.screensnone
CHAT_EDITchat editContent rootui.screensnone
CHAT_MEMBERSmember listContent rootui.screensnone
INVITE_LINKSinvite linksContent rootui.screensnone
GROUP_CREATEgroup creationContent rootui.screensnone
CHANNEL_CREATEchannel creationContent rootui.screensnone
THEMEtheme settingsContent rootui.screensnone
DATAdata settingsContent rootui.screensnone

Slot catalogue: CHAT_LIST_HEADER, CHAT_LIST_FOOTER, SETTINGS_HEADER, SETTINGS_FOOTER, CHAT_HEADER, CHAT_COMPOSER, PROFILE_HEADER, MAIN_NAVIGATION_START, MAIN_NAVIGATION_END, MESSAGE_BUBBLE_HEADER, MESSAGE_BUBBLE_FOOTER, CHAT_LIST_ITEM_BADGE, NOTIFICATION_FOOTER. This host build renders the chat-list and settings header slots; the other slot keys are part of the stable catalogue and become visible when their seam is enabled.

5. Screen contract#

java
public interface PluginScreen {
    View onCreateView(ScreenContext context);
    void onResume();
    void onPause();
    void onDestroyView();
    boolean onBackPressed();
    void onThemeChanged();
}

public abstract class PluginScreenAdapter implements PluginScreen {
    // no-op implementations of every callback except onCreateView
}

public interface PluginScreenFactory {
    PluginScreen create();
}

Interface default methods are not used by the plugin API. Extend PluginScreenAdapter when only onCreateView is needed; implement the interface directly to override every callback.

onCreateView runs on the main thread with the host-provided themed context. It should return within 100 ms. The host logs a warning at 100 ms and disables the plugin after three repeated violations. Returning null or throwing leaves the stock screen visible; the failure is counted by PluginGuard.

The same PluginScreen instance can receive several resume/pause cycles. The factory is called again after a configuration change; do not reuse a view across factory calls.

6. Screen contexts#

java
public interface ScreenContext {
    Context context();
    PluginContext plugin();
    AppearanceHost appearance();
    int account();
    ScreenKey screenKey();
    ScreenInsets insets();
    float density();
    float fontScale();
    boolean isDark();
    void requestLayout();
    void requestClose();
    Navigation navigation();
}
  • context() is the themed host context; create all views with it.
  • plugin() is the normal plugin context, with the same permission gates.
  • appearance() is the appearance host; it still requires ui.appearance for appearance calls.
  • screenKey() is the key being replaced. It is null for plugin-owned screens opened through AndroidHost.openScreen.
  • insets() is an immutable pixel snapshot of system bars, IME and safe content edges.
  • requestLayout() asks the host to re-measure the overlay.
  • requestClose() finishes the host fragment that owns the current screen.
  • navigation() gives the host navigation actions.

6.1 Navigation#

java
public interface Navigation {
    void openChat(long dialogId);
    void openProfile(long userId);
    void openChatList();
    void openSettings();
    void openNextGramSettings();
    void openMainNavigation();
    void close();
}

Navigation always goes through the host. A plugin cannot push a BaseFragment, replace the back stack or open an arbitrary Telegram screen by class name. Navigation works from a replaced screen and from a plugin-owned screen opened with openScreen; it always opens a stock destination. openScreen itself stays unavailable while a plugin-owned screen is in the foreground, so plugin-owned screens cannot be stacked.

6.2 ScreenInsets#

java
public final class ScreenInsets {
    public static ScreenInsets of(int statusBar, int navigationBar, int ime,
                                  int left, int right, int top, int bottom);
    public int statusBar();
    public int navigationBar();
    public int ime();
    public int left();
    public int right();
    public int top();
    public int bottom();
}

All values are pixels and must be non-negative. statusBar, navigationBar and ime report system sizes; left, right, top and bottom report the remaining safe content area. The plugin view receives the full content area and must apply the insets it needs.

7. The five contexts#

7.1 ChatListScreenContext#

java
public interface ChatListScreenContext extends ScreenContext {
    Chats chats();
    void openChat(long dialogId);
    void openSettings();
    void openProfile(long userId);
    void openMainNavigation();
}

chats() requires chats.read and filters secret chats. The chat list data is the normal permission-checked snapshot API, not a raw adapter.

7.2 ChatScreenContext#

java
public interface ChatScreenContext extends ScreenContext {
    long dialogId();
    Chats chats();
    Messages messages();
    void openProfile();
    CompletableFuture<Void> sendText(String text);
    void close();
}

sendText requires messages.send, rejects empty text and secret chats, and uses the host send path. It completes when the host accepts the send, not when the message is delivered. messages() requires messages.read.

7.3 SettingsScreenContext#

java
public interface SettingsScreenContext extends ScreenContext {
    void openNextGramSettings();
}

The host settings shell remains kernel-owned; the plugin can navigate to it but cannot replace it with another plugin's screen.

7.4 ProfileScreenContext#

java
public interface ProfileScreenContext extends ScreenContext {
    long userId();
    String title();
    Chats chats();
    void openChat();
}

title() is the host-resolved display title. chats() requires chats.read and hides secret chats.

7.5 MainNavigationScreenContext#

java
public interface MainNavigationScreenContext extends ScreenContext {
    MainTab currentTab();
    void selectTab(MainTab tab);
    void openChatList();
    void openSettings();
    void openProfile();
}

MainTab values map to the main tab positions:

java
public enum MainTab {
    CHATS,
    NEWS_OR_CONTACTS,
    CALLS_OR_SETTINGS,
    PROFILE
}

MAIN_NAVIGATION covers only the tab bar. The page content remains the stock screen unless that screen key is separately replaced.

8. Slots#

java
public final class SlotKey {
    public static final SlotKey CHAT_LIST_HEADER;
    public static final SlotKey SETTINGS_HEADER;
}

public interface SlotContribution {
    String id();
    View createView(SlotContext context);
    SlotSpec spec();
}

public interface SlotContext {
    Context context();
    PluginContext plugin();
    AppearanceHost appearance();
    int account();
    SlotKey slotKey();
}

public final class SlotSpec {
    public static SlotSpec wrapContent();
    public static SlotSpec fixedHeightDp(int dp);
    public SlotSpec order(int order);
    public int heightDp();
    public int order();
}
  • SlotContribution.id() is stable within the plugin; duplicate ids are rejected.
  • CHAT_LIST_HEADER requires ui.chatlist; SETTINGS_HEADER requires ui.settings.
  • Contributions are ordered by ascending order, then registration order.
  • fixedHeightDp requires a positive value; wrapContent lets the host size the slot.
  • Closing the registration removes the view and reflows the host layout without a restart.
  • Slot views are host-rendered additions. They are attached only when the screen is not replaced by an overlay; a screen replacement owns the whole content area.
  • The slot host is a top-aligned child of the stock content. It does not replace or reflow the stock list, so keep its height small and do not duplicate stock chrome.

9. Overlay semantics#

The host creates the stock fragment and its normal view tree, then adds an opaque FrameLayout overlay as the last child of the screen root. The plugin view fills the overlay and consumes touches.

  • The stock fragment, its fragmentView identity, its parent and the back stack are unchanged.
  • The stock screen keeps running underneath the overlay. This costs CPU and GPU while a replacement is active; it is a deliberate v1 trade-off that preserves navigation, lifecycle and upstream stability.
  • For full-screen keys, the host hides the action bar and the overlay covers the content. The plugin draws its own toolbar and navigation affordances.
  • For MAIN_NAVIGATION, the overlay covers only the bottom tab bar area.
  • The overlay uses the current window background color and the plugin view's own background.
  • The no-provider path has no allocation, no wrapper view and no plugin call.

10. Lifecycle#

Host eventPlugin callback
Screen view created and provider resolvedPluginScreenFactory.create() then onCreateView(context)
Fragment resumedonResume()
Fragment pausedonPause()
Fragment view destroyedonDestroyView(); the overlay is removed
Back pressedonBackPressed() first; true consumes the event, false falls through to stock
Theme appliedonThemeChanged() on the main thread
Rotation or configuration changeNew factory call, new view, old view destroyed
Plugin disabled, uninstalled, revoked or safe modeOverlay removed; stock screen visible

The host preserves system insets, RTL layout direction, font scale and the system back gesture/button. It does not preserve arbitrary plugin view state across rotation. Save state in plugin storage or the view's saved state.

A plugin view that blocks the main thread is logged and can disable the plugin. A factory or view exception is caught by PluginGuard, the stock screen remains, and the plugin may be disabled after three failures.

11. Protected surfaces#

The resolver returns no provider and no context when any of these is true:

  • SharedConfig.appLocked is true;
  • no account is active;
  • the current surface is login, registration, phone confirmation, QR login, two-step verification, passcode, biometric unlock or screen lock;
  • the surface is a payment form, checkout, Premium purchase, gift, Wallet or Telegram Passport;
  • the chat is a secret chat;
  • the surface is the plugin manager, installer, permission consent, update prompt, safe mode, crash recovery, catalog trust UI or signature details;
  • the surface is a kernel plugin-manager, installer or other dev.nextgram.plugin.* UI class, or a fragment in preview/passive-preview mode;
  • the surface is a call, group call or screen sharing UI;
  • the plugin is disabled, revoked or lacks the required permission.

Protected surfaces never receive plugin views, screen contexts or slot contributions. The stock UI is used. This is an API and UI boundary, not a process boundary: a malicious DEX plugin can still attempt reflection. See security.md.

12. Kill switch#

The plugin manager security section has a kernel-owned switch:

Allow screen replacement plugins — default on.

The manager also lists each replaced screen and the installed plugin that owns it; tapping a row opens that plugin's details, where it can be disabled. When the kill switch is off:

  • all screen overlays and slots are removed and stock screens are shown;
  • providers stay registered but inactive;
  • no plugin is uninstalled or disabled;
  • re-enabling the switch restores the providers at the next screen creation.

Safe mode unloads external plugins and also removes appearance and screen providers.

13. Plugin-owned screens#

java
AndroidHost host = context.require(AndroidHost.class);
host.openScreen(new AboutScreen());

openScreen requires ui.custom_screens. The host presents a full-screen fragment with the plugin view, hides the action bar and keeps the normal lifecycle. The plugin draws its own top bar if it needs one. The system back gesture/button calls PluginScreen.onBackPressed and then closes the fragment. The plugin does not control transitions or the back stack. The context passed to this screen has screenKey() == null, because it is not replacing a host key.

openScreen does not grant data access beyond the plugin's existing permissions. A plugin-owned screen is not a route: it cannot be registered as a Telegram screen, cannot be opened by another plugin and cannot replace a protected surface. The host rejects the call while the app is locked or a login, passcode, payment, installer, consent, safe-mode, secret-chat or other protected surface is in the foreground, and re-checks the surface when the screen is actually presented. For openScreen, a plugin-owned screen counts as a protected surface too, so a plugin cannot stack a second plugin-owned screen on top of one that is already open.

14. Complete example#

This plugin replaces the chat list and adds a header slot. The manifest declares "permissions": ["ui.screens", "ui.chatlist"].

java
package dev.example.redesign;

import android.content.Context;
import android.graphics.Color;
import android.graphics.Typeface;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import dev.nextgram.plugin.v1.AbstractNextGramPlugin;
import dev.nextgram.plugin.v1.PluginContext;
import dev.nextgram.plugin.v1.Registration;
import dev.nextgram.plugin.v1.android.AndroidHost;
import dev.nextgram.plugin.v1.android.ChatListScreenContext;
import dev.nextgram.plugin.v1.android.PluginScreenAdapter;
import dev.nextgram.plugin.v1.android.ScreenContext;
import dev.nextgram.plugin.v1.android.ScreenKey;
import dev.nextgram.plugin.v1.android.SlotContext;
import dev.nextgram.plugin.v1.android.SlotContribution;
import dev.nextgram.plugin.v1.android.SlotKey;
import dev.nextgram.plugin.v1.android.SlotSpec;

public final class RedesignPlugin extends AbstractNextGramPlugin {

    private Registration chatList;
    private Registration header;

    @Override
    public void onLoad(PluginContext context) {
        AndroidHost host = context.require(AndroidHost.class);
        chatList = host.screens().replace(ScreenKey.CHAT_LIST, ChatListScreen::new);
        header = host.screens().addSlot(SlotKey.CHAT_LIST_HEADER, new HeaderContribution());
    }

    @Override
    public void onUnload() {
        header.close();
        chatList.close();
    }

    private static final class ChatListScreen extends PluginScreenAdapter {

        @Override
        public View onCreateView(ScreenContext context) {
            ChatListScreenContext chatList = (ChatListScreenContext) context;
            Context themed = chatList.context();

            LinearLayout root = new LinearLayout(themed);
            root.setOrientation(LinearLayout.VERTICAL);
            root.setBackgroundColor(0xFF101318);
            root.setPadding(chatList.insets().left(), chatList.insets().top(),
                    chatList.insets().right(), chatList.insets().bottom());

            TextView title = new TextView(themed);
            title.setText("Chats");
            title.setTextSize(28);
            title.setTypeface(Typeface.DEFAULT_BOLD);
            title.setTextColor(Color.WHITE);
            title.setContentDescription("Chats");
            root.addView(title);

            Button settings = new Button(themed);
            settings.setText("Settings");
            settings.setContentDescription("Open settings");
            settings.setOnClickListener(view -> chatList.openSettings());
            root.addView(settings);

            Button profile = new Button(themed);
            profile.setText("Navigation");
            profile.setContentDescription("Open main navigation");
            profile.setOnClickListener(view -> chatList.openMainNavigation());
            root.addView(profile);

            return root;
        }

        @Override
        public boolean onBackPressed() {
            return false;
        }
    }

    private static final class HeaderContribution implements SlotContribution {

        @Override
        public String id() {
            return "chat-list-header";
        }

        @Override
        public View createView(SlotContext context) {
            TextView header = new TextView(context.context());
            header.setText("Redesign");
            header.setTextSize(16);
            header.setGravity(Gravity.CENTER_VERTICAL);
            header.setPadding(24, 16, 24, 16);
            header.setTextColor(Color.WHITE);
            header.setContentDescription("Redesign header");
            return header;
        }

        @Override
        public SlotSpec spec() {
            return SlotSpec.wrapContent().order(10);
        }
    }
}

The example uses fixed colors. A plugin that wants theme-aware colors declares ui.appearance and reads them with context.appearance().themeColor(...); otherwise that call throws PermissionDeniedException.

15. Limitations#

  • The stock screen still runs under the overlay. V1 does not detach stock children or replace fragments in the navigation stack.
  • Media, calls, payments, secret chats, login and passcode are not available to plugin screens. They stay stock or are out of scope.
  • CHAT replacement covers text and read access; media playback is not exposed.
  • Script plugins do not get views, slots or screen replacement.
  • There is no desktop screen API.
  • Plugins cannot provide BaseFragment, Activity, Service, BroadcastReceiver or ContentProvider types.
  • There is no custom drawer key because there is no classic drawer.
  • Global font, wallpaper, icon-pack, drawable and layout overrides are not part of this milestone.
  • A plugin screen cannot change the host action bar, the navigation stack or another plugin's screen.

For colors, see themes.md. For the security boundary, see security.md.