Skip to content

chore(perf): Flashlight tester-session listener POC - #38554

Draft
tommasini wants to merge 14 commits into
mainfrom
poc/flashlight-tester-sessions
Draft

tommasini wants to merge 14 commits into
mainfrom
poc/flashlight-tester-sessions

Conversation

@tommasini

Copy link
Copy Markdown
Contributor

Description

POC. Adds scripts/perf-sessions/, a standalone tool (with its own package.json, so the app's dependencies don't change) that measures Android performance with Flashlight while product managers test a main-rc build by hand. It then merges recordings from many testers so we can spot low-performance patterns they share.

Why: PM test sessions exercise the app on real, varied devices, but today nothing is measured. Flashlight gives CPU per thread (JS / UI), FPS and RAM over adb on release builds without changing the app.

How it works

  • agent.mjs is the listener. It runs on the tester's laptop with the phone attached over adb and records every 500 ms. Testers type a flow name (swap, send…) to label what they're testing, press Enter to flag jank (or ! note), and type q to stop. Output is a valid Flashlight result (opens in npx @perf-profiler/web-reporter report <file>), plus tester, device, app version, flow labels and jank flags. Measures are streamed to .ndjson, so a crash doesn't lose data.
  • aggregate.mjs merges every tester's files into report.md and report.json. Flows are ranked worst-first. A shared hotspot is a flow that was slow (low FPS or a locked JS thread) for at least half of the testers who used it; problems seen on only one device go to a per-device table instead. report.json is structured for a bot or LLM to triage.
  • npm run demo runs the aggregator on synthetic data for 4 testers, so it can be tried without devices.

Notes / limits

  • Flashlight is host-side: each tester needs a laptop with adb (USB or wireless), or several phones can share one test laptop.
  • Flow labels are manual: release builds strip console.* (babel.config.js), so the agent can't see the current screen. A possible follow-up is a small native route log in RC builds that the agent tails from logcat.
  • The published @perf-profiler/profiler (0.10.11) has no refresh-rate detection, so the agent reads it from dumpsys display. FPS is reported as a % of the refresh rate, so 120 Hz devices are compared fairly.
  • Flashlight registers a SIGINT handler that exits immediately; the agent replaces it so Ctrl+C still saves the recording.

Possible next steps: automatic screen tagging → automatic upload and post-session aggregation → LLM triage of report.json plus Release-profiler CPU profiles for the hotspot flows.

Changelog

CHANGELOG entry: null

Related issues

Refs: N/A (POC, no ticket yet)

Manual testing steps

Feature: Flashlight tester-session listener

  Scenario: tester records a session
    Given an Android device with io.metamask (main-rc) installed is attached over adb
    And `npm install` has been run in scripts/perf-sessions

    When the tester runs `node agent.mjs --tester ana --session bugbash`
    And opens the app, types flow names, presses Enter on jank and finally types `q`
    Then perf-sessions-output/bugbash/ana-<time>.json is written with samples, flows and jank flags
    And `npx @perf-profiler/web-reporter report <that file>` opens Flashlight's report

  Scenario: merge recordings from several testers
    Given several recordings in one folder (or `npm run demo` for synthetic ones)

    When the user runs `node aggregate.mjs <folder>`
    Then report.md lists shared hotspots, flows worst-first, devices and jank flags
    And report.json contains the same data

Tested on an Android 13 emulator (sdk_gphone64_arm64, io.metamask 7.27.0 debug build): 75 samples, flow labels and jank flags recorded, file opened in Flashlight's web reporter, and the aggregator ran on it and on the synthetic data. Not yet tested on a physical device or an actual main-rc APK.

Screenshots/Recordings

Before

N/A (new tool)

After

Pre-merge author checklist

Performance checks (if applicable)

  • I've tested on Android
    • Ideally on a mid-range device; emulator is acceptable
  • I've tested with a power user scenario
    • Use these power-user SRPs to import wallets with many accounts and tokens
  • I've instrumented key operations with Sentry traces for production performance metrics

For performance guidelines and tooling, see the Performance Guide.

Pre-merge reviewer checklist

  • I've manually tested the PR (e.g. pull and build branch, run the app, test code being changed).
  • I confirm that this PR addresses all acceptance criteria described in the ticket it closes and includes the necessary testing evidence such as recordings and or screenshots.

🤖 Generated with Claude Code

Adds scripts/perf-sessions, a standalone tool that records Android
performance (CPU per thread, FPS, RAM via Flashlight over adb) while
product managers test an RC build by hand, and merges recordings from
many testers into a report of shared low-performance flows.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tommasini tommasini added the no-changelog no-changelog Indicates no external facing user changes, therefore no changelog documentation needed label Oct 30, 2026
@github-actions

Copy link
Copy Markdown
Contributor

CLA Signature Action: All authors have signed the CLA. You may need to manually re-run the blocking PR check if it doesn't pass in a few minutes.

@metamask-ci metamask-ci Bot added the team-mobile-platform Mobile Platform team label Oct 30, 2026
@metamask-ci

metamask-ci Bot commented Oct 30, 2026

Copy link
Copy Markdown
Contributor

PR template — items to address before "Ready for review"

Warnings — informational, address before merging:

See docs/readme/ready-for-review.md for the full Definition of Ready for Review.

@socket-security

socket-security Bot commented Oct 30, 2026 •

Copy link
Copy Markdown

No dependency changes detected. Learn more about Socket for GitHub.

👍 No dependency changes detected in pull request

@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Smart E2E Test Selection

Selected E2E tags: ALL

AI Confidence: 100

E2E reasoning

Expand to read

The hard rule seed mandates ALL tags due to changes in .github/workflows/build.yml. Beyond the hard rule, the analysis confirms this is appropriate:

  1. build.yml / nightly-build.yml changes: These CI workflow files add perf session build triggers and configuration. Changes to E2E-relevant workflow files warrant running all E2E tags per the hard rule.

  2. app/store/index.ts: Core Redux store setup is modified to conditionally add perfSessionReduxMiddleware. While gated behind isPerfSessionAvailable() (which is false in E2E builds), this is a foundational file that all E2E tests depend on.

  3. app/components/Nav/NavigationProvider/NavigationProvider.tsx: Core navigation provider is modified to call setPerfSessionScreen() on navigation state changes. This is a critical path that all E2E tests traverse. The calls are no-ops in non-perf builds, but the code path is exercised.

  4. app/util/trace.ts: The trace utility (used throughout the app for performance tracking) is modified to wrap callbacks with perf session recording. This is a widely-used utility.

  5. app/util/sentry/utils.ts: Sentry setup is modified to conditionally set profilesSampleRate to 0 in perf builds. In regular E2E builds this remains 1.0, but the change touches error monitoring setup.

  6. builds.yml: Large addition of perf session build configuration affecting build variants.

  7. Android native modules: New PerfSession native module added to MainApplication.kt, gated behind BuildConfig.PERF_SESSION_URL.

The changes are primarily additive and gated behind perf-build-only flags, but they touch core infrastructure (navigation, Redux store, trace utilities) that all E2E tests depend on. The workflow changes to build.yml are the primary trigger for the ALL tag selection per the hard rule, and the core infrastructure changes reinforce this conservative approach.

View run

Replaces the USB/adb-driven tester flow with an always-on sampler in a
dedicated main-rc-perf Android build. The native PerfSession module samples
FPS/jank/freezes, per-thread CPU and RAM every 500ms, tags samples with the
focused screen from NavigationProvider, persists batches to disk and POSTs
them to MM_PERF_SESSION_URL. A local collector (npm run collector) receives
batches and serves a live dashboard plus markdown/JSON reports.

The sampler is compiled in but disabled unless MM_PERF_SESSION_URL is set,
which only happens for main-rc-perf.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions github-actions Bot added size-XL and removed size-L labels Nov 2, 2026
tommasini and others added 2 commits November 3, 2026 18:12
- PerfSession records only while the collector's GET /status says so for
  the build's env (main-exp), so turning the collector off stops every
  installed build. Nothing is sampled or queued while it is off.
- Batch v2 adds env and selfCpu; the sampler's own threads are excluded
  from per-thread CPU. Sample every 1s, 10 samples per batch.
- FPS is only reported while actively rendering (>= 25% of the refresh
  rate) so idle redraws no longer look like slow screens.
- Drop queued batches only on 400/413; keep 401/403/429/5xx for retry.
- Gradle fails the build if the sampler is configured for anything but
  dev/exp/rc, for a non-https URL or a malformed key. Startup failures
  are caught in MainApplication.
- builds.yml: *perf_session anchor merged into main-exp only; adding
  main-rc is one line. The URL and key are public by design. Removes
  main-rc-perf.
- The collector moves to a separate project; the lab agent stays.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…profiles

Every feature is switched per env by the collector's /status, so overhead
can be measured without a rebuild:
- Time: wall (t) and monotonic (mono, us) clocks on every record, clock
  pairs and seq per batch, versionCode, process start and firstFrame,
  for cross-referencing with Hermes/release-profiler and Perfetto traces.
- spans: trace()/endTrace() name, id and timing, recorded before the
  Sentry consent check; batched to native once a second.
- interactions: taps and scrolls named by the touched view's testID.
- framePhases: per-stage durations of janky frames, slowest frame and the
  display's actual refresh rate.
- redux / jsLag: action type counts and JS event-loop lag.
- uiStalls: main-thread watchdog with the stalled stack.
- profiles: Hermes sampling in 10s segments, uploaded only around
  problems, on unmetered networks, within an hourly budget; paused while
  the shake-to-profile ProfilerManager records.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@codecov-commenter

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.27451% with 21 lines in your changes missing coverage. Please review.
✅ Project coverage is 87.68%. Comparing base (71eb71a) to head (cb96b1f).
⚠️ Report is 202 commits behind head on main.

Files with missing lines Patch % Lines
app/core/Performance/perfSession.ts 86.20% 8 Missing and 12 partials ⚠️
.../components/UI/ProfilerManager/ProfilerManager.tsx 66.66% 1 Missing ⚠️
Additional details and impacted files
@@            Coverage Diff             @@
##             main   #38554      +/-   ##
==========================================
+ Coverage   87.53%   87.68%   +0.15%     
==========================================
  Files        7880     7992     +112     
  Lines      228739   232514    +3775     
  Branches    57925    58923     +998     
==========================================
+ Hits       200217   203877    +3660     
+ Misses      16293    16263      -30     
- Partials    12229    12374     +145     

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.
  • 📦 JS Bundle Analysis: Save yourself from yourself by tracking and limiting bundle sizes in JS merges.

tommasini and others added 4 commits November 4, 2026 08:50
Sentry's profiler disables the global Hermes sampler and dumps its buffer
at every transaction end, so perf-session profiles were empty whenever no
Sentry transaction was running. Builds with the perf session now set
Sentry's profilesSampleRate to 0.

Also: empty Hermes segments are dropped on device instead of using up the
hourly profile cap, and UI stalls no longer force an early batch flush
(up to 20 per batch, the contract limit).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Stalls on one screen usually share a stack (781 stalls, 17 distinct stacks
in a 22-minute session), and stacks were 65% of upload volume. Batches now
carry a `stacks` table and stalls point at it with `stackRef`. Per batch,
so a lost batch never makes another unreadable. Needs perf-collector with
the stackRef contract change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When a screen keeps drawing with nobody touching it, the JS profile shows
nothing: the work is on the RenderThread and GPU. The new `renderLoops`
feature walks the view tree twice, 150 ms apart, and reports the views
responsible (moving, playing, running drawable, or surface) with their
testID and layer type. Triggered after 3 s idle with sustained drawing,
at most once per 30 s per screen.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
A sample taken between the dump and disable() stayed in the buffer and
showed up in the next segment with an old timestamp.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
tommasini and others added 3 commits November 4, 2026 16:14
…p build

The sampler is now compiled in only when the build sets
MM_PERF_SESSION_ENABLED=true. nightly-build.yml sets it (via a new
workflow_call-only `perf_session` input on build.yml) for the scheduled
Android main-exp build on Fridays (UTC). Gradle refuses the flag on any
build other than nightly main-exp. The URL and key in builds.yml no longer
turn the sampler on by themselves.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The always-on sampler in Friday's nightly main-exp build replaces the
Flashlight-over-adb lab agent, so scripts/perf-sessions (agent, aggregate
script, fixtures and its own package.json/package-lock.json) is gone. The
documentation moves to docs/performance/perf-sessions.md and is linked from
the performance docs index.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…ntains

Every source on the phone, the three collector endpoints, and the
dashboard downloads, with a table of which data each download includes.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@tommasini

Copy link
Copy Markdown
Contributor Author

Data flow: what the phone sends and what you can download

Everything the phone sends, where it comes from, and where it can be downloaded. The phone only talks to three collector endpoints. Every request carries the env name and the build's key.

flowchart LR
  subgraph phone["Phone: MetaMask main-exp (Friday nightly)"]
    direction TB
    subgraph native["Native sampler: mm-perf-* threads"]
      proc["/proc/self/task, statm<br/>CPU per thread, RSS"]
      heap["Runtime<br/>Java heap"]
      fm["FrameMetrics + Display<br/>frames, janky, frozen,<br/>refresh rate, frame phases"]
      touch["Window.Callback<br/>tap, scrollStart, scrollEnd<br/>(testID / a11y label)"]
      wd["Main-looper watchdog<br/>UI stalls ≥ 100 ms + Java stack"]
      views["View tree, 2 snapshots<br/>render loops: animating views"]
      life["Activity lifecycle<br/>launch, firstFrame,<br/>foreground, background"]
      hermes["Hermes sampling profiler<br/>JS CPU profile, 10 s segments"]
    end
    subgraph js["JS: perfSession.ts"]
      nav["React Navigation<br/>screen name"]
      spans["trace() / endTrace()<br/>span name, duration, status"]
      redux["Redux middleware<br/>actions per second, top types"]
      lag["100 ms timer<br/>JS event-loop lag"]
    end
    queue[("On-disk queue<br/>≤ 500 batches, ≤ 20 MB profiles")]
  end

  subgraph collector["Perf collector (laptop + ngrok)"]
    status["GET /status<br/>record on/off, features"]
    ingest["POST /ingest<br/>batch v3: meta, clock, samples,<br/>events, spans, stalls + stacks,<br/>render loops"]
    profile["POST /profile<br/>gzip Hermes trace +<br/>X-Perf-Profile metadata"]
    store[("data/&lt;env&gt;/<br/>batches (ndjson), profiles (gz)<br/>+ source maps per versionCode")]
  end

  subgraph out["Downloads (dashboard, localhost only)"]
    ai["Download report for AI<br/>ai-report.md"]
    rep["report.json / report.md"]
    trace["Device trace.json<br/>(Perfetto / Chrome tracing)"]
    fl["Device flashlight.json<br/>(Flashlight web reporter)"]
    pv["Profile view<br/>(symbolicated functions, flame graph)"]
  end

  proc & heap & fm & touch & wd & views & life --> queue
  nav & spans & redux & lag -->|"bridge, once a second"| queue
  hermes -->|"only segments around a problem,<br/>≤ 12 per hour, unmetered networks only"| queue
  status -.->|"features to collect"| phone
  queue --> ingest
  queue --> profile
  ingest --> store
  profile --> store
  store --> ai & rep & trace & fl & pv
Loading
Data ai-report.md report.json / .md trace.json flashlight.json Profile view
CPU per thread, FPS, janky/frozen, RAM ±5 s around each problem per screen ✓ ✓
Frame phases, slowest frame ±5 s around each problem per screen ✓
Java heap ✓ ✓
JS lag ✓ ✓ ✓ ✓
Redux actions ✓ ✓
Screens, taps, scrolls, lifecycle events 10 s before each problem last tap before each problem ✓
Spans overlapping each problem per screen ✓
UI stalls and stacks ✓ per screen ✓
Render loops ✓ per screen ✓
Hermes profiles top functions, hottest path samples on the timeline ✓
Sampler overhead (selfCpu, features on) fixed note only ✓ (per feature set) ✓ ✓

What isn't in any download today: the raw Hermes profile (.cpuprofile, for Chrome DevTools or speedscope), and one file with all data for a time window. The AI report covers the worst 30 problems, and trace.json covers one device.

What's missing that would make problems easier to pin down

Ordered by how much each would turn an investigation ticket into a pointed issue.

Data the phone doesn't collect yet

  1. Network requests: host and route template (never query strings or addresses), status, duration, size. The homepage's time to content waits on the network, and today we can't say which request was slow.
  2. Build identity: the git commit and build number in batch and profile metadata. Source maps are stored per versionCode, so test builds that share one (all of ours today were 4532) overwrite each other's maps, and older profiles get symbolicated with the wrong one.
  3. Static span tags: an allow-list such as section_id. A "Homepage Section Time To Content" span stayed open for 11–14 minutes, and without the tag we can't tell which section.
  4. An explicit unlock event: today unlock is inferred from the first WalletView sample, up to 1 s late. An exact timestamp gives a clean "unlock → usable" metric.
  5. Device state: thermal status, battery saver and network type. These explain the run-to-run variance we hit when comparing builds.
  6. Hermes heap size and GC pauses: we have RSS and Java heap, but no JS heap trend. GC shows up in profiles only as [GC Young Gen] samples.
  7. Better render-loop detection: views that redraw every frame without moving, indeterminate spinners, and readable class names in release builds (R8 renames React Native's views, so one showed up as i). On WalletView the check fired but named no view.

Data collected but not downloadable

  1. The raw Hermes profile (.cpuprofile) for Chrome DevTools or speedscope.
  2. One export with everything for a time window, across devices. The AI report covers only the worst 30 problems, and trace.json covers one device.
  3. Small report gaps: the AI report uses a fixed overhead note instead of the measured per-feature overhead, and has no Java heap. trace.json has no Redux actions.

Pipeline

  1. Profile queue order: a phone idling on a stalling screen fills its profile queue, and the collector accepts about one profile a minute. New profiles wait behind old ones (it happened during today's measurements). Uploading newest first, or skipping a stack already captured recently, would fix it.

Items 2, 8 and 9 are the cheapest. Items 1 and 2 add the most.

🤖 Generated with Claude Code

tommasini and others added 2 commits November 5, 2026 10:12
Times every fetch / XHR from JS natively: an OkHttp EventListener installed
through NetworkingModule.setCustomClientBuilder, forwarding every event to the
base client's listener so Sentry's instrumentation keeps working. Per request:
host, path template (ids, keys, addresses -> :id, no query), method, JSON-RPC
method (copied from the first 2 KB of small JSON bodies as they are written,
so RN's upload progress events don't fire twice), status or error, protocol,
and queue (OkHttp's 5-per-host dispatcher), DNS, connect, TLS, first byte and
total. No headers or bodies are recorded.

Batches carry up to 200 requests (400 when the extra ones are slow or
failed) plus requestsDropped; requests never force a flush.

Docs: data-flow diagram and download table updated; every collected record
is now downloadable (collector: .cpuprofile, raw profile, export.tar.gz).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
…lt off)

Lets a branch be tested with the sampler before Friday: Build → main-exp,
android, perf_session checked. The guard is now main-exp (any attribution)
instead of nightly main-exp; the scheduled nightly still sets it Fridays only.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
weitingsun pushed a commit to Poovarasan-Sandhanam/metamask-mobile that referenced this pull request Nov 6, 2026
…ask#38837)

## **Description**

<!-- mms-check: type=text required=true -->

**Problem.** Every unlock blocks the Android main thread for about 400
ms, even for users who never use Lighter. `LighterSignerWebView` mounts
as soon as the wallet unlocks and passes `wasm-wrapper.standalone.html`
(10.3 MB, the Go/WASM signer as base64) as `source.html`.

**Evidence.** An always-on perf session ran on a Galaxy Z Fold4 with the
exp build 8.19.0 (4532). About 2.5 s after `WalletView` first appeared,
it recorded two UI-thread stalls, both inside
`RNCWebViewManager.onAfterUpdateTransaction` ←
`ViewManager.createViewInstance` (Fabric `preallocateView` /
`createView`):
- 145 ms in `ReadableNativeMap.importValues`: copying the 10 MB prop
across JNI.
- 259 ms in `WebView.loadDataWithBaseURL`: loading the inline document
on the main thread.

The only other inline-HTML WebView in `Root` is `SnapsExecutionWebView`,
and it mounts before Engine init, not at unlock.

**Fix.** Mount the signer page only when a Lighter call needs it:
- `lighterSignerBridge` now records a request (`requestLighterSigner`)
when client setup starts or a WASM call is made. `LighterSignerWebView`
subscribes to it with `useSyncExternalStore`, and mounts only when the
wallet is unlocked **and** a request exists.
- Callers already wait behind the bridge's readiness promise (90 s
deadline), so the first call queues until the page reports `ready`.
Client setup requests the page before reading the keychain, so both
happen in parallel.
- Key discovery (`getStoredKeyIndices`, `getRecoverableKeyIndices`)
doesn't need the page, so it doesn't trigger a load.
- Locking still unmounts the page, and now also forgets the request. The
next unlock waits for the next call.

The security properties are unchanged: same `https://localhost` origin,
navigation filter, file-access flags, message validation and lock
lifecycle. Only the moment the page mounts changes.

**Risk.** The first Lighter call in a session waits for the page to load
(hundreds of ms to a few seconds on low-end devices), which used to
happen at unlock. Users who never use Lighter never pay it.

**Follow-up (not in this PR).** The 10 MB document is still inlined into
the JS bundle and copied over JNI when it does mount. Shipping it as a
native asset and loading it by URL would remove both the copy and the
bundle weight. That needs care with the origin and
`onShouldStartLoadWithRequest`, so it's left for a separate change.

**Verification.** Measured with the perf session on a Galaxy Z Fold4
over 4–5 cold unlocks per build. Main-thread stalls with the Lighter
WebView on the stack went from a median of 323 ms per unlock to 0 ms,
both [with
MetaMask#38839](MetaMask#38837 (comment))
and [with only this PR
applied](MetaMask#38837 (comment)).
The test wallet uses Hyperliquid, so for Lighter users the cost moves to
their first trading action rather than disappearing.

## **Changelog**

<!-- mms-check: type=changelog required=true blocking=true -->

CHANGELOG entry: Improved unlock responsiveness on Android by loading
the Lighter signer only when it is needed

## **Related issues**

<!-- mms-check: type=issue-link required=true -->

Refs: MetaMask#38554 (perf session POC that found this)

## **Manual testing steps**

<!-- mms-check: type=manual-testing required=true -->

```gherkin
Feature: Lighter signer loads on demand

  Scenario: unlock without using Lighter
    Given a build with MM_PERPS_LIGHTER_PROVIDER_ENABLED=true
    When user unlocks the wallet and stays on the wallet home
    Then no hidden Lighter WebView is created (no lighter-signer-webview in the view tree)
    And no loadDataWithBaseURL stall appears at unlock

  Scenario: first Lighter action
    Given the wallet is unlocked and Lighter has not been used yet
    When user starts a Lighter flow that needs the signer (client setup / placing an order)
    Then the signer page loads and the action completes

  Scenario: lock and unlock
    Given the signer page is loaded
    When user locks and unlocks the wallet
    Then the page is gone after lock and only loads again on the next Lighter action
```

## **Screenshots/Recordings**

<!-- mms-check: type=screenshot required=true -->

### **Before**

N/A (no UI change). Perf-session evidence above; before/after numbers
are in the comments linked under Verification.

### **After**

N/A (no UI change).

## **Pre-merge author checklist**

<!-- mms-check: type=checklist required=true -->

- [x] I've followed [MetaMask Contributor
Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Mobile
Coding
Standards](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/CODING_GUIDELINES.md).
- [x] I've completed the PR template to the best of my ability
- [x] I've included tests if applicable
- [x] I've documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [x] I've applied the right labels on the PR (see [labeling
guidelines](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/LABELING_GUIDELINES.md)).
Not required for external contributors.

#### Performance checks (if applicable)

- [x] I've tested on Android
  - Ideally on a mid-range device; emulator is acceptable
- [ ] I've tested with a power user scenario
- Use these [power-user
SRPs](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/edit-v2/401401446401?draftShareId=9d77e1e1-4bdc-4be1-9ebb-ccd916988d93)
to import wallets with many accounts and tokens
- [ ] I've instrumented key operations with Sentry traces for production
performance metrics
- See [`trace()`](/app/util/trace.ts) for usage and
[`addToken`](/app/components/Views/AddAsset/components/AddCustomToken/AddCustomToken.tsx#L274)
for an example

For performance guidelines and tooling, see the [Performance
Guide](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/400085549067/Performance+Guide+for+Engineers).

## **Pre-merge reviewer checklist**

- [ ] I've manually tested the PR (e.g. pull and build branch, run the
app, test code being changed).
- [ ] I confirm that this PR addresses all acceptance criteria described
in the ticket it closes and includes the necessary testing evidence such
as recordings and or screenshots.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Changes wallet-lock coordination and when the key-holding WebView
mounts, but signing semantics and isolation are unchanged; the main
product risk is first-use latency for Lighter users.
> 
> **Overview**
> **Defers loading the ~10 MB Lighter WASM WebView** so it no longer
mounts on every wallet unlock (which blocked the Android main thread for
hundreds of ms). The hidden signer page now mounts only when the wallet
is unlocked **and** a bridge call actually needs it.
> 
> The bridge gains a small **demand signal** (`requestLighterSigner` /
`clearLighterSignerRequest` + `useSyncExternalStore` in
`LighterSignerWebView`). **`createClient`** and **`execute`** set the
request before keychain read / WASM work; **key discovery** does not.
Pending calls still wait on the existing readiness promise, so the first
Lighter action pays the load cost instead of unlock.
> 
> **Lock handling** moves partly to the always-mounted host: on
`KeyringController:lock` it clears the demand flag and marks the bridge
unavailable even when no WebView is mounted; on unlock it revives the
bridge without reloading until the next request. Tests add a **lazy
mounting** suite and adjust lock/unlock expectations (e.g. batched
lock+unlock no longer auto-remounts the page).
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
91feb61. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
Resolve app/util/trace.ts: keep perf session span recording alongside main's timeline entries.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@sonarqubecloud

sonarqubecloud Bot commented Nov 9, 2026

Copy link
Copy Markdown

@github-actions

github-actions Bot commented Nov 9, 2026

Copy link
Copy Markdown
Contributor

❌ E2E Fixture Validation — Failed
The fixture validation job failed. Review the logs

weitingsun pushed a commit to Poovarasan-Sandhanam/metamask-mobile that referenced this pull request Nov 10, 2026
…sk#38839)

<!--
Please submit this PR as a draft initially.
-->

## **Description**

<!-- mms-check: type=text required=true -->

**Problem.** WalletConnect signs a relay auth JWT every time its relayer
connects. That happens in `core.crypto.signJWT`, called from
`relayer.createProvider` at unlock, on foreground and on network
changes. It also derives the client's public key in `getClientId`. Both
go through `@walletconnect/relay-auth`, which bundles a pure-JS ed25519
(`@noble/curves`). On Hermes the first call in a process costs about
half a second of JS thread: it builds precompute tables, then runs two
scalar multiplications.

**Who pays it: every wallet with a WalletConnect pairing or session.**
`Relayer.init()` in `@walletconnect/core` 2.23.4 ends with
`this.transportOpen()` → `createProvider()` → `core.crypto.signJWT()`.
`transportOpen()` returns early when the subscriber has no topics
("Starting WS connection skipped because the client has no topics to
work with."), so the relay connect and its JWT only happen for wallets
that have one. `WC2Manager.init` runs at every unlock
(`initializeSDKServices`, `app/store/sagas/index.ts:83`), so those
wallets pay the ~500 ms on the JS thread at every unlock, and again when
the network comes back (`subscribeToNetworkChange` → `transportOpen`). A
wallet that has never connected to a dApp skips the relay connect at
unlock. Whether it still derives the client key at unlock (`getClientId`
→ `generateKeyPair`) is not established: the app builds the core with
`new Core()`, and `Core.init()` is what calls `getClientId`.

**Evidence.** From the always-on perf session (MetaMask#38554) on a Galaxy Z
Fold4 at 120 Hz, exp build 8.19.0 (4532), right after unlock: JS lag was
928 ms with the JS thread at 85.7%. The Hermes profile covering that
moment (symbolicated with the build's source map) has this hottest path:

```
@walletconnect/core → relay-auth generateKeyPair/signJWT → multiply → wNAF → wNAFCached → getPrecomputes
506 ms total (relay-auth `i`: 387 ms self)
```

**Fix.** Metro resolves `@walletconnect/relay-auth` to
`app/shims/walletconnect-relay-auth.ts`. That shim re-exports the
package unchanged and replaces only two functions, `generateKeyPair` and
`signJWT`, with native libraries the app already ships:
- **Public key:** `getPublicKeyEd25519(seed)` from
`@metamask/native-utils`, the same synchronous Nitro library
`shimPerf.js` already uses for secp256k1 (see
`docs/performance/native-crypto.md`).
- **Signature:** `new Ed('ed25519').signSync(data, seed)` from
`react-native-quick-crypto` (OpenSSL). `@metamask/native-utils` 0.8.0
has no ed25519 signing. If it gains one, this can move there too.
- **Fallback:** each native call falls back to the original JS on its
own for the rest of the session if it throws or returns a malformed
result. A failure in one library doesn't turn off the other. The first
fallback of each call is reported once through `Logger.error` (Sentry,
tag `operation:relay_auth_native_ed25519`) with the call name only, so a
broken native library shows up instead of silently costing the ~500 ms
again. A secret key of the wrong length goes to JS without turning
native signing off.

The JWT header, payload and encoding still come from relay-auth's own
helpers (`encodeIss`, `encodeData`, `encodeJWT`). ed25519 is
deterministic, so keys and JWTs are byte-identical to the JS
implementation.

**Why a Metro shim and not a patch, or a `shimPerf.js`-style mutation.**
relay-auth pins `@noble/curves` 1.8.0 exactly, while the app uses 1.9.7.
So mutating the app's `@noble/curves` the way `shimPerf.js` does would
never reach relay-auth's copy: that's the single-copy invariant in
`docs/performance/native-crypto.md`. relay-auth's dist is also a
minified bundle that inlines noble, so patching it would be fragile. The
redirect follows the existing `react-native-safe-area-context` shim
pattern in `metro.config.js`. The shim imports the copy of relay-auth
that core resolves, so it follows core's version. Jest doesn't remap the
package, so unit tests keep using the real JS implementation.

**Risks.**
- **Crypto correctness.** Equivalence tests compare the shim with the JS
implementation for fixed seeds and inputs: public key, secret key, the
full JWT string, and `verifyJWT` on the shim's output. They back
quick-crypto with Node's OpenSSL ed25519.
- **Native availability.** If a native call throws or returns a key or
signature of the wrong length, the shim switches the native path off for
the session and uses the JS implementation, so the behaviour is the same
as today, and reports it once to Sentry. `EdKeyPair` and
`KeyObjectHandle` are registered on both iOS and Android (OpenSSL 3.6.2
on both).
- **Key material.** The seed is WalletConnect's client identity key. It
is passed to the native module in memory only, exactly as it is passed
to the JS curve today. It is never logged or stored.

**Follow-up, not in this PR.** Defer `WC2Manager.init`
(`app/store/sagas/index.ts:83`, `initializeSDKServices`) until after the
homepage's first content. The relayer connect would then leave the
unlock path entirely.

## **Changelog**

<!-- mms-check: type=changelog required=true blocking=true -->

CHANGELOG entry: Improved app responsiveness right after unlock by
signing WalletConnect relay authentication natively

## **Related issues**

<!-- mms-check: type=issue-link required=true -->

Refs: MetaMask#38554 (perf session that found it)

## **Manual testing steps**

<!-- mms-check: type=manual-testing required=true -->

```gherkin
Feature: WalletConnect relay auth with native ed25519

  Scenario: user unlocks with existing WalletConnect sessions
    Given the wallet has an active WalletConnect v2 session with a dapp
    When user kills the app, reopens it and unlocks
    Then the relayer connects (the dapp session stays active and requests arrive)
    And no "falling back" behaviour is needed (signing requests from the dapp work)

  Scenario: user pairs a new dapp
    Given the wallet is unlocked
    When user scans a WalletConnect v2 pairing QR code from a dapp
    Then the pairing and session proposal complete as before
```

**Verification:** before/after over cold unlocks on a device is in the
PR comments: relay-auth JS time went from a median of 505 ms to 0 ms. A
run with only this change applied is in progress.

Manual test evidence on an iOS simulator and a Galaxy Z Fold4 (pairing,
signing requests, kill + reopen + unlock with a saved session, on-device
equivalence and cold timings: 559 ms JS vs 8 ms native on the Fold4):
MetaMask#38839 (comment)

## **Screenshots/Recordings**

<!-- mms-check: type=screenshot required=true -->

N/A: no UI change. The before/after Hermes profiles will be attached in
the verification comment.

### **Before**

N/A

### **After**

N/A

## **Pre-merge author checklist**

<!-- mms-check: type=checklist required=true -->

- [x] I've followed [MetaMask Contributor
Docs](https://github.com/MetaMask/contributor-docs) and [MetaMask Mobile
Coding
Standards](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/CODING_GUIDELINES.md).
- [x] I've completed the PR template to the best of my ability
- [x] I've included tests if applicable
- [x] I've documented my code using [JSDoc](https://jsdoc.app/) format
if applicable
- [ ] I've applied the right labels on the PR (see [labeling
guidelines](https://github.com/MetaMask/metamask-mobile/blob/main/.github/guidelines/LABELING_GUIDELINES.md)).
Not required for external contributors.

#### Performance checks (if applicable)

- [ ] I've tested on Android (pending: perf-session before/after on a
Galaxy Z Fold4)
  - Ideally on a mid-range device; emulator is acceptable
- [ ] I've tested with a power user scenario
- Use these [power-user
SRPs](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/edit-v2/401401446401?draftShareId=9d77e1e1-4bdc-4be1-9ebb-ccd916988d93)
to import wallets with many accounts and tokens
- [ ] I've instrumented key operations with Sentry traces for production
performance metrics
- See [`trace()`](/app/util/trace.ts) for usage and
[`addToken`](/app/components/Views/AddAsset/components/AddCustomToken/AddCustomToken.tsx#L274)
for an example

For performance guidelines and tooling, see the [Performance
Guide](https://consensyssoftware.atlassian.net/wiki/spaces/TL1/pages/400085549067/Performance+Guide+for+Engineers).

## **Pre-merge reviewer checklist**

- [ ] I've manually tested the PR (e.g. pull and build branch, run the
app, test code being changed).
- [ ] I confirm that this PR addresses all acceptance criteria described
in the ticket it closes and includes the necessary testing evidence such
as recordings and or screenshots.

🤖 Generated with [Claude Code](https://claude.com/claude-code)




<!-- CURSOR_SUMMARY -->
---

> [!NOTE]
> **Medium Risk**
> Touches cryptographic signing for WalletConnect relayers; correctness
and native dependency availability need vigilance though JS fallbacks
exist.
> 
> **Overview**
> Adds a Metro redirect so WalletConnect loads
`app/shims/walletconnect-relay-auth.ts`, which wraps
`@walletconnect/relay-auth` to derive keys and sign relay-auth JWTs with
`@metamask/native-utils` and `react-native-quick-crypto`, falling back
to the bundled JS implementation per native call on error while
re-exporting the rest of relay-auth.
> 
> The companion Jest suite asserts byte-for-byte parity with the JS
path, exercises every fallback scenario, and guards that only one
lockfile copy exists; `.depcheckrc.yml` now whitelists
`@walletconnect/relay-auth` because the shim imports that transitive
package directly.
> 
> <sup>Reviewed by [Cursor Bugbot](https://cursor.com/bugbot) for commit
9375cbd. Bugbot is set up for automated
code reviews on this repo. Configure
[here](https://www.cursor.com/dashboard/bugbot).</sup>
<!-- /CURSOR_SUMMARY -->

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

no-changelog no-changelog Indicates no external facing user changes, therefore no changelog documentation needed size-XL team-mobile-platform Mobile Platform team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants