| sandbox (QuickJS, UNTRUSTED) ──ops / queries / listen / pd / raf / log / diag / bridge / storage──▶ host (trusted) |
| 7 | sandbox ◀── events / timer & frame ticks / query results / viewport / theme / safeArea / visibility ──── host |
| 8 | host ──validated RenderOps / queries / listen / preventDefault / requestFrame / theme / safeArea / policy / frozen / arbitrate──▶ renderer (trusted code, sandboxed iframe) |
| 9 | host ◀── events / query results / size / resize / frame / media / gesture / bubble / limit / violation ──── renderer |
| 10 | ``` |
| 11 |
| 12 | Type definitions live in `packages/core/src/shared/protocol.ts`. Nothing from the sandbox is |
| 13 | forwarded to the renderer without passing through `Validator` |
| 14 | (`packages/core/src/host/validator.ts`); the renderer additionally refuses forbidden tags and |
| 15 | attributes on its own (defense in depth). |
| 16 |
| 17 | This page is protocol 1 (`protocol` in `VERSION.json`). A change that a glue of the previous |
| 18 | release cannot run with (a config field it must send, a host call or message it does not |
| 19 | handle, a change to the validator's API) bumps it in the same commit; an addition the old glue |
| 20 | can ignore does not. Every native bundle carries the number on its first line and the native |
| 21 | glue refuses a bundle of another protocol before it runs (`bundle-mismatch`, |
| 22 | `docs/integration.md` "Pinning a release"). |
| 23 |
| 24 | ## Node ids |
| 25 |
| 26 | - Every node that the sandbox wants rendered gets a **stable integer id** chosen |
| 27 | by the sandbox (`> 1`, `< 2^31`). Id `1` is reserved for the Document and is |
| 28 | only valid as the parent of the `<html>` element. |
| 29 | - An id may be reused only after the host has been told to remove it (`rm`). |
| 30 | Creating an existing id is a protocol violation and the op is dropped. |
| 31 | - The validator keeps its own model (kind, tag, parent, children, rendered or |
| 32 | not) and never trusts anything the sandbox claims beyond the op itself. |
| 33 |
| 34 | ## Sandbox → host: `ops` (mutation batch) |
| 35 |
| 36 | `{ type: 'ops', ops: SandboxOp[] }` — applied in order, at most 10 000 per |
| 37 | batch under `strict` (past it the widget stops), 200 000 under `compat`. The sandbox flushes a batch at the end of every task (event, timer, |
| 38 | frame, script) and *before* every sync query; a long flush goes out in several batches, split between two nodes once |
| 39 | about 1000 ops are buffered (since v0.6.0; its `call` ops, canvases and animations go in its last batch, with the staged |
| 40 | canvas payloads). A host applies them in order, as it always did. |
| 41 |
| 42 | | op | fields | meaning | |
| 43 | |---|---|---| |
| 44 | | `el` | `id, tag, ns?: 'svg', attrs?: {name: value}` | create element (detached) | |
| 45 | | `text` | `id, data` | create text node | |
| 46 | | `comment` | `id, data` | create comment (tracked, never rendered) | |
| 47 | | `attr` | `id, name, value` | set attribute | |
| 48 | | `rattr` | `id, name` | remove attribute | |
| 49 | | `data` | `id, data` | set text/comment data | |
| 50 | | `ins` | `parent, id, before: id \| null` | insert `id` under `parent` before `before` (null = append) | |
| 51 | | `rm` | `id` | remove node and forget its subtree | |
| 52 | | `style` | `id, name, value, important?` | set one inline style property (`value: ''` removes) | |
| 53 | | `prop` | `id, name, value` | set a DOM property: `scrollTop`, `scrollLeft` (profile 1; the form control properties left with the controls) | |
| 54 | | `call` | `id, method, args?` | call a method: `scrollTo scrollBy setPointerCapture releasePointerCapture observeResize unobserveResize` (profile 1: `focus`, `blur`, `select`, `setSelectionRange`, `scrollIntoView`, the dialog and popover methods and `completeEditorCommand` are no-ops in the shim and refused by the validator) | |
| 55 | | `canvas` | `id, cmds: CanvasCmd[]` | replay 2D canvas commands on `<canvas id>` | |
| 56 |
| 57 | ### Canvas commands |
| 58 |
| 59 | `CanvasCmd` is an array `[kind, ...]`: |
| 60 |
| 61 | | kind | shape | meaning | |
| 62 | |---|---|---| |
| 63 | | `c` | `['c', method, ...args]` | call a method from the allowlist (`fillRect`, `arc`, `drawImage`, …) | |
| 64 | | `s` | `['s', prop, value]` | set a state property (`fillStyle`, `font`, …); `filter` is CSS-sanitized and may not contain `url()` | |
| 65 | | `r` | `['r', width, height]` | resize the bitmap (resets state), 0…16384 | |
| 66 | | `g` | `['g', gid, 'linear'\|'radial'\|'conic'\|'pattern', ...args]` | create a gradient / pattern object `gid` | |
| 67 | | `gs` | `['gs', gid, offset, color]` | `addColorStop` | |
| 68 | | `pn` | `['pn', pid, svgPath \| null]` | create a `Path2D` | |
| 69 | | `pc` | `['pc', pid, method, ...args]` | call a path-building method on `Path2D pid` | |
| 70 |
| 71 | Arguments are numbers, short strings, booleans, `null`, flat number arrays, or |
| 72 | object references: `{g: gid}` gradient/pattern, `{p: pid}` Path2D, |
| 73 | `{n: nodeId}` an image source that must be a rendered `canvas`/`img`/`video`, |
| 74 | `{w, h, b64}` an `ImageData`. |
| 75 |
| 76 | ### Features (opt-in wire forms) |
| 77 |
| 78 | `config.features` lists the optional forms a host understands; absent or |
| 79 | empty means plain JSON only, which every host, glue and renderer speaks, so |
| 80 | web, Android and desktop keep working unchanged. The shim uses a form only when |
| 81 | the feature is listed **and** the glue installed the matching function. Each |
| 82 | glue passes on only the features it implements and drops the rest: |
| 83 |
| 84 | | feature | web (`WidgetHostOptions.features`) | Node harness | Swift | Kotlin | C++ | |
| 85 | |---|---|---|---|---|---| |
| 86 | | `webAnimations` | yes | yes | yes | yes | yes | |
| 87 | | `noInPlaceText`, `noAttrFast`, `noCanvasRect` (opt-outs) | yes | yes | yes | yes | yes | |
| 88 | | `canvasWords`, `binaryOps` | no | yes | yes | no | no | |
| 89 | | `morphUpdates` | no | yes | yes | no | no | |
| 90 |
| 91 | The Swift-only forms are performance paths for Telegram macOS; see |
| 92 | `docs/changes.md` for the full list of what stays Swift-only. |
| 93 |
| 94 | ### Web Animations (`webAnimations`) |
| 95 |
| 96 | With `webAnimations` in `config.features`, `Element.animate`, `getAnimations`, |
| 97 | `document.timeline`, `document.getAnimations` and the `Animation`, |
| 98 | `KeyframeEffect`, `AnimationEffect`, `AnimationTimeline`, `DocumentTimeline`, |
| 99 | `AnimationPlaybackEvent`, `CSSAnimation` and `CSSTransition` globals run in the |
| 100 | shim (`packages/core/src/sandbox/waapi.ts`). Timing, events and promises are |
| 101 | computed in the sandbox; the renderer only plays what it is told. Without the |
| 102 | feature `Element.animate` returns a finished stub and reports `unsupported`. |
| 103 | It uses no new host function: the shim sends `__host('anim', json)` after the |
| 104 | tick's ops, and `getAnimations` asks the renderer with the `anims` query. |
| 105 |
| 106 | `anim` is a JSON array of records (max 4096 per batch, 4 MB of JSON): |
| 107 |
| 108 | - `{aid, remove: true}`: the animation left the renderer. |
| 109 | - Script animation: `{aid, target, keyframes: [{offset, easing, composite, values: {css-property: value}}], |
| 110 | timing: {duration, delay, endDelay, iterations (null = infinite), iterationStart, direction, fill, easing}, |
| 111 | composite, iterationComposite, startTime, holdTime, playbackRate}`. `startTime` is on the |
| 112 | sandbox clock (`now`), `holdTime` is a current time while paused or pending; one of them is set. |
| 113 | - CSS animation control: `{aid, target, css: {kind: 'animation'|'transition', name, origin}, startTime, |
| 114 | holdTime, playbackRate, cancelled}`, for a CSS animation the widget paused, seeked or |
| 115 | cancelled; `origin` is the renderer's id from the `anims` answer. |
| 116 |
| 117 | The host validates with `validateAnim` (`validator.ts`; the Swift native node |
| 118 | model has its twin in `NativeAnimValidator.swift`): `target` must be a rendered |
| 119 | element, at most 64 keyframes with sorted offsets in [0, 1] and 64 values each, |
| 120 | times finite and within 24 h, playback rate within ±1000, easings from the CSS |
| 121 | easing grammar, and at most 64 live script animations under `strict`, 1024 under |
| 122 | `compat` (`animation-limit`; a CSS animation or transition the script controls |
| 123 | does not count, in the shim or here). |
| 124 | Every keyframe value goes through the same CSS property sanitizer as |
| 125 | `element.style` (no `url()` other than `#fragment`, no `expression()`), and |
| 126 | `animation-*` / `transition-*` properties are dropped, and so are the keyframe |
| 127 | member names `offset`, `easing`, `composite` and `computed-offset`, so a value |
| 128 | can never override the checked keyframe fields. Rejected records are |
| 129 | reported as `protocol-violation` and a live one becomes a `remove` record. |
| 130 | The renderer gets `{type: 'anim', now, anims}`, where `now` is the sandbox |
| 131 | clock at delivery so it can map `startTime` onto its own timeline. Renderers |
| 132 | keep animation state per widget (`AnimationState` in `renderer/web-animations.ts`; |
| 133 | the shadow-DOM renderer puts many widgets in one page), apply a CSS animation |
| 134 | record only to the animation whose effect target is the record's `target`, and |
| 135 | cancel a script animation whose update throws instead of leaving it running. The |
| 136 | web worker forwards `anim` only when `webAnimations` is enabled. |
| 137 |
| 138 | ### Canvas words (`canvasWords`) |
| 139 |
| 140 | The glue installs `__hostCanvas(key, words: Float64Array, strings: string)` |
| 141 | (captured by the bundle and deleted from the global object like `__host`). |
| 142 | Commands are written into one word buffer per canvas; at flush the `canvas` op |
| 143 | becomes a placeholder `{"op":"canvas","id":N,"bin":K}` in the JSON batch and |
| 144 | payload `K` is handed over first, right before the `ops` call: |
| 145 |
| 146 | ``` |
| 147 | words = commands… , length(string 0) … length(string m-1), m |
| 148 | command = kind, name, ident, argc, (tag, payload)… |
| 149 | kind = 0 c | 1 s | 2 r | 3 g | 4 gs | 5 pn | 6 pc |
| 150 | name = string index (c, s, g, pc) or -1 |
| 151 | ident = gradient/path id (g, gs, pn, pc) or 0 |
| 152 | tag = 0 number | 1 string index | 2 {g:id} | 3 {p:id} | 4 {n:id} |
| 153 | | 5 list (payload = n, followed by n numbers) | 6 null | 7 boolean |
| 154 | strings = the m strings joined, lengths in UTF-16 units |
| 155 | ``` |
| 156 |
| 157 | Command K maps 1:1 onto the JSON command array; non-finite numbers mean JSON |
| 158 | `null`. Anything the words cannot express (`ImageData`, other objects, |
| 159 | ill-formed UTF-16) turns that canvas back into JSON arrays for the frame. At |
| 160 | most 64 payloads per batch, 2 M words and 2 M string units per payload; the |
| 161 | glue validates payloads (the same rules as JSON commands) and drops malformed |
| 162 | ones. A payload key may be referenced **once per batch**: in a binary batch a |
| 163 | second `canvas` op with the same key rejects the whole batch (`BinaryOps` |
| 164 | `canvasKey`), in a JSON batch only the first placeholder is spliced and a |
| 165 | repeated one reaches the validator without commands and is rejected, so one |
| 166 | payload is never expanded or validated twice. The Node harness decodes payloads |
| 167 | back into JSON (`canvasWords: true`, `decodeCanvasWords`); the Swift glue |
| 168 | validates them natively. |
| 169 |
| 170 | ## Host → renderer: `RenderOp` |
| 171 |
| 172 | Same shapes as above, after validation: |
| 173 |
| 174 | - `el` carries `attrs` as `[name, value][]` already filtered, plus |
| 175 | `adopt: 'html' | 'head' | 'body'` the first time each of those appears (the |
| 176 | renderer maps them to its own existing elements instead of creating new ones). |
| 177 | - `css { id, text }` replaces the text of a `<style>` element with the |
| 178 | **sanitized** stylesheet (the sandbox never sends `<style>` text through |
| 179 | `text`/`data` to the renderer; those nodes stay in the host model only). |
| 180 | - `ins` with `parent: 0` detaches a node but keeps it alive (used when a |
| 181 | subtree moves under an unrendered parent). |
| 182 |
| 183 | ### Typed delivery (Swift, in-process renderers) |
| 184 |
| 185 | A native renderer living in the host process may set `acceptsTypedOps` and |
| 186 | receive the same validated batch as `[WidgetOp]` through `send(ops:)` |
| 187 | (`WidgetSandboxProtocol`, a dependency-free target of the Swift package), so |
| 188 | neither side formats or parses JSON. `WidgetOp` has typed kinds for `el`, |
| 189 | `text`, `data`, `ins`, `rm`, `attr`, `rattr`, `style`, `css` and canvas word |
| 190 | batches; every other op stays a generic field map. It is a different encoding |
| 191 | of the same `RenderOp`s, not a protocol change: `WidgetOp.json` renders the |
| 192 | batch back to this document's JSON, and the default `send(ops:)` sends exactly |
| 193 | that as `{type:'ops'}`, so the WebView renderer and every other port are |
| 194 | unaffected. |
| 195 |
| 196 | ### Validation rules (summary — see `allowlist.ts`, `validator.ts`, `css-sanitizer.ts`, `url-policy.ts`) |
| 197 |
| 198 | - The widget profile (`docs/profile-v1.md`, from `packages/core/profile.json`) sets |
| 199 | every list below; what it leaves out is removed with the `profile` diagnostic: |
| 200 | form controls dropped with their subtree, `<form>`/`<dialog>`/`<center>` as |
| 201 | `<div>` and `<ruby>`/`<label>`/the legacy inline elements as `<span>` |
| 202 | (`data-tg-tag` names the original), out-of-profile CSS properties, functions, |
| 203 | units, selectors, at-rules and media queries dropped, `@supports` decided, |
| 204 | nested rules dropped, font families reduced to the generic ones. |
| 205 | - Tags: allowlist of HTML and SVG elements. `script iframe frame frameset |
| 206 | object embed link meta base portal noscript template set applet param track |
| 207 | area map math …` are dropped with their subtrees (tracked in the model so |
| 208 | later ops referring to them are consistent). Unknown elements render as |
| 209 | `<span data-tg-tag="…">`. |
| 210 | - Media: `audio video source track` are dropped with their subtrees, even with |
| 211 | `data:` sources (no codec parser ever sees widget bytes; no autoplay). |
| 212 | - Attributes: every `on*` is dropped; HTML and SVG have their own allowlists. |
| 213 | URL-carrying attributes are allowed only for `img[src]` (with `data:` of a |
| 214 | profile image type: PNG, JPEG, GIF, WebP) and SVG |
| 215 | `use/linearGradient/radialGradient[href]` (fragment only). `a[href]` keeps fragments; any other value becomes |
| 216 | `href="#" data-tg-link` and the real URL stays in the sandbox (`openLink`). |
| 217 | `srcset`, `ping`, `action`, `formaction`, `background`, `data`, `srcdoc`, … |
| 218 | are never forwarded. |
| 219 | - SVG `animate*` and `<set>` are outside the profile and dropped. |
| 220 | - CSS: parsed with css-tree, re-generated from the AST; `@import`, `@namespace`, |
| 221 | `@font-face` (system fonts only: `font-family` can name only installed |
| 222 | fonts) and unknown at-rules dropped; `url()`, `image-set()`, `image()`, |
| 223 | `src()`, `cross-fade()` only with `data:` images or a fragment; |
| 224 | `var()`/`env()`/`attr()` inside URL-taking functions rejected. |
| 225 | - Sizes under `strict`: ≤ 2000 nodes in the document, a text value ≤ 32 K and the document's |
| 226 | text ≤ 48 K UTF-16 units, an attribute ≤ 8 K, a batch ≤ 10 000 ops, a canvas op |
| 227 | ≤ 4000 commands, the document's stylesheets ≤ 400 rules and 32 `@keyframes`, |
| 228 | the widget's canvases ≤ 2048² pixels together (a new canvas 300 × 150, then its |
| 229 | `width` / `height` and the `r` command; the nodes, the document's text, rules and `@keyframes` as they stand after the whole |
| 230 | batch); past one the validator reports the fatal `limit` diagnostic (the reason), refuses |
| 231 | the batch and every later one, and the host stops the widget (`docs/decisions.md`, |
| 232 | "Strict limits from the start"). Under `compat`: text ≤ 2 MB, attribute ≤ 4 MB, |
| 233 | batch ≤ 200 000 ops, canvas ≤ 500 000 commands, no rule or canvas pixel cap |
| 234 | (the renderer refuses a size past 4096² on its own), nothing stops. A `data:` |
| 235 | image of more than 1024² pixels by its bytes (`checkUrl`) becomes the |
| 236 | placeholder under both. |
| 237 |
| 238 | ### `icon:` images (Swift hosts, `WidgetHost.Options.assetResolver`) |
| 239 |
| 240 | A host that knows a built-in icon set passes `assetResolver: (String) -> String?` |
| 241 | (the Telegram app uses the twidget kit's `twa_icon_data_url`). Before validation, |
| 242 | `TrustedValidator` replaces `icon:<name>[?query]` tokens with the resolver's answer: a |
| 243 | whole JSON string value under any key except `data` and `text`, and `url(icon:…)` anywhere, |
| 244 | in JSON batches and in binary op fields alike (`IconExpansion.swift`). The resolver only |
| 245 | sees tokens of the grammar `icon:[A-Za-z0-9_.-]{0,96}(?:\?[A-Za-z0-9=&.%#_-]{0,400})?`; |
| 246 | the prefix is exactly `icon:` (`ICON:` stays a blocked URL), only the CSS function |
| 247 | name `url(` is ASCII case-insensitive. |
| 248 | An answer is used only if it is a `data:image/` URL of at most 64 KB made of |
| 249 | `[A-Za-z0-9-._~,/:=%;+]`, so it can never become a fetchable URL or break out of a |
| 250 | JSON string or a CSS `url()`. A batch expands at most 1024 tokens and 2 MB |
| 251 | (`icon-limit`, once per batch). A widget asks the resolver about at most 256 |
| 252 | distinct tokens and keeps at most 2 MB of its answers; past that, new tokens stay |
| 253 | unresolved (`icon-limit`, once per widget) while the known ones keep expanding. |
| 254 | An answer must also be one of the profile's image types (the validator's `tables.mime`). |
| 255 | The validator never sees the answer: each token goes in as a stand-in, a 2×2 PNG `data:` |
| 256 | URL whose fragment carries a random nonce of this widget and the icon's index |
| 257 | (`#tw<nonce><index>`, about 140 characters), so the strict caps (an attribute 8 K, the |
| 258 | text budget, the image pixels) count what the widget sent, not the host's icon; after |
| 259 | validation `restore` puts the answer back in the validated ops, on the JSON, the binary |
| 260 | and the typed outputs and in stylesheets re-sent on a theme change. A stand-in the widget |
| 261 | writes itself (another nonce, an index it never had) stays the 2×2 image. At most 2 MB of |
| 262 | answers are restored per validated batch (`icon-limit`); past that the rest stay the |
| 263 | stand-in. Without a resolver `icon:` URLs are blocked like every other non-`data:` URL. Widgets can read the answers |
| 264 | back (computed style, canvas), so a resolver hands out public icons only. |
| 265 |
| 266 | ## Sync queries |
| 267 |
| 268 | The sandbox posts `{ type: 'query', query }` and blocks with `Atomics.wait` on |
| 269 | the shared buffer (`SAB_STATE` word: 0 idle, 1 waiting, 2 done). The host |
| 270 | validates the query, relays it to the renderer with a `qid`, writes the |
| 271 | answer (UTF-8 JSON, optional binary payload for `getImageData`) into the buffer, |
| 272 | sets state 2 and `Atomics.notify`s. Timeout: 3 s (answer `{error:'timeout'}`). |
| 273 |
| 274 | | query | answer | |
| 275 | |---|---| |
| 276 | | `rect {id}` | DOMRect JSON | |
| 277 | | `rects {id}` | DOMRect[] | |
| 278 | | `box {id}` | `offsetWidth/Height/Top/Left, offsetParent (id), clientWidth/Height/Top/Left, scrollWidth/Height/Top/Left` | |
| 279 | | `cs {id, pseudo?, prop?}` | all computed properties as `{name: value}`, or one custom property | |
| 280 | | `svg {id, method, args}` | `getBBox`, `getCTM`, `getScreenCTM`, `getComputedTextLength`, `getTotalLength`, `getPointAtLength`, `getSubStringLength`, `getNumberOfChars` | |
| 281 | | `measureText {font, text}` | TextMetrics JSON | |
| 282 | | `imageData {id, x, y, w, h}` | `{width, height}` + binary RGBA | |
| 283 | | `canvasCall {id, method, args}` | `isPointInPath`, `isPointInStroke`, `getTransform`, `getLineDash`, `toDataURL` | |
| 284 | | `elementFromPoint {x, y}` | node id or 0 | |
| 285 | | `validity {id}` | ValidityState JSON + `message` | |
| 286 | | `matchMedia {query}` | `{matches}` — `prefers-color-scheme` is rewritten by the host against the chat theme before the renderer evaluates the query | |
| 287 | | `viewport` | `{innerWidth, innerHeight, dpr}` | |
| 288 | | `anims {id, subtree}` | `{list: [{kind, id, name, index, origin, currentTime, playbackRate, paused, duration, delay, iterations, direction, fill, easing}]}`: running CSS animations and transitions (`webAnimations`) | |
| 289 |
| 290 | Answers are cached in the sandbox until the next flush that sent ops. The |
| 291 | diagnostics panel shows query count, total latency and cache hits. |
| 292 |
| 293 | ## Events (renderer → host → sandbox) |
| 294 |
| 295 | The renderer listens at document level (capture) and forwards an event only if |
| 296 | it is in the profile's list (`tables.events`: taps, pointer and mouse events, |
| 297 | `load`, `error`, `toggle`, the animation and transition events) and the |
| 298 | sandbox declared interest in its type (`listen`) or it is one of |
| 299 | `click load error toggle`. Move-type events are throttled to animation frames. |
| 300 | Keys, focus, input, touch, wheel and scroll events are never forwarded |
| 301 | (profile 1): the renderer cancels the keys' and the context menu's default |
| 302 | actions, never lets the focus into the widget and drops a trusted `click` |
| 303 | without a press (`detail` 0). The engine's own `dblclick` and `contextmenu` |
| 304 | are never forwarded either; since v0.1.2 the renderer sends its own, decided by |
| 305 | the gesture policy (`src/shared/gesture-policy.ts`): `dblclick` after the second |
| 306 | tap's `click`, for every double tap, and `contextmenu` at a hold (or a |
| 307 | right-button press) only when the press's claim gives the widget the hold |
| 308 | (`touch-action: none`). |
| 309 |
| 310 | ```ts |
| 311 | interface WidgetEvent { |
| 312 | type; targetId; relatedId?; |
| 313 | clientX/Y, offsetX/Y, pageX/Y, movementX/Y, button, buttons, detail, |
| 314 | pointerId, pointerType, isPrimary, pressure, |
| 315 | modifiers (bit0 alt, bit1 ctrl, bit2 meta, bit3 shift), |
| 316 | naturalWidth/Height (img load), open (details toggle) |
| 317 | } |
| 318 | ``` |
| 319 |
| 320 | ### `defaultActions` on a click |
| 321 |
| 322 | A native renderer that does not perform a button's default action itself sends |
| 323 | `defaultActions: true` on the `click`, and the shim does it (a submit button |
| 324 | submits its form through `requestSubmit`). The WebView and Shadow DOM |
| 325 | renderers ignore it. (The native editor commands, `editorGeneration` / |
| 326 | `editorCommand` and `completeEditorCommand`, went with `<textarea>` in profile 1.) |
| 327 |
| 328 | ### preventDefault |
| 329 |
| 330 | `preventDefault()` in the sandbox runs after the renderer has already |
| 331 | dispatched the event, so it cannot cancel native defaults. The renderer |
| 332 | cancels navigation and form submission unconditionally. For everything else the |
| 333 | sandbox reports keys `"<targetId>:<type>"` (or `"<id>:keydown:<key>"`) of events |
| 334 | it prevented (`pd` message); the renderer cancels those synchronously from the |
| 335 | next occurrence on ("learned preventDefault"). See `docs/decisions.md`. |
| 336 |
| 337 | ### Touch gestures inside a scrolling host |
| 338 |
| 339 | On every primary `pointerdown` the renderer also posts |
| 340 | `{ type: 'gesture', wants, x, y }` — `x` is true when an ancestor of the target |
| 341 | has a computed `touch-action` that forbids horizontal panning (`none`, `pan-y`, |
| 342 | `pinch-zoom`, …), `y` when one forbids vertical panning (`none`, `pan-x`, …), |
| 343 | both when the sandbox has learned to prevent `pointerdown` / `touchstart` on that |
| 344 | target; `wants` is `y`. (Range inputs and scrollable boxes, which also claimed the gesture, |
| 345 | are outside profile 1.) Every host hands `x` and `y` to the client |
| 346 | (`onGestureClaim`, docs/sdk-v1.md §5.5): the client keeps swipe-to-reply off a |
| 347 | touch the widget takes horizontally and the list still on one it takes |
| 348 | vertically. Hosts whose renderer view sits inside a scrolling container that |
| 349 | cannot see into it also act on `wants` themselves: the Android host denies the |
| 350 | container's touch interception from `ACTION_DOWN` and releases it on |
| 351 | `wants: false` (or after 150 ms without an answer). |
| 352 |
| 353 | Since v0.2.2 the renderer also posts `{ type: 'release' }` when the primary |
| 354 | press ends (`pointerup` or `pointercancel`), whether or not the widget listens: |
| 355 | with the claim at `pointerdown` (its start) the host's haptic gate knows when a |
| 356 | finger is down on the widget and when it was lifted (docs/sdk-v1.md §2.6). Both |
| 357 | are the renderer's own messages from trusted input; nothing the widget does |
| 358 | makes one. |
| 359 |
| 360 | Since v0.1.2 the message is `{ type: 'gesture', wants, x, y, hold }`: the claim |
| 361 | is `claimOf` of the gesture policy over the target's and its ancestors' computed |
| 362 | `touch-action` (a learned `preventDefault` claims both axes), and `hold` is true |
| 363 | only under `touch-action: none`; taps and double taps are always the widget's. The |
| 364 | client drives its recognizers with the policy's `GestureArbiter` (docs/sdk-v1.md |
| 365 | §5.5) and cancels the widget's touch the platform's way when the bubble takes |
| 366 | the press. |
| 367 |
| 368 | Since v0.1.3 vertical drags are always the chat's: `y` and `wants` are always |
| 369 | false, `none` claims `x` and `hold`, `pan-x` claims nothing, a learned |
| 370 | `preventDefault` claims `x`, and every host reports `y` false whatever a |
| 371 | renderer sends (the Blitz and litehtml prototypes, which send only `wants`, now |
| 372 | claim nothing). The claim reads the widget's own `touch-action`: the renderer |
| 373 | core gives the engine each value widened to allow vertical panning (`none` → |
| 374 | `pan-y`, `pan-x` → `pan-x pan-y`, `src/renderer/touch-action.ts`) and keeps the |
| 375 | widget's in the inherited custom property `--tw-touch-action`; its `cs` query |
| 376 | answers `touch-action` with the widget's value. |
| 377 |
| 378 | ### The renderer as the bubble (`arbitrate`, v0.1.2) |
| 379 |
| 380 | A host without recognizers over the widget (the web: `WidgetHost` |
| 381 | `bubbleGestures`) sends `{ type: 'arbitrate', bubble: true, touch?, rtl? }`. |
| 382 | The renderer then acts on the arbiter's verdicts itself: a press the bubble |
| 383 | takes (a hold, a swipe or a scroll over an element that does not claim it, a |
| 384 | right click) ends for the widget with a |
| 385 | `pointercancel` built from the press's last event, nothing more of that pointer |
| 386 | is forwarded (no `pointerup`, no compatibility `mouseup` / `click`), and the |
| 387 | host gets `{ type: 'bubble', action, gesture, x, y, edge }`. `touch`: the |
| 388 | mouse's primary button arbitrates as a finger, and the widget sees |
| 389 | `pointerType: 'touch'` for the press and no click after a drag or a hold, as on |
| 390 | a phone; `rtl`: the leading edge strip is the right one. `{ bubble: false }` |
| 391 | (the default) leaves the presses to the client. |
| 392 |
| 393 | ## Host ⇄ worker envelope |
| 394 |
| 395 | Host → worker: `init {html, sab, config, sandboxBundle}`, `event {ev}`, |
| 396 | `frame {time}`, `viewport`, `resize {entries}`, `theme {theme, themeParams}`, |
| 397 | `safeArea {inset}` (the client's time over the widget, docs/sdk-v1.md §2.17: the shim's `safeArea` dispatch with |
| 398 | `{top, right, bottom, left, cornerLeft, cornerRight}`; not deferred under the CPU quota), |
| 399 | `visibility {visible}`, `bridge {event}` (a change of the widget's state, a request's answer; |
| 400 | see "Bridge calls and storage commits" below). (The profile-0 |
| 401 | `bridge {event, data}` message, host → widget events for `sendMessage`, went |
| 402 | with v1.) |
| 403 |
| 404 | Host → renderer, besides ops and queries: `listen {types}`, `preventDefault |
| 405 | {keys}`, `requestFrame`, `anim {now, anims}` (`webAnimations`), `theme {theme: |
| 406 | {colorScheme, params, button}}` — the renderer core builds the CSS variables of |
| 407 | docs/sdk-v1.md §2.3–§2.4 from it (`themeVariables` in |
| 408 | `packages/core/src/shared/sdk-policy.ts`: names from a fixed list, values |
| 409 | checked against their grammar) and sets them inline and `!important` on the |
| 410 | widget's root, ignoring style ops of the widget that would set those names |
| 411 | there and re-applying them when the widget replaces the root's `style` |
| 412 | attribute — `safeArea {inset}` — the six `--tg-content-safe-area-*` variables |
| 413 | (`contentSafeAreaVariables`, docs/sdk-v1.md §2.17), set and protected the same |
| 414 | way, `0px` until the first one; hosts send it right after `theme` — and `frozen {reason, fatal}` — the runtime is gone |
| 415 | (or paused): the renderer keeps the DOM as it is, cancels the pending frame, |
| 416 | stops forwarding events, sets `data-tw-frozen="fatal"|"paused"` on `<html>` |
| 417 | (`pointer-events: none`, a slight grayscale when fatal) and shows a small badge |
| 418 | with `reason` (a renderer element, never in the widget's node table). The host |
| 419 | sends it from its death path; the iframe / WKWebView / WebView stays on screen |
| 420 | until the owner calls `destroy()`. And `policy {policy, paintReports?}`, the host's |
| 421 | `SandboxConfig.policy`, sent at load right after `safeArea`: under `strict` (also before |
| 422 | it arrives, and for any value but exactly `compat`) the renderer counts heavy boxes |
| 423 | (`packages/core/src/shared/paint-policy.ts`, decisions.md "Heavy boxes"), under `compat` |
| 424 | it counts nothing; `paintReports` (tooling: the Node harness) asks for |
| 425 | `paint {heavy, backdrop}` whenever the counts change, which a host ignores. |
| 426 |
| 427 | Renderer → host, besides events, results and sizes: `limit {code, count}`, past a paint |
| 428 | limit: `paint-limit` with the number of heavy boxes (more than 16: a blurred shadow, a |
| 429 | filter, a backdrop-filter, opacity below 1, or an animation of one of them) or |
| 430 | `backdrop-limit` with the number of boxes with backdrop-filter (more than 2). Once per |
| 431 | widget, and only under `strict`. The renderer has already drawn that frame without the |
| 432 | effects (no blurred shadow layer, filter, backdrop-filter or transparency; animations |
| 433 | paused) and takes no more ops. The host stops the widget like a counted cap: the |
| 434 | diagnostic `paint-limit` / `backdrop-limit` with the reason, then its death path with |
| 435 | `Paint limit exceeded: 17 boxes with shadows, filters or transparency (max 16)` or |
| 436 | `Paint limit exceeded: 3 boxes with backdrop-filter (max 2)` (`paintLimitMessage`); |
| 437 | `compat` ignores it, an unknown code or a count that is no number from 0 is a |
| 438 | `renderer-violation`. A client's own renderer sends the same message through the seam's |
| 439 | `limitExceeded(code, count)` (`Renderer.swift`, `Renderer.kt`, `renderer.h`). |
| 440 |
| 441 | Worker → host (payload untrusted unless noted): `ops`, `query`, `listen |
| 442 | {types}`, `pd {keys}`, `anim {anims, now}` (`now` from the glue), `raf`, `log {level, text}`, `diag {kind, detail}`, |
| 443 | `bridge {method, args}`, `storage {commit}`; trusted glue: `loaded`, `stats`, `dead {reason}`. |
| 444 | Diagnostic kinds added by the runtime limits: `timer-limit` (shim, once), |
| 445 | `timer-limit-enforced` (glue backstop — a shim bug), `cpu-throttled` (glue, at |
| 446 | most once per second). |
| 447 |
| 448 | Inside the worker the QuickJS context has one capability, |
| 449 | `__host(kind: string, arg: string): string | number | undefined`, with kinds |
| 450 | `ops query now timer clearTimer raf log diag listen pd anim bridge storage intl random stat`, |
| 451 | plus `__hostBinary()` to fetch the binary part of the last query answer and, |
| 452 | when the host enabled them, `__hostCanvas` (`canvasWords`) and `__hostOps` |
| 453 | (`binaryOps`). The bundle captures them and the glue deletes all of them from |
| 454 | the global object before widget code runs. QuickJS implements V8's stack-trace |
| 455 | API (`Error.prepareStackTrace`, `CallSite`); before any library code the shim |
| 456 | makes `CallSite.getFunction` (and `getThis`, where present) answer `undefined`, so |
| 457 | no stack frame hands widget code a shim closure. One more function exists only in |
| 458 | Swift debug builds: `__tw3d`, the 3D side channel of the twidget kit |
| 459 | (`Widget3DChannel`, `WidgetHost.Options.sideChannels`), which hands buffers to |
| 460 | a Metal backend past the validator. It is compiled out of release builds |
| 461 | (`DEBUG || TWIDGET_EXPERIMENTAL_3D`); see decisions.md, "3D side channel". |
| 462 |
| 463 | ### User activation for privileged bridge calls |
| 464 |
| 465 | The `bridge` methods `openLink` and `openTelegramLink` (also what the shim |
| 466 | makes of `<a href>` taps and `window.open`) and `copyText` are |
| 467 | privileged (`PRIVILEGED_METHODS` in `sdk-policy.ts`; `ready` and `haptic` are |
| 468 | not): the glue forwards one only while the task of a trusted user gesture runs |
| 469 | on a visible widget, and one gesture unlocks one call. A `request` shares the |
| 470 | same gesture through its own gate: it looks at the task's gesture without |
| 471 | consuming it, and consumes it only when the request goes out as the tap's |
| 472 | (`foreground`); without a gesture it may go out as a background request where |
| 473 | the server's flags allow them (below). A gesture is one physical pointer press (`pointerdown`, |
| 474 | `mousedown`, `pointerup`, `mouseup`, `click`, `dblclick` of the same press). |
| 475 | A finger's or a pen's press is one from its `pointerup` on: its `pointerdown` may still |
| 476 | become the chat's scroll (it then ends in `pointercancel`), so the renderer does not mark |
| 477 | it `trusted` (HTML's activation-triggering input events; a mouse's press counts from its |
| 478 | `pointerdown`); nor is a mouse event of a finger or a pen still down (the `mousedown` a pen's |
| 479 | contact makes at once, its barrel button with the tip down). Neither is a release of a press begun |
| 480 | outside the widget `trusted`. Every host starts a new gesture at the renderer's `gesture` claim, |
| 481 | sent for every primary press before its events, and at every `pointerdown` event, trusted or not. |
| 482 | Keys are never gestures: widgets get no keyboard. A `click` or `dblclick` |
| 483 | starts a gesture only with a click count (`detail` ≥ 1); the click that Enter |
| 484 | or Space on a focused control produces has `detail` 0 and counts only as the |
| 485 | end of a pointer press already open. Only renderer `event` messages with |
| 486 | `trusted: true` count, on every host: the WebView/iframe renderer sets it from |
| 487 | the DOM event's `isTrusted`, and a renderer without a script-driven document |
| 488 | (Blitz, litehtml) sets it on every input event; a renderer behind the |
| 489 | `Renderer` seam that leaves it out gets no gestures. The host numbers gestures |
| 490 | and hands them to the engine with the event. Calls from timers, frames, |
| 491 | promises after the task, scripted `click()`/`dispatchEvent` or a hidden widget |
| 492 | are dropped with an `activation-blocked` diag (at most 20). On the web the |
| 493 | main-thread host decides: the host's `event` to the worker carries `gesture: n` |
| 494 | for trusted gestures, the worker tags `bridge` messages made in that task with |
| 495 | `gesture`, and the host accepts each issued gesture once, within 5 s. Native |
| 496 | glue gates in the engine (`activationEvent(json, gesture)`). See decisions.md, |
| 497 | "User activation". |
| 498 |
| 499 | ### Bridge calls and storage commits (SDK v1) |
| 500 |
| 501 | `__host('bridge', JSON [method, args])`: `ready []`, `openLink [url]`, |
| 502 | `openTelegramLink [url]`, `haptic ['impact', style] | ['notification', type] | |
| 503 | ['selection']`, `setResizeAnchor ['top' | 'bottom']` (v0.1.3: not privileged, |
| 504 | not an action; the host keeps the latest edge and reports it with the height, |
| 505 | and the shim sends only changes), `watchPublicData [on]` (one boolean; not |
| 506 | privileged, not an action, refused in a preview: the host keeps the latest value |
| 507 | and reports a change, the shim sends only changes), `request [id, data]` and |
| 508 | `copyText [text]` (the widget's state and requests). Every glue checks, in order: the method and its arguments |
| 509 | (`checkBridgeCall`: anything else is dropped with `bridge-rejected`, at most 20; |
| 510 | `request` takes an integer id 1–2147483647 and 1–64 bytes of UTF-8, `copyText` |
| 511 | 1–256 UTF-16 code units, neither a lone surrogate), the request gate for |
| 512 | `request` (below), user activation for the two link methods and `copyText` |
| 513 | (above), the haptic gate for `haptic` (visible, a bucket of 5 refilled at 10 per |
| 514 | second; `haptic-limit` at most once per second). What passes reaches the client |
| 515 | as a `WidgetAction` (`onAction`) with the URL normalised; the deprecated |
| 516 | `onBridge` still gets the raw method and arguments. `copyText` goes to |
| 517 | `onCopyText(text)` and `request` to `onRequest({data, background})`, neither to |
| 518 | `onAction` / `onBridge`. |
| 519 |
| 520 | **Requests and the widget's state (docs/sdk-v1.md §2.13–§2.14).** The request gate |
| 521 | (`RequestGate`) reads only the server's flags the host passes in its context: |
| 522 | no `canQuery` → `disabled`; one in flight → `busy`; an unconsumed gesture on a |
| 523 | visible widget → `foreground` (consumed; `compat` counts every call as |
| 524 | pressed); no `backgroundQuery` → `no-activation`; hidden → `hidden`; under 5 s |
| 525 | since the last background request → `rate-limited`; else `background`; the host |
| 526 | calls the gate's `show` when the widget becomes visible (its next background |
| 527 | request may go out at once). Refusals are reported as `request-blocked` (at |
| 528 | most 20) and go back at once. An accepted request goes to the client as |
| 529 | `{data}`; a client without `onRequest` then refuses it (`unsupported`). The host |
| 530 | → sandbox `bridge` dispatch (a task of kind `bridge`, deferred under the CPU |
| 531 | quota like `theme`, order kept) carries: |
| 532 |
| 533 | - `{type: 'data', chatData, publicData}`: the full state, the chat state and |
| 534 | the shared state, after a change (the client's `setData`: the server's update, |
| 535 | or a polled shared state); |
| 536 | the shim fires `chatDataChanged`, then `publicDataChanged`, for each that |
| 537 | differs, in that task; |
| 538 | - `{type: 'answer', id, result}`: the bot's result (an answer carries no state); |
| 539 | - `{type: 'answer', id, error, reason?}`: `error` one of `NOT_ALLOWED`, `BUSY`, |
| 540 | `RATE_LIMITED` (refusals; `reason` = the gate's verdict or `unsupported`, for |
| 541 | the error's message), `TIMEOUT`, `RATE_LIMITED`, `FAILED` (the client's |
| 542 | failures) and `INVALID_ANSWER` (the answer's `result` over 1024 bytes or not |
| 543 | text: `answer-rejected`). |
| 544 |
| 545 | Every string coming in is checked again in the glue, as the server checks its |
| 546 | text fields: the chat state (`chatData`), the shared state (`publicData`) and |
| 547 | `result` are each a text of up to 1024 bytes (UTF-8) without a NUL; a state that |
| 548 | fails is `null` (`data-rejected`), a copy's `chatData` is dropped. Request ids are the shim's; an answer to an id the |
| 549 | shim is not waiting for is ignored. |
| 550 |
| 551 | `__host('storage', JSON {local?, session?})`: the full areas of Web Storage a |
| 552 | task changed, sent once at the end of that task. The glue checks the commit |
| 553 | whole (only those two keys, objects of strings, 4096 bytes of UTF-8 per area; |
| 554 | an argument longer than 2 × 12 × 4096 + 64 characters is refused unparsed) and |
| 555 | hands each area to the client (`onStorageCommit(area, values)`), or drops it with |
| 556 | `storage-rejected` (at most 20). |
| 557 |
| 558 | The rules live in one policy with four copies, `packages/core/src/shared/sdk-policy.ts`, |
| 559 | `SdkPolicy.swift`, `SdkPolicy.kt` and `sdk_policy.cpp`, checked against one fixture, |
| 560 | `packages/core/tests/fixtures/sdk-policy.json`. The widget-facing side and the |
| 561 | client's duties are in docs/sdk-v1.md. |
| 562 |
| 563 | ### `config` (SandboxConfig, same fields on iOS and Android) |
| 564 |
| 565 | | field | default | meaning | |
| 566 | |---|---|---| |
| 567 | | `memoryLimitBytes` | 8 MB | QuickJS heap limit; exceeding it kills the runtime | |
| 568 | | `cpuLimitMs` | 500 | longest continuous run of widget JS in one task (interrupt handler); exceeding it kills | |
| 569 | | `cpuQuotaMs` / `cpuQuotaWindowMs` | 300 / 1000 | JS time the widget may spend per sliding window (ten buckets); on the native hosts also the validator's CPU time for its messages (`stats.validatorMs`); beyond it timers, frames, resize/viewport/theme/bridge tasks are **deferred**, never killed; events always run with at least 50 ms | |
| 570 | | `cpuKillAfterMs` | 0 (off) | kill once throttling has lasted this long without a gap longer than one window | |
| 571 | | `mainThreadQuotaMs` | 100 | the host's main-thread work for the widget per `cpuQuotaWindowMs`: the wall time its layout queries block the renderer plus 25 µs per op and 2 µs per canvas command the glue forwards (`opsCostMs`); beyond it the same tasks are deferred, apart from the JS quota (which counts JS time only) | |
| 572 | | `maxTimers` | 64 | live `setTimeout` + `setInterval` slots; the shim throws `RangeError` past it, the glue refuses as a backstop; timer delays are clamped to 24 h | |
| 573 | | `visible` | true | initial visibility (see `visibility` below) | |
| 574 | | `policy` | `strict` | `strict`: privileged bridge calls need a user gesture, the counted caps above stop the widget (text values 32 K, document text 48 K, attributes 8 K, 10 000 ops per batch, 10 000 canvas commands per op, 400 CSS rules / 32 `@keyframes`, 2048² canvas pixels together), the shim caps canvas commands per canvas and task (10 000, `RangeError`) and script animations (64), visible text is budgeted (text nodes, visible and `data-*` / `aria-*` attributes, strings in CSS), `attr()` reads only budgeted attributes. `compat`: the limits before that hardening, for tests and tooling. Anything but exactly `compat` is `strict` | |
| 575 | | `features` | `[]` | opt-in wire forms (see "Features"); each glue drops the ones it does not implement | |
| 576 | | `viewport`, `theme` | | as before | |
| 577 | | `themeParams` | `{}` | the chat's palette, `#rrggbb` per Mini Apps key (docs/sdk-v1.md §2.3), checked by the glue; missing keys take the scheme's defaults in the shim | |
| 578 | | `locale` | `en-US` | the client's UI language (BCP 47, ≤ 35 characters), checked by the glue: `navigator.language` and the Intl default | |
| 579 | | `contentSafeArea` | all 0 | the client's time over a widget with no caption below it (docs/sdk-v1.md §2.17), CSS px `{top, right, bottom, left, cornerLeft, cornerRight}`; the shim checks it (an inset 0–64, a corner 0–200, else 0): `TelegramWidget.contentSafeAreaInset` | |
| 580 | | `profile` | 1 | the widget profile the glue enforces (`VERSION.json`'s `profile`); the shim reports `profile-mismatch` when its bundle's differs | |
| 581 | | `storage` | `{}` | the client's Web Storage preload `{local?, session?}`, checked by the glue (4096 bytes of UTF-8 per area; over it: `storage-rejected`, empty) | |
| 582 | | `chatData`, `publicData` | `null` | the chat state and the shared state, which only the bot writes, checked by the glue (text of 1–1024 bytes of UTF-8 without a NUL, else `null` and `data-rejected`); a copy's `chatData` is `null` | |
| 583 | | `isCopy` | `false` | a forwarded copy (the server's `is_copy`; the widget's `isForward`) | |
| 584 | | `canQuery` | `false` | the server's `can_query`: the shim refuses a request at once without it | |
| 585 | | `chatType` | `null` | `private`, `group`, `supergroup` or `channel`; `null` in every copy (`isCopy`) and in a preview | |
| 586 | | `viewer` | `null` | `{id, first_name?, last_name?, username?, is_premium?}` (`WebAppUser`): an id of 1 to 2^53 − 1, names of 1–64 UTF-16 code units, a username of 5–32 of `[A-Za-z0-9_]`, `is_premium` only when true; `null` without `canQuery` (and so in a preview) | |
| 587 |
| 588 | The policy that counts and decides lives in trusted glue only: |
| 589 | `packages/core/src/host/cpu-budget.ts`, `ios/.../CpuBudget.swift`, `android/.../CpuBudget.kt` |
| 590 | (one fixture, `packages/core/tests/fixtures/cpu-budget.json`). The shim gets `maxTimers` |
| 591 | through `boot` and the visibility signal; it enforces nothing the host relies |
| 592 | on. Before each task the glue asks `decide(kind, now)`: `{run, sliceMs}` sets |
| 593 | the interrupt deadline (always `cpuLimitMs`: what a task spends past the quota |
| 594 | is a debt of at most one more quota, `record(kind, cpuMs, now)` after the task), |
| 595 | `{run: false, retryAt}` puts the task in the deferred |
| 596 | queue (frames collapse into one, one fire per timer id, order kept) and a |
| 597 | single wake-up timer. A task that overruns its slice is reported as |
| 598 | `CPU limit exceeded: more than N ms of continuous execution (…)`. On the native |
| 599 | hosts the validator measures its thread's CPU time per call for the widget's |
| 600 | messages (ops, queries, `listen`, `preventDefault`, anim) and the engine records |
| 601 | it the same way when it arrives, `record('validator', ms, now)` |
| 602 | (`SandboxEngine.chargeValidator`; docs/decisions.md, "The validator's time |
| 603 | counts"); the web, which validates on its main thread in V8, leaves it to the |
| 604 | main-thread window. Diagnostics: `cpu-throttled` at most once per second; |
| 605 | `stats.throttledTasks`, `stats.cpuWindowMs` (the window plus the debt, the |
| 606 | validator's records included), `stats.validatorMs` (the validator's time charged |
| 607 | so far; native hosts). |
| 608 |
| 609 | ### `visibility {visible}` |
| 610 |
| 611 | The host knows whether the bubble is on screen (`WidgetHost.setVisible`); the |
| 612 | sandbox does not. Hidden: the glue requests no frames from the renderer (one |
| 613 | is requested on return if the shim asked meanwhile; a frame already in flight |
| 614 | is dropped), timers fire at most once per second (new timers are armed with |
| 615 | `max(delay, 1000)`, due ones are batched into one wake-up; intervals do not |
| 616 | accumulate missed ticks), events pass through as usual. The shim receives |
| 617 | `visibility` through `__twDispatch` and flips `document.hidden` / |
| 618 | `document.visibilityState` and dispatches `visibilitychange` on the document, |
| 619 | like a background tab (no `pagehide`/`pageshow`). |
| 620 |
| 621 | ### `morph {html}` (`morphUpdates`) |
| 622 |
| 623 | In-place document update, opt-in through the `morphUpdates` feature (it must be in |
| 624 | both the host's `config.features` and the engine's runtime features). The shim parses |
| 625 | `html` like `boot` does and patches the live DOM to match it: element children are |
| 626 | matched by `id`, then by tag in order; attributes (`class`, `style` included) and text |
| 627 | are updated in place, unmatched nodes are inserted or removed. Node identity is kept, |
| 628 | so CSS transitions run from the old values. Scripts in `html` are inert and existing |
| 629 | scripts are left alone; elements with `data-morph-keep` keep their children (content |
| 630 | the widget built itself). The changes leave the sandbox as an ordinary `ops` batch |
| 631 | and are validated like any other. Afterwards `widgetupdate` fires on `document`. |
| 632 | The dispatch returns `'1'` when applied; hosts fall back to a fresh boot otherwise |
| 633 | (Swift: `WidgetBubble.morph(html:completion:)`, `WidgetHost.morph`, `SandboxEngine.morph`). |
| 634 |
| 635 | ## Shared buffer layout |
| 636 |
| 637 | ``` |
| 638 | Int32[0] state (0 idle, 1 waiting, 2 done) ← Atomics.wait / notify |
| 639 | Int32[1] json byte length |
| 640 | Int32[2] binary byte length |
| 641 | Int32[3] reserved |
| 642 | bytes[16…] json, then binary (16 MB total) |
| 643 | ``` |
| 644 |
| 645 | ## Mapping to MCP Apps later |
| 646 |
| 647 | The bridge (`TelegramWidget.*` → `bridge` messages, docs/sdk-v1.md §3) is a thin method/args |
| 648 | envelope; wrapping it as JSON-RPC 2.0 over the same channel (`ui/initialize`, |
| 649 | `ui/notifications/*`, `tools/call`) is a renaming exercise — the sandbox |
| 650 | already cannot reach `postMessage` directly, so the host would be the JSON-RPC |
| 651 | endpoint. |
| 652 |