App icon indicating copy to clipboard operation
App copied to clipboard

[$250] [Exploratory] Expense - Creating receipt expense with two receipts displays Not Here page

Open applause-bot[bot] opened this issue 2 months ago • 47 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.4.72-0 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://test-management.browserstack.com/projects/2219752/test-runs/72250955/folder/54281512/41237700/1723618117 Email or phone of affected tester (no customers): [email protected] Issue reported by: Applause Internal Team Bug source: Exploratory - Significant User Experience Deterioration Device used: Web, android App Component: Money Requests

Action Performed:

Preconditions: Use expensifail account

  1. Go to staging.new.expensify.com
  2. Create a receipt expense with two receipts.
  3. Open the expense.

Expected Result:

Not Here page should not appear.

Actual Result:

Not Here page appears.

Workaround:

Unknown

Platforms:

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

Screenshots/Videos

https://github.com/user-attachments/assets/17a3b3a5-ecc4-4444-937f-0b56118d907a

View all open jobs on GitHub

Applause Internal Information Exported by: Mita Rachim Bug ID: 7250729

Issue OwnerCurrent Issue Owner: @mkhutornyi
Upwork Automation - Do Not Edit

applause-bot[bot] avatar Sep 04 '26 03:09 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/c5ec4db8bab078aa2f6170ee079f779b0fb515ff4c09fc13564c960694e83ad3

applause-bot[bot] avatar Sep 04 '26 03:09 applause-bot[bot]

Proposal

What is the root cause of that problem?

Scan expenses are created without transaction threads. When there is only one expense, opening it side-steps threads entirely — so the bug can't happen. With two, the app has to mint a transaction thread on the client at press time and navigate to it, and that route has no protection against a report the server doesn't know about yet. The not-found guard fires, and you get "Hmm… it's not here".

The chain, with the 1-vs-2 fork in the middle:

  1. Scan submission hardcodes shouldGenerateTransactionThreadReport = false, so every new expense has iouAction.childReportID === undefined.
  2. The fork. MoneyRequestReportPreview/index.tsx:360-363 short-circuits to the expense report when transactions.length <= 1. One receipt → always opens a report that exists. Two receipts → falls through to the thread path. The same fork exists inside the expense report: the transaction table only renders for multi-transaction reports, and it is the only caller of useNavigateToTransactionThread.
  3. Because childReportID is undefined, the app calls createTransactionThreadReport, which generates a client-side report ID and navigates to search/view/<clientGeneratedID>.
  4. That thread's parentReportActionID is the still-optimistic IOU action of a brand-new scan expense. The guard at TransactionNavigationUtils.ts:62 renders not-found as soon as the parent report's actions report themselves loaded but that action isn't resolvable. Crucially, the isPendingCreation grace period that exists for exactly this situation is scoped to SCREENS.REPORT only — the RHP thread route gets no such protection.

There is a second, unconditional defect on the same path worth fixing regardless: in useNavigateToTransactionThread, if createTransactionThreadReport returns undefined (it can) there is no else branch, so routeParams.reportID stays undefined and the app navigates to the literal string search/view/undefined, which isValidReportIDFromPath rejects outright — instant not-found, no loading state, no recovery.

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

  1. Never navigate to an unresolved thread. In useNavigateToTransactionThread, when thread creation returns nothing, fall back to opening the expense report instead of pushing search/view/undefined. This is what MoneyRequestReportPreview already does via its openReportFromPreview() fallback — the hook is just missing it.
  2. Extend the pending-creation grace period to the thread route. Thread the isPendingCreation signal through ROUTES.SEARCH_REPORT and stop scoping it to SCREENS.REPORT at ReportNotFoundGuard.tsx:61, so a just-minted thread whose parent IOU action is still optimistic shows the loading state rather than flipping to not-found.

Option 1 alone removes the hard failure; option 2 removes the race. I'd do both.

What alternative solutions did you explore? (Optional)

Alternatives considered, and how I'd confirm which branch actually fired

Alternative A — create transaction threads optimistically for scan expenses (flip shouldGenerateTransactionThreadReport to true). This removes the press-time mint entirely, so childReportID is always populated. Rejected as the primary fix: the flag is false in three separate submit paths, so it looks deliberate (likely a payload-size/perf decision), and flipping it changes behaviour for every scan expense rather than fixing the broken navigation.

Alternative B — a second asapSubmit-only defect. With the asapSubmit beta, shouldCreateNewMoneyRequestReport forces a new expense report per scan, while the submit loop reuses one optimisticReportPreviewActionID across both iterations. Two client reports end up sharing one preview action ID. I could not prove this from static reading alone, but it would produce the same symptom and is worth a look while fixing the above.

Confirming which branch fired. The code logs enough to settle this from a single repro. Look for, in order:

  • Invalid reportID is used to build the SEARCH_REPORT route and Cannot build transaction thread report without a valid report → confirms the search/view/undefined variant.
  • [ReportScreen] Displaying NotFound Page → its payload includes reportIDFromPath, isLoadingInitialReportActions and isPendingCreation, which distinguishes an invalid path from a thread whose parent action never resolved.

Verification status. This is code evidence only. I tried to reproduce it on web, but the browser test harness has no way to attach files to the receipt upload input, so neither the two-receipt repro nor the one-receipt control could be created. Note also that the reported version (9.4.72) predates a significant refactor of this area; line references above are against e029fad. The 1-vs-2 fork and the missing else branch are both still present at HEAD.

Related issues. I scanned open App issues for "Not Here" + receipt/scan/multi-scan phrasings and found no duplicate.


Next Steps for Contributor+ team: To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/100368) to create a draft PR. To refine: @MelvinBot <your feedback> To reject: Explain why you are rejecting Melvin's proposal.


view run · no recording available

MelvinBot avatar Sep 24 '26 04:09 MelvinBot

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

melvin-bot[bot] avatar Sep 24 '26 04:09 melvin-bot[bot]

Unable to auto-create job on Upwork. The BZ team member should create it manually for this issue.

melvin-bot[bot] avatar Sep 24 '26 04:09 melvin-bot[bot]

Melvin proposal doesn't work

🆘 C+ Help Wanted

marufsharifi avatar Sep 26 '26 06:09 marufsharifi

Proposal

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

When a user creates a receipt expense by attaching/scanning two receipts at once (instead of just one), opening the resulting expense afterwards shows the "Not Here" page instead of the expense. Creating an expense with a single receipt works fine; it's specifically the two-receipt (multi-scan) case that breaks.

What is the root cause of that problem?

Scanning multiple receipts in one go builds one optimistic draft transaction per file: the first file reuses the placeholder transaction that was allocated when the Scan screen was opened, and every additional file gets a brand-new transaction created on the spot. https://github.com/Expensify/App/blob/e029fad955164435583153ee7f862942711273cb/src/pages/iou/request/step/IOURequestStepScan/utils/buildReceiptFiles.ts#L61-L75

Whether a given index reuses the placeholder or gets a new transaction is decided here — note index !== 0 unconditionally forces a new transaction for every receipt after the first: https://github.com/Expensify/App/blob/e029fad955164435583153ee7f862942711273cb/src/libs/TransactionUtils/index.ts#L3702-L3722

So after scanning two receipts, buildReceiptFiles/submitMultiScan end up with two different transactionIDs, and this array is passed into navigateGlobalCreate(transactionIDs, isMultiScanEnabled). That function correctly loops over the whole array to attach the resolved report/participants to every transaction that was just created: https://github.com/Expensify/App/blob/e029fad955164435583153ee7f862942711273cb/src/pages/iou/request/step/IOURequestStepScan/components/NavigateGlobalCreateContext.tsx#L111-L128

But when it actually navigates to the confirmation screen, it ignores that same transactionIDs array and instead uses transactionID — a single value captured from the component's original props (the very first placeholder ID), not from the batch that was just built/updated: https://github.com/Expensify/App/blob/e029fad955164435583153ee7f862942711273cb/src/pages/iou/request/step/IOURequestStepScan/components/NavigateGlobalCreateContext.tsx#L117 https://github.com/Expensify/App/blob/e029fad955164435583153ee7f862942711273cb/src/pages/iou/request/step/IOURequestStepScan/components/NavigateGlobalCreateContext.tsx#L119 https://github.com/Expensify/App/blob/e029fad955164435583153ee7f862942711273cb/src/pages/iou/request/step/IOURequestStepScan/components/NavigateGlobalCreateContext.tsx#L131 https://github.com/Expensify/App/blob/e029fad955164435583153ee7f862942711273cb/src/pages/iou/request/step/IOURequestStepScan/components/NavigateGlobalCreateContext.tsx#L135

The exact same pattern exists in the report-scoped scan entry point: navigateFromReport receives fileTransactionIDs (the real, freshly created IDs) and correctly uses the whole array to assign participants, but then navigates using the outer transactionID prop instead: https://github.com/Expensify/App/blob/e029fad955164435583153ee7f862942711273cb/src/pages/iou/request/step/IOURequestStepScan/components/ScanFromReport.tsx#L59-L64

For a single receipt this is harmless, because the lone transaction always reuses the placeholder, so transactionID and the "real" ID are the same value. For two (or more) receipts, the second transaction is a distinct entity that the navigation code never actually targets or accounts for — the function signature was updated to accept the full batch (transactionIDs: string[]) so participants/report data would be correct for every scanned receipt, but the navigation call sites were never updated to match, so they still act as if there's only ever one transaction.

Downstream, when the user opens one of these expenses, its receipt is shown through TransactionReceiptModalContent, which decides whether to render the literal "Not Here" state by comparing the report used to reach the screen against the report actually stored on the transaction: https://github.com/Expensify/App/blob/e029fad955164435583153ee7f862942711273cb/src/pages/media/AttachmentModalScreen/routes/TransactionReceiptModalContent.tsx#L266-L271

That shouldShowNotFoundPage flag is what drives the "Not Here" title shown to the user: https://github.com/Expensify/App/blob/e029fad955164435583153ee7f862942711273cb/src/pages/media/AttachmentModalScreen/AttachmentModalBaseContent/index.tsx#L374-L383

Because the confirmation flow never tracked the two transactions created for the two receipts as a consistent set (it collapsed them back down to a single stale transactionID at the navigation step), the report/transaction pairing that downstream screens rely on for one of the two resulting expenses doesn't line up, and this check fails, producing the "Not Here" page reported here.

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

The fix is to stop discarding the transactionIDs/fileTransactionIDs array at the navigation step and make the navigation call sites use the same batch that the loops right above them already operate on, instead of the stale, closure-captured transactionID.

In NavigateGlobalCreateContext.tsx: https://github.com/Expensify/App/blob/e029fad955164435583153ee7f862942711273cb/src/pages/iou/request/step/IOURequestStepScan/components/NavigateGlobalCreateContext.tsx#L97-L137

Replace each of the four transactionID references used for navigation (lines 117, 119, 131, 135) with the corresponding entry from the transactionIDs parameter that was just iterated over, e.g.:

const navigationTransactionID = transactionIDs.at(0) ?? transactionID;

and use navigationTransactionID in place of transactionID in the four Navigation.navigate(...) / navigateToConfirmationPage(...) / navigateToParticipantPage(...) calls in this function. This keeps single-receipt behavior unchanged (where transactionIDs.at(0) is always the reused placeholder) while making the multi-receipt case navigate to a transaction that was actually created and configured by the loops above.

In ScanFromReport.tsx: https://github.com/Expensify/App/blob/e029fad955164435583153ee7f862942711273cb/src/pages/iou/request/step/IOURequestStepScan/components/ScanFromReport.tsx#L59-L64

Apply the same fix — use fileTransactionIDs.at(0) ?? transactionID instead of the bare transactionID when calling navigateToConfirmationPage.

This reuses the arrays the code already builds (no new helpers needed) and makes the navigation logic consistent with the participant/report-assignment loops that already treat transactionIDs/fileTransactionIDs as the source of truth for "which transactions were just created in this batch."

abbasifaizan70 avatar Sep 26 '26 06:09 abbasifaizan70

Proposal

What is the root cause of that problem?

A report preview is the card shown in the parent chat for an expense report. Its action ID is also stored as the expense report’s parentReportActionID, so each independent expense report must have its own preview action ID.

During multi-scan submission, the app generates one optimisticReportPreviewActionID before entering the receipt loop and passes that same ID to every receipt https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/pages/iou/request/step/confirmation/useExpenseSubmission.ts#L480-L548

Sharing that ID is correct when all receipts are added to the same expense report: every receipt should update the same preview.

However, the builder may decide that the next receipt requires a new expense report. shouldCreateNewMoneyRequestReport returns true when:

  • the existing report is pending deletion;
  • the existing report cannot accept another transaction;
  • an IOU is waiting for the user’s bank account;
  • an ASAP Submit smart scan must have its own report.

These conditions are defined in https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/ReportUtils.ts#L12072-L12091

This is why the reported flow requires the asapSubmit beta. Without the beta, the second scanned receipt normally joins the first receipt's report, so sharing the preview ID is correct. With the beta, each smart scan is forced into a new report, but the preview ID was still shared as if both receipts belonged to one report.

When the report is split, MoneyRequestBuilder correctly creates another expense report, but it still passes the batch’s original preview ID to buildOptimisticReportPreview https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/actions/IOU/MoneyRequestBuilder.ts#L1677-L1696

This produces an invalid relationship:

Expense report A ─┐
                  ├── same preview action ID
Expense report B ─┘

Report actions are stored by their action ID https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/actions/IOU/MoneyRequestBuilder.ts#L627-L646 Therefore, the second preview overwrites the first instead of creating an independent preview.

In the reproduced case:

  • The client created reports 6205596215078666 and 890087559465102.
  • Both RequestMoney calls sent preview ID 492316971273331559.
  • The user opened /e/890087559465102.
  • The second response marked 890087559465102 as an optimistic duplicate of 6205596215078666.
  • The reconciliation code removed report 890087559465102 and its parent preview https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/actions/replaceOptimisticReportWithActualReport.ts#L81-L87
  • Because both reports shared that preview ID, cleanup also removed the preview now associated with the surviving report.
  • The URL still referenced the removed report, so the expense page found no report or transactions and displayed “Not Here” through its existing access-error condition https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/pages/Search/SearchMoneyRequestReportPage.tsx#L336-L385

The logs prove that the shared preview ID caused the two reports to overwrite and clean up the same client-side action. They do not prove why the server returned preexistingReportID; that may depend on whether ASAP Submit is also enabled server-side. The fix does not need to make an assumption about that server decision: independent reports must have independent preview IDs in either case.

The problem was introduced by the interaction of two changes:

  • #63848 reused action IDs during bulk expense creation.
  • #64390 allowed ASAP smart scans to create separate reports.

Reusing the chat CREATED action ID remains necessary. The missing case is specifically regenerating the preview ID when the builder splits an expense into a different report.

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

Resolve the preview action ID inside MoneyRequestBuilder, immediately after calculating shouldCreateNewMoneyRequestReport.

If the builder rejects the report supplied by the previous iteration, generate a fresh preview ID. If the next receipt joins that report, reuse the ID already stored in its parentReportActionID. This is important because the report-action cache may not contain previews created earlier in the same loop yet.

const reportPreviewActionID = shouldCreateNewMoneyRequestReport
  ? existingIOUReport
    ? rand64()
    : optimisticReportPreviewActionID
  : (existingIOUReport?.parentReportActionID ??
    optimisticReportPreviewActionID);

Pass this resolved ID to buildOptimisticReportPreview.

The resulting behavior is:

Situation Preview behavior
First expense creates report A Use the caller-provided preview X
Another expense joins report A Reuse report A'sparentReportActionID (X)
Another expense is split into report B Generate an independent preview Y
A later expense joins the newly created report B Reuse report B'sparentReportActionID (Y)

The decision belongs in MoneyRequestBuilder because that is where the app already determines whether the selected report can be used. This covers every report-splitting condition without duplicating those rules in the multi-scan UI.

It also follows the existing bulk-duplicate pattern, which generates a new preview ID whenever an expense is split into another report https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/actions/IOU/Duplicate.ts#L1341-L1394

Do not regenerate optimisticCreatedReportActionID. That ID belongs to the containing chat’s CREATED action. Each expense report already receives a separate CREATED action internally https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/ReportUtils.ts#L9686-L9693

The following cases should be verified:

  • two ASAP Submit smart scans;
  • normal multi-scan where both expenses remain in one report;
  • a report split because canAddTransaction returns false;
  • three receipts where receipt 2 splits into a new report and receipt 3 joins it;
  • three receipts where every receipt is split into a separate report;
  • offline submission and later reconciliation;
  • partial or out-of-order responses;
  • submission to a newly created P2P chat, ensuring only one chat CREATED action appears.

Manual verification with the proposed change confirmed that split reports received different preview IDs and the “Not Here” error no longer appeared.

What alternative solutions did you explore? (Optional)

  1. Regenerate the preview ID in the multi-scan loop

    This would require duplicating the report-splitting rules outside the builder. An ASAP-only condition would also miss pending-deletion, bank-account, and canAddTransaction splits.

  2. Generate a new preview ID for every receipt

    This would create multiple previews when several receipts correctly belong to one report. Those receipts should update a single preview.

  3. Generate both the preview ID and CREATED action ID per receipt

    The chat CREATED action ID is intentionally shared. Regenerating it could restore duplicate CREATED rows when bulk-creating expenses in a new chat.

  4. Redirect or delay the “Not Here” page during reconciliation

    This would hide the visible result but leave two independent reports sharing one action identity. Cleanup could still overwrite or remove the wrong preview. There is also a broader case where reconciliation deletes a legitimately merged report while it is open without redirecting to preexistingReportID; that should be handled separately rather than expanding this fix.

  5. Change transaction-thread navigation or its not-found guard

    The reproduced URL was /e/<reportID>, and the expense-page logs showed that the report referenced by that route had been removed. No transaction-thread route was involved.

  6. Prevent the server from combining the optimistic reports

    Server reconciliation is authoritative and may differ when ASAP Submit is forced only through a local client override. Whether the final reports should remain separate must be confirmed independently; it is not necessary to fix the client-side preview-ID collision.

nabi-ebrahimi avatar Sep 26 '26 06:09 nabi-ebrahimi

Proposal

What is the root cause of that problem?

Submitting several receipts at once mints a single optimisticReportPreviewActionID before the loop starts, and hands that one ID to every receipt:

https://github.com/Expensify/App/blob/c134a8df49ca39dce693b81084cf0e58354c0821/src/pages/iou/request/step/confirmation/useExpenseSubmission.ts#L483-L488

That is deliberate for the ordinary case. Each later receipt joins the report the previous one created, so reusing the ID keeps updating one preview card instead of stacking a card per receipt. The loop feeds the report forward for exactly that reason:

https://github.com/Expensify/App/blob/c134a8df49ca39dce693b81084cf0e58354c0821/src/pages/iou/request/step/confirmation/useExpenseSubmission.ts#L615-L621

The assumption breaks when a receipt cannot join that report. shouldCreateNewMoneyRequestReport forces a separate expense report per scan under ASAP Submit, and also whenever the previous report stops accepting transactions:

https://github.com/Expensify/App/blob/c134a8df49ca39dce693b81084cf0e58354c0821/src/libs/ReportUtils.ts#L12076-L12096

Both receipts then reach buildOptimisticReportPreview with the same supplied ID, so both previews are written to the chat under one reportActionID and the second overwrites the first:

https://github.com/Expensify/App/blob/c134a8df49ca39dce693b81084cf0e58354c0821/src/libs/actions/IOU/MoneyRequestBuilder.ts#L1674-L1688

The ID does not stay local either. It is what the request sends as reportPreviewReportActionID, so the server sees the collision too:

https://github.com/Expensify/App/blob/c134a8df49ca39dce693b81084cf0e58354c0821/src/libs/actions/IOU/TrackExpense.ts#L1947

What I watched happen with two receipts on a workspace chat:

  • Two RequestMoney calls went out carrying the identical reportPreviewReportActionID 2605693961172736906, with iouReportID 8333712557575768 on the first and 3540756868666091 on the second.
  • Both came back jsonCode 200, and both wrote that one preview key with childReportID 8333712557575768. The second report got no preview of its own, and the first finished with transactionCount 2.
  • The chat kept one card. Optimistically it pointed at the second report, since that write landed last.
  • Pressing View there navigated to /e/3540756868666091, and report_3540756868666091 was undefined in Onyx by the time the screen painted. The not-found page rendered.
flowchart TD
    A["requestMoney mints one optimisticReportPreviewActionID"] -->|"passed to every receipt"| B["shouldCreateNewMoneyRequestReport: a separate report per scan"]
    B -->|"two previews, one reportActionID key"| C["Second preview overwrites the first, one card left"]
    C -->|"both requests send reportPreviewReportActionID 2605693961172736906"| D["Server binds the preview to report 8333712557575768, transactionCount 2"]
    D -->|"report_3540756868666091 stays undefined"| E["Card still carries the optimistic second report"]
    E -->|"openReportFromPreview navigates to e/3540756868666091"| F["Hmm... it's not here"]

Worth noting which path the press actually took, because it rules out the transaction-thread explanation. Each of these reports holds one transaction, so openTransactionFromPreview short-circuits on transactions.length <= 1 and openReportFromPreview navigates straight to e/<iouReportID>:

https://github.com/Expensify/App/blob/c134a8df49ca39dce693b81084cf0e58354c0821/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx#L184-L208

The route I landed on was /e/3540756868666091, an expense report route, so no thread was minted and search/view/... never ran. The report ID in the URL is the second receipt's report, not a client-generated thread ID.

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

Let the batch keep its shared preview ID only while the receipts stay on the report that preview belongs to. When a receipt ends up on a different report, buildOptimisticReportPreview should mint its own ID.

+        const isOnAnotherReport = !!existingIOUReport && iouReport.reportID !== existingIOUReport.reportID;
+        const reportPreviewActionID = isOnAnotherReport ? undefined : optimisticReportPreviewActionID;
         reportPreviewAction = buildOptimisticReportPreview(
             ...
-            optimisticReportPreviewActionID,
+            reportPreviewActionID,
             delegateAccountID,
         );

I would compare the reports rather than branch on shouldCreateNewMoneyRequestReport. The duplicate-expense loop passes existingIOUReport together with an optimisticIOUReportID pinned to that same report, so it rebuilds the report under the ID it supplied and still wants the preview it already reserved. Keying on the flag alone gives that flow a second card for one report. Comparing IDs also covers the non-ASAP triggers for free, since a receipt pushed onto a fresh report because the previous one stopped accepting transactions hits the same collision.

With this change the two receipts get two preview actions, so the second report keeps a card of its own and the press resolves to a report that exists. I confirmed it on the same flow that failed: the chat now shows two cards instead of one, and View no longer reaches the not-found page. I would cover all three cases in GetMoneyRequestInformationTest: two ASAP scan receipts must produce different preview action IDs (this one fails on current main), two receipts on one report must keep the single reserved ID, and a caller that rebuilds the report under its own optimisticIOUReportID must keep it too.

What alternative solutions did you explore? (Optional)

Minting a fresh preview ID inside the receipt loop in useExpenseSubmission would also break the collision, but it throws away the batching the shared ID exists for and gives ordinary multi-receipt expenses a card per receipt. The builder is the only place that knows which report the receipt actually landed on, so the decision belongs there.

I also looked at guarding the destination instead, either by relaxing the not-found check or by holding navigation until the report is confirmed. That treats the symptom. The second report is genuinely never created, so any guard would leave the user on a spinner or bounce them somewhere else, and the first report would still be silently holding both expenses behind one card.

Flipping shouldGenerateTransactionThreadReport to true for scans does not apply here. The press never reaches thread code, since a single-transaction preview opens its expense report directly through openReportFromPreview.

mukhrr avatar Sep 26 '26 06:09 mukhrr

Proposal

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

After creating a receipt expense with two receipts (multi-scan), opening the created expense shows the "Hmm... it's not here" page shortly after creation, and the expense report preview also disappears from the workspace chat.

What is the root cause of that problem?

When the user presses "Create 2 expenses" on the confirmation page, requestMoney in useExpenseSubmission generates one optimisticChatReportID, one optimisticCreatedReportActionID, and one optimisticReportPreviewActionID before the loop, and then calls the requestMoney IOU action once per receipt, passing those same three IDs to every call:

https://github.com/Expensify/App/blob/acf82f8d03974165cd9bf51de2d4137b713ff213/src/pages/iou/request/step/confirmation/useExpenseSubmission.ts#L425-L432

https://github.com/Expensify/App/blob/acf82f8d03974165cd9bf51de2d4137b713ff213/src/pages/iou/request/step/confirmation/useExpenseSubmission.ts#L486-L492

Sharing one optimisticReportPreviewActionID is only correct when all the transactions in the batch land in the same expense report, because a chat has exactly one report preview action per money request report, so both loop iterations then intentionally collapse into the same optimistic action.

However, the bug's precondition is an expensifail account, which has the ASAP Submit beta enabled. Under that beta, shouldCreateNewMoneyRequestReport forces a brand-new expense report for every scan request, even when an existingIOUReport from the previous loop iteration is passed in:

https://github.com/Expensify/App/blob/acf82f8d03974165cd9bf51de2d4137b713ff213/src/libs/ReportUtils.ts#L11984-L11990

So with two scanned receipts, each iteration creates its own new expense report, and for each of those two different reports getMoneyRequestInformation builds a report preview action using the same caller-provided optimisticReportPreviewActionID:

https://github.com/Expensify/App/blob/acf82f8d03974165cd9bf51de2d4137b713ff213/src/libs/actions/IOU/MoneyRequestBuilder.ts#L1635-L1655

The app therefore sends two RequestMoney API commands that reference two different iouReportID values but the same reportPreviewReportActionID. Locally, the second preview action overwrites the first one under the same report actions key, which is why the workspace chat only shows a single preview reading "1 expense" even though two expenses were created. On the server, the two commands collide on that report action ID, so the second expense report is not created successfully. Once the server state syncs back, the report the user opened resolves as not found: the report screen flips to the "Not here" page and the preview vanishes from the chat, exactly as shown in the video in the OP (the first report still exists, which is why an "Expense Report" row remains visible in the LHN).

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

A report preview action ID must be unique per created expense report. In getMoneyRequestInformation, the caller-provided optimisticReportPreviewActionID should only be used for the first report of a batch. When shouldCreateNewMoneyRequestReport is true and an existingIOUReport was passed in (meaning a previous item in the same batch already created a report using the shared optimistic IDs), the preview action should be built without the provided ID, so that buildOptimisticReportPreview falls back to generating a fresh unique ID, which it already does whenever that parameter is undefined:

https://github.com/Expensify/App/blob/acf82f8d03974165cd9bf51de2d4137b713ff213/src/libs/ReportUtils.ts#L8289

With this change, each scanned receipt on the ASAP Submit path creates its own report with its own report preview action, both RequestMoney commands succeed, both previews render in the workspace chat, and opening either expense no longer shows the Not Here page. The non-beta path is unaffected: when the batch keeps adding transactions to the same report, the builder either finds and updates the existing preview action or reuses the shared ID on the one report that is created, which is the current intended deduplication behavior.

Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/100368-unique-report-preview-per-new-report?expand=1

What alternative solutions did you explore? (Optional)

Generating a fresh optimisticReportPreviewActionID per loop iteration in useExpenseSubmission instead. This was rejected as the primary option because the caller cannot know whether the builder will attach the transaction to the existing report or create a new one — that decision (scan request plus ASAP Submit beta) is made inside shouldCreateNewMoneyRequestReport — and always using fresh IDs would break the intended deduplication of the preview action when the batch lands in a single report, since the first call's optimistic data is written via a deferred API write and is not yet readable from Onyx when the second call builds its data. Making the builder decide keeps both paths correct.

wildan-m avatar Sep 26 '26 06:09 wildan-m

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

melvin-bot[bot] avatar Sep 26 '26 06:09 melvin-bot[bot]

🤖 ProposalPolice™ is tracking duplicate proposals for this issue using an OpenAI Conversation. This comment stores that Conversation's ID and can be safely ignored.

github-actions[bot] avatar Sep 26 '26 06:09 github-actions[bot]

Proposal updated — added compare branch with implementation.

wildan-m avatar Sep 26 '26 06:09 wildan-m

Proposal

What is the root cause of that problem?

The "Not Here" page is rendered because the expense report the user is looking at is deleted out from under them, and the code that deletes it returns before the code that would re-route them.

Multi-scan submission mints one optimisticReportPreviewActionID for the whole batch:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/pages/iou/request/step/confirmation/useExpenseSubmission.ts#L481

Under ASAP Submit, shouldCreateNewMoneyRequestReport forces a separate expense report per scan request, so two receipts produce two client reports A and B:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/libs/ReportUtils.ts#L12075-L12083

The builder stamps that one batch ID onto both of them as parentReportActionID:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/libs/actions/IOU/MoneyRequestBuilder.ts#L1702-L1716

One card is left in the chat and it points at B, so View opens /e/B. The server then merges the batch and returns B carrying preexistingReportID = A. That is where the reported symptom is produced:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/libs/actions/replaceOptimisticReportWithActualReport.ts#L81-L88

This branch deletes the chat's preview action, deletes report B, and returns. Every re-route path in this module lives below that return — including step 2 of the module's own header contract, "Redirect the user to the preexisting report (if they're currently viewing the optimistic one)".

Even if the branch fell through, the focus test below has no case for /e/:reportID:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/libs/actions/replaceOptimisticReportWithActualReport.ts#L164-L180

isOptimisticReportFocused matches /r/<id> and the search-report RHP carousel. isOptimisticReportInBackground matches the expense-report screen, but only when the replaced report sits in backTo (#77657). Sitting on /e/B matches neither, because /e/:reportID is SCREENS.RIGHT_MODAL.EXPENSE_REPORT with B as the screen's own param:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/libs/Navigation/linkingConfig/config.ts#L2225

The last hop is mechanical. The page reads its report ID off the Onyx record, not the route:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/pages/Search/SearchMoneyRequestReportPage.tsx#L141

Once B is gone that is undefined, report actions have loaded, and there are no transactions, so the access-error page renders:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/pages/Search/SearchMoneyRequestReportPage.tsx#L345-L353

Why two receipts and not one. One receipt produces one report, nothing is merged away, and preexistingReportID never arrives. The expensifail precondition is there because ASAP Submit is what splits the batch in two.

The shared preview ID is the trigger, not the producer. The collision is real: it is why the chat keeps one card, and why line 83 deleting parentReportActionID also removes the surviving report's card, the second symptom in the video. But if the producer is this missing re-route, a report that already has a unique preview action ID must still strand the user, because the deletion is driven by the server's preexistingReportID and not by that ID. I ran that case against current main and it fails identically to the colliding one:

● still strands the user when the report already has its own unique preview action ID
    Expected: "1111111111111111"
    Received: undefined

So fixing only the ID collision cannot remove this page. The logs on this thread are consistent with that: the merge happened, with report A finishing at transactionCount 2.

Why no test caught it. There is no test file for this module; the nearest coverage is ReplaceOptimisticAgentAccountIDTest.ts, on the agent-mapping sibling.

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

Re-route before the money-request branch destroys the report:

 if (isMoneyRequestReport(report) && parentReportID && parentReportActionID) {
+    const currentRoute = navigationRef.isReady() ? navigationRef.getCurrentRoute() : undefined;
+    const currentRouteReportID = (currentRoute?.params as {reportID?: string} | undefined)?.reportID;
+    if (currentRoute?.name === SCREENS.RIGHT_MODAL.EXPENSE_REPORT && currentRouteReportID === reportID) {
+        Navigation.setParams({reportID: preexistingReportID.toString()});
+    }
     Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${parentReportID}`, {[parentReportActionID]: null});
     Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, null);
     return;
 }

Navigation.setParams is what the existing focused branch already uses for the same purpose, so the user lands on the report that survived and holds their expenses.

I would keep this branch's early return rather than let it fall through to the shared callback. That callback writes {...report, reportID: preexistingReportID} onto the preexisting report, which for an expense report would overwrite real report A with B's optimistic fields. That is why the early return exists and it should stay; the missing piece is only the re-route.

I am not contesting the preview-ID collision — it should be fixed too. My point is only that it is not sufficient alone.

What I observed. Three cases in a new suite for this module. On main the bug case fails on a value:

● moves the user to the surviving report when they are viewing the replaced one
    Expected: "1111111111111111"
    Received: undefined

With the diff all three pass. I checked the control case as well — the same reconciliation while the user is on a different /e/ report leaves setParams uncalled, undefined before and after, so an unrelated expense report screen is never navigated. After reverting only this file, I confirmed both failures return with identical assertions.

Regression safety

  • Only reachable when preexistingReportID is set on an IOU/expense report, which is the merge path alone. Chats, threads and DMs are untouched.
  • Guarded on the screen name and on the param equalling the replaced reportID — that is the control case above.
  • navigationRef.isReady() is checked, matching the guard this module already applies further down.
  • No timer or transition is altered: it runs in the tick that already deletes the report, just before the delete.

Also worth adding: a chat report replaced while on /r/B, proving the existing /r/ re-route still fires, and a render test asserting SearchMoneyRequestReportPage shows the access-error page for a report missing from Onyx — the user-visible symptom, which must not appear after the re-route.

What alternative solutions did you explore? (Optional)

Only fix the shared preview action ID. Necessary, and it removes the single-card symptom, but it leaves this page — see the unique-ID failure above.

Relax the access-error condition, or hold it while the report is pending. That leaves the user on a route whose report does not exist: a spinner or an empty report instead of a wrong page. The ID in the URL is dead, so the fix has to change the URL.

The transaction-thread route. Does not apply. Each of these reports holds one transaction, so the preview opens the expense report directly and search/view/... is never built. The route reached is /e/<reportID>.

The stale transactionID at the scan navigation call sites. That decides which transaction the confirmation page edits, before submission. This page renders after submission, from the report's absence in Onyx.

yusufdeveloper2903 avatar Sep 26 '26 06:09 yusufdeveloper2903

Proposal

What is the root cause of that problem?

The transaction-thread route is not on this path, and that is checkable in two lines. MoneyRequestReportPreview derives its transaction list from the linked expense report only — useReportTransactionsCollection(iouReportID) at line 90 — and under ASAP Submit each scanned receipt is forced onto its own single-transaction expense report. So both cards satisfy transactions.length <= 1 and short-circuit before any thread logic runs:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx#L358-L361

openReportFromPreview() pushes EXPENSE_REPORT_RHP (wide) or REPORT_WITH_ID (Android). useNavigateToTransactionThread is never called, so search/view/undefined and the RHP not-found guard cannot explain this repro. The report we land on genuinely exists in Onyx — what is missing is its parent report-preview action.

That missing action is a reportActionID collision. One ID is minted before the receipt loop and handed to every receipt:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/pages/iou/request/step/confirmation/useExpenseSubmission.ts#L479-L481

With ASAP Submit (expensifail), every scan is forced onto a brand-new expense report:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/libs/ReportUtils.ts#L12088-L12094

That same flag also skips the "reuse the existing preview" lookup, so both iterations take the else branch with the identical supplied ID, and each stamps its own report's parentReportActionID with it:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/libs/actions/IOU/MoneyRequestBuilder.ts#L1697-L1716

reportActions_<chatID> is keyed by reportActionID, so the second MERGE overwrites the first: the chat retains a single preview pointing at report #2, while report #1 survives claiming the same parentReportActionID. This is not a transient optimistic-data artifact — the same ID is sent to the server twice against two different iouReportIDs:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/libs/actions/IOU/TrackExpense.ts#L1948-L1956

So the collision outlives the round trip. Opening the orphaned report fails the access gate — wasParentActionDeleted, or !reportID && hasLoadedReportActions && !hasAnyTransactions:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/pages/Search/SearchMoneyRequestReportPage.tsx#L336-L353

That also explains the second reported symptom — one preview card vanishing from the workspace chat — which a navigation-guard theory does not cover at all.

The crucial constraint: sharing that ID is load-bearing, so simply moving rand64() inside the loop is the wrong fix. The lookup at L1697 resolves through a module-level Onyx snapshot (getAllReportActionsFromIOU(), src/libs/actions/IOU/index.ts#L85-L92), and the optimistic write is deferred behind a write barrier (deferredAPIWrite?.() at TrackExpense.ts#L2000 → API.writeWhenReady). Within the synchronous loop, iteration 2 therefore cannot see iteration 1's preview action even when both receipts land on the same report — the supplied ID is the only mechanism collapsing the two writes into one card. A per-iteration rand64() would give one expense report two REPORT_PREVIEW actions in the ordinary non-ASAP two-receipt case, trading this bug for duplicate preview cards.

Two other IDs in the same hoist are innocent: optimisticCreatedReportActionID is the chat's CREATED action (ReportUtils.ts#L9689) — the IOU report gets a fresh CREATED ID per iteration — and optimisticChatReportID is per-chat by construction.

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

Scope the supplied preview action ID to the report it was actually spent on. Only getMoneyRequestInformation knows whether this item starts a new report, so decide there. In src/libs/actions/IOU/MoneyRequestBuilder.ts, replace line 1697 with:

// The caller mints one report-preview action ID per batch so that several receipts landing on the SAME
// report collapse into one preview action — the previous item's optimistic write is not visible to the
// lookup below yet (deferred API write + module-level report-actions snapshot). When this item starts a
// *new* report, that ID already belongs to `existingIOUReport`'s preview, so mint a fresh one instead.
const isSuppliedPreviewActionIDAlreadyUsed = !!optimisticReportPreviewActionID && existingIOUReport?.parentReportActionID === optimisticReportPreviewActionID;
let reportPreviewAction = shouldCreateNewMoneyRequestReport ? null : getReportPreviewReportAction(chatReport.reportID, iouReport.reportID);

and at line 1710 pass:

            shouldCreateNewMoneyRequestReport && isSuppliedPreviewActionIDAlreadyUsed ? undefined : optimisticReportPreviewActionID,

buildOptimisticReportPreview already falls back to rand64() on an undefined reportActionID (ReportUtils.ts#L8351), so no API-shape change is needed.

Why each branch is correct: the previous iteration mutated the very object fed forward as existingIOUReport (requestMoney returns it, TrackExpense.ts#L2005), setting parentReportActionID to the supplied ID at L1716. The new condition therefore reads exactly as "an earlier receipt in this batch already spent this ID". Receipt #1 keeps it; a receipt that joins report #1 keeps it (one card); a receipt that forks a new report gets its own ID, its own chat preview action, and a resolvable parentReportActionID. The other callers passing optimisticReportPreviewActionID (Duplicate.ts#L1199, #L1429) submit into an existing open target where shouldCreateNewMoneyRequestReport is false, so their behaviour is unchanged.

Regression coverage: a unit test calling getMoneyRequestInformation twice with the same optimisticReportPreviewActionID, feeding the first call's iouReport back as existingIOUReport, asserting the returned reportPreviewAction.reportActionIDs differ when a scan forks a new report under ASAP Submit and match when the second transaction joins the first report.

trasnake87 avatar Sep 26 '26 06:09 trasnake87

Proposal

What is the root cause of that problem?

When a multi-receipt submit creates two expense reports, both reports' preview actions are written under one reportActionID. The second write overwrites the first. After reconciliation, the report the user opens has no preview and no data, so the page shows "Not here".

The loop in useExpenseSubmission.requestMoney mints one preview ID for the whole batch and hands it to every receipt:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/pages/iou/request/step/confirmation/useExpenseSubmission.ts#L481

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/pages/iou/request/step/confirmation/useExpenseSubmission.ts#L540-L548

The loop only forwards the report to the next iteration, not the preview it built:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/pages/iou/request/step/confirmation/useExpenseSubmission.ts#L620

I think the shared ID exists to paper over a missing hand-off. The builder looks up the existing preview in Onyx. Within a batch, the first receipt's write is deferred, so that lookup finds nothing. The builder then rebuilds the preview from scratch, and the shared ID is what makes that rebuild land on the same key:

https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/libs/actions/IOU/MoneyRequestBuilder.ts#L1697-L1716

This workaround breaks in two ways:

  1. This issue. shouldCreateNewMoneyRequestReport sends every scan to its own report under ASAP Submit. The expensifail precondition has this beta on. It does the same when the previous report can't accept another transaction:

    https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/libs/ReportUtils.ts#L12075-L12093

    Report B then gets a preview under report A's key. Both RequestMoney calls send the same reportPreviewReportActionID:

    https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/libs/actions/IOU/TrackExpense.ts#L1956

  2. The same-report case is also wrong, just less visibly. The rebuild uses buildOptimisticReportPreview, which hardcodes childMoneyRequestCount: 1:

    https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/libs/ReportUtils.ts#L8372

    updateReportPreview would have incremented the count instead:

    https://github.com/Expensify/App/blob/a9709e2c8906ff2095cde1e02128e5c9b0b128bd/src/libs/ReportUtils.ts#L8549

    I checked this on main: two receipts joining one report produce {sameReport: true, id: 'X', childMoneyRequestCount: 1}. The optimistic card reads "1 expense" for two expenses.

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

I'd remove the batch-wide preview ID instead of teaching the builder when to distrust it. Instead, the loop hands the previous iteration's preview action forward, the same way it already hands existingIOUReport forward. The fix spans the data hand-off between the submit loop and the builder:

// useExpenseSubmission loop: no shared optimisticReportPreviewActionID
const {iouReport, reportPreviewAction} = requestMoneyIOUActions({existingIOUReport, existingReportPreviewAction, ...});
existingIOUReport = iouReport;
existingReportPreviewAction = reportPreviewAction;

// MoneyRequestBuilder: use the hand-off only when it belongs to the report we landed on
const handedOff = isReportPreviewAction(existingReportPreviewAction) && getOriginalMessage(existingReportPreviewAction)?.linkedReportID === iouReport.reportID ? existingReportPreviewAction : null;
let reportPreviewAction = shouldCreateNewMoneyRequestReport ? null : (getReportPreviewReportAction(chatReport.reportID, iouReport.reportID) ?? handedOff);

requestMoney returns reportPreviewAction next to iouReport. The builder already has it.

How this behaves:

  • A receipt the builder splits onto a new report never receives a pinned ID. It gets its own preview, with no ordering or timing involved.
  • A receipt that joins the same report goes through updateReportPreview. It keeps the same reportActionID (so the API payload is unchanged) and the count becomes 2.
  • Other callers are untouched. Duplicate, PerDiem and Split don't pass the new param, so they keep their explicit optimisticReportPreviewActionID.

Verification (patch against a9709e2c):

  • tests/actions/IOU (30 suites): 984/984 pass with the patch.
  • tests/unit/hooks/useExpenseSubmission.test.ts: 28 existing tests + 1 new, all pass.
  • New tests:
    • The hook test checks that no call gets a shared preview ID and that call 2 receives call 1's preview.
    • Three builder tests cover these cases:
      • a receipt split onto a new report gets its own preview;
      • a receipt joining the same report updates the handed-off preview, ending with the same ID and a count of 2;
      • a handed-off preview linked to a different report is ignored.
  • With the src/ changes reverted, the hook test and the same-report builder test fail on main (2 failed / 60 passed across the two files). With the patch, all 62 pass.

This is code and test evidence only. I couldn't reproduce it in the app, because that needs an account with ASAP Submit enabled.

What alternative solutions did you explore? (Optional)

Mint a fresh preview ID per receipt in the loop, with no hand-off. Rejected: without the hand-off, the builder can't find report A's preview (it isn't in Onyx yet). Two receipts on one report would then get two cards. That is the same builder test that fails on main above.

Keep the shared ID and have the builder decide when to ignore it. That fixes the collision. But the builder has to infer, from report IDs or shouldCreateNewMoneyRequestReport, what the caller meant by a shared ID. It also still rebuilds the preview with childMoneyRequestCount: 1 in the same-report case. Handing off the actual action removes the need for that inference.

Guard or redirect the "Not here" page during reconciliation. Rejected: report B's preview is gone from the chat either way, so this would hide the symptom and leave the data wrong.

Abdulloh0109 avatar Sep 26 '26 06:09 Abdulloh0109

Proposal

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

Creating a receipt expense from two receipts and then opening it shows "Hmm... it's not here". One receipt opens normally. The reported account is an expensifail account, and the issue reproduces on every platform listed. The same failure also happens with ASAP Submit turned off, on a workspace whose policy is instant submit, submit and close, and payments disabled.

What is the root cause of that problem?

A report preview is the chat card for one expense report, and its action ID is that report's parentReportActionID. The multi-receipt submit reserves a single preview action ID before the loop and passes that same ID into every receipt, carrying the previous receipt's report forward so the next receipt can join it:

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/pages/iou/request/step/confirmation/useExpenseSubmission.ts#L480-L482

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/pages/iou/request/step/confirmation/useExpenseSubmission.ts#L540-L548

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/pages/iou/request/step/confirmation/useExpenseSubmission.ts#L619-L621

Sharing that ID is correct while every receipt lands on the same expense report. The builder judges the report it was handed and can refuse it. The next receipt then starts from that handed report:

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/actions/IOU/MoneyRequestBuilder.ts#L1408-L1409

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/ReportUtils.ts#L12072-L12092

When the builder refuses the report, it builds a new one under a fresh ID, because the scan loop does not pass optimisticIOUReportID:

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/actions/IOU/MoneyRequestBuilder.ts#L1420-L1428

The new report still receives the batch's original preview ID. Report actions are stored by that ID, so the second preview replaces the first, and both reports record the same parentReportActionID:

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/actions/IOU/MoneyRequestBuilder.ts#L1677-L1697

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/actions/IOU/MoneyRequestBuilder.ts#L642-L646

That ID is also the reportPreviewReportActionID on the RequestMoney command, so the server receives two creates for two iouReportIDs that claim one preview:

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/actions/IOU/TrackExpense.ts#L1946-L1952

The server keeps one report. The response for the other carries preexistingReportID. For a money-request report the client deletes that report and the parent preview, then returns:

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/actions/replaceOptimisticReportWithActualReport.ts#L81-L87

The chat card is the preview that was written last, so it points at the report that was just deleted. Each of those reports holds one transaction, so the press opens the expense report directly:

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx#L358-L361

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/components/ReportActionItem/MoneyRequestReportPreview/index.tsx#L204-L208

The route is /e/<reportID>. That report is gone from Onyx, so the expense page renders "Hmm... it's not here". Because the two reports shared one parentReportActionID, deleting it also removes the card of the report that survived. One receipt never reaches this: there is one report, one preview, and no preexistingReportID.

The expensifail precondition is the ASAP Submit clause, the last line of shouldCreateNewMoneyRequestReport. It is one trigger, and the scan loop has no moneyRequestReportID, so isFromExistingReport is false and the clause fires on receipt two.

The same split happens with the beta off. On instant submit plus submit-and-close plus payments disabled, the optimistic expense report is built closed. getExpenseReportStateAndStatus is called with its default isEmptyOptimisticReport = false:

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/ReportUtils.ts#L7434-L7450

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/ReportUtils.ts#L7503-L7517

Receipt two is handed that closed report. canAddTransaction rejects it from the report's own status, with no Onyx read of the previous transaction:

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/ReportUtils.ts#L3056-L3063

isOpenExpenseReport requires stateNum and statusNum both open, so the closed report fails it, shouldCreateNewMoneyRequestReport returns true, and receipt two is a new report wearing the first receipt's preview ID. The payload the server sees is the same collision as the ASAP case.

bulkDuplicateExpenses already treats this policy as a split and mints a new preview ID when it happens. The scan loop has no equivalent:

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/actions/IOU/Duplicate.ts#L1343-L1347

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/actions/IOU/Duplicate.ts#L1390-L1394

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

Resolve the preview ID at the point the report has already been chosen, inside the branch that builds a new preview. Keep the caller's reserved ID when this expense is still on the report the caller held. When the built report is a different report, pass undefined and let buildOptimisticReportPreview mint a new ID, which it already does:

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/ReportUtils.ts#L8347-L8349

     } else {
+        // A preview is the parent action of one expense report. The ID reserved for the
+        // batch belongs to the report the caller held. A receipt that landed on a different
+        // report needs its own preview, and buildOptimisticReportPreview mints one when this is undefined.
+        const isCallerReservedReport = !existingIOUReport || existingIOUReport.reportID === iouReport.reportID;
         reportPreviewAction = buildOptimisticReportPreview(
             chatReport,
             iouReport,
             getCurrencyDecimals,
             comment,
             optimisticTransaction,
             undefined,
-            optimisticReportPreviewActionID,
+            isCallerReservedReport ? optimisticReportPreviewActionID : undefined,
             delegateAccountID,
         );

The comparison follows the report the expense actually landed on, so every split trigger is covered by the same line: the ASAP Submit clause, a closed report under instant submit, a report that is pending deletion, and a report waiting on a bank account. The scan loop does not pass optimisticIOUReportID, so a split there always produces a new report ID and therefore a new preview ID.

The comparison also leaves the pinned-ID caller alone. duplicateExpenseTransaction passes existingIOUReport together with an optimisticIOUReportID of that same report, and optimisticReportID = optimisticIOUReportID ?? generateReportID() rebuilds under the ID the caller supplied. The bulk loop only pre-splits when canAddTransaction is false or policyWillSplitReport is set. shouldCreateNewMoneyRequestReport can still be true for a reason that loop does not check (errorFields.createChat, pending deletion, the bank-account hold, the ASAP clause) while the report ID stays the one the caller pinned. The reserved preview still belongs to that report, and the comparison keeps it.

Three expenses that stay on one report are what DuplicateTest locks in, and this change leaves that assertion green:

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/tests/actions/IOUTest/DuplicateTest.ts#L3356-L3371

Blast radius is the else branch of getMoneyRequestInformation. The branch that finds an existing preview and calls updateReportPreview is unchanged. A caller that passes no existingIOUReport keeps the reserved ID. Two receipts that stay on one report keep one preview, including the same-loop case where the first preview is not readable from Onyx yet and the builder falls through to this else. optimisticCreatedReportActionID stays shared: it is the chat CREATED action, and each expense report already gets its own CREATED action with a fresh ID.

What alternative solutions did you explore? (Optional)

Branch on shouldCreateNewMoneyRequestReport instead of the report ID. When the flag is true and existingIOUReport was passed, mint a new preview ID; otherwise reuse the reserved one. That fixes the scan loop, because the scan loop never pins optimisticIOUReportID, so a true flag there really is a new report. It gives the pinned-ID caller a second preview for one report. The duplicate loop is that caller, and the three triggers it does not pre-check still reach the builder with the flag true and the report ID unchanged. Comparing the IDs covers the scan splits and that caller with one condition. The default duplicate test stays green under either version, because those three expenses share a report and the flag is false; the pinned-ID case is the one that separates them.

Mint a fresh preview ID on every iteration of the scan loop. The loop cannot see whether the builder will join the previous report or leave it. A fresh ID on every receipt gives an ordinary multi-receipt expense one card per receipt, and it fails the duplicate test above. The builder is where the report decision already happens.

Regenerate optimisticCreatedReportActionID per receipt as well. That ID is applied only to the chat CREATED action. The expense report's own CREATED action is built without it:

https://github.com/Expensify/App/blob/e1e5d9f45ff538851c774e133f8debd254100fff/src/libs/ReportUtils.ts#L9686-L9693

Re-route /e/:reportID inside replaceOptimisticReportWithActualReport before the money-request branch returns. That branch does delete the open report and return before any of the re-route logic, and the focused-route check has no case for sitting on /e/<reportID>. A test that writes preexistingReportID onto a report by hand will still strand the route after the preview IDs are unique, because it never sends the RequestMoney the server answered. The logs already on this issue show what the server answered: both commands carried one reportPreviewReportActionID, and the surviving report finished holding both expenses. That answer is the server collapsing two creates that claimed one preview. Unique preview IDs are two creates. Re-routing alone would also land the user on the surviving report, which is holding both receipts, and the early return would still delete parentReportActionID. While the two reports share that ID, deleting it removes the surviving report's card too. The re-route does not put the card back.

Hold or relax the not-found page. The report in the URL has been removed. A spinner or a looser guard leaves the user on a route whose report was never created on the server.

Transaction-thread navigation, which is what the first proposal on this issue suggested. Maruf reported that proposal does not fix the bug. With one transaction on the report, the press takes openReportFromPreview and the route is /e/<reportID>. No transaction thread is minted.

Use the batch transaction IDs at the scan-screen navigation call sites. That chooses which draft the confirmation page edits, before the user submits. This page is rendered after submit, from the report's absence in Onyx.

What specific scenarios should we cover in automated tests?

  • Two ASAP Submit scan receipts produce two RequestMoney calls with different reportPreviewReportActionID values and different iouReportID values. This fails on current main.
  • Two receipts that stay on one report keep the single reserved preview ID.
  • A caller that passes existingIOUReport and an optimisticIOUReportID equal to that report's ID keeps the reserved preview ID, including when shouldCreateNewMoneyRequestReport is true for a reason other than canAddTransaction.
  • Instant submit, submit and close, and payments disabled, with ASAP Submit off: two scan receipts produce two reports and two preview IDs.
  • DuplicateTest "should pass the same reportPreviewReportActionID to all expense calls" stays green.

neerajbachani avatar Sep 26 '26 06:09 neerajbachani

Proposal

What is the root cause of that problem?

Creating two receipts at once under ASAP Submit builds two separate expense reports on the client. When the server later says the second report already exists as the first one (preexistingReportID), a special cleanup path for money-request reports runs.

That path was built for a different situation: throw away a stale optimistic expense report and its chat preview card, then stop. It deletes the report the user may still be looking at and returns immediately — it never remaps them to the surviving report, and it never runs the normal “you are viewing the optimistic report → switch to the real one” logic that exists for DMs and threads.

So after a two-receipt create, opening the expense that got marked as a duplicate lands on a report ID that was just wiped from local state. The screen has nothing left to show, which is the “Not Here” page. Melvin’s transaction-thread explanation does not match this path: each ASAP scan report has a single expense, so opening it goes to the expense report itself, not a thread.

A shared preview action ID across the batch makes this collision more likely, but the visible failure is produced by treating a user-facing duplicate expense report like disposable IOU cleanup instead of a report that should be replaced and re-routed.

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

  1. When an expense report comes back as a duplicate of another expense report, do not use the “delete preview + delete report + stop” shortcut as the only step.
  2. Remap the open expense view (and any local data still tied to the optimistic report ID) onto the surviving report, the same way other optimistic-report replacements already re-route the user.
  3. Only clear the chat preview when it truly belongs to the discarded report and is not still the card for the surviving one.

That keeps the user on a real expense after a two-receipt create instead of a wiped report ID.

What alternative solutions did you explore? (Optional)

  • Only mint a fresh preview ID when the batch splits into a new report. Worth doing so two scans do not collide on one chat card, but it does not fix the case where the server still returns a preexisting report and the money-request cleanup path wipes the open expense without remapping.
  • Only add a redirect for the expense route and keep the destructive cleanup. That hides the symptom for whoever is already on the page, but still drops local data tied to the optimistic ID and does not fix opening the same expense again from the LHN or search.
  • Melvin’s transaction-thread / not-found guard changes. Rejected for this repro: ASAP multi-scan opens the expense report directly, not a client-minted thread.

yifangoh avatar Sep 26 '26 06:09 yifangoh

Proposal

What is the root cause?

The failing path is the optimistic-report reconciliation used by ASAP Submit when two scanned receipts are submitted together. Each receipt can create a separate optimistic expense report, while the batch reuses the same reportPreviewReportActionID. When the server resolves one optimistic report to a preexistingReportID, the money-request cleanup branch removes the optimistic report/preview and returns before the normal optimistic-to-actual report replacement can reroute an open /e/:reportID view.

The user is therefore left on an expense-report ID that has just been removed from Onyx, so the report guard renders the Not Here page. This repro opens a single-transaction expense report directly, so changing transaction-thread navigation alone would not cover the observed path.

Proposed changes

  1. Generate a distinct preview action/report identity whenever a multi-scan submission actually creates a separate optimistic expense report, while preserving the shared ID when transactions intentionally remain on one report.
  2. Update the money-request branch of replaceOptimisticReportWithActualReport so it remaps references from the optimistic report to the surviving report and reroutes an active expense route before deleting obsolete Onyx data.
  3. Delete the preview action only when it belongs exclusively to the discarded report; do not remove a preview still used by the surviving report.
  4. Keep the existing fallback behavior for unresolved IDs so navigation never targets an ID that is absent after reconciliation.

Tests

  • Two ASAP Submit scan receipts that create separate reports use distinct iouReportID and reportPreviewReportActionID values.
  • When the server returns preexistingReportID, an open /e/ route is replaced with the surviving report and does not show Not Here.
  • A batch intentionally adding two transactions to one report retains one preview ID.
  • Cover instant submit, submit-and-close, payments-disabled, web, and Android paths.
  • Verify the existing duplicate-request test remains green and that the surviving preview card is not deleted.

I would first add the failing reconciliation tests, then make the smallest change to ID allocation and the replacement/reroute branch.

Rushow111 avatar Sep 26 '26 08:09 Rushow111

📣 @Rushow111! 📣 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 Sep 26 '26 08:09 melvin-bot[bot]

⚠️ @Rushow111 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).

github-actions[bot] avatar Sep 26 '26 08:09 github-actions[bot]