App icon indicating copy to clipboard operation
App copied to clipboard

[$250] Hybrid-Home- Home cards do not refresh after reopen app from other apps

Open applause-bot[bot] opened this issue 1 month ago • 89 comments

If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.


Version Number: 9.5.24-2 Reproducible in staging?: Yes Reproducible in production?: Yes If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://github.com/Expensify/App/pull/103996 Email or phone of affected tester (no customers): [email protected] Issue reported by: Applause Internal Team Bug source: Pull Request QA execution Device used: Pixel 7a Android 17 App Component: Left Hand Navigation (LHN)

Action Performed:

Preconditions:

  • Submit any expenses for more than 10 minutes: so the Awaiting approval section will be displayed in Home
  • Approval should be enabled in Workspace
  1. Open Hybrid app
  2. Go to Home
  3. Open another app (like Gmail, Slack,...)
  4. Wait for more than 1 minute (should be 2-3 minutes)
  5. Reopen Hybrid app

Expected Result:

Verify the Home cards refresh once.

Actual Result:

The Home cards do not refresh

Workaround:

Unknown

Platforms:

  • [x] Android: App
  • [ ] Android: mWeb Chrome
  • [ ] iOS: App
  • [ ] iOS: mWeb Safari
  • [ ] iOS: mWeb Chrome
  • [ ] Windows: Chrome
  • [ ] MacOS: Chrome Safari

Screenshots/Videos

https://github.com/user-attachments/assets/ba1235f4-0dc8-4391-8a44-f9be399a4932

View all open jobs on GitHub

Applause Internal Information Exported by: Julia Ponikarchuk Bug ID: 7298507

Upwork Automation - Do Not Edit

applause-bot[bot] avatar Oct 28 '26 07:10 applause-bot[bot]

While Applause doesn't embed attachments for this bug, here are the links for quick view: https://platform.applause.com/services/links/v1/external/d68ba0c4f736e003260aedcfe78f0dafcc35b5f8f5b6b7b3327baff2d9bc706a

applause-bot[bot] avatar Oct 28 '26 07:10 applause-bot[bot]

⚠️ Preliminary analysis (low confidence) — treat as a starting point, not a conclusion.

I think the Home cards probably do refresh when you reopen the app, but the refresh has nothing visible to show. The cards never show a loading state during a background refresh. If no data changed while you were away, the screen looks exactly the same before and after.

This would also explain why production reproduces. The QA steps come from Stop Home refetching on first expense loads and quick tab returns, merged 2026-10-27, so production likely doesn't have it yet. The return-to-app refresh it changed has been there since September.

I couldn't confirm this. I had no access to server logs, and I couldn't check the HybridApp Android host code. To confirm, check one of these:

  1. Server logs: look for a burst of Search requests from the tester's account right after each reopen. If they're there, this isn't a bug. QA step 9 should then say to check the network log, or to change an expense on another device while the phone is in the background.
  2. Visible test: with the phone on Home, send the app to the background. On web, submit a new expense. Wait more than 1 minute, then reopen the phone app. Awaiting approval should show the new total. If it doesn't, the refresh really isn't firing on HybridApp Android.
Code path
  • src/hooks/useAppReturnCount/index.native.ts:14-24: counts a return each time React Native's AppState goes background → active. Nothing in this path is specific to HybridApp.
  • src/hooks/useTabFocusedRefresh.ts:50-72: a return 60 seconds or more after the last refresh calls the refresh right away while Home is focused. A return under 60 seconds sets a timer and refreshes when it ends. I found no path that drops a return after more than 60 seconds.
  • src/pages/home/YourSpendSection/useYourSpendData.ts:374-399: a row shows LOADING only when it has no results yet or an unconfirmed total. A refresh of existing results changes nothing on screen unless the data changed. The PR's QA step 5 expects this ("no loading state, the list does not jump").

Other explanations I couldn't rule out:

  • The HybridApp Android host may not pass app pause and resume through to React Native. If so, AppState never changes and no refresh runs. A visible test (option 2 above) would show this.
  • The request may be skipped at the moment of resume. For example, the app still thinks it's offline, or an identical request is already in flight. Each of these is followed by a later refresh, so it's unlikely to explain a refresh that never happens.

Next Steps: Reply with @MelvinBot <your feedback> to refine this analysis.


view run

MelvinBot avatar Oct 28 '26 07:10 MelvinBot

Triggered auto assignment to Contributor-plus team member for initial proposal review - @getusha (External)

melvin-bot[bot] avatar Oct 28 '26 07:10 melvin-bot[bot]

Job added to Upwork: https://www.upwork.com/jobs/~022115347557253975645

melvin-bot[bot] avatar Oct 28 '26 07:10 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

On Android Hybrid version 9.5.24-2, Home cards reportedly remain stale after the user backgrounds the app for two to three minutes and returns. The required behavior is one refresh on return under the issue’s stated conditions.

Audit verdict: insufficient evidence for an implementation-ready proposal. The report establishes a symptom, but supplies no lifecycle trace, request log, affected source revision, or executable regression test.

What is the root cause of that problem?

The root cause is unverified. Claiming a missing AppState listener, broken navigation focus handling, or expired refresh timer would currently be speculation.

The source retrieved during this review shows:

  • src/pages/home/HomePage.tsx, lines 28–38, reads loading state and initializes component state. Lines 69–105 compose independently rendered Home sections. This component alone does not establish which layer owns their refresh behavior. Retrieved source
  • A separately cached src/pages/home/ForYouSection/index.tsx subscribes to derived Onyx todo data. That demonstrates a data subscription in that retrieved revision; it does not prove that the reported Awaiting approval card uses the same refresh path in 9.5.24-2. Retrieved source

These are mutable main references retrieved from different cached snapshots, not verified release-specific evidence. The referenced PR #103996 and affected release source could not be retrieved. No Expensify checkout was available locally, and shell access to GitHub failed.

The following failure modes remain unresolved:

  1. The native foreground event never reaches the relevant JavaScript runtime.
  2. The event arrives, but refresh eligibility incorrectly rejects it.
  3. A request executes, but its response fails to update the subscribed data.
  4. Data updates correctly, but the card fails to render the change.

Each requires a different fix.

What changes do you think we should make in order to solve the problem?

No exact TypeScript diff is defensible yet. Inventing a refresh function, import, or insertion line would violate the required evidence standard.

First capture one reproduction against a pinned affected commit, recording:

  • Native and JavaScript lifecycle transitions with timestamps.
  • Existing refresh eligibility decisions and request counts.
  • Refresh response completion and the relevant Onyx changes.
  • The resulting card content.

Then modify the existing owner of the demonstrated failure. A new foreground listener is justified only if the trace proves that the current refresh path lacks that trigger.

The smallest acceptable patch must preserve existing refresh timing, prevent duplicate requests from overlapping triggers, and clean up any subscription it introduces. The report’s waiting instructions do not establish an exact throttle boundary.

What alternative solutions did you explore? (Optional)

No MelvinBot proposal was supplied, so there is no concrete implementation to rebut.

The following approaches should be rejected without additional evidence:

  • Navigation focus alone: Returning from another app does not establish that navigation focus changes.
  • An unconditional foreground fetch: May duplicate existing resume or reconnect requests.
  • Forced remounting: May reset local state while leaving the data refresh defect unresolved.
  • Periodic polling: Adds ongoing requests without demonstrating why the existing refresh mechanism fails.

Existing-proposal overlap and current issue eligibility also remain unverified. Expensify requires reproduction and review of existing proposals before submission. Contribution requirements

What automated tests can you add to prevent this from re-occurring?

Once the refresh owner is identified, add a Jest regression test using its real lifecycle handler and mocked API boundary:

  1. Mount Home with stale Awaiting approval data and complete initial loading.
  2. Clear initial request observations.
  3. Emit the captured Hybrid background transition, advance fake time by 180_000 milliseconds, then emit the captured foreground transition.
  4. Assert exactly one relevant refresh request.
  5. Resolve it with changed approval data and assert that the displayed card updates.
  6. Emit a duplicate foreground notification and assert no additional refresh.
  7. Unmount, emit another lifecycle event, and assert no request.

Add boundary tests only after verifying the existing timing policy. A mocked JavaScript event cannot prove that Android Hybrid delivers that event; retain a device reproduction with lifecycle and request logs.

Validation status: No application reproduction, patch, Jest execution, TypeScript check, or lint run was completed. No security impact or CVSS score is supported by this report.

Contributor details
Your Expensify account email: [email protected]
Upwork Profile Link: https://www.upwork.com/freelancers/~01b60d704ba377be83

camesenin avatar Oct 28 '26 07:10 camesenin

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 28 '26 07:10 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

On Android (specifically HybridApp), after backgrounding the app or switching to another app (e.g. Gmail, Slack) for more than 1 minute, reopening the app does not refresh the Home cards (e.g. "Awaiting approval").

What is the root cause of that problem?

In src/hooks/useAppReturnCount/index.native.ts:

        const subscription = AppState.addEventListener('change', (nextAppState) => {
            if (nextAppState === 'background') {
                wasBackgroundedRef.current = true;
                return;
            }
            if (nextAppState !== 'active' || !wasBackgroundedRef.current) {
                return;
            }
            wasBackgroundedRef.current = false;
            setReturnCount((count) => count + 1);
        });
  1. PR #103996 introduced useAppReturnCount to track when the user returns to the app and trigger useTabFocusedRefresh.
  2. To prevent iOS Control Center and system permission dialogs from triggering unwanted refreshes, line 15 strictly checks if (nextAppState === 'background') before setting wasBackgroundedRef.current = true.
  3. However, on Android—and especially in HybridApp where NewDot is hosted within the native Android activity container—switching to another app (or pressing Home) pauses the host activity and transitions React Native's AppState to 'inactive'.
  4. Because wasBackgroundedRef.current is only set when nextAppState === 'background', it remains false on Android when transitioning through 'inactive'.
  5. When the user reopens the app and nextAppState returns to 'active', line 19 (if (nextAppState !== 'active' || !wasBackgroundedRef.current) return;) evaluates !wasBackgroundedRef.current to true and bails out.
  6. As a result, returnCount is never incremented, useTabFocusedRefresh never detects the app return on Android, and the Home cards never refresh.

What changes do you think we should make in order to solve the problem?

In src/hooks/useAppReturnCount/index.native.ts:

  1. Import Platform from react-native:
import {AppState, Platform} from 'react-native';
  1. On Android, treat 'inactive' as leaving the app while preserving the 'background' requirement on iOS to prevent iOS Control Center interruptions from triggering refreshes:
        const subscription = AppState.addEventListener('change', (nextAppState) => {
-           if (nextAppState === 'background') {
+           if (nextAppState === 'background' || (Platform.OS === 'android' && nextAppState === 'inactive')) {
                wasBackgroundedRef.current = true;
                return;
            }
            if (nextAppState !== 'active' || !wasBackgroundedRef.current) {
                return;
            }
            wasBackgroundedRef.current = false;
            setReturnCount((count) => count + 1);
        });

What alternative solutions did you explore? (Optional)

  • Treating inactive as leaving the app across all platforms: Explored, but this would regress iOS behavior by causing Control Center, Notification Center, or camera permission dialogs to trigger unwanted refreshes.
  • Using AppStateMonitor.addBecameActiveListener: While AppStateMonitor correctly recognizes both INACTIVE and BACKGROUND followed by ACTIVE, using it directly on iOS would re-introduce the Control Center refresh issue that PR #103996 specifically worked around. Platform-scoping the inactive check provides the correct cross-platform balance.

What automated tests can you add to prevent this from re-occurring?

In tests/unit/hooks/useAppReturnCount.test.ts, add a test case verifying that on Android, transitioning from inactive to active counts as an app return:

    it('counts a return on Android when transitioning through inactive', () => {
        // Given an Android environment
        Platform.OS = 'android';
        const {result} = renderHook(() => useAppReturnCount());

        // When switching to another app (which sets AppState to inactive) and reopening
        emitAppState('inactive');
        emitAppState('active');

        // Then that counts as one return
        expect(result.current).toBe(1);
    });

Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~01f7d7991785f2ee01

apoorv-xs avatar Oct 28 '26 07:10 apoorv-xs

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 28 '26 07:10 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

On HybridApp (iOS/Android), when the user is on the Home page, puts the Expensify app in the background while another device/session makes changes (e.g., submitting or approving an expense, adding an expense, or updating to-do items), and then reopens the Expensify app from another app, the Home cards (For you, Your spend, Recently added, etc.) do not refresh automatically.

What is the root cause of that problem?

There are two gaps when the app returns to the foreground while the user is on the Home tab:

  1. HomePage only calls openHomePage() on React Navigation screen focus (useFocusEffect), not when the app returns from the background (src/pages/home/HomePage.tsx): In src/pages/home/HomePage.tsx (lines 65–67):
    useFocusEffect(() => {
        openHomePage();
    });
    
    When the user leaves the Expensify app to another app and reopens Expensify, the React Navigation route (SCREENS.HOME) never blurs or re-focuses, so useFocusEffect does not re-run. Additionally, openHomePage() (src/libs/actions/HomePage.ts) only dispatches READ_COMMANDS.OPEN_HOME_PAGE (which refreshes data like the early renewal offer), and does not refresh the report/to-do data backing ForYouSection (useTodoCounts reads live Onyx REPORT / TRANSACTION / POLICY collections).
  2. useTabFocusedRefresh (src/hooks/useTabFocusedRefresh.ts) throttles foreground returns within APP_RETURN_REFRESH_INTERVAL_MS (60 seconds) and only runs for sections that wire useTabFocusedRefresh (YourSpendSection, RecentlyAddedSection, InsightsSection):
    • ForYouSection (src/pages/home/ForYouSection/index.tsx), UpcomingTravelSection, and HomePage (openHomePage) do not subscribe to useAppReturnCount() / useTabFocusedRefresh at all. If a Pusher event was missed while the app was backgrounded by the OS (before the 5-minute ReconnectApp inactivity threshold in src/libs/actions/Reconnect.ts), reopening the app within 5 minutes does not trigger ReconnectApp or openHomePage(), leaving ForYouSection and HomePage stale.
    • Furthermore, on HybridApp/native (src/hooks/useAppReturnCount/index.native.ts), useAppReturnCount only increments when nextAppState === 'background' is observed before 'active'. On Android/HybridApp or certain iOS transitions where the native host transitions or resumes without firing a 'background' -> 'active' sequence after the hook mounted (or when returning within APP_RETURN_REFRESH_INTERVAL_MS), the Home cards fail to refresh immediately upon reopening the app.

What changes do you think we should make in order to solve the problem?

  1. Trigger openHomePage() (and reconnect/sync Home data) when the app returns to the foreground on HomePage (src/pages/home/HomePage.tsx): Use useTabFocusedRefresh(NAVIGATION_TABS.HOME, String(isOffline), openHomePage) (or observe useAppReturnCount() in HomePage) alongside useFocusEffect so that returning to the app while HomePage is focused refreshes openHomePage() as well.
  2. Ensure foreground app returns refresh active Home sections and live Onyx data (src/libs/actions/Reconnect.ts / src/hooks/useTabFocusedRefresh.ts):
    • In src/hooks/useTabFocusedRefresh.ts (or HomePage), ensure that returning from a backgrounded app state on native/HybridApp triggers an immediate refresh of the focused tab's sections (YourSpendSection, RecentlyAddedSection, InsightsSection, and HomePage) without forcing the user to wait up to 60 seconds after reopening the app from another app, or trigger Reconnect.reconnectApp() when returning from background on native so ForYouSection (useTodoCounts) receives any report/transaction updates missed while backgrounded.

What alternative solutions did you explore? (Optional)

We also considered calling Reconnect.reconnectApp() on every AppState 'active' event in src/libs/actions/Reconnect.ts without the 5-minute CONST.NETWORK.MAX_PENDING_TIME_MS delay, but scoping the foreground refresh to useTabFocusedRefresh / openHomePage (or reducing the reconnect threshold on native background return) avoids redundant full-app reconnects on brief inactive interruptions like Control Center or notification shade pulls.

huhuli083-creator avatar Oct 28 '26 08:10 huhuli083-creator

Proposal

Please re-state the problem that we are trying to solve in this issue.

On HybridApp and mobile platforms, when the user is on the Home tab, switches to another app (such as Gmail or Slack) for more than 1 minute, and reopens Expensify, the Home cards do not refresh upon reopening.

What is the root cause of that problem?

In PR #103996, useTabFocusedRefresh was modified to prevent rapid tab refetches by introducing APP_RETURN_REFRESH_INTERVAL_MS = 60 * 1000 and scheduling deferredReturnTimerRef:

  1. In src/hooks/useTabFocusedRefresh.ts (lines 64–73), the effect gates execution solely on React Navigation focus state:
    if (!isTabFocused || !isScreenVisible || !isRefreshPendingRef.current) {
        return;
    }
    
  2. When the user sends the app to the background (or switches to another app), React Navigation's route state does not blur or change; useIsTabFocused and useIsFocused both remain true.
  3. When deferredReturnTimerRef expires while the user is still in another app (backgrounded), setDeferredReturnCount triggers the effect while the app is in the background. Because isTabFocused and isScreenVisible are true and there is no check for Visibility.isVisible(), the hook executes onRefresh() in the background and resets lastRefreshTimeRef.current = Date.now().
  4. When the user reopens Expensify, appReturnCount increments, but elapsed = Date.now() - lastRefreshTimeRef.current is only a few seconds (< 60s), so useTabFocusedRefresh treats the reopen as a rapid return within the 60-second window and defers/skips the visible refresh upon reopening.

(Note: The hypothesis that Android emits an 'inactive' AppState is incorrect; React Native's Android AppStateModule only emits 'active' and 'background'.)

What changes do you think we should make in order to solve the problem?

In src/hooks/useTabFocusedRefresh.ts:

  1. Import Visibility from @libs/Visibility:
    import Visibility from '@libs/Visibility';
    
  2. Guard the execution block so that a refresh is never consumed while the app is backgrounded (!Visibility.isVisible()). If a deferred timer expires while in the background, keep isRefreshPendingRef.current = true without firing onRefresh() or resetting lastRefreshTimeRef.current:
--- a/src/hooks/useTabFocusedRefresh.ts
+++ b/src/hooks/useTabFocusedRefresh.ts
@@ -1,6 +1,7 @@
 import {useIsFocused} from '@react-navigation/native';
 import {useEffect, useEffectEvent, useRef, useState} from 'react';
 
+import Visibility from '@libs/Visibility';
 import useAppReturnCount from './useAppReturnCount';
 import useIsTabFocused from './useIsTabFocused';
 
@@ -61,7 +62,7 @@ function useTabFocusedRefresh(tabName: string, refreshKey: string, refresh: () =
             }
         }
 
-        if (!isTabFocused || !isScreenVisible || !isRefreshPendingRef.current) {
+        if (!isTabFocused || !isScreenVisible || !Visibility.isVisible() || !isRefreshPendingRef.current) {
             return;
         }
 

When the user reopens the app from the background, Visibility.isVisible() evaluates to true, and the pending refresh executes immediately.

What alternative solutions did you explore? (Optional)

  • Listening to Visibility.onVisibilityChange directly inside useTabFocusedRefresh: Adding another event listener is redundant because useAppReturnCount already triggers re-renders on app returns, and gating Visibility.isVisible() directly at the execution condition guarantees that no background Search requests fire while the app is backgrounded.

What automated tests can you add to prevent this from re-occurring?

In tests/unit/hooks/useTabFocusedRefresh.test.ts:

  1. Add a test case where a deferred return timer fires while Visibility.isVisible() returns false: verify that onRefresh is not called and lastRefreshTimeRef is not updated.
  2. Advance the mock to Visibility.isVisible() = true on the next app return: verify that onRefresh is called immediately once upon reopening.

Contributor details

Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~015c92a110b06ee5b3

andregrunert-ctrl avatar Oct 28 '26 12:10 andregrunert-ctrl

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Oct 28 '26 12:10 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

On HybridApp (and mobile), when the user is on the Home page (with sections such as Awaiting approval in For you and Your spend / Recently added), switches to another app (e.g. Gmail or Slack) for more than 1 minute, and reopens Expensify, the Home cards do not refresh upon reopening.

What is the root cause of that problem?

There are two complementary root causes in the Home refresh flow introduced/updated in PR #103996:

  1. deferredReturnTimerRef in useTabFocusedRefresh fires while the app is in the background (src/hooks/useTabFocusedRefresh.ts:56-72):

    • In src/hooks/useTabFocusedRefresh.ts, when a quick app return happens within APP_RETURN_REFRESH_INTERVAL_MS (60_000 ms, as in QA Step 6 of PR #103996), a deferred timer is scheduled:
      } else if (!deferredReturnTimerRef.current) {
          deferredReturnTimerRef.current = setTimeout(() => {
              deferredReturnTimerRef.current = undefined;
              setDeferredReturnCount((count) => count + 1);
          }, APP_RETURN_REFRESH_INTERVAL_MS - elapsed);
      }
      
    • When the user then switches to another app (Gmail/Slack) for > 1 minute (QA Step 8), React Navigation's isTabFocused (useIsTabFocused) and isScreenVisible (useIsFocused) both remain true while the app is backgrounded.
    • Because line 64 (if (!isTabFocused || !isScreenVisible || !isRefreshPendingRef.current)) never checks Visibility.isVisible(), when deferredReturnTimerRef expires at the 60s mark while the user is still in Gmail, useTabFocusedRefresh executes onRefresh() while backgrounded and resets lastRefreshTimeRef.current = Date.now().
    • When the user reopens Expensify shortly after (QA Step 9), elapsed = Date.now() - lastRefreshTimeRef.current is < 60_000 ms, so the reopen is treated as a sub-60s return and does not refresh on reopen.
  2. HomePage only calls openHomePage() in useFocusEffect, not via useTabFocusedRefresh (src/pages/home/HomePage.tsx:59-61):

    • Look at the issue's precondition: "Submit any expenses for more than 10 minutes: so the Awaiting approval section will be displayed in Home".
    • Awaiting approval is rendered inside ForYouSection (src/pages/home/ForYouSection/index.tsx:107-118), which derives its counts from Onyx report/todo data, while src/pages/home/HomePage.tsx:59-61 only calls openHomePage() inside useFocusEffect(() => { openHomePage(); }).
    • When switching to another app and reopening Expensify after 1–3 minutes, the React Navigation screen never blurs/refocuses (so useFocusEffect does not re-run), and HomePage does not use useTabFocusedRefresh to call openHomePage() on app return.

What changes do you think we should make in order to solve the problem?

  1. In src/hooks/useTabFocusedRefresh.ts:

    • Import Visibility from @libs/Visibility.
    • Guard execution with !Visibility.isVisible() at line 64 so a pending or deferred refresh is never consumed while the app is in the background:
      import Visibility from '@libs/Visibility';
      
      if (!isTabFocused || !isScreenVisible || !Visibility.isVisible() || !isRefreshPendingRef.current) {
          return;
      }
      
      isRefreshPendingRef.current = false;
      lastRefreshTimeRef.current = Date.now();
      clearTimeout(deferredReturnTimerRef.current);
      deferredReturnTimerRef.current = undefined;
      onRefresh();
      
    • If deferredReturnTimerRef expires while the user is in another app (!Visibility.isVisible()), isRefreshPendingRef.current stays true without firing onRefresh() in the background or resetting lastRefreshTimeRef.current. As soon as the user reopens Expensify (Visibility.isVisible() === true and appReturnCount increments), onRefresh() fires once immediately.
  2. In src/pages/home/HomePage.tsx:

    • Replace (or complement) the bare useFocusEffect with useTabFocusedRefresh(NAVIGATION_TABS.HOME, String(isOffline), openHomePage) so returning to the app after > 60 seconds while on the Home tab also refreshes openHomePage() alongside YourSpendSection, RecentlyAddedSection, and InsightsSection.
  3. Unit Tests (tests/unit/hooks/useTabFocusedRefresh.test.ts):

    • Add a regression test verifying that when deferredReturnTimerRef expires while Visibility.isVisible() is false, refresh is not called in the background, and when the app subsequently returns to the foreground (Visibility.isVisible() === true), refresh fires immediately once.

What alternative solutions did you explore? (Optional)

  • Checking nextAppState === 'inactive' on Android in useAppReturnCount/index.native.ts: React Native's Android AppStateModule only emits 'active' and 'background' ('inactive' is iOS-only), so changing useAppReturnCount for 'inactive' on Android is a no-op and does not address the background timer consumption in useTabFocusedRefresh.

Enes2553 avatar Oct 28 '26 17:10 Enes2553

reviewing today

getusha avatar Nov 02 '26 12:11 getusha

@getusha Uh oh! This issue is overdue by 2 days. Don't forget to update your issues!

melvin-bot[bot] avatar Nov 05 '26 21:11 melvin-bot[bot]

Proposal

Please re-state the problem that we are trying to solve in this issue.

On HybridApp (Android and iOS), when the user is on the Home tab, switches to another app (e.g., Gmail or Slack) for more than 1 minute while changes occur on their account, and then reopens Expensify, the Home cards (For you / Awaiting approval, Your spend, Recently added) do not automatically refresh.

What is the root cause of that problem?

In PR #103996, src/hooks/useTabFocusedRefresh.ts and src/hooks/useAppReturnCount/index.native.ts were introduced to throttle background-to-foreground refreshes using APP_RETURN_REFRESH_INTERVAL_MS = 60 * 1000. Two issues prevent the refresh from firing when reopening from another app on HybridApp:

  1. In src/hooks/useTabFocusedRefresh.ts (lines 50–73), when a return or timer schedules deferredReturnTimerRef, the effect checks if (!isTabFocused || !isScreenVisible || !isRefreshPendingRef.current) return;. However, when the user switches to another OS app, React Navigation's route focus state does not change (isTabFocused and isScreenVisible remain true while the app is in the background), so deferredReturnTimerRef can fire while the app is still backgrounded and clear isRefreshPendingRef.current = false before the user returns.
  2. Furthermore, in src/pages/home/HomePage.tsx (lines 65–67), openHomePage() is only called inside useFocusEffect, which does not re-run when returning from background to an already-focused Home screen, and in src/hooks/useAppReturnCount/index.native.ts, wasBackgroundedRef.current only sets on nextAppState === 'background' (missing Android HybridApp activity pause/resume cycles that report 'inactive' or native host resume).

What changes do you think we should make in order to solve the problem?

  1. In src/hooks/useAppReturnCount/index.native.ts, set wasBackgroundedRef.current = true when nextAppState === 'background' || nextAppState === 'inactive' so Android and iOS HybridApp activity switches reliably increment returnCount when transitioning back to 'active'.
  2. In src/hooks/useTabFocusedRefresh.ts (lines 50–73), guard both immediate and deferred timer refreshes on the app currently being in the 'active' foreground state (AppState.currentState === 'active'), and in src/pages/home/HomePage.tsx invoke openHomePage() alongside the search refresh callback inside useTabFocusedRefresh so all Home cards (For you as well as search-backed spend cards) refresh on foreground return after APP_RETURN_REFRESH_INTERVAL_MS.

What alternative solutions did you explore? (Optional)

We considered adding a separate AppState.addEventListener('change', ...) listener directly inside HomePage.tsx, but fixing useAppReturnCount and useTabFocusedRefresh keeps all tab-focused foreground refresh throttling unified in one hook.

jeffrey-graham avatar Nov 07 '26 06:11 jeffrey-graham

📣 @jeffrey-graham! 📣 Hey, it seems we don’t have your contributor details yet! You'll only have to do this once, and this is how we'll hire you on Upwork. Please follow these steps:

  1. Make sure you've read and understood the contributing guidelines.
  2. Get the email address used to login to your Expensify account. If you don't already have an Expensify account, create one here. If you have multiple accounts (e.g. one for testing), please use your main account email.
  3. Get the link to your Upwork profile. It's necessary because we only pay via Upwork. You can access it by logging in, and then clicking on your name. It'll look like this. If you don't already have an account, sign up for one here.
  4. Copy the format below and paste it in a comment on this issue. Replace the placeholder text with your actual details. Screen Shot 2022-11-16 at 4 42 54 PM Format:
Contributor details
Your Expensify account email: <REPLACE EMAIL HERE>
Upwork Profile Link: <REPLACE LINK HERE>

melvin-bot[bot] avatar Nov 07 '26 06:11 melvin-bot[bot]

@MelvinBot is this highly likely an internal issue?

getusha avatar Nov 09 '26 11:11 getusha

Not yet—I wouldn’t classify this as highly likely internal. Being reported only on Hybrid Android doesn’t establish that the fault is in the native host.

The refresh throttling lives in the public App repo, as shown in Stop Home refetching on first expense loads and quick tab returns. A Hybrid lifecycle/bridge issue remains possible, but unverified.

I’d keep this External pending confirmation:

  • If Search requests run on reopen, check whether data actually changed; an unchanged screen alone doesn’t prove refresh failed.
  • If no requests run, trace the foreground event. Escalate internally if the Hybrid host fails to deliver it; otherwise investigate App’s refresh logic.

My earlier analysis was preliminary—not evidence that this requires an internal fix.


view run

MelvinBot avatar Nov 09 '26 11:11 MelvinBot

🚨 Edited by proposal-police: This proposal was edited at 2026-11-09 17:19:52 UTC.

Proposal

Please re-state the problem that we are trying to solve in this issue.

On Android HybridApp, after leaving Home for another app for more than a minute and reopening, QA expects the Home cards to "refresh once" (#103996 QA step 9) but sees nothing happen.

What is the root cause of that problem?

The cards do refresh on that reopen. The refresh has nothing visible to show, so there is no way to see it pass or fail by looking at the screen. This confirms the preliminary analysis the C+ asked about.

1. The reopen is counted. Native useAppReturnCount counts background -> active:

https://github.com/Expensify/App/blob/73dd511c2a1fa34d205fe8ca1ffef9a616f06178/src/hooks/useAppReturnCount/index.native.ts#L13-L24

2. A reopen more than 60s after the last refresh refreshes right away. elapsed is measured from the last refresh, and the time away is part of it, so after 1+ minute away it is always >= 60s:

https://github.com/Expensify/App/blob/73dd511c2a1fa34d205fe8ca1ffef9a616f06178/src/hooks/useTabFocusedRefresh.ts#L50-L72

Steps 6-7 (quick reopens) only schedule a replay timer. On Android JS timers are paused while the activity is paused, so that timer can't fire while we're in Gmail and stamp lastRefreshTimeRef. On reopen the return branch wins, refreshes, and clears the timer, so it's exactly one refresh.

3. The refresh is silent by design. Awaiting approval fires Search with isLoading: false:

https://github.com/Expensify/App/blob/73dd511c2a1fa34d205fe8ca1ffef9a616f06178/src/pages/home/YourSpendSection/useYourSpendData.ts#L578-L590

and the row only shows LOADING when it has no snapshot yet, never during a refetch:

https://github.com/Expensify/App/blob/73dd511c2a1fa34d205fe8ca1ffef9a616f06178/src/pages/home/YourSpendSection/useYourSpendData.ts#L374-L388

That's the "no loading state, the list does not jump" behavior from step 5 of the same QA. If nothing changed on the account while the phone was away, the refreshed card is pixel identical to the old one.

What the Applause video actually shows (I went through it frame by frame):

  • 00:00 - 01:01 the tester is in Gmail (status bar 11:34 -> 11:35, ~62s)
  • 01:02 - 01:03 launcher, Expensify icon tapped
  • 01:04 Home is drawn instantly (warm resume, no splash), Awaiting approval £12.80, Recently added "Bill" / "10min"
  • 01:04 - 01:07 nothing changes, and nothing was changed on another device during the recording

So the video has no signal that could show a refresh happening or not. It's the same screen either way.

Why it also "reproduces in production": before #103996 every reopen refetched every card, with the same isLoading: false path. That refresh was just as invisible, which is why production shows the "same bug".

Proof on main: I ran the exact QA sequence through the real useTabFocusedRefresh + real native useAppReturnCount (only AppState mocked, Android timer pause simulated by moving the wall clock without running timers): mount, three quick reopens (steps 6-7), then background, 150s away, active (steps 8-9). Result: 0 refreshes on the quick reopens, exactly 1 right on the reopen, 0 more over the next 2 minutes (the pending replay is cancelled). Same result when the step 6 replay already ran before leaving.

About the other root causes posted here:

  • "Android HybridApp never sends background": there's nothing in the report that shows that. Our own App coming to foreground log only fires when the previous state was background/inactive, so the tester's server logs for 10-28 answer this directly. If that line is there followed by Search, the host passes the lifecycle through and there is nothing to fix.
  • "A background refresh stamps lastRefreshTimeRef": needs something to run while away (data change or a timer). In the QA steps nothing changes while away and Android pauses the timers, so it doesn't apply here. I'm dropping the away-time change from my earlier version for that reason.
  • openHomePage / For you: the card in the steps is Your spend > Awaiting approval, which is Search-backed, not openHomePage.

What changes do you think we should make in order to solve the problem?

No change to the refresh logic. Making QA step 9 checkable and pinning the behavior so it can't regress silently:

  1. Fix #103996 QA steps 8-9 to something that can fail:
8. Keep the phone on Home and send the app to the background.
9. On web, edit an expense on an outstanding report (e.g. $10.00 -> $25.00). Wait more than 1 minute.
10. Reopen the app on the phone.
11. Verify Your spend > Awaiting approval shows the new total right after reopening, without going to another tab.

For the network check (web/dev only), verify one Search per Home card right after returning.

  1. Add the QA sequence as a regression test in a new tests/unit/hooks/useTabFocusedRefreshAppReturn.test.ts that uses the real native useAppReturnCount (only AppState mocked, same emitAppState helper as useAppReturnCount.test.ts), so both hooks are covered together:
it('refreshes exactly once when the app is reopened after quick returns and more than a minute away', () => {
    // Given Home has refreshed on mount
    const refresh = jest.fn();
    renderHook(() => useTabFocusedRefresh(SCREENS.HOME, 'key', refresh));

    // When the app is reopened a few times within seconds (QA steps 6-7)
    for (let i = 0; i < 3; i++) {
        jest.setSystemTime(Date.now() + 2000);
        emitAppState('background');
        emitAppState('active');
    }

    // Then those quick returns are skipped
    expect(refresh).toHaveBeenCalledTimes(1);

    // When it then stays in the background for over a minute with JS timers paused, as on Android, and is reopened
    emitAppState('background');
    jest.setSystemTime(Date.now() + 150 * 1000);
    emitAppState('active');

    // Then the cards refresh right on reopen
    expect(refresh).toHaveBeenCalledTimes(2);

    // And the replay scheduled by the quick returns does not refresh a second time
    act(() => jest.advanceTimersByTime(2 * 60 * 1000));
    expect(refresh).toHaveBeenCalledTimes(2);
});

This passes on main today, which is the point: it fails the moment a change breaks the one-refresh-on-reopen contract that step 9 is meant to check.

  1. If we want this verifiable on HybridApp without server logs, add one Log.info in useTabFocusedRefresh when an app return triggers a refresh (tab + elapsed). It goes to the same logs as App coming to foreground, so QA/C+ can see the refresh fired on a real Hybrid device.

What alternative solutions did you explore? (Optional)

  • Showing a loading state on every reopen so the refresh is visible. Rejected: it brings back the flash and list jump that #103996 removed on purpose.
  • Arming the return on inactive/blur on Android, or dropping the background guard there. Only makes sense if the logs show the background event is missing on Hybrid, which nothing in the report shows yet. If it does, that belongs in the Hybrid host forwarding onHostPause, so it'd be an internal fix.
  • Gating the refresh on Visibility.isVisible(). Doesn't change what QA sees, since nothing refreshes in the background in these steps.

David-2002065 avatar Nov 09 '26 11:11 David-2002065

Proposal

Please re-state the problem that we are trying to solve in this issue.

On the Android HybridApp, the Home cards (Your spend / Awaiting approval, Recently added, Insights) are supposed to refresh once when the user reopens the app after being away for more than a minute. They do not: the app resumes straight onto a fully drawn Home screen built from cached data, no loading state ever appears, and no refresh is fired — no matter how long the user was away.

What is the root cause of that problem?

The Home sections refresh through useTabFocusedRefresh, whose only "the user came back to the app" signal is the counter returned by useAppReturnCount. The native implementation of that counter only counts a return after it has first seen an AppState change event with the literal state background, and then a change to active:

https://github.com/Expensify/App/blob/06496858b8d684d045b270024ab39ad35036a857/src/hooks/useAppReturnCount/index.native.ts#L13-L24

The "require a real background first" guard exists for iOS, where Control Center, the app switcher and permission dialogs produce inactive → active pairs that must not count as returns.

On Android, React Native's AppState has no inactive state at all. It emits exactly two change events, both driven by the host forwarding activity lifecycle callbacks to the React instance: host resume emits active and host pause emits background (see onHostResume/onHostPause in React Native's AppStateModule). In the HybridApp the Android activity lifecycle is owned by the OldDot host, and when the app is backgrounded from a NewDot screen the pause side never reaches this listener as a background change event. The resume side demonstrably does reach React Native — after reopening, the app resumes normally (rendering and JS timers resume, and host resume emits an active change event unconditionally). The listener therefore receives active while wasBackgroundedRef is still false, bails out at the guard on line 19, and returnCount stays at 0 forever on Android HybridApp.

A missing background event is otherwise invisible — nothing user-facing depends on it — which is why only this feature breaks. With the counter frozen, the app-return branch of useTabFocusedRefresh never runs:

https://github.com/Expensify/App/blob/06496858b8d684d045b270024ab39ad35036a857/src/hooks/useTabFocusedRefresh.ts#L50-L62

And nothing else can fire the refresh in this scenario either: React Native pauses JS timers while the app is backgrounded on Android, so the 60-second window logic never gets a signal to act on. The result is exactly what the Applause video shows — a warm resume (no splash, so no remount refresh) directly onto stale cards with no refresh at any point.

This also matches the platform split in the report: iOS delivers the background state through its own application lifecycle wiring and web uses visibilitychange (the non-native useAppReturnCount), so both refresh correctly; only Android HybridApp is affected.

What changes do you think we should make in order to solve the problem?

In src/hooks/useAppReturnCount/index.native.ts, stop relying solely on the change → background event to arm the return marker. On Android, additionally subscribe to the AppState blur event — the Android-only window-focus-lost event that React Native delivers through a separate host callback (onWindowFocusChange) — and set the same wasBackgroundedRef flag when it fires. The counting logic stays exactly as it is: a return is still only counted when a change event to active arrives afterwards.

This channel is proven to be delivered in the HybridApp: the soft-keyboard helper for Android already depends on AppState focus/blur and works in the HybridApp today:

https://github.com/Expensify/App/blob/06496858b8d684d045b270024ab39ad35036a857/src/libs/isWindowReadyToFocus/index.android.ts#L6-L17

This change is safe against false positives. An Android dialog or share sheet that merely steals window focus fires blur and arms the flag, but it never pauses and resumes the host activity, so no active change event follows and nothing is counted — the flag simply waits until a real background-and-return happens, which is precisely when it should count. On a standalone Android build, blur and background both fire on a real backgrounding, so arming twice changes nothing. iOS is untouched: iOS never emits blur (the listener is only added on Android), so the Control Center protection introduced by PR #103996 is preserved exactly.

For regression coverage, extend the existing unit test for the native useAppReturnCount: on Android a blur followed by a change to active counts one return, a blur on its own counts none, and a blur plus background before active still counts once; on iOS no blur listener is added, so an inactive → active pair still counts none.

Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/105231-arm-app-return-on-window-blur?expand=1

What alternative solutions did you explore? (Optional)

Counting every change → active event as a return, without any arming flag. Rejected: on iOS this re-introduces exactly the over-refresh that the guard was built to prevent (Control Center, app switcher and permission dialogs all end in an active change), and it would also count any host-side re-emit of active that is not a real return from another app.

Fixing the lifecycle forwarding in the Mobile-Expensify host so that the pause event reaches the React instance as a background change. That addresses the same gap at its source, but it is a native change in the closed host application with a much wider blast radius (host lifecycle forwarding also controls timer and rendering suspension), and it cannot be carried in this repository.

wildan-m avatar Nov 09 '26 11:11 wildan-m