Skip to content
Repos

mologram

Markdown 76.7 KB738 lines Opens in site

Directory Raw Download

mologram - Complete Implementation Document

  • Version: 0.1.12
  • Status: Baseline, graded A- (ADR 0008). Zero untracked open items: A-01 to A-06 are tracked assumptions with owner, date and fallback; requirements that are not built are open or partial rows in section 10
  • Date: 2026-11-05
  • Owner: retoor

mologram is a Telegram Desktop clone that runs in a terminal. One statically linked binary mologram (UI) and one mologramd (daemon). Languages and libraries: C++20, rgui (UI), tapi (Telegram MTProto), WolfSSL (via tapi).

0. Document control

0.1 Conventions

  • Normative IDs: FR (functional), NFR, UX, SEC, OPS, D (decision), PIN (stack pin), A (assumption), TRK, DOC. IDs are never reused after retirement. Other documents cite IDs, never paraphrase.
  • Tables between <!-- spec:NAME --> and <!-- /spec:NAME --> markers are machine-checked against the code by tests/test_spec.cpp (config keys, actions, protocol methods, widgets, premium features). A row in the table without code, or code without a row, fails the build. The traceability table in section 10 is checked by tests/test_docs.cpp.
  • The words MUST, MUST NOT, SHOULD are used as in RFC 2119.
  • No open gaps: anything undecided is a decided default in section 9, or a tracked assumption in 0.2.

0.2 Assumptions (tracked)

ID Assumption Owner Verify by Fallback Status
A-01 tapi (blocking, thread-safe per its DESIGN.md) is safe to drive from one dedicated worker thread plus one event pump thread retoor 2026-11-19 Serialize all calls through one worker thread (decided design, D-04, so no change needed) verified 2026-11-05: one worker plus one pump thread ran 47 live checks and 169 offline tests without a race
A-02 Terminals deliver SGR mouse drags that stay clamped on the grid edge when the pointer leaves the window retoor 2026-11-19 Tear-off by Ctrl+T, menu, and double-click remain; edge-drag detection is then documented as terminal dependent partly verified 2026-11-05: edge drag tested with injected events and the rgui terminal emulator, not on a real xterm or kitty
A-03 A terminal emulator can be spawned by terminal.command with -e mologram --chat <id> semantics retoor 2026-11-19 terminal.command is a template string with {cmd} placeholder, so any terminal can be configured verified 2026-11-05: template with {cmd} and 6 detection paths tested; real terminal spawn tested in a pty only
A-04 Telegram answers PREMIUM_ACCOUNT_REQUIRED consistently for gated calls retoor 2026-11-26 PremiumRequiredError also maps *_PREMIUM_* and PREMIUM_* codes (SEC-04, FR-60) verified 2026-11-05: a non-Premium account got PremiumAccountRequiredError on reaction send; related codes mapped by a table test
A-05 libwolfssl.a is installed system wide on build machines retoor 2026-11-12 CMake option MOLOGRAM_WOLFSSL_DIR points at a local build verified 2026-11-05: libwolfssl.a present, both binaries link static
A-06 Static glibc resolves names; if NSS is absent at run time the DC IPs are used directly retoor 2026-11-12 D-09: connect to hardcoded DC IPs first, getaddrinfo second partly verified 2026-11-05: static link works (glibc warns about getaddrinfo); name resolution in an empty container not yet run

0.3 Hard global caps

None. D-02 forbids inventing any cap, floor, timeout, quota, retention or rate limit. Only limits enforced by the Telegram server exist, and they are shown as the server's error text.

0.4 Changelog (ascending, one row per change)

Version Date Change
0.1.0 2026-11-05 Initial spec: goals, requirements, architecture, protocol, config, actions, widgets, decisions
0.1.1 2026-11-05 Protocol params exact with optional marker; error code bad_params; D-14 int64 ids as strings
0.1.2 2026-11-05 Frame magic MLG1; error code disconnected; D-13 fixed 1 s retry
0.1.3 2026-11-05 D-15: terminal-deliverable default keys (Alt+I, Ctrl+G, F2)
0.1.4 2026-11-05 Event payloads defined
0.1.6 2026-11-05 69 protocol methods (premium, business, stories, gifts, payments, passport, secret, calls, dialogs.folder_set); messages.send entities/effect; messages.search offset_id; premium table gets a Method column; 7 more events
0.1.7 2026-11-05 Media: media.download thumb?, messages.send_file kind?, messages.send_album, waveform, story media tokens (M8); actions transfers (F4), stories (F5), story_post (F6)
0.1.8 2026-11-05 M6: 16 methods (pinned, scheduled, stickers, custom emoji, bot commands/inline, contacts.import, privacy and notification setters, member management, resend code), params on send/edit/send_poll, 16 actions (float_chat, react, select, poll, schedule, contacts, new_chat, profile, accounts, mute, archive, mark_read, search_in_chat, pinned_next, fmt_code, fmt_spoiler), config keys language and account, parameter value contract, D-16 to D-18
0.1.9 2026-11-05 UX family (UX-01 to UX-07), section 10 acceptance criteria and traceability table, assumption status column, 7.1 actuals and open work, R-06 and R-07; DOC and TRK families (3.12), command line section matches the binaries
0.1.10 2026-11-05 Actions call (F7), secret_chat (F8), gifts (Alt+G), business (Alt+B); config tearoff.edge_hold_ms; acceptance and tests of FR-23, FR-51, FR-52, FR-63, FR-73, NFR-07, OPS-02 updated
0.1.11 2026-11-05 Track D: stickers.sets, stickers.set, stickers.premium; service contract details (html and plain text, filters, sticker and bot results, privacy rules, members role, resend code)
0.1.12 2026-11-05 Login: auth.send_phone and auth.resend_code report type, next_type and timeout; the service uses the config phone when phone is empty; OPS-03 log file built; mologramd --import-auth

1. Goals and non-goals

  • G-01: Behave like Telegram Desktop in a terminal: same layout, flows, wording and shortcuts where a terminal can express them.
  • G-02: Full keyboard operation and full mouse operation at all times; neither is required for the other.
  • G-03: Several conversations visible at once: floating windows in one terminal and tear-off into new terminals, all live and in sync.
  • G-04: Every Telegram feature the protocol offers, including Premium (FR-60 to FR-69), calls, secret chats, animated stickers, Business and stories.
  • G-05: Premium is optional: its absence or loss is a handled state (FR-61).
  • G-06: One static binary pair, no shared libraries at run time.
  • NG-01: No Telegram-blue reskin. The look stays Transport Tycoon (D-05).
  • NG-02: No caps or limits of mologram's own (D-02).
  • NG-03: No dependencies besides C++ standard library, POSIX, WolfSSL via tapi, rgui (PIN-01).

2. Scope

Personas: P1 the owner, a power user on Linux with a terminal emulator and Telegram Premium; P2 a user without Premium; P3 a user running several chats side by side. Platforms: Linux with POSIX sockets. --no-daemon runs the service in-process for machines without unix sockets.

3. Requirements

3.1 Accounts and login

  • FR-01: Login with phone, code, 2FA password, and QR code. Session in a file with mode 0600, locked with flock (tapi).
  • FR-02: Multiple accounts, switched from settings; each account has its own session file and daemon.
  • FR-03: Log out (server auth.logOut), removing the session file.
  • FR-04: The 2FA password hint, the flood-wait and the resend-code flow are shown in the login dialog with the server's text.

3.2 Chats

  • FR-10: Chat list with avatar block, name, last message preview, time, unread badge, muted, pinned, verified, scam/fake, typing indicator, draft marker.
  • FR-11: Folders as tabs (server chat folders), archive folder, pin, mute, mark read/unread, delete, leave, lazy paging without end.
  • FR-12: Search box over chats, contacts and messages (global), per chat, with type filters (photos, videos, files, links, voice, GIFs, music).
  • FR-13: Saved Messages, with tags; Saved dialogs view.
  • FR-14: Forum groups: topic list, topic open, create, edit, close, delete.
  • FR-15: Channel comments (discussion thread) and replies in threads.

3.3 Messages

  • FR-20: Send text with markdown/html entities, reply, edit, delete (for me, for everyone), forward (with or without sender), copy, multi-select, pin/unpin, jump to message.
  • FR-21: History paging both directions with scroll position kept. Unread divider. Day separators.
  • FR-22: Drafts synced with the server. Scheduled messages (list, send now, delete).
  • FR-23: Link previews, mentions, hashtags, bot commands, inline bots, bot buttons and callbacks, bot menu.
  • FR-24: Reactions (add, remove, list who reacted), polls (vote, create, quiz, close), dice, location, contact, venue cards.
  • FR-25: Message read ticks, edited mark, forward header, reply quote, via-bot mark, sponsored message mark.

3.4 Media

  • FR-30: Send file, photo, video, audio, voice file, document, album, with caption and progress and cancel. Paste of a path (bracketed paste) attaches.
  • FR-31: Download with progress and cancel, open with xdg-open, save as, thumbnails first then full file.
  • FR-32: Image preview in the terminal with rgui ImageWidget (halfblock, kitty, sixel); static sticker as image; GIF and video as frame by frame image (FR-33); voice and audio as waveform bar with play via the host audio player.
  • FR-33: Animated stickers (Lottie/TGS), video stickers and GIFs are rendered frame by frame through rgui's image path.

3.5 Groups, channels, contacts

  • FR-40: Members, admins, permissions, invite links, join/leave, slow mode, admin log, create group/channel/forum, add/remove members.
  • FR-41: Contacts list, search, add, import, block/unblock, profile with shared media/files/links/voice/groups tabs.
  • FR-42: Presence: online status, last seen, typing, upload/record indicators, read receipts, unread counters.

3.6 Settings

  • FR-50: Profile edit, username, bio, phone privacy, active sessions list and terminate, notification settings per chat and global, theme, keybindings, interface language table.
  • FR-51: Stories: view list, play as slideshow of images, post with text and media, privacy, view history.
  • FR-52: Calls: 1-to-1 and group call signaling and audio through the host audio device when present; UI shows call state; secret chats; payments display; Passport. Each is a separate milestone in BUILD-TRACK and none is excluded.

3.7 Premium

  • FR-60: Every Premium feature in the premium table of section 6.5 works when the account has Premium.
  • FR-61: Premium absence and loss are handled states. One PremiumState (Premium, NotPremium, Unknown) is owned by the daemon, refreshed at login and on every user update, and fanned out to all UI processes without restart.
  • FR-62: One typed PremiumRequiredError maps PREMIUM_ACCOUNT_REQUIRED and related codes in one place. No feature catches raw 403s.
  • FR-63: Without Premium, every Premium control stays visible, drawn disabled with a lock mark. Activation opens one calm panel: what the feature is, that it needs Telegram Premium, how to get it (open the Premium bot chat). Never a stack trace, raw RPC error or blank result.
  • FR-64: If Premium is lost while running, or a call returns PremiumRequiredError while the state says Premium: the state flips to NotPremium, controls disable, the failed action states plainly what did not happen, drafts and queued messages and scroll position stay, and controls return by themselves when Premium returns.
  • FR-65: Content created with Premium stays readable without it. Custom emoji show their fallback emoji, a missing effect shows the plain message, translated text and voice transcriptions already received stay.
  • FR-66: Offline tests run every Premium feature three ways: Premium, NotPremium, Premium lost midway.

3.8 Windows and input

  • FR-70: Three panes (chat list, conversation, info), resizable by mouse and keyboard, collapsing on narrow terminals. Responsive down to 40x15; reflow on every resize.
  • FR-71: Every action in the actions table of section 6.3 has a default key, a menu entry, and a mouse affordance. Keys are rebindable.
  • FR-72: Floating chat windows in one terminal using rgui WindowManager (move, resize, snap, tasklist). State persisted across restarts.
  • FR-73: Tear-off: drag a chat row or header to the window edge and release (or hold on the clamped edge), Ctrl+T, context menu "Open in new window", double click. Spawns terminal.command running mologram --chat <id> attached to the same daemon.
  • FR-74: Mouse: click, double click, wheel, drag-resize, right-click menus, reactions/buttons/links/avatars clickable, drag text selection, tooltips, scrollbars draggable.
  • FR-75: F1 help overlay listing all bindings from the registry.

3.9 Non-functional

  • NFR-01: UI thread never blocks on the network. Every RPC is asynchronous with a request id and a cancel.
  • NFR-02: Terminal restored on every exit path, including crash signals and tear-off child death.
  • NFR-03: C++20 with -Wall -Wextra -Wpedantic -Werror. One responsibility per class, virtual interfaces at module borders, no globals, RAII for terminal, sockets, threads, files.
  • NFR-04: UI depends on ITelegramService, never on tapi::Client.
  • NFR-05: Text is UTF-8; width and clustering from rgui unicode.hpp; RTL per UAX #9.
  • NFR-06: Colors: 24-bit with 256 and 16 color fallback chosen by COLORTERM and TERM.
  • NFR-07: Reconnect retries until it succeeds, with visible state "Connecting", "Reconnecting".
  • NFR-08: Nothing is truncated, dropped or evicted by mologram (D-02).

3.10 Security and ops

  • SEC-01: Secrets (api_id, api_hash, phone, auth keys, session files) are never printed, logged, committed or echoed, including in tests and errors. A test greps logs and dumps for them.
  • SEC-02: --dump-config redacts secrets.
  • SEC-03: Socket file mode 0600, directory 0700.
  • SEC-04: Unverifiable input (bad frame, bad version, bad checksum) is rejected with a reason and a counter (rejected_frames, rejected_cache); nothing unverifiable is stored.
  • OPS-01: Commands: make build, make test, make run, make clean, make check, make image, make up.
  • OPS-02: The daemon is started by the first UI process (lockfile, stale-socket detection) and stops when the last UI process leaves unless keep_daemon is true.
  • OPS-03: Logs go to data_dir/log/mologram-YYYY-MM-DD.log, rotated daily, never size capped, never deleted by mologram (D-02).
  • OPS-04: Version in the VERSION file, read by CMake, bumped and tagged by the commit workflow.

3.11 User experience

  • UX-01: The layout adapts to the terminal: one pane at 40x15, list plus conversation at 80x24, three panes at 160x50, reflowing on every resize.
  • UX-02: Every dialog opens and fits at 40x15, 80x24 and 160x50 and never exceeds the work area.
  • UX-03: Every action works by keyboard and by mouse; neither is required for the other.
  • UX-04: The Transport Tycoon look stays (D-05); themes change colours only, never glyphs or bevels.
  • UX-05: A failure shows the server's text unchanged, in plain words; never a stack trace, a raw error object or a blank result.
  • UX-06: Long operations (transfers, searches, stories) show progress and can be cancelled.
  • UX-07: The interface language falls back to English key by key; the choice is remembered.

3.12 Documentation and tracking

  • DOC-01: Every markdown file of the project has a versioned header <!-- doc: path | version | updated --> on line 1 and a row in docs/DOC-REGISTER.md with owner, trigger and staleness.
  • DOC-02: DESIGN.md describes every class in include/ with its owner, lifetime and thread.
  • DOC-03: The key table of README.md equals the action registry.
  • DOC-04: Every runbook has a dated "Last drilled" entry; an undrilled runbook fails the ops gate.
  • TRK-01: BUILD-TRACK.md is at most 7 days old and lists every open requirement of section 10.

4. Surfaces (UI inventory)

ID Surface Notes
PG-01 MainWindow chat list, conversation, info
PG-02 ChatWindow tear-off or floating, conversation only
PG-03 LoginDialog phone, code, password, QR
PG-04 SettingsDialog profile, privacy, notifications, sessions, theme, keybindings
PG-05 ProfileDialog user, group, channel, bot
PG-06 SearchDialog global search
PG-07 ForwardDialog choose targets
PG-08 AttachDialog file chooser, paste a path
PG-09 EmojiDialog emoji, stickers, GIFs, custom emoji
PG-10 ContactsDialog list, add, import
PG-11 NewChatDialog group, channel, forum
PG-12 PremiumPanel the calm "needs Premium" panel (FR-63)
PG-13 HelpOverlay F1
PG-14 StoriesViewer slideshow
PG-15 CallPanel call state and controls

5. Architecture

mologram (UI process, one per terminal window)
  App : rgui::Application
    MainWindow  (ChatListPane | ChatPane | InfoPane)
    ChatWindow  (tear-off: ChatPane only)
    Dialogs     (PG-03 to PG-15)
  ViewModels: ChatListModel, ChatModel, MessageModel, ContactModel, MediaModel, PremiumModel
  RemoteService : ITelegramService  ---- unix socket, framed JSON ---->  mologramd
mologramd (daemon, exactly one per session)
  Daemon        : socket server, lockfile, attached UI processes
  TapiService   : ITelegramService, owns tapi::Client, the only network user, one worker thread
  EventBus      : fans events out to every attached UI process
  MediaCache    : on-disk cache, checksum verified, never evicts
  PremiumState  : single source of truth

Pins:

  • PIN-01: C++20, g++ 15 on Linux, CMake 3.20+, static link (-static -pthread).
  • PIN-02: UI library ../rgui (header-only). Telegram library ../grrbackupclankertelegram/tapi (static lib).
  • PIN-03: JSON via rgui's json namespace; no other JSON library.
  • PIN-04: Protocol: length-prefixed JSON frames over a unix stream socket, proto_version 1.
  • PIN-05: Terminal spawn: terminal.command template with {cmd}; default auto-detect $TERMINAL, x-terminal-emulator, gnome-terminal, xterm.
  • PIN-06: Test framework: rgui's tttest.hpp.

6. Interfaces

6.1 Config keys (.env.json)

Search order: $MOLOGRAM_CONFIG, ./.env.json, $XDG_CONFIG_HOME/mologram/.env.json, built-in defaults. --config <path>, --dump-config (secrets redacted). Unknown keys warn. Wrong types fall back per key. Bad JSON reports line:column.

Key Type Default Secret
api_id int none (required) yes
api_hash string none (required) yes
phone string none (required) yes
session_path string $XDG_DATA_HOME/mologram/main.session no
data_dir string $XDG_DATA_HOME/mologram no
socket_path string $XDG_RUNTIME_DIR/mologram.sock no
theme string default no
colors object {} no
uiColors object {} no
glyphs object {} no
ascii_mode bool false no
unicode.probe bool true no
unicode.emojiWidth int 0 no
unicode.vs16Width int 0 no
unicode.zwjMode string first no
keybindings object {} no
media.image_mode string auto no
media.auto_download bool true no
notifications.enabled bool true no
notifications.bell bool true no
notifications.mute_default bool false no
terminal.command string auto-detect no
language string en no
account string main no
keep_daemon bool false no
tearoff.keep_source bool true no
tearoff.edge_hold_ms int 600 no
premium.show_locked bool true no

6.2 Command line

mologram [--config P] [--dump-config] [--help] [--version] [--fake] [--no-daemon] [--chat KEY] [--socket P] [--auth-tsv P]; mologramd [--config P] [--socket P] [--fake] [--auth-tsv P] [--foreground] [--help] [--version].

  • --fake serves or uses the in-memory service (demos, tests, container smoke tests).
  • --chat KEY opens one conversation (KEY like user:123) in this terminal: the torn-off window.
  • --auth-tsv P loads an exported auth key for development; it is never a default and only valid while the Python userbot is not running.
  • --no-daemon is declared but not built (README Open gaps).

6.3 Actions

Each action has an id, a default key, a menu entry and a mouse affordance. The key is rebindable through keybindings. Ctrl+K opens the link dialog when the composer has a selection, otherwise it opens search (D-08).

Action Default key Menu
search Ctrl+K Chat/Search
search_chat Ctrl+F Chat/Search in chat
chat_prev Ctrl+Up Go/Previous chat
chat_next Ctrl+Down Go/Next chat
chat_prev_alt Alt+Up Go/Previous chat
chat_next_alt Alt+Down Go/Next chat
folder_prev Ctrl+PgUp Go/Previous folder
folder_next Ctrl+PgDn Go/Next folder
back Escape Go/Back
send Enter Message/Send
newline Shift+Enter Message/New line
edit_last Up Message/Edit last
fmt_bold Ctrl+B Format/Bold
fmt_italic Alt+I Format/Italic
fmt_underline Ctrl+U Format/Underline
fmt_link Ctrl+K Format/Link
fmt_code Alt+E Format/Code
fmt_spoiler Alt+H Format/Spoiler
emoji Ctrl+E Message/Emoji
attach Ctrl+O Message/Attach
reply Ctrl+R Message/Reply
delete Ctrl+D Message/Delete
forward Ctrl+G Message/Forward
pin Ctrl+P Message/Pin
info F3 View/Info pane
transfers F4 View/Transfers
stories F5 View/Stories
story_post F6 View/Post story
close_window Ctrl+W Window/Close
tear_off Ctrl+T Window/Open in new window
settings F2 App/Settings
help F1 Help/Keys
quit Ctrl+Q App/Quit
float_chat Alt+T Window/Open floating window
react Alt+R Message/React
select Alt+S Message/Select
poll Alt+O Message/Create poll
schedule Alt+D Message/Schedule
contacts Alt+C App/Contacts
new_chat Alt+N App/New chat
profile Alt+P View/Profile
accounts Alt+A App/Accounts
mute Alt+M Chat/Mute
archive Alt+V Chat/Archive
mark_read Alt+K Chat/Mark as read
search_in_chat Alt+F Chat/Search messages
pinned_next Alt+J Message/Next pinned
call F7 Chat/Call
secret_chat F8 Chat/Secret chat
gifts Alt+G App/Gifts
business Alt+B App/Business

6.4 Protocol (daemon <-> UI)

Frame: the 4 bytes MLG1, a 4-byte big-endian length, then a JSON object. A stream that does not begin a frame with the magic is bad_frame; the connection is closed and rejected_frames is counted (no size cap, D-02). Request {"v":1,"id":N,"m":"method","p":{...}}; response {"v":1,"id":N,"ok":true,"r":{...}} or {"v":1,"id":N,"ok":false,"e":{"code":"...","text":"..."}}; event {"v":1,"ev":"name","d":{...}}; cancel {"v":1,"cancel":N}. A frame with an unknown v is rejected with error bad_version and counted. Error codes: bad_version, bad_frame, bad_params, unknown_method, cancelled, premium_required, not_logged_in, disconnected, rpc_error (server text unchanged), internal.

Method Params Result
hello client? proto_version, account, premium state
auth.state none state
auth.send_phone phone sent, type, next_type, timeout
auth.send_code code state
auth.send_password password state
auth.qr_start none url
auth.logout none ok
dialogs.list folder?, offset? dialogs
dialogs.folders none folders
dialogs.pin peer, on ok
dialogs.mute peer, until ok
dialogs.mark_read peer ok
dialogs.archive peer, on ok
dialogs.delete peer ok
messages.history peer, offset_id?, direction?, count? messages
messages.send peer, text, reply_to?, schedule?, format?, entities?, effect? message
messages.edit peer, id, text, format?, entities? message
messages.delete peer, ids, revoke? ok
messages.forward from, to, ids messages
messages.pin peer, id, on ok
messages.react peer, id, reactions ok
messages.search peer?, query, filter?, offset_id? messages
messages.draft peer, text ok
messages.send_file peer, path, caption?, kind? message
messages.send_album peer, paths, caption? messages
messages.send_poll peer, question, options, multiple?, quiz?, correct? message
messages.vote peer, id, options ok
messages.click_button peer, id, data answer
media.download media, dest?, thumb? path
peer.info peer info
peer.members peer, offset? members
contacts.list none contacts
contacts.search query peers
contacts.add user, name ok
contacts.block user, on ok
chat.create kind, title, members? peer
chat.join link_or_name peer
chat.leave peer ok
chat.delete peer ok
chat.invite_link peer link
account.profile none profile
account.update_profile fields profile
account.sessions none sessions
account.terminate_session hash ok
account.privacy key rules
premium.state none state
premium.translate peer, id, to text
premium.transcribe peer, id text
premium.emoji_status document_id, until? ok
premium.profile_color color, background? ok
messages.pinned peer messages
messages.scheduled peer messages
messages.scheduled_delete peer, ids ok
messages.scheduled_send_now peer, ids ok
messages.send_sticker peer, sticker message
bot.commands peer commands
bot.inline bot, peer, query results
bot.inline_send peer, query_id, result_id message
contacts.import contacts imported
stickers.search query? stickers
emoji.custom query? emoji
stickers.sets emoji? sets
stickers.set short_name stickers
stickers.premium none stickers
account.set_privacy key, rule ok
account.notifications none scopes
account.set_notifications scope, muted ok
auth.resend_code none sent, type, next_type, timeout
chat.add_members peer, users ok
chat.remove_member peer, user ok
chat.set_admin peer, user, on ok
premium.promo none promo
premium.translate_toggle peer, disabled ok
premium.transcribe_rate peer, id, transcription_id, good ok
premium.emoji_statuses none statuses
premium.name_color color, background? ok
premium.reaction_tags peer? tags
premium.reaction_tag_set reaction, title? ok
premium.effects none effects
premium.wallpapers none wallpapers
premium.wallpaper_set peer, slug, for_both? ok
premium.wallpaper_remove peer ok
premium.privacy_global none settings
premium.privacy_global_set settings ok
premium.privacy_voice who ok
premium.custom_emoji ids documents
business.get none settings
business.hours_set hours? ok
business.location_set location? ok
business.greeting_set greeting? ok
business.away_set away? ok
business.intro_set intro? ok
business.bots none bots
business.bot_set bot, recipients, rights?, remove? ok
business.quick_replies none replies
business.quick_reply_messages id messages
business.quick_reply_add shortcut, text message
business.quick_reply_rename id, shortcut ok
business.quick_reply_delete id ok
business.quick_reply_send peer, id ok
business.chat_links none links
business.chat_link_create message, title? link
business.chat_link_delete slug ok
stories.list hidden?, state? stories
stories.peer peer stories
stories.read peer, max_id ok
stories.send path, caption?, privacy?, period?, pinned? story
stories.delete peer, ids ok
stories.views peer, ids views
stories.view_list peer, id, offset?, limit? views
stories.react peer, id, reaction ok
stories.archive peer, offset_id?, limit? stories
stories.stealth past?, future? ok
stories.pin peer, ids, pinned ok
stories.link peer, id link
gifts.list none gifts
gifts.saved peer, offset?, limit? gifts
gifts.stars peer? status
gifts.send peer, gift, message?, hide_name?, confirm result
payments.form peer, id form
payments.receipt peer, id receipt
passport.values none values
secret.list none chats
secret.request user chat
secret.accept chat chat
secret.discard chat, delete_history? ok
secret.send chat, text, ttl? message
secret.ttl chat, seconds ok
secret.typing chat, on ok
secret.fingerprint chat fingerprint
secret.history chat messages
calls.request user, video? call
calls.accept call call
calls.discard call, reason?, duration? ok
calls.rate call, stars, comment? ok
calls.list none calls
calls.group_create peer, title? group_call
calls.group_get call, access_hash group_call
calls.group_discard call, access_hash ok
dialogs.folder_set folder folder

In the Params column a trailing ? marks an optional parameter; a call with a missing required or an unknown parameter is rejected with bad_params and counted. All int64 ids travel as decimal strings (D-14).

Media (FR-30 to FR-33). A media token identifies a message's media (user:100/1234) or a story's (story:user:100/7). media.download returns the path of a verified file in the daemon's cache; with thumb true it returns the small preview instead, which is cached separately. messages.send_file takes kind: photo, video, voice, audio or document (default: by file extension, see sendKindForPath). messages.send_album sends 2 to 10 photos or videos as one grouped message (the 10 is Telegram's own limit); the caption goes on the first. A message's media.waveform is the voice note's waveform as a list of 0 to 31 samples.

Parameter values (the contract between the UI and the service layer; ids are strings, D-14):

  • messages.send / messages.edit: format is html when the text carries our formatting tags (b i u s code pre tg-spoiler, a href), the other characters already escaped (&amp; &lt; &gt;); absent means plain text. entities is an array of {type:"custom_emoji", offset, length, document_id} with UTF-16 offsets (Premium, premium_required without it); entities and format are not combined. schedule is a unix time in the future: the message is scheduled, not sent, and the reply is the scheduled message. Sending clears the draft of that chat on the server.
  • messages.send_poll: multiple and quiz are booleans, correct is the zero-based index of the right option (quiz only).
  • messages.search: filter is empty or one of photo, video, file, link, voice, gif, music; peer absent searches everywhere; query may be empty with a filter (shared media lists).
  • messages.delete: revoke false deletes for this account only.
  • messages.draft: a changed draft produces a dialog.updated event (also to the process that wrote it) so other windows of the account follow.
  • chat.create: kind is group, channel or forum; members is an array of peer keys. chat.add_members takes users (peer keys); chat.set_admin takes on.
  • contacts.import: contacts is an array of {name, phone}; the result imported counts the people added.
  • account.privacy / account.set_privacy: key is one of last_seen, profile_photo, phone_number, calls, groups, forwards, about, voice_messages (Premium), read_time (Premium); rule is everybody, contacts or nobody. account.notifications returns {private:{muted}, groups:{muted}, channels:{muted}}; account.set_notifications takes one of those scopes and muted.
  • peer.members entries carry role: empty, admin or owner.
  • stickers.search returns {stickers:[{id, emoji, title, animated, premium}]}; emoji.custom returns {emoji:[{id, fallback, title}]}; messages.send_sticker takes sticker (an id from stickers.search).
  • bot.commands returns {commands:[{command, description}]}; bot.inline returns {query_id, results:[{id, title, description}]}; bot.inline_send sends one result.
  • auth.send_phone / auth.resend_code: phone may be empty, then the service uses the phone of the config. The result says how Telegram delivers the code: type is app (a message from the account "Telegram" in the Telegram app on the user's other devices), sms, call, flash_call, missed_call, email_code, firebase_sms, fragment_sms, sms_word, sms_phrase or already_signed_in (no code needed); next_type is how a resend would arrive (empty when there is none); timeout is the seconds Telegram asks to wait before a resend. The UI shows this to the user.
  • auth.state may carry hint (the 2FA password hint) in the need_password state; auth.resend_code asks for a new code.
  • Service contract details (track D, the real service answers exactly this):
    • messages.send / messages.edit: format absent or plain sends the text exactly as typed (no parsing); html parses the tags b i u s code pre tg-spoiler a; any other value is bad_params. Sending clears the server draft. schedule is a unix time; the reply is the scheduled message.
    • messages.search: filter accepts photo, video, file, link, voice, gif, music (plural spellings also); an unknown filter is bad_params.
    • messages.pinned / messages.scheduled return {messages} ascending by id.
    • messages.scheduled_delete removes scheduled messages, messages.scheduled_send_now sends them at once (the sent messages arrive as message.new). chat.delete deletes a group or channel for everybody and only works for its creator; chat.leave only removes the account.
    • stickers.search with an empty query returns the recently used stickers, with an emoji the stickers for that emoji, with words the stickers of the sticker sets found by that name. Each sticker is {id, emoji, title, mime, animated, video, premium, custom_emoji}. stickers.sets returns {sets:[{id, short_name, title, count, emojis, masks, official, archived}]} (emoji true lists the custom emoji sets), stickers.set the stickers of one set by short_name, stickers.premium the Premium stickers (Premium gifts set plus recent stickers with a Premium animation). messages.send_sticker needs an id the service listed before, else bad_params.
    • emoji.custom with an empty query lists the custom emoji of every installed emoji set; with words it searches emoji sets by name; with an emoji it also matches installed custom emoji by their fallback emoji.
    • bot.commands returns {commands:[{command, description, bot}]} (a user chat: that bot; a group or channel: every bot in it). bot.inline returns {query_id, next_offset, results:[{id, type, title, description}]} with query_id a string; bot.inline_send takes that query_id.
    • contacts.import returns {imported, not_on_telegram}; contacts are sent in batches, any number is accepted. chat.add_members returns {missing} (people whose privacy settings stopped the invitation); chat.set_admin gives or takes the usual admin rights.
    • account.privacy returns {key, rule, rules} (rules are the raw rule type names, exceptions included); account.set_privacy replaces only the base rule and keeps the exception lists. read_time (Premium) accepts everybody or nobody. An unknown key or rule is bad_params; no value is ever guessed.
    • stories.send takes a photo (jpg, png, webp) or a video (mp4, mov, m4v, webm, mkv); a video needs ffprobe to read its size and length and is refused with VIDEO_STORY_UNREADABLE without it. privacy is everyone, contacts, close_friends or self; any other value is bad_params, never widened.
    • Secret chats: decrypted messages are kept in data_dir/secret_history.json (mode 0600, first line is the SHA-256 of the JSON). A file that does not verify is ignored and counted, never half-loaded; a disk that refuses the write raises service.warning and the history stays in memory.
    • peer.members entries carry role ("", admin, owner); auth.resend_code returns {sent, type, next_type, timeout?} with the delivery types app, sms, call and so on.

Events and their d payloads (names are exact; ids are strings, D-14):

Event Payload
message.new, message.edited {message}
message.deleted {peer, ids}
message.read {peer, max_id, outgoing}; outgoing true means the other side read our messages up to max_id
typing {peer, name, action}; action is typing, recording, uploading, or empty when it stopped
presence {peer, online, status}
dialog.updated {dialog}
premium.changed {state} (premium, not_premium, unknown)
connection.state {state} (connected, disconnected, connecting, reconnecting)
auth.state {state} (as auth.state results)
transfer.progress {id, done, total}
message.reactions {peer, id, reactions} (reaction counts of one message changed)
transcription {peer, id, transcription_id, text, pending} (voice-to-text arrived or finished)
story.updated {peer, story}
secret.chat {chat} (requested, ready or discarded)
secret.message {message} (decrypted secret chat message)
call.state {call} (ringing, exchanging, active, ended)
service.warning {what, text}; the service could not do something it normally does and carries on (for example secret_history_not_saved: the disk refused the secret chat history, the message is kept in memory)

6.5 Premium features

Feature Gated call Fallback without Premium Method
extra_reactions messages.sendReaction free reactions only, picker shows lock messages.react
custom_emoji_reactions messages.sendReaction lock on the custom tab messages.react
saved_tags messages.updateSavedReactionTag tags hidden, lock premium.reaction_tag_set
custom_emoji_message send with MessageEntityCustomEmoji fallback emoji sent messages.send
emoji_status account.updateEmojiStatus lock on the status button premium.emoji_status
message_effects messages.sendMessage effect plain message messages.send
premium_stickers stickers static preview, lock premium.custom_emoji
voice_to_text messages.transcribeAudio lock on the transcribe button premium.transcribe
translate messages.translateText lock on translate premium.translate
big_upload upload.saveBigFilePart server file-size error text messages.send_file
fast_download upload.getFile normal speed media.download
profile_color account.updateColor lock premium.profile_color
profile_background account.updateProfileColor lock premium.profile_color
wallpapers account.setChatWallpaper lock premium.wallpaper_set
folder_tags messages.updateDialogFilter lock dialogs.folder_set
auto_archive account.setGlobalPrivacySettings lock premium.privacy_global_set
read_time_privacy account.setGlobalPrivacySettings lock premium.privacy_global_set
voice_privacy account.setPrivacy lock premium.privacy_voice
story_extras stories.* normal story options stories.stealth
business account.updateBusiness* lock business.get
gifts payments.* lock gifts.send

6.6 Widgets

Telegram widgets come from rgui tgwidgets.hpp (themable by uiColors). mologram classes:

Widget Role
MainWindow three pane host
ChatWindow tear-off and floating host
ChatListPane list, folders, search
ChatPane header, messages, composer
InfoPane profile
PremiumPanel calm Premium dialog
LoginDialog login
SettingsDialog settings
SearchDialog search
ForwardDialog forward
AttachDialog attach
EmojiDialog emoji picker
ContactsDialog contacts
NewChatDialog create chat
StoriesViewer stories
CallPanel calls
HelpOverlay key list

7. Estimates (person-weeks, one developer, ranges)

Area PW Driver
Spec, ADRs, build system, config, drift test 1 to 1.5 spec size, registries
ITelegramService, models, Fake service 1 to 1.5 model breadth
Protocol, daemon, RemoteService, MediaCache 2 to 3 races, failure injection
TapiService (all FR groups) 3 to 4 breadth of tapi surface
UI main window, chats, messages 3 to 4 rgui glue, scroll, paging
Dialogs and settings 2 to 3 count of dialogs
Tear-off and floating windows 1 to 1.5 terminal behavior
Media (images, files, voice, animated) 3 to 4 decoders, Lottie
Premium (all features, three-way tests) 2 to 3 tapi extensions
Business, stories, gifts, calls, secret chats 4 to 8 protocol size, audio
Verification live and static gate 1 to 2 account actions
Total 23 to 35

Scope freeze: D-06. Dates move when the total moves; this table is recomputed on every scope change.

7.1 Actuals and what is left (2026-11-05)

The table above is for one human developer and was not calibrated: all milestones M0 to M11 (service side) were produced in one working day by an LLM agent and three parallel forks, so person-weeks cannot be compared. Not measured: human review effort, live-test calendar time. What is left, as human estimates:

Open item PW Driver
Call audio (reflector UDP protocol, Opus decoder and encoder in pure C++, audio device access) 6 to 10 no static libopus or audio libraries under PIN-03 (measured: shared only)
Forum topics and channel comments (FR-14, FR-15) 1 to 1.5 new protocol methods, topic list UI
Admin tools: slow mode, admin log, permissions (FR-40) 1 protocol methods and dialogs
UI for secret chats and calls (FR-52) 1 to 1.5 dialogs, key emoji view, call panel
Logging to data_dir/log (OPS-03) 0.3 one class, daily file
Pane resizing, mention and hashtag completion, scheduled list (FR-70, FR-22, FR-23) 1 rgui SplitPane glue
RTL reordering in rgui (NFR-05) 1 to 2 UAX #9 implementation and tests
Live verification of write paths and a second party 1 needs a second account

8. Risks

  • R-01: Calls need a VoIP stack that tapi does not have. Mitigation: milestone isolated at the end; open gap listed in README until done.
  • R-02: Terminal drag-out detection varies by emulator (A-02). Mitigation: four other tear-off paths.
  • R-03: Static glibc and NSS (A-06). Mitigation: D-09.
  • R-04: Premium behavior can only be measured on the owner's account. Mitigation: three-way tests with error injection (FR-66).
  • R-05: Concurrent tapi use (A-01). Mitigation: D-04, one worker.
  • R-06: Call audio cannot be built under PIN-03 (no static Opus or audio libraries). Mitigation: signaling is built and live checked; the audio path is estimated in 7.1 and listed in README Open gaps.
  • R-07: Unlimited in-memory image caches (ADR 0007) can grow with long sessions. Mitigation: derived data, rebuilt on demand; the owner can ask for an LRU later.

9. Decisions

  • D-01: Daemon plus UI processes, because a tapi session is single-process (flock).
  • D-02: No caps, floors, timeouts, quotas, retention or rate limits of our own, by owner instruction on 2026-11-05. This overrides the skill's caps rule (ADR 0002).
  • D-03: Object oriented: one responsibility per class, interfaces at module borders.
  • D-04: One worker thread owns all blocking tapi calls; an event pump thread feeds the EventBus; UI never calls tapi.
  • D-05: Transport Tycoon look stays (owner decision).
  • D-06: Scope is frozen to this spec; new ideas go to a later release.
  • D-07: Static binaries, -static -pthread, a Containerfile only copies them (ADR 0004).
  • D-08: Ctrl+K is the link dialog when the composer has a selection, search otherwise.
  • D-09: Connect to hardcoded DC IPs first, getaddrinfo second, loud counted error if both fail.
  • D-10: Premium absence is a normal state (FR-61 to FR-66); one PremiumState, one error type.
  • D-11: Secrets are human-only: the agent never reads, prints, copies or moves them; the owner copies .env.json (ADR 0006).
  • D-12: Dependency changes happen in the dependency's own repo, via UPSTREAM.md and its plan, never patched from mologram.
  • D-18: A reply that arrives after its asker is gone is dropped: every service request remembers the dialog window or chat session it came from (ServiceClient::Scope), and a closed window or destroyed session never receives it. Premium refusals are the exception, they still flip the Premium state. Dialogs that close themselves right after firing a request close first, so their reply (a toast, a reload) is not dropped with them.
  • D-17: Formatting is decided from the text, not from a flag: a message is sent with format:"html" exactly when it contains one of our formatting tags. The editor has no selection, so a format action inserts an opening and closing tag with the caret between them.
  • D-16: Alt+letter keys are compared in canonical form (Alt+c from a terminal equals Alt+C in the spec), see ActionRouter::canonicalKey.
  • D-15: Terminals cannot deliver every Telegram Desktop key: Ctrl+I arrives as Tab, Ctrl+Comma has no code, and rgui names Ctrl+Shift+letter as Ctrl+letter. Defaults changed to Alt+I (italic), Ctrl+G (forward), F2 (settings). Rebinding stays possible.
  • D-19: One way to attach by paste: a pasted file path (one or several) opens the media send dialog (caption, album, as document). Ctrl+O opens the file chooser (AttachDialog), which hands its file to the same sender.
  • D-14: int64 ids (peer, message, document, file) are decimal strings in JSON, because JSON numbers lose precision above 2^53.
  • D-13: Reconnect retries every 1 s until it succeeds. No cap, no growth, no give-up (a fixed pacing, not a limit).

10. Acceptance criteria and traceability

Every requirement of sections 3.1 to 3.12 (families FR, NFR, UX, SEC, OPS, DOC, TRK) has one row: a testable acceptance line, a status, and the names of the tests that cover it. tests/test_docs.cpp checks that every such ID has exactly one row, that every named test exists in run_tests, and that every open row is listed in README.md under "Open gaps" and in BUILD-TRACK.md. Status covered means the acceptance line is fully tested offline; partial means the text after "Open:" is not built or not tested; open means nothing is built. Test names are separated by ;;.

Requirement Acceptance Status Tests
FR-01 Phone, code, 2FA password and QR login complete against the service; a wrong code shows the server text. With the number in the config the code is requested at once; with an exported auth key (mologramd --import-auth) no code is needed. The chat list loads right after the login. covered login flow: phone, code, password ;; login dialog opens in every state at 40x15, 80x24 and 160x50 ;; login: phone, wrong code with the server text, resend, 2FA password, ready ;; login by QR code shows the token and finishes when the service reports ready ;; login: the number is in the config, so the code is requested without typing and the dialog says it went to the app ;; login: without a number in the config the phone field waits for the user and nothing is sent ;; login: before the login finished no chats are requested; after it they load ;; import auth: the data centre and key of an exported tsv end up in the session file with mode 0600
FR-02 Accounts are found by their session files; each has its own session and socket path; switching starts that account. covered accounts: profiles are found by their session files; switch, add and log out ;; account profiles get their own session and socket paths
FR-03 Log out ends the session through auth.logout and the account list updates. covered accounts: profiles are found by their session files; switch, add and log out
FR-04 The 2FA hint, flood-wait text and the resend flow are shown exactly as the server sent them. The code step says where Telegram sent the code (the Telegram app on the user's other devices, SMS, a call, email) and how a resend arrives. covered login: phone, wrong code with the server text, resend, 2FA password, ready ;; error mapping table: premium, cancel, auth, flood, plain server text ;; stickers, bots, contacts, members and login: bad input is rejected before the network ;; login delivery text names the channel in plain words for every type ;; login: resend changes the explanation to SMS and the automatic request happens only once per run
FR-10 Chat rows show name, preview, time, unread badge, pinned/muted/verified marks, typing text and the draft marker. covered app shows chats, folders and status from the service ;; incoming message: appended in the open chat, counted as unread elsewhere ;; drafts are saved while typing and show up in the chat list ;; chat row menu: pin, mute, archive, mark read, delete through the controller and the context menu ;; event conversion: presence and typing from user updates
FR-11 Folder tabs and the archive tab filter the list; pin, mute, archive, mark read, delete and leave reach the service. covered app shows chats, folders and status from the service ;; chat row menu: pin, mute, archive, mark read, delete through the controller and the context menu ;; a mouse click on a chat row opens it
FR-12 Global search finds chats and messages, per-chat search stays in the chat, shared-media filters come from messages.search. covered global search finds chats and messages and opens a result; scoped search stays in one chat ;; profile media tabs: media, files and links come from messages.search filters and open the right way ;; search filters and polls: unknown values and impossible quizzes are rejected
FR-13 Saved reaction tags work through the service. Open: the Saved dialogs view. partial premium extras: tags, wallpapers, privacy, effects round trip when Premium
FR-14 Forum topics can be listed, opened, created, edited, closed and deleted. Open: no protocol method yet. open -
FR-15 Channel comments and thread replies open as a conversation. Open: no protocol method yet. open -
FR-20 Formatted send, reply, edit, delete for me or everyone, forward, copy, multi-select and pin reach the service and the view. covered send from the composer reaches the service and the view exactly once ;; reply, edit and delete through the controller ;; forward dialog filters the chats and forwards the chosen messages ;; formatting actions insert tags with the caret between them and the message is sent as formatted ;; multi-select then delete removes exactly the selected messages ;; delete for me sends revoke=false; cancel deletes nothing; the context menu asks too ;; pin, pinned bar, jump and unpin ;; text contract: only plain or html, entities and format are not combined
FR-21 History pages older and newer without gaps, the open chat keeps its position, the first unread gets a divider, days are separated. covered history pages older and newer without gaps ;; opening a chat loads its history and header ;; jumping to a message that is not loaded fetches the page around it ;; the first unread message gets a New messages divider ;; a conversation opened before the daemon connection was up loads when it connects
FR-22 Drafts are saved while typing and follow to the other windows; a scheduled message stays out of the history. Open: a list view for scheduled messages. partial drafts are saved while typing and show up in the chat list ;; a draft typed in a floating window appears in the other windows of that chat ;; schedule dialog parses the time and keeps the message out of the history ;; no TapiService method answers 'not implemented': the stub file is gone and the phrase appears nowhere in src/tapi ;; scheduled messages: listed, deleted, and sent now into the history
FR-23 Bot commands, inline bots and bot buttons work; typing @, # or / offers people, hashtags and commands. Open: service provided link previews. partial bot commands dialog lists the commands of a bot chat and inserts the chosen one ;; stickers, inline bots, bot buttons and edit-last by the Up key ;; @bot query asks the inline bot; other @ text is sent as it is ;; suggestion word: trigger at the start or after a space, caret inside the word ;; suggestions: people with a username, hashtags by use, commands by prefix ;; accepting a suggestion replaces the word and leaves exactly one space ;; typing @ in a group offers its people; Enter inserts and does not send ;; Escape closes the popup and keeps the text; Down moves the choice ;; typing # offers hashtags seen in the chat, most used first ;; typing / in a bot chat offers its commands; elsewhere nothing opens ;; the popup stays inside the work area at 40x15 ;; stickers, bots, contacts, members and login: bad input is rejected before the network
FR-24 Reactions and polls (create, vote) work. Open: dice, location, contact and venue cards beyond a text tag. partial reaction picker: a free reaction works, custom emoji need Premium (three ways) ;; poll dialog creates a poll with the typed options ;; voting in a poll through the message view reaches the service ;; search filters and polls: unknown values and impossible quizzes are rejected
FR-25 Read state, edited mark, forward header and reply quote follow the service. Open: via-bot and sponsored marks. partial event conversion: new, edited, deleted, read, connection state ;; incoming message: appended in the open chat, counted as unread elsewhere ;; reply, edit and delete through the controller
FR-30 Files and photos are sent by kind (extension) or as album or document, with caption, progress and cancel; a pasted path asks first. covered pasted paths: quotes, escapes, file URLs, lines; only existing files survive ;; send dialog: describes files, offers an album only for 2+ photos/videos, calls back with the choice ;; sending: kind by extension, album, failure text, progress rows, cancel ;; paste of a file path asks, then sends; text that is not a path goes to the composer as before ;; attach dialog lists directories, sends the file with its caption, and a pasted path attaches it
FR-31 Downloads show progress, can be cancelled, are verified, never overwrite on save as, and open with the system tool; previews come first. covered media store: one transfer per token, progress, done path, cached after ;; media store: progress events move the percentage ;; media store: cancel stops a running download and reports cancelled ;; media store: a failing download reports the server's text ;; host tools: find, save as never overwrites silently, missing audio player and file errors are plain ;; transfer list: a running transfer is cancelled with c, a progress bar fills ;; viewer: browsing with keys and mouse, fit toggle, close, failure note offers the system player ;; module in the app: click opens the viewer, menu entries, Save as never overwrites, voice without a player is a plain message
FR-32 Images in bubbles show the thumbnail first, then the full file; formats decode; every image mode draws; voice shows its waveform. covered image source: thumbnail shows first, the full image replaces it ;; image source: auto download off fetches only previews until asked ;; image source: formats decode (png-free set: jpeg, gif, webp) and garbage fails with a reason ;; module in the app: click opens the viewer, menu entries, Save as never overwrites, voice without a player is a plain message ;; media at 40x15, 80x24 and 160x50 renders without crashing, with the viewer open ;; image modes: config selects halfblock, kitty, sixel or off; every mode draws a decoded sticker without crashing
FR-33 Animated stickers and GIFs follow the clock and freeze under reduced motion. Open: animated WebP; video needs host ffmpeg. partial image source: formats decode (png-free set: jpeg, gif, webp) and garbage fails with a reason ;; image source: animated GIF and TGS follow the clock; reduced motion freezes them ;; video frames through ffmpeg when it is installed (measured)
FR-40 Members with roles, invite link, join, leave, create group and add or remove members work. Open: slow mode, admin log, permissions. partial new chat dialog creates a group with the chosen members ;; profile dialog: info, shared media sections, members with roles, invite link, member management ;; profile dialog of a person: block and open chat; the info section shows flags ;; chat.delete removes a group for everybody and refuses a person
FR-41 Contacts: search, add, block, unblock, import, open chat; the profile has media, files and links tabs. covered contacts: add from a search, block, unblock, import a file, open the chat ;; contacts picker returns the chosen person once ;; profile media tabs: media, files and links come from messages.search filters and open the right way ;; profile dialog: info, shared media sections, members with roles, invite link, member management ;; profile dialog of a person: block and open chat; the info section shows flags ;; stickers, bots, contacts, members and login: bad input is rejected before the network
FR-42 Typing, presence, read receipts and unread counters follow the events; notifications ring only for unopened unmuted chats. covered event conversion: new, edited, deleted, read, connection state ;; event conversion: presence and typing from user updates ;; simulated incoming message raises unread and emits ;; incoming message: appended in the open chat, counted as unread elsewhere ;; notifications: ring and toast for an unopened unmuted chat, silence for open, muted or disabled
FR-50 Settings edit the profile, privacy, sessions and notifications, apply theme and language at once, rebind keys and are remembered. covered preferences: atomic save and load, corrupt file rejected, recent emoji unique and newest first ;; preferences saved earlier are applied at startup: language, theme and key bindings ;; settings dialog opens every section at 40x15, 80x24 and 160x50 ;; settings: profile edit, privacy cycling, sessions and notifications reach the service ;; settings: Premium-only privacy keys three ways ;; settings: theme and language apply at once and are remembered ;; settings: key binding editor rebinds, rejects conflicts, saves, and resets ;; privacy and notifications: unknown keys, rules and scopes are rejected, read_time has no contacts rule
FR-51 Stories are read, shown as a slideshow that marks them read, and posted with a caption, an audience, a duration and an upload row; views, stealth, react, link, keep and delete work from the viewer. covered story parser: groups items by owner, skips deleted ones, reads video length and tokens ;; stories viewer: slideshow advances by itself, Space pauses, each story is marked read, the last one closes ;; stories viewer: nothing to show is said plainly; a failing list shows the server text ;; post a story: the dialog checks the file, sends stories.send with the caption, shows an upload row ;; stories: send, list, delete; stealth needs Premium ;; story audience and duration choices never widen by accident ;; posting a story sends the chosen audience; the default duration is left to the server ;; a 2 day story needs Premium: locked and explained without it, sent with it ;; story keys: stealth and views are Premium extras, react link keep delete are for everybody ;; story extras with Premium, and with Premium lost midway ;; video paths: the extensions Telegram treats as video ;; an unreadable or missing file gives an unknown probe and no attribute, never a guess ;; a real video is probed: size, length, streaming attribute
FR-52 Payments display, Passport, secret chats and call signaling work in the service layer and in the UI (call panel, secret chat windows, gifts, Passport). Open: call audio (no audio transport exists in this build). partial gifts: sending spends Stars and needs an explicit confirm ;; secret chats: request, send, history, fingerprint, discard ;; calls: outgoing and incoming state machine, honest about media ;; call panel text: buttons, status, fingerprint and the honest audio notice ;; outgoing call from the header button and F7: ringing, active with a fingerprint, hang up ;; incoming call: panel with Accept and Decline, accept shows the key fingerprint ;; declining an incoming call ends it; a second incoming call while one runs is refused as busy ;; the Call button only appears for people, not channels or bots ;; secret chats: create, list, converse, timer, fingerprint, discard ;; gifts: browsing is free, sending is a Premium action that shows the price and charges nothing before the confirm ;; gifts with Premium: pick a person, see the price, Stars are spent only by the explicit button ;; Passport and payments show data read only and report a bad invoice id ;; secret history: saved, then loaded again by a new store; the file is 0600 ;; secret history: a missing file is an empty history; no path means memory only ;; secret history: a tampered or truncated file is refused and counted, never half-loaded ;; secret history: a full disk fails loudly and leaves the previous file intact
FR-60 Every Premium feature of section 6.5 has a case that works with Premium. covered every Premium feature of SPEC 6.5 has a case, three ways: Premium, NotPremium, Premium lost midway ;; premium extras: tags, wallpapers, privacy, effects round trip when Premium ;; Business: every setter needs Premium, reading and quick reply round trip work ;; stories: send, list, delete; stealth needs Premium
FR-61 The Premium state is read after login, mirrored in the UI, changes live and recovers without restart. covered premium three ways: premium, not premium, premium lost midway ;; Premium state is read after login and a regained Premium works again without restart ;; premium: missing Premium shows the calm panel, state flips live, loss midway keeps the draft ;; settings: Premium-only privacy keys three ways
FR-62 Premium refusals map to one error code in one place; plain flood waits never do. covered error mapping table: premium, cancel, auth, flood, plain server text ;; premium text recognition covers PREMIUM_* and PREMIUM but never flood waits ;; premium three ways: premium, not premium, premium lost midway
FR-63 Without Premium a control stays visible with a lock and opens the calm panel; nothing runs. covered premium: missing Premium shows the calm panel, state flips live, loss midway keeps the draft ;; settings Premium section: explains a feature without Premium, nothing happens with it ;; reaction picker: a free reaction works, custom emoji need Premium (three ways) ;; emoji: pick inserts and is remembered, stickers send, custom emoji are Premium (three ways) ;; Premium three ways inside a floating window: a custom emoji reaction ;; Business three ways: without Premium the calm panel opens and nothing is written ;; Business with Premium: quick replies, greeting, hours, location, intro, chatbots, links all write through ;; Business: Premium lost midway flips the state, explains, keeps the typed text
FR-64 Premium lost midway flips the state, keeps drafts and the open chat, and the next call is refused plainly. covered premium: missing Premium shows the calm panel, state flips live, loss midway keeps the draft ;; premium three ways: premium, not premium, premium lost midway ;; Premium state is read after login and a regained Premium works again without restart
FR-65 Custom emoji reactions keep a visible fallback glyph and received content stays when Premium is off. covered premium content stays readable without Premium (FR-65)
FR-66 All Premium features run three ways: Premium, NotPremium, Premium lost midway. covered every Premium feature of SPEC 6.5 has a case, three ways: Premium, NotPremium, Premium lost midway ;; premium three ways: premium, not premium, premium lost midway ;; settings: Premium-only privacy keys three ways ;; emoji: pick inserts and is remembered, stickers send, custom emoji are Premium (three ways) ;; Premium three ways inside a floating window: a custom emoji reaction
FR-70 The layout shows one pane at 40x15 and three at 160x50 and reflows. Open: resizing panes by mouse or keyboard. partial narrow terminal 40x15 renders without overlap or crash and one pane at a time ;; wide terminal 160x50 shows list, conversation and info at once ;; app shows chats, folders and status from the service
FR-71 Every registered action has a handler and a menu entry, runs without crashing, and keys are rebindable. covered every registered action has a handler and a menu entry ;; running every action with a chat open never crashes and leaves no stuck state at 40x15 and 120x34 ;; menu bar has one entry per action menu path ;; settings: key binding editor rebinds, rejects conflicts, saves, and resets
FR-72 Floating chats open, stay in sync, move, resize, snap, appear in the task list and are restored after a restart. covered floating chat windows open, show history, and stay in sync with the main window and each other ;; a draft typed in a floating window appears in the other windows of that chat ;; closing a floating window releases its session; events afterwards are harmless ;; floating windows move, resize, snap and appear in the task list ;; floating windows are restored after a restart with their size and place ;; float_chat opens the active conversation in a floating window by key and by menu
FR-73 Ctrl+T, double click, the menu and an edge drag open a new terminal with --chat; the child follows events and the terminal is restored. covered tear-off command: configured template, $TERMINAL, x-terminal-emulator, gnome-terminal, xterm, none ;; tear-off spawn starts a detached process and reports a missing program ;; Ctrl+T, double click, context menu and edge drag each open a new terminal with --chat and --socket ;; without a usable terminal the conversation opens as a floating window and says why ;; keep_source=false closes the source pane after a tear-off ;; a torn-off process shows its conversation, follows live events and restores the terminal on quit ;; two terminals on one daemon stay in sync: a message typed in one shows up in the other and in the service ;; holding a dragged chat row on the edge tears it off after the hold time, without a release ;; the hold only counts on the edge: leaving it, or releasing in the middle, tears nothing off ;; after a hold tear-off the release does not open a second window; edge_hold_ms 0 keeps only release at the edge
FR-74 Click, double click, right-click menus, media click and the chat-row click work. Open: tests for text selection, tooltips and scrollbars. partial a mouse click on a chat row opens it ;; chat row menu: pin, mute, archive, mark read, delete through the controller and the context menu ;; delete for me sends revoke=false; cancel deletes nothing; the context menu asks too ;; module in the app: click opens the viewer, menu entries, Save as never overwrites, voice without a player is a plain message
FR-75 F1 opens the help window listing every action with its effective key. covered keys: F1 opens help listing the actions, Ctrl+Q quits, Ctrl+Down opens the next chat
NFR-01 Calls are asynchronous with a request id; cancel ends a request; all tapi work runs on one worker thread. covered TapiService runs every call on one worker thread ;; cancel travels over the wire and the request ends cancelled ;; cancel before start yields cancelled and the callback still runs once ;; daemon death fails pending calls with disconnected and the client reconnects when it returns ;; remote calls round trip and events reach every attached client
NFR-02 The terminal is restored after quit, SIGTERM, SIGHUP, a crash signal and a child dying. covered a torn-off process shows its conversation, follows live events and restores the terminal on quit ;; SIGTERM and SIGHUP end a torn-off process normally with the terminal restored ;; a crash of a torn-off process still resets its terminal and dies with the crash signal ;; the daemon keeps serving when a torn-off process dies
NFR-03 The build uses -Wall -Wextra -Wpedantic -Werror for every target. covered build: warning flags, UI layering and the Makefile commands (NFR-03, NFR-04, OPS-01)
NFR-04 No UI or media source includes a tapi header; only src/tapi does. covered build: warning flags, UI layering and the Makefile commands (NFR-03, NFR-04, OPS-01)
NFR-05 Text round trips as UTF-8 through the models. Open: RTL reordering (UAX #9) in rgui. partial message round trip keeps ids above 2^53, media, poll, reactions, buttons ;; config derives an rgui config without unknown-key warnings
NFR-06 Image and colour modes are chosen from the config and the terminal by rgui. Open: a mologram level test of the 16 colour fallback. partial image modes: config selects halfblock, kitty, sixel or off; every mode draws a decoded sticker without crashing ;; config derives an rgui config without unknown-key warnings
NFR-07 The client reconnects every second until it succeeds and reloads what it shows. covered daemon death fails pending calls with disconnected and the client reconnects when it returns ;; a conversation opened before the daemon connection was up loads when it connects ;; a connect-and-leave probe does not make the daemon stop (launcher race) ;; the supervisor relaunches a killed daemon and the client reconnects without help ;; the supervisor leaves a healthy daemon alone and stops promptly when destroyed ;; a UI process in a terminal keeps its draft and open chat when its daemon is killed and comes back
NFR-08 No cap-like identifier exists in the code, the config has no limits section and frames have no size cap. covered no cap-like identifiers in include/ and src/ (allowlist starts empty) ;; no limits section exists in the config schema ;; frame reader handles byte-by-byte feeds, rejects garbage without any size cap
SEC-01 Secrets never appear in dumps, warnings, errors or logs, and the service writes no secrets to disk. covered error text never contains a secret value ;; session file is created with mode 0600 only by tapi's store; the service never writes secrets to disk elsewhere ;; dumpRedacted hides every secret value ;; warnings never echo a secret value ;; missing required keys are reported by name only
SEC-02 --dump-config redacts every secret value. covered dumpRedacted hides every secret value
SEC-03 The daemon socket has mode 0600 and its directory 0700. covered socket permissions: the socket is 0600 and the directory 0700 (SEC-03)
SEC-04 Bad magic, bad version, bad params and a tampered cache file are rejected with a reason and counted. covered bad magic and bad version are rejected, answered and counted ;; media cache stores, verifies, rejects tampering, survives a full disk ;; unknown method and bad params are rejected and counted ;; frame reader handles byte-by-byte feeds, rejects garbage without any size cap
OPS-01 make build, test, run, clean, check, image, up, down, logs and dist exist. covered build: warning flags, UI layering and the Makefile commands (NFR-03, NFR-04, OPS-01)
OPS-02 The daemon is started by the launcher and stops when the last UI leaves; a connect-and-leave probe does not count. covered daemon stops when the last UI process leaves unless told to stay ;; a connect-and-leave probe does not make the daemon stop (launcher race) ;; stale socket file is detected and replaced; a live daemon and a second lock holder are refused ;; the supervisor relaunches a killed daemon and the client reconnects without help ;; the supervisor leaves a healthy daemon alone and stops promptly when destroyed ;; a UI process in a terminal keeps its draft and open chat when its daemon is killed and comes back ;; --no-daemon needs the account keys and says which are missing; --help names the process options
OPS-03 A daily log file under data_dir/log (mode 0600, appended, no size cap, never deleted); secrets are replaced by ; failed requests, login steps and start-up problems are logged by the daemon and the UI process. covered log: one file per day under the directory, appended, mode 0600, never needs the directory to exist ;; log: registered secrets never reach the file, newlines are flattened ;; log: concurrent writers never interleave inside a line and nothing is dropped ;; table service reports every finished request, success and failure, to onResult
OPS-04 VERSION, the generated version header and the newest changelog row agree. covered version: VERSION, the generated header and the changelog agree (OPS-04)
UX-01 The layout adapts: one pane at 40x15, list plus conversation, then three panes at 160x50. covered narrow terminal 40x15 renders without overlap or crash and one pane at a time ;; wide terminal 160x50 shows list, conversation and info at once ;; people dialogs open and fit at 40x15, 80x24 and 160x50
UX-02 Every dialog opens and fits at 40x15, 80x24 and 160x50. covered every message dialog opens and fits at 40x15, 80x24 and 160x50 ;; people dialogs open and fit at 40x15, 80x24 and 160x50 ;; settings dialog opens every section at 40x15, 80x24 and 160x50 ;; login dialog opens in every state at 40x15, 80x24 and 160x50 ;; emoji dialog opens at 40x15, 80x24 and 160x50
UX-03 Every action works by keyboard and by mouse. covered keys: F1 opens help listing the actions, Ctrl+Q quits, Ctrl+Down opens the next chat ;; every registered action has a handler and a menu entry ;; running every action with a chat open never crashes and leaves no stuck state at 40x15 and 120x34 ;; a mouse click on a chat row opens it ;; Ctrl+T, double click, context menu and edge drag each open a new terminal with --chat and --socket
UX-04 The Transport Tycoon look stays; themes change colours only and unknown themes fall back. covered themes change the colours and fall back to defaults for unknown names ;; preferences saved earlier are applied at startup: language, theme and key bindings ;; settings: theme and language apply at once and are remembered
UX-05 A failure shows the server text unchanged and never a stack trace or a blank result. covered edit of a foreign message and send of empty text return server style errors ;; login: phone, wrong code with the server text, resend, 2FA password, ready ;; error mapping table: premium, cancel, auth, flood, plain server text ;; stories viewer: nothing to show is said plainly; a failing list shows the server text ;; media store: a failing download reports the server's text
UX-06 Long operations show progress and can be cancelled. covered media store: cancel stops a running download and reports cancelled ;; transfer list: a running transfer is cancelled with c, a progress bar fills ;; sending: kind by extension, album, failure text, progress rows, cancel ;; cancel travels over the wire and the request ends cancelled
UX-07 The interface language falls back to English key by key and is remembered. covered language table: every key exists in every language, unknown keys and languages are safe ;; settings: theme and language apply at once and are remembered ;; preferences saved earlier are applied at startup: language, theme and key bindings
DOC-01 Every markdown file has a versioned header on line 1 and a row in the doc register. covered docs: markdown files carry a versioned header and are in the doc register; runbooks are drilled
DOC-02 Every class in include/ appears in DESIGN.md with responsibility, owner, lifetime and thread. covered docs: every class in include/ is described in DESIGN.md
DOC-03 The key table in README.md is identical to the action registry, row by row. covered docs: the README key table equals the action registry
DOC-04 Every runbook has a dated drill entry; the test rejects a runbook that says Never. covered docs: markdown files carry a versioned header and are in the doc register; runbooks are drilled
TRK-01 BUILD-TRACK.md was updated within 7 days and names every open requirement. covered docs: the build track sheet is not stale (7 days) ;; docs: every requirement has an acceptance line and a covering test that exists

Appendix A. Research log

Date Query or source Synthesis
2026-11-05 tapi live_check against real account, Premium off then on Reaction in Saved Messages returned PremiumAccountRequiredError without Premium, passes with Premium (21 of 21)
2026-11-05 static link stub of libtapi.a + libwolfssl.a links static, 799K, ldd says not a dynamic executable
2026-11-05 rgui ./run_tests 245 run, 231 passed, 0 failed, 14 skipped (opt-in tiers)
264.0ms