Skip to content

refactor: remove unsafe assertions from router history, duplicate merging and bank lookups - #102986

Merged
blimpich merged 11 commits into
Expensify:mainfrom
KJ21-ENG:seatbelt-v2/2f101b35-a968-40b8-9601-b263fb872904
Nov 23, 2026
Merged

blimpich merged 11 commits into
Expensify:mainfrom
KJ21-ENG:seatbelt-v2/2f101b35-a968-40b8-9601-b263fb872904

Conversation

@KJ21-ENG

@KJ21-ENG KJ21-ENG commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

Remove unsafe as casts from router history, duplicate merging and bank connection lookups.

  • Router history (addPushParamsRouterExtension, addRootHistoryRouterExtension, addRootHistoryRouterExtensionUtils, useSyncSidePanelWithHistory): React Navigation types history as unknown[]. The asCustomHistory helper and the as CustomHistoryEntry[] / as NavigationRoute casts are gone. The helpers now take unknown[] and check each entry at runtime: typeof entry === 'string' for back-guard entries and isRecord(entry) for route snapshots.
  • getRehydratedState: React Navigation's Router.getRehydratedState accepts a partial or a full state. Our wrappers now accept both too, so the as PartialState cast and the @ts-expect-error are gone. The rehydrate wrapper only held that cast, so it is removed and its callers use getRehydratedState directly.
  • removeSettledAndApprovedTransactions: the filter is a type guard (transaction is Transaction), so the as Transaction[] is gone.
  • compareDuplicateTransactionFields: 'modifiedMerchant' and 'merchant' are already keys of Transaction, so their as keyof Transaction casts are removed.
  • buildMergeDuplicatesParams passes a Partial<Transaction>. getAmount, getCurrency, getCreated, getFormattedCreated and hasValidModifiedAmount now accept the partial fields they read, so the as OnyxEntry<Transaction> casts are gone.
  • getCompanyCardBankConnection / getPersonalCardBankConnection: getObjectKeys gives typed bank keys, and hasKey checks the key exists in BANK_CONNECTIONS. BANKS has keys such as OTHER that have no connection, and those still give undefined.

No behavior change. The app writes every history entry itself, so the new runtime checks pass for every entry it stores.

Changed files
  • src/components/SidePanel/useSyncSidePanelWithHistory/index.ts
  • src/libs/Navigation/AppNavigator/routerExtensions/addPushParamsRouterExtension.ts
  • src/libs/Navigation/AppNavigator/routerExtensions/addRootHistoryRouterExtension.ts
  • src/libs/Navigation/AppNavigator/routerExtensions/addRootHistoryRouterExtensionUtils.ts
  • src/libs/TransactionUtils/amountUtils.ts
  • src/libs/TransactionUtils/duplicates.ts
  • src/libs/TransactionUtils/fields.ts
  • src/libs/actions/getCompanyCardBankConnection/index.tsx

Fixed Issues

$ #94739
PROPOSAL: #94739 (comment)

Tests

C01 Tab history and layout changes
Precondition: On web, use a browser window narrower than 800 px. On Android, use the app. Open Spend > Expenses. Skip this case on iOS native, because the Spend tab has no Back action there.

  1. Switch to Reports, then Expenses, then Reports.
  2. Go Back once (on web, the browser Back button; on Android, the device Back button).
  3. Verify that Expenses is selected and its list is shown.
  4. Go Back once more.
  5. Verify that Reports is selected and its list is shown.
  6. On web only: go Forward twice.
  7. Verify that Expenses is selected after the first Forward, and Reports after the second.
  8. On web on a computer only: resize the window to wider than 800 px, then back to narrower than 800 px, then press the browser Back button.
  9. Verify that Back moves to the previous tab, with no extra step.

C02 Expense editor, close order, and focus
Precondition: Open an existing expense in its chat.

  1. Open the expense details, then the merchant editor.
  2. Close the editor, then the details, with Back (on web, the browser Back button or Esc; on Android, the device Back button; on iOS, swipe back).
  3. Verify that the merchant value and the chat are kept.
  4. Open the details and the merchant editor again, then close both with the back arrow at the top of each page.
  5. Verify that you return to the same place.

C03 Desktop side-panel resize
Precondition: Web in a computer browser, window wider than 1300 px.

  1. Open Help, then resize the window to between 800 px and 1300 px wide.
  2. Verify that the Help panel stays open and keeps its content.
  3. Press the browser Back button.
  4. Verify that the Help panel closes and the page under it stays.
  5. Open Help again and resize the window back to wider than 1300 px.
  6. Verify that the Help panel is still open and usable.

C04 Merge duplicate expenses
Precondition: You created two workspace expenses with the same amount, merchant and date in your own draft report, and they are flagged as duplicates.

  1. Open one of the expenses and press Review duplicates.
  2. Press Keep this one on the expense to keep. If field choices appear, choose the fields to keep, until the confirmation page opens.
  3. Press Confirm.
  4. Verify that one expense remains with the chosen fields, and the duplicate is removed.

C05 Company card bank connection
Precondition: You are an admin of a workspace with Company cards enabled. On Collect, the workspace has no company card feed yet.

  1. Go to Workspaces > your workspace > Company cards > Add cards, choose a bank such as Chase, and press Next until the connection step.
  2. On web, verify that a browser window opens with the bank's sign-in page, and the app shows "Check your browser window". If no window opens, press "please click here" and verify that the window opens.
  3. On Android and iOS, verify that the bank's sign-in page opens inside the app.

No new tests are added, because each cast removal keeps the same behavior. tests/unit/Navigation/routerExtensions/addPushParamsRouterExtension.test.ts, tests/unit/Navigation/routerExtensions/addRootHistoryRouterExtension.test.ts, tests/unit/TransactionUtilsTest.ts, tests/actions/IOUTest/DuplicateTest.ts and tests/unit/GetCompanyCardBankConnectionTest.ts cover the changed code.

Offline tests

N/A. These history, field and lookup changes do not change requests, queues, stored data or reconnect handling.

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 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 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.
  • If the PR adds or modifies the UI:
    • I asked an AI agent to review the changes for accessibility issues and addressed its findings.
    • I tested with a screen reader (VoiceOver on macOS) and verified all new/changed elements are reachable with a logical focus order.
    • I verified all new/changed elements have meaningful accessible names and roles.
    • I verified state changes are announced (e.g. checked/unchecked, expanded/collapsed, selected).
  • I added unit tests for any new feature or bug fix in this PR to help automatically prevent regressions in this user flow.
  • If the main branch was merged into this PR after a review, I tested again and verified the outcome was still expected according to the Test steps.

Screenshots/Videos

Screenshots/Videos (6)

C01 phone-sized

PR-102986-C01-M.mp4

C02 desktop

102986-C02-desktop.mp4

C02 phone-sized

102986-C02-phone-sized.mp4

C03 desktop

102986-C03-desktop.mp4

C04 desktop

102986-C04-desktop.mp4

C05 desktop

102986-C05-desktop.mp4

…n types

Seatbelt-Operation: session4-sign-28673b16-6202-4c89-baec-1773e1dedf28
Seatbelt-Operation: session4-corrected-sign-b69973f5-49aa-4f55-b41a-dfcdc1d1c3a7
Seatbelt-Operation: remaining-102986-sign-35ae4f8f-bb11-4640-a2dc-ce2aed4c9faa
@codecov

codecov Bot commented Oct 17, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Looks like you've decreased code coverage for some files. Please write tests to increase, or at least maintain, the existing level of code coverage. See our documentation here for how to interpret this table.

Files with missing lines Coverage Δ
...r/routerExtensions/addPushParamsRouterExtension.ts 99.33% <100.00%> (+<0.01%) ⬆️
.../routerExtensions/addRootHistoryRouterExtension.ts 100.00% <100.00%> (ø)
...erExtensions/addRootHistoryRouterExtensionUtils.ts 89.04% <100.00%> (-0.44%) ⬇️
src/libs/TransactionUtils/amountUtils.ts 100.00% <100.00%> (ø)
src/libs/TransactionUtils/duplicates.ts 90.47% <100.00%> (ø)
src/libs/TransactionUtils/fields.ts 100.00% <100.00%> (ø)
...ibs/actions/getCompanyCardBankConnection/index.tsx 92.59% <100.00%> (ø)
...nts/SidePanel/useSyncSidePanelWithHistory/index.ts 0.00% <0.00%> (ø)
... and 332 files with indirect coverage changes

@KJ21-ENG KJ21-ENG changed the title Remove unsafe type assertions from navigation, duplicates, and bank connections refactor: remove unsafe assertions from navigation, duplicates and bank lookups Oct 19, 2026
Seatbelt-Operation: main-20261030-102986-sign-7c520341-4f79-4712-b2ac-e1b4eedb3664
Resolve the TransactionUtils conflicts by widening the moved field helpers. Revert the helper renames
and keep the history tests as on main.
@KJ21-ENG KJ21-ENG changed the title refactor: remove unsafe assertions from navigation, duplicates and bank lookups refactor: remove unsafe assertions from router history, duplicate merging and bank lookups Nov 12, 2026
@KJ21-ENG
KJ21-ENG marked this pull request as ready for review November 20, 2026 09:31
@KJ21-ENG
KJ21-ENG requested review from a team as code owners November 20, 2026 09:31
@KJ21-ENG

Copy link
Copy Markdown
Contributor Author

@situchan, could you please review this PR? Merged main at d6cc7089a6bf in b71a6f0959cb.

@expensify-chore-bot
expensify-chore-bot Bot requested review from situchan and removed request for a team November 20, 2026 09:31
@expensify-chore-bot

Copy link
Copy Markdown

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

@expensify-chore-bot
expensify-chore-bot Bot requested review from JmillsExpensify and removed request for a team November 20, 2026 09:31
@chatgpt-codex-connector

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

Copy link
Copy Markdown
Codex Review Summary: ✅ Completed

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

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-20T09:43:28.291775Z b71a6f0 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.

function preserveHistoryForRoutes(oldHistory: unknown[], routes: Array<{key?: string}>): unknown[] {
const remainingKeys = new Set(routes.map((r) => r.key));
return oldHistory.filter((entry) => typeof entry === 'string' || remainingKeys.has(entry.key));
// Keep history sentinels and anything that is not a route snapshot; drop only route snapshots whose route is gone.

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.

❌ CONSISTENCY-16 (docs)

This newly added comment uses the banned term "sentinels". Per CONSISTENCY-16, prefer plain language such as "guard entries" / "markers" in authored comments.

Suggested fix:

// Keep history guard entries and anything that is not a route snapshot; drop only route snapshots whose route is gone.
return oldHistory.filter((entry) => !isRecord(entry) || typeof entry.key !== 'string' || remainingKeys.has(entry.key));

Note: this is low-confidence, since sentinel is already established terminology in these files (isModalHistorySentinel, getTrailingStringSentinels, etc.) that this PR keeps.


Reviewed at: b71a6f0 | Please rate this suggestion with 👍 or 👎 to help us improve! Reactions are used to monitor reviewer efficiency.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Fixed in cf90f6c. The comment now says "string history markers". I kept the existing isModalHistorySentinel and related function names, because this PR does not add them.

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

No product review required.

@situchan

situchan commented Nov 22, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer Checklist

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

Screenshots/Videos

Android: HybridApp
Android: mWeb Chrome
iOS: HybridApp
iOS: mWeb Safari
MacOS: Chrome / Safari
test1.mov
test2.mov

Comment on lines 57 to 59
function rehydrate(newState: PartialState<RootHistoryState> | RootHistoryState, configOptions: RouterConfigOptions) {
return getRehydratedState(newState as PartialState<RootHistoryState>, configOptions);
return getRehydratedState(newState, configOptions);
}

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.

rehydrate now only forwards to getRehydratedState

rehydrate existed to hold the cast to PartialState. With the cast gone and getRehydratedState taking PartialState | RootHistoryState, both have the same signature.

const getRehydratedState = (partialState: PartialState<RootHistoryState> | RootHistoryState, configOptions: RouterConfigOptions) => {

Can we remove rehydrate and pass getRehydratedState at its four call sites?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done in 7b83543.

@melvin-bot
melvin-bot Bot requested a review from blimpich November 23, 2026 18:05
@blimpich
blimpich merged commit 40c77c4 into Expensify:main Nov 23, 2026
38 of 42 checks passed
@OSBotify

Copy link
Copy Markdown
Contributor

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

@github-actions

Copy link
Copy Markdown
Contributor

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

@github-actions

Copy link
Copy Markdown
Contributor

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/blimpich in version: 9.5.53-0 🚀

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

@MelvinBot

Copy link
Copy Markdown
Contributor

No help site update needed — this PR is an internal type-safety refactor that adds no user-facing functionality and leaves existing documented workflows unchanged.


view run

@jponikarchuk

Copy link
Copy Markdown

This PR failing because of the issue #107807
This issue is reproducible in: Android app

@KJ21-ENG

KJ21-ENG commented Nov 25, 2026 •

Copy link
Copy Markdown
Contributor Author

#107807 is not caused by this PR. The bug was already in production.

  1. Production has the bug, but not this PR. Production 9.5.52-4 still has the old code this PR removed (L188).

  2. The code that causes the bug did not change. Android Back runs canGoBack() and then goBack() (source). Both calls move the router's history position (production L218, the same as L224 after this PR). So each Back press goes back two steps: it skips Expenses, and then the app leaves Spend.

This PR only replaced type casts around that code. @jponikarchuk, could you please mark this PR as not failing for this issue?

@situchan @blimpich

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/arosiclair in version: 9.5.53-3 🚀

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

Bundle Size Analysis (Sentry):

1 similar comment
@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/arosiclair in version: 9.5.53-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

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

7 participants