Skip to content

Migrate useSingleExecution off InteractionManager#95391

Draft
collectioneur wants to merge 24 commits into
Expensify:mainfrom
software-mansion-labs:collectioneur/transition-tracker-use-single-execution
Draft

Migrate useSingleExecution off InteractionManager#95391
collectioneur wants to merge 24 commits into
Expensify:mainfrom
software-mansion-labs:collectioneur/transition-tracker-use-single-execution

Conversation

@collectioneur

@collectioneur collectioneur commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

Explanation of Change

Migrates native useSingleExecution off InteractionManager.runAfterInteractions onto a new heuristic helper, runAfterPredictedTransition, and fixes two TransitionTracker / ScreenLayout bugs that made that wait unreliable.

Bug fixes in transitionStart / transitionEnd tracking

  1. Tab transitions were unreliable on Android for every tab, and on iOS for the Home tab specifically. Besides Home, the other bottom-tab routes host nested split navigators whose screens register via stack screenLayout, but that registration relies on transitionStart/transitionEnd, which react-native-screens only fires when tied to an actual view animation. Since tab switches use animation: 'none', no such animation ever runs on Android, so the nested-stack signal never fires there either, it just happened to look fine on iOS, where viewWillAppear fires on any visibility change regardless of animation. Home was simply the most visible case on any platform, since it has no nested navigator and thus no screenLayout wiring at all.
    Fixed by wiring bottomTabScreenLayoutWrapper directly into TabNavigator's own screenLayout, so tracking now comes from bottom-tabs' own transitionStart/transitionEnd, which fires consistently on both platforms regardless of the animation option.

  2. Unmount can leave a stuck open transition. A screen may emit transitionStart and then unmount before transitionEnd; cleanup unsubscribes the listeners, so transitionEnd never arrives and queued callbacks wait up to MAX_TRANSITION_DURATION_MS (1s). Fixed by calling TransitionTracker.endTransition on unmount whenever a handle is still open.

runAfterPredictedTransition (prediction mechanism)
Naive TransitionTracker.runAfterTransitions() right after a press usually sees zero active transitions (registration gap) and unlocks too early. Always using waitForUpcomingTransition: true would make non-navigating presses wait up to 1s. The new helper predicts whether the current press will cause a visual transition by watching navigationRef __unsafe_action__ + state: if a navigable action is followed by a focused-route change within NAVIGATION_PREDICTION_WINDOW_MS (150ms), it waits for that upcoming transition to finish; otherwise it settles immediately. useSingleExecution then re-enables the button after the predicted (or already-active) transition ends - or right away when no transition is predicted.

Fixed Issues

$ #71913
$ #83071

Tests

Tests (on iOS and Android):

  1. Go to Settings. You'll see a list of settings items.
  2. As fast as you can, tap one of the list buttons, then immediately tap any other one.
  3. Verify that no double navigation happens, only the first navigation that occurred goes through.

  1. Create a workspace.
  2. Go to the workspace, you'll see another list of buttons leading to different workspace pages.
  3. Double-tap them the same way as above.
  4. Verify that only the first navigation triggers and everything works as expected.

  1. Go to any chat and send a message.
  2. Start spamming reactions on that message: quickly add a reaction, reopen the reaction modal, add the next one, and repeat.
  3. Verify that emojis are applied correctly, i.e. the reaction picker isn't left blocked when you reopen the modal.

  1. Find any back button (top-left).
  2. Double-tap that button.
  3. Verify that only a single back navigation happens.
  • Verify that no errors appear in the JS console

Offline tests

N/A

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
Screen.Recording.2026-07-07.at.12.41.22.mov
Android: mWeb Chrome
iOS: Native
Screen.Recording.2026-07-07.at.12.46.48.mov
iOS: mWeb Safari
MacOS: Chrome / Safari

@codecov

codecov Bot commented Jul 6, 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 Δ
src/CONST/index.ts 94.81% <ø> (ø)
...on/AppNavigator/Navigators/TabNavigator.native.tsx 96.87% <ø> (ø)
...avigation/AppNavigator/Navigators/TabNavigator.tsx 0.00% <ø> (ø)
...avigation/PlatformStackNavigation/ScreenLayout.tsx 86.66% <100.00%> (+3.33%) ⬆️
src/libs/Navigation/TransitionTracker.ts 98.78% <92.30%> (-1.22%) ⬇️
src/libs/Navigation/runAfterPredictedTransition.ts 94.93% <94.93%> (ø)
src/hooks/useSingleExecution/index.native.ts 0.00% <0.00%> (-94.45%) ⬇️
... and 360 files with indirect coverage changes

@collectioneur collectioneur changed the title migrate last InteractionManager Migrate useSingleExecution off InteractionManager Jul 6, 2026
Comment thread src/hooks/useSingleExecution/index.native.ts Outdated
Comment thread src/hooks/useSingleExecution/index.native.ts Outdated
@roryabraham

Copy link
Copy Markdown
Contributor

posted a discussion on an alternate solution: https://expensify.slack.com/archives/C01GTK53T8Q/p1783451929635129

@collectioneur
collectioneur marked this pull request as ready for review July 8, 2026 15:30
@collectioneur
collectioneur requested review from a team as code owners July 8, 2026 15:30
@melvin-bot
melvin-bot Bot requested review from Pujan92 and ikevin127 and removed request for a team July 8, 2026 15:30
@melvin-bot

melvin-bot Bot commented Jul 8, 2026

Copy link
Copy Markdown

@Pujan92 @ikevin127 One of you needs to 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 July 8, 2026 15:30

@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: 781df22a2e

ℹ️ 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 thread src/hooks/useSingleExecution/index.native.ts Outdated

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

Comment on lines +44 to +46
timeoutRef.current = setTimeout(() => {
transitionHandleRef.current = TransitionTracker.runAfterTransitions({
callback: () => {

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.

Suggested change
timeoutRef.current = setTimeout(() => {
transitionHandleRef.current = TransitionTracker.runAfterTransitions({
callback: () => {
transitionHandleRef.current = TransitionTracker.runAfterTransitions({
waitForUpcomingTransition: true,
upcomingTransitionTimeoutMs: CONST.TIMING.SINGLE_EXECUTION_TRANSITION_WAIT_TIME, // ~150 for non-nav taps
callback: () => {

shall we use waitForUpcomingTransition and new prop with a lower timeout value?

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.

I looked into that, but unfortunately, it won't quite work. On slower devices, the transition can sometimes take more than 150ms to register, which would bring back the exact regression that useSingleExecution was originally meant to fix.

Instead, I went with a slightly different approach: I added a new prop to GenericPressable that disables useSingleExecution altogether, and I've applied it to all buttons where users might need to tap rapidly. I feel this is a cleaner solution because it explicitly separates rapid-tap buttons from regular ones, while still safely waiting for transitions when needed. It seems like a reasonable trade-off.

As for using the new prop, that's a great suggestion, thanks! I've added the updated TransitionTracker code from this PR and applied the changes (removed setTimeout and added a timeout prop instead).

The PR is ready for another look 🙌

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

Let's step back ... it seems like we are headed towards a more robust solution in this thread, without any delay/throttling issues, or needing to manually track the buttons for which a double-tap might trigger a double-navigation.

Meanwhile, the current solution using the (albeit deprecated) InteractionManager doesn't have these pitfalls either.

So I suggest that we close this pull request, and instead pursue the better solution described here, keeping the deprecated InteractionManager-based solution in the meantime.

@collectioneur

collectioneur commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

@roryabraham Yeah, I agree with you, it’s not a clean migration. I’ve tried to add unsafe_event first, but it turns out, that the commit adding unsafe_event (react-navigation/react-navigation@d22044d) was actually backported last month to @react-navigation/core@7.21.0.

Since we are currently on version 7.16.1, we'd need to update react-navigation first to use this in TransitionTracker. This would require a fair amount of effort, as we'll have to manually resolve some of the patches due to underlying logic changes before we can implement the event logic itself.

I think it might be a good idea to spin up a quick test app first, just to make sure this approach works for us. If it looks good, we can go ahead with the update.

I have some availability right now, so I’d be happy to take this on and start the update if we want to go that route 🙌

@roryabraham

Copy link
Copy Markdown
Contributor

sounds good

@collectioneur
collectioneur marked this pull request as draft July 15, 2026 14:03
@collectioneur

Copy link
Copy Markdown
Contributor Author

@codex review

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

ℹ️ 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 +51 to +53
navigationRef.addListener('__unsafe_action__', (event) => {
if (event.data.noop || ACTION_TYPES_WITHOUT_TRANSITION.has(event.data.action.type)) {
return;

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

P2 Badge Exempt nested tab switches from predicted transition waits

Plain tab bar presses in this app dispatch NAVIGATE (for example NavigationTabBar calls Navigation.navigate(...), and linkTo preserves NAVIGATE for isSwitchingTabsWithinTabNavigator). This branch treats those tab switches as transition candidates, so after the focused leaf route changes the hook waits for an upcoming TransitionTracker transition. For tabs backed by nested navigators, the new bottom-tab screen layout ignores the tab-level transition and the nested stack does not emit a stack transition for a root tab switch, so ordinary tab switches fall back to MAX_TRANSITION_START_WAIT_MS with a timeout log and a disabled pressed tab. Please special-case tab-switch NAVIGATEs or track those tab transitions.

Useful? React with 👍 / 👎.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

The tab-level navigator and the nested stack navigator are two different navigators. In my tests, the nested navigator always emits transitionStart and transitionEnd later than the tab navigator. That's why I disabled all tabs except for Home

@collectioneur

Copy link
Copy Markdown
Contributor Author

@codex review

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

Changes lgtm, left a few comments

Comment thread src/CONST/index.ts
COMPOSER_FOCUS_DELAY: 150,
MAX_TRANSITION_DURATION_MS: 1000,
MAX_TRANSITION_START_WAIT_MS: 1000,
NAVIGATION_PREDICTION_WINDOW_MS: 150,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I'd verify if 150ms is enough even on low-end android devices

@collectioneur collectioneur Jul 17, 2026

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.

I’ve investigated runAfterPredictedTransition on a lower-end device (Motorola Moto G15), and the results are pretty interesting.

The registered 150ms safety timeout is blocked and does not run while the js thread is busy with react’s state update and commit. After react commits, that overdue timeout races the state listener: react navigation emits the new state from useEffect (after commit), so once the thread is free again the timeout can fire either before or after the listener sees the update.

I fixed this by adding an extra check when the 150ms timeout runs: before clearing the prediction, it checks whether the navigation ref already has the new focused route. That check is reliable for normal navigations, because the ref store is updated during react navigation setState, before commit, so the new route is already visible even if the state listener has not run yet.

Comment on lines +11 to +12
// never move the focused route. JUMP_TO can, but only tab navigators use it and they do not emit
// transitionStart/transitionEnd, so waiting on TransitionTracker would never settle.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I wonder if we should try to support JUMP_TO in TransitionTracker 🤔 From what the comment says, it's not an issue at the moment, but we could be future-proof and handle it right away
Of course, we should do it in a separate issue

Let me know if that's worth investigating @roryabraham @collectioneur

Comment thread src/libs/Navigation/runAfterPredictedTransition.ts

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

ℹ️ 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 thread src/libs/Navigation/runAfterPredictedTransition.ts Outdated

@JakubKorytko JakubKorytko left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

nice direction overall! most of my comments are around scoping tab-level tracking, a couple edge cases in the prediction helper, and test coverage gaps

Comment thread src/libs/Navigation/runAfterPredictedTransition.ts Outdated
backBehavior="fullHistory"
tabBar={renderTabBar}
screenOptions={screenOptions}
screenLayout={bottomTabScreenLayoutWrapper}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

the PR description mentions wiring this with a focus guard so nested tab routes do not double-register, but screenLayout is applied on Tab.Navigator for every tab. Nested tabs already get stack screenLayout, and tab switches use animation: 'none', so it is unclear what extra transitions this adds outside Home. If Home is the only tab that mounts a screen directly, consider scoping bottomTabScreenLayoutWrapper to the Home Tab.Screen instead of the whole navigator

let innerHandle: CancelHandle | null = null;

// Yield one macrotask so a navigation dispatch in the same press handler can register first.
setTimeout(() => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

cancel() sets a flag and cancels the inner TransitionTracker handle, but the outer setTimeout(..., 0) is never cleared. It is harmless today because the callback no-ops when cancelled is true, but storing the timeout id and calling clearTimeout in cancel() would make the CancelHandle fully abort work (and avoids running whenPredictionSettled after unmount)

InteractionManager.runAfterInteractions(() => {
// Re-enables the button once the predicted (or actual) transition triggered by this press
// ends - or immediately, if the press wasn't predicted to cause one.
transitionHandleRef.current = runAfterPredictedTransition(() => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

unmount cleanup cancels the transition handle, but if action() returned a Promise, execution.finally inside this callback can still call setIsExecuting(false) afterward. That is the same class of issue as the old uncancelled debounce timer. A small mounted/ref guard around the setIsExecuting(false) paths would prevent a post-unmount state update when the async action settles late

return;
}

const didFocusedRouteChange = focusedRouteKey !== lastFocusedRouteKey;

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

when lastFocusedRouteKey is still undefined, the first hydrated key always looks like a focus change (undefined !== 'route-a'). That is probably fine once the app has emitted a baseline state event, but on a cold start where the first state event arrives after a press, this can confirm a focus move even if the action did not actually move focus yet.

Worth a test (or an explicit "baseline captured" flag) so we do not regress the double-tap fix on slow initial hydration

expect(callback).toHaveBeenCalledTimes(1);
});

it('waits for an upcoming transition when an action is followed by a focus change', async () => {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

this covers the happy path where a focus change is followed by a real transitionStart. There is still no test for a focus change with no upcoming transition (for example a tab switch that changes the focused leaf route but never emits transitionStart). That path falls through to waitForUpcomingTransition: true and then the 1s TransitionTracker timeout. A test here would document the expected behavior and catch accidental 1s button lockouts

Comment thread jest/setupAfterEnv.ts
// `runAfterPredictedTransition`/`TransitionTracker`), which don't happen in unit tests and would
// otherwise leave buttons stuck disabled. Mocked globally so no test needs to import the navigation
// listener machinery just because it renders a Pressable-based component (Button, MenuItem, etc.).
jest.mock('@hooks/useSingleExecution', () => ({

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

globally mocking useSingleExecution makes sense for unit tests, but it means nothing in Jest exercises the native hook wiring end to end. The new runAfterPredictedTransition tests are thorough; a small native-hook test (even with mocked navigation listeners) would give extra confidence that isExecuting clears on both sync and async actions

};
}

const TransitionTracker = {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

new onTransitionStart API drives prediction clearing in runAfterPredictedTransition, but TransitionTrackerTest does not cover listener notification or error isolation through this path (only the renamed invokeSafely messages changed). A small test that startTransition invokes subscribers would protect this hook from regressions

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