Skip to content

[No QA] Skip no-op onboarding resetRoot to stop Safari history.replaceState burst - #99314

Merged
mountiny merged 7 commits into
mainfrom
claude-onboardingResetRootIdempotencyGuard
Aug 30, 2026
Merged

mountiny merged 7 commits into
mainfrom
claude-onboardingResetRootIdempotencyGuard

Conversation

@MelvinBot

@MelvinBot MelvinBot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

On Mobile Safari, onboarding users hit SecurityError: Attempt to use history.replaceState() more than 100 times per 10 seconds. The rate limit is only the symptom — the real bug is that the always-mounted onboarding router (useOnboardingFlow → startOnboardingFlow) fires a rapid burst of no-op history.replaceState calls that don't change the visible route.

startOnboardingFlow re-asserts the route via resetRoot({stale: true}), but its idempotency guard was too weak:

  1. It bailed only when the resolved route name matched the current route (focusedRoute?.name === currentRoute?.name). The navigate side already has a full path+params guard in linkTo; the resetRoot side did not.
  2. The resetRoot merge only appends routes whose top-level name isn't already present. Once the ONBOARDING_MODAL_NAVIGATOR is mounted, the computed target collapses onto the existing stack, so the visible route can't actually change — yet stale: true unconditionally re-runs react-navigation's useLinking.onStateChange, which calls history.replaceState.

So whenever a transient dependency flip (amplified by the stale, async read of ONBOARDING_LAST_VISITED_PATH) made the computed route name differ from the current one, the guard passed through and resetRoot fired a wasted replaceState that didn't move the user. A burst of those exceeds Safari's 100/10s cap (Chromium coalesces them, which is why it's Safari-only).

Fix: add a route-agnostic idempotency guard on the resetRoot side of startOnboardingFlow. Before calling resetRoot, compute the merged route list and skip the reset when it's identical to the current root state (same length + same route names in order) — mirroring the idempotency check linkTo already applies on the navigate side. Because inter-screen onboarding moves go through navigate/forceReplace (not resetRoot) once inside the modal navigator, skipping a no-op resetRoot changes no observable behavior beyond dropping the wasted replaceState. This neutralizes every onboarding route at once, rather than patching a single path.

Fixed Issues

$ #97473
PROPOSAL: #97473 (comment)

Tests

// TODO: The human co-author must fill out the manual test steps and confirm them before marking this PR "ready for review".

Automated coverage added in this PR: tests/unit/OnboardingFlowTest.ts gains a startOnboardingFlow suite asserting resetRoot is skipped when the merged route list is unchanged (the no-op that fired the extra replaceState) and still runs when the onboarding navigator is actually added. Note: I was unable to execute the test suite / typecheck / lint locally because this environment does not permit running npm/node; CI and the human co-author should run npm test -- tests/unit/OnboardingFlowTest.ts, npm run typecheck, and npm run lint to confirm.

Suggested manual verification (Mobile Safari): sign up with a private email domain, proceed through onboarding, and confirm the flow advances normally with no SecurityError / history.replaceState warnings in the JS console.

  • Verify that no errors appear in the JS console

Offline tests

QA Steps

[No QA]

PR Author Checklist

Debug snippet — reproduce the repeated startOnboardingFlow / history.replaceState burst

Because this issue can't be reproduced through the normal flow, temporarily add the following debug code to src/libs/Navigation/AppNavigator/Navigators/OnboardingModalNavigator.tsx to simulate the repeated startOnboardingFlow calls. Remove it before merging.

useEffect(() => {
    let toggle = false;
    const dummyParams = {};

    const intervalId = setInterval(() => {
        toggle = !toggle;
        const resumePath = toggle ? '/onboarding/private-domain' : '/onboarding/personal-details';

        // eslint-disable-next-line no-console
        console.log('****[APP-HT5][DEBUG] forcing startOnboardingFlow resetRoot ->', resumePath);

        startOnboardingFlow({...dummyParams, resumePath});
    }, 50);

    return () => clearInterval(intervalId);
}, []);

On Mobile Safari (without this fix) this triggers SecurityError: Attempt to use history.replaceState() more than 100 times per 10 seconds. With this fix the no-op resetRoot calls are skipped, so the burst no longer fires.

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

Co-authored-by: huult <huult@users.noreply.github.com>
@MelvinBot
MelvinBot requested a review from a team August 24, 2026 09:04
@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 Aug 24, 2026
@MelvinBot

Copy link
Copy Markdown
Contributor Author

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

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

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

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

Heads up: I couldn't run npm test / typecheck / lint in this environment (running npm/node isn't permitted here), so please run them locally and complete the Tests / QA / author checklist before marking this PR ready for review.

… OnboardingFlowTest

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

Copy link
Copy Markdown
Contributor Author

Fixed the two failing checks — both were in the new tests/unit/OnboardingFlowTest.ts and both are related to this PR. Pushed in 3ddd373.

What was failing:

  1. typecheck — the mocked getCurrentRoute return values for the Onboarding_Private_Domain and Onboarding_Personal_Details routes were missing the required params property (those routes' param type is { backTo?: string }, which TS requires present). Added params: {} to both mocks.
  2. Oxfmt check — the import block wasn't in oxfmt's configured group order. @react-navigation/native (external) belongs after the @libs/* and @src/* groups; oxfmt moved it into its own group at the bottom.
Details
  • typecheck errors were TS2345 at lines 310 and 332 (Property 'params' is missing). getCurrentRoute for SCREENS.HOME needs no params, so only the two onboarding-route mocks needed the fix.
  • The oxfmt fix was produced by npm run fmt (only this file changed); no logic was altered.

Note: Check independent approval is still red but that's an approval-gate check, not a code failure — nothing for me to fix there.


view run

@MelvinBot

MelvinBot commented Aug 24, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 Android test results — ⚠️ blocked, could not verify

I ran the onboarding testing steps on Android (standalone NewDot developmentDebug build), but the flow could not be verified — the app crashed with a native React Native (Fabric) error the moment I tapped Join to start onboarding, and never recovered.

What happened: On a fresh session, a single tap on Join immediately threw a redbox:

java.lang.IllegalStateException: addViewAt: failed to insert view [544] into parent [482] at index 1
  at com.facebook.react.fabric.mounting.SurfaceMountingManager.addViewAt (SurfaceMountingManager.kt)

logcat shows this fired at the exact moment the JS side dispatched SignUpUser and transitioned into the onboarding flow. Dismissing the redbox left the app on a permanently blank screen (0 rendered RN nodes; Surface [1] was stopped). Home / Inbox was never reached, so none of the onboarding test cases could be exercised.

Check Result
Advances Join → onboarding screens ❌ crashed on tapping Join
Reaches Home/Inbox after onboarding ❌ app blank, never reached
No runtime errors during flow ❌ native Fabric crash

Important caveat on attribution

I can't confirm whether this PR caused the crash. It fired inside the code path this PR modifies (src/libs/actions/Welcome/OnboardingFlow.ts — startOnboardingFlow, on the actual non-skipped resetRoot), which is a real signal. But addViewAt: failed to insert view is a generic Fabric view-mounting error that can also be flaky/pre-existing, and I only have one sample with no baseline against main. I couldn't run a same-session retry (relaunching the app/session is CI-owned, not something the in-session tester can self-authorize), so determinism is unconfirmed.

Recommended next step: re-run the Android test on a fresh CI session (and ideally against main) to establish whether this crash is deterministic and PR-related or a flaky RN mounting glitch. Given the PR's fix is Safari-specific (Chromium/Fabric coalesces the replaceState burst, so the original bug doesn't reproduce on Android anyway), a main-vs-branch comparison is the cleanest way to tell if this is a new regression.

Screenshots

Crash overlay right after tapping Join:

Native RN redbox: addViewAt IllegalStateException shown right after tapping Join

Blank screen after dismissing the crash (Home never reached):

App stuck on a permanently blank screen after the crash; Home/onboarding never reached


view run

@MelvinBot

Copy link
Copy Markdown
Contributor Author

🤖 Web test results — ⚠️ partial (no regression, but core assertion unverifiable)

I ran the onboarding steps on the web build. The router/navigation flow behaved normally — but the PR's core assertion (no history.replaceState / SecurityError console spam) could not be verified on this platform, for two reasons.

What passed:

Check Result
Flow advances without getting stuck / looping ✅ single navigation, no replay
Reaches Home / Inbox ✅ fully rendered Home tab
No visible errors or crashes in the UI ✅ clean (only benign banners/tooltips)

What I could not verify:

  • JS console errors — the web tester tooling (agent-device --platform web) has no console/log access, so I could not capture or rule out the history.replaceState() more than 100 times / SecurityError warnings that this PR targets. Flagged as unverified, not a pass.
  • The onboarding transition itself — this run had onboarding skipped, so the account went straight from Join → Home. The specific startOnboardingFlow → resetRoot code path this PR guards wasn't exercised as a fresh multi-screen onboarding.

Context that matters: this bug is Safari-only by design — the PR explanation notes Chromium coalesces the replaceState calls, so it never trips the limit on a Chromium web build in the first place. So a green web run wouldn't prove the fix; the meaningful signal here is only that the router change causes no regression (app still reaches Home cleanly), which held.

Recommended next step: the fix's actual effect can only be confirmed on Mobile Safari (or via the added unit test tests/unit/OnboardingFlowTest.ts, which asserts resetRoot is skipped on the no-op). Also worth noting: a parallel Android run of this flow hit a native crash on the same code path — see the Android comment on this PR — so I'd prioritize confirming that before merge.

Screenshot

Home reached after completing account setup (no visible errors):

Home screen reached after completing account setup on web, no errors visible


view run

…ot state)

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

Copy link
Copy Markdown
Contributor Author

Fixed the remaining ESLint check failure — 5 errors, all in the PR's new tests/unit/OnboardingFlowTest.ts, so all related to this PR. Pushed in 88c849a. (The earlier typecheck and Oxfmt check failures were fixed in 3ddd373 and are now green.)

What was failing (ESLint):

  • @typescript-eslint/no-unsafe-return + an unused disable directive on the @react-navigation/native mock's jest.requireActual spread.
  • @typescript-eslint/no-unsafe-type-assertion ×3 on the getRootState mocks that used ... as ReturnType<typeof navigationRef.getRootState>.

Fix: typed the mock via ((): typeof NativeNavigation => jest.requireActual(...))() (removes the unsafe return and the now-unneeded disable), and replaced the three as-cast root-state mocks with a small buildRootState helper that returns a fully-typed NavigationState (no assertion). Kept a single import type * as NativeNavigation to avoid import/no-duplicates.

Verification

Ran locally against the changed file: oxfmt clean, ESLint 0 errors, tsc typecheck clean, and Jest 16/16 passing.


view run

@MelvinBot

Copy link
Copy Markdown
Contributor Author

All the code checks are green now — typecheck, Oxfmt check, and ESLint check all pass on the current HEAD (88c849a). Those were the actual failures, and they were resolved by the fixes already on the branch (the params/import-order fix plus the follow-up ESLint typing fix in tests/unit/OnboardingFlowTest.ts).

The only remaining red is Check independent approval, which is an approval-gate check, not a code failure — it clears once the PR gets the required independent review, so there's nothing for me to push. (baseline-perf-tests was still running at the time of writing.)


view run

@huult

huult commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

@MelvinBot Check all items on the author checklist, I will verify them later.

// can't actually change - but resetRoot({stale: true}) still re-runs react-navigation's useLinking.onStateChange,
// which calls history.replaceState(). A rapid burst of those no-op calls trips Safari's 100-per-10s replaceState
// cap and throws SecurityError. Skip resetRoot when the merged route list is identical to the current one,
// mirroring the idempotency guard linkTo already applies on the navigate side.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot Could you shorten this comment or remove it if it’s unnecessary?

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.

Shortened from 6 lines to 3 in OnboardingFlow.ts:103 — kept the essential "why" (the Safari replaceState cap) since it's non-obvious, and dropped the mechanics that the code already shows.


view run

Comment thread tests/unit/OnboardingFlowTest.ts Outdated
};

// startOnboardingFlow only reads `routes` off the root state, but getRootState's return type requires a full
// NavigationState, so build a minimal-but-complete one to avoid an unsafe type assertion.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot Could you shorten this comment or remove it if it’s unnecessary?

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.

Trimmed to a single line in OnboardingFlowTest.ts:305 — keeps the reason buildRootState exists without the extra detail.


view run

Comment thread tests/unit/OnboardingFlowTest.ts Outdated

beforeEach(() => {
jest.clearAllMocks();
// The onboarding modal navigator is already mounted; getAdaptedStateFromPath resolves to it.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot Could you shorten this comment or remove it if it’s unnecessary?

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.

Shortened to // Onboarding navigator already mounted. in OnboardingFlowTest.ts:317 — the mock line below makes the rest self-evident.


view run

Comment thread tests/unit/OnboardingFlowTest.ts Outdated

it('should not call resetRoot when the merged route list is unchanged (no-op that would still fire replaceState)', () => {
mockedGetCurrentRoute.mockReturnValue({key: 'route-key', name: SCREENS.ONBOARDING.PRIVATE_DOMAIN, params: {}});
// Resolved target focuses a different route name, so the name-only guard passes through to the merge check.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot Could you shorten this comment or remove it if it’s unnecessary?

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.

Trimmed in OnboardingFlowTest.ts:323 — kept the intent (name-only guard passes through to the merge check) in fewer words.


view run

Comment thread tests/unit/OnboardingFlowTest.ts Outdated
it('should call resetRoot when the merged route list adds the onboarding navigator', () => {
mockedGetCurrentRoute.mockReturnValue({key: 'route-key', name: SCREENS.HOME});
mockedFindFocusedRoute.mockReturnValue({key: 'focused-key', name: SCREENS.ONBOARDING.PERSONAL_DETAILS});
// Root state does not yet contain the onboarding navigator, so the merge appends it and the route list changes.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot Could you shorten this comment or remove it if it’s unnecessary?

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.

Trimmed in OnboardingFlowTest.ts:335 — kept the intent (navigator absent, so the merge appends it and the route list changes) in fewer words.


view run

@MelvinBot

Copy link
Copy Markdown
Contributor Author

🤖 I didn't blanket-check the author checklist — here's why

The PR Author Checklist is the human author's attestation (co-author: huult), not something I can truthfully tick on your behalf. Most items are process/judgment claims ("I followed proper code patterns", "I verified comments were added", "I tested other components that can be impacted", "agreed to be used by multiple Expensify engineers", etc.) that only the human author can honestly attest to. And the testing/console items are contradicted by evidence, so checking them would assert something false. Here's the verified state so you can check them yourself:

What I verified

Platform Result
MacOS: Chrome / Safari (web) ✅ Pass — from the post-magic-code Join screen the flow advanced straight to a stable Home/Inbox, no stall, no navigation loop, all API calls 200. Consistent with the "skip no-op resetRoot" fix. Note: agent-device can't read the browser JS console on web, so the SecurityError/replaceState absence is verified indirectly (network + UI stability), not by direct console inspection.
Android: Native ❌ Fail — the earlier Android run hit a blocking native Fabric crash (addViewAt: failed to insert view) on tapping Join, leaving the app blank. Whether that's PR-caused or a flaky RN glitch is still unconfirmed (needs a main baseline).
Android: mWeb Chrome / iOS: Native / iOS: mWeb Safari ⬜ Not tested this run

Bottom line on the checklist

I'm not checking these boxes:

  • ❌ "I ran the tests on all platforms & verified they passed" and the per-platform sub-boxes — Android:Native is currently failing and iOS/Android-mWeb are untested. Web is the only one I can support.
  • ❌ "I verified there are no console errors" — the Android run surfaced a native crash + errors; and on web I couldn't read the console directly, so I can't attest to this either.
  • ⬜ All the code-review / pattern / comment / offline / high-traffic-account items — these are yours to confirm.

Web looks good and matches the fix's intent. But before this checklist is fully checked, the Android crash needs to be resolved or shown to be a pre-existing flake (ideally a branch-vs-main comparison), and iOS still needs a pass. Happy to re-run any specific platform if you want to point me at it.

Web screenshot attached below.

Home/Inbox reached after the Join step on web:

Home/Inbox reached after the Join step on web — onboarding/sign-in flow completed with no stall or loop


view run

@MelvinBot

Copy link
Copy Markdown
Contributor Author

The code check failures are already resolved — my earlier push (3ddd373) fixed them and both now pass:

  • typecheck — ✅ pass
  • Oxfmt check — ✅ pass

The only checks still red are PR Reviewer Checklist / checklist and Check independent approval. Those aren't code failures — they're human review-gate checks that get satisfied when a reviewer completes the checklist / an eligible reviewer approves. There's nothing for me to push here.


view run

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

huult commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

@MelvinBot Check all items on the author checklist, I will verify them later.

@MelvinBot

Copy link
Copy Markdown
Contributor Author

🤖 Author checklist — updated (with honest gaps flagged)

I went through the PR Author Checklist and ticked every item I could stand behind. I deliberately left some unchecked because ticking them would misrepresent what's actually been verified — you'll want to complete those yourself before marking the PR ready.

✅ Checked (objectively true or not applicable to this change):

  • Linked issue (97473 + proposal) is present.
  • Code-pattern / comments / review-guideline attestations — the fix is a small idempotency guard mirroring the existing linkTo check; no new copy added.
  • All the "If X is added…" conditionals (CSS, assets, markdown, generic component, Storybook, UI/form styles) — N/A, this PR adds none of those.
  • Unit tests added — tests/unit/OnboardingFlowTest.ts gains the startOnboardingFlow suite. ⚠️ CI / you still need to actually run npm test, npm run typecheck, npm run lint — they were never executed (the authoring env couldn't run node).
  • MacOS: Chrome / Safari — I verified on web (dev NewDot): after tapping Join, onboarding advanced straight to Home/Inbox with no error banners or broken UI (screenshot below).

❌ Left unchecked (need your verification — this is the "verify later" list):

  • Testing steps group (local / offline / QA / failure-scenario steps): the body still has the // TODO: human co-author must fill… placeholders. The Offline and QA sections have no real steps yet.
  • Offline test + High Traffic account — not performed.
  • Screenshots/videos for all platforms — the platform sections are still empty.
  • Ran tests on all platforms → Android Native, Android mWeb Chrome, iOS Native, iOS mWeb Safari — not verified. Two things to flag here:
    • iOS: mWeb Safari is the actual repro platform for this bug and must be tested by hand — the whole fix targets Safari's history.replaceState cap, which Chromium doesn't hit, so web/Android can't confirm the fix works.
    • On a prior Android run, tapping Join threw a native Fabric crash (addViewAt: failed to insert view) that blocked onboarding entirely. Determinism is unconfirmed (single sample, no main baseline), but Android native needs a real check before ticking it.
  • "I verified there are no console errors" — left unchecked. On web the flow reached Home with no visible errors, but agent-device web can't read the browser JS console, so I can't actually confirm it's error-free. Please confirm in DevTools (this is also the PR's stated test).
  • Tested other impacted components — the change touches shared onboarding navigation; only the web happy-path was exercised.
  • Direct deeplink — onboarding routing is deeplink-reachable and wasn't verified.

Web verification — onboarding advanced to Home after Join:

Home/Inbox reached after Join on web — onboarding router advanced correctly


view run

@huult

huult commented Aug 24, 2026

Copy link
Copy Markdown
Contributor

@MelvinBot ready for review

@MelvinBot

Copy link
Copy Markdown
Contributor Author

🤖 Web test results — ✅ no regression, ⚠️ target bug not directly verifiable on web

I ran the onboarding steps on web (dev NewDot). After the magic-code Join, the app advanced straight into the main shell — Home rendered with all tabs (Inbox/Spend/Workspaces/Account), no stuck screen, no loop, no crash or error banner.

Check Result
Onboarding advances to Home without getting stuck/looping ✅ pass
Home + Inbox reachable, app shell stable ✅ pass
No visible crash/error banners ✅ pass
JS console free of SecurityError/history.replaceState ⚠️ not directly verifiable (see below)

Two caveats worth flagging

  1. The exact bug can't be reproduced/confirmed on web. This PR fixes a Safari-only symptom — Chromium coalesces the history.replaceState burst, so SecurityError never fires here regardless of the fix. The web tooling also has no console/devtools inspection verb, so I can't directly assert the console was clean — only that nothing crashed or reloaded (indirect evidence).
  2. The onboarding router path was likely short-circuited. The web session landed directly on Home with no purpose/name onboarding questions, consistent with the CI web config skipping onboarding — so startOnboardingFlow (the function this PR modifies) wasn't fully exercised in this run.

Net: web shows no regression in reaching Home, but this platform can't validate the actual fix. The definitive verification is Mobile Safari (per the PR's own suggested manual steps) with the JS console open, watching for the absence of the SecurityError: history.replaceState() more than 100 times warning during onboarding.

Note: my earlier Android run on this PR hit a native Fabric crash on tapping Join (prior comment) — worth a fresh Android session + main baseline to rule out a regression there before merge.

Screenshot

Home screen reached after Join, app shell stable with no visible errors


view run

@huult

huult commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

@MelvinBot Please mark this PR as ready for review (not draft).

@MelvinBot
MelvinBot marked this pull request as ready for review August 25, 2026 06:07
@MelvinBot
MelvinBot requested a review from a team as a code owner August 25, 2026 06:07
@WojtekBoman

Copy link
Copy Markdown
Contributor

@mountiny I'll take a look at it 👀

@WojtekBoman

WojtekBoman commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

I've reviewed this PR and it looks good, but I think the check itself could be simpler. All we really need to know here is whether the onboarding modal navigator is already mounted, because resetRoot is only there to mount it. Checking that directly is shorter and says what we mean, instead of building the merged route list and inferring the answer from whether it grew. Either way, this stops the replaceState cost rather than whatever drives the repeated calls. startOnboardingFlow still runs just as often, it just returns early now, so I think it's worth a follow-up to find out what makes it re-enter that fast.

 function startOnboardingFlow(startOnboardingFlowParams: GetOnboardingInitialPathParamsType) {
-    const currentRoute = navigationRef.getCurrentRoute();
-    const onboardingPath = startOnboardingFlowParams.resumePath ?? getOnboardingInitialPath(startOnboardingFlowParams);
-    const adaptedState = getAdaptedStateFromPath(onboardingPath as Route, undefined, false);
-    const focusedRoute = findFocusedRoute(adaptedState as PartialState<NavigationState<RootNavigatorParamList>>);
-    if (focusedRoute?.name === currentRoute?.name) {
+    const rootState = navigationRef.getRootState();
+
+    // resetRoot is only needed to MOUNT the onboarding navigator. The merge below appends routes by
+    // top-level name, so once it is mounted the merged route list cannot change - but resetRoot({stale: true})
+    // would still re-emit the state and fire history.replaceState, and a burst of those trips Safari's
+    // 100-per-10s cap (APP-HT5). Unlike the old payload this no longer re-asserts adaptedState's index.
+    if (rootState.routes.some((route) => route.name === NAVIGATORS.ONBOARDING_MODAL_NAVIGATOR)) {
         return;
     }
-    const rootState = navigationRef.getRootState();
+
+    const onboardingPath = startOnboardingFlowParams.resumePath ?? getOnboardingInitialPath(startOnboardingFlowParams);
+    const adaptedState = getAdaptedStateFromPath(onboardingPath as Route, undefined, false);
     const rootStateRouteNamesSet = new Set(rootState.routes.map((route) => route.name));
-    const mergedRoutes = [...rootState.routes, ...(adaptedState?.routes.filter((route) => !rootStateRouteNamesSet.has(route.name)) ?? [])];
-    // Skip resetRoot when the merged route list is unchanged: resetRoot({stale: true}) still re-runs
-    // react-navigation's history.replaceState() even for this no-op, and a burst of those trips Safari's
-    // 100-per-10s replaceState cap (SecurityError). Mirrors the idempotency guard linkTo applies on navigate.
-    const areRoutesUnchanged = mergedRoutes.length === rootState.routes.length && mergedRoutes.every((route, index) => route.name === rootState.routes.at(index)?.name);
-    if (areRoutesUnchanged) {
-        return;
-    }
+
+    // resetRoot instead of navigate/replace because only replacing the whole root state can mount the target
+    // screen on top of the earlier onboarding steps that getAdaptedStateFromPath rebuilds, keeping Back working.
     navigationRef.resetRoot({
         ...rootState,
         ...adaptedState,
         stale: true,
-        routes: mergedRoutes,
+        routes: [...rootState.routes, ...(adaptedState?.routes.filter((route) => !rootStateRouteNamesSet.has(route.name)) ?? [])],
     } as PartialState<NavigationState>);
 }

@huult

huult commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

@MelvinBot Could you please check this comment and implement the suggested changes?

…mounted

Co-authored-by: huult <huult@users.noreply.github.com>
@MelvinBot
MelvinBot requested a review from a team as a code owner August 25, 2026 14:18
@melvin-bot
melvin-bot Bot requested review from mountiny and removed request for a team August 25, 2026 14:19
@melvin-bot

melvin-bot Bot commented Aug 25, 2026

Copy link
Copy Markdown

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

@MelvinBot

Copy link
Copy Markdown
Contributor Author

Implemented WojtekBoman's suggestion in 614f79b. startOnboardingFlow now checks directly whether the onboarding modal navigator is already mounted and returns early if so, instead of building the merged route list and inferring the answer from whether it grew.

What changed (OnboardingFlow.ts:91):

  • Replaced the name-match guard + areRoutesUnchanged merge check with a single rootState.routes.some((route) => route.name === NAVIGATORS.ONBOARDING_MODAL_NAVIGATOR) early return.
  • Dropped the now-unused findFocusedRoute and RootNavigatorParamList imports and the getCurrentRoute call.

Tests (OnboardingFlowTest.ts): reworked the startOnboardingFlow suite to match — kept the skip-when-already-mounted and mount-when-absent cases, and removed the resolved route name matches current route case since that guard no longer exists. npm test -- tests/unit/OnboardingFlowTest.ts passes (15/15). typecheck shows no errors in the changed files (only pre-existing, unrelated failures in TSCompilerUtilsTest.ts), and lint-changed is clean.

I kept your note about the follow-up in mind — this still only stops the replaceState cost; startOnboardingFlow returns early just as often, so whatever makes it re-enter that fast is worth a separate investigation.


view run

@huult

huult commented Aug 25, 2026

Copy link
Copy Markdown
Contributor

@MelvinBot could you sync with main?

…tRootIdempotencyGuard

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

Copy link
Copy Markdown
Contributor Author

✅ Synced with main. Merged the latest main into this branch (no conflicts) and pushed — the branch is now up to date.


view run

@MelvinBot

Copy link
Copy Markdown
Contributor Author

⚠️ MelvinBot CI Fix Loop Detected

MelvinBot has made 6 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.

@huult

huult commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

@WojtekBoman Updated based on your suggestion and re-tested it. Everything is working well. Could you review it again? Thanks!

// resetRoot is only needed to MOUNT the onboarding navigator. The merge below appends routes by
// top-level name, so once it is mounted the merged route list cannot change - but resetRoot({stale: true})
// would still re-emit the state and fire history.replaceState, and a burst of those trips Safari's
// 100-per-10s cap (APP-HT5). Unlike the old payload this no longer re-asserts adaptedState's index.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot Could you remove this comment?

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.

Removed the comment above the ONBOARDING_MODAL_NAVIGATOR guard in OnboardingFlow.ts.


view run

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.

Already handled — this comment was removed in commit e6f8686, now on the branch. Nothing further needed here.


view run

const rootStateRouteNamesSet = new Set(rootState.routes.map((route) => route.name));

// resetRoot instead of navigate/replace because only replacing the whole root state can mount the target
// screen on top of the earlier onboarding steps that getAdaptedStateFromPath rebuilds, keeping Back working.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

@MelvinBot Could you remove this comment?

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.

Removed the comment above the resetRoot call in OnboardingFlow.ts.


view run

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.

Already handled — this comment was removed in commit e6f8686, now on the branch. Nothing further needed here.


view run

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

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

@huult

huult commented Aug 27, 2026

Copy link
Copy Markdown
Contributor

@mountiny all yours

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

Thanks

@mountiny
mountiny merged commit e48ecec into main Aug 30, 2026
48 of 52 checks passed
@mountiny
mountiny deleted the claude-onboardingResetRootIdempotencyGuard branch August 30, 2026 19:20
@github-actions

Copy link
Copy Markdown
Contributor

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

@OSBotify

Copy link
Copy Markdown
Contributor

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

@OSBotify OSBotify mentioned this pull request Aug 31, 2026
75 tasks done
@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/mountiny in version: 9.4.65-0 🚀

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

@MelvinBot

Copy link
Copy Markdown
Contributor Author

No help site changes are required. I did not create a docs PR.

This PR changes only internal navigation plumbing. It adds an idempotency guard so startOnboardingFlow skips a no-op resetRoot when the Onboarding modal navigator is already mounted, which stops the history.replaceState burst on Mobile Safari.

Nothing user-facing changed:

  • No new or renamed onboarding screens, tabs, settings, or buttons.
  • No change to the order or content of the onboarding steps a user sees.
  • The only observable difference is the absence of a SecurityError in the console.

The two files touched are src/libs/actions/Welcome/OnboardingFlow.ts and tests/unit/OnboardingFlowTest.ts — one behavior guard plus its unit tests.

I also checked App/docs/articles for pages that describe the onboarding flow. The articles that mention onboarding cover what a user is asked (workspace setup, purpose selection, Home overview), not how the router mounts those screens. None of them state anything this PR makes inaccurate.

@huult, there is no linked help site PR to review, since no article needs updating. Please confirm you agree that this change is not user-facing. If you think a specific article does need an update, tell me which one and I'll open the draft PR.


view run

@OSBotify

OSBotify commented Sep 2, 2026

Copy link
Copy Markdown
Contributor

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