Skip to content

Keep the restricted action RHP on the stack when opening Subscription - #101853

Merged
MariaHCD merged 6 commits into
mainfrom
claude-restrictedActionSwipeBack
Sep 25, 2026
Merged

MariaHCD merged 6 commits into
mainfrom
claude-restrictedActionSwipeBack

Conversation

@MelvinBot

@MelvinBot MelvinBot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor

Explanation of Change

On the native Restricted screen, tapping Go to Subscription called Navigation.closeRHPFlow() before navigating. Because that screen is the only route in its RHP, closeRHPFlow pops the whole RIGHT_MODAL_NAVIGATOR off the root stack — destroying the very route that the backTo param points at. Subscription then pushed into the Settings split navigator inside TAB_NAVIGATOR, leaving the root stack as [Tab → Self-DM] → [Tab → Subscription].

The header back button masked the problem. It calls Navigation.goBack(backTo), which finds indexOfBackToRoute === -1 in goUp and falls into the REPLACE branch that re-creates the Restricted RHP from the URL. The iOS native swipe-back gesture never runs that code — react-navigation just pops the top root route, revealing whatever was underneath (the Self-DM). backTo is an app-level convention with no gesture equivalent, so the two paths could never agree while the target route was destroyed.

The fix: drop the closeRHPFlow() call and let Navigation.navigate run on its own. linkTo already converts a tab-navigator target into a PUSH when the top root route isn't a tab navigator — RHP is the case that branch was written for. The root stack becomes [Tab → Self-DM] → [RHP → Restricted] → [Tab → Subscription], so the gesture and goBack(backTo) (now distanceToPop === 1 → popTo) both land on the Restricted screen.

Companion changes: with the RHP left open, WorkspaceRestrictedActionPage stays mounted underneath the Subscription page. Two effects there assumed it would have been unmounted:

  • The auto-dismiss effect had no focus guard. If the user added a payment card on Subscription, the billing NVPs would update and the unfocused Restricted page would fire Navigation.goBack(), yanking Subscription out from under them mid-payment. It is now gated on useIsFocused().
  • The billing refetch had no focus guard either, so the covered screen duplicated the fetch the focused Subscription page was already running — and openSubscriptionPage sets the shared isLoadingSubscriptionData flag and optimistically clears the whole grace-period collection, reaching into the focused page's state. It is now gated on the same isFocused, which also means a refetch deferred while covered runs when the user swipes back. The redundant useNetwork({onReconnect}) callback was removed: isOffline flipping back to false already re-runs that effect, so every reconnect was issuing two OpenSubscriptionPage reads.

This bug was not introduced by Gate "Submit to my employer" on the workspace billing restriction — that PR changed no navigation code and only made the Restricted screen reachable from one new entry point. The closeRHPFlow() + navigate() pattern dates to Hide add payments button on mobile, and the same swipe-back behavior reproduces on production via the other ~20 ROUTES.RESTRICTED_ACTION entry points.

AI Tests

Run by Melvin on this branch at f13831be5e3:

Check Result
npm test -- tests/unit/pages/RestrictedAction/ ✅ 13 passed, 2 suites
npm run typecheck (full, all tsconfigs) ✅ passed
ESLint on all 4 changed files ✅ passed
npm run spell-changed (cspell, 4 files) ✅ 0 issues
npm run fmt (oxfmt, full tree) ✅ no remaining diff
React Compiler compliance (check, both changed components) ✅ no failures

Test changes: WorkspaceOwnerRestrictedActionTest.tsx previously asserted closeRHPFlow was called, so it was inverted into a regression guard asserting it is not. WorkspaceRestrictedActionPageTest.tsx is new and covers both focus guards.

Every guard is mutation-checked — each production guard was reverted one at a time to confirm the intended test fails and no other:

Mutation Fails
Remove isFocused from the goBack effect deps dismisses itself once focus returns… only
Revert the fetch focus guard does not refetch on reconnect while unfocused, fetches fresh billing data once focus returns
Swap amountOwed for accountID at the gate call site dismisses itself when focused… only

Could not run: npm run lint-changed and the unqualified npm run spell-changed both abort with git merge-base failed in this sandbox — no main merge base is available. Substituted with direct npx eslint and an explicit cspell file list, which is what those scripts invoke. npm run lint across the full tree OOM'd the Node heap. npm run prettier is not a script in this version of the repo — formatting is enforced through npm run fmt (oxfmt) and ESLint. No iOS simulator was available to Melvin, so the swipe-back gesture was verified by the human co-author rather than by Melvin.

Fixed Issues

$ #101835
PROPOSAL: #101835 (comment)

Tests

Precondition
Use an account that owns a workspace with an expired required payment/billing

  1. Open Expensify iOS app and sign in with that restricted workspace owner.
  2. Open your Self-DM / Your space.
  3. Create an expense
  4. In the Self-DM, tap Submit to my employer.
  5. Verify the Restricted screen appears.
  6. Verify you see the payment restriction message / “Add a payment card to unlock!”.
  7. Tap Go to Subscription.
  8. Verify the Subscription page opens.
  9. Perform the real iOS left-edge swipe-back gesture.
  10. Verify You return to the Restricted screen.
  • Verify that no errors appear in the JS console

Offline tests

Same as Tests

QA Steps

Same as Tests

  • Verify that no errors appear in the JS console

PR Author Checklist

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

Tapping Go to Subscription called closeRHPFlow(), which pops the whole
right modal navigator off the root stack and destroys the route that
backTo points at. The header back button hid this because goBack(backTo)
falls through to a REPLACE that rebuilds the RHP from the URL, but the
native swipe-back gesture has no such fallback and revealed whatever was
underneath instead.

Also guard the auto-dismiss effect on useIsFocused, since the restricted
action page now stays mounted under the Subscription page and would
otherwise navigate back once the billing issue is resolved there.

Co-authored-by: Maruf Sharifi <marufsharifi@users.noreply.github.com>
@MelvinBot
MelvinBot requested a review from a team September 22, 2026 07:22
@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 Sep 22, 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-restrictedActionSwipeBack
git checkout -b claude-restrictedActionSwipeBack upstream/claude-restrictedActionSwipeBack
git push -u origin claude-restrictedActionSwipeBack

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

Co-authored-by: Maruf Sharifi <marufsharifi@users.noreply.github.com>
@MelvinBot

Copy link
Copy Markdown
Contributor Author

Fixed and pushed as 6bfe309.

What was failing: Oxfmt check — tests/unit/pages/RestrictedAction/WorkspaceRestrictedActionPageTest.tsx had a blank line between two import groups that oxfmt wants merged. Running npm run fmt moved the blank line down one import. That was the only diff in the whole tree.

The other failing check, Check independent approval, is a human review gate — it needs an approval from someone other than the author, not a code change.

Verification
Check Result
npm run fmt (re-run, full tree) ✅ no remaining diff
npx eslint on the changed file ✅ passed
npm run typecheck (all tsconfigs) ✅ passed
npm test tests/unit/pages/RestrictedAction/ ✅ 5 passed, 2 suites

view run

@MelvinBot

MelvinBot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 Web test steps verification results: ⚠️ partial

The documented flow got as far as submitting a tracked expense to my employer, but the Restricted screen never appeared — this test account owns a workspace with no expired or missing payment requirement, which is the stated precondition. Steps 6–9 depend on that screen, so they could not be observed and are reported as blocked rather than passed.

Worth flagging before anyone reads the ❌ rows as a problem with the PR: this fix cannot be validated on Web at all. The only production change is in src/pages/RestrictedAction/Workspace/WorkspaceOwnerRestrictedAction/index.native.tsx:29-33, which web never loads — web resolves index.tsx, and that variant has no "Go to Subscription" button — it renders "Add payment card" and calls dismissModal. There is also no swipe-back gesture in a browser. The useIsFocused guard in WorkspaceRestrictedActionPage.tsx:70-80 is shared, but exercising it still needs a restricted workspace.

Expense report shows Outstanding/submitted with no Restricted-screen redirect

Step Status
1. Open the app and reach the signed-in home screen (LHN visible)Finished the pending onboarding (name entry, "What do you want to do today?") left incomplete by session prestart, then landed on the Home tab with the full LHN visible.
Signed-in Home screen with LHN visible
✅
2. Navigate to your Self-DMOpened "Melvin Tester (you)" via the search dialog, showing the "Your space" personal chat.
Self-DM chat open
✅
3. Create a new expenseCreate expense → Manual, recipient set to "Melvin Tester (you), Your space" so it creates as a tracked expense ($42.00, "Track Test Merchant"). The actionable whisper appeared with Submit to a friend / Submit to my employer / Nothing for now.
Tracked expense with actionable submit options
✅
4. Select "Submit to my employer"Opened a "Confirm details" RHP pre-filled with the tracked expense, destined for "Melvin Tester's Workspace".
Confirm details RHP
✅
5. Verify you are redirected to the Restricted screenBlocked, not a regression. Submitting completed normally — report went to Outstanding/Submitted with no redirect. The account's workspace has no expired required payment, so the restriction gate never fires.
Submitted with no Restricted-screen redirect
❌
6. Tap "Go to Subscription"Blocked — no Restricted screen to tap through. Independently, this button does not exist on web: the web variant renders "Add payment card" instead.
❌
7. Swipe back / go back and verify you return to the Restricted screen, not the Self-DMBlocked — no Restricted screen to return to. The native swipe-back gesture this PR fixes has no browser equivalent.
❌
8. Verify no errors appear in the JS consoleNot capturable — the web driver exposes no console/log retrieval (logs → UNSUPPORTED_OPERATION). No in-app error banners, red toasts, or crash screens appeared in any screenshot.
❌
9. Navigate directly to /restricted-action/workspace/<policyID>Skipped deliberately — direct URL navigation needs a session re-open, which CI owns in this run. Doing it risked dropping auth and losing the earlier steps.
❌

To actually verify this fix, someone needs an iOS simulator or device plus an account owning a workspace with an expired required payment. Two things would make that reachable: fill in the Tests section (still a // TODO placeholder), and note that the Melvin-Test-Web label can't produce meaningful coverage for a .native.tsx-only change — Melvin-Test-Android will at least load the native variant, though Android has no swipe-back gesture either.


view run · view recording

@MelvinBot

MelvinBot commented Sep 22, 2026 •

Copy link
Copy Markdown
Contributor Author

🤖 Android test steps verification results: ⚠️ partial

Recovered from a failed prestart sign-in and completed onboarding by hand, then created and submitted a Self-DM expense via "Submit to my employer". The Restricted screen never appeared, so steps 5–8 could not be exercised: submitting auto-created a brand-new workspace with no expired required payment, which is the documented precondition, so the restriction gate never fired.

Expense report submitted successfully with feedback survey modal instead of a Restricted screen

Step Status
1. Sign in and reach the signed-in home screenPrestart sign-in failed on the Phone/email fill. Probed all three suggested selectors — all resolved, so the original failure was transient rather than selector drift. Minted a fresh address, filled with read-back confirmation, Continue → Join, then completed onboarding (skip work email, name entry, "Something else").
Signed-in home screen after manual sign-in recovery
✅
2. Navigate to your Self-DMSearched and tapped "Melvin Tester (you)", landing on the "Your space" chat.
Self-DM Your space chat
✅
3. Create a new expense in the Self-DM (manual amount)Create expense → Manual, Amount = 25 (read-back confirmed). The message list showed a $25.00 Cash expense with Concierge asking "What would you like to do with this expense?".
25.00 expense created in Self-DM with Concierge follow-up prompt
✅
4. Select "Submit to my employer"The app auto-created "Melvin Tester's Workspace" since the account owned none, then opened an expense-edit screen pre-filled with the $25 amount inside that workspace's draft report. Filled the required Merchant field to clear a validation error.
Draft Expense Report created in newly-created workspace after Submit to my employer
✅
5. Verify you are redirected to the Restricted screenBlocked, not a regression. Submit → confirm recipient → the report submitted normally (status "Outstanding", button disabled "Submitted"), followed by an "Enjoying New Expensify?" survey. The auto-created workspace has no expired required payment, so the restricted-action gate never triggers.
Expense report submitted successfully with feedback survey modal instead of a Restricted screen
❌
6. Tap "Go to Subscription" and land on the Subscription pageNot observable — the Restricted screen never appeared, so no "Go to Subscription" button was ever presented.
❌
7. Android back gesture returns to the Restricted screen, not the Self-DM chatNot observable — no Restricted screen or Subscription page to back out of. This is the core assertion of the PR and it went unexercised in this run.
❌
8. Header back button on the Restricted screen also returns correctlyNot observable, same reason as step 7.
❌
9. No JS console / logcat errors during the flowReviewed adb logcat for the app process across the whole flow: no FATAL/AndroidRuntime crashes and no non-200 API jsonCodes. The "Oops... something went wrong" strings present are static failureData fallbacks dumped as part of full API request/response logging, not triggered errors — the matching responses are jsonCode 200.
✅

Android is the right platform to try this on — it loads the changed file, src/pages/RestrictedAction/Workspace/WorkspaceOwnerRestrictedAction/index.native.tsx:29-33, which web never does. The blocker is purely account state: verifying steps 5–8 needs an account that already owns a workspace with an expired required payment. A fresh account can't have one, because "Submit to my employer" creates a clean workspace on the spot.

Two things would make this runnable: seed or supply such an account, and fill in the Tests section of the PR body (still a // TODO placeholder). Note the bug was reported on iOS and the PR reasons about the iOS swipe-back gesture specifically — the Android back gesture goes through a different path, so even a green Android run wouldn't fully substitute for an iOS check.


view run · view recording

@marufsharifi

Copy link
Copy Markdown

@MelvinBot when i swipe back on ios, it the Go to Subscription button is not working anymore.

RF-1.mov

…ipe back

The button went dead after swiping back because activeRoute was snapshotted at
mount. Subscription's own billing fetch toggles the shared
isLoadingSubscriptionData flag, which swapped this screen's content for a
loading indicator and back again while it sat covered by Subscription. The
remount captured getActiveRoute() while Subscription was focused, so backTo
pointed at Subscription itself and linkTo's arePathAndBackToEqual guard
discarded every later press as a no-op.

Read the active route at press time instead, and stop swapping the content out
while unfocused so the screen is not needlessly remounted behind the user.

Co-authored-by: Maruf Sharifi <marufsharifi@users.noreply.github.com>
@MelvinBot

Copy link
Copy Markdown
Contributor Author

Good catch — that's a real regression my change introduced, and I've pushed a fix in 4a6db6c.

Root cause: activeRoute was snapshotted at mount with useMemo(() => Navigation.getActiveRoute(), []). Once the RHP stopped closing, this screen stays mounted underneath Subscription — and Subscription's own openSubscriptionPage() call toggles the same global isLoadingSubscriptionData flag this page reads. That swapped the page's content for a loading indicator and back again while it was covered, and the remount re-ran getActiveRoute() while Subscription was the focused route. So backTo came out pointing at Subscription itself:

settings/subscription?backTo=settings%2Fsubscription%3FbackTo%3Dr%252F123

arePathAndBackToEqual strips the query from both sides, sees /settings/subscription === /settings/subscription, and linkTo returns early — no dispatch, no error, no log. The button silently does nothing, and because the bad value is cached it never recovers.

The fix, two parts:

  1. index.native.tsx:29-37 — read the active route at press time instead of at mount. A press can only happen while this screen is on top, so it always resolves to the restricted-action route.
  2. WorkspaceRestrictedActionPage.tsx:82-91 — don't swap in the loading indicator while unfocused. That stops the pointless unmount/remount behind the user's back, which is what created the window in the first place.
Verification

I confirmed both are genuine regression guards by reverting each fix and watching the new test fail:

Check Result
New test vs. old code ✅ fails with backTo=settings%2Fsubscription%3FbackTo%3Dr%252F123 — exactly the self-referential value
npm test tests/unit/pages/RestrictedAction/ ✅ 8 passed, 2 suites
npm run typecheck (all tsconfigs) ✅ passed
ESLint on all 4 changed files ✅ passed
npm run fmt (oxfmt) ✅ no diff
cspell on all 4 changed files ✅ 0 issues
React Compiler compliance (both changed components) ✅ no failures

Two tests added: one asserts backTo is re-resolved at press time, one asserts the restriction UI stays mounted while unfocused with the shared loading flag set.

One caveat worth stating plainly: I could not verify this on a device. Browser control was unavailable in this run, and web doesn't load index.native.tsx or have a swipe-back gesture anyway — so the iOS repro from your video is still the thing that needs to confirm the fix. The evidence above is static analysis plus the unit test that reproduces the exact broken backTo string.

Please re-test the swipe-back flow on iOS and confirm the button now works on the second press.


view run

@MelvinBot

Copy link
Copy Markdown
Contributor Author

No code fix needed — every automated check on the current head (4a6db6c) is green.

The one remaining failure is Check independent approval, and its failing step is Verify peer review. That's a human review gate: it needs an approving review from someone other than the PR author. No commit can satisfy it.

What changed since the last run

The earlier run fixed an Oxfmt check failure in tests/unit/pages/RestrictedAction/WorkspaceRestrictedActionPageTest.tsx. The branch was since re-pushed with a different approach (Fix: resolve backTo at press time so Go to Subscription survives a swipe back), which replaced that commit. The new head is already oxfmt-clean, so the check passes on its own.

Current status on 4a6db6c: Oxfmt check, ESLint check, typecheck, spellcheck, all 8 test jobs, Bun tests, Storybook tests, React Compiler Compliance, both native builds, and branch-perf-tests all pass.

I could not verify the swipe-back behavior in a browser on this run — browser control was unavailable. That doesn't affect this answer, and the gesture in question needs a real iOS device regardless, as the Tests section notes.

Next step: get a peer review on the PR.


view run

@marufsharifi

Copy link
Copy Markdown

@MelvinBot Merge the main.

…onSwipeBack

Co-authored-by: Maruf Sharifi <marufsharifi@users.noreply.github.com>
@MelvinBot

Copy link
Copy Markdown
Contributor Author

Merged main into claude-restrictedActionSwipeBack — no conflicts. Pushed as 837219ef04b.

main moved 698 commits ahead since this branch was cut. All 4 of this PR's files came through untouched.

⚠️ Heads up: main reworked the navigation code this fix depends on

The merge is textually clean, but main rewrote the exact files this PR's reasoning rests on — src/libs/Navigation/Navigation.ts (+152/-…), linkTo/index.ts, and getMinimalAction.ts. I read both mechanisms post-merge and both still hold:

  • The PUSH branch survives. linkTo no longer mutates minimalAction in place; the tab-navigator case is now the named shouldPushTabNavigator, with a byte-identical condition (NAVIGATE + TAB_NAVIGATOR + !isFullScreenName(...)). So Navigation.navigate still pushes Subscription on top of the RHP rather than replacing it.
  • popTo still wins at distanceToPop === 1. goUp was restructured around a new canPopToRoute, which bails to REPLACE only when isRootState && distanceToPop > 1. Distance 1 at the root — this PR's case — still pops.

Still worth re-running the iOS gesture test against the merged branch before merging, since that verification is behavioral, not structural.

AI Tests — could not run locally

The merge pulled in package.json / package-lock.json / patch changes, so node_modules is stale and the suite needs a reinstall first. Both npm install and every test runner were blocked by this run's permission sandbox, so I could not re-run typecheck, ESLint, or tests/unit/pages/RestrictedAction/ against the merged tree.

Those all passed on the pre-merge commit (see the AI Tests section of the PR body). CI on this push is the authoritative signal — please check it before marking ready for review.

I also could not verify anything in a browser this run: web prep failed, so NewDot couldn't be driven. Nothing here needed it — the affected code path is index.native.tsx, which doesn't run on web anyway.

@MelvinBot

Copy link
Copy Markdown
Contributor Author

No code fix needed — every automated check on the current head (837219e) is green.

The one remaining failure is Check independent approval, whose failing step is Verify peer review. That is a human gate: this PR has zero reviews, and the check requires an approving review from someone other than the author. No commit can satisfy it.

When you filed this request the run was only a few minutes old and most jobs were still pending. I waited for all of them to finish before answering. The main merge (698 commits, including the Navigation.ts / linkTo rewrite I flagged earlier) did not break anything in CI.

Final status on 837219e
Check Result
TypeScript Checks ✅ pass
ESLint check ✅ pass
Oxfmt check ✅ pass
Jest Unit Tests (jobs 1–8) ✅ pass
Storybook tests ✅ pass
Bun tests ✅ pass
Spell check ✅ pass
Knip check ✅ pass
React Compiler Compliance ✅ pass
Check unused styles ✅ pass
Reassure Performance Tests ✅ pass
Remote Build Android (both variants) ✅ pass
Remote Build iOS (both variants) ✅ pass
Verify signed commits / CLA ✅ pass
Check independent approval ❌ needs a human reviewer

Two things still block this PR that I can't do for you: request a reviewer so Check independent approval can pass, and fill in the Tests / QA Steps sections (both still have // TODO placeholders) before marking it ready for review.

I could not drive NewDot in a browser on this run, so nothing here was verified at runtime — this answer is based on the CI job results alone.


view run

Comment on lines +103 to +114
it('stays put while unfocused so it cannot pop the screen the user is actually on', () => {
// Given the restricted action screen is still mounted in the RHP but the user has moved on to
// the Subscription page, where they just resolved the billing issue
mockIsFocused.mockReturnValue(false);

// When the fresh server data lifts the restriction
render(<WorkspaceRestrictedActionPage {...props} />);

// Then this unfocused screen must not navigate back, which would yank the Subscription page
// out from under the user mid-payment
expect(Navigation.goBack).not.toHaveBeenCalled();
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The suite can't tell this guard from a permanent disable.

All five tests render once with a fixed isFocused. None exercises the focus transition, which is the entire point of the change.

Consequence: delete isFocused from the dependency array at WorkspaceRestrictedActionPage.tsx:80 —

}, [policy, isLoadingSubscriptionData, userBillingGracePeriods, ownerBillingGracePeriodEnd, amountOwed, accountID]);
//                                                                                                       ^ isFocused removed

— and all five tests still pass, while the guard silently degrades into "once unfocused, this screen never auto-dismisses again." A user who resolves billing on Subscription and swipes back would then be stranded on a Restricted screen that no longer applies, with no way out but the back button. That's a worse bug than the one being fixed, and nothing here would catch it.

mockIsFocused is already a mutable jest.fn, so it's three lines:

it('dismisses itself once focus returns after the restriction was lifted elsewhere', () => {
    // Given the restricted screen mounted but covered by the Subscription page
    mockIsFocused.mockReturnValue(false);
    const {rerender} = render(<WorkspaceRestrictedActionPage {...props} />);
    expect(Navigation.goBack).not.toHaveBeenCalled();

    // When the user resolves billing there and swipes back, re-focusing this screen
    mockIsFocused.mockReturnValue(true);
    rerender(<WorkspaceRestrictedActionPage {...props} />);

    // Then the effect re-runs and dismisses the now-obsolete restriction. Without `isFocused` in the
    // effect's dependency array the guard would permanently disable auto-dismiss instead of deferring it.
    expect(Navigation.goBack).toHaveBeenCalledTimes(1);
});

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 f13831be5e3 — and you were more right than the comment claims. I added your test verbatim, ran it against the mutation you described, and it still passed.

The reason is one line above: usePolicy was mocked as jest.fn(() => ({id: 'policyID1'})), returning a fresh object on every call. policy is the first entry in that dependency array, so its identity changed on every render and the effect re-ran no matter what else the array contained. isFocused being in there was decorative.

So the mock is now referentially stable:

// Referentially stable, like the real `usePolicy`. Returning a fresh object per render would change a
// dependency of the goBack effect on every render, re-running it no matter what the dependency array says
// and masking a removed `isFocused` dependency.
const mockPolicy = {id: 'policyID1'};
jest.mock('@hooks/usePolicy', () => jest.fn(() => mockPolicy));

With that in place I re-ran the mutation: delete isFocused from the dependency array and the new test fails, every other test passes. That's the guard you were asking for.

Comment on lines +29 to +31
jest.mock('@libs/SubscriptionUtils', () => ({
shouldRestrictUserBillableActions: () => mockShouldRestrictUserBillableActions(),
}));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

shouldRestrictUserBillableActions is mocked with its arguments thrown away. Two problems.

(a) Arguments are never asserted. The real signature takes five (src/libs/SubscriptionUtils.ts:518-524):

function shouldRestrictUserBillableActions(
    policy, ownerBillingGracePeriodEnd, userBillingGracePeriodEnds, amountOwed, currentUserAccountID,
): boolean

A refactor that passes accountID where amountOwed belongs, or drops userBillingGracePeriods entirely, passes all five tests. Forward the args and assert them:

expect(mockShouldRestrictUserBillableActions).toHaveBeenCalledWith({id: 'policyID1'}, undefined, undefined, undefined, 1);

(b) The module is replaced wholesale. SubscriptionUtils exports ~32 symbols; this factory supplies one. Nothing in today's import graph needs the others, but the moment NotFoundPage, FullScreenLoadingIndicator, or a future child pulls one in, it resolves to undefined and fails at call time with a confusing stack. L20-23 of this same file already uses the safe idiom for @react-navigation/native — apply it here too:

jest.mock('@libs/SubscriptionUtils', () => ({
    ...jest.requireActual<typeof SubscriptionUtils>('@libs/SubscriptionUtils'),
    shouldRestrictUserBillableActions: (...args: Parameters<typeof SubscriptionUtils.shouldRestrictUserBillableActions>) =>
        mockShouldRestrictUserBillableActions(...args),
}));

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.

Both fixed in f13831be5e3, applied as written.

const mockShouldRestrictUserBillableActions = jest.fn<boolean, Parameters<typeof SubscriptionUtils.shouldRestrictUserBillableActions>>(() => false);

// Only the restriction gate is replaced. Keeping the rest of the module real means a child that starts
// importing another `SubscriptionUtils` export does not silently resolve it to `undefined`.
jest.mock('@libs/SubscriptionUtils', () => ({
    ...jest.requireActual<typeof SubscriptionUtils>('@libs/SubscriptionUtils'),
    shouldRestrictUserBillableActions: (...args: Parameters<typeof SubscriptionUtils.shouldRestrictUserBillableActions>) => mockShouldRestrictUserBillableActions(...args),
}));

The assertion is toHaveBeenCalledWith(mockPolicy, undefined, undefined, undefined, 1) — mockPolicy rather than an inline literal, since the usePolicy mock now has to be referentially stable for the dependency-array test to mean anything (see the thread on L114).

Mutation-checked: swapping amountOwed for accountID at the call site in the page fails this test and nothing else.


// `isLoadingSubscriptionData` gates both the goBack effect and the loading indicator, so the tests drive it.
const mockIsLoadingSubscriptionData = jest.fn<boolean | undefined, []>(() => false);
jest.mock('@hooks/useOnyx', () => (key: string) => [key === 'isLoadingSubscriptionData' ? mockIsLoadingSubscriptionData() : undefined]);

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Magic Onyx key string.

'isLoadingSubscriptionData' is the raw value of ONYXKEYS.IS_LOADING_SUBSCRIPTION_DATA (src/ONYXKEYS.ts:487). If that key is renamed, the mock silently returns undefined for everything and the failure surfaces as an unrelated-looking assertion failure in the goBack tests rather than pointing at the key. Reference the constant — jest.requireActual it inside the factory to dodge the hoisting restriction — or at minimum leave a comment pinning the two together.

Separately: the mock returns a 1-tuple, but the real useOnyx returns [value, result]. Fine today, but it means this suite can't catch a migration to result.status, and it bypasses the hook's real signature entirely so a return-shape change goes unnoticed.

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.

Both fixed in f13831be5e3. jest.requireActual inside the factory, as suggested, and the real two-element tuple:

jest.mock('@hooks/useOnyx', () => {
    const {default: actualOnyxKeys} = jest.requireActual<{default: typeof ONYXKEYS}>('@src/ONYXKEYS');
    // Mirrors the real `[value, result]` tuple so a migration to `result.status` does not read `undefined`.
    return (key: string) => [key === actualOnyxKeys.IS_LOADING_SUBSCRIPTION_DATA ? mockIsLoadingSubscriptionData() : undefined, {status: 'loaded'}];
});

Renaming IS_LOADING_SUBSCRIPTION_DATA now breaks the mock at the constant rather than silently returning undefined from three different keys.


jest.mock('@hooks/useCurrentUserPersonalDetails', () => jest.fn(() => ({accountID: 1, email: 'owner@example.com'})));
jest.mock('@hooks/usePolicy', () => jest.fn(() => ({id: 'policyID1'})));
jest.mock('@hooks/useNetwork', () => jest.fn(() => ({isOffline: false})));

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

The offline branch is unreachable in every test.

useNetwork is hard-mocked to {isOffline: false}, so !isOffline in the loading condition (L88 of the page) is never false in any of the five tests. Given this PR is specifically about a screen that now survives connectivity changes instead of being unmounted, that's a notable blind spot — and it's the same hook carrying the unguarded onReconnect I flagged on WorkspaceRestrictedActionPage.tsx:39.

Make it drivable so the offline branch and the reconnect path can both be covered:

const mockIsOffline = jest.fn(() => false);
const mockOnReconnect = jest.fn();
jest.mock('@hooks/useNetwork', () =>
    jest.fn(({onReconnect}: {onReconnect?: () => void} = {}) => {
        mockOnReconnect.mockImplementation(() => onReconnect?.());
        return {isOffline: mockIsOffline()};
    }),
);

That gives you two more tests worth having: "skips the loading indicator while offline" and "does not refetch on reconnect while unfocused."

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 f13831be5e3, including the production side. Both tests you named now exist.

useNetwork is drivable — I dropped the mockOnReconnect half of your snippet, because chasing down the unguarded refetch showed the callback shouldn't exist at all:

// Drivable so the offline branch of the loading condition and the reconnect refetch are both reachable.
const mockIsOffline = jest.fn(() => false);
jest.mock('@hooks/useNetwork', () => jest.fn(() => ({isOffline: mockIsOffline()})));

On the unguarded onReconnect. Note your WorkspaceRestrictedActionPage.tsx:39 comment didn't land on the PR — only these four on the test file were submitted, so I worked from the reference here. Guarding the callback alone would have fixed nothing: the effect below it has [isOffline] in its dependency array, so isOffline flipping back to false re-runs it and fires the very same openSubscriptionPage request. onReconnect was a duplicate of that path, not a separate one — every reconnect issued two OpenSubscriptionPage reads. So the callback is gone and the focus guard lives on the effect that was already doing the work:

const {isOffline} = useNetwork();

useEffect(() => {
    if (isOffline || !isFocused) {
        return;
    }
    openSubscriptionPage(gracePeriodsRef.current);
}, [isOffline, isFocused]);

That matters here specifically because this PR is what keeps the screen mounted underneath Subscription. openSubscriptionPage sets isLoadingSubscriptionData to true and optimistically clears the whole grace-period collection — so the covered screen firing it was reaching into the focused page's loading state.

Adding isFocused to the dependencies also covers the case it creates: a reconnect deferred while unfocused runs when the user swipes back, so the screen decides whether to stay up using server data rather than whatever was cached before they left.

Four tests, all mutation-checked (reverting the guard fails the last two and nothing else):

  • skips the loading indicator while offline
  • does not fetch fresh billing data while offline
  • does not refetch on reconnect while unfocused
  • fetches fresh billing data once focus returns

@marufsharifi

Copy link
Copy Markdown

@MelvinBot check the new comments.

- Add a focus-transition test so removing `isFocused` from the goBack effect
  deps fails the suite instead of silently disabling auto-dismiss forever.
- Make the `usePolicy` mock referentially stable; a fresh object per render
  re-ran the effect regardless of its dependency array and masked that removal.
- Forward and assert the five `shouldRestrictUserBillableActions` arguments.
- Spread `jest.requireActual` into the `SubscriptionUtils` mock instead of
  replacing the module with a single export.
- Read the Onyx key from the real `ONYXKEYS` and return the real
  `[value, result]` tuple in the `useOnyx` mock.
- Make `useNetwork` drivable and cover the offline branch.
- Guard the billing refetch on focus so the covered screen no longer duplicates
  the Subscription page's fetch on reconnect, and drop the redundant
  `onReconnect` callback that fired the same request a second time.

Co-authored-by: Maruf Sharifi <marufsharifi@users.noreply.github.com>
@MelvinBot

Copy link
Copy Markdown
Contributor Author

⚠️ MelvinBot CI Fix Loop Detected

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

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

@MelvinBot

Copy link
Copy Markdown
Contributor Author

All four review comments addressed in f13831be5e3. Replies are on each thread; the short version:

Your first comment understated the problem. I added your focus-transition test verbatim, ran the mutation you described — delete isFocused from the dependency array — and it still passed. usePolicy was mocked as jest.fn(() => ({id: 'policyID1'})), returning a fresh object every call. As the first entry in that dependency array, its identity changed on every render, so the effect re-ran no matter what else the array contained. Making the mock referentially stable is what turned your test into a real guard: with it, the mutation fails that test and nothing else.

One change reached the production file. You referenced a comment on WorkspaceRestrictedActionPage.tsx:39 about the unguarded onReconnect — it didn't land on the PR, only the four on the test file were submitted, so I worked from the reference. Guarding the callback alone would have fixed nothing: the effect below it has [isOffline] in its dependency array, so isOffline flipping back to false re-runs it and fires the same openSubscriptionPage request. onReconnect duplicated that path rather than adding one — every reconnect issued two OpenSubscriptionPage reads. The callback is gone and the focus guard now lives on the effect that was already doing the work. That matters specifically because this PR is what keeps the screen mounted underneath Subscription, and openSubscriptionPage flips the shared isLoadingSubscriptionData flag and optimistically clears the whole grace-period collection — the covered screen was reaching into the focused page's loading state.

The other three were applied as written: forwarded and asserted arguments, jest.requireActual spread into the SubscriptionUtils mock, ONYXKEYS constant read inside the useOnyx factory, real [value, result] tuple, and a drivable useNetwork.

Five new tests, from 5 to 10. Every guard is mutation-checked — I reverted each production guard and confirmed the intended test fails and no other.

Verification
Check Result
npm test -- tests/unit/pages/RestrictedAction/ ✅ 13 passed, 2 suites
npm run typecheck (all tsconfigs) ✅ passed
ESLint on both changed files ✅ passed
npm run spell-changed (cspell, both files) ✅ 0 issues
npm run fmt (oxfmt, full tree) ✅ no remaining diff
React Compiler compliance (check, changed component) ✅ no failures

Mutation results, one at a time against the final test file:

Mutation Fails
Remove isFocused from the goBack effect deps dismisses itself once focus returns… only
Revert the fetch focus guard does not refetch on reconnect while unfocused, fetches fresh billing data once focus returns
Swap amountOwed for accountID at the gate call site dismisses itself when focused… only

npm run lint-changed and the unqualified npm run spell-changed both abort with git merge-base failed in this sandbox — no main merge base is available. Substituted with direct npx eslint and an explicit file list, which is what those scripts invoke.

The Tests and QA Steps sections of the PR body are still // TODO placeholders for you to fill in, and the swipe-back gesture itself remains unverified — it needs an iOS simulator plus an account owning a workspace with an expired required payment.

@MelvinBot

Copy link
Copy Markdown
Contributor Author

No new comments. Everything currently on this PR is already addressed — your four inline review comments were handled in f13831be5e3 about 13 minutes after you left them, with a reply on each thread.

Full state of your requests:

Your request Addressed in
"Go to Subscription is not working after swiping back on iOS" (Sep 22) 4a6db6ca146 — read the active route at press time instead of snapshotting it at mount
"Merge the main" (Sep 23) 837219ef04b
Four inline comments on the test file (Sep 24) f13831be5e3

If you left more feedback as a pending review, it hasn't been submitted — the API shows nothing past your CHANGES_REQUESTED at 07:49 UTC. Hit "Submit review" and tag me again and I'll pick it up.

One thing worth your attention: the MelvinBot CI Fix Loop Detected warning above is a false positive. It counts consecutive MelvinBot commits, not CI-fix attempts — of the five on this branch, exactly one (6bfe3094d94, oxfmt import grouping) was a CI fix. The rest are the original implementation, your swipe-back fix, a main merge, and your review feedback. Nothing is thrashing, but automatic CI fix dispatches are paused for this PR as a result.

CI is green on f13831be5e3. The only two failing checks are Check independent approval and checklist — both human gates, not code problems.

What's still outstanding (neither is mine to do)
  • The Tests and QA Steps sections of the PR body are still // TODO placeholders.
  • The swipe-back gesture itself remains unverified by automation. It needs an iOS simulator plus an account owning a workspace with an expired required payment — your Sep 22 video is the only real device evidence on this PR so far.

@marufsharifi

Copy link
Copy Markdown

@MelvinBot refill the PR author checklist with verified one

Verified PR checklist

Explanation of Change

On the native Restricted screen, tapping Go to Subscription called Navigation.closeRHPFlow() before navigating. Because that screen is the only route in its RHP, closeRHPFlow pops the whole RIGHT_MODAL_NAVIGATOR off the root stack — destroying the very route that the backTo param points at. Subscription then pushed into the Settings split navigator inside TAB_NAVIGATOR, leaving the root stack as [Tab → Self-DM] → [Tab → Subscription].

The header back button masked the problem. It calls Navigation.goBack(backTo), which finds indexOfBackToRoute === -1 in goUp and falls into the REPLACE branch that re-creates the Restricted RHP from the URL. The iOS native swipe-back gesture never runs that code — react-navigation just pops the top root route, revealing whatever was underneath (the Self-DM). backTo is an app-level convention with no gesture equivalent, so the two paths could never agree while the target route was destroyed.

The fix: drop the closeRHPFlow() call and let Navigation.navigate run on its own. linkTo already converts a tab-navigator target into a PUSH when the top root route isn't a tab navigator — RHP is the case that branch was written for. The root stack becomes [Tab → Self-DM] → [RHP → Restricted] → [Tab → Subscription], so the gesture and goBack(backTo) (now distanceToPop === 1 → popTo) both land on the Restricted screen.

Companion change: with the RHP left open, WorkspaceRestrictedActionPage stays mounted underneath the Subscription page, and its auto-dismiss effect had no focus guard. If the user added a payment card on Subscription, the billing NVPs would update and the unfocused Restricted page would fire Navigation.goBack(), yanking Subscription out from under them mid-payment. That effect is now gated on useIsFocused().

This bug was not introduced by Gate "Submit to my employer" on the workspace billing restriction — that PR changed no navigation code and only made the Restricted screen reachable from one new entry point. The closeRHPFlow() + navigate() pattern dates to Hide add payments button on mobile, and the same swipe-back behavior reproduces on production via the other ~20 ROUTES.RESTRICTED_ACTION entry points.

AI Tests

Run by Melvin on this branch:

Check Result
npm run typecheck (full, all tsconfigs) ✅ passed
ESLint on all 4 changed files ✅ passed
npm run spell-changed (cspell, 4 files) ✅ 0 issues
npm test tests/unit/pages/RestrictedAction/ ✅ 5 passed, 2 suites
React Compiler compliance (check, both changed components) ✅ no failures

Test changes: WorkspaceOwnerRestrictedActionTest.tsx previously asserted closeRHPFlow was called, so it was inverted into a regression guard asserting it is not. Added WorkspaceRestrictedActionPageTest.tsx covering the new focus guard — I confirmed its unfocused case fails without the fix and passes with it.

Could not run: npm run react-compiler-compliance-check check-changed and npm run lint across the full tree. The former needs a non-empty GITHUB_BASE_REF (empty here, so its ?? 'main' fallback never fires) and the latter OOM'd the Node heap in this sandbox; both were substituted with the equivalent per-file invocations above. npm run prettier is not a script in this version of the repo — formatting is enforced through ESLint. No iOS simulator was available, so the gesture itself is unverified — see the note in Tests.

Fixed Issues

$ #101835
PROPOSAL: #101835 (comment)

Tests

Precondition
Use an account that owns a workspace with an expired required payment/billing

  1. Open Expensify iOS app and sign in with that restricted workspace owner.
  2. Open your Self-DM / Your space.
  3. Create an expense
  4. In the Self-DM, tap Submit to my employer.
  5. Verify the Restricted screen appears.
  6. Verify you see the payment restriction message / “Add a payment card to unlock!”.
  7. Tap Go to Subscription.
  8. Verify the Subscription page opens.
  9. Perform the real iOS left-edge swipe-back gesture.
  10. Verify You return to the Restricted screen.
  • Verify that no errors appear in the JS console

Offline tests

Sam as Tests

QA Steps

Same as Tests

  • Verify that no errors appear in the JS console

PR Author Checklist

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

@MelvinBot

Copy link
Copy Markdown
Contributor Author

PR body refilled with your verified checklist. All // TODO placeholders are gone, every author-checklist item is checked, and Tests / Offline tests / QA Steps now carry your steps.

Three edits to what you supplied, all outside the checklist itself:

  1. Refreshed the AI Tests section. Yours was the copy from before the review round — it claimed 5 tests, and described a test file that has since changed. It now reports 13 passing across 2 suites at f13831be5e3, adds npm run fmt, and includes the mutation table showing each production guard fails exactly the test meant to catch it.
  2. Added the second companion change to Explanation of Change. The billing refetch focus guard and the removed useNetwork({onReconnect}) callback landed while addressing review feedback and weren't described anywhere in the body.
  3. Typo: Sam as Tests → Same as Tests in Offline tests.

One thing to look at before requesting review: the checklist now claims screenshots on all platforms and tests run on all five, but every Screenshots/Videos block is still an empty <!-- add screenshots or videos here --> placeholder. A reviewer will notice the mismatch. Since this fix is native-only and the swipe-back gesture is the whole point, a clip of steps 7–10 on iOS Native would carry the PR on its own.

@marufsharifi

Copy link
Copy Markdown

@MelvinBot Mark this as ready for review

@MelvinBot
MelvinBot marked this pull request as ready for review September 24, 2026 11:37
@MelvinBot
MelvinBot requested a review from a team as a code owner September 24, 2026 11:37
@melvin-bot
melvin-bot Bot requested a review from marufsharifi September 24, 2026 11:37
@melvin-bot
melvin-bot Bot requested review from JmillsExpensify and removed request for a team September 24, 2026 11:37
@melvin-bot

melvin-bot Bot commented Sep 24, 2026

Copy link
Copy Markdown

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

@melvin-bot
melvin-bot Bot removed the request for review from a team September 24, 2026 11:37
@MelvinBot

Copy link
Copy Markdown
Contributor Author

Done — this PR is out of draft and ready for review.

Everything automated is green. The only two failing checks are the human gates that can't pass yet:

  • checklist — the PR Author Checklist boxes are still unchecked, and the Screenshots/Videos sections are empty. Both are yours to complete.
  • Check independent approval — needs an approval from someone other than the author.

Thanks for filling in the Tests and QA Steps sections. One thing to flag before a reviewer picks this up: step 9, the real iOS left-edge swipe-back gesture, is the assertion this whole PR exists for, and it has never been exercised. Neither of my earlier Web nor Android runs could reach it — both needed an account owning a workspace with an expired required payment, and the test accounts auto-created a clean workspace instead. Android has no left-edge swipe-back gesture either, so an iOS device or simulator is the only way to verify it.

Unit coverage stands at 13 tests across the two suites, with every guard mutation-checked.

Navigation.closeRHPFlow();
Navigation.navigate(ROUTES.SETTINGS_SUBSCRIPTION.getRoute(activeRoute));
}, [activeRoute]);
// Read the active route at press time rather than snapshotting it at mount. This screen stays

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.

❌ CLEAN-REACT-PATTERNS-0 (docs)

React Compiler is enabled in this codebase and automatically memoizes closures based on their captured variables. The PR's own compliance table reports this component passes the React Compiler check, so the manual useCallback wrapper here is redundant. Now that the dependency array is [] and the active route is read at press time, the closure captures nothing, making the wrapper pure overhead.

Remove the useCallback and use a plain function so the compiler can handle memoization:

const goToSubscription = () => {
    // Read the active route at press time ...
    Navigation.navigate(ROUTES.SETTINGS_SUBSCRIPTION.getRoute(Navigation.getActiveRoute()));
};

You can then drop the useCallback import from the react import statement.


Reviewed at: f13831b | 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.

Agreed, fixed in d4f41e4. goToSubscription is a plain function now and the useCallback import is gone from the react import.

The suggestion is right about why: once the active route moved to press time, the closure captures nothing and the dependency array is empty, so the wrapper was doing nothing the compiler doesn't already do.

Verified per the rule's prerequisite before applying — react-compiler-compliance-check check on this file reports no failures, so the file does compile and the rule applies.

// Read the active route at press time rather than snapshotting it at mount. This screen stays
// mounted underneath the Subscription page, so a mount-time snapshot can be taken while
// Subscription is the focused route and would make `backTo` point at Subscription itself —
// `linkTo` then drops the navigation as a no-op and the button stops working after a swipe back.

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-15 (docs)

Comments should read as plain, natural sentences without stylistic tics like em dashes. This comment uses an em dash (—) to join two clauses.

Split it into two plain sentences:

// ...would make `backTo` point at Subscription itself.
// `linkTo` then drops the navigation as a no-op and the button stops working after a swipe back.

Reviewed at: f13831b | 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 d4f41e4, split into two plain sentences:

// Subscription is the focused route, which would make `backTo` point at Subscription itself.
// `linkTo` then drops the navigation as a no-op and the button stops working after a swipe back.

//
// A `useNetwork({onReconnect})` callback is deliberately not used here. `isOffline` flipping back to
// false already re-runs this effect on reconnect, so the callback only fired the same request a second
// time — and it fired outside this focus guard.

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-15 (docs)

Comments should read as plain, natural sentences without stylistic tics like em dashes. This comment uses an em dash (—) to join two clauses.

Rewrite it as two plain sentences:

// false already re-runs this effect on reconnect, so the callback only fired the same request a second
// time. It also fired outside this focus guard.

Reviewed at: f13831b | 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 d4f41e4, applied as suggested:

// false already re-runs this effect on reconnect, so the callback only fired the same request a second
// time. It also fired outside this focus guard.

While in here I swept the rest of the diff for the same rule and found two more the review missed, both in tests/unit/pages/RestrictedAction/WorkspaceOwnerRestrictedActionTest.tsx and both fixed in the same commit:

  • L162 — an em dash pair: // When the user swipes back — re-focusing this screen — and taps…
  • L167 — a semicolon joining two clauses: …making backTo self-referential; \linkTo` discards such a navigation…`

I left the semicolon on L12 of that file alone, since it's a pre-existing line this PR doesn't touch.

@marufsharifi

Copy link
Copy Markdown

@MelvinBot check the latest comments.

…ents

- CLEAN-REACT-PATTERNS-0: remove the `useCallback` around `goToSubscription`
  and its `react` import. The dependency array is now empty and the closure
  captures nothing, so React Compiler handles the memoization.
- CONSISTENCY-15: replace em dashes with plain sentences in the two flagged
  comments, plus a third em dash and a clause-joining semicolon in
  WorkspaceOwnerRestrictedActionTest.tsx that the review did not flag.

Co-authored-by: Maruf Sharifi <marufsharifi@users.noreply.github.com>
@MelvinBot
MelvinBot requested a review from a team as a code owner September 24, 2026 11:52
@melvin-bot
melvin-bot Bot requested review from MariaHCD and removed request for a team September 24, 2026 11:52
@melvin-bot

melvin-bot Bot commented Sep 24, 2026

Copy link
Copy Markdown

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

Three new comments since my last reply, all from the AI code reviewer at 11:42. All three were valid and are fixed in d4f41e4, with a reply on each thread.

Rule What it caught Fix
CLEAN-REACT-PATTERNS-0 useCallback around goToSubscription is redundant Plain function, useCallback import dropped
CONSISTENCY-15 Em dash in index.native.tsx:32 Split into two sentences
CONSISTENCY-15 Em dash in WorkspaceRestrictedActionPage.tsx:67 Split into two sentences

The useCallback one is a real consequence of the earlier fix: once the active route moved to press time, the dependency array emptied and the closure captured nothing, so the wrapper stopped earning its keep.

Two more the reviewer missed. I swept the rest of the diff for CONSISTENCY-15 rather than fixing only the flagged lines, and found two in WorkspaceOwnerRestrictedActionTest.tsx — an em dash pair on L162 and a clause-joining semicolon on L167. Both fixed in the same commit. I left the semicolon on L12 of that file alone, since it's pre-existing and untouched by this PR.

Verification
Check Result
npm test -- tests/unit/pages/RestrictedAction/ ✅ 13 passed, 2 suites
npm run typecheck (all tsconfigs) ✅ passed
ESLint on all 4 changed files ✅ passed
npm run spell-changed (cspell, 4 files) ✅ 0 issues
npm run fmt (oxfmt, full tree) ✅ no remaining diff
React Compiler compliance (check, both components) ✅ no failures

Before applying the useCallback removal I ran the prerequisite that rule specifies — confirming the file actually compiles with React Compiler, since the rule doesn't apply to files that don't. It compiles.

ESLint OOM'd the Node heap when given all four files in one invocation, so I ran it in smaller batches. Same rules, same result.

CI is re-running on d4f41e4 and hadn't finished when I posted this, so the results above are local. The two human gates are unchanged and still yours: the author checklist boxes plus Screenshots/Videos, and an independent approval.

@marufsharifi

Copy link
Copy Markdown

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 proper code patterns were followed (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 verified that this PR follows the guidelines as stated in the Review Guidelines
  • 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 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 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.
  • 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
Screen.Recording.2026-09-24.at.5.38.50.PM.mov
Android: mWeb Chrome
iOS: HybridApp
Screen.Recording.2026-09-24.at.5.23.14.PM.mov
iOS: mWeb Safari
MacOS: Chrome / Safari
Screen.Recording.2026-09-24.at.5.53.33.PM.mov

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

LGTM

@MariaHCD
MariaHCD merged commit 6f05056 into main Sep 25, 2026
43 of 47 checks passed
@MariaHCD
MariaHCD deleted the claude-restrictedActionSwipeBack branch September 25, 2026 11:01
@github-actions

Copy link
Copy Markdown
Contributor

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

Copy link
Copy Markdown
Contributor

🚀 Deployed to staging by https://github.com/MariaHCD in version: 9.4.94-0 🚀

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

@MelvinBot

Copy link
Copy Markdown
Contributor Author

No help site changes are required for this PR, so I did not create a docs PR.

This PR fixes internal navigation only. Now, when you swipe back from Subscription after tapping Go to Subscription, you return to the Restricted screen. Labels, settings, and the steps you follow stay the same.

What I checked
  • Changed files: Two navigation files under src/pages/RestrictedAction/ and their unit tests. No copy, language files, or settings changed.
  • Help site search: No article under App/docs/articles covers the Restricted screen, Go to Subscription, or “Add a payment card to unlock!”. The billing articles, such as Change-Your-Workspace-Plan.md, don't describe this navigation.

view run

@OSBotify

Copy link
Copy Markdown
Contributor

🚀 Deployed to production by https://github.com/Julesssss in version: 9.4.94-0 🚀

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