Skip to content

chore(runway): cherry-pick fix(perps): recover connection after app state changes#26918

Merged
joaoloureirop merged 1 commit intorelease/7.68.0from
cherry-pick-7-68-0-c4f83e4
Mar 3, 2026
Merged

chore(runway): cherry-pick fix(perps): recover connection after app state changes#26918
joaoloureirop merged 1 commit intorelease/7.68.0from
cherry-pick-7-68-0-c4f83e4

Conversation

@runway-github
Copy link
Contributor

@runway-github runway-github bot commented Mar 3, 2026

Description

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.

Root Cause

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

Fix

  • 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

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

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

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

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.

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.

Written by Cursor
Bugbot
for commit
b3aab14. This will update automatically
on new commits. Configure
here.

[c4f83e4](https://github.com/MetaMask/metamask-mobile/commit/c4f83e4148417219ccde8dc0f59442d46aca07de)

)

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 -->
@runway-github runway-github bot requested a review from a team as a code owner March 3, 2026 16:33
@github-actions
Copy link
Contributor

github-actions bot commented Mar 3, 2026

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.

@metamaskbot metamaskbot added the team-bots Bot team (for MetaMask Bot, Runway Bot, etc.) label Mar 3, 2026
@joaoloureirop joaoloureirop enabled auto-merge (squash) March 3, 2026 16:34
@github-actions
Copy link
Contributor

github-actions bot commented Mar 3, 2026

🔍 Smart E2E Test Selection

⏭️ Smart E2E selection skipped - base branch is not main (base: release/7.68.0)

All E2E tests pre-selected.

View GitHub Actions results

@github-actions github-actions bot added the size-M label Mar 3, 2026
@joaoloureirop joaoloureirop merged commit 2529967 into release/7.68.0 Mar 3, 2026
109 checks passed
@joaoloureirop joaoloureirop deleted the cherry-pick-7-68-0-c4f83e4 branch March 3, 2026 17:32
@github-actions github-actions bot locked and limited conversation to collaborators Mar 3, 2026
@metamaskbot metamaskbot added the release-7.68.0 Issue or pull request that will be included in release 7.68.0 label Mar 4, 2026
@metamaskbot
Copy link
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.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

release-7.68.0 Issue or pull request that will be included in release 7.68.0 size-M team-bots Bot team (for MetaMask Bot, Runway Bot, etc.)

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants