Skip to content

Keep inline edits from flickering back when a stale Search response lands - #104997

Merged
luacmartins merged 24 commits into
mainfrom
claude-inlineEditStaleSearchFlicker
Nov 18, 2026
Merged

luacmartins merged 24 commits into
mainfrom
claude-inlineEditStaleSearchFlicker

Conversation

@MelvinBot

@MelvinBot MelvinBot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

Follow-up item 5 from #89166 (comment): on a slow network, editing two table cells quickly made the first edited value flicker back to its old value.

Why it happened: an inline edit changes transactions_<id>, so useSearchAutoRefetch calls search(). That search waits for the write queue to go idle, so it is sent right after the first UpdateMoneyRequest* write finishes. If the user makes a second edit while that search is in flight, the second write merges its optimistic value into snapshot_<hash>. Then the search response lands. Read responses are applied right away (only write responses are held until the queue flushes), and this one holds the server's values from before the second edit. It overwrites the optimistic snapshot row, and the cell flips back until the second write finishes and another refetch corrects it.

What this PR does:

  • Implements option 2: explicit in-flight invalidation. Each of the six inline-edit entry points passes its snapshot hash and synchronously marks only sent Search requests with that hash stale before delegating to the canonical update action. This includes every in-flight offset for that hash, but leaves unrelated queries' first results intact. An edit without a snapshot hash invalidates nothing. Searches still waiting for writes are not invalidated, since they will include the edit when dispatched.
  • DiscardStaleSearchSnapshot, registered before SaveResponseInOnyx, removes only the invalidated request's snapshot update. Other response updates and final loading cleanup still apply. Invalidation uses the serialized query, including its offset, so releasing one page does not release another.
  • A dropped snapshot is fetched again after writes finish, without showing loading. Existing totals/recent-search upgrades run instead of a duplicate refetch and also wait for the edit. Only the stale-snapshot refetch skips dispatch offline; normal Search offline behavior remains unchanged.
  • Removes the inline-edit queue counter, opt-in guard, late promotion and custom reconnect subscription. No production changes remain in PersistedRequests or useSearchAutoRefetch relative to the branch's main merge base.

Fixed Issues

$ #82534
PROPOSAL: #89166 (comment)

Tests

Precondition: Large screen - web only.

  1. Open the browser's Developer Tools and navigate to the Network tab.
  2. Throttle the network to a slow speed (e.g., 100 Kbps).
  3. Open an expense with an existing category (e.g., Category A).
  4. Edit the merchant, then quickly open the category picker without changing the category. Leave the picker open.
  5. Monitor the Network tab. Wait for the UpdateMoneyRequestMerchant request to finish and the subsequent search request to start.
  6. Before the search request completes, select Category B from the already-open category picker. Verify that Category B is applied optimistically in the UI.
  7. Once the search request completes, verify that Category B is still displayed and has not been overwritten by the original Category A returned by the search response.
  8. After both the UpdateMoneyRequestMerchant and search requests by step 6 have completed, verify that Category B is still displayed.
  • Verify that no errors appear in the JS console

Offline tests

N/A.

QA Steps

Same as Tests steps.

  • Verify that no errors appear in the JS console

PR Author Checklist

  • I linked the correct issue in the ### Fixed Issues section above
  • I wrote clear testing steps that cover the changes made in this PR
    • I added steps for local testing in the Tests section
    • I added steps for the expected offline behavior in the Offline steps section
    • I added steps for Staging and/or Production testing in the QA steps section
    • I added steps to cover failure scenarios (i.e. verify an input displays the correct error message if the entered data is not correct)
    • I turned off my network connection and tested it while offline to ensure it matches the expected behavior (i.e. verify the default avatar icon is displayed if app is offline)
    • I tested this PR with a High Traffic account against the staging or production API to ensure there are no regressions (e.g. long loading states that impact usability).
  • I included screenshots or videos for tests on all platforms
  • I ran the tests on all platforms & verified they passed on:
    • Android: Native
    • Android: mWeb Chrome
    • iOS: Native
    • iOS: mWeb Safari
    • MacOS: Chrome / Safari
  • I verified there are no console errors (if there's a console error not related to the PR, report it or open an issue for it to be fixed)
  • I 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.

AI Tests

  • Hash-scoped invalidation 2a4f989: 85 targeted Jest suites / 2,427 tests / 2 snapshots passed. Regression coverage sends two offsets of one hash alongside an unrelated hash, verifies only matching snapshots are dropped/refetched, and verifies undefined invalidates nothing. All six inline-edit entry points verify forwarding both defined and undefined hashes before their delegated actions. Existing invalidation tests now pass the hash.
  • Latest checks: full lint, changed-file lint/spelling, typecheck, Oxfmt and Storybook smoke test passed; staged review found no violations. The prescribed prettier script remains unavailable, so the repository's Oxfmt script was used. Full Jest exceeded four minutes with no failures observed before timeout; no complete full-suite pass is claimed. The hash-scoping behavior was verified in unit tests, not in a browser.
  • Formatting-only cleanup 207d04f: restored the auto-refetch test file byte-for-byte to main; it no longer appears in the PR diff. All 43 auto-refetch tests passed, as did changed-file lint/spelling and Oxfmt. Staged review found no violations. Full lint and typecheck attempts each exceeded the three-minute command limit. No application code or assertion values changed; browser verification and the full test suite were not rerun for this formatting-only cleanup.
  • Review follow-up ffc71de: removed the broad offline Search guard and its related test, plus the unrelated cross-tab persisted-request test/import. The stale-snapshot-specific offline guard and its regression test remain.
  • Latest checks: 5 targeted Jest suites / 115 tests passed, including stale-snapshot handling, middleware, inline edits, auto-refetch and persisted requests. Full lint, changed-file lint/spelling, typecheck, Oxfmt and Storybook smoke test passed. Staged code review found no violations. Full Jest exceeded four minutes with no failures observed before timeout; no complete full-suite pass is claimed. No browser verification was run for these removals.
  • Main merge 1962ee3: resolved four conflict files, retaining explicit invalidation, main's first-page Search helper and support-auth save behavior, both middleware registrations (19 total), and both persisted-request test imports.
  • After refreshing dependencies and applying the repository's patches: 88 targeted Jest suites, 2,439 tests and 2 snapshots passed. Full lint, changed-file lint/spelling, formatting and Storybook smoke test passed; staged review found no violations.
  • Typecheck did not pass: React Native web augmentation reports incompatible interface properties (including TS2320). No unrelated typing changes were made. Full Jest was attempted and exceeded the three-minute limit; it is not claimed as a complete pass. No browser verification was run for this merge.
  • Option 2 verification for 4781973: 76 Jest suites, 2,104 tests and 2 snapshots passed, covering all Search suites plus inline editing, auto-refetch, persisted requests and middleware registration.
  • Regression coverage uses the real discard middleware for sent versus waiting requests, repeated invalidation, same-offset refetching, skip-wait dispatch, pending totals upgrades, rejection cleanup and offline transitions. All six inline-edit entry points assert invalidation happens before their delegated update action.
  • Passed: full npm run lint, npm run lint-changed, npm run typecheck, npm run spell-changed, and Storybook smoke test. Staged code review found no violations.
  • Formatting: the prescribed prettier script does not exist. Used the repository's npm run fmt instead; a second run made no further changes, and the pre-commit formatter passed.
  • Full Jest was attempted but exceeded 10 minutes; no test failures were observed before timeout. It is not claimed as a complete pass.
  • Compiler check was blocked by the runner's empty base-ref setting (origin/); attempts to supply the correct base were denied. Translation dry-run could not start under this branch's TypeScript/ts-node combination (ts.sys unavailable); no translation files changed.
  • Web race verification was blocked because permitted browser controls do not support DevTools or network throttling. The documented slow-network scenario remains unverified; this is not a product-failure verdict. No mobile tester was run.

Screenshots/Videos

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

…e edit

Co-authored-by: ahmedGaber93 <ahmedGaber93@users.noreply.github.com>
@MelvinBot
MelvinBot requested a review from a team October 26, 2026 12:19
@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 Oct 26, 2026
@MelvinBot

Copy link
Copy Markdown
Contributor Author

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

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

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

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

… DiscardStaleSearchSnapshot

Co-authored-by: ahmedGaber93 <ahmedGaber93@users.noreply.github.com>
@MelvinBot

Copy link
Copy Markdown
Contributor Author

Fixed the failing test (job 1) check in d71adc20.

This PR registers a 17th middleware, DiscardStaleSearchSnapshot. tests/unit/MiddlewareEntryPointTest.ts:25 still expected 16 calls. I updated it to 17, which matches MiddlewareRegistrationTest. Both tests pass locally.

Check independent approval is also failing. It needs a reviewer approval, not a code change.

@MelvinBot

MelvinBot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 Android test steps verification results: ✅ pass

The PR's Tests section is still a TODO, so I tested steps derived from the PR description. Inline cell editing runs only on wide layouts (MoneyRequestReportTransactionItem.tsx:422), so on Android I checked the same Search auto-refetch path through the normal edit flow. The Expenses list loaded with no stuck skeleton, two back-to-back merchant edits (Alpha → Bravo → Charlie) settled on "Charlie" with no flip-back, and the list still showed "Charlie" after pull-to-refresh and reopening.
Reopened Expenses list after pull-to-refresh, still showing Charlie

Step Status
The Search Expenses list loads and shows at least one expense row, with no stuck loading skeletonAfter I created a manual expense (Alpha, $25.00), Spend → Expenses showed the row "Draft, Alpha, $25.00, Oct 26, Cash, Missing category." No skeleton or spinner appeared.
Expenses list showing the Alpha expense row
✅
Edit Merchant to "Bravo" and save, then immediately edit to "Charlie" and save. Details show "Charlie" with no flip-backAfter the Bravo save landed, I changed the merchant to Charlie and saved right away. The details screen settled on "Merchant, Charlie" and still showed it after a 3-second wait. A "Merchant, Bravo" check did not match, so the value did not revert.
Expense detail screen showing Merchant: Charlie
✅
Back on the Search Expenses list, the row shows "Charlie" and stays that way after the refetch settlesThe row updated to "Draft, Charlie, $25.00" right away. It still showed Charlie after a wait and a pull-to-refresh. The list was not stuck loading.
Expenses list row showing Charlie after returning from detail
✅
Pull to refresh and reopen the Expenses list. The row still shows "Charlie" with no new errorAfter pull-to-refresh, then Home → Spend → Expenses, the row still showed Charlie, $25.00, Draft. The red "Missing category" indicator was there from creation because the expense had no category. The edits added no new error.
Reopened Expenses list after pull-to-refresh, still showing Charlie
✅

view run · view recording

@MelvinBot

MelvinBot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 Web test steps verification results: ❌ fail

I couldn't test the fix on Web because the test browser blocked inline editing. These failures show a test-environment problem, not a confirmed bug in this PR. The PR's Tests section is still a TODO, so I wrote the steps from the PR description. The 2 expenses I created (Alpha $10, Delta $20) were in the Expenses table data, but the rows never painted on screen. A row-level element also covered the Merchant cell's Edit control, so clicking it opened the full report instead of an inline input. I couldn't slow the network in this browser, so the slow-network race was not reproduced. Someone needs to run the inline-edit steps by hand on a desktop browser.
Expenses table still blank on recheck after navigating away and back

Step Status
Spend → Expenses loads in wide layout with at least 2 rows, and the merchant cell supports inline editingAt 1440×900 and 1920×1080, the page's accessibility data listed both rows (Delta $20.00, Alpha $10.00), but the row area on screen was blank. The browser refused to click the Merchant cell's Edit control because a row text element covered it. Clicking that spot by position opened the full report instead of an inline input.
Expenses list header renders; row area blank despite accessibility tree showing dataExpenses table still blank on recheck after navigating away and back
❌
Inline-edit row 1 merchant to "Bravo", then right away to "Charlie". The cell shows "Charlie" with no flip-backNot run. No inline merchant input would open.
❌
Inline-edit row 1 merchant to "Echo", then right away row 2 to "Foxtrot". Both keep their new valuesNot run. Blocked for the same reason as step 2.
❌
Reload. Row 1 shows "Echo", row 2 shows "Foxtrot", nothing is stuck loading, and no new console errors appearNot run. No edits were made to check after reload. The tester saw no console errors during the run.
❌

view run · view recording

@ahmedGaber93

Copy link
Copy Markdown
Contributor

@MelvinBot merge main

…eSearchFlicker

Co-authored-by: ahmedGaber93 <ahmedGaber93@users.noreply.github.com>

# Conflicts:
#	src/libs/Middleware/register.ts
#	src/libs/actions/Search.ts
#	tests/unit/MiddlewareRegistrationTest.ts
@MelvinBot

Copy link
Copy Markdown
Contributor Author

Merged main into this branch and pushed it in 7f10004.

Main and this PR changed the same lines in three files. I kept both sides in each:

  • src/libs/actions/Search.ts: search() now takes both shouldDiscardStaleSnapshot and main's shouldReturnTripRooms. I also pass shouldReturnTripRooms to the re-run that follows a dropped stale snapshot. Without it, that re-run would return travel expenses instead of trip rooms.
  • src/libs/Middleware/register.ts: DiscardStaleSearchSnapshot and main's ReconcileBulkEditReportAction both register before SaveResponseInOnyx.
  • Middleware tests: Both tests now expect 18 middlewares. Each branch had raised the count from 16 to 17.

I couldn't run the tests locally, so CI will be the first check of this merge.

@ahmedGaber93

Copy link
Copy Markdown
Contributor

@MelvinBot Please update

Tests

  1. Open the browser's Developer Tools and navigate to the Network tab.
  2. Throttle the network to a slow speed (e.g., 100 Kbps).
  3. Open an expense with an existing category (e.g., Category A).
  4. Edit the merchant, then quickly open the category picker without changing the category. Leave the picker open.
  5. Monitor the Network tab. Wait for the UpdateMoneyRequestMerchant request to finish and the subsequent search request to start.
  6. Before the search request completes, select Category B from the already-open category picker. Verify that Category B is applied optimistically in the UI.
  7. Once the search request completes, verify that Category B is still displayed and has not been overwritten by the original Category A returned by the search response.
  8. After both the UpdateMoneyRequestMerchant and search requests by step 6 have completed, verify that Category B is still displayed.

Offline tests

N/A.

QA Steps

Same as Tests step

PR Author Checklist

Mark all author checklist checked

@ahmedGaber93

Copy link
Copy Markdown
Contributor

@MelvinBot Mark this PR ready for review

@MelvinBot

Copy link
Copy Markdown
Contributor Author

I updated the PR description:

  • Tests: added your 8 steps.
  • Offline tests: set to N/A.
  • QA Steps: set to "Same as Tests steps."
  • PR Author Checklist: checked every item.

I left the "Verify that no errors appear in the JS console" checkbox in Tests and QA unchecked. Check it once you confirm it.


view run

@MelvinBot
MelvinBot marked this pull request as ready for review November 3, 2026 08:51
@MelvinBot
MelvinBot requested a review from a team as a code owner November 3, 2026 08:51
@MelvinBot

Copy link
Copy Markdown
Contributor Author

I marked this PR as ready for review.


view run

@melvin-bot
melvin-bot Bot requested review from ahmedGaber93 and removed request for a team November 3, 2026 08:51
@melvin-bot

melvin-bot Bot commented Nov 3, 2026

Copy link
Copy Markdown

@ahmedGaber93 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]

@melvin-bot
melvin-bot Bot requested review from flaviadefaria and removed request for a team November 3, 2026 08:51
@chatgpt-codex-connector

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

Copy link
Copy Markdown

Codex Review Summary

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-03T08:58:21.319767Z 7f10004 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.

@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: 7f10004041

ℹ️ 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".

const discardStaleSearchSnapshot: Middleware = (requestResponse, request) =>
requestResponse.then((response) => {
const hash = request?.data?.hash;
if (request?.command !== READ_COMMANDS.SEARCH || typeof hash !== 'number' || !guardedSearchHashes.has(hash) || !response?.onyxData || getPersistedRequestsLength() === 0) {

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P1 Badge Remember writes after they leave the queue

When an intervening edit's write completes and is removed from PersistedRequests before the older Search response resolves, this returns the response unchanged because the current queue length is zero, even though the server may have produced that snapshot before processing the write. No follow-up search is scheduled, so the table can remain reverted until another refresh; the guard needs to record whether any write was queued during the request rather than inspecting only the queue's state at response time.

AGENTS.md reference: AGENTS.md:L99-L101

Useful? React with 👍 / 👎.

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 fix this

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.

Fixed in e9d7466. The guard now remembers whether a write was queued while the search was in flight, even if that write has already finished. Before, it only checked for writes still in the queue.

  • PersistedRequests.ts has a new counter of every request ever queued, including ones merged from other tabs. Unlike getLength(), it never goes down.
  • DiscardStaleSearchSnapshot.ts records that count when it guards a search. When the response arrives, it drops the snapshot if the count has gone up or writes are still pending. The search then runs again and picks up the write.

One behavior change: any write queued during the search, including an unrelated one, now causes one extra re-run. Before, that only happened if the write was still pending when the response arrived. Each re-run records a fresh count, so it only repeats if yet another write is queued while it is in flight.

Tests and checks
  • New middleware tests: the snapshot is dropped when the write finished before the response arrived, and kept when the only writes were queued before the guard was set.
  • New PersistedRequests test: the counter still counts a request after it leaves the queue.
  • Passed: targeted Jest suites (80 suites, 2,205 tests), npm run typecheck, and lint and spell check on the changed files.
  • Not run: the oxfmt check and the full Jest suite.

view run

@@ -1401,6 +1409,7 @@ function search({
// A re-fire that only adds the save flag returns the same results the finished request just showed,

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 the stale guard through search deduplication

When this auto-refetch collides with an identical in-flight search and does not require a totals, recent-search, breakdown, or trip-room upgrade, the earlier inFlightRequest branch returns without creating this callback. Because shouldDiscardStaleSnapshot is not itself treated as an upgrade dimension, the existing pre-edit request remains unguarded and can overwrite the optimistic snapshot; schedule a guarded refire for this collision too.

AGENTS.md reference: AGENTS.md:L99-L101

Useful? React with 👍 / 👎.

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 Could you please explain this further here in this conversation?

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.

The finding is real but narrow. A guarded auto-refetch can merge into an unguarded search that is already running for the same query. When that happens, nothing guards the unguarded search, so its stale response can still flip an edited cell back.

Why it happens

  • search() lets only one request run per hash_offset (Search.ts:1378-1381). A second call with the same key joins the running one instead of sending its own request.
  • The joining call only schedules a re-run for four differences: totals, save-to-recent, footer breakdown or trip rooms (Search.ts:1386-1395). shouldDiscardStaleSnapshot isn't one of them. A guarded call that differs only in that flag returns undefined at Search.ts:1418, and its flag is lost.
  • The guard is only set inside a request's own waitForWrites().then (Search.ts:1608), and only when that request was started with the flag. A request started without the flag can never become guarded.

Example

  1. A report action calls refreshSearchAfterReportAction (SearchRefreshUtils.ts:17). That search is unguarded and waits for the write queue.
  2. You make edit 1. The auto-refetch (useSearchAutoRefetch.ts:183) calls search() with the guard flag. It merges into the waiting search and the flag is lost.
  3. Edit 1's write finishes, so the unguarded search is sent.
  4. You make edit 2 while that search is in flight.
  5. Its response lands and overwrites edit 2's optimistic value. This is the flip-back this PR is meant to fix.

How narrow it is

  • The auto-refetch skips search() entirely if the snapshot already shows isLoading (Search.ts:1374). So it only collides with an unguarded search that hasn't shown loading yet: one still waiting for writes, or one sent with shouldShowLoading: false.
  • This isn't a regression. Before this PR, no search was guarded.
  • When the merge does schedule a re-run (for example a totals upgrade), the re-run carries the flag and fixes the data. The cell can still flicker once before that.

Possible fixes

  • Full fix: store shouldDiscardStaleSnapshot on the running request. When a guarded call joins, upgrade the running request in place: set the flag, and if it has already been sent, guard it right away. This stops the flicker.
  • Smaller fix: treat a missing guard as another reason to re-run, like the other four. The data ends up correct, but the cell can still flicker once.

I haven't changed any code for this. To have me make one of these fixes, reply @MelvinBot with the one you want.


view run

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.

A request started without the flag can never become guarded.

Ah, normal search call still reproduce this issue.

Screen.Recording.2026-11-03.at.3.10.12.PM.mov

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 Please go with the full fix

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.

The full fix is in ad79a38. A refetch that wants the guard now passes it to the search already running for the same query. This also covers the normal search case in your video, where the results already show loading.

What changed

  • The guard joins the running search (Search.ts:1382-1397). This happens before the isLoading check, so the loading case no longer drops it.
    • If that search is still waiting for writes, it guards itself when it is sent.
    • If it was already sent, it is guarded right away. Writes are counted from when it was sent, so the edit's write counts even if it finishes first.
  • Each in-flight search stores its guard state: the flag, the query it sent, and the queued-request count when it was sent. The guard is set at Search.ts:1643. guardSearchAgainstStaleSnapshot now takes that count.
  • A late join still re-runs (Search.ts:1501). If the refetch joins after the response already passed the guard, the stale snapshot is applied. But a write queued since the search was sent schedules a guarded re-run, which corrects it.
  • Re-runs keep the guard. A re-run set up by a joining call, for example a totals upgrade, is guarded too.

A search started with skipWaitForWrites is still never guarded, so it can't loop.

Tests and checks
  • New search() tests:
    • A guarded refetch joins a search already sent while it shows loading. That search is guarded with the count from when it was sent, and runs again after its snapshot is dropped.
    • A guarded refetch joins a search still waiting for writes, which then guards itself when sent. Only one request goes out.
    • A write queued since sending causes a re-run even when the snapshot passed the guard.
  • New middleware test: writes are counted from when the search was sent, even if it is guarded later.
  • Passed: targeted Jest suites (79 suites, 2,183 tests), npm run typecheck, and lint and spell check on the changed files.
  • Not run: the oxfmt check, the full Jest suite, and a manual repro of your video's flow.

view run

@ahmedGaber93

ahmedGaber93 commented Nov 3, 2026 •

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 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 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 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

Android: HybridApp
Android: mWeb Chrome
iOS: HybridApp
iOS: mWeb Safari
MacOS: Chrome / Safari
Screen.Recording.2026-11-03.at.11.44.18.PM.mov

@ahmedGaber93

Copy link
Copy Markdown
Contributor

@MelvinBot review

@MelvinBot

Copy link
Copy Markdown
Contributor Author

Review: changes needed

The approach is sound: the middleware runs before SaveResponseInOnyx, it drops only snapshot_<hash>, and the guards are released on success, error and cancel. But the guard decides "stale" by checking whether the write queue is non-empty at response time, and it is keyed by hash only. That misses real races in some cases and drops good responses in others. Both Codex findings hold up.

One change fixes 1–3 together. Record a write watermark when the guard is set, for example a counter bumped in PersistedRequests.save(). Then key the guard per request (hash + offset or a token), not per hash. Discard only when the counter has moved past the watermark.

# Severity Issue
1 P2
A write that finishes before the Search response is missed (Codex P1)DiscardStaleSearchSnapshot.ts:40 checks getPersistedRequestsLength() === 0 only at response time. Writes run on their own queue, so the edit-2 write can finish and leave the queue before the slower Search response lands. The stale snapshot is then applied. Nothing re-runs the search: useSearchAutoRefetch.ts:104 bails while the first search is loading. The cell stays reverted until the next refresh.
2 P2
Back-to-back re-run loop in a second browser tabIn a tab that isn't the queue leader, flush() resolves waitForIdle right away (SequentialQueue.ts:662-671). But getPersistedRequestsLength() still counts the leader's shared writes. That tab's guarded search is sent, then dropped, then re-run (Search.ts:1476-1491), once per round trip until the leader drains its queue. A per-tab watermark avoids this. A re-run cap (for example 2) is a cheap backstop. Plausible: confirmed in code, not reproduced.
3 P2
Hash-only guard drops other requests on the same hashThe guard sets at DiscardStaleSearchSnapshot.ts:11-14 are keyed by hash, while in-flight searches are keyed by hash_offset. While a guarded refetch is in flight, an unguarded "load more" page for the same hash also has its snapshot dropped. That page is never re-run, and its discard flag triggers a re-run of the wrong request. Also, the first guarded search to finish removes the guard from a second one on the same hash.
4 P3
A guarded refetch that dedups into an unguarded in-flight search gets no guard (Codex P2)shouldDiscardStaleSnapshot is not an upgrade condition in the dedup branch (Search.ts:1379-1417), so the call returns with no guard. Example: refreshSearchAfterReportAction is parked in waitForWrites, edit 1 dedups into it, it is sent, edit 2 lands, and the response flips edit 2 back. Fix: store shouldDiscardStaleSnapshot on the in-flight request and upgrade it in place, guarding it at once if it was already sent. The window is narrow, and this was not guarded before the PR either.
5 P3
The re-run can fire offline and replace cached rows with an errorIf the network drops while the edit-2 write is retrying, flush() resolves (offline) and the re-run is sent. The fetch fails, and the catch path writes errors to the snapshot. Check isOffline() before re-running and leave it to the auto-refetch's reconnect handling. Plausible, not reproduced.
6 P3
The tests don't exercise the race end to endsearchDiscardStaleSnapshotTest.ts mocks both @libs/API and the middleware. Add tests for: queue empty at response time but a write queued mid-flight (1), and two offsets on one hash (3).

To have me make these fixes, reply @MelvinBot implement the review fixes (or name the ones you want).


view run

@luacmartins
luacmartins self-requested a review November 17, 2026 16:13
@luacmartins

Copy link
Copy Markdown
Contributor

@ahmedGaber93 let's go with option 2. I think the inflight invalidation would be fine in this case

@ahmedGaber93

Copy link
Copy Markdown
Contributor

@MelvinBot Please implement option 2 here #104997 (comment)

Co-authored-by: ahmedGaber93 <ahmedGaber93@users.noreply.github.com>
@MelvinBot

Copy link
Copy Markdown
Contributor Author

🤖 Web test steps verification results: ❌ fail

Implemented option 2 and pushed 4781973: inline edits explicitly invalidate sent Search snapshots, with no queue counter; 76 suites (2,104 tests), lint, typecheck, formatting, spelling and Storybook passed, while full Jest timed out. Browser verification was blocked by unsupported DevTools/throttling controls—not a confirmed product failure.

Step Status
1. Open Network viewBlocked: DevTools control is unsupported.
❌
2. Throttle to approximately 100 KbpsBlocked: network throttling is unsupported.
❌
3. Open an expense with Category ANot executed because the required network setup was unavailable.
❌
4. Edit merchant and leave category picker openNot executed.
❌
5. Observe merchant update finish and Search startNot verified.
❌
6. Select Category B before Search completesOptimistic appearance not verified.
❌
7. Category B remains after Search completesNot verified.
❌
8. Category B remains after both requests finishNot verified.
❌
9. No new JavaScript console errorsNot verified; the reproduction was not run.
❌

view run

@ahmedGaber93

Copy link
Copy Markdown
Contributor

@MelvinBot merge main

Co-authored-by: ahmedGaber93 <ahmedGaber93@users.noreply.github.com>
@MelvinBot

Copy link
Copy Markdown
Contributor Author

Merged main, resolved the conflicts, and pushed 1962ee3.

Passed: 88 targeted suites (2,439 tests), lint, formatting, spelling and Storybook. Typecheck failed on React Native web type incompatibilities; full Jest timed out.


view run

@ahmedGaber93 ahmedGaber93 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 Please fix

Comment thread src/libs/actions/Search.ts Outdated
Comment on lines +1711 to +1717

// The queue can also become idle offline. Keep cached results until the reconnect refetch.
if (getIsOffline()) {
inFlightSearchRequests.delete(dedupeKey);
return undefined;
}

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.

I think this change isn't needed for what this PR fixes. It changes how every Search behaves offline, not only after inline edits, so let's remove it and related tests.

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.

We don't need this test now, please remove it.

@ahmedGaber93

Copy link
Copy Markdown
Contributor

@MelvinBot please address this changes #104997 (review)

Co-authored-by: ahmedGaber93 <ahmedGaber93@users.noreply.github.com>
@MelvinBot

Copy link
Copy Markdown
Contributor Author

Addressed both review comments in ffc71de:

  • Removed the general offline Search guard and related test.
  • Removed the unrelated cross-tab test.
  • Kept offline protection for stale-snapshot refetches.

115 targeted tests, typecheck, lint, formatting, spelling and Storybook passed. Full Jest timed out.


view run

@MelvinBot

Copy link
Copy Markdown
Contributor Author

Both requested changes are already addressed in ffc71de:

  • Removed the general offline Search guard and related test.
  • Removed the unrelated cross-tab test.
  • Preserved offline protection specifically for stale-snapshot refetches.

Verified against the current PR head; no additional changes were needed.


view run

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 tests/unit/useSearchAutoRefetchTest.ts only has line-wrapping changes left (git diff -w shows nothing), from the removed shouldDiscardStaleSnapshot assertions. Can we revert it to main so it drops out of the diff?

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.

Restored it to main in 207d04f, and confirmed it no longer appears in the PR diff.

All 43 tests passed. Changed-file lint, spelling and formatting passed; full lint and typecheck timed out.


view run

Co-authored-by: ahmedGaber93 <ahmedGaber93@users.noreply.github.com>
@ahmedGaber93

ahmedGaber93 commented Nov 18, 2026 •

Copy link
Copy Markdown
Contributor

@MelvinBot A small improvement from Claude (reviewed it locally): only mark in-flight Searches for the edited snapshot's hash as stale, instead of all of them. If you agree, please apply it and update the tests that call markInFlightSearchRequestsStale() to pass the hash.


markInFlightSearchRequestsStale() marks every sent Search, including ones for other queries (Home sections, a preloaded tab, the tab you're not on). If one of those is loading for the first time, its snapshot data is dropped. But finallyData still sets state: loaded / isLoading: false, and the refetch runs with shouldShowLoading: false. So it shows the empty state until the refetch returns, or until the next refetch after reconnecting if the app went offline meanwhile.

The edit only writes optimistic data to snapshot_<hash> for the search it was made in (getSearchSnapshotOnyxData in UpdateMoneyRequest.ts), so only requests for that hash can revert it. Suggest passing the edit's hash and only marking matching requests:

  function markInFlightSearchRequestsStale(hash: number | undefined) {
      for (const request of inFlightSearchRequests.values()) {
          if (!request.isSent || request.hash !== hash) {
              continue;
          }
          markSearchSnapshotStale(request.jsonQuery);
      }
  }

with hash: queryJSON.hash stored on InFlightSearchRequest and markInFlightSearchRequestsStale(params.hash) in the 6 inline edit functions. The edited search always already shows rows, so it can't flash empty. An edit from the Expense Report page has no hash and writes no snapshot, so it marks nothing, which is correct.

Suggested diff
diff --git a/src/libs/actions/Search.ts b/src/libs/actions/Search.ts
--- a/src/libs/actions/Search.ts
+++ b/src/libs/actions/Search.ts
@@ -1293,6 +1293,7 @@ type InFlightSearchRequest = {
     pendingShouldSaveRecentSearch?: boolean;
     pendingUpgradeRequest?: () => Promise<string | number | undefined> | undefined;
     didSucceed?: boolean;
+    hash: number;
     jsonQuery: string;
     /** False while the request waits for writes. */
     isSent: boolean;
@@ -1309,13 +1310,14 @@ const inFlightSearchRequests = new Map<string, InFlightSearchRequest>();
 /**
  * Invalidates sent Search snapshots before an inline edit applies its optimistic update. Requests waiting for writes
  * already include the edit when they are sent. Call synchronously before the edit's write so a Search cannot slip between them.
+ * Only the edited snapshot is invalidated: the edit writes no other snapshot, and dropping one still loading would show it empty.
  */
-function markInFlightSearchRequestsStale() {
-    for (const {jsonQuery, isSent} of inFlightSearchRequests.values()) {
-        if (!isSent) {
+function markInFlightSearchRequestsStale(hash: number | undefined) {
+    for (const request of inFlightSearchRequests.values()) {
+        if (!request.isSent || request.hash !== hash) {
             continue;
         }
-        markSearchSnapshotStale(jsonQuery);
+        markSearchSnapshotStale(request.jsonQuery);
     }
 }
 
@@ -1546,6 +1548,7 @@ function search({
         shouldSaveRecentSearch: shouldSaveSearchToAccount,
         footerTotal,
         shouldReturnTripRooms: isTripRoomsSearch,
+        hash: queryJSON.hash,
         jsonQuery,
         isSent: false,
     };
diff --git a/src/libs/actions/TransactionInlineEdit.ts b/src/libs/actions/TransactionInlineEdit.ts
--- a/src/libs/actions/TransactionInlineEdit.ts
+++ b/src/libs/actions/TransactionInlineEdit.ts
@@ -265,7 +265,7 @@ function getIouParamsForTransaction({
 function editTransactionDateInline(params: TransactionInlineEditParams, newDate: string, personalPolicyOutputCurrency: string | undefined) {
     const iouParams = getIouParamsForTransaction(params);
 
-    markInFlightSearchRequestsStale();
+    markInFlightSearchRequestsStale(params.hash);
     updateMoneyRequestDate({
         isVendorMatchingBetaEnabled: params.isVendorMatchingBetaEnabled,
         ...iouParams,
@@ -297,7 +297,7 @@ function editTransactionMerchantInline(translate: LocalizedTranslate, params: Tr
     // Building params can create a transaction thread, so do it only once the merchant is valid.
     const iouParams = getIouParamsForTransaction(params);
 
-    markInFlightSearchRequestsStale();
+    markInFlightSearchRequestsStale(params.hash);
     updateMoneyRequestMerchant({
         isVendorMatchingBetaEnabled: params.isVendorMatchingBetaEnabled,
         ...iouParams,
@@ -321,7 +321,7 @@ function editTransactionDescriptionInline(translate: LocalizedTranslate, params:
     }
 
     const iouParams = getIouParamsForTransaction(params);
-    markInFlightSearchRequestsStale();
+    markInFlightSearchRequestsStale(params.hash);
     updateMoneyRequestDescription({
         isVendorMatchingBetaEnabled: params.isVendorMatchingBetaEnabled,
         ...iouParams,
@@ -333,7 +333,7 @@ function editTransactionDescriptionInline(translate: LocalizedTranslate, params:
 /** Updates the category of an expense from the Search results table or the Expense Report page. */
 function editTransactionCategoryInline(params: TransactionInlineEditParams, newCategory: string) {
     const iouParams = getIouParamsForTransaction(params);
-    markInFlightSearchRequestsStale();
+    markInFlightSearchRequestsStale(params.hash);
     updateMoneyRequestCategory({
         isVendorMatchingBetaEnabled: params.isVendorMatchingBetaEnabled,
         ...iouParams,
@@ -364,7 +364,7 @@ function editTransactionAmountInline(translate: LocalizedTranslate, params: Tran
     const taxPercentage = getTaxValue(iouParams.policy, iouParams.transaction, taxCode) ?? '';
     const decimals = params.getCurrencyDecimals(getCurrency(iouParams.transaction));
     const taxAmount = convertToBackendAmount(calculateTaxAmount(taxPercentage, newAmount, decimals));
-    markInFlightSearchRequestsStale();
+    markInFlightSearchRequestsStale(params.hash);
     updateMoneyRequestAmountAndCurrency({
         isVendorMatchingBetaEnabled: params.isVendorMatchingBetaEnabled,
         ...iouParams,
@@ -384,7 +384,7 @@ function editTransactionAmountInline(translate: LocalizedTranslate, params: Tran
 /** Updates the tag of an expense from the Search results table or the Expense Report page. */
 function editTransactionTagInline(params: TransactionInlineEditParams, newTag: string) {
     const iouParams = getIouParamsForTransaction(params);
-    markInFlightSearchRequestsStale();
+    markInFlightSearchRequestsStale(params.hash);
     updateMoneyRequestTag({
         isVendorMatchingBetaEnabled: params.isVendorMatchingBetaEnabled,
         ...iouParams,

Co-authored-by: ahmedGaber93 <ahmedGaber93@users.noreply.github.com>
@MelvinBot

Copy link
Copy Markdown
Contributor Author

Agreed—applied in 2a4f989.

  • Only sent Searches matching the edited hash are invalidated, across all offsets.
  • Undefined hashes invalidate nothing.
  • Updated all six callers and added regression coverage.

2,427 targeted tests, typecheck, lint, formatting, spelling and Storybook passed. Full Jest timed out.


view run

@ahmedGaber93 ahmedGaber93 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!

@ahmedGaber93

Copy link
Copy Markdown
Contributor

@luacmartins All yours!

@luacmartins
luacmartins merged commit 5f3ba46 into main Nov 18, 2026
46 of 48 checks passed
@luacmartins
luacmartins deleted the claude-inlineEditStaleSearchFlicker branch November 18, 2026 19:04
@github-actions

Copy link
Copy Markdown
Contributor

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

@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.

@github-actions

Copy link
Copy Markdown
Contributor

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/luacmartins in version: 9.5.42-0 🚀

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

@MelvinBot

Copy link
Copy Markdown
Contributor Author

No help site update needed — this PR fixes edited expense values briefly reverting on slow connections, restoring expected behavior without introducing a new workflow or making existing instructions incorrect.


view run

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/marcaaron in version: 9.5.42-2 🚀

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

Bundle Size Analysis (Sentry):

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