[$175] PDF download modal stays open after signing out from another tab/device
If you haven’t already, check out our contributing guidelines for onboarding. To join our Slack channel, fill out this form.
Version Number: 9.5.39-0 Reproducible in staging?: Y Reproducible in production?: Y If this was caught during regression testing, add the test name, ID and link from BrowserStack: Email or phone of affected tester (no customers): Logs: https://stackoverflow.com/c/expensify/questions/4856 Expensify/Expensify Issue URL: Issue reported by: @jjcoffee Slack conversation (hyperlinked to channel name): #Expensify Bugs
Action Performed:
- Open any expense.
- Go to More > Download report.
- Leave the modal open and open a new tab or a device where you're signed in to the same account.
- Go to Profile > Sign Out.
- Go back to the first tab/device.
Expected Result:
The sign in screen should display normally without any modal.
Actual Result:
The download PDF modal shows overlayed on the sign in screen.
Workaround:
Unknown
Platforms:
Select the officially supported platforms where the issue was reproduced:
- [ ] Android: App
- [ ] Android: mWeb Chrome
- [ ] iOS: App
- [ ] iOS: mWeb Safari
- [ ] iOS: mWeb Chrome
- [x] Windows: Chrome
- [x] MacOS: Chrome / Safari
Screenshots/Videos
https://github.com/user-attachments/assets/852cdd57-77a4-436e-b9fa-346f77346ad9
https://github.com/user-attachments/assets/0a1ae075-8cc4-468c-8b5e-c7f13b506fd9
Upwork Automation - Do Not Edit
- Upwork Job URL: https://www.upwork.com/jobs/~022121238479866359028
- Upwork Job ID: 2121238479866359028
- Last Price Increase: 2026-11-13
Issue Owner
Current Issue Owner: @carlosmiceli
Triggered auto assignment to Contributor-plus team member for initial proposal review - @mkhutornyi (External)
Job added to Upwork: https://www.upwork.com/jobs/~022121238479866359028
Proposal
Confidence: Medium. Code explains the reported behavior, but browser reproduction was blocked by tester restrictions.
What is the root cause of that problem?
The PDF dialog belongs to a global modal provider that remains mounted after logout. Losing the session switches navigation to the sign-in screen, but does not clear the provider’s modal stack or the dialog’s visibility state.
Consequently, the existing dialog remains above sign-in. Clearing its PDF data can change it back to “generating” rather than dismissing it.
Code evidence and alternatives checked
- Download report opens the dialog separately from the export request: useExportActions.ts:285–300.
- The modal provider wraps authenticated navigation: App.tsx:104–141.
- Its stack has no session-loss cleanup: ModalContext.tsx:53–172.
- Visibility remains local state until explicitly dismissed: FileDownloadModalWrapper.tsx:20–61.
- Missing PDF data selects the generating state, not dismissal: ReportPDFDownloadModal.tsx:22–79.
A late PDF response is not necessary to explain this: the dialog never closes on session loss. Ordinary screen-unmount survival is intentional and already tested in useReportPDFDownloadModalTest.tsx:239–260.
What changes do you think we should make in order to solve the problem?
Add session-loss cleanup to the global modal provider:
- On an authenticated → unauthenticated transition, dismiss outgoing-session modals and settle their pending promises.
- Preserve ordinary report navigation, token refresh, and modals opened on public screens.
- Use a teardown result distinct from user cancellation. In particular,
CLOSEtriggers report retraction in the shared Submit-via-PDF flow;DISMISSavoids that branch: SubmitPrimaryAction.tsx:199–209.
Add regression coverage for session loss during generating, ready, and failed states; stacked modals; promise settlement; and unaffected public-screen modals.
Browser verification limitation
🤖 Web test steps verification results: ❌ fail
The tester could not execute this workflow because cross-tab control is unsupported and sign-out is prohibited by its session rules. The issue was neither reproduced nor disproved.
| Step | Status |
|---|---|
Open an expenseNot attempted because the complete workflow was unsupported. |
❌ |
More → Download reportNot attempted. |
❌ |
Open another signed-in tabBlocked: cross-tab control is unsupported. |
❌ |
Sign out in the second tabBlocked by tester session rules. |
❌ |
Return and inspect sign-inBlocked by preceding steps; no screenshots captured. |
❌ |
Next Steps for Contributor+ team:
To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/106852) to create a draft PR.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.
Proposal
What is the root cause of that problem?
- Root-Level Placement of
ModalProvider(src/App.tsx:131):ModalProvideris positioned at the top-level provider tree inApp.tsx(wrappingExpensifyand the entire navigation hierarchy). It manages its modal queue via internal state:const [modalStack, setModalStack] = useState<{modals: ModalInfo[]}>({modals: []}); const modalPromisesStack = useRef<Record<string, CloseModalPromiseWithResolvers>>({}); - Absence of Session Lifecycle Awareness in
ModalProvider(src/components/Modal/Global/ModalContext.tsx:53–175): When the user signs out on another tab or device, cross-tab Onyx synchronization clearsONYXKEYS.SESSION. InExpensify.tsx,useIsAuthenticated()detects thatauthTokenis absent and switches the navigation tree fromAuthScreenstoPublicScreens(displaying the sign-in screen). However,ModalProviderhas no subscription or listener for authentication state changes. As a result, itsmodalStackstate remains populated with{component: ReportPDFDownloadModal, ...}, and it continues to renderModalComponenton top of the newly displayed public Sign-In screen. - Promise Settlement & Retraction Safeguard:
When an authenticated session is terminated, outgoing modals cannot merely be dropped; their pending promises in
modalPromisesStackmust be settled cleanly. Critically, resolving withModalActions.CLOSEwould cause side effects in shared workflows such asSubmitPrimaryAction.tsx:199–209, whereaction === ModalActions.CLOSEis interpreted as user cancellation during file generation and triggersretractReport(...). The session-loss cleanup must settle promises withModalActions.DISMISSto cleanly dismiss outgoing modals without triggering business logic rollbacks.
What changes do you think we should make in order to solve the problem?
1. Subscribe ModalProvider to Auth Lifecycle & Dismiss Outgoing Modals (src/components/Modal/Global/ModalContext.tsx)
In ModalProvider, subscribe to authentication state using useIsAuthenticated() and track the previous state with usePrevious:
import useIsAuthenticated from '@hooks/useIsAuthenticated';
import usePrevious from '@hooks/usePrevious';
// Inside ModalProvider:
const isAuthenticated = useIsAuthenticated();
const prevIsAuthenticated = usePrevious(isAuthenticated);
useEffect(() => {
// Only trigger when transitioning from authenticated -> unauthenticated
if (!prevIsAuthenticated || isAuthenticated) {
return;
}
setModalStack((prevState) => {
for (const modal of prevState.modals) {
const modalPromise = modalPromisesStack.current?.[modal.id];
if (modalPromise) {
modalPromise.resolve({action: ModalActions.DISMISS});
delete modalPromisesStack.current[modal.id];
}
}
return {modals: []};
});
}, [isAuthenticated, prevIsAuthenticated]);
2. Expose dismissAllModals via ModalContext (src/components/Modal/Global/ModalContext.tsx)
Add dismissAllModals to ModalContextType and the provider's exported context value so that programmatic sign-out flows (or tests) can also explicitly clear all active modals when tearing down a session:
const dismissAllModals = () => {
setModalStack((prevState) => {
for (const modal of prevState.modals) {
const modalPromise = modalPromisesStack.current?.[modal.id];
if (modalPromise) {
modalPromise.resolve({action: ModalActions.DISMISS});
delete modalPromisesStack.current[modal.id];
}
}
return {modals: []};
});
};
Why this is architecturally superior:
- Centralized & Universal: It fixes the issue not only for
ReportPDFDownloadModal, but for all global modals rendered viaModalProvider(ExpensifyCardStatementPDFDownloadModal,useConfirmModal,useDecisionModal,useHoldMenuModal, etc.), guaranteeing no authenticated modal ever leaks onto the sign-in screen. - Safe Promise Settlement: Resolving with
ModalActions.DISMISSensures that submit-via-PDF (SubmitPrimaryAction.tsx:202) does NOT inadvertently retract submitted reports, and confirmation dialogs do not execute destructive actions. - Zero Impact on Public Modals: The transition guard
!prevIsAuthenticated || isAuthenticatedensures that unauthenticated startup or modals opened on public screens are unaffected.
What alternative solutions did you explore? (Optional)
- Handling cleanup locally inside
ReportPDFDownloadModal.tsx: Subscribing tosessioninsideReportPDFDownloadModaland callingcloseModal()when!session?.authTokenwould fix this single modal, but leaves all other global modals (ExpensifyCardStatementPDFDownloadModal,useConfirmModal,useDecisionModal, etc.) broken if a user signs out while they are displayed. Handling this at theModalProviderlevel provides complete, system-wide protection. - Settling promises with
ModalActions.CLOSE: InSubmitPrimaryAction.tsx,openPDFDownload().then((result) => { if (result?.action !== ModalActions.CLOSE) return; retractReport(...); }). UsingCLOSEupon sign-out would trigger report retraction for an expense the user already submitted. UsingModalActions.DISMISScleanly avoids this bug.
What automated tests can you add to prevent this from re-occurring?
- In
tests/unit/hooks/useReportPDFDownloadModalTest.tsx: Add a test case verifying that whenReportPDFDownloadModalis open andONYXKEYS.SESSIONis cleared (authToken: null), the modal is dismissed and unmounts, and the promise resolves with{action: ModalActions.DISMISS}. - In
tests/unit/ModalContextTest.tsx: Add tests verifying that:- When
isAuthenticatedtransitions fromtruetofalse, all active modals inmodalStackare cleared and their promises resolve with{action: ModalActions.DISMISS}. - Initial unauthenticated render does not trigger modal clearing.
- When
Contributor details
Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
Please re-state the problem that we are trying to solve in this issue.
When a user opens the PDF download modal (implemented by ReportPDFDownloadModal → FileDownloadModalWrapper → FileDownloadModal) and then signs out from another tab or device, the modal remains visible on the original tab, overlaying the sign‑in screen.
What is the root cause of that problem?
The modal stack is independent of the authentication state. ReportPDFDownloadModal subscribes to the session via useOnyx(ONYXKEYS.SESSION), but it never reacts to the session being cleared. Consequently, when the user signs out, the modal stays in the global modal queue and continues to render on top of the new public screens.
What changes do you think we should make in order to solve the problem?
Add a side‑effect in src/components/ReportPDFDownloadModal.tsx that watches the session value. When the session becomes falsy (i.e., the user is signed out), invoke the closeModal callback to dismiss the modal immediately.
// src/components/ReportPDFDownloadModal.tsx
import React, {useEffect} from 'react'; // <-- add useEffect import
...
function ReportPDFDownloadModal({reportID, closeModal, resolveModal}: ReportPDFDownloadModalProps) {
const [session] = useOnyx(ONYXKEYS.SESSION);
...
// Existing logic
// New effect: close modal on sign‑out
useEffect(() => {
if (!session?.encryptedAuthToken) {
// Session cleared – dismiss the modal
closeModal({action: 'CLOSE'});
}
}, [session, closeModal]);
return (
<FileDownloadModalWrapper
closeModal={closeModal}
resolveModal={resolveModal}
...
/>
);
}
- The
closeModalprop is already typed asModalProps['closeModal']and expects an object with anactionfield, matching the existing usage inFileDownloadModalWrapper. - By reacting to the session change, the modal is removed from the global stack before the sign‑in screen is rendered, preventing the overlay.
What alternative solutions did you explore?
- Modify the global
ModalProviderto listen forONYXKEYS.SESSIONchanges and clear its stack on sign‑out. This would affect all modals but requires changes to a file not included in the provided snippets, making it harder to reference accurately. - Add a cleanup in
FileDownloadModalWrapperthat checks the session and callscloseModal. This approach duplicates the session logic across wrappers and is less centralized than handling it at the source modal (ReportPDFDownloadModal). - Force a full navigation reset on sign‑out which would unmount the modal tree. This is already happening for the main app navigation, but the modal provider lives above that tree, so the modal persists.
The chosen solution directly addresses the modal that is open (the PDF download modal) with minimal impact and stays within the files we can reference.
Contributor details
- Your Expensify account email: [email protected]
Proposal
Please re-state the problem that we are trying to solve in this issue.
When a user opens the report PDF download modal (More > Download PDF or Submit via PDF) on Web/mWeb and signs out of the same account from another tab or device, the main navigation switches back to the Sign-In screen (PublicScreens), but the Download modal remains mounted over the Sign-In UI (reverting to its loading spinner if it had already finished generating) until manually dismissed or refreshed.
What is the root cause of that problem?
ModalProviderlives aboveNavigationRootand has no session-lifecycle cleanup: Insrc/App.tsx:131,ModalProvider(src/components/Modal/Global/ModalContext.tsx:53-175) wraps<Expensify />above<NavigationRoot authenticated={isAuthenticated} />(src/Expensify.tsx:113,314-320).- Cross-tab sign-out clears
ONYXKEYS.SESSIONwithout clearingmodalStack: When another tab/device signs out, cross-tab Onyx sync clearsONYXKEYS.SESSION.NavigationRootunmountsAuthScreensand rendersPublicScreens, unmounting the report screen that calledopenPDFDownload(). However,ReportPDFDownloadModal(src/components/ReportPDFDownloadModal.tsx:26-88) is intentionally hosted inModalProvider'smodalStack.modalsso it can outlive report-screen unmounts during normal navigation. BecauseModalProvidernever clearsmodalStackwhen an authenticated session ends (or switches accounts),ReportPDFDownloadModal—along with any other global modal hosted inModalProvider—stays rendered over Sign-In. Worse, clearing${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID}flipshasFinishedPDFDownloadback tofalse(CONST.FILE_DOWNLOAD_STATUS.GENERATING) and restartsuseStallLogger.
What changes do you think we should make in order to solve the problem?
Clear the global modal stack and settle pending modal promises with {action: ModalActions.DISMISS} whenever an active authenticated session ends or switches to a different account in src/components/Modal/Global/ModalContext.tsx:
-
Add a pure
dismissAllModalshelper inModalProvider(src/components/Modal/Global/ModalContext.tsx):- Read open entries from
modalStackRef.current.modals(instead of mutating refs or resolving promises inside asetModalStackstate updater, which violates React updater purity under<React.StrictMode>insrc/App.tsx:76). - For each open modal, resolve its entry in
modalPromisesStack.currentwith{action: ModalActions.DISMISS}, delete the resolver entry, and callsetModalStack({modals: []}). - Using
ModalActions.DISMISS(rather thanModalActions.CLOSE) ensures callers awaiting the modal promise—such asSubmitPrimaryAction.tsx:201-210, which runsretractReport(...)specifically whenresult?.action === ModalActions.CLOSE—do not fire authenticated report mutations during sign-out.
- Read open entries from
-
Isolate the
ONYXKEYS.SESSIONsubscription in a lightweight child<ModalSessionCleanupWatcher />insideModalProvider(and memoize the context value):- Subscribing to
ONYXKEYS.SESSIONdirectly insideModalProviderwith an inlinevalue={{showModal, closeModal, closeModalByID, resolveModal}}would re-renderModalProviderand everyuseModal()consumer on unrelated session updates (compare#96411noted atModalContext.tsx:58-59). Memoizing the context value (useMemo) and placing the Onyx subscription in a null-rendering child<ModalSessionCleanupWatcher onSessionChange={dismissAllModals} />avoids unnecessary consumer re-renders. - Derive an active authenticated session key from
ONYXKEYS.SESSION(guardingconst [session] = useOnyx(ONYXKEYS.SESSION) ?? []so unit tests that mock@hooks/useOnyxwithout selectors continue to work):function getAuthenticatedSessionKey(session: OnyxEntry<Session>): string | undefined { if (!session?.authToken || session.authTokenType === CONST.AUTH_TOKEN_TYPES.ANONYMOUS) { return undefined; } return session.accountID ? String(session.accountID) : 'authenticated'; } - Track
prevSessionKeyRefinuseEffect: wheneverprevSessionKeyRef.current !== undefined && prevSessionKeyRef.current !== sessionKey, invokeonSessionChange()(dismissAllModals). - This handles:
- Local and cross-tab/remote sign-out (
'12345' -> undefined): dismisses all open global modals immediately. - Direct account switches such as exiting Supportal /
restoreStashedSession('12345' -> '67890', whereBoolean(session?.authToken)staystrue -> true): prevents Account A's modal from leaking into Account B. - In-session
407token refreshes (authTokenrotates whileaccountIDstays'12345'): preserves an in-progress PDF download modal. - Public-screen modals (
undefined -> undefinedorundefined -> '12345'): leaves unauthenticated modals untouched.
- Local and cross-tab/remote sign-out (
- Subscribing to
-
Add unit tests in
tests/unit/ModalContextCloseByIDTest.tsx(orModalContextSessionCleanupTest.tsx) andtests/unit/hooks/useReportPDFDownloadModalTest.tsxcovering:- Opening
ReportPDFDownloadModal, clearingONYXKEYS.SESSION(simulating cross-tab sign-out), and asserting the modal unmounts and its promise resolves with{action: ModalActions.DISMISS}. - Rotating
session.authTokenfor the sameaccountIDand asserting the open modal remains mounted. - Switching
session.accountIDand asserting the previous account's modal is dismissed. - Opening a modal while unauthenticated (
ONYXKEYS.SESSIONempty) and asserting it remains mounted.
- Opening
What alternative solutions did you explore?
- Watching
session?.encryptedAuthTokeninsideReportPDFDownloadModal.tsxand callingcloseModal({action: ModalActions.CLOSE}): Rejected because (a) every other global modal rendered byModalProvider(ExpensifyCardStatementPDFDownloadModal,ConfirmModalWrapper,DecisionModalWrapper,HoldMenuModalWrapper,WiseQuoteConfirmModalWrapper, etc.) would still stay stuck over Sign-In on cross-tab sign-out, (b)ModalActions.CLOSEtriggersretractReportinSubmitPrimaryAction.tsx:201-210, and (c)closeModal()pops the top ofmodalStackrather than targeting a specific modal ID. - Using
registerSessionCleanupCallback(src/libs/SessionCleanup.ts):cleanupSession()runs imperatively inSessionactions, whereasModalProviderowns React component state (modalStack); driving cleanup fromONYXKEYS.SESSIONstate transitions insideModalContext.tsxdirectly covers both local sign-out, cross-tab storage clearance, and Supportal/stashed-session account switches cleanly within React's lifecycle.
Contributor details Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~014898525b9c53fc32
Proposal
Please re-state the problem that we are trying to solve in this issue.
When a user opens the report PDF download modal and signs out of their account from another tab or device, the application transitions to the public Sign-In screen, but the PDF download modal remains mounted on top of the Sign-In UI (reverting to a perpetual loading spinner).
What is the root cause of that problem?
ModalProvidersits above navigation with no session lifecycle awareness (src/App.tsx:130&src/components/Modal/Global/ModalContext.tsx:53-175):ModalProviderwraps<Expensify />inApp.tsx. When cross-tab sign-out clearsONYXKEYS.SESSION,Expensify.tsxswitches navigation fromAuthScreenstoPublicScreens. However,ModalProviderretains its internalmodalStackstate, soReportPDFDownloadModalremains mounted over the Sign-In screen.SubmitPrimaryActionretraction side effect (src/components/MoneyReportHeaderPrimaryAction/SubmitPrimaryAction.tsx:201-209):SubmitPrimaryActionchecksresult?.action !== ModalActions.CLOSEbefore invokingretractReport(...). Outgoing session modals cannot be resolved withModalActions.CLOSE, or legitimate report submissions will be retracted upon sign-out. Modals must be dismissed usingModalActions.DISMISS.- Clearing PDF NVP resets modal to loading spinner (
src/components/ReportPDFDownloadModal.tsx:38-40): WhenONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAMEis wiped on sign-out,hasFinishedPDFDownloadflips fromtruetofalse, resetting the modal to a loading spinner and re-triggeringuseStallLogger.
What changes do you think we should make in order to solve the problem?
-
Implement
dismissAllModalsand session termination watcher insrc/components/Modal/Global/ModalContext.tsx:- Add a pure
dismissAllModalsfunction inModalProvider:- Reads open modals from
modalStackRef.current.modals. - Resolves each modal's pending promise in
modalPromisesStack.currentwith{action: ModalActions.DISMISS}outside of the state updater to preserve React StrictMode updater purity. - Cleans up
modalPromisesStack.currentand callssetModalStack({modals: []}).
- Reads open modals from
- Add a lightweight session listener:
- Subscribes to
ONYXKEYS.SESSION. - Derives the active authenticated session key:
session?.authToken && session.authTokenType !== CONST.AUTH_TOKEN_TYPES.ANONYMOUS ? String(session.accountID ?? 'authenticated') : undefined. - When transitioning from an authenticated session to unauthenticated (
prevSessionKey !== undefined && currentSessionKey === undefined) or when switching accounts (prevSessionKey !== currentSessionKey), callsdismissAllModals(). - Preserves modals opened on public screens (
undefined -> undefined) and in-session token refreshes (accountIDunchanged).
- Subscribes to
- Add a pure
-
Automated tests:
- In
tests/unit/ModalContextTest.tsx: Test that transitioningONYXKEYS.SESSIONfrom authenticated to unauthenticated dismisses all open modals inmodalStackand resolves their promises with{action: ModalActions.DISMISS}. - In
tests/unit/hooks/useReportPDFDownloadModalTest.tsx: Test that clearingONYXKEYS.SESSIONwhileReportPDFDownloadModalis open dismisses the modal cleanly without callingretractReport.
- In
What alternative solutions did you explore? (Optional)
- Adding cleanup logic locally inside
ReportPDFDownloadModal.tsx: Rejected because it only fixes one modal, leaving all other global modals (ExpensifyCardStatementPDFDownloadModal,useConfirmModal,useDecisionModal,useHoldMenuModal, etc.) stuck on the Sign-In screen on sign-out. Centralizing inModalProviderprotects the entire application. - Resolving promises with
ModalActions.CLOSE: Rejected becauseSubmitPrimaryAction.tsxexplicitly checksresult?.action === ModalActions.CLOSEto retract submitted reports, which would inadvertently undo report submissions on sign-out.
✅ Contributor details stored successfully. Thank you for contributing to Expensify!
Proposal
What is the root cause of that problem?
ModalProvider sits above navigation in App.tsx. Signing out changes the authenticated navigator to the sign-in screens, but the provider stays mounted and retains its modal stack. That lifetime lets a PDF download survive ordinary report navigation, but there is no corresponding cleanup when its session ends. See ModalContext.tsx.
Clearing the PDF filename also selects the generating state again, which explains the spinner over sign-in. See ReportPDFDownloadModal.tsx.
What changes do you think we should make in order to solve the problem?
Keep session cleanup inside ModalProvider, with these rules:
- Read the auth token and account ID through existing Onyx selectors and compare their previous values. Clear the stack when authentication ends or a known account changes. Preserve same-account token refresh, initial account-ID hydration, and modals opened while signed out.
- Resolve every pending modal promise with
ModalActions.DISMISS, remove its resolver, then clear the stack. Perform settlement outside the state updater so the updater stays pure. Drain the resolver registry: a descendant effect can open a modal during the logout commit before that entry reaches the rendered stack or its ref. - Make callers treat forced dismissal as no answer.
CLOSEis unsafe here because SubmitPrimaryAction interprets it as cancellation and retracts the submitted report.
DISMISS also needs caller changes. Copilot removal currently treats every non-CLOSE result as confirmation. Expense education uses .finally for follow-up actions, and domain account-closure confirmation retries on every non-confirmation result. Those continuations can remove access, write data, or reopen a modal after logout. Require explicit confirmation for removal, skip expense actions and retries on DISMISS, and retain local resource cleanup. Apply the same guard to import-summary navigation and outgoing account, bank, and workspace error-state writes.
The provider-level approach overlaps the existing proposals. The additional work here is the consumer audit, safe promise settlement during the logout commit, and verified regression coverage. This uses the existing context API and adds no dependency or watcher component.
What alternative solutions did you explore? (Optional)
- Closing only the PDF component leaves other queued global entries behind. Its
closeModalcallback also removes the top entry, which may belong to another modal. - Clearing rendered entries alone can strand a promise opened during the same commit. Removing entries without settling their promises leaves awaiters pending.
- Remounting the provider with an authentication key also remounts its app subtree. The provider can clean up its own stack without that reset.
Verification
The regression fails against the original provider: one modal remains mounted after session loss. With the fix, 113 tests pass across 16 suites. Coverage includes generating, ready, and failed PDFs; stacked promises; the logout commit race; account changes and hydration; token refresh; public modals; reusable IDs; and affected caller behavior.
The accompanying videos show the actual app in two browser tabs with synthetic Onyx data and blocked API requests. 106852-before-fix.webm shows the original provider: ending the fixture session in tab B leaves the generating PDF modal over the public screen in tab A. 106852-after-fix.webm separately labels generating, ready, and failed PDFs; all disappear and resolve as DISMISS. The fixture calls the app's real local sign-out cleanup from tab B; backend authentication and PDF generation are not exercised.
React Compiler compliance, spelling, formatting, and the repository standards review pass. Full lint and typecheck remain failing in this Windows checkout: lint reports existing source violations plus a test-path check that only recognizes /tests/, and TypeScript reports 480 diagnostics outside the changed files. No live-account backend flow or native build was verified.
https://github.com/user-attachments/assets/21baa4b9-99fb-44a6-afbb-de8d56179b5f
https://github.com/user-attachments/assets/36c79303-790e-4478-a465-6cf769aeffd0
Proposal
Please re-state the problem that we are trying to solve in this issue.
When a user opens the PDF download modal (More > Download report / ReportPDFDownloadModal) in one browser tab or device and signs out of the same account from another tab or device, the first tab transitions to the public Sign-In screen while leaving the PDF download modal overlayed on top of the Sign-In screen.
What is the root cause of that problem?
ModalProvidersits above the navigation tree and has no session-loss cleanup (src/App.tsx:130,src/components/Modal/Global/ModalContext.tsx:53-172):ModalProviderwrapsExpensifyat the root ofApp.tsxso global modals likeReportPDFDownloadModalsurvive ordinary report-to-report navigation (tests/unit/hooks/useReportPDFDownloadModalTest.tsx:239-260).- When the user signs out in another tab, cross-tab Onyx storage sync clears
ONYXKEYS.SESSION.Expensify.tsxswitches fromAuthScreenstoPublicScreens, and clearing the cached PDF filename causesReportPDFDownloadModal.tsx:66to fall back to the'generating'spinner state (!pdfFilename), whileModalProviderkeepsmodalStack.modalsmounted above the Sign-In screen.
- Settling outgoing modal promises on logout requires
ModalActions.DISMISS(notModalActions.CLOSE) and must drainmodalPromisesStack:- In
src/components/MoneyReportHeaderPrimaryAction/SubmitPrimaryAction.tsx:199-209,result.action === ModalActions.CLOSEis treated as explicit user cancellation during PDF generation and callsretractReport(...). Resolving outgoing session modals withModalActions.CLOSEon sign-out would inadvertently retract submitted reports. - Similarly, callers that check
action !== ModalActions.CLOSE(such as copilot removal or account-closure retry flows) or.finally(...)continuations must not treat a session-lossModalActions.DISMISSas confirmation.
- In
What changes do you think we should make in order to solve the problem?
- Clear the global modal stack and settle pending promises with
ModalActions.DISMISSon session loss or account change insrc/components/Modal/Global/ModalContext.tsx:- Track
authToken(session?.authToken) andaccountID(session?.accountID) viauseOnyx(ONYXKEYS.SESSION)andusePrevious. - Detect when an authenticated session ends (
Boolean(prevAuthToken) && !authToken) or switches to a different known account (prevAccountID != null && accountID != null && prevAccountID !== accountID), while ignoring same-account token refreshes, initial hydration, and modals opened while already signed out:useEffect(() => { const didSessionEnd = Boolean(prevAuthToken) && !authToken; const didAccountChange = prevAccountID != null && accountID != null && prevAccountID !== accountID; if (!didSessionEnd && !didAccountChange) { return; } const pendingResolvers = Object.values(modalPromisesStack.current); modalPromisesStack.current = {}; setModalStack((prev) => (prev.modals.length > 0 ? {modals: []} : prev)); for (const promise of pendingResolvers) { promise.resolve({action: ModalActions.DISMISS}); } }, [authToken, prevAuthToken, accountID, prevAccountID]); - Settling
pendingResolversoutsidesetModalStackkeeps the state updater pure and ensures any promise registered inmodalPromisesStack.currentduring the same commit is settled and cleared.
- Track
- Ensure callers treat
ModalActions.DISMISSas a no-op teardown:- Audit
showModal/useConfirmModalcallers that branch onaction !== ModalActions.CLOSE(requiringaction === ModalActions.CONFIRMfor destructive confirmations and skipping post-modal mutations whenaction === ModalActions.DISMISS).
- Audit
- Add regression tests in
tests/unit/hooks/useReportPDFDownloadModalTest.tsxandModalContexttests:- Verify that clearing
ONYXKEYS.SESSION(cross-tab sign-out) dismissesReportPDFDownloadModalacross generating, ready, and error states, resolves pendingshowModalpromises with{action: ModalActions.DISMISS}, preserves modals during same-accountauthTokenrefresh, and leaves public-screen modals unaffected.
- Verify that clearing
What alternative solutions did you explore? (Optional)
- Closing only inside
ReportPDFDownloadModal: Discarded because other global modals inModalProviderwould remain mounted over Sign-In, and callingcloseModal()inside a child effect only pops the top modal entry. - Resolving outgoing modals with
ModalActions.CLOSE: Discarded becauseSubmitPrimaryAction.tsx:202treatsModalActions.CLOSEas user cancellation and retracts the submitted report.
@mkhutornyi Eep! 4 days overdue now. Issues have feelings too...
@mkhutornyi 6 days overdue. This is scarier than being forced to listen to Vogon poetry!
Claude posting on behalf of Matt:
@QichenZhu you're now the C+ on this issue. The previous C+ is no longer in the Contributor program. Next step: review the proposals.
Reproduced. Proposals before Help Wanted other than MelvinBot's won't be reviewed.
https://github.com/user-attachments/assets/58568185-a4e6-4b15-a911-6b19f05415be
@MelvinBot your proposal is promising but only partly fixes the issue. I tested it and switching Copilot accounts doesn't clear the modal. Could you update your proposal? Please work independently and don't look at the other proposals in this thread.
Proposal
What is the root cause of that problem?
My previous proposal used the wrong cleanup boundary: losing authentication is not the same as changing accounts.
Copilot switching replaces the active session while keeping the user authenticated. Therefore, an authenticated → unauthenticated check misses the switch, and the persistent global modal provider retains the previous account’s PDF dialog.
Code evidence
- Authentication checks only whether a token exists: useIsAuthenticated.tsx:6–9.
- Copilot entry replaces tokens and clears account data while preserving the session: Delegate.ts:278–319.
- Returning from Copilot restores the original session’s account ID: Delegate.ts:1030–1057.
- The global provider keeps its stack and pending promises independently of navigation: ModalContext.tsx:53–134.
What changes do you think we should make in order to solve the problem?
In the global modal provider, observe both the effective session account ID and authentication state. After establishing the initial loaded-session baseline, clear outgoing-account modals when:
- The effective account ID changes, including entering or leaving Copilot.
- An authenticated session becomes unauthenticated, including logout from another tab.
Remove the entire stack, clear its references and pending-resolver registry, and settle outstanding promises exactly once with DISMISS. Do this outside React state-updater callbacks.
Do not trigger cleanup on raw token changes, ordinary navigation, or initial hydration. Token refresh must leave the modal open.
Settlement safety and regression coverage
CLOSE is inappropriate for session teardown: the Submit-via-PDF flow interprets it as an instruction to retract the report. Use DISMISS instead: SubmitPrimaryAction.tsx:199–213.
Cover logout, Copilot entry and return, stacked dialogs, and PDF generating/ready/error states. Also verify that token refresh, initial loading, ordinary navigation, and public-screen modals remain unaffected.
What alternative solutions did you explore? (Optional)
Closing only in the account-switch button would miss changes received from another tab. Remounting the provider would unnecessarily remount its application subtree and would not, by itself, settle pending promises.
Confidence: Medium. This revision is based on independent code tracing; it has not been browser-verified. I did not read other proposals.
Next Steps for Contributor+ team:
To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/106852) to create a draft PR.
To refine: @MelvinBot <your feedback>
To reject: Explain why you are rejecting Melvin's proposal.
I'm good with MelvinBot's proposal. Its previous proposal already addressed the main issue, and the updated one covers covers switching between Copilot accounts as well.
🎀 👀 🎀 C+ reviewed
Triggered auto assignment to @carlosmiceli, see https://stackoverflow.com/c/expensify/questions/7972 for more details.
@QichenZhu sounds good!