Skip to content

Open reports at first unread action#51366

Open
janicduplessis wants to merge 273 commits intoExpensify:mainfrom
janicduplessis:@janic/open-at-new
Open

Open reports at first unread action#51366
janicduplessis wants to merge 273 commits intoExpensify:mainfrom
janicduplessis:@janic/open-at-new

Conversation

@janicduplessis
Copy link
Copy Markdown
Contributor

@janicduplessis janicduplessis commented Oct 23, 2024

Details

Implements opening reports at the last unread message. This builds on top of #52149 to be able to start our list at any item. This removes a few assumptions that open report will always open at the newest action.

Fixed Issues

$ #35011
PROPOSAL:

Tests

  • Verify that no errors appear in the JS console
  • Test the scenarios described in the QA steps

Offline tests

QA Steps

  • Verify that no errors appear in the JS console
  • Using 2 accounts in the same chat test the following scenarios:
  1. With account A send 30+ messages, with account B open the chat. It should open at the last unread message and load more messages once scrolled at the bottom.
  2. With account A send 20 new messages, with account B open the chat. It should open at the last unread message and all messages should be loaded already.
  3. With account A send 1 new message, with account B open the chat. It should open at the last unread message and all messages should be loaded already.

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
    • MacOS: Desktop
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I verified there are no new alerts related to the canBeMissing param for useOnyx
  • I followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text shown in the product is localized by adding it to src/languages/* files and using the translation method
      • If any non-english text was added/modified, I verified the translation was requested/reviewed in #expensify-open-source and it was approved by an internal Expensify engineer. Link to Slack message:
    • I verified all numbers, amounts, dates and phone numbers shown in the product are using the localization methods
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
    • I verified proper file naming conventions were followed for any new files or renamed files. All non-platform specific files are named after what they export and are not named "index.js". All platform-specific files are named for the platform the code supports as outlined in the README.
    • I verified the JSDocs style guidelines (in STYLE.md) were followed
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I followed the guidelines as stated in the Review Guidelines
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • I verified all code is DRY (the PR doesn't include any logic written more than once, with the exception of tests)
  • I verified any variables that can be defined as constants (ie. in CONST.js or at the top of the file that uses the constant) are defined as such
  • I verified that if a function's arguments changed that all usages have also been updated correctly
  • If any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG))
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If a new page is added, I verified it's using the ScrollView component to make it scrollable when more elements are added to the page.
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Screen.Recording.2025-01-27.at.23.42.32.mov
Android: mWeb Chrome
Screen.Recording.2025-01-27.at.23.37.31.mov
iOS: Native
Screen.Recording.2025-01-27.at.22.56.37.mov
iOS: mWeb Safari
Screen.Recording.2025-01-27.at.23.02.45.mov
MacOS: Chrome / Safari
Screen.Recording.2025-01-27.at.22.33.19.mov
MacOS: Desktop
Screen.Recording.2025-01-27.at.23.32.32.mov

@janicduplessis
Copy link
Copy Markdown
Contributor Author

I have a UX question here, where do we want the scroll of the list to open at? Currently it opens the chat where the new message is aligned at the bottom so like this:

image

But it could also be aligned at the top so we see more new messages instead of old ones, like this:

image

@janicduplessis janicduplessis force-pushed the @janic/open-at-new branch 2 times, most recently from b88cba8 to 13de5ad Compare January 28, 2025 17:26
@rlinoz rlinoz requested review from a team and removed request for a team January 28, 2025 17:34
@rlinoz
Copy link
Copy Markdown
Contributor

rlinoz commented Jan 28, 2025

Oh I guess I am not sure how to assign someone from the @Expensify/design team to the PR, but I think they can help with your question #51366 (comment)

@shawnborton
Copy link
Copy Markdown
Contributor

But it could also be aligned at the top so we see more new messages instead of old ones, like this:

I personally like this, but I think I would prefer to let an older message slightly peak out from above so there is a little more context that you are starting from a certain point. So basically what you have but maybe push down the starting point by like 56px or 64px or something like that.

@dannymcclain
Copy link
Copy Markdown
Contributor

Yeah I like that too Shawn!

@dubielzyk-expensify
Copy link
Copy Markdown
Contributor

+1 to that. Always like it when we peek content to show that there's more there

@ikevin127
Copy link
Copy Markdown
Contributor

ikevin127 commented Feb 2, 2025

@janicduplessis First of all, props for picking up this veteran difficulty level issue, doing such great work on it so far and getting it so close to completion 🚀

👋 Please tag me before merging this in case I don't get notified because I'd like to run some tests myself to make sure this works as expected, I have 2 scenarios in mind:

  • opening a report for the first time on fresh login, with 300-500 unread new messages
  • opening a report for the first time on fresh login where the last read message was deleted in the meantime

Note: I'm one of the contributors which attempted to fix this from FE only but ultimately figured out it won't work and suggested a BE + FE implementation discussion months ago before Rory went on parental leave.

How did I get here ? Another C+ reviewer asked just yesterday about an issue on Slack, which will basically be fixed by this PR - that's how I remembered this 1 year old issue and decided to join the testing effort as well since I have some context on this.

Note: No compensation needed, just want to help 👍

@janicduplessis janicduplessis force-pushed the @janic/open-at-new branch 4 times, most recently from cb8fd25 to 4a9ef9f Compare February 22, 2025 19:44
@janicduplessis janicduplessis marked this pull request as ready for review February 22, 2025 19:44
@janicduplessis janicduplessis requested a review from a team as a code owner February 22, 2025 19:44
@melvin-bot melvin-bot Bot requested review from ishpaul777 and removed request for a team February 22, 2025 19:44
@melvin-bot
Copy link
Copy Markdown

melvin-bot Bot commented Feb 22, 2025

@ishpaul777 Please copy/paste the Reviewer Checklist from here into a new comment on this PR and complete it. If you have the K2 extension, you can simply click: [this button]

@janicduplessis
Copy link
Copy Markdown
Contributor Author

This is ready for review and further testing. Sadly adjusting the scroll position so the newest message is near the top ended up very difficult with the way we handle opening the list in the middle of a chat. I think we should punt that for later since this is already taking longer than I would have liked.

Comment on lines +655 to +658
// This scrolls the unread action at the top of the screen.
viewPosition: 1,
// This makes sure that the unread indicator doesn't get cut off.
viewOffset: -64,
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sadly adjusting the scroll position so the newest message is near the top ended up very difficult with the way we handle opening the list in the middle of a chat.

how is this relevant if the last unread message is show at the bottom not the top?

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From Flatlist's scrollToIndex() docs:

Scrolls to the item at the specified index such that it is positioned in the viewable area such that viewPosition 0 places it at the top, 1 at the bottom, and 0.5 centered in the middle.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This is actually not needed anymore.

@ishpaul777
Copy link
Copy Markdown
Contributor

Did the first pass of testing on the web desktop, and it work really well no issues spotted so far, Great Work @janicduplessis 🥇

Screen.Recording.2025-02-26.at.12.54.52.AM-1.mov

I'll test more and update back soon... @janicduplessis we have some conflicts can you please resolve them

@chrispader
Copy link
Copy Markdown
Contributor

chrispader commented Apr 23, 2026

@rlinoz i'm currently investigating whether we can achieve this feature with the new FlashList implementation. Basically, lots of the logic we needed for FlatList just became obsolete, because maintainVisibleContentPostion and initialScrollIndex work better with FlashList, so this works already.

@github-actions
Copy link
Copy Markdown
Contributor

🚧 @rlinoz has triggered a test Expensify/App build. You can view the workflow run here.

@github-actions
Copy link
Copy Markdown
Contributor

🚧 @rlinoz has triggered a test Expensify/App build. You can view the workflow run here.

@chrispader
Copy link
Copy Markdown
Contributor

Detailed Code Review

This is a large, complex PR touching pagination, scroll positioning, and mark-as-read logic across 28 files. Below are the findings organized by severity.

Bugs

1. In-place mutation of Onyx-cached array (Pagination.ts:144-147) The firstPage.shift() call mutates the Onyx cache directly. existingPages is a reference from pagesCollections[pageKey], and .at(0) returns a reference to the same array. This violates Onyx's immutability contract and can cause missed re-renders and stale state. Additionally, this is redundant with lines 152-153, which already strip PAGINATION_START_ID from all existing pages under the same response.hasNewerActions === true condition.

Valid comment. This is redundant and also in-place mutations are bad. Fixed this!

2. oldestUnreadReportActionIndex is in the wrong index domain (usePaginatedReportActions.ts:95-100) resourceItem.index comes from getContinuousChain, which uses sortedAllReportActions (full, unfiltered). This index flows into unreadMarkerReportActionIndex and eventually reaches useReportUnreadMessageScrollTracking.ts:115, where it's compared against FlatList viewable item indexes. But the FlatList data source is sortedVisibleReportActions — a different, smaller array. The fallback path via getUnreadMarkerReportAction correctly uses visibleReportActions indices, but the new oldestUnreadReportActionMarker path (ReportActionsList.tsx:324) uses the wrong domain. This could cause the floating message counter to show/hide at incorrect scroll positions.

Also valid. Weird this didn't cause any issues with the rendering logic so far 🤔 Fixed!

3. Refs not reset on report navigation (ReportActionsView.tsx:400, ReportActionsList.tsx:465) isReportUnreadInitially and didMarkReportAsReadInitially are useRefs set once and never reset when reportID changes. If ReportActionsView/ReportActionsList is reused for a different report (e.g., route param change without unmount), switching to an unread report won't trigger the initial mark-as-read, and the skeleton guard could behave incorrectly. Similarly, isListInitiallyLoaded state (line 454) is never reset.

Addressed!

4. setTimeout leak in scroll useEffect (useFlatListScrollKey.ts:128-141) The useEffect calls setTimeout for INITIAL_SCROLL_DELAY but never returns a cleanup function. If the component unmounts or the effect re-fires before the 200ms elapses, the callback will still execute, potentially calling renderQueue.start() on a stale/cancelled queue.

Outdated, i removed this hook because it's no longer needed with FlashList

5. Race condition between Onyx prune and pagination anchor reset (ReportActionsList.tsx:924) In onLayoutInner during await_prune, pruneReportActionPagesToNewestWindow writes to Onyx (async), then setTreatAsNoPaginationAnchor(false) fires synchronously. The next render of usePaginatedReportActions will use old (unread-anchored) pages because the Onyx write hasn't committed yet, potentially snapping the view back to the unread position.

I don't think this edge-case has ever happened so far. Agree that this might be a race condition, but fixing it would mean that we have to await the promise from Onyx.set in the action, which is disregarded as per https://github.com/Expensify/App/blob/main/contributingGuides/philosophies/DATA-BINDING.md#--action-methods-should-not-return-a-promise.

@rlinoz do you think we should handle this or simply ignore? The potential result would not be critical anyway. We can fix if this ever occurs.

Concerns

6. Double-timeout race in RenderTaskQueue (RenderTaskQueue.tsx:30-35, 50-53) renderWithDelay() does not set isRendering = true. So between calling start() (or add()) and the 500ms timeout firing, isRendering remains false, allowing a second add() or start() to schedule another timeout chain. This creates two concurrent render loops.

Outdated, we don't need the changes in RenderTaskQueue anymore.

7. isUnreadMessagePageLoadingInitially can cause permanent skeleton (ReportActionsView.tsx:409) If a report is unread but usePaginatedReportActions cannot find any action with created > lastReadTime (e.g., actions deleted, or lastReadTime stale), oldestUnreadReportAction stays undefined forever, shouldWaitForOpenReportResultInitially stays true, and the skeleton is shown indefinitely. A fallback (e.g., release after hasOnceLoadedReportActions becomes true) is needed.

Addressed!

8. Live tail jump state machine has no timeout/escape hatch (ReportActionsList.tsx:406) If openReport fails or isLoadingInitialReportActions never transitions, the machine stays in open_report forever, swallowing new-message scroll events. Additionally, await_scrollawait_prune transitions when hasNewestReportAction becomes true, but the scroll hasn't actually happened yet — just been requested via setIsScrollToBottomEnabled(true). If onLayoutInner doesn't fire, the machine gets stuck.

Also going to ignore this until this really becomes a problem. Implementing an escape hatch would mean to add an alternative timeout, after which the OpenReport response would be disregarded, which is not very elegant either way.

9. as unknown as double-cast in Pagination.ts:130-140 The comment says tooling resolves @libs/PaginationUtils as untyped, but these functions are already properly typed generics. The as unknown as pattern completely bypasses TypeScript's type system. If signatures diverge, TS won't catch it. The underlying tooling issue should be fixed instead.

Addressed!

10. renderQueue.setHandler() called every render outside useEffect (useFlatListScrollKey.ts:143-155) This is a side effect during render. The handler closure captures render-time values. Under React concurrent mode, this could behave unpredictably. Consider using useEffectEvent for the handler.

This needs to run during render, because it affects the initial render. Moving this to an effect wouldn't work.

11. treatAsNoPaginationAnchor silently discards reportActionID (usePaginatedReportActions.ts:52-58) When treatAsNoPaginationAnchor is true, even an explicit reportActionID is ignored. But linkedAction (line 93) still uses reportActionID, creating an inconsistency where linkedAction could reference an action outside the paginated window.

Addressed!

12. No unit tests for new PaginationUtils functions mergePagesByIDOverlap, prunePagesToNewestWindow, and selectNewestPageWithIndex are critical new functions with zero test coverage.

Added tests for these functions

Nits

13. Commented-out console.log left in code (ReportActionsView.tsx:413)

// console.log({isLinkedMessageLoading: isLinkedMessagePageLoading, ...});

Variable names in the comment don't even match the current names — stale from a rename.

Removed.

14. getFirstAndLastIndexForPage backward loop is unnecessarily complex (PaginationUtils.ts:215-221) The loop scans backwards but effectively only checks the last element. A simple if (page.at(-1) === CONST.PAGINATION_END_ID) would be clearer.

Addressed.

15. useEffect dependency array includes ref objects (useFlatListScrollKey.ts:141) isMessageOnFirstPage and listRef are useRef objects — stable across renders, so they have no effect in the dependency array.

Outdated, this code has been removed.

@chrispader
Copy link
Copy Markdown
Contributor

@rlinoz i've detected one minor issue with recent changes that i still need to fix. Other than that, we're good to go

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

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[$1000] Jump to last unread chat when opening a report