Skip to content

[$250] Reports - Back button on report view returns to different scroll position #70080

Open

Description

@jponikarchuk

If you haven’t already, check out our contributing guidelines for onboarding and email contributors@expensify.com to request to join our Slack channel!


Version Number: 9.2.2-0
Reproducible in staging?: Yes
Reproducible in production?: No
If this was caught during regression testing, add the test name, ID and link from TestRail: #69128
Email or phone of affected tester (no customers): applausetester+khcategory19@applause.expensifail.com
Issue reported by: Applause Internal Team
Device used: Mac 15.5 / Chrome
App Component: Search

Action Performed:

Precondition:

  • Account has more than 50 reports.
  1. Go to staging.new.expensify.com
  2. Go to Reports > Reports.
  3. Scroll down to the last report (or report that is after 50th report).
  4. Click on the expense report.
  5. Click app back button.

Expected Result:

App will return to the same scroll position.

Actual Result:

Scroll position is not reset, but app returns to a different scroll position. User will have to scroll down to find the same report.
It seems that app scrolls back to the first 50th reports.

Workaround:

Unknown

Platforms:

  • Android: App
  • Android: mWeb Chrome
  • iOS: App
  • iOS: mWeb Safari
  • iOS: mWeb Chrome
  • Windows: Chrome
  • MacOS: Chrome / Safari
  • MacOS: Desktop

Screenshots/Videos

1.mp4

View all open jobs on GitHub

Upwork Automation - Do Not Edit
  • Upwork Job URL: https://www.upwork.com/jobs/~021965145771047289052
  • Upwork Job ID: 1965145771047289052
  • Last Price Increase: 2026-11-26
Issue OwnerCurrent Issue Owner: @
Issue OwnerCurrent Issue Owner: @eVoloshchak

Activity

  1. added
    DeployBlockerCash
    Bug
    on Sep 8, 2025
  2. melvin-bot commented on Sep 8, 2025

    @melvin-bot

    Triggered auto assignment to @strepanier03 (Bug), see https://stackoverflow.com/c/expensify/questions/14418 for more details. Please add this bug to a GH project, as outlined in the SO.

  3. melvin-bot commented on Sep 8, 2025

    @melvin-bot

    Triggered auto assignment to @chiragsalian (DeployBlockerCash), see https://stackoverflowteams.com/c/expensify/questions/9980/ for more details.

  4. melvin-bot commented on Sep 8, 2025

    @melvin-bot

    💬 A slack conversation has been started in #expensify-open-source

  5. github-actions commented on Sep 8, 2025

    @github-actions
    Contributor

    👋 Friendly reminder that deploy blockers are time-sensitive ⏱ issues! Check out the open `StagingDeployCash` deploy checklist to see the list of PRs included in this release, then work quickly to do one of the following:

    1. Identify the pull request that introduced this issue and revert it.
    2. Find someone who can quickly fix the issue.
    3. Fix the issue yourself.
  6. chiragsalian commented on Sep 8, 2025

    @chiragsalian
    Contributor

    Hmm, i cant reproduce this. I have an account with a very large number of reports. I scrolled a lot, clicked on the expense report, when i click back it takes a while to load but the scroll position was exactly the same as before i clicked the expense report. Asking for a retest.

  7. chiragsalian commented on Sep 8, 2025

    @chiragsalian
    Contributor

    Doesn't feel blocker worthy, demoting and applying external label for it.

  8. removed
    DeployBlockerCash
    on Sep 8, 2025
  9. 357 remaining items

  10. added 7 commits that reference this issue on Nov 23, 2026
    892ad75
    24de6ab
    2cc7580
    ed52e7c
    bb77037
    3468bd8
    770a966
  11. Morganshi2026 commented on Nov 23, 2026

    @Morganshi2026

    Follow-up to my proposal from Nov 16 on this issue - this is not a new proposal.

    On the question @eVoloshchak asked on Nov 17 (are we safe to close this?) - the defect is still live in main.

    I re-checked the three mechanisms in the report against main @ d75ece45 (2026-11-23). All three are unchanged since the report was filed:

    1. src/components/Search/primitives/useScrollRestoration.ts still restores a pixel offset, in a single requestAnimationFrame, with scrollToOffset. The Search list is server-paginated, so on that frame the list holds only the first page (CONST.SEARCH.RESULTS_PAGE_SIZE = 50). An offset that was reachable on the full list is not reachable there, so the list clamps it to its own maximum.
    2. src/pages/Search/SearchPageWide.tsx still calls saveScrollOffset(route, e.nativeEvent.contentOffset.y) on every scroll event, so the clamped value overwrites the position the user actually left on.
    3. src/components/ScrollOffsetContextProvider.tsx still keeps the row index and the pixel offset in the same map slot (scrollOffsetsRef.current[getKey(route)]), so saving one destroys the other.

    The reproduction is the one @eVoloshchak pointed the KI retest at, and @Burapa-J's before/after video in this thread shows the same jump (scrollTop 6049 -> 2803, the bottom of page 1). The code path that produces the clamped position is unchanged, so closing this would drop a defect that is still in the product.

    The proposal from Nov 16 is ready for review.

    It restores by row index instead of by pixel offset: the list reports its first viewable row, that row is stored next to the offset, and on a back-navigation the restore waits until that row is in the list and lands on it. That is what @chiragsalian asked for on Sep 18 - the report that was clicked on should be shown in view - rather than a pixel position that a shorter list cannot honour. A position that does not reach the restore target is not stored, so the clamped position can no longer replace the real one.

    The implementation is on a compare branch (7 files, 2 of them new unit tests):

    main...Morganshi2026:fix/70080-report-list-scroll-restoration

    The branch is a review branch: its base is a few days older than main, but the change itself applies cleanly to the current main (all seven patches verified with git apply --check against main @ d75ece45). The pull request will be opened with the change re-applied to the current main.

    One note on the checks: they were run against copies of the upstream modules with the upstream imports replaced by faithful stubs, because this machine cannot clone the repository. The upstream jest, lint and typecheck runs are left to the upstream CI.

    Could the Nov 16 proposal get a C+ review and an assignment? I will open the pull request as soon as the issue is assigned to me.

  12. github-actions commented on Nov 23, 2026

    @github-actions
    Contributor

    ⚠️ @Morganshi2026 Thanks for your proposal. Please update it to follow the proposal template, as proposals are only reviewed if they follow that format (note the mandatory sections).

  13. expensify-chore-bot commented on Nov 24, 2026

    @expensify-chore-bot

    @eVoloshchak Still overdue 6 days?! Let's take care of this!

  14. melvin-bot commented on Nov 26, 2026

    @melvin-bot

    📣 It's been a week! Do we have any satisfactory proposals yet? Do we need to adjust the bounty for this issue? 💸

  15. expensify-chore-bot commented on Nov 26, 2026

    @expensify-chore-bot

    @eVoloshchak Now this issue is 8 days overdue. Are you sure this should be a Daily? Feel free to change it!

  16. mvtglobally commented on Nov 28, 2026

    @mvtglobally

    Issue not reproducible during KI retests. (Fifth week).

  17. expensify-chore-bot commented on Nov 30, 2026

    @expensify-chore-bot

    @eVoloshchak 12 days overdue. Walking. Toward. The. Light...

  18. dostonbunyodov0006 commented on Dec 1, 2026

    @dostonbunyodov0006
    Contributor

    Proposal

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

    With more than one page of reports in Reports > Reports, I scroll past the 50th report, open one and go back. The list should be where I left it, but it ends up near the bottom of the first page and I have to scroll down again to find the report.

    What is the root cause of that problem?

    The plain open/back flow passes KI retests because the report opens in the RHP and Search stays mounted under it, so the list keeps its rows and its scroll position. The bug shows up when something refreshes Search from page 1 while the RHP is open, like the Submit flow in the steps mukhrr posted here.

    What happens in that flow:

    1. Submit calls refreshSearchAfterReportAction, which always searches with offset: 0. It runs even when submitReport stops at the billing guard and opens the Restricted panel.

    refreshSearchAfterReportAction({
    currentSearchQueryJSON,
    currentSearchKey,
    shouldCalculateTotals,
    isOffline,
    isLoading: !!currentSearchResults?.search?.isLoading,
    shouldReturnTripRooms,
    });

    function refreshSearchAfterReportAction({currentSearchQueryJSON, currentSearchKey, shouldCalculateTotals, isOffline, isLoading, shouldReturnTripRooms}: RefreshSearchParams) {
    if (!currentSearchQueryJSON || isOffline) {
    return;
    }
    search({
    searchKey: currentSearchKey,
    shouldCalculateTotals,
    offset: 0,
    queryJSON: currentSearchQueryJSON,
    isLoading,
    shouldReturnTripRooms,
    });
    }

    1. The page-1 response replaces the snapshot, so 150 rows become 50 in a list that is still mounted. The browser clamps scrollTop to the bottom of page 1 (mukhrr measured 6049 -> 2803 in the recording linked above) and fires a scroll event. The page wrapper saves every scroll event, so the clamped 2803 overwrites the real offset:

    const scrollHandler = (e: NativeSyntheticEvent<NativeScrollEvent>) => {
    if (!e.nativeEvent.contentOffset.y) {
    return;
    }
    saveScrollOffset(route, e.nativeEvent.contentOffset.y);
    };

    When the Restricted panel gets focus, cleanStaleScrollOffsets goes to its last line and deletes the Search key completely, because RestrictedAction_Root is not one of the three report screens it keeps:

    const cleanStaleScrollOffsets: ScrollOffsetContextValue['cleanStaleScrollOffsets'] = (state) => {
    const sidebarRoutes = state.routes.filter((route) => isSidebarScreenName(route.name));
    const existingScreenKeys = new Set(sidebarRoutes.map(getKey));
    const focusedRoute = findFocusedRoute(state);
    const routeName = focusedRoute?.name;
    const isSearchScreen = routeName === SCREENS.SEARCH.ROOT;
    const isSearchMoneyRequestReport =
    routeName === SCREENS.RIGHT_MODAL.EXPENSE_REPORT || routeName === SCREENS.RIGHT_MODAL.SEARCH_MONEY_REQUEST_REPORT || routeName === SCREENS.RIGHT_MODAL.SEARCH_REPORT;
    const scrollOffsetKeys = Object.keys(scrollOffsetsRef.current);
    if (isSearchScreen || isSearchMoneyRequestReport) {
    const currentKey = focusedRoute ? getKey(focusedRoute) : null;
    cleanScrollOffsets(scrollOffsetKeys, (key) => key.startsWith(SCREENS.SEARCH.ROOT) && key !== currentKey && !isSearchMoneyRequestReport);
    return;
    }
    cleanScrollOffsets(scrollOffsetKeys, (key) => !existingScreenKeys.has(key));
    };

    1. When we go back, useScrollRestoration reads that context value. By then it is either 2803 or undefined, so it puts the list at the bottom of page 1 or doesn't move it at all. Retrying the restore later doesn't help, because the value it would retry is already wrong:

    useFocusEffect(
    useCallback(() => {
    const offset = getScrollOffset(route);
    requestAnimationFrame(() => {
    if (!offset || !listRef.current) {
    return;
    }
    listRef.current.scrollToOffset({offset, animated: false});
    });
    }, [getScrollOffset, route, listRef]),
    );

    1. The recovery from [cp stag & prod] Derive the next Search page from the snapshot cursor #100144 sees serverOffset (0) < offset (100) and wants page 3 back. Its comment says "The list has not moved", which is no longer true once the list has clamped:

    useEffect(() => {
    const serverOffset = shouldUseLiveData ? answeredLiveOffset : (searchResults?.search?.offset ?? 0);
    // A first-page response that lands after the page it displaces drags the cursor back below the page we
    // hold, after that page's arrival already cleared the intent. The list has not moved, so arm it again.
    // Live rows stay in Onyx through that, so there is nothing to fetch again.
    if (!shouldUseLiveData && wantedOffsetRef.current === undefined && searchResults?.search?.hasMoreResults && serverOffset < offset) {
    wantedOffsetRef.current = offset;
    }

    It can't run under the RHP, because fetchMoreResults returns early when !isFocused:

    if (!isFocused || shouldShowLoadingState) {
    return;
    }

    After focus comes back it fetches page 2, but it lowers both the target and offset to 50. Nothing asks for page 3 after that:

    // the cap can outrun the cursor, and pulling the cursor up to it would skip server pages for good
    wantedOffsetRef.current = nextOffset;
    // Offline, the request would only fail and leave an error on the snapshot. Hold the page until reconnect.
    if (isLoadingMorePage || isOffline) {
    return;
    }
    // Dispatched here rather than left to the offset effect: after a first-page response `nextOffset` can
    // equal the offset we already hold, and that effect only runs on a change. search() dedupes the pair.
    setOffset(nextOffset);

    So the real problem is that the position we restore is read from a shared store after the list has already been changed under it, and that store has no reliable copy of the position anymore. The one moment we know the right position is when Search loses focus: the RHP has just opened and nothing has touched the list yet. The hook doesn't keep that value.

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

    Two small changes. ScrollOffsetContextProvider, the page scroll handlers and the refresh callers stay as they are.

    1. useScrollRestoration: remember where the list was when Search lost focus, and restore that once the rows are back.

    • In the useFocusEffect cleanup (it runs on blur), read the offset from the list itself (getAbsoluteLastScrollOffset(), already used in useSearchListViewState) and the row count.
    • On focus, use that value first and fall back to the context value. The context is still used when Search remounts, because the ref is empty then.
    • If fewer rows are loaded than at blur, don't scroll yet. Scroll once when the row count is back, unless the user scrolled in the meantime.
    -import {useCallback, useContext} from 'react';
    +import {useCallback, useContext, useEffect, useRef} from 'react';
    +
    +type ListPosition = {offset: number; rowCount: number};
     
    -function useScrollRestoration<TItem>(listRef: RefObject<FlashListRef<TItem> | null>) {
    +function useScrollRestoration<TItem>(listRef: RefObject<FlashListRef<TItem> | null>, rowCount: number) {
         const route = useRoute();
         const {getScrollOffset} = useContext(ScrollOffsetContext);
    +    const rowCountRef = useRef(rowCount);
    +    // Search stays mounted under the RHP. A first-page refresh that lands there shrinks the list, clamps the scroll and
    +    // saves the clamped value (or the key gets cleaned up), so the position read on blur is the only one we can trust.
    +    const positionAtBlurRef = useRef<ListPosition | undefined>(undefined);
    +    // Set when we come back before the dropped rows are loaded again. Applied once they are.
    +    const pendingRef = useRef<(ListPosition & {startOffset: number}) | undefined>(undefined);
     
         useFocusEffect(
             useCallback(() => {
    -            const offset = getScrollOffset(route);
    +            const positionAtBlur = positionAtBlurRef.current;
    +            positionAtBlurRef.current = undefined;
    +            const offset = positionAtBlur?.offset ?? getScrollOffset(route);
                 requestAnimationFrame(() => {
                     if (!offset || !listRef.current) {
                         return;
                     }
     
    +                if (positionAtBlur && rowCountRef.current < positionAtBlur.rowCount) {
    +                    pendingRef.current = {...positionAtBlur, startOffset: listRef.current.getAbsoluteLastScrollOffset()};
    +                    return;
    +                }
    +
                     listRef.current.scrollToOffset({offset, animated: false});
                 });
    +
    +            return () => {
    +                const list = listRef.current;
    +                positionAtBlurRef.current = pendingRef.current ?? (list ? {offset: list.getAbsoluteLastScrollOffset(), rowCount: rowCountRef.current} : undefined);
    +                pendingRef.current = undefined;
    +            };
             }, [getScrollOffset, route, listRef]),
         );
    +
    +    useEffect(() => {
    +        rowCountRef.current = rowCount;
    +        const pending = pendingRef.current;
    +        const list = listRef.current;
    +        if (!pending || !list || rowCount < pending.rowCount) {
    +            return;
    +        }
    +        pendingRef.current = undefined;
    +        // The user scrolled while the rows were loading, so leave them where they are.
    +        if (Math.abs(list.getAbsoluteLastScrollOffset() - pending.startOffset) > 1) {
    +            return;
    +        }
    +        list.scrollToOffset({offset: pending.offset, animated: false});
    +    }, [rowCount, listRef]);
     }

    and the only call site:

    useScrollRestoration(listRef);

    -    useScrollRestoration(listRef);
    +    useScrollRestoration(listRef, data.length);

    2. fetchMoreResults: let the displaced-page recovery run under the RHP and stop it from lowering its own target. The Math.max part is the same idea ocakciomursel-pixel, cocvn157, aswadi and 0xmiroslav already pointed out, and I'm reusing it here. Without it, step 1 would wait for page 3 forever.

    -        if (!isFocused || shouldShowLoadingState) {
    +        // Search stays mounted under the RHP, so it can reload the pages a first-page refresh dropped before the user comes back
    +        const isRecoveringUnderRHP = !shouldUseLiveData && wantedOffsetRef.current !== undefined && isSearchTopmostFullScreenRoute();
    +        if ((!isFocused && !isRecoveringUnderRHP) || shouldShowLoadingState) {
                 return;
             }
     ...
    -        wantedOffsetRef.current = nextOffset;
    +        // recovery goes back one page at a time, so never lower the page it is going back to
    +        wantedOffsetRef.current = Math.max(wantedOffsetRef.current ?? 0, nextOffset);
     ...
    -        setOffset(nextOffset);
    +        setOffset((previousOffset) => Math.max(previousOffset, nextOffset));

    isSearchTopmostFullScreenRoute is already imported in this file, and useSearchAutoRefetch uses the same check to keep refreshing under the RHP.

    What happens in the repro flow with this:

    • RHP opens: the blur cleanup stores {offset: 6049, rowCount: 150}.
    • Page-1 refresh lands: the list clamps and the context gets 2803 or loses the key. We don't read the context anymore in this case, so it doesn't matter.
    • The recovery reloads pages 2 and 3 while the RHP is still open.
    • Back: 150 rows are loaded, so we scroll to 6049 on the first frame. If the user is faster than the network, the scroll waits until the rows arrive and then happens once. It doesn't jump step by step, and it doesn't pull the user back if they scrolled on their own.

    Other callers and why they don't break

    • useScrollRestoration has one caller, useSearchListViewState. The six views that use that hook (ExpenseReportSearchView, ExpenseFlatSearchView, ExpenseGroupedSearchView, ChatSearchView, TaskSearchView, TripSearchView) don't change. Grouped views pass data.length, which counts groups. That is the same unit before and after, so the comparison still holds.
    • Normal open/back: the list never changed, so the offset saved on blur is the current one and the scroll does nothing, same as today.
    • Leaving the Spend tab for Inbox: the tab uses freezeOnBlur without unmounting (L968-L971), so the frozen list keeps its scroll anyway. We restore the same value the list already shows.
    • Search remounts (query change, <Search key={hash}>, cold start): the ref is empty, so we use getScrollOffset(route) exactly as today.
    • fetchMoreResults callers are onEndReached and the recovery effect. While focused, onEndReached is unchanged, and Math.max does nothing when paging forward because nextOffset is always above the current offset. Live to-do data is excluded from the new blurred path, so useLiveRowLimit paging is unchanged.
    • ScrollOffsetContextProvider, SearchPageWide / SearchPageNarrow scroll handlers and LHN restore are not touched, so Inbox, Settings and Workspace offsets behave as before.

    Tests

    • New tests/unit/Search/useScrollRestorationTest.tsx (mocked useFocusEffect that keeps the cleanup, fake list ref):
      • blur at 6049 with 150 rows, context returns 2803, focus with 150 rows -> scrollToOffset(6049)
      • focus with 50 rows -> no scroll; rerender with 100 -> no scroll; rerender with 150 -> one scrollToOffset(6049)
      • same as above, but getAbsoluteLastScrollOffset changes before the rows come back -> no scroll
      • fresh mount with no blur -> uses the context offset, same as today
    • tests/ui/SearchPageTest.tsx, next to "re-requests the paginated page after a first-page response replaces the loaded results":
      • load 3 pages, set page 1 again -> requests offset 50, then after page 2 merges, offset 100 (fails on main, which stops at 50)
      • same with useIsFocused false and isSearchTopmostFullScreenRoute true -> recovery requests still go out
    • Existing ExpenseReportSearchViewTest, ExpenseFlatSearchViewTest, ExpenseGroupedSearchViewTest, ChatSearchViewTest, TaskSearchViewTest and SearchPageTest should pass unchanged.
    • Manual (web wide, mWeb, desktop):
      1. mukhrr's repro steps linked above: scroll to around row 94, open the Draft, More > Submit > Submit anyway, close the Restricted panel, press back -> list is at the same row.
      2. Same, but press back right away, before the refresh finishes -> list lands on the row once pages come back, with one jump.
      3. Same as 2, but scroll up while the rows load -> list stays where the user scrolled.
      4. Plain open/back past row 50 -> no change from today.
      5. Spend -> Inbox -> Spend, and changing the query -> no change from today.

    I haven't run this yet. The diff above is written against bd19e411 and still needs to be tried in the app with an account that has more than 100 reports.

    What alternative solutions did you explore? (Optional)

    • Keep the saved context offset pending and retry it (franklincg, mukhrr, Burapa-J and others): in this flow the context value is already 2803 or gone, so the retry has nothing correct to retry. Reading the list on blur gets the right value without changing how the provider saves or cleans up.
    • Ignore scroll saves while blurred and keep Search keys in cleanStaleScrollOffsets (darkodixit, cocvn157, aswadi): that works, but it touches the shared provider (also used by LHN and Settings) and both page scroll handlers. Fixing it in the one hook that does the restore is smaller.
    • Only refresh after a real submit (ocakciomursel-pixel, EazyHood): this removes one trigger, but a real submit, pay or useSearchAutoRefetch refresh still drops pages the same way. It's still a good change on its own.
    • Keep the old rows or skeletons on screen during recovery (ocakciomursel-pixel, aswadi, 0xmiroslav): this avoids the clamp, but it renders stale or placeholder rows and changes what Search shows. Under the RHP nobody sees the clamp, so restoring the position on return is enough.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

BugDailyEngineeringExternalHelp WantedOverdueretest-weekly

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions