| 6 |
| fourth copy of the host glue (web Worker, Swift, Kotlin, C++) over the same |
| 7 | three JS bundles; see `docs/decisions.md` (Desktop C++ core) for why the product |
| 8 | renderer is not here (tdesktop has no WebView inside the chat) and what the |
| 9 | product path on tdesktop looks like. The Blitz renderer prototype |
| 10 | (`-DTW_BLITZ=ON`, below) is dev tooling behind the same `Renderer` seam the |
| 11 | iOS/macOS and Android demos have; it and the litehtml one (`-DTW_LITEHTML=ON`) are |
| 12 | frozen since 2026-10-30 (`docs/decisions.md`, "The renderer prototypes are frozen"): no check builds them. |
| 13 |
| 14 | ``` |
| 15 | packages/desktop/ |
| 16 | sandbox/include/twidget/ public headers |
| 17 | sandbox_engine.h SandboxEngine + SandboxEngineDelegate (= SandboxEngine.swift / .kt) |
| 18 | trusted_validator.h validator-bundle.js in a second, trusted QuickJS runtime |
| 19 | widget_host.h WidgetHost: engine + validator + Renderer, one widget (= WidgetHost.swift / .kt) |
| 20 | renderer.h Renderer seam + RendererFactory (= Renderer.swift / .kt) |
| 21 | cpu_budget.h CpuBudget (fixture: packages/core/tests/fixtures/cpu-budget.json) |
| 22 | sdk_policy.h SDK v1 checks: links, haptics + HapticGate, theme params, locale, storage, bridge calls; |
| 23 | the widget's state, viewer, chat type, request answers + RequestGate, previews |
| 24 | (= SdkPolicy.swift / .kt; fixture: packages/core/tests/fixtures/sdk-policy.json) |
| 25 | gesture_policy.h the widget or the bubble: claimOf + GestureArbiter for the client's recognizers |
| 26 | (= GesturePolicy.swift / .kt; fixture: packages/core/tests/fixtures/gesture-policy.json) |
| 27 | js_thread.h one dedicated thread per runtime, 8 MB stack, timers |
| 28 | quickjs_context.h thin wrapper over quickjs-ng via packages/ios/Sources/CQuickJS/shim |
| 29 | resources.h WidgetJS/ loader + CDN URL → bundled library |
| 30 | intl.h IntlProvider; BasicIntl fallback (plug QLocale/ICU here) |
| 31 | json.h small strict JSON (hostile input: bounded depth) |
| 32 | renderer/ BlitzRenderer (twidget/blitz_renderer.h): the Renderer over ../renderer-blitz's C ABI; -DTW_BLITZ=ON only |
| 33 | LitehtmlRenderer (twidget/litehtml_renderer.h): the same over ../renderer-litehtml's C ABI; -DTW_LITEHTML=ON, macOS only |
| 34 | harness/ twidget-run + RecordingHost (fake host with canned layout answers) + png.h |
| 35 | tests/ twidget-tests (XCTest suite ported) + fixtures/ |
| 36 | WidgetJS/ bundles from `pnpm build:desktop` (committed) |
| 37 | ``` |
| 38 |
| 39 | quickjs-ng is not copied: CMake compiles `../ios/Sources/CQuickJS` (the same |
| 40 | sources Android builds). The library links only the C++ standard library, |
| 41 | pthreads and `m`; on Windows `bcrypt` (CSPRNG) and `_beginthreadex`. |
| 42 |
| 43 | ## Build and run |
| 44 |
| 45 | ```bash |
| 46 | corepack pnpm build:desktop # bundles → packages/desktop/WidgetJS, fixture → packages/desktop/tests/fixtures |
| 47 | cd packages/desktop && cmake -S . -B build -G Ninja && cmake --build build |
| 48 | ./build/twidget-tests # 75 tests (engine, limits, validator, JSThread, CpuBudget, SDK and gesture fixtures, SDK v1, JSON) |
| 49 | ./build/twidget-run ../corpus/compat/tabs.html --wait-ms 500 [--verbose] [--ops] [--probe 'document.title'] |
| 50 | ./build/twidget-run w.html --theme dark --theme-params '{"bg_color":"#212121"}' --locale ru --storage '{"local":{"n":"1"}}' \ |
| 51 | --events '{"type":"click","targetId":5,"detail":1,"gesture":1}' # SDK v1: prints `action …`, `storage …` and `resize anchor …`; "gesture" makes a trusted press (and the haptic gate's press, or its release for anything but pointerdown / mousedown) |
| 52 | ./build/twidget-run w.html --message group --viewer 42,Ann,Lee,ann_lee,premium --chat-data c1 --public-data p1 --answer '{"result":"ok"}' \ |
| 53 | --events '{"type":"click","targetId":5,"detail":1,"gesture":1}' # the bot's requests: prints `request …` and `copyText …`; --message private|group|via-bot|no-queries|live-copy|copy|preview, or --copy / --can-query / --background-query / --chat-type; --answer-error TIMEOUT, --set-data JSON |
| 54 | ./build/twidget-run --corpus ../../corpus/compat # loaded, alive, no uncaught errors; also generated/with-profile, generated/without-profile |
| 55 | ./build/twidget-run --attacks # 104 files: nothing but data:/#fragment may reach the validated ops |
| 56 | ``` |
| 57 |
| 58 | Status (2026-10-17, macOS arm64): tests 45/45; compat 12/12 and |
| 59 | generated/with-profile 20/20 load without errors; attacks 98 with 0 URLs |
| 60 | leaking into validated ops and the four expected kills (`fallback-at-boot.html`, |
| 61 | three `mem-*`). Boot of the sandbox bundle takes |
| 62 | ~20 ms in a release quickjs-ng from the precompiled `.qbc` (38–74 ms from |
| 63 | source; the diag says which one was used). |
| 64 |
| 65 | ## What the harness checks and what it cannot |
| 66 |
| 67 | Without `--blitz` there is no renderer, so layout queries (`rect`, `box`, |
| 68 | `measureText`, …) get the same canned answers as `packages/core/scripts/sandbox-node.ts`. |
| 69 | That is enough to prove the engine, the limits and the validator; pixels and |
| 70 | the renderer-side defenses (CSP, request blocking) are checked on the platforms |
| 71 | that have a WebView. |
| 72 |
| 73 | `--attacks` parses every validated `RenderOp` and flags, as a **LEAK**, any |
| 74 | attribute, inline style, stylesheet or canvas argument through which a renderer |
| 75 | could reach the network: non-`data:` URLs in attributes, `url()`-family |
| 76 | functions whose argument is not `data:`/`#…`, and `@import`. Two attack files |
| 77 | produce a **note**, not a leak: an external URL *inside* a `data:image/svg+xml` |
| 78 | payload. SVG loaded as an image may not fetch external resources in any engine, |
| 79 | and the browser attack suite confirms zero canary hits for those files. A |
| 80 | native renderer that is not a browser engine must keep that property. |
| 81 |
| 82 | ## Blitz renderer prototype (`-DTW_BLITZ=ON`) |
| 83 |
| 84 | The same Rust crate the mobile and macOS demos use (`../renderer-blitz`: |
| 85 | blitz-dom + blitz-paint + vello_cpu, validated `RenderOp`s in, layout answers |
| 86 | and events out, premultiplied RGBA8 on request) linked into the C++ core |
| 87 | through its C ABI (`include/twidget_blitz.h`). CMake runs rustup's `cargo` |
| 88 | for the host triple (`TW_RUST_TARGET`, autodetected) and links the static |
| 89 | library; macOS and Linux only for now (the Windows link line is not wired). |
| 90 | Dev tooling for `docs/blitz-experiment.md`, not a product path: the sandbox |
| 91 | and the validator are untouched, the Rust side only ever sees validated ops |
| 92 | and `data:` images. |
| 93 |
| 94 | ```bash |
| 95 | cd packages/desktop && cmake -S . -B build -G Ninja -DTW_BLITZ=ON && cmake --build build # first cargo build: 1–2 min, ≈ 39 MB static library |
| 96 | ./build/twidget-tests # 72 tests: + layout answers from the document, hit-tested clicks, frozen fallback |
| 97 | ./build/twidget-run ../corpus/compat/tabs.html --blitz --dpr 2 --png /tmp/tabs.png [--click X,Y]... |
| 98 | ./build/twidget-run --corpus ../../corpus/compat --blitz --dpr 2 --png-dir /tmp/compat # + height / paint / loaded columns, one PNG per widget |
| 99 | ./build/twidget-run --attacks --blitz # a fetch attempt from the Rust document counts as a leak too |
| 100 | ``` |
| 101 |
| 102 | ## litehtml renderer prototype (`-DTW_LITEHTML=ON`, macOS) |
| 103 |
| 104 | The C++ core in `../renderer-litehtml` (vendored litehtml, the validated DOM |
| 105 | kept as a shadow tree and re-parsed per batch, fonts and pixels from |
| 106 | CoreText/CoreGraphics — hence macOS only until a QPainter backend exists) |
| 107 | behind the same owner contract as `BlitzRenderer`: `twidget/litehtml_renderer.h` |
| 108 | is `blitz_renderer.h` with `twl_*` for `twb_*`. `docs/litehtml-renderer.md`. |
| 109 |
| 110 | ```bash |
| 111 | cd packages/desktop && cmake -S . -B build -G Ninja -DTW_BLITZ=ON -DTW_LITEHTML=ON && cmake --build build |
| 112 | ./build/twidget-tests # 75 tests: + 3 litehtml twins of the Blitz ones |
| 113 | ./build/twidget-run ../corpus/compat/tabs.html --litehtml --dpr 2 --png /tmp/tabs.png [--click X,Y]... |
| 114 | ./build/twidget-run --corpus ../../corpus/compat --litehtml --dpr 2 --png-dir /tmp/compat # 12/12, paint 0.3–6 ms at 800 px |
| 115 | ./build/twidget-run --attacks --litehtml # 104 attacks, 0 leaks, 0 fetch attempts |
| 116 | ``` |
| 117 |
| 118 | What it is on this platform: |
| 119 |
| 120 | - `twidget/renderer.h` is the seam (`Renderer` + `RendererFactory`), the C++ |
| 121 | twin of `Renderer.swift` / `Renderer.kt`. `WidgetHost` takes a factory; the |
| 122 | product renderer on tdesktop (its Web App window) would be another |
| 123 | implementation of it. |
| 124 | - `twidget/blitz_renderer.h` has no view: the owner takes rasters |
| 125 | (`paint()`, or `onPaint` from the renderer's own 60 Hz clock, which also |
| 126 | delivers `requestAnimationFrame` ticks) and feeds pointers in CSS px |
| 127 | (`touch()`, `click()`) — on tdesktop a `QWidget::paintEvent` and mouse |
| 128 | events, in the harness `--click` and `--png`. |
| 129 | - Threading: a Qt-free library has no main thread, so `WidgetHost` owns a |
| 130 | host thread that stands in for it (every renderer call, every diagnostics |
| 131 | update); the Rust document is used from the host thread, the clock thread |
| 132 | and the owner's thread one at a time, behind one mutex in `BlitzRenderer`. |
| 133 | A Qt host replaces the host thread with the UI thread one for one. |
| 134 | - Numbers (macOS arm64, 2×, RelWithDebInfo): compat 21/21 and generated 40/40 |
| 135 | load and paint, 1–9 ms per paint at 800 px wide; attacks 89 with 0 leaks and |
| 136 | 0 fetch attempts from the renderer. Gaps are the crate's, the same on every |
| 137 | platform: empty `<canvas>`, CSS not reaching inline SVG, form values and |
| 138 | sliders not drawn, no 3D transforms. |
| 139 |
| 140 | ## Embedding (tdesktop or any Qt app) |
| 141 |
| 142 | - One `WidgetHost` per widget with a `RendererFactory` for your renderer, or, |
| 143 | one level down, one `SandboxEngine` with your own `SandboxEngineDelegate`. |
| 144 | Engine callbacks arrive on the engine's thread; hop to the UI thread |
| 145 | yourself (`QMetaObject::invokeMethod` / `crl::on_main`). `onQuery` is |
| 146 | synchronous and blocks the engine thread until you answer — never answer it |
| 147 | by waiting on the UI thread from the UI thread. `WidgetHost` does all of |
| 148 | this on its host thread; `destroy()` it from the owner's thread. |
| 149 | - Every `onOps` batch goes through `TrustedValidator::processOps` before it is |
| 150 | sent to a renderer. Nothing else from the engine is trusted. |
| 151 | - Pass an `IntlProvider` built on `QLocale` to the engine; `BasicIntl` is only |
| 152 | a fallback. |
| 153 | - Limits live in `SandboxConfig` / `WidgetHostOptions` (same fields and |
| 154 | defaults as `protocol.ts`: 8 MB of QuickJS heap, 64 timers, 300 ms of JS and |
| 155 | 100 ms of main-thread work per second; `docs/decisions.md`, "Strict limits |
| 156 | from the start"). The main-thread window charges a task's layout queries and |
| 157 | 25 µs per op and 2 µs per canvas command it sent; past it, as past the JS |
| 158 | quota, timers and frames wait. Under `strict` a counted cap of the validator |
| 159 | (32 KB per text value, 48 KB of document text, 8 KB per attribute, 10 000 ops |
| 160 | per batch, 10 000 canvas commands per send, 400 CSS rules, 32 `@keyframes`) |
| 161 | stops the widget: `diagnostics().dead` carries the reason |
| 162 | (`TrustedValidator::stopped()`, `SandboxEngine::stop`), as for memory or CPU. |
| 163 | `setVisible(false)` when the bubble leaves the screen. |
| 164 | - SDK v1 (`docs/sdk-v1.md` §4.3, §5): build the host with a `WidgetTheme` |
| 165 | (scheme, this bubble's 15 `themeParams` colours, `WidgetButtonTokens`, |
| 166 | `WidgetTextTokens` with the chat's text size) and call |
| 167 | `setTheme(WidgetTheme)` on every chat theme change; pass `locale` and the |
| 168 | stored `storage` (`WidgetStorage { local, session }`) in `WidgetHostOptions`. |
| 169 | `onAction` gets checked actions only (`OpenLink` / `OpenTelegramLink` with |
| 170 | the normalised URL, at most one per pointer press; `Haptic`, rate-limited, |
| 171 | and since v0.2.2 free only while a press is down and 5 s after it is lifted, |
| 172 | else one 1 s series per touch or per 10 s: the presses are the renderer's |
| 173 | `gesture` and `release` messages, which WidgetHost passes to the engine's |
| 174 | `pressBegan` / `pressEnded`; a renderer that sends neither gets the no-touch |
| 175 | rule; `Ready`); `onStorageCommit(area, values)` the full new content of an area at |
| 176 | the end of each task that changed it, within the 4 KB quota (persist |
| 177 | `local`, keep `session` in memory); `onGesture(WidgetGestureClaim)` on every |
| 178 | primary press: what of it the widget claims with `touch-action` (`x`: |
| 179 | horizontal drags, `hold`; taps and double taps are always the widget's, and |
| 180 | since v0.1.3 a vertical drag is always the chat's: `y` is always false and |
| 181 | the arbiter scrolls the list over any widget). Feed the claim |
| 182 | to a `GestureArbiter` (`gesture_policy.h`) in your recognizers over the |
| 183 | widget and act on its verdicts: on `cancel` end the press for the widget, |
| 184 | then do the bubble's `action` (message menu, swipe-to-reply or back, list |
| 185 | scroll). `diagnostics().resizeAnchor` (since v0.1.3, `"top"` until the |
| 186 | widget calls `TelegramWidget.setResizeAnchor`) is the edge of the bubble that |
| 187 | stays put on screen when `height` changes: for `"bottom"` the bubble grows |
| 188 | upward and the content above it moves (in a top-down list, add the height |
| 189 | delta to the scroll offset while the bubble is on screen, and pin the widget |
| 190 | to the bubble's bottom during the transition). A change reaches `onChange` |
| 191 | before the height it anchors; it is not an action. With no caption below the |
| 192 | widget (none, or one shown above it) the client draws the message time over the widget's bottom corner and passes |
| 193 | `WidgetHostOptions::contentSafeArea` (`bottom`, `cornerRight` or |
| 194 | `cornerLeft`, CSS px; 0 by default) at creation and `setContentSafeArea` when |
| 195 | the bubble's layout changes (`docs/sdk-v1.md` §2.17, §5.12); the renderer gets |
| 196 | `{type:'safeArea'}` right after the theme. |
| 197 | Strings are UTF-8; a widget's lone surrogate arrives in its 3-byte WTF-8 |
| 198 | form. The string-theme constructor, `setTheme(std::string)`, `onBridgeCall` |
| 199 | and `onGestureClaim(x, y)` are deprecated forwards; the host → widget |
| 200 | `bridgeEvent` is gone. |
| 201 | - The widget's state and requests (`docs/sdk-v1.md` §2.13–§2.16, §4.4): pass the |
| 202 | widget's state, which only the bot writes, in `WidgetHostOptions::data` |
| 203 | (`WidgetData { chatData, publicData }`: the chat state and the shared state, |
| 204 | each 1–1024 bytes of text without NUL, none = `std::nullopt`) and the |
| 205 | message's flags as the server sends them in `context` (`WidgetContext { |
| 206 | isCopy, canQuery, backgroundQuery, chatType, viewer }`; all false by default: no requests; a |
| 207 | copy gets no chat type; the viewer, `WidgetViewer { id, firstName, lastName, |
| 208 | username, isPremium }`, reaches the widget only with `canQuery`, as Mini Apps' |
| 209 | `WebAppUser`, a field that breaks its rule left out with `data-rejected`); call |
| 210 | `setData(WidgetData)` with the full state on every edit from the server (the |
| 211 | widget gets `chatDataChanged`, then `publicDataChanged`, for each field that |
| 212 | changed; a copy keeps no chat state, its shared state can change). |
| 213 | `diagnostics().watchesPublicData` (false until the widget calls |
| 214 | `TelegramWidget.watchPublicData()`) says whether to poll a shared widget's |
| 215 | shared state (`public_data`) while it is on screen; `onWatchPublicData(on)` gets each |
| 216 | change (not an action, no gesture). A widget |
| 217 | in an inline-results list before it is sent gets `context.preview`: its state |
| 218 | as usual but no input (the host drops the renderer's events and gesture |
| 219 | claims; a tap is the client's), no requests or bridge calls but `ready` and |
| 220 | `setResizeAnchor` (`preview-blocked`), no chat type, viewer or storage |
| 221 | preload, and no `onStorageCommit`. |
| 222 | `onRequest(request, respond)` gets a checked request (`data` 1–64 bytes; only |
| 223 | with `canQuery`; one press unlocks one privileged call, without a press only |
| 224 | with `backgroundQuery`, while visible: one when the widget appears on screen, |
| 225 | then one per 5 s; one in flight): send it like a callback button's press and |
| 226 | call `respond` once, from any thread, with a `WidgetRequestOutcome` (the |
| 227 | server's answer, `result`: text of at most 1024 bytes without NUL; or a |
| 228 | `Timeout` / `RateLimited` / `Failed` failure); later calls and calls after |
| 229 | `destroy()` are ignored. Without `onRequest` when a request is delivered, the |
| 230 | widget gets `NOT_ALLOWED`. `onCopyText(text)` (1–256 UTF-16 code units, one |
| 231 | per press): copy it and show a toast. Neither is an action; both are read on |
| 232 | the host thread. On a bare `SandboxEngine` the delegate gets |
| 233 | `onBridgeRequest` (completing a `WidgetRequestResponder`, or |
| 234 | `respond.unsupported()`) and `onBridgeCopyText`. |
| 235 |