Skip to content

Spec: Expo mobile PostHog analytics — pairing, activation and notification outcomes #1929

Open
0 of 1 issue completed

Description

@DoodleBears

Spec: DeepSeekBot Expo 移动端匿名使用统计

Parent: #1643。Related: #948、#1644、#1645、#1646。

Problem Statement

我们已经能看到官网访问、插件使用和 Campaign Link 点击,却无法回答原生 iOS/Android App 是否成功完成配对、连接、首次聊天和通知审批,也无法区分功能未被使用与连接失败。

2026-10-16 调研基于 freshly fetched main e6abf66710c5f34267e2e5f8a91f6668c5459366。Expo 57 / React Native 0.86 App 已有配对、多个 Host、Chats / Activity、DM / Group、Human Inbox、通知按钮、文件、语音、Browser / Computer viewer 和 Full Web Client。移动 workspace 未发现 PostHog 依赖或 analytics/telemetry 调用。Host 的 plugin_started / daily_usage 不具备原生 App 的使用视角。

PostHog DeepSeekBot project 648269 的本次最近 7 天原始摄取盘点只有 plugin(6,566)、site / Web SDK(6,498)、links(275);没有 native/mobile 来源。它们是事件条数,含测试流量的原始盘点,不是用户数、业务转化率或永久不存在移动事件的证明。之前查到的 Mobile 官网 pageview 属于手机浏览器,不能代表 Expo App。

Solution

为原生 App 增加一条独立、内容无关、可关闭的匿名事件流,复用同一 PostHog 项目和第一方摄取代理,固定 source=mobile,与 site / plugin / links 分开分析。

先完成“开启匿名统计 → 配对 → Host 数据就绪 → 首次有效聊天”的可运行纵向切片,再补通知审批闭环。分析口径以实际完成的操作为准,不以按钮点击或动画完成代替成功。后续按需扩展功能使用与可靠性,不给所有点击、消息、流式 token 都埋点。

以下是待实现规格,不代表已上线;确认过的 Human 验收边界是:复用 Host client、Conversation、PushSession,通过可注入埋点出口验证真实结果、去重和隐私,再分别做 iOS、Android 真机及 PostHog 收数验收。

User Stories

  1. As a maintainer, I want native App events separated from mobile website visits, so that I can measure the correct product surface.
  2. As a maintainer, I want version, platform and environment breakdowns, so that I can locate release-specific regressions.
  3. As a maintainer, I want pairing starts and outcomes, so that I can find onboarding losses.
  4. As a maintainer, I want QR, pasted-link and deep-link entry categories, so that I can compare pairing paths without collecting links.
  5. As a maintainer, I want pairing persistence failures separated from offer redemption, so that a half-finished pairing is not counted as success.
  6. As a maintainer, I want usable Host data distinguished from socket connectivity, so that connection success reflects what the Human can use.
  7. As a maintainer, I want bounded reconnect outcomes, so that background recovery can be improved without counting every retry.
  8. As a maintainer, I want first Host-accepted mobile sends, so that I can measure activation rather than composer clicks.
  9. As a maintainer, I want newly observed Bot messages distinguished from cached history, so that old conversations do not manufacture activation.
  10. As a maintainer, I want permission and push-registration outcomes, so that unavailable notifications can be diagnosed.
  11. As a maintainer, I want notification opens and target-load outcomes, so that a tap on an obsolete notification is visible.
  12. As a maintainer, I want approval and question outcomes from the owning Host, so that stale requests and failed actions are not counted as successful decisions.
  13. As a maintainer, I want notification-button actions included even when the approval screen does not open, so that the main phone workflow is measured.
  14. As a maintainer, I want multi-Host switching separated from first-time pairing, so that switching does not inflate activation.
  15. As a maintainer, I want aggregate DM and Group usage, so that I can prioritize native chat capabilities without a per-message event stream.
  16. As a maintainer, I want Full Web Client fallback usage by fixed destination category, so that I can prioritize missing native capabilities.
  17. As a maintainer, I want attachment, dictation and remote-viewer outcomes, so that attempted use is distinguishable from usable results.
  18. As a Human, I want to understand and disable this phone's anonymous statistics before pairing, so that I control collection even when my Host is unreachable.
  19. As a Human, I want names, messages, files, addresses, credentials and notification contents excluded, so that analytics never copies my workspace.
  20. As a Human, I want telemetry failure to leave my connection, messages and approvals unaffected, so that analytics is never a product dependency.
  21. As a developer, I want one typed, injectable analytics boundary, so that behavior and privacy can be tested without contacting a vendor.
  22. As a reviewer, I want independent automated, native-device and ingestion evidence, so that successful unit tests are not mistaken for a shipping integration.

Implementation Decisions

1. Scope, ownership and delivery

  • The native App owns an application-defined Mobile Telemetry service. Product modules report semantic outcomes through its typed interface; only its sender adapter knows PostHog. Screens must not call a vendor SDK independently. No generic interception of Host RPC arguments, responses or socket frames.
  • Host client, Conversation, Requests, HostSession and PushSession remain the owners of their existing behavior. Instrument their accepted outcomes without adding another message, approval or pairing authority. The App remains a Consumer of the existing Host Client bridge / API Gateway; no new Host RPC is required for this spec.
  • Amend the current Host-only telemetry definition in ADR-0132 with a new mobile decision and integrate it into the living architecture / product glossary. This is an explicit extension, not an assertion that the existing Host-only ADR already authorizes native collection.
  • First tracer: privacy controls + mobile event boundary + pairing / connection / activation + one real-device PostHog path. Pause for Human QA before widening. Second tracer: permissions / push / notification / request resolution. P1 and P2 below are ranked follow-up scope, not permission to start every sibling at once.
  • Prefer a posthog-react-native adapter, subject to qualification against Expo SDK 57 and the first-party proxy. Disable automatic lifecycle, screen, touch, exception, replay, feature-flag and survey collection; emit the approved event dictionary manually. Check actual pinned SDK options and inspect the serialized payload. If its defaults cannot satisfy the allowlist, use the existing minimal PostHog batch protocol behind the same interface; do not relax privacy to accommodate an SDK.
  • Install compatible native dependencies through Expo's version-aware workflow. A dependency/configuration requiring native code needs new development builds; a Metro reload alone is not native verification.

2. Event dictionary and priority

All names below are proposed new events. result, reason, screen, entry and similar fields are bounded enums; never arbitrary strings from an error, route, user or Host.

Priority Event Exact trigger / meaning Additional allowed properties
P0-A mobile_app_opened One foreground session starts after telemetry is enabled; not each React render or temporary system permission dialog launch_kind=cold/resume, paired_host_count_bucket=0/1/2plus
P0-A mobile_pairing_started One explicit QR/paste/deep-link submission begins, before parsing; repeated scan callbacks for the same ongoing attempt do not count entry=qr/paste/deep_link, random attempt_id
P0-A mobile_pairing_result Attempt reaches a terminal result; success requires offer redemption and saved Host persistence, not just an HTTP 200 Same attempt; result=success/refused/failed/cancelled, reason allowlist including invalid/expired link, no route, invalid/expired offer, unreachable, storage failure, unknown; duration bucket
P0-A mobile_connection_result One connection episode reaches authenticated, usable initial Roster data, an explicit refusal, cancellation or a 30-second observation deadline trigger=pair/open/resume/switch/recovery/manual_retry, result=ready/refused/timeout/cancelled, bounded refusal class, duration bucket, retry-count bucket, random attempt ID
P0-A mobile_activation_step Each step at most once per anonymous mobile identity: first live Roster; first Host-accepted mobile send; first newly committed Bot message observed while its conversation is foreground after that accepted send step=host_ready/message_accepted/bot_message_observed, channel_kind=dm/group where applicable
P0-B mobile_permission_result Result of a permission interaction initiated by the Human, or a detected permission-state change on resume; not every status poll permission=notifications/camera/microphone/speech, entry=request/resume, result=granted/denied/unavailable/undetermined
P0-B mobile_push_registration_result A logical enable/register episode finishes; permission granted alone is not registration success result=success/partial/failed/unavailable, failed-Host-count bucket, bounded reason, random attempt ID
P0-B mobile_notification_opened OS delivers a notification response/tap or action to the App; deduplicate cold-start response and live listener kind=tool_approval/user_question/private_input/reply/mention/badge/test/unknown, action=open/approve/reject/always, random flow ID
P0-B mobile_notification_target_result The intended Host and destination's data become ready, or opening is refused/unavailable/expired; router navigation alone is not success Flow ID, result=ready/host_missing/refused/unreachable/unavailable/expired, duration bucket
P0-B mobile_request_result Tool approval or Human question operation finishes through the owning Host, including direct notification buttons kind=tool_approval/user_question, entry=dm/group/activity/notification_action, result=accepted/already_decided/expired/failed, bounded reason; flow ID only for notification flow
P1 mobile_screen_viewed A normalized native destination becomes foreground/focused, once per visit screen allowlist: chats, activity, dm, group, pair, settings, notifications, usage, bot_profile, memory, bot_activity, browser, computer, full_client; no route parameters
P1 mobile_host_selected A user- or notification-requested switch has persisted the chosen local selection; connection is measured separately entry=drawer/notification, paired-Host-count bucket
P1 mobile_chat_summary A closed foreground chat segment or periodic checkpoint, containing disjoint count deltas; no single-message events channel_kind, buckets for sends accepted/failed/retried, committed Bot messages observed, attachment sends; duration bucket
P1 mobile_full_client_result Explicit fallback entry and initial WebView load outcome; network load is not proof the target task completed target=home/dm/channel/new_bot/new_channel/private_input, result=opened/loaded/failed, duration bucket
P1 mobile_feature_result An explicit native feature operation completes, not each render/poll/frame Fixed feature / action / result combinations for attachment upload/share, dictation, Browser/Computer initial frame and takeover, Memory view, routine save, profile/settings save, stop Bot
P2 mobile_performance_sample A capped diagnostic sample for a preselected experience, when measurement tooling is validated Fixed metric name, numeric duration or bucket, build/platform; never a claim to measure native FPS from JS timings
P2 mobile_error_summary Bounded aggregation of classified app errors after a separate privacy review Stable error code, count bucket, owning surface; no raw messages or stacks in this slice

Feature-result success semantics: attachment upload is Host acceptance, sharing means handoff to the OS share UI (not recipient receipt), dictation means recognition produced usable input (not that a message was sent), viewer ready requires first usable frame, takeover requires Host acceptance. Never collect image pixels, transcript, filename, clipboard contents, coordinates or typed remote-control input. P1 feature enums should only be enabled with that feature's focused test and review; no catch-all feature/property escape hatch.

3. Semantics, deduplication and identity

  • Use a random, app-owned Mobile Install ID, separate from the Host Install ID, paired-device ID, Host ID and site visitor. Do not call identify / alias with any of those identities; do not join website campaigns to mobile or Host installations. Keep person-profile creation off.
  • Persist mobile telemetry identity and its activation markers as telemetry-only local state. They are not domain state. Scope is an installation/telemetry identity, not a Human. Unpairing or switching Hosts does not make a new mobile install. Turning off telemetry clears queued events and identity; enabling again starts a new identity, disclosed as a limitation of retention counts. Native uninstall/restore identity behavior must be verified rather than assumed from SecureStore behavior.
  • Each outbound event gets an independent event ID / PostHog deduplication identifier. Retries reuse it. Attempt/flow IDs are random and bounded to the local operation; never reuse or hash a real message, notification, device, Channel, Bot, offer or Host ID for analytics. Local domain IDs may be used only internally for deduplication and must never enter the sender payload.
  • Pairing scan replay, StrictMode remounts, response listener replay, socket reconnects, Host switching and Channel history replay must not duplicate one semantic event. An explicit new user retry is a new attempt; route fallback inside an attempt is not.
  • The connection observation deadline does not stop product reconnection. A later recovery is a separate recovery episode, not an overwrite of a timeout; repeated backoff ticks emit no events. Backgrounding cancels a still-pending foreground observation instead of inventing a timeout. Record ready only after the usable live data condition, not when a socket opens or cached Roster appears.
  • First message acceptance uses channelSend success or canonical reconciliation of the same outgoing message after ambiguous network failure. The immediate local outgoing ID / optimistic bubble is not acceptance. Replayed message history cannot increment activation or usage.
  • bot_message_observed is a client observation, not proof of a causal reply to that first send, successful model execution, task completion or every reply delivered. No prompt-to-reply latency metric is promised without a verified correlation contract. Streamed draft/token frames are not committed messages.
  • Approval accepted means the Host accepted the Human's decision; that decision may be rejection. Do not equate accepted with “allowed”. Do not collect the tool name, command, arguments, question text, answer, saved permission rule or secret. Private input records only fallback opening; never submission/result data from the secret form.
  • Native foreground-session identity expires after 30 minutes in background; short OS dialogs do not create a new session. A random session ID may support same-session funnels. Durations use monotonic clocks and fixed buckets: under 1s, 1–5s, 5–15s, 15–60s, 60s or more. App termination can lose an unfinished segment; do not pretend to have a reliable app-closed callback.

4. Privacy, transport and configuration

  • New mobile policy in this spec: explicit local opt-in to “此手机的匿名使用统计”, available on first use and in Settings even before pairing/offline. Declining or ignoring is fully usable and sends nothing, including SDK bootstrap/config requests. No backfill of pre-consent actions. This is distinct from the existing Host's default-on policy; changing Host defaults is out of scope. The App explains that its switch controls this phone, while Host statistics keep their existing separate controls. Do not claim Host environment variables automatically control a native SDK.
  • Common allowlist: source=mobile, schema_version=1, platform=ios/android, public app version/build, environment=production/preview/development, supported language code, random telemetry identity/session/event IDs. Missing version values become unknown. No branch names, local build paths, hardware identifiers, advertising IDs or device names. Event-specific enums and buckets are the only additional application properties. Review SDK-added properties at serialized egress too, not only the properties passed to capture.
  • No Host URLs, tailnet addresses, QR/deep-link payloads, paired-device credentials, Expo push tokens, Bot/Channel/Session/message identifiers, names, conversation text, Memory, file paths, search text, raw errors, notifications or tool arguments. Do not hash these values as a substitute for exclusion.
  • Use the existing first-party ingest proxy with the public ingestion project token only; never bundle management API credentials. Existing proxy code forwards an IP for ingestion processing, so do not describe it as IP-free transport. Verify effective PostHog IP-discard / GeoIP configuration before production enablement, and ensure app payloads never add an IP property. If native-specific proxy handling is required, preserve website behavior and add a focused proxy test.
  • Keep the SDK/sender out of HostCarrier credential-bearing requests. Telemetry must not inherit Authorization, route URLs or Host headers. No new DSH interceptor or relay is needed.
  • Use a bounded asynchronous queue (at most 100 events, 256 KiB, 24-hour TTL; oldest-first eviction), sanitized before persistence, with bounded backoff and stable event IDs. A maximum 8-second send timeout and no synchronous wait in chat/approval paths. On opt-out, cancel new uploads and discard queued data; an already transmitted request cannot be recalled. No diagnostic retry loop may emit events about its own failed sends.
  • Development, test, Simulator and Expo web-preview paths send nothing by default. A deliberately enabled QA build is tagged preview/development; analytics dashboards exclude it. Production credentials/config must not silently be reused by tests. The App's Web export is a preview target and does not count as native usage.
  • Update the mobile notice and public privacy descriptions in the first implementation slice, in supported languages; check store privacy declarations against the actual serialized collection. Do not announce that the existing public Host-only promise already covers the new App stream.

5. Analysis views to enable

Question Definition Interpretation boundary
Can opted-in installations activate? Open → pairing success → first Host ready → first accepted mobile send; installation-level ordered funnel within 7 days, plus a separate observed-Bot-message step New installations cohort; returning paired installs skip pairing. No estimate of all installs or non-consenting users
Where does pairing fail? Pairing success / started, paired by attempt ID; failure buckets by entry and platform Explicit attempts, not people; abrupt process death leaves censored attempts
Does the phone become usable? Ready / terminal connection episodes, split by trigger and platform; timeout/refusal shown separately Do not mix a new pairing with reconnect or claim socket open is usable
Do notifications help complete work? Notification response → target ready → accepted request, restricted to actionable kinds; direct notification action → request result is a separate branch Not a push-delivery/open rate: OS delivery denominator is unavailable here. Repeated/expired requests remain visible
Do users return? D1/D7 return on mobile_app_opened and separately on meaningful use, by Mobile Install ID Anonymous installation retention among opted-in users; disabling/reinstalling/identity reset breaks continuity
What should become native next? Full-client fallback counts and failed/loaded proportions by fixed target Opening new_bot or private input is not completed creation or secret submission

Use the project's confirmed timezone (currently Asia/Shanghai), event-time platform/build/environment and source=mobile filters. Publish actual denominator and exclusions in each dashboard. Avoid combining Host daily_usage and mobile chat summaries into a single message total: they are overlapping observations with different identities. This research does not create dashboards or modify PostHog settings.

Testing Decisions

The Human confirmed the testing boundary described above. Test externally observable behavior, not capture-call placement or snapshots of implementation internals.

  1. One injectable typed Mobile Telemetry boundary supplies a test sink, controllable clock, identity store and transport. Reuse HostCarrier / recorded stream fixtures and Conversation / PushSession fakes; do not create a second fake product implementation.
  2. Use existing Host-client tests as prior art: route fallback, Host restart, revoked credential, live Roster and pairing. Assert the whole ordered event sequence for valid pairing, parse refusal, expired offer, storage failure, timeout, recovery and multi-Host switching.
  3. Use existing Conversation tests: optimistic send, Host acceptance, retry with the same outgoing ID, cached history, live committed messages and stream replay. Assert first accepted-send activation once; no success on refusal; no raw per-message/token events; no cached-history activation; no duplicate after reconciliation.
  4. Use existing Requests / Inbox and push tests: accepted/decided/expired results, registration permission denial, offline-Host retry, cold/warm notification open, direct action buttons, wrong/missing Host, and already-resolved requests. Test acceptance once through the shared owner even when multiple UI entry paths can trigger it.
  5. Test actual serialized egress using sentinel secrets in QR URLs, route/credential headers, device names, messages, errors, file names and notification data. None may appear in payload, persisted queue or diagnostic output. Unknown fields and arbitrary strings must be rejected, not forwarded. Verify defaults added by the real SDK adapter.
  6. No config / no opt-in / declined / disabled / preview-web states: zero vendor requests and no queued historic events. Verify opt-out clears the queue and identity and survives restart. Verify bounded size/TTL, retry deduplication, timeout and telemetry failure without delaying or failing product actions.
  7. Native QA, scheduled through the repository's shared-device queue: iOS and Android separately. Exercise one real Host pairing, first chat, background/reconnect, notification permission, notification tap and button, already-processed request, opt-out and offline recovery. Simulator tests do not prove physical push delivery; iOS results do not prove Android.
  8. PostHog acceptance uses an explicitly tagged QA build and a pre-recorded expected event sequence. Confirm source/platform/build/environment, allowed fields, identities, exact-once observations within the tested paths, and no events after disabling. Record ingestion delay and any loss separately. Inspect the first-party proxy and PostHog-visible payload, not only a mocked sender.
  9. Evidence categories in each delivery: typecheck/focused automated checks, native Simulator evidence, physical iOS, physical Android, PostHog readback, Human QA. Missing categories stay “not run”; no merge/deploy authorization is implied by this spec.

Out of Scope

  • Implementing telemetry or installing SDKs in this research task; automatic implementation of all priority tiers.
  • Per-message/prompt/token/tool-call analytics, LLM analytics, session replay, touch autocapture, raw crash reports or full-screen recordings.
  • Website-to-phone attribution, linking Host and mobile identities, accounts, advertising identifiers or collecting private domain IDs.
  • Using analytics as message delivery, approval audit, pairing authority, authorization or durable business state.
  • Push delivery receipts / guaranteed app-close events, crash-free rate, correlated model reply latency or native FPS without additional verified instrumentation.
  • Changing Host default-on telemetry policy, existing Host metrics, pairing permissions, transport protocol or other sessions' device/QA stacks.
  • Deployment, store submission, changing live PostHog settings or creating a PR in this task.

Further Notes

Evidence and sources

Research limitations

Static inspection and live PostHog read-only inventory completed. No app build, native run, push delivery test, telemetry implementation, automated test execution, runtime collection verification or production setting change was performed. Existing checkout changes were preserved; the research used an independent detached worktree at the revision above. The ready-for-agent label applies to this specification's delivery definition, not to proof that any instrumentation has shipped.

Metadata

Metadata

Assignees

No one assigned

    Labels

    area:frontendClient-side implementationfeature:telemetryContent-free event measurement and verified ingestionready-for-agentFully specified, ready for an AFK agentscope:specNormative specification for follow-on slices

    Type

    No type

    Projects

    No projects

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions