chore(runway): cherry-pick fix(perps): recover connection after app state changes#26918
Merged
joaoloureirop merged 1 commit intorelease/7.68.0from Mar 3, 2026
Merged
Conversation
) Fixes Perps WebSocket connectivity issues when: 1. **App returns from background** — after a few minutes in background, the OS silently kills the WebSocket but `PerpsConnectionManager` still reports `isConnected = true`. No code path detected the stale connection or triggered reconnection. 2. **WiFi/network drops and restores** — toggling WiFi, airplane mode, or losing cellular signal kills the WebSocket, but since the app stays in `active` state, the existing `AppState`-based recovery (if any) never fires. `PerpsConnectionManager` had no lifecycle awareness of: - **React Native `AppState` transitions** (background → foreground) - **Network connectivity changes** (offline → online via `@react-native-community/netinfo`) Arthur's prior fix ([#26334](#26334)) made `StreamChannel.ensureReady()` connection-aware to avoid blind polling on slow connections, but it only helps when a reconnection is **already in progress** (`isConnecting = true`). After background resume or WiFi restore, nobody triggers the reconnection in the first place. - **`AppState` listener** — on `active`, cancels any pending grace period and runs `validateAndReconnect()` - **`NetInfo` listener** — tracks `wasOffline` state; on offline → online transition, runs `validateAndReconnect()` - **`validateAndReconnect(context)`** — shared method that sends a lightweight `ping()` health check to the active provider. If the ping fails (stale WebSocket), marks the connection as lost and triggers `reconnectWithNewContext({ force: true })` which reinitializes the controller, validates with a fresh health check, and preloads all stream subscriptions. - **Cleanup** — both listeners are properly removed in `cleanupStateMonitoring()` CHANGELOG entry: Fixed Perps WebSocket not reconnecting after app resume from background or WiFi/network toggle Fixes: connectivity loss after backgrounding app, WiFi off/on not recovering Perps data ```gherkin Feature: Perps connection recovery Scenario: App returns from background after several minutes Given the user has navigated to the Perps trading screen And the user has an open position When the user backgrounds the app for 3+ minutes And the user returns to the app Then the Perps WebSocket reconnects automatically And positions, prices, and account data resume updating Scenario: WiFi is toggled off and back on Given the user is viewing live Perps positions And WiFi is connected When the user turns WiFi off And waits a few seconds And turns WiFi back on Then the Perps WebSocket reconnects after network is restored And live data resumes without requiring navigation away Scenario: Airplane mode is toggled Given the user is on the Perps trading screen When the user enables airplane mode And then disables airplane mode Then the connection recovers and live data resumes ``` After backgrounding or WiFi toggle, Perps shows stale data with no automatic recovery. User must navigate away and back to restore the connection. Connection automatically recovers via health-check ping and force reconnection. Live data resumes within seconds. - [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. - [x] 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. <!-- CURSOR_SUMMARY --> --- > [!NOTE] > **Medium Risk** > Touches Perps connection lifecycle and reconnection paths; regressions could cause reconnect loops or delayed/stuck loading during flaky connectivity. > > **Overview** > Improves Perps WebSocket resilience by adding AppState and NetInfo listeners in `PerpsConnectionManager` to detect background→foreground and offline→online transitions, validate the connection via provider `ping()`, and force a reconnect when stale. > > Adds network-restore retry/backoff knobs (`NetworkRestoreMaxRetries`, `NetworkRestoreRetryBaseMs`) and ensures cleanup of new subscriptions/timers on teardown; reconnection now explicitly calls `PerpsController.disconnect()` before `init()` to avoid skipping re-init on a dead socket. > > Updates `usePerpsHomeData` to treat WebSocket-backed sections (positions/orders/activity) as loading while `isConnecting`, preventing brief empty-state flashes during reconnection. > > <sup>Written by [Cursor Bugbot](https://cursor.com/dashboard?tab=bugbot) for commit b3aab14. This will update automatically on new commits. Configure [here](https://cursor.com/dashboard?tab=bugbot).</sup> <!-- /CURSOR_SUMMARY -->
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. |
joaoloureirop
approved these changes
Mar 3, 2026
Contributor
🔍 Smart E2E Test Selection⏭️ Smart E2E selection skipped - base branch is not main (base: release/7.68.0) All E2E tests pre-selected. |
Collaborator
|
No release label on PR. Adding release label release-7.68.0 on PR, as PR was cherry-picked in branch 7.68.0. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to subscribe to this conversation on GitHub.
Already have an account?
Sign in.
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
Fixes Perps WebSocket connectivity issues when:
the OS silently kills the WebSocket but
PerpsConnectionManagerstillreports
isConnected = true. No code path detected the stale connectionor triggered reconnection.
or losing cellular signal kills the WebSocket, but since the app stays
in
activestate, the existingAppState-based recovery (if any) neverfires.
Root Cause
PerpsConnectionManagerhad no lifecycle awareness of:AppStatetransitions (background → foreground)@react-native-community/netinfo)Arthur's prior fix
(#26334) made
StreamChannel.ensureReady()connection-aware to avoid blind polling onslow connections, but it only helps when a reconnection is already in
progress (
isConnecting = true). After background resume or WiFirestore, nobody triggers the reconnection in the first place.
Fix
AppStatelistener — onactive, cancels any pending graceperiod and runs
validateAndReconnect()NetInfolistener — trackswasOfflinestate; on offline →online transition, runs
validateAndReconnect()validateAndReconnect(context)— shared method that sends alightweight
ping()health check to the active provider. If the pingfails (stale WebSocket), marks the connection as lost and triggers
reconnectWithNewContext({ force: true })which reinitializes thecontroller, validates with a fresh health check, and preloads all stream
subscriptions.
cleanupStateMonitoring()Changelog
CHANGELOG entry: Fixed Perps WebSocket not reconnecting after app resume
from background or WiFi/network toggle
Related issues
Fixes: connectivity loss after backgrounding app, WiFi off/on not
recovering Perps data
Manual testing steps
Screenshots/Recordings
Before
After backgrounding or WiFi toggle, Perps shows stale data with no
automatic recovery. User must navigate away and back to restore the
connection.
After
Connection automatically recovers via health-check ping and force
reconnection. Live data resumes within seconds.
Pre-merge author checklist
Docs and MetaMask Mobile
Coding
Standards.
if applicable
guidelines).
Not required for external contributors.
Pre-merge reviewer checklist
app, test code being changed).
in the ticket it closes and includes the necessary testing evidence such
as recordings and or screenshots.
Note
Medium Risk
Touches Perps connection lifecycle and reconnection paths; regressions
could cause reconnect loops or delayed/stuck loading during flaky
connectivity.
Overview
Improves Perps WebSocket resilience by adding AppState and NetInfo
listeners in
PerpsConnectionManagerto detect background→foregroundand offline→online transitions, validate the connection via provider
ping(), and force a reconnect when stale.Adds network-restore retry/backoff knobs (
NetworkRestoreMaxRetries,NetworkRestoreRetryBaseMs) and ensures cleanup of newsubscriptions/timers on teardown; reconnection now explicitly calls
PerpsController.disconnect()beforeinit()to avoid skipping re-initon a dead socket.
Updates
usePerpsHomeDatato treat WebSocket-backed sections(positions/orders/activity) as loading while
isConnecting, preventingbrief empty-state flashes during reconnection.
Written by Cursor
Bugbot for commit
b3aab14. This will update automatically
on new commits. Configure
here.