App icon indicating copy to clipboard operation
App copied to clipboard

[$175] [Exploratory] Unexpected error when open App and change track distance rate

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

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


Version Number: v9.5.23-2 Reproducible in staging?: Yes Reproducible in production?: Yes If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://github.com/Expensify/App/pull/101685 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: iPhone 15 Pro / iOS 27.0.1, Google Pixel 7a / Android 17 App Component: Chat Report View

Action Performed:

  1. Open the Expensify App and log in
  2. Create a workspace and enable "Distance rates" in the "More features"
  3. Create a couple of new rates and save them
  4. Go back to the workspace and tap on the "+" button
  5. Tap on "Track distance" and create a track distance expense with any of the existing rates (can also be a default one)
  6. Save the expense and submit it
  7. Kill and restart the App
  8. Open the just-created expense
  9. Change the rate to any other one and save
  10. Wait for a second and observe the expense thread
  11. Repeat steps 7-10 if needed

Expected Result:

The rate should be changed to the selected one.

Actual Result:

The rate in the Rate field doesn't change to the selected one. An unexpected error appears in the expense thread.

Workaround:

Unknown

Platforms:

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

Screenshots/Videos

https://github.com/user-attachments/assets/ad6cb3bf-f723-41d6-bc97-885949e4926b

Image

View all open jobs on GitHub

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

Upwork Automation - Do Not Edit

applause-bot[bot] avatar Oct 27 '26 18:10 applause-bot[bot]

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

https://platform.applause.com/services/links/v1/external/9808292a2f58559b7c334c02d8e8951878c4554f50cd91e985434516ad5e1ec2

applause-bot[bot] avatar Oct 27 '26 18:10 applause-bot[bot]

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

I think the backend is rejecting UpdateMoneyRequestDistanceRate, and the App shows its generic fallback. The App's failure data restores the pre-edit transaction (UpdateMoneyRequest.ts:2317-2327). That snapshot reverts the rate and shows "Unexpected error editing this expense". This matches both symptoms.

I couldn't confirm why the server rejects the request, because I had no access to the API response or backend code. To confirm, check the UpdateMoneyRequestDistanceRate response (jsonCode and message) for [email protected] on 2026-10-26.

Investigation details
  • Request sent: customUnitRateID, reportID (parent expense report), transactionID, reportActionID, plus merchant and taxValue when relevant. It sends no policyID, distance, or amount, so the server recomputes the amount itself. No App commit since 2026-08-20 changes how these params are built.
  • Possible restart-dependent inputs: after a restart, the transaction thread may be an optimistic one created by ReportFetchHandler.tsx (FAKE_REPORT_ID path). The edit's reportActionID would then point into a thread the server may not know yet.
  • Possible double submit: the bug was found while regression-testing Gate IOU distance rate and vendor edit selection behind a Save button (a11y On Input, PR 14). Save stays enabled until draftRateID === currentRateID re-renders (DynamicIOURequestStepDistanceRate.tsx:281-291). On a slow device after a cold start, a fast double tap could send two requests. If the second fails, it reverts the rate. This is unverified.
  • Web check: on web, without a reload, changing the rate on a submitted manual distance expense worked. The API returned jsonCode 200, the rate and amount updated, and no error appeared. I couldn't test the reload or restart step.
  • Unexplained: the screenshot shows "deleted an expense ($67.64 for 89.00 mi @ $0.76 / mi)" in the same report. A second, deleted expense may affect which thread the single-expense view uses.

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


view run · view recording

MelvinBot avatar Nov 03 '26 00:11 MelvinBot

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

melvin-bot[bot] avatar Nov 03 '26 00:11 melvin-bot[bot]

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

melvin-bot[bot] avatar Nov 03 '26 00:11 melvin-bot[bot]

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

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

Proposal

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

When a user creates a distance expense in a workspace chat (especially in an expense report that previously had a deleted expense, as seen in the issue screenshot showing "deleted an expense ($67.64 for 89.00 mi @ $0.76 / mi)"), kills and reopens the app, opens the expense report, taps Rate, and selects another distance rate, the edit fails with "Unexpected error editing this expense. Please try again later." and reverts to the original rate.

What is the root cause of that problem?

The root cause is a mismatch between how ReportFetchHandler detects a single-transaction report (transactionThreadReportID) and how createOneTransactionThread selects the transaction and IOU report action when lazily creating the transaction thread after a cold start (src/pages/inbox/ReportFetchHandler.tsx, lines 160–166, 271–290, and 428–438):

  1. In src/pages/inbox/ReportFetchHandler.tsx (lines 160–166), visibleTransactions is computed using getAllNonDeletedTransactions(allReportTransactions, reportActions, isOffline, true):

    const reportTransactionsCollection = useReportTransactionsCollection(reportID);
    const allReportTransactions = useReportTransactionsCollection(reportIDFromRoute);
    const reportTransactions = getAllNonDeletedTransactions(allReportTransactions, reportActions, isOffline, true);
    const visibleTransactions = isOffline ? reportTransactions : reportTransactions?.filter((transaction) => transaction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE);
    const reportTransactionIDs = visibleTransactions?.map((transaction) => transaction.transactionID);
    
    const transactionThreadReportID = getOneTransactionThreadReportID(report, chatReport, reportActions ?? [], isOffline, reportTransactionIDs);
    

    getAllNonDeletedTransactions filters out any transaction whose parent IOU report action is deleted (isDeletedAction), and getOneTransactionThreadReportID (via getOneTransactionThreadReportAction in src/libs/ReportActionsUtils.ts, lines 2596–2686) finds the single live IOU action. When that live IOU action does not yet have a childReportID in Onyx after reopening the app, getOneTransactionThreadReportID returns CONST.FAKE_REPORT_ID ('0').

  2. That triggers the useEffect at lines 428–438, which calls createOneTransactionThread() (lines 271–290):

    const createOneTransactionThread = useEffectEvent(() => {
        const currentReportTransactions = Object.values(reportTransactionsCollection ?? {}).filter(
            (transaction): transaction is Transaction => !!transaction && transaction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE,
        );
        const oneTransactionID = currentReportTransactions.at(0)?.transactionID;
        const iouAction = getIOUActionForReportID(reportID, oneTransactionID);
        createTransactionThreadReport({
            ...
            iouReport: report,
            iouReportAction: iouAction,
            transaction: currentReportTransactions.at(0),
            ...
        });
    });
    

    Notice three bugs here:

    • Instead of using visibleTransactions (which excludes transactions whose IOU report action was deleted) and getOneTransactionThreadReportAction, createOneTransactionThread reads raw Object.values(reportTransactionsCollection ?? {}) and only checks transaction.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.DELETE. After an app restart, a previously deleted transaction that is still cached in ONYXKEYS.COLLECTION.TRANSACTION no longer has pendingAction: 'delete' (its deletion already settled on the server, while its IOU report action has originalMessage.deleted set).
    • Consequently, currentReportTransactions.at(0) can pick the deleted transaction instead of the single live transaction in visibleTransactions!
    • Furthermore, getIOUActionForReportID(reportID, oneTransactionID) is called without shouldPreferLiveAction = true (src/libs/ReportActionsUtils.ts, line 3380), so createTransactionThreadReport creates an optimistic transaction thread bound to the deleted IOU report action (or with iouReportAction: undefined if reportID vs reportIDFromRoute differs), leaving the live expense's IOU action without a valid childReportID or binding the combined single-expense view (MoneyReportContentCreated -> MoneyRequestView) to a transaction thread whose parentReportActionID belongs to the deleted expense.
    • When the user then taps Rate in MoneyRequestView (src/components/ReportActionItem/MoneyRequestView.tsx, line 1174) and saves a new rate in DynamicIOURequestStepDistanceRate.tsx (lines 250–269), updateMoneyRequestDistanceRate sends UpdateMoneyRequestDistanceRate with a reportActionID created on an uninitialized/mismatched transaction thread. The server rejects UpdateMoneyRequestDistanceRate, and failureData (src/libs/actions/IOU/UpdateMoneyRequest.ts, lines 2324–2333) reverts the rate and sets errorFields to iou.error.genericEditFailureMessage ("Unexpected error editing this expense. Please try again later.").

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

  1. In src/pages/inbox/ReportFetchHandler.tsx (createOneTransactionThread, lines 271–290): Use the already-filtered visibleTransactions and getOneTransactionThreadReportAction (with getIOUActionForReportID(reportID, oneTransaction?.transactionID, true) as fallback) so createOneTransactionThread always creates the transaction thread for the exact same live transaction and live IOU report action that getOneTransactionThreadReportID resolved:

    const createOneTransactionThread = useEffectEvent(() => {
        const oneTransaction = visibleTransactions?.at(0);
        const iouAction =
            getOneTransactionThreadReportAction(report, chatReport, reportActions ?? [], isOffline, reportTransactionIDs) ??
            getIOUActionForReportID(reportID, oneTransaction?.transactionID, true);
        createTransactionThreadReport({
            introSelected,
            conciergeChat,
            isSelfTourViewed,
            hasCompletedGuidedSetupFlow,
            currentUserLogin: currentUserEmail ?? '',
            currentUserAccountID,
            iouReport: report,
            iouReportAction: iouAction,
            transaction: oneTransaction,
            personalDetails,
            fullPolicySnapshotLastModified,
        });
    });
    
  2. In tests/unit/ReportFetchHandlerTest.tsx (or tests/actions/ReportTest.ts): Add a regression test verifying that when a report contains both a previously deleted transaction (whose IOU action is deleted) and a single active distance transaction without a childReportID, createOneTransactionThread passes the active transaction and its live IOU action to createTransactionThreadReport.

What alternative solutions did you explore?

We considered resolving the transaction thread inside DynamicIOURequestStepDistanceRate.tsx when report?.parentReportID is missing, but DynamicIOURequestStepDistanceRate already receives transactionThreadReport.reportID from MoneyRequestView. Ensuring createOneTransactionThread in ReportFetchHandler.tsx uses visibleTransactions and getOneTransactionThreadReportAction fixes the root cause for distance rate edits as well as all other single-expense edits after an app restart.

e5ash avatar Nov 07 '26 14:11 e5ash

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

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

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

⚠️ Invalid email. Please make sure to create an Expensify account with this email first here.

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

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

e5ash avatar Nov 07 '26 15:11 e5ash

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

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

Proposal

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

After creating a Track Distance expense in a workspace chat, submitting it to someone, killing and reopening the app, and then navigating to the expense to change its distance rate, the rate change fails and shows Unexpected error editing this expense. Please try again later.

What is the root cause of that problem?

In src/pages/iou/request/step/IOURequestStepDistanceRate.tsx (lines 105–185), when determining whether the expense is a self-DM track expense (isTrackExpense = action === CONST.IOU.ACTION.TRACK or isTrackExpenseReport(report)), the route or report state after a cold restart causes updateMoneyRequestDistanceRate (src/libs/actions/IOU/UpdateMoneyRequest.ts, lines 2220–2335) to be called with inconsistent isTrackExpense / report context:

  1. When the user creates a Track Distance expense in the workspace chat and then clicks Submit it to someone from the whisper action, createTransactionThreadReport / moveIOUReportToPolicy moves the transaction from selfDM (reportID = selfDM or UNREPORTED_REPORT_ID) to a newly created expense report (iouReport).
  2. After killing and reopening the app, the user taps the transaction preview in the workspace chat or self-DM, which opens the transaction thread report (RHP). At that point, the parent expense report (iouReport) may not yet be loaded in Onyx (or report.parentReportID points to the expense report while isTrackExpense is evaluated from the original whisper action).
  3. Inside getUpdateMoneyRequestParams / getUpdateTrackExpenseParams (src/libs/actions/IOU/UpdateMoneyRequest.ts, lines 1166–1340), if iouReport is missing in Onyx or report.reportID is the transaction thread report whose parent report is not yet fetched, getUpdateMoneyRequestParams builds optimisticData and failureData (lines 2323–2333) and sends UpdateMoneyRequestDistanceRate with transactionThreadReportID. When the backend rejects the rate update (for example because the rate ID belongs to the workspace policy while the command was dispatched as a track expense or before the report's policy context is hydrated), failureData sets errorFields (getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericEditFailureMessage')), displaying Unexpected error editing this expense. Please try again later.

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

  1. In src/pages/iou/request/step/IOURequestStepDistanceRate.tsx, resolve the expense report via useReport(transaction?.reportID) in addition to the transaction thread report, and use that parent expense report's policyID (expenseReport?.policyID ?? report?.policyID) to load policy via usePolicy.
  2. Ensure that when transaction?.reportID belongs to a submitted workspace expense report (expenseReport && !isSelfDM(expenseReport)), IOURequestStepDistanceRate treats the rate update as a regular workspace money request (isPolicyExpenseChat) rather than a personal track expense, and passes policy (Workspace policy) to updateMoneyRequestDistanceRate so that getUpdateMoneyRequestParams sends valid rate and policy parameters to UpdateMoneyRequestDistanceRate.

What alternative solutions did you explore? (Optional)

We also explored waiting for OpenReport on the parent iouReport before allowing edits in MoneyRequestView, but resolving expenseReport via transaction?.reportID directly in IOURequestStepDistanceRate.tsx immediately provides the accurate policyID and report context as soon as the transaction is in Onyx.

ghost avatar Nov 08 '26 15:11 ghost

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

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

melvin-bot[bot] avatar Nov 08 '26 15:11 melvin-bot[bot]

@aimane-chnaif this issue was created 2 weeks ago. Are we close to approving a proposal? If not, what's blocking us from getting this issue assigned? Don't hesitate to create a thread in #expensify-open-source to align faster in real time. Thanks!

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

@aimane-chnaif Still overdue 6 days?! Let's take care of this!

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

@aimane-chnaif 8 days overdue is a lot. Should this be a Weekly issue? If so, feel free to change it!

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

Proposal

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

When a user creates and submits a distance expense in a workspace, force-closes and reopens the app, opens the expense from Spend / the expense report, taps Rate, selects a different workspace distance rate, and taps Save, the existing amount/distance/rate briefly turn pending without updating to the new rate, the edit fails and reverts to the original rate, and a changed the expense report action is left behind with "Unexpected error editing this expense. Please try again later."

What is the root cause of that problem?

DynamicIOURequestStepDistanceRate already loads the single transactions_${transactionID} entry via withFullTransactionOrNotFound (useOnyx) and passes transaction into updateMoneyRequestDistanceRate (DynamicIOURequestStepDistanceRate.tsx#L245-L270).

However, inside updateMoneyRequestDistanceRate:

  • The self-DM track-expense branch passes transaction to getUpdateTrackExpenseParams (L1607–1621, updated in #105656).
  • The else branch used for workspace / reported expenses calls getUpdateMoneyRequestParams (L1623–1648) with transactionID: transaction?.transactionID without forwarding transaction (unlike updateMoneyRequestDate, updateMoneyRequestMerchant, updateMoneyRequestTag, updateMoneyRequestCategory, updateMoneyRequestDescription, and updateMoneyRequestAmountAndCurrency).

Because transactionParam is omitted, getUpdateMoneyRequestParams falls back to the deprecated module-level getAllTransactions()?.[\${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`] ([src/libs/actions/IOU/index.ts#L13-L24](https://github.com/Expensify/App/blob/7bd6f6553af7208cb9067a0883691f943ea5c4f2/src/libs/actions/IOU/index.ts#L13-L24), tracked for removal in #66510). Right after a native/HybridApp cold start onto Spend, the single-key useOnyx(`transactions_${transactionID}`)subscription resolves immediately soMoneyRequestViewandDynamicIOURequestStepDistanceRaterender and allow saving, whereas the fullONYXKEYS.COLLECTION.TRANSACTIONcollection callback inIOU/index.tshas not yet populatedallTransactions[`transactions_${transactionID}`]`.

When transaction resolves to undefined at UpdateMoneyRequest.ts#L1901, every symptom seen in the reproduction video (01:12–01:17) and screenshot occurs deterministically:

  1. Pending fields without optimistic rate/amount update (01:12–01:13): pendingFields (L1911–1925) sets {customUnitRateID: 'update', merchant: 'update'}, while updatedTransaction (L1947–1959) is undefined, so optimisticData (L2156–2167) dims the existing $17.48 / Default Rate values without recalculating them.
  2. Backend rejects UpdateMoneyRequestDistanceRate: getTransactionDetails(undefined) (L1961, ReportUtils.ts#L5942-L5951) returns undefined, leaving dataToIncludeInParams (L1967) as {}. apiParams (L1975–1979) is sent with {reportID, transactionID, reportActionID} and no customUnitRateID, causing the server to reject the request.
  3. "changed the expense" message (01:17 & screenshot): getModifiedExpenseOriginalMessage skips the hasModifiedDistanceRate branch when updatedTransaction is undefined, producing an empty originalMessage that renders as "changed the expense".
  4. Generic edit failure attached to a distance expense (01:17 & screenshot): At UpdateMoneyRequest.ts#L2099-L2112, const isDistanceTransaction = transaction && isDistanceRequestTransactionUtils(transaction) evaluates to undefined instead of true, so failureData attaches iou.error.genericEditFailureMessage ("Unexpected error editing this expense. Please try again later.") instead of clearing [updatedReportAction.reportActionID]: null.

The same omission also exists in the other four UpdateMoneyRequest.ts functions that already accept transaction as a parameter (updateMoneyRequestDistance at L1233, updateMoneyRequestBillable at L410, updateMoneyRequestReimbursable at L494, and updateMoneyRequestTaxRate at L1108).

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

  1. Pass transaction directly to getUpdateMoneyRequestParams in updateMoneyRequestDistanceRate (src/libs/actions/IOU/UpdateMoneyRequest.ts#L1623-L1648), matching its getUpdateTrackExpenseParams branch right above (L1607–1621):
         } else {
             data = getUpdateMoneyRequestParams({
                 isVendorMatchingBetaEnabled,
                 transactionID: transaction?.transactionID,
    +            transaction,
                 transactionThreadReport,
                 iouReport: parentReport,
    
  2. Forward transaction in the remaining sibling getUpdateMoneyRequestParams calls in src/libs/actions/IOU/UpdateMoneyRequest.ts that already receive transaction (updateMoneyRequestBillable at L410, updateMoneyRequestReimbursable at L494, updateMoneyRequestTaxRate at L1108, and updateMoneyRequestDistance at L1233) so cold-start edits on those fields cannot fall back to an unhydrated getAllTransactions() entry either.
  3. Add a unit test in tests/actions/IOUTest.ts verifying that when updateMoneyRequestDistanceRate is called with a valid transaction prop while getAllTransactions() does not yet contain transactions_${transactionID}, the UpdateMoneyRequestDistanceRate API request includes customUnitRateID, optimistically updates amount and modifiedMerchant, builds the distance-rate MODIFIED_EXPENSE action, and clears the optimistic report action on failure.

What alternative solutions did you explore? (Optional)

  • Adjusting single-transaction thread resolution in ReportFetchHandler for deleted expenses / FAKE_REPORT_ID: In the reproduction video (Expense Report 2026-10-27), the workspace and report are newly created with a single 23.00 mi expense, no deleted expenses, and an already-created childReportID from opening the expense before restarting. Moreover, if transaction were defined in getUpdateMoneyRequestParams, optimisticData would immediately display the recalculated $46.00 / Two rate at 01:12–01:13 and failureData (isDistanceTransaction === true) would remove the optimistic action (null) rather than rendering "changed the expense" with genericEditFailureMessage.
  • Blocking edits until the full ONYXKEYS.COLLECTION.TRANSACTION Onyx.connect cache finishes hydrating: Unnecessary and contrary to the Onyx.connect deprecation (#66510), since withFullTransactionOrNotFound already provides the hydrated transaction directly to the step component and action.

cocvn157 avatar Nov 14 '26 01:11 cocvn157

This issue has not been updated in over 14 days. @aimane-chnaif eroding to Weekly issue.