Skip to content

Scan Receipt- X button is shown instead of three dots on receipt after offline scan #101902

Closed

Description

@applause-bot

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


Version Number: v9.4.91-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://test-management.browserstack.com/projects/2219752/folder/57710137/test-cases/41237716
Email or phone of affected tester (no customers): N/A
Issue reported by: Applause Internal Team
Bug source: Regression TC Execution
Device used: Windows 11 / Chrome, iPhone 13 / iOS 27 Beta, Samsung Galaxy A52 / Android 14
App Component: Chat Report View

Action Performed:

Preconditions: logged in to any account

Steps:

  1. Go to a 1:1 chat
  2. Go offline
  3. Create a Scan IOU
  4. Open the IOU details view
  5. Click on the receipt

Expected Result:

there is a 3 dot menu on the top right

Actual Result:

X button is shown instead of three dots on receipt after offline scan, so user cannot delete the receipt in offline mode

Workaround:

Unknown

Platforms:

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

Screenshots/Videos

Bug7266397_1790091279250.bandicam_2026-09-22_22-31-54-911.mp4

View all open jobs on GitHub

Applause Internal Information
Exported by: Svetlana Lazutkina
Bug ID: 7266397

Issue OwnerCurrent Issue Owner: @Eskalifer1

Activity

  1. added
    BugSomething is broken. Auto assigns a BugZero manager.
    on Sep 22, 2026
  2. applause-bot commented on Sep 22, 2026

    @applause-bot
    Author

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

  3. MelvinBot commented on Sep 22, 2026

    @MelvinBot
    Contributor

    Proposal

    What is the root cause of that problem?

    The three-dots button is only rendered when the menu has at least one item — AttachmentModalBaseContent/index.tsx:355 sets shouldShowThreeDotsButton={threeDotsMenuItems.length > 0}. For an offline scan, both items that could populate that menu are filtered out, so the array is empty and the header falls back to the close (X) button.

    The menu factory lives in TransactionReceiptModalContent.tsx:474-539. Two independent conditions both fail offline:

    1. Download is gated on (!isOffline && allowDownload && !isLocalSource) || !!draftTransactionID — :477. Offline, isOffline is true and the receipt source is still a local blob:/file: URI so isLocalSource is true. Opened from the details view there is no action param, so draftTransactionID is undefined (:95-96).
    2. Delete receipt is gated on !isReceiptBeingScanned(transaction) — :491. Every scan receipt is created with state: SCAN_READY (IOU/MoneyRequest.ts:171), and isReceiptBeingScanned returns true for SCAN_READY (TransactionUtils/index.ts:1977-1979). Nothing client-side ever advances that state — only a backend Onyx update does. So while offline the transaction is stuck at SCAN_READY forever and Delete can never appear.

    Online, the queued request returns, the source becomes an https:// URL and the state advances, so Download (then Delete) appear and the menu renders. That is the only reason the bug looks offline-specific.

    The permission check itself is not the blocker: shouldShowDeleteReceiptButton (:178) has no network dependency and is true offline.

    How the two guards got here, and why deleting offline is safe
    • The !isOffline guard on Download and the threeDotsMenuItems.length !== 0 header gate were added in the same commit, Hide download receipt button when offline (merged 2024-01-11). Before it, the button showed whenever the modal was a receipt attachment. That combination is what turns "no download offline" into "no menu at all offline".
    • The !isReceiptBeingScanned guard on Delete came from Allow detaching receipts from transactions; !hasMissingSmartscanFields was added by Hide delete option for fail scan request. The current file is the 2025 AttachmentModal.tsx → AttachmentModalScreen migration carrying all three forward.
    • hasMissingSmartscanFields is a second latent blocker: it short-circuits to false today only because isReceiptBeingScanned is already true (TransactionUtils/index.ts:2038-2040). Relaxing guard 2 without accounting for this will not surface Delete.
    • Deleting offline would actually work. deleteReceiptAndClose calls detachReceipt, a fully offline-capable API.write with complete optimistic/success/failure data and a resolveDetachReceiptConflicts conflict resolver. Nothing in it needs the network at call time.
    • No other attachment-modal route sets threeDotsMenuItems at all, so there is no existing offline-friendly precedent to copy.

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

    Two separable changes. The second is what the tester is actually asking for.

    1. Stop suppressing Delete for a scan that has not started. In the isDeletableReceipt check at TransactionReceiptModalContent.tsx:487-492, treat a never-synced expense as not-being-scanned. The signal is the transaction's own pendingAction === ADD (the create request is still queued), not isOffline — that also covers the user who reconnects before the queue flushes. Since hasMissingSmartscanFields would then start evaluating, exempt the same never-synced case there too, or the Delete item still won't appear.

    2. Don't let an offline-only filter erase the whole affordance. Either keep Download in the list and disable it offline, or make the header gate tolerant of the offline case, so the three-dots button survives when its items were removed purely for connectivity reasons.

    Change 1 alone fixes both the reported symptom and the stated grievance. Change 2 is the more general guard and is worth doing regardless.

    What alternative solutions did you explore? (Optional)

    • Revert only the threeDotsMenuItems.length !== 0 half of #34118. Cheapest fix for the title symptom, but it renders an empty menu offline — the user gets three dots that open nothing, and still cannot delete. Rejected.
    • Gate on isOffline rather than pendingAction. Simpler, but wrong at the boundary: reconnect before the queue flushes and Delete vanishes again even though the scan still hasn't started.
    • Do nothing and call it working as intended. Defensible for Download, not for Delete — an offline scan is stuck at SCAN_READY indefinitely, so "wait for the scan to finish" never resolves.

    Note on verification: I could not drive NewDot in a browser on this run, so this analysis is from code reading only. I have not confirmed the rendered header in a live offline session.


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


    view run

  4. added
    ExternalAdded to denote the issue can be worked on by a contributor
    on Sep 22, 2026
  5. melvin-bot commented on Sep 22, 2026

    @melvin-bot

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

  6. melvin-bot commented on Sep 22, 2026

    @melvin-bot

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

  7. Eskalifer1 commented on Sep 23, 2026

    @Eskalifer1
    Contributor

    @MelvinBot Could you post the code diff for your solution?

    I’m also interested in identifying the PR that introduced this regression. Looking at the TCs, the test steps seem to reflect the expected behavior, which suggests that when the feature was originally added or the bug was fixed, the behavior was correct.

    At some point, a subsequent PR appears to have changed that behavior. It would be useful to identify that PR so we can understand why the behavior changed and validate our solution properly. The goal should be to fix the current bug without unintentionally breaking any existing behavior.

  8. MelvinBot commented on Sep 23, 2026

    @MelvinBot
    Contributor

    ⏱️ Ran out of time before I could finish. This usually means the task was too complex or I got stuck exploring. Please try again with a more specific request or post in #melvinbot-ai.

    Run details

  9. Eskalifer1 commented on Sep 23, 2026

    @Eskalifer1
    Contributor

    @MelvinBot Check this comment: #101902 (comment)

  10. MelvinBot commented on Sep 23, 2026

    @MelvinBot
    Contributor

    Both answers below: the regression PR, then the diff.

    The PR that changed the behavior

    [Odometer] Redirecting to inbox on photo capture after App reload on OdometerImage screen (Expensify/App#83668), merged 2026-03-09, commit 4abc137 ("fix: removed duplicated replace button"). High confidence.

    It removed the Replace entry from threeDotsMenuItems in TransactionReceiptModalContent.tsx — de-duplicating it against the footer Replace button that feat: add crop receipt had added two weeks earlier. For an offline scan, Replace was the only menu item that survived; Download and Delete were already filtered out. Removing it emptied the array, and the pre-existing gate AttachmentModalBaseContent/index.tsx:355 (shouldShowThreeDotsButton={threeDotsMenuItems.length > 0}) then hid the button, leaving only the X.

    Verification and the full causal chain

    Offline scan, each item independently suppressed in TransactionReceiptModalContent.tsx:474-539:

    Item Gate Offline scan
    Download (!isOffline && allowDownload && !isLocalSource) || !!draftTransactionID ❌ isOffline true, source is a local blob, no action param so no draftTransactionID
    Delete … && !isReceiptBeingScanned(transaction) && !hasMissingSmartscanFields(…) ❌ optimistic receipt is SCAN_READY (TransactionUtils/index.ts:1983) and never advances offline
    Replace shouldShowReplaceReceiptButton ✅ was the only survivor — removed by #83668

    Before/after 4abc137, same file:

    • 4abc137^: line 396 if (shouldShowReplaceReceiptButton || isOdometerImage) { menuItems.push({icon: Camera, text: translate('common.replace'), …}) → menu length 1 → three dots shown, matching the BrowserStack expectation.
    • 4abc137: that 35-line block is deleted (2 insertions, 39 deletions); only the footer copy remains → menu length 0 → X only.

    I confirmed the threeDotsMenuItems.length > 0 gate was already live in that same tree, so the button vanished the moment the last item was removed.

    Ruled out:

    Latent enablers (harmless for ~2 years because Replace kept the menu non-empty): Hide download receipt button when offline added both the !isOffline Download guard and the length !== 0 header gate; Allow detaching receipts from transactions and Hide delete option for fail scan request added the two Delete guards.

    What this means for the fix: removing Replace from the menu was deliberate — it still exists as a footer button, so that half of the TC expectation is now stale. The part that is genuinely broken is the Actual Result line: the user cannot delete the receipt offline. Fixing that puts an item back in the menu, which restores the three dots as a side effect.

    The diff

    diff --git a/src/pages/media/AttachmentModalScreen/routes/TransactionReceiptModalContent.tsx b/src/pages/media/AttachmentModalScreen/routes/TransactionReceiptModalContent.tsx
    --- a/src/pages/media/AttachmentModalScreen/routes/TransactionReceiptModalContent.tsx
    +++ b/src/pages/media/AttachmentModalScreen/routes/TransactionReceiptModalContent.tsx
    @@ -484,12 +484,15 @@ function TransactionReceiptModalContent({navigation, route}: AttachmentModalScre
                 }
     
                 const hasOnlyEReceipt = hasEReceipt(transaction) && !hasReceiptSource(transaction);
    +            // A scan whose create request is still queued never leaves SCAN_READY and has no scanned fields yet,
    +            // so both scan guards below would hide Delete indefinitely while offline. Detaching is offline-capable,
    +            // so allow it for an expense that has not reached the server yet.
    +            const isUnsentExpense = transaction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD;
                 const isDeletableReceipt =
                     shouldShowDeleteReceiptButton &&
                     !hasOnlyEReceipt &&
                     hasReceipt(transaction) &&
    -                !isReceiptBeingScanned(transaction) &&
    -                !hasMissingSmartscanFields(transaction, transactionReport);
    +                (isUnsentExpense || (!isReceiptBeingScanned(transaction) && !hasMissingSmartscanFields(transaction, transactionReport)));
                 const isDraftOdometer = isOdometerImage && isDraftTransaction;
                 if (isDeletableReceipt || isDraftOdometer) {
                     menuItems.push({

    No new imports needed (CONST is already imported) and transaction is already in the useCallback dep array. npx eslint on the file reports only the 9 pre-existing errors, none in the changed region.

    Why this shape, and why it doesn't break existing behavior

    Why pendingAction, not isOffline. buildOptimisticTransaction defaults pendingAction to ADD, and the success data clears it to null. So pendingAction === ADD means exactly "the create request has not been acknowledged yet" — which also covers the user who reconnects before the queue flushes. Gating on isOffline would make Delete vanish again at that boundary even though the scan still hasn't started.

    Why both guards have to be bypassed together. hasMissingSmartscanFields short-circuits to false today only because isReceiptBeingScanned is already true (TransactionUtils/index.ts:2044-2046). Relax only the scan guard and areRequiredFieldsEmpty starts evaluating — amount 0, merchant unknown — so Delete still won't appear. Hence the single isUnsentExpense || wrapping both.

    Deleting offline actually works. deleteReceiptAndClose calls detachReceipt, a normal API.write with full optimistic/success/failure data and a resolveDetachReceiptConflicts resolver. Nothing needs the network at call time; it queues behind the create request and the server applies them in order.

    What is not changed: every currently-synced transaction (pendingAction cleared) keeps the exact old condition, so the intent of #26219 and #37954 — hide Delete while a real scan is running or a scan failed — is preserved. Replace stays in the footer; #83668's de-duplication is untouched.

    Known nuance, your call: an expense created online also has pendingAction === ADD for the ~1s before the response lands, so Delete would briefly appear then disappear if the user is already in the receipt modal during that window. If you'd rather not have that, narrow the guard to isOffline && transaction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD — at the cost of Delete vanishing again the instant connectivity returns but before the queue flushes.

    Optional second change, not in the diff. The deeper fragility is that a connectivity-only filter can erase the entire affordance. Either keep Download in the list and disable it offline, or make the header gate tolerant of the offline case. Not required to fix this bug, but it prevents the next "menu disappeared" report.


    Note on verification: browser control was unavailable on this run, so this is from code reading and git history only. I have not confirmed the rendered header in a live offline session, and the diff has been linted but not run.


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


    view run

  11. Eskalifer1 commented on Sep 23, 2026

    @Eskalifer1
    Contributor

    @MelvinBot i don't think youproposal is correct. Even after applying your changes i still don't get it.

    Here is some console.log for you:

    {
        "isUnsentExpense": true,
        "shouldShowDeleteReceiptButton": false,
        "hasOnlyEReceipt": false,
        "hasReceipt": true,
        "isDeletableReceipt": false
    }
    
    {
        "canDeleteReceipt": false,
        "readonly": true,
        "isDraftTransaction": false
    }

    Create a completely new proposal with code diffs that includes a full root cause analysis (RCA) and a fix for this issue

  12. MelvinBot commented on Sep 23, 2026

    @MelvinBot
    Contributor

    You're right, and thank you for the console output — it disproved my previous proposal. readonly: true and canDeleteReceipt: false meant the menu was already dead two components upstream of where I was looking, so relaxing isDeletableReceipt alone could never have worked. My earlier claim that [Odometer] Redirecting to inbox on photo capture after App reload on OdometerImage screen caused this was also wrong; correction at the end.

    Proposal

    What is the root cause of that problem?

    One predicate, read in three places: !isReceiptBeingScanned(transaction) in the RECEIPT branch of canEditFieldOfMoneyRequest — src/libs/ReportUtils.ts:5525.

    An offline Scan expense is created with receipt.state = SCAN_READY (IOU/MoneyRequest.ts:171), and isReceiptBeingScanned returns true for SCAN_READY (TransactionUtils/index.ts:1983-1985). Only a backend Onyx update advances that state, so while the RequestMoney request sits in the queue the expense is indistinguishable from an in-flight SmartScan — permanently, offline.

    That single false value reaches the header three separate ways, which is why your console.log shows every gate off at once:

    Your value Where it comes from
    canDeleteReceipt: false TransactionReceiptModalContent.tsx:171 → same guard, isDeleteAction: true
    readonly: true MoneyRequestReceiptView.tsx:251 computes canEditReceipt with the same guard → :773 builds the route as readonly || !canEditReceipt
    shouldShowDeleteReceiptButton: false :178 canDeleteReceipt && !readonly && … — doubly false
    isDeletableReceipt: false :487-492 re-checks !isReceiptBeingScanned again, a third copy

    Download is independently skipped offline (:477), Replace is gated on the same canEditReceipt (:177), so menuItems is empty → AttachmentModalBaseContent/index.tsx:355 sets shouldShowThreeDotsButton={threeDotsMenuItems.length > 0} to false, and the header renders only the X.

    In one line: the permission layer treats "queued locally" as "scanning", and "scanning" as "receipt is locked".

    Why it is this guard and not any of the others — I walked the whole function

    Every other guard on the path passes offline, so line 5525 is genuinely the only one that fires. Note it sits above the delete-specific isRequestor clause on :5529, which is why the edit and delete calls fail identically:

    Guard file:line Fires offline?
    !isMoneyRequestAction(reportAction) || !canEditMoneyRequest(...) ReportUtils.ts:5463 No — parentReportAction is defined
    ↳ pendingAction === ADD && !isEmptyObject(errors) ReportUtils.ts:5157 No — pendingAction is ADD but errors is empty
    ↳ IOU branch isSubmitted && isRequestor ReportUtils.ts:5178-5180 No — buildOptimisticIOUReport sets state/status to SUBMITTED
    isSettled || isReportApproved ReportUtils.ts:5491 No
    canEditExpense / isRequestor ReportUtils.ts:5391-5410 No — you created it
    !isReceiptBeingScanned(transaction) ReportUtils.ts:5525 Yes

    parentReportAction resolves fine: the transaction thread is built optimistically with both parentReportID and parentReportActionID (ReportUtils.ts:9631-9632) and the IOU create action is written into the parent's report-actions key (MoneyRequestBuilder.ts:645-658), so getReportAction finds it.

    Also worth knowing: the readonly prop is false here. The details view renders MoneyRequestReceiptView without it (ReportActionItemContentCreated.tsx:98-103); only the duplicate/merge flows pass it truthy. So readonly=true in your URL is entirely !canEditReceipt — a symptom, not a second cause.

    And this is not 1:1-specific: an offline Scan on a workspace expense hits the same guard. The 1:1 IOU path is just the repro in the TC.

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

    Distinguish "queued locally" from "scan in progress". While transaction.pendingAction === ADD the create request has not reached the server, so no scan can be running; SCAN_READY there means "waiting to be uploaded".

    diff --git a/src/libs/ReportUtils.ts b/src/libs/ReportUtils.ts
    --- a/src/libs/ReportUtils.ts
    +++ b/src/libs/ReportUtils.ts
    @@ -5519,10 +5519,14 @@ function canEditFieldOfMoneyRequest({
         }
     
         if (fieldToEdit === CONST.EDIT_REQUEST_FIELD.RECEIPT) {
    +        // A transaction whose creation is still queued has not reached SmartScan yet, so its SCAN_READY state means
    +        // "waiting to be uploaded", not "a scan is running". Offline that state never advances, so treating it as
    +        // scanning would lock the receipt forever.
    +        const isScanInProgress = isReceiptBeingScanned(transaction) && transaction?.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD;
             return (
                 !isClosedReport(moneyRequestReport) &&
                 !isInvoiceReport(moneyRequestReport) &&
    -            !isReceiptBeingScanned(transaction) &&
    +            !isScanInProgress &&
                 !isPerDiemRequest(transaction) &&
                 (!isDistanceRequest(transaction) || isManualDistanceRequestTransactionUtils(transaction)) &&
                 canEditExpense &&
    diff --git a/src/pages/media/AttachmentModalScreen/routes/TransactionReceiptModalContent.tsx b/src/pages/media/AttachmentModalScreen/routes/TransactionReceiptModalContent.tsx
    --- a/src/pages/media/AttachmentModalScreen/routes/TransactionReceiptModalContent.tsx
    +++ b/src/pages/media/AttachmentModalScreen/routes/TransactionReceiptModalContent.tsx
    @@ -484,12 +484,10 @@ function TransactionReceiptModalContent({navigation, route}: AttachmentModalScre
                 }
     
                 const hasOnlyEReceipt = hasEReceipt(transaction) && !hasReceiptSource(transaction);
    +            // Mirrors the scan check in canEditFieldOfMoneyRequest: a queued expense is not scanning yet.
    +            const isScanInProgress = isReceiptBeingScanned(transaction) && transaction?.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD;
                 const isDeletableReceipt =
    -                shouldShowDeleteReceiptButton &&
    -                !hasOnlyEReceipt &&
    -                hasReceipt(transaction) &&
    -                !isReceiptBeingScanned(transaction) &&
    -                !hasMissingSmartscanFields(transaction, transactionReport);
    +                shouldShowDeleteReceiptButton && !hasOnlyEReceipt && hasReceipt(transaction) && !isScanInProgress && !hasMissingSmartscanFields(transaction, transactionReport);
                 const isDraftOdometer = isOdometerImage && isDraftTransaction;
                 if (isDeletableReceipt || isDraftOdometer) {
                     menuItems.push({

    No change to MoneyRequestReceiptView, ReportActionItemImage, or ROUTES.ts is needed — readonly flips to false on its own once canEditReceipt is true, since both call the patched function. Both hunks are required: patch 1 alone leaves the third copy at :491 blocking, patch 2 alone leaves canDeleteReceipt/readonly blocking.

    Leave hasMissingSmartscanFields (:492) alone — it internally re-checks isReceiptBeingScanned (TransactionUtils/index.ts:2044-2046), which stays true, so it keeps returning false and does not re-block the item.

    Validation, blast radius, and the two risks worth your call

    What I ran (patch applied locally, then reverted):

    • npm run typecheck — passed (all 5 projects).
    • npx eslint on both files — no errors in the changed regions. The 107 reported are pre-existing/grandfathered. One real finding I fixed while iterating: naming the local isScanning shadowed an outer binding at ReportUtils.ts:290, hence isScanInProgress.
    • I could not run Jest in this environment. I did read tests/unit/canEditFieldOfMoneyRequestTest.ts: none of its 12 RECEIPT cases set receipt.state or pendingAction, so none exercise this guard and none can flip. A new case for "queued scan → receipt is deletable" would be worth adding.
    • I could not verify in a browser — the handed-over web session never rendered (blank page, 0 snapshot nodes), so the offline repro could not be driven. This fix is unverified at runtime.

    Blast radius — canEditFieldOfMoneyRequest(…, RECEIPT) has exactly 4 call sites, all receipt add/replace/delete affordances: TransactionReceiptModalContent.tsx:170 and :171, MoneyRequestReceiptView.tsx:256, useShouldAddOrReplaceReceipt.ts:40. All four become available for a queued expense, which is the offline-first behavior we want. Every currently-synced transaction keeps the exact old condition.

    Deleting offline works. deleteReceiptAndClose calls detachReceipt, a normal API.write with full optimistic/success/failure data and a resolveDetachReceiptConflicts resolver. It queues behind RequestMoney and the server applies them in order. Please confirm that ordering in QA — I could not exercise it.

    Risk 1 (needs your call): pendingAction === ADD is also briefly true online, for the ~1s before the response clears it. So Delete/Replace would appear for about a second on an online scan if the user is already in the modal. Threading isOffline into canEditFieldOfMoneyRequest to avoid this would touch ~40 call sites and is not worth it; if the flash is unacceptable, prefer the alternative below.

    Risk 2: after detaching, the expense is left partial (amount 0, PARTIAL_TRANSACTION_MERCHANT) with a queued RequestMoney. That is a legitimate state the user can fill in, but it is a product decision worth confirming.

    What alternative solutions did you explore? (Optional)

    • Gate on SCANNING only, not SCAN_READY. Semantically the cleanest: SCAN_READY means "queued for scanning", SCANNING means "the backend is working on it". It fixes the online flash too. I did not pick it because isReceiptBeingScanned has ~60 call sites driving scanning UI everywhere, so changing what it means is a much larger behavioral change than this bug warrants. If the team prefers it, it belongs in a separate PR.
    • Relax only isDeletableReceipt — my previous proposal. Your console.log proves it cannot work: shouldShowDeleteReceiptButton is already false.
    • Make the header gate tolerant of an empty offline menu. Restores the three dots, but they would open a menu with nothing actionable. Treats the symptom, not the cause.
    • Do nothing. Not defensible: offline the expense is stuck at SCAN_READY indefinitely, so "wait for the scan to finish" never resolves.

    Correction to my earlier comment on the regression PR

    My previous comment named #83668 as the regression. That was wrong — I had missed that Replace is gated on the same canEditReceipt. I fetched the file at 7fb25a9, the commit immediately before it, and confirmed shouldShowReplaceReceiptButton = ((canEditReceipt && !readonly) || isDraftTransaction) && …, which is already false offline. Replace was not a survivor; the menu was already empty before #83668 touched it.

    What the history actually shows:

    • The X-instead-of-three-dots symptom dates to Hide download receipt button when offline, merged 2024-01-11. Its diff changes shouldShowThreeDotsButton = props.isReceiptAttachment && isModalOpen to … && threeDotsMenuItems.length !== 0 and adds the if (!isOffline) guard around Download in the same commit. Before it, the three dots always rendered for a receipt and Download was in the menu offline.
    • The inability to delete offline is not a regression at all. I fetched ReportUtils.ts at ca3c4db (Hide download receipt button when offline #34118's merge commit, Jan 2024): the RECEIPT branch already read return !TransactionUtils.isReceiptBeingScanned(transaction) && !TransactionUtils.isDistanceRequest(transaction) && isRequestor;. The guard predates the symptom, so this flow has never worked offline — the TC expectation reflects the online flow, not a behavior we later broke.

    Note on verification: typecheck and lint pass, but I could not run Jest or drive a browser on this run, so the fix is unverified at runtime.


    Next Steps for Contributor+ team:
    To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/101902) 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

  13. 11 remaining items

  14. trasnake87 commented on Sep 24, 2026

    @trasnake87
    Contributor

    Proposal

    What is the root cause of that problem?

    Worth checking against the code first: narrowing isReceiptBeingScanned to match only SCANNING and not SCAN_READY is not merely a wide-blast-radius refactor — on this path it does not fix the bug at all. isDeletableReceipt ends in !hasMissingSmartscanFields(...), and that helper is !isReceiptBeingScanned(transaction) && areRequiredFieldsEmpty(transaction):

    */
    function hasMissingSmartscanFields(transaction: OnyxInputOrEntry<Transaction>, transactionReport: OnyxEntry<Report>): boolean {
    return !!(transaction && !isDistanceRequest(transaction) && !isReceiptBeingScanned(transaction) && areRequiredFieldsEmpty(transaction, transactionReport));

    Here areRequiredFieldsEmpty returns true — the parent is an IOU report, not an expense report, so isZeroAmountAllowed is false and the partial scan's getAmount() is 0:

    function areRequiredFieldsEmpty(transaction: OnyxEntry<Transaction>, transactionReport: OnyxEntry<Report>): boolean {
    const isFromExpenseReport = transactionReport?.type === CONST.REPORT.TYPE.EXPENSE;
    // A zero amount is a deliberate, valid choice for an unreported expense, so it isn't a missing field there. It is never
    // a missing field on an expense report either, where only the merchant is checked.
    const isZeroAmountAllowed = isFromExpenseReport || isExpenseUnreported(transaction);
    return (isFromExpenseReport && isMerchantMissing(transaction)) || isCreatedMissing(transaction) || (!isZeroAmountAllowed && getAmount(transaction) === 0);
    }

    So hasMissingSmartscanFields returns false today only because the transaction reads as scanning. Flip isReceiptBeingScanned and it flips to true, re-blocking the very item being unblocked. The fix must be a new predicate above that term, with isReceiptBeingScanned left as it is.

    The mechanism: the tell is the asymmetry between deleting the expense and deleting its receipt on the same offline Scan. Deleting the expense is allowed — isDeleteAction routes to canDeleteMoneyRequestReport, whose IOU branch is only isSingleTransaction && isOwner && isReportOpenOrProcessing, all true for the optimistic 1:1 IOU report, with zero scan checks:

    App/src/libs/ReportUtils.ts

    Lines 3270 to 3274 in c134a8d

    // Users cannot delete a report in the unreported or IOU cases, but they can delete individual transactions.
    // So we check if the reportTransactions length is 1 which means they're viewing a single transaction and thus can delete it.
    if (isIOUReport(report)) {
    return isSingleTransaction && isOwner && isReportOpenOrProcessing;
    }

    A queued, un-synced Scan expense is already mutable offline by design. The receipt-level gate is the outlier:

    App/src/libs/ReportUtils.ts

    Lines 5521 to 5529 in c134a8d

    if (fieldToEdit === CONST.EDIT_REQUEST_FIELD.RECEIPT) {
    return (
    !isClosedReport(moneyRequestReport) &&
    !isInvoiceReport(moneyRequestReport) &&
    !isReceiptBeingScanned(transaction) &&
    !isPerDiemRequest(transaction) &&
    (!isDistanceRequest(transaction) || isManualDistanceRequestTransactionUtils(transaction)) &&
    canEditExpense &&
    (isDeleteAction ? isRequestor : true)

    buildOptimisticTransaction stamps the offline Scan with pendingAction: ADD and receipt.state: SCAN_READY in one literal:

    pendingAction,
    receipt: receipt?.source
    ? {
    source: receipt.source,
    filename: receipt?.name ?? filename,
    state: receiptState ?? receipt.state ?? CONST.IOU.RECEIPT_STATE.SCAN_READY,
    isTestDriveReceipt: receipt.isTestDriveReceipt,

    and isReceiptBeingScanned treats SCAN_READY as "scanning":

    function isReceiptBeingScanned(transaction: OnyxInputOrEntry<Transaction>): boolean {
    return transaction?.receipt?.state === CONST.IOU.RECEIPT_STATE.SCAN_READY || transaction?.receipt?.state === CONST.IOU.RECEIPT_STATE.SCANNING;
    }

    Only a server OnyxUpdate advances that state, so while RequestMoney sits in the SequentialQueue the expense is indistinguishable from a real in-flight SmartScan — permanently, offline. Every other guard in canEditFieldOfMoneyRequest passes (the bail at :5157 needs errors, which are empty; the IOU branch at :5178 needs isSubmitted && isRequestor, both true), so :5525 is the only one that fires. It reaches the header three ways: canDeleteReceipt and canEditReceipt at TransactionReceiptModalContent.tsx:170-171, and the readonly route param, which MoneyRequestReceiptView builds as readonly || !canEditReceipt (:710, :773) — so readonly=true is a symptom of this guard, not a second cause. A fourth, independent copy sits in the menu factory:

    const isDeletableReceipt =
    shouldShowDeleteReceiptButton &&
    !hasOnlyEReceipt &&
    hasReceipt(transaction) &&
    !isReceiptBeingScanned(transaction) &&
    !hasMissingSmartscanFields(transaction, transactionReport);

    Download is legitimately skipped offline (:477), so menuItems is empty and the header gate collapses to the X:

    shouldShowThreeDotsButton={threeDotsMenuItems.length > 0}

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

    Add one exported helper next to isReceiptBeingScanned in src/libs/TransactionUtils/index.ts, leaving that function itself untouched so the hasMissingSmartscanFields term keeps its current value:

    /**
     * SmartScan only starts once the receipt is uploaded, so a transaction whose own creation is still queued
     * (pendingAction ADD) is not scanning — SCAN_READY there means "waiting to be uploaded", and offline that
     * state never advances.
     */
    function isReceiptBeingScannedOnServer(transaction: OnyxInputOrEntry<Transaction>): boolean {
        return isReceiptBeingScanned(transaction) && transaction?.pendingAction !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD;
    }

    Then swap the two blocking call sites, ReportUtils.ts:5525 and TransactionReceiptModalContent.tsx:490:

    -            !isReceiptBeingScanned(transaction) &&
    +            !isReceiptBeingScannedOnServer(transaction) &&

    Both hunks are required: the first alone leaves the modal's own copy blocking; the second alone leaves canDeleteReceipt/readonly blocking. readonly flips to false on its own since it derives from canEditReceipt. Nothing else changes — the distinction lives once, named, beside the function it qualifies.

    Blast radius: the four EDIT_REQUEST_FIELD.RECEIPT call sites (TransactionReceiptModalContent.tsx:170-171, MoneyRequestReceiptView.tsx:256, useShouldAddOrReplaceReceipt.ts:40) — all add/replace/delete affordances that should be live for a queued expense. Synced transactions keep the old condition exactly, as pendingAction is cleared by the create response.

    I'm deliberately not threading isOffline in: pendingAction: ADD means the create has not reached the server either way, and detachReceipt is a normal API.write that queues behind RequestMoney. Its conflict resolver only dedupes REPLACE_RECEIPT and otherwise falls through to a plain push, so ordering holds:

    if (indicesToDelete.length === 0) {
    return {
    conflictAction: {
    type: 'push',
    },
    };
    }

    QA note: after detaching, the expense stays partial (amount: 0, PARTIAL_TRANSACTION_MERCHANT) with the create still queued — the same state as detaching a receipt on any scan, and the fields stay editable. I'd add a RECEIPT case to tests/unit/canEditFieldOfMoneyRequestTest.ts setting receipt.state: SCAN_READY with pendingAction: ADD; no existing case sets either field, so none move.

    What alternative solutions did you explore?

    Gating isReceiptBeingScanned on SCANNING only — rejected for the reason above, plus it silently changes ~60 call sites driving scanning UI. Making the header tolerate an empty menu — rejected: it restores the three dots over a menu with nothing in it.

  15. paulnjs commented on Sep 24, 2026

    @paulnjs
    Contributor

    Proposal

    What is the root cause of that problem?

    The three-dots menu only renders when it has items. Offline, Download is dropped, and Delete is blocked because the receipt sits at SCAN_READY - which we treat as still scanning - even though SmartScan can’t run until the create (or replace) actually syncs. So the menu is empty and the header shows X instead.

    shouldShowThreeDotsButton={threeDotsMenuItems.length > 0}
    threeDotsMenuItems={threeDotsMenuItems}

    function isReceiptBeingScanned(transaction: OnyxInputOrEntry<Transaction>): boolean {
    return transaction?.receipt?.state === CONST.IOU.RECEIPT_STATE.SCAN_READY || transaction?.receipt?.state === CONST.IOU.RECEIPT_STATE.SCANNING;
    }

    App/src/libs/ReportUtils.ts

    Lines 5504 to 5509 in 8c11276

    if (fieldToEdit === CONST.EDIT_REQUEST_FIELD.RECEIPT) {
    return (
    !isClosedReport(moneyRequestReport) &&
    !isInvoiceReport(moneyRequestReport) &&
    !isReceiptBeingScanned(transaction) &&
    !isPerDiemRequest(transaction) &&

    const isDeletableReceipt =
    shouldShowDeleteReceiptButton &&
    !hasOnlyEReceipt &&
    hasReceipt(transaction) &&

    Same idea after delete -> re-add: the replace is still pending (pendingFields.receipt), fields are empty, and hasMissingSmartscanFields hides Delete again.

    Detach already works offline — we’re just not offering it.

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

    Treat a queued create or receipt attach/replace as "scan has not really started", and allow Delete in that case.

    1. Add a helper for a pending create or pending receipt field write:
      function isReceiptBeingScanned(transaction: OnyxInputOrEntry<Transaction>): boolean {
      return transaction?.receipt?.state === CONST.IOU.RECEIPT_STATE.SCAN_READY || transaction?.receipt?.state === CONST.IOU.RECEIPT_STATE.SCANNING;
      }
    function hasPendingReceiptWrite(transaction) {
        const pendingReceiptField = transaction?.pendingFields?.receipt;
        return (
            transaction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD ||
            pendingReceiptField === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD ||
            pendingReceiptField === CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE
        );
    }
    1. In receipt permission checks, do not block on isReceiptBeingScanned while that helper is true:

      App/src/libs/ReportUtils.ts

      Lines 5504 to 5509 in 8c11276

      if (fieldToEdit === CONST.EDIT_REQUEST_FIELD.RECEIPT) {
      return (
      !isClosedReport(moneyRequestReport) &&
      !isInvoiceReport(moneyRequestReport) &&
      !isReceiptBeingScanned(transaction) &&
      !isPerDiemRequest(transaction) &&
    const isReceiptScanBlockingEdit = isReceiptBeingScanned(transaction) && !hasPendingReceiptWrite(transaction);
    
    return (
        !isClosedReport(moneyRequestReport) &&
        !isInvoiceReport(moneyRequestReport) &&
        !isReceiptScanBlockingEdit &&
        !isPerDiemRequest(transaction) &&
        (!isDistanceRequest(transaction) || isManualDistanceRequestTransactionUtils(transaction)) &&
        canEditExpense &&
        (isDeleteAction ? isRequestor : true)
    );
    1. In the receipt modal menu, use the same exemption for Delete (including hasMissingSmartscanFields), and keep Download in the list but disabled offline when it would otherwise be dropped only for connectivity:
      if ((!isOffline && allowDownload && !isLocalSource) || !!draftTransactionID) {
      menuItems.push({
      icon: expensifyIcons.Download,
      text: translate('common.download'),
      onSelected: () => onDownloadAttachment({source: innerSource, file}),
      sentryLabel: CONST.SENTRY_LABEL.RECEIPT_MODAL.DOWNLOAD_RECEIPT,
      });
      }
      const hasOnlyEReceipt = hasEReceipt(transaction) && !hasReceiptSource(transaction);
      const isDeletableReceipt =
      shouldShowDeleteReceiptButton &&
      !hasOnlyEReceipt &&
      hasReceipt(transaction) &&
    if ((allowDownload && !isLocalSource) || !!draftTransactionID) {
        menuItems.push({
            icon: expensifyIcons.Download,
            text: translate('common.download'),
            onSelected: () => onDownloadAttachment({source: innerSource, file}),
            disabled: isOffline && !draftTransactionID,
            sentryLabel: CONST.SENTRY_LABEL.RECEIPT_MODAL.DOWNLOAD_RECEIPT,
        });
    }
    
    const isReceiptWritePending = hasPendingReceiptWrite(transaction);
    const isDeletableReceipt =
        shouldShowDeleteReceiptButton &&
        !hasOnlyEReceipt &&
        hasReceipt(transaction) &&
        (!isReceiptBeingScanned(transaction) || isReceiptWritePending) &&
        (!hasMissingSmartscanFields(transaction, transactionReport) || isReceiptWritePending);

    Once the write syncs and SmartScan is actually running, Delete stays hidden as today. After scan completes, Delete shows when the user is allowed to edit the expense.

    What alternative solutions did you explore? (Optional)

    N/A

    Screen.Recording.2026-09-23.at.18.03.36.mov
  16. yusufdeveloper2903 commented on Sep 24, 2026

    @yusufdeveloper2903
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-09-24 10:31:54 UTC.

    Proposal

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

    After a Scan expense is created offline, the receipt modal shows only the X instead of the three-dot menu, so the receipt cannot be deleted offline.

    What is the root cause of that problem?

    I reproduced this on current main against the production backend with no code changes. After the steps below, the receipt modal shows only the X and the route carries readonly=true. In Onyx the transaction has receipt.state: SCANREADY, pendingAction: add and a blob: source, and RequestMoney is waiting in the queue.

    1. Open a 1:1 chat and turn on Force offline.
    2. Choose + > Create expense > Scan, pick an image, and create the expense.
    3. Open the expense details and click the receipt.

    [[ATTACH EXTERNAL/evidence/101902/before-web.png]]

    Every scan is created as SCAN_READY, and nothing changes that state until the server answers:

    receipt.state = CONST.IOU.RECEIPT_STATE.SCAN_READY;

    The RECEIPT branch of canEditFieldOfMoneyRequest returns false while a receipt is SCAN_READY or SCANNING. So canEditReceipt and canDeleteReceipt are both false, and the details view opens the modal as readonly:

    App/src/libs/ReportUtils.ts

    Lines 5521 to 5530 in c134a8d

    if (fieldToEdit === CONST.EDIT_REQUEST_FIELD.RECEIPT) {
    return (
    !isClosedReport(moneyRequestReport) &&
    !isInvoiceReport(moneyRequestReport) &&
    !isReceiptBeingScanned(transaction) &&
    !isPerDiemRequest(transaction) &&
    (!isDistanceRequest(transaction) || isManualDistanceRequestTransactionUtils(transaction)) &&
    canEditExpense &&
    (isDeleteAction ? isRequestor : true)
    );

    const parentReportAction = getReportAction(report?.parentReportID, report?.parentReportActionID);
    const canEditReceipt = canEditFieldOfMoneyRequest({reportAction: parentReportAction, fieldToEdit: CONST.EDIT_REQUEST_FIELD.RECEIPT, transaction, rules});
    const canDeleteReceipt = canEditFieldOfMoneyRequest({reportAction: parentReportAction, fieldToEdit: CONST.EDIT_REQUEST_FIELD.RECEIPT, isDeleteAction: true, transaction, rules});
    const receiptFilename = transaction?.receipt?.filename;
    const isStitchedOdometerReceipt = isOdometerDistanceRequest(transaction) && !imageType;
    const canEditReceiptButtons = ((canEditReceipt && !readonly) || isDraftTransaction) && !transaction?.receipt?.isTestDriveReceipt;
    const shouldShowReplaceReceiptButton = canEditReceiptButtons && !isStitchedOdometerReceipt;
    const shouldShowDeleteReceiptButton = canDeleteReceipt && !readonly && !isDraftTransaction && !transaction?.receipt?.isTestDriveReceipt;

    Online, Download is the only item in the menu while a scan runs. Offline it is dropped, so the menu is empty and the header falls back to the X:

    if ((!isOffline && allowDownload && !isLocalSource) || !!draftTransactionID) {

    shouldShowThreeDotsButton={threeDotsMenuItems.length > 0}

    Which PR changed it

    I looked for a regression and found none after January 2024. #34118 (merged 2024-01-11) added both the !isOffline check on Download and the check that hides the dots when the menu is empty. Before that PR the dots always showed, with Download inside them even offline, and that is the behaviour the test case describes. I also checked the candidates raised on this thread against the older code:

    • [Odometer] Redirecting to inbox on photo capture after App reload on OdometerImage screen #83668, which moved Replace out of the menu: Replace uses the same canEditReceipt, which was already false for a SCANREADY receipt in Oct 2025 (f05f7b7f501) and Jan 2025 (2b5511cc6fd).
    • 89659b93a75 (2026-08-12), which changed the role check in this branch: it still checks the same four roles, so the behaviour did not change.
    • A scan created with a different state: scans were already created as SCANREADY in Jan 2025.

    Why Delete cannot be offered for a queued scan

    Every code proposal on this thread adds Delete for a queued scan, either through a pendingAction === ADD exemption or an isOffline exemption. Both rely on the backend accepting the delete on reconnect. I built the pendingAction version in both gates and ran the same steps:

    Diff I tested
    @@ src/libs/ReportUtils.ts (canEditFieldOfMoneyRequest, RECEIPT branch)
    -            !isReceiptBeingScanned(transaction) &&
    +            (!isReceiptBeingScanned(transaction) || transaction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD) &&
    @@ src/pages/media/AttachmentModalScreen/routes/TransactionReceiptModalContent.tsx (isDeletableReceipt)
    -                !isReceiptBeingScanned(transaction) &&
    -                !hasMissingSmartscanFields(transaction, transactionReport);
    +                (transaction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD || (!isReceiptBeingScanned(transaction) && !hasMissingSmartscanFields(transaction, transactionReport)));

    The dots appear, and Delete receipt clears the receipt while offline:

    [[ATTACH EXTERNAL/evidence/101902/rival-fix-offline.png]]

    Then I turned Force offline off. The queue sent RequestMoney, which returned 200, and then DetachReceipt, which returned 405 Cannot detach receipt from partial transaction. The backend does not detach a receipt from an expense that has not been scanned yet. The client already follows the same rule online through isReceiptBeingScanned / hasMissingSmartscanFields.

    The failed request then leaves the expense in a worse state than before. failureData spreads the transaction as it was when Delete was pressed, including pendingAction: add and the dead blob: source, on top of the successful create:

    const failureData: Array<
    OnyxUpdate<typeof ONYXKEYS.COLLECTION.TRANSACTION | typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS | typeof ONYXKEYS.COLLECTION.REPORT | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS>
    > = [
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
    value: {
    ...(transaction ?? null),
    errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.receiptDeleteFailureError'),
    pendingFields: {

    The conflict resolver only removes queued ReplaceReceipt requests, so the RequestMoney that uploads the receipt still runs first:

    function resolveDetachReceiptConflicts<TKey extends OnyxKey>(persistedRequests: Array<OnyxRequest<TKey>>, parameters: DetachReceiptParams): ConflictActionData {
    const indicesToDelete: number[] = [];
    for (const [index, request] of persistedRequests.entries()) {
    if (request.command !== WRITE_COMMANDS.REPLACE_RECEIPT || request.data?.transactionID !== parameters.transactionID) {
    continue;
    }
    indicesToDelete.push(index);
    }

    After a reload the server's receipt is back (SCANFAILED), pendingAction: add is still set, and the user sees "Unexpected error deleting this receipt" and "Unexpected error editing this expense":

    [[ATTACH EXTERNAL/evidence/101902/rival-fix-after-reconnect.png]]

    Because pendingAction: add stays on the synced expense, the exemption also keeps Delete and Replace visible there, and every new attempt fails the same way. The isOffline version sends the same DetachReceipt after the same RequestMoney, so it ends in the same 405.

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

    Keep the permission gates as they are, and update the test case. For a scan that has not synced yet, the X is the correct header. The only action the menu could hold is Delete, and the backend refuses it. Download has been hidden offline on purpose since #34118. Online, the same receipt shows the dots only because Download is available, never Delete.

    Suggested test-case wording: "Offline, the receipt of an unsynced Scan expense shows only the close button. After going online, the three-dot menu shows Download, and Delete receipt appears once SmartScan has filled in the expense."

    If product still wants a menu here, the only item that works offline is Download of the local file. But 955009bd8da (2024-07-29) removed it on purpose because local sources go stale. I saw that happen: after a reload the offline receipt's blob: URL no longer loads. I would not bring it back just to fill the menu.

    What alternative solutions did you explore? (Optional)

    • Exempt pendingAction === ADD from the scan check. Most proposals here use this, and it is the only version that brings the dots back, because changing only isDeletableReceipt still leaves readonly=true. I measured it above: DetachReceipt returns 405 on reconnect, and the rollback leaves the expense with a stale pendingAction: add and two errors.
    • Gate on isOffline. It sends the same DetachReceipt after the same RequestMoney, so it ends in the same 405.
    • Always show the dots. They would open an empty menu.
  17. nabi-ebrahimi commented on Sep 24, 2026

    @nabi-ebrahimi

    🚨 Edited by proposal-police: This proposal was edited at 2026-09-24 13:00:40 UTC.

    Proposal

    What is the root cause of that problem?

    An offline Scan expense is created optimistically with pendingAction: ADD and receipt.state: SCAN_READY.

    return {
    ...(!isEmptyObject(pendingFields) ? {pendingFields} : {}),
    transactionID,
    amount,
    currency,
    reportID,
    comment: commentJSON,
    merchant: merchant || (isManualTransaction ? CONST.TRANSACTION.DEFAULT_MERCHANT : CONST.TRANSACTION.PARTIAL_TRANSACTION_MERCHANT),
    created: created || DateUtils.getDBTime(),
    pendingAction,
    receipt: receipt?.source
    ? {
    source: receipt.source,
    filename: receipt?.name ?? filename,
    state: receiptState ?? receipt.state ?? CONST.IOU.RECEIPT_STATE.SCAN_READY,
    isTestDriveReceipt: receipt.isTestDriveReceipt,
    pageCount: receipt.pageCount,
    }

    isReceiptBeingScanned() treats both SCAN_READY and SCANNING as an active scan. While the create request is queued offline, the backend cannot advance that state, so the receipt remains locked even though SmartScan has not started.

    function isReceiptBeingScanned(transaction: OnyxInputOrEntry<Transaction>): boolean {
    return transaction?.receipt?.state === CONST.IOU.RECEIPT_STATE.SCAN_READY || transaction?.receipt?.state === CONST.IOU.RECEIPT_STATE.SCANNING;
    }

    The receipt permission check therefore returns false. This makes the receipt route read-only, makes canDeleteReceipt false, and the modal repeats the same scan check before adding Delete.

    App/src/libs/ReportUtils.ts

    Lines 5521 to 5530 in c134a8d

    if (fieldToEdit === CONST.EDIT_REQUEST_FIELD.RECEIPT) {
    return (
    !isClosedReport(moneyRequestReport) &&
    !isInvoiceReport(moneyRequestReport) &&
    !isReceiptBeingScanned(transaction) &&
    !isPerDiemRequest(transaction) &&
    (!isDistanceRequest(transaction) || isManualDistanceRequestTransactionUtils(transaction)) &&
    canEditExpense &&
    (isDeleteAction ? isRequestor : true)
    );

    const parentReportAction = getReportAction(report?.parentReportID, report?.parentReportActionID);
    const canEditReceipt = canEditFieldOfMoneyRequest({reportAction: parentReportAction, fieldToEdit: CONST.EDIT_REQUEST_FIELD.RECEIPT, transaction, rules});
    const canDeleteReceipt = canEditFieldOfMoneyRequest({reportAction: parentReportAction, fieldToEdit: CONST.EDIT_REQUEST_FIELD.RECEIPT, isDeleteAction: true, transaction, rules});
    const receiptFilename = transaction?.receipt?.filename;
    const isStitchedOdometerReceipt = isOdometerDistanceRequest(transaction) && !imageType;
    const canEditReceiptButtons = ((canEditReceipt && !readonly) || isDraftTransaction) && !transaction?.receipt?.isTestDriveReceipt;
    const shouldShowReplaceReceiptButton = canEditReceiptButtons && !isStitchedOdometerReceipt;
    const shouldShowDeleteReceiptButton = canDeleteReceipt && !readonly && !isDraftTransaction && !transaction?.receipt?.isTestDriveReceipt;

    const threeDotsMenuItems: ThreeDotsMenuItemFactory = useCallback(
    ({file, source: innerSource, isLocalSource}) => {
    const menuItems = [];
    if ((!isOffline && allowDownload && !isLocalSource) || !!draftTransactionID) {
    menuItems.push({
    icon: expensifyIcons.Download,
    text: translate('common.download'),
    onSelected: () => onDownloadAttachment({source: innerSource, file}),
    sentryLabel: CONST.SENTRY_LABEL.RECEIPT_MODAL.DOWNLOAD_RECEIPT,
    });
    }
    const hasOnlyEReceipt = hasEReceipt(transaction) && !hasReceiptSource(transaction);
    const isDeletableReceipt =
    shouldShowDeleteReceiptButton &&
    !hasOnlyEReceipt &&
    hasReceipt(transaction) &&
    !isReceiptBeingScanned(transaction) &&
    !hasMissingSmartscanFields(transaction, transactionReport);

    Download is also unavailable offline, leaving the menu empty. AttachmentModalBaseContent only renders the three-dot button when the menu has an item, so it shows the X instead.

    isRotating={isRotating}
    shouldDisplayHelpButton={shouldDisplayHelpButton}
    onDownloadButtonPress={() => onDownloadAttachment?.({file: fileToDisplay, source})}
    shouldShowCloseButton={!shouldUseNarrowLayout}
    shouldShowBackButton={shouldUseNarrowLayout}
    onBackButtonPress={onClose}
    onCloseButtonPress={onClose}
    shouldShowThreeDotsButton={threeDotsMenuItems.length > 0}
    threeDotsMenuItems={threeDotsMenuItems}

    The icon change can be traced to PR #34118. Comparing its merge commit with its first parent shows that it removed Download offline and hid empty menus. Delete was already blocked for scanning receipts in the parent; the original detach feature (#26219) introduced that restriction. PR #83668 is not the cause: before its Replace-menu removal, Replace was already blocked by the same receipt permission.

    if (!isOffline) {
    menuItems.push({
    icon: Expensicons.Download,
    text: props.translate('common.download'),
    onSelected: () => downloadAttachment(source),
    });
    }
    if (TransactionUtils.hasReceipt(props.transaction) && !TransactionUtils.isReceiptBeingScanned(props.transaction) && props.canEditReceipt) {
    menuItems.push({
    icon: Expensicons.Trashcan,
    text: props.translate('receipt.deleteReceipt'),
    onSelected: () => {
    setIsDeleteReceiptConfirmModalVisible(true);
    },
    });
    }
    return menuItems;
    // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [props.isReceiptAttachment, props.parentReport, props.parentReportActions, props.policy, props.transaction, file, source]);
    // There are a few things that shouldn't be set until we absolutely know if the file is a receipt or an attachment.
    // props.isReceiptAttachment will be null until its certain what the file is, in which case it will then be true|false.
    let headerTitle = props.headerTitle;
    let shouldShowDownloadButton = false;
    let shouldShowThreeDotsButton = false;
    if (!_.isEmpty(props.report)) {
    headerTitle = translate(props.isReceiptAttachment ? 'common.receipt' : 'common.attachment');
    shouldShowDownloadButton = props.allowDownload && isDownloadButtonReadyToBeShown && !props.isReceiptAttachment && !isOffline;
    shouldShowThreeDotsButton = props.isReceiptAttachment && isModalOpen && threeDotsMenuItems.length !== 0;

    There is also a backend constraint that an App-only exemption cannot solve. In the manual reproduction, RequestMoney succeeded with jsonCode: 200, followed by DetachReceipt with HTTP 200 but jsonCode: 405 and Cannot detach receipt from partial transaction. After the queue drained, the receipt was present as SCANFAILED, with a receipt-delete error and stale pendingAction: ADD. The detach failure data spreads the old transaction snapshot back into Onyx, which can overwrite successful creation updates.

    const failureData: Array<
    OnyxUpdate<typeof ONYXKEYS.COLLECTION.TRANSACTION | typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS | typeof ONYXKEYS.COLLECTION.REPORT | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS>
    > = [
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
    value: {
    ...(transaction ?? null),
    errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.receiptDeleteFailureError'),
    pendingFields: {
    receipt: null,
    },
    },
    },

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

    App/src/libs/ReportUtils.ts

    Lines 5521 to 5530 in c134a8d

    if (fieldToEdit === CONST.EDIT_REQUEST_FIELD.RECEIPT) {
    return (
    !isClosedReport(moneyRequestReport) &&
    !isInvoiceReport(moneyRequestReport) &&
    !isReceiptBeingScanned(transaction) &&
    !isPerDiemRequest(transaction) &&
    (!isDistanceRequest(transaction) || isManualDistanceRequestTransactionUtils(transaction)) &&
    canEditExpense &&
    (isDeleteAction ? isRequestor : true)
    );

    This approach requires product confirmation that offline receipt deletion is desired despite the existing restriction. First, the backend must support detaching from a partial transaction and define how the resulting receiptless, incomplete expense remains editable. Detach must handle queued, running, failed, or completed SmartScan work, prevent late scan results from restoring the receipt, and tolerate retries. Deploy that support before enabling the App action. The backend handler is outside this repository, so these are required API guarantees, not a verified backend implementation.

    Limit the allowance in the RECEIPT branch of canEditFieldOfMoneyRequest() to its existing isDeleteAction option. Replace only its scan condition with:

    !isReceiptBeingScanned(transaction) || (isDeleteAction && transaction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD)

    Keep the other permission checks. Unlike a general receipt-edit exception, this does not also enable Replace, Crop, Rotate, or the composer receipt action. No new TransactionUtils helper is needed.

    In MoneyRequestReceiptView, compute canDeleteReceipt through the same permission function, with the same arguments as canEditReceipt plus isDeleteAction: true. Keep the existing isEditable requirement. At both the thumbnail and expand entry points, use readonly || !(canEditReceipt || canDeleteReceipt) for the receipt viewer's readonly value. This lets an authorized delete-only viewer open without enabling edit controls.

    const canEditReceipt =
    isEditable &&
    canEditFieldOfMoneyRequest({
    reportAction: parentReportAction,
    reportActions: parentReportActions,
    fieldToEdit: CONST.EDIT_REQUEST_FIELD.RECEIPT,
    isChatReportArchived,
    reportNameValuePairs,
    transaction,
    report: moneyRequestReport,
    policy,
    rules,
    });

    onPress={() =>
    Navigation.navigate(
    ROUTES.TRANSACTION_RECEIPT.getRoute(report?.reportID, (updatedTransaction ?? transaction)?.transactionID, readonly || !canEditReceipt),
    )

    Then allow pending creation in the modal's separate Delete gate:

    const threeDotsMenuItems: ThreeDotsMenuItemFactory = useCallback(
    ({file, source: innerSource, isLocalSource}) => {
    const menuItems = [];
    if ((!isOffline && allowDownload && !isLocalSource) || !!draftTransactionID) {
    menuItems.push({
    icon: expensifyIcons.Download,
    text: translate('common.download'),
    onSelected: () => onDownloadAttachment({source: innerSource, file}),
    sentryLabel: CONST.SENTRY_LABEL.RECEIPT_MODAL.DOWNLOAD_RECEIPT,
    });
    }
    const hasOnlyEReceipt = hasEReceipt(transaction) && !hasReceiptSource(transaction);
    const isDeletableReceipt =
    shouldShowDeleteReceiptButton &&
    !hasOnlyEReceipt &&
    hasReceipt(transaction) &&
    !isReceiptBeingScanned(transaction) &&
    !hasMissingSmartscanFields(transaction, transactionReport);

    const isReceiptPendingCreation = transaction?.pendingAction === CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD;
    const isDeletableReceipt =
        shouldShowDeleteReceiptButton &&
        !hasOnlyEReceipt &&
        hasReceipt(transaction) &&
        (!isReceiptBeingScanned(transaction) || isReceiptPendingCreation) &&
        (isReceiptPendingCreation || !hasMissingSmartscanFields(transaction, transactionReport));

    For the original SCAN_READY reproduction, hasMissingSmartscanFields() already returns false because it excludes scanning receipts. Bypassing it is not needed to show Delete in that exact state. The explicit allowance also covers a terminal scan-state update arriving before creation is acknowledged. Once creation is acknowledged, the ordinary scan and missing-field guards apply again.

    pendingAction: ADD means creation is not yet acknowledged locally, not that the request has never reached the server. This also occurs briefly online and during retries. Backend correctness must therefore not depend on the frontend's pending flag or the device still being offline. Existing failed-create, readonly, ownership, invoice, eReceipt, test-drive, and distance restrictions remain in place.

    Reuse the existing optimistic detachReceipt() action and request order, but fix its failure recovery before release. A backend change removes the known 405, not every possible failure. Rollback must not merge an entire pre-create transaction over newer server data: it must preserve the acknowledged creation state and newer fields, restore the current receipt, and retain a useful error. Verify create failure followed by detach failure, detach failure after successful create, and late receipt updates. Do not declare the current action safe unchanged.

    function detachReceipt(
    transaction: OnyxEntry<OnyxTypes.Transaction>,
    transactionPolicy: OnyxEntry<OnyxTypes.Policy>,
    transactionPolicyTagList: OnyxEntry<OnyxTypes.PolicyTagLists>,
    transactionViolations: OnyxEntry<OnyxTypes.TransactionViolations>,
    transactionReport: OnyxEntry<OnyxTypes.Report>,
    isVendorMatchingBetaEnabled: boolean | undefined,
    transactionPolicyCategories?: OnyxEntry<OnyxTypes.PolicyCategories>,
    ) {
    const transactionID = transaction?.transactionID;
    if (!transactionID) {
    return;
    }
    const newTransaction = transaction
    ? {
    ...transaction,
    receipt: {},
    }
    : null;
    const optimisticData: Array<
    OnyxUpdate<typeof ONYXKEYS.COLLECTION.TRANSACTION | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS | typeof ONYXKEYS.COLLECTION.REPORT | typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS>
    > = [
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
    value: {
    receipt: null,
    pendingFields: {
    receipt: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE,
    },
    },
    },
    ];
    const successData: Array<OnyxUpdate<typeof ONYXKEYS.COLLECTION.TRANSACTION | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS>> = [
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
    value: {
    pendingFields: {
    receipt: null,
    },
    },
    },
    ];
    const failureData: Array<
    OnyxUpdate<typeof ONYXKEYS.COLLECTION.TRANSACTION | typeof ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS | typeof ONYXKEYS.COLLECTION.REPORT | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS>
    > = [
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`,
    value: {
    ...(transaction ?? null),
    errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.receiptDeleteFailureError'),
    pendingFields: {
    receipt: null,
    },
    },
    },

    const parameters: DetachReceiptParams = {transactionID, reportActionID: updatedReportAction.reportActionID};
    API.write(
    WRITE_COMMANDS.DETACH_RECEIPT,
    parameters,
    {optimisticData, successData, failureData},
    {
    checkAndFixConflictingRequest: (persistedRequests) => resolveDetachReceiptConflicts(persistedRequests, parameters),
    },
    );

    What alternative solutions did you explore? (Optional)

    Alternative 1: Make only the frontend permission change

    Use pendingAction === ADD to bypass the two scan guards without changing the backend. This restores the three-dot menu and removes the receipt optimistically, but DetachReceipt fails with a 405 after reconnect and rolls stale transaction data back into Onyx. It is not a complete fix.

    Alternative 2: Keep the current behavior and update the test case

    Document that an unsynced Scan receipt shows only the close button. After reconnect, Download can appear; Delete requires the scan to stop, required fields to be filled, and normal permissions to pass. A failed scan can therefore remain non-deletable. This matches the existing contract and historical code, and is preferable if product does not approve changing that contract.

  18. mukhrr commented on Sep 24, 2026

    @mukhrr
    Contributor

    @Eskalifer1 I think is expected behavior. BE rejects scanning receipt deletion after going online.

    jsonCode: 405
    message: 405 Cannot detach receipt from partial transaction

    you can see #29766 (comment)

  19. github-actions commented on Sep 24, 2026

    @github-actions
    Contributor

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

  20. yifangoh commented on Sep 24, 2026

    @yifangoh
    Contributor

    Proposal

    What is the root cause of that problem?

    When you create a Scan expense while offline, that expense is still only on the device — an unsent local create that has not reached the server yet. The receipt viewer still applies the same “SmartScan is in progress” lock that is meant for receipts already on the server and actively being scanned. That lock clears the receipt actions and opens the view as read-only, so the header has no menu items left and falls back to the X. Download is already unavailable offline, so nothing else fills the menu either. The inconsistency is that the user can still remove the whole unsent expense from elsewhere; only the receipt screen treats that same local create as an untouchable in-flight scan.

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

    For expenses that are still unsent (only queued locally), allow the receipt menu to offer delete and keep the three-dot control visible, instead of applying the live SmartScan lock. Keep that lock for receipts that are truly scanning after the expense exists on the server. Offline download can stay hidden; delete is the action that should remain available.

    What alternative solutions did you explore? (Optional)

    1. Broadly stop treating “ready to scan” as “currently scanning” everywhere. That can help, but it is easy to break other screens that rely on today’s meaning, and on a 1:1 Scan it can trip a second “incomplete fields” check that hides delete again.
    2. Always show the three-dot control even when the menu is empty. That only changes the icon; it does not restore a way to remove the receipt.
    3. Treat this as expected because the backend later rejects detaching a receipt from a partial transaction. That may matter once the expense is online, but it does not explain why the offline receipt UI is locked while the user can still discard the whole unsent expense.
  21. nabi-ebrahimi commented on Sep 24, 2026

    @nabi-ebrahimi

    @Eskalifer1, when you have a chance, could you please confirm whether we should update the test case to match the current backend behavior or change the backend to support deleting a receipt from a partial transaction?

    I verified that RequestMoney succeeds, but the queued DetachReceipt returns jsonCode: 405 with Cannot detach receipt from partial transaction. This restores the receipt and adds an error. I have updated my proposal with these findings and a backend-first approach. Thank you!

  22. Abdulloh0109 commented on Sep 24, 2026

    @Abdulloh0109
    Contributor

    @Eskalifer1 This isn't a regression. On 9.0.0-0 an offline Scan is already SCANREADY, the RECEIPT permission blocks it via isReceiptBeingScanned, and #34118 (for #33939) hides Download offline and removes the empty menu. So the X has been the expected result since Jan 2024, and the TC is stale.

  23. PiyushChandra17 commented on Sep 26, 2026

    @PiyushChandra17
    Contributor

    Proposal

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

    Scan Receipt- X button is shown instead of three dots on receipt after offline scan

    What is the root cause of that problem?

    1. In AttachmentBaseModalContent, while offline when we scan the expense > shouldShowThreeDotsButton ends up being an empty array, threeDotsMenuItems.length === 0 here

    shouldShowThreeDotsButton={threeDotsMenuItems.length > 0}

    shouldShowThreeDotsButton > false, HeaderWithBackButton shows X instead of three dots.

    1. In TransactionReceiptModalContent, shouldShowDeleteReceiptButton ends up being false value because !isDraftTransaction === true (since we are scanning the receipt in offline mode, this falls in the category of Draft Transaction).

    const shouldShowDeleteReceiptButton = canDeleteReceipt && !readonly && !isDraftTransaction && !transaction?.receipt?.isTestDriveReceipt;

    1. Thus isDeletableReceipt also becomes false when shouldShowDeleteReceiptButton becomes false here

    const isDeletableReceipt =
    shouldShowDeleteReceiptButton &&
    !hasOnlyEReceipt &&
    hasReceipt(transaction) &&
    !isReceiptBeingScanned(transaction) &&
    !hasMissingSmartscanFields(transaction, transactionReport);

    isDeletableReceipt > false
    shouldShowDeleteReceiptButton > false
    !hasOnlyEReceipt > true
    hasReceipt(transaction) > true
    !isReceiptBeingScanned(transaction) > false
    !hasMissingSmartscanFields(transaction, transactionReport) > true
    1. We are detecting the isOffline check here

    Perhaps we aren't checking for isOffline check before pushing in menuItems here

    if (isDeletableReceipt || isDraftOdometer) {

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

    1. Add a isOffline check so that three dot is visible instead of X

    2. Updated code:

    - if (isDeletableReceipt || isDraftOdometer) {
    + if (isDeletableReceipt || isOffline || isDraftOdometer) {

    Test Branch

    What alternative solutions did you explore? (Optional)

    Result

    Image
    fix-three-dot-offline-02.mov

    Reminder: Please use plain English, be brief and avoid jargon. Feel free to use images, charts or pseudo-code if necessary. Do not post large multi-line diffs or write walls of text. Do not create PRs unless you have been hired for this job.

  24. PiyushChandra17 commented on Sep 27, 2026

    @PiyushChandra17
    Contributor

    @Eskalifer1 Proposal Updated with Test Branch and Working Video Recording of the fix. Thanks!

  25. dominictb commented on Sep 28, 2026

    @dominictb
    Contributor

    @Eskalifer1 thought this is expected so closing

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

Metadata

Metadata

Assignees

Labels

BugSomething is broken. Auto assigns a BugZero manager.DailyKSv2ExternalAdded to denote the issue can be worked on by a contributorHelp WantedApply this label when an issue is open to proposals by contributors

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions