Skip to content

Update the to-do "Select all" count when a report leaves the list - #104015

Merged
justinpersaud merged 10 commits into
mainfrom
claude-liveTodoSelectAllReportCount
Oct 19, 2026
Merged

justinpersaud merged 10 commits into
mainfrom
claude-liveTodoSelectAllReportCount

Conversation

@MelvinBot

@MelvinBot MelvinBot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

On the to-do tabs (Drafts, Needs approval, Ready to pay and Awaiting export), the rows come from data on the device, but "N selected" after "Select all" shows the report count the server sent with the first page. Submitting a report from its row removes the row right away, but nothing updates that count, so the label stays at N.

The label can't just count the reports on the device. "Select all" actions send the search itself, so the server acts on every matching report, including ones this device hasn't loaded. The number has to stay the server's.

This PR:

  • Saves which expense reports each to-do search response contained.
  • Shows the server's count minus the saved reports that are no longer in the list. The label drops as soon as a report leaves, whether it was submitted, approved, paid or exported, here or on another device, with no extra request. Nothing is subtracted until local data has finished loading, so reports that haven't loaded yet don't count as gone.
  • Loads more pages on these tabs without asking for a new count. Before, the first next-page request asked for one. A response with a count starts the saved list over, so a count with a later page would drop the first page's reports from it. "Select all" after scrolling still asks for a fresh count, as before.
  • Fixes how the response is read. To-do search responses put the results last, but the code read the first entry, so every to-do search logged a false empty-result message.

Known limit: reports that join the list, and reports that leave from pages loaded before the last fresh count, only show up in the count the next time the server sends one, for example when the first page reloads after bulk Submit or a report's Submit or Pay. Until then it can be one off for each such report.

Fixed Issues

$ #102298
PROPOSAL: #102298 (comment)

Tests

Prerequisite: use an account with at least 55 draft reports in a workspace, each with at least one expense. For the phone test you also need a second device, or a different browser signed in to the same account. Don't use a second tab of the same browser.

  1. Go to Spend > Drafts.
  2. Press the checkbox at the top of the list.
  3. Verify a menu opens with "Select all on this page" and "Select all". Choose "Select all".
  4. Note the number in the "N selected" bar at the bottom of the list. This is N.
  5. Press the checkbox again to clear the selection.
  6. Press "Submit" on any report row. Some workspaces show "Done" instead.
  7. Verify the report leaves the list.
  8. Press the checkbox and choose "Select all".
  9. Verify the bar shows N−1 straight away.
  10. Wait a few seconds and verify it still shows N−1.
  11. Press the checkbox to clear the selection, then scroll to the bottom of the list until more reports load.
  12. Press "Submit" on one of the newly loaded reports, below the first 50.
  13. Press the checkbox. If a menu opens, choose "Select all".
  14. Verify the bar shows N−2.
  15. Press the checkbox to clear the selection. Check the boxes of two reports, then press "Submit" in the bar at the bottom of the list.
  16. Verify both reports leave the list. Then press the checkbox, choose "Select all" if a menu opens, and verify the bar shows N−4.
  17. Reload the page and go back to Spend > Drafts.
  18. Press the checkbox, choose "Select all", and verify the bar still shows N−4.

Web and desktop, Needs approval (only if the account has more than 50 reports waiting for its approval)

  1. Go to Spend > Needs approval.
  2. Press the checkbox, choose "Select all", and note N in the bar at the bottom.
  3. Press the checkbox again to clear the selection.
  4. Press "Approve" on any report row and verify the report leaves the list.
  5. Press the checkbox, choose "Select all", and verify the bar shows N−1.

iOS, Android and mobile web

  1. Go to Spend and tap the Drafts tab.
  2. Long-press any report and tap "Select". Tap the same report again to unselect it.
  3. Tap "Select all" at the top of the list and choose "Select all" from the menu.
  4. Note the number on the green "N selected" button at the top. This is N.
  5. Keep everything selected. On the second device or browser, submit any draft report.
  6. On the phone, verify that report leaves the list and the button shows N−1 without leaving the page.
  • Verify that no errors appear in the JS console

Offline tests

Same as tests

QA Steps

Same as tests

  • 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 followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • 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 followed the guidelines as stated in the Review Guidelines
  • 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 any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • 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 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.
  • 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

Live to-do searches now take reportCount from Onyx instead of the stale server snapshot, so the select-all count drops after a report leaves the bucket. The select-all menu only offers selecting every match when the row cap holds back rows, and selecting all on a live search no longer requests totals.

Co-authored-by: TaduJR <TaduJR@users.noreply.github.com>
@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 14, 2026
@MelvinBot
MelvinBot requested a review from a team October 14, 2026 16:09
@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-liveTodoSelectAllReportCount
git checkout -b claude-liveTodoSelectAllReportCount upstream/claude-liveTodoSelectAllReportCount
git push -u origin claude-liveTodoSelectAllReportCount

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

@MelvinBot

Copy link
Copy Markdown
Contributor Author

The failing ESLint check is unrelated to this PR, so I didn't push a fix.

Analysis: Both errors are in files this PR doesn't touch. They come from main:

  • src/libs/Navigation/helpers/swapBackgroundTabForRHPTarget.ts:41:74 — @typescript-eslint/no-unnecessary-type-assertion
  • tests/unit/ReportUtilsGetIconsTest.ts:129:19 — @typescript-eslint/no-unsafe-assignment

Evidence: The same two errors fail ESLint on several unrelated PRs opened today, for example the fix/onboarding-join-empty-last-name and claude-inlineEditPickerOverlap branches.

Next step: [No QA] Remove useless Onyx.connect causing lint failures fixes the ReportUtilsGetIconsTest.ts error. I found no open PR for the swapBackgroundTabForRHPTarget.ts error. It touches a file last changed in [NoQA] Fix import/no-cycle - part 16. Once both are fixed on main, merge main into this branch and the check should pass.

Check independent approval also fails, but it only needs a reviewer approval.

@MelvinBot

MelvinBot commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 Android test steps verification results: ✅ pass

With 51 draft reports, "Select all" showed 51 selected. After submitting one report, "Select all" showed 50, not a stale 51. The PR's Tests section is still a TODO, so I ran the reproduction steps from [$175] Spend - Select all count is stale after submitting a report.
50 selected after submit

Step Status
Account has more than 50 draft expense reports, listed under Spend > Reports > DraftsCreated a workspace and 51 draft reports. The Drafts tab badge read "50+", which is past the 50-row page size needed to reproduce the bug.
Drafts tab showing 50+ badge
✅
Select all (using "Select all matching" when offered) shows N selected equal to the total number of draft reportsTapping "Select all items" offered "Select all on this page" and "Select all". Choosing "Select all" showed "51 selected", which matches the total.
51 selected
✅
Deselect all leaves nothing selectedTapping the "Select all items" checkbox again showed "0 selected", and every row was unchecked.
0 selected
✅
Submitting one draft report removes it from the Drafts listSubmitted the report with a $15.00 expense ("Draft Merchant 1"). Its status changed to Outstanding, and the Drafts badge changed from "50+" to "50".
Drafts badge reading 50 after submit
✅
After submitting, Select all shows a count exactly one lower than before"Select all items" on Drafts showed "50 selected", which matches the new total. It did not show the old value of 51.
50 selected after submit
✅

view run · view recording

@MelvinBot

Copy link
Copy Markdown
Contributor Author

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

Run details

@TaduJR

TaduJR commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

@MelvinBot

Please merge main

…AllReportCount

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

Copy link
Copy Markdown
Contributor Author

🤖 I merged main into this branch in 21ef3b7. The merge brought in 455 commits and had no conflicts.

I couldn't run the tests or the type check locally on this run, so please check CI on the new commit.


view run

@TaduJR

TaduJR commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

@MelvinBot

Please replace your PR description with the below

Description

Explanation of Change

On to-do searches like Drafts, the list is built from live Onyx data, so a report drops out of it once you submit it. The "N selected" count after "Select all" didn't follow. It read the report count the server sent when the list loaded, and submitting from a row's Submit button doesn't ask the server again, so the old number stayed.

This PR changes three things on to-do searches:

  • The matching-report count now comes from the same live data as the list, so the "Select all" count drops as soon as a report leaves the list, including offline.
  • "Select all" only offers the "Select all on this page / Select all" choice when the list is still holding back reports below the ones shown. Before, it used the server's old "more results" flag, so going from 51 drafts to 50 still showed the choice even though every report was already on screen.
  • "Select all" no longer sends a totals request to the server, since those numbers are no longer used.

Fixed Issues

$ #102298
PROPOSAL: #102298 (comment)

Tests

Before you start: sign in to an account on a Collect or Control workspace that has more than 50 draft reports.

Test 1: "Select all" count after submitting a report (web and desktop)

  1. Go to Spend > Drafts.
  2. Click the checkbox at the top of the list. If a menu opens, click "Select all".
  3. Note the number shown in "N selected".
  4. Click the X on the selection bar to clear the selection.
  5. Click "Submit" on any report that has a Submit button. If "Submit report?" appears, click "Submit anyway".
  6. Verify the report leaves the list.
  7. Click the checkbox at the top of the list. If a menu opens, click "Select all".
  8. Verify the number is one less than in step 3.

Test 2: Same check while offline

  1. Go to Spend > Drafts and select all as in Test 1. Note the number, then clear the selection.
  2. Go offline.
  3. Open any report and submit it. If "Submit report?" appears, choose "Submit anyway". Go back to Drafts.
  4. Select all again.
  5. Verify the number is one less than in step 1.

On mobile: long-press a report and tap "Select", then tap "Select all" at the top of the list. The number is on the "N selected" button at the top of the screen. Tap the back arrow to leave selection mode before opening a report.

Test 3: Exactly 50 drafts left

Before you start: have exactly 51 draft reports, so "Select all" shows "51 selected".

  1. Go to Spend > Drafts.
  2. Click "Submit" on any report row. If "Submit report?" appears, click "Submit anyway".
  3. Verify the Drafts badge in the left menu shows 50.
  4. Click the checkbox at the top of the list.
  5. Verify every report is selected right away, without the "Select all on this page / Select all" menu, and the count shows "50 selected".

Test 4: Reports page still offers selecting everything (more than 50 reports)

  1. Go to Spend > Reports.
  2. Click the checkbox at the top of the list.
  3. Verify a menu opens with "Select all on this page" and "Select all".
  4. Click "Select all" and verify the count is higher than 50.
  • Verify that no errors appear in the JS console

Offline tests

Same as tests

QA Steps

Same as tests

  • 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 followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • 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 followed the guidelines as stated in the Review Guidelines
  • 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 any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • 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 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.
  • 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

Also please apply this one-line comment fix.

diff --git a/tests/unit/Search/SearchResultsProviderLiveReportCountTest.tsx b/tests/unit/Search/SearchResultsProviderLiveReportCountTest.tsx
--- a/tests/unit/Search/SearchResultsProviderLiveReportCountTest.tsx
+++ b/tests/unit/Search/SearchResultsProviderLiveReportCountTest.tsx
@@ -133 +133 @@ describe('SearchResultsProvider live to-do report count', () => {
-        // Then the count the "Select all" label and the footer read drops by one, the same as the Drafts badge
+        // Then the count the "Select all" label reads drops by one, the same as the Drafts badge

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

Copy link
Copy Markdown
Contributor Author

Done. I replaced the PR description with your text and pushed the one-line comment fix to SearchResultsProviderLiveReportCountTest.tsx in 99ee549.


view run

@TaduJR

TaduJR commented Oct 15, 2026

Copy link
Copy Markdown
Contributor

@codex review

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 15, 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-10-17T06:23:16.401328Z c49f8ce 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[bot]

This comment was marked as resolved.

@TaduJR

TaduJR commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

@MelvinBot

Please replace your PR description with the below

Description

Explanation of Change

On the to-do tabs (Drafts, Needs approval, Ready to pay and Awaiting export), the rows come from data on the device, but "N selected" after "Select all" shows the report count the server sent with the first page. Submitting a report from its row removes the row right away, but nothing updates that count, so the label stays at N.

The label can't just count the reports on the device. "Select all" actions send the search itself, so the server acts on every matching report, including ones this device hasn't loaded. The number has to stay the server's.

This PR:

  • Saves which expense reports each to-do search response contained.
  • Shows the server's count minus the saved reports that are no longer in the list. The label drops as soon as a report leaves, whether it was submitted, approved, paid or exported, here or on another device, with no extra request. Nothing is subtracted until local data has finished loading, so reports that haven't loaded yet don't count as gone.
  • Asks for a new count only with the first page on these tabs. Before, the first next-page request asked for one, and so did "Select all" after scrolling. A count from a later page already leaves out reports submitted before it, but they're still in the saved list, so they'd come off twice. If the count is missing, "Select all" still asks for it.
  • Makes the "Select all" menu compare that count with the loaded rows from the saved reports, instead of the server's "more results" flag, which can be wrong once reports have left the list.
  • Fixes how the response is read. To-do search responses put the results last, but the code read the first entry, so every to-do search logged a false empty-result message.

Known limit: reports that join the list after it loads, like a draft created on another device, aren't added to the count until the list reloads from the first page (for example after reopening the tab or reloading the page). Until then the count can be one low, and if one of those reports leaves again first, it can stay one low.

Fixed Issues

$ #102298
PROPOSAL: #102298 (comment)

Tests

Prerequisite: use an account with at least 55 draft reports in a workspace, each with at least one expense. For the phone test you also need a second device, or a different browser signed in to the same account. Don't use a second tab of the same browser.

  1. Go to Spend > Drafts.
  2. Press the checkbox at the top of the list.
  3. Verify a menu opens with "Select all on this page" and "Select all". Choose "Select all".
  4. Note the number in the "N selected" bar at the bottom of the list. This is N.
  5. Press the checkbox again to clear the selection.
  6. Press "Submit" on any report row. Some workspaces show "Done" instead.
  7. Verify the report leaves the list.
  8. Press the checkbox and choose "Select all".
  9. Verify the bar shows N−1 straight away.
  10. Wait a few seconds and verify it still shows N−1.
  11. Press the checkbox to clear the selection, then scroll to the bottom of the list until more reports load.
  12. Press "Submit" on one of the newly loaded reports, below the first 50.
  13. Press the checkbox. If a menu opens, choose "Select all".
  14. Verify the bar shows N−2.
  15. Press the checkbox to clear the selection. Check the boxes of two reports, then press "Submit" in the bar at the bottom of the list.
  16. Verify both reports leave the list. Then press the checkbox, choose "Select all" if a menu opens, and verify the bar shows N−4.
  17. Reload the page and go back to Spend > Drafts.
  18. Press the checkbox, choose "Select all", and verify the bar still shows N−4.

Web and desktop, Needs approval (only if the account has more than 50 reports waiting for its approval)

  1. Go to Spend > Needs approval.
  2. Press the checkbox, choose "Select all", and note N in the bar at the bottom.
  3. Press the checkbox again to clear the selection.
  4. Press "Approve" on any report row and verify the report leaves the list.
  5. Press the checkbox, choose "Select all", and verify the bar shows N−1.

iOS, Android and mobile web

  1. Go to Spend and tap the Drafts tab.
  2. Long-press any report and tap "Select". Tap the same report again to unselect it.
  3. Tap "Select all" at the top of the list and choose "Select all" from the menu.
  4. Note the number on the green "N selected" button at the top. This is N.
  5. Keep everything selected. On the second device or browser, submit any draft report.
  6. On the phone, verify that report leaves the list and the button shows N−1 without leaving the page.
  • Verify that no errors appear in the JS console

Offline tests

Same as tests

QA Steps

Same as tests

  • 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 followed proper code patterns (see Reviewing the code)
    • I verified that any callback methods that were added or modified are named for what the method does and never what callback they handle (i.e. toggleReport and not onIconClick)
    • 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 followed the guidelines as stated in the Review Guidelines
  • 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 any new file was added I verified that:
    • The file has a description of what it does and/or why is needed at the top of the file if the code is not self explanatory
  • 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 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.
  • 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

Also please resolve and make them hidden the above codex comments

I will give you the updated code on next comment.

@MelvinBot

Copy link
Copy Markdown
Contributor Author

Done, TaduJR:

  • I replaced the PR description with the text you sent.
  • I resolved both Codex review threads and hid them as resolved. I also hid the Codex review summary.

I haven't changed any code yet. Send the updated code in your next comment and I'll apply it.


view run

@TaduJR

TaduJR commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

@MelvinBot

Please delete the outer details of the PR description

@MelvinBot

Copy link
Copy Markdown
Contributor Author

Done, TaduJR. I removed the outer "Description" <details> wrapper from the PR description. The rest of the description is unchanged, including the five platform <details> blocks under Screenshots/Videos.


view run

@TaduJR

TaduJR commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

@MelvinBot

Please update this PR to the final code. This comment has the source changes. I'll send the test changes in the next one.

  1. Revert every file in this PR to main, so no changes are left. This removes the live device count, the hasMoreMatchingItems prop and their tests, including SearchSelectAllMenuTest.tsx.
  2. Apply the diff below. It changes 6 source files and applies cleanly on current main.
  3. In the PR description, delete this bullet from the Explanation of Change, since the "Select all" menu now keeps main's behavior:
    • Makes the "Select all" menu compare that count with the loaded rows from the saved reports, instead of the server's "more results" flag, which can be wrong once reports have left the list.
  4. Change the PR title to: Update the to-do "Select all" count when a report leaves the list
Source diff
diff --git a/src/components/Search/SearchResultsProvider.tsx b/src/components/Search/SearchResultsProvider.tsx
--- a/src/components/Search/SearchResultsProvider.tsx
+++ b/src/components/Search/SearchResultsProvider.tsx
@@ -55,3 +55,3 @@ function SearchResultsProvider({children}: SearchResultsProviderProps) {
     const {footerTotal} = isBetaEnabled(CONST.BETAS.SPEND_FOOTER_SELECTORS) ? getFooterSelectionFromQuery(currentSearchQueryJSON) : {footerTotal: undefined};
-    const liveTodoData = useTodoSearchResults(shouldUseLiveData ? currentSearchKey : undefined, footerTotal);
+    const liveTodoData = useTodoSearchResults(shouldUseLiveData ? currentSearchKey : undefined, footerTotal, snapshotSearchResults?.search);
 
@@ -67,2 +67,3 @@ function SearchResultsProvider({children}: SearchResultsProviderProps) {
             currency: liveData.metadata.currency,
+            reportCount: liveData.metadata.reportCount,
         };
diff --git a/src/components/Search/index.tsx b/src/components/Search/index.tsx
--- a/src/components/Search/index.tsx
+++ b/src/components/Search/index.tsx
@@ -229,5 +229,2 @@ function Search({
     const shouldCalculateExpenseTotals = useSearchShouldCalculateTotals(currentSearchKey, offset === 0 || isAllMatchingItemsCountMissing, isExpenseAllMatchingSelection);
-    const shouldCalculateTotals = (areAllMatchingItemsSelected && !isExpenseAllMatchingSelection) || shouldCalculateExpenseTotals;
-    const previousShouldCalculateTotals = usePrevious(shouldCalculateTotals);
-    const searchRequestOffset = getSearchRequestOffsetForMissingAllMatchingCount(offset, searchResults?.search?.offset, isAllMatchingItemsCountMissing);
     // For an expense-report "select all matching", the total the bulk-actions button waits for is the server
@@ -239,2 +236,8 @@ function Search({
         isExpenseReportType && areAllMatchingItemsSelected ? typeof searchResults?.search?.reportCount !== 'number' : searchResults?.search?.count === undefined;
+    // Live to-do totals come only with page 1, unless the report count is missing. Merged onto older pages, they'd take a report that left off twice.
+    const shouldCalculateAllMatchingTotals = areAllMatchingItemsSelected && !isExpenseAllMatchingSelection && (!shouldUseLiveData || isRequiredAllMatchingTotalMissing);
+    const shouldCalculateTotals = shouldCalculateAllMatchingTotals || shouldCalculateExpenseTotals;
+    const shouldCalculateNextPageTotals = shouldCalculateTotals && !shouldUseLiveData;
+    const previousShouldCalculateTotals = usePrevious(shouldCalculateTotals);
+    const searchRequestOffset = getSearchRequestOffsetForMissingAllMatchingCount(offset, searchResults?.search?.offset, isAllMatchingItemsCountMissing);
 
@@ -1019,3 +1022,10 @@ function Search({
                 setIsLivePageAdopted(false);
-                handleSearch({queryJSON, searchKey: currentSearchKey, offset: nextOffset, shouldCalculateTotals, prevReportsLength: filteredDataLength, isLoading: false});
+                handleSearch({
+                    queryJSON,
+                    searchKey: currentSearchKey,
+                    offset: nextOffset,
+                    shouldCalculateTotals: shouldCalculateNextPageTotals,
+                    prevReportsLength: filteredDataLength,
+                    isLoading: false,
+                });
             }
@@ -1042,3 +1052,3 @@ function Search({
             offset: nextOffset,
-            shouldCalculateTotals,
+            shouldCalculateTotals: shouldCalculateNextPageTotals,
             prevReportsLength: filteredDataLength,
@@ -1069,3 +1079,3 @@ function Search({
         currentSearchKey,
-        shouldCalculateTotals,
+        shouldCalculateNextPageTotals,
         filteredDataLength,
diff --git a/src/hooks/useTodoSearchResults.ts b/src/hooks/useTodoSearchResults.ts
--- a/src/hooks/useTodoSearchResults.ts
+++ b/src/hooks/useTodoSearchResults.ts
@@ -27,2 +27,4 @@ type TodoMetadata = {
     currency: string | undefined;
+    /** The server's report count, minus the reports that have left the list since its response */
+    reportCount?: number;
 };
@@ -63,2 +65,29 @@ function computeMetadata(reports: Report[], transactionsByReportID: Record<strin
 
+type TodoReportCountParams = {
+    /** The server's figures for the search, from its snapshot */
+    serverSearch: SearchResults['search'] | undefined;
+
+    /** The to-do list as search data */
+    liveData: TodoSearchResultsData;
+
+    /** Whether every collection that decides which reports are to-dos has loaded */
+    isLoaded: boolean;
+};
+
+/**
+ * The report count a live to-do search shows: the server's, which also covers reports this device doesn't hold, minus
+ * the reports its responses held that have left the list since (`countedReportIDs`). To-do search responses also write
+ * their reports to Onyx, so a report that still matches is always in the list.
+ */
+function getTodoReportCount({serverSearch, liveData, isLoaded}: TodoReportCountParams): number | undefined {
+    if (serverSearch?.reportCount === undefined) {
+        return undefined;
+    }
+
+    // Until everything has loaded, reports that still match are missing from the list, so none counts as left.
+    const countedReportIDs = isLoaded ? Object.keys(serverSearch.countedReportIDs ?? {}) : [];
+    const departedReportCount = countedReportIDs.filter((reportID) => !liveData[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`]).length;
+    return Math.max(serverSearch.reportCount - departedReportCount, 0);
+}
+
 /**
@@ -138,2 +167,3 @@ function buildSearchResultsData(
  * Builds live SearchResults-shaped data and metadata for a single to-do search (submit/approve/pay/export).
+ * Its report count is the server's from `serverSearch`, minus the reports that have left the list since.
  * Returns `undefined` (and skips all classification work) when `searchKey` is not provided, so the app-wide
@@ -141,14 +171,18 @@ function buildSearchResultsData(
  */
-function useTodoSearchResults(searchKey: SearchKey | undefined, footerTotal: SearchFooterTotal | undefined): {data: TodoSearchResultsData; metadata: TodoMetadata} | undefined {
-    const [allReports] = useOnyx(ONYXKEYS.COLLECTION.REPORT);
-    const [allPolicies] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
-    const [allReportNameValuePairs] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS);
+function useTodoSearchResults(
+    searchKey: SearchKey | undefined,
+    footerTotal: SearchFooterTotal | undefined,
+    serverSearch: SearchResults['search'] | undefined,
+): {data: TodoSearchResultsData; metadata: TodoMetadata} | undefined {
+    const [allReports, reportsResult] = useOnyx(ONYXKEYS.COLLECTION.REPORT);
+    const [allPolicies, policiesResult] = useOnyx(ONYXKEYS.COLLECTION.POLICY);
+    const [allReportNameValuePairs, reportNameValuePairsResult] = useOnyx(ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS);
     const [allTransactions, transactionsMetadata] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION);
-    const [allReportActions] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS);
-    const [allReportMetadata] = useOnyx(ONYXKEYS.COLLECTION.REPORT_METADATA);
-    const [bankAccountList] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST);
-    const [session] = useOnyx(ONYXKEYS.SESSION);
-    const [personalDetailsList] = useAllPersonalDetailsWithoutSnapshots();
+    const [allReportActions, reportActionsResult] = useOnyx(ONYXKEYS.COLLECTION.REPORT_ACTIONS);
+    const [allReportMetadata, reportMetadataResult] = useOnyx(ONYXKEYS.COLLECTION.REPORT_METADATA);
+    const [bankAccountList, bankAccountListResult] = useOnyx(ONYXKEYS.BANK_ACCOUNT_LIST);
+    const [session, sessionResult] = useOnyx(ONYXKEYS.SESSION);
+    const [personalDetailsList, personalDetailsResult] = useAllPersonalDetailsWithoutSnapshots();
     const [allTransactionViolations] = useOnyx(ONYXKEYS.COLLECTION.TRANSACTION_VIOLATIONS);
-    const [rules] = useOnyx(ONYXKEYS.COLLECTION.RULE);
+    const [rules, rulesResult] = useOnyx(ONYXKEYS.COLLECTION.RULE);
 
@@ -160,2 +194,16 @@ function useTodoSearchResults(searchKey: SearchKey | undefined, footerTotal: Sea
     const login = personalDetailsList?.[userAccountID]?.login ?? session?.email ?? '';
+    const areTransactionsLoaded = transactionsMetadata.status === 'loaded';
+    // Every input of getTodoReportsForSearchKey must be listed here, or a report still loading counts as left.
+    const isLoaded = [
+        reportsResult,
+        policiesResult,
+        reportNameValuePairsResult,
+        transactionsMetadata,
+        reportActionsResult,
+        reportMetadataResult,
+        bankAccountListResult,
+        sessionResult,
+        personalDetailsResult,
+        rulesResult,
+    ].every((result) => result.status === 'loaded');
 
@@ -172,3 +220,3 @@ function useTodoSearchResults(searchKey: SearchKey | undefined, footerTotal: Sea
         login,
-        areTransactionsLoaded: transactionsMetadata.status === 'loaded',
+        areTransactionsLoaded,
         rules,
@@ -176,6 +224,7 @@ function useTodoSearchResults(searchKey: SearchKey | undefined, footerTotal: Sea
 
-    const metadata = computeMetadata(reports, transactionsByReportID, footerTotal);
     const data = buildSearchResultsData(reports, transactionsByReportID, allPolicies, allReportActions, allReportNameValuePairs, personalDetailsList, allTransactionViolations);
+    const {count, total, currency} = computeMetadata(reports, transactionsByReportID, footerTotal);
+    const reportCount = getTodoReportCount({serverSearch, liveData: data, isLoaded});
 
-    return {data, metadata};
+    return {data, metadata: {count, total, currency, reportCount}};
 }
@@ -183 +232,2 @@ function useTodoSearchResults(searchKey: SearchKey | undefined, footerTotal: Sea
 export default useTodoSearchResults;
+export {getTodoReportCount};
diff --git a/src/libs/SearchUIUtils.ts b/src/libs/SearchUIUtils.ts
--- a/src/libs/SearchUIUtils.ts
+++ b/src/libs/SearchUIUtils.ts
@@ -870,2 +870,13 @@ function isReportEntry(key: string): key is ReportKey {
 
+/** The IDs of the expense reports in search data */
+function getExpenseReportIDs(data: OnyxTypes.SearchResults['data']): Record<string, boolean> {
+    const reportIDs: Record<string, boolean> = {};
+    for (const key of Object.keys(data)) {
+        if (isReportEntry(key) && isExpenseReportUtil(data[key])) {
+            reportIDs[key.replace(ONYXKEYS.COLLECTION.REPORT, '')] = true;
+        }
+    }
+    return reportIDs;
+}
+
 /**
@@ -7422,2 +7433,3 @@ export {
     isReportEntry,
+    getExpenseReportIDs,
     isTransactionEntry,
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
@@ -70,3 +70,3 @@ import {savedSearchIDToSearchKey} from '@libs/SearchKeyUtils';
 import {buildSearchQueryJSON, buildSearchQueryString, getFooterSelectionFromQuery, serializeQueryJSONForBackend} from '@libs/SearchQueryUtils';
-import {isTransactionGroupListItemType} from '@libs/SearchUIUtils';
+import {getExpenseReportIDs, isTransactionGroupListItemType, TODO_SEARCH_KEYS} from '@libs/SearchUIUtils';
 import {shouldRestrictUserBillableActions} from '@libs/SubscriptionUtils';
@@ -94,2 +94,3 @@ import type {
     SaveSearch,
+    SearchResults,
     SearchTagFilterItem,
@@ -125,3 +126,3 @@ import {saveLastSearchParams} from './ReportNavigation';
 type OnyxSearchResponse = {
-    data: [];
+    data: SearchResults['data'];
     search: {
@@ -1417,3 +1418,5 @@ function search({
             .then((result) => {
-                const response = result?.onyxData?.[0]?.value as OnyxSearchResponse;
+                const snapshotKey = `${ONYXKEYS.COLLECTION.SNAPSHOT}${queryJSON.hash}` as const;
+                // To-do responses list the other collections first and the snapshot last.
+                const response = result?.onyxData?.find((update) => update.key === snapshotKey)?.value as OnyxSearchResponse | undefined;
                 inFlightRequestState.didSucceed = result?.jsonCode === CONST.JSON_CODE.SUCCESS;
@@ -1434,2 +1437,9 @@ function search({
 
+                // Record the reports a to-do response held, apart from rows this device writes. A first-page response starts the record over.
+                if (searchKey && TODO_SEARCH_KEYS.has(searchKey) && result?.jsonCode === CONST.JSON_CODE.SUCCESS) {
+                    Onyx.merge(snapshotKey, {search: {countedReportIDs: getExpenseReportIDs(response?.data ?? {})}}).catch((error: unknown) =>
+                        Log.hmmm('[Search] failed to record the counted reports', {error: String(error)}),
+                    );
+                }
+
                 if (shouldUpdateLastSearchParams) {
diff --git a/src/types/onyx/SearchResults.ts b/src/types/onyx/SearchResults.ts
--- a/src/types/onyx/SearchResults.ts
+++ b/src/types/onyx/SearchResults.ts
@@ -92,2 +92,5 @@ type SearchResultsInfo = {
 
+    /** Expense reports a to-do search's responses held. Those no longer in the live list come off `reportCount`. */
+    countedReportIDs?: Record<string, boolean>;
+
     /** The total spend */

@TaduJR

TaduJR commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

@MelvinBot

Here are the test changes. Please apply the diff below on top of the source changes. It changes 2 existing test files and adds 4 new ones.

Test diff
diff --git a/tests/ui/SearchPageTest.tsx b/tests/ui/SearchPageTest.tsx
--- a/tests/ui/SearchPageTest.tsx
+++ b/tests/ui/SearchPageTest.tsx
@@ -113,2 +113,3 @@ type WriteActionsRender = {
     applySelection: SearchSelectionActionsValue['applySelection'];
+    selectAllMatchingItems: SearchSelectionActionsValue['selectAllMatchingItems'];
 };
@@ -123,4 +124,4 @@ jest.mock('@components/Search/SearchWriteActionsProvider', () => {
     function MockSearchWriteActionsProvider(props: WriteActionsProviderProps) {
-        const {applySelection} = useSearchSelectionActions();
-        mockRenderWriteActions({filteredData: props.filteredData, applySelection});
+        const {applySelection, selectAllMatchingItems} = useSearchSelectionActions();
+        mockRenderWriteActions({filteredData: props.filteredData, applySelection, selectAllMatchingItems});
         return createElement(SearchWriteActionsProvider, props);
@@ -1006,2 +1007,55 @@ describe('SearchPageNarrow', () => {
 
+        it('asks for its next page without totals', async () => {
+            // Given Drafts showing its first page, whose response carried the report count
+            await seedTodoReports(CONST.SEARCH.RESULTS_PAGE_SIZE + 10);
+            await seedTodoSnapshot(true, {reportCount: CONST.SEARCH.RESULTS_PAGE_SIZE + 10});
+            renderPage(TODO_QUERY);
+            await act(async () => {
+                jest.advanceTimersByTime(0);
+            });
+            mockSearch.mockClear();
+
+            // When the list reaches its end
+            await act(async () => {
+                listProps.onEndReached?.();
+            });
+            await act(async () => {
+                jest.advanceTimersByTime(0);
+            });
+
+            // Then the next page is asked for without totals, since totals sent with a later page would merge onto older pages
+            expect(mockSearch).toHaveBeenCalledWith(expect.objectContaining({offset: CONST.SEARCH.RESULTS_PAGE_SIZE}));
+            expect(mockSearch.mock.calls.some(([params]) => !!params?.shouldCalculateTotals)).toBe(false);
+        });
+
+        it.each([
+            ['sends no totals request once paged, since the first page already brought the report count', {reportCount: CONST.SEARCH.RESULTS_PAGE_SIZE + 10}, false],
+            ['asks for totals once paged when the report count is missing, so the bulk actions get one', {}, true],
+        ])('when every match is selected, %s', async (_description, snapshotFigures, shouldAskForTotals) => {
+            // Given Drafts paged past its first page
+            await seedTodoReports(CONST.SEARCH.RESULTS_PAGE_SIZE + 10);
+            await seedTodoSnapshot(true, snapshotFigures);
+            searchWritesLoadingState();
+            renderPage(TODO_QUERY);
+            await act(async () => {
+                jest.advanceTimersByTime(0);
+            });
+            await act(async () => {
+                listProps.onEndReached?.();
+            });
+            await answerTodoPage(CONST.SEARCH.RESULTS_PAGE_SIZE, true);
+            mockSearch.mockClear();
+
+            // When every matching report is selected
+            await act(async () => {
+                lastWriteActionsRender()?.selectAllMatchingItems(true);
+            });
+            await act(async () => {
+                jest.advanceTimersByTime(0);
+            });
+
+            // Then totals are asked for only when there's no report count, since totals merged onto older pages would take a report that left off twice
+            expect(mockSearch.mock.calls.some(([params]) => !!params?.shouldCalculateTotals)).toBe(shouldAskForTotals);
+        });
+
         it('shows the next rows only once the server answers their page, and ignores ends meanwhile', async () => {
diff --git a/tests/unit/Search/SearchResultsProviderLiveLoadingTest.tsx b/tests/unit/Search/SearchResultsProviderLiveLoadingTest.tsx
--- a/tests/unit/Search/SearchResultsProviderLiveLoadingTest.tsx
+++ b/tests/unit/Search/SearchResultsProviderLiveLoadingTest.tsx
@@ -24,5 +24,7 @@ jest.mock('@libs/SearchUIUtils', () => ({
 
+const EMPTY_TODO_METADATA = {count: 0, total: 0, currency: undefined};
+let mockTodoMetadata: Record<string, unknown> = EMPTY_TODO_METADATA;
 jest.mock('@hooks/useTodoSearchResults', () => ({
     __esModule: true,
-    default: () => ({data: {}, metadata: {count: 0, total: 0, currency: undefined}}),
+    default: () => ({data: {}, metadata: mockTodoMetadata}),
 }));
@@ -50,2 +52,3 @@ describe('SearchResultsProvider live to-do loading flag', () => {
         mockIsTodoSearch = true;
+        mockTodoMetadata = EMPTY_TODO_METADATA;
     });
@@ -68,2 +71,13 @@ describe('SearchResultsProvider live to-do loading flag', () => {
     });
+
+    it('shows the figures the to-do list worked out, including the report count, over the snapshot', () => {
+        // Given the to-do list corrected the server's figures for reports that left it on this device
+        mockTodoMetadata = {count: 125, total: 125000, currency: 'USD', reportCount: 119};
+
+        // When the provider builds the live results over a snapshot that still holds the server's old figures
+        const {result} = renderProvider({isLoading: false, offset: 0, hash: 1, count: 126, total: 126000, currency: 'USD', reportCount: 120});
+
+        // Then the search shows the corrected figures, which "Select all" and the footer read
+        expect(result.current.currentSearchResults?.search).toMatchObject({count: 125, total: 125000, currency: 'USD', reportCount: 119});
+    });
 });
diff --git a/tests/unit/Search/SearchResultsProviderLiveReportCountTest.tsx b/tests/unit/Search/SearchResultsProviderLiveReportCountTest.tsx
new file mode 100644
--- /dev/null
+++ b/tests/unit/Search/SearchResultsProviderLiveReportCountTest.tsx
@@ -0,0 +1,280 @@
+import {act, renderHook} from '@testing-library/react-native';
+
+import {SearchResultsContext} from '@components/Search/SearchContextDefinitions';
+import SearchResultsProvider from '@components/Search/SearchResultsProvider';
+
+import {getSuggestedSearches} from '@libs/SearchSuggestionUtils';
+
+import CONST from '@src/CONST';
+import ONYXKEYS from '@src/ONYXKEYS';
+import type {Policy, Report, SearchResults, Transaction} from '@src/types/onyx';
+
+import React, {use} from 'react';
+import Onyx from 'react-native-onyx';
+
+import createMock from '../../utils/createMock';
+import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates';
+
+const CURRENT_USER_ACCOUNT_ID = 1;
+const CURRENT_USER_EMAIL = 'tester@mail.com';
+const APPROVER_ACCOUNT_ID = 2;
+const POLICY_ID = 'policy123';
+const DRAFT_REPORT_IDS = ['draft_1', 'draft_2', 'draft_3'];
+
+// The server matched more drafts than this device holds, as on an account whose to-dos aren't all loaded. Each draft
+// has one 10.00 expense.
+const SERVER_REPORT_COUNT = 120;
+const EXPENSE_AMOUNT = 1000;
+
+const suggestedSearches = getSuggestedSearches(CURRENT_USER_ACCOUNT_ID);
+const draftsQueryJSON = suggestedSearches[CONST.SEARCH.SEARCH_KEYS.SUBMIT].searchQueryJSON;
+
+const mockQueryContext = {
+    currentSearchHash: draftsQueryJSON?.hash ?? CONST.DEFAULT_NUMBER_ID,
+    currentSearchKey: CONST.SEARCH.SEARCH_KEYS.SUBMIT,
+    currentSearchQueryJSON: draftsQueryJSON,
+    suggestedSearches,
+};
+jest.mock('@components/Search/SearchContext', () => ({
+    useSearchQueryContext: () => mockQueryContext,
+}));
+
+const snapshotKey = `${ONYXKEYS.COLLECTION.SNAPSHOT}${mockQueryContext.currentSearchHash}` as const;
+const firstDraftReportID = DRAFT_REPORT_IDS.at(0) ?? '';
+
+const draftReport = (reportID: string): Report =>
+    createMock<Report>({
+        reportID,
+        chatReportID: `chat_${reportID}`,
+        policyID: POLICY_ID,
+        ownerAccountID: CURRENT_USER_ACCOUNT_ID,
+        managerID: APPROVER_ACCOUNT_ID,
+        stateNum: CONST.REPORT.STATE_NUM.OPEN,
+        statusNum: CONST.REPORT.STATUS_NUM.OPEN,
+        type: CONST.REPORT.TYPE.EXPENSE,
+        currency: 'USD',
+    });
+
+const draftTransaction = (reportID: string): Transaction =>
+    createMock<Transaction>({
+        transactionID: `transaction_${reportID}`,
+        reportID,
+        amount: -1000,
+        currency: 'USD',
+        merchant: 'Merchant',
+        created: '2026-10-13',
+        reimbursable: true,
+        groupAmount: -1000,
+        groupCurrency: 'USD',
+    });
+
+// The first page the server returned when Drafts loaded: the three drafts this device holds, out of SERVER_REPORT_COUNT.
+const draftsSnapshotData = createMock<SearchResults['data']>({});
+for (const reportID of DRAFT_REPORT_IDS) {
+    Object.assign(draftsSnapshotData, {
+        [`${ONYXKEYS.COLLECTION.REPORT}${reportID}` as const]: draftReport(reportID),
+        [`${ONYXKEYS.COLLECTION.TRANSACTION}${draftTransaction(reportID).transactionID}` as const]: draftTransaction(reportID),
+    });
+}
+
+const draftsSnapshot = createMock<SearchResults>({
+    search: {
+        hash: mockQueryContext.currentSearchHash,
+        offset: 0,
+        type: CONST.SEARCH.DATA_TYPES.EXPENSE_REPORT,
+        hasMoreResults: true,
+        hasResults: true,
+        isLoading: false,
+        count: SERVER_REPORT_COUNT,
+        reportCount: SERVER_REPORT_COUNT,
+        total: SERVER_REPORT_COUNT * EXPENSE_AMOUNT,
+        currency: 'USD',
+        footerTotal: CONST.SEARCH.FOOTER_TOTAL.TOTAL,
+        countedReportIDs: Object.fromEntries(DRAFT_REPORT_IDS.map((reportID) => [reportID, true])),
+    },
+    data: draftsSnapshotData,
+});
+
+function renderProvider() {
+    return renderHook(() => use(SearchResultsContext), {
+        wrapper: ({children}: {children: React.ReactNode}) => <SearchResultsProvider>{children}</SearchResultsProvider>,
+    });
+}
+
+async function seedDraftsAndSnapshot() {
+    const policy = createMock<Policy>({
+        id: POLICY_ID,
+        name: 'Test Policy',
+        role: CONST.POLICY.ROLE.ADMIN,
+        type: CONST.POLICY.TYPE.TEAM,
+        owner: CURRENT_USER_EMAIL,
+        ownerAccountID: CURRENT_USER_ACCOUNT_ID,
+        outputCurrency: 'USD',
+        approvalMode: CONST.POLICY.APPROVAL_MODE.BASIC,
+    });
+
+    await Onyx.set(ONYXKEYS.SESSION, {email: CURRENT_USER_EMAIL, accountID: CURRENT_USER_ACCOUNT_ID});
+    await Onyx.set(`${ONYXKEYS.COLLECTION.POLICY}${POLICY_ID}`, policy);
+    await Promise.all(DRAFT_REPORT_IDS.map((reportID) => Onyx.set(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, draftReport(reportID))));
+    await Promise.all(DRAFT_REPORT_IDS.map((reportID) => Onyx.set(`${ONYXKEYS.COLLECTION.TRANSACTION}${draftTransaction(reportID).transactionID}`, draftTransaction(reportID))));
+    await Onyx.set(snapshotKey, draftsSnapshot);
+    await waitForBatchedUpdates();
+}
+
+async function renderDrafts() {
+    await seedDraftsAndSnapshot();
+    const rendered = renderProvider();
+    await act(async () => {
+        await waitForBatchedUpdates();
+    });
+    return rendered;
+}
+
+async function moveFirstDraft(stateNum: Report['stateNum'], statusNum: Report['statusNum']) {
+    await act(async () => {
+        await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${firstDraftReportID}`, {stateNum, statusNum});
+        await waitForBatchedUpdates();
+    });
+}
+
+// The last draft stands for a report from a later page, which a first-page response leaves out of its record.
+const laterPageDraftReportID = DRAFT_REPORT_IDS.at(-1) ?? '';
+const firstPageDraftReportIDs = DRAFT_REPORT_IDS.filter((reportID) => reportID !== laterPageDraftReportID);
+
+async function submitDraft(reportID: string) {
+    await act(async () => {
+        await Onyx.merge(`${ONYXKEYS.COLLECTION.REPORT}${reportID}`, {stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED});
+        await waitForBatchedUpdates();
+    });
+}
+
+/** A first-page response, which replaces the snapshot with the server's fresh count and a record of page 1 */
+async function answerFirstPage(reportCount: number) {
+    await act(async () => {
+        await Onyx.set(snapshotKey, {
+            ...draftsSnapshot,
+            search: {...draftsSnapshot.search, reportCount, countedReportIDs: Object.fromEntries(firstPageDraftReportIDs.map((reportID) => [reportID, true]))},
+        });
+        await waitForBatchedUpdates();
+    });
+}
+
+function getReportCount(result: Awaited<ReturnType<typeof renderDrafts>>['result']) {
+    return result.current.currentSearchResults?.search?.reportCount;
+}
+
+function expectFigures(result: Awaited<ReturnType<typeof renderDrafts>>['result'], reportCount: number, deviceDraftCount: number) {
+    const search = result.current.currentSearchResults?.search;
+    expect(search?.reportCount).toBe(reportCount);
+    expect(search?.count).toBe(deviceDraftCount);
+    expect(search?.total).toBe(deviceDraftCount * EXPENSE_AMOUNT);
+    expect(search?.currency).toBe('USD');
+}
+
+describe('SearchResultsProvider live to-do report count', () => {
+    beforeAll(() => {
+        // As in the app, Onyx.update copies pending markers into the snapshots that hold the updated keys.
+        Onyx.init({keys: ONYXKEYS, snapshotMergeKeys: ['pendingAction', 'pendingFields']});
+    });
+
+    beforeEach(async () => {
+        await Onyx.clear();
+        await waitForBatchedUpdates();
+    });
+
+    it("keeps the server's report count when the device holds only some of the matching reports", async () => {
+        // Given Drafts on a device that holds three of the 120 drafts the server counted
+        // When the provider builds the live results
+        const {result} = await renderDrafts();
+
+        // Then "Select all" counts every matching report, not only the three on the device
+        expect(result.current.shouldUseLiveData).toBe(true);
+        expectFigures(result, SERVER_REPORT_COUNT, DRAFT_REPORT_IDS.length);
+    });
+
+    it('lowers the report count as soon as a report leaves Drafts, without a new search', async () => {
+        // Given Drafts with the server's 120 reports
+        const {result} = await renderDrafts();
+
+        // When one draft is submitted from its row, which moves it out of Drafts on this device
+        await moveFirstDraft(CONST.REPORT.STATE_NUM.SUBMITTED, CONST.REPORT.STATUS_NUM.SUBMITTED);
+
+        // Then the report count drops with it, like the Drafts badge does
+        expectFigures(result, SERVER_REPORT_COUNT - 1, DRAFT_REPORT_IDS.length - 1);
+    });
+
+    it('keeps it lowered after the submit succeeds and removes the report from the snapshot', async () => {
+        // Given a draft that was submitted from its row
+        const {result} = await renderDrafts();
+        await moveFirstDraft(CONST.REPORT.STATE_NUM.SUBMITTED, CONST.REPORT.STATUS_NUM.SUBMITTED);
+
+        // When the submit succeeds and its success data removes the report's row from the snapshot
+        await act(async () => {
+            await Onyx.merge(snapshotKey, {data: {[`${ONYXKEYS.COLLECTION.REPORT}${firstDraftReportID}`]: null}});
+            await waitForBatchedUpdates();
+        });
+
+        // Then the report count stays lowered instead of jumping back to the server's old one
+        expectFigures(result, SERVER_REPORT_COUNT - 1, DRAFT_REPORT_IDS.length - 1);
+    });
+
+    it('puts the report back in the report count when a failed submit returns it to Drafts', async () => {
+        // Given a draft that was submitted from its row
+        const {result} = await renderDrafts();
+        await moveFirstDraft(CONST.REPORT.STATE_NUM.SUBMITTED, CONST.REPORT.STATUS_NUM.SUBMITTED);
+
+        // When the submit fails and its failure data returns the report to Drafts
+        await moveFirstDraft(CONST.REPORT.STATE_NUM.OPEN, CONST.REPORT.STATUS_NUM.OPEN);
+
+        // Then the report count is the server's again, without anything having to restore it
+        expectFigures(result, SERVER_REPORT_COUNT, DRAFT_REPORT_IDS.length);
+    });
+
+    it('takes nothing off for a draft created on this device and then submitted, even once its creation succeeded', async () => {
+        // Given Drafts with the server's 120 reports, and a draft created on this device, which the app writes into the snapshot with its pending markers
+        const {result} = await renderDrafts();
+        const createdReportKey = `${ONYXKEYS.COLLECTION.REPORT}created` as const;
+        const createdTransaction = {...draftTransaction('created'), pendingAction: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD};
+        const createdTransactionKey = `${ONYXKEYS.COLLECTION.TRANSACTION}${createdTransaction.transactionID}` as const;
+        const createdReport = {...draftReport('created'), pendingFields: {createReport: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD}};
+        const createdSnapshotData = createMock<SearchResults['data']>({});
+        Object.assign(createdSnapshotData, {[createdReportKey]: createdReport, [createdTransactionKey]: createdTransaction});
+        await act(async () => {
+            await Onyx.set(createdReportKey, createdReport);
+            await Onyx.set(createdTransactionKey, createdTransaction);
+            await Onyx.merge(snapshotKey, {data: createdSnapshotData});
+            await waitForBatchedUpdates();
+        });
+
+        // When the creation succeeds, its success data clearing the pending markers through Onyx.update, which also clears them in the snapshot
+        await act(async () => {
+            await Onyx.update([
+                {onyxMethod: Onyx.METHOD.MERGE, key: createdReportKey, value: {pendingFields: {createReport: null}}},
+                {onyxMethod: Onyx.METHOD.MERGE, key: createdTransactionKey, value: {pendingAction: null}},
+            ]);
+            await waitForBatchedUpdates();
+        });
+
+        // And the draft is then submitted
+        await act(async () => {
+            await Onyx.merge(createdReportKey, {stateNum: CONST.REPORT.STATE_NUM.SUBMITTED, statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED});
+            await waitForBatchedUpdates();
+        });
+
+        // Then the server's 120 stand, since the draft isn't among the reports its responses held
+        expect(result.current.currentSearchResults?.search?.reportCount).toBe(SERVER_REPORT_COUNT);
+    });
+
+    it("doesn't take a report off twice when a first-page response lands after it left", async () => {
+        // Given a later-page draft submitted, so the count drops to 119
+        const {result} = await renderDrafts();
+        await submitDraft(laterPageDraftReportID);
+        expect(getReportCount(result)).toBe(SERVER_REPORT_COUNT - 1);
+
+        // When a first-page response brings the server's fresh count, which no longer covers it, and a record of page 1
+        await answerFirstPage(SERVER_REPORT_COUNT - 1);
+
+        // Then the count stays at 119, since the fresh count already left it out
+        expect(getReportCount(result)).toBe(SERVER_REPORT_COUNT - 1);
+    });
+});
diff --git a/tests/unit/Search/searchCountedReportIDsTest.ts b/tests/unit/Search/searchCountedReportIDsTest.ts
new file mode 100644
--- /dev/null
+++ b/tests/unit/Search/searchCountedReportIDsTest.ts
@@ -0,0 +1,172 @@
+import {search} from '@libs/actions/Search';
+import {makeRequestWithSideEffects, waitForWrites} from '@libs/API';
+import {getExpenseReportIDs, getSuggestedSearches} from '@libs/SearchUIUtils';
+
+import CONST from '@src/CONST';
+import ONYXKEYS from '@src/ONYXKEYS';
+import type {Report, SearchResults} from '@src/types/onyx';
+
+import type {OnyxUpdate} from 'react-native-onyx';
+
+import Onyx from 'react-native-onyx';
+
+import createMock from '../../utils/createMock';
+import getOnyxValue from '../../utils/getOnyxValue';
+import waitForBatchedUpdates from '../../utils/waitForBatchedUpdates';
+
+jest.mock('@libs/API', () => ({
+    makeRequestWithSideEffects: jest.fn(),
+    waitForWrites: jest.fn(),
+    write: jest.fn(),
+    read: jest.fn(),
+}));
+
+const draftsQueryJSON = getSuggestedSearches(1)[CONST.SEARCH.SEARCH_KEYS.SUBMIT].searchQueryJSON;
+if (!draftsQueryJSON) {
+    throw new Error('The Drafts query should build');
+}
+const snapshotKey = `${ONYXKEYS.COLLECTION.SNAPSHOT}${draftsQueryJSON.hash}` as const;
+
+function buildSearchData(reports: Array<{reportID: string; type: string}>): SearchResults['data'] {
+    const data = createMock<SearchResults['data']>({});
+    for (const report of reports) {
+        data[`${ONYXKEYS.COLLECTION.REPORT}${report.reportID}`] = createMock<Report>(report);
+    }
+    return data;
+}
+
+/**
+ * Answers the next request the way the API layer does: it applies the response's onyxData before search() sees the
+ * result. Like a real to-do response, it lists another collection first and the snapshot last.
+ */
+function answerWith(onyxMethod: typeof Onyx.METHOD.SET | typeof Onyx.METHOD.MERGE, data: SearchResults['data'], jsonCode: number = CONST.JSON_CODE.SUCCESS) {
+    const onyxData: Array<OnyxUpdate<typeof ONYXKEYS.PERSONAL_DETAILS_LIST | typeof ONYXKEYS.COLLECTION.SNAPSHOT>> = [
+        {onyxMethod: Onyx.METHOD.MERGE, key: ONYXKEYS.PERSONAL_DETAILS_LIST, value: {}},
+        {onyxMethod, key: snapshotKey, value: {search: {reportCount: 120}, data}},
+    ];
+    jest.mocked(makeRequestWithSideEffects).mockImplementationOnce(async () => {
+        await Onyx.update(onyxData);
+        return {jsonCode, onyxData};
+    });
+}
+
+async function getCountedReportIDs() {
+    await waitForBatchedUpdates();
+    const snapshot = await getOnyxValue(snapshotKey);
+    return snapshot?.search?.countedReportIDs;
+}
+
+describe('getExpenseReportIDs', () => {
+    it('keeps only the expense reports, which are the only reports a live to-do list holds', () => {
+        // Given search data with expense, IOU, invoice and chat reports
+        const data = buildSearchData([
+            {reportID: 'expense1', type: CONST.REPORT.TYPE.EXPENSE},
+            {reportID: 'iou', type: CONST.REPORT.TYPE.IOU},
+            {reportID: 'invoice', type: CONST.REPORT.TYPE.INVOICE},
+            {reportID: 'chat', type: CONST.REPORT.TYPE.CHAT},
+            {reportID: 'expense2', type: CONST.REPORT.TYPE.EXPENSE},
+        ]);
+
+        // When their IDs are collected
+        const reportIDs = getExpenseReportIDs(data);
+
+        // Then only the expense reports are kept
+        expect(reportIDs).toEqual({expense1: true, expense2: true});
+    });
+
+    it("takes each report's ID from its key, so an entry without a reportID is still recorded", () => {
+        // Given an expense report entry whose value carries no reportID
+        const data = createMock<SearchResults['data']>({});
+        data[`${ONYXKEYS.COLLECTION.REPORT}expense1`] = createMock<Report>({type: CONST.REPORT.TYPE.EXPENSE});
+
+        // When its ID is collected
+        const reportIDs = getExpenseReportIDs(data);
+
+        // Then it is recorded under its key's ID, never as "undefined", which would count as a report that left
+        expect(reportIDs).toEqual({expense1: true});
+    });
+
+    it('returns nothing for data without reports', () => {
+        // Given search data holding no reports
+        // When the IDs are collected
+        // Then there are none
+        expect(getExpenseReportIDs(createMock<SearchResults['data']>({}))).toEqual({});
+    });
+});
+
+describe('search() records the reports a to-do search counted', () => {
+    beforeAll(() => {
+        Onyx.init({keys: ONYXKEYS});
+    });
+
+    beforeEach(async () => {
+        jest.clearAllMocks();
+        jest.mocked(waitForWrites).mockResolvedValue(undefined);
+        await Onyx.clear();
+    });
+
+    it("records the expense reports a to-do search's first page held", async () => {
+        // Given Drafts answers its first page with two expense reports and a chat report
+        answerWith(
+            Onyx.METHOD.SET,
+            buildSearchData([
+                {reportID: 'A', type: CONST.REPORT.TYPE.EXPENSE},
+                {reportID: 'B', type: CONST.REPORT.TYPE.EXPENSE},
+                {reportID: 'chat', type: CONST.REPORT.TYPE.CHAT},
+            ]),
+        );
+
+        // When the first page is searched
+        await search({queryJSON: draftsQueryJSON, searchKey: CONST.SEARCH.SEARCH_KEYS.SUBMIT, offset: 0, shouldCalculateTotals: true, isLoading: false});
+
+        // Then the two expense reports are recorded as the ones its count covers
+        expect(await getCountedReportIDs()).toEqual({A: true, B: true});
+    });
+
+    it("adds a later page's reports to the record", async () => {
+        // Given Drafts already recorded report A from its first page
+        answerWith(Onyx.METHOD.SET, buildSearchData([{reportID: 'A', type: CONST.REPORT.TYPE.EXPENSE}]));
+        await search({queryJSON: draftsQueryJSON, searchKey: CONST.SEARCH.SEARCH_KEYS.SUBMIT, offset: 0, shouldCalculateTotals: true, isLoading: false});
+
+        // When the next page answers with report C, merged into the snapshot
+        answerWith(Onyx.METHOD.MERGE, buildSearchData([{reportID: 'C', type: CONST.REPORT.TYPE.EXPENSE}]));
+        await search({queryJSON: draftsQueryJSON, searchKey: CONST.SEARCH.SEARCH_KEYS.SUBMIT, offset: CONST.SEARCH.RESULTS_PAGE_SIZE, shouldCalculateTotals: false, isLoading: false});
+
+        // Then both are recorded
+        expect(await getCountedReportIDs()).toEqual({A: true, C: true});
+    });
+
+    it('starts the record over with a first-page response, which replaces the snapshot', async () => {
+        // Given a record from an earlier response holding report OLD
+        await Onyx.set(snapshotKey, createMock<SearchResults>({search: {countedReportIDs: {OLD: true}}, data: {}}));
+
+        // When a new first page answers with report A
+        answerWith(Onyx.METHOD.SET, buildSearchData([{reportID: 'A', type: CONST.REPORT.TYPE.EXPENSE}]));
+        await search({queryJSON: draftsQueryJSON, searchKey: CONST.SEARCH.SEARCH_KEYS.SUBMIT, offset: 0, shouldCalculateTotals: true, isLoading: false});
+
+        // Then only report A is recorded, since the old record went with the replaced snapshot
+        expect(await getCountedReportIDs()).toEqual({A: true});
+    });
+
+    it('records nothing for a search that is not a to-do', async () => {
+        // Given the same response answers a search that isn't a to-do
+        answerWith(Onyx.METHOD.SET, buildSearchData([{reportID: 'A', type: CONST.REPORT.TYPE.EXPENSE}]));
+
+        // When it is searched
+        await search({queryJSON: draftsQueryJSON, searchKey: CONST.SEARCH.SEARCH_KEYS.EXPENSES, offset: 0, shouldCalculateTotals: true, isLoading: false});
+
+        // Then no record is kept, since only a live to-do search corrects its count
+        expect(await getCountedReportIDs()).toBeUndefined();
+    });
+
+    it('records nothing when the response failed', async () => {
+        // Given Drafts' request fails
+        answerWith(Onyx.METHOD.MERGE, {}, 500);
+
+        // When the first page is searched
+        await search({queryJSON: draftsQueryJSON, searchKey: CONST.SEARCH.SEARCH_KEYS.SUBMIT, offset: 0, shouldCalculateTotals: true, isLoading: false});
+
+        // Then no record is kept
+        expect(await getCountedReportIDs()).toBeUndefined();
+    });
+});
diff --git a/tests/unit/hooks/getTodoReportCountTest.ts b/tests/unit/hooks/getTodoReportCountTest.ts
new file mode 100644
--- /dev/null
+++ b/tests/unit/hooks/getTodoReportCountTest.ts
@@ -0,0 +1,89 @@
+import {getTodoReportCount} from '@hooks/useTodoSearchResults';
+
+import CONST from '@src/CONST';
+import ONYXKEYS from '@src/ONYXKEYS';
+import type {Report, SearchResults} from '@src/types/onyx';
+
+import createMock from '../../utils/createMock';
+
+// The server matched 120 reports. Its responses held reports A, B and C.
+const SERVER_REPORT_COUNT = 120;
+const COUNTED_REPORT_IDS = {A: true, B: true, C: true};
+
+function buildServerSearch(search: Partial<SearchResults['search']> = {}): SearchResults['search'] {
+    return createMock<SearchResults['search']>({reportCount: SERVER_REPORT_COUNT, countedReportIDs: COUNTED_REPORT_IDS, ...search});
+}
+
+/** The to-do list on the device, holding the given reports */
+function buildLiveData(reportIDs: string[]): SearchResults['data'] {
+    const data = createMock<SearchResults['data']>({});
+    for (const reportID of reportIDs) {
+        data[`${ONYXKEYS.COLLECTION.REPORT}${reportID}`] = createMock<Report>({reportID, type: CONST.REPORT.TYPE.EXPENSE});
+    }
+    return data;
+}
+
+describe('getTodoReportCount', () => {
+    it("has no report count when the server hasn't sent one", () => {
+        // Given no server snapshot yet
+        // When the report count is worked out
+        const reportCount = getTodoReportCount({serverSearch: undefined, liveData: buildLiveData(['B', 'C']), isLoaded: true});
+
+        // Then there is none to show
+        expect(reportCount).toBeUndefined();
+    });
+
+    it("keeps the server's report count while every counted report is still in the list", () => {
+        // Given the device still holds every report the server's responses held
+        // When the report count is worked out
+        const reportCount = getTodoReportCount({serverSearch: buildServerSearch(), liveData: buildLiveData(['A', 'B', 'C']), isLoaded: true});
+
+        // Then it is the server's, which also covers the reports this device doesn't hold
+        expect(reportCount).toBe(SERVER_REPORT_COUNT);
+    });
+
+    it('takes a counted report that left the list off the server count', () => {
+        // Given report A left the list, so it's gone from it whatever the snapshot's rows still hold
+        // When the report count is worked out
+        const reportCount = getTodoReportCount({serverSearch: buildServerSearch(), liveData: buildLiveData(['B', 'C']), isLoaded: true});
+
+        // Then one report comes off, without waiting for the next search
+        expect(reportCount).toBe(SERVER_REPORT_COUNT - 1);
+    });
+
+    it('leaves a report the server never counted out until the next response, such as a draft created on this device', () => {
+        // Given the list also holds a draft this device created, which isn't among the reports the server's responses held
+        // When the report count is worked out
+        const reportCount = getTodoReportCount({serverSearch: buildServerSearch(), liveData: buildLiveData(['A', 'B', 'C', 'created']), isLoaded: true});
+
+        // Then the server's count stands. The next first-page response counts the draft
+        expect(reportCount).toBe(SERVER_REPORT_COUNT);
+    });
+
+    it("keeps the server's report count while local data is still loading", () => {
+        // Given local data hasn't finished loading, so the list is still empty
+        // When the report count is worked out
+        const reportCount = getTodoReportCount({serverSearch: buildServerSearch(), liveData: buildLiveData([]), isLoaded: false});
+
+        // Then nothing counts as having left, since reports that still match are missing until then
+        expect(reportCount).toBe(SERVER_REPORT_COUNT);
+    });
+
+    it("keeps the server's report count when the snapshot has no record of the reports it counted", () => {
+        // Given a snapshot cached before the counted reports were recorded
+        // When the report count is worked out
+        const reportCount = getTodoReportCount({serverSearch: buildServerSearch({countedReportIDs: undefined}), liveData: buildLiveData(['B', 'C']), isLoaded: true});
+
+        // Then it is the server's until the next response records them
+        expect(reportCount).toBe(SERVER_REPORT_COUNT);
+    });
+
+    it('never goes below zero', () => {
+        // Given a stale server count smaller than what has left
+        // When the report count is worked out
+        const reportCount = getTodoReportCount({serverSearch: buildServerSearch({reportCount: 1}), liveData: buildLiveData([]), isLoaded: true});
+
+        // Then it stops at zero
+        expect(reportCount).toBe(0);
+    });
+});
diff --git a/tests/unit/hooks/useTodoSearchResultsTest.ts b/tests/unit/hooks/useTodoSearchResultsTest.ts
new file mode 100644
--- /dev/null
+++ b/tests/unit/hooks/useTodoSearchResultsTest.ts
@@ -0,0 +1,66 @@
+import {renderHook} from '@testing-library/react-native';
+
+import useTodoSearchResults from '@hooks/useTodoSearchResults';
+
+import CONST from '@src/CONST';
+import ONYXKEYS from '@src/ONYXKEYS';
+import type {SearchResults} from '@src/types/onyx';
+
+import createMock from '../../utils/createMock';
+
+const mockLoadingKeys = new Set<string>();
+jest.mock('react-native-onyx', () => ({
+    __esModule: true,
+    ...jest.requireActual<Record<string, unknown>>('react-native-onyx'),
+    useOnyx: (key: string) => [undefined, {status: mockLoadingKeys.has(key) ? 'loading' : 'loaded'}],
+}));
+
+jest.mock('@hooks/usePersonalDetails', () => ({
+    useAllPersonalDetailsWithoutSnapshots: () => [undefined, {status: mockLoadingKeys.has('personalDetailsList') ? 'loading' : 'loaded'}],
+}));
+
+const SERVER_REPORT_COUNT = 120;
+
+// The server counted 120 drafts, two of them on its first page. The device list built from the mocked Onyx is empty.
+const serverSearch = createMock<SearchResults['search']>({reportCount: SERVER_REPORT_COUNT, countedReportIDs: {A: true, B: true}});
+
+function renderDrafts() {
+    return renderHook(() => useTodoSearchResults(CONST.SEARCH.SEARCH_KEYS.SUBMIT, undefined, serverSearch));
+}
+
+describe('useTodoSearchResults', () => {
+    beforeEach(() => {
+        mockLoadingKeys.clear();
+    });
+
+    it('treats counted reports missing from the list as having left once everything has loaded', () => {
+        // Given every collection the to-do list reads has loaded, and the two counted reports aren't in the list
+        // When the Drafts list is built
+        const {result} = renderDrafts();
+
+        // Then both come off the server's count
+        expect(result.current?.metadata.reportCount).toBe(SERVER_REPORT_COUNT - 2);
+    });
+
+    it.each([
+        ONYXKEYS.COLLECTION.REPORT,
+        ONYXKEYS.COLLECTION.POLICY,
+        ONYXKEYS.COLLECTION.REPORT_NAME_VALUE_PAIRS,
+        ONYXKEYS.COLLECTION.TRANSACTION,
+        ONYXKEYS.COLLECTION.REPORT_ACTIONS,
+        ONYXKEYS.COLLECTION.REPORT_METADATA,
+        ONYXKEYS.BANK_ACCOUNT_LIST,
+        ONYXKEYS.SESSION,
+        'personalDetailsList',
+        ONYXKEYS.COLLECTION.RULE,
+    ])("keeps the server's count while %s is still loading", (loadingKey) => {
+        // Given one of the collections that decides whether a report is a to-do is still loading from storage
+        mockLoadingKeys.add(loadingKey);
+
+        // When the Drafts list is built
+        const {result} = renderDrafts();
+
+        // Then nothing comes off, because reports that still match can be missing from the list until it loads
+        expect(result.current?.metadata.reportCount).toBe(SERVER_REPORT_COUNT);
+    });
+});

MelvinBot and others added 2 commits October 16, 2026 13:15
…AllReportCount

Co-authored-by: TaduJR <TaduJR@users.noreply.github.com>
Reset every file in this PR to main, removing the live device count, the
hasMoreMatchingItems prop and their tests, then apply the final source changes:
record which expense reports each to-do search response held, subtract the ones
that have left the live list from the server's report count, ask for totals only
with the first page on to-do tabs, and read the snapshot entry from the response.

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

Copy link
Copy Markdown
Contributor Author

⚠️ MelvinBot CI Fix Loop Detected

MelvinBot has made 5 consecutive commits trying to fix CI failures. Automatic CI fix dispatches are now paused for this PR.

Next steps: A human should review the recent commits and resolve the conflicting CI errors manually.

@MelvinBot MelvinBot changed the title Use the live report count for select-all on to-do searches Update the to-do "Select all" count when a report leaves the list Oct 16, 2026
@MelvinBot

Copy link
Copy Markdown
Contributor Author

Done, TaduJR. The PR now has only your source changes.

  • Reset to main: I merged the latest main, reset all 23 PR files to main, and deleted SearchResultsProviderLiveReportCountTest.tsx and SearchSelectAllMenuTest.tsx.
  • Source diff: It applied cleanly. The PR now changes only your 6 source files (commit d1bddb5).
  • Description: I removed the "Select all" menu bullet. The rest is unchanged, including your removal of the outer <details> wrapper.
  • Title: It now reads: Update the to-do "Select all" count when a report leaves the list
Checks
  • npm run lint-changed: passed.
  • Jest: tests/unit/Search, tests/unit/hooks, tests/unit/HomePage, SearchActionsTest, SearchUIUtilsTest, and the other search hook tests all passed across two runs (73 and 203 suites).
  • npm run typecheck: one error, in useNativeTabBarOptions/index.ios.ts. This PR doesn't touch that file.
  • oxfmt: not run locally. CI will check formatting.

Send the test changes when they're ready.

…ches

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

Copy link
Copy Markdown
Contributor Author

Done, TaduJR. I applied your diff on top of 30ac49e in eb920ac and updated the description.

Code: The diff applied exactly as written to src/components/Search/index.tsx and tests/ui/SearchPageTest.tsx.

Description:

  • I replaced the "Asks for a new count only with the first page" bullet with your "Loads more pages on these tabs…" bullet.
  • I replaced the "Known limit" paragraph with your new text.
  • I left everything else unchanged.

Checks:

  • tests/ui/SearchPageTest.tsx: all 42 tests pass.
  • ESLint on both files: clean.
  • npm run typecheck: passed.
  • React Compiler check on Search/index.tsx: fails with 19 errors, both before and after this change. The diff adds no new errors.

@TaduJR

TaduJR commented Oct 17, 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-Native.mp4
Android: mWeb Chrome
Android-mWeb.mp4
iOS: HybridApp
iOS: mWeb Safari
MacOS: Chrome / Safari
Mac-Chrome.mp4

@TaduJR

TaduJR commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

@MelvinBot Please merge main

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

Copy link
Copy Markdown
Contributor Author

I merged main into this branch and pushed it as c49f8ce. The merge was clean, with no conflicts.

The merge brought in 6 files: deep-link handling, navigation after onboarding, the Concierge page, and their tests. None of them are files this PR changes, so I didn't re-run local checks. CI will run on the new commit.


view run

@TaduJR

TaduJR commented Oct 17, 2026

Copy link
Copy Markdown
Contributor

@MelvinBot

Please make the PR ready for review

@MelvinBot
MelvinBot marked this pull request as ready for review October 17, 2026 06:19
@MelvinBot
MelvinBot requested a review from a team as a code owner October 17, 2026 06:19
@MelvinBot

Copy link
Copy Markdown
Contributor Author

Done, TaduJR. This PR is now marked ready for review.


view run

@melvin-bot
melvin-bot Bot requested review from TaduJR and removed request for a team October 17, 2026 06:19
@melvin-bot

melvin-bot Bot commented Oct 17, 2026

Copy link
Copy Markdown

@TaduJR 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 JmillsExpensify and removed request for a team October 17, 2026 06:19

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

ℹ️ 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 +1441 to +1443
const clearRecord = shouldCalculateTotals ? Onyx.merge(snapshotKey, {search: {countedReportIDs: null}}) : Promise.resolve();
clearRecord
.then(() => Onyx.merge(snapshotKey, {search: {countedReportIDs}}))

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 Retain live IDs from previously loaded pages

When selecting all after paging triggers a totals request for the current page, this clear discards countedReportIDs from every other loaded page and repopulates the record only from the response page. For example, after page 2 returns fresh totals, completing a still-visible page-1 report no longer lowers reportCount, because getTodoReportCount() cannot find that ID in the new record; the bulk-action count remains one too high until another totals refresh. Reset the departure baseline without dropping still-live counted IDs from the other hydrated pages.

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.

Pre-existing on main and documented as known limit. It will be handled on follow-up PR.

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

@melvin-bot

melvin-bot Bot commented Oct 17, 2026

Copy link
Copy Markdown

We did not find an internal engineer to review this PR, trying to assign a random engineer to #102298 as well as to this PR... Please reach out for help on Slack if no one gets assigned!

@melvin-bot
melvin-bot Bot requested a review from justinpersaud October 17, 2026 06:30

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

Makes sense to me.

@justinpersaud
justinpersaud merged commit d5772eb into main Oct 19, 2026
51 of 54 checks passed
@justinpersaud
justinpersaud deleted the claude-liveTodoSelectAllReportCount branch October 19, 2026 14:14
@github-actions

Copy link
Copy Markdown
Contributor

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

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/justinpersaud in version: 9.5.14-0 🚀

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

@MelvinBot

Copy link
Copy Markdown
Contributor Author

No help site update is needed. This PR is a bug fix that makes the "N selected" count after Select all drop when a report leaves a to-do list, which is what users already expect, and it doesn't make any existing article sentence incorrect.


view run

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/grgia in version: 9.5.14-3 🚀

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