Skip to content

perf(perps): mount the Lighter signer WebView only when needed - #38837

Merged
tommasini merged 7 commits into
mainfrom
perf/lighter-signer-webview-unlock
Nov 6, 2026
Merged

tommasini merged 7 commits into
mainfrom
perf/lighter-signer-webview-unlock

Conversation

@tommasini

@tommasini tommasini commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Description

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 #38839 and with only this PR applied. The test wallet uses Hyperliquid, so for Lighter users the cost moves to their first trading action rather than disappearing.

Changelog

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

Related issues

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

Manual testing steps

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

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

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


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).

Reviewed by Cursor Bugbot for commit 91feb61. Bugbot is set up for automated code reviews on this repo. Configure here.

The signer page is a 10.3 MB inline HTML document. Mounting it on every
unlock blocked the Android main thread for about 400 ms (JNI prop copy plus
WebView.loadDataWithBaseURL), even for users who never use Lighter.

The bridge now asks the host to mount the page on the first call that needs
it (client setup or a WASM call). Calls already wait behind the readiness
promise, so they queue until the page loads. Key discovery stays page-free.
Locking unmounts the page and forgets the request, as before.

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

github-actions Bot commented Nov 4, 2026

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.

@github-actions github-actions Bot added the size-M label Nov 4, 2026
@metamask-ci metamask-ci Bot added the team-mobile-platform Mobile Platform team label Nov 4, 2026
@metamask-ci

metamask-ci Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

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

Warnings — informational, address before merging:

  • Pre-merge author checklist has unchecked items (e.g. "I've tested with a power user scenario"). Every box must be consciously checked — see docs/readme/ready-for-review.md.

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

@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Smart E2E Test Selection

Selected E2E tags

SmokePerps
SmokeWalletPlatform
SmokeConfirmations

AI Confidence: 85

E2E reasoning

Expand to read

The PR modifies the Lighter signer infrastructure for Perps trading:

  1. lighterSignerBridge.ts: Adds lazy-loading demand tracking (requestLighterSigner, clearLighterSignerRequest, isLighterSignerRequested, subscribeLighterSignerRequest). The 10MB signer WebView page is now only loaded on-demand when a signing call is actually needed, rather than eagerly on every wallet unlock.

  2. LighterSignerWebView.tsx: Updated to use useSyncExternalStore for demand subscription. The WebView now only mounts when isUnlocked && isRequested (previously just isUnlocked). Added Engine.controllerMessenger subscriptions for lock/unlock events to clear demand state.

  3. LighterSignerWebView.test.tsx: Extensive new unit tests for lazy mounting behavior, lock/unlock cycles, demand clearing, and bridge lifecycle.

Risk factors:

  • The LighterSignerWebView is mounted in Root/index.tsx (app startup path), so any regression could affect all users
  • Open PR review comments flag potential bugs in lock/unlock handling (demand not cleared on lock event, bridge revival on repeated unlocks)
  • Behavioral change to when the signer page loads could break the Perps Add Funds flow if the demand signal isn't triggered correctly
  • The change touches Engine.controllerMessenger subscriptions (lock/unlock events), which is a shared infrastructure concern

Tag selection rationale:

  • SmokePerps: Directly tests the Perps Add Funds flow which relies on the Lighter signer
  • SmokeWalletPlatform: Perps is embedded in the Trending tab; also the Root component hosts this WebView
  • SmokeConfirmations: Per SmokePerps tag description, Add Funds deposits are on-chain transactions requiring confirmations

View run

@tommasini

Copy link
Copy Markdown
Contributor Author

Before/after on a device

Measured with the internal perf session (in-app sampler, UI-thread stall watchdog, Hermes sampling profiles). Device: Galaxy Z Fold4 (SM-F936B, 120 Hz), main-exp 8.19.0 (4532), same wallet. Each run was a cold start, then a biometric unlock, then 20 s on WalletView.

Main-thread stalls with the Lighter WebView on the stack (loadDataWithBaseURL / RNCWebViewManager / ReadableNativeMap.importValues) Before After
Per unlock 221, 379, 411, 323, 296 ms 0, 0, 0, 0 ms
Median 323 ms 0 ms

No WebView mount appears in any after-fix stall. The test wallet uses Hyperliquid as its Perps provider; for wallets with Lighter as the active provider, the page now loads on the first Lighter call instead of at unlock.

Caveat: UI-thread busy time over the 10 s after unlock is noisy run to run (before median 1.49 s, after 1.48 s). The remaining UI stalls on WalletView are a separate RenderThread-bound redraw (HardwareRenderer.nSyncAndDrawFrame) that this PR doesn't touch.

🤖 Generated with Claude Code

@tommasini

Copy link
Copy Markdown
Contributor Author

With only this PR applied

Same device and method as above: Galaxy Z Fold4, main-exp, cold start, then biometric unlock, then 20 s on WalletView. This time the build is the perf-session branch plus only this PR's commit (poc/perf-verify-lighter, run 41836353611, built normally with the TapAndPay SDK).

Baseline (5 unlocks) This PR only (5 unlocks)
Main-thread stalls with the Lighter WebView on the stack 221, 379, 411, 323, 296 ms (median 323 ms) 0, 0, 0, 0, 0 ms (median 0 ms)
JS time in @walletconnect/relay-auth (control, not touched by this PR) median 505 ms 472, 548, 585, 639 ms (median 548 ms)

The control shows this build still has the WalletConnect cost that #38839 addresses, so the WebView result comes from this PR alone.

🤖 Generated with Claude Code

@tommasini
tommasini marked this pull request as ready for review November 4, 2026 19:13
@tommasini
tommasini requested a review from a team as a code owner November 4, 2026 19:13

@cursor cursor Bot left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Stale Bugbot comment from a previous run.

The page that sees a lock marks the bridge unavailable, and mounting used to
revive it on the next unlock. With lazy mounting nothing mounts at unlock, so
the next call failed before it could request a page and Lighter stayed broken
until restart. The host now revives the bridge when the wallet unlocks.

Also wraps bridge calls in the tests in act() to silence update warnings.

Co-authored-by: Cursor <cursoragent@cursor.com>

@abretonc7s abretonc7s left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Static review of PR 38837

COMMIT: 82f6226
BASE: 22744b7
VERDICT: REQUEST_CHANGES
RULE REVISION: cc1fe2d29937273f1ba3c142d5ef7b1ba9762120

Summary

The demand gate avoids the native page on an ordinary unlock. Request changes for two lock lifecycle defects and missing recorded validation. All source review was read-only. This is review round 1; there are no prior findings to disposition.

Request and evidence boundary

MetaMask/metamask-mobile, mobile client. Review the frozen contribution that defers the Lighter signer until demanded. No separate acceptance criteria were supplied. The frozen description requires no page at ordinary unlock, first-call readiness, key discovery without mounting, and request removal at lock.

Inspected the exact frozen diff and source at the head above. The checkout was clean. Read inputs/instruction-manifest.json, whose additional frozen instruction list is empty, review-support.json, review-subject.json, handoff.json and worker-terminal-contract.json. Applied the frozen shared review skill and read the frozen recipe-harness skill. Its execution instructions are superseded by TASK.md's static-only boundary.

Reference revisions inspected through git show:

  • Core 9c5ffbb681459fd796e1916da97e7d00da6ab3ca, packages/perps-controller/src/types/lighter-types.ts:225-294 and providers/LighterProvider.ts:2150-2255.
  • Extension 95553d8431511c2686c9c7ae3b4fa759a0cdaaf2, app/scripts/messenger-client-init/perps-controller-init.ts:98-129. This client config supplies Hyperliquid credentials and no Lighter signer.
  • Mobile is the frozen reviewed head. Root/index.tsx:120-127 and adapters/mobileInfrastructure.ts:253-269 wire the host and injected bridge under the same enablement rule.

No CI results, deterministic-check receipts, logs or raw performance captures were supplied in task inputs or artifacts. No tests, builds, recipes, installs, probes, network fetches or runtime validation were executed. Linked PR comments are author claims, not inspected performance evidence.

Diff scope

File Ticket AC or required test Scope justification or finding
app/components/UI/Perps/Lighter/LighterSignerWebView.tsx Demand-only mounting and lock/unlock lifecycle Directly implements the frozen description's host timing change.
app/components/UI/Perps/Lighter/lighterSignerBridge.ts Request from client setup and WASM execution, leave discovery lazy Directly implements the frozen description's bridge demand mechanism.
app/components/UI/Perps/Lighter/LighterSignerWebView.test.tsx Required regression coverage of lazy mounting Adds host/bridge tests and adapts existing mounted-page setup.

PASS. All three files serve the supplied description. No CI, configuration, dependencies, lockfiles, build tooling or repository-wide formatting changes.

Findings

  1. Major, LighterSignerWebView.tsx:509. Keep lock retirement active while the signer page is absent. getStoredKeyIndices/getRecoverableKeyIndices intentionally do not request the page, but the KeyringController:lock subscription and setLighterBridgeUnavailable call remain inside UnlockedLighterSignerWebView. Hold a native keychain read during discovery, then lock: the outer component only clears demand, so the bridge generation is unchanged and the pending request waits for the read or its 90-second timeout. If the same wallet unlocks before the read resolves, the old operation can complete in the new session. Move lock retirement to an always-mounted owner and add a lazy-discovery regression asserting prompt rejection on lock and rejection of late completion.

    Evidence: bridge :406-452 and :455-497 execute discovery under withOwnership without requesting a page. Its cancellation listener at :169-174 observes only bridge resets. Host :267-313 owns the lock subscription inside the gated child. The outer host :498-508 clears demand without retiring work. First execution before the child's lock effect registers has the same missing-owner gap.

  2. Major, LighterSignerWebView.tsx:506. Clear signer demand on the keyring lock event, independently of Redux rendering. This effect only clears it when selectIsUnlocked commits false. With lock and unlock in one render batch, demand stays true and the existing child's onUnlock recreates the 10 MB page before any new Lighter call. The retained test at LighterSignerWebView.test.tsx:356-374 explicitly expects that eager second mount. Clear the request at the event boundary and update the batched-transition test to assert that no replacement page appears until a fresh signer call.

    Evidence: host :284-294 recreates the native page on unlock; :498-508 cannot observe a locked state omitted by batching. The existing test supplies the batched transition explicitly.

  3. Minor, body-only evidence gap. Supply head-bound CI results and logs for the signer host and bridge tests and required code checks, plus recorded runtime evidence for successful first Lighter setup/action and lock/unlock demand reset. No CI receipts or runtime captures were supplied. The PR's Hyperliquid-wallet performance narrative cannot establish successful Lighter signing, so these claims remain unverified.

BLOCKERS: Findings 1 and 2. These violate the shared cleanup-owner, derived-state lifecycle and embedded-signer retirement rules, which require REQUEST_CHANGES. Finding 3 is an author evidence request under TASK.md. None of these findings claims runtime execution.

Shared criteria ledger

Paths below are relative to app/components/UI/Perps unless otherwise stated. PASS means source inspection only.

Family / individual rule Outcome Evidence or exclusion
Base / normal and empty demand PASS Lighter/lighterSignerBridge.ts:75-115,274,360 starts false, sets idempotently and notifies subscribers; Lighter/LighterSignerWebView.tsx:493-509 requires unlock and demand.
Base / first execution and deadline PASS Bridge :159-181 installs reset ownership before operation; :267-298 shares readiness and execution deadline; :356-400 shares key retrieval deadline. Host :334-380 connects after ready.
Base / cleanup, boundary and late activation FINDING Findings 1 and 2. Child-only lock ownership and selector-only clearing leave uncovered lifecycle transitions.
Base / error paths PASS Host :230-265,303-313,316-437,440-478 preserves bounded retries, stale-page guards, rejection, native transport failure and terminal unavailability. Bridge :151-181,301-349 preserves locked, generation and unavailable checks.
Base / tests FINDING New tests :155-305 cover no demand, first execute readiness, start of setup, stored discovery and ordinary lock/unlock. Existing tests :316-394,454-588,620-744 cover mounted-page lock, batch transition, missing ref, unmount, invalid results and retries. Batch assertion preserves the wrong demand behavior. No pre-mount lock regression. All inspected, none executed.
Base / permissions, secrets and product wiring PASS No dependency/permission changes. Bridge :184-264 keeps keychain scope and wallet binding; :367-380 sends key only through readiness. Root :120-127 and mobileInfrastructure :253-269 retain common enablement. No locale/metrics changes.
Base / signal over noise PASS Added demand functions have distinct responsibilities and production callers. No new TODO, debug output, commented code or unused exports. Listener exception isolation at bridge :78-85 follows existing reset notification :117-125.
Blocking checks / anti-pattern disposition FINDING Both lifecycle defects require REQUEST_CHANGES under frozen shared policy.
Controller portability / platform import; platform globals; new dependency outside DI NOT_APPLICABLE No controller code or DI change. Native dependencies remain in the existing mobile bridge.
Controller portability / deep import PASS New code adds no controller imports. Existing utils/accountUtils subpath import at bridge :13 predates the contribution.
Controller portability / publisher contract PASS LighterSignerBridge object and Core method signatures remain unchanged; new demand exports are mobile-local. Core types :232-294 retain createClient/execute/reset/onReset.
Missing numeric data / converted zero; unknown zero; fabricated value; placeholder state NOT_APPLICABLE No financial numeric conversion, loading value, fallback or calculation changed.
Constants / timeout, slippage, leverage, precision, URL, provider, threshold, cache literals NOT_APPLICABLE No production literals in these categories added. Existing signer deadlines and origin remain unchanged. Test literals are fixtures.
Protocol / execution ID; provider identity; bypass; UI branching; errors; symbols; precision; detailedOrderType NOT_APPLICABLE No routing, normalization, order display or market semantics changed. This is the existing mobile signer transport, not a new provider-specific UI path.
Pro gates / single gate; fixture mode; shared logic; tab index NOT_APPLICABLE Hidden transport has no Pro market UI, tabs or mode behavior. Existing host/credentials gate unchanged.
MetaMetrics / property keys; values; new events; source; reusable source; new view tracking; duration NOT_APPLICABLE No metrics event or visible screen/view added or changed. Hidden host timing changes only.
Sentry / background volume and sampling NOT_APPLICABLE No spans or instrumentation added. Existing dev-only readiness latency is unchanged at host :39-49,380.
Sentry / async flow named trace and completion NOT_APPLICABLE Existing signer flow and instrumentation retained; no new named user flow. Claimed timings lack recorded evidence, finding 3.
Connection / cleanup owner before async setup FINDING Finding 1. Lazy child owns lock retirement while discovery can remain active without ever mounting it.
Connection / second connect owner; tick setState; per-component socket; subscription leak NOT_APPLICABLE No provider connection/disconnection, stream subscription or socket changes. Demand subscription cleanup is explicit at bridge :108-115.
Connection / stale reads; static WebView tick work; cache invalidation NOT_APPLICABLE No position/order snapshots, chart payload or post-trade invalidation changed.
Data / derived structural flag lifecycle FINDING Demand initializes false, requests set true, selector false clears it. Batched lock misses clear, finding 2.
Data / old context, async cleanup ownership FINDING Finding 1. Existing wallet binding checks at bridge :247-264 remain, but cannot retire work on a missed lock/unlock generation.
Data / delayed balance; advisory ranking; active inputs; chart synchronization; unknown balance; late defaults NOT_APPLICABLE No balances, controls, classification or chart state changed.
Data / direct controller call; missing accountState; unknown CTA blocker; accepted mutations; stale position; preload; order race; leverage bypass NOT_APPLICABLE No UI/controller data path, trading inputs, mutation reconciliation, preload or submission validation change.
Trade / signed bounds; pre-trade checks; post-trade refresh; user slippage NOT_APPLICABLE Signer transport timing does not change order parameters, financial checks or confirmations.
Locale / duplicate keys; source translations; orphaned keys; revert-sensitive locale tests NOT_APPLICABLE No localized copy, strings calls or locale keys changed.
Tests / degenerate arithmetic; numeric units NOT_APPLICABLE No formulas, numeric controls or quantization change.
Tests / clock control PASS New lazy tests use async act without fake clock manipulation. Existing retry/deadline tests retain timer control and teardown :137-143.
Tests / assertions target behavior and layer FINDING Real bridge and React subscription used with mocked native WebView, appropriate for host protocol. Mount count and postMessage assertions cover timing. Missing pre-mount lock case and incorrect batched expectation as findings 1/2.
Embedded signer / outbound denial before keys PASS wasm-wrapper.standalone.html:5-19 denies connect/subresources and installs transport denial before runtime. Host :451-464 retains origin/navigation/file flags. No HTML changes. Native enforcement execution not verified.
Embedded signer / messages parsed unknown; typed result validation PASS Host :131-204,324-410 parses unknown and checks message/result shapes before resolving. Existing protocol validation unchanged.
Embedded signer / missing transport and unmount reject promptly FINDING Mounted child covers these paths at :303-313,345-349; lazy discovery and pre-mount lock lack retirement, finding 1.
Embedded signer / bounded recovery; one deadline PASS Host :230-265 bounds retries; bridge :267-298,356-381 uses one deadline across retrieval/readiness/execution.
Parity / compare affected counterparts PASS Frozen Core types and LighterProvider :2150-2255 show cached session invalidation via bridge onReset. Frozen Extension init :98-129 has no Lighter host/credential counterpart. No mirrored extension change required.
Shared packages / methods, state, events, exports, versions and migration NOT_APPLICABLE No published controller state/method/event/export/version change. Mobile demand exports are host internals. Frozen type and consumer reads establish the existing seam only, not compilation.

Unchecked evidence and Run QA handoff

CI execution and deterministic-check receipts are NOT_CHECKED because none were supplied. Performance captures and first Lighter action success are NOT_CHECKED. Request recorded head-bound evidence, finding 3. Run QA should explicitly cover first signer demand, held discovery keychain retrieval with lock while no host exists, first-call lock before host mount, batched lock/unlock, ordinary lock/unlock, recovery, and the Android unlock stall comparison. No runtime pass is inferred from source or test inspection.

Mobile criteria outcomes

Family / individual rule Outcome Evidence or exclusion
Testability / interactive identifiers; value owner; TP/SL inputs NOT_APPLICABLE Hidden host has no controls, displayed input or TP/SL field. Existing WebView testID remains on the native element at host :448.
Testability / centralized testID NOT_APPLICABLE No new or changed testID. Existing local constant at host :65 predates this contribution; no request to move unrelated code.
Navigation / all exit paths NOT_APPLICABLE No routes, back handlers or gestures changed. Wallet lock is covered by the shared lifecycle findings.
Modal / width-constrained wrapper and Android close NOT_APPLICABLE No modal, bottom sheet or layout change. Existing hidden styles unchanged.
Controller integration / bump and hand-written mocks NOT_APPLICABLE No package bump or controller call-site signature change. No integration execution claimed.
Tracing / new screen; error context; ensureError; TraceName; finally completion NOT_APPLICABLE No new screen, logger call, error forwarding or trace. Read docs/perps/perps-sentry-reference.md:14-80 and connection trace references. Existing signer dev latency is retained.
Reference paths / UI and controller constants PASS No added production timing, financial or event literal. Existing PERPS_CONSTANTS package import at host :35 retained.
Reference paths / update documented patterns NOT_APPLICABLE docs/perps/lighter-api-keys.md documents derivation/recovery and developer configuration, not eager host mounting. No documented pattern there changes.
Test layers / whole page unit tests PASS Hidden native signer protocol is a narrow host contract, not a rendered market page. Real bridge and React subscription are exercised; native I/O and Engine are mocked. No Lighter host view test exists.
Test layers / fake provider flow; hook/selector page mocks NOT_APPLICABLE Tests do not fake provider/trading success or assert screen behavior. Selector mock controls the host boundary only. Real provider setup/action success remains unverified, finding 3.
Test layers / coverage conversion NOT_APPLICABLE No tests converted or removed. Existing mounted-page cases are retained by explicit demand in setup. Findings 1/2 name required regression corrections.

Evidence

Static source and test evidence is cited throughout the shared and mobile ledgers. The source diff inventory contains exactly the three files in Diff scope. The frozen instruction manifest lists no extra instruction files. Read both frozen skill entrypoints, shared.md, parity.md, shared-packages.md, owned-paths.json, the selected mobile overlay and mobile.md. Source testing instructions were read, with TASK.md's no-execution boundary controlling this review.

Limitations

CI, deterministic checks, raw performance measurements and native first-action behavior are not verified by this review. No receipts or logs were available to inspect. Test source establishes intended coverage only. Outbound denial is present in source but was not executed here. A separate Run QA handoff is required for runtime claims. Review-side non-execution alone is not a product failure; finding 3 asks for missing author evidence.

Recommended action

REQUEST_CHANGES. Keep lock retirement outside the demand-gated page, clear demand at every lock event, and cover lazy discovery plus batched lock/unlock before supplying head-bound CI and runtime evidence. Keep the existing on-demand mount and readiness protocol. Do not publish this review from this task.

clearLighterSignerRequest();
}
}, [isUnlocked]);
return isUnlocked && isRequested ? <UnlockedLighterSignerWebView /> : null;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major. Keep lock retirement active while the signer page is absent. getStoredKeyIndices/getRecoverableKeyIndices intentionally do not request the page, but the KeyringController:lock subscription and setLighterBridgeUnavailable call remain inside UnlockedLighterSignerWebView. Hold a native keychain read during discovery, then lock: the outer component only clears demand, so the bridge generation is unchanged and the pending request waits for the read or its 90-second timeout. If the same wallet unlocks before the read resolves, the old operation can complete in the new session. Move lock retirement to an always-mounted owner and add a lazy-discovery regression asserting prompt rejection on lock and rejection of late completion.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, this was real. Key discovery deliberately doesn't request the page. So while no page was mounted, nothing subscribed to KeyringController:lock. The lock only cleared demand, generation stayed the same, and the retired promise never rejected. A keychain read held across a lock and unlock of the same wallet could finish in the new session. The same gap covered createClient between requestLighterSigner() and the page's effect registering, for example when Redux still reports locked. The impact was small, since discovery only returns slot indices for the same bound wallet and assertWallet still runs, but it broke the "lock retires all bridge work" rule that main keeps.

Fixed in fc88a91. The always-mounted LighterSignerWebView host now owns the keyring lock and unlock events:

  • On lock, it calls clearLighterSignerRequest() and setLighterBridgeUnavailable(LIGHTER_SIGNER_LOCKED_ERROR). That bumps generation and rejects every withOwnership operation right away, whether or not a page is mounted. A late completion after the unlock fails on its stale owner.
  • On unlock, it calls reviveLighterBridge() only. It never requests or mounts the page.
  • The page component's own lock handler is unchanged. It still hides the native page synchronously and rejects executePromises.

New regressions in LighterSignerWebView.test.tsx, each of which fails against the previous head:

  • retires key discovery on lock while no page is mounted: discovery rejects with the locked error without waiting for the held keychain read, and no page renders.
  • does not let discovery from before a lock complete after the unlock: a discovery held across lock and unlock rejects. A fresh discovery afterwards succeeds without mounting a page.
  • retires client setup that requested the page before it mounted: createClient with Redux still locked rejects promptly on lock, and the request is cleared.

The unlock path still mounts nothing, so the unlock stall result is unaffected.

reviveLighterBridge();
} else {
// Locking unmounts the page; the next unlock waits for a new request.
clearLighterSignerRequest();

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Major. Clear signer demand on the keyring lock event, independently of Redux rendering. This effect only clears it when selectIsUnlocked commits false. With lock and unlock in one render batch, demand stays true and the existing child's onUnlock recreates the 10 MB page before any new Lighter call. The retained test at LighterSignerWebView.test.tsx:356-374 explicitly expects that eager second mount. Clear the request at the event boundary and update the batched-transition test to assert that no replacement page appears until a fresh signer call.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Confirmed, this was real, though the impact is performance rather than correctness. EngineService batches controller updates into Redux, so a lock and unlock inside one flush never commit isUnlocked = false. The Redux-driven effect never cleared demand, and the page's onUnlock reloaded the 10 MB document before any new Lighter call. Security was unaffected, because the page's own handlers still rotated the page and retired pending calls. It was the old unlock cost coming back in an edge case.

Fixed in fc88a91. The host clears demand in its KeyringController:lock handler and no longer uses a Redux effect. Unlock revival also moved to the KeyringController:unlock event. Moving only the lock would have left a batched lock and unlock with no page stuck on the locked error, because the Redux effect that revives the bridge would never run.

Tests:

  • waits for a new call before loading a page after a lock and unlock in one render batch (rewritten from the eager-remount expectation). After the batch the old page is unmounted, no replacement renders, and demand is cleared. The next signer call mounts a fresh page and resolves.
  • keeps the bridge usable after a batched lock and unlock with no page (new). After the batch, the next call mounts the page and succeeds.
  • The two lazy-mount lock and unlock tests now drive the keyring events instead of Redux re-renders, which matches what the host listens to.

Move the keyring lock and unlock handlers to the always-mounted signer
host. Lock now clears the page request and retires bridge work even when
no page is mounted (key discovery never mounts one), and a lock and
unlock that Redux batches into one commit no longer reloads the page.

Co-authored-by: Cursor <cursoragent@cursor.com>
@tommasini

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Findings 1 and 2 were both real, and both are fixed in fc88a91. Details are in the inline threads. They had one cause: lock handling still lived in the page component, which now mounts only on demand. The always-mounted host now owns the keyring lock and unlock events. The page still mounts only when the wallet is unlocked and a signer call asks for it, so nothing loads at unlock and the unlock stall result in the PR description still applies.

Finding 3 (evidence):

  • Unit tests: all 130 tests in app/components/UI/Perps/Lighter pass locally on fc88a91. That includes 32 in LighterSignerWebView.test.tsx, of which 7 new or updated tests fail against 82f6226. ESLint is clean on the changed files, and lint:tsc shows no errors in Perps/Lighter. CI on this head is running.
  • Unlock stall: the per-unlock tables in the PR comments (with #38839, this PR only) were measured on a Hyperliquid wallet at 82f6226. This change adds two messenger subscriptions at Root mount and nothing to the unlock path. A re-run of the same Z Fold4 session on this head is still pending.
  • Still pending before re-review: a device run on a Lighter wallet showing the first Lighter action succeeding and lock and unlock resetting demand. You're right that the Hyperliquid runs don't show it.

Co-authored-by: Cursor <cursoragent@cursor.com>

@cursor cursor Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.

Fix All in Cursor

❌ Bugbot Autofix is OFF. To automatically fix reported issues with cloud agents, have a team admin enable autofix in the Cursor dashboard.

Reviewed by Cursor Bugbot for commit 91feb61. Configure here.

@tommasini

Copy link
Copy Markdown
Contributor Author

Device evidence for fc88a91 (review finding 3)

Same device and method as the earlier comments: Galaxy Z Fold4 (SM-F936B, 120 Hz), main-exp 8.19.0 (4532), cold start, then biometric unlock, then 20 s on WalletView, with the in-app perf session reporting to the collector. Stalls are counted the same way as before: UI-thread stalls on WalletView with the WebView mount on the stack (loadDataWithBaseURL / RNCWebViewManager).

Unlock stalls with this PR's current code

Build: run 42076900260, poc/perf-verify-lighter-v2. That's the same perf-session base as before plus this PR's Lighter files at fc88a91.

Baseline (5 unlocks) fc88a91 (5 unlocks)
Main-thread stalls with the Lighter WebView on the stack 221, 379, 411, 323, 296 ms (median 323 ms) 0, 0, 0, 0, 0 ms (median 0 ms)

Moving the lock handling into the host costs nothing at unlock, as expected.

First Lighter call, and lock then unlock, on a wallet with no Lighter account

The test wallet has no Lighter account, so the app never calls the signer on its own. To exercise the real page anyway, I made a verification-only build: run 42078616977, poc/perf-verify-lighter-v3, which will not be merged. 25 s after each KeyringController:unlock, it does three things through the real bridge and reports each step as a perf span:

  1. Records whether anything had requested the page yet.
  2. Runs createClient on testnet chain 300, account 1, slot 3. That path derives the key in memory, so nothing is written to the keychain and nothing goes over the network.
  3. Runs _createAuthToken.

The page's own mount-to-ready time and unmount are recorded as well. Scenario: cold start and unlock, 40 s in the app, background past the 30 s auto-lock, foreground and unlock again, 40 s more.

Step First unlock After lock and unlock
Page requested 25 s after unlock? No No (the lock cleared the request)
createClient ok, 1250 ms ok, 1154 ms (the bridge revived)
Page mount to ready 1064 ms 980 ms (a fresh page)
WebView stall when the page mounts 231 ms, on the first call 260 ms, on the first call
_createAuthToken ok, 183 ms ok, 167 ms
Page unmount at the auto-lock

So for Lighter users, the mount cost moves from every unlock to their first signer call in each unlocked session. The page doesn't come back after a lock until a new call asks for it, and that call works.

CI on 91feb61 (empty commit; GitHub hadn't picked up the push of fc88a91)

The three failures are unrelated to this change:

  • Detect flaky unit tests: its AI analysis step failed with tool errors ("reviewed 0 of 1 requested file(s)"). It reported 0 findings and 0 historically flaky tests.
  • Integration tests (2): PredictNext/services/PredictOrderService.integration.test.ts.

Co-authored-by: Cursor <cursoragent@cursor.com>

@abretonc7s abretonc7s left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Both lock findings from the last review are fixed and covered by tests: lock retirement now runs in the always-mounted host even with no page mounted, and the bridge only revives after an observed lock. Approving; one non-blocking suggestion inline.

messenger.subscribe('KeyringController:unlock', onUnlock);
return () => {
messenger.tryUnsubscribe('KeyringController:lock', onLock);
messenger.tryUnsubscribe('KeyringController:unlock', onUnlock);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Non-blocking: now that key discovery runs without a mounted page, nothing resets the bridge if this host unmounts (Lighter flag turned off mid-session) while a discovery is in flight. Before this PR the page's own cleanup called resetLighterBridge(). Low impact, since the host lives for the app's lifetime and discovery is bounded by the 90 s timeout and still checks the keyring lock, but calling resetLighterBridge() here would keep unmount consistent with lock.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Will create a follow up PR with this 🤞

@tommasini
tommasini enabled auto-merge November 6, 2026 05:17
@sonarqubecloud

sonarqubecloud Bot commented Nov 6, 2026

Copy link
Copy Markdown

@tommasini
tommasini added this pull request to the merge queue Nov 6, 2026
Merged via the queue into main with commit b92cb60 Nov 6, 2026
95 of 96 checks passed
@tommasini
tommasini deleted the perf/lighter-signer-webview-unlock branch November 6, 2026 05:40
@github-actions github-actions Bot locked and limited conversation to collaborators Nov 6, 2026
@metamask-ci metamask-ci Bot added the release-8.21.0 Issue or pull request that will be included in release 8.21.0 label Nov 6, 2026
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

release-8.21.0 Issue or pull request that will be included in release 8.21.0 size-M team-mobile-platform Mobile Platform team

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants