| 6 |
| what a widget can call, what travels between sandbox, host and renderer, what |
| 7 | every host exposes and what every client implements, so that client teams can |
| 8 | build their side in parallel with the PoC. Decisions behind it: release plan |
| 9 | D4, D7a, D8, D9, D12, D14, D17, D18, D19, D22, D23, and the decisions of |
| 10 | 2026-10-17 (no keyboard, no form controls, a client-styled `<button>`, |
| 11 | `docs/decisions.md`, "Profile v1"). |
| 12 |
| 13 | What the framework did before v1 is noted where a client may meet it |
| 14 | (**before v1**: the API of the profile-0 builds). |
| 15 |
| 16 | **The widget's state and requests** (2026-10-25, widget interactivity, decision I1 |
| 17 | in `docs/decisions.md`, "The bot's data and requests"; the server's side in |
| 18 | `docs/tgw-format.md`, "The widget's state and requests"): a widget is fixed code |
| 19 | plus changeable state. The code, its HTML, is set when the bot sends the widget |
| 20 | and never changes; the state changes, and only the bot writes it: the **chat |
| 21 | state** (`chatData`: this message in its chat, never forwarded) and the **shared |
| 22 | state** (`publicData`: wherever the widget is shown; a forward gets a copy, or |
| 23 | shares it with the original). The widget reads its state and cannot change it |
| 24 | itself: it can send the bot a request, a callback button inside the widget, and |
| 25 | gets the bot's `result`; the server's flags on the message say where it may ask |
| 26 | (on a tap, or in the background too); `copyText` copies a text on a tap |
| 27 | (§2.13–§2.15). |
| 28 | They are part of SDK v1 and of layer 233 from the launch. A widget in an |
| 29 | inline-results list, before it is sent, runs as a preview (§2.16). |
| 30 |
| 31 | Related documents, not repeated here: `docs/integration.md` (embedding the |
| 32 | host on each platform), `docs/tgw-format.md` (the widget payload: mini-HTML), |
| 33 | `docs/protocol.md` (the full wire protocol), `docs/changes.md` |
| 34 | (per-release notes). |
| 35 |
| 36 | ## 1. Who does what |
| 37 |
| 38 | | | the framework (widget-sandbox) | the client | |
| 39 | |---|---|---| |
| 40 | | widget API | `TelegramWidget`, Web Storage, `CSS.supports`, `navigator.language`, `visibilitychange`, the inert stubs | — | |
| 41 | | checks | argument schemas, user activation, rate limits, storage quota, profile tables, in all five glue copies | — | |
| 42 | | theme | CSS variables on the renderer root, `themeChanged`, the defaults of the root, the text and `<button>` (the UA layer) | maps the bubble's colours to `themeParams`, its button and message text to the button and text tokens, calls `setTheme` | |
| 43 | | links | validates the URL, lets one call through per pointer press | `openLink`: shows the confirmation with the full URL, opens it; `openTelegramLink`: opens it as a `t.me` link in a message, no confirmation of its own | |
| 44 | | haptics | validates, rate-limits, drops calls from hidden widgets | plays them (or ignores them on desktop and web) | |
| 45 | | storage | preload at start, per-task commits, the quota | persists per message, deletes with the message, chat, account, "Clear cache" | |
| 46 | | gestures | reports per press what the widget claims with `touch-action` (horizontal drags, holds); the shared policy (thresholds, who wins); `dblclick` for every double tap, `contextmenu` for claimed holds; on the web, plays the bubble itself | drives its recognizers from the policy: menu and swipe-to-reply unless the widget claims the press, and then cancels the widget's touch; the list scroll always; no double-tap reaction over the widget (v0.1.2; vertical drags the chat's since v0.1.3, §5.5) | |
| 47 | | size | reports the content height and the widget's resize anchor (`setResizeAnchor`, v0.1.3) | sizes the bubble from the bot's hint before load, caps it, clips; keeps the anchored edge in place when the height changes (§5.6) | |
| 48 | | failures | freezes the last frame with a badge and reports `dead` | rebuilds it after a crash; after 2 crashes in a row leaves it stopped | |
| 49 | | the widget's state | `chatData` (the chat state), `publicData` (the shared state), `chatDataChanged`, `publicDataChanged` in the widget; the limits; a copy without chat state | passes the message's state at creation and the full state again on every change (`setData`): the server's update, and the shared state it polls (§5.11) | |
| 50 | | where the widget is | `isForward`, `chatType`, `viewer` in the widget; a copy is told nothing about the chat it is in (no `chatType`); the widget knows its `viewer` only where it may send requests | passes the server's flags (`isCopy`, `canQuery`, `backgroundQuery`), the chat type and the viewer at creation (`context`) | |
| 51 | | requests | the limits of `data`, the server's flags, one tap per request or the background rules, one in flight, the answer's limits | sends each request like a callback button's press, hands back the bot's `result` or the failure (§5.11) | |
| 52 | | copyText | the text's limits, one tap per call | copies the text and shows a toast that says what was copied | |
| 53 |
| 54 | ## 2. Widget-facing API |
| 55 |
| 56 | Everything below is what widget code sees inside the sandbox. The object is |
| 57 | `window.TelegramWidget`; member names follow `Telegram.WebApp` (Mini Apps) |
| 58 | where one exists, so that code and models that know Mini Apps carry over, |
| 59 | and so that a JSON-RPC facade for MCP Apps (`ui/open-link`, |
| 60 | `ui/notifications/host-context-changed`, `ui/notifications/initialized`) can be |
| 61 | laid over the same calls later (D19). |
| 62 |
| 63 | ### 2.1 Members |
| 64 |
| 65 | | member | type | note | |
| 66 | |---|---|---| |
| 67 | | `profile` | `number`, read-only | | |
| 68 | | `isProfileAtLeast(n)` | `(n: number) => boolean` | | |
| 69 | | `colorScheme` | `'light' \| 'dark'`, read-only | before v1: `theme` | |
| 70 | | `themeParams` | `ThemeParams`, read-only, a fresh frozen object per change | | |
| 71 | | `isActive` | `boolean`, read-only (`!document.hidden`) | | |
| 72 | | `contentSafeAreaInset` | `{ top, right, bottom, left, cornerLeft, cornerRight }` in CSS px, read-only, a fresh frozen object per change | §2.17: the client's time over the bottom corner of a widget with no caption below it; detect it with `TelegramWidget.contentSafeAreaInset !== undefined` | |
| 73 | | `onEvent(type, handler)`, `offEvent(type, handler)` | `type`: `'themeChanged' \| 'activated' \| 'deactivated' \| 'chatDataChanged' \| 'publicDataChanged' \| 'contentSafeAreaChanged'` (`chatDataChanged`, `publicDataChanged`: §2.13; `contentSafeAreaChanged`: §2.17); the handler is called with `this` = `TelegramWidget` and no arguments | before v1: `on(event, cb)`, reserved; removed | |
| 74 | | `openLink(url)` | `(url: string) => void` | before v1 without the checks below | |
| 75 | | `openTelegramLink(url)` | `(url: string) => void` | | |
| 76 | | `HapticFeedback.impactOccurred(style)` | `style`: `'light' \| 'medium' \| 'heavy' \| 'rigid' \| 'soft'` | | |
| 77 | | `HapticFeedback.notificationOccurred(type)` | `type`: `'error' \| 'success' \| 'warning'` | | |
| 78 | | `HapticFeedback.selectionChanged()` | `() => HapticFeedback` | | |
| 79 | | `ready()` | `() => void` | | |
| 80 | | `setResizeAnchor(edge)` | `(edge: 'top' \| 'bottom') => void` | v0.1.3 (§2.12); detect it with `typeof TelegramWidget.setResizeAnchor === 'function'` | |
| 81 | | `watchPublicData()`, `unwatchPublicData()` | `() => void` | §2.13: follow the shared state live (the client polls it only for widgets that watch) and stop; no tap needed | |
| 82 | | `chatData`, `publicData` | `string \| null`, read-only | §2.13: the widget's chat state and shared state, which only the bot writes; `chatData` is null in a copy | |
| 83 | | `isForward` | `boolean`, read-only | §2.13: this message is a forwarded copy | |
| 84 | | `chatType` | `'private' \| 'group' \| 'supergroup' \| 'channel' \| null`, read-only | §2.13: null in a copy (it is told nothing about the chat it is in) and in a preview, or when the client does not say | |
| 85 | | `viewer` | `{ id, first_name?, last_name?, username?, is_premium? } \| null` (Mini Apps' `WebAppUser`), read-only, frozen | §2.13: the user looking at the widget; null wherever the widget may not send requests (no `canQuery`), a preview included | |
| 86 | | `isPreview` | `boolean`, read-only | §2.16: an inline result shown before it is sent | |
| 87 | | `request(data, options?)` | `(data: string, options?: { wallet?: boolean }) => Promise<{ result: string \| null }>` | §2.14; `{ wallet: true }`: §2.18 | |
| 88 | | `wallet` | `{ sendTransaction(transaction, data), signData(payload, data) } \| null`, read-only, frozen | §2.18: Gram Wallet; null where the client has no wallet for this user, where the widget may not ask the bot, in a preview | |
| 89 | | `copyText(text)` | `(text: string) => void` | §2.15 | |
| 90 | | `theme`, `onTheme(cb)` | aliases of `colorScheme` and `onEvent('themeChanged')` (the callback gets the colour scheme, at once and on every change) | deprecated | |
| 91 | | `sendMessage` | `typeof TelegramWidget.sendMessage === 'undefined'` | removed | |
| 92 |
| 93 | All methods are synchronous and return `undefined`, except the three haptic |
| 94 | methods, which return `TelegramWidget.HapticFeedback` for chaining, as in Mini |
| 95 | Apps, `isProfileAtLeast`, and `request` and the two wallet calls, which return a promise of the |
| 96 | bot's answer. No other call gets an answer from the client: whether the user |
| 97 | confirmed a link is not reported back. |
| 98 |
| 99 | ### 2.2 Profile detection (D23) |
| 100 |
| 101 | - `TelegramWidget.profile` is the integer version of the widget profile the |
| 102 | client's framework build enforces (`profile` in `VERSION.json`, stamped into |
| 103 | the bundles at build time; profile v1 is `1`). It is a property of the |
| 104 | framework build, not of the client app: clients do not set it. |
| 105 | - `TelegramWidget.isProfileAtLeast(n)` is `profile >= n`; a non-number `n` gives |
| 106 | `false`. |
| 107 | - `CSS.supports(property, value)` and `CSS.supports(conditionText)` answer from |
| 108 | the profile tables compiled into the sandbox bundle: `true` only when the |
| 109 | validator would keep that declaration (one evaluator for both, |
| 110 | `packages/core/src/shared/css-supports.ts`). |
| 111 | - `@supports` rules are evaluated by the validator against the same tables: |
| 112 | the block is kept or dropped before the CSS reaches the renderer, so the |
| 113 | renderer's engine never decides. |
| 114 | - A widget that checks nothing still loads; on an older client the features |
| 115 | outside that client's profile are dropped by its validator (accepted product |
| 116 | behaviour). Clients below API layer 233 receive `messageMediaUnsupported` |
| 117 | with the caption and show their usual placeholder; a client with widget |
| 118 | rendering off does the same (`docs/tgw-format.md`). |
| 119 |
| 120 | ### 2.3 Theme (D14) |
| 121 |
| 122 | `TelegramWidget.themeParams` carries the chat's palette as `#rrggbb` strings |
| 123 | (lowercase), with the keys of Mini Apps' `themeParams`: |
| 124 |
| 125 | | key | meaning inside a bubble | |
| 126 | |---|---| |
| 127 | | `bg_color` | the colour of this bubble, behind the widget: an incoming bubble's, or an outgoing bubble's when the user sent or forwarded the widget (§5.1). The client draws it under the transparent renderer: it is the widget's canvas (§2.4) | |
| 128 | | `text_color` | message text | |
| 129 | | `hint_color` | secondary text: time, meta | |
| 130 | | `link_color` | links in messages | |
| 131 | | `button_color`, `button_text_color` | the client's primary button; also the default `<button>` look (§2.4) | |
| 132 | | `secondary_bg_color` | a second surface on the bubble (quote, inline-button background) | |
| 133 | | `accent_text_color` | accent text | |
| 134 | | `subtitle_text_color` | subtitles | |
| 135 | | `destructive_text_color` | destructive actions | |
| 136 | | `section_bg_color`, `section_header_text_color`, `section_separator_color`, `header_bg_color`, `bottom_bar_bg_color` | no bubble counterpart; filled by the client from the closest colour so that Mini Apps code works (`section_separator_color` draws the lines of a table and `<hr>`, §2.4) | |
| 137 |
| 138 | The palette is the bubble's: a widget in an outgoing bubble gets that bubble's |
| 139 | background, text, hint, link and separator colours, as the client draws a |
| 140 | message there. Every key is always present. The same values are CSS custom properties on the |
| 141 | widget's root element: `--tg-theme-bg-color`, `--tg-theme-text-color`, … (the |
| 142 | key with `_` turned into `-`), plus `--tg-color-scheme: light | dark`. The host |
| 143 | sets them in the renderer; a widget cannot overwrite the root's values, only |
| 144 | shadow them on its own elements. `prefers-color-scheme` media queries and |
| 145 | `color-scheme: light dark` follow the chat's scheme. Keys the client leaves |
| 146 | out take the framework's defaults for the scheme (`DEFAULT_THEME_PARAMS` in |
| 147 | `packages/core/src/shared/sdk-policy.ts`, Web K-like); clients pass every key. |
| 148 |
| 149 | A theme change (the user switches theme, the chat's theme changes, night mode) |
| 150 | updates `colorScheme`, `themeParams` and the variables in one task, then fires |
| 151 | `themeChanged` (and the legacy `onTheme` callbacks). The renderer sets the |
| 152 | variables inline and `!important` on the root, so neither a widget stylesheet |
| 153 | (`:root { … !important }`, any specificity) nor a style the widget sets on its |
| 154 | own root element replaces them. |
| 155 |
| 156 | ### 2.4 The renderer's defaults: the root, the text, `<button>` |
| 157 |
| 158 | Every renderer inserts one user-agent-level stylesheet built from one template |
| 159 | in `packages/core` (`uaStylesheet` in `packages/core/profile.json`, printed in |
| 160 | `docs/profile-v1.md`): `@layer tw-ua` declared first, every selector inside |
| 161 | `:where()`, so any rule of the widget wins over it, whatever its specificity. |
| 162 | A widget without CSS therefore looks the same on every client and like the |
| 163 | client's own messages; the engine's own stylesheet (Times 16 px and an 8 px |
| 164 | body margin in a WebView, litehtml's master CSS) never shows through. Since |
| 165 | v0.1.1 the layer covers the root and the text elements, not only `<button>`: a |
| 166 | clarification of profile 1, not profile 2 (`docs/decisions.md`, "The |
| 167 | renderer's defaults"). |
| 168 |
| 169 | **The root.** `html`: text `--tg-theme-text-color`, font |
| 170 | `var(--tg-text-font-size)/var(--tg-text-line-height) system-ui, sans-serif`, |
| 171 | no text-size adjustment, long words wrap, text not selectable (below). It has |
| 172 | no background of its own: the renderer is transparent and the bubble the |
| 173 | client draws under it, in `bg_color`, is the canvas. A background the widget |
| 174 | sets on its root or on its body paints the whole bubble, as in a browser (root |
| 175 | background propagation: the shadow-DOM renderer paints it on its host |
| 176 | element). `body`: the padding token as its margin |
| 177 | (`margin: var(--tg-text-padding)`), no padding; the first child's top margin |
| 178 | and the last child's bottom margin are dropped, so text starts at the token's |
| 179 | inset as in a message. A widget that writes `body { margin: 0 }` goes edge to |
| 180 | edge, as authors expect from a browser. The content height the renderer |
| 181 | reports, and so the bubble's height, includes the body's margins. |
| 182 |
| 183 | **Text selection** (D18 since v0.1.1). Text in a widget is not selectable by |
| 184 | default: the layer sets `user-select: none` on the root. A widget makes text |
| 185 | selectable with `user-select: text` (or `-webkit-user-select: text`) on an |
| 186 | element; its children follow (`auto`), and `none` turns it off again below. |
| 187 | `user-select: all` and `contain`, `::selection` and editing stay outside the |
| 188 | profile. The widget cannot read or change the selection (`getSelection()` is a |
| 189 | stub); the user selects and copies with the client's own gestures and copy |
| 190 | command (§5.10). A renderer that cannot select text yet keeps it |
| 191 | unselectable: the widget still works (an accepted exception to "every client |
| 192 | draws it", like `:hover`). |
| 193 |
| 194 | **The text elements**, in `em` of the parent's size, so they follow the |
| 195 | client's text size: |
| 196 |
| 197 | | element | default | |
| 198 | |---|---| |
| 199 | | `h1` … `h6` | 1.6, 1.35, 1.2, 1.07, 1, 0.87 em; weight 600; line height 1.25; 0.75 em above, 0.35 em below | |
| 200 | | `p`, `ul`, `ol`, `menu`, `dl`, `pre`, `blockquote`, `figure`, `table` | 0.6 em above and below | |
| 201 | | `ul`, `ol`, `menu` | 1.5 em of start padding; disc, decimal; a list inside a list item: circle, no margins | |
| 202 | | `dt`, `dd` | weight 600; 1.5 em of start margin | |
| 203 | | `table` | collapsed borders, no spacing; cells 0.3 em × 0.6 em of padding, start-aligned, top, a 1 px `--tg-theme-section-separator-color` line under each; `th` 600; no outer padding on the first and last cell of a row, so the text lines up with the paragraphs; `caption` in the hint colour, 0.87 em | |
| 204 | | `hr` | one 1 px line in `--tg-theme-section-separator-color`, 0.6 em margins | |
| 205 | | `pre`, `code`, `kbd`, `samp` | `ui-monospace, monospace` at 0.9 em (once: `code` inside `pre` keeps the size); `pre` wraps (`pre-wrap`, the bubble does not scroll) on a translucent grey, 0.5 em × 0.7 em of padding, 6 px radius | |
| 206 | | `blockquote` | no indent; a 3 px bar in `--tg-theme-accent-text-color` and 0.75 em before the text | |
| 207 | | `figure`, `figcaption` | no indent; `figcaption` in `--tg-theme-hint-color` at 0.87 em | |
| 208 | | `a[href]` | `--tg-theme-link-color`, not underlined | |
| 209 | | `b`, `strong`; `i`, `em`, `cite`, `dfn`, `var`; `small`; `sub`, `sup`; `mark` | 600; italic; 0.85 em; 0.75 em, shifted without changing the line height; a translucent yellow | |
| 210 | | `img` | at most the bubble's width (`max-width: 100%`; the `width`/`height` attributes still apply) | |
| 211 |
| 212 | Every property that WebKit's, Chromium's or litehtml's own stylesheet sets |
| 213 | differently is set here, so the three draw the same. RTL widgets get the list, |
| 214 | `dd`, table and quote indents on the right (logical properties after the |
| 215 | physical ones, which litehtml keeps). |
| 216 |
| 217 | **The text tokens.** The client passes them in the theme (`WidgetTheme.text`, |
| 218 | §4); the renderer checks each one and always sets the three variables on the |
| 219 | root, with the reference value for a token it did not get or refused: |
| 220 |
| 221 | | token (`text.…`) | variable | grammar | reference value | |
| 222 | |---|---|---|---| |
| 223 | | `fontSize` | `--tg-text-font-size` | CSS px (= points, dp) 8–64: a number, or a string `"15px"` | `15px` | |
| 224 | | `lineHeight` | `--tg-text-line-height` | a unitless number 1–3 | `1.35` | |
| 225 | | `padding` | `--tg-text-padding` (the body's margin) | one to four CSS lengths in `px`, `em`, `rem` | `8px 12px` (vertical, horizontal) | |
| 226 |
| 227 | `fontSize` is the chat's message text size: it follows the client's text-size |
| 228 | setting, and the client calls `setTheme` when it changes. A widget may use the |
| 229 | variables in its own CSS (`calc(var(--tg-text-font-size) * 1.2)`). Every |
| 230 | reference picture (the conformance set, the corpus reference mode) is drawn |
| 231 | with the reference set and the default palettes |
| 232 | (`packages/core/src/shared/reference.ts`). |
| 233 |
| 234 | **The `<button>`.** A `<button>` the widget did not style is drawn in the |
| 235 | client's own button style; any author CSS overrides it (`docs/decisions.md`, |
| 236 | "Profile v1"). The template fixes the states: base, `:active` (not disabled), |
| 237 | `[disabled]`; no hover state, no focus ring. |
| 238 |
| 239 | The client passes its tokens in the theme (`WidgetTheme.button`, §4); the |
| 240 | renderer sets each one it gets as the variable on the root and checks its |
| 241 | grammar (`themeVariables`): colours `#rrggbb`, lengths in `px`/`em`/`rem`, a |
| 242 | font shorthand naming generic families only, opacities 0–1. A token the client |
| 243 | does not pass keeps the template's default: |
| 244 |
| 245 | | token (`button.…`) | variable | the template's default | |
| 246 | |---|---|---| |
| 247 | | `bg` | `--tg-button-bg` | `rgba(51,144,236,.12)`: a tint, so that a widget that sets only its own `color` or only its own `background` stays readable (`docs/decisions.md`, "Profile v1") | |
| 248 | | `text` | `--tg-button-text` | `inherit` | |
| 249 | | `radius` | `--tg-button-radius` | `8px` | |
| 250 | | `font` | `--tg-button-font` | `500 14px/1.2 system-ui,sans-serif` (D3b) | |
| 251 | | `padding` | `--tg-button-padding` | `8px 14px` | |
| 252 | | `height` | `--tg-button-height` (minimum height) | `auto` | |
| 253 | | `pressedOpacity`, `disabledOpacity` | `--tg-button-pressed-opacity`, `--tg-button-disabled-opacity` | `.7`, `.5` | |
| 254 |
| 255 | A client whose buttons are solid (`bg` = its button colour, `text` = white) |
| 256 | accepts that a widget overriding only its button's `background` keeps the |
| 257 | client's text colour on it. |
| 258 |
| 259 | Other form controls are outside the profile and dropped by the validator. |
| 260 |
| 261 | ### 2.5 Links (D8) |
| 262 |
| 263 | - `openLink(url)` opens an external page. `url` must be an absolute `https:` |
| 264 | URL of at most 256 characters, without user name or password, |
| 265 | whose host is not `t.me`, `telegram.me` or `telegram.dog`. |
| 266 | - `openTelegramLink(url)` opens a Telegram link: `https://t.me/…` (also |
| 267 | `telegram.me`, `telegram.dog`), at most 256 characters, any path, as in Mini |
| 268 | Apps: the client's own `t.me` handler confirms the dangerous ones (proxy, |
| 269 | login, language and the like). `tg:` URLs are not accepted. |
| 270 | - An invalid argument throws `TypeError` in the widget synchronously (the shim |
| 271 | checks the syntax; the glue checks it again). A valid call returns |
| 272 | `undefined` and goes to the host. |
| 273 | - **User activation** (`docs/protocol.md`, "User activation"): the glue |
| 274 | forwards a call only while the task of a real pointer press on the visible |
| 275 | widget runs, and one press unlocks one call shared by both methods. A press |
| 276 | is `pointerdown` … `click` from the renderer, marked `trusted` (a finger's or |
| 277 | a pen's from its `pointerup`: the renderer does not mark their `pointerdown`, |
| 278 | which may still become the chat's scroll), and the |
| 279 | `dblclick` that ends a double tap (delivered since v0.1.2, §2.10) belongs to |
| 280 | the press of its second click; |
| 281 | keys never count (D4: no keyboard input or focus at all), nor does a click a |
| 282 | key produced (`detail` 0), a scripted `click()`, a timer, a frame or a promise |
| 283 | job after the task. Blocked calls are dropped without an exception and |
| 284 | reported as the diagnostic `activation-blocked` (at most 20 per widget). |
| 285 | - `<a href="https://…">` clicks and `window.open(url)` take the same path: the |
| 286 | shim calls `openTelegramLink` for Telegram hosts and `openLink` otherwise |
| 287 | (before v1 everything went to `openLink`); what neither accepts (`http:`, |
| 288 | `javascript:`) is ignored with the diagnostic `navigation-blocked`, never an |
| 289 | exception. `window.open` returns `null`. |
| 290 | - The URL the client gets is normalised: scheme and host lowercase (A–Z only), |
| 291 | characters outside ASCII after the host percent-encoded as UTF-8. The host |
| 292 | is ASCII (an IDN in its `xn--` form); ASCII outside RFC 3986's unreserved and |
| 293 | reserved characters and `%` (space, `"<>\^\`{|}`, controls) and a `%` that does |
| 294 | not start `%XX` are a `TypeError`. The 256-character limit applies to the |
| 295 | normalised URL. |
| 296 | - The widget is not told whether the user confirmed. |
| 297 |
| 298 | ### 2.6 Haptics |
| 299 |
| 300 | - `impactOccurred`, `notificationOccurred`, `selectionChanged` as in Mini |
| 301 | Apps' `HapticFeedback`. An unknown style or type throws `TypeError`. |
| 302 | - Delivered only while the widget is visible. Rate limit per widget: a bucket |
| 303 | of 5 calls refilled at 10 per second. |
| 304 | - **A touch** (since v0.2.2): while a finger (or a mouse button) is down on the |
| 305 | widget, and for 5 s after it is lifted, haptics pass under the rate limit. |
| 306 | Outside a touch the first call opens a **series**: the calls of its first |
| 307 | second pass, later ones do not. A new series may start after a touch (one |
| 308 | series at any time later, until the next touch: a bot's answer that arrives |
| 309 | seconds after the tap, the end of an animation), or, with no touch since the |
| 310 | last series, 10 s after the last one began. So a timer cannot buzz the phone: |
| 311 | it gets one second of haptics, then nothing for nine. The touch is the |
| 312 | client's trusted input (the renderer's press and its release), never an event |
| 313 | the widget dispatches; a press whose end never arrives counts as lifted 30 s |
| 314 | after it began. |
| 315 | - Calls over the limit, outside a touch after the series, or from a hidden |
| 316 | widget are dropped without an exception and reported once per second as |
| 317 | `haptic-limit`. The numbers are the policy's named constants |
| 318 | (`HAPTIC_TOUCH_WINDOW_MS`, `HAPTIC_SERIES_MS`, `HAPTIC_SERIES_GAP_MS`, |
| 319 | `HAPTIC_PRESS_MAX_MS`). |
| 320 | - Desktop and web clients accept the calls and play nothing. |
| 321 |
| 322 | ### 2.7 Lifecycle |
| 323 |
| 324 | - `document.hidden`, `document.visibilityState` and `visibilitychange`: a widget scrolled off screen, in a background tab or app gets |
| 325 | `hidden`; while hidden it gets no animation frames and its timers fire at |
| 326 | most once per second. `isActive` and the `activated` / `deactivated` events |
| 327 | mirror the same state (fired after `visibilitychange`). |
| 328 | - `ready()` tells the host the first state is drawn. It is optional: |
| 329 | the host also notices the first content on its own. |
| 330 | - A widget can be destroyed and recreated at any time (scrolled far away, |
| 331 | memory pressure, app restart). Only Web Storage survives (§2.8). |
| 332 | - When the runtime is killed (CPU, memory, a crash), the last frame stays |
| 333 | frozen with a "Widget stopped" badge. |
| 334 |
| 335 | ### 2.8 Storage (D17) |
| 336 |
| 337 | Why local storage, and why per message: the state belongs to the message |
| 338 | (a client already keeps a record per message, the cached bubble height); the |
| 339 | bot cannot hold state for the widget because v1 has no messages or callbacks |
| 340 | to the bot (D8); and the server checks only the payload's size (D15), so any |
| 341 | cloud synchronisation would be new server work. (Since 2026-10-25 a widget also |
| 342 | has a state that only the bot writes, the chat state and the shared state, and |
| 343 | can ask the bot to change it, §2.13–§2.14. Web Storage stays what the widget |
| 344 | keeps for itself on this device.) Local Web Storage keyed by |
| 345 | the message is what fits all three; a cloud or per-bot `DeviceStorage` is |
| 346 | out of v1 (§6). |
| 347 |
| 348 | - `localStorage` is stored by the client for this message on this device, |
| 349 | under (account, chat, message id), where the chat is the one the message is |
| 350 | in: the bot's private chat or the group for the message it sent; a forwarded |
| 351 | copy (allowed into any chat) is another message in another chat, another key, |
| 352 | and starts empty. (D17 first said (account, bot, `message_id`); message ids |
| 353 | are unique only within a chat, in supergroups too, so the chat is the key.) It |
| 354 | survives the widget's |
| 355 | destruction and app restarts, and is deleted with the message, the chat |
| 356 | (or its history), the account and on "Clear cache". It is never sent to the |
| 357 | bot or the server. |
| 358 | - `sessionStorage` has the same key and lives in the client's memory until the |
| 359 | app restarts. |
| 360 | - Quota: 4 KB per area and message (4096 bytes of keys and values counted in |
| 361 | UTF-8; 16 KB until the strict limits, `docs/decisions.md` "Strict limits from the start"). `setItem` that would exceed it throws a `DOMException` named |
| 362 | `QuotaExceededError` (the shim provides `DOMException`) and stores nothing. |
| 363 | Keys and values are converted to strings, as in browsers. |
| 364 | - The data is in the widget at start (synchronous reads from the first line of |
| 365 | script). Writes are local at once; at the end of the task in which an area |
| 366 | changed, the shim commits that area to the glue (§3.2), which hands it to |
| 367 | the client. |
| 368 | - No `storage` event: a message is shown in one place at a time; if it ever is |
| 369 | in two, the last commit wins. |
| 370 | - The code of a sent widget, its HTML, never changes: no edit replaces it (only |
| 371 | the caption can be edited, as for any media). The bot changes only the |
| 372 | widget's state (§2.13), and the changes reach the running widget as |
| 373 | `chatDataChanged` / `publicDataChanged`; nothing restarts. A bot that wants a |
| 374 | new widget sends a new message. |
| 375 |
| 376 | ### 2.9 Locale |
| 377 |
| 378 | `navigator.language` is the client's UI language as a BCP 47 tag (`ru`, |
| 379 | `en-US`, `pt-BR`), `navigator.languages` is `[language]`, and the `Intl` |
| 380 | default locale is the same (a locale argument the widget passes still wins). A |
| 381 | missing or malformed locale is `en-US` (before v1: always `en-US`). |
| 382 |
| 383 | ### 2.10 Removed and inert |
| 384 |
| 385 | | API | v1 behaviour | |
| 386 | |---|---| |
| 387 | | `TelegramWidget.sendMessage` | removed; no message is ever sent on the user's behalf | |
| 388 | | `alert`, `confirm`, `prompt` | no dialog, nothing sent to the host; `confirm` returns `false`, `prompt` `null` (before v1 they reached the host as a bridge call `alert`) | |
| 389 | | `navigator.clipboard.writeText`, `readText`, `write`, `read`, `navigator.share` | reject with a `DOMException` named `NotAllowedError`, nothing sent to the host (before v1 `writeText` reached the host as `clipboard`); `navigator.canShare()` is `false` | |
| 390 | | `fetch`, `XMLHttpRequest`, `WebSocket`, … | throw `NetworkDisabledError` (invariant 5) | |
| 391 | | keyboard | no key events, no keyboard focus (D4; the renderers and glue drop key events in profile v1) | |
| 392 | | double tap | always the widget's, on every element: both clicks, then the renderer's own `dblclick` (since v0.1.2; before, never delivered) | |
| 393 | | long press | the bubble's over `touch-action: auto` and `pan-*` (§5.5): the touch the client takes ends for the widget with `pointercancel` and no `click`; over `touch-action: none` the widget's, with the renderer's own `contextmenu` (since v0.1.2), unless the press first leaves the slop vertically: then it is the list's scroll (since v0.1.3). The engine's own `dblclick` and `contextmenu` never reach the widget | |
| 394 | | vertical drag | always the chat's (the list scrolls), on every element and whatever `touch-action` says; the widget gets `pointercancel` (since v0.1.3; before, `pan-x` and `none` claimed it) | |
| 395 |
| 396 | ### 2.11 Errors and limits |
| 397 |
| 398 | | call | invalid arguments | outside the rules | other limits | |
| 399 | |---|---|---|---| |
| 400 | | `openLink`, `openTelegramLink` | `TypeError` | dropped, `activation-blocked` (no press, hidden, press used) | 256 characters; one call per press | |
| 401 | | haptics | `TypeError` | dropped, `haptic-limit` (hidden, over the bucket, outside a touch after the series) | bucket 5, 10 per second; outside a touch (a press and 5 s after it) one 1 s series, the next after a touch or 10 s later | |
| 402 | | `localStorage`, `sessionStorage` | — | `QuotaExceededError` | 4 KB per area | |
| 403 | | `isProfileAtLeast` | `false` | — | — | |
| 404 | | `onEvent`, `offEvent` | ignored (unknown type or non-function) | — | 16 handlers per type; further ones are ignored | |
| 405 | | `ready` | — | — | — | |
| 406 | | `setResizeAnchor` | `TypeError` (anything but exactly `'top'` or `'bottom'`) | — | only a change reaches the host | |
| 407 | | `watchPublicData`, `unwatchPublicData` | — | dropped, `preview-blocked` (a preview) | only a change reaches the host | |
| 408 | | `request` | `TypeError` (not a string of 1–64 bytes in UTF-8, or a lone surrogate) | the promise rejects: `NOT_ALLOWED` (no `can_query` on this message, no tap where background requests are off, a background call while hidden, a client without requests), `BUSY` (one in flight), `RATE_LIMITED` (background sooner than 5 s after the last one while visible, or the server's flood limit) | one in flight; one per tap; background: one when the widget appears on screen, then one per 5 s | |
| 409 | | `copyText` | `TypeError` (not a string of 1–256 UTF-16 code units, or a lone surrogate) | dropped, `activation-blocked` | one per tap | |
| 410 |
| 411 | Diagnostics go to the host's diagnostics (`onDiag` / `WidgetDiagnostics`), |
| 412 | never to the widget. The widget's state and requests add `request-blocked` (a refused |
| 413 | request, at most 20 per widget), `answer-rejected` (an answer whose `result` |
| 414 | broke the limits) and `data-rejected` (a chat state or shared state the client |
| 415 | passed that is over 1024 bytes or not text). |
| 416 |
| 417 | A widget is killed, and its last frame kept (§5.7), for one of these reasons the |
| 418 | host sees in `died` / `onDead`: `CPU limit exceeded` (more than `cpuLimitMs`, |
| 419 | 500 ms, of continuous JS in one task), `Layout query limit exceeded` (more than 128 synchronous layout |
| 420 | queries in one task, or their time past 1000 ms; the queries also count |
| 421 | toward the host's main-thread window), `Memory limit exceeded (8 MB)`, and, under |
| 422 | `strict`, a counted cap of the validator (`Text limit exceeded`, `Attribute limit |
| 423 | exceeded`, `Node limit exceeded`, `Ops limit exceeded`, `Canvas limit exceeded`, `CSS limit exceeded`; the |
| 424 | validator's `limit` diagnostic carries the same reason; `docs/decisions.md`, "Strict |
| 425 | limits from the start") or the renderer's paint limit (v0.6.0: `Paint limit exceeded: N |
| 426 | boxes with shadows, filters or transparency (max 16)` or `Paint limit exceeded: N boxes |
| 427 | with backdrop-filter (max 2)`, more than 16 heavy boxes at once or more than 2 of them |
| 428 | with backdrop-filter; the diagnostic `paint-limit` / `backdrop-limit` carries the same |
| 429 | reason; `docs/decisions.md`, "Heavy boxes"). The paint limit's last frame is drawn |
| 430 | without the effects (no blurred shadow, filter, backdrop-filter or transparency, |
| 431 | animations stopped). |
| 432 |
| 433 | ### 2.12 Resize anchor (v0.1.3) |
| 434 |
| 435 | `TelegramWidget.setResizeAnchor(edge)` says which edge of the bubble stays put |
| 436 | on screen when the widget's height changes: |
| 437 |
| 438 | - `'top'` (the default, also before any call): the bubble grows and shrinks |
| 439 | downward; the content below it moves. An FAQ whose answers expand, "show |
| 440 | more" results, an order summary that opens. |
| 441 | - `'bottom'`: the bubble grows and shrinks upward; its bottom stays and the |
| 442 | content above it moves. A chat log or a support thread where new messages |
| 443 | appear at the bottom and the older ones move up. |
| 444 |
| 445 | It may be called at any time and applies to the height changes that follow, |
| 446 | until it is called again; call it before the change it should anchor, at the |
| 447 | start of the script for a widget that always grows one way (the anchor of a |
| 448 | re-created widget is what its new run sets). It needs no tap and works while |
| 449 | hidden. Anything but exactly `'top'` or `'bottom'` throws `TypeError`. A client |
| 450 | whose framework predates v0.1.3 has no such method: check |
| 451 | `typeof TelegramWidget.setResizeAnchor === 'function'` (the profile number does |
| 452 | not tell: it stays 1). The anchor is a request: a client keeps it for a bubble |
| 453 | on screen; for a bubble off screen it keeps what is on screen in place |
| 454 | (§5.6). The widget is not told which edge moved. |
| 455 |
| 456 | ### 2.13 The widget's state and where it is |
| 457 |
| 458 | A widget is fixed code plus changeable state. The code, its HTML, is set when |
| 459 | the bot sends the widget and never changes (§2.8). The state changes, and only |
| 460 | the bot writes it. Besides what it keeps for itself in Web Storage (§2.8), a |
| 461 | widget gets: |
| 462 |
| 463 | | member | what it is | in a forwarded copy | |
| 464 | |---|---|---| |
| 465 | | `chatData` | the **chat state**: tied to this message and seen only in its chat; in the private chat it is the user's, in a group every member sees the same one; a forward never carries it. A text of up to 1024 bytes (UTF-8), or `null`. For example a game in progress, whose turn it is | `null`, always | |
| 466 | | `publicData` | the **shared state**: seen wherever the widget is shown. A static widget keeps it in the message, and a forward gets a copy as of the forward, which never changes again; a shared widget (the server's object by `widget_id`, like a poll) has one shared state for all its messages and forwards, which changes for all of them at once. A text of up to 1024 bytes (UTF-8), or `null`. For example poll results, a price | the copy taken at the forward, or the shared widget's shared state | |
| 467 | | `isForward` | the message is a forwarded copy | `true` | |
| 468 | | `chatType` | `'private'`, `'group'`, `'supergroup'` or `'channel'`: the kind of chat the message is in (Bot API `Chat.type`; `'channel'` is not used yet); `null` when the client does not say | `null`, always: a copy is told nothing about the chat it is in (below) | |
| 469 | | `viewer` | the account looking at the widget, shaped like Mini Apps' `WebAppUser`: `id` (the Telegram user id, the same the bot gets with a request), `first_name`, `last_name`, `username` and `is_premium` (only when true); a field the client does not have is absent (frozen); **only where the widget may send requests** (the message's `can_query`), else `null`, in an original too | the viewer if the copy may send requests (below), else `null` | |
| 470 |
| 471 | - Only the bot writes the state: when it sends the widget and by separate |
| 472 | edits. The widget reads it and cannot change it itself; it can only ask the |
| 473 | bot (`request`, §2.14). A request's answer does not change the state. |
| 474 | - When the state changes, the widget gets `chatDataChanged` for the chat state |
| 475 | and `publicDataChanged` for the shared state (`onEvent`), with the new values |
| 476 | already in place: it redraws itself, nothing restarts and the page keeps its |
| 477 | DOM and variables. One change that touches both fires both, |
| 478 | `chatDataChanged` first, in the same task; a change that leaves a value as it |
| 479 | was fires nothing for it. `chatDataChanged` never fires in a copy. |
| 480 | - The empty string is how the bot clears the chat state or the shared state: |
| 481 | the widget sees `null`, never `''`. |
| 482 | - **Live shared state: `watchPublicData()`.** A shared widget (the bot sent it |
| 483 | as one: a ticker, the counts of a poll others vote in) calls |
| 484 | `TelegramWidget.watchPublicData()` to follow its shared state live: while it |
| 485 | is on screen the client polls the shared state at the server's period |
| 486 | (5–3600 s, 30 s by default) and `publicDataChanged` brings each change. |
| 487 | `unwatchPublicData()` stops it. Synchronous, no tap needed, calling it again |
| 488 | changes nothing. A widget that does not watch gets its shared state with the |
| 489 | message, and the bot's edits of this message, but nothing polled: most |
| 490 | widgets need nothing more. In a static widget, and in a preview, it does |
| 491 | nothing. |
| 492 | - Where a widget lives: the private chat with the bot that sent it (it may |
| 493 | also ask in the background, §2.14); a group or supergroup the bot is a member |
| 494 | of (`chatType` `'group'` / `'supergroup'`: requests on a tap only, and the |
| 495 | chat state is one for everyone in the group: no secrets there, draw it per |
| 496 | `viewer.id`); any chat through the bot's inline mode (a message "via the |
| 497 | bot": requests on a tap only); and forwards of any of these. |
| 498 | - `viewer` is what the bot gets as `from` with a tap: `{ id: 42, first_name: |
| 499 | 'Ann', last_name: 'Lee', username: 'ann_lee', is_premium: true }`. The names |
| 500 | are 1–64 characters (UTF-16 code units), the username 5–32 characters of |
| 501 | A–Z, a–z, 0–9 and _; the client leaves out a field that breaks its rule (and |
| 502 | reports it), never the whole viewer. |
| 503 | - **The widget knows its viewer only where it may send requests** (the |
| 504 | message's `can_query`): an original the bot sent without requests allowed, |
| 505 | a copy that may not ask and a preview have `viewer` `null`. A widget that may |
| 506 | not talk to the bot does not know who views it, so it cannot pass the id out |
| 507 | through a link either, and the rule matches the network marker (§5.11). A |
| 508 | bot that wants the user's id in its private chat puts it into the chat state |
| 509 | itself. |
| 510 | - **A copy is told nothing about the chat it is in**: `chatType` is `null` in |
| 511 | every forward, with requests or without. The bot must not learn where its |
| 512 | widget was forwarded, and whatever the widget knows it could put into a |
| 513 | request's `data`. |
| 514 | - A forward has no chat state. It may send requests (on a tap only) when the bot |
| 515 | sent the widget with forwards allowed to ask (the server's |
| 516 | `fwd_allow_queries`): then it also knows the viewer, whom the bot learns with |
| 517 | a tap anyway (who pressed); the bot gets no message, chat or chat type with a |
| 518 | copy's request, only who pressed, `data` and the shared object's id. A forward of a |
| 519 | widget sent without it sends nothing and has no `viewer` either. To bring its reader to the bot, link to it with |
| 520 | `openTelegramLink('https://t.me/<bot>?start=…')`: the bot learns who it is only |
| 521 | when they press Start. A forward has its own Web Storage (§2.8). |
| 522 | - One state for all, drawn per viewer: chess for two is one widget and one |
| 523 | chat state, drawn from `viewer.id`. |
| 524 |
| 525 | ### 2.14 Requests to the bot |
| 526 |
| 527 | `TelegramWidget.request(data)` is how a widget asks the bot, the only writer of |
| 528 | its state; it is a callback button inside the widget: the bot gets what an |
| 529 | inline button's press gives it (who pressed, the message with its chat state and |
| 530 | shared state, `chat_instance`, the chat type; from a copy only who pressed and |
| 531 | the shared object's id) plus `data`, and answers with a `result` for this |
| 532 | widget. Only a widget the bot sent with requests allowed (the server's |
| 533 | `allow_queries`) may ask at all; the client marks such a widget as one whose tap |
| 534 | may send data to the bot (§5.11). |
| 535 |
| 536 | ```js |
| 537 | TelegramWidget.request('vote:2').then( |
| 538 | (answer) => show(answer.result), // { result: string | null }, frozen |
| 539 | (error) => showError(error.code), // error.name === 'WidgetRequestError' |
| 540 | ); |
| 541 | ``` |
| 542 |
| 543 | - `data`: a string of 1–64 bytes in UTF-8 (as `callback_data`); anything else |
| 544 | throws `TypeError` at once. |
| 545 | - The promise resolves with `{ result }`: the bot's answer for this widget, |
| 546 | text of at most 1024 bytes (empty allowed), or `null` when the bot answered |
| 547 | with nothing. Only the widget that asked gets it. |
| 548 | - **The answer does not change the state.** A bot that changes the chat state |
| 549 | or the shared state does it with separate calls, and the change reaches the |
| 550 | widget the usual way (`chatDataChanged` / `publicDataChanged`), before or |
| 551 | after the answer. A |
| 552 | widget that needs the new state at once gets it from the bot in `result` |
| 553 | (for example the user's own vote, or the new score as JSON). |
| 554 | - **Where a widget may ask** is the server's decision, per message, and the |
| 555 | client passes it on; the widget does not derive it: |
| 556 |
| 557 | | message (of a widget the bot sent with `allow_queries`) | on a tap | in the background | |
| 558 | |---|:-:|:-:| |
| 559 | | the original in the private chat with the bot | ✓ | ✓ | |
| 560 | | an original in a group, or sent via the bot (inline) | ✓ | – | |
| 561 | | a forward of a widget the bot sent with `fwd_allow_queries` | ✓ | – | |
| 562 | | a forward of any other widget | – | – | |
| 563 |
| 564 | A widget sent without `allow_queries` asks nowhere, its originals included. |
| 565 |
| 566 | - **A tap per request.** A request on a tap runs in that tap's handler, on the |
| 567 | visible widget, like `openLink`: one tap unlocks one call, shared with |
| 568 | `openLink`, `openTelegramLink` and `copyText` (a handler that calls `request` |
| 569 | and then `copyText` copies nothing). |
| 570 | - **Background requests**, without a tap, only where the table allows them; |
| 571 | they go out only while the widget is visible: one at once when the widget |
| 572 | appears on screen (scrolled into view, the app back in front, at creation on |
| 573 | screen), then at most one per 5 s (from the start of the last one) while it |
| 574 | stays visible. One made while the widget is off screen waits in the client |
| 575 | and goes out when the widget appears, as that appearance's one; its promise |
| 576 | stays pending meanwhile (a widget that never appears never asks). Clients |
| 577 | create a bubble before it is on screen, so a request in the script's first |
| 578 | lines is the way to fetch fresh state: it goes out as soon as the widget is |
| 579 | seen. The server and the bot cannot tell a background request from a tap (as |
| 580 | for callback buttons); the limit is the client's, the framework's. |
| 581 | - **One in flight.** A second call while a request waits for its answer, or |
| 582 | waits off screen to go out, rejects with `BUSY`. Only the client's gate |
| 583 | decides it: a request it refused never makes the next one `BUSY`. |
| 584 | - The promise rejects with an `Error` whose `name` is `WidgetRequestError` and |
| 585 | whose `code` says why: |
| 586 |
| 587 | | `code` | when | |
| 588 | |---|---| |
| 589 | | `NOT_ALLOWED` | this message may not ask (a widget sent without `allow_queries`, or a forward of one sent without `fwd_allow_queries`); no tap where background requests are off; a client that does not deliver requests | |
| 590 | | `BUSY` | another request is in flight, or waits off screen to go out | |
| 591 | | `RATE_LIMITED` | a background call sooner than 5 s after the last one while the widget stayed visible, or the server's flood limit | |
| 592 | | `TIMEOUT` | the bot did not answer in time (15 s: it is down, not subscribed to the updates, or slow) | |
| 593 | | `FAILED` | anything else: the bot was blocked or deleted, the message is gone, the network | |
| 594 | | `INVALID_ANSWER` | the bot's `result` broke the limits (it never reaches the widget) | |
| 595 |
| 596 | - What the bot learns: everything the widget's code knows can go into the 64 |
| 597 | bytes (its language, theme, text size, bubble width, time zone, what it kept |
| 598 | in Web Storage); in the private chat background requests also tell the bot |
| 599 | when the user has the chat open. Bot-side handling, the server's checks and |
| 600 | the update the bot gets (`widget_query`, `answerWidgetQuery`) are the server's |
| 601 | contract (`docs/tgw-format.md`, "The widget's state and requests"). |
| 602 |
| 603 | ### 2.15 `copyText` |
| 604 |
| 605 | `TelegramWidget.copyText(text)` copies a text to the clipboard, as an inline |
| 606 | button's `copy_text` does: a string of 1–256 UTF-16 code units (anything else |
| 607 | throws `TypeError`), on a tap only (one call per tap, shared as in §2.14; |
| 608 | outside a tap it is dropped with `activation-blocked`). The client shows a |
| 609 | toast that says what it copied, so a widget cannot show one text and copy |
| 610 | another unnoticed. The widget is not told that it was copied. A copy may copy. |
| 611 | `navigator.clipboard` stays a stub (§2.10). |
| 612 |
| 613 | ### 2.16 Previews |
| 614 |
| 615 | A bot's inline result can be a widget; in the list of results, before the user |
| 616 | sends one, the client shows the widget as a **preview**: `isPreview` is `true`. |
| 617 | A preview has its state (`chatData`, `publicData`) and runs as usual |
| 618 | (timers, animations, the theme, the visibility and CPU rules of any bubble), but |
| 619 | it is not a message yet and is not the user's: |
| 620 |
| 621 | - it gets no input: a tap on it selects the result, and the widget gets no |
| 622 | pointer events, clicks or gestures; |
| 623 | - it asks nothing: `request` rejects with `NOT_ALLOWED`; `openLink`, |
| 624 | `openTelegramLink`, `copyText` and haptics do nothing (`ready` and |
| 625 | `setResizeAnchor` work); |
| 626 | - it knows nothing about the user: `chatType` and `viewer` are `null`, |
| 627 | `isForward` is `false`; |
| 628 | - its Web Storage starts empty and lives only for that run: nothing is kept. |
| 629 |
| 630 | Draw the same first state a sent widget would draw: the preview is what the |
| 631 | user is about to send. |
| 632 |
| 633 | ### 2.17 The client's time over the widget: the content safe area |
| 634 |
| 635 | A message with a widget and **no caption below it** (no caption, or a caption |
| 636 | shown above the media, `invert_media`) gets its time and status (the ticks, |
| 637 | "edited", a channel's views) drawn by the client **over the widget's bottom |
| 638 | corner**, on a backing, as over a photo: the right corner in a left-to-right |
| 639 | interface, the left one in a right-to-left one (a physical side: an English widget |
| 640 | in an Arabic client has the time on its left). With a caption below the widget the |
| 641 | time is in the caption's line and nothing is drawn over the widget: everything is |
| 642 | 0. A caption above the widget is as no caption: the time is over the corner |
| 643 | again, as on a photo whose caption is moved up. Taps on the time are the |
| 644 | client's (a view over the widget), never the widget's: put nothing a user taps |
| 645 | under it. The floating date pill of a chat that scrolls past the widget has no |
| 646 | contract: it is drawn over the widget like over a photo and moves every frame. |
| 647 |
| 648 | The widget gets the band and the corner the way a web page gets the screen's notch; |
| 649 | the client gives the numbers: |
| 650 |
| 651 | ```css |
| 652 | /* the band the time is drawn in, at the bottom: keep it clear */ |
| 653 | .footer { padding-bottom: max(8px, env(safe-area-inset-bottom)); } |
| 654 | /* only the corner of the band is covered: content may run into the band on the other side */ |
| 655 | .footer { padding-right: max(12px, var(--tg-content-safe-area-corner-right)); |
| 656 | padding-left: max(12px, var(--tg-content-safe-area-corner-left)); } |
| 657 | ``` |
| 658 |
| 659 | - `env(safe-area-inset-top|right|bottom|left[, fallback])` is in profile 1 (a |
| 660 | clarification of 2026-10-29, before widgets launched; `P1-safe-area` in |
| 661 | `profile.json`). The validator rewrites it, in stylesheets, `style` attributes |
| 662 | and CSSOM writes alike, to `var(--tg-content-safe-area-inset-…[, fallback])`: the |
| 663 | engine's own `env()` belongs to the document (on the web, to the chat page) and |
| 664 | comes from the view's system insets, so it never reaches the renderer. The |
| 665 | variables are always set (0 with a caption below), so a fallback applies only where a |
| 666 | client sets nothing. Any other `env()` name (`keyboard-inset-*`, `titlebar-area-*`) |
| 667 | resolves to its fallback, or drops the declaration without one; `env()` inside |
| 668 | `url()` and the other URL-taking functions is rejected like `var()`. `CSS.supports` |
| 669 | and `@supports` answer `true` for the safe-area insets only. |
| 670 | - The root variables, set by the renderer like the theme's (inline and |
| 671 | `!important`, names from a fixed list, values checked): `--tg-content-safe-area-inset-top`, |
| 672 | `-right`, `-bottom`, `-left` (bottom = the height of the time's band, the rest |
| 673 | 0; the names are Mini Apps', so `var(--tg-content-safe-area-inset-bottom)` from |
| 674 | Mini Apps code works too) and `--tg-content-safe-area-corner-left`, `-right`: the |
| 675 | width the client's corner takes in the band, on its physical side (`right` in a |
| 676 | left-to-right interface, `left` in a right-to-left one, the other 0). An inset is |
| 677 | 0–64 px and a corner 0–200 px; a client value outside that is 0. |
| 678 | - The renderer's UA layer (§2.4) adds the band to the body's bottom padding |
| 679 | (`:where(body){padding-bottom:var(--tg-content-safe-area-inset-bottom,0px)}`), so |
| 680 | an unstyled widget (and one that sets only `body { margin: 0 }`) stays clear of |
| 681 | the time and is that much taller. A widget that sets the body's padding, or resets |
| 682 | every padding (`* { padding: 0 }`), handles the band itself. The converse: a widget that |
| 683 | pads for the band itself must set the body's padding too (`body { margin: 0; padding: 0 }`), |
| 684 | or the default bottom padding comes on top of its own (`corpus/safe-area`, README). |
| 685 | - `TelegramWidget.contentSafeAreaInset`, `{ top, right, bottom, left, cornerLeft, |
| 686 | cornerRight }` in CSS px, has the same numbers for script (a canvas widget lays |
| 687 | its own controls out with them; `getComputedStyle` on the variables would be a |
| 688 | layout query). A change (a caption added, removed or moved above or below the widget |
| 689 | by an edit, an "edited" mark that widens the time) gives a fresh frozen object and fires |
| 690 | `contentSafeAreaChanged`, in one task, with the variables already set. It never |
| 691 | changes per frame. |
| 692 |
| 693 | ### 2.18 The wallet |
| 694 |
| 695 | A widget can ask the user to pay or to sign through Telegram's built-in wallet (Gram Wallet). The widget is the |
| 696 | front of a dApp and its bot is the back end, as a site and its server are in TON Connect; the formats are TON |
| 697 | Connect's, but there is no connection, no manifest, no bridge and no domain: who asks is the bot that sent the |
| 698 | message, and the client's own wallet window says so. Decided in `docs/decisions.md`, "The wallet". |
| 699 |
| 700 | ```js |
| 701 | // A tap asks the bot with the user's wallet; the bot answers with a fresh transaction; the widget passes it on. |
| 702 | TelegramWidget.request('pay:42', { wallet: true }) |
| 703 | .then((a) => TelegramWidget.wallet.sendTransaction(JSON.parse(a.result), 'paid:42')) |
| 704 | .then((a) => show(a.result), (e) => showError(e.code)); |
| 705 |
| 706 | TelegramWidget.wallet.signData({ type: 'text', text: 'I accept the terms of order 42' }, 'terms:42') |
| 707 | .then((a) => show(a.result)); |
| 708 | ``` |
| 709 |
| 710 | - **`TelegramWidget.wallet`** is `null` where the client has no wallet for this user (a client without it, a |
| 711 | country where the wallet is not available), where the widget may not ask the bot (no `canQuery`: §2.14's table; |
| 712 | a forward of a widget sent with `fwd_allow_queries` may) and in a preview. Check it before drawing a pay button. |
| 713 | The widget never learns the user's address from the client; the bot does (below) and may put it in `result`. |
| 714 | - **`request(data, { wallet: true })`**, on a tap only: the bot gets the wallet card of the user's profile (the |
| 715 | cloud wallet's address and balance) with the request; a user without a wallet gets one created then (a new wallet |
| 716 | is empty: the client offers to top it up when it is paid from). Refused (`NOT_ALLOWED`) without `wallet` or |
| 717 | without a tap, background requests included. `options` is an object with at most `wallet`, a boolean; anything |
| 718 | else throws `TypeError`. The wallet that pays or signs is the one on the device, and it can be another one: with |
| 719 | the wallet's backup off a device keeps its own key and its own wallet. So the bot does not put the profile's |
| 720 | address in a transaction's `from` (the wallet refuses a `from` that is not its own: `BAD_REQUEST`); it learns the |
| 721 | device's wallet with the outcome (below). |
| 722 | - **`wallet.sendTransaction(transaction, data)`**: `transaction` is TON Connect's `sendTransaction` request with |
| 723 | its own field names: `{ valid_until?, network?, from?, messages: [{ address, amount, payload?, stateInit? }] }`; |
| 724 | 1–255 messages (what Gram Wallet takes); `valid_until` in Unix seconds; `network` `'-239'` (the mainnet) or |
| 725 | `'-3'` (the testnet); a message's `address` user-friendly (48 characters, the bounce flag in it; a raw `0:…` is |
| 726 | refused, as TON Connect wallets must), `from` raw or user-friendly; `amount` nanotons as a decimal string; |
| 727 | `payload` and `stateInit` bags of cells in base64, at most 8192 characters each and 65536 for all messages |
| 728 | together. `null` fields are left out; any other field (`items`, `extra_currency`, the SDK's `validUntil`) throws |
| 729 | `TypeError`. The client shows the transaction in its own wallet window |
| 730 | (each message's amount and destination, the emulated outcome) with the bot of the message; on confirmation it |
| 731 | sends it, gives the bot the outcome (the message hash and the device's wallet that sent it: its address and |
| 732 | balance, its key and StateInit where the client has them; the bot checks the transaction on the chain) and resolves |
| 733 | with the bot's answer to it, `{ result }`, as `request` does. The widget never gets the signed message. |
| 734 | - **`wallet.signData(payload, data)`**: `payload` is TON Connect's: `{ type: 'text', text }` (at most 4096 bytes |
| 735 | of UTF-8, shown to the user), `{ type: 'binary', bytes }` or `{ type: 'cell', schema, cell }` (base64 of at most |
| 736 | 4096 characters, the TL-B schema at most 1024 bytes; the window warns that it cannot show them), optionally with |
| 737 | `network` and `from`. There is no domain: the client signs for `bot<bot_id>` of the message. The signature goes |
| 738 | to the bot with the device's wallet that signed (its address, public key and StateInit: the bot checks the signature |
| 739 | with the key and ties the key to the address by the StateInit or on the chain); the bot checks it or passes it on, |
| 740 | and resolves this with its answer. |
| 741 | - `data` (1–64 bytes, a request's) is the label the bot gets with the outcome: what the payment or the signature |
| 742 | is for. |
| 743 | - **When.** On a tap, in its handler, on the visible widget (one call per tap, shared as in §2.14), or **within |
| 744 | 10 s of the answer to a call made by a tap** (a request or a wallet call): the answer grants one wallet call |
| 745 | without a new tap, so a tap can pay for what the bot answers. Any call made on a tap or on the grant uses the |
| 746 | grant up; a refusal, a failure or a background request's answer brings none. Never in the background, never |
| 747 | from a timer. One call in flight, shared with requests (`BUSY`). |
| 748 | - The promise rejects as a request's does (§2.14), plus two codes: |
| 749 |
| 750 | | `code` | when | |
| 751 | |---|---| |
| 752 | | `REJECTED` | the user declined in the wallet window | |
| 753 | | `BAD_REQUEST` | the wallet refused the transaction or the payload (another network or sender than the user's, an expired `valid_until`, cells it cannot parse) | |
| 754 | | `NOT_ALLOWED` | no wallet, no tap and no grant, a preview | |
| 755 |
| 756 | A failure after the window (`TIMEOUT`, `FAILED`) means the bot's answer did not come: the transaction may have |
| 757 | been sent; ask the bot about the order again rather than paying twice. |
| 758 |
| 759 | ## 3. Protocol |
| 760 |
| 761 | What carries the API between the sandbox (QuickJS), the host glue and the |
| 762 | renderer. Every message from the sandbox is untrusted and is checked in all |
| 763 | five glue copies: the web worker and `WidgetHost` (TS), the Node harness, |
| 764 | Swift, Kotlin, C++ (`sandbox_engine.cpp`, `widget_host.cpp`). The checks live in |
| 765 | one policy with a shared JSON fixture, as `cpu-budget` does: |
| 766 | `packages/core/src/shared/sdk-policy.ts` and its twins `SdkPolicy.swift`, |
| 767 | `SdkPolicy.kt`, `sdk_policy.cpp`, all checked against |
| 768 | `packages/core/tests/fixtures/sdk-policy.json`. |
| 769 |
| 770 | ### 3.1 Config (`SandboxConfig`, host → sandbox at start) |
| 771 |
| 772 | | field | type | set by | status | |
| 773 | |---|---|---|---| |
| 774 | | `theme` | `'light' \| 'dark'` | client (`colorScheme`) | | |
| 775 | | `themeParams` | `Record<ThemeKey, '#rrggbb'>` | client | | |
| 776 | | `locale` | BCP 47 string, at most 35 characters | client | | |
| 777 | | `contentSafeArea` | `{ top, right, bottom, left, cornerLeft, cornerRight }`, CSS px | client (§2.17, §5.12; all 0 when absent); the shim checks it: an inset 0–64, a corner 0–200, two decimals, else 0 | | |
| 778 | | `profile` | integer | glue (`WidgetSandboxVersion` / `twidget::version`, generated from `VERSION.json`'s `profile`) | the shim reports `profile-mismatch` when it differs from the bundle's; the native glue does not start a bundle stamped with another profile (`bundle-mismatch`, `docs/integration.md` "Pinning a release") | |
| 779 | | `storage` | `{ local: Record<string, string>, session: Record<string, string> }` | client (the preload), glue checks the quota | | |
| 780 | | `policy` | `'strict'` | glue default | | |
| 781 | | `chatData`, `publicData` | `string \| null` | client (`data`: the chat state and the shared state), glue checks: text of 1–1024 bytes without a NUL, else `null` (`data-rejected`); a copy's `chatData` is dropped | | |
| 782 | | `isCopy` | `boolean` | client (`context.isCopy`, the server's `is_copy`); the widget's `isForward` | | |
| 783 | | `canQuery` | `boolean` | client (`context.canQuery`, the server's `can_query`); the shim refuses a request at once without it; `false` in a preview | | |
| 784 | | `isPreview` | `boolean` | client (`context.preview`): an inline result before it is sent (§2.16) | | |
| 785 | | `chatType` | one of the four or `null` | client (`context`), `null` in every copy and in a preview | | |
| 786 | | `viewer` | `{ id, first_name?, last_name?, username?, is_premium? } \| null` | client (`context`), checked: an id of 1 to 2^53 − 1 (else `null`), names of 1–64 UTF-16 code units, a username of 5–32 characters of A–Z, a–z, 0–9 and _, `is_premium` only when true; a field that breaks its rule is left out (`data-rejected`); `null` without `canQuery` (an original sent without requests allowed, a copy that may not ask, a preview) | | |
| 787 |
| 788 | The client's values are trusted but still checked: unknown theme keys and |
| 789 | values that are not `#rrggbb` are dropped, a storage preload over the quota is |
| 790 | dropped whole with the diagnostic `storage-rejected` (the widget starts empty). |
| 791 |
| 792 | ### 3.2 Sandbox → host |
| 793 |
| 794 | `__host('bridge', JSON.stringify([method, args]))`, one call per API call: |
| 795 |
| 796 | | method | args | glue checks | goes to the client as | |
| 797 | |---|---|---|---| |
| 798 | | `ready` | `[]` | — | `ready` | |
| 799 | | `openLink` | `[url]` | URL rules of §2.5; privileged: needs the task's gesture, consumes it | `openLink(url)` | |
| 800 | | `openTelegramLink` | `[url]` | URL rules of §2.5; privileged | `openTelegramLink(url)` | |
| 801 | | `haptic` | `['impact', style]`, `['notification', type]`, `['selection']` | enum values; visible; rate limit | `haptic(...)` | |
| 802 | | `setResizeAnchor` | `[edge]` | exactly `'top'` or `'bottom'` (v0.1.3); no gesture, no visibility gate | not an action: the host keeps the latest value and reports it with the height (§4) | |
| 803 | | `watchPublicData` | `[on]` | exactly one boolean; no gesture, no visibility gate; refused in a preview | not an action: the host keeps the latest value and reports a change (`onWatchPublicData`, `watchesPublicData`, §4) | |
| 804 | | `request` | `[id, data]` or `[id, data, { wallet }]` | `id` an integer 1–2147483647 (the shim numbers its requests), `data` 1–64 bytes, the options an object with at most `wallet`, a boolean; then the request gate (below) | `onRequest({ data, wallet? })`; the answer goes back as a `bridge` event (§3.3) | |
| 805 | | `wallet` | `[id, 'sendTransaction', transaction, data]` or `[id, 'signData', payload, data]` | the transaction or the payload as §2.18 has it (`checkWalletTransaction`, `checkSignDataPayload`), `data` 1–64 bytes; then the request gate's `decideWallet` (below) | `onWallet(call)`; the answer goes back as a `bridge` event, as a request's | |
| 806 | | `copyText` | `[text]` | 1–256 UTF-16 code units; privileged: needs the task's gesture, consumes it | `onCopyText(text)` | |
| 807 |
| 808 | The glue checks in this order: the method and its arguments |
| 809 | (`checkBridgeCall`; any other method or a malformed call is dropped with |
| 810 | `bridge-rejected`, at most 20 reported); for `request` and `wallet` the request gate (below); |
| 811 | user activation for the two link methods and `copyText` (`activation-blocked`); |
| 812 | for `haptic` the gate of §2.6 (`haptic-limit`). |
| 813 |
| 814 | In a preview (§2.16) the host takes no input from the renderer (no events, no |
| 815 | gesture claims), lets only `ready` and `setResizeAnchor` through |
| 816 | (`allowedInPreview`; the rest are dropped with `preview-blocked`, a request is |
| 817 | answered `NOT_ALLOWED`) and drops storage commits. |
| 818 |
| 819 | The request gate (`RequestGate` in the policy), from the server's flags only, in |
| 820 | this order: no `canQuery` → `disabled`; a request in flight → `busy`; the |
| 821 | task's gesture is unconsumed and the widget visible → `foreground` (the gesture |
| 822 | is consumed; under `compat` every call counts as pressed); no |
| 823 | `backgroundQuery` → `no-activation`; hidden → `hidden`; less than 5 s since the |
| 824 | last background request → `rate-limited`; else `background`. The host calls the gate's `show` |
| 825 | when the widget becomes visible: the next background request may go out at |
| 826 | once. A refusal goes back to the widget as an `answer` event with the error code |
| 827 | (`requestRefusal`) and is reported as `request-blocked` (at most 20). An |
| 828 | accepted request goes to the client with its `data` only (whether it came from |
| 829 | a tap stays in the framework); a client without `onRequest` at that moment |
| 830 | refuses it (`NOT_ALLOWED`, reason `unsupported`). The answer is checked |
| 831 | (`checkRequestAnswer`: `result` text of at most 1024 bytes without a NUL, else |
| 832 | `INVALID_ANSWER` and `answer-rejected`) and frees the gate; so does a failure |
| 833 | (`TIMEOUT`, `RATE_LIMITED`, `FAILED`). |
| 834 |
| 835 | The wallet (§2.18) in the same gate: a request with `{ wallet: true }` without the context's `wallet` → |
| 836 | `no-wallet`; it goes out only as `foreground` (no background, never held). A wallet call (`decideWallet`): no |
| 837 | `canQuery` → `disabled`; no `wallet` → `no-wallet`; a call in flight → `busy`; a press on the visible widget → |
| 838 | `foreground`; the visible widget within 10 s of the grant → `granted`; else `no-activation`. The grant: an answer |
| 839 | with no error to a call that went out as `foreground` or `granted` (`finish(answeredAt)`); any call that goes out |
| 840 | as either uses it up. A wallet call's failure keeps the wallet's codes (`REJECTED`, `BAD_REQUEST`); a request's |
| 841 | turns them into `FAILED`. |
| 842 | A call that passes goes to the client as a `WidgetAction` with the normalised |
| 843 | URL (and, deprecated, to `onBridge` with the raw method and arguments), except |
| 844 | `setResizeAnchor` and `watchPublicData`, which only set a value the host keeps: |
| 845 | the shim sends them only when the value changes, and the host keeps one value, |
| 846 | so a widget that calls them in a loop costs the client nothing. The |
| 847 | method names `sendMessage`, `alert` and `clipboard` are gone from the wire. |
| 848 |
| 849 | Gesture tagging: on native hosts the engine runs a trusted event's task |
| 850 | with that press's gesture number and lets the first privileged call of the task |
| 851 | consume it. On the web the worker tags a `bridge` message with the gesture of |
| 852 | the task (`{type:'bridge', method, args, gesture}`) and the main-thread host |
| 853 | accepts each issued gesture once, within 5 s. |
| 854 |
| 855 | `__host('storage', JSON.stringify(commit))`, at most once per task, after the |
| 856 | task's `ops`: `commit` is `{ local?: Record<string, string>, session?: |
| 857 | Record<string, string> }`, the full content of each area that changed in the |
| 858 | task. The shim sends it once the task is over (after the MutationObserver |
| 859 | callbacks, when the glue's last `endTick` of the task returns). The glue |
| 860 | refuses an argument longer than any commit within the quota can be (2 × 12 × |
| 861 | 4096 + 64 characters) before parsing it, checks that the commit has only |
| 862 | `local` / `session`, each an object of strings within the quota, and hands |
| 863 | each area to the client (`onStorageCommit(area, values)`, `local` first); a |
| 864 | commit that fails is dropped whole with `storage-rejected` (at most 20 |
| 865 | reported) and the client keeps the previous content. Commits reach the client |
| 866 | in order. |
| 867 |
| 868 | ### 3.3 Host → sandbox |
| 869 |
| 870 | | message | payload | |
| 871 | |---|---| |
| 872 | | `theme` | `{ theme: 'light' \| 'dark', themeParams }` (before v1: the scheme only) | |
| 873 | | `safeArea` | `{ top, right, bottom, left, cornerLeft, cornerRight }` (§2.17): the shim checks it, and on a change sets a fresh `contentSafeAreaInset`, drops its cached layout answers and fires `contentSafeAreaChanged`, in one task. Not deferred under the CPU quota (it comes from the client, never from the widget, and only with the bubble's layout) | |
| 874 | | `visibility` | `{ visible }` | |
| 875 | | `event` | a renderer event, with `gesture: n` for a trusted press | |
| 876 | | `bridge` | `{ type: 'data', chatData, publicData }` (the full state after a change: the shim fires `chatDataChanged`, then `publicDataChanged`, for each that differs), or `{ type: 'answer', id, result }` / `{ type: 'answer', id, error, reason? }`. Deferred under the CPU quota like `theme`, in order | |
| 877 |
| 878 | The `bridge` message of the profile-0 builds (host → widget events such as a |
| 879 | bot's answer to `sendMessage`) went with `sendMessage` in v1; the name is back |
| 880 | for the widget's state and the answers to `request`. |
| 881 |
| 882 | ### 3.4 Host → renderer |
| 883 |
| 884 | | message | payload | |
| 885 | |---|---| |
| 886 | | `theme` | `{ type: 'theme', theme: { colorScheme, params, button, text } }`: the renderer core builds the variables of §2.3 and §2.4 (`themeVariables`) and sets them on the root (`:root`, or `[data-tw-root]` on the shadow-DOM renderer); the colour scheme itself still goes to the renderer element (`color-scheme`, the WebView's appearance) as before. A native renderer does the same with its own copy of `themeVariables` (`apps/renderer-litehtml/src/theme.cpp`) | |
| 887 | | `safeArea` | `{ type: 'safeArea', inset: { top, right, bottom, left, cornerLeft, cornerRight } }` (§2.17): the renderer core sets the six `--tg-content-safe-area-*` variables (`contentSafeAreaVariables`) on the root next to the theme's, 0 until the first one; hosts send it right after `theme` and on every `setContentSafeArea`. The litehtml prototype's twin is `theme::safe_area_variables`; Blitz ignores it (the fallback of a widget's `env()` then applies) | |
| 888 |
| 889 | | `policy` | `{ type: 'policy', policy, paintReports? }` (v0.6.0): the host's policy, right after `safeArea`. Under `strict` (also before it arrives, and for anything but exactly `compat`) the renderer core counts heavy boxes (`paint-policy.ts`) and reports `limit`; under `compat` it counts nothing. `paintReports` (tooling) asks for `paint { heavy, backdrop }` on every change | |
| 890 | | `arbitrate` | `{ type: 'arbitrate', bubble, touch?, rtl? }` (v0.1.2): `bubble` true, the renderer plays the bubble itself with the gesture policy (the web hosts, `bubbleGestures`): a press the bubble takes ends for the widget with `pointercancel` and the host gets `bubble`. `touch`: a mouse's primary button arbitrates as a finger (and the widget sees `pointerType: 'touch'`). `rtl`: the edge strip is on the right. Native hosts leave it off: their own recognizers take the presses | |
| 891 |
| 892 | The renderer takes only variable names from the fixed list above and values |
| 893 | that match their grammar (`#rrggbb`, CSS lengths, a font shorthand with a |
| 894 | generic family, numbers 0–1, a font size of 8–64 px, a line height of 1–3, a |
| 895 | safe-area inset of 0–64 px and a corner of 0–200 px). |
| 896 |
| 897 | ### 3.5 Renderer → host |
| 898 |
| 899 | | message | payload | |
| 900 | |---|---| |
| 901 | | `gesture` | `{ wants, x, y, hold }` (booleans) on every primary `pointerdown`: what of this press the widget claims (`claimOf` of the gesture policy): horizontal drags (`x`), from the `touch-action` the widget gave the target and its ancestors and its `preventDefault` on `pointerdown`/`touchstart`; `hold` only from `touch-action: none` (v0.1.2). Taps and double taps are always the widget's, vertical drags always the chat's: `y` and `wants` (the field before v1, equal to `y`) are always false since v0.1.3, and hosts report `y` false whatever a renderer sends | |
| 902 | | `bubble` | `{ action, gesture, x, y, edge }` with `arbitrate` `bubble` on (v0.1.2): the bubble took a press: `action` `menu` \| `swipe` \| `scroll` \| `back`; (x, y) where the pointer was, widget coordinates; `edge`: it started in the leading edge strip | |
| 903 | | `size` | the content height | |
| 904 | | `event` | `trusted: true` only for real input | |
| 905 | | `limit` | `{ code, count }` (v0.6.0), past a paint limit, once, strict only: `paint-limit` with the number of heavy boxes (more than 16) or `backdrop-limit` with the number of boxes with backdrop-filter (more than 2). The renderer has drawn that frame without the effects and takes no more ops; the host stops the widget with `Paint limit exceeded: …` (§2.11's reasons). A client's own renderer sends it through the seam's `limitExceeded(code, count)` (§4.1–§4.3) | |
| 906 |
| 907 | ## 4. Host interface per platform |
| 908 |
| 909 | The shapes the client wires up, as implemented (v0.1.0). Callbacks run on the |
| 910 | main thread (Swift, Kotlin), on the host thread (C++) or on the page's event |
| 911 | loop (web). On every platform the string-theme constructor, `setTheme(String)` |
| 912 | and `onBridge` are kept as deprecated forwards (no behaviour of their own; |
| 913 | `onBridge` gets the raw method and arguments of each call `onAction` got, right |
| 914 | after it); the host → widget bridge events (`bridgeEvent`) are removed. |
| 915 |
| 916 | ### 4.1 Swift (iOS, macOS): `WidgetHost` |
| 917 |
| 918 | ```swift |
| 919 | public struct WidgetTheme { var colorScheme: ColorScheme /* .light / .dark */; var params: [String: String]; var button: WidgetButtonTokens; var text: WidgetTextTokens } |
| 920 | public struct WidgetButtonTokens { var bg, text, radius, font, padding, height: String?; var pressedOpacity, disabledOpacity: Double? } |
| 921 | public struct WidgetTextTokens { var fontSize, lineHeight: Double?; var padding: String? } // v0.1.1 |
| 922 | public struct WidgetStorage { var local: [String: String]; var session: [String: String] } |
| 923 | public enum WidgetStorageArea: String { case local, session } |
| 924 | public enum WidgetHaptic { case impact(String), notification(String), selection } |
| 925 | public enum WidgetAction { case ready, openLink(URL), openTelegramLink(URL), haptic(WidgetHaptic) } |
| 926 | public struct WidgetGestureClaim { var x: Bool; var y: Bool; var hold: Bool } // hold: v0.1.2; y: always false since v0.1.3 |
| 927 | public enum WidgetResizeAnchor: String { case top, bottom } // v0.1.3: WidgetDiagnostics.resizeAnchor, next to height |
| 928 |
| 929 | init(html: String, theme: WidgetTheme = WidgetTheme(), width: CGFloat = 400, options: Options = Options(), …) throws |
| 930 | // Options: maximumHeight (600), policy (.strict), features, pools, …, locale ("en-US"), storage (the preload), |
| 931 | // contentSafeArea (WidgetContentSafeArea(): the client's time over a widget with no caption below it, §2.17, §5.12) |
| 932 | public struct WidgetContentSafeArea { var top, right, bottom, left, cornerLeft, cornerRight: Double } // points = CSS px, 0 by default |
| 933 | var onChange: ((WidgetDiagnostics) -> Void)? // height, resizeAnchor (v0.1.3), watchesPublicData, loaded, rendered, dead, diags, actions |
| 934 | var onWatchPublicData: ((Bool) -> Void)? // the widget started or stopped watching its shared state (§5.11): on a change |
| 935 | var onError: ((String) -> Void)? |
| 936 | var onAction: ((WidgetAction) -> Void)? |
| 937 | var onStorageCommit: ((WidgetStorageArea, [String: String]) -> Void)? // local before session |
| 938 | var onGestureClaim: ((WidgetGestureClaim) -> Void)? // every primary pointerdown; drive the bubble's recognizers with GestureArbiter (§5.5) |
| 939 | func setTheme(_ theme: WidgetTheme) |
| 940 | func setContentSafeArea(_ area: WidgetContentSafeArea) // only with the bubble's layout (a caption edit or move), never per frame |
| 941 | func setVisible(_ visible: Bool); func snapshot(completion:); func destroy() |
| 942 | // the renderer seam (rendererFactory), v0.6.0: a renderer of your own reports the paint limit, once, before it draws that frame (§5.14) |
| 943 | public enum WidgetPaintLimit: String { case paint = "paint-limit", backdrop = "backdrop-limit" } // maxHeavyBoxes 16, maxBackdropBoxes 2; message(count:) |
| 944 | extension Renderer { func limitExceeded(_ code: WidgetPaintLimit, count: Int) } |
| 945 | ``` |
| 946 |
| 947 | The widget's state and requests (§2.13–§2.15, §5.11): |
| 948 |
| 949 | ```swift |
| 950 | public struct WidgetData { var chatData: String?; var publicData: String? } // the full state: the chat state and the shared state |
| 951 | public enum WidgetChatType: String { case `private`, group, supergroup, channel } |
| 952 | public struct WidgetViewer { var id: Int64; var firstName: String?; var lastName: String?; var username: String?; var isPremium = false } // the account's own |
| 953 | public struct WidgetContext { var isCopy = false; var canQuery = false; var backgroundQuery = false; var chatType: WidgetChatType?; var viewer: WidgetViewer?; var preview = false; var wallet = false } // the server's flags; preview: §2.16; wallet: §2.18 |
| 954 | public struct WidgetRequest { let data: String; let wallet: Bool } // wallet: attach the wallet card (with_wallet) |
| 955 | public struct WidgetRequestAnswer { var result: String? } |
| 956 | public enum WidgetRequestFailure: Error { case timeout, rateLimited, notAllowed, failed, rejected, badRequest } // rejected, badRequest: wallet calls |
| 957 | public enum WalletCall { case sendTransaction(WalletTransaction, data: String), signData(SignDataPayload, data: String) } // .json: TON Connect's shapes |
| 958 | // Options: data (WidgetData()), context (WidgetContext()) |
| 959 | var onRequest: ((WidgetRequest, @escaping (Result<WidgetRequestAnswer, WidgetRequestFailure>) -> Void) -> Void)? // complete once, from any thread |
| 960 | var onWallet: ((WalletCall, @escaping (Result<WidgetRequestAnswer, WidgetRequestFailure>) -> Void) -> Void)? // §2.18, §5.13 |
| 961 | var onCopyText: ((String) -> Void)? |
| 962 | func setData(_ data: WidgetData) |
| 963 | ``` |
| 964 |
| 965 | `WidgetBubble`, `WidgetModel` (`WidgetView`) and `WidgetPreparer` take a |
| 966 | `WidgetTheme` the same way. `URL(string:)` may escape a few characters the |
| 967 | check keeps (`[`, `]`, a second `#`); the checked string is |
| 968 | `SdkPolicy.checkLink`'s. |
| 969 |
| 970 | ### 4.2 Kotlin (Android): `WidgetHost` |
| 971 |
| 972 | ```kotlin |
| 973 | data class WidgetTheme(val colorScheme: String = "light", val params: Map<String, String> = emptyMap(), val button: WidgetButtonTokens = WidgetButtonTokens(), |
| 974 | val text: WidgetTextTokens = WidgetTextTokens()) |
| 975 | data class WidgetButtonTokens(val bg: String? = null, val text: String? = null, val radius: String? = null, val font: String? = null, |
| 976 | val padding: String? = null, val height: String? = null, val pressedOpacity: Double? = null, val disabledOpacity: Double? = null) |
| 977 | data class WidgetTextTokens(val fontSize: Double? = null, val lineHeight: Double? = null, val padding: String? = null) // v0.1.1 |
| 978 | data class WidgetStorage(val local: Map<String, String> = emptyMap(), val session: Map<String, String> = emptyMap()) |
| 979 | sealed class WidgetAction { Ready; OpenLink(url); OpenTelegramLink(url); Haptic(kind, value?) } // kind: impact | notification | selection |
| 980 |
| 981 | WidgetHost(context, html, theme: WidgetTheme, widthDp, options, resources, rendererFactory) |
| 982 | // Options: minHeightDp (50), maxHeightDp (600), policy ("strict"), features, pools, …, locale ("en-US"), storage (the preload), |
| 983 | // contentSafeArea (WidgetContentSafeArea(): the client's time over a widget with no caption below it, §2.17, §5.12) |
| 984 | data class WidgetContentSafeArea(val top: Double = 0.0, val right: Double = 0.0, val bottom: Double = 0.0, val left: Double = 0.0, val cornerLeft: Double = 0.0, val cornerRight: Double = 0.0) // dp = CSS px |
| 985 | var onChange: ((WidgetDiagnostics) -> Unit)? // … height, resizeAnchor ("top" | "bottom", v0.1.3), watchesPublicData, actions |
| 986 | var onWatchPublicData: ((Boolean) -> Unit)? // the widget started or stopped watching its shared state (§5.11): on a change |
| 987 | var onError: ((String) -> Unit)? |
| 988 | var onAction: ((WidgetAction) -> Unit)? |
| 989 | var onStorageCommit: ((area: String, values: Map<String, String>) -> Unit)? // "local" | "session" |
| 990 | var onGesture: ((WidgetGestureClaim) -> Unit)? // v0.1.2: x, y, hold (y always false since v0.1.3); drive the bubble's recognizers with GestureArbiter (§5.5) |
| 991 | var onGestureClaim: ((x: Boolean, y: Boolean) -> Unit)? // deprecated since v0.1.2: called right after onGesture |
| 992 | fun setTheme(theme: WidgetTheme); fun setContentSafeArea(area: WidgetContentSafeArea); fun setVisible(visible: Boolean); fun destroy() |
| 993 | // the renderer seam (rendererFactory), v0.6.0: a renderer of your own reports the paint limit, once, before it draws that frame (§5.14) |
| 994 | enum class WidgetPaintLimit(val code: String) { PAINT("paint-limit"), BACKDROP("backdrop-limit") } // MAX_HEAVY_BOXES 16, MAX_BACKDROP_BOXES 2; message(count) |
| 995 | interface Renderer { …; fun limitExceeded(code: WidgetPaintLimit, count: Int) /* default: posts the limit message to WidgetHost */ } |
| 996 | ``` |
| 997 |
| 998 | The widget's state and requests: |
| 999 |
| 1000 | ```kotlin |
| 1001 | data class WidgetData(val chatData: String? = null, val publicData: String? = null) |
| 1002 | data class WidgetViewer(val id: Long, val firstName: String? = null, val lastName: String? = null, val username: String? = null, val isPremium: Boolean = false) |
| 1003 | data class WidgetContext(val isCopy: Boolean = false, val canQuery: Boolean = false, val backgroundQuery: Boolean = false, |
| 1004 | val chatType: String? = null, val viewer: WidgetViewer? = null, val preview: Boolean = false, |
| 1005 | val wallet: Boolean = false) // the server's flags; preview: §2.16; wallet: §2.18 |
| 1006 | data class WidgetRequest(val data: String, val wallet: Boolean = false) // wallet: attach the wallet card (with_wallet) |
| 1007 | data class WidgetRequestAnswer(val result: String? = null) |
| 1008 | enum class WidgetRequestFailure { TIMEOUT, RATE_LIMITED, FAILED, REJECTED, BAD_REQUEST } // REJECTED, BAD_REQUEST: wallet calls |
| 1009 | class WidgetRequestException(val failure: WidgetRequestFailure) : Exception() |
| 1010 | sealed class WalletCall { SendTransaction(transaction, data), SignData(payload, data) } // .json(): TON Connect's shapes |
| 1011 | // Options: data, context |
| 1012 | var onRequest: ((WidgetRequest, (Result<WidgetRequestAnswer>) -> Unit) -> Unit)? // Result.failure(WidgetRequestException(…)); any other exception is FAILED |
| 1013 | var onWallet: ((WalletCall, (Result<WidgetRequestAnswer>) -> Unit) -> Unit)? // §2.18, §5.13 |
| 1014 | var onCopyText: ((String) -> Unit)? |
| 1015 | fun setData(data: WidgetData) |
| 1016 | ``` |
| 1017 |
| 1018 | The WebView renderer keeps its parent from intercepting a press only while the |
| 1019 | widget may still take it as a hold (a `hold` claim, until the press leaves the |
| 1020 | slop vertically: `requestDisallowInterceptTouchEvent`). The Blitz and litehtml |
| 1021 | prototypes send only `wants`, always false now: they claim nothing. |
| 1022 |
| 1023 | ### 4.3 C++ (desktop core): `twidget::WidgetHost` |
| 1024 |
| 1025 | ```cpp |
| 1026 | struct WidgetButtonTokens { std::optional<std::string> bg, text, radius, font, padding, height; std::optional<double> pressedOpacity, disabledOpacity; }; |
| 1027 | struct WidgetTextTokens { std::optional<double> fontSize, lineHeight; std::optional<std::string> padding; }; // v0.1.1 |
| 1028 | struct WidgetTheme { std::string colorScheme; std::map<std::string, std::string> params; WidgetButtonTokens button; WidgetTextTokens text; }; |
| 1029 | struct WidgetStorage { std::map<std::string, std::string> local, session; }; |
| 1030 | struct WidgetAction { enum Kind { Ready, OpenLink, OpenTelegramLink, Haptic } kind; std::string url, hapticKind, hapticValue; }; |
| 1031 |
| 1032 | WidgetHost(std::string html, WidgetTheme theme, double width, WidgetHostOptions, std::shared_ptr<SandboxResources>, RendererFactory, …); |
| 1033 | // WidgetHostOptions: …, std::string locale ("en-US"), WidgetStorage storage (the preload), |
| 1034 | // WidgetContentSafeArea contentSafeArea (the client's time over a widget with no caption below it, §2.17, §5.12) |
| 1035 | struct WidgetContentSafeArea { double top = 0, right = 0, bottom = 0, left = 0, cornerLeft = 0, cornerRight = 0; }; // CSS px |
| 1036 | std::function<void(const WidgetDiagnostics&)> onChange; // … height, resizeAnchor ("top" | "bottom", v0.1.3), watchesPublicData, actions, storageCommits (first 1000) |
| 1037 | std::function<void(bool)> onWatchPublicData; // the widget started or stopped watching its shared state (§5.11): on a change |
| 1038 | std::function<void(const std::string&)> onError; |
| 1039 | std::function<void(const WidgetAction&)> onAction; |
| 1040 | std::function<void(const std::string& area, const std::map<std::string, std::string>&)> onStorageCommit; |
| 1041 | std::function<void(const WidgetGestureClaim&)> onGesture; // v0.1.2: x, y, hold (y always false since v0.1.3; twidget/gesture_policy.h, GestureArbiter) |
| 1042 | std::function<void(bool x, bool y)> onGestureClaim; // deprecated since v0.1.2: called right after onGesture |
| 1043 | void start(); void setTheme(const WidgetTheme&); void setContentSafeArea(const WidgetContentSafeArea&); void setVisible(bool); void destroy(); |
| 1044 | // the renderer seam (RendererFactory), v0.6.0: a renderer of your own reports the paint limit, once, before it draws that frame (§5.14) |
| 1045 | enum class WidgetPaintLimit { Paint, Backdrop }; // kMaxHeavyBoxes 16, kMaxBackdropBoxes 2; paintLimitCode, paintLimitMessage, paintLimitFromCode |
| 1046 | void Renderer::limitExceeded(WidgetPaintLimit code, int count); |
| 1047 | ``` |
| 1048 |
| 1049 | The widget's state and requests: |
| 1050 |
| 1051 | ```cpp |
| 1052 | struct WidgetData { std::optional<std::string> chatData, publicData; }; |
| 1053 | struct WidgetViewer { int64_t id = 0; std::optional<std::string> firstName, lastName, username; bool isPremium = false; }; |
| 1054 | struct WidgetContext { bool isCopy = false, canQuery = false, backgroundQuery = false; std::string chatType; /* "" = none */ std::optional<WidgetViewer> viewer; bool preview = false; bool wallet = false; }; |
| 1055 | struct WidgetRequest { std::string data; bool wallet = false; }; // wallet: attach the wallet card (with_wallet) |
| 1056 | struct WidgetRequestAnswer { std::optional<std::string> result; }; |
| 1057 | enum class WidgetRequestFailure { None, Timeout, RateLimited, Failed, Rejected, BadRequest }; // Rejected, BadRequest: wallet calls |
| 1058 | struct WalletCall { Method method; WalletTransaction transaction; SignDataPayload payload; std::string data; }; // toJson(): TON Connect's shapes |
| 1059 | struct WidgetRequestOutcome { WidgetRequestFailure failure = WidgetRequestFailure::None; WidgetRequestAnswer answer; }; |
| 1060 | // WidgetHostOptions: WidgetData data; WidgetContext context; |
| 1061 | std::function<void(const WidgetRequest&, std::function<void(const WidgetRequestOutcome&)> respond)> onRequest; // respond once, from any thread |
| 1062 | std::function<void(const WalletCall&, std::function<void(const WidgetRequestOutcome&)> respond)> onWallet; // §2.18, §5.13 |
| 1063 | std::function<void(const std::string& text)> onCopyText; |
| 1064 | void setData(const WidgetData& data); |
| 1065 | ``` |
| 1066 |
| 1067 | Storage strings keep a lone surrogate as WTF-8 (what QuickJS hands over), so |
| 1068 | a value round-trips exactly; it is not strict UTF-8 in that case. Commits |
| 1069 | already on their way reach `onStorageCommit` before `destroy()` returns. |
| 1070 |
| 1071 | ### 4.4 Web: `WidgetHost` (`@telegram/widget-sandbox/host/widget-host`) |
| 1072 |
| 1073 | ```ts |
| 1074 | interface WidgetTheme { colorScheme: 'light' | 'dark'; params?: Partial<ThemeParams>; button?: ButtonTokens; text?: TextTokens } |
| 1075 | interface TextTokens { fontSize?: number | string; lineHeight?: number | string; padding?: string } // v0.1.1 |
| 1076 | type WidgetAction = |
| 1077 | | { kind: 'ready' } |
| 1078 | | { kind: 'openLink'; url: string } |
| 1079 | | { kind: 'openTelegramLink'; url: string } |
| 1080 | | { kind: 'haptic'; haptic: 'impact' | 'notification' | 'selection'; value?: string }; |
| 1081 | new WidgetHost(container, html, { |
| 1082 | theme, // WidgetTheme, or a plain 'light' | 'dark' |
| 1083 | locale, storage: { local, session }, // the client's language and Web Storage preload |
| 1084 | contentSafeArea: { bottom, cornerRight, cornerLeft }, // the client's time over a widget with no caption below it (§2.17, §5.12); 0 by default |
| 1085 | onAction(action), onStorageCommit(area, values), onGestureClaim({ x, y, hold }), |
| 1086 | bubbleGestures, onBubbleGesture({ action, gesture, x, y, edge }), // v0.1.2: the renderer plays the bubble (§5.5) |
| 1087 | onResize(height, anchor), // anchor: 'top' | 'bottom', the widget's setResizeAnchor (v0.1.3) |
| 1088 | onWatchPublicData(on), // the widget started or stopped watching its shared state (§5.11): on a change |
| 1089 | data: { chatData, publicData }, // the chat state and the shared state as the message has them now |
| 1090 | context: { isCopy, canQuery, backgroundQuery, chatType, viewer: { id, firstName, lastName, username, isPremium }, preview, wallet }, // the server's flags (preview: §2.16; wallet: §2.18); fixed for the host's life |
| 1091 | onRequest({ data, wallet }), // resolve with the server's answer { result } or reject 'TIMEOUT' | 'RATE_LIMITED' | 'FAILED'; wallet: attach the wallet card |
| 1092 | onWallet(call), // §2.18, §5.13: { method: 'sendTransaction', transaction, data } | { method: 'signData', payload, data }; resolve with the bot's answer or reject 'REJECTED' | 'BAD_REQUEST' | … |
| 1093 | onCopyText(text), |
| 1094 | policy, visible, onDead, onError, onLoaded, onDiag, rendererFactory, workerPool, features, … |
| 1095 | }) |
| 1096 | host.resizeAnchor; // v0.1.3: the latest anchor, 'top' until the widget sets one |
| 1097 | host.watchesPublicData; // the widget's latest watchPublicData / unwatchPublicData, false until then |
| 1098 | host.setTheme(theme); host.setVisible(visible); host.setBubbleGestures(mode); host.destroy(); |
| 1099 | host.setContentSafeArea({ bottom, cornerRight, cornerLeft }); host.contentSafeArea; // only with the bubble's layout, never per frame |
| 1100 | host.setData({ chatData, publicData }); // the state changed (the server's update, the polled shared state): the full state |
| 1101 | // @telegram/widget-sandbox/shared/gesture-policy: GestureArbiter, claimOf and the thresholds, for a client's own recognizers |
| 1102 | ``` |
| 1103 |
| 1104 | The web client's page must also carry the CSP of invariant 6 (`connect-src` |
| 1105 | only Telegram's endpoints, `form-action 'none'`, no third-party |
| 1106 | `img-src`/`media-src`/`font-src`/`frame-src`). |
| 1107 |
| 1108 | ### 4.5 Node harness (`packages/core/scripts/sandbox-node.ts`) |
| 1109 |
| 1110 | For tests and tooling, not for clients. `RunOptions` takes `theme`, `locale`, |
| 1111 | `themeParams`, `button`, `text`, `storage` and `script` steps `{ theme, themeParams }`; |
| 1112 | `RunResult` has `actions` (what `onAction` would get), `storageCommits`, |
| 1113 | `resizeAnchor` and `resizeAnchors` (the latest anchor and each one the glue |
| 1114 | accepted, v0.1.3; the CLI prints a `resize anchor:` line), `watchesPublicData` |
| 1115 | and `publicDataWatches` (the same for `watchPublicData`; a `public data:` line) and `theme` (the |
| 1116 | renderer's `theme` message, which `--ops-file` writes before the ops, then the |
| 1117 | `safeArea` one). `contentSafeArea` and `script` steps `{ safeArea }` are the client's |
| 1118 | time over the widget (§2.17; `RunResult.contentSafeArea`); from a shell |
| 1119 | `--safe-area bottom[,cornerRight[,cornerLeft]]` (`--safe-area 24,64`, or `24,0,64` for a |
| 1120 | right-to-left client). |
| 1121 | Gestures are injected per event (`gesture: n`). Since v0.1.2 `width` (the bubble's, |
| 1122 | default 400) and `gestures` (`tap`, `hold`, `double-tap`, `swipe`, `right-click`) run the |
| 1123 | widget on the real renderer core in headless Chromium after load: `RunResult.gestures` |
| 1124 | reports per press the element, its `touch-action` claim, the policy's outcome, the events |
| 1125 | the widget received and a hint; `height` is the laid-out content height. From a shell: |
| 1126 | `sandbox-node.ts widget.html --width 360 --hold 120,40 --double-tap 120,40 --swipe 60,80,120,0` |
| 1127 | (`--desktop` for a desktop client's bubble, `--json` for the full result). With `width` the |
| 1128 | renderer also counts heavy boxes (v0.6.0): `RunResult.paint` (`heavy`, `backdrop` at the end, `peakHeavy`, |
| 1129 | `peakBackdrop`), a `paint: N heavy boxes (max 16), M with backdrop-filter (max 2)` line with a warning past 12, and |
| 1130 | past the limit `stopped` with the renderer's reason, as a host stops the widget. |
| 1131 |
| 1132 | The widget's state and requests: `data`, `context` (`WIDGET_MESSAGE_KINDS` in |
| 1133 | `sdk-policy.ts` has the server's flags per kind of message) and `onRequest` |
| 1134 | (sync or a promise; its answers go into the widget at the next step of the |
| 1135 | run), `script` steps `{ data }` (the client's `setData`) and `{ visible }` (a |
| 1136 | hidden → visible step resets the background interval); `RunResult.requests` |
| 1137 | (each request's data, whether it went out without a tap, the gate's verdict and |
| 1138 | what went back) and `copiedTexts`. From a shell: `--message |
| 1139 | private|group|via-bot|no-queries|live-copy|copy|preview`, or `--copy`, `--can-query`, |
| 1140 | `--background-query`, `--chat-type` one by one; `--viewer id[,first,last,username,premium]`, `--chat-data`, |
| 1141 | `--public-data`, `--answer '{"result":"…"}'` or `--answer-error TIMEOUT`, |
| 1142 | `--set-data '{…}'`; the CLI prints a `request` line per request and a |
| 1143 | `copyText` line per copy. The wallet (§2.18): `context.wallet` and `onWallet` (`RunResult.walletCalls`: each call |
| 1144 | as checked, the gate's verdict, what went back); from a shell `--wallet`, `--wallet-answer '{"result":"…"}'` or |
| 1145 | `--wallet-error REJECTED`, and a `wallet.<method>` line per call. |
| 1146 |
| 1147 | ## 5. What the client implements |
| 1148 |
| 1149 | ### 5.1 Theme |
| 1150 |
| 1151 | - Map the chat's theme to every key of §2.3 for the bubble the widget sits |
| 1152 | in: `bg_color` is that bubble's own fill, the colour the UA layer paints |
| 1153 | behind the widget. A widget the user sent or forwarded sits in an outgoing |
| 1154 | bubble: pass the outgoing bubble's colours (fill, text, hint, link, |
| 1155 | separator), not the incoming ones; custom chat themes and night mode the |
| 1156 | same way. A bubble with a gradient or a translucent fill has no single |
| 1157 | colour: pass the one the widget's area shows most (the client draws the |
| 1158 | bubble under a transparent widget view either way). |
| 1159 | - Pass the button tokens of §2.4 from the client's own button, and the text |
| 1160 | tokens from its message text: `fontSize` = the chat's message font size, |
| 1161 | following the text-size setting; `lineHeight` and `padding` as the client's |
| 1162 | text bubble lays out text (the reference set 15 / 1.35 / `8px 12px` when |
| 1163 | unsure). Pass them at creation and call `setTheme` on every change. |
| 1164 | - Pass the UI language as `locale`. |
| 1165 |
| 1166 | ### 5.2 Links |
| 1167 |
| 1168 | - On `openLink(url)`: show a native confirmation that displays the **full |
| 1169 | URL** (not only the domain; the host in its ASCII form, as the framework's |
| 1170 | URL parser gives it), with Open and Cancel. On Open, go to the external |
| 1171 | browser (or the client's in-app browser, by its usual setting). |
| 1172 | - On `openTelegramLink(url)`: no confirmation of its own; open it as a tapped |
| 1173 | `t.me` link in a message, through the client's own `t.me` handling, which |
| 1174 | keeps its own confirmations (joining a chat, a proxy, a login and the like). |
| 1175 | Telegram opens its own links without asking (decided 2026-10-29, |
| 1176 | `docs/decisions.md`, "Telegram links open without a confirmation"). |
| 1177 | - One dialog at a time; drop actions that arrive while one is shown. |
| 1178 | - The framework guarantees at most one link action per pointer press. |
| 1179 |
| 1180 | ### 5.3 Haptics |
| 1181 |
| 1182 | Play `impact`, `notification` and `selection` with the platform's generators |
| 1183 | (iOS `UIImpactFeedbackGenerator`, `UINotificationFeedbackGenerator`, |
| 1184 | `UISelectionFeedbackGenerator`; Android `View.performHapticFeedback` or |
| 1185 | `VibrationEffect`); respect the system's haptics setting. Desktop and web |
| 1186 | ignore them. |
| 1187 |
| 1188 | ### 5.4 Storage |
| 1189 |
| 1190 | - Key: (account, chat, message id) of the message the widget belongs to (§2.8). |
| 1191 | - At creation, pass the stored `local` area and the in-memory `session` area as |
| 1192 | `storage`. |
| 1193 | - On `onStorageCommit(area, values)`: keep `values` as the new content of that |
| 1194 | area. Write `local` to disk with a short delay (for example 1 s) and at once |
| 1195 | when the widget is hidden or destroyed and when the app goes to the |
| 1196 | background or terminates. Keep `session` in memory only. |
| 1197 | - Delete both areas with the message, with the chat or its history, with the |
| 1198 | account, and on "Clear cache". There are no per-bot quotas and no age-based |
| 1199 | eviction. |
| 1200 | - The framework enforces the 4 KB quota; the client stores what it gets. |
| 1201 |
| 1202 | ### 5.5 Gestures and drag (D4) |
| 1203 |
| 1204 | Who gets a press is decided by one shared policy, so every client and the sandbox |
| 1205 | behave the same (v0.1.2, `docs/decisions.md` "Gestures: `touch-action` is the |
| 1206 | claim" and, v0.1.3, "Vertical drags are the chat's"). Taps and **double taps |
| 1207 | over the widget are always the widget's**, on every element: a double tap |
| 1208 | reaches it as both clicks and then `dblclick`, and the client's double-tap |
| 1209 | reaction stays on the bubble outside the widget. **Vertical drags are always |
| 1210 | the chat's**: the list scrolls over every widget, whatever `touch-action` says, |
| 1211 | and the widget gets `pointercancel`. Horizontal drags and holds are claimed per |
| 1212 | element at `pointerdown` by CSS `touch-action`: |
| 1213 |
| 1214 | | over an element with | hold | horizontal drag | vertical drag | |
| 1215 | |---|---|---|---| |
| 1216 | | `touch-action: auto` (default), `manipulation` | bubble: message menu | bubble: swipe-to-reply / back | list scroll | |
| 1217 | | `pan-y` | bubble | widget | list scroll | |
| 1218 | | `pan-x` (claims nothing since v0.1.3) | bubble | bubble | list scroll | |
| 1219 | | `none` | widget (`contextmenu`) | widget | list scroll (since v0.1.3) | |
| 1220 |
| 1221 | The first move past the slop locks the press's axis: a press that starts |
| 1222 | horizontally on a claimed element is the widget's on both axes until the |
| 1223 | finger lifts; one that starts vertically is the list's. A hold the widget has |
| 1224 | won (on `none`) is locked the same way at its first move past the slop: |
| 1225 | sideways it stays the widget's, up or down the list takes it and the widget |
| 1226 | gets `pointercancel` after its `contextmenu`. |
| 1227 |
| 1228 | `touch-action` on a container covers its children, as in CSS (the ancestor |
| 1229 | chain runs up to the widget's `<html>`). The leading 20 px of the widget (the |
| 1230 | right edge in a right-to-left UI) take no claim (the system back gesture), and the bubble |
| 1231 | outside the widget (caption, time, edges) is always the place for the menu and |
| 1232 | the reaction. With a mouse: a |
| 1233 | right click is the menu, or `contextmenu` for the widget on `none`; clicks, |
| 1234 | double clicks, holds and drags are the widget's. |
| 1235 |
| 1236 | The policy is `GestureArbiter` (`packages/core/src/shared/gesture-policy.ts`; |
| 1237 | `GesturePolicy.swift`, `GesturePolicy.kt`, `twidget/gesture_policy.h`), checked on |
| 1238 | every platform against `packages/core/tests/fixtures/gesture-policy.json`: |
| 1239 |
| 1240 | | | value | |
| 1241 | |---|---| |
| 1242 | | touch slop (a tap or a hold stays within it) | 10 px | |
| 1243 | | hold | 500 ms within the slop | |
| 1244 | | double tap (`dblclick`) | the 2nd `pointerdown` ≤ 300 ms after the 1st `pointerup`, ≤ 40 px from the 1st `pointerdown` | |
| 1245 | | axis lock | the dominant axis when the press leaves the slop (a tie is vertical) | |
| 1246 | | edge strip | 20 px from the widget's leading edge | |
| 1247 |
| 1248 | What the client does: |
| 1249 |
| 1250 | 1. On every primary `pointerdown` the host reports `onGestureClaim` (Kotlin and |
| 1251 | C++: `onGesture`): `x` (horizontal drags) and `hold`; `y` is always false |
| 1252 | since v0.1.3 (the arbiter ignores it). It arrives a few |
| 1253 | milliseconds after the touch starts; hold the bubble's recognizers until it |
| 1254 | does (or 150 ms pass, then treat it as no claim). |
| 1255 | 2. Feed the touch over the widget to a `GestureArbiter`: `down(t, x, y, claim, |
| 1256 | pointer, button)` with x from the widget's leading edge (`width - x` in a |
| 1257 | right-to-left UI) and y from its top, in CSS px (points, dp), then `move`, |
| 1258 | `up`, `cancel` (the platform cancelled it), and `tick` at `holdDeadline()`. |
| 1259 | 3. On a verdict with `cancel`: take the touch from the widget view the |
| 1260 | platform's way (iOS: a recognizer that begins with `cancelsTouchesInView`; |
| 1261 | Android: intercept in the parent, the WebView gets `ACTION_CANCEL`; desktop: |
| 1262 | end the press for the view), so the widget gets `pointercancel` and no |
| 1263 | `click`, and do `action`: `menu` (the message menu), `swipe` (swipe-to-reply, |
| 1264 | or back by its direction), `scroll` (the list), `back` (the system's or the |
| 1265 | chat's back gesture). |
| 1266 | 4. On a verdict for the widget: stand back for the rest of the press (no menu, |
| 1267 | no swipe, no list scroll from it: the axis is locked). Until then the list's |
| 1268 | own scroll must still be able to start on a vertical move: never keep the |
| 1269 | list from scrolling because of a claim. The double-tap reaction recognizer must not |
| 1270 | act over the widget at all. The renderer sends the widget its own `dblclick` |
| 1271 | / `contextmenu`; the client sends nothing. |
| 1272 | 5. No keyboard: the client never routes key events to the widget, and the |
| 1273 | chat's input field keeps the focus. |
| 1274 |
| 1275 | Platform notes, from the demo bubbles: on iOS a recognizer with |
| 1276 | `cancelsTouchesInView` does not cancel a touch WKWebView already handles (WebKit |
| 1277 | reads touches through its own recognizers); disabling and re-enabling the web |
| 1278 | view's enabled gesture recognizers once, when the bubble takes the press, makes |
| 1279 | WebKit send `pointercancel` (public API; the iOS demo's `BubbleGestures`). On |
| 1280 | Android, intercept in the parent and send the child an `ACTION_CANCEL` (the |
| 1281 | Android demo's `BubbleGestureLayout`). The Android WebView renderer keeps its |
| 1282 | parent from intercepting only while a `hold` claim may still win (until the |
| 1283 | press leaves the slop: vertically, the list takes it). The Blitz and litehtml |
| 1284 | prototypes report only `wants`, always false: they claim nothing. On the web |
| 1285 | there are no recognizers over the widget: `WidgetHost` with `bubbleGestures` |
| 1286 | lets the renderer play the bubble with the same policy and reports what it took |
| 1287 | (`onBubbleGesture`); the dev app and the feed demo do that by default |
| 1288 | (`gestures`: phone, desktop or off). The browser's own panning is the list |
| 1289 | scroll there: the renderer gives the engine every `touch-action` widened to |
| 1290 | allow vertical panning (`none` → `pan-y`), so a touch screen scrolls the page |
| 1291 | over any widget, while the claim reads the widget's own value. |
| 1292 |
| 1293 | ### 5.6 Bubble size |
| 1294 |
| 1295 | - The size anchors `width` and `height` of `messageMediaWidget` (D12b; `0` = |
| 1296 | auto, each axis independent, `docs/tgw-format.md`). Width `0`: the widget |
| 1297 | takes the bubble's width; `W > 0`: a fixed-width widget, `W` clamped to |
| 1298 | [200, the bubble's maximum width], and the host is created with that width. |
| 1299 | Height `0`: the default placeholder before load, then the content height the |
| 1300 | host reports (`onChange` → `height`, web `onResize`) clamped to [50, 600] and |
| 1301 | cached per message; `H > 0`: a fixed height clamp(H, 50, 600) from the start, |
| 1302 | unchanged by the content. The four combinations are tabulated in |
| 1303 | `docs/integration.md` ("Bubble sizing"). 200 / 50 / 600 are the shared |
| 1304 | v0.1.0 constants, the same on every client; the hosts clamp to [50, 600] by |
| 1305 | default. Test it with a test bot sending `inputMediaWidget` with the anchors |
| 1306 | set. |
| 1307 | - Content beyond the bubble's height (600 in auto mode, or the fixed height) is |
| 1308 | clipped: no inner scrolling (outside the profile), no fullscreen button |
| 1309 | (D12a). |
| 1310 | - The widget view fills the bubble: no padding of the bubble's own around it |
| 1311 | (the widget's body margin, the `padding` text token, is the inset, §2.4), and |
| 1312 | the bubble clips the view at its corner radius, so a background the widget |
| 1313 | paints reaches the rounded edges. |
| 1314 | - Text is not selectable unless the widget enables it with `user-select: text` |
| 1315 | (D18 since v0.1.1; §2.4, §5.10). |
| 1316 | - **The resize anchor** (v0.1.3, §2.12): with every height the host reports the |
| 1317 | edge that stays put (`WidgetDiagnostics.resizeAnchor` next to `height`; web |
| 1318 | `onResize(height, anchor)`), `top` until the widget sets one. When an auto |
| 1319 | height changes, the list keeps that edge where it is on screen: for `top` the |
| 1320 | content below the bubble moves; for `bottom` the content above moves (in a |
| 1321 | list laid out from the top, add the height difference to the scroll offset; |
| 1322 | in an inverted chat list that grows from the bottom it is the natural |
| 1323 | behaviour). The same holds when the bubble opens at its cached height and the |
| 1324 | first report differs, and after the bubble is re-created (the anchor is the |
| 1325 | one the new run reports with its height). A bubble off screen keeps the |
| 1326 | visible content in place, as for any item that changes height. Keep the |
| 1327 | anchor with the cached height per message. |
| 1328 | - During an animated height change, align the old pixels to the anchored |
| 1329 | edge: the widget view (or its snapshot) is pinned to the bubble's bottom for |
| 1330 | `bottom` and to its top for `top`, so the edge that stays put does not move |
| 1331 | while the bubble's other edge animates. A fixed height (`H > 0`) never |
| 1332 | changes, whatever the anchor. |
| 1333 |
| 1334 | ### 5.7 Failures and restarts (D22) |
| 1335 |
| 1336 | - When the host reports `dead`, the last frame stays with the badge |
| 1337 | (`stoppedLabel`, localised by the client). |
| 1338 | - The client may build a new host for the message the next time the bubble is |
| 1339 | shown; after 2 crashes in a row the widget stays stopped until the app |
| 1340 | restarts (D22). The HTML never changes after sending, so no edit brings a |
| 1341 | stopped widget back. |
| 1342 |
| 1343 | ### 5.8 Visibility |
| 1344 |
| 1345 | Call `setVisible(false)` when the bubble leaves the screen and when the app |
| 1346 | goes to the background, `setVisible(true)` when it is back. |
| 1347 |
| 1348 | ### 5.9 The message: media, caption, flag |
| 1349 |
| 1350 | - The widget is `messageMediaWidget` (layer 233): inflate `payload` (zlib, |
| 1351 | RFC 1950, not gzip), no size limit of your own, hand the HTML to the host (`docs/tgw-format.md`, |
| 1352 | `docs/integration.md`). The HTML never changes after sending: a change of the |
| 1353 | widget's state goes to the live host with `setData` (§5.11); there is no new |
| 1354 | host for it. |
| 1355 | - Rendering is enabled by the client's own platform/version flag; off, or |
| 1356 | below layer 233 (`messageMediaUnsupported`), the message shows as |
| 1357 | unsupported media with its caption. Keep that fallback. |
| 1358 | - The media caption is the preview and search text; without one, the localized |
| 1359 | "Widget" stub. A widget with no caption below it (none, or one shown above it) |
| 1360 | gets the message time over its bottom corner (§5.12). |
| 1361 | - Test with a test bot in a tester's private chat and forward into the shared |
| 1362 | test channel (a bot sends widgets to its private chats, to the basic groups |
| 1363 | and supergroups it is a member of, and via its inline mode; the channel gets |
| 1364 | forwards). Every conformance widget is sent that way as a layer-233 message, with its |
| 1365 | reference picture posted next to it (`packages/conformance/channel.json`, |
| 1366 | `docs/integration.md`, "Testing"). |
| 1367 |
| 1368 | ### 5.10 Text selection (v0.1.1) |
| 1369 |
| 1370 | Text a widget marked `user-select: text` is selectable; everything else is not |
| 1371 | (§2.4). |
| 1372 |
| 1373 | - Touch: a long press over text (`touch-action: auto`) is the bubble's (§5.5), |
| 1374 | so selection inside a widget starts the way the client |
| 1375 | selects text in an ordinary message (its bubble menu's Select, or its own |
| 1376 | selection mode), and the renderer view then takes the selection gestures. |
| 1377 | - Mouse (desktop, web): a drag over selectable text selects it; a press |
| 1378 | anywhere else still selects nothing and keeps the chat input's focus. |
| 1379 | - Copy uses the client's normal copy command and menu. |
| 1380 | - A native renderer (litehtml, TwidgetCore, the Swift renderer) must honour |
| 1381 | `user-select: text` to be conformant; until it does, the text stays |
| 1382 | unselectable and the widget still works. |
| 1383 |
| 1384 | ### 5.11 The widget's state, requests and copies |
| 1385 |
| 1386 | The server's side is `docs/tgw-format.md`, "The widget's state and requests" |
| 1387 | (the TL names there are the server's). The widget's HTML never changes; its |
| 1388 | state does, and only the bot writes it: the chat state (`chat_data`) and the |
| 1389 | shared state (`public_data`). |
| 1390 |
| 1391 | - **Create** the host with `data` = the message's state, `chat_data` and |
| 1392 | `public_data`, as the client has it now (absent = none), and `context` from |
| 1393 | the message, read, not derived: `isCopy` = `is_copy`, `canQuery` = `can_query`, |
| 1394 | `backgroundQuery` = `background_query` (the server computes them per |
| 1395 | message), `chatType` = the kind of chat the message is in, `viewer` = the |
| 1396 | account's user id. Pass them for every message; the framework drops the chat |
| 1397 | type and the chat state of any copy (a copy is told nothing about the chat it |
| 1398 | is in) and the viewer of any message without `canQuery`. A client that passes no flags gets no requests. |
| 1399 | - **Changes of the state** reach the client two ways; pass the full new state |
| 1400 | to the live host each time (`setData`), no new host, no restart: |
| 1401 | - `updateMessageWidgetData` (the bot edited `chat_data` and/or |
| 1402 | `public_data`; in a supergroup it comes with the channel's pts, through the |
| 1403 | usual edit of channel posts): apply the chat state and the shared state it |
| 1404 | carries; |
| 1405 | - a shared widget's shared state (`public_data`; the media has a `widget_id`) |
| 1406 | changes for every carrier at once, and the client polls it **for widgets |
| 1407 | that watch** (`onWatchPublicData` / `watchesPublicData`, §2.13): while such |
| 1408 | widgets are on screen, call `messages.getWidgetPublicData` for one visible |
| 1409 | carrier per id, one message per call with its `hash` (the last one, 0 at |
| 1410 | first), again after the `period` each answer carries (the server's: |
| 1411 | 5–3600 s, 30 s by default, also before the first answer), and apply a new |
| 1412 | shared state to every widget on screen with that id. A widget that does not watch is never polled; one |
| 1413 | without a `widget_id` has nothing to poll. This includes |
| 1414 | forwarded copies: on a copy `setData` changes only the shared state. |
| 1415 | Keep the state with the message, so a host created later gets it. |
| 1416 | - **Requests.** On `onRequest`, call `messages.getBotWidgetQueryAnswer` (the peer, |
| 1417 | the message id in the user's own coordinates, `data` as UTF-8 bytes) and |
| 1418 | complete with the answer's `result` (absent: `{ result: null }`). Map the |
| 1419 | errors: `WIDGET_RESPONSE_TIMEOUT` → `timeout`, `FLOOD_WAIT` → `rateLimited`, |
| 1420 | anything else (`WIDGET_QUERY_NOT_ALLOWED`, `MESSAGE_ID_INVALID`, the network) |
| 1421 | → `failed`. Complete every request exactly once: the widget can send its next |
| 1422 | request only after it. Do not re-fetch the state after an answer: the bot's |
| 1423 | edits arrive the usual ways above, and a widget that needs them at once gets |
| 1424 | them in `result`. Whether a request came from a tap is not passed on: the |
| 1425 | server and the bot cannot tell either. The framework has already checked |
| 1426 | `data`, the flags, the tap or the background rules and the one-in-flight rule: |
| 1427 | the client only delivers. Show nothing of its own for a request: the answer |
| 1428 | has no toast, alert or link; the bot's `result` is the widget's to show. |
| 1429 | - **copyText.** On `onCopyText`, copy the text and show the client's toast |
| 1430 | with the text itself ("Copied: …", truncated to the toast if long). No |
| 1431 | confirmation: the framework allowed it only on a tap. |
| 1432 | - **The network marker.** Where the message has `can_query`, mark the widget |
| 1433 | as network-capable ("a tap may send data to the bot's server"); without it, |
| 1434 | no marker: the server refuses every request from that message |
| 1435 | (`docs/integration.md`, "The network marker"). |
| 1436 | - **Previews.** In a list of inline results, show a widget result |
| 1437 | (`botInlineMessageWidget`: its state, no flags) as a preview: create the host |
| 1438 | with `context.preview` and the result's `chat_data` / `public_data` as |
| 1439 | `data`, no viewer, no storage, no `onRequest` needed, no network marker; a tap |
| 1440 | on it is yours (it selects the result: route no touches to the widget view). |
| 1441 | When the user sends it, the sent message is a new widget: create a new host |
| 1442 | for it. |
| 1443 | - **Forwards.** Forwarding a widget without its author is not offered (the |
| 1444 | server keeps the forward header anyway), so a widget always shows which bot it |
| 1445 | is from. |
| 1446 |
| 1447 | ### 5.13 The wallet (§2.18) |
| 1448 |
| 1449 | - **`context.wallet`**: pass `true` when the client supports Gram Wallet and the wallet is available to this user |
| 1450 | (their country); the widget then gets `TelegramWidget.wallet` wherever it may ask the bot. Whether the user |
| 1451 | already has a wallet is not part of it: one is created when a widget asks for it. |
| 1452 | - **A request with the wallet** (`WidgetRequest.wallet`): call `messages.getBotWidgetQueryAnswer` with |
| 1453 | `widgetQueryTypeData` and `with_wallet`: the server attaches the cloud wallet's card from the user's profile |
| 1454 | (`wallet_card`) to the bot's update, creating the wallet if the user has none. The framework let it through only |
| 1455 | on a tap. |
| 1456 | - **`onWallet`**: show the client's existing TON Connect window over the chat, with the bot of the message in its |
| 1457 | header (name, username, avatar; never anything the widget says about itself) and the emulation of the |
| 1458 | transaction, or the text to sign (a warning for bytes and cells). Ignore touches on it for its first 0.5–1 s: the |
| 1459 | second tap of a double tap over the widget must not land on Confirm. If the wallet is empty, offer the top-up over |
| 1460 | the chat before sending; if `valid_until` has passed meanwhile, fail with `badRequest`. Decline → `rejected`; |
| 1461 | the wallet's refusal (network, sender, cells) → `badRequest`. |
| 1462 | - **After the confirmation**: `sendTransaction` goes out the wallet's usual way (`wallet.sendTransfer`); then send |
| 1463 | the outcome to the bot as a widget query with `call.data`: `widgetQueryTypeSentTransaction` with the |
| 1464 | transaction's normalised message hash (`msg_hash`), or `widgetQueryTypeSignData` with the signature as TON |
| 1465 | Connect's result (`signature`, `address`, `timestamp`, `domain` = `bot<bot_id>`, `payload`), each with **the |
| 1466 | device's wallet** (`userWallet`: address, balance, public key, StateInit), the one that signed: with the wallet's |
| 1467 | backup off a device can hold another key and another wallet than the profile's card. Complete with the bot's answer |
| 1468 | as for a request. No second tap: the call already had one. A failure of that query maps as a request's. |
| 1469 | - **The formats**, as the server takes them (the server team, 2026-10-30); `userWallet` reaches the bot as the client |
| 1470 | wrote it: |
| 1471 | - `userWallet.address`: the raw form (`0:` and 64 hex digits) or the user-friendly one (base64url, 48 characters, |
| 1472 | `UQ…` / `EQ…`), mainnet only: the server refuses a testnet form, parses either and checks it against |
| 1473 | `sign_data.address`. A bot parses it as well: the two forms are one address; |
| 1474 | - `userWallet.balance`: nanotons (1 TON = 10⁹), a whole number, the balance the device last knew (toncenter or the |
| 1475 | app's cache). For display only: the server checks its type alone, and a bot that needs the balance asks the chain; |
| 1476 | - `userWallet.public_key` and `userWallet.state_init` share `flags.0`: both or neither. Both with |
| 1477 | `widgetQueryTypeSignData` (the server requires the key and checks its length), and with |
| 1478 | `widgetQueryTypeSentTransaction` whenever the wallet SDK has them; |
| 1479 | - `userWallet.public_key`: the 32 bytes of the Ed25519 key, as bytes (not hex or base64), from the wallet SDK or the |
| 1480 | StateInit's data: the bot checks the signature with it; |
| 1481 | - `userWallet.state_init`: the wallet contract's StateInit as a bag of cells, what the TON SDK gives as |
| 1482 | `stateInit.toBoc()` (`wallet.createStateInit()`; a few hundred bytes for a standard wallet; the server takes about |
| 1483 | 1 KB and does not look inside). Its hash is the address, and a standard wallet's data holds the key, so a bot ties |
| 1484 | the key to the address before the contract is deployed (a new wallet is not on chain until its first transfer, and |
| 1485 | there is no `connect` with `walletStateInit`). Once the wallet is deployed, the chain's `get_public_key` ties them |
| 1486 | too; |
| 1487 | - `msg_hash`: the normalised hash of the external message (TEP-467), 64 lowercase hex digits, by which toncenter |
| 1488 | and tonapi find the transaction; |
| 1489 | - `sign_data`: `signData`'s result as is: `signature` in base64, `address` in the raw form, `timestamp` in Unix |
| 1490 | seconds, `domain`, and `payload` as the widget sent it. |
| 1491 | - The server's API (the query types, `with_wallet`, `userWallet`, the card in the updates; `docs/decisions.md`, |
| 1492 | "The wallet") is agreed and not shipped yet: until it is, leave `context.wallet` unset. |
| 1493 |
| 1494 | ### 5.12 The time over a widget with no caption below it (§2.17) |
| 1495 |
| 1496 | - With a caption below the widget, draw the time in the caption's line as for any |
| 1497 | media and pass nothing (the content safe area stays 0). Without a caption, and |
| 1498 | with a caption shown above the widget (`invert_media`, as on a photo), draw the |
| 1499 | message time and its status (ticks, "edited", views) over the widget's bottom |
| 1500 | corner, on a |
| 1501 | backing as over a photo or a video (the widget's background can be any colour): |
| 1502 | the right corner in a left-to-right interface, the left one in a right-to-left |
| 1503 | one. |
| 1504 | - Pass the band and the corner as the host's `contentSafeArea`, in points / dp / |
| 1505 | CSS px: `bottom` = the height of the band the time takes at the widget's |
| 1506 | bottom edge (the backing and its margins), `cornerRight` (or `cornerLeft` in a |
| 1507 | right-to-left interface) = the width of the corner the time takes in that band, |
| 1508 | the backing and its margins; `top`, `left` and `right` 0. Give them **at |
| 1509 | creation**, before the first render, so the first height the host reports |
| 1510 | already has the band. |
| 1511 | - Change them with `setContentSafeArea` only when the bubble's layout changes: a |
| 1512 | caption added or removed by an edit, or moved above or below the widget, |
| 1513 | "edited" appearing, a views counter that grows wider. Never per frame and never for the chat's scroll: the floating date |
| 1514 | pill has no contract (draw it over the widget like over a photo). |
| 1515 | - The time is a view over the widget: taps on it are the client's (its own |
| 1516 | hit test; on the web an element over the renderer), never forwarded to the |
| 1517 | widget. Nothing in the gesture policy changes. |
| 1518 | - What the widget sees and how a widget handles it: §2.17. The renderer's UA |
| 1519 | layer pads an unstyled body by the band, so such a widget is that much taller |
| 1520 | with no caption below it. |
| 1521 |
| 1522 | ### 5.14 Heavy boxes, with a renderer of your own (v0.6.0) |
| 1523 |
| 1524 | The framework's WebView renderer counts by itself. A client renderer counts the boxes it lays out that are heavy, by |
| 1525 | the rule of `packages/core/src/shared/paint-policy.ts` on the computed style (a blurred shadow, a filter, a |
| 1526 | backdrop-filter, opacity below 1 but a disabled or pressed `<button>`'s own dimming, or an animation of one of them), checks the fixture |
| 1527 | `packages/core/tests/fixtures/paint-policy.json`, and past 16 (or 2 with backdrop-filter) calls the seam's |
| 1528 | `limitExceeded(code, count)` before it draws that frame. It draws the stopped widget without those effects; the host |
| 1529 | does the rest (`docs/integration.md`, "Heavy boxes"). |
| 1530 |
| 1531 | ## 6. Out of v1 and the decisions of 2026-10-17 |
| 1532 |
| 1533 | Out of v1: sending messages on the user's behalf (requests to the bot and the |
| 1534 | widget's state came in on 2026-10-25, §2.13–§2.14); sharing; payments; the viewer's |
| 1535 | identity beyond the id (§2.13); popups; `MainButton`; per-bot |
| 1536 | `DeviceStorage` and cloud storage; keyboard input; form controls other than |
| 1537 | `<button>`; `TelegramWidget.platform`; |
| 1538 | a `linkOpened` event; fullscreen; accessibility (D21); MCP Apps transport (D19, |
| 1539 | later). |
| 1540 |
| 1541 | The questions this contract left open, as decided on 2026-10-17: |
| 1542 |
| 1543 | 1. Haptics need no gesture: allowed while the widget is visible, with the rate |
| 1544 | limit of §2.6 (a bucket of 5, refilled at 10 per second). Since v0.2.2 they |
| 1545 | need a touch, or get one 1 s series without one (§2.6). |
| 1546 | 2. Limits: URLs at most 256 characters, at most 16 handlers per event type, and |
| 1547 | the widget stays stopped after 2 crashes in a row (D22, which said 2–3). |
| 1548 | 3. `openTelegramLink` takes any `t.me` path, as in Mini Apps; the client's own |
| 1549 | handler confirms the dangerous ones. No deny-list in the glue. |
| 1550 | 4. No `TelegramWidget.platform` in v1. |
| 1551 | 5. Double tap and long press always stay with the bubble (the reaction, the |
| 1552 | message menu): the widget gets single taps and, in v1, drags. *Replaced in |
| 1553 | v0.1.2*: double taps over the widget are always the widget's, and |
| 1554 | `touch-action: none` gives it holds too (§5.5, `docs/decisions.md` "Gestures: |
| 1555 | `touch-action` is the claim"). |
| 1556 | 6. No `linkOpened` event in v1: the widget is not told whether the user opened |
| 1557 | the link. |
| 1558 | 7. The bubble size from the bot's `width` and `height` is tested end to end |
| 1559 | with a test bot (layer 233 ships with v0.1.0). |
| 1560 |
| 1561 | ## 7. The framework milestone |
| 1562 |
| 1563 | SDK v1 is implemented in the framework as part of v0.1.0 (2026-10-17): the |
| 1564 | shim, all five glue copies and the Node harness, with tests on every platform |
| 1565 | (the policy fixture `packages/core/tests/fixtures/sdk-policy.json` in each |
| 1566 | suite; `packages/core/tests/unit/sdk.test.ts`, `tests/sdk.spec.ts` — |
| 1567 | `pnpm test:sdk` — and the platform suites through the real engine). The corpus |
| 1568 | widgets that called `sendMessage` keep their state in `localStorage` or link |
| 1569 | out with `openLink`, and the corpus READMEs say so; the attack files keep |
| 1570 | calling it to check that it is gone. |
| 1571 |
| 1572 | The widget's state and requests (§2.13–§2.15, §5.11) are implemented in the |
| 1573 | framework on `claude/widget-queries-25a3d2` (2026-10-25, for the next release): |
| 1574 | the shim, all five glue copies and the Node harness, the policy's new sections |
| 1575 | in `sdk-policy.json` on every platform, `packages/core/tests/unit/sdk.test.ts`, |
| 1576 | `tests/sdk.spec.ts` and the `request-*` attacks (`tests/attacks.spec.ts`, |
| 1577 | "requests to the bot") through the dev app's mock bot |
| 1578 | (`apps/web/src/mock-bot.ts`), and the Swift, Kotlin and C++ host tests through |
| 1579 | the real engine. The server side (`docs/tgw-format.md`, "The widget's state and |
| 1580 | requests") is being built in parallel; clients wire `onRequest`, `setData` and |
| 1581 | the polling to it once it ships. |
| 1582 |