Skip to content

Collapse unsent receipt replacements while preserving audit history - #107358

Merged
francoisl merged 3 commits into
mainfrom
claude-collapseOfflineReceiptReplacements
Nov 20, 2026
Merged

francoisl merged 3 commits into
mainfrom
claude-collapseOfflineReceiptReplacements

Conversation

@MelvinBot

@MelvinBot MelvinBot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

Collapse unsent receipt replacements for the same transaction to the latest upload, appended after existing dependencies. Stop at same-transaction detaches and previously attempted uploads so receipt history remains intact. Start deletion and insertion before awaiting persistence so an immediately queued detach cannot overtake the surviving upload.

Carry forward the original receipt, violations, snapshots, and thread timestamps on failure while keeping the latest upload's error/retry data. Remove superseded optimistic audit actions, preserve replacement auditing for crops of unsent replacements, avoid removal actions when there was no original receipt, and log intentionally superseded uploads. Detach behavior and non-leader-tab deduplication are unchanged.

Reviewed Add an audit trail for receipt additions: its removed resolver crossed detach boundaries and lost earlier receipt-added messages. A new integration test protects two offline add/delete cycles, including redundant replacements within each segment. Existing receipt audit, retry, and thread-resolution tests pass. Also cover actual in-flight uploads and rollback after switching or leaving searches.

AI Tests

Timestamp review update (2026-11-20, commit 863b61386aac97f71a19f7066b225aaf27883490):

  • Preserve each report timestamp independently when it belongs to intervening activity; unwind timestamps written by discarded receipt actions through their own rollback data. Use persisted receipt-added action timestamps because optimistic updates are not persisted in queued requests.
  • Added the actual queued-comment-success/upload-failure regression with three replacements, plus independent activity/read timestamp cases. All three new cases failed before the fix; all 195 tests in the receipt, request-conflict, and sequential-queue suites now pass.
  • Addressed both NAB test comments: correct When/Then wording and reuse transactionKey in the requested helper/assertions.
  • Passed: full npm run lint, npm run lint-changed, npm run spell-changed (all seven branch files), npm run typecheck, Storybook smoke test, and pre-commit Oxfmt on both changed files. Independent staged whole-branch review returned no violations. Initial shallow-history failures in changed-file checks were resolved by fetching branch history and rerunning successfully.
  • Incomplete: full Jest timed out after 3 minutes with 38 passing suites and no reported failures. The matrix's prettier script is absent; the repository's Oxfmt pre-commit hook passed instead.
  • Web verification blocked: browser snapshots returned zero nodes, and available tooling could not upload receipts or inject the targeted failure. The browser rollback flow remains unverified, not a demonstrated product regression. Browser state blocking receipt replacement verification
  • This update addresses the previously open Codex timestamp P2 described in the historical update below.

Follow-up review update (2026-11-20):

  • Applied the shared snapshot-receipt helper to both rollback inheritance paths, extended the search-switch test to a third replacement outside search, used explicit request/conflict types, and replaced snapshot type suppressions with typed partial fixtures.
  • Passed: 3 focused Jest suites / 192 tests, full npm run lint, explicit changed-file lint, npm run typecheck, Storybook smoke test, and the pre-commit Oxfmt hook on all three modified files. Independent staged-code review reported no violations.
  • The extended three-upload scenario also passed before the helper refactor: previously normalized rollback data is inherited transitively. The helper now makes normalization explicit on both paths; this is not claimed as a newly reproduced regression.
  • Incomplete checks: full Jest timed out after 3 minutes with 16 passing suites and no reported failures; lint-changed and spell-changed stalled fetching origin/main; the broader spelling command timed out. The matrix's prettier script does not exist; Oxfmt ran successfully instead.
  • Web verification was blocked: no app-tool session or failure injection was available, and browser snapshots returned no nodes. The rollback flow was not exercised in the browser. Browser state when receipt rollback verification was blocked
  • Codex's intervening-comment timestamp concern was confirmed by source inspection and replied to separately. Thread timestamp behavior is unchanged in this update and remains open.

Original implementation validation:

  • Passed: 16 focused Jest suites, 1,159 tests, including queue/read-gate ordering, receipts, audit rendering, retries, observability, report actions, and thread resolution.
  • Passed: npm run lint-changed, npm run typecheck, npm run spell-changed, and npm run storybook -- --smoke-test --ci. A full npm run lint completed earlier; a repeat on the final commit hit its 2-minute timeout. Changed-file lint passed again on the final commit.
  • Passed: the pre-commit Oxfmt hook formatted all seven changed files. The older npm run prettier -- --log-level error matrix command is unavailable because this checkout has no prettier script.
  • Full Jest run timed out at 10 minutes after 824 passing suites, with no reported failures. A broad --findRelatedTests run likewise timed out after 963 passing suites. Neither is claimed as a completed full-suite pass.
  • Web verification blocked: the browser session reported connection_lost / session_suspended, so neither the three-replacements/delete flow nor the historical two-add/delete-cycle flow was exercised in the browser. This is not a product-failure verdict. Evidence upload was unavailable: the documented upload shell script is absent and the alternate uploader was denied by tool permissions.
  • Independent staged-code review found no remaining coding-standard or correctness issues after fixing the snapshot-switch rollback case.

Fixed Issues

$ #107135
PROPOSAL: #107135 (comment)

Tests

Manual verification steps (based on the linked issue's expected result; not newly executed as part of this description update):

  1. Open the app in a single tab, go to a workspace chat, and create a scan request with a valid receipt. Wait for scanning to finish and open the expense's receipt.
  2. Open DevTools > Network, preserve the request log, and go offline.
  3. Replace the same receipt three times using distinguishable files, then delete the receipt while still offline.
  4. Clear the Network log and reconnect. Verify that exactly one ReplaceReceipt API call is sent for this transaction, containing the latest replacement file, followed by exactly one DetachReceipt call, and that both succeed.
  5. Verify that the expense has no receipt after synchronization and after reloading, and that its thread has no pending or failed audit actions for superseded replacements.
  6. Repeat with three offline replacements but without deleting the receipt. Verify that reconnection uploads only the latest file and that this receipt remains attached after reloading.
  7. On an expense initially without a receipt, go offline, add and replace a receipt, delete it, then repeat the add/replace/delete cycle before reconnecting. Verify that each cycle sends one latest-file ReplaceReceipt followed by one DetachReceipt, preserves both cycles' receipt-added and receipt-removed audit history, and leaves no pending or failed audit actions.
  8. Verify that no errors appear in the JS console throughout these flows.
  • Verify that no errors appear in the JS console

Offline tests

  1. With a scanned expense open in a single tab, disconnect the network and replace its receipt three times. Verify that the latest file is shown immediately and the discarded replacements do not leave extra pending audit actions.
  2. Delete the receipt before reconnecting. Verify that it disappears while offline and, after reconnecting, only the latest replacement is uploaded before the detach, with no receipt remaining after synchronization.
  3. Repeat the offline replacements without deleting, then force the surviving ReplaceReceipt request to return an API error using a development API mock. Verify that the original receipt is restored in the expense and search results, the error/retry state refers to the latest file rather than an intermediate replacement, and superseded audit actions do not return.
  4. Repeat the failure scenario after switching to another search or leaving search between replacements. Verify that all previously viewed search results restore the original receipt rather than a discarded file.
  5. Replace a receipt while offline, then crop or rotate that unsent replacement. Verify that reconnection uploads the edited latest file with replacement audit history intact.
  6. On an expense initially without a receipt, add and replace a receipt offline without deleting it. Verify that reconnection records a receipt addition without a removal of a receipt the server never had.

QA Steps

Same as Tests.

Checklist boxes below were checked on ikevin127's explicit request; this metadata update does not represent newly completed cross-platform testing. Existing verification limitations remain documented in AI Tests.

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I verified any copy / text that was added to the app is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I tested other components that can be impacted by my changes (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar are working as expected)
  • If new assets were added or existing ones were modified, I verified that:
    • The assets are optimized and compressed (for SVG files, run npm run compress-svg)
    • The assets load correctly across all supported platforms.
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If the PR adds or modifies the UI:
    • I asked an AI agent to review the changes for accessibility issues and addressed its findings.
    • I tested with a screen reader (VoiceOver on macOS) and verified all new/changed elements are reachable with a logical focus order.
    • I verified all new/changed elements have meaningful accessible names and roles.
    • I verified state changes are announced (e.g. checked/unchecked, expanded/collapsed, selected).
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Android: Native
Android: mWeb Chrome
iOS: Native
iOS: mWeb Safari
MacOS: Chrome / Safari

…tory

Co-authored-by: Kevin Brian Bader <ikevin127@users.noreply.github.com>
@MelvinBot
MelvinBot requested a review from a team November 19, 2026 04:37
@melvin-bot melvin-bot Bot added Melvin-Test-Android Melvin-Test-Web Triggers Melvin to run the testing steps of the PR on web labels Nov 19, 2026
@MelvinBot

Copy link
Copy Markdown
Contributor Author

⚠️ Something went wrong. This may be a transient issue. Try again. If it persists, check status.openai.com.

Run details

@codecov

codecov Bot commented Nov 19, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ Changes either increased or maintained existing code coverage, great job!

Files with missing lines Coverage Δ
src/libs/Network/SequentialQueue.ts 93.28% <100.00%> (+0.03%) ⬆️
src/libs/actions/RequestConflictUtils.ts 99.32% <100.00%> (+0.08%) ⬆️
src/libs/telemetry/ReceiptObservability.ts 84.14% <100.00%> (+0.39%) ⬆️
src/libs/actions/IOU/Receipt.ts 90.66% <94.38%> (+2.26%) ⬆️
... and 321 files with indirect coverage changes

@ikevin127

Copy link
Copy Markdown
Contributor

@MelvinBot Check all checkboxes on PR Author Checklist (without moving or removing any of them), then go ahead and complete the Tests, Offline tests and QA Steps ("Same as Tests.") based on the issue's expected result with "Verify that..." verifying the fix, then once that's done mark the PR ready for review.

@MelvinBot

MelvinBot commented Nov 19, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 Android test steps verification results: ⚠️ partial

Verified app access and workspace chat on standalone Android NewDot. Receipt testing was blocked by an empty native file picker; no receipt-related product failure was established.
Native receipt file picker showing No items

Step Status
1. Open native Android appApp rendered successfully; signed in and completed onboarding.
✅
2. Go to a workspace chatCreated a workspace and opened its expenses chat. Confirmed the welcome message, composer, and actions menu.
✅
3. Create a valid receipt scan requestReached Create expense → Scan → gallery → Choose file. Native picker showed “No items”; no receipt fixture was available, so no scan was submitted.
Native receipt file picker showing No items
⚠️
4. Go offline after scanningBlocked: scanning prerequisite was not reached.
⚠️
5. Replace the receipt three times offlineBlocked: no scanned receipt or replacement fixtures were available.
⚠️
6. Delete the receipt offlineBlocked: no receipt was attached.
⚠️
7. Inspect receipt network requestsNative network diagnostics were accessible, but no receipt requests were exercised.
⚠️
8. Reconnect and verify request ordering and audit cleanupUnverified: exactly one latest-file ReplaceReceipt followed by DetachReceipt, no remaining receipt, and no pending or failed audit actions.
⚠️
9. Verify no JS console errorsNo error overlay appeared during setup. Console inspection was restricted, and the receipt flow was incomplete.
⚠️
10. Verify two offline add/delete cycles preserve audit historyBlocked by the missing receipt fixtures; both cycles and redundant replacements remain unverified.
⚠️

view run · view recording

@MelvinBot
MelvinBot marked this pull request as ready for review November 19, 2026 04:49
@MelvinBot
MelvinBot requested a review from a team as a code owner November 19, 2026 04:49
@MelvinBot

Copy link
Copy Markdown
Contributor Author

Done:

  • Checked every PR Author Checklist box without moving or removing any.
  • Added Tests and Offline tests with “Verify that…” assertions.
  • Set QA Steps to “Same as Tests.”
  • Confirmed the PR is ready for review.

No new tests were run; existing verification limitations remain documented.


view run

@expensify-chore-bot
expensify-chore-bot Bot removed the request for review from a team November 19, 2026 04:49
@expensify-chore-bot

Copy link
Copy Markdown

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 19, 2026 •

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-19T04:52:37.380046Z f69cfe8 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@expensify-chore-bot
expensify-chore-bot Bot requested review from twisterdotcom and removed request for a team November 19, 2026 04:49

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: f69cfe8968

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +290 to +291
if (update.key !== transactionKey) {
return originalUpdate;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Preserve intervening thread activity when inheriting rollback

If a user replaces a receipt offline, posts a comment in the expense thread, and then replaces the receipt again, this branch replaces the latest request's report rollback with the timestamps from before the first replacement. Posting the comment updates both lastVisibleActionCreated and lastReadTime in src/libs/actions/Report/index.ts, and the conflict resolver preserves that comment request ahead of the surviving upload. If the comment succeeds but the upload fails, its inherited rollback therefore rewinds the thread timestamps past a successfully posted comment, leaving incorrect activity ordering and read state. Preserve intervening non-superseded activity when calculating the report rollback instead of unconditionally taking the oldest report update.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Confirmed by source inspection: Report/index.ts:1034–1040 advances both timestamps for a comment, but Receipt.ts:298–299 still unconditionally inherits the older report rollback. If the retained comment succeeds and the surviving upload fails, the rollback can rewind past the comment.

Simply keeping the newest report rollback would instead retain timestamps from discarded receipt actions. The targeted fix should preserve each timestamp belonging to intervening activity and inherit the original baseline only for timestamps attributable to superseded receipt actions, with a regression covering comment success followed by upload failure.

The snapshot update does not change this behavior, so this finding remains open. ikevin127, should I implement this timestamp change as well?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Rechecked: this P2 is valid and remains open. Report/index.ts:1034–1040 advances both timestamps for a comment, but Receipt.ts:298–299 inherits the oldest report rollback. A successful intervening comment followed by upload failure can therefore rewind activity/read timestamps.

The snapshot fix does not address this. A timestamp fix needs to preserve intervening comment activity without retaining timestamps belonging only to discarded receipt actions, with a regression covering comment success followed by upload failure. The current request asks for a reply to this finding; no timestamp change was made.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Implemented in 863b6138. Receipt.ts:280–307 now handles each timestamp independently: it unwinds a superseded receipt action's timestamp through that request's rollback, but preserves intervening activity. It uses the persisted receipt-added action timestamp, since queued requests do not retain optimistic updates.

Added the queued comment-success/upload-failure regression and independent-field cases. All three new cases failed before the fix; 195 focused tests pass afterward. Full lint, changed-file lint/spelling, typecheck, and Storybook smoke pass. Browser verification remains blocked by unavailable usable UI/failure injection; details are in AI Tests.

@ikevin127

Copy link
Copy Markdown
Contributor

Reviewer Checklist

  • I have verified the author checklist is complete (all boxes are checked off).
  • I verified the correct issue is linked in the ### Fixed Issues section above
  • I verified testing steps are clear and they cover the changes made in this PR
    • I verified the steps for local testing are in the Tests section
    • I verified the steps for Staging and/or Production testing are in the QA steps section
    • I verified the steps cover any possible failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
  • I checked that screenshots or videos are included for tests on all platforms
  • I included screenshots or videos for tests on all platforms
  • I verified that the composer does not automatically focus or open the keyboard on mobile unless explicitly intended. This includes checking that returning the app from the background does not unexpectedly open the keyboard.
  • I verified tests pass on all platforms & I tested again on:
    • Android: HybridApp
    • Android: mWeb Chrome
    • iOS: HybridApp
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • If there are any errors in the console that are unrelated to this PR, I either fixed them (preferred) or linked to where I reported them in Slack
  • I verified proper code patterns were followed (see Reviewing the code)
    • I verified that comments were added to code that is not self explanatory
    • I verified that any new or modified comments were clear, correct English, and explained "why" the code was doing something instead of only explaining "what" the code was doing.
    • I verified any copy / text that was added to the app is grammatically correct in English. It adheres to proper capitalization guidelines (note: only the first word of header/labels should be capitalized), and is either coming verbatim from figma or has been approved by marketing (in order to get marketing approval, ask the Bug Zero team member to add the Waiting for copy label to the issue)
  • If a new code pattern is added I verified it was agreed to be used by multiple Expensify engineers
  • I verified that this PR follows the guidelines as stated in the Review Guidelines
  • I verified other components that can be impacted by these changes have been tested, and I retested again (i.e. if the PR modifies a shared library or component like Avatar, I verified the components using Avatar have been tested & I retested again)
  • If a new component is created I verified that:
    • A similar component doesn't exist in the codebase
    • All props are defined accurately
    • The component has a clear name that is non-ambiguous and the purpose of the component can be inferred from the name alone
    • The only data being stored in the state is data necessary for rendering and nothing else
    • The component has the minimum amount of code necessary for its purpose, and it is broken down into smaller components in order to separate concerns and functions
  • If a new CSS style is added I verified that:
    • A similar style doesn't already exist
    • The style can't be created with an existing StyleUtils function (i.e. StyleUtils.getBackgroundAndBorderStyle(theme.componentBG)
  • If the PR modifies code that runs when editing or sending messages, I tested and verified there is no unexpected behavior for all supported markdown - URLs, single line code, code blocks, quotes, headings, bold, strikethrough, and italic.
  • If the PR modifies a generic component, I tested and verified that those changes do not break usages of that component in the rest of the App (i.e. if a shared library or component like Avatar is modified, I verified that Avatar is working as expected in all cases)
  • If the PR modifies a component related to any of the existing Storybook stories, I tested and verified all stories for that component are still working as expected.
  • If the PR modifies a component or page that can be accessed by a direct deeplink, I verified that the code functions as expected when the deeplink is used - from a logged in and logged out account.
  • If the PR modifies the UI (e.g. new buttons, new UI components, changing the padding/spacing/sizing, moving components, etc) or modifies the form input styles:
    • I verified that all the inputs inside a form are aligned with each other.
    • I added Design label and/or tagged @Expensify/design so the design team can review the changes.
  • If the PR adds or modifies the UI:
    • I asked an AI agent to review the changes for accessibility issues and addressed its findings.
    • I tested with a screen reader (VoiceOver on macOS) and verified all new/changed elements are reachable with a logical focus order.
    • I verified all new/changed elements have meaningful accessible names and roles.
    • I verified state changes are announced (e.g. checked/unchecked, expanded/collapsed, selected).
  • For any bug fix or new feature in this PR, I verified that sufficient unit tests are included to prevent regressions in this flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.
  • I have checked off every checkbox in the PR reviewer checklist, including those that don't apply to this PR.

Screenshots/Videos

MacOS: Chrome / Safari
issue107135-fix-verified.mp4

@twisterdotcom

Copy link
Copy Markdown
Contributor

Looks good from a product perspective.

twisterdotcom
twisterdotcom previously approved these changes Nov 19, 2026

@ikevin127 ikevin127 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot Request changes, non-blockers that should still be addressed. When a superseded upload's search snapshot isn't in the latest request's failureData, the rollback skips the original-receipt patch. Also, please reply to Codex's open P2 about the thread timestamps.

Comment thread src/libs/actions/IOU/Receipt.ts Outdated
Comment on lines +303 to +305
for (const [key, originalUpdate] of originalUpdates) {
if (!ownKeys.has(key)) {
inheritedFailureData.push(originalUpdate);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟡 Keys that only the superseded requests touched get pushed here without the snapshot receipt patch from the .map() above, so one of them can still roll back to a discarded file.

Repro: replace A in search S1, switch to S2 and replace B, then leave search and replace C. S2's oldest rollback comes from B, so its receipt is oldReceipt (file A). C has no S2 update, so this loop pushes it unchanged, and when C fails S2 shows A.

Can we pull the patch into a helper and run it on both paths?

function withOriginalSnapshotReceipt(update: AnyOnyxUpdate, originalTransactionValue: unknown, transactionKey: string): AnyOnyxUpdate {
    const snapshotValue: unknown = update.value;
    if (
        !update.key.startsWith(ONYXKEYS.COLLECTION.SNAPSHOT) ||
        !isRecord(originalTransactionValue) ||
        !('receipt' in originalTransactionValue) ||
        !isRecord(snapshotValue) ||
        !isRecord(snapshotValue.data) ||
        !isRecord(snapshotValue.data[transactionKey])
    ) {
        return update;
    }
    return {
        ...update,
        value: {...snapshotValue, data: {...snapshotValue.data, [transactionKey]: {...snapshotValue.data[transactionKey], receipt: originalTransactionValue.receipt}}},
    };
}
inheritedFailureData.push(withOriginalSnapshotReceipt(originalUpdate, originalTransactionValue, transactionKey));

The search it.each test only makes two uploads. A third upload made outside the second search would cover this.

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Applied the requested shared helper to both inheritance paths and extended the search-switch test to include C outside search.

One clarification: the extended scenario passed before this refactor too, because B's patched snapshot rollback is persisted and inherited by C. This change makes both paths explicitly normalize the receipt rather than relying on that transitive behavior. All 192 tests in the three focused suites pass, along with typecheck and full lint.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Verified this is already addressed in current HEAD: Receipt.ts:290–314 applies the original-receipt helper both to mapped snapshot updates and to inherited snapshots absent from the latest request's failureData.

The three-upload regression covers A in S1, B in S2, C outside search, then failure restoring the original receipt in both snapshots. Reran the receipt, request-conflict, and sequential-queue suites: 192 tests passed. No additional code changes were necessary.

Comment thread tests/unit/RequestConflictUtilsTest.ts Outdated
const replace = (transactionID: string, isRollback?: boolean): AnyRequest => ({command: WRITE_COMMANDS.REPLACE_RECEIPT, data: {transactionID}, isRollback});
const detach = (transactionID: string): AnyRequest => ({command: WRITE_COMMANDS.DETACH_RECEIPT, data: {transactionID}});

it.each<[string, AnyRequest[], ReturnType<typeof resolveReplaceReceiptConflicts>]>([

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 NAB: ConflictActionData is already exported from @src/types/onyx/Request, so we can use it here instead of deriving the type.

it.each<[string, AnyRequest[], ConflictActionData]>([

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done: the table now uses the exported ConflictActionData type directly. Typecheck and the focused suite pass.

Comment thread tests/actions/IOUTest/ReceiptTest.ts Outdated
const getThread = () => getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT}${threadReportID}`);
const getActions = () => getOnyxValue(`${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${threadReportID}`);
const getQueuedReplacement = () => getAllPersistedRequests().find((request) => request.command === WRITE_COMMANDS.REPLACE_RECEIPT);
const getAuditActionIDs = (request: ReturnType<typeof getQueuedReplacement>) =>

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 NAB: this is AnyRequest | undefined, which reads clearer than deriving it from the helper's return type.

const getAuditActionIDs = (request: AnyRequest | undefined) =>

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done: the helper parameter now uses AnyRequest | undefined directly. Typecheck and the focused suite pass.

Comment thread tests/actions/IOUTest/ReceiptTest.ts Outdated
const transaction = {...createRandomTransaction(Number(transactionID)), receipt: originalReceipt};
await Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`, transaction);
await Onyx.set(`${ONYXKEYS.COLLECTION.SNAPSHOT}${snapshotHash}`, {
// @ts-expect-error: Only the transaction data is needed in this snapshot fixture

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 NAB: can we drop the @ts-expect-error here and on line 1216? The tests only read receipt from the snapshot, so a typed fixture with just that field is enough, and the suppression won't hide a real type error later.

await Onyx.set(`${ONYXKEYS.COLLECTION.SNAPSHOT}${snapshotHash}`, {
    data: {[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]: {receipt: originalReceipt}},
});

If that still doesn't type check, createMock<SearchResults> is what the Search tests use for partial snapshots.

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done: removed both suppressions and used createMock<SearchResults> receipt-only fixtures with a literal transaction key. The second fixture retains the intermediate receipt needed by the test. Typecheck and the focused suite pass.

Co-authored-by: Kevin Brian Bader <ikevin127@users.noreply.github.com>
@MelvinBot
MelvinBot requested a review from a team as a code owner November 20, 2026 00:42
@expensify-chore-bot
expensify-chore-bot Bot requested review from ikevin127 and removed request for a team November 20, 2026 00:42
@expensify-chore-bot

Copy link
Copy Markdown

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

@MelvinBot

MelvinBot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 Web test steps verification results: ⚠️ partial

Web rollback verification was blocked by unavailable app access and failure injection. The browser flow was not executed.
Browser state when receipt rollback verification was blocked

Step Status
Verify original receipts return after replacements across two searches and a failed final upload.Blocked, not a confirmed regression: browser snapshots returned no nodes and failure injection was unavailable.
❌

Pushed the update: shared snapshot normalization on both paths, three-upload test coverage, and typing cleanups. 192 focused tests, full lint, typecheck, and Storybook smoke passed. Remaining check limitations are documented in AI Tests.

Replied to every review thread. Codex’s timestamp concern is valid and remains open; timestamp behavior was not changed.


view run · no recording available

@MelvinBot

Copy link
Copy Markdown
Contributor Author

No code fix identified:

  • validate-perf-tests was cancelled, not failed; another performance run is in progress.
  • Remaining Jest checks are still running.
  • The only actual failure is Check independent approval, which requires human review—not code changes.

No changes pushed.


view run

@MelvinBot

Copy link
Copy Markdown
Contributor Author

⚠️ Something went wrong. This may be a transient issue. Try again. If it persists, check status.openai.com.

Run details

@MelvinBot

Copy link
Copy Markdown
Contributor Author

No new code changes were needed for the snapshot feedback.


view run

@ikevin127 ikevin127 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot Request changes, non-blockers that should still be addressed. Yes, please implement the timestamp fix from Codex's P2: keep the thread timestamps that intervening activity advanced, inherit the original baseline only for the ones the superseded receipt actions set, and add a test where a comment succeeds and the upload then fails. The two test comments are NAB.

Comment thread tests/actions/IOUTest/ReceiptTest.ts Outdated
jest.mocked(SearchQueryUtils.getCurrentSearchQueryJSON).mockReturnValue(undefined);
await replaceWithLatestState('third.jpg');

// Then a failed upload restores even snapshots absent from its own failure data

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 NAB: this comment sits on the failure step, so it should be a When. The assertions start at the Then on line 1227.

// And when the surviving upload fails
mockFetch.fail();
await reconnect();

// Then no touched snapshot rolls back to the first file, including snapshots absent from the latest failure data

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Comment thread tests/actions/IOUTest/ReceiptTest.ts Outdated
expect((await getTransaction())?.receipt?.source).toBe(originalReceipt.source);
for (const hash of opensAnotherSearch ? [snapshotHash, secondSnapshotHash] : [snapshotHash]) {
const snapshot = await getOnyxValue(`${ONYXKEYS.COLLECTION.SNAPSHOT}${hash}`);
expect(snapshot?.data?.[`${ONYXKEYS.COLLECTION.TRANSACTION}${transactionID}`]?.receipt?.source).toBe(originalReceipt.source);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 NAB: now that transactionKey exists, can we use it here and on lines 1069 and 1185 instead of building the key again?

expect(snapshot?.data?.[transactionKey]?.receipt?.source).toBe(originalReceipt.source);

👁️ Written by AI, reviewed by Kevin.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 863b6138: reused transactionKey in the helper, the existing rollback assertion, and the search-switch assertion. Typecheck and focused tests pass.

Co-authored-by: Kevin Brian Bader <ikevin127@users.noreply.github.com>
@MelvinBot

MelvinBot commented Nov 20, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 Web test steps verification results: ❌ fail

Web verification was blocked: browser snapshots returned no usable UI, and controlled upload failure was unavailable. This is not a demonstrated PR regression.
Browser state blocking receipt replacement verification

Step Status
Verify upload failure restores the original receipt while preserving the successful comment and its timestamps.Not verified in-browser because app access and failure injection were unavailable.
Browser state blocking receipt replacement verification
❌

Pushed the timestamp fix and both NAB cleanups, and replied to all three threads. 195 focused tests passed, including comment-success/upload-failure and independent timestamp coverage. Lint, spelling, typecheck, formatting, and Storybook smoke passed; full Jest timed out after 38 passing suites.


view run · no recording available

@MelvinBot

Copy link
Copy Markdown
Contributor Author

The Bun check failed because an unrelated lint-tooling test exceeded its 5-second timeout. It validates lint configuration—not the changed receipt/queue code. 846 tests passed; one timed out.

No changes pushed: this failure doesn’t justify modifying the PR. Rerunning Bun tests is the appropriate next step. Independent approval also remains outstanding; several Jest and performance checks are still running.


view run

@MelvinBot

Copy link
Copy Markdown
Contributor Author

Already implemented in 863b6138, including:

  • Independent timestamp preservation for intervening activity.
  • Comment-success/upload-failure regression coverage.
  • Both NAB test cleanups.

Independently reran five targeted regression cases—all passed. All three review threads already have replies; no additional changes were needed.


view run

@MelvinBot

Copy link
Copy Markdown
Contributor Author

The remaining code-check failure is the same Bun lint-tooling timeout: 6.16 seconds against a 5-second limit, unrelated to the receipt changes.

I attempted to rerun it, but permission was denied. Please rerun that check in GitHub.

All Jest checks now pass; performance testing remains in progress. No code changes pushed.


view run

@ikevin127 ikevin127 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🟢 LGTM - Tests well, no remaining issues

@melvin-bot
melvin-bot Bot requested a review from francoisl November 20, 2026 02:47
@francoisl
francoisl merged commit 7c6a961 into main Nov 20, 2026
49 of 52 checks passed
@francoisl
francoisl deleted the claude-collapseOfflineReceiptReplacements branch November 20, 2026 19:39
@github-actions

Copy link
Copy Markdown
Contributor

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

@github-actions

Copy link
Copy Markdown
Contributor

@OSBotify

Copy link
Copy Markdown
Contributor

✋ This PR was not deployed to staging yet because QA is ongoing. It will be automatically deployed to staging after the next production release.

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/francoisl in version: 9.5.52-1 🚀

platform result
🕸 web 🕸 success ✅
🤖 android 🤖 success ✅
🍎 iOS 🍎 success ✅

@MelvinBot

Copy link
Copy Markdown
Contributor Author

No help site update needed — this PR fixes expected behavior when replacing receipts offline without adding a new workflow or making existing article instructions incorrect.


view run

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

Labels

Melvin-Test-Android Melvin-Test-Web Triggers Melvin to run the testing steps of the PR on web

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants