Skip to content

[Due for payment 2026-08-07] [$250] Invoice - Infinite loading when creating invoice offline then viewing it online #96925

Closed

Description

@applause-bot

If you haven’t already, check out our contributing guidelines for onboarding and email contributors@expensify.com to request to join our Slack channel!


Version Number: 9.4.44-0
Reproducible in staging?: Yes
Reproducible in production?: Yes
If this was caught during regression testing, add the test name, ID and link from BrowserStack: https://test-management.browserstack.com/projects/2219752/test-runs/66080909/folder/13176671/41237472/1597946639
Email or phone of affected tester (no customers): emady.syed1234+invoice@gmail.com
Issue reported by: Applause Internal Team
Bug source: Regression TC Execution
Device used: Windows 10 / Chrome
App Component: Other

Action Performed:

  1. Open staging.new.expensify
  2. Go offline
  3. Click on FAB > Invoice
  4. Create an invoice with valid user ( user is not a part of WS ) and enter invalid website address in company address (www.none.com).
  5. Go online
  6. Click on Invoice created on step#4

Expected Result:

Infinite loading should not appear and after clearing cache it should be visible if it contain any error.

Actual Result:

Infinite loading appears and after clearing cache, invoice disappear.

Workaround:

Unknown

Platforms:

  • Android: App
  • Android: mWeb Chrome
  • iOS: App
  • iOS: mWeb Safari
  • iOS: mWeb Chrome
  • Windows: Chrome
  • MacOS: Chrome Safari

Screenshots/Videos

Bug7216080_1784866611395.Recording__297.mp4

View all open jobs on GitHub

Applause Internal Information
Exported by: Julia Ponikarchuk
Bug ID: 7216080

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

Activity

  1. applause-bot commented on Jul 24, 2026

    @applause-bot
    Author

    While Applause doesn't embed attachments for this bug, here are the links for quick view:
    https://platform.applause.com/services/links/v1/external/488523f350c59740e88b08be7c4dd97e8060d2630d30231eb6708cf522078816

  2. added
    Daily
    Bug
    on Jul 24, 2026
  3. MelvinBot commented on Jul 24, 2026

    @MelvinBot
    Contributor

    Proposal

    What is the root cause of that problem?

    The offline invoice only ever exists as optimistic Onyx data, and when the queued request fails on going online, the app has no path to surface or dismiss that failure — so the report gets stuck loading and vanishes on cache clear.

    Walking the flow:

    1. Offline: sendInvoice() builds an optimistic invoice report, transaction and report actions, then queues the SEND_INVOICE write. The optimistic report is tagged with pendingFields.createChat and carries a non-zero total (SendInvoice.ts:153-171, ReportUtils.ts:6905-6926).

    2. Online: the queued request is rejected by the backend (recipient is not a WS member and/or the company website is invalid). The failureData only annotates the optimistic report/transaction/actions with errors / errorFields.createChat — it never deletes them (SendInvoice.ts:419-478). The report was never persisted server-side, so it's now a phantom that only lives locally.

    3. Infinite loading: opening the invoice renders the report-actions skeleton via shouldWaitForTransactions(). For an online invoice report with an empty transaction list it stays "loading" because report.total !== 0, and its only escape hatch checks pendingFields.createReport === ADD — but invoices use createChat, so the escape never fires (MoneyRequestReportUtils.ts:145-164, gated at ReportActions.tsx:56-80).

    4. No way out: the ReportScreen error/dismiss banner only reads errorFields.createReport, but the invoice's error is on errorFields.createChat, so no red-brick-road banner appears and removeFailedReport is never reachable (ReportScreen.tsx:94-106).

    5. Disappears after cache clear: the invoice is purely optimistic Onyx state, so wiping the cache removes it entirely and nothing server-side backs it up.

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

    Make the failed offline invoice visible and dismissible instead of silently stuck:

    • Surface the errorFields.createChat (and transaction errors) on the report screen so the user sees the "red brick road" error and can dismiss it — i.e. include createChat in the reportPendingAction / reportErrors selectors in ReportScreen.tsx:94-106 (mirroring how createReport is handled), so dismissing it calls removeFailedReport.
    • Fix the skeleton escape hatch in shouldWaitForTransactions() so an invoice report with a pending/errored createChat (or one carrying errors) does not render the infinite loading skeleton.

    What alternative solutions did you explore? (Optional)

    Have SEND_INVOICE's failureData clean up the optimistic report/transaction/actions on hard-failure (as removeFailedReport does) so no phantom remains — though keeping the error visible so the user knows the invoice failed is preferable to silently removing it.

    Confidence & open questions

    Confidence: medium. The "disappears after cache clear" and "no dismiss path" mechanisms are well supported by the code above. The exact infinite-loading branch has one caveat worth verifying at runtime: a focused trace suggested the optimistic transaction may persist attached to the invoice report after failure (making transactions.length === 1), which would bypass the skeleton. Confirming with logs whether the transaction/report-actions are actually empty at skeleton time — and the exact backend rejection jsonCode for a non-WS-member recipient / invalid website — would pin this down. The backend rejection reason itself lives in a backend repo, but the user-facing bug (stuck + no error surfaced) is an App-side handling gap and is fixable in App.

    Possibly related


    Next Steps for Contributor+ team:
    To accept: @MelvinBot implement [this](https://github.com/Expensify/App/issues/96925) to create a draft PR.
    To refine: @MelvinBot <your feedback>
    To reject: Explain why you are rejecting Melvin's proposal.

  4. added
    External
    on Jul 24, 2026
  5. added
    Help Wanted
    on Jul 24, 2026
  6. ahmdshrif commented on Jul 24, 2026

    @ahmdshrif
    Contributor

    🚨 Edited by proposal-police: This proposal was edited at 2026-07-24 06:03:39 UTC.

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    An invoice created offline shows an infinite loading skeleton when the user goes online and opens it, instead of rendering the (failed) invoice with its error state. After clearing cache the invoice vanishes, because the server never actually created it.

    What is the root cause of that problem?

    SendInvoice is the only money-request creation flow whose Onyx data never settles the "optimistic / never-loaded" bookkeeping, so an offline-created invoice gets permanently stuck in a loading state that only resolves offline — the exact state this repro views online.

    1. buildOnyxDataForInvoice marks all three optimistic reports (invoice room, invoice report, transaction thread) with reportMetadata.isOptimisticReport: true:
      {
      onyxMethod: Onyx.METHOD.MERGE,
      key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${iou.report?.reportID}`,
      value: {
      isOptimisticReport: true,
      },
      },
      (thread:
      {
      onyxMethod: Onyx.METHOD.MERGE,
      key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${transactionParams.threadReport?.reportID}`,
      value: {
      isOptimisticReport: true,
      },
      },
      , room:
      if (chat.isNewReport) {
      optimisticData.push({
      onyxMethod: Onyx.METHOD.MERGE,
      key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${chat.report?.reportID}`,
      value: {
      isOptimisticReport: true,
      },
      });
      }
      ). It resets them only in successData (
      {
      onyxMethod: Onyx.METHOD.MERGE,
      key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${iou.report?.reportID}`,
      value: {
      isOptimisticReport: false,
      },
      },
      ); the entire failureData block contains no metadata or loading-state reset (
      const failureData: Array<
      OnyxUpdate<typeof ONYXKEYS.COLLECTION.REPORT | typeof ONYXKEYS.COLLECTION.TRANSACTION | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS | typeof ONYXKEYS.COLLECTION.POLICY>
      > = [
      {
      onyxMethod: Onyx.METHOD.MERGE,
      key: `${ONYXKEYS.COLLECTION.REPORT}${chat.report?.reportID}`,
      value: {
      iouReportID: chat.report?.iouReportID,
      lastReadTime: chat.report?.lastReadTime,
      pendingFields: null,
      hasOutstandingChildRequest: chat.report?.hasOutstandingChildRequest,
      ...(chat.isNewReport
      ? {
      errorFields: {
      createChat: getMicroSecondOnyxErrorWithTranslationKey('report.genericCreateReportFailureMessage'),
      },
      }
      : {}),
      },
      },
      {
      onyxMethod: Onyx.METHOD.MERGE,
      key: `${ONYXKEYS.COLLECTION.REPORT}${iou.report?.reportID}`,
      value: {
      pendingFields: null,
      errorFields: {
      createChat: getMicroSecondOnyxErrorWithTranslationKey('report.genericCreateReportFailureMessage'),
      },
      },
      },
      {
      onyxMethod: Onyx.METHOD.MERGE,
      key: `${ONYXKEYS.COLLECTION.REPORT}${transactionParams.threadReport.reportID}`,
      value: {
      errorFields: {
      createChat: getMicroSecondOnyxErrorWithTranslationKey('report.genericCreateReportFailureMessage'),
      },
      },
      },
      {
      onyxMethod: Onyx.METHOD.MERGE,
      key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionParams.transaction.transactionID}`,
      value: {
      errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericCreateInvoiceFailureMessage'),
      pendingFields: clearedPendingFields,
      },
      },
      {
      onyxMethod: Onyx.METHOD.MERGE,
      key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${iou.report?.reportID}`,
      value: {
      [iou.createdAction.reportActionID]: {
      errors: getReceiptError(transactionParams.transaction.receipt, transactionParams.transaction.receipt?.filename, false, errorKey),
      },
      [iou.action.reportActionID]: {
      errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericCreateInvoiceFailureMessage'),
      },
      },
      },
      ];
      if (transactionParams.threadCreatedReportAction?.reportActionID) {
      failureData.push({
      onyxMethod: Onyx.METHOD.MERGE,
      key: `${ONYXKEYS.COLLECTION.REPORT_ACTIONS}${transactionParams.threadReport.reportID}`,
      value: {
      [transactionParams.threadCreatedReportAction.reportActionID]: {
      errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericCreateInvoiceFailureMessage', errorKey),
      },
      },
      });
      }
      if (companyName && companyWebsite) {
      optimisticData.push({
      onyxMethod: Onyx.METHOD.MERGE,
      key: `${ONYXKEYS.COLLECTION.POLICY}${policyParams.policy?.id}`,
      value: {
      invoice: {
      companyName,
      companyWebsite,
      pendingFields: {
      companyName: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE,
      companyWebsite: CONST.RED_BRICK_ROAD_PENDING_ACTION.UPDATE,
      },
      },
      },
      });
      successData.push({
      onyxMethod: Onyx.METHOD.MERGE,
      key: `${ONYXKEYS.COLLECTION.POLICY}${policyParams.policy?.id}`,
      value: {
      invoice: {
      pendingFields: {
      companyName: null,
      companyWebsite: null,
      },
      },
      },
      });
      failureData.push({
      onyxMethod: Onyx.METHOD.MERGE,
      key: `${ONYXKEYS.COLLECTION.POLICY}${policyParams.policy?.id}`,
      value: {
      invoice: {
      companyName: null,
      companyWebsite: null,
      pendingFields: {
      companyName: null,
      companyWebsite: null,
      },
      },
      },
      });
      }
      ). When the queued SendInvoice is rejected on reconnect (here: the invalid company website), the reports stay flagged optimistic forever.
    2. The sibling expense flow stamps its optimistic report as already loaded — hasOnceLoadedReportActions: true in RAM_ONLY_REPORT_LOADING_STATE:
      onyxData.optimisticData?.push({
      onyxMethod: Onyx.METHOD.MERGE,
      key: `${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${iou.report?.reportID}`,
      value: {
      hasOnceLoadedReportActions: true,
      },
      });
      . SendInvoice.ts has zero writes to that key, so every invoice report starts (and stays) at the default isLoadingInitialReportActions: true / hasOnceLoadedReportActions: false (
      const defaultReportLoadingState = {
      hasOnceLoadedReportActions: false,
      isLoadingInitialReportActions: true,
      isLoadingOlderReportActions: false,
      hasLoadingOlderReportActionsError: false,
      isLoadingNewerReportActions: false,
      hasLoadingNewerReportActionsError: false,
      };
      ).
    3. That flag can only be cleared by a finished OpenReport call — but for the optimistic invoice room, fetchReport deliberately never dispatches one:
      const fetchReport = useEffectEvent(() => {
      if (reportMetadata.isOptimisticReport && report?.type === CONST.REPORT.TYPE.CHAT && !isPolicyExpenseChat(report)) {
      return;
      }
      — and this effect keeps re-arming the flag to true while hasOnceLoadedReportActions is false:
      useEffect(() => {
      if (reportLoadingState.hasOnceLoadedReportActions) {
      return;
      }
      updateLoadingInitialReportAction(reportIDFromRoute, true);
      }, [reportIDFromRoute, reportLoadingState.hasOnceLoadedReportActions]);
      . Where OpenReport does fire (the invoice report itself), it 404s (the server rejected the create) and its failureData clears only isLoadingInitialReportActions, never hasOnceLoadedReportActions:
      {
      onyxMethod: Onyx.METHOD.MERGE,
      key: `${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${reportID}`,
      value: {
      isLoadingInitialReportActions: false,
      },
      .
    4. Every loading gate on the online path keys on exactly these stuck flags: shouldWaitForTransactions/hasLoadedReportActions (
      function shouldWaitForTransactions(report: OnyxEntry<Report>, transactions: Transaction[] | undefined, reportLoadingState: OnyxEntry<ReportLoadingState>, isOffline = false) {
      if (isOffline) {
      return false;
      }
      const isTransactionDataReady = transactions !== undefined;
      const isTransactionThreadView = isReportTransactionThread(report);
      // Scope the dismiss-write check to *this* report so an unrelated submit flow that's
      // mid-dismiss doesn't make every empty money-request/invoice report look like it's loading.
      const hasPendingDismissWrite = hasDeferredWriteForReport(CONST.DEFERRED_LAYOUT_WRITE_KEYS.DISMISS_MODAL, report?.reportID);
      const isStillLoadingData =
      transactions?.length === 0 &&
      ((!!reportLoadingState?.isLoadingInitialReportActions && !reportLoadingState.hasOnceLoadedReportActions) || report?.total !== 0 || hasPendingDismissWrite);
      return (
      (isMoneyRequestReport(report) || isInvoiceReport(report)) &&
      (!isTransactionDataReady || isStillLoadingData) &&
      !isTransactionThreadView &&
      report?.pendingFields?.createReport !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD
      );
      ,
      function hasLoadedReportActions(reportLoadingState: OnyxInputOrEntry<ReportLoadingState>, isOffline = false): boolean {
      if (!reportLoadingState) {
      return false;
      }
      return reportLoadingState?.hasOnceLoadedReportActions === true || reportLoadingState?.isLoadingInitialReportActions === false || isOffline;
      }
      ), the report-view skeleton (
      const shouldShowOpenReportLoadingSkeleton = !!(isLoadingInitialReportActions && reportActions.length === 0 && !isOffline) || shouldWaitForTransactions;
      ), and the chat skeleton gates (
      const isInitiallyLoadingReport = isReportUnread && !!isLoadingInitialReportActions && reportActionsLength <= 1;
      // Same for unread messages, we need to wait for the results from the OpenReport API call
      // if the oldest unread report action is not available yet. Only applies during the *first* load
      // for this report: after `hasOnceLoadedReportActions` is set, a later "mark as unread" must not
      // bring back this loading gate (we are not re-opening the report from a cold cache).
      const isUnreadMessagePageLoadingInitially = !shouldBeAlignedToTop && !reportActionIDFromRoute && isReportUnread && !oldestUnreadReportAction && !hasOnceLoadedReportActions;
      // Once all the above conditions are met, we can consider the report ready.
      const isReportLoading = isInitiallyLoadingReport || isUnreadMessagePageLoadingInitially;
      const isReportReady = isOffline || !isReportLoading;
      const isMissingTransactionThreadReportID = !transactionThreadReport?.reportID;
      const isReportDataIncomplete = isSingleExpenseReport && isMissingTransactionThreadReportID;
      const shouldShowSkeletonForInitialLoad = !!isLoadingInitialReportActions && (isReportDataIncomplete || isMissingReportActions) && !isOffline;
      const shouldShowSkeletonForAppLoad = !!isLoadingApp && !isOffline;
      // Show skeleton for the Concierge chat (side panel or main DM) until report
      // data has been loaded at least once. Before the first openReport response,
      // hasOlderActions is unreliable, so we can't determine whether to show the
      // greeting or onboarding messages. The skeleton avoids flashing wrong content.
      // hasOnceLoadedReportActions is RAM-only and resets on a page refresh, but
      // cached report actions persist in Onyx. For the main DM, render those cached
      // actions immediately (matching production) instead of flashing a skeleton on
      // every refresh; the side panel always opens fresh so it keeps gating on
      // hasOnceLoadedReportActions only. hasCachedReportActions is false only on a
      // genuinely cold load with no cached history (it excludes the synthetic CREATED
      // action that is always injected for Concierge).
      const shouldShowSkeletonForConciergePanel = isConciergeHiddenHistory && !hasOnceLoadedReportActions && !(isConciergeMainDM && hasCachedReportActions) && !isOffline;
      // When opening a linked message online, wait for the first load before rendering the list: the batch of
      // actions that arrives right after the initial load shifts the list and breaks the anchor to the linked action.
      const shouldShowSkeletonForLinkedMessageLoad = !!reportActionIDFromRoute && !isOffline && !hasOnceLoadedReportActions && !!isLoadingInitialReportActions;
      const shouldShowInitialSkeleton = shouldShowSkeletonForConciergePanel || shouldShowSkeletonForInitialLoad || shouldShowSkeletonForAppLoad || shouldShowSkeletonForLinkedMessageLoad;
      const hasDerivedValueTimingIssue = reportActionsLength > 0 && isMissingReportActions;
      const shouldShowLoadingSkeleton = isLoadingOnyxValue(reportResult) || !report || !isReportReady || shouldShowInitialSkeleton;
      ). This is the same regression family as #96925's sibling #90293 ("Invoice report loads infinitely when sent offline"): its fix #90323 added !isOffline escapes to these gates, which cures the offline view but by design does nothing once the user is back online — this issue's exact repro.

    This explains every symptom: only invoices (expenses get the sibling stamp), only after offline creation (online success clears the flags via successData), infinite loading rather than an error (the gates never resolve, so the already-written errorFields.createChat is never rendered), and disappearance after cache clear (the report exists only in local optimistic data).

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

    Bring buildOnyxDataForInvoice to parity with the expense flow: in its optimisticData, stamp the loading state for the three reports it creates, mirroring MoneyRequestBuilder.ts#L668-L674:

    for (const id of [iou.report?.reportID, transactionParams.threadReport.reportID, chat.isNewReport ? chat.report?.reportID : undefined]) {
        if (!id) continue;
        optimisticData.push({
            onyxMethod: Onyx.METHOD.MERGE,
            key: `${ONYXKEYS.COLLECTION.RAM_ONLY_REPORT_LOADING_STATE}${id}`,
            value: {hasOnceLoadedReportActions: true, isLoadingInitialReportActions: false},
        });
    }

    The optimistic data written by SendInvoice is already the complete local truth for these reports, so "loaded" is correct from the moment of creation — exactly the invariant expenses already rely on. Every gate above then resolves, and after the rejected SendInvoice the room renders with its errorFields.createChat RBR error, matching the expected result. Regression safety: this key is RAM-only and per-reportID, the stamp matches the long-shipped expense behavior, and success/failure flows for existing invoice rooms are untouched.

    Why the obvious spot-fix fails: relaxing the fetchReport skip-gate (ReportFetchHandler.tsx#L156-L159) to force an OpenReport doesn't work — while the create is still queued, OpenReport on an optimistic ID 404s and merges errorFields.notFound into a perfectly healthy pending room (the gate exists precisely to prevent that), and even after it fires, its failureData still never sets hasOnceLoadedReportActions (Report/index.ts#L1627-L1632), so shouldWaitForTransactions-class gates keep waiting on a fetch that can never succeed for a report the server refused to create. The stamp removes the dependency on any network call instead of adding one that must fail.

    Secondary (optional): mirror the three successData isOptimisticReport: false resets into failureData so a room whose create was rejected stops being treated as "creation still pending" by ReportFetchHandler and becomes re-fetchable/dismissable consistently.

    What alternative solutions did you explore? (Optional)

    1. Add more !isOffline/error escapes to the individual skeleton gates (the #90323 approach again) — incomplete: there are at least four independent gate sites across chat view, report view, and thread navigation; patching them one by one leaves the underlying "never loaded" state to resurface in the next consumer.
    2. Clear isLoadingInitialReportActions in SendInvoice failureData only — fixes the post-failure view but not the window while the request is in flight online, and leaves hasOnceLoadedReportActions false, so hasLoadedReportActions-based gates (thread deletion checks, legacy-thread creation) still misbehave.
    3. Backend accepts/creates the invoice and reports the website error afterwards — out of scope for this repo; the App must handle a rejected queued create gracefully regardless.
  7. mukhrr commented on Jul 24, 2026

    @mukhrr
    Contributor

    Proposal

    What is the root cause of that problem?

    I found that the failed invoice remains an optimistic report with a non-zero total. buildOptimisticInvoiceReport() assigns that total before the offline request is sent:

    App/src/libs/ReportUtils.ts

    Lines 6894 to 6918 in 2b3f4c0

    /** Builds an optimistic invoice report with a randomly generated reportID */
    function buildOptimisticInvoiceReport(
    chatReportID: string,
    policyID: string | undefined,
    receiverAccountID: number,
    receiverName: string,
    total: number,
    currency: string,
    ): OptimisticExpenseReport {
    const formattedTotal = convertToDisplayString(total, currency);
    const created = DateUtils.getDBTime();
    const invoiceReport = {
    reportID: generateReportID(),
    chatReportID,
    policyID,
    type: CONST.REPORT.TYPE.INVOICE,
    ownerAccountID: deprecatedCurrentUserAccountID,
    managerID: receiverAccountID,
    currency,
    // We don't translate reportName because the server response is always in English
    reportName: `${receiverName} owes ${formattedTotal}`,
    stateNum: CONST.REPORT.STATE_NUM.SUBMITTED,
    statusNum: CONST.REPORT.STATUS_NUM.SUBMITTED,
    total: total * -1,
    participants: {

    When the deferred SendInvoice request fails validation, its failure data clears the pending state and adds a createChat error to the invoice report:

    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.REPORT}${iou.report?.reportID}`,
    value: {
    pendingFields: null,
    errorFields: {
    createChat: getMicroSecondOnyxErrorWithTranslationKey('report.genericCreateReportFailureMessage'),
    },
    },
    },
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.REPORT}${transactionParams.threadReport.reportID}`,
    value: {
    errorFields: {
    createChat: getMicroSecondOnyxErrorWithTranslationKey('report.genericCreateReportFailureMessage'),
    },
    },
    },
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionParams.transaction.transactionID}`,
    value: {
    errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericCreateInvoiceFailureMessage'),
    pendingFields: clearedPendingFields,
    },
    },

    However, shouldWaitForTransactions() treats every online invoice with no transactions and a non-zero report total as still loading. It does not account for the terminal errorFields.createChat state:

    function shouldWaitForTransactions(report: OnyxEntry<Report>, transactions: Transaction[] | undefined, reportLoadingState: OnyxEntry<ReportLoadingState>, isOffline = false) {
    if (isOffline) {
    return false;
    }
    const isTransactionDataReady = transactions !== undefined;
    const isTransactionThreadView = isReportTransactionThread(report);
    // Scope the dismiss-write check to *this* report so an unrelated submit flow that's
    // mid-dismiss doesn't make every empty money-request/invoice report look like it's loading.
    const hasPendingDismissWrite = hasDeferredWriteForReport(CONST.DEFERRED_LAYOUT_WRITE_KEYS.DISMISS_MODAL, report?.reportID);
    const isStillLoadingData =
    transactions?.length === 0 &&
    ((!!reportLoadingState?.isLoadingInitialReportActions && !reportLoadingState.hasOnceLoadedReportActions) || report?.total !== 0 || hasPendingDismissWrite);
    return (
    (isMoneyRequestReport(report) || isInvoiceReport(report)) &&
    (!isTransactionDataReady || isStillLoadingData) &&
    !isTransactionThreadView &&
    report?.pendingFields?.createReport !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD
    );

    Consequently, MoneyRequestReportView returns the loading skeleton before reaching the OfflineWithFeedback component that would display the creation error:

    // Prevent the empty state flash by ensuring transaction data is fully loaded before deciding which view to render
    // We need to wait for both the selector to finish AND ensure we're not in a loading state where transactions could still populate
    const shouldWaitForTransactions = shouldWaitForTransactionsUtil(report, transactions, reportLoadingState, isOffline);
    const shouldShowOpenReportLoadingSkeleton = !!(isLoadingInitialReportActions && reportActions.length === 0 && !isOffline) || shouldWaitForTransactions;
    const isEmptyTransactionReport = visibleTransactions?.length === 0 && transactionThreadReportID === undefined;
    const shouldDisplayMoneyRequestActionsList = !!isEmptyTransactionReport || shouldDisplayReportTableView(report, visibleTransactions ?? []);

    useMarkOpenReportEndOnSkeleton(report, shouldShowOpenReportLoadingSkeleton);
    if (shouldShowOpenReportLoadingSkeleton) {
    const skeletonReasonAttributes: SkeletonSpanReasonAttributes = {
    context: 'MoneyRequestReportView.InitialLoadingSkeleton',
    isLoadingInitialReportActions: !!isLoadingInitialReportActions,
    shouldWaitForTransactions,
    };
    return (
    <InitialLoadingSkeleton
    styles={styles}

    return (
    <View style={styles.flex1}>
    <OfflineWithFeedback
    pendingAction={reportPendingAction ?? report?.pendingFields?.reimbursed}
    errors={reportErrors}
    needsOffscreenAlphaCompositing
    shouldShowErrorMessages={false}
    >
    <CollapsibleHeaderOnKeyboard>{reportHeaderView}</CollapsibleHeaderOnKeyboard>
    </OfflineWithFeedback>
    <OfflineWithFeedback
    pendingAction={reportPendingAction}
    errors={reportErrors}
    onClose={dismissReportCreationError}
    needsOffscreenAlphaCompositing
    style={styles.flex1}
    contentContainerStyle={styles.flex1}
    errorRowStyles={[styles.ph5, styles.mv2]}

    The history shows that the non-zero-total check was introduced to avoid briefly rendering an empty report while transactions are loading, but no terminal-error exception was added:

    }
    const isTransactionDataReady = transactions !== undefined;
    const isTransactionThreadView = isReportTransactionThread(report);
    const hasPendingDismissWrite = hasDeferredWrite(CONST.DEFERRED_LAYOUT_WRITE_KEYS.DISMISS_MODAL);
    const isStillLoadingData =
    transactions?.length === 0 &&
    ((!!reportLoadingState?.isLoadingInitialReportActions && !reportLoadingState.hasOnceLoadedReportActions) || report?.total !== 0 || hasPendingDismissWrite);
    return (
    (isMoneyRequestReport(report) || isInvoiceReport(report)) &&
    (!isTransactionDataReady || isStillLoadingData) &&
    !isTransactionThreadView &&
    report?.pendingFields?.createReport !== CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD
    );

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

    I think we should update shouldWaitForTransactions() to stop waiting when the report has a createChat error:

     return (
         (isMoneyRequestReport(report) || isInvoiceReport(report)) &&
         (!isTransactionDataReady || isStillLoadingData) &&
    +    !report?.errorFields?.createChat &&
         !isTransactionThreadView &&

    This allows MoneyRequestReportView to render its existing OfflineWithFeedback error row instead of an endless skeleton, so the user can see and dismiss the failed invoice.

    Successful reports are unaffected because they do not have errorFields.createChat; the existing loading protection for non-zero reports and deferred writes remains intact. The same guard also correctly handles failed optimistic expense reports that use the same creation-error field.

    I would add unit coverage for shouldWaitForTransactions() confirming that:

    • A non-zero invoice with no transactions still waits while loading normally.
    • The same invoice stops waiting after errorFields.createChat is set.
    • Existing offline, transaction-thread, and successful-report behavior remains unchanged.

    What alternative solutions did you explore? (Optional)

    I considered resetting the optimistic report’s total on failure. That would happen to bypass the loading condition, but it would mutate valid invoice data merely to control rendering and couple the failure handler to this UI heuristic. Checking the existing terminal creation-error state directly in shouldWaitForTransactions() is smaller and preserves the failed invoice’s details.

  8. melvin-bot commented on Jul 24, 2026

    @melvin-bot

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

  9. wildan-m commented on Jul 24, 2026

    @wildan-m
    Contributor

    Proposal

    Please re-state the problem that we are trying to solve in this issue.

    An invoice created while offline never finishes loading once the user comes back online and opens it. The invoice chat shows an endless loading skeleton instead of either the invoice content or the error that caused the creation to fail, and clearing the cache makes the invoice vanish entirely.

    What is the root cause of that problem?

    Creating an invoice offline builds three optimistic reports (the invoice room, the invoice report and the transaction thread) and flags each of them in Onyx with REPORT_METADATA.isOptimisticReport = true. For the invoice room this happens only when the room is new, which is exactly the reported scenario (the receiver is not a member of the workspace, so a brand new invoice room is created):

    // Use SET for new reports because it doesn't exist yet, is faster and we need the data to be available when we navigate to the chat page
    onyxMethod: chat.isNewReport ? Onyx.METHOD.SET : Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.REPORT}${chat.report.reportID}`,
    value: {
    ...chat.report,
    lastReadTime: DateUtils.getDBTime(),
    iouReportID: iou.report?.reportID,
    ...(chat.isNewReport ? {pendingFields: {createChat: CONST.RED_BRICK_ROAD_PENDING_ACTION.ADD}} : {}),
    },
    });
    if (chat.isNewReport) {
    optimisticData.push({
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${chat.report?.reportID}`,
    value: {
    isOptimisticReport: true,
    },
    });
    }

    For the invoice room that flag is cleared only when the queued SendInvoice request comes back successfully:

    if (chat.isNewReport) {
    successData.push(
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.REPORT}${chat.report?.reportID}`,
    value: {
    participants: redundantParticipants,
    pendingFields: null,
    errorFields: null,
    },
    },
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.REPORT_METADATA}${chat.report?.reportID}`,
    value: {
    isOptimisticReport: false,
    },
    },
    );
    }

    In the repro the request deliberately fails on reconnect (the invalid company website is rejected), so failureData runs instead. It records the error on the reports and on the transaction, but it never clears isOptimisticReport, so the invoice room stays flagged as optimistic forever:

    const failureData: Array<
    OnyxUpdate<typeof ONYXKEYS.COLLECTION.REPORT | typeof ONYXKEYS.COLLECTION.TRANSACTION | typeof ONYXKEYS.COLLECTION.REPORT_ACTIONS | typeof ONYXKEYS.COLLECTION.POLICY>
    > = [
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.REPORT}${chat.report?.reportID}`,
    value: {
    iouReportID: chat.report?.iouReportID,
    lastReadTime: chat.report?.lastReadTime,
    pendingFields: null,
    hasOutstandingChildRequest: chat.report?.hasOutstandingChildRequest,
    ...(chat.isNewReport
    ? {
    errorFields: {
    createChat: getMicroSecondOnyxErrorWithTranslationKey('report.genericCreateReportFailureMessage'),
    },
    }
    : {}),
    },
    },
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.REPORT}${iou.report?.reportID}`,
    value: {
    pendingFields: null,
    errorFields: {
    createChat: getMicroSecondOnyxErrorWithTranslationKey('report.genericCreateReportFailureMessage'),
    },
    },
    },
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.REPORT}${transactionParams.threadReport.reportID}`,
    value: {
    errorFields: {
    createChat: getMicroSecondOnyxErrorWithTranslationKey('report.genericCreateReportFailureMessage'),
    },
    },
    },
    {
    onyxMethod: Onyx.METHOD.MERGE,
    key: `${ONYXKEYS.COLLECTION.TRANSACTION}${transactionParams.transaction.transactionID}`,
    value: {
    errors: getMicroSecondOnyxErrorWithTranslationKey('iou.error.genericCreateInvoiceFailureMessage'),
    pendingFields: clearedPendingFields,
    },
    },
    {

    The invoice room is a report of type CHAT that is not a policy expense chat, so when the user opens it, fetchReport in ReportFetchHandler takes its early return and never calls openReport:

    const fetchReport = useEffectEvent(() => {
    if (reportMetadata.isOptimisticReport && report?.type === CONST.REPORT.TYPE.CHAT && !isPolicyExpenseChat(report)) {
    return;
    }

    The problem is that this bail-out path leaves the report permanently marked as loading. The effect just above it unconditionally sets isLoadingInitialReportActions back to true for any report that has not yet successfully loaded its actions:

    useEffect(() => {
    if (reportLoadingState.hasOnceLoadedReportActions) {
    return;
    }
    updateLoadingInitialReportAction(reportIDFromRoute, true);
    }, [reportIDFromRoute, reportLoadingState.hasOnceLoadedReportActions]);

    Nothing will ever flip that flag back to false for this report. The success and failure handlers of openReport do, but openReport is precisely what we just decided to skip. The only other writers that clear it are the handlers of createGroupChat, which never run for an invoice room, and a hook that clears it when deep-linking to a message while offline, which requires a linked report action ID in the route. So isLoadingInitialReportActions stays true with hasOnceLoadedReportActions stuck at false, which keeps the report-actions skeleton on screen and also keeps ReportNotFoundGuard in its "still loading" branch, so the screen can never settle on content or on an error either:

    const isLoading = isLoadingApp !== false || isLoadingReportData || (!isOffline && !!isLoadingInitialReportActions);

    While the user is offline the loading flag is ignored by these gates, which is why the invoice looks fine offline and only hangs after going back online. And because the whole thing only ever existed in local Onyx data, clearing the cache removes it — hence the disappearing invoice.

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

    In fetchReport in src/pages/inbox/ReportFetchHandler.tsx, when we take the early return for an optimistic chat report, we should also mark the initial report-actions load as finished for that report before returning, by calling the existing updateLoadingInitialReportAction helper with false for the report ID from the route.

    The reasoning is that this branch is a deliberate decision that there is nothing to fetch from the server for this report — its content is purely local. Leaving the loading flag asserted claims a fetch is in flight when none will ever happen, which is what produces the infinite skeleton. Resolving the flag on the same path where we decide not to fetch keeps the loading state honest. There is already precedent for exactly this in the codebase: the deep-link-while-offline hook clears the same flag on another path where the initial actions are known to be available locally and no fetch is going to resolve it:

    useEffect(() => {
    // When we linked to message - we do not need to wait for initial actions - they already exists
    if (!reportActionIDFromRoute || !isOffline) {
    return;
    }
    updateLoadingInitialReportAction(reportID);
    }, [isOffline, reportID, reportActionIDFromRoute]);

    With that change the invoice room renders its locally available content, and the red brick road error that SendInvoice's failure handling already writes onto the report and the transaction becomes visible, which matches the expected result in the issue: no infinite loading, and the error is surfaced instead.

    This is scoped to the branch we already short-circuit, so reports that genuinely have a pending server fetch are unaffected, and the fix is not invoice specific — any chat report that is still flagged optimistic and therefore never fetched gets the same correct behaviour.

    Compare branch: https://github.com/Expensify/App/compare/main...wildan-m:App:wildan/96925-optimistic-chat-loading-flag?expand=1

    What alternative solutions did you explore? (Optional)

    I also looked at clearing isOptimisticReport inside SendInvoice's failureData, mirroring what successData does for the three reports. I decided against it because clearing the flag would let openReport run against a report that was never created on the server, which returns not found and would replace the invoice with a "not here" page rather than showing the creation error the issue asks for. It would also be inconsistent with the rest of the codebase, where isOptimisticReport is only ever reset in success handlers.

    I also considered changing the effect that re-asserts isLoadingInitialReportActions so it skips reports that will never be fetched, but that would mean duplicating the optimistic-report condition in a second place and would risk regressing the stale-flag fix that effect was added for.

  10. changed the title [-]Invoice - Infinite loading when creating invoice offline then viewing it online[/-] [+][$250] Invoice - Infinite loading when creating invoice offline then viewing it online[/+] on Jul 24, 2026
  11. melvin-bot commented on Jul 24, 2026

    @melvin-bot
  12. godzillaxbox19982014-lgtm commented on Jul 24, 2026

    @godzillaxbox19982014-lgtm

    🚫 Duplicated proposal withdrawn by 🤖 ProposalPolice.

  13. 49 remaining items

  14. daledah commented on Jul 31, 2026

    @daledah
    Contributor

    BugZero Checklist:

    • [Contributor] The offending PR and associated issue have been commented on, pointing out the bug it caused and why, so the author and reviewers can learn from the mistake.

      Link to the comment on the PR: N/A

    • [Contributor] If the regression was CRITICAL (e.g. interrupts a core flow) A discussion in #expensify-open-source has been started about whether any other steps should be taken (e.g. updating the PR review checklist) in order to catch this type of bug sooner.

      Link to discussion:

    • [Contributor] If it was decided to create a regression test for the bug, please propose the regression test steps using the template below to ensure the same bug will not reach production again.

    • [BugZero Assignee] Create a GH issue for creating/updating the regression test once above steps have been agreed upon.

      Link to issue: https://github.com/Expensify/Expensify/issues/669708

    Regression Test Proposal

    Test:

    1. Go offline.
    2. Click FAB > Invoice.
    3. Create an invoice with a valid user who is not a member of the workspace, and enter an invalid website address in the company address (e.g. www.none.com).
    4. Go online.
    5. Open the invoice created in step 3.
    6. Verify no infinite loading skeleton appears — the invoice renders and its red-brick-road creation error is visible.
    7. Verify the created invoice is dismissable (dismiss-and-delete of the failed local invoice still works).

    Do we agree 👍 or 👎

    Zapier Logs Run ID: 00040eee-dd4c-a098-a5aa-25ec4eb16074
  15. added
    Daily
    Awaiting Payment
    and removed
    Weekly
    on Aug 6, 2026
  16. melvin-bot commented on Aug 6, 2026

    @melvin-bot

    Triggered auto assignment to @mallenexpensify (Awaiting Payment)

  17. melvin-bot commented on Aug 6, 2026

    @melvin-bot

    Payment Summary

    Resolving PRs:

    Upwork Job

    • Reviewer: @daledah owed $250 via NewDot
    • ROLE: @dilshodmackbook-sketch paid $(AMOUNT) via Upwork (LINK)

    BugZero Checklist (@mallenexpensify)

    • I have confirmed assignees, roles, and Upwork contracts look correct
    • I have paid out Upwork contracts / manual NewDot requests
  18. mallenexpensify commented on Aug 8, 2026

    @mallenexpensify
    Contributor

    Payment Summary

    Contributor: @dilshodmackbook-sketch paid $250 via Upwork
    Contributor+: @daledah due $250 via NewDot

    @dilshodmackbook-sketch can you please accept the job below? Please reply here and tag me once you have.
    https://www.upwork.com/jobs/~022080532865576867228

  19. David-2002065 commented on Aug 8, 2026

    @David-2002065
    Contributor

    @mallenexpensify accepted thanks.

  20. mallenexpensify commented on Aug 11, 2026

    @mallenexpensify
    Contributor

    @dilshodmackbook-sketch paid, summary updated above. Thx.

  21. quinthar commented on Sep 26, 2026

    @quinthar
    Contributor

    Approved $250 to @daledah

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Labels

Awaiting PaymentBugDailyExternal

Type

No type

Projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions