App icon indicating copy to clipboard operation
App copied to clipboard

[$175] PDF download modal stays open after signing out from another tab/device

Open m-natarajan opened this issue 2 weeks ago • 22 comments

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:

  1. Open any expense.
  2. Go to More > Download report.
  3. Leave the modal open and open a new tab or a device where you're signed in to the same account.
  4. Go to Profile > Sign Out.
  5. 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

View all open jobs on GitHub

Upwork Automation - Do Not Edit
Issue OwnerCurrent Issue Owner: @carlosmiceli

m-natarajan avatar Nov 13 '26 13:11 m-natarajan

Triggered auto assignment to Contributor-plus team member for initial proposal review - @mkhutornyi (External)

melvin-bot[bot] avatar Nov 13 '26 13:11 melvin-bot[bot]

Job added to Upwork: https://www.upwork.com/jobs/~022121238479866359028

melvin-bot[bot] avatar Nov 13 '26 13:11 melvin-bot[bot]

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

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, CLOSE triggers report retraction in the shared Submit-via-PDF flow; DISMISS avoids 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.


view run

MelvinBot avatar Nov 13 '26 13:11 MelvinBot

Proposal

What is the root cause of that problem?

  1. Root-Level Placement of ModalProvider (src/App.tsx:131): ModalProvider is positioned at the top-level provider tree in App.tsx (wrapping Expensify and 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>>({});
    
  2. 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 clears ONYXKEYS.SESSION. In Expensify.tsx, useIsAuthenticated() detects that authToken is absent and switches the navigation tree from AuthScreens to PublicScreens (displaying the sign-in screen). However, ModalProvider has no subscription or listener for authentication state changes. As a result, its modalStack state remains populated with {component: ReportPDFDownloadModal, ...}, and it continues to render ModalComponent on top of the newly displayed public Sign-In screen.
  3. Promise Settlement & Retraction Safeguard: When an authenticated session is terminated, outgoing modals cannot merely be dropped; their pending promises in modalPromisesStack must be settled cleanly. Critically, resolving with ModalActions.CLOSE would cause side effects in shared workflows such as SubmitPrimaryAction.tsx:199–209, where action === ModalActions.CLOSE is interpreted as user cancellation during file generation and triggers retractReport(...). The session-loss cleanup must settle promises with ModalActions.DISMISS to 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 via ModalProvider (ExpensifyCardStatementPDFDownloadModal, useConfirmModal, useDecisionModal, useHoldMenuModal, etc.), guaranteeing no authenticated modal ever leaks onto the sign-in screen.
  • Safe Promise Settlement: Resolving with ModalActions.DISMISS ensures 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 || isAuthenticated ensures that unauthenticated startup or modals opened on public screens are unaffected.

What alternative solutions did you explore? (Optional)

  1. Handling cleanup locally inside ReportPDFDownloadModal.tsx: Subscribing to session inside ReportPDFDownloadModal and calling closeModal() when !session?.authToken would 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 the ModalProvider level provides complete, system-wide protection.
  2. Settling promises with ModalActions.CLOSE: In SubmitPrimaryAction.tsx, openPDFDownload().then((result) => { if (result?.action !== ModalActions.CLOSE) return; retractReport(...); }). Using CLOSE upon sign-out would trigger report retraction for an expense the user already submitted. Using ModalActions.DISMISS cleanly avoids this bug.

What automated tests can you add to prevent this from re-occurring?

  1. In tests/unit/hooks/useReportPDFDownloadModalTest.tsx: Add a test case verifying that when ReportPDFDownloadModal is open and ONYXKEYS.SESSION is cleared (authToken: null), the modal is dismissed and unmounts, and the promise resolves with {action: ModalActions.DISMISS}.
  2. In tests/unit/ModalContextTest.tsx: Add tests verifying that:
    • When isAuthenticated transitions from true to false, all active modals in modalStack are cleared and their promises resolve with {action: ModalActions.DISMISS}.
    • Initial unauthenticated render does not trigger modal clearing.

Contributor details

Your Expensify account email: [email protected] Upwork Profile Link: https://www.upwork.com/freelancers/~0131dae36abcf59374

kevinjosh10 avatar Nov 13 '26 13:11 kevinjosh10

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 13 '26 13:11 melvin-bot[bot]

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 closeModal prop is already typed as ModalProps['closeModal'] and expects an object with an action field, matching the existing usage in FileDownloadModalWrapper.
  • 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?

  1. Modify the global ModalProvider to listen for ONYXKEYS.SESSION changes 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.
  2. Add a cleanup in FileDownloadModalWrapper that checks the session and calls closeModal. This approach duplicates the session logic across wrappers and is less centralized than handling it at the source modal (ReportPDFDownloadModal).
  3. 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

almagas avatar Nov 13 '26 14:11 almagas

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?

  1. ModalProvider lives above NavigationRoot and has no session-lifecycle cleanup: In src/App.tsx:131, ModalProvider (src/components/Modal/Global/ModalContext.tsx:53-175) wraps <Expensify /> above <NavigationRoot authenticated={isAuthenticated} /> (src/Expensify.tsx:113,314-320).
  2. Cross-tab sign-out clears ONYXKEYS.SESSION without clearing modalStack: When another tab/device signs out, cross-tab Onyx sync clears ONYXKEYS.SESSION. NavigationRoot unmounts AuthScreens and renders PublicScreens, unmounting the report screen that called openPDFDownload(). However, ReportPDFDownloadModal (src/components/ReportPDFDownloadModal.tsx:26-88) is intentionally hosted in ModalProvider's modalStack.modals so it can outlive report-screen unmounts during normal navigation. Because ModalProvider never clears modalStack when an authenticated session ends (or switches accounts), ReportPDFDownloadModal—along with any other global modal hosted in ModalProvider—stays rendered over Sign-In. Worse, clearing ${ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME}${reportID} flips hasFinishedPDFDownload back to false (CONST.FILE_DOWNLOAD_STATUS.GENERATING) and restarts useStallLogger.

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:

  1. Add a pure dismissAllModals helper in ModalProvider (src/components/Modal/Global/ModalContext.tsx):

    • Read open entries from modalStackRef.current.modals (instead of mutating refs or resolving promises inside a setModalStack state updater, which violates React updater purity under <React.StrictMode> in src/App.tsx:76).
    • For each open modal, resolve its entry in modalPromisesStack.current with {action: ModalActions.DISMISS}, delete the resolver entry, and call setModalStack({modals: []}).
    • Using ModalActions.DISMISS (rather than ModalActions.CLOSE) ensures callers awaiting the modal promise—such as SubmitPrimaryAction.tsx:201-210, which runs retractReport(...) specifically when result?.action === ModalActions.CLOSE—do not fire authenticated report mutations during sign-out.
  2. Isolate the ONYXKEYS.SESSION subscription in a lightweight child <ModalSessionCleanupWatcher /> inside ModalProvider (and memoize the context value):

    • Subscribing to ONYXKEYS.SESSION directly inside ModalProvider with an inline value={{showModal, closeModal, closeModalByID, resolveModal}} would re-render ModalProvider and every useModal() consumer on unrelated session updates (compare #96411 noted at ModalContext.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 (guarding const [session] = useOnyx(ONYXKEYS.SESSION) ?? [] so unit tests that mock @hooks/useOnyx without 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 prevSessionKeyRef in useEffect: whenever prevSessionKeyRef.current !== undefined && prevSessionKeyRef.current !== sessionKey, invoke onSessionChange() (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', where Boolean(session?.authToken) stays true -> true): prevents Account A's modal from leaking into Account B.
      • In-session 407 token refreshes (authToken rotates while accountID stays '12345'): preserves an in-progress PDF download modal.
      • Public-screen modals (undefined -> undefined or undefined -> '12345'): leaves unauthenticated modals untouched.
  3. Add unit tests in tests/unit/ModalContextCloseByIDTest.tsx (or ModalContextSessionCleanupTest.tsx) and tests/unit/hooks/useReportPDFDownloadModalTest.tsx covering:

    • Opening ReportPDFDownloadModal, clearing ONYXKEYS.SESSION (simulating cross-tab sign-out), and asserting the modal unmounts and its promise resolves with {action: ModalActions.DISMISS}.
    • Rotating session.authToken for the same accountID and asserting the open modal remains mounted.
    • Switching session.accountID and asserting the previous account's modal is dismissed.
    • Opening a modal while unauthenticated (ONYXKEYS.SESSION empty) and asserting it remains mounted.

What alternative solutions did you explore?

  1. Watching session?.encryptedAuthToken inside ReportPDFDownloadModal.tsx and calling closeModal({action: ModalActions.CLOSE}): Rejected because (a) every other global modal rendered by ModalProvider (ExpensifyCardStatementPDFDownloadModal, ConfirmModalWrapper, DecisionModalWrapper, HoldMenuModalWrapper, WiseQuoteConfirmModalWrapper, etc.) would still stay stuck over Sign-In on cross-tab sign-out, (b) ModalActions.CLOSE triggers retractReport in SubmitPrimaryAction.tsx:201-210, and (c) closeModal() pops the top of modalStack rather than targeting a specific modal ID.
  2. Using registerSessionCleanupCallback (src/libs/SessionCleanup.ts): cleanupSession() runs imperatively in Session actions, whereas ModalProvider owns React component state (modalStack); driving cleanup from ONYXKEYS.SESSION state transitions inside ModalContext.tsx directly covers both local sign-out, cross-tab storage clearance, and Supportal/stashed-session account switches cleanly within React's lifecycle.

cocvn157 avatar Nov 13 '26 15:11 cocvn157

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?

  1. ModalProvider sits above navigation with no session lifecycle awareness (src/App.tsx:130 & src/components/Modal/Global/ModalContext.tsx:53-175): ModalProvider wraps <Expensify /> in App.tsx. When cross-tab sign-out clears ONYXKEYS.SESSION, Expensify.tsx switches navigation from AuthScreens to PublicScreens. However, ModalProvider retains its internal modalStack state, so ReportPDFDownloadModal remains mounted over the Sign-In screen.
  2. SubmitPrimaryAction retraction side effect (src/components/MoneyReportHeaderPrimaryAction/SubmitPrimaryAction.tsx:201-209): SubmitPrimaryAction checks result?.action !== ModalActions.CLOSE before invoking retractReport(...). Outgoing session modals cannot be resolved with ModalActions.CLOSE, or legitimate report submissions will be retracted upon sign-out. Modals must be dismissed using ModalActions.DISMISS.
  3. Clearing PDF NVP resets modal to loading spinner (src/components/ReportPDFDownloadModal.tsx:38-40): When ONYXKEYS.COLLECTION.NVP_EXPENSIFY_REPORT_PDF_FILENAME is wiped on sign-out, hasFinishedPDFDownload flips from true to false, resetting the modal to a loading spinner and re-triggering useStallLogger.

What changes do you think we should make in order to solve the problem?

  1. Implement dismissAllModals and session termination watcher in src/components/Modal/Global/ModalContext.tsx:

    • Add a pure dismissAllModals function in ModalProvider:
      • Reads open modals from modalStackRef.current.modals.
      • Resolves each modal's pending promise in modalPromisesStack.current with {action: ModalActions.DISMISS} outside of the state updater to preserve React StrictMode updater purity.
      • Cleans up modalPromisesStack.current and calls setModalStack({modals: []}).
    • 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), calls dismissAllModals().
      • Preserves modals opened on public screens (undefined -> undefined) and in-session token refreshes (accountID unchanged).
  2. Automated tests:

    • In tests/unit/ModalContextTest.tsx: Test that transitioning ONYXKEYS.SESSION from authenticated to unauthenticated dismisses all open modals in modalStack and resolves their promises with {action: ModalActions.DISMISS}.
    • In tests/unit/hooks/useReportPDFDownloadModalTest.tsx: Test that clearing ONYXKEYS.SESSION while ReportPDFDownloadModal is open dismisses the modal cleanly without calling retractReport.

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 in ModalProvider protects the entire application.
  • Resolving promises with ModalActions.CLOSE: Rejected because SubmitPrimaryAction.tsx explicitly checks result?.action === ModalActions.CLOSE to retract submitted reports, which would inadvertently undo report submissions on sign-out.

RajGahoi avatar Nov 14 '26 12:11 RajGahoi

✅ Contributor details stored successfully. Thank you for contributing to Expensify!

melvin-bot[bot] avatar Nov 14 '26 12:11 melvin-bot[bot]

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:

  1. 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.
  2. 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.
  3. Make callers treat forced dismissal as no answer. CLOSE is 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 closeModal callback 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

MannA-001 avatar Nov 15 '26 14:11 MannA-001

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?

  1. ModalProvider sits above the navigation tree and has no session-loss cleanup (src/App.tsx:130, src/components/Modal/Global/ModalContext.tsx:53-172):
    • ModalProvider wraps Expensify at the root of App.tsx so global modals like ReportPDFDownloadModal survive 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.tsx switches from AuthScreens to PublicScreens, and clearing the cached PDF filename causes ReportPDFDownloadModal.tsx:66 to fall back to the 'generating' spinner state (!pdfFilename), while ModalProvider keeps modalStack.modals mounted above the Sign-In screen.
  2. Settling outgoing modal promises on logout requires ModalActions.DISMISS (not ModalActions.CLOSE) and must drain modalPromisesStack:
    • In src/components/MoneyReportHeaderPrimaryAction/SubmitPrimaryAction.tsx:199-209, result.action === ModalActions.CLOSE is treated as explicit user cancellation during PDF generation and calls retractReport(...). Resolving outgoing session modals with ModalActions.CLOSE on 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-loss ModalActions.DISMISS as confirmation.

What changes do you think we should make in order to solve the problem?

  1. Clear the global modal stack and settle pending promises with ModalActions.DISMISS on session loss or account change in src/components/Modal/Global/ModalContext.tsx:
    • Track authToken (session?.authToken) and accountID (session?.accountID) via useOnyx(ONYXKEYS.SESSION) and usePrevious.
    • 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 pendingResolvers outside setModalStack keeps the state updater pure and ensures any promise registered in modalPromisesStack.current during the same commit is settled and cleared.
  2. Ensure callers treat ModalActions.DISMISS as a no-op teardown:
    • Audit showModal / useConfirmModal callers that branch on action !== ModalActions.CLOSE (requiring action === ModalActions.CONFIRM for destructive confirmations and skipping post-modal mutations when action === ModalActions.DISMISS).
  3. Add regression tests in tests/unit/hooks/useReportPDFDownloadModalTest.tsx and ModalContext tests:
    • Verify that clearing ONYXKEYS.SESSION (cross-tab sign-out) dismisses ReportPDFDownloadModal across generating, ready, and error states, resolves pending showModal promises with {action: ModalActions.DISMISS}, preserves modals during same-account authToken refresh, and leaves public-screen modals unaffected.

What alternative solutions did you explore? (Optional)

  • Closing only inside ReportPDFDownloadModal: Discarded because other global modals in ModalProvider would remain mounted over Sign-In, and calling closeModal() inside a child effect only pops the top modal entry.
  • Resolving outgoing modals with ModalActions.CLOSE: Discarded because SubmitPrimaryAction.tsx:202 treats ModalActions.CLOSE as user cancellation and retracts the submitted report.

U-ITACHII avatar Nov 15 '26 22:11 U-ITACHII

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

mallenexpensify avatar Nov 23 '26 22:11 mallenexpensify

Reproduced. Proposals before Help Wanted other than MelvinBot's won't be reviewed.

https://github.com/user-attachments/assets/58568185-a4e6-4b15-a911-6b19f05415be

QichenZhu avatar Nov 23 '26 22:11 QichenZhu

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

QichenZhu avatar Nov 23 '26 23:11 QichenZhu

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

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.


view run

MelvinBot avatar Nov 23 '26 23:11 MelvinBot

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

QichenZhu avatar Nov 24 '26 00:11 QichenZhu

Triggered auto assignment to @carlosmiceli, see https://stackoverflow.com/c/expensify/questions/7972 for more details.

@QichenZhu sounds good!

carlosmiceli avatar Nov 24 '26 00:11 carlosmiceli