| 6 | responsive, and how long does a bubble stay blank?* This note is the design of |
| 7 | the chat-feed demo (`apps/ios/DemoApp/Sources/ChatFeed/`, iOS only), the |
| 8 | optimisations it measures, and the numbers. Every optimisation is a switch |
| 9 | (`FeedConfig`), so `baseline` (the host exactly as the single-widget screen |
| 10 | uses it) and `max` (everything on) run in the same build, on the same corpus, |
| 11 | with the same scripted scroll. |
| 12 |
| 13 | ## What a bubble costs without any of this |
| 14 |
| 15 | One `WidgetHost` is three things, each with a start-up cost on the critical |
| 16 | path of a bubble that just scrolled in: |
| 17 |
| 18 | | part | work before the widget can show anything | where it runs | |
| 19 | |---|---|---| |
| 20 | | renderer (`WKWebView`) | configuration, data store, rule list, web content process (the first one), document load, renderer bundle parse + `ready` | main thread (creation), web process (load) | |
| 21 | | engine (QuickJS) | thread, runtime, **sandbox bundle evaluation** (linkedom + shim, 600 KB of bytecode), then the widget's own HTML/scripts | the engine's `JSThread` | |
| 22 | | validator (trusted QuickJS) | thread, runtime, validator bundle (css-tree), then every ops batch | the validator's thread, **synchronously from the main thread** per batch | |
| 23 |
| 24 | And the single-widget host serialises them: the engine does not even start |
| 25 | until the renderer says `ready`. On the simulator (Release) that is ~380 ms |
| 26 | from creation to the first content of a bubble, every bubble, plus a |
| 27 | main-thread stall of up to half a second per screen of bubbles. |
| 28 |
| 29 | ## The optimisations |
| 30 |
| 31 | All of them are host glue; the three JS bundles, the validator and the |
| 32 | invariants are untouched. Each is a `WidgetHost.Options` flag or a pool the |
| 33 | app fills, so a product can pick. |
| 34 |
| 35 | 1. **Shared WebKit environment** (`RendererEnvironment`, `Options.sharedWebKit`). |
| 36 | One process pool, one non-persistent data store, one |
| 37 | `WKUserContentController` (hardening script, the `tw` message handler, the |
| 38 | content rule list) and one scheme handler for every renderer, instead of a |
| 39 | fresh set per web view. The per-widget origin stays |
| 40 | (`tgwidget://w-<uuid>/`): the shared scheme handler serves each registered |
| 41 | document by its own URL and refuses everything else, and the shared message |
| 42 | handler routes by `WKScriptMessage.webView`. The content rule list is looked |
| 43 | up in `WKContentRuleListStore`'s on-disk cache before being compiled (a |
| 44 | compile is ~50 ms on every launch otherwise). |
| 45 | 2. **Pools** (`RendererPool`, `EnginePool`, `ValidatorPool`, `WidgetWarmup`, |
| 46 | `Options.pools`). Renderer documents are loaded ahead of time and parked |
| 47 | (their `ready` is buffered until a host adopts them); engines are created |
| 48 | with the sandbox bundle already evaluated (`SandboxEngine.prewarm()`, the |
| 49 | widget's HTML comes later with `start(html:config:)`); validators are |
| 50 | trusted contexts built on a shared thread, recycled on `destroy()` with |
| 51 | `__twValidator.create()` (a fresh instance, the bundle stays evaluated). |
| 52 | Engines are never recycled: a runtime that ran widget code dies with the |
| 53 | widget. Refills happen one at a time when the main run loop is idle and |
| 54 | the list is not scrolling (`RendererPool.canRefill`). |
| 55 | 3. **Parallel boot** (`Options.parallelBoot`): the runtime and the sandbox |
| 56 | bundle are prepared on the engine thread while WebKit loads the document; |
| 57 | only the widget's own boot waits for `ready`. |
| 58 | 4. **Validation off the main thread** (`Options.asyncValidation`): ops, |
| 59 | queries, `listen` and `preventDefault` are validated on the validator's |
| 60 | thread and only the renderer call hops to the main thread. Order is kept — |
| 61 | one serial validator thread feeding one serial main queue — so a sync layout |
| 62 | query still sees the ops flushed before it (`PoolsTests`). With one shared |
| 63 | validator thread (`Options.sharedValidatorThread`) a chat of widgets costs |
| 64 | one thread for all its validators instead of one each. |
| 65 | 5. **Transport**: `RendererWebView.transport = .callAsync` hands the JSON to |
| 66 | `callAsyncJavaScript` as an argument instead of escaping it into an |
| 67 | `evaluateJavaScript` string literal on the main thread. |
| 68 | 6. **The list's own lifecycle** (`FeedModel`, `ChatFeedViewController`): |
| 69 | - hosts are created on display or on prefetch (the collection view's |
| 70 | prefetch API plus one screen ahead in the scroll direction while a flick |
| 71 | is in flight); |
| 72 | - a bubble that leaves the screen is hidden (`setVisible(false)`: no |
| 73 | frames, timers at 1 Hz) and, beyond `keepScreens` screens away, dropped: |
| 74 | the renderer is asked for a snapshot (`WidgetHost.snapshot`, at 2 px per |
| 75 | point, kept as JPEG), the host is destroyed, the cell shows the picture |
| 76 | until the bubble comes back and a new host from the pools replaces it; |
| 77 | - heights are remembered per widget (`UserDefaults`), so a bubble is laid |
| 78 | out at its final height before the widget renders, and kept there until |
| 79 | `loaded` (markup-then-script widgets would shrink and grow back |
| 80 | otherwise); height changes are coalesced into one layout invalidation per |
| 81 | run-loop turn, and a bubble above the viewport resizes with a |
| 82 | `contentOffsetAdjustment` so the reader's view does not move; |
| 83 | - snapshots are decoded off the main thread (`preparingForDisplay`), a |
| 84 | handful kept decoded near the viewport. |
| 85 | 7. **Prewarm at launch**: a messenger fills the pools when the app starts, not |
| 86 | when a chat opens. The autorun does the same (`prewarmAtLaunch`), and the |
| 87 | setup screen prewarms while the reader looks at it. |
| 88 |
| 89 | ## Measuring |
| 90 |
| 91 | `--autorun feed --feed max|baseline --feed-count N --feed-scroll step|flick |
| 92 | [--feed-set key=value,…]` scrolls the feed like a reader (`step`: one screen, |
| 93 | pause 0.9 s, repeat, down and back up) or like a hard flick (`flick`: 2500 |
| 94 | pt/s to the end and back), then writes `feed-report.json` (the simulator's app |
| 95 | container, or the phone's Documents). Per widget: creation → renderer ready → |
| 96 | first content → loaded (the `WidgetDiagnostics` clocks), and the same from the |
| 97 | moment the bubble was displayed (negative when prefetch finished first), pool |
| 98 | hits, layout jumps, recreations, snapshot. Per phase: main-thread hitch rate |
| 99 | (`CADisplayLink` late time per second, the number Xcode's hitch instrument |
| 100 | reports), worst frame, dropped frames, freezes > 100 ms. Plus the process |
| 101 | memory footprint (the app process only — the web content process is WebKit's |
| 102 | and not counted), pool statistics and a breakdown of main-thread work |
| 103 | (`host-create`, `renderer-create`, `layout-invalidate`, …). |
| 104 |
| 105 | ```bash |
| 106 | cd apps/ios/DemoApp && xcodegen generate && xcodebuild build -scheme TwidgetDemo -configuration Release -destination 'platform=iOS Simulator,name=iPhone 17,OS=26.5' CODE_SIGNING_ALLOWED=NO -derivedDataPath /tmp/twidget-sim |
| 107 | xcrun simctl install booted /tmp/twidget-sim/Build/Products/Release-iphonesimulator/TwidgetDemo.app |
| 108 | xcrun simctl launch booted org.telegram.widgetsandbox.TwidgetDemo --autorun feed --feed max --feed-count 40 --feed-scroll step |
| 109 | cat "$(xcrun simctl get_app_container booted org.telegram.widgetsandbox.TwidgetDemo data)/Documents/feed-report.json" |
| 110 | ``` |
| 111 |
| 112 | Measure in Release: a debug build of quickjs-ng is several times slower and |
| 113 | moves every number. |
| 114 |
| 115 | ## Numbers (iPhone 17 simulator, iOS 26.5, Release, 2026-10-10) |
| 116 |
| 117 | 40 widgets (compat + the start of the generated corpus), each after a text |
| 118 | bubble; the same scripted scroll for both presets. "display → content" is |
| 119 | what the reader waits for: from the bubble appearing to the renderer's first |
| 120 | size report after validated ops; negative means the widget was ready before |
| 121 | the bubble came into view (prefetch). "loaded" is from host creation. Hitch |
| 122 | rate is main-thread late frame time per second of scrolling. |
| 123 |
| 124 | | `step` scroll (read a screen, flick, repeat) | baseline | max | |
| 125 | |---|---|---| |
| 126 | | display → content, median / p90 | 370 / 669 ms | ready before display / −195 ms | |
| 127 | | loaded (host creation → scripts done), median / p90 | 381 / 677 ms | 17 / 61 ms | |
| 128 | | renderer ready (creation → `ready`), median | 363 ms | 4 ms (pooled) | |
| 129 | | first screen on a cold open, display → content | 755 ms (3 bubbles) | 597 ms (process launch; the pools were still filling) | |
| 130 | | hitch rate down / up | 61 / 0 ms/s, worst frame 294 ms, 4 freezes | 4.2 / 2.1 ms/s, worst 53 ms, 0 freezes | |
| 131 | | layout jumps seen by the reader | 35 | 11 (post-load growth of charts and timers) | |
| 132 | | app memory peak | 277 MB (40 live runtimes) | 127 MB (≤ ~12 live, snapshots for the rest) | |
| 133 | | hosts created / dropped | 40 / 0 | 75 / 68 (recreated on the way back up) | |
| 134 |
| 135 | | `flick` scroll (2500 pt/s to the end and back) | baseline | max | |
| 136 | |---|---|---| |
| 137 | | widgets that managed to load | 31 / 40 | 40 / 40 | |
| 138 | | display → content, median / p90 | 393 / 690 ms | 85 / 121 ms | |
| 139 | | hitch rate down / up | 231 / 65 ms/s, worst 323 ms | 74 / 88 ms/s, worst 91 ms | |
| 140 | | layout jumps | 22 | 2 | |
| 141 | | app memory peak | 177 MB | 132 MB | |
| 142 |
| 143 | 120 widgets, `step`, max: 120/120 loaded, loaded median 19 ms / p90 65 ms, |
| 144 | hitch 4.6 ms/s both ways, memory peak 116 MB, 236 hosts created and 229 |
| 145 | dropped over 3.5 minutes of scrolling — the list does not grow with the chat. |
| 146 |
| 147 | What each switch is worth (step, 40 widgets, `max` minus one): |
| 148 |
| 149 | - `park=false` (prefetched views not in the window): hitch 8.7 / 10.2 ms/s |
| 150 | instead of 3.7 / 4.1 — WebKit reports the height only once the view is on |
| 151 | screen, so the layout happens while the bubble is being shown. |
| 152 | - `asyncValidation=false`, `callAsync=false`: within noise on the simulator |
| 153 | (hitch 0.5–4.6 ms/s either way). Kept in `max` because the main-thread cost |
| 154 | they remove scales with the ops a widget emits and with the number of |
| 155 | cores a phone has, both worse on a device than on the simulator. |
| 156 | - `poolRenderers=6,poolEngines=3`: no gain in `step`; the pools are refilled |
| 157 | between flicks anyway. |
| 158 | - `keepScreens=4`: hitch 2.2 / 1.5 ms/s (fewer re-creations on the way back) |
| 159 | for 166 MB instead of 103 MB peak. The knob a product tunes by device. |
| 160 | - Without the `rendered` ack (`WidgetDiagnostics.rendered`), the flick run |
| 161 | had 117 layout jumps and 138 layout invalidations: `loaded` arrives from |
| 162 | the engine before the renderer has applied the loading ops, so the bubble |
| 163 | would briefly adopt the empty document's height. With it: 2 and 2. |
| 164 |
| 165 | What is left on the critical path with everything on: the widget's own boot |
| 166 | in QuickJS (the loaded median of 17 ms is mostly `__twDispatch('boot')` + |
| 167 | scripts; Chart.js / D3 widgets reach 60 ms), and on a cold open the web |
| 168 | content process launch (~600 ms on the simulator before the first renderer |
| 169 | is ready — a messenger prewarms at launch and never pays it in a chat). |
| 170 | Still open: the same pools on Android, and a renderer `reset` op so a |
| 171 | `WKWebView` could be recycled instead of created at idle (≈4 ms of main |
| 172 | thread each, see decisions.md). |
| 173 |
| 174 | ### iPhone 17 Pro Max (iOS 27.0.1), Release, 40 widgets, `step` |
| 175 |
| 176 | The same build on the phone (`xcrun devicectl device process launch … --autorun |
| 177 | feed …`, the report copied with `devicectl device copy from --domain-type |
| 178 | appDataContainer`). The phone is several times faster than the simulator on |
| 179 | the baseline path, and the optimisations still turn the wait into zero: |
| 180 |
| 181 | | `step`, iPhone 17 Pro Max | baseline | max | |
| 182 | |---|---|---| |
| 183 | | display → content, median / p90 | 88 / 149 ms | ready before display (p90 −132 ms) | |
| 184 | | loaded (host creation → scripts done), median / p90 | 103 / 161 ms | 27 / 60 ms | |
| 185 | | renderer ready, median | 82 ms | 4 ms | |
| 186 | | first screen on a cold open, display → content | 167 ms median, 202 max (4 bubbles) | 93 ms (2 bubbles) | |
| 187 | | hitch rate down / up | 16.3 / 0 ms/s, worst frame 33 ms | 1.5 / 13.8 ms/s, worst 37 ms | |
| 188 | | layout jumps | 34 | 4 | |
| 189 | | app memory peak | 286 MB | 126 MB | |
| 190 |
| 191 | | `flick`, iPhone 17 Pro Max | baseline | max | |
| 192 | |---|---|---| |
| 193 | | widgets that managed to load | 29 / 40 | 40 / 40 | |
| 194 | | display → content, median / p90 | 54 / 140 ms (of those that loaded) | ready before display (p90 −126 ms) | |
| 195 | | hitch rate down / up | 5.1 / 0 ms/s | 3.5 / 0 ms/s | |
| 196 | | layout jumps | 28 | 0 | |
| 197 | | app memory peak | 211 MB | 126 MB | |
| 198 |
| 199 | The way back up in `step` costs `max` 14–15 ms/s on the phone (26–28 dropped |
| 200 | frames of ≤ 37 ms over 28 s, no freezes), and `keepScreens=4` does not change |
| 201 | it (15.2 ms/s, 152 MB peak), so it is not the re-creation of dropped bubbles |
| 202 | but the bursts of cell work when a screen of snapshots and hosts swaps in |
| 203 | after the flick; the flick run shows 0 ms/s on the way up. Left as the next |
| 204 | thing to profile on the device. |
| 205 |
| 206 | 120 widgets, `step`, max, on the phone: 120/120 loaded, every bubble ready |
| 207 | before it was displayed (p90 −1208 ms), loaded median 26 ms / p90 62 ms, |
| 208 | hitch 1.5 ms/s down and 8.9 ms/s up (worst frame 38 ms, no freezes), memory |
| 209 | peak 127 MB and 58 MB at the end after 235 hosts created and 227 dropped over |
| 210 | three minutes of scrolling. |
| 211 |
| 212 | ## Corpus (2026-10-12) |
| 213 |
| 214 | The setup screen's **Widgets** picker chooses what fills the bubbles: `showcase` |
| 215 | (default on the phone: `corpus/showcase`, the 21 interactive demos in exactly |
| 216 | the web feed's order — each batch shuffled with the web's seeds, one of each |
| 217 | batch in turn, the web's text bubbles before every other one) or `classic` |
| 218 | (compat → generated → Telegram demos, the set every number above was measured |
| 219 | on; still the default from a shell, `--feed-set corpus=showcase` switches). Since |
| 220 | v0.1.1 every widget fills its bubble, as on a client: no bubble padding (the widget's |
| 221 | body margin is the inset), the cell clips the widget at its 16 px corner radius, and |
| 222 | the bubble's colour is the `bg_color` the feed passes. |
| 223 |
| 224 | ## The feed bar (2026-10-12) |
| 225 |
| 226 | The feed got the web feed's bar (`docs/chat-feed-web.md`), a SwiftUI strip |
| 227 | over the UIKit list (`FeedBar` / `FeedSwitches` in `ChatFeedView.swift`), |
| 228 | applied live through `ChatFeedViewController`: |
| 229 |
| 230 | | Switch | What it does | |
| 231 | |---|---| |
| 232 | | **WebView / Blitz / litehtml** | `FeedModel.switchRenderer`: every live bubble's host is destroyed and boots again behind the new `Renderer` seam — the visible ones at once, parked ones when scrolled to; heights are remembered, killed bubbles stay stopped. The report keeps the first host's timings; the overlay samples every boot | |
| 233 | | **pool** | `FeedModel.setPools`: hosts created from now on take from the pools (filled now) or boot cold (pools drained); the overlay keeps one column of samples per setting, so one scroll with the pool on and one with it off compare on the same screen | |
| 234 | | corpus, hostile, bubbles | a rebuild (`rebuild()`: every host dropped, metrics cleared, scroll to the top; renderer and pool setting stay). `hostile` puts one `corpus/attacks` file in the third bubble, on the first screen, like the web feed: `fallback-at-boot` (killed by the boot slice, the markup stays), `cpu-raf-burn` (throttled, "CPU deferred ×N" in the caption), `timer-flood`, `api-fetch`, `markup-img-src`, `mem-*`; a killed bubble is never re-run | |
| 235 | | reset, ▶ scroll | reset = the rebuild above; ▶ scroll = the autorun's scripted scroll on demand (writes feed-report.json at the end), a second tap stops it | |
| 236 |
| 237 | The overlay (the status label) now shows, like the web one: corpus, renderer, |
| 238 | live / dropped / stopped counts, the pools, `create → content` and |
| 239 | `shown → content` (median / p90, negative = ready before the reader got there) |
| 240 | per pool setting, pool misses, memory, what the validator and shim blocked and |
| 241 | how often the CPU quota deferred a task. Each bubble's caption starts with the |
| 242 | renderer it is on and whether it came pooled or cold. From a shell the same |
| 243 | switches: `--feed-set renderer=blitz,hostile=cpu-raf-burn,corpus=showcase`. |
| 244 |