| 7 |
| 8 | ### QuickJS: `quickjs-emscripten-core` + `@jitl/quickjs-ng-wasmfile-release-sync` |
| 9 |
| 10 | - The **quickjs-ng sync variant** works in a dedicated Worker. Host functions |
| 11 | (`vm.newFunction`) may block the worker thread with `Atomics.wait` — that is |
| 12 | how the sync query bridge works (see `packages/core/src/host/worker.ts`). The asyncify |
| 13 | variant was not needed and is ~2× slower. |
| 14 | - `setInterruptHandler` fires often enough to kill `for(;;){}` within a few ms |
| 15 | of the deadline. `setMemoryLimit(64 MB)` alone is **not** a memory limit in |
| 16 | this build (see "The memory limit is the wasm memory's maximum" below): the |
| 17 | worker also hands the module a `WebAssembly.Memory` whose `maximum` is |
| 18 | 16 MB + the limit. Allocation failures then throw `InternalError: out of |
| 19 | memory`, which the worker turns into a clear UI error when uncaught. |
| 20 | - `evalCode(..., { compileOnly: true })` returns a bytecode handle, but |
| 21 | `encodeBinaryJSON` cannot serialize function bytecode in this build |
| 22 | ("Couldn't allocate memory to get ArrayBuffer"). **Bytecode caching of |
| 23 | bundled libraries is therefore done differently**: the library source is |
| 24 | fetched once per worker (sync XHR of a same-origin file) and kept as a string; |
| 25 | QuickJS compiles ~200 KB of minified Chart.js in well under 100 ms, so the |
| 26 | cost is acceptable for the prototype. A native port would use |
| 27 | `JS_WriteObject`/`JS_ReadObject` directly (see `native-port-notes.md`). |
| 28 | - The runtime has **no module loader** installed, so `import()` and static |
| 29 | `import` of anything fail inside the sandbox — this is the intended behaviour |
| 30 | for invariant 5. |
| 31 | - quickjs-ng has no `Intl`. Rather than shipping ICU into the sandbox, `Intl` |
| 32 | and the `toLocale*` methods are **delegated to the host** through the single |
| 33 | `__host('intl', …)` capability (pure formatting, no I/O). |
| 34 |
| 35 | ### DOM library: linkedom (+ parse5 for parsing) |
| 36 |
| 37 | linkedom runs inside QuickJS after two adjustments: |
| 38 |
| 39 | - it needs `atob`/`btoa` at module-evaluation time (`packages/core/src/sandbox/prelude.ts`); |
| 40 | - its optional `canvas` dependency is aliased to a stub; `<canvas>` is served by |
| 41 | our recording proxy instead. |
| 42 |
| 43 | Known linkedom gaps that the shim fills (`packages/core/src/sandbox/*`): |
| 44 |
| 45 | | Gap | Shim | |
| 46 | |---|---| |
| 47 | | HTML parsing differs from browsers (no implied `<tbody>`, `<head>`/`<body>` for fragments, SVG attribute casing) | **parse5** parses; linkedom only holds the tree (`dom.ts`) | |
| 48 | | `EventTarget` has no capture phase and no `on*` attribute handlers | own event system (`events.ts`) | |
| 49 | | `MutationObserver` misses text nodes, style writes and several insertion paths | own observer on top of the reconciliation pass (`capture.ts`) | |
| 50 | | `element.style` splits on `;` (breaks `data:` URLs) | own `CSSStyleDeclaration` (`style.ts`) | |
| 51 | | no layout, no `getBoundingClientRect`, `offsetWidth`, `getBBox`, … | sync queries to the renderer (`layout.ts`) | |
| 52 | | no form control state (`value`, `checked`, `selectedIndex`), tables API | `forms.ts` | |
| 53 | | doctype node is not linked to `<html>` through `nextSibling` | the document's children are taken from `documentElement` | |
| 54 |
| 55 | Alternatives considered: **jsdom** (far too heavy, depends on Node APIs), |
| 56 | **happy-dom** (also Node-oriented, larger, slower to boot in QuickJS), |
| 57 | **remote-dom** (Shopify; would have required rewriting widgets against a |
| 58 | custom element model instead of running them unchanged). linkedom boots in |
| 59 | ~0.5 s (QuickJS, unminified eval of a 500 KB bundle) which is acceptable for a |
| 60 | prototype; bytecode would cut this on native. |
| 61 |
| 62 | ### Mutation capture: reconciliation, not MutationObserver |
| 63 |
| 64 | The shim does not rely on linkedom's MutationObserver. DOM mutators are wrapped |
| 65 | only to mark nodes dirty; at the end of every task the dirty nodes are |
| 66 | re-read and diffed against a mirror of what the host already knows. This is |
| 67 | correct regardless of which internal path linkedom used to mutate the tree, |
| 68 | and a periodic full walk (every 500 ms) catches anything unwrapped — such |
| 69 | misses are counted in the diagnostics (`missed mutations`). |
| 70 |
| 71 | ### Cross-origin isolation and the sandboxed `srcdoc` iframe |
| 72 |
| 73 | `COOP: same-origin` + `COEP: require-corp` on the dev server makes |
| 74 | `crossOriginIsolated === true` and `SharedArrayBuffer` available. A |
| 75 | `<iframe sandbox="allow-scripts" srcdoc=…>` **does** load and run under COEP |
| 76 | (an opaque-origin srcdoc document is same-site for embedding purposes), and the |
| 77 | renderer bundle, images (`data:`) and fonts all work there. |
| 78 |
| 79 | ### Reference mode under cross-origin isolation |
| 80 |
| 81 | A nested document loaded into a COEP `require-corp` page must itself carry |
| 82 | `Cross-Origin-Embedder-Policy` (and CORP) headers, otherwise Chrome blocks it |
| 83 | with `ERR_BLOCKED_BY_RESPONSE`. Responses ended by the dev-server middleware |
| 84 | bypass Vite's `server.headers`, so the middleware sets the isolation headers |
| 85 | itself. (The product path — `srcdoc` — never hits this.) |
| 86 |
| 87 | ### Fragments always render in standards mode |
| 88 |
| 89 | A bare fragment (no `<!DOCTYPE html>`) is rendered in the renderer's own |
| 90 | document, which has a doctype, so it is laid out in standards mode. A browser |
| 91 | opening the same file directly would use quirks mode (different inline line |
| 92 | boxes: a 1–2 px drift that showed up as a 2 % pixel diff). Reference mode |
| 93 | therefore prepends a doctype to doctype-less files — the comparison target is |
| 94 | "the widget inside our document", not "the file opened as a page". Full |
| 95 | documents are untouched. |
| 96 |
| 97 | ### Shadow DOM renderer: the renderer core without the frame |
| 98 |
| 99 | Since 2026-10-16 this is the web product renderer (decision D2; see "The web |
| 100 | renders through Shadow DOM; invariant 6 reworded" below). Until then the web |
| 101 | product path was the sandboxed `srcdoc` iframe, but a feed of |
| 102 | hundreds of bubbles pays per bubble for a document: asynchronous boot, a |
| 103 | style context, nothing buildable before insertion. The renderer code was |
| 104 | therefore split into `packages/core/src/renderer/core.ts` (`createRenderer(env)`, one |
| 105 | instance per widget, an environment abstracting document vs shadow root) and |
| 106 | the transport entry `packages/core/src/renderer/renderer.ts`; `ShadowDomRenderer` |
| 107 | (`packages/core/src/host/shadow-renderer.ts`) runs the same core on an open shadow root in |
| 108 | the host page with real `<html>/<head>/<body>` elements inside, `:host { all: |
| 109 | initial; contain: layout paint style; container-type: inline-size }`, and the |
| 110 | validator in `scope: 'shadow'` (host-reaching selectors dropped, `:root` → |
| 111 | `[data-tw-root]`, size media queries → `@container tw`, viewport units → |
| 112 | container units). This relaxes invariant 6 (no opaque origin, no per-widget |
| 113 | CSP): the attack suite on `TW_RENDERER=shadow` measures exactly what the frame |
| 114 | used to add, and the decision is made on its result plus the feed bench |
| 115 | (`docs/shadow-dom-renderer.md`). Native platforms keep their WebView documents |
| 116 | (`scope: 'document'`, the default). |
| 117 |
| 118 | ### Renderer iframe: `allow-scripts allow-forms` |
| 119 |
| 120 | Without `allow-forms`, Chrome blocks a form submission *before* dispatching the |
| 121 | `submit` event ("Blocked form submission … 'allow-forms' permission is not |
| 122 | set"), so widgets never see `submit` and implicit submission (Enter in a text |
| 123 | field) stops working. `allow-forms` is therefore set. Navigation through a form |
| 124 | is still impossible three times over: the renderer calls `preventDefault()` on |
| 125 | every `submit` unconditionally, the CSP has `form-action 'none'`, and the |
| 126 | `action`/`formaction` attributes never reach the renderer (so the only possible |
| 127 | target would be the frame's own `about:srcdoc`). `allow-popups`, |
| 128 | `allow-top-navigation*`, `allow-same-origin` and `allow-modals` stay off. |
| 129 |
| 130 | ### The host owns the colour scheme |
| 131 |
| 132 | Setting `color-scheme` on the iframe element does **not** change |
| 133 | `prefers-color-scheme` inside a sandboxed `srcdoc` frame in Chromium 153 |
| 134 | (verified with a probe), and in the product the chat theme is the app's |
| 135 | choice anyway, not the OS setting. So the host is authoritative: the CSS |
| 136 | sanitizer evaluates `@media (prefers-color-scheme: …)` against the host |
| 137 | theme (rewriting the feature to an always-true/always-false width query), |
| 138 | resolves `color-scheme: light dark` to the current scheme and picks the branch |
| 139 | of `light-dark()`; the validator re-emits every stylesheet when the theme |
| 140 | changes; `matchMedia('(prefers-color-scheme: …)')` queries are rewritten the |
| 141 | same way before they reach the renderer; and the sandbox receives a `theme` |
| 142 | event for `TelegramWidget.onTheme`. Known gap: `light-dark()` inside a `style` |
| 143 | attribute is resolved once, when the attribute is set. |
| 144 |
| 145 | ### Renderer ↔ host communication |
| 146 |
| 147 | A `MessageChannel` port is handed to the renderer with a single |
| 148 | `postMessage` after it announces itself; the renderer checks `e.source === |
| 149 | window.parent` and ignores everything else. All later traffic goes through the |
| 150 | private port, so other scripts on the host page cannot inject ops. |
| 151 |
| 152 | ### Why plain JSON for ops |
| 153 |
| 154 | The protocol is JSON so that it can be validated with a strict schema on every |
| 155 | platform and logged/replayed in tests. Binary encodings would be faster but |
| 156 | are a production concern (non-goal). |
| 157 |
| 158 | ### Stack |
| 159 |
| 160 | | Dependency | Why | |
| 161 | |---|---| |
| 162 | | `quickjs-emscripten-core`, `@jitl/quickjs-ng-wasmfile-release-sync` | the sandbox engine; the prompt asked for quickjs-ng sync | |
| 163 | | `linkedom` | in-sandbox DOM (see above) | |
| 164 | | `parse5` | spec-compliant HTML parsing in the sandbox; also used by linkedom's competitors; small | |
| 165 | | `css-tree` | real CSS parser for the sanitizer (no regex-only sanitizing) | |
| 166 | | `chart.js`, `d3` | the bundled libraries the loader rewrites CDN URLs to | |
| 167 | | `vite`, `esbuild` | dev server with COOP/COEP; esbuild builds the in-sandbox and renderer IIFE bundles | |
| 168 | | `@playwright/test`, `pixelmatch`, `pngjs` | attack suite and screenshot diffing | |
| 169 | | `ws` | canary WebSocket server | |
| 170 | | `tsx` | runs the Node harness / scripts without a build step | |
| 171 |
| 172 | ## Shim lessons from the compat suite |
| 173 |
| 174 | Each of these was found by a failing compat scenario and fixed generally in |
| 175 | the shim (never per widget): |
| 176 |
| 177 | - **`window`, `self`, `top`, `parent`, `frames` must be writable.** They are |
| 178 | `[Replaceable]` in browsers; a top-level `var frames = 0` silently kept the |
| 179 | window object when the alias was read-only, and the widget's counter became |
| 180 | `NaN`. |
| 181 | - **`submit` needs `allow-forms`** on the sandboxed frame (see above); without |
| 182 | it the event is never dispatched, which looked like "the handler never ran". |
| 183 | - **Parsing must match the browser's tree.** linkedom's own parser does not |
| 184 | insert `<tbody>`, puts fragment-level `<style>` in the wrong place and keeps |
| 185 | SVG attribute casing differently; parse5 removed a whole class of layout |
| 186 | diffs. |
| 187 | - **Doctype-less fragments** are standards-mode in the product; reference mode |
| 188 | normalizes them the same way (see "Fragments always render in standards |
| 189 | mode"). |
| 190 | - **`:checked` / `:focus` must reflect live state.** css-select (linkedom's |
| 191 | selector engine) resolves `:checked` from the `checked` *attribute*, and its |
| 192 | built-in string aliases take precedence over user-supplied pseudo functions, |
| 193 | so overriding by name is impossible. The build redirects linkedom's |
| 194 | `import 'css-select'` to `packages/core/src/sandbox/css-select-shim.ts`, which rewrites |
| 195 | `:checked` → `:tw-checked` (outside quoted strings) and registers |
| 196 | state-backed predicates under the rewritten names. A quiz widget scored 0/3 |
| 197 | before this. |
| 198 | - **Scripts inserted by fragment parsing are inert.** Browsers never run a |
| 199 | `<script>` that arrives through `innerHTML`, `outerHTML` or |
| 200 | `insertAdjacentHTML`; the shim initially queued them, so a widget doing |
| 201 | `document.body.innerHTML += …` re-created and re-ran itself until the |
| 202 | document had ~100 000 elements (found by `corpus/attacks/api-innerhtml.html`, |
| 203 | which also exposed that the dev UI re-rendered its diagnostics panel per |
| 204 | rejected op and froze; panel rendering is now coalesced per frame). The |
| 205 | validator's 50 000-node cap and the 64 MB memory limit were the only things |
| 206 | bounding it before. |
| 207 | - **Animated widgets need deterministic hit targets for the harness**, not for |
| 208 | the sandbox: a counter next to a button made the button "unstable" for |
| 209 | Playwright in both modes. The corpus widget got a fixed-width counter; the |
| 210 | harness parks the mouse before each run so hover state cannot leak between |
| 211 | layouts. |
| 212 |
| 213 | ## iOS implementation (`ios/`) |
| 214 |
| 215 | - **quickjs-ng v0.17.0 vendored as a C target** (4 source files + headers, |
| 216 | MIT) behind a 40-line C shim that hides `JSValue` macros and inline helpers |
| 217 | from Swift. Chosen over JavaScriptCore because JSC has no public interrupt / |
| 218 | memory-limit API and the design calls for one engine, one shim, one protocol |
| 219 | on every platform. |
| 220 | - **The validator is not ported to Swift** — the same `validator.ts` (with |
| 221 | css-tree) is bundled (`validator-bundle.js`, built for the browser platform |
| 222 | so css-tree's prebuilt data modules are used) and runs in a *second, trusted* |
| 223 | QuickJS runtime. One implementation to audit; the cost is a JSON round trip |
| 224 | per batch. |
| 225 | - **Renderer bundle is shared** with the web host; only the transport differs |
| 226 | (`__TW_TRANSPORT__` define: MessagePort vs `WKScriptMessageHandler` + |
| 227 | `evaluateJavaScript`). Binary query results travel as base64. |
| 228 | - **Each widget gets its own origin**: the renderer document is served from |
| 229 | `tgwidget://w-<uuid>/` by a `WKURLSchemeHandler` that refuses every other |
| 230 | URL; CSP comes both as a response header and a `<meta>`. |
| 231 | - **Found while writing the Swift tests**: the validator forwarded a |
| 232 | `<style>` element's raw text as a *detached* text node to the renderer. Not |
| 233 | a leak (never in the DOM), but it now emits `rm` for it so only the sanitized |
| 234 | `css` op is ever shipped. |
| 235 | - **Found only on the simulator** (at the time the WKWebView path was |
| 236 | UIKit-only, so the macOS `swift test` run could not see them): |
| 237 | - `WKURLSchemeHandler` / script message handlers must be registered on the |
| 238 | configuration *before* `WKWebView` is created — the view copies its |
| 239 | configuration, and a handler added afterwards is silently ignored (the |
| 240 | document failed with `NSURLErrorUnsupportedURL`, so the engine never |
| 241 | received `ready` and sat at "loading" forever). |
| 242 | - codesign refuses an iOS bundle with a top-level `Resources/` directory |
| 243 | ("bundle format unrecognized"), so the package's resource directory is |
| 244 | `WidgetJS/`. |
| 245 | - The renderer reports its `size` before `ready`; the engine therefore |
| 246 | receives input before its QuickJS context exists. Inputs are now buffered |
| 247 | until boot (`pendingBeforeBoot`), mirroring what the web Worker gets for |
| 248 | free from the message queue. Regression test: `inputsBeforeStartAreBuffered`. |
| 249 | - QuickJS measures stack depth from the stack pointer it recorded at |
| 250 | `JS_NewRuntime`. A serial `DispatchQueue` is not a thread: later blocks run |
| 251 | on other pool threads with other stacks, and every call from one of them |
| 252 | failed with a bogus `RangeError: Maximum call stack size exceeded` (seen |
| 253 | when the Dark toggle fired after d3 had loaded). Pinning the limit under the |
| 254 | 512 KB GCD stack was not an option either: a debug build of quickjs-ng |
| 255 | spends ~10 KB of C stack per JS call, which gave 40 levels — css-tree in the |
| 256 | validator already failed at that. **Each runtime is now pinned to its own |
| 257 | `JSThread`** (a `Thread` with an 8 MB stack and a run loop; the QuickJS limit |
| 258 | is 6 MB, ~680 levels in debug) and `QuickJSContext` re-reads the stack top |
| 259 | on every entry as a belt-and-braces measure. The validator's calls stay |
| 260 | synchronous for the host but execute on its thread. Regression tests: |
| 261 | `stackCheckFollowsTheCallingThread`, `pinnedThreadGivesDeepRecursion`. |
| 262 | - **Verification status**: XCTest suite (engine, trusted validator, renderer |
| 263 | in a real WKWebView) passes on the iPhone 17 simulator (iOS 26.5) and the |
| 264 | engine/validator subset passes natively on macOS. The demo app renders the |
| 265 | compat corpus (Chart.js, d3, forms, drag, dark theme) and its attack runner |
| 266 | loads every `corpus/attacks` file against the canary on the Mac — see |
| 267 | `packages/ios/README.md` for the recorded result. |
| 268 |
| 269 | ## macOS implementation (`macos/` + the `ios/` package) |
| 270 |
| 271 | - **No fourth port: the iOS package compiles for AppKit.** `Package.swift` |
| 272 | already declared `.macOS(.v13)`; the engine, validator, JSThread and Intl |
| 273 | bridge are Foundation-only, and WebKit's API is shared. What was UIKit-only |
| 274 | (`RendererWebView`, `WidgetHost`, `WidgetView`) is now split by |
| 275 | `#if canImport(UIKit) / canImport(AppKit)`: `PlatformView` (UIView | NSView), |
| 276 | the container view, the SwiftUI representable, and five WKWebView knobs |
| 277 | (background, colour scheme, scrolling, context menu, file panel). The |
| 278 | bundles, the corpus and `pnpm build:macos` (= `build:ios`) are the same files. |
| 279 | - **Off-screen pause on AppKit = window attachment + `NSWindow.occlusionState`.** |
| 280 | A minimised, fully covered or other-Space window counts as hidden (the |
| 281 | background-tab analogy). `occlusionState` is trusted only after the window |
| 282 | server has reported on the window (a notification, or `.visible` seen); |
| 283 | before that `isVisible` decides. Reason: a process that never finishes |
| 284 | launching `NSApplication` — the xctest runner — gets no occlusion events, its |
| 285 | windows stay "not visible" forever, and WebKit in that process keeps the page |
| 286 | `hidden` too (no `requestAnimationFrame`, timers at 1 Hz; checked with a bare |
| 287 | WKWebView). So `testRemovingTheViewFromTheWindowPausesTheWidget` is iOS-only, |
| 288 | and the macOS demo runs the same scenario in a real app |
| 289 | (`--autorun pause`: minimise → tasks stop → restore → tasks resume, widget |
| 290 | sees `visible,hidden,visible,`). |
| 291 | - **Context menu and file dialogs are closed on macOS.** A `WKWebView` |
| 292 | subclass empties the menu in `willOpenMenu` (Reload / Open in New Window / |
| 293 | Download / Inspect Element); `runOpenPanelWith` answers `nil` so |
| 294 | `<input type=file>` never shows an NSOpenPanel. Neither is a new barrier |
| 295 | (navigations were already cancelled) but a bubble must not expose them. |
| 296 | - **Transparent page on macOS** needs `drawsBackground = false` through KVC; |
| 297 | the public `underPageBackgroundColor` only tints the area past the |
| 298 | document's end. It is the switch WebKit itself reads; not security-relevant. |
| 299 | - **The demos share their sources**: `apps/macos/DemoApp/project.yml` points at |
| 300 | `apps/ios/DemoApp/Sources` and `apps/ios/DemoApp/Corpus`; the platform differences are |
| 301 | `DemoPlatform.swift` (colours, report location, `--autorun`) and the scroll |
| 302 | visibility check, which now compares the bubble with the enclosing |
| 303 | ScrollView's bounds instead of `UIScreen.main` (same result on iOS, works on |
| 304 | both). Runners got launch-argument autorun and JSON reports like the Android |
| 305 | demo, plus a compat runner. |
| 306 | - **Reference mode in the native demo** (`ReferenceWebView.swift`, demo |
| 307 | sources, shared by iOS and macOS): the web prototype's `?reference=1` |
| 308 | rebuilt on a WKWebView — rewritten library URLs, doctype, private scheme, |
| 309 | `REFERENCE_CSP`, rule list, navigations cancelled — plus a `compare` runner |
| 310 | that times every compat/generated widget both ways. Kept out of the package |
| 311 | and off the attack corpus, as CLAUDE.md requires. The reference view is |
| 312 | sized and attached before it navigates, like the web iframe. One finding: |
| 313 | `d3-bar` fails natively on WebKit (`getBBox()` on a just-appended SVG |
| 314 | `<text>` during parsing throws `NotFoundError`; Chromium does not) while the |
| 315 | sandboxed copy passes, because its layout queries run against the laid-out |
| 316 | renderer document — a case where the protocol is more forgiving than the |
| 317 | engine. |
| 318 | - **Verification status**: package tests green natively (21; the 22nd is |
| 319 | iOS-only as explained) and still 22/22 on the iPhone 17 simulator; the macOS |
| 320 | demo loads generated 40/40 and compat 21/21, the attack corpus (89 files) |
| 321 | with 0 canary hits, and the pause probe passes — see `apps/macos/README.md`, |
| 322 | which also has the sandbox-vs-reference timings (debug build: ~2.3× wall |
| 323 | time to loaded, dominated by the source-eval boot). |
| 324 |
| 325 | ## Android implementation (`android/`) |
| 326 |
| 327 | The iOS architecture, ported glue for glue (Oct 2026). What was reused |
| 328 | unchanged: the three JS bundles, the vendored quickjs-ng sources *and* |
| 329 | `qjs_shim.c` (the CMake file points at `packages/ios/Sources/CQuickJS`), the protocol, |
| 330 | the `__host` string API, the engine/validator/host structure. What differed |
| 331 | from iOS and why: |
| 332 |
| 333 | - **JNI strings are byte arrays.** JNI's `jstring` helpers speak *modified* |
| 334 | UTF-8: supplementary characters (emoji, common in widgets) become |
| 335 | surrogate-pair sequences that QuickJS does not understand, and |
| 336 | `NewStringUTF` on a real 4-byte sequence is undefined behaviour under |
| 337 | CheckJNI. Every string crossing the boundary is therefore a `byte[]` of |
| 338 | real UTF-8, decoded on the Kotlin side (`QuickJSContext.kt`). Exceptions |
| 339 | are raised the same way: C calls a private Kotlin `raise(byte[])` that |
| 340 | throws `QuickJSException`, so the message survives non-ASCII too. |
| 341 | - **The interpreter is compiled with `-O2` even in debug builds.** Measured |
| 342 | on the emulator: 394 JS frames at the default 384 KB limit and ~6300 on a |
| 343 | `JSThread` (6 MB), i.e. ~1 KB of C stack per JS call, versus ~10 KB in the |
| 344 | iOS debug build. Widget boot (sandbox bundle eval + initial tree) is |
| 345 | 60–90 ms instead of ~150 ms. Nobody debugs quickjs-ng internals through the |
| 346 | app, so the trade is free. |
| 347 | - **`JSThread` is a plain `Thread` + `Looper`**, not a `HandlerThread`: |
| 348 | `HandlerThread` has no stack-size constructor and the ~1 MB default is too |
| 349 | small for css-tree inside the validator. The looper gives timers |
| 350 | (`postDelayed`) and ordered posts for free, same role as the iOS run loop. |
| 351 | - **Interrupt deadline on `CLOCK_BOOTTIME`** (= `SystemClock.elapsedRealtimeNanos()`), |
| 352 | compared inside the C interrupt handler; Kotlin credits the time spent in a |
| 353 | sync query back to the deadline, like Swift does. |
| 354 | - **Memory and CPU limits are public API from day one** |
| 355 | (`WidgetHost.Options(memoryLimitBytes, cpuLimitMs)`), the gap noted for iOS. |
| 356 | A test covers both through the host, not only through the engine. |
| 357 | - **The renderer origin is `https://w-<uuid>.tgwidget.invalid/`**, served by |
| 358 | `shouldInterceptRequest`, not a custom scheme: Android WebView has no |
| 359 | `WKURLSchemeHandler`, and an `https` origin keeps the document a secure |
| 360 | context. `.invalid` can never resolve, and `setBlockNetworkLoads(true)` |
| 361 | stays on because interception runs before the network stack — verified |
| 362 | on the emulator (the document loads with the flag set, an injected |
| 363 | external `<img>` is refused and reported, `location.href` navigation is |
| 364 | cancelled). Every non-document request is answered with an empty 403 and a |
| 365 | `url-blocked` diagnostic instead of being merely dropped, so a leak attempt |
| 366 | is visible in the panel. `WebViewAssetLoader` was not used: it is a |
| 367 | convenience over the same callback, not a boundary. |
| 368 | - **Hardening lives in a document-start script** through |
| 369 | `WebViewCompat.addDocumentStartJavaScript` (androidx.webkit), the WKWebView |
| 370 | `WKUserScript` equivalent, with the same list plus `WebTransport`, |
| 371 | `RTCDataChannel` and `navigator.serviceWorker`. `RendererWebViewTest` |
| 372 | checks `typeof fetch` etc. through `evaluateJavascript` — the only place |
| 373 | where the host evaluates trusted script other than `__twReceive`. |
| 374 | - **Safe Browsing is switched off twice** (`WebSettingsCompat` and the |
| 375 | manifest meta-data merged from the library): it is the one way a stock |
| 376 | WebView talks to Google on its own, which would show up as unexplained |
| 377 | traffic in a pentest even though it is not a widget leak. |
| 378 | - **The attack runner's canary address is editable and remembered** |
| 379 | (default `10.0.2.2:9999`, the emulator's alias for the host); the iOS demo |
| 380 | hardcodes `127.0.0.1` and cannot run on a phone without a source edit. |
| 381 | - **Runners are drivable from `adb`** (`--es autorun attacks|generated|compat`) |
| 382 | and write JSON reports into the app's `files/` directory; the compat corpus |
| 383 | got a runner of its own because Android has no reference renderer for the |
| 384 | pixel diff, so loaded / errors / diagnostics are what is recorded. |
| 385 | - **Theme toggling needs no WebView-level dark mode.** `WKWebView` has |
| 386 | `overrideUserInterfaceStyle`; a `WebView`'s `prefers-color-scheme` is read |
| 387 | from its context's configuration at creation and cannot be flipped later |
| 388 | (`dispatchConfigurationChanged` with a night-mode `uiMode` was tried on the |
| 389 | emulator: no effect). The first write-up of this port called that a gap and |
| 390 | proposed a host→renderer `theme` message; measuring showed it is not one: |
| 391 | the validator already resolves `prefers-color-scheme` media queries, |
| 392 | `color-scheme: light dark` and `light-dark()` against the host theme and |
| 393 | re-emits every stylesheet on `setTheme`, and `matchMedia` is answered by the |
| 394 | host. After a toggle the root `color-scheme`, `light-dark()` colours and |
| 395 | the UA's own form-control colours switch (regression test |
| 396 | `themeToggleReachesComputedStylesAndFormControls`). The renderer's internal |
| 397 | preference stays stale but nothing a widget can observe depends on it, so |
| 398 | the protocol stays as it is. |
| 399 | - **Found on a real phone: drags died under the chat scroll.** drag.html moved |
| 400 | a few px and stopped whenever the finger had a vertical component, while |
| 401 | horizontal drags worked; the diagnostics were clean. The Compose scroll |
| 402 | container intercepted the touch past the slop and the WebView got |
| 403 | `ACTION_CANCEL` → `pointercancel`. iOS and the web never had this: WebKit |
| 404 | resolves `touch-action` against `UIScrollView` itself, and the web |
| 405 | prototype's iframe shares the page compositor. Fix: the renderer posts a |
| 406 | `gesture` message on every primary `pointerdown` (`touch-action` on the |
| 407 | ancestor chain forbids vertical panning, a range input, a vertically |
| 408 | scrollable box, or a learned `preventDefault` — the range sliders of |
| 409 | inputs.html stopped the same way, Chromium's own thumb drag does not ask |
| 410 | the parent to stand back either), |
| 411 | and `RendererWebView` denies parent interception from `ACTION_DOWN` until |
| 412 | the answer says no (or 150 ms pass). The message is part of the shared |
| 413 | renderer; web and iOS hosts ignore it. Regression test: `GestureTest`. |
| 414 | - **Found on a real phone: pickers did nothing.** Tapping `<input type=color>` |
| 415 | (inputs.html) and the `<select>` of form-validation.html opened nothing, |
| 416 | with no error anywhere. Chromium shows those dialogs only when it finds an |
| 417 | Activity behind the WebView's context, and the renderer view was created |
| 418 | from `createConfigurationContext(...)` — a bare context, chosen to pin the |
| 419 | initial `uiMode`. The themed context is now a `ContextThemeWrapper` over |
| 420 | the caller's context with the same override configuration, so the Activity |
| 421 | stays reachable; colour picker and select popup work, the value reaches |
| 422 | the widget (`#ff0000`, preview recoloured). Regression test: |
| 423 | `themedContextKeepsTheActivityAndSetsNightMode`. |
| 424 | - **Found on the emulator only**: `[null].join()` is `''` (a test |
| 425 | expectation, not a bug); a throw inside a promise reaction does not make |
| 426 | `JS_ExecutePendingJob` fail (only the derived promise rejects), so the |
| 427 | engine's job-error path only ever sees interrupts and OOM — same as iOS, |
| 428 | now covered by a test. |
| 429 | - **Verification status**: see `packages/android/README.md` (26 instrumented tests, |
| 430 | attack runner, generated and compat runners on the Android 15 emulator). |
| 431 |
| 432 | ## Phase 6 — generated corpus (`corpus/generated/`) |
| 433 |
| 434 | - **How it was produced.** No Anthropic API key was available, so the two |
| 435 | batches (20 prompts from `scripts/generate-corpus.ts`, with and without |
| 436 | `docs/widget-runtime-profile.md`) were written by Claude inside a Claude Code |
| 437 | session instead of by `pnpm generate-corpus`. The "without" batch was written |
| 438 | the way an assistant writes for a generic `show_widget(html)` tool — Google |
| 439 | Fonts `<link>`s, a CDN-hosted hero image, `fetch` for live rates, |
| 440 | `navigator.clipboard`, `alert`/`confirm`, `Notification`, `localStorage`, |
| 441 | `element.animate`, `location.reload()`; the "with" batch follows the profile |
| 442 | (inline everything, `color-scheme: light dark`, `TelegramWidget.sendMessage` |
| 443 | for user actions, `typeof Chart` fallbacks, no blocking dialogs). Caveat: |
| 444 | generator and sandbox came from the same model, so this measures the profile |
| 445 | as a prompt, not what a third-party model would do. |
| 446 | - **Result** (`pnpm test:generated`, see `docs/compat-report-generated.md`): |
| 447 | every widget in both batches loads, runs without JS errors and renders within |
| 448 | 3 % of the native reference after the harness clicks up to four buttons. The |
| 449 | profile did not change the pass rate — the sandbox absorbs the "without" |
| 450 | habits: external fonts and images are dropped (`tag-dropped`, `url-blocked`; |
| 451 | system font and a blank hero render instead), `fetch` rejects and the |
| 452 | widget's own catch path shows "offline" (`network-blocked`), `confirm()` |
| 453 | returns `false` so deletes are silently refused (`unsupported`), `localStorage` |
| 454 | simply does not persist. What the profile *does* change is behaviour the |
| 455 | pixel diff cannot see: the "with" widgets send results to the chat, follow |
| 456 | the dark theme and never attempt a network request, while the "without" ones |
| 457 | log a blocked request or a no-op dialog per widget. |
| 458 | - **Same corpus on iOS** (demo app → "Run the generated corpus", iPhone 17 |
| 459 | simulator, iOS 26.5): 40/40 load without JS errors or termination; median |
| 460 | JS time per widget 171 ms including the ~150 ms sandbox-bundle boot (debug |
| 461 | build, no bytecode cache yet); the same `tag-dropped` / `url-blocked` / |
| 462 | `network-blocked` diagnostics appear on the "without" widgets as on the web. |
| 463 | No pixel comparison on iOS (there is no reference renderer there); the runner |
| 464 | writes `Documents/generated-report.json` in the app container. |
| 465 | - **One corpus bug, not a sandbox bug.** The tic-tac-toe widget (both batches) |
| 466 | accepted clicks during the computer's 350–400 ms "thinking" delay, so the |
| 467 | harness's rapid clicks finished the game three times ("You 3") and the two |
| 468 | modes diverged on timing (3.9 % diff). Both files were fixed identically |
| 469 | (ignore clicks while busy) and the suite re-run; the race is a realistic |
| 470 | thing for a model to write, and the sandbox handled it the same way a browser |
| 471 | does. |
| 472 |
| 473 | ## Dropped features |
| 474 |
| 475 | - **`<a target=_blank>` / `window.open` opening anything** — links never |
| 476 | navigate; they go through `TelegramWidget.openLink`, logged by the host. |
| 477 | - **`document.cookie`, `document.write`, Blob/File, `URL.createObjectURL`** — |
| 478 | no-ops with an `unsupported` diagnostic. `createObjectURL` would create a |
| 479 | URL the sandbox could inject into markup; the host mints no blob: URLs in |
| 480 | this prototype, so the renderer accepts none. |
| 481 | - **Shadow DOM, custom elements, Web Animations API** — out of scope for the |
| 482 | prototype; logged as unsupported. |
| 483 | - **`alert/confirm/prompt`** — cannot block the sandbox thread; they are |
| 484 | forwarded to the host as a bridge call and return `false`/`null`. |
| 485 |
| 486 | ## Runtime limits (Oct 2026) |
| 487 |
| 488 | Four changes. |
| 489 | Everything that counts and decides lives in trusted glue; the shim only gets |
| 490 | information. |
| 491 |
| 492 | ### Throttle, not kill: a CPU quota per second |
| 493 |
| 494 | - Telegram kills a widget the moment it exceeds its budget. We **defer**: a |
| 495 | sliding window of 1 s in ten 100 ms buckets, 300 ms of JS per window; |
| 496 | past it timers, frames, resize/viewport/theme/bridge tasks wait until the |
| 497 | oldest busy bucket leaves the window (frames collapse into one, one fire per |
| 498 | timer id, order kept). The widget animates less often but keeps working, |
| 499 | which is what the compat corpus (Chart.js animations, rAF loops, D3 |
| 500 | transitions) needs. `cpuKillAfterMs` (default 0 = off) brings back the kill |
| 501 | for products that want it: sustained throttling, no gap longer than one |
| 502 | window, for that long. |
| 503 | - Events always run, so the widget answers the user even with the budget |
| 504 | spent. Every task gets the whole `cpuLimitMs` slice (500 ms), the hang |
| 505 | guard, whatever the window holds; what a task spends past the quota is a |
| 506 | debt of at most one more quota that enters the window as its buckets leave, |
| 507 | so the quota holds over time and the next timers and frames wait for it. |
| 508 | - Until 2026-11-02 the slice was the quota left, at least 50 ms (`min(cpuLimitMs, |
| 509 | max(remaining, 50))`), and a task that overran it was killed like an |
| 510 | infinite loop. That stop depends on the device: in the client teams' |
| 511 | stress-kit runs a 3D showcase widget's 70 ms timer task, started with 15 ms |
| 512 | of the quota left, died on a Redmi Note 8T in three runs out of three, while |
| 513 | an A55 and an iPhone ran it. A slice cut to the quota left stopped widgets |
| 514 | a fast phone runs; the hang guard alone stops the same widgets everywhere. |
| 515 | - Our own cost is not the widget's: evaluating the sandbox bundle (~0.5 s of |
| 516 | source eval on the web, ~150 ms on an iOS debug build) is excluded from the |
| 517 | boot task's recorded time, otherwise every widget would spend its first |
| 518 | second throttled. |
| 519 | - One pure policy, three copies, one fixture: `packages/core/src/host/cpu-budget.ts`, |
| 520 | `CpuBudget.swift`, `CpuBudget.kt` are line-for-line mirrors checked against |
| 521 | `packages/core/tests/fixtures/cpu-budget.json` (the build script copies it into the native |
| 522 | test resources). The glue around them (worker.ts, the Node harness, |
| 523 | SandboxEngine.swift/.kt) is ported, as everything else in the native layer. |
| 524 | - Debug builds of quickjs-ng are several times slower than release, so the iOS |
| 525 | demo and the native tests use a wider quota (1000 ms/s, or 100 ms/s where a |
| 526 | test wants throttling quickly); the product default stays 300. |
| 527 |
| 528 | ### Strict-policy text limits |
| 529 |
| 530 | Strict validators allow at most 32 Ki UTF-16 units per text value and 48 Ki units across tracked text and comment nodes (64 Ki and 256 Ki until the strict limits; past either the widget now stops, "Strict limits from the start"), and 8192 complex-script units across text nodes. Removal and shrinking release the document budget; resetting a pooled native validator clears it. Since the pre-release hardening the budgets also charge `data-*` / `aria-*` values and the strings of sanitized CSS (see "Strict budgets reach attributes and CSS strings"). |
| 531 |
| 532 | Text mutations longer than 256 UTF-16 units, or containing complex-script, CJK, Kana, Hangul or fullwidth characters, also consume a shared token bucket with an 8192-work-unit burst and a 1024-unit-per-second refill; short Latin, digit and symbol text such as ticker cells is never charged, so a 400-cell ticker updating every frame keeps all its updates. Work counts words separated by whitespace, hyphens, question marks, slashes, or zero-width spaces, and counts CJK, Kana, Hangul, fullwidth and supplementary characters individually. Long unbroken runs cost at least one unit per 1024 UTF-16 units. Creating, replacing, splitting, or removing nodes cannot refund mutation work. Rejected mutations preserve the last accepted text. Compatibility policy keeps its existing limits. |
| 533 |
| 534 | The TypeScript validator and Swift native validator enforce the same accounting. The native JS bundles and matching QuickJS bytecode are regenerated for iOS/macOS, Android, and desktop together. |
| 535 |
| 536 | ### CPU time, not wall-clock time (Oct 2026) |
| 537 |
| 538 | - The slice and the quota count the JS thread's own CPU time |
| 539 | (`CLOCK_THREAD_CPUTIME_ID` in Swift, C++ and the Android JNI layer, |
| 540 | `GetThreadTimes` on Windows), not wall-clock time. On a loaded machine (a |
| 541 | build, a busy chat list, other widgets) wall-clock slices killed widgets that |
| 542 | had used a fraction of their budget. Waiting for a sync query no longer needs |
| 543 | subtracting: a blocked thread uses no CPU. |
| 544 | - Wall-clock time stays as a backstop, `max(10 x slice, 5 s)`, for a thread |
| 545 | that is starved or stuck outside JS. |
| 546 | - The web worker and the Node harness keep wall-clock slices: browsers and |
| 547 | Node expose no per-thread CPU clock to a worker. A loaded browser can still |
| 548 | throttle or kill a widget early there; the quota policy (`cpu-budget.ts` and |
| 549 | its twins) is unchanged, only what the native glue feeds it. |
| 550 |
| 551 | ### The validator's time counts (2026-11-02) |
| 552 |
| 553 | The client teams' stress-kit runs (v0.5.0) found the validator outside every limit. On the native hosts it is the JS |
| 554 | validator in a QuickJS context of its own on a thread of its own (`TrustedValidator` in Swift, Kotlin and C++), and one |
| 555 | style op cost 134 µs there on a Galaxy A55 (43 µs on a Mac, 3 µs in V8 on the web), 94 % of it css-tree parsing, |
| 556 | walking and writing the one declaration. `opacity-moving/128` kept it busy about 900 ms a second, nearly a core, while |
| 557 | its JS used 92 ms of the 300 ms quota and the main-thread window charged the modelled 25 µs per op. Two changes |
| 558 | (Artem, 2026-11-02): |
| 559 |
| 560 | - **A fast path in `css-sanitizer.ts`** (`fastStyleValue`: one JS for every platform, in the validator bundle). |
| 561 | `sanitizeStyleProperty` (style ops, anim keyframe values, SVG `font-family`) first tries one linear scan over |
| 562 | `[0-9A-Za-z.%#(),-]` and the space: numbers, lengths, percentages, `#` colours, keywords and the profile's functions |
| 563 | of them, checked by the full path's rules (units, functions, keyword sets, rewrites, the transform / rotate / |
| 564 | translate / scale checks, `background-clip: text`) and written with css-tree's whitespace between tokens. It only |
| 565 | accepts; everything else goes through css-tree, which decides and reports as before: escapes, strings, comments, |
| 566 | `url()`, `var()`, `env()`, `attr()`, `light-dark()`, `!`, operators (`calc(100% - 1px)`), exponents, viewport units |
| 567 | (the shadow scope rewrites them), fonts, filters, `color-scheme`, `sticky`, scrolling overflow, values over 256 |
| 568 | characters. Its alphabet has no character that starts a URL, a string, an escape or a comment, so not even a wrong |
| 569 | table could let a URL through (invariant 4), and what it accepts does not depend on the `CssEnv`. |
| 570 | - **Checked against css-tree byte for byte**, diagnostics included (`tests/unit/css-fast-path.test.ts`): every |
| 571 | declaration of `corpus/**` (the attacks too), the conformance set and the stress kit, in all 32 envs (both schemes, |
| 572 | document and shadow scope, strict and compat, reduced motion, native scrolling; 5 403 declarations, 4 100 taken), |
| 573 | each of their values under every profile property (896 K declarations, 635 K taken), a generated set (every pair of |
| 574 | token kinds with every separator, the edge cases, a seeded fuzz; 1.2 M, 495 K taken), the shapes moving widgets send, |
| 575 | and the validator with the fast path on and off. Once, outside the suite: every style op the 513 widgets of the |
| 576 | corpora, the conformance set and the stress kit sent in 40 frames (426 169 distinct values, 426 145 taken) gave the |
| 577 | same answer, and the validator's output over their 10 568 batches was byte-identical. |
| 578 | - **What it gives** (a Mac with other builds running; an A55 is about 3.1 times slower): |
| 579 |
| 580 | | | before | after | |
| 581 | |---|---|---| |
| 582 | | QuickJS, the sanitizer alone per style op (the stress kit's `transform`, `hsl()`) | 42–49 µs | 2.2–2.3 µs | |
| 583 | | QuickJS, the same for a two-stop gradient | 59 µs | 3.4 µs | |
| 584 | | QuickJS, the showcase's style ops on average | 18 µs | 0.95 µs | |
| 585 | | QuickJS end to end per style op (`TrustedValidator::processOps` + `nodeCount`: the hops, JSON, the validator), compat | 42–63 µs | 3.6–5.0 µs | |
| 586 | | the same, strict and shadow scope | 44–64 µs | 4.5–6.3 µs | |
| 587 | | `opacity-moving/128`: one batch of 256 style ops | 11.8 ms | 0.93 ms | |
| 588 | | the showcase's 27 widgets: every batch of a 40-frame run | 21.8 ms | 13.1 ms | |
| 589 | | V8, `processOps` per op of the moving stress levels | 3.6 µs | 0.17–0.22 µs | |
| 590 | | V8, `processOps` per op of the showcase | 0.43–0.53 µs | 0.19–0.21 µs | |
| 591 |
| 592 | On an A55 that is about 12–15 µs instead of 134 per style op, and `opacity-moving/128` costs the validator about |
| 593 | 75 ms a second instead of 900, plus its wake-ups (below). |
| 594 | - **Its CPU time is charged to the widget's JS quota on the native hosts.** `TrustedValidator` measures its thread's |
| 595 | CPU time (`CLOCK_THREAD_CPUTIME_ID`, the JS quota's clock) around each call made for the widget's messages (ops |
| 596 | batches: JSON, for a renderer, binary; queries and their media rewrite; `listen`, `preventDefault`, anim batches) and |
| 597 | hands it to a sink `WidgetHost` sets; `SandboxEngine.chargeValidator` records it with `CpuBudget.record` on the engine |
| 598 | thread as it arrives. The budget belongs to the engine thread and the validator's is never that one, so the time is |
| 599 | posted, not shared; with the debt rule a record after the task counts in full. It shows as `stats.validatorMs` next |
| 600 | to `jsMs`, and `cpuWindowMs` includes it. A shared validator thread (the pools, Swift's `sharedValidatorThread`) |
| 601 | changes nothing: a call's CPU time on it is that call's. Not charged: what the host asks for itself (the stylesheets |
| 602 | again on a theme change, their warm-up at boot, a pool's reset). The JS quota is the right meter because the |
| 603 | validator works for this widget alone, on its own thread, like the widget's JS: a weak phone throttles the widget |
| 604 | earlier, and three busy widgets can no longer take the big cores unseen. The policy and its fixture are unchanged |
| 605 | (one more `record`); the tests are `ValidatorTimeTests.swift`, `ValidatorCpuTest.kt` (JVM) and `ValidatorTimeTest.kt` |
| 606 | (device), and desktop `validator_time_counts_against_the_js_quota` and `widget_host_charges_the_validators_time`. |
| 607 | - **The main-thread window stays a model** (25 µs per op, 2 µs per canvas command): it prices the host's shared thread, |
| 608 | and on the native hosts the validator is not on it. |
| 609 | - **The web is not charged.** It validates on the page's main thread in V8 (the worker sends ops asynchronously), |
| 610 | now about 0.2 µs per op of a moving widget, and stays modelled by the main-thread window; the web worker and the Node |
| 611 | harness have no validator thread, so their copies of the glue do not charge it. |
| 612 | - Open: the A55's "about 1 ms per batch" is the validator thread waking (a small batch costs 10–20 µs on a Mac, 60–76 µs |
| 613 | after 8 ms idle), not computation, and CPU time does not count it. A pipeline of depth one would hide it, after a |
| 614 | decision on how a widget stops past a counted cap with batches in flight. |
| 615 |
| 616 | ### Layout queries are bounded per task and charged to the quota (Oct 2026) |
| 617 |
| 618 | A synchronous layout query (`offsetHeight`, `getBoundingClientRect`, |
| 619 | `getComputedStyle`, …) blocks the sandbox thread until the host's renderer has |
| 620 | answered. Only the CPU of the JS thread counted toward the slice, and the time |
| 621 | spent waiting moved the deadline, so a widget looping on `a.style.width = …; |
| 622 | a.offsetHeight` burned almost no CPU of its own, was never interrupted, and |
| 623 | kept the renderer answering forever: the host was busy, the widget alive. Found |
| 624 | by Misha on the macOS client (54bdfa5); now the rule on every host: |
| 625 |
| 626 | - the queries the host answers in a task are counted (`taskQueries`) and their |
| 627 | wall time summed (`taskQueryMs`); past 128 queries, or past 1000 ms of their |
| 628 | time, the hang guard (`queryLimitHit`, `QUERY_LIMIT` / `QUERY_BUDGET_MS` in |
| 629 | `cpu-budget.ts` and its three twins, checked against |
| 630 | `tests/fixtures/cpu-budget.json`) the task is interrupted at the next poll (the |
| 631 | CPU deadline is moved into the past) and killed with "Layout query limit |
| 632 | exceeded: more than 128 layout queries in one <kind> task" or "… host queries |
| 633 | blocked the renderer for more than 1000 ms in one <kind> task"; any further |
| 634 | query of that task is answered `{"error":"query budget exceeded"}`, and a task |
| 635 | that ends on those answers before the interrupt lands is killed at its end all |
| 636 | the same. Until 2026-11-02 the limit was 100 ms of the queries' time (the |
| 637 | slice, up to 500 ms, before the strict limits): in the client teams' runs a |
| 638 | widget with one `getBoundingClientRect` at load died on a Redmi Note 8T in the |
| 639 | first run after install (a cold first layout over 100 ms), and a query costs |
| 640 | 0.12 ms on an M5, 0.36 on an iPhone Air, 0.68 on an A55, 1.3 on tdesktop and |
| 641 | 1.9 on the Redmi. A count stops the same widget on every device; the most |
| 642 | query-heavy real widget, `auto/03-layout-a`, makes 47; |
| 643 | - the query time is charged to the host's main-thread window (with the modelled |
| 644 | cost of the task's ops; it was charged to the CPU quota with the task's CPU |
| 645 | until the strict limits): a layout-heavy widget pays for what it costs the host, |
| 646 | and the window throttles it like a busy one; |
| 647 | - both counters reset at the start of each task. |
| 648 |
| 649 | The limit is per task, not per widget, so an ordinary widget that measures a |
| 650 | few elements per frame is far from it, while a forced-layout loop reaches it |
| 651 | within the first task. The Node harness |
| 652 | keeps the same accounting (its answers are in-process, so only a slow `answer` |
| 653 | callback can trip it). `corpus/attacks/layout-query-loop.html` is the attack. |
| 654 |
| 655 | ### 64 timers, and an error instead of a hang |
| 656 |
| 657 | - Telegram allows 16 timers; browsers have no limit. D3 transitions and |
| 658 | staggered animations put dozens of timers in flight, so 256 was the default, |
| 659 | configurable (`maxTimers`); 64 since the strict limits (the busiest widget of |
| 660 | the corpora holds 31). |
| 661 | - The cap used to be 2000 and silent: the glue dropped the timer and the shim |
| 662 | returned an id whose callback never came — a hang with no error. Now the |
| 663 | shim throws `RangeError('too many timers (max N)')` (reported once as |
| 664 | `timer-limit`), the glue keeps its own count as a backstop and reports |
| 665 | `timer-limit-enforced` if it is ever hit (which means a shim bug or a |
| 666 | tampered shim). Delays are clamped to 24 h on every platform. |
| 667 |
| 668 | ### The last render stays on screen when the runtime dies |
| 669 |
| 670 | - The renderer was never told that the runtime had died: buttons kept |
| 671 | "working", frames and events went nowhere. The host now sends `frozen` and |
| 672 | the renderer makes the snapshot honest: `pointer-events: none`, a slight |
| 673 | grayscale, a badge ("Widget stopped", host-provided text, no error details), |
| 674 | no more event forwarding, pending frame cancelled. `destroy()` stays an |
| 675 | explicit owner action, on every platform. |
| 676 | - Mid-task kills are atomic for the renderer: the shim flushes ops at the end |
| 677 | of a task only, so a handler that mutates 500 nodes and then hangs leaves |
| 678 | none of them on screen (`fallback-mid-batch.html` pins this down). |
| 679 | - One difference from a browser, documented by `fallback-at-boot.html`: the |
| 680 | whole document is parsed and shipped before the first script runs, so |
| 681 | markup *after* a hanging boot script is visible too. |
| 682 | - Non-fatal uncaught exceptions get a dedicated `onError` callback on all |
| 683 | three hosts, so a product can show an error line under the bubble the way |
| 684 | Telegram does; the dev UI and the iOS demo show the last one until a later |
| 685 | task completes without one, plus a Restart action (a new host from the same |
| 686 | HTML). |
| 687 |
| 688 | ### The memory limit is the wasm memory's maximum (web only) |
| 689 |
| 690 | - Found with `corpus/attacks/mem-*.html` (Oct 2026): a widget retaining 1 MB |
| 691 | typed arrays grew the runtime past 1.2 GB with `rt.setMemoryLimit(64 MB)` in |
| 692 | place, while one 256 MB allocation was refused. quickjs-ng counts its heap as |
| 693 | Σ `malloc_usable_size(ptr)`; `cutils.h` implements that for Apple, Windows, |
| 694 | glibc/Android and wasi but has no `EMSCRIPTEN` branch, so in the |
| 695 | quickjs-emscripten build every block counts as 0 bytes (+ 8 of overhead) and |
| 696 | the limit check `malloc_size + size > limit` only bites for a single |
| 697 | oversized allocation. `computeMemoryUsage().memory_used_size` walks the |
| 698 | object graph and does include `ArrayBuffer` bytes, which is why the stats |
| 699 | showed the growth that the limit did not see. |
| 700 | - **Fix in the glue, not the shim**: the wasm module imports its memory, so the |
| 701 | worker (and `packages/core/scripts/sandbox-node.ts`) creates it with |
| 702 | `maximum = INITIAL (16 MB) + memoryLimitBytes` and passes it through |
| 703 | `newVariant(..., { wasmMemory })`. When dlmalloc cannot grow the memory, |
| 704 | quickjs throws the same catchable `InternalError: out of memory` that |
| 705 | `JS_SetMemoryLimit` throws natively; the glue keeps working at the cap |
| 706 | (host → VM strings, calls) and memory is reusable after the widget frees it. |
| 707 | `setMemoryLimit` stays as the cheap first check for one huge allocation. |
| 708 | The footprint of a worker is therefore bounded by 16 MB + the limit (24 MB at |
| 709 | the 8 MB default of the strict limits, 80 MB at the 64 MB it was); a polling or |
| 710 | interrupt-handler guard was rejected because quickjs polls interrupts every |
| 711 | 10 000 back-edges, i.e. gigabytes of 1 MB allocations between polls. |
| 712 | - Semantics match native: a widget that catches the error lives on at the cap |
| 713 | (`mem-steady-growth.html` shows "62 (alloc refused: InternalError)"), an |
| 714 | uncaught one is killed with "Memory limit exceeded (64 MB)" and keeps the |
| 715 | last render frozen (`mem-uncaught-growth.html`). Verified natively by |
| 716 | compiling the vendored quickjs-ng v0.17.0 on macOS (Apple `malloc_size`): |
| 717 | steady growth capped at 62 MB, burst refused, arrays capped. Android uses |
| 718 | bionic `malloc_usable_size` through the `__linux__` branch. Swift, Kotlin and |
| 719 | the C++ core need nothing extra. |
| 720 |
| 721 | ### Strict limits from the start (2026-10-29) |
| 722 |
| 723 | Widgets are not launched yet. A limit can be loosened later without breaking anything; tightening it breaks widgets |
| 724 | that worked, and with honest strict limits bots adapt to them (Artem, 2026-10-28: "лучше посильнее зарезать на старте"). |
| 725 | So every count and size limit was re-measured over 346 widgets of the corpora and the conformance set (5 s each in the |
| 726 | dev app, a tap on the first button; memory also in the native C++ harness) and set to about twice the largest real use: |
| 727 |
| 728 | | Limit | Largest real use | Limit | Past it | |
| 729 | |---|---|---|---| |
| 730 | | QuickJS heap | 3.1 MB (1.9 MB of it the runtime and the shim) | 8 MB (was 64) | stops | |
| 731 | | Live timers | 31 | 64 (was 256) | `RangeError` | |
| 732 | | Live script animations | 4 | 64 (was 1024) | not rendered | |
| 733 | | One text value | 12.9 K (a stylesheet) | 32 K (was 64 K) | stops | |
| 734 | | The document's text | 21.7 K | 48 K (was 256 K) | stops | |
| 735 | | An attribute value | 1 066 (an inline style) | 8 K (was 4 MB) | stops | |
| 736 | | Nodes in the document | 962 (604 elements) | 2000 (was 50 000, not created past it; 2026-11-02) | stops | |
| 737 | | Ops in one batch | 2 700 | 10 000 (was 200 000) | stops | |
| 738 | | CSS rules / `@keyframes` | 167 / 12 | 400 / 32 (no cap) | stops | |
| 739 | | Canvas commands per canvas and task | 237 (the projected 3D showcase: 9 510 a frame, now under 2000) | 4000 (10 000 until 2026-11-02; was 400 000 buffered) | `RangeError`; stops past it in a batch | |
| 740 | | Web Storage per area | 585 characters | 4 KB (was 16 KB) | `QuotaExceededError` | |
| 741 | | Layout queries per task | 47 (conformance `auto/03-layout-a`) | 128 queries, and 1000 ms of their time (100 ms until 2026-11-02; before that the slice) | stops | |
| 742 | | Canvas pixels, all of a widget's canvases | 0.41 M (736 × 560) | 2048² = 4.2 M (the audit's 4096²) | stops | |
| 743 | | A data: image's pixels | 800 (40 × 20) | 1024² = 1 M (the audit's 4096²) | the placeholder | |
| 744 |
| 745 | - **Stop, not drop.** A counted cap used to drop the op with a diagnostic and the widget went on with a hole in its |
| 746 | document, whose look depended on what had passed. Now the validator (`validator.ts`, the same bundle on every native |
| 747 | host, and Swift's `NativeValidator`) sets `stopped`, reports the `limit` diagnostic with the reason and refuses that |
| 748 | batch whole and every later one; the host stops the widget with that reason, as for memory or CPU, and the bubble |
| 749 | keeps its last render. The author sees the cause at once. The complex-script budget and text churn still drop: |
| 750 | a widget in those scripts needs all of its budget, and the numbers did not change. Text inserted while the widget |
| 751 | loads is not charged to the churn bucket (2026-11-02): the host calls the validator's `markLoaded` after the loading |
| 752 | tasks' ops, and only then do text changes count against the rate. A 48 K document of paragraphs built by the loading |
| 753 | script lost them past ~45 K, silently, on every host; the document's caps bound a load anyway. |
| 754 | - **Totals after the batch** (2026-10-30, the tweb team's move to v0.4.0). The document's text, CSS rules and |
| 755 | `@keyframes` are compared with their caps once the whole batch is applied (`checkTotals`): what counts is the document |
| 756 | the widget leaves after a task, not the sum of an old and a new subtree in the middle of `innerHTML` or of two sheets |
| 757 | rewritten in one task. The batch is in memory whole either way, so nothing grows unbounded meanwhile. The shim helps |
| 758 | the budget that drops: it sends the removal of a subtree replaced in one task before the new one. The node count |
| 759 | (2026-11-02) is a total too: a document rebuilt in one task never counts twice. |
| 760 | - **A long flush goes out in parts** (2026-11-02). The shim hands the glue what it has between two nodes once ~1000 ops |
| 761 | are buffered (`capture.ts` `sendIfLarge`): in the client teams' runs a document built in one task (2000 elements, |
| 762 | ~4000 ops) stopped at the 8 MB heap on 64-bit hosts while it held 4.4 MB; the op buffer and its JSON were the boot's |
| 763 | peak, not the document (checked in the C++ harness: the same widget with a flush every 500–1000 elements loads at |
| 764 | 4.4 MB). The protocol is unchanged and the renderer gets the same ops; the method calls, canvases and animations of a |
| 765 | flush stay in its last part, with the staged canvas payloads. The totals above are compared after each part, which |
| 766 | the early removal keeps right for a replaced subtree; a rebuild that moves nodes out of the old subtree and passes 1000 |
| 767 | ops can see old and new together for one part. The ops cap stops a flood of element method calls (`auto/33`), not |
| 768 | a large document: the per-task cost of the DOM ops is the main-thread window's. |
| 769 | - **The shim refuses at the same numbers**, so the author gets an error inside the widget where the host would stop it: |
| 770 | timers (`RangeError`), script animations (not rendered, `animation-limit`) and canvas commands (the 4001st command for |
| 771 | one canvas in one task throws `RangeError`; the validator stops a batch with more, i.e. a tampered shim). |
| 772 | - **Canvas commands: 4000** (2026-11-02, from the stress kit; 10 000 until then). The cap bounds one frame, not the |
| 773 | rate: under strict the main-thread window (2 µs a command) gives 2000 commands a frame ~25 fps, 4000 ~13 and 9 510 ~5 |
| 774 | on every client measured (A55, iPhone Air, tdesktop, the web; a Redmi Note 8T is slower on its own: 14 fps at 2000). |
| 775 | JS per command: iPhone 1.1–1.4 µs, M5 2.7, tdesktop 3.0, A55 4.2–4.4, Redmi 10.9–12.9, so 10 000 in one task was |
| 776 | 110–130 ms of JS on the Redmi. Outside the projected 3D showcase no widget draws more than 237; the showcase's meshes |
| 777 | were lightened to at most 2000 a frame (`corpus/showcase/3d`), so it runs at ~25 fps under strict everywhere. |
| 778 | - **The main-thread window.** The JS quota (300 ms per second, unchanged: a widget's JS runs on its own thread, and the |
| 779 | busiest widgets on a weak phone are already throttled by it) no longer pays for what the widget costs the client's main |
| 780 | thread. That is a second `CpuBudget` in the glue, `mainThreadQuotaMs` = 100 ms per `cpuQuotaWindowMs`: the wall time of |
| 781 | the widget's layout queries plus a modelled, deterministic cost of the ops the glue forwards (25 µs per op, 2 µs per |
| 782 | canvas command; `opsCostMs` in `cpu-budget.ts` and its twins). A deferrable task waits while either window is spent. |
| 783 | The busiest widget of the corpora (`htmlbubbles-ported/06-trip-lisbon/10-ana-bare`, a list redrawn whole) costs |
| 784 | 82 ms per second; 1000 elements moved every frame get about 6 frames a second instead of 60. |
| 785 | - **Bitmaps.** The tweb audit (`docs/changes.md`, "Bitmaps a widget makes the page hold are bounded") found that |
| 786 | nothing bounded the bitmaps a widget makes the page hold: four canvases of 16384² grew a browser by ~16 GB, and a |
| 787 | data: image is decoded at the size its header claims (2 KB of a one-colour PNG is a real 4096², 64 MB; the attribute |
| 788 | cap bounds the bytes, not the pixels). The audit capped both at 4096² (64 MB) in the renderer and in `checkUrl`; by |
| 789 | the rule above they are lower. The corpora's canvases, run at a devicePixelRatio of 3, hold at most 0.41 M pixels |
| 790 | together, but the guide tells authors to scale a canvas by devicePixelRatio, and one across a whole 430 px bubble at |
| 791 | 3× is 2.3 M: so the validator stops a widget whose canvases would hold more than 2048² together (a new canvas is |
| 792 | 300 × 150; its `width` and `height` attributes and the shim's `r` command size it; removing it refunds it). The |
| 793 | renderer keeps the audit's 4096² as its own backstop for compat and for any path past the validator. A data: image |
| 794 | is a URL, so past 1024² it gets the placeholder as a refused URL does, and the widget goes on: the corpora's largest |
| 795 | is 40 × 20, and an image across a 320 px bubble at 3× fits. |
| 796 | - **compat keeps the old caps** and never stops: tests, tooling, and the measuring runs of the stress kit |
| 797 | (`packages/stress`), which must see the cost past the limits. |
| 798 | - **The client teams' numbers** (v0.6.0, 2026-11-02). The stress kit ran on a Redmi Note 8T and a Galaxy A55 |
| 799 | (Android, TwidgetCore), an iPhone Air (iOS, the client's own runtime), tdesktop on an i9 and the web (the reference), |
| 800 | plus seven real widgets on the Redmi in strict. Counted limits must not depend on the device, so they were set now: |
| 801 | 2000 nodes (the heap no longer stops first, since the flush goes out in parts: Android stopped a 2000-node load, the |
| 802 | 32-bit web and tdesktop a 4000-node one), 4000 canvas commands, 128 layout queries per task, and the heavy-box limit |
| 803 | (its own section). Limits in time only slow a widget down and stop it on a hang: the slice is the whole `cpuLimitMs` |
| 804 | ("Throttle, not kill"), a layout query's time no longer stops it below the 1000 ms guard, and the renderer's frame |
| 805 | time is no stop (the draft's three frames over 50 ms would have stopped widgets within every limit on the Redmi: |
| 806 | `complex-text/8192` 80 ms a change, `text-volume/49152` 99 ms, `dom-static/2000` 77 ms). The prices (300 ms/s of JS, |
| 807 | the 100 ms/s window at 25/2 µs) stay: the window slows a widget alike on every device; they were checked only on |
| 808 | strong and middle devices and can move either way later. |
| 809 |
| 810 | ### Heavy boxes: 16, of them 2 with backdrop-filter (2026-11-02) |
| 811 |
| 812 | The count of heavy boxes the strict limits left for the stress kit's numbers (Artem, 2026-11-02, after the client teams' |
| 813 | runs on five devices; the rule was the paint-limits draft's §3). A blurred shadow, a filter, a backdrop-filter or |
| 814 | transparency on a box that changes is what costs a renderer, not the number of boxes or the rate of change as such: |
| 815 |
| 816 | | Renderer time a frame, 16 moving heavy boxes (stress kit, measure pass) | A55 | Redmi Note 8T | iPhone Air (hot) | tdesktop (CPU) | |
| 817 | |---|---|---|---|---| |
| 818 | | `shadow-moving/16` | 3.4 ms | 4.5 | 5.0 | 3.7 | |
| 819 | | `ars-cell/16` (every effect) | 4.8 | 5.3 | 5.9 | 8.1 | |
| 820 | | `opacity-moving/16` | 2.9 | 3.5 | 4.2 | 1.2 | |
| 821 | | `filter-moving/16` | 3.6 | 3.5 | 3.6 | 7.4 | |
| 822 | | `ars-cell/64`, for comparison | 16.6 | 21.4 | 29.7 | 30.7 | |
| 823 |
| 824 | 16 cost 1–8 ms a frame on all four clients, under half a 60 Hz frame even on the Redmi and the hot iPhone; 64 cost more |
| 825 | than a frame everywhere. Two backdrop-filter panels cost the iPhone 7.3 ms (16: 14.1 ms) and tdesktop, which blurs on the |
| 826 | CPU, 3.9 ms (16: 25.4 ms). The corpora's largest real use was 40 heavy boxes in one widget and 340 of 346 had at most |
| 827 | 16 (measured on 2026-10-28 over the corpora and the conformance set). |
| 828 |
| 829 | - **The rule** (`packages/core/src/shared/paint-policy.ts`, `tests/fixtures/paint-policy.json`). A box is what the |
| 830 | renderer lays out: an element whose `display` is not `none`, under no `display: none` ancestor (`display: contents`, |
| 831 | out of profile 1 anyway, builds none), and a `::before` / `::after` whose `content` is not `none` / `normal`; SVG |
| 832 | elements alike; the widget's root and body count, the renderer's own nodes do not. A box is heavy when its computed |
| 833 | `box-shadow` has a layer with a blur above 0 (inset too), its `filter` or `backdrop-filter` is not `none`, its |
| 834 | `opacity` is below 1 (unless it is a `<button>` that is disabled or pressed: below), or while an animation runs on |
| 835 | it that changes `filter`, `backdrop-filter` or `opacity`, or |
| 836 | `box-shadow` through a blurred layer: a CSS animation from `animationstart` to its end or cancel, a transition likewise, |
| 837 | a Web Animation while `running`, whatever the value at the moment. The value counts, not the picture (`opacity: .999`, |
| 838 | `brightness(1)`); `visibility`, clipping, being on screen, `transform` and engine layers do not. An animation of |
| 839 | shadows without blur (a ring, an inset fill that pulses: `htmlbubbles-ported/10-game-night/08-kai` sparkles 23 cells |
| 840 | so) costs what the ring costs, so it is not heavy; a keyframe list that leaves the first or last value to the box's |
| 841 | own is. |
| 842 | - **A disabled or pressed `<button>`'s opacity is its own dimming** (2026-11-02, with the limit): the UA layer's |
| 843 | client-styled button dims a disabled one to `--tg-button-disabled-opacity` (0.5) and a pressed one to |
| 844 | `--tg-button-pressed-opacity` (0.7), so a calendar with 17 past days disabled or a poll after the vote would stop. |
| 845 | The `opacity` of a `<button>` with the `disabled` attribute or held down (`:active`) does not make it heavy, the |
| 846 | author's own as well (the same static dimming); a blurred shadow, a filter, a backdrop-filter or an animation of its |
| 847 | opacity still do, and its `::before` / `::after` are boxes of their own. The stopped frame keeps a disabled button's |
| 848 | dimming. |
| 849 | - **At most 16 at once, of them at most 2 with `backdrop-filter`.** Past either the widget stops, as at a counted cap: |
| 850 | `Paint limit exceeded: 17 boxes with shadows, filters or transparency (max 16)` or `... 3 boxes with backdrop-filter |
| 851 | (max 2)`, the diagnostic `paint-limit` / `backdrop-limit`. Stop rather than drop the effects of the boxes past the |
| 852 | limit: the author sees the cause at once and the look does not depend on the DOM order. A tightening of profile 1 |
| 853 | (`L2` in `profile.json`, `limit.paint-heavy`, `limit.paint-backdrop`), not profile 2: widgets were not launched. |
| 854 | - **Counted by the renderer, not the validator.** The validator knows no cascade: an upper bound from the rightmost |
| 855 | compound of each selector inflated small counts (2 → 26, 0 → 19 in the corpora) and knows nothing of `:hover` and |
| 856 | animations. The computed style is the same on every client, so a widget passes or stops everywhere alike, and the |
| 857 | fixture makes the count the same. When: before each frame the renderer draws, after a batch (counted whole, never op by |
| 858 | op), when an animation of the rule starts or ends, and when the cascade changes without an op (the theme, the safe |
| 859 | area, the bubble's width, `:hover`, `:active`). |
| 860 | - **The framework's WebView renderer** (`renderer/core.ts`: iframe, Shadow DOM, WKWebView, Android WebView) keeps the |
| 861 | count incrementally and checks it in `requestAnimationFrame`: a batch marks the subtrees it can reach (the parent's |
| 862 | with a sibling combinator or a structural pseudo-class in the widget's sheets), a stylesheet, the theme, the safe area |
| 863 | and the viewport recount everything, `pointerover` / `out` and a press recount the elements whose `:hover` / |
| 864 | `:active` changed, the animation events and the renderer's Web Animations feed rule 5. Inline styles that touch no |
| 865 | heavy property (transform, positions, colours) mark nothing, unless a selector reads the style attribute. Cost in |
| 866 | Chromium on an M5 Max, 1000 boxes all changed every frame: nothing for style ops of `transform`, +0.1 ms a frame when |
| 867 | the style attribute is rewritten, 0.65 ms when every box changes class (2.7 ms when every box also matches a |
| 868 | `::before` rule), next to 1.3–4.3 ms of the renderer's own main-thread work there; the main-thread window lets such |
| 869 | a widget about 4 frames a second. Past a limit it reports `{ type: 'limit', code, count }` (`docs/protocol.md`). |
| 870 | - **A client's own renderer** counts the same rule against the fixture and calls the seam's `limitExceeded(code, |
| 871 | count)` (`Renderer.swift`, `Renderer.kt`, `renderer.h`); every host turns it into the stop (`docs/integration.md`). |
| 872 | - **The stopped widget is drawn without the effects**: no blurred shadow (a layer without blur stays), filter, |
| 873 | backdrop-filter or transparency, animations paused, then the usual badge. A fully transparent box is hidden rather |
| 874 | than turned opaque (an overlay faded out stays out of sight). The frozen frame then costs nothing while the chat |
| 875 | scrolls. The WebView renderer draws it so before the frame in which the count went past the limit (for a CSS |
| 876 | animation, the frame its start event arrives in, one after the engine starts it), with a first cascade layer of |
| 877 | `!important` declarations and the elements' own inline values replaced, and takes no more ops. |
| 878 | - **compat counts nothing**: the stress kit's measuring runs must see the cost past the limits. |
| 879 | - **Corpora.** Six widgets went past 16, each muting with `opacity`: `showcase/travel/04-weather` and |
| 880 | `life/01-fitness-rings` (18), both `generated/…/12-…countdown` (twinkling stars), `gestures` `08-wheel-picker-y` (34) |
| 881 | and `07-range-slider-x` (18). They mute with colour now (`rgba()`, `--tg-theme-hint-color`, `fill-opacity` / |
| 882 | `stroke-opacity`), which looks the same. The most left in a widget is 14. |
| 883 | - **Not decided here**: a renderer's frame time as a stop (the draft's §4.3: "50 ms three frames in a row" would stop |
| 884 | widgets on the Redmi that live within every limit elsewhere, and a stop must not depend on the device; rejected), the |
| 885 | renderer's frame cost in the quota (the draft's §4: a slowdown, later), and the validator's clamps of shadow layers, |
| 886 | blur radii and filter functions (the draft's §5). |
| 887 |
| 888 | ### Off-screen pause mirrors a background tab |
| 889 |
| 890 | - The host knows visibility, the sandbox does not: `setVisible(false)` stops |
| 891 | frame requests (one is made on return if the shim asked meanwhile), runs |
| 892 | timers at 1 Hz through the same deferred queue the CPU quota uses, and gives |
| 893 | the shim `document.hidden` / `visibilitychange` — the signal widgets are |
| 894 | already written against (the clock and the generated video players pause on |
| 895 | it). Timers set while hidden are armed with `max(delay, 1000)`; due ones are |
| 896 | batched into one wake-up; intervals never catch up on missed ticks. |
| 897 | - Who calls it: the web dev UI from an `IntersectionObserver` on the iframe |
| 898 | plus the page's own `visibilitychange`; the iOS host from the container |
| 899 | view's window attachment combined with the owner's call (the demo wires |
| 900 | `scenePhase`); the Android host from the WebView's attach state combined |
| 901 | with the owner's call. Snapshot-and-drop after N minutes hidden |
| 902 | (`native-port-notes.md`, Lifecycle) is still open; the hidden state it needs |
| 903 | now exists. |
| 904 |
| 905 | ## QuickJS for the web and Node from our fork (Oct 2026) |
| 906 |
| 907 | - The npm wasm build (`@jitl/quickjs-ng-wasmfile-release-sync` 0.32.0) vendors |
| 908 | quickjs-ng 0.12.1, which frees a mapped `arguments` object's variable refs too |
| 909 | early (quickjs-ng#1400): any non-strict widget function reading `arguments` |
| 910 | plus enough allocation to run the GC corrupts the heap and aborts the worker |
| 911 | (`gc_scan`, `mark_weak_map_value`, out-of-bounds; the assertion moves with the |
| 912 | heap layout). The native builds (quickjs-ng 0.17) were not affected; ASan runs |
| 913 | of the same widget on the Swift and C++ cores are clean. |
| 914 | - `packages/quickjs-wasm` (`@telegram/widget-sandbox-quickjs`) is that variant |
| 915 | rebuilt from the TelegramMessenger/quickjs fork: `build.sh <fork checkout>` |
| 916 | amalgamates the fork with its own `qjs`, applies quickjs-emscripten's one |
| 917 | quickjs-ng patch and compiles quickjs-emscripten 0.32.0's `interface.c` |
| 918 | (adapted to quickjs-ng 0.17's ArrayBuffer and interrupt-handler signatures) |
| 919 | with the variant's emcc flags. `@jitl`'s FFI and `quickjs-emscripten-core` |
| 920 | are unchanged; the output in `dist/` is committed, so the web build and CI |
| 921 | need no emcc (it is excluded from the repository-wide `dist` ignore rule on |
| 922 | purpose). `dist/QUICKJS_VERSION` names the fork commit; `build.sh` defaults to |
| 923 | the `packages/ios/Sources/CQuickJS/quickjs` submodule, so the wasm and the |
| 924 | native builds come from the same commit. |
| 925 | - Reproducible since v0.6.0 (Nov 2026): the same fork commit and the pinned |
| 926 | emscripten (6.0.12; `build.sh --docker` uses the emsdk image by digest) give |
| 927 | the same bytes on any machine. Before, `dist/` differed from a rebuild only in |
| 928 | the amalgamation's `__FILE__`, the random temporary directory in the assert |
| 929 | messages of the data segment; `-ffile-prefix-map` removes it (the wasm was |
| 930 | rebuilt once for that, 64 bytes shorter, nothing else changed), and the |
| 931 | version string is the commit's first 7 hex digits instead of `git describe`. |
| 932 | `dist.sha256` lists every `dist/` file; `build.sh --check` rebuilds in a |
| 933 | temporary directory and compares (the `wasm.yml` job on the branch `claude/ci` when an input changes), and |
| 934 | the unit suite checks `dist/` against the list and `QUICKJS_VERSION` against |
| 935 | the submodule on every commit. Checked: macOS arm64 with Homebrew's |
| 936 | emscripten 6.0.12 and the emsdk 6.0.12 image on Linux arm64 give identical |
| 937 | files. A new emscripten is a deliberate change: both pins in `build.sh`, then |
| 938 | `dist/` and `dist.sha256` in one commit. |
| 939 | - Behaviour change, now the same on every platform: out-of-memory is |
| 940 | uncatchable in quickjs-ng 0.17, so a widget that hits the cap is stopped |
| 941 | (`Memory limit exceeded`, last render frozen) even inside `try/catch`. |
| 942 | - The web validator is not in this wasm: it runs in the host page's own JS |
| 943 | engine on the main thread (`WidgetHost`); only widget code runs in the |
| 944 | worker's QuickJS heap. |
| 945 |
| 946 | ## User activation for privileged bridge calls (Oct 2026) |
| 947 |
| 948 | - `openLink`, `sendMessage` and any future privileged bridge method act for the |
| 949 | user, so a widget may only call them from the handler of a real gesture: one |
| 950 | physical pointer press (`pointerdown` … `click`/`dblclick`) on the visible |
| 951 | widget unlocks one call. Keys never do (no keyboard for widgets, "Profile |
| 952 | v1" below), nor does the click a key activates (`detail` 0). Timers, frames, |
| 953 | promise jobs after the task, scripted `click()`/`dispatchEvent` and hidden |
| 954 | widgets get an `activation-blocked` diag instead. `ready` stays free. |
| 955 | - A finger's or a pen's press is a gesture from its `pointerup` on (Oct 2026, after |
| 956 | v0.2.3), as HTML's activation-triggering input events have it: its `pointerdown` may |
| 957 | still become the chat's scroll, which ends it in `pointercancel`, and a swipe that |
| 958 | started on a widget let it copy text and send a request. The renderer core marks |
| 959 | such a `pointerdown` not `trusted`, nor a mouse event of a finger or a pen still |
| 960 | down: the `mousedown` a pen's contact makes at once, its barrel button pressed or |
| 961 | let go with the tip down (by the pointer whose buttons changed last: a mouse |
| 962 | pressed while a finger is held keeps its own `mousedown`; by the input's own |
| 963 | `pointerType`: a mouse that |
| 964 | plays a finger in the dev app's phone mode keeps its press), so the rule is one |
| 965 | JS change for every host. The counters no longer see that `pointerdown`, so every |
| 966 | host starts a new gesture at the renderer's `gesture` claim, which comes before |
| 967 | the press's events for every primary press, listened to or not, and at every |
| 968 | `pointerdown` event, trusted or not, which a second finger (no claim) has |
| 969 | (`GestureCounter.pressBegan`): without it a finger's release and click after a |
| 970 | press that ended without a click (a drag) continued that press's spent gesture. |
| 971 | - Native glue (Swift, Kotlin, C++): the host numbers gestures from renderer |
| 972 | events marked `trusted` and hands the number to the engine with the event; |
| 973 | the engine opens the gesture for that event's task only and consumes it with |
| 974 | the first privileged call. The renderer is trusted code and the only source |
| 975 | of events, but a WebView renderer also sees events its own page dispatched, |
| 976 | so the hosts take its word (`isTrusted`) like the web host does. |
| 977 | - Web: the worker shares a thread with nothing trusted, but it is a separate |
| 978 | realm whose glue we would rather not have to trust with this decision, so |
| 979 | the main-thread host decides. The renderer marks an event `trusted` only |
| 980 | when the DOM event's `isTrusted` is true; the host numbers gestures from |
| 981 | trusted events only, sends the number with the event, and accepts a |
| 982 | privileged `bridge` message only when it carries a gesture the host issued, |
| 983 | has not consumed and issued within 5 s. A worker that lies can at most spend |
| 984 | a real gesture once, which is what the gesture allowed anyway. |
| 985 | - One policy in four copies: `packages/core/src/host/user-activation.ts`, |
| 986 | `UserActivation.kt`, `WidgetHost.gesture(for:)` + `SandboxEngine` in Swift, |
| 987 | `GestureCounter` (`widget_host.h`) + `SandboxEngine` in C++, each with its tests |
| 988 | (`user-activation.test.ts`, `UserActivationTest.kt`, `UserActivationTests`, |
| 989 | `bridge_and_timers`); attack widgets `corpus/attacks/activation-*.html`. |
| 990 |
| 991 | ## Desktop C++ core (`packages/desktop/`, Oct 2026) |
| 992 |
| 993 | Written for the tdesktop question: the part of |
| 994 | the stack that is new on a Qt/C++ client is the glue, so the glue was ported |
| 995 | first and alone, as a library with no renderer. |
| 996 |
| 997 | - **No Qt in the core.** `std::thread` cannot choose a stack size, so |
| 998 | `js_thread.h` is a 150-line pthread/`_beginthreadex` loop (tasks, timers, |
| 999 | `sync`) rather than a `QThread`; the engine's delegate is a plain abstract |
| 1000 | class and the host hops to its UI thread itself. tdesktop can wrap it in Qt; |
| 1001 | the Node-style harness and the tests do not need Qt at all, which keeps the |
| 1002 | attack and compat runs a `cmake --build` away on any machine. |
| 1003 | - **No JSON library either.** The glue parses only what the shim sends |
| 1004 | (`[id, delay]`, `[method, args]`, `nextScript`, `stat`, Intl requests) and |
| 1005 | builds the boot config; `json.h` is a 300-line strict parser with a depth |
| 1006 | bound, which is what hostile input needs and all a dependency would add. |
| 1007 | - **quickjs-ng is compiled from `packages/ios/Sources/CQuickJS`**, through the same |
| 1008 | `qjs_shim.c` (quickjs.h's `JS_UNDEFINED` & co are C compound literals, not |
| 1009 | C++). One engine, one shim, one set of sources, now on four platforms. |
| 1010 | - **Validator unchanged**: the same `validator-bundle.js` in a second trusted |
| 1011 | runtime (`TrustedValidator`), exactly as on iOS and Android. 256 MB heap, |
| 1012 | 6 MB QuickJS stack on an 8 MB thread (6 340 JS frames in release — css-tree |
| 1013 | needs > 40). |
| 1014 | - **Fourth `CpuBudget` copy** (`cpu_budget.cpp`) against the shared fixture; |
| 1015 | the engine (`sandbox_engine.cpp`) is `SandboxEngine.swift` line for line: |
| 1016 | same `__host` kinds, same deferred queue, same 1 Hz hidden timers, same |
| 1017 | kill messages. |
| 1018 | - **`Intl` is an interface** (`IntlProvider`); `BasicIntl` is the fallback without |
| 1019 | locale data: en-US formatting with CLDR plural rules and a few dozen languages' |
| 1020 | number separators, checked against V8 on the `basic` cases of |
| 1021 | `tests/fixtures/intl-cases.json`. A product host plugs `QLocale`/ICU in — |
| 1022 | deliberately not done here, to keep the core Qt-free. |
| 1023 | - **Harness leak scan instead of a canary.** Without a renderer there is no |
| 1024 | network to hit, so `twidget-run --attacks` inspects the *validated* ops: any |
| 1025 | non-`data:` URL in an attribute, any `url()`-family function not pointing at |
| 1026 | `data:`/`#`, any `@import` is a leak. First run flagged three false |
| 1027 | positives — external URLs inside `data:image/svg+xml` payloads and a |
| 1028 | `"http://…"` string token in a CSS custom property — all inert in browsers |
| 1029 | (SVG-as-image loads nothing external; a string is not a `url()`), confirmed |
| 1030 | by the Playwright suite's zero canary hits on the same files. The scanner now |
| 1031 | reports the data: cases as notes. A native, non-browser renderer would have to |
| 1032 | honour the same two properties; that is a constraint on option D in the |
| 1033 | feasibility note, not on the validator. |
| 1034 | - Results on the first green run: 21 tests / 180 checks; compat 21/21 and |
| 1035 | generated 40/40 load without uncaught errors; attacks 89, 0 leaks, one |
| 1036 | expected kill (`fallback-at-boot.html`). Sandbox bundle boot: tens of ms in |
| 1037 | release quickjs-ng from source (bytecode still open). |
| 1038 |
| 1039 | ## One QuickJS for every platform: the TelegramMessenger/quickjs fork (Oct 2026) |
| 1040 |
| 1041 | - `packages/ios/Sources/CQuickJS/quickjs` is a git submodule of the |
| 1042 | TelegramMessenger/quickjs fork (quickjs-ng 0.17 plus fixes and speed-ups), |
| 1043 | replacing the vendored quickjs-ng 0.17.0. The iOS/macOS package, the Android |
| 1044 | library, the desktop core, `packages/tools/qjsc` and the web/Node wasm |
| 1045 | (`packages/quickjs-wasm`) all build from it; clone with |
| 1046 | `git submodule update --init` (SwiftPM does it for package dependencies). |
| 1047 | - The fork's interrupt handler receives the `JSContext`, not the runtime; the |
| 1048 | C++ and JNI glue follow. |
| 1049 | - Every `.qbc` was regenerated with qjsc built from the fork; |
| 1050 | `BundledBytecodeTests` (Swift) fails when a shipped `.qbc` is not exactly what |
| 1051 | the engine compiles from the shipped `.js`. |
| 1052 | - The fork makes out-of-memory uncatchable everywhere; the memory attacks that |
| 1053 | catch the error are now stopped like the ones that do not. |
| 1054 | - Fork master c24d6b0 (2026-10-16) makes the uncatchable state a property of |
| 1055 | the runtime, not only a bit on the error object: until the embedder takes the |
| 1056 | exception with `JS_GetException` outside any JS call, no catch block, Promise |
| 1057 | executor, thenable, async generator, disposer, iterator `return()` or |
| 1058 | `Error.prepareStackTrace` can observe it, and every interrupt poll raises it |
| 1059 | again. Before it, `for (;;) new Promise(function () { for (;;) {} })` turned |
| 1060 | the CPU interrupt into a rejection and never returned to the glue (found by |
| 1061 | the fork review below). The glue needs no change: every host already calls |
| 1062 | `JS_GetException` at top level. Bytecode format unchanged. |
| 1063 |
| 1064 | ### The QuickJS fork review (Oct 2026) |
| 1065 |
| 1066 | The TelegramMessenger/quickjs fork at 7d1085a is upstream quickjs-ng 9b06171 |
| 1067 | (v0.17.0 plus 21 upstream commits) plus 22 commits of its own: allocator arenas |
| 1068 | and slabs, inline interpreter paths, early allocation of shapes, dtoa changes. |
| 1069 | All 22 were read against upstream; **the fork is accepted** and every commit |
| 1070 | kept. No memory-safety bug was found; three medium-risk commits (27787d3 slabs, |
| 1071 | e65afb8 zombie shapes, ee1ef12 inline properties) carry follow-ups rather than |
| 1072 | blockers. Checked: test262 at the same 40 of 82 220 failures as upstream; the |
| 1073 | fork's `tests.conf` and `api-test` on Release and under ASan + UBSan (Apple |
| 1074 | clang does not define `__SANITIZE_ADDRESS__` under `-fsanitize=address`, so the |
| 1075 | flag has to be passed by hand or the arenas stay on and ASan is blind inside |
| 1076 | small blocks); a differential dtoa run (the Grisu3 change is right, matching |
| 1077 | V8, 54 powers of two differ from upstream); instruction counts over the desktop |
| 1078 | corpora (fork −8.7 % against upstream); footprint after 30 freed runtimes |
| 1079 | (7.5 MB against 13.6 MB, the slabs). The one release blocker was upstream's, |
| 1080 | not the fork's: the CPU interrupt swallowed by Promise executors and the other |
| 1081 | constructs above, fixed by the patch now in fork master c24d6b0, which the |
| 1082 | submodule pins. Still owed: fuzzing of the allocator and interpreter commits |
| 1083 | (a differential fuzz against upstream over the corpora exists as a harness, not |
| 1084 | as CI), test262 on CI, and a second pair of eyes on the uncatchable-exception |
| 1085 | patch from the fork's owner. |
| 1086 |
| 1087 | ## Bytecode precompilation of the bundles (Oct 2026) |
| 1088 |
| 1089 | - **Build time, not first launch.** `packages/core/scripts/build-native-bundles.ts` compiles |
| 1090 | `sandbox-bundle.js`, `validator-bundle.js` and `libs/*.js` to `.qbc` with |
| 1091 | `packages/tools/qjsc/qjsc.c`, built on the fly from the vendored |
| 1092 | `packages/ios/Sources/CQuickJS` (one quickjs-ng copy for iOS, macOS, Android and the |
| 1093 | desktop core, all 64-bit little-endian, so one set of blobs serves every |
| 1094 | port). A first-launch cache was rejected: it keeps the slow first boot and |
| 1095 | adds cache invalidation code to three ports for no gain, since the bundles |
| 1096 | never change at runtime. |
| 1097 | - **A stale blob is refused, never run.** The `TWQB` header carries the |
| 1098 | source's length and FNV-1a 64 hash; `qjs_eval_bytecode` compares them with |
| 1099 | the `.js` the host would otherwise evaluate and quickjs-ng checks its own |
| 1100 | `BC_VERSION`. Any mismatch is an exception; the glue falls back to the source |
| 1101 | and reports a `bytecode` diag. A test on each platform boots a widget with a |
| 1102 | bundled library and asserts `(bytecode)` in the `boot` and `library` diags and |
| 1103 | no fallback, so a `.js` committed without its `.qbc` fails the tests, not a phone. |
| 1104 | - **Only our own code goes through `JS_ReadObject`.** It has no verifier |
| 1105 | (quickjs.h says so); widget scripts keep going through the parser. Debug |
| 1106 | info is kept for shim stack traces, source text is stripped. |
| 1107 | - **What it buys.** Desktop core, release quickjs-ng: sandbox boot 38–74 ms → |
| 1108 | 20–22 ms, Chart.js 18 → 4 ms. The remainder is the bundle's top-level |
| 1109 | execution (building the shim's DOM classes); QuickJS cannot snapshot a heap, |
| 1110 | so that part stays. Cost: ~1.6 MB of `.qbc` per platform (1.2–1.5× the |
| 1111 | minified source). |
| 1112 |
| 1113 | ## Chat feed on iOS: pools, one WebKit environment, validation off the main thread (Oct 2026) |
| 1114 |
| 1115 | `docs/chat-feed-ios.md` has the design and the numbers; the decisions: |
| 1116 |
| 1117 | - **Optimise the glue, not the bundles.** Every gain came from the host side |
| 1118 | (`RendererEnvironment`, `Pools.swift`, `WidgetHost.Options`); the three JS |
| 1119 | bundles, the validator and the invariants are unchanged, so the web, Android |
| 1120 | and desktop hosts keep working and can port the same ideas (Android: |
| 1121 | `WebView` pool + `SandboxEngine.prewarm`; the C++ core already separates |
| 1122 | runtime creation from boot). |
| 1123 | - **Flags, not a rewrite.** `sharedWebKit`, `sharedValidatorThread`, `pools`, |
| 1124 | `parallelBoot`, `asyncValidation` are options with the old behaviour as the |
| 1125 | default of the single-widget path; the feed demo measures `baseline` against |
| 1126 | `max` in one build. A product turns on what it needs; the pools are filled |
| 1127 | by the app (`WidgetWarmup.prewarm`), never implicitly. |
| 1128 | - **Engines are never recycled, validators are, renderers are not (yet).** A |
| 1129 | QuickJS runtime that ran widget code is dead on `destroy()`; a validator |
| 1130 | context ran only trusted code and is reused with a fresh |
| 1131 | `__twValidator.create()`; a `WKWebView` could be reused with a `reset` op in |
| 1132 | the renderer, but that would share one document (and origin) between widgets |
| 1133 | sequentially, weakening the per-widget origin of invariant 6 — left as an |
| 1134 | option to discuss, not done. |
| 1135 | - **Order over speed in async validation.** Ops and sync queries go through |
| 1136 | one serial validator thread and then one serial main queue; a query |
| 1137 | therefore always follows the ops flushed before it. The alternative — a |
| 1138 | validator thread per widget — was rejected: a chat of 40 widgets would run |
| 1139 | 80 threads for no gain. |
| 1140 | - **Snapshot-and-drop is the list's policy, not the host's.** `WidgetHost` |
| 1141 | only offers `snapshot(completion:)`; the feed decides when (beyond |
| 1142 | `keepScreens` screens, after scrolling settles or every 0.5 s during a |
| 1143 | flick) and keeps the JPEG. The host keeps the off-screen pause |
| 1144 | (`setVisible`) as before. |
| 1145 | - **Heights are the app's problem.** The renderer reports sizes; the feed |
| 1146 | remembers them per widget and refuses to shrink a bubble before `loaded`. |
| 1147 | A messenger would get the height from the server with the message. |
| 1148 |
| 1149 | ## Android validator pool and the renderer bench (Oct 2026) |
| 1150 |
| 1151 | `docs/android-renderer-bench.md` has the numbers; the decisions: |
| 1152 |
| 1153 | - **The validator half of the iOS pools, nothing else yet.** `ValidatorPool`, |
| 1154 | `WidgetHost.Options.pools` / `sharedValidatorThread`, `TrustedValidator.background` |
| 1155 | / `reset` / `sharedThread` mirror `Pools.swift` and `TrustedValidator.swift` |
| 1156 | one to one; renderer and engine pools stay open. The pool is filled by the |
| 1157 | app (`ValidatorPool.prewarm`), never implicitly, and a pooled validator is |
| 1158 | recycled on `destroy()` with a fresh `__twValidator.create()`. |
| 1159 | - **It buys start-up, not memory**, and the doc says so: the bundle evaluation |
| 1160 | (~17 ms on a phone) leaves the main thread and the bubble's critical path, one |
| 1161 | thread serves every validator; a live widget still owns a ~3.7 MB validator |
| 1162 | context. One context per process with an instance per widget would halve |
| 1163 | that, but it is a change to `validator-bundle.ts` and every platform's `.qbc`, |
| 1164 | so it is written down as the next step rather than done here. |
| 1165 | - **Measure the renderer as a difference.** The bench's `none` renderer (engine + |
| 1166 | validator, no renderer) is the floor every renderer is compared against; on a |
| 1167 | phone the engine floor is 6.3 MB per bubble, WebView adds ~14 (mostly graphics), |
| 1168 | Blitz ~7 (its CPU bitmap and the texture of it), litehtml ~1.3. |
| 1169 |
| 1170 | ## Renderer choice and the core: two tracks, one profile (Oct 2026) |
| 1171 |
| 1172 | (The record of the three-way comparison; the prototypes it weighs are frozen since 2026-10-30, "The renderer |
| 1173 | prototypes are frozen" below.) |
| 1174 |
| 1175 | Written after the Android renderer bench (`docs/android-renderer-bench.md`), |
| 1176 | the three-way renderer matrix (`docs/blitz-experiment.md`, |
| 1177 | `docs/litehtml-renderer.md`, `corpus/common`) and the iOS chat feed |
| 1178 | (`docs/chat-feed-ios.md`). |
| 1179 |
| 1180 | - **The core is renderer-independent, by evidence, not by design intent.** |
| 1181 | Three renderers (WebView, Blitz, litehtml) run on five hosts behind the |
| 1182 | `Renderer` seam with the three JS bundles, the validator and the invariants |
| 1183 | untouched; the attack suite is at zero on every combination. Work on the |
| 1184 | core (bytecode, pools, snapshot-and-drop, validator memory, engine boot) |
| 1185 | proceeds independently of which renderer a platform ends up with. |
| 1186 | - **A WebView in every bubble is not the product path on Android or |
| 1187 | Telegram Desktop.** Android, phone: the first WebView in the process costs |
| 1188 | 168 ms of main-thread stall and ≈ 120 MiB that never come back, then |
| 1189 | ≈ 14 MiB per live bubble, most of it graphics memory the emulator does not |
| 1190 | show; prewarming moves the stall to app launch, it does not remove it. |
| 1191 | tdesktop: inline is unreachable on Linux (WebKitGTK helper process) and a |
| 1192 | whole Edge runtime on Windows. On iOS the |
| 1193 | pooled WKWebView path measures as good enough (ready before display, |
| 1194 | 126 MB peak for 120 bubbles) and stays a candidate there. |
| 1195 | - **Once the WebView is out, the engine is the biggest per-bubble cost.** |
| 1196 | Phone, 20 live bubbles, over the `none` floor: engine + validator 6.3 MB, |
| 1197 | litehtml ≈ 1.3, Blitz ≈ 7 (its bitmap and texture; the engine is the |
| 1198 | bigger half of a Blitz bubble too). The widget's own heap is 1.7 MB of that; |
| 1199 | the rest is the runtime, the validator context (≈ 3.7 MB of css-tree per |
| 1200 | live widget) and two threads. A shared QuickJS runtime with one context per |
| 1201 | widget was rejected: one memory limit and one interrupt handler for all |
| 1202 | widgets lets one widget starve the others. The core track's levers are |
| 1203 | therefore *fewer live runtimes* (snapshot-and-drop, pools, fast boot from |
| 1204 | bytecode) and *one validator context per process with an instance per |
| 1205 | widget*, not a smaller runtime. |
| 1206 | - **Per platform for the implementation, one profile for the promise.** A |
| 1207 | platform may pick its renderer, but the widget profile must be one across |
| 1208 | platforms: the same file has to draw the same picture on every client or |
| 1209 | the format is not a format. The profile is the intersection of the chosen |
| 1210 | renderers; `corpus/common` (32 widgets all three draw alike) is that |
| 1211 | intersection today and the acceptance test for any renderer on any |
| 1212 | platform. Every extra renderer family narrows the profile, which is the |
| 1213 | argument for converging on one native engine everywhere (Blitz and |
| 1214 | litehtml both already build on all five hosts, wasm included) and keeping |
| 1215 | the WebView for the expanded widget, not the bubble. |
| 1216 | - **What moves with the renderer** and belongs on its checklist, not in the |
| 1217 | core: the answers to layout queries and `measureText`, the canvas command |
| 1218 | stream, event delivery and form state, and the replacement for invariant 6 |
| 1219 | (a native renderer has no CSP and no separate process, so it needs a layout |
| 1220 | timeout, `catch_unwind` around every call, and a memory cap per document; |
| 1221 | the 160–190 ms layout outlier on an emoji font fallback in |
| 1222 | `docs/blitz-experiment.md` is the DoS vector that timeout exists for). |
| 1223 | - **Options, ranked.** (1) Blitz as the product renderer: the only open |
| 1224 | engine above litehtml's profile (grid, var, calc, shadows, 2D transforms) |
| 1225 | at 3 ms per card; gaps are concrete (canvas on vello, forms, CSS into SVG, |
| 1226 | `overflow: auto`, 3D) but it is beta, Rust in three client builds, and |
| 1227 | 14 MB of `.so`. (2) Hybrid by capability: the validator sees the whole DOM |
| 1228 | and CSS before rendering, so "uses canvas / 3D / `<input type=range>`" is a |
| 1229 | deterministic flag; such widgets get a static native card in the bubble and |
| 1230 | the full WebView on tap, like a Web App — one prewarmed WebView per app, |
| 1231 | never a hundred. (3) litehtml with a reduced CSS profile: cheap, but 17 of 40 generated widgets use grid and that is not fixable in a |
| 1232 | sanitizer. (4) A renderer of our own on platform text (variant D): months, |
| 1233 | not before Blitz has failed. Recommendation: (2) as the product shape with |
| 1234 | (1) as its renderer, conditional on the measurements below. |
| 1235 | - **Not measured yet, and the recommendation rests on it:** the chat feed on |
| 1236 | Blitz (the iOS feed takes no `--blitz`), Blitz on `corpus/compat` (Chart.js |
| 1237 | and D3 need the canvas), 3× rasterisation on a device (CPU vs vello on the |
| 1238 | GPU), Blitz's size after strip, a low-end phone for the WebView stall, the |
| 1239 | renderer and engine pools on Android. |
| 1240 |
| 1241 | ## Opt-in WebKit view reuse (Oct 2026) |
| 1242 |
| 1243 | `WidgetHost.Options.recyclesRenderers` returns shared-environment WebKit renderers |
| 1244 | on destruction when pools are enabled. It remains off by default. The QuickJS |
| 1245 | runtime is terminated; it is never reused after running a widget. |
| 1246 |
| 1247 | A returned WKWebView replaces its current history entry with a new trusted renderer |
| 1248 | document at a fresh random origin, with a fresh CSP nonce. Repeated reuse does not |
| 1249 | accumulate old pages in the back-forward list. The previous document is unregistered, callbacks |
| 1250 | and buffered messages are cleared, and messages from the previous frame URL are |
| 1251 | rejected. Only a new `ready` message admits the view to the idle pool. Failed or |
| 1252 | timed-out resets destroy the view. This preserves per-widget origins rather than |
| 1253 | resetting untrusted content inside a shared document. |
| 1254 |
| 1255 | The pool holds at most twice its warm target, counting resets in flight. Draining |
| 1256 | also cancels pending refills and resets. Memory pressure drains the pool and |
| 1257 | suppresses refills/recycling for 30 seconds. Async bubble snapshots are accepted |
| 1258 | only for the host generation that requested them. |
| 1259 |
| 1260 | ## Pre-release hardening of the integration branch (Oct 2026) |
| 1261 |
| 1262 | Release plan decisions D2, D5, D6 and D13, and the blockers found by the |
| 1263 | pre-release branch review (2026-10-16), before `telegram-macos` becomes `main`. |
| 1264 |
| 1265 | ### `strict` is the default policy, parsed fail-closed |
| 1266 |
| 1267 | The gesture gate for privileged bridge calls, the 64 KB text caps and the text |
| 1268 | budgets applied only under `strict`, and every glue copy defaulted to `compat`: |
| 1269 | a client that forgot the option let `openLink` run from a timer. `strict` is now |
| 1270 | the default in all five copies (web `WidgetHost`, Node harness, Swift |
| 1271 | `SandboxConfig` / `WidgetHost.Options`, Kotlin, C++). Kotlin and C++ keep a |
| 1272 | string option; anything but exactly `"compat"` is strict (`isStrictPolicy`, |
| 1273 | `resolvePolicy` in TS, `Validator.setPolicy`), so a typo never weakens the |
| 1274 | sandbox. `compat` stays for tests and tooling. |
| 1275 |
| 1276 | ### Strict budgets reach attributes and CSS strings |
| 1277 |
| 1278 | The budgets of "Strict-policy text limits" charged text nodes, form values and |
| 1279 | five visible attributes (`value`, `placeholder`, `alt`, `label`, `title`). A |
| 1280 | widget could still put 60 000 ideographs on screen through `data-x` and |
| 1281 | `content: attr(data-x)`, or through a string in a custom property and |
| 1282 | `content: var(--x)`. Under `strict` now: |
| 1283 |
| 1284 | - `data-*` and `aria-*` values are charged like the visible attributes |
| 1285 | (`isTextAttr`, exported to the Swift native model through `tables()`); |
| 1286 | - `attr()` may only read those attributes; any other name drops the declaration; |
| 1287 | - the string tokens of a sanitized `style` attribute, of each `style` op and of |
| 1288 | each sanitized stylesheet are charged too, decoded (`cssStringText`), so |
| 1289 | `\5b57` escapes count as the ideographs they draw. The raw stylesheet text |
| 1290 | stays charged as text nodes; strings are short in real widgets, so the double |
| 1291 | count costs nothing. An over-budget property is cleared, an over-budget |
| 1292 | stylesheet ships empty. |
| 1293 |
| 1294 | SVG path data, classes and other attributes that cannot become text stay |
| 1295 | outside the budgets: charging them would break animated SVG under the churn |
| 1296 | bucket. |
| 1297 |
| 1298 | ### One canvas payload per reference |
| 1299 |
| 1300 | With `canvasWords` a batch referenced a word payload by key, and nothing |
| 1301 | stopped a batch from naming the same key thousands of times: each reference |
| 1302 | re-validated (native model) or re-serialised (JSON splice) the whole payload, |
| 1303 | which could hang the validator thread or exhaust memory from one message. A key |
| 1304 | now counts once per batch: a binary batch with a repeated key is rejected whole |
| 1305 | (`BinaryOps.Failure.canvasKey`, mirrored in `binary-ops-decode.ts`), a JSON batch |
| 1306 | splices only the first placeholder and the validator rejects the rest, and the |
| 1307 | Node harness takes each payload once. |
| 1308 |
| 1309 | ### Web Animations records |
| 1310 |
| 1311 | `values` of a keyframe may no longer use `offset`, `easing`, `composite` or |
| 1312 | `computed-offset` (validator and `NativeAnimValidator`), and the renderer |
| 1313 | writes those members after the values, so a value can never override the |
| 1314 | checked fields. A failed `setKeyframes` cancels the old animation instead of |
| 1315 | leaving it running outside `MAX_LIVE_ANIMS`. Animation state moved from module |
| 1316 | globals into `AnimationState`, one per renderer instance: on the shadow-DOM |
| 1317 | renderer every widget shares the page, and widgets cancelled each other's |
| 1318 | animations. A CSS-animation record applies only to an animation whose effect |
| 1319 | target is the record's `target`. The web worker forwards `anim` only when |
| 1320 | `webAnimations` is enabled. |
| 1321 |
| 1322 | ### 3D side channel (`__tw3d`): out of release builds |
| 1323 |
| 1324 | `Widget3DChannel` (twidget kit) installs `__tw3d`, a C function that takes an |
| 1325 | op string and byte buffers from the widget's heap (up to 64 MB per call) and |
| 1326 | hands them to a Metal backend: a second capability next to `__host`, with no |
| 1327 | validator, policy, gesture or visibility check. Decision D6: 3D is cut from the |
| 1328 | release. `Widget3DChannel.install` is compiled only under `DEBUG || |
| 1329 | TWIDGET_EXPERIMENTAL_3D`; release builds keep the API (the kit still compiles) |
| 1330 | but never expose the function and report a `3d` diag. Before it comes back: |
| 1331 | a security review of the backend, ops checked by trusted glue against a schema, |
| 1332 | visibility and CPU accounting, and `destroy()` that does not wait on the lock |
| 1333 | the JS thread holds during a backend call (a main-thread hang today). |
| 1334 |
| 1335 | ### Swift-only extensions and parity |
| 1336 |
| 1337 | `binaryOps` with the native node model (`NativeValidator.swift`), `canvasWords`, |
| 1338 | `morphUpdates`, `icon:` expansion, side channels and the feed/pool machinery |
| 1339 | exist only in the Swift glue; they are performance paths for Telegram macOS, |
| 1340 | opt-in, and listed in `docs/changes.md`. Every glue now passes on only the |
| 1341 | features it implements (`RUNTIME_FEATURES` in Kotlin, `WEB_FEATURES` in the |
| 1342 | worker, the C++ engine's own list), and Android and the web take `features` |
| 1343 | (so Web Animations work there). A platform copy of a validator part is allowed |
| 1344 | only with parity tests (D13): the differential fuzz of `NativeValidator` |
| 1345 | against the script validator runs under both policies, and the attack corpus |
| 1346 | runs through the native model. |
| 1347 |
| 1348 | ### Review follow-ups: gestures, harness clock, library patterns, `icon:`, CallSite |
| 1349 |
| 1350 | The lower-priority findings of the pre-release branch review, closed after the |
| 1351 | hardening above: |
| 1352 |
| 1353 | - **Native hosts require `trusted`** (§3.5, §4.10). Swift, Kotlin and C++ counted |
| 1354 | any renderer event of a gesture type, the web host only `trusted` ones. No |
| 1355 | validated op makes the WebView renderer dispatch a click today, but the |
| 1356 | difference was one renderer feature away from a gesture forged by the widget. |
| 1357 | All four hosts now count only `trusted: true`. Blitz and litehtml have no |
| 1358 | script-driven document, so they mark every input event trusted; any other |
| 1359 | renderer behind the seam has to do the same or it gets no gestures. |
| 1360 | - **Only Enter and Space were key gestures, one press one gesture** (since |
| 1361 | replaced: no key is a gesture, see "Profile v1"). Any |
| 1362 | non-repeat `keydown` used to count, so Tab or an arrow key while moving |
| 1363 | through the chat handed the focused widget an `openLink`, and Enter on a |
| 1364 | button was two gestures (the `keydown` and the click it activates). The |
| 1365 | click a key press activates comes with `detail` 0, which a pointer click |
| 1366 | never has; that click, and the clicks of a held key, continue the key's |
| 1367 | gesture. A pointer click (`detail` ≥ 1) after a key press is a new one. |
| 1368 | Letters do not count either: a widget that sends on Enter still works, one |
| 1369 | that would send on every keystroke does not. |
| 1370 | - **Node harness** (§3.6): frame times now tick in 100 µs steps like `now` |
| 1371 | (the worker coarsens both), and the gesture gate checks visibility; a hidden |
| 1372 | widget (`RunOptions.visible: false` or a `{visible: false}` step) gets no |
| 1373 | frames, like the worker. |
| 1374 | - **Provided-library patterns** (§4.11). A pattern is wrapped as `^(?:p)$` |
| 1375 | (TS) / `\A(?:p)\z` (Swift); `x)|(.*` closed the group early and left an |
| 1376 | alternative unanchored, so a prefix pattern could claim every URL that starts |
| 1377 | with it (the four probe URLs miss most such cases). A pattern now has to |
| 1378 | compile on its own first: balanced, it cannot leave the group. Patterns and |
| 1379 | bytecode stay trusted input from the kit. |
| 1380 | - **`icon:`** (§4.13): the prefix is exact (`icon:`, as the grammar says); |
| 1381 | only `url(` keeps CSS's ASCII case-insensitivity. Next to the per-batch |
| 1382 | limits a widget now has a budget of its own: 256 distinct tokens asked of |
| 1383 | the resolver and 2 MB of answers kept. Without it a widget could cycle |
| 1384 | through tokens and make the resolver run up to 1024 times per batch, and the |
| 1385 | cache (512 entries of up to 64 KB, cleared when full) could hold 32 MB per |
| 1386 | widget. The budget does not refill; known tokens keep expanding, which is |
| 1387 | what a re-rendering widget needs. |
| 1388 | - **CallSite** (§4.12): the fork's `CallSite.getFunction()` returned the |
| 1389 | function of every frame, so a widget handler could take the shim's closures, |
| 1390 | the dispatcher among them, from its own stack. The shim's prelude now |
| 1391 | replaces `getFunction` and `getThis` on the shared CallSite prototype with |
| 1392 | functions that answer `undefined` (V8 does the same for strict frames). The |
| 1393 | glue still checks gestures, limits and batches, so this was defence in |
| 1394 | depth; `fn.caller` and `arguments.callee.caller` already answer `undefined`. |
| 1395 |
| 1396 | ### `completeEditorCommand` |
| 1397 |
| 1398 | The twidget renderers keep a textarea's Enter pending until the widget's |
| 1399 | `keydown`/`keypress` handlers ran; the shim then calls |
| 1400 | `completeEditorCommand(generation, command, allowDefault)`. It is documented in |
| 1401 | `docs/protocol.md` ("Native editor commands") and the validators accept it only |
| 1402 | on a `<textarea>` with integer arguments. Forms are outside the v1 profile |
| 1403 | (D3a); the call goes when the profile drops them. |
| 1404 |
| 1405 | ### The web renders through Shadow DOM; invariant 6 reworded |
| 1406 |
| 1407 | Decision D2 (2026-10-16): the web product renderer is the shadow-DOM renderer, |
| 1408 | not the iframe. Invariant 6 now reads "a sandboxed frame with a per-widget CSP, |
| 1409 | or a shadow root with a scoped validator inside a page whose CSP closes the |
| 1410 | network". The frame was never the primary boundary: widget JS never reaches the |
| 1411 | page (invariant 1), every op is validated (2, 4), and the renderer core refuses |
| 1412 | forbidden tags, attributes and URLs itself and cancels every navigation and |
| 1413 | submit. What the per-widget CSP added, the web client's page CSP has to give: |
| 1414 |
| 1415 | - `connect-src` only Telegram's own endpoints, no wildcards; |
| 1416 | - `form-action 'none'`, `frame-src` / `child-src` without third-party origins; |
| 1417 | - `img-src` and `media-src` without third-party hosts (`data:` and `blob:` plus |
| 1418 | Telegram's own), `font-src` likewise; |
| 1419 | - `style-src` admits the renderer's `<style>` elements in the shadow roots |
| 1420 | (a nonce the renderer sets, or `'unsafe-inline'`), nothing remote. |
| 1421 |
| 1422 | `TW_RENDERER=shadow corepack pnpm test:attacks` keeps measuring exactly what |
| 1423 | the frame used to add (0 canary hits, 0 requests). |
| 1424 |
| 1425 | ## Profile v1: no keyboard, no form controls, a client-styled `<button>` (Oct 2026) |
| 1426 |
| 1427 | Decided 2026-10-17 (release plan D3a, D4). Implemented in the profile v1 and SDK |
| 1428 | milestones; recorded here so the work in between does not drift from it. |
| 1429 |
| 1430 | - **No keyboard input.** Widgets get no key events and never take keyboard |
| 1431 | focus: Enter or Space in a bubble would fight the chat's input field. User |
| 1432 | activation for privileged bridge calls comes from a pointer press only: no |
| 1433 | `keydown` counts in any host, and a `click` starts a gesture only with a |
| 1434 | click count (`detail` ≥ 1), so the click Enter or Space produces on a focused |
| 1435 | control does not count either (done 2026-10-17, all hosts). Since profile 1 |
| 1436 | the renderer forwards no key event, swallows the keys' default actions, never |
| 1437 | lets the focus into the widget (a mouse press moves no focus, a `focusin` is |
| 1438 | blurred) and drops a trusted click without a press (`detail` 0); `focus()`, |
| 1439 | `blur()`, `select()` and `scrollIntoView()` do nothing. |
| 1440 | - **Form controls are outside the profile.** `input`, `textarea`, `select`, |
| 1441 | `option`, `optgroup`, `datalist`, `fieldset`, `progress` and `meter` are drawn |
| 1442 | by each engine in its own way (WebKit, Chromium, litehtml, Blitz), and text |
| 1443 | entry needs a keyboard. The validator drops them with their subtree; `<form>` |
| 1444 | renders as a `<div>` and `<label>`, `<legend>` and `<output>` as a `<span>`, |
| 1445 | so a button inside a form stays. The compat widgets built on controls moved |
| 1446 | to `corpus/out-of-profile/`; the other corpora keep theirs (they show what |
| 1447 | the profile removes). `completeEditorCommand` went with `textarea`. If |
| 1448 | controls come back, they look like the client's own UI. |
| 1449 | - **`<button>` stays** (95 corpus files; the main tap target), and a button |
| 1450 | the widget did not style is drawn in the client's own style. Any author CSS |
| 1451 | wins over it. |
| 1452 | - Layer: the renderer, as a user-agent-level stylesheet. Neither the |
| 1453 | validator (it would change the cascade the author wrote) nor the shim (it |
| 1454 | draws nothing; `getComputedStyle` answers from the renderer, so the widget |
| 1455 | sees the client's real colours). |
| 1456 | - Form: one template in `packages/core` that every renderer inserts as |
| 1457 | trusted CSS before the widget's: `@layer tw-ua` declared first and |
| 1458 | `:where(button)` selectors, so unlayered author rules beat it whatever |
| 1459 | their specificity. It fixes the structure: base look, `:active`, |
| 1460 | `[disabled]` (`:disabled` itself is outside the profile and is rewritten to |
| 1461 | it), no focus ring. It is `tables.uaStylesheet` in `profile.json`, with |
| 1462 | text selection switched off in the same sheet (since v0.1.1 inside the layer and overridable, "Text selection" below). |
| 1463 | - Values are per-client tokens (background and text from `themeParams`, |
| 1464 | radius, font, padding, height, pressed and disabled opacity) that the host |
| 1465 | sets as variables on the renderer root and updates with the theme. Native |
| 1466 | renderers bake the same template into their master CSS with the values |
| 1467 | filled in. |
| 1468 | - The defaults (before the SDK delivers tokens) survive partial overrides, |
| 1469 | which widgets write against browsers: a translucent accent tint as the |
| 1470 | background and the inherited text colour, no minimum height. A first |
| 1471 | version painted white text on the accent colour and set a 34 px minimum |
| 1472 | height; a widget that styled only the background got white on white (9 |
| 1473 | buttons in 6 corpus widgets), and one that set a small height got a taller |
| 1474 | button. With the tint and inherited text, 1 corpus button in the light |
| 1475 | theme stays under 2:1 contrast (the author's own colours) of 318. A client |
| 1476 | whose tokens set a light text colour on a solid background brings the |
| 1477 | first problem back; `docs/sdk-v1.md` says so next to the tokens. |
| 1478 | - Height and padding tokens stay within a narrow range: they move the |
| 1479 | bubble's height. Corpus references render with one fixed reference token |
| 1480 | set so renderers stay comparable; per-client tokens are checked by eye. |
| 1481 |
| 1482 | ### Frozen as widget profile 1 (2026-10-17) |
| 1483 |
| 1484 | The candidate table went to Artem on 2026-10-17 and came back decided: grid |
| 1485 | in, on condition that the Swift renderer and TwidgetCore implement it before |
| 1486 | their releases; SVG CSS, `font-variant-numeric`, conic gradients and |
| 1487 | `text-overflow` in; `touch-action`, `pointer-events`, the `ui-*` families, |
| 1488 | `prefers-reduced-motion` and `Intl` `formatToParts` in; no bundled |
| 1489 | libraries; the rarely used rest out until the native renderers are measured, |
| 1490 | when profile 2 can add them. Freeze now, with these defaults. |
| 1491 |
| 1492 | - **One source.** `packages/core/profile.json`: the 255 features of the |
| 1493 | conformance catalogue with their status (173 in, 82 out; 174 and 81 since v0.1.1 made text selection opt-in), the decision each |
| 1494 | comes from, how each out feature is neutralised, and the tables that are |
| 1495 | enforced. `packages/core/scripts/profile-build.ts` generates |
| 1496 | `src/shared/profile-tables.ts` and `docs/profile-v1.md` from it; |
| 1497 | `tests/unit/profile.test.ts` checks both are current, that the features |
| 1498 | agree with the tables, and that `CSS.supports` answers what the sanitizer |
| 1499 | does. The catalogue in `packages/conformance` syncs its statuses from it. |
| 1500 | - **Where it is enforced.** The validator (`allowlist.ts` builds its element, |
| 1501 | attribute, event, method, property and canvas lists from the tables; |
| 1502 | `css-sanitizer.ts` checks properties, functions, units, pseudo-classes, |
| 1503 | at-rules and media features, rewrites sticky and scrolling overflow, reduces |
| 1504 | font families, drops nested rules and decides `@supports`), the Swift node |
| 1505 | model (`NativeValidator` reads the same tables through `validatorTables()`, |
| 1506 | now with the SVG attributes and the replaced elements apart), the shim |
| 1507 | (`TelegramWidget.profile` and `isProfileAtLeast`, `CSS.supports` from the |
| 1508 | same evaluator as `@supports`, out-of-profile element methods and canvas |
| 1509 | read-back are local no-ops) and the renderer (no key, focus, touch, wheel |
| 1510 | or scroll events; `dblclick` and `contextmenu` only the renderer's own since |
| 1511 | v0.1.2: `dblclick` for every double tap, `contextmenu` on `touch-action: |
| 1512 | none`, "Gestures" below; the user-agent stylesheet). |
| 1513 | A removal the profile causes is the `profile` diagnostic; `css-dropped`, |
| 1514 | `url-blocked` and `tag-dropped` stay the security ones. |
| 1515 | - **The Shadow DOM gaps resolved by the profile**: the top layer (`<dialog>` |
| 1516 | is a block, popovers and `showModal` are out), `@property` and `:scope` (out |
| 1517 | everywhere), and `scrollIntoView` and `#fragment` scrolling (out: on that |
| 1518 | renderer they scroll the chat). |
| 1519 | - **No bundled libraries.** Chart.js 4 and D3 7 left the product: the CDN-name |
| 1520 | loader, `config.libraries` / `SandboxResources.provide` on every platform, |
| 1521 | the `WidgetJS/libs` bundles and their bytecode, and the npm dependencies. A |
| 1522 | `<script src>` to a CDN is an external script like any other and never runs. |
| 1523 | Kept dev-only it would still have been a code path in five glue copies and |
| 1524 | an API (`provide`) clients could build on; v1 starts with mini-widgets of |
| 1525 | 4 KB compressed that cannot carry a library's worth of code anyway, the profile |
| 1526 | cannot describe a library's own rendering, and git keeps the code for a |
| 1527 | profile that wants it back. The compat widgets built on them moved to |
| 1528 | `corpus/out-of-profile/`; the generated ones stay (with the profile prompt |
| 1529 | they fall back to a table; without it they fail, which is what that batch |
| 1530 | measures). |
| 1531 | - **Reference mode** (dev tooling) adds the renderer's user-agent stylesheet, |
| 1532 | so a sandbox-vs-reference diff shows what the profile removes, not the |
| 1533 | client's button style. |
| 1534 |
| 1535 |
| 1536 | ### The renderer's defaults: the root and the text (v0.1.1, 2026-10-20) |
| 1537 |
| 1538 | The first client implementations showed that a widget without CSS does not look |
| 1539 | native: profile 1 defined no defaults for the root and the text, so every |
| 1540 | renderer fell back to its own stylesheet. A WebView drew Times at 16 px with an |
| 1541 | 8 px body margin; litehtml, TwidgetCore and the Swift renderer each have their |
| 1542 | own master CSS. The same widget looked different on every client and like the |
| 1543 | client on none. |
| 1544 |
| 1545 | Artem decided (2026-10-20): |
| 1546 |
| 1547 | - **A full normalized UA layer** for the profile-1 elements, in the same |
| 1548 | `@layer tw-ua` as the button template, declared first, every selector in |
| 1549 | `:where()`, so any unlayered author rule wins. `html` takes the bubble's text |
| 1550 | colour and the client's text font; `body` takes the client's padding token as |
| 1551 | its margin; headings, paragraphs, lists, `dl`, tables, `hr`, `pre`/`code`, |
| 1552 | quotes, figures, images and the inline elements get explicit sizes and |
| 1553 | margins in `em` (the table in `docs/sdk-v1.md` §2.4). |
| 1554 | - **Text tokens next to the button tokens** on every host (`WidgetTheme.text`: |
| 1555 | `fontSize`, `lineHeight`, `padding` in TS, Swift, Kotlin, C++, and in the Node |
| 1556 | harness's renderer message), set as `--tg-text-*` on the renderer root. The |
| 1557 | renderer always sets them; the reference set 15 px / 1.35 / `8px 12px` stands |
| 1558 | for what the client does not pass, so a client on defaults gets sane output. |
| 1559 | `fontSize` follows the client's chat text-size setting. |
| 1560 | - **`bg_color` is this bubble's colour**: an outgoing bubble's when the user |
| 1561 | sent or forwarded the widget. The palette is the bubble's (`docs/sdk-v1.md` |
| 1562 | §2.3, §5.1). |
| 1563 | - **Shipped in v0.1.1 as a clarification of profile 1**, not as profile 2. |
| 1564 |
| 1565 | Why a clarification. The profile's rule, a feature goes in when every client |
| 1566 | draws it, governs what a widget may use and detect. The UA layer adds nothing |
| 1567 | a widget can use or detect: no element, property, value or API; `profile` stays |
| 1568 | 1, `CSS.supports` and `@supports` answer as before. Profile 1 already had a |
| 1569 | user-agent layer (the `<button>` template) and already promised UA defaults: |
| 1570 | "h1–h6 with UA default sizes and margins", "blockquote, figure, figcaption (UA |
| 1571 | indents)", "lists with markers". It did not say whose UA, and the engines' |
| 1572 | answers differ. Saying it now defines what was unspecified; every widget valid |
| 1573 | under profile 1 stays valid, and one that styles its own elements keeps its |
| 1574 | look (any author rule wins). "UA default" in profile 1 means this layer |
| 1575 | (decision `P1-ua` in `profile.json`). |
| 1576 |
| 1577 | **The padding token is the body's margin, not its padding.** The first draft |
| 1578 | said `body { margin: 0; padding: var(--tg-text-padding) }`. 169 of the 208 |
| 1579 | corpus widgets (every widget of `showcase`, `common` and `htmlbubbles-ported`) |
| 1580 | write `body { margin: 0 }` without a padding to go edge to edge, as authors do |
| 1581 | in a browser; under the draft each of them gained an 8/12 px inset and 16 px of |
| 1582 | height. With `body { margin: var(--tg-text-padding); padding: 0 }` none of the |
| 1583 | 208 changes, an unstyled widget looks the same, and the margin is inside the |
| 1584 | reported height as the padding was (the root is a flow root on every |
| 1585 | renderer). Artem's goal is that an unstyled widget looks native; the padding |
| 1586 | was wording, not a decision (2026-10-20). |
| 1587 |
| 1588 | **The bubble is the canvas; the layer paints no background.** Painting |
| 1589 | `html { background: var(--tg-theme-bg-color) }` would stop CSS's root |
| 1590 | background propagation: a widget's `body { background: X }` with the default |
| 1591 | margin would show a ring of the bubble's colour around the body, where a |
| 1592 | browser paints X over the whole canvas. So the renderer stays transparent and |
| 1593 | the client's bubble under it, drawn in `bg_color`, is the canvas, as before |
| 1594 | v0.1.1. The engines propagate a root or body background to the canvas |
| 1595 | themselves: WebKit and Chromium in the iframe and the WebViews, litehtml in its |
| 1596 | root background (`html_tag::get_background`, painted over the whole raster). |
| 1597 | The shadow-DOM renderer has no canvas, so the renderer core does it on the host |
| 1598 | element (`RendererEnv.canvas`): after every batch that touches the root, the |
| 1599 | body or a stylesheet, it copies the root's background, or the body's when the |
| 1600 | root has none, onto the host. Colours match a frame exactly; a body gradient is |
| 1601 | drawn once on the host and once on the body box, so its geometry can differ at |
| 1602 | the body's edges. `visual/15-body-background` checks the result on every |
| 1603 | renderer against one picture. Reference pictures get the bubble's colour as |
| 1604 | the page's default background (Chromium, outside the document), so |
| 1605 | propagation shows there too. |
| 1606 |
| 1607 | Two details make the transparent renderer hold on the web. The bubble itself |
| 1608 | has no padding around the widget and clips it at its corner radius (the |
| 1609 | widget's body margin is the inset): the dev app, the web and iOS chat feeds |
| 1610 | and the native demos draw their bubbles that way, in exactly the `bg_color` |
| 1611 | they pass, and `tests/sdk.spec.ts` screenshots the whole demo bubble. And the |
| 1612 | web's frame: `IframeRenderer` puts the theme's `color-scheme` on the frame |
| 1613 | element, and Chromium gives a frame whose root scheme differs from its |
| 1614 | element's an opaque canvas, white in a dark chat. The renderer therefore sets |
| 1615 | the same scheme on the frame's root, in the UA layer so a widget's own |
| 1616 | `color-scheme` still wins (`RendererEnv.frameColorScheme`, the web frame only: |
| 1617 | a dark root in a top-level WebView makes Chromium paint its own dark canvas); |
| 1618 | the dev app's reference frame gets the same. |
| 1619 |
| 1620 | How the values were chosen. |
| 1621 |
| 1622 | - Every property that WebKit's, Chromium's or litehtml's own stylesheet sets |
| 1623 | differently is set explicitly, so the three agree (the conformance widget |
| 1624 | `visual/14-unstyled-document` measures 494 px at 320 px wide in Chromium and |
| 1625 | 500 px through litehtml; the difference is litehtml's line boxes in table |
| 1626 | cells). |
| 1627 | - Sizes are compact, for a 300 px bubble rather than a page: headings 1.6 to |
| 1628 | 0.87 em at weight 600, 0.6 em between blocks, 1.5 em list indents, quotes |
| 1629 | and figures without the 40 px indent, a table with separator lines and its |
| 1630 | outer cells flush with the text, `pre` wrapping (the bubble does not scroll). |
| 1631 | - `em`, never `rem`: on the shadow-DOM renderer `rem` resolves against the chat |
| 1632 | page's root, not the widget's. |
| 1633 | - Physical properties first, logical ones after (`padding-left` then |
| 1634 | `padding-inline-start`): litehtml keeps the first, the WebViews take the |
| 1635 | second, so RTL widgets indent on the right where the engine can. |
| 1636 | - `img` gets `max-width: 100%` but not `height: auto`: a layered rule outranks |
| 1637 | the presentational `height` attribute, so `height: auto` would replace the |
| 1638 | author's `<img height>` (measured in Chromium). |
| 1639 | - Colours in the template have no fallback: a renderer that sets no variables |
| 1640 | keeps the engine's text colour. The text sizes and the margin fall back to |
| 1641 | the reference set. |
| 1642 |
| 1643 | Consequences for existing widgets: none of the 208 corpus widgets changes its |
| 1644 | box layout (all of them set the body's margin); a widget that never mentions |
| 1645 | the body's margin gets the client's inset instead of the engine's 8 px; text |
| 1646 | that relied on the engine's defaults (Times, 16 px, 40 px list indents, |
| 1647 | underlined links) now gets the layer's. |
| 1648 |
| 1649 | Where it lives. |
| 1650 |
| 1651 | - The WebView renderers (iframe, shadow DOM, WKWebView, Android WebView) insert |
| 1652 | `PROFILE_UA_STYLESHEET` through the shared renderer core and set the |
| 1653 | variables from the host's `theme` message (`themeVariables`). The shadow |
| 1654 | renderer's base stylesheet lost its unlayered `body { margin: 8px }`, which |
| 1655 | would have beaten the layer. |
| 1656 | - Native renderers bake the template into their master CSS. |
| 1657 | `apps/renderer-litehtml` reads it from `profile.json` at build time (CMake; |
| 1658 | `scripts/build-litehtml-web.ts` for the wasm build), so there is no copy to |
| 1659 | keep in sync, and handles the `theme` message with `src/theme.cpp`, a twin of |
| 1660 | `themeVariables`, writing the variables inline and `!important` on `<html>`. |
| 1661 | Two litehtml behaviours needed care: it applies a `var()` inside a shorthand |
| 1662 | after the cascade (so `margin: var(…)` from the master CSS would beat a |
| 1663 | widget's `margin: 0`), and it sorts the master CSS by specificity (so its own |
| 1664 | `body { margin: 8px }` beat a later `:where(body)`). The renderer therefore |
| 1665 | puts the theme's values into the template and unwraps `:where()` before |
| 1666 | handing it over; litehtml applies the whole master CSS before any author CSS, |
| 1667 | so no author rule can lose to it. TwidgetCore and the Swift renderer (in the |
| 1668 | twidget repository) must do the same: append `tables.uaStylesheet` to their |
| 1669 | master CSS (with litehtml: values substituted, `:where()` unwrapped), set the |
| 1670 | variables of the `theme` message on the root with `themeVariables`' |
| 1671 | semantics (the fixed names, the grammars, the palette and text tokens always |
| 1672 | complete), refuse the widget's own style ops for those names on the root, |
| 1673 | paint no background of their own (a root or body background propagates to |
| 1674 | the whole raster), report the content height with the body's margins, and |
| 1675 | honour `user-select: text` (below). The Blitz prototype has neither the |
| 1676 | button template nor the variables yet. |
| 1677 | - Reference pictures use one stylesheet, `packages/core/src/shared/reference.ts`: |
| 1678 | the layer plus the default palettes and the reference text tokens. The dev |
| 1679 | app's reference mode, the conformance build's native runs and the iOS/macOS |
| 1680 | and Android demos' reference modes (`Corpus/reference.css`, written by |
| 1681 | `scripts/sync-demo-corpus.ts`) apply it, so a corpus diff still shows what |
| 1682 | the profile removes. |
| 1683 | - The conformance harness sets `body { padding: 0 }` next to its `margin: 0`, |
| 1684 | so the existing pictures did not move; `auto/22-ua-defaults` checks the |
| 1685 | computed defaults against the client's own tokens, and |
| 1686 | `visual/14-unstyled-document` is a page with no CSS at all, both "bare" (no |
| 1687 | harness CSS). `corpus/defaults` holds six example widgets with little or no |
| 1688 | CSS. |
| 1689 |
| 1690 | ### Text selection: off by default, `user-select: text` turns it on (v0.1.1, 2026-10-20) |
| 1691 |
| 1692 | Replaces D18 ("text selection forbidden"), Artem's decision. Text in a widget |
| 1693 | is not selectable by default anywhere; a widget makes text selectable with |
| 1694 | `user-select: text` (or `-webkit-user-select: text`). Widgets that show data a |
| 1695 | user wants to copy (an address, a code, a result) no longer need a workaround, |
| 1696 | and a widget that is a drawing stays one. |
| 1697 |
| 1698 | - **The default is in the UA layer, without `!important`**: |
| 1699 | `-webkit-user-select: none; user-select: none; -webkit-touch-callout: none` |
| 1700 | on `:where(html)`. Before, a `*{… !important}` rule outside the layer beat |
| 1701 | any author CSS. Only the root: `user-select` is not inherited, and an |
| 1702 | element's `auto` follows its parent, so `user-select: text` on a container |
| 1703 | reaches its children (with `:where(*)` every child would have been reset to |
| 1704 | `none`; WebKit inherits `-webkit-user-select`, with the same result). |
| 1705 | - **The profile** takes `user-select` and `-webkit-user-select` with `none`, |
| 1706 | `text` and `auto` (`css.text.selection` is in; `all`, `contain` and |
| 1707 | `::selection` stay out and are dropped). `behaviour.no-selection` now reads |
| 1708 | "not selectable by default". Editing (`contenteditable`) stays out. The |
| 1709 | widget cannot read or change the selection: `getSelection()` stays a stub. |
| 1710 | - **The web renderers**: a mouse press no longer cancels its default action |
| 1711 | when it lands on selectable text, so a drag selects there; anywhere else it |
| 1712 | is still cancelled (no selection, no focus move, the chat input keeps the |
| 1713 | focus), and `selectstart` likewise. Copy is the browser's. |
| 1714 | - **Touch**: a long press over ordinary text (`touch-action: auto`) is the |
| 1715 | bubble's (since v0.1.2 by the gesture rule below), so a selection inside a |
| 1716 | widget starts the way the client selects text in an ordinary message, and |
| 1717 | copy is the client's: client work |
| 1718 | (`docs/sdk-v1.md` §5.10). |
| 1719 | - **An accepted exception to "every client draws it"**, like `:hover`: a native |
| 1720 | renderer that cannot select text yet (litehtml here; TwidgetCore and the |
| 1721 | Swift renderer until they implement it) keeps the text unselectable, and the |
| 1722 | widget still works. Conformance: `auto/06-text-fonts-c` checks the computed |
| 1723 | values, `auto/17-drag-hover` that a drag over ordinary text selects nothing, |
| 1724 | and `visual/16-selection` lets a tester select one paragraph and nothing |
| 1725 | else. |
| 1726 |
| 1727 | ## Gestures: `touch-action` is the claim (v0.1.2, 2026-10-22) |
| 1728 |
| 1729 | Artem's decisions, after a client developer (Android) showed the sandbox and a |
| 1730 | client disagreeing. Replaces "double tap and long press always stay with the |
| 1731 | bubble" (SDK v1, decided 2026-10-17, `docs/sdk-v1.md` §6 item 5). Since v0.1.3 |
| 1732 | vertical drags are always the chat's ("Vertical drags are the chat's" below): |
| 1733 | `pan-x` claims nothing and `none` no longer takes vertical drags. |
| 1734 |
| 1735 | **What went wrong.** In the web dev app a widget's "hold a button" worked |
| 1736 | (`pointerdown` … `pointerup`, the game controls of a wolf3d port), and a |
| 1737 | double tap made of two clicks worked too. On Android the held touch got |
| 1738 | `pointercancel` unless the element had `touch-action: none`. The rule "long |
| 1739 | press and double tap stay with the bubble" was enforced only by each client's |
| 1740 | own recognizers (they cancel the touch), the demo apps had none, and the |
| 1741 | renderer dropped `dblclick` and `contextmenu` for everyone. So a widget that |
| 1742 | worked in the sandbox failed in a client, and AI agents that test widgets in |
| 1743 | the sandbox were misled. |
| 1744 |
| 1745 | **The rule.** The framework decides who gets a press over the widget, with one |
| 1746 | shared policy: |
| 1747 |
| 1748 | - Taps and **double taps are always the widget's**, on every element, whatever |
| 1749 | `touch-action` says: a double tap reaches it as both clicks and then |
| 1750 | `dblclick`. The bubble's double-tap reaction stays on the bubble outside the |
| 1751 | widget (caption, time, edges). A first version gave the second tap on |
| 1752 | `touch-action: auto` to the reaction; the compat suite showed what that costs |
| 1753 | (a counter's "+", a tab switch or a sort header tapped twice quickly lost the |
| 1754 | second tap: tabs, fragment, table-sort and stepper failed under the phone |
| 1755 | bubble), and the client developer's view was that nobody double-taps a widget |
| 1756 | to react. Decided the same day: the double tap is the widget's. |
| 1757 | - The rest is claimed per element, at `pointerdown`, by standard CSS |
| 1758 | `touch-action` on the target and its ancestors (the renderer already reported |
| 1759 | the drag axes from it): |
| 1760 | - `auto` (the default): the bubble wins. A hold opens the message menu and |
| 1761 | the widget gets `pointercancel` when the hold is recognised; a horizontal |
| 1762 | swipe is reply or back; a vertical one scrolls the list. |
| 1763 | - `pan-y` / `pan-x`: the widget gets drags on the other axis; holds stay |
| 1764 | with the bubble. |
| 1765 | - `none`: the widget gets everything over that element: drags on both axes |
| 1766 | and holds (no menu; it gets `contextmenu`). The platform's own context menu |
| 1767 | stays cancelled. |
| 1768 | - Never claimable: the bubble outside the widget stays the place for the menu |
| 1769 | and the reaction, and the leading 20 px of the widget (the left edge, the |
| 1770 | right one in a right-to-left UI) take no claim, so the system back gesture |
| 1771 | keeps working where the widget touches the screen edge. |
| 1772 | - With a mouse (desktop): a right click is the message menu over anything but |
| 1773 | `none`, and `contextmenu` for the widget on `none`; clicks, double clicks, |
| 1774 | holds and drags are the widget's (desktop has no long-press menu and no |
| 1775 | swipes). |
| 1776 |
| 1777 | Why CSS `touch-action`: it is the web's own declaration of "this element |
| 1778 | handles its touches", authors and models already write it for sliders and |
| 1779 | canvases, the renderer reads it synchronously at `pointerdown` (a computed |
| 1780 | style, no round trip to the sandbox), and every client's WebView already obeys |
| 1781 | it for scrolling. A widget-side API (`TelegramWidget.claimGestures()`) would |
| 1782 | have been a second, non-standard way to say the same thing, asked for after the |
| 1783 | press had started. A learned `preventDefault` on `pointerdown` keeps claiming |
| 1784 | the drag axes (as before), never holds: those need the declaration. |
| 1785 |
| 1786 | **The hold is per element.** Decided the same day: no whole-widget flag (no |
| 1787 | `<meta>`, no SDK call), and nothing treats the root differently. `touch-action` |
| 1788 | on an ancestor covers its descendants through the normal intersection, as in |
| 1789 | browsers (the chain the renderer reads runs up to the widget's `<html>`). |
| 1790 |
| 1791 | **One shared policy.** `packages/core/src/shared/gesture-policy.ts` is pure: given |
| 1792 | the claim and the press's movement and timing, a `GestureArbiter` says who wins |
| 1793 | and when the widget's pointer must end with `pointercancel`. Twins: |
| 1794 | `GesturePolicy.swift`, `GesturePolicy.kt`, `gesture_policy.cpp`, all checked |
| 1795 | against `packages/core/tests/fixtures/gesture-policy.json` like the CPU budget |
| 1796 | and the SDK checks; every host exposes it, so a client drives its recognizers |
| 1797 | from it instead of inventing thresholds. The values (open for Artem; they are |
| 1798 | constants in four copies and the fixture): |
| 1799 |
| 1800 | | constant | value | from | |
| 1801 | |---|---|---| |
| 1802 | | `TOUCH_SLOP_PX` | 10 | iOS `UILongPressGestureRecognizer.allowableMovement` 10 pt; Android `ViewConfiguration` touch slop 8 dp | |
| 1803 | | `HOLD_MS` | 500 | iOS `minimumPressDuration` 0.5 s; Android's long-press timeout (500 ms in AOSP 9, 400 ms in later releases) | |
| 1804 | | `DOUBLE_TAP_MS` | 300 | Android `DOUBLE_TAP_TIMEOUT` (first up to second down); decides when the widget gets `dblclick` | |
| 1805 | | `DOUBLE_TAP_SLOP_PX` | 40 | tighter than Android's 100 dp: two adjacent buttons tapped quickly are two taps, not a `dblclick` | |
| 1806 | | `EDGE_STRIP_PX` | 20 | iOS's edge-pan region (about 20 pt); Android's gesture-navigation back inset is 18–40 dp by setting | |
| 1807 |
| 1808 | The axis of a drag is the dominant one when the press leaves the slop (a tie |
| 1809 | is vertical: the list scroll is the commoner gesture). |
| 1810 |
| 1811 | **Where it runs.** |
| 1812 |
| 1813 | - The renderer core always runs an arbiter on the primary pointer: it is what |
| 1814 | sends the widget `dblclick` (after the second tap's click, for every double |
| 1815 | tap) and `contextmenu` (at a hold or a right-button press the widget claims). |
| 1816 | The engine's own `dblclick` and `contextmenu` never reach the widget, so |
| 1817 | WebKit, Chromium and the native renderers deliver the same events at the same |
| 1818 | thresholds. `input.dblclick` is now in the profile, and `input.long-press` on |
| 1819 | `touch-action: none` elements (decision G1 in `profile.json`; |
| 1820 | `TelegramWidget.profile` stays 1: what changes is which presses the bubble |
| 1821 | keeps, not what a renderer draws). |
| 1822 | - Native clients keep their own recognizers, driven by the policy and the |
| 1823 | claim the host reports (`onGestureClaim` / `onGesture`: `x`, `y`, `hold`), and |
| 1824 | cancel the touch to the WebView the platform's way (it becomes |
| 1825 | `pointercancel`); a double-tap recognizer must not act over the widget. The |
| 1826 | demo apps' bubbles do the same. |
| 1827 | - The web has no recognizers over the widget, so there the renderer plays the |
| 1828 | bubble (`WidgetHost` `bubbleGestures`, the `arbitrate` message): a press the |
| 1829 | bubble takes ends for the widget with `pointercancel` and nothing more of that |
| 1830 | pointer, and the host gets `onBubbleGesture` (menu, swipe, scroll, back). The |
| 1831 | dev app and the feed demo use it by default with a mouse arbitrated as a |
| 1832 | finger (the `gestures` select: phone, desktop, off), and every Playwright |
| 1833 | suite runs on that default, so "works in the sandbox" now means "works in a |
| 1834 | client". In that mode the widget also sees `pointerType: 'touch'` for the |
| 1835 | press and no click after a drag or a hold, as on a phone. |
| 1836 | - The Node harness (`sandbox-node.ts --width N --tap / --hold / --double-tap / |
| 1837 | --swipe / --right-click`) runs the same renderer core in headless Chromium on |
| 1838 | the sandbox's ops and reports per press the element, its claim, the policy's |
| 1839 | outcome, what the widget received and a hint for the author. |
| 1840 |
| 1841 | **Possible later step: an area quota.** A widget that puts `touch-action: none` |
| 1842 | on its whole surface takes the bubble's menu and swipes away from the widget's |
| 1843 | area entirely (they remain on the caption, the time and the bubble's edges). |
| 1844 | A client developer suggested capping how much of the widget may claim holds, |
| 1845 | like Android's limit on gesture-exclusion rects (200 dp of each edge). Not now: |
| 1846 | the rule is simple and testable as it is, and the conformance and corpus |
| 1847 | widgets claim small areas (buttons, knobs, canvases). If widgets start |
| 1848 | claiming everything, the policy can take an area budget per widget and fall |
| 1849 | back to `auto` beyond it. |
| 1850 |
| 1851 | ## Vertical drags are the chat's (v0.1.3, 2026-10-24) |
| 1852 |
| 1853 | Artem's decision, after trying the widgets of `corpus/gestures` in the Telegram |
| 1854 | test group: a widget can claim only horizontal drags. A vertical drag over a |
| 1855 | widget always scrolls the chat, whatever `touch-action` says; the widget gets |
| 1856 | `pointercancel`. Replaces the vertical half of G1 (decision G2 in |
| 1857 | `profile.json`). |
| 1858 |
| 1859 | | `touch-action` | hold | horizontal drag | vertical drag | |
| 1860 | |---|---|---|---| |
| 1861 | | `auto`, `manipulation` | bubble: message menu | bubble: swipe / back | chat | |
| 1862 | | `pan-y` | bubble | widget | chat | |
| 1863 | | `pan-x` | bubble | bubble (it claimed vertical drags until v0.1.3) | chat | |
| 1864 | | `none` | widget (`contextmenu`) | widget | chat (the widget's until v0.1.3) | |
| 1865 |
| 1866 | Unchanged: taps and double taps are the widget's on every element, the axis |
| 1867 | lock (the first move past the 10 px slop decides for the whole press: a |
| 1868 | horizontal-first drag stays the widget's on both axes until the finger lifts, |
| 1869 | a vertical-first one is the chat's; a hold the widget won on `none` is locked |
| 1870 | the same way at its first move past the slop), the 20 px leading strip, and the |
| 1871 | mouse (a drag on any axis is the widget's: desktop scrolls with the wheel). |
| 1872 | The hold's lock was first meant to keep the press for the widget whatever |
| 1873 | moved next; the Android port showed that a WebView, whose engine now always |
| 1874 | allows vertical panning, cancels such a press itself, so the policy says what |
| 1875 | every engine does. |
| 1876 |
| 1877 | **Why.** The chat never gets stuck under a widget: a reader scrolling through |
| 1878 | a chat cannot know which bubble claims vertical drags, and a widget that does |
| 1879 | (a full-surface canvas, a game on `none`) stops the scroll exactly where the |
| 1880 | finger is. With vertical always the chat's, scrolling works the same over |
| 1881 | every bubble, and what a widget can take is one predictable thing: horizontal |
| 1882 | drags (and holds on `none`), where the chat's own gesture, swipe-to-reply, is |
| 1883 | rarer and already gives way per element. |
| 1884 |
| 1885 | **What is lost.** Everything whose input is vertical or two-dimensional: |
| 1886 | two-axis joysticks and game pads, drawing and signature pads, map and image |
| 1887 | panning, vertical sliders, faders and wheel pickers, swipe-up/down in games |
| 1888 | (2048). Authors turn such controls horizontal, use taps (buttons for up and |
| 1889 | down, a tap-to-place board), or both. |
| 1890 |
| 1891 | **How it was decided.** `corpus/gestures` (v0.1.3, `corpus/gestures/README.md`) |
| 1892 | put the cost side by side before the change: a joystick game and 2048, each on |
| 1893 | `touch-action: none` (both axes) and on `pan-y` (what the rule leaves them), |
| 1894 | and a wheel picker on `pan-x`, against what is fine with horizontal only (a |
| 1895 | paddle game, a card carousel, a range slider on `pan-y`). Artem tried them in |
| 1896 | the Telegram test group (2026-10-23); the pairs now show what the rule |
| 1897 | removed, and the `-xy` variants behave like their `-x` twins. |
| 1898 |
| 1899 | **Where it is enforced.** In the policy, four copies and the fixture: |
| 1900 | `claimOf` never claims `y` (the field stays in the claim types, always false, |
| 1901 | so code written for v0.1.2 builds), and `GestureArbiter` gives a vertical touch |
| 1902 | drag to the chat even for a claim built by hand with `y`. In the renderer: the |
| 1903 | engine under it (Chromium, WebKit) gets each `touch-action` value widened to |
| 1904 | allow vertical panning (`none` → `pan-y`, `pan-x` → `pan-x pan-y`, |
| 1905 | `src/renderer/touch-action.ts`), so a browser on a touch screen, the web |
| 1906 | client on a phone, scrolls the page over any widget; the claim and the |
| 1907 | widget's `getComputedStyle` read the widget's own value. On Android the |
| 1908 | WebView renderer keeps its parent from intercepting only for a hold claim, and |
| 1909 | only until the press leaves the slop vertically. |
| 1910 |
| 1911 | ## The resize anchor (v0.1.3, 2026-10-24) |
| 1912 |
| 1913 | Artem's decision: a widget chooses which edge of its bubble stays put when its |
| 1914 | height changes, with `TelegramWidget.setResizeAnchor('top' | 'bottom')` |
| 1915 | (decision R1 in `profile.json`; `docs/sdk-v1.md` §2.12, §5.6). |
| 1916 |
| 1917 | **Why.** A chat list keeps the top of a growing bubble still, which is right |
| 1918 | for an FAQ, "show more" or an order summary that opens below the line the |
| 1919 | reader tapped, and wrong for a widget that grows at its bottom, a chat log or |
| 1920 | a support thread: there the reader's finger is on the quick replies at the |
| 1921 | bottom, and every new message pushes them away. Only the widget knows which |
| 1922 | kind it is. `top` stays the default, so every widget written before keeps its |
| 1923 | behaviour. |
| 1924 |
| 1925 | **The shape.** One call with two values, applied to the height changes that |
| 1926 | follow until it is called again, rather than an argument of each change (the |
| 1927 | renderer measures the height; the widget never reports it). It goes through |
| 1928 | the bridge as a checked call like the others (`sdk-policy`: four copies and |
| 1929 | the fixture; only `'top'` and `'bottom'`, case-sensitive; no gesture, no |
| 1930 | visibility gate), but it is not an action: the host keeps the latest value and |
| 1931 | reports it with the height (`WidgetDiagnostics.resizeAnchor`, web |
| 1932 | `onResize(height, anchor)`), and the shim sends only changes, so a widget that |
| 1933 | calls it in a loop costs the client nothing. It is an SDK v1 addition inside |
| 1934 | profile 1: `TelegramWidget.profile` stays 1 and widgets detect the method with |
| 1935 | `typeof`, as a client whose framework predates v0.1.3 lacks it. |
| 1936 |
| 1937 | **The client's part.** The list compensates its scroll so the anchored edge of |
| 1938 | a bubble on screen stays in place, also when the bubble opens at its cached |
| 1939 | height and the first report differs and after it is re-created; a bubble off |
| 1940 | screen keeps the visible content in place; during a height animation the old |
| 1941 | pixels are aligned to the anchored edge. The web dev app and the feed do it |
| 1942 | (`corpus/resize` has one widget per anchor). |
| 1943 |
| 1944 | ## The bot's data and requests: widget interactivity (2026-10-25) |
| 1945 |
| 1946 | Artem's decisions after the product discussion of October 2026 and the server's |
| 1947 | spec of 2026-10-25 (decision I1 in `profile.json`; `docs/sdk-v1.md` §2.13–§2.15 |
| 1948 | and §5.11; the server's side, `docs/tgw-format.md` "The widget's state and |
| 1949 | requests"): **a widget is fixed code plus changeable state: the HTML never |
| 1950 | changes after sending; the state changes, and only the bot writes it.** The |
| 1951 | chat state, `chat_data`, is tied to one original message and seen only in its |
| 1952 | chat (the user's in the private chat, shared by the members of a group) and is |
| 1953 | never forwarded; the shared state, `public_data`, is seen wherever the widget is |
| 1954 | shown (a forward gets a frozen copy, or the state of a server object shared by |
| 1955 | the original and all its forwards). The widget reads its state and cannot |
| 1956 | change it itself; it can only ask the bot. A request from the widget is a |
| 1957 | callback button inside it: the bot gets what an inline button's press gives |
| 1958 | (`from`, the message with its state, `chat_instance`, the chat type; from a |
| 1959 | forward only `from` and the shared object's id) plus `data` of at most 64 bytes, |
| 1960 | and answers with a `result` of at most 1 KB for the widget that asked. The bot |
| 1961 | changes the state only with separate calls, never in an answer. Whether a |
| 1962 | widget may ask at all is the bot's choice per widget (`allow_queries`, and |
| 1963 | `fwd_allow_queries` for its forwards); where it may ask is the server's flags |
| 1964 | per message: `can_query` (originals of a widget sent with `allow_queries`; |
| 1965 | forwards of one sent with `fwd_allow_queries`), `background_query` (only the |
| 1966 | original in the private chat with the bot). The second version of the server's |
| 1967 | spec (same day) replaced `fwd_live` with these two flags, showed the shared |
| 1968 | object's id to the bot and took the place out of a forward's request; the |
| 1969 | framework reads the flags, so only the docs changed. The final spec (2026-10-26) |
| 1970 | made the shared object the widget itself (the HTML, the size, `public_data`, its |
| 1971 | refresh period and its flags, named by `widget_id`, sent by reference with |
| 1972 | `inputMediaWidgetId`), let `fwd_allow_queries` imply `allow_queries`, gave |
| 1973 | the bot three updates (an original, a via-bot message, a copy with only |
| 1974 | `from`, `data` and `widget_id`), set the request limit to 5 per 5 s and made |
| 1975 | the poll one message per call again; the framework's side did not change |
| 1976 | (`docs/tgw-format.md` has the server's side). |
| 1977 |
| 1978 | **Why this model.** Code that the bot can swap after sending would let one |
| 1979 | edit change a thousand forwarded copies and make every widget a moving target |
| 1980 | for moderation; fixed code with changing state keeps what a reader saw |
| 1981 | reviewable and lets the widget animate into its new state instead of |
| 1982 | restarting. A request shaped as a callback query needs no signature (it |
| 1983 | reaches the bot as an update from Telegram) and no bot server at all with |
| 1984 | Telegram's serverless handlers. The widget knows locally only what the bot |
| 1985 | gets with a press anyway (in an original that may ask: the viewer's id and the |
| 1986 | chat type; in a live forward: the viewer's id; where it cannot ask: no viewer), |
| 1987 | so a request has nothing extra to leak. A copy is told nothing about the chat it is |
| 1988 | in (Artem: the bot must learn nothing about where its widget was forwarded, and |
| 1989 | whatever the widget knows can go to the bot in a request's 64 bytes). |
| 1990 |
| 1991 | **Part of SDK v1 and layer 233 from the launch** (Artem: everything ships with |
| 1992 | the widgets' launch; no client ever has widgets without state and requests). No |
| 1993 | version of its own, no detection: every client has it. A client that passes no |
| 1994 | flags gets widgets whose requests are refused (`NOT_ALLOWED`); the profile |
| 1995 | stays 1. |
| 1996 |
| 1997 | **The shapes we chose.** |
| 1998 | - Names follow Mini Apps where one exists (`chatType` from `chat_type`, |
| 1999 | `viewer` for `initDataUnsafe.user`); `request` returns a promise of |
| 2000 | `{ result }` and rejects with `error.code` (`NOT_ALLOWED`, `BUSY`, |
| 2001 | `RATE_LIMITED`, `TIMEOUT`, `FAILED`, `INVALID_ANSWER`), so a widget always |
| 2002 | learns how its request ended. |
| 2003 | - **The client reads the server's flags, it derives nothing.** The host's |
| 2004 | context is `isCopy`, `canQuery`, `backgroundQuery` as the media has them, plus |
| 2005 | the chat type and the viewer; no flags, no requests. The request gate decides from them: no `canQuery` → |
| 2006 | refused; a tap → out (and the tap is used); no `backgroundQuery` → refused; |
| 2007 | hidden → refused; a background request: one when the widget appears on screen, |
| 2008 | then at most one per 5 s while it stays visible (Artem; one constant, |
| 2009 | `BACKGROUND_REQUEST_INTERVAL_MS`, and the gate's `show`). The server and the bot |
| 2010 | cannot tell a tap from a background request, as for callback buttons, so the |
| 2011 | request carries only `data` and the limit is the client's. One request in |
| 2012 | flight per widget, whatever its kind. |
| 2013 | - **`viewer` is a `WebAppUser`** (Artem, 2026-10-26): `{ id, first_name, |
| 2014 | last_name?, username?, is_premium? }`, as Mini Apps' `initDataUnsafe.user`, |
| 2015 | since the SDK already follows Mini Apps' names (`themeParams`, |
| 2016 | `HapticFeedback`). The client passes the account's own names, username and |
| 2017 | Premium flag; the glue checks them like the id (names 1–64 UTF-16 code units, |
| 2018 | a username 5–32 of `[A-Za-z0-9_]`, `is_premium` a boolean, kept only when |
| 2019 | true) and leaves out a field that breaks its rule (`data-rejected`), not the |
| 2020 | whole viewer. On a tap the bot gets `from` with the same fields, so nothing |
| 2021 | new leaks; a fake Telegram dialog that greets the reader by name was the |
| 2022 | worry before, and the rule below answers it: only a widget that may ask |
| 2023 | knows. **The viewer only with `canQuery`** (Artem, after the |
| 2024 | server's spec v2): an original or a forward that may ask gets the viewer, whom |
| 2025 | the bot learns with its first tap anyway; an original sent without |
| 2026 | `allow_queries`, a copy that may not ask and a preview get none. A widget that |
| 2027 | may not talk to the bot does not know who views it, so it cannot pass the id |
| 2028 | out through `openLink` either, and the rule matches the network marker; in the |
| 2029 | private chat the bot can put the user's id into the chat state itself. No copy |
| 2030 | gets the chat type, with or without `canQuery`. |
| 2031 | - **Polling only for widgets that ask: `watchPublicData()`** (Artem, 2026-10-26; |
| 2032 | the second proposal to the server, `notes/server-proposal-widget-object.md`). |
| 2033 | A bot may make a widget shared only to send it by `widget_id`, and polling |
| 2034 | every such card on screen would ask the server for nothing. So the widget asks |
| 2035 | to follow its shared state live with `TelegramWidget.watchPublicData()` (and |
| 2036 | stops with `unwatchPublicData()`): synchronous, no tap, idempotent; the shim |
| 2037 | sends only changes, the host keeps the latest value and reports a change, like |
| 2038 | the resize anchor; a preview never watches. The client polls |
| 2039 | `getWidgetPublicData` only for watching widgets on screen with a `widget_id`, |
| 2040 | one carrier per id; every other widget gets its shared state with the |
| 2041 | message. The protocol does not change. The same proposal moved `period` to 5–3600 s with a default of 30 s |
| 2042 | (`cache_time` 0 sets it back to 30 s; the final spec had 2–3600 s and 5 s); |
| 2043 | the server made it so (Artem: "на сервере сделал 5, 30, 3600"). |
| 2044 | - **The network marker** (the server's spec, a UI contract): where the message |
| 2045 | has `can_query`, the client marks the widget as one whose tap may send data to |
| 2046 | the bot's server; without it there is no marker, and the server refuses every |
| 2047 | request from that message. The marker is the client's own UI from the flag it |
| 2048 | already passes (`context.canQuery`), so the framework adds no API for it; the |
| 2049 | dev app draws one in its bubble's header. |
| 2050 | - **The answer is only `result`** (no toast, alert, URL, `cache_time` or state): |
| 2051 | the widget shows the result itself and the client shows nothing for a |
| 2052 | request. Changes of the state reach the widget the usual ways (the server's |
| 2053 | update for the chat state, polling for a shared widget's shared state), and |
| 2054 | the client does not re-fetch after an answer: a bot whose widget needs the new |
| 2055 | state at once returns it in `result`. This keeps one path for the state and |
| 2056 | the edits under their own rate limits. |
| 2057 | - **Two events**, `chatDataChanged` (the chat state) and `publicDataChanged` |
| 2058 | (the shared state), not one: a widget redraws what changed, and in a forward |
| 2059 | only `publicDataChanged` can fire. One `setData` that changes both fires |
| 2060 | both, chat first, in one task; a value that did not change fires nothing (so a |
| 2061 | duplicate delivery is harmless). `setData` always takes the full state: the |
| 2062 | client knows its message's values. |
| 2063 | - The chat state, the shared state and `result` are the server's text fields, |
| 2064 | each a text of up to 1024 bytes (UTF-8) without a NUL; the glue refuses the |
| 2065 | same (`data-rejected`, `INVALID_ANSWER`), so a client bug cannot hand the |
| 2066 | widget what the server would refuse. |
| 2067 | - One tap unlocks one privileged call, shared by `openLink`, |
| 2068 | `openTelegramLink`, `copyText` and a request: the rule a reader can rely on |
| 2069 | ("one tap, one thing"). A request looks at the tap without consuming it and |
| 2070 | consumes it only when it goes out as the tap's. |
| 2071 | - A client without `onRequest` refuses at delivery, after the gate, on every |
| 2072 | host (`NOT_ALLOWED`, reason `unsupported`): the native hosts take `onRequest` |
| 2073 | as a property set after creation, and a widget that asks at boot must not |
| 2074 | lose that race. |
| 2075 | - `copyText` is a separate callback, not a `WidgetAction` case, so clients' |
| 2076 | exhaustive switches keep compiling; the client's toast shows the copied text |
| 2077 | so a widget cannot show one address and copy another unnoticed. |
| 2078 |
| 2079 | **Where it lives.** The checks are one policy with four copies and the |
| 2080 | fixture (`sdk-policy`: `checkRequestData`, `checkCopyText`, |
| 2081 | `checkWidgetData`, `checkViewer`, `checkChatType`, `checkRequestAnswer`, |
| 2082 | `RequestGate`, `requestRefusal`; `tests/fixtures/sdk-policy.json`). The shim |
| 2083 | checks the same limits to give the widget a `TypeError` or an immediate `BUSY` |
| 2084 | or `NOT_ALLOWED`; every glue checks again (a widget can rewrite what the shim |
| 2085 | sends: `JSON.stringify` is a global, `corpus/attacks/request-forged-wire.html`). |
| 2086 | Answers and changes of the state go into the sandbox as a host → sandbox |
| 2087 | `bridge` dispatch, the task kind the CPU budget already defers (it carried the |
| 2088 | profile-0 bot answers), so no policy change was needed there. The request and |
| 2089 | the polling go over the client's own connection: the sandbox still has no |
| 2090 | network (invariant 5). |
| 2091 |
| 2092 | **Downsides we accept.** Through a request the bot learns whatever the widget's |
| 2093 | code knows, up to 64 bytes (language, theme, text size, bubble width, time |
| 2094 | zone, what it kept locally); in the private chat background requests also |
| 2095 | show the bot when the user has the chat open. A tap "for the game" and a tap |
| 2096 | "for the bot" look the same to the reader, so the bot is always visible as |
| 2097 | the sender or via, and a widget is never forwarded without its author. |
| 2098 | The chat state in a group is visible to every member. A bug in a sent widget |
| 2099 | cannot be fixed, only replaced by a new message. Forwards of widgets not sent |
| 2100 | live cannot vote or play: that goes through the bot. |
| 2101 |
| 2102 | **Previews** (Artem, 2026-10-25: "give all the data, but the client must know |
| 2103 | the widget is in a preview and give it no interactivity and no data about the |
| 2104 | user"). A widget in an inline-results list, before it is sent, runs with its |
| 2105 | state and `TelegramWidget.isPreview`; the host (`context.preview`) takes no |
| 2106 | input from it (a tap selects the result), lets through only `ready` and |
| 2107 | `setResizeAnchor` (`PREVIEW_METHODS` in the policy: no request, link, copy or |
| 2108 | haptic), gives it no chat type or viewer and the request flags off, and never |
| 2109 | commits its Web Storage (there is no message yet). Timers, animations, the theme |
| 2110 | and the limits are as for any bubble, so the preview is the first state the user |
| 2111 | is about to send. |
| 2112 |
| 2113 | ## Haptics need a touch (v0.2.2) |
| 2114 |
| 2115 | **The bug.** Telegram Android 13.2.0 (7255): a widget with |
| 2116 | `setInterval(function(){TelegramWidget.HapticFeedback.notificationOccurred("error")},0)` vibrated the phone for as |
| 2117 | long as it was on screen. The gate allowed haptics with no gesture, under a rate limit only (a burst of 5, 10 per |
| 2118 | second), and 10 a second is a continuous buzz. |
| 2119 |
| 2120 | **The rule** (Artem, 2026-10-26; `HapticGate` in `sdk-policy` and its three twins, the numbers named constants he may |
| 2121 | tune): while a finger or a mouse button is down on the widget and 5 s after it is lifted, haptics pass under the rate |
| 2122 | limit; outside a touch the first call opens a 1 s series, and the next series needs a touch (one series at any time |
| 2123 | after it) or 10 s since the last one began. Hidden widgets and previews get nothing, as before. The touch is trusted |
| 2124 | input the renderer reports (its claim at `pointerdown`, and since v0.2.2 `release` at the end of the press), never an |
| 2125 | event the widget dispatches; a press whose end the host never sees (the finger left the view) counts as lifted 30 s |
| 2126 | after it began. |
| 2127 |
| 2128 | **Why not a gesture-only rule** (haptics only within a tap's task, like links): widgets play haptics where no tap is |
| 2129 | at hand. A bot's answer arrives 1.5–15 s after the tap that asked; an animation ends a second later; an arcade game |
| 2130 | buzzes on a collision while the finger is still down or just lifted. The touch window covers the game and the |
| 2131 | animation, the one series after a touch covers the late answer, and the 1 s series every 10 s keeps a widget with no |
| 2132 | touch at all (a timer, a ticker) from becoming a vibrator. |
| 2133 |
| 2134 |
| 2135 | ## Native scrolling: an experiment (v0.2.3, 2026-10-27) |
| 2136 |
| 2137 | `WidgetHost.Options.nativeScrolling` (Swift, from the Telegram macOS work, a5a7023) lets the validator keep `overflow: |
| 2138 | auto` / `scroll` and lets a widget listen to `scroll`. Widget profile 1 clips instead (no inner scrolling, `docs/profile-v1.md`), |
| 2139 | and every other client does. Earlier Swift-only options (`canvasWords`, `binaryOps`, `morphUpdates`) change how the same |
| 2140 | validated output travels; this one changes what a widget can do, so a widget written against a client that turns it on |
| 2141 | breaks on every other client. It stays as an experiment, the way the 3D side channel does: only DEBUG builds or builds |
| 2142 | with `TWIDGET_EXPERIMENTAL_SCROLLING` honour it, and a release build reports a `native-scrolling` diag and keeps profile 1. |
| 2143 | The shared validator code is unchanged and inert unless a host turns the flag on (Kotlin, C++ and the web never do). |
| 2144 | Inner scrolling for every client is a question for widget profile 2: with a wheel or a trackpad it is safe; on a touch |
| 2145 | screen horizontal scrolling fits the gesture rule, vertical scrolling conflicts with "vertical drags are the chat's" (v0.1.3). |
| 2146 |
| 2147 |
| 2148 | ## Telegram links open without a confirmation (2026-10-29) |
| 2149 |
| 2150 | `openTelegramLink(url)` no longer asks the client for a confirmation of its own (`docs/sdk-v1.md` §5.2; Artem, |
| 2151 | 2026-10-29, after the bot demos: "Open @bot" in a widget showed a dialog that a `t.me` link in a message never shows). |
| 2152 | The client opens it as a tapped `t.me` link in a message, through its own `t.me` handling, which keeps the confirmations |
| 2153 | it has for the dangerous kinds (joining a chat, a proxy, a login, a language). `openLink(url)` keeps the confirmation |
| 2154 | with the full URL: an external page is where a widget could lead the user somewhere unexpected. Nothing changes in the |
| 2155 | framework: both calls stay privileged (only from a real tap, one per press) and the URL rules stay as they were; the |
| 2156 | confirmation was always the client's. |
| 2157 |
| 2158 | ## The renderer prototypes are frozen (2026-10-30) |
| 2159 |
| 2160 | Blitz (`apps/renderer-blitz`) and the plain litehtml core (`apps/renderer-litehtml`), with their glue in the demos and |
| 2161 | in `packages/desktop/renderer`, stay in the repository as the record of the comparison above, but nothing builds or runs |
| 2162 | them by default and a change is not checked on them (Artem, 2026-10-30). |
| 2163 |
| 2164 | - **Why.** Every client draws with a renderer of its own: the web with the Shadow DOM renderer, the native clients with |
| 2165 | their own engines, and those that use litehtml use their own extended one, not our plain core; no client ships Blitz. |
| 2166 | A result on the prototypes therefore says nothing about a client: plain litehtml fails where the clients' litehtml is |
| 2167 | fixed (`auto/19` dies on the 100 ms layout-query window there) and passes where a client may be broken. Their job, |
| 2168 | the evidence for the decision above and the probes behind profile 1, is done; whether every client draws a feature is |
| 2169 | answered by the clients' own conformance runs (`packages/conformance/CLIENTS.md`), and what it costs by the stress |
| 2170 | kit (`packages/stress/CLIENTS.md`). Meanwhile they cost every demo build a Rust and a CMake build and every report a |
| 2171 | "not checked on Blitz/litehtml" line. |
| 2172 | - **What is off by default.** The demos' builds: the iOS/macOS demo builds, links and compiles them in (Swift condition |
| 2173 | `TW_NATIVE_RENDERERS`) only with `TW_NATIVE_RENDERERS=YES` on `xcodebuild`, the Android demo includes their modules |
| 2174 | only with `-Ptw.nativeRenderers=true`; without them no Rust toolchain or extra CMake build is needed and the renderer |
| 2175 | picker is hidden. Their wasm unit tests run only with `TW_NATIVE_RENDERERS=1`. The default renderers of |
| 2176 | `scripts/conformance/run-web.ts` and the default cells of `scripts/feed-report.ts` and the feed's bench panel are |
| 2177 | iframe and shadow. Opt-in already before: the desktop core's `-DTW_BLITZ` / `-DTW_LITEHTML`, the web dev app's |
| 2178 | toggles (they need `build:blitz-web` / `build:litehtml-web`), `TW_RENDERER=blitz|litehtml` for the Playwright suites. |
| 2179 | - **No obligation.** A framework change is not tested on the prototypes and a report does not list them as a gap. A |
| 2180 | prototype that breaks stays broken until someone revives it; reviving one means its opt-in build and its checks first. |
| 2181 | - **What our native runs check instead.** The framework without a renderer (QuickJS on its thread, the glue, the |
| 2182 | validator, the shared policies on their fixtures, the attack corpus through the native node model) and the `Renderer` |
| 2183 | seam on our WebView renderer, which stands in for a client's. The clients' renderers are checked by the clients: |
| 2184 | drawing by the conformance set, cost by the stress kit. Their renderer-side defences (no network attempt, `trusted` |
| 2185 | only for a real press) have no shared check yet. |
| 2186 |
| 2187 | ## The client's time over a widget with no caption below it: the content safe area (2026-10-29) |
| 2188 |
| 2189 | Artem's decision (`P1-safe-area` in `profile.json`; `docs/sdk-v1.md` §2.17, §5.12): a message with a widget and no |
| 2190 | caption gets its time and status drawn by the client over the widget's bottom corner, on a backing, as on a photo; |
| 2191 | with a caption below the widget the time is in the caption's line and nothing covers the widget. The widget is told |
| 2192 | what is covered so it can keep clear of it. |
| 2193 |
| 2194 | **A caption above the widget** (`invert_media`, Bot API `show_caption_above_media`; Artem's decision of |
| 2195 | 2026-10-30): as no caption. The time is drawn over the widget's bottom corner again, as on |
| 2196 | a photo whose caption is moved up, so the client passes the same band and corner; only a caption below gives 0. An |
| 2197 | edit that moves the caption above or below the widget is a layout change like adding or removing it. |
| 2198 |
| 2199 | **Why `env()`, rewritten.** `env(safe-area-inset-bottom)` is what web code and models already write |
| 2200 | (`padding-bottom: max(12px, env(safe-area-inset-bottom))`), and it means the right thing: keep this band clear. But the |
| 2201 | engine's own `env()` cannot carry it: its values belong to the document (in the shadow renderer, to the whole chat |
| 2202 | page), come from the system insets of the view on WKWebView and Android WebView, and do not exist in Blitz or |
| 2203 | litehtml. So the validator rewrites `env(safe-area-inset-{top,right,bottom,left}[, fb])` to |
| 2204 | `var(--tg-content-safe-area-inset-…[, fb])`, root variables the renderer sets like the theme's (inline, `!important`, |
| 2205 | names from a fixed list, values checked: an inset 0–64 px, a corner 0–200 px). Every renderer then draws the same, and |
| 2206 | the names are Mini Apps', so `var(--tg-content-safe-area-inset-bottom)` from Mini Apps code works too. Before this the |
| 2207 | validator dropped every declaration with `env()`, fallback or not: `padding: 12px 12px calc(12px + |
| 2208 | env(safe-area-inset-bottom))` lost the whole padding. Another `env()` name now resolves to its fallback (dropped without |
| 2209 | one); none inside `url()`. |
| 2210 |
| 2211 | **Why a corner as well.** CSS has no cut-outs: a safe area is four edge lengths. One number would leave the whole band |
| 2212 | empty, while the time takes only one corner of it, and its width varies (12- or 24-hour time, "edited", ticks, views). |
| 2213 | `--tg-content-safe-area-corner-left|right` gives that width on its physical side (right in a left-to-right interface, |
| 2214 | left in a right-to-left one, whatever the widget's own direction), so content may enter the band on the other side. |
| 2215 | Script gets the same numbers as `TelegramWidget.contentSafeAreaInset` (one frozen object of six numbers, a fresh one per |
| 2216 | change, and `contentSafeAreaChanged`; Artem: one object, no separate members), for a canvas widget that lays out its |
| 2217 | own controls: `getComputedStyle` on the variables would be a layout query. |
| 2218 |
| 2219 | **Static, never per frame.** The client passes the band at creation, so the first height already has it, and changes |
| 2220 | it only with the bubble's layout (a caption added, removed or moved above or below by an edit, "edited"). The floating date pill moves |
| 2221 | relative to the bubble every frame; passing it would restyle every visible bubble on every frame and lag behind it, so |
| 2222 | it has no contract and is drawn over the widget as over a photo. Taps on the time are the client's (a view over the |
| 2223 | widget); nothing changes in the gesture policy. |
| 2224 |
| 2225 | **The UA layer pads the body.** `:where(body){padding-bottom:var(--tg-content-safe-area-inset-bottom,0px)}`: an |
| 2226 | unstyled widget (and one that only sets `body { margin: 0 }`, as most do) stays clear of the time; a widget that sets |
| 2227 | the body's padding handles the band itself. The price: a widget with no caption below it is that much taller. |
| 2228 |
| 2229 | **A clarification of profile 1, not profile 2.** `css.value.env` moved from out to in on 2026-10-29, before widgets |
| 2230 | launched, as the UA layer was clarified in v0.1.1 (`P1-safe-area`, like `P1-ua`): `TelegramWidget.profile` stays 1. A |
| 2231 | client that passes no safe area keeps v0.3.0's layout, except that a declaration with `env(safe-area-inset-*)` now |
| 2232 | applies with 0 where it used to be dropped, and another `env()` name with a fallback now takes its fallback. |
| 2233 |
| 2234 | ## The wallet: Gram Wallet for widgets (2026-10-30) |
| 2235 |
| 2236 | A widget can pay and sign through Telegram's built-in wallet (Gram Wallet; `docs/sdk-v1.md` §2.18, §5.13). The |
| 2237 | widget is the front of a dApp and its bot is the back end, as a site and its server are in TON Connect. Decided with |
| 2238 | Artem on 2026-10-29 and 2026-10-30 after the wallet team's answer; the framework side is built, the server and the |
| 2239 | clients' windows are not. |
| 2240 |
| 2241 | - **Gram Wallet only, TON Connect's formats, not TON Connect's protocol.** The transaction is TON Connect's |
| 2242 | `sendTransaction` request and the payload TON Connect's `signData`, field for field, so a bot reuses its TON |
| 2243 | Connect code and the client hands both to its existing TON Connect window. There is no bridge, no session keys, |
| 2244 | no manifest and no `connect`: the widget and the wallet are in one app, and who asks is the bot that sent the |
| 2245 | message, which the client puts in the window's header. A widget cannot claim to be anyone else, and the window is |
| 2246 | the client's, outside the bubble, so a widget cannot draw a fake one. An object shaped like TON Connect's bridge |
| 2247 | was dropped: with `connect`, `restoreConnection`, `listen` and `ton_proof` missing it would only mislead |
| 2248 | (`connect` → `send` would fail), so the API is two calls of its own on TON Connect's data. |
| 2249 | - **No connection: the bot gets the wallet with a request, on a tap.** `request(data, { wallet: true })` makes the |
| 2250 | server attach the wallet card of the user's profile (the cloud wallet's address and balance) to the bot's update |
| 2251 | and create the wallet if there is none (wallets are created on the fly; where the wallet is unavailable by |
| 2252 | country, the client passes no `context.wallet` and the widget sees `null`). Never in the background: a widget must |
| 2253 | not create wallets or learn addresses without the user's action. `ton_proof` is not needed: the address comes from |
| 2254 | the server, and the bot knows who asked. |
| 2255 | - **The device's wallet signs, and the bot learns it with the outcome** (the server team, 2026-10-30). With the |
| 2256 | wallet's backup off a device keeps its own key and its own wallet, which can differ from the profile's card. So a |
| 2257 | sent transaction and a signature reach the bot with the wallet that made them (`userWallet`: address, balance, |
| 2258 | public key, StateInit), which the client fills from the device, and the profile's card comes only with |
| 2259 | `with_wallet`. A bot does not put the card's address in `from`. The device's wallet comes from the user's own |
| 2260 | client: the signature proves the key, the chain proves a payment (its sender), and an address the bot must tie to |
| 2261 | the key: by the wallet's StateInit (its hash is the address, its data holds the key; the server passes it without |
| 2262 | looking inside) or, once the wallet is deployed, by the chain's `get_public_key`, as a TON Connect back end does |
| 2263 | with `walletStateInit`. |
| 2264 | - **The grant.** A tap unlocks one call; paying needs two (ask the bot for a fresh transaction, then send it), |
| 2265 | and a transaction prepared earlier would outlive its `valid_until`. So the answer to a call made by a tap grants |
| 2266 | one wallet call within 10 s, and the answer to that call grants the next: a chain that goes on only while the |
| 2267 | user keeps confirming windows. A refusal, a failure, a background request's answer bring none; any call made on a |
| 2268 | tap or a grant uses the grant up. The grant is time-bound rather than task-bound: an answer can wait under the CPU |
| 2269 | quota, and a time window is the same rule in five glue copies (`RequestGate.decideWallet`, the fixture). |
| 2270 | - **The outcome goes to the bot, not to the widget.** The widget has no network: a signature or a signed message |
| 2271 | is of use only to the bot, and 64 bytes of `data` would not carry it. The client sends it to the server as a |
| 2272 | widget query of its own type (the transaction's normalised message hash, or `signData`'s result as is, each with |
| 2273 | the device's wallet), and the widget gets the bot's answer, as for a request. The bot checks a payment on the |
| 2274 | chain (the sender is that wallet's address, the recipients, amounts and order, the trace's success), not by the |
| 2275 | hash alone. |
| 2276 | - **The domain of `signData` is `bot<bot_id>`,** set by the client: a widget has no domain, and a verifier compares |
| 2277 | the string and checks the signature with the public key of the device's wallet that came with it. |
| 2278 | - **Tap-jacking.** A double tap over the widget is the widget's (v0.1.2): its second tap could land on Confirm in a |
| 2279 | window opened by the first. The client ignores taps on the window for its first 0.5–1 s. |
| 2280 | - **Limits.** 1–255 messages: TON Connect sets no limit of its own (each wallet declares `maxMessages`), Gram Wallet |
| 2281 | takes 255, and a limit is harder to raise later than to keep (Artem, 2026-10-30; batches of payouts and multi-step |
| 2282 | swaps need more than 4). What bounds the call instead is its size: payloads of 8192 base64 characters each and 65536 |
| 2283 | for all messages together, `signData` text and bytes of 4096, a schema of 1024. A message's destination is |
| 2284 | user-friendly only (TON Connect: a wallet must refuse a raw one, the bounce flag is in the friendly form); `from` |
| 2285 | may be raw. Any field outside TON Connect's set is refused (`items`, `extra_currency`, which Gram Wallet does not |
| 2286 | take; the SDK's `validUntil` too, rather than a transaction without an expiry). |
| 2287 | - **The server's API (agreed 2026-10-30, not shipped yet).** A query type per kind; the bot's update carries the |
| 2288 | type and, for `with_wallet`, the profile's card: |
| 2289 |
| 2290 | ```tl |
| 2291 | userWallet flags:# address:string balance:long public_key:flags.0?bytes state_init:flags.0?bytes = UserWallet; |
| 2292 |
| 2293 | widgetQueryTypeData flags:# with_wallet:flags.0?true = WidgetQueryType; |
| 2294 | widgetQueryTypeSignData wallet:UserWallet sign_data:DataJSON = WidgetQueryType; |
| 2295 | widgetQueryTypeSentTransaction wallet:UserWallet msg_hash:string = WidgetQueryType; |
| 2296 |
| 2297 | updateBotWidgetQuery flags:# query_id:long query_type:WidgetQueryType user_id:long peer:Peer msg_id:int chat_instance:long chat_type:string data:bytes widget_id:flags.0?long wallet_card:flags.1?wallet.Card = Update; |
| 2298 | updateInlineBotWidgetQuery flags:# query_id:long query_type:WidgetQueryType user_id:long inline_message_id:InputBotInlineMessageID chat_instance:long chat_type:string data:bytes widget_id:flags.0?long wallet_card:flags.1?wallet.Card = Update; |
| 2299 | updateBotWidgetCopyQuery flags:# query_id:long query_type:WidgetQueryType user_id:long data:bytes widget_id:long wallet_card:flags.1?wallet.Card = Update; |
| 2300 |
| 2301 | ---functions--- |
| 2302 |
| 2303 | messages.getBotWidgetQueryAnswer peer:InputPeer msg_id:int query_type:WidgetQueryType data:bytes = messages.BotWidgetQueryAnswer; |
| 2304 | ``` |
| 2305 |
| 2306 | In Bot API 10.4 a `widget_query` (and a copy's `shared_widget_query`) carries the query type as `type`: `data` |
| 2307 | with the card as `wallet_card` (TonWalletCard), `sign_data` with `sign_data` as JSON, `sent_transaction` with |
| 2308 | `msg_hash`, the last two with `wallet` (WidgetQueryWallet: `address`, `amount` in nanotons as a decimal string, |
| 2309 | `public_key` in hex); `state_init` is not in it yet. |
| 2310 |
| 2311 | Open: which message hash the server keeps (the normalised one, TEP-467, is what toncenter looks up), the TEP-81 |
| 2312 | form of `bot<bot_id>` for a cell signature, how jettons and NFTs show in the window. |
| 2313 |