@shotik/mcp 0.1.1 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/data/PROTOCOL.md CHANGED
@@ -160,7 +160,104 @@ Attachment { id, type, size, width|null, height|null, path } // path is serv
160
160
  `configure({ appKey, serverUrl })`, `identify(user?)`, `reset()`, `setPushToken(token|null, platform)`,
161
161
  `open(conversationId?)`, `close()`, `select(conversationId|null)`, `send(body, conversationId?, attachments?)`,
162
162
  `retry(localId)`, `handoff(conversationId)`, `markRead(id)`, `pull()`, `foreground()`, `disconnect()`, `stop()`,
163
- observable state `{ status, userId, conversations, messages, unread, unreadBy, typing, open, activeConversationId, error }`.
163
+ observable state `{ status, userId, conversations, messages, unread, unreadBy, typing, open, activeConversationId, error, aiConsent, subscription, widget, friction }`.
164
+ v1.1 adds `setAiConsent(allowed)`, `setSubscription(sub|null)`, `track(kind, data?, conversationId?)`, `runAction(action, conversationId?)`,
165
+ `rate(conversationId, score, comment?)`, `reviewMoment(name)`, `friction(f)`, `openFriction()`, `dismissFriction()`, `askForOffer(reason)` (§3.7-3.12).
166
+
167
+ ### 3.7 AI consent (v1.1)
168
+
169
+ Apple 5.1.2(i) needs explicit permission before a user's messages reach a third-party AI. identify sends
170
+ `aiConsent: true | false` once known (omitted while unknown); the server keeps it on support_users.ai_consent. The founder's
171
+ Mac drafts with AI only when it is true; otherwise the conversation goes to the founder with one localized note
172
+ ("A person from the team will reply here."). Client API: `setAiConsent(allowed)`, config `aiConsent` (consent the host app
173
+ already collected), state `aiConsent` (null = not asked). Widget: one line above the composer until the user picks,
174
+ "Replies may be drafted by AI and checked by the team." with "Allow" / "Only a person" (ru «Ответы может готовить ИИ,
175
+ команда их проверяет.» «Разрешить» / «Только человек»). Stored on the device under `shotik.support.aiConsent`.
176
+
177
+ ### 3.8 Subscription context (v1.1)
178
+
179
+ `setSubscription(sub | null)` sends `subscription` with identify: `{ status: trial | active | grace | billing_retry | cancelled | expired | refunded | none, product, period (P1W | P1M | P3M | P6M | P1Y | lifetime), price (localized string), renewsAt, expiresAt, trialEndsAt (ms), willRenew, store (app_store | play | stripe) }`.
180
+ The founder sees it next to the chat; the AI uses it. identify's anonymousId is also the analytics anonymous id (both read
181
+ `shotik.support.anon`), so the founder's GET /v1/support/context returns the user's last 30 analytics events and last 3
182
+ screens. Swift reads StoreKit 2 itself when the host opts in (Product.SubscriptionInfo.status / Transaction.currentEntitlements);
183
+ React Native and Flutter take it from the host (RevenueCat customerInfo or the platform billing library).
184
+
185
+ ### 3.9 Actions in messages (v1.1)
186
+
187
+ A founder or AI message may carry `meta.actions: [{ id, kind, label, value? }]`, at most 3. kinds:
188
+ `manage_subscription`, `restore`, `redeem_code` (value = offer code), `change_plan` (value = product id), `request_refund`, `open_url` (value = https URL), `write_review`, `custom` (value = the host's action id, e.g. `restore_streak`).
189
+ The widget renders them as buttons under the message. On tap: the host's `onAction(action)` (returns done | cancelled | failed);
190
+ without one, the fallbacks open through `openUrl`: manage → apps.apple.com/account/subscriptions (Play:
191
+ play.google.com/store/account/subscriptions), refund → reportaproblem.apple.com, redeem → apps.apple.com/redeem?ctx=offercodes&id=APPID&code=CODE,
192
+ review → apps.apple.com/app/idAPPID?action=write-review (config `appStoreId`). Swift's built-ins: AppStore.showManageSubscriptions,
193
+ AppStore.sync, AppStore.presentOfferCodeRedeemSheet, Transaction.beginRefundRequest, the SubscriptionStoreView for change_plan.
194
+ Every tap reports POST /support/v1/events `{ kind: 'action', conversationId, data: { actionId, action, label, result } }`.
195
+ Nothing that touches money or is public leaves the founder's Mac without the founder's click. The AI may attach only
196
+ manage_subscription and restore. An answer that proposes a code, a plan change, a refund or a custom action goes to the founder
197
+ (needs_human) without it, and only a founder reply sends those buttons. Refunds and disputed charges always go to the founder.
198
+
199
+ ### 3.10 Subscription screen and honest cancel (v1.1)
200
+
201
+ GET /support/v1/config → `{ offers: { too_expensive?, not_using?, bug?, other?: { kind: 'chat', label } }, offerEligible, review, quietScreens, customActions }`.
202
+ The founder sets each offer as a code, a plan change or a chat; the device only ever gets its label. `askForOffer(reason)` posts
203
+ offer_accepted and opens a new conversation whose first message carries `meta.trigger { kind: 'offer', element: reason }`. The
204
+ AI never answers it: it goes to the founder, whose reply sends the code or the plan change as an action button.
205
+ offers is empty while the user is inside the founder's offer cooldown (default 60 days after an offer_shown).
206
+ When the host gave a subscription, the widget home shows a Subscription row: plan, price, renewal date; then Manage
207
+ subscription, Restore purchases, Redeem code, Request a refund, Cancel subscription.
208
+ - Cancel: one optional reason (too_expensive, not_using, bug, mistake, other) with Skip, and "Cancel in App Store" on the
209
+ same screen. Then at most one alternative from offers[reason] next to "Continue to cancel" at equal weight. "mistake"
210
+ goes straight to the refund screen. No second offer, no countdown, no "you'll lose everything".
211
+ - Refund: a help-first screen (Restore, Chat with us) with "Request a refund" visible without scrolling.
212
+ - Events (POST /support/v1/events, `kind` + optional `conversationId` + flat `data`): cancel_started, cancel_reason { reason },
213
+ offer_shown { reason }, offer_accepted { reason }, cancel_continued, refund_help, refund_requested.
214
+ - Renewed after support (server only, never posted by an SDK; attribution, not proof): when an identify brings a
215
+ subscription that will renew (active or trial, willRenew not false) after one that would not (cancelled, billing_retry,
216
+ grace, or willRenew false), and the user had a conversation, cancel_started or refund_requested in the 30 days before
217
+ without an offer_accepted, the server records renewed_after_support { from }. The week card counts it as "Renewed after
218
+ support".
219
+ - Support saved is only money the store actually charged, never projected: the first paid charge (analytics purchase done
220
+ with a price, not a trial, §4) within a year after an offer_accepted ("Saved at cancel", at the price charged, discounted
221
+ or not) or after a renewed_after_support ("Renewed after support"), counted in the week it charged.
222
+
223
+ ### 3.11 Reviews (v1.1)
224
+
225
+ `reviewMoment(name)` counts a success moment on the device (`shotik.support.review` ledger) and calls the host's
226
+ `requestReview` (Swift: AppStore.requestReview built in) only when every rule from config.review passes: moments[name]
227
+ reached, minDaysSinceInstall, not yet asked in this app version, under maxPerYear (3), no friction in this session, and the
228
+ quiet days after friction (7) and after a refund or cancel (30). Never from a button, never after a "do you like it?"
229
+ question (Google forbids it; Apple calls it filtered feedback). Each ask posts review_prompt { moment, version }: the store
230
+ API never says whether the prompt showed, so this is the ledger. A persistent "Rate {app}" row opens the write-review link.
231
+
232
+ ### 3.12 Friction chip and CSAT (v1.1)
233
+
234
+ `friction({ kind: purchase_fail | rage | error, screen?, element? })` (React Native wires analytics onEvent to it) shows a
235
+ non-modal chip "Something wrong? Write to us" after a failed purchase, a rage tap, or the same error three times in a
236
+ session: once per session, never on config.quietScreens, and not for 7 days after "Not now". `openFriction()` opens the
237
+ widget; the first message carries `meta.trigger { kind, screen, element }` and the server keeps it on the conversation.
238
+ `dismissFriction()`. Events: friction_shown, friction_opened, friction_dismissed { friction }.
239
+ When a conversation is resolved the thread shows "Did this help? 👍 👎" once; `rate(conversationId, 1 | -1, comment?)` →
240
+ POST /support/v1/conversations/:id/rating; the conversation keeps csat and csat_at, and Conversation carries `csat`.
241
+
242
+ **Founder-only rows.** Events with a conversation land there as author `event` messages. The server never sends them to
243
+ the device (stream, pull, delivered receipts).
244
+
245
+
246
+ ### 3.13 Delete my data (v1.1)
247
+
248
+ Apple 5.1.1(v) and GDPR erase. The widget home ends with a "Delete my data" row («Удалить мои данные»). It opens a confirm:
249
+ "Delete your chats and app usage data? This can't be undone." with "Delete" (danger) and "Cancel" (ru «Удалить ваши
250
+ переписки и данные об использовании приложения? Это нельзя отменить.» «Удалить» / «Отмена»), then "Your data is deleted."
251
+ or, offline, "We'll finish deleting when you're back online." («Удалим, когда появится сеть.»).
252
+ `deleteMyData()` wipes the device at once: conversations, the send queue, the session, ids, AI consent, the review ledger and
253
+ the push token. It also calls the install's analytics `forget()` (config `analytics`, else ShotikAnalytics once initialized; a forget
254
+ that can't reach the server still starts a new analytics install). Then it sends POST /support/v1/erase with the old user
255
+ token. Offline or on a 5xx/429 the token waits on the device under `shotik.support.erase` and is retried with backoff (2 s doubling
256
+ to 5 min), on foreground and after an app restart. It resolves `done` or `pending`.
257
+ The server deletes every conversation, message, attachment file, claim and event of the install's support users (the
258
+ signed-in one and the anonymous one before it), the user rows, and what analytics recorded for the install's anonymous id.
259
+ Synced rows become empty tombstones, so the founder's Macs drop them too. One founder-only event stays,
260
+ `sdk.data_erased { conversations, messages, attachments }`, with no user id. Repeating the call is harmless.
164
261
 
165
262
  ## 4. Analytics
166
263
 
@@ -172,18 +269,25 @@ Type codes are array positions: **append only, never reorder.**
172
269
  |---|---|---|---|
173
270
  | 0 | session | a new session starts | `first: 1` on the first session of the install; `store: 'none' \| 'error'` when the install id can't be persisted (no storage, or the read threw), so every launch looks new (APPC-20, additive). Key order `first, store` |
174
271
  | 1 | open | app to foreground | |
175
- | 2 | close | app to background | |
272
+ | 2 | close | app to background | `perf` (the SDK's own cost this session, see Self-cost below; APPC-20, 2026-11-29, additive) |
176
273
  | 3 | screen | screen shown (`name` = screen) | `from` (previous screen), `resume: 1` after foreground, `ms` ready time |
177
274
  | 4 | leave | screen left (`name` = the screen left) | `dur` ms, `depth` 0..1 (2 decimals), `drag` pt, `stalls`, `maxStall` ms |
178
- | 5 | tap | any tap | `el`, `label`, `x`, `y` (pt, rounded), `nx`, `ny` (0..1000 of the window), `dead: 1`, `input: 1`, `id` |
179
- | 6 | rage | 3 taps within 800 ms and 40 pt | `el`, `label`, `n: 3`, `x`, `y`, `id` |
180
- | 7 | scroll | reserved (scroll goes into `leave`) | |
275
+ | 5 | tap | any tap | `el`, `label`, `x`, `y` (pt, rounded), `nx`, `ny` (0..1000 of the window), `dead: 1`, `input: 1`, `id`, `resp` ms (see below). `x`, `y`, `nx`, `ny` are absent on masked taps (inside `<ShotikMask>` or a secure text input, 7) |
276
+ | 6 | rage | 3 taps within 800 ms and 40 pt, at least one of them without a `resp` | `el`, `label`, `n: 3`, `x`, `y`, `id` (`x`, `y` absent when masked) |
277
+ | 7 | scroll | a touch scrolled a container and it settled at a new offset (APPC-20, 2026-11-29: defined, was reserved) | `el`, `id` (the container), `off` pt, `len` content length pt, `vis` visible length pt, `hz: 1` for a horizontal container, `pg` page index of a pager. Key order `el, id, off, len, vis, hz, pg`; `el` is dictionary packed |
181
278
  | 8 | error | uncaught error or reported one | `msg` ≤ 200 chars, `fatal: 1`, `stack` top 5 frames ≤ 120 chars each, no values, no URLs |
182
279
  | 9 | slow | screen ready > 700 ms, or a main-thread stall > 1000 ms | `ms`, `kind: 'ready'\|'stall'` |
183
- | 10 | purchase | purchase lifecycle (`name` = product id) | `product`, `status: start\|done\|cancel\|fail`, `price` (decimal major units), `currency` (ISO 4217), `store` (`app_store`, `play`, `stripe`…), `trial: 1` |
184
- | 11 | custom | `track(name, props)` | free-form, no PII by contract |
185
- | 12 | identify | `identify(userId, traits)` | `traits` |
280
+ | 10 | purchase | purchase lifecycle (`name` = product id) | `product`, `status: start\|done\|cancel\|fail`, `price` (decimal major units), `currency` (ISO 4217), `store` (`app_store`, `play`, `stripe`, `revenuecat`…), `trial: 1`, `renew: 1`, `conv: 1`, `at` (see Purchases below). Key order `product, status, price, currency, store, trial, renew, conv, at` |
281
+ | 11 | custom | `track(name, props)` | free-form; string values redacted and personal-data keys dropped on the device (7) |
282
+ | 12 | identify | `identify(userId, traits)` | `traits` (same key filter and redaction as custom props) |
186
283
  | 13 | snapshot | a wireframe was recorded for this screen | `n` node count |
284
+ | 14 | net | a request failed (status ≥ 400 or a network error) or took > 3 s (APPC-20, 2026-11-29, additive) | `m` method, `host`, `path` template, `s` status (`0` = network error), `ms`. Key order `m, host, path, s, ms`; all plain props (not dictionary packed) |
285
+ | 15 | field | a text input lost focus (APPC-20, 2026-11-29, additive) | `id`, `el`, `ms` (time focused), `edits` (change events, capped at 20; absent on secure inputs), `filled: 1` (the input holds a value at blur). Never a value, a length or characters. Key order `id, el, ms, edits, filled`; `el` is dictionary packed like a tap's. `ts` = the focus time, `screen` = the screen at focus |
286
+ | 16 | state | the UI-state fingerprint of the current screen changed (APPC-20, 2026-11-29, additive) | `h` (8 lowercase hex characters, a 32-bit hash), `n` (element count). Key order `h, n`; plain props |
287
+ | 17 | gesture | a touch that was neither a tap nor a scroll ended (APPC-20, 2026-11-29, additive) | `k`: `long`, `swipe`, `pan` or `pinch`; `dir`: `left`, `right`, `up`, `down` (swipe, pan) or `in`, `out` (pinch); `dx`, `dy` pt (end minus start, rounded; a pinch's centroid); `ms` duration; `el`, `id` (the touched element, tap rules); `sc` (pinch only: end span / start span, 2 decimals). Key order `k, dir, dx, dy, ms, el, id, sc`; `el` is dictionary packed. Never a position |
288
+
289
+ Codes 15 `field` and 16 `state` are the analytics-100x design's `field` and `state` (its numbering assumed `gesture` at 14
290
+ before `net` took that code); `gesture` (item C) took the next free code, 17.
187
291
 
188
292
  Every event: `{ seq, ts, type, sessionId, screen?, name?, props? }`. `screen` is the current screen when the event happened.
189
293
  Props whose value is undefined/nil are left out; booleans travel as `1` and are absent when false.
@@ -192,11 +296,100 @@ Props whose value is undefined/nil are left out; booleans travel as `1` and are
192
296
  touched element, joined with `>`, at most 3 segments, plus `#<id>` when the element has a developer id (testID,
193
297
  accessibilityIdentifier, Flutter `Key` value). Generic containers are skipped. `label` is the element's accessibility
194
298
  label, else its visible text, ≤ 40 characters, and empty for masked elements and inputs. Tap targets that handle no
195
- press are `dead: 1`; text inputs are `input: 1`.
299
+ press are `dead: 1`; text inputs are `input: 1`. A handler is an element with real press handling (React Native: an
300
+ `onPress`-style prop, a button/link role, a responder host that isn't a scroll view, a `GestureDetector`, or a
301
+ pressable native host such as the gesture-handler button or a switch), never an ancestor matched by name: providers
302
+ like `GestureHandlerRootView` or `LinkingContext` wrap every tap. A dead tap takes its id and label only from the
303
+ touched element, and a label only when it hit text.
196
304
  - **Stable element key (`id`, added 2026-11-28 by APPC-20, additive).** The developer's id for the element: testID or
197
305
  nativeID in React Native, accessibilityIdentifier on iOS, the `Key` value or `Semantics(identifier:)` in Flutter; React
198
306
  Native falls back to `"h" + hash(fiber index path)`. It is a plain prop (not dictionary packed). Key order as core.ts builds it: tap `el, x, y, nx, ny,
199
307
  id, label, dead, input`; rage `el, id, label, n, x, y`. Without it the server keys elements on `el|label`.
308
+ - **Response (`resp`, added 2026-11-29 by APPC-20, additive).** Milliseconds from the tap to the first response: a
309
+ screen change or the start of a network request, within 1.5 s. A response belongs to the newest tap only, so a tap is
310
+ resolved by its screen change, by the next tap, or 1.5 s later, and is queued then with its own `ts` and screen (so
311
+ `dt` can be negative, 4.3). Props key order: tap `el, x, y, nx, ny, id, label, dead, input, resp`. A tap with no
312
+ handler is `dead: 1` unless the screen changes within 1.5 s, and a dead tap never carries `resp`. `resp` absent
313
+ means "no response" only when the batch's device context has `sdk` (older SDKs never send it). A rage burst whose
314
+ taps all had a response (steppers, counters that call the network) is not rage.
315
+ A UI-state change (`state`, below) is a response too, added 2026-11-29: while fingerprints run, a tap that is
316
+ resolved without a response waits for the next fingerprint walk (at most 1.5 s after the tap). If that walk finds a
317
+ changed state, every tap waiting for it gets `resp` = ms from the tap to the walk, so a fast "Next, Next, Next" through
318
+ a single-route stepper is three responded taps and no rage. Such a `resp` is an upper bound (the walk runs about 400 ms
319
+ after the last tap); screen changes and request starts still go to the newest tap only. Dead taps never wait.
320
+ - **UI-state fingerprint (`state`, added 2026-11-29 by APPC-20, additive).** A 32-bit hash of the set of interactive
321
+ elements visible on screen, so one route with several states (an onboarding pager, a multi-step paywall, a stepper)
322
+ splits into virtual steps (`onboarding@3` on the server). Walk: from the analytics root, visit the live tree, skip
323
+ hidden subtrees (inactive navigator screens, `accessibilityElementsHidden` / `no-hide-descendants`, `display: none`,
324
+ hidden offscreen/Activity trees), collect each interactive element (the handler rule above) that intersects the
325
+ window, keyed by its developer id (testID, nativeID; iOS accessibilityIdentifier; Flutter Key) or else `"h" +
326
+ hash(index path from the nearest screen)`, plus `"c" + key` for each visible virtualized-list cell. Sort, dedupe, join
327
+ with `\n`, FNV-1a 32 → `h` as 8 hex characters; `n` is the set size. When: about 400 ms after a tap, 600 ms after a
328
+ horizontal swipe, 700 ms after a screen change, 800 ms after a vertical scroll; never while a finger is down; at most
329
+ once per second (and never more often than 1000 × the last walk's ms, so a 3 ms walk runs at most every 3 s). The
330
+ first walk after a screen change is the screen's baseline and is not sent; later walks send `state` when `h` differs
331
+ from the last one on that screen; a walk after a vertical scroll only moves the baseline (scrolled feeds aren't
332
+ steps). Old-architecture React Native (no synchronous layout) treats every mounted element as visible. `h` is
333
+ comparable within one app and platform, not across SDKs. Budget: ≤ 1 ms per walk (sdk/react-native/test/analytics-rn.test.ts
334
+ measures a 4000-fiber synthetic tree).
335
+ - **Fields (`field`, added 2026-11-29 by APPC-20, additive).** One event per focus span of a text input, sent when it
336
+ blurs (or when the screen changes or the app goes to the background while it is focused). React Native listens with
337
+ capture-phase `onFocusCapture` / `onBlurCapture` / `onChangeCapture` on the analytics root View: `topFocus`,
338
+ `topBlur` and `topChange` are bubbling events with captured names in the base view configs on both platforms
339
+ (react-native 0.81 `BaseViewConfig.ios.js`, `BaseViewConfig.android.js`, `RCTTextInputViewConfig.js`), so no
340
+ per-input wiring and no `TextInput.State.currentlyFocusedInput()` polling. Only targets inside a TextInput count
341
+ (Switch also sends `topChange`). `filled` reads whether the text is empty at that moment and keeps only the flag.
342
+ `id` and `el` follow the tap's element rules (`el` = `TextInput` or `TextInput#<testID>`), so a field joins its taps.
343
+ - **Purchases from store truth (added 2026-11-29 by APPC-20, additive).** React Native wraps RevenueCat's purchase calls
344
+ for `start`, `cancel`, `fail` and the `done` of a purchase made through them, and adds
345
+ `Purchases.addCustomerInfoUpdateListener`: each active entitlement's latest purchase time is compared with a
346
+ watermark per product (`shotik.analytics.purchases`, 5). A newer one is a `done` with `at` = the store's purchase time
347
+ (ms), `trial: 1` when the entitlement is in its TRIAL period, `renew: 1` when it isn't the first purchase of that
348
+ subscription (a renewal or a re-subscribe: count it as revenue, never as a new purchase), and `conv: 1` on the first
349
+ paid period after a trial this install saw. Entitlements bought before the install's first launch, and everything
350
+ seen during `restorePurchases`, only move the watermark. The wrapped call's own `done` also carries `at` when the
351
+ result has it. Every device of a user reports the same renewal, so servers dedupe `done` events on
352
+ `(product, at)` when `at` is present.
353
+ - **Network (`net`).** fetch and XMLHttpRequest (URLSession / HttpClient in the native ports) are wrapped once at
354
+ start. Every request start counts as a tap response; only failures and slow calls become events. Never sent: bodies,
355
+ headers, query strings, fragments, credentials, or the scheme. `path` is a template: a segment that is a number or
356
+ digit run (`2026-11-29`), a UUID or hex id (16+ hex characters), a token of 8+ characters with 2+ digits, or an
357
+ email becomes `:id`, keeping a file extension (`/img/:id.png`); at most 120 characters. Requests to the Shotik
358
+ server are not recorded. Budget: ≤ 0.05 ms added per request.
359
+ - **Touch classes (`gesture`, `scroll`, added 2026-11-29 by APPC-20, additive).** Every touch, from its first pointer
360
+ down to its last pointer up, is exactly one of these (pt = points, `max` = the largest distance from the start point
361
+ any move reached):
362
+ - **tap**: one pointer, `max` ≤ 12 pt, ≤ 500 ms. Unchanged otherwise (`tap`, `rage`, `resp`).
363
+ - A touch the OS cancels (`touchcancel`: a native scroll view or recognizer took it over after its touch slop) is a
364
+ scroll when it moved > 3 pt along an axis a container scrolls, a `long` when still and > 500 ms, else nothing.
365
+ - **long**: one pointer, `max` ≤ 12 pt, > 500 ms. Before 2026-11-29 a press held 500-1500 ms was a tap and a longer
366
+ one was dropped; both are now one `gesture` with `k: 'long'`.
367
+ - **scroll**: one pointer that moved > 12 pt along an axis that a scroll container around the touched element scrolls
368
+ (the nearest one on that axis: a horizontal drag on a carousel inside a vertical feed scrolls the carousel, a
369
+ vertical drag on it scrolls the feed). No `gesture` event. The container's offset is read 600 ms after the touch
370
+ ends and then every 300 ms until two reads agree (at most 3 s, so momentum has settled); when it differs by ≥ 1 pt
371
+ from the last offset sent for that container (0 at first), one `scroll` event: `off` (offset along the axis),
372
+ `len` (content length), `vis` (visible length), `hz: 1` (horizontal), `pg` (paging containers only:
373
+ `round(off / vis)` with `pagingEnabled`, `round(off / snapToInterval)` with a snap interval). `el`/`id` follow
374
+ the tap's element rules applied to the container (testID, nativeID, else `"h" + hash(fiber index path)`). React
375
+ Native reads the offset from the host scroll view's layout (scroll view rect minus its content container's rect,
376
+ DOM API) and falls back to a VirtualizedList's scroll metrics; the same read now feeds `leave.depth` for every
377
+ vertical container. The `ts` is the touch end, the `screen` the screen at the touch end; nothing is sent when
378
+ the screen changed before the read.
379
+ - **swipe**: one pointer, moved > 12 pt with no scroll container on that axis, ≤ 300 ms and ≥ 0.3 pt/ms.
380
+ - **pan**: any other one-pointer move with no scroll container on that axis.
381
+ - **pinch**: two or more pointers down at once at any point. `sc` = the distance between the first two pointers
382
+ when the touch ended over the distance when the second one went down; `dir` `out` when `sc` > 1.
383
+ `dir` for swipe and pan is the dominant axis of `dx`, `dy` (screen y grows downwards: `up` = negative `dy`).
384
+ A gesture's `ts` is the touch start, its `screen` the screen at the touch end. One event per touch at most, built at touch end (≤ 0.5 ms, one fiber walk up plus one layout read per scroll
385
+ read); positions never leave the device, only deltas.
386
+ - **Self-cost (`perf` on `close`, added 2026-11-29 by APPC-20, additive).** Every `close` carries the session's
387
+ running totals, so the session's last `close` holds what the SDK cost in this app on this device:
388
+ `perf = { tap, walk, fp, rb, eb }`: `tap` p95 ms of the touch-end handler (element identity plus classification),
389
+ `walk` p95 ms of a replay capture (walk plus diff, 4.7), `fp` p95 ms of a UI-state fingerprint walk, each over the
390
+ session's last 256 samples with 3 decimals, absent without samples; `rb` replay bytes and `eb` event bytes the SDK
391
+ uploaded successfully in this session before this `close` (request bodies; the close's own flush counts in the next
392
+ one). A plain nested object, not dictionary packed.
200
393
  - **Sessions.** A new session starts when there is none or the app was idle longer than `sessionTimeoutMs` (30 min).
201
394
  `sessionId` = `"s_" + random`; `seq` restarts at 1 per session and increases by 1 per event.
202
395
  - **Dedupe.** The server keys events on `(app, sessionId, seq)` and ignores repeats, so a retried batch never double
@@ -207,7 +400,8 @@ Props whose value is undefined/nil are left out; booleans travel as `1` and are
207
400
 
208
401
  ### 4.2 Batches and upload
209
402
 
210
- `POST /analytics/v1/events` with `x-shotik-key`, body = the packed batch (4.3) → `{ accepted, duplicate }`.
403
+ `POST /analytics/v1/events` with `x-shotik-key`, body = the packed batch (4.3) → `{ accepted, duplicate }`. Replay chunks
404
+ travel on their own route, `POST /analytics/v1/replay` (4.7), never inside event batches.
211
405
 
212
406
  - Queue limit **2000** events (oldest dropped). Batch size **300**. Flush every **10 s** (`flushMs`), at 300 queued, on
213
407
  background, and on `flush()`. One upload at a time; while the queue holds ≥ 300 after a success, flush again at once.
@@ -237,8 +431,17 @@ PackedEvent = [dt, type, seq, session, screen, name, props]
237
431
  `dt` can be negative: a tap is resolved after the event and can be queued behind the next screen's events while
238
432
  keeping its own earlier `ts` and screen. Servers sort by `ts` (store.ts ingest does) and never assume order.
239
433
  - `props` is `0` when the event has none, else an object.
240
- - `DeviceContext` (analytics naming): `{ platform, os, model, app, build, locale, tz, w, h }` (`w`/`h` = window size in
241
- points, rounded). `platform` is `ios`, `android`, `macos`, or `web`.
434
+ - `DeviceContext` (analytics naming): `{ platform, os, model, app, build, locale, tz, w, h, ota, ch, rt, sdk, tzo, dev }`
435
+ (`w`/`h` = window size in points, rounded). `platform` is `ios`, `android`, `macos`, or `web`. Release context
436
+ (APPC-20, 2026-11-29, additive; absent fields are left out):
437
+ - `ota`: the id of the running over-the-air update (Expo `Updates.updateId`); absent when the embedded bundle runs,
438
+ so a store build is `app` + `build` and an OTA release is `app` + `build` + `ota`.
439
+ - `ch`: the update channel (`Updates.channel`). `rt`: the runtime version (`Updates.runtimeVersion`).
440
+ - `sdk`: the SDK and its version, `<sdk>/<semver>`: `rn/0.1.1`, `swift/…`, `flutter/…`.
441
+ - `tzo`: the UTC offset in minutes, east positive (`-new Date().getTimezoneOffset()`; UTC+8 = 480).
442
+ - `dev: 1` in development builds (React Native `__DEV__`, Swift `DEBUG`, Flutter `kDebugMode`), absent otherwise, so
443
+ servers can leave dev sessions out of release numbers.
444
+ Swift and Flutter fill `ota`/`ch`/`rt` only when they have an update mechanism; `sdk`, `tzo` and `dev` always.
242
445
 
243
446
  Example: two taps and a screen on Paywall become
244
447
 
@@ -252,13 +455,15 @@ Example: two taps and a screen on Paywall become
252
455
 
253
456
  A privacy-safe picture of one screen, recorded once per screen per sampled session (`snapshots` share, default 0.2,
254
457
  decided at session start). `WireNode = [kind, x, y, w, h, fill?, radius?]` in points, kinds `v` view, `t` text (a bar,
255
- never characters), `i` image (a box, never pixels), `b` button, `n` input (never its value), `s` scroll, `m` masked.
458
+ never characters), `i` image (a box, never pixels), `b` button, `n` input (never its value), `s` scroll, `m` masked
459
+ (replay, 4.7, adds `w` web view).
256
460
  Cap 400 nodes; skip views smaller than 2×2 pt, hidden, fully transparent or off screen. `fill` is `#RRGGBB` of the
257
461
  background when opaque. The server keeps the newest 3 per screen.
258
462
 
259
463
  ### 4.5 Client API
260
464
 
261
- `configure({ appKey, serverUrl, consent?, snapshots?, flushMs?, sessionTimeoutMs?, debug? })`, `track(name, props?)`,
465
+ `configure({ appKey, serverUrl, consent?, snapshots?, flushMs?, sessionTimeoutMs?, debug?, labels?, replay? })` (`labels`: 7; `replay`: `false` or
466
+ `{ wifiOnly? }`, 4.7), `track(name, props?)`,
262
467
  `identify(userId|null, traits?)`, `screen(name)`, `purchase({ product, status, price?, currency?, store?, trial? })`,
263
468
  `error(e, fatal?)`, `setConsent(granted|denied|pending)`, `optIn()`, `optOut()`, `reset()`, `flush()`, `ids`.
264
469
 
@@ -271,9 +476,90 @@ background when opaque. The server keeps the newest 3 per screen.
271
476
  | Open / close | AppState | scene / application notifications | `AppLifecycleListener` |
272
477
  | Crashes | global error handler | `NSSetUncaughtExceptionHandler` chained to the previous handler (Swift traps stay with the crash reporter) | `FlutterError.onError` + `PlatformDispatcher.onError`, chained |
273
478
  | Stalls | 500 ms timer drift | background watchdog pinging the main queue | `SchedulerBinding` frame timings |
479
+ | Network (`net`, `resp`) | fetch and XMLHttpRequest wrapped once at init | URLProtocol (APPC-22) | HttpOverrides (APPC-22) |
274
480
  | Purchases | RevenueCat calls wrapped | StoreKit 2 `Transaction.updates` + a watermark scan of `Transaction.all` on foreground; `ShotikAnalytics.purchase(product:result:)` for start/cancel | `in_app_purchase` purchase stream adapter (duck typed, no dependency) |
275
481
  | Wireframes | host tree measure | view hierarchy walk on the main thread inside the ≤ 2 ms frame budget, encoded off main | render tree walk, encoded off main |
482
+ | Replay (4.7) | host tree walk from the root (DOM API), diffed in JS | view hierarchy walk, diffed off main (APPC-22) | render tree walk (APPC-22) |
483
+ | Gestures and scroll | the root's capture-phase touch start / move / end; scroll offset from the host scroll view's layout | the passive recognizer's touches; `UIScrollView` offset after deceleration (APPC-22) | the root `Listener`; `ScrollPosition` (APPC-22) |
276
484
  | Masking | `<ShotikMask>` / `shotikMask` | `.shotikMask()` / `view.shotikMasked = true`; secure text fields and all inputs always | `ShotikMask` widget; all `EditableText` always |
485
+ | Fields (`field`) | capture-phase focus / blur / change on the root View | `UITextField` / `UITextView` begin/end editing notifications (APPC-22) | `FocusManager` listener + `EditableText` (APPC-22) |
486
+ | UI state (`state`) | fiber walk from the root with a layout check for interactive hosts | accessibility-element walk of the key window (APPC-22) | element tree walk of `Semantics` nodes (APPC-22) |
487
+
488
+ ### 4.7 Wireframe replay (added 2026-11-29 by APPC-20, additive)
489
+
490
+ A session replay made of wireframes: a keyframe per screen, then diffs of only the nodes that changed. No characters,
491
+ no pixels, no input values; the player overlays taps, gestures and signals from the event stream by `ts`.
492
+
493
+ **Route.** `POST /analytics/v1/replay` with `x-shotik-key`, `content-type: application/json`, identity encoding:
494
+
495
+ ```ts
496
+ ReplayUpload { v: 1, a: anonymousId, why: Why, chunks: ReplayChunk[] } // chunks ascending by (sess, seq)
497
+ Why = 'sample' | 'rage' | 'dead' | 'unresponsive' | 'errtap' | 'error' | 'crash'
498
+ ReplayChunk { sess: sessionId, seq: number, t: ms, keyframe?: Keyframe, diff?: Diff, scroll?: ScrollPos[] }
499
+ Keyframe { screen: string, w: number, h: number, nodes: KeyedNode[] } // the whole picture, draw order
500
+ Diff { add?: Run[], rm?: string[], mv?: [key: string, x: number, y: number][] }
501
+ Run { after: string | null, nodes: KeyedNode[] } // consecutive nodes in draw order
502
+ KeyedNode = [key, kind, x, y, w, h, fill?, radius?, in?]
503
+ ScrollPos { node: string, y: number, x?: number } // a scroll container's content offset
504
+ ```
505
+
506
+ Answer `{ accepted, duplicate }`. The server keys chunks on `(app, sess, seq)` and ignores repeats. Exactly one of
507
+ `keyframe` and `diff` is present, except that a chunk with only `scroll` (a container scrolled, nothing else moved)
508
+ has neither. A body holds at most 64 KB of chunks (one chunk larger than that travels alone; servers accept bodies up to
509
+ 1 MB and answer 413 above). Status: 2xx removes the chunks; 5xx, 429 and network errors keep them and back off (the
510
+ analytics backoff, 1); **403** means replay is off or over quota for this app: the SDK drops what it holds and sends no
511
+ replay until the next launch; any other 4xx drops that request's chunks. `why` is `sample` for a sampled session,
512
+ else the signal that released the chunks (below).
513
+
514
+ **Nodes.** `kind` as in 4.4 (`v t i b n s m`) plus `w` (a web view). `x, y, w, h` in points, rounded. Trailing
515
+ absent slots are left out and inner ones are `null` (`["k3x9a","t",16,120,180,17]`, `["q0b","v",0,0,402,64,"#FFFFFF"]`,
516
+ `["7fz2","b",16,900,370,52,null,12,"m1p0"]`). `fill` and `radius` as in 4.4. `in` is the key of the scroll container
517
+ the node scrolls with; such a node's `x, y` are in that container's content space (0, 0 = the top left of its content),
518
+ every other node's are window coordinates. The window position of a node with `in` = the container's window position
519
+ (resolved the same way when the container has an `in` itself) plus its `x, y` minus the container's current offset; the
520
+ player clips it to the container's box. Inputs (`n`), masked subtrees (`m`, `<ShotikMask>` and secure inputs) and web
521
+ views (`w`) are one box each and nothing inside them is walked.
522
+
523
+ **Keys.** `key` = base36 of FNV-1a 32 over `kind + path`, where `path` joins, from the analytics root's host view down,
524
+ each host view's index among its parent's host children, with `.` (`"0.2.1.4"`); the host view of a virtualized-list
525
+ cell (React Native: the view rendered by a VirtualizedList CellRenderer) uses `r<item index>` instead, so a row keeps
526
+ its key when rows above it unmount. Keys are stable for an unchanged tree within an app build and platform; they are
527
+ labels for diffs, not ids to compare across platforms.
528
+
529
+ **Applying a diff** to the picture after chunk `seq - 1`: (1) delete every key in `rm` and every key that appears in a
530
+ run; (2) insert each run's nodes, runs in order, directly after the node whose key is `after` (`null` = at the start);
531
+ (3) set `x, y` of each `mv` key (same coordinate space as before); (4) apply `scroll`. In a keyframe, a container
532
+ missing from `scroll` has offset 0; in a diff it keeps its offset. A chunk's `seq` starts at 1 per session and grows by
533
+ 1 per chunk the SDK built, including chunks it later dropped. The SDK only drops whole spans that end right before a
534
+ keyframe, so a diff always applies to `seq - 1`; a server missing `seq - 1` for a diff skips to the next keyframe.
535
+
536
+ **Capture (SDK).** Walk the host tree from the analytics root: nodes whose window rect intersects the window grown by
537
+ half a window on each side (the viewport plus one screen of scroll content), prune subtrees outside it, skip what 4.4
538
+ skips, cap 600 nodes, preorder. A capture runs ~600 ms after a screen change (a keyframe), 300 ms after a tap or gesture
539
+ ends and again 1 s after it when the first capture found changes, when a scroll settles (4.1), and after a `state`
540
+ change; never while a finger is down, at most once per second, and spaced to at least 500 × the last capture's ms. A
541
+ capture on a new screen is a keyframe; so is one whose diff would add or replace more than 60% of the walk's nodes. A capture that
542
+ changed nothing sends nothing. No timers run otherwise. Budget: ≤ 2 ms per capture (walk plus diff) on the JS/main
543
+ thread; encoding happens after the walk, off the touch path.
544
+
545
+ **Who uploads.**
546
+ - **Sampled sessions** (the `snapshots` share, default 0.2, decided at session start, 4.4) upload chunks as they are
547
+ made, with the analytics flush (`why: 'sample'`).
548
+ - **Every other session** keeps a ring in memory: the chunks of the last 30 s from the newest keyframe at or before them (a
549
+ capture is a keyframe when the newest keyframe is older than 15 s, so the ring spans 30-45 s), at most 1 MB. It is uploaded only when a signal fires:
550
+ `rage`; a `dead` tap; an `unresponsive` tap (a handler, no `resp`); an `errtap` (a failed `net`, status 0 or
551
+ ≥ 400, within 2 s after a tap on the same screen); an `error`; a `crash` (a fatal error). Chunks built in the 5 s
552
+ after a signal follow it, and a stronger signal in those 5 s relabels the release (`unresponsive` < `dead` <
553
+ `errtap` < `rage` < `error` < `crash`: a rage burst first releases on its unresponsive taps). On a crash the released chunks are written to `shotik.analytics.replay` (5) and sent on
554
+ the next launch. A calm unsampled session uploads 0 replay bytes.
555
+ - Consent `pending` holds chunks (bounded like the ring), `denied` drops them and stops capture. `replay: false`
556
+ turns replay off. `replay: { wifiOnly: true }` holds uploads while the device isn't on Wi-Fi or Ethernet (React
557
+ Native asks `@react-native-community/netinfo`, else `expo-network`; with neither installed it never uploads).
558
+ Whatever is held stays ≤ 1 MB by dropping the oldest spans up to a keyframe.
559
+ - A new session starts a new picture (keyframe, `seq` 1) and empties the ring.
560
+
561
+ **Server (wt/analytics-replay-server).** A chunk store per `(app, sess)` with a per-app byte quota (403 above it) and
562
+ 30-day retention that never deletes a session an insight cites; `forget` deletes an install's chunks (7).
277
563
 
278
564
  ## 5. Storage keys
279
565
 
@@ -290,6 +576,8 @@ the app support dir), except that secrets go to the secure store.
290
576
  | `shotik.analytics.state` | `{ f: firstSeen, s: sessionId, l: lastActive, q: seq, p: sampled 0/1, u: userId }` | no |
291
577
  | `shotik.analytics.queue` | unsent WireEvents (unpacked) | no |
292
578
  | `shotik.analytics.consent` | `granted` / `denied` / `pending` | no |
579
+ | `shotik.analytics.replay` | replay chunks released by a crash, `{ a, why, chunks }` (4.7), sent and removed on the next launch | no |
580
+ | `shotik.analytics.purchases` | `{ [product]: { t: latest purchase ms, tr?: 1 when in trial } }`, the store-truth watermark (4.1) | no |
293
581
 
294
582
  Storage is read once, off the main thread, after `configure`; nothing is read at app launch before that.
295
583
  Swift always has UserDefaults and never sends `store`. Flutter's file store can fail (no app-support path from the plugin, or
@@ -322,9 +610,48 @@ Every platform's widget follows the reference's design, refs and copy so a found
322
610
  ## 7. Privacy
323
611
 
324
612
  - No IDFA, no fingerprinting, no contacts or location. Device context is the fields listed above and nothing else.
325
- - Inputs never send their value: taps on inputs carry `input: 1` and no label; wireframes draw them as `n` boxes.
326
- - Masked subtrees send no label, and wireframes draw them as one `m` box.
327
- - `custom` and `identify` props are the developer's responsibility; the docs say "no PII" for custom props.
613
+ - Network events carry method, host, a templated path, status and duration only (4.1): no bodies, headers, query
614
+ strings or credentials.
615
+ - Inputs never send their value: taps on inputs carry `input: 1` and no label; wireframes draw them as `n` boxes;
616
+ `field` events carry timing, a capped edit count (none on secure inputs) and a filled flag only.
617
+ - Masked subtrees (`<ShotikMask>`, or `shotikMask` on a view) and secure text inputs send no label and no tap position (`x`, `y`, `nx`, `ny` are
618
+ left out of the tap and its rage), and wireframes draw masked subtrees as one `m` box.
619
+ - Replay (4.7) is wireframes only: boxes with a kind, a position and a background color. Text is a bar, images and web
620
+ views are boxes, inputs, masked subtrees and secure inputs are one box with nothing inside walked. Gestures and
621
+ scroll events carry deltas and offsets, never touch positions. Masking is on by default and can't be turned off: no
622
+ option unmasks inputs, and no view's text is read, masked or not. Release gate: the RN test "replay privacy: a
623
+ TextInput value never appears in a replay frame or upload" (sdk/react-native/test/analytics-replay.test.ts); every
624
+ port carries the same case before it publishes replay.
625
+ - **What replay collects**, for the App Store privacy label (Product Interaction, not linked to the user, analytics):
626
+ screen layouts as boxes (kind, position, size, background color, corner radius), the screen's route pattern, scroll
627
+ offsets, gesture kinds with distances, and the session and install ids. Never text, input values, images, web
628
+ content or touch positions. The server keeps chunks 30 days unless an insight cites the session (4.7).
629
+ - **Right to be forgotten:** `forget()` (RN `ShotikAnalytics.forget()`) drops the device's queue, wireframes, replay
630
+ ring and crash-saved ring, sends `POST /analytics/v1/forget {anonymousId}` (the server deletes the install's events,
631
+ wireframes and replay chunks and refuses that install's chunks afterwards), and on success starts a new anonymous
632
+ install. It resolves false when the server can't be reached and keeps the id so a second call retries. Consent
633
+ doesn't gate it.
634
+ - **One redaction on the device** (sdk/react-native/src/analytics/privacy.ts `redact`, added 2026-11-29 by APPC-20), applied
635
+ before anything is queued to tap and rage labels, error messages, custom and identify string values, custom event
636
+ names, and `net` path segments. In this order: a URL's query and fragment are cut (`https://x/a?b=1` → `https://x/a`,
637
+ and a bare `?k=v…` is cut too); `Bearer …` / `Basic …` credentials and JWT-like tokens (`eyJ…`, two or three
638
+ dot-separated base64url parts) → `[token]`; emails → `[email]`; UUIDs → `[id]`; hex runs of 16+ characters with a
639
+ digit → `[id]`; other tokens of 24+ letters, digits, `_` or `-` with both a letter and a digit → `[token]`; phone
640
+ numbers (7+ digits with a leading `+`, parentheses or space-separated groups) → `[phone]`; any other run of 7+
641
+ digits with separators, and every digit run of 4+ → `[n]`. Labels then turn each remaining digit into `#` (as before).
642
+ Stacks are code, not user data, and keep only the URL stripping.
643
+ - **Labels** (`labels` option, default `'a11y'`): `'a11y'` sends the element's accessibility label, else a name derived
644
+ from its testID (`startTrialButton`, `start-trial` → `Start trial button`, `Start trial`), else nothing; `'visible'`
645
+ also falls back to the visible text under the pressed element (the pre-2026-11-29 behaviour, ≤ 40 characters);
646
+ `'none'` sends no labels. Element ids (`id`, `el`) are unaffected.
647
+ - **Personal-data keys.** Keys of `custom` props and `identify` traits (at any depth up to 3) that match
648
+ `/email|phone|name|token|password|address/i` are dropped on the device, with one console warning per key in
649
+ development builds (`__DEV__` or `debug`). That also drops harmless keys such as `plan_name`: rename them
650
+ (`plan`). String values are redacted as above. Developers still must not send personal data in custom props.
651
+ - **Network paths keep only templates.** Path segments that are ids (4.1), anything the redaction changes, or that
652
+ hold percent-encoded or non-ASCII characters become `:id`. A plain word that is personal data, such as a username
653
+ in `/users/anna`, can't be told apart from a route word and stays: put personal data in bodies or queries (never sent),
654
+ not in paths.
328
655
  - The app key is public; the user token is per-user and kept in the secure store.
329
656
  - Apple privacy manifest (`PrivacyInfo.xcprivacy`) ships with the Swift and Flutter iOS packages: UserDefaults access
330
657
  (CA92.1), `NSPrivacyTracking` false, no tracking domains, and these collected data types (none used for tracking):
@@ -346,6 +673,12 @@ Every platform's widget follows the reference's design, refs and copy so a found
346
673
  | `configure` on the main thread | < 5 ms cold (< 1 ms typical) | signpost / Stopwatch around configure in the sample app, release build, 20 launches, p95 |
347
674
  | Main-thread I/O | none | storage, network, JSON and wireframe encoding on a background queue/isolate; checked with a main-thread I/O assertion in debug |
348
675
  | Tap handler on main | < 0.1 ms p95 | measured over 1000 synthetic taps |
676
+ | UI-state fingerprint walk | ≤ 1 ms per walk, ≤ 1 walk per second, none while scrolling | sdk/react-native/test/analytics-rn.test.ts: a 4000-fiber synthetic tree with 80 interactive hosts, best of 5 runs of 200 walks |
677
+ | Replay capture | ≤ 2 ms per capture (walk plus diff), ≤ 1 capture per second, ring ≤ 1 MB | sdk/react-native/test/analytics-rn.test.ts: a synthetic host tree of ~1500 views, best of 5 runs of 100 captures; a 3 s tap storm makes ≤ 4 captures |
678
+ | Replay bytes | ≤ 150 KB per 3-minute sampled session; 0 for a calm unsampled session | the same file: a synthetic 3-minute session (12 screens, scrolls, taps, state changes) through the real walker and encoder |
679
+ | Event bytes | ≤ 25 KB per 3-minute session | sdk/react-native/test/analytics-core.test.ts: a synthetic session with taps, gestures, scrolls and screens, packed batch bytes |
680
+ | Gesture end | ≤ 0.5 ms (classification, one fiber walk up) | touch-end handler p95 over 1000 synthetic touches, which also covers the < 0.1 ms tap path |
681
+ | Wrapped network request | ≤ 0.05 ms added per request | sdk/react-native/test/analytics-rn.test.ts: 5000 requests on a stub transport, wrapped against raw |
349
682
  | Network | ≤ 1 analytics request per 10 s while active, 1 on background; support: 1 socket in the foreground, 0 in the background | counted in tests with a fake transport |
350
683
  | Memory | < 2 MB resident added with both modules idle, widget closed | sample app with and without the SDK, same build |
351
684
  | CPU idle | 0 timers firing while the app is backgrounded; one 10 s flush timer and one 500 ms watchdog in the foreground | Instruments Time Profiler / DevTools |
@@ -378,6 +711,47 @@ Each SDK runs the same cases against a fake transport and, where a server can ru
378
711
  10. Stream: `ready` → live; `typing` ttl clears; close 4003 re-identifies; other closes back off with jitter.
379
712
  11. Unread counts per conversation and in total; reading the open thread clears them.
380
713
  12. Reset gives a new anonymous id and clears the session, queue and read marks.
714
+ 13. Snapshots: a 5xx or 429 keeps the wireframe for the next flush with backoff; another 4xx drops it; a delivered one
715
+ is never sent again.
716
+ 14. Device context: `sdk` and `tzo` on every batch; `dev: 1` only in development builds; `ota` only off the embedded
717
+ bundle.
718
+ 15. `resp`: a tap followed by a screen change after 400 ms has `resp: 400`; one with no response within 1.5 s has none;
719
+ a response after a second tap belongs to the second tap only. A dead tap stays dead unless the screen changes within
720
+ 1.5 s and never carries `resp`.
721
+ 16. Rage: three taps within 800 ms and 40 pt each followed by a request start emit no `rage`; without responses, one.
722
+ 17. `net`: a 200 in 120 ms emits nothing; a 500, a network error (`s: 0`), a 404 and a 200 after 3.5 s emit one each, with
723
+ `https://u:p@API.x.com/v1/users/123/orders/<uuid>?q=1` as host `api.x.com`, path `/v1/users/:id/orders/:id`.
724
+ 18. App lifecycle (iOS): active → inactive → active emits nothing (the purchase sheet); only background emits `leave`
725
+ and `close`, and the next active `open` and `screen` with `resume: 1`.
726
+ 19. Purchases: `trial: 1` only on `done`, when the purchase result shows the bought product in a trial period (RevenueCat
727
+ entitlement `periodType: 'TRIAL'` for that product; the native ports read the store transaction's offer), never because
728
+ the product has an intro offer.
729
+ 20. Redaction: `redact('Mail anna@x.io, call +1 (555) 123-4567, order 123456, id 0193d1c2-5b7e-7c1a-9f3e-2a4b6c8d0e1f,
730
+ eyJhbGciOiJIUzI1NiJ9.eyJzdWIiOiIxIn0.sig, https://a.io/p?t=1')` =
731
+ `'Mail [email], call [phone], order [n], id [id], [token], https://a.io/p'`; custom props `{ email, user_name, plan }`
732
+ keep only `plan`.
733
+ 21. Labels: by default a tap on a button whose only label is its text "Start trial" has no `label`; with an
734
+ accessibility label "Start trial" it has it; `labels: 'visible'` brings the text back; a tap inside a mask or a
735
+ secure input has no `x`, `y`, `nx`, `ny`.
736
+ 22. `state`: the first walk after a screen change sends nothing; a walk with another element set on the same screen
737
+ sends `{ h, n }`; three taps 200 ms apart followed by a changed walk 400 ms later all carry `resp` and emit no
738
+ `rage`; an unchanged walk leaves them without `resp`.
739
+ 23. `field`: focus, 3 changes, blur after 2.5 s → `{ id, el, ms: 2500, edits: 3, filled: 1 }` with the focus time as
740
+ `ts`; a secure input has no `edits`; no value or length appears anywhere in the batch.
741
+ 24. Store truth: a customerInfo update with a newer latest purchase for a known product → `done` with `renew: 1`; a
742
+ TRIAL entitlement turning NORMAL → `renew: 1, conv: 1`; the same info twice → one event; an entitlement bought before
743
+ the first launch → nothing.
744
+ 25. `gesture`: a still 700 ms press → `{ k: 'long', ms: 700 }` and no tap; a 150 ms 80 pt move left with no horizontal
745
+ scroll container → `swipe`, `dir: 'left'`; a slow 600 ms move → `pan`; two pointers spreading 100 → 150 pt → `pinch`,
746
+ `dir: 'out'`, `sc: 1.5`; a vertical drag inside a vertical scroll view → no `gesture`.
747
+ 26. `scroll`: a horizontal paging container (`vis` 400) settling at offset 800 → `{ off: 800, len, vis: 400, hz: 1, pg: 2 }`
748
+ once; the same offset again → nothing.
749
+ 27. Replay diff: a keyframe, then the same tree with one node recolored, one removed, one moved and a container
750
+ scrolled → one diff with that node in a run, the removed key in `rm`, the moved one in `mv`, the container in
751
+ `scroll`, and applying it (4.7) to the keyframe gives the second walk's picture; an unchanged walk → no chunk.
752
+ 28. Replay upload: a sampled session uploads chunks with `why: 'sample'`; an unsampled one uploads nothing until a
753
+ rage, then the ring (starting at a keyframe 30-45 s old) with `why: 'rage'`; a 403 stops replay uploads.
754
+ 29. `perf` on `close`: `tap`, `walk`, `fp` p95 ms and `rb`, `eb` bytes sent before the close.
381
755
 
382
756
  ## 10. Versioning
383
757
 
@@ -16,10 +16,28 @@ as the React Native and Swift SDKs.
16
16
  replies, "Talk to a person", photos and screenshots, unread counts, push token.
17
17
  - The widget: a bottom sheet built from plain Flutter widgets (no Material or Cupertino look), a spring open and drag to
18
18
  dismiss, an optional launcher with an unread badge, light and dark, text scaling, semantics labels, RTL, English and
19
- Russian copy from the device locale.
19
+ Russian copy from the device locale. v1.1 screens: the AI consent line, action buttons under replies (in progress,
20
+ done, didn't work), the friction chip, "Did this help?", the Subscription screen with an honest cancel (one optional
21
+ reason, "Cancel in App Store" or Google Play on the same screen, at most one founder alternative at equal weight), a
22
+ help-first refund screen, "Rate {app}" and Delete my data with a confirm.
20
23
  - Analytics: screens from a `NavigatorObserver` (MaterialApp, CupertinoApp, GoRouter), taps identified by widget names,
21
24
  keys and `Semantics(identifier:)`, wireframes that never contain characters, `ShotikMask` for anything private,
22
- consent, one-line `in_app_purchase` wiring.
25
+ consent, one-line `in_app_purchase` wiring, tap response times, and failed or slow requests through `HttpOverrides`
26
+ (chained to any you set; method, host, a templated path, status and duration only).
27
+ - On-device privacy: tap labels from `Semantics(label:)` or the key only (`labels: Labels.visible` brings visible text
28
+ back), emails, phones, ids and tokens redacted from labels, errors and custom props, personal-data keys dropped, no
29
+ tap position inside a mask or a secure field.
30
+ - UI-state changes on one screen (pagers, steppers) as `state` events, text field focus spans without their text, and
31
+ store-truth purchases (renewals and trial conversions) from RevenueCat's customer info or `in_app_purchase`.
32
+ - Touches as one of tap, long press, swipe, pan, pinch or scroll (`gesture` events carry no position), one `scroll` per
33
+ container once it settles (with the page of a `PageView`), and the SDK's own cost on `close` (`perf`).
34
+ - Wireframe replay: keyed wireframe frames and diffs, no text and no field contents. Sampled sessions stream them; the
35
+ rest keep the last 30 s on the device and send them only after a rage, dead or unresponsive tap, a failed request
36
+ right after a tap, an error or a crash. `enable(replay: false)` turns it off; `wifiOnly: true` holds uploads until
37
+ your `wifi` callback answers true (the SDK adds no connectivity dependency). For the App Store privacy label (Product
38
+ Interaction, not linked to the user, analytics), replay collects screen layouts as boxes (kind, position, size,
39
+ background color, corner radius), the screen name, scroll offsets, gesture kinds with distances, and the session and
40
+ install ids; never text, input values, images, web content or touch positions. The server keeps chunks 30 days.
23
41
  - Flutter 3.24+ and Dart 3.5+. iOS 13+ as a Swift package (no CocoaPods); Android minSdk 21.
24
42
 
25
43
  The full walkthrough, with troubleshooting, is in [INTEGRATION.md](INTEGRATION.md). Русская версия: [README.ru.md](README.ru.md).
@@ -70,20 +88,29 @@ The iOS app needs Swift Package Manager support enabled once on the machine that
70
88
  |---|---|
71
89
  | `Shotik.configure(appKey:, serverUrl:, debug:)` | Once, as early as you like. No I/O on the calling isolate. |
72
90
  | `ShotikRoot(child:)` | Wrap the app once (around `MaterialApp`). Deep links, the screenshot boundary, the root that taps are described against, and the scroll layer. |
73
- | `ShotikSupportWidget.builder(...)` | For `MaterialApp` / `CupertinoApp` / `WidgetsApp` `builder:`. `title`, `teamName`, `theme`, `launcher`, `launcherBottom` (distance above the bottom safe area, to clear a bottom button or tab bar), `quickReplies`, `locale`. |
91
+ | `ShotikSupportWidget.builder(...)` | For `MaterialApp` / `CupertinoApp` / `WidgetsApp` `builder:`. `title`, `teamName`, `theme`, `launcher`, `launcherBottom` (distance above the bottom safe area, to clear a bottom button or tab bar), `quickReplies`, `locale`, `appName` (for "Rate {app}"), `frictionChip` (default `true`). |
92
+ | `ShotikFrictionChip(theme:, locale:)` | The "Something wrong? Write to us" chip on its own, for apps that place it (set `frictionChip: false` on the widget). |
74
93
  | `ShotikSupport.open([conversationId])`, `close()` | Show or hide the sheet. |
75
94
  | `ShotikSupport.identify(userId:, name:, email:, attributes:)`, `reset()` | Signed-in user / sign-out (new anonymous id). |
76
95
  | `ShotikSupport.setPushToken(token, platform:)` | APNs or FCM token; `null` clears it. |
77
96
  | `ShotikSupport.handleLink(uri)` | `<scheme>://support` opens the sheet. `ShotikRoot` already routes platform links here. |
78
97
  | `ShotikSupport.attachmentPicker` | Your image picker; with it set the attach menu offers "Photo". "Screenshot" needs nothing. |
79
- | `ShotikSupport.client`, `clientListenable` | The `SupportClient`: `state` (conversations, messages, unread, typing, status), `send`, `retry`, `handoff`. |
98
+ | `ShotikSupport.setAiConsent(allowed)`, `aiConsent` | The user's answer to AI-drafted replies (Apple 5.1.2(i)); `aiConsent` is consent your app already collected. Unset, the widget asks once. |
99
+ | `ShotikSupport.setSubscription(Subscription(...))` | The plan from RevenueCat or your billing code (`null`: none). The founder sees it next to the chat. |
100
+ | `ShotikSupport.onAction`, `openUrl`, `appStoreId` | Buttons under founder and AI messages (manage, restore, redeem, change plan, refund, review, custom). `onAction` returns `ActionResult`; without it the store pages open through `openUrl`. |
101
+ | `ShotikSupport.reviewMoment(name)`, `requestReview` | A success moment. Calls your review prompt only when the founder's rules pass (count, days since install, once per version, 3 a year, quiet after friction, refund or cancel). |
102
+ | `ShotikSupport.friction(Friction(kind:, screen:, element:))` | `purchase_fail`, `rage` or `error`: may show the "Something wrong?" chip, once per session. |
103
+ | `ShotikSupport.deleteMyData()` | Delete my data (Apple 5.1.1(v), GDPR): wipes chats, ids, consent, the review ledger, the push token and the install's analytics on the device at once, then has the server erase them. `EraseResult.pending` offline: retried with backoff on foreground and after a restart. |
104
+ | `ShotikSupport.client`, `clientListenable` | The `SupportClient`: `state` (conversations, messages, unread, typing, status, aiConsent, subscription, widget, friction), `send`, `retry`, `handoff`, `runAction`, `rate`, `track`, `openFriction`, `dismissFriction`, `askForOffer(reason)` (the device only has an offer's label; asking opens a conversation for the founder). |
80
105
  | `ShotikAnalytics.navigatorObserver` | One per navigator. Starts analytics. |
81
106
  | `ShotikScreen(name:, child:)` | Names a screen explicitly (tabs, pages without a route name). |
82
- | `ShotikMask(child:)` | Hidden from tap labels and wireframes. Text fields are always masked. |
83
- | `ShotikAnalytics.track(name, props)`, `screen(name)`, `identify(userId, traits)` | Custom events, manual screens, the user. |
84
- | `ShotikAnalytics.purchase(...)`, `watchPurchases(stream, products:)` | Purchases, by hand or from `in_app_purchase`. |
85
- | `ShotikAnalytics.enable(consent:, snapshots:, flushMs:, sessionTimeoutMs:, debug:)` | Options; `optIn()` / `optOut()` / `setConsent()`. |
107
+ | `ShotikMask(child:)`, `key: const ShotikMaskKey()` | Hidden from tap labels, tap positions, wireframes and replay; the key does the same as a flag on any widget (`ShotikMaskKey('pan')` tells masked siblings apart). Text fields are always masked; secure ones lose the tap position too. Masking can't be turned off. |
108
+ | `ShotikAnalytics.track(name, props)`, `screen(name)`, `identify(userId, traits)` | Custom events, manual screens, the user. Keys like `email`, `phone`, `name`, `token` are dropped and strings redacted. |
109
+ | `ShotikAnalytics.purchase(...)`, `watchPurchases(stream, products:)` | Purchases, by hand or from `in_app_purchase` (`at` from the transaction; renewals through the watermark on iOS). |
110
+ | `ShotikAnalytics.customerInfo(info, quiet:)`, `entitled([Entitled(...)])` | Store truth: `Purchases.addCustomerInfoUpdateListener(ShotikAnalytics.customerInfo)`; renewals (`renew`) and trial conversions (`conv`) once each. |
111
+ | `ShotikAnalytics.enable(consent:, snapshots:, flushMs:, sessionTimeoutMs:, debug:, labels:, replay:, wifiOnly:, wifi:)` | Options; `labels` is `Labels.a11y` (default), `visible` or `none`; `replay` (default on) is wireframe replay, `wifiOnly` holds its uploads until `wifi: () async => onWifi` answers true. `optIn()` / `optOut()` / `setConsent()`. |
86
112
  | `ShotikAnalytics.flush()`, `reset()`, `ids` | Send now, new anonymous id, current ids. |
113
+ | `ShotikAnalytics.forget()` | A user's data deletion request: drops the queue, wireframes and replay on the device, has the server delete the install's events, wireframes and replay, then starts a new anonymous install. `false` when the server can't be reached (the id is kept; call again to retry). Works whatever the consent. |
87
114
 
88
115
  | `ShotikSupportTheme` | Default | |
89
116
  |---|---|---|