Skip to content

Fix duplicate expense navigation arrows showing inverted state on first open#83753

Draft
MelvinBot wants to merge 1 commit intomainfrom
claude-fixDuplicateExpenseArrowSequence
Draft

Fix duplicate expense navigation arrows showing inverted state on first open#83753
MelvinBot wants to merge 1 commit intomainfrom
claude-fixDuplicateExpenseArrowSequence

Conversation

@MelvinBot
Copy link
Contributor

Explanation of Change

When opening a duplicate expense from the "Review duplicates" screen, the navigation arrows (left/right) showed inverted state on the first open but correct state on the second open. This was caused by a race condition between two callers of setActiveTransactionIDs:

  1. Review.tsx's onPreviewPressed sets the IDs to the duplicate-sorted order
  2. MoneyRequestReportTransactionList's useEffect fires when visualOrderTransactionIDs gets a new reference (due to navigation-triggered re-renders) and overwrites the IDs with the parent report's visual sort order

This fix adds a guard to the useEffect in MoneyRequestReportTransactionList.tsx to skip setting active transaction IDs when the SEARCH_REPORT was opened from the duplicate review context (detected via the backTo route param). This matches the existing isFromReviewDuplicates pattern already used in MoneyRequestHeader.tsx.

Fixed Issues

$ #83751
PROPOSAL: #83751 (comment)

Tests

  1. Go to staging.new.expensify.com
  2. Go to workspace chat
  3. Create two expenses with the same amount
  4. Open the report
  5. Click Review duplicates
  6. Click on the second expense preview
  7. Verify the left arrow is enabled and the right arrow is disabled (since this is the last expense)
  8. Close the report RHP
  9. Click on the second expense preview again
  10. Verify the arrow state is the same as step 7
  • Verify that no errors appear in the JS console

Offline tests

N/A - This change only affects navigation state during UI interaction and does not involve network requests.

QA Steps

  1. Go to a workspace chat
  2. Create two expenses with the same amount
  3. Open the report
  4. Click Review duplicates
  5. Click on the second expense preview
  6. Verify the left arrow is enabled and the right arrow is disabled
  7. Close the report RHP
  8. Click on the second expense preview again
  9. Verify the arrow state is the same as step 6 (left enabled, right disabled)
  • Verify that no errors appear in the JS console

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
  • 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 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 used JaimeGPT to get English > Spanish translation. I then posted it 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.ts 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
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari

…st open

When opening a duplicate expense from the Review Duplicates screen,
MoneyRequestReportTransactionList's useEffect was racing with
Review.tsx's onPreviewPressed, overwriting the active transaction IDs
with the parent report's visual order. This caused the left/right
navigation arrows to show inverted state on the first open.

Skip setting active transaction IDs when the SEARCH_REPORT was opened
from the duplicate review context (backTo ends with /duplicates/review),
matching the existing isFromReviewDuplicates pattern in MoneyRequestHeader.

Co-authored-by: Chavda Sachin <ChavdaSachin@users.noreply.github.com>
@MelvinBot MelvinBot requested a review from a team February 27, 2026 19:45
@MelvinBot
Copy link
Contributor Author

I created this PR from an upstream branch since I don't have push access to your fork.

To take ownership of this branch and be able to push updates, run:

git remote add upstream https://github.com/Expensify/App.git
git fetch upstream claude-fixDuplicateExpenseArrowSequence
git checkout -b claude-fixDuplicateExpenseArrowSequence upstream/claude-fixDuplicateExpenseArrowSequence
git push -u origin claude-fixDuplicateExpenseArrowSequence

Then you can close this PR and open a new one from your fork.

@ChavdaSachin
Copy link
Contributor

@MelvinBot current PR approach is not good enough,

I have two candidate approaches here, please analyze and do not make changes to the code yet.

Option 1 - As MoneyRequestReportTransactionList.tsx is already taking care of setting the active IDs, how about avoiding race condition by removing the setActiveTransactionIDs from review.tsx.

Option 2 - In Review.tsx sort siblingTransactionIDsList before passing it to setActiveTransactionIDs, the sorting logic should be similar to MoneyRequestReportTransactionList.tsx, and hence the array passed to the setActiveTransactionIDs is exactly same from both call sites.

@MelvinBot
Copy link
Contributor Author

Thanks for the feedback ChavdaSachin. Here's a detailed analysis of both options:


Analysis of Option 1 — Remove setActiveTransactionIDs from Review.tsx

Verdict: This would break the duplicate review UX.

The two call sites operate on fundamentally different transaction sets:

Review.tsx MoneyRequestReportTransactionList.tsx
Transaction set Duplicate sibling transactions (from DUPLICATED_TRANSACTION violation data) All transactions on the report
Purpose Navigate prev/next through duplicate siblings Navigate prev/next through report expenses

When a user taps a duplicate in Review.tsx, onPreviewPressed builds siblingTransactionIDsList from the current transaction + its duplicates (sourced from violation data at Review.tsx:54-65), then navigates to SEARCH_REPORT. If we removed this call, MoneyRequestReportTransactionList's useEffect would set the active IDs to the report's full transaction list — the prev/next arrows would then cycle through all report expenses instead of through the duplicate siblings, which is incorrect behavior.

Additionally, Review.tsx has a restore mechanism (Review.tsx:71-97) — it saves the pre-existing transactionIDsList on first click and restores it via useFocusEffect when navigating back. Removing the setActiveTransactionIDs call would also break this restoration logic.


Analysis of Option 2 — Sort siblingTransactionIDsList in Review.tsx with the same logic as MoneyRequestReportTransactionList.tsx

Verdict: This doesn't solve the problem because the transaction sets differ, not just the sort order.

Even if Review.tsx used the same compareValues() sort logic from MoneyRequestReportTransactionList.tsx, the two callers would still produce different ID arrays for three reasons:

  1. Different transaction sets: Review.tsx has duplicate sibling IDs (e.g., [txn_A, txn_B] — two duplicates), while MoneyRequestReportTransactionList has the full report's transaction IDs (e.g., [txn_A, txn_B, txn_C, txn_D]). Since the arrays have different elements, the idempotency check in setActiveTransactionIDs would still detect a mismatch and overwrite.

  2. Grouping: MoneyRequestReportTransactionList can group transactions by category/tag (sorted alphabetically via sortGroupedTransactions in ReportLayoutUtils.ts:13-22), further reordering IDs. Review.tsx has no grouping concept.

  3. User-configurable sort column: MoneyRequestReportTransactionList lets users sort by merchant, category, tag, amount, or description — not just date. Even if you aligned the default date sort, a user who previously sorted by amount would still get a different order.


Why the current PR approach (guard in useEffect) is the right direction

The core issue is that these two callers serve different navigation contexts:

  • Review.tsx → "navigate between duplicate siblings"
  • MoneyRequestReportTransactionList → "navigate between report expenses"

A guard that prevents one from overwriting the other is the architecturally correct solution. The backTo URL check in the current PR accurately detects the duplicate review context.

That said, if there are concerns about the fragility of URL string matching (backTo?.replaceAll(/\?.*/g, '').endsWith('/duplicates/review')), one alternative refinement could be using a more explicit signal — for example, passing a boolean flag through route params or using a context/ref that Review.tsx sets before navigation to indicate "I've already set the active IDs, don't overwrite."

@ChavdaSachin
Copy link
Contributor

@MelvinBot do you have any other ideas here?
Remember do not change code without my explicit instructions.

@codecov
Copy link

codecov bot commented Feb 27, 2026

Codecov Report

❌ Looks like you've decreased code coverage for some files. Please write tests to increase, or at least maintain, the existing level of code coverage. See our documentation here for how to interpret this table.

Files with missing lines Coverage Δ
...stReportView/MoneyRequestReportTransactionList.tsx 1.31% <0.00%> (-0.02%) ⬇️
... and 10 files with indirect coverage changes

@MelvinBot
Copy link
Contributor Author

Here are some alternative ideas, beyond the two options we already analyzed and the current PR's URL guard approach:


Idea 1 — Source-aware setActiveTransactionIDs (Recommended)

Add a source parameter to setActiveTransactionIDs in TransactionThreadNavigation.ts. Track the source in a module-level variable alongside the existing lastSetIDs. The rule: a 'reportList' write cannot overwrite a 'reviewDuplicates' write.

let lastSetIDs: string[] | null = null;
let lastSource: string | null = null;

function setActiveTransactionIDs(ids: string[], source: 'reportList' | 'reviewDuplicates' | 'searchList' = 'reportList') {
    if (lastSource === 'reviewDuplicates' && source === 'reportList') {
        return Promise.resolve();
    }
    if (lastSetIDs?.length === ids.length && lastSetIDs.every((id, i) => id === ids.at(i))) {
        return Promise.resolve();
    }
    lastSetIDs = ids;
    lastSource = source;
    return Onyx.set(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS, ids);
}

function clearActiveTransactionIDs() {
    lastSetIDs = null;
    lastSource = null;
    return Onyx.set(ONYXKEYS.TRANSACTION_THREAD_NAVIGATION_TRANSACTION_IDS, null);
}

Then Review.tsx passes 'reviewDuplicates' as the source, and MoneyRequestReportTransactionList uses the default 'reportList'. The existing clearActiveTransactionIDs (called via cleanup effects when navigating away) naturally resets the lock.

Pros:

  • Centralizes conflict resolution in the one module responsible for the state
  • No URL string matching, no route param changes, no Onyx type changes
  • All existing callers are unaffected (default source is 'reportList')
  • Easy to reason about and extend to future callers
  • TransactionGroupListExpanded.tsx (another caller using the same set-then-navigate pattern at line 111-120) would also work without changes

Cons:

  • Module-level state only works within the same JS runtime (fine for React Native)

Idea 2 — Separate Onyx key for duplicate review context

Create ONYXKEYS.DUPLICATE_REVIEW_TRANSACTION_IDS. Review.tsx writes to this new key. MoneyRequestReportTransactionsNavigation (the consumer at line 36-37) reads both keys and prefers the duplicate key when non-null.

Pros: Eliminates the race entirely — the two contexts write to different keys.
Cons: More Onyx plumbing — new key, new cleanup logic, navigation component must merge/prioritize two sources.


Idea 3 — Conditional write: only set IDs if Onyx key is empty

Change the useEffect in MoneyRequestReportTransactionList to read the current Onyx value first (via useOnyx) and skip the write if IDs already exist.

Pros: Simple, minimal change.
Cons: Fragile — would prevent the useEffect from updating IDs when visualOrderTransactionIDs legitimately changes (e.g., a transaction is deleted while viewing). Also depends on cleanup ordering between components. I'd consider this weaker than the other two.


My recommendation

Idea 1 (source-aware setActiveTransactionIDs) is the cleanest approach. It solves the race condition at the right level of abstraction — the module that owns the state — without URL parsing, route param changes, or additional Onyx keys. The change is small (one module + one call site passes a source string), and the clearActiveTransactionIDs call already handles resetting when navigating away.

Let me know which direction you'd like to go and I'll implement it.

@mountiny
Copy link
Contributor

I would prefer not to rely on the routes/ backTo

@ChavdaSachin
Copy link
Contributor

Idea 2 — Separate Onyx key for duplicate review context
Create ONYXKEYS.DUPLICATE_REVIEW_TRANSACTION_IDS. Review.tsx writes to this new key. MoneyRequestReportTransactionsNavigation (the consumer at line 36-37) reads both keys and prefers the duplicate key when non-null.

Pros: Eliminates the race entirely — the two contexts write to different keys.
Cons: More Onyx plumbing — new key, new cleanup logic, navigation component must merge/prioritize two sources.

This one makes the most sense to me.

@mountiny should I prepare CP using this idea?

@ChavdaSachin
Copy link
Contributor

Also could we add "help wanted" label back, in case someone has a better idea.

@mountiny
Copy link
Contributor

I might have one from Claude

@mountiny
Copy link
Contributor

@ChavdaSachin let me know what you think #83772

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants