Repository navigation
perf(perps): mount the Lighter signer WebView only when needed - #38837
Conversation
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>
|
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. |
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. |
Smart E2E Test SelectionSelected E2E tagsSmokePerps AI Confidence: 85 E2E reasoningExpand to readThe PR modifies the Lighter signer infrastructure for Perps trading:
Risk factors:
Tag selection rationale:
|
Before/after on a deviceMeasured 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.
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 ( 🤖 Generated with Claude Code |
With only this PR appliedSame 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 (
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 |
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
left a comment
There was a problem hiding this comment.
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
-
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.
-
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.
-
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; |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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()andsetLighterBridgeUnavailable(LIGHTER_SIGNER_LOCKED_ERROR). That bumpsgenerationand rejects everywithOwnershipoperation 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:createClientwith 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(); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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>
|
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):
|
Co-authored-by: Cursor <cursoragent@cursor.com>
There was a problem hiding this comment.
Cursor Bugbot has reviewed your changes using default effort and found 1 potential issue.
❌ 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.
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 ( Unlock stalls with this PR's current codeBuild: run 42076900260,
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 accountThe 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,
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.
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:
|
Co-authored-by: Cursor <cursoragent@cursor.com>
abretonc7s
left a comment
There was a problem hiding this comment.
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); |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Will create a follow up PR with this 🤞
|




Description
Problem. Every unlock blocks the Android main thread for about 400 ms, even for users who never use Lighter.
LighterSignerWebViewmounts as soon as the wallet unlocks and passeswasm-wrapper.standalone.html(10.3 MB, the Go/WASM signer as base64) assource.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
WalletViewfirst appeared, it recorded two UI-thread stalls, both insideRNCWebViewManager.onAfterUpdateTransaction←ViewManager.createViewInstance(FabricpreallocateView/createView):ReadableNativeMap.importValues: copying the 10 MB prop across JNI.WebView.loadDataWithBaseURL: loading the inline document on the main thread.The only other inline-HTML WebView in
RootisSnapsExecutionWebView, and it mounts before Engine init, not at unlock.Fix. Mount the signer page only when a Lighter call needs it:
lighterSignerBridgenow records a request (requestLighterSigner) when client setup starts or a WASM call is made.LighterSignerWebViewsubscribes to it withuseSyncExternalStore, and mounts only when the wallet is unlocked and a request exists.ready. Client setup requests the page before reading the keychain, so both happen in parallel.getStoredKeyIndices,getRecoverableKeyIndices) doesn't need the page, so it doesn't trigger a load.The security properties are unchanged: same
https://localhostorigin, 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
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)
trace()for usage andaddTokenfor an exampleFor performance guidelines and tooling, see the Performance Guide.
Pre-merge reviewer checklist
🤖 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+useSyncExternalStoreinLighterSignerWebView).createClientandexecuteset 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:lockit 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.